Files
waggle-os/packages/server/tests/local/workspaces-lifecycle.test.ts
shumeiko.it e9ed8c0765 refactor(server): read workspace state, briefings and workspaces from the memory contract (P1.5)
- Workspace state, the "Workspace Now" block, the home briefing and the
  proactive handlers read the workspace's memory through server.memory:
  decisions are memories of kind 'decision', critical ones or ones worded
  as decisions; summaries list memories most important first. They no
  longer open workspace .mind files, so the builders are async and
  ProactiveContext carries `memory` instead of `getWorkspaceMindDb`.
- The home briefing counts extracted personal facts that are neither
  confirmed nor archived as awaiting review (memory-status.ts).
- Workspace routes count memories through the contract, seed template
  starter memories with remember() in the background (origin
  'workspace-template'), export memories through list(), and deleting a
  workspace forgets its memory scope and clears its awareness items before
  the directory is removed; the delete is refused if forgetting fails.
  agentState.releaseWorkspace() replaces closeWorkspaceMind for callers.
- The command palette searches personal memory and the active workspace's
  memory (UF-033).
- chat.ts drops the MindDB-flake diagnostics; the mind cache they guarded
  no longer serves chat turns.
2026-10-24 13:19:06 +02:00

239 lines
9.1 KiB
TypeScript

