moving
Some checks failed
Installer Smoke / installer-smoke (push) Has been cancelled

This commit is contained in:
Oleg Maslov
2026-09-02 10:10:29 +02:00
commit 0c3e2ead3b
3841 changed files with 970576 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
import { describe, it, expect } from 'vitest';
import { humanizeActivitySummary } from './activity-labels';
describe('humanizeActivitySummary', () => {
it('maps known tool events to plain language', () => {
expect(humanizeActivitySummary('tool_result: create_skill')).toBe('Created a skill');
expect(humanizeActivitySummary('tool_use: web_search')).toBe('Searched the web');
});
it('falls back to "Used <words>" for unknown tools', () => {
expect(humanizeActivitySummary('tool_result: fancy_new_tool')).toBe('Used fancy new tool');
});
it('passes plain summaries through untouched', () => {
expect(humanizeActivitySummary('Drafted the Q3 editorial memo')).toBe('Drafted the Q3 editorial memo');
});
});

View File

@@ -0,0 +1,37 @@
/**
* Humanize raw activity-event summaries for user-facing surfaces.
*
* The activity feed stores machine summaries like "tool_result: create_skill".
* Showing those verbatim in the workspace rail read as "the app is talking to
* itself, not to me" (judge-flagged on every non-developer persona).
*/
const TOOL_LABELS: Record<string, string> = {
create_skill: 'Created a skill',
delete_skill: 'Removed a skill',
read_skill: 'Looked up a skill',
promote_skill: 'Promoted a skill',
write_file: 'Wrote a file',
read_file: 'Read a file',
search_memory: 'Searched memory',
save_memory: 'Saved a memory',
recall_memory: 'Recalled a memory',
web_search: 'Searched the web',
install_capability: 'Installed a capability',
spawn_agent: 'Started an agent',
bash: 'Ran a command',
};
function humanizeToolName(tool: string): string {
const known = TOOL_LABELS[tool];
if (known) return known;
const words = tool.replace(/[_-]+/g, ' ').trim();
return `Used ${words}`;
}
/** "tool_result: create_skill" → "Created a skill"; plain text passes through. */
export function humanizeActivitySummary(summary: string): string {
const m = /^(tool_result|tool_use|tool_call):\s*([\w-]+)\s*$/.exec(summary.trim());
if (m) return humanizeToolName(m[2]);
return summary;
}

View File

@@ -0,0 +1,548 @@
/**
* P1b D3 — structural auth gate: deferral, throw-on-!ok, 401-refresh-retry.
*
* Pins the four-state ensureReady() contract (never-attempted passthrough /
* in-flight deferral / settled-success passthrough / settled-failure re-arm),
* the connect watchdog, the setServerUrl epoch guard, AdapterHttpError's
* message-first precedence, the 403 dispatch-then-throw ordering, the
* token-versioned single-flight 401 retry, and the fetchRaw body-envelope
* contract for the getters whose ERROR bodies are load-bearing (installMcp's
* ApprovalModal security envelope et al). These are the regression locks the
* existing component tests cannot provide — they mock the adapter methods
* themselves and are structurally blind to the fetch-layer semantics.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import LocalAdapter, {
AdapterHttpError,
adapter as singletonAdapter,
resolveDefaultServerUrl,
} from './adapter';
const BASE = 'http://test-server:4242';
const jsonRes = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
const HEALTH = { status: 'ok', mode: 'local' };
const TOKEN_PATH = '/api/auth/session-token';
/** Route-style fetch mock: dispatch on URL substring, in registration order. */
function routeMock(fetchSpy: ReturnType<typeof vi.spyOn>, routes: Array<[string, () => Response | Promise<Response>]>) {
fetchSpy.mockImplementation(async (url: unknown) => {
const u = String(url);
for (const [needle, handler] of routes) {
if (u.includes(needle)) return handler();
}
throw new Error(`unmocked fetch: ${u}`);
});
}
const callsTo = (fetchSpy: ReturnType<typeof vi.spyOn>, needle: string) =>
fetchSpy.mock.calls.filter(([u]) => String(u).includes(needle)) as unknown as Array<[string, RequestInit]>;
describe('P1b auth gate', () => {
let fetchSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch');
localStorage.clear();
});
afterEach(() => {
fetchSpy.mockRestore();
vi.useRealTimers();
});
it('fresh local web sessions default to the current HTTP origin', () => {
expect(resolveDefaultServerUrl({
protocol: 'http:',
hostname: '127.0.0.1',
port: '3344',
origin: 'http://127.0.0.1:3344',
} as Location)).toBe('http://127.0.0.1:3344');
expect(resolveDefaultServerUrl({
protocol: 'http:',
hostname: 'localhost',
port: '8081',
origin: 'http://localhost:8081',
} as Location)).toBe('http://localhost:8081');
});
it('non-local or non-HTTP browser origins keep the sidecar fallback', () => {
expect(resolveDefaultServerUrl({
protocol: 'https:',
hostname: 'localhost',
port: '3344',
origin: 'https://localhost:3344',
} as Location)).toBe('http://127.0.0.1:3333');
expect(resolveDefaultServerUrl({
protocol: 'tauri:',
hostname: 'localhost',
port: '',
origin: 'tauri://localhost',
} as Location)).toBe('http://127.0.0.1:3333');
expect(resolveDefaultServerUrl({
protocol: 'http:',
hostname: 'localhost.evil.com',
port: '3344',
origin: 'http://localhost.evil.com:3344',
} as Location)).toBe('http://127.0.0.1:3333');
});
/** Standard happy-path connect: /health ok + token ok. */
async function connectedAdapter(token = 'tok-A') {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [
['/health', () => jsonRes(HEALTH)],
[TOKEN_PATH, () => jsonRes({ token })],
]);
await a.connect();
return a;
}
// ── Gate states ──────────────────────────────────────────────────────────
it('zero network on construction (kickoff lives in boot-connect.ts, not the adapter)', () => {
void new LocalAdapter(BASE);
expect(singletonAdapter).toBeDefined(); // module import already happened — and made no calls
expect(fetchSpy).not.toHaveBeenCalled();
});
it('never-attempted: requests pass through ungated, no token fetch (unit-test compat)', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [['/api/workspaces', () => jsonRes([])]]);
await a.getWorkspaces();
expect(fetchSpy).toHaveBeenCalledOnce();
const [, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
expect((init.headers as Record<string, string>).Authorization).toBeUndefined();
});
it('in-flight: a request fired during connect defers until the token is attached', async () => {
const a = new LocalAdapter(BASE);
let releaseToken!: (r: Response) => void;
const tokenGate = new Promise<Response>(res => { releaseToken = res; });
routeMock(fetchSpy, [
['/health', () => jsonRes(HEALTH)],
[TOKEN_PATH, () => tokenGate],
['/api/workspaces', () => jsonRes([])],
]);
const connectP = a.connect();
const wsP = a.getWorkspaces(); // must NOT fire token-less
await new Promise(r => setTimeout(r, 10));
expect(callsTo(fetchSpy, '/api/workspaces')).toHaveLength(0); // still gated
releaseToken(jsonRes({ token: 'tok-A' }));
await connectP;
await wsP;
const ws = callsTo(fetchSpy, '/api/workspaces');
expect(ws).toHaveLength(1);
expect((ws[0][1]!.headers as Record<string, string>).Authorization).toBe('Bearer tok-A');
});
it('settled-success: memo retained — a second connect() makes no new requests', async () => {
const a = await connectedAdapter();
const callsAfterFirst = fetchSpy.mock.calls.length;
await a.connect();
expect(fetchSpy.mock.calls.length).toBe(callsAfterFirst);
});
it('same-tick connect() calls share one probe (StrictMode / boot+provider dedup)', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [
['/health', () => jsonRes(HEALTH)],
[TOKEN_PATH, () => jsonRes({ token: 'tok-A' })],
]);
await Promise.all([a.connect(), a.connect()]);
expect(callsTo(fetchSpy, '/health')).toHaveLength(1);
expect(callsTo(fetchSpy, TOKEN_PATH)).toHaveLength(1);
});
it('settled-failure: gate re-arms — the next request kicks a fresh connect and goes out authed', async () => {
const a = new LocalAdapter(BASE);
fetchSpy.mockRejectedValue(new TypeError('ECONNREFUSED'));
await expect(a.connect()).rejects.toThrow();
// Sidecar comes up:
routeMock(fetchSpy, [
['/health', () => jsonRes(HEALTH)],
[TOKEN_PATH, () => jsonRes({ token: 'tok-A' })],
['/api/workspaces', () => jsonRes([])],
]);
await a.getWorkspaces();
const ws = callsTo(fetchSpy, '/api/workspaces');
expect(ws).toHaveLength(1);
expect((ws[0][1]!.headers as Record<string, string>).Authorization).toBe('Bearer tok-A');
expect(callsTo(fetchSpy, '/health').length).toBeGreaterThanOrEqual(1);
});
it('a failed connect releases the gate — the request fails with its own cause, no hang', async () => {
const a = new LocalAdapter(BASE);
fetchSpy.mockRejectedValue(new TypeError('ECONNREFUSED'));
await expect(a.connect()).rejects.toThrow();
await expect(a.getWorkspaces()).rejects.toThrow(/Network error/);
});
it('watchdog: connect settles even when a probe body read hangs forever', async () => {
vi.useFakeTimers();
const a = new LocalAdapter(BASE);
const hanging = {
ok: true, status: 200, statusText: 'OK',
json: () => new Promise(() => { /* never */ }),
clone() { return this; },
} as unknown as Response;
fetchSpy.mockResolvedValue(hanging);
const p = a.connect();
const assertion = expect(p).rejects.toThrow(/timed out/);
await vi.advanceTimersByTimeAsync(16000);
await assertion;
expect(a.isConnected).toBe(false);
});
it('exempt paths bypass the gate: getSystemHealth works on a fresh adapter with zero token traffic', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [['/health', () => jsonRes(HEALTH)]]);
const h = await a.getSystemHealth();
expect(h.status).toBe('ok');
expect(callsTo(fetchSpy, TOKEN_PATH)).toHaveLength(0);
});
// ── setServerUrl epoch guard ─────────────────────────────────────────────
it('setServerUrl mid-flight: the stale connect cannot set connected state or the token', async () => {
const a = new LocalAdapter(BASE);
let releaseHealth!: (r: Response) => void;
const healthGate = new Promise<Response>(res => { releaseHealth = res; });
routeMock(fetchSpy, [
['/health', () => healthGate],
[TOKEN_PATH, () => jsonRes({ token: 'stale-token' })],
]);
const p = a.connect();
a.setServerUrl('http://user-chose-this:9999');
releaseHealth(jsonRes(HEALTH));
await p.catch(() => { /* either outcome — state must not leak */ });
expect(a.isConnected).toBe(false);
expect(a.getServerUrl()).toBe('http://user-chose-this:9999');
expect(localStorage.getItem('waggle:server-url')).toBe('http://user-chose-this:9999');
});
// ── Throw-on-!ok chokepoint ──────────────────────────────────────────────
it('AdapterHttpError: message-first precedence (body.message ?? body.error ?? HTTP n) + status/body fields', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [['/api/tier', () => jsonRes({ error: 'E_CODE', message: 'Human reason' }, 500)]]);
const err = await a.getTier().catch((e: unknown) => e) as AdapterHttpError;
expect(err).toBeInstanceOf(AdapterHttpError);
expect(err.message).toBe('Human reason');
expect(err.status).toBe(500);
expect((err.body as { error: string }).error).toBe('E_CODE');
routeMock(fetchSpy, [['/api/tier', () => jsonRes({ error: 'only-error' }, 404)]]);
const err2 = await a.getTier().catch((e: unknown) => e) as AdapterHttpError;
expect(err2.message).toBe('only-error');
routeMock(fetchSpy, [['/api/tier', () => new Response('plain text', { status: 502 })]]);
const err3 = await a.getTier().catch((e: unknown) => e) as AdapterHttpError;
expect(err3.message).toBe('HTTP 502');
});
it('the six ruling-named getters reject on HTTP failure instead of returning silent-empty', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [['/api/', () => jsonRes({ error: 'Unauthorized', code: 'MISSING_TOKEN' }, 500)]]);
await expect(a.getMarketplace()).rejects.toThrow(AdapterHttpError);
await expect(a.getMcps()).rejects.toThrow(AdapterHttpError);
await expect(a.getPersonas()).rejects.toThrow(AdapterHttpError);
await expect(a.getModels()).rejects.toThrow(AdapterHttpError);
await expect(a.getWorkspaceTemplates()).rejects.toThrow(AdapterHttpError);
await expect(a.getTier()).rejects.toThrow(AdapterHttpError);
});
it('403 TIER_INSUFFICIENT: dispatch-then-throw on the throwing path, dispatch-and-return on fetchRaw', async () => {
const a = new LocalAdapter(BASE);
const events: unknown[] = [];
const listener = (e: Event) => events.push((e as CustomEvent).detail);
window.addEventListener('waggle:tier-insufficient', listener);
try {
const tierBody = { error: 'TIER_INSUFFICIENT', message: 'Needs TEAMS', required: 'TEAMS', actual: 'FREE' };
routeMock(fetchSpy, [['/api/personas', () => jsonRes(tierBody, 403)]]);
await expect(a.getPersonas()).rejects.toThrow('Needs TEAMS');
expect(events).toHaveLength(1);
routeMock(fetchSpy, [['/api/mcps/install', () => jsonRes({ installed: false, ...tierBody }, 403)]]);
const envelope = await a.installMcp('exa');
expect((envelope as { error?: string }).error).toBe('TIER_INSUFFICIENT');
expect(events).toHaveLength(2);
} finally {
window.removeEventListener('waggle:tier-insufficient', listener);
}
});
it('sendMessage: an HTTP error now throws into the consumer instead of yielding nothing', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [
[TOKEN_PATH, () => jsonRes({ token: 'tok-A' })],
['/api/chat', () => jsonRes({ error: 'Unauthorized', code: 'INVALID_TOKEN' }, 401)],
]);
const consume = async () => {
const events = [];
for await (const ev of a.sendMessage('ws1', 'hi')) events.push(ev);
return events;
};
await expect(consume()).rejects.toThrow(AdapterHttpError);
});
// ── Body-envelope getters (fetchRaw contract — ApprovalModal flow et al) ──
it('installMcp resolves the 422 SecurityGate envelope (requiresApproval) instead of throwing', async () => {
const a = new LocalAdapter(BASE);
const envelope = { installed: false, requiresApproval: true, blocked: true, severity: 'HIGH', scanResult: { findings: 2 } };
routeMock(fetchSpy, [['/api/mcps/install', () => jsonRes(envelope, 422)]]);
await expect(a.installMcp('shady-mcp')).resolves.toMatchObject({ installed: false, requiresApproval: true });
});
it.each([
['addCustomMcp', (a: InstanceType<typeof LocalAdapter>) => a.addCustomMcp({ name: 'x', command: 'y' }), '/api/mcps'],
['testMcp', (a: InstanceType<typeof LocalAdapter>) => a.testMcp('m1'), '/api/mcps/m1/test'],
['startMcp', (a: InstanceType<typeof LocalAdapter>) => a.startMcp('m1'), '/api/mcps/m1/start'],
['stopMcp', (a: InstanceType<typeof LocalAdapter>) => a.stopMcp('m1'), '/api/mcps/m1/stop'],
['revokeMcp', (a: InstanceType<typeof LocalAdapter>) => a.revokeMcp('m1'), '/api/mcps/m1/revoke'],
['updateMcpPermissions', (a: InstanceType<typeof LocalAdapter>) => a.updateMcpPermissions('m1', { scope: 'personal' }), '/api/mcps/m1/permissions'],
['revokeConnector', (a: InstanceType<typeof LocalAdapter>) => a.revokeConnector('c1'), '/api/connectors/c1/revoke'],
])('%s resolves its error envelope as data (body-envelope contract)', async (_name, call, path) => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [[path, () => jsonRes({ error: 'spawn timed out after 10000ms' }, 502)]]);
await expect(call(a)).resolves.toMatchObject({ error: 'spawn timed out after 10000ms' });
});
it('installMarketplacePackage stays raw (status readable); uninstall now throws on failure', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [['/api/marketplace/install', () => jsonRes({ error: 'TIER_INSUFFICIENT' }, 403)]]);
const res = await a.installMarketplacePackage(7);
expect(res.status).toBe(403);
routeMock(fetchSpy, [['/api/marketplace/uninstall', () => jsonRes({ error: 'boom' }, 500)]]);
await expect(a.uninstallMarketplacePackage(7)).rejects.toThrow(AdapterHttpError);
});
// ── 401 → refresh → single retry ─────────────────────────────────────────
it('401: refreshes the token once and retries with the new bearer', async () => {
const a = await connectedAdapter('tok-A');
let wsCalls = 0;
routeMock(fetchSpy, [
[TOKEN_PATH, () => jsonRes({ token: 'tok-B' })],
['/api/workspaces', () => (++wsCalls === 1
? jsonRes({ error: 'Unauthorized', code: 'INVALID_TOKEN' }, 401)
: jsonRes([]))],
]);
await a.getWorkspaces();
const ws = callsTo(fetchSpy, '/api/workspaces');
expect(ws).toHaveLength(2);
expect((ws[1][1]!.headers as Record<string, string>).Authorization).toBe('Bearer tok-B');
});
it('still-401 after the retry surfaces as AdapterHttpError — exactly one refresh, one retry', async () => {
const a = await connectedAdapter('tok-A');
fetchSpy.mockClear();
routeMock(fetchSpy, [
[TOKEN_PATH, () => jsonRes({ token: 'tok-B' })],
['/api/workspaces', () => jsonRes({ error: 'Unauthorized', code: 'INVALID_TOKEN' }, 401)],
]);
await expect(a.getWorkspaces()).rejects.toThrow(AdapterHttpError);
expect(callsTo(fetchSpy, '/api/workspaces')).toHaveLength(2);
expect(callsTo(fetchSpy, TOKEN_PATH)).toHaveLength(1);
});
it('straggler 401 burst: concurrent failures share ONE single-flight refresh', async () => {
const a = await connectedAdapter('tok-A');
fetchSpy.mockClear();
let wsCalls = 0;
let sesCalls = 0;
routeMock(fetchSpy, [
[TOKEN_PATH, () => jsonRes({ token: `tok-B` })],
['/api/workspaces', () => (++wsCalls <= 2
? jsonRes({ error: 'Unauthorized', code: 'INVALID_TOKEN' }, 401)
: jsonRes([]))],
['/api/sessions-x', () => (++sesCalls <= 1 ? jsonRes({ error: 'Unauthorized' }, 401) : jsonRes([]))],
]);
await Promise.all([a.getWorkspaces(), a.getWorkspaces()]);
expect(callsTo(fetchSpy, TOKEN_PATH)).toHaveLength(1);
});
it('token-versioned: a straggler whose 401 lands after the token rotated retries WITHOUT a new refresh', async () => {
const a = await connectedAdapter('tok-A');
fetchSpy.mockClear();
let release401!: (r: Response) => void;
const gate401 = new Promise<Response>(res => { release401 = res; });
let tierCalls = 0;
let wsCalls = 0;
routeMock(fetchSpy, [
[TOKEN_PATH, () => jsonRes({ token: 'tok-B' })],
['/api/tier', () => (++tierCalls === 1 ? gate401 : jsonRes({ tier: 'TEAMS', capabilities: {}, usage: {} }))],
['/api/workspaces', () => (++wsCalls === 1
? jsonRes({ error: 'Unauthorized', code: 'INVALID_TOKEN' }, 401)
: jsonRes([]))],
]);
const tierP = a.getTier(); // in flight with tok-A, response held
await a.getWorkspaces(); // 401 → refresh → tok-B
expect(callsTo(fetchSpy, TOKEN_PATH)).toHaveLength(1);
release401(jsonRes({ error: 'Unauthorized', code: 'INVALID_TOKEN' }, 401)); // straggler lands post-rotation
await tierP;
expect(callsTo(fetchSpy, TOKEN_PATH)).toHaveLength(1); // no second refresh
const tier = callsTo(fetchSpy, '/api/tier');
expect((tier[1][1]!.headers as Record<string, string>).Authorization).toBe('Bearer tok-B');
});
it('refresh failure is LOUD: the original call rejects with the refresh cause, no token-less retry', async () => {
const a = await connectedAdapter('tok-A');
fetchSpy.mockClear();
routeMock(fetchSpy, [
[TOKEN_PATH, () => { throw new TypeError('ECONNREFUSED'); }],
['/api/workspaces', () => jsonRes({ error: 'Unauthorized' }, 401)],
]);
await expect(a.getWorkspaces()).rejects.toThrow(/Network error/);
expect(callsTo(fetchSpy, '/api/workspaces')).toHaveLength(1); // no blind retry
});
it('loop guard: a 401 from the token endpoint itself cannot recurse', async () => {
const a = await connectedAdapter('tok-A');
fetchSpy.mockClear();
routeMock(fetchSpy, [
[TOKEN_PATH, () => jsonRes({ error: 'Forbidden: external origin' }, 403)],
['/api/workspaces', () => jsonRes({ error: 'Unauthorized' }, 401)],
]);
await expect(a.getWorkspaces()).rejects.toThrow(AdapterHttpError);
expect(callsTo(fetchSpy, TOKEN_PATH)).toHaveLength(1);
});
// ── Multipart through the shared core ────────────────────────────────────
it('uploadFile: FormData body gets the bearer but NOT the JSON content-type default', async () => {
const a = await connectedAdapter('tok-A');
fetchSpy.mockClear();
routeMock(fetchSpy, [['/files/upload', () => jsonRes({ name: 'f.txt' })]]);
await a.uploadFile('ws1', '/', new File(['x'], 'f.txt'));
const [, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
const headers = init.headers as Record<string, string>;
expect(headers.Authorization).toBe('Bearer tok-A');
expect(Object.keys(headers).find(h => h.toLowerCase() === 'content-type')).toBeUndefined();
expect(init.body).toBeInstanceOf(FormData);
});
it('uploadFile: 401 → refresh → retried multipart succeeds; 413 surfaces the server reason', async () => {
const a = await connectedAdapter('tok-A');
fetchSpy.mockClear();
let calls = 0;
routeMock(fetchSpy, [
[TOKEN_PATH, () => jsonRes({ token: 'tok-B' })],
['/files/upload', () => (++calls === 1
? jsonRes({ error: 'Unauthorized', code: 'INVALID_TOKEN' }, 401)
: jsonRes({ name: 'f.txt' }))],
]);
await expect(a.uploadFile('ws1', '/', new File(['x'], 'f.txt'))).resolves.toMatchObject({ name: 'f.txt' });
const ups = callsTo(fetchSpy, '/files/upload');
expect(ups).toHaveLength(2);
expect((ups[1][1].headers as Record<string, string>).Authorization).toBe('Bearer tok-B');
routeMock(fetchSpy, [['/api/ingest', () => jsonRes({ error: 'backup too large', message: 'File exceeds 50MB' }, 413)]]);
const err = await a.ingestFile(new File(['x'], 'big.bin')).catch((e: unknown) => e) as AdapterHttpError;
expect(err).toBeInstanceOf(AdapterHttpError);
expect(err.status).toBe(413);
expect(err.message).toBe('File exceeds 50MB');
});
// ── 404→null contracts + envelope stragglers (review fixes) ──────────────
it.each([
['getMemory', (a: InstanceType<typeof LocalAdapter>) => a.getMemory('m1'), '/api/memory/m1'],
['getArtifact', (a: InstanceType<typeof LocalAdapter>) => a.getArtifact('a1'), '/api/artifacts/a1'],
['getAgent', (a: InstanceType<typeof LocalAdapter>) => a.getAgent('ag1'), '/api/agents/ag1'],
])('%s preserves the documented 404→null contract and throws on other failures', async (_n, call, path) => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [[path, () => jsonRes({ error: 'not found' }, 404)]]);
await expect(call(a)).resolves.toBeNull();
routeMock(fetchSpy, [[path, () => jsonRes({ error: 'boom' }, 500)]]);
await expect(call(a)).rejects.toThrow(AdapterHttpError);
});
it('manageHooks maps a non-2xx body into the { ok:false, stderr, code } envelope (not a throw)', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [['/api/tools/hooks', () => jsonRes({ ok: false, action: 'install', stdout: '', stderr: 'permission denied', code: 1, error: 'install failed' }, 500)]]);
await expect(a.manageHooks({ id: 'claude-code', action: 'install' })).resolves.toMatchObject({
ok: false, stderr: 'permission denied', code: 1, error: 'install failed',
});
});
it('manageHooks preserves a structured hook failure without replacing it with HTTP status text', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [['/api/tools/hooks', () => jsonRes({
ok: false,
action: 'verify',
packageName: '@waggle/hive-mind-hooks-claude-code',
stdout: '',
stderr: '',
code: 1,
}, 400)]]);
await expect(a.manageHooks({ id: 'claude-code', action: 'verify' })).resolves.toMatchObject({
ok: false,
action: 'verify',
stdout: '',
stderr: '',
code: 1,
error: undefined,
});
});
// ── Watchdog recovery + setServerUrl memo hygiene (review fixes) ─────────
it('after a hung-body timeout, the NEXT connect probes fresh (memo does not wedge re-arms)', async () => {
vi.useFakeTimers();
const a = new LocalAdapter(BASE);
const hanging = {
ok: true, status: 200, statusText: 'OK',
json: () => new Promise(() => { /* never */ }),
clone() { return this; },
} as unknown as Response;
fetchSpy.mockResolvedValue(hanging);
const p1 = a.connect();
const assertion1 = expect(p1).rejects.toThrow(/timed out/);
await vi.advanceTimersByTimeAsync(16000);
await assertion1;
vi.useRealTimers();
// Sidecar healthy now — a fresh connect must succeed, not dedup onto the hung probe.
routeMock(fetchSpy, [
['/health', () => jsonRes(HEALTH)],
[TOKEN_PATH, () => jsonRes({ token: 'tok-A' })],
]);
await expect(a.connect()).resolves.toMatchObject({ status: 'ok' });
});
it('setServerUrl clears the probe memo — a follow-up connect probes the NEW url', async () => {
const a = new LocalAdapter(BASE);
let releaseOld!: (r: Response) => void;
const oldGate = new Promise<Response>(res => { releaseOld = res; });
fetchSpy.mockImplementation(async (url: unknown) => {
const u = String(url);
if (u.startsWith(BASE)) return oldGate; // old-server probe hangs
if (u.includes('/health')) return jsonRes(HEALTH);
if (u.includes(TOKEN_PATH)) return jsonRes({ token: 'tok-NEW' });
throw new Error(`unmocked: ${u}`);
});
const p1 = a.connect();
a.setServerUrl('http://new-server:5555');
const p2 = a.connect();
await expect(p2).resolves.toMatchObject({ status: 'ok' });
expect(fetchSpy.mock.calls.some(([u]) => String(u).startsWith('http://new-server:5555/health'))).toBe(true);
releaseOld(jsonRes(HEALTH));
await p1.catch(() => { /* stale attempt — outcome irrelevant */ });
});
it('forceReconnect bypasses the settled-success memo and re-probes', async () => {
const a = await connectedAdapter('tok-A');
fetchSpy.mockClear();
routeMock(fetchSpy, [
['/health', () => jsonRes(HEALTH)],
[TOKEN_PATH, () => jsonRes({ token: 'tok-B' })],
]);
await a.forceReconnect();
expect(callsTo(fetchSpy, '/health')).toHaveLength(1); // a plain connect() would have made zero calls
});
});

View File

@@ -0,0 +1,89 @@
/**
* M-44 / P26 — guard the POST /api/cron contract from the client side.
*
* Prior shape sent `{ name, schedule, workspaceId, enabled }` which the
* server (`cron.ts:47-49`) rejected with 400 because both `cronExpr`
* and `jobType` are required. This test pins the corrected payload so
* a regression shows up in CI, not in a user's "why won't my job
* create" moment.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import LocalAdapter from './adapter';
describe('LocalAdapter.createCronJob', () => {
let fetchSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
new Response(
JSON.stringify({
id: 42,
name: 'Nightly consolidation',
cronExpr: '0 9 * * *',
jobType: 'memory_consolidation',
workspaceId: '',
enabled: true,
lastRunAt: null,
nextRunAt: '2026-04-20T09:00:00Z',
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
),
);
});
afterEach(() => {
fetchSpy.mockRestore();
});
it('POSTs cronExpr + jobType to /api/cron (not legacy `schedule`)', async () => {
const adapter = new LocalAdapter('http://test:1');
await adapter.createCronJob({
name: 'Nightly consolidation',
cronExpr: '0 9 * * *',
jobType: 'memory_consolidation',
enabled: true,
});
const [url, init] = fetchSpy.mock.calls[0] as [string | URL, RequestInit];
expect(String(url)).toBe('http://test:1/api/cron');
expect(init.method).toBe('POST');
const body = JSON.parse(init.body as string);
expect(body.name).toBe('Nightly consolidation');
expect(body.cronExpr).toBe('0 9 * * *');
expect(body.jobType).toBe('memory_consolidation');
// Legacy `schedule` must NOT be sent — server schema no longer
// accepts it and including it would fail strict-mode validators.
expect(body).not.toHaveProperty('schedule');
});
it('normalizes the server response back to the legacy client shape', async () => {
// Server emits cronExpr / lastRunAt / nextRunAt; UI consumers still
// read schedule / lastRun / nextRun. Ensure the remap hides that.
const adapter = new LocalAdapter('http://test:1');
const job = await adapter.createCronJob({
name: 'Nightly',
cronExpr: '0 9 * * *',
jobType: 'memory_consolidation',
});
expect(job.schedule).toBe('0 9 * * *');
expect(job.nextRun).toBe('2026-04-20T09:00:00Z');
expect(job.enabled).toBe(true);
});
it('forwards jobConfig + workspaceId when provided', async () => {
const adapter = new LocalAdapter('http://test:1');
await adapter.createCronJob({
name: 'Scoped',
cronExpr: '*/5 * * * *',
jobType: 'agent_task',
workspaceId: 'ws-42',
jobConfig: { prompt: 'hi' },
});
const [, init] = fetchSpy.mock.calls[0] as [string | URL, RequestInit];
const body = JSON.parse(init.body as string);
expect(body.workspaceId).toBe('ws-42');
expect(body.jobConfig).toEqual({ prompt: 'hi' });
});
});

View File

@@ -0,0 +1,85 @@
/**
* LocalAdapter.eraseData — GDPR Art. 17 erasure request wiring.
*
* Pins the contract between Settings → Privacy → "Erase all my data" + the
* EraseDataDialog and the server's POST /api/data/erase route (data-erase.ts).
* Specifically guards the confirmation gate: header `X-Confirm-Erase: yes`
* + body `{ confirmation: '<exact phrase>' }`. If either drops, the route
* returns 400 and an unsuspecting user could think their data was wiped.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import LocalAdapter from './adapter';
describe('LocalAdapter.eraseData', () => {
let fetchSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch');
});
afterEach(() => {
fetchSpy.mockRestore();
});
it('POSTs to /api/data/erase with the confirmation header AND body phrase', async () => {
fetchSpy.mockResolvedValue(
new Response(JSON.stringify({
requestedAt: '2026-05-08T12:00:00.000Z',
markerPath: '/tmp/waggle/.erase-pending.json',
dataDirSnapshot: { fileCount: 4, totalBytes: 1024, topLevelEntries: [] },
instruction: 'Quit Waggle and relaunch — erasure completes during startup.',
}), {
status: 200,
headers: { 'Content-Type': 'application/json' },
}),
);
const adapter = new LocalAdapter('http://test-server:9999');
const result = await adapter.eraseData('I UNDERSTAND THIS IS PERMANENT');
expect(fetchSpy).toHaveBeenCalledOnce();
const [url, init] = fetchSpy.mock.calls[0] as [string | URL, RequestInit];
expect(String(url)).toBe('http://test-server:9999/api/data/erase');
expect(init.method).toBe('POST');
// Both halves of the confirmation gate MUST be present.
const headers = init.headers as Record<string, string>;
expect(headers['X-Confirm-Erase']).toBe('yes');
const body = JSON.parse(init.body as string);
expect(body).toEqual({ confirmation: 'I UNDERSTAND THIS IS PERMANENT' });
// Receipt returned verbatim — dialog needs every field.
expect(result.requestedAt).toBe('2026-05-08T12:00:00.000Z');
expect(result.markerPath).toBe('/tmp/waggle/.erase-pending.json');
expect(result.dataDirSnapshot.fileCount).toBe(4);
expect(result.dataDirSnapshot.totalBytes).toBe(1024);
expect(result.instruction).toMatch(/relaunch/i);
});
it('forwards whatever phrase the caller passes — server validates exact match', async () => {
fetchSpy.mockResolvedValue(
new Response(JSON.stringify({
error: 'ERASE_NOT_CONFIRMED',
message: '"confirmation" must match the exact phrase',
}), { status: 400, headers: { 'Content-Type': 'application/json' } }),
);
const adapter = new LocalAdapter('http://test-server:9999');
// Wrong phrase. Server returns 400. Adapter must throw — silently
// swallowing would let the dialog claim success.
await expect(adapter.eraseData('i understand this is permanent'))
.rejects.toThrow(/Erase failed.*400/);
// The phrase the caller passed is what gets sent — no client-side
// normalization or validation.
const [, init] = fetchSpy.mock.calls[0] as [string | URL, RequestInit];
expect(JSON.parse(init.body as string).confirmation).toBe('i understand this is permanent');
});
it('throws on 500 with the server status text when the body is not JSON', async () => {
fetchSpy.mockResolvedValue(new Response('disk full', { status: 500, statusText: 'Internal Server Error' }));
const adapter = new LocalAdapter('http://test-server:9999');
await expect(adapter.eraseData('I UNDERSTAND THIS IS PERMANENT'))
.rejects.toThrow(/Erase failed.*500/);
});
});

View File

@@ -0,0 +1,49 @@
/**
* P2 regression lock — getWorkspaceFiles envelope unwrap.
*
* The /api/workspaces/:id/files route returns `{ files: [...] }` (workspaces.ts
* F2), but the adapter used to return the envelope object itself; the
* defensive Array.isArray guard in WorkspaceDesktopApp's normalizeArtifacts()
* then silently rendered the Artifacts widget/tab permanently empty. This file
* pins the unwrap at the fetch layer — component tests mock the adapter and
* are structurally blind to it (same class as the authgate fetch-layer pins).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import LocalAdapter from './adapter';
const BASE = 'http://test-server:4242';
const jsonRes = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
describe('getWorkspaceFiles envelope unwrap (P2)', () => {
let fetchSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch');
localStorage.clear();
});
afterEach(() => {
fetchSpy.mockRestore();
});
it('unwraps the { files: [...] } envelope', async () => {
const a = new LocalAdapter(BASE);
fetchSpy.mockResolvedValue(jsonRes({ files: [{ name: 'plan.md' }, { name: 'deck.pptx' }] }));
const files = await a.getWorkspaceFiles('w1');
expect(files).toEqual([{ name: 'plan.md' }, { name: 'deck.pptx' }]);
});
it('passes a raw array through unchanged (forward compat)', async () => {
const a = new LocalAdapter(BASE);
fetchSpy.mockResolvedValue(jsonRes([{ name: 'plan.md' }]));
expect(await a.getWorkspaceFiles('w1')).toEqual([{ name: 'plan.md' }]);
});
it('degrades to [] on a body without a files array', async () => {
const a = new LocalAdapter(BASE);
fetchSpy.mockResolvedValue(jsonRes({ unexpected: true }));
expect(await a.getWorkspaceFiles('w1')).toEqual([]);
});
});

View File

@@ -0,0 +1,63 @@
/**
* AI-OS #4 — adapter launcher tests: observe flows into the launch body, and
* streamToolOutput is a safe no-op without EventSource (jsdom).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import LocalAdapter from './adapter';
const BASE = 'http://test-server:4242';
const jsonRes = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
const HEALTH = { status: 'ok', mode: 'local' };
const TOKEN_PATH = '/api/auth/session-token';
function routeMock(
spy: ReturnType<typeof vi.spyOn>,
routes: Array<[string, () => Response]>,
) {
spy.mockImplementation(async (url: unknown) => {
const u = String(url);
for (const [needle, handler] of routes) {
if (u.includes(needle)) return handler();
}
throw new Error(`unmocked fetch: ${u}`);
});
}
describe('adapter launcher #4', () => {
let fetchSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch');
localStorage.clear();
});
afterEach(() => {
fetchSpy.mockRestore();
});
it('forwards observe:true in the POST body', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [
['/health', () => jsonRes(HEALTH)],
[TOKEN_PATH, () => jsonRes({ token: 'tok' })],
['/api/tools/launch', () => jsonRes({ ok: true, pid: 5 }, 202)],
]);
await a.connect();
const res = await a.launchTool({ id: 'claude-code', installedPath: '/x', observe: true });
expect(res.ok).toBe(true);
const launchCall = fetchSpy.mock.calls.find((c) =>
String(c[0]).includes('/api/tools/launch'),
) as unknown as [string, RequestInit] | undefined;
const body = JSON.parse(String(launchCall?.[1]?.body));
expect(body.observe).toBe(true);
});
it('streamToolOutput returns a no-op unsubscribe without EventSource (jsdom)', () => {
const a = new LocalAdapter(BASE);
const off = a.streamToolOutput(5, { onLine: () => {}, onExit: () => {} });
expect(typeof off).toBe('function');
expect(() => off()).not.toThrow();
});
});

View File

@@ -0,0 +1,112 @@
/**
* Guards the snake_case → camelCase remap inside
* LocalAdapter.getMemoryStats. Server emits {frameCount, entityCount,
* relationCount}; the client contract exposes {frames, entities,
* relations}. Before this test landed, the adapter returned `res.json()`
* raw, so every consumer (useMemory, DashboardApp, Brain Health metric)
* read `undefined` and displayed 0.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import LocalAdapter from './adapter';
describe('LocalAdapter.getMemoryStats', () => {
let fetchSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch');
});
afterEach(() => {
fetchSpy.mockRestore();
});
function respondWith(payload: unknown): void {
fetchSpy.mockResolvedValue(
new Response(JSON.stringify(payload), {
status: 200,
headers: { 'Content-Type': 'application/json' },
}),
);
}
it('remaps server snake_case field names to the client contract', async () => {
respondWith({
personal: { frameCount: 100, entityCount: 20, relationCount: 15 },
workspace: { frameCount: 5, entityCount: 2, relationCount: 1 },
total: { frameCount: 105, entityCount: 22, relationCount: 16 },
});
const adapter = new LocalAdapter('http://test:1');
const stats = await adapter.getMemoryStats();
expect(stats.personal).toEqual({ frames: 100, entities: 20, relations: 15 });
expect(stats.workspace).toEqual({ frames: 5, entities: 2, relations: 1 });
expect(stats.total).toEqual({ frames: 105, entities: 22, relations: 16 });
});
it('coerces null workspace (no filter passed) to a zeroed object', async () => {
respondWith({
personal: { frameCount: 42, entityCount: 8, relationCount: 3 },
workspace: null,
total: { frameCount: 42, entityCount: 8, relationCount: 3 },
});
const adapter = new LocalAdapter('http://test:1');
const stats = await adapter.getMemoryStats();
expect(stats.workspace).toEqual({ frames: 0, entities: 0, relations: 0 });
expect(stats.personal.frames).toBe(42);
});
it('tolerates already-camelCase payloads (future-proofing)', async () => {
respondWith({
personal: { frames: 7, entities: 3, relations: 1 },
workspace: null,
total: { frames: 7, entities: 3, relations: 1 },
});
const adapter = new LocalAdapter('http://test:1');
const stats = await adapter.getMemoryStats();
expect(stats.personal).toEqual({ frames: 7, entities: 3, relations: 1 });
});
it('W2D: scopes to a workspace via ?workspace= when an id is passed', async () => {
respondWith({
personal: { frameCount: 100, entityCount: 20, relationCount: 15 },
workspace: { frameCount: 5, entityCount: 2, relationCount: 1 },
total: { frameCount: 105, entityCount: 22, relationCount: 16 },
});
const adapter = new LocalAdapter('http://test:1');
await adapter.getMemoryStats('ws-42');
const url = String(fetchSpy.mock.calls[0][0]);
expect(url).toContain('/api/memory/stats');
expect(url).toContain('workspace=ws-42');
});
it('does not append a workspace param when called with no argument', async () => {
respondWith({ personal: { frameCount: 1 }, workspace: null, total: { frameCount: 1 } });
const adapter = new LocalAdapter('http://test:1');
await adapter.getMemoryStats();
const url = String(fetchSpy.mock.calls[0][0]);
expect(url).not.toContain('workspace=');
});
it('returns zeroed stats on network / parse failure', async () => {
fetchSpy.mockRejectedValue(new Error('boom'));
const adapter = new LocalAdapter('http://test:1');
const stats = await adapter.getMemoryStats();
expect(stats.personal).toEqual({ frames: 0, entities: 0, relations: 0 });
expect(stats.workspace).toEqual({ frames: 0, entities: 0, relations: 0 });
expect(stats.total).toEqual({ frames: 0, entities: 0, relations: 0 });
});
it('treats missing fields as zero, not NaN', async () => {
respondWith({
personal: { frameCount: 10 }, // no entityCount / relationCount
workspace: null,
total: { frameCount: 10 },
});
const adapter = new LocalAdapter('http://test:1');
const stats = await adapter.getMemoryStats();
expect(stats.personal.entities).toBe(0);
expect(stats.personal.relations).toBe(0);
expect(Number.isNaN(stats.personal.entities)).toBe(false);
});
});

View File

@@ -0,0 +1,33 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import LocalAdapter from './adapter';
describe('model router request deadlines', () => {
let client: LocalAdapter;
beforeEach(() => {
client = new LocalAdapter('http://127.0.0.1:3333');
});
it('allows provider discovery and managed router startup to finish', async () => {
const fetchSpy = vi.spyOn(client, 'fetch').mockImplementation(async () => new Response(JSON.stringify({
ok: true,
model: 'openai/new-model',
configured: true,
verified: true,
running: true,
models: ['openai/new-model'],
}), { status: 200, headers: { 'content-type': 'application/json' } }));
await client.setModel('openai/new-model');
await client.probeModel('openai/new-model');
await client.setProviderKey('openai', 'secret');
await client.restartModelRouter();
expect(fetchSpy.mock.calls.map((call) => call[2])).toEqual([
45_000,
45_000,
45_000,
45_000,
]);
});
});

View File

@@ -0,0 +1,105 @@
/**
* P4 · LocalAdapter permissions roundtrip.
*
* Verifies the client side of the P4 refactor: getPermissions() hits the
* right URL + deserializes defaultAutonomy, and savePermissions() passes
* through the partial payload untouched. The server half is covered by
* packages/server/tests/local/settings-permissions.test.ts.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import LocalAdapter from './adapter';
describe('LocalAdapter permissions methods (P4)', () => {
let fetchSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch');
});
afterEach(() => {
fetchSpy.mockRestore();
});
function respondWith(payload: unknown, status = 200): void {
fetchSpy.mockResolvedValue(
new Response(JSON.stringify(payload), {
status,
headers: { 'Content-Type': 'application/json' },
}),
);
}
describe('getPermissions', () => {
it('GETs /api/settings/permissions and returns the body as-is', async () => {
respondWith({
defaultAutonomy: 'trusted',
externalGates: ['git push'],
workspaceOverrides: { 'ws-1': ['deploy'] },
});
const adapter = new LocalAdapter('http://test:1');
const result = await adapter.getPermissions();
expect(fetchSpy).toHaveBeenCalledTimes(1);
const [url, init] = fetchSpy.mock.calls[0] as [RequestInfo | URL, RequestInit | undefined];
expect(String(url)).toContain('/api/settings/permissions');
// GET — no explicit method or body. The adapter may still send default
// request options (e.g. auth headers), so just assert the semantic opts.
expect(init?.method ?? 'GET').toBe('GET');
expect(init?.body).toBeUndefined();
expect(result).toEqual({
defaultAutonomy: 'trusted',
externalGates: ['git push'],
workspaceOverrides: { 'ws-1': ['deploy'] },
});
});
it('returns each enum value untouched', async () => {
for (const level of ['normal', 'trusted', 'yolo'] as const) {
respondWith({ defaultAutonomy: level, externalGates: [], workspaceOverrides: {} });
const adapter = new LocalAdapter('http://test:1');
const result = await adapter.getPermissions();
expect(result.defaultAutonomy).toBe(level);
}
});
});
describe('savePermissions', () => {
it('PUTs /api/settings/permissions with a JSON body containing the partial payload', async () => {
respondWith({ defaultAutonomy: 'yolo', externalGates: [], workspaceOverrides: {} });
const adapter = new LocalAdapter('http://test:1');
await adapter.savePermissions({ defaultAutonomy: 'yolo' });
expect(fetchSpy).toHaveBeenCalledTimes(1);
const [url, init] = fetchSpy.mock.calls[0] as [RequestInfo | URL, RequestInit | undefined];
expect(String(url)).toContain('/api/settings/permissions');
expect(init?.method).toBe('PUT');
const body = JSON.parse(String(init?.body ?? '{}'));
expect(body).toEqual({ defaultAutonomy: 'yolo' });
});
it('accepts partial updates — gates-only, no autonomy', async () => {
respondWith({ defaultAutonomy: 'normal', externalGates: ['rm -rf'], workspaceOverrides: {} });
const adapter = new LocalAdapter('http://test:1');
await adapter.savePermissions({ externalGates: ['rm -rf'] });
const body = JSON.parse(String((fetchSpy.mock.calls[0][1] as RequestInit | undefined)?.body ?? '{}'));
expect(body).toEqual({ externalGates: ['rm -rf'] });
expect(body).not.toHaveProperty('defaultAutonomy');
});
it('accepts the full triple (autonomy + gates + workspace overrides)', async () => {
respondWith({ defaultAutonomy: 'trusted', externalGates: ['x'], workspaceOverrides: { w: ['y'] } });
const adapter = new LocalAdapter('http://test:1');
await adapter.savePermissions({
defaultAutonomy: 'trusted',
externalGates: ['x'],
workspaceOverrides: { w: ['y'] },
});
const body = JSON.parse(String((fetchSpy.mock.calls[0][1] as RequestInit | undefined)?.body ?? '{}'));
expect(body.defaultAutonomy).toBe('trusted');
expect(body.externalGates).toEqual(['x']);
expect(body.workspaceOverrides).toEqual({ w: ['y'] });
});
});
});

View File

@@ -0,0 +1,117 @@
/**
* H-03 · P36 — LocalAdapter.spawnAgent submission wiring.
*
* The dock spawn-agent button opens SpawnAgentDialog; the dialog's submit
* path calls `adapter.spawnAgent(...)` which must POST the task payload to
* `/api/fleet/spawn`. This test pins the contract between the UI and the
* server route so regressions in either side surface as a test failure.
*
* E2E coverage for the dock click → dialog open path lives in
* tests/e2e/spawn-agent-flow.spec.ts.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import LocalAdapter from './adapter';
describe('LocalAdapter.spawnAgent', () => {
let fetchSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
new Response(
JSON.stringify({
id: 'run-1',
runId: 'run-1',
roomId: 'room-1',
workspaceId: 'ws-1',
sessionId: 'spawn-run-1',
status: 'queued',
statusUrl: '/api/agent-runs/run-1',
resumable: false,
task: 'test',
persona: 'researcher',
model: 'claude-sonnet-4-6',
}),
{
status: 202,
headers: { 'Content-Type': 'application/json' },
},
),
);
});
afterEach(() => {
fetchSpy.mockRestore();
});
it('POSTs to /api/fleet/spawn with the full form payload', async () => {
const adapter = new LocalAdapter('http://test-server:9999');
await adapter.spawnAgent({
task: 'Run a short sanity check',
model: 'claude-sonnet-4-6',
persona: 'researcher',
parentWorkspaceId: 'ws-1',
});
expect(fetchSpy).toHaveBeenCalledOnce();
const [url, init] = fetchSpy.mock.calls[0] as [string | URL, RequestInit];
expect(String(url)).toBe('http://test-server:9999/api/fleet/spawn');
expect(init.method).toBe('POST');
const headers = init.headers as Record<string, string>;
expect(headers['Content-Type']).toBe('application/json');
const body = JSON.parse(init.body as string);
expect(body).toEqual({
task: 'Run a short sanity check',
model: 'claude-sonnet-4-6',
persona: 'researcher',
parentWorkspaceId: 'ws-1',
});
});
it('POSTs a minimal payload when optional fields are omitted', async () => {
const adapter = new LocalAdapter('http://test-server:9999');
await adapter.spawnAgent({ task: 'minimal' });
const [, init] = fetchSpy.mock.calls[0] as [string | URL, RequestInit];
const body = JSON.parse(init.body as string);
expect(body).toEqual({ task: 'minimal' });
// Guards against accidental default injection server-side — undefined
// optional keys must be dropped, not sent as explicit undefined/null.
expect(body).not.toHaveProperty('model');
expect(body).not.toHaveProperty('persona');
expect(body).not.toHaveProperty('parentWorkspaceId');
});
it('returns the parsed server response', async () => {
const adapter = new LocalAdapter('http://test-server:9999');
const result = await adapter.spawnAgent({ task: 'test' });
expect(result).toEqual({
id: 'run-1',
runId: 'run-1',
roomId: 'room-1',
workspaceId: 'ws-1',
sessionId: 'spawn-run-1',
status: 'queued',
statusUrl: '/api/agent-runs/run-1',
resumable: false,
task: 'test',
persona: 'researcher',
model: 'claude-sonnet-4-6',
});
});
it('rejects a legacy response without canonical run and Room identity', async () => {
fetchSpy.mockResolvedValueOnce(new Response(
JSON.stringify({ id: 'legacy-session', workspaceId: 'ws-1', status: 'running' }),
{ status: 200, headers: { 'Content-Type': 'application/json' } },
));
const adapter = new LocalAdapter('http://test-server:9999');
await expect(adapter.spawnAgent({ task: 'test' })).rejects.toThrow(
'Agent started without a canonical Room identity',
);
});
});

View File

@@ -0,0 +1,296 @@
/**
* P1b-SSE — client EventSource machinery: token-attached URLs, lazy-open
* behind the connect gate, reconnect-with-fresh-token on error, per-path
* dedup, the named-event subagent listener surviving reopen, and the
* harvest `ready` contract. jsdom has no EventSource — a fake records
* construction and lets tests drive open/error.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import LocalAdapter from './adapter';
const BASE = 'http://test-server:4242';
const TOKEN_PATH = '/api/auth/session-token';
const jsonRes = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
class FakeEventSource {
static instances: FakeEventSource[] = [];
static OPEN = 1;
url: string;
readyState = 0;
onmessage: ((e: MessageEvent) => void) | null = null;
onerror: (() => void) | null = null;
onopen: (() => void) | null = null;
closed = false;
listeners = new Map<string, EventListener[]>();
constructor(url: string) {
this.url = url;
FakeEventSource.instances.push(this);
}
addEventListener(type: string, fn: EventListener) {
this.listeners.set(type, [...(this.listeners.get(type) ?? []), fn]);
}
removeEventListener(type: string, fn: EventListener) {
this.listeners.set(type, (this.listeners.get(type) ?? []).filter(l => l !== fn));
}
close() { this.closed = true; }
/** Test drivers */
fireOpen() { this.readyState = 1; this.onopen?.(); }
fireError() { this.onerror?.(); }
fireNamed(type: string, data: unknown) {
for (const fn of this.listeners.get(type) ?? []) {
(fn as unknown as (e: { data: string }) => void)({ data: JSON.stringify(data) });
}
}
}
const flush = () => new Promise<void>(r => setTimeout(r, 0));
describe('P1b-SSE client', () => {
let fetchSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
FakeEventSource.instances = [];
vi.stubGlobal('EventSource', FakeEventSource);
fetchSpy = vi.spyOn(globalThis, 'fetch');
localStorage.clear();
});
afterEach(() => {
vi.unstubAllGlobals();
fetchSpy.mockRestore();
vi.useRealTimers();
});
async function connectedAdapter(token = 'tok-A') {
const a = new LocalAdapter(BASE);
fetchSpy.mockImplementation(async (url: unknown) => {
const u = String(url);
if (u.includes('/health')) return jsonRes({ status: 'ok' });
if (u.includes(TOKEN_PATH)) return jsonRes({ token });
throw new Error(`unmocked: ${u}`);
});
await a.connect();
return a;
}
it('attaches ?token= to the stream URL after connect', async () => {
const a = await connectedAdapter('tok-A');
a.subscribeNotifications(() => {});
await flush();
expect(FakeEventSource.instances).toHaveLength(1);
expect(FakeEventSource.instances[0].url).toBe(`${BASE}/api/notifications/stream?token=tok-A`);
});
it('LAZY-OPEN: a subscription mounted DURING connect opens after the token arrives (noop-forever class dead)', async () => {
const a = new LocalAdapter(BASE);
let releaseToken!: (r: Response) => void;
const gate = new Promise<Response>(res => { releaseToken = res; });
fetchSpy.mockImplementation(async (url: unknown) => {
const u = String(url);
if (u.includes('/health')) return jsonRes({ status: 'ok' });
if (u.includes(TOKEN_PATH)) return gate;
throw new Error(`unmocked: ${u}`);
});
const connectP = a.connect();
a.subscribeWaggleDance(() => {}); // pre-settle — old code returned a dead noop here
await flush();
expect(FakeEventSource.instances).toHaveLength(0); // deferred, not opened token-less
releaseToken(jsonRes({ token: 'tok-A' }));
await connectP;
await flush();
expect(FakeEventSource.instances).toHaveLength(1);
expect(FakeEventSource.instances[0].url).toContain('token=tok-A');
});
it('RECONNECT: on stream error, refreshes the token and reopens with the NEW token on backoff', async () => {
vi.useFakeTimers();
const a = await connectedAdapter('tok-A');
a.subscribeNotifications(() => {});
await vi.advanceTimersByTimeAsync(0);
const first = FakeEventSource.instances[0];
expect(first.url).toContain('token=tok-A');
// Sidecar restarted: token rotates server-side.
fetchSpy.mockImplementation(async (url: unknown) => {
const u = String(url);
if (u.includes(TOKEN_PATH)) return jsonRes({ token: 'tok-B' });
return jsonRes({ status: 'ok' });
});
first.fireError();
await vi.advanceTimersByTimeAsync(1100); // first backoff ≈1s
expect(first.closed).toBe(true);
expect(FakeEventSource.instances).toHaveLength(2);
expect(FakeEventSource.instances[1].url).toContain('token=tok-B');
});
it('RECONNECT backoff caps and unsubscribe cancels the loop', async () => {
vi.useFakeTimers();
const a = await connectedAdapter('tok-A');
const unsub = a.subscribeNotifications(() => {});
await vi.advanceTimersByTimeAsync(0);
FakeEventSource.instances[0].fireError();
await vi.advanceTimersByTimeAsync(1100);
expect(FakeEventSource.instances).toHaveLength(2);
FakeEventSource.instances[1].fireError();
unsub(); // cancel mid-backoff
await vi.advanceTimersByTimeAsync(60000);
expect(FakeEventSource.instances).toHaveLength(2); // no further reopens
expect(FakeEventSource.instances[1].closed).toBe(true);
});
it('FAN-OUT: concurrent same-path subscribers share ONE stream; both receive events; last-out closes', async () => {
// Review fix: the old replace-on-resubscribe dedup let a second mount
// (WaggleDance screen) permanently kill the first's stream (AppShell's
// always-mounted badge).
const a = await connectedAdapter('tok-A');
const got1: unknown[] = [];
const got2: unknown[] = [];
const unsub1 = a.subscribeNotifications((n) => got1.push(n));
const unsub2 = a.subscribeNotifications((n) => got2.push(n));
await flush();
expect(FakeEventSource.instances).toHaveLength(1); // shared socket
const es = FakeEventSource.instances[0];
es.onmessage?.({ data: JSON.stringify({ id: '1', title: 'hi' }) } as MessageEvent);
expect(got1).toHaveLength(1);
expect(got2).toHaveLength(1);
unsub1();
expect(es.closed).toBe(false); // second subscriber keeps it alive
es.onmessage?.({ data: JSON.stringify({ id: '2', title: 'again' }) } as MessageEvent);
expect(got1).toHaveLength(1); // unsubscribed callback no longer fires
expect(got2).toHaveLength(2);
unsub2();
expect(es.closed).toBe(true); // last-out closes
// A fresh subscribe after full teardown opens a NEW stream.
a.subscribeNotifications(() => {});
await flush();
expect(FakeEventSource.instances).toHaveLength(2);
});
it('NAMED EVENTS: subscribeEvents/<audit> and subscribeWaggleDance/<signal> receive named payloads, not onmessage', async () => {
// Review fix: the server emits `event: audit` / `event: signal` — an
// onmessage-only listener made both channels payload-dead even with
// working auth.
const a = await connectedAdapter('tok-A');
const audits: unknown[] = [];
const signals: unknown[] = [];
a.subscribeEvents((e) => audits.push(e));
a.subscribeWaggleDance((s) => signals.push(s));
await flush();
const [eventsEs, waggleEs] = FakeEventSource.instances;
eventsEs.fireNamed('audit', { type: 'tool_call' });
waggleEs.fireNamed('signal', { id: 's1' });
expect(audits).toEqual([{ type: 'tool_call' }]);
expect(signals).toEqual([{ id: 's1' }]);
// The named `event: connected` waggle handshake is ignored by spec.
waggleEs.fireNamed('connected', { type: 'connected' });
expect(signals).toHaveLength(1);
});
it('HANDSHAKE FILTER: the unnamed {"type":"connected"} on the notifications stream never reaches the consumer', async () => {
const a = await connectedAdapter('tok-A');
const got: unknown[] = [];
a.subscribeNotifications((n) => got.push(n));
await flush();
const es = FakeEventSource.instances[0];
es.onmessage?.({ data: JSON.stringify({ type: 'connected' }) } as MessageEvent);
expect(got).toHaveLength(0); // junk handshake filtered
es.onmessage?.({ data: JSON.stringify({ id: 'n1', title: 'real' }) } as MessageEvent);
expect(got).toHaveLength(1);
});
it('subagent named-event listener is re-attached on every reopen (configure contract)', async () => {
vi.useFakeTimers();
const a = await connectedAdapter('tok-A');
const events: unknown[] = [];
a.subscribeSubagentStatus((e) => events.push(e));
await vi.advanceTimersByTimeAsync(0);
const first = FakeEventSource.instances[0];
first.fireNamed('subagent_status', { workspaceId: 'w1' });
expect(events).toHaveLength(1);
first.fireError();
await vi.advanceTimersByTimeAsync(1100);
const second = FakeEventSource.instances[1];
second.fireNamed('subagent_status', { workspaceId: 'w1' });
expect(events).toHaveLength(2); // listener survived the reopen
});
it('subagent stream does NOT clobber the notifications stream (no shared-path dedup)', async () => {
const a = await connectedAdapter('tok-A');
a.subscribeNotifications(() => {});
a.subscribeSubagentStatus(() => {});
await flush();
expect(FakeEventSource.instances).toHaveLength(2);
expect(FakeEventSource.instances.every(i => !i.closed)).toBe(true);
});
it('tool output stream closes permanently after exit instead of reconnecting and replaying old output', async () => {
vi.useFakeTimers();
const a = await connectedAdapter('tok-A');
const lines: string[] = [];
let exitCode: number | null | undefined;
a.streamToolOutput(4242, {
onLine: (line) => lines.push(line),
onExit: (code) => { exitCode = code; },
});
await vi.advanceTimersByTimeAsync(0);
const first = FakeEventSource.instances[0];
first.fireNamed('line', { line: 'mock observed output' });
first.fireNamed('exit', { code: 0 });
expect(lines).toEqual(['mock observed output']);
expect(exitCode).toBe(0);
expect(first.closed).toBe(true);
first.fireError();
await vi.advanceTimersByTimeAsync(1100);
expect(FakeEventSource.instances).toHaveLength(1);
});
it('harvest: ready resolves on handshake; close stops the stream', async () => {
const a = await connectedAdapter('tok-A');
const sub = a.subscribeHarvestProgress(() => {});
await flush();
const es = FakeEventSource.instances[0];
expect(es.url).toContain('/api/harvest/progress?token=tok-A');
let readyResolved = false;
void sub.ready.then(() => { readyResolved = true; });
es.fireOpen();
await flush();
expect(readyResolved).toBe(true);
sub.close();
expect(es.closed).toBe(true);
});
it('harvest: ready safety-caps at 5s when the server never answers', async () => {
vi.useFakeTimers();
const a = await connectedAdapter('tok-A');
const sub = a.subscribeHarvestProgress(() => {});
let readyResolved = false;
void sub.ready.then(() => { readyResolved = true; });
await vi.advanceTimersByTimeAsync(5100);
expect(readyResolved).toBe(true);
sub.close();
});
it('no EventSource in the environment → safe noops (unit-test compat)', async () => {
vi.unstubAllGlobals();
const a = new LocalAdapter(BASE);
const unsub = a.subscribeNotifications(() => {});
expect(typeof unsub).toBe('function');
unsub();
const sub = a.subscribeHarvestProgress(() => {});
await expect(sub.ready).resolves.toBeUndefined();
sub.close();
});
});

View File

@@ -0,0 +1,89 @@
/**
* LocalAdapter.startTrial — atomic 15-day trial start wiring.
*
* Pins the contract between Desktop's UpgradeModal `onStartTrial` callback
* + the onboarding-complete handler, and the server's POST
* /api/tier/start-trial route. Guards against the original silent-failure
* pattern where the call site used a non-existent `adapter.updateSettings`
* method behind an `as any` cast (see commit db069a7 for the bug
* post-mortem).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import LocalAdapter from './adapter';
describe('LocalAdapter.startTrial', () => {
let fetchSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
fetchSpy = vi.spyOn(globalThis, 'fetch');
});
afterEach(() => {
fetchSpy.mockRestore();
});
it('POSTs to /api/tier/start-trial and returns the parsed body on 200', async () => {
const serverBody = {
tier: 'TRIAL',
rawTier: 'TRIAL',
trialStartedAt: '2026-05-07T18:00:00.000Z',
trialDaysRemaining: 15,
trialExpired: false,
capabilities: { workspaceLimit: -1, spawnAgents: true },
};
fetchSpy.mockResolvedValue(
new Response(JSON.stringify(serverBody), {
status: 200,
headers: { 'Content-Type': 'application/json' },
}),
);
const adapter = new LocalAdapter('http://test-server:9999');
const result = await adapter.startTrial();
// Wiring: correct URL + method.
expect(fetchSpy).toHaveBeenCalledOnce();
const [url, init] = fetchSpy.mock.calls[0] as [string | URL, RequestInit];
expect(String(url)).toBe('http://test-server:9999/api/tier/start-trial');
expect(init.method).toBe('POST');
// Returns the server body verbatim — Desktop's refreshTier path depends
// on `tier` + `trialDaysRemaining` being present.
expect(result).toEqual(serverBody);
});
it('throws on 409 TRIAL_ALREADY_STARTED so call sites can decide whether to surface', async () => {
fetchSpy.mockResolvedValue(
new Response(JSON.stringify({
error: 'TRIAL_ALREADY_STARTED',
message: 'A trial has already been started for this installation.',
tier: 'TRIAL',
trialStartedAt: '2026-05-01T00:00:00.000Z',
trialDaysRemaining: 9,
trialExpired: false,
}), {
status: 409,
headers: { 'Content-Type': 'application/json' },
}),
);
const adapter = new LocalAdapter('http://test-server:9999');
await expect(adapter.startTrial()).rejects.toThrow(/Start trial failed.*409/);
// The thrown message must surface the server's `message` field so a
// future toast/inline-error UI can show something useful instead of
// the bare HTTP status text.
await expect(adapter.startTrial()).rejects.toThrow(/A trial has already been started/);
});
it('throws on 500 with the server status text when the body is not JSON', async () => {
fetchSpy.mockResolvedValue(
new Response('upstream timeout', {
status: 500,
statusText: 'Internal Server Error',
}),
);
const adapter = new LocalAdapter('http://test-server:9999');
await expect(adapter.startTrial()).rejects.toThrow(/Start trial failed.*500/);
});
});

View File

@@ -0,0 +1,144 @@
// CC Sesija A §2.5 Task A17 — adapter isTauri() branch happy-path integration.
//
// Brief: briefs/2026-04-30-cc-sesija-A-waggle-apps-web-integration.md §2.5 Task A17
//
// Verifies the §2.2 adapter.ts isTauri() branches actually route through the
// Tauri command bindings when running inside the Tauri webview, instead of
// falling back to HTTP fetch. The full Tauri-test-harness e2e (launch app +
// onboarding + recall + save) is deferred to Track G Computer Use validation
// per PM 2026-04-30 — this test covers the JS-side wiring contract.
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
// Mock the @tauri-apps modules BEFORE importing adapter so the import chain
// in adapter.ts → tauri-bindings.ts → @tauri-apps/api picks up the mock.
vi.mock('@tauri-apps/api/core', () => ({
invoke: vi.fn(),
}));
vi.mock('@tauri-apps/api/event', () => ({
listen: vi.fn(async () => () => {/* unlisten */}),
}));
import { invoke } from '@tauri-apps/api/core';
import { adapter } from './adapter';
const mockedInvoke = vi.mocked(invoke);
describe('adapter isTauri() branch routing', () => {
beforeEach(() => {
mockedInvoke.mockReset();
// Activate Tauri detection — adapter's isTauri() reads from window.
(window as unknown as { __TAURI_INTERNALS__: unknown }).__TAURI_INTERNALS__ = {};
});
afterEach(() => {
delete (window as unknown as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__;
});
it('searchMemory routes to recall_memory Tauri command (not HTTP fetch)', async () => {
mockedInvoke.mockResolvedValue({
results: [
{ id: 'f1', content: 'hit-1', frameType: 'I', importance: 'normal', timestamp: '2026-04-30' },
],
count: 1,
});
const result = await adapter.searchMemory('hello world', 'all');
expect(mockedInvoke).toHaveBeenCalledWith('recall_memory', {
query: 'hello world',
scope: 'all',
});
expect(result.length).toBe(1);
expect(result[0].content).toBe('hit-1');
});
it('addMemoryFrame routes to save_memory Tauri command with importance string', async () => {
mockedInvoke.mockResolvedValue({
id: 'frame-new',
content: 'saved',
frameType: 'I',
importance: 'high',
timestamp: '2026-04-30',
});
await adapter.addMemoryFrame({
type: 'insight',
title: 'test',
content: 'saved',
importance: 3, // numeric → 'high' via IMPORTANCE_NUM_TO_STRING
timestamp: '2026-04-30',
workspaceId: 'ws-1',
metadata: { source: 'user_stated' },
});
expect(mockedInvoke).toHaveBeenCalledWith('save_memory', {
content: 'saved',
workspaceId: 'ws-1',
importance: 'high',
source: 'user_stated',
});
});
it('getKnowledgeGraph routes to search_entities Tauri command', async () => {
mockedInvoke.mockResolvedValue({
nodes: [{ id: 'n1', label: 'Entity', type: 'person' }],
edges: [{ source: 'n1', target: 'n2', type: 'knows' }],
});
const result = await adapter.getKnowledgeGraph('ws-1', 'personal');
expect(mockedInvoke).toHaveBeenCalledWith('search_entities', {
scope: 'personal',
});
expect(result.nodes.length).toBe(1);
expect(result.edges.length).toBe(1);
});
it('getKnowledgeGraph defaults to workspace-scoped when scope omitted', async () => {
mockedInvoke.mockResolvedValue({ nodes: [], edges: [] });
await adapter.getKnowledgeGraph('ws-2');
expect(mockedInvoke).toHaveBeenCalledWith('search_entities', {
workspaceId: 'ws-2',
});
});
it('getIdentity routes to get_identity Tauri command + returns shape', async () => {
mockedInvoke.mockResolvedValue({
configured: true,
name: 'Marko',
role: 'Founder',
department: 'Egzakta',
});
const id = await adapter.getIdentity();
expect(mockedInvoke).toHaveBeenCalledWith('get_identity');
expect(id.configured).toBe(true);
expect(id.name).toBe('Marko');
});
});
describe('adapter HTTP fallback when not in Tauri', () => {
beforeEach(() => {
mockedInvoke.mockReset();
delete (window as unknown as { __TAURI_INTERNALS__?: unknown }).__TAURI_INTERNALS__;
// Stub fetch so HTTP calls return synthetic data without network.
vi.spyOn(global, 'fetch').mockResolvedValue(
new Response(JSON.stringify({ results: [] }), { status: 200 }),
);
});
afterEach(() => {
vi.restoreAllMocks();
});
it('searchMemory uses fetch (HTTP) when isTauri() is false', async () => {
await adapter.searchMemory('q', 'all');
expect(mockedInvoke).not.toHaveBeenCalled();
expect(global.fetch).toHaveBeenCalled();
});
});

3658
apps/web/src/lib/adapter.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,161 @@
/**
* Phase 3B (S09) — Agent Center display vocabulary.
* - §14.5: every AgentRunState renders a badge label + tone (exhaustive).
* - C22: tab filtering incl. the archive split.
* - C27: KPI math keeps success-rate, has no "hours saved".
* - C23: the workspace_ambiguous error shape detector.
*/
import { describe, it, expect } from 'vitest';
import { AGENT_RUN_STATES } from '@waggle/shared';
import type { Agent } from '@/lib/types';
import {
AGENT_STATE_META,
AGENT_CENTER_TABS,
filterAgentsByTab,
formatSuccessRate,
formatRelativeTime,
agentKpis,
workspaceAmbiguityIds,
shouldSuggestAgents,
SUGGESTED_PERSONA_IDS,
type AgentCenterTab,
} from './agent-center-display';
function makeAgent(over: Partial<Agent> = {}): Agent {
return {
id: 'a1', name: 'Scout', goal: 'Research things', type: 'personal',
model: 'auto', autonomyLevel: 'guided', memoryScopes: ['personal'],
status: 'idle', createdAt: '2026-06-01T00:00:00Z', updatedAt: '2026-06-01T00:00:00Z',
...over,
};
}
describe('AGENT_STATE_META — §14.5 full vocabulary', () => {
it('maps every shared AgentRunState to a non-empty label and tone', () => {
for (const state of AGENT_RUN_STATES) {
const meta = AGENT_STATE_META[state];
expect(meta, `missing meta for ${state}`).toBeDefined();
expect(meta.label.length).toBeGreaterThan(0);
expect(['healthy', 'attention', 'risk', 'info', 'neutral']).toContain(meta.tone);
}
});
it('uses human labels for the multi-word states', () => {
expect(AGENT_STATE_META.waiting_for_approval.label).toBe('Waiting for approval');
expect(AGENT_STATE_META.failed.tone).toBe('risk');
// Wave-S Lane C: running reads as an active-good state (healthy sage), not
// the intelligence/info violet.
expect(AGENT_STATE_META.running.tone).toBe('healthy');
});
});
describe('filterAgentsByTab — C22', () => {
const agents = [
makeAgent({ id: 'p', type: 'personal' }),
makeAgent({ id: 'w', type: 'workspace' }),
makeAgent({ id: 't', type: 'team' }),
makeAgent({ id: 'auto', type: 'autonomous' }),
makeAgent({ id: 'arch', type: 'personal', status: 'archived' }),
];
it('declares exactly the six C22 tabs (Templates is NOT a tab)', () => {
expect(AGENT_CENTER_TABS.map(t => t.id)).toEqual(['all', 'personal', 'workspace', 'team', 'autonomous', 'archive']);
expect(AGENT_CENTER_TABS.some(t => t.label.toLowerCase() === 'templates')).toBe(false);
});
it('"all" shows live agents and hides archived ones', () => {
expect(filterAgentsByTab(agents, 'all').map(a => a.id)).toEqual(['p', 'w', 't', 'auto']);
});
it('type tabs filter by AgentType (still excluding archived)', () => {
expect(filterAgentsByTab(agents, 'workspace').map(a => a.id)).toEqual(['w']);
expect(filterAgentsByTab(agents, 'personal').map(a => a.id)).toEqual(['p']); // arch is personal but archived
});
it('"archive" shows only archived agents', () => {
expect(filterAgentsByTab(agents, 'archive').map(a => a.id)).toEqual(['arch']);
});
});
describe('formatSuccessRate / formatRelativeTime', () => {
it('renders 0-1 rates as percentages and absent rates as a dash', () => {
expect(formatSuccessRate(0.834)).toBe('83%');
expect(formatSuccessRate(0)).toBe('0%');
expect(formatSuccessRate(1)).toBe('100%');
expect(formatSuccessRate(undefined)).toBe('—');
});
it('renders compact relative times against an injected now', () => {
const now = Date.parse('2026-06-10T12:00:00Z');
expect(formatRelativeTime(undefined, now)).toBe('never');
expect(formatRelativeTime('2026-06-10T11:59:30Z', now)).toBe('just now');
expect(formatRelativeTime('2026-06-10T11:30:00Z', now)).toBe('30m ago');
expect(formatRelativeTime('2026-06-10T06:00:00Z', now)).toBe('6h ago');
expect(formatRelativeTime('2026-06-07T12:00:00Z', now)).toBe('3d ago');
});
});
describe('agentKpis — C27', () => {
it('counts live agents + running and averages only the rated ones', () => {
const kpis = agentKpis([
makeAgent({ id: '1', status: 'running', successRate: 0.5 }),
makeAgent({ id: '2', status: 'idle', successRate: 1 }),
makeAgent({ id: '3', status: 'idle' }), // unrated — excluded from the mean
makeAgent({ id: '4', status: 'archived', successRate: 0 }), // archived — excluded entirely
]);
expect(kpis.total).toBe(3);
expect(kpis.running).toBe(1);
expect(kpis.avgSuccessRate).toBeCloseTo(0.75);
});
it('reports null (not 0) when no agent has a derived rate', () => {
expect(agentKpis([makeAgent()]).avgSuccessRate).toBeNull();
});
it('exposes no "hours saved" figure (C27 — no data source)', () => {
expect(Object.keys(agentKpis([]))).toEqual(['total', 'running', 'avgSuccessRate']);
});
});
describe('shouldSuggestAgents — F-W5C sparse state', () => {
const base = { loading: false, error: false, tab: 'all' as AgentCenterTab, query: '', agentCount: 0 };
it('shows on the unfiltered "all" tab with a near-empty fleet (0-2 agents)', () => {
expect(shouldSuggestAgents({ ...base, agentCount: 0 })).toBe(true);
expect(shouldSuggestAgents({ ...base, agentCount: 2 })).toBe(true);
});
it('hides once the fleet grows past two', () => {
expect(shouldSuggestAgents({ ...base, agentCount: 3 })).toBe(false);
});
it('hides while loading, errored, searching, or on a non-"all" tab', () => {
expect(shouldSuggestAgents({ ...base, loading: true })).toBe(false);
expect(shouldSuggestAgents({ ...base, error: true })).toBe(false);
expect(shouldSuggestAgents({ ...base, query: 'scout' })).toBe(false);
expect(shouldSuggestAgents({ ...base, query: ' ' })).toBe(true); // whitespace-only = no search
expect(shouldSuggestAgents({ ...base, tab: 'workspace' })).toBe(false);
expect(shouldSuggestAgents({ ...base, tab: 'archive' })).toBe(false);
});
it('curates 6 unique persona ids (round-7 fix 3a)', () => {
expect(SUGGESTED_PERSONA_IDS.length).toBe(6);
expect(new Set(SUGGESTED_PERSONA_IDS).size).toBe(SUGGESTED_PERSONA_IDS.length);
});
});
describe('workspaceAmbiguityIds — C23 error shape', () => {
it('extracts workspaceIds from the 400 workspace_ambiguous body', () => {
const err = Object.assign(new Error('runAgent failed (400): workspace_ambiguous'), {
status: 400,
body: { error: 'workspace_ambiguous', workspaceIds: ['ws-1', 'ws-2'] },
});
expect(workspaceAmbiguityIds(err)).toEqual(['ws-1', 'ws-2']);
});
it('returns null for other errors (different status / different body)', () => {
expect(workspaceAmbiguityIds(new Error('boom'))).toBeNull();
expect(workspaceAmbiguityIds(Object.assign(new Error('x'), { status: 500, body: { error: 'workspace_ambiguous' } }))).toBeNull();
expect(workspaceAmbiguityIds(Object.assign(new Error('x'), { status: 400, body: { error: 'bad_request' } }))).toBeNull();
});
});

View File

@@ -0,0 +1,126 @@
/**
* Agent Center display vocabulary (UX-Refactor Phase 3B, S09).
*
* Pure functions only — tested in lib/agent-center-display.test.ts.
* - PRD §14.5: ALL eight AgentRunState values map to a StatusBadge tone +
* human label (exhaustive Record — adding a state without a badge entry
* is a compile error).
* - C22: category tabs = All / Personal / Workspace / Team / Autonomous /
* Archive (Templates is a side affordance, NOT a tab).
* - C27: KPI row keeps the success-rate tile and total/running counts;
* "hours saved" is deliberately absent (no data source).
*/
import type { AgentRunState, AgentType } from '@waggle/shared';
import type { Agent } from '@/lib/types';
import type { StatusTone } from '@/components/ui/status-badge';
import { DATE_LOCALE } from '@/lib/date-locale';
export const AGENT_STATE_META: Record<AgentRunState, { label: string; tone: StatusTone }> = {
draft: { label: 'Draft', tone: 'neutral' },
idle: { label: 'Idle', tone: 'neutral' },
running: { label: 'Running', tone: 'healthy' },
paused: { label: 'Paused', tone: 'attention' },
failed: { label: 'Failed', tone: 'risk' },
waiting_for_approval: { label: 'Waiting for approval', tone: 'attention' },
completed: { label: 'Completed', tone: 'healthy' },
archived: { label: 'Archived', tone: 'neutral' },
};
/** C22 tab vocabulary: 'all' + the four AgentType categories + 'archive'. */
export type AgentCenterTab = 'all' | AgentType | 'archive';
export const AGENT_CENTER_TABS: ReadonlyArray<{ id: AgentCenterTab; label: string }> = [
{ id: 'all', label: 'All' },
{ id: 'personal', label: 'Personal' },
{ id: 'workspace', label: 'Workspace' },
{ id: 'team', label: 'Team' },
{ id: 'autonomous', label: 'Autonomous' },
{ id: 'archive', label: 'Archive' },
];
/**
* C22 filtering: Archive shows ONLY archived agents; every other tab hides
* them ('all' = every live agent; type tabs = live agents of that type).
*/
export function filterAgentsByTab(agents: Agent[], tab: AgentCenterTab): Agent[] {
if (tab === 'archive') return agents.filter((a) => a.status === 'archived');
const live = agents.filter((a) => a.status !== 'archived');
if (tab === 'all') return live;
return live.filter((a) => a.type === tab);
}
/** 0-1 derived rate → display percent; '—' when there are no finalized runs. */
export function formatSuccessRate(rate?: number): string {
if (typeof rate !== 'number' || Number.isNaN(rate)) return '—';
return `${Math.round(rate * 100)}%`;
}
/** Compact relative time for lastRunAt ('never' when absent). */
export function formatRelativeTime(iso?: string, now: number = Date.now()): string {
if (!iso) return 'never';
const t = Date.parse(iso);
if (Number.isNaN(t)) return 'never';
const diff = now - t;
if (diff < 60_000) return 'just now';
if (diff < 3_600_000) return `${Math.floor(diff / 60_000)}m ago`;
if (diff < 86_400_000) return `${Math.floor(diff / 3_600_000)}h ago`;
if (diff < 30 * 86_400_000) return `${Math.floor(diff / 86_400_000)}d ago`;
return new Date(t).toLocaleDateString(DATE_LOCALE);
}
/** KPI row inputs (C27: success-rate yes, hours-saved no). Archived agents
* are excluded — they are not part of the working fleet. */
export function agentKpis(agents: Agent[]): {
total: number;
running: number;
/** Mean of the agents that HAVE a derived rate; null when none do. */
avgSuccessRate: number | null;
} {
const live = agents.filter((a) => a.status !== 'archived');
const rated = live.filter((a) => typeof a.successRate === 'number');
return {
total: live.length,
running: live.filter((a) => a.status === 'running').length,
avgSuccessRate: rated.length > 0
? rated.reduce((s, a) => s + (a.successRate ?? 0), 0) / rated.length
: null,
};
}
/**
* F-W5C sparse-state suggestions: the curated persona ids offered as
* click-to-create cards when the fleet is near-empty. Ids are the canonical
* persona ids (packages/agent/src/persona-data.ts, mirrored in lib/personas).
*/
export const SUGGESTED_PERSONA_IDS: readonly string[] = [
'researcher', 'writer', 'analyst', 'planner', 'coder', 'consultant',
];
/**
* Whether to surface the "Suggested agents" block: only on the unfiltered
* 'all' tab with no active search and a near-empty fleet (≤2 agents, archived
* included). Never renders while loading/errored or during any filter/search,
* and disappears once the fleet grows past two.
*/
export function shouldSuggestAgents(params: {
loading: boolean;
error: boolean;
tab: AgentCenterTab;
query: string;
agentCount: number;
}): boolean {
return !params.loading
&& !params.error
&& params.tab === 'all'
&& params.query.trim() === ''
&& params.agentCount <= 2;
}
/** C23: shape of the runAgent ambiguity error the FE branches on. */
export function workspaceAmbiguityIds(err: unknown): string[] | null {
const e = err as { status?: number; body?: { error?: string; workspaceIds?: unknown } } | null;
if (!e || e.status !== 400) return null;
if (e.body?.error !== 'workspace_ambiguous') return null;
const ids = e.body.workspaceIds;
return Array.isArray(ids) ? ids.map(String) : [];
}

View File

@@ -0,0 +1,22 @@
import { describe, it, expect } from 'vitest';
import { installTargetFor, type AgentSearchSuggestion } from './agent-search';
const sug = (install: AgentSearchSuggestion['install']): AgentSearchSuggestion => ({
name: 'Thing', type: 'x', availability: 'installable', description: '', matchReason: 'why', matchScore: 0.5, install,
});
describe('installTargetFor', () => {
it('builds a package target from a store-mode suggestion', () => {
expect(installTargetFor(sug({ mode: 'store', extensionId: 'pkg:7', type: 'skill', kind: 'package', packageId: 7 })))
.toEqual({ id: 'pkg:7', type: 'skill', kind: 'package', name: 'Thing', packageId: 7 });
});
it('builds a connector target (no packageId)', () => {
expect(installTargetFor(sug({ mode: 'store', extensionId: 'connector:slack', type: 'connector', kind: 'federated', authType: 'bearer' })))
.toEqual({ id: 'connector:slack', type: 'connector', kind: 'federated', name: 'Thing' });
});
it('returns null for non-store modes', () => {
expect(installTargetFor(sug({ mode: 'starter-pack', name: 'pdf' }))).toBeNull();
expect(installTargetFor(sug({ mode: 'open-in', appId: 'connectors' }))).toBeNull();
expect(installTargetFor(sug({ mode: 'active' }))).toBeNull();
});
});

View File

@@ -0,0 +1,59 @@
/**
* agent-search — FE types + helpers for the PR4 agent-pick suggestion box
* (screen 09's centered ask bar). Mirrors the POST /api/marketplace/agent-search
* response: each suggestion carries a deterministic "why" (matchReason) and an
* install descriptor telling the FE how to act (store install / starter-pack /
* Hub handoff / already-active).
*/
import type { InstallTarget } from './install-store';
export interface AgentSearchInstall {
mode: 'store' | 'starter-pack' | 'open-in' | 'active';
extensionId?: string;
type?: 'skill' | 'mcp' | 'connector';
kind?: 'package' | 'federated';
packageId?: number;
authType?: string;
/** starter-pack mode — the skill id to install. */
name?: string;
/** open-in mode — the app to deep-link to (e.g. an OAuth connector → Hub). */
appId?: string;
}
export interface AgentSearchSuggestion {
name: string;
type: string; // CapabilitySourceType: native | skill | marketplace | connector | …
availability: string;
description: string;
/** The deterministic "why" the engine matched this. */
matchReason: string;
matchScore: number;
install: AgentSearchInstall;
}
export interface AgentSearchResponse {
need: string;
gapDetected: boolean;
alreadyHandled: boolean;
recommendation: AgentSearchSuggestion | null;
candidates: AgentSearchSuggestion[];
picks: {
connector?: AgentSearchSuggestion;
skill?: AgentSearchSuggestion;
tool?: AgentSearchSuggestion;
};
}
/** Build an InstallTarget from a store-mode suggestion (null if not directly
* store-installable — connectors hand off to the Hub, starters to installPack). */
export function installTargetFor(s: AgentSearchSuggestion): InstallTarget | null {
const i = s.install;
if (i.mode !== 'store' || !i.extensionId || !i.type || !i.kind) return null;
return {
id: i.extensionId,
type: i.type,
kind: i.kind,
name: s.name,
...(i.packageId != null ? { packageId: i.packageId } : {}),
};
}

View File

@@ -0,0 +1,37 @@
/**
* Pending deep-link handoff for the `waggle:open-app` channel (Journey 16 /
* M-09 class). The event is dispatched synchronously, but a closed target app
* only mounts on the NEXT React render — its own listener registers after the
* event is gone, so any `tab`/target payload was silently dropped on cold
* open. Desktop's always-mounted handler stashes the intent here; the target
* app consumes it once in a mount effect (and clears it when it handles the
* live event instead, so a later remount never replays a stale intent).
*/
export interface AppDeepLink {
appId: string;
/** Target tab inside the app (validated by the consumer). */
tab?: string;
/** Journey 16: the failing automation to preselect on the Logs tab. */
automationId?: string;
/** J08: a list-filter to preselect in the target app (validated by the
* consumer — e.g. Memory Center seeds its status filter from this). */
filter?: string;
/** C2 (UX-Northstar): a file path to preselect/preview — Files app
* navigates to its directory and opens the preview (chat artifact cards). */
path?: string;
}
const pending = new Map<string, AppDeepLink>();
/** Stash (or overwrite) the pending intent for an app. */
export function stashDeepLink(detail: AppDeepLink): void {
if (!detail.appId) return;
pending.set(detail.appId, detail);
}
/** Read-and-clear the pending intent for an app (null when none). */
export function consumeDeepLink(appId: string): AppDeepLink | null {
const detail = pending.get(appId) ?? null;
pending.delete(appId);
return detail;
}

View File

@@ -0,0 +1,51 @@
/**
* F2 — wizard first-task auto-send gate regression.
*
* Pins the race guard (session + history must both be ready) and the "never
* override an edited composer" / "once only" rules.
*/
import { describe, it, expect } from 'vitest';
import { shouldAutoSendFirstTask, type AutoSendFirstTaskInput } from './auto-send-first-task';
function base(overrides: Partial<AutoSendFirstTaskInput> = {}): AutoSendFirstTaskInput {
return {
autoSendInitial: true,
alreadySent: false,
initialMessage: 'Draft the launch brief',
activeSessionId: 'sess-1',
historyLoaded: true,
inputUnchanged: true,
...overrides,
};
}
describe('shouldAutoSendFirstTask', () => {
it('sends when seeded, ready, and untouched', () => {
expect(shouldAutoSendFirstTask(base())).toBe(true);
});
it('does not send when autoSendInitial is false', () => {
expect(shouldAutoSendFirstTask(base({ autoSendInitial: false }))).toBe(false);
});
it('does not send twice (alreadySent)', () => {
expect(shouldAutoSendFirstTask(base({ alreadySent: true }))).toBe(false);
});
it('does not send an empty/whitespace message', () => {
expect(shouldAutoSendFirstTask(base({ initialMessage: ' ' }))).toBe(false);
expect(shouldAutoSendFirstTask(base({ initialMessage: undefined }))).toBe(false);
});
it('waits for the session to resolve', () => {
expect(shouldAutoSendFirstTask(base({ activeSessionId: null }))).toBe(false);
});
it('waits for history to load (the clobber race)', () => {
expect(shouldAutoSendFirstTask(base({ historyLoaded: false }))).toBe(false);
});
it('never overrides an edited composer', () => {
expect(shouldAutoSendFirstTask(base({ inputUnchanged: false }))).toBe(false);
});
});

View File

@@ -0,0 +1,38 @@
/**
* F2 — pure gate for the wizard first-task auto-send.
*
* The imperative bits (the once-only ref, the actual dispatch, clearing the
* composer) live in ChatApp's effect; this captures the pure decision so it can
* be unit-tested without rendering the whole chat surface.
*
* THE RACE this guards (see useChat history effect): the active session id
* resolves async, and when it lands useChat REPLACES `messages` with fetched
* history. An auto-send fired before that replace has its optimistic turn
* clobbered. So we require BOTH a resolved session AND a completed history
* fetch before sending.
*/
export interface AutoSendFirstTaskInput {
/** Seed asked for an auto-send (wizard "Let's go"). */
autoSendInitial: boolean;
/** The one-shot has already fired this mount. */
alreadySent: boolean;
/** The seeded first message (prefilled into the composer). */
initialMessage: string | undefined;
/** Resolved chat session id; null/undefined until useSessions lands. */
activeSessionId: string | null | undefined;
/** A real session's history fetch has completed. */
historyLoaded: boolean;
/** The composer still holds the untouched seed (user hasn't edited it). */
inputUnchanged: boolean;
}
export function shouldAutoSendFirstTask(i: AutoSendFirstTaskInput): boolean {
if (!i.autoSendInitial || i.alreadySent) return false;
const text = i.initialMessage?.trim();
if (!text) return false;
// Wait out the session-land + history-refetch race.
if (!i.activeSessionId || !i.historyLoaded) return false;
// User already edited the prefilled text — never override them.
if (!i.inputUnchanged) return false;
return true;
}

View File

@@ -0,0 +1,145 @@
/**
* Phase 3B (S11) — Automation Center display vocabulary.
* - §14.6: the FULL automation state vocabulary renders a label + tone.
* - Derived status from row + latest log + in-flight flag.
* - C27: success-rate math from execution logs.
* - C24: trigger description (schedule | manual only).
*/
import { describe, it, expect } from 'vitest';
import type { AutomationLog } from '@/lib/types';
import type { Automation } from '@waggle/shared';
import {
AUTOMATION_STATE_META,
type AutomationViewStatus,
deriveAutomationStatus,
successRateFromLogs,
formatRatePercent,
describeTrigger,
workspaceLabel,
groupAutomationsByWorkspace,
describeActionTarget,
} from './automation-display';
const auto = (id: string, workspaceId: string): Automation => ({
id, name: `A${id}`, triggerType: 'schedule', schedule: '0 9 * * *',
actions: [], workspaceId, status: 'active',
});
const ALL_STATES: AutomationViewStatus[] = [
'draft', 'scheduled', 'running', 'success', 'failed', 'paused', 'awaiting_approval', 'disabled',
];
function log(success: boolean): AutomationLog {
return { id: 1, executedAt: '2026-06-10T01:00:00Z', durationMs: 1200, success, resultSummary: success ? 'ok' : null, error: success ? null : 'boom' };
}
describe('workspaceLabel', () => {
const ws = [{ id: 'w1', name: 'Acme Sales' }, { id: 'w2', name: 'Legal' }];
it('maps the cross-workspace sentinels to "All workspaces"', () => {
expect(workspaceLabel('*', ws)).toBe('All workspaces');
expect(workspaceLabel('global', ws)).toBe('All workspaces');
expect(workspaceLabel(undefined, ws)).toBe('All workspaces');
expect(workspaceLabel('', ws)).toBe('All workspaces');
});
it('resolves a known id to its name and falls back to the raw id', () => {
expect(workspaceLabel('w1', ws)).toBe('Acme Sales');
expect(workspaceLabel('w9', ws)).toBe('w9');
});
});
describe('groupAutomationsByWorkspace', () => {
const labelFor = (id: string | undefined) =>
workspaceLabel(id, [{ id: 'w1', name: 'Acme' }, { id: 'w2', name: 'Legal' }]);
it('returns [] for no rows', () => {
expect(groupAutomationsByWorkspace([], labelFor)).toEqual([]);
});
it('partitions by workspace with the cross-workspace group first', () => {
const groups = groupAutomationsByWorkspace(
[auto('1', 'w2'), auto('2', '*'), auto('3', 'w1'), auto('4', 'w2')],
labelFor,
);
expect(groups.map(g => g.key)).toEqual(['*', 'w1', 'w2']);
expect(groups[0].label).toBe('All workspaces');
expect(groups.find(g => g.key === 'w2')?.automations).toHaveLength(2);
});
it('treats a blank workspaceId as the cross-workspace group', () => {
const groups = groupAutomationsByWorkspace([auto('1', '')], labelFor);
expect(groups).toHaveLength(1);
expect(groups[0].key).toBe('*');
});
});
describe('describeActionTarget (held-action card — shows the REAL args, not the maker summary)', () => {
it('shows the email recipient for send_email (bare + connector alias)', () => {
expect(describeActionTarget('send_email', { to: 'a@b.c', subject: 'Hi' })).toBe('To: a@b.c — Hi');
expect(describeActionTarget('connector_gmail_send_email', { to: 'a@b.c' })).toBe('To: a@b.c');
});
it('shows the path for file tools, and falls back to keys for connector writes', () => {
expect(describeActionTarget('write_file', { path: '/tmp/x', content: '…' })).toBe('/tmp/x');
expect(describeActionTarget('connector_x_create_record', { name: 'Acme', stage: 'lead' })).toContain('name: Acme');
});
});
describe('AUTOMATION_STATE_META — §14.6 full vocabulary', () => {
it('maps every state to a non-empty label and tone', () => {
for (const s of ALL_STATES) {
const meta = AUTOMATION_STATE_META[s];
expect(meta, `missing meta for ${s}`).toBeDefined();
expect(meta.label.length).toBeGreaterThan(0);
expect(['healthy', 'attention', 'risk', 'info', 'neutral']).toContain(meta.tone);
}
expect(AUTOMATION_STATE_META.awaiting_approval.label).toBe('Awaiting approval');
expect(AUTOMATION_STATE_META.failed.tone).toBe('risk');
});
});
describe('deriveAutomationStatus', () => {
it('an enabled schedule is Scheduled', () => {
expect(deriveAutomationStatus({ status: 'active' })).toBe('scheduled');
});
it('a disabled automation is Paused', () => {
expect(deriveAutomationStatus({ status: 'paused' })).toBe('paused');
});
it('a failing latest run surfaces as Failed (overrides enabled)', () => {
expect(deriveAutomationStatus({ status: 'active' }, log(false))).toBe('failed');
});
it('a successful latest run keeps the schedule state', () => {
expect(deriveAutomationStatus({ status: 'active' }, log(true))).toBe('scheduled');
});
it('server-marked failed/running pass through even without logs', () => {
expect(deriveAutomationStatus({ status: 'failed' }, null)).toBe('failed');
expect(deriveAutomationStatus({ status: 'running' }, null)).toBe('running');
});
it('an in-flight Run-now wins over everything', () => {
expect(deriveAutomationStatus({ status: 'paused' }, log(false), true)).toBe('running');
});
});
describe('successRateFromLogs — C27 math', () => {
it('returns the success fraction over the loaded rows', () => {
expect(successRateFromLogs([log(true), log(true), log(false), log(true)])).toBeCloseTo(0.75);
expect(successRateFromLogs([log(false)])).toBe(0);
});
it('returns null (rendered as a dash) when no runs are recorded', () => {
expect(successRateFromLogs([])).toBeNull();
expect(formatRatePercent(null)).toBe('—');
expect(formatRatePercent(0.5)).toBe('50%');
});
});
describe('describeTrigger — C24 (schedule-only v1 + manual)', () => {
it('humanises a preset cron schedule', () => {
expect(describeTrigger({ triggerType: 'schedule', schedule: '0 9 * * *' })).toBe('Every day at 9:00 AM');
});
it('labels manual automations as Run-now-only', () => {
expect(describeTrigger({ triggerType: 'manual', schedule: '0 0 1 1 *' })).toContain('Manual');
expect(describeTrigger({ triggerType: 'manual', schedule: '0 0 1 1 *' })).toContain('Run now');
});
});

View File

@@ -0,0 +1,142 @@
/**
* Automation Center display vocabulary (UX-Refactor Phase 3B, S11).
*
* Pure functions only — tested in lib/automation-display.test.ts.
* - PRD §14.6: the FULL automation state vocabulary maps to a StatusBadge
* tone + label (exhaustive Record). At runtime only the states derivable
* from the cron surface appear (see deriveAutomationStatus); the others
* ('draft', 'awaiting_approval', …) are reachable from the Builder/test
* flows and stay in the map so every state renders consistently.
* - C27: success-rate derives from cron_execution_history log rows,
* client-side. No "hours saved" (no data source).
* - C24/C25: trigger description is schedule-only v1 + manual; condition
* is advisory text.
*/
import type { Automation } from '@waggle/shared';
import type { AutomationLog } from '@/lib/types';
import type { StatusTone } from '@/components/ui/status-badge';
import { describeCronExpr } from '@/lib/cron-presets';
/** PRD §14.6 vocabulary (FE-derived — never stored). */
export type AutomationViewStatus =
| 'draft' | 'scheduled' | 'running' | 'success' | 'failed'
| 'paused' | 'awaiting_approval' | 'disabled';
export const AUTOMATION_STATE_META: Record<AutomationViewStatus, { label: string; tone: StatusTone }> = {
draft: { label: 'Draft', tone: 'neutral' },
scheduled: { label: 'Scheduled', tone: 'info' },
running: { label: 'Running', tone: 'info' },
success: { label: 'Success', tone: 'healthy' },
failed: { label: 'Failed', tone: 'risk' },
paused: { label: 'Paused', tone: 'attention' },
awaiting_approval: { label: 'Awaiting approval', tone: 'attention' },
disabled: { label: 'Disabled', tone: 'neutral' },
};
/**
* Derive the §14.6 badge state from what the cron surface exposes: the row's
* server status + the latest execution log when loaded + a local in-flight
* "Run now" flag. Precedence: local in-flight run > failing latest log >
* server-marked 'failed'/'running' (kept even when the log fetch failed) >
* enabled ('active') → 'scheduled' > everything else → 'paused'.
* Manual-trigger automations are stored disabled, so they read 'paused' —
* callers pair that with the 'Manual' trigger chip.
*/
export function deriveAutomationStatus(
a: Pick<Automation, 'status'>,
lastLog?: AutomationLog | null,
runningNow?: boolean,
): AutomationViewStatus {
if (runningNow) return 'running';
if (lastLog && !lastLog.success) return 'failed';
if (a.status === 'failed') return 'failed';
if (a.status === 'running') return 'running';
if (a.status === 'active') return 'scheduled';
return 'paused';
}
/** C27 math: fraction of successful runs over the loaded log rows. */
export function successRateFromLogs(logs: AutomationLog[]): number | null {
if (logs.length === 0) return null;
return logs.filter((l) => l.success).length / logs.length;
}
export function formatRatePercent(rate: number | null): string {
if (rate === null) return '—';
return `${Math.round(rate * 100)}%`;
}
/** C24 trigger vocabulary: schedule (cron, humanised) or manual. */
export function describeTrigger(a: Pick<Automation, 'triggerType' | 'schedule'>): string {
if (a.triggerType === 'manual') return 'Manual — runs only via "Run now"';
return describeCronExpr(a.schedule ?? '');
}
/**
* Human label for the workspace an automation runs in. The sentinel ids
* ('*'/'global'/empty) mean cross-workspace → "All workspaces"; a known id
* resolves to its name; an unknown id falls back to the raw id (never blank).
*/
export function workspaceLabel(
id: string | undefined,
workspaces: ReadonlyArray<{ id: string; name: string }>,
): string {
if (!id || id === '*' || id === 'global') return 'All workspaces';
return workspaces.find(w => w.id === id)?.name ?? id;
}
export interface AutomationGroup {
key: string;
label: string;
automations: Automation[];
}
/**
* Describe the REAL target of a proposed action from its args — never the
* maker's self-authored summary (which is untrusted and may not match the
* args). This is what a human must see before approving a side-effecting action
* (e.g. the actual send_email recipient, not "send a follow-up").
*/
export function describeActionTarget(toolName: string, input: Record<string, unknown>): string {
const str = (v: unknown) => (v == null ? '' : String(v));
if (toolName === 'send_email' || /_send_email$/.test(toolName)) {
const to = str(input.to ?? input.recipient ?? input.toEmail);
const subject = str(input.subject);
if (to) return `To: ${to}${subject ? ` — ${subject}` : ''}`;
}
const path = input.path ?? input.file_path ?? input.target_workspace_id;
if (path) return str(path);
if (input.command) return str(input.command).slice(0, 80);
if (input.query) return str(input.query).slice(0, 80);
const keys = Object.keys(input).slice(0, 3);
if (keys.length) return keys.map(k => `${k}: ${str(input[k]).slice(0, 40)}`).join(' · ');
return toolName;
}
/**
* Partition automations by the workspace they run in, so the Center can show
* "which workspaces" at a glance. The cross-workspace ('*') group sorts first,
* the rest alphabetically by label. Empty input → []. Preserves input order
* within each group.
*/
export function groupAutomationsByWorkspace(
rows: Automation[],
labelFor: (id: string | undefined) => string,
): AutomationGroup[] {
if (rows.length === 0) return [];
const byKey = new Map<string, AutomationGroup>();
for (const a of rows) {
const key = a.workspaceId || '*';
let group = byKey.get(key);
if (!group) {
group = { key, label: labelFor(key), automations: [] };
byKey.set(key, group);
}
group.automations.push(a);
}
return [...byKey.values()].sort((x, y) => {
if (x.key === '*' && y.key !== '*') return -1;
if (y.key === '*' && x.key !== '*') return 1;
return x.label.localeCompare(y.label);
});
}

View File

@@ -0,0 +1,39 @@
/**
* F18 — confirm-gate for the "Never ask" (yolo) approval level.
*
* Pins that the confirmation fires ONLY on the transition into `yolo`, and
* never for the safe levels or a re-select of the already-active level.
*/
import { describe, it, expect } from 'vitest';
import { requiresYoloConfirm, type ApprovalLevel } from './autonomy-confirm';
const LEVELS: ApprovalLevel[] = ['normal', 'trusted', 'yolo'];
describe('requiresYoloConfirm', () => {
it('gates the transition into yolo from a safer level', () => {
expect(requiresYoloConfirm('normal', 'yolo')).toBe(true);
expect(requiresYoloConfirm('trusted', 'yolo')).toBe(true);
});
it('does not re-prompt when yolo is already active', () => {
expect(requiresYoloConfirm('yolo', 'yolo')).toBe(false);
});
it('never gates a switch to a safe level', () => {
for (const current of LEVELS) {
expect(requiresYoloConfirm(current, 'normal')).toBe(false);
expect(requiresYoloConfirm(current, 'trusted')).toBe(false);
}
});
it('only ever returns true when the target is yolo', () => {
for (const current of LEVELS) {
for (const next of LEVELS) {
if (requiresYoloConfirm(current, next)) {
expect(next).toBe('yolo');
expect(current).not.toBe('yolo');
}
}
}
});
});

View File

@@ -0,0 +1,26 @@
/**
* F18 — "Never ask" (yolo) confirm-gate decision.
*
* The Permissions "Default approval level" radiogroup lets a user pick
* `yolo` (auto-pass every write/edit/mutating tool call except a hardcoded
* critical blacklist). Selecting it should carry one-time friction: a
* confirmation fires only on the TRANSITION into `yolo`, never on the safe
* levels and never when re-selecting the already-active level.
*
* NB: this permissions-approval union (`normal | trusted | yolo`) is a
* distinct concept from `@waggle/shared`'s agent-lifecycle `AutonomyLevel`
* (`manual | guided | medium | high`) — keep them separate.
*/
/** Permissions default-approval level for new chat windows. */
export type ApprovalLevel = 'normal' | 'trusted' | 'yolo';
/**
* Whether switching the default approval level from `current` to `next`
* requires an explicit confirmation. Only the transition INTO `yolo`
* ("Never ask") is gated; re-selecting the already-active level or moving
* to any safer level is friction-free.
*/
export function requiresYoloConfirm(current: ApprovalLevel, next: ApprovalLevel): boolean {
return next === 'yolo' && current !== 'yolo';
}

View File

@@ -0,0 +1,133 @@
/**
* M-27 / ENG-6 — Brain Health score regression coverage.
* Pure function, no React, no server — trivially fast vitest.
*/
import { describe, it, expect } from 'vitest';
import {
computeBrainHealth,
brainHealthTier,
brainHealthBreakdown,
HEALTH_TARGETS,
HEALTH_WEIGHTS,
} from './brain-health';
describe('computeBrainHealth', () => {
it('returns 0 for an empty brain', () => {
expect(computeBrainHealth({ frames: 0, entities: 0, relations: 0 })).toBe(0);
});
it('returns 100 when every dimension is at or above its target', () => {
expect(
computeBrainHealth({
frames: HEALTH_TARGETS.frames,
entities: HEALTH_TARGETS.entities,
relations: HEALTH_TARGETS.relations,
}),
).toBe(100);
});
it('caps at 100 when counts exceed targets', () => {
expect(
computeBrainHealth({
frames: HEALTH_TARGETS.frames * 10,
entities: HEALTH_TARGETS.entities * 10,
relations: HEALTH_TARGETS.relations * 10,
}),
).toBe(100);
});
it('each dimension at its target contributes its full weight', () => {
expect(computeBrainHealth({
frames: HEALTH_TARGETS.frames, entities: 0, relations: 0,
})).toBe(Math.round(HEALTH_WEIGHTS.frames * 100));
expect(computeBrainHealth({
frames: 0, entities: HEALTH_TARGETS.entities, relations: 0,
})).toBe(Math.round(HEALTH_WEIGHTS.entities * 100));
expect(computeBrainHealth({
frames: 0, entities: 0, relations: HEALTH_TARGETS.relations,
})).toBe(Math.round(HEALTH_WEIGHTS.relations * 100));
});
it('half-saturated counts contribute half of the dimension weight', () => {
const score = computeBrainHealth({
frames: HEALTH_TARGETS.frames / 2,
entities: HEALTH_TARGETS.entities / 2,
relations: HEALTH_TARGETS.relations / 2,
});
// 0.5 × (0.4 + 0.3 + 0.3) × 100 = 50
expect(score).toBe(50);
});
it('negative inputs are treated as zero', () => {
expect(computeBrainHealth({ frames: -10, entities: -1, relations: -5 })).toBe(0);
});
it('handles missing / undefined counts defensively', () => {
expect(computeBrainHealth({
frames: undefined as unknown as number,
entities: undefined as unknown as number,
relations: undefined as unknown as number,
})).toBe(0);
});
it('returns an integer (never fractional)', () => {
const score = computeBrainHealth({ frames: 1234, entities: 67, relations: 89 });
expect(Number.isInteger(score)).toBe(true);
});
it('weights sum to 1 — guarantees 100 is the ceiling', () => {
const sum = HEALTH_WEIGHTS.frames + HEALTH_WEIGHTS.entities + HEALTH_WEIGHTS.relations;
// Allow for floating point rounding noise.
expect(Math.abs(sum - 1)).toBeLessThan(1e-9);
});
});
describe('brainHealthTier', () => {
it.each([
[0, 'empty'],
[4, 'empty'],
[5, 'sparse'],
[24, 'sparse'],
[25, 'growing'],
[49, 'growing'],
[50, 'healthy'],
[79, 'healthy'],
[80, 'mature'],
[100, 'mature'],
] as const)('score %d → tier %s', (score, tier) => {
expect(brainHealthTier(score)).toBe(tier);
});
});
describe('brainHealthBreakdown', () => {
it('components sum to the overall score at saturation', () => {
const counts = {
frames: HEALTH_TARGETS.frames,
entities: HEALTH_TARGETS.entities,
relations: HEALTH_TARGETS.relations,
};
const breakdown = brainHealthBreakdown(counts);
const total = breakdown.frames + breakdown.entities + breakdown.relations;
expect(total).toBe(computeBrainHealth(counts));
expect(total).toBe(100);
});
it('components reflect dimension weights when uniform saturation is half', () => {
const breakdown = brainHealthBreakdown({
frames: HEALTH_TARGETS.frames / 2,
entities: HEALTH_TARGETS.entities / 2,
relations: HEALTH_TARGETS.relations / 2,
});
expect(breakdown.frames).toBe(20); // 0.5 × 0.4 × 100
expect(breakdown.entities).toBe(15); // 0.5 × 0.3 × 100
expect(breakdown.relations).toBe(15); // 0.5 × 0.3 × 100
});
it('reports 0 for empty brain', () => {
expect(brainHealthBreakdown({ frames: 0, entities: 0, relations: 0 })).toEqual({
frames: 0, entities: 0, relations: 0,
});
});
});

View File

@@ -0,0 +1,104 @@
/**
* Brain Health metric — weighted saturation score across memory stats.
*
* Surfaces a single 0-100 signal answering "how much of my brain is
* populated?". Weights reflect relative signal value per dimension:
* - frames (raw captured memory) carries the most quantity (40%)
* - entities (distilled KG nouns) carries mid (30%)
* - relations (KG edges) carries mid (30%)
*
* Each dimension saturates at its target count so no single dimension
* can push the overall score above 100%. Targets are tuned against
* observed counts on a "mature" personal.mind and can be revisited.
*
* Divergence from the M-27 backlog spec:
* The backlog's original formula was (frames × 0.3) + (concepts ×
* 0.4) + (entities × 0.3). `concept_mastery` exists in MindDB schema
* but ConceptTracker isn't wired into the cognify pipeline yet, so
* counting concepts would produce a constant zero. Until that lands,
* we swap the concepts term for relations (which is emitted by the
* KG and already flows through /api/memory/stats). When concepts
* ship, update `BrainHealthCounts` + the formula to match the spec.
*/
export interface BrainHealthCounts {
frames: number;
entities: number;
relations: number;
}
/** Target counts that correspond to 100% saturation per dimension. */
export const HEALTH_TARGETS = {
frames: 10_000,
entities: 500,
relations: 500,
} as const;
/** Weights per dimension — sum to 1. */
export const HEALTH_WEIGHTS = {
frames: 0.4,
entities: 0.3,
relations: 0.3,
} as const;
export type BrainHealthTier = 'empty' | 'sparse' | 'growing' | 'healthy' | 'mature';
export const TIER_LABELS: Record<BrainHealthTier, string> = {
empty: 'Empty',
sparse: 'Sparse',
growing: 'Growing',
healthy: 'Healthy',
mature: 'Mature',
};
/**
* Compute a 0-100 integer Brain Health score from memory counts.
* Negative inputs clamp to 0; counts above the dimension target cap
* that dimension's contribution at its weight.
*/
export function computeBrainHealth(counts: BrainHealthCounts): number {
const frames = Math.max(0, counts.frames ?? 0);
const entities = Math.max(0, counts.entities ?? 0);
const relations = Math.max(0, counts.relations ?? 0);
const framesRatio = Math.min(1, frames / HEALTH_TARGETS.frames);
const entitiesRatio = Math.min(1, entities / HEALTH_TARGETS.entities);
const relationsRatio = Math.min(1, relations / HEALTH_TARGETS.relations);
const score =
framesRatio * HEALTH_WEIGHTS.frames +
entitiesRatio * HEALTH_WEIGHTS.entities +
relationsRatio * HEALTH_WEIGHTS.relations;
return Math.round(score * 100);
}
/** Qualitative tier label for a given score. */
export function brainHealthTier(score: number): BrainHealthTier {
if (score < 5) return 'empty';
if (score < 25) return 'sparse';
if (score < 50) return 'growing';
if (score < 80) return 'healthy';
return 'mature';
}
/**
* Per-dimension contribution breakdown (rounded integers summing to
* the final score). Useful for tooltips that show "why" a score is
* low — the user can see which dimension is lagging.
*/
export function brainHealthBreakdown(counts: BrainHealthCounts): {
frames: number;
entities: number;
relations: number;
} {
const frames = Math.max(0, counts.frames ?? 0);
const entities = Math.max(0, counts.entities ?? 0);
const relations = Math.max(0, counts.relations ?? 0);
return {
frames: Math.round(Math.min(1, frames / HEALTH_TARGETS.frames) * HEALTH_WEIGHTS.frames * 100),
entities: Math.round(Math.min(1, entities / HEALTH_TARGETS.entities) * HEALTH_WEIGHTS.entities * 100),
relations: Math.round(Math.min(1, relations / HEALTH_TARGETS.relations) * HEALTH_WEIGHTS.relations * 100),
};
}

View File

@@ -0,0 +1,133 @@
/**
* L-22 — briefing highlight ranker regression.
*/
import { describe, it, expect } from 'vitest';
import {
BRIEFING_HIGHLIGHT_LIMIT,
selectBriefingHighlights,
type BriefingFrameLike,
} from './briefing-highlights';
function make(overrides: Partial<BriefingFrameLike> = {}): BriefingFrameLike {
return {
content: overrides.content ?? 'A reasonably long concrete memory about a topic.',
importance: overrides.importance ?? 'normal',
timestamp: overrides.timestamp ?? '2026-04-01T00:00:00Z',
...overrides,
};
}
describe('selectBriefingHighlights', () => {
it('returns at most BRIEFING_HIGHLIGHT_LIMIT items', () => {
// Distinct contents — identical ones are now collapsed by the dedup.
const input = Array.from({ length: 10 }, (_, i) => make({ content: `A reasonably long concrete memory about topic number ${i}.` }));
expect(selectBriefingHighlights(input)).toHaveLength(BRIEFING_HIGHLIGHT_LIMIT);
});
it('filters deprecated/archived frames and extraction echoes', () => {
const input = [
make({ content: 'A deprecated but otherwise concrete memory.', status: 'deprecated' }),
make({ content: 'An archived but otherwise concrete memory.', status: 'archived' }),
make({ content: 'User asked: Review recent decisions and next steps' }),
make({ content: 'A living, concrete memory about the launch plan.', status: 'active' }),
];
const result = selectBriefingHighlights(input);
expect(result).toHaveLength(1);
expect(result[0].content).toContain('living');
});
it('collapses duplicate content to one highlight, keeping the earliest timestamp', () => {
const input = [
make({ content: 'Session (2026-04-30): What is sovereign AI — 4 messages', timestamp: '2026-06-11T00:00:00Z' }),
make({ content: 'Session (2026-04-30): What is sovereign AI — 4 messages', timestamp: '2026-05-01T00:00:00Z' }),
make({ content: 'A different, equally concrete memory about the launch.', timestamp: '2026-06-01T00:00:00Z' }),
];
const result = selectBriefingHighlights(input);
const dupes = result.filter(f => (f.content ?? '').startsWith('Session (2026-04-30)'));
expect(dupes).toHaveLength(1);
// The kept copy is the moment it was learned, not the consolidation rewrite.
expect(dupes[0].timestamp).toBe('2026-05-01T00:00:00Z');
});
it('collapses near-duplicates that differ only by an embedded run/uuid token (F22)', () => {
const input = [
make({ content: 'LoCoMo benchmark hit 86.49 (audit-run-id: 3f9a2b)', timestamp: '2026-07-04T00:00:00Z' }),
make({ content: 'LoCoMo benchmark hit 86.49 (audit-run-id: 71ee44)', timestamp: '2026-07-01T00:00:00Z' }),
make({ content: 'A different, equally concrete memory about pricing.', timestamp: '2026-06-01T00:00:00Z' }),
];
const result = selectBriefingHighlights(input);
const benchmarks = result.filter(f => (f.content ?? '').startsWith('LoCoMo benchmark'));
expect(benchmarks).toHaveLength(1);
// Earliest-learned copy is kept.
expect(benchmarks[0].timestamp).toBe('2026-07-01T00:00:00Z');
});
it('collapses near-duplicates that differ only by a bare "audit-<digits>" id (live wave-4 QA regression)', () => {
// Reproduces the actual finding: "Imran uses 2x2 frameworks…" appeared
// twice in the briefing, differing only by "audit-1782648502308" vs
// "audit-1782638749061" — a form RUN_ID_RE didn't cover (no "run" word).
const input = [
make({ content: 'Imran uses 2x2 frameworks and wants every client decision remembered by account. (audit-1782648502308)', timestamp: '2026-07-04T00:00:00Z' }),
make({ content: 'Imran uses 2x2 frameworks and wants every client decision remembered by account. (audit-1782638749061)', timestamp: '2026-07-01T00:00:00Z' }),
];
const result = selectBriefingHighlights(input);
const imran = result.filter(f => (f.content ?? '').startsWith('Imran uses 2x2'));
expect(imran).toHaveLength(1);
expect(imran[0].timestamp).toBe('2026-07-01T00:00:00Z');
});
it('filters out content shorter than 20 chars', () => {
const input = [make({ content: 'short' }), make({ content: '' }), make({ content: 'x'.repeat(50) })];
const result = selectBriefingHighlights(input);
expect(result).toHaveLength(1);
expect(result[0].content).toBe('x'.repeat(50));
});
it('orders by importance desc', () => {
const input = [
make({ content: 'x'.repeat(30), importance: 'normal', timestamp: '2026-04-10T00:00:00Z' }),
make({ content: 'y'.repeat(30), importance: 'critical', timestamp: '2026-04-01T00:00:00Z' }),
make({ content: 'z'.repeat(30), importance: 'important', timestamp: '2026-04-05T00:00:00Z' }),
];
const result = selectBriefingHighlights(input);
expect(result.map(r => r.content)).toEqual([
'y'.repeat(30),
'z'.repeat(30),
'x'.repeat(30),
]);
});
it('breaks importance ties by recency desc', () => {
const input = [
make({ content: 'old' + 'x'.repeat(30), importance: 'important', timestamp: '2026-04-01T00:00:00Z' }),
make({ content: 'new' + 'x'.repeat(30), importance: 'important', timestamp: '2026-04-19T00:00:00Z' }),
];
const result = selectBriefingHighlights(input);
expect(result[0].content).toBe('new' + 'x'.repeat(30));
});
it('accepts numeric importance values too', () => {
const input = [
make({ content: 'lo' + 'x'.repeat(30), importance: 1 }),
make({ content: 'hi' + 'x'.repeat(30), importance: 5 }),
];
const result = selectBriefingHighlights(input);
expect(result[0].content).toBe('hi' + 'x'.repeat(30));
});
it('does not mutate the input', () => {
const input = [make(), make()];
const before = input.slice();
selectBriefingHighlights(input);
expect(input).toEqual(before);
});
it('tolerates missing fields', () => {
const input = [
{ content: 'x'.repeat(30) } as BriefingFrameLike,
{ content: 'y'.repeat(30), importance: undefined, timestamp: null } as BriefingFrameLike,
];
const result = selectBriefingHighlights(input);
expect(result).toHaveLength(2);
});
});

View File

@@ -0,0 +1,125 @@
/**
* LoginBriefing highlight ranker (L-22 — richer memory bragging).
*
* Picks the 3 most concrete memory frames to show under "I remember"
* so the briefing proves Waggle's long-term memory with real content,
* not placeholder noise.
*
* Ranking order:
* 1. Importance descending ("critical" > "important" > others), so
* a curated "critical" memory wins over a trivial "normal" one.
* 2. Recency descending (so older important memories don't crowd
* out recent ones at the same importance).
*
* Filters:
* - content length ≥ 20 chars (short snippets are usually tool
* receipts, not meaningful highlights).
* - skip empty / null content.
*/
import { normalizeMemoryKey, isGroupableKey } from '@/lib/memory-text-normalize';
export interface BriefingFrameLike {
readonly content?: string | null;
readonly importance?: string | number | null;
readonly timestamp?: string | number | null;
readonly workspaceName?: string | null;
/** Frame lifecycle status — deprecated/archived frames must never headline. */
readonly status?: string | null;
}
/**
* Extraction echoes ("User asked: …", "User preference: …") are machine
* paraphrases of the user's own prompts — showing them under "I remember"
* reads as a log, not a memory, and talks about the user in the third person.
*/
const JUNK_HIGHLIGHT_PREFIXES = /^(user asked|user preference|user requested|user identity)\s*:/i;
export const BRIEFING_HIGHLIGHT_LIMIT = 3;
const MIN_HIGHLIGHT_CONTENT_CHARS = 20;
function importanceScore(f: BriefingFrameLike): number {
const v = f.importance;
if (typeof v === 'number') return v;
switch (v) {
case 'critical': return 4;
case 'important': return 3;
case 'normal': return 2;
case 'low': return 1;
default: return 2;
}
}
function timestampMs(f: BriefingFrameLike): number {
const ts = f.timestamp;
if (typeof ts === 'number') return ts;
if (typeof ts === 'string') {
const parsed = Date.parse(ts);
return Number.isFinite(parsed) ? parsed : 0;
}
return 0;
}
function isConcrete(f: BriefingFrameLike): boolean {
if (typeof f.content !== 'string') return false;
const trimmed = f.content.trim();
if (trimmed.length < MIN_HIGHLIGHT_CONTENT_CHARS) return false;
if (JUNK_HIGHLIGHT_PREFIXES.test(trimmed)) return false;
// Only living memories headline the greeting — a deprecated/superseded
// frame in "I remember" is the product visibly misremembering itself.
if (f.status === 'deprecated' || f.status === 'archived') return false;
return true;
}
/**
* First line of the content, normalized — the identity used for dedup.
*
* Routes through the shared `normalizeMemoryKey` (F22) so near-duplicates that
* differ only by an embedded volatile token (audit-run id, uuid, timestamp)
* collapse to a single highlight too — not just byte-identical rewrites. Falls
* back to the raw first line when the normalized key is too thin to trust
* (short/punctuation-only), so unrelated short facts never merge.
*/
function highlightKey(f: BriefingFrameLike): string {
const firstLine = (f.content ?? '').split('\n')[0];
const normalized = normalizeMemoryKey(firstLine);
if (isGroupableKey(normalized)) return normalized.slice(0, 120);
return firstLine.trim().toLowerCase().slice(0, 120);
}
/**
* Rank and trim the frames to the top BRIEFING_HIGHLIGHT_LIMIT
* highlights. Returns a new array — does not mutate input.
*
* Duplicate content (consolidation re-writes the same fact as a fresh
* frame) is collapsed to ONE highlight, keeping the EARLIEST timestamp —
* the moment it was learned. Showing the same memory twice with two
* different ages was the single most trust-destroying defect judges hit.
*/
export function selectBriefingHighlights<T extends BriefingFrameLike>(frames: readonly T[]): T[] {
const concrete = frames.filter(isConcrete);
const byKey = new Map<string, T>();
for (const f of concrete) {
const key = highlightKey(f);
const existing = byKey.get(key);
if (!existing) {
byKey.set(key, f);
continue;
}
// Keep the higher-importance copy; tie → the earliest-learned copy.
if (
importanceScore(f) > importanceScore(existing) ||
(importanceScore(f) === importanceScore(existing) &&
timestampMs(f) > 0 &&
(timestampMs(existing) === 0 || timestampMs(f) < timestampMs(existing)))
) {
byKey.set(key, f);
}
}
const sorted = [...byKey.values()].sort((a, b) => {
const impDiff = importanceScore(b) - importanceScore(a);
if (impDiff !== 0) return impDiff;
return timestampMs(b) - timestampMs(a);
});
return sorted.slice(0, BRIEFING_HIGHLIGHT_LIMIT);
}

View File

@@ -0,0 +1,48 @@
/**
* Lane H item 4 — away-days computation for the "double catch-up collapse".
*
* The full "Catching you up" modal fires only on a ≥7-day absence; the everyday
* catch-up is the home hero recall strip. computeAwayDays derives the absence
* from the SAME workspace lastActive stream the hero greeting reads, and returns
* 0 for a no-activity account so a brand-new user never trips the modal.
*/
import { describe, it, expect } from 'vitest';
import { computeAwayDays, BRIEFING_ABSENCE_DAYS } from '@/lib/briefing-source';
const NOW = Date.parse('2026-07-07T12:00:00.000Z');
const daysAgo = (n: number) => new Date(NOW - n * 86_400_000).toISOString();
describe('computeAwayDays (Lane H item 4)', () => {
it('is 0 for a no-activity / empty account (modal never trips)', () => {
expect(computeAwayDays([], NOW)).toBe(0);
expect(computeAwayDays([{ lastActive: '' }, {}], NOW)).toBe(0);
});
it('uses the MOST-RECENT workspace lastActive, not the oldest', () => {
const away = computeAwayDays(
[{ lastActive: daysAgo(30) }, { lastActive: daysAgo(2) }, { lastActive: daysAgo(15) }],
NOW,
);
expect(Math.round(away)).toBe(2);
});
it('a recent user (<7d) is below the modal threshold', () => {
expect(computeAwayDays([{ lastActive: daysAgo(3) }], NOW)).toBeLessThan(BRIEFING_ABSENCE_DAYS);
});
it('a long-absent user (≥7d) is at/above the modal threshold', () => {
expect(computeAwayDays([{ lastActive: daysAgo(10) }], NOW)).toBeGreaterThanOrEqual(BRIEFING_ABSENCE_DAYS);
});
it('ignores unparseable timestamps', () => {
expect(computeAwayDays([{ lastActive: 'not-a-date' }], NOW)).toBe(0);
});
it('clamps a future timestamp to 0 (never negative away days)', () => {
expect(computeAwayDays([{ lastActive: daysAgo(-5) }], NOW)).toBe(0);
});
it('N=7 is the founder-decided absence threshold', () => {
expect(BRIEFING_ABSENCE_DAYS).toBe(7);
});
});

View File

@@ -0,0 +1,211 @@
/**
* briefing-source — the ONE briefing truth (Path-to-9 Pillar 2.3 / Lane H item 3).
*
* The "catch you up" data (recall highlights + workspace summaries + brag counts)
* used to live ONLY inside LoginBriefing, so the home hero and the modal derived
* their catch-up facts independently — the number-drift bug class ("2 workspaces"
* in the modal vs "6 workspaces waiting" in the hero). This module is the single
* fetch + shaping + count formula BOTH surfaces consume, so they can never state
* two truths about one store.
*
* The fetch/shape/prefetch logic is the exact code the LoginBriefing component
* used to own inline (moved, not changed) — see the git history of
* overlays/LoginBriefing.tsx. HomeCockpit (hero recall strip) and LoginBriefing
* (the ≥7-day modal) both import from here.
*/
import { adapter } from '@/lib/adapter';
import type { Workspace } from '@/lib/types';
import { selectBriefingHighlights } from '@/lib/briefing-highlights';
import { isDevNoiseWorkspace, workspaceCounts } from '@/lib/workspace-counts';
import {
computeBragSummary,
type BragSummary,
} from '@/lib/login-briefing-brag';
export interface WorkspaceSummary {
id: string;
name: string;
group: string;
memoryCount: number;
sessionCount: number;
lastActive: string;
summary?: string;
pendingTasks?: string[];
}
export interface MemoryHighlight {
content: string;
workspace?: string;
timestamp: string;
}
export interface BriefingData {
highlights: MemoryHighlight[];
summaries: WorkspaceSummary[];
brag: BragSummary | null;
}
/**
* The modal (full "Catching you up" overlay) is reserved for long absences —
* the everyday catch-up is the home hero's recall strip (Lane H item 4, the
* "double catch-up collapse"). N=7, founder-decided (path-to-9 v3 §Pillar 2.3c).
*/
export const BRIEFING_ABSENCE_DAYS = 7;
export function truncateHighlight(content: string): string {
// Plain text only — highlights render as text nodes, so markdown tokens
// (**bold**, # headings, `code`) would show literally.
const firstLine = content.split('\n')[0].trim()
.replace(/^#{1,3}\s+/, '')
.replace(/\*\*(.+?)\*\*/g, '$1')
.replace(/`(.+?)`/g, '$1');
return firstLine.length > 120 ? firstLine.slice(0, 117) + '...' : firstLine;
}
// Workspace names matching dev/test-artefact patterns leaked into the user's
// real store and should not surface in the briefing. Filtered at the UI layer
// (defensive), not deleted — W2B consolidated predicate.
const isTestWorkspace = isDevNoiseWorkspace;
// The server emits a brochure default summary ("Everything you discuss in
// {name} stays in context …") whenever a workspace has no real generated
// summary yet. That is template copy, not the user's data — it must never
// render as a summary. Matched on the name-invariant tail.
export const CANNED_SUMMARY_TAIL =
'stays in context — decisions, research, and progress are remembered across sessions';
export function isCannedWorkspaceSummary(summary?: string): boolean {
return typeof summary === 'string' && summary.includes(CANNED_SUMMARY_TAIL);
}
/**
* The full briefing fetch + shaping. Throws only on a hard failure
* (getWorkspaces reject) so the caller renders its error/degraded surface; the
* soft sources (memory search / stats) already degrade to []/null inline.
* Byte-for-byte the logic LoginBriefing used to run inline.
*/
export async function fetchBriefingData(): Promise<BriefingData> {
const [workspaces, frames, stats] = await Promise.all([
adapter.getWorkspaces(),
adapter.searchMemory('important decision project plan', 'global').catch(() => []),
adapter.getMemoryStats().catch(() => null),
]);
// L-22: rank by importance desc, break ties by recency. Concrete content only
// (≥20 chars), living frames only — deprecated/archived and extraction echoes
// are filtered inside the ranker.
const ranked = selectBriefingHighlights(
(frames as Array<{ content?: string; importance?: number; timestamp?: string; metadata?: Record<string, unknown> }>).map((f) => ({
content: f.content,
importance: f.importance,
timestamp: f.timestamp,
status: typeof f.metadata?.status === 'string' ? f.metadata.status : undefined,
})),
);
const highlights: MemoryHighlight[] = ranked.map((f) => ({
content: truncateHighlight(f.content ?? ''),
timestamp: (typeof f.timestamp === 'string' ? f.timestamp : '') ?? '',
}));
// Workspace summaries — show all, not just ones with content. Drop E2E/test
// workspaces that leaked into the real store so the briefing surfaces only
// user work.
const sorted = workspaces
.filter((ws: Workspace) => !isTestWorkspace(ws.name))
.slice(0, 5);
const contextPromises = sorted.map(async (ws: Workspace): Promise<WorkspaceSummary> => {
try {
const ctx = await adapter.getWorkspaceContext(ws.id);
return {
id: ws.id,
name: ws.name,
group: ws.group ?? 'Personal',
memoryCount: ctx.stats?.memoryCount ?? ctx.memoryCount ?? 0,
sessionCount: ctx.stats?.sessionCount ?? ctx.sessionCount ?? 0,
// USER activity from the workspace store — machine cron writes are not
// "active" (ws.lastActive, not ctx.lastActive).
lastActive: ws.lastActive ?? '',
summary: ctx.summary,
pendingTasks: ctx.pendingTasks,
};
} catch {
return {
id: ws.id,
name: ws.name,
group: ws.group ?? 'Personal',
memoryCount: 0,
sessionCount: 0,
lastActive: '',
};
}
});
const summaries = await Promise.all(contextPromises);
// Most recent first — a two-month-stale workspace above yesterday's work
// contradicted the Home grid's recency ordering.
summaries.sort((a, b) => Date.parse(b.lastActive || '0') - Date.parse(a.lastActive || '0'));
// Numbers reconciliation (Wave U Lane B item 2): the header's workspace count
// must equal Home's hero ("N workspaces waiting"). Both read the SAME canonical
// visible count (non-archived, non-dev-noise) from workspaceCounts(), so the
// modal and the hero it overlays can never state two totals for one store.
const brag = computeBragSummary(stats, summaries);
return {
highlights,
summaries,
brag: { ...brag, workspaceCount: workspaceCounts(workspaces).visible },
};
}
// Prefetch cache: a single in-flight/settled briefing promise the BootScreen
// warms via prefetchBriefing(). takeBriefingData() consumes it ONCE, then falls
// back to a fresh fetch — so retries/revalidation always re-fetch, and a direct
// consumer with no prefetch (unit tests) is unaffected. A failed prefetch is
// dropped so the consumer's own load fetches fresh. Consume-once (not a shared
// promise) keeps every consumer independent, so no cross-consumer/cross-test
// state can leak.
let prefetchedBriefing: Promise<BriefingData> | null = null;
export function prefetchBriefing(): void {
if (prefetchedBriefing) return;
prefetchedBriefing = fetchBriefingData();
prefetchedBriefing.catch(() => { prefetchedBriefing = null; });
}
export function takeBriefingData(): Promise<BriefingData> {
if (prefetchedBriefing) {
const pending = prefetchedBriefing;
prefetchedBriefing = null;
return pending;
}
return fetchBriefingData();
}
/** Test-only: drop the prefetch so module state can't leak across tests. */
export function resetBriefingSource(): void {
prefetchedBriefing = null;
}
/**
* Days since the user was last active, computed from the SAME workspace
* `lastActive` stream the hero greeting and briefing summaries read (user
* activity, not machine cron writes). Returns 0 when no valid activity exists
* (a brand-new / no-activity account is never treated as a long absence — the
* hero owns first-run, the modal stays closed). Pure; `now` overridable.
*/
export function computeAwayDays(
workspaces: ReadonlyArray<{ lastActive?: string }>,
now: number = Date.now(),
): number {
let mostRecent = -Infinity;
for (const ws of workspaces) {
const raw = ws.lastActive;
if (!raw) continue;
const ms = Date.parse(raw);
if (Number.isFinite(ms) && ms > mostRecent) mostRecent = ms;
}
if (!Number.isFinite(mostRecent)) return 0;
const days = (now - mostRecent) / 86_400_000;
return days > 0 ? days : 0;
}

View File

@@ -0,0 +1,112 @@
/**
* P14 regression — breadcrumb rendering across POSIX + Windows + virtual
* storage types.
*/
import { describe, it, expect } from 'vitest';
import { buildBreadcrumbs } from './browse-breadcrumbs';
describe('buildBreadcrumbs', () => {
describe('root variants', () => {
it('returns only the root crumb when path is "/"', () => {
const out = buildBreadcrumbs('/', 'My Drive', 'local');
expect(out).toEqual([{ label: 'My Drive', path: '/' }]);
});
it('returns only the root crumb when path is empty', () => {
expect(buildBreadcrumbs('', 'Drives', 'local')).toEqual([
{ label: 'Drives', path: '/' },
]);
});
it('returns only the root crumb when path is a single backslash', () => {
expect(buildBreadcrumbs('\\', 'Drives', 'local')).toEqual([
{ label: 'Drives', path: '/' },
]);
});
});
describe('Windows local paths', () => {
it('surfaces the drive letter as the second crumb', () => {
const out = buildBreadcrumbs('C:\\', 'Drives', 'local');
expect(out).toEqual([
{ label: 'Drives', path: '/' },
{ label: 'C:', path: 'C:\\' },
]);
});
it('splits C:\\Users\\Marko into root / drive / Users / Marko', () => {
const out = buildBreadcrumbs('C:\\Users\\Marko', 'Drives', 'local');
expect(out).toEqual([
{ label: 'Drives', path: '/' },
{ label: 'C:', path: 'C:\\' },
{ label: 'Users', path: 'C:\\Users' },
{ label: 'Marko', path: 'C:\\Users\\Marko' },
]);
});
it('handles drive-only paths without trailing separator', () => {
const out = buildBreadcrumbs('D:', 'Drives', 'local');
expect(out).toEqual([
{ label: 'Drives', path: '/' },
{ label: 'D:', path: 'D:\\' },
]);
});
it('uppercases a lowercase drive letter in the crumb label', () => {
const out = buildBreadcrumbs('c:\\Projects', 'Drives', 'local');
expect(out[1]).toEqual({ label: 'C:', path: 'C:\\' });
});
it('accepts mixed separators (C:/Users/Marko)', () => {
const out = buildBreadcrumbs('C:/Users/Marko', 'Drives', 'local');
expect(out).toEqual([
{ label: 'Drives', path: '/' },
{ label: 'C:', path: 'C:\\' },
{ label: 'Users', path: 'C:\\Users' },
{ label: 'Marko', path: 'C:\\Users\\Marko' },
]);
});
});
describe('POSIX local paths', () => {
it('splits /Users/marko/Documents into three crumbs', () => {
const out = buildBreadcrumbs('/Users/marko/Documents', 'Drives', 'local');
expect(out).toEqual([
{ label: 'Drives', path: '/' },
{ label: 'Users', path: '/Users' },
{ label: 'marko', path: '/Users/marko' },
{ label: 'Documents', path: '/Users/marko/Documents' },
]);
});
});
describe('virtual / team storage', () => {
it('treats virtual paths as POSIX', () => {
const out = buildBreadcrumbs('/workspace/docs', 'Virtual', 'virtual');
expect(out).toEqual([
{ label: 'Virtual', path: '/' },
{ label: 'workspace', path: '/workspace' },
{ label: 'docs', path: '/workspace/docs' },
]);
});
it('treats team paths as POSIX', () => {
const out = buildBreadcrumbs('/team/shared', 'Team', 'team');
expect(out).toEqual([
{ label: 'Team', path: '/' },
{ label: 'team', path: '/team' },
{ label: 'shared', path: '/team/shared' },
]);
});
});
it('handles deeply nested Windows paths without collapsing', () => {
const deep = 'C:\\Users\\Marko\\OneDrive - Egzakta d.o.o\\Desktop';
const out = buildBreadcrumbs(deep, 'Drives', 'local');
// root + drive + Users + Marko + OneDrive... + Desktop = 6
expect(out).toHaveLength(6);
expect(out[5]).toEqual({ label: 'Desktop', path: deep });
expect(out[4].label).toBe('OneDrive - Egzakta d.o.o');
});
});

View File

@@ -0,0 +1,88 @@
/**
* Breadcrumb helper for the local-browse dialog.
*
* On Windows the sidecar returns paths like `C:\Users\Marko`. The old
* breadcrumb rendering split on `/` only, so Windows paths collapsed
* into a single unusable crumb. This helper normalises across both
* separator styles, keeping virtual (POSIX) storage untouched.
*
* P14 scope extension: enabling drive enumeration at the API level
* (see `browse-helpers.ts`) only helps if the UI can walk the resulting
* paths. Splitting logic lives here, tested independently.
*/
export type StorageBrowseType = 'local' | 'virtual' | 'team';
export interface Crumb {
label: string;
path: string;
}
const WINDOWS_DRIVE_RE = /^([A-Za-z]):[\\/]?/;
/**
* Break a `currentPath` into navigable crumbs.
*
* - `'/'` always resolves to a single root crumb.
* - Local paths on Windows keep backslashes in the `path` field so the
* server can resolve them natively; only the strip labels are friendly.
* - Virtual/team paths (POSIX) split on `/` and reassemble with `/`.
*/
export function buildBreadcrumbs(
currentPath: string,
rootLabel: string,
storageType: StorageBrowseType,
): Crumb[] {
if (currentPath === '/' || currentPath === '' || currentPath === '\\') {
return [{ label: rootLabel, path: '/' }];
}
if (storageType === 'local') {
return buildLocalCrumbs(currentPath, rootLabel);
}
return buildPosixCrumbs(currentPath, rootLabel);
}
function buildLocalCrumbs(currentPath: string, rootLabel: string): Crumb[] {
const match = currentPath.match(WINDOWS_DRIVE_RE);
if (match) {
const driveLetter = match[1].toUpperCase();
const drivePath = `${driveLetter}:\\`;
const rest = currentPath.slice(match[0].length);
const parts = splitPathParts(rest);
const crumbs: Crumb[] = [
{ label: rootLabel, path: '/' },
{ label: `${driveLetter}:`, path: drivePath },
];
let acc = drivePath;
for (const part of parts) {
acc = joinWindows(acc, part);
crumbs.push({ label: part, path: acc });
}
return crumbs;
}
return buildPosixCrumbs(currentPath, rootLabel);
}
function buildPosixCrumbs(currentPath: string, rootLabel: string): Crumb[] {
const parts = splitPathParts(currentPath);
const crumbs: Crumb[] = [{ label: rootLabel, path: '/' }];
let acc = '';
for (const part of parts) {
acc = `${acc}/${part}`;
crumbs.push({ label: part, path: acc });
}
return crumbs;
}
function splitPathParts(p: string): string[] {
return p.split(/[\\/]/).filter((s) => s.length > 0);
}
function joinWindows(base: string, part: string): string {
return base.endsWith('\\') ? `${base}${part}` : `${base}\\${part}`;
}

View File

@@ -0,0 +1,63 @@
/**
* M-21 / UX-6 — chat-header layout decision regression.
*
* Pins the threshold and classification so a future width tweak or
* "let's move autonomy into the overflow too" refactor surfaces as a
* failing test rather than a silent UX regression.
*/
import { describe, it, expect } from 'vitest';
import {
CHAT_HEADER_COMPACT_THRESHOLD_PX,
CHAT_HEADER_OVERFLOW_CONTROLS,
CHAT_HEADER_PRIMARY_CONTROLS,
shouldCollapseChatHeader,
} from './chat-header-layout';
describe('shouldCollapseChatHeader', () => {
it('returns false when width is unknown (first render)', () => {
expect(shouldCollapseChatHeader(null)).toBe(false);
expect(shouldCollapseChatHeader(undefined)).toBe(false);
});
it('returns false for non-finite values (defensive against 0-sized containers)', () => {
expect(shouldCollapseChatHeader(Number.NaN)).toBe(false);
expect(shouldCollapseChatHeader(Number.POSITIVE_INFINITY)).toBe(false);
});
it('returns false at and above the threshold', () => {
expect(shouldCollapseChatHeader(CHAT_HEADER_COMPACT_THRESHOLD_PX)).toBe(false);
expect(shouldCollapseChatHeader(CHAT_HEADER_COMPACT_THRESHOLD_PX + 1)).toBe(false);
expect(shouldCollapseChatHeader(1200)).toBe(false);
});
it('returns true below the threshold', () => {
expect(shouldCollapseChatHeader(CHAT_HEADER_COMPACT_THRESHOLD_PX - 1)).toBe(true);
expect(shouldCollapseChatHeader(320)).toBe(true);
expect(shouldCollapseChatHeader(0)).toBe(true);
});
});
describe('chat header control classification', () => {
it('threshold is 480 px', () => {
expect(CHAT_HEADER_COMPACT_THRESHOLD_PX).toBe(480);
});
it('overflow set is the informational chips only', () => {
expect([...CHAT_HEADER_OVERFLOW_CONTROLS].sort()).toEqual(
['storage-type', 'team-presence'].sort(),
);
});
it('primary set is the interactive controls that must not nest in a popover', () => {
expect([...CHAT_HEADER_PRIMARY_CONTROLS].sort()).toEqual(
['persona-picker', 'autonomy-toggle', 'model-picker'].sort(),
);
});
it('primary and overflow sets are disjoint', () => {
const overflow = new Set(CHAT_HEADER_OVERFLOW_CONTROLS as readonly string[]);
for (const primary of CHAT_HEADER_PRIMARY_CONTROLS) {
expect(overflow.has(primary as string)).toBe(false);
}
});
});

View File

@@ -0,0 +1,53 @@
/**
* Chat-header layout decision (M-21 / UX-6).
*
* The header crowds the persona picker + storage badge + team presence
* + autonomy toggle + model picker into a single row. Below a narrow
* threshold, the informational surfaces (storage badge, team presence)
* move into a ⋯ overflow menu so the interactive controls (persona,
* autonomy, model) stay reachable without the header wrapping or
* truncating.
*
* This module holds the pure decision so a test can pin the threshold
* and the classification of each control without booting React.
*/
/** Pixel width at which we switch to compact layout. */
export const CHAT_HEADER_COMPACT_THRESHOLD_PX = 480;
/**
* Decide whether the header should render in compact mode.
*
* Returns `false` during the first render when the container width is
* not yet known — rendering the full header briefly is preferable to
* mounting with the compact layout and flashing into the full layout
* when the observer fires.
*/
export function shouldCollapseChatHeader(containerWidth: number | null | undefined): boolean {
if (containerWidth == null) return false;
if (!Number.isFinite(containerWidth)) return false;
return containerWidth < CHAT_HEADER_COMPACT_THRESHOLD_PX;
}
/**
* Informational chips that move into the overflow menu when compact.
* Listed here so tests can pin the set, and a future contributor
* adding a new chip has to update both the UI and this list.
*/
export const CHAT_HEADER_OVERFLOW_CONTROLS = [
'storage-type',
'team-presence',
] as const;
export type ChatHeaderOverflowControl = (typeof CHAT_HEADER_OVERFLOW_CONTROLS)[number];
/**
* Controls that MUST stay in the primary row regardless of width —
* they're interactive and nesting them inside another dropdown would
* produce a nested-popover UX.
*/
export const CHAT_HEADER_PRIMARY_CONTROLS = [
'persona-picker',
'autonomy-toggle',
'model-picker',
] as const;
export type ChatHeaderPrimaryControl = (typeof CHAT_HEADER_PRIMARY_CONTROLS)[number];

70
apps/web/src/lib/clerk.ts Normal file
View File

@@ -0,0 +1,70 @@
/**
* PR7b Clerk config — the shared-instance publishable key + the warm appearance.
*
* D2(b): Clerk is OPTIONAL. Hosted auth must be explicitly enabled; otherwise the
* SPA runs fully accountless (WaggleClerkProvider renders children with no ClerkProvider;
* /auth shows the local-first AccountlessNotice). The key is public-safe by design
* (ships in the client bundle); the SECRET key is server-side only and the desktop
* never uses it (the local sidecar authorizes with its device token).
*/
import { dark } from '@clerk/themes';
/**
* Faithful inline of Clerk's own `isPublishableKey` shape check: a `pk_test_`/`pk_live_`
* prefix plus a base64 payload that decodes to a frontend-API host ending in "$". Inlined
* (not imported from `@clerk/shared/keys`) because the monorepo resolves MULTIPLE
* `@clerk/shared` majors — clerk-react@5 bundles 3.x while @clerk/themes pulls 4.x — so an
* imported validator could resolve to a different copy than ClerkProvider uses. This
* deterministic inline can't drift from whichever copy hoists; the format itself is
* fundamental to how Clerk keys are minted and is stable across majors.
*/
function isValidPublishableKey(key: string): boolean {
if (!key.startsWith('pk_test_') && !key.startsWith('pk_live_')) return false;
try {
return atob(key.split('_')[2] ?? '').endsWith('$');
} catch {
return false;
}
}
/**
* The Clerk publishable key (shared "elegant-camel-8" instance), or undefined when
* unconfigured OR shape-invalid. Read at CALL time (not module load) so it stays
* test-stubbable and so the no-key fallback is decided at render.
*
* The shape gate is load-bearing: ClerkProvider throws *synchronously in render* on a
* malformed key, and WaggleClerkProvider sits ABOVE AppErrorBoundary, so a placeholder /
* typo'd / truncated key (e.g. the `.env.example` placeholder) would otherwise blank the
* WHOLE app at boot. Rejecting it here degrades cleanly to the honest accountless state
* instead (the §6/D16 "absent → accountless" guarantee).
*/
export function clerkPublishableKey(): string | undefined {
if (import.meta.env.VITE_WAGGLE_ENABLE_CLERK !== '1') return undefined;
const k = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY;
return k && isValidPublishableKey(k) ? k : undefined;
}
/**
* Warm-token Clerk appearance. Mirrors the apps/www pattern (baseTheme: dark + a
* variables override) recolored to the WARM hex (apps/www uses the old cooler hex).
* NOTE: do NOT add `as const` — it over-narrows Clerk's Appearance union and silently
* drops `baseTheme` (recon 05 §5.3 / apps/www layout.tsx:31-34 gotcha).
*/
export function clerkAppearance(isDark: boolean) {
return {
baseTheme: isDark ? dark : undefined,
variables: {
colorPrimary: isDark ? '#e9a52c' : '#b57d12',
colorBackground: isDark ? '#1a160f' : '#f1e9d8',
colorText: isDark ? '#ece3cf' : '#2a2418',
colorInputBackground: isDark ? '#14110b' : '#fffdf8',
borderRadius: '11px',
fontFamily: '"Hanken Grotesk", system-ui, sans-serif',
},
elements: {
// We render our own design-faithful "New to Waggle? Create an account" toggle,
// so hide Clerk's built-in switch link to avoid a duplicate.
footerAction: { display: 'none' },
},
};
}

View File

@@ -0,0 +1,82 @@
/**
* F5 — coach-marks first-run deferral gate regression.
*
* Pins the deferral ladder (never before completion, honors dismiss, force
* replay wins, same-session + 24h defer) and the sessionStorage accessors.
*/
import { describe, it, expect, beforeEach } from 'vitest';
import {
shouldShowCoachMarks,
readOnboardedThisSession,
readForceTour,
clearForceTour,
ONBOARDED_THIS_SESSION_KEY,
COACH_MARKS_FORCE_KEY,
COACH_MARKS_DEFER_MS,
type CoachMarksGateInput,
} from './coach-marks-gate';
const NOW = Date.parse('2026-07-04T12:00:00Z');
/** Baseline that SHOWS the carousel; each case overrides one field. */
function base(overrides: Partial<CoachMarksGateInput> = {}): CoachMarksGateInput {
return {
completed: true,
tooltipsDismissed: false,
completedAt: null,
completedThisSession: false,
forceTour: false,
now: NOW,
...overrides,
};
}
describe('shouldShowCoachMarks', () => {
it('shows when completed, not dismissed, and no deferral trips (legacy: no completedAt)', () => {
expect(shouldShowCoachMarks(base())).toBe(true);
});
it('never shows before onboarding completes', () => {
expect(shouldShowCoachMarks(base({ completed: false }))).toBe(false);
});
it('never shows once dismissed permanently', () => {
expect(shouldShowCoachMarks(base({ tooltipsDismissed: true }))).toBe(false);
});
it('force replay overrides same-session + defer', () => {
expect(shouldShowCoachMarks(base({ forceTour: true, completedThisSession: true, completedAt: NOW }))).toBe(true);
});
it('defers within the same session the wizard completed', () => {
expect(shouldShowCoachMarks(base({ completedThisSession: true }))).toBe(false);
});
it('defers within 24h of completion (12h ago)', () => {
expect(shouldShowCoachMarks(base({ completedAt: NOW - 12 * 60 * 60_000 }))).toBe(false);
});
it('shows once past the 24h deferral', () => {
expect(shouldShowCoachMarks(base({ completedAt: NOW - COACH_MARKS_DEFER_MS - 1 }))).toBe(true);
});
});
describe('sessionStorage accessors', () => {
beforeEach(() => {
window.sessionStorage.clear();
});
it('readOnboardedThisSession is false until the flag is set', () => {
expect(readOnboardedThisSession()).toBe(false);
window.sessionStorage.setItem(ONBOARDED_THIS_SESSION_KEY, '1');
expect(readOnboardedThisSession()).toBe(true);
});
it('readForceTour reflects the force flag, clearForceTour removes it', () => {
expect(readForceTour()).toBe(false);
window.sessionStorage.setItem(COACH_MARKS_FORCE_KEY, '1');
expect(readForceTour()).toBe(true);
clearForceTour();
expect(readForceTour()).toBe(false);
});
});

View File

@@ -0,0 +1,85 @@
/**
* Coach-marks (OnboardingTooltips) first-run deferral gate (F5).
*
* The tooltip carousel used to fire the instant the shell first landed —
* stacking on top of the trial-paywall dismissal and any other first-launch
* overlay. This gate defers the FIRST post-completion showing: it suppresses
* the carousel while the user just finished the wizard (same session) or within
* 24h of completion, so the very first landing stays calm and the tour shows on
* the next eligible visit. "Dismiss all" (tooltipsDismissed) and the Settings
* "Replay tour" force path are honored unchanged.
*
* Mirrors login-briefing.ts: a pure decision function plus try/catch storage
* accessors. Session/force flags live in sessionStorage (per page load);
* completedAt lives in the onboarding localStorage blob (useOnboarding).
*/
/** Defer the first post-completion showing for a day. */
export const COACH_MARKS_DEFER_MS = 24 * 60 * 60 * 1000;
/** sessionStorage: set once the wizard completes in THIS page-load session. */
export const ONBOARDED_THIS_SESSION_KEY = 'waggle:onboarded_this_session';
/** sessionStorage: set by replayTour() to bypass the deferral immediately. */
export const COACH_MARKS_FORCE_KEY = 'waggle:coachmarks_force';
export interface CoachMarksGateInput {
/** Onboarding wizard completed. */
completed: boolean;
/** User clicked "Dismiss all" (permanent). */
tooltipsDismissed: boolean;
/** Epoch ms the wizard was completed; null = legacy/returning (past first-run). */
completedAt: number | null;
/** Wizard was completed in this page-load session. */
completedThisSession: boolean;
/** Settings "Replay tour" requested an immediate show. */
forceTour: boolean;
/** Current epoch ms. */
now?: number;
}
/**
* Decide whether the coach-mark carousel may show now. Pure — reads/writes are
* the caller's responsibility.
*/
export function shouldShowCoachMarks(input: CoachMarksGateInput): boolean {
if (!input.completed) return false;
if (input.tooltipsDismissed) return false;
// Explicit user replay wins over the deferral (replayTour already flipped
// tooltipsDismissed back to false).
if (input.forceTour) return true;
if (input.completedThisSession) return false;
const now = input.now ?? Date.now();
if (input.completedAt != null && now - input.completedAt < COACH_MARKS_DEFER_MS) {
return false;
}
// Legacy states without completedAt fall through to true — they're past
// first-run, so there's nothing to defer.
return true;
}
/** sessionStorage snapshot: did the wizard complete in this session? */
export function readOnboardedThisSession(): boolean {
try {
return window.sessionStorage.getItem(ONBOARDED_THIS_SESSION_KEY) === '1';
} catch {
return false;
}
}
/** sessionStorage snapshot: has Settings requested an immediate tour replay? */
export function readForceTour(): boolean {
try {
return window.sessionStorage.getItem(COACH_MARKS_FORCE_KEY) === '1';
} catch {
return false;
}
}
/** Clear the replay-force flag once consumed (on carousel dismiss). */
export function clearForceTour(): void {
try {
window.sessionStorage.removeItem(COACH_MARKS_FORCE_KEY);
} catch {
// no-op — storage disabled
}
}

View File

@@ -0,0 +1,22 @@
import { describe, it, expect } from 'vitest';
import { buildCommandCatalog } from './command-catalog';
describe('command catalog watch-agent (#4)', () => {
it('includes a "Watch a coding agent live" entry deep-linking to watch mode', () => {
const groups = buildCommandCatalog({ chatHref: '/chat', isPro: false, billingRank: 0 });
const all = groups.flatMap((g) => g.items);
const watch = all.find((i) => i.id === 'watch-agent');
expect(watch).toBeTruthy();
expect(watch!.name).toMatch(/watch a coding agent live/i);
expect(watch!.to).toBe('/launcher?watch=1');
expect(watch!.group).toBe('do');
});
it('labels the pinned group without legacy Pro copy', () => {
const groups = buildCommandCatalog({ chatHref: '/chat', isPro: true, billingRank: 3 });
const pinned = groups.find((g) => g.key === 'pinned');
expect(pinned).toBeTruthy();
expect(pinned!.heading).toBe('Pinned');
expect(pinned!.heading).not.toMatch(/pro/i);
});
});

View File

@@ -0,0 +1,122 @@
import type { ElementType } from "react";
import { BILLING_TIER_ORDER } from "@/lib/dock-tiers";
import {
Home, MessageSquare, Brain, ListTodo, Library, UserCircle,
Plus, Rocket, Settings, Sparkles,
Network, Server, Plug, Store, Package, Shield, Clock, FolderOpen,
Lock, Activity, History, BarChart3, Users, Radio,
Gauge, Monitor, LayoutGrid, Eye,
} from "lucide-react";
/**
* Curated ⌘K catalog (design ref: design-files/screens/ia.html).
*
* The command bar holds the depth the calm spine leaves out. Every entry is
* **plain name + a mono technical subtitle** and routes to a REAL destination
* (no dead links) or fires a known overlay action. Tier-gated entries (Approvals,
* Team governance) drop below their billing rank. In power mode a "Pinned"
* group floats the power tools to the top.
*/
export type CatalogGroupKey = "pinned" | "jump" | "do" | "power";
export interface CatalogCommand {
id: string;
group: CatalogGroupKey;
/** Plain-language name. */
name: string;
/** Mono technical subtitle (the jargon, surfaced quietly). */
subtitle?: string;
/** Extra search synonyms/aliases (not shown) so legacy terms still resolve. */
keywords?: string;
icon: ElementType;
/** Route to navigate to (mutually exclusive with `action`). */
to?: string;
/** Overlay action key (handled by the integrator). */
action?: "spawn";
/** Keyboard hint shown on the right. */
meta?: string;
/** Minimum billing rank to show (FREE 0 · TRIAL 1 · TEAMS 2 · ENT 3). */
minBillingRank?: number;
/** Also floats into the Pinned group. */
pinned?: boolean;
}
export interface CatalogGroup {
key: CatalogGroupKey;
heading: string;
items: CatalogCommand[];
}
export interface CatalogContext {
/** Resolved chat route (active workspace chat tab, or fallback). */
chatHref: string;
/** Power/admin tier — shows the Pinned group. */
isPro: boolean;
/** Billing rank for tier gating. */
billingRank: number;
}
const TEAMS_RANK = BILLING_TIER_ORDER.TEAMS;
export function buildCommandCatalog(ctx: CatalogContext): CatalogGroup[] {
const { chatHref, isPro, billingRank } = ctx;
const jump: CatalogCommand[] = [
{ id: "home", group: "jump", name: "Home", subtitle: "your daily briefing", icon: Home, to: "/home" },
{ id: "workspaces", group: "jump", name: "All workspaces", subtitle: "every workspace · grid", icon: LayoutGrid, to: "/workspaces" },
{ id: "chat", group: "jump", name: "Chat", subtitle: "the work surface", icon: MessageSquare, to: chatHref },
{ id: "memory", group: "jump", name: "Memory", subtitle: "what Waggle knows · provenance kept", icon: Brain, to: "/memory" },
{ id: "agents", group: "jump", name: "Agents", subtitle: "running · scheduled · finished", keywords: "tasks agent center", icon: ListTodo, to: "/agents" },
{ id: "library", group: "jump", name: "Library", subtitle: "artifacts · files · skills", icon: Library, to: "/artifacts" },
{ id: "profile", group: "jump", name: "Your profile", subtitle: "what Waggle knows about you", icon: UserCircle, to: "/settings/profile" },
];
const doGroup: CatalogCommand[] = [
{ id: "start-task", group: "do", name: "Start a task", subtitle: "new agent run", icon: Plus, action: "spawn" },
{ id: "launch-agent", group: "do", name: "Launch a coding agent", subtitle: "Claude Code · Cursor · Codex — shares this hive", icon: Rocket, to: "/launcher" },
{ id: "watch-agent", group: "do", name: "Watch a coding agent live", subtitle: "Claude Code · Cursor · Codex — stream its output", keywords: "observe pty terminal live output tail", icon: Eye, to: "/launcher?watch=1" },
{ id: "settings", group: "do", name: "Settings", subtitle: "models · failover · permissions · plan", icon: Settings, to: "/settings" },
{ id: "upgrade", group: "do", name: "Upgrade to Team", subtitle: "plans · billing · invoices", icon: Sparkles, to: "/settings?tab=billing" },
];
const power: CatalogCommand[] = [
{ id: "swarm", group: "power", name: "Run a team of agents", subtitle: "waggle-dance · swarm", icon: Network, to: "/waggle-dance", pinned: true },
{ id: "connect-mcp", group: "power", name: "Connect a tool", subtitle: "MCP servers", icon: Server, to: "/mcps" },
{ id: "connectors", group: "power", name: "Connectors", subtitle: "integrations", icon: Plug, to: "/connectors", pinned: true },
{ id: "marketplace", group: "power", name: "Add a capability", subtitle: "marketplace · skills, connectors, tools", icon: Store, to: "/marketplace" },
{ id: "skills", group: "power", name: "Skills", subtitle: "teach your agents new abilities", icon: Package, to: "/skills" },
{ id: "approvals", group: "power", name: "Approvals", subtitle: "pending agent actions", icon: Shield, to: "/approvals", minBillingRank: TEAMS_RANK, pinned: true },
{ id: "automations", group: "power", name: "Automations", subtitle: "scheduled jobs", icon: Clock, to: "/automations" },
{ id: "files", group: "power", name: "Files & storage", subtitle: "where this workspace lives", icon: FolderOpen, to: "/files" },
{ id: "room", group: "power", name: "Room", subtitle: "work alongside agents live", icon: Users, to: "/room" },
{ id: "vault", group: "power", name: "Secrets", subtitle: "encrypted vault", icon: Lock, to: "/settings/vault" },
{ id: "mission-control", group: "power", name: "Mission Control", subtitle: "system health", keywords: "cockpit connectors fleet status", icon: Activity, to: "/settings/mission-control" },
{ id: "timeline", group: "power", name: "Timeline", subtitle: "activity history", icon: History, to: "/settings/timeline" },
{ id: "events", group: "power", name: "Events & logs", subtitle: "live activity feed", icon: Radio, to: "/settings/events" },
{ id: "usage", group: "power", name: "Usage & cost", subtitle: "tokens · spend", icon: BarChart3, to: "/settings/usage" },
{ id: "benchmarks", group: "power", name: "Benchmarks", subtitle: "capabilities · memory SOTA", icon: Gauge, to: "/benchmarks" },
{ id: "platform", group: "power", name: "Platform & roadmap", subtitle: "desktop · what's coming", icon: Monitor, to: "/platform" },
{ id: "team", group: "power", name: "Team governance", subtitle: "rules · permissions · oversight", icon: Shield, to: "/team", minBillingRank: TEAMS_RANK },
];
const gate = (items: CatalogCommand[]): CatalogCommand[] =>
items.filter((i) => i.minBillingRank === undefined || billingRank >= i.minBillingRank);
const groups: CatalogGroup[] = [];
if (isPro) {
const pinnedItems = [...jump, ...doGroup, ...power]
.filter((i) => i.pinned && (i.minBillingRank === undefined || billingRank >= i.minBillingRank))
.map((i) => ({ ...i, id: `pin-${i.id}`, group: "pinned" as const }));
if (pinnedItems.length > 0) {
groups.push({ key: "pinned", heading: "Pinned", items: pinnedItems });
}
}
groups.push({ key: "jump", heading: "Jump to", items: gate(jump) });
groups.push({ key: "do", heading: "Do", items: gate(doGroup) });
groups.push({ key: "power", heading: "Power tools", items: gate(power) });
return groups;
}

View File

@@ -0,0 +1,73 @@
/**
* R5-001 — context-menu action indexing regression test.
*
* Locks the invariant that the render-side highlight index agrees with the
* filtered list the Enter handler activates from, even when disabled
* (non-separator) items precede the focused row.
*/
import { describe, it, expect } from 'vitest';
import { isActionItem, actionIndexForRenderItem, type ContextMenuActionItem } from './context-menu-index';
describe('isActionItem', () => {
it('treats a plain item as an action item', () => {
expect(isActionItem({})).toBe(true);
});
it('excludes separators', () => {
expect(isActionItem({ separator: true })).toBe(false);
});
it('excludes disabled items', () => {
expect(isActionItem({ disabled: true })).toBe(false);
});
});
describe('actionIndexForRenderItem', () => {
it('maps positions one-to-one when every item is an action item', () => {
const items: ContextMenuActionItem[] = [{}, {}, {}];
expect(actionIndexForRenderItem(items, 0)).toBe(0);
expect(actionIndexForRenderItem(items, 1)).toBe(1);
expect(actionIndexForRenderItem(items, 2)).toBe(2);
});
it('returns null for separator and disabled rows', () => {
const items: ContextMenuActionItem[] = [{}, { separator: true }, { disabled: true }, {}];
expect(actionIndexForRenderItem(items, 1)).toBeNull();
expect(actionIndexForRenderItem(items, 2)).toBeNull();
});
it('does NOT consume an index for a disabled row (highlight matches activation)', () => {
// [A(enabled), B(disabled), C(enabled)] — Enter handler list is [A, C].
// Arrowing once gives focusIndex=1 → activates C. The render index for C
// must therefore also be 1, NOT 2, so the highlight lands on C, not B.
const items: ContextMenuActionItem[] = [{}, { disabled: true }, {}];
expect(actionIndexForRenderItem(items, 0)).toBe(0); // A
expect(actionIndexForRenderItem(items, 1)).toBeNull(); // B (disabled, never highlightable)
expect(actionIndexForRenderItem(items, 2)).toBe(1); // C — agrees with actionItems[1]
});
it('stays aligned with the filtered actionItems list the Enter handler uses', () => {
const items: ContextMenuActionItem[] = [
{ separator: true },
{}, // action 0
{ disabled: true },
{}, // action 1
{ separator: true },
{ disabled: true },
{}, // action 2
];
const actionItems = items.filter(isActionItem);
items.forEach((_, i) => {
const idx = actionIndexForRenderItem(items, i);
if (idx !== null) {
// The row mapped to action index `idx` must be the SAME object the
// Enter handler would activate at actionItems[idx].
expect(items[i]).toBe(actionItems[idx]);
}
});
expect(actionItems.length).toBe(3);
});
it('returns null for an out-of-range index', () => {
const items: ContextMenuActionItem[] = [{}];
expect(actionIndexForRenderItem(items, 5)).toBeNull();
});
});

View File

@@ -0,0 +1,38 @@
/**
* R5-001 — context-menu action indexing.
*
* The ContextMenu keyboard handler activates from the list of *action* items —
* `items.filter(i => !i.separator && !i.disabled)` — indexed by `focusIndex`.
* The render loop must highlight using the SAME indexing, otherwise the
* highlighted row and the row Enter activates disagree whenever a disabled
* (non-separator) item precedes the focused one.
*
* These pure helpers are the single source of truth so highlight and
* activation always agree and disabled rows are never highlightable.
*/
export interface ContextMenuActionItem {
separator?: boolean;
disabled?: boolean;
}
/** True when an item participates in keyboard navigation/activation. */
export function isActionItem(item: ContextMenuActionItem): boolean {
return !item.separator && !item.disabled;
}
/**
* Action index for the item rendered at position `i`, or null when that item
* is a separator or disabled (i.e. not focusable). The returned index lines up
* exactly with `items.filter(isActionItem)` — the same list the Enter handler
* activates from.
*/
export function actionIndexForRenderItem(items: ReadonlyArray<ContextMenuActionItem>, i: number): number | null {
const item = items[i];
if (!item || !isActionItem(item)) return null;
let actionIndex = 0;
for (let n = 0; n < i; n++) {
if (isActionItem(items[n])) actionIndex++;
}
return actionIndex;
}

View File

@@ -0,0 +1,222 @@
/**
* L-16 — context-rail-fetch vitests. Pure helper; mocked adapter.
*/
import { describe, it, expect } from 'vitest';
import {
buildMemoryQuery,
rankNeighbors,
fetchContextRailItems,
DEFAULT_MEMORY_LIMIT,
DEFAULT_NEIGHBOR_LIMIT,
type ContextRailAdapter,
type ContextRailTarget,
} from './context-rail-fetch';
import type { MemoryFrame, KGNode, KGEdge } from './types';
function mkFrame(overrides: Partial<MemoryFrame> = {}): MemoryFrame {
return {
id: 'f1',
type: 'fact',
title: 'Frame one',
content: 'First line of frame content\nsecond line that should not show up in title',
importance: 50,
timestamp: '2026-04-19T12:00:00Z',
workspaceId: 'ws-1',
...overrides,
};
}
function mkNode(id: string, label: string, type = 'concept'): KGNode {
return { id, label, type };
}
function mkEdge(source: string, target: string, relationship = 'relates-to'): KGEdge {
return { source, target, relationship };
}
function mkAdapter(
searchMemory: (query: string, scope?: string) => Promise<MemoryFrame[]>,
getKnowledgeGraph: (ws: string, scope?: 'current' | 'personal' | 'all')
=> Promise<{ nodes: KGNode[]; edges: KGEdge[] }>,
): ContextRailAdapter {
return { searchMemory, getKnowledgeGraph };
}
describe('buildMemoryQuery', () => {
it('uses label for entity/frame/message targets', () => {
const frame: ContextRailTarget = { type: 'frame', id: 'f1', label: 'Claude' };
const entity: ContextRailTarget = { type: 'entity', id: 'e1', label: 'Anthropic' };
const message: ContextRailTarget = { type: 'message', id: 'm1', label: 'hi there' };
expect(buildMemoryQuery(frame)).toBe('Claude');
expect(buildMemoryQuery(entity)).toBe('Anthropic');
expect(buildMemoryQuery(message)).toBe('hi there');
});
it('falls back to id for file targets with empty label', () => {
const target: ContextRailTarget = { type: 'file', id: '/notes/ideas.md', label: '' };
expect(buildMemoryQuery(target)).toBe('/notes/ideas.md');
});
it('uses label for file targets when present', () => {
const target: ContextRailTarget = { type: 'file', id: '/notes/ideas.md', label: 'ideas.md' };
expect(buildMemoryQuery(target)).toBe('ideas.md');
});
});
describe('rankNeighbors', () => {
it('returns neighbors + edges around the target entity', () => {
const nodes = [mkNode('a', 'A'), mkNode('b', 'B'), mkNode('c', 'C'), mkNode('d', 'D')];
const edges = [mkEdge('a', 'b'), mkEdge('c', 'a'), mkEdge('b', 'd')];
const { neighbors, relations } = rankNeighbors('a', nodes, edges);
expect(neighbors.map(n => n.id).sort()).toEqual(['b', 'c']);
expect(relations).toHaveLength(2);
});
it('ranks neighbors by degree, ties broken by label', () => {
// b has degree 3, c has degree 1, d has degree 1. Among c/d (same degree),
// label order decides: "C" < "D".
const nodes = [mkNode('a', 'A'), mkNode('b', 'B'), mkNode('c', 'C'), mkNode('d', 'D')];
const edges = [
mkEdge('a', 'b'),
mkEdge('a', 'c'),
mkEdge('a', 'd'),
mkEdge('b', 'c'),
mkEdge('b', 'd'),
];
const { neighbors } = rankNeighbors('a', nodes, edges);
expect(neighbors.map(n => n.id)).toEqual(['b', 'c', 'd']);
});
it('ignores self-loops', () => {
const nodes = [mkNode('a', 'A'), mkNode('b', 'B')];
const edges = [mkEdge('a', 'a'), mkEdge('a', 'b')];
const { neighbors } = rankNeighbors('a', nodes, edges);
expect(neighbors.map(n => n.id)).toEqual(['b']);
});
it('returns empty when the target entity has no edges', () => {
const nodes = [mkNode('a', 'A'), mkNode('b', 'B')];
const edges = [mkEdge('b', 'a')];
const { neighbors, relations } = rankNeighbors('z', nodes, edges);
expect(neighbors).toEqual([]);
expect(relations).toEqual([]);
});
});
describe('fetchContextRailItems', () => {
it('returns memory frames for a frame target', async () => {
const adapter = mkAdapter(
async () => [mkFrame()],
async () => ({ nodes: [], edges: [] }),
);
const target: ContextRailTarget = { type: 'frame', id: 'f1', label: 'Claude' };
const items = await fetchContextRailItems(target, adapter);
expect(items).toHaveLength(1);
expect(items[0].kind).toBe('memory');
expect(items[0].id).toBe('frame-f1');
expect(items[0].title).toBe('First line of frame content');
});
it('adds entity + relation items for an entity target, in KG-first order', async () => {
const nodes = [
mkNode('target', 'Target', 'person'),
mkNode('neighbor-1', 'N1'),
mkNode('neighbor-2', 'N2'),
];
const edges = [mkEdge('target', 'neighbor-1', 'works-with'), mkEdge('neighbor-2', 'target', 'reports-to')];
const adapter = mkAdapter(
async () => [mkFrame({ id: 'mem-1', content: 'Target info' })],
async () => ({ nodes, edges }),
);
const target: ContextRailTarget = { type: 'entity', id: 'target', label: 'Target', workspaceId: 'ws-1' };
const items = await fetchContextRailItems(target, adapter);
// Entity-first ordering: entities, then relations, then memory.
expect(items.map(i => i.kind)).toEqual(['entity', 'entity', 'relation', 'relation', 'memory']);
expect(items.find(i => i.id === 'entity-neighbor-1')).toBeDefined();
});
it('deduplicates items by id', async () => {
const adapter = mkAdapter(
async () => [mkFrame({ id: 'dup' }), mkFrame({ id: 'dup' }), mkFrame({ id: 'other' })],
async () => ({ nodes: [], edges: [] }),
);
const target: ContextRailTarget = { type: 'frame', id: 'f1', label: 'x' };
const items = await fetchContextRailItems(target, adapter);
expect(items.map(i => i.id).sort()).toEqual(['frame-dup', 'frame-other']);
});
it('respects memoryLimit opt', async () => {
const frames = Array.from({ length: 25 }, (_, i) => mkFrame({ id: `f${i}` }));
const adapter = mkAdapter(async () => frames, async () => ({ nodes: [], edges: [] }));
const target: ContextRailTarget = { type: 'frame', id: 'root', label: 'q' };
const items = await fetchContextRailItems(target, adapter, { memoryLimit: 3 });
expect(items).toHaveLength(3);
});
it('caps entity neighbors at neighborLimit', async () => {
const nodes = [
mkNode('target', 'Target'),
...Array.from({ length: 10 }, (_, i) => mkNode(`n${i}`, `N${i}`)),
];
const edges = Array.from({ length: 10 }, (_, i) => mkEdge('target', `n${i}`));
const adapter = mkAdapter(
async () => [],
async () => ({ nodes, edges }),
);
const target: ContextRailTarget = { type: 'entity', id: 'target', label: 'Target' };
const items = await fetchContextRailItems(target, adapter, { neighborLimit: 3, relationLimit: 0 });
expect(items.filter(i => i.kind === 'entity')).toHaveLength(3);
expect(items.filter(i => i.kind === 'relation')).toHaveLength(0);
});
it('falls back to memory when the KG fetch throws', async () => {
const adapter = mkAdapter(
async () => [mkFrame()],
async () => { throw new Error('graph unreachable'); },
);
const target: ContextRailTarget = { type: 'entity', id: 'e1', label: 'E' };
const items = await fetchContextRailItems(target, adapter);
expect(items).toHaveLength(1);
expect(items[0].kind).toBe('memory');
});
it('returns the partial KG list when memory search throws', async () => {
const adapter = mkAdapter(
async () => { throw new Error('memory unreachable'); },
async () => ({
nodes: [mkNode('e1', 'E'), mkNode('n1', 'N1')],
edges: [mkEdge('e1', 'n1')],
}),
);
const target: ContextRailTarget = { type: 'entity', id: 'e1', label: 'E' };
const items = await fetchContextRailItems(target, adapter);
// One neighbor + one relation; no memory.
expect(items.map(i => i.kind)).toEqual(['entity', 'relation']);
});
it('returns an empty list when both sources fail', async () => {
const adapter = mkAdapter(
async () => { throw new Error('x'); },
async () => { throw new Error('y'); },
);
const target: ContextRailTarget = { type: 'frame', id: 'f1', label: 'nope' };
const items = await fetchContextRailItems(target, adapter);
expect(items).toEqual([]);
});
it('uses provided workspaceId for KG fetches', async () => {
let receivedWs = '';
const adapter = mkAdapter(
async () => [],
async (ws) => { receivedWs = ws; return { nodes: [], edges: [] }; },
);
const target: ContextRailTarget = { type: 'entity', id: 'x', label: 'X', workspaceId: 'my-ws' };
await fetchContextRailItems(target, adapter);
expect(receivedWs).toBe('my-ws');
});
it('exports the canonical default limits', () => {
expect(DEFAULT_MEMORY_LIMIT).toBe(10);
expect(DEFAULT_NEIGHBOR_LIMIT).toBe(5);
});
});

View File

@@ -0,0 +1,198 @@
/**
* L-16 — ContextRail fetch helper.
*
* Extracted out of ContextRail.tsx so the "what to fetch for which target
* type" logic is testable without rendering React. The helper does per-type
* fan-out: memory frames for every target, plus (for entity targets) the
* surrounding KG subgraph — neighbors + edges — so clicking a graph node
* surfaces structural context, not just substring-matched memory hits.
*
* Pure contract: take a target + adapter, return a capped, deduplicated list.
* No React, no DOM, no module-level state. Safe under jsdom.
*/
import type { MemoryFrame, KGNode, KGEdge } from './types';
// Kept in sync with ContextRail.tsx; duplicated here instead of imported to
// keep the helper free of UI-layer dependencies. The shape is small and
// stable — a type-identity drift would show up as a tsc error at the caller.
export interface ContextRailTarget {
type: 'file' | 'frame' | 'entity' | 'message';
id: string;
label: string;
workspaceId?: string;
}
export interface ContextRailItem {
id: string;
kind: 'memory' | 'entity' | 'relation';
title: string;
content: string;
importance?: string;
timestamp?: string;
}
export interface ContextRailAdapter {
searchMemory: (query: string, scope?: string) => Promise<MemoryFrame[]>;
getKnowledgeGraph: (
workspaceId: string,
scope?: 'current' | 'personal' | 'all',
) => Promise<{ nodes: KGNode[]; edges: KGEdge[] }>;
}
export interface FetchOptions {
memoryLimit?: number;
neighborLimit?: number;
relationLimit?: number;
}
export const DEFAULT_MEMORY_LIMIT = 10;
export const DEFAULT_NEIGHBOR_LIMIT = 5;
export const DEFAULT_RELATION_LIMIT = 5;
/**
* Build the search query for the memory pass. Use the label for human-
* readable targets; fall back to the id for files where the label is just
* the filename and the id (path) is more likely to hit a frame.
*/
export function buildMemoryQuery(target: ContextRailTarget): string {
if (target.type === 'file') {
return target.label || target.id;
}
return target.label;
}
function frameToItem(frame: MemoryFrame): ContextRailItem {
const rawContent = typeof frame.content === 'string'
? frame.content
: JSON.stringify(frame.content);
const firstLine = rawContent.split('\n')[0] ?? '';
const title = firstLine.trim().slice(0, 80) || frame.title || 'Memory';
// MemoryFrame.importance is numeric at the type level but older callers
// sometimes hand in a string label. Coerce to string for display; do NOT
// invent category buckets — that's the existing ContextRail.tsx concern.
const importance = frame.importance != null
? String(frame.importance)
: undefined;
return {
id: `frame-${frame.id}`,
kind: 'memory',
title,
content: rawContent,
importance,
timestamp: frame.timestamp,
};
}
function nodeToItem(node: KGNode): ContextRailItem {
return {
id: `entity-${node.id}`,
kind: 'entity',
title: node.label,
content: `${node.type}: ${node.label}`,
};
}
function edgeToItem(edge: KGEdge, nodesById: Map<string, KGNode>): ContextRailItem {
const source = nodesById.get(edge.source);
const target = nodesById.get(edge.target);
const srcLabel = source?.label ?? edge.source;
const tgtLabel = target?.label ?? edge.target;
return {
id: `relation-${edge.source}-${edge.relationship}-${edge.target}`,
kind: 'relation',
title: `${srcLabel} → ${tgtLabel}`,
content: `${srcLabel} ${edge.relationship} ${tgtLabel}`,
};
}
/**
* Rank KG neighbors by connection count (ties broken by label) so high-
* centrality entities surface first. Keeps the top-N selection deterministic,
* which matters for the relation list (stable ordering across renders) and
* for vitest snapshots.
*/
export function rankNeighbors(
entityId: string,
nodes: KGNode[],
edges: KGEdge[],
): { neighbors: KGNode[]; relations: KGEdge[] } {
const nodesById = new Map(nodes.map(n => [n.id, n] as const));
const neighborIds = new Set<string>();
const relations: KGEdge[] = [];
for (const edge of edges) {
if (edge.source === entityId && edge.target !== entityId) {
neighborIds.add(edge.target);
relations.push(edge);
} else if (edge.target === entityId && edge.source !== entityId) {
neighborIds.add(edge.source);
relations.push(edge);
}
}
const degree: Record<string, number> = {};
for (const e of edges) {
degree[e.source] = (degree[e.source] ?? 0) + 1;
degree[e.target] = (degree[e.target] ?? 0) + 1;
}
const neighbors = [...neighborIds]
.map(id => nodesById.get(id))
.filter((n): n is KGNode => n !== undefined)
.sort((a, b) => {
const diff = (degree[b.id] ?? 0) - (degree[a.id] ?? 0);
return diff !== 0 ? diff : a.label.localeCompare(b.label);
});
return { neighbors, relations };
}
/**
* Main entry point. Fans out to memory + KG depending on target type,
* deduplicates by id, and returns a single flat list suitable for rendering.
*
* Error policy: any failing branch is swallowed — we prefer returning a
* partial list over surfacing a tangled error. The rail is an auxiliary UI;
* a broken KG fetch should not blank out the memory results.
*/
export async function fetchContextRailItems(
target: ContextRailTarget,
adapter: ContextRailAdapter,
opts: FetchOptions = {},
): Promise<ContextRailItem[]> {
const memoryLimit = opts.memoryLimit ?? DEFAULT_MEMORY_LIMIT;
const neighborLimit = opts.neighborLimit ?? DEFAULT_NEIGHBOR_LIMIT;
const relationLimit = opts.relationLimit ?? DEFAULT_RELATION_LIMIT;
const items: ContextRailItem[] = [];
const seen = new Set<string>();
const push = (item: ContextRailItem) => {
if (seen.has(item.id)) return;
seen.add(item.id);
items.push(item);
};
// Entity targets go to the KG first so structural context leads the list.
if (target.type === 'entity') {
try {
const ws = target.workspaceId ?? 'current';
const graph = await adapter.getKnowledgeGraph(ws, 'all');
const { neighbors, relations } = rankNeighbors(target.id, graph.nodes, graph.edges);
const nodesById = new Map(graph.nodes.map(n => [n.id, n] as const));
for (const n of neighbors.slice(0, neighborLimit)) push(nodeToItem(n));
for (const e of relations.slice(0, relationLimit)) push(edgeToItem(e, nodesById));
} catch {
// Graph fetch failed — fall through to memory search.
}
}
// Memory pass — every target type benefits from this.
try {
const frames = await adapter.searchMemory(buildMemoryQuery(target), 'all');
for (const f of frames.slice(0, memoryLimit)) push(frameToItem(f));
} catch {
// Leave whatever we already gathered from the graph pass.
}
return items;
}

View File

@@ -0,0 +1,141 @@
/**
* M-44 / P26 — cron presets + expression summariser regression.
* Pure functions, no React, no network.
*/
import { describe, it, expect } from 'vitest';
import {
CRON_SCHEDULE_PRESETS,
CRON_JOB_TYPES,
DEFAULT_CRON_PRESET_ID,
DEFAULT_CRON_JOB_TYPE,
getCronPreset,
presetForExpr,
describeCronExpr,
humanizeCron,
isPlausibleCronExpr,
} from './cron-presets';
describe('cron preset catalog', () => {
it('has a non-empty preset list', () => {
expect(CRON_SCHEDULE_PRESETS.length).toBeGreaterThan(3);
});
it('every preset has a plausible cron expression', () => {
for (const p of CRON_SCHEDULE_PRESETS) {
expect(isPlausibleCronExpr(p.cronExpr), `${p.id}: ${p.cronExpr}`).toBe(true);
}
});
it('preset ids are unique', () => {
const ids = CRON_SCHEDULE_PRESETS.map(p => p.id);
expect(new Set(ids).size).toBe(ids.length);
});
it('DEFAULT_CRON_PRESET_ID refers to a real preset', () => {
expect(getCronPreset(DEFAULT_CRON_PRESET_ID)).toBeDefined();
});
});
describe('cron job type catalog', () => {
it('has at least one entry per supported CronJobType', () => {
const ids = CRON_JOB_TYPES.map(j => j.id);
// Ensure the default is in the list.
expect(ids).toContain(DEFAULT_CRON_JOB_TYPE);
});
it('every job type has a non-empty label and description', () => {
for (const j of CRON_JOB_TYPES) {
expect(j.label.length, `${j.id} label`).toBeGreaterThan(0);
expect(j.description.length, `${j.id} description`).toBeGreaterThan(0);
}
});
it('ids are unique', () => {
const ids = CRON_JOB_TYPES.map(j => j.id);
expect(new Set(ids).size).toBe(ids.length);
});
});
describe('presetForExpr', () => {
it('returns the exact preset for a known expression', () => {
expect(presetForExpr('0 9 * * *')?.id).toBe('daily-9am');
});
it('tolerates leading / trailing whitespace', () => {
expect(presetForExpr(' 0 9 * * * ')?.id).toBe('daily-9am');
});
it('collapses internal whitespace before matching', () => {
expect(presetForExpr('0 9 * * *')?.id).toBe('daily-9am');
});
it('returns undefined for a custom expression', () => {
expect(presetForExpr('15 7 * * *')).toBeUndefined();
});
});
describe('describeCronExpr', () => {
it('returns the preset summary for a known expression', () => {
expect(describeCronExpr('0 9 * * *')).toBe('Every day at 9:00 AM');
});
it('humanises a valid-shape custom expression instead of leaking raw cron', () => {
expect(describeCronExpr('15 7 * * *')).toBe('Every day at 7:15 AM');
});
it('falls back to Custom schedule only for shapes it cannot describe', () => {
expect(describeCronExpr('0 9 1-5 * *')).toBe('Custom schedule: 0 9 1-5 * *');
});
it('reports "no schedule set" for an empty string', () => {
expect(describeCronExpr('')).toBe('No schedule set');
expect(describeCronExpr(' ')).toBe('No schedule set');
});
it('reports a validity hint for a malformed expression', () => {
expect(describeCronExpr('not-cron')).toMatch(/Not a valid cron expression/);
expect(describeCronExpr('0 9 * *')).toMatch(/Not a valid cron expression/);
});
});
describe('humanizeCron (no raw cron leaks to users)', () => {
it('humanises the QA-brief examples', () => {
expect(humanizeCron('0 5 * * *')).toBe('Every day at 5:00 AM');
expect(humanizeCron('0 10 * * 3')).toBe('Wednesdays at 10:00 AM');
});
it('humanises multi-day, every-N-minutes, hourly, and monthly', () => {
expect(humanizeCron('30 17 * * 1,5')).toBe('Mondays and Fridays at 5:30 PM');
expect(humanizeCron('*/15 * * * *')).toBe('Every 15 minutes');
expect(humanizeCron('20 * * * *')).toBe('Every hour at :20');
expect(humanizeCron('0 8 15 * *')).toBe('On the 15th of every month at 8:00 AM');
expect(humanizeCron('0 0 * * *')).toBe('Every day at 12:00 AM');
expect(humanizeCron('0 12 * * *')).toBe('Every day at 12:00 PM');
});
it('returns null for shapes it cannot confidently describe', () => {
expect(humanizeCron('0 9 1-5 * *')).toBeNull();
expect(humanizeCron('not cron')).toBeNull();
expect(humanizeCron('0 9 * *')).toBeNull();
});
});
describe('isPlausibleCronExpr', () => {
it('accepts 5-field whitespace-separated expressions', () => {
expect(isPlausibleCronExpr('0 9 * * *')).toBe(true);
expect(isPlausibleCronExpr('*/5 * * * *')).toBe(true);
expect(isPlausibleCronExpr('0 9 * * 1-5')).toBe(true);
});
it('rejects non-5-field strings', () => {
expect(isPlausibleCronExpr('')).toBe(false);
expect(isPlausibleCronExpr('0 9 * *')).toBe(false);
expect(isPlausibleCronExpr('0 9 * * * *')).toBe(false);
});
it('rejects strings with empty fields after collapsing whitespace', () => {
// " 0 9 * * *" split by /\s+/ yields ['', '0', '9', '*', '*', '*'] — 6 parts.
// Current contract: 5 non-empty fields, extras reject. Documents the
// boundary so a regex tweak can't silently loosen it.
expect(isPlausibleCronExpr(' 0 9 * * *')).toBe(true); // leading ws trimmed
expect(isPlausibleCronExpr('0 9 * * * ')).toBe(true); // trailing ws trimmed
});
});

View File

@@ -0,0 +1,181 @@
/**
* Cron schedule presets + human-readable summary helper (M-44 / P26).
*
* The /api/cron create endpoint requires both a `cronExpr` and a
* `jobType` from the CronJobType union. Raw cron syntax is intimidating
* and historically the client shipped neither correctly (schedule field
* + no jobType), so this module provides:
* - Named cron-expression presets covering the most-common cadences.
* - A jobType catalog with human-facing labels and descriptions.
* - A cheap cron→English summariser for the preset expressions; when
* the user types a custom expression, the summariser returns
* "Custom schedule" so we don't mislead.
*/
export type CronJobType =
| 'agent_task'
| 'memory_consolidation'
| 'workspace_health'
| 'proactive'
| 'prompt_optimization'
| 'monthly_assessment';
export interface CronSchedulePreset {
id: string;
label: string;
cronExpr: string;
/** What the preset means in plain English (for the form hint + summary). */
summary: string;
}
export interface CronJobTypeOption {
id: CronJobType;
label: string;
description: string;
}
/** Cron preset list, keyed by human-recognisable cadence. */
export const CRON_SCHEDULE_PRESETS: readonly CronSchedulePreset[] = [
{ id: 'daily-9am', label: 'Daily at 9:00 AM', cronExpr: '0 9 * * *', summary: 'Every day at 9:00 AM' },
{ id: 'daily-6pm', label: 'Daily at 6:00 PM', cronExpr: '0 18 * * *', summary: 'Every day at 6:00 PM' },
{ id: 'weekday-9am', label: 'Weekdays at 9:00 AM', cronExpr: '0 9 * * 1-5', summary: 'Mon–Fri at 9:00 AM' },
{ id: 'weekly-mon-9am', label: 'Mondays at 9:00 AM', cronExpr: '0 9 * * 1', summary: 'Every Monday at 9:00 AM' },
{ id: 'monthly-1st-9am', label: 'Monthly (1st at 9:00 AM)', cronExpr: '0 9 1 * *', summary: 'First of the month at 9:00 AM' },
{ id: 'hourly', label: 'Every hour', cronExpr: '0 * * * *', summary: 'Every hour on the hour' },
] as const;
/** Job type catalog with user-facing copy. */
export const CRON_JOB_TYPES: readonly CronJobTypeOption[] = [
{
id: 'memory_consolidation',
label: 'Consolidate memory',
description: 'Summarise new frames + prune duplicates. Recommended daily.',
},
{
id: 'workspace_health',
label: 'Workspace health check',
description: 'Surface stale sessions, broken connectors, or quota warnings.',
},
{
id: 'agent_task',
label: 'Run an agent task',
description: 'Kick off a sub-agent with a saved prompt at this schedule.',
},
{
id: 'proactive',
label: 'Proactive briefing',
description: 'Generate a short "what changed" digest to nudge attention.',
},
{
id: 'prompt_optimization',
label: 'Optimise agent prompts',
description: 'Run the evolution loop over recent traces; deploy any wins.',
},
{
id: 'monthly_assessment',
label: 'Monthly assessment',
description: 'Longer-form review: memory growth, entity coverage, goal progress.',
},
] as const;
export const DEFAULT_CRON_PRESET_ID = 'daily-9am';
export const DEFAULT_CRON_JOB_TYPE: CronJobType = 'memory_consolidation';
/** Map a preset id back to its preset row. */
export function getCronPreset(id: string): CronSchedulePreset | undefined {
return CRON_SCHEDULE_PRESETS.find(p => p.id === id);
}
/** Map a cronExpr back to a preset row if one matches exactly. */
export function presetForExpr(cronExpr: string): CronSchedulePreset | undefined {
const trimmed = cronExpr.trim().replace(/\s+/g, ' ');
return CRON_SCHEDULE_PRESETS.find(p => p.cronExpr === trimmed);
}
/**
* Short English summary for the preview text under the schedule input.
* Returns the matching preset's summary when the expression hits one
* exactly, or a generic "Custom schedule: <expr>" when it doesn't. The
* summary is advisory only — server-side evaluation remains the source
* of truth for what actually runs.
*/
export function describeCronExpr(cronExpr: string): string {
const preset = presetForExpr(cronExpr);
if (preset) return preset.summary;
const trimmed = cronExpr.trim();
if (!trimmed) return 'No schedule set';
if (!isPlausibleCronExpr(trimmed)) return `Not a valid cron expression (expected 5 fields)`;
return humanizeCron(trimmed) ?? `Custom schedule: ${trimmed}`;
}
const CRON_DOW = ['Sundays', 'Mondays', 'Tuesdays', 'Wednesdays', 'Thursdays', 'Fridays', 'Saturdays'];
function formatCronTime(min: string, hour: string): string | null {
if (!/^\d+$/.test(min) || !/^\d+$/.test(hour)) return null;
const h = Number(hour);
const m = Number(min);
if (h > 23 || m > 59) return null;
const ampm = h < 12 ? 'AM' : 'PM';
const h12 = h % 12 === 0 ? 12 : h % 12;
return `${h12}:${String(m).padStart(2, '0')} ${ampm}`;
}
function ordinal(d: number): string {
if (d % 10 === 1 && d !== 11) return `${d}st`;
if (d % 10 === 2 && d !== 12) return `${d}nd`;
if (d % 10 === 3 && d !== 13) return `${d}rd`;
return `${d}th`;
}
/**
* Humanise common cron expressions to plain English ("Mondays at 10:00 AM",
* "Every day at 5:00 AM", "Every 15 minutes"). No external dependency — covers
* the cases the scheduler actually produces; returns null for anything it can't
* describe confidently, so describeCronExpr falls back to "Custom schedule".
*/
export function humanizeCron(cronExpr: string): string | null {
const parts = cronExpr.trim().split(/\s+/);
if (parts.length !== 5) return null;
const [min, hour, dom, mon, dow] = parts;
const allDate = dom === '*' && mon === '*' && dow === '*';
// Every N minutes
const everyMin = min.match(/^\*\/(\d+)$/);
if (everyMin && hour === '*' && allDate) return `Every ${everyMin[1]} minutes`;
// Every hour at :MM
if (/^\d+$/.test(min) && hour === '*' && allDate) {
return `Every hour at :${String(Number(min)).padStart(2, '0')}`;
}
const time = formatCronTime(min, hour);
if (!time) return null;
// Daily
if (allDate) return `Every day at ${time}`;
// Weekly (one or more days of week), any month
if (dom === '*' && mon === '*' && /^[0-6](,[0-6])*$/.test(dow)) {
const days = dow.split(',').map((d) => CRON_DOW[Number(d)]);
const phrase =
days.length === 1 ? days[0]
: days.length === 2 ? `${days[0]} and ${days[1]}`
: `${days.slice(0, -1).join(', ')} and ${days[days.length - 1]}`;
return `${phrase} at ${time}`;
}
// Monthly on a fixed day-of-month, any month
if (/^\d+$/.test(dom) && Number(dom) >= 1 && Number(dom) <= 31 && mon === '*' && dow === '*') {
return `On the ${ordinal(Number(dom))} of every month at ${time}`;
}
return null;
}
/**
* Very-surface-level plausibility check — 5 whitespace-separated
* non-empty fields. The server's validator is authoritative; this
* only exists to label the UI preview honestly when the user is
* mid-edit and the expression can't yet match a preset.
*/
export function isPlausibleCronExpr(cronExpr: string): boolean {
const parts = cronExpr.trim().split(/\s+/);
if (parts.length !== 5) return false;
return parts.every(p => p.length > 0);
}

View File

@@ -0,0 +1 @@
export const DATE_LOCALE = 'en-US' as const;

View File

@@ -0,0 +1,10 @@
/**
* Decode HTML entities in a string (e.g. &#x27; → ').
* Safe: uses a textarea which only decodes entities — does not execute scripts.
* The textarea.innerHTML setter decodes entities, and textarea.value returns plain text.
*/
export function decodeHtmlEntities(text: string): string {
const textarea = document.createElement('textarea');
textarea.innerHTML = text;
return textarea.value;
}

View File

@@ -0,0 +1,67 @@
import { describe, it, expect } from 'vitest';
import { dedupePacks, packKey } from './dedupe-packs';
import type { SkillPack } from '@/lib/types';
const pack = (over: Partial<SkillPack>): SkillPack => ({
id: 'x',
name: 'X',
description: '',
category: 'research',
skills: [],
installed: false,
trust: 'community',
...over,
});
describe('packKey', () => {
it('prefers id over name', () => {
expect(packKey(pack({ id: 'abc', name: 'Different' }))).toBe('abc');
});
it('falls back to name when id is empty', () => {
expect(packKey(pack({ id: '', name: 'Only Name' }))).toBe('Only Name');
});
it('returns empty string when both missing', () => {
expect(packKey(pack({ id: '', name: '' }))).toBe('');
});
});
describe('dedupePacks', () => {
it('keeps first occurrence by id', () => {
const a = pack({ id: 'dup', name: 'Skills version', installed: true });
const b = pack({ id: 'dup', name: 'Starter version', installed: false });
expect(dedupePacks([a, b])).toEqual([a]);
});
it('treats id-less packs as keyed by name', () => {
const a = pack({ id: '', name: 'Research', installed: true });
const b = pack({ id: '', name: 'Research', installed: false });
const c = pack({ id: '', name: 'Writing' });
expect(dedupePacks([a, b, c])).toEqual([a, c]);
});
it('drops entries without any key rather than keeping them all', () => {
const a = pack({ id: '', name: '' });
const b = pack({ id: '', name: '' });
const c = pack({ id: 'real', name: 'Real' });
expect(dedupePacks([a, b, c])).toEqual([c]);
});
it('returns empty on empty input', () => {
expect(dedupePacks([])).toEqual([]);
});
it('preserves order across non-duplicate entries', () => {
const a = pack({ id: 'a' });
const b = pack({ id: 'b' });
const c = pack({ id: 'c' });
expect(dedupePacks([a, b, c, a, b])).toEqual([a, b, c]);
});
it('keeps installed:true marker when it comes first', () => {
const installed = pack({ id: 'dup', installed: true });
const catalog = pack({ id: 'dup', installed: false });
expect(dedupePacks([installed, catalog])[0].installed).toBe(true);
});
});

View File

@@ -0,0 +1,29 @@
import type { SkillPack } from '@/lib/types';
/**
* Stable key for pack identity — prefer id, fall back to name. Closes L-17 C4:
* the Capabilities app concatenates skills, starter-pack, and capability-pack
* catalogs, and the marketplace tab reads a fourth source. Without a dedup
* step the same logical pack can surface twice under different sources.
*/
export function packKey(pack: SkillPack): string {
return pack.id || pack.name || '';
}
/**
* Deduplicate a list of SkillPacks by id||name, keeping the first occurrence.
* Ordering matters — callers should concatenate the most-authoritative source
* first (e.g., installed skills before catalog entries) so the "installed"
* flag isn't lost to a catalog copy.
*/
export function dedupePacks(packs: SkillPack[]): SkillPack[] {
const seen = new Set<string>();
const result: SkillPack[] = [];
for (const p of packs) {
const key = packKey(p);
if (!key || seen.has(key)) continue;
seen.add(key);
result.push(p);
}
return result;
}

View File

@@ -0,0 +1,109 @@
/**
* M-19 / UX-4 — progressive dock label visibility rule.
* Pure function; deterministic `now` injection keeps tests stable.
*/
import { describe, it, expect } from 'vitest';
import {
shouldShowDockLabels,
DOCK_LABELS_AGE_THRESHOLD_MS,
DOCK_LABELS_SESSION_THRESHOLD,
} from './dock-labels';
const NOW = 1_700_000_000_000; // arbitrary fixed instant
const JUST_NOW = NOW - 60_000;
const SIX_DAYS_AGO = NOW - 6 * 24 * 60 * 60 * 1000;
const EIGHT_DAYS_AGO = NOW - 8 * 24 * 60 * 60 * 1000;
describe('shouldShowDockLabels — override modes', () => {
it("always returns true regardless of usage", () => {
expect(shouldShowDockLabels({
sessionCount: 999,
firstLaunchAt: EIGHT_DAYS_AGO,
now: NOW,
mode: 'always',
})).toBe(true);
});
it('never returns false regardless of usage', () => {
expect(shouldShowDockLabels({
sessionCount: 0,
firstLaunchAt: JUST_NOW,
now: NOW,
mode: 'never',
})).toBe(false);
});
});
describe('shouldShowDockLabels — auto heuristic', () => {
it('shows labels when sessionCount is below the threshold (even if install is old)', () => {
expect(shouldShowDockLabels({
sessionCount: DOCK_LABELS_SESSION_THRESHOLD - 1,
firstLaunchAt: EIGHT_DAYS_AGO,
now: NOW,
mode: 'auto',
})).toBe(true);
});
it('shows labels when install age is below the threshold (even with many sessions)', () => {
expect(shouldShowDockLabels({
sessionCount: DOCK_LABELS_SESSION_THRESHOLD * 5,
firstLaunchAt: SIX_DAYS_AGO,
now: NOW,
mode: 'auto',
})).toBe(true);
});
it('hides labels when both thresholds are exceeded', () => {
expect(shouldShowDockLabels({
sessionCount: DOCK_LABELS_SESSION_THRESHOLD,
firstLaunchAt: EIGHT_DAYS_AGO,
now: NOW,
mode: 'auto',
})).toBe(false);
});
it('shows labels on a fresh install with no first-launch timestamp recorded', () => {
expect(shouldShowDockLabels({
sessionCount: 0,
firstLaunchAt: null,
now: NOW,
mode: 'auto',
})).toBe(true);
});
it('hides labels when sessionCount is at threshold and install age is unknown but sessions are already past', () => {
// Without a first-launch timestamp we can't gate on age, so the
// session counter alone decides. At/above threshold → hidden.
expect(shouldShowDockLabels({
sessionCount: DOCK_LABELS_SESSION_THRESHOLD,
firstLaunchAt: null,
now: NOW,
mode: 'auto',
})).toBe(false);
});
it('threshold constants are the documented 20 sessions / 7 days', () => {
expect(DOCK_LABELS_SESSION_THRESHOLD).toBe(20);
expect(DOCK_LABELS_AGE_THRESHOLD_MS).toBe(7 * 24 * 60 * 60 * 1000);
});
});
describe('shouldShowDockLabels — boundary behaviour', () => {
it('exactly at the session threshold is treated as "no longer new"', () => {
expect(shouldShowDockLabels({
sessionCount: DOCK_LABELS_SESSION_THRESHOLD,
firstLaunchAt: EIGHT_DAYS_AGO,
now: NOW,
mode: 'auto',
})).toBe(false);
});
it('exactly at the age threshold is treated as "no longer new"', () => {
expect(shouldShowDockLabels({
sessionCount: DOCK_LABELS_SESSION_THRESHOLD,
firstLaunchAt: NOW - DOCK_LABELS_AGE_THRESHOLD_MS,
now: NOW,
mode: 'auto',
})).toBe(false);
});
});

View File

@@ -0,0 +1,51 @@
/**
* Progressive disclosure for dock icon text labels (M-19 / UX-4).
*
* New users need the text to learn the icon vocabulary; experienced
* users find it noisy. We show labels while the user is still "new",
* defined as either condition holding:
* - fewer than 20 sessions logged on this install, OR
* - install age under 7 days
*
* The user can override via Settings:
* - 'always': labels stay pinned (accessibility / preference)
* - 'never': labels hidden regardless of novice heuristic
* - 'auto': the heuristic above (default)
*/
export type DockLabelsMode = 'auto' | 'always' | 'never';
export const DOCK_LABELS_SESSION_THRESHOLD = 20;
export const DOCK_LABELS_AGE_THRESHOLD_MS = 7 * 24 * 60 * 60 * 1000;
export interface DockLabelsInput {
/** Running count of page loads for this install. */
sessionCount: number;
/** Unix-ms timestamp of the first launch, or null if unknown. */
firstLaunchAt: number | null;
/** Current time for age comparison — injected so tests stay deterministic. */
now: number;
/** User-chosen override from Settings. */
mode: DockLabelsMode;
}
/**
* Decide whether dock icon labels should render.
* Pure function: no side effects, injectable `now` for deterministic tests.
*/
export function shouldShowDockLabels(input: DockLabelsInput): boolean {
switch (input.mode) {
case 'always':
return true;
case 'never':
return false;
case 'auto': {
if (input.sessionCount < DOCK_LABELS_SESSION_THRESHOLD) return true;
if (input.firstLaunchAt !== null) {
const ageMs = input.now - input.firstLaunchAt;
if (ageMs < DOCK_LABELS_AGE_THRESHOLD_MS) return true;
}
return false;
}
}
}

View File

@@ -0,0 +1,80 @@
/**
* M-24 / ENG-3 — dock unlock nudge decision regression.
* Pure function, deterministic.
*/
import { describe, it, expect } from 'vitest';
import {
DOCK_NUDGE_MILESTONES,
DOCK_NUDGE_COPY,
findPendingMilestone,
copyForMilestone,
} from './dock-nudge';
describe('findPendingMilestone', () => {
it('returns null below every milestone', () => {
expect(findPendingMilestone(0, [])).toBeNull();
expect(findPendingMilestone(9, [])).toBeNull();
});
it('returns the first milestone when it has been reached and nothing is dismissed', () => {
expect(findPendingMilestone(10, [])).toBe(10);
expect(findPendingMilestone(25, [])).toBe(10);
expect(findPendingMilestone(50, [])).toBe(10);
});
it('returns the next milestone after the first is dismissed', () => {
expect(findPendingMilestone(50, [10])).toBe(50);
expect(findPendingMilestone(200, [10])).toBe(50);
});
it('returns null when every reached milestone is dismissed', () => {
expect(findPendingMilestone(100, [10, 50])).toBeNull();
expect(findPendingMilestone(50, [10, 50])).toBeNull();
});
it('defensive: rejects non-finite or negative counts', () => {
expect(findPendingMilestone(Number.NaN, [])).toBeNull();
expect(findPendingMilestone(Number.POSITIVE_INFINITY, [])).toBeNull();
expect(findPendingMilestone(-5, [])).toBeNull();
});
it('ignores dismissed milestones that do not correspond to any real milestone', () => {
// A stale "dismissed" entry of 999 from a future contract doesn't
// suppress the current 10/50 milestones.
expect(findPendingMilestone(10, [999])).toBe(10);
});
});
describe('DOCK_NUDGE_MILESTONES + DOCK_NUDGE_COPY', () => {
it('milestones are strictly ascending', () => {
for (let i = 1; i < DOCK_NUDGE_MILESTONES.length; i += 1) {
expect(DOCK_NUDGE_MILESTONES[i]).toBeGreaterThan(DOCK_NUDGE_MILESTONES[i - 1]);
}
});
it('every milestone has copy', () => {
for (const m of DOCK_NUDGE_MILESTONES) {
expect(DOCK_NUDGE_COPY[m], `copy for ${m}`).toBeDefined();
expect(DOCK_NUDGE_COPY[m].title.length).toBeGreaterThan(0);
expect(DOCK_NUDGE_COPY[m].description.length).toBeGreaterThan(0);
}
});
it('the canonical milestones are [10, 50]', () => {
// Pin the current contract so a silent re-order or addition of a
// new milestone trips this test and forces an explicit update.
expect([...DOCK_NUDGE_MILESTONES]).toEqual([10, 50]);
});
});
describe('copyForMilestone', () => {
it('returns the keyed copy when available', () => {
expect(copyForMilestone(10)).toBe(DOCK_NUDGE_COPY[10]);
});
it('falls back to a generic string for an unknown milestone', () => {
const copy = copyForMilestone(999);
expect(copy.title).toContain('999');
expect(copy.description.length).toBeGreaterThan(0);
});
});

View File

@@ -0,0 +1,65 @@
/**
* Dock unlock nudge decision (M-24 / ENG-3).
*
* Fires a one-time toast when the user's session counter reaches each
* milestone in DOCK_NUDGE_MILESTONES. The nudge points the user at
* left-nav zones they may not have explored yet — at 10 sessions we point
* at the Ops zone, at 50 we point at Memory. (P1a AppShell conversion §3.2:
* the IA zones survive as nav zones; copy retargeted "dock" → left nav.)
*
* Persistent storage contract:
* - waggle:session-count (owned by useDockLabels; incremented per mount)
* - waggle:dock-nudge-dismissed (JSON array of milestone numbers this helper owns)
*/
export const DOCK_NUDGE_MILESTONES = [10, 50] as const;
export interface DockNudgeCopy {
readonly title: string;
readonly description: string;
}
/** Toast copy keyed by milestone. Missing entries fall back to a generic string. */
export const DOCK_NUDGE_COPY: Record<number, DockNudgeCopy> = {
10: {
title: "You've logged 10 sessions",
description: 'Open the Ops zone in the left nav to see workflows, timelines, and scheduled jobs.',
},
50: {
title: '50 sessions in — nicely done',
description: 'If you haven\u2019t yet, try the Memory app. It\u2019s where Waggle keeps track of what matters to you.',
},
};
/**
* Return the next milestone that has been reached but not yet
* dismissed, or `null` when nothing is pending. The user sees the
* lowest pending milestone first; later milestones surface after the
* earlier ones are dismissed.
*/
export function findPendingMilestone(
sessionCount: number,
dismissed: readonly number[],
): number | null {
if (!Number.isFinite(sessionCount) || sessionCount < 0) return null;
const dismissedSet = new Set(dismissed);
for (const milestone of DOCK_NUDGE_MILESTONES) {
if (sessionCount >= milestone && !dismissedSet.has(milestone)) {
return milestone;
}
}
return null;
}
/**
* Copy for a milestone, with a defensive fallback when the milestone
* set gains a new entry but the copy map hasn't been updated.
*/
export function copyForMilestone(milestone: number): DockNudgeCopy {
return (
DOCK_NUDGE_COPY[milestone] ?? {
title: `${milestone} sessions — explore the left nav`,
description: 'New zones and apps are available — check the left nav for what\u2019s there.',
}
);
}

View File

@@ -0,0 +1,171 @@
import type { ElementType } from 'react';
import {
LayoutDashboard, MessageSquare, FolderOpen, Settings, Bot, Brain,
Zap, Activity, Radio, Clock, Package, Plug, Store, Lock, Users, Shield, Rocket, FileStack, Server,
} from 'lucide-react';
export type AppId =
| 'home' | 'chat' | 'dashboard' | 'memory' | 'events'
| 'capabilities' | 'connectors' | 'cockpit' | 'mission-control'
| 'settings' | 'vault' | 'profile'
| 'waggle-dance' | 'files' | 'artifacts' | 'agents'
| 'scheduled-jobs' | 'marketplace' | 'voice' | 'room' | 'approvals' | 'timeline'
| 'backup' | 'telemetry' | 'governance' | 'launcher'
// UX-Refactor Phase 1 (S02): single-workspace runtime surface, opened from
// Home / workspace selection (not a dock entry — A1 fixed-layout window).
| 'workspace-desktop'
// UX-Refactor Phase 4B (S08): standalone MCP Hub under the Extend zone.
| 'mcp-hub';
export type UserTier = 'simple' | 'professional' | 'power' | 'admin';
export type BillingTier = 'TRIAL' | 'FREE' | 'TEAMS' | 'ENTERPRISE';
export interface DockEntry {
type: 'app' | 'zone-parent' | 'separator';
key: string;
appId?: AppId;
icon?: ElementType;
label: string;
color?: string;
children?: DockEntry[];
/**
* Minimum billing tier required to see this entry.
* If the user's tier is below this, the entry is hidden from the dock.
* Undefined = always visible.
*/
minBillingTier?: BillingTier;
/**
* UX Refactor v2.1 P1a (conversion plan §1.3): the entry's canonical URL —
* the appId→route table the AppShell left nav navigates by and prefix-matches
* active state against (§2.1.2). Additive; the windowed Dock ignores it.
* `chat` carries its prefix family ('/workspaces') because its real route is
* parameterized — clicks resolve through routeFor('chat', ctx) (§2.3).
*/
route?: string;
/**
* One-line plain-language explanation of the entry, surfaced as a hover
* tooltip in the nav — labels like "Waggle Dance" / "MCP Hub" are opaque
* to non-technical users without it.
*/
description?: string;
}
export const BILLING_TIER_ORDER: Record<BillingTier, number> = {
FREE: 0, TRIAL: 1, TEAMS: 2, ENTERPRISE: 3,
};
export const DEFAULT_TIER: UserTier = 'simple';
// UX-Refactor Phase 0 (S00 §4b): the power dock expresses the PRD §10 IA layers —
// Work (flat primary spine) + Intelligence / Extend / Team / System zone-parents.
// The Command Center (Ctrl+K) lives in the StatusBar, not the dock. Grouping is data-only; the
// Dock renders zone-parents generically off entry.type/entry.key.
const POWER_CONFIG: DockEntry[] = [
// ── Work (primary spine, always visible) ──
{ type: 'app', key: 'home', appId: 'home', icon: LayoutDashboard, label: 'Home', color: 'text-sky-400', route: '/home', description: 'Your starting point — daily briefing and quick actions' },
{ type: 'app', key: 'chat', appId: 'chat', icon: MessageSquare, label: 'Chat', color: 'text-honey', route: '/workspaces', description: 'Talk to your AI agents' },
{ type: 'app', key: 'memory', appId: 'memory', icon: Brain, label: 'Memory', color: 'text-amber-300', route: '/memory', description: 'Everything Waggle remembers about you and your work' },
{ type: 'app', key: 'files', appId: 'files', icon: FolderOpen, label: 'Files', color: 'text-amber-300', route: '/files', description: 'Browse the files in your workspaces' },
{ type: 'app', key: 'artifacts', appId: 'artifacts', icon: FileStack, label: 'Library', color: 'text-amber-300', route: '/artifacts', description: 'Documents and files your agents produce' },
{ type: 'separator', key: 'sep-work', label: '' },
// ── Intelligence ──
{
type: 'zone-parent', key: 'intelligence', icon: Bot, label: 'Intelligence', color: 'text-violet-400', description: 'Your agents and what they can do',
children: [
{ type: 'app', key: 'agents', appId: 'agents', icon: Bot, label: 'Agents', color: 'text-orange-400', route: '/agents', description: 'Create and manage your AI agents' },
{ type: 'app', key: 'skills', appId: 'capabilities', icon: Package, label: 'Skills Hub', color: 'text-violet-400', route: '/skills', description: 'Teach your agents new abilities' },
{ type: 'app', key: 'jobs', appId: 'scheduled-jobs', icon: Clock, label: 'Automation Center', color: 'text-amber-400', route: '/automations', description: 'Set up tasks that run on a schedule' },
{ type: 'app', key: 'room', appId: 'room', icon: Users, label: 'Room', color: 'text-violet-400', route: '/room', description: 'Watch your agents work together live' },
{ type: 'app', key: 'dance', appId: 'waggle-dance', icon: Zap, label: 'Waggle Dance', color: 'text-amber-400', route: '/waggle-dance', description: 'See what your agents learn from each other' },
// Approvals: TEAMS-tier trust/audit surface (Pro gets inline chat approvals).
{ type: 'app', key: 'approvals', appId: 'approvals', icon: Shield, label: 'Approvals', color: 'text-amber-400', minBillingTier: 'TEAMS', route: '/approvals', description: 'Review and approve actions your agents want to take' },
],
},
// ── Extend ──
{
type: 'zone-parent', key: 'extend', icon: Package, label: 'Extend', color: 'text-emerald-400', description: 'Add tools and connections to Waggle',
children: [
{ type: 'app', key: 'connect', appId: 'connectors', icon: Plug, label: 'Connector Hub', color: 'text-emerald-400', route: '/connectors', description: 'Link your apps and accounts so agents can use them' },
// Phase 4B (S08/S21): the dedicated Extend entries landed.
{ type: 'app', key: 'mcp-hub', appId: 'mcp-hub', icon: Server, label: 'MCP Hub', color: 'text-emerald-400', route: '/mcps', description: 'Connect outside tools your agents can use' },
{ type: 'app', key: 'marketplace', appId: 'marketplace', icon: Store, label: 'Marketplace', color: 'text-orange-400', route: '/marketplace', description: 'Browse ready-made skills and add-ons' },
{ type: 'app', key: 'launcher', appId: 'launcher', icon: Rocket, label: 'AI Tools', color: 'text-amber-400', route: '/launcher', description: 'Launch other AI tools you use, linked to Waggle' },
],
},
// ── Team (TEAMS-tier; whole zone hidden below TEAMS) ──
{
type: 'zone-parent', key: 'team', icon: Users, label: 'Team', color: 'text-violet-400', minBillingTier: 'TEAMS', description: 'Shared workspaces and team controls',
children: [
{ type: 'app', key: 'governance', appId: 'governance', icon: Shield, label: 'Team Governance', color: 'text-violet-400', minBillingTier: 'TEAMS', route: '/team', description: 'Team rules, permissions, and oversight' },
],
},
{ type: 'separator', key: 'sep-system', label: '' },
// ── System ──
{
type: 'zone-parent', key: 'system', icon: Settings, label: 'System', color: 'text-muted-foreground', description: 'Settings and system tools',
children: [
{ type: 'app', key: 'settings', appId: 'settings', icon: Settings, label: 'Settings', color: 'text-muted-foreground', route: '/settings', description: 'Preferences, account, and app options' },
{ type: 'app', key: 'vault', appId: 'vault', icon: Lock, label: 'Vault', color: 'text-amber-400', route: '/settings/vault', description: 'Your API keys and secrets, stored locally' },
// D8 (v2.1): "Command Center" is reserved for the Ctrl+K palette.
{ type: 'app', key: 'cockpit', appId: 'cockpit', icon: Activity, label: 'Mission Control', color: 'text-emerald-400', route: '/settings/mission-control', description: 'System health at a glance' },
{ type: 'app', key: 'timeline', appId: 'timeline', icon: Clock, label: 'Timeline', color: 'text-cyan-400', route: '/settings/timeline', description: 'A history of everything that has happened' },
{ type: 'app', key: 'events', appId: 'events', icon: Radio, label: 'Events & Logs', color: 'text-cyan-400', route: '/settings/events', description: 'Live activity feed and technical logs' },
{ type: 'app', key: 'telemetry', appId: 'telemetry', icon: Activity, label: 'Usage & Cost', color: 'text-sky-400', route: '/settings/usage', description: 'What you have used and what it costs' },
// P23: Backup stays in Settings → Backup (not a dock entry).
],
},
];
export const TIER_DOCK_CONFIG: Record<UserTier, DockEntry[]> = {
simple: [
{ type: 'app', key: 'home', appId: 'home', icon: LayoutDashboard, label: 'Home', color: 'text-sky-400', route: '/home', description: 'Your starting point — daily briefing and quick actions' },
{ type: 'app', key: 'chat', appId: 'chat', icon: MessageSquare, label: 'Chat', color: 'text-honey', route: '/workspaces', description: 'Talk to your AI agents' },
// Memory is the product's flagship — onboarding imports the user's AI
// history into it; hiding it from the novice tier orphaned that moment.
{ type: 'app', key: 'memory', appId: 'memory', icon: Brain, label: 'Memory', color: 'text-amber-300', route: '/memory', description: 'Everything Waggle remembers about you and your work' },
{ type: 'app', key: 'files', appId: 'files', icon: FolderOpen, label: 'Files', color: 'text-amber-300', route: '/files', description: 'Browse the files in your workspaces' },
{ type: 'separator', key: 'sep-1', label: '' },
{ type: 'app', key: 'vault', appId: 'vault', icon: Lock, label: 'Vault', color: 'text-amber-400', route: '/settings/vault', description: 'Your API keys and secrets, stored locally' },
{ type: 'app', key: 'system', appId: 'settings', icon: Settings, label: 'Settings', color: 'text-muted-foreground', route: '/settings', description: 'Preferences, account, and app options' },
],
professional: [
{ type: 'app', key: 'home', appId: 'home', icon: LayoutDashboard, label: 'Home', color: 'text-sky-400', route: '/home', description: 'Your starting point — daily briefing and quick actions' },
{ type: 'app', key: 'chat', appId: 'chat', icon: MessageSquare, label: 'Chat', color: 'text-honey', route: '/workspaces', description: 'Talk to your AI agents' },
{ type: 'app', key: 'agents', appId: 'agents', icon: Bot, label: 'Agents', color: 'text-orange-400', route: '/agents', description: 'Create and manage your AI agents' },
{ type: 'app', key: 'files', appId: 'files', icon: FolderOpen, label: 'Files', color: 'text-amber-300', route: '/files', description: 'Browse the files in your workspaces' },
{ type: 'separator', key: 'sep-1', label: '' },
{ type: 'app', key: 'memory', appId: 'memory', icon: Brain, label: 'Memory', color: 'text-amber-300', route: '/memory', description: 'Everything Waggle remembers about you and your work' },
{ type: 'app', key: 'vault', appId: 'vault', icon: Lock, label: 'Vault', color: 'text-amber-400', route: '/settings/vault', description: 'Your API keys and secrets, stored locally' },
{ type: 'app', key: 'system', appId: 'settings', icon: Settings, label: 'Settings', color: 'text-muted-foreground', route: '/settings', description: 'Preferences, account, and app options' },
],
power: POWER_CONFIG,
admin: POWER_CONFIG,
};
/**
* Recursively filter out entries whose minBillingTier exceeds the user's tier.
* Zone parents with no remaining children are also removed.
*/
function filterByBillingTier(entries: DockEntry[], billingTier: BillingTier): DockEntry[] {
const userRank = BILLING_TIER_ORDER[billingTier] ?? 0;
const out: DockEntry[] = [];
for (const e of entries) {
if (e.minBillingTier && BILLING_TIER_ORDER[e.minBillingTier] > userRank) continue;
if (e.type === 'zone-parent' && e.children) {
const kids = filterByBillingTier(e.children, billingTier);
if (kids.length === 0) continue;
out.push({ ...e, children: kids });
} else {
out.push(e);
}
}
return out;
}
export function getDockForTier(tier: UserTier, billingTier: BillingTier = 'FREE'): DockEntry[] {
const base = TIER_DOCK_CONFIG[tier] ?? TIER_DOCK_CONFIG[DEFAULT_TIER];
return filterByBillingTier(base, billingTier);
}

View File

@@ -0,0 +1,209 @@
/**
* Phase 4B (S21) — pure-module tests for the six-domain extension federation
* (extension-catalog.ts): normalizer shapes, lifecycle derivation, honest
* installability flags, filter and sort.
*/
import { describe, it, expect } from 'vitest';
import type { ConnectorDefinition } from '@waggle/shared';
import type { SkillPack } from './types';
import {
filterExtensions, sortExtensions, dedupeExtensions,
fromConnector, fromMarketplacePackage, fromMcpCatalogRow, fromModel,
fromPersona, fromSkillPack, fromTemplate,
type Extension,
} from './extension-catalog';
const airtableConnector: ConnectorDefinition = {
id: 'airtable', name: 'Airtable', description: 'Bases', service: 'airtable',
authType: 'api_key', status: 'disconnected', capabilities: ['read'],
substrate: 'waggle', tools: [], category: 'productivity',
};
describe('extension-catalog normalizers', () => {
it('marketplace packages are installable with a namespaced id + scan status', () => {
const ext = fromMarketplacePackage({
id: 12, name: 'web-scraper', description: 'Scrape', type: 'skill',
installed: false, scanStatus: 'passed',
});
expect(ext).toMatchObject({
id: 'pkg:12', type: 'skill', kind: 'package', packageId: 12,
installable: true, installed: false, lifecycle: 'available', scanStatus: 'passed',
});
});
it('an mcp registry package maps to the mcp facet via waggle_install_type (real rows have no `type`)', () => {
const ext = fromMarketplacePackage({
id: 3, name: 'pg-mcp', description: '', waggle_install_type: 'mcp', installed: true,
});
expect(ext.type).toBe('mcp');
expect(ext.lifecycle).toBe('installed');
// Legacy fixture `type` still honoured when waggle_install_type is absent.
expect(fromMarketplacePackage({ id: 4, name: 'x', description: '', type: 'mcp', installed: false }).type).toBe('mcp');
});
it('skill packs normalize the RAW /api/marketplace/packs row (slug/display_name, no name/installed) and are browse-only', () => {
// Exactly what db.listPacks() emits — the route adds nothing.
const raw = {
id: 1, slug: 'research-pack', display_name: 'Research Pack',
description: 'Research skills', target_roles: '["researcher"]',
icon: 'book', priority: 1, connectors_needed: '[]', created_at: '2026-06-01',
};
const ext = fromSkillPack(raw);
expect(ext).toMatchObject({
id: 'pack:research-pack', name: 'Research Pack', type: 'skill', kind: 'pack',
// A4: no pack-install route exists — packs must not offer Install.
installable: false, installed: false, lifecycle: 'available',
});
// ≥2 raw rows must sort without throwing (the live-registry crash).
expect(() => sortExtensions([ext, fromSkillPack({ ...raw, id: 2, slug: 'ops-pack', display_name: 'Ops Pack' })])).not.toThrow();
});
it('legacy FE SkillPack fixtures keep their trust label and stay browse-only', () => {
const legacy: SkillPack = {
id: 'research', name: 'research', description: 'Research skills',
category: 'research', skills: [], installed: true, trust: 'verified',
};
const ext = fromSkillPack(legacy);
expect(ext).toMatchObject({ id: 'pack:research', kind: 'pack', trust: 'verified', installed: true, installable: false });
});
it('connectors are connectable in-place (PR4 D3), carry authType, and keep the Hub deep link', () => {
const conn: ConnectorDefinition = {
id: 'github', name: 'GitHub', description: 'Code', service: 'github',
authType: 'bearer', status: 'connected', capabilities: ['read'],
substrate: 'waggle', tools: [], category: 'development',
};
const ext = fromConnector(conn);
expect(ext).toMatchObject({
id: 'connector:github', type: 'connector', installable: true,
kind: 'federated', installed: true, source: 'local registry', authType: 'bearer',
});
expect(ext.openIn).toEqual({ appId: 'connectors', label: 'Connector Hub' });
});
it('mcp catalog rows are enableable in-place (PR4 D3) and keep the MCP Hub deep link', () => {
const ext = fromMcpCatalogRow({ id: 'postgres', name: 'PostgreSQL', description: '', category: 'Database', installed: false });
expect(ext.installable).toBe(true);
expect(ext.openIn?.appId).toBe('mcp-hub');
expect(ext.lifecycle).toBe('available');
});
it('personas, models and templates are local — always installed, never installable', () => {
const agent = fromPersona({ id: 'researcher', name: 'Researcher', description: 'Deep research' });
const model = fromModel('claude-fable-5');
const tpl = fromTemplate({
id: 't1', name: 'Research', description: '', persona: 'researcher',
connectors: [], suggestedCommands: [], starterMemory: [], builtIn: true,
});
for (const ext of [agent, model, tpl]) {
expect(ext.installed).toBe(true);
expect(ext.installable).toBe(false);
expect(ext.kind).toBe('federated');
}
expect(agent.openIn?.appId).toBe('agents');
expect(model.openIn?.appId).toBe('settings');
});
});
describe('filterExtensions / sortExtensions', () => {
const list = [
fromModel('zeta-model'),
fromMarketplacePackage({ id: 1, name: 'alpha-skill', description: 'first', type: 'skill', installed: false }),
fromMarketplacePackage({ id: 2, name: 'beta-skill', description: 'scraper tool', type: 'skill', installed: false }),
];
it('filters case-insensitively across name and description', () => {
expect(filterExtensions(list, 'SCRAPER').map(e => e.name)).toEqual(['beta-skill']);
expect(filterExtensions(list, '')).toHaveLength(3);
});
it('sorts available before installed, then by name, without mutating the input', () => {
const sorted = sortExtensions(list);
expect(sorted.map(e => e.name)).toEqual(['alpha-skill', 'beta-skill', 'zeta-model']);
expect(list[0].name).toBe('zeta-model'); // input untouched (immutability)
});
it('tolerates rows whose name/description went missing (raw-envelope defensiveness)', () => {
const broken = [
{ ...fromModel('a-model'), name: undefined, description: undefined },
fromModel('b-model'),
] as unknown as Extension[];
expect(() => sortExtensions(broken)).not.toThrow();
expect(() => filterExtensions(broken, 'b')).not.toThrow();
expect(filterExtensions(broken, 'b-model')).toHaveLength(1);
});
});
describe('dedupeExtensions', () => {
it('collapses connector + catalog-mcp + package for one integration into a single winner (connector)', () => {
const list = [
fromMcpCatalogRow({ id: 'airtable-mcp', name: 'Airtable', description: 'MCP', category: 'productivity', installed: false }),
fromConnector(airtableConnector),
fromMarketplacePackage({ id: 7, name: 'airtable-mcp', description: 'pkg', waggle_install_type: 'mcp', installed: false }),
];
const out = dedupeExtensions(list);
expect(out).toHaveLength(1);
const [winner] = out;
// Winner is the connector — richest install UX (highest precedence).
expect(winner.id).toBe('connector:airtable');
expect(winner.kind).toBe('federated');
expect(winner.type).toBe('connector');
// The other two forms fold into altIds…
expect(winner.altIds).toEqual(expect.arrayContaining(['mcp:airtable-mcp', 'pkg:7']));
expect(winner.altIds).toHaveLength(2);
// …and the distinct forms surface (precedence-ordered) for the badge.
expect(winner.sources).toEqual(['connector', 'mcp', 'package']);
});
it('is installed if ANY form is installed (OR across the group)', () => {
const list = [
fromConnector(airtableConnector), // disconnected → not installed
fromMcpCatalogRow({ id: 'airtable-mcp', name: 'Airtable', description: '', category: 'productivity', installed: true }),
];
const [winner] = dedupeExtensions(list);
expect(winner.id).toBe('connector:airtable');
expect(winner.installed).toBe(true);
expect(winner.lifecycle).toBe('installed');
});
it('passes a unique-key entry through untouched (no altIds/sources added)', () => {
const solo = fromConnector({
id: 'github', name: 'GitHub', description: 'Code', service: 'github',
authType: 'bearer', status: 'connected', capabilities: ['read'],
substrate: 'waggle', tools: [], category: 'development',
});
const out = dedupeExtensions([solo]);
expect(out).toHaveLength(1);
expect(out[0]).toBe(solo); // same reference — untouched
expect(out[0].altIds).toBeUndefined();
expect(out[0].sources).toBeUndefined();
});
it('collapses the within-mcp catalog + package double into one (winner = catalog-mcp)', () => {
// Same server surfaced twice in the mcp facet: the catalog row ("Postgres")
// and its registry package ("postgres-mcp") — both normalize to "postgres".
const list = [
fromMcpCatalogRow({ id: 'postgres', name: 'Postgres', description: 'db', category: 'Database', installed: true }),
fromMarketplacePackage({ id: 9, name: 'postgres-mcp', description: 'pkg', waggle_install_type: 'mcp', installed: false }),
];
const out = dedupeExtensions(list);
expect(out).toHaveLength(1);
const [winner] = out;
expect(winner.id).toBe('mcp:postgres'); // catalog-mcp outranks the package
expect(winner.altIds).toEqual(['pkg:9']);
expect(winner.sources).toEqual(['mcp', 'package']);
expect(winner.installed).toBe(true); // catalog form was installed
});
it('leaves genuinely distinct integrations as separate rows', () => {
const list = [
fromConnector(airtableConnector),
fromConnector({
id: 'slack', name: 'Slack', description: 'Chat', service: 'slack',
authType: 'oauth2', status: 'disconnected', capabilities: ['read'],
substrate: 'waggle', tools: [], category: 'communication',
}),
];
expect(dedupeExtensions(list)).toHaveLength(2);
});
});

View File

@@ -0,0 +1,339 @@
/**
* extension-catalog — pure normalizers for the S21 Marketplace/Extend surface
* (UX-Refactor Phase 4B). Merges the six B7 extension domains into ONE
* `Extension[]` view-model, federating AT READ (A5 — no marketplace.db
* migration, no fake remote entries):
*
* | facet | source | install path |
* |-----------|---------------------------------------------------|---------------------|
* | skill | marketplace registry packages + skill packs | real (marketplace) |
* | mcp | GET /api/mcps (catalog ⋈ runtime) | via MCP Hub (S08) |
* | agent | GET /api/personas | local — Agent Center|
* | connector | GET /api/connectors | local — Connector Hub|
* | model | GET /api/litellm/models | local — Settings |
* | template | GET /api/workspace-templates | local — Home |
*
* Pure module (no adapter import) so the merge/derivation logic is unit-
* testable without rendering React.
*/
import type { ExtensionType } from '@waggle/shared';
import type { ConnectorDefinition } from '@waggle/shared';
import { normalizeMcpId } from '@waggle/shared';
import type { Persona, WorkspaceTemplate } from './types';
// Re-exported so the dedup key can be computed by any caller (and tested) from
// one place. Same canonical normalizer the MCP catalog uses to collapse
// "Airtable" / "airtable-mcp" / "@scope/server-airtable" to one key.
export { normalizeMcpId };
/** §14.7 lifecycle subset derivable from today's backends. */
export type ExtensionLifecycle = 'available' | 'installed';
export interface Extension {
/** Namespaced id — unique across all six domains. */
id: string;
name: string;
description: string;
type: ExtensionType;
/** Honest provenance label rendered on the card. */
source: string;
installed: boolean;
lifecycle: ExtensionLifecycle;
/** True when S21 can install it directly (marketplace-backed). */
installable: boolean;
/** Install dispatch discriminator. */
kind: 'package' | 'pack' | 'federated';
/** Numeric registry id (kind 'package' only). */
packageId?: number;
/** Security-scan state from the marketplace registry. */
scanStatus?: 'passed' | 'failed' | 'not_scanned';
trust?: string;
category?: string;
/** Deep-link CTA for federated entries / advanced management (e.g. the Hub). */
openIn?: { appId: string; label: string };
/** Connector auth method — drives token-paste (bearer/api_key/basic) vs
* OAuth-redirect (the Hub) in the grid's in-place Connect flow (PR4 D3). */
authType?: ConnectorDefinition['authType'];
/** Namespaced ids of the alternate forms this winner absorbed at dedup
* (`dedupeExtensions`) — e.g. a connector winner records its `mcp:` and
* `pkg:` twins. Used to resolve installed-state across every form. */
altIds?: string[];
/** Distinct provenance forms this row represents ('connector' | 'mcp' |
* 'package', precedence-ordered). `length > 1` ⇒ a genuinely multi-form
* integration — the card renders a "Connector + MCP" badge so it reads as
* merged, not silently dropped. Distinct from the singular `source` label. */
sources?: string[];
}
/** Marketplace registry row (numeric-id /api/marketplace search envelope).
* Real rows discriminate the install domain via `waggle_install_type`
* (the packages table has no `type` column) — `type` is kept only for
* legacy fixtures. */
export interface MarketplacePackageRow {
id: number;
name: string;
description: string;
type?: string;
waggle_install_type?: string;
category?: string;
source?: string;
installed?: boolean;
scanStatus?: 'passed' | 'failed' | 'not_scanned';
scanScore?: number;
}
/** Raw GET /api/marketplace/packs row — the route returns db.listPacks()
* verbatim (MarketplacePack: id:number, slug, display_name, description,
* target_roles, icon, priority, connectors_needed, created_at). There is NO
* name/installed/trust/category on real rows; the optional fields below also
* accept the legacy FE SkillPack shape so older fixtures keep working. */
export interface MarketplacePackRow {
id?: number | string;
slug?: string;
display_name?: string;
name?: string;
description?: string;
category?: string;
trust?: string;
installed?: boolean;
}
/** MCP Hub list item subset needed here (see mcp-hub-types.ts). */
export interface McpCatalogRow {
id: string;
name: string;
description: string;
category: string;
installed: boolean;
}
const lifecycle = (installed: boolean): ExtensionLifecycle => (installed ? 'installed' : 'available');
export function fromMarketplacePackage(pkg: MarketplacePackageRow): Extension {
// Real rows carry waggle_install_type, never `type` (legacy fixtures only).
const installType = pkg.waggle_install_type ?? pkg.type;
const installed = Boolean(pkg.installed); // SQLite emits 0/1
return {
id: `pkg:${pkg.id}`,
name: pkg.name ?? '',
description: pkg.description ?? '',
type: installType === 'mcp' ? 'mcp' : 'skill',
source: pkg.source ?? 'marketplace',
installed,
lifecycle: lifecycle(installed),
installable: true,
kind: 'package',
packageId: pkg.id,
...(pkg.scanStatus ? { scanStatus: pkg.scanStatus } : {}),
...(pkg.category ? { category: pkg.category } : {}),
};
}
export function fromSkillPack(pack: MarketplacePackRow): Extension {
// Normalize the RAW MarketplacePack row at the boundary: real rows have
// slug/display_name only (no name/installed/trust) — reading pack.name
// unguarded crashed sortExtensions with the live 18-pack registry.
const name = pack.display_name ?? pack.name ?? String(pack.slug ?? pack.id ?? 'pack');
const installed = pack.installed === true;
return {
id: `pack:${pack.slug ?? pack.id ?? name}`,
name,
description: pack.description ?? '',
type: 'skill',
source: 'marketplace pack',
installed,
lifecycle: lifecycle(installed),
// Browse-only (A4 honesty): no pack-install route exists server-side —
// POST /api/marketplace/install resolves PACKAGE ids, so posting a pack
// id would install an unrelated entity (or 404). Flip this back when a
// real install-pack route ships.
installable: false,
kind: 'pack',
...(pack.trust ? { trust: pack.trust } : {}),
...(pack.category ? { category: pack.category } : {}),
};
}
export function fromConnector(conn: ConnectorDefinition): Extension {
const installed = conn.status === 'connected';
return {
id: `connector:${conn.id}`,
name: conn.name,
description: conn.description ?? '',
type: 'connector',
source: 'local registry',
installed,
lifecycle: lifecycle(installed),
// PR4 D3: connectable in-place — token-paste (bearer/api_key/basic) writes
// the credential to the vault here; OAuth-only falls back to the Hub (the
// card branches on authType). The Hub deep-link stays for management.
installable: true,
kind: 'federated',
authType: conn.authType,
...(conn.category ? { category: conn.category } : {}),
openIn: { appId: 'connectors', label: 'Connector Hub' },
};
}
export function fromPersona(persona: Persona): Extension {
return {
id: `agent:${persona.id}`,
name: persona.name,
description: persona.description ?? '',
type: 'agent',
source: 'built-in persona',
installed: true,
lifecycle: 'installed',
installable: false,
kind: 'federated',
openIn: { appId: 'agents', label: 'Agents' },
};
}
export function fromModel(modelId: string): Extension {
return {
id: `model:${modelId}`,
name: modelId,
description: 'Model available through the configured providers',
type: 'model',
source: 'LLM router',
installed: true,
lifecycle: 'installed',
installable: false,
kind: 'federated',
openIn: { appId: 'settings', label: 'Settings' },
};
}
export function fromTemplate(tpl: WorkspaceTemplate): Extension {
return {
id: `template:${tpl.id}`,
name: tpl.name,
description: tpl.description ?? '',
type: 'template',
source: tpl.builtIn ? 'built-in template' : 'custom template',
installed: true,
lifecycle: 'installed',
installable: false,
kind: 'federated',
...(tpl.category ? { category: tpl.category } : {}),
openIn: { appId: 'home', label: 'Home' },
};
}
export function fromMcpCatalogRow(row: McpCatalogRow): Extension {
return {
id: `mcp:${row.id}`,
name: row.name,
description: row.description ?? '',
type: 'mcp',
source: 'MCP catalog',
installed: row.installed,
lifecycle: lifecycle(row.installed),
// PR4 D3: enableable in-place — installMcp still rides the real
// SecurityGate + PRO gate server-side; the Hub deep-link stays for
// managing running servers.
installable: true,
kind: 'federated',
category: row.category,
openIn: { appId: 'mcp-hub', label: 'MCP Hub' },
};
}
/** Case-insensitive name/description filter shared by every facet.
* Defensive `?? ''`: rows from raw server envelopes can miss fields the
* Extension typing promises — a search keystroke must never throw in render. */
export function filterExtensions(list: Extension[], query: string): Extension[] {
const q = query.trim().toLowerCase();
if (!q) return list;
return list.filter(e =>
(e.name ?? '').toLowerCase().includes(q) || (e.description ?? '').toLowerCase().includes(q),
);
}
/** Stable merged ordering: installed last within a facet, name asc. */
export function sortExtensions(list: Extension[]): Extension[] {
return [...list].sort((a, b) => {
if (a.installed !== b.installed) return a.installed ? 1 : -1;
return (a.name ?? '').localeCompare(b.name ?? '');
});
}
/** Collapsible provenance forms in winner-precedence order — the connector's
* vault-connect UX is the richest, then the catalog-mcp enable, then the
* marketplace package. Any other form (pack) never wins over these three. */
const SOURCE_PRECEDENCE = ['connector', 'mcp', 'package'] as const;
/** The provenance form of an extension, keyed off its namespaced-id prefix. */
function sourceForm(ext: Extension): string {
if (ext.id.startsWith('connector:')) return 'connector';
if (ext.id.startsWith('mcp:')) return 'mcp';
if (ext.id.startsWith('pkg:')) return 'package';
return ext.kind; // 'pack' / other — outranked by all three above
}
function precedenceRank(form: string): number {
const i = (SOURCE_PRECEDENCE as readonly string[]).indexOf(form);
return i === -1 ? SOURCE_PRECEDENCE.length : i;
}
/**
* Collapse the three catalog sources (native connector / local MCP catalog /
* marketplace package) into ONE deduped entry per integration — display-layer
* only, no server/db change. The same integration otherwise appears up to 3×
* with distinct namespaced ids (connector:airtable 'Connect' /
* mcp:airtable-mcp 'Enable' / pkg:… 'Add'), and every installed MCP appears
* twice within the mcp facet (catalog `mcp:` row + package `pkg:` row).
*
* Identity key = `normalizeMcpId(name)`. Within a colliding group the WINNER is
* the highest-precedence form (connector > catalog-mcp > package); the losers'
* ids fold into `altIds` and their forms into `sources`. Installed-state is
* OR-ed across every form (installed if ANY form is). Entries whose key is
* unique pass through untouched (no altIds/sources added).
*/
export function dedupeExtensions(list: Extension[]): Extension[] {
const groups = new Map<string, Extension[]>();
const order: string[] = [];
for (const ext of list) {
const key = normalizeMcpId(ext.name ?? '');
const group = groups.get(key);
if (group) {
group.push(ext);
} else {
groups.set(key, [ext]);
order.push(key);
}
}
const out: Extension[] = [];
for (const key of order) {
const group = groups.get(key)!;
if (group.length === 1) {
out.push(group[0]);
continue;
}
// Winner = lowest precedence rank; stable (first-seen) on a tie.
let winner = group[0];
for (let i = 1; i < group.length; i++) {
if (precedenceRank(sourceForm(group[i])) < precedenceRank(sourceForm(winner))) {
winner = group[i];
}
}
const installedAny = group.some(e => e.installed);
// Distinct forms present, precedence-ordered, with any non-standard form
// (pack) appended so the "N + M" badge stays deterministic.
const forms = new Set(group.map(sourceForm));
const sources = [
...SOURCE_PRECEDENCE.filter(f => forms.has(f)),
...[...forms].filter(f => !(SOURCE_PRECEDENCE as readonly string[]).includes(f)),
];
out.push({
...winner,
installed: installedAny,
lifecycle: installedAny ? 'installed' : winner.lifecycle,
altIds: group.filter(e => e !== winner).map(e => e.id),
sources,
});
}
return out;
}

View File

@@ -0,0 +1,37 @@
export class TimeoutError extends Error {
constructor(url: string, timeoutMs: number) {
super(`Request to ${url} timed out after ${timeoutMs}ms`);
this.name = 'TimeoutError';
}
}
export class NetworkError extends Error {
constructor(url: string, cause?: Error) {
super(`Network error reaching ${url}: ${cause?.message || 'unreachable'}`);
this.name = 'NetworkError';
}
}
export async function fetchWithTimeout(
url: string,
options: RequestInit = {},
timeoutMs = 10000
): Promise<Response> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await fetch(url, {
...options,
signal: controller.signal,
});
return response;
} catch (err: unknown) {
if (err instanceof Error && err.name === 'AbortError') {
throw new TimeoutError(url, timeoutMs);
}
throw new NetworkError(url, err instanceof Error ? err : undefined);
} finally {
clearTimeout(timeout);
}
}

View File

@@ -0,0 +1,55 @@
/**
* frame.source provenance vocabulary.
*
* The `memory_frames.source` column persists exactly 5 values (the DB CHECK
* constraint at `packages/hive-mind-core/src/mind/schema.ts:57`). The server
* projects the raw string; the FE owns the friendly label/description map
* (recon 01 §5). Single source of truth for the ⬡ provenance pill across
* Workspace Overview, Chat activity steps, and the Memory-Trust screen.
*
* Anything outside the 5 known values falls back to the raw string — never
* throws, never fabricates.
*/
export type FrameSourceValue =
| 'user_stated'
| 'tool_verified'
| 'agent_inferred'
| 'import'
| 'system';
interface FrameSourceMeta {
/** Short pill label, e.g. "you". */
label: string;
/** Longer phrase for tooltips / detail, e.g. "you told Waggle". */
description: string;
}
const FRAME_SOURCE_META: Record<FrameSourceValue, FrameSourceMeta> = {
user_stated: { label: 'you', description: 'you told Waggle directly' },
tool_verified: { label: 'verified', description: 'confirmed by a tool execution' },
agent_inferred: { label: 'agent', description: 'inferred by an agent' },
import: { label: 'imported', description: 'brought in via harvest / import' },
system: { label: 'system', description: 'seeded by Waggle' },
};
/**
* Friendly pill label for a raw `frame.source` value. Returns `undefined` for
* an absent source (so callers render the date-only fallback, never a
* fabricated pill); falls back to the raw string for an unknown value.
*/
export function frameSourceLabel(source: string | undefined | null): string | undefined {
if (!source) return undefined;
return FRAME_SOURCE_META[source as FrameSourceValue]?.label ?? source;
}
/** Longer human description of a `frame.source` value (tooltips / detail). */
export function frameSourceDescription(source: string | undefined | null): string | undefined {
if (!source) return undefined;
return FRAME_SOURCE_META[source as FrameSourceValue]?.description ?? source;
}
/** True when a memory's provenance means it was independently verified. */
export function isVerifiedSource(source: string | undefined | null): boolean {
return source === 'tool_verified';
}

View File

@@ -0,0 +1,32 @@
/**
* Simple fuzzy matching — no external deps.
* Used by GlobalSearch (Ctrl+K).
*/
export interface FuzzyResult {
match: boolean;
score: number;
}
export function fuzzyMatch(query: string, text: string): FuzzyResult {
const q = query.toLowerCase();
const t = text.toLowerCase();
if (!q) return { match: true, score: 0 };
// Exact substring — highest score
const idx = t.indexOf(q);
if (idx >= 0) return { match: true, score: 100 - idx };
// Character-by-character fuzzy
let qi = 0;
let score = 0;
for (let ti = 0; ti < t.length && qi < q.length; ti++) {
if (t[ti] === q[qi]) {
score += (ti === 0 || t[ti - 1] === ' ' || t[ti - 1] === '/' || t[ti - 1] === '-') ? 10 : 1;
qi++;
}
}
return { match: qi === q.length, score };
}

View File

@@ -0,0 +1,51 @@
// Pure display mapping for the canonical PRD §15.2 `MemoryKind` vocabulary (B6).
//
// `MemoryKind` is the single source of truth for memory typing (defined once in
// `@waggle/shared`). This module maps each kind to (a) a human label for Memory
// Center filter chips / cards (S04) and (b) an onboarding Memory Review grouping
// bucket (S16). The server-side `ImportItemType → MemoryKind` normalization lives
// in the sidecar harvest layer (Phase 2B), NOT here — the build order forbids
// `@waggle/shared` from importing the hive-mind-core `ImportItemType` union.
//
// Pure functions only; no side effects. The `Record<MemoryKind, …>` map is the
// safety net: tsc fails if a new `MemoryKind` member is added without a mapping.
import type { MemoryKind } from '@waggle/shared';
/** Onboarding Memory Review grouping buckets (S16). Artifacts are sourced from
* the Artifact entity, not a `MemoryKind`, so they are not a target here. */
export type MemoryDisplayCategory = 'Memories' | 'Decisions' | 'Tasks' | 'Projects';
interface MemoryKindMeta {
/** Human label for filter chips / cards (S04). */
label: string;
/** Memory Review grouping bucket (S16). */
category: MemoryDisplayCategory;
}
export const MEMORY_KIND_META: Record<MemoryKind, MemoryKindMeta> = {
fact: { label: 'Fact', category: 'Memories' },
decision: { label: 'Decision', category: 'Decisions' },
task: { label: 'Task', category: 'Tasks' },
preference: { label: 'Preference', category: 'Memories' },
strategy: { label: 'Strategy', category: 'Projects' },
learning: { label: 'Learning', category: 'Memories' },
goal: { label: 'Goal', category: 'Projects' },
entity: { label: 'Entity', category: 'Memories' },
};
export function memoryKindLabel(kind: MemoryKind): string {
return MEMORY_KIND_META[kind]?.label ?? 'Memory';
}
export function memoryKindDisplayCategory(kind: MemoryKind): MemoryDisplayCategory {
return MEMORY_KIND_META[kind]?.category ?? 'Memories';
}
/** Display categories in render order for the Review step grouping (S16). */
export const MEMORY_DISPLAY_CATEGORIES: readonly MemoryDisplayCategory[] = [
'Memories',
'Decisions',
'Tasks',
'Projects',
] as const;

View File

@@ -0,0 +1,107 @@
/**
* Lane H item 1 — disk-persisted cache-first Home payload.
*
* Pins the persistence discipline: versioned key, schema-guarded parse (a
* malformed / partial / stale-version / first-run blob is a MISS, never a
* half-rendered hero), and the size cap.
*/
import { describe, it, expect, beforeEach } from 'vitest';
import {
readHomeCache,
writeHomeCache,
homeCacheExists,
clearHomeCache,
} from '@/lib/home-cache';
import type { HomeBriefing } from '@/lib/types';
const CACHE_KEY = 'waggle:home-cache:v1';
function briefing(over: Partial<HomeBriefing> = {}): HomeBriefing {
return {
greeting: 'Welcome back, Marko',
date: '2026-07-07T08:00:00.000Z',
recentWorkspaces: [
{ id: 'w1', name: 'Alpha', group: 'Personal', lastActive: '2026-07-06T09:00:00.000Z', pendingCount: 0 },
],
suggestedActions: [],
upNext: [],
isFirstRun: false,
...over,
};
}
beforeEach(() => {
clearHomeCache();
window.localStorage.clear();
});
describe('home-cache (Lane H item 1)', () => {
it('round-trips a written payload', () => {
writeHomeCache({
briefing: briefing(),
overnight: null,
highlights: [{ content: 'We decided to ship on Friday.', timestamp: '2026-07-06T09:00:00.000Z' }],
});
const got = readHomeCache();
expect(got).not.toBeNull();
expect(got!.briefing.greeting).toBe('Welcome back, Marko');
expect(got!.highlights).toHaveLength(1);
expect(got!.overnight).toBeNull();
expect(typeof got!.savedAt).toBe('number');
expect(homeCacheExists()).toBe(true);
});
it('returns null when nothing is cached', () => {
expect(readHomeCache()).toBeNull();
expect(homeCacheExists()).toBe(false);
});
it('NEVER caches a first-run payload (day-0 keeps the skeleton path)', () => {
writeHomeCache({ briefing: briefing({ isFirstRun: true }), overnight: null, highlights: [] });
expect(readHomeCache()).toBeNull();
});
it('rejects a stale cache version', () => {
window.localStorage.setItem(
CACHE_KEY,
JSON.stringify({ version: 999, savedAt: Date.now(), briefing: briefing(), overnight: null, highlights: [] }),
);
expect(readHomeCache()).toBeNull();
});
it('rejects a malformed blob (not JSON)', () => {
window.localStorage.setItem(CACHE_KEY, '{ not json');
expect(readHomeCache()).toBeNull();
});
it('rejects a structurally-invalid briefing (missing required field)', () => {
window.localStorage.setItem(
CACHE_KEY,
JSON.stringify({
version: 1,
savedAt: Date.now(),
briefing: { greeting: 'hi' }, // no date/recentWorkspaces/... → guard fails
overnight: null,
highlights: [],
}),
);
expect(readHomeCache()).toBeNull();
});
it('drops an over-cap payload rather than storing a quota-buster', () => {
const huge = 'x'.repeat(200_000);
writeHomeCache({
briefing: briefing(),
overnight: null,
highlights: [{ content: huge, timestamp: '2026-07-06T09:00:00.000Z' }],
});
expect(readHomeCache()).toBeNull(); // never stored
});
it('clearHomeCache removes the cached payload', () => {
writeHomeCache({ briefing: briefing(), overnight: null, highlights: [] });
expect(homeCacheExists()).toBe(true);
clearHomeCache();
expect(readHomeCache()).toBeNull();
});
});

View File

@@ -0,0 +1,121 @@
/**
* home-cache — disk-persisted cache-first paint for the Home cockpit
* (Path-to-9 Pillar 2.1 / Lane H item 1).
*
* The returning-user "boot tax" is that Home waits for the sidecar before it
* paints anything. This module persists the last SUCCESSFUL Home payload
* (server briefing + overnight + the recall highlights) to localStorage so the
* next launch — including a cold desktop-binary start where the sidecar is
* still warming — paints real content IMMEDIATELY, then refreshes silently.
*
* Discipline:
* - Versioned key: a shape change bumps CACHE_VERSION and old blobs are ignored.
* - Schema-guarded parse: any malformed / partial blob returns null (never a
* half-rendered hero). We validate the load path, not just trust JSON.parse.
* - Size-capped: arrays are trimmed on write and the serialized blob is capped,
* so a pathological payload can't blow the localStorage quota.
* - First-run payloads are NEVER cached (the caller guards on isFirstRun) — a
* day-0 user must keep the skeleton path, there is nothing real to paint.
*/
import type { HomeBriefing, OvernightSummary } from '@/lib/types';
import type { MemoryHighlight } from '@/lib/briefing-source';
const CACHE_VERSION = 1;
const CACHE_KEY = `waggle:home-cache:v${CACHE_VERSION}`;
/** Serialized blob larger than this is dropped rather than stored (quota guard). */
const MAX_BLOB_CHARS = 128_000;
/** Trim over-long lists before persisting — the hero only paints a handful. */
const MAX_RECENT_WORKSPACES = 6;
const MAX_HIGHLIGHTS = 3;
export interface HomeCachePayload {
briefing: HomeBriefing;
overnight: OvernightSummary | null;
highlights: MemoryHighlight[];
/** Epoch ms the payload was written — lets the caller reason about staleness. */
savedAt: number;
}
function isObject(v: unknown): v is Record<string, unknown> {
return typeof v === 'object' && v !== null;
}
/** Minimal structural guard for a persisted HomeBriefing (not exhaustive — just
* enough that the hero never renders against a shape it can't read). */
function isBriefingShape(v: unknown): v is HomeBriefing {
if (!isObject(v)) return false;
return (
typeof v.greeting === 'string' &&
typeof v.date === 'string' &&
Array.isArray(v.recentWorkspaces) &&
Array.isArray(v.suggestedActions) &&
Array.isArray(v.upNext) &&
typeof v.isFirstRun === 'boolean'
);
}
/** Read the last cached Home payload, or null if absent / malformed / stale-version. */
export function readHomeCache(): HomeCachePayload | null {
try {
const raw = window.localStorage.getItem(CACHE_KEY);
if (!raw) return null;
const parsed: unknown = JSON.parse(raw);
if (!isObject(parsed)) return null;
if (parsed.version !== CACHE_VERSION) return null;
const { briefing, overnight, highlights, savedAt } = parsed as Record<string, unknown>;
if (!isBriefingShape(briefing)) return null;
if (!Array.isArray(highlights)) return null;
if (typeof savedAt !== 'number') return null;
// A cached first-run payload is meaningless (nothing real to paint) — treat
// as a miss so the caller takes the day-0 skeleton path.
if (briefing.isFirstRun) return null;
return {
briefing,
overnight: (overnight ?? null) as OvernightSummary | null,
highlights: highlights as MemoryHighlight[],
savedAt,
};
} catch {
return null;
}
}
/** Persist the last successful Home payload. No-op on first-run / storage errors. */
export function writeHomeCache(payload: {
briefing: HomeBriefing;
overnight: OvernightSummary | null;
highlights: MemoryHighlight[];
}): void {
try {
if (payload.briefing.isFirstRun) return;
const trimmedBriefing: HomeBriefing = {
...payload.briefing,
recentWorkspaces: payload.briefing.recentWorkspaces.slice(0, MAX_RECENT_WORKSPACES),
};
const blob = JSON.stringify({
version: CACHE_VERSION,
savedAt: Date.now(),
briefing: trimmedBriefing,
overnight: payload.overnight,
highlights: payload.highlights.slice(0, MAX_HIGHLIGHTS),
});
if (blob.length > MAX_BLOB_CHARS) return;
window.localStorage.setItem(CACHE_KEY, blob);
} catch {
// no-op — storage disabled / quota exceeded
}
}
/** True when a paintable Home payload is cached — drives the warm-boot floor. */
export function homeCacheExists(): boolean {
return readHomeCache() !== null;
}
/** Test-only / sign-out: drop the cached payload. */
export function clearHomeCache(): void {
try {
window.localStorage.removeItem(CACHE_KEY);
} catch {
// no-op
}
}

View File

@@ -0,0 +1,156 @@
/**
* Phase 1 #7 — import-reminder-state unit tests.
*
* Pins the eligibility ladder and the 7-day re-show cadence so the banner
* doesn't accidentally start spamming users on a future refactor. localStorage
* helpers are exercised separately so the gate logic remains pure.
*/
import { describe, it, expect, beforeEach } from 'vitest';
import {
shouldShowImportReminder,
readDismissedAt,
writeDismissedAt,
readRetired,
writeRetired,
IMPORT_REMINDER_DISMISSED_KEY,
IMPORT_REMINDER_RETIRED_KEY,
DEFAULT_RESHOW_WINDOW_MS,
} from './import-reminder-state';
const NOW = Date.parse('2026-05-01T00:00:00Z');
describe('shouldShowImportReminder', () => {
it('suppresses when onboarding incomplete (wizard owns this surface)', () => {
expect(
shouldShowImportReminder({
onboardingCompleted: false,
harvestEventCount: 0,
permanentlyRetired: false,
lastDismissedIso: null,
now: NOW,
})
).toBe(false);
});
it('suppresses when retired flag set (post-import, never returns)', () => {
expect(
shouldShowImportReminder({
onboardingCompleted: true,
harvestEventCount: 0,
permanentlyRetired: true,
lastDismissedIso: null,
now: NOW,
})
).toBe(false);
});
it('suppresses when frame count > 0 (proxy for has-imported)', () => {
expect(
shouldShowImportReminder({
onboardingCompleted: true,
harvestEventCount: 5,
permanentlyRetired: false,
lastDismissedIso: null,
now: NOW,
})
).toBe(false);
});
it('suppresses when dismissed within the 7-day re-show window', () => {
const dismissedAt = new Date(NOW - 3 * 86_400_000).toISOString(); // 3d ago
expect(
shouldShowImportReminder({
onboardingCompleted: true,
harvestEventCount: 0,
permanentlyRetired: false,
lastDismissedIso: dismissedAt,
now: NOW,
})
).toBe(false);
});
it('shows after the 7-day window elapses', () => {
const dismissedAt = new Date(NOW - 8 * 86_400_000).toISOString(); // 8d ago
expect(
shouldShowImportReminder({
onboardingCompleted: true,
harvestEventCount: 0,
permanentlyRetired: false,
lastDismissedIso: dismissedAt,
now: NOW,
})
).toBe(true);
});
it('shows on first eligible mount (onboarded + zero frames + no dismiss)', () => {
expect(
shouldShowImportReminder({
onboardingCompleted: true,
harvestEventCount: 0,
permanentlyRetired: false,
lastDismissedIso: null,
now: NOW,
})
).toBe(true);
});
it('treats malformed lastDismissedIso as no-dismiss (defensive)', () => {
expect(
shouldShowImportReminder({
onboardingCompleted: true,
harvestEventCount: 0,
permanentlyRetired: false,
lastDismissedIso: 'not-a-date',
now: NOW,
})
).toBe(true);
});
it('honours an override re-show window for shorter cadence tests', () => {
const dismissedAt = new Date(NOW - 2 * 86_400_000).toISOString(); // 2d ago
expect(
shouldShowImportReminder({
onboardingCompleted: true,
harvestEventCount: 0,
permanentlyRetired: false,
lastDismissedIso: dismissedAt,
now: NOW,
reshowWindowMs: 86_400_000, // 1 day
})
).toBe(true);
});
});
describe('localStorage helpers', () => {
beforeEach(() => {
window.localStorage.clear();
});
it('readDismissedAt returns null when unset', () => {
expect(readDismissedAt()).toBeNull();
});
it('writeDismissedAt + readDismissedAt round-trip an ISO timestamp', () => {
const iso = '2026-05-01T12:00:00.000Z';
writeDismissedAt(iso);
expect(readDismissedAt()).toBe(iso);
expect(window.localStorage.getItem(IMPORT_REMINDER_DISMISSED_KEY)).toBe(iso);
});
it('readRetired returns false when unset', () => {
expect(readRetired()).toBe(false);
});
it('writeRetired persists the literal string "true"', () => {
writeRetired();
expect(readRetired()).toBe(true);
expect(window.localStorage.getItem(IMPORT_REMINDER_RETIRED_KEY)).toBe('true');
});
});
describe('default re-show window', () => {
it('is 7 days', () => {
expect(DEFAULT_RESHOW_WINDOW_MS).toBe(7 * 86_400_000);
});
});

View File

@@ -0,0 +1,117 @@
/**
* Phase 1 #7 — Pending Imports Reminder banner state.
*
* Tracks when the import-reminder banner was last dismissed and whether it
* has been permanently retired (after the user has imported anything). Pure
* helpers — all side effects are the caller's responsibility.
*
* Cadence: re-show 7 days after the last dismiss. Once retired (first
* successful import), the banner never returns regardless of dismissal
* state.
*/
export const IMPORT_REMINDER_DISMISSED_KEY = 'waggle:import-banner-dismissed-at';
export const IMPORT_REMINDER_RETIRED_KEY = 'waggle:import-banner-retired';
export const IMPORT_REMINDER_CC_SIGNATURE_KEY = 'waggle:import-banner-cc-signature';
/** Default re-show window. 7 days = 7 × 86_400_000 ms. */
export const DEFAULT_RESHOW_WINDOW_MS = 7 * 86_400_000;
export interface ImportReminderInput {
/** Has the user completed the onboarding wizard? */
onboardingCompleted: boolean;
/** Count of harvest events committed to memory. 0 = never imported. */
harvestEventCount: number;
/** Persistent retired flag. Set to true once the user imports anything. */
permanentlyRetired: boolean;
/** ISO timestamp of last dismiss (or null). */
lastDismissedIso: string | null;
/** Current time, override for tests. */
now?: number;
/** Re-show window in ms. Defaults to 7 days. */
reshowWindowMs?: number;
}
/**
* Decide whether the reminder banner should render this mount.
*
* Rules:
* 1. Suppress if not onboarded (the wizard is the right surface, not this banner).
* 2. Suppress if user has already imported (retired flag OR harvestEventCount > 0).
* 3. Suppress if dismissed within the re-show window.
* 4. Otherwise show.
*/
export function shouldShowImportReminder(input: ImportReminderInput): boolean {
if (!input.onboardingCompleted) return false;
if (input.permanentlyRetired) return false;
if (input.harvestEventCount > 0) return false;
if (input.lastDismissedIso) {
const parsed = Date.parse(input.lastDismissedIso);
if (Number.isFinite(parsed)) {
const now = input.now ?? Date.now();
const window = input.reshowWindowMs ?? DEFAULT_RESHOW_WINDOW_MS;
if (now - parsed < window) return false;
}
}
return true;
}
/** Read the persistent dismissed-at flag. Returns null when storage disabled or unset. */
export function readDismissedAt(): string | null {
try {
return window.localStorage.getItem(IMPORT_REMINDER_DISMISSED_KEY);
} catch {
return null;
}
}
/** Persist the dismissed-at timestamp. */
export function writeDismissedAt(iso: string): void {
try {
window.localStorage.setItem(IMPORT_REMINDER_DISMISSED_KEY, iso);
} catch {
/* storage disabled — no-op */
}
}
/** Read the retired flag — true once the user has imported anything. */
export function readRetired(): boolean {
try {
return window.localStorage.getItem(IMPORT_REMINDER_RETIRED_KEY) === 'true';
} catch {
return false;
}
}
/** Mark the banner permanently retired. Called when user imports anything. */
export function writeRetired(): void {
try {
window.localStorage.setItem(IMPORT_REMINDER_RETIRED_KEY, 'true');
} catch {
/* storage disabled — no-op */
}
}
/**
* Track the auto-detect signature so dismissing the banner doesn't keep
* re-firing it on every Memory app mount when Claude Code is detected with
* the same item count. Writing a fresh signature on detection-change clears
* the dismissal so the user sees the new state.
*/
export function readCCSignature(): string | null {
try {
return window.localStorage.getItem(IMPORT_REMINDER_CC_SIGNATURE_KEY);
} catch {
return null;
}
}
export function writeCCSignature(signature: string): void {
try {
window.localStorage.setItem(IMPORT_REMINDER_CC_SIGNATURE_KEY, signature);
} catch {
/* storage disabled — no-op */
}
}

View File

@@ -0,0 +1,57 @@
import { describe, it, expect } from 'vitest';
import { rawId, isTogglable, describeError, isTierError } from './install-store';
describe('rawId', () => {
it('strips the namespace prefix', () => {
expect(rawId('connector:slack')).toBe('slack');
expect(rawId('pkg:7')).toBe('7');
expect(rawId('mcp:postgres')).toBe('postgres');
});
it('returns the id unchanged when there is no prefix', () => {
expect(rawId('slack')).toBe('slack');
});
it('only strips the FIRST colon (ids may contain colons)', () => {
expect(rawId('mcp:scope:postgres')).toBe('scope:postgres');
});
});
describe('isTogglable', () => {
it('package kinds are togglable (marketplace skill / mcp package)', () => {
expect(isTogglable({ type: 'skill', kind: 'package' })).toBe(true);
expect(isTogglable({ type: 'mcp', kind: 'package' })).toBe(true);
});
it('packs are browse-only', () => {
expect(isTogglable({ type: 'skill', kind: 'pack' })).toBe(false);
});
it('federated connectors and catalog mcps are togglable', () => {
expect(isTogglable({ type: 'connector', kind: 'federated' })).toBe(true);
expect(isTogglable({ type: 'mcp', kind: 'federated' })).toBe(true);
});
it('ambient kinds (agent/model/template) are NOT togglable', () => {
expect(isTogglable({ type: 'agent', kind: 'federated' })).toBe(false);
expect(isTogglable({ type: 'model', kind: 'federated' })).toBe(false);
expect(isTogglable({ type: 'template', kind: 'federated' })).toBe(false);
});
});
describe('describeError', () => {
it('uses an Error message', () => {
expect(describeError(new Error('boom'))).toBe('boom');
});
it('falls back for non-errors', () => {
expect(describeError('nope')).toBe('Server unreachable');
expect(describeError(undefined)).toBe('Server unreachable');
});
});
describe('isTierError', () => {
it('is true for a 403 with the TIER_INSUFFICIENT marker', () => {
expect(isTierError({ status: 403, body: { error: 'TIER_INSUFFICIENT' } })).toBe(true);
});
it('is false for other 403s, other statuses, and non-errors', () => {
expect(isTierError({ status: 403, body: { error: 'blocked' } })).toBe(false);
expect(isTierError({ status: 500, body: { error: 'TIER_INSUFFICIENT' } })).toBe(false);
expect(isTierError(new Error('boom'))).toBe(false);
expect(isTierError(undefined)).toBe(false);
});
});

View File

@@ -0,0 +1,81 @@
/**
* install-store — pure types + helpers for the PR4 shared install store
* (Warm-Hive Marketplace "sync"). The store (InstallProvider) is the single
* FE source of truth for "what is installed / connecting" that the grid
* (Variation A), agent-pick, and inline-in-chat (Variation B) all subscribe
* to, so installing in ANY view reflects in ALL.
*
* This module is React-free on purpose: the dispatch discriminator + the
* count-eligibility rule are unit-testable without rendering.
*/
import type { ExtensionType } from '@waggle/shared';
/**
* The minimal descriptor the store installs/uninstalls. `Extension`
* (lib/extension-catalog) is a structural superset, so the grid passes its
* Extensions verbatim; the inline-chat card (Phase D) builds one from a
* CapabilityRequest.
*/
export interface InstallTarget {
/** Namespaced catalog id — `pkg:<n>` | `connector:<id>` | `mcp:<id>` | `pack:<…>`. */
id: string;
type: ExtensionType;
kind: 'package' | 'pack' | 'federated';
name: string;
/** Numeric registry id — kind 'package' only. */
packageId?: number;
}
/** Why an install attempt did not succeed (drives the caller's follow-up UI). */
export type InstallReason =
| 'tier' // PRO required — the adapter already dispatched waggle:tier-insufficient
| 'security' // SecurityGate blocked / requires approval
| 'error' // network / server / unknown failure (toast already shown)
| 'needs-credentials' // connector needs a token the caller did not supply (card collects it / OAuth → Hub)
| 'unsupported'; // browse-only (pack) or ambient (agent/model/template) — not installable via the store
export interface InstallOutcome {
ok: boolean;
reason?: InstallReason;
}
/** Credentials/options a caller may supply for a connector (token-paste) or MCP enable. */
export interface InstallCredentials {
token?: string;
apiKey?: string;
settings?: Record<string, string>;
force?: boolean;
forceInsecure?: boolean;
}
/** Strip the catalog namespace prefix: `connector:slack` → `slack`, `mcp:postgres` → `postgres`. */
export function rawId(namespacedId: string): string {
const i = namespacedId.indexOf(':');
return i === -1 ? namespacedId : namespacedId.slice(i + 1);
}
/**
* The togglable kinds the store can install/connect/enable AND that count
* toward the installed count (D1, honest global count). Ambient kinds
* (agent/model/template) are always present; packs are browse-only — neither
* flows through the store, so neither inflates the count.
*/
export function isTogglable(target: Pick<InstallTarget, 'type' | 'kind'>): boolean {
if (target.kind === 'package') return true; // marketplace skill / mcp package
if (target.kind === 'pack') return false; // browse-only (no install-pack route)
return target.type === 'connector' || target.type === 'mcp'; // federated connector / catalog mcp
}
/** Narrow an unknown thrown value to a human-readable message. */
export function describeError(e: unknown): string {
if (e instanceof Error && e.message) return e.message;
return 'Server unreachable';
}
/** A thrown AdapterHttpError that is a 403 tier rejection (the adapter has
* already dispatched waggle:tier-insufficient). The connector connect path
* throws (vs the fetchRaw install paths whose tier body is inspected inline). */
export function isTierError(e: unknown): boolean {
const err = e as { status?: number; body?: { error?: unknown } } | undefined;
return err?.status === 403 && err?.body?.error === 'TIER_INSUFFICIENT';
}

View File

@@ -0,0 +1,324 @@
/**
* M-30 — kg-export vitest. Pure / DOM-only helpers under jsdom.
*/
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import {
KG_THEME_VARS,
buildKgExportFilename,
buildKgPngFilename,
resolveThemeStyleAttr,
serializeKgSvg,
downloadKgSvg,
downloadKgPng,
} from './kg-export';
function makeSvg(): SVGSVGElement {
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('width', '100');
svg.setAttribute('height', '100');
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
circle.setAttribute('cx', '50');
circle.setAttribute('cy', '50');
circle.setAttribute('r', '20');
circle.setAttribute('fill', 'hsl(var(--primary))');
svg.appendChild(circle);
return svg as SVGSVGElement;
}
describe('buildKgExportFilename', () => {
it('produces ISO-dated .svg filename', () => {
const name = buildKgExportFilename(new Date('2026-04-19T12:34:56Z'));
expect(name).toBe('waggle-knowledge-graph-2026-04-19.svg');
});
it('defaults to "now" when no date provided', () => {
const name = buildKgExportFilename();
expect(name).toMatch(/^waggle-knowledge-graph-\d{4}-\d{2}-\d{2}\.svg$/);
});
});
describe('resolveThemeStyleAttr', () => {
let root: HTMLElement;
beforeEach(() => {
root = document.createElement('div');
document.body.appendChild(root);
});
afterEach(() => {
root.remove();
});
it('returns empty string when no vars are set on the root', () => {
// jsdom returns '' for missing CSS vars — nothing to emit.
expect(resolveThemeStyleAttr(root, ['--not-set', '--also-not-set'])).toBe('');
});
it('emits declarations only for vars that resolve', () => {
root.style.setProperty('--primary', '45 100% 50%');
root.style.setProperty('--foreground', '0 0% 10%');
const attr = resolveThemeStyleAttr(root, ['--primary', '--foreground', '--missing']);
expect(attr).toContain('--primary: 45 100% 50%');
expect(attr).toContain('--foreground: 0 0% 10%');
expect(attr).not.toContain('--missing');
});
it('uses semicolon+space separator so it stacks with an existing style attr', () => {
root.style.setProperty('--primary', '45 100% 50%');
root.style.setProperty('--background', '0 0% 100%');
const attr = resolveThemeStyleAttr(root, ['--primary', '--background']);
expect(attr).toBe('--primary: 45 100% 50%; --background: 0 0% 100%');
});
it('exports the canonical KG theme variable list', () => {
// Regression guard: the list MUST include at least the five page-level
// tokens used in the KG SVG markup. Changing the list is intentional.
const required = ['--primary', '--foreground', '--muted-foreground', '--background', '--border'];
for (const v of required) {
expect(KG_THEME_VARS).toContain(v);
}
});
});
describe('serializeKgSvg', () => {
let root: HTMLElement;
beforeEach(() => {
root = document.createElement('div');
document.body.appendChild(root);
root.style.setProperty('--primary', '45 100% 50%');
});
afterEach(() => {
root.remove();
});
it('prepends XML declaration', () => {
const xml = serializeKgSvg(makeSvg(), root);
expect(xml.startsWith('<?xml version="1.0" encoding="UTF-8"?>\n')).toBe(true);
});
it('injects xmlns on the root svg', () => {
const xml = serializeKgSvg(makeSvg(), root);
expect(xml).toContain('xmlns="http://www.w3.org/2000/svg"');
});
it('injects resolved theme variables as inline style on the root svg', () => {
const xml = serializeKgSvg(makeSvg(), root);
expect(xml).toContain('--primary: 45 100% 50%');
});
it('does NOT mutate the original SVG element', () => {
const svg = makeSvg();
const before = svg.outerHTML;
serializeKgSvg(svg, root);
expect(svg.outerHTML).toBe(before);
});
it('preserves inner markup (circle survives the clone)', () => {
const xml = serializeKgSvg(makeSvg(), root);
expect(xml).toContain('<circle');
expect(xml).toContain('cx="50"');
expect(xml).toContain('fill="hsl(var(--primary))"');
});
});
describe('downloadKgSvg', () => {
let createdUrls: string[];
let revokedUrls: string[];
let clickedAnchors: HTMLAnchorElement[];
let originalCreate: typeof URL.createObjectURL;
let originalRevoke: typeof URL.revokeObjectURL;
beforeEach(() => {
createdUrls = [];
revokedUrls = [];
clickedAnchors = [];
originalCreate = URL.createObjectURL;
originalRevoke = URL.revokeObjectURL;
URL.createObjectURL = vi.fn((blob: Blob | MediaSource) => {
const url = `blob:mock-${createdUrls.length}`;
createdUrls.push(url);
void blob;
return url;
});
URL.revokeObjectURL = vi.fn((url: string) => {
revokedUrls.push(url);
});
// Capture anchor clicks without navigating the jsdom window.
HTMLAnchorElement.prototype.click = function click(this: HTMLAnchorElement) {
clickedAnchors.push(this);
};
});
afterEach(() => {
URL.createObjectURL = originalCreate;
URL.revokeObjectURL = originalRevoke;
});
it('returns the filename used for the download', () => {
const filename = downloadKgSvg(makeSvg(), 'custom.svg');
expect(filename).toBe('custom.svg');
});
it('defaults to the ISO-dated filename when none provided', () => {
const filename = downloadKgSvg(makeSvg());
expect(filename).toMatch(/^waggle-knowledge-graph-\d{4}-\d{2}-\d{2}\.svg$/);
});
it('creates a blob URL, clicks an anchor, and revokes the URL', () => {
downloadKgSvg(makeSvg(), 'custom.svg');
expect(createdUrls).toHaveLength(1);
expect(clickedAnchors).toHaveLength(1);
expect(clickedAnchors[0].href).toBe(createdUrls[0]);
expect(clickedAnchors[0].download).toBe('custom.svg');
expect(revokedUrls).toEqual(createdUrls);
});
});
// ── E-5 — PNG export ────────────────────────────────────────────────
describe('buildKgPngFilename', () => {
it('uses the .png extension with the same date convention', () => {
const name = buildKgPngFilename(new Date('2026-05-20T12:34:56Z'));
expect(name).toBe('waggle-knowledge-graph-2026-05-20.png');
});
it('defaults to today when no date provided', () => {
expect(buildKgPngFilename()).toMatch(/^waggle-knowledge-graph-\d{4}-\d{2}-\d{2}\.png$/);
});
});
describe('downloadKgPng', () => {
// jsdom doesn't implement Image-loads-SVG or canvas.toBlob in a way that
// would let us hit the happy path without mocking. We mock the
// Image / canvas surface and assert the orchestration: SVG blob created,
// Image loaded, canvas drawn at scaled dims, PNG blob created, anchor
// clicked, URLs revoked.
let createdUrls: string[];
let revokedUrls: string[];
let clickedAnchors: HTMLAnchorElement[];
let originalCreate: typeof URL.createObjectURL;
let originalRevoke: typeof URL.revokeObjectURL;
let originalImage: typeof Image;
let canvasToBlob: ReturnType<typeof vi.fn>;
beforeEach(() => {
createdUrls = [];
revokedUrls = [];
clickedAnchors = [];
originalCreate = URL.createObjectURL;
originalRevoke = URL.revokeObjectURL;
originalImage = globalThis.Image;
URL.createObjectURL = vi.fn((blob: Blob | MediaSource) => {
const url = `blob:mock-${createdUrls.length}`;
createdUrls.push(url);
void blob;
return url;
});
URL.revokeObjectURL = vi.fn((url: string) => {
revokedUrls.push(url);
});
HTMLAnchorElement.prototype.click = function click(this: HTMLAnchorElement) {
clickedAnchors.push(this);
};
// Mock Image to synchronously fire onload.
class MockImage {
onload: (() => void) | null = null;
onerror: (() => void) | null = null;
crossOrigin = '';
private _src = '';
get src(): string { return this._src; }
set src(value: string) {
this._src = value;
// Fire onload on the next microtask so the await in downloadKgPng resolves.
queueMicrotask(() => this.onload?.());
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).Image = MockImage;
// Mock canvas.toBlob to immediately return a stub PNG blob.
canvasToBlob = vi.fn(function (this: HTMLCanvasElement, cb: BlobCallback) {
cb(new Blob(['png-bytes'], { type: 'image/png' }));
});
HTMLCanvasElement.prototype.toBlob = canvasToBlob;
// Stub the 2D context — we only need drawImage to be present.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
HTMLCanvasElement.prototype.getContext = (function () {
return { drawImage: vi.fn() };
}) as any;
});
afterEach(() => {
URL.createObjectURL = originalCreate;
URL.revokeObjectURL = originalRevoke;
globalThis.Image = originalImage;
});
it('returns the PNG filename', async () => {
const svg = makeSvg();
svg.setAttribute('viewBox', '0 0 100 100');
const filename = await downloadKgPng(svg, 'custom.png');
expect(filename).toBe('custom.png');
});
it('defaults to the ISO-dated .png filename', async () => {
const svg = makeSvg();
svg.setAttribute('viewBox', '0 0 200 200');
const filename = await downloadKgPng(svg);
expect(filename).toMatch(/^waggle-knowledge-graph-\d{4}-\d{2}-\d{2}\.png$/);
});
it('creates two blob URLs (svg + png), clicks an anchor, revokes both', async () => {
const svg = makeSvg();
svg.setAttribute('viewBox', '0 0 100 100');
await downloadKgPng(svg, 'custom.png');
// 1st URL = serialized SVG (input to Image), 2nd = PNG blob (download)
expect(createdUrls).toHaveLength(2);
expect(clickedAnchors).toHaveLength(1);
expect(clickedAnchors[0].download).toBe('custom.png');
// Both URLs revoked (svg in finally, png after click).
expect(revokedUrls.length).toBe(2);
});
it('scales the canvas by the given factor (default 2)', async () => {
const svg = makeSvg();
svg.setAttribute('viewBox', '0 0 100 100');
// Spy on canvas dimensions by inspecting the canvas created during the call.
const widthHistory: number[] = [];
const heightHistory: number[] = [];
const originalCreateElement = document.createElement.bind(document);
const stub = vi.spyOn(document, 'createElement').mockImplementation(
(tag: string) => {
const el = originalCreateElement(tag) as HTMLCanvasElement;
if (tag === 'canvas') {
// Trap width/height setters via Object.defineProperty
let _w = 0, _h = 0;
Object.defineProperty(el, 'width', {
get: () => _w,
set: (v: number) => { _w = v; widthHistory.push(v); },
});
Object.defineProperty(el, 'height', {
get: () => _h,
set: (v: number) => { _h = v; heightHistory.push(v); },
});
}
return el;
},
);
await downloadKgPng(svg, 'scale.png', 3);
expect(widthHistory).toContain(300);
expect(heightHistory).toContain(300);
stub.mockRestore();
});
it('rejects when no dimensions can be determined', async () => {
const svg = makeSvg();
svg.removeAttribute('width');
svg.removeAttribute('height');
// No viewBox either. getBoundingClientRect returns 0×0 in jsdom.
await expect(downloadKgPng(svg)).rejects.toThrow(/dimensions/i);
});
});

View File

@@ -0,0 +1,189 @@
/**
* M-30 — Knowledge Graph export helpers.
*
* Serializes an SVGSVGElement to a standalone SVG string with theme variables
* resolved (so the exported file renders the same colors outside the app),
* and builds a deterministic filename for the download.
*
* Pure / DOM-only — no React, no network. Safe to unit-test under jsdom.
*/
// Theme variables referenced inside the KG SVG markup. Resolved against
// document.documentElement and injected as inline style on the exported <svg>
// so the file renders standalone without the waggle-theme.css stylesheet.
export const KG_THEME_VARS: readonly string[] = [
'--primary',
'--foreground',
'--muted-foreground',
'--background',
'--border',
'--kg-person',
'--kg-project',
'--kg-concept',
'--kg-org',
'--kg-default',
] as const;
/**
* Build the download filename — `waggle-knowledge-graph-YYYY-MM-DD.svg`.
* ISO date (UTC) keeps it stable regardless of the user's timezone; matches
* the backup-filename convention in SettingsApp.tsx.
*/
export function buildKgExportFilename(now: Date = new Date()): string {
const iso = now.toISOString().slice(0, 10);
return `waggle-knowledge-graph-${iso}.svg`;
}
/**
* Read each theme variable off the root element and return the style-attribute
* string to paste onto the exported SVG. Missing variables are skipped so we
* don't emit empty declarations.
*/
export function resolveThemeStyleAttr(
root: HTMLElement,
vars: readonly string[] = KG_THEME_VARS,
): string {
const computed = getComputedStyle(root);
const declarations: string[] = [];
for (const name of vars) {
const value = computed.getPropertyValue(name).trim();
if (value.length > 0) {
declarations.push(`${name}: ${value}`);
}
}
return declarations.join('; ');
}
/**
* Serialize an SVGSVGElement to a complete standalone SVG document. The theme
* variables referenced by `hsl(var(--foo))` strings inside the markup are
* resolved on the clone so the exported file renders identically outside the
* app. Caller owns the blob + URL lifecycle.
*/
export function serializeKgSvg(
svg: SVGSVGElement,
root: HTMLElement = document.documentElement,
): string {
const clone = svg.cloneNode(true) as SVGSVGElement;
// xmlns is required for standalone rendering; React-rendered SVGs omit it.
if (!clone.getAttribute('xmlns')) {
clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
}
const themeStyle = resolveThemeStyleAttr(root);
if (themeStyle.length > 0) {
const existing = clone.getAttribute('style') ?? '';
clone.setAttribute('style', existing.length > 0 ? `${existing}; ${themeStyle}` : themeStyle);
}
const serializer = new XMLSerializer();
return `<?xml version="1.0" encoding="UTF-8"?>\n${serializer.serializeToString(clone)}`;
}
/**
* Trigger a browser download of the serialized SVG. Caller provides the SVG
* element; helper owns the blob/URL/anchor lifecycle and revokes the URL once
* the click is dispatched.
*
* Returns the filename so callers can surface it in a toast.
*/
export function downloadKgSvg(
svg: SVGSVGElement,
filename: string = buildKgExportFilename(),
): string {
const xml = serializeKgSvg(svg);
const blob = new Blob([xml], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
return filename;
}
/**
* E-5 — PNG export. Rasterizes the serialized SVG via a canvas at the
* given scale factor (default 2× for retina) and triggers a download.
*
* Resolves with the filename on success or rejects on rasterization
* failure (image load error, canvas blob failure, dimensions missing).
* Caller can decide whether to fall back to SVG export or surface a toast.
*/
export function buildKgPngFilename(now: Date = new Date()): string {
const iso = now.toISOString().slice(0, 10);
return `waggle-knowledge-graph-${iso}.png`;
}
export async function downloadKgPng(
svg: SVGSVGElement,
filename: string = buildKgPngFilename(),
scale: number = 2,
): Promise<string> {
// Read dimensions from viewBox first (responsive SVGs often lack
// explicit width/height attrs), then fall back to width/height,
// then to getBoundingClientRect.
let width = 0;
let height = 0;
const viewBox = svg.getAttribute('viewBox');
if (viewBox) {
const parts = viewBox.split(/[\s,]+/).map(Number);
if (parts.length === 4 && parts.every((n) => Number.isFinite(n))) {
width = parts[2];
height = parts[3];
}
}
if (!width || !height) {
const w = svg.getAttribute('width');
const h = svg.getAttribute('height');
width = w ? parseFloat(w) : 0;
height = h ? parseFloat(h) : 0;
}
if (!width || !height) {
const rect = svg.getBoundingClientRect();
width = rect.width;
height = rect.height;
}
if (!width || !height) {
throw new Error('Cannot rasterize SVG — no dimensions available');
}
const xml = serializeKgSvg(svg);
const svgBlob = new Blob([xml], { type: 'image/svg+xml;charset=utf-8' });
const svgUrl = URL.createObjectURL(svgBlob);
try {
const img = new Image();
img.crossOrigin = 'anonymous';
await new Promise<void>((resolve, reject) => {
img.onload = () => resolve();
img.onerror = () => reject(new Error('Failed to load SVG into Image'));
img.src = svgUrl;
});
const canvas = document.createElement('canvas');
canvas.width = Math.round(width * scale);
canvas.height = Math.round(height * scale);
const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('Canvas 2D context unavailable');
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const pngBlob = await new Promise<Blob>((resolve, reject) => {
canvas.toBlob(
(b) => (b ? resolve(b) : reject(new Error('Canvas toBlob returned null'))),
'image/png',
);
});
const pngUrl = URL.createObjectURL(pngBlob);
const a = document.createElement('a');
a.href = pngUrl;
a.download = filename;
a.click();
URL.revokeObjectURL(pngUrl);
return filename;
} finally {
URL.revokeObjectURL(svgUrl);
}
}

View File

@@ -0,0 +1,98 @@
/**
* E-2 — promptArgsForTool unit tests.
*
* Locks the mapping between tool id and CLI args shape. When a tool's
* CLI convention changes (or a new tool is added), the lock surfaces
* a test diff so the LauncherApp's launch flow doesn't silently send
* the wrong args.
*/
import { describe, it, expect } from 'vitest';
import {
promptArgsForTool,
toolAcceptsInlinePrompt,
} from './launcher-prompt-args';
describe('promptArgsForTool', () => {
// ── Empty / whitespace handling ────────────────────────────────────
it.each(['', ' ', '\t\n'])(
'returns null for empty/whitespace prompt %j',
(empty) => {
expect(promptArgsForTool('claude-code', empty)).toBeNull();
},
);
it('trims the prompt before building args', () => {
const args = promptArgsForTool('claude-code', ' refactor x ');
expect(args).toEqual(['--print', 'refactor x']);
});
// ── Per-tool shapes ────────────────────────────────────────────────
describe('claude-code', () => {
it('uses --print flag (non-interactive Claude Code)', () => {
expect(promptArgsForTool('claude-code', 'rotate the webhook secret')).toEqual([
'--print',
'rotate the webhook secret',
]);
});
});
describe('openclaw', () => {
it('inherits claude-code --print convention (Claude Code fork)', () => {
expect(promptArgsForTool('openclaw', 'list open PRs')).toEqual([
'--print',
'list open PRs',
]);
});
});
describe('codex', () => {
it('passes prompt as positional argument (OpenAI Codex CLI)', () => {
expect(promptArgsForTool('codex', 'fix the failing test in main.py')).toEqual([
'fix the failing test in main.py',
]);
});
});
describe('hermes', () => {
it('passes prompt as positional argument (best-effort convention)', () => {
expect(promptArgsForTool('hermes', 'summarize todays standup')).toEqual([
'summarize todays standup',
]);
});
});
// ── GUI / folder-based tools ───────────────────────────────────────
describe('GUI-only / folder-based tools return null', () => {
it.each(['cursor', 'claude-desktop', 'codex-desktop'])(
'%s — no CLI prompt surface',
(toolId) => {
expect(promptArgsForTool(toolId, 'anything')).toBeNull();
},
);
});
// ── Unknown tool ───────────────────────────────────────────────────
it('returns null for unknown tool ids (defensive default)', () => {
expect(promptArgsForTool('made-up-tool', 'anything')).toBeNull();
});
});
describe('toolAcceptsInlinePrompt', () => {
it.each([
['claude-code', true],
['openclaw', true],
['codex', true],
['hermes', true],
['cursor', false],
['claude-desktop', false],
['codex-desktop', false],
['made-up', false],
])('%s → %s', (toolId, expected) => {
expect(toolAcceptsInlinePrompt(toolId)).toBe(expected);
});
});

View File

@@ -0,0 +1,96 @@
/**
* E-2 — Cross-tool prompt-arg shapes for the AI-OS launcher.
*
* Given a tool id and a free-form prompt, returns the CLI args array
* to pass to /api/tools/launch so the spawned tool boots with the
* prompt pre-filled. Returns null for tools that have no CLI
* inline-prompt surface — those launch bare and the user types the
* prompt manually inside the tool.
*
* Conventions (sources documented per-case):
*
* claude-code → ['--print', prompt]
* openclaw → ['--print', prompt] (Claude Code fork)
* codex → [prompt] (positional arg)
* hermes → [prompt] (positional arg — best-effort)
* cursor → null (folder-based; no CLI prompt)
* claude-desktop → null (GUI only)
* codex-desktop → null (GUI only)
*
* Adding a tool:
* 1. Verify the CLI convention against a real binary (`<tool> --help`).
* 2. Add the case below with a one-line source comment.
* 3. Add an it() to launcher-prompt-args.test.ts that locks the shape.
* 4. Update CROSS_TOOL_NOTES in the JSDoc above.
*
* Out of scope:
* - Stdin-piped prompts. Some CLIs (codex) accept stdin as a
* fallback; we don't pipe today because the Phase 2A backend
* doesn't expose a stdin field on POST /api/tools/launch. If
* stdin becomes the right shape for any tool, extend the route
* schema first.
* - Multi-arg shapes (e.g. claude-code's --continue + --print). The
* LauncherApp only sends a prompt; continuation/session args belong
* in a separate launch-options surface.
*/
/**
* Build the CLI args for launching `toolId` with `prompt`. Returns
* `null` when the tool has no inline-prompt CLI — the launcher then
* passes no args and the user types the prompt inside the tool.
*
* Trims the prompt first; an empty/whitespace prompt always returns
* null regardless of tool support.
*/
export function promptArgsForTool(toolId: string, prompt: string): string[] | null {
const p = prompt.trim();
if (!p) return null;
switch (toolId) {
// Anthropic Claude Code: `claude --print "<prompt>"` runs in
// non-interactive mode and prints the response. Documented in
// claude-code --help; verified against shipped CLI.
case 'claude-code':
return ['--print', p];
// OpenClaw: Claude Code fork (hive-mind-hooks-openclaw exists).
// Same --print flag inherited from the upstream CLI convention.
case 'openclaw':
return ['--print', p];
// OpenAI Codex CLI: `codex "<prompt>"` — prompt is positional.
// See https://github.com/openai/codex (Codex CLI uses the first
// non-flag argument as the task prompt).
case 'codex':
return [p];
// Hermes Agent CLI: positional-arg convention by analogy. The
// hive-mind-hooks-hermes package is a Wave 2/3 stub; this entry
// is documented as best-effort and should be verified once the
// Hermes CLI is exercised against a real binary.
case 'hermes':
return [p];
// GUI-only tools: no CLI prompt surface.
// cursor: opens a folder (`cursor /path`), no --prompt flag.
// claude-desktop / codex-desktop: GUI binaries with no
// prompt-from-CLI handoff documented.
case 'cursor':
case 'claude-desktop':
case 'codex-desktop':
return null;
default:
return null;
}
}
/**
* UI hint — does this tool accept an inline prompt at all? Used by
* the launch dialog to grey-out the prompt textarea when the active
* tool can't consume it (and surface a tooltip explaining why).
*
* Returns true iff `promptArgsForTool(toolId, 'x')` is non-null.
*/
export function toolAcceptsInlinePrompt(toolId: string): boolean {
return promptArgsForTool(toolId, 'x') !== null;
}

View File

@@ -0,0 +1,233 @@
/**
* L-22 regression — memory-brag summary + global last-active picker.
*/
import { describe, it, expect } from 'vitest';
import {
computeBragSummary,
pickGlobalLastActive,
timeAgo,
formatBragLine,
type BriefingWorkspaceSummary,
} from './login-briefing-brag';
const NOW = new Date('2026-04-19T22:00:00Z').getTime();
function mkSummary(lastActive?: string, pending: number = 0): BriefingWorkspaceSummary {
return {
lastActive,
pendingTasks: Array.from({ length: pending }, (_, i) => `task-${i}`),
};
}
describe('computeBragSummary', () => {
it('uses stats.total when present', () => {
const out = computeBragSummary({
personal: { frames: 100, entities: 20, relations: 50 },
workspace: { frames: 200, entities: 40, relations: 80 },
total: { frames: 400, entities: 75, relations: 150 },
}, [], NOW);
expect(out.totalFrames).toBe(400);
expect(out.totalEntities).toBe(75);
expect(out.totalRelations).toBe(150);
});
it('falls back to summing personal + workspace when total is absent', () => {
const out = computeBragSummary({
personal: { frames: 100, entities: 20, relations: 50 },
workspace: { frames: 200, entities: 40, relations: 80 },
}, [], NOW);
expect(out.totalFrames).toBe(300);
expect(out.totalEntities).toBe(60);
expect(out.totalRelations).toBe(130);
});
it('returns zeros when stats is null / undefined', () => {
expect(computeBragSummary(null, [], NOW)).toMatchObject({
totalFrames: 0,
totalEntities: 0,
totalRelations: 0,
workspaceCount: 0,
pendingCount: 0,
lastActiveIso: null,
});
});
it('counts workspaces and pending tasks from summaries', () => {
const summaries = [
mkSummary('2026-04-19T20:00:00Z', 2),
mkSummary('2026-04-19T15:00:00Z', 0),
mkSummary('2026-04-18T10:00:00Z', 1),
];
const out = computeBragSummary(null, summaries, NOW);
expect(out.workspaceCount).toBe(3);
expect(out.pendingCount).toBe(3);
});
it('surfaces the most recent lastActive across workspaces', () => {
const summaries = [
mkSummary('2026-04-17T10:00:00Z'),
mkSummary('2026-04-19T20:00:00Z'), // newest
mkSummary('2026-04-18T10:00:00Z'),
];
const out = computeBragSummary(null, summaries, NOW);
expect(out.lastActiveIso).toBe('2026-04-19T20:00:00Z');
expect(out.lastActiveLabel).toBe('2h ago');
});
});
describe('pickGlobalLastActive', () => {
it('returns null for an empty list', () => {
expect(pickGlobalLastActive([])).toBeNull();
});
it('returns null when no summary has a valid iso', () => {
expect(pickGlobalLastActive([
{ lastActive: '' },
{ lastActive: null },
{ lastActive: 'not-a-date' },
])).toBeNull();
});
it('ignores invalid iso strings and picks the newest valid one', () => {
expect(pickGlobalLastActive([
{ lastActive: 'garbage' },
{ lastActive: '2026-04-18T10:00:00Z' },
{ lastActive: '2026-04-19T20:00:00Z' },
{ lastActive: '' },
])).toBe('2026-04-19T20:00:00Z');
});
it('handles a single-item list', () => {
expect(pickGlobalLastActive([{ lastActive: '2026-04-19T20:00:00Z' }]))
.toBe('2026-04-19T20:00:00Z');
});
});
describe('timeAgo', () => {
it('returns "just now" for times less than a minute ago', () => {
expect(timeAgo('2026-04-19T21:59:30Z', NOW)).toBe('just now');
});
it('renders minutes for recent times', () => {
expect(timeAgo('2026-04-19T21:30:00Z', NOW)).toBe('30m ago');
});
it('renders hours for same-day-ish', () => {
expect(timeAgo('2026-04-19T17:00:00Z', NOW)).toBe('5h ago');
});
it('renders "yesterday" for ~1 day ago', () => {
expect(timeAgo('2026-04-18T22:00:00Z', NOW)).toBe('yesterday');
});
it('renders days for 2-6 days ago', () => {
expect(timeAgo('2026-04-16T22:00:00Z', NOW)).toBe('3d ago');
});
it('renders weeks for 7+ days ago', () => {
expect(timeAgo('2026-04-05T22:00:00Z', NOW)).toBe('2w ago');
});
it('returns empty string for bad input', () => {
expect(timeAgo('', NOW)).toBe('');
expect(timeAgo('not-a-date', NOW)).toBe('');
});
});
describe('formatBragLine', () => {
it('renders the full memory+entity+relation brag with thousands separators', () => {
const line = formatBragLine({
totalFrames: 1487,
totalEntities: 234,
totalRelations: 892,
workspaceCount: 5,
pendingCount: 0,
lastActiveIso: '2026-04-19T20:00:00Z',
lastActiveLabel: '2h ago',
});
// Plain words ("entities"/"relations" = database vocabulary) and NO
// "across N workspaces" clause — the total counts all minds while the
// cards show per-workspace counts; coupling them read as bad arithmetic.
expect(line).toBe('1,487 memories · 234 people, projects & things it knows · active 2h ago');
});
it('hides entity/relation chips when zero (first-run polish)', () => {
const line = formatBragLine({
totalFrames: 42,
totalEntities: 0,
totalRelations: 0,
workspaceCount: 1,
pendingCount: 0,
lastActiveIso: null,
lastActiveLabel: '',
});
expect(line).toBe('42 memories');
});
it('omits the active-suffix when lastActive is unknown', () => {
const line = formatBragLine({
totalFrames: 100,
totalEntities: 20,
totalRelations: 30,
workspaceCount: 2,
pendingCount: 0,
lastActiveIso: null,
lastActiveLabel: '',
});
expect(line).not.toContain('active');
expect(line).toBe('100 memories · 20 people, projects & things it knows');
});
it('suppresses the active-suffix when totalFrames is 0 even if lastActiveLabel is set', () => {
// FR #24/#26: fresh user has a default workspace (workspaceCount=1) whose
// `lastActive` is just the creation time. Without this guard the brag line
// reads "0 memories across 1 workspace · active 2h ago", which falsely
// implies the user has activity worth tracking. Suppress the suffix until
// the user actually has memories.
const line = formatBragLine({
totalFrames: 0,
totalEntities: 0,
totalRelations: 0,
workspaceCount: 1,
pendingCount: 0,
lastActiveIso: '2026-04-19T20:00:00Z',
lastActiveLabel: '2h ago',
});
expect(line).not.toContain('active');
expect(line).toBe('0 memories across 1 workspace');
});
it('renders the empty state copy when zero memories + zero workspaces', () => {
const line = formatBragLine({
totalFrames: 0,
totalEntities: 0,
totalRelations: 0,
workspaceCount: 0,
pendingCount: 0,
lastActiveIso: null,
lastActiveLabel: '',
});
expect(line).toBe('No memories yet — create a workspace to start building yours');
});
it('uses singular "memory" when count is 1; "across N workspaces" only on the zero-state', () => {
const line = formatBragLine({
totalFrames: 1,
totalEntities: 1,
totalRelations: 1,
workspaceCount: 1,
pendingCount: 0,
lastActiveIso: null,
lastActiveLabel: '',
});
expect(line).toContain('1 memory');
expect(line).not.toContain('across');
const zero = formatBragLine({
totalFrames: 0, totalEntities: 0, totalRelations: 0,
workspaceCount: 1, pendingCount: 0, lastActiveIso: null, lastActiveLabel: '',
});
expect(zero).toBe('0 memories across 1 workspace');
});
});

View File

@@ -0,0 +1,170 @@
/**
* L-22 — richer LoginBriefing "memory bragging" copy.
*
* Pure helpers that turn memory stats + workspace summaries into the
* one-line brag rendered in the briefing header. Kept out of the React
* component so the formatting rules are testable without mounting the
* overlay.
*
* Stats come from `adapter.getMemoryStats()` — frames / entities /
* relations across personal + workspace minds — and the workspace
* summaries already computed by the briefing's `loadBriefing()`.
*/
export interface BriefingStats {
frames: number;
entities: number;
relations: number;
}
export interface BriefingWorkspaceSummary {
lastActive?: string | null;
pendingTasks?: readonly unknown[] | null;
}
export interface BragSummary {
totalFrames: number;
totalEntities: number;
totalRelations: number;
workspaceCount: number;
pendingCount: number;
/** ISO timestamp of the most recent cross-workspace activity, or null. */
lastActiveIso: string | null;
/** Human-readable "yesterday", "3d ago", "", etc. — empty when unknown. */
lastActiveLabel: string;
}
/** Minimum content length the briefing considers "real" memory. */
export const MIN_BRAG_FRAME_COUNT = 0;
/**
* Build the brag summary from adapter stats + workspace summaries.
*
* Uses `stats.total` when present (server-side aggregate across personal
* + workspace), else falls back to summing personal + workspace manually
* to stay correct when the server returns only the per-scope pieces.
*/
export function computeBragSummary(
stats: {
personal?: BriefingStats | null;
workspace?: BriefingStats | null;
total?: BriefingStats | null;
} | null | undefined,
summaries: readonly BriefingWorkspaceSummary[] = [],
now: number = Date.now(),
): BragSummary {
const personal = stats?.personal ?? { frames: 0, entities: 0, relations: 0 };
const workspace = stats?.workspace ?? { frames: 0, entities: 0, relations: 0 };
const total = stats?.total ?? {
frames: personal.frames + workspace.frames,
entities: personal.entities + workspace.entities,
relations: personal.relations + workspace.relations,
};
const lastActiveIso = pickGlobalLastActive(summaries);
const pendingCount = summaries.reduce(
(acc, s) => acc + (Array.isArray(s.pendingTasks) ? s.pendingTasks.length : 0),
0,
);
return {
totalFrames: total.frames,
totalEntities: total.entities,
totalRelations: total.relations,
workspaceCount: summaries.length,
pendingCount,
lastActiveIso,
lastActiveLabel: lastActiveIso ? timeAgo(lastActiveIso, now) : '',
};
}
/**
* Find the most recent ISO timestamp across workspace summaries.
* Returns null when none have a valid lastActive string.
*/
export function pickGlobalLastActive(
summaries: readonly BriefingWorkspaceSummary[],
): string | null {
let best: { iso: string; time: number } | null = null;
for (const s of summaries) {
const iso = typeof s.lastActive === 'string' ? s.lastActive.trim() : '';
if (!iso) continue;
const time = Date.parse(iso);
if (!Number.isFinite(time)) continue;
if (!best || time > best.time) {
best = { iso, time };
}
}
return best?.iso ?? null;
}
/**
* Relative time formatter matching the rest of the briefing (matches
* the existing in-component `timeAgo` helper so the header + per-frame
* labels stay consistent). Pure — accepts a `now` override for tests.
*/
export function timeAgo(iso: string, now: number = Date.now()): string {
if (!iso) return '';
const parsed = Date.parse(iso);
if (!Number.isFinite(parsed)) return '';
const diffMs = now - parsed;
const mins = Math.floor(diffMs / 60_000);
if (mins < 1) return 'just now';
if (mins < 60) return `${mins}m ago`;
const hours = Math.floor(mins / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
if (days === 1) return 'yesterday';
if (days < 7) return `${days}d ago`;
const weeks = Math.floor(days / 7);
return `${weeks}w ago`;
}
/**
* Render the single brag line that replaces the terse
* "N memories across N workspaces" header. Example outputs:
*
* "1,487 memories · 234 people, projects & things it knows across 5 workspaces · active 3h ago"
* "42 memories across 1 workspace" (low counts — entity chip hidden)
* "No memories yet — create a workspace to start building yours"
*
* Plain words only: "entities"/"relations" are database vocabulary — every
* judge persona below "developer" flagged them as jargon in a greeting.
*/
export function formatBragLine(summary: BragSummary): string {
if (summary.totalFrames === 0 && summary.workspaceCount === 0) {
return 'No memories yet — create a workspace to start building yours';
}
const parts: string[] = [];
parts.push(`${summary.totalFrames.toLocaleString('en-US')} ${plural('memory', summary.totalFrames)}`);
// Hide the knowledge chip until the substrate has enough to brag about —
// avoids "0 people, projects & things" cluttering a first-run header.
if (summary.totalEntities > 0) {
parts.push(`${summary.totalEntities.toLocaleString('en-US')} people, projects & things it knows`);
}
let line = parts.join(' · ');
// No "across N workspaces" clause: the header total counts ALL minds while
// the cards below show per-workspace counts — coupling them invited users
// to sum the cards and catch an apparent arithmetic lie (judge-flagged).
if (summary.totalFrames === 0) {
line += ` across ${summary.workspaceCount} ${plural('workspace', summary.workspaceCount)}`;
}
// FR #24/#26: suppress the "active Xago" suffix on a fresh-state user
// (totalFrames === 0). The lastActive timestamp on a brand-new workspace
// tracks creation time, not activity, so labels like "active 2h ago" or
// "active 1w ago" mislead — they imply work happened that hasn't.
if (summary.lastActiveLabel && summary.totalFrames > 0) {
line += ` · active ${summary.lastActiveLabel}`;
}
return line;
}
function plural(word: string, count: number): string {
if (count === 1) return word;
if (word === 'memory') return 'memories';
if (word === 'entity') return 'entities';
return `${word}s`;
}

View File

@@ -0,0 +1,114 @@
/**
* M-25 / ENG-4 — LoginBriefing visibility contract regression.
*
* Guards the two independent reasons the briefing would be hidden
* (E2E skip vs. permanent user dismiss) and the localStorage key
* contract for the "Don't show again" flag.
*/
import { describe, it, expect, beforeEach } from 'vitest';
import {
shouldShowLoginBriefing,
readLoginBriefingDismissed,
writeLoginBriefingDismissed,
writeLoginBriefingLastDismissedAt,
readMinutesSinceLastDismiss,
LOGIN_BRIEFING_DISMISSED_KEY,
LOGIN_BRIEFING_LAST_DISMISSED_AT_KEY,
LOGIN_BRIEFING_COOLDOWN_MINUTES,
} from './login-briefing';
describe('shouldShowLoginBriefing', () => {
it('shows the briefing when neither gate trips', () => {
expect(shouldShowLoginBriefing({ skipBriefing: false, permanentlyDismissed: false })).toBe(true);
});
it('hides when ?skipBriefing=true (E2E escape hatch)', () => {
expect(shouldShowLoginBriefing({ skipBriefing: true, permanentlyDismissed: false })).toBe(false);
});
it('hides when the user has permanently dismissed', () => {
expect(shouldShowLoginBriefing({ skipBriefing: false, permanentlyDismissed: true })).toBe(false);
});
it('hides when both gates are active', () => {
expect(shouldShowLoginBriefing({ skipBriefing: true, permanentlyDismissed: true })).toBe(false);
});
it('hides within the dismiss cooldown — a quick reload must not re-greet', () => {
expect(shouldShowLoginBriefing({
skipBriefing: false, permanentlyDismissed: false, minutesSinceLastDismiss: 2,
})).toBe(false);
});
it('shows again once the cooldown has elapsed', () => {
expect(shouldShowLoginBriefing({
skipBriefing: false, permanentlyDismissed: false,
minutesSinceLastDismiss: LOGIN_BRIEFING_COOLDOWN_MINUTES + 1,
})).toBe(true);
});
it('null minutesSinceLastDismiss (never dismissed) shows the briefing', () => {
expect(shouldShowLoginBriefing({
skipBriefing: false, permanentlyDismissed: false, minutesSinceLastDismiss: null,
})).toBe(true);
});
});
describe('last-dismissed-at cooldown storage', () => {
beforeEach(() => {
window.localStorage.removeItem(LOGIN_BRIEFING_LAST_DISMISSED_AT_KEY);
});
it('returns null when never dismissed', () => {
expect(readMinutesSinceLastDismiss()).toBe(null);
});
it('round-trips a dismiss timestamp into minutes', () => {
const now = 10_000_000;
writeLoginBriefingLastDismissedAt(now - 5 * 60_000);
expect(readMinutesSinceLastDismiss(now)).toBe(5);
});
it('returns null for a corrupt stored value', () => {
window.localStorage.setItem(LOGIN_BRIEFING_LAST_DISMISSED_AT_KEY, 'not-a-number');
expect(readMinutesSinceLastDismiss()).toBe(null);
});
});
describe('readLoginBriefingDismissed / writeLoginBriefingDismissed', () => {
beforeEach(() => {
window.localStorage.removeItem(LOGIN_BRIEFING_DISMISSED_KEY);
});
it('returns false when nothing is stored', () => {
expect(readLoginBriefingDismissed()).toBe(false);
});
it('returns true only when the stored value is the literal "true"', () => {
window.localStorage.setItem(LOGIN_BRIEFING_DISMISSED_KEY, 'true');
expect(readLoginBriefingDismissed()).toBe(true);
});
it('returns false for any other stored literal', () => {
for (const v of ['false', '1', 'yes', '']) {
window.localStorage.setItem(LOGIN_BRIEFING_DISMISSED_KEY, v);
expect(readLoginBriefingDismissed(), `stored=${JSON.stringify(v)}`).toBe(false);
}
});
it('write(true) then read returns true', () => {
writeLoginBriefingDismissed(true);
expect(readLoginBriefingDismissed()).toBe(true);
});
it('write(false) then read returns false — supports "show again" reset', () => {
writeLoginBriefingDismissed(true);
writeLoginBriefingDismissed(false);
expect(readLoginBriefingDismissed()).toBe(false);
});
it('the storage key matches the documented literal', () => {
// Pins the key so a rename ships a migration, not a silent reset.
expect(LOGIN_BRIEFING_DISMISSED_KEY).toBe('waggle:login-briefing-dismissed');
});
});

View File

@@ -0,0 +1,100 @@
/**
* LoginBriefing visibility contract (M-25 / ENG-4).
*
* The briefing shows on every fresh session by default. A user who
* clicks "Don't show again" sets a persistent localStorage flag that
* hides it permanently across sessions. The per-session behaviour is
* implicit — React state naturally resets on each full page load, so
* all we need to gate is the permanent dismiss.
*
* Extra knobs:
* - `?skipBriefing=true` URL param: short-circuits for E2E runs.
* - Settings toggle: lets a user who changed their mind re-enable
* the briefing via `writeLoginBriefingDismissed(false)`.
*/
export const LOGIN_BRIEFING_DISMISSED_KEY = 'waggle:login-briefing-dismissed';
export const LOGIN_BRIEFING_LAST_DISMISSED_AT_KEY = 'waggle:login-briefing-last-dismissed-at';
/**
* Re-show cooldown after a dismiss. A reload minutes after dismissing must
* NOT re-greet "you've been away N days" — repeating the welcome to someone
* who was just here breaks the "it knows me" promise the briefing exists for.
*/
export const LOGIN_BRIEFING_COOLDOWN_MINUTES = 30;
export interface LoginBriefingVisibilityInput {
/** URL `?skipBriefing=true` — E2E escape hatch. */
skipBriefing: boolean;
/** Persistent "Don't show again" flag from localStorage. */
permanentlyDismissed: boolean;
/** Minutes since the user last dismissed the briefing; null = never. */
minutesSinceLastDismiss?: number | null;
}
/**
* Decide whether to render the LoginBriefing at the start of a session.
* Pure function — all side effects are the caller's responsibility.
*/
export function shouldShowLoginBriefing(input: LoginBriefingVisibilityInput): boolean {
if (input.skipBriefing) return false;
if (input.permanentlyDismissed) return false;
if (
input.minutesSinceLastDismiss != null &&
input.minutesSinceLastDismiss < LOGIN_BRIEFING_COOLDOWN_MINUTES
) {
return false;
}
return true;
}
/** Non-hook snapshot of the persistent dismiss flag. */
export function readLoginBriefingDismissed(): boolean {
try {
return window.localStorage.getItem(LOGIN_BRIEFING_DISMISSED_KEY) === 'true';
} catch {
return false;
}
}
/** Persist the dismiss flag. Writes the literal string "true" / "false". */
export function writeLoginBriefingDismissed(value: boolean): void {
try {
window.localStorage.setItem(LOGIN_BRIEFING_DISMISSED_KEY, String(value));
} catch {
// no-op — storage disabled
}
}
/** Record "the user dismissed the briefing just now" for the cooldown gate. */
export function writeLoginBriefingLastDismissedAt(now: number = Date.now()): void {
try {
window.localStorage.setItem(LOGIN_BRIEFING_LAST_DISMISSED_AT_KEY, String(now));
} catch {
// no-op — storage disabled
}
}
/** Minutes since the last dismiss, or null if never dismissed / unreadable. */
export function readMinutesSinceLastDismiss(now: number = Date.now()): number | null {
try {
const raw = window.localStorage.getItem(LOGIN_BRIEFING_LAST_DISMISSED_AT_KEY);
if (!raw) return null;
const ts = Number(raw);
if (!Number.isFinite(ts)) return null;
return (now - ts) / 60_000;
} catch {
return null;
}
}
/** Read the `?skipBriefing=true` URL param; safe to call in SSR contexts. */
export function readSkipBriefingParam(): boolean {
if (typeof window === 'undefined') return false;
try {
const params = new URLSearchParams(window.location.search);
return params.get('skipBriefing') === 'true';
} catch {
return false;
}
}

View File

@@ -0,0 +1,103 @@
import { describe, it, expect } from 'vitest';
import { dedupeMemoriesForDisplay } from './memory-dedup';
import type { Memory } from '@/lib/types';
const mem = (over: Partial<Memory> = {}): Memory => ({
id: '1',
kind: 'fact',
title: 'GTM fact',
content: 'The Germany GTM launches in Q3.',
scope: 'workspace',
workspaceId: 'w1',
source: 'user_stated',
sourceId: null,
sourceUrl: null,
importance: 'normal',
status: 'active',
confidence: 50,
createdAt: '2026-06-11T08:00:00.000Z',
...over,
});
describe('dedupeMemoriesForDisplay', () => {
it('collapses exact duplicates and counts them', () => {
const result = dedupeMemoriesForDisplay([mem({ id: 'a' }), mem({ id: 'b' }), mem({ id: 'c' })]);
expect(result).toHaveLength(1);
expect(result[0].duplicateCount).toBe(3);
});
it('collapses near-duplicates differing only by an embedded audit-run id', () => {
const result = dedupeMemoriesForDisplay([
mem({ id: 'a', title: 'Benchmark', content: 'LoCoMo scored 86.49 (audit-run-id: 3f9a2b)' }),
mem({ id: 'b', title: 'Benchmark', content: 'LoCoMo scored 86.49 (audit-run-id: 71ee44)' }),
]);
expect(result).toHaveLength(1);
expect(result[0].duplicateCount).toBe(2);
});
it('collapses a growing-composite chain (same title, each record a prefix of the next)', () => {
// Reproduces the live wave-4 QA finding: a benchmark "anchor" record kept
// getting re-written with more appended `---`-separated turns over time,
// so every copy has different LENGTH content and pass-1's exact-key match
// never merges them, even though they're visibly "the same memory".
const base = 'BENCHMARK: User prefers TypeScript, works at Egzakta Group, building Waggle OS. Timestamp: 1782400441971';
const result = dedupeMemoriesForDisplay([
mem({ id: 'shortest', title: 'BENCHMARK: User prefers TypeScript…', content: base }),
mem({ id: 'middle', title: 'BENCHMARK: User prefers TypeScript…', content: `${base}\n---\nI lead a team building an enterprise AI platform.` }),
mem({ id: 'longest', title: 'BENCHMARK: User prefers TypeScript…', content: `${base}\n---\nI lead a team building an enterprise AI platform.\n---\nComposite benchmark test memory anchor` }),
]);
expect(result).toHaveLength(1);
expect(result[0].memory.id).toBe('longest');
expect(result[0].duplicateCount).toBe(3);
});
it('does NOT collapse two records that share content but have different titles', () => {
const result = dedupeMemoriesForDisplay([
mem({ id: '1', title: 'GTM fact' }),
mem({ id: '2', title: 'Second' }),
]);
expect(result).toHaveLength(2);
expect(result.every((r) => r.duplicateCount === 1)).toBe(true);
});
it('prefers an active record over an archived one as the representative', () => {
const result = dedupeMemoriesForDisplay([
mem({ id: 'archived', status: 'archived' }),
mem({ id: 'active', status: 'active' }),
]);
expect(result).toHaveLength(1);
expect(result[0].memory.id).toBe('active');
expect(result[0].duplicateCount).toBe(2);
});
it('breaks status ties by higher confidence', () => {
const result = dedupeMemoriesForDisplay([
mem({ id: 'lo', confidence: 30 }),
mem({ id: 'hi', confidence: 90 }),
]);
expect(result[0].memory.id).toBe('hi');
});
it('keeps short/empty-content records distinct (min-length guard)', () => {
const result = dedupeMemoriesForDisplay([
mem({ id: '1', title: '', content: 'hi' }),
mem({ id: '2', title: '', content: 'ok' }),
]);
expect(result).toHaveLength(2);
});
it('preserves first-seen order', () => {
const result = dedupeMemoriesForDisplay([
mem({ id: '1', title: 'Alpha', content: 'First distinct memory about alpha topic' }),
mem({ id: '2', title: 'Beta', content: 'Second distinct memory about beta topic' }),
]);
expect(result.map((r) => r.memory.id)).toEqual(['1', '2']);
});
it('does not mutate the input array or its members', () => {
const input = [mem({ id: 'a' }), mem({ id: 'b' })];
const snapshot = JSON.parse(JSON.stringify(input));
dedupeMemoriesForDisplay(input);
expect(input).toEqual(snapshot);
});
});

View File

@@ -0,0 +1,120 @@
import type { Memory } from '@/lib/types';
import { normalizeMemoryKey, isGroupableKey } from '@/lib/memory-text-normalize';
/**
* W4B (F22) — display-layer dedup for the Memories tab.
*
* Groups near-identical memories (same normalized title + content, ignoring
* embedded volatile ids/timestamps) and picks one representative per group so
* the list stops showing the same fact several times. This is a rendering-only
* collapse: every underlying record is left untouched in the store, and the
* representative card's id is the real id all row actions (edit/archive/delete/
* erase) operate on.
*
* The group key includes the TITLE deliberately — two records that legitimately
* share body text but differ in what they're about (e.g. the two-mind test
* fixture) must stay separate.
*/
export interface DedupedMemory {
memory: Memory;
/** How many raw records collapsed into this representative (>= 1). */
duplicateCount: number;
}
/** Preference order for which record represents a group (lower = preferred). */
function statusRank(status: Memory['status']): number {
switch (status) {
case 'active': return 0;
case 'unreviewed': return 1;
case 'low_confidence': return 2;
case 'conflict': return 3;
case 'deprecated': return 4;
case 'archived': return 5;
default: return 3;
}
}
function createdMs(m: Memory): number {
const parsed = Date.parse(m.createdAt);
return Number.isFinite(parsed) ? parsed : 0;
}
/** True if `a` is a better representative than `b`. */
function isBetterRepresentative(a: Memory, b: Memory): boolean {
const rankDiff = statusRank(a.status) - statusRank(b.status);
if (rankDiff !== 0) return rankDiff < 0;
const confA = a.confidence ?? 0;
const confB = b.confidence ?? 0;
if (confA !== confB) return confA > confB;
return createdMs(a) > createdMs(b);
}
/**
* Group by normalized title+content and return one representative per group,
* preserving first-seen group order (the server already returns createdAt-desc).
* Records whose normalized key is too short to group on are always kept distinct.
* Does not mutate the input.
*/
export function dedupeMemoriesForDisplay(memories: readonly Memory[]): DedupedMemory[] {
const groups = new Map<string, DedupedMemory>();
const order: string[] = [];
memories.forEach((m, index) => {
const titleKey = normalizeMemoryKey(m.title);
const contentKey = normalizeMemoryKey(m.content);
const composite = `${titleKey} ${contentKey}`;
// Too-thin keys (empty/short) can't be trusted to mean "the same memory" -
// give each such record its own group so unrelated stubs never merge.
const key = isGroupableKey(titleKey + contentKey) ? composite : `__unique__:${m.id}:${index}`;
const existing = groups.get(key);
if (!existing) {
groups.set(key, { memory: m, duplicateCount: 1 });
order.push(key);
return;
}
existing.duplicateCount += 1;
if (isBetterRepresentative(m, existing.memory)) {
existing.memory = m;
}
});
// Second pass: collapse a GROWING-COMPOSITE chain - a repeatedly re-written
// "anchor" record where each new write is the previous content plus more
// appended turns (same title, content is a strict prefix of a later sibling).
// These aren't equal after normalization (they differ in length), so pass 1
// never merges them, but they are visibly "the same memory" to a user.
// Bucket by normalized title only, then absorb any entry whose normalized
// content is a prefix of a longer sibling's - the longest one wins.
const byTitle = new Map<string, DedupedMemory[]>();
for (const key of order) {
const entry = groups.get(key)!;
const titleKey = normalizeMemoryKey(entry.memory.title);
if (!isGroupableKey(titleKey)) continue;
const bucket = byTitle.get(titleKey);
if (bucket) bucket.push(entry);
else byTitle.set(titleKey, [entry]);
}
const absorbed = new Set<DedupedMemory>();
for (const bucket of byTitle.values()) {
if (bucket.length < 2) continue;
const withContentKey = bucket
.map((entry) => ({ entry, contentKey: normalizeMemoryKey(entry.memory.content) }))
.sort((a, b) => b.contentKey.length - a.contentKey.length);
for (let i = 0; i < withContentKey.length; i++) {
const longer = withContentKey[i];
if (absorbed.has(longer.entry)) continue;
for (let j = i + 1; j < withContentKey.length; j++) {
const shorter = withContentKey[j];
if (absorbed.has(shorter.entry)) continue;
if (shorter.contentKey.length > 0 && longer.contentKey.startsWith(shorter.contentKey)) {
longer.entry.duplicateCount += shorter.entry.duplicateCount;
absorbed.add(shorter.entry);
}
}
}
}
return order.map((key) => groups.get(key)!).filter((entry) => !absorbed.has(entry));
}

View File

@@ -0,0 +1,105 @@
/**
* M-22 / ENG-1 — memory recall toast trigger + query-building regression.
*/
import { describe, it, expect } from 'vitest';
import {
MEMORY_RECALL_TRIGGER_AT,
MEMORY_RECALL_PREVIEW_LIMIT,
shouldFireMemoryRecall,
buildRecallQuery,
previewRecall,
} from './memory-recall-toast';
describe('shouldFireMemoryRecall', () => {
it('fires exactly at the trigger when not yet fired', () => {
expect(shouldFireMemoryRecall({ userMessageCount: MEMORY_RECALL_TRIGGER_AT, alreadyFired: false })).toBe(true);
});
it('suppresses when already fired', () => {
expect(shouldFireMemoryRecall({ userMessageCount: MEMORY_RECALL_TRIGGER_AT, alreadyFired: true })).toBe(false);
});
it('does not fire below the trigger', () => {
for (let i = 0; i < MEMORY_RECALL_TRIGGER_AT; i += 1) {
expect(shouldFireMemoryRecall({ userMessageCount: i, alreadyFired: false })).toBe(false);
}
});
it('does not re-fire past the trigger — miss once, miss forever', () => {
expect(shouldFireMemoryRecall({ userMessageCount: MEMORY_RECALL_TRIGGER_AT + 1, alreadyFired: false })).toBe(false);
expect(shouldFireMemoryRecall({ userMessageCount: 50, alreadyFired: false })).toBe(false);
});
it('defensive against non-finite counts', () => {
expect(shouldFireMemoryRecall({ userMessageCount: Number.NaN, alreadyFired: false })).toBe(false);
expect(shouldFireMemoryRecall({ userMessageCount: Number.POSITIVE_INFINITY, alreadyFired: false })).toBe(false);
});
});
describe('buildRecallQuery', () => {
it('returns empty string when there are no user messages', () => {
expect(buildRecallQuery([])).toBe('');
expect(buildRecallQuery([{ role: 'assistant', content: 'hi' }])).toBe('');
});
it('joins the last 3 user messages in order', () => {
const messages = [
{ role: 'user', content: 'one' },
{ role: 'assistant', content: 'ack' },
{ role: 'user', content: 'two' },
{ role: 'user', content: 'three' },
{ role: 'user', content: 'four' },
];
expect(buildRecallQuery(messages)).toBe('two three four');
});
it('collapses whitespace in each message', () => {
const messages = [
{ role: 'user', content: 'hello world\n\twith noise' },
];
expect(buildRecallQuery(messages)).toBe('hello world with noise');
});
it('skips user messages whose content is empty / whitespace', () => {
const messages = [
{ role: 'user', content: '' },
{ role: 'user', content: ' ' },
{ role: 'user', content: 'real question' },
];
expect(buildRecallQuery(messages)).toBe('real question');
});
it('tolerates null / undefined content', () => {
const messages = [
{ role: 'user', content: null },
{ role: 'user', content: undefined },
{ role: 'user', content: 'ok' },
];
expect(buildRecallQuery(messages)).toBe('ok');
});
it('caps very long queries at 500 characters', () => {
const messages = [{ role: 'user', content: 'x'.repeat(2000) }];
expect(buildRecallQuery(messages).length).toBe(500);
});
});
describe('previewRecall', () => {
it('passes short content through unchanged (except whitespace)', () => {
expect(previewRecall('hello world')).toBe('hello world');
expect(previewRecall(' hello world ')).toBe('hello world');
});
it('truncates at word boundary with an ellipsis', () => {
const long = 'a b c d e f g h i '.repeat(20); // > preview limit
const out = previewRecall(long);
expect(out.length).toBeLessThanOrEqual(MEMORY_RECALL_PREVIEW_LIMIT + 1); // + ellipsis
expect(out.endsWith('\u2026')).toBe(true);
});
it('respects a custom limit', () => {
const out = previewRecall('some long content here that goes on', 10);
expect(out.length).toBeLessThanOrEqual(11);
expect(out.endsWith('\u2026')).toBe(true);
});
});

View File

@@ -0,0 +1,71 @@
/**
* "I just remembered" toast trigger (M-22 / ENG-1).
*
* Fires once per chat session when the user has sent exactly
* MEMORY_RECALL_TRIGGER_AT messages and a memory search returns at
* least one relevant frame. The user-facing intent: Waggle proves
* its long-term memory by surfacing something genuinely relevant
* right when the conversation is picking up.
*/
/** Number of user messages at which the recall toast should fire. */
export const MEMORY_RECALL_TRIGGER_AT = 5;
/** Maximum characters of recalled content to show in the toast body. */
export const MEMORY_RECALL_PREVIEW_LIMIT = 150;
/** How many recent user messages to fold into the search query. */
export const MEMORY_RECALL_QUERY_WINDOW = 3;
export interface MemoryRecallTriggerInput {
/** Count of user-role messages in the current session. */
readonly userMessageCount: number;
/** Whether this session has already fired the toast. */
readonly alreadyFired: boolean;
}
/**
* Pure decision: should the recall toast fire right now?
* True only when the count hits exactly the trigger and we haven't
* fired yet. Returning false once the count moves past the trigger
* prevents late firing if messages replay (e.g. session reload with
* saved history).
*/
export function shouldFireMemoryRecall(input: MemoryRecallTriggerInput): boolean {
if (input.alreadyFired) return false;
if (!Number.isFinite(input.userMessageCount)) return false;
return input.userMessageCount === MEMORY_RECALL_TRIGGER_AT;
}
export interface MessageLike {
readonly role: string;
readonly content?: string | null;
}
/**
* Build a recall query from the last MEMORY_RECALL_QUERY_WINDOW user
* messages. Collapses whitespace, trims, and caps at 500 characters
* — longer queries dilute semantic search signal.
*/
export function buildRecallQuery(messages: readonly MessageLike[]): string {
const userMsgs = messages
.filter(m => m.role === 'user' && typeof m.content === 'string' && m.content.trim().length > 0);
const window = userMsgs.slice(-MEMORY_RECALL_QUERY_WINDOW);
const joined = window
.map(m => (m.content as string).replace(/\s+/g, ' ').trim())
.join(' ');
return joined.slice(0, 500);
}
/**
* Trim a recalled frame's content into a toast-sized preview. Cuts on
* a word boundary when possible and appends an ellipsis if truncated.
*/
export function previewRecall(content: string, limit: number = MEMORY_RECALL_PREVIEW_LIMIT): string {
const collapsed = content.replace(/\s+/g, ' ').trim();
if (collapsed.length <= limit) return collapsed;
const cut = collapsed.slice(0, limit);
const lastSpace = cut.lastIndexOf(' ');
const base = lastSpace > limit * 0.6 ? cut.slice(0, lastSpace) : cut;
return `${base}\u2026`;
}

View File

@@ -0,0 +1,234 @@
import { describe, it, expect } from 'vitest';
import {
normalizeMemoryKey,
isGroupableKey,
MIN_NORMALIZED_KEY_CHARS,
buildMemoryPreview,
humanizeMemoryTitle,
sentenceTruncate,
} from './memory-text-normalize';
describe('normalizeMemoryKey', () => {
it('collapses two strings that differ only by an embedded audit-run id', () => {
const a = normalizeMemoryKey('BENCHMARK completed for audit-run-id: 3f9a2b0c on the LoCoMo suite');
const b = normalizeMemoryKey('BENCHMARK completed for audit-run-id: 71ee4400 on the LoCoMo suite');
expect(a).toBe(b);
expect(a).toContain('benchmark completed');
expect(a).not.toContain('3f9a2b0c');
});
it('strips bare "audit-<digits>" ids without requiring the word "run"', () => {
// Real live-data shape found in wave-4 QA: "audit-1782648502308", not the
// "audit-run-id: …" form RUN_ID_RE already covers.
const a = normalizeMemoryKey('Imran uses 2x2 frameworks and wants every decision remembered (audit-1782648502308)');
const b = normalizeMemoryKey('Imran uses 2x2 frameworks and wants every decision remembered (audit-1782638749061)');
expect(a).toBe(b);
expect(a).toContain('imran uses 2x2 frameworks');
});
it('does NOT strip ordinary prose containing the word "audit" (e.g. "audit trail")', () => {
const key = normalizeMemoryKey('This constitutes an audit trail requirement for the compliance review');
expect(key).toContain('audit trail');
});
it('strips the whole "Audit run audit-<id>" phrase, label words included (live wave-5 QA)', () => {
// The exact live shape: label "Audit run" + a doubled "audit-<digits>" id.
// Stripping only the id left "audit run" behind -> two dedup keys
// ("…account" vs "…account audit run") -> the SAME fact showed twice in the
// login briefing. The label words must go too.
const withRun = normalizeMemoryKey('Imran uses 2x2 frameworks and wants every client decision remembered by account. Audit run audit-1782648502308.');
const without = normalizeMemoryKey('Imran uses 2x2 frameworks and wants every client decision remembered by account.');
expect(withRun).toBe(without);
expect(withRun).not.toContain('audit');
expect(withRun).not.toContain('1782648502308');
});
it('strips "benchmark run <date>" as a phrase but keeps "audit trail" prose', () => {
const a = normalizeMemoryKey('Deploy uses a benchmark run 20260704 marker');
const b = normalizeMemoryKey('Deploy uses a benchmark run 20260812 marker');
expect(a).toBe(b);
// ordinary prose containing "audit" (no run/id) is untouched
expect(normalizeMemoryKey('an audit trail requirement')).toContain('audit trail');
});
it('strips a raw epoch-ms "Timestamp: …" label (not just ISO-8601)', () => {
const a = normalizeMemoryKey('BENCHMARK anchor fact. Timestamp: 1782400441971');
const b = normalizeMemoryKey('BENCHMARK anchor fact. Timestamp: 1782639999999');
expect(a).toBe(b);
expect(a).toContain('benchmark anchor fact');
});
it('strips BENCH-SECRET benchmark-harness tokens', () => {
const a = normalizeMemoryKey('Confidential: BENCH-SECRET-5yu27cwrmsv');
const b = normalizeMemoryKey('Confidential: BENCH-SECRET-9zz10qexampl');
expect(a).toBe(b);
expect(a).toContain('confidential');
});
it('strips UUIDs', () => {
const a = normalizeMemoryKey('Imran prefers dark mode (uuid a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d)');
const b = normalizeMemoryKey('Imran prefers dark mode (uuid ffffffff-1111-4222-8333-444455556666)');
expect(a).toBe(b);
expect(a).toContain('imran prefers dark mode');
});
it('strips ISO timestamps', () => {
const a = normalizeMemoryKey('Session recorded 2026-07-01T12:30:00Z about the launch plan');
const b = normalizeMemoryKey('Session recorded 2026-07-04T09:00:00Z about the launch plan');
expect(a).toBe(b);
});
it('case-folds and collapses whitespace', () => {
expect(normalizeMemoryKey(' The Launch\nPlan ')).toBe('the launch plan');
});
it('returns empty string for nullish input', () => {
expect(normalizeMemoryKey(null)).toBe('');
expect(normalizeMemoryKey(undefined)).toBe('');
expect(normalizeMemoryKey('')).toBe('');
});
it('does not merge genuinely different facts (guard via isGroupableKey)', () => {
const a = normalizeMemoryKey('Ships in Q3');
const b = normalizeMemoryKey('Ships in Q4');
expect(a).not.toBe(b);
});
it('min-length guard flags short normalized keys as non-groupable', () => {
expect(isGroupableKey(normalizeMemoryKey('#42'))).toBe(false);
expect(isGroupableKey(normalizeMemoryKey(''))).toBe(false);
expect(normalizeMemoryKey('#42').length).toBeLessThan(MIN_NORMALIZED_KEY_CHARS);
expect(isGroupableKey(normalizeMemoryKey('The Germany GTM launches in Q3'))).toBe(true);
});
it('does not mutate or retain state across calls', () => {
const input = 'audit-run-id: abc123 stable body text here';
const first = normalizeMemoryKey(input);
const second = normalizeMemoryKey(input);
expect(first).toBe(second);
});
});
describe('buildMemoryPreview (round-7 fix 3 — humanized row titles)', () => {
it('skips a bare "Timestamp: <digits>" lead line and titles with the first human line', () => {
const { title, excerpt } = buildMemoryPreview(
'Timestamp: 1782400441971\nImran prefers dark mode in every editor he uses',
);
expect(title).toBe('Imran prefers dark mode in every editor he uses');
expect(excerpt).toBe('');
});
it('de-slugifies AND lifts the handoff prefix out of a "[Harvest:…] <slug>" lead', () => {
// round-9 Lane C fix 1: the de-slugged "session handoff 2026 06 24 s2 final"
// now humanizes to a clean title + a provenance meta chip.
const { title, titleMeta } = buildMemoryPreview(
'[Harvest:claude-code] session-handoff-2026-06-24-s2-final\nBody of the harvested note follows here.',
);
expect(title).toBe('Final');
expect(titleMeta).toBe('session handoff · 2026-06-24 · s2');
});
it('lifts a "session handoff <date> sN" prefix into titleMeta and humanizes the remainder', () => {
const { title, titleMeta } = buildMemoryPreview(
'session handoff 2026 06 24 s2 warm hive pr8 landing shipped roadmap complete\nStart here next session.',
);
expect(title).toBe('Warm hive PR8 landing shipped roadmap complete');
expect(titleMeta).toBe('session handoff · 2026-06-24 · s2');
});
it('leaves a non-handoff title untouched with no titleMeta', () => {
const { title, titleMeta } = buildMemoryPreview('The launch plan needs a review\nbody');
expect(title).toBe('The launch plan needs a review');
expect(titleMeta).toBeUndefined();
});
it('keeps the remainder as the title when the harvest prefix wraps human text', () => {
const { title } = buildMemoryPreview('[Harvest:claude] Marko prefers dark mode across all tools');
expect(title).toBe('Marko prefers dark mode across all tools');
});
it('advances past a harvest lead with no usable remainder to the first human line', () => {
const { title } = buildMemoryPreview(
'[Harvest:gemini]\n#42\nThe Germany GTM launch plan needs a final review',
);
expect(title).toBe('The Germany GTM launch plan needs a final review');
});
it('falls back to the raw first line when nothing qualifies (today\'s behavior)', () => {
const { title } = buildMemoryPreview('Timestamp: 1782400441971');
expect(title).toBe('Timestamp: 1782400441971');
});
it('leaves ordinary content untouched: first line = title, rest = excerpt', () => {
const { title, excerpt } = buildMemoryPreview('The launch plan\nWe ship Q3. Then we review.');
expect(title).toBe('The launch plan');
expect(excerpt).toBe('We ship Q3. Then we review.');
});
it('still strips markdown tokens for the display split', () => {
const { title } = buildMemoryPreview('## Weekly review notes for the team\nbody');
expect(title).toBe('Weekly review notes for the team');
});
it('excludes skipped machine lines from the excerpt', () => {
const { excerpt } = buildMemoryPreview(
'Timestamp: 1782400441971\nA human title line for this memory\nAnd the excerpt body.',
);
expect(excerpt).toBe('And the excerpt body.');
expect(excerpt).not.toContain('1782400441971');
});
it('handles empty content without throwing', () => {
expect(buildMemoryPreview('')).toEqual({ title: '', excerpt: '' });
});
});
describe('humanizeMemoryTitle (round-9 Lane C fix 1)', () => {
it('lifts a full "session handoff YYYY MM DD sN" prefix and uppercases PR tokens', () => {
const { title, meta } = humanizeMemoryTitle(
'session handoff 2026 06 24 s2 warm hive pr8 landing shipped roadmap complete',
);
expect(title).toBe('Warm hive PR8 landing shipped roadmap complete');
expect(meta).toBe('session handoff · 2026-06-24 · s2');
});
it('matches dash-separated handoff slugs and a missing session number', () => {
const { title, meta } = humanizeMemoryTitle('handoff 2026-07-01-billing auth shipped');
expect(title).toBe('Billing auth shipped');
expect(meta).toBe('session handoff · 2026-07-01');
});
it('is case-insensitive and matches a "project session handoff" label', () => {
const { title, meta } = humanizeMemoryTitle('Project Session Handoff 2026 05 20 s1 AI-OS phases landed');
expect(title).toBe('AI-OS phases landed');
expect(meta).toBe('session handoff · 2026-05-20 · s1');
});
it('leaves ordinary titles untouched with no meta', () => {
expect(humanizeMemoryTitle('Marko prefers dark mode')).toEqual({ title: 'Marko prefers dark mode' });
});
it('does not strip a handoff prefix down to an empty title', () => {
// The prefix consumes the whole string (trailing separator, no body) —
// rather than emit an empty title, humanize returns the input untouched.
const input = 'session handoff 2026 06 24 s2 ';
expect(humanizeMemoryTitle(input)).toEqual({ title: input });
});
});
describe('sentenceTruncate', () => {
it('returns short text unchanged', () => {
expect(sentenceTruncate('Short and sweet.', 220)).toBe('Short and sweet.');
});
it('cuts a long excerpt at the last full stop inside the budget', () => {
const text = 'First sentence here. Second sentence lands inside. Third one runs well past the budget and keeps going.';
const out = sentenceTruncate(text, 60);
expect(out).toBe('First sentence here. Second sentence lands inside.');
});
it('leaves text without a usable stop for the CSS clamp', () => {
const text = 'x'.repeat(300);
expect(sentenceTruncate(text, 220)).toBe(text);
});
});

View File

@@ -0,0 +1,269 @@
/**
* W4B (F22) — shared memory-text normalizer for DISPLAY-LAYER dedup.
*
* The substrate (`packages/hive-mind-core/src/mind/frames.ts` `findDuplicate`)
* dedupes only on an exact content hash, so two writes that differ by a single
* embedded volatile token — a benchmark/audit-run id, a UUID, a timestamp — land
* as separate frames and surface to the user as near-identical duplicates.
*
* This is a pure rendering-side collapse key: it strips those volatile tokens,
* case-folds, and collapses whitespace so near-duplicates group together. It does
* NOT touch the store — nothing is merged or deleted.
*
* Min-length guard: if the normalized result is shorter than
* MIN_NORMALIZED_KEY_CHARS, callers MUST treat it as non-groupable (fall back to
* per-item uniqueness) so short/empty content is never over-collapsed.
*/
export const MIN_NORMALIZED_KEY_CHARS = 8;
/** UUID (v1-v5 shape) — a very common embedded volatile id. */
const UUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
/**
* "Audit run <id>" harvest-provenance suffix as a WHOLE PHRASE, e.g.
* "Audit run audit-1782648502308." / "benchmark run 20260704".
* The label words ("audit run") AND the id must be stripped together — stripping
* only the id (RUN_ID_RE/AUDIT_NUMERIC_ID_RE) leaves "audit run" behind, which
* produced two distinct dedup keys ("…account" vs "…account audit run") so the
* SAME fact showed twice in the login briefing (live wave-5 QA finding). Runs
* BEFORE RUN_ID_RE so the label isn't half-consumed. The optional `audit[-_]`
* lets it also swallow the doubled "audit run audit-<digits>" live shape.
*/
const AUDIT_RUN_PHRASE_RE = /\b(?:audit|benchmark)[-_ ]?run\b\s*[:=#-]?\s*(?:audit[-_])?\d{3,}/gi;
/**
* Explicit run/audit/benchmark id tokens, e.g.
* "audit-run-id: 3f9a2b", "run_id=abc123", "benchmark run 20260704",
* "auditRunId:00ab". The value can be hex/alphanumeric of length >= 3.
*/
const RUN_ID_RE = /\b(?:audit[-_ ]?run[-_ ]?id|run[-_ ]?id|benchmark[-_ ]?run|audit[-_ ]?run)s?\b[:=#-]?\s*[0-9a-z]{3,}/gi;
/**
* Bare "audit-<digits>" / "audit_<digits>" ids (e.g. "audit-1782648502308").
* Hyphen/underscore-joined only — deliberately does NOT match a bare space
* ("audit trail") so ordinary prose containing the word "audit" survives.
*/
const AUDIT_NUMERIC_ID_RE = /\baudit[-_]\d{4,}\b/gi;
/** ISO-8601 timestamps (date, optional time/zone). */
const ISO_TS_RE = /\d{4}-\d{2}-\d{2}(?:[t ]\d{2}:\d{2}(?::\d{2})?(?:\.\d+)?z?)?/gi;
/**
* "Timestamp: <epoch ms>" — a raw epoch millisecond value is not ISO-8601 and
* would otherwise survive normalization untouched (the original per-fact
* volatile token in the benchmark harness's anchor text).
*/
const RAW_TIMESTAMP_LABEL_RE = /\btimestamp\s*:?\s*\d{9,}\b/gi;
/**
* Benchmark-harness secret tokens, e.g. "BENCH-SECRET-5yu27cwrmsv". Narrow to
* this exact prefix so real "confidential"/"secret" prose is never touched.
*/
const BENCH_SECRET_RE = /\bbench-secret-[0-9a-z]+\b/gi;
/** Bare ticket-style tokens: #1234 (>= 2 digits) — not markdown headings (no space after #). */
const TICKET_RE = /#\d{2,}\b/g;
/** Markdown emphasis / code fences that don't change meaning. */
const MD_NOISE_RE = /[*_`~]+/g;
/**
* Produce a normalized grouping key for a memory text fragment.
*
* Order matters: strip run-id phrases (which may contain hex) BEFORE the bare
* UUID/timestamp strippers so a labeled id is removed as a unit.
* Returns '' for nullish input.
*/
export function normalizeMemoryKey(text: string | null | undefined): string {
if (typeof text !== 'string') return '';
return text
.toLowerCase()
.replace(AUDIT_RUN_PHRASE_RE, ' ')
.replace(RUN_ID_RE, ' ')
.replace(AUDIT_NUMERIC_ID_RE, ' ')
.replace(RAW_TIMESTAMP_LABEL_RE, ' ')
.replace(BENCH_SECRET_RE, ' ')
.replace(UUID_RE, ' ')
.replace(ISO_TS_RE, ' ')
.replace(TICKET_RE, ' ')
.replace(MD_NOISE_RE, ' ')
.replace(/[^\p{L}\p{N}]+/gu, ' ') // fold remaining punctuation to spaces
.trim()
.replace(/\s+/g, ' ');
}
/**
* True when the normalized key is substantial enough to group on. Callers use a
* per-item fallback key when this is false so unrelated short facts never merge.
*/
export function isGroupableKey(key: string): boolean {
return key.length >= MIN_NORMALIZED_KEY_CHARS;
}
// ── Display-layer markdown strip (round-6 fix 2a) ──────────────────────────
//
// Memory-card previews render as PLAIN TEXT nodes, so raw markdown tokens
// ('## heading', **bold**, `code`, [links](url)) show literally and read as
// log output. This is the same cleanup LoginBriefing's truncateHighlight
// applies, extracted so Memory-Trust rows share one implementation. Display
// only — never applied to stored content (the drawer still edits the raw
// text and renders a real markdown preview).
const MD_HEADING_RE = /^#{1,6}\s+/;
const MD_BOLD_RE = /\*\*(.+?)\*\*/g;
const MD_CODE_RE = /`(.+?)`/g;
const MD_FENCE_RE = /^```[\w-]*\s*$/;
const MD_LINK_RE = /\[([^\]]+)\]\([^)]*\)/g;
/** Strip markdown tokens from ONE line of preview text (display only). */
export function stripMarkdownTokens(line: string): string {
if (MD_FENCE_RE.test(line.trim())) return '';
return line
.replace(MD_HEADING_RE, '')
.replace(MD_LINK_RE, '$1')
.replace(MD_BOLD_RE, '$1')
.replace(MD_CODE_RE, '$1')
.trim();
}
// ── Display-layer preview split (round-7 fix 3) ─────────────────────────────
//
// MemoryTrustManage renders a memory as "first line = title, rest = excerpt",
// but harvested frames often LEAD with machine provenance — a bare
// "Timestamp: 1782400441971" line, or a "[Harvest:claude-code] session-handoff-…"
// slug — which read as garbage titles. buildMemoryPreview picks the first
// HUMAN lead instead. Display only: nothing here touches the stored content;
// the drawer still shows and edits the raw text.
export interface MemoryPreview {
/** Humanized first display line (falls back to the raw first line). */
title: string;
/** Remaining lines joined, sentence-truncated near the clamp budget. */
excerpt: string;
/** Provenance (handoff label + date + session) lifted out of the title's
* lead into a quiet meta chip. Absent when the title had no such prefix. */
titleMeta?: string;
}
/** Bare machine-provenance line: 'Timestamp: 1782400441971' and nothing else. */
const TIMESTAMP_LINE_RE = /^timestamp\s*:?\s*\d{6,}$/i;
/** '[Harvest:<tool>]' provenance prefix on a lead line. */
const HARVEST_PREFIX_RE = /^\[harvest:[^\]]*\]\s*/i;
/** A slug: no whitespace, at least one dash/underscore joint. */
function isSlug(s: string): boolean {
return s.length > 0 && !/\s/.test(s) && /[-_]/.test(s);
}
function deSlugify(s: string): string {
return s.replace(/[-_]+/g, ' ').replace(/\s+/g, ' ').trim();
}
/** A line a human reads as a title/sentence: ≥4 words and not majority
* punctuation/digits. */
function isHumanLine(line: string): boolean {
const words = line.split(/\s+/).filter(Boolean);
if (words.length < 4) return false;
const noise = (line.match(/[\p{N}\p{P}\p{S}]/gu) ?? []).length;
return noise <= line.length / 2;
}
/** Pick the display title from the stripped non-empty lines, skipping machine
* provenance leads. Returns null when nothing qualifies (caller falls back to
* the first line, exactly today's behavior). */
function selectPreviewTitle(lines: string[]): { title: string; index: number } | null {
let scanningForHuman = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (TIMESTAMP_LINE_RE.test(line)) continue; // (a) bare timestamp — never a title
if (HARVEST_PREFIX_RE.test(line)) {
// (b) harvest-provenance lead: de-slugify the remainder if it's a slug,
// keep it if it already reads human, else scan on for a human line.
const remainder = line.replace(HARVEST_PREFIX_RE, '').trim();
if (isSlug(remainder)) return { title: deSlugify(remainder), index: i };
if (isHumanLine(remainder)) return { title: remainder, index: i };
scanningForHuman = true;
continue;
}
if (scanningForHuman && !isHumanLine(line)) continue;
return { title: line, index: i };
}
return null;
}
/** Rough character budget of the two clamped excerpt lines. */
const EXCERPT_SENTENCE_CAP = 220;
/** Cut a long excerpt at the last full stop inside the clamp budget so the
* preview ends on a sentence instead of a mid-word ellipsis. When no usable
* stop exists, return the text untouched and let the CSS clamp ellipsize. */
export function sentenceTruncate(text: string, cap = EXCERPT_SENTENCE_CAP): string {
if (text.length <= cap) return text;
const head = text.slice(0, cap);
const lastStop = head.lastIndexOf('. ');
if (lastStop >= cap * 0.4) return head.slice(0, lastStop + 1);
return text;
}
// ── Display-layer handoff-title humanization (round-9 Lane C fix 1) ──────────
//
// Harvested session-handoff notes lead with a machine filename slug —
// "session handoff 2026 06 24 s2 warm hive pr8 landing shipped roadmap
// complete" — which reads as log output and punctures the "memory you can
// trust" promise. Lift the provenance prefix (handoff label + date + optional
// session) out of the title into a quiet meta chip and leave the human
// remainder as the title. Deterministic string transforms only — no content is
// invented (the em-dash/comma phrasing a human editor might add is deliberately
// NOT synthesized); nothing here touches the stored content.
const HANDOFF_PREFIX_RE =
/^(?:project[\s-]+)?(?:session[\s-]+)?handoff[\s-]+(\d{4})[\s-]+(\d{2})[\s-]+(\d{2})(?:[\s-]+s(\d+))?[\s-]+/i;
/** Uppercase the first alphabetic character; leave the rest as-is. */
function capitalizeFirst(s: string): string {
return s.replace(/\p{L}/u, (c) => c.toUpperCase());
}
/** "pr8" → "PR8" (the PR abbreviation only, digits required). Display polish. */
function upperPrTokens(s: string): string {
return s.replace(/\bpr(\d+)\b/gi, (_m, n: string) => `PR${n}`);
}
export interface HumanizedTitle {
title: string;
/** Provenance lifted out of the title lead, e.g.
* "session handoff · 2026-06-24 · s2". Undefined when no prefix matched. */
meta?: string;
}
/**
* Lift a leading "session handoff <date> [sN]" provenance slug out of a memory
* title into a compact meta string, humanizing the remainder. Returns the title
* untouched (no meta) when no handoff prefix is present, or when nothing
* readable would remain after the strip (never strip down to an empty title).
*/
export function humanizeMemoryTitle(title: string): HumanizedTitle {
const m = HANDOFF_PREFIX_RE.exec(title);
if (!m) return { title };
const remainder = title.slice(m[0].length).trim();
if (remainder === '') return { title };
const [, y, mo, d, s] = m;
const meta = `session handoff · ${y}-${mo}-${d}${s ? ` · s${s}` : ''}`;
return { title: capitalizeFirst(upperPrTokens(remainder)), meta };
}
/** Split memory content into a humanized {title, excerpt, titleMeta} for row previews. */
export function buildMemoryPreview(content: string): MemoryPreview {
const lines = content.split('\n').map(stripMarkdownTokens).filter((l) => l !== '');
if (lines.length === 0) return { title: stripMarkdownTokens(content), excerpt: '' };
const picked = selectPreviewTitle(lines) ?? { title: lines[0], index: 0 };
// Machine-provenance lines BEFORE the picked title are dropped from the
// preview entirely (they're still in the stored content and the drawer).
const excerpt = sentenceTruncate(lines.slice(picked.index + 1).join(' ').trim());
const humanized = humanizeMemoryTitle(picked.title);
return humanized.meta
? { title: humanized.title, excerpt, titleMeta: humanized.meta }
: { title: humanized.title, excerpt };
}

View File

@@ -0,0 +1,56 @@
/**
* P15 regression — drag-constraint computation for centered modals.
*/
import { describe, it, expect } from 'vitest';
import { computeDragConstraints } from './modal-drag';
describe('computeDragConstraints', () => {
it('gives symmetric bounds for a centered modal smaller than the viewport', () => {
const c = computeDragConstraints(1200, 800, 600, 400);
expect(c.left).toBe(-300);
expect(c.right).toBe(300);
expect(c.top).toBe(-200);
expect(c.bottom).toBe(200);
});
it('zeros out when modal equals container exactly', () => {
const c = computeDragConstraints(800, 600, 800, 600);
expect(c).toEqual({ top: 0, left: 0, right: 0, bottom: 0 });
});
it('zeros out when modal is larger than container (no dragging)', () => {
const c = computeDragConstraints(400, 300, 600, 500);
expect(c).toEqual({ top: 0, left: 0, right: 0, bottom: 0 });
});
it('handles a tall portrait viewport', () => {
const c = computeDragConstraints(400, 1200, 300, 400);
expect(c.left).toBe(-50);
expect(c.right).toBe(50);
expect(c.top).toBe(-400);
expect(c.bottom).toBe(400);
});
it('handles a landscape viewport with a narrow modal', () => {
const c = computeDragConstraints(1920, 1080, 400, 300);
expect(c.left).toBe(-760);
expect(c.right).toBe(760);
expect(c.top).toBe(-390);
expect(c.bottom).toBe(390);
});
it('never returns negative "right" or "bottom" (violates motion contract)', () => {
const c = computeDragConstraints(100, 100, 200, 200);
expect(c.right).toBeGreaterThanOrEqual(0);
expect(c.bottom).toBeGreaterThanOrEqual(0);
expect(c.left).toBeLessThanOrEqual(0);
expect(c.top).toBeLessThanOrEqual(0);
});
it('is symmetric in every axis when modal fits', () => {
const c = computeDragConstraints(1000, 800, 500, 400);
expect(c.left).toBe(-c.right);
expect(c.top).toBe(-c.bottom);
});
});

View File

@@ -0,0 +1,47 @@
/**
* Drag-constraint helper for modals that need to be repositionable
* without drifting off-screen.
*
* P15 · Create-template modal drag handle. framer-motion's
* `dragConstraints` takes `{ top, left, right, bottom }` as pixel
* offsets from the initial position. For a centered modal that means
* symmetric constraints bounded by the container/modal size gap.
*/
export interface DragConstraints {
top: number;
left: number;
right: number;
bottom: number;
}
/**
* Compute framer-motion drag constraints for a centered modal.
*
* Assumes the modal starts centered inside the container (e.g. via
* `flex items-center justify-center` on the backdrop). Returns the
* maximum offsets in each direction that keep the modal fully inside
* the container, so the user can't drag its header off-screen and
* lose the handle.
*
* @param containerWidth Viewport (or backdrop) width in px.
* @param containerHeight Viewport height in px.
* @param modalWidth Rendered modal width in px.
* @param modalHeight Rendered modal height in px.
*/
export function computeDragConstraints(
containerWidth: number,
containerHeight: number,
modalWidth: number,
modalHeight: number,
): DragConstraints {
const horizontalPad = Math.max(0, (containerWidth - modalWidth) / 2);
const verticalPad = Math.max(0, (containerHeight - modalHeight) / 2);
// Normalise -0 to +0 so deep-equal checks don't trip on the sign bit.
return {
left: horizontalPad === 0 ? 0 : -horizontalPad,
right: horizontalPad,
top: verticalPad === 0 ? 0 : -verticalPad,
bottom: verticalPad,
};
}

View File

@@ -0,0 +1,55 @@
import { describe, it, expect } from 'vitest';
import { formatModelLabel } from './model-label';
import type { Provider } from '@/hooks/useProviders';
const providers: Provider[] = [
{
id: 'anthropic', name: 'Anthropic', hasKey: true, badge: null, keyUrl: null, requiresKey: true,
models: [{ id: 'claude-sonnet-4-6', name: 'Claude Sonnet 4.6', cost: '', speed: '' }],
},
];
describe('formatModelLabel (W2C)', () => {
it('returns the catalog friendly name on an exact match', () => {
expect(formatModelLabel('claude-sonnet-4-6', providers)).toBe('Claude Sonnet 4.6');
});
it('prettifies an ollama tag the catalog cannot name', () => {
expect(formatModelLabel('ollama/minimax-m2.7:cloud', providers)).toBe('Minimax M2.7 (cloud)');
});
it('strips an 8-digit date suffix', () => {
expect(formatModelLabel('gpt-4o-20260115')).toBe('GPT 4o');
});
it('title-cases an unknown bare id', () => {
expect(formatModelLabel('qwen3-35b')).toBe('Qwen3 35b');
});
it('re-joins dash-encoded version digits with a dot (heuristic path, no catalog)', () => {
expect(formatModelLabel('claude-opus-4-6')).toBe('Claude Opus 4.6');
expect(formatModelLabel('claude-3-5-sonnet')).toBe('Claude 3.5 Sonnet');
});
it('is empty-safe', () => {
expect(formatModelLabel(undefined)).toBe('');
expect(formatModelLabel('')).toBe('');
});
it('falls back to the heuristic when the catalog name equals the id', () => {
const p: Provider[] = [{ id: 'x', name: 'X', hasKey: true, badge: null, keyUrl: null, requiresKey: false, models: [{ id: 'kimi-k2', name: 'kimi-k2', cost: '', speed: '' }] }];
expect(formatModelLabel('kimi-k2', p)).toBe('Kimi K2');
});
it('humanizes an installed Ollama model even when the catalog carries a matching (bare-tag) entry (wave-4 QA regression)', () => {
// Reproduces the live bug: routes/providers.ts fetchOllamaModels sets
// `name` to the bare installed tag by design ("Display name stays the
// bare tag") — the catalog-match branch must not trust that as an
// already-friendly name and short-circuit before the heuristic runs.
const p: Provider[] = [{
id: 'ollama', name: 'Local / Ollama', hasKey: true, badge: null, keyUrl: null, requiresKey: false,
models: [{ id: 'ollama/gemma4:31b', name: 'gemma4:31b', cost: '', speed: '' }],
}];
expect(formatModelLabel('ollama/gemma4:31b', p)).toBe('Gemma4 (31b)');
});
});

View File

@@ -0,0 +1,77 @@
/**
* W2C — one display-name formatter for model ids.
*
* Model ids surface from three disconnected stores (agent runtime, config.json,
* LiteLLM /models) and were formatted ad-hoc in ~7 places (raw `split('/').pop()`,
* date-suffix strips, catalog lookups), so the same model read differently in the
* top-bar chip, Settings, the New-Agent modal, Telemetry, and chat headers.
*
* `formatModelLabel(id, providers?)`:
* 1. exact catalog match (providers[].models[].name) — the friendly name.
* 2. heuristic fallback — strip provider prefix + date suffix, surface a
* cloud/free tag, title-case the tokens. Load-bearing for Ollama models,
* whose catalog `name` equals the bare tag (providers.ts), so lookup alone
* can't prettify them.
*/
import type { Provider } from '@/hooks/useProviders';
/** Acronym tokens to uppercase rather than title-case. */
const ACRONYMS = new Set(['gpt', 'glm', 'ai', 'llm']);
function titleCaseToken(tok: string): string {
if (!tok) return tok;
if (ACRONYMS.has(tok.toLowerCase())) return tok.toUpperCase();
return tok.charAt(0).toUpperCase() + tok.slice(1);
}
function heuristicLabel(rawId: string): string {
let id = rawId;
// Drop the provider/router prefix (ollama/, openai/, anthropic/, …).
const slash = id.lastIndexOf('/');
if (slash >= 0) id = id.slice(slash + 1);
// Split off a `:cloud` / `:free` / other tag suffix → " (tag)".
let suffix = '';
const colon = id.indexOf(':');
if (colon >= 0) {
const tag = id.slice(colon + 1);
id = id.slice(0, colon);
suffix = tag ? ` (${tag})` : '';
}
// Strip a trailing 8-digit date stamp (e.g. -20260115).
id = id.replace(/-\d{8}$/, '');
// Re-join dash-separated version digits with a dot: claude-opus-4-6 →
// "Claude Opus 4.6", not "Claude Opus 4 6" (ids encode dots as dashes).
const merged: string[] = [];
for (const tok of id.split(/[-_]/).filter(Boolean)) {
const prev = merged[merged.length - 1];
if (prev !== undefined && /^\d+$/.test(tok) && /^\d+(\.\d+)*$/.test(prev)) {
merged[merged.length - 1] = `${prev}.${tok}`;
} else {
merged.push(tok);
}
}
const label = merged.map(titleCaseToken).join(' ');
return (label || id) + suffix;
}
export function formatModelLabel(id: string | undefined | null, providers?: Provider[]): string {
if (!id) return '';
// Ollama's catalog `name` is deliberately the bare installed tag (server
// fetchOllamaModels — "Display name stays the bare tag"), not a curated
// display name like the static cloud catalog's. Trusting it here would
// short-circuit before the heuristic gets to humanize the colon/dash tag,
// so local models always go through the same formatting as everyone else.
if (providers && !id.startsWith('ollama/')) {
for (const p of providers) {
for (const m of p.models) {
if (m.id === id && m.name && m.name !== id) return m.name;
}
}
}
return heuristicLabel(id);
}

View File

@@ -0,0 +1,45 @@
/**
* Hero shared-element morph identifiers (path-to-9 Pillar 1.1 · Lane HM).
*
* The two hero cases in the motion system are shared-element morphs, driven by
* framer-motion `layoutId`: a source element (a workspace shelf card) and a
* destination element (the workspace surface header) that carry the SAME
* `layoutId` animate between one another on route change — the card GROWS into
* the surface. These builders are the single source of truth for those ids so
* source and destination can never drift out of sync (the whole morph silently
* no-ops if the two strings disagree).
*
* Pure data — imports nothing — so both React callers and the (non-React)
* motion-gate scripts can read it.
*
* Integration note (Lane RT): the morph fires via framer's global layoutId
* registry, so it works without a wrapping `LayoutGroup`. When Lane RT's
* RouteTransition lands (an `AnimatePresence mode="popLayout"` around the
* AppShell `<Outlet/>`), the exiting shelf and the entering surface briefly
* co-exist, which makes the morph land even more reliably; no id changes are
* needed here.
*/
/** layoutId for a workspace's hex avatar (card ⇄ surface header). */
export function workspaceHeroAvatarId(workspaceId: string): string {
return `ws-hero-avatar-${workspaceId}`;
}
/** layoutId for a workspace's name (card ⇄ surface header). */
export function workspaceHeroNameId(workspaceId: string): string {
return `ws-hero-name-${workspaceId}`;
}
/**
* Kill switch for every hero morph. A regression in the shared-element system
* is one env flip away from off: build with `VITE_HERO_MORPH_DISABLED=true` and
* all morph callers fall back to the default route crossfade. Wrapped in
* try/catch so non-Vite consumers (node gate scripts) resolve to enabled.
*/
export function heroMorphEnabled(): boolean {
try {
return import.meta.env?.VITE_HERO_MORPH_DISABLED !== 'true';
} catch {
return true;
}
}

View File

@@ -0,0 +1,89 @@
/**
* Route-transition pure helpers (Pillar 1.1 · Lane RT). No JSX / no React so the
* contract is unit-testable in isolation and the component file stays fast-refresh
* clean. The <RouteTransition/> component consumes all three.
*
* - routeGroupKey — the AnimatePresence key. Derived from the TOP path
* segment ONLY, so a workspace sub-tab change within
* /workspaces/:id (overview→chat) never crossfades the
* whole surface — only a top-level surface change does.
* - routeAnnouncement — the polite-live-region label for the destination
* surface (assistive-tech route announce).
* - routeTransitionEnabled — the kill switch. Default ON; one localStorage flag
* flip disables the whole tier if it ever regresses.
*/
/** localStorage kill-switch key. `'off'|'false'|'0'` disables; anything else = ON. */
export const ROUTE_TRANSITION_FLAG_KEY = 'waggle-route-transition';
/**
* The AnimatePresence key for a pathname: the first path segment, lowercased.
* '/' (the transient index before IndexRedirect) maps to 'home' so the boot
* redirect to /home does not read as a crossfade. Every /workspaces/* path —
* grid, :id, and every sub-tab — shares the single 'workspaces' key (the
* card→workspace-open hero morph, Lane HM, owns that pair, not this crossfade).
*/
export function routeGroupKey(pathname: string): string {
const seg = pathname.split('/').filter(Boolean)[0];
return seg ? seg.toLowerCase() : 'home';
}
/** Human labels for the known top-level surfaces (route-announce copy). */
const ROUTE_LABELS: Record<string, string> = {
home: 'Home',
workspaces: 'Workspaces',
memory: 'Memory',
artifacts: 'Artifacts',
files: 'Files',
agents: 'Agents',
automations: 'Automations',
skills: 'Skills',
room: 'Room',
'waggle-dance': 'Agent swarm',
approvals: 'Approvals',
connectors: 'Connectors',
mcps: 'MCP hub',
marketplace: 'Marketplace',
launcher: 'Launcher',
team: 'Team',
settings: 'Settings',
benchmarks: 'Benchmarks',
platform: 'Platform',
};
/**
* The polite-live-region announcement for a destination pathname: the surface
* label. Unknown segments fall back to a title-cased form of the segment so the
* announce is never empty (a wrong-but-present label is still better for SR than
* silence, and this never fires on a known surface).
*/
export function routeAnnouncement(pathname: string): string {
const key = routeGroupKey(pathname);
return ROUTE_LABELS[key] ?? titleCase(key);
}
function titleCase(seg: string): string {
return seg
.split('-')
.filter(Boolean)
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
.join(' ');
}
/**
* Kill switch. Default ON everywhere; a regression is one flag flip:
* `localStorage.setItem('waggle-route-transition', 'off')`. Reads defensively so
* a disabled/throwing storage falls back to ON (the shipped default).
*/
export function routeTransitionEnabled(): boolean {
try {
if (typeof localStorage !== 'undefined') {
const v = localStorage.getItem(ROUTE_TRANSITION_FLAG_KEY);
if (v === 'off' || v === 'false' || v === '0') return false;
if (v === 'on' || v === 'true' || v === '1') return true;
}
} catch {
/* storage disabled — fall through to the ON default */
}
return true;
}

View File

@@ -0,0 +1,65 @@
import { describe, it, expect } from 'vitest';
import { SPRING, DUR, EASE_OUT, STAGGER, SIGNATURE, REDUCED, dampingRatio } from './tokens';
describe('motion tokens — the vocabulary invariants', () => {
it('every spring family variant shares the `spring` type', () => {
for (const variant of Object.values(SPRING)) {
expect(variant.type).toBe('spring');
}
});
it('all three springs share ONE physical character (damping ratio band)', () => {
// ζ = damping / (2·√(stiffness·mass)); all variants must read as the same
// "material" — a light single-overshoot settle. Band is tight on purpose so
// a future retune of amplitude/speed can never silently change the feel.
const ratios = Object.values(SPRING).map(dampingRatio);
for (const z of ratios) {
expect(z).toBeGreaterThan(0.7);
expect(z).toBeLessThan(0.8);
}
const spread = Math.max(...ratios) - Math.min(...ratios);
expect(spread).toBeLessThan(0.05);
});
it('DUR is strictly ascending (fast < base < slow < settle)', () => {
const seq = [DUR.fast, DUR.base, DUR.slow, DUR.settle];
for (let i = 1; i < seq.length; i++) {
expect(seq[i]).toBeGreaterThan(seq[i - 1]);
}
});
it('EASE_OUT is a valid 4-point cubic-bezier control tuple', () => {
expect(EASE_OUT).toHaveLength(4);
for (const n of EASE_OUT) {
expect(typeof n).toBe('number');
}
});
it('STAGGER list is tighter than brief and both are positive', () => {
expect(STAGGER.list).toBeGreaterThan(0);
expect(STAGGER.brief).toBeGreaterThan(STAGGER.list);
});
it('SIGNATURE full vs micro moment sets are disjoint', () => {
const full = new Set<string>(SIGNATURE.full.moments);
const overlap = SIGNATURE.micro.moments.filter((m) => full.has(m));
expect(overlap).toEqual([]);
});
it('SIGNATURE full is the rare/flourish tier, micro is the frequent tier', () => {
// Full flourishes carry a per-session cooldown; micro must not (routine).
expect(SIGNATURE.full.perSessionCooldownMs).toBeGreaterThan(0);
expect(SIGNATURE.full.durS).toBe(DUR.settle);
expect(SIGNATURE.micro.durS).toBe(DUR.fast);
});
it('REDUCED covers every motion tier with a non-empty mapping', () => {
const tiers = ['routeTransition', 'hover', 'settle', 'streamingCaret', 'countUp', 'ambient'] as const;
// Exactly these tiers, no more (no orphan tier, no missing tier).
expect(Object.keys(REDUCED).sort()).toEqual([...tiers].sort());
for (const tier of tiers) {
expect(REDUCED[tier]).toBeTruthy();
expect(typeof REDUCED[tier]).toBe('string');
}
});
});

View File

@@ -0,0 +1,104 @@
/**
* Motion vocabulary — THE single source of motion truth (Phase-0 items 1, 3, 7).
*
* Every animation on the judged surfaces resolves to a token here (springs for
* framer-motion; DUR/EASE_OUT/STAGGER for CSS-driven motion via the `--mo-*`
* custom props in index.css). The retrofit lanes (R1/R2/R3) migrate the shipped
* duration/easing zoo onto these; the reviewable demo lives at /motion-spec.
*
* Design contract (path-to-9 §Phase-0):
* - One spring FAMILY, not one config: three named variants that share ONE
* physical character (same damping ratio band ≈ 0.74–0.77 → the same
* "material", a light single-overshoot settle). Tune amplitude/speed per
* tier, never the character. See `dampingRatio` + tokens.test.ts.
* - Reduced-motion mapping is defined for EVERY tier (not just ambient) and is
* CONSUMED, not just documented — /motion-spec switches behaviour off it.
* - Signature-moment frequency taxonomy caps full-amplitude flourishes to rare
* accrual milestones; high-frequency actions get the micro variant only.
*
* This file imports nothing (pure data) so the CI contrast/motion gate scripts
* and non-React callers can read it too.
*/
/** framer-motion mass default is 1; damping ratio uses that. */
const SPRING_MASS = 1;
/**
* The spring FAMILY. `type: 'spring'` + stiffness/damping are structurally the
* framer-motion spring Transition shape, so `transition={SPRING.standard}` just
* works without importing framer-motion here.
*
* - micro: chips, presses, selection — a ≤150ms-feel snap.
* - standard: hovers, panel/route fades — the default working tier.
* - expressive: hero morphs, the settle gesture — more travel, same settle DNA.
*/
export const SPRING = {
micro: { type: 'spring', stiffness: 550, damping: 35 },
standard: { type: 'spring', stiffness: 380, damping: 30 },
expressive: { type: 'spring', stiffness: 260, damping: 24 },
} as const;
/**
* Durations (seconds) for non-spring / CSS-timed motion. Mirrored 1:1 into
* index.css as `--mo-fast/--mo-base/--mo-slow/--mo-settle` (ms). Ascending by
* contract (tokens.test.ts) so "slower = a longer token" always holds.
*/
export const DUR = { fast: 0.15, base: 0.2, slow: 0.32, settle: 0.4 } as const;
/** Standard-out cubic-bezier for non-spring CSS motion. Mirrors `--mo-ease`. */
export const EASE_OUT = [0.22, 1, 0.36, 1] as const;
/** Per-item entrance stagger (seconds): list = Wave W's 40ms, brief = 80ms. */
export const STAGGER = { list: 0.04, brief: 0.08 } as const;
/**
* Signature-moment frequency/intensity taxonomy (Phase-0.7).
* FULL settle only on rare accrual milestones (per-session cooldown); MICRO for
* high-frequency actions. `full.moments` and `micro.moments` are DISJOINT by
* contract — a moment is either a flourish or routine, never both.
*/
export const SIGNATURE = {
full: {
moments: ['memory-saved-first-of-session', 'install-success', 'agent-spawned'],
durS: DUR.settle,
perSessionCooldownMs: 60_000,
},
micro: {
moments: ['send-arm', 'selection'],
durS: DUR.fast,
},
} as const;
/**
* Reduced-motion mapping per motion TIER (Phase-0.3). Consumers read this to
* degrade gracefully under `prefers-reduced-motion: reduce`:
* - routeTransition → crossfade only (no shared-element travel)
* - hover → keep colour + shadow, drop translate/scale
* - settle → instant state + a colour pulse, no gesture
* - streamingCaret → static (no blink/trail)
* - countUp → set the final number instantly
* - ambient → off (below-attention loops stop)
*/
export const REDUCED = {
routeTransition: 'crossfade-only',
hover: 'color-shadow-only-no-transform',
settle: 'instant-state-color-pulse',
streamingCaret: 'static',
countUp: 'instant-set',
ambient: 'off',
} as const;
/** A named spring-family variant. */
export type SpringVariant = keyof typeof SPRING;
/** A motion tier with a defined reduced-motion behaviour. */
export type MotionTier = keyof typeof REDUCED;
/**
* Damping ratio ζ = c / (2·√(k·m)) — the mathematical expression of a spring's
* "material". All three family variants must sit in one narrow band (see
* tokens.test.ts) so the system reads as one physical character, not a zoo.
* /motion-spec surfaces this number next to each variant.
*/
export function dampingRatio(spring: { stiffness: number; damping: number }): number {
return spring.damping / (2 * Math.sqrt(spring.stiffness * SPRING_MASS));
}

View File

@@ -0,0 +1,45 @@
import { describe, it, expect } from 'vitest';
import { humanizeNotification } from './notification-copy';
import type { Notification } from '@/lib/types';
const notif = (over: Partial<Notification> = {}): Notification => ({
id: '1',
type: 'cron',
title: 'Daily digest completed',
body: 'Scheduled task ran successfully.',
read: false,
timestamp: '2026-07-04T00:00:00Z',
...over,
});
describe('humanizeNotification', () => {
it('softens the generic cron-tick jargon body', () => {
const out = humanizeNotification(notif());
expect(out.body).toBe('Your scheduled automation just ran.');
expect(out.title).toBe('Daily digest completed');
});
it('surfaces actionUrl as href', () => {
const out = humanizeNotification(notif({ actionUrl: '/settings/mission-control' }));
expect(out.href).toBe('/settings/mission-control');
});
it('trims whitespace-only actionUrl to undefined', () => {
expect(humanizeNotification(notif({ actionUrl: ' ' })).href).toBeUndefined();
expect(humanizeNotification(notif({ actionUrl: undefined })).href).toBeUndefined();
});
it('passes through non-generic bodies unchanged', () => {
const out = humanizeNotification(notif({ type: 'approval', title: 'Approval needed', body: 'Delete database requires your OK.' }));
expect(out.body).toBe('Delete database requires your OK.');
});
it('fills an empty body with a per-category fallback', () => {
expect(humanizeNotification(notif({ type: 'approval', body: '' })).body).toBe('An action is waiting for your approval.');
expect(humanizeNotification(notif({ type: 'agent', body: ' ' })).body).toBe('An agent finished its work.');
});
it('falls back to a default title when title is empty', () => {
expect(humanizeNotification(notif({ title: '' })).title).toBe('Notification');
});
});

View File

@@ -0,0 +1,47 @@
import type { Notification } from '@/lib/types';
/**
* W4C (F25) — humanize a notification for display.
*
* The server persists machine-flavored copy (e.g. a generic per-tick cron
* completion reads "<name> completed" / "Scheduled task ran successfully.") and
* a deep-link `actionUrl` that the inbox never rendered. This pure mapper turns
* a raw Notification into { title, body, href } the inbox can render directly:
* - softens the known generic-jargon bodies,
* - surfaces the action link as an href,
* - always falls back to the raw copy so unmapped events still read sensibly.
*/
export interface HumanizedNotification {
title: string;
body: string;
/** Deep-link target for a CTA, when the notification carries one. */
href?: string;
}
/** The hardcoded generic cron-tick body (packages/server/src/local/index.ts). */
const GENERIC_CRON_BODY = /^scheduled task ran successfully\.?$/i;
/** A friendlier default body per category when the server sent none. */
const EMPTY_BODY_FALLBACK: Record<string, string> = {
cron: 'Your scheduled automation just ran.',
approval: 'An action is waiting for your approval.',
task: 'A task was updated.',
message: 'You have a new message.',
agent: 'An agent finished its work.',
};
export function humanizeNotification(n: Notification): HumanizedNotification {
const href = typeof n.actionUrl === 'string' && n.actionUrl.trim() ? n.actionUrl.trim() : undefined;
const title = (n.title ?? '').trim() || 'Notification';
let body = (n.body ?? '').trim();
if (!body) {
body = EMPTY_BODY_FALLBACK[n.type] ?? '';
} else if (n.type === 'cron' && GENERIC_CRON_BODY.test(body)) {
// "Scheduled task ran successfully." → plain-language equivalent.
body = 'Your scheduled automation just ran.';
}
return { title, body, href };
}

View File

@@ -0,0 +1,59 @@
import { describe, it, expect } from 'vitest';
import {
WORK_TYPES,
TEAM_SIZES,
GOALS,
buildProfilePreview,
} from './onboarding-profile';
describe('onboarding-profile option constants', () => {
it('exposes non-empty option lists with unique ids', () => {
for (const list of [WORK_TYPES, TEAM_SIZES, GOALS]) {
expect(list.length).toBeGreaterThan(0);
const ids = list.map(o => o.id);
expect(new Set(ids).size).toBe(ids.length);
for (const o of list) {
expect(o.id).toBeTruthy();
expect(o.label).toBeTruthy();
}
}
});
});
describe('buildProfilePreview', () => {
const at = (hour: number) => new Date(2026, 5, 12, hour, 0, 0);
it('prompts for a name when nothing is filled in', () => {
expect(buildProfilePreview({})).toBe("Tell me your name and I'll greet you properly.");
});
it('treats a whitespace-only name as empty', () => {
const out = buildProfilePreview({ name: ' ', role: 'Consultant', goals: [] });
expect(out).toBe("Tell me your name and I'll greet you properly.");
});
it('greets by name with the memory promise when only the name is set', () => {
expect(buildProfilePreview({ name: 'Marko' }, at(20)))
.toBe('Good evening, Marko — your work will be remembered here.');
});
it('varies the salutation with the time of day', () => {
expect(buildProfilePreview({ name: 'Marko' }, at(9))).toMatch(/^Good morning, Marko/);
expect(buildProfilePreview({ name: 'Marko' }, at(14))).toMatch(/^Good afternoon, Marko/);
expect(buildProfilePreview({ name: 'Marko' }, at(20))).toMatch(/^Good evening, Marko/);
});
it('adds a role-aware clause from the selected work type', () => {
expect(buildProfilePreview({ name: 'Marko', workType: 'consulting' }, at(20)))
.toBe('Good evening, Marko — ready to pick up your consulting work?');
});
it('falls back to the free-text role when no work type is selected', () => {
expect(buildProfilePreview({ name: 'Marko', role: 'Strategy Consultant' }, at(9)))
.toBe('Good morning, Marko — ready to pick up your strategy consultant work?');
});
it('falls back to the raw id for an unknown work-type id', () => {
expect(buildProfilePreview({ name: 'A', workType: 'mystery' }, at(20))).toContain('mystery work');
});
});

View File

@@ -0,0 +1,89 @@
// Pure option constants + preview helper for the onboarding "Who Are You" step
// (S13 / B8). Kept out of the React component so the step stays thin and the
// option lists + preview shape are unit-testable without mounting the tree.
//
// These three signals (workType / teamSize / goals) mirror the net-new fields
// on the server `UserProfile` (profile.ts, Phase 2D.1) and are merged through
// `PUT /api/profile`. `buildProfilePreview` produces the one-line "live preview"
// the step renders under the form.
/** Work-type personalization signal (C30 — distinct from the workspace template). */
export interface OnboardingOption {
readonly id: string;
readonly label: string;
}
export const WORK_TYPES: readonly OnboardingOption[] = [
{ id: 'engineering', label: 'Engineering' },
{ id: 'product', label: 'Product' },
{ id: 'research', label: 'Research' },
{ id: 'sales', label: 'Sales' },
{ id: 'marketing', label: 'Marketing' },
{ id: 'operations', label: 'Operations' },
{ id: 'finance', label: 'Finance' },
{ id: 'legal', label: 'Legal' },
{ id: 'consulting', label: 'Consulting' },
{ id: 'design', label: 'Design' },
{ id: 'leadership', label: 'Leadership' },
{ id: 'other', label: 'Other' },
] as const;
export const TEAM_SIZES: readonly OnboardingOption[] = [
{ id: 'solo', label: 'Just me' },
{ id: '2-10', label: '2–10' },
{ id: '11-50', label: '11–50' },
{ id: '51-200', label: '51–200' },
{ id: '200+', label: '200+' },
] as const;
export const GOALS: readonly OnboardingOption[] = [
{ id: 'remember', label: 'Remember everything I work on' },
{ id: 'research', label: 'Research faster' },
{ id: 'draft', label: 'Draft documents & content' },
{ id: 'code', label: 'Write & review code' },
{ id: 'plan', label: 'Plan & manage projects' },
{ id: 'automate', label: 'Automate repetitive work' },
{ id: 'decisions', label: 'Track decisions & rationale' },
{ id: 'collaborate', label: 'Collaborate with my team' },
] as const;
/** The partial profile slice the step collects before commit. */
export interface OnboardingProfileDraft {
readonly name?: string;
readonly role?: string;
readonly industry?: string;
readonly workType?: string;
readonly teamSize?: string;
readonly goals?: readonly string[];
}
function labelFor(options: readonly OnboardingOption[], id: string | undefined): string | undefined {
if (!id) return undefined;
return options.find(o => o.id === id)?.label ?? id;
}
/** Time-of-day salutation for the live greeting preview. */
function salutation(hour: number): string {
if (hour < 12) return 'Good morning';
if (hour < 18) return 'Good afternoon';
return 'Good evening';
}
/**
* Build the live greeting preview under the form — a demonstration of the
* personalization promise (how Waggle will actually greet the user), not a
* profile summary. Degrades gracefully: no name → prompt for one; name only →
* the memory promise; name + work type/role → a role-aware greeting. Pure —
* `now` is injectable so tests can pin the time of day.
*/
export function buildProfilePreview(partial: OnboardingProfileDraft, now: Date = new Date()): string {
const name = partial.name?.trim();
if (!name) return "Tell me your name and I'll greet you properly.";
const greeting = `${salutation(now.getHours())}, ${name}`;
// Prefer the curated work-type label (clean noun); fall back to the
// free-text role so either signal personalizes the clause.
const work = labelFor(WORK_TYPES, partial.workType) ?? partial.role?.trim();
if (work) return `${greeting} — ready to pick up your ${work.toLowerCase()} work?`;
return `${greeting} — your work will be remembered here.`;
}

View File

@@ -0,0 +1,37 @@
/**
* M-18 / UX-1 — skip-setup defaults contract.
*
* Guards the user-facing promise: picking "Skip and set me up" on the
* onboarding WhyWaggle step must produce a workable desktop with
* sensible defaults (blank template, general-purpose persona). A
* silent change to either value would surface only via user-reported
* "why is my agent suddenly acting like a sales rep" noise.
*/
import { describe, it, expect } from 'vitest';
import { SKIP_SETUP_DEFAULTS } from './onboarding-skip';
describe('SKIP_SETUP_DEFAULTS', () => {
it('uses the blank template (no domain scoping)', () => {
expect(SKIP_SETUP_DEFAULTS.templateId).toBe('blank');
});
it('uses the general-purpose persona (no role bias)', () => {
expect(SKIP_SETUP_DEFAULTS.personaId).toBe('general-purpose');
});
it('names the workspace "Default Workspace"', () => {
expect(SKIP_SETUP_DEFAULTS.workspaceName).toBe('Default Workspace');
expect(SKIP_SETUP_DEFAULTS.workspaceName.length).toBeGreaterThan(0);
});
it('places the workspace in the Personal group', () => {
expect(SKIP_SETUP_DEFAULTS.group).toBe('Personal');
});
it('every field is populated (no silent empty strings)', () => {
for (const [key, value] of Object.entries(SKIP_SETUP_DEFAULTS)) {
expect(typeof value, `${key} type`).toBe('string');
expect((value as string).length, `${key} length`).toBeGreaterThan(0);
}
});
});

View File

@@ -0,0 +1,27 @@
/**
* Defaults applied when the user picks "Skip and set me up" on the
* onboarding WhyWaggle step (M-18 / UX-1).
*
* Pinning these as a named constant (rather than inline literals in
* the wizard) means a regression test can assert the skip contract
* without having to mount the full React tree — if these shift, we
* want a failing test, not a silent UX regression.
*/
export interface SkipSetupDefaults {
/** Template id used for the workspace (matches TEMPLATES in onboarding/constants). */
readonly templateId: string;
/** Persona id used for the workspace (matches PERSONAS in persona-data). */
readonly personaId: string;
/** Display name for the auto-created workspace. */
readonly workspaceName: string;
/** Workspace group folder. */
readonly group: string;
}
export const SKIP_SETUP_DEFAULTS: SkipSetupDefaults = {
templateId: 'blank',
personaId: 'general-purpose',
workspaceName: 'Default Workspace',
group: 'Personal',
};

View File

@@ -0,0 +1,189 @@
/**
* Phase 4.1 unblock — onboarding tier-filter tests.
*
* Spec: docs/ux-disclosure-levels.md r2 §"Templates — filter for Essential" + §"Personas — filter for Essential".
* Decision (Marko Q1, 2026-05-07): drop `coder` from Essential personas — quote: "this is not the target."
*/
import { describe, it, expect } from 'vitest';
import {
ESSENTIAL_TEMPLATE_IDS,
ESSENTIAL_PERSONA_IDS,
getTemplatesForTier,
getPersonasForTier,
} from './onboarding-tier-filter';
import { TEMPLATES, ALL_ONBOARDING_PERSONAS, getPersonasForTemplate } from '@/components/os/overlays/onboarding/constants';
describe('ESSENTIAL_TEMPLATE_IDS', () => {
it('contains exactly 3 IDs in spec order: agency-consulting, research-project, blank', () => {
expect(ESSENTIAL_TEMPLATE_IDS).toEqual(['agency-consulting', 'research-project', 'blank']);
});
it('every essential ID exists in TEMPLATES', () => {
const all = new Set(TEMPLATES.map(t => t.id));
for (const id of ESSENTIAL_TEMPLATE_IDS) {
expect(all.has(id), `${id} not in TEMPLATES`).toBe(true);
}
});
});
describe('ESSENTIAL_PERSONA_IDS', () => {
it('contains exactly 4 IDs', () => {
expect(ESSENTIAL_PERSONA_IDS).toEqual(['general-purpose', 'researcher', 'writer', 'analyst']);
});
it('does NOT include coder (Marko Q1 drop decision)', () => {
expect(ESSENTIAL_PERSONA_IDS).not.toContain('coder');
});
it('every essential ID exists in ALL_ONBOARDING_PERSONAS', () => {
const all = new Set(ALL_ONBOARDING_PERSONAS.map(p => p.id));
for (const id of ESSENTIAL_PERSONA_IDS) {
expect(all.has(id), `${id} not in ALL_ONBOARDING_PERSONAS`).toBe(true);
}
});
});
describe('getTemplatesForTier', () => {
it('returns 3 essential templates for simple tier', () => {
const result = getTemplatesForTier('simple', TEMPLATES);
expect(result.map(t => t.id)).toEqual(['agency-consulting', 'research-project', 'blank']);
});
it('preserves spec ordering, not input ordering, for simple tier', () => {
// TEMPLATES order is [sales-pipeline, research-project, code-review, ..., agency-consulting, ..., blank]
// ESSENTIAL_TEMPLATE_IDS order is [agency-consulting, research-project, blank] — that's what we surface
const result = getTemplatesForTier('simple', TEMPLATES);
expect(result[0].id).toBe('agency-consulting');
expect(result[1].id).toBe('research-project');
expect(result[2].id).toBe('blank');
});
it('returns all templates for professional tier', () => {
const result = getTemplatesForTier('professional', TEMPLATES);
expect(result.length).toBe(TEMPLATES.length);
});
it('returns all templates for power tier', () => {
const result = getTemplatesForTier('power', TEMPLATES);
expect(result.length).toBe(TEMPLATES.length);
});
it('returns all templates for admin tier', () => {
const result = getTemplatesForTier('admin', TEMPLATES);
expect(result.length).toBe(TEMPLATES.length);
});
it('non-simple tiers preserve input array reference (no copy)', () => {
// Optimization sanity check — non-simple tiers should pass through untouched
const result = getTemplatesForTier('professional', TEMPLATES);
expect(result).toBe(TEMPLATES);
});
it('handles empty input gracefully', () => {
expect(getTemplatesForTier('simple', [])).toEqual([]);
expect(getTemplatesForTier('professional', [])).toEqual([]);
});
});
describe('getPersonasForTier', () => {
it('returns 4 essential personas for simple tier when no recommended persona', () => {
const personas = getPersonasForTemplate('blank');
const result = getPersonasForTier('simple', personas);
const ids = result.map(p => p.id);
expect(ids).toContain('general-purpose');
expect(ids).toContain('researcher');
expect(ids).toContain('writer');
expect(ids).toContain('analyst');
expect(ids).not.toContain('coder');
expect(result.length).toBe(4);
});
it('drops coder from simple tier', () => {
const personas = getPersonasForTemplate('code-review'); // recommended = coder
const result = getPersonasForTier('simple', personas);
// Even though coder is recommended for code-review, simple tier drops it
expect(result.find(p => p.id === 'coder')).toBeUndefined();
});
it('preserves the input ordering for simple tier (recommended-first when in essential set)', () => {
const personas = getPersonasForTemplate('research-project'); // recommended = researcher (in essentials)
const result = getPersonasForTier('simple', personas);
// getPersonasForTemplate sorts: domain.recommended (none for knowledge-recommended), universal, knowledge, domain.others
// For research-project: input is [general-purpose, researcher, writer, analyst, coder, ...domain]
// After filtering: [general-purpose, researcher, writer, analyst]
expect(result[0].id).toBe('general-purpose');
expect(result[1].id).toBe('researcher');
expect(result[2].id).toBe('writer');
expect(result[3].id).toBe('analyst');
});
it('includes the recommended domain persona at simple tier (consultant for agency-consulting)', () => {
const personas = getPersonasForTemplate('agency-consulting'); // recommended = consultant (domain)
const result = getPersonasForTier('simple', personas);
// Spec: simple tier = 4 essentials + recommended-domain-persona (if not already in essentials)
expect(result.find(p => p.id === 'consultant'), 'consultant must appear at simple tier when recommended').toBeDefined();
// Plus all 4 essentials
for (const id of ['general-purpose', 'researcher', 'writer', 'analyst']) {
expect(result.find(p => p.id === id), `${id} missing`).toBeDefined();
}
expect(result.length).toBe(5);
});
it('places the recommended domain persona FIRST in simple tier (matches getPersonasForTemplate ordering)', () => {
const personas = getPersonasForTemplate('agency-consulting');
const result = getPersonasForTier('simple', personas);
expect(result[0].id).toBe('consultant');
});
it('does not duplicate when recommended is already in essentials', () => {
const personas = getPersonasForTemplate('research-project'); // recommended = researcher (in essentials)
const result = getPersonasForTier('simple', personas);
const researcherCount = result.filter(p => p.id === 'researcher').length;
expect(researcherCount).toBe(1);
expect(result.length).toBe(4);
});
it('returns all personas for professional tier', () => {
const personas = getPersonasForTemplate('blank');
const result = getPersonasForTier('professional', personas);
expect(result.length).toBe(personas.length);
expect(result).toBe(personas); // pass-through reference
});
it('returns all personas for power tier', () => {
const personas = getPersonasForTemplate('blank');
const result = getPersonasForTier('power', personas);
expect(result.length).toBe(personas.length);
});
it('returns all personas for admin tier', () => {
const personas = getPersonasForTemplate('blank');
const result = getPersonasForTier('admin', personas);
expect(result.length).toBe(personas.length);
});
it('handles empty input gracefully', () => {
expect(getPersonasForTier('simple', [])).toEqual([]);
expect(getPersonasForTier('professional', [])).toEqual([]);
});
});
describe('integration with constants.ts', () => {
it('every essential template ID maps to an OnboardingTemplate object', () => {
const filtered = getTemplatesForTier('simple', TEMPLATES);
expect(filtered).toHaveLength(3);
expect(filtered.every(t => typeof t.name === 'string' && t.icon !== undefined)).toBe(true);
});
it('Ljiljana-archetype journey: simple tier + agency-consulting → consultant first, 5 personas total', () => {
// The named-user persona Marko anchors against (consulting partner archetype).
// This test guards against the "Ljiljana sees 19 personas + 15 templates" regression.
const templates = getTemplatesForTier('simple', TEMPLATES);
expect(templates.find(t => t.id === 'agency-consulting')).toBeDefined();
const personas = getPersonasForTemplate('agency-consulting');
const filtered = getPersonasForTier('simple', personas);
expect(filtered.length).toBe(5);
expect(filtered[0].id).toBe('consultant');
});
});

View File

@@ -0,0 +1,101 @@
/**
* Phase 4.1 unblock — onboarding tier-filter helpers.
*
* Source spec: `docs/ux-disclosure-levels.md` r2 §"Templates — filter for Essential" + §"Personas — filter for Essential".
*
* Live system context: the dock is already filtered by `UserTier` via `TIER_DOCK_CONFIG`
* (apps/web/src/lib/dock-tiers.ts). The 0507_s1 brownfield diagnostic identified that
* onboarding's TemplateStep + PersonaStep show ALL options regardless of the tier the
* user picked at step 2 — an internal inconsistency that breaks the Ljiljana-bar.
*
* This file provides the smallest pure functions to close that gap. Pure helpers
* keep the test surface trivial; the components import + apply.
*
* Marko Q1 (2026-05-07): drop `coder` from Essential personas — quote: "this is not
* the target, unless you identify this tool can be useful for coders too, which I
* don't believe."
*/
import type { UserTier } from '@/lib/dock-tiers';
import type { OnboardingTemplate, OnboardingPersona } from '@/components/os/overlays/onboarding/types';
/**
* Templates surfaced by default at Essential. Listed in display order — TemplateStep
* renders these in the same sequence regardless of where they appear in the source
* `TEMPLATES` array. Other 12 templates remain reachable via "Show all" toggle.
*/
export const ESSENTIAL_TEMPLATE_IDS = [
'agency-consulting', // Marko's archetype, Ljiljana's role, broadest professional services match
'research-project', // Universally useful (HR research, market research, due diligence)
'blank', // Universal escape — any user who doesn't fit a category
] as const;
/**
* Personas surfaced by default at Essential. The recommended persona for the chosen
* template (e.g. `consultant` when the template is `agency-consulting`) is added on
* top by `getPersonasForTier` so users still see the right specialist for their work.
*
* Coder is excluded per Marko Q1 (2026-05-07).
*/
export const ESSENTIAL_PERSONA_IDS = [
'general-purpose',
'researcher',
'writer',
'analyst',
] as const;
const ESSENTIAL_TEMPLATE_SET = new Set<string>(ESSENTIAL_TEMPLATE_IDS);
const ESSENTIAL_PERSONA_SET = new Set<string>(ESSENTIAL_PERSONA_IDS);
/**
* Filter the template list according to the user's chosen tier. At `simple`, returns
* the 3 essential templates in spec order (NOT input order — `TEMPLATES` interleaves
* essentials between domain templates). At all other tiers, returns the input array
* unchanged so the reference is preserved (cheap render-side comparison wins).
*/
export function getTemplatesForTier(
tier: UserTier,
all: readonly OnboardingTemplate[],
): readonly OnboardingTemplate[] {
if (tier !== 'simple') return all;
if (all.length === 0) return all;
const byId = new Map<string, OnboardingTemplate>(all.map(t => [t.id, t]));
const out: OnboardingTemplate[] = [];
for (const id of ESSENTIAL_TEMPLATE_IDS) {
const t = byId.get(id);
if (t) out.push(t);
}
return out;
}
/**
* Filter the persona list according to the user's chosen tier. At `simple`, returns
* the 4 essential personas plus the recommended persona for the template (if it's
* a domain persona — knowledge/universal recommendations are already in the essential
* set). Input ordering is preserved so `getPersonasForTemplate`'s recommended-first
* sort survives — that's why the REC badge in PersonaStep still lands on the right
* tile after filtering.
*
* At all other tiers, returns the input array unchanged.
*/
export function getPersonasForTier(
tier: UserTier,
all: readonly OnboardingPersona[],
): readonly OnboardingPersona[] {
if (tier !== 'simple') return all;
if (all.length === 0) return all;
// The first entry of `all` is either:
// (a) the domain-recommended persona (when getPersonasForTemplate found one), or
// (b) the universal `general-purpose` (when the recommended is not a domain persona).
// Case (a) is the "consultant for agency-consulting" path — the persona must survive
// the filter even though it's `tier='domain'`. We detect (a) by checking if the
// first entry's id is OUTSIDE the essential set; if so, allow it through.
const first = all[0];
const allowedFirstId = ESSENTIAL_PERSONA_SET.has(first.id) ? null : first.id;
return all.filter(p =>
ESSENTIAL_PERSONA_SET.has(p.id) ||
(allowedFirstId !== null && p.id === allowedFirstId)
);
}

View File

@@ -0,0 +1,27 @@
import { describe, it, expect } from 'vitest';
import { formatPersonaName } from './persona-display';
describe('formatPersonaName', () => {
it('title-cases a kebab-case id', () => {
expect(formatPersonaName('sales-rep')).toBe('Sales Rep');
expect(formatPersonaName('product-manager-senior')).toBe('Product Manager Senior');
expect(formatPersonaName('general-purpose')).toBe('General Purpose');
});
it('capitalizes a single-word id', () => {
expect(formatPersonaName('writer')).toBe('Writer');
expect(formatPersonaName('coder')).toBe('Coder');
});
it('returns empty string for empty / undefined / non-string input — surface stays clean instead of showing "Undefined"', () => {
expect(formatPersonaName('')).toBe('');
expect(formatPersonaName(undefined)).toBe('');
expect(formatPersonaName(null)).toBe('');
expect(formatPersonaName(42)).toBe('');
});
it('preserves consecutive dashes as empty segments without crashing', () => {
// Defensive: any malformed id from the wire shouldn't blow up the UI.
expect(formatPersonaName('foo--bar')).toBe('Foo Bar');
});
});

View File

@@ -0,0 +1,24 @@
/**
* Tiny utility for turning a canonical persona ID (kebab-case)
* into a user-facing display name.
*
* Used by the connector landing surface ("Recommended for Sales Rep")
* and any other place that has only the ID at hand and needs a string
* for the UI without coupling to apps/web's onboarding constants or
* apps/agent's persona-data.
*
* Edge cases the regex covers:
* - 'sales-rep' → 'Sales Rep'
* - 'product-manager-senior' → 'Product Manager Senior'
* - 'general-purpose' → 'General Purpose'
* - 'pm' → 'Pm' (single word, capitalized)
* - '' → '' (empty stays empty)
* - undefined / null / non-string → '' (defensive)
*/
export function formatPersonaName(id: unknown): string {
if (typeof id !== 'string' || id.length === 0) return '';
return id
.split('-')
.map(part => part.length === 0 ? part : part[0].toUpperCase() + part.slice(1))
.join(' ');
}

Some files were not shown because too many files have changed in this diff Show More