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,134 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import type { Artifact, RelatedSearchResult } from '@/lib/types';
const mocks = vi.hoisted(() => ({
adapter: {
listArtifacts: vi.fn(),
searchRelatedArtifacts: vi.fn(),
deleteArtifact: vi.fn(),
archiveArtifact: vi.fn(),
patchArtifact: vi.fn(),
createArtifact: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter }));
import ArtifactCenterApp, { resetArtifactRouteCache } from '@/components/os/apps/ArtifactCenterApp';
const artifact: Artifact = {
id: 'artifact-brief',
title: 'Quarterly Research Brief',
kind: 'document',
workspaceId: 'workspace-research',
createdBy: 'agent-researcher',
source: 'agent',
status: 'ready',
storagePath: '/artifacts/quarterly-brief.md',
tags: ['research'],
createdAt: '2026-07-08T08:00:00.000Z',
updatedAt: '2026-07-08T09:00:00.000Z',
};
const emptyRelated: RelatedSearchResult = {
memories: [],
sessions: [],
tasks: [],
agents: [],
artifacts: [],
};
function renderArtifactCenter() {
return render(
<MemoryRouter>
<ArtifactCenterApp activeWorkspaceId="workspace-research" workspaceName="Research" />
</MemoryRouter>,
);
}
beforeEach(() => {
vi.clearAllMocks();
resetArtifactRouteCache();
mocks.adapter.listArtifacts.mockResolvedValue([artifact]);
mocks.adapter.searchRelatedArtifacts.mockResolvedValue(emptyRelated);
mocks.adapter.deleteArtifact.mockResolvedValue(undefined);
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
it('repaints the keyed artifact list on return and refreshes silently', async () => {
const first = renderArtifactCenter();
expect(await screen.findByText('Quarterly Research Brief')).toBeInTheDocument();
const baseline = mocks.adapter.listArtifacts.mock.calls.length;
first.unmount();
renderArtifactCenter();
expect(screen.getByText('Quarterly Research Brief')).toBeInTheDocument();
await waitFor(() => expect(mocks.adapter.listArtifacts.mock.calls.length).toBeGreaterThan(baseline));
});
describe('Artifact Center trust flows', () => {
it('a11y: search and create controls expose stable form metadata', () => {
renderArtifactCenter();
const search = screen.getByRole('textbox', { name: 'Search artifacts' });
expect(search).toHaveAttribute('name', 'artifactSearch');
expect(search).toHaveAttribute('autocomplete', 'off');
const title = screen.getByRole('textbox', { name: 'New artifact title' });
expect(title).toHaveAttribute('name', 'artifactTitle');
expect(title).toHaveAttribute('autocomplete', 'off');
const kind = screen.getByRole('combobox', { name: 'New artifact kind' });
expect(kind).toHaveAttribute('name', 'artifactKind');
expect(kind).toHaveAttribute('autocomplete', 'off');
});
it('scopes artifact card hover transitions to explicit properties', async () => {
renderArtifactCenter();
const card = await screen.findByRole('button', { name: /quarterly research brief/i });
expect(card.className).not.toContain('transition-all');
expect(card.className).toContain('transition-[border-color,transform]');
});
it('a11y: detail editor controls expose stable form metadata', async () => {
renderArtifactCenter();
fireEvent.click(await screen.findByRole('button', { name: /quarterly research brief/i }));
const title = await screen.findByLabelText('Title');
expect(title).toHaveAttribute('name', 'artifactDraftTitle');
expect(title).toHaveAttribute('autocomplete', 'off');
const kind = screen.getByLabelText('Kind');
expect(kind).toHaveAttribute('name', 'artifactDraftKind');
expect(kind).toHaveAttribute('autocomplete', 'off');
expect(kind.className).toContain('focus-visible:ring-2');
});
it('asks in-app before permanently deleting an artifact', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
renderArtifactCenter();
fireEvent.click(await screen.findByRole('button', { name: /quarterly research brief/i }));
fireEvent.click(await screen.findByRole('button', { name: /^delete$/i }));
expect(confirmSpy).not.toHaveBeenCalled();
expect(mocks.adapter.deleteArtifact).not.toHaveBeenCalled();
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent(/delete artifact permanently/i);
expect(modal).toHaveTextContent(/quarterly research brief/i);
expect(modal).toHaveTextContent(/backing file/i);
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.deleteArtifact).toHaveBeenCalledWith('artifact-brief', 'workspace-research'));
});
});

View File

@@ -0,0 +1,55 @@
import { describe, expect, it } from 'vitest';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
const sourceRoot = join(process.cwd(), 'src');
describe('build warning hygiene', () => {
it('does not dynamically import shape-selection from the adapter', () => {
const adapterSource = readFileSync(join(sourceRoot, 'lib', 'adapter.ts'), 'utf8');
expect(adapterSource).not.toContain("import('./shape-selection')");
expect(adapterSource).toContain("from './shape-selection'");
});
it('keeps routed app surfaces out of the root app bundle', () => {
const appSource = readFileSync(join(sourceRoot, 'App.tsx'), 'utf8');
expect(appSource).not.toContain('from "@/routes"');
for (const route of ['HomeRoute', 'LauncherRoute', 'SettingsRoute']) {
expect(appSource).toContain(`lazy(() => import("@/routes/${route}"))`);
}
});
it('keeps closed shell overlays out of the root shell bundle', () => {
const shellSource = readFileSync(join(sourceRoot, 'components', 'os', 'AppShell.tsx'), 'utf8');
expect(shellSource).not.toContain("import ChatHost from './ChatHost'");
expect(shellSource).toContain("lazy(() => import('./ChatHost'))");
for (const overlay of [
'CommandCenter',
'CreateWorkspaceDialog',
'PersonaSwitcher',
'SpawnAgentDialog',
'WorkspaceSwitcher',
'NotificationInbox',
'KeyboardShortcutsHelp',
'OnboardingWizard',
'OnboardingTooltips',
'LoginBriefing',
'ContextRail',
'TrialExpiredModal',
]) {
expect(shellSource).not.toContain(`import ${overlay} from './overlays/${overlay}'`);
expect(shellSource).toContain(`lazy(() => import('./overlays/${overlay}'))`);
}
});
it('keeps cloud analytics out of the startup bundle', () => {
const mainSource = readFileSync(join(sourceRoot, 'main.tsx'), 'utf8');
expect(mainSource).not.toContain('from "@/lib/posthog"');
expect(mainSource).toContain('import("@/lib/posthog")');
});
});

View File

@@ -0,0 +1,72 @@
/**
* ArtifactBlock (UX-Northstar Phase C2) — artifact-first chat rendering.
* Pins:
* - completed write_file/edit_file blocks render the artifact card
* - running / failed / non-file tool blocks keep the generic tool row
* - Open in Files stashes a path deep-link and fires waggle:open-app
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
import BlockRenderer from '@/components/os/apps/chat-blocks/BlockRenderer';
import { isArtifactBlock } from '@/components/os/apps/chat-blocks/ArtifactBlock';
import { consumeDeepLink } from '@/lib/app-deeplink';
import type { ToolUseContentBlock } from '@/lib/types';
const toolBlock = (over: Partial<ToolUseContentBlock>): ToolUseContentBlock => ({
type: 'tool_use',
id: 'tb-1',
name: 'write_file',
status: 'done',
input: { path: 'reports/q3-summary.md' },
...over,
});
describe('ArtifactBlock', () => {
afterEach(() => {
cleanup();
consumeDeepLink('files'); // drain any stashed link between tests
});
it('renders the artifact card for a completed write_file', () => {
render(<BlockRenderer blocks={[toolBlock({})]} />);
expect(screen.getByTestId('chat-artifact-block')).toBeTruthy();
expect(screen.getByText('q3-summary.md')).toBeTruthy();
expect(screen.getByText(/Created by the agent/)).toBeTruthy();
});
it('says Updated for edit_file', () => {
render(<BlockRenderer blocks={[toolBlock({ name: 'edit_file' })]} />);
expect(screen.getByText(/Updated by the agent/)).toBeTruthy();
});
it('keeps the generic tool row while running and on error', () => {
render(
<BlockRenderer
blocks={[
toolBlock({ id: 'tb-r', status: 'running' }),
toolBlock({ id: 'tb-e', status: 'error' }),
]}
/>,
);
expect(screen.queryByTestId('chat-artifact-block')).toBeNull();
});
it('does not treat non-file tools as artifacts', () => {
expect(isArtifactBlock(toolBlock({ name: 'web_search', input: { path: 'x' } }))).toBe(false);
expect(isArtifactBlock(toolBlock({ input: {} }))).toBe(false);
expect(isArtifactBlock(toolBlock({}))).toBe(true);
});
it('Open in Files stashes the path deep-link and fires waggle:open-app', () => {
const events: string[] = [];
const handler = (e: Event) => events.push((e as CustomEvent).detail?.appId);
window.addEventListener('waggle:open-app', handler);
render(<BlockRenderer blocks={[toolBlock({})]} />);
fireEvent.click(screen.getByTestId('chat-artifact-open'));
window.removeEventListener('waggle:open-app', handler);
expect(events).toEqual(['files']);
expect(consumeDeepLink('files')).toMatchObject({ appId: 'files', path: 'reports/q3-summary.md' });
});
});

View File

@@ -0,0 +1,89 @@
/**
* PR3 Phase B2/B3 — Chat work-canvas selector + activity grouping.
*
* Locks two net-new behaviors:
* - selectCanvasArtifact: latest completed file-write → {path, body}, body
* prefers input.content over the opaque result; null when none.
* - BlockRenderer: a consecutive run of `step` blocks collapses into ONE
* Activity card (default-collapsed off the active turn, open while streaming),
* while a completed write_file still routes to the artifact card.
*/
import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
import type { ChatMessage, ContentBlock } from '@/lib/types';
import { BlockRenderer } from '@/components/os/apps/chat-blocks';
import { selectCanvasArtifact } from '@/components/os/apps/chat-blocks/ChatWorkCanvas';
afterEach(cleanup);
function asstMsg(blocks: ContentBlock[]): ChatMessage {
return { id: 'm1', role: 'assistant', content: '', blocks, timestamp: new Date().toISOString() };
}
const writeBlock = (path: string, content?: string, result?: string): ContentBlock => ({
type: 'tool_use', id: 't1', name: 'write_file', status: 'done',
input: { path, ...(content !== undefined ? { content } : {}) },
...(result !== undefined ? { result } : {}),
});
describe('selectCanvasArtifact', () => {
it('returns the latest completed file-write, preferring input.content', () => {
const out = selectCanvasArtifact([asstMsg([writeBlock('docs/teardown.md', '# Q2 Teardown', 'ok')])]);
expect(out).toEqual({ path: 'docs/teardown.md', body: '# Q2 Teardown' });
});
it('falls back to the result string when no input.content', () => {
const out = selectCanvasArtifact([asstMsg([writeBlock('a.md', undefined, 'wrote 9 rows')])]);
expect(out).toEqual({ path: 'a.md', body: 'wrote 9 rows' });
});
it('ignores running/non-file blocks and returns null when none qualify', () => {
const running: ContentBlock = { type: 'tool_use', id: 't2', name: 'write_file', status: 'running', input: { path: 'x.md' } };
expect(selectCanvasArtifact([asstMsg([running])])).toBeNull();
expect(selectCanvasArtifact([asstMsg([{ type: 'text', blockId: 'b', content: 'hi' }])])).toBeNull();
});
});
describe('BlockRenderer — activity grouping', () => {
const steps: ContentBlock[] = [
{ type: 'step', blockId: 's1', description: 'Recalled 6 memories', status: 'done' },
{ type: 'step', blockId: 's2', description: 'Searched 9 sites', status: 'done' },
];
it('collapses consecutive steps into one Activity card (closed off the active turn)', () => {
render(<BlockRenderer blocks={steps} />);
expect(screen.getByText(/Worked across your memory/)).toBeInTheDocument();
// collapsed → step text hidden until expanded
expect(screen.queryByText('Recalled 6 memories')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { expanded: false }));
expect(screen.getByText('Recalled 6 memories')).toBeInTheDocument();
expect(screen.getByText('Searched 9 sites')).toBeInTheDocument();
});
it('opens the Activity card by default while streaming', () => {
render(<BlockRenderer blocks={steps} isStreaming />);
expect(screen.getByText('Recalled 6 memories')).toBeInTheDocument();
});
it('still routes a completed write_file to the artifact card', () => {
render(<BlockRenderer blocks={[writeBlock('out/report.md', '# R')]} />);
expect(screen.getByTestId('chat-artifact-block')).toBeInTheDocument();
});
it('F11: steps split by a tool_use (auto-recall) still yield ONE Activity card', () => {
const blocks: ContentBlock[] = [
{ type: 'step', blockId: 's1', description: 'Recalling relevant memories', status: 'done' },
{ type: 'tool_use', id: 't1', name: 'auto_recall', status: 'done', input: {}, result: '2 memories recalled' },
{ type: 'step', blockId: 's2', description: 'Recalled 2 relevant memories', status: 'done' },
{ type: 'step', blockId: 's3', description: 'Searched 3 sites', status: 'done' },
];
render(<BlockRenderer blocks={blocks} />);
// Exactly one summary despite the tool_use splitting the step run.
expect(screen.getAllByText(/Worked across your memory/)).toHaveLength(1);
// Expanding the single card reveals all three step descriptions.
fireEvent.click(screen.getByRole('button', { expanded: false }));
expect(screen.getByText('Recalling relevant memories')).toBeInTheDocument();
expect(screen.getByText('Recalled 2 relevant memories')).toBeInTheDocument();
expect(screen.getByText('Searched 3 sites')).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,106 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
const mocks = vi.hoisted(() => ({
adapter: {
listComplianceTemplates: vi.fn(),
deleteComplianceTemplate: vi.fn(),
updateComplianceTemplate: vi.fn(),
createComplianceTemplate: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import { ComplianceTemplateModal, type ComplianceTemplate } from '@/components/os/apps/cockpit/ComplianceTemplateModal';
const template: ComplianceTemplate = {
id: 7,
name: 'High Risk Template',
description: 'EU AI Act evidence packet',
sections: {
interactions: true,
oversight: true,
models: true,
provenance: true,
riskAssessment: true,
fria: true,
},
riskClassification: 'high-risk',
orgName: 'Egzakta',
footerText: null,
createdAt: '2026-07-08T08:00:00.000Z',
updatedAt: '2026-07-08T09:00:00.000Z',
};
beforeEach(() => {
vi.clearAllMocks();
mocks.adapter.listComplianceTemplates.mockResolvedValue({ templates: [template] });
mocks.adapter.deleteComplianceTemplate.mockResolvedValue({ ok: true });
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
describe('ComplianceTemplateModal trust flows', () => {
it('exposes template form fields with stable metadata and focus rings', async () => {
render(<ComplianceTemplateModal open onClose={vi.fn()} />);
await screen.findByText('High Risk Template');
fireEvent.click(screen.getByRole('button', { name: /new template/i }));
const name = screen.getByRole('textbox', { name: /^name$/i });
expect(name).toHaveAttribute('name', 'complianceTemplateName');
expect(name).toHaveAttribute('autocomplete', 'off');
expect(name.className).toContain('focus-visible:ring-2');
expect(name.className).toContain('focus-visible:ring-[var(--focus-ring)]');
const description = screen.getByRole('textbox', { name: /description/i });
expect(description).toHaveAttribute('name', 'complianceTemplateDescription');
expect(description).toHaveAttribute('autocomplete', 'off');
expect(description.className).toContain('focus-visible:ring-2');
expect(description.className).toContain('focus-visible:ring-[var(--focus-ring)]');
const riskClass = screen.getByRole('combobox', { name: /risk class/i });
expect(riskClass).toHaveAttribute('name', 'complianceTemplateRiskClass');
expect(riskClass).toHaveAttribute('autocomplete', 'off');
expect(riskClass.className).toContain('focus-visible:ring-2');
expect(riskClass.className).toContain('focus-visible:ring-[var(--focus-ring)]');
const orgName = screen.getByRole('textbox', { name: /org name/i });
expect(orgName).toHaveAttribute('name', 'complianceTemplateOrgName');
expect(orgName).toHaveAttribute('autocomplete', 'organization');
expect(orgName.className).toContain('focus-visible:ring-2');
expect(orgName.className).toContain('focus-visible:ring-[var(--focus-ring)]');
const footerText = screen.getByRole('textbox', { name: /footer text/i });
expect(footerText).toHaveAttribute('name', 'complianceTemplateFooterText');
expect(footerText).toHaveAttribute('autocomplete', 'off');
expect(footerText.className).toContain('focus-visible:ring-2');
expect(footerText.className).toContain('focus-visible:ring-[var(--focus-ring)]');
});
it('asks in-app before deleting a compliance template', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
const onChange = vi.fn();
render(<ComplianceTemplateModal open onClose={vi.fn()} onChange={onChange} />);
await screen.findByText('High Risk Template');
fireEvent.click(screen.getByRole('button', { name: /delete high risk template/i }));
expect(confirmSpy).not.toHaveBeenCalled();
expect(mocks.adapter.deleteComplianceTemplate).not.toHaveBeenCalled();
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent(/delete compliance template/i);
expect(modal).toHaveTextContent(/high risk template/i);
expect(modal).toHaveTextContent(/saved report shape/i);
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.deleteComplianceTemplate).toHaveBeenCalledWith(7));
expect(onChange).toHaveBeenCalledTimes(1);
});
});

View File

@@ -0,0 +1,27 @@
/**
* ContextMenu (Pillar 2.7, Lane K) — the arrow-key roving highlight paints a
* visible focus indicator using the systemic --focus-ring token, so keyboard
* navigation reads the same as the app-wide :focus-visible ring.
*/
import { describe, it, expect, afterEach, vi } from 'vitest';
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
import ContextMenu from '@/components/os/ContextMenu';
afterEach(() => cleanup());
describe('ContextMenu keyboard focus ring', () => {
it('rings the keyboard-highlighted item with --focus-ring after ArrowDown', () => {
render(
<ContextMenu
items={[{ label: 'Rename', onClick: vi.fn() }, { label: 'Delete', onClick: vi.fn() }]}
position={{ x: 0, y: 0 }}
onClose={vi.fn()}
/>,
);
// At rest nothing is roving-highlighted.
expect(screen.getByText('Rename').className).not.toContain('ring-[var(--focus-ring)]');
// ArrowDown moves the roving highlight onto the first action item.
fireEvent.keyDown(document, { key: 'ArrowDown' });
expect(screen.getByText('Rename').className).toContain('ring-[var(--focus-ring)]');
});
});

View File

@@ -0,0 +1,112 @@
/**
* EmbeddingRoutingCard (steal #10) — provider picker + live status + reprobe.
* Verifies: tier-scoped options, key-gating (openai disabled without a key),
* reprobe calls the API, provider change persists + surfaces the restart hint,
* and the env-override state disables the picker.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
const mocks = vi.hoisted(() => ({
adapter: {
getEmbeddingStatus: vi.fn(),
setEmbeddingProvider: vi.fn(),
reprobeEmbedding: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({
adapter: mocks.adapter,
// Card uses `instanceof AdapterHttpError` in its catch — provide a real class.
AdapterHttpError: class AdapterHttpError extends Error {},
default: vi.fn(),
}));
const baseStatus = {
activeProvider: 'mock',
availableProviders: ['mock'],
dimensions: 1024,
modelName: 'deterministic-mock',
configuredProvider: 'auto',
envOverride: false,
};
const PROVIDERS = [
{ id: 'openai', name: 'OpenAI', hasKey: false, badge: null, keyUrl: null, requiresKey: true, models: [] },
{ id: 'anthropic', name: 'Anthropic', hasKey: true, badge: null, keyUrl: null, requiresKey: true, models: [] },
];
async function renderCard(tier: 'FREE' | 'TEAMS' = 'FREE') {
const { default: EmbeddingRoutingCard } = await import('@/components/os/EmbeddingRoutingCard');
const { TooltipProvider } = await import('@/components/ui/tooltip');
render(
<TooltipProvider>
<EmbeddingRoutingCard providers={PROVIDERS as never} tier={tier} />
</TooltipProvider>,
);
}
beforeEach(() => {
mocks.adapter.getEmbeddingStatus.mockResolvedValue({ ...baseStatus });
mocks.adapter.setEmbeddingProvider.mockResolvedValue({ ...baseStatus, configuredProvider: 'inprocess', restartRequired: true });
mocks.adapter.reprobeEmbedding.mockResolvedValue({ ...baseStatus });
});
afterEach(() => { cleanup(); vi.clearAllMocks(); });
describe('EmbeddingRoutingCard', () => {
it('names the embeddings information control', async () => {
await renderCard('FREE');
expect(screen.getByRole('button', { name: 'About memory embeddings' })).toBeInTheDocument();
});
it('renders the tier-allowed provider options (FREE has no litellm)', async () => {
await renderCard('FREE');
const select = await screen.findByTestId('embedding-provider-select');
const values = Array.from(select.querySelectorAll('option')).map(o => (o as HTMLOptionElement).value);
expect(values).toEqual(expect.arrayContaining(['auto', 'inprocess', 'ollama', 'voyage', 'openai']));
expect(values).not.toContain('litellm');
expect(values).not.toContain('mock');
});
it('includes litellm on TEAMS', async () => {
await renderCard('TEAMS');
const select = await screen.findByTestId('embedding-provider-select');
const values = Array.from(select.querySelectorAll('option')).map(o => (o as HTMLOptionElement).value);
expect(values).toContain('litellm');
});
it('disables the openai option when its vault key is missing', async () => {
await renderCard('FREE');
const select = await screen.findByTestId('embedding-provider-select');
const openai = Array.from(select.querySelectorAll('option')).find(
o => (o as HTMLOptionElement).value === 'openai',
) as HTMLOptionElement;
expect(openai.disabled).toBe(true);
});
it('shows the active provider from the status probe', async () => {
await renderCard('FREE');
expect(await screen.findByTestId('embedding-active-provider')).toHaveTextContent(/mock/i);
});
it('Reprobe calls the API', async () => {
await renderCard('FREE');
fireEvent.click(await screen.findByTestId('embedding-reprobe'));
await waitFor(() => expect(mocks.adapter.reprobeEmbedding).toHaveBeenCalledTimes(1));
});
it('changing the provider persists and surfaces the restart hint', async () => {
await renderCard('FREE');
const select = await screen.findByTestId('embedding-provider-select');
fireEvent.change(select, { target: { value: 'inprocess' } });
await waitFor(() => expect(mocks.adapter.setEmbeddingProvider).toHaveBeenCalledWith('inprocess'));
expect(await screen.findByTestId('embedding-restart-hint')).toBeInTheDocument();
});
it('disables the picker and hints when an env override is active', async () => {
mocks.adapter.getEmbeddingStatus.mockResolvedValue({ ...baseStatus, envOverride: true });
await renderCard('FREE');
const select = await screen.findByTestId('embedding-provider-select');
expect((select as HTMLSelectElement).disabled).toBe(true);
expect(screen.getByTestId('embedding-env-hint')).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,7 @@
import { describe, it, expect } from "vitest";
describe("example", () => {
it("should pass", () => {
expect(true).toBe(true);
});
});

View File

@@ -0,0 +1,43 @@
/**
* normalizeWorkspacePath (push-review MEDIUM, path traversal): lexical guard
* for untrusted deep-link paths. Pure-function pinning of the traversal cases.
*/
import { describe, it, expect } from 'vitest';
import { normalizeWorkspacePath } from '@/components/os/apps/files/file-utils';
describe('normalizeWorkspacePath', () => {
it('leaves a clean absolute path intact', () => {
expect(normalizeWorkspacePath('/reports/q3-summary.md')).toBe('/reports/q3-summary.md');
});
it('adds a leading slash to a relative path', () => {
expect(normalizeWorkspacePath('reports/q3-summary.md')).toBe('/reports/q3-summary.md');
});
it('strips a single ../ segment', () => {
expect(normalizeWorkspacePath('/reports/../notes.md')).toBe('/notes.md');
});
it('cannot escape root with stacked ../', () => {
expect(normalizeWorkspacePath('/reports/../../etc/passwd')).toBe('/etc/passwd');
expect(normalizeWorkspacePath('../../../../etc/passwd')).toBe('/etc/passwd');
});
it('collapses . and empty segments', () => {
expect(normalizeWorkspacePath('/a/./b//c')).toBe('/a/b/c');
});
it('resolves to root for empty / dot-only / over-popped inputs', () => {
expect(normalizeWorkspacePath('')).toBe('/');
expect(normalizeWorkspacePath('/')).toBe('/');
expect(normalizeWorkspacePath('.')).toBe('/');
expect(normalizeWorkspacePath('/reports/..')).toBe('/');
expect(normalizeWorkspacePath('/..')).toBe('/');
});
it('never leaves a .. segment in the output', () => {
for (const input of ['/a/../../b', '..%2f..', '/x/../../../y', 'a/b/../../../../z']) {
expect(normalizeWorkspacePath(input).split('/')).not.toContain('..');
}
});
});

View File

@@ -0,0 +1,90 @@
/**
* Files deep-link consumption (UX-Northstar Phase C2) — chat artifact cards
* stash {appId:'files', path} and open the Files app; FilesApp must navigate
* to the file's directory, select it, and open the preview.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render as rtlRender, waitFor, cleanup } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
import { stashDeepLink, consumeDeepLink } from '@/lib/app-deeplink';
const mocks = vi.hoisted(() => ({
adapter: {
listFiles: vi.fn(),
downloadFile: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import FilesApp, { resetFilesRouteCache } from '@/components/os/apps/FilesApp';
const render = () =>
rtlRender(<TooltipProvider><FilesApp workspaceId="ws1" /></TooltipProvider>);
beforeEach(() => {
resetFilesRouteCache();
vi.clearAllMocks();
mocks.adapter.listFiles.mockResolvedValue([
{ name: 'q3-summary.md', path: '/reports/q3-summary.md', type: 'file', size: 12, modified: Date.now() },
]);
mocks.adapter.downloadFile.mockResolvedValue(new Blob(['# Q3 summary']));
});
afterEach(() => {
cleanup();
consumeDeepLink('files'); // drain leftovers between tests
});
describe('Files deep-link (chat artifact → Open in Files)', () => {
it('navigates to the file directory and opens its preview', async () => {
stashDeepLink({ appId: 'files', path: '/reports/q3-summary.md' });
render();
await waitFor(() => {
expect(mocks.adapter.listFiles).toHaveBeenCalledWith('ws1', '/reports');
expect(mocks.adapter.downloadFile).toHaveBeenCalledWith('ws1', '/reports/q3-summary.md');
});
});
it('normalizes a relative path before navigating', async () => {
stashDeepLink({ appId: 'files', path: 'reports/q3-summary.md' });
render();
await waitFor(() => {
expect(mocks.adapter.listFiles).toHaveBeenCalledWith('ws1', '/reports');
});
});
it('without a stashed link, loads the root as before', async () => {
render();
await waitFor(() => {
expect(mocks.adapter.listFiles).toHaveBeenCalledWith('ws1', '/');
});
expect(mocks.adapter.downloadFile).not.toHaveBeenCalled();
});
// Security (push review MEDIUM): the deep-link path originates from an agent
// tool-call input — a traversal payload must be neutralized before it can set
// currentPath/selection or reach the adapter.
it('strips ../ traversal from a malicious deep-link path', async () => {
stashDeepLink({ appId: 'files', path: '/reports/../../etc/passwd' });
render();
await waitFor(() => {
// '/reports/../../etc/passwd' normalizes to '/etc/passwd' → parent '/etc'.
// No '..' ever reaches the adapter; backend resolveSafe is the hard guard.
expect(mocks.adapter.listFiles).toHaveBeenCalledWith('ws1', '/etc');
});
const calledPaths = mocks.adapter.listFiles.mock.calls.map(c => c[1]);
expect(calledPaths.some(p => String(p).includes('..'))).toBe(false);
const dlPaths = mocks.adapter.downloadFile.mock.calls.map(c => c[1]);
expect(dlPaths.some(p => String(p).includes('..'))).toBe(false);
});
it('a path that resolves to root preselects nothing', async () => {
stashDeepLink({ appId: 'files', path: '/reports/..' });
render();
await waitFor(() => {
expect(mocks.adapter.listFiles).toHaveBeenCalledWith('ws1', '/');
});
// Resolved to '/', so no file is selected/previewed.
expect(mocks.adapter.downloadFile).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,43 @@
/**
* KeyboardShortcutsHelp (Pillar 2.7, Lane K) — the discoverable cheat sheet.
* Pins that the new power-path shortcuts and the keyboard-first reveal tip are
* documented, and that the close control carries a ≥40px hit area.
*/
import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/react';
import KeyboardShortcutsHelp from '@/components/os/overlays/KeyboardShortcutsHelp';
afterEach(() => cleanup());
describe('KeyboardShortcutsHelp', () => {
it('renders nothing when closed', () => {
const { container } = render(<KeyboardShortcutsHelp open={false} onClose={() => {}} />);
expect(container.firstChild).toBeNull();
});
it('documents the new-chat and open-last-workspace power paths', () => {
render(<KeyboardShortcutsHelp open onClose={() => {}} />);
expect(screen.getByText('New chat')).toBeTruthy();
expect(screen.getByText('Open last workspace')).toBeTruthy();
});
it('lists the "?" cheat-sheet trigger', () => {
render(<KeyboardShortcutsHelp open onClose={() => {}} />);
// The Keyboard Shortcuts row is keyed to the discoverable bare "?".
const kbds = screen.getAllByText('?');
expect(kbds.length).toBeGreaterThan(0);
});
it('surfaces the keyboard-first reveal tip (Tab reaches card & row actions)', () => {
render(<KeyboardShortcutsHelp open onClose={() => {}} />);
expect(screen.getByText(/Tab reaches every card/i)).toBeTruthy();
});
it('gives the close control a ≥40px hit area (centered 40px ::before)', () => {
render(<KeyboardShortcutsHelp open onClose={() => {}} />);
const close = screen.getByLabelText('Close keyboard shortcuts');
expect(close.className).toContain('relative');
expect(close.className).toContain('before:h-10');
expect(close.className).toContain('before:w-10');
});
});

View File

@@ -0,0 +1,187 @@
/**
* Lane AL — the aliveness loop (Path-to-9 Pillar 3.2/3.3/3.4).
*
* Locks the aliveness moments this lane owns:
* - Surprise-recall bloom: the memory-recall step blooms honey on the ACTIVE
* turn (data-recall-bloom), never on a history reload; reduced-motion → plain.
* - Investment celebration: the overnight accrual figure reuses the DeltaNumber
* pulse, bound to the exact source-of-truth count (no fabrication).
* - Home ambient hive glow: a home-only, below-attention breath; reduced-motion
* holds a static faint radial (REDUCED.ambient = off).
*
* framer-motion's `useReducedMotion` caches globally across renders, so it can't
* be flipped per-test via matchMedia — it's mocked to a hoisted toggle (the real
* `motion` components stay, so class/data-attribute assertions are unaffected).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react';
import type { ContentBlock, HomeBriefing, OvernightSummary, RecentWorkspaceCard } from '@/lib/types';
const h = vi.hoisted(() => ({ reduce: false }));
vi.mock('framer-motion', async () => {
const actual = await vi.importActual<typeof import('framer-motion')>('framer-motion');
return { ...actual, useReducedMotion: () => h.reduce };
});
const mocks = vi.hoisted(() => ({
adapter: {
getHomeBriefing: vi.fn(),
getHomeOvernight: vi.fn(),
quickCapture: vi.fn(),
getWorkspaces: vi.fn(),
searchMemory: vi.fn(),
getMemoryStats: vi.fn(),
getWorkspaceContext: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/providers/ServiceProvider', () => ({
useService: () => ({ connecting: false, connected: true }),
ServiceProvider: ({ children }: { children: React.ReactNode }) => children,
}));
vi.mock('@/hooks/useOfflineStatus', () => ({ useOfflineStatus: () => false }));
vi.mock('@/providers/ShellContext', () => ({
useShell: () => ({ patchWorkspace: vi.fn().mockResolvedValue(true), deleteWorkspace: vi.fn().mockResolvedValue(true) }),
}));
import { ActivityStream } from '@/components/os/warm';
import { AmbientHiveGlow } from '@/components/os/warm/AmbientHiveGlow';
import { BlockRenderer } from '@/components/os/apps/chat-blocks';
beforeEach(() => { h.reduce = false; });
afterEach(() => { cleanup(); });
// ── Surprise-recall bloom (Pillar 3.2) ─────────────────────────────────────
describe('surprise-recall bloom', () => {
it('blooms the recall step (data-recall-bloom) when bloom is set and motion is allowed', () => {
const { container } = render(
<ActivityStream
summary="Worked across your memory"
defaultOpen
steps={[{ text: 'Recalled 6 memories', provenance: { source: 'you' }, bloom: true }]}
/>,
);
expect(container.querySelector('[data-recall-bloom]')).not.toBeNull();
expect(screen.getByText('Recalled 6 memories')).toBeInTheDocument();
});
it('does NOT bloom under prefers-reduced-motion (plain row, no marker)', () => {
h.reduce = true;
const { container } = render(
<ActivityStream
summary="Worked across your memory"
defaultOpen
steps={[{ text: 'Recalled 6 memories', provenance: { source: 'you' }, bloom: true }]}
/>,
);
expect(container.querySelector('[data-recall-bloom]')).toBeNull();
expect(screen.getByText('Recalled 6 memories')).toBeInTheDocument();
});
it('a non-bloom step stays a plain row', () => {
const { container } = render(
<ActivityStream summary="Worked" defaultOpen steps={[{ text: 'Searched 9 sites' }]} />,
);
expect(container.querySelector('[data-recall-bloom]')).toBeNull();
});
it('BlockRenderer blooms a memory-recall step on the ACTIVE (streaming) turn only', () => {
const recall: ContentBlock[] = [
{ type: 'step', blockId: 's1', description: 'Recalled 3 memories', status: 'done', provenance: { sources: ['user_stated'] } },
];
// Streaming turn → the card is open and the recall row blooms.
const streaming = render(<BlockRenderer blocks={recall} isStreaming />);
expect(streaming.container.querySelector('[data-recall-bloom]')).not.toBeNull();
cleanup();
// History reload (not streaming) → expand the card; the recall row is plain.
const history = render(<BlockRenderer blocks={recall} />);
fireEvent.click(history.getByRole('button', { expanded: false }));
expect(history.getByText('Recalled 3 memories')).toBeInTheDocument();
expect(history.container.querySelector('[data-recall-bloom]')).toBeNull();
});
});
// ── Home ambient hive glow (Pillar 3.4) ────────────────────────────────────
describe('AmbientHiveGlow', () => {
it('renders nothing when inactive (home-only gate)', () => {
const { container } = render(<AmbientHiveGlow active={false} />);
expect(container.querySelector('[data-testid="ambient-hive-glow"]')).toBeNull();
});
it('renders a breathing radial when active and motion is allowed', () => {
render(<AmbientHiveGlow />);
const glow = screen.getByTestId('ambient-hive-glow');
expect(glow).toBeInTheDocument();
expect(glow.getAttribute('data-reduced')).toBe('false');
expect(glow.getAttribute('aria-hidden')).toBe('true');
expect(glow.querySelector('.hive-ambient-breath')).not.toBeNull();
});
it('holds a static radial under prefers-reduced-motion (no breath loop)', () => {
h.reduce = true;
render(<AmbientHiveGlow />);
const glow = screen.getByTestId('ambient-hive-glow');
expect(glow.getAttribute('data-reduced')).toBe('true');
expect(glow.querySelector('.hive-ambient-breath')).toBeNull();
});
});
// ── Investment celebration (Pillar 3.3) — overnight accrual DeltaNumber ─────
describe('investment celebration — overnight accrual pulse', () => {
function wsCard(id: string, name: string): RecentWorkspaceCard {
return { id, name, group: 'Personal', lastActive: '2026-07-06T09:00:00.000Z', pendingCount: 0 };
}
function makeBriefing(over: Partial<HomeBriefing> = {}): HomeBriefing {
return {
greeting: 'Welcome back, Marko',
date: '2026-07-07T08:00:00.000Z',
recentWorkspaces: [wsCard('w1', 'Alpha')],
suggestedActions: [],
upNext: [],
isFirstRun: false,
needsReviewCount: 0,
...over,
};
}
const overnight = (consolidated: number): OvernightSummary => ({
consolidated,
artifactsCreated: 0,
automationsCompleted: 0,
failures: [],
});
beforeEach(async () => {
const { clearHomeCache } = await import('@/lib/home-cache');
const { resetBriefingSource } = await import('@/lib/briefing-source');
clearHomeCache();
resetBriefingSource();
window.localStorage.clear();
vi.clearAllMocks();
});
it('the accrual figure pulses (home-delta-pulse) when it grows over a cache-first paint, bound to the exact count', async () => {
const { writeHomeCache } = await import('@/lib/home-cache');
const HomeCockpit = (await import('@/components/os/apps/HomeCockpit')).default;
// Cache: 5 memories folded. Fresh: 12 (the number the user should SEE grow).
// Workspace count is held constant so the ONLY pulsing figure is the accrual.
writeHomeCache({ briefing: makeBriefing(), overnight: overnight(5), highlights: [] });
mocks.adapter.getHomeBriefing.mockResolvedValue(makeBriefing());
mocks.adapter.getHomeOvernight.mockResolvedValue(overnight(12));
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.searchMemory.mockResolvedValue([]);
mocks.adapter.getMemoryStats.mockResolvedValue(null);
render(<HomeCockpit onContinue={vi.fn()} onOpenWorkspaceDesktop={vi.fn()} onCreateWorkspace={vi.fn()} totalWorkspaceCount={1} />);
// Cache-first paint shows the accrual from cache.
expect(screen.getByText(/folded/)).toBeInTheDocument();
// Silent refresh lands the real 12 — and only that figure carries the pulse.
await waitFor(() => {
const pulsed = document.querySelector('.home-delta-pulse');
expect(pulsed?.textContent).toBe('12');
});
});
});

View File

@@ -0,0 +1,296 @@
/**
* Lane C — input-during-warmup + send-path budget + chat route-cache
* (Path-to-9 Phase B · Pillar 2.2 / 2.5 / 2.6-chat).
*
* Contracts as TESTS (spec §Lane C):
* 1. Composer accepts typing at paint; a send fired before the reply is ready
* is QUEUED (one optimistic `queued` turn), then dispatched on ready —
* never errors, never drops.
* 2. Composer never locks on send: a send while the previous streams is
* accepted immediately (send enabled, no concurrent stream) and dispatches
* when the current reply finishes.
* 4. Chat thread session cache: (workspace, session) messages seed instantly
* on remount then refresh silently; a transient refresh failure keeps the
* cached paint (no re-skeleton, no wipe).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act, render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { ChatMessage } from '@/lib/types';
import {
chatThreadCacheKey,
readChatThreadCache,
writeChatThreadCache,
clearChatThreadCache,
} from '@/hooks/chat-thread-cache';
// jsdom lacks ResizeObserver (ChatApp's agent strip observes its own width).
class ResizeObserverStub {
observe() {}
unobserve() {}
disconnect() {}
}
(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = ResizeObserverStub;
const mocks = vi.hoisted(() => ({
adapter: {
getHistory: vi.fn().mockResolvedValue([]),
sendMessage: vi.fn(),
clearHistory: vi.fn().mockResolvedValue(undefined),
respondApproval: vi.fn().mockResolvedValue(undefined),
// ChatApp mount side-effects
getPins: vi.fn().mockResolvedValue([]),
searchMemory: vi.fn().mockResolvedValue([]),
submitFeedback: vi.fn(),
ingestFile: vi.fn(),
addPin: vi.fn(),
removePin: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
function deferred<T = unknown>() {
let resolve!: (v: T) => void;
let reject!: (e: unknown) => void;
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
return { promise, resolve, reject };
}
beforeEach(() => {
vi.clearAllMocks();
mocks.adapter.getHistory.mockResolvedValue([]);
clearChatThreadCache();
});
afterEach(() => { cleanup(); });
// ── chat-thread-cache (the module, mirrors memory-list-cache) ───────────────
describe('chat-thread-cache module', () => {
it('keys by (workspace, session) and round-trips a list; clear resets', () => {
const key = chatThreadCacheKey('ws-1', 'sess-1');
expect(key).toBe('ws-1|sess-1');
expect(readChatThreadCache(key)).toBeUndefined();
const msgs: ChatMessage[] = [{ id: 'a', role: 'user', content: 'hi', timestamp: 'now' }];
writeChatThreadCache(key, msgs);
expect(readChatThreadCache(key)).toBe(msgs);
// Distinct session → distinct slot.
expect(readChatThreadCache(chatThreadCacheKey('ws-1', 'sess-2'))).toBeUndefined();
clearChatThreadCache();
expect(readChatThreadCache(key)).toBeUndefined();
});
});
// ── useChat send queue (contracts 1 + 2) ────────────────────────────────────
describe('useChat — send queue (never locks, never drops)', () => {
async function mountChat(sessionId = 'sess-1') {
const { useChat } = await import('@/hooks/useChat');
const hook = renderHook(() => useChat({ workspaceId: 'ws-1', sessionId }));
// Let the mount-time history fetch settle to [].
await act(async () => { await Promise.resolve(); });
return hook;
}
it('a send fired while the reply streams is QUEUED, then dispatched on ready', async () => {
const gate = deferred<void>();
mocks.adapter.sendMessage
.mockImplementationOnce(async function* () {
await gate.promise; // hold the first reply open
yield { type: 'done', data: { content: 'A-reply' } };
})
.mockImplementationOnce(async function* () {
yield { type: 'done', data: { content: 'B-reply' } };
});
const { result } = await mountChat();
// Start the first send but DO NOT await its completion (gated open).
let firstPromise: Promise<boolean> | undefined;
await act(async () => {
firstPromise = result.current.sendMessage('first');
await Promise.resolve();
});
// The first reply is in flight (one stream opened, still streaming).
expect(mocks.adapter.sendMessage).toHaveBeenCalledTimes(1);
// Send a SECOND while the first still streams → queued, NOT a 2nd stream.
await act(async () => { await result.current.sendMessage('second'); });
expect(mocks.adapter.sendMessage).toHaveBeenCalledTimes(1);
const queued = result.current.messages.find(m => m.content === 'second');
expect(queued?.queued).toBe(true); // truthful "waiting" marker on the optimistic turn
// Release the first reply → its completion flushes the queue → second dispatches.
await act(async () => {
gate.resolve();
await firstPromise;
await new Promise(r => setTimeout(r, 0));
});
expect(mocks.adapter.sendMessage).toHaveBeenCalledTimes(2);
const secondNow = result.current.messages.find(m => m.content === 'second');
expect(secondNow?.queued).toBeFalsy(); // promoted, no longer "waiting"
// Both replies landed, in order, none dropped.
const texts = result.current.messages.filter(m => m.role === 'assistant').map(m => m.content);
expect(texts).toContain('A-reply');
expect(texts).toContain('B-reply');
const users = result.current.messages.filter(m => m.role === 'user').map(m => m.content);
expect(users).toEqual(['first', 'second']);
});
it('does NOT spawn a concurrent stream — the queued send waits for the in-flight one', async () => {
const gate = deferred<void>();
mocks.adapter.sendMessage
.mockImplementationOnce(async function* () { await gate.promise; yield { type: 'done', data: { content: 'A' } }; })
.mockImplementationOnce(async function* () { yield { type: 'done', data: { content: 'B' } }; });
const { result } = await mountChat('sess-concurrent');
let firstPromise: Promise<boolean> | undefined;
await act(async () => { firstPromise = result.current.sendMessage('one'); await Promise.resolve(); });
// Two more sends while streaming — both queued behind the one in-flight stream.
await act(async () => { await result.current.sendMessage('two'); });
await act(async () => { await result.current.sendMessage('three'); });
expect(mocks.adapter.sendMessage).toHaveBeenCalledTimes(1); // still ONE stream
await act(async () => {
gate.resolve();
await firstPromise;
await new Promise(r => setTimeout(r, 0));
});
// FIFO flush dispatched the two queued sends after the first finished.
expect(mocks.adapter.sendMessage).toHaveBeenCalledTimes(3);
const users = result.current.messages.filter(m => m.role === 'user').map(m => m.content);
expect(users).toEqual(['one', 'two', 'three']);
});
});
// ── useChat thread cache (contract 4) ───────────────────────────────────────
describe('useChat — thread session cache (2.6-chat)', () => {
it('seeds instantly from cache before history resolves (no re-skeleton on return)', async () => {
const key = chatThreadCacheKey('ws-1', 'sess-seed');
const cachedMsg: ChatMessage = { id: 'c1', role: 'user', content: 'from cache', timestamp: 'now' };
writeChatThreadCache(key, [cachedMsg]);
const gate = deferred<ChatMessage[]>();
mocks.adapter.getHistory.mockReturnValueOnce(gate.promise);
const { useChat } = await import('@/hooks/useChat');
const { result } = renderHook(() => useChat({ workspaceId: 'ws-1', sessionId: 'sess-seed' }));
await act(async () => { await Promise.resolve(); });
// Painted from cache WHILE history is still in flight.
expect(result.current.messages).toHaveLength(1);
expect(result.current.messages[0].content).toBe('from cache');
// Silent refresh replaces with the server truth.
await act(async () => { gate.resolve([]); await Promise.resolve(); });
expect(result.current.messages).toHaveLength(0);
});
it('keeps the cached paint when the history refresh fails (no wipe)', async () => {
const key = chatThreadCacheKey('ws-1', 'sess-fail');
writeChatThreadCache(key, [{ id: 'c1', role: 'user', content: 'cached', timestamp: 'now' }]);
mocks.adapter.getHistory.mockRejectedValueOnce(new Error('offline'));
const { useChat } = await import('@/hooks/useChat');
const { result } = renderHook(() => useChat({ workspaceId: 'ws-1', sessionId: 'sess-fail' }));
await act(async () => { await Promise.resolve(); await Promise.resolve(); });
expect(result.current.messages).toHaveLength(1);
expect(result.current.messages[0].content).toBe('cached');
});
it('writes the settled thread to cache after a clean send', async () => {
mocks.adapter.sendMessage.mockImplementationOnce(async function* () {
yield { type: 'done', data: { content: 'answer' } };
});
const { useChat } = await import('@/hooks/useChat');
const { result } = renderHook(() => useChat({ workspaceId: 'ws-1', sessionId: 'sess-write' }));
await act(async () => { await Promise.resolve(); });
await act(async () => { await result.current.sendMessage('question'); });
const cached = readChatThreadCache(chatThreadCacheKey('ws-1', 'sess-write'));
expect(cached).toBeDefined();
expect(cached!.some(m => m.role === 'user' && m.content === 'question')).toBe(true);
expect(cached!.some(m => m.role === 'assistant' && m.content === 'answer')).toBe(true);
// Settled thread has no `queued` turns.
expect(cached!.some(m => m.queued)).toBe(false);
});
});
// ── ChatApp composer surface (contracts 1a + 2 + queued paint) ──────────────
describe('ChatApp — composer input primacy', () => {
const noop = () => {};
const baseProps = {
messages: [] as ChatMessage[],
isLoading: false,
onSendMessage: noop,
onClearHistory: noop,
pendingApproval: null,
onApprove: noop,
activeSessionId: null as string | null,
historyLoaded: false,
initialMessage: undefined as string | undefined,
autoSendInitial: false,
};
const renderChat = (props: Partial<typeof baseProps> & { messages: ChatMessage[] }) =>
render(<TooltipProvider><ChatAppEl {...baseProps} {...props} /></TooltipProvider>);
// Late import so the adapter mock is installed first.
let ChatAppEl: typeof import('@/components/os/apps/ChatApp').default;
beforeEach(async () => { ChatAppEl = (await import('@/components/os/apps/ChatApp')).default; });
const assistantMsg: ChatMessage = { id: 'm1', role: 'assistant', content: 'Answer.', timestamp: 'now' };
it('the composer textarea is ENABLED at paint (not gated behind loading)', () => {
renderChat({ messages: [] });
expect(screen.getByRole('textbox')).not.toBeDisabled();
});
it('names the composer textarea for assistive tech and browser metadata', () => {
renderChat({ messages: [] });
const composer = screen.getByRole('textbox', { name: /message composer/i });
expect(composer).toHaveAttribute('name', 'message');
expect(composer).toHaveAttribute('autocomplete', 'off');
expect(composer.className).toContain('focus-visible:ring-2');
expect(composer.className).toContain('focus-visible:ring-[var(--focus-ring)]');
});
it('the textarea stays enabled even while a reply streams (isLoading)', () => {
renderChat({ messages: [assistantMsg], isLoading: true });
expect(screen.getByRole('textbox')).not.toBeDisabled();
});
it('send is NOT locked while a reply streams — text present + isLoading enables send', () => {
renderChat({ messages: [assistantMsg], isLoading: true });
fireEvent.change(screen.getByRole('textbox'), { target: { value: 'next message' } });
expect(screen.getByRole('button', { name: 'Send' })).not.toBeDisabled();
});
it('renders the truthful "waiting to send" state on a queued optimistic turn', () => {
const queuedMsg: ChatMessage = { id: 'q1', role: 'user', content: 'queued one', timestamp: 'now', queued: true };
renderChat({ messages: [assistantMsg, queuedMsg] });
const badge = screen.getByTestId('chat-msg-queued');
expect(badge).toBeInTheDocument();
expect(badge.textContent).toContain('Waiting to send');
});
it('clears an auto-sent first task before the send promise resolves', async () => {
const gate = deferred<boolean | void>();
const onSendMessage = vi.fn(() => gate.promise);
renderChat({
messages: [],
activeSessionId: 'sess-first-task',
historyLoaded: true,
initialMessage: 'Draft my launch checklist',
autoSendInitial: true,
onSendMessage,
});
await waitFor(() => expect(onSendMessage).toHaveBeenCalledWith('Draft my launch checklist'));
expect(screen.getByRole('textbox', { name: /message composer/i })).toHaveValue('');
gate.resolve(true);
});
});

View File

@@ -0,0 +1,217 @@
/**
* Lane H — home cache-first paint + silent-refresh reconciliation + one
* briefing truth (Path-to-9 Pillar 2.1–2.4).
*
* These are the TESTED contracts of the pillar's heart:
* - item 1: a warm disk cache paints content immediately (no skeleton), then
* refreshes silently; a refresh failure keeps the last-good content.
* - item 2: fresh data over a cache-first paint does NOT remount above-the-fold
* elements (key stability) and the changed count carries the delta-pulse class.
* - item 3: the hero workspace count === the modal workspace count from ONE mock.
* - item 4: the recall "I remember" strip renders INSIDE the home hero.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, cleanup, act } from '@testing-library/react';
import { resetBriefingSource } from '@/lib/briefing-source';
import { writeHomeCache, clearHomeCache } from '@/lib/home-cache';
import { workspaceCounts } from '@/lib/workspace-counts';
import type { HomeBriefing, RecentWorkspaceCard } from '@/lib/types';
const mocks = vi.hoisted(() => ({
adapter: {
getHomeBriefing: vi.fn(),
getHomeOvernight: vi.fn(),
quickCapture: vi.fn(),
getWorkspaces: vi.fn(),
searchMemory: vi.fn(),
getMemoryStats: vi.fn(),
getWorkspaceContext: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/providers/ServiceProvider', () => ({
useService: () => ({ connecting: false, connected: true }),
ServiceProvider: ({ children }: { children: React.ReactNode }) => children,
}));
vi.mock('@/hooks/useOfflineStatus', () => ({ useOfflineStatus: () => false }));
vi.mock('@/providers/ShellContext', () => ({
useShell: () => ({ patchWorkspace: vi.fn().mockResolvedValue(true), deleteWorkspace: vi.fn().mockResolvedValue(true) }),
}));
function wsCard(id: string, name: string, pendingCount = 0): RecentWorkspaceCard {
return { id, name, group: 'Personal', lastActive: '2026-07-06T09:00:00.000Z', pendingCount };
}
function makeBriefing(over: Partial<HomeBriefing> = {}): HomeBriefing {
return {
greeting: 'Welcome back, Marko',
date: '2026-07-07T08:00:00.000Z',
recentWorkspaces: [],
suggestedActions: [],
upNext: [],
isFirstRun: false,
needsReviewCount: 0,
...over,
};
}
beforeEach(() => {
clearHomeCache();
resetBriefingSource();
window.localStorage.clear();
vi.clearAllMocks();
});
afterEach(() => { cleanup(); });
async function importHome() {
return (await import('@/components/os/apps/HomeCockpit')).default;
}
describe('HomeCockpit cache-first paint + reconciliation (Lane H items 1-2)', () => {
it('a warm cache paints content immediately (no skeleton) and reconciles a changed count in place, with the delta-pulse marker', async () => {
const HomeCockpit = await importHome();
// Disk cache: 1 workspace.
writeHomeCache({
briefing: makeBriefing({ recentWorkspaces: [wsCard('w1', 'Alpha')] }),
overnight: null,
highlights: [{ content: 'Cached: we chose SQLite for the local store.', timestamp: '2026-07-06T09:00:00.000Z' }],
});
// Fresh server briefing: 3 workspaces (count changes 1 → 3).
mocks.adapter.getHomeBriefing.mockResolvedValue(makeBriefing({
recentWorkspaces: [wsCard('w1', 'Alpha'), wsCard('w2', 'Bravo'), wsCard('w3', 'Charlie')],
}));
mocks.adapter.getHomeOvernight.mockResolvedValue(null);
// Recall fetch is best-effort; keep it inert.
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.searchMemory.mockResolvedValue([]);
mocks.adapter.getMemoryStats.mockResolvedValue(null);
render(<HomeCockpit onContinue={vi.fn()} onOpenWorkspaceDesktop={vi.fn()} onCreateWorkspace={vi.fn()} />);
// Cache-first: content is up on the first paint, no skeleton.
expect(screen.queryByTestId('home-cockpit-loading')).toBeNull();
const factsBefore = screen.getByTestId('home-cockpit-facts');
expect(factsBefore.textContent).toContain('1 workspace');
// Silent refresh lands the fresh count in the SAME node.
await waitFor(() => expect(screen.getByTestId('home-cockpit-facts').textContent).toContain('3 workspaces'));
const factsAfter = screen.getByTestId('home-cockpit-facts');
expect(factsAfter).toBe(factsBefore); // no above-the-fold remount (key stability)
// The changed count carries the delta-pulse marker class.
await waitFor(() => {
const pulsed = factsAfter.querySelector('.home-delta-pulse');
expect(pulsed?.textContent).toBe('3');
});
});
it('a silent-refresh FAILURE over a cache-first paint keeps the last-good content (no error flash)', async () => {
const HomeCockpit = await importHome();
writeHomeCache({
briefing: makeBriefing({ recentWorkspaces: [wsCard('w1', 'Alpha')] }),
overnight: null,
highlights: [],
});
mocks.adapter.getHomeBriefing.mockRejectedValue(new Error('network down'));
render(<HomeCockpit onContinue={vi.fn()} onOpenWorkspaceDesktop={vi.fn()} onCreateWorkspace={vi.fn()} />);
expect(screen.getByTestId('home-cockpit')).toBeTruthy();
await waitFor(() => expect(mocks.adapter.getHomeBriefing).toHaveBeenCalled());
await act(async () => { await Promise.resolve(); });
// Content persists; the cold error/permission surfaces never appear.
expect(screen.queryByTestId('home-cockpit-error')).toBeNull();
expect(screen.queryByTestId('home-cockpit-permission-denied')).toBeNull();
expect(screen.getByTestId('home-cockpit')).toBeTruthy();
expect(screen.getByTestId('home-cockpit-facts').textContent).toContain('1 workspace');
});
it('cold (no cache): shows the skeleton first, then content', async () => {
const HomeCockpit = await importHome();
mocks.adapter.getHomeBriefing.mockResolvedValue(makeBriefing({ recentWorkspaces: [wsCard('w1', 'Alpha')] }));
mocks.adapter.getHomeOvernight.mockResolvedValue(null);
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.searchMemory.mockResolvedValue([]);
mocks.adapter.getMemoryStats.mockResolvedValue(null);
render(<HomeCockpit onContinue={vi.fn()} onOpenWorkspaceDesktop={vi.fn()} onCreateWorkspace={vi.fn()} />);
// No cache → the skeleton is the first paint.
expect(screen.getByTestId('home-cockpit-loading')).toBeTruthy();
await waitFor(() => expect(screen.getByTestId('home-cockpit')).toBeTruthy());
});
});
describe('HomeCockpit recall strip (Lane H item 4 — double catch-up collapse)', () => {
it('renders the "I remember" recall cards INSIDE the home hero', async () => {
const HomeCockpit = await importHome();
mocks.adapter.getHomeBriefing.mockResolvedValue(makeBriefing({ recentWorkspaces: [wsCard('w1', 'Alpha')] }));
mocks.adapter.getHomeOvernight.mockResolvedValue(null);
mocks.adapter.getWorkspaces.mockResolvedValue([
{ id: 'w1', name: 'Alpha', group: 'Personal', status: 'active', lastActive: '2026-07-06T09:00:00.000Z' },
]);
mocks.adapter.searchMemory.mockResolvedValue([
{ content: 'We decided to prioritise compliance over speed for the launch.', importance: 'important', timestamp: '2026-07-06T09:00:00.000Z' },
]);
mocks.adapter.getMemoryStats.mockResolvedValue(null);
mocks.adapter.getWorkspaceContext.mockResolvedValue({ stats: { memoryCount: 5, sessionCount: 2 }, summary: 'launch prep', pendingTasks: [] });
render(<HomeCockpit onContinue={vi.fn()} onOpenWorkspaceDesktop={vi.fn()} onCreateWorkspace={vi.fn()} />);
await waitFor(() => expect(screen.getByTestId('home-cockpit')).toBeTruthy());
await waitFor(() => {
const strip = screen.getByTestId('home-cockpit-recall');
expect(strip.textContent).toContain('I remember');
expect(strip.textContent).toContain('prioritise compliance');
});
});
});
describe('one briefing truth (Lane H item 3)', () => {
// 6 active + 2 archived + 1 dev-noise → workspaceCounts().visible === 6 (the
// exact Wave U fixture). total.frames:0 forces the modal brag line to state the
// workspace count so the two surfaces can be compared.
const WORKSPACES = [
{ id: 'w1', name: 'Alpha', group: 'Personal', status: 'active' as const },
{ id: 'w2', name: 'Bravo', group: 'Personal', status: 'active' as const },
{ id: 'w3', name: 'Charlie', group: 'Personal', status: 'active' as const },
{ id: 'w4', name: 'Delta', group: 'Personal', status: 'active' as const },
{ id: 'w5', name: 'Echo', group: 'Personal', status: 'active' as const },
{ id: 'w6', name: 'Foxtrot', group: 'Personal', status: 'active' as const },
{ id: 'a1', name: 'ArchivedOne', group: 'Personal', status: 'archived' as const },
{ id: 'a2', name: 'ArchivedTwo', group: 'Personal', status: 'archived' as const },
{ id: 'n1', name: 'test-noise', group: 'Personal', status: 'active' as const },
];
it('the hero count and the modal count are the SAME number from one workspaces mock', async () => {
const HomeCockpit = await importHome();
const { default: LoginBriefing } = await import('@/components/os/overlays/LoginBriefing');
const { TooltipProvider } = await import('@/components/ui/tooltip');
mocks.adapter.getWorkspaces.mockResolvedValue(WORKSPACES);
mocks.adapter.searchMemory.mockResolvedValue([]);
mocks.adapter.getMemoryStats.mockResolvedValue({ total: { frames: 0, entities: 0, relations: 0 } });
mocks.adapter.getWorkspaceContext.mockResolvedValue({ stats: { memoryCount: 0, sessionCount: 0 } });
mocks.adapter.getHomeBriefing.mockResolvedValue(makeBriefing({ recentWorkspaces: [] }));
mocks.adapter.getHomeOvernight.mockResolvedValue(null);
const visible = workspaceCounts(WORKSPACES).visible;
expect(visible).toBe(6);
// Hero — HomeRoute passes workspaceCounts(workspaces).visible as totalWorkspaceCount.
render(<HomeCockpit onContinue={vi.fn()} onOpenWorkspaceDesktop={vi.fn()} onCreateWorkspace={vi.fn()} totalWorkspaceCount={visible} />);
const facts = await screen.findByTestId('home-cockpit-facts');
await waitFor(() => expect(facts.textContent).toMatch(/\d+\s+workspaces?/));
const heroCount = Number(/(\d+)\s+workspaces?/.exec(facts.textContent ?? '')?.[1]);
// Modal — reads briefing-source getWorkspaces → the SAME visible count.
resetBriefingSource();
render(<TooltipProvider><LoginBriefing onDismiss={vi.fn()} onOpenWorkspace={vi.fn()} /></TooltipProvider>);
const bragLine = await screen.findByTestId('login-briefing-brag-line');
await waitFor(() => expect(bragLine.textContent).toContain('across'));
const modalCount = Number(/across\s+(\d+)\s+workspaces?/.exec(bragLine.textContent ?? '')?.[1]);
expect(heroCount).toBe(visible);
expect(modalCount).toBe(visible);
expect(heroCount).toBe(modalCount); // the number-drift bug class is dead
});
});

View File

@@ -0,0 +1,273 @@
/**
* Lane HM (path-to-9 Pillar 1.1) — hero shared-element morphs.
*
* Two morph cases, one contract: a SOURCE element and a DESTINATION element
* carry the SAME framer `layoutId`, so the element animates between them on
* route change (the card GROWS into the workspace surface). This suite pins:
*
* 1. the card→workspace pair — the shelf card's hex avatar + name and the
* workspace header's avatar + name resolve to identical layoutIds
* (`ws-hero-avatar-<id>` / `ws-hero-name-<id>`), the whole reason the morph
* lands rather than silently no-op'ing on a string mismatch;
* 2. the morph target is mounted at route commit — the workspace LOADING
* skeleton already carries the hero layoutIds (context lands async; without
* this the destination wouldn't exist when framer looks for it);
* 3. reduced motion drops every shared-element id (REDUCED.routeTransition =
* crossfade-only — no shared-element travel) on BOTH ends;
* 4. interruptibility — opening a card fires navigation synchronously, never
* gated on an animation (Phase-0.4 input-primacy);
* 5. the Trust↔Memories tab morph — the panel body animates on view change and
* degrades to an instant swap (initial=false) under reduced motion.
*
* framer-motion is stubbed to plain DOM: `layoutId` surfaces as `data-layout-id`
* and `initial` as `data-initial`, so both the morph wiring and the
* reduced-motion degradation are assertable without a real layout engine.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, cleanup, fireEvent } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
import { workspaceHeroAvatarId, workspaceHeroNameId } from '@/lib/motion/hero-morph';
const h = vi.hoisted(() => ({ reduce: false }));
vi.mock('framer-motion', async () => {
const React = await vi.importActual<typeof import('react')>('react');
const DROP = new Set([
'initial', 'animate', 'exit', 'transition', 'variants',
'whileHover', 'whileTap', 'whileFocus', 'whileInView',
'layout', 'layoutId', 'onAnimationComplete', 'custom',
]);
const make = (tag: string) =>
React.forwardRef(function MotionMock(props: Record<string, unknown>, ref: React.Ref<HTMLElement>) {
const passed: Record<string, unknown> = {};
for (const k of Object.keys(props)) if (!DROP.has(k)) passed[k] = props[k];
// Surface the two props the morph contract depends on.
if (props.layoutId !== undefined) passed['data-layout-id'] = props.layoutId;
if (props.initial !== undefined) passed['data-initial'] = JSON.stringify(props.initial);
return React.createElement(tag, { ...passed, ref });
});
const motion = new Proxy({}, { get: (_t, tag: string) => make(tag) });
return {
__esModule: true,
motion,
AnimatePresence: ({ children }: { children: React.ReactNode }) =>
React.createElement(React.Fragment, null, children),
LayoutGroup: ({ children }: { children: React.ReactNode }) =>
React.createElement(React.Fragment, null, children),
useReducedMotion: () => h.reduce,
};
});
// ── Shared mocks ───────────────────────────────────────────────────────────
const mocks = vi.hoisted(() => ({
shell: {
workspaces: [{ id: 'w1', name: 'Alpha' }, { id: 'w2', name: 'Beta' }] as Array<{ id: string; name: string }>,
workspacesError: null as unknown,
workspacesLoading: false,
selectWorkspace: vi.fn(),
createWorkspace: vi.fn(),
refreshWorkspaces: vi.fn(),
billingTier: 'FREE' as string,
tierResolved: true,
activeWorkspaceId: 'w1' as string | null,
setContextRailTarget: vi.fn(),
},
adapter: {
getWorkspaceContext: vi.fn(),
getWorkspaceState: vi.fn(),
getWorkspaceActivity: vi.fn(),
getTeamMembers: vi.fn(),
getWorkspaceFiles: vi.fn(),
uploadFile: vi.fn(),
},
}));
vi.mock('@/providers/ShellContext', () => ({ useShell: () => mocks.shell }));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/hooks/useRoomState', () => ({ useRoomState: () => ({ workspaceMap: new Map() }) }));
vi.mock('@/hooks/useOnboarding', () => ({ useOnboarding: () => ({ state: { completed: true } }) }));
// Heavy children the morph surfaces don't need — stubbed to keep the tree light.
vi.mock('@/components/os/WorkspaceActionsMenu', () => ({ default: () => <div data-testid="stub-actions" /> }));
vi.mock('@/components/os/overlays/CreateWorkspaceDialog', () => ({ default: () => null }));
vi.mock('@/components/os/apps/workspace/TasksTab', () => ({ default: () => <div data-testid="stub-tasks" /> }));
vi.mock('@/components/os/apps/MemoryTrust', () => ({ default: () => <div data-testid="stub-trust" /> }));
vi.mock('@/components/os/apps/memory/MemoryCenterTab', () => ({ default: () => <div data-testid="stub-mc-tab" /> }));
vi.mock('@/components/os/apps/memory/TimelineTab', () => ({ default: () => <div data-testid="stub-timeline" /> }));
vi.mock('@/components/os/apps/memory/KnowledgeGraphViewer', () => ({ default: () => <div data-testid="stub-graph" /> }));
vi.mock('@/components/os/apps/memory/HarvestTab', () => ({ default: () => <div data-testid="stub-harvest" /> }));
vi.mock('@/components/os/apps/memory/WeaverPanel', () => ({ default: () => <div data-testid="stub-weaver" /> }));
vi.mock('@/components/os/apps/memory/WikiTab', () => ({ default: () => <div data-testid="stub-wiki" /> }));
vi.mock('@/components/os/apps/memory/EvolutionTab', () => ({ default: () => <div data-testid="stub-evolution" /> }));
vi.mock('@/components/os/apps/memory/ImportReminderBanner', () => ({ default: () => null }));
const timelineProps = {
frames: [], selectedFrame: null, onSelectFrame: vi.fn(),
searchQuery: '', onSearchChange: vi.fn(), onDeleteFrame: vi.fn(),
loading: false, error: null, stats: { total: 0, filtered: 0 },
typeFilters: [], onTypeFiltersChange: vi.fn(),
minImportance: 0, onMinImportanceChange: vi.fn(),
};
beforeEach(() => {
h.reduce = false;
vi.clearAllMocks();
mocks.shell.workspaces = [{ id: 'w1', name: 'Alpha' }, { id: 'w2', name: 'Beta' }];
mocks.shell.workspacesError = null;
mocks.shell.workspacesLoading = false;
});
afterEach(() => cleanup());
// ── 1. The id contract ──────────────────────────────────────────────────────
describe('Lane HM · layoutId contract', () => {
it('source and destination derive the SAME id from a workspace id', () => {
expect(workspaceHeroAvatarId('w1')).toBe('ws-hero-avatar-w1');
expect(workspaceHeroNameId('w1')).toBe('ws-hero-name-w1');
});
});
// ── 2. Source: the shelf card ────────────────────────────────────────────────
describe('Lane HM · workspace card (source)', () => {
it('the card hex avatar + name carry the hero layoutIds', async () => {
const { default: AllWorkspacesApp } = await import('@/components/os/apps/AllWorkspacesApp');
const { container } = render(<AllWorkspacesApp onOpenWorkspace={vi.fn()} />);
// Avatar (decorative span) carries the avatar id…
expect(container.querySelector(`[data-layout-id="${workspaceHeroAvatarId('w1')}"]`)).toBeTruthy();
// …and the name (the accessible heading) carries the name id.
const name = screen.getByTestId('all-workspaces-open-w1');
expect(name.getAttribute('data-layout-id')).toBe(workspaceHeroNameId('w1'));
expect(name.textContent).toBe('Alpha');
});
it('reduced motion drops the card layoutIds (no shared-element travel)', async () => {
h.reduce = true;
const { default: AllWorkspacesApp } = await import('@/components/os/apps/AllWorkspacesApp');
const { container } = render(<AllWorkspacesApp onOpenWorkspace={vi.fn()} />);
expect(container.querySelector('[data-layout-id]')).toBeNull();
// The card + name still render — only the morph is gone.
expect(screen.getByTestId('all-workspaces-open-w1').textContent).toBe('Alpha');
});
it('opening a card navigates SYNCHRONOUSLY — never gated on an animation', async () => {
const onOpen = vi.fn();
const { default: AllWorkspacesApp } = await import('@/components/os/apps/AllWorkspacesApp');
render(<AllWorkspacesApp onOpenWorkspace={onOpen} />);
fireEvent.click(screen.getByTestId('all-workspaces-card-w1'));
// fireEvent is synchronous: if navigation were awaiting an exit animation
// these would not have fired by now.
expect(mocks.shell.selectWorkspace).toHaveBeenCalledWith('w1');
expect(onOpen).toHaveBeenCalledWith('w1');
});
});
// ── 3. Destination: the workspace surface ────────────────────────────────────
describe('Lane HM · workspace surface (destination)', () => {
const okCtx = {
workspace: { id: 'w1', name: 'Alpha', group: 'Personal', status: 'active' },
stats: { memoryCount: 2, sessionCount: 1, fileCount: 0 },
recentMemories: [{ content: 'x', date: new Date().toISOString() }],
};
it('the loaded header avatar + name carry the MATCHING layoutIds', async () => {
mocks.adapter.getWorkspaceContext.mockResolvedValue(okCtx);
mocks.adapter.getWorkspaceState.mockResolvedValue({ pending: [], blocked: [] });
mocks.adapter.getWorkspaceActivity.mockResolvedValue({ events: [] });
mocks.adapter.getTeamMembers.mockResolvedValue([]);
mocks.adapter.getWorkspaceFiles.mockResolvedValue([]);
const { default: WorkspaceDesktopApp } = await import('@/components/os/apps/WorkspaceDesktopApp');
const { container } = render(<WorkspaceDesktopApp workspaceId="w1" workspaceName="Alpha" />);
await waitFor(() => expect(screen.getByTestId('ws-desktop-root')).toBeTruthy());
const avatar = container.querySelector(`[data-layout-id="${workspaceHeroAvatarId('w1')}"]`);
const name = container.querySelector(`[data-layout-id="${workspaceHeroNameId('w1')}"]`);
expect(avatar).toBeTruthy();
expect(name?.textContent).toBe('Alpha');
});
it('the LOADING skeleton already carries the hero ids (target mounted at commit)', async () => {
// Context never resolves → the surface stays in its loading skeleton.
mocks.adapter.getWorkspaceContext.mockReturnValue(new Promise(() => {}));
const { default: WorkspaceDesktopApp } = await import('@/components/os/apps/WorkspaceDesktopApp');
const { container } = render(<WorkspaceDesktopApp workspaceId="w1" workspaceName="Alpha" />);
expect(screen.getByTestId('ws-desktop-loading')).toBeTruthy();
// The morph target exists while data is still loading.
expect(container.querySelector(`[data-layout-id="${workspaceHeroAvatarId('w1')}"]`)).toBeTruthy();
const name = container.querySelector(`[data-layout-id="${workspaceHeroNameId('w1')}"]`);
expect(name?.textContent).toBe('Alpha');
});
it('reduced motion drops the header layoutIds', async () => {
h.reduce = true;
mocks.adapter.getWorkspaceContext.mockResolvedValue(okCtx);
mocks.adapter.getWorkspaceState.mockResolvedValue({ pending: [], blocked: [] });
mocks.adapter.getWorkspaceActivity.mockResolvedValue({ events: [] });
mocks.adapter.getTeamMembers.mockResolvedValue([]);
mocks.adapter.getWorkspaceFiles.mockResolvedValue([]);
const { default: WorkspaceDesktopApp } = await import('@/components/os/apps/WorkspaceDesktopApp');
const { container } = render(<WorkspaceDesktopApp workspaceId="w1" workspaceName="Alpha" />);
await waitFor(() => expect(screen.getByTestId('ws-desktop-root')).toBeTruthy());
expect(container.querySelector('[data-layout-id]')).toBeNull();
// The name still renders — just no morph.
expect(screen.getByRole('heading', { level: 2, name: 'Alpha' })).toBeTruthy();
});
});
// ── 4. Trust↔Memories tab morph ──────────────────────────────────────────────
describe('Lane HM · Trust↔Memories tab morph', () => {
async function renderMemory(view: 'trust' | 'memories', reduce = false) {
h.reduce = reduce;
const { default: MemoryCenterApp } = await import('@/components/os/apps/MemoryCenterApp');
return render(
<TooltipProvider>
<MemoryCenterApp
mind="personal"
onMindChange={vi.fn()}
view={view}
onViewChange={vi.fn()}
workspaceId="w1"
workspaceName="Alpha"
timeline={timelineProps}
/>
</TooltipProvider>,
);
}
it('the panel body is wrapped in the morph container on both views', async () => {
const { rerender } = await renderMemory('trust');
const panel = screen.getByTestId('memory-view-panel');
expect(panel).toBeTruthy();
expect(panel.querySelector('[data-testid="stub-trust"]')).toBeTruthy();
const { default: MemoryCenterApp } = await import('@/components/os/apps/MemoryCenterApp');
rerender(
<TooltipProvider>
<MemoryCenterApp
mind="personal" onMindChange={vi.fn()} view="memories" onViewChange={vi.fn()}
workspaceId="w1" workspaceName="Alpha" timeline={timelineProps}
/>
</TooltipProvider>,
);
const panel2 = screen.getByTestId('memory-view-panel');
expect(panel2.querySelector('[data-testid="stub-mc-tab"]')).toBeTruthy();
// Exactly one panel — no dual-mount hard-cut leak.
expect(screen.getAllByTestId('memory-view-panel')).toHaveLength(1);
});
it('animates on view change but swaps INSTANTLY under reduced motion', async () => {
const { unmount } = await renderMemory('trust', false);
expect(screen.getByTestId('memory-view-panel').getAttribute('data-initial')).not.toBe('false');
unmount();
await renderMemory('trust', true);
// Reduced motion → initial disabled (instant swap, no settle).
expect(screen.getByTestId('memory-view-panel').getAttribute('data-initial')).toBe('false');
});
});

View File

@@ -0,0 +1,219 @@
/**
* Lane S2 — streaming interaction contract
* (Path-to-9 Phase C · Pillar 3.1: input-primacy applied to the stream).
*
* Contracts as TESTS (spec §Lane S2):
* 1. Auto-follow pins the viewport to the newest content while streaming; a
* user scroll-up breaks auto-follow INSTANTLY and surfaces a "Jump to
* latest" affordance; clicking it re-pins.
* 2. A visible Stop control halts the in-flight reply immediately: the
* useChat abort/cancel path fires, the partial answer stays, and the
* composer returns to send (Stop only shows while streaming).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act, render, screen, fireEvent, cleanup } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { ChatMessage } from '@/lib/types';
// jsdom lacks ResizeObserver (ChatApp's agent strip observes its own width).
class ResizeObserverStub {
observe() {}
unobserve() {}
disconnect() {}
}
(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = ResizeObserverStub;
const mocks = vi.hoisted(() => ({
adapter: {
getHistory: vi.fn().mockResolvedValue([]),
sendMessage: vi.fn(),
abortAgent: vi.fn().mockResolvedValue(undefined),
clearHistory: vi.fn().mockResolvedValue(undefined),
respondApproval: vi.fn().mockResolvedValue(undefined),
// ChatApp mount side-effects
getPins: vi.fn().mockResolvedValue([]),
searchMemory: vi.fn().mockResolvedValue([]),
submitFeedback: vi.fn(),
ingestFile: vi.fn(),
addPin: vi.fn(),
removePin: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
function deferred<T = unknown>() {
let resolve!: (v: T) => void;
let reject!: (e: unknown) => void;
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
return { promise, resolve, reject };
}
const flush = () => new Promise((r) => setTimeout(r, 0));
beforeEach(() => {
vi.clearAllMocks();
mocks.adapter.getHistory.mockResolvedValue([]);
mocks.adapter.abortAgent.mockResolvedValue(undefined);
mocks.adapter.getPins.mockResolvedValue([]);
mocks.adapter.searchMemory.mockResolvedValue([]);
});
afterEach(() => { cleanup(); });
// ── useChat.stopStreaming (contract 2, the hook side) ───────────────────────
describe('useChat — stopStreaming (halt in-flight, keep partial, re-enable send)', () => {
async function mountChat(sessionId = 'sess-1') {
const { useChat } = await import('@/hooks/useChat');
const hook = renderHook(() => useChat({ workspaceId: 'ws-1', sessionId }));
await act(async () => { await Promise.resolve(); });
return hook;
}
it('aborts the stream, keeps the partial answer, flips isLoading off, and calls the server cancel', async () => {
const gate = deferred<void>();
mocks.adapter.sendMessage.mockImplementationOnce(async function* () {
yield { type: 'token', data: { content: 'partial answer' } };
await gate.promise; // hold the stream open until (never) released
yield { type: 'done', data: {} };
});
const { result } = await mountChat();
// Start the send; let the first token land, then leave the stream in-flight.
let firstPromise: Promise<boolean> | undefined;
await act(async () => {
firstPromise = result.current.sendMessage('question');
await flush();
});
expect(result.current.isLoading).toBe(true);
const streaming = result.current.messages.find(m => m.role === 'assistant');
expect(streaming?.content).toBe('partial answer');
// Stop.
await act(async () => { result.current.stopStreaming(); await flush(); });
// Composer returns to send (isLoading off) and the partial answer stays.
expect(result.current.isLoading).toBe(false);
const afterStop = result.current.messages.find(m => m.role === 'assistant');
expect(afterStop?.content).toBe('partial answer');
// Best-effort server-side cancel fired for this workspace.
expect(mocks.adapter.abortAgent).toHaveBeenCalledWith('ws-1');
// Send is re-enabled: a fresh send dispatches a new stream (not queued).
mocks.adapter.sendMessage.mockImplementationOnce(async function* () {
yield { type: 'done', data: { content: 'second' } };
});
await act(async () => { await result.current.sendMessage('again'); await flush(); });
expect(mocks.adapter.sendMessage).toHaveBeenCalledTimes(2);
gate.resolve(); // let the abandoned first generator settle
await act(async () => { await firstPromise?.catch(() => {}); });
});
it('is a no-op when nothing is streaming', async () => {
const { result } = await mountChat('sess-idle');
await act(async () => { result.current.stopStreaming(); await flush(); });
expect(mocks.adapter.abortAgent).not.toHaveBeenCalled();
expect(result.current.isLoading).toBe(false);
});
});
// ── ChatApp streaming interaction surface (contracts 1 + 2, the UI side) ────
describe('ChatApp — streaming interaction contract', () => {
const noop = () => {};
const baseProps = {
messages: [] as ChatMessage[],
isLoading: false,
onSendMessage: noop,
onClearHistory: noop,
pendingApproval: null,
onApprove: noop,
workspaceId: 'ws-1',
onStopStreaming: noop as () => void,
};
let ChatAppEl: typeof import('@/components/os/apps/ChatApp').default;
beforeEach(async () => { ChatAppEl = (await import('@/components/os/apps/ChatApp')).default; });
// Render, then settle ChatApp's async mount effect (getPins → setPins) so its
// resolution doesn't land outside act after the test body.
const renderChat = async (props: Partial<typeof baseProps> & { messages: ChatMessage[] }) => {
const utils = render(<TooltipProvider><ChatAppEl {...baseProps} {...props} /></TooltipProvider>);
await act(async () => { await flush(); });
return utils;
};
const a1: ChatMessage = { id: 'a1', role: 'assistant', content: 'first line.', timestamp: 'now' };
const a2: ChatMessage = { id: 'a2', role: 'assistant', content: 'second line.', timestamp: 'now' };
/** Give a jsdom element measurable, mutable scroll geometry. */
function mockScrollGeometry(el: HTMLElement, opts: { scrollHeight: number; clientHeight: number; scrollTop: number }) {
let top = opts.scrollTop;
Object.defineProperty(el, 'scrollHeight', { configurable: true, get: () => opts.scrollHeight });
Object.defineProperty(el, 'clientHeight', { configurable: true, get: () => opts.clientHeight });
Object.defineProperty(el, 'scrollTop', { configurable: true, get: () => top, set: (v: number) => { top = v; } });
return { getTop: () => top };
}
it('auto-follow pins the viewport to the newest content while streaming', async () => {
const { rerender } = await renderChat({ messages: [a1], isLoading: true });
const scrollEl = screen.getByTestId('chat-scroll');
// Real geometry: a tall thread whose bottom is 1000px down.
const geo = mockScrollGeometry(scrollEl, { scrollHeight: 1000, clientHeight: 300, scrollTop: 0 });
// A new streamed turn arrives while following (default) → pin to bottom.
await act(async () => {
rerender(<TooltipProvider><ChatAppEl {...baseProps} messages={[a1, a2]} isLoading /></TooltipProvider>);
});
expect(geo.getTop()).toBe(1000);
// No jump affordance while pinned.
expect(screen.queryByTestId('chat-jump-to-latest')).toBeNull();
});
it('a user scroll-up breaks auto-follow and shows "Jump to latest"; clicking re-pins', async () => {
await renderChat({ messages: [a1, a2], isLoading: true });
const scrollEl = screen.getByTestId('chat-scroll');
// Scrolled up: 600px from the bottom (well past the 48px window).
const geo = mockScrollGeometry(scrollEl, { scrollHeight: 1000, clientHeight: 300, scrollTop: 100 });
expect(screen.queryByTestId('chat-jump-to-latest')).toBeNull();
fireEvent.scroll(scrollEl);
// Auto-follow broke → the affordance appears.
expect(screen.getByTestId('chat-jump-to-latest')).toBeInTheDocument();
// Clicking snaps to the newest content and re-pins (affordance hides).
fireEvent.click(screen.getByTestId('chat-jump-to-latest'));
expect(geo.getTop()).toBe(1000);
expect(screen.queryByTestId('chat-jump-to-latest')).toBeNull();
});
it('re-pins automatically when the user scrolls back to the bottom', async () => {
await renderChat({ messages: [a1, a2], isLoading: true });
const scrollEl = screen.getByTestId('chat-scroll');
mockScrollGeometry(scrollEl, { scrollHeight: 1000, clientHeight: 300, scrollTop: 100 });
fireEvent.scroll(scrollEl);
expect(screen.getByTestId('chat-jump-to-latest')).toBeInTheDocument();
// User scrolls back near the bottom (within the 48px window; routed through
// the mocked scrollTop setter). distance = 1000 - 700 - 300 = 0.
scrollEl.scrollTop = 700;
fireEvent.scroll(scrollEl);
expect(screen.queryByTestId('chat-jump-to-latest')).toBeNull();
});
it('shows a Stop control while streaming that calls onStopStreaming, keeping Send available', async () => {
const onStopStreaming = vi.fn();
await renderChat({ messages: [a1], isLoading: true, onStopStreaming });
const stop = screen.getByTestId('chat-stop-stream');
expect(stop).toBeInTheDocument();
// Lane C: Send is NOT replaced — it stays for queueing a follow-up.
expect(screen.getByRole('button', { name: 'Send' })).toBeInTheDocument();
fireEvent.click(stop);
expect(onStopStreaming).toHaveBeenCalledTimes(1);
});
it('hides the Stop control when not streaming', async () => {
const onStopStreaming = vi.fn();
await renderChat({ messages: [a1], isLoading: false, onStopStreaming });
expect(screen.queryByTestId('chat-stop-stream')).toBeNull();
});
});

View File

@@ -0,0 +1,188 @@
/**
* Lane WS (path-to-9 Pillar 1.3) — the commissioned waggle-settle, judged
* STANDALONE. This suite pins the two contracts that make it "the waggle" and
* keep it safe:
*
* 1. Identity — the dancer animates a figure-eight TRANSLATION path (not a
* scale-pop): the `x` keyframes trace the Gerono lemniscate (two lobes,
* returns to origin). SPRING.expressive carries the settle.
* 2. Reduced motion (REDUCED.settle = 'instant-state-color-pulse') — the dancer
* carries NO transform keyframe (static settled state); only the honey glow
* colour-pulses (an opacity pulse, no transform).
* 3. Lifecycle — mounts only while `play`, calls `onDone` after the gesture.
* 4. The SIGNATURE.full session gate — first-of-session + cooldown, idempotent.
*
* framer-motion is stubbed to plain DOM: each element's `animate` prop surfaces
* as `data-animate` (JSON), so the keyframe contract is assertable without a
* real animation engine — the same harness the BootScreen/HM lanes use.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, cleanup, act } from '@testing-library/react';
const h = vi.hoisted(() => ({ reduce: false }));
vi.mock('framer-motion', async () => {
const React = await vi.importActual<typeof import('react')>('react');
const DROP = new Set([
'initial', 'animate', 'exit', 'transition', 'variants',
'whileHover', 'whileTap', 'whileFocus', 'whileInView',
'layout', 'layoutId', 'onAnimationComplete', 'custom',
]);
const make = (tag: string) =>
React.forwardRef(function MotionMock(props: Record<string, unknown>, ref: React.Ref<HTMLElement>) {
const passed: Record<string, unknown> = {};
for (const k of Object.keys(props)) if (!DROP.has(k)) passed[k] = props[k];
if (props.animate !== undefined) passed['data-animate'] = JSON.stringify(props.animate);
return React.createElement(tag, { ...passed, ref });
});
const motion = new Proxy({}, { get: (_t, tag: string) => make(tag) });
return {
__esModule: true,
motion,
AnimatePresence: ({ children }: { children: React.ReactNode }) =>
React.createElement(React.Fragment, null, children),
useReducedMotion: () => h.reduce,
};
});
import { WaggleSettle, WAGGLE_FIG8_X, WAGGLE_FIG8_Y, WAGGLE_TIMES, WAGGLE_WOBBLE_DEG } from '@/components/os/warm/WaggleSettle';
import {
canFireFullSignature,
recordFullSignature,
claimFullSignature,
readSignatureFullState,
EMPTY_SIGNATURE_STATE,
type SignatureFullState,
} from '@/components/os/warm/waggle-settle-gate';
function animateOf(el: Element | null): Record<string, unknown> | null {
if (!el) return null;
const raw = el.getAttribute('data-animate');
return raw ? (JSON.parse(raw) as Record<string, unknown>) : null;
}
beforeEach(() => {
h.reduce = false;
try { window.sessionStorage.clear(); } catch { /* ignore */ }
});
afterEach(() => cleanup());
// ── 1. Identity — the figure-eight path DNA ─────────────────────────────────
describe('Lane WS · figure-eight path DNA', () => {
it('the x path is a two-lobe lemniscate that returns to origin', () => {
expect(WAGGLE_FIG8_X).toHaveLength(9);
expect(WAGGLE_FIG8_X[0]).toBe(0);
expect(WAGGLE_FIG8_X[WAGGLE_FIG8_X.length - 1]).toBe(0);
// Both lobes present: a positive AND a negative extreme (not a one-way pop).
expect(Math.max(...WAGGLE_FIG8_X)).toBeGreaterThan(0);
expect(Math.min(...WAGGLE_FIG8_X)).toBeLessThan(0);
});
it('the y path oscillates above and below the run line (the waggle crossbars)', () => {
expect(WAGGLE_FIG8_Y).toHaveLength(9);
expect(Math.max(...WAGGLE_FIG8_Y)).toBeGreaterThan(0);
expect(Math.min(...WAGGLE_FIG8_Y)).toBeLessThan(0);
});
it('the body wobble decays and the keyframe times ascend 0→1', () => {
expect(WAGGLE_WOBBLE_DEG[0]).toBe(0);
expect(WAGGLE_WOBBLE_DEG[WAGGLE_WOBBLE_DEG.length - 1]).toBe(0);
expect(WAGGLE_TIMES[0]).toBe(0);
expect(WAGGLE_TIMES[WAGGLE_TIMES.length - 1]).toBe(1);
for (let i = 1; i < WAGGLE_TIMES.length; i++) {
expect(WAGGLE_TIMES[i]).toBeGreaterThan(WAGGLE_TIMES[i - 1]);
}
});
});
// ── 2. Component render contract ────────────────────────────────────────────
describe('Lane WS · WaggleSettle render contract', () => {
it('renders nothing while play is false', () => {
const { queryByTestId } = render(<WaggleSettle play={false} />);
expect(queryByTestId('waggle-settle')).toBeNull();
});
it('motion: the dancer runs a figure-eight TRANSLATION (not a scale-pop)', () => {
const { getByTestId } = render(<WaggleSettle play size={40} />);
const dancer = animateOf(getByTestId('waggle-settle-dancer'));
expect(dancer).toBeTruthy();
// The identity is the translation path — x must be a keyframe array…
expect(Array.isArray(dancer!.x)).toBe(true);
const xs = dancer!.x as number[];
expect(xs).toHaveLength(9);
expect(xs[0]).toBe(0);
expect(xs[xs.length - 1]).toBe(0);
expect(Math.max(...xs)).toBeGreaterThan(0);
expect(Math.min(...xs)).toBeLessThan(0);
// …and scale is a single settle value, NOT the driver of the gesture.
expect(Array.isArray(dancer!.scale)).toBe(false);
expect(dancer!.scale).toBe(1);
});
it('reduced motion: the dancer is static (no transform keyframe) — only the glow colour-pulses', () => {
h.reduce = true;
const { getByTestId } = render(<WaggleSettle play size={40} />);
const dancer = animateOf(getByTestId('waggle-settle-dancer'));
// Instant settled state — opacity only, and zero array-valued transforms.
expect(dancer).toEqual({ opacity: 1 });
const hasTransformKeyframe = Object.values(dancer!).some((v) => Array.isArray(v));
expect(hasTransformKeyframe).toBe(false);
// The colour pulse survives: the glow opacity-pulses (a colour pulse, no transform).
const glow = animateOf(getByTestId('waggle-settle-glow'));
expect(Array.isArray(glow!.opacity)).toBe(true);
expect('scale' in glow!).toBe(false);
});
it('calls onDone after the gesture settles, not before', () => {
vi.useFakeTimers();
try {
const onDone = vi.fn();
render(<WaggleSettle play onDone={onDone} />);
expect(onDone).not.toHaveBeenCalled();
act(() => { vi.advanceTimersByTime(300); });
expect(onDone).not.toHaveBeenCalled();
act(() => { vi.advanceTimersByTime(400); });
expect(onDone).toHaveBeenCalledTimes(1);
} finally {
vi.useRealTimers();
}
});
});
// ── 3. The SIGNATURE.full session gate ──────────────────────────────────────
describe('Lane WS · SIGNATURE.full gate', () => {
it('fires for the memory-saved moment on a fresh session', () => {
expect(canFireFullSignature({ moment: 'memory-saved-first-of-session', state: EMPTY_SIGNATURE_STATE, now: 1000 })).toBe(true);
});
it('rejects an unrecognised (non-full-tier) moment', () => {
expect(canFireFullSignature({ moment: 'send-arm', state: EMPTY_SIGNATURE_STATE, now: 1000 })).toBe(false);
});
it('spends a first-of-session moment once', () => {
const spent: SignatureFullState = { lastFiredAt: 0, firedMoments: ['memory-saved-first-of-session'] };
expect(canFireFullSignature({ moment: 'memory-saved-first-of-session', state: spent, now: 10_000_000 })).toBe(false);
});
it('blocks a different full moment while inside the cooldown, allows it after', () => {
const state: SignatureFullState = { lastFiredAt: 1_000_000, firedMoments: ['memory-saved-first-of-session'] };
// install-success is a different full moment; still cooling down.
expect(canFireFullSignature({ moment: 'install-success', state, now: 1_000_000 + 30_000 })).toBe(false);
// …past the 60s cooldown it is allowed.
expect(canFireFullSignature({ moment: 'install-success', state, now: 1_000_000 + 61_000 })).toBe(true);
});
it('recordFullSignature is immutable and appends the moment', () => {
const next = recordFullSignature(EMPTY_SIGNATURE_STATE, 'memory-saved-first-of-session', 5000);
expect(EMPTY_SIGNATURE_STATE.firedMoments).toEqual([]); // original untouched
expect(next.lastFiredAt).toBe(5000);
expect(next.firedMoments).toEqual(['memory-saved-first-of-session']);
});
it('claimFullSignature is idempotent across the session (persists via sessionStorage)', () => {
expect(claimFullSignature('memory-saved-first-of-session', 2000)).toBe(true);
// A second claim in the same session (even much later) does not re-fire.
expect(claimFullSignature('memory-saved-first-of-session', 5_000_000)).toBe(false);
expect(readSignatureFullState().firedMoments).toEqual(['memory-saved-first-of-session']);
});
});

View File

@@ -0,0 +1,46 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, cleanup } from '@testing-library/react';
const mocks = vi.hoisted(() => ({
adapter: {
detectTools: vi.fn(),
getToolProcesses: vi.fn(),
launchTool: vi.fn(),
manageHooks: vi.fn(),
killTool: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import LauncherApp, { resetLauncherRouteCache } from '@/components/os/apps/LauncherApp';
beforeEach(() => {
vi.clearAllMocks();
resetLauncherRouteCache();
mocks.adapter.detectTools.mockResolvedValue({
platform: 'win32',
detectedAt: new Date().toISOString(),
tools: [],
});
mocks.adapter.getToolProcesses.mockResolvedValue({ processes: [] });
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
describe('LauncherApp accessibility metadata', () => {
it('names the refresh control and optional prompt textarea', async () => {
render(<LauncherApp activeWorkspaceId="workspace-1" />);
expect(await screen.findByRole('button', { name: /refresh installed tools/i })).toBeInTheDocument();
const prompt = screen.getByRole('textbox', { name: /optional launch prompt/i });
expect(prompt).toHaveAttribute('name', 'launcherPrompt');
expect(prompt).toHaveAttribute('autocomplete', 'off');
expect(prompt.className).toContain('focus-visible:ring-2');
await waitFor(() => expect(mocks.adapter.detectTools).toHaveBeenCalled());
});
});

View File

@@ -0,0 +1,174 @@
/**
* R5-006 — light-mode token contrast ratchet.
*
* Parses index.css and asserts that every --status-* and --kg-* token has a
* value in BOTH the dark `:root` block and the light `:root[data-theme="light"]`
* block, and that the light values meet WCAG AA (>=4.5:1) against the light
* --background surface.
*
* This is a STATIC contrast check (computable without a browser) — it does NOT
* replace the independent visual QA the GA plan requires for the broader
* hardcoded-Tailwind migration. It locks in the token-level guarantee so a
* future edit that regresses a token below AA fails CI.
*/
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import path from 'node:path';
// __dirname resolves under this vitest config (see skill-recommendations.test.ts).
const css = readFileSync(path.resolve(__dirname, '../index.css'), 'utf-8');
/** Extract the body of a `selector { ... }` block (first match). */
function block(selector: string): string {
const start = css.indexOf(selector);
if (start === -1) throw new Error(`selector not found: ${selector}`);
const open = css.indexOf('{', start);
// Walk to the matching close brace (blocks here are flat — no nesting).
let depth = 0;
for (let i = open; i < css.length; i++) {
if (css[i] === '{') depth++;
else if (css[i] === '}') {
depth--;
if (depth === 0) return css.slice(open + 1, i);
}
}
throw new Error(`unterminated block: ${selector}`);
}
function tokens(body: string): Map<string, string> {
const m = new Map<string, string>();
for (const match of body.matchAll(/(--(?:status|kg)-[a-z]+)\s*:\s*([^;]+);/g)) {
m.set(match[1], match[2].trim());
}
return m;
}
// ── WCAG contrast (sRGB relative luminance) ──
function hexToRgb(x: string): [number, number, number] {
const h = x.replace('#', '');
return [parseInt(h.slice(0, 2), 16), parseInt(h.slice(2, 4), 16), parseInt(h.slice(4, 6), 16)];
}
function hslToRgb(h: number, s: number, l: number): [number, number, number] {
s /= 100; l /= 100;
const k = (n: number) => (n + h / 30) % 12;
const a = s * Math.min(l, 1 - l);
const f = (n: number) => l - a * Math.max(-1, Math.min(k(n) - 3, 9 - k(n), 1));
return [255 * f(0), 255 * f(8), 255 * f(4)];
}
function lum([r, g, b]: [number, number, number]): number {
const a = [r, g, b].map(v => {
v /= 255;
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
});
return 0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2];
}
function ratio(c1: [number, number, number], c2: [number, number, number]): number {
const L1 = lum(c1), L2 = lum(c2);
return (Math.max(L1, L2) + 0.05) / (Math.min(L1, L2) + 0.05);
}
const darkTokens = tokens(block(':root'));
const lightTokens = tokens(block(':root[data-theme="light"]'));
// Light --background: `40 18% 97%` (HSL components, Tailwind hsl() convention).
const lightBgMatch = block(':root[data-theme="light"]').match(/--background:\s*([\d.]+)\s+([\d.]+)%\s+([\d.]+)%/);
const lightBg: [number, number, number] = lightBgMatch
? hslToRgb(Number(lightBgMatch[1]), Number(lightBgMatch[2]), Number(lightBgMatch[3]))
: hslToRgb(40, 18, 97);
const SEMANTIC = ['--status-healthy', '--status-warning', '--status-error', '--status-info', '--status-ai',
'--kg-person', '--kg-project', '--kg-concept', '--kg-org', '--kg-default'];
describe('R5-006 light-mode token contrast', () => {
it('defines every status/kg token in the dark :root block', () => {
for (const t of SEMANTIC) expect(darkTokens.has(t), `dark missing ${t}`).toBe(true);
});
it('defines every status/kg token in the light block (no dark-color bleed)', () => {
for (const t of SEMANTIC) expect(lightTokens.has(t), `light missing ${t}`).toBe(true);
});
it.each(SEMANTIC)('light %s meets WCAG AA (>=4.5:1) on the cream surface', (token) => {
const val = lightTokens.get(token)!;
expect(val, `${token} must be a hex color`).toMatch(/^#[0-9a-fA-F]{6}$/);
const r = ratio(lightBg, hexToRgb(val));
expect(r, `${token} = ${val} → ${r.toFixed(2)}:1`).toBeGreaterThanOrEqual(4.5);
});
});
// ── Honey button text contrast (--primary-foreground on --primary) ──
// The default shadcn button/badge render `bg-primary text-primary-foreground`,
// and the design mandates dark ink (#1a1407) on the honey accent. Guard the
// ratio in BOTH themes so a light-mode regression (white-on-honey ≈ 3.6:1)
// can't ship green again.
function hslTriple(body: string, name: string): [number, number, number] | null {
const m = body.match(new RegExp(`${name}:\\s*([\\d.]+)\\s+([\\d.]+)%\\s+([\\d.]+)%`));
return m ? hslToRgb(Number(m[1]), Number(m[2]), Number(m[3])) : null;
}
describe('honey button text contrast (--primary-foreground on --primary)', () => {
it.each([
['dark', ':root'],
['light', ':root[data-theme="light"]'],
])('%s primary button text meets WCAG AA (>=4.5:1)', (label, selector) => {
const body = block(selector);
const primary = hslTriple(body, '--primary');
const fg = hslTriple(body, '--primary-foreground');
expect(primary, `${selector} --primary must be HSL`).not.toBeNull();
expect(fg, `${selector} --primary-foreground must be HSL`).not.toBeNull();
const r = ratio(primary!, fg!);
expect(r, `${label} primary-foreground → ${r.toFixed(2)}:1`).toBeGreaterThanOrEqual(4.5);
});
});
// ── Pillar 4 AA-floor tiers (Lane T, 2026-07-07) ──
// --text-tertiary must be AA (>=4.5:1) on EVERY surface token in BOTH themes;
// --focus-ring + --line-affordance are non-text tiers (WCAG 1.4.11, >=3:1).
// The four surfaces a tier may sit over: --bg (--background), --bg-2,
// --surface (--card), --surface-2 (--secondary). This freezes the guarantee
// so a future edit that dims a tier below its floor fails CI.
function hexToken(body: string, name: string): string | null {
const m = body.match(new RegExp(`${name}:\\s*(#[0-9a-fA-F]{6})`));
return m ? m[1] : null;
}
function surfaces(body: string): Record<string, [number, number, number]> {
const bg2 = hexToken(body, '--bg-2');
return {
'--bg': hslTriple(body, '--background')!,
'--bg-2': bg2 ? hexToRgb(bg2) : hslTriple(body, '--background')!,
'--surface': hslTriple(body, '--card')!,
'--surface-2': hslTriple(body, '--secondary')!,
};
}
describe('Pillar 4 AA-floor tiers (text-tertiary / focus-ring / line-affordance)', () => {
it.each([
['dark', ':root'],
['light', ':root[data-theme="light"]'],
])('%s --text-tertiary is AA (>=4.5:1) on all four surfaces', (label, selector) => {
const body = block(selector);
const tier = hexToken(body, '--text-tertiary');
expect(tier, `${label} --text-tertiary must be a hex color`).toMatch(/^#[0-9a-fA-F]{6}$/);
const tierRgb = hexToRgb(tier!);
for (const [name, surf] of Object.entries(surfaces(body))) {
const r = ratio(tierRgb, surf);
expect(r, `${label} --text-tertiary ${tier} on ${name} → ${r.toFixed(2)}:1`).toBeGreaterThanOrEqual(4.5);
}
});
it.each([
['dark', ':root'],
['light', ':root[data-theme="light"]'],
])('%s --focus-ring + --line-affordance meet WCAG 1.4.11 (>=3:1) on all four surfaces', (label, selector) => {
const body = block(selector);
for (const token of ['--focus-ring', '--line-affordance']) {
const val = hexToken(body, token);
expect(val, `${label} ${token} must be a hex color`).toMatch(/^#[0-9a-fA-F]{6}$/);
const rgb = hexToRgb(val!);
for (const [name, surf] of Object.entries(surfaces(body))) {
const r = ratio(rgb, surf);
expect(r, `${label} ${token} ${val} on ${name} → ${r.toFixed(2)}:1`).toBeGreaterThanOrEqual(3);
}
}
});
});

View File

@@ -0,0 +1,182 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react';
import type { Memory } from '@/lib/types';
import { clearMemoryListCache } from '@/components/os/apps/memory/memory-list-cache';
const mocks = vi.hoisted(() => ({
adapter: {
listMemories: vi.fn(),
patchMemory: vi.fn(),
archiveMemory: vi.fn(),
deleteMemoryById: vi.fn(),
mergeMemories: vi.fn(),
getMemoryOriginalSource: vi.fn(),
eraseMemory: vi.fn(),
listSuppression: vi.fn(),
allowReimport: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter }));
import MemoryCenterTab from '@/components/os/apps/memory/MemoryCenterTab';
const memory: Memory = {
id: 'memory-research-note',
kind: 'fact',
title: 'Research Note',
content: 'The supplier review belongs in the Q3 diligence packet.',
scope: 'personal',
workspaceId: undefined,
source: 'user_stated',
sourceId: null,
sourceUrl: null,
importance: 'normal',
status: 'active',
confidence: 91,
tags: ['research'],
evidence: [],
hasOriginalSource: false,
createdAt: '2026-07-08T08:00:00.000Z',
updatedAt: '2026-07-08T09:00:00.000Z',
};
function renderMemoryCenter() {
return render(<MemoryCenterTab consumeDeepLinks={false} />);
}
beforeEach(() => {
clearMemoryListCache();
vi.clearAllMocks();
mocks.adapter.listMemories.mockResolvedValue([memory]);
mocks.adapter.patchMemory.mockResolvedValue(memory);
mocks.adapter.archiveMemory.mockResolvedValue({ ...memory, status: 'archived' });
mocks.adapter.deleteMemoryById.mockResolvedValue(undefined);
mocks.adapter.mergeMemories.mockResolvedValue(memory);
mocks.adapter.getMemoryOriginalSource.mockResolvedValue({ archiveRows: [] });
mocks.adapter.eraseMemory.mockResolvedValue({
erased: true,
result: { framesDeleted: 1, archiveRedacted: 1, entitiesErased: 1 },
});
mocks.adapter.listSuppression.mockResolvedValue({
mind: 'personal',
suppressed: [{
source: 'chatgpt',
sourceRef: 'research-export.json',
erasedAt: '2026-07-08T09:30:00.000Z',
reason: 'GDPR Art.17 erasure',
}],
});
mocks.adapter.allowReimport.mockResolvedValue({ removed: true });
});
afterEach(() => {
cleanup();
clearMemoryListCache();
vi.restoreAllMocks();
});
describe('Memory Center trust flows', () => {
it('a11y: filters and detail editor expose stable form metadata', async () => {
renderMemoryCenter();
const search = await screen.findByRole('textbox', { name: /search memories/i });
expect(search).toHaveAttribute('name', 'memorySearch');
expect(search).toHaveAttribute('autocomplete', 'off');
expect(search.parentElement?.className).toContain('focus-within:ring-2');
expect(search.parentElement?.className).toContain('focus-within:ring-[var(--focus-ring)]');
const confidence = screen.getByRole('combobox', { name: /filter by confidence/i });
expect(confidence).toHaveAttribute('name', 'memoryConfidenceFilter');
expect(confidence).toHaveAttribute('autocomplete', 'off');
expect(confidence.className).toContain('focus-visible:ring-2');
expect(confidence.className).toContain('focus-visible:ring-[var(--focus-ring)]');
for (const name of [/needs review/i, /active/i, /all kinds/i, /fact/i]) {
expect(screen.getByRole('button', { name }).className).toContain('focus-visible:ring-2');
}
fireEvent.click(await screen.findByLabelText('Research Note'));
const kind = await screen.findByLabelText('Kind');
expect(kind).toHaveAttribute('name', 'memoryKind');
expect(kind).toHaveAttribute('autocomplete', 'off');
expect(kind.className).toContain('focus-visible:ring-2');
expect(kind.className).toContain('focus-visible:ring-[var(--focus-ring)]');
const content = screen.getByLabelText('Content');
expect(content).toHaveAttribute('name', 'memoryContent');
expect(content).toHaveAttribute('autocomplete', 'off');
expect(content.className).toContain('focus-visible:ring-2');
expect(content.className).toContain('focus-visible:ring-[var(--focus-ring)]');
});
it('asks in-app before permanently deleting a memory', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
renderMemoryCenter();
fireEvent.click(await screen.findByLabelText('Research Note'));
fireEvent.click(await screen.findByRole('button', { name: /^delete$/i }));
expect(confirmSpy).not.toHaveBeenCalled();
expect(mocks.adapter.deleteMemoryById).not.toHaveBeenCalled();
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent(/delete memory permanently/i);
expect(modal).toHaveTextContent(/research note/i);
expect(modal).toHaveTextContent(/archive/i);
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.deleteMemoryById).toHaveBeenCalledWith('memory-research-note', undefined, 'personal'));
});
it('asks in-app before erasing a memory and derived data', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
renderMemoryCenter();
fireEvent.click(await screen.findByLabelText('Research Note'));
fireEvent.click(await screen.findByRole('button', { name: /^erase$/i }));
expect(confirmSpy).not.toHaveBeenCalled();
expect(mocks.adapter.eraseMemory).not.toHaveBeenCalled();
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent(/erase memory and derived data/i);
expect(modal).toHaveTextContent(/research note/i);
expect(modal).toHaveTextContent(/cannot be undone/i);
expect(modal).toHaveTextContent(/original source/i);
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.eraseMemory).toHaveBeenCalledWith(
{ frameId: 'memory-research-note' },
{ workspaceId: undefined, mind: 'personal' },
));
await screen.findByText(/erased "research note"/i);
});
it('asks in-app before allowing an erased source to be re-imported', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
renderMemoryCenter();
fireEvent.click(await screen.findByRole('button', { name: /erased sources/i }));
await screen.findByText('research-export.json');
fireEvent.click(await screen.findByRole('button', { name: /allow re-import/i }));
expect(confirmSpy).not.toHaveBeenCalled();
expect(mocks.adapter.allowReimport).not.toHaveBeenCalled();
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent(/allow source to be re-imported/i);
expect(modal).toHaveTextContent(/research-export\.json/i);
expect(modal).toHaveTextContent(/re-consented/i);
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.allowReimport).toHaveBeenCalledWith(
{ source: 'chatgpt', sourceRef: 'research-export.json' },
{ workspaceId: undefined, mind: 'personal' },
));
});
});

View File

@@ -0,0 +1,59 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/react';
import MissionControlApp from '@/components/os/apps/MissionControlApp';
import type { FleetSession } from '@/lib/types';
const mocks = vi.hoisted(() => ({
adapter: {
getFleet: vi.fn(),
getTeamMembers: vi.fn(),
getTeamActivity: vi.fn(),
detectTools: vi.fn(),
fleetAction: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
const session = (workspaceId: string, workspaceName: string, status: FleetSession['status']): FleetSession => ({
workspaceId,
workspaceName,
status,
duration: 120,
toolCount: 2,
model: 'gpt-4.1',
tokenUsage: 1234,
});
beforeEach(() => {
vi.clearAllMocks();
mocks.adapter.getFleet.mockResolvedValue([
session('w-active', 'Alpha Workspace', 'active'),
session('w-paused', 'Beta Workspace', 'paused'),
]);
mocks.adapter.getTeamMembers.mockResolvedValue([]);
mocks.adapter.getTeamActivity.mockResolvedValue([]);
mocks.adapter.detectTools.mockResolvedValue({ tools: [] });
mocks.adapter.fleetAction.mockResolvedValue(undefined);
});
afterEach(cleanup);
describe('MissionControlApp accessibility', () => {
it('names icon-only refresh and fleet action controls with visible focus rings', async () => {
render(<MissionControlApp onSpawnOpen={vi.fn()} />);
await screen.findByText('Alpha Workspace');
const refresh = screen.getByRole('button', { name: /refresh mission control/i });
const pause = screen.getByRole('button', { name: /pause alpha workspace/i });
const resume = screen.getByRole('button', { name: /resume beta workspace/i });
const stopAlpha = screen.getByRole('button', { name: /stop alpha workspace/i });
const stopBeta = screen.getByRole('button', { name: /stop beta workspace/i });
for (const control of [refresh, pause, resume, stopAlpha, stopBeta]) {
expect(control.className).toContain('focus-visible:ring-2');
expect(control.className).toContain('focus-visible:ring-[var(--focus-ring)]');
}
});
});

View File

@@ -0,0 +1,46 @@
import { describe, expect, it } from 'vitest';
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
const sourceRoot = join(process.cwd(), 'src');
const sourceFilePattern = /\.(tsx?|css)$/;
const ignoredDirs = new Set(['node_modules', 'dist']);
const ambiguousMotionTokenPattern = /\b(?:duration|ease)-\[var\(--mo-[^\]]+\)\]/;
function collectSourceFiles(dir: string, files: string[] = []): string[] {
for (const entry of readdirSync(dir)) {
const fullPath = join(dir, entry);
const stat = statSync(fullPath);
if (stat.isDirectory()) {
if (!ignoredDirs.has(entry)) collectSourceFiles(fullPath, files);
continue;
}
if (sourceFilePattern.test(entry)) files.push(fullPath);
}
return files;
}
describe('motion class hygiene', () => {
it('defines named utilities for tokenized CSS motion timing', () => {
const css = readFileSync(join(sourceRoot, 'index.css'), 'utf8');
expect(css).toContain('.duration-mo-fast');
expect(css).toContain('transition-duration: var(--mo-fast)');
expect(css).toContain('.duration-mo-base');
expect(css).toContain('transition-duration: var(--mo-base)');
expect(css).toContain('.ease-mo');
expect(css).toContain('transition-timing-function: var(--mo-ease)');
});
it('uses named motion utilities instead of Tailwind-ambiguous arbitrary motion tokens', () => {
const offenders = collectSourceFiles(sourceRoot).flatMap(file => {
const text = readFileSync(file, 'utf8');
return text
.split(/\r?\n/)
.map((line, index) => ({ file, line, index: index + 1 }))
.filter(({ line }) => ambiguousMotionTokenPattern.test(line));
});
expect(offenders).toEqual([]);
});
});

View File

@@ -0,0 +1,68 @@
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import ImportStep from '@/components/os/overlays/onboarding/ImportStep';
import type { ImportStepProps } from '@/components/os/overlays/onboarding/types';
const baseProps = (overrides: Partial<ImportStepProps> = {}): ImportStepProps => ({
importSource: null,
importItems: [],
importDone: false,
importing: false,
onFileImport: vi.fn(),
onImportCommit: vi.fn(),
onContinue: vi.fn(),
...overrides,
});
afterEach(cleanup);
describe('Onboarding ImportStep', () => {
it('makes high-volume Claude Code history a deliberate review flow', () => {
const onContinue = vi.fn();
const onClaudeCodeHarvest = vi.fn();
render(
<ImportStep
{...baseProps({
claudeCodeDetected: {
found: true,
itemCount: 5514,
path: 'C:/Users/Marko/.claude/projects',
},
onClaudeCodeHarvest,
onContinue,
})}
/>,
);
expect(screen.getByText(/5,514 items from Claude Code/i)).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /import my history/i })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /review after setup/i }));
expect(onContinue).toHaveBeenCalledTimes(1);
expect(onClaudeCodeHarvest).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: /import 5,514 now/i }));
expect(onClaudeCodeHarvest).toHaveBeenCalledTimes(1);
});
it('keeps the simple import CTA for small detected histories', () => {
const onClaudeCodeHarvest = vi.fn();
render(
<ImportStep
{...baseProps({
claudeCodeDetected: {
found: true,
itemCount: 12,
path: 'C:/Users/Marko/.claude/projects',
},
onClaudeCodeHarvest,
})}
/>,
);
fireEvent.click(screen.getByRole('button', { name: /import my history/i }));
expect(onClaudeCodeHarvest).toHaveBeenCalledTimes(1);
});
});

View File

@@ -0,0 +1,256 @@
/**
* P1a Stage B — chat machinery (conversion plan §3.2/§4.2/§5.2):
* - useChatWidgetState: the useWindowManager:316-361 relocation re-keyed to
* workspaceId (persona set, autonomy TTL + 10s auto-revert, P4 default
* inheritance) persisted under waggle-chat-state-v1.
* - seedChat one-shot semantics (§4.2).
* - chat-title composition (§3.2, getWindowTitle relocation).
* - The founder-ratified two-seam WorkspaceDesktopApp edit, test-pinned
* (§5.2): controlled activeTab/onTabChange + chat-slot render, with the
* uncontrolled/placeholder defaults preserved.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, renderHook, act } from '@testing-library/react';
import {
CHAT_STATE_KEY,
composeChatTitle,
loadChatEntries,
rekeyLocalDefaultChatState,
seedChat,
takeChatSeed,
useChatWidgetState,
writeChatEntry,
} from '@/hooks/useChatWidgetState';
// WorkspaceDesktopApp deps (the §5.2 pin renders the real component).
const mocks = vi.hoisted(() => ({
adapter: {
getWorkspaceContext: vi.fn(),
getWorkspaceState: vi.fn(),
getWorkspaceActivity: vi.fn(),
getTeamMembers: vi.fn(),
getWorkspaceFiles: vi.fn(),
getWorkspaceTasks: vi.fn().mockResolvedValue([]),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/hooks/useRoomState', () => ({ useRoomState: () => ({ workspaceMap: new Map() }) }));
// WorkspaceActionsMenu (G1) reads ShellContext for patch/delete — these tests
// render the desktop bare, so stub the shell surface the menu needs.
vi.mock('@/providers/ShellContext', () => ({
useShell: () => ({ patchWorkspace: vi.fn().mockResolvedValue(true), deleteWorkspace: vi.fn().mockResolvedValue(true) }),
}));
import WorkspaceDesktopApp from '@/components/os/apps/WorkspaceDesktopApp';
beforeEach(() => {
vi.clearAllMocks();
localStorage.clear();
mocks.adapter.getWorkspaceContext.mockResolvedValue({
workspace: { name: 'Acme', status: 'active' },
});
// One pending task so the Tasks tab renders its list body (ws-tasks-tab)
// rather than the no-tasks placeholder.
mocks.adapter.getWorkspaceState.mockResolvedValue({
pending: [{ id: 't1', content: 'Draft the launch brief' }], blocked: [], completed: [],
});
mocks.adapter.getWorkspaceActivity.mockResolvedValue({ events: [] });
mocks.adapter.getTeamMembers.mockResolvedValue([]);
mocks.adapter.getWorkspaceFiles.mockResolvedValue([]);
});
afterEach(() => {
cleanup();
vi.useRealTimers();
});
describe('useChatWidgetState (§3.2 relocation)', () => {
it('setPersona persists under waggle-chat-state-v1 keyed by workspaceId', () => {
const { result } = renderHook(() => useChatWidgetState('ws-1'));
act(() => result.current.setPersona('coder'));
expect(result.current.entry).toMatchObject({ personaId: 'coder', personaLabel: 'Coder' });
const persisted = JSON.parse(localStorage.getItem(CHAT_STATE_KEY)!);
expect(persisted.version).toBe(1);
expect(persisted.chats['ws-1']).toMatchObject({ personaId: 'coder', personaLabel: 'Coder' });
});
it('keeps per-workspace state isolated (re-key instanceId → workspaceId)', () => {
const a = renderHook(() => useChatWidgetState('ws-a'));
const b = renderHook(() => useChatWidgetState('ws-b'));
act(() => a.result.current.setPersona('writer'));
expect(a.result.current.entry.personaId).toBe('writer');
expect(b.result.current.entry.personaId).toBeUndefined();
});
it('auto-reverts an expired elevated autonomy on the 10s sweep', () => {
vi.useFakeTimers();
const { result } = renderHook(() => useChatWidgetState('ws-2'));
act(() => result.current.setAutonomy('trusted', 1)); // 1 minute TTL
expect(result.current.entry.autonomyLevel).toBe('trusted');
expect(result.current.entry.autonomyExpiresAt).toBeGreaterThan(Date.now());
act(() => { vi.advanceTimersByTime(80_000); }); // past TTL + a 10s tick
expect(result.current.entry.autonomyLevel).toBe('normal');
expect(result.current.entry.autonomyExpiresAt).toBeNull();
});
it('null TTL ("until explicitly lowered") never auto-reverts', () => {
vi.useFakeTimers();
const { result } = renderHook(() => useChatWidgetState('ws-3'));
act(() => result.current.setAutonomy('yolo', null));
act(() => { vi.advanceTimersByTime(600_000); });
expect(result.current.entry.autonomyLevel).toBe('yolo');
expect(result.current.entry.autonomyExpiresAt).toBeNull();
});
it('P4: a never-seen workspace inherits an elevated defaultAutonomy with null expiry', () => {
const { result } = renderHook(() =>
useChatWidgetState('ws-new', { defaultAutonomy: 'trusted' }));
expect(result.current.entry).toMatchObject({ autonomyLevel: 'trusted', autonomyExpiresAt: null });
});
it('P4: an entry with an autonomy level is NOT overridden by defaultAutonomy (restored-window parity via the §3.3 normal marker)', () => {
writeChatEntry('ws-old', { personaId: 'analyst', autonomyLevel: 'normal', autonomyExpiresAt: null });
const { result } = renderHook(() =>
useChatWidgetState('ws-old', { defaultAutonomy: 'yolo' }));
expect(result.current.entry.autonomyLevel).toBe('normal');
expect(result.current.entry.personaId).toBe('analyst');
});
it('P4: a persona-only entry (PersonaSwitcher pre-visit) does NOT block inheritance (review finding)', () => {
// PersonaSwitcher can write {personaId} for a never-visited workspace via
// setActiveChatPersona — that must not count as "seen" for P4.
writeChatEntry('ws-persona-only', { personaId: 'analyst' });
const { result } = renderHook(() =>
useChatWidgetState('ws-persona-only', { defaultAutonomy: 'trusted' }));
expect(result.current.entry).toMatchObject({
personaId: 'analyst', autonomyLevel: 'trusted', autonomyExpiresAt: null,
});
});
it('P4: a defaultAutonomy arriving AFTER mount (async getPermissions) still stamps the widget (review finding)', () => {
// ShellContext fetches defaultAutonomy asynchronously; a deep-link-mounted
// widget first renders with the 'normal' initial value. The effect must
// re-fire when the elevated value arrives — the keep-alive instance never
// remounts.
const { result, rerender } = renderHook(
({ level }: { level: 'normal' | 'trusted' | 'yolo' }) =>
useChatWidgetState('ws-late', { defaultAutonomy: level }),
{ initialProps: { level: 'normal' as const } },
);
expect(result.current.entry.autonomyLevel).toBeUndefined();
rerender({ level: 'trusted' });
expect(result.current.entry).toMatchObject({ autonomyLevel: 'trusted', autonomyExpiresAt: null });
});
it('P4: a late defaultAutonomy never overrides an autonomy level the user already set', () => {
const { result, rerender } = renderHook(
({ level }: { level: 'normal' | 'trusted' | 'yolo' }) =>
useChatWidgetState('ws-late-set', { defaultAutonomy: level }),
{ initialProps: { level: 'normal' as const } },
);
// User explicitly chooses 'normal' before the permissions fetch resolves.
act(() => result.current.setAutonomy('normal'));
rerender({ level: 'yolo' });
expect(result.current.entry.autonomyLevel).toBe('normal');
});
it('rekeyLocalDefaultChatState moves the placeholder entry; an existing real entry wins', () => {
writeChatEntry('local-default', { personaId: 'writer' });
rekeyLocalDefaultChatState('ws-real');
expect(loadChatEntries()['local-default']).toBeUndefined();
expect(loadChatEntries()['ws-real']).toMatchObject({ personaId: 'writer' });
// Placeholder vs an already-present real entry: real entry wins.
writeChatEntry('local-default', { personaId: 'coder' });
rekeyLocalDefaultChatState('ws-real');
expect(loadChatEntries()['local-default']).toBeUndefined();
expect(loadChatEntries()['ws-real']).toMatchObject({ personaId: 'writer' });
});
});
describe('seedChat (§4.2 one-shot)', () => {
it('takeChatSeed returns the seed exactly once', () => {
seedChat('ws-seed', { personaId: 'writer', initialMessage: 'Hello!' });
expect(takeChatSeed('ws-seed')).toEqual({ personaId: 'writer', initialMessage: 'Hello!' });
expect(takeChatSeed('ws-seed')).toBeUndefined();
});
it('seeds are per-workspace and never persisted', () => {
seedChat('ws-x', { initialMessage: 'draft' });
expect(takeChatSeed('ws-y')).toBeUndefined();
expect(localStorage.getItem(CHAT_STATE_KEY)).toBeNull();
expect(takeChatSeed('ws-x')).toEqual({ initialMessage: 'draft' });
});
it('F2: round-trips the autoSend flag and is still never persisted', () => {
seedChat('ws-auto', { personaId: 'coder', initialMessage: 'Ship it', autoSend: true });
expect(localStorage.getItem(CHAT_STATE_KEY)).toBeNull();
expect(takeChatSeed('ws-auto')).toEqual({ personaId: 'coder', initialMessage: 'Ship it', autoSend: true });
expect(takeChatSeed('ws-auto')).toBeUndefined();
});
});
describe('composeChatTitle (§3.2 getWindowTitle relocation)', () => {
it('composes workspace · template · persona with the short labels', () => {
expect(composeChatTitle('Acme', 'sales-pipeline', 'coder')).toBe('Acme · Sales · Coder');
expect(composeChatTitle('Acme', 'blank', 'unknown-persona')).toBe('Acme · unknown-persona');
expect(composeChatTitle(undefined, undefined, undefined)).toBe('Chat');
});
});
describe('WorkspaceDesktopApp two-seam edit (§5.2, founder-ratified, test-pinned)', () => {
it('seam (a): controlled activeTab renders that tab; clicks call onTabChange without internal flips', async () => {
const onTabChange = vi.fn();
render(
<WorkspaceDesktopApp
workspaceId="ws-1" workspaceName="Acme"
activeTab="tasks" onTabChange={onTabChange}
/>,
);
// Tasks is reachable but NOT a bar tab in the warm-Hive 6-tab set, so a
// controlled activeTab='tasks' still renders the Tasks body (the seam is
// tab-agnostic) while no bar tab is selected.
expect(await screen.findByTestId('ws-tasks-tab')).toBeInTheDocument();
fireEvent.click(screen.getByTestId('ws-tab-chat'));
expect(onTabChange).toHaveBeenCalledWith('chat');
// Still controlled by the prop — the panel did not flip internally (the
// click fired onTabChange but the controlled body stays on Tasks).
expect(screen.getByTestId('ws-tab-chat')).toHaveAttribute('aria-selected', 'false');
expect(screen.getByTestId('ws-tasks-tab')).toBeInTheDocument();
});
it('seam (a): uncontrolled default preserves the original internal tab behavior', async () => {
render(<WorkspaceDesktopApp workspaceId="ws-1" workspaceName="Acme" />);
expect(await screen.findByTestId('ws-tab-bar')).toBeInTheDocument();
// Drive the internal tab via a bar tab (Tasks is no longer in the bar);
// the chat tab's deep-link body (no slot) confirms the internal switch.
fireEvent.click(screen.getByTestId('ws-tab-chat'));
expect(screen.getByTestId('ws-chat-tab-open')).toBeInTheDocument();
expect(screen.getByTestId('ws-tab-chat')).toHaveAttribute('aria-selected', 'true');
});
it('seam (b): the chat tab renders the provided chatSlot instead of the placeholder', async () => {
render(
<WorkspaceDesktopApp
workspaceId="ws-1" workspaceName="Acme"
activeTab="chat" chatSlot={<div data-testid="chat-slot-stub" />}
/>,
);
expect(await screen.findByTestId('chat-slot-stub')).toBeInTheDocument();
expect(screen.queryByTestId('ws-chat-tab-open')).not.toBeInTheDocument();
});
it('seam (b): without chatSlot the original deep-link placeholder is preserved', async () => {
render(
<WorkspaceDesktopApp workspaceId="ws-1" workspaceName="Acme" activeTab="chat" />,
);
expect(await screen.findByTestId('ws-chat-tab-open')).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,245 @@
/**
* UX Refactor v2.1 P1a — pins the §1.1 appId→route table (routeFor), the §2.2
* search-result retarget (routeForSearchResult, total over NAVIGABLE_TYPES),
* the queryString deep-link carrier, the §2.1.2 nav active-state matcher, and
* the §1.3 dock-tiers `route` field invariant (every nav entry's route agrees
* with routeFor).
*/
import { describe, it, expect } from 'vitest';
import {
APP_ROUTES,
matchNavRoute,
queryString,
routeFor,
routeForSearchResult,
} from '@/lib/routes';
import {
TIER_DOCK_CONFIG,
getDockForTier,
type AppId,
type DockEntry,
} from '@/lib/dock-tiers';
/** Every AppId in the union (dock-tiers.ts:7-18) — keep in sync; 28 ids. */
const ALL_APP_IDS: 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',
'workspace-desktop', 'mcp-hub',
];
describe('routeFor — §1.1 table', () => {
it('maps every static AppId exactly per the table (22 routed ids)', () => {
const expected: Record<string, string> = {
home: '/home',
memory: '/memory',
artifacts: '/artifacts',
files: '/files',
agents: '/agents',
'scheduled-jobs': '/automations',
capabilities: '/skills',
connectors: '/connectors',
'mcp-hub': '/mcps',
marketplace: '/marketplace',
launcher: '/launcher',
room: '/room',
'waggle-dance': '/waggle-dance',
approvals: '/approvals',
governance: '/team',
settings: '/settings',
vault: '/settings/vault',
profile: '/settings/profile',
cockpit: '/settings/mission-control',
timeline: '/settings/timeline',
events: '/settings/events',
telemetry: '/settings/usage',
};
for (const [appId, route] of Object.entries(expected)) {
expect(routeFor(appId as AppId), appId).toBe(route);
}
expect(Object.keys(expected)).toHaveLength(22);
});
it('retargets the 4 KILLED ids per §2.2 (dashboard/voice/mission-control → /home, backup → /settings?tab=backup)', () => {
expect(routeFor('dashboard')).toBe('/home');
expect(routeFor('voice')).toBe('/home');
expect(routeFor('mission-control')).toBe('/home');
expect(routeFor('backup')).toBe('/settings?tab=backup');
});
it('parameterizes chat → /workspaces/:id/chat and workspace-desktop → /workspaces/:id', () => {
expect(routeFor('chat', { activeWorkspaceId: 'ws-1' })).toBe('/workspaces/ws-1/chat');
expect(routeFor('workspace-desktop', { activeWorkspaceId: 'ws-1' })).toBe('/workspaces/ws-1');
});
it('falls back to /home when there is no active workspace (§1.3)', () => {
expect(routeFor('chat')).toBe('/home');
expect(routeFor('chat', {})).toBe('/home');
expect(routeFor('chat', { activeWorkspaceId: null })).toBe('/home');
expect(routeFor('workspace-desktop')).toBe('/home');
// 'local-default' is the pre-fetch placeholder, never a real route param (§3.3).
expect(routeFor('chat', { activeWorkspaceId: 'local-default' })).toBe('/home');
expect(routeFor('workspace-desktop', { activeWorkspaceId: 'local-default' })).toBe('/home');
});
it('is total over all 28 AppIds (never throws, never returns empty)', () => {
expect(ALL_APP_IDS).toHaveLength(28);
for (const appId of ALL_APP_IDS) {
const route = routeFor(appId, { activeWorkspaceId: 'ws-x' });
expect(route, appId).toMatch(/^\//);
}
});
it('Ctrl+Shift+0/4 shortcut ids resolve per §2.2 (0:dashboard → /home, 4:cockpit → /settings/mission-control)', () => {
expect(routeFor('dashboard')).toBe('/home');
expect(routeFor('cockpit')).toBe('/settings/mission-control');
});
});
describe('routeForSearchResult — §2.2 row 1', () => {
it('workspace: → /workspaces/:id', () => {
expect(routeForSearchResult('workspace', 'workspace:ws-1')).toBe('/workspaces/ws-1');
});
it('session: → /workspaces/:ws/chat?session=:sid (two segments after the prefix)', () => {
expect(routeForSearchResult('session', 'session:ws-1:sess-9')).toBe('/workspaces/ws-1/chat?session=sess-9');
});
it('session: without a session segment still lands on the chat tab', () => {
expect(routeForSearchResult('session', 'session:ws-1')).toBe('/workspaces/ws-1/chat');
});
it('session: with no workspace segment is a no-op (parity with Desktop.tsx:261-269)', () => {
expect(routeForSearchResult('session', 'session:')).toBeNull();
});
it('memory:/skill:/connector:/mcp: → their hub routes', () => {
expect(routeForSearchResult('memory', 'memory:m-1')).toBe('/memory');
expect(routeForSearchResult('skill', 'skill:my-skill')).toBe('/skills');
expect(routeForSearchResult('connector', 'connector:slack')).toBe('/connectors');
expect(routeForSearchResult('mcp', 'mcp:github')).toBe('/mcps');
});
it('command: falls back to routeFor(appId), incl. the chat special-case through ctx', () => {
expect(routeForSearchResult('command', 'command:settings')).toBe('/settings');
expect(routeForSearchResult('command', 'command:scheduled-jobs')).toBe('/automations');
expect(routeForSearchResult('command', 'command:chat', { activeWorkspaceId: 'ws-1' })).toBe('/workspaces/ws-1/chat');
expect(routeForSearchResult('command', 'command:chat')).toBe('/home');
});
it('command: with an unknown app name is a no-op', () => {
expect(routeForSearchResult('command', 'command:not-an-app')).toBeNull();
});
it('person: → null no-op (server does not federate person yet — routes/command.ts:22-24)', () => {
expect(routeForSearchResult('person', 'person:p-1')).toBeNull();
});
it('is total over NAVIGABLE_TYPES (CommandCenter.tsx:66-68) — no throw on any of them', () => {
const navigableTypes = ['workspace', 'memory', 'session', 'person', 'command'];
for (const type of navigableTypes) {
expect(() => routeForSearchResult(type, `${type}:x`)).not.toThrow();
}
});
it('unknown result types are a no-op', () => {
expect(routeForSearchResult('artifact', 'artifact:a-1')).toBeNull();
expect(routeForSearchResult('', '')).toBeNull();
});
});
describe('queryString — §2.3 deep-link carrier', () => {
it('returns an empty string for empty params', () => {
expect(queryString({})).toBe('');
});
it('serializes tab + automationId (Journey 16 payload)', () => {
expect(queryString({ tab: 'logs' })).toBe('?tab=logs');
expect(queryString({ tab: 'logs', automationId: 'auto-1' })).toBe('?tab=logs&automationId=auto-1');
});
it('URL-encodes values', () => {
expect(queryString({ automationId: 'a b' })).toBe('?automationId=a+b');
});
it('serializes the reserved session param (§1.1 /workspaces row)', () => {
expect(queryString({ session: 'sess-1' })).toBe('?session=sess-1');
});
it('serializes the filter param (P2/J08 — Memory Center needs-review deep link)', () => {
expect(queryString({ filter: 'unreviewed' })).toBe('?filter=unreviewed');
expect(queryString({ tab: 'memories', filter: 'unreviewed' })).toBe('?tab=memories&filter=unreviewed');
});
});
describe('matchNavRoute — §2.1.2 active-state prefix match', () => {
const navRoutes = ['/home', '/workspaces', '/memory', '/settings', '/settings/vault', '/settings/usage'];
it('matches exact routes', () => {
expect(matchNavRoute('/memory', navRoutes)).toBe('/memory');
});
it('matches by path prefix (chat tab under the /workspaces family)', () => {
expect(matchNavRoute('/workspaces/ws-1/chat', navRoutes)).toBe('/workspaces');
});
it('longest prefix wins — /settings/vault activates Vault, not Settings', () => {
expect(matchNavRoute('/settings/vault', navRoutes)).toBe('/settings/vault');
expect(matchNavRoute('/settings', navRoutes)).toBe('/settings');
// Nested System surface with no nav entry of its own falls back to /settings.
expect(matchNavRoute('/settings/profile', navRoutes)).toBe('/settings');
});
it('does not match on partial segment names', () => {
expect(matchNavRoute('/memoryx', navRoutes)).toBeNull();
});
it('returns null when nothing matches', () => {
expect(matchNavRoute('/nowhere', navRoutes)).toBeNull();
});
});
describe('dock-tiers route field — §1.3 invariant', () => {
function flattenAppEntries(entries: DockEntry[]): DockEntry[] {
const out: DockEntry[] = [];
for (const e of entries) {
if (e.type === 'app') out.push(e);
if (e.type === 'zone-parent' && e.children) {
out.push(...e.children.filter(c => c.type === 'app'));
}
}
return out;
}
it('every app entry in every UI tier carries a route that agrees with routeFor', () => {
for (const tier of ['simple', 'professional', 'power', 'admin'] as const) {
for (const entry of flattenAppEntries(TIER_DOCK_CONFIG[tier])) {
expect(entry.route, `${tier}/${entry.key} missing route`).toBeTruthy();
if (entry.appId === 'chat') {
// Parameterized: the field carries the prefix family for active-state
// matching; clicks resolve through routeFor('chat', ctx) (§2.3).
expect(entry.route).toBe('/workspaces');
} else {
expect(entry.route, `${tier}/${entry.key}`).toBe(routeFor(entry.appId!));
}
}
}
});
it('billing-tier filtering still applies to nav data (Approvals/Team hidden below TEAMS — D5)', () => {
const free = flattenAppEntries(getDockForTier('power', 'FREE'));
const teams = flattenAppEntries(getDockForTier('power', 'TEAMS'));
expect(free.some(e => e.appId === 'approvals')).toBe(false);
expect(free.some(e => e.appId === 'governance')).toBe(false);
expect(teams.some(e => e.appId === 'approvals')).toBe(true);
expect(teams.some(e => e.appId === 'governance')).toBe(true);
});
it('APP_ROUTES has no entry for the parameterized ids (function-not-record, §2.3)', () => {
expect('chat' in APP_ROUTES).toBe(false);
expect('workspace-desktop' in APP_ROUTES).toBe(false);
});
});

View File

@@ -0,0 +1,202 @@
/**
* P1a Stage B — §3.3 `waggle-window-state-v1` migration (acceptance check 6):
* populated key → salvaged route + chat state + key removed; corrupt value →
* /home + key removed, no throw; 'local-default' placeholder → /home + the
* §3.3.3 re-key contract; multi-window same-workspace → last-write-wins.
*/
import { describe, it, expect, beforeEach } from 'vitest';
import {
bootWindowStateMigration,
computeWindowStateMigration,
indexLandingRoute,
resetWindowStateMigrationForTests,
runWindowStateMigration,
WINDOW_STATE_KEY,
type LegacyWindowState,
} from '@/lib/window-state-migration';
import {
CHAT_STATE_KEY,
loadChatEntries,
rekeyLocalDefaultChatState,
} from '@/hooks/useChatWidgetState';
function win(over: Partial<LegacyWindowState> = {}): LegacyWindowState {
return {
instanceId: `i-${Math.random()}`, appId: 'home',
zIndex: 10, minimized: false, cascadeOffset: 0,
...over,
};
}
function setLegacy(windows: LegacyWindowState[]): void {
localStorage.setItem(WINDOW_STATE_KEY, JSON.stringify({ version: 1, windows }));
}
beforeEach(() => {
localStorage.clear();
resetWindowStateMigrationForTests();
});
describe('runWindowStateMigration (§3.3)', () => {
it('salvages the highest-zIndex non-minimized window as the initial route, salvages chat state, and removes the key', () => {
setLegacy([
win({ appId: 'memory', zIndex: 5 }),
win({
appId: 'chat', workspaceId: 'ws-1', zIndex: 9,
personaId: 'coder', autonomyLevel: 'trusted', autonomyExpiresAt: null,
}),
]);
const result = runWindowStateMigration();
expect(result.initialRoute).toBe('/workspaces/ws-1/chat');
expect(loadChatEntries()['ws-1']).toMatchObject({
personaId: 'coder', personaLabel: 'Coder',
autonomyLevel: 'trusted', autonomyExpiresAt: null,
});
expect(localStorage.getItem(WINDOW_STATE_KEY)).toBeNull();
expect(localStorage.getItem(CHAT_STATE_KEY)).toContain('ws-1');
});
it('skips minimized windows for the route salvage (all-minimized → /home)', () => {
setLegacy([
win({ appId: 'capabilities', zIndex: 99, minimized: true }),
win({ appId: 'scheduled-jobs', zIndex: 3 }),
]);
expect(runWindowStateMigration().initialRoute).toBe('/automations');
setLegacy([win({ appId: 'memory', zIndex: 1, minimized: true })]);
expect(runWindowStateMigration().initialRoute).toBe('/home');
});
it('routes killed ids through the §2.2 retargets and workspace-desktop to /workspaces/:id', () => {
setLegacy([win({ appId: 'dashboard', zIndex: 4 })]);
expect(runWindowStateMigration().initialRoute).toBe('/home');
setLegacy([win({ appId: 'workspace-desktop', workspaceId: 'ws-7', zIndex: 4 })]);
expect(runWindowStateMigration().initialRoute).toBe('/workspaces/ws-7');
});
it('corrupt value → /home, key removed, no throw, no chat state', () => {
localStorage.setItem(WINDOW_STATE_KEY, '{not json');
let result: ReturnType<typeof runWindowStateMigration> | undefined;
expect(() => { result = runWindowStateMigration(); }).not.toThrow();
expect(result!.initialRoute).toBe('/home');
expect(result!.chatState).toEqual({});
expect(localStorage.getItem(WINDOW_STATE_KEY)).toBeNull();
expect(localStorage.getItem(CHAT_STATE_KEY)).toBeNull();
});
it('wrong version / malformed shape → /home, key removed', () => {
localStorage.setItem(WINDOW_STATE_KEY, JSON.stringify({ version: 2, windows: [win()] }));
expect(runWindowStateMigration().initialRoute).toBe('/home');
expect(localStorage.getItem(WINDOW_STATE_KEY)).toBeNull();
localStorage.setItem(WINDOW_STATE_KEY, JSON.stringify({ version: 1, windows: 'nope' }));
expect(runWindowStateMigration().initialRoute).toBe('/home');
expect(localStorage.getItem(WINDOW_STATE_KEY)).toBeNull();
});
it('absent key → /home and nothing written', () => {
const result = runWindowStateMigration();
expect(result.initialRoute).toBe('/home');
expect(result.chatState).toEqual({});
expect(localStorage.getItem(CHAT_STATE_KEY)).toBeNull();
});
it("'local-default'-stamped chat → /home, entry written as-is, then re-keyed by the store (§3.3.3)", () => {
setLegacy([
win({ appId: 'chat', workspaceId: 'local-default', personaId: 'writer', zIndex: 99 }),
]);
const result = runWindowStateMigration();
expect(result.initialRoute).toBe('/home');
expect(loadChatEntries()['local-default']).toMatchObject({ personaId: 'writer' });
// The re-key contract: when the store first sees the real workspace list,
// the placeholder entry moves onto the first real workspace.
rekeyLocalDefaultChatState('ws-first');
expect(loadChatEntries()['local-default']).toBeUndefined();
expect(loadChatEntries()['ws-first']).toMatchObject({ personaId: 'writer' });
});
it('multiple chat windows on one workspace collapse last-write-wins', () => {
setLegacy([
win({ appId: 'chat', workspaceId: 'ws-1', personaId: 'coder', autonomyLevel: 'yolo', autonomyExpiresAt: 123, zIndex: 1 }),
win({ appId: 'chat', workspaceId: 'ws-1', personaId: 'writer', zIndex: 2 }),
]);
const { chatState } = runWindowStateMigration();
const expected = {
personaId: 'writer', personaLabel: 'Writer',
autonomyLevel: 'normal', autonomyExpiresAt: null,
};
expect(chatState['ws-1']).toEqual(expected);
expect(loadChatEntries()['ws-1']).toEqual(expected);
});
});
describe('computeWindowStateMigration (pure)', () => {
it('drops chat windows without a workspaceId and ignores unknown appIds for routing', () => {
const { initialRoute, chatState } = computeWindowStateMigration([
win({ appId: 'chat', zIndex: 50 }), // no workspaceId → /home route, no entry
win({ appId: 'not-an-app', zIndex: 99 }),
]);
expect(initialRoute).toBe('/home');
expect(chatState).toEqual({});
});
it("stamps a plain chat window with an explicit autonomyLevel:'normal' marker so P4 inheritance treats it as seen (restored-window parity)", () => {
const { chatState } = computeWindowStateMigration([
win({ appId: 'chat', workspaceId: 'ws-plain' }),
]);
expect(chatState).toHaveProperty('ws-plain');
// The marker (NOT a bare empty entry) is what blocks P4 retro-inheritance:
// the inheritance gate is autonomy-specific, so a persona-only live write
// stays inheritable while migrated chats do not (review finding).
expect(chatState['ws-plain']).toEqual({ autonomyLevel: 'normal', autonomyExpiresAt: null });
});
});
describe('bootWindowStateMigration + indexLandingRoute (Stage C boot wrapper)', () => {
it('index entry: the salvaged route is served exactly once, /home after', () => {
setLegacy([win({ appId: 'memory', zIndex: 5 })]);
bootWindowStateMigration('/');
// Side effects ran at boot regardless of route consumption.
expect(localStorage.getItem(WINDOW_STATE_KEY)).toBeNull();
expect(indexLandingRoute()).toBe('/memory');
// Typing '/' again mid-session must not replay the salvage.
expect(indexLandingRoute()).toBe('/home');
});
it('deep-link entry wins: salvage side effects still run but the route is never applied (acceptance check 2)', () => {
setLegacy([
win({ appId: 'chat', workspaceId: 'ws-1', personaId: 'coder', zIndex: 9 }),
]);
bootWindowStateMigration('/skills');
// §3.3 steps 3-4 ran (chat salvage + key removal)…
expect(localStorage.getItem(WINDOW_STATE_KEY)).toBeNull();
expect(loadChatEntries()['ws-1']).toMatchObject({ personaId: 'coder' });
// …but a later visit to '/' lands on /home, not the salvaged chat route.
expect(indexLandingRoute()).toBe('/home');
});
it('boot is idempotent — a second call does not re-run the migration', () => {
bootWindowStateMigration('/');
// A key written AFTER boot must not be consumed by a re-entrant call.
setLegacy([win({ appId: 'memory', zIndex: 5 })]);
bootWindowStateMigration('/');
expect(localStorage.getItem(WINDOW_STATE_KEY)).not.toBeNull();
expect(indexLandingRoute()).toBe('/home');
});
it('indexLandingRoute before boot degrades to /home', () => {
expect(indexLandingRoute()).toBe('/home');
});
});

View File

@@ -0,0 +1,81 @@
/**
* P1a review finding — WorkspaceRoute URL→shell sync (§2.1: the URL is the
* single source of truth). activeWorkspaceId is parallel state only updated
* through explicit selectWorkspace call sites; two sanctioned navigation
* paths bypass all of them (typed deep links — W2A: useWorkspaces no longer
* auto-selects data[0], so this sync also persists the deep link — and browser
* Back/Forward). WorkspaceRoute must reconcile the
* routed :workspaceId into shell state so shell-global surfaces (StatusBar,
* PersonaSwitcher, Ctrl+Shift+N / nav-Chat) act on the on-screen workspace.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, cleanup } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
const mocks = vi.hoisted(() => ({
shell: {
workspaces: [
{ id: 'ws-a', name: 'Alpha' },
{ id: 'ws-b', name: 'Beta' },
],
activeWorkspaceId: null as string | null,
selectWorkspace: vi.fn(),
},
}));
vi.mock('@/providers/ShellContext', () => ({
useShell: () => mocks.shell,
}));
// The route's render target is pinned elsewhere (p1a-chat-state §5.2 tests);
// here only the sync side effect is under test, so the heavy surfaces stub out.
vi.mock('@/components/os/apps/WorkspaceDesktopApp', () => ({
default: () => <div data-testid="wsd-stub" />,
}));
vi.mock('@/components/os/ChatHost', () => ({
default: () => null,
ChatSlot: () => <div data-testid="chat-slot-stub" />,
}));
import WorkspaceRoute from '@/routes/WorkspaceRoute';
function renderAt(path: string) {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="workspaces/:workspaceId/:tab?" element={<WorkspaceRoute />} />
</Routes>
</MemoryRouter>,
);
}
beforeEach(() => {
vi.clearAllMocks();
mocks.shell.activeWorkspaceId = null;
});
afterEach(() => cleanup());
describe('WorkspaceRoute URL→shell sync (review finding)', () => {
it('syncs the routed workspace into shell state when it differs from activeWorkspaceId', () => {
mocks.shell.activeWorkspaceId = 'ws-b'; // e.g. Back/Forward landed on A while B is "active"
renderAt('/workspaces/ws-a/chat');
expect(mocks.shell.selectWorkspace).toHaveBeenCalledWith('ws-a');
});
it('syncs on a typed deep link before the workspace fetch settles (activeWorkspaceId null)', () => {
mocks.shell.activeWorkspaceId = null; // fresh tab, useWorkspaces not resolved yet
renderAt('/workspaces/ws-b/chat');
expect(mocks.shell.selectWorkspace).toHaveBeenCalledWith('ws-b');
});
it('does not re-select when the routed workspace is already active', () => {
mocks.shell.activeWorkspaceId = 'ws-a';
renderAt('/workspaces/ws-a');
expect(mocks.shell.selectWorkspace).not.toHaveBeenCalled();
});
it("never syncs the 'local-default' pre-fetch placeholder", () => {
mocks.shell.activeWorkspaceId = 'ws-a';
renderAt('/workspaces/local-default');
expect(mocks.shell.selectWorkspace).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,462 @@
/**
* P1b D3 — Stage B boot-path surface contracts over a mocked adapter:
*
* - ShellContext tier: a failed getTier touches NEITHER billingTier NOR
* trialInfo (the severity-critical silent-FREE class), tierResolved stays
* false, and the tier revalidates on connect-settled.
* - useBilling: failure keeps tierResolved=false (Billing tab renders the
* unresolved state, never 'FREE' as fact).
* - useWorkspaces: failure sets the (previously dead) error channel, keeps
* a previously-good list, and recovers on connect-settled.
* - useChat: a thrown AdapterHttpError-shaped failure renders a status-true
* error block ('Backend is offline' reserved for network errors); the
* tier-403 copy defers to the UpgradeModal; empty-messages race guarded.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act, waitFor, cleanup } from '@testing-library/react';
import { CONNECT_SETTLED_EVENT } from '@/hooks/useRevalidateOnError';
const mocks = vi.hoisted(() => ({
adapter: {
connect: vi.fn().mockResolvedValue(undefined),
getTier: vi.fn(),
getWorkspaces: vi.fn(),
getPermissions: vi.fn().mockResolvedValue({ defaultAutonomy: 'normal', externalGates: {} }),
getAgentStatus: vi.fn().mockResolvedValue({ active: 0, agents: [] }),
getNotificationHistory: vi.fn().mockResolvedValue([]),
subscribeNotifications: vi.fn().mockReturnValue(() => {}),
getSystemHealth: vi.fn().mockResolvedValue({ status: 'ok' }),
getHistory: vi.fn().mockResolvedValue([]),
sendMessage: vi.fn(),
getSessions: vi.fn().mockResolvedValue([]),
getIdentity: vi.fn(),
searchMemory: vi.fn(),
getMemoryStats: vi.fn(),
fetchRaw: vi.fn(),
getSettings: vi.fn(),
getTelemetryStatus: vi.fn(),
getTeamStatus: vi.fn(),
getServerUrl: vi.fn(),
// PR5: Settings opens on the Models tab → ModelGate fetches these on mount.
getProviders: vi.fn(),
getLocalInferenceStatus: vi.fn(),
// MODEL-GATE: the mount probe calls these too — absent, the probe's async
// closure throws (TypeError: not a function) as an UNHANDLED rejection that
// poisons unrelated tests in the full-suite run. configured:false = the
// probe's honest "nothing to check" idle path.
probeModel: vi.fn().mockResolvedValue({ configured: false }),
probeProvider: vi.fn().mockResolvedValue({ configured: false, valid: false, verified: false }),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
/** AdapterHttpError stand-in — the real class is mocked away with the module,
* so consumers must duck-type on error.name (that is part of the contract). */
function httpError(status: number, body: unknown, message: string) {
const e = new Error(message) as Error & { status: number; body: unknown };
e.name = 'AdapterHttpError';
e.status = status;
e.body = body;
return e;
}
const settleConnect = () =>
act(() => { window.dispatchEvent(new CustomEvent(CONNECT_SETTLED_EVENT, { detail: { connected: true } })); });
afterEach(() => { cleanup(); vi.clearAllMocks(); });
// ── useWorkspaces ──────────────────────────────────────────────────────────
describe('useWorkspaces (P1b)', () => {
it('failure sets the error channel and keeps the previous list; connect-settled recovers', async () => {
const { useWorkspaces } = await import('@/hooks/useWorkspaces');
mocks.adapter.getWorkspaces.mockResolvedValueOnce([{ id: 'w1', name: 'Alpha' }]);
const { result } = renderHook(() => useWorkspaces());
await waitFor(() => expect(result.current.workspaces).toHaveLength(1));
mocks.adapter.getWorkspaces.mockRejectedValueOnce(httpError(401, { code: 'INVALID_TOKEN' }, 'Unauthorized'));
await act(async () => { await result.current.refresh(); });
expect(result.current.error).toBe('Unauthorized');
expect(result.current.workspaces).toHaveLength(1); // previous list preserved
mocks.adapter.getWorkspaces.mockResolvedValueOnce([{ id: 'w1', name: 'Alpha' }, { id: 'w2', name: 'Beta' }]);
settleConnect();
await waitFor(() => expect(result.current.workspaces).toHaveLength(2));
expect(result.current.error).toBeNull();
});
});
// ── useBilling ─────────────────────────────────────────────────────────────
describe('useBilling (P1b D3-4)', () => {
it('failure keeps tierResolved=false and surfaces the error — FREE default is never presented as fact', async () => {
const { useBilling } = await import('@/hooks/useBilling');
mocks.adapter.getTier.mockRejectedValue(httpError(401, {}, 'Unauthorized'));
const { result } = renderHook(() => useBilling());
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.tierResolved).toBe(false);
expect(result.current.error).toBe('Unauthorized');
});
it('connect-settled revalidates an unresolved tier to the real plan', async () => {
const { useBilling } = await import('@/hooks/useBilling');
mocks.adapter.getTier.mockRejectedValueOnce(httpError(401, {}, 'Unauthorized'));
const { result } = renderHook(() => useBilling());
await waitFor(() => expect(result.current.loading).toBe(false));
expect(result.current.tierResolved).toBe(false);
mocks.adapter.getTier.mockResolvedValue({ tier: 'TEAMS', capabilities: {}, usage: {} });
settleConnect();
await waitFor(() => expect(result.current.tierResolved).toBe(true));
expect(result.current.tier).toBe('TEAMS');
});
});
// ── ShellContext tier (the severity-critical silent-FREE class) ────────────
describe('ShellContext tier (P1b D3-4)', () => {
beforeEach(() => {
window.localStorage.clear();
});
async function renderShell() {
const { ShellProvider, useShell } = await import('@/providers/ShellContext');
const wrapper = ({ children }: { children: React.ReactNode }) => <ShellProvider>{children}</ShellProvider>;
return renderHook(() => useShell(), { wrapper });
}
/** Seed a completed-wizard onboarding blob so the trial gate's
* onboardingCompleted precondition is met. `completedAt` past the 10-min
* quiet window by default. */
function seedOnboardingCompleted(completedAt = Date.now() - 11 * 60_000) {
window.localStorage.setItem(
'waggle:onboarding',
JSON.stringify({ completed: true, step: 7, tier: 'power', completedAt }),
);
// Wave-3 modal coordination: the paywall defers while the login briefing
// is eligible to show. These tests exercise the paywall itself, so arrange
// a dismissed briefing (as a returning user who closed it would have).
window.localStorage.setItem('waggle:login-briefing-dismissed', 'true');
}
it('failed getTier touches neither billingTier nor trialInfo; tierResolved stays false', async () => {
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.getTier.mockRejectedValue(httpError(401, { code: 'MISSING_TOKEN' }, 'Unauthorized'));
const { result } = await renderShell();
await waitFor(() => expect(result.current.tierError).toBe('Unauthorized'));
expect(result.current.billingTier).toBe('FREE'); // fail-closed capability default…
expect(result.current.tierResolved).toBe(false); // …never presented as resolved fact
expect(result.current.trialInfo).toEqual({}); // trial countdown not clobbered
expect(result.current.showTrialExpired).toBe(false);
});
it('a paying user is not reset to FREE by a transient failure, and recovers on connect-settled', async () => {
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.getTier.mockResolvedValueOnce({
tier: 'TEAMS', trialDaysRemaining: undefined, trialExpired: false, capabilities: {}, usage: {},
});
const { result } = await renderShell();
await waitFor(() => expect(result.current.billingTier).toBe('TEAMS'));
expect(result.current.tierResolved).toBe(true);
// Transient failure (e.g. sidecar restart mid-refresh): state must hold.
mocks.adapter.getTier.mockRejectedValueOnce(httpError(401, {}, 'Unauthorized'));
await act(async () => { await result.current.refreshTier(); });
expect(result.current.billingTier).toBe('TEAMS');
expect(result.current.tierError).toBe('Unauthorized');
// Recovery: connect-settled revalidates while errored.
mocks.adapter.getTier.mockResolvedValue({ tier: 'TEAMS', capabilities: {}, usage: {} });
settleConnect();
await waitFor(() => expect(result.current.tierError).toBeNull());
});
// ── F1: trial-expired auto-open gate ──
it('auto-opens the paywall once and stamps the snooze when trial expired + onboarding done', async () => {
seedOnboardingCompleted();
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.getTier.mockResolvedValue({ tier: 'TRIAL', trialExpired: true, capabilities: {}, usage: {} });
const { result } = await renderShell();
await waitFor(() => expect(result.current.showTrialExpired).toBe(true));
expect(window.localStorage.getItem('waggle:trial-expired-last-shown-at')).not.toBeNull();
});
it('does NOT auto-open within the post-onboarding quiet window', async () => {
seedOnboardingCompleted(Date.now() - 60_000); // completed 1 min ago
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.getTier.mockResolvedValue({ tier: 'TRIAL', trialExpired: true, capabilities: {}, usage: {} });
const { result } = await renderShell();
await waitFor(() => expect(result.current.tierResolved).toBe(true));
expect(result.current.showTrialExpired).toBe(false);
});
it('a dismissed paywall stays closed on later same-session refreshTier re-runs', async () => {
seedOnboardingCompleted();
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.getTier.mockResolvedValue({ tier: 'TRIAL', trialExpired: true, capabilities: {}, usage: {} });
const { result } = await renderShell();
await waitFor(() => expect(result.current.showTrialExpired).toBe(true));
act(() => { result.current.setShowTrialExpired(false); });
await act(async () => { await result.current.refreshTier(); });
expect(result.current.showTrialExpired).toBe(false);
});
it('a fresh session (reload) within the 7-day snooze does not auto-open', async () => {
const now = Date.now();
seedOnboardingCompleted(now - 2 * 24 * 60 * 60_000);
window.localStorage.setItem('waggle:trial-expired-last-shown-at', String(now - 24 * 60 * 60_000));
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.getTier.mockResolvedValue({ tier: 'TRIAL', trialExpired: true, capabilities: {}, usage: {} });
const { result } = await renderShell();
await waitFor(() => expect(result.current.tierResolved).toBe(true));
expect(result.current.showTrialExpired).toBe(false);
});
});
// ── LoginBriefing failure ≠ Day-0 ──────────────────────────────────────────
describe('LoginBriefing (P1b)', () => {
async function renderBriefing() {
const { default: LoginBriefing } = await import('@/components/os/overlays/LoginBriefing');
const { ServiceProvider } = await import('@/providers/ServiceProvider');
const { TooltipProvider } = await import('@/components/ui/tooltip');
const { render, screen } = await import('@testing-library/react');
render(
<TooltipProvider>
<ServiceProvider>
<LoginBriefing onDismiss={() => {}} onOpenWorkspace={() => {}} />
</ServiceProvider>
</TooltipProvider>,
);
return screen;
}
it('batch failure renders the error state, NOT the Day-0 demo bubbles', async () => {
mocks.adapter.getIdentity.mockRejectedValue(new Error('no identity'));
mocks.adapter.searchMemory.mockRejectedValue(httpError(401, {}, 'Unauthorized'));
mocks.adapter.getMemoryStats.mockRejectedValue(httpError(401, {}, 'Unauthorized'));
mocks.adapter.getWorkspaces.mockRejectedValue(httpError(401, { code: 'MISSING_TOKEN' }, 'Unauthorized'));
const screen = await renderBriefing();
// Wave Q Lane A: a failed briefing degrades to the slim inline row (NOT a
// blocking modal). The behavioral contract — error state, never the Day-0
// demo bubbles — is unchanged; only the surface it renders on moved.
await waitFor(() => expect(screen.getByTestId('login-briefing-error')).toBeInTheDocument());
expect(screen.queryByTestId('login-briefing-empty-hook')).toBeNull();
expect(screen.getByTestId('login-briefing-error').textContent).toContain('Briefing unavailable');
// Generous budget: full framer-motion render under parallel suite load.
}, 15000);
it('a genuinely empty (Day-0) account still gets the demo bubbles', async () => {
mocks.adapter.getIdentity.mockResolvedValue(null);
mocks.adapter.searchMemory.mockResolvedValue([]);
mocks.adapter.getMemoryStats.mockResolvedValue(null);
mocks.adapter.getWorkspaces.mockResolvedValue([]);
const screen = await renderBriefing();
await waitFor(() => expect(screen.getByTestId('login-briefing-empty-hook')).toBeInTheDocument());
expect(screen.queryByTestId('login-briefing-error')).toBeNull();
}, 15000);
it('RECOVERS: connect-settled after the backend returns replaces the error with the briefing', async () => {
mocks.adapter.getIdentity.mockRejectedValue(new Error('down'));
mocks.adapter.searchMemory.mockRejectedValue(httpError(401, {}, 'Unauthorized'));
mocks.adapter.getMemoryStats.mockRejectedValue(httpError(401, {}, 'Unauthorized'));
mocks.adapter.getWorkspaces.mockRejectedValue(httpError(401, {}, 'Unauthorized'));
const screen = await renderBriefing();
await waitFor(() => expect(screen.getByTestId('login-briefing-error')).toBeInTheDocument());
// Backend comes back; the bus settlement revalidates the errored briefing.
mocks.adapter.searchMemory.mockResolvedValue([]);
mocks.adapter.getMemoryStats.mockResolvedValue(null);
mocks.adapter.getWorkspaces.mockResolvedValue([]);
settleConnect();
await waitFor(() => expect(screen.queryByTestId('login-briefing-error')).toBeNull());
expect(screen.getByTestId('login-briefing-empty-hook')).toBeInTheDocument();
}, 15000);
});
// ── BackupApp 404→empty (fetchRaw migration pin) ───────────────────────────
describe('BackupApp (P1b)', () => {
it('a 404 metadata response renders the empty state, not the error panel', async () => {
mocks.adapter.fetchRaw.mockResolvedValue(
new Response(JSON.stringify({ error: 'no backups' }), { status: 404 }),
);
const { default: BackupApp } = await import('@/components/os/apps/BackupApp');
const { render, screen } = await import('@testing-library/react');
render(<BackupApp />);
await waitFor(() => expect(screen.getByText(/no backups yet/i)).toBeInTheDocument());
expect(screen.queryByText(/couldn.t load backups|retry/i)).toBeNull();
});
it('a 500 metadata response renders the retryable error, never the empty state', async () => {
mocks.adapter.fetchRaw.mockResolvedValue(
new Response(JSON.stringify({ error: 'boom' }), { status: 500 }),
);
const { default: BackupApp } = await import('@/components/os/apps/BackupApp');
const { render, screen } = await import('@testing-library/react');
render(<BackupApp />);
await waitFor(() => expect(screen.queryByText(/no backups yet/i)).toBeNull());
});
it('restore uses an in-app approval before posting backup data', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
mocks.adapter.fetchRaw
.mockResolvedValueOnce(new Response(JSON.stringify({ error: 'no backups' }), { status: 404 }))
.mockResolvedValueOnce(new Response(JSON.stringify({ filesRestored: 2 }), { status: 200 }));
const { default: BackupApp } = await import('@/components/os/apps/BackupApp');
const { render, screen, fireEvent } = await import('@testing-library/react');
render(<BackupApp />);
await screen.findByText(/no backups yet/i);
const file = new File(['backup-data'], 'team.waggle-backup', { type: 'application/octet-stream' });
fireEvent.change(screen.getByLabelText(/restore backup file/i), { target: { files: [file] } });
expect(confirmSpy).not.toHaveBeenCalled();
expect(mocks.adapter.fetchRaw).toHaveBeenCalledTimes(1);
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent(/restore backup/i);
expect(modal).toHaveTextContent(/team\.waggle-backup/i);
expect(modal).toHaveTextContent(/overwrite current data/i);
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.fetchRaw).toHaveBeenCalledWith(
'/api/restore',
expect.objectContaining({ method: 'POST' }),
));
await screen.findByText(/backup restored successfully \(2 files\)/i);
});
});
// ── SettingsApp tier-as-fact pins ──────────────────────────────────────────
describe('SettingsApp tier badges (P1b D3-4)', () => {
async function renderSettings() {
mocks.adapter.getSettings.mockResolvedValue({});
mocks.adapter.getTelemetryStatus.mockResolvedValue({ enabled: false });
mocks.adapter.getTeamStatus.mockResolvedValue({ connected: false });
mocks.adapter.getServerUrl.mockReturnValue('http://127.0.0.1:3333');
mocks.adapter.getProviders.mockResolvedValue({ providers: [], search: [], activeSearch: 'duckduckgo' });
mocks.adapter.getLocalInferenceStatus.mockResolvedValue({ servers: [], ollamaInstalled: false, totalLocalModels: 0 });
const { default: SettingsApp } = await import('@/components/os/apps/SettingsApp');
const { TooltipProvider } = await import('@/components/ui/tooltip');
const { MemoryRouter } = await import('react-router-dom');
const { render, screen, fireEvent } = await import('@testing-library/react');
// SettingsApp reads `?tab=` via useSearchParams (PR7a/D12) — needs a Router.
render(<MemoryRouter><TooltipProvider><SettingsApp /></TooltipProvider></MemoryRouter>);
// PR5 §11: Settings now opens on Models ("Models leads"). The tier card lives
// in General — navigate there for these tier-as-fact assertions.
fireEvent.click(await screen.findByRole('tab', { name: /general/i }));
return screen;
}
it('getTier failure: General tab never renders "FREE plan" as fact', async () => {
mocks.adapter.getTier.mockRejectedValue(httpError(401, {}, 'Unauthorized'));
const screen = await renderSettings();
await waitFor(() => expect(screen.getByText(/confirming plan/i)).toBeInTheDocument());
expect(screen.queryByText(/FREE plan/i)).toBeNull();
}, 15000);
it('resolved TEAMS tier renders the real plan in the General tab', async () => {
mocks.adapter.getTier.mockResolvedValue({ tier: 'TEAMS', capabilities: {}, usage: {} });
const screen = await renderSettings();
await waitFor(() => {
expect(screen.getAllByText(/Team plan/i).some((el) => el.textContent?.trim() === 'Team plan')).toBe(true);
});
}, 15000);
});
// ── useChat catch semantics ────────────────────────────────────────────────
describe('useChat error surfacing (P1b)', () => {
beforeEach(() => {
mocks.adapter.getHistory.mockResolvedValue([]);
});
async function sendFailing(err: unknown) {
const { useChat } = await import('@/hooks/useChat');
mocks.adapter.sendMessage.mockImplementation(async function* (): AsyncGenerator<never> {
throw err;
// eslint-disable-next-line no-unreachable
yield undefined as never;
});
const { result } = renderHook(() => useChat({ workspaceId: 'ws-1', sessionId: 'sess-1' }));
// Let the mount-time history fetch settle first — it resolves to [] and
// would otherwise clobber the messages pushed by sendMessage.
await act(async () => { await Promise.resolve(); });
await act(async () => { await result.current.sendMessage('hello'); });
return result;
}
it('HTTP failure renders a status-true error block, not the offline lie', async () => {
const result = await sendFailing(httpError(500, { error: 'boom' }, 'boom'));
const last = result.current.messages[result.current.messages.length - 1];
const errBlock = last.blocks?.find(b => b.type === 'error') as { message?: string } | undefined;
expect(errBlock?.message).toBe('Chat request failed (500): boom');
});
it('tier-403 copy defers to the UpgradeModal instead of duplicating the upsell', async () => {
const result = await sendFailing(httpError(403, { error: 'TIER_INSUFFICIENT', required: 'TEAMS' }, 'Needs TEAMS'));
const last = result.current.messages[result.current.messages.length - 1];
expect(last.content).toBe('This action needs a higher plan — see the upgrade window.');
});
it('network failure keeps the Backend-is-offline copy', async () => {
const result = await sendFailing(new TypeError('fetch failed'));
const last = result.current.messages[result.current.messages.length - 1];
expect(last.content).toBe('Backend is offline. Connect to a Waggle server to start chatting.');
});
// ── F2/F4: sendMessage success reporting + retryLastFailed ──
it('sendMessage resolves true on a clean stream, false on HTTP failure', async () => {
const { useChat } = await import('@/hooks/useChat');
const { result } = renderHook(() => useChat({ workspaceId: 'ws-1', sessionId: 'sess-1' }));
await act(async () => { await Promise.resolve(); });
mocks.adapter.sendMessage.mockImplementation(async function* () {
yield { type: 'done', data: { content: 'hi there' } };
});
let ok: boolean | void = undefined;
await act(async () => { ok = await result.current.sendMessage('hello'); });
expect(ok).toBe(true);
mocks.adapter.sendMessage.mockImplementation(async function* (): AsyncGenerator<never> {
throw httpError(500, { error: 'boom' }, 'boom');
// eslint-disable-next-line no-unreachable
yield undefined as never;
});
let failed: boolean | void = undefined;
await act(async () => { failed = await result.current.sendMessage('again'); });
expect(failed).toBe(false);
});
it('retryLastFailed drops the failed pair and re-issues the same content (no duplicate user bubble)', async () => {
const { useChat } = await import('@/hooks/useChat');
const { result } = renderHook(() => useChat({ workspaceId: 'ws-1', sessionId: 'sess-1' }));
await act(async () => { await Promise.resolve(); });
mocks.adapter.sendMessage.mockImplementationOnce(async function* (): AsyncGenerator<never> {
throw httpError(500, { error: 'boom' }, 'boom');
// eslint-disable-next-line no-unreachable
yield undefined as never;
});
await act(async () => { await result.current.sendMessage('hello'); });
expect(result.current.messages).toHaveLength(2); // user + assistant(error)
mocks.adapter.sendMessage.mockImplementationOnce(async function* () {
yield { type: 'done', data: { content: 'recovered' } };
});
await act(async () => {
result.current.retryLastFailed();
await new Promise(r => setTimeout(r, 0));
});
const users = result.current.messages.filter(m => m.role === 'user');
expect(users).toHaveLength(1);
expect(users[0].content).toBe('hello');
// retryLastFailed threads { retry: true } so the server strips the persisted failed pair.
expect(mocks.adapter.sendMessage).toHaveBeenLastCalledWith('ws-1', 'hello', 'sess-1', undefined, undefined, true);
});
});

View File

@@ -0,0 +1,323 @@
/**
* P2 (verify + J08) — Home Cockpit + Workspace Desktop surface contracts:
*
* - J08 (D6): the "N memories need review" banner renders from
* briefing.needsReviewCount and its CTA deep-links to the Memory Center
* "Needs review" filter via waggle:open-app {appId:'memory',
* filter:'unreviewed'}; absent at 0.
* - Greeting date renders as a human date, never the raw ISO string.
* - Workspace Desktop branches the whole-screen error on the P1b
* AdapterHttpError contract: 404 → "Workspace not found" (+ go-Home CTA),
* network → offline with a working Retry.
* - MemoryCenterTab consumes the deep-link filter on both paths (stash on
* cold mount; live event while mounted) and refetches with
* status='unreviewed'.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, waitFor, cleanup, fireEvent } from '@testing-library/react';
import { stashDeepLink } from '@/lib/app-deeplink';
import { DATE_LOCALE } from '@/lib/date-locale';
const mocks = vi.hoisted(() => ({
adapter: {
getHomeBriefing: vi.fn(),
getHomeOvernight: vi.fn(),
quickCapture: vi.fn(),
getWorkspaceContext: vi.fn(),
getWorkspaceState: vi.fn(),
getWorkspaceActivity: vi.fn(),
getTeamMembers: vi.fn(),
getWorkspaceFiles: vi.fn(),
getWorkspaceTasks: vi.fn().mockResolvedValue([]),
listMemories: vi.fn(),
patchMemory: vi.fn(),
archiveMemory: vi.fn(),
deleteMemoryById: vi.fn(),
mergeMemories: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/providers/ServiceProvider', () => ({ useService: () => ({ connecting: false, connected: true }) }));
vi.mock('@/hooks/useOfflineStatus', () => ({ useOfflineStatus: () => false }));
vi.mock('@/hooks/useRoomState', () => ({ useRoomState: () => ({ workspaceMap: new Map() }) }));
// WorkspaceActionsMenu (G1) reads ShellContext for patch/delete — these tests
// render screens bare, so stub the shell surface the menu needs.
vi.mock('@/providers/ShellContext', () => ({
useShell: () => ({ patchWorkspace: vi.fn().mockResolvedValue(true), deleteWorkspace: vi.fn().mockResolvedValue(true) }),
}));
/** AdapterHttpError stand-in — components duck-type on error.name + status. */
function httpError(status: number, message = `HTTP ${status}`) {
const e = new Error(message) as Error & { status: number };
e.name = 'AdapterHttpError';
e.status = status;
return e;
}
const RAW_ISO = '2026-06-11T07:42:13.512Z';
const briefing = (over: Record<string, unknown> = {}) => ({
greeting: "Good morning, Marko. Here's your day",
userName: 'Marko',
date: RAW_ISO,
recentWorkspaces: [],
suggestedActions: [],
upNext: [],
isFirstRun: false,
needsReviewCount: 0,
...over,
});
afterEach(() => { cleanup(); vi.clearAllMocks(); });
// ── Home Cockpit: J08 banner + date ────────────────────────────────────────
describe('HomeCockpit (P2)', () => {
async function renderHome(
b: ReturnType<typeof briefing>,
handlers: {
onContinue?: (workspaceId: string, sessionId?: string) => void;
onOpenWorkspaceDesktop?: (workspaceId: string) => void;
onCreateWorkspace?: () => void;
} = {},
) {
const { default: HomeCockpit } = await import('@/components/os/apps/HomeCockpit');
mocks.adapter.getHomeBriefing.mockResolvedValue(b);
mocks.adapter.getHomeOvernight.mockResolvedValue(null);
const onContinue = handlers.onContinue ?? vi.fn();
const onOpenWorkspaceDesktop = handlers.onOpenWorkspaceDesktop ?? vi.fn();
const onCreateWorkspace = handlers.onCreateWorkspace ?? vi.fn();
render(
<HomeCockpit
onContinue={onContinue}
onOpenWorkspaceDesktop={onOpenWorkspaceDesktop}
onCreateWorkspace={onCreateWorkspace}
/>,
);
await waitFor(() => expect(screen.getByTestId('home-cockpit')).toBeTruthy());
return { onContinue, onOpenWorkspaceDesktop, onCreateWorkspace };
}
it('renders the J08 review banner and deep-links to the Memory Center filter', async () => {
await renderHome(briefing({ needsReviewCount: 3 }));
const banner = screen.getByTestId('home-cockpit-review-banner');
// Scope-qualified copy ("from your imports") so the Home count can't read
// as contradicting the Memory Center's broader "awaiting your confirm" total.
expect(banner.textContent).toContain('3 memories from your imports need your review');
const events: Array<Record<string, unknown>> = [];
const spy = (e: Event) => events.push((e as CustomEvent).detail as Record<string, unknown>);
window.addEventListener('waggle:open-app', spy);
try {
fireEvent.click(screen.getByTestId('home-cockpit-review-cta'));
} finally {
window.removeEventListener('waggle:open-app', spy);
}
expect(events).toEqual([{ appId: 'memory', filter: 'unreviewed' }]);
});
it('omits the review banner at 0 (and on pre-P2 sidecars without the field)', async () => {
await renderHome(briefing({ needsReviewCount: undefined }));
expect(screen.queryByTestId('home-cockpit-review-banner')).toBeNull();
});
it('omits the Up next section when there are no items (zero or absent field)', async () => {
await renderHome(briefing({ upNext: [] }));
expect(screen.queryByTestId('home-cockpit-upnext')).toBeNull();
cleanup();
await renderHome(briefing({ upNext: undefined }));
expect(screen.queryByTestId('home-cockpit-upnext')).toBeNull();
});
it('renders the Up next section when at least one item exists', async () => {
await renderHome(briefing({
upNext: [{ id: 'e1', label: 'Weekly digest', kind: 'schedule', at: 'Jun 13, 9:00 AM' }],
}));
expect(screen.getByTestId('home-cockpit-upnext').textContent).toContain('Weekly digest');
});
it('renders the briefing date as a human date, not the raw ISO string', async () => {
await renderHome(briefing());
expect(screen.queryByText(RAW_ISO)).toBeNull();
// Locale-agnostic: assert the exact formatting call the component makes.
const expected = new Date(RAW_ISO).toLocaleDateString(DATE_LOCALE, {
weekday: 'long', month: 'long', day: 'numeric',
});
expect(screen.getByText(expected)).toBeTruthy();
});
it('renders the personal work-aware positioning in the shell', async () => {
await renderHome(briefing());
const positioning = screen.getByTestId('home-cockpit-positioning').textContent ?? '';
expect(positioning).toMatch(/personal AI workspace/i);
expect(positioning).toMatch(/remembers you/i);
expect(positioning).toMatch(/knows your projects/i);
expect(positioning).toMatch(/guides the next step/i);
});
it('scopes recent workspace card transitions to explicit properties', async () => {
await renderHome(briefing({
recentWorkspaces: [
{ id: 'launch', name: 'Launch Plan', group: 'Marketing', summary: 'Three decisions still need review.', lastActive: RAW_ISO, pendingCount: 3 },
],
}));
const card = screen.getByTestId('home-cockpit-ws-launch');
expect(card.className).not.toContain('transition-all');
expect(card.className).toContain('transition-[border-color,box-shadow,transform]');
});
it('promotes the best suggested action into one Start Here move', async () => {
const onContinue = vi.fn();
await renderHome(briefing({
recentWorkspaces: [
{ id: 'board', name: 'Board Update', group: 'Finance', summary: 'Variance narrative is half drafted.', lastActive: RAW_ISO, pendingCount: 1, continueSessionId: 'fallback-session' },
],
suggestedActions: [
{ label: 'Draft the churn explanation', workspaceId: 'board', sessionId: 'suggestion-session', kind: 'draft' },
],
}), { onContinue });
const startHere = screen.getByTestId('home-cockpit-start-here');
expect(startHere.textContent).toContain('Start here');
expect(startHere.textContent).toContain('Draft the churn explanation');
expect(startHere.textContent).toContain('Board Update');
expect(startHere.textContent).toContain('Because Waggle found this as the next useful move');
fireEvent.click(screen.getByTestId('home-cockpit-start-primary'));
expect(onContinue).toHaveBeenCalledWith('board', 'suggestion-session');
});
it('falls back to the most urgent workspace when no suggested action exists', async () => {
const onContinue = vi.fn();
await renderHome(briefing({
recentWorkspaces: [
{ id: 'quiet', name: 'Quiet Research', group: 'Research', summary: 'Archived notes are settled.', lastActive: '2026-06-09T09:00:00.000Z', pendingCount: 0 },
{ id: 'launch', name: 'Launch Plan', group: 'Marketing', summary: 'Three decisions still need review.', lastActive: '2026-06-12T09:00:00.000Z', pendingCount: 3, continueSessionId: 'launch-session' },
],
suggestedActions: [],
}), { onContinue });
const startHere = screen.getByTestId('home-cockpit-start-here');
expect(startHere.textContent).toContain('Review 3 pending items');
expect(startHere.textContent).toContain('Launch Plan');
expect(startHere.textContent).toContain('Because this workspace has unresolved decisions');
fireEvent.click(screen.getByTestId('home-cockpit-start-primary'));
expect(onContinue).toHaveBeenCalledWith('launch', 'launch-session');
});
});
// ── Workspace Desktop: error-state branching (P1b error contract) ──────────
describe('WorkspaceDesktopApp error states (P2)', () => {
async function renderDesktop() {
const { default: WorkspaceDesktopApp } = await import('@/components/os/apps/WorkspaceDesktopApp');
render(<WorkspaceDesktopApp workspaceId="w1" workspaceName="Alpha" />);
}
function mockFeedsOk() {
mocks.adapter.getWorkspaceState.mockResolvedValue(null);
mocks.adapter.getWorkspaceActivity.mockResolvedValue({ events: [] });
mocks.adapter.getTeamMembers.mockResolvedValue([]);
mocks.adapter.getWorkspaceFiles.mockResolvedValue([]);
}
it('404 renders "Workspace not found" with a go-Home CTA — not the offline state', async () => {
mocks.adapter.getWorkspaceContext.mockRejectedValue(httpError(404, 'Workspace not found'));
await renderDesktop();
await waitFor(() => expect(screen.getByTestId('ws-desktop-notfound')).toBeTruthy());
expect(screen.queryByTestId('ws-desktop-offline')).toBeNull();
const events: Array<Record<string, unknown>> = [];
const spy = (e: Event) => events.push((e as CustomEvent).detail as Record<string, unknown>);
window.addEventListener('waggle:open-app', spy);
try {
fireEvent.click(screen.getByTestId('ws-desktop-notfound-home'));
} finally {
window.removeEventListener('waggle:open-app', spy);
}
expect(events).toEqual([{ appId: 'home' }]);
});
it('403 still renders the permission state', async () => {
mocks.adapter.getWorkspaceContext.mockRejectedValue(httpError(403, 'Forbidden'));
await renderDesktop();
await waitFor(() => expect(screen.getByTestId('ws-desktop-permission-denied')).toBeTruthy());
});
it('network failure renders offline with a Retry that refetches', async () => {
mocks.adapter.getWorkspaceContext.mockRejectedValueOnce(new Error('fetch failed'));
mockFeedsOk();
await renderDesktop();
await waitFor(() => expect(screen.getByTestId('ws-desktop-offline')).toBeTruthy());
mocks.adapter.getWorkspaceContext.mockResolvedValueOnce({
workspace: { id: 'w1', name: 'Alpha', group: 'Personal', status: 'active' },
stats: { memoryCount: 0, sessionCount: 0, fileCount: 0 },
});
fireEvent.click(screen.getByTestId('ws-desktop-retry'));
await waitFor(() => expect(screen.getByTestId('ws-desktop-root')).toBeTruthy());
});
it('offline state revalidates on window focus (D3 plus-clause wiring)', async () => {
mocks.adapter.getWorkspaceContext.mockRejectedValueOnce(new Error('fetch failed'));
mockFeedsOk();
await renderDesktop();
await waitFor(() => expect(screen.getByTestId('ws-desktop-offline')).toBeTruthy());
mocks.adapter.getWorkspaceContext.mockResolvedValue({
workspace: { id: 'w1', name: 'Alpha', group: 'Personal', status: 'active' },
stats: { memoryCount: 0, sessionCount: 0, fileCount: 0 },
});
// Re-fire inside waitFor: revalidation is idempotent, and this absorbs the
// listener-attach timing between the error commit and the event.
await waitFor(() => {
fireEvent(window, new Event('focus'));
expect(screen.getByTestId('ws-desktop-root')).toBeTruthy();
});
});
});
// ── MemoryCenterTab: deep-link filter consumption ───────────────────────────
describe('MemoryCenterTab deep-link (P2/J08)', () => {
it('cold mount consumes a stashed filter and queries status=unreviewed', async () => {
const { default: MemoryCenterTab } = await import('@/components/os/apps/memory/MemoryCenterTab');
mocks.adapter.listMemories.mockResolvedValue([]);
stashDeepLink({ appId: 'memory', filter: 'unreviewed' });
render(<MemoryCenterTab />);
await waitFor(() => {
expect(mocks.adapter.listMemories).toHaveBeenCalledWith(
expect.objectContaining({ status: 'unreviewed' }),
);
});
});
it('applies a live waggle:open-app event while mounted', async () => {
const { default: MemoryCenterTab } = await import('@/components/os/apps/memory/MemoryCenterTab');
mocks.adapter.listMemories.mockResolvedValue([]);
render(<MemoryCenterTab />);
await waitFor(() => expect(mocks.adapter.listMemories).toHaveBeenCalled());
fireEvent(window, new CustomEvent('waggle:open-app', {
detail: { appId: 'memory', filter: 'unreviewed' },
}));
await waitFor(() => {
expect(mocks.adapter.listMemories).toHaveBeenCalledWith(
expect.objectContaining({ status: 'unreviewed' }),
);
});
});
it('ignores an invalid filter value', async () => {
const { default: MemoryCenterTab } = await import('@/components/os/apps/memory/MemoryCenterTab');
mocks.adapter.listMemories.mockResolvedValue([]);
stashDeepLink({ appId: 'memory', filter: 'drop-table' });
render(<MemoryCenterTab />);
await waitFor(() => expect(mocks.adapter.listMemories).toHaveBeenCalled());
expect(mocks.adapter.listMemories).not.toHaveBeenCalledWith(
expect.objectContaining({ status: 'drop-table' }),
);
});
});

View File

@@ -0,0 +1,84 @@
/**
* P2 regression lock — the ?forceWizard reset must fire ONCE per page load.
*
* Found by the acceptance-check-8 live run: loadState() also runs in the
* 'waggle:onboarding-sync' listener, so without the once-per-load latch every
* wizard save (e.g. workspace-create persisting workspaceId) triggered a sync
* reload that reset state to {completed:false, step:0} AND wiped the
* just-saved fields — onFinish then ran with a fallback `local-*` id and the
* chat seeding/navigation chain silently broke, stranding the user on /home.
*
* vi.resetModules() per test gives each test a fresh module-level latch.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act, cleanup } from '@testing-library/react';
const mocks = vi.hoisted(() => ({
adapter: {
// P4: the auto-complete effect keys on /api/onboarding/status now (the
// workspace count counted the boot-seeded default — clean-install skip).
getOnboardingStatus: vi.fn().mockResolvedValue({ completed: false }),
markOnboardingComplete: vi.fn().mockResolvedValue(undefined),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/lib/tauri-bindings', () => ({
isTauri: () => false,
isFirstLaunch: vi.fn().mockResolvedValue(true),
markFirstLaunchComplete: vi.fn().mockResolvedValue(undefined),
}));
describe('useOnboarding ?forceWizard latch (P2)', () => {
beforeEach(() => {
vi.resetModules();
localStorage.clear();
});
afterEach(() => {
cleanup();
window.history.replaceState({}, '', '/');
vi.clearAllMocks();
});
it('resets to step 0 at load, but wizard saves SURVIVE the sync reload', async () => {
window.history.replaceState({}, '', '/?forceWizard=true');
localStorage.setItem('waggle:onboarding', JSON.stringify({ completed: true, step: 7 }));
const { useOnboarding } = await import('@/hooks/useOnboarding');
const { result } = renderHook(() => useOnboarding());
// The forced reset applied at page load:
expect(result.current.state.completed).toBe(false);
expect(result.current.state.step).toBe(0);
// A mid-wizard save (workspace-create persisting its result). saveState()
// fires the waggle:onboarding-sync event, whose handler reloads via
// loadState() — pre-fix, that re-ran the forceWizard reset and wiped this.
act(() => { result.current.update({ workspaceId: 'ws-live', step: 4 }); });
expect(result.current.state.workspaceId).toBe('ws-live');
expect(result.current.state.step).toBe(4);
const persisted = JSON.parse(localStorage.getItem('waggle:onboarding') ?? '{}');
expect(persisted.workspaceId).toBe('ws-live');
});
it('completion survives too — complete() is not undone by the sync reload', async () => {
window.history.replaceState({}, '', '/?forceWizard=true');
const { useOnboarding } = await import('@/hooks/useOnboarding');
const { result } = renderHook(() => useOnboarding());
act(() => { result.current.update({ workspaceId: 'ws-live' }); });
act(() => { result.current.complete(); });
expect(result.current.state.completed).toBe(true);
// The wizard-completion shape keeps the saved fields (no defaultState wipe).
expect(result.current.state.workspaceId).toBe('ws-live');
});
it('without forceWizard, persisted completed state loads as-is', async () => {
window.history.replaceState({}, '', '/');
localStorage.setItem('waggle:onboarding', JSON.stringify({ completed: true, step: 7, tier: 'power' }));
const { useOnboarding } = await import('@/hooks/useOnboarding');
const { result } = renderHook(() => useOnboarding());
expect(result.current.state.completed).toBe(true);
});
});

View File

@@ -0,0 +1,232 @@
/**
* P3 (D2) — MemoryCenterApp shell + MemoryRoute URL wiring + the
* WorkspaceDesktop Memory-tab embed (S02-FR2).
*
* - The shell is CONTROLLED: URL (via the route) is the only navigation
* authority for mind + view. These tests mount the real route + real shell
* with stubbed tab children and assert the URL↔UI contract both ways.
* - `/memory` ≡ personal (J08 alignment); unknown :mindScope or ?tab= values
* degrade to defaults, never crash.
* - WorkspaceDesktopApp's memory tab embeds the per-mind list with
* mind='workspace' + consumeDeepLinks=false (the J08 stash belongs to the
* /memory route instance).
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, waitFor, cleanup, fireEvent } from '@testing-library/react';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';
import { TooltipProvider } from '@/components/ui/tooltip';
import { consumeDeepLink } from '@/lib/app-deeplink';
const mocks = vi.hoisted(() => ({
adapter: {
getWorkspaceContext: vi.fn(),
getWorkspaceState: vi.fn(),
getWorkspaceActivity: vi.fn(),
getTeamMembers: vi.fn(),
getWorkspaceFiles: vi.fn(),
},
shell: {
activeWorkspaceId: 'w1' as string | null,
workspaces: [{ id: 'w1', name: 'Alpha' }],
setContextRailTarget: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/providers/ShellContext', () => ({ useShell: () => mocks.shell }));
vi.mock('@/hooks/useRoomState', () => ({ useRoomState: () => ({ workspaceMap: new Map() }) }));
vi.mock('@/hooks/useOnboarding', () => ({ useOnboarding: () => ({ state: { completed: true } }) }));
vi.mock('@/hooks/useMemory', () => ({
useMemory: () => ({
frames: [], selectedFrame: null, setSelectedFrame: vi.fn(),
filters: { searchQuery: '', types: [], minImportance: 0 }, setFilters: vi.fn(),
deleteFrame: vi.fn(), loading: false, stats: { total: 0, filtered: 0 },
}),
}));
vi.mock('@/hooks/useKnowledgeGraph', () => ({
useKnowledgeGraph: () => ({
nodes: [], edges: [], refresh: vi.fn(), scope: 'current', setScope: vi.fn(),
loading: false, error: null,
}),
}));
// Stub the tab children — these tests pin the SHELL contract, not tab internals.
vi.mock('@/components/os/apps/MemoryTrust', () => ({
default: (props: { mind?: string; workspaceId?: string }) => (
<div data-testid="stub-trust" data-mind={String(props.mind)} data-ws={String(props.workspaceId)} />
),
}));
vi.mock('@/components/os/apps/memory/MemoryCenterTab', () => ({
default: (props: { mind?: string; workspaceId?: string; consumeDeepLinks?: boolean }) => (
<div
data-testid="stub-mc-tab"
data-mind={String(props.mind)}
data-ws={String(props.workspaceId)}
data-cdl={String(props.consumeDeepLinks)}
/>
),
}));
vi.mock('@/components/os/apps/memory/TimelineTab', () => ({ default: () => <div data-testid="stub-timeline" /> }));
vi.mock('@/components/os/apps/memory/KnowledgeGraphViewer', () => ({ default: () => <div data-testid="stub-graph" /> }));
vi.mock('@/components/os/apps/memory/HarvestTab', () => ({ default: () => <div data-testid="stub-harvest" /> }));
vi.mock('@/components/os/apps/memory/WeaverPanel', () => ({ default: () => <div data-testid="stub-weaver" /> }));
vi.mock('@/components/os/apps/memory/WikiTab', () => ({ default: () => <div data-testid="stub-wiki" /> }));
vi.mock('@/components/os/apps/memory/EvolutionTab', () => ({ default: () => <div data-testid="stub-evolution" /> }));
vi.mock('@/components/os/apps/memory/ImportReminderBanner', () => ({ default: () => null }));
const LocationProbe = () => {
const loc = useLocation();
return <div data-testid="loc">{loc.pathname + loc.search}</div>;
};
async function renderRoute(path: string) {
const { default: MemoryRoute } = await import('@/routes/MemoryRoute');
render(
<TooltipProvider>
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="memory/:mindScope?" element={<MemoryRoute />} />
</Routes>
<LocationProbe />
</MemoryRouter>
</TooltipProvider>,
);
}
afterEach(() => { cleanup(); vi.clearAllMocks(); mocks.shell.activeWorkspaceId = 'w1'; consumeDeepLink('memory'); });
describe('MemoryRoute + MemoryCenterApp URL wiring (P3/D2)', () => {
it('/memory defaults to the personal mind on the Trust view (PR3.5 new front door)', async () => {
await renderRoute('/memory');
// Trust is the new default front door; the personal mind pill is pressed.
expect(screen.getByTestId('stub-trust').getAttribute('data-mind')).toBe('personal');
expect(screen.getByTestId('memory-mind-personal').getAttribute('aria-pressed')).toBe('true');
});
it('/memory/workspace selects the workspace mind with the active workspace', async () => {
await renderRoute('/memory/workspace');
// Default view is Trust now — assert the mind via the Trust front-door stub.
const tab = screen.getByTestId('stub-trust');
expect(tab.getAttribute('data-mind')).toBe('workspace');
expect(tab.getAttribute('data-ws')).toBe('w1');
expect(screen.getByTestId('memory-mind-workspace').getAttribute('aria-pressed')).toBe('true');
});
it('an unknown :mindScope degrades to personal', async () => {
await renderRoute('/memory/garbage');
expect(screen.getByTestId('stub-trust').getAttribute('data-mind')).toBe('personal');
});
it('?tab=graph mounts the Graph view and hides the mind pills', async () => {
await renderRoute('/memory?tab=graph');
expect(screen.getByTestId('stub-graph')).toBeTruthy();
expect(screen.queryByTestId('memory-mind-personal')).toBeNull();
expect(screen.queryByTestId('stub-mc-tab')).toBeNull();
});
it('lets the Memory view tabs wrap instead of forcing mobile horizontal overflow', async () => {
await renderRoute('/memory');
const tablist = screen.getByRole('tablist', { name: /memory views/i });
expect(tablist).toHaveClass('min-w-0');
expect(tablist).toHaveClass('flex-wrap');
});
it('an unknown ?tab= degrades to the Trust default', async () => {
await renderRoute('/memory?tab=bogus');
expect(screen.getByTestId('stub-trust')).toBeTruthy();
});
it('?tab=memories mounts the legacy Memories list view (now secondary)', async () => {
await renderRoute('/memory?tab=memories');
// The legacy list is reachable as a secondary view; the Trust front door is
// NOT present (we're on the plain Memories list).
expect(screen.getByTestId('stub-mc-tab')).toBeTruthy();
expect(screen.queryByTestId('stub-trust')).toBeNull();
});
it.each([
['timeline', 'stub-timeline'],
['harvest', 'stub-harvest'],
['weaver', 'stub-weaver'],
['wiki', 'stub-wiki'],
['evolution', 'stub-evolution'],
])('?tab=%s mounts its legacy view (capability preserved)', async (tabId, testId) => {
await renderRoute(`/memory?tab=${tabId}`);
expect(screen.getByTestId(testId)).toBeTruthy();
});
it('switching minds navigates between /memory and /memory/workspace', async () => {
await renderRoute('/memory');
fireEvent.click(screen.getByTestId('memory-mind-workspace'));
await waitFor(() => {
expect(screen.getByTestId('loc').textContent).toBe('/memory/workspace');
});
fireEvent.click(screen.getByTestId('memory-mind-personal'));
await waitFor(() => {
expect(screen.getByTestId('loc').textContent).toBe('/memory');
});
});
it('?filter= is stashed for the Memories view then STRIPPED from the URL (one-shot intent)', async () => {
await renderRoute('/memory?filter=unreviewed');
// The route stashed it for the (stubbed) tab to consume…
expect(consumeDeepLink('memory')).toEqual(expect.objectContaining({ filter: 'unreviewed' }));
// …and the URL stops advertising it, so refresh/share can't replay a stale filter.
await waitFor(() => expect(screen.getByTestId('loc').textContent).toBe('/memory'));
});
it('a ?filter= aimed at a legacy tab is dropped, never stranded in the stash', async () => {
await renderRoute('/memory?tab=graph&filter=unreviewed');
expect(consumeDeepLink('memory')).toBeNull();
await waitFor(() => expect(screen.getByTestId('loc').textContent).toBe('/memory?tab=graph'));
});
it('switching views writes/clears ?tab= — Trust is the canonical no-tab default', async () => {
await renderRoute('/memory');
fireEvent.click(screen.getByText('Graph'));
await waitFor(() => expect(screen.getByTestId('loc').textContent).toBe('/memory?tab=graph'));
expect(screen.getByTestId('stub-graph')).toBeTruthy();
// The legacy Memories list now carries an explicit ?tab= (it's secondary).
fireEvent.click(screen.getByText('Memories'));
await waitFor(() => expect(screen.getByTestId('loc').textContent).toBe('/memory?tab=memories'));
expect(screen.getByTestId('stub-mc-tab')).toBeTruthy();
// Trust clears ?tab= (the canonical default).
fireEvent.click(screen.getByText('Trust'));
await waitFor(() => expect(screen.getByTestId('loc').textContent).toBe('/memory'));
expect(screen.getByTestId('stub-trust')).toBeTruthy();
});
it('the workspace pill is inert without an active workspace', async () => {
mocks.shell.activeWorkspaceId = null;
await renderRoute('/memory');
const pill = screen.getByTestId('memory-mind-workspace');
expect(pill.getAttribute('aria-disabled')).toBe('true');
fireEvent.click(pill);
expect(screen.getByTestId('loc').textContent).toBe('/memory');
});
});
describe('WorkspaceDesktopApp memory tab embed (P3/D2, S02-FR2)', () => {
it('renders the workspace-mind list instead of the placeholder', async () => {
mocks.adapter.getWorkspaceContext.mockResolvedValue({
workspace: { id: 'w1', name: 'Alpha', group: 'Personal', status: 'active' },
stats: { memoryCount: 2, sessionCount: 1, fileCount: 0 },
});
mocks.adapter.getWorkspaceState.mockResolvedValue({ pending: [], blocked: [] });
mocks.adapter.getWorkspaceActivity.mockResolvedValue([]);
mocks.adapter.getTeamMembers.mockResolvedValue([]);
mocks.adapter.getWorkspaceFiles.mockResolvedValue([]);
const { default: WorkspaceDesktopApp } = await import('@/components/os/apps/WorkspaceDesktopApp');
render(<WorkspaceDesktopApp workspaceId="w1" workspaceName="Alpha" activeTab="memory" />);
await waitFor(() => expect(screen.getByTestId('ws-memory-tab')).toBeTruthy());
const tab = screen.getByTestId('stub-mc-tab');
expect(tab.getAttribute('data-mind')).toBe('workspace');
expect(tab.getAttribute('data-ws')).toBe('w1');
expect(tab.getAttribute('data-cdl')).toBe('false');
});
});

View File

@@ -0,0 +1,245 @@
/**
* P3 (D2) — two-mind Memory Center: MemoryCenterTab per-mind parameterization.
*
* - Default mount stays personal-mind (pre-P3 call sites + J08 unchanged).
* - mind='workspace' reads with {mind, workspaceId} and every mutation carries
* workspaceId — without it the server's candidateStores search misses the
* workspace store and 404s (the bug class this phase fixes).
* - mind='workspace' with no workspaceId must NOT fall back to a personal
* fetch mislabeled as workspace data.
* - consumeDeepLinks=false (WorkspaceDesktop embed) must not steal the J08
* stash meant for the /memory route instance.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, waitFor, cleanup, fireEvent } from '@testing-library/react';
import { stashDeepLink, consumeDeepLink } from '@/lib/app-deeplink';
import { clearMemoryListCache } from '@/components/os/apps/memory/memory-list-cache';
import type { Memory } from '@/lib/types';
const mocks = vi.hoisted(() => ({
adapter: {
listMemories: vi.fn(),
patchMemory: vi.fn(),
archiveMemory: vi.fn(),
deleteMemoryById: vi.fn(),
mergeMemories: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
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',
createdAt: '2026-06-11T08:00:00.000Z',
...over,
});
async function renderTab(props: Record<string, unknown> = {}) {
const { default: MemoryCenterTab } = await import('@/components/os/apps/memory/MemoryCenterTab');
render(<MemoryCenterTab {...props} />);
}
afterEach(() => {
cleanup();
vi.clearAllMocks();
consumeDeepLink('memory'); // drop any stash a test left behind
clearMemoryListCache(); // Wave T Lane D: reset the module-level list cache between tests
});
describe('MemoryCenterTab two-mind parameterization (P3/D2)', () => {
it('defaults to the personal mind with no workspace param', async () => {
mocks.adapter.listMemories.mockResolvedValue([]);
await renderTab();
await waitFor(() => expect(mocks.adapter.listMemories).toHaveBeenCalled());
const arg = mocks.adapter.listMemories.mock.calls[0][0];
expect(arg.mind).toBe('personal');
expect(arg.workspaceId).toBeUndefined();
});
it('lands on the full recent list (All), with the curated Active view as a filter chip (Wave W Lane D item 2)', async () => {
mocks.adapter.listMemories.mockResolvedValue([]);
await renderTab();
await waitFor(() => expect(mocks.adapter.listMemories).toHaveBeenCalled());
const arg = mocks.adapter.listMemories.mock.calls[0][0];
// No status filter → the server returns the full recent list (density); the
// curated 'active' view is one click away as a labeled chip.
expect(arg.status).toBeUndefined();
expect(screen.getByRole('button', { name: 'All' }).getAttribute('aria-pressed')).toBe('true');
expect(screen.getByRole('button', { name: 'Active' }).getAttribute('aria-pressed')).toBe('false');
});
it("mind='workspace' reads with {mind:'workspace', workspaceId}", async () => {
mocks.adapter.listMemories.mockResolvedValue([]);
await renderTab({ mind: 'workspace', workspaceId: 'w1', consumeDeepLinks: false });
await waitFor(() => expect(mocks.adapter.listMemories).toHaveBeenCalled());
expect(mocks.adapter.listMemories).toHaveBeenCalledWith(
expect.objectContaining({ mind: 'workspace', workspaceId: 'w1' }),
);
});
it("mind='workspace' without a workspaceId renders the hint and never fetches", async () => {
await renderTab({ mind: 'workspace', consumeDeepLinks: false });
await waitFor(() => expect(screen.getByText(/No workspace selected/)).toBeTruthy());
expect(mocks.adapter.listMemories).not.toHaveBeenCalled();
});
it('merge on the workspace mind carries workspaceId', async () => {
mocks.adapter.listMemories.mockResolvedValue([mem({ id: '1' }), mem({ id: '2', title: 'Second' })]);
mocks.adapter.mergeMemories.mockResolvedValue(mem({ id: '3' }));
await renderTab({ mind: 'workspace', workspaceId: 'w1', consumeDeepLinks: false });
await waitFor(() => expect(screen.getAllByRole('checkbox', { name: /^Select memory/ })).toHaveLength(2));
for (const box of screen.getAllByRole('checkbox', { name: /^Select memory/ })) fireEvent.click(box);
fireEvent.click(screen.getByText(/Merge 2 memories/));
await waitFor(() => {
expect(mocks.adapter.mergeMemories).toHaveBeenCalledWith(['1', '2'], { workspaceId: 'w1', mind: 'workspace' });
});
});
it('archive from the detail drawer on the workspace mind carries workspaceId', async () => {
mocks.adapter.listMemories.mockResolvedValue([mem({ id: '9' })]);
mocks.adapter.archiveMemory.mockResolvedValue(mem({ id: '9', status: 'archived' }));
await renderTab({ mind: 'workspace', workspaceId: 'w1', consumeDeepLinks: false });
await waitFor(() => expect(screen.getByLabelText('GTM fact')).toBeTruthy());
fireEvent.click(screen.getByLabelText('GTM fact'));
const archiveBtn = await screen.findByText('Archive');
fireEvent.click(archiveBtn);
await waitFor(() => {
// mind rides along so server-side store resolution is STRICT (no
// cross-mind fall-through on colliding ids — P3 review HIGH).
expect(mocks.adapter.archiveMemory).toHaveBeenCalledWith('9', 'w1', 'workspace');
});
});
it('personal-mind mutations keep the workspace param off (no cross-mind shadowing)', async () => {
mocks.adapter.listMemories.mockResolvedValue([mem({ id: '4', workspaceId: undefined, scope: 'personal' })]);
mocks.adapter.archiveMemory.mockResolvedValue(mem({ id: '4', status: 'archived' }));
await renderTab();
await waitFor(() => expect(screen.getByLabelText('GTM fact')).toBeTruthy());
fireEvent.click(screen.getByLabelText('GTM fact'));
fireEvent.click(await screen.findByText('Archive'));
await waitFor(() => {
expect(mocks.adapter.archiveMemory).toHaveBeenCalledWith('4', undefined, 'personal');
});
});
it('consumeDeepLinks=false leaves the J08 stash for the route instance', async () => {
mocks.adapter.listMemories.mockResolvedValue([]);
stashDeepLink({ appId: 'memory', filter: 'unreviewed' });
await renderTab({ mind: 'workspace', workspaceId: 'w1', consumeDeepLinks: false });
await waitFor(() => expect(mocks.adapter.listMemories).toHaveBeenCalled());
expect(mocks.adapter.listMemories).not.toHaveBeenCalledWith(
expect.objectContaining({ status: 'unreviewed' }),
);
// The stash is still there for the /memory route's own instance.
expect(consumeDeepLink('memory')).toBeTruthy();
});
it('switching minds clears the merge checklist (no cross-mind merge)', async () => {
mocks.adapter.listMemories.mockResolvedValue([mem({ id: '1' }), mem({ id: '2', title: 'Second' })]);
const { default: MemoryCenterTab } = await import('@/components/os/apps/memory/MemoryCenterTab');
const { rerender } = render(
<MemoryCenterTab mind="workspace" workspaceId="w1" consumeDeepLinks={false} />,
);
await waitFor(() => expect(screen.getAllByRole('checkbox', { name: /^Select memory/ })).toHaveLength(2));
for (const box of screen.getAllByRole('checkbox', { name: /^Select memory/ })) fireEvent.click(box);
expect(screen.getByText(/Merge 2 memories/)).toBeTruthy();
rerender(<MemoryCenterTab mind="personal" consumeDeepLinks={false} />);
await waitFor(() => expect(screen.queryByText(/Merge 2 memories/)).toBeNull());
});
it('a mutation resolving AFTER a mind switch refetches with the new mind (no stale-closure load)', async () => {
mocks.adapter.listMemories.mockResolvedValue([mem({ id: '1' })]);
let resolveArchive: ((v: unknown) => void) | undefined;
mocks.adapter.archiveMemory.mockImplementation(() => new Promise((r) => { resolveArchive = r; }));
const { default: MemoryCenterTab } = await import('@/components/os/apps/memory/MemoryCenterTab');
const { rerender } = render(
<MemoryCenterTab mind="workspace" workspaceId="w1" consumeDeepLinks={false} />,
);
await waitFor(() => expect(screen.getByLabelText('GTM fact')).toBeTruthy());
fireEvent.click(screen.getByLabelText('GTM fact'));
fireEvent.click(await screen.findByText('Archive')); // archive now in flight
rerender(<MemoryCenterTab mind="personal" consumeDeepLinks={false} />); // switch mid-flight
resolveArchive!(mem({ id: '1', status: 'archived' }));
// The post-mutation refetch must ride the effect (current props), not the
// mutation-render's closured load — with the old bug the LAST call would
// carry mind:'workspace' and out-order the personal fetch.
await waitFor(() => {
const last = mocks.adapter.listMemories.mock.calls.at(-1)?.[0];
expect(last?.mind).toBe('personal');
expect(last?.workspaceId).toBeUndefined();
});
});
it('frames the list with a result-count header — count always, filter descriptor once narrowed (Wave V Lane A item 2 / Wave W Lane D item 2)', async () => {
mocks.adapter.listMemories.mockResolvedValue([
mem({ id: '1', title: 'First fact', content: 'Alpha content' }),
mem({ id: '2', title: 'Second fact', content: 'Beta content' }),
]);
await renderTab();
await waitFor(() => expect(screen.getByLabelText('First fact')).toBeTruthy());
// Trust-hero parity: the header always names the result count, so a
// filtered-down set never reads as one card floating in a void.
expect(screen.getByText('2 memories')).toBeTruthy();
// Wave W Lane D (item 2): the default is now the full recent list (All), so no
// filter descriptor rides the header at rest…
expect(screen.queryByText(/filtered by/)).toBeNull();
// …but selecting the curated Active view names it in the descriptor.
fireEvent.click(screen.getByRole('button', { name: 'Active' }));
await waitFor(() => expect(screen.getByText(/filtered by Active/)).toBeTruthy());
});
it('keeps a "loading the rest…" status over seeded rows while a refresh is in flight (Wave V Lane A item 2)', async () => {
// First load seeds the session list cache.
mocks.adapter.listMemories.mockResolvedValueOnce([mem({ id: '1', title: 'Seeded fact', content: 'Cached content' })]);
const { default: MemoryCenterTab } = await import('@/components/os/apps/memory/MemoryCenterTab');
const first = render(<MemoryCenterTab mind="personal" consumeDeepLinks={false} />);
await waitFor(() => expect(screen.getByLabelText('Seeded fact')).toBeTruthy());
first.unmount();
// Tab return: rows re-seed from cache instantly; the background refresh never
// resolves here, so the header must carry the loading affordance OVER the
// seeded card (not a bare floating card, and not a full-surface skeleton).
mocks.adapter.listMemories.mockImplementationOnce(() => new Promise(() => {}));
render(<MemoryCenterTab mind="personal" consumeDeepLinks={false} />);
expect(screen.getByLabelText('Seeded fact')).toBeTruthy();
await waitFor(() => expect(screen.getByText(/loading the rest/)).toBeTruthy());
});
it("switching minds never renders the previous mind's rows while the new fetch is in flight", async () => {
mocks.adapter.listMemories.mockResolvedValueOnce([mem({ id: '1', title: 'Workspace-only fact' })]);
const { default: MemoryCenterTab } = await import('@/components/os/apps/memory/MemoryCenterTab');
const { rerender } = render(
<MemoryCenterTab mind="workspace" workspaceId="w1" consumeDeepLinks={false} />,
);
await waitFor(() => expect(screen.getByText('Workspace-only fact')).toBeTruthy());
// Second fetch (the personal mind) never resolves inside this test — the
// workspace rows must STILL disappear immediately on the switch.
mocks.adapter.listMemories.mockImplementationOnce(() => new Promise(() => {}));
rerender(<MemoryCenterTab mind="personal" consumeDeepLinks={false} />);
await waitFor(() => expect(screen.queryByText('Workspace-only fact')).toBeNull());
expect(mocks.adapter.listMemories).toHaveBeenLastCalledWith(
expect.objectContaining({ mind: 'personal' }),
);
});
});

View File

@@ -0,0 +1,91 @@
/**
* P4 — clean-install onboarding fix (S4 founder flag, confirmed):
* useOnboarding's returning-user auto-complete keys on the server's
* /api/onboarding/status, NOT the workspace count. The boot-time
* wsManager.ensureDefault() stub gave every clean install ≥1 workspace, so
* the old `getWorkspaces().length > 0` evidence silently skipped the wizard
* for brand-new production users.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act, waitFor, cleanup } from '@testing-library/react';
const mocks = vi.hoisted(() => ({
adapter: {
getOnboardingStatus: vi.fn(),
markOnboardingComplete: vi.fn().mockResolvedValue(undefined),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/lib/tauri-bindings', () => ({
isTauri: () => false,
isFirstLaunch: vi.fn().mockResolvedValue(true),
markFirstLaunchComplete: vi.fn().mockResolvedValue(undefined),
}));
describe('useOnboarding clean-install gate (P4)', () => {
beforeEach(() => {
vi.resetModules();
localStorage.clear();
});
afterEach(() => {
cleanup();
window.history.replaceState({}, '', '/');
vi.clearAllMocks();
});
it('CLEAN INSTALL: server says not completed → the wizard stays (no auto-complete)', async () => {
mocks.adapter.getOnboardingStatus.mockResolvedValue({ completed: false, source: 'none' });
const { useOnboarding } = await import('@/hooks/useOnboarding');
const { result } = renderHook(() => useOnboarding());
await waitFor(() => expect(mocks.adapter.getOnboardingStatus).toHaveBeenCalled());
// Give any (wrong) auto-complete a tick to land, then assert it didn't.
await act(async () => { await Promise.resolve(); });
expect(result.current.state.completed).toBe(false);
});
it('RETURNING USER: server says completed → auto-completes the wizard', async () => {
mocks.adapter.getOnboardingStatus.mockResolvedValue({ completed: true, source: 'legacy-evidence' });
const { useOnboarding } = await import('@/hooks/useOnboarding');
const { result } = renderHook(() => useOnboarding());
await waitFor(() => expect(result.current.state.completed).toBe(true));
expect(result.current.state.step).toBe(7);
});
it('sidecar unreachable → stays on the wizard (fail toward onboarding)', async () => {
mocks.adapter.getOnboardingStatus.mockRejectedValue(new Error('ECONNREFUSED'));
const { useOnboarding } = await import('@/hooks/useOnboarding');
const { result } = renderHook(() => useOnboarding());
await waitFor(() => expect(mocks.adapter.getOnboardingStatus).toHaveBeenCalled());
await act(async () => { await Promise.resolve(); });
expect(result.current.state.completed).toBe(false);
});
it('MID-WIZARD: step > 0 never auto-completes — an in-wizard C33 import must not eject the user', async () => {
// The import step writes personal-mind frames BEFORE completion — that is
// legacy evidence to the server. A refresh mid-wizard must keep the wizard.
mocks.adapter.getOnboardingStatus.mockResolvedValue({ completed: true, source: 'legacy-evidence' });
localStorage.setItem('waggle:onboarding', JSON.stringify({ completed: false, step: 3 }));
const { useOnboarding } = await import('@/hooks/useOnboarding');
const { result } = renderHook(() => useOnboarding());
await act(async () => { await Promise.resolve(); });
expect(mocks.adapter.getOnboardingStatus).not.toHaveBeenCalled();
expect(result.current.state.completed).toBe(false);
expect(result.current.state.step).toBe(3);
});
it('completing the wizard stamps the server-side flag', async () => {
mocks.adapter.getOnboardingStatus.mockResolvedValue({ completed: false, source: 'none' });
const { useOnboarding } = await import('@/hooks/useOnboarding');
const { result } = renderHook(() => useOnboarding());
act(() => { result.current.complete(); });
expect(result.current.state.completed).toBe(true);
expect(mocks.adapter.markOnboardingComplete).toHaveBeenCalledTimes(1);
});
});

View File

@@ -0,0 +1,37 @@
/**
* P7/D15 A5 — D4(ii): the in-chat approval card renders the risk taxonomy the
* server already sends. Before, the FE ApprovalRequest type dropped riskLevel /
* trustSource / explanation, so the highest-risk approval showed the least info.
* The card and the shared modal must now read the SAME risk vocabulary.
*/
import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/react';
import { RiskBadge, RISK_LABELS, canAlwaysAllow } from '@/lib/risk-display';
afterEach(cleanup);
describe('A5 — shared risk-display vocabulary', () => {
it('RISK_LABELS covers all four canonical levels incl. critical', () => {
expect(RISK_LABELS.low).toBe('Low');
expect(RISK_LABELS.critical).toBe('Critical');
});
it('RiskBadge renders the level label', () => {
render(<RiskBadge level="high" />);
expect(screen.getByText(/high risk/i)).toBeInTheDocument();
});
it('RiskBadge can render critical (the level the old modal could not)', () => {
render(<RiskBadge level="critical" />);
expect(screen.getByText(/critical risk/i)).toBeInTheDocument();
});
// A6 policy helper — Always-allow gating (verified again in the A6 card test).
it('canAlwaysAllow blocks permanent grants on critical/blocked only', () => {
expect(canAlwaysAllow('standard')).toBe(true);
expect(canAlwaysAllow('elevated')).toBe(true);
expect(canAlwaysAllow('critical')).toBe(false);
expect(canAlwaysAllow('blocked')).toBe(false);
expect(canAlwaysAllow(undefined)).toBe(true);
});
});

View File

@@ -0,0 +1,37 @@
/**
* P7/D15 A6 — the shared modal can represent 'critical', and "Always allow" is
* gated by approvalClass (a critical/blocked action can't be permanently granted
* in one click — founder-ratified, mirrors MCPHub's CRITICAL rule).
*/
import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/react';
import { ApprovalModal } from '@/components/ui/approval-modal';
import { canAlwaysAllow } from '@/lib/risk-display';
afterEach(cleanup);
describe('A6 — modal represents critical', () => {
it('renders a critical risk level (was impossible with the old 3-value type)', () => {
render(
<ApprovalModal
request={{ action: 'Install dangerous MCP', scope: ['network', 'secrets'], riskLevel: 'critical' }}
onApprove={() => {}}
onCancel={() => {}}
/>,
);
expect(screen.getByText('Critical')).toBeInTheDocument();
expect(screen.getByText('Install dangerous MCP')).toBeInTheDocument();
});
});
// The card's "Always allow" is wired as
// {canAlwaysAllow(request.approvalClass) && <button>Always allow</button>}
// so the permanent grant disappears for critical/blocked approvals.
describe('A6 — Always-allow gating policy', () => {
it('hides the permanent grant for critical/blocked, offers it below', () => {
expect(canAlwaysAllow('critical')).toBe(false);
expect(canAlwaysAllow('blocked')).toBe(false);
expect(canAlwaysAllow('elevated')).toBe(true);
expect(canAlwaysAllow('standard')).toBe(true);
});
});

View File

@@ -0,0 +1,41 @@
/**
* P7/D15 A7 — one shared install-risk classifier (divergence #8) + audit-feed
* risk rendering reuse (#16). classifyInstallRisk is the single scan/trust→risk
* map every install surface delegates to; isKnownRiskLevel gates the audit panel
* reusing the shared label/colour vocabulary.
*/
import { describe, it, expect } from 'vitest';
import { classifyInstallRisk, isKnownRiskLevel, RISK_LABELS } from '@/lib/risk-display';
import { installRiskFor } from '@/components/os/apps/MarketplaceApp';
describe('A7 — classifyInstallRisk (shared scan/trust → risk)', () => {
it('failed scan → high', () => {
expect(classifyInstallRisk({ scanStatus: 'failed' })).toBe('high');
});
it('passed scan → low', () => {
expect(classifyInstallRisk({ scanStatus: 'passed' })).toBe('low');
});
it('verified trust → low', () => {
expect(classifyInstallRisk({ trust: 'verified' })).toBe('low');
});
it('no signal → medium', () => {
expect(classifyInstallRisk({})).toBe('medium');
});
it('MarketplaceApp.installRiskFor delegates to the shared classifier', () => {
// Same scan/trust signal must yield the same risk as the shared fn.
const ext = { scanStatus: 'failed' } as Parameters<typeof installRiskFor>[0];
expect(installRiskFor(ext)).toBe(classifyInstallRisk({ scanStatus: 'failed' }));
});
});
describe('A7 — audit-feed risk rendering (#16)', () => {
it('isKnownRiskLevel accepts canonical levels, rejects unknown', () => {
expect(isKnownRiskLevel('critical')).toBe(true);
expect(isKnownRiskLevel('low')).toBe(true);
expect(isKnownRiskLevel('unknown')).toBe(false);
expect(isKnownRiskLevel('')).toBe(false);
});
it('known levels have a shared label', () => {
expect(RISK_LABELS.high).toBe('High');
});
});

View File

@@ -0,0 +1,119 @@
/**
* P7/D15 B1 — Approvals must not render a fetch FAILURE as an empty inbox.
* On a TEAMS trust surface, "No pending approvals" while the server is down is a
* correctness defect: it tells the user nothing is awaiting them when the truth
* is unknown. A failed load must show an error + Retry, not the empty state.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render as rtlRender, screen, cleanup, waitFor, fireEvent } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
const mocks = vi.hoisted(() => ({
adapter: {
getPendingApprovals: vi.fn(),
getApprovalGrants: vi.fn(),
respondApproval: vi.fn(),
revokeApprovalGrant: vi.fn(),
clearApprovalGrants: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/hooks/use-toast', () => ({ useToast: () => ({ toast: vi.fn() }) }));
import ApprovalsApp, { resetApprovalsRouteCache } from '@/components/os/apps/ApprovalsApp';
const render = () => rtlRender(<TooltipProvider><ApprovalsApp /></TooltipProvider>);
beforeEach(() => {
vi.clearAllMocks();
resetApprovalsRouteCache();
mocks.adapter.getPendingApprovals.mockResolvedValue({ pending: [], count: 0 });
mocks.adapter.getApprovalGrants.mockResolvedValue({ grants: [], count: 0 });
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
const approvalGrant = {
id: 'grant-send-email',
toolName: 'send_email',
targetKey: 'client@example.com',
sourceWorkspaceId: 'workspace-1',
description: 'Always allow send_email to client@example.com',
grantedAt: new Date().toISOString(),
expiresAt: null,
};
describe('P7/B1 — Approvals error state', () => {
it('repaints the trust inbox on return and refreshes silently', async () => {
const first = render();
await waitFor(() => expect(screen.getByText('No pending approvals')).toBeInTheDocument());
const baseline = mocks.adapter.getPendingApprovals.mock.calls.length;
first.unmount();
render();
expect(screen.getByText('No pending approvals')).toBeInTheDocument();
await waitFor(() => expect(mocks.adapter.getPendingApprovals.mock.calls.length).toBeGreaterThan(baseline));
});
it('shows an error + Retry (not "No pending approvals") when the fetch fails', async () => {
mocks.adapter.getPendingApprovals.mockRejectedValue(new Error('server down'));
render();
await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());
expect(screen.queryByText('No pending approvals')).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: /retry/i })).toBeInTheDocument();
});
it('shows the empty state (not an error) when the fetch succeeds with no approvals', async () => {
mocks.adapter.getPendingApprovals.mockResolvedValue({ pending: [], count: 0 });
render();
await waitFor(() => expect(screen.getByText('No pending approvals')).toBeInTheDocument());
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
it('Retry re-fetches and clears the error on recovery', async () => {
mocks.adapter.getPendingApprovals
.mockRejectedValueOnce(new Error('server down'))
.mockResolvedValueOnce({ pending: [], count: 0 });
render();
await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', { name: /retry/i }));
await waitFor(() => expect(screen.getByText('No pending approvals')).toBeInTheDocument());
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
it('asks in-app before revoking all saved approval grants', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
mocks.adapter.getPendingApprovals.mockResolvedValue({ pending: [], count: 0 });
mocks.adapter.getApprovalGrants.mockResolvedValue({ grants: [approvalGrant], count: 1 });
mocks.adapter.clearApprovalGrants.mockResolvedValue({ ok: true });
render();
fireEvent.click(await screen.findByRole('button', { name: /grants/i }));
await screen.findByText('1 active grant');
fireEvent.click(screen.getByRole('button', { name: /revoke all/i }));
expect(confirmSpy).not.toHaveBeenCalled();
expect(mocks.adapter.clearApprovalGrants).not.toHaveBeenCalled();
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent(/revoke all saved approval grants/i);
expect(modal).toHaveTextContent(/1 saved grant/i);
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.clearApprovalGrants).toHaveBeenCalledTimes(1));
});
it('names icon-only refresh and grant revoke controls', async () => {
mocks.adapter.getPendingApprovals.mockResolvedValue({ pending: [], count: 0 });
mocks.adapter.getApprovalGrants.mockResolvedValue({ grants: [approvalGrant], count: 1 });
render();
expect(await screen.findByRole('button', { name: /refresh approvals/i })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /grants/i }));
expect(await screen.findByRole('button', { name: /revoke grant always allow send_email to client@example.com/i })).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,234 @@
/**
* P7/D15 B2 — useRoomState must expose connecting/error so RoomApp can tell a
* broken SSE channel apart from an idle room (both rendered "No agents running"
* before this fix). A subscribe failure → error + a reconnect affordance.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { createElement } from 'react';
import { renderHook, act, waitFor, render, cleanup } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import {
COLLABORATION_RUN_STATUSES,
type CollaborationRoomRun,
type CollaborationWorkerRun,
} from '@waggle/shared';
const mocks = vi.hoisted(() => ({
adapter: {
subscribeSubagentStatus: vi.fn(),
getAgentRunSnapshot: vi.fn(),
getAgentRunEvents: vi.fn(),
},
}));
const routeCapture = vi.hoisted(() => ({
props: null as null | { roomId?: string; workspaceNames?: Record<string, string> },
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/components/os/apps/RoomApp', () => ({
default: (props: { roomId?: string; workspaceNames?: Record<string, string> }) => {
routeCapture.props = props;
return null;
},
}));
vi.mock('@/providers/ShellContext', () => ({
useShell: () => ({ workspaces: [{ id: 'ws-a', name: 'Alpha' }, { id: 'ws-b', name: 'Beta' }] }),
}));
import { useRoomState } from '@/hooks/useRoomState';
import {
applyCanonicalRunEvents,
hydrateCanonicalRuns,
indexCanonicalRooms,
} from '@/lib/room-state-reducer';
import RoomRoute from '@/routes/RoomRoute';
const NOW = '2026-07-11T00:00:00.000Z';
function room(id: string, workspaceIds: string[]): CollaborationRoomRun {
return {
schemaVersion: 1,
kind: 'room',
id,
roomId: id,
rootRunId: id,
parentRunId: null,
workspaceIds,
source: 'external_tool',
executor: { kind: 'coordinator', toolId: 'codex' },
title: `Room ${id}`,
task: 'Compare implementations',
status: 'running',
progress: { message: 'Coordinating', phase: 'fan-out', current: 1, total: 2 },
memoryRefs: { status: 'pending', personalFrameIds: [], workspaceFrameIds: {} },
capabilities: { cancel: true, pause: false, resume: false, message: false },
revision: 1,
createdAt: NOW,
updatedAt: NOW,
startedAt: NOW,
};
}
function worker(
id: string,
roomId: string,
workspaceId: string,
status: CollaborationWorkerRun['status'] = 'running',
): CollaborationWorkerRun {
return {
schemaVersion: 1,
kind: 'worker',
id,
roomId,
rootRunId: roomId,
parentRunId: roomId,
workspaceId,
source: 'external_tool',
executor: { kind: 'external_tool', toolId: 'codex', model: 'gpt-test', pid: 42 },
title: `Worker ${id}`,
task: `Work in ${workspaceId}`,
status,
progress: { message: 'Reviewing', phase: 'analysis', current: 2, total: 4 },
result: {
summary: 'Partial finding',
error: 'One source unavailable',
sessionId: `session-${id}`,
traceId: `trace-${id}`,
artifacts: [`${workspaceId}/report.md`],
exitCode: null,
},
metrics: { toolsUsed: ['read_file'], inputTokens: 10, outputTokens: 20, costUsd: 0.01 },
memoryRefs: {
status: 'partial',
personalFrameIds: [1],
workspaceFrameIds: { [workspaceId]: [2] },
},
capabilities: { cancel: true, pause: true, resume: true, message: false },
revision: 1,
createdAt: NOW,
updatedAt: NOW,
startedAt: NOW,
};
}
beforeEach(() => {
routeCapture.props = null;
mocks.adapter.subscribeSubagentStatus.mockReset().mockReturnValue(() => {});
mocks.adapter.getAgentRunSnapshot.mockReset().mockResolvedValue({ lastSeq: 0, runs: [] });
mocks.adapter.getAgentRunEvents.mockReset().mockResolvedValue({
lastSeq: 0, resetRequired: false, events: [],
});
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
describe('P7/B2 — useRoomState connection status', () => {
it('settles to connected (no error) when subscribe succeeds', async () => {
const { result } = renderHook(() => useRoomState());
await waitFor(() => expect(result.current.connecting).toBe(false));
expect(result.current.error).toBeNull();
});
it('exposes an error (not silent console) when subscribe throws', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
mocks.adapter.subscribeSubagentStatus.mockImplementation(() => { throw new Error('SSE 401'); });
const { result } = renderHook(() => useRoomState());
await waitFor(() => expect(result.current.error).toBe('SSE 401'));
expect(result.current.connecting).toBe(false);
});
it('reconnect() re-attempts the subscription and clears the error on recovery', async () => {
vi.spyOn(console, 'error').mockImplementation(() => {});
mocks.adapter.subscribeSubagentStatus
.mockImplementationOnce(() => { throw new Error('SSE 401'); })
.mockReturnValueOnce(() => {});
const { result } = renderHook(() => useRoomState());
await waitFor(() => expect(result.current.error).toBe('SSE 401'));
act(() => result.current.reconnect());
await waitFor(() => expect(result.current.error).toBeNull());
expect(mocks.adapter.subscribeSubagentStatus).toHaveBeenCalledTimes(2);
});
});
describe('canonical Room state fidelity', () => {
it('preserves every canonical status and exact parent-child records', () => {
const root = room('room-all-statuses', ['ws-a']);
const workers = COLLABORATION_RUN_STATUSES.map((status, index) =>
worker(`run-${index}`, root.id, 'ws-a', status));
const runsById = hydrateCanonicalRuns([root, ...workers]);
const indexed = indexCanonicalRooms(runsById);
expect(indexed.roomsById.get(root.id)).toBe(root);
expect(indexed.childrenByRoomId.get(root.id)?.map((run) => run.status)).toEqual([
...COLLABORATION_RUN_STATUSES,
]);
const interrupted = { ...workers[0], status: 'interrupted' as const, revision: 2 };
const updated = applyCanonicalRunEvents(runsById, [{
seq: 2, type: 'upsert', run: interrupted, timestamp: NOW,
}]);
expect(updated.get(interrupted.id)).toBe(interrupted);
expect(updated.get(root.id)).toBe(root);
});
it('focuses one root while retaining its complete worker state and the global graph', async () => {
const rootA = room('room-a', ['ws-a']);
const rootB = room('room-b', ['ws-b']);
const workerA = worker('run-a', rootA.id, 'ws-a', 'waiting_for_approval');
const workerB = worker('run-b', rootB.id, 'ws-b', 'paused');
mocks.adapter.getAgentRunSnapshot.mockResolvedValue({
lastSeq: 4,
runs: [rootA, workerA, rootB, workerB],
});
const { result } = renderHook(() => useRoomState(rootA.id));
await waitFor(() => expect(result.current.focusedRoom?.id).toBe(rootA.id));
expect(result.current.focusedRoom?.workspaceIds).toEqual(['ws-a']);
expect(result.current.focusedWorkers).toEqual([workerA]);
expect(result.current.getRoomWorkers(rootA.id)).toEqual([workerA]);
expect(result.current.runsById.get(workerA.id)).toMatchObject({
status: 'waiting_for_approval',
executor: workerA.executor,
progress: workerA.progress,
result: workerA.result,
metrics: workerA.metrics,
memoryRefs: workerA.memoryRefs,
capabilities: workerA.capabilities,
workspaceId: 'ws-a',
parentRunId: rootA.id,
});
expect([...result.current.workspaceMap.keys()]).toEqual(['ws-a']);
expect(result.current.workspaceMap.get('ws-a')?.live[0]).toMatchObject({
runStatus: 'waiting_for_approval',
workspaceId: 'ws-a',
executor: workerA.executor,
progress: workerA.progress,
result: workerA.result,
metrics: workerA.metrics,
memoryRefs: workerA.memoryRefs,
capabilities: workerA.capabilities,
});
expect([...result.current.allWorkspaceMap.keys()].sort()).toEqual(['ws-a', 'ws-b']);
expect(result.current.rooms).toHaveLength(2);
});
});
describe('RoomRoute focus plumbing', () => {
it('decodes the canonical room query and passes it with workspace names', () => {
render(createElement(
MemoryRouter,
{
initialEntries: ['/room?room=room%2Fmulti'],
future: { v7_startTransition: true, v7_relativeSplatPath: true },
},
createElement(RoomRoute),
));
expect(routeCapture.props).toEqual({
roomId: 'room/multi',
workspaceNames: { 'ws-a': 'Alpha', 'ws-b': 'Beta' },
});
});
});

View File

@@ -0,0 +1,120 @@
/**
* P7/D15 B3 — Command Center.
* Part 1 (structural): the Win+K overlay must be inside an AppErrorBoundary so a
* render throw can't blank the whole shell — verified via the boundary contract.
* Part 2 (in-body): a failed search must surface a degraded-results notice, not
* silently swap in local fuzzy matches with no signal.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup, waitFor, fireEvent } from '@testing-library/react';
import AppErrorBoundary from '@/components/os/ErrorBoundary';
const mocks = vi.hoisted(() => ({
adapter: {
commandRecent: vi.fn(),
commandSuggestions: vi.fn(),
commandSearch: vi.fn(),
commandExecute: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
// cmdk (Command primitive) observes layout — jsdom lacks ResizeObserver.
class ResizeObserverStub { observe() {} unobserve() {} disconnect() {} }
(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = ResizeObserverStub;
(globalThis.Element.prototype as unknown as { scrollIntoView: () => void }).scrollIntoView = () => {};
import CommandCenter from '@/components/os/overlays/CommandCenter';
beforeEach(() => {
vi.clearAllMocks();
mocks.adapter.commandRecent.mockResolvedValue({ results: [{ id: 'r1', title: 'Recent thing', type: 'navigate' }] });
mocks.adapter.commandSuggestions.mockResolvedValue({ results: [{ id: 's1', title: 'Suggested thing', type: 'navigate' }] });
});
afterEach(cleanup);
describe('P7/B3 — Command Center error containment', () => {
it('provides an accessible dialog description for screen readers', async () => {
render(<CommandCenter open onClose={() => {}} onNavigate={() => {}} onExecute={() => {}} />);
const dialog = await screen.findByRole('dialog', { name: /command center/i });
const describedBy = dialog.getAttribute('aria-describedby');
expect(describedBy).toBeTruthy();
expect(document.getElementById(describedBy ?? '')).toHaveTextContent(/search and run commands/i);
});
it('gives the command search input a visible token focus ring', async () => {
render(<CommandCenter open onClose={() => {}} onNavigate={() => {}} onExecute={() => {}} />);
const input = await screen.findByLabelText('Command Center search');
expect(input.className).toContain('focus-visible:ring-2');
expect(input.className).toContain('focus-visible:ring-[var(--focus-ring)]');
});
it('renders catalog subtitles as their own truncating line for mobile fit', async () => {
const Icon = () => <span aria-hidden="true" />;
render(
<CommandCenter
open
onClose={() => {}}
onNavigate={() => {}}
onExecute={() => {}}
catalog={[
{
key: 'power',
heading: 'Power tools',
items: [
{
id: 'watch-agent',
group: 'power',
name: 'Watch a coding agent live',
subtitle: 'Claude Code · Cursor · Codex — stream its output',
icon: Icon,
to: '/launcher?watch=1',
},
],
},
]}
/>,
);
const subtitle = await screen.findByText(/stream its output/i);
expect(subtitle).toHaveClass('block');
expect(subtitle).toHaveClass('truncate');
});
it('Part 1: a render throw inside the overlay is caught by AppErrorBoundary (shell survives)', () => {
const Boom = () => { throw new Error('overlay exploded'); };
vi.spyOn(console, 'error').mockImplementation(() => {});
render(
<div data-testid="shell-survives">
<AppErrorBoundary appName="Command Center" onClose={() => {}}>
<Boom />
</AppErrorBoundary>
</div>,
);
// Shell sibling still mounted; boundary shows its fallback instead of unmounting the tree.
expect(screen.getByTestId('shell-survives')).toBeInTheDocument();
expect(screen.getByText('Command Center encountered an error')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /close window/i })).toBeInTheDocument();
});
it('Part 2: a failed search surfaces a degraded-results notice', async () => {
mocks.adapter.commandSearch.mockRejectedValue(new Error('search 500'));
render(<CommandCenter open onClose={() => {}} onNavigate={() => {}} onExecute={() => {}} />);
const input = await screen.findByLabelText('Command Center search');
fireEvent.change(input, { target: { value: 'thing' } });
await waitFor(
() => expect(screen.getByText(/search service unreachable/i)).toBeInTheDocument(),
{ timeout: 1500 },
);
});
it('Part 2: a successful search shows no degraded notice', async () => {
mocks.adapter.commandSearch.mockResolvedValue({ results: [{ id: 'x', title: 'Hit', type: 'navigate' }] });
render(<CommandCenter open onClose={() => {}} onNavigate={() => {}} onExecute={() => {}} />);
const input = await screen.findByLabelText('Command Center search');
fireEvent.change(input, { target: { value: 'thing' } });
await waitFor(() => expect(mocks.adapter.commandSearch).toHaveBeenCalled(), { timeout: 1500 });
expect(screen.queryByText(/search service unreachable/i)).not.toBeInTheDocument();
});
});

View File

@@ -0,0 +1,78 @@
/**
* P7/D15 B4 — Files must distinguish a real cold-load FAILURE from offline-with-cache.
* Before: every failure set offline=true → "showing cached files" even with no cache,
* and an in-flight load looked like "Empty directory".
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render as rtlRender, screen, cleanup, waitFor, fireEvent } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
const mocks = vi.hoisted(() => ({ adapter: { listFiles: vi.fn() } }));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import FilesApp, { resetFilesRouteCache } from '@/components/os/apps/FilesApp';
const render = () =>
rtlRender(<TooltipProvider><FilesApp workspaceId="ws1" /></TooltipProvider>);
beforeEach(() => {
resetFilesRouteCache();
vi.clearAllMocks();
});
afterEach(cleanup);
describe('P7/B4 — Files cold-load error vs offline', () => {
it('cold-load failure (no cache) shows an error, not "Empty directory" or "cached files"', async () => {
mocks.adapter.listFiles.mockRejectedValue(new Error('500'));
render();
await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());
expect(screen.getByText(/couldn't load files/i)).toBeInTheDocument();
expect(screen.queryByText('Empty directory')).not.toBeInTheDocument();
expect(screen.queryByText(/showing cached files/i)).not.toBeInTheDocument();
});
it('successful empty load shows "Empty directory", not an error', async () => {
mocks.adapter.listFiles.mockResolvedValue([]);
render();
await waitFor(() => expect(screen.getByText('Empty directory')).toBeInTheDocument());
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
// Review MEDIUM: navigating into a new directory whose load FAILS must show the
// error — stale entries from the previous dir must not route it to "Empty directory".
it('cross-directory nav failure shows an error, not a stale "Empty directory"', async () => {
mocks.adapter.listFiles.mockImplementation((_ws: string, p: string) => {
if (p === '/sub') return Promise.reject(new Error('500'));
return Promise.resolve([{ name: 'sub', path: '/sub', type: 'directory', size: 0, modified: Date.now() }]);
});
render();
// Double-click the LIST row (the tree sidebar also lists 'sub'); the list row
// sits inside a table <tr> whose double-click handler navigates.
await waitFor(() => expect(screen.getAllByText('sub').length).toBeGreaterThan(0));
const listRow = screen.getAllByText('sub').map((el) => el.closest('tr')).find(Boolean);
expect(listRow).toBeTruthy();
fireEvent.doubleClick(listRow!);
await waitFor(() => expect(screen.getByRole('alert')).toBeInTheDocument());
expect(screen.getByText(/couldn't load files/i)).toBeInTheDocument();
expect(screen.queryByText('Empty directory')).not.toBeInTheDocument();
expect(screen.queryByText(/showing cached files/i)).not.toBeInTheDocument();
});
// Review LOW: a failed REFRESH of an already-loaded EMPTY dir keeps showing
// "Empty directory" (we proved it empty) — not a false cold-load error.
it('failed refresh of a known-empty dir keeps "Empty directory", not a false error', async () => {
mocks.adapter.listFiles
.mockResolvedValueOnce([])
.mockRejectedValue(new Error('transient 503'));
render();
await waitFor(() => expect(screen.getByText('Empty directory')).toBeInTheDocument());
// Open the file-list context menu (right-click the pane) and hit Refresh to
// drive the second (failing) load against the already-loaded empty dir.
fireEvent.contextMenu(screen.getByText('Empty directory'));
const refreshItem = await screen.findByText('Refresh');
fireEvent.click(refreshItem);
await waitFor(() => expect(mocks.adapter.listFiles).toHaveBeenCalledTimes(2));
expect(screen.getByText('Empty directory')).toBeInTheDocument();
expect(screen.queryByText(/couldn't load files/i)).not.toBeInTheDocument();
});
});

View File

@@ -0,0 +1,100 @@
/**
* P7/D15 B5 — error states that hooks already capture but components dropped.
* Covers WaggleDanceApp + EventsApp (error≠empty) and TimelineTab (error≠empty).
* The SettingsApp missing-.catch defect is structurally verified separately.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render as rtlRender, screen, cleanup, fireEvent } from '@testing-library/react';
import type { ReactElement } from 'react';
import { TooltipProvider } from '@/components/ui/tooltip';
const mocks = vi.hoisted(() => ({
useWaggleDance: vi.fn(),
}));
vi.mock('@/lib/adapter', () => ({ adapter: {}, default: vi.fn() }));
vi.mock('@/hooks/useWaggleDance', () => ({ useWaggleDance: mocks.useWaggleDance }));
const render = (ui: ReactElement) => rtlRender(<TooltipProvider>{ui}</TooltipProvider>);
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
describe('P7/B5 — WaggleDanceApp action names', () => {
it('names the refresh action', async () => {
const refresh = vi.fn();
mocks.useWaggleDance.mockReturnValue({
signals: [],
allSignals: [],
loading: false,
error: null,
filter: 'all',
setFilter: vi.fn(),
refresh,
acknowledge: vi.fn(),
});
const { default: WaggleDanceApp } = await import('@/components/os/apps/WaggleDanceApp');
render(<WaggleDanceApp />);
expect(screen.getByRole('button', { name: /refresh waggle dance/i })).toBeInTheDocument();
});
});
describe('P7/B5 — EventsApp error state', () => {
it('renders an error (not "No events yet") when error is set', async () => {
const { default: EventsApp } = await import('@/components/os/apps/EventsApp');
render(<EventsApp steps={[]} autoScroll={false} onToggleAutoScroll={() => {}} filter={null} onFilterChange={() => {}} error="boom" />);
expect(screen.getByRole('alert')).toBeInTheDocument();
expect(screen.getByText(/couldn't load events/i)).toBeInTheDocument();
expect(screen.queryByText('No events yet')).not.toBeInTheDocument();
});
it('renders "No events yet" (not an error) when error is null and steps empty', async () => {
const { default: EventsApp } = await import('@/components/os/apps/EventsApp');
render(<EventsApp steps={[]} autoScroll={false} onToggleAutoScroll={() => {}} filter={null} onFilterChange={() => {}} error={null} />);
expect(screen.getByText('No events yet')).toBeInTheDocument();
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
});
describe('P7/B5 — TimelineTab error state', () => {
const base = {
frames: [], selectedFrame: null, onSelectFrame: () => {}, searchQuery: '',
onSearchChange: () => {}, onDeleteFrame: () => {}, loading: false,
stats: { total: 0, filtered: 0 },
};
it('renders an error (not "No memories found") when error is set', async () => {
const { default: TimelineTab } = await import('@/components/os/apps/memory/TimelineTab');
render(<TimelineTab {...base} error="down" />);
expect(screen.getByRole('alert')).toBeInTheDocument();
expect(screen.getByText(/couldn't load memories/i)).toBeInTheDocument();
expect(screen.queryByText('No memories found')).not.toBeInTheDocument();
});
it('renders "No memories found" when error is null and frames empty', async () => {
const { default: TimelineTab } = await import('@/components/os/apps/memory/TimelineTab');
render(<TimelineTab {...base} error={null} />);
expect(screen.getByText('No memories found')).toBeInTheDocument();
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
});
it('a11y: sidebar search and importance filter expose stable controls', async () => {
const { default: TimelineTab } = await import('@/components/os/apps/memory/TimelineTab');
const onMinImportanceChange = vi.fn();
render(<TimelineTab {...base} error={null} minImportance={2} onMinImportanceChange={onMinImportanceChange} />);
const search = screen.getByLabelText('Search timeline memories');
expect(search).toHaveAttribute('name', 'timelineMemorySearch');
expect(search).toHaveAttribute('autocomplete', 'off');
expect(search.closest('div')?.className).toContain('focus-within:ring-2');
fireEvent.click(screen.getByRole('button', { name: 'Show timeline filters' }));
const minImportance = screen.getByLabelText(/min importance/i);
expect(minImportance).toHaveAttribute('name', 'timelineMinImportance');
expect(minImportance).toHaveAttribute('min', '0');
expect(minImportance).toHaveAttribute('max', '5');
expect(minImportance.className).toContain('focus-visible:ring-2');
});
});

View File

@@ -0,0 +1,57 @@
/**
* P7/D15 #17 — provenance (trustSource) is the dimension that justifies the risk.
* It was shown on no install surface except a hand-built MarketplaceApp scope
* line. The modal now renders it consistently from a structured field, and
* MarketplaceApp populates it via installTrustSource.
*/
import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/react';
import { ApprovalModal } from '@/components/ui/approval-modal';
import { installTrustSource, TRUST_SOURCE_LABELS } from '@/lib/risk-display';
import { buildInstallRequest } from '@/components/os/apps/MarketplaceApp';
afterEach(cleanup);
describe('#17 — modal renders trust source', () => {
it('shows the labelled trust source when present', () => {
render(
<ApprovalModal
request={{ action: 'Install X', scope: ['Type: skill'], riskLevel: 'low', trustSource: 'third_party_verified' }}
onApprove={() => {}}
onCancel={() => {}}
/>,
);
expect(screen.getByText('Trust source:')).toBeInTheDocument();
expect(screen.getByText(TRUST_SOURCE_LABELS.third_party_verified)).toBeInTheDocument();
});
it('omits the trust-source line when absent (no false provenance)', () => {
render(
<ApprovalModal
request={{ action: 'Activate Y', scope: ['enable'], riskLevel: 'medium' }}
onApprove={() => {}}
onCancel={() => {}}
/>,
);
expect(screen.queryByText('Trust source:')).not.toBeInTheDocument();
});
});
describe('#17 — installTrustSource maps scan/trust to canonical provenance', () => {
it('failed scan → security-gate', () => {
expect(installTrustSource({ scanStatus: 'failed' })).toBe('security-gate');
});
it('verified / passed → third_party_verified', () => {
expect(installTrustSource({ trust: 'verified' })).toBe('third_party_verified');
expect(installTrustSource({ scanStatus: 'passed' })).toBe('third_party_verified');
});
it('no signal → unknown', () => {
expect(installTrustSource({})).toBe('unknown');
});
it('MarketplaceApp.buildInstallRequest carries a structured trustSource', () => {
const req = buildInstallRequest({ name: 'pkg', type: 'skill', source: 'marketplace', scanStatus: 'failed' } as Parameters<typeof buildInstallRequest>[0]);
expect(req.trustSource).toBe('security-gate');
// the hand-built "Trust: …" scope string is gone (structured field instead).
expect(req.scope.some((s) => s.startsWith('Trust:'))).toBe(false);
});
});

View File

@@ -0,0 +1,21 @@
/**
* P7/D15 #8 — one shared source for non-install approval risk. The builder/install
* surfaces used to inline scattered riskLevel literals, so the same conceptual
* action could read differently in two places. actionRisk(kind) is now the single
* source; this pins the action-kind → risk contract.
*/
import { describe, it, expect } from 'vitest';
import { actionRisk } from '@/lib/risk-display';
describe('#8 — actionRisk shared classifier', () => {
it('recoverable state changes are medium', () => {
expect(actionRisk('connector-revoke')).toBe('medium');
expect(actionRisk('agent-elevation')).toBe('medium');
expect(actionRisk('automation-activation')).toBe('medium');
expect(actionRisk('mcp-revoke')).toBe('medium');
expect(actionRisk('install-remove')).toBe('medium');
});
it('overriding a security-scan finding is high', () => {
expect(actionRisk('mcp-install-override')).toBe('high');
});
});

View File

@@ -0,0 +1,252 @@
/**
* Phase 3B (S09) — Agent Center component behaviour over a mocked adapter:
* render-from-data, C22 tab filtering, the C23 workspace-ambiguity picker
* branch (pick → retry with workspaceId), pause flow, empty + error states.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, within, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { Agent } from '@/lib/types';
const mocks = vi.hoisted(() => ({
adapter: {
// ServiceProvider's mount connect() — resolves so `connecting` settles
// and the app's connect-gated load() fires.
connect: vi.fn().mockResolvedValue(undefined),
listAgents: vi.fn(),
runAgent: vi.fn(),
pauseAgent: vi.fn(),
patchAgent: vi.fn(),
createAgent: vi.fn(),
getAgentTraces: vi.fn(),
// TemplatesView deps (not exercised here, but the module mock is total):
getPersonas: vi.fn().mockResolvedValue([]),
getCapabilityStatus: vi.fn().mockResolvedValue({}),
getAgentGroups: vi.fn().mockResolvedValue([]),
runAgentGroup: vi.fn(),
getJobStatus: vi.fn().mockResolvedValue(null),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import AgentsApp, { resetAgentsRouteCache } from '@/components/os/apps/AgentsApp';
import { ServiceProvider } from '@/providers/ServiceProvider';
function makeAgent(over: Partial<Agent> = {}): Agent {
return {
id: 'a1', name: 'Scout', goal: 'Research the market', type: 'personal',
model: 'auto', autonomyLevel: 'guided', memoryScopes: ['personal'],
status: 'idle', createdAt: '2026-06-01T00:00:00Z', updatedAt: '2026-06-01T00:00:00Z',
successRate: 0.8, lastRunAt: '2026-06-09T00:00:00Z',
...over,
};
}
const renderApp = () => render(
<MemoryRouter>
<ServiceProvider>
<TooltipProvider>
<AgentsApp workspaces={[
{ id: 'ws-1', name: 'Acme Research', group: 'work' },
{ id: 'ws-2', name: 'Personal Lab', group: 'personal' },
]} activeWorkspaceId="ws-2" />
</TooltipProvider>
</ServiceProvider>
</MemoryRouter>,
);
beforeEach(() => {
vi.clearAllMocks();
resetAgentsRouteCache(); // Pillar 2.6: reset the module-level route cache between tests
mocks.adapter.connect.mockResolvedValue(undefined);
mocks.adapter.getAgentTraces.mockResolvedValue([]);
});
afterEach(cleanup);
describe('AgentsApp — Agent Center', () => {
it('a11y: search control exposes stable form metadata', async () => {
mocks.adapter.listAgents.mockResolvedValue([]);
renderApp();
await screen.findByText(/No custom agents yet/);
const search = screen.getByRole('textbox', { name: 'Search agents' });
expect(search).toHaveAttribute('name', 'agentSearch');
expect(search).toHaveAttribute('autocomplete', 'off');
});
it('renders agent rows from the adapter with §14.5 status badges', async () => {
mocks.adapter.listAgents.mockResolvedValue([
makeAgent({ id: 'a1', name: 'Scout', status: 'idle' }),
makeAgent({ id: 'a2', name: 'Drafter', status: 'running', type: 'workspace' }),
]);
renderApp();
expect(await screen.findByText('Scout')).toBeInTheDocument();
expect(screen.getByText('Drafter')).toBeInTheDocument();
expect(screen.getByText('Idle')).toBeInTheDocument();
expect(screen.getByText('Running')).toBeInTheDocument();
const scoutButton = screen.getByRole('button', { name: 'Open agent Scout' });
const scoutAvatar = scoutButton.querySelector('img');
expect(scoutAvatar).toHaveAttribute('width', '28');
expect(scoutAvatar).toHaveAttribute('height', '28');
});
it('filters by C22 category tab (Personal hides the workspace agent)', async () => {
mocks.adapter.listAgents.mockResolvedValue([
makeAgent({ id: 'a1', name: 'Scout', type: 'personal' }),
makeAgent({ id: 'a2', name: 'Drafter', type: 'workspace' }),
]);
renderApp();
await screen.findByText('Scout');
fireEvent.click(screen.getByRole('tab', { name: 'Personal' }));
expect(screen.getByText('Scout')).toBeInTheDocument();
expect(screen.queryByText('Drafter')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('tab', { name: 'Archive' }));
expect(screen.queryByText('Scout')).not.toBeInTheDocument();
});
it('C23: opens the workspace picker on workspace_ambiguous and retries with the chosen id', async () => {
mocks.adapter.listAgents.mockResolvedValue([makeAgent({ id: 'a1', name: 'Scout', workspaceIds: ['ws-1', 'ws-2'] })]);
mocks.adapter.runAgent
.mockRejectedValueOnce(Object.assign(new Error('runAgent failed (400): workspace_ambiguous'), {
status: 400,
body: { error: 'workspace_ambiguous', workspaceIds: ['ws-1', 'ws-2'] },
}))
.mockResolvedValueOnce({ sessionId: 's1', workspaceId: 'ws-1', status: 'spawned', task: 'Research the market' });
renderApp();
await screen.findByText('Scout');
fireEvent.click(screen.getByRole('button', { name: 'Run Scout' }));
const picker = await screen.findByTestId('agent-workspace-picker');
// Ids resolve to workspace names through the workspaces prop.
fireEvent.click(within(picker).getByRole('button', { name: 'Acme Research' }));
await waitFor(() => expect(mocks.adapter.runAgent).toHaveBeenCalledTimes(2));
expect(mocks.adapter.runAgent).toHaveBeenNthCalledWith(1, 'a1', {});
expect(mocks.adapter.runAgent).toHaveBeenNthCalledWith(2, 'a1', { workspaceId: 'ws-1' });
});
it('C23 (drawer path): ambiguity closes the modal detail drawer before opening the picker', async () => {
mocks.adapter.listAgents.mockResolvedValue([makeAgent({ id: 'a1', name: 'Scout', workspaceIds: ['ws-1', 'ws-2'] })]);
mocks.adapter.runAgent.mockRejectedValueOnce(Object.assign(new Error('runAgent failed (400): workspace_ambiguous'), {
status: 400,
body: { error: 'workspace_ambiguous', workspaceIds: ['ws-1', 'ws-2'] },
}));
renderApp();
await screen.findByText('Scout');
// Open the detail drawer, then Run from its footer (accessible name is
// exactly 'Run' — distinct from the list row's 'Run Scout').
fireEvent.click(screen.getByRole('button', { name: 'Open agent Scout' }));
fireEvent.click(await screen.findByRole('button', { name: 'Run' }));
expect(await screen.findByTestId('agent-workspace-picker')).toBeInTheDocument();
// The drawer is a portaled MODAL sheet (z-50 + pointer-events lock): if it
// stayed open the picker would be painted over and inert. It must be gone.
await waitFor(() => expect(screen.queryByRole('button', { name: 'Run' })).not.toBeInTheDocument());
});
it('pauses a running agent through adapter.pauseAgent', async () => {
mocks.adapter.listAgents.mockResolvedValue([makeAgent({ id: 'a2', name: 'Drafter', status: 'running' })]);
mocks.adapter.pauseAgent.mockResolvedValue({ ok: true, paused: 1 });
renderApp();
await screen.findByText('Drafter');
fireEvent.click(screen.getByRole('button', { name: 'Pause Drafter' }));
await waitFor(() => expect(mocks.adapter.pauseAgent).toHaveBeenCalledWith('a2'));
// The list reloads after the pause completes.
await waitFor(() => expect(mocks.adapter.listAgents).toHaveBeenCalledTimes(2));
});
it('shows the empty state when no agents exist', async () => {
mocks.adapter.listAgents.mockResolvedValue([]);
renderApp();
expect(await screen.findByText(/No custom agents yet/)).toBeInTheDocument();
// Empty custom-agent list must still show the built-in workspace
// assistants — "No agents" while agents demonstrably work was a
// judge-flagged contradiction.
expect(screen.getByText(/Already working for you/)).toBeInTheDocument();
expect(screen.getByText(/Acme Research/)).toBeInTheDocument();
});
it('sparse fleet shows the browse-all-specialists card that opens the Templates view', async () => {
mocks.adapter.listAgents.mockResolvedValue([]);
renderApp();
await screen.findByText(/No custom agents yet/);
// Round-6 fix 4b: ONE affordance (avatar sample + count), not 22
// indistinguishable per-persona thumbnails.
const roster = screen.getByTestId('persona-roster');
expect(roster).toHaveTextContent('Browse all 22 specialists');
expect(within(roster).getAllByRole('button')).toHaveLength(1);
fireEvent.click(within(roster).getByRole('button', { name: /browse all 22 specialists/i }));
expect(screen.getByRole('button', { name: /Templates/ })).toHaveAttribute('aria-pressed', 'true');
});
it('a11y: templates search control exposes stable form metadata', async () => {
mocks.adapter.listAgents.mockResolvedValue([]);
renderApp();
await screen.findByText(/No custom agents yet/);
fireEvent.click(within(screen.getByTestId('persona-roster')).getByRole('button', { name: /browse all 22 specialists/i }));
const search = await screen.findByRole('textbox', { name: 'Search persona templates' });
expect(search).toHaveAttribute('name', 'agentTemplateSearch');
expect(search).toHaveAttribute('autocomplete', 'off');
});
it('runs an agent group in the active workspace and keeps its Room handoff', async () => {
mocks.adapter.listAgents.mockResolvedValue([]);
mocks.adapter.getAgentGroups.mockResolvedValueOnce([{
id: 'group-1',
name: 'Research pair',
strategy: 'parallel',
members: [
{ agentId: 'researcher', roleInGroup: 'lead', executionOrder: 1 },
{ agentId: 'general-purpose', roleInGroup: 'worker', executionOrder: 2 },
],
}]);
mocks.adapter.runAgentGroup.mockResolvedValueOnce({
jobId: 'job-1',
roomId: 'room-1',
workspaceId: 'ws-2',
status: 'queued',
});
renderApp();
await screen.findByText(/No custom agents yet/);
fireEvent.click(screen.getByRole('button', { name: /^Templates$/ }));
fireEvent.click(await screen.findByRole('tab', { name: /Groups \(1\)/ }));
fireEvent.click(screen.getByRole('button', { name: 'Select group "Research pair"' }));
fireEvent.change(screen.getByRole('textbox', { name: 'Group task' }), {
target: { value: 'Compare the launch plans' },
});
fireEvent.click(screen.getByRole('button', { name: 'Run' }));
await waitFor(() => expect(mocks.adapter.runAgentGroup).toHaveBeenCalledWith(
'group-1',
'Compare the launch plans',
{ workspaceId: 'ws-2' },
));
expect(await screen.findByRole('link', { name: 'Open Room' })).toHaveAttribute('href', '/room?room=room-1');
});
it('shows the error state with a Retry that reloads', async () => {
mocks.adapter.listAgents.mockRejectedValueOnce(new Error('listAgents failed: 500'));
renderApp();
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent('listAgents failed: 500');
mocks.adapter.listAgents.mockResolvedValueOnce([makeAgent({ name: 'Recovered' })]);
fireEvent.click(screen.getByRole('button', { name: /Retry/ }));
expect(await screen.findByText('Recovered')).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,345 @@
/**
* Phase 3B (S11) — Automation Center component behaviour over a mocked
* adapter: render-from-data, success-rate tile math (C27), the C26
* validation-only Test preview framing, pause flow, empty + error states.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { Automation } from '@waggle/shared';
import type { AutomationLog } from '@/lib/types';
const mocks = vi.hoisted(() => ({
adapter: {
// ServiceProvider's mount connect() — resolves so `connecting` settles
// and the app's connect-gated refresh() fires.
connect: vi.fn().mockResolvedValue(undefined),
listAutomations: vi.fn(),
getAutomationLogs: vi.fn(),
runAutomation: vi.fn(),
pauseAutomation: vi.fn(),
updateAutomation: vi.fn(),
createAutomation: vi.fn(),
deleteCronJob: vi.fn(),
testAutomation: vi.fn(),
// AutomationBuilder (3C) deps: workspace scope picker + edit-mode
// jobType/jobConfig read off the cron rows.
getWorkspaces: vi.fn(),
getCronJobs: vi.fn(),
// Multi-workspace UX (engine pill + grouping).
getEngineStatus: vi.fn(),
// L2 approval queue.
getPendingApprovals: vi.fn(),
respondApproval: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import AutomationCenterApp from '@/components/os/apps/AutomationCenterApp';
import { ServiceProvider } from '@/providers/ServiceProvider';
import { stashDeepLink } from '@/lib/app-deeplink';
function makeAutomation(over: Partial<Automation> = {}): Automation {
return {
id: '1', name: 'Nightly consolidation', triggerType: 'schedule', schedule: '0 9 * * *',
actions: ['memory_consolidation'], workspaceId: '*', status: 'active',
...over,
};
}
function log(id: number, success: boolean): AutomationLog {
return { id, executedAt: `2026-06-0${(id % 9) + 1}T01:00:00Z`, durationMs: 900, success, resultSummary: success ? 'ok' : null, error: success ? null : 'exploded' };
}
const renderApp = () => render(
<ServiceProvider><TooltipProvider><AutomationCenterApp /></TooltipProvider></ServiceProvider>,
);
beforeEach(() => {
vi.clearAllMocks();
mocks.adapter.connect.mockResolvedValue(undefined);
mocks.adapter.getAutomationLogs.mockResolvedValue([]);
mocks.adapter.getWorkspaces.mockResolvedValue([]);
mocks.adapter.getCronJobs.mockResolvedValue([]);
mocks.adapter.getEngineStatus.mockResolvedValue({ running: true, host: 'test-host' });
mocks.adapter.getPendingApprovals.mockResolvedValue({ pending: [], count: 0 });
mocks.adapter.respondApproval.mockResolvedValue({ ok: true });
});
afterEach(cleanup);
describe('AutomationCenterApp', () => {
it('renders overview tiles with the C27 success rate derived from logs', async () => {
mocks.adapter.listAutomations.mockResolvedValue([makeAutomation()]);
mocks.adapter.getAutomationLogs.mockResolvedValue([log(1, true), log(2, true), log(3, false), log(4, true)]);
renderApp();
expect(await screen.findByTestId('automation-overview-tiles')).toBeInTheDocument();
expect(screen.getByTestId('automation-success-rate')).toHaveTextContent('75%');
expect(screen.getByText('Active schedules')).toBeInTheDocument();
// No "hours saved" tile anywhere (C27).
expect(screen.queryByText(/hours saved/i)).not.toBeInTheDocument();
});
it('shows the Loops engine pill as live with the host (sovereignty)', async () => {
mocks.adapter.listAutomations.mockResolvedValue([makeAutomation()]);
mocks.adapter.getEngineStatus.mockResolvedValue({ running: true, host: 'lab-box' });
renderApp();
expect(await screen.findByText(/Engine live/)).toBeInTheDocument();
expect(screen.getByTestId('automation-engine-pill')).toHaveTextContent('lab-box');
});
it('shows the engine pill as offline when the local engine is not running', async () => {
mocks.adapter.listAutomations.mockResolvedValue([makeAutomation()]);
mocks.adapter.getEngineStatus.mockResolvedValue({ running: false, host: 'lab-box' });
renderApp();
expect(await screen.findByText('Engine offline')).toBeInTheDocument();
});
it('groups the Scheduled tab by workspace when automations span multiple workspaces', async () => {
mocks.adapter.listAutomations.mockResolvedValue([
makeAutomation({ id: '1', name: 'Sales digest', workspaceId: 'w1' }),
makeAutomation({ id: '2', name: 'Legal sweep', workspaceId: 'w2' }),
]);
mocks.adapter.getWorkspaces.mockResolvedValue([
{ id: 'w1', name: 'Acme Sales' }, { id: 'w2', name: 'Legal' },
]);
renderApp();
await screen.findByTestId('automation-overview-tiles');
fireEvent.click(screen.getByRole('tab', { name: 'Scheduled' }));
expect(await screen.findByTestId('automation-workspace-groups')).toBeInTheDocument();
expect(screen.getByText('Acme Sales')).toBeInTheDocument();
expect(screen.getByText('Legal')).toBeInTheDocument();
});
it('does not group the Scheduled tab when all automations share one workspace', async () => {
mocks.adapter.listAutomations.mockResolvedValue([makeAutomation()]); // workspaceId '*'
renderApp();
await screen.findByTestId('automation-overview-tiles');
fireEvent.click(screen.getByRole('tab', { name: 'Scheduled' }));
expect(await screen.findByText('Nightly consolidation')).toBeInTheDocument();
expect(screen.queryByTestId('automation-workspace-groups')).toBeNull();
});
it('creates a report-only Loop from a knowledge-worker template', async () => {
mocks.adapter.listAutomations.mockResolvedValue([]);
mocks.adapter.createAutomation.mockResolvedValue(makeAutomation());
renderApp();
fireEvent.click(await screen.findByTestId('automation-template-daily-desk-brief'));
await waitFor(() => expect(mocks.adapter.createAutomation).toHaveBeenCalled());
const arg = mocks.adapter.createAutomation.mock.calls[0][0];
expect(arg.jobType).toBe('loop');
expect(arg.trigger).toEqual({ type: 'schedule', cron: '0 8 * * *' });
expect(arg.jobConfig.prompt).toContain('attention today');
});
it('surfaces held actions awaiting approval and approves via respondApproval (L2)', async () => {
mocks.adapter.listAutomations.mockResolvedValue([]);
mocks.adapter.getPendingApprovals.mockResolvedValue({
pending: [{ requestId: 'pa-1', toolName: 'send_email', input: { to: 'x@y.z' }, timestamp: 1, source: 'held', riskLevel: 'medium', summary: 'Send a follow-up to x' }],
count: 1,
});
renderApp();
expect(await screen.findByTestId('automation-pending-actions')).toBeInTheDocument();
// The card shows the REAL action target (recipient), not the maker's summary.
expect(screen.getByText('To: x@y.z')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Approve send_email' }));
await waitFor(() => expect(mocks.adapter.respondApproval).toHaveBeenCalledWith('pa-1', true));
});
it('creates an assist-mode Loop from a template when the toggle is on (L2)', async () => {
mocks.adapter.listAutomations.mockResolvedValue([]);
mocks.adapter.createAutomation.mockResolvedValue(makeAutomation());
renderApp();
await screen.findByTestId('automation-overview-tiles');
fireEvent.click(screen.getByTestId('automation-template-assist')); // turn assist on
fireEvent.click(await screen.findByTestId('automation-template-daily-desk-brief'));
await waitFor(() => expect(mocks.adapter.createAutomation).toHaveBeenCalled());
const arg = mocks.adapter.createAutomation.mock.calls[0][0];
expect(arg.jobConfig.mode).toBe('assist');
});
it('names template workspace and assist-mode controls', async () => {
mocks.adapter.listAutomations.mockResolvedValue([]);
mocks.adapter.getWorkspaces.mockResolvedValue([{ id: 'ws-1', name: 'Acme Research' }]);
renderApp();
const templates = await screen.findByTestId('automation-templates');
const workspace = within(templates).getByRole('combobox', { name: /workspace for the new loop/i });
expect(workspace).toHaveAttribute('name', 'automationTemplateWorkspace');
expect(workspace).toHaveAttribute('autocomplete', 'off');
expect(workspace).toHaveClass('focus-visible:ring-ring');
const assistMode = within(templates).getByRole('checkbox', { name: /propose actions for approval/i });
expect(assistMode).toHaveAttribute('name', 'automationTemplateAssistMode');
expect(assistMode).toHaveClass('focus-visible:ring-ring');
});
it('surfaces a failed latest run in the attention list and as a Failed badge', async () => {
mocks.adapter.listAutomations.mockResolvedValue([makeAutomation()]);
mocks.adapter.getAutomationLogs.mockResolvedValue([log(1, false)]);
renderApp();
const attention = await screen.findByTestId('automation-attention');
expect(attention).toHaveTextContent('Nightly consolidation — exploded');
fireEvent.click(screen.getByRole('tab', { name: 'Scheduled' }));
expect(await screen.findByText('Failed')).toBeInTheDocument();
});
it('lists rows on the Scheduled tab and pauses via adapter.pauseAutomation', async () => {
mocks.adapter.listAutomations.mockResolvedValue([makeAutomation()]);
mocks.adapter.pauseAutomation.mockResolvedValue(undefined);
renderApp();
await screen.findByTestId('automation-overview-tiles');
fireEvent.click(screen.getByRole('tab', { name: 'Scheduled' }));
expect(await screen.findByText('Nightly consolidation')).toBeInTheDocument();
expect(screen.getByText('Every day at 9:00 AM')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: 'Pause Nightly consolidation' }));
expect(mocks.adapter.pauseAutomation).toHaveBeenCalledWith('1');
});
it('asks in-app before deleting an automation', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
mocks.adapter.listAutomations.mockResolvedValue([makeAutomation()]);
mocks.adapter.deleteCronJob.mockResolvedValue(undefined);
renderApp();
await screen.findByTestId('automation-overview-tiles');
fireEvent.click(screen.getByRole('tab', { name: 'Scheduled' }));
fireEvent.click(await screen.findByRole('button', { name: 'Delete Nightly consolidation' }));
expect(confirmSpy).not.toHaveBeenCalled();
expect(mocks.adapter.deleteCronJob).not.toHaveBeenCalled();
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent(/delete automation/i);
expect(modal).toHaveTextContent(/Nightly consolidation/i);
expect(modal).toHaveTextContent(/run history/i);
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.deleteCronJob).toHaveBeenCalledWith('1'));
});
it('C26: the Builder review-step Check renders issues + the nothing-executed framing', async () => {
mocks.adapter.listAutomations.mockResolvedValue([]);
mocks.adapter.testAutomation.mockResolvedValue({
previewResult: {
ok: false,
jobType: 'memory_consolidation',
triggerType: 'schedule',
issues: ['invalid cron expression "nope": expected 5 fields'],
executed: false,
wouldRun: 'Would run job "memory_consolidation" on schedule "0 9 * * *"',
},
});
renderApp();
await screen.findByTestId('automation-overview-tiles');
fireEvent.click(screen.getByRole('button', { name: /New/ }));
await screen.findByTestId('automation-builder');
fireEvent.change(screen.getByLabelText('Automation name'), { target: { value: 'Draft check' } });
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Action
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Condition
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Review
fireEvent.click(screen.getByTestId('automation-builder-check'));
const preview = await screen.findByTestId('automation-test-preview');
expect(preview).toHaveTextContent('1 issue found');
expect(preview).toHaveTextContent('invalid cron expression');
expect(preview).toHaveTextContent('Validation only — nothing was executed or saved.');
expect(mocks.adapter.testAutomation).toHaveBeenCalledTimes(1);
// What the FE SENDS is part of the C26 contract — a drifted draft shape
// (wrong trigger, missing jobType) must fail here, not only in the render.
expect(mocks.adapter.testAutomation).toHaveBeenCalledWith(expect.objectContaining({
name: 'Draft check',
jobType: 'memory_consolidation',
trigger: expect.objectContaining({ type: 'schedule' }),
}));
// The check must never trigger a real run.
expect(mocks.adapter.runAutomation).not.toHaveBeenCalled();
});
it('C26 (edit mode): the Check draft carries the stored row id + actions, not a bare agent_task fallback', async () => {
mocks.adapter.listAutomations.mockResolvedValue([makeAutomation()]);
// 3C: the Builder reads the stored jobType/jobConfig off the cron rows.
mocks.adapter.getCronJobs.mockResolvedValue([
{ id: '1', name: 'Nightly consolidation', schedule: '0 9 * * *', workspaceId: '*', enabled: true, jobType: 'memory_consolidation', jobConfig: {} },
]);
mocks.adapter.testAutomation.mockResolvedValue({
previewResult: {
ok: true, jobType: 'memory_consolidation', triggerType: 'schedule',
issues: [], executed: false,
wouldRun: 'Would run job "memory_consolidation" on schedule "0 9 * * *"',
},
});
renderApp();
await screen.findByTestId('automation-overview-tiles');
fireEvent.click(screen.getByRole('tab', { name: 'Scheduled' }));
fireEvent.click(await screen.findByRole('button', { name: 'Edit Nightly consolidation' }));
await screen.findByTestId('automation-builder');
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Action
// Output-channel select rendering = the stored config finished loading.
await screen.findByLabelText('Where the result goes');
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Condition
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Review
fireEvent.click(screen.getByTestId('automation-builder-check'));
await screen.findByTestId('automation-test-preview');
expect(mocks.adapter.testAutomation).toHaveBeenCalledWith(expect.objectContaining({
id: '1',
actions: ['memory_consolidation'],
name: 'Nightly consolidation',
}));
// Edit mode never sends jobType (not patchable — the server resolves it
// from the stored row via the id). jobConfig IS sent in 3C: the Builder
// now edits prompt/output channel, merged server-side over the blob.
const sent = mocks.adapter.testAutomation.mock.calls[0][0] as Record<string, unknown>;
expect(sent.jobType).toBeUndefined();
expect(sent.jobConfig).toEqual({ outputChannel: 'log' });
});
it('Journey 16 (cold open): a stashed deep-link lands on Logs with the failing automation preselected', async () => {
mocks.adapter.listAutomations.mockResolvedValue([makeAutomation()]);
mocks.adapter.getAutomationLogs.mockResolvedValue([log(1, false)]);
// Desktop stashes the intent when the dispatch happens before this app
// mounts (the live listener doesn't exist yet) — consumed once on mount.
stashDeepLink({ appId: 'scheduled-jobs', tab: 'logs', automationId: '1' });
renderApp();
expect(await screen.findByRole('tab', { name: 'Logs', selected: true })).toBeInTheDocument();
expect(await screen.findByText('Retry / run now')).toBeInTheDocument();
});
it('Journey 16 (already mounted): the live event switches to Logs and preselects the automation', async () => {
mocks.adapter.listAutomations.mockResolvedValue([makeAutomation()]);
renderApp();
await screen.findByTestId('automation-overview-tiles');
fireEvent(window, new CustomEvent('waggle:open-app', {
detail: { appId: 'scheduled-jobs', tab: 'logs', automationId: '1' },
}));
expect(await screen.findByRole('tab', { name: 'Logs', selected: true })).toBeInTheDocument();
expect(await screen.findByText('Retry / run now')).toBeInTheDocument();
});
it('shows the empty state when no automations exist', async () => {
mocks.adapter.listAutomations.mockResolvedValue([]);
renderApp();
expect(await screen.findByText(/No automations yet/)).toBeInTheDocument();
});
it('shows the error state with Retry', async () => {
mocks.adapter.listAutomations.mockRejectedValueOnce(new Error('listAutomations failed: 500'));
renderApp();
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent('listAutomations failed: 500');
mocks.adapter.listAutomations.mockResolvedValueOnce([makeAutomation({ name: 'Recovered job' })]);
fireEvent.click(screen.getByRole('button', { name: /Retry/ }));
expect(await screen.findByTestId('automation-overview-tiles')).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,170 @@
/**
* Phase 3B (S06) — Skills Hub component behaviour over a mocked adapter:
* My Skills per-skill table, Custom-tab derivation (user-authored = not in
* any catalog), the C37 preview-only Test rendering, and pack-tab behaviour.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
const mocks = vi.hoisted(() => ({
adapter: {
// ServiceProvider's mount connect() — resolves so `connecting` settles
// and the app's connect-gated load() fires.
connect: vi.fn().mockResolvedValue(undefined),
getSkills: vi.fn(),
getStarterPacks: vi.fn(),
getMarketplacePacks: vi.fn(),
getCapabilityPacks: vi.fn(),
testSkill: vi.fn(),
installSkill: vi.fn(),
installMarketplacePack: vi.fn(),
createSkill: vi.fn(),
updateSkill: vi.fn(),
fetch: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import CapabilitiesApp from '@/components/os/apps/CapabilitiesApp';
import { ServiceProvider } from '@/providers/ServiceProvider';
const renderApp = () => render(
<ServiceProvider><TooltipProvider><CapabilitiesApp /></TooltipProvider></ServiceProvider>,
);
beforeEach(() => {
vi.clearAllMocks();
mocks.adapter.connect.mockResolvedValue(undefined);
mocks.adapter.getSkills.mockResolvedValue([
{ id: 'deep-research', name: 'deep-research', preview: 'Research anything deeply', installed: true },
{ id: 'my-custom', name: 'my-custom', preview: 'A skill I authored', installed: true },
]);
mocks.adapter.getStarterPacks.mockResolvedValue([
{ id: 'deep-research', name: 'deep-research', description: 'Starter research skill', category: 'research', trust: 'verified', installed: true, skills: [] },
]);
mocks.adapter.getMarketplacePacks.mockResolvedValue([]);
mocks.adapter.getCapabilityPacks.mockResolvedValue([]);
});
afterEach(cleanup);
describe('CapabilitiesApp — Skills Hub', () => {
it('a11y: search control exposes stable form metadata', async () => {
renderApp();
await screen.findByText('deep-research');
const search = screen.getByRole('textbox', { name: 'Search skills' });
expect(search).toHaveAttribute('name', 'skillSearch');
expect(search).toHaveAttribute('autocomplete', 'off');
});
it('renders the My Skills per-skill table from the adapter', async () => {
renderApp();
expect(await screen.findByText('deep-research')).toBeInTheDocument();
expect(screen.getByText('my-custom')).toBeInTheDocument();
expect(screen.getByText('Research anything deeply')).toBeInTheDocument();
// Catalog-known skill reads as installed; user-authored one as custom.
expect(screen.getByText('installed')).toBeInTheDocument();
expect(screen.getByText('custom')).toBeInTheDocument();
});
it('P5/D4: badges an agent-authored skill "agent · review"', async () => {
mocks.adapter.getSkills.mockResolvedValue([
{ id: 'agent-made', name: 'agent-made', preview: 'Authored by the agent', installed: true, initiator: 'agent', source: 'chat' },
{ id: 'user-made', name: 'user-made', preview: 'Authored by me', installed: true, initiator: 'user' },
]);
renderApp();
expect(await screen.findByText('agent-made')).toBeInTheDocument();
// The agent skill carries the review badge; the user skill does not.
expect(screen.getByText('agent · review')).toBeInTheDocument();
expect(screen.getAllByText('agent · review')).toHaveLength(1);
// Review #5: the agent skill must NOT also wear the name-heuristic 'custom'
// status — provenance supersedes it (D4(iv)). The user skill keeps 'custom'.
expect(screen.queryAllByText('custom')).toHaveLength(1);
});
it('the Custom tab shows only user-authored skills (not in any catalog)', async () => {
renderApp();
await screen.findByText('deep-research');
fireEvent.click(screen.getByRole('tab', { name: 'Custom' }));
expect(screen.getByText('my-custom')).toBeInTheDocument();
expect(screen.queryByText('deep-research')).not.toBeInTheDocument();
});
it('marketplace-installed skills classify as marketplace, not Custom ("authored locally")', async () => {
mocks.adapter.getSkills.mockResolvedValue([
{ id: 'mp-skill', name: 'mp-skill', preview: 'Installed from the marketplace', installed: true },
{ id: 'my-custom', name: 'my-custom', preview: 'A skill I authored', installed: true },
]);
mocks.adapter.getMarketplacePacks.mockResolvedValue([
{ id: 'mp-pack', name: 'mp-pack', description: 'Marketplace pack', category: 'research', trust: 'community', installed: true, skills: ['mp-skill'] },
]);
renderApp();
await screen.findByText('mp-skill');
expect(screen.getByText('marketplace')).toBeInTheDocument();
fireEvent.click(screen.getByRole('tab', { name: 'Custom' }));
expect(screen.getByText('my-custom')).toBeInTheDocument();
expect(screen.queryByText('mp-skill')).not.toBeInTheDocument();
});
it('a failed catalog fetch degrades skills to installed instead of mislabeling them custom', async () => {
mocks.adapter.getStarterPacks.mockRejectedValueOnce(new Error('getStarterPacks failed: 500'));
renderApp();
await screen.findByText('my-custom');
// No catalog → 'custom' ("not in any catalog") is unprovable; nothing may
// claim it. The Custom tab must therefore be empty, not polluted.
expect(screen.queryByText('custom')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('tab', { name: 'Custom' }));
expect(screen.queryByText('my-custom')).not.toBeInTheDocument();
});
it('C37: Test renders the injected-prompt preview with the nothing-executed framing', async () => {
mocks.adapter.testSkill.mockResolvedValue({
skill: { name: 'deep-research' },
wouldInject: 'You are a deep researcher. Steps: …',
wouldInjectLength: 34,
});
renderApp();
await screen.findByText('deep-research');
fireEvent.click(screen.getByRole('button', { name: 'Test skill deep-research (preview only)' }));
const preview = await screen.findByTestId('skill-test-preview');
expect(preview).toHaveTextContent('Test: deep-research');
expect(preview).toHaveTextContent('You are a deep researcher');
expect(preview).toHaveTextContent('Preview only — nothing was executed');
expect(mocks.adapter.testSkill).toHaveBeenCalledWith('deep-research');
});
it('the Packs tab shows the catalog grid with installed markers', async () => {
renderApp();
await screen.findByText('my-custom');
fireEvent.click(screen.getByRole('tab', { name: 'Packs' }));
const card = await screen.findByTestId('skill-pack-card');
expect(card).toHaveTextContent('deep-research');
expect(card).toHaveTextContent('Installed');
});
it('the Workspace tab states honestly that scope metadata is not exposed yet', async () => {
renderApp();
await screen.findByText('my-custom');
fireEvent.click(screen.getByRole('tab', { name: 'Workspace' }));
expect(screen.getByText(/No workspace-scoped skills/)).toBeInTheDocument();
expect(screen.getByText(/scope metadata/)).toBeInTheDocument();
});
it('shows an error state with Retry when the skills load fails', async () => {
mocks.adapter.getSkills.mockRejectedValueOnce(new Error('boom'));
renderApp();
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent('Failed to load skills');
fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
expect(await screen.findByText('deep-research')).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,256 @@
/**
* Phase 3C (S18) — Agent Builder: step gating, the §12.9 review surface, the
* exact create payload through the Agent Center (+ post-create Run offer),
* the elevated-access ApprovalModal gate, the persona prefill path, and the
* house overlay a11y contract (focus trap + Escape).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { Agent } from '@/lib/types';
const mocks = vi.hoisted(() => ({
adapter: {
connect: vi.fn().mockResolvedValue(undefined),
listAgents: vi.fn(),
runAgent: vi.fn(),
pauseAgent: vi.fn(),
patchAgent: vi.fn(),
createAgent: vi.fn(),
getAgentTraces: vi.fn(),
// AgentBuilder catalogs:
getPersonas: vi.fn(),
getSkills: vi.fn(),
getConnectors: vi.fn(),
getCapabilityStatus: vi.fn(),
getProviders: vi.fn(),
// TemplatesView deps (module mock stays total):
getAgentGroups: vi.fn().mockResolvedValue([]),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import AgentsApp, { resetAgentsRouteCache } from '@/components/os/apps/AgentsApp';
import AgentBuilder from '@/components/os/apps/agents/AgentBuilder';
import { ServiceProvider } from '@/providers/ServiceProvider';
function makeAgent(over: Partial<Agent> = {}): Agent {
return {
id: 'a1', name: 'Scout', goal: 'Research the market', type: 'personal',
model: 'auto', autonomyLevel: 'guided', memoryScopes: ['personal'],
status: 'idle', createdAt: '2026-06-01T00:00:00Z', updatedAt: '2026-06-01T00:00:00Z',
...over,
};
}
const WORKSPACES = [
{ id: 'ws-1', name: 'Acme Research', group: 'work' },
{ id: 'ws-2', name: 'Personal Lab', group: 'personal' },
];
const renderApp = () => render(
<MemoryRouter>
<ServiceProvider>
<TooltipProvider>
<AgentsApp workspaces={WORKSPACES} />
</TooltipProvider>
</ServiceProvider>
</MemoryRouter>,
);
beforeEach(() => {
vi.clearAllMocks();
resetAgentsRouteCache(); // Pillar 2.6: reset the module-level route cache between tests
mocks.adapter.connect.mockResolvedValue(undefined);
mocks.adapter.getAgentTraces.mockResolvedValue([]);
mocks.adapter.getPersonas.mockResolvedValue([{ id: 'researcher', name: 'Researcher', description: 'Digs deep' }]);
mocks.adapter.getSkills.mockResolvedValue([
{ id: 'deep-research', name: 'deep-research', installed: true },
{ id: 'weekly-report', name: 'weekly-report', installed: true },
]);
mocks.adapter.getConnectors.mockResolvedValue([{ id: 'github', name: 'GitHub', type: 'github', status: 'connected' }]);
mocks.adapter.getCapabilityStatus.mockResolvedValue({ mcpServers: [{ name: 'filesystem', tools: 3 }] });
mocks.adapter.getProviders.mockResolvedValue({ providers: [], search: [], activeSearch: 'duckduckgo' });
mocks.adapter.getAgentGroups.mockResolvedValue([]);
});
afterEach(cleanup);
const openBuilder = async () => {
fireEvent.click(screen.getByRole('button', { name: /New Agent/ }));
return screen.findByTestId('agent-builder');
};
describe('AgentBuilder — S18', () => {
it('gates the Identity step on name + goal', async () => {
mocks.adapter.listAgents.mockResolvedValue([]);
renderApp();
await screen.findByText(/No custom agents yet/);
await openBuilder();
const next = screen.getByTestId('agent-builder-next');
expect(next).toBeDisabled();
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Scout' } });
expect(next).toBeDisabled();
fireEvent.change(screen.getByLabelText('Goal'), { target: { value: 'Research the market' } });
expect(next).not.toBeDisabled();
});
it('a11y: builder fields expose stable form metadata', () => {
render(<AgentBuilder onCreate={vi.fn()} onCancel={vi.fn()} />);
expect(screen.getByLabelText('Name')).toHaveAttribute('name', 'agentName');
expect(screen.getByLabelText('Name')).toHaveAttribute('autocomplete', 'off');
expect(screen.getByLabelText('Goal')).toHaveAttribute('name', 'agentGoal');
expect(screen.getByLabelText('Goal')).toHaveAttribute('autocomplete', 'off');
expect(screen.getByLabelText(/^Description/)).toHaveAttribute('name', 'agentDescription');
expect(screen.getByLabelText(/^Description/)).toHaveAttribute('autocomplete', 'off');
expect(screen.getByLabelText(/^Persona/)).toHaveAttribute('name', 'agentPersona');
expect(screen.getByLabelText('Type')).toHaveAttribute('name', 'agentType');
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Scout' } });
fireEvent.change(screen.getByLabelText('Goal'), { target: { value: 'Research the market' } });
fireEvent.click(screen.getByTestId('agent-builder-next'));
expect(screen.getByLabelText('Model id')).toHaveAttribute('name', 'agentModel');
expect(screen.getByLabelText('Model id')).toHaveAttribute('autocomplete', 'off');
expect(screen.getByLabelText('Autonomy level')).toHaveAttribute('name', 'agentAutonomyLevel');
});
// Headroom for parallel-suite load — this walk renders every wizard step
// and is the suite's known load-flake (passes in isolation).
it('happy path declares scope/memory/skills, reviews EVERY field, sends the exact payload and offers Run', { timeout: 20_000 }, async () => {
mocks.adapter.listAgents.mockResolvedValue([]);
const created = makeAgent({ id: 'a-new', name: 'Scout', workspaceIds: ['ws-1'], skillIds: ['deep-research'] });
mocks.adapter.createAgent.mockResolvedValue(created);
renderApp();
await screen.findByText(/No custom agents yet/);
await openBuilder();
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Scout' } });
fireEvent.change(screen.getByLabelText('Goal'), { target: { value: 'Research the market' } });
fireEvent.click(screen.getByTestId('agent-builder-next')); // → Capabilities (model defaults to auto)
fireEvent.click(screen.getByTestId('agent-builder-next')); // → Scope & memory
fireEvent.click(await screen.findByRole('button', { name: 'Acme Research' }));
fireEvent.click(await screen.findByRole('checkbox', { name: /deep-research/ }));
fireEvent.click(screen.getByTestId('agent-builder-next')); // → Permissions (none — stays default)
fireEvent.click(screen.getByTestId('agent-builder-next')); // → Review
// §12.9 rule #6: the review surface shows every declared field, and the
// explicit no-access copy for undeclared ones.
const review = screen.getByTestId('agent-builder-review');
expect(review).toHaveTextContent('Scout');
expect(review).toHaveTextContent('Research the market');
expect(review).toHaveTextContent('auto');
expect(review).toHaveTextContent('guided');
expect(review).toHaveTextContent('Acme Research');
expect(review).toHaveTextContent('personal');
expect(review).toHaveTextContent('deep-research');
expect(review).toHaveTextContent('None declared — no access'); // connectors + MCPs
expect(review).toHaveTextContent('Default permissions — elevated actions require approval');
mocks.adapter.listAgents.mockResolvedValue([created]);
fireEvent.click(screen.getByTestId('agent-builder-finish'));
await waitFor(() => expect(mocks.adapter.createAgent).toHaveBeenCalledTimes(1));
expect(mocks.adapter.createAgent).toHaveBeenCalledWith({
name: 'Scout',
goal: 'Research the market',
model: 'auto',
type: 'personal',
autonomyLevel: 'guided',
memoryScopes: ['personal'],
workspaceIds: ['ws-1'],
skillIds: ['deep-research'],
});
// Post-create: the detail drawer opens on the new agent and offers Run.
expect(await screen.findByRole('button', { name: 'Run' })).toBeInTheDocument();
});
it('elevated access (connector selected) warns inline and routes through the ApprovalModal', async () => {
mocks.adapter.listAgents.mockResolvedValue([]);
mocks.adapter.createAgent.mockResolvedValue(makeAgent());
renderApp();
await screen.findByText(/No custom agents yet/);
await openBuilder();
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Octo' } });
fireEvent.change(screen.getByLabelText('Goal'), { target: { value: 'Triage issues' } });
fireEvent.click(screen.getByTestId('agent-builder-next'));
fireEvent.click(screen.getByTestId('agent-builder-next'));
fireEvent.click(screen.getByTestId('agent-builder-next')); // → Permissions
fireEvent.click(await screen.findByRole('checkbox', { name: /GitHub/ }));
expect(screen.getByTestId('agent-builder-elevated-warning')).toBeInTheDocument();
fireEvent.click(screen.getByTestId('agent-builder-next')); // → Review
fireEvent.click(screen.getByTestId('agent-builder-finish'));
// No create yet — approval first (§17.3), with the scope readable as text
// in the same vocabulary the picker used (display name, not raw id).
expect(mocks.adapter.createAgent).not.toHaveBeenCalled();
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent('Connector: GitHub');
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.createAgent).toHaveBeenCalledTimes(1));
expect(mocks.adapter.createAgent).toHaveBeenCalledWith(expect.objectContaining({
name: 'Octo',
connectorIds: ['github'],
}));
});
it('prefill path (agent-from-persona): initial seeds the fields and the payload carries personaId', async () => {
const onCreate = vi.fn();
render(
<AgentBuilder
initial={{ personaId: 'researcher', name: 'Researcher', goal: 'Digs deep' }}
workspaces={WORKSPACES}
onCreate={onCreate}
onCancel={vi.fn()}
/>,
);
expect(screen.getByLabelText('Name')).toHaveValue('Researcher');
expect(screen.getByLabelText('Goal')).toHaveValue('Digs deep');
fireEvent.click(screen.getByTestId('agent-builder-next'));
fireEvent.click(screen.getByTestId('agent-builder-next'));
fireEvent.click(screen.getByTestId('agent-builder-next'));
fireEvent.click(screen.getByTestId('agent-builder-next'));
expect(screen.getByTestId('agent-builder-review')).toHaveTextContent('persona researcher');
fireEvent.click(screen.getByTestId('agent-builder-finish'));
expect(onCreate).toHaveBeenCalledWith(expect.objectContaining({
name: 'Researcher',
goal: 'Digs deep',
personaId: 'researcher',
}));
});
it('a11y: mounts as a focus-trapped dialog with aria-current step, Escape cancels', () => {
const onCancel = vi.fn();
render(<AgentBuilder onCreate={vi.fn()} onCancel={onCancel} />);
const dialog = screen.getByRole('dialog', { name: 'Agent Builder' });
expect(dialog).toHaveAttribute('aria-modal', 'true');
expect(dialog.contains(document.activeElement)).toBe(true);
expect(screen.getByTestId('agent-builder-step-identity')).toHaveAttribute('aria-current', 'step');
// Forward jumps past the gate are blocked at the step nav too — via
// aria-disabled (NOT disabled), so the pill stays in the Tab order.
const reviewPill = screen.getByTestId('agent-builder-step-review');
expect(reviewPill).toHaveAttribute('aria-disabled', 'true');
expect(reviewPill).not.toBeDisabled();
fireEvent.click(reviewPill);
expect(screen.getByTestId('agent-builder-step-identity')).toHaveAttribute('aria-current', 'step');
fireEvent.keyDown(dialog, { key: 'Escape' });
expect(onCancel).toHaveBeenCalledTimes(1);
});
it('does not steal focus from a field when the parent re-renders with a fresh onCancel (toast-driven re-render)', () => {
const { rerender } = render(<AgentBuilder onCreate={vi.fn()} onCancel={() => undefined} />);
const nameInput = screen.getByLabelText('Name');
nameInput.focus();
expect(document.activeElement).toBe(nameInput);
// New inline closure identity — previously tore the focus trap down and
// refocused the first tabbable (the Close X) mid-typing.
rerender(<AgentBuilder onCreate={vi.fn()} onCancel={() => undefined} />);
expect(document.activeElement).toBe(nameInput);
});
});

View File

@@ -0,0 +1,306 @@
/**
* Phase 3C (S20) — Automation Builder: step gating, the exact create payload
* through the Center, the edit-mode jobConfig round-trip (stored config read
* off the cron rows → prompt edit → PATCH merge), the agent_task
* ApprovalModal gate, and the house overlay a11y contract (focus trap +
* Escape).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { Automation } from '@waggle/shared';
const mocks = vi.hoisted(() => ({
adapter: {
connect: vi.fn().mockResolvedValue(undefined),
listAutomations: vi.fn(),
getAutomationLogs: vi.fn(),
runAutomation: vi.fn(),
pauseAutomation: vi.fn(),
updateAutomation: vi.fn(),
createAutomation: vi.fn(),
deleteCronJob: vi.fn(),
testAutomation: vi.fn(),
getWorkspaces: vi.fn(),
getCronJobs: vi.fn(),
// AutomationCenterApp polls these on mount (engine pill + L2 approval queue).
// Without them the poll's `adapter.getEngineStatus()` call is `undefined()`,
// which throws synchronously in the effect (before the `.catch`) → the
// component crashes to the error boundary and the tests can't find their
// testids. Mirrors the phase3b-automation-center mock.
getEngineStatus: vi.fn(),
getPendingApprovals: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import AutomationCenterApp from '@/components/os/apps/AutomationCenterApp';
import AutomationBuilder from '@/components/os/apps/automations/AutomationBuilder';
import { ServiceProvider } from '@/providers/ServiceProvider';
function makeAutomation(over: Partial<Automation> = {}): Automation {
return {
id: '1', name: 'Nightly agent', triggerType: 'schedule', schedule: '0 9 * * *',
actions: ['agent_task'], workspaceId: '*', status: 'active',
...over,
};
}
const renderApp = () => render(
<ServiceProvider><TooltipProvider><AutomationCenterApp /></TooltipProvider></ServiceProvider>,
);
beforeEach(() => {
vi.clearAllMocks();
mocks.adapter.connect.mockResolvedValue(undefined);
mocks.adapter.getAutomationLogs.mockResolvedValue([]);
mocks.adapter.getWorkspaces.mockResolvedValue([{ id: 'ws-1', name: 'Acme Research', group: 'work' }]);
mocks.adapter.getCronJobs.mockResolvedValue([]);
// AutomationCenterApp's mount poll: return real Promises (a bare vi.fn()
// yields undefined → `.then` throws in the effect and crashes the app).
mocks.adapter.getEngineStatus.mockResolvedValue({ running: true, host: 'test-host' });
mocks.adapter.getPendingApprovals.mockResolvedValue({ pending: [], count: 0 });
});
afterEach(cleanup);
describe('AutomationBuilder — S20', () => {
it('gates step advance on required input (name, then agent_task prompt)', async () => {
render(<AutomationBuilder onSubmit={vi.fn()} onCancel={vi.fn()} />);
const next = screen.getByTestId('automation-builder-next');
// Trigger step: empty name blocks Next.
expect(next).toBeDisabled();
fireEvent.change(screen.getByLabelText('Automation name'), { target: { value: 'Morning brief' } });
expect(next).not.toBeDisabled();
// Action step: agent_task without a prompt blocks Next.
fireEvent.click(next);
fireEvent.change(screen.getByTestId('automation-job-type'), { target: { value: 'agent_task' } });
expect(screen.getByTestId('automation-builder-next')).toBeDisabled();
fireEvent.change(screen.getByTestId('automation-prompt'), { target: { value: 'Summarise the inbox' } });
expect(screen.getByTestId('automation-builder-next')).not.toBeDisabled();
});
it('a11y: builder fields expose stable form metadata', () => {
render(<AutomationBuilder onSubmit={vi.fn()} onCancel={vi.fn()} />);
expect(screen.getByLabelText('Automation name')).toHaveAttribute('name', 'automationName');
expect(screen.getByLabelText('Automation name')).toHaveAttribute('autocomplete', 'off');
expect(screen.getByLabelText('Trigger')).toHaveAttribute('name', 'automationTrigger');
expect(screen.getByLabelText('When it runs')).toHaveAttribute('name', 'automationPreset');
expect(screen.getByLabelText('Workspace scope')).toHaveAttribute('name', 'automationWorkspace');
fireEvent.change(screen.getByLabelText('When it runs'), { target: { value: 'custom' } });
expect(screen.getByLabelText('Custom cron expression')).toHaveAttribute('name', 'automationCustomCron');
expect(screen.getByLabelText('Custom cron expression')).toHaveAttribute('autocomplete', 'off');
fireEvent.change(screen.getByLabelText('Custom cron expression'), { target: { value: '0 8 * * *' } });
fireEvent.change(screen.getByLabelText('Automation name'), { target: { value: 'Morning brief' } });
fireEvent.click(screen.getByTestId('automation-builder-next'));
expect(screen.getByLabelText('What it does')).toHaveAttribute('name', 'automationJobType');
expect(screen.getByLabelText('Where the result goes')).toHaveAttribute('name', 'automationOutputChannel');
fireEvent.change(screen.getByLabelText('What it does'), { target: { value: 'agent_task' } });
expect(screen.getByLabelText('Agent task prompt')).toHaveAttribute('name', 'automationPrompt');
expect(screen.getByLabelText('Agent task prompt')).toHaveAttribute('autocomplete', 'off');
fireEvent.change(screen.getByLabelText('Agent task prompt'), { target: { value: 'Summarise the inbox' } });
fireEvent.click(screen.getByTestId('automation-builder-next'));
expect(screen.getByLabelText(/^Condition/)).toHaveAttribute('name', 'automationCondition');
expect(screen.getByLabelText(/^Condition/)).toHaveAttribute('autocomplete', 'off');
});
it('create happy path sends the EXACT adapter payload (with workspace scope + telegram channel)', async () => {
mocks.adapter.listAutomations.mockResolvedValue([]);
mocks.adapter.createAutomation.mockResolvedValue(makeAutomation());
renderApp();
await screen.findByTestId('automation-overview-tiles');
fireEvent.click(screen.getByRole('button', { name: /New/ }));
const builder = await screen.findByTestId('automation-builder');
fireEvent.change(screen.getByLabelText('Automation name'), { target: { value: 'Nightly consolidation' } });
// Workspace picker options load async. Scope the wait to the builder: the
// Center behind the modal has its own "template workspace" select listing
// the same workspaces, so a document-wide option query is ambiguous.
await within(builder).findByRole('option', { name: 'Acme Research' });
fireEvent.change(screen.getByTestId('automation-workspace'), { target: { value: 'ws-1' } });
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Action
fireEvent.change(screen.getByTestId('automation-output-channel'), { target: { value: 'telegram' } });
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Condition
fireEvent.change(screen.getByTestId('automation-condition'), { target: { value: 'only on weekdays' } });
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Review
fireEvent.click(screen.getByTestId('automation-builder-finish'));
await waitFor(() => expect(mocks.adapter.createAutomation).toHaveBeenCalledTimes(1));
expect(mocks.adapter.createAutomation).toHaveBeenCalledWith({
name: 'Nightly consolidation',
trigger: { type: 'schedule', cron: '0 9 * * *' },
condition: 'only on weekdays',
jobType: 'memory_consolidation',
jobConfig: { outputChannel: 'telegram' },
workspaceId: 'ws-1',
enabled: true,
});
});
it('agent_task + "All workspaces" sends the "*" fan-out sentinel (store requires a workspaceId)', async () => {
// Without this mapping the create 400s: CronStore.create throws
// 'agent_task jobs require a workspace ID' (2026-06-10 live-smoke fix).
mocks.adapter.listAutomations.mockResolvedValue([]);
mocks.adapter.createAutomation.mockResolvedValue(makeAutomation());
renderApp();
await screen.findByTestId('automation-overview-tiles');
fireEvent.click(screen.getByRole('button', { name: /New/ }));
await screen.findByTestId('automation-builder');
fireEvent.change(screen.getByLabelText('Automation name'), { target: { value: 'All-ws agent task' } });
// Workspace scope left at the default "All workspaces" ('' value).
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Action
fireEvent.change(screen.getByTestId('automation-job-type'), { target: { value: 'agent_task' } });
fireEvent.change(screen.getByTestId('automation-prompt'), { target: { value: 'Summarise the day' } });
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Condition
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Review
fireEvent.click(screen.getByTestId('automation-builder-finish'));
// agent_task gates on approval before submitting.
fireEvent.click(await screen.findByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.createAutomation).toHaveBeenCalledTimes(1));
expect(mocks.adapter.createAutomation.mock.calls[0][0]).toMatchObject({
jobType: 'agent_task',
workspaceId: '*',
});
});
it('edit round-trip: reads stored jobConfig off the cron row, edits the prompt, gates on approval, PATCHes the merge', async () => {
mocks.adapter.listAutomations.mockResolvedValue([makeAutomation()]);
mocks.adapter.getCronJobs.mockResolvedValue([
{
id: '1', name: 'Nightly agent', schedule: '0 9 * * *', workspaceId: '*', enabled: true,
jobType: 'agent_task', jobConfig: { prompt: 'old prompt', outputChannel: 'telegram' },
},
]);
mocks.adapter.updateAutomation.mockResolvedValue(makeAutomation());
renderApp();
await screen.findByTestId('automation-overview-tiles');
fireEvent.click(screen.getByRole('tab', { name: 'Scheduled' }));
fireEvent.click(await screen.findByRole('button', { name: 'Edit Nightly agent' }));
await screen.findByTestId('automation-builder');
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Action
// The stored prompt round-trips into the editable field.
const promptField = await screen.findByTestId('automation-prompt');
expect(promptField).toHaveValue('old prompt');
// The job type itself is read-only in edit mode.
expect(screen.queryByTestId('automation-job-type')).not.toBeInTheDocument();
expect(screen.getByText(/can’t be changed after creation/)).toBeInTheDocument();
fireEvent.change(promptField, { target: { value: 'new prompt' } });
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Condition
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Review
fireEvent.click(screen.getByTestId('automation-builder-finish'));
// agent_task is approval-gated: the request renders action/scope/risk as text.
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent('Approval required');
expect(modal).toHaveTextContent('Risk level');
expect(modal).toHaveTextContent('Agent prompt: new prompt');
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.updateAutomation).toHaveBeenCalledTimes(1));
expect(mocks.adapter.updateAutomation).toHaveBeenCalledWith('1', {
name: 'Nightly agent',
trigger: { type: 'schedule', cron: '0 9 * * *' },
condition: '',
jobConfig: { outputChannel: 'telegram', prompt: 'new prompt' },
});
});
it('edit mode while the cron read is PENDING: shows a loading label (never the default job type) and blocks Save', async () => {
let resolveCron: (rows: unknown[]) => void = () => undefined;
mocks.adapter.getCronJobs.mockReturnValue(new Promise((res) => { resolveCron = res; }));
render(
<AutomationBuilder
initial={makeAutomation()} // stored agent_task
onSubmit={vi.fn()}
onCancel={vi.fn()}
/>,
);
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Action (trigger prefilled = valid)
// While in flight the surface must not claim the default 'Consolidate
// memory' for a stored agent_task.
expect(screen.getByText('Loading stored action…')).toBeInTheDocument();
expect(screen.queryByText('Consolidate memory')).not.toBeInTheDocument();
// The Action step is invalid while pending — Next (and therefore Finish)
// waits for loaded-or-unavailable.
expect(screen.getByTestId('automation-builder-next')).toBeDisabled();
resolveCron([{
id: '1', name: 'Nightly agent', schedule: '0 9 * * *', workspaceId: '*', enabled: true,
jobType: 'agent_task', jobConfig: { prompt: 'stored prompt' },
}]);
expect(await screen.findByTestId('automation-prompt')).toHaveValue('stored prompt');
expect(screen.getByTestId('automation-builder-next')).not.toBeDisabled();
});
it('§17.3 never fails open: editing a stored agent_task still gates on approval when the cron read FAILS', async () => {
mocks.adapter.getCronJobs.mockRejectedValue(new Error('500'));
const onSubmit = vi.fn();
render(
<AutomationBuilder
initial={makeAutomation()} // actions: ['agent_task'] — the projected job type
onSubmit={onSubmit}
onCancel={vi.fn()}
/>,
);
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Action
await screen.findByTestId('automation-builder-config-unavailable');
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Condition
fireEvent.click(screen.getByTestId('automation-builder-next')); // → Review
fireEvent.click(screen.getByTestId('automation-builder-finish'));
// The gate derives the job type from initial.actions — no silent save.
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent('Approval required');
expect(modal).toHaveTextContent('saving keeps it unchanged');
expect(onSubmit).not.toHaveBeenCalled();
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));
// Degraded path stays config-safe: the draft must not carry jobConfig.
expect(onSubmit.mock.calls[0][0]).not.toHaveProperty('jobConfig');
});
it('cancelling the approval modal does not submit', async () => {
const onSubmit = vi.fn();
render(<AutomationBuilder onSubmit={onSubmit} onCancel={vi.fn()} />);
fireEvent.change(screen.getByLabelText('Automation name'), { target: { value: 'Agent run' } });
fireEvent.click(screen.getByTestId('automation-builder-next'));
fireEvent.change(screen.getByTestId('automation-job-type'), { target: { value: 'agent_task' } });
fireEvent.change(screen.getByTestId('automation-prompt'), { target: { value: 'Do the thing' } });
fireEvent.click(screen.getByTestId('automation-builder-next'));
fireEvent.click(screen.getByTestId('automation-builder-next'));
fireEvent.click(screen.getByTestId('automation-builder-finish'));
const modal = await screen.findByTestId('approval-modal');
fireEvent.click(within(modal).getByRole('button', { name: 'Cancel' }));
await waitFor(() => expect(screen.queryByTestId('approval-modal')).not.toBeInTheDocument());
expect(onSubmit).not.toHaveBeenCalled();
});
it('a11y: mounts as a focus-trapped dialog and Escape cancels', () => {
const onCancel = vi.fn();
render(<AutomationBuilder onSubmit={vi.fn()} onCancel={onCancel} />);
const dialog = screen.getByRole('dialog', { name: 'Automation Builder' });
expect(dialog).toHaveAttribute('aria-modal', 'true');
// Focus moved inside on open (house useFocusTrap contract).
expect(dialog.contains(document.activeElement)).toBe(true);
// The active step is exposed via aria-current="step".
expect(screen.getByTestId('automation-builder-step-trigger')).toHaveAttribute('aria-current', 'step');
fireEvent.keyDown(dialog, { key: 'Escape' });
expect(onCancel).toHaveBeenCalledTimes(1);
});
});

View File

@@ -0,0 +1,277 @@
/**
* Phase 3C (S19) — Skill Builder: kebab-name gating, ordered steps editing,
* the exact create payload (C13 create-to-local), the C14 inputs/outputs
* body-markdown append (including the honest partial-failure path), the Hub
* wiring (create → refresh → editor drawer opens), and the overlay a11y
* contract.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
const mocks = vi.hoisted(() => ({
adapter: {
connect: vi.fn().mockResolvedValue(undefined),
getSkills: vi.fn(),
getStarterPacks: vi.fn(),
getMarketplacePacks: vi.fn(),
getCapabilityPacks: vi.fn(),
testSkill: vi.fn(),
installSkill: vi.fn(),
installMarketplacePack: vi.fn(),
createSkill: vi.fn(),
updateSkill: vi.fn(),
fetch: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import CapabilitiesApp from '@/components/os/apps/CapabilitiesApp';
import SkillBuilder, { appendIoSections } from '@/components/os/apps/skills/SkillBuilder';
import { ServiceProvider } from '@/providers/ServiceProvider';
const renderBuilder = (over: Partial<Parameters<typeof SkillBuilder>[0]> = {}) => {
const props = {
onCreated: vi.fn(),
onCancel: vi.fn(),
onTierError: vi.fn().mockReturnValue(false),
...over,
};
render(<SkillBuilder {...props} />);
return props;
};
const fillIdentity = (name = 'weekly-report') => {
fireEvent.change(screen.getByLabelText(/^Name/), { target: { value: name } });
fireEvent.change(screen.getByLabelText('Description'), { target: { value: 'Weekly digest' } });
};
beforeEach(() => {
vi.clearAllMocks();
mocks.adapter.connect.mockResolvedValue(undefined);
mocks.adapter.getSkills.mockResolvedValue([]);
mocks.adapter.getStarterPacks.mockResolvedValue([]);
mocks.adapter.getMarketplacePacks.mockResolvedValue([]);
mocks.adapter.getCapabilityPacks.mockResolvedValue([]);
});
afterEach(cleanup);
describe('SkillBuilder — S19', () => {
it('gates Identity on a kebab-case name + description, with an inline error', () => {
renderBuilder();
const next = screen.getByTestId('skill-builder-next');
expect(next).toBeDisabled();
fireEvent.change(screen.getByLabelText(/^Name/), { target: { value: 'My Skill!' } });
expect(screen.getByTestId('skill-builder-name-error')).toBeInTheDocument();
fireEvent.change(screen.getByLabelText('Description'), { target: { value: 'Weekly digest' } });
expect(next).toBeDisabled();
fireEvent.change(screen.getByLabelText(/^Name/), { target: { value: 'weekly-report' } });
expect(screen.queryByTestId('skill-builder-name-error')).not.toBeInTheDocument();
expect(next).not.toBeDisabled();
});
it('a11y: builder fields expose stable form metadata', () => {
renderBuilder();
expect(screen.getByLabelText(/^Name/)).toHaveAttribute('name', 'skillName');
expect(screen.getByLabelText(/^Name/)).toHaveAttribute('autocomplete', 'off');
expect(screen.getByLabelText('Description')).toHaveAttribute('name', 'skillDescription');
expect(screen.getByLabelText('Description')).toHaveAttribute('autocomplete', 'off');
expect(screen.getByLabelText('Category')).toHaveAttribute('name', 'skillCategory');
fillIdentity();
fireEvent.click(screen.getByTestId('skill-builder-next'));
expect(screen.getByLabelText('Step 1')).toHaveAttribute('name', 'skillStep');
expect(screen.getByLabelText('Step 1')).toHaveAttribute('autocomplete', 'off');
expect(screen.getByLabelText(/^Inputs/)).toHaveAttribute('name', 'skillInputs');
expect(screen.getByLabelText(/^Inputs/)).toHaveAttribute('autocomplete', 'off');
expect(screen.getByLabelText(/^Outputs/)).toHaveAttribute('name', 'skillOutputs');
expect(screen.getByLabelText(/^Outputs/)).toHaveAttribute('autocomplete', 'off');
});
it('gates Content on at least one step; reordering steps reorders the payload', async () => {
const props = renderBuilder();
fillIdentity();
fireEvent.click(screen.getByTestId('skill-builder-next')); // → Content
expect(screen.getByTestId('skill-builder-next')).toBeDisabled();
fireEvent.change(screen.getByLabelText('Step 1'), { target: { value: 'Draft the report' } });
fireEvent.click(screen.getByTestId('skill-builder-add-step'));
fireEvent.change(screen.getByLabelText('Step 2'), { target: { value: 'Gather activity' } });
// Reorder: move step 2 up so "Gather activity" runs first.
fireEvent.click(screen.getByRole('button', { name: 'Move step 2 up' }));
fireEvent.click(screen.getByTestId('skill-builder-next')); // → Scope
fireEvent.click(screen.getByTestId('skill-builder-next')); // → Review
mocks.adapter.createSkill.mockResolvedValue(undefined);
fireEvent.click(screen.getByTestId('skill-builder-finish'));
await waitFor(() => expect(props.onCreated).toHaveBeenCalledWith('weekly-report'));
expect(mocks.adapter.createSkill).toHaveBeenCalledWith({
name: 'weekly-report',
description: 'Weekly digest',
steps: ['Gather activity', 'Draft the report'],
category: 'writing',
});
// No inputs/outputs → no body rewrite round-trip.
expect(mocks.adapter.fetch).not.toHaveBeenCalled();
expect(mocks.adapter.updateSkill).not.toHaveBeenCalled();
});
it('C14: inputs/outputs append to the created body as ## Inputs / ## Outputs via updateSkill', async () => {
const props = renderBuilder();
fillIdentity();
fireEvent.click(screen.getByTestId('skill-builder-next'));
fireEvent.change(screen.getByLabelText('Step 1'), { target: { value: 'Draft the report' } });
fireEvent.change(screen.getByLabelText(/^Inputs/), { target: { value: 'topic — what to cover\naudience' } });
fireEvent.change(screen.getByLabelText(/^Outputs/), { target: { value: 'a one-page summary' } });
fireEvent.click(screen.getByTestId('skill-builder-next'));
fireEvent.click(screen.getByTestId('skill-builder-next'));
mocks.adapter.createSkill.mockResolvedValue(undefined);
mocks.adapter.fetch.mockResolvedValue({
ok: true,
json: () => Promise.resolve({ content: '---\nname: weekly-report\n---\n\n# weekly-report\n\nBody\n' }),
});
mocks.adapter.updateSkill.mockResolvedValue(undefined);
fireEvent.click(screen.getByTestId('skill-builder-finish'));
await waitFor(() => expect(props.onCreated).toHaveBeenCalledWith('weekly-report'));
expect(mocks.adapter.fetch).toHaveBeenCalledWith('/api/skills/weekly-report');
const [savedName, savedContent] = mocks.adapter.updateSkill.mock.calls[0] as [string, string];
expect(savedName).toBe('weekly-report');
expect(savedContent).toContain('## Inputs');
expect(savedContent).toContain('- topic — what to cover');
expect(savedContent).toContain('- audience');
expect(savedContent).toContain('## Outputs');
expect(savedContent).toContain('- a one-page summary');
});
it('C14 partial failure is honest: skill exists, warning renders, Done still hands the name back', async () => {
const props = renderBuilder();
fillIdentity();
fireEvent.click(screen.getByTestId('skill-builder-next'));
fireEvent.change(screen.getByLabelText('Step 1'), { target: { value: 'Draft the report' } });
fireEvent.change(screen.getByLabelText(/^Inputs/), { target: { value: 'topic' } });
fireEvent.click(screen.getByTestId('skill-builder-next'));
fireEvent.click(screen.getByTestId('skill-builder-next'));
mocks.adapter.createSkill.mockResolvedValue(undefined);
mocks.adapter.fetch.mockRejectedValue(new Error('boom'));
fireEvent.click(screen.getByTestId('skill-builder-finish'));
const warning = await screen.findByTestId('skill-builder-warning');
expect(warning).toHaveTextContent('was created, but the Inputs/Outputs sections could not be written');
expect(props.onCreated).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole('button', { name: 'Done' }));
expect(props.onCreated).toHaveBeenCalledWith('weekly-report');
});
it('post-warning the wizard is frozen: navigation is inert and Done hands back the CREATED name, not the live field', async () => {
const props = renderBuilder();
fillIdentity();
fireEvent.click(screen.getByTestId('skill-builder-next'));
fireEvent.change(screen.getByLabelText('Step 1'), { target: { value: 'Draft the report' } });
fireEvent.change(screen.getByLabelText(/^Inputs/), { target: { value: 'topic' } });
fireEvent.click(screen.getByTestId('skill-builder-next'));
fireEvent.click(screen.getByTestId('skill-builder-next'));
mocks.adapter.createSkill.mockResolvedValue(undefined);
mocks.adapter.fetch.mockRejectedValue(new Error('boom'));
fireEvent.click(screen.getByTestId('skill-builder-finish'));
await screen.findByTestId('skill-builder-warning');
// Back / step-pill navigation is frozen — the review (+ warning) stays up.
fireEvent.click(screen.getByTestId('skill-builder-back'));
fireEvent.click(screen.getByTestId('skill-builder-step-identity'));
expect(screen.getByTestId('skill-builder-warning')).toBeInTheDocument();
// Even if the name state could drift, Done returns the name the skill
// was actually created under.
fireEvent.click(screen.getByRole('button', { name: 'Done' }));
expect(props.onCreated).toHaveBeenCalledWith('weekly-report');
});
it('blocks creating over an existing skill name (silent-overwrite guard)', async () => {
mocks.adapter.getSkills.mockResolvedValue([{ id: 'code-review', name: 'code-review', installed: true }]);
renderBuilder();
fillIdentity('code-review');
const taken = await screen.findByTestId('skill-builder-name-taken');
expect(taken).toHaveTextContent('already exists');
expect(screen.getByTestId('skill-builder-next')).toBeDisabled();
// A fresh name clears the guard.
fireEvent.change(screen.getByLabelText(/^Name/), { target: { value: 'code-review-v2' } });
expect(screen.queryByTestId('skill-builder-name-taken')).not.toBeInTheDocument();
expect(screen.getByTestId('skill-builder-next')).not.toBeDisabled();
});
it('routes a 403 through onTierError instead of rendering it as a plain error', async () => {
const props = renderBuilder({ onTierError: vi.fn().mockReturnValue(true) });
fillIdentity();
fireEvent.click(screen.getByTestId('skill-builder-next'));
fireEvent.change(screen.getByLabelText('Step 1'), { target: { value: 'Draft' } });
fireEvent.click(screen.getByTestId('skill-builder-next'));
fireEvent.click(screen.getByTestId('skill-builder-next'));
mocks.adapter.createSkill.mockRejectedValue(Object.assign(new Error('tier_insufficient'), { status: 403 }));
fireEvent.click(screen.getByTestId('skill-builder-finish'));
await waitFor(() => expect(props.onTierError).toHaveBeenCalledWith(expect.any(Error), 'weekly-report'));
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
expect(props.onCreated).not.toHaveBeenCalled();
});
it('Hub wiring: Create Skill opens the builder; created skill refreshes the Hub and opens the editor drawer', async () => {
mocks.adapter.createSkill.mockResolvedValue(undefined);
// SkillEditorDrawer loads the body of the freshly created skill.
mocks.adapter.fetch.mockResolvedValue({
ok: true,
json: () => Promise.resolve({ content: '# weekly-report' }),
});
render(
<ServiceProvider><TooltipProvider><CapabilitiesApp /></TooltipProvider></ServiceProvider>,
);
fireEvent.click(await screen.findByTestId('skills-hub-create'));
await screen.findByTestId('skill-builder');
fillIdentity();
fireEvent.click(screen.getByTestId('skill-builder-next'));
fireEvent.change(screen.getByLabelText('Step 1'), { target: { value: 'Draft the report' } });
fireEvent.click(screen.getByTestId('skill-builder-next'));
fireEvent.click(screen.getByTestId('skill-builder-next'));
fireEvent.click(screen.getByTestId('skill-builder-finish'));
// Builder closes, catalogs reload, the editor drawer opens on the new skill.
await waitFor(() => expect(screen.queryByTestId('skill-builder')).not.toBeInTheDocument());
expect(mocks.adapter.getSkills.mock.calls.length).toBeGreaterThanOrEqual(2);
const editor = await screen.findByLabelText('Skill markdown content');
expect(editor).toHaveAttribute('name', 'skillMarkdownContent');
expect(editor).toHaveAttribute('autocomplete', 'off');
expect(editor).toHaveAttribute('spellcheck', 'false');
});
it('a11y: mounts as a focus-trapped dialog with aria-current step, Escape cancels', () => {
const props = renderBuilder();
const dialog = screen.getByRole('dialog', { name: 'Skill Builder' });
expect(dialog).toHaveAttribute('aria-modal', 'true');
expect(dialog.contains(document.activeElement)).toBe(true);
expect(screen.getByTestId('skill-builder-step-identity')).toHaveAttribute('aria-current', 'step');
fireEvent.keyDown(dialog, { key: 'Escape' });
expect(props.onCancel).toHaveBeenCalledTimes(1);
});
});
describe('appendIoSections (C14)', () => {
it('appends only the declared sections and preserves the body', () => {
const out = appendIoSections('# skill\n\nBody\n', ['a', 'b'], []);
expect(out).toContain('# skill');
expect(out).toContain('## Inputs\n\n- a\n- b');
expect(out).not.toContain('## Outputs');
});
});

View File

@@ -0,0 +1,237 @@
/**
* Phase 4B (S07) — Connector Hub behaviour over a mocked adapter:
* shared-type rendering (§8a categories + lastSyncAt), tab filtering,
* the C16 sync-now honest health-probe flow, the C17 revoke confirm with the
* shared-Google-pair consequence + result rendering, and the C18 per-connector
* audit history drawer.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
const mocks = vi.hoisted(() => ({
adapter: {
connect: vi.fn().mockResolvedValue(undefined),
getConnectors: vi.fn(),
getConnectorHealth: vi.fn(),
addVaultSecret: vi.fn(),
connectConnector: vi.fn(),
disconnectConnector: vi.fn(),
syncConnector: vi.fn(),
revokeConnector: vi.fn(),
getExtendAudit: vi.fn(),
fetch: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import ConnectorsApp, { buildRevokeRequest, resetConnectorsRouteCache, shouldResetCredentialInputs } from '@/components/os/apps/ConnectorsApp';
import { ServiceProvider } from '@/providers/ServiceProvider';
const CONNECTORS = [
{
id: 'github', name: 'GitHub', description: 'Code hosting', service: 'github',
authType: 'bearer', status: 'connected', capabilities: ['read', 'write'],
substrate: 'waggle', tools: [], category: 'development',
lastSyncAt: '2026-06-01T10:00:00.000Z',
},
{
id: 'gmail', name: 'Gmail', description: 'Email', service: 'google',
authType: 'oauth2', status: 'connected', capabilities: ['read'],
substrate: 'waggle', tools: [], category: 'communication',
},
{
id: 'slack', name: 'Slack', description: 'Team chat', service: 'slack',
authType: 'bearer', status: 'disconnected', capabilities: ['read'],
substrate: 'waggle', tools: [], category: 'communication',
},
];
const JIRA_CONNECTOR = {
id: 'jira', name: 'Jira', description: 'Project tracking', service: 'jira',
authType: 'bearer', status: 'disconnected', capabilities: ['read', 'write'],
substrate: 'waggle', tools: [], category: 'productivity',
};
const renderApp = () => render(
<ServiceProvider><TooltipProvider><ConnectorsApp /></TooltipProvider></ServiceProvider>,
);
beforeEach(() => {
vi.clearAllMocks();
resetConnectorsRouteCache();
mocks.adapter.connect.mockResolvedValue(undefined);
mocks.adapter.getConnectors.mockResolvedValue(CONNECTORS);
mocks.adapter.getConnectorHealth.mockResolvedValue({
id: 'github', name: 'GitHub', status: 'connected', lastChecked: '2026-06-01T10:00:00.000Z',
});
mocks.adapter.getExtendAudit.mockResolvedValue([]);
});
afterEach(cleanup);
describe('ConnectorsApp — Connector Hub (S07)', () => {
it('repaints the last roster on return and refreshes silently', async () => {
const first = renderApp();
expect(await screen.findByText('GitHub')).toBeInTheDocument();
const baseline = mocks.adapter.getConnectors.mock.calls.length;
first.unmount();
renderApp();
expect(screen.getByText('GitHub')).toBeInTheDocument();
expect(screen.queryByRole('status')).not.toBeInTheDocument();
await waitFor(() => expect(mocks.adapter.getConnectors.mock.calls.length).toBeGreaterThan(baseline));
});
it('renders connectors grouped by the shared category with status badges + lastSyncAt', async () => {
renderApp();
expect(await screen.findByText('GitHub')).toBeInTheDocument();
// §8a: shared category labels, not the old hardcoded id map.
expect(screen.getByText('Code & DevOps')).toBeInTheDocument();
expect(screen.getByText('Communication')).toBeInTheDocument();
// §14.7 text labels — never colour alone.
expect(screen.getAllByText('Connected').length).toBeGreaterThanOrEqual(2);
expect(screen.getByText('Not connected')).toBeInTheDocument();
// C16 stamp surfaces on the row.
expect(screen.getByText(/Last sync/)).toBeInTheDocument();
});
it('scopes connector row and brand tile transitions to explicit properties', async () => {
renderApp();
const githubLabel = await screen.findByText('GitHub');
const rowButton = githubLabel.closest('button');
expect(rowButton).not.toBeNull();
const row = rowButton?.parentElement;
expect(row?.className).not.toContain('transition-all');
expect(row?.className).toContain('transition-colors');
const brandTile = rowButton?.querySelector('div[aria-hidden="true"]');
expect(brandTile?.className).not.toContain('transition-all');
expect(brandTile?.className).toContain('transition-shadow');
});
it('the Connected tab filters out disconnected connectors', async () => {
renderApp();
await screen.findByText('GitHub');
fireEvent.click(screen.getByRole('tab', { name: /Connected/ }));
expect(screen.getByText('GitHub')).toBeInTheDocument();
expect(screen.queryByText('Slack')).not.toBeInTheDocument();
});
it('Sync now runs the C16 health probe and renders the honest no-data-pull copy', async () => {
mocks.adapter.syncConnector.mockResolvedValue({
ok: true, connectorId: 'github', lastSyncAt: '2026-06-02T12:00:00.000Z', status: 'connected',
});
renderApp();
fireEvent.click(await screen.findByText('GitHub'));
fireEvent.click(await screen.findByRole('button', { name: /Sync now/ }));
await waitFor(() => expect(mocks.adapter.syncConnector).toHaveBeenCalledWith('github'));
expect(await screen.findByText(/it does not re-pull data/)).toBeInTheDocument();
});
it('a failed sync says so and does not claim a stamp', async () => {
mocks.adapter.syncConnector.mockResolvedValue({ ok: false, connectorId: 'github', status: 'error' });
renderApp();
fireEvent.click(await screen.findByText('GitHub'));
fireEvent.click(await screen.findByRole('button', { name: /Sync now/ }));
expect(await screen.findByText(/Sync failed — health status: error/)).toBeInTheDocument();
expect(screen.getByText(/No last-sync stamp written/)).toBeInTheDocument();
});
it('Revoke on a Google-family connector confirms with the shared-pair warning and renders the purge result', async () => {
mocks.adapter.revokeConnector.mockResolvedValue({
ok: true, connectorId: 'gmail', revoked: true, cleanedKeys: 2, oauthPurged: 2,
});
renderApp();
fireEvent.click(await screen.findByText('Gmail'));
fireEvent.click(await screen.findByRole('button', { name: /Revoke/ }));
// Scope-and-consequence confirm (C17) incl. the Google blast radius.
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent('Revoke all access for Gmail?');
expect(modal).toHaveTextContent(/SHARED Google OAuth token pair/);
expect(modal).toHaveTextContent(/audit trail/);
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.revokeConnector).toHaveBeenCalledWith('gmail'));
const notice = await screen.findByTestId('revoke-notice');
expect(notice).toHaveTextContent('2 credential key(s) removed');
expect(notice).toHaveTextContent('2 OAuth token(s) purged');
});
it('a failed revoke (404/503 error body as data) renders the error — never a fabricated success', async () => {
// adapter.fetch does not throw on HTTP errors: the 503 vault-down body
// resolves as data with no ok/cleanedKeys fields.
mocks.adapter.revokeConnector.mockResolvedValue({ error: 'Vault not available' });
renderApp();
fireEvent.click(await screen.findByText('Gmail'));
fireEvent.click(await screen.findByRole('button', { name: /Revoke/ }));
await screen.findByTestId('approval-modal');
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.revokeConnector).toHaveBeenCalledWith('gmail'));
const notice = await screen.findByTestId('revoke-notice');
expect(notice).toHaveTextContent('Vault not available');
expect(notice).not.toHaveTextContent(/Access revoked/);
});
it('the History drawer reads the C18 shared audit feed scoped to the connector', async () => {
renderApp();
fireEvent.click(await screen.findByText('GitHub'));
fireEvent.click(await screen.findByRole('button', { name: /History/ }));
await waitFor(() => expect(mocks.adapter.getExtendAudit).toHaveBeenCalledWith({
type: 'connector', capability: 'github', limit: 10,
}));
});
it('the Activity tab renders the connector-typed shared audit feed', async () => {
mocks.adapter.getExtendAudit.mockResolvedValue([{
id: 1, timestamp: '2026-06-01T10:00:00.000Z', capabilityName: 'github',
capabilityType: 'connector', source: 'native', riskLevel: 'low',
trustSource: 'local_user', approvalClass: 'standard', action: 'installed',
initiator: 'user', detail: 'Connector connected',
}]);
renderApp();
await screen.findByText('GitHub');
fireEvent.click(screen.getByRole('tab', { name: 'Activity' }));
await waitFor(() => expect(mocks.adapter.getExtendAudit).toHaveBeenCalledWith({ type: 'connector', limit: 25 }));
expect(await screen.findByText('Connector connected')).toBeInTheDocument();
});
it('a11y: Jira setup fields expose stable credential metadata', async () => {
mocks.adapter.getConnectors.mockResolvedValue([...CONNECTORS, JIRA_CONNECTOR]);
renderApp();
fireEvent.click(await screen.findByText('Jira'));
const email = await screen.findByRole('textbox', { name: /atlassian account email/i });
expect(email).toHaveAttribute('type', 'email');
expect(email).toHaveAttribute('name', 'connectorEmail');
expect(email).toHaveAttribute('autocomplete', 'email');
expect(email).toHaveAttribute('spellcheck', 'false');
expect(email.className).toContain('focus-visible:ring-2');
const token = screen.getByLabelText(/jira api token/i);
expect(token).toHaveAttribute('type', 'password');
expect(token).toHaveAttribute('name', 'connectorToken');
expect(token).toHaveAttribute('autocomplete', 'off');
expect(token).toHaveAttribute('spellcheck', 'false');
expect(token.className).toContain('focus-visible:ring-2');
expect(screen.getByRole('button', { name: /^connect$/i }).className).toContain('focus-visible:ring-2');
});
});
describe('pure helpers', () => {
it('shouldResetCredentialInputs is preserved (R4-007)', () => {
expect(shouldResetCredentialInputs('github', 'slack')).toBe(true);
expect(shouldResetCredentialInputs('github', 'github')).toBe(false);
});
it('buildRevokeRequest warns about the Google pair only for the Google family', () => {
const gmail = buildRevokeRequest({ id: 'gmail', name: 'Gmail' });
expect(gmail.scope.join(' ')).toMatch(/SHARED Google OAuth token pair/);
const github = buildRevokeRequest({ id: 'github', name: 'GitHub' });
expect(github.scope.join(' ')).not.toMatch(/Google/);
});
});

View File

@@ -0,0 +1,334 @@
/**
* PR4 Variation A (screen 09) — the Warm-Hive Marketplace surface. Supersedes
* the Phase-4B contract: four shelves (D2: All/Skills/Connectors/MCP),
* type-aware ONE-CLICK install via the shared store (D3 — Add/Connect/Enable,
* no pre-emptive ApprovalModal), the in-place connector token-paste (OAuth →
* Hub), the store-derived install count (D1), and the destructive Remove that
* KEEPS its consequence dialog. Security regressions (tier vs SecurityGate) are
* pinned in pr4-install-store; this file pins the surface wiring.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, waitFor, within } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
const mocks = vi.hoisted(() => ({
adapter: {
connect: vi.fn().mockResolvedValue(undefined),
forceReconnect: vi.fn().mockResolvedValue(undefined),
getMarketplace: vi.fn(),
getMarketplacePacks: vi.fn(),
getMcps: vi.fn(),
getConnectors: vi.fn(),
installMarketplacePackage: vi.fn(),
uninstallMarketplacePackage: vi.fn(),
connectConnector: vi.fn().mockResolvedValue(undefined),
disconnectConnector: vi.fn().mockResolvedValue(undefined),
installMcp: vi.fn(),
revokeMcp: vi.fn().mockResolvedValue({ ok: true }),
getExtendAudit: vi.fn(),
agentSearch: vi.fn(),
installPack: vi.fn().mockResolvedValue(undefined),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import type { AgentSearchResponse } from '@/lib/agent-search';
import MarketplaceApp, { resetMarketplaceRouteCache } from '@/components/os/apps/MarketplaceApp';
import { ServiceProvider } from '@/providers/ServiceProvider';
import { InstallProvider } from '@/providers/InstallProvider';
const renderApp = () => render(
<ServiceProvider><InstallProvider><TooltipProvider><MarketplaceApp /></TooltipProvider></InstallProvider></ServiceProvider>,
);
const skillRows = (installed = false) => ([
{ id: 7, name: 'web-scraper', description: 'Scrape pages', waggle_install_type: 'skill', installed, scanStatus: 'passed', source: 'registry' },
]);
// Semantic-match fixtures for the NL auto-run (Wave U Lane C). MATCH resolves a
// skill pick; NO_MATCH resolves empty picks so the catalog fallback shows.
const MATCH: AgentSearchResponse = {
need: 'send a slide deck to my whole team', gapDetected: true, alreadyHandled: false,
recommendation: null, candidates: [],
picks: {
skill: { name: 'deck-builder', type: 'marketplace', availability: 'installable', description: 'Turn work into slides', matchReason: 'matches: slide, deck', matchScore: 0.8, install: { mode: 'store', extensionId: 'pkg:42', type: 'skill', kind: 'package', packageId: 42 } },
},
};
const NO_MATCH: AgentSearchResponse = {
need: 'send a slide deck to my whole team', gapDetected: true, alreadyHandled: false,
recommendation: null, candidates: [], picks: {},
};
beforeEach(() => {
vi.clearAllMocks();
resetMarketplaceRouteCache(); // Pillar 2.6: reset the module-level route cache between tests
mocks.adapter.connect.mockResolvedValue(undefined);
mocks.adapter.forceReconnect.mockResolvedValue(undefined);
mocks.adapter.getMarketplace.mockImplementation(async (params?: { type?: string }) => (
params?.type === 'mcp'
? { packages: [{ id: 9, name: 'pg-mcp-pkg', description: 'Registry MCP server', waggle_install_type: 'mcp', installed: false, scanStatus: 'passed', source: 'registry' }], total: 1 }
: { packages: skillRows(), total: 1 }
));
mocks.adapter.getMarketplacePacks.mockResolvedValue([
{ 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' },
]);
mocks.adapter.getMcps.mockResolvedValue([
{ id: 'postgres', name: 'PostgreSQL', description: 'Query databases', category: 'Database', installed: false },
]);
mocks.adapter.getConnectors.mockResolvedValue([
{ id: 'github', name: 'GitHub', description: 'Code hosting', service: 'github', authType: 'bearer', status: 'connected', capabilities: [], substrate: 'waggle', tools: [], category: 'development' },
]);
mocks.adapter.installMarketplacePackage.mockResolvedValue(new Response('{}', { status: 200 }));
mocks.adapter.uninstallMarketplacePackage.mockResolvedValue(new Response('{}', { status: 200 }));
mocks.adapter.installMcp.mockResolvedValue({ installed: true });
mocks.adapter.getExtendAudit.mockResolvedValue([]);
mocks.adapter.agentSearch.mockResolvedValue(MATCH);
});
afterEach(cleanup);
describe('MarketplaceApp — Warm-Hive Marketplace (PR4 Variation A)', () => {
it('the All shelf federates skills + connectors + MCP (and only those three)', async () => {
renderApp();
expect(await screen.findByText('Web Scraper')).toBeInTheDocument();
// Browse-only pack: display_name renders, no install affordance (A4).
expect(screen.getByText('Research Pack')).toBeInTheDocument();
expect(screen.queryByTestId('extension-install-pack:research-pack')).not.toBeInTheDocument();
expect(screen.getByText('PostgreSQL')).toBeInTheDocument();
// Wave X Lane D: displayExtensionName now uppercases known acronyms, so the
// slug "pg-mcp-pkg" humanizes to "Pg MCP Pkg" (was "Pg Mcp Pkg").
expect(screen.getByText('Pg MCP Pkg')).toBeInTheDocument();
expect(screen.getByText('GitHub')).toBeInTheDocument();
// Agents/models/templates are NOT in the marketplace shelf (D2).
expect(screen.queryByText('Researcher')).not.toBeInTheDocument();
expect(mocks.adapter.getMarketplace).toHaveBeenCalledWith({ type: 'skill', limit: 30 });
expect(mocks.adapter.getMarketplace).toHaveBeenCalledWith({ type: 'mcp', limit: 30 });
});
it('exposes exactly the four shelves (D2)', async () => {
renderApp();
await screen.findByText('Web Scraper');
const rail = screen.getByTestId('extension-facets');
expect(rail).toHaveTextContent('All');
expect(rail).toHaveTextContent('Skills');
expect(rail).toHaveTextContent('Connectors');
expect(rail).toHaveTextContent('MCPs');
expect(rail).not.toHaveTextContent('Agents');
expect(rail).not.toHaveTextContent('Models');
expect(rail).not.toHaveTextContent('Templates');
const allFacet = within(rail).getByRole('button', { name: /^All$/i });
expect(allFacet.className).not.toContain('transition-all');
expect(allFacet.className).toContain('transition-[background-color,color,box-shadow]');
});
it('the install count bar reflects the store (a connected connector counts) (D1)', async () => {
renderApp();
// GitHub is connected in the mock → the store hydrates it → count = 1.
await waitFor(() => expect(screen.getByTestId('install-count')).toHaveTextContent('1 installed'));
});
it('Add installs a package one-click through the store — no ApprovalModal', async () => {
renderApp();
await screen.findByText('Web Scraper');
fireEvent.click(screen.getByTestId('extension-install-pkg:7'));
await waitFor(() => expect(mocks.adapter.installMarketplacePackage).toHaveBeenCalledWith(7));
// One-click: the pre-emptive consequence dialog is gone for installs.
expect(screen.queryByTestId('approval-modal')).not.toBeInTheDocument();
// Reflected: the count bar ticks up (GitHub + web-scraper).
await waitFor(() => expect(screen.getByTestId('install-count')).toHaveTextContent('2 installed'));
});
it('a blocked install (SecurityGate 403) leaves the item installable — not silently added', async () => {
mocks.adapter.installMarketplacePackage.mockResolvedValue(
new Response(JSON.stringify({ blocked: true, severity: 'CRITICAL', message: 'Blocked' }), { status: 403 }));
renderApp();
await screen.findByText('Web Scraper');
fireEvent.click(screen.getByTestId('extension-install-pkg:7'));
await waitFor(() => expect(mocks.adapter.installMarketplacePackage).toHaveBeenCalledWith(7));
// Still offers Add — a gate-rejected item never enters the installed count.
expect(await screen.findByTestId('extension-install-pkg:7')).toBeInTheDocument();
expect(screen.getByTestId('install-count')).toHaveTextContent('1 installed');
});
it('a disconnected connector offers Connect → token-paste → connectConnector (D3 in-place)', async () => {
mocks.adapter.getConnectors.mockResolvedValue([
{ id: 'slack', name: 'Slack', description: 'Chat', service: 'slack', authType: 'bearer', status: 'disconnected', capabilities: [], substrate: 'waggle', tools: [], category: 'comms' },
]);
renderApp();
await screen.findByText('Web Scraper');
fireEvent.click(screen.getByRole('button', { name: 'Connectors' }));
fireEvent.click(await screen.findByTestId('extension-install-connector:slack'));
const input = await screen.findByLabelText(/slack api token/i);
expect(input).toHaveAttribute('type', 'password');
expect(input).toHaveAttribute('name', 'marketplaceConnectorToken');
expect(input).toHaveAttribute('autocomplete', 'off');
expect(input).toHaveAttribute('spellcheck', 'false');
expect(input).toHaveClass('focus-visible:ring-ring');
fireEvent.change(input, { target: { value: 'xoxb-123' } });
fireEvent.click(screen.getByTestId('connector-token-submit'));
await waitFor(() => expect(mocks.adapter.connectConnector).toHaveBeenCalledWith('slack', { token: 'xoxb-123' }));
});
it('an OAuth connector routes Connect to the Hub (no inline token field)', async () => {
mocks.adapter.getConnectors.mockResolvedValue([
{ id: 'gcal', name: 'Google Calendar', description: 'Cal', service: 'google', authType: 'oauth2', status: 'disconnected', capabilities: [], substrate: 'waggle', tools: [], category: 'productivity' },
]);
const events: CustomEvent[] = [];
const listener = (e: Event) => events.push(e as CustomEvent);
window.addEventListener('waggle:open-app', listener);
try {
renderApp();
await screen.findByText('Web Scraper');
fireEvent.click(screen.getByRole('button', { name: 'Connectors' }));
fireEvent.click(await screen.findByTestId('extension-install-connector:gcal'));
await waitFor(() => expect(events.some(e => e.detail.appId === 'connectors')).toBe(true));
expect(screen.queryByTestId('connector-token-input')).not.toBeInTheDocument();
expect(mocks.adapter.connectConnector).not.toHaveBeenCalled();
} finally {
window.removeEventListener('waggle:open-app', listener);
}
});
it('the connector shelf shows the honest in-place note', async () => {
renderApp();
await screen.findByText('Web Scraper');
fireEvent.click(screen.getByRole('button', { name: 'Connectors' }));
expect(await screen.findByTestId('federated-note')).toHaveTextContent(/vault/i);
});
it('all backends down renders the error + Retry state, never a healthy-looking empty catalog', async () => {
const down = new Error('ECONNREFUSED');
mocks.adapter.getMarketplace.mockRejectedValue(down);
mocks.adapter.getMarketplacePacks.mockRejectedValue(down);
mocks.adapter.getMcps.mockRejectedValue(down);
mocks.adapter.getConnectors.mockRejectedValue(down);
renderApp();
expect(await screen.findByText(/Could not load extensions/)).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();
expect(screen.queryByText(/No extensions available/)).not.toBeInTheDocument();
});
it('Remove confirms through the ApprovalModal before uninstalling (no one-click destroy)', async () => {
mocks.adapter.getMarketplace.mockImplementation(async (params?: { type?: string }) => (
params?.type === 'mcp' ? { packages: [], total: 0 } : { packages: skillRows(true), total: 1 }
));
renderApp();
await screen.findByText('Web Scraper');
fireEvent.click(await screen.findByRole('button', { name: /Remove/ }));
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent('Remove "web-scraper"?');
expect(modal).toHaveTextContent(/audit trail/);
expect(mocks.adapter.uninstallMarketplacePackage).not.toHaveBeenCalled();
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.uninstallMarketplacePackage).toHaveBeenCalledWith(7));
});
it('a FAILED uninstall keeps the item installed (the store does not flip on error)', async () => {
mocks.adapter.getMarketplace.mockImplementation(async (params?: { type?: string }) => (
params?.type === 'mcp' ? { packages: [], total: 0 } : { packages: skillRows(true), total: 1 }
));
mocks.adapter.uninstallMarketplacePackage.mockRejectedValue(
Object.assign(new Error('boom'), { name: 'AdapterHttpError', status: 500 }),
);
renderApp();
await screen.findByText('Web Scraper');
fireEvent.click(await screen.findByRole('button', { name: /Remove/ }));
fireEvent.click(await screen.findByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.uninstallMarketplacePackage).toHaveBeenCalledWith(7));
// Still installed: the Remove affordance survives the failed uninstall.
expect(await screen.findByRole('button', { name: /Remove/ })).toBeInTheDocument();
});
it('the Start-here band surfaces curated matches on the All shelf only — no duplicate rows', async () => {
renderApp();
await screen.findByText('Web Scraper');
// GitHub (connector) + PostgreSQL (mcp) match the curated list → band shows.
const band = screen.getByTestId('start-here-band');
expect(within(band).getByText('GitHub')).toBeInTheDocument();
expect(within(band).getByText('PostgreSQL')).toBeInTheDocument();
// Banded entries are lifted OUT of the grid — exactly one row each.
expect(screen.getAllByText('GitHub')).toHaveLength(1);
expect(screen.getAllByText('PostgreSQL')).toHaveLength(1);
// Uncurated entries stay in the grid, not the band.
expect(within(band).queryByText('Web Scraper')).not.toBeInTheDocument();
// Off the All facet the band disappears.
fireEvent.click(screen.getByRole('button', { name: 'Skills' }));
await waitFor(() => expect(screen.queryByTestId('start-here-band')).not.toBeInTheDocument());
});
it('the Start-here band stays hidden under 2 curated matches (never fabricated)', async () => {
mocks.adapter.getConnectors.mockResolvedValue([]); // drop GitHub → only PostgreSQL matches
renderApp();
await screen.findByText('Web Scraper');
expect(screen.queryByTestId('start-here-band')).not.toBeInTheDocument();
expect(screen.getByText('PostgreSQL')).toBeInTheDocument(); // still in the grid
});
it('an NL query with no keyword match AUTO-RUNS the semantic match — no dead-end (Wave U Lane C §1)', async () => {
renderApp();
await screen.findByText('Web Scraper');
// ≥3-word described need that no loaded row matches by name/description.
fireEvent.change(screen.getByLabelText('Ask Waggle'), {
target: { value: 'send a slide deck to my whole team' },
});
// The bridge runs itself — no "press Enter" hint — and renders the ranked
// result under the "Matched to your request" label.
await waitFor(
() => expect(mocks.adapter.agentSearch).toHaveBeenCalledWith('send a slide deck to my whole team'),
{ timeout: 3000 },
);
expect(await screen.findByTestId('nl-matched-label')).toBeInTheDocument();
expect(screen.getByTestId('agent-search-pick-skill')).toHaveTextContent('deck-builder');
// The old "press Enter" dead-end hint is gone.
expect(screen.queryByTestId('nl-search-bridge')).not.toBeInTheDocument();
});
it('when the semantic match ALSO finds nothing, shows closest catalog entries + a real escape (Lane C §2)', async () => {
mocks.adapter.agentSearch.mockResolvedValue(NO_MATCH);
renderApp();
await screen.findByText('Web Scraper');
fireEvent.change(screen.getByLabelText('Ask Waggle'), {
target: { value: 'reconcile invoices against the ledger nightly' },
});
const fallback = await screen.findByTestId('nl-no-match-fallback', {}, { timeout: 3000 });
// A real escape button (not a text link), and no gray "no match by name" lead.
expect(within(fallback).getByTestId('nl-ask-agent').tagName).toBe('BUTTON');
expect(screen.queryByTestId('nl-search-bridge')).not.toBeInTheDocument();
expect(screen.queryByText(/by name/i)).not.toBeInTheDocument();
});
it('a 1-2 word miss keeps the plain "No results" copy and never auto-runs (Lane C §3)', async () => {
renderApp();
await screen.findByText('Web Scraper');
fireEvent.change(screen.getByLabelText('Ask Waggle'), { target: { value: 'zzzznope' } });
expect(await screen.findByText('No results for "zzzznope"')).toBeInTheDocument();
expect(screen.queryByTestId('nl-no-match-fallback')).not.toBeInTheDocument();
// Below the NL threshold — the semantic engine is never invoked.
await waitFor(() => expect(mocks.adapter.agentSearch).not.toHaveBeenCalled(), { timeout: 1200 });
});
it('the Audit tab reads the C18 shared feed and the type filter re-queries', async () => {
mocks.adapter.getExtendAudit.mockResolvedValue([{
id: 3, timestamp: '2026-06-01T09:00:00.000Z', capabilityName: 'web-scraper',
capabilityType: 'marketplace', source: 'marketplace', riskLevel: 'medium',
trustSource: 'third_party_verified', approvalClass: 'standard', action: 'installed',
initiator: 'user', detail: 'Installed from registry',
}]);
renderApp();
await screen.findByText('Web Scraper');
fireEvent.click(screen.getByRole('tab', { name: 'Audit' }));
await waitFor(() => expect(mocks.adapter.getExtendAudit).toHaveBeenCalledWith({ limit: 30 }));
expect(await screen.findByText('Installed from registry')).toBeInTheDocument();
const typeFilter = screen.getByRole('combobox', { name: 'Type' });
expect(typeFilter).toHaveAttribute('name', 'extendAuditTypeFilter');
expect(typeFilter).toHaveAttribute('autocomplete', 'off');
expect(typeFilter).toHaveClass('focus-visible:ring-ring');
fireEvent.change(typeFilter, { target: { value: 'mcp' } });
await waitFor(() => expect(mocks.adapter.getExtendAudit).toHaveBeenCalledWith({ type: 'mcp', limit: 30 }));
});
});

View File

@@ -0,0 +1,385 @@
/**
* Phase 4B (S08) — MCP Hub behaviour over a mocked adapter: installed
* instance rendering (state badge + C19 scope chip + honest logs-coming-soon),
* the C21 test-mode label, the B5 install tier gate (TIER_INSUFFICIENT →
* upgrade event), the SecurityGate blocked → ApprovalModal → forceInsecure-
* override flow, the C19 scope-editor exact payloads, and revoke with
* consequences.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
const mocks = vi.hoisted(() => ({
adapter: {
connect: vi.fn().mockResolvedValue(undefined),
getMcps: vi.fn(),
getMarketplace: vi.fn(),
installMcp: vi.fn(),
addCustomMcp: vi.fn(),
testMcp: vi.fn(),
startMcp: vi.fn(),
stopMcp: vi.fn(),
revokeMcp: vi.fn(),
updateMcpPermissions: vi.fn(),
getWorkspaces: vi.fn(),
getExtendAudit: vi.fn(),
fetch: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
// The real MCP_CATALOG is 100+ entries — rendering the full Radix-tooltip grid
// in jsdom is slow enough to time out under parallel suite load. The hub's
// behaviour under test only needs a small honest catalog.
vi.mock('@/components/os/apps/connectors/mcp-registry', () => ({
MCP_CATALOG: [
{
id: 'filesystem', name: 'Filesystem', description: 'Read/write files', author: 'MCP',
category: 'Files', url: 'https://example.com/fs', installCmd: 'npx @modelcontextprotocol/server-filesystem /path',
capabilities: ['read', 'write'], official: true,
},
{
id: 'postgres', name: 'PostgreSQL', description: 'Query databases', author: 'MCP',
category: 'Database', url: 'https://example.com/pg', installCmd: 'npx @modelcontextprotocol/server-postgres',
capabilities: ['query'], official: true,
},
],
}));
import MCPHubApp, { resetMcpRouteCache } from '@/components/os/apps/MCPHubApp';
import { mcpStateBadge } from '@/components/os/apps/mcp/mcp-hub-types';
import { ServiceProvider } from '@/providers/ServiceProvider';
const MCPS = [
{
id: 'filesystem', name: 'Filesystem', description: 'Read/write files', category: 'Files',
official: true, installCmd: 'npx @modelcontextprotocol/server-filesystem /path',
source: 'catalog', installed: true, tools: ['read_file', 'write_file'],
status: 'running', scope: 'workspace', connectedTo: ['ws-1'], state: 'ready',
},
{
id: 'postgres', name: 'PostgreSQL', description: 'Query databases', category: 'Database',
official: true, installCmd: 'npx @modelcontextprotocol/server-postgres',
source: 'catalog', installed: false, tools: [],
},
];
const renderApp = () => render(
<ServiceProvider><TooltipProvider><MCPHubApp /></TooltipProvider></ServiceProvider>,
);
beforeEach(() => {
vi.clearAllMocks();
resetMcpRouteCache();
mocks.adapter.connect.mockResolvedValue(undefined);
mocks.adapter.getMcps.mockResolvedValue(MCPS);
// The A4 install-affordance gate: only catalog ids whose name resolves in
// the marketplace registry (waggle_install_type='mcp') render Install.
mocks.adapter.getMarketplace.mockResolvedValue({
packages: [{ name: 'filesystem' }, { name: 'postgres' }], total: 2,
});
mocks.adapter.getWorkspaces.mockResolvedValue([
{ id: 'ws-1', name: 'Workspace One' },
{ id: 'ws-2', name: 'Workspace Two' },
]);
mocks.adapter.getExtendAudit.mockResolvedValue([]);
});
afterEach(cleanup);
describe('MCPHubApp — MCP Hub (S08)', () => {
it('repaints installed MCP state on return and refreshes silently', async () => {
const first = renderApp();
expect(await screen.findByText('Filesystem')).toBeInTheDocument();
const baseline = mocks.adapter.getMcps.mock.calls.length;
first.unmount();
renderApp();
expect(screen.getByText('Filesystem')).toBeInTheDocument();
expect(screen.queryByText(/Loading MCP/i)).not.toBeInTheDocument();
await waitFor(() => expect(mocks.adapter.getMcps.mock.calls.length).toBeGreaterThan(baseline));
});
it('renders installed instances with the runtime state badge, scope chip and honest logs affordance', async () => {
renderApp();
expect(await screen.findByText('Filesystem')).toBeInTheDocument();
expect(screen.getByText('Ready')).toBeInTheDocument();
expect(screen.getByText('workspace: ws-1')).toBeInTheDocument();
expect(screen.getByText('read_file')).toBeInTheDocument();
// C2: no logs route exists — the affordance must be an honest coming-soon.
// aria-disabled (not `disabled`) so the explanatory tooltip is reachable
// by hover/focus (Radix never fires on a hard-disabled trigger).
expect(screen.getByRole('button', { name: /Logs \(soon\)/ })).toHaveAttribute('aria-disabled', 'true');
// The not-installed catalog entry must NOT appear as an instance.
expect(screen.queryByText('PostgreSQL')).not.toBeInTheDocument();
});
it('C21: the test result is labelled with the mode that actually ran', async () => {
mocks.adapter.testMcp.mockResolvedValue({
ok: true, mode: 'static', tools: [],
note: 'Not installed — static manifest validation only (C21 fallback)',
});
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('button', { name: /Test/ }));
await waitFor(() => expect(mocks.adapter.testMcp).toHaveBeenCalledWith('filesystem'));
const result = await screen.findByTestId('mcp-test-result-filesystem');
expect(result).toHaveTextContent('Static manifest check: passed');
expect(result).toHaveTextContent('C21 fallback');
});
// Headroom for parallel-suite load on the catalog-tab tests.
const CATALOG_TIMEOUT = 20_000;
it('B5: a TIER_INSUFFICIENT install routes through the upgrade event', { timeout: CATALOG_TIMEOUT }, async () => {
mocks.adapter.installMcp.mockResolvedValue({ error: 'TIER_INSUFFICIENT', required: 'TEAMS', actual: 'FREE' });
const events: CustomEvent[] = [];
const listener = (e: Event) => events.push(e as CustomEvent);
window.addEventListener('waggle:tier-insufficient', listener);
try {
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('tab', { name: 'Catalog' }));
fireEvent.click(await screen.findByTestId('mcp-install-postgres'));
await waitFor(() => expect(mocks.adapter.installMcp).toHaveBeenCalledWith('postgres', undefined));
await waitFor(() => expect(events.length).toBeGreaterThan(0));
expect(events[0].detail.required).toBe('TEAMS');
} finally {
window.removeEventListener('waggle:tier-insufficient', listener);
}
});
it('scopes MCP catalog filters and distribution transitions to explicit properties', { timeout: CATALOG_TIMEOUT }, async () => {
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('tab', { name: 'Catalog' }));
await screen.findByText('PostgreSQL');
const distributionSegment = screen.getByRole('button', { name: /Files: 1 servers/i });
expect(distributionSegment.className).not.toContain('transition-all');
expect(distributionSegment.className).toContain('transition-[filter]');
const allChip = screen.getByRole('button', { name: /^All/i });
const databaseChip = screen.getByRole('button', { name: /^Database\s+.\s+1$/i });
expect(allChip?.className).not.toContain('transition-all');
expect(allChip?.className).toContain('transition-[background-color,color,box-shadow]');
expect(databaseChip?.className).not.toContain('transition-all');
expect(databaseChip?.className).toContain('transition-[background-color,color,box-shadow]');
});
it('a11y: catalog search exposes stable form metadata', { timeout: CATALOG_TIMEOUT }, async () => {
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('tab', { name: 'Catalog' }));
const search = await screen.findByRole('textbox', { name: /search mcp catalog/i });
expect(search).toHaveAttribute('name', 'mcpCatalogSearch');
expect(search).toHaveAttribute('autocomplete', 'off');
});
it('a SecurityGate-blocked install renders the risk ApprovalModal; approve retries with forceInsecure', { timeout: CATALOG_TIMEOUT }, async () => {
// Mirror the REAL installer-level contract: the block only clears when
// forceInsecure is sent (installer.ts gates on `!request.forceInsecure`;
// `force` alone means "reinstall"). A retry without it re-blocks — this
// mock pins the approve-loop regression: the assertion below fails if
// the FE retries with {force:true} only.
mocks.adapter.installMcp.mockImplementation(async (_id: string, opts?: { force?: boolean; forceInsecure?: boolean }) => (
opts?.forceInsecure
? { installed: true, mcpId: 'postgres', server: 'postgres', status: 'ready' }
: {
installed: false, requiresApproval: true,
message: 'Installation blocked: 1 HIGH severity finding(s). Use forceInsecure=true to override.',
scanResult: { overall_severity: 'HIGH', blocked: true },
}
));
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('tab', { name: 'Catalog' }));
fireEvent.click(await screen.findByTestId('mcp-install-postgres'));
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent(/despite security-scan findings/);
expect(modal).toHaveTextContent('Security scan severity: HIGH');
expect(modal).toHaveTextContent(/install audit trail/);
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.installMcp).toHaveBeenLastCalledWith('postgres', { force: true, forceInsecure: true }));
// The override succeeded — the modal must NOT reopen (the approve loop).
await waitFor(() => expect(screen.queryByTestId('approval-modal')).not.toBeInTheDocument());
});
it('a CRITICAL block is rendered as non-overridable — no approval offered', { timeout: CATALOG_TIMEOUT }, async () => {
mocks.adapter.installMcp.mockResolvedValue({
installed: false, requiresApproval: true,
message: 'Installation blocked: 2 CRITICAL security finding(s) detected.',
scanResult: { overall_severity: 'CRITICAL', blocked: true },
});
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('tab', { name: 'Catalog' }));
fireEvent.click(await screen.findByTestId('mcp-install-postgres'));
const notice = await screen.findByTestId('mcp-install-notice');
expect(notice).toHaveTextContent(/CRITICAL blocks cannot be overridden/);
expect(screen.queryByTestId('approval-modal')).not.toBeInTheDocument();
});
it('a ROUTE-level CRITICAL block (top-level severity, no scanResult) is also non-overridable', { timeout: CATALOG_TIMEOUT }, async () => {
mocks.adapter.installMcp.mockResolvedValue({
installed: false, requiresApproval: true, blocked: true, severity: 'CRITICAL',
message: 'Installation blocked: CRITICAL severity (score: 9.8).',
});
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('tab', { name: 'Catalog' }));
fireEvent.click(await screen.findByTestId('mcp-install-postgres'));
const notice = await screen.findByTestId('mcp-install-notice');
expect(notice).toHaveTextContent(/CRITICAL blocks cannot be overridden/);
expect(screen.queryByTestId('approval-modal')).not.toBeInTheDocument();
});
it('A4: catalog entries the marketplace cannot resolve render NO Install button (copy-command only)', { timeout: CATALOG_TIMEOUT }, async () => {
// Only 'filesystem' resolves — 'postgres' must fall back to copy-command.
mocks.adapter.getMarketplace.mockResolvedValue({ packages: [{ name: 'filesystem' }], total: 1 });
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('tab', { name: 'Catalog' }));
await screen.findByText('PostgreSQL');
expect(screen.queryByTestId('mcp-install-postgres')).not.toBeInTheDocument();
});
it('C19: the scope editor sends the exact single-workspace / personal payloads', async () => {
mocks.adapter.updateMcpPermissions.mockResolvedValue({ ok: true, id: 'filesystem', scope: 'personal' });
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('button', { name: /Scope/ }));
const dialog = await screen.findByTestId('mcp-scope-dialog');
expect(dialog).toBeInTheDocument();
const workspaceSelect = screen.getByLabelText('Target workspace');
expect(workspaceSelect).toHaveAttribute('name', 'mcpScopeWorkspaceId');
expect(workspaceSelect).toHaveAttribute('autocomplete', 'off');
expect(workspaceSelect.className).toContain('focus-visible:ring-2');
expect(workspaceSelect.className).toContain('focus-visible:ring-[var(--focus-ring)]');
// Pinned to ws-1 today → switch to personal and save.
fireEvent.click(screen.getByRole('radio', { name: /Personal — all workspaces/ }));
fireEvent.click(screen.getByTestId('mcp-scope-save'));
await waitFor(() => expect(mocks.adapter.updateMcpPermissions).toHaveBeenCalledWith('filesystem', { scope: 'personal' }));
});
it('C19: a rejected scope save (error body as data) keeps the dialog open instead of faking success', async () => {
// 400/404 bodies resolve as data through adapter.fetch — no ok field.
mocks.adapter.updateMcpPermissions.mockResolvedValue({ error: '"filesystem" is not installed' });
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('button', { name: /Scope/ }));
await screen.findByTestId('mcp-scope-dialog');
fireEvent.click(screen.getByRole('radio', { name: /Personal — all workspaces/ }));
fireEvent.click(screen.getByTestId('mcp-scope-save'));
await waitFor(() => expect(mocks.adapter.updateMcpPermissions).toHaveBeenCalled());
// The dialog must stay open — closing it would claim the save landed.
expect(screen.getByTestId('mcp-scope-dialog')).toBeInTheDocument();
});
it('a failed Start surfaces the server error inline (never silently swallowed)', async () => {
mocks.adapter.getMcps.mockResolvedValue([
{ ...MCPS[0], status: 'stopped', state: 'stopped' },
]);
// POST /:id/start 502 body resolves as data through adapter.fetch.
mocks.adapter.startMcp.mockResolvedValue({ status: 'error', error: 'spawn timed out after 10000ms' });
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('button', { name: /Start/ }));
const err = await screen.findByTestId('mcp-action-error-filesystem');
expect(err).toHaveTextContent('Start failed — spawn timed out after 10000ms');
});
it('revoke confirms with consequences and renders the stopped/removed result', async () => {
mocks.adapter.revokeMcp.mockResolvedValue({ ok: true, id: 'filesystem', stoppedInstance: true, removedConfig: true });
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('button', { name: /Revoke/ }));
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent('Revoke MCP server "Filesystem"?');
expect(modal).toHaveTextContent(/Stops the running process/);
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.revokeMcp).toHaveBeenCalledWith('filesystem'));
const notice = await screen.findByTestId('mcp-revoke-notice');
expect(notice).toHaveTextContent('process stopped');
expect(notice).toHaveTextContent('persisted config removed');
});
it('the custom-add form submits the exact addCustomMcp payload', async () => {
mocks.adapter.addCustomMcp.mockResolvedValue({ id: 'my-server', registered: true });
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('tab', { name: 'Custom' }));
fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'my-server' } });
fireEvent.change(screen.getByLabelText('Command'), { target: { value: 'npx' } });
fireEvent.change(screen.getByLabelText('Arguments (one per line)'), { target: { value: '-y\nmy-pkg' } });
fireEvent.click(screen.getByTestId('add-custom-mcp-submit'));
await waitFor(() => expect(mocks.adapter.addCustomMcp).toHaveBeenCalledWith({
name: 'my-server', command: 'npx', args: ['-y', 'my-pkg'],
}));
});
it('a11y: the custom-add form exposes stable metadata and focus rings', async () => {
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('tab', { name: 'Custom' }));
await screen.findByTestId('add-custom-mcp-form');
const name = screen.getByLabelText('Name');
expect(name).toHaveAttribute('name', 'mcpServerName');
expect(name).toHaveAttribute('autocomplete', 'off');
expect(name.className).toContain('focus-visible:ring-2');
expect(name.className).toContain('focus-visible:ring-[var(--focus-ring)]');
const command = screen.getByLabelText('Command');
expect(command).toHaveAttribute('name', 'mcpServerCommand');
expect(command).toHaveAttribute('autocomplete', 'off');
const args = screen.getByLabelText('Arguments (one per line)');
expect(args).toHaveAttribute('name', 'mcpServerArgs');
expect(args).toHaveAttribute('autocomplete', 'off');
const env = screen.getByLabelText('Environment (KEY=VALUE, one per line)');
expect(env).toHaveAttribute('name', 'mcpServerEnv');
expect(env).toHaveAttribute('autocomplete', 'off');
const scope = screen.getByLabelText(/Workspace scope/);
expect(scope).toHaveAttribute('name', 'mcpWorkspaceScope');
expect(scope).toHaveAttribute('autocomplete', 'off');
expect(scope.className).toContain('focus-visible:ring-2');
expect(scope.className).toContain('focus-visible:ring-[var(--focus-ring)]');
const submit = screen.getByTestId('add-custom-mcp-submit');
expect(submit.className).toContain('focus-visible:ring-2');
expect(submit.className).toContain('focus-visible:ring-[var(--focus-ring)]');
});
it('C20: the Remote Registry tab is an honest stdio-only pointer, not a fake catalog', async () => {
renderApp();
await screen.findByText('Filesystem');
fireEvent.click(screen.getByRole('tab', { name: 'Remote Registry' }));
const panel = await screen.findByTestId('mcp-remote-registry');
expect(panel).toHaveTextContent(/stdio-only/);
expect(panel).toHaveTextContent(/awesome-mcp-servers/);
});
});
describe('mcpStateBadge', () => {
it('maps the raw runtime states and the installed fallback honestly', () => {
expect(mcpStateBadge({ state: 'ready', installed: true })).toEqual({ tone: 'healthy', label: 'Ready' });
expect(mcpStateBadge({ state: 'starting', installed: true })).toEqual({ tone: 'info', label: 'Starting…' });
expect(mcpStateBadge({ state: 'error', installed: true })).toEqual({ tone: 'risk', label: 'Error' });
expect(mcpStateBadge({ installed: true })).toEqual({ tone: 'neutral', label: 'Installed — not running' });
expect(mcpStateBadge({ installed: false })).toEqual({ tone: 'neutral', label: 'Not installed' });
});
});

View File

@@ -0,0 +1,48 @@
/**
* Phase 5b · R4-006 — BackupApp metadata-fetch status classification.
*
* Before the fix, `GET /api/backup/metadata` was consumed with a bare
* `.then(r => r.json())` — no `response.ok` guard. A non-2xx response (e.g. a
* 500 from a broken backend) deserialized to the error body, whose
* `data.backups` is undefined, so `data.backups ?? []` collapsed every server
* fault into the misleading "No backups yet" empty state.
*
* The fix routes the status through the pure `classifyMetadataStatus`:
* - 404 → 'empty' (legitimate "no backups yet")
* - 2xx → 'ok' (parse + render the metadata)
* - anything else → 'error' (retryable error panel, never the empty state)
*
* Why no component-render test: `@testing-library/react` (React 19, hoisted to
* the monorepo root) mixes its `react-dom/client` copy with this app's React
* 18.3 and throws "A React Element from an older version of React was
* rendered." This is the same documented constraint that keeps
* `ConnectorsApp.shouldResetCredentialInputs` at the pure-function layer; the
* R4-002 Restore wiring + the rendered error/retry panel are covered by
* Playwright.
*/
import { describe, it, expect } from 'vitest';
import { classifyMetadataStatus } from '@/components/os/apps/BackupApp';
describe('BackupApp · R4-006 classifyMetadataStatus', () => {
it('treats 404 as the legitimate empty state, not an error', () => {
expect(classifyMetadataStatus(404)).toBe('empty');
});
it('treats a 200 metadata response as ok', () => {
expect(classifyMetadataStatus(200)).toBe('ok');
});
it('treats a 500 as a (retryable) error, NOT the empty state', () => {
expect(classifyMetadataStatus(500)).toBe('error');
});
it('treats other server faults (502/503) as errors', () => {
expect(classifyMetadataStatus(502)).toBe('error');
expect(classifyMetadataStatus(503)).toBe('error');
});
it('treats a 401/403 as an error rather than silently showing no backups', () => {
expect(classifyMetadataStatus(401)).toBe('error');
expect(classifyMetadataStatus(403)).toBe('error');
});
});

View File

@@ -0,0 +1,46 @@
/**
* Phase 5b · R4-007 — ConnectorsApp shared-credential footgun.
*
* `ConnectorsApp` holds a SINGLE `tokenInput` (and `emailInput`) state that is
* reused by every connector row. Before the fix, switching the expanded
* connector left whatever was typed for connector A sitting in connector B's
* input — a wrong-credential footgun where A's token could be submitted to B.
*
* The fix routes every expand/collapse through `selectConnector`, which clears
* the inputs whenever the target connector changes. The decision rule is
* extracted into the pure `shouldResetCredentialInputs(prev, next)` so it can
* be regression-tested here without rendering React.
*
* Why no component-render test: `@testing-library/react` (built for React 19,
* hoisted to the monorepo root) mixes its `react-dom/client` copy with this
* app's React 18.3 and throws "A React Element from an older version of React
* was rendered." This is the same documented constraint that keeps
* `useDeveloperMode.test.ts` and `TextBlock.test.tsx` at the pure-function
* layer; full render is covered by Playwright.
*/
import { describe, it, expect } from 'vitest';
import { shouldResetCredentialInputs } from '@/components/os/apps/ConnectorsApp';
describe('ConnectorsApp · R4-007 shouldResetCredentialInputs', () => {
it('resets when switching from one connector to a different one', () => {
// Token typed for "github" must NOT survive into "slack".
expect(shouldResetCredentialInputs('github', 'slack')).toBe(true);
});
it('does NOT reset when re-collapsing the same open connector', () => {
// Toggling the open row shut keeps the field as-is for that connector.
expect(shouldResetCredentialInputs('github', 'github')).toBe(false);
});
it('resets when opening the first connector from a collapsed state', () => {
expect(shouldResetCredentialInputs(null, 'github')).toBe(true);
});
it('resets when collapsing an open connector to none', () => {
expect(shouldResetCredentialInputs('github', null)).toBe(true);
});
it('does NOT reset when nothing is open and nothing opens', () => {
expect(shouldResetCredentialInputs(null, null)).toBe(false);
});
});

View File

@@ -0,0 +1,76 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
// This monorepo nests React 18 under apps/web while hoisting React 19 at the
// root. `@testing-library/react` (built for React 19) mixes its react-dom/client
// copy with this app's React 18 and throws "A React Element from an older
// version of React was rendered." This is the same documented constraint that
// keeps ConnectorsApp / useDeveloperMode / TextBlock tests at the pure layer.
// To still exercise the *render-time* catch behaviour of the boundary (which has
// no pure function to extract), we render with React 18's own createRoot from
// THIS app's copy, keeping a single consistent React instance. lucide-react
// resolves the hoisted React copy, so its decorative icon is stubbed out.
vi.mock("lucide-react", () => ({
AlertTriangle: (props: Record<string, unknown>) => <svg data-testid="alert-icon" {...props} />,
}));
import AppErrorBoundary from "@/components/os/ErrorBoundary";
/**
* Phase 5b · R4-001 — top-level recoverable error boundary.
*
* App.tsx now wraps the route shell (Routes/Index + Desktop chrome + overlays)
* in AppErrorBoundary. These tests prove the boundary catches a render throw and
* shows a recoverable fallback instead of letting the whole app white-screen.
*/
const Boom = () => {
throw new Error("render exploded");
};
describe("phase5b · AppErrorBoundary", () => {
let container: HTMLDivElement;
let root: Root;
let consoleError: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
// React logs caught render errors to console.error; silence the expected noise.
consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
});
afterEach(() => {
act(() => root.unmount());
container.remove();
consoleError.mockRestore();
});
it("renders the recoverable fallback when a child throws (no white screen)", () => {
act(() => {
root.render(
<AppErrorBoundary appName="Waggle OS" onClose={() => {}}>
<Boom />
</AppErrorBoundary>,
);
});
expect(container.textContent).toContain("Waggle OS encountered an error");
expect(container.textContent).toContain("render exploded");
expect(container.querySelector("button")?.textContent).toContain("Close Window");
});
it("renders children unchanged when nothing throws", () => {
act(() => {
root.render(
<AppErrorBoundary appName="Waggle OS">
<div>healthy child</div>
</AppErrorBoundary>,
);
});
expect(container.textContent).toContain("healthy child");
expect(container.textContent).not.toContain("Waggle OS encountered an error");
});
});

View File

@@ -0,0 +1,70 @@
import { describe, it, expect } from 'vitest';
import type { ChatMessage } from '@/lib/types';
/**
* Phase 5b · R4-003 — useChat empty-array guard.
*
* useChat's streaming setMessages updater reads the last message's role:
*
* const msgs = [...prev];
* const last = msgs[msgs.length - 1];
* if (!last || last.role !== 'assistant') return msgs; // R4-003 guard
*
* A session/workspace switch mid-stream resets messages to [] via the load
* effect. A late stream event then arrives while `prev` is empty, so
* `msgs[msgs.length - 1]` is `undefined` and reading `.role` off it throws
* `TypeError: Cannot read properties of undefined (reading 'role')` inside the
* React state updater — crashing the render commit.
*
* Full render-level coverage via renderHook/render is unavailable here: the
* monorepo hoists react-dom@19 at the root while apps/web targets react@18.3,
* so @testing-library/react 16's renderer mixes React copies and throws (same
* limitation documented in useDeveloperMode.test.ts). We instead pin the exact
* updater head — the `prev → msgs → last → last.role` access — which is the
* line R4-003 fixes. The unguarded form throws on []; the guarded form returns
* the array unchanged.
*/
// The unguarded access exactly as it stood before R4-003 (lines 130-133).
function unguardedUpdater(prev: ChatMessage[]): ChatMessage[] {
const msgs = [...prev];
const last = msgs[msgs.length - 1];
if (last.role !== 'assistant') return msgs; // throws when last is undefined
return msgs;
}
// The guarded access as shipped by R4-003.
function guardedUpdater(prev: ChatMessage[]): ChatMessage[] {
const msgs = [...prev];
const last = msgs[msgs.length - 1];
if (!last || last.role !== 'assistant') return msgs;
return msgs;
}
const assistantMsg: ChatMessage = {
id: 'a1',
role: 'assistant',
content: '',
timestamp: new Date().toISOString(),
};
describe('useChat — R4-003 empty-array guard', () => {
it('reproduces the crash: unguarded last.role throws on an empty array', () => {
// This is the pre-fix behaviour — proves the finding is real.
expect(() => unguardedUpdater([])).toThrowError(
/Cannot read properties of undefined \(reading 'role'\)/,
);
});
it('guarded updater returns the empty array unchanged instead of throwing', () => {
expect(() => guardedUpdater([])).not.toThrow();
expect(guardedUpdater([])).toEqual([]);
});
it('guarded updater still passes through a non-empty array (no behaviour change)', () => {
const prev = [assistantMsg];
// Same result as the unguarded path when the array is non-empty.
expect(guardedUpdater(prev)).toEqual(prev);
expect(unguardedUpdater(prev)).toEqual(prev);
});
});

View File

@@ -0,0 +1,159 @@
/**
* Pillar 2.6 — route-cache contract for Marketplace + Agents (path-to-9 v3
* §Pillar 2.6). A judged surface that unmounts on tab-away must, on return
* WITHIN the session: (a) repaint its last-known content instantly — no cold
* skeleton; (b) refresh silently in the background; (c) Marketplace also lands
* on the shelf the user left, not a reset to All. These are the contract, so
* they are asserted as tests (not left as guidelines).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { Agent } from '@/lib/types';
const mocks = vi.hoisted(() => ({
adapter: {
connect: vi.fn().mockResolvedValue(undefined),
forceReconnect: vi.fn().mockResolvedValue(undefined),
// Marketplace + InstallProvider hydrate surface
getMarketplace: vi.fn(),
getMarketplacePacks: vi.fn(),
getMcps: vi.fn(),
getConnectors: vi.fn(),
getExtendAudit: vi.fn().mockResolvedValue([]),
agentSearch: vi.fn().mockResolvedValue({ need: '', gapDetected: false, alreadyHandled: false, recommendation: null, candidates: [], picks: {} }),
installMarketplacePackage: vi.fn(),
uninstallMarketplacePackage: vi.fn(),
connectConnector: vi.fn().mockResolvedValue(undefined),
disconnectConnector: vi.fn().mockResolvedValue(undefined),
installMcp: vi.fn(),
revokeMcp: vi.fn().mockResolvedValue({ ok: true }),
installPack: vi.fn().mockResolvedValue(undefined),
// Agents surface
listAgents: vi.fn(),
runAgent: vi.fn(),
pauseAgent: vi.fn(),
patchAgent: vi.fn(),
createAgent: vi.fn(),
getAgentTraces: vi.fn().mockResolvedValue([]),
getPersonas: vi.fn().mockResolvedValue([]),
getCapabilityStatus: vi.fn().mockResolvedValue({}),
getAgentGroups: vi.fn().mockResolvedValue([]),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import MarketplaceApp, { resetMarketplaceRouteCache } from '@/components/os/apps/MarketplaceApp';
import AgentsApp, { resetAgentsRouteCache } from '@/components/os/apps/AgentsApp';
import { ServiceProvider } from '@/providers/ServiceProvider';
import { InstallProvider } from '@/providers/InstallProvider';
const renderMarketplace = () => render(
<ServiceProvider><InstallProvider><TooltipProvider><MarketplaceApp /></TooltipProvider></InstallProvider></ServiceProvider>,
);
const WORKSPACES = [{ id: 'ws-1', name: 'Acme Research', group: 'work' }];
const renderAgents = () => render(
<MemoryRouter><ServiceProvider><TooltipProvider>
<AgentsApp workspaces={WORKSPACES} />
</TooltipProvider></ServiceProvider></MemoryRouter>,
);
function makeAgent(over: Partial<Agent> = {}): Agent {
return {
id: 'a1', name: 'Scout', goal: 'Research the market', type: 'personal',
model: 'auto', autonomyLevel: 'guided', memoryScopes: ['personal'],
status: 'idle', createdAt: '2026-06-01T00:00:00Z', updatedAt: '2026-06-01T00:00:00Z',
successRate: 0.8, lastRunAt: '2026-06-09T00:00:00Z', ...over,
};
}
beforeEach(() => {
vi.clearAllMocks();
resetMarketplaceRouteCache();
resetAgentsRouteCache();
mocks.adapter.connect.mockResolvedValue(undefined);
mocks.adapter.forceReconnect.mockResolvedValue(undefined);
mocks.adapter.getMarketplace.mockImplementation(async (params?: { type?: string }) => (
params?.type === 'mcp'
? { packages: [], total: 0 }
: { packages: [{ id: 7, name: 'web-scraper', description: 'Scrape pages', waggle_install_type: 'skill', installed: false, scanStatus: 'passed', source: 'registry' }], total: 1 }
));
mocks.adapter.getMarketplacePacks.mockResolvedValue([]);
mocks.adapter.getMcps.mockResolvedValue([
{ id: 'postgres', name: 'PostgreSQL', description: 'Query databases', category: 'Database', installed: false },
]);
mocks.adapter.getConnectors.mockResolvedValue([
{ id: 'github', name: 'GitHub', description: 'Code hosting', service: 'github', authType: 'bearer', status: 'connected', capabilities: [], substrate: 'waggle', tools: [], category: 'development' },
]);
});
afterEach(cleanup);
describe('Pillar 2.6 route-cache — Marketplace', () => {
it('a return within the session repaints the grid instantly (no cold spinner) and refreshes silently', async () => {
const first = renderMarketplace();
expect(await screen.findByText('Web Scraper')).toBeInTheDocument();
let baseline = 0;
await waitFor(() => {
baseline = mocks.adapter.getMarketplace.mock.calls.length;
expect(baseline).toBeGreaterThan(0);
});
first.unmount();
// Return: the last-loaded grid is on screen SYNCHRONOUSLY on the first paint
// (seeded from cache), before any fetch resolves — and the cold spinner is
// never shown.
renderMarketplace();
expect(screen.getByText('Web Scraper')).toBeInTheDocument();
expect(screen.queryByText('Loading extensions...')).not.toBeInTheDocument();
// …and it still refreshes silently in the background.
await waitFor(() => expect(mocks.adapter.getMarketplace.mock.calls.length).toBeGreaterThan(baseline));
});
it('a return lands on the shelf the user left, not a reset to All', async () => {
const first = renderMarketplace();
await screen.findByText('Web Scraper');
// Switch to the Skills shelf and let its load commit (connectors drop off).
fireEvent.click(screen.getByRole('button', { name: 'Skills' }));
await waitFor(() => expect(screen.queryByText('GitHub')).not.toBeInTheDocument());
expect(screen.getByRole('button', { name: 'Skills' })).toHaveAttribute('aria-pressed', 'true');
first.unmount();
// Return: Skills is the active shelf on the first paint (restored from cache).
renderMarketplace();
expect(screen.getByRole('button', { name: 'Skills' })).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByRole('button', { name: 'All' })).toHaveAttribute('aria-pressed', 'false');
});
});
describe('Pillar 2.6 route-cache — Agents', () => {
it('a return within the session repaints the roster instantly (no BeeLoader) and refreshes silently', async () => {
mocks.adapter.listAgents.mockResolvedValue([makeAgent({ id: 'a1', name: 'Scout' })]);
const first = renderAgents();
expect(await screen.findByText('Scout')).toBeInTheDocument();
const baseline = mocks.adapter.listAgents.mock.calls.length;
first.unmount();
// Return: the roster is on screen synchronously and the cold BeeLoader never
// shows (agents seeded → the `loading && agents.length===0` guard is false).
renderAgents();
expect(screen.getByText('Scout')).toBeInTheDocument();
expect(screen.queryByTestId('bee-loader')).not.toBeInTheDocument();
await waitFor(() => expect(mocks.adapter.listAgents.mock.calls.length).toBeGreaterThan(baseline));
});
it('a return to a genuinely-empty fleet shows the empty-state instantly, not a fresh BeeLoader', async () => {
mocks.adapter.listAgents.mockResolvedValue([]);
const first = renderAgents();
// Cold load: BeeLoader → resolves empty → empty-state.
expect(await screen.findByText(/No custom agents yet/)).toBeInTheDocument();
first.unmount();
// Return: the empty-state is on screen synchronously — a resolved-empty
// surface must NOT re-skeleton (the shelf-cache `hasResolved` lesson).
renderAgents();
expect(screen.getByText(/No custom agents yet/)).toBeInTheDocument();
expect(screen.queryByTestId('bee-loader')).not.toBeInTheDocument();
});
});

View File

@@ -0,0 +1,203 @@
/**
* PR3.5 Phase B+C — Memory-Trust "Manage" view (stats + filters + row actions).
*
* Pins the no-fabrication stat gating, the filter-chip behavior, and that the
* row actions hit the real adapter routes (forget/confirm).
*/
import { describe, it, expect, afterEach, vi, beforeEach } from 'vitest';
import { render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react';
import type { Memory } from '@/lib/types';
const mocks = vi.hoisted(() => ({
adapter: {
listMemories: vi.fn(),
deleteMemoryById: vi.fn().mockResolvedValue(undefined),
confirmMemory: vi.fn().mockResolvedValue({}),
patchMemory: vi.fn().mockResolvedValue({}),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/lib/app-deeplink', () => ({ consumeDeepLink: () => null }));
import MemoryTrustManage, { resetMemoryHeroSession } from '@/components/os/apps/memory/MemoryTrustManage';
import { clearMemoryListCache } from '@/components/os/apps/memory/memory-list-cache';
const DAY = 86_400_000;
const iso = (ageDays: number) => new Date(Date.now() - ageDays * DAY).toISOString();
function mem(over: Partial<Memory> & Pick<Memory, 'id'>): Memory {
return {
kind: 'fact', title: `Fact ${over.id}`, content: `Content for ${over.id}`,
scope: 'personal', source: 'agent_inferred', sourceId: null, sourceUrl: null,
confidence: undefined, importance: 'normal', evidence: undefined, tags: undefined,
status: 'active', createdAt: iso(1), updatedAt: undefined, lastAccessedAt: iso(1),
...over,
} as Memory;
}
afterEach(() => { cleanup(); vi.clearAllMocks(); clearMemoryListCache(); resetMemoryHeroSession(); });
beforeEach(() => {
mocks.adapter.deleteMemoryById.mockResolvedValue(undefined);
mocks.adapter.confirmMemory.mockResolvedValue({});
});
describe('MemoryTrustManage stats + filters + actions (PR3.5 Phase B+C)', () => {
it('gates "high confidence" to — when no memory carries confidence (no fabrication)', async () => {
mocks.adapter.listMemories.mockResolvedValue([
mem({ id: '1', createdAt: iso(1) }),
mem({ id: '2', createdAt: iso(60) }),
]);
render(<MemoryTrustManage mind="personal" onToast={() => {}} />);
// W2D: headline now names the scope ("· personal mind").
await waitFor(() => expect(screen.getByText(/Memories in this hive/)).toBeTruthy());
// No confidence on any frame → the "high confidence" dimension chip's VALUE
// is a neutral dash, never a count. (W2D split the old near-always-0
// "high confidence & fresh" conjunction into two independent chips.)
const card = screen.getByText('high confidence').previousElementSibling;
expect(card?.textContent).toBe('—');
});
it('renders the confidence ring as NN% when confidence is present', async () => {
mocks.adapter.listMemories.mockResolvedValue([mem({ id: '7', confidence: 94, createdAt: iso(1) })]);
render(<MemoryTrustManage mind="personal" onToast={() => {}} />);
await waitFor(() => expect(screen.getByText('⬡ M-7')).toBeTruthy());
expect(screen.getByText('94%')).toBeTruthy();
});
it('the "Needs confirm" filter shows only unreviewed memories', async () => {
mocks.adapter.listMemories.mockResolvedValue([
mem({ id: '1', status: 'active', createdAt: iso(1) }),
mem({ id: '2', status: 'unreviewed', createdAt: iso(1) }),
]);
render(<MemoryTrustManage mind="personal" onToast={() => {}} />);
await waitFor(() => expect(screen.getByText('⬡ M-1')).toBeTruthy());
fireEvent.click(screen.getByText('Needs confirm'));
await waitFor(() => expect(screen.queryByText('⬡ M-1')).toBeNull());
expect(screen.getByText('⬡ M-2')).toBeTruthy();
});
it('the "Forgotten" filter chip is gated off (disabled — hard delete leaves no list)', async () => {
mocks.adapter.listMemories.mockResolvedValue([mem({ id: '1' })]);
render(<MemoryTrustManage mind="personal" onToast={() => {}} />);
await waitFor(() => expect(screen.getByText('⬡ M-1')).toBeTruthy());
const forgotten = screen.getByText('Forgotten').closest('button')!;
expect(forgotten.getAttribute('aria-disabled')).toBe('true');
});
it('a11y: search control exposes stable form metadata', async () => {
mocks.adapter.listMemories.mockResolvedValue([mem({ id: '1' })]);
render(<MemoryTrustManage mind="personal" onToast={() => {}} />);
const search = await screen.findByLabelText('Search memories');
expect(search).toHaveAttribute('name', 'memoryTrustSearch');
expect(search).toHaveAttribute('autocomplete', 'off');
expect(search.className).toContain('focus-visible:ring-2');
expect(search.className).toContain('focus-visible:ring-[var(--focus-ring)]');
});
it('a11y: correction editor exposes stable form metadata and a visible focus style', async () => {
mocks.adapter.listMemories.mockResolvedValue([mem({ id: '5', createdAt: iso(1) })]);
render(<MemoryTrustManage mind="personal" onToast={() => {}} />);
fireEvent.click(await screen.findByRole('button', { name: 'Edit or correct memory M-5' }));
const editor = await screen.findByLabelText('Correct this memory');
expect(editor).toHaveAttribute('name', 'memoryTrustCorrection');
expect(editor).toHaveAttribute('autocomplete', 'off');
expect(editor.className).toContain('focus-visible:ring-2');
});
it('Forget hits deleteMemoryById and fires a toast', async () => {
mocks.adapter.listMemories.mockResolvedValue([mem({ id: '5', createdAt: iso(1) })]);
const onToast = vi.fn();
render(<MemoryTrustManage mind="personal" onToast={onToast} />);
await waitFor(() => expect(screen.getByText('⬡ M-5')).toBeTruthy());
fireEvent.click(screen.getByTitle('Forget this'));
await waitFor(() => expect(mocks.adapter.deleteMemoryById).toHaveBeenCalledWith('5', undefined, 'personal'));
expect(onToast).toHaveBeenCalledWith(expect.stringContaining('Forgotten M-5'));
});
// R20 Lane CL (item 2, second surface): the memory-row actions are reachable
// without a mouse — they are always-rendered native <button>s with accessible
// names (not a hover-gated menu), so Tab lands on them and the systemic
// :focus-visible ring (index.css → --focus-ring) paints on focus.
it('the row Forget/Edit actions are keyboard-reachable buttons with accessible names', async () => {
mocks.adapter.listMemories.mockResolvedValue([mem({ id: '5', createdAt: iso(1) })]);
render(<MemoryTrustManage mind="personal" onToast={() => {}} />);
await waitFor(() => expect(screen.getByText('⬡ M-5')).toBeTruthy());
const forget = screen.getByRole('button', { name: 'Forget memory M-5' });
const edit = screen.getByRole('button', { name: 'Edit or correct memory M-5' });
expect(forget.tagName).toBe('BUTTON');
expect(edit.tagName).toBe('BUTTON');
// Provably reachable: focus lands directly on the action (natural tab order).
forget.focus();
expect(document.activeElement).toBe(forget);
});
it('Confirm on an unreviewed memory hits confirmMemory and fires a toast', async () => {
mocks.adapter.listMemories.mockResolvedValue([mem({ id: '8', status: 'unreviewed', createdAt: iso(1) })]);
const onToast = vi.fn();
render(<MemoryTrustManage mind="personal" onToast={onToast} />);
await waitFor(() => expect(screen.getByText('⬡ M-8')).toBeTruthy());
fireEvent.click(screen.getByTitle('Confirm this memory'));
await waitFor(() => expect(mocks.adapter.confirmMemory).toHaveBeenCalledWith('8', undefined, 'personal'));
expect(onToast).toHaveBeenCalledWith(expect.stringContaining('Confirmed M-8'));
});
it('hero count settles instantly on a tab-return remount — never a transient 0 (Wave V Lane A item 1)', async () => {
resetMemoryHeroSession();
mocks.adapter.listMemories.mockResolvedValue([
mem({ id: '1', createdAt: iso(1) }),
mem({ id: '2', createdAt: iso(1) }),
mem({ id: '3', createdAt: iso(1) }),
]);
const { unmount } = render(<MemoryTrustManage mind="personal" onToast={() => {}} />);
// First visit resolves the real count (the once-per-session count-up runs here).
await waitFor(() => expect(screen.getByTestId('memory-trust-total').textContent).toBe('3'));
unmount();
// Tab return: the list re-seeds from the session cache, so the hero must show
// the cached 3 on its very FIRST paint — no skeleton, no count-up from 0.
render(<MemoryTrustManage mind="personal" onToast={() => {}} />);
expect(screen.getByTestId('memory-trust-total').textContent).toBe('3');
// Drain the background refresh so its setState lands inside act().
await waitFor(() => expect(mocks.adapter.listMemories).toHaveBeenCalledTimes(2));
});
it('the hero count-up floors at ceil(15%) — never paints 0/near-0 above rendered rows (Wave W Lane D item 1)', async () => {
resetMemoryHeroSession();
// 20 rows → floor = ceil(20 * 0.15) = 3, so no animation frame can show 0/1/2.
mocks.adapter.listMemories.mockResolvedValue(
Array.from({ length: 20 }, (_, i) => mem({ id: String(i + 1), createdAt: iso(1) })),
);
render(<MemoryTrustManage mind="personal" onToast={() => {}} />);
// Once data lands the hero replaces the stat-bar skeleton.
await waitFor(() => expect(screen.getByTestId('memory-trust-total')).toBeTruthy());
// The count-up is monotonic from the floor, so every sampled frame is ≥ floor
// (and thus never the "0 Memories with data present" data-bug frame).
expect(Number(screen.getByTestId('memory-trust-total').textContent)).toBeGreaterThanOrEqual(3);
// …and it still settles on the true total.
await waitFor(() => expect(screen.getByTestId('memory-trust-total').textContent).toBe('20'));
});
// Pillar 2.7 (Lane K) — row-action keyboard/hit-area parity.
it('row actions carry a ≥40px hit area (centered 40px ::before, no visual size change)', async () => {
mocks.adapter.listMemories.mockResolvedValue([mem({ id: '5', createdAt: iso(1) })]);
render(<MemoryTrustManage mind="personal" onToast={() => {}} />);
await waitFor(() => expect(screen.getByText('⬡ M-5')).toBeTruthy());
for (const title of ['Edit / correct', 'Forget this']) {
const btn = screen.getByTitle(title);
expect(btn.className).toContain('relative');
expect(btn.className).toContain('before:h-10');
expect(btn.className).toContain('before:w-10');
// Visual size is untouched — the 30px button box stays 30px.
expect(btn.className).toContain('h-[30px]');
}
});
it('workspace mind passes the workspace param to mutations', async () => {
mocks.adapter.listMemories.mockResolvedValue([mem({ id: '9', createdAt: iso(1) })]);
render(<MemoryTrustManage mind="workspace" workspaceId="w1" onToast={() => {}} />);
await waitFor(() => expect(screen.getByText('⬡ M-9')).toBeTruthy());
fireEvent.click(screen.getByTitle('Forget this'));
await waitFor(() => expect(mocks.adapter.deleteMemoryById).toHaveBeenCalledWith('9', 'w1', 'workspace'));
});
});

View File

@@ -0,0 +1,74 @@
/**
* PR3.5 Phase D — Memory-Trust "Why did you do that?" trace view.
*
* Pins: the real-trace chain (goal → tool calls → acted) from getMemoryTrace,
* the two HONEST empty states (no memory picked / no trace linked), and the
* footer actions (looks-right toast, correct, forget).
*/
import { describe, it, expect, afterEach, vi } from 'vitest';
import { render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react';
import type { MemoryTrace } from '@/lib/types';
const mocks = vi.hoisted(() => ({
adapter: { getMemoryTrace: vi.fn() },
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import MemoryTrustWhy from '@/components/os/apps/memory/MemoryTrustWhy';
const TRACE: MemoryTrace = {
id: 42, sessionId: 'sess1234abcd', workspaceId: null, model: 'claude-sonnet-4-6',
outcome: 'success', costUsd: 0.012, durationMs: 1200,
createdAt: new Date().toISOString(), finalizedAt: new Date().toISOString(),
input: 'tighten the board narrative', output: 'Wrote slide 6 around the regulated angle.',
reasoning: [{ content: 'considering the angle', timestamp: new Date().toISOString() }],
toolCalls: [
{ tool: 'auto_recall', ok: true, durationMs: 50, timestamp: new Date().toISOString() },
{ tool: 'web_search', ok: true, durationMs: 300, timestamp: new Date().toISOString() },
],
tokens: { input: 100, output: 50 },
};
afterEach(() => { cleanup(); vi.clearAllMocks(); });
describe('MemoryTrustWhy (PR3.5 Phase D)', () => {
it('with no memory selected, prompts the user to open one (no fetch)', () => {
render(<MemoryTrustWhy mind="personal" memoryId={null} onToast={() => {}} onCorrect={() => {}} onForget={() => {}} />);
expect(screen.getByText(/Open a memory.+trace to see why/i)).toBeTruthy();
expect(mocks.adapter.getMemoryTrace).not.toHaveBeenCalled();
});
it('renders an honest "no trace linked" state when the frame has no backlink', async () => {
mocks.adapter.getMemoryTrace.mockResolvedValue({ trace: null });
render(<MemoryTrustWhy mind="personal" memoryId="204" onToast={() => {}} onCorrect={() => {}} onForget={() => {}} />);
await waitFor(() => expect(screen.getByText(/No trace is linked to M-204/)).toBeTruthy());
});
it('renders the real trace chain: goal → tool calls → acted + footer', async () => {
mocks.adapter.getMemoryTrace.mockResolvedValue({ trace: TRACE });
render(<MemoryTrustWhy mind="personal" memoryId="204" onToast={() => {}} onCorrect={() => {}} onForget={() => {}} />);
await waitFor(() => expect(screen.getByText('Goal received')).toBeTruthy());
expect(screen.getByText(/tighten the board narrative/)).toBeTruthy();
expect(screen.getByText('Recalled memories')).toBeTruthy(); // auto_recall humanized
expect(screen.getByText('Web Search')).toBeTruthy();
expect(screen.getByText(/Acted —/)).toBeTruthy();
expect(screen.getByText('trace #42')).toBeTruthy();
expect(screen.getByText('Looks right')).toBeTruthy();
});
it('footer actions fire the right callbacks', async () => {
mocks.adapter.getMemoryTrace.mockResolvedValue({ trace: TRACE });
const onToast = vi.fn(); const onCorrect = vi.fn(); const onForget = vi.fn();
render(<MemoryTrustWhy mind="personal" memoryId="204" onToast={onToast} onCorrect={onCorrect} onForget={onForget} />);
await waitFor(() => expect(screen.getByText('Looks right')).toBeTruthy());
fireEvent.click(screen.getByText('Looks right'));
expect(onToast).toHaveBeenCalledWith(expect.stringContaining('M-204'));
fireEvent.click(screen.getByText(/That memory is wrong/));
expect(onCorrect).toHaveBeenCalledWith('204');
fireEvent.click(screen.getByText(/Forget M-204/));
expect(onForget).toHaveBeenCalledWith('204');
});
});

View File

@@ -0,0 +1,54 @@
/**
* PR3.5 Phase A — Memory Trust (screen 19) host shell.
*
* Pins the segmented-control contract: two views behind one switch, each with
* its own editorial hero + trust-principle footnote. The Manage body embeds the
* per-mind list (stubbed here — Phase C replaces it with the native rows); the
* Why body shows an honest empty state until Phase D wires the real trace.
*/
import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
import { vi } from 'vitest';
// Stub the Manage body — this test pins the Trust SHELL, not list internals.
vi.mock('@/components/os/apps/memory/MemoryTrustManage', () => ({
default: (props: { mind?: string; workspaceId?: string }) => (
<div data-testid="stub-trust-manage" data-mind={String(props.mind)} data-ws={String(props.workspaceId)} />
),
}));
import MemoryTrust from '@/components/os/apps/MemoryTrust';
afterEach(cleanup);
describe('MemoryTrust shell (PR3.5 Phase A)', () => {
it('defaults to the Manage view: hero + segmented control + Manage body + principle', () => {
render(<MemoryTrust mind="personal" />);
expect(screen.getByText('Manage memory')).toBeTruthy();
expect(screen.getByText('Why did you do that?')).toBeTruthy();
expect(screen.getByText(/Memory you can/)).toBeTruthy();
expect(screen.getByText(/correct, age, and forget\./)).toBeTruthy();
expect(screen.getByTestId('stub-trust-manage').getAttribute('data-mind')).toBe('personal');
expect(screen.getByText(/Nothing is remembered behind your back\./)).toBeTruthy();
});
it('passes the workspace mind through to the Manage body', () => {
render(<MemoryTrust mind="workspace" workspaceId="w1" />);
const body = screen.getByTestId('stub-trust-manage');
expect(body.getAttribute('data-mind')).toBe('workspace');
expect(body.getAttribute('data-ws')).toBe('w1');
});
it('toggles to the Why view: trace hero + honest empty state + its principle', () => {
render(<MemoryTrust mind="personal" />);
fireEvent.click(screen.getByText('Why did you do that?'));
// Why hero + empty state (no synthesized reason) + Why-specific principle.
// (Match the hero by its unique opener — "why did you do that?" also appears
// on the segmented button.)
expect(screen.getByText(/Ask the agent/i)).toBeTruthy();
expect(screen.getByText(/to see why Waggle acted/i)).toBeTruthy();
expect(screen.getByText(/Every agent action keeps its trace\./)).toBeTruthy();
// The Manage body is unmounted on the Why view.
expect(screen.queryByTestId('stub-trust-manage')).toBeNull();
});
});

View File

@@ -0,0 +1,121 @@
/**
* PR4 Phase C — the AgentSearchBox suggestion box (screen 09). A need produces
* a connector/skill/tool three-up; the skill installs through the shared store,
* the connector hands off to the Hub, and example chips run a search.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import type { AgentSearchResponse } from '@/lib/agent-search';
const mocks = vi.hoisted(() => ({
adapter: {
connect: vi.fn().mockResolvedValue(undefined),
forceReconnect: vi.fn().mockResolvedValue(undefined),
getConnectors: vi.fn().mockResolvedValue([]),
getMcps: vi.fn().mockResolvedValue([]),
getMarketplace: vi.fn().mockResolvedValue({ packages: [] }),
installMarketplacePackage: vi.fn().mockResolvedValue(new Response('{}', { status: 200 })),
connectConnector: vi.fn().mockResolvedValue(undefined),
installMcp: vi.fn().mockResolvedValue({ installed: true }),
revokeMcp: vi.fn().mockResolvedValue({ ok: true }),
uninstallMarketplacePackage: vi.fn().mockResolvedValue(new Response('{}', { status: 200 })),
disconnectConnector: vi.fn().mockResolvedValue(undefined),
installPack: vi.fn().mockResolvedValue(undefined),
agentSearch: vi.fn(),
},
toast: vi.fn(),
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/hooks/use-toast', () => ({ useToast: () => ({ toast: mocks.toast }) }));
import { ServiceProvider } from '@/providers/ServiceProvider';
import { InstallProvider } from '@/providers/InstallProvider';
import AgentSearchBox from '@/components/os/apps/extend/AgentSearchBox';
const wrapper = ({ children }: { children: ReactNode }) => (
<ServiceProvider><InstallProvider>{children}</InstallProvider></ServiceProvider>
);
const RESULT: AgentSearchResponse = {
need: 'send a message to my team',
gapDetected: true,
alreadyHandled: false,
recommendation: null,
candidates: [],
picks: {
connector: { name: 'Slack', type: 'connector', availability: 'installable', description: 'Team chat', matchReason: 'matches: slack, message', matchScore: 0.9, install: { mode: 'store', extensionId: 'connector:slack', type: 'connector', kind: 'federated', authType: 'bearer' } },
skill: { name: 'team-update', type: 'marketplace', availability: 'installable', description: 'Draft team updates', matchReason: 'matches: team, message', matchScore: 0.7, install: { mode: 'store', extensionId: 'pkg:7', type: 'skill', kind: 'package', packageId: 7 } },
tool: { name: 'web_search', type: 'native', availability: 'active', description: 'Search the web', matchReason: 'name matches: search', matchScore: 0.6, install: { mode: 'active' } },
},
};
const ask = (text: string) => {
const input = screen.getByLabelText('Ask Waggle');
fireEvent.change(input, { target: { value: text } });
fireEvent.keyDown(input, { key: 'Enter' });
};
beforeEach(() => {
mocks.adapter.connect.mockResolvedValue(undefined);
mocks.adapter.getConnectors.mockResolvedValue([]);
mocks.adapter.getMcps.mockResolvedValue([]);
mocks.adapter.getMarketplace.mockResolvedValue({ packages: [] });
mocks.adapter.installMarketplacePackage.mockResolvedValue(new Response('{}', { status: 200 }));
mocks.adapter.installPack.mockResolvedValue(undefined);
mocks.adapter.agentSearch.mockResolvedValue(RESULT);
});
afterEach(() => { cleanup(); vi.clearAllMocks(); });
describe('AgentSearchBox', () => {
it('renders the connector + skill + tool three-up with each "why"', async () => {
render(<AgentSearchBox />, { wrapper });
ask('send a message to my team');
await waitFor(() => expect(mocks.adapter.agentSearch).toHaveBeenCalledWith('send a message to my team'));
expect(await screen.findByTestId('agent-search-pick-connector')).toHaveTextContent('Slack');
expect(screen.getByTestId('agent-search-pick-skill')).toHaveTextContent('team-update');
expect(screen.getByTestId('agent-search-pick-tool')).toHaveTextContent('web_search');
// the deterministic "why" surfaces
expect(screen.getByTestId('agent-search-pick-connector')).toHaveTextContent('matches: slack, message');
// a native tool you already have reads Available (no install)
expect(screen.getByTestId('agent-search-pick-tool')).toHaveTextContent('Available');
});
it('installs a skill pick through the shared store (one-click)', async () => {
render(<AgentSearchBox />, { wrapper });
ask('send a message to my team');
await screen.findByTestId('agent-search-pick-skill');
fireEvent.click(screen.getByTestId('agent-search-act-team-update'));
await waitFor(() => expect(mocks.adapter.installMarketplacePackage).toHaveBeenCalledWith(7));
});
it('hands a connector pick off to the Connector Hub (token-paste lives there)', async () => {
const events: CustomEvent[] = [];
const listener = (e: Event) => events.push(e as CustomEvent);
window.addEventListener('waggle:open-app', listener);
try {
render(<AgentSearchBox />, { wrapper });
ask('send a message to my team');
await screen.findByTestId('agent-search-pick-connector');
fireEvent.click(screen.getByTestId('agent-search-act-Slack'));
await waitFor(() => expect(events.some(e => e.detail.appId === 'connectors')).toBe(true));
expect(mocks.adapter.connectConnector).not.toHaveBeenCalled();
} finally {
window.removeEventListener('waggle:open-app', listener);
}
});
it('an example chip runs a search', async () => {
render(<AgentSearchBox />, { wrapper });
fireEvent.click(await screen.findByTestId('agent-search-chip-0'));
await waitFor(() => expect(mocks.adapter.agentSearch).toHaveBeenCalled());
});
it('surfaces a search error without crashing', async () => {
mocks.adapter.agentSearch.mockRejectedValue(new Error('backend down'));
render(<AgentSearchBox />, { wrapper });
ask('anything');
expect(await screen.findByRole('alert')).toHaveTextContent('backend down');
});
});

View File

@@ -0,0 +1,115 @@
/**
* PR4 Phase D — the inline capability card (Variation B). Each kind routes
* through the shared install store (so a chat install reflects in the grid +
* count bar): connector token-paste / OAuth→Hub, mcp enable, marketplace
* resolve-then-install, starter via installPack.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import type { CapabilityRequest } from '@/components/os/apps/chat-blocks/CapabilityRequestCard';
const mocks = vi.hoisted(() => ({
adapter: {
connect: vi.fn().mockResolvedValue(undefined),
forceReconnect: vi.fn().mockResolvedValue(undefined),
getConnectors: vi.fn().mockResolvedValue([]),
getMcps: vi.fn().mockResolvedValue([]),
getMarketplace: vi.fn().mockResolvedValue({ packages: [] }),
searchMarketplace: vi.fn(),
installMarketplacePackage: vi.fn().mockResolvedValue(new Response('{}', { status: 200 })),
uninstallMarketplacePackage: vi.fn().mockResolvedValue(new Response('{}', { status: 200 })),
connectConnector: vi.fn().mockResolvedValue(undefined),
disconnectConnector: vi.fn().mockResolvedValue(undefined),
installMcp: vi.fn().mockResolvedValue({ installed: true }),
revokeMcp: vi.fn().mockResolvedValue({ ok: true }),
installPack: vi.fn().mockResolvedValue(undefined),
},
toast: vi.fn(),
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/hooks/use-toast', () => ({ useToast: () => ({ toast: mocks.toast }) }));
import { ServiceProvider } from '@/providers/ServiceProvider';
import { InstallProvider } from '@/providers/InstallProvider';
import CapabilityRequestCard from '@/components/os/apps/chat-blocks/CapabilityRequestCard';
const wrapper = ({ children }: { children: ReactNode }) => (
<ServiceProvider><InstallProvider>{children}</InstallProvider></ServiceProvider>
);
const renderCard = (request: CapabilityRequest) => render(<CapabilityRequestCard request={request} />, { wrapper });
beforeEach(() => {
mocks.adapter.connect.mockResolvedValue(undefined);
mocks.adapter.getConnectors.mockResolvedValue([]);
mocks.adapter.getMcps.mockResolvedValue([]);
mocks.adapter.getMarketplace.mockResolvedValue({ packages: [] });
mocks.adapter.searchMarketplace.mockResolvedValue(
new Response(JSON.stringify({ packages: [{ id: 7, waggle_install_type: 'skill' }] }), { status: 200 }));
mocks.adapter.installMarketplacePackage.mockResolvedValue(new Response('{}', { status: 200 }));
mocks.adapter.installMcp.mockResolvedValue({ installed: true });
mocks.adapter.connectConnector.mockResolvedValue(undefined);
mocks.adapter.installPack.mockResolvedValue(undefined);
});
afterEach(() => { cleanup(); vi.clearAllMocks(); });
describe('CapabilityRequestCard (PR4 Variation B)', () => {
it('a marketplace request resolves the package id then installs through the store', async () => {
renderCard({ name: 'web-scraper', source: 'marketplace', kind: 'marketplace' });
fireEvent.click(screen.getByTestId('capability-request-install'));
await waitFor(() => expect(mocks.adapter.searchMarketplace).toHaveBeenCalledWith('web-scraper', 1));
await waitFor(() => expect(mocks.adapter.installMarketplacePackage).toHaveBeenCalledWith(7));
expect(await screen.findByText(/Done — available/)).toBeInTheDocument();
});
it('a token connector reveals an inline paste row and connects FE-direct (not over the approval wire)', async () => {
renderCard({ name: 'Slack', source: 'connector', kind: 'connector', connectorId: 'slack', authType: 'bearer' });
// The verb is Connect, not Install.
expect(screen.getByTestId('capability-request-install')).toHaveTextContent('Connect');
fireEvent.click(screen.getByTestId('capability-request-install'));
const input = await screen.findByLabelText(/slack api token/i);
expect(input).toHaveAttribute('name', 'capabilityConnectorToken');
expect(input).toHaveAttribute('autocomplete', 'off');
fireEvent.change(input, { target: { value: 'xoxb-9' } });
fireEvent.click(screen.getByTestId('capability-connector-token-submit'));
await waitFor(() => expect(mocks.adapter.connectConnector).toHaveBeenCalledWith('slack', { token: 'xoxb-9' }));
});
it('an OAuth connector hands off to the Hub (no inline token)', async () => {
const events: CustomEvent[] = [];
const listener = (e: Event) => events.push(e as CustomEvent);
window.addEventListener('waggle:open-app', listener);
try {
renderCard({ name: 'Google Calendar', source: 'connector', kind: 'connector', authType: 'oauth2' });
fireEvent.click(screen.getByTestId('capability-request-install'));
await waitFor(() => expect(events.some(e => e.detail.appId === 'connectors')).toBe(true));
expect(screen.queryByTestId('capability-connector-token-input')).not.toBeInTheDocument();
expect(mocks.adapter.connectConnector).not.toHaveBeenCalled();
} finally {
window.removeEventListener('waggle:open-app', listener);
}
});
it('an mcp request enables through the store', async () => {
renderCard({ name: 'postgres', source: 'mcp', kind: 'mcp' });
expect(screen.getByTestId('capability-request-install')).toHaveTextContent('Enable');
fireEvent.click(screen.getByTestId('capability-request-install'));
await waitFor(() => expect(mocks.adapter.installMcp).toHaveBeenCalledWith('postgres', undefined));
expect(await screen.findByText(/Done — available/)).toBeInTheDocument();
});
it('a starter-pack request installs via installPack (bundled, not store-tracked)', async () => {
renderCard({ name: 'daily-plan', source: 'starter-pack' });
fireEvent.click(screen.getByTestId('capability-request-install'));
await waitFor(() => expect(mocks.adapter.installPack).toHaveBeenCalledWith('daily-plan'));
expect(mocks.adapter.installMarketplacePackage).not.toHaveBeenCalled();
});
it('Dismiss declines without installing', async () => {
renderCard({ name: 'web-scraper', source: 'marketplace', kind: 'marketplace' });
fireEvent.click(screen.getByTestId('capability-request-decline'));
expect(await screen.findByText('Dismissed')).toBeInTheDocument();
expect(mocks.adapter.installMarketplacePackage).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,286 @@
/**
* PR4 Phase A — the shared install store (InstallProvider / useInstallStore).
* Verifies hydrate, the type-aware dispatcher, confirmed-success flip,
* reconcile (roll back / carry-over), the in-flight micro-state, and the
* honest global count — all over a mocked adapter.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act, waitFor, cleanup } from '@testing-library/react';
import type { ReactNode } from 'react';
const mocks = vi.hoisted(() => ({
adapter: {
connect: vi.fn().mockResolvedValue(undefined),
forceReconnect: vi.fn().mockResolvedValue(undefined),
getConnectors: vi.fn().mockResolvedValue([]),
getMcps: vi.fn().mockResolvedValue([]),
getMarketplace: vi.fn().mockResolvedValue({ packages: [] }),
installMarketplacePackage: vi.fn(),
uninstallMarketplacePackage: vi.fn().mockResolvedValue(undefined),
connectConnector: vi.fn().mockResolvedValue(undefined),
disconnectConnector: vi.fn().mockResolvedValue(undefined),
installMcp: vi.fn(),
revokeMcp: vi.fn().mockResolvedValue({ ok: true, stoppedInstance: true, removedConfig: true }),
},
toast: vi.fn(),
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/hooks/use-toast', () => ({ useToast: () => ({ toast: mocks.toast }) }));
import { ServiceProvider } from '@/providers/ServiceProvider';
import { InstallProvider, useInstallStore } from '@/providers/InstallProvider';
import type { InstallTarget } from '@/lib/install-store';
const wrapper = ({ children }: { children: ReactNode }) => (
<ServiceProvider><InstallProvider>{children}</InstallProvider></ServiceProvider>
);
/** Mount and wait for the connect→settle→initial-hydrate to actually finish.
* hydrating starts false, so we first wait for the hydrate to START (a read
* fired) and only then for it to settle — otherwise the wait returns at t=0. */
async function mountStore() {
const view = renderHook(() => useInstallStore(), { wrapper });
await waitFor(() => expect(mocks.adapter.getMarketplace).toHaveBeenCalled());
await waitFor(() => expect(view.result.current.hydrating).toBe(false));
return view;
}
const pkg = (id: number, name = `pkg${id}`): InstallTarget =>
({ id: `pkg:${id}`, type: 'skill', kind: 'package', name, packageId: id });
const connector = (id: string, name = id): InstallTarget =>
({ id: `connector:${id}`, type: 'connector', kind: 'federated', name });
const catalogMcp = (id: string, name = id): InstallTarget =>
({ id: `mcp:${id}`, type: 'mcp', kind: 'federated', name });
/** AdapterHttpError stand-in (the connect path throws on !ok). */
function httpError(status: number, body: unknown): Error {
const e = new Error('http') as Error & { status: number; body: unknown };
e.name = 'AdapterHttpError';
e.status = status;
e.body = body;
return e;
}
// clearAllMocks resets call history but NOT implementations, so re-establish
// the default adapter responses before each test (otherwise a per-test
// mockResolvedValue override leaks into the next test).
beforeEach(() => {
mocks.adapter.connect.mockResolvedValue(undefined);
mocks.adapter.forceReconnect.mockResolvedValue(undefined);
mocks.adapter.getConnectors.mockResolvedValue([]);
mocks.adapter.getMcps.mockResolvedValue([]);
mocks.adapter.getMarketplace.mockResolvedValue({ packages: [] });
mocks.adapter.installMarketplacePackage.mockResolvedValue(new Response('{}', { status: 200 }));
mocks.adapter.uninstallMarketplacePackage.mockResolvedValue(undefined);
mocks.adapter.connectConnector.mockResolvedValue(undefined);
mocks.adapter.disconnectConnector.mockResolvedValue(undefined);
mocks.adapter.installMcp.mockResolvedValue({ installed: true });
mocks.adapter.revokeMcp.mockResolvedValue({ ok: true, stoppedInstance: true, removedConfig: true });
});
afterEach(() => { cleanup(); vi.clearAllMocks(); });
describe('InstallProvider — hydrate', () => {
it('populates installed from connected connectors + enabled MCPs + installed packages', async () => {
mocks.adapter.getConnectors.mockResolvedValue([
{ id: 'slack', status: 'connected' }, { id: 'gmail', status: 'disconnected' },
]);
mocks.adapter.getMcps.mockResolvedValue([
{ id: 'postgres', installed: true }, { id: 'redis', installed: false },
]);
mocks.adapter.getMarketplace.mockImplementation((p: { type?: string }) =>
Promise.resolve({ packages: p?.type === 'skill' ? [{ id: 7, installed: true }, { id: 8, installed: false }] : [] }));
const { result } = await mountStore();
expect(result.current.isInstalled('connector:slack')).toBe(true);
expect(result.current.isInstalled('connector:gmail')).toBe(false);
expect(result.current.isInstalled('mcp:postgres')).toBe(true);
expect(result.current.isInstalled('mcp:redis')).toBe(false);
expect(result.current.isInstalled('pkg:7')).toBe(true);
expect(result.current.isInstalled('pkg:8')).toBe(false);
// Honest global count = connected + enabled + installed (D1).
expect(result.current.installedCount).toBe(3);
});
});
describe('InstallProvider — install dispatcher', () => {
it('package install success flips installed + toasts Added', async () => {
mocks.adapter.installMarketplacePackage.mockResolvedValue(new Response('{}', { status: 200 }));
const { result } = await mountStore();
let outcome;
await act(async () => { outcome = await result.current.install(pkg(9, 'Foo')); });
expect(outcome).toEqual({ ok: true });
expect(result.current.isInstalled('pkg:9')).toBe(true);
expect(result.current.installedCount).toBe(1);
expect(mocks.toast).toHaveBeenCalledWith(expect.objectContaining({ title: 'Added' }));
});
it('package install 403 TIER → reason tier, NOT installed, no destructive toast (adapter dispatches the event)', async () => {
mocks.adapter.installMarketplacePackage.mockResolvedValue(
new Response(JSON.stringify({ error: 'TIER_INSUFFICIENT', required: 'TEAMS' }), { status: 403 }));
const { result } = await mountStore();
let outcome;
await act(async () => { outcome = await result.current.install(pkg(9)); });
expect(outcome).toEqual({ ok: false, reason: 'tier' });
expect(result.current.isInstalled('pkg:9')).toBe(false);
expect(mocks.toast).not.toHaveBeenCalled();
});
it('package install SecurityGate block → reason security + destructive toast, NOT installed', async () => {
mocks.adapter.installMarketplacePackage.mockResolvedValue(
new Response(JSON.stringify({ blocked: true, severity: 'high', message: 'bad pkg' }), { status: 403 }));
const { result } = await mountStore();
let outcome;
await act(async () => { outcome = await result.current.install(pkg(9)); });
expect(outcome).toEqual({ ok: false, reason: 'security' });
expect(result.current.isInstalled('pkg:9')).toBe(false);
expect(mocks.toast).toHaveBeenCalledWith(expect.objectContaining({ variant: 'destructive' }));
});
it('connector without a token returns needs-credentials and never calls the adapter', async () => {
const { result } = await mountStore();
let outcome;
await act(async () => { outcome = await result.current.install(connector('slack')); });
expect(outcome).toEqual({ ok: false, reason: 'needs-credentials' });
expect(mocks.adapter.connectConnector).not.toHaveBeenCalled();
expect(result.current.isInstalling('connector:slack')).toBe(false);
});
it('connector with a token connects via the un-prefixed id and flips installed', async () => {
const { result } = await mountStore();
let outcome;
await act(async () => { outcome = await result.current.install(connector('slack'), { token: 'xoxb' }); });
expect(outcome).toEqual({ ok: true });
expect(mocks.adapter.connectConnector).toHaveBeenCalledWith('slack', { token: 'xoxb' });
expect(result.current.isInstalled('connector:slack')).toBe(true);
expect(mocks.toast).toHaveBeenCalledWith(expect.objectContaining({ title: 'Connected' }));
});
it('a connector 403 tier rejection is classified as tier (no destructive toast)', async () => {
mocks.adapter.connectConnector.mockRejectedValue(httpError(403, { error: 'TIER_INSUFFICIENT' }));
const { result } = await mountStore();
let outcome;
await act(async () => { outcome = await result.current.install(connector('slack'), { token: 'xoxb' }); });
expect(outcome).toEqual({ ok: false, reason: 'tier' });
expect(result.current.isInstalled('connector:slack')).toBe(false);
expect(mocks.toast).not.toHaveBeenCalled(); // the adapter dispatched the upgrade event
});
it('catalog MCP enable success flips installed', async () => {
mocks.adapter.installMcp.mockResolvedValue({ installed: true, server: 'postgres', status: 'running' });
const { result } = await mountStore();
let outcome;
await act(async () => { outcome = await result.current.install(catalogMcp('postgres')); });
expect(outcome).toEqual({ ok: true });
expect(mocks.adapter.installMcp).toHaveBeenCalledWith('postgres', undefined);
expect(result.current.isInstalled('mcp:postgres')).toBe(true);
});
it('catalog MCP requiresApproval → reason security, NOT installed', async () => {
mocks.adapter.installMcp.mockResolvedValue({ installed: false, requiresApproval: true, severity: 'high' });
const { result } = await mountStore();
let outcome;
await act(async () => { outcome = await result.current.install(catalogMcp('postgres')); });
expect(outcome).toEqual({ ok: false, reason: 'security' });
expect(result.current.isInstalled('mcp:postgres')).toBe(false);
});
it('a browse-only pack is unsupported and touches no backend', async () => {
const { result } = await mountStore();
let outcome;
await act(async () => {
outcome = await result.current.install({ id: 'pack:research', type: 'skill', kind: 'pack', name: 'Research' });
});
expect(outcome).toEqual({ ok: false, reason: 'unsupported' });
expect(mocks.adapter.installMarketplacePackage).not.toHaveBeenCalled();
});
it('exposes the in-flight micro-state while a package install is pending', async () => {
let release: (r: Response) => void = () => {};
mocks.adapter.installMarketplacePackage.mockReturnValue(new Promise<Response>(res => { release = res; }));
const { result } = await mountStore();
let done!: Promise<unknown>;
act(() => { done = result.current.install(pkg(9)); });
await waitFor(() => expect(result.current.isInstalling('pkg:9')).toBe(true));
expect(result.current.isInstalled('pkg:9')).toBe(false); // not yet confirmed
await act(async () => { release(new Response('{}', { status: 200 })); await done; });
expect(result.current.isInstalling('pkg:9')).toBe(false);
expect(result.current.isInstalled('pkg:9')).toBe(true);
});
});
describe('InstallProvider — uninstall + reconcile', () => {
it('uninstalling a package removes it from the installed set', async () => {
mocks.adapter.getMarketplace.mockImplementation((p: { type?: string }) =>
Promise.resolve({ packages: p?.type === 'skill' ? [{ id: 7, installed: true }] : [] }));
const { result } = await mountStore();
expect(result.current.isInstalled('pkg:7')).toBe(true);
let outcome;
await act(async () => { outcome = await result.current.uninstall(pkg(7)); });
expect(outcome).toEqual({ ok: true });
expect(result.current.isInstalled('pkg:7')).toBe(false);
expect(result.current.installedCount).toBe(0);
});
it('a total hydrate failure keeps the previously-known installed set (no wipe)', async () => {
mocks.adapter.getConnectors.mockResolvedValueOnce([{ id: 'slack', status: 'connected' }]);
mocks.adapter.getMarketplace.mockImplementation((p: { type?: string }) =>
Promise.resolve({ packages: p?.type === 'skill' ? [{ id: 7, installed: true }] : [] }));
const { result } = await mountStore();
expect(result.current.installedCount).toBe(2);
// Backend goes down: every read rejects → previous set must survive.
mocks.adapter.getConnectors.mockRejectedValue(new Error('down'));
mocks.adapter.getMcps.mockRejectedValue(new Error('down'));
mocks.adapter.getMarketplace.mockRejectedValue(new Error('down'));
await act(async () => { await result.current.hydrate(); });
expect(result.current.isInstalled('connector:slack')).toBe(true);
expect(result.current.isInstalled('pkg:7')).toBe(true);
expect(result.current.installedCount).toBe(2);
});
it('a confirmed install survives a concurrent in-flight hydrate (HIGH race regression)', async () => {
const { result } = await mountStore();
// Arm a hydrate whose marketplace reads are held open (issued BEFORE the install).
let releaseSkill = () => {};
let releaseMcp = () => {};
mocks.adapter.getMarketplace.mockImplementation((p: { type?: string }) =>
p?.type === 'skill'
? new Promise(res => { releaseSkill = () => res({ packages: [] }); })
: new Promise(res => { releaseMcp = () => res({ packages: [] }); }));
let hydratePromise!: Promise<void>;
act(() => { hydratePromise = result.current.hydrate(); }); // in-flight; reads held
// Confirm an install while the stale hydrate is mid-flight.
await act(async () => { await result.current.install(pkg(9, 'Foo')); });
expect(result.current.isInstalled('pkg:9')).toBe(true);
// Release the stale reads — the hydrate's commit must ABORT (the flip bumped
// the seq), so it cannot wipe the just-confirmed install.
await act(async () => { releaseSkill(); releaseMcp(); await hydratePromise; });
expect(result.current.isInstalled('pkg:9')).toBe(true);
expect(result.current.installedCount).toBe(1);
});
it('an asymmetric package-read failure preserves the failed domain pkg ids (MEDIUM regression)', async () => {
mocks.adapter.getMarketplace.mockImplementation((p: { type?: string }) =>
Promise.resolve({ packages: p?.type === 'skill' ? [{ id: 7, installed: true }] : [{ id: 99, installed: true }] }));
const { result } = await mountStore();
expect(result.current.installedCount).toBe(2);
// Re-hydrate: skill read OK, mcp read REJECTS → pkg:99 must NOT be dropped.
mocks.adapter.getMarketplace.mockImplementation((p: { type?: string }) =>
p?.type === 'skill' ? Promise.resolve({ packages: [{ id: 7, installed: true }] }) : Promise.reject(new Error('500')));
await act(async () => { await result.current.hydrate(); });
expect(result.current.isInstalled('pkg:7')).toBe(true);
expect(result.current.isInstalled('pkg:99')).toBe(true);
expect(result.current.installedCount).toBe(2);
});
});

View File

@@ -0,0 +1,83 @@
/**
* PR5 Phase B — Settings reskin/reconcile pins:
* - Settings opens on the Models tab with the shared ModelGate leading (D: "Models leads").
* - Billing rail tab renamed to "Plan" (D8).
* - The "Show" disclosure control (D6, anchored to the foot of the tab rail)
* drives the rail, with Advanced surfacing only at Everything (D7).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { act, render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
const mocks = vi.hoisted(() => ({
adapter: {
getSettings: vi.fn().mockResolvedValue({}),
getPermissions: vi.fn().mockResolvedValue({ defaultAutonomy: 'normal', externalGates: [] }),
getTeamStatus: vi.fn().mockResolvedValue({ connected: false }),
getTelemetryStatus: vi.fn().mockResolvedValue({ enabled: false, totalEvents: 0 }),
getTier: vi.fn().mockResolvedValue({ tier: 'FREE', capabilities: {}, usage: {} }),
getServerUrl: vi.fn().mockReturnValue('http://127.0.0.1:3333'),
getProviders: vi.fn().mockResolvedValue({ providers: [], search: [], activeSearch: 'duckduckgo' }),
getLocalInferenceStatus: vi.fn().mockResolvedValue({ servers: [], ollamaInstalled: false, totalLocalModels: 0 }),
// MODEL-GATE: the mount probe calls these too — absent, the probe's async
// closure throws (TypeError: not a function) as an UNHANDLED rejection that
// poisons unrelated tests in the full-suite run. configured:false = the
// probe's honest "nothing to check" idle path.
probeModel: vi.fn().mockResolvedValue({ configured: false }),
probeProvider: vi.fn().mockResolvedValue({ configured: false, valid: false, verified: false }),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
async function renderSettings() {
const { default: SettingsApp } = await import('@/components/os/apps/SettingsApp');
const { TooltipProvider } = await import('@/components/ui/tooltip');
const { MemoryRouter } = await import('react-router-dom');
await act(async () => {
render(
// SettingsApp reads `?tab=` via useSearchParams (PR7a/D12) — it is a routed
// surface (SettingsRoute mounts it inside BrowserRouter), so tests must
// provide a Router context.
<MemoryRouter future={{ v7_relativeSplatPath: true, v7_startTransition: true }}>
<TooltipProvider>
<SettingsApp />
</TooltipProvider>
</MemoryRouter>,
);
});
await screen.findByText(/no working model yet/i);
await waitFor(() => {
expect(mocks.adapter.getSettings).toHaveBeenCalled();
expect(mocks.adapter.getPermissions).toHaveBeenCalled();
expect(mocks.adapter.getTeamStatus).toHaveBeenCalled();
expect(mocks.adapter.getTelemetryStatus).toHaveBeenCalled();
expect(mocks.adapter.getProviders).toHaveBeenCalled();
expect(mocks.adapter.getLocalInferenceStatus).toHaveBeenCalled();
});
}
beforeEach(() => { window.localStorage.clear(); });
afterEach(() => { cleanup(); vi.clearAllMocks(); });
describe('PR5 Settings reskin', () => {
it('opens on the Models tab with the ModelGate leading (no click needed)', async () => {
await renderSettings();
expect(await screen.findByRole('tablist', { name: /how to add a model/i })).toBeInTheDocument();
});
it('renames the Billing rail tab to "Plan" (D8)', async () => {
await renderSettings();
expect(await screen.findByRole('tab', { name: /^plan$/i })).toBeInTheDocument();
expect(screen.queryByRole('tab', { name: /^billing$/i })).toBeNull();
});
it('the Show control gates Advanced to Everything (D6 + D7)', async () => {
await renderSettings();
await screen.findByRole('group', { name: /settings detail level/i });
// Default disclosure (Essential) hides Advanced from the rail.
expect(screen.queryByRole('tab', { name: /advanced/i })).toBeNull();
// Switch to Everything → Advanced appears.
fireEvent.click(screen.getByRole('button', { name: /everything/i }));
expect(await screen.findByRole('tab', { name: /advanced/i })).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,179 @@
/**
* PR7a — Billing (screen 14) themed over the REAL useBilling→Stripe flow.
* Pins the load-bearing behaviors + the no-fabrication gates:
* - PlanCards: 2-card grid (Solo · free / Team · most-popular), annual toggle
* swaps the displayed price AND threads the real `billingPeriod` to checkout
* (D8/F9), current tier marked "Your plan". Team is the only checkout path.
* - useBilling.startCheckout passes billingPeriod to the adapter (D8).
* - SettingsApp `?tab=billing` deep-link snaps to the Plan tab (D12).
* - PaymentSuccessApp confirms off the SYNCED tier and renders NO fabricated
* receipt rows (F5).
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, renderHook, act, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
const mocks = vi.hoisted(() => ({
adapter: {
getSettings: vi.fn().mockResolvedValue({}),
getPermissions: vi.fn().mockResolvedValue({ defaultAutonomy: 'normal', externalGates: [] }),
getTeamStatus: vi.fn().mockResolvedValue({ connected: false }),
getTelemetryStatus: vi.fn().mockResolvedValue({ enabled: false, totalEvents: 0 }),
getTier: vi.fn().mockResolvedValue({ tier: 'FREE', capabilities: {}, usage: {} }),
getServerUrl: vi.fn().mockReturnValue('http://127.0.0.1:3333'),
getProviders: vi.fn().mockResolvedValue({ providers: [], search: [], activeSearch: 'duckduckgo' }),
getLocalInferenceStatus: vi.fn().mockResolvedValue({ servers: [], ollamaInstalled: false, totalLocalModels: 0 }),
createCheckoutSession: vi.fn().mockResolvedValue({ url: 'https://checkout.stripe.test/abc' }),
createPortalSession: vi.fn().mockResolvedValue({ url: 'https://portal.stripe.test/abc' }),
syncStripeCheckout: vi.fn().mockResolvedValue({ tier: 'TEAMS', customerId: 'cus_1' }),
getStripeStatus: vi.fn().mockResolvedValue({ configured: true }),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
beforeEach(() => { window.localStorage.clear(); });
afterEach(() => { cleanup(); vi.clearAllMocks(); window.history.replaceState({}, '', '/'); });
describe('PR7a · PlanCards', () => {
it('renders the 2-card grid (Solo · free / Team · most-popular)', async () => {
const { default: PlanCards } = await import('@/components/os/billing/PlanCards');
render(<PlanCards currentTier="FREE" onChoose={vi.fn()} />);
expect(screen.getByText('Solo')).toBeInTheDocument();
expect(screen.getByText('Team')).toBeInTheDocument();
expect(screen.queryByText('Pro')).not.toBeInTheDocument();
expect(screen.getByText('Most popular')).toBeInTheDocument();
// Solo (FREE) user → Solo is the current plan
expect(screen.getByText('Your plan')).toBeInTheDocument();
});
it('annual toggle swaps the displayed price AND threads billingPeriod to onChoose (D8/F9)', async () => {
const { default: PlanCards } = await import('@/components/os/billing/PlanCards');
const onChoose = vi.fn();
render(<PlanCards currentTier="FREE" onChoose={onChoose} />);
// Monthly default → Team shows $49
expect(screen.getByText('$49')).toBeInTheDocument();
// Switch to annual → Team shows $39 (the real annual price label, not a client × 0.8)
fireEvent.click(screen.getByRole('button', { name: /Annual/i }));
expect(screen.getByText('$39')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Choose Team/i }));
expect(onChoose).toHaveBeenCalledWith('TEAMS', 'annual');
});
it('does not offer an in-app downgrade — lower tiers show "Included", not a CTA (D6)', async () => {
const { default: PlanCards } = await import('@/components/os/billing/PlanCards');
const onChoose = vi.fn();
render(<PlanCards currentTier="TEAMS" onChoose={onChoose} />);
// TEAMS user: Team = "Your plan", Solo = "Included", no downgrade CTA
expect(screen.getByText('Your plan')).toBeInTheDocument();
expect(screen.getByText('Included')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /Choose Team/i })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /Choose Solo/i })).not.toBeInTheDocument();
});
it('TRIAL user: no card claims "Current"/"Your plan" — a trial is not a purchasable plan', async () => {
const { default: PlanCards } = await import('@/components/os/billing/PlanCards');
render(<PlanCards currentTier="TRIAL" onChoose={vi.fn()} />);
expect(screen.queryByText('Current')).not.toBeInTheDocument();
expect(screen.queryByText('Your plan')).not.toBeInTheDocument();
// Team remains the upgrade path during trial
expect(screen.getByRole('button', { name: /Choose Team/i })).toBeInTheDocument();
});
it('disabled (F8 Stripe-not-configured): upgrade CTAs render "Unavailable" and never fire onChoose', async () => {
const { default: PlanCards } = await import('@/components/os/billing/PlanCards');
const onChoose = vi.fn();
render(<PlanCards currentTier="FREE" onChoose={onChoose} disabled />);
const ctas = screen.getAllByRole('button', { name: /Unavailable/i });
expect(ctas.length).toBeGreaterThanOrEqual(1);
ctas.forEach((b) => expect(b).toBeDisabled());
fireEvent.click(ctas[0]);
expect(onChoose).not.toHaveBeenCalled();
});
});
describe('PR7a · useBilling.startCheckout', () => {
it('threads billingPeriod to adapter.createCheckoutSession (D8)', async () => {
const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null);
const { useBilling } = await import('@/hooks/useBilling');
const { result } = renderHook(() => useBilling());
await waitFor(() => expect(mocks.adapter.getTier).toHaveBeenCalled());
await act(async () => { await result.current.startCheckout('TEAMS', 'annual'); });
expect(mocks.adapter.createCheckoutSession).toHaveBeenCalledWith('TEAMS', 'annual');
expect(openSpy).toHaveBeenCalledWith('https://checkout.stripe.test/abc', '_blank', 'noopener,noreferrer');
openSpy.mockRestore();
});
});
describe('PR7a · SettingsApp ?tab= deep-link (D12)', () => {
it('?tab=billing snaps Settings to the Plan tab', async () => {
mocks.adapter.getTier.mockResolvedValue({ tier: 'FREE', capabilities: {}, usage: {} });
const { default: SettingsApp } = await import('@/components/os/apps/SettingsApp');
const { TooltipProvider } = await import('@/components/ui/tooltip');
render(
<MemoryRouter initialEntries={['/settings?tab=billing']}>
<TooltipProvider><SettingsApp /></TooltipProvider>
</MemoryRouter>,
);
// The Plan tab is selected (the rail tab labelled "Plan")
await waitFor(() => {
expect(screen.getByRole('tab', { name: /plan/i })).toHaveAttribute('aria-selected', 'true');
});
expect(await screen.findByText('Plan & Subscription')).toBeInTheDocument();
});
});
describe('PR7a · PaymentSuccessApp', () => {
it('confirms off the synced tier with NO fabricated receipt (F5)', async () => {
mocks.adapter.getTier.mockResolvedValue({ tier: 'TEAMS', capabilities: {}, usage: {} });
const { default: PaymentSuccessApp } = await import('@/components/os/apps/PaymentSuccessApp');
render(
<MemoryRouter initialEntries={['/payment-success']}>
<PaymentSuccessApp />
</MemoryRouter>,
);
expect(await screen.findByText(/You’re/i)).toBeInTheDocument();
expect(screen.getByText('Team.')).toBeInTheDocument();
// No-fabrication: the mock's receipt rows must NOT appear
expect(screen.queryByText(/Trial ends/i)).not.toBeInTheDocument();
expect(screen.queryByText(/Emailed/i)).not.toBeInTheDocument();
expect(screen.queryByText(/Receipt/i)).not.toBeInTheDocument();
expect(screen.queryByText(/\$49\.00/)).not.toBeInTheDocument();
});
it('sync wins a LATE getTier — a just-paid user is never flashed "Nothing to confirm" (race guard)', async () => {
// useBilling reads window.location for ?session_id= (not the router), so set it.
window.history.replaceState({}, '', '/payment-success?session_id=cs_test');
// getTier resolves FREE *after* the checkout sync resolves TEAMS; the authoritative
// sync result must not be clobbered back to FREE.
let resolveTier: (v: { tier: string; capabilities: object; usage: object }) => void = () => {};
mocks.adapter.getTier.mockReturnValue(new Promise((res) => { resolveTier = res; }));
mocks.adapter.syncStripeCheckout.mockResolvedValue({ tier: 'TEAMS', customerId: 'cus_1' });
const { default: PaymentSuccessApp } = await import('@/components/os/apps/PaymentSuccessApp');
render(
<MemoryRouter initialEntries={['/payment-success?session_id=cs_test']}>
<PaymentSuccessApp />
</MemoryRouter>,
);
// Sync resolves first → paid confirmation
expect(await screen.findByText('Team.')).toBeInTheDocument();
// The late getTier resolves FREE — must NOT flip the screen to "Nothing to confirm"
await act(async () => { resolveTier({ tier: 'FREE', capabilities: {}, usage: {} }); });
expect(screen.getByText('Team.')).toBeInTheDocument();
expect(screen.queryByText(/Nothing to confirm/i)).not.toBeInTheDocument();
});
it('renders legacy PRO checkout state as explicitly legacy', async () => {
mocks.adapter.getTier.mockResolvedValue({ tier: 'PRO', capabilities: {}, usage: {} });
const { default: PaymentSuccessApp } = await import('@/components/os/apps/PaymentSuccessApp');
render(
<MemoryRouter initialEntries={['/payment-success']}>
<PaymentSuccessApp />
</MemoryRouter>,
);
expect(await screen.findByText('Legacy Pro.')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Start using Legacy Pro/i })).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,128 @@
/**
* PR7b — Auth (screen 13): the pre-shell /auth route.
* B1 (no key): the honest accountless local-first state — never a fabricated identity,
* demo email, or a fake SSO button that does nothing (F1/F10).
* B2 (explicitly enabled + key present): the real prebuilt Clerk <SignIn/>/<SignUp/>
* (D13) with a redirect to the fully-local app, the §2b honey local-first note on
* Sign up, our own design-faithful toggle, and the enterprise panel as a sales CTA
* (not a live SAML form — F11/D15).
*/
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
// Mock the Clerk SDK so tests never touch the network or need a real ClerkProvider.
vi.mock('@clerk/themes', () => ({ dark: { __mock: 'dark' } }));
vi.mock('@clerk/clerk-react', () => ({
ClerkProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
SignIn: (p: { forceRedirectUrl?: string }) => (
<div data-testid="clerk-signin" data-redirect={p.forceRedirectUrl} />
),
SignUp: (p: { forceRedirectUrl?: string }) => (
<div data-testid="clerk-signup" data-redirect={p.forceRedirectUrl} />
),
}));
// A well-formed, PUBLIC-safe publishable key (the shared elegant-camel-8 instance key —
// publishable keys ship in the client bundle by design). Used where a VALID key must
// pass the isPublishableKey shape gate; 'pk_test_x' would now (correctly) be rejected.
const VALID_PK = 'pk_test_ZWxlZ2FudC1jYW1lbC04LmNsZXJrLmFjY291bnRzLmRldiQ';
const navigateMock = vi.fn();
vi.mock('react-router-dom', async (orig) => {
const actual = await orig<typeof import('react-router-dom')>();
return { ...actual, useNavigate: () => navigateMock };
});
afterEach(() => { cleanup(); vi.clearAllMocks(); vi.unstubAllEnvs(); });
describe('PR7b · /auth — B1 accountless (no Clerk key)', () => {
beforeEach(() => vi.stubEnv('VITE_CLERK_PUBLISHABLE_KEY', ''));
it('renders the honest local-first state with NO fabricated identity (F1/F10)', async () => {
const { default: AuthRoute } = await import('@/routes/AuthRoute');
render(<MemoryRouter><AuthRoute /></MemoryRouter>);
expect(screen.getByText(/running fully local/i)).toBeInTheDocument();
expect(screen.getByText(/don.t need this to start/i)).toBeInTheDocument();
expect(screen.queryByText(/mara@egzakta/i)).not.toBeInTheDocument();
expect(screen.queryByTestId('clerk-signin')).not.toBeInTheDocument();
expect(screen.queryByText(/signed in/i)).not.toBeInTheDocument();
});
it('brand panel carries the verbatim trust copy (recon 03 §2e)', async () => {
const { default: AuthRoute } = await import('@/routes/AuthRoute');
render(<MemoryRouter><AuthRoute /></MemoryRouter>);
expect(screen.getByText(/An account is optional/i)).toBeInTheDocument();
expect(screen.getByText(/Your memory stays yours/i)).toBeInTheDocument();
});
it('"Continue to Waggle" navigates into the fully-local app (/home)', async () => {
const { default: AuthRoute } = await import('@/routes/AuthRoute');
render(<MemoryRouter><AuthRoute /></MemoryRouter>);
fireEvent.click(screen.getByRole('button', { name: /Continue to Waggle/i }));
expect(navigateMock).toHaveBeenCalledWith('/home');
});
});
describe('PR7b · /auth — B2 Clerk form (explicitly enabled + key present)', () => {
beforeEach(() => {
vi.stubEnv('VITE_WAGGLE_ENABLE_CLERK', '1');
vi.stubEnv('VITE_CLERK_PUBLISHABLE_KEY', VALID_PK);
});
it('renders the real prebuilt Clerk <SignIn/> redirecting to /home (no fake SSO/OTP — F10)', async () => {
const { default: AuthRoute } = await import('@/routes/AuthRoute');
render(<MemoryRouter><AuthRoute /></MemoryRouter>);
const signin = screen.getByTestId('clerk-signin');
expect(signin).toBeInTheDocument();
expect(signin).toHaveAttribute('data-redirect', '/home');
expect(screen.queryByText(/mara@egzakta/i)).not.toBeInTheDocument();
});
it('toggles to Sign up (with the honey local-first note) and back', async () => {
const { default: AuthRoute } = await import('@/routes/AuthRoute');
render(<MemoryRouter><AuthRoute /></MemoryRouter>);
expect(screen.getByTestId('clerk-signin')).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /Create an account/i }));
expect(screen.getByTestId('clerk-signup')).toBeInTheDocument();
expect(screen.getByText(/don.t need this to start/i)).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /^Sign in$/i }));
expect(screen.getByTestId('clerk-signin')).toBeInTheDocument();
});
it('enterprise panel is a sales CTA → kvark.ai, NOT a live SAML form (F11/D15)', async () => {
const { default: AuthRoute } = await import('@/routes/AuthRoute');
render(<MemoryRouter><AuthRoute /></MemoryRouter>);
expect(screen.getByRole('link', { name: /Talk to sales/i })).toHaveAttribute('href', 'https://www.kvark.ai');
expect(screen.queryByPlaceholderText(/work email|organization/i)).not.toBeInTheDocument();
});
});
describe('PR7b · clerkPublishableKey() shape gate (CRITICAL: an invalid key must never reach ClerkProvider)', () => {
it('rejects the .env.example placeholder → undefined (stays accountless, never a boot crash)', async () => {
vi.stubEnv('VITE_CLERK_PUBLISHABLE_KEY', 'pk_test_REPLACE_ME');
const { clerkPublishableKey } = await import('@/lib/clerk');
expect(clerkPublishableKey()).toBeUndefined();
});
it('rejects empty and malformed keys → undefined', async () => {
const { clerkPublishableKey } = await import('@/lib/clerk');
vi.stubEnv('VITE_CLERK_PUBLISHABLE_KEY', '');
expect(clerkPublishableKey()).toBeUndefined();
vi.stubEnv('VITE_CLERK_PUBLISHABLE_KEY', 'not-a-key');
expect(clerkPublishableKey()).toBeUndefined();
});
it('ignores a well-formed publishable key unless hosted Clerk auth is explicitly enabled', async () => {
vi.stubEnv('VITE_CLERK_PUBLISHABLE_KEY', VALID_PK);
const { clerkPublishableKey } = await import('@/lib/clerk');
expect(clerkPublishableKey()).toBeUndefined();
});
it('accepts a well-formed publishable key when hosted Clerk auth is explicitly enabled', async () => {
vi.stubEnv('VITE_WAGGLE_ENABLE_CLERK', '1');
vi.stubEnv('VITE_CLERK_PUBLISHABLE_KEY', VALID_PK);
const { clerkPublishableKey } = await import('@/lib/clerk');
expect(clerkPublishableKey()).toBe(VALID_PK);
});
});

View File

@@ -0,0 +1,85 @@
/**
* R20 Lane CL (item 1) — the boot screen carries ZERO lingering animation under
* prefers-reduced-motion.
*
* The two repeating keyframe loops on the boot surface are (a) the logo glow
* `boxShadow` breath (gated in A2) and (b) the active phase-dot `scale` pulse
* (gated here). Both are expressed as ARRAY-valued `animate` props — a keyframe
* sequence. The background radial (`bg-primary/5 blur`) is a static <div>, not a
* motion element, so it needs no gating.
*
* framer-motion is stubbed to plain DOM and surfaces each element's `animate`
* prop as `data-animate`, so the reduced-motion contract is assertable: under
* reduce, no element may carry an array-valued (keyframe-loop) animate.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, cleanup, screen } from '@testing-library/react';
const h = vi.hoisted(() => ({ reduce: false }));
vi.mock('framer-motion', async () => {
const React = await vi.importActual<typeof import('react')>('react');
const DROP = new Set([
'initial', 'animate', 'exit', 'transition', 'variants',
'whileHover', 'whileTap', 'whileFocus', 'whileInView',
'layout', 'layoutId', 'onAnimationComplete', 'custom',
]);
const make = (tag: string) =>
React.forwardRef(function MotionMock(props: Record<string, unknown>, ref: React.Ref<HTMLElement>) {
const passed: Record<string, unknown> = {};
for (const k of Object.keys(props)) if (!DROP.has(k)) passed[k] = props[k];
// Surface `animate` so the reduced-motion keyframe-loop contract is testable.
if (props.animate !== undefined) passed['data-animate'] = JSON.stringify(props.animate);
return React.createElement(tag, { ...passed, ref });
});
const motion = new Proxy({}, { get: (_t, tag: string) => make(tag) });
return {
__esModule: true,
motion,
AnimatePresence: ({ children }: { children: React.ReactNode }) =>
React.createElement(React.Fragment, null, children),
useReducedMotion: () => h.reduce,
};
});
import BootScreen from '@/components/os/BootScreen';
/** Count elements whose `animate` prop contains an array value — i.e. a
* keyframe sequence / lingering loop (glow breath, dot pulse). One-shot
* entrances use single values and are not counted. */
function keyframeLoopCount(container: HTMLElement): number {
let count = 0;
container.querySelectorAll('[data-animate]').forEach((el) => {
try {
const a = JSON.parse(el.getAttribute('data-animate') ?? 'null');
if (a && typeof a === 'object' && Object.values(a).some((v) => Array.isArray(v))) count++;
} catch { /* non-JSON animate — ignore */ }
});
return count;
}
describe('BootScreen — reduced-motion glow/pulse freeze (R20 Lane CL item 1)', () => {
beforeEach(() => { h.reduce = false; vi.useFakeTimers(); });
afterEach(() => { cleanup(); vi.clearAllTimers(); vi.useRealTimers(); });
it('runs keyframe-loop animation (logo glow + active dot pulse) with motion enabled', () => {
const { container } = render(<BootScreen onComplete={vi.fn()} ready />);
// At least the logo glow breath and the active phase-dot scale pulse loop.
expect(keyframeLoopCount(container)).toBeGreaterThanOrEqual(1);
});
it('renders the boot logo with stable intrinsic dimensions', () => {
render(<BootScreen onComplete={vi.fn()} ready />);
const logo = screen.getByAltText('Waggle AI');
expect(logo).toHaveAttribute('width', '80');
expect(logo).toHaveAttribute('height', '80');
});
it('freezes ALL keyframe loops under prefers-reduced-motion — zero lingering animation', () => {
h.reduce = true;
const { container } = render(<BootScreen onComplete={vi.fn()} ready />);
// No element may carry an array-valued (keyframe) animate: the logo glow is
// undefined and every phase dot resolves to an empty {} under reduce.
expect(keyframeLoopCount(container)).toBe(0);
});
});

View File

@@ -0,0 +1,207 @@
/**
* Router arc P1-B (B2) — RouteProposalCard + BlockRenderer route_proposal branch.
* - renders the propose payload (header, selected executor, reason, verbatim
* cost line, egress summary)
* - per-frame remove (×) and "Run without memory" shape the confirm body
* - alternatives select overrides the executor; rejected options are greyed
* with a reason tooltip
* - dispatched state links the external run / says "running in this chat"
* - blocked brief (egress null + briefBlocked) renders run-without-memory only
* - cancel rejects and collapses; revalidation_failed shows reason + re-propose
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, waitFor } from '@testing-library/react';
import type { RouteProposalPayload } from '@/lib/route-proposals';
const mocks = vi.hoisted(() => ({
routeProposals: {
propose: vi.fn(),
confirm: vi.fn(),
reject: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: { routeProposals: mocks.routeProposals } }));
import RouteProposalCard from '@/components/os/apps/chat-blocks/RouteProposalCard';
import { BlockRenderer } from '@/components/os/apps/chat-blocks';
const basePayload: RouteProposalPayload = {
routeDecisionId: 'rd-1',
selected: { id: 'external:codex', displayName: 'Codex CLI', reason: 'best coding fit, available now' },
alternatives: [
{ id: 'external:claude-code', displayName: 'Claude Code' },
{ id: 'persona:coder', displayName: 'Coder' },
],
rejected: [{ id: 'external:hermes', reason: 'not installed' }],
scores: [],
egress: {
destination: 'OpenAI',
items: [
{ frameId: 'f1', date: '2026-07-01', source: 'user_stated', preview: 'Prefers pnpm over npm' },
{ frameId: 'f2', date: '2026-07-02', source: 'tool_verified', preview: 'CI runs on node 20' },
{ frameId: 'f3', date: '2026-07-03', source: 'agent_inferred', preview: 'Repo tests use vitest' },
],
briefChars: 4200,
},
costLine: 'uses your existing Codex allowance',
};
beforeEach(() => {
mocks.routeProposals.confirm.mockResolvedValue({ status: 'dispatched', mode: 'internal' });
mocks.routeProposals.reject.mockResolvedValue(undefined);
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
describe('RouteProposalCard (router arc B2)', () => {
it('renders the proposal payload — header, executor, reason, verbatim cost line, egress summary', () => {
render(<RouteProposalCard proposal={basePayload} />);
expect(screen.getByText('Where should this run?')).toBeInTheDocument();
expect(screen.getByTestId('route-proposal-selected')).toHaveTextContent('Codex CLI');
expect(screen.getByTestId('route-proposal-reason')).toHaveTextContent('best coding fit, available now');
expect(screen.getByTestId('route-proposal-cost-line')).toHaveTextContent('uses your existing Codex allowance');
expect(screen.getByTestId('route-proposal-egress-toggle')).toHaveTextContent(
'Will send 3 workspace memories to OpenAI',
);
});
it('per-item remove (×) drops the frame from the list and the confirm body', async () => {
render(<RouteProposalCard proposal={basePayload} />);
fireEvent.click(screen.getByTestId('route-proposal-egress-toggle'));
expect(screen.getAllByTestId('route-proposal-egress-item')).toHaveLength(3);
fireEvent.click(screen.getByTestId('route-proposal-remove-f2'));
expect(screen.getAllByTestId('route-proposal-egress-item')).toHaveLength(2);
expect(screen.getByTestId('route-proposal-egress-toggle')).toHaveTextContent(
'Will send 2 workspace memories to OpenAI',
);
fireEvent.click(screen.getByTestId('route-proposal-confirm'));
await waitFor(() =>
expect(mocks.routeProposals.confirm).toHaveBeenCalledWith('rd-1', { removeFrameIds: ['f2'] }),
);
});
it('"Run without memory" removes every frame from the confirm body', async () => {
render(<RouteProposalCard proposal={basePayload} />);
fireEvent.click(screen.getByTestId('route-proposal-run-without-memory'));
fireEvent.click(screen.getByTestId('route-proposal-confirm'));
await waitFor(() =>
expect(mocks.routeProposals.confirm).toHaveBeenCalledWith('rd-1', {
removeFrameIds: ['f1', 'f2', 'f3'],
}),
);
});
it('overriding via the alternatives select sends executorId; rejected options are greyed with a reason tooltip', async () => {
render(<RouteProposalCard proposal={basePayload} />);
const select = screen.getByTestId('route-proposal-executor-select');
const rejectedOption = screen.getByRole('option', { name: /external:hermes — unavailable/ }) as HTMLOptionElement;
expect(rejectedOption.disabled).toBe(true);
expect(rejectedOption).toHaveAttribute('title', 'not installed');
fireEvent.change(select, { target: { value: 'persona:coder' } });
fireEvent.click(screen.getByTestId('route-proposal-confirm'));
await waitFor(() =>
expect(mocks.routeProposals.confirm).toHaveBeenCalledWith('rd-1', { executorId: 'persona:coder' }),
);
});
it('keeping the suggested executor sends NO executorId (server default)', async () => {
render(<RouteProposalCard proposal={basePayload} />);
fireEvent.click(screen.getByTestId('route-proposal-confirm'));
await waitFor(() => expect(mocks.routeProposals.confirm).toHaveBeenCalledWith('rd-1', {}));
});
it('dispatched external run renders a /room link with room + run ids', async () => {
mocks.routeProposals.confirm.mockResolvedValue({
status: 'dispatched', mode: 'external', roomId: 'room-9', runId: 'run-3',
});
render(<RouteProposalCard proposal={basePayload} />);
fireEvent.click(screen.getByTestId('route-proposal-confirm'));
const link = await screen.findByTestId('route-proposal-run-link');
expect(link).toHaveAttribute('href', '/room?room=room-9&run=run-3');
});
it('dispatched internal run says "Running in this chat" and fires onDispatched', async () => {
const onDispatched = vi.fn();
render(<RouteProposalCard proposal={basePayload} onDispatched={onDispatched} />);
fireEvent.click(screen.getByTestId('route-proposal-confirm'));
await screen.findByText('Running in this chat');
expect(screen.queryByTestId('route-proposal-run-link')).not.toBeInTheDocument();
expect(onDispatched).toHaveBeenCalledWith({ status: 'dispatched', mode: 'internal' });
});
it('blocked brief (egress null + briefBlocked) renders run-without-memory only', async () => {
const blocked: RouteProposalPayload = {
...basePayload,
egress: null,
briefBlocked: true,
briefBlockedReason: 'injection patterns detected',
};
render(<RouteProposalCard proposal={blocked} />);
expect(screen.getByTestId('route-proposal-blocked')).toHaveTextContent('injection patterns detected');
// No egress list, no per-item remove, no plain Confirm — only run-without-memory.
expect(screen.queryByTestId('route-proposal-egress')).not.toBeInTheDocument();
expect(screen.queryByTestId('route-proposal-confirm')).not.toBeInTheDocument();
fireEvent.click(screen.getByTestId('route-proposal-run-without-memory'));
await waitFor(() => expect(mocks.routeProposals.confirm).toHaveBeenCalledWith('rd-1', {}));
});
it('cancel POSTs reject and collapses the card', async () => {
render(<RouteProposalCard proposal={basePayload} />);
fireEvent.click(screen.getByTestId('route-proposal-cancel'));
await screen.findByText('Routing cancelled');
expect(mocks.routeProposals.reject).toHaveBeenCalledWith('rd-1');
expect(screen.queryByTestId('route-proposal-confirm')).not.toBeInTheDocument();
});
it('revalidation_failed confirm shows the reason and a re-propose button', async () => {
const err = Object.assign(new Error('revalidation_failed'), {
status: 409,
body: { error: 'revalidation_failed', reason: 'Codex CLI was uninstalled' },
});
mocks.routeProposals.confirm.mockRejectedValue(err);
const onRePropose = vi.fn();
render(<RouteProposalCard proposal={basePayload} onRePropose={onRePropose} />);
fireEvent.click(screen.getByTestId('route-proposal-confirm'));
const error = await screen.findByTestId('route-proposal-error');
expect(error).toHaveTextContent('Codex CLI was uninstalled');
fireEvent.click(screen.getByTestId('route-proposal-re-propose'));
expect(onRePropose).toHaveBeenCalledTimes(1);
});
it('no eligible executor (selected null) disables Confirm', () => {
render(<RouteProposalCard proposal={{ ...basePayload, selected: null, egress: null }} />);
expect(screen.getByText('No eligible executor is available right now.')).toBeInTheDocument();
expect(screen.getByTestId('route-proposal-confirm')).toBeDisabled();
});
});
describe('BlockRenderer route_proposal branch', () => {
it('renders a route_proposal content block as a RouteProposalCard', () => {
render(
<BlockRenderer
blocks={[{ type: 'route_proposal', blockId: 'route-rd-1', proposal: basePayload }]}
/>,
);
expect(screen.getByTestId('route-proposal-card')).toBeInTheDocument();
expect(screen.getByText('Where should this run?')).toBeInTheDocument();
});
it('threads onRouteProposalDispatched with the blockId', async () => {
const onDispatched = vi.fn();
render(
<BlockRenderer
blocks={[{ type: 'route_proposal', blockId: 'route-rd-1', proposal: basePayload }]}
onRouteProposalDispatched={onDispatched}
/>,
);
fireEvent.click(screen.getByTestId('route-proposal-confirm'));
await waitFor(() =>
expect(onDispatched).toHaveBeenCalledWith('route-rd-1', { status: 'dispatched', mode: 'internal' }),
);
});
});

View File

@@ -0,0 +1,104 @@
/**
* Router arc P1-B (B2) — adapter.routeProposals.{propose,confirm,reject}
* fetch-mock unit test. Verifies the wire contract against SPEC A4:
* POST /api/route-proposals, /:id/confirm, /:id/reject, and that confirm's
* 409 revalidation body survives on the thrown AdapterHttpError.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { adapter, AdapterHttpError } from '@/lib/adapter';
import type { RouteProposalPayload } from '@/lib/route-proposals';
const payload: RouteProposalPayload = {
routeDecisionId: 'rd-42',
selected: { id: 'external:claude-code', displayName: 'Claude Code', reason: 'best coding fit' },
alternatives: [{ id: 'persona:coder', displayName: 'Coder' }],
rejected: [],
scores: [],
egress: {
destination: 'Anthropic',
items: [{ frameId: 'f1', date: '2026-07-10', source: 'user_stated', preview: 'p' }],
briefChars: 1200,
},
costLine: 'uses your existing Claude Code allowance',
};
const jsonResponse = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
/** The (url, init) of the fetch call that hit a route-proposals path. */
function routeCall(): { url: string; init: RequestInit } {
const call = vi.mocked(global.fetch).mock.calls.find(([u]) => String(u).includes('/api/route-proposals'));
expect(call).toBeDefined();
const [u, init] = call as [RequestInfo | URL, RequestInit];
return { url: String(u), init };
}
beforeEach(() => {
vi.spyOn(global, 'fetch');
});
afterEach(() => {
vi.restoreAllMocks();
});
describe('adapter.routeProposals (router arc B2)', () => {
it('propose POSTs {workspaceId, prompt} to /api/route-proposals and returns the payload', async () => {
vi.mocked(global.fetch).mockResolvedValue(jsonResponse(payload));
const result = await adapter.routeProposals.propose({ workspaceId: 'ws-1', prompt: 'fix the flaky test' });
expect(result).toEqual(payload);
const { url, init } = routeCall();
expect(url.endsWith('/api/route-proposals')).toBe(true);
expect(init.method).toBe('POST');
expect(JSON.parse(String(init.body))).toEqual({ workspaceId: 'ws-1', prompt: 'fix the flaky test' });
});
it('confirm POSTs executorId + removeFrameIds to /api/route-proposals/:id/confirm', async () => {
vi.mocked(global.fetch).mockResolvedValue(
jsonResponse({ status: 'dispatched', mode: 'external', roomId: 'room-1', runId: 'run-1' }),
);
const result = await adapter.routeProposals.confirm('rd-42', {
executorId: 'persona:coder',
removeFrameIds: ['f1'],
});
expect(result).toEqual({ status: 'dispatched', mode: 'external', roomId: 'room-1', runId: 'run-1' });
const { url, init } = routeCall();
expect(url.endsWith('/api/route-proposals/rd-42/confirm')).toBe(true);
expect(init.method).toBe('POST');
expect(JSON.parse(String(init.body))).toEqual({ executorId: 'persona:coder', removeFrameIds: ['f1'] });
});
it('confirm surfaces the 409 revalidation_failed body on the thrown AdapterHttpError', async () => {
vi.mocked(global.fetch).mockResolvedValue(
jsonResponse({ error: 'revalidation_failed', reason: 'tool uninstalled' }, 409),
);
let thrown: unknown;
try {
await adapter.routeProposals.confirm('rd-42');
} catch (err) {
thrown = err;
}
expect(thrown).toBeInstanceOf(AdapterHttpError);
const httpErr = thrown as AdapterHttpError;
expect(httpErr.status).toBe(409);
expect(httpErr.message).toBe('revalidation_failed');
expect((httpErr.body as { reason?: string }).reason).toBe('tool uninstalled');
});
it('reject POSTs to /api/route-proposals/:id/reject', async () => {
vi.mocked(global.fetch).mockResolvedValue(jsonResponse({ status: 'rejected' }));
await adapter.routeProposals.reject('rd-42');
const { url, init } = routeCall();
expect(url.endsWith('/api/route-proposals/rd-42/reject')).toBe(true);
expect(init.method).toBe('POST');
});
it('proposal ids are URI-encoded in the path', async () => {
vi.mocked(global.fetch).mockResolvedValue(jsonResponse({ status: 'rejected' }));
await adapter.routeProposals.reject('rd/odd id');
const { url } = routeCall();
expect(url.endsWith(`/api/route-proposals/${encodeURIComponent('rd/odd id')}/reject`)).toBe(true);
});
});

View File

@@ -0,0 +1,159 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, fireEvent, cleanup, within } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { TooltipProvider } from '@/components/ui/tooltip';
const mocks = vi.hoisted(() => ({
adapter: {
getSettings: vi.fn(),
getPermissions: vi.fn(),
getTeamStatus: vi.fn(),
getTelemetryStatus: vi.fn(),
getTier: vi.fn(),
getServerUrl: vi.fn(),
getProviders: vi.fn(),
getLocalInferenceStatus: vi.fn(),
probeModel: vi.fn(),
probeProvider: vi.fn(),
toggleTelemetry: vi.fn(),
clearTelemetry: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import SettingsApp from '@/components/os/apps/SettingsApp';
function renderSettings(initialEntry = '/settings') {
return render(
<MemoryRouter initialEntries={[initialEntry]}>
<TooltipProvider>
<SettingsApp />
</TooltipProvider>
</MemoryRouter>,
);
}
async function exposeEverything() {
await screen.findByRole('group', { name: /settings detail level/i });
fireEvent.click(screen.getByRole('button', { name: /everything/i }));
}
async function openBackupTab() {
await exposeEverything();
fireEvent.click(await screen.findByRole('tab', { name: /^backup$/i }));
await screen.findByRole('heading', { name: /encrypted backup/i });
}
beforeEach(() => {
vi.clearAllMocks();
window.localStorage.clear();
mocks.adapter.getSettings.mockResolvedValue({});
mocks.adapter.getPermissions.mockResolvedValue({ defaultAutonomy: 'normal', externalGates: [] });
mocks.adapter.getTeamStatus.mockResolvedValue({ connected: false });
mocks.adapter.getTelemetryStatus.mockResolvedValue({ enabled: true, totalEvents: 3 });
mocks.adapter.getTier.mockResolvedValue({ tier: 'FREE', capabilities: {}, usage: {} });
mocks.adapter.getServerUrl.mockReturnValue('http://127.0.0.1:3333');
mocks.adapter.getProviders.mockResolvedValue({ providers: [], search: [], activeSearch: 'duckduckgo' });
mocks.adapter.getLocalInferenceStatus.mockResolvedValue({ servers: [], ollamaInstalled: false, totalLocalModels: 0 });
mocks.adapter.probeModel.mockResolvedValue({ configured: false });
mocks.adapter.probeProvider.mockResolvedValue({ configured: false, valid: false, verified: false });
mocks.adapter.toggleTelemetry.mockResolvedValue({ enabled: false });
mocks.adapter.clearTelemetry.mockResolvedValue({ ok: true });
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
describe('Settings trust flows', () => {
it('labels high-traffic model and privacy controls for assistive tech', async () => {
renderSettings();
const promptShape = await screen.findByRole('combobox', { name: /prompt shape/i });
expect(promptShape).toHaveAttribute('name', 'promptShape');
expect(promptShape).toHaveAttribute('autocomplete', 'off');
const dailyBudget = screen.getByRole('spinbutton', { name: /daily budget/i });
expect(dailyBudget).toHaveAttribute('name', 'dailyBudget');
expect(dailyBudget).toHaveAttribute('autocomplete', 'off');
await exposeEverything();
fireEvent.click(screen.getByRole('tab', { name: /^general$/i }));
expect(await screen.findByRole('button', { name: /disable anonymous telemetry/i })).toBeInTheDocument();
});
it('asks in-app before clearing telemetry events', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(true);
renderSettings();
await exposeEverything();
fireEvent.click(screen.getByRole('tab', { name: /^general$/i }));
await screen.findByText(/3 events collected/i);
fireEvent.click(screen.getByRole('button', { name: /clear telemetry events/i }));
expect(confirmSpy).not.toHaveBeenCalled();
expect(mocks.adapter.clearTelemetry).not.toHaveBeenCalled();
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent(/clear telemetry events/i);
expect(modal).toHaveTextContent(/does not delete your memory/i);
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(mocks.adapter.clearTelemetry).toHaveBeenCalledTimes(1));
await screen.findByText(/0 events collected/i);
await screen.findByText(/telemetry events cleared/i);
});
it('shows backup failures in-app without alerting', async () => {
const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: false,
json: async () => ({ error: 'Vault key missing' }),
} as Response);
renderSettings();
await openBackupTab();
fireEvent.click(screen.getByRole('button', { name: /create backup/i }));
await waitFor(() => expect(fetchMock).toHaveBeenCalledWith('http://127.0.0.1:3333/api/backup', { method: 'POST' }));
expect(alertSpy).not.toHaveBeenCalled();
const alert = await screen.findByRole('alert');
expect(alert).toHaveTextContent(/vault key missing/i);
});
it('asks in-app before restoring a backup and reports success in-app', async () => {
const confirmSpy = vi.spyOn(window, 'confirm').mockReturnValue(false);
const alertSpy = vi.spyOn(window, 'alert').mockImplementation(() => {});
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
ok: true,
json: async () => ({}),
} as Response);
renderSettings();
await openBackupTab();
const file = new File(['backup-data'], 'research.waggle-backup', { type: 'application/octet-stream' });
const input = screen.getByLabelText(/^restore$/i);
fireEvent.change(input, { target: { files: [file] } });
expect(confirmSpy).not.toHaveBeenCalled();
expect(alertSpy).not.toHaveBeenCalled();
expect(fetchMock).not.toHaveBeenCalled();
const modal = await screen.findByTestId('approval-modal');
expect(modal).toHaveTextContent(/restore backup/i);
expect(modal).toHaveTextContent(/research\.waggle-backup/i);
expect(modal).toHaveTextContent(/overwrite current data/i);
fireEvent.click(screen.getByTestId('approval-modal-approve'));
await waitFor(() => expect(fetchMock).toHaveBeenCalledWith(
'http://127.0.0.1:3333/api/restore',
expect.objectContaining({ method: 'POST' }),
));
await screen.findByText(/backup restored successfully/i);
expect(screen.getByRole('status')).toHaveTextContent(/restart the server/i);
});
});

View File

@@ -0,0 +1,24 @@
import "@testing-library/jest-dom";
import { configure } from "@testing-library/react";
// Testing-library's findBy*/waitFor use their OWN async timeout (default 1000ms),
// which vitest's testTimeout does NOT govern. Under heavy parallel jsdom load the
// event loop starves and these DOM-polling queries can exceed 1s. Raising the
// ceiling is pure insurance: a passing query still resolves the instant the
// element appears (zero cost on green runs); only a starved query gets more room
// before throwing. Pairs with vitest.config.ts testTimeout/hookTimeout + retry.
configure({ asyncUtilTimeout: 8000 });
Object.defineProperty(window, "matchMedia", {
writable: true,
value: (query: string) => ({
matches: false,
media: query,
onchange: null,
addListener: () => {},
removeListener: () => {},
addEventListener: () => {},
removeEventListener: () => {},
dispatchEvent: () => {},
}),
});

View File

@@ -0,0 +1,466 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { useState } from 'react';
import { render, screen, fireEvent, cleanup, waitFor, within, act } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { TooltipProvider } from '@/components/ui/tooltip';
import NotificationInbox from '@/components/os/overlays/NotificationInbox';
import CreateWorkspaceDialog from '@/components/os/overlays/CreateWorkspaceDialog';
import WorkspaceSwitcher from '@/components/os/overlays/WorkspaceSwitcher';
import PersonaSwitcher from '@/components/os/overlays/PersonaSwitcher';
import ContextRail from '@/components/os/overlays/ContextRail';
import OnboardingTooltips from '@/components/os/overlays/OnboardingTooltips';
import UpgradeModal from '@/components/os/overlays/UpgradeModal';
import TrialExpiredModal from '@/components/os/overlays/TrialExpiredModal';
import type { Notification, Workspace, WorkspaceTemplate } from '@/lib/types';
const mocks = vi.hoisted(() => ({
adapter: {
getWorkspaceTemplates: vi.fn(),
getConnectors: vi.fn(),
getPersonas: vi.fn(),
getAgentGroups: vi.fn(),
deleteWorkspaceTemplate: vi.fn(),
browseLocal: vi.fn(),
browseLocalMkdir: vi.fn(),
},
fetchContextRailItems: vi.fn(),
useWorkspaces: vi.fn(),
useShell: vi.fn(),
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/lib/context-rail-fetch', () => ({ fetchContextRailItems: mocks.fetchContextRailItems }));
vi.mock('@/hooks/useWorkspaces', () => ({ useWorkspaces: mocks.useWorkspaces }));
vi.mock('@/providers/ShellContext', () => ({ useShell: mocks.useShell }));
const customTemplate: WorkspaceTemplate = {
id: 'custom-retention',
name: 'Retention Sprint',
description: 'Customer retention workspace',
category: 'sales',
persona: 'analyst',
connectors: [],
suggestedCommands: [],
starterMemory: [],
builtIn: false,
};
const switcherWorkspace: Workspace = {
id: 'alpha',
name: 'Alpha Workspace',
group: 'Engineering',
status: 'active',
updatedAt: '2026-07-09T00:00:00Z',
};
function renderWithProviders(ui: React.ReactElement) {
return render(
<MemoryRouter>
<TooltipProvider>
{ui}
</TooltipProvider>
</MemoryRouter>,
);
}
function WorkspaceSwitcherHarness() {
const [open, setOpen] = useState(false);
return (
<>
<button type="button" onClick={() => setOpen(true)}>Open workspace switcher</button>
{open && (
<WorkspaceSwitcher
open
onClose={() => setOpen(false)}
workspaces={[switcherWorkspace]}
activeWorkspaceId="alpha"
onSelect={vi.fn()}
onCreateNew={vi.fn()}
/>
)}
<button type="button">Behind shell control</button>
</>
);
}
describe('Shell overlay contracts', () => {
beforeEach(() => {
mocks.useWorkspaces.mockReturnValue({ workspaces: [] });
mocks.useShell.mockReturnValue({ billingTier: 'FREE' });
mocks.adapter.getWorkspaceTemplates.mockResolvedValue({ templates: [] });
mocks.adapter.getConnectors.mockResolvedValue([]);
mocks.adapter.getPersonas.mockResolvedValue([]);
mocks.adapter.getAgentGroups.mockResolvedValue([]);
mocks.adapter.deleteWorkspaceTemplate.mockResolvedValue(undefined);
mocks.adapter.browseLocal.mockResolvedValue({ entries: [], current: '/' });
mocks.adapter.browseLocalMkdir.mockResolvedValue({ name: 'Drafts', path: '/Drafts', type: 'directory' });
mocks.fetchContextRailItems.mockResolvedValue([]);
localStorage.clear();
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
vi.restoreAllMocks();
});
it('Notification Inbox is a named dismissible dialog with named icon actions', () => {
const onClose = vi.fn();
const onMarkAllRead = vi.fn();
const notifications: Notification[] = [{
id: 'n1',
type: 'message',
title: 'Agent finished',
body: 'Review the draft',
timestamp: new Date().toISOString(),
read: false,
}];
renderWithProviders(
<NotificationInbox
open
onClose={onClose}
notifications={notifications}
onMarkRead={vi.fn()}
onMarkAllRead={onMarkAllRead}
/>,
);
expect(screen.getByRole('dialog', { name: /notifications/i })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /mark all notifications as read/i }));
expect(onMarkAllRead).toHaveBeenCalledTimes(1);
fireEvent.keyDown(screen.getByRole('dialog', { name: /notifications/i }), { key: 'Escape' });
expect(onClose).toHaveBeenCalledTimes(1);
expect(screen.getByRole('button', { name: /close notifications/i })).toBeInTheDocument();
});
it('Create Workspace opens as a named dialog and closes on Escape', async () => {
const onClose = vi.fn();
renderWithProviders(<CreateWorkspaceDialog open onClose={onClose} onCreate={vi.fn()} />);
await waitFor(() => expect(mocks.adapter.getWorkspaceTemplates).toHaveBeenCalled());
const dialog = screen.getByRole('dialog', { name: /create workspace/i });
expect(dialog).toBeInTheDocument();
expect(screen.getByRole('button', { name: /close create workspace/i })).toBeInTheDocument();
fireEvent.keyDown(dialog, { key: 'Escape' });
expect(onClose).toHaveBeenCalledTimes(1);
});
it('Create Workspace asks in-app before deleting a custom template', async () => {
const confirmSpy = vi.spyOn(window, 'confirm');
mocks.adapter.getWorkspaceTemplates.mockResolvedValue({ templates: [customTemplate] });
renderWithProviders(<CreateWorkspaceDialog open onClose={vi.fn()} onCreate={vi.fn()} />);
fireEvent.click(screen.getByRole('button', { name: /start from template/i }));
await screen.findByText('Retention');
fireEvent.click(screen.getByRole('button', { name: /select template retention sprint/i }));
fireEvent.click(screen.getByRole('button', { name: /delete selected template retention sprint/i }));
expect(confirmSpy).not.toHaveBeenCalled();
const confirmDialog = screen.getByRole('dialog', { name: /delete template/i });
expect(confirmDialog).toBeInTheDocument();
expect(within(confirmDialog).getByText(/Retention Sprint/)).toBeInTheDocument();
fireEvent.click(within(confirmDialog).getByRole('button', { name: /delete template/i }));
await waitFor(() => expect(mocks.adapter.deleteWorkspaceTemplate).toHaveBeenCalledWith('custom-retention'));
});
it('Create Workspace prioritizes the primary setup before optional templates', async () => {
renderWithProviders(<CreateWorkspaceDialog open onClose={vi.fn()} onCreate={vi.fn()} />);
await waitFor(() => expect(mocks.adapter.getWorkspaceTemplates).toHaveBeenCalled());
const dialog = screen.getByRole('dialog', { name: /create workspace/i });
const nameInput = within(dialog).getByRole('textbox', { name: /what project or area/i });
const startFromTemplate = within(dialog).getByRole('button', { name: /start from template/i });
expect(nameInput).toBeInTheDocument();
expect(nameInput.compareDocumentPosition(startFromTemplate) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
expect(within(dialog).queryByPlaceholderText(/search templates/i)).not.toBeInTheDocument();
fireEvent.click(startFromTemplate);
expect(within(dialog).getByPlaceholderText(/search templates/i)).toBeInTheDocument();
const chooseAgent = within(dialog).getByRole('button', { name: /choose an agent/i });
expect(chooseAgent).toHaveAttribute('aria-expanded', 'false');
expect(within(dialog).queryByText('Agent (optional)', { exact: true })).not.toBeInTheDocument();
fireEvent.click(chooseAgent);
expect(chooseAgent).toHaveAttribute('aria-expanded', 'true');
expect(within(dialog).getByText('Agent (optional)', { exact: true })).toBeInTheDocument();
});
it('Create Workspace resets optional disclosures after a cancelled attempt', async () => {
const props = { onClose: vi.fn(), onCreate: vi.fn() };
const view = renderWithProviders(<CreateWorkspaceDialog open {...props} />);
await waitFor(() => expect(mocks.adapter.getWorkspaceTemplates).toHaveBeenCalled());
const dialog = screen.getByRole('dialog', { name: /create workspace/i });
const chooseAgent = within(dialog).getByRole('button', { name: /choose an agent/i });
fireEvent.click(chooseAgent);
expect(chooseAgent).toHaveAttribute('aria-expanded', 'true');
view.rerender(<CreateWorkspaceDialog open={false} {...props} />);
view.rerender(<CreateWorkspaceDialog open {...props} />);
const reopened = screen.getByRole('dialog', { name: /create workspace/i });
expect(within(reopened).getByRole('button', { name: /choose an agent/i })).toHaveAttribute('aria-expanded', 'false');
expect(within(reopened).queryByText('Agent (optional)', { exact: true })).not.toBeInTheDocument();
});
it('Create Workspace visible setup fields expose stable form metadata and focus rings', async () => {
renderWithProviders(<CreateWorkspaceDialog open onClose={vi.fn()} onCreate={vi.fn()} />);
await waitFor(() => expect(mocks.adapter.getWorkspaceTemplates).toHaveBeenCalled());
const dialog = screen.getByRole('dialog', { name: /create workspace/i });
const workspaceName = within(dialog).getByRole('textbox', { name: /what project or area/i });
expect(workspaceName).toHaveAttribute('name', 'workspaceName');
expect(workspaceName).toHaveAttribute('autocomplete', 'off');
expect(workspaceName.className).toContain('focus-visible:ring-2');
fireEvent.click(within(dialog).getByRole('button', { name: /local/i }));
const storagePath = within(dialog).getByRole('textbox', { name: /local directory path/i });
expect(storagePath).toHaveAttribute('name', 'workspaceStoragePath');
expect(storagePath).toHaveAttribute('autocomplete', 'off');
expect(storagePath.className).toContain('focus-visible:ring-2');
fireEvent.click(within(dialog).getByRole('button', { name: /start from template/i }));
const templateSearch = within(dialog).getByRole('textbox', { name: /search workspace templates/i });
expect(templateSearch).toHaveAttribute('name', 'workspaceTemplateSearch');
expect(templateSearch).toHaveAttribute('autocomplete', 'off');
expect(templateSearch.className).toContain('focus-visible:ring-2');
});
it('Create Workspace scoped controls avoid broad transition-all animations', async () => {
mocks.adapter.getWorkspaceTemplates.mockResolvedValue({ templates: [customTemplate] });
mocks.adapter.getAgentGroups.mockResolvedValue([{
id: 'group-1',
name: 'Launch Squad',
strategy: 'parallel',
memberCount: 2,
members: [],
}]);
renderWithProviders(<CreateWorkspaceDialog open onClose={vi.fn()} onCreate={vi.fn()} />);
await waitFor(() => expect(mocks.adapter.getWorkspaceTemplates).toHaveBeenCalled());
const dialog = screen.getByRole('dialog', { name: /create workspace/i });
fireEvent.click(within(dialog).getByRole('button', { name: /start from template/i }));
await within(dialog).findByRole('button', { name: /select template retention sprint/i });
fireEvent.click(within(dialog).getByRole('button', { name: /choose an agent/i }));
fireEvent.click(within(dialog).getByRole('button', { name: /^agent group$/i }));
expect(dialog.innerHTML).not.toContain('transition-all');
fireEvent.click(within(dialog).getByRole('button', { name: /new template/i }));
const templateDialog = await screen.findByRole('dialog', { name: /create template/i });
expect(templateDialog.innerHTML).not.toContain('transition-all');
});
it('Create Workspace subdialogs are named and dismissible', async () => {
const onClose = vi.fn();
renderWithProviders(<CreateWorkspaceDialog open onClose={onClose} onCreate={vi.fn()} />);
await waitFor(() => expect(mocks.adapter.getWorkspaceTemplates).toHaveBeenCalled());
const dialog = screen.getByRole('dialog', { name: /create workspace/i });
fireEvent.click(within(dialog).getByRole('button', { name: /local/i }));
fireEvent.click(within(dialog).getByRole('button', { name: /browse local folders/i }));
const folderDialog = await screen.findByRole('dialog', { name: /browse folders/i });
expect(within(folderDialog).getByRole('button', { name: /close folder picker/i })).toBeInTheDocument();
fireEvent.keyDown(folderDialog, { key: 'Escape' });
await waitFor(() => expect(screen.queryByRole('dialog', { name: /browse folders/i })).not.toBeInTheDocument());
expect(onClose).not.toHaveBeenCalled();
fireEvent.click(within(dialog).getByRole('button', { name: /start from template/i }));
fireEvent.click(within(dialog).getByRole('button', { name: /new template/i }));
const templateDialog = await screen.findByRole('dialog', { name: /create template/i });
expect(within(templateDialog).getByRole('button', { name: /close template creator/i })).toBeInTheDocument();
fireEvent.keyDown(templateDialog, { key: 'Escape' });
await waitFor(() => expect(screen.queryByRole('dialog', { name: /create template/i })).not.toBeInTheDocument());
expect(onClose).not.toHaveBeenCalled();
});
it('Create Workspace template textareas are named and visibly focusable', async () => {
renderWithProviders(<CreateWorkspaceDialog open onClose={vi.fn()} onCreate={vi.fn()} />);
await waitFor(() => expect(mocks.adapter.getWorkspaceTemplates).toHaveBeenCalled());
const dialog = screen.getByRole('dialog', { name: /create workspace/i });
fireEvent.click(within(dialog).getByRole('button', { name: /start from template/i }));
fireEvent.click(within(dialog).getByRole('button', { name: /new template/i }));
const templateDialog = await screen.findByRole('dialog', { name: /create template/i });
const description = within(templateDialog).getByRole('textbox', { name: /^description$/i });
const starterMemory = within(templateDialog).getByRole('textbox', { name: /^starter memory$/i });
expect(description).toHaveAttribute('name', 'template-description');
expect(description).toHaveAttribute('autocomplete', 'off');
expect(description.className).toContain('focus-visible:ring-2');
expect(description.className).toContain('focus-visible:ring-[var(--focus-ring)]');
expect(starterMemory).toHaveAttribute('name', 'template-starter-memory');
expect(starterMemory).toHaveAttribute('autocomplete', 'off');
expect(starterMemory.className).toContain('focus-visible:ring-2');
expect(starterMemory.className).toContain('focus-visible:ring-[var(--focus-ring)]');
});
it('Create Workspace template creator and folder picker fields expose stable form metadata', async () => {
renderWithProviders(<CreateWorkspaceDialog open onClose={vi.fn()} onCreate={vi.fn()} />);
await waitFor(() => expect(mocks.adapter.getWorkspaceTemplates).toHaveBeenCalled());
const dialog = screen.getByRole('dialog', { name: /create workspace/i });
fireEvent.click(within(dialog).getByRole('button', { name: /start from template/i }));
fireEvent.click(within(dialog).getByRole('button', { name: /new template/i }));
const templateDialog = await screen.findByRole('dialog', { name: /create template/i });
const aiPrompt = within(templateDialog).getByRole('textbox', { name: /describe workspace template/i });
expect(aiPrompt).toHaveAttribute('name', 'templateAiPrompt');
expect(aiPrompt).toHaveAttribute('autocomplete', 'off');
expect(aiPrompt.className).toContain('focus-visible:ring-2');
const templateName = within(templateDialog).getByRole('textbox', { name: /^template name$/i });
expect(templateName).toHaveAttribute('name', 'templateName');
expect(templateName).toHaveAttribute('autocomplete', 'off');
expect(templateName.className).toContain('focus-visible:ring-2');
fireEvent.keyDown(templateDialog, { key: 'Escape' });
await waitFor(() => expect(screen.queryByRole('dialog', { name: /create template/i })).not.toBeInTheDocument());
fireEvent.click(within(dialog).getByRole('button', { name: /local/i }));
fireEvent.click(within(dialog).getByRole('button', { name: /browse local folders/i }));
const folderDialog = await screen.findByRole('dialog', { name: /browse folders/i });
fireEvent.click(within(folderDialog).getByRole('button', { name: /new folder/i }));
const newFolderName = within(folderDialog).getByRole('textbox', { name: /new folder name/i });
expect(newFolderName).toHaveAttribute('name', 'newFolderName');
expect(newFolderName).toHaveAttribute('autocomplete', 'off');
expect(newFolderName.className).toContain('focus-visible:ring-2');
});
it('Workspace Switcher moves focus in, traps Tab, and restores focus on Escape', async () => {
renderWithProviders(<WorkspaceSwitcherHarness />);
const trigger = screen.getByRole('button', { name: /open workspace switcher/i });
trigger.focus();
fireEvent.click(trigger);
const dialog = await screen.findByRole('dialog', { name: /switch workspace/i });
await waitFor(() => expect(document.activeElement).toBe(dialog));
expect(dialog.innerHTML).not.toContain('transition-all');
const buttons = within(dialog).getAllByRole('button');
const firstButton = buttons[0];
const lastButton = buttons[buttons.length - 1];
lastButton.focus();
fireEvent.keyDown(dialog, { key: 'Tab' });
expect(document.activeElement).toBe(firstButton);
fireEvent.keyDown(dialog, { key: 'Escape' });
await waitFor(() => expect(screen.queryByRole('dialog', { name: /switch workspace/i })).not.toBeInTheDocument());
expect(document.activeElement).toBe(trigger);
});
it('Persona Switcher scoped cards avoid broad transition-all animations', async () => {
mocks.adapter.getPersonas.mockResolvedValue([{
id: 'general-purpose',
name: 'General Purpose',
description: 'General workspace agent',
}]);
mocks.adapter.getAgentGroups.mockResolvedValue([{
id: 'group-1',
name: 'Launch Squad',
description: 'Go-to-market group',
strategy: 'parallel',
members: [{ agentId: 'agent-1' }],
}]);
renderWithProviders(
<PersonaSwitcher
open
onClose={vi.fn()}
currentPersona="general-purpose"
currentGroupId="group-1"
onSelect={vi.fn()}
onSelectGroup={vi.fn()}
/>,
);
const dialog = await screen.findByRole('dialog', { name: /switch agent/i });
const personaCard = await within(dialog).findByRole('button', { name: /general purpose/i });
expect(personaCard.className).not.toContain('transition-all');
expect(personaCard.className).toContain('transition-colors');
fireEvent.click(within(dialog).getByRole('button', { name: /groups/i }));
const groupCard = await within(dialog).findByRole('button', { name: /launch squad/i });
expect(groupCard.className).not.toContain('transition-all');
expect(groupCard.className).toContain('transition-colors');
expect(dialog.innerHTML).not.toContain('transition-all');
});
it('Context Rail is a labelled complementary panel with a named close action', async () => {
const onClose = vi.fn();
mocks.fetchContextRailItems.mockResolvedValue([{
id: 'frame-1',
kind: 'memory',
title: 'Launch checklist',
content: 'Ship the revised onboarding checklist.',
importance: 'important',
}]);
renderWithProviders(
<ContextRail
target={{ type: 'message', id: 'm1', label: 'Launch plan' }}
onClose={onClose}
/>,
);
const panel = await screen.findByRole('complementary', { name: /related context for launch plan/i });
expect(panel).toBeInTheDocument();
fireEvent.click(within(panel).getByRole('button', { name: /close related context/i }));
expect(onClose).toHaveBeenCalledTimes(1);
});
it('Onboarding tooltips expose a named non-modal dialog and dismiss on Escape', () => {
const onDismiss = vi.fn();
renderWithProviders(<OnboardingTooltips onDismiss={onDismiss} />);
const dialog = screen.getByRole('dialog', { name: /waggle tips/i });
expect(dialog).toHaveAttribute('aria-modal', 'false');
fireEvent.keyDown(window, { key: 'Escape' });
expect(onDismiss).toHaveBeenCalledTimes(1);
expect(localStorage.getItem('waggle:tooltips_done')).toBe('true');
});
it('Tier interruption modals have named close controls', async () => {
renderWithProviders(<UpgradeModal />);
act(() => {
window.dispatchEvent(new CustomEvent('waggle:tier-insufficient', {
detail: {
required: 'TEAMS',
actual: 'FREE',
message: 'Team workspaces require a Team plan.',
},
}));
});
const upgradeDialog = await screen.findByRole('dialog', { name: /upgrade to unlock/i });
expect(within(upgradeDialog).getByRole('button', { name: /close upgrade dialog/i })).toBeInTheDocument();
cleanup();
renderWithProviders(
<TrialExpiredModal open onDismiss={vi.fn()} onUpgrade={vi.fn()} />,
);
const trialDialog = screen.getByRole('dialog', { name: /trial has ended/i });
expect(within(trialDialog).getByRole('button', { name: /close trial expired dialog/i })).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,66 @@
/**
* F8 — Sidebar active-state predicate.
*
* The Chat spine item resolves active via `activeWhen` (only /workspaces/:id/chat),
* NOT a static '/workspaces' prefix that wrongly lit Chat on Overview and every
* other workspace tab. Home stays prefix-matched.
*/
import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { Home, MessageSquare, Brain } from 'lucide-react';
import Sidebar, { type SidebarNavItem } from '@/components/os/Sidebar';
afterEach(cleanup);
const spine: SidebarNavItem[] = [
{ key: 'home', label: 'Home', icon: Home, to: '/home', match: ['/home'] },
{
key: 'chat', label: 'Chat', icon: MessageSquare, to: '/workspaces/ws-1/chat',
match: [], activeWhen: (p: string) => /^\/workspaces\/[^/]+\/chat(\/|$)/.test(p),
},
{ key: 'memory', label: 'Memory', icon: Brain, to: '/memory', match: ['/memory'] },
];
function renderAt(pathname: string) {
return render(
<MemoryRouter initialEntries={[pathname]}>
<Sidebar
workspaceName="Acme"
spine={spine}
onOpenWorkspaceSwitcher={() => {}}
onOpenCommand={() => {}}
onSpawnAgent={() => {}}
userName="Marko"
tierLabel="Solo"
/>
</MemoryRouter>,
);
}
const isActive = (testId: string) =>
screen.getByTestId(testId).getAttribute('aria-current') === 'page';
describe('Sidebar active state (F8)', () => {
it('Chat is active on the chat tab', () => {
renderAt('/workspaces/ws-1/chat');
expect(isActive('nav-chat')).toBe(true);
expect(isActive('nav-memory')).toBe(false);
});
it('Chat is NOT active on the workspace Overview (bare /workspaces/:id)', () => {
renderAt('/workspaces/ws-1');
expect(isActive('nav-chat')).toBe(false);
});
it('Chat is NOT active on another workspace tab (memory)', () => {
renderAt('/workspaces/ws-1/memory');
expect(isActive('nav-chat')).toBe(false);
});
it('Home is active on /home via prefix match', () => {
renderAt('/home');
expect(isActive('nav-home')).toBe(true);
expect(isActive('nav-chat')).toBe(false);
});
});

View File

@@ -0,0 +1,44 @@
/**
* #15 skill requirement badges: the amber "setup needed" badge renders only
* when a skill's declared requirements are unsatisfied, with a tooltip
* listing every missing item. Badge-only v1 — the skill stays active, so the
* badge must never appear for satisfied or requirement-free skills.
*/
import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/react';
import SkillRow from '@/components/os/apps/skills/SkillRow';
import type { Skill } from '@/lib/types';
afterEach(cleanup);
const base: Skill = { name: 'video-helper', status: 'installed' };
const renderRow = (skill: Skill) =>
render(<ul><SkillRow skill={skill} onTest={() => {}} onEdit={() => {}} /></ul>);
describe('SkillRow "setup needed" badge (#15)', () => {
it('shows the badge with a tooltip listing missing env + bins', () => {
renderRow({
...base,
requirements: { satisfied: false, missingEnv: ['OPENAI_API_KEY'], missingBins: ['ffmpeg'] },
});
const badge = screen.getByText('setup needed');
expect(badge).toBeInTheDocument();
expect(badge.closest('[title]')).toHaveAttribute(
'title',
'Missing: OPENAI_API_KEY (env), ffmpeg (binary)',
);
});
it('shows NO badge when requirements are satisfied', () => {
renderRow({ ...base, requirements: { satisfied: true, missingEnv: [], missingBins: [] } });
expect(screen.queryByText('setup needed')).toBeNull();
});
it('shows NO badge when the skill declares no requirements (null/absent)', () => {
renderRow({ ...base, requirements: null });
expect(screen.queryByText('setup needed')).toBeNull();
cleanup();
renderRow(base);
expect(screen.queryByText('setup needed')).toBeNull();
});
});

View File

@@ -0,0 +1,58 @@
/**
* §D2 skill-audit: the "verified" badge renders on a skill row only when the
* audit loop confirmed the skill, with confidence shown as a percentage. Skill
* audit is a free (Solo) feature, so the badge's presence must track the
* verified flag exactly (never shown on an unverified skill).
*/
import { describe, it, expect, afterEach, vi } from 'vitest';
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
import SkillRow from '@/components/os/apps/skills/SkillRow';
import type { Skill } from '@/lib/types';
afterEach(cleanup);
const base: Skill = { name: 'deploy-helper', status: 'installed' };
const renderRow = (skill: Skill, props: Partial<{ onVerify: (s: Skill) => void; verifying: boolean }> = {}) =>
render(<ul><SkillRow skill={skill} onTest={() => {}} onEdit={() => {}} {...props} /></ul>);
describe('SkillRow verified badge (§D2)', () => {
it('shows "verified · NN%" when the skill is verified with confidence', () => {
renderRow({ ...base, verified: true, confidence: 0.88 });
expect(screen.getByText('verified · 88%')).toBeInTheDocument();
});
it('shows a bare "verified" badge when confidence is absent', () => {
renderRow({ ...base, verified: true });
expect(screen.getByText('verified')).toBeInTheDocument();
});
it('shows NO verified badge for an unverified skill', () => {
renderRow({ ...base, verified: false, confidence: 0.2 });
expect(screen.queryByText(/verified/)).toBeNull();
});
it('shows NO verified badge when the audit field is absent (legacy skill)', () => {
renderRow(base);
expect(screen.queryByText(/verified/)).toBeNull();
});
});
describe('SkillRow Verify trigger (§D2)', () => {
it('renders a Verify button and calls onVerify when provided', () => {
const onVerify = vi.fn();
renderRow(base, { onVerify });
const btn = screen.getByLabelText(/Verify skill deploy-helper/);
fireEvent.click(btn);
expect(onVerify).toHaveBeenCalledWith(base);
});
it('renders NO Verify button when onVerify is not provided', () => {
renderRow(base);
expect(screen.queryByLabelText(/Verify skill/)).toBeNull();
});
it('disables the Verify button while verifying', () => {
renderRow(base, { onVerify: () => {}, verifying: true });
expect(screen.getByLabelText(/Verify skill deploy-helper/)).toBeDisabled();
});
});

View File

@@ -0,0 +1,65 @@
/**
* surface-cache (Pillar 2.6) — the typed, keyed, session-scoped cache that backs
* the Marketplace + Agents route-cache. The distinguishing contract vs. a plain
* Map is `hasResolved`: "never fetched" and "fetched, genuinely empty" must be
* separable so a return to an empty surface resolves without a skeleton flash.
*/
import { describe, it, expect } from 'vitest';
import { createSurfaceCache, surfaceCacheKey } from '@/lib/surface-cache';
describe('surface-cache', () => {
it('read returns undefined before a write and the exact value after', () => {
const cache = createSurfaceCache<number[]>();
expect(cache.read('k')).toBeUndefined();
const value = [1, 2, 3];
cache.write('k', value);
expect(cache.read('k')).toBe(value); // identity preserved (seeds React state directly)
});
it('hasResolved distinguishes never-fetched from fetched-then-empty', () => {
const cache = createSurfaceCache<string[]>();
// Never fetched → not resolved (a mount here must skeleton).
expect(cache.hasResolved('k')).toBe(false);
// Resolved to a genuinely-empty payload → resolved (a mount here must show
// the empty-state, not a skeleton).
cache.write('k', []);
expect(cache.hasResolved('k')).toBe(true);
expect(cache.read('k')).toEqual([]);
});
it('keys are independent — a write to one leaves the other untouched', () => {
const cache = createSurfaceCache<number>();
cache.write('a', 1);
expect(cache.read('a')).toBe(1);
expect(cache.read('b')).toBeUndefined();
expect(cache.hasResolved('b')).toBe(false);
});
it('resetForTests drops both the values and the resolved marks', () => {
const cache = createSurfaceCache<number[]>();
cache.write('k', [9]);
cache.resetForTests();
expect(cache.read('k')).toBeUndefined();
expect(cache.hasResolved('k')).toBe(false);
});
it('separate instances do not share state (one cache per surface)', () => {
const a = createSurfaceCache<number>();
const b = createSurfaceCache<number>();
a.write('k', 1);
expect(b.read('k')).toBeUndefined();
});
});
describe('surfaceCacheKey', () => {
it('joins parts stably and maps undefined to an empty segment', () => {
expect(surfaceCacheKey(['skill', ''])).toBe('skill|');
expect(surfaceCacheKey(['skill', undefined])).toBe('skill|');
expect(surfaceCacheKey(['all', 'note', 3, true])).toBe('all|note|3|true');
});
it('distinct dimension tuples produce distinct keys', () => {
expect(surfaceCacheKey(['skill', 'q'])).not.toBe(surfaceCacheKey(['connector', 'q']));
expect(surfaceCacheKey(['all', ''])).not.toBe(surfaceCacheKey(['all', 'q']));
});
});

View File

@@ -0,0 +1,132 @@
/**
* Lane D (Wave V) — signature theme crossfade ("sunset over the hive").
*
* Two guarantees:
* 1. CSS: the `.theme-transition` rule is motion-safe gated
* (`prefers-reduced-motion: no-preference`) and animates COLOR properties
* only — never a layout property (width/inset/transform), so the swap can
* never reflow.
* 2. ThemeProvider stamps `.theme-transition` on <html> for a REAL swap, skips
* it on the initial apply (no crossfade on load), and honours reduced motion.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
import { ThemeProvider, useTheme, applyStoredThemeEarly } from '@/providers/ThemeProvider';
// ── 1. CSS shape (static, browser-free) ──────────────────────────────────────
const css = readFileSync(path.resolve(__dirname, '../index.css'), 'utf-8');
/** Body of the first `selector { ... }` rule (flat blocks — no nesting). */
function rule(selector: string): string {
const start = css.indexOf(selector);
if (start === -1) throw new Error(`selector not found: ${selector}`);
const open = css.indexOf('{', start);
const close = css.indexOf('}', open);
return css.slice(open + 1, close);
}
describe('theme crossfade — CSS shape', () => {
const body = rule('html.theme-transition');
it('lives inside a prefers-reduced-motion: no-preference block', () => {
const guardIdx = css.lastIndexOf('prefers-reduced-motion: no-preference', css.indexOf('html.theme-transition'));
expect(guardIdx).toBeGreaterThan(-1);
});
it('animates color-family properties only', () => {
for (const prop of ['background-color', 'border-color', 'color', 'fill', 'stroke']) {
expect(body).toContain(prop);
}
});
it('never animates a layout property (no reflow)', () => {
for (const layout of ['width', 'height', 'transform', 'inset', 'top:', 'left:', 'margin', 'padding']) {
expect(body).not.toContain(layout);
}
});
it('drives its duration from the --mo-slow motion token (one source of truth with ThemeProvider)', () => {
// R3 motion sweep: the crossfade window is no longer a bespoke literal — it
// resolves to var(--mo-slow), the SAME token ThemeProvider's JS cleanup timer
// reads via DUR.slow, so the CSS and JS can never drift.
expect(body).toMatch(/transition-duration:\s*var\(--mo-slow\)/);
// …and that token sits in the intended 300-400ms band.
const tok = css.match(/--mo-slow:\s*(\d+)ms/);
expect(tok).not.toBeNull();
const ms = Number(tok![1]);
expect(ms).toBeGreaterThanOrEqual(300);
expect(ms).toBeLessThanOrEqual(400);
});
});
// ── 2. ThemeProvider stamping behaviour ──────────────────────────────────────
function ToggleProbe() {
const { toggleTheme } = useTheme();
return <button onClick={toggleTheme}>toggle</button>;
}
const realMatchMedia = window.matchMedia;
beforeEach(() => {
localStorage.clear();
document.documentElement.className = '';
document.documentElement.removeAttribute('data-theme');
window.matchMedia = realMatchMedia; // default mock (matches:false everywhere)
});
afterEach(() => {
cleanup();
window.matchMedia = realMatchMedia;
});
describe('theme crossfade — ThemeProvider', () => {
it('does NOT stamp .theme-transition on the initial apply (no crossfade on load)', () => {
localStorage.setItem('waggle-theme', 'dark');
applyStoredThemeEarly(); // mirrors main.tsx pre-paint apply
render(
<ThemeProvider>
<ToggleProbe />
</ThemeProvider>,
);
expect(document.documentElement.classList.contains('theme-transition')).toBe(false);
});
it('stamps .theme-transition on a real toggle (motion allowed)', () => {
localStorage.setItem('waggle-theme', 'dark');
applyStoredThemeEarly();
render(
<ThemeProvider>
<ToggleProbe />
</ThemeProvider>,
);
fireEvent.click(screen.getByText('toggle'));
expect(document.documentElement.getAttribute('data-theme')).toBe('light');
expect(document.documentElement.classList.contains('theme-transition')).toBe(true);
});
it('keeps the instant swap under reduced motion (no class stamped)', () => {
window.matchMedia = ((query: string) => ({
matches: query.includes('prefers-reduced-motion'),
media: query,
onchange: null,
addListener: () => {},
removeListener: () => {},
addEventListener: () => {},
removeEventListener: () => {},
dispatchEvent: () => false,
})) as unknown as typeof window.matchMedia;
localStorage.setItem('waggle-theme', 'dark');
applyStoredThemeEarly();
render(
<ThemeProvider>
<ToggleProbe />
</ThemeProvider>,
);
fireEvent.click(screen.getByText('toggle'));
expect(document.documentElement.getAttribute('data-theme')).toBe('light');
expect(document.documentElement.classList.contains('theme-transition')).toBe(false);
});
});

View File

@@ -0,0 +1,41 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup } from '@testing-library/react';
import TimelineApp from '@/components/os/apps/TimelineApp';
import type { TimelineEvent } from '@/lib/types';
const mocks = vi.hoisted(() => ({
adapter: {
getTimeline: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
const event = (id: number, eventType: string): TimelineEvent => ({
id,
eventType,
timestamp: '2026-07-09T00:00:00Z',
});
beforeEach(() => {
vi.clearAllMocks();
mocks.adapter.getTimeline.mockResolvedValue([
event(1, 'memory_write'),
event(2, 'tool_call'),
]);
});
afterEach(cleanup);
describe('TimelineApp', () => {
it('labels the event-type filter and gives it a visible token focus ring', async () => {
render(<TimelineApp workspaceId="w1" workspaceName="Alpha" />);
const filter = await screen.findByRole('combobox', { name: /filter timeline by event type/i });
expect(filter).toHaveAttribute('name', 'timeline-event-type');
expect(filter).toHaveAttribute('autocomplete', 'off');
expect(filter.className).toContain('focus-visible:ring-2');
expect(filter.className).toContain('focus-visible:ring-[var(--focus-ring)]');
});
});

View File

@@ -0,0 +1,64 @@
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts';
const options = () => ({
onOpenApp: vi.fn(),
onToggleGlobalSearch: vi.fn(),
onTogglePersonaSwitcher: vi.fn(),
onToggleWorkspaceSwitcher: vi.fn(),
onToggleKeyboardHelp: vi.fn(),
onNewChatWindow: vi.fn(),
});
function Harness({ callbacks }: { callbacks: ReturnType<typeof options> }) {
useKeyboardShortcuts(callbacks);
return <input aria-label="Quick capture" />;
}
afterEach(() => cleanup());
describe('useKeyboardShortcuts', () => {
it('keeps Ctrl+Shift+N available when a text input is focused', () => {
const callbacks = options();
render(<Harness callbacks={callbacks} />);
screen.getByRole('textbox', { name: 'Quick capture' }).focus();
fireEvent.keyDown(window, { key: 'N', code: 'KeyN', ctrlKey: true, shiftKey: true });
expect(callbacks.onNewChatWindow).toHaveBeenCalledTimes(1);
});
// Pillar 2.7 — "open last workspace" ≤2-keystroke power path.
it('opens the last/active workspace desktop on Ctrl+Shift+O, even from an input', () => {
const callbacks = options();
render(<Harness callbacks={callbacks} />);
// Global (survives input focus) like new-chat.
screen.getByRole('textbox', { name: 'Quick capture' }).focus();
fireEvent.keyDown(window, { key: 'O', code: 'KeyO', ctrlKey: true, shiftKey: true });
expect(callbacks.onOpenApp).toHaveBeenCalledTimes(1);
expect(callbacks.onOpenApp).toHaveBeenCalledWith('workspace-desktop');
});
// Pillar 2.7 — the conventional "press ? for help" discoverability path.
it('opens the shortcut cheat sheet on a bare "?" when no input is focused', () => {
const callbacks = options();
render(<Harness callbacks={callbacks} />);
fireEvent.keyDown(window, { key: '?' });
expect(callbacks.onToggleKeyboardHelp).toHaveBeenCalledTimes(1);
});
it('never hijacks a literal "?" typed into an input', () => {
const callbacks = options();
render(<Harness callbacks={callbacks} />);
screen.getByRole('textbox', { name: 'Quick capture' }).focus();
fireEvent.keyDown(window, { key: '?' });
expect(callbacks.onToggleKeyboardHelp).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,159 @@
/**
* PR3 Phase 0 — warm-Hive shared primitives render smoke.
*
* Locks the foundation atoms in `components/os/warm/` so a broken import,
* token typo, or runtime error surfaces before the three screens consume them.
* Behavioural atoms (AskBar submit, ActivityStream toggle, InlineApprovalCard
* Always-allow gating) get a real assertion; the rest assert mount + content.
*/
import { describe, it, expect, afterEach } from 'vitest';
import { render, screen, cleanup, fireEvent } from '@testing-library/react';
import { Sparkles } from 'lucide-react';
import {
HexAvatar,
SectionLabel,
DotLive,
ProvenanceLine,
RunChip,
IconTile,
HexCheckTile,
StreakChip,
ModelPill,
OvernightHero,
AskBar,
ActivityStream,
InlineApprovalCard,
ConfidenceRing,
confidenceColor,
} from '@/components/os/warm';
import type { ApprovalRequest } from '@/components/ui/approval-modal';
afterEach(cleanup);
describe('warm primitives — render smoke', () => {
it('HexAvatar shows the derived initial', () => {
render(<HexAvatar label="Competitive Intelligence" />);
expect(screen.getByText('C')).toBeInTheDocument();
});
it('SectionLabel renders its text', () => {
render(<SectionLabel rule>What Waggle knows</SectionLabel>);
expect(screen.getByText('What Waggle knows')).toBeInTheDocument();
});
it('StreakChip renders an N-day streak', () => {
render(<StreakChip days={12} />);
expect(screen.getByText('12-day streak')).toBeInTheDocument();
});
it('ProvenanceLine renders the ⬡ source · when label', () => {
render(<ProvenanceLine source="web · mem0.ai" when="2h ago" />);
expect(screen.getByText('⬡ web · mem0.ai · 2h ago')).toBeInTheDocument();
});
it('RunChip renders its label', () => {
render(<RunChip label="14 memories consolidated" tone="intel" />);
expect(screen.getByText('14 memories consolidated')).toBeInTheDocument();
});
it('ConfidenceRing renders NN% + CONF caption, and a labeled "unscored" badge when unknown', () => {
const { rerender } = render(<ConfidenceRing value={94} />);
expect(screen.getByText('94%')).toBeInTheDocument();
expect(screen.getByText('conf')).toBeInTheDocument();
// Unknown confidence (harvest-only signal absent) → a quiet labeled badge,
// never an empty dial with a dash and never a fabricated number (Wave F 3a).
rerender(<ConfidenceRing value={undefined} />);
expect(screen.getByText('unscored')).toBeInTheDocument();
expect(screen.queryByText('—')).not.toBeInTheDocument();
});
it('confidenceColor maps bands ≥85 healthy / ≥60 attention / <60 risk', () => {
expect(confidenceColor(94)).toBe('var(--healthy)');
expect(confidenceColor(85)).toBe('var(--healthy)');
expect(confidenceColor(61)).toBe('var(--attention)');
expect(confidenceColor(60)).toBe('var(--attention)');
expect(confidenceColor(47)).toBe('var(--risk)');
});
it('ModelPill renders mode · model', () => {
render(<ModelPill mode="auto" model="Claude Sonnet" />);
expect(screen.getByText('Claude Sonnet')).toBeInTheDocument();
expect(screen.getByText(/auto/)).toBeInTheDocument();
});
it('OvernightHero always renders the statement; the chip row only when runs exist', () => {
const { rerender } = render(
<OvernightHero statement={<>Folded 14 memories</>} runs={[{ label: '14 consolidated' }]} />,
);
expect(screen.getByText('Folded 14 memories')).toBeInTheDocument();
expect(screen.getByText('14 consolidated')).toBeInTheDocument();
// H2: single-clause stories pass no chips (a lone chip would repeat the
// sentence) — the statement must still render; the caller owns the
// empty-night fallback line.
rerender(<OvernightHero statement={<>A calm night</>} runs={[]} />);
expect(screen.getByText('A calm night')).toBeInTheDocument();
expect(screen.queryByText('14 consolidated')).not.toBeInTheDocument();
});
it('AskBar submits trimmed text and clears the input', () => {
let sent = '';
render(<AskBar onSubmit={(t) => (sent = t)} />);
const input = screen.getByLabelText('Ask Waggle') as HTMLInputElement;
expect(input).toHaveAttribute('name', 'ask-waggle');
expect(input).toHaveAttribute('autocomplete', 'off');
expect(input.className).toContain('focus-visible:ring-2');
expect(input.className).toContain('focus-visible:ring-[var(--focus-ring)]');
fireEvent.change(input, { target: { value: ' draft the board update ' } });
fireEvent.keyDown(input, { key: 'Enter' });
expect(sent).toBe('draft the board update');
expect(input.value).toBe('');
});
it('ActivityStream is collapsed by default and reveals steps on click', () => {
render(
<ActivityStream
summary="Worked across memory, web & files"
durationMs={38000}
steps={[{ text: 'Recalled 6 frames', provenance: { source: 'mem://hive' } }]}
/>,
);
expect(screen.getByText(/Worked across memory/)).toBeInTheDocument();
expect(screen.queryByText('Recalled 6 frames')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { expanded: false }));
expect(screen.getByText('Recalled 6 frames')).toBeInTheDocument();
});
it('InlineApprovalCard renders the target and gates Always-allow on critical', () => {
const base: ApprovalRequest = {
action: 'Export to Salesforce',
scope: ['Q2 Pricing'],
riskLevel: 'high',
};
const { rerender } = render(
<InlineApprovalCard request={base} onApprove={() => {}} onDecline={() => {}} onAlwaysAllow={() => {}} />,
);
expect(screen.getByText('Export to Salesforce › Q2 Pricing')).toBeInTheDocument();
expect(screen.getByText('Always allow')).toBeInTheDocument();
rerender(
<InlineApprovalCard
request={{ ...base, approvalClass: 'critical' }}
onApprove={() => {}}
onDecline={() => {}}
onAlwaysAllow={() => {}}
/>,
);
expect(screen.queryByText('Always allow')).not.toBeInTheDocument();
});
it('IconTile / DotLive / HexCheckTile mount without throwing', () => {
expect(() =>
render(
<>
<IconTile icon={Sparkles} tone="work" />
<DotLive tone="healthy" />
<HexCheckTile tone="healthy" />
</>,
),
).not.toThrow();
});
});

View File

@@ -0,0 +1,92 @@
/**
* Wave T Lane A (item 1) — boot-time onboarding resolution.
*
* The wizard flashed for ~1s for a server-onboarded user whose webview
* localStorage is fresh: /api/onboarding/status only resolved AFTER the shell
* mounted. AppShell now holds the boot screen until the decision is KNOWN using
* these two helpers. isOnboardingStatusKnownSync answers "can we decide without
* the server?"; resolveReturningUserOnboarding persists the completed flag so
* useOnboarding reads it synchronously and never paints the wizard.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
const mocks = vi.hoisted(() => ({
adapter: {
getOnboardingStatus: vi.fn(),
markOnboardingComplete: vi.fn().mockResolvedValue(undefined),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/lib/tauri-bindings', () => ({
isTauri: () => false,
isFirstLaunch: vi.fn().mockResolvedValue(true),
markFirstLaunchComplete: vi.fn().mockResolvedValue(undefined),
}));
const STORAGE_KEY = 'waggle:onboarding';
describe('isOnboardingStatusKnownSync (Wave T item 1)', () => {
beforeEach(() => { localStorage.clear(); window.history.replaceState({}, '', '/'); });
afterEach(() => { vi.clearAllMocks(); });
it('fresh localStorage → NOT known (must ask the server)', async () => {
const { isOnboardingStatusKnownSync } = await import('@/hooks/useOnboarding');
expect(isOnboardingStatusKnownSync()).toBe(false);
});
it('completed in localStorage → known', async () => {
localStorage.setItem(STORAGE_KEY, JSON.stringify({ completed: true, step: 7 }));
const { isOnboardingStatusKnownSync } = await import('@/hooks/useOnboarding');
expect(isOnboardingStatusKnownSync()).toBe(true);
});
it('mid-wizard (step > 0) → known (the server is never consulted mid-wizard)', async () => {
localStorage.setItem(STORAGE_KEY, JSON.stringify({ completed: false, step: 3 }));
const { isOnboardingStatusKnownSync } = await import('@/hooks/useOnboarding');
expect(isOnboardingStatusKnownSync()).toBe(true);
});
it('?skipOnboarding=true (E2E) → known', async () => {
window.history.replaceState({}, '', '/?skipOnboarding=true');
const { isOnboardingStatusKnownSync } = await import('@/hooks/useOnboarding');
expect(isOnboardingStatusKnownSync()).toBe(true);
});
});
describe('resolveReturningUserOnboarding (Wave T item 1)', () => {
beforeEach(() => { localStorage.clear(); window.history.replaceState({}, '', '/'); });
afterEach(() => { vi.clearAllMocks(); });
it('RETURNING USER: server says completed → persists completed=true synchronously', async () => {
mocks.adapter.getOnboardingStatus.mockResolvedValue({ completed: true, source: 'legacy-evidence' });
const { resolveReturningUserOnboarding } = await import('@/hooks/useOnboarding');
await resolveReturningUserOnboarding();
expect(mocks.adapter.getOnboardingStatus).toHaveBeenCalledTimes(1);
const persisted = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}');
expect(persisted.completed).toBe(true);
expect(persisted.step).toBe(7);
});
it('CLEAN INSTALL: server says not completed → does NOT persist completion', async () => {
mocks.adapter.getOnboardingStatus.mockResolvedValue({ completed: false, source: 'none' });
const { resolveReturningUserOnboarding } = await import('@/hooks/useOnboarding');
await resolveReturningUserOnboarding();
const raw = localStorage.getItem(STORAGE_KEY);
expect(raw == null || JSON.parse(raw).completed !== true).toBe(true);
});
it('sidecar unreachable → does NOT persist (fail toward the wizard)', async () => {
mocks.adapter.getOnboardingStatus.mockRejectedValue(new Error('ECONNREFUSED'));
const { resolveReturningUserOnboarding } = await import('@/hooks/useOnboarding');
await resolveReturningUserOnboarding();
const raw = localStorage.getItem(STORAGE_KEY);
expect(raw == null || JSON.parse(raw).completed !== true).toBe(true);
});
it('already known locally (completed) → skips the server probe entirely', async () => {
localStorage.setItem(STORAGE_KEY, JSON.stringify({ completed: true, step: 7 }));
const { resolveReturningUserOnboarding } = await import('@/hooks/useOnboarding');
await resolveReturningUserOnboarding();
expect(mocks.adapter.getOnboardingStatus).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,123 @@
/**
* Wave U Lane D — boot warm-start floor.
*
* The boot screen used a FIXED ~2.3s choreography floor before it called
* onComplete, so returning users sat through dead air even when the shell's
* data was already warm. It now enforces a PERCEPTUAL floor (MIN_BRAND_MS) and
* exits the instant `ready` is true — but holds past the floor while deps are
* genuinely unresolved (ready=false, e.g. onboarding status still probing).
* Manual skip (click / any key) exits at any time. Item 2: the exit stays a
* choreographed fade at the shorter floor, and collapses to an instant swap
* under reduced motion.
*
* framer-motion is stubbed to plain DOM so the timer logic is deterministic
* under fake timers, and so the exit/transition props are assertable.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup, act } from '@testing-library/react';
const h = vi.hoisted(() => ({ reduce: false }));
vi.mock('framer-motion', async () => {
const React = await vi.importActual<typeof import('react')>('react');
const DROP = new Set([
'initial', 'animate', 'exit', 'transition', 'variants',
'whileHover', 'whileTap', 'whileFocus', 'whileInView',
'layout', 'layoutId', 'onAnimationComplete', 'custom',
]);
const make = (tag: string) =>
React.forwardRef(function MotionMock(props: Record<string, unknown>, ref: React.Ref<HTMLElement>) {
const passed: Record<string, unknown> = {};
for (const k of Object.keys(props)) if (!DROP.has(k)) passed[k] = props[k];
// Surface exit/transition so the fade / instant-swap contract is assertable.
if (props.transition !== undefined) passed['data-motion-transition'] = JSON.stringify(props.transition);
if (props.exit !== undefined) passed['data-motion-exit'] = JSON.stringify(props.exit);
return React.createElement(tag, { ...passed, ref });
});
const motion = new Proxy({}, { get: (_t, tag: string) => make(tag) });
return {
__esModule: true,
motion,
AnimatePresence: ({ children }: { children: React.ReactNode }) =>
React.createElement(React.Fragment, null, children),
useReducedMotion: () => h.reduce,
};
});
import BootScreen from '@/components/os/BootScreen';
const BOOT = 'boot-screen';
describe('BootScreen — perceptual warm-start floor (Wave U Lane D)', () => {
beforeEach(() => { h.reduce = false; vi.useFakeTimers(); });
afterEach(() => { cleanup(); vi.clearAllTimers(); vi.useRealTimers(); });
it('does NOT exit before the brand-moment floor even when ready', () => {
const onComplete = vi.fn();
render(<BootScreen onComplete={onComplete} ready />);
act(() => { vi.advanceTimersByTime(700); }); // < MIN_BRAND_MS (850)
expect(onComplete).not.toHaveBeenCalled();
});
it('exits once (and only once) at the floor when deps are ready', () => {
const onComplete = vi.fn();
render(<BootScreen onComplete={onComplete} ready />);
act(() => { vi.advanceTimersByTime(900); }); // > floor
expect(onComplete).toHaveBeenCalledTimes(1);
// Advancing further must not re-fire — the old fixed-floor path chained its
// own exit timer; the ref guard makes every later path a no-op.
act(() => { vi.advanceTimersByTime(3000); });
expect(onComplete).toHaveBeenCalledTimes(1);
});
it('holds past the floor while deps are unresolved (ready=false)', () => {
const onComplete = vi.fn();
render(<BootScreen onComplete={onComplete} ready={false} />);
act(() => { vi.advanceTimersByTime(4000); }); // well past floor + the old ~2.3s ceiling
expect(onComplete).not.toHaveBeenCalled();
});
it('exits promptly once deps resolve after the floor', () => {
const onComplete = vi.fn();
const { rerender } = render(<BootScreen onComplete={onComplete} ready={false} />);
act(() => { vi.advanceTimersByTime(1200); }); // floor elapsed, still not ready
expect(onComplete).not.toHaveBeenCalled();
act(() => { rerender(<BootScreen onComplete={onComplete} ready />); });
expect(onComplete).toHaveBeenCalledTimes(1);
});
it('manual skip (click) exits immediately regardless of readiness', () => {
const onComplete = vi.fn();
render(<BootScreen onComplete={onComplete} ready={false} />);
act(() => { fireEvent.click(screen.getByTestId(BOOT)); });
expect(onComplete).toHaveBeenCalledTimes(1);
});
it('exit stays a choreographed fade at the shorter floor', () => {
render(<BootScreen onComplete={vi.fn()} ready />);
const root = screen.getByTestId(BOOT);
expect(JSON.parse(root.getAttribute('data-motion-exit') ?? '{}')).toMatchObject({ opacity: 0, scale: 1.05 });
expect(JSON.parse(root.getAttribute('data-motion-transition') ?? '{}').duration).toBe(0.5);
});
it('reduced motion → instant swap on exit (no fade, no scale)', () => {
h.reduce = true;
render(<BootScreen onComplete={vi.fn()} ready />);
const root = screen.getByTestId(BOOT);
const exit = JSON.parse(root.getAttribute('data-motion-exit') ?? '{}');
expect(exit).toEqual({ opacity: 0 });
expect(JSON.parse(root.getAttribute('data-motion-transition') ?? '{}').duration).toBe(0);
});
// Lane H item 5 — a warm (cache-first) session exits at the shorter ≤500ms
// brand flash, well before the cold 850ms floor a returning-user boot used to
// sit through with content already waiting behind it.
it('warm session exits at the shorter ≤500ms floor when ready', () => {
const onComplete = vi.fn();
render(<BootScreen onComplete={onComplete} ready warm />);
act(() => { vi.advanceTimersByTime(450); }); // < WARM_BRAND_MS (500)
expect(onComplete).not.toHaveBeenCalled();
act(() => { vi.advanceTimersByTime(100); }); // now past 500 — a cold boot (850) would still be waiting
expect(onComplete).toHaveBeenCalledTimes(1);
});
});

View File

@@ -0,0 +1,67 @@
/**
* Wave U Lane B (item 1) — briefing interruption discipline.
*
* The "Catching you up" briefing must fire ONLY on true session start AND only
* when Home is the landing surface. An in-session navigation to Home (s02:
* Settings→Home) must never re-pop it. AppShell gates the modal on a
* `nextBriefingLanding` state machine fed by the pathname stream; these tests
* pin every transition of that reducer so the discipline holds without mounting
* the shell.
*/
import { describe, it, expect, vi } from 'vitest';
// AppShell pulls the whole shell import graph; nothing runs at module load, but
// mock the two side-effect-capable leaves defensively so the import is inert.
vi.mock('@/lib/adapter', () => ({ adapter: {}, default: vi.fn() }));
vi.mock('@/lib/tauri-bindings', () => ({
isTauri: () => false,
isFirstLaunch: vi.fn().mockResolvedValue(false),
markFirstLaunchComplete: vi.fn().mockResolvedValue(undefined),
}));
import { nextBriefingLanding, type BriefingLanding } from '@/components/os/AppShell';
describe('nextBriefingLanding (Wave U Lane B item 1)', () => {
it('the bare index "/" is transitional — never decides the landing', () => {
expect(nextBriefingLanding('pending', '/')).toBe('pending');
expect(nextBriefingLanding('armed', '/')).toBe('armed');
expect(nextBriefingLanding('spent', '/')).toBe('spent');
});
it('landing on Home arms the briefing', () => {
expect(nextBriefingLanding('pending', '/home')).toBe('armed');
expect(nextBriefingLanding('pending', '/home/anything')).toBe('armed');
});
it('landing on a non-Home surface spends it (deep link)', () => {
expect(nextBriefingLanding('pending', '/settings')).toBe('spent');
expect(nextBriefingLanding('pending', '/workspaces/w1/chat')).toBe('spent');
});
it('staying on Home keeps it armed', () => {
expect(nextBriefingLanding('armed', '/home')).toBe('armed');
});
it('leaving Home spends it — a later return can never re-arm', () => {
expect(nextBriefingLanding('armed', '/settings')).toBe('spent');
// terminal: 'spent' is sticky no matter where the user goes next
expect(nextBriefingLanding('spent', '/home')).toBe('spent');
expect(nextBriefingLanding('spent', '/settings')).toBe('spent');
});
// Replays of the real pathname streams the gate must survive.
const run = (steps: string[]): BriefingLanding =>
steps.reduce<BriefingLanding>(nextBriefingLanding, 'pending');
it('HAPPY PATH: boot "/" → "/home" arms (briefing greets on first landing)', () => {
expect(run(['/', '/home'])).toBe('armed');
});
it('s02: Home landing → Settings → Home never re-arms ("double catch-up" fix)', () => {
expect(run(['/', '/home', '/settings', '/home'])).toBe('spent');
});
it('DEEP LINK: land on Settings first → later Home is spent', () => {
expect(run(['/', '/settings', '/home'])).toBe('spent');
});
});

View File

@@ -0,0 +1,65 @@
/**
* Wave U Lane B (item 2) — numbers reconciliation.
*
* The briefing modal showed a different workspace count than the Home hero it
* overlays ("2 workspaces" vs "6 workspaces waiting"): the hero reads the
* canonical visible count (workspaceCounts().visible — non-archived, non-dev-
* noise) while the modal's brag line read computeBragSummary's own
* summaries.length (a capped, archived-inclusive subset). fetchBriefingData now
* reconciles the modal onto the SAME workspaceCounts().visible, so the two
* surfaces can never state two truths about one store.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
const mocks = vi.hoisted(() => ({
adapter: {
getWorkspaces: vi.fn(),
searchMemory: vi.fn(),
getMemoryStats: vi.fn(),
getWorkspaceContext: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import { fetchBriefingData } from '@/lib/briefing-source';
import { formatBragLine } from '@/lib/login-briefing-brag';
import { workspaceCounts } from '@/lib/workspace-counts';
// 6 real (active, non-noise) + 2 archived + 1 dev-noise name. The hero counts 6;
// the modal's OLD subset was min(5, non-noise) = 5 (archived pass the name filter,
// then .slice(0,5) caps) — the exact "counts disagree" the judges flagged.
const WORKSPACES = [
{ id: 'w1', name: 'Alpha', group: 'Personal', status: 'active' as const },
{ id: 'w2', name: 'Bravo', group: 'Personal', status: 'active' as const },
{ id: 'w3', name: 'Charlie', group: 'Personal', status: 'active' as const },
{ id: 'w4', name: 'Delta', group: 'Personal', status: 'active' as const },
{ id: 'w5', name: 'Echo', group: 'Personal', status: 'active' as const },
{ id: 'w6', name: 'Foxtrot', group: 'Personal', status: 'active' as const },
{ id: 'a1', name: 'ArchivedOne', group: 'Personal', status: 'archived' as const },
{ id: 'a2', name: 'ArchivedTwo', group: 'Personal', status: 'archived' as const },
{ id: 'n1', name: 'test-noise', group: 'Personal', status: 'active' as const },
];
describe('fetchBriefingData numbers reconciliation (Wave U Lane B item 2)', () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.adapter.getWorkspaces.mockResolvedValue(WORKSPACES);
mocks.adapter.searchMemory.mockResolvedValue([]);
// total.frames === 0 → formatBragLine renders the "across N workspaces" clause.
mocks.adapter.getMemoryStats.mockResolvedValue({ total: { frames: 0, entities: 0, relations: 0 } });
mocks.adapter.getWorkspaceContext.mockResolvedValue({ memoryCount: 0, sessionCount: 0 });
});
it('brag.workspaceCount equals Home’s canonical visible count (not the capped subset)', async () => {
const data = await fetchBriefingData();
const heroCount = workspaceCounts(WORKSPACES).visible;
expect(heroCount).toBe(6); // hero: 6 real, archived + noise excluded
expect(data.brag.workspaceCount).toBe(heroCount); // modal now agrees
expect(data.brag.workspaceCount).not.toBe(5); // the old capped/archived-inclusive subset
});
it('the rendered brag line states the SAME count the hero shows', async () => {
const data = await fetchBriefingData();
expect(formatBragLine(data.brag)).toContain('across 6 workspaces');
});
});

View File

@@ -0,0 +1,130 @@
/**
* Wave U Lane F — chat action-row presence + send pulse.
* fix 1: the message action row reads as a toolbar — rests at opacity-75 on a
* subtle --surface-2 pill with 16px icons (keeps the 150ms reveal +
* focus-within parity from Wave T).
* fix 2: the send button gets a one-shot, motion-safe scale pop on the
* empty→ready transition (fires once, never on mount / re-render).
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render as rtlRender, screen, fireEvent, cleanup } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { ComponentProps } from 'react';
// jsdom lacks ResizeObserver (ChatApp's agent strip observes its own width).
class ResizeObserverStub {
observe() {}
unobserve() {}
disconnect() {}
}
(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = ResizeObserverStub;
const mocks = vi.hoisted(() => ({
adapter: {
getPins: vi.fn().mockResolvedValue([]),
searchMemory: vi.fn().mockResolvedValue([]),
submitFeedback: vi.fn(),
ingestFile: vi.fn(),
addPin: vi.fn(),
removePin: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: {} }));
import ChatApp from '@/components/os/apps/ChatApp';
import type { ChatMessage } from '@/lib/types';
const noop = () => {};
const baseProps = {
messages: [] as ChatMessage[],
isLoading: false,
onSendMessage: noop,
onClearHistory: noop,
pendingApproval: null,
onApprove: noop,
};
const assistantMsg: ChatMessage = {
id: 'm1',
role: 'assistant',
content: 'Here is your answer.',
timestamp: new Date().toISOString(),
};
type ChatAppRenderProps = Partial<ComponentProps<typeof ChatApp>> & { messages: ChatMessage[] };
const render = (props: ChatAppRenderProps) =>
rtlRender(
<TooltipProvider>
<ChatApp {...baseProps} {...props} />
</TooltipProvider>,
);
afterEach(() => cleanup());
describe('Wave U Lane F fix 1 — message action row presence', () => {
it('keeps the empty-state mascot intrinsically sized before image decode', () => {
render({ messages: [] });
const emptyState = screen.getByText("Pick a workspace and Waggle's ready").closest('div');
const mascot = emptyState?.querySelector('img[aria-hidden="true"]');
expect(mascot).toHaveAttribute('width', '56');
expect(mascot).toHaveAttribute('height', '56');
});
it('scopes the chat history sidebar animation to width only', () => {
render({
messages: [assistantMsg],
sessions: [{ id: 's1', title: 'Earlier research', messageCount: 3 }],
activeSessionId: 's1',
onSelectSession: noop,
onNewSession: noop,
});
const sidebar = screen.getByTestId('chat-session-sidebar');
expect(sidebar.className).not.toContain('transition-all');
expect(sidebar.className).toContain('transition-[width]');
});
it('rests at opacity-75 on a --surface-2 toolbar pill (keeps the reveal + focus-within parity)', () => {
render({ messages: [assistantMsg] });
const row = screen.getByTestId('chat-action-row');
expect(row.className).toContain('opacity-75');
expect(row.className).toContain('bg-[var(--surface-2)]');
expect(row.className).toContain('rounded-full');
// The Wave T reveal + keyboard parity survive unchanged.
expect(row.className).toContain('group-hover/turn:opacity-100');
expect(row.className).toContain('group-focus-within/turn:opacity-100');
// R3 motion sweep: the raw 150ms reveal now resolves to the --mo-fast token
// (still 150ms) — the reveal timing is unchanged, only the source moved.
expect(row.className).toContain('duration-mo-fast');
expect(row.className).toContain('motion-reduce:translate-y-0');
});
it('renders the action icons at 16px (w-4 h-4)', () => {
render({ messages: [assistantMsg] });
const copyIcon = screen.getByTestId('chat-msg-copy').querySelector('svg');
expect(copyIcon?.getAttribute('class')).toContain('w-4');
expect(copyIcon?.getAttribute('class')).toContain('h-4');
});
});
describe('Wave U Lane F fix 2 — send-button micro-pulse', () => {
it('does not pulse at rest (empty composer)', () => {
render({ messages: [assistantMsg] });
const sendBtn = screen.getByRole('button', { name: 'Send' });
expect(sendBtn.className).not.toContain('scale-110');
});
it('fires a motion-safe scale pop on the empty→ready transition', () => {
render({ messages: [assistantMsg] });
const sendBtn = screen.getByRole('button', { name: 'Send' });
const textarea = screen.getByRole('textbox');
fireEvent.change(textarea, { target: { value: 'Ship it' } });
const tokens = sendBtn.className.split(/\s+/);
// The pulse is gated behind motion-safe so reduced-motion users never scale.
expect(tokens).toContain('motion-safe:scale-110');
expect(tokens).not.toContain('scale-110');
expect(sendBtn.className).toContain('transition-[color,background-color,transform]');
});
});

View File

@@ -0,0 +1,80 @@
/**
* Wave W Lane B (item 1) — briefing entrance beat.
*
* The recall cards + workspace rows now share ONE staggered rise+fade entrance
* grammar (was: recall cards slid on `x`, rows had no motion at all). These pins
* guard the happy-path render survived the motion.div/motion.button conversion —
* a broken conversion would drop the rows or highlights entirely:
* - a real memory highlight renders under "I remember" (recall card)
* - the workspace row still renders AS a button (motion.button → <button>)
* Motion timing itself is not asserted (jsdom has no layout); the contract here
* is "content still lands", which is what the entrance re-key must never break.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, waitFor, cleanup } from '@testing-library/react';
const mocks = vi.hoisted(() => ({
adapter: {
connect: vi.fn().mockResolvedValue(undefined),
getWorkspaces: vi.fn(),
searchMemory: vi.fn(),
getMemoryStats: vi.fn(),
getWorkspaceContext: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
afterEach(() => { cleanup(); vi.clearAllMocks(); });
async function renderBriefing() {
const { default: LoginBriefing } = await import('@/components/os/overlays/LoginBriefing');
const { ServiceProvider } = await import('@/providers/ServiceProvider');
const { TooltipProvider } = await import('@/components/ui/tooltip');
render(
<TooltipProvider>
<ServiceProvider>
<LoginBriefing onDismiss={() => {}} onOpenWorkspace={() => {}} />
</ServiceProvider>
</TooltipProvider>,
);
return screen;
}
describe('LoginBriefing entrance (Wave W Lane B)', () => {
it('renders a recall card and a workspace row after the content lands', async () => {
mocks.adapter.searchMemory.mockResolvedValue([
{
content: 'We decided to prioritise compliance over speed for the launch.',
importance: 'important',
timestamp: '2026-07-01T10:00:00.000Z',
},
]);
mocks.adapter.getWorkspaces.mockResolvedValue([
{ id: 'w1', name: 'Alpha Project', group: 'Personal', status: 'active', lastActive: '2026-07-05T09:00:00.000Z' },
]);
mocks.adapter.getMemoryStats.mockResolvedValue(null);
mocks.adapter.getWorkspaceContext.mockResolvedValue({
stats: { memoryCount: 12, sessionCount: 3 },
summary: 'Ongoing launch prep work.',
pendingTasks: [],
});
const screen = await renderBriefing();
const briefing = await screen.findByRole('dialog', { name: 'Catching you up' });
const mascot = briefing.querySelector('img[aria-hidden="true"]');
expect(mascot).toHaveAttribute('width', '28');
expect(mascot).toHaveAttribute('height', '28');
// Workspace row lands — and is still a real <button> after the
// motion.button conversion (a broken conversion would strand the row).
const row = await screen.findByText('Alpha Project');
const rowButton = row.closest('button');
expect(rowButton).not.toBeNull();
expect(rowButton?.className).not.toContain('transition-all');
expect(rowButton?.className).toContain('transition-colors');
// Recall card (the "I remember" highlight) lands too.
await waitFor(() => expect(screen.getByText(/prioritise compliance/)).toBeInTheDocument());
}, 15000);
});

View File

@@ -0,0 +1,130 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, fireEvent, cleanup, within } from '@testing-library/react';
import { TooltipProvider } from '@/components/ui/tooltip';
const mocks = vi.hoisted(() => ({
adapter: {
getWikiPages: vi.fn(),
getWikiPageContent: vi.fn(),
compileWiki: vi.fn(),
getWikiHealth: vi.fn(),
exportWikiToObsidian: vi.fn(),
exportWikiToNotion: vi.fn(),
},
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter }));
import WikiTab, { type WikiPage } from '@/components/os/apps/memory/WikiTab';
const wikiPage: WikiPage = {
slug: 'research-guide',
pageType: 'entity',
name: 'Research Guide',
contentHash: 'hash-research-guide',
markdown: '# Research Guide',
frameIds: 'memory-1',
compiledAt: '2026-07-08T09:00:00.000Z',
sourceCount: 3,
};
function renderWikiTab() {
return render(
<TooltipProvider>
<WikiTab />
</TooltipProvider>,
);
}
function exportButtons() {
const buttons = screen.getAllByRole('button');
return {
obsidian: buttons[2],
notion: buttons[3],
};
}
beforeEach(() => {
vi.clearAllMocks();
mocks.adapter.getWikiPages.mockResolvedValue([wikiPage]);
mocks.adapter.getWikiPageContent.mockResolvedValue({ slug: wikiPage.slug, markdown: wikiPage.markdown });
mocks.adapter.exportWikiToObsidian.mockResolvedValue({
outDir: 'C:/Research Vault',
filesWritten: 3,
indexPath: 'C:/Research Vault/index.md',
byType: { entity: 1, concept: 2 },
});
mocks.adapter.exportWikiToNotion.mockResolvedValue({
pagesCreated: 1,
pagesUpdated: 2,
pagesUnchanged: 0,
pagesFailed: 0,
byType: { entity: 1 },
errors: [],
});
});
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
describe('Wiki export trust flows', () => {
it('a11y: search exposes stable metadata and an input-level token focus ring', async () => {
renderWikiTab();
await screen.findByText('Research Guide');
const search = screen.getByRole('textbox', { name: /search wiki pages/i });
expect(search).toHaveAttribute('name', 'wikiSearch');
expect(search).toHaveAttribute('autocomplete', 'off');
expect(search.className).toContain('focus-visible:ring-2');
expect(search.className).toContain('focus-visible:ring-[var(--focus-ring)]');
});
it('asks for the Obsidian vault path in-app before exporting', async () => {
const promptSpy = vi.spyOn(window, 'prompt').mockReturnValue('C:/Research Vault');
renderWikiTab();
await screen.findByText('Research Guide');
fireEvent.click(exportButtons().obsidian);
expect(promptSpy).not.toHaveBeenCalled();
expect(mocks.adapter.exportWikiToObsidian).not.toHaveBeenCalled();
const dialog = await screen.findByRole('alertdialog', { name: /export to obsidian/i });
const pathInput = within(dialog).getByLabelText(/obsidian vault directory/i);
expect(pathInput).toHaveAttribute('name', 'obsidianVaultDirectory');
expect(pathInput).toHaveAttribute('autocomplete', 'off');
expect(pathInput.className).toContain('focus-visible:ring-2');
expect(pathInput.className).toContain('focus-visible:ring-[var(--focus-ring)]');
fireEvent.change(pathInput, { target: { value: ' C:/Research Vault ' } });
fireEvent.click(within(dialog).getByRole('button', { name: /^export to obsidian$/i }));
await waitFor(() => expect(mocks.adapter.exportWikiToObsidian).toHaveBeenCalledWith('C:/Research Vault'));
await screen.findByText(/obsidian export complete/i);
});
it('asks for the Notion root page in-app before exporting', async () => {
const promptSpy = vi.spyOn(window, 'prompt').mockReturnValue('https://notion.so/root');
renderWikiTab();
await screen.findByText('Research Guide');
fireEvent.click(exportButtons().notion);
expect(promptSpy).not.toHaveBeenCalled();
expect(mocks.adapter.exportWikiToNotion).not.toHaveBeenCalled();
const dialog = await screen.findByRole('alertdialog', { name: /export to notion/i });
const urlInput = within(dialog).getByLabelText(/notion root page url/i);
expect(urlInput).toHaveAttribute('name', 'notionRootPageUrl');
expect(urlInput).toHaveAttribute('autocomplete', 'off');
expect(urlInput.className).toContain('focus-visible:ring-2');
expect(urlInput.className).toContain('focus-visible:ring-[var(--focus-ring)]');
fireEvent.change(urlInput, { target: { value: ' https://notion.so/root ' } });
fireEvent.click(within(dialog).getByRole('button', { name: /^export to notion$/i }));
await waitFor(() => expect(mocks.adapter.exportWikiToNotion).toHaveBeenCalledWith('https://notion.so/root'));
await screen.findByText(/notion export complete/i);
});
});

View File

@@ -0,0 +1,64 @@
import { describe, it, expect } from 'vitest';
import { passesQualityFloor, type WikiPage } from '@/components/os/apps/memory/WikiTab';
function page(overrides: Partial<WikiPage>): WikiPage {
return {
slug: 's',
pageType: 'entity',
name: 'Kubernetes',
contentHash: 'h',
markdown: '',
frameIds: '',
compiledAt: '',
sourceCount: 5,
...overrides,
};
}
describe('passesQualityFloor', () => {
it('keeps a well-formed entity (long name, >=2 sources)', () => {
expect(passesQualityFloor(page({}))).toBe(true);
});
it('preserves 3-char tech acronyms', () => {
expect(passesQualityFloor(page({ name: 'AWS', sourceCount: 3 }))).toBe(true);
expect(passesQualityFloor(page({ name: 'GPT', sourceCount: 2 }))).toBe(true);
});
it('hides 1–2 char entity noise fragments', () => {
expect(passesQualityFloor(page({ name: 'A' }))).toBe(false);
expect(passesQualityFloor(page({ name: 'Ab' }))).toBe(false);
});
it('treats whitespace-padded short names as too short', () => {
expect(passesQualityFloor(page({ name: ' x ' }))).toBe(false);
});
it('hides thin-provenance entities (<2 sources)', () => {
expect(passesQualityFloor(page({ sourceCount: 1 }))).toBe(false);
expect(passesQualityFloor(page({ sourceCount: 0 }))).toBe(false);
});
it('keeps entities with exactly 2 sources', () => {
expect(passesQualityFloor(page({ sourceCount: 2 }))).toBe(true);
});
it('never floors non-entity page types, even short/thin ones', () => {
for (const pageType of ['concept', 'synthesis', 'index', 'health']) {
expect(passesQualityFloor(page({ pageType, name: 'A', sourceCount: 0 }))).toBe(true);
}
});
it('hides entity date-fragment names (month abbrev or bare year token)', () => {
expect(passesQualityFloor(page({ name: 'Act Aug', sourceCount: 30 }))).toBe(false);
expect(passesQualityFloor(page({ name: 'Roadmap 2026', sourceCount: 30 }))).toBe(false);
});
it('preserves names where a date-like string is only a substring or a full month word', () => {
expect(passesQualityFloor(page({ name: 'August Company', sourceCount: 30 }))).toBe(true);
expect(passesQualityFloor(page({ name: 'AI Act', sourceCount: 30 }))).toBe(true);
expect(passesQualityFloor(page({ name: 'EU AI Act', sourceCount: 30 }))).toBe(true);
expect(passesQualityFloor(page({ name: 'GPT API', sourceCount: 30 }))).toBe(true);
expect(passesQualityFloor(page({ name: 'New York', sourceCount: 30 }))).toBe(true);
});
});

View File

@@ -0,0 +1,223 @@
/**
* WorkspaceActionsMenu (UX-Northstar 2026-06-13 G1) — the management surface
* for a workspace. Pins:
* - the kebab opens Rename / Archive / Export summary / Delete…
* - Archive ↔ Restore label follows workspace.status
* - rename + archive go through ShellContext.patchWorkspace and fire onChanged
* - delete is gated on typing the exact workspace name
* - a failed mutation (false from the hook) does NOT fire onChanged
*/
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
import WorkspaceActionsMenu from '@/components/os/WorkspaceActionsMenu';
const mocks = vi.hoisted(() => ({
shell: {
patchWorkspace: vi.fn(),
deleteWorkspace: vi.fn(),
},
adapter: {
getWorkspaceContext: vi.fn(),
exportWorkspaceBriefing: vi.fn(),
},
toast: vi.fn(),
}));
vi.mock('@/providers/ShellContext', () => ({ useShell: () => mocks.shell }));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/hooks/use-toast', () => ({ useToast: () => ({ toast: mocks.toast }) }));
const openMenu = () => fireEvent.click(screen.getByTestId('workspace-actions-trigger'));
describe('WorkspaceActionsMenu', () => {
beforeEach(() => {
mocks.shell.patchWorkspace.mockResolvedValue(true);
mocks.shell.deleteWorkspace.mockResolvedValue(true);
mocks.adapter.getWorkspaceContext.mockResolvedValue({ stats: { memoryCount: 12 } });
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
it('opens a menu with all management actions', () => {
render(<WorkspaceActionsMenu workspace={{ id: 'w1', name: 'Alpha' }} />);
openMenu();
expect(screen.getByText('Rename')).toBeTruthy();
expect(screen.getByText('Archive')).toBeTruthy();
expect(screen.getByText('Export summary')).toBeTruthy();
expect(screen.getByText('Delete…')).toBeTruthy();
});
it('shows Restore instead of Archive for an archived workspace', () => {
render(<WorkspaceActionsMenu workspace={{ id: 'w1', name: 'Alpha', status: 'archived' }} />);
openMenu();
expect(screen.getByText('Restore')).toBeTruthy();
expect(screen.queryByText('Archive')).toBeNull();
});
it('archives via patchWorkspace and fires onChanged', async () => {
const onChanged = vi.fn();
render(<WorkspaceActionsMenu workspace={{ id: 'w1', name: 'Alpha' }} onChanged={onChanged} />);
openMenu();
fireEvent.click(screen.getByText('Archive'));
await waitFor(() => {
expect(mocks.shell.patchWorkspace).toHaveBeenCalledWith('w1', { status: 'archived' });
expect(onChanged).toHaveBeenCalledWith('archive');
});
});
it('renames via patchWorkspace from the rename dialog', async () => {
const onChanged = vi.fn();
render(<WorkspaceActionsMenu workspace={{ id: 'w1', name: 'Alpha' }} onChanged={onChanged} />);
openMenu();
fireEvent.click(screen.getByText('Rename'));
const input = screen.getByTestId('workspace-rename-input');
fireEvent.change(input, { target: { value: 'Client Alpha' } });
fireEvent.click(screen.getByTestId('workspace-rename-save'));
await waitFor(() => {
expect(mocks.shell.patchWorkspace).toHaveBeenCalledWith('w1', { name: 'Client Alpha' });
expect(onChanged).toHaveBeenCalledWith('rename');
});
});
it('labels destructive dialog inputs and gives them visible focus rings', async () => {
render(<WorkspaceActionsMenu workspace={{ id: 'w1', name: 'Alpha' }} />);
openMenu();
fireEvent.click(screen.getByText('Rename'));
const renameInput = screen.getByRole('textbox', { name: /workspace name/i });
expect(renameInput).toHaveAttribute('name', 'workspace-name');
expect(renameInput).toHaveAttribute('autocomplete', 'off');
expect(renameInput.className).toContain('focus-visible:ring-2');
expect(renameInput.className).toContain('focus-visible:ring-[var(--focus-ring)]');
fireEvent.click(screen.getByText('Cancel'));
openMenu();
fireEvent.click(screen.getByText(/Delete/));
const deleteInput = screen.getByRole('textbox', { name: /type alpha to confirm/i });
expect(deleteInput).toHaveAttribute('name', 'workspace-delete-confirmation');
expect(deleteInput).toHaveAttribute('autocomplete', 'off');
expect(deleteInput.className).toContain('focus-visible:ring-2');
expect(deleteInput.className).toContain('focus-visible:ring-[var(--focus-ring)]');
await waitFor(() => expect(screen.getByText(/12 memories/)).toBeTruthy());
});
it('gates delete on typing the exact workspace name', async () => {
const onChanged = vi.fn();
render(<WorkspaceActionsMenu workspace={{ id: 'w1', name: 'Alpha' }} onChanged={onChanged} />);
openMenu();
fireEvent.click(screen.getByText('Delete…'));
const confirmButton = screen.getByTestId('workspace-delete-confirm-button') as HTMLButtonElement;
expect(confirmButton.disabled).toBe(true);
fireEvent.change(screen.getByTestId('workspace-delete-confirm-input'), { target: { value: 'Alph' } });
expect(confirmButton.disabled).toBe(true);
fireEvent.change(screen.getByTestId('workspace-delete-confirm-input'), { target: { value: 'Alpha' } });
expect(confirmButton.disabled).toBe(false);
fireEvent.click(confirmButton);
await waitFor(() => {
expect(mocks.shell.deleteWorkspace).toHaveBeenCalledWith('w1');
expect(onChanged).toHaveBeenCalledWith('delete');
});
});
it('shows what is at stake in the delete dialog (memory count, best-effort)', async () => {
render(<WorkspaceActionsMenu workspace={{ id: 'w1', name: 'Alpha' }} />);
openMenu();
fireEvent.click(screen.getByText('Delete…'));
await waitFor(() => {
expect(mocks.adapter.getWorkspaceContext).toHaveBeenCalledWith('w1');
expect(screen.getByText(/12 memories/)).toBeTruthy();
});
});
// ── Wave W Lane B (item 2) — actions-menu craft ──────────────────────────
it('opens with the roomier "comfortable" item density (py-2, marketplace-matched)', () => {
render(<WorkspaceActionsMenu workspace={{ id: 'w1', name: 'Alpha' }} />);
openMenu();
// The workspace actions menu opts into the roomier density rather than the
// compact default other ContextMenu callers keep.
expect(screen.getByText('Rename').className).toContain('py-2');
});
it('scales the menu in FROM the trigger corner (transform-origin top-left)', () => {
render(<WorkspaceActionsMenu workspace={{ id: 'w1', name: 'Alpha' }} />);
openMenu();
const container = screen.getByText('Rename').parentElement as HTMLElement;
expect(container.style.transformOrigin).toBe('top left');
});
it('does not steal focus into the menu (preserves Escape-returns-focus) and Escape closes it', () => {
render(<WorkspaceActionsMenu workspace={{ id: 'w1', name: 'Alpha' }} />);
openMenu();
// The menu never auto-focuses an item — focus stays on the kebab, which is
// what makes Escape return focus to the trigger. Escape then closes it.
expect(screen.getByText('Rename')).not.toBe(document.activeElement);
fireEvent.keyDown(document, { key: 'Escape' });
expect(screen.queryByText('Rename')).toBeNull();
});
// ── Pillar 2.7 (Lane K) — keyboard-power layer ───────────────────────────
it('the kebab trigger reveals on keyboard focus and carries a ≥40px hit area', () => {
render(<WorkspaceActionsMenu workspace={{ id: 'w1', name: 'Alpha' }} />);
const kebab = screen.getByTestId('workspace-actions-trigger');
// focus-visible reveal (the systemic :focus-visible ring paints --focus-ring).
expect(kebab.className).toContain('focus-visible:opacity-100');
// Centered 40px ::before expands the effective target from 24px, no visual change.
expect(kebab.className).toContain('relative');
expect(kebab.className).toContain('before:h-10');
expect(kebab.className).toContain('before:w-10');
});
// ── R20 Lane CL (item 2 + 4) — reach card actions without a mouse ────────
// s10 acceptance made provable: Tab lands on the kebab (a native <button>, so
// Enter/Space activate it per the platform), the menu's arrow-key roving
// highlight walks down to Delete with a VISIBLE --focus-ring, and Enter on it
// opens the delete flow. No pointer touches this path.
it('reaches Delete by keyboard alone — focus kebab → open → ArrowDown to Delete (visible ring) → Enter opens the delete dialog', async () => {
render(<WorkspaceActionsMenu workspace={{ id: 'w1', name: 'Alpha' }} />);
const kebab = screen.getByTestId('workspace-actions-trigger');
// The action is Tab-reachable: it is a real focusable <button>.
expect(kebab.tagName).toBe('BUTTON');
kebab.focus();
expect(document.activeElement).toBe(kebab);
// Enter/Space on a focused native button dispatches click (platform behavior).
fireEvent.click(kebab);
expect(screen.getByText('Delete…')).toBeTruthy();
// Roving highlight: 4 ArrowDowns walk Rename → Archive → Export → Delete.
fireEvent.keyDown(document, { key: 'ArrowDown' });
fireEvent.keyDown(document, { key: 'ArrowDown' });
fireEvent.keyDown(document, { key: 'ArrowDown' });
fireEvent.keyDown(document, { key: 'ArrowDown' });
// The Delete action carries a VISIBLE focus indicator on the ACTION itself,
// bound to the --focus-ring TOKEN (item 4: the token resolves to the light
// value #9a6408 in light theme — 4.14–4.91:1 over the menu's surfaces per
// contrast-tokens, well above the WCAG 1.4.11 3:1 floor; not a hardcoded
// dark-only hex, so the ring survives the theme switch).
expect(screen.getByText('Delete…').className).toContain('ring-[var(--focus-ring)]');
// Enter on the highlighted Delete opens the confirm-by-name flow.
fireEvent.keyDown(document, { key: 'Enter' });
expect(screen.getByTestId('workspace-delete-confirm-input')).toBeInTheDocument();
await waitFor(() => expect(screen.getByText(/12 memories/)).toBeTruthy());
});
it('does NOT fire onChanged when the mutation fails', async () => {
mocks.shell.patchWorkspace.mockResolvedValue(false);
const onChanged = vi.fn();
render(<WorkspaceActionsMenu workspace={{ id: 'w1', name: 'Alpha' }} onChanged={onChanged} />);
openMenu();
fireEvent.click(screen.getByText('Archive'));
await waitFor(() => {
expect(mocks.shell.patchWorkspace).toHaveBeenCalled();
});
expect(onChanged).not.toHaveBeenCalled();
expect(mocks.toast).toHaveBeenCalledWith(expect.objectContaining({ variant: 'destructive' }));
});
});

View File

@@ -0,0 +1,62 @@
/**
* F9 — WorkspaceBriefing first-visit variant.
*
* A brand-new workspace (stats.sessionCount === 0) — even one seeded with
* imported memories — must show fresh copy instead of "here's where you left
* off" / "…across 0 sessions", and must not render the "0 sessions" stat.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup, waitFor } from '@testing-library/react';
const mocks = vi.hoisted(() => ({
adapter: { getWorkspaceContext: vi.fn() },
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
import WorkspaceBriefing from '@/components/os/WorkspaceBriefing';
import { TooltipProvider } from '@/components/ui/tooltip';
beforeEach(() => {
vi.clearAllMocks();
localStorage.clear();
});
afterEach(cleanup);
function renderBriefing() {
return render(
<TooltipProvider>
<WorkspaceBriefing workspaceId="ws-1" />
</TooltipProvider>,
);
}
describe('WorkspaceBriefing first-visit (F9)', () => {
it('sessionCount 0 → fresh copy, no "0 sessions", server summary suppressed', async () => {
mocks.adapter.getWorkspaceContext.mockResolvedValue({
workspace: { name: 'Acme' },
greeting: "Good afternoon. Here's where you left off:",
summary: 'A few open threads across 0 sessions.',
welcomeMessage: 'This workspace tracks your sales pipeline.',
stats: { memoryCount: 12, sessionCount: 0 },
});
renderBriefing();
await waitFor(() => expect(screen.getByText(/fresh workspace/i)).toBeInTheDocument());
expect(screen.queryByText(/across 0 sessions/i)).toBeNull();
expect(screen.queryByText(/sessions/i)).toBeNull(); // stat hidden at 0
expect(screen.getByText(/12 memories/i)).toBeInTheDocument();
expect(screen.getByText(/tracks your sales pipeline/i)).toBeInTheDocument();
});
it('sessionCount > 0 → server greeting + the "N sessions" stat', async () => {
mocks.adapter.getWorkspaceContext.mockResolvedValue({
workspace: { name: 'Acme' },
greeting: "Good afternoon. Here's where you left off:",
summary: '3 open threads to pick back up.',
stats: { memoryCount: 12, sessionCount: 3 },
});
renderBriefing();
await waitFor(() => expect(screen.getByText(/where you left off/i)).toBeInTheDocument());
expect(screen.getByText(/3 sessions/i)).toBeInTheDocument();
expect(screen.queryByText(/fresh workspace/i)).toBeNull();
});
});

View File

@@ -0,0 +1,109 @@
/**
* Workspace Desktop Tasks tab (UX-Northstar 2026-06-13 G8) — the real task
* board. Pins:
* - tasks load from the adapter and render on the board
* - add (input + button) calls createWorkspaceTask and appends
* - clicking the status icon cycles open → in_progress → done via PATCH
* - delete removes the row
* - memory-derived signals (WorkspaceStateView) still render below
*/
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
import TasksTab from '@/components/os/apps/workspace/TasksTab';
import type { WorkspaceTask, WorkspaceStateView } from '@/lib/types';
const mocks = vi.hoisted(() => ({
adapter: {
getWorkspaceTasks: vi.fn(),
createWorkspaceTask: vi.fn(),
patchWorkspaceTask: vi.fn(),
deleteWorkspaceTask: vi.fn(),
},
toast: vi.fn(),
}));
vi.mock('@/lib/adapter', () => ({ adapter: mocks.adapter, default: vi.fn() }));
vi.mock('@/hooks/use-toast', () => ({ useToast: () => ({ toast: mocks.toast }) }));
const task = (id: string, title: string, status: WorkspaceTask['status'] = 'open'): WorkspaceTask => ({
id, title, status, createdAt: '2026-06-13T00:00:00Z', updatedAt: '2026-06-13T00:00:00Z',
});
const emptyState: WorkspaceStateView = {
active: [], openQuestions: [], pending: [], blocked: [],
completed: [], stale: [], recentDecisions: [], nextActions: [],
};
describe('TasksTab', () => {
beforeEach(() => {
mocks.adapter.getWorkspaceTasks.mockResolvedValue([]);
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
});
it('renders loaded tasks on the board', async () => {
mocks.adapter.getWorkspaceTasks.mockResolvedValue([task('t1', 'Ship the report')]);
render(<TasksTab workspaceId="w1" state={null} />);
expect(await screen.findByText('Ship the report')).toBeTruthy();
expect(mocks.adapter.getWorkspaceTasks).toHaveBeenCalledWith('w1');
});
it('adds a task through the input', async () => {
mocks.adapter.createWorkspaceTask.mockResolvedValue(task('t2', 'Call the client'));
render(<TasksTab workspaceId="w1" state={null} />);
const input = await screen.findByRole('textbox', { name: /add workspace task/i }) as HTMLInputElement;
expect(input).toHaveAttribute('name', 'workspace-task-title');
expect(input).toHaveAttribute('autocomplete', 'off');
expect(input.className).toContain('focus-visible:ring-2');
expect(input.className).toContain('focus-visible:ring-[var(--focus-ring)]');
fireEvent.change(input, { target: { value: 'Call the client' } });
fireEvent.click(screen.getByTestId('ws-task-add'));
await waitFor(() => {
expect(mocks.adapter.createWorkspaceTask).toHaveBeenCalledWith('w1', 'Call the client');
expect(screen.getByText('Call the client')).toBeTruthy();
});
expect(input.value).toBe('');
});
it('cycles status open → in_progress via PATCH', async () => {
mocks.adapter.getWorkspaceTasks.mockResolvedValue([task('t1', 'Draft outline')]);
mocks.adapter.patchWorkspaceTask.mockResolvedValue(task('t1', 'Draft outline', 'in_progress'));
render(<TasksTab workspaceId="w1" state={null} />);
fireEvent.click(await screen.findByLabelText('Mark "Draft outline" as in progress'));
await waitFor(() => {
expect(mocks.adapter.patchWorkspaceTask).toHaveBeenCalledWith('w1', 't1', { status: 'in_progress' });
});
});
it('deletes a task', async () => {
mocks.adapter.getWorkspaceTasks.mockResolvedValue([task('t1', 'Old task')]);
mocks.adapter.deleteWorkspaceTask.mockResolvedValue(undefined);
render(<TasksTab workspaceId="w1" state={null} />);
const deleteButton = await screen.findByLabelText('Delete task "Old task"');
expect(deleteButton.className).not.toContain('transition-all');
expect(deleteButton.className).toContain('transition-[opacity,color]');
fireEvent.click(deleteButton);
await waitFor(() => {
expect(mocks.adapter.deleteWorkspaceTask).toHaveBeenCalledWith('w1', 't1');
expect(screen.queryByText('Old task')).toBeNull();
});
});
it('renders memory-derived signals below the board', async () => {
render(
<TasksTab
workspaceId="w1"
state={{ ...emptyState, pending: [{ id: 'p1', content: 'Waiting on legal review' }] }}
/>,
);
expect(await screen.findByText('Waiting on legal review')).toBeTruthy();
expect(screen.getByText(/From this workspace/)).toBeTruthy();
});
});