/**
* Workspace lifecycle route tests (UX-Northstar 2026-06-13 G1/G2).
*
* Covers the management surface the UI now exposes (WorkspaceActionsMenu):
* - PATCH/PUT accept `status` (archive/restore/pause) and `description`,
* persist via WorkspaceManager, and reject invalid status values with 400.
* - Rename round-trips.
* - DELETE forgets the workspace's memories and awareness items, releases
* the workspace, then removes the directory.
* - POST with a template seeds its starter memories in the background.
*
* Scaffolding follows home.test.ts: Fastify inject + plain-object decorators,
* but with a REAL WorkspaceManager on a tmp dir so persistence is verified.
* localConfig is intentionally absent → emitAuditEvent stays a safe no-op.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import Fastify, { type FastifyInstance } from 'fastify';
import { AwarenessLayer, WaggleDB, WorkspaceManager, workspaceDataScope } from '@waggle/core';
import {
createInMemoryMemoryStore,
PERSONAL_SCOPE,
workspaceScope,
type MemoryStore,
} from '@waggle/memory-contract';
import { workspaceRoutes, toStateItemViews } from '../../src/local/routes/workspaces.js';
import type { StateItem } from '../../src/local/workspace-state.js';
describe('workspace lifecycle routes', () => {
let tmpDir: string;
let manager: WorkspaceManager;
let server: FastifyInstance;
let releaseWorkspace: ReturnType<typeof vi.fn>;
let memory: MemoryStore;
let waggleDb: WaggleDB;
let wsId: string;
beforeEach(async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'waggle-ws-lifecycle-'));
manager = new WorkspaceManager(tmpDir);
wsId = manager.create({ name: 'Side Project', group: 'Personal' }).id;
releaseWorkspace = vi.fn();
memory = createInMemoryMemoryStore();
waggleDb = new WaggleDB(':memory:');
server = Fastify({ logger: false });
server.decorate('workspaceManager', manager);
server.decorate('memory', memory);
server.decorate('waggleDb', waggleDb);
server.decorate('agentState', {
activateWorkspaceMind: () => undefined,
releaseWorkspace,
});
// localConfig intentionally absent — see file header.
await server.register(workspaceRoutes);
});
afterEach(async () => {
await server.close();
waggleDb.close();
fs.rmSync(tmpDir, { recursive: true, force: true });
});
it('PATCH archives a workspace and persists the status', async () => {
const res = await server.inject({
method: 'PATCH',
url: `/api/workspaces/${wsId}`,
payload: { status: 'archived' },
});
expect(res.statusCode).toBe(200);
expect(res.json().status).toBe('archived');
expect(manager.get(wsId)?.status).toBe('archived');
});
it('PATCH restores an archived workspace to active', async () => {
manager.update(wsId, { status: 'archived' });
const res = await server.inject({
method: 'PATCH',
url: `/api/workspaces/${wsId}`,
payload: { status: 'active' },
});
expect(res.statusCode).toBe(200);
expect(manager.get(wsId)?.status).toBe('active');
});
it('PATCH rejects an invalid status with 400 and persists nothing', async () => {
const res = await server.inject({
method: 'PATCH',
url: `/api/workspaces/${wsId}`,
payload: { status: 'banana' },
});
expect(res.statusCode).toBe(400);
expect(res.json().error).toMatch(/Invalid status/);
expect(manager.get(wsId)?.status).toBeUndefined();
});
it('PUT rejects an invalid status with 400', async () => {
const res = await server.inject({
method: 'PUT',
url: `/api/workspaces/${wsId}`,
payload: { status: 'deleted' },
});
expect(res.statusCode).toBe(400);
});
it('PUT pauses a workspace and accepts a description', async () => {
const res = await server.inject({
method: 'PUT',
url: `/api/workspaces/${wsId}`,
payload: { status: 'paused', description: 'On hold until Q3' },
});
expect(res.statusCode).toBe(200);
const stored = manager.get(wsId);
expect(stored?.status).toBe('paused');
expect(stored?.description).toBe('On hold until Q3');
});
it('PATCH renames a workspace', async () => {
const res = await server.inject({
method: 'PATCH',
url: `/api/workspaces/${wsId}`,
payload: { name: 'Client Alpha' },
});
expect(res.statusCode).toBe(200);
expect(manager.get(wsId)?.name).toBe('Client Alpha');
// Rename must not disturb identity or grouping
expect(manager.get(wsId)?.id).toBe(wsId);
expect(manager.get(wsId)?.group).toBe('Personal');
});
it('PATCH normalizes the legacy persona alias and accepts safe type metadata', async () => {
const res = await server.inject({
method: 'PATCH',
url: `/api/workspaces/${wsId}`,
payload: { persona: 'coder', type: 'project' },
});
expect(res.statusCode).toBe(200);
const stored = manager.get(wsId);
expect(stored?.personaId).toBe('coder');
expect(stored?.type).toBe('project');
expect(stored).not.toHaveProperty('persona');
});
it.each([
['storageType', 'local'],
['storagePath', 'C:\\outside'],
['storageConfig', { bucket: 'outside' }],
['directory', 'C:\\outside'],
] as const)('PUT and PATCH reject immutable %s updates', async (field, value) => {
const before = manager.get(wsId);
for (const method of ['PUT', 'PATCH'] as const) {
const res = await server.inject({
method,
url: `/api/workspaces/${wsId}`,
payload: { [field]: value },
});
expect(res.statusCode).toBe(400);
expect(manager.get(wsId)).toEqual(before);
}
});
it('PATCH on an unknown workspace returns 404', async () => {
const res = await server.inject({
method: 'PATCH',
url: '/api/workspaces/nope',
payload: { status: 'archived' },
});
expect(res.statusCode).toBe(404);
});
it('toStateItemViews produces unique ids when items share a sourceId', () => {
// Multiple completed items from one session all carry the same sourceId —
// the FE uses these ids as React keys, so collisions are a rendering bug
// (live-observed as `completed:default-workspace` duplicate-key errors).
const items: StateItem[] = [
{ content: 'a', sourceId: 'default-workspace' },
{ content: 'b', sourceId: 'default-workspace' },
{ content: 'c' },
] as StateItem[];
const ids = toStateItemViews(items, 'completed').map(v => v.id);
expect(new Set(ids).size).toBe(ids.length);
});
it('DELETE forgets the workspace memory, releases it, removes the directory, and 404s after', async () => {
const otherId = manager.create({ name: 'Other Project', group: 'Personal' }).id;
await memory.remember({ scope: workspaceScope(wsId), text: 'Side project memory' });
await memory.remember({ scope: workspaceScope(otherId), text: 'Other project memory' });
await memory.remember({ scope: PERSONAL_SCOPE, text: 'Personal memory' });
new AwarenessLayer(waggleDb, workspaceDataScope(wsId)).add('task', 'Side project task');
new AwarenessLayer(waggleDb, workspaceDataScope(otherId)).add('task', 'Other project task');
const res = await server.inject({ method: 'DELETE', url: `/api/workspaces/${wsId}` });
expect(res.statusCode).toBe(204);
expect(releaseWorkspace).toHaveBeenCalledWith(wsId);
expect(await memory.count({ scopes: [workspaceScope(wsId)] })).toBe(0);
expect(await memory.count({ scopes: [workspaceScope(otherId), PERSONAL_SCOPE] })).toBe(2);
expect(new AwarenessLayer(waggleDb, workspaceDataScope(wsId)).getAll()).toEqual([]);
expect(new AwarenessLayer(waggleDb, workspaceDataScope(otherId)).getAll()).toHaveLength(1);
expect(manager.get(wsId)).toBeNull();
expect(fs.existsSync(path.join(tmpDir, 'workspaces', wsId))).toBe(false);
const after = await server.inject({ method: 'DELETE', url: `/api/workspaces/${wsId}` });
expect(after.statusCode).toBe(404);
});
it('DELETE keeps the workspace when its memory cannot be forgotten', async () => {
vi.spyOn(memory, 'forgetMatching').mockRejectedValueOnce(new Error('store unavailable'));
const res = await server.inject({ method: 'DELETE', url: `/api/workspaces/${wsId}` });
expect(res.statusCode).toBe(500);
expect(releaseWorkspace).not.toHaveBeenCalled();
expect(manager.get(wsId)).not.toBeNull();
});
it('POST with a template seeds its starter memories into the new workspace', async () => {
const res = await server.inject({
method: 'POST',
url: '/api/workspaces',
payload: { name: 'Research Desk', group: 'Work', templateId: 'research-project' },
});
expect(res.statusCode).toBe(201);
const id = res.json().id as string;
await vi.waitFor(async () => {
expect(await memory.count({ scopes: [workspaceScope(id)] })).toBe(3);
});
const seeded = await memory.list({ scopes: [workspaceScope(id)] });
expect(seeded.every((m) => m.origin === 'workspace-template' && m.source === 'system')).toBe(true);
expect(seeded.map((m) => m.text)).toContain('This workspace is dedicated to research and investigation.');
});
});