Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Migrate raw-source React tests to runtime behavior coverage (#1320)

Dimitri POSTOLOV20d2dfdd0160
diff --git a/packages/app/src/App.dom.test.tsx b/packages/app/src/App.dom.test.tsx
new file mode 100644
index 000000000..b28407949
--- /dev/null
+++ b/packages/app/src/App.dom.test.tsx
@@ -0,0 +1,460 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { expectVisualClassTokens } from '@/test-utils/visual-contract';
+
+type NavigationTarget =
+ | { kind: 'doc'; target: string; docName: string }
+ | { kind: 'folder-index'; target: string; docName: string; folderPath: string }
+ | { kind: 'folder'; target: string; folderPath: string }
+ | { kind: 'asset'; target: string; assetPath: string; mediaKind: string }
+ | { kind: 'missing'; target: string };
+
+let activeTarget: NavigationTarget | null = null;
+let pages = new Set<string>();
+let pageMeta = new Map<string, unknown>();
+let pagesBySlug = new Map<string, unknown>();
+let pagesByBasename = new Map<string, unknown>();
+let folderPaths = new Set<string>();
+let assetPaths = new Set<string>();
+let loading = false;
+let singleFileMode = false;
+let tabSessionLoaded = true;
+let fetchApiConfigMock = mock(() =>
+ Promise.resolve({
+ status: 'ok' as const,
+ config: {
+ collabUrl: null,
+ previewUrl: null,
+ port: 0,
+ paneTarget: null,
+ singleFile: false,
+ },
+ }),
+);
+let clearTargetMock = mock(() => {});
+let syncOpenTabsWithKnownTargetsMock = mock(() => {});
+let openTargetTransitionMock = mock((_: NavigationTarget) => {});
+let resolveNavigationTargetMock = mock(
+ (docName: string): NavigationTarget => ({ kind: 'doc', target: docName, docName }),
+);
+let downgradeFolderIndexForHashNavMock = mock((target: NavigationTarget) => target);
+let withLargeFileOpenGuardMock = mock((target: NavigationTarget) => target);
+
+mock.module('@/lib/perf', () => ({
+ mark: () => {},
+ ProfilerBoundary: ({ children }: { children: ReactNode }) => children,
+}));
+
+mock.module('@/editor/DocumentContext', () => ({
+ DocumentProvider: ({ children }: { children: ReactNode }) => (
+ <div data-testid="document-provider">{children}</div>
+ ),
+ useDocumentContext: () => ({
+ activeDocName: activeTarget?.kind === 'doc' ? activeTarget.docName : null,
+ activeTarget,
+ clearTarget: clearTargetMock,
+ syncOpenTabsWithKnownTargets: syncOpenTabsWithKnownTargetsMock,
+ tabSessionLoaded,
+ }),
+ useDocumentTransition: () => ({
+ openTargetTransition: openTargetTransitionMock,
+ }),
+}));
+
+mock.module('@/components/PageListContext', () => ({
+ PageListProvider: ({ children }: { children: ReactNode }) => (
+ <div data-testid="page-list-provider">{children}</div>
+ ),
+ usePageList: () => ({
+ assetPaths,
+ folderPaths,
+ loading,
+ pageMeta,
+ pages,
+ pagesBySlug,
+ pagesByBasename,
+ }),
+}));
+
+mock.module('@/components/navigation-targets', () => ({
+ resolveNavigationTarget: (...args: Parameters<typeof resolveNavigationTargetMock>) =>
+ resolveNavigationTargetMock(...args),
+ downgradeFolderIndexForHashNav: (target: NavigationTarget) =>
+ downgradeFolderIndexForHashNavMock(target),
+ withLargeFileOpenGuard: (target: NavigationTarget) => withLargeFileOpenGuardMock(target),
+}));
+
+mock.module('@/lib/config-provider', () => ({
+ ConfigProvider: ({ children }: { children: ReactNode }) => (
+ <div data-testid="config-provider">{children}</div>
+ ),
+}));
+
+mock.module('@/lib/api-config', () => ({
+ fetchApiConfig: (...args: Parameters<typeof fetchApiConfigMock>) => fetchApiConfigMock(...args),
+}));
+
+mock.module('@/lib/single-file-mode', () => ({
+ SingleFileModeProvider: ({ children }: { children: ReactNode }) => (
+ <div data-testid="single-file-mode-provider">{children}</div>
+ ),
+ useSingleFileMode: () => singleFileMode,
+}));
+
+mock.module('@/components/ConnectingBanner', () => ({
+ ConnectingBanner: () => <div data-testid="connecting-banner" />,
+}));
+
+mock.module('@/components/SystemDocSubscriber', () => ({
+ SystemDocSubscriber: () => <div data-testid="system-doc-subscriber" />,
+}));
+
+mock.module('@/components/McpConsentDialog', () => ({
+ McpConsentDialog: () => <div data-testid="mcp-consent-dialog" />,
+}));
+
+mock.module('@/components/CommandPalette', () => ({
+ CommandPalette: ({ open }: { open: boolean }) => (
+ <div data-testid="command-palette" data-open={String(open)} />
+ ),
+}));
+
+mock.module('@/components/AuthModal', () => ({
+ AuthModal: ({ open }: { open: boolean }) => (
+ <div data-testid="auth-modal" data-open={String(open)} />
+ ),
+}));
+
+mock.module('@/components/InstallInClaudeDesktopDialog', () => ({
+ InstallInClaudeDesktopDialog: ({ open }: { open: boolean }) => (
+ <div data-testid="install-dialog" data-open={String(open)} />
+ ),
+}));
+
+mock.module('@/components/CreateProjectMenuTrigger', () => ({
+ CreateProjectMenuTrigger: () => <div data-testid="create-project-menu-trigger" />,
+}));
+
+mock.module('@/components/ShareBranchSwitchDialog', () => ({
+ ShareBranchSwitchDialog: () => <div data-testid="share-branch-switch-dialog" />,
+}));
+
+mock.module('@/components/NewItemDialog', () => ({
+ isNewItemShortcut: () => false,
+ NewItemDialog: ({ open, initialDir }: { open: boolean; initialDir: string }) => (
+ <div data-testid="new-item-dialog" data-open={String(open)} data-initial-dir={initialDir} />
+ ),
+}));
+
+mock.module('@/components/FileSidebar', () => ({
+ FileSidebar: ({ onOpenSearch }: { onOpenSearch: () => void }) => (
+ <button type="button" data-testid="file-sidebar" onClick={onOpenSearch}>
+ Sidebar
+ </button>
+ ),
+}));
+
+mock.module('@/components/EditorPane', () => ({
+ EditorPane: () => <main data-testid="editor-pane" />,
+}));
+
+mock.module('@/components/ui/sidebar', () => ({
+ SidebarProvider: ({ children, className }: { children: ReactNode; className?: string }) => (
+ <section data-testid="sidebar-provider" className={className}>
+ {children}
+ </section>
+ ),
+ SidebarInset: ({ children, className }: { children: ReactNode; className?: string }) => (
+ <section data-testid="sidebar-inset" className={className}>
+ {children}
+ </section>
+ ),
+}));
+
+mock.module('@/components/ShareReceiveDialog', () => ({
+ ShareReceiveDialog: () => <div data-testid="share-receive-dialog" />,
+}));
+
+mock.module('@/lib/share/clone-controller', () => ({
+ createCloneController: () => ({}),
+}));
+
+mock.module('@/lib/transports/auth-query-transport', () => ({
+ httpAuthQueryTransport: () => ({}),
+}));
+
+mock.module('@/lib/transports/clone-transport', () => ({
+ httpCloneTransport: () => ({}),
+}));
+
+const { App } = await import('./App');
+
+function createBridge() {
+ return {
+ editor: {
+ notifyActiveTargetChanged: mock(() => {}),
+ },
+ };
+}
+
+function renderApp({ bridge = null }: { bridge?: ReturnType<typeof createBridge> | null } = {}) {
+ if (bridge) {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: bridge,
+ });
+ }
+ return render(<App />);
+}
+
+function setHash(hash: string) {
+ window.history.replaceState(null, '', `${window.location.pathname}${hash}`);
+}
+
+describe('App runtime wiring', () => {
+ beforeEach(() => {
+ cleanup();
+ Reflect.deleteProperty(window, 'okDesktop');
+ setHash('');
+ activeTarget = null;
+ pages = new Set(['reports/index']);
+ pageMeta = new Map();
+ pagesBySlug = new Map();
+ pagesByBasename = new Map();
+ folderPaths = new Set(['reports']);
+ assetPaths = new Set();
+ loading = false;
+ singleFileMode = false;
+ tabSessionLoaded = true;
+ fetchApiConfigMock = mock(() =>
+ Promise.resolve({
+ status: 'ok' as const,
+ config: {
+ collabUrl: null,
+ previewUrl: null,
+ port: 0,
+ paneTarget: null,
+ singleFile: false,
+ },
+ }),
+ );
+ globalThis.fetch = mock(() => Promise.resolve(new Response(null, { status: 204 }))) as never;
+ clearTargetMock = mock(() => {});
+ syncOpenTabsWithKnownTargetsMock = mock(() => {});
+ openTargetTransitionMock = mock((_: NavigationTarget) => {});
+ resolveNavigationTargetMock = mock(
+ (docName: string): NavigationTarget => ({ kind: 'doc', target: docName, docName }),
+ );
+ downgradeFolderIndexForHashNavMock = mock((target: NavigationTarget) => target);
+ withLargeFileOpenGuardMock = mock((target: NavigationTarget) => target);
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('imports and mounts the app shell providers and core surfaces', () => {
+ renderApp();
+
+ expect(screen.getByTestId('document-provider')).not.toBeNull();
+ expect(screen.getByTestId('config-provider')).not.toBeNull();
+ expect(screen.getByTestId('page-list-provider')).not.toBeNull();
+ expect(screen.getByTestId('system-doc-subscriber')).not.toBeNull();
+ expect(screen.getByTestId('file-sidebar')).not.toBeNull();
+ expect(screen.getByTestId('editor-pane')).not.toBeNull();
+ });
+
+ test('Cmd/Ctrl-comma opens settings via the canonical hash and ignores text inputs', () => {
+ renderApp();
+
+ const input = document.createElement('input');
+ document.body.append(input);
+ fireEvent.keyDown(input, { key: ',', metaKey: true });
+ expect(window.location.hash).toBe('');
+
+ fireEvent.keyDown(window, { key: ',', metaKey: true });
+ expect(window.location.hash).toBe('#settings');
+ });
+
+ test('hash navigation opens the downgraded folder-index target, not the pre-downgrade result', async () => {
+ const resolved: NavigationTarget = {
+ kind: 'folder-index',
+ target: 'reports/index',
+ docName: 'reports/index',
+ folderPath: 'reports',
+ };
+ const downgraded: NavigationTarget = {
+ kind: 'folder',
+ target: 'reports',
+ folderPath: 'reports',
+ };
+ resolveNavigationTargetMock = mock(() => resolved);
+ downgradeFolderIndexForHashNavMock = mock(() => downgraded);
+ setHash('#/reports/');
+
+ renderApp();
+
+ await waitFor(() => {
+ expect(downgradeFolderIndexForHashNavMock).toHaveBeenCalledWith(resolved);
+ expect(openTargetTransitionMock).toHaveBeenCalledWith(downgraded);
+ });
+ expect(openTargetTransitionMock).not.toHaveBeenCalledWith(resolved);
+ });
+
+ test('base-open pane target applies a well-formed config route once and consumes it', async () => {
+ fetchApiConfigMock = mock(() =>
+ Promise.resolve({
+ status: 'ok' as const,
+ config: {
+ collabUrl: null,
+ previewUrl: null,
+ port: 0,
+ paneTarget: '#/docs/pane-target',
+ singleFile: false,
+ },
+ }),
+ );
+
+ renderApp();
+
+ await waitFor(() => {
+ expect(window.location.hash).toBe('#/docs/pane-target');
+ });
+ expect(fetchApiConfigMock).toHaveBeenCalledTimes(1);
+ expect(globalThis.fetch).toHaveBeenCalledWith('/api/config', { method: 'DELETE' });
+ });
+
+ test('base-open pane target ignores malformed and direct-navigation routes', async () => {
+ fetchApiConfigMock = mock(() =>
+ Promise.resolve({
+ status: 'ok' as const,
+ config: {
+ collabUrl: null,
+ previewUrl: null,
+ port: 0,
+ paneTarget: 'https://example.invalid/docs/readme',
+ singleFile: false,
+ },
+ }),
+ );
+
+ renderApp();
+
+ await waitFor(() => {
+ expect(fetchApiConfigMock).toHaveBeenCalledTimes(1);
+ });
+ expect(window.location.hash).toBe('');
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+
+ cleanup();
+ fetchApiConfigMock = mock(() =>
+ Promise.resolve({
+ status: 'ok' as const,
+ config: {
+ collabUrl: null,
+ previewUrl: null,
+ port: 0,
+ paneTarget: '#/docs/pane-target',
+ singleFile: false,
+ },
+ }),
+ );
+ setHash('#/docs/already-open');
+
+ renderApp();
+
+ await waitFor(() => {
+ expect(fetchApiConfigMock).not.toHaveBeenCalled();
+ });
+ expect(window.location.hash).toBe('#/docs/already-open');
+ });
+
+ test('active doc and folder targets are pushed to the desktop bridge', async () => {
+ const bridge = createBridge();
+ activeTarget = { kind: 'doc', target: 'docs/readme', docName: 'docs/readme' };
+
+ renderApp({ bridge });
+
+ await waitFor(() => {
+ expect(bridge.editor.notifyActiveTargetChanged).toHaveBeenCalledWith({
+ kind: 'doc',
+ identifier: 'docs/readme',
+ });
+ });
+
+ cleanup();
+ activeTarget = { kind: 'folder', target: 'docs', folderPath: 'docs' };
+
+ renderApp({ bridge });
+
+ await waitFor(() => {
+ expect(bridge.editor.notifyActiveTargetChanged).toHaveBeenCalledWith({
+ kind: 'folder',
+ identifier: 'docs',
+ });
+ });
+ });
+
+ test('active asset targets are pushed to the desktop bridge', async () => {
+ const bridge = createBridge();
+ activeTarget = {
+ kind: 'asset',
+ target: 'images/logo.png',
+ assetPath: 'images/logo.png',
+ mediaKind: 'image',
+ };
+
+ renderApp({ bridge });
+
+ await waitFor(() => {
+ expect(bridge.editor.notifyActiveTargetChanged).toHaveBeenCalledWith({
+ kind: 'asset',
+ identifier: 'images/logo.png',
+ });
+ });
+ });
+
+ test('missing and folder-index targets collapse to the project-scope desktop snapshot', async () => {
+ const bridge = createBridge();
+ activeTarget = { kind: 'missing', target: 'missing/path' };
+
+ renderApp({ bridge });
+
+ await waitFor(() => {
+ expect(bridge.editor.notifyActiveTargetChanged).toHaveBeenCalledWith({ kind: null });
+ });
+ });
+
+ test('active-target push is a web-mode no-op without the desktop bridge', () => {
+ activeTarget = { kind: 'doc', target: 'docs/readme', docName: 'docs/readme' };
+
+ renderApp();
+
+ expect(screen.queryByTestId('share-receive-dialog')).toBeNull();
+ });
+
+ test('Electron host renders the drag strip with fixed 8px chrome geometry', () => {
+ renderApp({ bridge: createBridge() });
+
+ const strip = screen.getByTestId('editor-window-chrome-drag-strip');
+ expect(strip.getAttribute('aria-hidden')).toBe('true');
+ expect(strip.getAttribute('data-electron-drag')).toBe('');
+ expectVisualClassTokens(strip.className, [
+ 'pointer-events-none',
+ 'fixed',
+ 'inset-x-0',
+ 'top-0',
+ 'z-50',
+ 'h-2',
+ '[-webkit-app-region:drag]',
+ ]);
+ });
+
+ test('web host does not render Electron-only drag or share-receive surfaces', () => {
+ renderApp();
+
+ expect(screen.queryByTestId('editor-window-chrome-drag-strip')).toBeNull();
+ expect(screen.queryByTestId('share-receive-dialog')).toBeNull();
+ });
+});
diff --git a/packages/app/src/App.test.ts b/packages/app/src/App.test.ts
deleted file mode 100644
index 634feebb5..000000000
--- a/packages/app/src/App.test.ts
+++ /dev/null
@@ -1,199 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
-
-const SRC_PATH = join(__dirname, 'App.tsx');
-const src = readFileSync(SRC_PATH, 'utf-8');
-
-describe('App module', () => {
- test('Component module imports cleanly', async () => {
- const mod = await import('./App');
- expect(typeof mod.App).toBe('function');
- });
-});
-
-describe('NavigationHandler folder-index downgrade', () => {
- test('hash-driven nav routes folder-index through downgradeFolderIndexForHashNav', () => {
- expect(src).toContain('downgradeFolderIndexForHashNav');
- expect(src).toMatch(/downgradeFolderIndexForHashNav\(\s*resolved\s*\)/);
- expect(src).toMatch(/openTargetTransition\(\s*target\s*\)/);
- });
-});
-
-describe('SettingsShortcutHandler wiring (US-010)', () => {
- test('imports isSettingsShortcut and SETTINGS_OPEN_HASH from use-settings-route', () => {
- expect(src).toContain('isSettingsShortcut');
- expect(src).toContain('SETTINGS_OPEN_HASH');
- expect(src).toMatch(/from\s*'@\/lib\/use-settings-route'/);
- });
-
- test('declares a SettingsShortcutHandler component and mounts it in App body', () => {
- expect(src).toContain('function SettingsShortcutHandler()');
- expect(src).toMatch(/<SettingsShortcutHandler\s*\/>/);
- });
-
- const handlerBlock =
- src
- .split('function SettingsShortcutHandler()')[1]
- ?.split('function NewItemShortcutHandler()')[0] ?? '';
-
- test('handler subscribes to window keydown and dispatches via isSettingsShortcut', () => {
- expect(handlerBlock).toContain("addEventListener('keydown'");
- expect(handlerBlock).toContain("removeEventListener('keydown'");
- expect(handlerBlock).toContain('isSettingsShortcut');
- });
-
- test('handler routes to the canonical SETTINGS_OPEN_HASH (no inlined literal)', () => {
- expect(handlerBlock).toContain('SETTINGS_OPEN_HASH');
- expect(handlerBlock).not.toContain("'#settings'");
- });
-
- test('SettingsShortcutHandler mount sits between NewItemShortcutHandler and InstallInClaudeDesktopTrigger', () => {
- const newItemIdx = src.indexOf('<NewItemShortcutHandler');
- const settingsIdx = src.indexOf('<SettingsShortcutHandler');
- const installIdx = src.indexOf('<InstallInClaudeDesktopTrigger');
- expect(newItemIdx).toBeGreaterThanOrEqual(0);
- expect(settingsIdx).toBeGreaterThan(newItemIdx);
- expect(installIdx).toBeGreaterThan(settingsIdx);
- });
-});
-
-describe('PaneTargetLanding wiring (R7)', () => {
- const block = src.split('function PaneTargetLanding()')[1]?.split(/\nfunction /)[0] ?? '';
-
- test('declares PaneTargetLanding and mounts it in the App tree', () => {
- expect(src).toContain('function PaneTargetLanding()');
- expect(src).toMatch(/<PaneTargetLanding\s*\/>/);
- });
-
- test('fetches /api/config and applies an armed paneTarget to the hash', () => {
- expect(block).toContain('fetchApiConfig');
- expect(block).toContain('result.config.paneTarget');
- expect(block).toContain('window.location.hash = target');
- });
-
- test('only applies a well-formed in-app route fragment', () => {
- expect(block).toContain("target?.startsWith('#/')");
- });
-
- test('consumes the target on apply (DELETE /api/config)', () => {
- expect(block).toMatch(/fetch\('\/api\/config',\s*\{\s*method:\s*'DELETE'/);
- });
-});
-
-const DRAG_LITERAL = '[-webkit-app-region:drag]';
-
-function hasIsElectronHostGatedDrag(appSrc: string): boolean {
- const lines = appSrc.split('\n');
- for (let i = 0; i < lines.length; i += 1) {
- if (!lines[i]?.includes(DRAG_LITERAL)) continue;
- const start = Math.max(0, i - 6);
- const end = Math.min(lines.length, i + 6);
- const context = lines.slice(start, end).join('\n');
- if (/isElectronHost\s*(?:&&|\?)/.test(context)) return true;
- }
- return false;
-}
-
-describe('Editor BrowserWindow — wrapper-strip drag region contract', () => {
- test('App.tsx declares an isElectronHost-gated drag region covering the y=0..y=8 wrapper strip', () => {
- expect(hasIsElectronHostGatedDrag(src)).toBe(true);
- });
-
- test('App.tsx uses the canonical isElectronHost detection idiom', () => {
- expect(src).toMatch(
- /typeof\s+window\s*!==\s*['"]undefined['"]\s*&&\s*window\.okDesktop\s*!=\s*null/,
- );
- expect(src).toContain('const isElectronHost');
- });
-
- test('the drag-strip element pins fixed-position 8px-tall full-width pointer-passthrough geometry', () => {
- const lines = src.split('\n');
- let geometryPinLanded = false;
- for (let i = 0; i < lines.length; i += 1) {
- const line = lines[i] ?? '';
- if (!line.includes(DRAG_LITERAL)) continue;
- const start = Math.max(0, i - 4);
- const end = Math.min(lines.length, i + 5);
- const context = lines.slice(start, end).join('\n');
- expect(context).toContain('fixed');
- expect(context).toContain('top-0');
- expect(context).toContain('h-2');
- expect(context).toContain('inset-x-0');
- expect(context).toContain('pointer-events-none');
- expect(context).toContain('z-50');
- geometryPinLanded = true;
- }
- expect(geometryPinLanded).toBe(true);
- });
-
- test('the drag region is conditional on isElectronHost (web mode is unchanged)', () => {
- const lines = src.split('\n');
- let dragLiteralFound = false;
- for (let i = 0; i < lines.length; i += 1) {
- const line = lines[i] ?? '';
- if (!line.includes(DRAG_LITERAL)) continue;
- dragLiteralFound = true;
- const start = Math.max(0, i - 6);
- const end = Math.min(lines.length, i + 6);
- const context = lines.slice(start, end).join('\n');
- expect(context).toMatch(/isElectronHost/);
- }
- expect(dragLiteralFound).toBe(true);
- });
-
- test('the drag strip carries data-electron-drag so the globals.css `:has()` rule can target it', () => {
- const lines = src.split('\n');
- let attrLanded = false;
- for (let i = 0; i < lines.length; i += 1) {
- const line = lines[i] ?? '';
- if (!line.includes(DRAG_LITERAL)) continue;
- const start = Math.max(0, i - 4);
- const end = Math.min(lines.length, i + 4);
- const context = lines.slice(start, end).join('\n');
- expect(context).toContain('data-electron-drag');
- attrLanded = true;
- }
- expect(attrLanded).toBe(true);
- });
-});
-
-describe('ActiveTargetBridgePush — renderer→main push for File menu', () => {
- test('declares an ActiveTargetBridgePush component and mounts it inside the App tree', () => {
- expect(src).toMatch(/function\s+ActiveTargetBridgePush\s*\(/);
- expect(src).toMatch(/<ActiveTargetBridgePush\s*\/>/);
- });
-
- const handlerBlock =
- src
- .split('function ActiveTargetBridgePush()')[1]
- ?.split('function NewItemShortcutHandler()')[0] ?? '';
-
- test('reads activeTarget via useDocumentContext (single source of truth)', () => {
- expect(handlerBlock).toContain('useDocumentContext');
- expect(handlerBlock).toMatch(/const\s*\{\s*activeTarget\s*\}\s*=\s*useDocumentContext\(\)/);
- });
-
- test('gates the push on the desktop bridge being present (web mode is no-op)', () => {
- expect(handlerBlock).toMatch(/window\.okDesktop\s*\?\?\s*null/);
- expect(handlerBlock).toMatch(/if\s*\(!bridge\)\s*return\s*;/);
- });
-
- test('invokes bridge.editor.notifyActiveTargetChanged with the normalized snapshot', () => {
- expect(handlerBlock).toMatch(/bridge\.editor\.notifyActiveTargetChanged\(/);
- });
-
- test('effect deps narrow to the discriminator + identifier (no full-target re-fires)', () => {
- expect(handlerBlock).toMatch(
- /useEffect\(\s*\(\)\s*=>\s*\{[\s\S]*?\},\s*\[\s*bridge\s*,\s*kind\s*,\s*identifier\s*\]\)/,
- );
- });
-
- test('collapses non-{doc,folder,asset} kinds to the project-scope null snapshot', () => {
- expect(handlerBlock).toMatch(
- /activeTarget\?\.kind\s*===\s*'doc'\s*\|\|\s*activeTarget\?\.kind\s*===\s*'folder'\s*\|\|\s*activeTarget\?\.kind\s*===\s*'asset'/,
- );
- expect(handlerBlock).toContain('activeTarget.assetPath');
- expect(handlerBlock).toMatch(/notifyActiveTargetChanged\(\s*\{\s*kind:\s*null\s*\}\s*\)/);
- });
-});
diff --git a/packages/app/src/components/AssetPreview.dom.test.tsx b/packages/app/src/components/AssetPreview.dom.test.tsx
index 2fb58153b..e001d1f5f 100644
--- a/packages/app/src/components/AssetPreview.dom.test.tsx
+++ b/packages/app/src/components/AssetPreview.dom.test.tsx
@@ -1,5 +1,9 @@
import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
mock.module('@/editor/components/Pdf', () => ({
Pdf: (props: { src?: string; title?: string; fillContainer?: boolean }) => (
@@ -38,7 +42,7 @@ describe('AssetPreview — image loading-state placeholder (PRD-6638)', () => {
const slot = screen.queryByTestId('image-slot') as HTMLElement | null;
expect(slot).not.toBeNull();
- expect(slot?.className).toContain('aspect-[16/9]');
+ expectVisualClassTokens(slot?.className, ['aspect-[16/9]']);
});
test('removes the placeholder and releases the aspect-ratio constraint after the inner <img>.load event fires', () => {
@@ -54,7 +58,7 @@ describe('AssetPreview — image loading-state placeholder (PRD-6638)', () => {
const slotAfterLoad = screen.queryByTestId('image-slot') as HTMLElement | null;
expect(slotAfterLoad).not.toBeNull();
- expect(slotAfterLoad?.className).not.toContain('aspect-[16/9]');
+ expectVisualClassTokensAbsent(slotAfterLoad?.className, ['aspect-[16/9]']);
});
test('renders an <audio> player for mediaKind="audio"', () => {
@@ -102,6 +106,6 @@ describe('AssetPreview — image loading-state placeholder (PRD-6638)', () => {
expect(screen.queryByTestId('image-loading-skeleton')).not.toBeNull();
const slot = screen.queryByTestId('image-slot') as HTMLElement | null;
- expect(slot?.className).toContain('aspect-[16/9]');
+ expectVisualClassTokens(slot?.className, ['aspect-[16/9]']);
});
});
diff --git a/packages/app/src/components/AutoSyncOnboardingDialog.dom.test.tsx b/packages/app/src/components/AutoSyncOnboardingDialog.dom.test.tsx
new file mode 100644
index 000000000..b498841d4
--- /dev/null
+++ b/packages/app/src/components/AutoSyncOnboardingDialog.dom.test.tsx
@@ -0,0 +1,115 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+
+type SyncWriter = (enabled: boolean) => { ok: true } | { ok: false; error: string };
+
+let writer: SyncWriter | null = null;
+const toastErrors: string[] = [];
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((out, part, index) => `${out}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+mock.module('sonner', () => ({
+ toast: {
+ error: (message: string) => {
+ toastErrors.push(message);
+ },
+ },
+}));
+
+mock.module('@/hooks/use-enable-sync-with-confirm', () => ({
+ useSyncEnabledWriter: () => writer,
+}));
+
+async function renderDialog(onResolved: () => void = () => {}) {
+ const { AutoSyncOnboardingDialog } = await import('./AutoSyncOnboardingDialog');
+ render(<AutoSyncOnboardingDialog open={true} onResolved={onResolved} />);
+}
+
+describe('AutoSyncOnboardingDialog runtime behavior', () => {
+ afterEach(() => {
+ cleanup();
+ writer = null;
+ toastErrors.length = 0;
+ });
+
+ test('exports the component', async () => {
+ const mod = await import('./AutoSyncOnboardingDialog');
+ expect(typeof mod.AutoSyncOnboardingDialog).toBe('function');
+ });
+
+ test('renders stable primary and secondary choices without a close affordance', async () => {
+ writer = () => ({ ok: true });
+ await renderDialog();
+
+ expect(screen.getByRole('button', { name: 'Enable auto-sync' })).not.toBeNull();
+ expect(screen.getByRole('button', { name: 'Keep disabled' })).not.toBeNull();
+ expect(screen.queryByRole('button', { name: /close/i })).toBeNull();
+ expect(screen.getByRole('alert').textContent).toContain('Before you enable it');
+ });
+
+ test('disables both choices until the project-local sync writer is ready', async () => {
+ writer = null;
+ await renderDialog();
+
+ expect(
+ (screen.getByRole('button', { name: 'Enable auto-sync' }) as HTMLButtonElement).disabled,
+ ).toBe(true);
+ expect(
+ (screen.getByRole('button', { name: 'Keep disabled' }) as HTMLButtonElement).disabled,
+ ).toBe(true);
+ });
+
+ test('persists enable and disable choices through the shared writer', async () => {
+ const writerCalls: boolean[] = [];
+ const resolvedCalls: string[] = [];
+ writer = (enabled) => {
+ writerCalls.push(enabled);
+ return { ok: true };
+ };
+ await renderDialog(() => resolvedCalls.push('resolved'));
+
+ await userEvent.click(screen.getByRole('button', { name: 'Enable auto-sync' }));
+ expect(writerCalls).toEqual([true]);
+ expect(resolvedCalls).toEqual(['resolved']);
+
+ cleanup();
+ writerCalls.length = 0;
+ resolvedCalls.length = 0;
+ await renderDialog(() => resolvedCalls.push('resolved'));
+ await userEvent.click(screen.getByRole('button', { name: 'Keep disabled' }));
+
+ expect(writerCalls).toEqual([false]);
+ expect(resolvedCalls).toEqual(['resolved']);
+ });
+
+ test('surfaces writer failures without resolving the dialog', async () => {
+ const resolvedCalls: string[] = [];
+ writer = () => ({ ok: false, error: 'binding unavailable' });
+ await renderDialog(() => resolvedCalls.push('resolved'));
+
+ await userEvent.click(screen.getByRole('button', { name: 'Enable auto-sync' }));
+
+ expect(resolvedCalls).toEqual([]);
+ expect(toastErrors).toEqual(['Could not enable sync: binding unavailable']);
+ });
+
+ test('Escape does not resolve the non-dismissible prompt', async () => {
+ const resolvedCalls: string[] = [];
+ writer = () => ({ ok: true });
+ await renderDialog(() => resolvedCalls.push('resolved'));
+
+ await userEvent.keyboard('{Escape}');
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'Enable auto-sync' })).not.toBeNull();
+ });
+ expect(resolvedCalls).toEqual([]);
+ });
+});
diff --git a/packages/app/src/components/AutoSyncOnboardingDialog.test.ts b/packages/app/src/components/AutoSyncOnboardingDialog.test.ts
deleted file mode 100644
index 56b336854..000000000
--- a/packages/app/src/components/AutoSyncOnboardingDialog.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './AutoSyncOnboardingDialog?raw';
-
-describe('AutoSyncOnboardingDialog module', () => {
- test('exports AutoSyncOnboardingDialog component', async () => {
- const mod = await import('./AutoSyncOnboardingDialog');
- expect(typeof mod.AutoSyncOnboardingDialog).toBe('function');
- });
-});
-
-describe('AutoSyncOnboardingDialog source-level guards', () => {
- test('writes route through the project-local ConfigBinding (not HTTP)', () => {
- expect(SRC).toContain("from '@/hooks/use-enable-sync-with-confirm'");
- expect(SRC).toContain('useSyncEnabledWriter');
- expect(SRC).toContain('persistChoice(true)');
- expect(SRC).toContain('persistChoice(false)');
- expect(SRC).toContain('writer(enabled)');
- expect(SRC).not.toContain('postSyncEnabled');
- expect(SRC).not.toContain('/api/sync/set-enabled');
- expect(SRC).not.toContain('onboardingResolvedAt');
- });
-
- test('renders both primary and secondary buttons with stable copy', () => {
- expect(SRC).toContain('<Trans>Enable auto-sync</Trans>');
- expect(SRC).toContain('<Trans>Keep disabled</Trans>');
- });
-
- test('non-dismissible: ignores Radix outside-click / Esc until a button is clicked', () => {
- expect(SRC).toContain('onOpenChange={() => {}}');
- expect(SRC).toContain('showCloseButton={false}');
- });
-
- test('disables buttons during the cold-start window when the binding is null', () => {
- expect(SRC).toMatch(/disabled=\{writer === null\}/);
- });
-});
diff --git a/packages/app/src/components/BetaBadge.dom.test.tsx b/packages/app/src/components/BetaBadge.dom.test.tsx
new file mode 100644
index 000000000..2f2bf4262
--- /dev/null
+++ b/packages/app/src/components/BetaBadge.dom.test.tsx
@@ -0,0 +1,55 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+let channel: 'beta' | 'latest' | null = null;
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+mock.module('@/hooks/use-update-channel', () => ({
+ useUpdateChannel: () => ({ channel }),
+}));
+
+async function renderBetaBadge(className?: string) {
+ const { BetaBadge } = await import('./BetaBadge');
+ return render(<BetaBadge className={className} />);
+}
+
+describe('BetaBadge runtime behavior', () => {
+ afterEach(() => {
+ cleanup();
+ channel = null;
+ });
+
+ test('exports the component', async () => {
+ const mod = await import('./BetaBadge');
+ expect(typeof mod.BetaBadge).toBe('function');
+ });
+
+ test('renders nothing while the channel is null or latest', async () => {
+ channel = null;
+ const { rerender } = await renderBetaBadge();
+ expect(screen.queryByTestId('beta-badge')).toBeNull();
+
+ channel = 'latest';
+ const { BetaBadge } = await import('./BetaBadge');
+ rerender(<BetaBadge />);
+ expect(screen.queryByTestId('beta-badge')).toBeNull();
+ });
+
+ test('renders an accessible secondary badge for the beta channel', async () => {
+ channel = 'beta';
+ await renderBetaBadge('ml-2');
+
+ const badge = screen.getByTestId('beta-badge');
+ expect(badge.textContent).toBe('BETA');
+ expect(badge.getAttribute('aria-label')).toBe('Beta channel');
+ expect(badge.getAttribute('data-slot')).toBe('badge');
+ expect(badge.getAttribute('data-variant')).toBe('secondary');
+ expect(badge.classList.contains('ml-2')).toBe(true);
+ });
+});
diff --git a/packages/app/src/components/BetaBadge.test.ts b/packages/app/src/components/BetaBadge.test.ts
deleted file mode 100644
index 985feff6e..000000000
--- a/packages/app/src/components/BetaBadge.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './BetaBadge?raw';
-
-describe('BetaBadge module', () => {
- test('exports BetaBadge component', async () => {
- const mod = await import('./BetaBadge');
- expect(typeof mod.BetaBadge).toBe('function');
- });
-});
-
-describe('BetaBadge source-level guards', () => {
- test('uses the shared useUpdateChannel hook (single source of truth across Settings + chrome + About panel)', () => {
- expect(SRC).toMatch(/from\s+['"]@\/hooks\/use-update-channel['"]/);
- expect(SRC).toContain('useUpdateChannel(');
- });
-
- test('returns null when channel is anything other than beta (covers latest AND null/loading)', () => {
- expect(SRC).toMatch(/channel\s*!==\s*['"]beta['"]/);
- expect(SRC).toMatch(/return\s+null/);
- });
-
- test('renders a shadcn Badge primitive (not a custom div / dock-icon / app-name surface)', () => {
- expect(SRC).toMatch(/from\s+['"]\.\/ui\/badge['"]/);
- expect(SRC).toMatch(/<Badge\b/);
- expect(SRC).toMatch(/variant=["']secondary["']/);
- });
-
- test('renders the literal text "BETA"', () => {
- expect(SRC).toMatch(/<Trans>BETA<\/Trans>/);
- });
-
- test('exposes accessibility + test seams', () => {
- expect(SRC).toContain('aria-label={t`Beta channel`}');
- expect(SRC).toContain('data-testid="beta-badge"');
- });
-
- test('accepts an optional className for layout overrides without forking the component', () => {
- expect(SRC).toMatch(/className\?:\s*string/);
- expect(SRC).toContain('className={className}');
- });
-});
diff --git a/packages/app/src/components/CommandPalette.dom.test.tsx b/packages/app/src/components/CommandPalette.dom.test.tsx
new file mode 100644
index 000000000..c5def15dc
--- /dev/null
+++ b/packages/app/src/components/CommandPalette.dom.test.tsx
@@ -0,0 +1,374 @@
+import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+type CommandDialogProps = {
+ children?: ReactNode;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+ title?: string;
+ description?: string;
+ className?: string;
+ commandProps?: Record<string, unknown>;
+ transition?: unknown;
+ placement?: unknown;
+};
+type CommandItemProps = {
+ children?: ReactNode;
+ disabled?: boolean;
+ onSelect?: () => void;
+ value?: string;
+ [key: string]: unknown;
+};
+
+let activeDocName: string | null = 'docs/active';
+let activeTarget: { kind: 'doc'; docName: string } | null = { kind: 'doc', docName: 'docs/active' };
+let requestDocPanelTabCalls: string[] = [];
+let seedDialogProps: Array<{ open: boolean }> = [];
+let newItemDialogProps: Array<{ open: boolean; kind: string; initialDir: string }> = [];
+let createProjectDialogProps: Array<{ open: boolean; bridge: unknown }> = [];
+let commandDialogProps: CommandDialogProps[] = [];
+let refreshInstallStatesCalls = 0;
+const refreshInstallStates = () => {
+ refreshInstallStatesCalls += 1;
+};
+const installedAgentStates = {
+ codex: { installed: false },
+ 'claude-code': { installed: false },
+ cursor: { installed: false },
+};
+const workspaceValue = { rootPath: '/workspace' };
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (
+ <>{(value === 1 ? one : other).replace('#', String(value))}</>
+ ),
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+mock.module('@/components/ui/command', () => ({
+ CommandDialog: (props: CommandDialogProps) => {
+ commandDialogProps.push(props);
+ return props.open ? (
+ <div
+ aria-describedby="command-palette-description"
+ aria-label={props.title}
+ className={props.className}
+ role="dialog"
+ >
+ <p id="command-palette-description">{props.description}</p>
+ {props.children}
+ </div>
+ ) : null;
+ },
+ CommandEmpty: ({ children }: { children?: ReactNode }) => <div role="status">{children}</div>,
+ CommandGroup: ({ children, heading }: { children?: ReactNode; heading?: ReactNode }) => (
+ <section aria-label={typeof heading === 'string' ? heading : undefined}>
+ {heading ? <h2>{heading}</h2> : null}
+ {children}
+ </section>
+ ),
+ CommandInput: ({
+ onValueChange,
+ value,
+ ...props
+ }: {
+ onValueChange?: (value: string) => void;
+ value?: string;
+ [key: string]: unknown;
+ }) => (
+ <input
+ {...props}
+ aria-label="Command search"
+ value={value}
+ onChange={(event) => onValueChange?.(event.currentTarget.value)}
+ />
+ ),
+ CommandItem: ({ children, disabled, onSelect, ...props }: CommandItemProps) => (
+ <button type="button" role="option" disabled={disabled} onClick={() => onSelect?.()} {...props}>
+ {children}
+ </button>
+ ),
+ CommandList: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div role="listbox" {...props}>
+ {children}
+ </div>
+ ),
+ CommandShortcut: ({ children }: { children?: ReactNode }) => (
+ <span data-testid="command-shortcut">{children}</span>
+ ),
+}));
+
+mock.module('@/components/doc-panel-events', () => ({
+ requestDocPanelTab: (tab: string) => {
+ requestDocPanelTabCalls.push(tab);
+ },
+}));
+
+mock.module('@/components/NewItemDialog', () => ({
+ NewItemDialog: (props: { open: boolean; kind: string; initialDir: string }) => {
+ newItemDialogProps.push(props);
+ return (
+ <div data-kind={props.kind} data-open={String(props.open)} data-testid="new-item-dialog" />
+ );
+ },
+}));
+
+mock.module('@/components/SeedDialog', () => ({
+ SeedDialog: (props: { open: boolean }) => {
+ seedDialogProps.push(props);
+ return <div data-open={String(props.open)} data-testid="seed-dialog" />;
+ },
+}));
+
+mock.module('@/components/CreateProjectDialog', () => ({
+ CreateProjectDialog: (props: { open: boolean; bridge: unknown }) => {
+ createProjectDialogProps.push(props);
+ return (
+ <div
+ data-open={String(props.open)}
+ data-has-bridge={String(props.bridge !== null)}
+ data-testid="create-project-dialog"
+ />
+ );
+ },
+}));
+
+mock.module('@/components/PageListContext', () => ({
+ usePageList: () => ({
+ pages: new Set<string>(),
+ pageTitles: new Map<string, string>(),
+ pageMeta: new Map<string, unknown>(),
+ folderPaths: new Set<string>(),
+ }),
+}));
+
+mock.module('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({
+ activeDocName,
+ activeTarget,
+ }),
+}));
+
+mock.module('@/lib/use-workspace', () => ({
+ useWorkspace: () => workspaceValue,
+}));
+
+mock.module('./handoff/useInstalledAgents', () => ({
+ useInstalledAgents: () => ({
+ states: installedAgentStates,
+ refresh: refreshInstallStates,
+ }),
+}));
+
+mock.module('./handoff/useHandoffDispatch', () => ({
+ buildHandoffInput: ({ docName, workspace }: { docName: string | null; workspace: unknown }) =>
+ docName && workspace ? { docName, workspace } : null,
+ useHandoffDispatch: () => ({
+ dispatch: mock(() => Promise.resolve()),
+ }),
+}));
+
+mock.module('@/components/command-palette-tag-search', () => ({
+ TAG_QUERY_PREFIX: 'tag:',
+ parseTagPaletteQuery: () => ({ kind: 'normal' }),
+ filterTagList: () => [],
+ fetchTagsList: mock(() => Promise.resolve([])),
+ fetchDocsForTag: mock(() => Promise.resolve([])),
+}));
+
+function recent(name: string, path = `/projects/${name.toLowerCase()}`) {
+ return { name, path: path.replaceAll(' ', '-') };
+}
+
+function createBridge() {
+ return {
+ config: {
+ projectName: 'Current Project',
+ projectPath: '/projects/current',
+ },
+ project: {
+ listRecent: mock(() =>
+ Promise.resolve([
+ recent('Current', '/projects/current'),
+ recent('Alpha', '/projects/alpha'),
+ recent('Omega', '/archive/omega-project'),
+ ]),
+ ),
+ open: mock(() => Promise.resolve()),
+ },
+ dialog: {
+ openFolder: mock(() => Promise.resolve('/chosen/folder')),
+ },
+ navigator: {
+ open: mock(() => Promise.resolve()),
+ },
+ };
+}
+
+async function renderPalette({
+ bridge = createBridge(),
+ docName = 'docs/active',
+}: {
+ bridge?: ReturnType<typeof createBridge> | null;
+ docName?: string | null;
+} = {}) {
+ activeDocName = docName;
+ activeTarget = docName ? { kind: 'doc', docName } : null;
+ const onOpenChange = mock(() => {});
+ const { CommandPalette } = await import('./CommandPalette');
+ render(<CommandPalette bridge={bridge as never} open={true} onOpenChange={onOpenChange} />);
+ await waitFor(() => expect(screen.getByRole('dialog')).not.toBeNull());
+ return { bridge, onOpenChange };
+}
+
+async function setQuery(value: string) {
+ fireEvent.change(screen.getByLabelText('Command search'), { target: { value } });
+ await waitFor(() => {
+ expect((screen.getByLabelText('Command search') as HTMLInputElement).value).toBe(value);
+ });
+}
+
+describe('CommandPalette DOM behavior', () => {
+ beforeEach(() => {
+ cleanup();
+ activeDocName = 'docs/active';
+ activeTarget = { kind: 'doc', docName: 'docs/active' };
+ requestDocPanelTabCalls = [];
+ seedDialogProps = [];
+ newItemDialogProps = [];
+ createProjectDialogProps = [];
+ commandDialogProps = [];
+ refreshInstallStatesCalls = 0;
+ window.location.hash = '';
+ globalThis.fetch = mock(() =>
+ Promise.resolve(new Response(JSON.stringify({ results: [] }), { status: 200 })),
+ ) as never;
+ });
+
+ test('hides active-document commands without an active doc and opens the graph panel when one exists', async () => {
+ await renderPalette({ bridge: null, docName: null });
+
+ expect(document.body.textContent).not.toContain('No active doc');
+ expect(screen.queryByTestId('command-palette-open-graph')).toBeNull();
+ expect(screen.queryByText('Open with AI Codex')).toBeNull();
+
+ cleanup();
+ await renderPalette({ bridge: null, docName: 'docs/active' });
+
+ fireEvent.click(screen.getByTestId('command-palette-open-graph'));
+
+ expect(requestDocPanelTabCalls).toEqual(['graph']);
+ });
+
+ test('routes project commands through runtime bridge entry points and exposes switch-project search tokens', async () => {
+ const bridge = createBridge();
+ const { onOpenChange } = await renderPalette({ bridge });
+ await waitFor(() => expect(bridge.project.listRecent).toHaveBeenCalledTimes(1));
+ expect(refreshInstallStatesCalls).toBeGreaterThan(0);
+
+ const switchProject = screen.getByTestId('command-palette-switch-project');
+ expect(switchProject.textContent).toContain('Switch Project');
+ expect(switchProject.textContent).toMatch(/⌘⇧N|Ctrl Shift P/);
+ expect(switchProject.querySelector('svg[aria-hidden="true"]')).not.toBeNull();
+ expect(document.body.textContent).not.toContain('Start fresh in a new folder');
+
+ fireEvent.click(switchProject);
+ await waitFor(() => expect(bridge.navigator.open).toHaveBeenCalledTimes(1));
+
+ fireEvent.click(screen.getByTestId('command-palette-open-folder'));
+ await waitFor(() => {
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/chosen/folder',
+ target: 'new-window',
+ entryPoint: 'pick-existing',
+ });
+ });
+
+ fireEvent.click(screen.getByTestId('command-palette-recent-/projects/alpha'));
+ await waitFor(() => {
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/projects/alpha',
+ target: 'new-window',
+ entryPoint: 'recents',
+ });
+ });
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+
+ await setQuery('navigator');
+ expect(screen.getByTestId('command-palette-switch-project')).not.toBeNull();
+
+ await setQuery('manage');
+ expect(screen.queryByTestId('command-palette-switch-project')).toBeNull();
+ });
+
+ test('settings command is searchable by preferences/config, closes the palette, and routes through the canonical hash', async () => {
+ const { onOpenChange } = await renderPalette({ bridge: null });
+
+ await setQuery('preferences');
+ const settingsByPreference = screen.getByTestId('command-palette-settings');
+ expect(settingsByPreference.textContent).toContain('Settings');
+ expect(settingsByPreference.textContent).toMatch(/⌘,|Ctrl ,/);
+ expect(settingsByPreference.querySelector('svg[aria-hidden="true"]')).not.toBeNull();
+
+ await setQuery('config');
+ expect(screen.getByTestId('command-palette-settings')).not.toBeNull();
+
+ fireEvent.click(screen.getByTestId('command-palette-settings'));
+
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ const { SETTINGS_OPEN_HASH } = await import('@/lib/use-settings-route');
+ expect(window.location.hash).toBe(SETTINGS_OPEN_HASH);
+ });
+
+ test('new-project command is desktop-only, searchable by scaffold tokens, and opens CreateProjectDialog', async () => {
+ await renderPalette({ bridge: null });
+
+ await setQuery('new project');
+ expect(screen.queryByTestId('command-palette-new-project')).toBeNull();
+ expect(screen.queryByTestId('create-project-dialog')).toBeNull();
+
+ cleanup();
+ const bridge = createBridge();
+ const { onOpenChange } = await renderPalette({ bridge });
+
+ await setQuery('scaffold');
+ const newProject = screen.getByTestId('command-palette-new-project');
+ expect(newProject.textContent).toContain('New project');
+
+ fireEvent.click(newProject);
+
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ await waitFor(() => {
+ expect(screen.getByTestId('create-project-dialog').getAttribute('data-open')).toBe('true');
+ });
+ expect(createProjectDialogProps.at(-1)?.bridge).toBe(bridge);
+ });
+
+ test('starter-pack command is searchable, participates in empty-state aggregation, and opens SeedDialog after closing', async () => {
+ const { onOpenChange } = await renderPalette({ bridge: null });
+
+ await setQuery('scaffold');
+ expect(screen.queryByText('No matching commands.')).toBeNull();
+ const seedItem = screen.getByTestId('command-palette-initialize-starter-pack');
+ expect(seedItem.textContent).toContain('Initialize starter pack');
+ expect(seedItem.querySelector('svg[aria-hidden="true"]')).not.toBeNull();
+
+ fireEvent.click(seedItem);
+
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ await waitFor(() => {
+ expect(screen.getByTestId('seed-dialog').getAttribute('data-open')).toBe('true');
+ });
+ expect(seedDialogProps.at(-1)?.open).toBe(true);
+ });
+
+ test('CommandDialog receives no transition or placement prop from CommandPalette', async () => {
+ await renderPalette();
+
+ expect(commandDialogProps.at(-1)?.transition).toBeUndefined();
+ expect(commandDialogProps.at(-1)?.placement).toBeUndefined();
+ });
+});
diff --git a/packages/app/src/components/CommandPalette.test.ts b/packages/app/src/components/CommandPalette.test.ts
index 99b137eeb..8993f3588 100644
--- a/packages/app/src/components/CommandPalette.test.ts
+++ b/packages/app/src/components/CommandPalette.test.ts
@@ -1,6 +1,4 @@
import { describe, expect, mock, test } from 'bun:test';
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
describe('CommandPalette module', () => {
test('Component module imports cleanly', async () => {
@@ -64,249 +62,3 @@ describe('CommandPalette.runWithToast (IPC rejection → toast feedback)', () =>
await expect(runWithToast(() => Promise.resolve(), 'fallback')).resolves.toBeUndefined();
});
});
-
-describe('Active-doc command visibility (source-level guards)', () => {
- const SRC_PATH = join(__dirname, 'CommandPalette.tsx');
- const src = readFileSync(SRC_PATH, 'utf-8');
-
- const showGraphDecision =
- src.match(/const showGraphCommand =[\s\S]*?;\n {2}const showProjectOpenFolder/)?.[0] ?? '';
- const showAgentGroupDecision =
- src.match(/const showAgentGroup =[\s\S]*?;\n {2}const tagListItems/)?.[0] ?? '';
- const graphBlock = (() => {
- const chunks = src.split(/(?=<CommandItem\b)/);
- const ours = chunks.find((c) => c.includes('data-testid="command-palette-open-graph"'));
- if (!ours) return '';
- return ours.split('</CommandItem>')[0] ?? '';
- })();
-
- test('active-document commands are not rendered as disabled "No active doc" rows', () => {
- expect(src).not.toContain('No active doc');
- expect(showGraphDecision).toContain('activeDocName !== null');
- expect(showAgentGroupDecision).toContain('handoffInput !== null');
- });
-
- test('Open graph block is selectable only after the visibility gate passes', () => {
- expect(graphBlock, 'CommandItem with command-palette-open-graph not found').toBeTruthy();
- expect(graphBlock).not.toContain('disabled={!activeDocName}');
- expect(graphBlock).not.toContain('aria-label={activeDocName');
- expect(graphBlock).toContain("requestDocPanelTab('graph')");
- });
-});
-
-describe('Switch Project entry (source-level guards)', () => {
- const SRC_PATH = join(__dirname, 'CommandPalette.tsx');
- const src = readFileSync(SRC_PATH, 'utf-8');
-
- const switchProjectBlock = (() => {
- const chunks = src.split(/(?=<CommandItem\b)/);
- const ours = chunks.find((c) => c.includes('data-testid="command-palette-switch-project"'));
- if (!ours) return '';
- return ours.split('</CommandItem>')[0] ?? '';
- })();
-
- test('replaces the legacy "Start fresh" placeholder entry', () => {
- expect(src).not.toContain('Start fresh in a new folder');
- expect(src).not.toContain('command-palette-start-fresh');
- });
-
- test('imports the LayoutGrid icon', () => {
- expect(src).toMatch(/import\s*\{[^}]*\bLayoutGrid\b[^}]*\}\s*from\s*'lucide-react'/);
- });
-
- test('Switch Project block contains LayoutGrid icon, "Switch Project" label, shortcut hint, and bridge.navigator.open() in the SAME CommandItem', () => {
- expect(
- switchProjectBlock,
- 'CommandItem with command-palette-switch-project not found',
- ).toBeTruthy();
- expect(switchProjectBlock).toContain('<LayoutGrid');
- expect(switchProjectBlock).toContain('<Trans>Switch Project</Trans>');
- expect(switchProjectBlock).toContain("{formatShortcut('switch-project')}");
- expect(switchProjectBlock).toMatch(/bridge\.navigator\.open\(\)/);
- });
-
- test('search-token value covers FR4(e) substrings (switch / projects / navigator)', () => {
- const valueLine = switchProjectBlock.match(/value="switch-project[^"]*"/)?.[0] ?? '';
- expect(valueLine).toContain('switch');
- expect(valueLine).toContain('projects');
- expect(valueLine).toContain('navigator');
- expect(valueLine).not.toContain('manage');
- });
-});
-
-describe('Settings entry (US-010 / FR-1 / D54 — source-level guards)', () => {
- const SRC_PATH = join(__dirname, 'CommandPalette.tsx');
- const src = readFileSync(SRC_PATH, 'utf-8');
-
- const settingsBlock = (() => {
- const chunks = src.split(/(?=<CommandItem\b)/);
- const ours = chunks.find((c) => c.includes('data-testid="command-palette-settings"'));
- if (!ours) return '';
- return ours.split('</CommandItem>')[0] ?? '';
- })();
-
- test('imports the Settings icon from lucide-react and SETTINGS_OPEN_HASH', () => {
- expect(src).toMatch(/import\s*\{[^}]*\bSettings\b[^}]*\}\s*from\s*'lucide-react'/);
- expect(src).toContain('SETTINGS_OPEN_HASH');
- expect(src).toMatch(/from\s*'@\/lib\/use-settings-route'/);
- });
-
- test('Settings CommandItem carries the icon, shortcut hint, and the Settings label', () => {
- expect(settingsBlock, 'CommandItem with command-palette-settings not found').toBeTruthy();
- expect(settingsBlock).toContain('<Settings');
- expect(settingsBlock).toContain('<Trans>Settings</Trans>');
- expect(settingsBlock).toContain("{formatShortcut('settings')}");
- });
-
- test('Settings onSelect closes the palette and routes to SETTINGS_OPEN_HASH', () => {
- expect(settingsBlock).toContain('onOpenChange(false)');
- expect(settingsBlock).toContain('SETTINGS_OPEN_HASH');
- });
-
- test('search-token value covers settings / preferences / config substrings', () => {
- const valueLine = settingsBlock.match(/value="settings[^"]*"/)?.[0] ?? '';
- expect(valueLine).toContain('settings');
- expect(valueLine).toContain('preferences');
- expect(valueLine).toContain('config');
- });
-
- test('Settings sits inside the "Project" CommandGroup', () => {
- const settingsIdx = src.indexOf('command-palette-settings');
- const projectGroupIdx = src.indexOf('heading={t`Project`}');
- const agentGroupIdx = src.indexOf('heading={t`Open with AI`}');
- expect(projectGroupIdx).toBeGreaterThanOrEqual(0);
- expect(projectGroupIdx).toBeLessThan(settingsIdx);
- if (agentGroupIdx >= 0) {
- expect(agentGroupIdx).toBeLessThan(projectGroupIdx);
- }
- });
-});
-
-describe('Initialize starter pack entry (source-level guards)', () => {
- const SRC_PATH = join(__dirname, 'CommandPalette.tsx');
- const src = readFileSync(SRC_PATH, 'utf-8');
-
- const seedBlock = (() => {
- const chunks = src.split(/(?=<CommandItem\b)/);
- const ours = chunks.find((c) =>
- c.includes('data-testid="command-palette-initialize-starter-pack"'),
- );
- if (!ours) return '';
- return ours.split('</CommandItem>')[0] ?? '';
- })();
-
- test('CommandItem carries the Package icon and "Initialize starter pack" label', () => {
- expect(
- seedBlock,
- 'CommandItem with command-palette-initialize-starter-pack not found',
- ).toBeTruthy();
- expect(seedBlock).toContain('<Package');
- expect(seedBlock).toContain('<Trans>Initialize starter pack</Trans>');
- });
-
- test('onSelect closes the palette and opens SeedDialog', () => {
- expect(seedBlock).toContain('onOpenChange(false)');
- expect(seedBlock).toContain('setSeedDialogOpen(true)');
- });
-
- test('search-token value covers initialize / scaffold / seed / pack substrings', () => {
- const valueLine = seedBlock.match(/value="initialize[^"]*"/)?.[0] ?? '';
- expect(valueLine).toContain('initialize');
- expect(valueLine).toContain('starter');
- expect(valueLine).toContain('pack');
- expect(valueLine).toContain('scaffold');
- expect(valueLine).toContain('seed');
- });
-
- test('showInitializeStarterPack participates in hasAnyResults', () => {
- const aggregate = src.match(/const hasAnyResults =[\s\S]*?;/)?.[0] ?? '';
- expect(aggregate).toContain('showInitializeStarterPack');
- });
-});
-
-describe('New project entry (source-level guards)', () => {
- const SRC_PATH = join(__dirname, 'CommandPalette.tsx');
- const src = readFileSync(SRC_PATH, 'utf-8');
-
- const newProjectBlock = (() => {
- const chunks = src.split(/(?=<CommandItem\b)/);
- const ours = chunks.find((c) => c.includes('data-testid="command-palette-new-project"'));
- if (!ours) return '';
- return ours.split('</CommandItem>')[0] ?? '';
- })();
-
- const showCreateProjectDecision =
- src.match(/const showCreateProject =[\s\S]*?;\n {2}const showProjectOpenFolder/)?.[0] ?? '';
-
- test('CommandItem carries the Plus icon and "New project" label', () => {
- expect(newProjectBlock, 'CommandItem with command-palette-new-project not found').toBeTruthy();
- expect(newProjectBlock).toContain('<Plus');
- expect(newProjectBlock).toContain('<Trans>New project</Trans>');
- });
-
- test('onSelect closes the palette and opens CreateProjectDialog', () => {
- expect(newProjectBlock).toContain('onOpenChange(false)');
- expect(newProjectBlock).toContain('setCreateProjectOpen(true)');
- });
-
- test('is desktop-only — the visibility gate requires bridge !== null', () => {
- expect(showCreateProjectDecision).toContain('bridge !== null');
- });
-
- test('search-token value covers new / project / create / scaffold substrings', () => {
- const valueLine = newProjectBlock.match(/value="new project[^"]*"/)?.[0] ?? '';
- expect(valueLine).toContain('new');
- expect(valueLine).toContain('project');
- expect(valueLine).toContain('create');
- expect(valueLine).toContain('scaffold');
- });
-
- test('CreateProjectDialog is mounted behind a bridge guard', () => {
- expect(src).toMatch(/bridge \? \(\s*<CreateProjectDialog/);
- expect(src).toMatch(
- /import \{ CreateProjectDialog \} from '@\/components\/CreateProjectDialog'/,
- );
- });
-
- test('showCreateProject participates in hasAnyResults', () => {
- const aggregate = src.match(/const hasAnyResults =[\s\S]*?;/)?.[0] ?? '';
- expect(aggregate).toContain('showCreateProject');
- });
-
- test('New project sits inside the "Project" CommandGroup', () => {
- const newProjectIdx = src.indexOf('command-palette-new-project');
- const projectGroupIdx = src.indexOf('heading={t`Project`}');
- expect(projectGroupIdx).toBeGreaterThanOrEqual(0);
- expect(projectGroupIdx).toBeLessThan(newProjectIdx);
- });
-});
-
-describe('CommandPalette entry-point propagation (source-level guards)', () => {
- const SRC_PATH = join(__dirname, 'CommandPalette.tsx');
- const src = readFileSync(SRC_PATH, 'utf-8');
-
- test('Open Folder command tags the open call with entryPoint: "pick-existing"', () => {
- const idx = src.indexOf('command-palette-open-folder');
- expect(idx).toBeGreaterThan(0);
- const window = src.slice(Math.max(0, idx - 800), idx + 200);
- expect(window).toMatch(/bridge\.project\.open\(\{[^}]*entryPoint:\s*'pick-existing'/);
- });
-
- test('Recents row entry tags the open call with entryPoint: "recents"', () => {
- expect(src).toMatch(
- /switchableProjects[\s\S]*?bridge\.project\.open\(\{[^}]*entryPoint:\s*'recents'/,
- );
- });
-});
-
-describe('CommandPalette overlay-motion policy (source-level guards)', () => {
- const SRC_PATH = join(__dirname, 'CommandPalette.tsx');
- const src = readFileSync(SRC_PATH, 'utf-8');
-
- test('CommandDialog is mounted with no transition or placement prop', () => {
- const openingTag = src.match(/<CommandDialog\b[^>]*>/);
- expect(openingTag).not.toBeNull();
- expect(openingTag?.[0]).not.toContain('transition');
- expect(openingTag?.[0]).not.toContain('placement');
- });
-});
diff --git a/packages/app/src/components/ConsentDialogBody.dom.test.tsx b/packages/app/src/components/ConsentDialogBody.dom.test.tsx
new file mode 100644
index 000000000..bc49ebc31
--- /dev/null
+++ b/packages/app/src/components/ConsentDialogBody.dom.test.tsx
@@ -0,0 +1,150 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import type { ConsentStore } from '@/lib/consent-store';
+import type {
+ OkDesktopBridge,
+ OkOnboardingConfirmRequest,
+ OkOnboardingShowPayload,
+} from '@/lib/desktop-bridge-types';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+import ConsentDialogBody from './ConsentDialogBody';
+
+mock.module('@lingui/core/macro', () => ({
+ msg: renderLinguiTemplate,
+}));
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+const payload: OkOnboardingShowPayload = {
+ pickedPath: '/project',
+ projectDir: '/project',
+ defaultContentDir: 'docs',
+ gitState: 'present',
+ gitRootPromoted: false,
+ warnings: [],
+ editorOptions: [
+ { id: 'claude-desktop', label: 'Claude Desktop', hasProjectConfig: true },
+ { id: 'codex', label: 'Codex', hasProjectConfig: false },
+ ],
+};
+
+function setBridge(bridge: unknown) {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ writable: true,
+ value: bridge,
+ });
+}
+
+function makeStore() {
+ const confirmCalls: OkOnboardingConfirmRequest[] = [];
+ const cancelCalls: string[] = [];
+ const store: ConsentStore = {
+ install: () => undefined,
+ getSnapshot: () => payload,
+ subscribe: () => () => {},
+ confirm: async (request) => {
+ confirmCalls.push(request);
+ return { ok: true };
+ },
+ cancel: async () => {
+ cancelCalls.push('cancel');
+ return { ok: true };
+ },
+ dismiss: () => {},
+ };
+ return { store, confirmCalls, cancelCalls };
+}
+
+function renderConsentDialog() {
+ const harness = makeStore();
+ render(<ConsentDialogBody payload={payload} store={harness.store} />);
+ return harness;
+}
+
+describe('ConsentDialogBody runtime form behavior', () => {
+ afterEach(() => {
+ cleanup();
+ setBridge(undefined);
+ });
+
+ test('exports the default component', () => {
+ expect(typeof ConsentDialogBody).toBe('function');
+ });
+
+ test('Cancel is a non-submit button and invokes cancel without confirming', async () => {
+ const { confirmCalls, cancelCalls } = renderConsentDialog();
+
+ const cancel = screen.getByTestId('consent-cancel');
+ expect(cancel.getAttribute('type')).toBe('button');
+ await userEvent.click(cancel);
+
+ await waitFor(() => {
+ expect(cancelCalls).toEqual(['cancel']);
+ });
+ expect(confirmCalls).toEqual([]);
+ });
+
+ test('Start is bound to the body form and form submit prevents default before confirming', async () => {
+ const { confirmCalls } = renderConsentDialog();
+
+ const form = screen.getByTestId('consent-form') as HTMLFormElement;
+ const start = screen.getByTestId('consent-start');
+ expect(start.getAttribute('type')).toBe('submit');
+ expect(start.getAttribute('form')).toBe(form.id);
+
+ expect(fireEvent.submit(form)).toBe(false);
+ await waitFor(() => {
+ expect(confirmCalls).toHaveLength(1);
+ });
+ expect(confirmCalls[0]).toEqual({
+ initGit: true,
+ contentDir: 'docs',
+ additionalIgnores: '',
+ editorIds: ['claude-desktop', 'codex'],
+ sharing: 'shared',
+ });
+ });
+
+ test('invalid contentDir submit is default-prevented and does not confirm', async () => {
+ const { confirmCalls } = renderConsentDialog();
+
+ fireEvent.change(screen.getByTestId('consent-content-dir'), {
+ target: { value: '../secrets' },
+ });
+
+ const form = screen.getByTestId('consent-form');
+ const start = screen.getByTestId('consent-start') as HTMLButtonElement;
+ expect(start.disabled).toBe(true);
+ expect(fireEvent.submit(form)).toBe(false);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(confirmCalls).toEqual([]);
+ });
+
+ test('Browse seeds the folder picker with the project directory', async () => {
+ const openFolderCalls: Array<{ defaultPath?: string } | undefined> = [];
+ setBridge({
+ dialog: {
+ openFolder: async (opts?: { defaultPath?: string }) => {
+ openFolderCalls.push(opts);
+ return '/project/docs/notes';
+ },
+ },
+ } as Pick<OkDesktopBridge, 'dialog'>);
+ renderConsentDialog();
+
+ await userEvent.click(screen.getByTestId('consent-content-dir-browse'));
+
+ await waitFor(() => {
+ expect(openFolderCalls).toEqual([{ defaultPath: '/project' }]);
+ });
+ expect((screen.getByTestId('consent-content-dir') as HTMLInputElement).value).toBe(
+ 'docs/notes',
+ );
+ });
+});
diff --git a/packages/app/src/components/ConsentDialogBody.test.ts b/packages/app/src/components/ConsentDialogBody.test.ts
deleted file mode 100644
index d0188385e..000000000
--- a/packages/app/src/components/ConsentDialogBody.test.ts
+++ /dev/null
@@ -1,44 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './ConsentDialogBody?raw';
-
-describe('ConsentDialogBody module', () => {
- test('exports default component', async () => {
- const mod = await import('./ConsentDialogBody');
- expect(typeof mod.default).toBe('function');
- });
-});
-
-describe('ConsentDialogBody — load-bearing structural guards', () => {
- test('Cancel button is type="button" so it does not submit the form', () => {
- expect(SRC).toMatch(
- /<Button[\s\S]{0,200}?type="button"[\s\S]{0,200}?data-testid="consent-cancel"/,
- );
- });
-
- test('Start button is type="submit" so Enter-on-input routes through onSubmit', () => {
- expect(SRC).toMatch(
- /<Button[\s\S]{0,200}?type="submit"[\s\S]{0,200}?data-testid="consent-start"/,
- );
- });
-
- test('Start button form attribute binds to the form element id (cross-form submit contract)', () => {
- expect(SRC).toMatch(/<form[\s\S]{0,400}?id={formId}/);
- expect(SRC).toMatch(
- /<Button[\s\S]{0,300}?form={formId}[\s\S]{0,300}?data-testid="consent-start"/,
- );
- });
-
- test('onSubmit calls preventDefault to suppress renderer page-reload', () => {
- expect(SRC).toMatch(/function onSubmit[\s\S]{0,200}?e\.preventDefault\(\)/);
- });
-
- test('onSubmit short-circuits when startDisabled (matches Start click gate)', () => {
- expect(SRC).toMatch(/function onSubmit[\s\S]{0,200}?if \(startDisabled\) return/);
- });
-
- test('Browse button calls bridge.dialog.openFolder with payload.projectDir as defaultPath', () => {
- expect(SRC).toMatch(
- /bridge\.dialog\.openFolder\(\{\s*defaultPath:\s*payload\.projectDir\s*\}\)/,
- );
- });
-});
diff --git a/packages/app/src/components/CreateProjectDialog.runtime.dom.test.tsx b/packages/app/src/components/CreateProjectDialog.runtime.dom.test.tsx
new file mode 100644
index 000000000..4ba446a1c
--- /dev/null
+++ b/packages/app/src/components/CreateProjectDialog.runtime.dom.test.tsx
@@ -0,0 +1,219 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { ALL_EDITOR_IDS, EDITOR_LABELS } from '@inkeep/open-knowledge-core';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type {
+ OkDesktopBridge,
+ OkFolderState,
+ OkMcpWiringEditorId,
+} from '@/lib/desktop-bridge-types';
+import { CreateProjectDialog } from './CreateProjectDialog';
+
+type WindowGlobals = {
+ NodeFilter?: typeof NodeFilter;
+};
+type GlobalWithDomShims = typeof globalThis &
+ WindowGlobals & {
+ window?: WindowGlobals;
+ ResizeObserver?: unknown;
+ };
+const globalWithDomShims = globalThis as GlobalWithDomShims;
+if (
+ globalWithDomShims.NodeFilter === undefined &&
+ globalWithDomShims.window?.NodeFilter !== undefined
+) {
+ globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;
+}
+if (globalWithDomShims.ResizeObserver === undefined) {
+ class NoopResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ globalWithDomShims.ResizeObserver = NoopResizeObserver;
+}
+
+const PARENT = '/Users/test/Projects';
+const TARGET = `${PARENT}/Runtime Project`;
+const SECOND_TARGET = `${PARENT}/Second Project`;
+
+function makeBridge() {
+ let pickedPath: string | null = TARGET;
+ let folderStateImpl = async (): Promise<OkFolderState> => 'free';
+ const openFolderArgs: unknown[] = [];
+ const folderStateCalls: string[] = [];
+ const bannerCalls: string[] = [];
+ const createNewCalls: Array<{
+ parent: string;
+ name: string;
+ editors: OkMcpWiringEditorId[];
+ }> = [];
+
+ const bridge = {
+ fs: {
+ defaultProjectsRoot: mock(() => Promise.resolve(PARENT)),
+ findEnclosingProjectRoot: mock(() => Promise.resolve(null)),
+ findEnclosingGitRoot: mock(() => Promise.resolve(null)),
+ folderState: mock((path: string) => {
+ folderStateCalls.push(path);
+ return folderStateImpl(path);
+ }),
+ removeGitFolder: mock(() => Promise.resolve()),
+ },
+ dialog: {
+ openFolder: mock((options?: unknown) => {
+ openFolderArgs.push(options);
+ return Promise.resolve(pickedPath);
+ }),
+ },
+ project: {
+ recordCreateNewBannerShown: mock((banner: string) => {
+ bannerCalls.push(banner);
+ return Promise.resolve();
+ }),
+ createNew: mock(
+ (payload: { parent: string; name: string; editors: OkMcpWiringEditorId[] }) => {
+ createNewCalls.push(payload);
+ return Promise.resolve();
+ },
+ ),
+ open: mock(() => Promise.resolve()),
+ },
+ } as unknown as OkDesktopBridge;
+
+ return {
+ bridge,
+ bannerCalls,
+ createNewCalls,
+ folderStateCalls,
+ openFolderArgs,
+ setPickedPath: (next: string | null) => {
+ pickedPath = next;
+ },
+ setFolderStateImpl: (next: (path: string) => Promise<OkFolderState>) => {
+ folderStateImpl = next;
+ },
+ };
+}
+
+async function renderDialog(stub = makeBridge()) {
+ const onOpenChange = mock(() => {});
+ render(<CreateProjectDialog open={true} onOpenChange={onOpenChange} bridge={stub.bridge} />);
+ await screen.findByTestId('create-project-dialog');
+ return { ...stub, onOpenChange };
+}
+
+async function browseAndWaitForTarget(target = TARGET) {
+ fireEvent.click(screen.getByTestId('create-browse'));
+ await waitFor(
+ () => {
+ expect(screen.getByTestId('create-target-caption').textContent).toBe(target);
+ },
+ { timeout: 2000 },
+ );
+}
+
+async function waitForSubmitEnabled() {
+ await waitFor(
+ () => {
+ expect((screen.getByTestId('create-submit') as HTMLButtonElement).disabled).toBe(false);
+ },
+ { timeout: 2000 },
+ );
+}
+
+describe('CreateProjectDialog runtime wiring', () => {
+ beforeEach(() => {
+ cleanup();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('cancel, browse, editor labels, and submit are wired through the mounted form', async () => {
+ const stub = await renderDialog();
+
+ const form = screen.getByTestId('create-project-form') as HTMLFormElement;
+ const cancel = screen.getByTestId('create-cancel') as HTMLButtonElement;
+ const submit = screen.getByTestId('create-submit') as HTMLButtonElement;
+ const browse = screen.getByTestId('create-browse') as HTMLButtonElement;
+
+ expect(cancel.type).toBe('button');
+ expect(submit.type).toBe('submit');
+ expect(submit.getAttribute('form')).toBe(form.id);
+ expect(browse.type).toBe('button');
+
+ for (const id of ALL_EDITOR_IDS) {
+ const checkbox = screen.getByTestId(`create-editor-${id}`);
+ expect(checkbox.closest('label')?.textContent).toContain(EDITOR_LABELS[id]);
+ expect(checkbox.getAttribute('aria-checked')).toBe('true');
+ }
+
+ fireEvent.click(screen.getByTestId('create-editor-cursor'));
+ expect(screen.getByTestId('create-editor-cursor').getAttribute('aria-checked')).toBe('false');
+
+ fireEvent.click(cancel);
+ expect(stub.onOpenChange).toHaveBeenCalledWith(false);
+ expect(stub.createNewCalls).toEqual([]);
+
+ await browseAndWaitForTarget();
+ expect(stub.openFolderArgs.at(-1)).toEqual({ defaultPath: PARENT });
+ await waitForSubmitEnabled();
+
+ fireEvent.click(submit);
+
+ await waitFor(() => {
+ expect(stub.createNewCalls).toEqual([
+ {
+ parent: PARENT,
+ name: 'Runtime Project',
+ editors: ALL_EDITOR_IDS.filter((id) => id !== 'cursor'),
+ sharing: 'shared',
+ },
+ ]);
+ });
+ expect(stub.onOpenChange).toHaveBeenLastCalledWith(false);
+ });
+
+ test('subfolder rescue sticks through a free re-probe and resets on a fresh Browse pick', async () => {
+ const stub = makeBridge();
+ stub.setFolderStateImpl(async (path) => (path === TARGET ? 'exists-nonempty' : 'free'));
+ await renderDialog(stub);
+
+ await browseAndWaitForTarget();
+
+ await waitFor(
+ () => {
+ expect(screen.getByTestId('create-subfolder-rescue')).not.toBeNull();
+ },
+ { timeout: 2000 },
+ );
+ expect(stub.bannerCalls).toContain('nonempty');
+
+ fireEvent.change(screen.getByTestId('create-subfolder-input'), {
+ target: { value: 'Nested Notes' },
+ });
+
+ await waitFor(
+ () => {
+ expect((screen.getByTestId('create-subfolder-input') as HTMLInputElement).value).toBe(
+ 'Nested Notes',
+ );
+ expect((screen.getByTestId('create-submit') as HTMLButtonElement).disabled).toBe(false);
+ },
+ { timeout: 2000 },
+ );
+
+ stub.setPickedPath(SECOND_TARGET);
+ stub.setFolderStateImpl(async () => 'free');
+ fireEvent.click(screen.getByTestId('create-browse'));
+
+ await waitFor(
+ () => {
+ expect(screen.getByTestId('create-target-caption').textContent).toBe(SECOND_TARGET);
+ expect(screen.queryByTestId('create-subfolder-rescue')).toBeNull();
+ },
+ { timeout: 2000 },
+ );
+ });
+});
diff --git a/packages/app/src/components/CreateProjectDialog.test.tsx b/packages/app/src/components/CreateProjectDialog.test.tsx
index 0a459a94c..5865b1b56 100644
--- a/packages/app/src/components/CreateProjectDialog.test.tsx
+++ b/packages/app/src/components/CreateProjectDialog.test.tsx
@@ -7,7 +7,6 @@ import {
joinPathPreview,
parseCreateNewError,
} from './CreateProjectDialog';
-import SRC from './CreateProjectDialog?raw';
describe('joinPathPreview', () => {
test('joins parent + name with forward slash by default', () => {
@@ -230,113 +229,3 @@ describe('CreateProjectDialog module', () => {
expect(typeof mod.parseCreateNewError).toBe('function');
});
});
-
-describe('CreateProjectDialog — load-bearing structural guards', () => {
- test('Cancel button is type="button" so it does not submit the form', () => {
- expect(SRC).toMatch(
- /<Button[\s\S]{0,400}?type="button"[\s\S]{0,400}?data-testid="create-cancel"/,
- );
- });
-
- test('Submit button is type="submit" so Enter-on-input fires Create', () => {
- expect(SRC).toMatch(
- /<Button[\s\S]{0,400}?type="submit"[\s\S]{0,400}?data-testid="create-submit"/,
- );
- });
-
- test('Submit button form attribute binds to the form element id (cross-form submit contract)', () => {
- expect(SRC).toMatch(/<form[\s\S]{0,400}?id={formId}/);
- expect(SRC).toMatch(
- /<Button[\s\S]{0,400}?form={formId}[\s\S]{0,400}?data-testid="create-submit"/,
- );
- });
-
- test('Subfolder rescue sticky-promotes on block-nonempty at the probe transition', () => {
- expect(SRC).toMatch(
- /nextCascade\.kind\s*===\s*['"]block-nonempty['"][\s\S]{0,100}?setNeedsSubfolder\(true\)/,
- );
- });
-
- test('Browse re-pick resets both needsSubfolder and subfolderName', () => {
- const onBrowseBlock = SRC.match(/async function onBrowse\(\)[\s\S]{0,2500}?\n\s{2}\}/);
- expect(onBrowseBlock).not.toBeNull();
- const body = onBrowseBlock?.[0] ?? '';
- expect(body).toContain('setNeedsSubfolder(false)');
- expect(body).toContain("setSubfolderName('')");
- });
-
- test('Browse button is type="button" and calls bridge.dialog.openFolder', () => {
- expect(SRC).toMatch(
- /<Button[\s\S]{0,400}?type="button"[\s\S]{0,400}?data-testid="create-browse"/,
- );
- expect(SRC).toMatch(/bridge\.dialog\.openFolder\s*\(/);
- });
-
- test('onSubmit calls preventDefault to suppress renderer page-reload', () => {
- expect(SRC).toMatch(/onSubmit[\s\S]{0,200}?e\.preventDefault\(\)/);
- });
-
- test('Editor labels + ALL_EDITOR_IDS are sourced from @inkeep/open-knowledge-core', () => {
- expect(SRC).toMatch(/EDITOR_LABELS[\s\S]{0,400}from '@inkeep\/open-knowledge-core'/);
- expect(SRC).toMatch(/ALL_EDITOR_IDS[\s\S]{0,400}from '@inkeep\/open-knowledge-core'/);
- expect(SRC).not.toMatch(/^const EDITOR_LABELS\b/m);
- expect(SRC).not.toMatch(/^const ALL_EDITOR_IDS\b/m);
- });
-
- test('Cascade evaluator imports + uses sanitizeFolderName from core', () => {
- expect(SRC).toContain("from '@inkeep/open-knowledge-core'");
- expect(SRC).toContain('sanitizeFolderName');
- });
-
- test('Telemetry call fires bridge.project.recordCreateNewBannerShown', () => {
- expect(SRC).toContain('recordCreateNewBannerShown');
- });
-
- test('All four ALL_EDITOR_IDS rendered as checkbox rows (data-testid contract)', () => {
- expect(SRC).toMatch(/data-testid={`create-editor-\$\{id\}`}/);
- });
-
- test('Banner variants carry stable data-testids the e2e relies on', () => {
- expect(SRC).toContain('data-testid="create-banner-nested"');
- expect(SRC).toContain('data-testid="create-banner-git-confirm"');
- expect(SRC).toContain('data-testid="create-banner-nested-open"');
- expect(SRC).toContain('data-testid="create-banner-sanitize-diverged"');
- expect(SRC).toContain('data-testid="create-banner-sanitize-erased"');
- expect(SRC).not.toContain('data-testid="create-banner-nonempty"');
- expect(SRC).toContain('data-testid="create-subfolder-rescue"');
- expect(SRC).toContain('data-testid="create-subfolder-input"');
- });
-
- test('No forbidden React Compiler escape hatches (memo / useMemo / useCallback / forwardRef)', () => {
- expect(SRC).not.toMatch(/\bforwardRef\b/);
- expect(SRC).not.toMatch(/\buseMemo\b/);
- expect(SRC).not.toMatch(/\buseCallback\b/);
- expect(SRC).not.toMatch(/\bmemo\(/);
- });
-
- test('No inline style props (Tailwind via className per code-style rule)', () => {
- expect(SRC).not.toMatch(/\bstyle=\{\{/);
- });
-
- test('Open-tracking useEffect resets transient state on each open', () => {
- const block = SRC.match(/if \(!open\) return;[\s\S]{0,1500}?bridge\.fs/);
- expect(block).not.toBeNull();
- const body = block?.[0] ?? '';
- expect(body).toContain('setBusy(false)');
- expect(body).toContain("setPicked('')");
- expect(body).toContain("setDefaultPath('')");
- expect(body).toContain('setEditorIds(new Set(ALL_EDITOR_IDS))');
- });
-
- test('dialog renders a single Location affordance, no Name <Input>', () => {
- expect(SRC).not.toMatch(/<Input[\s\S]{0,400}?id="create-name"/);
- expect(SRC).not.toMatch(/data-testid="create-name"/);
- expect(SRC).toContain('data-testid="create-browse"');
- expect(SRC).toContain('data-testid="create-target-caption"');
- });
-
- test('submit handler derives parent + name from the picked target', () => {
- expect(SRC).not.toMatch(/\bconst \[name, setName\] = useState/);
- expect(SRC).not.toMatch(/\bconst \[parent, setParent\] = useState/);
- });
-});
diff --git a/packages/app/src/components/DocPanel.dom.test.tsx b/packages/app/src/components/DocPanel.dom.test.tsx
index 27194bec9..8266a4f1f 100644
--- a/packages/app/src/components/DocPanel.dom.test.tsx
+++ b/packages/app/src/components/DocPanel.dom.test.tsx
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
import { TooltipProvider } from '@/components/ui/tooltip';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
type WindowGlobals = { NodeFilter?: typeof NodeFilter };
type GlobalWithDomShims = typeof globalThis &
@@ -19,14 +20,10 @@ if (g.ResizeObserver === undefined) {
g.ResizeObserver = NoopResizeObserver;
}
-function passthroughT(strings: TemplateStringsArray | string, ...values: unknown[]): string {
- if (typeof strings === 'string') return strings;
- return strings.reduce((out, s, i) => out + s + (i < values.length ? String(values[i]) : ''), '');
-}
-mock.module('@lingui/core/macro', () => ({ t: passthroughT }));
+mock.module('@lingui/core/macro', () => ({ t: renderLinguiTemplate }));
mock.module('@lingui/react/macro', () => ({
Trans: ({ children }: { children: ReactNode }) => children,
- useLingui: () => ({ t: passthroughT }),
+ useLingui: () => ({ t: renderLinguiTemplate }),
}));
let singleFileValue = false;
diff --git a/packages/app/src/components/EditorActivityPool.warm-skeleton.dom.test.tsx b/packages/app/src/components/EditorActivityPool.warm-skeleton.dom.test.tsx
index 5fa2c882d..c7d8b88e4 100644
--- a/packages/app/src/components/EditorActivityPool.warm-skeleton.dom.test.tsx
+++ b/packages/app/src/components/EditorActivityPool.warm-skeleton.dom.test.tsx
@@ -10,6 +10,7 @@ import {
type RenameSnapshot,
storeRenameSnapshot,
} from '@/editor/editor-cache';
+import { expectVisualClassTokens } from '@/test-utils/visual-contract';
function WarmContentFallbackReplica({ html }: { html: string }) {
return (
@@ -67,9 +68,7 @@ describe('WarmContentFallback DOM geometry', () => {
const { container } = render(<WarmContentFallbackReplica html="<p>hello</p>" />);
const outer = container.firstElementChild as HTMLElement;
expect(outer.tagName).toBe('DIV');
- expect(outer.className).toContain('tiptap-editor');
- expect(outer.className).toContain('h-full');
- expect(outer.className).toContain('pointer-events-none');
+ expectVisualClassTokens(outer.className, ['tiptap-editor', 'h-full', 'pointer-events-none']);
expect(outer.getAttribute('aria-hidden')).toBe('true');
});
@@ -78,9 +77,11 @@ describe('WarmContentFallback DOM geometry', () => {
const outer = container.firstElementChild as HTMLElement;
const inner = outer.firstElementChild as HTMLElement;
expect(inner.tagName).toBe('DIV');
- expect(inner.className).toContain('tiptap');
- expect(inner.className).toContain('ProseMirror');
- expect(inner.className).toContain('tiptap-editor-portal-content');
+ expectVisualClassTokens(inner.className, [
+ 'tiptap',
+ 'ProseMirror',
+ 'tiptap-editor-portal-content',
+ ]);
});
test('inner div renders provided html as child content', () => {
diff --git a/packages/app/src/components/EditorArea.dom.test.tsx b/packages/app/src/components/EditorArea.dom.test.tsx
new file mode 100644
index 000000000..5118d5d1b
--- /dev/null
+++ b/packages/app/src/components/EditorArea.dom.test.tsx
@@ -0,0 +1,122 @@
+import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+
+type SettingsDialogShellProps = {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+};
+
+let settingsRouteOpen = false;
+let closeSettingsRouteMock = mock(() => {});
+let shellProps: SettingsDialogShellProps[] = [];
+
+mock.module('@/lib/perf', () => ({
+ mark: () => {},
+ ProfilerBoundary: ({ children }: { children: ReactNode }) => children,
+}));
+
+mock.module('@/components/PropertyContext', () => ({
+ PropertyProvider: ({ children }: { children: ReactNode }) => children,
+ useProperties: () => ({ requestAddProperty: () => {} }),
+}));
+
+mock.module('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({
+ activeDocName: 'folder/index',
+ activeProvider: null,
+ activeTarget: { kind: 'folder', target: 'folder', folderPath: 'folder' },
+ recycleDocument: () => {},
+ docPanelMode: 'timeline',
+ docPanelAgentId: null,
+ docPanelExpandSignal: 0,
+ }),
+ useDocumentTransition: () => ({ openDocumentTransition: null }),
+}));
+
+mock.module('react-resizable-panels', () => ({
+ usePanelRef: () => ({
+ current: {
+ collapse: () => {},
+ expand: () => {},
+ },
+ }),
+}));
+
+mock.module('@/hooks/use-doc-panel-layout', () => ({
+ useDocPanelLayout: () => ({ layout: 'panel', autoCollapse: false }),
+}));
+
+mock.module('@/hooks/use-document-stats', () => ({
+ useDocumentStats: () => null,
+}));
+
+mock.module('@/hooks/use-lifecycle-status', () => ({
+ useLifecycleStatus: () => 'ready',
+}));
+
+mock.module('@/presence/use-sync-status', () => ({
+ useSyncStatus: () => 'synced',
+}));
+
+mock.module('@/components/FolderOverview', () => ({
+ FolderOverview: ({ folderPath }: { folderPath: string }) => (
+ <div data-testid="folder-overview">{folderPath}</div>
+ ),
+}));
+
+mock.module('@/components/settings/SettingsDialogShell', () => ({
+ SettingsDialogShell: (props: SettingsDialogShellProps) => {
+ shellProps.push(props);
+ return <div data-testid="settings-shell" data-open={String(props.open)} />;
+ },
+}));
+
+mock.module('@/lib/use-settings-route', () => ({
+ useSettingsRoute: () => ({
+ open: settingsRouteOpen,
+ close: closeSettingsRouteMock,
+ }),
+}));
+
+const { EditorArea } = await import('./EditorArea');
+
+function renderEditorArea() {
+ return render(
+ <EditorArea
+ editorMode="wysiwyg"
+ onModeChange={() => {}}
+ activeTab="timeline"
+ onActiveTabChange={() => {}}
+ onSaveVersion={() => {}}
+ saving={false}
+ />,
+ );
+}
+
+describe('EditorArea SettingsDialogPortal runtime wiring', () => {
+ beforeEach(() => {
+ cleanup();
+ settingsRouteOpen = false;
+ closeSettingsRouteMock = mock(() => {});
+ shellProps = [];
+ });
+
+ test('mounts the Settings shell while closed and delegates close to useSettingsRoute', () => {
+ renderEditorArea();
+
+ expect(screen.getByTestId('folder-overview').textContent).toBe('folder');
+ expect(screen.getByTestId('settings-shell').getAttribute('data-open')).toBe('false');
+ expect(shellProps.at(-1)?.open).toBe(false);
+
+ act(() => {
+ shellProps.at(-1)?.onOpenChange(true);
+ });
+ expect(closeSettingsRouteMock).not.toHaveBeenCalled();
+
+ act(() => {
+ shellProps.at(-1)?.onOpenChange(false);
+ });
+ expect(closeSettingsRouteMock).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/app/src/components/EditorArea.test.ts b/packages/app/src/components/EditorArea.test.ts
index bf5196003..b409a2f13 100644
--- a/packages/app/src/components/EditorArea.test.ts
+++ b/packages/app/src/components/EditorArea.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, test } from 'bun:test';
-import SRC from './EditorArea?raw';
describe('EditorArea module', () => {
test('exports EditorArea component', async () => {
@@ -7,34 +6,3 @@ describe('EditorArea module', () => {
expect(typeof mod.EditorArea).toBe('function');
});
});
-
-describe('EditorArea SettingsDialogPortal source-level guards', () => {
- test('imports SettingsDialogShell synchronously (not via React.lazy)', () => {
- expect(SRC).toMatch(
- /import\s+\{\s*SettingsDialogShell\s*\}\s+from\s+['"]@\/components\/settings\/SettingsDialogShell['"]/,
- );
- expect(SRC).not.toMatch(/lazy\(\s*\(\s*\)\s*=>\s*import\(['"]@\/components\/settings/);
- expect(SRC).not.toMatch(/m\.SettingsDialogShell/);
- });
-
- test('the Settings portal never lazy-loads the Settings chunk', () => {
- expect(SRC).toMatch(/import\s+\{[^}]*\}\s+from\s+['"]react['"]/);
- expect(SRC).not.toMatch(/lazy\([\s\S]{0,160}?import\(\s*['"]@\/components\/settings/);
- });
-
- test('no `<Suspense fallback={null}>` wrapper around the shell', () => {
- expect(SRC).not.toMatch(/<Suspense\s+fallback=\{null\}/);
- });
-
- test('SettingsDialogPortal mounts the shell directly with no first-open gate', () => {
- expect(SRC).not.toMatch(/\bhasOpened\b/);
- expect(SRC).not.toMatch(/setHasOpened\b/);
- expect(SRC).toMatch(/function\s+SettingsDialogPortal\s*\(/);
- expect(SRC).toMatch(/useSettingsRoute\(\)/);
- expect(SRC).toMatch(/<SettingsDialogShell\b[\s\S]*?open=\{settingsRoute\.open\}/);
- });
-
- test('close path delegates to settingsRoute.close()', () => {
- expect(SRC).toMatch(/onOpenChange=\{[\s\S]*?settingsRoute\.close\(\)/);
- });
-});
diff --git a/packages/app/src/components/EditorBreadcrumb.dom.test.tsx b/packages/app/src/components/EditorBreadcrumb.dom.test.tsx
index dfad894ff..21bc8c5ee 100644
--- a/packages/app/src/components/EditorBreadcrumb.dom.test.tsx
+++ b/packages/app/src/components/EditorBreadcrumb.dom.test.tsx
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
+import { expectVisualClassTokens } from '@/test-utils/visual-contract';
import { EditorBreadcrumb } from './EditorBreadcrumb';
describe('EditorBreadcrumb (Tier-3 mount)', () => {
@@ -22,6 +23,7 @@ describe('EditorBreadcrumb (Tier-3 mount)', () => {
const nav = screen.getByRole('navigation', { name: /breadcrumb/i });
expect(nav).toBeTruthy();
+ expectVisualClassTokens(nav.className, ['min-w-0']);
const itemEls = nav.querySelectorAll('li[data-slot="breadcrumb-item"]');
expect(itemEls.length).toBe(3);
@@ -34,6 +36,11 @@ describe('EditorBreadcrumb (Tier-3 mount)', () => {
const list = nav.querySelector('ol[data-slot="breadcrumb-list"]');
expect(list?.firstElementChild?.getAttribute('data-slot')).toBe('breadcrumb-item');
+ expectVisualClassTokens(list?.className, [
+ 'text-muted-foreground/70',
+ 'text-xs',
+ 'overflow-hidden',
+ ]);
});
test('renders the basename folder for a one-deep docName', () => {
@@ -57,6 +64,27 @@ describe('EditorBreadcrumb (Tier-3 mount)', () => {
expect(titleHosts[1]?.getAttribute('title')).toBe('another-folder');
});
+ test('deep paths collapse middle segments into an accessible ellipsis', () => {
+ render(<EditorBreadcrumb docName="one/two/three/four/five/six/notes" />);
+
+ const nav = screen.getByRole('navigation', { name: /breadcrumb/i });
+ const itemEls = Array.from(
+ nav.querySelectorAll<HTMLLIElement>('li[data-slot="breadcrumb-item"]'),
+ );
+ expect(itemEls.map((li) => li.textContent)).toEqual([
+ 'one',
+ 'two / three / four',
+ 'five',
+ 'six',
+ ]);
+
+ const ellipsis = itemEls[1];
+ expect(ellipsis?.querySelector('[aria-hidden="true"]')?.getAttribute('title')).toBe(
+ 'two / three / four',
+ );
+ expect(ellipsis?.querySelector('.sr-only')?.textContent).toBe('two / three / four');
+ });
+
test('reactivity: changing docName re-renders with new segments', () => {
const { rerender } = render(<EditorBreadcrumb docName="alpha/notes" />);
let nav = screen.getByRole('navigation', { name: /breadcrumb/i });
diff --git a/packages/app/src/components/EditorBreadcrumb.test.ts b/packages/app/src/components/EditorBreadcrumb.test.ts
deleted file mode 100644
index d56ea079e..000000000
--- a/packages/app/src/components/EditorBreadcrumb.test.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './EditorBreadcrumb?raw';
-
-describe('EditorBreadcrumb module', () => {
- test('exports the EditorBreadcrumb component', async () => {
- const mod = await import('./EditorBreadcrumb');
- expect(typeof mod.EditorBreadcrumb).toBe('function');
- });
-
- test('returns null for nullish docName', async () => {
- const { EditorBreadcrumb } = await import('./EditorBreadcrumb');
- expect(EditorBreadcrumb({ docName: null })).toBeNull();
- });
-
- test('returns null for project-root docName (no folder prefix)', async () => {
- const { EditorBreadcrumb } = await import('./EditorBreadcrumb');
- expect(EditorBreadcrumb({ docName: 'notes' })).toBeNull();
- expect(EditorBreadcrumb({ docName: '' })).toBeNull();
- });
-});
-
-describe('EditorBreadcrumb source-level guards', () => {
- test('derives folder segments via the shared tabParts parser', () => {
- expect(SRC).toMatch(/from\s+['"]@\/editor\/editor-tabs['"]/);
- expect(SRC).toContain('tabParts(docName,');
- });
-
- test('renders nothing at the project root', () => {
- expect(SRC).toContain('if (!docName) return null');
- expect(SRC).toContain('if (!prefix) return null');
- });
-
- test('uses the shadcn Breadcrumb primitive (Breadcrumb + List + Item + Page + Separator)', () => {
- expect(SRC).toMatch(
- /import\s+\{[\s\S]*?Breadcrumb[\s\S]*?\}\s+from\s+['"]@\/components\/ui\/breadcrumb['"]/,
- );
- expect(SRC).toContain('Breadcrumb');
- expect(SRC).toContain('BreadcrumbList');
- expect(SRC).toContain('BreadcrumbItem');
- expect(SRC).toContain('BreadcrumbPage');
- expect(SRC).toContain('BreadcrumbSeparator');
- });
-
- test('separator is BreadcrumbSeparator — NOT a raw ChevronRight import', () => {
- expect(SRC).not.toMatch(
- /import\s+\{[^}]*\bChevronRight\b[^}]*\}\s+from\s+['"]lucide-react['"]/,
- );
- expect(SRC).not.toMatch(/<ChevronRight\b/);
- });
-
- test('uses BreadcrumbPage primitive — pure display, never the link variant', () => {
- expect(SRC).toContain('BreadcrumbPage');
- const importLine = SRC.match(
- /import\s*\{[^}]*\}\s*from\s*['"]@\/components\/ui\/breadcrumb['"]/,
- );
- expect(importLine?.[0]).not.toMatch(/\bBreadcrumbLink\b/);
- expect(SRC).not.toMatch(/<BreadcrumbLink\b/);
- });
-
- test('uses the shared text-xs + text-muted-foreground/70 token pair', () => {
- expect(SRC).toContain('text-muted-foreground/70');
- expect(SRC).toContain('text-xs');
- });
-
- test('per-segment truncation surfaces a title tooltip for full text', () => {
- expect(SRC).toMatch(/title=\{node\.value\}/);
- expect(SRC).toContain('truncate');
- });
-
- test('pure display — no onClick / onMouseEnter / role="button" navigation handlers', () => {
- expect(SRC).not.toContain('onClick');
- expect(SRC).not.toContain('onMouseEnter');
- expect(SRC).not.toMatch(/role=['"]button['"]/);
- });
-});
diff --git a/packages/app/src/components/EditorHeader.dom.test.tsx b/packages/app/src/components/EditorHeader.dom.test.tsx
new file mode 100644
index 000000000..812ad64b6
--- /dev/null
+++ b/packages/app/src/components/EditorHeader.dom.test.tsx
@@ -0,0 +1,218 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+import type { HandoffDispatchInput } from './handoff/useHandoffDispatch';
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+let activeDocName: string | null = 'docs/notes';
+let activeTarget: unknown = { kind: 'doc' };
+let sidebarState: 'expanded' | 'collapsed' = 'expanded';
+let workspace: { contentDir: string; pathSeparator: string } | null = {
+ contentDir: '/tmp/project',
+ pathSeparator: '/',
+};
+let latestHandoffInput: HandoffDispatchInput | null | undefined;
+
+mock.module('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({ activeDocName, activeTarget }),
+}));
+
+mock.module('@/lib/use-workspace', () => ({
+ useWorkspace: () => workspace,
+}));
+
+mock.module('@/components/ui/sidebar', () => ({
+ useSidebar: () => ({ state: sidebarState }),
+ SidebarTrigger: ({ className }: { className?: string }) => (
+ <button type="button" data-testid="sidebar-trigger" className={className}>
+ sidebar
+ </button>
+ ),
+}));
+
+mock.module('./EditorTabs', () => ({
+ EditorTabs: () => <div data-testid="editor-tabs" />,
+}));
+
+mock.module('./handoff/OpenInAgentMenu', () => ({
+ OpenInAgentMenu: ({ input }: { input: HandoffDispatchInput | null }) => {
+ latestHandoffInput = input;
+ return <div data-testid="open-in-agent-menu" data-has-input={String(input !== null)} />;
+ },
+}));
+
+mock.module('./ShareButton', () => ({
+ ShareButton: () => <button type="button">Share</button>,
+}));
+
+mock.module('./PublishToGitHubDialog', () => ({
+ PublishToGitHubDialog: ({ open }: { open: boolean }) => (
+ <div data-testid="publish-dialog" data-open={String(open)} />
+ ),
+}));
+
+mock.module('./SyncStatusBadge', () => ({
+ SyncStatusBadge: () => <div data-testid="sync-status-badge" />,
+}));
+
+mock.module('@/presence/PresenceBar', () => ({
+ PresenceBar: () => <div data-testid="presence-bar" />,
+}));
+
+mock.module('./BetaBadge', () => ({
+ BetaBadge: () => <div data-testid="beta-badge" />,
+}));
+
+mock.module('./SettingsButton', () => ({
+ SettingsButton: () => <button type="button">Settings</button>,
+}));
+
+mock.module('./HelpPopover', () => ({
+ HelpPopover: () => <button type="button">Resources</button>,
+}));
+
+function setElectronHost(enabled: boolean) {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: enabled ? {} : undefined,
+ });
+}
+
+async function renderHeader() {
+ const { EditorHeader } = await import('./EditorHeader');
+ render(
+ <TooltipProvider>
+ <EditorHeader />
+ </TooltipProvider>,
+ );
+ return document.querySelector('header') as HTMLElement;
+}
+
+describe('EditorHeader runtime behavior', () => {
+ afterEach(() => {
+ cleanup();
+ setElectronHost(false);
+ activeDocName = 'docs/notes';
+ activeTarget = { kind: 'doc' };
+ sidebarState = 'expanded';
+ workspace = { contentDir: '/tmp/project', pathSeparator: '/' };
+ latestHandoffInput = undefined;
+ });
+
+ test('exports the EditorHeader component', async () => {
+ const mod = await import('./EditorHeader');
+ expect(typeof mod.EditorHeader).toBe('function');
+ });
+
+ test('web host keeps baseline header layout without Electron drag treatment', async () => {
+ setElectronHost(false);
+ sidebarState = 'collapsed';
+ const header = await renderHeader();
+
+ expect(header.getAttribute('data-electron-drag')).toBeNull();
+ expectVisualClassTokens(header.className, [
+ 'flex',
+ 'h-12',
+ 'shrink-0',
+ 'items-center',
+ 'shadow-[inset_0_-1px_0_var(--border)]',
+ ]);
+ expectVisualClassTokensAbsent(header.className, ['[-webkit-app-region:drag]', 'pl-[78px]']);
+ expectVisualClassTokensAbsent(screen.getByTestId('sidebar-trigger').className, [
+ '[-webkit-app-region:no-drag]',
+ ]);
+ });
+
+ test('Electron collapsed-sidebar host enables drag region and traffic-light reserve', async () => {
+ setElectronHost(true);
+ sidebarState = 'collapsed';
+ const header = await renderHeader();
+
+ expect(header.getAttribute('data-electron-drag')).toBe('');
+ expectVisualClassTokens(header.className, [
+ '[-webkit-app-region:drag]',
+ 'pl-[78px]',
+ 'motion-safe:transition-[padding]',
+ ]);
+ expectVisualClassTokens(screen.getByTestId('sidebar-trigger').className, [
+ '[-webkit-app-region:no-drag]',
+ ]);
+ const rightZone = header.children.item(1) as HTMLElement;
+ expectVisualClassTokens(rightZone.className, ['[&>*]:[-webkit-app-region:no-drag]']);
+ });
+
+ test('Electron expanded sidebar keeps drag region but does not reserve traffic-light padding', async () => {
+ setElectronHost(true);
+ sidebarState = 'expanded';
+ const header = await renderHeader();
+
+ expectVisualClassTokens(header.className, ['[-webkit-app-region:drag]']);
+ expectVisualClassTokensAbsent(header.className, ['pl-[78px]']);
+ });
+
+ test('renders tabs and action cluster without project or asset-title chrome', async () => {
+ await renderHeader();
+
+ expect(screen.getByTestId('editor-tabs')).toBeTruthy();
+ expect(screen.getByTestId('open-in-agent-menu')).toBeTruthy();
+ expect(screen.queryByText('projectName')).toBeNull();
+ expect(screen.queryByText('assetFileName')).toBeNull();
+ });
+
+ test('document target builds file-scope handoff input', async () => {
+ activeDocName = 'docs/notes';
+ activeTarget = { kind: 'doc' };
+ await renderHeader();
+
+ expect(latestHandoffInput?.docContext).toEqual({ relativePath: 'docs/notes.md' });
+ expect(latestHandoffInput?.docPath).toBe('/tmp/project/docs/notes.md');
+ });
+
+ test('folder target builds folder-scope handoff input', async () => {
+ activeDocName = null;
+ activeTarget = { kind: 'folder', folderPath: 'team' };
+ await renderHeader();
+
+ expect(latestHandoffInput).toMatchObject({
+ docContext: null,
+ folderRelativePath: 'team',
+ projectDir: '/tmp/project',
+ docPath: '',
+ });
+ });
+
+ test('null target builds project-scope handoff input so the menu still renders', async () => {
+ activeDocName = null;
+ activeTarget = null;
+ await renderHeader();
+
+ expect(screen.getByTestId('open-in-agent-menu')).toBeTruthy();
+ expect(latestHandoffInput).toMatchObject({
+ docContext: null,
+ projectDir: '/tmp/project',
+ docPath: '',
+ });
+ });
+
+ test('workspace-missing folder scope disables handoff without hiding the menu', async () => {
+ activeDocName = null;
+ activeTarget = { kind: 'folder', folderPath: 'team' };
+ workspace = null;
+ await renderHeader();
+
+ expect(screen.getByTestId('open-in-agent-menu').getAttribute('data-has-input')).toBe('false');
+ expect(latestHandoffInput).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/EditorHeader.test.ts b/packages/app/src/components/EditorHeader.test.ts
deleted file mode 100644
index 2ff66ad79..000000000
--- a/packages/app/src/components/EditorHeader.test.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './EditorHeader?raw';
-
-describe('EditorHeader module', () => {
- test('exports the EditorHeader component', async () => {
- const mod = await import('./EditorHeader');
- expect(typeof mod.EditorHeader).toBe('function');
- });
-});
-
-describe('EditorHeader source-level guards — chrome-row retrofit', () => {
- test('detects Electron host via the canonical window.okDesktop != null idiom', () => {
- expect(SRC).toMatch(
- /typeof\s+window\s*!==\s*['"]undefined['"]\s*&&\s*window\.okDesktop\s*!=\s*null/,
- );
- expect(SRC).toContain('const isElectronHost');
- });
-
- test('drag region opts in always-on in Electron mode (sidebar state independent)', () => {
- expect(SRC).toMatch(/isElectronHost\s*&&\s*['"]\[-webkit-app-region:drag\]['"]/);
- });
-
- test('header element carries data-electron-drag so the globals.css `:has()` rule can target it', () => {
- expect(SRC).toMatch(
- /data-electron-drag=\{\s*isElectronHost\s*\?\s*['"]['"]\s*:\s*undefined\s*\}/,
- );
- });
-
- test('traffic-light reserve only engages when sidebar is collapsed (offcanvas)', () => {
- expect(SRC).toContain("const isCollapsed = sidebarState === 'collapsed';");
- expect(SRC).toMatch(/isElectronHost\s*&&\s*isCollapsed\s*&&\s*['"]pl-\[78px\]['"]/);
- });
-
- test('animates the traffic-light-reserve change with shadcn sidebar timing', () => {
- expect(SRC).toMatch(
- /motion-safe:transition-\[padding\]\s+motion-safe:duration-200\s+motion-safe:ease-linear/,
- );
- });
-
- test('SidebarTrigger opts out of drag region in Electron mode (interactive child)', () => {
- expect(SRC).toMatch(
- /SidebarTrigger[\s\S]*?isElectronHost\s*&&\s*['"]\[-webkit-app-region:no-drag\]['"]/,
- );
- });
-
- test('right zone uses [&>*] child combinator to opt every direct child out of drag region', () => {
- expect(SRC).toMatch(/isElectronHost\s*&&\s*['"]\[&>\*\]:\[-webkit-app-region:no-drag\]['"]/);
- });
-
- test('cn helper from @/lib/utils is used to compose conditional classes', () => {
- expect(SRC).toMatch(/from\s+['"]@\/lib\/utils['"]/);
- expect(SRC).toContain('cn(');
- });
-
- test('does NOT introduce a new <AppTopBar /> component (EditorHeader IS the chrome row)', () => {
- expect(SRC).not.toMatch(/AppTopBar/);
- });
-
- test('does NOT add a project name to EditorHeader (project name lives in FileSidebar header)', () => {
- expect(SRC).not.toMatch(/projectName/);
- });
-
- test('does NOT render a separate asset title outside EditorTabs', () => {
- expect(SRC).not.toMatch(/isAssetTarget|assetFileName|assetPrefix/);
- expect(SRC).toContain('<EditorTabs />');
- });
-
- test('header root retains structural layout primitives (h-12 + flex + items-center)', () => {
- expect(SRC).toMatch(/flex h-12 shrink-0 items-center/);
- });
-
- test('header root applies a divider treatment between header and editor body', () => {
- expect(SRC).toMatch(/border-b|shadow-\[inset_0_-1px_0_var\(--border\)\]/);
- });
-});
-
-describe('EditorHeader — sparkle icon 3-scope dispatch (US-011 source-level)', () => {
- test('imports all three handoff input helpers — file, folder, project scopes', () => {
- expect(SRC).toContain('buildHandoffInput');
- expect(SRC).toContain('buildFolderHandoffInput');
- expect(SRC).toContain('buildProjectScopedHandoffInput');
- });
-
- test('destructures activeTarget alongside activeDocName from useDocumentContext', () => {
- expect(SRC).toMatch(
- /const\s*\{\s*activeDocName\s*,\s*activeTarget\s*\}\s*=\s*useDocumentContext\(\)/,
- );
- });
-
- test('handoffInput is built via an IIFE that switches on activeTarget shape', () => {
- expect(SRC).toMatch(
- /const\s+handoffInput\s*:\s*HandoffDispatchInput\s*\|\s*null\s*=\s*\(\(\)\s*=>/,
- );
- });
-
- test('null activeTarget routes to buildProjectScopedHandoffInput (project scope)', () => {
- expect(SRC).toMatch(
- /if\s*\(\s*activeTarget\s*===\s*null\s*\)[\s\S]{0,80}buildProjectScopedHandoffInput/,
- );
- });
-
- test('folder kind routes to buildFolderHandoffInput with folderRelativePath', () => {
- expect(SRC).toMatch(
- /activeTarget\.kind\s*===\s*['"]folder['"][\s\S]*?buildFolderHandoffInput\s*\(\s*\{[\s\S]*?folderRelativePath:\s*activeTarget\.folderPath/,
- );
- });
-
- test('folder scope short-circuits to null when workspace is not yet resolved', () => {
- expect(SRC).toMatch(
- /activeTarget\.kind\s*===\s*['"]folder['"][\s\S]*?if\s*\(\s*!workspace\s*\)\s*return\s+null/,
- );
- });
-
- test('fallback (doc / folder-index / missing / asset) routes to buildHandoffInput', () => {
- expect(SRC).toMatch(/return\s+buildHandoffInput\s*\(\s*\{\s*docName:\s*activeDocName/);
- });
-
- test('OpenInAgentMenu has no activeDocName gate (renders across all scopes in project mode)', () => {
- expect(SRC).not.toMatch(/activeDocName\s*&&\s*<OpenInAgentMenu/);
- expect(SRC).toMatch(/<OpenInAgentMenu[\s\S]*?input=\{menuHandoffInput\}/);
- });
-
- test('agent handoff + share surfaces are gated out of single-file mode', () => {
- expect(SRC).toMatch(
- /\{!singleFile\s*&&\s*\([\s\S]*?<OpenInAgentMenu[\s\S]*?<ShareButton[\s\S]*?<PublishToGitHubDialog[\s\S]*?\)\}/,
- );
- });
-
- test('builds a shareInput: ShareTargetInput | null via an IIFE mirroring handoffInput (US-012)', () => {
- expect(SRC).toContain('buildDocShareInput');
- expect(SRC).toContain('buildFolderShareInput');
- expect(SRC).toMatch(/const\s+shareInput\s*:\s*ShareTargetInput\s*\|\s*null\s*=\s*\(\(\)\s*=>/);
- });
-
- test('folder-active routes shareInput to buildFolderShareInput with the folderPath', () => {
- expect(SRC).toMatch(
- /activeTarget\?\.kind\s*===\s*['"]folder['"][\s\S]{0,80}buildFolderShareInput\s*\(\s*activeTarget\.folderPath/,
- );
- });
-
- test('active-doc (non-folder) routes shareInput to buildDocShareInput; otherwise null', () => {
- expect(SRC).toMatch(
- /if\s*\(\s*activeDocName\s*\)[\s\S]{0,60}buildDocShareInput\s*\(\s*activeDocName/,
- );
- expect(SRC).toMatch(/return\s+null;[\s\S]{0,40}\}\)\(\);/);
- });
-
- test('ShareButton receives the shareInput prop (always-render-but-disable-when-null contract)', () => {
- expect(SRC).toMatch(
- /<ShareButton\s+input=\{shareInput\}\s+onClickWhenNoRemote=\{[\s\S]*?\}\s*\/>/,
- );
- });
-
- test('Save-version control is NOT in the header (moved to the timeline pane)', () => {
- expect(SRC).not.toMatch(/Checkpoint version/);
- expect(SRC).not.toMatch(/onSaveVersion/);
- });
-});
diff --git a/packages/app/src/components/EditorPane.dom.test.tsx b/packages/app/src/components/EditorPane.dom.test.tsx
new file mode 100644
index 000000000..dd388f56a
--- /dev/null
+++ b/packages/app/src/components/EditorPane.dom.test.tsx
@@ -0,0 +1,128 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+let hasRemote = false;
+let projectLocalSynced = false;
+let projectLocalConfig: { autoSync?: { enabled?: boolean | null } } | null = null;
+
+mock.module('@/hooks/use-git-sync-status', () => ({
+ useGitSyncStatus: () => ({
+ hasRemote,
+ pushPermission: { checkStatus: 'allowed' },
+ }),
+}));
+
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({ projectLocalConfig, projectLocalSynced }),
+}));
+
+mock.module('@/lib/use-workspace', () => ({
+ useWorkspace: () => ({ contentDir: '/tmp/project', pathSeparator: '/' }),
+}));
+
+mock.module('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({ activeDocName: 'docs/notes', collabUrl: 'ws://test' }),
+}));
+
+mock.module('@/editor/use-editor-mode', () => ({
+ useEditorMode: () => ['wysiwyg', () => {}],
+}));
+
+mock.module('./EditorHeader', () => ({
+ EditorHeader: () => <div data-testid="editor-header" />,
+}));
+
+mock.module('./EditorArea', () => ({
+ EditorArea: () => <div data-testid="editor-area" />,
+}));
+
+mock.module('./AuthModal', () => ({
+ AuthModal: () => <div data-testid="auth-modal" />,
+}));
+
+mock.module('@/editor/components/TagDialog', () => ({
+ TagDialog: () => <div data-testid="tag-dialog" />,
+}));
+
+mock.module('./AutoSyncOnboardingDialog', () => ({
+ AutoSyncOnboardingDialog: ({ open, onResolved }: { open: boolean; onResolved: () => void }) => (
+ <button
+ type="button"
+ data-testid="auto-sync-onboarding"
+ data-open={String(open)}
+ onClick={onResolved}
+ >
+ Auto sync onboarding
+ </button>
+ ),
+}));
+
+async function renderEditorPane() {
+ const { EditorPane } = await import('./EditorPane');
+ render(<EditorPane />);
+}
+
+describe('EditorPane auto-sync onboarding gate', () => {
+ afterEach(() => {
+ cleanup();
+ hasRemote = false;
+ projectLocalSynced = false;
+ projectLocalConfig = null;
+ });
+
+ test('exports the EditorPane component', async () => {
+ const mod = await import('./EditorPane');
+ expect(typeof mod.EditorPane).toBe('function');
+ });
+
+ test('opens only when remote exists, project-local config is synced, and autoSync.enabled is null', async () => {
+ hasRemote = true;
+ projectLocalSynced = true;
+ projectLocalConfig = { autoSync: { enabled: null } };
+
+ await renderEditorPane();
+
+ expect(screen.getByTestId('auto-sync-onboarding').getAttribute('data-open')).toBe('true');
+ });
+
+ test.each([
+ ['no remote', false, true, { autoSync: { enabled: null } }],
+ ['project-local config not synced', true, false, { autoSync: { enabled: null } }],
+ ['project-local config missing', true, true, null],
+ ['enabled true already answered', true, true, { autoSync: { enabled: true } }],
+ ['enabled false already answered', true, true, { autoSync: { enabled: false } }],
+ ['enabled undefined is not the unanswered sentinel', true, true, { autoSync: {} }],
+ ] as const)('stays closed when %s', async (_label, nextHasRemote, nextSynced, nextProjectLocalConfig) => {
+ hasRemote = nextHasRemote;
+ projectLocalSynced = nextSynced;
+ projectLocalConfig = nextProjectLocalConfig;
+
+ await renderEditorPane();
+
+ expect(screen.getByTestId('auto-sync-onboarding').getAttribute('data-open')).toBe('false');
+ });
+
+ test('resolved onboarding dismisses the dialog in the same render path', async () => {
+ hasRemote = true;
+ projectLocalSynced = true;
+ projectLocalConfig = { autoSync: { enabled: null } };
+ await renderEditorPane();
+
+ const dialog = screen.getByTestId('auto-sync-onboarding');
+ expect(dialog.getAttribute('data-open')).toBe('true');
+
+ await userEvent.click(dialog);
+
+ expect(screen.getByTestId('auto-sync-onboarding').getAttribute('data-open')).toBe('false');
+ });
+});
diff --git a/packages/app/src/components/EditorPane.test.ts b/packages/app/src/components/EditorPane.test.ts
deleted file mode 100644
index 98bb89768..000000000
--- a/packages/app/src/components/EditorPane.test.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import { shouldShowAutoSyncOnboarding } from './auto-sync-onboarding-gate';
-
-describe('EditorPane module', () => {
- test('exports the EditorPane component', async () => {
- const mod = await import('./EditorPane');
- expect(typeof mod.EditorPane).toBe('function');
- });
-});
-
-describe('shouldShowAutoSyncOnboarding — truth table', () => {
- const baseShow = {
- autoSyncOnboardingDismissed: false,
- hasRemote: true,
- projectLocalSynced: true,
- projectLocalConfig: { autoSync: { enabled: null as boolean | null } },
- pushPermissionCheckStatus: 'allowed' as 'allowed' | 'denied' | 'unknown' | undefined,
- };
-
- test('shows the dialog when all six inputs align', () => {
- expect(shouldShowAutoSyncOnboarding(baseShow)).toBe(true);
- });
-
- test('hides when dismissed', () => {
- expect(shouldShowAutoSyncOnboarding({ ...baseShow, autoSyncOnboardingDismissed: true })).toBe(
- false,
- );
- });
-
- test('hides when there is no git remote', () => {
- expect(shouldShowAutoSyncOnboarding({ ...baseShow, hasRemote: false })).toBe(false);
- expect(shouldShowAutoSyncOnboarding({ ...baseShow, hasRemote: undefined })).toBe(false);
- });
-
- test('hides during the cold-start window (flash-free guard)', () => {
- expect(shouldShowAutoSyncOnboarding({ ...baseShow, projectLocalSynced: false })).toBe(false);
- expect(shouldShowAutoSyncOnboarding({ ...baseShow, projectLocalSynced: undefined })).toBe(
- false,
- );
- });
-
- test('hides when the local config binding has not yet hydrated (null)', () => {
- expect(shouldShowAutoSyncOnboarding({ ...baseShow, projectLocalConfig: null })).toBe(false);
- });
-
- test('hides once the user has answered the prompt (enabled !== null)', () => {
- expect(
- shouldShowAutoSyncOnboarding({
- ...baseShow,
- projectLocalConfig: { autoSync: { enabled: true } },
- }),
- ).toBe(false);
- expect(
- shouldShowAutoSyncOnboarding({
- ...baseShow,
- projectLocalConfig: { autoSync: { enabled: false } },
- }),
- ).toBe(false);
- });
-
- test('hides when the push-permission probe returns denied', () => {
- expect(shouldShowAutoSyncOnboarding({ ...baseShow, pushPermissionCheckStatus: 'denied' })).toBe(
- false,
- );
- });
-
- test('hides while the probe is still pending (undefined) — no flash-then-close', () => {
- expect(
- shouldShowAutoSyncOnboarding({ ...baseShow, pushPermissionCheckStatus: undefined }),
- ).toBe(false);
- });
-
- test('SHOWS when probe resolved allowed OR unknown (graceful degradation)', () => {
- expect(
- shouldShowAutoSyncOnboarding({ ...baseShow, pushPermissionCheckStatus: 'allowed' }),
- ).toBe(true);
- expect(
- shouldShowAutoSyncOnboarding({ ...baseShow, pushPermissionCheckStatus: 'unknown' }),
- ).toBe(true);
- });
-});
diff --git a/packages/app/src/components/EditorTabs.dom.test.tsx b/packages/app/src/components/EditorTabs.dom.test.tsx
new file mode 100644
index 000000000..33929039c
--- /dev/null
+++ b/packages/app/src/components/EditorTabs.dom.test.tsx
@@ -0,0 +1,571 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { assetTabId, folderTabId } from '@/editor/editor-tabs';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+let activeDocName: string | null = 'docs/team/spec';
+let activeTabId: string | null = 'docs/team/spec';
+let activeNewTabId: string | null = null;
+let activeTarget: unknown = null;
+let isNewTabActive = false;
+let openTabs: string[] = [];
+let visibleTabIds: string[] = [];
+let newTabIds: string[] = [];
+let pinnedTabIds: string[] = [];
+let pageMeta: Map<string, { docExt?: string }> = new Map();
+let lifecycleStatuses: Map<string, string> = new Map();
+let toastErrors: string[] = [];
+
+const activateTab = mock(() => {});
+const activateNewTab = mock(() => {});
+const closeAndClearForRename = mock(() => Promise.resolve());
+const closeNewTab = mock(() => {});
+const closeTab = mock(() => {});
+const closeTabs = mock(() => {});
+const getPoolActiveDocName = mock(() => null as string | null);
+const openNewTab = mock(() => {});
+const pinTab = mock(() => {});
+const remapTabsForRename = mock(() => {});
+const reorderTabs = mock(() => {});
+const unpinTab = mock(() => {});
+
+type DndContextProps = {
+ accessibility?: { container?: HTMLElement };
+ children?: ReactNode;
+ onDragEnd?: (event: { active: { id: string }; over: { id: string } | null }) => void;
+ sensors?: unknown;
+};
+
+const pointerSensorToken = { name: 'PointerSensor' };
+const keyboardSensorToken = { name: 'KeyboardSensor' };
+const closestCenterToken = { name: 'closestCenter' };
+const horizontalListSortingStrategyToken = { name: 'horizontalListSortingStrategy' };
+const sortableKeyboardCoordinatesToken = { name: 'sortableKeyboardCoordinates' };
+const dndContextProps: DndContextProps[] = [];
+const sensorCalls: Array<{ sensor: unknown; options: unknown }> = [];
+const sortableContextProps: Array<{ items: string[]; strategy: unknown }> = [];
+const sortableOptions: Array<{ id: string; disabled?: boolean }> = [];
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+mock.module('@dnd-kit/core', () => ({
+ closestCenter: closestCenterToken,
+ DndContext: (props: DndContextProps) => {
+ dndContextProps.push(props);
+ return <div data-testid="dnd-context">{props.children}</div>;
+ },
+ KeyboardCode: {
+ Down: 'ArrowDown',
+ End: 'End',
+ Enter: 'Enter',
+ Esc: 'Escape',
+ Home: 'Home',
+ Left: 'ArrowLeft',
+ Right: 'ArrowRight',
+ Space: 'Space',
+ Up: 'ArrowUp',
+ },
+ KeyboardSensor: keyboardSensorToken,
+ PointerSensor: pointerSensorToken,
+ useSensor: (sensor: unknown, options: unknown) => {
+ sensorCalls.push({ sensor, options });
+ return { sensor, options };
+ },
+ useSensors: (...sensors: unknown[]) => sensors,
+}));
+
+mock.module('@dnd-kit/sortable', () => ({
+ arrayMove: <T,>(items: T[], from: number, to: number) => {
+ const next = [...items];
+ const [item] = next.splice(from, 1);
+ next.splice(to, 0, item);
+ return next;
+ },
+ horizontalListSortingStrategy: horizontalListSortingStrategyToken,
+ sortableKeyboardCoordinates: sortableKeyboardCoordinatesToken,
+ SortableContext: ({
+ children,
+ items,
+ strategy,
+ }: {
+ children?: ReactNode;
+ items: string[];
+ strategy: unknown;
+ }) => {
+ sortableContextProps.push({ items: [...items], strategy });
+ return <div data-testid="sortable-context">{children}</div>;
+ },
+ useSortable: ({ id, disabled }: { id: string; disabled?: boolean }) => {
+ sortableOptions.push({ id, disabled });
+ return {
+ attributes: {
+ role: 'button',
+ 'aria-roledescription': 'sortable',
+ 'data-sortable-id': id,
+ },
+ isDragging: false,
+ listeners: {},
+ rect: { current: { width: 120 } },
+ setNodeRef: () => {},
+ transform: null,
+ transition: 'transform 200ms ease',
+ };
+ },
+}));
+
+mock.module('@dnd-kit/utilities', () => ({
+ CSS: {
+ Transform: {
+ toString: () => undefined,
+ },
+ },
+}));
+
+mock.module('@/components/ui/context-menu', () => ({
+ ContextMenu: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ ContextMenuContent: ({ children, className }: { children?: ReactNode; className?: string }) => (
+ <div className={className} role="menu">
+ {children}
+ </div>
+ ),
+ ContextMenuItem: ({
+ children,
+ disabled,
+ onSelect,
+ ...props
+ }: {
+ children?: ReactNode;
+ disabled?: boolean;
+ onSelect?: () => void;
+ [key: string]: unknown;
+ }) => (
+ <button
+ type="button"
+ role="menuitem"
+ disabled={disabled}
+ onClick={() => {
+ if (!disabled) onSelect?.();
+ }}
+ {...props}
+ >
+ {children}
+ </button>
+ ),
+ ContextMenuSeparator: () => <hr data-testid="context-menu-separator" />,
+ ContextMenuTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,
+}));
+
+mock.module('@/components/ui/tooltip', () => ({
+ Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ TooltipContent: ({ children }: { children?: ReactNode }) => <div role="tooltip">{children}</div>,
+ TooltipTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,
+}));
+
+mock.module('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({
+ activeDocName,
+ activeNewTabId,
+ activeTabId,
+ activeTarget,
+ activateNewTab,
+ activateTab,
+ closeAndClearForRename,
+ closeNewTab,
+ closeTab,
+ closeTabs,
+ getPoolActiveDocName,
+ isNewTabActive,
+ newTabIds,
+ openNewTab,
+ openTabs,
+ pinTab,
+ pinnedTabIds,
+ remapTabsForRename,
+ reorderTabs,
+ unpinTab,
+ visibleTabIds,
+ }),
+}));
+
+mock.module('@/components/PageListContext', () => ({
+ usePageList: () => ({
+ pageMeta,
+ }),
+}));
+
+mock.module('@/hooks/use-lifecycle-status', () => ({
+ useLifecycleStatus: (docName: string) => lifecycleStatuses.get(docName) ?? null,
+}));
+
+mock.module('sonner', () => ({
+ toast: {
+ error: (message: string) => {
+ toastErrors.push(message);
+ },
+ },
+}));
+
+function defaultTabs() {
+ const folderId = folderTabId('docs/team');
+ const assetId = assetTabId('images/cat.png');
+ const newId = 'new-tab-1';
+ return {
+ assetId,
+ folderId,
+ newId,
+ tabs: ['docs/team/notes', 'docs/team/spec', 'docs/team/readme', folderId, assetId],
+ visible: ['docs/team/notes', 'docs/team/spec', 'docs/team/readme', folderId, assetId, newId],
+ };
+}
+
+function resetState() {
+ const { newId, tabs, visible } = defaultTabs();
+ activeDocName = 'docs/team/spec';
+ activeTabId = 'docs/team/spec';
+ activeNewTabId = null;
+ activeTarget = null;
+ isNewTabActive = false;
+ openTabs = tabs;
+ visibleTabIds = visible;
+ newTabIds = [newId];
+ pinnedTabIds = [];
+ pageMeta = new Map([
+ ['docs/team/notes', { docExt: '.md' }],
+ ['docs/team/spec', { docExt: '.mdx' }],
+ ['docs/team/readme', { docExt: '.txt' }],
+ ]);
+ lifecycleStatuses = new Map();
+ toastErrors = [];
+ dndContextProps.length = 0;
+ sensorCalls.length = 0;
+ sortableContextProps.length = 0;
+ sortableOptions.length = 0;
+ for (const fn of [
+ activateTab,
+ activateNewTab,
+ closeAndClearForRename,
+ closeNewTab,
+ closeTab,
+ closeTabs,
+ getPoolActiveDocName,
+ openNewTab,
+ pinTab,
+ remapTabsForRename,
+ reorderTabs,
+ unpinTab,
+ ]) {
+ fn.mockClear();
+ }
+ closeAndClearForRename.mockImplementation(() => Promise.resolve());
+ getPoolActiveDocName.mockImplementation(() => null);
+ remapTabsForRename.mockImplementation(() => {});
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: undefined,
+ });
+ window.location.hash = '';
+ globalThis.fetch = mock(() => Promise.reject(new Error('unexpected fetch'))) as never;
+}
+
+async function renderEditorTabs() {
+ const { EditorTabs } = await import('./EditorTabs');
+ return render(<EditorTabs />);
+}
+
+function latestDndContext() {
+ const latest = dndContextProps.at(-1);
+ expect(latest).toBeDefined();
+ return latest as DndContextProps;
+}
+
+function tabButton(name: string) {
+ const button = screen
+ .getAllByRole('button', { name })
+ .find((element) => element.tagName === 'BUTTON' && !element.hasAttribute('data-sortable-id'));
+ expect(button).toBeDefined();
+ return button as HTMLButtonElement;
+}
+
+describe('EditorTabs runtime behavior', () => {
+ beforeEach(() => {
+ resetState();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('renders markdown doc labels without extensions while preserving full-path accessible names and titles', async () => {
+ await renderEditorTabs();
+
+ const markdownTab = tabButton('docs/team/notes.md');
+ expect(markdownTab.textContent).toBe('notes');
+ expect(markdownTab.getAttribute('title')).toBe('docs/team/notes.md');
+
+ const mdxTab = tabButton('docs/team/spec.mdx');
+ expect(mdxTab.textContent).toBe('spec');
+ expect(mdxTab.getAttribute('title')).toBe('docs/team/spec.mdx');
+ expect(mdxTab.closest('[data-sortable-id]')?.getAttribute('aria-current')).toBe('page');
+
+ const txtTab = tabButton('docs/team/readme.txt');
+ expect(txtTab.textContent).toBe('readme.txt');
+ expect(txtTab.getAttribute('title')).toBe('docs/team/readme.txt');
+ });
+
+ test('keeps folder, asset, and new-tab branches closeable and independently activatable', async () => {
+ const { assetId, folderId, newId } = defaultTabs();
+ await renderEditorTabs();
+
+ const folderTab = tabButton('docs/team/');
+ expect(folderTab.textContent).toBe('docs/team/');
+ fireEvent.click(folderTab);
+ expect(activateTab).toHaveBeenCalledWith(folderId);
+
+ const assetTab = tabButton('images/cat.png');
+ expect(assetTab.textContent).toBe('images/cat.png');
+ fireEvent.click(assetTab);
+ expect(activateTab).toHaveBeenCalledWith(assetId);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Activate new tab' }));
+ expect(activateNewTab).toHaveBeenCalledWith(newId);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Close new tab' }));
+ expect(closeNewTab).toHaveBeenCalledWith(newId);
+
+ fireEvent.click(screen.getByTestId('editor-new-tab-button'));
+ expect(openNewTab).toHaveBeenCalledTimes(1);
+ });
+
+ test('Electron host applies drag only to the strip root and no-drag to the content wrapper', async () => {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: {},
+ });
+
+ const { container } = await renderEditorTabs();
+ const root = container.firstElementChild as HTMLElement;
+ const wrapper = root.firstElementChild as HTMLElement;
+
+ expect(root.getAttribute('data-electron-drag')).toBe('');
+ expectVisualClassTokens(root.className, ['[-webkit-app-region:drag]']);
+ expectVisualClassTokens(wrapper.className, [
+ '[-webkit-app-region:no-drag]',
+ 'flex',
+ 'items-end',
+ 'gap-1',
+ ]);
+ expectVisualClassTokensAbsent(wrapper.className, ['flex-1']);
+ });
+
+ test('web host keeps baseline scroll layout without app-region classes', async () => {
+ const { container } = await renderEditorTabs();
+ const root = container.firstElementChild as HTMLElement;
+ const wrapper = root.firstElementChild as HTMLElement;
+
+ expect(root.getAttribute('data-electron-drag')).toBeNull();
+ expectVisualClassTokens(root.className, ['overflow-x-auto', 'scroll-fade-mask-x']);
+ expectVisualClassTokensAbsent(root.className, ['[-webkit-app-region:drag]']);
+ expectVisualClassTokensAbsent(wrapper.className, ['[-webkit-app-region:no-drag]']);
+ });
+
+ test('wires sortable sensors, visible items, drag-end reorder, and the accessibility portal at runtime', async () => {
+ await renderEditorTabs();
+
+ expect(sensorCalls).toEqual([
+ { sensor: pointerSensorToken, options: { activationConstraint: { distance: 8 } } },
+ {
+ sensor: keyboardSensorToken,
+ options: {
+ coordinateGetter: sortableKeyboardCoordinatesToken,
+ keyboardCodes: {
+ cancel: ['Escape'],
+ end: ['Space', 'Enter'],
+ start: ['Space'],
+ },
+ },
+ },
+ ]);
+ expect(latestDndContext().accessibility?.container).toBe(document.body);
+ expect(latestDndContext().sensors).toEqual(sensorCalls.map((call) => call));
+ expect(sortableContextProps.at(-1)).toEqual({
+ items: visibleTabIds,
+ strategy: horizontalListSortingStrategyToken,
+ });
+
+ act(() => {
+ latestDndContext().onDragEnd?.({
+ active: { id: 'docs/team/readme' },
+ over: { id: 'docs/team/notes' },
+ });
+ });
+
+ expect(reorderTabs).toHaveBeenCalledWith(
+ [
+ 'docs/team/readme',
+ 'docs/team/notes',
+ 'docs/team/spec',
+ defaultTabs().folderId,
+ defaultTabs().assetId,
+ defaultTabs().newId,
+ ],
+ 'docs/team/readme',
+ );
+ });
+
+ test('context actions close visible document tabs in bulk while routing empty tabs through closeNewTab', async () => {
+ const { newId } = defaultTabs();
+ pinnedTabIds = ['docs/team/readme'];
+ await renderEditorTabs();
+
+ fireEvent.click(screen.getAllByRole('menuitem', { name: 'Close others' })[0]);
+
+ expect(closeTabs).toHaveBeenCalledWith([
+ 'docs/team/spec',
+ defaultTabs().folderId,
+ defaultTabs().assetId,
+ ]);
+ expect(closeNewTab).toHaveBeenCalledWith(newId);
+
+ closeTabs.mockClear();
+ closeNewTab.mockClear();
+ fireEvent.click(screen.getAllByRole('menuitem', { name: 'Close all unpinned' })[0]);
+
+ expect(closeTabs).toHaveBeenCalledWith([
+ 'docs/team/notes',
+ 'docs/team/spec',
+ defaultTabs().folderId,
+ defaultTabs().assetId,
+ ]);
+ expect(closeNewTab).toHaveBeenCalledWith(newId);
+ });
+
+ test('pin state changes close controls, menu actions, and middle-click behavior', async () => {
+ pinnedTabIds = ['docs/team/readme'];
+ await renderEditorTabs();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Close docs/team/notes.md' }));
+ expect(closeTab).toHaveBeenCalledWith('docs/team/notes');
+
+ const unpinButton = screen.getByRole('button', { name: 'Unpin docs/team/readme.txt' });
+ expect(unpinButton.getAttribute('title')).toBeNull();
+ expectVisualClassTokens(unpinButton.className, ['text-primary']);
+ fireEvent.click(unpinButton);
+ expect(unpinTab).toHaveBeenCalledWith('docs/team/readme');
+
+ fireEvent.click(screen.getAllByRole('menuitem', { name: 'Pin tab' })[0]);
+ expect(pinTab).toHaveBeenCalledWith('docs/team/notes');
+
+ fireEvent.click(screen.getAllByRole('menuitem', { name: 'Unpin tab' })[0]);
+ expect(unpinTab).toHaveBeenCalledWith('docs/team/readme');
+
+ fireEvent(
+ tabButton('docs/team/readme.txt').closest('[data-sortable-id]') ??
+ tabButton('docs/team/readme.txt'),
+ new MouseEvent('auxclick', { bubbles: true, button: 1, cancelable: true }),
+ );
+ expect(closeTab).not.toHaveBeenCalledWith('docs/team/readme');
+ });
+
+ test('rename mode strips the file extension, disables sorting, reports invalid input, and keeps the extension addon', async () => {
+ await renderEditorTabs();
+
+ fireEvent.doubleClick(tabButton('docs/team/readme.txt'));
+
+ const input = screen.getByTestId('editor-tab-rename-input') as HTMLInputElement;
+ expect(input.value).toBe('readme');
+ expect(screen.getByText('.txt')).toBeTruthy();
+ expect(
+ sortableOptions.some((options) => options.id === 'docs/team/readme' && options.disabled),
+ ).toBe(true);
+
+ fireEvent.change(input, { target: { value: 'bad/name.txt' } });
+ expect(input.value).toBe('bad/name');
+ fireEvent.keyDown(input, { key: 'Enter' });
+
+ expect((await screen.findByRole('alert')).textContent).toBe(
+ 'Name can’t be empty, ".", "..", or contain / or \\',
+ );
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ });
+
+ test('rename post-commit reconciliation failures surface the refresh toast and skip navigation', async () => {
+ activeDocName = 'docs/team/readme';
+ activeTabId = 'docs/team/readme';
+ remapTabsForRename.mockImplementation(() => {
+ throw new Error('idb clear failed');
+ });
+ globalThis.fetch = mock(() =>
+ Promise.resolve(
+ new Response(
+ JSON.stringify({
+ renamed: [{ fromDocName: 'docs/team/readme', toDocName: 'docs/team/renamed' }],
+ }),
+ { headers: { 'Content-Type': 'application/json' }, status: 200 },
+ ),
+ ),
+ ) as never;
+
+ await renderEditorTabs();
+ fireEvent.doubleClick(tabButton('docs/team/readme.txt'));
+ const input = screen.getByTestId('editor-tab-rename-input') as HTMLInputElement;
+ fireEvent.change(input, { target: { value: 'renamed.txt' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+
+ await waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
+ });
+ await waitFor(() => {
+ expect(toastErrors).toContain(
+ 'Rename succeeded but the tabstrip may be out of date — refresh to resync',
+ );
+ });
+ expect(toastErrors).not.toContain('Network error — please try again');
+ expect(window.location.hash).toBe('');
+ });
+
+ test('tab context menus and active tab styling are visible behavior, not source-shape details', async () => {
+ lifecycleStatuses.set('docs/team/notes', 'conflict');
+ await renderEditorTabs();
+
+ expect(screen.getByTestId('editor-tab-conflict-badge').getAttribute('aria-label')).toBe(
+ 'Conflict',
+ );
+ expect(screen.getAllByRole('menuitem', { name: 'Close' }).length).toBeGreaterThan(0);
+ expect(screen.getAllByRole('menuitem', { name: 'Close others' }).length).toBeGreaterThan(0);
+ expect(screen.getAllByRole('menuitem', { name: 'Close all' }).length).toBeGreaterThan(0);
+ expect(screen.getAllByRole('menuitem', { name: 'Pin tab' }).length).toBeGreaterThan(0);
+ expect(screen.getAllByTestId('context-menu-separator').length).toBeGreaterThan(0);
+
+ const activeSortable = screen
+ .getAllByRole('button', { name: 'docs/team/spec.mdx' })
+ .find((element) => element.tagName === 'BUTTON')
+ ?.closest('[data-sortable-id]') as HTMLElement;
+ expectVisualClassTokens(activeSortable.className, [
+ 'rounded-t-lg',
+ 'rounded-b-none',
+ 'border-border',
+ 'border-b-0',
+ 'bg-background',
+ ]);
+
+ const inactiveClose = within(
+ tabButton('docs/team/notes.md').closest('[data-sortable-id]') as HTMLElement,
+ ).getByRole('button', { name: 'Close docs/team/notes.md' });
+ expectVisualClassTokens(inactiveClose.className, ['mr-1.5']);
+
+ const placeholderClose = screen.getByTestId('editor-new-tab-placeholder-close');
+ expectVisualClassTokens(placeholderClose.className, [
+ 'pointer-events-none',
+ 'opacity-0',
+ 'group-hover:pointer-events-auto',
+ ]);
+ });
+});
diff --git a/packages/app/src/components/EditorTabs.test.ts b/packages/app/src/components/EditorTabs.test.ts
index 22435b951..56b2265fa 100644
--- a/packages/app/src/components/EditorTabs.test.ts
+++ b/packages/app/src/components/EditorTabs.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, test } from 'bun:test';
-import SRC from './EditorTabs?raw';
describe('EditorTabs module', () => {
test('exports the EditorTabs component', async () => {
@@ -25,287 +24,3 @@ describe('EditorTabs module', () => {
expect(rootParts.baseName).toBe('notes');
});
});
-
-describe('EditorTabs source-level guards — doc-tab label shape', () => {
- test('doc-tab branch derives hideDocExtension for .md / .mdx only', () => {
- expect(SRC).toContain("const hideDocExtension = docExt === '.md' || docExt === '.mdx';");
- });
-
- test('doc-tab label render gates the extension span on !hideDocExtension', () => {
- expect(SRC).toMatch(
- /\{!hideDocExtension\s*&&\s*<span\s+className=["']shrink-0["']\s*>\{extension\}<\/span>\}/,
- );
- });
-
- test('doc-tab label render does NOT include the folder prefix span', () => {
- const docBranch = SRC.split(
- "const hideDocExtension = docExt === '.md' || docExt === '.mdx';",
- )[1];
- expect(docBranch).toBeDefined();
- const renderSlice = (docBranch ?? '').split('TabPinOrCloseButton')[0] ?? '';
- expect(renderSlice).not.toMatch(/min-w-0 flex-1 truncate text-muted-foreground\/60/);
- expect(renderSlice).not.toContain('{prefix}');
- });
-
- test('doc-tab button surfaces the full path via title for disambiguation on hover', () => {
- expect(SRC).toMatch(
- /<button\s+type="button"\s+aria-label=\{accessibleLabel\}\s+title=\{accessibleLabel\}/,
- );
- });
-
- test('tab rename mode still uses the InputGroupAddon extension treatment', () => {
- expect(SRC).toMatch(
- /<InputGroupAddon\s+align="inline-end"[\s\S]*?text-muted-foreground\/60[\s\S]*?\{docExt\}/,
- );
- expect(SRC).toMatch(
- /setRenameValue\(\s*stripRenameExtensionSuffix\(event\.target\.value,\s*docExt\),?\s*\)/,
- );
- });
-
- test('folder tab and asset tab render branches retain their own basename+extension shape', () => {
- expect(SRC).toContain('<span className="shrink-0">/</span>');
- expect(SRC).toMatch(
- /tab\.kind === ['"]asset['"][\s\S]*?<span className="shrink-0">\{extension\}/,
- );
- });
-});
-
-describe('EditorTabs source-level guards — tab-strip drag region', () => {
- test('detects Electron host via the canonical window.okDesktop != null idiom', () => {
- expect(SRC).toMatch(
- /typeof\s+window\s*!==\s*['"]undefined['"]\s*&&\s*window\.okDesktop\s*!=\s*null/,
- );
- expect(SRC).toContain('const isElectronHost');
- });
-
- test('strip ROOT stays a drag region in Electron mode (empty band + trailing space draggable)', () => {
- expect(SRC).toMatch(/isElectronHost\s*&&\s*['"]\[-webkit-app-region:drag\]['"]/);
- });
-
- test('an inner wrapper declares no-drag so tabs + inter-tab gaps stay interactive', () => {
- expect(SRC).toMatch(/isElectronHost\s*&&\s*['"]\[-webkit-app-region:no-drag\]['"]/);
- });
-
- test('exactly one drag region (root) and one no-drag opt-out (wrapper) — no per-tab opt-outs', () => {
- const drag = SRC.match(/\[-webkit-app-region:drag\]/g);
- const noDrag = SRC.match(/\[-webkit-app-region:no-drag\]/g);
- expect(drag?.length ?? 0).toBe(1);
- expect(noDrag?.length ?? 0).toBe(1);
- });
-
- test('the no-drag wrapper hugs its content (no flex-1) so trailing space stays draggable', () => {
- expect(SRC).toContain("'flex items-end gap-1'");
- });
-
- test('strip root carries data-electron-drag so the globals.css `:has()` rule can neutralize it', () => {
- expect(SRC).toMatch(
- /data-electron-drag=\{\s*isElectronHost\s*\?\s*['"]['"]\s*:\s*undefined\s*\}/,
- );
- });
-
- test('per-tab div keeps its onAuxClick middle-click-close handler', () => {
- expect(SRC).toMatch(/onAuxClick=\{\(event\)\s*=>\s*\{[\s\S]*?closeTab\(\w+\)/);
- });
-
- test('cn helper composes conditional classes (does not break twMerge contract)', () => {
- expect(SRC).toMatch(/from\s+['"]@\/lib\/utils['"]/);
- expect(SRC).toContain('cn(');
- });
-
- test('web-mode baseline unchanged — existing scroll-on-wheel + flex layout primitives preserved', () => {
- expect(SRC).toContain('overflow-x-auto');
- expect(SRC).toMatch(/subtle-scrollbar|scroll-fade-mask-x/);
- expect(SRC).toContain('onWheel={scrollTabListOnWheel}');
- });
-});
-
-describe('EditorTabs source-level guards — tab context menu', () => {
- test('uses the shadcn/Radix context menu primitives for tab actions', () => {
- expect(SRC).toContain("from '@/components/ui/context-menu'");
- expect(SRC).toContain('<ContextMenuTrigger asChild>');
- expect(SRC).toContain('<ContextMenuContent');
- });
-
- test('folder, asset, document, and new-tab branches wrap with EditorTabContextMenu', () => {
- const matches = SRC.match(/<EditorTabContextMenu[\s\n]/g);
- expect(matches?.length ?? 0).toBeGreaterThanOrEqual(4);
- expect(SRC).toMatch(
- /visibleTabIds\.map[\s\S]*?newTabIdSet\.has\(tabId\)[\s\S]*?<EditorTabContextMenu[\s\S]*?openTabs=\{visibleTabIds\}[\s\S]*?closeTab=\{closeNewTab\}[\s\S]*?closeTabs=\{closeVisibleTabs\}/,
- );
- });
-
- test('asset tabs render inside the tab strip as closeable tabs', () => {
- expect(SRC).toContain("tab.kind === 'asset'");
- expect(SRC).toMatch(
- /tab\.kind === ['"]asset['"][\s\S]*?<EditorTabContextMenu[\s\S]*?closeTab=\{closeTab\}[\s\S]*?activateTab\(tabId\)[\s\S]*?<TabPinOrCloseButton[\s\S]*?accessibleLabel=\{accessibleLabel\}/,
- );
- });
-
- test('tabs avoid file/folder/asset type icons and keep the close control on the right', () => {
- expect(SRC).not.toContain('FileIcon');
- expect(SRC).not.toContain('FolderOpen');
- expect(SRC).toMatch(/<Button[\s\S]*?aria-label=\{t`Close \$\{accessibleLabel\}`\}/);
- expect(SRC).toMatch(
- /<button[\s\S]*?aria-label=\{accessibleLabel\}[\s\S]*?<\/button>\s*<TabPinOrCloseButton/,
- );
- });
-
- test('active tabs use Obsidian-style contrast without bottom overlay strips', () => {
- expect(SRC).toContain('group relative -mb-px flex h-10');
- expect(SRC).toContain('rounded-t-lg rounded-b-none');
- expect(SRC).toContain('border-border border-b-0 bg-background text-foreground');
- expect(SRC).toContain('bg-transparent hover:bg-muted focus-visible:bg-muted');
- expect(SRC).toContain('border-transparent hover:border-border focus-visible:border-border');
- expect(SRC).not.toContain('tab-bottom-flares');
- expect(SRC).not.toContain('h-2 w-[calc(100%+16px)]');
- expect(SRC).not.toContain("isActive ? 'font-semibold' : 'font-medium'");
- });
-
- test('tab context menu exposes close, close-others, and close-all actions', () => {
- expect(SRC).toMatch(/<ContextMenuItem[\s\S]*?<Trans>Close<\/Trans>\s*<\/ContextMenuItem>/);
- expect(SRC).toMatch(
- /<ContextMenuItem[\s\S]*?<Trans>Close others<\/Trans>\s*<\/ContextMenuItem>/,
- );
- expect(SRC).toContain('<Trans>Close all</Trans>');
- expect(SRC).toContain(
- 'pinnedTabIds.length ? <Trans>Close all unpinned</Trans> : <Trans>Close all</Trans>',
- );
- });
-
- test('tab context menu exposes pin and unpin actions', () => {
- expect(SRC).toContain('<Trans>Pin tab</Trans>');
- expect(SRC).toContain('<Trans>Unpin tab</Trans>');
- expect(SRC).toContain('PinIcon');
- expect(SRC).toContain('ContextMenuSeparator');
- });
-
- test('bulk tab context actions route through closeTabs, not repeated single closes', () => {
- expect(SRC).toContain('filterClosableTabIds');
- expect(SRC).toContain('const otherTabIds = filterClosableTabIds');
- expect(SRC).toContain('disabled={otherTabIds.length === 0}');
- expect(SRC).toContain('closeTabs(otherTabIds)');
- expect(SRC).toContain('const closableTabIds = filterClosableTabIds(openTabs, pinnedTabIds)');
- expect(SRC).toContain('closeTabs(closableTabIds)');
- });
-
- test('pinned tabs replace close controls with an unpin button', () => {
- expect(SRC).toMatch(/aria-label=\{t`Unpin \$\{accessibleLabel\}`\}/);
- expect(SRC).not.toMatch(/title=\{t?`Unpin \$\{accessibleLabel\}`\}/);
- expect(SRC).not.toMatch(/title=\{t?`Close \$\{accessibleLabel\}`\}/);
- expect(SRC).toContain('text-primary');
- });
-
- test('bulk context actions operate on document and new-tab ids together', () => {
- expect(SRC).toContain('visibleTabIds,');
- expect(SRC).toContain('const newTabIdSet = new Set(newTabIds);');
- expect(SRC).toContain('function closeVisibleTabs(tabIds: readonly string[])');
- expect(SRC).toMatch(/newTabIdSet\.has\(tabId\)[\s\S]*?emptyTabIds\.push\(tabId\)/);
- expect(SRC).toMatch(
- /if\s*\(documentTabIds\.length > 0\)\s*closeTabs\(documentTabIds\);[\s\S]*?for\s*\(const tabId of emptyTabIds\)\s*closeNewTab\(tabId\)/,
- );
- const contextMenuMatches = SRC.match(/<EditorTabContextMenu[\s\n]/g);
- const closeVisibleMatches = SRC.match(/closeTabs=\{closeVisibleTabs\}/g);
- expect(closeVisibleMatches?.length ?? 0).toBe(contextMenuMatches?.length ?? 0);
- });
-});
-
-describe('EditorTabs source-level guards — tab drag-reorder (US-004)', () => {
- test('reuses the already-eager @dnd-kit packages — no new bundle deps', () => {
- expect(SRC).toContain("from '@dnd-kit/core'");
- expect(SRC).toContain("from '@dnd-kit/sortable'");
- expect(SRC).toContain('DndContext');
- expect(SRC).toContain('SortableContext');
- expect(SRC).toContain('useSortable');
- });
-
- test('PointerSensor activates at distance: 8 so plain clicks still switch the tab', () => {
- expect(SRC).toMatch(
- /useSensor\(\s*PointerSensor\s*,\s*\{\s*activationConstraint:\s*\{\s*distance:\s*8\s*\}\s*\}\s*\)/,
- );
- });
-
- test('KeyboardSensor with sortableKeyboardCoordinates wires keyboard accessibility (FR1d)', () => {
- expect(SRC).toContain('KeyboardSensor');
- expect(SRC).toContain('sortableKeyboardCoordinates');
- expect(SRC).toContain('keyboardCodes: TAB_KEYBOARD_DRAG_CODES');
- });
-
- test('SortableContext uses horizontalListSortingStrategy keyed off visibleTabIds', () => {
- expect(SRC).toContain('horizontalListSortingStrategy');
- expect(SRC).toMatch(
- /<SortableContext\s+items=\{\[\.\.\.visibleTabIds\]\}\s+strategy=\{horizontalListSortingStrategy\}/,
- );
- });
-
- test('handleDragEnd uses arrayMove and threads the dragged id into reorderTabs', () => {
- expect(SRC).toContain('arrayMove');
- expect(SRC).toContain('reorderTabs');
- expect(SRC).toMatch(/function handleDragEnd\(event:\s*DragEndEvent\)/);
- expect(SRC).toMatch(
- /reorderTabs\(arrayMove\(\[\.\.\.visibleTabIds\],\s*fromIndex,\s*toIndex\),\s*activeId\)/,
- );
- });
-
- test('every tab branch (new-tab, folder, asset, doc) is wrapped in a SortableTab', () => {
- const matches = SRC.match(/<SortableTab[\s\n]/g);
- expect(matches?.length ?? 0).toBeGreaterThanOrEqual(4);
- expect(SRC).not.toMatch(/<SortableTab[\s\S]*?role=["']presentation["']/);
- });
-
- test('doc-tab SortableTab disables drag while renaming so the input stays interactive', () => {
- expect(SRC).toMatch(/<SortableTab[\s\S]*?disabled=\{isRenaming\}/);
- });
-
- test('DndContext wraps the visibleTabIds.map output but NOT the standalone "New tab" button', () => {
- expect(SRC).toMatch(/<DndContext\s+[\s\S]*?sensors=\{sensors\}[\s\S]*?<SortableContext/);
- expect(SRC).toMatch(
- /<\/SortableContext>\s*<\/DndContext>\s*<Tooltip>[\s\S]*?aria-label=\{t`New tab`\}/,
- );
- });
-
- test('DndContext portals @dnd-kit SR helpers out of the strip via accessibility.container', () => {
- expect(SRC).toMatch(/accessibility=\{\{[\s\S]*?container:\s*typeof\s+document/);
- expect(SRC).toMatch(/typeof\s+document\s*!==\s*['"]undefined['"]\s*\?\s*document\.body/);
- });
-
- test('SortableTab composes refs for dnd-kit and Radix wrappers', () => {
- expect(SRC).toContain('function composedRef');
- expect(SRC).toContain('setNodeRef(node)');
- });
-});
-
-describe('EditorTabs — Post-commit reconciliation error labeling', () => {
- test('reconciliation is wrapped in its own try/catch (split from the fetch catch)', () => {
- const handlerStart = SRC.indexOf('async function commitRename');
- expect(handlerStart).toBeGreaterThan(-1);
- const handlerEnd = SRC.indexOf('\n }\n', handlerStart);
- const handlerBody = SRC.slice(handlerStart, handlerEnd);
- const remapIdx = handlerBody.indexOf('remapTabsForRename(renamed)');
- expect(remapIdx).toBeGreaterThan(-1);
- const beforeRemap = handlerBody.slice(0, remapIdx);
- const innerTryIdx = beforeRemap.lastIndexOf('try {');
- expect(innerTryIdx).toBeGreaterThan(-1);
- const sliceFromTry = handlerBody.slice(innerTryIdx);
- expect(sliceFromTry).toMatch(/catch\s*\(\s*reconcileErr\s*\)/);
- });
-
- test('post-commit failure surfaces a distinct toast (NOT "Network error")', () => {
- expect(SRC).toContain(
- 'toast.error(t`Rename succeeded but the tabstrip may be out of date — refresh to resync`)',
- );
- });
-
- test('post-commit navigation is gated on reconciliation success', () => {
- expect(SRC).toMatch(/let\s+reconcileOk\s*=\s*true/);
- expect(SRC).toMatch(/reconcileOk\s*=\s*false/);
- expect(SRC).toMatch(/reconcileOk\s*&&\s*nextActiveDocName/);
- });
-});
-
-describe('EditorTabs — Active-tab accessibility', () => {
- test('aria-current="page" is emitted on the active SortableTab', () => {
- expect(SRC).toMatch(/aria-current=\{isActive \? 'page' : undefined\}/);
- const matches = SRC.match(/aria-current=\{isActive \? 'page' : undefined\}/g) ?? [];
- expect(matches.length).toBeGreaterThanOrEqual(4);
- });
-});
diff --git a/packages/app/src/components/EditorToolbar.dom.test.tsx b/packages/app/src/components/EditorToolbar.dom.test.tsx
new file mode 100644
index 000000000..f494ca25c
--- /dev/null
+++ b/packages/app/src/components/EditorToolbar.dom.test.tsx
@@ -0,0 +1,69 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+import { expectVisualClassTokens } from '@/test-utils/visual-contract';
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+mock.module('./EditorBreadcrumb', () => ({
+ EditorBreadcrumb: ({ docName }: { docName: string | null }) => (
+ <span data-testid="editor-breadcrumb-probe">{docName}</span>
+ ),
+}));
+
+describe('EditorToolbar runtime layout', () => {
+ afterEach(() => cleanup());
+
+ async function renderToolbar() {
+ const { EditorToolbar } = await import('./EditorToolbar');
+
+ render(
+ <TooltipProvider>
+ <EditorToolbar
+ activeDocName="docs/Page.md"
+ isSourceMode={false}
+ sourceDisabled={false}
+ onModeChange={() => {}}
+ showAddPropertyButton={true}
+ onAddProperty={() => {}}
+ isPanelCollapsed={false}
+ onTogglePanel={() => {}}
+ />
+ </TooltipProvider>,
+ );
+ }
+
+ test('toolbar overlay lets editor clicks pass through except explicit cells', async () => {
+ await renderToolbar();
+
+ const toolbar = screen.getByTestId('editor-toolbar');
+ expectVisualClassTokens(toolbar.className, ['pointer-events-none']);
+
+ const breadcrumbCell = screen.getByTestId('editor-breadcrumb-probe').parentElement;
+ expectVisualClassTokens(breadcrumbCell?.className, ['pointer-events-auto']);
+ });
+
+ test('content-column wrapper encloses the three-column toolbar grid', async () => {
+ await renderToolbar();
+
+ const toolbar = screen.getByTestId('editor-toolbar');
+ const alignedWrapper = toolbar.querySelector('.editor-content-aligned');
+ expect(alignedWrapper).toBeTruthy();
+
+ const grid = alignedWrapper?.querySelector('.grid.grid-cols-3');
+ expect(grid).toBeTruthy();
+ });
+
+ test('mode toggle stays centered in the middle toolbar cell', async () => {
+ await renderToolbar();
+
+ const sourceButton = screen.getByRole('radio', { name: 'Markdown source' });
+ const middleCell = sourceButton.closest('.pointer-events-auto.flex.justify-center');
+ expect(middleCell).toBeTruthy();
+ });
+});
diff --git a/packages/app/src/components/EditorToolbar.test.ts b/packages/app/src/components/EditorToolbar.test.ts
deleted file mode 100644
index 926827661..000000000
--- a/packages/app/src/components/EditorToolbar.test.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './EditorToolbar?raw';
-
-describe('EditorToolbar source-level guards', () => {
- test('toolbar wraps its 3-col grid in `.editor-content-aligned` so cells map to the editor content column', () => {
- const alignedIdx = SRC.indexOf('editor-content-aligned');
- expect(alignedIdx).toBeGreaterThan(-1);
- const gridColsIdx = SRC.indexOf('grid grid-cols-3');
- expect(gridColsIdx).toBeGreaterThan(-1);
- expect(alignedIdx).toBeLessThan(gridColsIdx);
- });
-
- test('breadcrumb cell keeps `pointer-events-auto` so the title tooltip surfaces', () => {
- const cellStart = SRC.indexOf('<EditorBreadcrumb');
- const outerCellStart = SRC.lastIndexOf('pointer-events-auto', cellStart);
- expect(outerCellStart).toBeGreaterThan(-1);
- });
-
- test('toolbar root is `pointer-events-none` overlay', () => {
- expect(SRC).toMatch(/data-testid="editor-toolbar"[^>]*pointer-events-none/);
- });
-
- test('mode toggle cell stays centered (justify-center) — alignment fix did not shift it', () => {
- expect(SRC).toMatch(/<div\s+className="pointer-events-auto flex justify-center">/);
- });
-});
diff --git a/packages/app/src/components/FileSidebar.dom.test.tsx b/packages/app/src/components/FileSidebar.dom.test.tsx
new file mode 100644
index 000000000..ea113f7b9
--- /dev/null
+++ b/packages/app/src/components/FileSidebar.dom.test.tsx
@@ -0,0 +1,629 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { type ReactNode, useEffect } from 'react';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+function PassThrough({ children }: { children?: ReactNode }) {
+ return <>{children}</>;
+}
+
+function ElementPassThrough({
+ children,
+ asChild: _asChild,
+ ...props
+}: {
+ children?: ReactNode;
+ asChild?: boolean;
+ [key: string]: unknown;
+}) {
+ return <div {...props}>{children}</div>;
+}
+
+function Button({
+ children,
+ asChild: _asChild,
+ onCheckedChange: _onCheckedChange,
+ onClick,
+ onSelect,
+ size: _size,
+ variant: _variant,
+ ...props
+}: {
+ children?: ReactNode;
+ asChild?: boolean;
+ onCheckedChange?: unknown;
+ onClick?: () => void;
+ onSelect?: () => void;
+ size?: unknown;
+ variant?: unknown;
+ [key: string]: unknown;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={() => {
+ onClick?.();
+ onSelect?.();
+ }}
+ {...props}
+ >
+ {children}
+ </button>
+ );
+}
+
+type FolderState = { folderCount: number; expandedCount: number };
+
+let sidebarState: 'expanded' | 'collapsed' = 'expanded';
+let workspace: { contentDir: string; pathSeparator: string } | null = {
+ contentDir: '/tmp/open-knowledge',
+ pathSeparator: '/',
+};
+let activeDocName: string | null = 'docs/current';
+let activeTarget: { kind: 'folder'; folderPath: string } | null = {
+ kind: 'folder',
+ folderPath: 'docs',
+};
+let folderState: FolderState = { folderCount: 2, expandedCount: 1 };
+let hasTemplates = true;
+let mergedConfig: {
+ appearance?: { sidebar?: { showHiddenFiles?: boolean; showAllFiles?: boolean } };
+} | null = {
+ appearance: { sidebar: { showHiddenFiles: false, showAllFiles: true } },
+};
+let sidebarSearchThrows = false;
+let projectPatchResult: { ok: true } | { ok: false; error: unknown } = { ok: true };
+let openInAgentSubmenuProps: Array<{
+ input: unknown;
+ webFallbackVisible: boolean;
+}> = [];
+let toastSuccesses: unknown[][] = [];
+let toastErrors: unknown[][] = [];
+let pillRenderErrors: unknown[][] = [];
+const treeListeners = new Set<() => void>();
+
+const treeCalls = {
+ collapseAll: mock(() => {}),
+ createFromTemplate: mock((_parentDir: string, _templateName: string) => {}),
+ expandAll: mock(() => {}),
+ startCreating: mock((_kind: 'file' | 'folder', _parentDir: string) => {}),
+ startCreatingFromTemplate: mock((_parentDir: string) => {}),
+};
+const projectLocalPatch = mock((_patch: unknown) => projectPatchResult);
+const dispatchOpenInTerminalMock = mock((_bridge: unknown, _path: string) => Promise.resolve());
+const showItemInFolderMock = mock((_path: string) => Promise.resolve());
+const notifyViewMenuStateChangedMock = mock((_snapshot: unknown) => {});
+const onOpenSearch = mock(() => {});
+
+function setFolderState(next: FolderState) {
+ folderState = next;
+ for (const listener of treeListeners) listener();
+}
+
+function installBridge() {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: {
+ platform: 'darwin',
+ editor: {
+ notifyViewMenuStateChanged: notifyViewMenuStateChangedMock,
+ },
+ shell: {
+ showItemInFolder: showItemInFolderMock,
+ },
+ onMenuAction: () => () => {},
+ },
+ });
+}
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+mock.module('@/lib/perf', () => ({
+ ProfilerBoundary: PassThrough,
+}));
+
+mock.module('@/components/FileTree', () => ({
+ FileTree: ({ ref }: { ref?: (handle: unknown) => void }) => {
+ useEffect(() => {
+ const handle = {
+ collapseAll: treeCalls.collapseAll,
+ createFromTemplate: treeCalls.createFromTemplate,
+ expandAll: treeCalls.expandAll,
+ getFolderState: () => folderState,
+ startCreating: treeCalls.startCreating,
+ startCreatingFromTemplate: treeCalls.startCreatingFromTemplate,
+ subscribe: (listener: () => void) => {
+ treeListeners.add(listener);
+ return () => treeListeners.delete(listener);
+ },
+ };
+ ref?.(handle);
+ return () => ref?.(null);
+ }, [ref]);
+ return <div data-testid="file-tree-stub" />;
+ },
+}));
+
+mock.module('@/components/ConflictsSection', () => ({
+ ConflictsSection: () => <div data-testid="conflicts-section" />,
+}));
+
+mock.module('@/components/ProjectSwitcher', () => ({
+ ProjectSwitcher: () => <button type="button">Project switcher</button>,
+}));
+
+mock.module('@/components/SidebarSearchBar', () => ({
+ SidebarSearchBar: ({ onClick }: { onClick: () => void }) => {
+ if (sidebarSearchThrows) throw new Error('search pill render failed');
+ return (
+ <button data-testid="sidebar-search" type="button" onClick={onClick}>
+ Search
+ </button>
+ );
+ },
+ onPillRenderError: (...args: unknown[]) => {
+ pillRenderErrors.push(args);
+ },
+}));
+
+mock.module('@/components/UpdateNotices', () => ({
+ UpdateNotices: () => <div data-testid="update-notices" />,
+}));
+
+mock.module('@/components/handoff/OpenInAgentEmptySpaceSubmenu', () => ({
+ OpenInAgentEmptySpaceSubmenu: (props: { input: unknown; webFallbackVisible: boolean }) => {
+ openInAgentSubmenuProps.push(props);
+ return (
+ <div
+ data-testid="open-in-agent-empty-space-submenu"
+ data-web-fallback-visible={String(props.webFallbackVisible)}
+ />
+ );
+ },
+}));
+
+mock.module('@/components/handoff/useHandoffDispatch', () => ({
+ buildFolderHandoffInput: () => ({ docContext: null, docPath: '', folderRelativePath: 'docs' }),
+ buildHandoffInput: () => ({
+ docContext: { docName: 'docs/current' },
+ docPath: 'docs/current.md',
+ }),
+ buildProjectScopedHandoffInput: ({ workspace: inputWorkspace }: { workspace: unknown }) =>
+ inputWorkspace ? { docContext: null, docPath: '', projectDir: '/tmp/open-knowledge' } : null,
+ useHandoffDispatch: () => ({ dispatch: mock(() => Promise.resolve({ ok: true })) }),
+}));
+
+mock.module('@/components/handoff/useInstalledAgents', () => ({
+ useInstalledAgents: () => ({ states: { codex: { installed: true } } }),
+}));
+
+mock.module('@/components/ui/button', () => ({
+ Button,
+}));
+
+mock.module('@/components/ui/context-menu', () => ({
+ ContextMenu: PassThrough,
+ ContextMenuContent: ({ children }: { children?: ReactNode }) => <div role="menu">{children}</div>,
+ ContextMenuItem: ({
+ children,
+ disabled,
+ onSelect,
+ ...props
+ }: {
+ children?: ReactNode;
+ disabled?: boolean;
+ onSelect?: () => void;
+ [key: string]: unknown;
+ }) => (
+ <button
+ type="button"
+ role="menuitem"
+ disabled={disabled}
+ onClick={() => {
+ if (!disabled) onSelect?.();
+ }}
+ {...props}
+ >
+ {children}
+ </button>
+ ),
+ ContextMenuCheckboxItem: ({
+ checked,
+ children,
+ disabled,
+ onCheckedChange,
+ ...props
+ }: {
+ checked?: boolean;
+ children?: ReactNode;
+ disabled?: boolean;
+ onCheckedChange?: (checked: boolean) => void;
+ [key: string]: unknown;
+ }) => (
+ <button
+ type="button"
+ role="menuitemcheckbox"
+ aria-checked={checked ? 'true' : 'false'}
+ disabled={disabled}
+ onClick={() => {
+ if (!disabled) onCheckedChange?.(!checked);
+ }}
+ {...props}
+ >
+ {children}
+ </button>
+ ),
+ ContextMenuSeparator: () => <hr data-testid="context-menu-separator" />,
+ ContextMenuSub: PassThrough,
+ ContextMenuSubContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ ContextMenuSubTrigger: Button,
+ ContextMenuTrigger: PassThrough,
+}));
+
+mock.module('@/components/ui/dropdown-menu', () => ({
+ DropdownMenu: PassThrough,
+ DropdownMenuContent: ({ children }: { children?: ReactNode }) => (
+ <div data-testid="tree-options-menu">{children}</div>
+ ),
+ DropdownMenuItem: Button,
+ DropdownMenuTrigger: PassThrough,
+}));
+
+mock.module('@/components/ui/sidebar', () => ({
+ Sidebar: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <aside data-testid="sidebar" {...props}>
+ {children}
+ </aside>
+ ),
+ SidebarContent: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <main data-testid="sidebar-content" {...props}>
+ {children}
+ </main>
+ ),
+ SidebarFooter: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <footer data-testid="sidebar-footer" {...props}>
+ {children}
+ </footer>
+ ),
+ SidebarHeader: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <header data-testid="sidebar-header" {...props}>
+ {children}
+ </header>
+ ),
+ SidebarMenu: ElementPassThrough,
+ SidebarMenuItem: ElementPassThrough,
+ SidebarRail: ({ enableToggle }: { enableToggle?: boolean }) => (
+ <button data-enable-toggle={String(enableToggle)} data-testid="sidebar-rail" type="button" />
+ ),
+ useSidebar: () => ({ state: sidebarState }),
+}));
+
+mock.module('@/components/ui/tooltip', () => ({
+ Tooltip: PassThrough,
+ TooltipContent: ({ children }: { children?: ReactNode }) => <div role="tooltip">{children}</div>,
+ TooltipTrigger: PassThrough,
+}));
+
+mock.module('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({
+ activeDocName,
+ activeTarget,
+ }),
+}));
+
+function templateEntries(folderPath: string | null) {
+ if (!hasTemplates) return [];
+ if (folderPath === '') {
+ return [
+ {
+ name: 'root-daily',
+ path: '.ok/templates/root-daily.md',
+ scope: 'local',
+ source_folder: '',
+ title: 'Root daily',
+ },
+ ];
+ }
+ return [
+ {
+ name: 'daily',
+ path: `${folderPath ?? ''}/.ok/templates/daily.md`,
+ scope: 'local',
+ source_folder: folderPath ?? '',
+ title: 'Daily',
+ },
+ ];
+}
+
+mock.module('@/hooks/use-folder-config', () => ({
+ useFolderConfig: (folderPath: string | null) => ({
+ state: {
+ status: 'ready',
+ data: { folder: { templates_available: templateEntries(folderPath) } },
+ },
+ }),
+}));
+
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ merged: mergedConfig,
+ projectLocalBinding: {
+ patch: projectLocalPatch,
+ },
+ }),
+}));
+
+mock.module('@/lib/dispatch-open-in-terminal', () => ({
+ dispatchOpenInTerminal: dispatchOpenInTerminalMock,
+}));
+
+mock.module('@/lib/use-workspace', () => ({
+ useWorkspace: () => workspace,
+}));
+
+mock.module('sonner', () => ({
+ toast: {
+ error: (...args: unknown[]) => toastErrors.push(args),
+ success: (...args: unknown[]) => toastSuccesses.push(args),
+ },
+}));
+
+async function renderSidebar() {
+ const { FileSidebar } = await import('./FileSidebar');
+ return render(<FileSidebar onOpenSearch={onOpenSearch} />);
+}
+
+describe('FileSidebar runtime behavior', () => {
+ beforeEach(() => {
+ cleanup();
+ sidebarState = 'expanded';
+ workspace = { contentDir: '/tmp/open-knowledge', pathSeparator: '/' };
+ activeDocName = 'docs/current';
+ activeTarget = { kind: 'folder', folderPath: 'docs' };
+ folderState = { folderCount: 2, expandedCount: 1 };
+ hasTemplates = true;
+ mergedConfig = { appearance: { sidebar: { showHiddenFiles: false, showAllFiles: true } } };
+ sidebarSearchThrows = false;
+ projectPatchResult = { ok: true };
+ openInAgentSubmenuProps = [];
+ toastSuccesses = [];
+ toastErrors = [];
+ pillRenderErrors = [];
+ treeListeners.clear();
+ for (const fn of [
+ treeCalls.collapseAll,
+ treeCalls.createFromTemplate,
+ treeCalls.expandAll,
+ treeCalls.startCreating,
+ treeCalls.startCreatingFromTemplate,
+ projectLocalPatch,
+ dispatchOpenInTerminalMock,
+ showItemInFolderMock,
+ notifyViewMenuStateChangedMock,
+ onOpenSearch,
+ ]) {
+ fn.mockClear();
+ }
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: undefined,
+ });
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: {
+ writeText: mock(() => Promise.resolve()),
+ },
+ });
+ });
+
+ afterEach(() => {
+ cleanup();
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: undefined,
+ });
+ });
+
+ test('web mode keeps the Files label, spread toolbar layout, search entry, and no Electron chrome classes', async () => {
+ await renderSidebar();
+
+ const header = screen.getByTestId('sidebar-header');
+ expect(screen.getByText('Files')).toBeTruthy();
+ expectVisualClassTokens(header.className, ['justify-between']);
+ expectVisualClassTokensAbsent(header.className, ['[-webkit-app-region:drag]']);
+ expect(header.getAttribute('data-electron-drag')).toBeNull();
+ expect(screen.queryByText('Project switcher')).toBeNull();
+
+ fireEvent.click(screen.getByTestId('sidebar-search'));
+ expect(onOpenSearch).toHaveBeenCalledTimes(1);
+ });
+
+ test('Electron mode moves identity to the footer and applies drag/no-drag chrome treatment', async () => {
+ installBridge();
+ await renderSidebar();
+
+ const header = screen.getByTestId('sidebar-header');
+ const toolbar = header.querySelector('div') as HTMLElement;
+ const pillRow = screen.getByTestId('sidebar-search').parentElement as HTMLElement;
+
+ expect(screen.queryByText('Files')).toBeNull();
+ expect(screen.getByText('Project switcher')).toBeTruthy();
+ expect(header.getAttribute('data-electron-drag')).toBe('');
+ expectVisualClassTokens(header.className, ['justify-end', '[-webkit-app-region:drag]']);
+ expectVisualClassTokens(toolbar.className, ['[&>*]:[-webkit-app-region:no-drag]']);
+ expectVisualClassTokens(pillRow.className, ['[-webkit-app-region:no-drag]']);
+ expect(screen.getByTestId('sidebar-rail').getAttribute('data-enable-toggle')).toBe('false');
+ });
+
+ test('collapsed Electron sidebar fades the toolbar and search pill in lockstep', async () => {
+ installBridge();
+ sidebarState = 'collapsed';
+ await renderSidebar();
+
+ expectVisualClassTokens(screen.getByTestId('sidebar-header').className, [
+ 'opacity-0',
+ 'motion-safe:transition-opacity',
+ 'motion-safe:duration-100',
+ 'motion-safe:ease-out',
+ ]);
+ const pillRow = screen.getByTestId('sidebar-search').parentElement as HTMLElement;
+ expectVisualClassTokens(pillRow.className, [
+ 'opacity-0',
+ 'motion-safe:transition-opacity',
+ 'motion-safe:duration-100',
+ 'motion-safe:ease-out',
+ ]);
+ });
+
+ test('toolbar actions use the active folder while tree-state actions smart-hide no-op menu items', async () => {
+ await renderSidebar();
+ await waitFor(() => expect(treeListeners.size).toBe(1));
+
+ fireEvent.click(screen.getAllByRole('button', { name: 'New File' })[0]);
+ fireEvent.click(screen.getAllByRole('button', { name: 'New from template' })[0]);
+ fireEvent.click(screen.getByRole('button', { name: 'Daily' }));
+ fireEvent.click(screen.getAllByRole('button', { name: 'New Folder' })[0]);
+ expect(treeCalls.startCreating).toHaveBeenCalledWith('file', 'docs');
+ expect(treeCalls.createFromTemplate).toHaveBeenCalledWith('docs', 'daily');
+ expect(treeCalls.startCreating).toHaveBeenCalledWith('folder', 'docs');
+
+ expect(screen.getByRole('button', { name: 'Expand All' })).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'Collapse All' })).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Expand All' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Collapse All' }));
+ expect(treeCalls.expandAll).toHaveBeenCalledTimes(1);
+ expect(treeCalls.collapseAll).toHaveBeenCalledTimes(1);
+
+ act(() => setFolderState({ folderCount: 2, expandedCount: 2 }));
+ expect(screen.queryByRole('button', { name: 'Expand All' })).toBeNull();
+ expect(screen.getByRole('button', { name: 'Collapse All' })).toBeTruthy();
+
+ act(() => setFolderState({ folderCount: 2, expandedCount: 0 }));
+ expect(screen.getByRole('button', { name: 'Expand All' })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'Collapse All' })).toBeNull();
+ });
+
+ test('empty-space menu renders ordered project-root actions and routes each runtime effect', async () => {
+ installBridge();
+ await renderSidebar();
+ await waitFor(() => expect(treeListeners.size).toBe(1));
+
+ const itemIds = [
+ 'empty-space-menu-new-file',
+ 'empty-space-menu-new-from-template',
+ 'empty-space-menu-new-folder',
+ 'empty-space-menu-reveal-in-finder',
+ 'open-in-agent-empty-space-submenu',
+ 'empty-space-menu-open-in-terminal',
+ 'empty-space-menu-copy-full-path',
+ 'empty-space-menu-show-hidden-files',
+ 'empty-space-menu-show-all-files',
+ 'empty-space-menu-expand-all',
+ 'empty-space-menu-collapse-all',
+ ];
+ const positions = itemIds.map((id) => {
+ const element = screen.getByTestId(id);
+ return Array.from(element.parentElement?.children ?? []).indexOf(element);
+ });
+ expect(positions).toEqual([...positions].sort((a, b) => a - b));
+
+ fireEvent.click(screen.getByTestId('empty-space-menu-new-file'));
+ fireEvent.click(screen.getByTestId('empty-space-menu-new-from-template'));
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Root daily' }));
+ fireEvent.click(screen.getByTestId('empty-space-menu-new-folder'));
+ expect(treeCalls.startCreating).toHaveBeenCalledWith('file', '');
+ expect(treeCalls.createFromTemplate).toHaveBeenCalledWith('', 'root-daily');
+ expect(treeCalls.startCreating).toHaveBeenCalledWith('folder', '');
+
+ fireEvent.click(screen.getByTestId('empty-space-menu-reveal-in-finder'));
+ expect(showItemInFolderMock).toHaveBeenCalledWith('/tmp/open-knowledge');
+
+ fireEvent.click(screen.getByTestId('empty-space-menu-open-in-terminal'));
+ expect(dispatchOpenInTerminalMock).toHaveBeenCalledWith(
+ window.okDesktop,
+ '/tmp/open-knowledge',
+ );
+
+ fireEvent.click(screen.getByTestId('empty-space-menu-copy-full-path'));
+ await waitFor(() =>
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith('/tmp/open-knowledge'),
+ );
+ expect(toastSuccesses[0]?.[0]).toBe('Copied full path');
+
+ fireEvent.click(screen.getByTestId('empty-space-menu-show-hidden-files'));
+ fireEvent.click(screen.getByTestId('empty-space-menu-show-all-files'));
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showHiddenFiles: true } },
+ });
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showAllFiles: false } },
+ });
+
+ expect(openInAgentSubmenuProps.at(-1)?.webFallbackVisible).toBe(false);
+ expect(openInAgentSubmenuProps.at(-1)?.input).toEqual({
+ docContext: null,
+ docPath: '',
+ projectDir: '/tmp/open-knowledge',
+ });
+ });
+
+ test('View menu state pushes merged visibility and tree smart-hide state to the desktop bridge', async () => {
+ installBridge();
+ await renderSidebar();
+
+ await waitFor(() =>
+ expect(notifyViewMenuStateChangedMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sidebarVisible: true,
+ canCollapseAll: true,
+ canExpandAll: true,
+ showAllFiles: true,
+ showHiddenFiles: false,
+ }),
+ ),
+ );
+
+ notifyViewMenuStateChangedMock.mockClear();
+ act(() => setFolderState({ folderCount: 2, expandedCount: 2 }));
+ await waitFor(() =>
+ expect(notifyViewMenuStateChangedMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ sidebarVisible: true,
+ canCollapseAll: true,
+ canExpandAll: false,
+ showAllFiles: true,
+ showHiddenFiles: false,
+ }),
+ ),
+ );
+ });
+
+ test('search pill render failures are contained to the pill row and reset when sidebar state changes', async () => {
+ const originalConsoleError = console.error;
+ console.error = mock(() => {}) as never;
+ try {
+ sidebarSearchThrows = true;
+ const rendered = await renderSidebar();
+
+ await waitFor(() => expect(pillRenderErrors.length).toBeGreaterThan(0));
+ expect(screen.queryByTestId('sidebar-search')).toBeNull();
+ expect(screen.getByTestId('file-tree-stub')).toBeTruthy();
+ expect(screen.getByTestId('sidebar-footer')).toBeTruthy();
+
+ sidebarSearchThrows = false;
+ sidebarState = 'collapsed';
+ const { FileSidebar } = await import('./FileSidebar');
+ rendered.rerender(<FileSidebar onOpenSearch={onOpenSearch} />);
+ expect(await screen.findByTestId('sidebar-search')).toBeTruthy();
+ } finally {
+ console.error = originalConsoleError;
+ }
+ });
+});
diff --git a/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx b/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
index db8bcb444..898a6c77a 100644
--- a/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
+++ b/packages/app/src/components/FileSidebar.menu-action.dom.test.tsx
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, waitFor } from '@testing-library/react';
-import type { ReactNode } from 'react';
+import { type ReactNode, useEffect } from 'react';
import type { ResolvedNavigationTarget } from './navigation-targets';
type MenuAction =
@@ -55,6 +55,19 @@ const ACTIVE_TARGET = {
} satisfies ResolvedNavigationTarget;
const notifyViewMenuStateChangedMock = mock(() => {});
+const toggleSidebarMock = mock(() => {});
+const showItemInFolderMock = mock((_path: string) => Promise.resolve());
+const dispatchOpenInTerminalMock = mock((_bridge: unknown, _path: string) => Promise.resolve());
+const handoffDispatchMock = mock((_target: string, _input: unknown) =>
+ Promise.resolve({ ok: true }),
+);
+const treeCalls = {
+ collapseAll: mock(() => {}),
+ expandAll: mock(() => {}),
+ startCreating: mock((_kind: 'file' | 'folder', _parentDir: string) => {}),
+ startCreatingFromTemplate: mock((_parentDir: string) => {}),
+};
+const projectLocalPatch = mock((_patch: unknown) => ({ ok: true as const }));
let menuActionCallback: ((action: MenuAction) => void) | null = null;
mock.module('@/lib/perf', () => ({
@@ -62,15 +75,31 @@ mock.module('@/lib/perf', () => ({
}));
mock.module('@/components/FileTree', () => ({
- FileTree: () => <div data-testid="file-tree-stub" />,
+ FileTree: ({ ref }: { ref?: (handle: unknown) => void }) => {
+ useEffect(() => {
+ const handle = {
+ collapseAll: treeCalls.collapseAll,
+ expandAll: treeCalls.expandAll,
+ getFolderState: () => ({ folderCount: 2, expandedCount: 1 }),
+ startCreating: treeCalls.startCreating,
+ startCreatingFromTemplate: treeCalls.startCreatingFromTemplate,
+ subscribe: () => () => {},
+ };
+ ref?.(handle);
+ return () => ref?.(null);
+ }, [ref]);
+ return <div data-testid="file-tree-stub" />;
+ },
+}));
+
+mock.module('@/components/ConflictsSection', () => ({
+ ConflictsSection: () => null,
}));
mock.module('@/components/ui/button', () => ({
Button,
}));
-const toggleSidebarMock = mock(() => {});
-
mock.module('@/components/ui/sidebar', () => ({
Sidebar: ElementPassThrough,
SidebarContent: ElementPassThrough,
@@ -112,14 +141,22 @@ mock.module('@/components/handoff/OpenInAgentEmptySpaceSubmenu', () => ({
}));
mock.module('@/components/handoff/useHandoffDispatch', () => ({
- buildFolderHandoffInput: () => null,
- buildHandoffInput: () => null,
- buildProjectScopedHandoffInput: () => null,
- useHandoffDispatch: () => ({ dispatch: mock(async () => ({ ok: true as const })) }),
+ buildFolderHandoffInput: () => ({ docContext: null, docPath: '', folderRelativePath: 'notes' }),
+ buildHandoffInput: () => ({
+ docContext: { docName: 'notes/source' },
+ docPath: 'notes/source.md',
+ projectDir: '/tmp/open-knowledge',
+ }),
+ buildProjectScopedHandoffInput: () => ({
+ docContext: null,
+ docPath: '',
+ projectDir: '/tmp/open-knowledge',
+ }),
+ useHandoffDispatch: () => ({ dispatch: handoffDispatchMock }),
}));
mock.module('@/components/handoff/useInstalledAgents', () => ({
- useInstalledAgents: () => ({ states: {} }),
+ useInstalledAgents: () => ({ states: { codex: { installed: true } } }),
}));
mock.module('@/components/ProjectSwitcher', () => ({
@@ -153,13 +190,13 @@ mock.module('@/hooks/use-folder-config', () => ({
mock.module('@/lib/config-provider', () => ({
useConfigContext: () => ({
- projectLocalBinding: null,
- merged: null,
+ projectLocalBinding: { patch: projectLocalPatch },
+ merged: { appearance: { sidebar: { showHiddenFiles: false, showAllFiles: true } } },
}),
}));
mock.module('@/lib/dispatch-open-in-terminal', () => ({
- dispatchOpenInTerminal: () => {},
+ dispatchOpenInTerminal: dispatchOpenInTerminalMock,
}));
mock.module('@/lib/use-workspace', () => ({
@@ -177,15 +214,35 @@ mock.module('sonner', () => ({
}));
const { FileSidebar } = await import('./FileSidebar');
-const { subscribeToFileTreeMenuActionDuplicate } = await import(
- '@/lib/file-tree-menu-action-events'
-);
+const {
+ subscribeToFileTreeMenuActionDelete,
+ subscribeToFileTreeMenuActionDuplicate,
+ subscribeToFileTreeMenuActionRename,
+} = await import('@/lib/file-tree-menu-action-events');
describe('FileSidebar menu-action runtime routing', () => {
beforeEach(() => {
menuActionCallback = null;
- notifyViewMenuStateChangedMock.mockClear();
- toggleSidebarMock.mockClear();
+ for (const fn of [
+ notifyViewMenuStateChangedMock,
+ toggleSidebarMock,
+ showItemInFolderMock,
+ dispatchOpenInTerminalMock,
+ handoffDispatchMock,
+ projectLocalPatch,
+ treeCalls.collapseAll,
+ treeCalls.expandAll,
+ treeCalls.startCreating,
+ treeCalls.startCreatingFromTemplate,
+ ]) {
+ fn.mockClear();
+ }
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: {
+ writeText: mock(() => Promise.resolve()),
+ },
+ });
Object.defineProperty(window, 'okDesktop', {
configurable: true,
value: {
@@ -194,7 +251,7 @@ describe('FileSidebar menu-action runtime routing', () => {
notifyViewMenuStateChanged: notifyViewMenuStateChangedMock,
},
shell: {
- showItemInFolder: mock(async () => {}),
+ showItemInFolder: showItemInFolderMock,
},
onMenuAction: (callback: (action: MenuAction) => void) => {
menuActionCallback = callback;
@@ -240,4 +297,99 @@ describe('FileSidebar menu-action runtime routing', () => {
expect(toggleSidebarMock).toHaveBeenCalledTimes(1);
});
+
+ test('create and tree-state actions route through the FileTree handle', async () => {
+ render(<FileSidebar onOpenSearch={() => {}} />);
+ await waitFor(() => expect(menuActionCallback).not.toBeNull());
+
+ menuActionCallback?.('new-doc' as MenuAction);
+ menuActionCallback?.('new-folder' as MenuAction);
+ menuActionCallback?.('new-from-template' as MenuAction);
+ menuActionCallback?.('expand-all-tree' as MenuAction);
+ menuActionCallback?.('collapse-all-tree' as MenuAction);
+
+ expect(treeCalls.startCreating).toHaveBeenCalledWith('file', 'notes');
+ expect(treeCalls.startCreating).toHaveBeenCalledWith('folder', 'notes');
+ expect(treeCalls.startCreatingFromTemplate).toHaveBeenCalledWith('notes');
+ expect(treeCalls.expandAll).toHaveBeenCalledTimes(1);
+ expect(treeCalls.collapseAll).toHaveBeenCalledTimes(1);
+ });
+
+ test('rename and move-to-trash menu actions emit the active target on FileTree event buses', async () => {
+ const renamed: ResolvedNavigationTarget[] = [];
+ const deleted: ResolvedNavigationTarget[] = [];
+ const unsubscribeRename = subscribeToFileTreeMenuActionRename((target) => renamed.push(target));
+ const unsubscribeDelete = subscribeToFileTreeMenuActionDelete((target) => deleted.push(target));
+
+ try {
+ render(<FileSidebar onOpenSearch={() => {}} />);
+ await waitFor(() => expect(menuActionCallback).not.toBeNull());
+
+ menuActionCallback?.('rename' as MenuAction);
+ menuActionCallback?.('move-to-trash' as MenuAction);
+
+ expect(renamed).toEqual([ACTIVE_TARGET]);
+ expect(deleted).toEqual([ACTIVE_TARGET]);
+ } finally {
+ unsubscribeRename();
+ unsubscribeDelete();
+ }
+ });
+
+ test('shell, clipboard, handoff, and visibility-toggle actions use runtime dependencies', async () => {
+ render(<FileSidebar onOpenSearch={() => {}} />);
+ await waitFor(() => expect(menuActionCallback).not.toBeNull());
+
+ menuActionCallback?.('reveal-in-finder' as MenuAction);
+ expect(showItemInFolderMock).toHaveBeenCalledWith('/tmp/open-knowledge/notes/source.md');
+
+ menuActionCallback?.('open-in-terminal' as MenuAction);
+ expect(dispatchOpenInTerminalMock).toHaveBeenCalledWith(
+ window.okDesktop,
+ '/tmp/open-knowledge/notes',
+ );
+
+ menuActionCallback?.('send-to-ai' as MenuAction);
+ expect(handoffDispatchMock).toHaveBeenCalledWith(
+ 'codex',
+ expect.objectContaining({ docPath: 'notes/source.md' }),
+ );
+
+ menuActionCallback?.('copy-full-path' as MenuAction);
+ await waitFor(() =>
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+ '/tmp/open-knowledge/notes/source.md',
+ ),
+ );
+
+ menuActionCallback?.('copy-relative-path' as MenuAction);
+ await waitFor(() =>
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith('notes/source.md'),
+ );
+
+ menuActionCallback?.('toggle-show-hidden-files' as MenuAction);
+ menuActionCallback?.('toggle-show-all-files' as MenuAction);
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showHiddenFiles: true } },
+ });
+ expect(projectLocalPatch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showAllFiles: false } },
+ });
+ });
+
+ test('pushes View menu state to the desktop bridge with merged visibility and tree gates', async () => {
+ render(<FileSidebar onOpenSearch={() => {}} />);
+
+ await waitFor(() =>
+ expect(notifyViewMenuStateChangedMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ canCollapseAll: true,
+ canExpandAll: true,
+ showAllFiles: true,
+ showHiddenFiles: false,
+ sidebarVisible: true,
+ }),
+ ),
+ );
+ });
});
diff --git a/packages/app/src/components/FileSidebar.test.ts b/packages/app/src/components/FileSidebar.test.ts
index 7da2d143a..7131858d9 100644
--- a/packages/app/src/components/FileSidebar.test.ts
+++ b/packages/app/src/components/FileSidebar.test.ts
@@ -1,6 +1,5 @@
import { describe, expect, test } from 'bun:test';
import { isInteractiveSidebarControl } from './FileSidebar';
-import SRC from './FileSidebar?raw';
describe('FileSidebar module', () => {
test('exports the FileSidebar component', async () => {
@@ -15,7 +14,7 @@ describe('FileSidebar module', () => {
});
describe('isInteractiveSidebarControl — runtime guard clauses', () => {
- test('returns false for null target (defensive against shim edge cases)', () => {
+ test('returns false for null target', () => {
expect(isInteractiveSidebarControl(null)).toBe(false);
});
@@ -25,450 +24,3 @@ describe('isInteractiveSidebarControl — runtime guard clauses', () => {
expect(isInteractiveSidebarControl(fakeElement)).toBe(false);
});
});
-
-describe('FileSidebar source-level guards — chrome-row retrofit', () => {
- test('detects Electron host via the canonical window.okDesktop != null idiom', () => {
- expect(SRC).toMatch(
- /typeof\s+window\s*!==\s*['"]undefined['"]\s*&&\s*window\.okDesktop\s*!=\s*null/,
- );
- expect(SRC).toContain('const isElectronHost');
- });
-
- test('reads sidebar state via useSidebar primitive', () => {
- expect(SRC).toContain('useSidebar');
- expect(SRC).toMatch(/state\s*:\s*sidebarState/);
- expect(SRC).toContain("const isExpanded = sidebarState === 'expanded';");
- expect(SRC).toContain("const isCollapsed = sidebarState === 'collapsed';");
- });
-
- test('does NOT render project name in SidebarHeader (ProjectSwitcher footer carries identity)', () => {
- expect(SRC).not.toMatch(/projectName/);
- expect(SRC).not.toMatch(/window\.okDesktop\?\.\s*config\.projectName/);
- });
-
- test('renders the action toolbar with justify-end in Electron, justify-between in web', () => {
- expect(SRC).toMatch(/isElectronHost\s*\?\s*['"]justify-end['"]\s*:\s*['"]justify-between['"]/);
- });
-
- test("hides 'Files' label in Electron mode (web-only section header)", () => {
- expect(SRC).toMatch(/isExpanded\s*&&\s*!isElectronHost[\s\S]*?Files/);
- });
-
- test("preserves the 'Files' label classes for web-mode visual continuity", () => {
- expect(SRC).toMatch(
- /font-mono\s+text-sm\s+uppercase\s+tracking-wider\s+text-sidebar-foreground\/50/,
- );
- });
-
- test('fades SidebarHeader content out during sidebar collapse in Electron mode', () => {
- expect(SRC).toMatch(/const\s+shouldFadeChrome\s*=\s*isElectronHost\s*&&\s*isCollapsed\s*;/);
- expect(SRC).toMatch(/shouldFadeChrome\s*&&\s*['"]opacity-0['"]/);
- });
-
- test('SidebarHeader empty space drags the window in Electron mode (mirrors EditorHeader)', () => {
- expect(SRC).toMatch(/isElectronHost\s*&&\s*['"]\[-webkit-app-region:drag\]['"]/);
- });
-
- test('SidebarHeader carries data-electron-drag so the globals.css `:has()` rule can target it', () => {
- expect(SRC).toMatch(
- /data-electron-drag=\{\s*isElectronHost\s*\?\s*['"]['"]\s*:\s*undefined\s*\}/,
- );
- });
-
- test('toolbar buttons opt out of drag via [&>*] no-drag in Electron mode', () => {
- expect(SRC).toMatch(/isElectronHost\s*&&\s*['"]\[&>\*\]:\[-webkit-app-region:no-drag\]['"]/);
- });
-
- test('frontloads the opacity fade — half the slide duration with ease-out', () => {
- expect(SRC).toMatch(
- /motion-safe:transition-opacity\s+motion-safe:duration-100\s+motion-safe:ease-out/,
- );
- });
-
- test('cn helper from @/lib/utils is used to compose conditional classes', () => {
- expect(SRC).toMatch(/from\s+['"]@\/lib\/utils['"]/);
- expect(SRC).toContain('cn(');
- });
-
- test('subscribes to FileTreeHandle via useState + ref-callback (no first-mount race)', () => {
- expect(SRC).toContain('useState<FileTreeHandle | null>(null)');
- expect(SRC).toMatch(/<FileTree\s+ref=\{setTree\}\s*\/>/);
- expect(SRC).toMatch(/useEffect\(\s*\(\)\s*=>\s*\{[\s\S]*?tree\.subscribe\(/);
- expect(SRC).toMatch(/\}\s*,\s*\[tree\]\s*\)/);
- expect(SRC).toMatch(/\.getFolderState\(\)/);
- expect(SRC).not.toMatch(
- /import\s*\{[^}]*\buseSyncExternalStore\b[^}]*\}\s*from\s*['"]react['"]/,
- );
- expect(SRC).not.toMatch(/useRef<FileTreeHandle/);
- });
-
- test('does NOT import useCallback — React Compiler memoizes inline arrows', () => {
- expect(SRC).not.toMatch(/import\s*\{[^}]*\buseCallback\b[^}]*\}\s*from\s*['"]react['"]/);
- });
-
- test('module-level EMPTY_FOLDER_STATE — stable initial state pre-handle-attach', () => {
- expect(SRC).toMatch(/^const\s+EMPTY_FOLDER_STATE/m);
- });
-
- test('hides Tree View Options dropdown trigger when there are no folders', () => {
- expect(SRC).toMatch(/hasFolders\s*\?\s*\(\s*<DropdownMenu>/);
- expect(SRC).toMatch(/<\/DropdownMenu>\s*\)\s*:\s*null/);
- });
-
- test('hides Expand All when allExpanded; hides Collapse All when noneExpanded', () => {
- expect(SRC).toMatch(/!allExpanded\s*\?\s*\(\s*<DropdownMenuItem[\s\S]*?Expand All/);
- expect(SRC).toMatch(/!noneExpanded\s*\?\s*\(\s*<DropdownMenuItem[\s\S]*?Collapse All/);
- });
-
- test('the lucide Search import is gone — pill is the canonical search entry point', () => {
- expect(SRC).not.toMatch(/import\s*\{[^}]*\bSearch\b[^}]*\}\s*from\s*['"]lucide-react['"]/);
- expect(SRC).not.toMatch(/<ToolbarButton\s+icon=\{Search\}/);
- });
-
- test('the four remaining ToolbarButtons keep their positions and behaviors', () => {
- expect(SRC).toMatch(/<ToolbarButton\s+icon=\{ListCollapse\}\s+label=\{t`Tree View Options`\}/);
- expect(SRC).toMatch(/<ToolbarButton[\s\S]*?icon=\{SquarePen\}[\s\S]*?label=\{t`New File`\}/);
- expect(SRC).toMatch(
- /<ToolbarButton[\s\S]*?icon=\{FilePlus\}[\s\S]*?label=\{t`New from template`\}/,
- );
- expect(SRC).toMatch(/<ToolbarButton[\s\S]*?icon=\{FolderPlus\}[\s\S]*?label=\{t`New Folder`\}/);
- });
-
- test('SidebarSearchBar is imported and mounted with onOpenSearch wired through', () => {
- expect(SRC).toMatch(
- /import\s*\{[^}]*\bSidebarSearchBar\b[^}]*\}\s*from\s*['"]@\/components\/SidebarSearchBar['"]/,
- );
- expect(SRC).toMatch(/<SidebarSearchBar\s+onClick=\{onOpenSearch\}\s*\/>/);
- });
-
- test('ErrorBoundary wraps the pill so a render-throw is contained to the row', () => {
- expect(SRC).toMatch(/import\s*\{\s*ErrorBoundary\s*\}\s*from\s*['"]react-error-boundary['"]/);
- expect(SRC).toMatch(
- /<ErrorBoundary[\s\S]*?fallbackRender=\{\(\)\s*=>\s*null\}[\s\S]*?<SidebarSearchBar[\s\S]*?<\/ErrorBoundary>/,
- );
- expect(SRC).not.toMatch(/FallbackComponent=\{/);
- });
-
- test('ErrorBoundary mounts the extracted onPillRenderError on its onError prop', () => {
- expect(SRC).toMatch(
- /import\s*\{[^}]*\bonPillRenderError\b[^}]*\}\s*from\s*['"]@\/components\/SidebarSearchBar['"]/,
- );
- expect(SRC).toMatch(
- /<ErrorBoundary[\s\S]*?onError=\{onPillRenderError\}[\s\S]*?<SidebarSearchBar/,
- );
- });
-
- test('ErrorBoundary exposes a recovery path via resetKeys keyed off sidebarState', () => {
- expect(SRC).toMatch(
- /<ErrorBoundary[\s\S]*?resetKeys=\{\[sidebarState\]\}[\s\S]*?<SidebarSearchBar/,
- );
- });
-
- test('pill row inherits Electron no-drag opt-out (structurally anchored)', () => {
- expect(SRC).toMatch(/isElectronHost\s*&&\s*['"]\[&>\*\]:\[-webkit-app-region:no-drag\]['"]/);
-
- expect(SRC).toMatch(
- /['"]px-2 pb-2['"][\s\S]{0,300}isElectronHost\s*&&\s*['"]\[-webkit-app-region:no-drag\]['"]/,
- );
- });
-
- test('imports the shadcn ContextMenu primitives for the empty-space surface (D28 / FR1)', () => {
- expect(SRC).toMatch(
- /import\s*\{[\s\S]*?\bContextMenu\b[\s\S]*?\bContextMenuContent\b[\s\S]*?\bContextMenuItem\b[\s\S]*?\bContextMenuTrigger\b[\s\S]*?\}\s*from\s*['"]@\/components\/ui\/context-menu['"]/,
- );
- });
-
- test('ContextMenu wraps Sidebar children INSIDE Sidebar (preserves Sidebar↔SidebarInset peer-data sibling-ship)', () => {
- expect(SRC).toMatch(/<Sidebar\s+variant="inset">[\s\S]*?<ContextMenu>/);
- expect(SRC).toMatch(/<ContextMenu>[\s\S]*?<ContextMenuTrigger\s+asChild>/);
- expect(SRC).toMatch(
- /<div\s+className="contents"\s+onContextMenu=\{handleSidebarSurfaceContextMenu\}>/,
- );
- expect(SRC).toMatch(/<\/ContextMenu>\s*\n?\s*<\/Sidebar>\s*\n?\s*\)\s*;\s*\n?\s*\}/);
- });
-
- test('the surface handler uses preventDefault + stopPropagation for button-target opt-out', () => {
- expect(SRC).toMatch(
- /const\s+handleSidebarSurfaceContextMenu[\s\S]*?if\s*\(\s*isInteractiveSidebarControl\(\s*event\.target\s*\)\s*\)\s*\{\s*\n?\s*event\.preventDefault\(\)\s*;\s*\n?\s*event\.stopPropagation\(\)\s*;\s*\n?\s*\}/,
- );
- });
-
- test('the isInteractiveSidebarControl selector covers all button-like sidebar controls', () => {
- expect(SRC).toMatch(
- /const\s+SIDEBAR_INTERACTIVE_CONTROL_SELECTOR\s*=\s*\n?\s*['"]button,\s*\[role="button"\],\s*\[role="menuitem"\],\s*input,\s*textarea,\s*select,\s*a\[href\]['"]/,
- );
- expect(SRC).toMatch(
- /target\.closest\(\s*SIDEBAR_INTERACTIVE_CONTROL_SELECTOR\s*\)\s*!==\s*null/,
- );
- expect(SRC).toMatch(/typeof\s+Element\s*===\s*['"]undefined['"]/);
- });
-
- test('empty-space menu — imports the dependencies the 11-item content needs (US-008)', () => {
- expect(SRC).toMatch(/import\s*\{\s*useWorkspace\s*\}\s*from\s*['"]@\/lib\/use-workspace['"]/);
- expect(SRC).toMatch(
- /import\s*\{[\s\S]*?\buseInstalledAgents\b[\s\S]*?\}\s*from\s*['"]@\/components\/handoff\/useInstalledAgents['"]/,
- );
- expect(SRC).toMatch(
- /import\s*\{[\s\S]*?\buseHandoffDispatch\b[\s\S]*?\}\s*from\s*['"]@\/components\/handoff\/useHandoffDispatch['"]/,
- );
- expect(SRC).toMatch(
- /import\s*\{[\s\S]*?\bbuildProjectScopedHandoffInput\b[\s\S]*?\}\s*from\s*['"]@\/components\/handoff\/useHandoffDispatch['"]/,
- );
- expect(SRC).toMatch(
- /import\s*\{\s*OpenInAgentEmptySpaceSubmenu\s*\}\s*from\s*['"]@\/components\/handoff\/OpenInAgentEmptySpaceSubmenu['"]/,
- );
- expect(SRC).toMatch(
- /import\s*\{\s*useConfigContext\s*\}\s*from\s*['"]@\/lib\/config-provider['"]/,
- );
- expect(SRC).toMatch(/import\s*\{\s*toast\s*\}\s*from\s*['"]sonner['"]/);
- expect(SRC).toMatch(
- /import\s*\{[\s\S]*?\bCopy\b[\s\S]*?\bFolderOpen\b[\s\S]*?\bTerminal\b[\s\S]*?\}\s*from\s*['"]lucide-react['"]/,
- );
- expect(SRC).toMatch(
- /import\s*\{[\s\S]*?\bContextMenuCheckboxItem\b[\s\S]*?\bContextMenuSeparator\b[\s\S]*?\}\s*from\s*['"]@\/components\/ui\/context-menu['"]/,
- );
- });
-
- test('empty-space menu — 11 items rendered in the spec §9 order (US-008)', () => {
- const items = [
- 'empty-space-menu-new-file',
- 'empty-space-menu-new-from-template',
- 'empty-space-menu-new-folder',
- 'empty-space-menu-reveal-in-finder',
- 'empty-space-menu-open-in-terminal',
- 'empty-space-menu-copy-full-path',
- 'empty-space-menu-show-hidden-files',
- 'empty-space-menu-show-all-files',
- 'empty-space-menu-expand-all',
- 'empty-space-menu-collapse-all',
- ];
- let lastIdx = -1;
- for (const id of items) {
- const idx = SRC.indexOf(`data-testid="${id}"`);
- expect(idx).toBeGreaterThan(lastIdx);
- lastIdx = idx;
- }
- });
-
- test('empty-space menu — Open with AI submenu mounts between Reveal and Open in Terminal (US-008)', () => {
- const sendToAiIdx = SRC.indexOf('<OpenInAgentEmptySpaceSubmenu');
- const revealIdx = SRC.indexOf('data-testid="empty-space-menu-reveal-in-finder"');
- const terminalIdx = SRC.indexOf('data-testid="empty-space-menu-open-in-terminal"');
- expect(sendToAiIdx).toBeGreaterThan(revealIdx);
- expect(sendToAiIdx).toBeLessThan(terminalIdx);
- });
-
- test('empty-space menu — Open with AI submenu hides the web fallback row (D25)', () => {
- expect(SRC).toMatch(
- /<OpenInAgentEmptySpaceSubmenu[\s\S]*?webFallbackVisible=\{false\}[\s\S]*?\/>/,
- );
- });
-
- test('empty-space menu — Reveal in Finder + Open in Terminal are Electron-only (D34)', () => {
- expect(SRC).toMatch(/\{bridge\s*\?\s*\([\s\S]*?empty-space-menu-reveal-in-finder/);
- expect(SRC).toMatch(/\{bridge\s*\?\s*\([\s\S]*?empty-space-menu-open-in-terminal/);
- });
-
- test('empty-space menu — Copy full path renders unconditionally per D36 (no bridge gate)', () => {
- const copyIdx = SRC.indexOf('data-testid="empty-space-menu-copy-full-path"');
- expect(copyIdx).toBeGreaterThan(-1);
- const windowBefore = SRC.slice(Math.max(0, copyIdx - 400), copyIdx);
- const lastBridgeOpenIdx = windowBefore.lastIndexOf('{bridge ?');
- if (lastBridgeOpenIdx >= 0) {
- const fragment = windowBefore.slice(lastBridgeOpenIdx);
- expect(fragment).toMatch(/:\s*null\}/);
- }
- });
-
- test('empty-space menu — disabled-with-hint pattern uses "No workspace" affordance (US-008)', () => {
- expect(SRC).toMatch(
- /aria-label=\{workspace\s*\?\s*t`Reveal in Finder`\s*:\s*t`Reveal in Finder,\s*No workspace`\}/,
- );
- expect(SRC).toMatch(
- /aria-label=\{workspace\s*\?\s*t`Open in Terminal`\s*:\s*t`Open in Terminal,\s*No workspace`\}/,
- );
- expect(SRC).toMatch(
- /aria-label=\{workspace\s*\?\s*t`Copy full path`\s*:\s*t`Copy full path,\s*No workspace`\}/,
- );
- });
-
- test('empty-space menu — Show . / Show all toggles bind to projectLocalBinding (US-008)', () => {
- expect(SRC).toMatch(/merged\?\.appearance\?\.sidebar\?\.showHiddenFiles\s*\?\?\s*false/);
- expect(SRC).toMatch(/merged\?\.appearance\?\.sidebar\?\.showAllFiles\s*\?\?\s*false/);
- expect(SRC).toMatch(
- /projectLocalBinding\.patch\(\s*\{\s*appearance:\s*\{\s*sidebar:\s*\{\s*showHiddenFiles:\s*checked/,
- );
- expect(SRC).toMatch(
- /projectLocalBinding\.patch\(\s*\{\s*appearance:\s*\{\s*sidebar:\s*\{\s*showAllFiles:\s*checked/,
- );
- expect(SRC).toMatch(/disabled=\{projectLocalBinding\s*===\s*null\}/);
- });
-
- test('empty-space menu — smart-hide gates for tree-state section (D15 / FR7)', () => {
- expect(SRC).toMatch(/const\s+showEmptySpaceExpandAll\s*=\s*hasFolders\s*&&\s*!allExpanded\s*;/);
- expect(SRC).toMatch(
- /const\s+showEmptySpaceCollapseAll\s*=\s*hasFolders\s*&&\s*!noneExpanded\s*;/,
- );
- expect(SRC).toMatch(
- /const\s+showEmptySpaceTreeStateSection\s*=\s*showEmptySpaceExpandAll\s*\|\|\s*showEmptySpaceCollapseAll\s*;/,
- );
- expect(SRC).toMatch(
- /\{showEmptySpaceTreeStateSection\s*\?\s*<ContextMenuSeparator\s*\/>\s*:\s*null\}/,
- );
- expect(SRC).toMatch(/\{showEmptySpaceExpandAll\s*\?\s*\([\s\S]*?Expand all/);
- expect(SRC).toMatch(/\{showEmptySpaceCollapseAll\s*\?\s*\([\s\S]*?Collapse all/);
- });
-
- test('empty-space menu — creation actions target the project root (D10)', () => {
- expect(SRC).toMatch(
- /const\s+handleEmptySpaceCreateFile\s*=\s*\(\)\s*=>\s*\{[\s\S]*?tree\?\.startCreating\(\s*['"]file['"]\s*,\s*['"]['"]\s*\)/,
- );
- expect(SRC).toMatch(
- /const\s+handleEmptySpaceSelectTemplate\s*=\s*\(templateName[^)]*\)\s*=>\s*\{[\s\S]*?tree\?\.createFromTemplate\(\s*['"]['"]\s*,\s*templateName\s*\)/,
- );
- expect(SRC).toMatch(
- /const\s+handleEmptySpaceCreateFolder\s*=\s*\(\)\s*=>\s*\{[\s\S]*?tree\?\.startCreating\(\s*['"]folder['"]\s*,\s*['"]['"]\s*\)/,
- );
- });
-
- test('empty-space menu — Open with AI submenu input uses buildProjectScopedHandoffInput (US-008)', () => {
- expect(SRC).toMatch(
- /const\s+emptySpaceHandoffInput\s*=\s*buildProjectScopedHandoffInput\(\s*\{\s*workspace\s*\}\s*\)/,
- );
- });
-
- test('empty-space menu — copy-to-clipboard uses navigator API per D36 (no bridge)', () => {
- expect(SRC).toMatch(/navigator\.clipboard\.writeText\(\s*workspace\.contentDir\s*\)/);
- });
-
- test('pill row fades synchronously with the toolbar during sidebar collapse (structurally anchored)', () => {
- const sidebarHeaderBlock = SRC.match(
- /SidebarHeader\b[^>]*?className=\{cn\(([\s\S]*?h-12[\s\S]*?)\)\}/,
- )?.[1];
- expect(sidebarHeaderBlock).toBeTruthy();
- expect(sidebarHeaderBlock).toMatch(/shouldFadeChrome\s*&&\s*['"]opacity-0['"]/);
- expect(sidebarHeaderBlock).toMatch(
- /motion-safe:transition-opacity\s+motion-safe:duration-100\s+motion-safe:ease-out/,
- );
- expect(sidebarHeaderBlock).toMatch(
- /isElectronHost\s*&&\s*isExpanded\s*&&\s*['"]motion-safe:delay-100['"]/,
- );
-
- const pillRowBlock = SRC.match(/cn\(\s*\n?\s*\/\/[\s\S]*?['"]px-2 pb-2['"]([\s\S]*?)\)/)?.[1];
- expect(pillRowBlock).toBeTruthy();
- expect(pillRowBlock).toMatch(/shouldFadeChrome\s*&&\s*['"]opacity-0['"]/);
- expect(pillRowBlock).toMatch(
- /motion-safe:transition-opacity\s+motion-safe:duration-100\s+motion-safe:ease-out/,
- );
- expect(pillRowBlock).toMatch(
- /isElectronHost\s*&&\s*isExpanded\s*&&\s*['"]motion-safe:delay-100['"]/,
- );
- });
-});
-
-describe('FileSidebar onMenuAction subscriber (US-020 + US-021)', () => {
- test('subscribes via the canonical bridge.onMenuAction surface', () => {
- expect(SRC).toMatch(/return\s+bridge\.onMenuAction\(\s*\(action\)\s*=>\s*\{/);
- });
-
- test('gates the subscription on bridge being present (web mode is no-op)', () => {
- const menuActionBlock =
- SRC.split('macOS menu-action subscriber')[1]?.split('return (')[0] ?? '';
- expect(menuActionBlock).toMatch(/if\s*\(!bridge\)\s*return\s*;/);
- });
-
- test('switch contains a case for every state-aware US-020 / US-021 action', () => {
- const ACTIONS = [
- 'new-doc',
- 'new-folder',
- 'new-from-template',
- 'rename',
- 'duplicate',
- 'move-to-trash',
- 'reveal-in-finder',
- 'open-in-terminal',
- 'send-to-ai',
- 'copy-full-path',
- 'copy-relative-path',
- 'toggle-show-hidden-files',
- 'toggle-show-all-files',
- 'expand-all-tree',
- 'collapse-all-tree',
- ];
- for (const action of ACTIONS) {
- expect(SRC).toMatch(new RegExp(`case\\s+['"]${action}['"]\\s*:`));
- }
- });
-
- test('move-to-trash routes through the FileTree event bus, not a direct HTTP call', () => {
- expect(SRC).toMatch(/emitFileTreeMenuActionDelete\(\s*activeTarget\s*\)/);
- });
-
- test('rename routes through the FileTree event bus, not a console warn', () => {
- expect(SRC).toMatch(/emitFileTreeMenuActionRename\(\s*activeTarget\s*\)/);
- expect(SRC).not.toMatch(/file-menu-rename-unsupported/);
- });
-
- test('reveal-in-finder + open-in-terminal go through the typed bridge.shell.* surface', () => {
- expect(SRC).toMatch(/bridge\.shell\.showItemInFolder\(\s*absPath\s*\)/);
- expect(SRC).toMatch(/dispatchOpenInTerminal\(\s*bridge\s*,\s*dirAbsPath\s*\)/);
- expect(SRC).toMatch(/dispatchOpenInTerminal\(\s*bridge\s*,\s*workspace\.contentDir\s*\)/);
- });
-
- test('toggle actions flip projectLocalBinding via .patch + surface validation failures', () => {
- expect(SRC).toMatch(
- /const result = projectLocalBinding\.patch\(\s*\{[\s\S]*?showHiddenFiles:\s*!showHiddenFiles/,
- );
- expect(SRC).toMatch(
- /const result = projectLocalBinding\.patch\(\s*\{[\s\S]*?showAllFiles:\s*!showAllFiles/,
- );
- expect(SRC).toMatch(/if \(!result\.ok\)/);
- expect(SRC).toMatch(/humanFormat\(result\.error\)/);
- });
-
- test('expand-all-tree + collapse-all-tree dispatch through the tree handle', () => {
- expect(SRC).toMatch(/case\s+['"]expand-all-tree['"]\s*:\s*\{\s*tree\?\.expandAll\(\)/);
- expect(SRC).toMatch(/case\s+['"]collapse-all-tree['"]\s*:\s*\{\s*tree\?\.collapseAll\(\)/);
- });
-
- test('toggle-sidebar invokes useSidebar().toggleSidebar()', () => {
- expect(SRC).toMatch(/case\s+['"]toggle-sidebar['"]\s*:\s*\{[\s\S]*?toggleSidebar\(\)/);
- });
-});
-
-describe('FileSidebar view-menu state push (US-021)', () => {
- test('declares a useEffect that calls bridge.editor.notifyViewMenuStateChanged', () => {
- expect(SRC).toMatch(/bridge\.editor\.notifyViewMenuStateChanged\(\s*\{/);
- });
-
- test('snapshot fields cover the full ViewMenuStateSnapshot shape', () => {
- const pushBlock =
- SRC.split('Push the View menu')[1]?.split('macOS menu-action subscriber')[0] ?? '';
- expect(pushBlock).toMatch(/showHiddenFiles/);
- expect(pushBlock).toMatch(/showAllFiles/);
- expect(pushBlock).toMatch(/canExpandAll:\s*showEmptySpaceExpandAll/);
- expect(pushBlock).toMatch(/canCollapseAll:\s*showEmptySpaceCollapseAll/);
- expect(pushBlock).toMatch(/sidebarVisible:\s*sidebarState\s*===\s*['"]expanded['"]/);
- });
-
- test('gates the push on bridge being present (web mode is no-op)', () => {
- const pushBlock =
- SRC.split('Push the View menu')[1]?.split('macOS menu-action subscriber')[0] ?? '';
- expect(pushBlock).toMatch(/if\s*\(!bridge\)\s*return\s*;/);
- });
-
- test('effect deps include the visibility flags AND the smart-hide signals AND sidebarState', () => {
- const pushBlock =
- SRC.split('Push the View menu')[1]?.split('macOS menu-action subscriber')[0] ?? '';
- expect(pushBlock).toMatch(
- /\[\s*bridge\s*,\s*showHiddenFiles\s*,\s*showAllFiles\s*,\s*showEmptySpaceExpandAll\s*,\s*showEmptySpaceCollapseAll\s*,\s*sidebarState\s*,?\s*\]/,
- );
- });
-
- test('canExpandAll / canCollapseAll mirror the empty-space menu gates exactly', () => {
- const pushBlock =
- SRC.split('Push the View menu')[1]?.split('macOS menu-action subscriber')[0] ?? '';
- expect(pushBlock).toContain('showEmptySpaceExpandAll');
- expect(pushBlock).toContain('showEmptySpaceCollapseAll');
- });
-});
diff --git a/packages/app/src/components/FileTree.duplicate.dom.test.tsx b/packages/app/src/components/FileTree.duplicate.dom.test.tsx
index 37a396304..388233336 100644
--- a/packages/app/src/components/FileTree.duplicate.dom.test.tsx
+++ b/packages/app/src/components/FileTree.duplicate.dom.test.tsx
@@ -7,7 +7,9 @@ import type { ResolvedNavigationTarget } from './navigation-targets';
type MenuItemProps = {
children?: ReactNode;
+ checked?: boolean;
disabled?: boolean;
+ onCheckedChange?: (checked: boolean) => void;
onSelect?: () => void;
[key: string]: unknown;
};
@@ -16,15 +18,35 @@ function PassThrough({ children }: { children?: ReactNode }) {
return <>{children}</>;
}
-function MenuItem({ children, disabled, onSelect, variant: _variant, ...props }: MenuItemProps) {
+function MenuItem({
+ children,
+ checked,
+ disabled,
+ onCheckedChange,
+ onSelect,
+ variant: _variant,
+ ...props
+}: MenuItemProps) {
+ const handleClick = () => {
+ onCheckedChange?.(!checked);
+ onSelect?.();
+ };
+ if (checked !== undefined) {
+ return (
+ <button
+ type="button"
+ role="menuitemcheckbox"
+ aria-checked={checked}
+ disabled={disabled}
+ onClick={handleClick}
+ {...props}
+ >
+ {children}
+ </button>
+ );
+ }
return (
- <button
- type="button"
- role="menuitem"
- disabled={disabled}
- onClick={() => onSelect?.()}
- {...props}
- >
+ <button type="button" role="menuitem" disabled={disabled} onClick={handleClick} {...props}>
{children}
</button>
);
@@ -184,6 +206,14 @@ let duplicateStatus = 200;
let duplicateGate: Promise<void> | null = null;
let duplicateFetchError: Error | null = null;
let fetchCalls: FetchCall[] = [];
+let okignoreBindingMock: {
+ current: () => string;
+ patch: ReturnType<typeof mock>;
+} | null = null;
+let projectLocalBindingMock: { patch: ReturnType<typeof mock> } | null = null;
+let mergedConfigMock: {
+ appearance?: { sidebar?: { showHiddenFiles?: boolean; showAllFiles?: boolean } };
+} | null = null;
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
@@ -196,6 +226,20 @@ function duplicateCalls() {
return fetchCalls.filter((call) => call.url === '/api/duplicate-path');
}
+function expectMenuOrder(labels: readonly RegExp[]) {
+ const items = Array.from(
+ document.querySelectorAll<HTMLElement>('[role="menuitem"], [role="menuitemcheckbox"]'),
+ );
+ let cursor = -1;
+ for (const label of labels) {
+ const next = items.findIndex(
+ (item, index) => index > cursor && label.test(item.textContent ?? ''),
+ );
+ expect(next, `expected menu item ${label} after index ${cursor}`).toBeGreaterThan(cursor);
+ cursor = next;
+ }
+}
+
function makeFetchMock() {
return mock(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
@@ -256,9 +300,9 @@ mock.module('./ui/sidebar', () => ({
mock.module('@/lib/config-provider', () => ({
useConfigContext: () => ({
- okignoreBinding: null,
- projectLocalBinding: null,
- merged: null,
+ okignoreBinding: okignoreBindingMock,
+ projectLocalBinding: projectLocalBindingMock,
+ merged: mergedConfigMock,
}),
}));
@@ -273,7 +317,16 @@ mock.module('./handoff/useHandoffDispatch', () => ({
}));
mock.module('./handoff/OpenInAgentContextSubmenu', () => ({
- OpenInAgentContextSubmenu: () => null,
+ OpenInAgentContextSubmenu: ({ webFallbackVisible }: { webFallbackVisible?: boolean }) => (
+ <button
+ type="button"
+ role="menuitem"
+ data-testid="file-tree-menu-open-in-agent"
+ data-web-fallback-visible={String(webFallbackVisible)}
+ >
+ Open with AI
+ </button>
+ ),
}));
mock.module('./sidebar-hover-prewarm', () => ({
@@ -386,6 +439,9 @@ describe('FileTree duplicate action runtime behavior', () => {
duplicateGate = null;
duplicateFetchError = null;
fetchCalls = [];
+ okignoreBindingMock = null;
+ projectLocalBindingMock = null;
+ mergedConfigMock = null;
globalThis.fetch = makeFetchMock() as unknown as typeof fetch;
toastSuccessMock.mockClear();
toastErrorMock.mockClear();
@@ -431,6 +487,49 @@ describe('FileTree duplicate action runtime behavior', () => {
expect(closeMenuMock).toHaveBeenCalled();
});
+ test('file context-menu Hide appends an anchored okignore pattern and shows reversible copy', async () => {
+ okignoreBindingMock = {
+ current: () => '',
+ patch: mock(() => ({ ok: true })),
+ };
+ const user = userEvent.setup();
+ renderFileTree();
+
+ const hide = (await screen.findByTestId('file-tree-menu-hide')) as HTMLButtonElement;
+ expect(hide.disabled).toBe(false);
+ expect(hide.textContent).toContain('Hide this file');
+
+ await user.click(hide);
+
+ expect(closeMenuMock).toHaveBeenCalled();
+ expect(okignoreBindingMock.patch).toHaveBeenCalledWith('/notes/source.mdx\n');
+ expect(toastSuccessMock).toHaveBeenCalledWith('Hidden “source”', {
+ description: 'Manage hidden files in Settings → Ignore patterns.',
+ duration: 5000,
+ });
+ });
+
+ test('Hide is disabled without the shared okignore binding and dedupes existing patterns', async () => {
+ renderFileTree();
+ expect(((await screen.findByTestId('file-tree-menu-hide')) as HTMLButtonElement).disabled).toBe(
+ true,
+ );
+ cleanup();
+
+ okignoreBindingMock = {
+ current: () => '/notes/source.mdx\n',
+ patch: mock(() => ({ ok: true })),
+ };
+ const user = userEvent.setup();
+ renderFileTree();
+
+ await user.click(await screen.findByTestId('file-tree-menu-hide'));
+
+ expect(closeMenuMock).toHaveBeenCalled();
+ expect(okignoreBindingMock.patch).not.toHaveBeenCalled();
+ expect(toastSuccessMock).not.toHaveBeenCalledWith('Hidden “source”', expect.anything());
+ });
+
test('folder context-menu Duplicate posts the selected folder target and navigates to the copy', async () => {
menuItem = { kind: 'directory', path: 'notes/' };
duplicateResponse = {
@@ -465,6 +564,75 @@ describe('FileTree duplicate action runtime behavior', () => {
expect(closeMenuMock).toHaveBeenCalled();
});
+ test('folder context menu exposes runtime order, subtree actions, visibility toggles, and folder hide', async () => {
+ menuItem = { kind: 'directory', path: 'notes/' };
+ okignoreBindingMock = {
+ current: () => '',
+ patch: mock(() => ({ ok: true })),
+ };
+ projectLocalBindingMock = { patch: mock(() => ({ ok: true })) };
+ mergedConfigMock = {
+ appearance: { sidebar: { showHiddenFiles: true, showAllFiles: false } },
+ };
+ const user = userEvent.setup();
+ renderFileTree();
+
+ await screen.findByRole('menuitem', { name: /duplicate/i });
+ expectMenuOrder([
+ /New File/,
+ /New from template/,
+ /New Folder/,
+ /Open with AI/,
+ /Copy Path/,
+ /Show Hidden Files/,
+ /Show all files/,
+ /Expand All/,
+ /Duplicate/,
+ /Rename/,
+ /Hide folder/,
+ /Delete/,
+ ]);
+
+ const showHidden = screen.getByTestId('file-tree-menu-show-hidden-files');
+ const showAll = screen.getByTestId('file-tree-menu-show-all-files');
+ expect(showHidden.getAttribute('aria-checked')).toBe('true');
+ expect(showAll.getAttribute('aria-checked')).toBe('false');
+
+ await user.click(showAll);
+ expect(projectLocalBindingMock.patch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showAllFiles: true } },
+ });
+ await user.click(showHidden);
+ expect(projectLocalBindingMock.patch).toHaveBeenCalledWith({
+ appearance: { sidebar: { showHiddenFiles: false } },
+ });
+
+ await user.click(screen.getByRole('menuitem', { name: /expand all/i }));
+ expect(model.getItem('notes/')?.isExpanded()).toBe(true);
+
+ await user.click(screen.getByTestId('file-tree-menu-hide'));
+ expect(okignoreBindingMock.patch).toHaveBeenCalledWith('/notes/\n');
+ expect(toastSuccessMock).toHaveBeenCalledWith('Hidden folder “notes”', {
+ description: 'Manage hidden files in Settings → Ignore patterns.',
+ duration: 5000,
+ });
+ });
+
+ test('asset context menu keeps path actions and suppresses document-only actions', async () => {
+ menuItem = { kind: 'file', path: 'images/logo.png' };
+ renderFileTree();
+
+ await waitFor(() => {
+ expect(screen.queryByTestId('file-tree-menu-hide')).toBeNull();
+ });
+ expect(screen.queryByTestId('file-tree-menu-open-in-agent')).toBeNull();
+ expect(screen.queryByRole('menuitem', { name: /duplicate/i })).toBeNull();
+ expect(screen.getByRole('menuitem', { name: /rename/i })).toBeTruthy();
+ expect(screen.getByRole('menuitem', { name: /^delete/i })).toBeTruthy();
+ expect(screen.queryByTestId('file-tree-menu-show-hidden-files')).toBeNull();
+ expect(screen.getByRole('menuitem', { name: /copy path/i })).toBeTruthy();
+ });
+
test('duplicate response is schema-validated before UI reconciliation', async () => {
duplicateResponse = {
kind: 'file',
diff --git a/packages/app/src/components/FileTree.selection-mirror.test.ts b/packages/app/src/components/FileTree.selection-mirror.test.ts
deleted file mode 100644
index 1ac85ad77..000000000
--- a/packages/app/src/components/FileTree.selection-mirror.test.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
-
-const HOOK_SRC = readFileSync(join(__dirname, 'use-selection-mirror.ts'), 'utf8');
-
-const ACTIVE_TREE_PATH_DEPS_CLOSE =
- '}, [\n activeAncestorTreePathsSignature,\n activeTreePath,\n model,\n suppressSelectionRef,\n treePathsSignature,\n ]);';
-const USE_EFFECT_OPEN = 'useEffect(() => {';
-
-function extractActiveTreePathEffectBody(): string {
- const closeIdx = HOOK_SRC.indexOf(ACTIVE_TREE_PATH_DEPS_CLOSE);
- if (closeIdx === -1) {
- throw new Error(
- 'Could not locate the activeTreePath useEffect deps-array close in use-selection-mirror.ts. ' +
- `Expected substring: \`${ACTIVE_TREE_PATH_DEPS_CLOSE}\`. ` +
- 'If the deps changed, update this anchor AND re-evaluate whether the ' +
- 'singleton-selection contract still holds at the new effect site.',
- );
- }
- const openIdx = HOOK_SRC.lastIndexOf(USE_EFFECT_OPEN, closeIdx);
- if (openIdx === -1) {
- throw new Error(
- 'Could not locate the matching `useEffect(() => {` opener for the ' +
- 'activeTreePath effect.',
- );
- }
- return HOOK_SRC.slice(openIdx + USE_EFFECT_OPEN.length, closeIdx);
-}
-
-describe('FileTree — activeTreePath → Pierre selection mirror (singleton invariant)', () => {
- test('the activeTreePath useEffect block exists with its expected deps signature', () => {
- expect(HOOK_SRC).toContain(ACTIVE_TREE_PATH_DEPS_CLOSE);
- expect(extractActiveTreePathEffectBody().length).toBeGreaterThan(0);
- });
-
- test('the activeTreePath effect must NOT use the additive `item.select()` shorthand', () => {
- const body = extractActiveTreePathEffectBody();
- expect(body).not.toMatch(/\bitem\.select\(\)/);
- });
-
- test('the activeTreePath effect must use a replace-semantic selection primitive', () => {
- const body = extractActiveTreePathEffectBody();
- const usesOptionA = /(?<![_\w])selectOnlyTreeItem\s*\(/.test(body);
- const usesOptionB = /\.selectOnlyPath\s*\(/.test(body);
- expect(usesOptionA || usesOptionB).toBe(true);
- });
-
- test('the activeTreePath effect guards against singleton-collapse when multi-selection includes the active row', () => {
- const body = extractActiveTreePathEffectBody();
- expect(body).toMatch(/getSelectedPaths\(\)\.length\s*>\s*1/);
- expect(body).toMatch(/item\.isSelected\(\)/);
- });
-
- test('the activeTreePath effect must still call `item.focus()` (focus side effect preserved)', () => {
- const body = extractActiveTreePathEffectBody();
- expect(body).toMatch(/\bitem\.focus\(\)/);
- });
-});
diff --git a/packages/app/src/components/FileTree.test.ts b/packages/app/src/components/FileTree.test.ts
deleted file mode 100644
index 89dab0ea3..000000000
--- a/packages/app/src/components/FileTree.test.ts
+++ /dev/null
@@ -1,894 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
-
-const FILETREE_SRC = readFileSync(join(__dirname, 'FileTree.tsx'), 'utf8');
-
-function folderBranchSlice(): string {
- const start = FILETREE_SRC.indexOf('{isFolder ? (');
- expect(start).toBeGreaterThan(-1);
- const end = FILETREE_SRC.indexOf(') : (', start);
- expect(end).toBeGreaterThan(start);
- return FILETREE_SRC.slice(start, end);
-}
-
-function expectOrder(haystack: string, anchors: readonly string[]): void {
- let cursor = -1;
- for (const anchor of anchors) {
- const at = haystack.indexOf(anchor, cursor + 1);
- expect(at, `expected "${anchor}" after position ${cursor}`).toBeGreaterThan(cursor);
- cursor = at;
- }
-}
-
-describe('FileTree — Hide this file/folder menu item (source-level)', () => {
- test('FileTree consumes useConfigContext to read okignoreBinding', () => {
- expect(FILETREE_SRC).toMatch(
- /import\s*\{[^}]*useConfigContext[^}]*\}\s*from\s*'@\/lib\/config-provider'/,
- );
- expect(FILETREE_SRC).toMatch(/const\s*\{\s*okignoreBinding[^}]*\}\s*=\s*useConfigContext\(\)/);
- });
-
- test('FileTreeMenuProps declares okignoreBinding as OkignoreBinding | null', () => {
- expect(FILETREE_SRC).toMatch(/okignoreBinding:\s*OkignoreBinding\s*\|\s*null/);
- });
-
- test('renderContextMenu threads okignoreBinding into FileTreeMenu', () => {
- expect(FILETREE_SRC).toMatch(/okignoreBinding=\{okignoreBinding\}/);
- });
-
- test('imports the pure pattern-builder helper from file-tree-okignore', () => {
- expect(FILETREE_SRC).toMatch(
- /import\s*\{\s*buildOkignorePatternFromTarget\s*\}\s*from\s*'@\/components\/file-tree-okignore'/,
- );
- });
-
- test('imports appendPattern + serializeOkignoreDoc + parseOkignoreDoc from settings/okignore-doc', () => {
- expect(FILETREE_SRC).toMatch(/from\s*'@\/components\/settings\/okignore-doc'/);
- expect(FILETREE_SRC).toContain('appendPattern');
- expect(FILETREE_SRC).toContain('serializeOkignoreDoc');
- expect(FILETREE_SRC).toContain('parseOkignoreDoc');
- });
-
- test('label flips between file and folder copy', () => {
- expect(FILETREE_SRC).toContain('t`Hide this file`');
- expect(FILETREE_SRC).toContain('t`Hide folder`');
- expect(FILETREE_SRC).toMatch(/isFolder\s*\?\s*t`Hide folder`\s*:\s*t`Hide this file`/);
- });
-
- test('canHide gates on a non-asset target and okignoreBinding !== null', () => {
- expect(FILETREE_SRC).toMatch(/okignoreTarget\s*=\s*target\.kind\s*===\s*'asset'\s*\?/);
- expect(FILETREE_SRC).toMatch(
- /canHide\s*=\s*okignoreTarget\s*!==\s*null\s*&&\s*okignoreBinding\s*!==\s*null/,
- );
- });
-
- test('menu item exposes the data-testid and the disabled gate (both surfaces)', () => {
- expect(FILETREE_SRC).toContain('data-testid="file-tree-menu-hide"');
- expect(FILETREE_SRC).toMatch(/disabled=\{!canHide\}/);
- });
-
- test('file/asset branch keeps Hide behind the okignoreTarget gate (asset rows omit it)', () => {
- const branch = fileBranchSlice();
- const hideIdx = branch.indexOf('data-testid="file-tree-menu-hide"');
- expect(hideIdx).toBeGreaterThan(-1);
- const blockOpen = branch.lastIndexOf('{okignoreTarget ? (', hideIdx);
- expect(blockOpen).toBeGreaterThan(-1);
- const deleteIdx = branch.indexOf('{deleteLabel}', hideIdx);
- expect(deleteIdx).toBeGreaterThan(hideIdx);
- const sliceBetween = branch.slice(blockOpen, deleteIdx);
- expect(sliceBetween).toContain('data-testid="file-tree-menu-hide"');
- expect(sliceBetween).toContain('{hideLabel}');
- });
-
- test('folder branch renders Hide + Delete unconditionally (folders are never assets)', () => {
- const folder = folderBranchSlice();
- expect(folder).toContain('data-testid="file-tree-menu-hide"');
- expect(folder).toContain('{deleteLabel}');
- expect(folder).not.toContain('{!isAsset ? (');
- });
-
- test('Hide menu item is NOT marked destructive (variant="destructive" reserved for Delete)', () => {
- const hideTestidIdx = FILETREE_SRC.indexOf('data-testid="file-tree-menu-hide"');
- expect(hideTestidIdx).toBeGreaterThan(-1);
- const itemOpen = FILETREE_SRC.lastIndexOf('<DropdownMenuItem', hideTestidIdx);
- expect(itemOpen).toBeGreaterThan(-1);
- const itemClose = FILETREE_SRC.indexOf('</DropdownMenuItem>', hideTestidIdx);
- expect(itemClose).toBeGreaterThan(itemOpen);
- const fragment = FILETREE_SRC.slice(itemOpen, itemClose);
- expect(fragment).not.toContain('variant="destructive"');
- });
-
- test('onSelect routes through the binding patch path with appendPattern', () => {
- expect(FILETREE_SRC).toMatch(/buildOkignorePatternFromTarget\(okignoreTarget\)/);
- expect(FILETREE_SRC).toMatch(/okignoreBinding\.current\(\)/);
- expect(FILETREE_SRC).toMatch(/parseOkignoreDoc\(current\)/);
- expect(FILETREE_SRC).toMatch(/appendPattern\(doc,\s*pattern\)/);
- expect(FILETREE_SRC).toMatch(/okignoreBinding\.patch\(serializeOkignoreDoc\(updated\)\)/);
- });
-
- test('onSelect short-circuits when appendPattern returns the same doc (dedup no-op)', () => {
- const hideStart = FILETREE_SRC.indexOf('data-testid="file-tree-menu-hide"');
- expect(hideStart).toBeGreaterThan(-1);
- const itemEnd = FILETREE_SRC.indexOf('</DropdownMenuItem>', hideStart);
- expect(itemEnd).toBeGreaterThan(hideStart);
- const fragment = FILETREE_SRC.slice(hideStart, itemEnd);
- const guardIdx = fragment.search(/if\s*\(\s*updated\s*===\s*doc\s*\)\s*return;/);
- const patchIdx = fragment.indexOf('okignoreBinding.patch(');
- expect(guardIdx).toBeGreaterThan(-1);
- expect(patchIdx).toBeGreaterThan(guardIdx);
- });
-
- test('onSelect closes the context menu before patching (matches Rename/Delete UX)', () => {
- const hideStart = FILETREE_SRC.indexOf('data-testid="file-tree-menu-hide"');
- expect(hideStart).toBeGreaterThan(-1);
- const itemEnd = FILETREE_SRC.indexOf('</DropdownMenuItem>', hideStart);
- expect(itemEnd).toBeGreaterThan(hideStart);
- const fragment = FILETREE_SRC.slice(hideStart, itemEnd);
- const closeIdx = fragment.indexOf('close()');
- const patchIdx = fragment.indexOf('okignoreBinding.patch(');
- expect(closeIdx).toBeGreaterThan(-1);
- expect(patchIdx).toBeGreaterThan(closeIdx);
- });
-
- test('uses the EyeOff lucide icon (visual cue that the file is being hidden, not deleted)', () => {
- expect(FILETREE_SRC).toMatch(/import\s*\{[^}]*EyeOff[^}]*\}\s*from\s*'lucide-react'/);
- const hideStart = FILETREE_SRC.indexOf('data-testid="file-tree-menu-hide"');
- const itemEnd = FILETREE_SRC.indexOf('</DropdownMenuItem>', hideStart);
- const fragment = FILETREE_SRC.slice(hideStart, itemEnd);
- expect(fragment).toContain('<EyeOff');
- });
-
- test('no confirmation dialog (Hide is reversible via Settings)', () => {
- const hideStart = FILETREE_SRC.indexOf('data-testid="file-tree-menu-hide"');
- const itemEnd = FILETREE_SRC.indexOf('</DropdownMenuItem>', hideStart);
- const fragment = FILETREE_SRC.slice(hideStart, itemEnd);
- expect(fragment).not.toMatch(/window\.confirm/);
- expect(fragment).not.toMatch(/<Dialog/);
- expect(fragment).not.toMatch(/<AlertDialog/);
- });
-});
-
-describe('FileTree — folder right-click menu §9 reorder (US-009 source-level)', () => {
- test('threads projectLocalBinding + merged config from useConfigContext into FileTreeMenu', () => {
- expect(FILETREE_SRC).toMatch(
- /const\s*\{\s*okignoreBinding,\s*projectLocalBinding,\s*merged\s*\}\s*=\s*useConfigContext\(\)/,
- );
- expect(FILETREE_SRC).toMatch(/projectLocalBinding=\{projectLocalBinding\}/);
- expect(FILETREE_SRC).toMatch(/mergedConfig=\{merged\}/);
- });
-
- test('FileTreeMenuProps declares the new config props with core types', () => {
- expect(FILETREE_SRC).toMatch(/projectLocalBinding:\s*ConfigBinding\s*\|\s*null/);
- expect(FILETREE_SRC).toMatch(/mergedConfig:\s*Config\s*\|\s*null/);
- expect(FILETREE_SRC).toMatch(
- /import\s*\{[^}]*type Config,\s*\n?\s*type ConfigBinding[^}]*\}\s*from\s*'@inkeep\/open-knowledge-core'/,
- );
- });
-
- test('toggle handlers patch the project-local appearance.sidebar leaves + surface validation failures', () => {
- expect(FILETREE_SRC).toMatch(
- /const result = projectLocalBinding\.patch\(\{\s*appearance:\s*\{\s*sidebar:\s*\{\s*showHiddenFiles:\s*checked\s*,?\s*\}\s*,?\s*\}\s*,?\s*\}\)/,
- );
- expect(FILETREE_SRC).toMatch(
- /const result = projectLocalBinding\.patch\(\{\s*appearance:\s*\{\s*sidebar:\s*\{\s*showAllFiles:\s*checked\s*,?\s*\}\s*,?\s*\}\s*,?\s*\}\)/,
- );
- expect(FILETREE_SRC).toMatch(/if \(!result\.ok\)/);
- expect(FILETREE_SRC).toMatch(/humanFormat\(result\.error\)/);
- expect(FILETREE_SRC).toMatch(/if\s*\(projectLocalBinding\s*===\s*null\)\s*return;/);
- });
-
- test('check-state reads from mergedConfig.appearance.sidebar', () => {
- expect(FILETREE_SRC).toMatch(
- /showHiddenFiles\s*=\s*mergedConfig\?\.appearance\?\.sidebar\?\.showHiddenFiles\s*\?\?\s*false/,
- );
- expect(FILETREE_SRC).toMatch(
- /showAllFiles\s*=\s*mergedConfig\?\.appearance\?\.sidebar\?\.showAllFiles\s*\?\?\s*false/,
- );
- });
-
- test('folder branch renders the 14-item / 5-section order from spec §9', () => {
- expectOrder(folderBranchSlice(), [
- 'New File',
- 'New from template',
- 'New Folder',
- '<DropdownMenuSeparator />',
- '<RevealInFileManagerMenuItem',
- '<OpenInAgentContextSubmenu',
- '<OpenInTerminalMenuItem',
- 'Copy Path',
- '<DropdownMenuSeparator />',
- 'data-testid="file-tree-menu-show-hidden-files"',
- 'data-testid="file-tree-menu-show-all-files"',
- 'Expand All',
- 'Collapse All',
- 'Duplicate',
- 'Rename',
- 'data-testid="file-tree-menu-hide"',
- '{deleteLabel}',
- ]);
- });
-
- test('folder Open with AI hides the claude.ai web fallback (no folder= companion param)', () => {
- const folder = folderBranchSlice();
- const submenuIdx = folder.indexOf('<OpenInAgentContextSubmenu');
- expect(submenuIdx).toBeGreaterThan(-1);
- const submenuEnd = folder.indexOf('/>', submenuIdx);
- expect(submenuEnd).toBeGreaterThan(submenuIdx);
- const submenu = folder.slice(submenuIdx, submenuEnd);
- expect(submenu).toContain('webFallbackVisible={false}');
- });
-
- test('file Open with AI explicitly opts into the claude.ai web fallback', () => {
- const start = FILETREE_SRC.indexOf(') : (');
- const fileBranch = FILETREE_SRC.slice(start);
- const submenuIdx = fileBranch.indexOf('<OpenInAgentContextSubmenu');
- expect(submenuIdx).toBeGreaterThan(-1);
- const submenuEnd = fileBranch.indexOf('/>', submenuIdx);
- const submenu = fileBranch.slice(submenuIdx, submenuEnd);
- expect(submenu).toContain('webFallbackVisible={true}');
- });
-
- test('OpenInTerminalMenuItem is Electron-only and folder-targeted', () => {
- expect(FILETREE_SRC).toMatch(/function OpenInTerminalMenuItem\(/);
- const fnStart = FILETREE_SRC.indexOf('function OpenInTerminalMenuItem(');
- const fnSlice = FILETREE_SRC.slice(fnStart, FILETREE_SRC.indexOf('\n}\n', fnStart));
- expect(fnSlice).toMatch(/if\s*\(!bridge\)\s*return null;/);
- expect(fnSlice).toContain('dispatchOpenInTerminal(bridge, dirAbsPath)');
- const folder = folderBranchSlice();
- expect(folder).toContain(
- '<OpenInTerminalMenuItem dirAbsPath={folderAbsPath} onClose={close} />',
- );
- expect(FILETREE_SRC).toMatch(/const folderAbsPath\s*=\s*\n?\s*isFolder && workspace/);
- });
-
- test('Show toggles are DropdownMenuCheckboxItem bound to the project-local binding', () => {
- expect(FILETREE_SRC).toMatch(
- /import\s*\{[^}]*DropdownMenuCheckboxItem[^}]*\}\s*from\s*'@\/components\/ui\/dropdown-menu'/,
- );
- const folder = folderBranchSlice();
- const dot = folder.indexOf('data-testid="file-tree-menu-show-hidden-files"');
- const dotItemOpen = folder.lastIndexOf('<DropdownMenuCheckboxItem', dot);
- expect(dotItemOpen).toBeGreaterThan(-1);
- const dotItem = folder.slice(dotItemOpen, folder.indexOf('</DropdownMenuCheckboxItem>', dot));
- expect(dotItem).toContain('checked={showHiddenFiles}');
- expect(dotItem).toContain('onCheckedChange={handleShowHiddenFilesToggle}');
- expect(dotItem).toContain('disabled={!canToggleVisibility}');
- });
-
- test("Expand/Collapse stay subtree-scoped (today's logic preserved, not tree-wide)", () => {
- const folder = folderBranchSlice();
- expect(folder).toContain('onExpandSubtree(item.path)');
- expect(folder).toContain('onCollapseSubtree(item.path)');
- expect(folder).toMatch(/showSubtreeExpandAll\s*\?\s*\(/);
- expect(folder).toMatch(/showSubtreeCollapseAll\s*\?\s*\(/);
- });
-
- test('Rename uses the inline-rename close (closeForInlineSurface, not close)', () => {
- const folder = folderBranchSlice();
- const renameIdx = folder.indexOf('model.startRenaming(item.path)');
- expect(renameIdx).toBeGreaterThan(-1);
- const onSelectOpen = folder.lastIndexOf('onSelect={', renameIdx);
- const handler = folder.slice(onSelectOpen, renameIdx);
- expect(handler).toContain('closeForInlineSurface()');
- });
-
- test('folder toast says "Hidden folder" while file toast stays "Hidden"', () => {
- const folder = folderBranchSlice();
- expect(folder).toMatch(/toast\.success\(t`Hidden folder/);
- const fileBranch = FILETREE_SRC.slice(FILETREE_SRC.indexOf(') : ('));
- expect(fileBranch).toMatch(/toast\.success\(t`Hidden /);
- expect(fileBranch).not.toMatch(/toast\.success\(t`Hidden folder/);
- });
-});
-
-function fileBranchSlice(): string {
- const start = FILETREE_SRC.indexOf(') : (');
- expect(start).toBeGreaterThan(-1);
- const end = FILETREE_SRC.indexOf('</DropdownMenuContent>', start);
- expect(end).toBeGreaterThan(start);
- return FILETREE_SRC.slice(start, end);
-}
-
-describe('FileTree — file right-click menu §9 reorder (US-010 source-level)', () => {
- test('parentDirAbsPath is computed for non-folder rows (folder rows use folderAbsPath)', () => {
- expect(FILETREE_SRC).toMatch(/const parentDirAbsPath:\s*string\s*\|\s*null\s*=\s*\(\(\)\s*=>/);
- expect(FILETREE_SRC).toMatch(/if\s*\(!workspace\s*\|\|\s*isFolder\)\s*return null;/);
- expect(FILETREE_SRC).toMatch(/if\s*\(lastSep\s*===\s*-1\)\s*return workspace\.contentDir;/);
- });
-
- test('file/asset branch renders the §9 act-section order (Reveal / SendToAI / Terminal / CopyPath)', () => {
- expectOrder(fileBranchSlice(), [
- '<RevealInFileManagerMenuItem',
- '<OpenInAgentContextSubmenu',
- '<OpenInTerminalMenuItem',
- 'Copy Path',
- ]);
- });
-
- test('file branch renders the §9 destructive-section order with asset-safe gates', () => {
- const branch = fileBranchSlice();
- expectOrder(branch, [
- '<DropdownMenuSeparator />',
- 'Duplicate',
- 'Rename',
- 'data-testid="file-tree-menu-hide"',
- '{deleteLabel}',
- ]);
- const duplicateIdx = branch.indexOf('Duplicate');
- const duplicateGate = branch.lastIndexOf('{!isAsset ? (', duplicateIdx);
- expect(duplicateGate).toBeGreaterThan(-1);
- const hideIdx = branch.indexOf('data-testid="file-tree-menu-hide"');
- const hideGate = branch.lastIndexOf('{okignoreTarget ? (', hideIdx);
- expect(hideGate).toBeGreaterThan(duplicateGate);
- });
-
- test('file/asset branch routes Open in Terminal through parentDirAbsPath (parent dir, not the row itself)', () => {
- expect(fileBranchSlice()).toContain(
- '<OpenInTerminalMenuItem dirAbsPath={parentDirAbsPath} onClose={close} />',
- );
- });
-
- test('asset rows suppress Open with AI / Duplicate / Hide but keep Reveal / Terminal / Copy / Rename / Delete', () => {
- const branch = fileBranchSlice();
- expect(branch).toMatch(/\{!isAsset && \(\s*<OpenInAgentContextSubmenu/);
- const revealIdx = branch.indexOf('<RevealInFileManagerMenuItem');
- const firstGateAfterReveal = branch.indexOf('{!isAsset', revealIdx);
- expect(firstGateAfterReveal).toBeGreaterThan(revealIdx);
- const terminalIdx = branch.indexOf('<OpenInTerminalMenuItem');
- const copyPathIdx = branch.indexOf('<DropdownMenuSub>');
- expect(terminalIdx).toBeGreaterThan(revealIdx);
- expect(copyPathIdx).toBeGreaterThan(terminalIdx);
- const renameIdx = branch.indexOf('Rename', copyPathIdx);
- const deleteIdx = branch.indexOf('{deleteLabel}', renameIdx);
- expect(renameIdx).toBeGreaterThan(copyPathIdx);
- expect(deleteIdx).toBeGreaterThan(renameIdx);
- });
-
- test('file branch Open with AI is the ONLY act-section item gated on !isAsset', () => {
- const branch = fileBranchSlice();
- const firstGate = branch.indexOf('{!isAsset');
- const submenuOpen = branch.indexOf('<OpenInAgentContextSubmenu');
- expect(submenuOpen).toBeGreaterThan(firstGate);
- expect(submenuOpen - firstGate).toBeLessThan(60);
- });
-
- test('Show Hidden Files / Show all files toggles do NOT appear on file/asset rows', () => {
- const branch = fileBranchSlice();
- expect(branch).not.toContain('data-testid="file-tree-menu-show-hidden-files"');
- expect(branch).not.toContain('data-testid="file-tree-menu-show-all-files"');
- });
-
- test('Expand All / Collapse All do NOT appear on file/asset rows (leaf rows have no tree state)', () => {
- const branch = fileBranchSlice();
- expect(branch).not.toContain('Expand All');
- expect(branch).not.toContain('Collapse All');
- });
-
- test('file/asset destructive section gates Duplicate and Hide separately', () => {
- const branch = fileBranchSlice();
- expect(branch.match(/\{!isAsset \? \(/g) ?? []).toHaveLength(1);
- expect(branch.match(/\{okignoreTarget \? \(/g) ?? []).toHaveLength(1);
- });
-});
-
-describe('FileTree — Show Hidden Files toggle wiring (US-012 source-level)', () => {
- test('FileTree reads showHiddenFiles from merged config with false default', () => {
- expect(FILETREE_SRC).toMatch(
- /const\s+showHiddenFiles\s*=\s*merged\?\.appearance\?\.sidebar\?\.showHiddenFiles\s*\?\?\s*false/,
- );
- });
-
- test('FileTree declares showHiddenFilesRef as a useRef<boolean> initialized to false', () => {
- expect(FILETREE_SRC).toMatch(/const\s+showHiddenFilesRef\s*=\s*useRef<boolean>\(false\)/);
- });
-
- test('showHiddenFilesRef.current is synced inside the bulk useLayoutEffect', () => {
- expect(FILETREE_SRC).toMatch(/showHiddenFilesRef\.current\s*=\s*showHiddenFiles;/);
- });
-
- test('docs-refresh closure filters via showHiddenFilesRef.current OR showAllFilesRef.current (US-012 + US-013 combined)', () => {
- expect(FILETREE_SRC).toMatch(
- /const\s+bypassClientDotDrop\s*=\s*showHiddenFilesRef\.current\s*\|\|\s*showAll/,
- );
- expect(FILETREE_SRC).toMatch(
- /filterVisibleEntries\(\s*success\.data\.documents\s+as\s+unknown\s+as\s+FileEntry\[\],\s*bypassClientDotDrop,?\s*\)/,
- );
- });
-
- test('refreshDocsScheduleRef is hoisted to allow re-fetch from sibling effects', () => {
- expect(FILETREE_SRC).toMatch(
- /const\s+refreshDocsScheduleRef\s*=\s*useRef<\(\(\)\s*=>\s*void\)\s*\|\s*null>\(null\)/,
- );
- expect(FILETREE_SRC).toMatch(
- /refreshDocsScheduleRef\.current\s*=\s*\(\)\s*=>\s*scheduler\.request\(\)/,
- );
- expect(FILETREE_SRC).toMatch(/refreshDocsScheduleRef\.current\s*=\s*null/);
- });
-
- test('separate useEffect triggers re-fetch on showHiddenFiles flip with first-render skip', () => {
- expect(FILETREE_SRC).toMatch(/const\s+isFirstShowHiddenFilesEffectRunRef\s*=\s*useRef\(true\)/);
- expect(FILETREE_SRC).toMatch(
- /if\s*\(isFirstShowHiddenFilesEffectRunRef\.current\)\s*\{\s*isFirstShowHiddenFilesEffectRunRef\.current\s*=\s*false;\s*return;\s*\}\s*refreshDocsScheduleRef\.current\?\.\(\);\s*\},\s*\[showHiddenFiles\]\)/,
- );
- });
-
- test('does NOT add showHiddenFiles to the docs-refresh useEffect dep array (avoids listener churn)', () => {
- const docsEffectStart = FILETREE_SRC.indexOf('async function refreshDocs()');
- expect(docsEffectStart).toBeGreaterThan(-1);
- const closing = FILETREE_SRC.indexOf('}, []);', docsEffectStart);
- expect(closing).toBeGreaterThan(docsEffectStart);
- expect(FILETREE_SRC.slice(closing, closing + 7)).toBe('}, []);');
- });
-});
-
-describe('FileTree — Show all files toggle wiring (US-013 source-level)', () => {
- test('FileTree reads showAllFiles from merged config with false default', () => {
- expect(FILETREE_SRC).toMatch(
- /const\s+showAllFiles\s*=\s*merged\?\.appearance\?\.sidebar\?\.showAllFiles\s*\?\?\s*false/,
- );
- });
-
- test('FileTree declares showAllFilesRef as a useRef<boolean> initialized to false', () => {
- expect(FILETREE_SRC).toMatch(/const\s+showAllFilesRef\s*=\s*useRef<boolean>\(false\)/);
- });
-
- test('showAllFilesRef.current is synced inside the bulk useLayoutEffect', () => {
- expect(FILETREE_SRC).toMatch(/showAllFilesRef\.current\s*=\s*showAllFiles;/);
- });
-
- test('docs-refresh closure picks the URL based on showAllFilesRef.current', () => {
- expect(FILETREE_SRC).toMatch(/const\s+showAll\s*=\s*showAllFilesRef\.current/);
- expect(FILETREE_SRC).toMatch(
- /const\s+url\s*=\s*showAll\s*\?\s*['"]\/api\/documents\?showAll=true['"]\s*:\s*['"]\/api\/documents['"]/,
- );
- expect(FILETREE_SRC).toMatch(
- /const\s+res\s*=\s*await\s+fetch\(\s*url,\s*\{[\s\S]*?signal:\s*controller\.signal[\s\S]*?\}\s*\)/,
- );
- expect(FILETREE_SRC).toMatch(
- /headers:\s*showAll\s*\?\s*SHOW_ALL_NDJSON_ACCEPT\s*:\s*undefined/,
- );
- expect(FILETREE_SRC).toMatch(/if\s*\(showAll\s*&&\s*isNdjsonResponse\(res\)\)/);
- });
-
- test('separate useEffect triggers re-fetch on showAllFiles flip with first-render skip', () => {
- expect(FILETREE_SRC).toMatch(/const\s+isFirstShowAllFilesEffectRunRef\s*=\s*useRef\(true\)/);
- expect(FILETREE_SRC).toMatch(
- /if\s*\(isFirstShowAllFilesEffectRunRef\.current\)\s*\{\s*isFirstShowAllFilesEffectRunRef\.current\s*=\s*false;\s*return;\s*\}\s*refreshDocsScheduleRef\.current\?\.\(\);\s*\},\s*\[showAllFiles\]\)/,
- );
- });
-
- test('does NOT add showAllFiles to the docs-refresh useEffect dep array', () => {
- const docsEffectStart = FILETREE_SRC.indexOf('async function refreshDocs()');
- expect(docsEffectStart).toBeGreaterThan(-1);
- const closing = FILETREE_SRC.indexOf('}, []);', docsEffectStart);
- expect(closing).toBeGreaterThan(docsEffectStart);
- expect(FILETREE_SRC.slice(closing, closing + 7)).toBe('}, []);');
- });
-});
-
-describe('FileTree — Option B 2-step Trash flow (US-018 source-level)', () => {
- test('imports TrashCleanupSuccessSchema for Step 2 response parsing', () => {
- expect(FILETREE_SRC).toContain('TrashCleanupSuccessSchema');
- });
-
- test('imports the VSCode-verbatim copy helper + TrashFailureModal', () => {
- expect(FILETREE_SRC).toMatch(
- /import\s*\{\s*selectTrashConfirmCopy[\s,]+trashTargetDisplayName\s*\}\s*from\s*'@\/components\/file-tree-trash-copy'/,
- );
- expect(FILETREE_SRC).toMatch(/TrashFailureModal/);
- expect(FILETREE_SRC).toMatch(/type\s+TrashFailedTarget/);
- });
-
- test('TrashFailureRequest interface declares failed + originalTargets', () => {
- expect(FILETREE_SRC).toMatch(
- /interface\s+TrashFailureRequest\s*\{[\s\S]*?failed:\s*TrashFailedTarget\[\]/,
- );
- expect(FILETREE_SRC).toMatch(
- /interface\s+TrashFailureRequest\s*\{[\s\S]*?originalTargets:\s*FileTreeTarget\[\]/,
- );
- });
-
- test('trashFailure state declared with TrashFailureRequest | null', () => {
- expect(FILETREE_SRC).toMatch(
- /const\s+\[trashFailure,\s*setTrashFailure\]\s*=\s*useState<TrashFailureRequest\s*\|\s*null>\(null\)/,
- );
- });
-
- test('handleDeleteTargets branches on Electron bridge + workspace before trashing', () => {
- const fn = FILETREE_SRC.indexOf('async function handleDeleteTargets(');
- expect(fn).toBeGreaterThan(-1);
- const slice = FILETREE_SRC.slice(fn, fn + 4000);
- expect(slice).toMatch(/if\s*\(bridge\s*&&\s*workspace\)\s*\{/);
- expect(slice).toContain('trashTargetsViaShell');
- expect(slice).toContain('postTrashCleanup');
- });
-
- test('trashTargetsViaShell awaits bridge.shell.trashItem per target with absolute path', () => {
- const fn = FILETREE_SRC.indexOf('async function trashTargetsViaShell(');
- expect(fn).toBeGreaterThan(-1);
- const slice = FILETREE_SRC.slice(fn, fn + 1600);
- expect(slice).toContain('buildTrashAbsPath(target, workspaceInfo)');
- expect(slice).toContain('bridge.shell.trashItem(absPath)');
- expect(slice).toContain('failed.push');
- expect(slice).toContain('trashed.push');
- });
-
- test('postTrashCleanup POSTs /api/trash/cleanup for each trashed target', () => {
- const fn = FILETREE_SRC.indexOf('async function postTrashCleanup(');
- expect(fn).toBeGreaterThan(-1);
- const slice = FILETREE_SRC.slice(fn, fn + 2400);
- expect(slice).toContain("'/api/trash/cleanup'");
- expect(slice).toContain('TrashCleanupSuccessSchema');
- });
-
- test('postTrashCleanup loop wraps fetch+parse in per-iteration try/catch so thrown fetch routes to failedCleanups', () => {
- const fn = FILETREE_SRC.indexOf('async function postTrashCleanup(');
- expect(fn).toBeGreaterThan(-1);
- const slice = FILETREE_SRC.slice(fn, fn + 3600);
- expect(slice).toMatch(/for\s*\(const\s+target\s+of\s+trashed\)\s*\{[\s\S]*?try\s*\{/);
- expect(slice).toMatch(/\}\s*catch\s*\(err\)\s*\{[\s\S]*?failedCleanups\.push/);
- expect(slice).toContain('trash-cleanup threw');
- });
-
- test('Option B ordering: trash IPC FIRST, then trash-cleanup, then aftermath', () => {
- const fn = FILETREE_SRC.indexOf('async function handleDeleteTargets(');
- const slice = FILETREE_SRC.slice(fn, fn + 4000);
- const trashIdx = slice.indexOf('trashTargetsViaShell');
- const cleanupIdx = slice.indexOf('postTrashCleanup(trashed)');
- const aftermathIdx = slice.indexOf('applyDeleteAftermath');
- expect(trashIdx).toBeGreaterThan(-1);
- expect(cleanupIdx).toBeGreaterThan(trashIdx);
- expect(aftermathIdx).toBeGreaterThan(cleanupIdx);
- });
-
- test('Step 1 partial failure: setTrashFailure called with failed + originalTargets', () => {
- const fn = FILETREE_SRC.indexOf('async function handleDeleteTargets(');
- const slice = FILETREE_SRC.slice(fn, fn + 4000);
- expect(slice).toMatch(
- /setTrashFailure\(\{\s*failed,\s*originalTargets:\s*\[\.\.\.deleteTargets\]\s*\}\)/,
- );
- });
-
- test('web mode (no bridge OR no workspace) falls back to hardDeleteTargets', () => {
- const fn = FILETREE_SRC.indexOf('async function handleDeleteTargets(');
- const slice = FILETREE_SRC.slice(fn, fn + 4000);
- expect(slice).toMatch(/}\s*else\s*\{[\s\S]*?await\s+hardDeleteTargets\(deleteTargets\)/);
- });
-
- test("hardDeleteTargets posts /api/delete-path (today's endpoint preserved)", () => {
- const fn = FILETREE_SRC.indexOf('async function hardDeleteTargets(');
- expect(fn).toBeGreaterThan(-1);
- const slice = FILETREE_SRC.slice(fn, fn + 2000);
- expect(slice).toContain("'/api/delete-path'");
- expect(slice).toContain('DeletePathSuccessSchema');
- });
-
- test('Trash Delete Permanently fallback re-uses hardDeleteTargets against failed subset', () => {
- const fn = FILETREE_SRC.indexOf('async function handleTrashFailureDeletePermanently(');
- expect(fn).toBeGreaterThan(-1);
- const slice = FILETREE_SRC.slice(fn, fn + 1600);
- expect(slice).toContain('originalTargets.filter');
- expect(slice).toContain('hardDeleteTargets');
- expect(slice).toContain('setTrashFailure(null)');
- });
-
- test('handleTrashFailureDeletePermanently catch mirrors handleDeleteTargets catch (no "Network error" misattribution)', () => {
- const fn = FILETREE_SRC.indexOf('async function handleTrashFailureDeletePermanently(');
- expect(fn).toBeGreaterThan(-1);
- const slice = FILETREE_SRC.slice(fn, fn + 1600);
- expect(slice).not.toContain('Network error');
- expect(slice).toContain('toast.error(t`Could not complete delete`');
- expect(slice).toMatch(/err\s+instanceof\s+Error\s*\?\s*err\.message\s*:\s*String\(err\)/);
- });
-
- test('Retry filters originalTargets to FAILED subset via compound kind:path key', () => {
- const fn = FILETREE_SRC.indexOf('async function handleTrashFailureRetry(');
- expect(fn).toBeGreaterThan(-1);
- const slice = FILETREE_SRC.slice(fn, fn + 800);
- expect(slice).toContain('setTrashFailure(null)');
- expect(slice).toContain('handleDeleteTargets(originals)');
- expect(slice).toMatch(
- /new Set\(trashFailure\.failed\.map\(\(f\) => `\$\{f\.kind\}:\$\{f\.path\}`\)\)/,
- );
- expect(slice).toMatch(
- /originalTargets\.filter\(\(t\)\s*=>\s*failedSet\.has\(`\$\{t\.kind\}:\$\{t\.path\}`\)\s*,?\s*\)/,
- );
- });
-
- test('DeleteConfirmationDialog gates copy variant on Electron bridge presence', () => {
- expect(FILETREE_SRC).toMatch(
- /const\s+variant:\s*'electron'\s*\|\s*'web'\s*=\s*[\s\S]*?window\.okDesktop\s*!=\s*null\s*\?\s*'electron'\s*:\s*'web'/,
- );
- expect(FILETREE_SRC).toMatch(/selectTrashConfirmCopy\(variant,\s*deleteRequest\.targets\)/);
- });
-
- test('multi-target list rendered with trashTargetDisplayName + stable React key', () => {
- expect(FILETREE_SRC).toMatch(/copy\.listedTargets\.map/);
- expect(FILETREE_SRC).toMatch(/key=\{`\$\{target\.kind\}:\$\{target\.path\}`\}/);
- expect(FILETREE_SRC).toContain('trashTargetDisplayName(target)');
- });
-
- test('TrashFailureModal mounts when trashFailure is set; cancel clears state', () => {
- const dialogStart = FILETREE_SRC.indexOf('open={!!trashFailure}');
- expect(dialogStart).toBeGreaterThan(-1);
- const slice = FILETREE_SRC.slice(dialogStart, dialogStart + 1200);
- expect(slice).toContain('<TrashFailureModal');
- expect(slice).toContain('failedTargets={trashFailure.failed}');
- expect(slice).toContain('onDeletePermanently={handleTrashFailureDeletePermanently}');
- expect(slice).toContain('onRetry={handleTrashFailureRetry}');
- expect(slice).toMatch(/onCancel=\{\(\)\s*=>\s*setTrashFailure\(null\)\}/);
- });
-
- test('applyDeleteAftermath is the single seam for tab close + IDB + tree state mirror', () => {
- const fn = FILETREE_SRC.indexOf('async function applyDeleteAftermath(');
- expect(fn).toBeGreaterThan(-1);
- const slice = FILETREE_SRC.slice(fn, fn + 3000);
- expect(slice).toContain('collectTabsToCloseForDelete');
- expect(slice).toContain('closeTabs');
- expect(slice).toContain('closeAndClearForRename');
- expect(slice).toContain('model.remove');
- expect(slice).toContain('setDocuments');
- expect(slice).toContain('emitDocumentsChanged');
- });
-
- test('duplicate success updates sidebar documents before navigating to the copy', () => {
- const fn = FILETREE_SRC.indexOf('async function handleDuplicateTarget(');
- expect(fn).toBeGreaterThan(-1);
- const slice = FILETREE_SRC.slice(fn, FILETREE_SRC.indexOf('toast.success', fn));
- expect(slice).toContain('applyDuplicateToDocuments(current, target, success)');
- expect(slice).toContain('resetModelToDocuments(next)');
- expect(slice).toContain('markNextDocumentsAsApplied(next)');
- expectOrder(slice, [
- 'const next = applyDuplicateToDocuments(current, target, success)',
- 'resetModelToDocuments(next)',
- 'markNextDocumentsAsApplied(next)',
- 'return next',
- 'emitDocumentsChanged',
- 'navigateToFolderWithPulse(success.path)',
- ]);
- expectOrder(slice, [
- 'const next = applyDuplicateToDocuments(current, target, success)',
- 'resetModelToDocuments(next)',
- 'markNextDocumentsAsApplied(next)',
- 'return next',
- 'emitDocumentsChanged',
- 'navigateToWithPulse(success.path)',
- ]);
- });
-});
-
-describe('FileTree — Sidebar extension badge (replaces US-007 CSS hide-and-reveal)', () => {
- const BADGE_MODULE_SRC = readFileSync(join(__dirname, 'file-tree-extension-badge.ts'), 'utf8');
-
- test('FileTree imports the badge processor + CSS from the dedicated module', () => {
- expect(FILETREE_SRC).toMatch(
- /import\s*\{[^}]*applyExtensionBadges[^}]*\}\s*from\s*'@\/components\/file-tree-extension-badge'/,
- );
- expect(FILETREE_SRC).toMatch(
- /import\s*\{[^}]*FILE_TREE_EXT_BADGE_CSS[^}]*\}\s*from\s*'@\/components\/file-tree-extension-badge'/,
- );
- });
-
- test('the .md/.mdx-only CSS hide-and-hover-reveal block is removed (its trailing-dot artifact is the bug)', () => {
- expect(FILETREE_SRC).not.toContain("[data-item-path$='.md']");
- expect(FILETREE_SRC).not.toContain("[data-item-path$='.mdx']");
- expect(FILETREE_SRC).not.toMatch(/:hover[^{]+:last-child\s*\{\s*display:\s*inline;/);
- });
-
- test('FILE_TREE_UNSAFE_CSS concatenates badge + rename-chip CSS (single unsafeCSS payload)', () => {
- expect(FILETREE_SRC).toMatch(
- /const\s+FILE_TREE_UNSAFE_CSS\s*=\s*`\$\{FILE_TREE_EXT_BADGE_CSS\}\\n\$\{FILE_TREE_RENAME_CHIP_CSS\}`\s*;/,
- );
- expect(FILETREE_SRC).toMatch(
- /import\s*\{[^}]*FILE_TREE_RENAME_CHIP_CSS[^}]*\}\s*from\s*'@\/components\/file-tree-rename-chip'/,
- );
- expect(FILETREE_SRC).toContain('useFileTree({');
- expect(FILETREE_SRC).toContain('unsafeCSS: FILE_TREE_UNSAFE_CSS,');
- });
-
- test('badge module imports getFileExtension from the existing rename-validation helper', () => {
- expect(BADGE_MODULE_SRC).toMatch(
- /import\s*\{[^}]*getFileExtension[^}]*\}\s*from\s*'@\/components\/file-tree-rename-validation'/,
- );
- });
-
- test('badge styling is small, muted, uppercase, non-interactive (matches text-muted-foreground/60 text-xs)', () => {
- expect(BADGE_MODULE_SRC).toContain(
- 'color: color-mix(in oklab, var(--muted-foreground) 60%, transparent)',
- );
- expect(BADGE_MODULE_SRC).toContain('font-size: 0.75rem');
- expect(BADGE_MODULE_SRC).toContain('text-transform: uppercase');
- expect(BADGE_MODULE_SRC).toContain('pointer-events: none');
- expect(BADGE_MODULE_SRC).toContain('user-select: none');
- });
-
- test('badge module preserves the pre-existing markdown selected-icon override (carryover from US-007)', () => {
- expect(BADGE_MODULE_SRC).toContain("[data-item-selected='true'] [data-icon-token='markdown']");
- });
-
- test('FileTree wires a useEffect MutationObserver that calls applyExtensionBadges', () => {
- expect(FILETREE_SRC).toContain('applyExtensionBadges(shadow)');
- const effectStart = FILETREE_SRC.indexOf('applyExtensionBadges(shadow)');
- expect(effectStart).toBeGreaterThan(-1);
- const useEffectIdx = FILETREE_SRC.lastIndexOf('useEffect(', effectStart);
- expect(useEffectIdx).toBeGreaterThan(-1);
- const effectClose = FILETREE_SRC.indexOf('}, [', effectStart);
- expect(effectClose).toBeGreaterThan(effectStart);
- const effectFragment = FILETREE_SRC.slice(useEffectIdx, effectClose);
- expect(effectFragment).toContain('shadowRoot');
- expect(effectFragment).toContain('new MutationObserver');
- expect(effectFragment).toContain('characterData: true');
- expect(effectFragment).toContain("attributeFilter: ['data-item-path']");
- });
-});
-
-describe('FileTree — Sidebar rename extension chip (lives next to badge)', () => {
- const CHIP_MODULE_SRC = readFileSync(join(__dirname, 'file-tree-rename-chip.ts'), 'utf8');
-
- test('FileTree imports the chip processor + CSS from the dedicated module', () => {
- expect(FILETREE_SRC).toMatch(
- /import\s*\{[^}]*applyRenameChip[^}]*\}\s*from\s*'@\/components\/file-tree-rename-chip'/,
- );
- expect(FILETREE_SRC).toMatch(
- /import\s*\{[^}]*FILE_TREE_RENAME_CHIP_CSS[^}]*\}\s*from\s*'@\/components\/file-tree-rename-chip'/,
- );
- });
-
- test('chip module imports getFileExtension from the existing rename-validation helper', () => {
- expect(CHIP_MODULE_SRC).toMatch(
- /import\s*\{[^}]*getFileExtension[^}]*\}\s*from\s*'@\/components\/file-tree-rename-validation'/,
- );
- });
-
- test('chip CSS targets only the active rename input + pads its inline-end so text clears the chip', () => {
- expect(CHIP_MODULE_SRC).toContain(
- '[data-item-section="content"]:has([data-item-rename-input])',
- );
- expect(CHIP_MODULE_SRC).toContain('padding-inline-end:');
- });
-
- test('chip is non-interactive (pointer-events: none + user-select: none + aria-hidden)', () => {
- expect(CHIP_MODULE_SRC).toContain('pointer-events: none');
- expect(CHIP_MODULE_SRC).toContain('user-select: none');
- expect(CHIP_MODULE_SRC).toContain("setAttribute('aria-hidden', 'true')");
- });
-
- test('strip path routes through the prototype native setter so React/Preact value-tracker syncs', () => {
- expect(CHIP_MODULE_SRC).toContain('window.HTMLInputElement.prototype');
- expect(CHIP_MODULE_SRC).toContain("new Event('input', { bubbles: true })");
- });
-
- test('basename is selected after strip (mirrors the tab rename UX)', () => {
- expect(CHIP_MODULE_SRC).toContain('setSelectionRange(0, stripped.length)');
- });
-
- test('FileTree wires a separate useEffect MutationObserver that calls applyRenameChip', () => {
- expect(FILETREE_SRC).toContain('applyRenameChip(shadow)');
- const effectStart = FILETREE_SRC.indexOf('applyRenameChip(shadow)');
- expect(effectStart).toBeGreaterThan(-1);
- const useEffectIdx = FILETREE_SRC.lastIndexOf('useEffect(', effectStart);
- expect(useEffectIdx).toBeGreaterThan(-1);
- const effectClose = FILETREE_SRC.indexOf('}, [', effectStart);
- expect(effectClose).toBeGreaterThan(effectStart);
- const effectFragment = FILETREE_SRC.slice(useEffectIdx, effectClose);
- expect(effectFragment).toContain('shadowRoot');
- expect(effectFragment).toContain('new MutationObserver');
- expect(effectFragment).toContain('childList: true');
- });
-});
-
-describe('FileTree — Sidebar rename extension preservation (US-008 source-level)', () => {
- test('FileTree imports the pure validateAndCoerceRenameDestination helper', () => {
- expect(FILETREE_SRC).toMatch(
- /import\s*\{[\s\S]*validateAndCoerceRenameDestination[\s\S]*\}\s*from\s*'@\/components\/file-tree-rename-validation'/,
- );
- });
-
- test('handleTreeRename calls the validator on RAW event paths (not the normalized ones)', () => {
- const handlerStart = FILETREE_SRC.indexOf('async function handleTreeRename(');
- expect(handlerStart).toBeGreaterThan(-1);
- const handlerEnd = FILETREE_SRC.indexOf('\n }\n', handlerStart);
- expect(handlerEnd).toBeGreaterThan(handlerStart);
- const handlerBody = FILETREE_SRC.slice(handlerStart, handlerEnd);
- expect(handlerBody).toMatch(
- /validateAndCoerceRenameDestination\(\s*event\.sourcePath,\s*event\.destinationPath,\s*event\.isFolder,\s*sourceIsAsset,?\s*\)/,
- );
- });
-
- test('the block branch surfaces the D15 toast literal verbatim', () => {
- expect(FILETREE_SRC).toContain(
- 't`File extensions are managed automatically - please rename without changing the extension`',
- );
- });
-
- test('the block branch reverts Pierre + clears pending + ends busy state, then returns', () => {
- const handlerStart = FILETREE_SRC.indexOf('async function handleTreeRename(');
- const handlerEnd = FILETREE_SRC.indexOf('\n }\n', handlerStart);
- const handlerBody = FILETREE_SRC.slice(handlerStart, handlerEnd);
- const blockIdx = handlerBody.indexOf("validation.kind === 'block'");
- expect(blockIdx).toBeGreaterThan(-1);
- const blockSlice = handlerBody.slice(blockIdx, blockIdx + 1200);
- expect(blockSlice).toContain('resetModelToDocuments()');
- expect(blockSlice).toContain('queueMicrotask(');
- expect(blockSlice).toContain('clearPendingCreate()');
- expect(blockSlice).toContain('setBusyPath(null)');
- expect(blockSlice).toMatch(/return\s*;/);
- expect(blockSlice.slice(0, blockSlice.indexOf('return'))).not.toMatch(
- /fetch\(\s*['"]\/api\/rename-path['"]/,
- );
- });
-
- test('the allow branch uses validation.destinationPath (NOT event.destinationPath)', () => {
- const handlerStart = FILETREE_SRC.indexOf('async function handleTreeRename(');
- const handlerEnd = FILETREE_SRC.indexOf('\n }\n', handlerStart);
- const handlerBody = FILETREE_SRC.slice(handlerStart, handlerEnd);
- expect(handlerBody).toMatch(
- /const\s+destinationTreePath\s*=\s*sourceIsAsset\s*\?\s*validation\.destinationPath\s*:\s*normalizeTreePathForKind\(\s*validation\.destinationPath,\s*event\.isFolder,?\s*\)/,
- );
- expect(handlerBody).not.toMatch(/normalizeTreePathForKind\(\s*event\.destinationPath,/);
- });
-
- test('payload.toPath still derives from the validated destinationTreePath', () => {
- const handlerStart = FILETREE_SRC.indexOf('async function handleTreeRename(');
- const handlerEnd = FILETREE_SRC.indexOf('\n }\n', handlerStart);
- const handlerBody = FILETREE_SRC.slice(handlerStart, handlerEnd);
- expect(handlerBody).toMatch(/toPath:\s*treeFilePathToDocName\(destinationTreePath\)/);
- });
-
- test('folder branch is unaffected by the validation gate (isFolder short-circuits to allow)', () => {
- const handlerStart = FILETREE_SRC.indexOf('async function handleTreeRename(');
- const handlerEnd = FILETREE_SRC.indexOf('\n }\n', handlerStart);
- const handlerBody = FILETREE_SRC.slice(handlerStart, handlerEnd);
- expect(handlerBody).toMatch(
- /validateAndCoerceRenameDestination\([^)]*event\.isFolder,\s*sourceIsAsset[^)]*\)/s,
- );
- });
-
- test('Pierre blur-without-onRename edge is preserved (no new onRename invocations added)', () => {
- expect(FILETREE_SRC).toContain('Pierre commits an unchanged inline rename on blur');
- });
-});
-
-describe('FileTree — Post-commit reconciliation error labeling', () => {
- test('applyRenamedDocuments is wrapped in its own try/catch (split from the fetch catch)', () => {
- const handlerStart = FILETREE_SRC.indexOf('async function handleTreeRename(');
- const handlerEnd = FILETREE_SRC.indexOf('\n }\n', handlerStart);
- const handlerBody = FILETREE_SRC.slice(handlerStart, handlerEnd);
- const applyIdx = handlerBody.indexOf('await applyRenamedDocuments(');
- expect(applyIdx).toBeGreaterThan(-1);
- const beforeApply = handlerBody.slice(0, applyIdx);
- const innerTryIdx = beforeApply.lastIndexOf('try {');
- expect(innerTryIdx).toBeGreaterThan(-1);
- const sliceFromTry = handlerBody.slice(innerTryIdx);
- expect(sliceFromTry).toMatch(/catch\s*\(\s*reconcileErr\s*\)/);
- });
-
- test('post-commit failure surfaces a distinct toast (NOT "Network error")', () => {
- expect(FILETREE_SRC).toContain(
- 't`Rename succeeded but the sidebar may be out of date — refresh to resync`',
- );
- });
-});
-
-describe('FileTree — handleDropComplete split try/catch (source-level)', () => {
- test('applyRenamedDocuments is wrapped in its own try/catch (split from the fetch catch)', () => {
- const handlerStart = FILETREE_SRC.indexOf('async function handleDropComplete(');
- expect(handlerStart).toBeGreaterThan(-1);
- const handlerEnd = FILETREE_SRC.indexOf('\n }\n', handlerStart);
- const handlerBody = FILETREE_SRC.slice(handlerStart, handlerEnd);
- const applyIdx = handlerBody.indexOf('await applyRenamedDocuments(');
- expect(applyIdx).toBeGreaterThan(-1);
- const beforeApply = handlerBody.slice(0, applyIdx);
- const innerTryIdx = beforeApply.lastIndexOf('try {');
- expect(innerTryIdx).toBeGreaterThan(-1);
- const sliceFromTry = handlerBody.slice(innerTryIdx);
- expect(sliceFromTry).toMatch(/catch\s*\(\s*reconcileErr\s*\)/);
- });
-
- test('post-move failure surfaces a distinct toast (NOT "Network error")', () => {
- expect(FILETREE_SRC).toContain(
- 't`Move succeeded but the sidebar may be out of date — refresh to resync`',
- );
- });
-});
diff --git a/packages/app/src/components/GraphPanel.fullscreen-safe-area.dom.test.tsx b/packages/app/src/components/GraphPanel.fullscreen-safe-area.dom.test.tsx
new file mode 100644
index 000000000..919847332
--- /dev/null
+++ b/packages/app/src/components/GraphPanel.fullscreen-safe-area.dom.test.tsx
@@ -0,0 +1,78 @@
+import { afterEach, describe, mock, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+mock.module('@lingui/core/macro', () => ({
+ t: renderLinguiTemplate,
+}));
+
+mock.module('@lingui/react/macro', () => ({
+ Plural: ({ one }: { one: string }) => <>{one}</>,
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+mock.module('next-themes', () => ({
+ useTheme: () => ({ resolvedTheme: 'light' }),
+}));
+
+mock.module('@/components/PageListContext', () => ({
+ usePageList: () => ({
+ assetPaths: new Set<string>(),
+ error: null,
+ folderPaths: new Set<string>(),
+ loading: false,
+ pages: new Set<string>(['docs/Active']),
+ pagesBySlug: new Map<string, string>(),
+ pageMeta: new Map(),
+ pageTitles: new Map([['docs/Active', 'Active']]),
+ refetch: () => {},
+ addPage: () => {},
+ }),
+}));
+
+mock.module('@/components/GraphView', () => ({
+ GraphView: ({ isExpanded }: { isExpanded: boolean }) => (
+ <div data-testid="graph-view" data-expanded={String(isExpanded)} />
+ ),
+}));
+
+describe('GraphPanel fullscreen safe-area behavior', () => {
+ afterEach(() => cleanup());
+
+ async function renderExpandedGraphPanel() {
+ const { GraphPanel } = await import('./GraphPanel');
+ render(
+ <TooltipProvider>
+ <GraphPanel activeDocName="docs/Active" />
+ </TooltipProvider>,
+ );
+
+ await userEvent.click(screen.getByRole('button', { name: 'Expand graph' }));
+ }
+
+ test('expanded overlay reserves the macOS traffic-light footprint at runtime', async () => {
+ await renderExpandedGraphPanel();
+
+ const graphView = screen.getByTestId('graph-view');
+ const panel = graphView.closest('[data-slot="panel"]');
+ expectVisualClassTokens(panel?.className, [
+ 'fixed',
+ 'inset-0',
+ 'z-50',
+ 'overflow-hidden',
+ 'bg-background',
+ ]);
+
+ const header = panel?.querySelector('[data-slot="panel-header"]');
+ expectVisualClassTokens(header?.className, ['pl-[var(--ok-titlebar-reserve-left,1rem)]']);
+ expectVisualClassTokensAbsent(header?.className, ['pl-[var(--ok-titlebar-reserve-left)]']);
+ });
+});
diff --git a/packages/app/src/components/GraphPanel.fullscreen-safe-area.test.ts b/packages/app/src/components/GraphPanel.fullscreen-safe-area.test.ts
deleted file mode 100644
index 1eb53c771..000000000
--- a/packages/app/src/components/GraphPanel.fullscreen-safe-area.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './GraphPanel?raw';
-
-const SAFE_AREA_AFFORDANCES: ReadonlyArray<{ marker: string; rationale: string }> = [
- { marker: 'pl-[78px]', rationale: 'inline literal mirroring EditorHeader.tsx:69' },
- {
- marker: 'pl-[var(--ok-titlebar-reserve-left,1rem)]',
- rationale: 'CSS-variable indirection with web-safe 1rem fallback',
- },
-];
-
-describe('GraphPanel — fullscreen-overlay safe-area contract', () => {
- test('expanded-state overlay reserves macOS traffic-light footprint', () => {
- const matchedMarkers = SAFE_AREA_AFFORDANCES.filter(({ marker }) => SRC.includes(marker));
- if (matchedMarkers.length === 0) {
- const lines = [
- 'GraphPanel.tsx does not adopt any known safe-area affordance for its',
- 'fullscreen-overlay state. The macOS traffic-light region (x=22..~100,',
- 'y=18..30) is currently overlapped by the PanelHeader content at',
- '(x≈16, y≈12) when `isExpanded === true`.',
- '',
- 'Expected one of:',
- ...SAFE_AREA_AFFORDANCES.map(({ marker, rationale }) => ` - "${marker}" (${rationale})`),
- '',
- 'If a genuinely new shape is required, extend `SAFE_AREA_AFFORDANCES`',
- 'above in the same commit that introduces it.',
- ];
- throw new Error(lines.join('\n'));
- }
- expect(matchedMarkers.length).toBeGreaterThan(0);
- });
-
- test('expanded-state className expression is NOT the bare bug-present literal', () => {
- expect(SRC).not.toContain("'fixed inset-0 z-50 bg-background overflow-hidden'");
- });
-
- test('safe-area CSS-variable reserve carries a web-safe var() fallback', () => {
- expect(SRC).not.toContain('pl-[var(--ok-titlebar-reserve-left)]');
- });
-});
diff --git a/packages/app/src/components/HelpPopover.dom.test.tsx b/packages/app/src/components/HelpPopover.dom.test.tsx
new file mode 100644
index 000000000..9880d2acd
--- /dev/null
+++ b/packages/app/src/components/HelpPopover.dom.test.tsx
@@ -0,0 +1,106 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+mock.module('@lingui/core/macro', () => ({
+ msg: renderLinguiTemplate,
+}));
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+mock.module('@/lib/external-link', () => ({
+ dispatchExternalLinkClick: () => {},
+}));
+
+async function renderOpenHelpPopover() {
+ const { HelpPopover } = await import('./HelpPopover');
+ render(
+ <TooltipProvider>
+ <HelpPopover />
+ </TooltipProvider>,
+ );
+ await userEvent.click(screen.getByRole('button', { name: 'Resources' }));
+}
+
+describe('HelpPopover runtime behavior', () => {
+ afterEach(() => cleanup());
+
+ test('exports the component', async () => {
+ const mod = await import('./HelpPopover');
+ expect(typeof mod.HelpPopover).toBe('function');
+ });
+
+ test('opens a resources-only nav whose accessible names match the visible heading', async () => {
+ await renderOpenHelpPopover();
+
+ expect(screen.getAllByText('Resources').length).toBeGreaterThanOrEqual(2);
+ const nav = screen.getByRole('navigation', { name: 'Resources' });
+ expect(nav).not.toBeNull();
+ expect(screen.queryByText(/Help\s*&\s*Resources/i)).toBeNull();
+ expect(screen.queryByText('Setup')).toBeNull();
+ expect(screen.queryByText('Settings')).toBeNull();
+ expect(screen.queryByText('Install for Claude Chat')).toBeNull();
+ });
+
+ test('renders the external resource links in the required order', async () => {
+ await renderOpenHelpPopover();
+
+ const nav = screen.getByRole('navigation', { name: 'Resources' });
+ const links = within(nav).getAllByRole('link');
+ expect(
+ links.map((link) => ({
+ label: Array.from(link.childNodes)
+ .filter((node) => node.nodeType === Node.TEXT_NODE)
+ .map((node) => node.textContent)
+ .join('')
+ .trim(),
+ href: link.getAttribute('href'),
+ target: link.getAttribute('target'),
+ rel: link.getAttribute('rel'),
+ hasIcon: link.querySelector('svg') !== null,
+ })),
+ ).toEqual([
+ {
+ label: 'Documentation',
+ href: 'https://openknowledge.ai/docs',
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ hasIcon: true,
+ },
+ {
+ label: 'GitHub',
+ href: 'https://github.com/inkeep/open-knowledge',
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ hasIcon: true,
+ },
+ {
+ label: 'Website',
+ href: 'https://openknowledge.ai/',
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ hasIcon: true,
+ },
+ {
+ label: 'Discord',
+ href: 'https://go.inkeep.com/ok-discord',
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ hasIcon: true,
+ },
+ {
+ label: 'Twitter',
+ href: 'https://x.com/inkeep',
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ hasIcon: true,
+ },
+ ]);
+ });
+});
diff --git a/packages/app/src/components/HelpPopover.test.ts b/packages/app/src/components/HelpPopover.test.ts
deleted file mode 100644
index 1374cfdd1..000000000
--- a/packages/app/src/components/HelpPopover.test.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './HelpPopover?raw';
-
-describe('HelpPopover module', () => {
- test('Component module imports cleanly', async () => {
- const mod = await import('./HelpPopover');
- expect(typeof mod.HelpPopover).toBe('function');
- });
-});
-
-describe('HelpPopover Resources section', () => {
- test('section header reads "Resources"', () => {
- expect(SRC).toMatch(/>\s*Resources\s*</);
- expect(SRC).not.toMatch(/Help\s*&(amp;)?\s*Resources/);
- });
-
- test('accessible names match the visible heading (WCAG 2.5.3 Label in Name)', () => {
- expect(SRC).toMatch(/<span className="sr-only">\s*<Trans>Resources<\/Trans>\s*<\/span>/);
- expect(SRC).toContain('<nav aria-label={t`Resources`}>');
- expect(SRC).not.toMatch(/Help\s+(and|&(amp;)?)\s+resources/i);
- });
-
- test('does NOT render a Setup section header', () => {
- expect(SRC).not.toMatch(/>\s*Setup\s*</);
- });
-
- test('does NOT render the install entry (moved to in-context Open in… menus)', () => {
- expect(SRC).not.toContain('Install for Claude Chat');
- expect(SRC).not.toContain('InstallInClaudeDesktopDialog');
- });
-
- test('does NOT render a Settings entry (moved to <SettingsButton />)', () => {
- expect(SRC).not.toContain('<span>Settings</span>');
- expect(SRC).not.toContain('SETTINGS_OPEN_HASH');
- expect(SRC).not.toContain('help-popover-settings');
- });
-});
-
-describe('HelpPopover links — order, labels, hrefs', () => {
- function extractLinkOrder(): Array<{ label: string; href: string }> {
- const items = SRC.match(/\{\s*label:\s*(?:msg`[^`]+`|'[^']+'),\s*href:\s*'([^']+)'/g) ?? [];
- return items.map((entry) => {
- const match = entry.match(/label:\s*(?:msg`([^`]+)`|'([^']+)'),\s*href:\s*'([^']+)'/);
- if (!match) throw new Error(`bad parse: ${entry}`);
- return { label: match[1] ?? match[2] ?? '', href: match[3] ?? '' };
- });
- }
-
- test('renders exactly five external links in the required order', () => {
- const order = extractLinkOrder();
- expect(order).toEqual([
- { label: 'Documentation', href: 'https://openknowledge.ai/docs' },
- { label: 'GitHub', href: 'https://github.com/inkeep/open-knowledge' },
- { label: 'Website', href: 'https://openknowledge.ai/' },
- { label: 'Discord', href: 'https://go.inkeep.com/ok-discord' },
- { label: 'Twitter', href: 'https://x.com/inkeep' },
- ]);
- });
-
- test('uses single-noun labels (no "Twitter / X", no "Homepage")', () => {
- expect(SRC).not.toMatch(/'Twitter \/ X'/);
- expect(SRC).not.toMatch(/'Homepage'/);
- });
-
- test('imports GithubIcon and DiscordIcon', () => {
- expect(SRC).toContain("from './icons/github'");
- expect(SRC).toContain("from './icons/discord'");
- });
-
- test('does NOT import LinkedinIcon (LinkedIn link was removed)', () => {
- expect(SRC).not.toContain('LinkedinIcon');
- expect(SRC).not.toContain('./icons/linkedin');
- });
-
- test('does NOT import the Download icon (Setup section deleted)', () => {
- expect(SRC).not.toMatch(/\bDownload\b\s*[,}]/);
- });
-});
diff --git a/packages/app/src/components/McpConsentDialog.dom.test.tsx b/packages/app/src/components/McpConsentDialog.dom.test.tsx
new file mode 100644
index 000000000..c7936d38c
--- /dev/null
+++ b/packages/app/src/components/McpConsentDialog.dom.test.tsx
@@ -0,0 +1,162 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import type { OkMcpWiringResult, OkMcpWiringShowPayload } from '@/lib/desktop-bridge-types';
+import type { McpConsentStore } from '@/lib/mcp-consent-store';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+import type { ToastImpl } from './McpConsentDialogBody';
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+const payload: OkMcpWiringShowPayload = {
+ detectedEditors: [
+ { id: 'claude', label: 'Claude', detected: true, willReplace: true },
+ { id: 'cursor', label: 'Cursor', detected: true, willReplace: false },
+ { id: 'codex', label: 'Codex', detected: false, willReplace: false },
+ ],
+};
+
+function deferredResult() {
+ let resolve!: (result: OkMcpWiringResult) => void;
+ const promise = new Promise<OkMcpWiringResult>((nextResolve) => {
+ resolve = nextResolve;
+ });
+ return { promise, resolve };
+}
+
+function makeHarness({
+ confirmResult = async () => ({ ok: true as const }),
+ skipResult = async () => ({ ok: true as const }),
+}: {
+ confirmResult?: (editorIds: readonly string[]) => Promise<OkMcpWiringResult>;
+ skipResult?: () => Promise<OkMcpWiringResult>;
+} = {}) {
+ const confirmCalls: readonly string[][] = [];
+ const skipCalls: string[] = [];
+ const toastErrors: string[] = [];
+ const store: McpConsentStore = {
+ confirm: async (editorIds) => {
+ (confirmCalls as string[][]).push([...editorIds]);
+ return confirmResult(editorIds);
+ },
+ dismiss: () => {},
+ getSnapshot: () => payload,
+ install: () => undefined,
+ skip: async () => {
+ skipCalls.push('skip');
+ return skipResult();
+ },
+ subscribe: () => () => {},
+ };
+ const toast: ToastImpl = {
+ error: (message) => toastErrors.push(message),
+ };
+ return { confirmCalls, skipCalls, store, toast, toastErrors };
+}
+
+async function renderDialog(harness = makeHarness()) {
+ const { McpConsentDialogBody } = await import('./McpConsentDialogBody');
+ render(<McpConsentDialogBody payload={payload} store={harness.store} toast={harness.toast} />);
+ return harness;
+}
+
+describe('McpConsentDialog runtime behavior', () => {
+ afterEach(() => cleanup());
+
+ test('renders willReplace disclosure and preselects detected editors only', async () => {
+ await renderDialog();
+
+ expect(
+ screen.getByRole('dialog', { name: 'Add Open Knowledge to your AI tools' }),
+ ).toBeTruthy();
+ expect(screen.getByTestId('mcp-consent-status-claude').textContent).toBe(
+ 'Will replace existing Open Knowledge entry',
+ );
+ expect(screen.getByTestId('mcp-consent-status-cursor').textContent).toBe(
+ 'Detected on this machine',
+ );
+ expect(screen.getByTestId('mcp-consent-status-codex').textContent).toBe('Not detected');
+ expect(screen.getByTestId('mcp-consent-checkbox-claude').getAttribute('aria-checked')).toBe(
+ 'true',
+ );
+ expect(screen.getByTestId('mcp-consent-checkbox-cursor').getAttribute('aria-checked')).toBe(
+ 'true',
+ );
+ expect(screen.getByTestId('mcp-consent-checkbox-codex').getAttribute('aria-checked')).toBe(
+ 'false',
+ );
+ });
+
+ test('failed Add resets busy state, reports the error, and allows retry', async () => {
+ const first = deferredResult();
+ const second = deferredResult();
+ const outcomes = [first, second];
+ const harness = makeHarness({
+ confirmResult: async () => outcomes.shift()?.promise ?? { ok: true },
+ });
+ await renderDialog(harness);
+
+ const add = screen.getByTestId('mcp-consent-add') as HTMLButtonElement;
+ const skip = screen.getByTestId('mcp-consent-skip') as HTMLButtonElement;
+
+ await userEvent.click(add);
+ expect(add.disabled).toBe(true);
+ expect(skip.disabled).toBe(true);
+ expect(add.textContent).toBe('Working');
+
+ first.resolve({ ok: false, error: 'Could not write Claude config' });
+ await waitFor(() => {
+ expect(add.disabled).toBe(false);
+ });
+
+ expect(skip.disabled).toBe(false);
+ expect(add.textContent).toBe('Add');
+ expect(harness.confirmCalls).toEqual([['claude', 'cursor']]);
+ expect(harness.toastErrors).toEqual(['Could not write Claude config']);
+
+ await userEvent.click(add);
+ second.resolve({ ok: false, error: 'Still unwritable' });
+ await waitFor(() => {
+ expect(harness.confirmCalls).toEqual([
+ ['claude', 'cursor'],
+ ['claude', 'cursor'],
+ ]);
+ });
+ });
+
+ test('failed Skip resets busy state, reports the error, and allows retry', async () => {
+ const first = deferredResult();
+ const second = deferredResult();
+ const outcomes = [first, second];
+ const harness = makeHarness({
+ skipResult: async () => outcomes.shift()?.promise ?? { ok: true },
+ });
+ await renderDialog(harness);
+
+ const add = screen.getByTestId('mcp-consent-add') as HTMLButtonElement;
+ const skip = screen.getByTestId('mcp-consent-skip') as HTMLButtonElement;
+
+ await userEvent.click(skip);
+ expect(add.disabled).toBe(true);
+ expect(skip.disabled).toBe(true);
+
+ first.resolve({ ok: false, error: 'Could not write marker' });
+ await waitFor(() => {
+ expect(skip.disabled).toBe(false);
+ });
+
+ expect(add.disabled).toBe(false);
+ expect(harness.skipCalls).toEqual(['skip']);
+ expect(harness.toastErrors).toEqual(['Could not write marker']);
+
+ await userEvent.click(skip);
+ second.resolve({ ok: false, error: 'Still cannot write marker' });
+ await waitFor(() => {
+ expect(harness.skipCalls).toEqual(['skip', 'skip']);
+ });
+ });
+});
diff --git a/packages/app/src/components/McpConsentDialog.test.ts b/packages/app/src/components/McpConsentDialog.test.ts
index 8d4a090df..28a7d6b90 100644
--- a/packages/app/src/components/McpConsentDialog.test.ts
+++ b/packages/app/src/components/McpConsentDialog.test.ts
@@ -129,26 +129,4 @@ describe('McpConsentDialog module shape', () => {
expect(spy.mock.calls.length).toBe(1);
expect(spy.mock.calls[0]).toEqual(['hello']);
});
-
- test('Pass 1 Major #8: dialog renders "Will replace existing" label for willReplace=true rows', () => {
- const { readFileSync } = require('node:fs') as typeof import('node:fs');
- const { join } = require('node:path') as typeof import('node:path');
- const source = readFileSync(join(import.meta.dir, 'McpConsentDialogBody.tsx'), 'utf8');
- expect(source).toContain('Will replace existing Open Knowledge entry');
- expect(source).toContain('editor.willReplace');
- });
-
- test('Pass 1 Major #1: onAdd / onSkip must reset `busy` on !result.ok so retry is possible', () => {
- const { readFileSync } = require('node:fs') as typeof import('node:fs');
- const { join } = require('node:path') as typeof import('node:path');
- const source = readFileSync(join(import.meta.dir, 'McpConsentDialogBody.tsx'), 'utf8');
- const onAddBlock = source.match(/async function onAdd\(\)\s*\{[\s\S]*?\n\s\s\}/);
- const onSkipBlock = source.match(/async function onSkip\(\)\s*\{[\s\S]*?\n\s\s\}/);
- expect(onAddBlock).not.toBeNull();
- expect(onSkipBlock).not.toBeNull();
- expect(onAddBlock?.[0]).toContain('if (!result.ok)');
- expect(onAddBlock?.[0]).toContain('setBusy(false)');
- expect(onSkipBlock?.[0]).toContain('if (!result.ok)');
- expect(onSkipBlock?.[0]).toContain('setBusy(false)');
- });
});
diff --git a/packages/app/src/components/NavigatorApp.dom.test.tsx b/packages/app/src/components/NavigatorApp.dom.test.tsx
new file mode 100644
index 000000000..b7aa2d240
--- /dev/null
+++ b/packages/app/src/components/NavigatorApp.dom.test.tsx
@@ -0,0 +1,203 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { expectVisualClassTokens } from '@/test-utils/visual-contract';
+import { NavigatorApp } from './NavigatorApp';
+
+let themeBridgeCalls: Array<[unknown, string]> = [];
+let createDialogProps: Array<{ open: boolean; bridge: unknown }> = [];
+let cloneDialogProps: Array<{
+ open: boolean;
+ onCloneComplete: (payload: { dir: string }) => void;
+}> = [];
+
+mock.module('next-themes', () => ({
+ useTheme: () => ({ theme: undefined }),
+}));
+
+mock.module('@/hooks/use-theme-bridge', () => ({
+ useThemeBridge: (bridge: unknown, theme: string) => {
+ themeBridgeCalls.push([bridge, theme]);
+ },
+}));
+
+mock.module('./BetaBadge', () => ({
+ BetaBadge: () => <span data-testid="beta-badge">Beta</span>,
+}));
+
+mock.module('./ui/button', () => ({
+ Button: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <button type="button" {...props}>
+ {children}
+ </button>
+ ),
+}));
+
+mock.module('./ui/badge', () => ({
+ Badge: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <span {...props}>{children}</span>
+ ),
+}));
+
+mock.module('./CreateProjectDialog', () => ({
+ CreateProjectDialog: (props: { open: boolean; bridge: unknown }) => {
+ createDialogProps.push(props);
+ return <div data-testid="create-project-dialog" data-open={String(props.open)} />;
+ },
+}));
+
+mock.module('./CloneDialog', () => ({
+ CloneDialog: (props: { open: boolean; onCloneComplete: (payload: { dir: string }) => void }) => {
+ cloneDialogProps.push(props);
+ return <div data-testid="clone-dialog" data-open={String(props.open)} />;
+ },
+}));
+
+mock.module('./AuthModal', () => ({
+ AuthModal: () => null,
+}));
+
+mock.module('./ConsentDialog', () => ({
+ ConsentDialog: () => null,
+}));
+
+mock.module('./McpConsentDialog', () => ({
+ McpConsentDialog: () => null,
+}));
+
+mock.module('./ShareReceiveDialog', () => ({
+ ShareReceiveDialog: () => null,
+}));
+
+mock.module('@/lib/share/clone-controller', () => ({
+ createCloneController: () => ({}),
+}));
+
+mock.module('@/lib/transports/auth-query-transport', () => ({
+ ipcAuthQueryTransport: () => ({}),
+}));
+
+mock.module('@/lib/transports/auth-transport', () => ({
+ ipcAuthTransport: () => ({}),
+}));
+
+mock.module('@/lib/transports/clone-transport', () => ({
+ ipcCloneTransport: () => ({}),
+}));
+
+function createBridge() {
+ return {
+ appVersion: '0.4.0-beta.1',
+ onMenuAction: mock(() => () => {}),
+ config: {
+ collabUrl: '',
+ apiOrigin: '',
+ projectPath: '',
+ projectName: 'Project Navigator',
+ mode: 'navigator',
+ },
+ project: {
+ listRecent: mock(() =>
+ Promise.resolve([{ path: '/projects/recent', name: 'Recent Project' }]),
+ ),
+ removeRecent: mock(() => Promise.resolve()),
+ getSessionState: mock(() => Promise.resolve({})),
+ setSessionState: mock(() => Promise.resolve()),
+ open: mock(() => Promise.resolve()),
+ createNew: mock(() => Promise.resolve()),
+ recordCreateNewBannerShown: mock(() => Promise.resolve()),
+ close: mock(() => Promise.resolve()),
+ },
+ dialog: {
+ openFolder: mock(() => Promise.resolve('/picked/folder')),
+ },
+ };
+}
+
+async function renderNavigator(bridge: ReturnType<typeof createBridge>) {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: bridge,
+ });
+ render(<NavigatorApp bridge={bridge as never} />);
+ await waitFor(() => expect(bridge.project.listRecent).toHaveBeenCalledTimes(1));
+}
+
+describe('NavigatorApp launcher runtime behavior', () => {
+ beforeEach(() => {
+ cleanup();
+ Reflect.deleteProperty(window, 'okDesktop');
+ themeBridgeCalls = [];
+ createDialogProps = [];
+ cloneDialogProps = [];
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('renders the launcher chrome, beta badge, drag strip, and theme bridge fallback', async () => {
+ const bridge = createBridge();
+ await renderNavigator(bridge);
+
+ expect(screen.getByRole('heading', { name: 'Open Knowledge' })).not.toBeNull();
+ expect(screen.getByTestId('beta-badge').textContent).toBe('Beta');
+ expect(document.body.textContent).not.toContain('Stable');
+
+ expect(themeBridgeCalls.at(-1)).toEqual([bridge, 'system']);
+
+ const chromeRow = screen.getByTestId('nav-chrome-row');
+ expect(chromeRow.getAttribute('data-electron-drag')).toBe('');
+ expectVisualClassTokens(chromeRow.className, ['inset-x-0', 'h-9']);
+ expect(screen.getByTestId('nav-open').getAttribute('data-electron-no-drag')).toBeNull();
+ expect(screen.getByTestId('nav-create-new').getAttribute('data-electron-no-drag')).toBeNull();
+ await screen.findByTestId('nav-recent-list');
+ expect(document.querySelector('[data-electron-no-drag]')).toBeNull();
+ });
+
+ test('routes open, recent, create, and clone-complete actions through the expected entry points', async () => {
+ const bridge = createBridge();
+ await renderNavigator(bridge);
+
+ fireEvent.click(screen.getByTestId('nav-open'));
+ await waitFor(() => {
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/picked/folder',
+ target: 'new-window',
+ entryPoint: 'pick-existing',
+ });
+ });
+
+ fireEvent.click(await screen.findByText('Recent Project'));
+ await waitFor(() => {
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/projects/recent',
+ target: 'new-window',
+ entryPoint: 'recents',
+ });
+ });
+
+ fireEvent.click(screen.getByTestId('nav-create-new'));
+ await waitFor(() => {
+ expect(screen.getByTestId('create-project-dialog').getAttribute('data-open')).toBe('true');
+ });
+ expect(createDialogProps.at(-1)?.bridge).toBe(bridge);
+
+ fireEvent.click(screen.getByTestId('nav-clone'));
+ await waitFor(() => {
+ expect(screen.getByTestId('clone-dialog').getAttribute('data-open')).toBe('true');
+ });
+
+ act(() => {
+ cloneDialogProps.at(-1)?.onCloneComplete({ dir: '/cloned/project' });
+ });
+
+ await waitFor(() => {
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/cloned/project',
+ target: 'new-window',
+ entryPoint: 'pick-existing',
+ });
+ });
+ });
+});
diff --git a/packages/app/src/components/NavigatorApp.test.ts b/packages/app/src/components/NavigatorApp.test.ts
index 917301be3..4da7fa4df 100644
--- a/packages/app/src/components/NavigatorApp.test.ts
+++ b/packages/app/src/components/NavigatorApp.test.ts
@@ -1,6 +1,4 @@
import { describe, expect, mock, test } from 'bun:test';
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
interface MockBridge {
config: {
@@ -221,13 +219,12 @@ describe('NavigatorApp error-state helpers', () => {
test('runWithErrorStatePure surfaces rejections via setError with Error.message', async () => {
const { runWithErrorStatePure } = await import('./NavigatorApp');
const setErrorCalls: Array<string | null> = [];
- const setError = (msg: string | null) => {
- setErrorCalls.push(msg);
- };
await runWithErrorStatePure(
() => Promise.reject(new Error('boot failed')),
'Failed to open project.',
- setError,
+ (msg) => {
+ setErrorCalls.push(msg);
+ },
);
expect(setErrorCalls).toEqual([null, 'boot failed']);
});
@@ -235,13 +232,12 @@ describe('NavigatorApp error-state helpers', () => {
test('runWithErrorStatePure falls back when rejection has no usable message', async () => {
const { runWithErrorStatePure } = await import('./NavigatorApp');
const setErrorCalls: Array<string | null> = [];
- const setError = (msg: string | null) => {
- setErrorCalls.push(msg);
- };
await runWithErrorStatePure(
() => Promise.reject('network dropped'),
'Failed to open project.',
- setError,
+ (msg) => {
+ setErrorCalls.push(msg);
+ },
);
expect(setErrorCalls).toEqual([null, 'Failed to open project.']);
});
@@ -258,116 +254,3 @@ describe('NavigatorApp error-state helpers', () => {
expect(afterAwait).toBe(true);
});
});
-
-const NAVIGATOR_SRC = readFileSync(join(__dirname, 'NavigatorApp.tsx'), 'utf8');
-
-describe('NavigatorApp launcher-header channel surface', () => {
- test('imports BetaBadge from the sibling component (cross-window subscription centralized via the hook)', () => {
- expect(NAVIGATOR_SRC).toMatch(/from\s+['"]\.\/BetaBadge['"]/);
- expect(NAVIGATOR_SRC).toMatch(/<BetaBadge\b/);
- });
-
- test('Channel badge is gone: no useUpdateChannel hook + no Beta/Stable string literal in the header', () => {
- expect(NAVIGATOR_SRC).not.toMatch(
- /channel\s*===\s*['"]beta['"]\s*\?\s*['"]Beta['"]\s*:\s*['"]Stable['"]/,
- );
- expect(NAVIGATOR_SRC).not.toMatch(/useUpdateChannel/);
- });
-
- test('BetaBadge sits in the title row (chrome-level signal, not About-row info)', () => {
- const titleMatch = NAVIGATOR_SRC.match(/<h1[^>]*>Open Knowledge<\/h1>\s*<BetaBadge/);
- expect(titleMatch).not.toBeNull();
- });
-});
-
-describe('NavigatorApp — Electron theme bridge wiring', () => {
- test('imports useTheme from next-themes for the user-intent value', () => {
- expect(NAVIGATOR_SRC).toMatch(
- /import\s*\{[^}]*\buseTheme\b[^}]*\}\s*from\s*['"]next-themes['"]/,
- );
- expect(NAVIGATOR_SRC).toMatch(/useTheme\(\)/);
- });
-
- test('delegates the theme bridge wiring to the shared useThemeBridge hook', () => {
- expect(NAVIGATOR_SRC).toMatch(
- /import\s*\{\s*useThemeBridge\s*\}\s*from\s*['"]@\/hooks\/use-theme-bridge['"]/,
- );
- expect(NAVIGATOR_SRC).toMatch(/useThemeBridge\(\s*bridge\s*,\s*themeValue/);
- });
-
- test('falls back to "system" for symmetry with ConfigProvider', () => {
- expect(NAVIGATOR_SRC).toMatch(/themeValue\s*\?\?\s*['"]system['"]/);
- });
-});
-
-describe('NavigatorApp launcher window drag region', () => {
- test('detects Electron host via the canonical window.okDesktop != null idiom', () => {
- expect(NAVIGATOR_SRC).toMatch(
- /typeof\s+window\s*!==\s*['"]undefined['"]\s*&&\s*window\.okDesktop\s*!=\s*null/,
- );
- expect(NAVIGATOR_SRC).toContain('const isElectronHost');
- });
-
- test('chrome row spans full window width and is draggable in Electron mode', () => {
- expect(NAVIGATOR_SRC).toMatch(
- /data-testid=['"]nav-chrome-row['"][\s\S]*?isElectronHost\s*\?\s*['"]\[-webkit-app-region:drag\]['"]|isElectronHost\s*\?\s*['"]\[-webkit-app-region:drag\]['"][\s\S]*?data-testid=['"]nav-chrome-row['"]/,
- );
- });
-
- test('chrome row carries data-electron-drag so the globals.css `:has()` rule can target it', () => {
- expect(NAVIGATOR_SRC).toMatch(
- /data-electron-drag=\{\s*isElectronHost\s*\?\s*['"]['"]\s*:\s*undefined\s*\}/,
- );
- });
-
- test('header element itself does NOT carry drag (chrome row owns it)', () => {
- expect(NAVIGATOR_SRC).not.toMatch(
- /<header\b[^>]*\[-webkit-app-region:drag\]|<header\b[\s\S]{0,200}?isElectronHost\s*\?\s*['"]\[-webkit-app-region:drag\]/,
- );
- });
-
- test('outer container is NOT draggable (drag is scoped to the chrome row)', () => {
- expect(NAVIGATOR_SRC).not.toMatch(
- /h-screen\s+w-screen[^"`']*\[-webkit-app-region:drag\]|className=\{`flex h-screen[\s\S]*?\[-webkit-app-region:drag\]/,
- );
- });
-
- test('NavigatorCard does NOT carry a no-drag opt-out (no drag ancestor)', () => {
- const cardFnMatch = NAVIGATOR_SRC.match(/function\s+NavigatorCard\b[\s\S]*?^}/m);
- expect(cardFnMatch).not.toBeNull();
- expect(cardFnMatch?.[0] ?? '').not.toMatch(/\[-webkit-app-region:no-drag\]/);
- });
-
- test('RecentRow does NOT carry a no-drag opt-out (no drag ancestor)', () => {
- const rowFnMatch = NAVIGATOR_SRC.match(/function\s+RecentRow\b[\s\S]*?^}/m);
- expect(rowFnMatch).not.toBeNull();
- expect(rowFnMatch?.[0] ?? '').not.toMatch(/\[-webkit-app-region:no-drag\]/);
- });
-});
-
-describe('NavigatorApp entry-point propagation', () => {
- test('Open folder on disk → openProject(..., "pick-existing")', () => {
- expect(NAVIGATOR_SRC).toMatch(/onOpenFolder\s*=[\s\S]*?openProject\([^)]*,\s*'pick-existing'/);
- });
-
- test('Create new project card opens CreateProjectDialog (no direct openProject dispatch)', () => {
- expect(NAVIGATOR_SRC).toMatch(/const\s+onCreate\s*=\s*\(\)\s*=>\s*setCreateDialogOpen\(true\)/);
- expect(NAVIGATOR_SRC).toMatch(/<CreateProjectDialog\b[\s\S]*?bridge=\{bridge\}/);
- expect(NAVIGATOR_SRC).toMatch(
- /data-testid=['"]nav-create-new['"]|dataTestId=['"]nav-create-new['"]/,
- );
- });
-
- test('Open Recent row → openProject(..., "recents")', () => {
- expect(NAVIGATOR_SRC).toMatch(/onOpenRecent\s*=[\s\S]*?openProject\([^)]*,\s*'recents'/);
- });
-
- test('Clone-complete → openProject(..., "pick-existing")', () => {
- expect(NAVIGATOR_SRC).toMatch(/onCloneComplete[\s\S]*?openProject\([^)]*,\s*'pick-existing'/);
- });
-
- test('local openProject helper threads an EntryPoint argument into bridge.project.open', () => {
- expect(NAVIGATOR_SRC).toMatch(/entryPoint:\s*OkProjectEntryPoint/);
- expect(NAVIGATOR_SRC).toMatch(/bridge\.project\.open\(\{[^}]*entryPoint(\s*,|\s*\})/);
- });
-});
diff --git a/packages/app/src/components/PackCardGrid.dom.test.tsx b/packages/app/src/components/PackCardGrid.dom.test.tsx
new file mode 100644
index 000000000..c307eca5f
--- /dev/null
+++ b/packages/app/src/components/PackCardGrid.dom.test.tsx
@@ -0,0 +1,140 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ComponentProps, ReactNode } from 'react';
+import type { OkPackId, OkSeedListPacksResult, OkSeedPackInfo } from '@/lib/desktop-bridge-types';
+
+let listPacksImpl: () => Promise<OkSeedListPacksResult> = async () => ({
+ ok: true,
+ packs: [],
+});
+const listPacksCalls: string[] = [];
+
+mock.module('@lingui/core/macro', () => ({
+ plural: (count: number, forms: { one: string; other: string }) =>
+ (count === 1 ? forms.one : forms.other).replace('#', String(count)),
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((out, part, index) => `${out}${part}${values[index] ?? ''}`, ''),
+}));
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((out, part, index) => `${out}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+mock.module('@/lib/seed-client', () => ({
+ seedClient: () => ({
+ listPacks: () => {
+ listPacksCalls.push('listPacks');
+ return listPacksImpl();
+ },
+ }),
+}));
+
+const packIds: OkPackId[] = [
+ 'knowledge-base',
+ 'software-lifecycle',
+ 'plain-notes',
+ 'worldbuilding',
+ 'writing-pipeline',
+ 'gbrain',
+];
+
+function makePack(id: OkPackId, index: number): OkSeedPackInfo {
+ return {
+ id,
+ name: `Pack ${index + 1}`,
+ description: `Starter pack ${index + 1}`,
+ folders: [{ path: `folder-${index + 1}`, summary: 'Folder' }],
+ entryCounts: { files: index, folders: index + 1 },
+ };
+}
+
+const allPacks = packIds.map(makePack);
+
+async function renderPackCardGrid(
+ props: Partial<ComponentProps<typeof import('./PackCardGrid')['PackCardGrid']>> = {},
+) {
+ const { PackCardGrid } = await import('./PackCardGrid');
+ const selected: OkPackId[] = [];
+ render(<PackCardGrid onPackSelect={(packId) => selected.push(packId)} {...props} />);
+ return { selected };
+}
+
+describe('PackCardGrid runtime behavior', () => {
+ afterEach(() => {
+ cleanup();
+ listPacksCalls.length = 0;
+ listPacksImpl = async () => ({ ok: true, packs: [] });
+ });
+
+ test('exports the component', async () => {
+ const mod = await import('./PackCardGrid');
+ expect(typeof mod.PackCardGrid).toBe('function');
+ });
+
+ test('renders caller-provided packs as keyboard-accessible cards and skips internal fetch', async () => {
+ const { selected } = await renderPackCardGrid({ packs: allPacks });
+
+ const buttons = screen.getAllByRole('button');
+ expect(buttons).toHaveLength(allPacks.length);
+ expect(listPacksCalls).toEqual([]);
+ for (const [index, button] of buttons.entries()) {
+ expect(button.textContent).toContain(allPacks[index].name);
+ expect(button.textContent).toContain(allPacks[index].description);
+ expect(button.querySelector('svg')).not.toBeNull();
+ }
+
+ await userEvent.click(buttons[0]);
+ expect(selected).toEqual(['knowledge-base']);
+ });
+
+ test('renders the loading skeleton when caller-owned packs are still null', async () => {
+ await renderPackCardGrid({ packs: null });
+
+ const status = screen.getByRole('status');
+ expect(status.getAttribute('aria-busy')).toBe('true');
+ expect(status.getAttribute('aria-label')).toBe('Loading starter packs');
+ expect(status.querySelectorAll('[class*="animate-pulse"]').length).toBeGreaterThanOrEqual(6);
+ expect(listPacksCalls).toEqual([]);
+ });
+
+ test('renders an empty state for an empty pack list', async () => {
+ await renderPackCardGrid({ packs: [] });
+
+ expect(screen.getByRole('status').textContent).toContain('No starter packs available.');
+ });
+
+ test('self-fetches packs when caller omits the packs prop', async () => {
+ listPacksImpl = async () => ({ ok: true, packs: [allPacks[0]] });
+
+ await act(async () => {
+ await renderPackCardGrid();
+ await Promise.resolve();
+ });
+
+ await waitFor(() => {
+ expect(screen.getByRole('button').textContent).toContain('Pack 1');
+ });
+ expect(listPacksCalls).toEqual(['listPacks']);
+ });
+
+ test('surfaces self-fetch failures as an alert', async () => {
+ listPacksImpl = async () => ({
+ ok: false,
+ error: { kind: 'internal', message: 'registry unavailable' },
+ });
+
+ await act(async () => {
+ await renderPackCardGrid();
+ await Promise.resolve();
+ });
+
+ await waitFor(() => {
+ expect(screen.getByRole('alert').textContent).toContain('registry unavailable');
+ });
+ });
+});
diff --git a/packages/app/src/components/PackCardGrid.test.ts b/packages/app/src/components/PackCardGrid.test.ts
index dceae0aaf..92cbc5d89 100644
--- a/packages/app/src/components/PackCardGrid.test.ts
+++ b/packages/app/src/components/PackCardGrid.test.ts
@@ -1,55 +1,5 @@
import { describe, expect, test } from 'bun:test';
import { formatEntryCounts } from './PackCardGrid';
-import SRC from './PackCardGrid?raw';
-
-describe('PackCardGrid module', () => {
- test('exports PackCardGrid component', async () => {
- const mod = await import('./PackCardGrid');
- expect(typeof mod.PackCardGrid).toBe('function');
- });
-});
-
-describe('PackCardGrid source-level guards', () => {
- test('routes pack listing through the shared seedClient transport', () => {
- expect(SRC).toContain("from '@/lib/seed-client'");
- expect(SRC).toContain('seedClient().listPacks()');
- });
-
- test('hardcodes a lucide icon for every registered PackId', () => {
- for (const id of [
- "'knowledge-base'",
- "'software-lifecycle'",
- "'plain-notes'",
- 'worldbuilding',
- "'writing-pipeline'",
- "'entity-vault'",
- ]) {
- expect(SRC).toContain(id);
- }
- });
-
- test('renders each card as a button for keyboard a11y', () => {
- expect(SRC).toContain('<button');
- expect(SRC).toContain('type="button"');
- });
-
- test('exposes a loading skeleton instead of nothing while packs are unknown', () => {
- expect(SRC).toContain('PackCardSkeleton');
- expect(SRC).toContain('aria-busy="true"');
- });
-
- test('surfaces fetch failures with role="alert"', () => {
- expect(SRC).toContain('role="alert"');
- });
-
- test('renders an empty-state instead of a blank gap when packs[] is []', () => {
- expect(SRC).toContain('No starter packs available.');
- });
-
- test('skips its internal fetch when the caller supplies packs', () => {
- expect(SRC).toContain('externalPacks === undefined');
- });
-});
describe('formatEntryCounts() — card subtitle formatting', () => {
test('renders "N files · N folders" for mixed packs', () => {
diff --git a/packages/app/src/components/PageListContext.loading-stability.dom.test.tsx b/packages/app/src/components/PageListContext.loading-stability.dom.test.tsx
index eaa2fbb48..8859abbbe 100644
--- a/packages/app/src/components/PageListContext.loading-stability.dom.test.tsx
+++ b/packages/app/src/components/PageListContext.loading-stability.dom.test.tsx
@@ -1,14 +1,64 @@
import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
-import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+interface PageListCachePayload {
+ pages: Set<string>;
+ folderPaths: Set<string>;
+ pagesBySlug: ReadonlyMap<string, string>;
+ pagesByBasename: ReadonlyMap<string, string>;
+ assetPaths: Set<string>;
+ pageIcons: ReadonlyMap<string, string>;
+}
+
+const setPageListCacheMock = mock((_payload: PageListCachePayload) => {});
mock.module('@/lib/documents-events', () => ({
subscribeToDocumentsChanged: () => () => {},
}));
+mock.module('@/editor/page-list-cache', () => ({
+ buildPageIconsIndex: (pageMeta: ReadonlyMap<string, { icon?: string }>) => {
+ const icons = new Map<string, string>();
+ for (const [docName, meta] of pageMeta) {
+ if (meta.icon) icons.set(docName, meta.icon);
+ }
+ return icons;
+ },
+ buildPagesBySlugIndex: (pages: ReadonlySet<string>, toSlug: (docName: string) => string) => {
+ const index = new Map<string, string>();
+ for (const docName of pages) {
+ const slug = toSlug(docName);
+ if (!index.has(slug)) index.set(slug, docName);
+ }
+ return index;
+ },
+ buildPagesByBasenameIndex: (pages: ReadonlySet<string>, toSlug: (docName: string) => string) => {
+ const index = new Map<string, string>();
+ for (const docName of [...pages].sort()) {
+ const basename = docName.split('/').pop() ?? docName;
+ const slug = toSlug(basename);
+ if (!index.has(slug)) index.set(slug, docName);
+ }
+ return index;
+ },
+ setPageListCache: setPageListCacheMock,
+}));
+
import { PageListProvider, usePageList } from './PageListContext';
interface PagesResponseBody {
- pages: { docName: string; title: string; size: number; modified: string }[];
+ pages: {
+ docName: string;
+ title: string;
+ size: number;
+ modified: string;
+ docExt?: string;
+ icon?: string;
+ }[];
+}
+interface DocumentListEntry {
+ kind: 'document' | 'asset' | 'folder';
+ path?: string;
}
type ResponseResolver = (res: Response) => void;
@@ -20,31 +70,54 @@ function jsonRes(body: unknown) {
return { ok: true, json: async () => body } as Response;
}
-function pagesBody(docNames: string[]): PagesResponseBody {
+function pagesBody(
+ entries: Array<
+ | string
+ | {
+ docName: string;
+ title?: string;
+ docExt?: string;
+ icon?: string;
+ }
+ >,
+): PagesResponseBody {
return {
- pages: docNames.map((docName) => ({
- docName,
- title: docName,
- size: 1,
- modified: '2026-01-01T00:00:00.000Z',
- })),
+ pages: entries.map((entry) => {
+ const docName = typeof entry === 'string' ? entry : entry.docName;
+ return {
+ docName,
+ title: typeof entry === 'string' ? entry : (entry.title ?? entry.docName),
+ size: 1,
+ modified: '2026-01-01T00:00:00.000Z',
+ docExt: typeof entry === 'string' ? undefined : entry.docExt,
+ icon: typeof entry === 'string' ? undefined : entry.icon,
+ };
+ }),
};
}
-async function settleRound(docNames: string[]) {
+async function settleRound(
+ docNames: Parameters<typeof pagesBody>[0],
+ documents: DocumentListEntry[] = [],
+) {
const pr = pageResolvers.shift();
const dr = docResolvers.shift();
if (!pr || !dr) throw new Error('settleRound: no in-flight fetch pair to resolve');
await act(async () => {
pr(jsonRes(pagesBody(docNames)));
- dr(jsonRes({ documents: [] }));
+ dr(jsonRes({ documents }));
await Promise.resolve();
});
}
+function latestCachePayload() {
+ return setPageListCacheMock.mock.calls.at(-1)?.[0] as PageListCachePayload | undefined;
+}
+
beforeEach(() => {
pageResolvers = [];
docResolvers = [];
+ setPageListCacheMock.mockClear();
originalFetch = globalThis.fetch;
globalThis.fetch = ((input: RequestInfo | URL) => {
const url = String(input);
@@ -73,6 +146,18 @@ function Probe() {
return <div data-testid="page-list-content">{[...pages].sort().join(',')}</div>;
}
+function AddPageProbe() {
+ const { addPage, pages } = usePageList();
+ return (
+ <div>
+ <button type="button" onClick={() => addPage('Draft')}>
+ Add draft
+ </button>
+ <span data-testid="page-list-content">{[...pages].sort().join(',')}</span>
+ </div>
+ );
+}
+
describe('PageListContext loading stability', () => {
test('PRD-6649: a background refetch (window focus) never re-shows the cold-load skeleton or remounts the view', async () => {
render(
@@ -115,4 +200,43 @@ describe('PageListContext loading stability', () => {
expect(afterNode.getAttribute('data-marker')).toBe('cold');
expect(screen.queryByTestId('page-list-skeleton')).toBeNull();
});
+
+ test('publishes runtime-derived pages, folders, slugs, assets, icons, and optimistic pages to the cache', async () => {
+ render(
+ <PageListProvider>
+ <AddPageProbe />
+ </PageListProvider>,
+ );
+
+ await settleRound(
+ [{ docName: 'Notes/Alpha', icon: '📘', docExt: '.mdx' }],
+ [
+ { kind: 'folder', path: 'Notes' },
+ { kind: 'asset', path: 'images/diagram.png' },
+ ],
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('page-list-content').textContent).toBe('Notes/Alpha');
+ });
+
+ let payload = latestCachePayload();
+ expect([...(payload?.pages ?? [])]).toEqual(['Notes/Alpha']);
+ expect(payload?.pagesBySlug.get('notes-alpha')).toBe('Notes/Alpha');
+ expect(payload?.pagesByBasename.get('alpha')).toBe('Notes/Alpha');
+ expect([...(payload?.assetPaths ?? [])]).toEqual(['images/diagram.png']);
+ expect(payload?.folderPaths.has('Notes')).toBe(true);
+ expect(payload?.pageIcons.get('Notes/Alpha')).toBe('📘');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Add draft' }));
+
+ await waitFor(() => {
+ expect(screen.getByTestId('page-list-content').textContent).toBe('Draft,Notes/Alpha');
+ });
+
+ payload = latestCachePayload();
+ expect(payload?.pages.has('Draft')).toBe(true);
+ expect(payload?.pagesBySlug.get('draft')).toBe('Draft');
+ expect(payload?.pagesByBasename.get('draft')).toBe('Draft');
+ });
});
diff --git a/packages/app/src/components/PageListContext.test.ts b/packages/app/src/components/PageListContext.test.ts
index eea47786d..ec8f7fbc7 100644
--- a/packages/app/src/components/PageListContext.test.ts
+++ b/packages/app/src/components/PageListContext.test.ts
@@ -1,6 +1,5 @@
import { describe, expect, test } from 'bun:test';
import { mergePageSets, pruneConfirmedOptimisticPages } from './PageListContext';
-import SRC from './PageListContext.tsx?raw';
describe('PageListContext helpers', () => {
test('mergePageSets keeps optimistic created pages visible until server confirms them', () => {
@@ -13,38 +12,3 @@ describe('PageListContext helpers', () => {
expect([...pending]).toEqual(['tim']);
});
});
-
-describe('PageListContext compiler-memoization preconditions', () => {
- test('no "use no memo" directive opts the file out of the React Compiler', () => {
- expect(SRC).not.toMatch(/['"]use no memo['"]/);
- });
-
- test('no hand-written useMemo / useCallback / memo (compiler covers it)', () => {
- expect(SRC).not.toMatch(/\buseMemo\s*\(/);
- expect(SRC).not.toMatch(/\buseCallback\s*\(/);
- expect(SRC).not.toMatch(/\bmemo\s*\(/);
- expect(SRC).not.toMatch(/from\s+['"]react['"][^;]*\b(useMemo|useCallback|memo)\b/);
- });
-
- test('per-render derivations exist and consume reactive state via top-level helpers', () => {
- expect(SRC).toMatch(
- /const\s+pages\s*=\s*mergePageSets\(\s*serverPages\s*,\s*optimisticPages\s*\)/,
- );
- expect(SRC).toMatch(
- /const\s+pageTitles\s*=\s*mergePageTitles\(\s*serverPageTitles\s*,\s*optimisticPages\s*\)/,
- );
- expect(SRC).toMatch(/const\s+folderPaths\s*=\s*new Set\(\[[\s\S]*?deriveKnownFolderPaths\(/);
- expect(SRC).toMatch(/const\s+pagesBySlug\s*=\s*buildPagesBySlugIndex\(\s*pages\s*,/);
- expect(SRC).toMatch(/const\s+pagesByBasename\s*=\s*buildPagesByBasenameIndex\(\s*pages\s*,/);
- });
-
- test('setPageListCache effect depends on every memoized derivation passed into the cache', () => {
- expect(SRC).toMatch(
- /useEffect\(\s*\(\)\s*=>\s*\{[\s\S]*?setPageListCache\([\s\S]*?\}\s*,\s*\[\s*pages\s*,\s*folderPaths\s*,\s*pagesBySlug\s*,\s*pagesByBasename\s*,\s*assetPaths\s*,\s*pageIcons\s*\]\s*\)/,
- );
- });
-
- test('setPageListCache object literal forwards pagesByBasename (not just the dep array)', () => {
- expect(SRC).toMatch(/setPageListCache\(\s*\{[\s\S]*?\bpagesByBasename\b[\s\S]*?\}\s*\)/);
- });
-});
diff --git a/packages/app/src/components/ProjectSwitcher.dom.test.tsx b/packages/app/src/components/ProjectSwitcher.dom.test.tsx
new file mode 100644
index 000000000..5326ec21b
--- /dev/null
+++ b/packages/app/src/components/ProjectSwitcher.dom.test.tsx
@@ -0,0 +1,202 @@
+import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { ProjectSwitcher } from './ProjectSwitcher';
+
+type MenuProps = {
+ children?: ReactNode;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
+};
+type ItemProps = {
+ children?: ReactNode;
+ disabled?: boolean;
+ onSelect?: () => void;
+ [key: string]: unknown;
+};
+
+let lastDropdownOpenChange: ((open: boolean) => void) | null = null;
+let keydownBubbleCount = 0;
+let createDialogProps: Array<{ open: boolean; bridge: unknown }> = [];
+
+mock.module('@/components/ui/dropdown-menu', () => ({
+ DropdownMenu: ({ children, onOpenChange }: MenuProps) => {
+ lastDropdownOpenChange = onOpenChange ?? null;
+ return <div>{children}</div>;
+ },
+ DropdownMenuContent: ({ children, ...props }: ItemProps) => (
+ <div role="menu" {...props}>
+ {children}
+ </div>
+ ),
+ DropdownMenuItem: ({ children, disabled, onSelect, ...props }: ItemProps) => (
+ <button type="button" role="menuitem" disabled={disabled} onClick={onSelect} {...props}>
+ {children}
+ </button>
+ ),
+ DropdownMenuLabel: ({ children, ...props }: ItemProps) => <div {...props}>{children}</div>,
+ DropdownMenuSeparator: () => <hr />,
+ DropdownMenuTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,
+}));
+
+mock.module('@/components/ui/input-group', () => ({
+ InputGroup: ({ children, ...props }: ItemProps) => (
+ <fieldset
+ {...props}
+ onKeyDown={() => {
+ keydownBubbleCount += 1;
+ }}
+ >
+ {children}
+ </fieldset>
+ ),
+ InputGroupAddon: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+ InputGroupInput: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+}));
+
+mock.module('@/components/ui/sidebar', () => ({
+ SidebarMenuButton: ({ children, ...props }: ItemProps) => (
+ <button type="button" {...props}>
+ {children}
+ </button>
+ ),
+}));
+
+mock.module('./CreateProjectDialog', () => ({
+ CreateProjectDialog: (props: { open: boolean; bridge: unknown }) => {
+ createDialogProps.push(props);
+ return <div data-testid="create-project-dialog" data-open={String(props.open)} />;
+ },
+}));
+
+function recent(name: string, path = `/projects/${name.toLowerCase()}`) {
+ return { name, path: path.replaceAll(' ', '-') };
+}
+
+function createBridge() {
+ return {
+ config: {
+ projectName: 'Current Project',
+ projectPath: '/projects/current',
+ },
+ project: {
+ listRecent: mock(() =>
+ Promise.resolve([
+ recent('Current', '/projects/current'),
+ ...Array.from({ length: 10 }, (_, index) => recent(`Project ${index + 1}`)),
+ recent('Omega', '/archive/omega-project'),
+ ]),
+ ),
+ open: mock(() => Promise.resolve()),
+ },
+ dialog: {
+ openFolder: mock(() => Promise.resolve('/chosen/folder')),
+ },
+ navigator: {
+ open: mock(() => Promise.resolve()),
+ },
+ };
+}
+
+async function openMenu() {
+ fireEvent.click(screen.getByTestId('project-switcher-trigger'));
+ act(() => {
+ lastDropdownOpenChange?.(true);
+ });
+ await waitFor(() => {
+ expect(screen.getByTestId('project-switcher-search')).not.toBeNull();
+ });
+}
+
+describe('ProjectSwitcher dropdown behavior', () => {
+ beforeEach(() => {
+ cleanup();
+ lastDropdownOpenChange = null;
+ keydownBubbleCount = 0;
+ createDialogProps = [];
+ });
+
+ test('renders footer actions in order and routes each action through the expected bridge entry point', async () => {
+ const bridge = createBridge();
+ render(<ProjectSwitcher bridge={bridge as never} />);
+
+ expect(screen.getByTestId('project-switcher-trigger').textContent).toContain('Current Project');
+
+ await openMenu();
+
+ const menuText = screen.getByTestId('project-switcher-menu').textContent ?? '';
+ const openFolderIndex = menuText.indexOf('Open folder');
+ const switchProjectIndex = menuText.indexOf('Switch Project');
+ const newProjectIndex = menuText.indexOf('New project');
+ expect(openFolderIndex).toBeGreaterThan(-1);
+ expect(switchProjectIndex).toBeGreaterThan(openFolderIndex);
+ expect(newProjectIndex).toBeGreaterThan(switchProjectIndex);
+
+ for (const testId of [
+ 'project-switcher-open-folder',
+ 'project-switcher-switch-project',
+ 'project-switcher-new-project',
+ ]) {
+ expect(screen.getByTestId(testId).querySelector('svg[aria-hidden="true"]')).not.toBeNull();
+ }
+
+ fireEvent.click(screen.getByTestId('project-switcher-switch-project'));
+ await waitFor(() => expect(bridge.navigator.open).toHaveBeenCalledTimes(1));
+
+ fireEvent.click(screen.getByTestId('project-switcher-open-folder'));
+ await waitFor(() => {
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/chosen/folder',
+ target: 'new-window',
+ entryPoint: 'pick-existing',
+ });
+ });
+
+ fireEvent.click(screen.getByTestId('project-switcher-recent-/projects/project-1'));
+ await waitFor(() => {
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ path: '/projects/project-1',
+ target: 'new-window',
+ entryPoint: 'recents',
+ });
+ });
+
+ fireEvent.click(screen.getByTestId('project-switcher-new-project'));
+ await waitFor(() => {
+ expect(screen.getByTestId('create-project-dialog').getAttribute('data-open')).toBe('true');
+ });
+ expect(createDialogProps.at(-1)?.bridge).toBe(bridge);
+ });
+
+ test('search filters before the ten-item slice, announces empty results, stops typeahead bubbling, and clears on close', async () => {
+ const bridge = createBridge();
+ render(<ProjectSwitcher bridge={bridge as never} />);
+
+ await openMenu();
+
+ const search = screen.getByTestId('project-switcher-search') as HTMLInputElement;
+
+ fireEvent.keyDown(search, { key: 'O' });
+ expect(keydownBubbleCount).toBe(0);
+
+ fireEvent.change(search, { target: { value: 'omega' } });
+
+ await waitFor(() => {
+ expect(screen.getByTestId('project-switcher-recent-/archive/omega-project')).not.toBeNull();
+ });
+ expect(screen.queryByTestId('project-switcher-recent-/projects/project-1')).toBeNull();
+
+ fireEvent.change(search, { target: { value: 'does-not-exist' } });
+
+ expect((await screen.findByRole('status')).textContent).toBe('No matching projects.');
+
+ act(() => {
+ lastDropdownOpenChange?.(false);
+ lastDropdownOpenChange?.(true);
+ });
+
+ await waitFor(() => {
+ expect((screen.getByTestId('project-switcher-search') as HTMLInputElement).value).toBe('');
+ });
+ });
+});
diff --git a/packages/app/src/components/ProjectSwitcher.test.ts b/packages/app/src/components/ProjectSwitcher.test.ts
index 88ba34271..2ad005e27 100644
--- a/packages/app/src/components/ProjectSwitcher.test.ts
+++ b/packages/app/src/components/ProjectSwitcher.test.ts
@@ -1,6 +1,4 @@
import { describe, expect, mock, test } from 'bun:test';
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
describe('ProjectSwitcher module', () => {
test('Component module imports cleanly', async () => {
@@ -64,158 +62,3 @@ describe('runWithToast (IPC rejection → toast feedback)', () => {
await expect(runWithToast(() => Promise.resolve(), 'fallback')).resolves.toBeUndefined();
});
});
-
-describe('Switch Project affordance (source-level guards)', () => {
- const SRC_PATH = join(__dirname, 'ProjectSwitcher.tsx');
- const src = readFileSync(SRC_PATH, 'utf-8');
-
- test('renders the Switch Project dropdown item with the correct testid and label', () => {
- expect(src).toContain('data-testid="project-switcher-switch-project"');
- expect(src).toMatch(
- /<DropdownMenuItem[^>]*data-testid="project-switcher-switch-project"[^>]*>[\s\S]*?<Trans>Switch Project<\/Trans>\s*<\/DropdownMenuItem>/,
- );
- });
-
- test('Switch Project item: onSelect routes through onSwitchProject which calls bridge.navigator.open()', () => {
- const tagRe = /<DropdownMenuItem\b[^>]*data-testid="project-switcher-switch-project"[^>]*>/;
- const tag = src.match(tagRe)?.[0];
- expect(
- tag,
- 'DropdownMenuItem with project-switcher-switch-project testid not found',
- ).toBeTruthy();
- expect(tag).toContain('onSelect={onSwitchProject}');
-
- const handlerRe = /const onSwitchProject = \(\) => \{[\s\S]*?\};/;
- const handler = src.match(handlerRe)?.[0];
- expect(handler, 'onSwitchProject handler definition not found').toBeTruthy();
- expect(handler).toMatch(/bridge\.navigator\.open\(\)/);
- });
-
- test('the new item sits BELOW "Open folder" (Obsidian-pattern position)', () => {
- const openFolderIdx = src.indexOf('data-testid="project-switcher-open-folder"');
- const switchProjectIdx = src.indexOf('data-testid="project-switcher-switch-project"');
- expect(openFolderIdx).toBeGreaterThan(0);
- expect(switchProjectIdx).toBeGreaterThan(0);
- expect(switchProjectIdx).toBeGreaterThan(openFolderIdx);
- });
-
- test('Recents row click tags the open call with entryPoint: "recents"', () => {
- expect(src).toMatch(
- /openProject\s*=[\s\S]*?bridge\.project\.open\(\{[^}]*entryPoint:\s*'recents'/,
- );
- });
-
- test('Open Folder click tags the open call with entryPoint: "pick-existing"', () => {
- expect(src).toMatch(
- /onOpenFolder\s*=[\s\S]*?bridge\.project\.open\(\{[^}]*entryPoint:\s*'pick-existing'/,
- );
- });
-});
-
-describe('New project action + footer icons (source-level guards)', () => {
- const SRC_PATH = join(__dirname, 'ProjectSwitcher.tsx');
- const src = readFileSync(SRC_PATH, 'utf-8');
-
- test('New project item sits at the bottom, below Switch Project', () => {
- const openFolderIdx = src.indexOf('data-testid="project-switcher-open-folder"');
- const switchProjectIdx = src.indexOf('data-testid="project-switcher-switch-project"');
- const newProjectIdx = src.indexOf('data-testid="project-switcher-new-project"');
- expect(newProjectIdx).toBeGreaterThan(switchProjectIdx);
- expect(switchProjectIdx).toBeGreaterThan(openFolderIdx);
- });
-
- test('New project item routes through onCreateProject', () => {
- const tag = src.match(
- /<DropdownMenuItem\b[^>]*data-testid="project-switcher-new-project"[^>]*>/,
- )?.[0];
- expect(tag, 'New project DropdownMenuItem not found').toBeTruthy();
- expect(tag).toContain('onSelect={onCreateProject}');
- });
-
- test('onCreateProject closes the menu and opens the create dialog', () => {
- const handler = src.match(/const onCreateProject = \(\) => \{[\s\S]*?\};/)?.[0];
- expect(handler, 'onCreateProject handler not found').toBeTruthy();
- expect(handler).toMatch(/setOpen\(false\)/);
- expect(handler).toMatch(/setCreateProjectOpen\(true\)/);
- });
-
- test('mounts CreateProjectDialog wired to the create-open state and bridge', () => {
- expect(src).toMatch(
- /<CreateProjectDialog\b[\s\S]*?open=\{createProjectOpen\}[\s\S]*?onOpenChange=\{setCreateProjectOpen\}[\s\S]*?bridge=\{bridge\}/,
- );
- });
-
- test('each footer item carries a leading icon', () => {
- const itemWithIcon = (testid: string, icon: string) =>
- new RegExp(`<DropdownMenuItem\\b[^>]*data-testid="${testid}"[^>]*>\\s*<${icon}\\b[^>]*/>`);
- expect(src).toMatch(itemWithIcon('project-switcher-open-folder', 'FolderOpen'));
- expect(src).toMatch(itemWithIcon('project-switcher-switch-project', 'LayoutGrid'));
- expect(src).toMatch(itemWithIcon('project-switcher-new-project', 'Plus'));
- });
-});
-
-describe('Recent-projects search affordance (source-level guards)', () => {
- const SRC_PATH = join(__dirname, 'ProjectSwitcher.tsx');
- const src = readFileSync(SRC_PATH, 'utf-8');
-
- test('renders a shadcn InputGroup search field (no raw <input>)', () => {
- expect(src).toContain('data-testid="project-switcher-search"');
- expect(src).toMatch(/<InputGroupInput\b[\s\S]*?data-testid="project-switcher-search"/);
- expect(src).toMatch(/from '@\/components\/ui\/input-group'/);
- expect(src).not.toMatch(/<input\b/);
- });
-
- test('search field stops keydown propagation so Radix typeahead does not eat it', () => {
- const tag = src.match(/<InputGroupInput\b[\s\S]*?\/>/)?.[0];
- expect(tag, 'InputGroupInput not found').toBeTruthy();
- expect(tag).toMatch(/onKeyDown=\{\(e\)\s*=>\s*e\.stopPropagation\(\)\}/);
- });
-
- test('filters BEFORE slicing to 10 so matches past the first ten are reachable', () => {
- expect(src).toMatch(/filtered\.slice\(0,\s*10\)/);
- expect(src).not.toMatch(/switchable\.slice\(0,\s*10\)/);
- });
-
- test('filter matches on both name and path', () => {
- expect(src).toMatch(/r\.name\.toLowerCase\(\)\.includes\(query\)/);
- expect(src).toMatch(/r\.path\.toLowerCase\(\)\.includes\(query\)/);
- });
-
- test('clears the query when the menu closes', () => {
- expect(src).toMatch(/if\s*\(!next\)\s*setSearch\(''\)/);
- });
-
- test('renders an announced "No matching projects." empty state for the filtered list', () => {
- const label = src.match(
- /<DropdownMenuLabel\b[^>]*>[\s\S]*?<Trans>No matching projects\.<\/Trans>[\s\S]*?<\/DropdownMenuLabel>/,
- )?.[0];
- expect(label, 'No matching projects label not found').toBeTruthy();
- expect(label).toMatch(/role="status"/);
- expect(label).toMatch(/aria-live="polite"/);
- });
-
- test('search field renders inside the has-recents branch, after the empty-recents label', () => {
- const emptyRecentsIdx = src.indexOf('No other recent projects.');
- const searchFieldIdx = src.indexOf('data-testid="project-switcher-search"');
- expect(emptyRecentsIdx).toBeGreaterThan(0);
- expect(searchFieldIdx).toBeGreaterThan(emptyRecentsIdx);
- });
-
- test('scrollable results container contains scroll chaining (overscroll-contain)', () => {
- const div = src.match(/<div className="max-h-64[^"]*overflow-y-auto[^"]*">/)?.[0];
- expect(div, 'scrollable results container not found').toBeTruthy();
- expect(div).toMatch(/overscroll-contain/);
- });
-});
-
-describe('macOS dropdown-open regression guard (click-to-open fallback)', () => {
- const SRC_PATH = join(__dirname, 'ProjectSwitcher.tsx');
- const src = readFileSync(SRC_PATH, 'utf-8');
-
- test('trigger opens from onClick on the Electron host, with a pointerdown guard', () => {
- expect(src).toMatch(/onClick=\{\s*isElectronHost/);
- expect(src).toMatch(/onPointerDown=\{\s*isElectronHost/);
- expect(src).toContain('sawPointerDownRef');
- expect(src).toMatch(/<DropdownMenu\b[^>]*\bmodal=\{false\}/);
- });
-});
diff --git a/packages/app/src/components/PublishToGitHubDialog.dom.test.tsx b/packages/app/src/components/PublishToGitHubDialog.dom.test.tsx
new file mode 100644
index 000000000..3aea73d22
--- /dev/null
+++ b/packages/app/src/components/PublishToGitHubDialog.dom.test.tsx
@@ -0,0 +1,365 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import type { SharePublishOwner } from '@inkeep/open-knowledge-core';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { act } from 'react';
+import type { PublishErrorPresentation } from '@/lib/share/publish-wizard';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+type OwnersResult =
+ | { ok: true; owners: SharePublishOwner[] }
+ | { ok: false; error: 'auth-required' | 'network' };
+
+type SubmitPayload = {
+ description?: string;
+ name: string;
+ owner: string;
+ visibility: 'private' | 'public';
+};
+
+const defaultOwners: SharePublishOwner[] = [
+ { kind: 'user', login: 'alice' },
+ { kind: 'org', login: 'docs-team' },
+];
+
+let ownersQueue: OwnersResult[] = [];
+let submitResult:
+ | { ok: true; ownerLogin: string; repoName: string }
+ | { ok: false; error: string } = {
+ ok: true,
+ ownerLogin: 'alice',
+ repoName: 'my-project',
+};
+let presentError: PublishErrorPresentation = {
+ banner: 'Could not publish',
+ next: { kind: 'edit-form' },
+};
+let workspaceContentDir = '/Users/alice/My Project';
+let activeDocName: string | null = 'docs/intro';
+let submitCalls: SubmitPayload[] = [];
+let openExternalCalls: string[] = [];
+let windowOpenCalls: string[] = [];
+let shareConstructUrlResponse:
+ | { ok: true; shareUrl: string; sharedUrl: string; branch: string }
+ | { ok: false; error: string; branch?: string } = {
+ ok: true,
+ shareUrl: 'https://openknowledge.ai/d/Published123',
+ sharedUrl: 'https://github.com/alice/my-project/blob/main/docs/intro.md',
+ branch: 'main',
+};
+let clipboardError: unknown = null;
+let permissionsPolicyRefusal = false;
+let clipboardCalls: string[] = [];
+
+function sanitizeRepoName(value: string) {
+ return value
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-|-$/g, '');
+}
+
+const fetchPublishOwnersMock = mock(
+ async () => ownersQueue.shift() ?? { ok: true, owners: defaultOwners },
+);
+const fetchPublishNameCheckMock = mock(async () => ({ ok: true }));
+const submitPublishRequestMock = mock(async (payload: SubmitPayload) => {
+ submitCalls.push(payload);
+ return submitResult;
+});
+const requestShareConstructUrlMock = mock(async () => shareConstructUrlResponse);
+const mapShareErrorToToastMock = mock((error: string, branch?: string) =>
+ branch ? `mapped ${error} on ${branch}` : `mapped ${error}`,
+);
+const scheduleClipboardWriteMock = mock(async (text: string) => {
+ clipboardCalls.push(text);
+ if (clipboardError) throw clipboardError;
+});
+const isPermissionsPolicyRefusalMock = mock(() => permissionsPolicyRefusal);
+const toastMock = {
+ error: mock(() => {}),
+ success: mock(() => {}),
+};
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+mock.module('@/components/AuthModal', () => ({
+ AuthModal: ({ onSuccess, open }: { onSuccess: () => void; open: boolean }) =>
+ open ? (
+ <button data-testid="auth-modal" type="button" onClick={onSuccess}>
+ GitHub auth
+ </button>
+ ) : null,
+}));
+
+mock.module('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({ activeDocName }),
+}));
+
+mock.module('@/lib/use-workspace', () => ({
+ useWorkspace: () => ({ contentDir: workspaceContentDir }),
+}));
+
+mock.module('@/lib/share/run-share-action', () => ({
+ mapShareErrorToToast: mapShareErrorToToastMock,
+ requestShareConstructUrl: requestShareConstructUrlMock,
+}));
+
+mock.module('@/lib/share/clipboard-adapter', () => ({
+ isPermissionsPolicyRefusal: isPermissionsPolicyRefusalMock,
+ scheduleClipboardWrite: scheduleClipboardWriteMock,
+}));
+
+mock.module('@/lib/share/publish-wizard', () => ({
+ canSubmitPublish: ({
+ nameCheck,
+ owner,
+ sanitizedName,
+ submitting,
+ }: {
+ nameCheck: { kind: string };
+ owner: SharePublishOwner | null;
+ sanitizedName: string;
+ submitting: boolean;
+ }) => Boolean(owner && sanitizedName && nameCheck.kind === 'available' && !submitting),
+ extractFolderBasename: (path: string) => path.split('/').filter(Boolean).at(-1) ?? '',
+ fetchPublishNameCheck: fetchPublishNameCheckMock,
+ fetchPublishOwners: fetchPublishOwnersMock,
+ presentPublishError: () => presentError,
+ resolveNameCheckStatus: (_result: unknown, owner: string, name: string) => ({
+ kind: 'available' as const,
+ name,
+ owner,
+ }),
+ sanitizeRepoName,
+ submitPublishRequest: submitPublishRequestMock,
+}));
+
+mock.module('sonner', () => ({
+ toast: toastMock,
+}));
+
+function setDesktopBridge(bridge: unknown) {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ writable: true,
+ value: bridge,
+ });
+}
+
+async function renderDialog() {
+ const { PublishToGitHubDialog } = await import('./PublishToGitHubDialog');
+ const onOpenChange = mock((_open: boolean) => {});
+ await act(async () => {
+ render(<PublishToGitHubDialog open={true} onOpenChange={onOpenChange} />);
+ await Promise.resolve();
+ });
+ return { onOpenChange };
+}
+
+async function waitForAvailableNameCheck() {
+ await waitFor(
+ () => {
+ expect(screen.getByTestId('publish-name-check').getAttribute('data-status')).toBe(
+ 'available',
+ );
+ },
+ { timeout: 1500 },
+ );
+}
+
+describe('PublishToGitHubDialog runtime behavior', () => {
+ afterEach(() => {
+ cleanup();
+ ownersQueue = [];
+ submitResult = { ok: true, ownerLogin: 'alice', repoName: 'my-project' };
+ presentError = { banner: 'Could not publish', next: { kind: 'edit-form' } };
+ workspaceContentDir = '/Users/alice/My Project';
+ activeDocName = 'docs/intro';
+ submitCalls = [];
+ openExternalCalls = [];
+ windowOpenCalls = [];
+ shareConstructUrlResponse = {
+ ok: true,
+ shareUrl: 'https://openknowledge.ai/d/Published123',
+ sharedUrl: 'https://github.com/alice/my-project/blob/main/docs/intro.md',
+ branch: 'main',
+ };
+ clipboardError = null;
+ permissionsPolicyRefusal = false;
+ clipboardCalls = [];
+ fetchPublishOwnersMock.mockClear();
+ fetchPublishNameCheckMock.mockClear();
+ submitPublishRequestMock.mockClear();
+ requestShareConstructUrlMock.mockClear();
+ mapShareErrorToToastMock.mockClear();
+ scheduleClipboardWriteMock.mockClear();
+ isPermissionsPolicyRefusalMock.mockClear();
+ toastMock.error.mockClear();
+ toastMock.success.mockClear();
+ setDesktopBridge(undefined);
+ window.open = ((url: string) => {
+ windowOpenCalls.push(url);
+ return null;
+ }) as typeof window.open;
+ });
+
+ test('renders the dialog frame, fields, default private visibility, and live name-check preview', async () => {
+ await renderDialog();
+
+ expect(screen.getByRole('dialog', { name: 'Publish to GitHub' })).toBeTruthy();
+ expect(await screen.findByTestId('publish-owner-trigger')).toBeTruthy();
+ expect((screen.getByTestId('publish-name') as HTMLInputElement).value).toBe('my-project');
+ expect(screen.getByText('Will be created as')).toBeTruthy();
+ expect(screen.getByText('my-project')).toBeTruthy();
+ expect(screen.getByTestId('publish-visibility-private').getAttribute('data-state')).toBe(
+ 'checked',
+ );
+ expect(screen.getByTestId('publish-visibility-public').getAttribute('data-state')).toBe(
+ 'unchecked',
+ );
+ expect(screen.getByTestId('publish-description')).toBeTruthy();
+ expect(screen.getByTestId('publish-submit').getAttribute('type')).toBe('button');
+ expect((screen.getByTestId('publish-submit') as HTMLButtonElement).disabled).toBe(true);
+
+ await waitForAvailableNameCheck();
+
+ expect(screen.getByTestId('publish-name-check').textContent).toContain('Available');
+ expect((screen.getByTestId('publish-submit') as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ test('submits through publish helpers, shows success URL, copies from a fresh button click, and Done closes', async () => {
+ const { onOpenChange } = await renderDialog();
+ await waitForAvailableNameCheck();
+
+ await userEvent.type(screen.getByTestId('publish-description'), 'Internal docs');
+ await userEvent.click(screen.getByTestId('publish-submit'));
+
+ await waitFor(() => {
+ expect(submitCalls).toHaveLength(1);
+ });
+ expect(submitCalls).toEqual([
+ {
+ description: 'Internal docs',
+ name: 'my-project',
+ owner: 'alice',
+ visibility: 'private',
+ },
+ ]);
+ expect(onOpenChange).not.toHaveBeenCalledWith(false);
+ expect(await screen.findByTestId('publish-success')).toBeTruthy();
+ await waitFor(() =>
+ expect(requestShareConstructUrlMock).toHaveBeenCalledWith({
+ kind: 'doc',
+ docPath: 'docs/intro.md',
+ }),
+ );
+ const shareUrl = (await screen.findByTestId('publish-share-url')) as HTMLInputElement;
+ expect(shareUrl.value).toBe('https://openknowledge.ai/d/Published123');
+
+ await userEvent.click(screen.getByTestId('publish-copy-link'));
+
+ expect(clipboardCalls).toEqual(['https://openknowledge.ai/d/Published123']);
+ await waitFor(() => expect(toastMock.success).toHaveBeenCalledWith('Link copied.'));
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+
+ cleanup();
+ const next = await renderDialog();
+ await waitForAvailableNameCheck();
+ await userEvent.click(screen.getByTestId('publish-submit'));
+ await screen.findByTestId('publish-success');
+ await userEvent.click(screen.getByTestId('publish-success-done'));
+ expect(next.onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ test('success view maps share-url prefetch failures into the inline manual-copy slot', async () => {
+ shareConstructUrlResponse = {
+ ok: false,
+ error: 'branch-not-on-origin',
+ branch: 'feat/share',
+ };
+ await renderDialog();
+ await waitForAvailableNameCheck();
+
+ await userEvent.click(screen.getByTestId('publish-submit'));
+
+ expect((await screen.findByTestId('publish-share-url-error')).textContent).toBe(
+ 'mapped branch-not-on-origin on feat/share',
+ );
+ expect(mapShareErrorToToastMock).toHaveBeenCalledWith('branch-not-on-origin', 'feat/share');
+ });
+
+ test('copy failure keeps the visible URL and surfaces generic manual-copy copy in jsdom', async () => {
+ clipboardError = new DOMException('Permission denied', 'NotAllowedError');
+ await renderDialog();
+ await waitForAvailableNameCheck();
+
+ await userEvent.click(screen.getByTestId('publish-submit'));
+ await screen.findByTestId('publish-share-url');
+ await userEvent.click(screen.getByTestId('publish-copy-link'));
+
+ await waitFor(() => {
+ expect(toastMock.error).toHaveBeenCalledWith(
+ "Couldn't copy. Select the URL above to copy it manually.",
+ );
+ });
+ expect((screen.getByTestId('publish-share-url') as HTMLInputElement).value).toBe(
+ 'https://openknowledge.ai/d/Published123',
+ );
+ });
+
+ test('mounts AuthModal for auth-required owners and retries owners after auth success', async () => {
+ ownersQueue = [
+ { ok: false, error: 'auth-required' },
+ { ok: true, owners: defaultOwners },
+ ];
+ await renderDialog();
+
+ expect(await screen.findByTestId('auth-modal')).toBeTruthy();
+ expect(screen.getByText('Connect GitHub to continue.')).toBeTruthy();
+
+ fireEvent.click(screen.getByTestId('auth-modal'));
+
+ await waitFor(() => {
+ expect(fetchPublishOwnersMock).toHaveBeenCalledTimes(2);
+ });
+ await waitForAvailableNameCheck();
+ expect(screen.queryByTestId('auth-modal') === null).toBe(true);
+ });
+
+ test('routes SAML authorization through desktop openExternal and falls back to window.open', async () => {
+ submitResult = { ok: false, error: 'saml-sso' };
+ presentError = {
+ banner: 'Authorize this organization.',
+ next: { authorizeUrl: 'https://github.com/orgs/docs-team/sso', kind: 'authorize-org' },
+ };
+ setDesktopBridge({
+ shell: {
+ openExternal: async (url: string) => {
+ openExternalCalls.push(url);
+ return { ok: true };
+ },
+ },
+ });
+ await renderDialog();
+ await waitForAvailableNameCheck();
+
+ await userEvent.click(screen.getByTestId('publish-submit'));
+ await userEvent.click(await screen.findByTestId('publish-authorize-org'));
+
+ expect(openExternalCalls).toEqual(['https://github.com/orgs/docs-team/sso']);
+ cleanup();
+
+ setDesktopBridge(undefined);
+ await renderDialog();
+ await waitForAvailableNameCheck();
+ await userEvent.click(screen.getByTestId('publish-submit'));
+ await userEvent.click(await screen.findByTestId('publish-authorize-org'));
+
+ expect(windowOpenCalls).toEqual(['https://github.com/orgs/docs-team/sso']);
+ });
+});
diff --git a/packages/app/src/components/PublishToGitHubDialog.test.ts b/packages/app/src/components/PublishToGitHubDialog.test.ts
index 78e94518c..f4d1727e8 100644
--- a/packages/app/src/components/PublishToGitHubDialog.test.ts
+++ b/packages/app/src/components/PublishToGitHubDialog.test.ts
@@ -1,137 +1,8 @@
import { describe, expect, test } from 'bun:test';
import { PublishToGitHubDialog } from './PublishToGitHubDialog';
-import SRC from './PublishToGitHubDialog?raw';
describe('PublishToGitHubDialog module', () => {
test('exports PublishToGitHubDialog as a named function component', () => {
expect(typeof PublishToGitHubDialog).toBe('function');
});
});
-
-describe('PublishToGitHubDialog — load-bearing structural guards', () => {
- test('uses the canonical Dialog primitives (Root, Content, Header, Body, Footer, Title)', () => {
- expect(SRC).toContain("from '@/components/ui/dialog'");
- expect(SRC).toContain('Dialog as DialogRoot');
- expect(SRC).toContain('DialogContent');
- expect(SRC).toContain('DialogHeader');
- expect(SRC).toContain('DialogBody');
- expect(SRC).toContain('DialogFooter');
- expect(SRC).toContain('DialogTitle');
- });
-
- test('imports decision-tree helpers from @/lib/share/publish-wizard', () => {
- expect(SRC).toContain("from '@/lib/share/publish-wizard'");
- expect(SRC).toContain('fetchPublishOwners');
- expect(SRC).toContain('fetchPublishNameCheck');
- expect(SRC).toContain('submitPublishRequest');
- expect(SRC).toContain('sanitizeRepoName');
- expect(SRC).toContain('resolveNameCheckStatus');
- expect(SRC).toContain('presentPublishError');
- expect(SRC).toContain('canSubmitPublish');
- });
-
- test('post-publish success view: pre-fetched URL field + Copy button + Done button', () => {
- expect(SRC).toContain('publishResult');
- expect(SRC).toContain('PublishSuccessView');
- expect(SRC).toContain('shareUrl');
- expect(SRC).toContain('shareUrlError');
- expect(SRC).toContain('data-testid="publish-success"');
- expect(SRC).toContain('data-testid="publish-share-url"');
- expect(SRC).toContain('data-testid="publish-copy-link"');
- expect(SRC).toContain('data-testid="publish-success-done"');
- expect(SRC).toContain('handleCopyShareLink');
- expect(SRC).not.toContain('copyPostPublishShareUrl');
- });
-
- test('share URL pre-fetch routes through requestShareConstructUrl + mapShareErrorToToast', () => {
- expect(SRC).toContain("from '@/lib/share/run-share-action'");
- expect(SRC).toContain('requestShareConstructUrl');
- expect(SRC).toContain('mapShareErrorToToast');
- });
-
- test('mounts AuthModal for the auth-required / reauth recovery branch', () => {
- expect(SRC).toContain("from '@/components/AuthModal'");
- expect(SRC).toContain('<AuthModal');
- expect(SRC).toContain('handleAuthSuccess');
- });
-
- test('reads contentDir via useWorkspace + activeDocName via useDocumentContext', () => {
- expect(SRC).toContain("from '@/lib/use-workspace'");
- expect(SRC).toContain('useWorkspace');
- expect(SRC).toContain("from '@/editor/DocumentContext'");
- expect(SRC).toContain('useDocumentContext');
- });
-
- test('iframe Permissions-Policy refusal surfaces a tailored toast (vs the generic fallback)', () => {
- expect(SRC).toContain('isPermissionsPolicyRefusal');
- expect(SRC).toContain('window.self !== window.top');
- expect(SRC).toContain('desktop app');
- });
-
- test('clipboard write goes through the clipboard adapter (Electron IPC + writeText fallback)', () => {
- expect(SRC).toContain("from '@/lib/share/clipboard-adapter'");
- expect(SRC).toContain('scheduleClipboardWrite');
- expect(SRC).not.toContain('navigator.clipboard.writeText');
- });
-
- test('SAML SSO surface routes through shell.openExternal (system browser) or window.open fallback', () => {
- expect(SRC).toContain('window.okDesktop?.shell?.openExternal');
- expect(SRC).toContain('window.open(');
- });
-
- test('Submit button is type="button" and disables when canSubmitPublish is false', () => {
- expect(SRC).toMatch(
- /<Button[\s\S]{0,400}?type="button"[\s\S]{0,400}?data-testid="publish-submit"/,
- );
- expect(SRC).toContain('canSubmitPublish');
- });
-
- test('Owner field, name field, visibility radio + description carry stable test-ids', () => {
- expect(SRC).toContain('data-testid="publish-owner-trigger"');
- expect(SRC).toContain('data-testid="publish-name"');
- expect(SRC).toContain('data-testid="publish-visibility-private"');
- expect(SRC).toContain('data-testid="publish-visibility-public"');
- expect(SRC).toContain('data-testid="publish-description"');
- expect(SRC).toContain('data-testid="publish-banner"');
- });
-
- test('Private visibility is the default (FR6) — initial state seeded by the open-effect', () => {
- expect(SRC).toMatch(/setVisibility\(['"]private['"]\)/);
- });
-
- test('Will be created as <name> preview is the FR6 inline preview surface', () => {
- expect(SRC).toContain('Will be created as');
- });
-
- test('Name-check debounce constant is set to the spec-required 500ms', () => {
- expect(SRC).toMatch(/NAME_CHECK_DEBOUNCE_MS\s*=\s*500/);
- });
-
- test('Re-arms transient state on open (FR consistency with CreateProjectDialog)', () => {
- const block = SRC.match(/if \(!open\) return;[\s\S]{0,1200}?\}, \[open\]\);/);
- expect(block).not.toBeNull();
- const body = block?.[0] ?? '';
- expect(body).toContain('setBanner(null)');
- expect(body).toContain('setSubmitting(false)');
- expect(body).toContain('setName(seededName)');
- expect(body).toContain('setPublishResult(null)');
- expect(body).toContain('setCopying(false)');
- expect(body).toContain('setShareUrl(null)');
- expect(body).toContain('setShareUrlError(null)');
- });
-
- test('No React Compiler escape hatches (memo / useMemo / useCallback / forwardRef)', () => {
- expect(SRC).not.toMatch(/\bforwardRef\b/);
- expect(SRC).not.toMatch(/\buseMemo\b/);
- expect(SRC).not.toMatch(/\buseCallback\b/);
- expect(SRC).not.toMatch(/\bmemo\(/);
- });
-
- test('No inline style props (Tailwind via className per code-style rule)', () => {
- expect(SRC).not.toMatch(/\bstyle=\{\{/);
- });
-
- test('Name-check indicator container is an aria-live region for status announcements (WCAG 4.1.3)', () => {
- expect(SRC).toMatch(/aria-live="polite"[\s\S]{0,800}?<NameCheckIndicator/);
- });
-});
diff --git a/packages/app/src/components/SeedDialog.dom.test.tsx b/packages/app/src/components/SeedDialog.dom.test.tsx
new file mode 100644
index 000000000..d9c1aa2e0
--- /dev/null
+++ b/packages/app/src/components/SeedDialog.dom.test.tsx
@@ -0,0 +1,227 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import type {
+ OkPackId,
+ OkScaffoldPlan,
+ OkSeedPackInfo,
+ OkSeedPlanResult,
+} from '@/lib/desktop-bridge-types';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+mock.module('@lingui/core/macro', () => ({
+ t: renderLinguiTemplate,
+ plural: (value: number, options: { one: string; other: string }) =>
+ (value === 1 ? options.one : options.other).replace('#', String(value)),
+}));
+
+mock.module('@/components/PackCardGrid', () => ({
+ PackCardGrid: ({
+ packs,
+ onPackSelect,
+ }: {
+ packs: OkSeedPackInfo[] | null;
+ onPackSelect: (packId: OkPackId) => void;
+ }) => (
+ <div data-testid="pack-card-grid">
+ {packs === null ? (
+ <span>Loading packs</span>
+ ) : (
+ packs.map((pack) => (
+ <button key={pack.id} type="button" onClick={() => onPackSelect(pack.id)}>
+ {pack.name}
+ </button>
+ ))
+ )}
+ </div>
+ ),
+}));
+
+const toastSuccesses: string[] = [];
+const toastErrors: string[] = [];
+const listPacksCalls: string[] = [];
+const planCalls: Array<{ packId?: OkPackId; rootDir?: string }> = [];
+const applyCalls: Array<{ plan: OkScaffoldPlan; packId?: OkPackId }> = [];
+
+const knowledgeBasePlan: OkScaffoldPlan = {
+ created: [
+ { kind: 'folder', path: 'notes' },
+ { kind: 'file', path: 'notes/index.md' },
+ ],
+ skipped: [],
+ warnings: [],
+};
+
+const plainNotesPlan: OkScaffoldPlan = {
+ created: [{ kind: 'file', path: 'plain.md' }],
+ skipped: [],
+ warnings: [],
+};
+
+const packs: OkSeedPackInfo[] = [
+ {
+ id: 'knowledge-base',
+ name: 'Knowledge Base',
+ description: 'Structured notes with templates.',
+ folders: [{ path: 'notes', summary: 'Notes folder' }],
+ entryCounts: { files: 1, folders: 1 },
+ },
+ {
+ id: 'plain-notes',
+ name: 'Plain Notes',
+ description: 'A minimal notes setup.',
+ folders: [],
+ entryCounts: { files: 1, folders: 0 },
+ },
+];
+
+let planImpl: (options: { packId?: OkPackId; rootDir?: string }) => Promise<OkSeedPlanResult> =
+ async (options) => ({
+ ok: true,
+ plan: options.packId === 'plain-notes' ? plainNotesPlan : knowledgeBasePlan,
+ });
+
+mock.module('@/lib/seed-client', () => ({
+ seedClient: () => ({
+ listPacks: async () => {
+ listPacksCalls.push('list');
+ return { ok: true as const, packs };
+ },
+ plan: async (options: { packId?: OkPackId; rootDir?: string }) => {
+ planCalls.push(options);
+ return planImpl(options);
+ },
+ apply: async (plan: OkScaffoldPlan, options: { packId?: OkPackId }) => {
+ applyCalls.push({ plan, packId: options.packId });
+ return {
+ ok: true as const,
+ result: { applied: plan.created.length, errors: [], durationMs: 1 },
+ };
+ },
+ }),
+}));
+
+mock.module('sonner', () => ({
+ toast: {
+ success: (message: string) => toastSuccesses.push(message),
+ error: (message: string) => toastErrors.push(message),
+ },
+}));
+
+async function renderSeedDialog(
+ props: Partial<React.ComponentProps<typeof import('./SeedDialog').SeedDialog>> = {},
+) {
+ const { SeedDialog } = await import('./SeedDialog');
+ const onOpenChange = props.onOpenChange ?? (() => {});
+ render(
+ <TooltipProvider>
+ <SeedDialog open onOpenChange={onOpenChange} {...props} />
+ </TooltipProvider>,
+ );
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+}
+
+describe('SeedDialog runtime behavior', () => {
+ afterEach(() => {
+ cleanup();
+ listPacksCalls.length = 0;
+ planCalls.length = 0;
+ applyCalls.length = 0;
+ toastSuccesses.length = 0;
+ toastErrors.length = 0;
+ planImpl = async (options) => ({
+ ok: true,
+ plan: options.packId === 'plain-notes' ? plainNotesPlan : knowledgeBasePlan,
+ });
+ });
+
+ test('exports SeedDialog component', async () => {
+ const mod = await import('./SeedDialog');
+ expect(typeof mod.SeedDialog).toBe('function');
+ });
+
+ test('starts on the shared pack grid when no initial pack is provided', async () => {
+ await renderSeedDialog();
+
+ expect(await screen.findByTestId('pack-card-grid')).toBeTruthy();
+ expect(screen.getByText('Knowledge Base')).toBeTruthy();
+ expect(screen.getByText('Plain Notes')).toBeTruthy();
+ expect(screen.queryByText('Where should it live?')).toBeNull();
+ expect(planCalls).toHaveLength(0);
+ expect(listPacksCalls).toEqual(['list']);
+ });
+
+ test('initialPackId skips the picker, plans the selected pack, and locks Back', async () => {
+ await renderSeedDialog({ initialPackId: 'plain-notes' });
+
+ expect(await screen.findByText('Initialize Plain Notes')).toBeTruthy();
+ await waitFor(() => {
+ expect(planCalls).toContainEqual({ packId: 'plain-notes', rootDir: undefined });
+ });
+
+ expect(screen.queryByTestId('pack-card-grid')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'Back' })).toBeNull();
+ expect(await screen.findByText('plain.md')).toBeTruthy();
+ });
+
+ test('Back returns to the picker and clears the previous pack plan before the next plan resolves', async () => {
+ let resolveKnowledgeBasePlan: ((result: OkSeedPlanResult) => void) | null = null;
+ planImpl = (options) => {
+ if (options.packId === 'knowledge-base') {
+ return new Promise((resolve) => {
+ resolveKnowledgeBasePlan = resolve;
+ });
+ }
+ return Promise.resolve({ ok: true, plan: plainNotesPlan });
+ };
+
+ await renderSeedDialog();
+ await userEvent.click(await screen.findByRole('button', { name: 'Plain Notes' }));
+ expect(await screen.findByText('Initialize Plain Notes')).toBeTruthy();
+ expect(await screen.findByText('plain.md')).toBeTruthy();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Back' }));
+ expect(await screen.findByTestId('pack-card-grid')).toBeTruthy();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Knowledge Base' }));
+ expect(await screen.findByText('Initialize Knowledge Base')).toBeTruthy();
+ expect(screen.queryByText('plain.md')).toBeNull();
+ expect(screen.getByText('Computing scaffold plan')).toBeTruthy();
+
+ await act(async () => {
+ resolveKnowledgeBasePlan?.({ ok: true, plan: knowledgeBasePlan });
+ });
+ expect(await screen.findByText('notes/')).toBeTruthy();
+ });
+
+ test('Initialize applies the selected pack through seedClient and closes on success', async () => {
+ const onOpenChangeCalls: boolean[] = [];
+ const applied: string[] = [];
+ await renderSeedDialog({
+ initialPackId: 'plain-notes',
+ onOpenChange: (open) => onOpenChangeCalls.push(open),
+ onSeedApplied: () => applied.push('yes'),
+ });
+
+ await screen.findByText('plain.md');
+ await userEvent.click(screen.getByRole('button', { name: 'Initialize' }));
+
+ await waitFor(() => {
+ expect(applyCalls).toHaveLength(1);
+ });
+ expect(applyCalls[0]).toEqual({ plan: plainNotesPlan, packId: 'plain-notes' });
+ expect(applied).toEqual(['yes']);
+ expect(onOpenChangeCalls).toEqual([false]);
+ expect(toastSuccesses[0]).toContain('Plain Notes initialized');
+ expect(toastErrors).toEqual([]);
+ });
+});
diff --git a/packages/app/src/components/SeedDialog.test.ts b/packages/app/src/components/SeedDialog.test.ts
deleted file mode 100644
index 86796b344..000000000
--- a/packages/app/src/components/SeedDialog.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './SeedDialog?raw';
-
-describe('SeedDialog module', () => {
- test('exports SeedDialog component', async () => {
- const mod = await import('./SeedDialog');
- expect(typeof mod.SeedDialog).toBe('function');
- });
-});
-
-describe('SeedDialog source-level guards', () => {
- test('accepts an initialPackId prop on the component signature', () => {
- expect(SRC).toContain('initialPackId?: OkPackId');
- expect(SRC).toMatch(/initialPackId\s*[,}]/);
- });
-
- test('honors initialPackId on dialog open (resets to it, not the default)', () => {
- expect(SRC).toContain('setSelectedPackId(initialPackId ?? DEFAULT_PACK_ID)');
- });
-
- test('derives a packLocked flag from initialPackId', () => {
- expect(SRC).toMatch(/packLocked\s*=\s*initialPackId/);
- });
-
- test('step 1 renders PackCardGrid (same surface as the empty-state canvas)', () => {
- expect(SRC).toContain("from '@/components/PackCardGrid'");
- expect(SRC).toContain('<PackCardGrid');
- });
-
- test('renders the configure step only when step === "configure"', () => {
- expect(SRC).toMatch(/step\s*===\s*'configure'/);
- });
-
- test('threads the selected pack name into the dialog title on the configure step', () => {
- expect(SRC).toContain('selectedPack?.name');
- expect(SRC).toContain('Initialize a starter pack');
- });
-
- test('routes plan/apply/listPacks through the shared seedClient transport', () => {
- expect(SRC).toContain("from '@/lib/seed-client'");
- });
-
- test('Back button shows only on the configure step AND only when not pack-locked', () => {
- expect(SRC).toMatch(/step\s*===\s*'configure'\s*&&\s*!packLocked/);
- });
-
- test('Back handler resets phase so a previous plan does not flash under the new pack title', () => {
- expect(SRC).toContain('handleBack');
- expect(SRC).toMatch(/handleBack[\s\S]{0,400}setPhase\(\{\s*kind:\s*'loading'/);
- });
-});
diff --git a/packages/app/src/components/SettingsButton.dom.test.tsx b/packages/app/src/components/SettingsButton.dom.test.tsx
new file mode 100644
index 000000000..e606d52b5
--- /dev/null
+++ b/packages/app/src/components/SettingsButton.dom.test.tsx
@@ -0,0 +1,112 @@
+import { afterEach, beforeEach, describe, expect, jest, mock, test } from 'bun:test';
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { TooltipProvider } from '@/components/ui/tooltip';
+
+const preloadCalls: string[] = [];
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+mock.module('@/components/settings/SettingsDialogBodyLazy', () => ({
+ SettingsDialogBodyLazy: {
+ preload: () => {
+ preloadCalls.push('preload');
+ return Promise.resolve();
+ },
+ },
+}));
+
+async function renderSettingsButton() {
+ const { SettingsButton } = await import('./SettingsButton');
+ return render(
+ <TooltipProvider>
+ <SettingsButton />
+ </TooltipProvider>,
+ );
+}
+
+function flushPendingPreloadTimers() {
+ act(() => {
+ jest.runOnlyPendingTimers();
+ });
+}
+
+describe('SettingsButton runtime behavior', () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ cleanup();
+ preloadCalls.length = 0;
+ window.location.hash = '';
+ });
+
+ test('exports the component', async () => {
+ const mod = await import('./SettingsButton');
+ expect(typeof mod.SettingsButton).toBe('function');
+ });
+
+ test('renders the header settings button with an accessible label', async () => {
+ await renderSettingsButton();
+
+ const button = screen.getByTestId('header-settings-button');
+ expect(button.tagName).toBe('BUTTON');
+ expect(button.textContent).toBe('Settings');
+ expect(button.querySelector('svg')).not.toBeNull();
+ });
+
+ test('click opens the canonical settings hash and cancels a pending preload', async () => {
+ await renderSettingsButton();
+
+ const button = screen.getByTestId('header-settings-button');
+ act(() => {
+ fireEvent.mouseEnter(button);
+ fireEvent.click(button);
+ });
+ flushPendingPreloadTimers();
+
+ expect(window.location.hash).toBe('#settings');
+ expect(preloadCalls).toEqual([]);
+ });
+
+ test('hover and focus intent preload the lazy settings body after the debounce', async () => {
+ await renderSettingsButton();
+
+ const button = screen.getByTestId('header-settings-button');
+ act(() => {
+ fireEvent.mouseEnter(button);
+ });
+ flushPendingPreloadTimers();
+ expect(preloadCalls).toEqual(['preload']);
+
+ preloadCalls.length = 0;
+ act(() => {
+ fireEvent.focus(button);
+ });
+ flushPendingPreloadTimers();
+ expect(preloadCalls).toEqual(['preload']);
+ });
+
+ test('leave and blur cancel pending intent preloads', async () => {
+ await renderSettingsButton();
+
+ const button = screen.getByTestId('header-settings-button');
+ act(() => {
+ fireEvent.mouseEnter(button);
+ fireEvent.mouseLeave(button);
+ });
+ flushPendingPreloadTimers();
+ expect(preloadCalls).toEqual([]);
+
+ act(() => {
+ fireEvent.focus(button);
+ fireEvent.blur(button);
+ });
+ flushPendingPreloadTimers();
+ expect(preloadCalls).toEqual([]);
+ });
+});
diff --git a/packages/app/src/components/SettingsButton.test.ts b/packages/app/src/components/SettingsButton.test.ts
deleted file mode 100644
index e43e753af..000000000
--- a/packages/app/src/components/SettingsButton.test.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './SettingsButton?raw';
-
-describe('SettingsButton module', () => {
- test('Component module imports cleanly', async () => {
- const mod = await import('./SettingsButton');
- expect(typeof mod.SettingsButton).toBe('function');
- });
-});
-
-describe('SettingsButton source-level guards', () => {
- test('imports the Settings icon from lucide-react', () => {
- expect(SRC).toMatch(/import\s*\{\s*Settings\s*\}\s*from\s*'lucide-react'/);
- expect(SRC).toMatch(/<Settings\b/);
- });
-
- test('routes through SETTINGS_OPEN_HASH (canonical hash literal)', () => {
- expect(SRC).toMatch(/from\s*'@\/lib\/use-settings-route'/);
- expect(SRC).toContain('SETTINGS_OPEN_HASH');
- expect(SRC).toMatch(/window\.location\.hash\s*=\s*SETTINGS_OPEN_HASH/);
- });
-
- test('carries an accessible label and stable test-id', () => {
- expect(SRC).toContain('data-testid="header-settings-button"');
- expect(SRC).toMatch(/<span\s+className="sr-only">\s*<Trans>Settings<\/Trans>\s*<\/span>/);
- });
-
- test('wraps in a Tooltip that announces "Settings"', () => {
- expect(SRC).toMatch(/from\s*'@\/components\/ui\/tooltip'/);
- expect(SRC).toMatch(/<TooltipContent>\s*<Trans>Settings<\/Trans>\s*<\/TooltipContent>/);
- });
-
- test('warms the lazy Settings body chunk on hover and focus intent', () => {
- expect(SRC).toMatch(/from\s*'@\/components\/settings\/SettingsDialogBodyLazy'/);
- expect(SRC).toContain('SettingsDialogBodyLazy.preload()');
- expect(SRC).toMatch(/onMouseEnter=\{schedulePreload\}/);
- expect(SRC).toMatch(/onFocus=\{schedulePreload\}/);
- expect(SRC).toMatch(/onMouseLeave=\{cancelPreload\}/);
- expect(SRC).toMatch(/onBlur=\{cancelPreload\}/);
- expect(SRC).toMatch(/PREFETCH_INTENT_DELAY_MS\s*=\s*50\b/);
- expect(SRC).toMatch(/onClick=\{\(\)\s*=>\s*\{\s*cancelPreload\(\)/);
- });
-});
diff --git a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
index 51a1af48b..a43bb6309 100644
--- a/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
+++ b/packages/app/src/components/ShareBranchSwitchDialog.dom.test.tsx
@@ -269,6 +269,43 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()
cleanup();
});
+ test('dirty conflicts disable Switch and describe the blocking file list', async () => {
+ const store = createShareReceiveStore();
+ const { bridge } = makeBridge({
+ fetchBranchInfo: mock(
+ async (): Promise<BranchInfoResponse> => ({
+ ok: true,
+ currentBranch: 'main',
+ currentHeadSha: 'aaaaaaa',
+ detached: false,
+ shareTargetExists: true,
+ dirtyConflicts: {
+ conflicts: true,
+ files: ['docs/notes.md', 'package.json'],
+ },
+ }),
+ ),
+ });
+ const payload = projectBranchSwitchPayload();
+ const fakeBridgeForStore = {
+ onShareReceived: (cb: (p: OkShareReceivedPayload) => void) => {
+ cb(payload);
+ return () => {};
+ },
+ } as unknown as OkDesktopBridge;
+ store.install({ bridge: fakeBridgeForStore });
+ render(<ShareBranchSwitchDialog bridge={bridge} store={store} />);
+
+ const switchBtn = await screen.findByTestId('share-branch-switch-switch');
+ const describedBy = switchBtn.getAttribute('aria-describedby');
+ expect((switchBtn as HTMLButtonElement).disabled).toBe(true);
+ expect(switchBtn.getAttribute('aria-disabled')).toBe('true');
+ expect(describedBy).toBe('share-receive-branch-conflict-files');
+ const conflictList = document.getElementById(describedBy ?? '');
+ expect(conflictList?.textContent).toContain('docs/notes.md');
+ expect(conflictList?.textContent).toContain('package.json');
+ });
+
test('Switch click runs checkout, awaits CC1, then warm-focus-dispatches with pendingDeepLinkDoc + pendingBranch', async () => {
const store = createShareReceiveStore();
const { bridge, calls } = makeBridge();
@@ -312,6 +349,76 @@ describe('ShareBranchSwitchDialog — Switch path (runCheckout + CC1 gate)', ()
expect(openArg.pendingBranch).toBe(payload.share.branch);
});
+ test('Switch does not navigate or warm-focus until CC1 resolves', async () => {
+ const store = createShareReceiveStore();
+ let resolveCc1: (result: { ok: true }) => void = () => {};
+ const cc1Promise = new Promise<{ ok: true }>((resolve) => {
+ resolveCc1 = resolve;
+ });
+ const { bridge, calls } = makeBridge({
+ awaitBranchSwitched: mock(() => cc1Promise),
+ });
+ const payload = projectBranchSwitchPayload();
+ const fakeBridgeForStore = {
+ onShareReceived: (cb: (p: OkShareReceivedPayload) => void) => {
+ cb(payload);
+ return () => {};
+ },
+ } as unknown as OkDesktopBridge;
+ store.install({ bridge: fakeBridgeForStore });
+ window.location.hash = '#before-switch';
+ render(<ShareBranchSwitchDialog bridge={bridge} store={store} />);
+
+ const switchBtn = await screen.findByTestId('share-branch-switch-switch');
+ await act(async () => {
+ fireEvent.click(switchBtn);
+ await Promise.resolve();
+ });
+
+ await waitFor(() => {
+ expect(calls.awaitBranchSwitched).toHaveBeenCalledTimes(1);
+ });
+ expect(calls.open).not.toHaveBeenCalled();
+ expect(window.location.hash).toBe('#before-switch');
+
+ resolveCc1({ ok: true });
+
+ await waitFor(() => {
+ expect(calls.open).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ test('Switch on a branchless share dismisses without waiting on CC1', async () => {
+ const store = createShareReceiveStore();
+ const { bridge, calls } = makeBridge();
+ const payload = projectBranchSwitchPayload();
+ payload.share.branch = '';
+ const fakeBridgeForStore = {
+ onShareReceived: (cb: (p: OkShareReceivedPayload) => void) => {
+ cb(payload);
+ return () => {};
+ },
+ } as unknown as OkDesktopBridge;
+ store.install({ bridge: fakeBridgeForStore });
+ render(<ShareBranchSwitchDialog bridge={bridge} store={store} />);
+
+ const switchBtn = await screen.findByTestId('share-branch-switch-switch');
+ await act(async () => {
+ fireEvent.click(switchBtn);
+ await Promise.resolve();
+ });
+
+ await waitFor(() => {
+ expect(store.getSnapshot()).toBeNull();
+ });
+ expect(calls.runCheckout).toHaveBeenCalledWith({
+ projectPath: payload.projectPath,
+ branch: '',
+ });
+ expect(calls.awaitBranchSwitched).not.toHaveBeenCalled();
+ expect(calls.open).not.toHaveBeenCalled();
+ });
+
test('Switch warm-focus open() reject surfaces a toast — no silent swallow', async () => {
const store = createShareReceiveStore();
const { bridge, calls } = makeBridge({
diff --git a/packages/app/src/components/ShareBranchSwitchDialog.test.ts b/packages/app/src/components/ShareBranchSwitchDialog.test.ts
deleted file mode 100644
index 82a9f01d3..000000000
--- a/packages/app/src/components/ShareBranchSwitchDialog.test.ts
+++ /dev/null
@@ -1,215 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './ShareBranchSwitchDialog?raw';
-
-describe('ShareBranchSwitchDialog — module shape', () => {
- test('exports the named component', () => {
- expect(SRC).toMatch(/export\s+function\s+ShareBranchSwitchDialog\s*\(/);
- });
-
- test('exports the props type', () => {
- expect(SRC).toMatch(/export\s+interface\s+ShareBranchSwitchDialogProps/);
- });
-});
-
-describe('ShareBranchSwitchDialog — wiring', () => {
- test('imports the Dialog primitives from @/components/ui/dialog (shadcn)', () => {
- expect(SRC).toContain("from '@/components/ui/dialog'");
- expect(SRC).toContain('DialogRoot');
- expect(SRC).toContain('DialogContent');
- expect(SRC).toContain('DialogHeader');
- expect(SRC).toContain('DialogTitle');
- expect(SRC).toContain('DialogBody');
- expect(SRC).toContain('DialogFooter');
- });
-
- test('imports Button from @/components/ui/button (no raw <button>)', () => {
- expect(SRC).toContain("from '@/components/ui/button'");
- expect(SRC).not.toMatch(/<button\b/);
- expect(SRC).not.toMatch(/<input\b/);
- expect(SRC).not.toMatch(/<select\b/);
- expect(SRC).not.toMatch(/<textarea\b/);
- });
-
- test('imports the branch-switch-flow state machine helpers', () => {
- expect(SRC).toContain("from '@/lib/share/branch-switch-flow'");
- expect(SRC).toContain('applyBranchInfo');
- expect(SRC).toContain('applyCheckoutOutcome');
- expect(SRC).toContain('selectBranchSwitchVariant');
- expect(SRC).toContain('formatCurrentLabel');
- expect(SRC).toContain('markSwitching');
- expect(SRC).toContain('initialBranchSwitchState');
- });
-
- test('imports the receive-store singleton + uses useSyncExternalStore', () => {
- expect(SRC).toContain("from '@/lib/share/receive-store'");
- expect(SRC).toContain('shareReceiveStore');
- expect(SRC).toContain('useSyncExternalStore');
- expect(SRC).toContain('store.subscribe');
- expect(SRC).toContain('store.getSnapshot');
- });
-});
-
-describe('ShareBranchSwitchDialog — main-resolved payload contract (US-003 seam)', () => {
- test('gates rendering on the project-branch-switch payload kind', () => {
- expect(SRC).toContain("'project-branch-switch'");
- });
-
- test('does NOT re-run selectCandidate / runQ1Lookup in the renderer', () => {
- expect(SRC).not.toMatch(/\brunQ1Lookup\s*\(/);
- expect(SRC).not.toMatch(/\bselectCandidate\s*\(/);
- expect(SRC).not.toMatch(/\basQ1BridgeDeps\s*\(/);
- });
-
- test('reads projectPath, share, and currentBranch from the payload', () => {
- expect(SRC).toContain('payload.projectPath');
- expect(SRC).toMatch(/payload\.share|active\.share/);
- });
-});
-
-describe('ShareBranchSwitchDialog — branch-info + checkout wiring', () => {
- test('fetches bridge.project.fetchBranchInfo once per payload (variant matrix data)', () => {
- expect(SRC).toMatch(/bridge\.project[\s\n.]+fetchBranchInfo\(/);
- expect(SRC).toContain('branchInfoStartedRef');
- });
-
- test('calls bridge.project.runCheckout on the Switch user click', () => {
- expect(SRC).toMatch(/bridge\.project[\s\n.]+runCheckout\(/);
- });
-
- test('calls bridge.project.awaitBranchSwitched after runCheckout returns ok', () => {
- expect(SRC).toMatch(/bridge\.project[\s\n.]+awaitBranchSwitched\(/);
- expect(SRC).toContain('timeoutMs: 30_000');
- });
-
- test('Switch handler does NOT navigate on runCheckout HTTP 200 (STOP rule)', () => {
- const switchIdx = SRC.indexOf('function handleSwitch');
- expect(switchIdx).toBeGreaterThan(-1);
- const handlerEndIdx = SRC.indexOf('function handleOpenCurrent', switchIdx);
- expect(handlerEndIdx).toBeGreaterThan(switchIdx);
- const handlerBody = SRC.slice(switchIdx, handlerEndIdx);
- expect(handlerBody).not.toMatch(/window\.location\.hash\s*=/);
- expect(handlerBody).not.toMatch(/window\.location\.assign\b/);
- expect(handlerBody).not.toContain('awaitBranchSwitched(');
- });
-
- test('await-CC1 effect single-fires via a ref + has a cancelled-flag cleanup', () => {
- expect(SRC).toContain('awaitBranchSwitchedStartedRef');
- const awaitIdx = SRC.indexOf('awaitBranchSwitched(');
- expect(awaitIdx).toBeGreaterThan(-1);
- const effectStart = SRC.lastIndexOf('useEffect(', awaitIdx);
- expect(effectStart).toBeGreaterThan(-1);
- const thenIdx = SRC.indexOf('.then((result)', awaitIdx);
- expect(thenIdx).toBeGreaterThan(awaitIdx);
- const effectEnd = SRC.indexOf('}, [branchSwitchState.phase', thenIdx);
- expect(effectEnd).toBeGreaterThan(thenIdx);
- const effectBody = SRC.slice(effectStart, effectEnd);
- expect(effectBody).toContain('let cancelled = false');
- expect(effectBody).toContain('cancelled = true');
- expect(effectBody).toMatch(/if \(cancelled\) return;/);
- });
-
- test('on Switch → awaitBranchSwitched ok: bridge.project.open re-called with pendingDeepLinkDoc AND pendingBranch (warm-focus)', () => {
- const awaitIdx = SRC.indexOf('awaitBranchSwitched(');
- expect(awaitIdx).toBeGreaterThan(-1);
- const completeIdx = SRC.indexOf("'branch-switch-complete'", awaitIdx);
- expect(completeIdx).toBeGreaterThan(awaitIdx);
- const timeoutIdx = SRC.indexOf("'branch-switch-timeout'", awaitIdx);
- expect(timeoutIdx).toBeGreaterThan(completeIdx);
- const okBranchBody = SRC.slice(completeIdx, timeoutIdx);
- expect(okBranchBody).toMatch(/bridge\.project[\s\n.]+open\(/);
- expect(okBranchBody).toContain('pendingDeepLinkTarget');
- expect(okBranchBody).toContain('pendingBranch');
- });
-
- test('branchless shares short-circuit the await gate (no 30s timeout sit)', () => {
- const idx = SRC.indexOf('awaitBranchSwitchedStartedRef.current = true');
- expect(idx).toBeGreaterThan(-1);
- const window_ = SRC.slice(Math.max(0, idx - 600), idx + 200);
- expect(window_).toMatch(/!shareBranch|shareBranch === ''|shareBranch\.length === 0/);
- });
-});
-
-describe('ShareBranchSwitchDialog — open-current (OQ2 sibling) + cancel', () => {
- test('Open-on-current dispatches bridge.project.open (warm-focus) without pendingBranch', () => {
- const idx = SRC.indexOf('function handleOpenCurrent');
- expect(idx).toBeGreaterThan(-1);
- const endIdx = SRC.indexOf('function handlePivot', idx);
- expect(endIdx).toBeGreaterThan(idx);
- const body = SRC.slice(idx, endIdx);
- expect(body).toMatch(/bridge\.project[\s\n.]+open\(/);
- expect(body).toContain('pendingDeepLinkTarget');
- expect(body).not.toContain('pendingBranch');
- });
-
- test('Cancel handler dismisses the store and does NOT close the editor window (OQ2)', () => {
- const idx = SRC.indexOf('function handleCancel');
- expect(idx).toBeGreaterThan(-1);
- const endIdx = SRC.indexOf('const variant =', idx);
- expect(endIdx).toBeGreaterThan(idx);
- const body = SRC.slice(idx, endIdx);
- expect(body).toContain('store.dismiss()');
- expect(body).not.toMatch(/window\.close\(/);
- expect(body).not.toContain('bridge.window.close');
- expect(body).not.toMatch(/bridge\.project[\s\n.]+close\(/);
- });
-
- test('logs branch_dialog_action for each user-visible outcome', () => {
- expect(SRC).toContain("branch_dialog_action: 'switch'");
- expect(SRC).toContain("branch_dialog_action: 'open-current'");
- expect(SRC).toContain("branch_dialog_action: 'cancel'");
- expect(SRC).toContain("branch_dialog_action: 'branch-switch-complete'");
- expect(SRC).toContain("branch_dialog_action: 'branch-switch-timeout'");
- });
-});
-
-describe('ShareBranchSwitchDialog — UI primitives + a11y', () => {
- test('uses shadcn Button for action buttons (no raw <button>)', () => {
- expect(SRC).toContain('<Button');
- expect(SRC).not.toMatch(/<button\b/);
- });
-
- test('Switch button carries aria-describedby pointing at the conflict file list', () => {
- expect(SRC).toContain('aria-describedby');
- expect(SRC).toContain('share-receive-branch-conflict-files');
- });
-
- test('renders dedicated data-testids for downstream e2e selection', () => {
- expect(SRC).toContain('data-testid="share-branch-switch-dialog"');
- expect(SRC).toContain('data-testid="share-branch-switch-switch"');
- expect(SRC).toContain('data-testid="share-branch-switch-cancel"');
- expect(SRC).toContain('data-testid="share-branch-switch-open-current"');
- });
-
- test('Dialog guards onInteractOutside and onPointerDownOutside (focus-loss dismiss)', () => {
- const idx = SRC.indexOf('share-branch-switch-dialog');
- expect(idx).toBeGreaterThan(-1);
- const dialogContentStart = SRC.lastIndexOf('<DialogContent', idx);
- const dialogContentEnd = SRC.indexOf('<DialogHeader', idx);
- expect(dialogContentStart).toBeGreaterThan(-1);
- expect(dialogContentEnd).toBeGreaterThan(dialogContentStart);
- const props = SRC.slice(dialogContentStart, dialogContentEnd);
- expect(props).toContain('onInteractOutside');
- expect(props).toContain('onPointerDownOutside');
- });
-
- test('no React Compiler escape hatches', () => {
- expect(SRC).not.toMatch(/\bforwardRef\b/);
- expect(SRC).not.toMatch(/\bmemo\(/);
- expect(SRC).not.toMatch(/\buseCallback\b/);
- expect(SRC).not.toMatch(/\buseMemo\b/);
- });
-
- test('no inline style props (Tailwind only)', () => {
- expect(SRC).not.toMatch(/style=\{\{/);
- });
-
- test('no try/finally (React Compiler BuildHIR rejects them)', () => {
- expect(SRC).not.toMatch(/\}\s*finally\s*\{/);
- });
-
- test('per-payload reset useEffect tracks [payload]', () => {
- expect(SRC).toMatch(
- /setBranchSwitchState\(initialBranchSwitchState\);\s*branchInfoStartedRef\.current = false;\s*awaitBranchSwitchedStartedRef\.current = false;\s*\},\s*\[payload\]\);/,
- );
- });
-});
diff --git a/packages/app/src/components/ShareButton.dom.test.tsx b/packages/app/src/components/ShareButton.dom.test.tsx
index 0d2761432..26b406822 100644
--- a/packages/app/src/components/ShareButton.dom.test.tsx
+++ b/packages/app/src/components/ShareButton.dom.test.tsx
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
-import { cleanup, render, screen } from '@testing-library/react';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ShareTargetInput } from '@/lib/share/run-share-action';
type WindowGlobals = { NodeFilter?: typeof NodeFilter };
@@ -42,6 +42,24 @@ function renderShareButton(input: ShareTargetInput | null) {
describe('ShareButton', () => {
beforeEach(() => {
if (typeof window !== 'undefined') window.location.hash = '';
+ Reflect.deleteProperty(globalThis, 'okDesktop');
+ Object.defineProperty(globalThis.navigator, 'clipboard', {
+ configurable: true,
+ value: undefined,
+ });
+ globalThis.fetch = mock(() =>
+ Promise.resolve(
+ new Response(
+ JSON.stringify({
+ ok: true,
+ shareUrl: 'https://openknowledge.ai/d/Share123',
+ sharedUrl: 'https://github.com/inkeep/open-knowledge/blob/main/docs/readme.md',
+ branch: 'main',
+ }),
+ { status: 200 },
+ ),
+ ),
+ ) as never;
});
afterEach(() => {
cleanup();
@@ -50,7 +68,7 @@ describe('ShareButton', () => {
test('renders an enabled button for a folder target', () => {
renderShareButton({ kind: 'folder', folderRelativePath: 'guides' });
- const button = screen.getByTestId('share-button');
+ const button = screen.getByRole('button', { name: 'Share folder' });
expect(button).not.toBeNull();
expect((button as HTMLButtonElement).disabled).toBe(false);
});
@@ -58,7 +76,7 @@ describe('ShareButton', () => {
test('renders an enabled button for a doc target', () => {
renderShareButton({ kind: 'doc', docName: 'notes' });
- const button = screen.getByTestId('share-button');
+ const button = screen.getByRole('button', { name: 'Share doc' });
expect(button).not.toBeNull();
expect((button as HTMLButtonElement).disabled).toBe(false);
});
@@ -70,4 +88,21 @@ describe('ShareButton', () => {
expect(button).not.toBeNull();
expect((button as HTMLButtonElement).disabled).toBe(true);
});
+
+ test('surfaces a manual-copy URL when clipboard write fails after constructing a share link', async () => {
+ renderShareButton({ kind: 'doc', docName: 'docs/readme' });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Share doc' }));
+
+ await waitFor(() => {
+ expect(screen.getByTestId('share-button-fallback-popover')).not.toBeNull();
+ });
+ const input = screen.getByLabelText('Share URL') as HTMLInputElement;
+ expect(input.value).toBe('https://openknowledge.ai/d/Share123');
+ expect(globalThis.fetch).toHaveBeenCalledWith('/api/share/construct-url', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ kind: 'doc', docPath: 'docs/readme.md' }),
+ });
+ });
});
diff --git a/packages/app/src/components/ShareButton.test.ts b/packages/app/src/components/ShareButton.test.ts
deleted file mode 100644
index e33e6aa9b..000000000
--- a/packages/app/src/components/ShareButton.test.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import { ShareButton } from './ShareButton';
-import SRC from './ShareButton?raw';
-
-describe('ShareButton module', () => {
- test('exports ShareButton as a named function component', () => {
- expect(typeof ShareButton).toBe('function');
- });
-});
-
-describe('ShareButton — load-bearing structural guards', () => {
- test('delegates orchestration to runShareAction (helper carries the unit-tested decision tree)', () => {
- expect(SRC).toContain("from '@/lib/share/run-share-action'");
- expect(SRC).toContain('runShareAction');
- });
-
- test('takes a discriminated ShareTargetInput (doc|folder) | null via props (not a self-read of activeDocName)', () => {
- expect(SRC).toContain('ShareTargetInput');
- expect(SRC).toContain("from '@/lib/share/run-share-action'");
- expect(SRC).toMatch(/input\s*:\s*ShareTargetInput\s*\|\s*null/);
- expect(SRC).not.toContain('useDocumentContext');
- });
-
- test('reads hasRemote via useGitSyncStatusDetailed (no extra fetch)', () => {
- expect(SRC).toContain("from '@/hooks/use-git-sync-status'");
- expect(SRC).toContain('useGitSyncStatusDetailed');
- expect(SRC).toContain('hasRemote');
- });
-
- test('writes the share URL through the clipboard adapter (Electron IPC + writeText fallback)', () => {
- expect(SRC).toContain("from '@/lib/share/clipboard-adapter'");
- expect(SRC).toContain('scheduleClipboardWrite');
- expect(SRC).not.toContain('navigator.clipboard.writeText');
- });
-
- test('uses sonner toast for the success + error notifications', () => {
- expect(SRC).toContain("from 'sonner'");
- expect(SRC).toContain('toast.success');
- expect(SRC).toContain('toast.error');
- });
-
- test('clipboard-failed result surfaces a Popover with the URL as a manual-copy fallback', () => {
- expect(SRC).toContain("from '@/components/ui/popover'");
- expect(SRC).toContain('PopoverAnchor');
- expect(SRC).toContain('PopoverContent');
- expect(SRC).toContain('clipboardFailedUrl');
- expect(SRC).toContain('data-testid="share-button-fallback-popover"');
- expect(SRC).toContain('data-testid="share-button-fallback-url"');
- expect(SRC).toContain('Link ready but could not copy to clipboard.');
- });
-
- test('does NOT wrap its labeled trigger in a redundant Tooltip (visible "Share" text is the affordance)', () => {
- expect(SRC).not.toContain("from '@/components/ui/tooltip'");
- expect(SRC).not.toContain('<TooltipContent>');
- expect(SRC).toContain('<Trans>Share</Trans>');
- });
-
- test('Button carries a kind-aware aria-label so the icon-bearing affordance is screen-reader navigable', () => {
- expect(SRC).toMatch(/aria-label=\{[\s\S]*?t`Share folder`[\s\S]*?t`Share doc`[\s\S]*?\}/);
- });
-
- test('renders the Share2 icon from lucide-react', () => {
- expect(SRC).toContain("from 'lucide-react'");
- expect(SRC).toContain('Share2');
- });
-
- test('Button gets data-testid="share-button" for downstream Playwright coverage', () => {
- expect(SRC).toContain('data-testid="share-button"');
- });
-
- test('busy flag disables the button so double-clicks cannot fire two requests', () => {
- expect(SRC).toMatch(/setBusy\(true\)/);
- expect(SRC).toMatch(/setBusy\(false\)/);
- });
-
- test('no React Compiler escape hatches (forwardRef / memo / useMemo / useCallback)', () => {
- expect(SRC).not.toMatch(/\bforwardRef\b/);
- expect(SRC).not.toMatch(/\buseMemo\b/);
- expect(SRC).not.toMatch(/\buseCallback\b/);
- expect(SRC).not.toMatch(/\bmemo\(/);
- });
-
- test('no inline style props (Tailwind className per code-style rule)', () => {
- expect(SRC).not.toMatch(/\bstyle=\{\{/);
- });
-});
diff --git a/packages/app/src/components/ShareReceiveDialog.dom.test.tsx b/packages/app/src/components/ShareReceiveDialog.dom.test.tsx
new file mode 100644
index 000000000..92b2cdc51
--- /dev/null
+++ b/packages/app/src/components/ShareReceiveDialog.dom.test.tsx
@@ -0,0 +1,264 @@
+import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import type { OkShareReceivedPayload } from '@/lib/desktop-bridge-types';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+type SharePayload = OkShareReceivedPayload | null;
+
+function createTestStore(initial: SharePayload) {
+ let current = initial;
+ const listeners = new Set<() => void>();
+ return {
+ dismiss: mock(() => {
+ current = null;
+ for (const listener of listeners) listener();
+ }),
+ getSnapshot: () => current,
+ install: () => undefined,
+ set(next: SharePayload) {
+ current = next;
+ for (const listener of listeners) listener();
+ },
+ subscribe(listener: () => void) {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ };
+}
+
+function okPayload(
+ overrides: Partial<Extract<OkShareReceivedPayload, { kind: 'launcher-miss' }>['share']> = {},
+): Extract<OkShareReceivedPayload, { kind: 'launcher-miss' }> {
+ return {
+ kind: 'launcher-miss',
+ share: {
+ owner: 'inkeep',
+ repo: 'open-knowledge',
+ branch: 'main',
+ sharedUrl: 'https://github.com/inkeep/open-knowledge/blob/main/docs/guide.md',
+ target: { kind: 'doc', docPath: 'docs/guide.md' },
+ ...overrides,
+ },
+ };
+}
+
+const toast = {
+ error: mock((_message: string, _opts?: unknown) => {}),
+ info: mock((_message: string, _opts?: unknown) => {}),
+ success: mock((_message: string, _opts?: unknown) => {}),
+};
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+mock.module('sonner', () => ({
+ toast,
+}));
+
+mock.module('@/components/ui/button', () => ({
+ Button: ({
+ children,
+ className: _className,
+ variant: _variant,
+ ...props
+ }: {
+ children?: ReactNode;
+ className?: string;
+ variant?: string;
+ [key: string]: unknown;
+ }) => (
+ <button type="button" {...props}>
+ {children}
+ </button>
+ ),
+}));
+
+mock.module('@/components/ui/dialog', () => ({
+ Dialog: ({ children, open }: { children?: ReactNode; open?: boolean }) =>
+ open ? <div data-testid="dialog-root">{children}</div> : null,
+ DialogBody: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ DialogContent: ({
+ children,
+ onInteractOutside: _onInteractOutside,
+ onPointerDownOutside: _onPointerDownOutside,
+ ...props
+ }: {
+ children?: ReactNode;
+ onInteractOutside?: unknown;
+ onPointerDownOutside?: unknown;
+ [key: string]: unknown;
+ }) => <section {...props}>{children}</section>,
+ DialogDescription: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <p {...props}>{children}</p>
+ ),
+ DialogFooter: ({ children }: { children?: ReactNode }) => <footer>{children}</footer>,
+ DialogHeader: ({ children }: { children?: ReactNode }) => <header>{children}</header>,
+ DialogTitle: ({ children }: { children?: ReactNode }) => <h2>{children}</h2>,
+}));
+
+function createBridge() {
+ const folderPicks: Array<string | null> = [];
+ const validationResults: unknown[] = [];
+ return {
+ __folderPicks: folderPicks,
+ __validationResults: validationResults,
+ dialog: {
+ openFolder: mock(() => Promise.resolve(folderPicks.shift() ?? null)),
+ },
+ navigator: {
+ open: mock(() => Promise.resolve()),
+ },
+ project: {
+ awaitBranchSwitched: mock(() => Promise.resolve({ ok: true as const })),
+ checkDocExists: mock(() => Promise.resolve('exists')),
+ fetchBranchInfo: mock(() =>
+ Promise.resolve({
+ branchIsLocal: true,
+ currentBranch: 'main',
+ currentHeadSha: null,
+ detached: false,
+ dirtyConflicts: { conflicts: false, files: [] },
+ shareFileExists: true,
+ }),
+ ),
+ listRecent: mock(() => Promise.resolve([])),
+ open: mock(() => Promise.resolve()),
+ readHeadBranch: mock(() =>
+ Promise.resolve({ currentBranch: 'main', detached: false, headSha: null }),
+ ),
+ runCheckout: mock(() => Promise.resolve({ ok: true as const })),
+ },
+ share: {
+ validateLocalFolder: mock(() =>
+ Promise.resolve(validationResults.shift() ?? { kind: 'ok', gitRemoteUrl: '' }),
+ ),
+ },
+ };
+}
+
+async function renderDialog({
+ bridge = createBridge(),
+ cloneController,
+ store = createTestStore(okPayload()),
+}: {
+ bridge?: ReturnType<typeof createBridge>;
+ cloneController?: {
+ getAuthStatus: () => Promise<{ authenticated: boolean; host: string; login?: string }>;
+ runClone: (args: { url: string; branch?: string | null }) => Promise<unknown>;
+ startSignIn: () => Promise<{ authenticated: boolean; host: string; login?: string } | null>;
+ };
+ store?: ReturnType<typeof createTestStore>;
+} = {}) {
+ const { ShareReceiveDialog } = await import('./ShareReceiveDialog');
+ render(
+ <ShareReceiveDialog
+ bridge={bridge as never}
+ cloneController={cloneController as never}
+ store={store as never}
+ />,
+ );
+ return { bridge, store };
+}
+
+describe('ShareReceiveDialog runtime behavior', () => {
+ let consoleLogSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof spyOn>;
+
+ beforeEach(() => {
+ for (const fn of [toast.error, toast.info, toast.success]) fn.mockClear();
+ consoleLogSpy = spyOn(console, 'log').mockImplementation(() => {});
+ consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ cleanup();
+ consoleLogSpy.mockRestore();
+ consoleWarnSpy.mockRestore();
+ });
+
+ test('exports the named component through a runtime import', async () => {
+ const mod = await import('./ShareReceiveDialog');
+ expect(typeof mod.ShareReceiveDialog).toBe('function');
+ });
+
+ test('non-ok payloads toast and dismiss without mounting the dialog', async () => {
+ const store = createTestStore({ kind: 'invalid' });
+ await renderDialog({ store });
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Invalid share URL.'));
+ expect(store.dismiss).toHaveBeenCalledTimes(1);
+ expect(screen.queryByTestId('share-receive-dialog')).toBeNull();
+ });
+
+ test('Q2 miss renders metadata, auth-gated clone, sign-in, clone success, and local picker recovery', async () => {
+ const bridge = createBridge();
+ const store = createTestStore(okPayload({ branch: 'feat/share' }));
+ const cloneController = {
+ getAuthStatus: mock(() => Promise.resolve({ authenticated: false, host: 'github.com' })),
+ runClone: mock(() => Promise.resolve({ kind: 'ok', dir: '/cloned/open-knowledge' })),
+ startSignIn: mock(() =>
+ Promise.resolve({ authenticated: true, host: 'github.com', login: 'alice' }),
+ ),
+ };
+ bridge.__folderPicks.push('/wrong', '/right');
+ bridge.__validationResults.push(
+ { kind: 'wrong-repo', actualOwner: 'fork', actualRepo: 'repo' },
+ { kind: 'ok', gitRemoteUrl: 'https://github.com/inkeep/open-knowledge.git' },
+ );
+
+ await renderDialog({ bridge, cloneController, store });
+
+ expect(await screen.findByTestId('share-receive-dialog')).toBeTruthy();
+ expect(screen.getByTestId('share-receive-metadata').textContent).toContain(
+ 'inkeep/open-knowledge',
+ );
+ expect(screen.getByTestId('share-receive-metadata').textContent).toContain('docs/guide.md');
+ expect(screen.getByTestId('share-receive-metadata-branch').textContent).toBe('feat/share');
+ await waitFor(() =>
+ expect(screen.getByTestId('share-receive-clone').textContent).toContain('Connect to clone'),
+ );
+ expect((screen.getByTestId('share-receive-clone') as HTMLButtonElement).disabled).toBe(true);
+
+ fireEvent.click(await screen.findByTestId('share-receive-signin'));
+ await waitFor(() => expect(cloneController.startSignIn).toHaveBeenCalledTimes(1));
+ expect(await screen.findByText(/@alice/)).toBeTruthy();
+
+ fireEvent.click(screen.getByTestId('share-receive-clone'));
+ await waitFor(() =>
+ expect(cloneController.runClone).toHaveBeenCalledWith({
+ branch: 'feat/share',
+ url: 'https://github.com/inkeep/open-knowledge.git',
+ }),
+ );
+ await waitFor(() =>
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ entryPoint: 'share-receive',
+ path: '/cloned/open-knowledge',
+ pendingDeepLinkTarget: { kind: 'doc', path: 'docs/guide.md' },
+ target: 'new-window',
+ }),
+ );
+
+ act(() => {
+ store.set(okPayload({ branch: 'feat/share' }));
+ });
+ await screen.findByTestId('share-receive-dialog');
+ fireEvent.click(screen.getByTestId('share-receive-local'));
+ await waitFor(() =>
+ expect(toast.error).toHaveBeenCalledWith(
+ 'This folder is a clone of fork/repo, not inkeep/open-knowledge. Pick a different folder?',
+ ),
+ );
+ await waitFor(() =>
+ expect(bridge.project.open).toHaveBeenCalledWith({
+ entryPoint: 'share-receive',
+ path: '/right',
+ pendingDeepLinkTarget: { kind: 'doc', path: 'docs/guide.md' },
+ target: 'new-window',
+ }),
+ );
+ });
+});
diff --git a/packages/app/src/components/ShareReceiveDialog.test.ts b/packages/app/src/components/ShareReceiveDialog.test.ts
index 17d70b193..db4a955b4 100644
--- a/packages/app/src/components/ShareReceiveDialog.test.ts
+++ b/packages/app/src/components/ShareReceiveDialog.test.ts
@@ -1,208 +1,8 @@
import { describe, expect, test } from 'bun:test';
-import SRC from './ShareReceiveDialog?raw';
-import METADATA_SRC from './share-metadata-rows?raw';
-describe('ShareReceiveDialog — module shape', () => {
- test('exports the named component', () => {
- expect(SRC).toMatch(/export\s+function\s+ShareReceiveDialog\s*\(/);
- });
-});
-
-describe('ShareReceiveDialog — wiring', () => {
- test('imports the Dialog primitives from @/components/ui/dialog', () => {
- expect(SRC).toContain("from '@/components/ui/dialog'");
- expect(SRC).toContain('DialogRoot');
- expect(SRC).toContain('DialogContent');
- expect(SRC).toContain('DialogHeader');
- expect(SRC).toContain('DialogTitle');
- expect(SRC).toContain('DialogBody');
- expect(SRC).toContain('DialogFooter');
- });
-
- test('imports the receive-flow helpers (no Q1 lookup wrapper)', () => {
- expect(SRC).toContain("from '@/lib/share/receive-flow'");
- expect(SRC).toContain('buildCloneUrl');
- expect(SRC).toContain('canonicalGitHubRemoteUrl');
- expect(SRC).toContain('formatReceiveLog');
- expect(SRC).toContain('mapValidationToToast');
- expect(SRC).toContain('presentReceiveError');
- });
-
- test('imports the consent-flow state machine helpers', () => {
- expect(SRC).toContain("from '@/lib/share/consent-flow'");
- expect(SRC).toContain('applyOkInitOutcome');
- expect(SRC).toContain('applyOpenOutcome');
- expect(SRC).toContain('initialConsentFlowState');
- expect(SRC).toContain('markInitializing');
- });
-
- test('imports the receive-store + singleton', () => {
- expect(SRC).toContain("from '@/lib/share/receive-store'");
- expect(SRC).toContain('shareReceiveStore');
- });
-
- test('uses useSyncExternalStore against the store snapshot/subscribe', () => {
- expect(SRC).toContain('useSyncExternalStore');
- expect(SRC).toContain('store.subscribe');
- expect(SRC).toContain('store.getSnapshot');
- });
-});
-
-describe('ShareReceiveDialog — main-resolved payload contract (US-006 seam)', () => {
- test('gates surfaces on launcher-consent and launcher-miss payload kinds', () => {
- expect(SRC).toContain("'launcher-consent'");
- expect(SRC).toContain("'launcher-miss'");
- });
-
- test('does NOT re-run selectCandidate / runQ1Lookup in the renderer', () => {
- expect(SRC).not.toMatch(/\brunQ1Lookup\s*\(/);
- expect(SRC).not.toMatch(/\bselectCandidate\s*\(/);
- expect(SRC).not.toMatch(/\basQ1BridgeDeps\s*\(/);
- });
-
- test('does NOT host the branch-switch surface (moved to ShareBranchSwitchDialog)', () => {
- expect(SRC).not.toContain("from '@/lib/share/branch-switch-flow'");
- expect(SRC).not.toMatch(/\bapplyBranchInfo\s*\(/);
- expect(SRC).not.toMatch(/\bapplyCheckoutOutcome\s*\(/);
- expect(SRC).not.toMatch(/\bmarkSwitching\s*\(/);
- expect(SRC).not.toMatch(/\bawaitBranchSwitched\s*\(/);
- expect(SRC).not.toMatch(/\bbridge\.project\.runCheckout\s*\(/);
- expect(SRC).not.toMatch(/\bbridge\.project\.fetchBranchInfo\s*\(/);
- expect(SRC).not.toContain('share-receive-branch-switch-dialog');
- expect(SRC).not.toContain('share-receive-doc-missing-dialog');
- });
-
- test('reads payload.share + payload.candidatePath directly (no resolveSharePayload wrapper)', () => {
- expect(SRC).not.toMatch(/\bresolveSharePayload\s*\(/);
- expect(SRC).toMatch(/share\?\.\.|share\?\.owner|share\?\.repo|share\.owner|share\.repo/);
- });
-});
-
-describe('ShareReceiveDialog — launcher-consent surface', () => {
- test('seeds the consent flow from payload.candidatePath + payload.share', () => {
- expect(SRC).toContain('initialConsentFlowState');
- expect(SRC).toContain('candidatePath:');
- expect(SRC).toContain('targetPath:');
- });
-
- test('threads payload.parentProjectName so the "(a worktree of <name>)" caption renders', () => {
- expect(SRC).toContain('parentProjectName');
- expect(SRC).toContain('share-receive-consent-parent');
- });
-
- test('Initialize button is disabled in the error phase (no-retry terminal)', () => {
- expect(SRC).toContain('data-testid="share-receive-consent-initialize"');
- expect(SRC).toContain("disabled={initializing || consentState.phase === 'error'}");
- });
-
- test('Initialize handler runs okInit then dispatches bridge.project.open with pendingDeepLinkTarget + pendingBranch', () => {
- expect(SRC).toMatch(/bridge\.project[\s\n.]+okInit\(/);
- expect(SRC).toMatch(/bridge\.project[\s\n.]+open\(/);
- const idx = SRC.indexOf('function handleConsentInitialize');
- expect(idx).toBeGreaterThan(-1);
- const endIdx = SRC.indexOf('function handleConsentCancel', idx);
- expect(endIdx).toBeGreaterThan(idx);
- const handlerBody = SRC.slice(idx, endIdx);
- expect(handlerBody).toContain('pendingDeepLinkTarget');
- expect(handlerBody).toContain('pendingBranch');
- });
-});
-
-describe('ShareReceiveDialog — launcher-miss surface', () => {
- test('renders Q2 clone + locate cards', () => {
- expect(SRC).toContain('data-testid="share-receive-dialog"');
- expect(SRC).toContain('data-testid="share-receive-clone"');
- expect(SRC).toContain('data-testid="share-receive-local"');
- });
-
- test('Q2 picker path uses bridge.dialog.openFolder + bridge.share.validateLocalFolder', () => {
- expect(SRC).toContain('bridge.dialog.openFolder()');
- expect(SRC).toContain('bridge.share.validateLocalFolder');
- });
-
- test('cloneController prop seam carries the streamlined auth + clone surface', () => {
- expect(SRC).toContain('cloneController');
- expect(SRC).toContain('ShareReceiveCloneController');
- expect(SRC).toContain('getAuthStatus');
- expect(SRC).toContain('runClone');
- expect(SRC).toContain('startSignIn');
- expect(SRC).toContain('toast.info');
- });
-
- test('Clone button disables until auth check resolves with authenticated', () => {
- expect(SRC).toMatch(/authStatus\?\.authenticated === true/);
- expect(SRC).toContain('Connect to clone');
- expect(SRC).toContain('Cloning...');
- expect(SRC).toContain('data-testid="share-receive-signin"');
- expect(SRC).toContain('data-testid="share-receive-auth-banner"');
- });
-});
-
-describe('ShareReceiveDialog — non-launcher kinds (toast-only)', () => {
- test('non-launcher payloads (unsupported-version / invalid) route through toast.error + store.dismiss', () => {
- expect(SRC).toContain("from 'sonner'");
- expect(SRC).toContain('toast.error');
- expect(SRC).toContain('store.dismiss');
- });
-});
-
-describe('ShareReceiveDialog — ShareMetadataRows (shared module)', () => {
- test('imports the shared ShareMetadataRows component', () => {
- expect(SRC).toContain("from '@/components/share-metadata-rows'");
- expect(SRC).toContain('ShareMetadataRows');
- });
-
- test('wires the dialog-scoped testids through the shared component props', () => {
- expect(SRC).toContain('testId="share-receive-metadata"');
- expect(SRC).toContain('branchTestId="share-receive-metadata-branch"');
- });
-
- test('shared module uses semantic <dl>/<dt>/<dd> markup for screen-reader friendliness', () => {
- expect(METADATA_SRC).toMatch(/<dl\s[^>]*data-testid=\{testId\}/);
- expect(METADATA_SRC).toContain('<dt ');
- expect(METADATA_SRC).toContain('<dd ');
- });
-
- test('shared module renders Repository / File / Branch labels via Lingui Trans', () => {
- expect(METADATA_SRC).toMatch(/<Trans>Repository<\/Trans>/);
- expect(METADATA_SRC).toMatch(/<Trans>File<\/Trans>/);
- expect(METADATA_SRC).toMatch(/<Trans>Branch<\/Trans>/);
- });
-
- test("shared module hides the Branch row for well-known defaults ('main' or 'master')", () => {
- expect(METADATA_SRC).toMatch(/DEFAULT_BRANCH_NAMES[\s\S]*?Set[\s\S]*?'main'[\s\S]*?'master'/);
- expect(METADATA_SRC).toContain("branch !== ''");
- expect(METADATA_SRC).toContain('!DEFAULT_BRANCH_NAMES.has(branch)');
- });
-
- test('shared module labels use w-20 shrink-0 font-mono uppercase tracking-wide text-xs', () => {
- expect(METADATA_SRC).toContain('w-20 shrink-0 font-mono uppercase tracking-wide text-xs');
- });
-
- test('shared module branch row guards a caller-supplied testid for downstream selection', () => {
- expect(METADATA_SRC).toContain('data-testid={branchTestId}');
- });
-});
-
-describe('ShareReceiveDialog — React Compiler discipline', () => {
- test('no React Compiler escape hatches', () => {
- expect(SRC).not.toMatch(/\bforwardRef\b/);
- expect(SRC).not.toMatch(/\bmemo\(/);
- expect(SRC).not.toMatch(/\buseCallback\b/);
- expect(SRC).not.toMatch(/\buseMemo\b/);
- });
-
- test('no inline style props (Tailwind only)', () => {
- expect(SRC).not.toMatch(/style=\{\{/);
- });
-
- test('no try/finally (BuildHIR rejects)', () => {
- expect(SRC).not.toMatch(/\}\s*finally\s*\{/);
- });
-
- test('remounts the inner dialog per payload via key (no manual reset effect)', () => {
- expect(SRC).toContain('ShareReceiveDialogInner');
- expect(SRC).toMatch(/<ShareReceiveDialogInner\s+key=\{remountKey\}/);
- expect(SRC).not.toMatch(/authProbeStartedRef\.current = false;\s*\},\s*\[payload\]\);/);
+describe('ShareReceiveDialog module', () => {
+ test('exports the named component', async () => {
+ const mod = await import('./ShareReceiveDialog');
+ expect(typeof mod.ShareReceiveDialog).toBe('function');
});
});
diff --git a/packages/app/src/components/SidebarSearchBar.dom.test.tsx b/packages/app/src/components/SidebarSearchBar.dom.test.tsx
index b20a88c21..402791091 100644
--- a/packages/app/src/components/SidebarSearchBar.dom.test.tsx
+++ b/packages/app/src/components/SidebarSearchBar.dom.test.tsx
@@ -1,116 +1,45 @@
-import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
-import { getParseHealth, resetParseHealth } from '@inkeep/open-knowledge-core';
+import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render, screen } from '@testing-library/react';
-import { ErrorBoundary } from 'react-error-boundary';
-import { onPillRenderError } from './SidebarSearchBar';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
-let shouldThrow = false;
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
-function MaybeThrowPill({ label }: { label: string }) {
- if (shouldThrow) {
- throw new Error(`MaybeThrowPill boom: ${label}`);
- }
- return (
- <button type="button" data-testid="pill">
- {label}
- </button>
- );
+async function renderSidebarSearchBar(onClick: () => void = () => {}) {
+ const { SidebarSearchBar } = await import('./SidebarSearchBar');
+ render(<SidebarSearchBar onClick={onClick} className="extra-class" />);
}
-describe('SidebarSearchBar ErrorBoundary (Tier-3 mount, QA-015)', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
- let consoleWarnSpy: ReturnType<typeof spyOn>;
+describe('SidebarSearchBar runtime behavior', () => {
+ afterEach(() => cleanup());
- beforeEach(() => {
- shouldThrow = false;
- resetParseHealth();
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
- consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ test('exports the component', async () => {
+ const mod = await import('./SidebarSearchBar');
+ expect(typeof mod.SidebarSearchBar).toBe('function');
});
- afterEach(() => {
- cleanup();
- consoleErrorSpy.mockRestore();
- consoleWarnSpy.mockRestore();
+ test('renders an accessible visible-label search button with the locked visual contract', async () => {
+ await renderSidebarSearchBar();
+
+ const button = screen.getByRole('button', { name: /Search/ });
+ expect(button.getAttribute('aria-label')).toBeNull();
+ expect(button.getAttribute('data-slot')).toBe('button');
+ expect(button.getAttribute('data-variant')).toBe('outline');
+ expect(button.getAttribute('data-telemetry-event')).toBe('ok.sidebar.search_pill.click');
+ expect(button.classList.contains('extra-class')).toBe(true);
+ expect(button.querySelector('svg')?.getAttribute('aria-hidden')).toBe('true');
+ expect(button.querySelector('span')?.textContent).toBe('Search');
+ expect(['⌘ K', 'Ctrl K']).toContain(button.querySelector('kbd')?.textContent);
});
- test('renders child when no throw — baseline (no boundary fallback, no observability emission)', () => {
- render(
- <ErrorBoundary fallbackRender={() => null} onError={onPillRenderError}>
- <MaybeThrowPill label="Search" />
- </ErrorBoundary>,
- );
- expect(screen.getByTestId('pill').textContent).toBe('Search');
- expect(getParseHealth().jsxRenderFailure.sidebarSearchPill).toBeUndefined();
- });
-
- test('renders null fallback on child throw + onPillRenderError fires the structured emission', () => {
- shouldThrow = true;
- render(
- <ErrorBoundary fallbackRender={() => null} onError={onPillRenderError}>
- <MaybeThrowPill label="Search" />
- </ErrorBoundary>,
- );
- expect(screen.queryByTestId('pill')).toBeNull();
- expect(getParseHealth().jsxRenderFailure.sidebarSearchPill).toBe(1);
- const sawStructuredEmission = consoleWarnSpy.mock.calls.some((call: unknown[]) => {
- const message = call[0];
- if (typeof message !== 'string') return false;
- try {
- const parsed = JSON.parse(message);
- return (
- parsed.event === 'jsx-render-failure' &&
- parsed.component === 'sidebarSearchPill' &&
- parsed.rawComponentName === 'sidebarSearchPill'
- );
- } catch {
- return false;
- }
- });
- expect(sawStructuredEmission).toBe(true);
- });
-
- test('sibling subtree outside the boundary stays mounted when the pill throws', () => {
- shouldThrow = true;
- render(
- <div>
- <ErrorBoundary fallbackRender={() => null} onError={onPillRenderError}>
- <MaybeThrowPill label="Search" />
- </ErrorBoundary>
- <div data-testid="sibling">FileTree + toolbar + ⌘K listener live here</div>
- </div>,
- );
- expect(screen.queryByTestId('pill')).toBeNull();
- expect(screen.getByTestId('sibling').textContent).toBe(
- 'FileTree + toolbar + ⌘K listener live here',
- );
- });
+ test('click delegates to the supplied handler', async () => {
+ const clicks: string[] = [];
+ await renderSidebarSearchBar(() => clicks.push('click'));
- test('resetKeys flip after a throw remounts the child for a fresh render attempt', () => {
- shouldThrow = true;
- const { rerender } = render(
- <ErrorBoundary
- fallbackRender={() => null}
- onError={onPillRenderError}
- resetKeys={['expanded']}
- >
- <MaybeThrowPill label="Search" />
- </ErrorBoundary>,
- );
- expect(screen.queryByTestId('pill')).toBeNull();
- expect(getParseHealth().jsxRenderFailure.sidebarSearchPill).toBe(1);
+ await userEvent.click(screen.getByRole('button', { name: /Search/ }));
- shouldThrow = false;
- rerender(
- <ErrorBoundary
- fallbackRender={() => null}
- onError={onPillRenderError}
- resetKeys={['collapsed']}
- >
- <MaybeThrowPill label="Search" />
- </ErrorBoundary>,
- );
- expect(screen.getByTestId('pill').textContent).toBe('Search');
- expect(getParseHealth().jsxRenderFailure.sidebarSearchPill).toBe(1);
+ expect(clicks).toEqual(['click']);
});
});
diff --git a/packages/app/src/components/SidebarSearchBar.test.ts b/packages/app/src/components/SidebarSearchBar.test.ts
index bc4dc3ae2..ad528df5a 100644
--- a/packages/app/src/components/SidebarSearchBar.test.ts
+++ b/packages/app/src/components/SidebarSearchBar.test.ts
@@ -1,7 +1,6 @@
import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
import { getParseHealth, resetParseHealth } from '@inkeep/open-knowledge-core';
import { onPillRenderError } from './SidebarSearchBar';
-import SRC from './SidebarSearchBar?raw';
describe('SidebarSearchBar module', () => {
test('exports the SidebarSearchBar component', async () => {
@@ -67,51 +66,3 @@ describe('onPillRenderError — Pattern C runtime observability emission', () =>
expect(payload.stack).toBe('\n at SidebarSearchBar\n at FileSidebar');
});
});
-
-describe('SidebarSearchBar source-level guards', () => {
- test('imports Button from \'@/components/ui/button\' and uses variant="outline"', () => {
- expect(SRC).toMatch(/import\s*\{\s*Button\s*\}\s*from\s*['"]@\/components\/ui\/button['"]/);
- expect(SRC).toMatch(/variant=['"]outline['"]/);
- });
-
- test('composition pins every visual class in the locked contract', () => {
- expect(SRC).toContain('rounded-lg');
- expect(SRC).toContain('h-9');
- expect(SRC).toContain('w-full');
- expect(SRC).toContain('justify-start');
- expect(SRC).toContain('gap-2');
- expect(SRC).toContain('px-3');
- expect(SRC).toContain('font-normal');
- expect(SRC).toContain('text-muted-foreground');
- });
-
- test("imports the Search icon from 'lucide-react' and renders it as decorative (aria-hidden)", () => {
- expect(SRC).toMatch(/import\s*\{\s*Search\s*\}\s*from\s*['"]lucide-react['"]/);
- expect(SRC).toMatch(/<Search\s+aria-hidden=['"]true['"]\s*\/>/);
- });
-
- test('renders the visible Search label with flex-1 text-left text-sm spans', () => {
- expect(SRC).toMatch(
- /<span\s+className=['"]flex-1\s+text-left\s+text-sm['"]>\s*<Trans>Search<\/Trans>\s*<\/span>/,
- );
- });
-
- test('button carries the stable telemetry selector value', () => {
- expect(SRC).toMatch(/data-telemetry-event=['"]ok\.sidebar\.search_pill\.click['"]/);
- });
-
- test('does NOT add aria-label to the button (visible label is the accessible name)', () => {
- expect(SRC).not.toMatch(/aria-label=['"]/);
- });
-
- test('does NOT import useCallback / useMemo / memo / forwardRef from react', () => {
- expect(SRC).not.toMatch(/import\s*\{[^}]*\buseCallback\b[^}]*\}\s*from\s*['"]react['"]/);
- expect(SRC).not.toMatch(/import\s*\{[^}]*\buseMemo\b[^}]*\}\s*from\s*['"]react['"]/);
- expect(SRC).not.toMatch(/import\s*\{[^}]*\bmemo\b[^}]*\}\s*from\s*['"]react['"]/);
- expect(SRC).not.toMatch(/import\s*\{[^}]*\bforwardRef\b[^}]*\}\s*from\s*['"]react['"]/);
- });
-
- test('does NOT import @testing-library/react (repo convention)', () => {
- expect(SRC).not.toMatch(/@testing-library\/react/);
- });
-});
diff --git a/packages/app/src/components/SyncStatusBadge.dom.test.tsx b/packages/app/src/components/SyncStatusBadge.dom.test.tsx
new file mode 100644
index 000000000..31493139a
--- /dev/null
+++ b/packages/app/src/components/SyncStatusBadge.dom.test.tsx
@@ -0,0 +1,272 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import type { GitSyncStatus } from '@/hooks/use-git-sync-status';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+mock.module('@lingui/core/macro', () => ({
+ t: renderLinguiTemplate,
+ plural: (value: number, options: { one: string; other: string }) =>
+ (value === 1 ? options.one : options.other).replace('#', String(value)),
+}));
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (
+ <>{(value === 1 ? one : other).replace('#', String(value))}</>
+ ),
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+let status: GitSyncStatus | null = null;
+let fetchError: 'network' | 'server' | null = null;
+let projectLocalConfig: { autoSync?: { enabled?: boolean | null } } | null = {
+ autoSync: { enabled: false },
+};
+let projectLocalSynced = true;
+const patches: unknown[] = [];
+
+mock.module('@/hooks/use-git-sync-status', () => ({
+ useGitSyncStatusDetailed: () => ({ status, fetchError }),
+}));
+
+mock.module('@/hooks/use-conflicts', () => ({
+ useConflicts: () => ({ conflicts: [{ file: 'docs/conflicted.md' }] }),
+}));
+
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ projectLocalConfig,
+ projectLocalSynced,
+ projectLocalBinding: {
+ patch: (patch: unknown) => {
+ patches.push(patch);
+ return { ok: true as const };
+ },
+ },
+ }),
+}));
+
+const baseStatus: GitSyncStatus = {
+ state: 'idle',
+ lastSyncUtc: null,
+ lastFetchUtc: null,
+ ahead: 0,
+ behind: 0,
+ conflictCount: 0,
+ hasRemote: true,
+ syncEnabled: true,
+ remote: { label: 'inkeep/open-knowledge', webUrl: 'https://github.com/inkeep/open-knowledge' },
+};
+
+async function renderBadge() {
+ const { SyncStatusBadge } = await import('./SyncStatusBadge');
+ render(
+ <TooltipProvider>
+ <SyncStatusBadge />
+ </TooltipProvider>,
+ );
+}
+
+async function openPopover() {
+ await userEvent.click(screen.getByRole('button', { name: /Sync status:/ }));
+ await waitFor(() => {
+ expect(screen.getByText('Repository')).toBeTruthy();
+ });
+}
+
+describe('SyncStatusBadge helper behavior', () => {
+ test('shouldDisableSyncSwitch only blocks before project-local sync or after push denial', async () => {
+ const { shouldDisableSyncSwitch } = await import('./SyncStatusBadge');
+
+ expect(shouldDisableSyncSwitch(false, 'allowed')).toBe(true);
+ expect(shouldDisableSyncSwitch(true, 'denied')).toBe(true);
+ expect(shouldDisableSyncSwitch(true, 'allowed')).toBe(false);
+ expect(shouldDisableSyncSwitch(true, 'unknown')).toBe(false);
+ expect(shouldDisableSyncSwitch(true, undefined)).toBe(false);
+ });
+
+ test('formats push-permission denial reasons into actionable copy', async () => {
+ const { formatPushPermissionDenied } = await import('./SyncStatusBadge');
+
+ expect(formatPushPermissionDenied('no-collaborator')).toBe(
+ "You don't have permission to push to this repo",
+ );
+ expect(formatPushPermissionDenied('private-no-access')).toBe(
+ "You don't have access to this private repo. Sign in with an account that does.",
+ );
+ expect(formatPushPermissionDenied('repo-not-found')).toBe(
+ 'Repository not found. It may have been renamed, deleted, or moved.',
+ );
+ expect(formatPushPermissionDenied(undefined)).toBe(
+ "You don't have permission to push to this repo",
+ );
+ });
+
+ test('collapses or labels push/pull sync errors by root cause', async () => {
+ const { computeSyncErrorLines } = await import('./SyncStatusBadge');
+
+ expect(computeSyncErrorLines({ pushErrorCode: 'auth-401' })).toEqual([
+ {
+ key: 'push',
+ direction: null,
+ message: 'GitHub authentication failed. Try signing in again.',
+ },
+ ]);
+ expect(
+ computeSyncErrorLines({
+ pushErrorCode: 'auth-401',
+ pullErrorCode: 'auth-401',
+ }),
+ ).toEqual([
+ {
+ key: 'sync',
+ direction: null,
+ message: 'GitHub authentication failed. Try signing in again.',
+ },
+ ]);
+ expect(
+ computeSyncErrorLines({
+ pushErrorCode: 'semantic-protected-branch',
+ pullErrorCode: 'auth-403',
+ }),
+ ).toEqual([
+ {
+ key: 'push',
+ direction: 'push',
+ message: 'The default branch is protected — pushes need a pull request.',
+ },
+ {
+ key: 'pull',
+ direction: 'pull',
+ message: "You don't have access to this repository.",
+ },
+ ]);
+ expect(
+ computeSyncErrorLines({
+ pushError: 'same raw failure',
+ pullError: 'same raw failure',
+ }),
+ ).toEqual([{ key: 'sync', direction: null, message: 'same raw failure' }]);
+ });
+
+ test('auth-no-credential copy directs the user to reconnect', async () => {
+ const { formatPullFailureCode, formatPushFailureCode, formatSyncFailureCode } = await import(
+ './SyncStatusBadge'
+ );
+
+ for (const format of [formatSyncFailureCode, formatPushFailureCode, formatPullFailureCode]) {
+ expect(format('auth-no-credential')).toMatch(/reconnect/i);
+ }
+ });
+
+ test('only token-invalid unknown push-permission probes offer sign-in again', async () => {
+ const { shouldOfferSignInAgain } = await import('./SyncStatusBadge');
+
+ expect(shouldOfferSignInAgain({ checkStatus: 'unknown', unknownError: 'token-invalid' })).toBe(
+ true,
+ );
+ expect(shouldOfferSignInAgain({ checkStatus: 'denied' })).toBe(false);
+ expect(shouldOfferSignInAgain({ checkStatus: 'unknown', unknownError: 'network' })).toBe(false);
+ expect(shouldOfferSignInAgain(undefined)).toBe(false);
+ });
+});
+
+describe('SyncStatusBadge runtime behavior', () => {
+ afterEach(() => {
+ cleanup();
+ status = null;
+ fetchError = null;
+ projectLocalConfig = { autoSync: { enabled: false } };
+ projectLocalSynced = true;
+ patches.length = 0;
+ });
+
+ test('exports the SyncStatusBadge component', async () => {
+ const mod = await import('./SyncStatusBadge');
+ expect(typeof mod.SyncStatusBadge).toBe('function');
+ });
+
+ test('renders nothing before status loads unless a fetch error exists', async () => {
+ status = null;
+ fetchError = null;
+ await renderBadge();
+
+ expect(screen.queryByRole('button')).toBeNull();
+ });
+
+ test.each([
+ ['disabled without paused reason', { state: 'disabled', pausedReason: undefined }],
+ ['dormant without a remote', { state: 'dormant', hasRemote: false }],
+ ] as const)('hides %s', async (_label, override) => {
+ status = { ...baseStatus, ...override } as GitSyncStatus;
+ await renderBadge();
+
+ expect(screen.queryByRole('button')).toBeNull();
+ });
+
+ test.each([
+ ['auth-error', { state: 'auth-error', syncEnabled: true }],
+ ['conflict', { state: 'conflict', conflictCount: 2, syncEnabled: true }],
+ ['offline', { state: 'offline', syncEnabled: true }],
+ ['dormant with remote', { state: 'dormant', hasRemote: true, syncEnabled: false }],
+ [
+ 'disabled with paused reason',
+ { state: 'disabled', pausedReason: 'protected-branch', syncEnabled: false },
+ ],
+ ] as const)('keeps attention-worthy state visible: %s', async (_label, override) => {
+ status = { ...baseStatus, ...override } as GitSyncStatus;
+ await renderBadge();
+
+ expect(screen.getByRole('button', { name: /Sync status:/ })).toBeTruthy();
+ });
+
+ test('paused disabled state opens details explaining why sync stopped', async () => {
+ status = {
+ ...baseStatus,
+ state: 'disabled',
+ syncEnabled: false,
+ pausedReason: 'protected-branch',
+ };
+ await renderBadge();
+ await openPopover();
+
+ expect(screen.getByText('Protected branch — cannot push')).toBeTruthy();
+ });
+
+ test('popover switch checked state reads local config, not server syncEnabled', async () => {
+ status = { ...baseStatus, state: 'idle', syncEnabled: false };
+ projectLocalConfig = { autoSync: { enabled: true } };
+ await renderBadge();
+ await openPopover();
+
+ const toggle = screen.getByRole('switch', { name: 'Disable sync' });
+ expect(toggle.getAttribute('aria-checked')).toBe('true');
+ });
+
+ test('popover switch is disabled until the project-local config has synced', async () => {
+ status = { ...baseStatus, state: 'idle', syncEnabled: false };
+ projectLocalConfig = { autoSync: { enabled: false } };
+ projectLocalSynced = false;
+ await renderBadge();
+ await openPopover();
+
+ const toggle = screen.getByRole('switch', { name: 'Enable sync' }) as HTMLButtonElement;
+ expect(toggle.disabled).toBe(true);
+ });
+
+ test('off to on opens confirmation before patching project-local config', async () => {
+ status = { ...baseStatus, state: 'idle', syncEnabled: false };
+ projectLocalConfig = { autoSync: { enabled: false } };
+ await renderBadge();
+ await openPopover();
+
+ await userEvent.click(screen.getByRole('switch', { name: 'Enable sync' }));
+ expect(patches).toEqual([]);
+
+ await userEvent.click(screen.getByRole('button', { name: 'Enable auto-sync' }));
+ expect(patches).toEqual([{ autoSync: { enabled: true } }]);
+ });
+});
diff --git a/packages/app/src/components/SyncStatusBadge.test.ts b/packages/app/src/components/SyncStatusBadge.test.ts
deleted file mode 100644
index 0578c7d48..000000000
--- a/packages/app/src/components/SyncStatusBadge.test.ts
+++ /dev/null
@@ -1,259 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import { SYNC_ERROR_CODES } from '@inkeep/open-knowledge-core';
-
-describe('SyncStatusBadge module', () => {
- test('exports the SyncStatusBadge component', async () => {
- const mod = await import('./SyncStatusBadge');
- expect(typeof mod.SyncStatusBadge).toBe('function');
- });
-
- test('exports the helper functions consumed by the settings mirror', async () => {
- const mod = await import('./SyncStatusBadge');
- expect(typeof mod.formatPausedReason).toBe('function');
- expect(typeof mod.formatPushPermissionDenied).toBe('function');
- expect(typeof mod.formatPushFailureCode).toBe('function');
- expect(typeof mod.formatPullFailureCode).toBe('function');
- expect(typeof mod.formatSyncFailureCode).toBe('function');
- expect(typeof mod.computeSyncErrorLines).toBe('function');
- expect(typeof mod.shouldDisableSyncSwitch).toBe('function');
- expect(typeof mod.shouldOfferSignInAgain).toBe('function');
- });
-});
-
-describe('shouldDisableSyncSwitch — truth table', () => {
- test('disabled when projectLocalSynced is false (cold start)', async () => {
- const { shouldDisableSyncSwitch } = await import('./SyncStatusBadge');
- expect(shouldDisableSyncSwitch(false, undefined)).toBe(true);
- expect(shouldDisableSyncSwitch(undefined, undefined)).toBe(true);
- expect(shouldDisableSyncSwitch(false, 'allowed')).toBe(true);
- });
-
- test('disabled when the push-permission probe resolves denied', async () => {
- const { shouldDisableSyncSwitch } = await import('./SyncStatusBadge');
- expect(shouldDisableSyncSwitch(true, 'denied')).toBe(true);
- });
-
- test('enabled when projectLocalSynced and the probe is allowed', async () => {
- const { shouldDisableSyncSwitch } = await import('./SyncStatusBadge');
- expect(shouldDisableSyncSwitch(true, 'allowed')).toBe(false);
- });
-
- test('enabled when projectLocalSynced and probe is undefined / unknown (read+write parity invariant)', async () => {
- const { shouldDisableSyncSwitch } = await import('./SyncStatusBadge');
- expect(shouldDisableSyncSwitch(true, undefined)).toBe(false);
- expect(shouldDisableSyncSwitch(true, 'unknown')).toBe(false);
- });
-});
-
-describe('formatPushPermissionDenied — branch coverage', () => {
- test('no-collaborator returns the push-permission copy', async () => {
- const { formatPushPermissionDenied } = await import('./SyncStatusBadge');
- expect(formatPushPermissionDenied('no-collaborator')).toBe(
- "You don't have permission to push to this repo",
- );
- });
-
- test('private-no-access returns the sign-in-with-other-account copy', async () => {
- const { formatPushPermissionDenied } = await import('./SyncStatusBadge');
- expect(formatPushPermissionDenied('private-no-access')).toBe(
- "You don't have access to this private repo. Sign in with an account that does.",
- );
- });
-
- test('repo-not-found returns the renamed-deleted-moved copy', async () => {
- const { formatPushPermissionDenied } = await import('./SyncStatusBadge');
- expect(formatPushPermissionDenied('repo-not-found')).toBe(
- 'Repository not found. It may have been renamed, deleted, or moved.',
- );
- });
-
- test('undefined defaults to the push-permission copy', async () => {
- const { formatPushPermissionDenied } = await import('./SyncStatusBadge');
- expect(formatPushPermissionDenied(undefined)).toBe(
- "You don't have permission to push to this repo",
- );
- });
-});
-
-describe('formatPushFailureCode — code-to-localized-string mapping', () => {
- test('every bounded enum value produces a non-empty string', async () => {
- const { formatPushFailureCode } = await import('./SyncStatusBadge');
- const codes = [
- 'auth-403',
- 'auth-401',
- 'auth-scope-mismatch',
- 'semantic-protected-branch',
- ] as const;
- for (const code of codes) {
- const out = formatPushFailureCode(code);
- expect(typeof out).toBe('string');
- expect(out.length).toBeGreaterThan(0);
- }
- });
-
- test('different codes produce different strings (no accidental collapse)', async () => {
- const { formatPushFailureCode } = await import('./SyncStatusBadge');
- const strings = new Set([
- formatPushFailureCode('auth-403'),
- formatPushFailureCode('auth-401'),
- formatPushFailureCode('auth-scope-mismatch'),
- formatPushFailureCode('semantic-protected-branch'),
- ]);
- expect(strings.size).toBe(4);
- });
-});
-
-describe('formatSyncFailureCode — neutral collapsed copy', () => {
- test('every bounded enum value produces a non-empty string', async () => {
- const { formatSyncFailureCode } = await import('./SyncStatusBadge');
- for (const code of SYNC_ERROR_CODES) {
- const out = formatSyncFailureCode(code);
- expect(typeof out).toBe('string');
- expect(out.length).toBeGreaterThan(0);
- }
- });
-
- test('auth-403 copy is direction-agnostic (not the push-only framing)', async () => {
- const { formatSyncFailureCode, formatPushFailureCode, formatPullFailureCode } = await import(
- './SyncStatusBadge'
- );
- expect(formatSyncFailureCode('auth-403')).not.toBe(formatPushFailureCode('auth-403'));
- expect(formatSyncFailureCode('auth-403')).toBe(formatPullFailureCode('auth-403'));
- });
-
- test('auth-no-credential copy directs the user to reconnect (all three formatters)', async () => {
- const { formatSyncFailureCode, formatPushFailureCode, formatPullFailureCode } = await import(
- './SyncStatusBadge'
- );
- for (const fmt of [formatSyncFailureCode, formatPushFailureCode, formatPullFailureCode]) {
- expect(fmt('auth-no-credential')).toMatch(/reconnect/i);
- }
- });
-});
-
-describe('computeSyncErrorLines — collapse + label truth table', () => {
- test('no errors → no lines', async () => {
- const { computeSyncErrorLines } = await import('./SyncStatusBadge');
- expect(computeSyncErrorLines({})).toEqual([]);
- });
-
- test('push-only → single unlabeled line with push copy', async () => {
- const { computeSyncErrorLines, formatPushFailureCode } = await import('./SyncStatusBadge');
- const lines = computeSyncErrorLines({ pushErrorCode: 'semantic-protected-branch' });
- expect(lines).toEqual([
- { key: 'push', direction: null, message: formatPushFailureCode('semantic-protected-branch') },
- ]);
- });
-
- test('pull-only (raw) → single unlabeled line with the raw message', async () => {
- const { computeSyncErrorLines } = await import('./SyncStatusBadge');
- const lines = computeSyncErrorLines({ pullError: 'Sync paused — local changes conflict.' });
- expect(lines).toEqual([
- { key: 'pull', direction: null, message: 'Sync paused — local changes conflict.' },
- ]);
- });
-
- test('same code on both legs → one collapsed, unlabeled, neutral line', async () => {
- const { computeSyncErrorLines, formatSyncFailureCode } = await import('./SyncStatusBadge');
- const lines = computeSyncErrorLines({ pushErrorCode: 'auth-401', pullErrorCode: 'auth-401' });
- expect(lines).toEqual([
- { key: 'sync', direction: null, message: formatSyncFailureCode('auth-401') },
- ]);
- });
-
- test('identical raw message on both legs → one collapsed line', async () => {
- const { computeSyncErrorLines } = await import('./SyncStatusBadge');
- const lines = computeSyncErrorLines({
- pushError: 'Network unreachable',
- pullError: 'Network unreachable',
- });
- expect(lines).toEqual([{ key: 'sync', direction: null, message: 'Network unreachable' }]);
- });
-
- test('different codes → two lines, each labeled with its direction', async () => {
- const { computeSyncErrorLines, formatPushFailureCode, formatPullFailureCode } = await import(
- './SyncStatusBadge'
- );
- const lines = computeSyncErrorLines({
- pushErrorCode: 'semantic-protected-branch',
- pullErrorCode: 'auth-403',
- });
- expect(lines).toEqual([
- {
- key: 'push',
- direction: 'push',
- message: formatPushFailureCode('semantic-protected-branch'),
- },
- { key: 'pull', direction: 'pull', message: formatPullFailureCode('auth-403') },
- ]);
- });
-
- test('coded push + raw pull → treated as different, both labeled', async () => {
- const { computeSyncErrorLines, formatPushFailureCode } = await import('./SyncStatusBadge');
- const lines = computeSyncErrorLines({
- pushErrorCode: 'auth-401',
- pullError: 'Could not detect conflict files',
- });
- expect(lines).toEqual([
- { key: 'push', direction: 'push', message: formatPushFailureCode('auth-401') },
- { key: 'pull', direction: 'pull', message: 'Could not detect conflict files' },
- ]);
- });
-});
-
-describe('formatPausedReason — push-permission case', () => {
- test('maps no-push-permission to the push-permission copy', async () => {
- const { formatPausedReason } = await import('./SyncStatusBadge');
- expect(formatPausedReason('no-push-permission')).toBe(
- "You don't have permission to push to this repo",
- );
- });
-
- test('falls back to the raw reason for unmapped values', async () => {
- const { formatPausedReason } = await import('./SyncStatusBadge');
- expect(formatPausedReason('totally-unmapped-reason')).toBe('totally-unmapped-reason');
- });
-});
-
-describe('shouldOfferSignInAgain — probe-401 truth table', () => {
- test('returns true only on unknown/token-invalid', async () => {
- const { shouldOfferSignInAgain } = await import('./SyncStatusBadge');
- expect(shouldOfferSignInAgain({ checkStatus: 'unknown', unknownError: 'token-invalid' })).toBe(
- true,
- );
- });
-
- test('returns false on unknown with any other error class', async () => {
- const { shouldOfferSignInAgain } = await import('./SyncStatusBadge');
- expect(shouldOfferSignInAgain({ checkStatus: 'unknown', unknownError: 'network' })).toBe(false);
- expect(shouldOfferSignInAgain({ checkStatus: 'unknown', unknownError: 'timeout' })).toBe(false);
- expect(shouldOfferSignInAgain({ checkStatus: 'unknown', unknownError: 'rate-limit' })).toBe(
- false,
- );
- expect(
- shouldOfferSignInAgain({ checkStatus: 'unknown', unknownError: 'malformed-response' }),
- ).toBe(false);
- });
-
- test('returns false on unknown without an unknownError field', async () => {
- const { shouldOfferSignInAgain } = await import('./SyncStatusBadge');
- expect(shouldOfferSignInAgain({ checkStatus: 'unknown' })).toBe(false);
- });
-
- test("returns false on 'denied' — denied has its own affordance, NOT Sign in again", async () => {
- const { shouldOfferSignInAgain } = await import('./SyncStatusBadge');
- expect(shouldOfferSignInAgain({ checkStatus: 'denied', deniedReason: 'no-collaborator' })).toBe(
- false,
- );
- });
-
- test("returns false on 'allowed' (no payload to misinterpret)", async () => {
- const { shouldOfferSignInAgain } = await import('./SyncStatusBadge');
- expect(shouldOfferSignInAgain({ checkStatus: 'allowed' })).toBe(false);
- });
-
- test('returns false on undefined push-permission (read+write parity)', async () => {
- const { shouldOfferSignInAgain } = await import('./SyncStatusBadge');
- expect(shouldOfferSignInAgain(undefined)).toBe(false);
- });
-});
diff --git a/packages/app/src/components/TrashFailureModal.dom.test.tsx b/packages/app/src/components/TrashFailureModal.dom.test.tsx
new file mode 100644
index 000000000..4c178d573
--- /dev/null
+++ b/packages/app/src/components/TrashFailureModal.dom.test.tsx
@@ -0,0 +1,161 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+import { expectVisualClassTokens } from '@/test-utils/visual-contract';
+import type { TrashFailedTarget } from './TrashFailureModal';
+
+mock.module('@lingui/core/macro', () => ({
+ plural: (
+ count: number,
+ forms: {
+ one?: string;
+ other: string;
+ },
+ ) => (count === 1 ? (forms.one ?? forms.other) : forms.other).replace('#', String(count)),
+ t: renderLinguiTemplate,
+}));
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+const fileTarget: TrashFailedTarget = {
+ kind: 'file',
+ path: 'notes/foo.md',
+ name: 'foo.md',
+ reason: 'permission-denied',
+ detail: 'Operation not permitted',
+};
+
+const folderTarget: TrashFailedTarget = {
+ kind: 'folder',
+ path: 'notes/archive',
+ name: 'archive',
+ reason: 'path-escape',
+};
+
+async function renderTrashFailureModal({
+ failedTargets = [fileTarget],
+ isSubmitting = false,
+}: {
+ failedTargets?: ReadonlyArray<TrashFailedTarget>;
+ isSubmitting?: boolean;
+} = {}) {
+ const [{ Dialog }, { TrashFailureModal }] = await Promise.all([
+ import('@/components/ui/dialog'),
+ import('./TrashFailureModal'),
+ ]);
+ const onCancel = mock(() => {});
+ const onRetry = mock(() => {});
+ const onDeletePermanently = mock(() => {});
+
+ render(
+ <Dialog open={true}>
+ <TrashFailureModal
+ failedTargets={failedTargets}
+ isSubmitting={isSubmitting}
+ onCancel={onCancel}
+ onDeletePermanently={onDeletePermanently}
+ onRetry={onRetry}
+ />
+ </Dialog>,
+ );
+
+ return { onCancel, onDeletePermanently, onRetry };
+}
+
+describe('TrashFailureModal runtime behavior', () => {
+ afterEach(() => cleanup());
+
+ test('exports the modal component and helper functions', async () => {
+ const mod = await import('./TrashFailureModal');
+ expect(typeof mod.TrashFailureModal).toBe('function');
+ expect(typeof mod.formatTrashFailureDetail).toBe('function');
+ expect(typeof mod.coerceTrashFailureReason).toBe('function');
+ });
+
+ test('renders the single-target VSCode-parity copy and routes each action', async () => {
+ const { onCancel, onDeletePermanently, onRetry } = await renderTrashFailureModal();
+
+ const dialog = screen.getByRole('dialog', { name: "Couldn't move to Trash" });
+ expect(dialog.textContent).toContain('Could not move "foo.md" to the Trash.');
+ expect(dialog.textContent).toContain('Do you want to permanently delete instead?');
+ expect(dialog.textContent).toContain('Reason: Permission denied (Operation not permitted)');
+ expect(screen.queryByTestId('trash-failure-modal-target')).toBeNull();
+
+ const cancel = screen.getByTestId('trash-failure-modal-cancel');
+ const retry = screen.getByTestId('trash-failure-modal-retry');
+ const deletePermanently = screen.getByTestId('trash-failure-modal-delete-permanently');
+
+ expect(cancel.textContent).toBe('Cancel');
+ expect(retry.textContent).toBe('Retry');
+ expect(deletePermanently.textContent).toBe('Delete Permanently');
+ expect(cancel.compareDocumentPosition(retry) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
+ expect(
+ retry.compareDocumentPosition(deletePermanently) & Node.DOCUMENT_POSITION_FOLLOWING,
+ ).toBeTruthy();
+
+ expect(cancel.getAttribute('data-variant')).toBe('outline');
+ expect(retry.getAttribute('data-variant')).toBe('outline');
+ expect(deletePermanently.getAttribute('data-variant')).toBe('destructive');
+ expectVisualClassTokens(cancel.className, ['font-mono']);
+ expectVisualClassTokens(retry.className, ['font-mono']);
+
+ await userEvent.click(cancel);
+ await userEvent.click(retry);
+ await userEvent.click(deletePermanently);
+
+ expect(onCancel).toHaveBeenCalledTimes(1);
+ expect(onRetry).toHaveBeenCalledTimes(1);
+ expect(onDeletePermanently).toHaveBeenCalledTimes(1);
+ });
+
+ test('disables every action while submitting and shows progress copy', async () => {
+ const { onCancel, onDeletePermanently, onRetry } = await renderTrashFailureModal({
+ isSubmitting: true,
+ });
+
+ const cancel = screen.getByTestId('trash-failure-modal-cancel') as HTMLButtonElement;
+ const retry = screen.getByTestId('trash-failure-modal-retry') as HTMLButtonElement;
+ const deletePermanently = screen.getByTestId(
+ 'trash-failure-modal-delete-permanently',
+ ) as HTMLButtonElement;
+
+ expect(cancel.disabled).toBe(true);
+ expect(retry.disabled).toBe(true);
+ expect(deletePermanently.disabled).toBe(true);
+ expect(retry.textContent).toContain('Retrying');
+ expect(deletePermanently.textContent).toContain('Deleting');
+
+ await userEvent.click(cancel);
+ await userEvent.click(retry);
+ await userEvent.click(deletePermanently);
+
+ expect(onCancel).not.toHaveBeenCalled();
+ expect(onRetry).not.toHaveBeenCalled();
+ expect(onDeletePermanently).not.toHaveBeenCalled();
+ });
+
+ test('renders multi-target failures as one aggregated list with one destructive action', async () => {
+ await renderTrashFailureModal({
+ failedTargets: [fileTarget, folderTarget],
+ });
+
+ const dialog = screen.getByRole('dialog', { name: "Couldn't move to Trash" });
+ expect(dialog.textContent).toContain(
+ '2 items could not be moved to the Trash. Do you want to permanently delete instead?',
+ );
+
+ const targets = screen.getAllByTestId('trash-failure-modal-target');
+ expect(targets).toHaveLength(2);
+ expect(within(targets[0]).getByText('foo.md')).toBeTruthy();
+ expect(
+ within(targets[0]).getByText('Reason: Permission denied (Operation not permitted)'),
+ ).toBeTruthy();
+ expect(within(targets[1]).getByText('archive/')).toBeTruthy();
+ expect(within(targets[1]).getByText('Reason: Path resolves outside project')).toBeTruthy();
+ expect(screen.getAllByRole('button', { name: 'Delete Permanently' })).toHaveLength(1);
+ });
+});
diff --git a/packages/app/src/components/TrashFailureModal.test.ts b/packages/app/src/components/TrashFailureModal.test.ts
index 11ba579f9..f6d61a2d9 100644
--- a/packages/app/src/components/TrashFailureModal.test.ts
+++ b/packages/app/src/components/TrashFailureModal.test.ts
@@ -1,139 +1,22 @@
import { describe, expect, test } from 'bun:test';
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
import {
+ coerceTrashFailureReason,
formatTrashFailureDetail,
type TrashFailedTarget,
TrashFailureModal,
} from './TrashFailureModal';
-const SRC = readFileSync(join(__dirname, 'TrashFailureModal.tsx'), 'utf8');
-
-describe('TrashFailureModal — exports', () => {
- test('exports the modal component + detail formatter + types', () => {
+describe('TrashFailureModal exports', () => {
+ test('exports the modal component and runtime helpers', () => {
expect(typeof TrashFailureModal).toBe('function');
expect(typeof formatTrashFailureDetail).toBe('function');
+ expect(typeof coerceTrashFailureReason).toBe('function');
});
});
-describe('TrashFailureModal — VSCode-parity copy (FR20)', () => {
- test('title is a short noun phrase fit for DialogTitle leading-none', () => {
- expect(SRC).toMatch(/<DialogTitle>\s*<Trans>Couldn't move to Trash<\/Trans>\s*<\/DialogTitle>/);
- });
-
- test('description preserves VSCode question phrasing', () => {
- expect(SRC).toContain('Do you want to permanently delete instead?');
- });
-
- test('Delete Permanently button label present and exact', () => {
- expect(SRC).toContain('<Trans>Delete Permanently</Trans>');
- });
-
- test('Retry button label present and exact', () => {
- expect(SRC).toContain('<Trans>Retry</Trans>');
- });
-
- test('Cancel button label present and exact', () => {
- expect(SRC).toMatch(/>\s*Cancel\s*</);
- });
-});
-
-describe('TrashFailureModal — button wiring + ordering', () => {
- test('button order in source is Cancel, Retry, Delete Permanently (left → right via flex-row)', () => {
- const cancel = SRC.indexOf('data-testid="trash-failure-modal-cancel"');
- const retry = SRC.indexOf('data-testid="trash-failure-modal-retry"');
- const del = SRC.indexOf('data-testid="trash-failure-modal-delete-permanently"');
- expect(cancel).toBeGreaterThan(-1);
- expect(retry).toBeGreaterThan(cancel);
- expect(del).toBeGreaterThan(retry);
- });
-
- test('Delete Permanently button uses destructive variant', () => {
- const idx = SRC.indexOf('data-testid="trash-failure-modal-delete-permanently"');
- expect(idx).toBeGreaterThan(-1);
- const buttonOpen = SRC.lastIndexOf('<Button', idx);
- expect(buttonOpen).toBeGreaterThan(-1);
- const buttonBlock = SRC.slice(buttonOpen, idx);
- expect(buttonBlock).toContain('variant="destructive"');
- });
-
- test('Retry button uses outline variant', () => {
- const idx = SRC.indexOf('data-testid="trash-failure-modal-retry"');
- const buttonOpen = SRC.lastIndexOf('<Button', idx);
- const buttonBlock = SRC.slice(buttonOpen, idx);
- expect(buttonBlock).toContain('variant="outline"');
- });
-
- test('Cancel button uses outline variant (safety-hierarchy parity with sibling DeleteConfirmation)', () => {
- const idx = SRC.indexOf('data-testid="trash-failure-modal-cancel"');
- const buttonOpen = SRC.lastIndexOf('<Button', idx);
- const buttonBlock = SRC.slice(buttonOpen, idx);
- expect(buttonBlock).toContain('variant="outline"');
- expect(buttonBlock).toContain('font-mono uppercase');
- });
-
- test('Retry button has font-mono uppercase class (parity with destructive primary)', () => {
- const idx = SRC.indexOf('data-testid="trash-failure-modal-retry"');
- const buttonOpen = SRC.lastIndexOf('<Button', idx);
- const buttonBlock = SRC.slice(buttonOpen, idx);
- expect(buttonBlock).toContain('font-mono uppercase');
- });
-
- test('each button routes to the matching callback prop', () => {
- const cancelIdx = SRC.indexOf('data-testid="trash-failure-modal-cancel"');
- expect(SRC.slice(SRC.lastIndexOf('<Button', cancelIdx), cancelIdx)).toContain(
- 'onClick={onCancel}',
- );
-
- const retryIdx = SRC.indexOf('data-testid="trash-failure-modal-retry"');
- expect(SRC.slice(SRC.lastIndexOf('<Button', retryIdx), retryIdx)).toContain(
- 'onClick={onRetry}',
- );
-
- const delIdx = SRC.indexOf('data-testid="trash-failure-modal-delete-permanently"');
- expect(SRC.slice(SRC.lastIndexOf('<Button', delIdx), delIdx)).toContain(
- 'onClick={onDeletePermanently}',
- );
- });
-
- test('all three buttons disable while isSubmitting', () => {
- const occurrences = SRC.match(/disabled=\{isSubmitting\}/g) ?? [];
- expect(occurrences.length).toBe(3);
- });
-
- test('Retry button shows Retrying spinner copy when isSubmitting', () => {
- expect(SRC).toMatch(/animate-spin"\s*\/>\s*<Trans>Retrying/);
- });
-
- test('Delete Permanently button shows Deleting spinner copy when isSubmitting', () => {
- expect(SRC).toMatch(/animate-spin"\s*\/>\s*<Trans>Deleting/);
- });
-});
-
-describe('TrashFailureModal — multi-target aggregation', () => {
- test('renders a DialogBody list when failedTargets.length > 1', () => {
- expect(SRC).toContain('const isMulti = failedTargets.length > 1;');
- expect(SRC).toMatch(/\{isMulti \?\s*\(\s*<DialogBody>/);
- });
-
- test('maps each failedTarget into a list item with stable key + testid', () => {
- expect(SRC).toContain('failedTargets.map((target)');
- expect(SRC).toContain('key={target.path}');
- expect(SRC).toContain('data-testid="trash-failure-modal-target"');
- });
-
- test('single-target branch renders inline description (no DialogBody list)', () => {
- expect(SRC).toMatch(/Could not move "\$\{targetName\}"/);
- });
-
- test('Delete Permanently applies to the aggregated list (caller resolves; modal is pure)', () => {
- expect(SRC).not.toMatch(/onDeletePermanently\(target/);
- });
-});
-
-describe('TrashFailureModal — detail formatting', () => {
- test('formats reason + detail when detail present', () => {
+describe('TrashFailureModal detail formatting', () => {
+ test('formats reason and detail when OS detail is present', () => {
const target: TrashFailedTarget = {
kind: 'file',
path: 'notes/foo.md',
@@ -146,7 +29,7 @@ describe('TrashFailureModal — detail formatting', () => {
);
});
- test('formats reason without detail when detail absent', () => {
+ test('formats reason without detail when OS detail is absent', () => {
const target: TrashFailedTarget = {
kind: 'file',
path: 'foo.md',
@@ -156,7 +39,7 @@ describe('TrashFailureModal — detail formatting', () => {
expect(formatTrashFailureDetail(target)).toBe('Reason: File not found');
});
- test('maps every TrashFailureReason to a non-empty user-facing label', () => {
+ test('maps every known trash failure reason to a non-empty user-facing label', () => {
const reasons = ['not-found', 'permission-denied', 'system-error', 'path-escape'] as const;
for (const reason of reasons) {
const out = formatTrashFailureDetail({
@@ -169,47 +52,15 @@ describe('TrashFailureModal — detail formatting', () => {
expect(out.length).toBeGreaterThan('Reason: '.length);
}
});
-
- test('appends slash to folder display name (single-target description)', () => {
- expect(SRC).toContain("target.kind === 'folder'");
- expect(SRC).toMatch(/target\.name\}\/`/);
- });
-});
-
-describe('TrashFailureModal — shadcn Dialog primitives', () => {
- test('imports DialogContent / Title / Description / Body / Footer from shared dialog primitive', () => {
- expect(SRC).toMatch(/from '@\/components\/ui\/dialog'/);
- expect(SRC).toContain('DialogBody');
- expect(SRC).toContain('DialogContent');
- expect(SRC).toContain('DialogDescription');
- expect(SRC).toContain('DialogFooter');
- expect(SRC).toContain('DialogTitle');
- });
-
- test('uses Button primitive (sibling DeleteConfirmationDialog convention)', () => {
- expect(SRC).toMatch(/from '@\/components\/ui\/button'/);
- });
});
-describe('TrashFailureModal — TrashFailureReason union', () => {
- test('union matches the IPC TrashItemReason from packages/desktop/src/main/ipc-handlers.ts', () => {
- expect(SRC).toContain(
- "type TrashFailureReason = 'not-found' | 'permission-denied' | 'system-error' | 'path-escape';",
- );
- });
-
- test('coerceTrashFailureReason coerces unknown IPC reasons to system-error (R7 trust boundary)', () => {
- expect(SRC).toMatch(
- /export function coerceTrashFailureReason\(reason: unknown\): TrashFailureReason/,
- );
- expect(SRC).toContain('TRASH_FAILURE_REASONS');
- expect(SRC).toMatch(/: 'system-error'/);
- });
-
- test('drift warning JSDoc explicitly names the three sibling bridge surfaces to keep in lockstep', () => {
- expect(SRC).toContain('DRIFT WARNING');
- expect(SRC).toContain('packages/desktop/src/shared/bridge-contract.ts');
- expect(SRC).toContain('packages/core/src/desktop-bridge.ts');
- expect(SRC).toContain('packages/app/src/lib/desktop-bridge-types.ts');
+describe('TrashFailureModal IPC reason coercion', () => {
+ test('passes through known IPC reasons and coerces unknown values to system-error', () => {
+ expect(coerceTrashFailureReason('not-found')).toBe('not-found');
+ expect(coerceTrashFailureReason('permission-denied')).toBe('permission-denied');
+ expect(coerceTrashFailureReason('system-error')).toBe('system-error');
+ expect(coerceTrashFailureReason('path-escape')).toBe('path-escape');
+ expect(coerceTrashFailureReason('future-desktop-reason')).toBe('system-error');
+ expect(coerceTrashFailureReason(null)).toBe('system-error');
});
});
diff --git a/packages/app/src/components/empty-state/AgentHandoffGrid.dom.test.tsx b/packages/app/src/components/empty-state/AgentHandoffGrid.dom.test.tsx
new file mode 100644
index 000000000..36632de95
--- /dev/null
+++ b/packages/app/src/components/empty-state/AgentHandoffGrid.dom.test.tsx
@@ -0,0 +1,127 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import type { HandoffTarget, InstallState, TargetData } from '@inkeep/open-knowledge-core';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+const states: Partial<Record<HandoffTarget, InstallState>> = {};
+const refreshCalls: string[] = [];
+const dispatchCalls: Array<{ target: HandoffTarget; input: unknown }> = [];
+const installCalls: TargetData[] = [];
+let workspace: unknown = { projectDir: '/project' };
+
+mock.module('@/components/handoff/OpenInAgentMenuItem', () => ({
+ TargetIcon: ({ id }: { id: HandoffTarget }) => <svg data-testid={`target-icon-${id}`} />,
+}));
+
+mock.module('@/components/handoff/useInstalledAgents', () => ({
+ useInstalledAgents: () => ({
+ states,
+ refresh: () => {
+ refreshCalls.push('refresh');
+ },
+ }),
+}));
+
+mock.module('@/components/handoff/useHandoffDispatch', () => ({
+ buildProjectScopedHandoffInput: ({ workspace: currentWorkspace }: { workspace: unknown }) =>
+ currentWorkspace === null ? null : { scope: 'project', workspace: currentWorkspace },
+ openInstallUrl: (target: TargetData) => {
+ installCalls.push(target);
+ return Promise.resolve();
+ },
+ useHandoffDispatch: () => ({
+ dispatch: (target: HandoffTarget, input: unknown) => {
+ dispatchCalls.push({ target, input });
+ return Promise.resolve({ ok: true });
+ },
+ }),
+}));
+
+mock.module('@/lib/use-workspace', () => ({
+ useWorkspace: () => workspace,
+}));
+
+async function renderAgentHandoffGrid() {
+ const { AgentHandoffGrid } = await import('./AgentHandoffGrid');
+ render(<AgentHandoffGrid />);
+}
+
+function setInstallStates(value: InstallState['installed']) {
+ states['claude-code'] = { installed: value };
+ states.codex = { installed: value };
+ states.cursor = { installed: value };
+}
+
+describe('AgentHandoffGrid runtime behavior', () => {
+ afterEach(() => {
+ cleanup();
+ for (const key of Object.keys(states) as HandoffTarget[]) delete states[key];
+ refreshCalls.length = 0;
+ dispatchCalls.length = 0;
+ installCalls.length = 0;
+ workspace = { projectDir: '/project' };
+ });
+
+ test('exports the component', async () => {
+ const mod = await import('./AgentHandoffGrid');
+ expect(typeof mod.AgentHandoffGrid).toBe('function');
+ });
+
+ test('renders only visible installed targets as Open buttons and dispatches through the shared hook', async () => {
+ setInstallStates(true);
+ await renderAgentHandoffGrid();
+
+ const buttons = screen.getAllByRole('button');
+ expect(buttons).toHaveLength(3);
+ expect(screen.queryByText('Claude Cowork')).toBeNull();
+ expect(screen.getByText('Claude')).not.toBeNull();
+ expect(screen.getByText('Codex')).not.toBeNull();
+ expect(screen.getByText('Cursor')).not.toBeNull();
+ expect(buttons.every((button) => button.textContent?.includes('Open'))).toBe(true);
+
+ await userEvent.click(screen.getByRole('button', { name: /Codex/ }));
+ expect(dispatchCalls).toEqual([
+ {
+ target: 'codex',
+ input: { scope: 'project', workspace: { projectDir: '/project' } },
+ },
+ ]);
+ });
+
+ test('disables installed Open buttons while workspace input is unavailable', async () => {
+ setInstallStates(true);
+ workspace = null;
+ await renderAgentHandoffGrid();
+
+ for (const button of screen.getAllByRole('button')) {
+ expect((button as HTMLButtonElement).disabled).toBe(true);
+ expect(button.textContent).toContain('Open');
+ }
+ });
+
+ test('missing targets open the install URL and refresh probe state', async () => {
+ setInstallStates(false);
+ await renderAgentHandoffGrid();
+
+ const codex = screen.getByRole('button', { name: /Codex/ });
+ expect(codex.textContent).toContain('Install');
+ expect((codex as HTMLButtonElement).disabled).toBe(false);
+
+ await userEvent.click(codex);
+ expect(installCalls.map((target) => target.id)).toEqual(['codex']);
+ expect(refreshCalls).toEqual(['refresh']);
+ expect(dispatchCalls).toEqual([]);
+ });
+
+ test('pending targets render disabled Checking buttons instead of install links', async () => {
+ setInstallStates(null);
+ await renderAgentHandoffGrid();
+
+ for (const button of screen.getAllByRole('button')) {
+ expect((button as HTMLButtonElement).disabled).toBe(true);
+ expect(button.textContent).toContain('Checking');
+ }
+ expect(installCalls).toEqual([]);
+ expect(dispatchCalls).toEqual([]);
+ });
+});
diff --git a/packages/app/src/components/empty-state/AgentHandoffGrid.test.ts b/packages/app/src/components/empty-state/AgentHandoffGrid.test.ts
deleted file mode 100644
index 61ce5d6de..000000000
--- a/packages/app/src/components/empty-state/AgentHandoffGrid.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './AgentHandoffGrid?raw';
-
-describe('AgentHandoffGrid module', () => {
- test('exports AgentHandoffGrid component', async () => {
- const mod = await import('./AgentHandoffGrid');
- expect(typeof mod.AgentHandoffGrid).toBe('function');
- });
-});
-
-describe('AgentHandoffGrid source-level guards', () => {
- test('uses the shared install probe (useInstalledAgents)', () => {
- expect(SRC).toContain("from '@/components/handoff/useInstalledAgents'");
- expect(SRC).toContain('useInstalledAgents()');
- });
-
- test('dispatches handoffs through the shared useHandoffDispatch hook', () => {
- expect(SRC).toContain('useHandoffDispatch');
- expect(SRC).toContain('buildProjectScopedHandoffInput');
- });
-
- test('iterates the VISIBLE_TARGETS render allow-list (no hardcoded id list)', () => {
- expect(SRC).toContain('VISIBLE_TARGETS.map');
- });
-
- test('not-installed path opens the editor installUrl via the handoff allowlist', () => {
- expect(SRC).toContain('openInstallUrl(target)');
- expect(SRC).not.toContain("from '@/lib/handoff/open-external'");
- });
-
- test('disables the Open button while workspace input is still resolving', () => {
- expect(SRC).toMatch(/status\s*===\s*['"]installed['"]\s*&&\s*handoffInput\s*!==\s*null/);
- });
-
- test('pre-probe install state renders as disabled "Checking", not clickable Install', () => {
- expect(SRC).toContain("'pending'");
- expect(SRC).toContain("status === 'pending'");
- expect(SRC).toContain("'Checking'");
- });
-
- test('re-probes installed state after Install click and on window focus', () => {
- expect(SRC).toContain('void refresh();');
- expect(SRC).toMatch(/refresh\s*}\s*=\s*useInstalledAgents\(\)/);
- });
-
- test('renders each card as a button for keyboard a11y', () => {
- expect(SRC).toContain('<button');
- expect(SRC).toContain('type="button"');
- });
-});
diff --git a/packages/app/src/components/empty-state/EmptyStateHeader.dom.test.tsx b/packages/app/src/components/empty-state/EmptyStateHeader.dom.test.tsx
new file mode 100644
index 000000000..41d5701a7
--- /dev/null
+++ b/packages/app/src/components/empty-state/EmptyStateHeader.dom.test.tsx
@@ -0,0 +1,47 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+mock.module('@/components/OkBlob', () => ({
+ OkBlob: ({ celebrateSignal, size }: { celebrateSignal: number; size: number }) => (
+ <div
+ data-testid="ok-blob-probe"
+ data-celebrate-signal={String(celebrateSignal)}
+ data-size={String(size)}
+ />
+ ),
+}));
+
+describe('EmptyStateHeader runtime behavior', () => {
+ afterEach(() => cleanup());
+
+ test('exports EmptyStateHeader component', async () => {
+ const mod = await import('./EmptyStateHeader');
+ expect(typeof mod.EmptyStateHeader).toBe('function');
+ });
+
+ test('renders title, optional subtitle, block-level row layout, and blob signal', async () => {
+ const { EmptyStateHeader } = await import('./EmptyStateHeader');
+
+ const { rerender } = render(
+ <EmptyStateHeader title="Choose a starter" subtitle="Pick one" celebrateSignal={3} />,
+ );
+
+ expect(screen.getByRole('heading', { level: 2, name: 'Choose a starter' })).toBeTruthy();
+ expect(screen.getByText('Pick one')).toBeTruthy();
+ expect(screen.getByTestId('ok-blob-probe').getAttribute('data-celebrate-signal')).toBe('3');
+ expect(screen.getByTestId('ok-blob-probe').getAttribute('data-size')).toBe('64');
+
+ const root = screen.getByTestId('ok-blob-probe').parentElement;
+ expectVisualClassTokens(root?.className, ['flex', 'items-center', 'gap-4']);
+ expectVisualClassTokensAbsent(root?.className, ['inline-flex']);
+
+ rerender(<EmptyStateHeader title="Choose a starter" celebrateSignal={4} />);
+
+ expect(screen.queryByText('Pick one')).toBeNull();
+ expect(screen.getByTestId('ok-blob-probe').getAttribute('data-celebrate-signal')).toBe('4');
+ });
+});
diff --git a/packages/app/src/components/empty-state/EmptyStateHeader.test.ts b/packages/app/src/components/empty-state/EmptyStateHeader.test.ts
deleted file mode 100644
index eb9356c11..000000000
--- a/packages/app/src/components/empty-state/EmptyStateHeader.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './EmptyStateHeader?raw';
-
-describe('EmptyStateHeader module', () => {
- test('exports EmptyStateHeader component', async () => {
- const mod = await import('./EmptyStateHeader');
- expect(typeof mod.EmptyStateHeader).toBe('function');
- });
-});
-
-describe('EmptyStateHeader source-level guards', () => {
- test('accepts title, optional subtitle, and celebrateSignal props', () => {
- expect(SRC).toContain('title: string');
- expect(SRC).toContain('subtitle?: string');
- expect(SRC).toContain('celebrateSignal: number');
- });
-
- test('renders subtitle only when provided', () => {
- expect(SRC).toMatch(/subtitle\s*\?\s*<p/);
- });
-
- test('forwards celebrateSignal to OkBlob', () => {
- expect(SRC).toContain('celebrateSignal={celebrateSignal}');
- });
-
- test('uses block-level layout (not inline-flex with text)', () => {
- expect(SRC).toContain('flex items-center gap-4');
- });
-});
diff --git a/packages/app/src/components/file-tree-refresh.dom.test.tsx b/packages/app/src/components/file-tree-refresh.dom.test.tsx
new file mode 100644
index 000000000..4bfa9f239
--- /dev/null
+++ b/packages/app/src/components/file-tree-refresh.dom.test.tsx
@@ -0,0 +1,318 @@
+import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
+import { cleanup, render } from '@testing-library/react';
+import type { MouseEventHandler, ReactNode } from 'react';
+
+type DocumentsChangedListener = (channels: string[]) => void;
+type TemplatesChangedListener = () => void;
+
+type MenuItemProps = {
+ children?: ReactNode;
+ disabled?: boolean;
+ onSelect?: () => void;
+ [key: string]: unknown;
+};
+
+function PassThrough({ children }: { children?: ReactNode }) {
+ return <>{children}</>;
+}
+
+function MenuItem({ children, disabled, onSelect, variant: _variant, ...props }: MenuItemProps) {
+ return (
+ <button type="button" role="menuitem" disabled={disabled} onClick={onSelect} {...props}>
+ {children}
+ </button>
+ );
+}
+
+class StubModel {
+ private readonly items = new Map<string, { isExpanded: () => boolean }>();
+
+ getFocusedPath() {
+ return null;
+ }
+
+ getFocusedIndex() {
+ return -1;
+ }
+
+ getItemHeight() {
+ return 24;
+ }
+
+ getSelectedPaths() {
+ return [];
+ }
+
+ getItem(path: string) {
+ return this.items.get(path) ?? null;
+ }
+
+ resetPaths(paths: string[]) {
+ this.items.clear();
+ for (const path of paths) {
+ this.items.set(path, { isExpanded: () => false });
+ }
+ }
+
+ subscribe() {
+ return () => {};
+ }
+
+ onMutation() {
+ return () => {};
+ }
+
+ isSearchOpen() {
+ return false;
+ }
+
+ add() {}
+ move() {}
+ remove() {}
+ focus() {}
+}
+
+let model = new StubModel();
+let documentsChangedListener: DocumentsChangedListener | null = null;
+let templatesChangedListener: TemplatesChangedListener | null = null;
+let unsubscribeDocumentsChangedMock = mock(() => {});
+let unsubscribeTemplatesChangedMock = mock(() => {});
+let schedulerRequestMock = mock(() => {});
+let schedulerDisposeMock = mock(() => {});
+const createRefreshSchedulerMock = mock(() => ({
+ request: schedulerRequestMock,
+ dispose: schedulerDisposeMock,
+}));
+const fetchMock = mock(async (input: RequestInfo | URL) => {
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
+ if (url === '/api/workspace') {
+ return new Response(
+ JSON.stringify({
+ contentDir: '/tmp/open-knowledge',
+ pathSeparator: '/',
+ symlinkResolved: true,
+ }),
+ { headers: { 'content-type': 'application/json' } },
+ );
+ }
+ throw new Error(`unexpected fetch: ${url}`);
+});
+
+mock.module('sonner', () => ({
+ toast: {
+ success: () => {},
+ error: () => {},
+ },
+}));
+
+mock.module('next-themes', () => ({
+ useTheme: () => ({ resolvedTheme: 'light' }),
+}));
+
+mock.module('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({
+ activeDocName: 'notes/source',
+ activeTarget: { kind: 'doc', target: 'notes/source', docName: 'notes/source' },
+ closeTabs: () => {},
+ closeDocument: () => {},
+ closeAndClearForRename: async () => {},
+ getPoolActiveDocName: () => 'notes/source',
+ isNewTabActive: false,
+ openTarget: () => {},
+ prewarm: () => {},
+ remapTabsForRename: () => {},
+ }),
+}));
+
+mock.module('@/components/PageListContext', () => ({
+ usePageList: () => ({ addPage: () => {} }),
+}));
+
+mock.module('./ui/sidebar', () => ({
+ useSidebar: () => ({ notifySidebarFileSelected: () => {} }),
+}));
+
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ okignoreBinding: null,
+ projectLocalBinding: null,
+ merged: null,
+ }),
+}));
+
+mock.module('@/hooks/use-conflicts', () => ({
+ useConflicts: () => ({ conflicts: [], loading: false, error: null }),
+}));
+
+mock.module('./handoff/useInstalledAgents', () => ({
+ useInstalledAgents: () => ({ states: {} }),
+}));
+
+mock.module('./handoff/useHandoffDispatch', () => ({
+ buildFolderHandoffInput: () => null,
+ buildHandoffInput: () => null,
+ useHandoffDispatch: () => ({ dispatch: async () => ({ ok: true as const }) }),
+}));
+
+mock.module('./handoff/OpenInAgentContextSubmenu', () => ({
+ OpenInAgentContextSubmenu: () => null,
+}));
+
+mock.module('./sidebar-hover-prewarm', () => ({
+ cancelHoverPrewarm: () => {},
+ scheduleHoverPrewarm: () => {},
+}));
+
+mock.module('@/components/ui/button', () => ({
+ Button: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <button type="button" {...props}>
+ {children}
+ </button>
+ ),
+}));
+
+mock.module('@/components/ui/dialog', () => ({
+ Dialog: PassThrough,
+}));
+
+mock.module('@/components/ui/dropdown-menu', () => ({
+ DropdownMenu: PassThrough,
+ DropdownMenuCheckboxItem: MenuItem,
+ DropdownMenuContent: ({ children }: { children?: ReactNode }) => (
+ <div role="menu">{children}</div>
+ ),
+ DropdownMenuItem: MenuItem,
+ DropdownMenuSeparator: () => <hr />,
+ DropdownMenuSub: PassThrough,
+ DropdownMenuSubContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ DropdownMenuSubTrigger: MenuItem,
+ DropdownMenuTrigger: PassThrough,
+}));
+
+mock.module('@/components/ui/skeleton', () => ({
+ Skeleton: ({ className }: { className?: string }) => <span className={className} />,
+}));
+
+mock.module('@/components/DeleteConfirmationDialog', () => ({
+ DeleteConfirmationDialog: () => null,
+}));
+
+mock.module('@/components/NewItemDialog', () => ({
+ NewItemDialog: () => null,
+}));
+
+mock.module('@/components/TrashFailureModal', () => ({
+ TrashFailureModal: () => null,
+ coerceTrashFailureReason: (reason: string) => reason,
+}));
+
+mock.module('@/components/use-selection-mirror', () => ({
+ asDirectoryHandle: () => null,
+ useSelectionMirror: () => {},
+}));
+
+mock.module('@pierre/trees', () => ({
+ FILE_TREE_TAG_NAME: 'ok-file-tree',
+ themeToTreeStyles: () => ({}),
+}));
+
+mock.module('@pierre/trees/react', () => ({
+ useFileTree: () => ({ model }),
+ FileTree: ({
+ onClickCapture,
+ onMouseMove,
+ onMouseLeave,
+ }: {
+ onClickCapture?: MouseEventHandler<HTMLDivElement>;
+ onMouseMove?: MouseEventHandler<HTMLDivElement>;
+ onMouseLeave?: MouseEventHandler<HTMLDivElement>;
+ }) => (
+ <div
+ data-testid="fake-pierre-tree"
+ role="tree"
+ onClickCapture={onClickCapture}
+ onMouseMove={onMouseMove}
+ onMouseLeave={onMouseLeave}
+ />
+ ),
+}));
+
+mock.module('@/lib/documents-events', () => ({
+ emitDocumentsChanged: () => {},
+ emitTemplatesChanged: () => {},
+ subscribeToDocumentsChanged: (listener: DocumentsChangedListener) => {
+ documentsChangedListener = listener;
+ return () => {
+ if (documentsChangedListener === listener) {
+ documentsChangedListener = null;
+ }
+ unsubscribeDocumentsChangedMock();
+ };
+ },
+ subscribeToTemplatesChanged: (listener: TemplatesChangedListener) => {
+ templatesChangedListener = listener;
+ return () => {
+ if (templatesChangedListener === listener) {
+ templatesChangedListener = null;
+ }
+ unsubscribeTemplatesChangedMock();
+ };
+ },
+}));
+
+mock.module('@/lib/refresh-scheduler', () => ({
+ createRefreshScheduler: createRefreshSchedulerMock,
+}));
+
+const { FileTree } = await import('./FileTree');
+
+describe('FileTree document-list refresh scheduling', () => {
+ let setIntervalSpy: ReturnType<typeof spyOn>;
+ let consoleWarnSpy: ReturnType<typeof spyOn>;
+
+ beforeEach(() => {
+ model = new StubModel();
+ documentsChangedListener = null;
+ templatesChangedListener = null;
+ unsubscribeDocumentsChangedMock = mock(() => {});
+ unsubscribeTemplatesChangedMock = mock(() => {});
+ schedulerRequestMock = mock(() => {});
+ schedulerDisposeMock = mock(() => {});
+ createRefreshSchedulerMock.mockClear();
+ fetchMock.mockClear();
+ globalThis.fetch = fetchMock as unknown as typeof fetch;
+ setIntervalSpy = spyOn(globalThis, 'setInterval');
+ consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ cleanup();
+ setIntervalSpy.mockRestore();
+ consoleWarnSpy.mockRestore();
+ });
+
+ test('routes mount, focus, and files-channel refreshes through the bounded scheduler', () => {
+ const { unmount } = render(<FileTree />);
+
+ expect(createRefreshSchedulerMock).toHaveBeenCalledTimes(1);
+ expect(schedulerRequestMock).toHaveBeenCalledTimes(1);
+ expect(documentsChangedListener).not.toBeNull();
+ expect(setIntervalSpy).not.toHaveBeenCalled();
+
+ window.dispatchEvent(new Event('focus'));
+ expect(schedulerRequestMock).toHaveBeenCalledTimes(2);
+
+ documentsChangedListener?.(['backlinks']);
+ expect(schedulerRequestMock).toHaveBeenCalledTimes(2);
+
+ documentsChangedListener?.(['files']);
+ expect(schedulerRequestMock).toHaveBeenCalledTimes(3);
+ expect(setIntervalSpy).not.toHaveBeenCalled();
+
+ unmount();
+
+ expect(schedulerDisposeMock).toHaveBeenCalledTimes(1);
+ expect(unsubscribeDocumentsChangedMock).toHaveBeenCalledTimes(1);
+ expect(documentsChangedListener).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/file-tree-refresh.test.ts b/packages/app/src/components/file-tree-refresh.test.ts
deleted file mode 100644
index 231dfa3c3..000000000
--- a/packages/app/src/components/file-tree-refresh.test.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import FILE_SIDEBAR_SOURCE from './FileSidebar?raw';
-import FILE_TREE_SOURCE from './FileTree?raw';
-
-describe('file tree document-list freshness wiring', () => {
- test('uses the bounded refresh scheduler for document-list refreshes', () => {
- expect(FILE_TREE_SOURCE).toContain(
- "import { createRefreshScheduler } from '@/lib/refresh-scheduler'",
- );
- expect(FILE_TREE_SOURCE).toContain(
- 'const scheduler = createRefreshScheduler(refreshDocs, () => refreshController?.abort())',
- );
- expect(FILE_TREE_SOURCE).toContain('subscribeToDocumentsChanged');
- });
-
- test('does not use recurring document-list polling in FileTree or FileSidebar', () => {
- expect(FILE_TREE_SOURCE).not.toContain('setInterval');
- expect(FILE_SIDEBAR_SOURCE).not.toContain('setInterval');
- });
-});
diff --git a/packages/app/src/components/handoff/OpenInAgentContextSubmenu.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentContextSubmenu.dom.test.tsx
new file mode 100644
index 000000000..62d9a25b2
--- /dev/null
+++ b/packages/app/src/components/handoff/OpenInAgentContextSubmenu.dom.test.tsx
@@ -0,0 +1,142 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import type { HandoffTarget, InstallState } from '@inkeep/open-knowledge-core';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { DropdownMenu, DropdownMenuContent } from '@/components/ui/dropdown-menu';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+import type { HandoffDispatchInput } from './useHandoffDispatch';
+
+mock.module('@lingui/core/macro', () => ({
+ t: renderLinguiTemplate,
+}));
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+mock.module('next-themes', () => ({
+ useTheme: () => ({ resolvedTheme: 'light' }),
+}));
+
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ merged: { appearance: { preview: { autoOpen: true } } },
+ }),
+}));
+
+mock.module('@/lib/config-context', () => ({
+ useConfigContext: () => ({
+ merged: { appearance: { preview: { autoOpen: true } } },
+ }),
+}));
+
+mock.module('sonner', () => ({
+ toast: {
+ error: mock(() => {}),
+ success: mock(() => {}),
+ },
+}));
+
+const readyInput: HandoffDispatchInput = {
+ docContext: { relativePath: 'notes/today.md' },
+ docPath: '/project/notes/today.md',
+ projectDir: '/project',
+};
+
+function installStates(
+ overrides: Partial<Record<HandoffTarget, InstallState>> = {},
+): Record<HandoffTarget, InstallState> {
+ return {
+ 'claude-code': { installed: false, lastChecked: 1 },
+ 'claude-cowork': { installed: true, lastChecked: 1 },
+ codex: { installed: true, lastChecked: 1 },
+ cursor: { installed: null, lastChecked: 1 },
+ ...overrides,
+ };
+}
+
+async function renderSubmenu({
+ input = readyInput,
+ states = installStates(),
+ webFallbackVisible,
+}: {
+ input?: HandoffDispatchInput | null;
+ states?: Record<HandoffTarget, InstallState>;
+ webFallbackVisible?: boolean;
+} = {}) {
+ const { OpenInAgentContextSubmenu } = await import('./OpenInAgentContextSubmenu');
+ const dispatchCalls: Array<{ input: HandoffDispatchInput; target: HandoffTarget }> = [];
+ const dispatch = mock(async (target: HandoffTarget, nextInput: HandoffDispatchInput) => {
+ dispatchCalls.push({ input: nextInput, target });
+ return { ok: true as const };
+ });
+
+ render(
+ <DropdownMenu open={true}>
+ <DropdownMenuContent forceMount={true}>
+ <OpenInAgentContextSubmenu
+ dispatch={dispatch}
+ input={input}
+ installStates={states}
+ isElectronHost={true}
+ webFallbackVisible={webFallbackVisible}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>,
+ );
+
+ const trigger = screen.getByRole('menuitem', { name: 'Open with AI' });
+ await userEvent.hover(trigger);
+ await waitFor(() => {
+ expect(document.querySelector('[data-slot="dropdown-menu-sub-content"]')).toBeTruthy();
+ });
+
+ return { dispatch, dispatchCalls, trigger };
+}
+
+describe('OpenInAgentContextSubmenu runtime behavior', () => {
+ afterEach(() => cleanup());
+
+ test('renders only installed visible targets and dispatches the selected row', async () => {
+ const { dispatchCalls } = await renderSubmenu();
+
+ const trigger = document.querySelector('[data-slot="dropdown-menu-sub-trigger"]');
+ expect(trigger?.textContent).toContain('Open with AI');
+ expect(screen.getByTestId('file-tree-open-in-codex')).toBeTruthy();
+ expect(screen.queryByTestId('file-tree-open-in-claude-cowork') === null).toBe(true);
+ expect(screen.queryByTestId('file-tree-open-in-cursor') === null).toBe(true);
+ expect(screen.getByTestId('file-tree-open-in-claude-web-fallback')).toBeTruthy();
+
+ await userEvent.click(screen.getByRole('menuitem', { name: 'Open with AI Codex' }));
+
+ expect(dispatchCalls).toEqual([{ input: readyInput, target: 'codex' }]);
+ });
+
+ test('keeps rows disabled with a No workspace label while input is missing', async () => {
+ const { dispatch } = await renderSubmenu({ input: null });
+
+ const codex = screen.getByRole('menuitem', { name: 'Open with AI Codex, No workspace' });
+ expect(codex.getAttribute('data-disabled')).toBe('');
+ expect(codex.textContent).toContain('No workspace');
+
+ await userEvent.click(codex);
+
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ test('hides the Claude web fallback when the caller opts out or Claude is installed', async () => {
+ await renderSubmenu({ webFallbackVisible: false });
+ expect(screen.queryByTestId('file-tree-open-in-claude-web-fallback') === null).toBe(true);
+ cleanup();
+
+ await renderSubmenu({
+ states: installStates({
+ 'claude-code': { installed: true, lastChecked: 1 },
+ }),
+ });
+ expect(screen.queryByTestId('file-tree-open-in-claude-web-fallback') === null).toBe(true);
+ expect(screen.getByTestId('file-tree-open-in-claude-code')).toBeTruthy();
+ });
+});
diff --git a/packages/app/src/components/handoff/OpenInAgentContextSubmenu.test.ts b/packages/app/src/components/handoff/OpenInAgentContextSubmenu.test.ts
index 6a0ccd284..cfcd7e6a4 100644
--- a/packages/app/src/components/handoff/OpenInAgentContextSubmenu.test.ts
+++ b/packages/app/src/components/handoff/OpenInAgentContextSubmenu.test.ts
@@ -1,52 +1,20 @@
import { describe, expect, test } from 'bun:test';
import { contextRowHint } from './OpenInAgentContextSubmenu';
-import SRC from './OpenInAgentContextSubmenu?raw';
-describe('contextRowHint (v1: inputMissing only)', () => {
- test('inputMissing=false (workspace known): returns null (no hint)', () => {
+describe('contextRowHint', () => {
+ test('returns null when workspace metadata is ready', () => {
expect(contextRowHint(false)).toBeNull();
});
- test('inputMissing=true (no workspace): returns "No workspace"', () => {
+ test('returns No workspace when workspace metadata is missing', () => {
expect(contextRowHint(true)).toBe('No workspace');
});
});
-describe('module surface', () => {
- test('exports OpenInAgentContextSubmenu + contextRowHint', async () => {
+describe('OpenInAgentContextSubmenu module surface', () => {
+ test('exports the component and row-hint helper', async () => {
const mod = await import('./OpenInAgentContextSubmenu');
expect(typeof mod.OpenInAgentContextSubmenu).toBe('function');
expect(typeof mod.contextRowHint).toBe('function');
});
});
-
-describe('source-level guards', () => {
- test('renders only the VISIBLE_TARGETS subset (cowork hidden from FileTree submenu)', () => {
- expect(SRC).toContain('installedTargets = VISIBLE_TARGETS.filter(');
- expect(SRC).toMatch(/installStates\[target\.id\]\?\.installed\s*===\s*true/);
- });
-
- test('claudeInstalled probe keys off the visible claude-code row', () => {
- expect(SRC).toMatch(/installStates\[['"]claude-code['"]\]\?\.installed\s*===\s*true/);
- expect(SRC).not.toContain("installStates['claude-cowork']");
- });
-
- test('preserves the Claude web-fallback row when !claudeInstalled', () => {
- expect(SRC).toContain('file-tree-open-in-claude-web-fallback');
- expect(SRC).toMatch(/!claudeInstalled\s*\?/);
- });
-});
-
-describe('webFallbackVisible prop (D25 — folder/empty-space hide the claude.ai row)', () => {
- test('prop is declared optional on the props interface', () => {
- expect(SRC).toMatch(/readonly webFallbackVisible\?:\s*boolean;/);
- });
-
- test("defaults to true so the file-surface caller keeps today's behavior", () => {
- expect(SRC).toMatch(/webFallbackVisible\s*=\s*true\s*\}\s*=\s*props/);
- });
-
- test('the web-fallback row is gated on BOTH webFallbackVisible AND !claudeInstalled', () => {
- expect(SRC).toMatch(/webFallbackVisible\s*&&\s*!claudeInstalled\s*\?/);
- });
-});
diff --git a/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.dom.test.tsx
new file mode 100644
index 000000000..b67e6c8a5
--- /dev/null
+++ b/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.dom.test.tsx
@@ -0,0 +1,161 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import type { HandoffTarget, InstallState } from '@inkeep/open-knowledge-core';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { act } from 'react';
+import { ContextMenu, ContextMenuContent, ContextMenuTrigger } from '@/components/ui/context-menu';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+import type { HandoffDispatchInput } from './useHandoffDispatch';
+
+mock.module('@lingui/core/macro', () => ({
+ t: renderLinguiTemplate,
+}));
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+mock.module('next-themes', () => ({
+ useTheme: () => ({ resolvedTheme: 'light' }),
+}));
+
+mock.module('sonner', () => ({
+ toast: {
+ error: mock(() => {}),
+ success: mock(() => {}),
+ },
+}));
+
+mock.module('@/lib/config-context', () => ({
+ useConfigContext: () => ({
+ merged: { appearance: { preview: { autoOpen: true } } },
+ }),
+}));
+
+mock.module('@/hooks/use-is-embedded', () => ({
+ useIsEmbedded: () => false,
+}));
+
+const readyInput: HandoffDispatchInput = {
+ docContext: null,
+ docPath: '',
+ projectDir: '/project',
+};
+
+function installStates(
+ overrides: Partial<Record<HandoffTarget, InstallState>> = {},
+): Record<HandoffTarget, InstallState> {
+ return {
+ 'claude-code': { installed: false, lastChecked: 1 },
+ 'claude-cowork': { installed: true, lastChecked: 1 },
+ codex: { installed: true, lastChecked: 1 },
+ cursor: { installed: null, lastChecked: 1 },
+ ...overrides,
+ };
+}
+
+async function renderSubmenu({
+ input = readyInput,
+ states = installStates(),
+ webFallbackVisible,
+}: {
+ input?: HandoffDispatchInput | null;
+ states?: Record<HandoffTarget, InstallState>;
+ webFallbackVisible?: boolean;
+} = {}) {
+ const { OpenInAgentEmptySpaceSubmenu } = await import('./OpenInAgentEmptySpaceSubmenu');
+ const dispatchCalls: Array<{ input: HandoffDispatchInput; target: HandoffTarget }> = [];
+ const dispatch = mock(async (target: HandoffTarget, nextInput: HandoffDispatchInput) => {
+ dispatchCalls.push({ input: nextInput, target });
+ return { ok: true as const };
+ });
+
+ render(
+ <ContextMenu>
+ <ContextMenuTrigger asChild>
+ <button type="button">Project files</button>
+ </ContextMenuTrigger>
+ <ContextMenuContent forceMount={true}>
+ <OpenInAgentEmptySpaceSubmenu
+ dispatch={dispatch}
+ input={input}
+ installStates={states}
+ webFallbackVisible={webFallbackVisible}
+ />
+ </ContextMenuContent>
+ </ContextMenu>,
+ );
+
+ await act(async () => {
+ fireEvent.contextMenu(screen.getByText('Project files'));
+ await Promise.resolve();
+ });
+
+ return { dispatch, dispatchCalls };
+}
+
+async function openEmptySpaceSubmenu() {
+ const trigger = screen.getByRole('menuitem', { name: 'Open with AI' });
+ await userEvent.hover(trigger);
+ await waitFor(() => {
+ expect(document.querySelector('[data-slot="context-menu-sub-content"]')).toBeTruthy();
+ });
+ return trigger;
+}
+
+describe('OpenInAgentEmptySpaceSubmenu runtime behavior', () => {
+ afterEach(() => cleanup());
+
+ test('renders as a ContextMenu submenu, filters visible installed targets, and dispatches rows', async () => {
+ const { dispatchCalls } = await renderSubmenu({ webFallbackVisible: false });
+ const trigger = await openEmptySpaceSubmenu();
+
+ expect(trigger.getAttribute('data-slot')).toBe('context-menu-sub-trigger');
+ expect(document.querySelector('[data-slot="dropdown-menu-sub-trigger"]') === null).toBe(true);
+ expect(screen.getByTestId('empty-space-open-in-codex')).toBeTruthy();
+ expect(screen.queryByTestId('empty-space-open-in-claude-cowork') === null).toBe(true);
+ expect(screen.queryByTestId('empty-space-open-in-cursor') === null).toBe(true);
+ expect(screen.queryByTestId('empty-space-open-in-claude-web-fallback') === null).toBe(true);
+
+ await userEvent.click(screen.getByRole('menuitem', { name: 'Open with AI Codex' }));
+
+ expect(dispatchCalls).toEqual([{ input: readyInput, target: 'codex' }]);
+ });
+
+ test('keeps rows disabled with a No workspace label while input is missing', async () => {
+ const { dispatch } = await renderSubmenu({ input: null });
+ await openEmptySpaceSubmenu();
+
+ const codex = screen.getByRole('menuitem', { name: 'Open with AI Codex, No workspace' });
+ expect(codex.getAttribute('data-disabled')).toBe('');
+ expect(codex.textContent).toContain('No workspace');
+
+ await userEvent.click(codex);
+
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ test('defaults the Claude web fallback on but hides the whole submenu when nothing can render', async () => {
+ await renderSubmenu({
+ states: installStates({
+ codex: { installed: false, lastChecked: 1 },
+ cursor: { installed: false, lastChecked: 1 },
+ }),
+ });
+ await openEmptySpaceSubmenu();
+ expect(screen.getByTestId('empty-space-open-in-claude-web-fallback')).toBeTruthy();
+ cleanup();
+
+ await renderSubmenu({
+ states: installStates({
+ 'claude-code': { installed: false, lastChecked: 1 },
+ codex: { installed: false, lastChecked: 1 },
+ cursor: { installed: false, lastChecked: 1 },
+ }),
+ webFallbackVisible: false,
+ });
+ expect(screen.queryByRole('menuitem', { name: 'Open with AI' }) === null).toBe(true);
+ });
+});
diff --git a/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.test.ts b/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.test.ts
index 23ce8878a..5f3c1ed1b 100644
--- a/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.test.ts
+++ b/packages/app/src/components/handoff/OpenInAgentEmptySpaceSubmenu.test.ts
@@ -1,20 +1,16 @@
import { describe, expect, test } from 'bun:test';
import { emptySpaceRowHint } from './OpenInAgentEmptySpaceSubmenu';
-import SRC from './OpenInAgentEmptySpaceSubmenu?raw';
-describe('OpenInAgentEmptySpaceSubmenu module', () => {
- test('exports the OpenInAgentEmptySpaceSubmenu component', async () => {
+describe('OpenInAgentEmptySpaceSubmenu module surface', () => {
+ test('exports the component and row-hint helper', async () => {
const mod = await import('./OpenInAgentEmptySpaceSubmenu');
expect(typeof mod.OpenInAgentEmptySpaceSubmenu).toBe('function');
- });
-
- test('exports emptySpaceRowHint helper for accessibility-label coherence', () => {
- expect(typeof emptySpaceRowHint).toBe('function');
+ expect(typeof mod.emptySpaceRowHint).toBe('function');
});
});
-describe('emptySpaceRowHint — pure helper contract', () => {
- test('returns "No workspace" when input is missing (workspace not yet resolved)', () => {
+describe('emptySpaceRowHint', () => {
+ test('returns No workspace when input is missing', () => {
expect(emptySpaceRowHint(true)).toBe('No workspace');
});
@@ -22,61 +18,3 @@ describe('emptySpaceRowHint — pure helper contract', () => {
expect(emptySpaceRowHint(false)).toBeNull();
});
});
-
-describe('OpenInAgentEmptySpaceSubmenu source-level guards', () => {
- test('imports ContextMenu submenu primitives (NOT DropdownMenu)', () => {
- expect(SRC).toMatch(
- /import\s*\{[\s\S]*?\bContextMenuItem\b[\s\S]*?\bContextMenuSub\b[\s\S]*?\bContextMenuSubContent\b[\s\S]*?\bContextMenuSubTrigger\b[\s\S]*?\}\s*from\s*['"]@\/components\/ui\/context-menu['"]/,
- );
- expect(SRC).not.toMatch(
- /import\s*\{[^}]*\bDropdownMenuSub\b[^}]*\}\s*from\s*['"]@\/components\/ui\/dropdown-menu/,
- );
- });
-
- test('renders ContextMenuSub root, NOT DropdownMenuSub', () => {
- expect(SRC).toMatch(/<ContextMenuSub>/);
- expect(SRC).toMatch(/<ContextMenuSubTrigger>/);
- expect(SRC).toMatch(/<ContextMenuSubContent>/);
- expect(SRC).not.toMatch(/<DropdownMenuSub>/);
- });
-
- test('trigger uses the canonical Sparkles icon + "Open with AI" label (D13)', () => {
- expect(SRC).toMatch(
- /<ContextMenuSubTrigger>\s*\n?\s*<Sparkles\s+aria-hidden="true"\s*\/>\s*\n?\s*<Trans>Open with AI<\/Trans>\s*\n?\s*<\/ContextMenuSubTrigger>/,
- );
- });
-
- test('webFallbackVisible prop defaults to true (file-surface parity)', () => {
- expect(SRC).toMatch(/webFallbackVisible\s*\??\s*:\s*boolean/);
- expect(SRC).toMatch(/webFallbackVisible\s*=\s*true/);
- });
-
- test('web fallback row is gated by both webFallbackVisible AND !claudeInstalled', () => {
- expect(SRC).toMatch(/webFallbackVisible\s*&&\s*!claudeInstalled/);
- });
-
- test('per-target aria-label uses "Open with AI <displayName>" (D13)', () => {
- expect(SRC).toMatch(
- /accessibleLabel\s*=\s*hint\s*\?\s*t`Open with AI\s+\$\{displayName\},\s*\$\{hint\}`\s*:\s*t`Open with AI\s+\$\{displayName\}`/,
- );
- });
-
- test('install-state filter is `installed === true` (v1 contract)', () => {
- expect(SRC).toMatch(/installStates\[target\.id\]\?\.installed\s*===\s*true/);
- });
-
- test('Claude web-fallback prompt uses composeFilePrompt(relativePath, autoOpen) for file scope, empty string otherwise', () => {
- expect(SRC).toMatch(
- /input\s*!==\s*null\s*&&\s*input\.docContext\s*!==\s*null\s*\?\s*composeFilePrompt\(\s*input\.docContext\.relativePath\s*,\s*autoOpen\s*\)\s*:\s*['"]['"]\s*;/,
- );
- });
-
- test('data-testid pattern uses "empty-space-open-in-<id>" prefix', () => {
- expect(SRC).toMatch(/data-testid=\{`empty-space-open-in-\$\{target\.id\}`\}/);
- expect(SRC).toMatch(/data-testid="empty-space-open-in-claude-web-fallback"/);
- });
-
- test('does NOT depend on isElectronHost — install-state filter subsumes host detection', () => {
- expect(SRC).not.toMatch(/isElectronHost/);
- });
-});
diff --git a/packages/app/src/components/handoff/OpenInAgentMenu.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentMenu.dom.test.tsx
new file mode 100644
index 000000000..543b6520d
--- /dev/null
+++ b/packages/app/src/components/handoff/OpenInAgentMenu.dom.test.tsx
@@ -0,0 +1,171 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import type { TargetData } from '@inkeep/open-knowledge-core';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import type { HandoffDispatchInput } from './useHandoffDispatch';
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+const refreshCalls: string[] = [];
+const dispatchCalls: Array<{ target: string; input: HandoffDispatchInput }> = [];
+const fallbackPrompts: string[] = [];
+let states: Record<string, { installed: boolean | null; lastChecked?: number }> = {};
+
+mock.module('./useInstalledAgents', () => ({
+ useInstalledAgents: () => ({
+ states,
+ refresh: () => {
+ refreshCalls.push('refresh');
+ return Promise.resolve();
+ },
+ }),
+}));
+
+mock.module('./useHandoffDispatch', () => ({
+ useHandoffDispatch: () => ({
+ dispatch: (target: string, input: HandoffDispatchInput) => {
+ dispatchCalls.push({ target, input });
+ return Promise.resolve({ ok: true as const });
+ },
+ }),
+}));
+
+mock.module('@/lib/config-context', () => ({
+ useConfigContext: () => ({
+ merged: { appearance: { preview: { autoOpen: true } } },
+ }),
+}));
+
+mock.module('@/hooks/use-is-embedded', () => ({
+ useIsEmbedded: () => false,
+}));
+
+const successToastForWebFallback = (displayName: string) =>
+ `Opened ${displayName} in your browser.`;
+
+mock.module('./OpenInAgentMenuItem', () => ({
+ OpenInAgentMenuItem: ({ target, onSelect }: { target: TargetData; onSelect: () => void }) => (
+ <button type="button" data-testid={`open-in-agent-row-${target.id}`} onClick={onSelect}>
+ {target.displayName}
+ </button>
+ ),
+ dispatchClaudeWebFallback: (prompt: string) => {
+ fallbackPrompts.push(prompt);
+ return Promise.resolve();
+ },
+ successToastForWebFallback,
+}));
+
+const input: HandoffDispatchInput = {
+ docContext: { relativePath: 'docs/notes.md' },
+ projectDir: '/tmp/project',
+ docPath: '/tmp/project/docs/notes.md',
+};
+
+async function renderMenu(menuInput: HandoffDispatchInput | null = input) {
+ const { OpenInAgentMenu } = await import('./OpenInAgentMenu');
+ render(
+ <TooltipProvider>
+ <OpenInAgentMenu input={menuInput} />
+ </TooltipProvider>,
+ );
+}
+
+async function openMenu() {
+ await userEvent.click(screen.getByTestId('open-in-agent-trigger'));
+ await waitFor(() => {
+ expect(screen.getByTestId('open-in-agent-menu')).toBeTruthy();
+ });
+}
+
+describe('OpenInAgentMenu runtime behavior', () => {
+ afterEach(() => {
+ cleanup();
+ refreshCalls.length = 0;
+ dispatchCalls.length = 0;
+ fallbackPrompts.length = 0;
+ states = {};
+ });
+
+ test('exports the shell component and success toast re-export', async () => {
+ const mod = await import('./OpenInAgentMenu');
+ const itemMod = await import('./OpenInAgentMenuItem');
+
+ expect(typeof mod.OpenInAgentMenu).toBe('function');
+ expect(mod.successToastForWebFallback).toBe(itemMod.successToastForWebFallback);
+ });
+
+ test('trigger uses visible Open with AI text as its accessible name', async () => {
+ await renderMenu();
+
+ const trigger = screen.getByTestId('open-in-agent-trigger');
+ expect(trigger.textContent).toContain('Open with AI');
+ expect(trigger.getAttribute('aria-label')).toBeNull();
+ expect(screen.getByRole('button', { name: 'Open with AI' })).toBe(trigger);
+ });
+
+ test('disabled trigger still keeps the visible Open with AI label when no input exists', async () => {
+ await renderMenu(null);
+
+ const trigger = screen.getByRole('button', { name: 'Open with AI' }) as HTMLButtonElement;
+ expect(trigger.disabled).toBe(true);
+ expect(trigger.getAttribute('aria-label')).toBeNull();
+ });
+
+ test('open refreshes install state and renders only installed visible targets', async () => {
+ states = {
+ 'claude-cowork': { installed: true, lastChecked: 1 },
+ 'claude-code': { installed: true, lastChecked: 1 },
+ codex: { installed: true, lastChecked: 1 },
+ cursor: { installed: true, lastChecked: 1 },
+ };
+ await renderMenu();
+ await openMenu();
+
+ expect(refreshCalls).toEqual(['refresh']);
+ expect(screen.getByTestId('open-in-agent-row-claude-code')).toBeTruthy();
+ expect(screen.getByTestId('open-in-agent-row-codex')).toBeTruthy();
+ expect(screen.getByTestId('open-in-agent-row-cursor')).toBeTruthy();
+ expect(screen.queryByTestId('open-in-agent-row-claude-cowork')).toBeNull();
+
+ await userEvent.click(screen.getByTestId('open-in-agent-row-codex'));
+ expect(dispatchCalls).toEqual([{ target: 'codex', input }]);
+ });
+
+ test('Claude web fallback appears when the visible Claude row is not installed', async () => {
+ states = {
+ 'claude-cowork': { installed: true, lastChecked: 1 },
+ 'claude-code': { installed: false, lastChecked: 1 },
+ codex: { installed: false, lastChecked: 1 },
+ cursor: { installed: false, lastChecked: 1 },
+ };
+ await renderMenu();
+ await openMenu();
+
+ const fallback = screen.getByTestId('open-in-agent-claude-web-fallback');
+ expect(fallback.textContent).toContain('Open in claude.ai');
+
+ await userEvent.click(fallback);
+ expect(fallbackPrompts).toHaveLength(1);
+ expect(fallbackPrompts[0]).toContain('docs/notes.md');
+ });
+
+ test('Claude web fallback is hidden when claude-code is installed', async () => {
+ states = {
+ 'claude-cowork': { installed: false, lastChecked: 1 },
+ 'claude-code': { installed: true, lastChecked: 1 },
+ };
+ await renderMenu();
+ await openMenu();
+
+ expect(screen.queryByTestId('open-in-agent-claude-web-fallback')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/handoff/OpenInAgentMenu.test.ts b/packages/app/src/components/handoff/OpenInAgentMenu.test.ts
deleted file mode 100644
index b09b256e2..000000000
--- a/packages/app/src/components/handoff/OpenInAgentMenu.test.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './OpenInAgentMenu?raw';
-
-describe('OpenInAgentMenu module surface', () => {
- test('exports the shell component', async () => {
- const mod = await import('./OpenInAgentMenu');
- expect(typeof mod.OpenInAgentMenu).toBe('function');
- });
-
- test('re-exports successToastForWebFallback for surface-level wiring', async () => {
- const mod = await import('./OpenInAgentMenu');
- expect(typeof mod.successToastForWebFallback).toBe('function');
- const itemMod = await import('./OpenInAgentMenuItem');
- expect(mod.successToastForWebFallback).toBe(itemMod.successToastForWebFallback);
- });
-});
-
-describe('OpenInAgentMenu source-level guards', () => {
- test('renders only the VISIBLE_TARGETS subset (cowork hidden from this surface)', () => {
- expect(SRC).toMatch(
- /installedTargets\s*=\s*VISIBLE_TARGETS\.filter\(\s*\(target\)\s*=>\s*states\[target\.id\]\?\.installed\s*===\s*true,?\s*\)/,
- );
- });
-
- test('claudeInstalled probe keys off the visible claude-code row', () => {
- expect(SRC).toMatch(/states\[['"]claude-code['"]\]\?\.installed\s*===\s*true/);
- expect(SRC).not.toContain("states['claude-cowork']");
- });
-
- test('preserves the always-visible Claude web fallback when !claudeInstalled', () => {
- expect(SRC).toContain('open-in-agent-claude-web-fallback');
- expect(SRC).toContain('Open in claude.ai');
- expect(SRC).toContain('!claudeInstalled && !isSelectionScope');
- expect(SRC).toContain('const isSelectionScope');
- });
-
- test('trigger shows a visible "Open with AI" label with NO aria-label override (WCAG 2.5.3)', () => {
- expect(SRC).toMatch(/<Trans>Open with AI<\/Trans>/);
- const triggerOpenTag = SRC.match(
- /<Button\b[\s\S]*?data-testid="open-in-agent-trigger"[\s\S]*?>/,
- );
- expect(triggerOpenTag).not.toBeNull();
- expect(triggerOpenTag?.[0]).not.toMatch(/aria-label/);
- });
-
- test('does NOT wrap its labeled trigger in a redundant Tooltip (visible "Open with AI" text is the affordance)', () => {
- expect(SRC).not.toContain("from '@/components/ui/tooltip'");
- expect(SRC).not.toContain('<TooltipContent>');
- expect(SRC).toContain('<Trans>Open with AI</Trans>');
- });
-
- test('opens from click on the Electron host (macOS drag region swallows pointerdown)', () => {
- expect(SRC).toMatch(/onClick=\{\s*isElectronHost/);
- expect(SRC).toMatch(/onPointerDown=\{\s*isElectronHost/);
- expect(SRC).toContain('sawPointerDownRef');
- });
-});
diff --git a/packages/app/src/components/handoff/OpenInAgentMenuItem.dom.test.tsx b/packages/app/src/components/handoff/OpenInAgentMenuItem.dom.test.tsx
new file mode 100644
index 000000000..b473ffad5
--- /dev/null
+++ b/packages/app/src/components/handoff/OpenInAgentMenuItem.dom.test.tsx
@@ -0,0 +1,102 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import type { ReactNode } from 'react';
+import { DropdownMenu, DropdownMenuContent } from '@/components/ui/dropdown-menu';
+import { KNOWN_TARGETS } from '@/lib/handoff/targets';
+
+mock.module('@lingui/core/macro', () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+}));
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+mock.module('next-themes', () => ({
+ useTheme: () => ({ resolvedTheme: 'light' }),
+}));
+
+function target(id: (typeof KNOWN_TARGETS)[number]['id']) {
+ const found = KNOWN_TARGETS.find((entry) => entry.id === id);
+ if (!found) throw new Error(`missing target ${id}`);
+ return found;
+}
+
+function renderMenuItem(children: ReactNode) {
+ render(
+ <DropdownMenu open>
+ <DropdownMenuContent>{children}</DropdownMenuContent>
+ </DropdownMenu>,
+ );
+}
+
+describe('OpenInAgentMenuItem runtime behavior', () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('enabled row dispatches through onSelect with an accessible target label', async () => {
+ const { OpenInAgentMenuItem } = await import('./OpenInAgentMenuItem');
+ const selected: string[] = [];
+ renderMenuItem(
+ <OpenInAgentMenuItem
+ target={target('codex')}
+ installState={{ installed: true, lastChecked: 1 }}
+ isElectronHost
+ prompt="Open docs/notes.md"
+ onSelect={() => selected.push('codex')}
+ />,
+ );
+
+ await userEvent.click(screen.getByRole('menuitem', { name: 'Open with AI Codex' }));
+
+ expect(selected).toEqual(['codex']);
+ });
+
+ test('not-installed Claude row exposes install and web-fallback submenu affordances', async () => {
+ const { OpenInAgentMenuItem } = await import('./OpenInAgentMenuItem');
+ const openedUrls: string[] = [];
+ const webFallbackSuccesses: string[] = [];
+ renderMenuItem(
+ <OpenInAgentMenuItem
+ target={target('claude-code')}
+ installState={{ installed: false, lastChecked: 1 }}
+ isElectronHost
+ prompt="Open docs/notes.md"
+ onSelect={() => {
+ throw new Error('disabled row should not dispatch');
+ }}
+ openExternal={async (url) => {
+ openedUrls.push(url);
+ return { ok: true };
+ }}
+ onWebFallbackSuccess={(entry) => webFallbackSuccesses.push(entry.id)}
+ />,
+ );
+
+ const trigger = screen.getByRole('menuitem', { name: 'Open with AI Claude, Not installed' });
+ expect(trigger.getAttribute('data-row-disabled')).toBe('');
+
+ await userEvent.hover(trigger);
+ await waitFor(() => {
+ expect(screen.getByTestId('open-in-agent-submenu-claude-code')).toBeTruthy();
+ });
+
+ expect(screen.getByTestId('open-in-agent-message-claude-code').textContent).toBe(
+ 'Requires Claude Desktop.',
+ );
+ await userEvent.click(screen.getByTestId('open-in-agent-install-claude-code'));
+ await userEvent.click(screen.getByTestId('open-in-agent-web-fallback-claude-code'));
+
+ expect(openedUrls[0]).toBe('https://claude.com/download');
+ expect(openedUrls[1]).toContain('https://claude.ai/new?q=');
+ expect(decodeURIComponent(openedUrls[1].split('q=')[1] ?? '')).toBe('Open docs/notes.md');
+ expect(webFallbackSuccesses).toEqual(['claude-code']);
+ });
+});
diff --git a/packages/app/src/components/handoff/OpenInAgentMenuItem.test.ts b/packages/app/src/components/handoff/OpenInAgentMenuItem.test.ts
index 56b057c2d..ae96634d0 100644
--- a/packages/app/src/components/handoff/OpenInAgentMenuItem.test.ts
+++ b/packages/app/src/components/handoff/OpenInAgentMenuItem.test.ts
@@ -1,7 +1,6 @@
import { describe, expect, test } from 'bun:test';
import type { InstallState, TargetData } from '@inkeep/open-knowledge-core';
import { KNOWN_TARGETS } from '@/lib/handoff/targets';
-import SRC from './OpenInAgentMenuItem?raw';
function targetById(id: TargetData['id']): TargetData {
const found = KNOWN_TARGETS.find((t) => t.id === id);
@@ -277,19 +276,6 @@ describe('successToastForWebFallback — distinct from dispatch toast copy', ()
});
});
-describe('OpenInAgentMenuItem source-level guards', () => {
- test('enabled branch dispatches via onSelect (no install-skill side door)', () => {
- expect(SRC).toMatch(/onSelect=\{onSelect\}/);
- expect(SRC).toMatch(/Open with AI \$\{targetDisplayName\}/);
- });
-
- test('not-installed branch (DropdownMenuSub with install + web fallback) is preserved', () => {
- expect(SRC).toContain('DropdownMenuSubTrigger');
- expect(SRC).toContain('open-in-agent-install-');
- expect(SRC).toContain('open-in-agent-web-fallback-');
- });
-});
-
describe('install-state cardinality used by the dropdown', () => {
test('every KNOWN_TARGETS entry maps to one of the three branches under any install state', async () => {
const { computeRowState } = await import('./OpenInAgentMenuItem');
diff --git a/packages/app/src/components/settings/OkignoreSection.dom.test.tsx b/packages/app/src/components/settings/OkignoreSection.dom.test.tsx
new file mode 100644
index 000000000..63976d034
--- /dev/null
+++ b/packages/app/src/components/settings/OkignoreSection.dom.test.tsx
@@ -0,0 +1,334 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { emitConfigIgnoreNestedError } from '@/lib/config-ignore-nested-error-events';
+import { emitConfigValidationRejected } from '@/lib/config-validation-events';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+const toast = {
+ error: mock((_message: string, _opts?: unknown) => {}),
+};
+
+type DragEndHandler = (event: { active: { id: string }; over: { id: string } | null }) => void;
+let latestDragEnd: DragEndHandler | null = null;
+const pointerSensorToken = { name: 'PointerSensor' };
+const keyboardSensorToken = { name: 'KeyboardSensor' };
+const sortableKeyboardCoordinatesToken = { name: 'sortableKeyboardCoordinates' };
+const verticalListSortingStrategyToken = { name: 'verticalListSortingStrategy' };
+const localStorageMap = new Map<string, string>();
+
+function installLocalStorage() {
+ const storage = {
+ clear: () => localStorageMap.clear(),
+ getItem: (key: string) => localStorageMap.get(key) ?? null,
+ key: (index: number) => Array.from(localStorageMap.keys())[index] ?? null,
+ removeItem: (key: string) => {
+ localStorageMap.delete(key);
+ },
+ setItem: (key: string, value: string) => {
+ localStorageMap.set(key, value);
+ },
+ get length() {
+ return localStorageMap.size;
+ },
+ } as Storage;
+ Object.defineProperty(globalThis, 'localStorage', {
+ configurable: true,
+ value: storage,
+ });
+}
+
+mock.module('@lingui/react/macro', () => ({
+ Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (
+ <>{(value === 1 ? one : other).replace('#', String(value))}</>
+ ),
+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+mock.module('sonner', () => ({
+ toast,
+}));
+
+mock.module('@dnd-kit/core', () => ({
+ closestCenter: { name: 'closestCenter' },
+ DndContext: ({ children, onDragEnd }: { children?: ReactNode; onDragEnd?: DragEndHandler }) => {
+ latestDragEnd = onDragEnd ?? null;
+ return <div data-testid="okignore-dnd-context">{children}</div>;
+ },
+ KeyboardSensor: keyboardSensorToken,
+ PointerSensor: pointerSensorToken,
+ useSensor: (sensor: unknown, options: unknown) => ({ sensor, options }),
+ useSensors: (...sensors: unknown[]) => sensors,
+}));
+
+mock.module('@dnd-kit/sortable', () => ({
+ SortableContext: ({
+ children,
+ items,
+ strategy,
+ }: {
+ children?: ReactNode;
+ items: string[];
+ strategy: unknown;
+ }) => (
+ <div
+ data-items={items.join('|')}
+ data-strategy={strategy === verticalListSortingStrategyToken ? 'vertical' : 'unknown'}
+ data-testid="okignore-sortable-context"
+ >
+ {children}
+ </div>
+ ),
+ sortableKeyboardCoordinates: sortableKeyboardCoordinatesToken,
+ useSortable: ({ id }: { id: string }) => ({
+ attributes: { 'data-sortable-attr-id': id },
+ isDragging: false,
+ listeners: {},
+ setNodeRef: () => {},
+ transform: null,
+ transition: undefined,
+ }),
+ verticalListSortingStrategy: verticalListSortingStrategyToken,
+}));
+
+mock.module('@dnd-kit/utilities', () => ({
+ CSS: {
+ Transform: {
+ toString: () => undefined,
+ },
+ },
+}));
+
+mock.module('@/components/ui/button', () => ({
+ Button: ({
+ children,
+ size: _size,
+ variant: _variant,
+ ...props
+ }: {
+ children?: ReactNode;
+ size?: string;
+ variant?: string;
+ [key: string]: unknown;
+ }) => (
+ <button type="button" {...props}>
+ {children}
+ </button>
+ ),
+}));
+
+mock.module('@/components/ui/input', () => ({
+ Input: (props: Record<string, unknown>) => <input {...props} />,
+}));
+
+mock.module('@/components/ui/skeleton', () => ({
+ Skeleton: ({ className }: { className?: string }) => (
+ <div className={className} data-testid="skeleton" />
+ ),
+}));
+
+mock.module('@/components/ui/tooltip', () => ({
+ Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ TooltipContent: ({ children }: { children?: ReactNode }) => <div role="tooltip">{children}</div>,
+ TooltipTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,
+}));
+
+mock.module('@/components/PageListContext', () => ({
+ usePageList: () => ({
+ assetPaths: new Set(['assets/logo.png']),
+ pageMeta: new Map([
+ ['docs/guide', { docExt: '.md' }],
+ ['drafts/note', { docExt: '.mdx' }],
+ ]),
+ pages: new Set(['docs/guide', 'drafts/note']),
+ }),
+}));
+
+function createBinding(initialText: string) {
+ let currentText = initialText;
+ const textListeners = new Set<(next: string) => void>();
+ const rejectionListeners = new Set<(event: { error: unknown }) => void>();
+ return {
+ current: () => currentText,
+ notifyRejection: (error: unknown) => {
+ for (const listener of rejectionListeners) listener({ error });
+ },
+ patch: mock((next: string) => {
+ currentText = next;
+ for (const listener of textListeners) listener(next);
+ return { ok: true };
+ }),
+ setText(next: string) {
+ currentText = next;
+ for (const listener of textListeners) listener(next);
+ },
+ subscribe: (listener: (next: string) => void) => {
+ textListeners.add(listener);
+ return () => textListeners.delete(listener);
+ },
+ subscribeRejection: (listener: (event: { error: unknown }) => void) => {
+ rejectionListeners.add(listener);
+ return () => rejectionListeners.delete(listener);
+ },
+ };
+}
+
+async function renderSection({
+ binding = createBinding(''),
+ synced = true,
+}: {
+ binding?: ReturnType<typeof createBinding> | null;
+ synced?: boolean;
+} = {}) {
+ const { OkignoreSection } = await import('./OkignoreSection');
+ render(<OkignoreSection binding={binding as never} synced={synced} />);
+ return binding;
+}
+
+describe('OkignoreSection runtime behavior', () => {
+ beforeEach(() => {
+ cleanup();
+ latestDragEnd = null;
+ toast.error.mockClear();
+ installLocalStorage();
+ localStorage.clear();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('renders skeleton until the binding is available and synced', async () => {
+ await renderSection({ binding: null, synced: false });
+ expect(screen.getByTestId('settings-okignore-skeleton')).toBeTruthy();
+ expect(screen.getByText('Ignore patterns')).toBeTruthy();
+ });
+
+ test('empty state uses plain language, primer link semantics, and disabled add until nonblank input', async () => {
+ const binding = await renderSection();
+
+ expect(screen.getByTestId('settings-okignore-section').getAttribute('aria-labelledby')).toBe(
+ 'settings-okignore-title',
+ );
+ expect(screen.getByText('Ignore patterns')).toBeTruthy();
+ expect(screen.getByText(/Hide files and folders/)).toBeTruthy();
+ expect(screen.getByTestId('settings-okignore-empty').textContent?.toLowerCase()).not.toContain(
+ 'gitignore',
+ );
+ const primer = screen.getByTestId('settings-okignore-primer') as HTMLAnchorElement;
+ expect(primer.textContent).toBe('Learn more about patterns');
+ expect(primer.target).toBe('_blank');
+ expect(primer.rel).toBe('noreferrer noopener');
+
+ const input = screen.getByTestId('settings-okignore-add-input') as HTMLInputElement;
+ const button = screen.getByTestId('settings-okignore-add-button') as HTMLButtonElement;
+ expect(button.disabled).toBe(true);
+ fireEvent.change(input, { target: { value: ' drafts/ ' } });
+ expect(button.disabled).toBe(false);
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(binding?.patch).toHaveBeenCalledWith('drafts/\n');
+ });
+
+ test('list rows edit on blur, remove by button, and skip duplicate add', async () => {
+ const binding = await renderSection({ binding: createBinding('drafts/\nassets/*.png\n') });
+ await screen.findByTestId('settings-okignore-list');
+
+ const rows = screen.getAllByTestId('settings-okignore-row');
+ expect(rows).toHaveLength(2);
+ expect(screen.getByTestId('okignore-sortable-context').getAttribute('data-strategy')).toBe(
+ 'vertical',
+ );
+ expect(
+ screen.getAllByTestId('settings-okignore-drag-handle')[0].getAttribute('aria-label'),
+ ).toBe('Drag drafts/ to reorder');
+
+ const firstInput = within(rows[0]).getByTestId(
+ 'settings-okignore-row-input',
+ ) as HTMLInputElement;
+ fireEvent.focus(firstInput);
+ fireEvent.change(firstInput, { target: { value: 'notes/private/' } });
+ fireEvent.blur(firstInput);
+ await waitFor(() => {
+ expect(binding?.patch).toHaveBeenCalledWith('notes/private/\nassets/*.png\n');
+ });
+
+ binding?.patch.mockClear();
+ const addInput = screen.getByTestId('settings-okignore-add-input') as HTMLInputElement;
+ fireEvent.change(addInput, { target: { value: 'assets/*.png' } });
+ fireEvent.click(screen.getByTestId('settings-okignore-add-button'));
+ expect(binding?.patch).not.toHaveBeenCalled();
+
+ const rowsAfterEdit = screen.getAllByTestId('settings-okignore-row');
+ fireEvent.click(within(rowsAfterEdit[1]).getByTestId('settings-okignore-remove'));
+ await waitFor(() => {
+ expect(binding?.patch).toHaveBeenCalledWith('notes/private/\n');
+ });
+ });
+
+ test('reorders pattern rows through the drag-end handler', async () => {
+ const binding = await renderSection({ binding: createBinding('drafts/\nassets/*.png\n') });
+ await screen.findByTestId('settings-okignore-list');
+
+ act(() => {
+ latestDragEnd?.({
+ active: { id: 'okignore-pattern-0' },
+ over: { id: 'okignore-pattern-1' },
+ });
+ });
+ expect(binding?.patch).toHaveBeenCalledWith('assets/*.png\ndrafts/\n');
+ });
+
+ test('advanced raw editor persists toggle state and flushes raw text on blur', async () => {
+ const binding = await renderSection({ binding: createBinding('# keep comments\ndrafts/\n') });
+
+ fireEvent.click(screen.getByTestId('settings-okignore-show-advanced-toggle'));
+ expect(localStorage.getItem('okignore-show-advanced')).toBe('true');
+
+ const textarea = screen.getByTestId(
+ 'settings-okignore-advanced-textarea',
+ ) as HTMLTextAreaElement;
+ expect(textarea.value).toBe('# keep comments\ndrafts/\n');
+ fireEvent.change(textarea, {
+ target: { value: '# keep comments\nprivate/\n!private/keep.md\n' },
+ });
+ fireEvent.blur(textarea);
+ expect(binding?.patch).toHaveBeenCalledWith('# keep comments\nprivate/\n!private/keep.md\n');
+
+ fireEvent.click(screen.getByTestId('settings-okignore-show-advanced-toggle'));
+ expect(localStorage.getItem('okignore-show-advanced')).toBe('false');
+ });
+
+ test('preview, rejection banner, and nested-error toast are runtime side effects', async () => {
+ const binding = await renderSection({ binding: createBinding('docs/**\n') });
+
+ const visiblePreview = screen
+ .getAllByTestId('settings-okignore-preview')
+ .find((el) => el.getAttribute('data-preview-state') === 'visible');
+ expect(visiblePreview?.getAttribute('data-preview-count')).toBe('1');
+
+ act(() => {
+ emitConfigValidationRejected({
+ docName: '__config__/okignore',
+ error: {
+ code: 'OKIGNORE_INVALID',
+ detail: 'bad glob',
+ lineNumber: 3,
+ },
+ } as never);
+ });
+ expect(binding?.current()).toBe('docs/**\n');
+ expect((await screen.findByTestId('settings-okignore-rejection-banner')).textContent).toBe(
+ 'Pattern syntax error (line 3): bad glob',
+ );
+
+ act(() => {
+ emitConfigIgnoreNestedError({ path: 'nested/.okignore', error: 'parse failed' } as never);
+ });
+ expect(toast.error).toHaveBeenCalledWith('Nested .okignore error in nested/.okignore', {
+ description: 'parse failed',
+ duration: 8000,
+ id: 'okignore-nested-error:nested/.okignore',
+ });
+ });
+});
diff --git a/packages/app/src/components/settings/OkignoreSection.test.ts b/packages/app/src/components/settings/OkignoreSection.test.ts
index 0cfdacb4a..2b43190d5 100644
--- a/packages/app/src/components/settings/OkignoreSection.test.ts
+++ b/packages/app/src/components/settings/OkignoreSection.test.ts
@@ -1,6 +1,4 @@
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
import {
derivePreviewPaths,
parseRows,
@@ -8,462 +6,81 @@ import {
writeShowAdvanced,
} from './OkignoreSection';
-const SECTION_SRC = readFileSync(join(__dirname, 'OkignoreSection.tsx'), 'utf8');
-const PANE_SRC = readFileSync(join(__dirname, 'SettingsDialogBody.tsx'), 'utf8');
-const CONFIG_PROVIDER_SRC = readFileSync(
- join(__dirname, '..', '..', 'lib', 'config-provider.tsx'),
- 'utf8',
-);
-
describe('OkignoreSection module', () => {
- test('exports OkignoreSection component', async () => {
+ test('loads the component and exported helpers', async () => {
const mod = await import('./OkignoreSection');
expect(typeof mod.OkignoreSection).toBe('function');
- });
-
- test('exports parseRows helper for empty-state detection', async () => {
- const mod = await import('./OkignoreSection');
expect(typeof mod.parseRows).toBe('function');
- });
-});
-
-describe('OkignoreSection source-level guards', () => {
- test('renders Ignore patterns heading + ARIA label', () => {
- expect(SECTION_SRC).toContain('Ignore patterns');
- expect(SECTION_SRC).toContain('aria-labelledby="settings-okignore-title"');
- expect(SECTION_SRC).toContain('id="settings-okignore-title"');
- });
-
- test('empty-state copy is plain-language and avoids the word "gitignore"', () => {
- const visibleSrc = SECTION_SRC.replace(/\/\*[\s\S]*?\*\//g, '')
- .replace(/(?<!:)\/\/[^\n]*/g, '')
- .replace(/PRIMER_HREF\s*=\s*['"][^'"]*['"]/g, '');
- expect(visibleSrc).not.toMatch(/gitignore/i);
- });
-
- test('renders empty-state hint about hiding files', () => {
- expect(SECTION_SRC).toContain('No patterns yet');
- expect(SECTION_SRC).toContain('Hide files and folders');
- });
-
- test('exposes a primer link for users who want to learn pattern syntax', () => {
- expect(SECTION_SRC).toContain('PRIMER_HREF');
- expect(SECTION_SRC).toContain('Learn more about patterns');
- expect(SECTION_SRC).toMatch(/target="_blank"/);
- expect(SECTION_SRC).toMatch(/rel="noreferrer noopener"/);
- });
-
- test('renders a loading skeleton until the binding has synced', () => {
- expect(SECTION_SRC).toContain('binding === null || !synced');
- expect(SECTION_SRC).toMatch(/from\s+['"]@\/components\/ui\/skeleton['"]/);
- expect(SECTION_SRC).toContain('OkignoreSectionSkeleton');
- });
-
- test('uses shadcn Input + Button for the add-pattern affordance', () => {
- expect(SECTION_SRC).toMatch(/from\s+['"]@\/components\/ui\/input['"]/);
- expect(SECTION_SRC).toMatch(/from\s+['"]@\/components\/ui\/button['"]/);
- expect(SECTION_SRC).toContain('Add pattern');
- });
-
- test('add-pattern button is disabled until the user types something non-blank', () => {
- expect(SECTION_SRC).toMatch(/disabled=\{pending\.trim\(\)\.length\s*===\s*0\}/);
- });
-
- test('Enter key on the add-input commits via the same path as the button', () => {
- expect(SECTION_SRC).toMatch(/onKeyDown=/);
- expect(SECTION_SRC).toMatch(/e\.key\s*===\s*'Enter'/);
- expect(SECTION_SRC).toContain('e.preventDefault()');
- });
-
- test('commit goes through binding.patch with bytes from the pure serializer', () => {
- expect(SECTION_SRC).toContain('binding.current()');
- expect(SECTION_SRC).toContain('binding.patch(');
- expect(SECTION_SRC).toMatch(/serializeOkignoreDoc\(/);
- });
-
- test('subscribes to binding text updates and re-derives rows on every change', () => {
- expect(SECTION_SRC).toContain('binding.subscribe(');
- expect(SECTION_SRC).toMatch(/parseOkignoreDoc\(text\)/);
- expect(SECTION_SRC).toMatch(/listPatterns\(doc\)/);
- });
-
- test('renders existing patterns as a divided list of editable rows', () => {
- expect(SECTION_SRC).toContain('settings-okignore-list');
- expect(SECTION_SRC).toContain('settings-okignore-row');
- expect(SECTION_SRC).toMatch(/font-mono/);
- });
-
- test('each row exposes a remove (×) button wired to onRemove', () => {
- expect(SECTION_SRC).toContain('settings-okignore-remove');
- expect(SECTION_SRC).toMatch(/aria-label=\{t`Remove \$\{patternText\}`\}/);
- expect(SECTION_SRC).toMatch(/onClick=\{\(\)\s*=>\s*onRemove\(patternIndex\)\}/);
- });
-
- test('each row commits an edit on focus-out via the binding', () => {
- expect(SECTION_SRC).toMatch(/onBlur=/);
- expect(SECTION_SRC).toMatch(/handleCommit/);
- expect(SECTION_SRC).toMatch(/lastSyncedRef/);
- expect(SECTION_SRC).toMatch(/focusedRef/);
- });
-
- test('Enter key commits via the same path as blur (uses currentTarget.blur)', () => {
- expect(SECTION_SRC).toMatch(/e\.key === 'Enter'/);
- expect(SECTION_SRC).toContain('e.preventDefault()');
- expect(SECTION_SRC).toMatch(/\(e\.currentTarget as HTMLInputElement\)\.blur\(\)/);
- });
-
- test('Escape key reverts the draft to the last synced value', () => {
- expect(SECTION_SRC).toMatch(/e\.key === 'Escape'/);
- expect(SECTION_SRC).toMatch(/setDraft\(lastSyncedRef\.current\)/);
- });
-
- test('exposes a drag handle on every row using @dnd-kit/sortable', () => {
- expect(SECTION_SRC).toContain('settings-okignore-drag-handle');
- expect(SECTION_SRC).toMatch(/from\s+['"]@dnd-kit\/sortable['"]/);
- expect(SECTION_SRC).toMatch(/useSortable\(\{\s*id:\s*sortableId/);
- expect(SECTION_SRC).toMatch(/GripVertical/);
- });
-
- test('wraps the row list in DndContext + SortableContext (vertical strategy)', () => {
- expect(SECTION_SRC).toMatch(/<DndContext/);
- expect(SECTION_SRC).toMatch(/<SortableContext/);
- expect(SECTION_SRC).toMatch(/verticalListSortingStrategy/);
- expect(SECTION_SRC).toMatch(/closestCenter/);
- });
-
- test('reorder handler delegates to the pure reorderPatterns op', () => {
- expect(SECTION_SRC).toContain('handleDragEnd');
- expect(SECTION_SRC).toMatch(/reorderPatterns\(doc,\s*fromIndex,\s*toIndex\)/);
- });
-
- test('add / remove / edit go through the pure structural ops, not ad-hoc string surgery', () => {
- expect(SECTION_SRC).toMatch(/appendPattern\(doc,\s*trimmed\)/);
- expect(SECTION_SRC).toMatch(/removePatternAt\(doc,\s*patternIndex\)/);
- expect(SECTION_SRC).toMatch(/editPatternAt\(doc,\s*patternIndex,\s*trimmed\)/);
- });
-
- test('handleAdd flashes the existing row and skips commit when the pattern is a duplicate', () => {
- expect(SECTION_SRC).toMatch(/findPatternIndex\(doc,\s*trimmed\)/);
- const handleAddIdx = SECTION_SRC.indexOf('const handleAdd');
- expect(handleAddIdx).toBeGreaterThan(-1);
- const handleAddEnd = SECTION_SRC.indexOf('\n };', handleAddIdx);
- expect(handleAddEnd).toBeGreaterThan(handleAddIdx);
- const fragment = SECTION_SRC.slice(handleAddIdx, handleAddEnd);
- const findIdx = fragment.indexOf('findPatternIndex(');
- const commitIdx = fragment.indexOf('commit(');
- expect(findIdx).toBeGreaterThan(-1);
- expect(commitIdx).toBeGreaterThan(findIdx);
- expect(fragment).toMatch(/existingIndex\s*>=\s*0/);
- expect(fragment).toMatch(/triggerFlash\(rowFlashKey\(trimmed,\s*existingIndex\)\)/);
- const flashMatch = fragment.match(/triggerFlash\(rowFlashKey\(trimmed,\s*existingIndex\)\);/);
- expect(flashMatch).not.toBeNull();
- const flashEnd = (flashMatch?.index ?? 0) + (flashMatch?.[0].length ?? 0);
- expect(fragment.slice(flashEnd, fragment.indexOf('commit(', flashEnd))).toMatch(/\breturn;/);
- });
-
- test('per-row SavedIndicator flashes a green check on commit (matches SettingsDialog pattern)', () => {
- expect(SECTION_SRC).toContain('settings-okignore-saved-indicator');
- expect(SECTION_SRC).toMatch(/text-emerald-600/);
- expect(SECTION_SRC).toMatch(/SAVED_FLASH_MS/);
- expect(SECTION_SRC).toMatch(/triggerFlash\(/);
- expect(SECTION_SRC).toMatch(/role="status"/);
- expect(SECTION_SRC).toMatch(/aria-live="polite"/);
- expect(SECTION_SRC).toContain('Saved');
- });
-
- test('flash timer is cleared on unmount to avoid setState on torn-down components', () => {
- expect(SECTION_SRC).toMatch(/flashTimerRef/);
- expect(SECTION_SRC).toMatch(/clearTimeout\(flashTimerRef\.current\)/);
- });
-
- test('parseRows is implemented in terms of the pure parser (single source of truth)', () => {
- expect(SECTION_SRC).toMatch(/export function parseRows/);
- expect(SECTION_SRC).toMatch(/listPatterns\(parseOkignoreDoc\(text\)\)/);
- });
-
- test('does NOT route through the shadcn form harness — stays a sibling of SyncSection / IntegrationsSection', () => {
- expect(SECTION_SRC).not.toMatch(/from\s+['"]@\/components\/ui\/form['"]/);
- expect(SECTION_SRC).not.toMatch(/<FormField\b/);
- expect(SECTION_SRC).not.toMatch(/useConfigForm\(/);
- });
-
- test('does NOT instantiate its own HocuspocusProvider (binding lives at ConfigProvider)', () => {
- expect(SECTION_SRC).not.toMatch(/HocuspocusProvider/);
- expect(SECTION_SRC).not.toMatch(/new\s+Y\.Doc\b/);
- });
-});
-
-describe('OkignoreSection wiring in SettingsDialog', () => {
- test('imports OkignoreSection from a sibling module', () => {
- expect(PANE_SRC).toMatch(/from\s+['"]\.\/OkignoreSection['"]/);
- expect(PANE_SRC).toContain('OkignoreSection');
- });
-
- test('renders OkignoreSection under THIS PROJECT in the "Ignore patterns" sidebar item (D12 LOCKED)', () => {
- expect(PANE_SRC).toMatch(/activeId\s*===\s*['"]okignore['"]\s*\)[\s\S]*?<OkignoreSection\b/);
- });
-
- test('reads the binding + sync state from the ConfigProvider context', () => {
- expect(PANE_SRC).toMatch(/from\s+['"]@\/lib\/config-provider['"]/);
- expect(PANE_SRC).toContain('useConfigContext');
- expect(PANE_SRC).toMatch(/okignoreBinding/);
- expect(PANE_SRC).toMatch(/okignoreSynced/);
- });
-});
-
-describe('ConfigProvider okignore wiring', () => {
- test('mounts a Hocuspocus provider on __config__/okignore alongside the existing config docs', () => {
- expect(CONFIG_PROVIDER_SRC).toContain('CONFIG_DOC_NAME_OKIGNORE');
- expect(CONFIG_PROVIDER_SRC).toContain('bindOkignoreDoc');
- expect(CONFIG_PROVIDER_SRC).toContain('makeOkignoreBinding');
- });
-
- test('tracks the provider synced event via the standard "synced" listener', () => {
- expect(CONFIG_PROVIDER_SRC).toMatch(/provider\.on\('synced'/);
- expect(CONFIG_PROVIDER_SRC).toMatch(/provider\.off\('synced'/);
- });
-
- test('cleans up the okignore binding + provider on unmount', () => {
- expect(CONFIG_PROVIDER_SRC).toMatch(
- /for \(const scoped of \[[^\]]*\bokignoreScoped\b[^\]]*\]\)/,
- );
- expect(CONFIG_PROVIDER_SRC).toMatch(/scoped\.cleanup\(\)/);
- });
-
- test('does NOT attach a client-side IndexedDB persistence layer', () => {
- expect(CONFIG_PROVIDER_SRC).not.toMatch(/IndexeddbPersistence/);
- expect(CONFIG_PROVIDER_SRC).not.toMatch(/createClientPersistence/);
+ expect(typeof mod.derivePreviewPaths).toBe('function');
+ expect(typeof mod.readShowAdvanced).toBe('function');
+ expect(typeof mod.writeShowAdvanced).toBe('function');
});
});
describe('parseRows helper', () => {
- test('returns an empty array for an empty body', () => {
+ test('returns no rows for empty bodies, blanks, or comments', () => {
expect(parseRows('')).toEqual([]);
- });
-
- test('returns an empty array for a body of only blank lines', () => {
expect(parseRows('\n\n \n\t\n')).toEqual([]);
- });
-
- test('returns an empty array for a body of only comments', () => {
expect(parseRows('# header\n# another comment\n')).toEqual([]);
});
- test('returns each non-comment, non-blank line as a row, trimmed', () => {
- expect(parseRows('drafts/\n*.draft.md\n')).toEqual(['drafts/', '*.draft.md']);
+ test('returns each non-comment, non-blank line as a trimmed row', () => {
+ expect(parseRows('# header\n drafts/ \n\n\t*.tmp\t\n')).toEqual(['drafts/', '*.tmp']);
});
- test('skips comment lines interleaved with patterns', () => {
- expect(parseRows('# header\ndrafts/\n\n# section 2\n*.tmp\n')).toEqual(['drafts/', '*.tmp']);
- });
-
- test('strips leading and trailing whitespace from rows (display layer convenience)', () => {
- expect(parseRows(' drafts/ \n\t*.tmp\t\n')).toEqual(['drafts/', '*.tmp']);
- });
-
- test('treats a leading "#" character as a comment (no support for escaped # patterns in v1)', () => {
- expect(parseRows('# not a row\n#also-comment\nactual\n')).toEqual(['actual']);
+ test('treats a leading hash as a comment while preserving escaped hash patterns', () => {
+ expect(parseRows('# not a row\n\\#literal\nactual\n')).toEqual(['\\#literal', 'actual']);
});
});
-describe('OkignoreSection — US-009 heuristic warnings', () => {
- test('imports the heuristic checker from the pure module', () => {
- expect(SECTION_SRC).toMatch(/from\s+['"]\.\/okignore-warnings['"]/);
- expect(SECTION_SRC).toContain('checkHeuristicWarnings');
- });
-
- test('warning indicator is rendered next to row inputs and the add input', () => {
- expect(SECTION_SRC).toContain('settings-okignore-warning-indicator');
- expect(SECTION_SRC).toContain('WarningIndicator');
- });
-
- test('warnings are debounced ~150ms via a useEffect timer (per FR7 perceptual budget)', () => {
- expect(SECTION_SRC).toContain('HEURISTIC_DEBOUNCE_MS');
- expect(SECTION_SRC).toMatch(/HEURISTIC_DEBOUNCE_MS\s*=\s*150/);
- expect(SECTION_SRC).toContain('useDebouncedHeuristicWarnings');
- });
-
- test('warning indicator surfaces tooltip with all warning messages (shadcn Tooltip)', () => {
- expect(SECTION_SRC).toMatch(/from\s+['"]@\/components\/ui\/tooltip['"]/);
- expect(SECTION_SRC).toContain('TooltipTrigger');
- expect(SECTION_SRC).toContain('TooltipContent');
- expect(SECTION_SRC).toMatch(/AlertTriangle/);
- });
-
- test('warnings are non-blocking — commit still happens regardless of warnings array', () => {
- expect(SECTION_SRC).not.toMatch(/if\s*\(\s*warnings\.length\s*>\s*0\s*\)\s*return/);
- expect(SECTION_SRC).not.toMatch(/warnings\.length\s*>\s*0\s*&&[^\n]*binding\.patch/);
- });
-
- test('warning input gets an amber border but stays usable (no disabled state)', () => {
- expect(SECTION_SRC).toMatch(/border-amber-500\/60/);
- expect(SECTION_SRC).not.toMatch(/warnings\.length\s*>\s*0\s*\|\|\s*pending\.trim/);
- });
-});
-
-describe('OkignoreSection — US-009 L3 rejection routing', () => {
- test('subscribes to subscribeToConfigValidationRejected and filters by docName', () => {
- expect(SECTION_SRC).toMatch(/subscribeToConfigValidationRejected/);
- expect(SECTION_SRC).toContain('CONFIG_DOC_NAME_OKIGNORE');
- expect(SECTION_SRC).toMatch(/event\.docName\s*!==\s*CONFIG_DOC_NAME_OKIGNORE/);
- });
-
- test('routes matching rejections into the binding via notifyRejection', () => {
- expect(SECTION_SRC).toMatch(/binding\.notifyRejection\(event\.error\)/);
- });
-
- test('local rejection state is driven by binding.subscribeRejection', () => {
- expect(SECTION_SRC).toContain('binding.subscribeRejection');
- expect(SECTION_SRC).toContain('setRejection');
- });
-
- test('rejection banner renders an alert with the offending detail and lineNumber', () => {
- expect(SECTION_SRC).toContain('settings-okignore-rejection-banner');
- expect(SECTION_SRC).toContain('Pattern syntax error');
- expect(SECTION_SRC).toMatch(
- /lineNumber !== undefined\s*\?\s*t`Pattern syntax error \(line \$\{lineNumber\}\): \$\{message\}`/,
- );
- expect(SECTION_SRC).toMatch(/:\s*t`Pattern syntax error: \$\{message\}`/);
- });
-
- test('rejection banner uses a destructive color treatment (matches existing settings-flash UX)', () => {
- expect(SECTION_SRC).toMatch(/border-destructive/);
- expect(SECTION_SRC).toMatch(/text-destructive/);
- expect(SECTION_SRC).toMatch(/bg-destructive/);
- });
-
- test('rejection banner auto-dismisses after REJECTION_BANNER_MS via a cleanup-aware timer', () => {
- expect(SECTION_SRC).toContain('REJECTION_BANNER_MS');
- expect(SECTION_SRC).toMatch(/REJECTION_BANNER_MS\s*=\s*5000/);
- expect(SECTION_SRC).toMatch(/rejectionTimerRef/);
- expect(SECTION_SRC).toMatch(/clearTimeout\(rejectionTimerRef\.current\)/);
- });
-
- test('AddPatternRow flashes red briefly when a rejection arrives', () => {
- expect(SECTION_SRC).toContain('useRejectionFlash');
- expect(SECTION_SRC).toContain('REJECTION_FLASH_MS');
- expect(SECTION_SRC).toMatch(/REJECTION_FLASH_MS\s*=\s*600/);
- expect(SECTION_SRC).toMatch(/data-rejection-flashing/);
- expect(SECTION_SRC).toMatch(/border-destructive/);
- });
-
- test('rejection routing only fires for the okignore docName (does NOT swallow project/user rejections)', () => {
- expect(SECTION_SRC).toMatch(/event\.docName\s*!==\s*CONFIG_DOC_NAME_OKIGNORE\)\s*return/);
- });
-
- test('error-formatting uses humanFormat as the fallback for unknown error codes', () => {
- expect(SECTION_SRC).toContain('humanFormat');
- expect(SECTION_SRC).toContain('isKnownConfigError');
- });
-});
-
-describe('OkignoreSection — US-010 Show advanced toggle (source-level)', () => {
- test('exports the localStorage helpers used by the hook', () => {
- expect(SECTION_SRC).toMatch(/export function readShowAdvanced/);
- expect(SECTION_SRC).toMatch(/export function writeShowAdvanced/);
- });
-
- test('uses the spec-locked localStorage key (D14)', () => {
- expect(SECTION_SRC).toMatch(/SHOW_ADVANCED_LS_KEY\s*=\s*['"]okignore-show-advanced['"]/);
- });
-
- test('readShowAdvanced + writeShowAdvanced are wrapped in try/catch (real R3 boundary)', () => {
- expect(SECTION_SRC).toMatch(/function readShowAdvanced[\s\S]*?try\s*\{[\s\S]*?\}\s*catch/);
- expect(SECTION_SRC).toMatch(/function writeShowAdvanced[\s\S]*?try\s*\{[\s\S]*?\}\s*catch/);
- });
-
- test('toggle button uses aria-pressed reflecting the on/off state', () => {
- expect(SECTION_SRC).toContain('settings-okignore-show-advanced-toggle');
- expect(SECTION_SRC).toMatch(/aria-pressed=\{enabled\}/);
- });
-
- test('toggle label flips between "Show advanced" and "Hide advanced"', () => {
- expect(SECTION_SRC).toMatch(
- /enabled\s*\?\s*<Trans>Hide advanced<\/Trans>\s*:\s*<Trans>Show advanced<\/Trans>/,
- );
- });
-
- test('raw-text editor is rendered ONLY when the toggle is on (replaces list/empty-state)', () => {
- expect(SECTION_SRC).toMatch(/showAdvanced\s*\?\s*\(?\s*<OkignoreAdvancedEditor/);
- expect(SECTION_SRC).toMatch(/:\s*isEmpty\s*\?\s*\(?\s*<OkignoreEmptyState/);
- });
-
- test('raw-text textarea uses the monospace settings textarea styling', () => {
- expect(SECTION_SRC).toMatch(/data-testid="settings-okignore-advanced-textarea"/);
- expect(SECTION_SRC).toMatch(/font-mono/);
- });
-
- test('raw-text textarea binds to the binding text prop and commits via binding.patch', () => {
- expect(SECTION_SRC).toMatch(/function OkignoreAdvancedEditor[\s\S]*?text:\s*string/);
- expect(SECTION_SRC).toMatch(/binding\.patch\(next\)/);
- expect(SECTION_SRC).toMatch(/binding\.patch\(draftRef\.current\)/);
- });
-
- test('raw-text commits are debounced via RAW_TEXT_COMMIT_MS in the 300-500ms range (per FR3)', () => {
- expect(SECTION_SRC).toMatch(/RAW_TEXT_COMMIT_MS\s*=\s*(3\d\d|4\d\d|500)/);
- expect(SECTION_SRC).toMatch(/scheduleCommit/);
- expect(SECTION_SRC).toMatch(/setTimeout\([\s\S]*?RAW_TEXT_COMMIT_MS\)/);
- });
-
- test('raw-text editor uses focusedRef + lastSyncedRef pattern (no remote-stomp during typing)', () => {
- expect(SECTION_SRC).toMatch(
- /function OkignoreAdvancedEditor[\s\S]*?focusedRef\.current[\s\S]*?lastSyncedRef\.current/,
- );
- });
-
- test('blur flushes any pending debounced commit immediately', () => {
- expect(SECTION_SRC).toMatch(/onBlur=[\s\S]*?flushCommit/);
- expect(SECTION_SRC).toMatch(/const\s+flushCommit\s*=\s*\(\)\s*=>/);
- });
-
- test('unmount flushes any pending commit (toggle-off does not drop typed content)', () => {
- expect(SECTION_SRC).toMatch(
- /return\s*\(\)\s*=>\s*\{[\s\S]*?clearTimeout\(commitTimerRef\.current\)/,
- );
- expect(SECTION_SRC).toMatch(/binding\.patch\(draftRef\.current\)/);
- });
+describe('derivePreviewPaths helper', () => {
+ test('reattaches document extensions and includes asset paths', () => {
+ const pages = new Set<string>(['drafts/foo', 'index', 'orphan']);
+ const pageMeta = new Map<string, { docExt?: string }>([
+ ['drafts/foo', { docExt: '.md' }],
+ ['index', { docExt: '.mdx' }],
+ ]);
+ const assetPaths = new Set<string>(['images/diagram.png']);
- test('raw-text editor does NOT engage the structural ops (no parse/serialize at this boundary)', () => {
- const editorSlice = SECTION_SRC.match(/function OkignoreAdvancedEditor[\s\S]*?^}/m)?.[0] ?? '';
- expect(editorSlice).not.toMatch(/appendPattern\b/);
- expect(editorSlice).not.toMatch(/editPatternAt\b/);
- expect(editorSlice).not.toMatch(/removePatternAt\b/);
- expect(editorSlice).not.toMatch(/reorderPatterns\b/);
- expect(editorSlice).not.toMatch(/serializeOkignoreDoc\b/);
- expect(editorSlice).not.toMatch(/parseOkignoreDoc\b/);
+ expect(derivePreviewPaths(pages, pageMeta, assetPaths)).toEqual([
+ 'drafts/foo.md',
+ 'index.mdx',
+ 'orphan.md',
+ 'images/diagram.png',
+ ]);
});
- test('toggle is rendered alongside the editor (always visible regardless of mode)', () => {
- expect(SECTION_SRC).toMatch(/<ShowAdvancedToggle\s+enabled=\{showAdvanced\}/);
- expect(SECTION_SRC).toMatch(/onToggle=\{[\s\S]*?setShowAdvanced\(!showAdvanced\)/);
+ test('returns an empty list on empty inputs', () => {
+ expect(derivePreviewPaths(new Set(), new Map(), new Set())).toEqual([]);
});
});
-describe('OkignoreSection — US-010 localStorage trust-boundary (mutation-pass via public interface)', () => {
+describe('advanced-toggle localStorage helpers', () => {
let storage: Map<string, string>;
const originalLocalStorage = (globalThis as unknown as { localStorage?: unknown }).localStorage;
+ const originalConsoleDebug = console.debug;
beforeEach(() => {
storage = new Map<string, string>();
(globalThis as unknown as { localStorage: Storage }).localStorage = {
- getItem: (k: string) => storage.get(k) ?? null,
- setItem: (k: string, v: string) => {
- storage.set(k, v);
- },
- removeItem: (k: string) => {
- storage.delete(k);
+ getItem: (key: string) => storage.get(key) ?? null,
+ setItem: (key: string, value: string) => {
+ storage.set(key, value);
},
- clear: () => {
- storage.clear();
+ removeItem: (key: string) => {
+ storage.delete(key);
},
+ clear: () => storage.clear(),
key: () => null,
get length() {
return storage.size;
},
} as Storage;
+ console.debug = () => {};
});
afterEach(() => {
+ console.debug = originalConsoleDebug;
if (originalLocalStorage === undefined) {
delete (globalThis as unknown as { localStorage?: unknown }).localStorage;
} else {
@@ -471,68 +88,32 @@ describe('OkignoreSection — US-010 localStorage trust-boundary (mutation-pass
}
});
- test('readShowAdvanced returns false when key is unset (default-off)', () => {
- expect(readShowAdvanced()).toBe(false);
- });
-
- test('readShowAdvanced returns true when key is set to "true"', () => {
- storage.set('okignore-show-advanced', 'true');
- expect(readShowAdvanced()).toBe(true);
- });
-
- test('readShowAdvanced returns false when key is set to anything other than "true"', () => {
- storage.set('okignore-show-advanced', 'false');
+ test('defaults off and round-trips persisted true/false values', () => {
expect(readShowAdvanced()).toBe(false);
- storage.set('okignore-show-advanced', '1');
- expect(readShowAdvanced()).toBe(false);
- storage.set('okignore-show-advanced', '');
- expect(readShowAdvanced()).toBe(false);
- });
-
- test('writeShowAdvanced(true) persists "true"', () => {
writeShowAdvanced(true);
expect(storage.get('okignore-show-advanced')).toBe('true');
- });
-
- test('writeShowAdvanced(false) persists "false" (so a previous "true" is cleared)', () => {
- storage.set('okignore-show-advanced', 'true');
+ expect(readShowAdvanced()).toBe(true);
writeShowAdvanced(false);
expect(storage.get('okignore-show-advanced')).toBe('false');
expect(readShowAdvanced()).toBe(false);
});
- test('round-trip: write(true) then read returns true', () => {
- writeShowAdvanced(true);
+ test('treats only the string true as enabled', () => {
+ storage.set('okignore-show-advanced', '1');
+ expect(readShowAdvanced()).toBe(false);
+ storage.set('okignore-show-advanced', 'true');
expect(readShowAdvanced()).toBe(true);
});
- test('readShowAdvanced returns false when localStorage is undefined (SSR safety)', () => {
+ test('fails closed when localStorage is unavailable or throws', () => {
delete (globalThis as unknown as { localStorage?: unknown }).localStorage;
expect(readShowAdvanced()).toBe(false);
- });
-
- test('writeShowAdvanced silently no-ops when localStorage is undefined', () => {
- delete (globalThis as unknown as { localStorage?: unknown }).localStorage;
expect(() => writeShowAdvanced(true)).not.toThrow();
- });
- test('readShowAdvanced returns false when getItem throws (Safari private mode)', () => {
(globalThis as unknown as { localStorage: Storage }).localStorage = {
getItem: () => {
- throw new Error('SecurityError: localStorage unavailable in private mode');
+ throw new Error('SecurityError');
},
- setItem: () => {},
- removeItem: () => {},
- clear: () => {},
- key: () => null,
- length: 0,
- } as Storage;
- expect(readShowAdvanced()).toBe(false);
- });
-
- test('writeShowAdvanced silently no-ops when setItem throws (quota exceeded)', () => {
- (globalThis as unknown as { localStorage: Storage }).localStorage = {
- getItem: () => null,
setItem: () => {
throw new Error('QuotaExceededError');
},
@@ -541,172 +122,7 @@ describe('OkignoreSection — US-010 localStorage trust-boundary (mutation-pass
key: () => null,
length: 0,
} as Storage;
+ expect(readShowAdvanced()).toBe(false);
expect(() => writeShowAdvanced(true)).not.toThrow();
});
});
-
-describe('OkignoreSection — US-011 per-row pattern preview (source-level)', () => {
- test('PatternRowInput threads filePaths and renders <PatternPreview />', () => {
- expect(SECTION_SRC).toMatch(/function PatternRowInput\(/);
- expect(SECTION_SRC).toMatch(/filePaths: ReadonlyArray<string>/);
- expect(SECTION_SRC).toMatch(/<PatternPreview count=\{previewCount\} \/>/);
- });
-
- test('PatternRowInput uses useDebouncedPreview against the input draft', () => {
- expect(SECTION_SRC).toMatch(/useDebouncedPreview\(draft, filePaths\)/);
- });
-
- test('AddPatternRow threads filePaths and renders <PatternPreview /> for the typing input', () => {
- expect(SECTION_SRC).toMatch(/function AddPatternRow\(/);
- const addRow = SECTION_SRC.slice(SECTION_SRC.indexOf('function AddPatternRow('));
- expect(addRow).toMatch(/filePaths: ReadonlyArray<string>/);
- expect(addRow).toMatch(/useDebouncedPreview\(pending, filePaths\)/);
- expect(addRow).toMatch(/<PatternPreview count=\{previewCount\}/);
- });
-
- test('OkignoreEmptyState forwards filePaths into AddPatternRow', () => {
- const empty = SECTION_SRC.slice(SECTION_SRC.indexOf('function OkignoreEmptyState('));
- expect(empty).toMatch(/filePaths: ReadonlyArray<string>/);
- expect(empty).toMatch(/<AddPatternRow[\s\S]*?filePaths=\{filePaths\}/);
- });
-
- test('OkignorePatternList forwards filePaths into rows AND AddPatternRow', () => {
- const list = SECTION_SRC.slice(SECTION_SRC.indexOf('function OkignorePatternList('));
- expect(list).toMatch(/filePaths: ReadonlyArray<string>/);
- expect(list).toMatch(/<SortablePatternRow[\s\S]*?filePaths=\{filePaths\}/);
- expect(list).toMatch(/<AddPatternRow[\s\S]*?filePaths=\{filePaths\}/);
- });
-
- test('OkignoreSectionBody calls usePageList and derives filePaths via derivePreviewPaths', () => {
- expect(SECTION_SRC).toMatch(/usePageList\(\)/);
- expect(SECTION_SRC).toMatch(/derivePreviewPaths\(pages, pageMeta, assetPaths\)/);
- });
-
- test('imports countMatches from the okignore-preview module (not a duplicate ignore() instantiation)', () => {
- expect(SECTION_SRC).toMatch(/from '\.\/okignore-preview'/);
- expect(SECTION_SRC).toMatch(/countMatches/);
- expect(SECTION_SRC).not.toMatch(/from 'ignore'/);
- });
-
- test('PREVIEW_DEBOUNCE_MS is 150ms (matches FR7 perceptual budget)', () => {
- expect(SECTION_SRC).toMatch(/const PREVIEW_DEBOUNCE_MS = 150;/);
- });
-
- test('useDebouncedPreview wires setTimeout with PREVIEW_DEBOUNCE_MS, not a literal magic number', () => {
- expect(SECTION_SRC).toMatch(
- /setTimeout\([\s\S]*?countMatches\(trimmed, filePaths\)[\s\S]*?\}, PREVIEW_DEBOUNCE_MS\)/,
- );
- });
-
- test('useDebouncedPreview returns null on empty input so PatternPreview hides gracefully', () => {
- expect(SECTION_SRC).toMatch(/trimmed\.length === 0[\s\S]{0,80}setCount\(null\)/);
- });
-
- test('PatternPreview renders the FR7 caveat label "(some may already be hidden by other rules)"', () => {
- expect(SECTION_SRC).toMatch(/\(some may already be hidden by other rules\)/);
- });
-
- test('PatternPreview uses muted styling for matches 0', () => {
- const preview = SECTION_SRC.slice(SECTION_SRC.indexOf('function PatternPreview('));
- expect(preview).toMatch(/isZero[\s\S]{0,60}text-muted-foreground/);
- });
-
- test('PatternPreview pluralizes correctly (1 file vs N files)', () => {
- expect(SECTION_SRC).toMatch(
- /<Plural value=\{count\} one="matches # file" other="matches # files" \/>/,
- );
- });
-
- test('PatternPreview exposes data-testid="settings-okignore-preview" + state attrs for e2e', () => {
- const preview = SECTION_SRC.slice(SECTION_SRC.indexOf('function PatternPreview('));
- expect(preview).toMatch(/data-testid="settings-okignore-preview"/);
- expect(preview).toMatch(/data-preview-state="visible"/);
- expect(preview).toMatch(/data-preview-state="hidden"/);
- expect(preview).toMatch(/data-preview-count=/);
- });
-
- test('derivePreviewPaths reattaches docExt to docName for documents and passes assetPaths through', () => {
- const pages = new Set<string>(['drafts/foo', 'index']);
- const pageMeta = new Map<string, { docExt?: string }>([
- ['drafts/foo', { docExt: '.md' }],
- ['index', { docExt: '.mdx' }],
- ]);
- const assetPaths = new Set<string>(['images/diagram.png']);
- const result = derivePreviewPaths(pages, pageMeta, assetPaths);
- expect(result).toContain('drafts/foo.md');
- expect(result).toContain('index.mdx');
- expect(result).toContain('images/diagram.png');
- expect(result).toHaveLength(3);
- });
-
- test('derivePreviewPaths defaults missing docExt to .md', () => {
- const pages = new Set<string>(['orphan']);
- const pageMeta = new Map<string, { docExt?: string }>();
- const result = derivePreviewPaths(pages, pageMeta, new Set());
- expect(result).toEqual(['orphan.md']);
- });
-
- test('derivePreviewPaths returns an empty array on empty inputs', () => {
- expect(derivePreviewPaths(new Set(), new Map(), new Set())).toEqual([]);
- });
-});
-
-describe('OkignoreSection — US-012 nested-error toast routing (source-level)', () => {
- test('imports subscribeToConfigIgnoreNestedError from the dedicated event-bus module', () => {
- expect(SECTION_SRC).toMatch(
- /import \{ subscribeToConfigIgnoreNestedError \} from '@\/lib\/config-ignore-nested-error-events';/,
- );
- });
-
- test('imports the sonner toast helper for surfacing nested-error notifications', () => {
- expect(SECTION_SRC).toMatch(/import \{ toast \} from 'sonner';/);
- });
-
- test('OkignoreSectionBody subscribes via useEffect for the section lifetime', () => {
- const body = SECTION_SRC.slice(SECTION_SRC.indexOf('function OkignoreSectionBody('));
- expect(body).toMatch(/return subscribeToConfigIgnoreNestedError\(\(event\) => \{[\s\S]*?\}\);/);
- expect(body).toMatch(
- /useEffect\(\(\) => \{\s*return subscribeToConfigIgnoreNestedError\(\(event\) => \{[\s\S]*?\}\);\s*\}, \[t\]\);/,
- );
- });
-
- test('toast.error renders the project-relative path in the title and the error in the description', () => {
- const body = SECTION_SRC.slice(SECTION_SRC.indexOf('function OkignoreSectionBody('));
- expect(body).toMatch(/toast\.error\(t`Nested \.okignore error in \$\{path\}`,/);
- expect(body).toMatch(/description: event\.error,/);
- });
-
- test('toast deduplicates per-path via a stable id so a watcher loop does NOT spam the toast queue', () => {
- const body = SECTION_SRC.slice(SECTION_SRC.indexOf('function OkignoreSectionBody('));
- expect(body).toMatch(/id: `okignore-nested-error:\$\{event\.path\}`,/);
- });
-
- test('toast is non-blocking with a bounded duration (auto-dismiss)', () => {
- const body = SECTION_SRC.slice(SECTION_SRC.indexOf('function OkignoreSectionBody('));
- expect(body).toMatch(/duration: \d+,/);
- });
-});
-
-describe('SystemDocSubscriber — US-012 nested-error CC1 routing', () => {
- const SUBSCRIBER_SRC = readFileSync(join(__dirname, '..', 'SystemDocSubscriber.tsx'), 'utf8');
-
- test('imports emitConfigIgnoreNestedError from the dedicated event-bus module', () => {
- expect(SUBSCRIBER_SRC).toMatch(
- /import \{ emitConfigIgnoreNestedError \} from '@\/lib\/config-ignore-nested-error-events';/,
- );
- });
-
- test('wires onConfigIgnoreNestedError handler in dispatchCC1Stateless', () => {
- expect(SUBSCRIBER_SRC).toMatch(
- /onConfigIgnoreNestedError:\s*\(p\) => \{\s*emitConfigIgnoreNestedError\(p\);\s*\},/,
- );
- });
-
- test('cc1.ts dispatcher exposes onConfigIgnoreNestedError handler slot', () => {
- const cc1Src = readFileSync(join(__dirname, '..', '..', 'lib', 'cc1.ts'), 'utf8');
- expect(cc1Src).toMatch(
- /onConfigIgnoreNestedError\?:\s*\(payload: CC1ConfigIgnoreNestedErrorPayload\) => void;/,
- );
- expect(cc1Src).toMatch(/parseCC1ConfigIgnoreNestedError/);
- });
-});
diff --git a/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx
index f43a3cd01..febd71eae 100644
--- a/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx
+++ b/packages/app/src/components/settings/SettingsDialogBody.dom.test.tsx
@@ -1,13 +1,16 @@
import { afterEach, describe, expect, test } from 'bun:test';
import {
+ CONFIG_DOC_NAME_USER,
type Config,
type ConfigBinding,
type ConfigPatch,
ConfigSchema,
} from '@inkeep/open-knowledge-core';
-import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { TooltipProvider } from '@/components/ui/tooltip';
+import { emitConfigValidationRejected } from '@/lib/config-validation-events';
+import { expectVisualClassTokens } from '@/test-utils/visual-contract';
import { SettingsDialogBody } from './SettingsDialogBody';
function makeBinding(config: Config = ConfigSchema.parse({})): {
@@ -60,6 +63,18 @@ describe('SettingsDialogBody preferences runtime', () => {
const field = container.querySelector('[data-field="editor.wordWrap"]');
expect(field).toBeTruthy();
expect(field?.querySelector('[role="switch"]')?.getAttribute('aria-checked')).toBe('true');
+
+ expect(screen.getByText('Open preview when agent edits')).toBeDefined();
+ expect(
+ screen.getByText(
+ 'When enabled, the agent opens or refreshes the preview after each edit. Disable if you manage your own preview window (OK Desktop, a browser tab on another display, etc.).',
+ ),
+ ).toBeDefined();
+ const previewField = container.querySelector('[data-field="appearance.preview.autoOpen"]');
+ expect(previewField).toBeTruthy();
+ expect(previewField?.querySelector('[role="switch"]')?.getAttribute('aria-checked')).toBe(
+ 'true',
+ );
});
test('commits editor.wordWrap changes through binding.patch', async () => {
@@ -85,75 +100,6 @@ describe('SettingsDialogBody preferences runtime', () => {
expect(wordWrapSwitch.getAttribute('aria-checked')).toBe('false');
});
- test('renders appearance.preview.autoOpen in the Preferences section', () => {
- const { binding } = makeBinding();
- const { container } = render(
- <TooltipProvider>
- <SettingsDialogBody
- activeId="preferences"
- userBinding={binding}
- okignoreBinding={null}
- okignoreSynced={false}
- />
- </TooltipProvider>,
- );
-
- expect(screen.getByText('Open preview when agent edits')).toBeDefined();
- expect(
- screen.getByText(
- 'When enabled, the agent opens or refreshes the preview after each edit. Disable if you manage your own preview window (OK Desktop, a browser tab on another display, etc.).',
- ),
- ).toBeDefined();
- const field = container.querySelector('[data-field="appearance.preview.autoOpen"]');
- expect(field).toBeTruthy();
- expect(field?.querySelector('[role="switch"]')?.getAttribute('aria-checked')).toBe('true');
- });
-
- test('renders shared hotkeys in the Hotkeys section', () => {
- render(
- <TooltipProvider>
- <SettingsDialogBody
- activeId="hotkeys"
- userBinding={null}
- okignoreBinding={null}
- okignoreSynced={false}
- />
- </TooltipProvider>,
- );
-
- expect(screen.getByRole('heading', { name: 'Hotkeys' })).toBeDefined();
- expect(screen.getByTestId('settings-hotkeys-list')).toBeDefined();
- expect(screen.getByTestId('settings-hotkey-command-palette')).toBeDefined();
- expect(screen.getByText('Command palette')).toBeDefined();
- expect(screen.queryByText(/Chrome uses this to search/)).toBeNull();
- });
-
- test('keeps long hotkey rows compact when shortcut chips wrap', () => {
- render(
- <TooltipProvider>
- <SettingsDialogBody
- activeId="hotkeys"
- userBinding={null}
- okignoreBinding={null}
- okignoreSynced={false}
- />
- </TooltipProvider>,
- );
-
- const row = screen.getByTestId('settings-hotkey-source-editing');
- expect(row.className).toContain('sm:grid-cols-1');
- const shortcutColumn = row.children.item(1);
- expect(shortcutColumn?.className).toContain('min-w-0');
- expect(shortcutColumn?.className).toContain('self-start');
- expect(shortcutColumn?.className).toContain('content-start');
- expect(shortcutColumn?.className).toContain('flex-wrap');
- expect(shortcutColumn?.className).toContain('sm:justify-start');
-
- const shortRow = screen.getByTestId('settings-hotkey-command-palette');
- expect(shortRow.className).toContain('sm:grid-cols-[minmax(0,1fr)_minmax(0,auto)]');
- expect(shortRow.children.item(1)?.className).toContain('sm:justify-end');
- });
-
test('commits appearance.preview.autoOpen changes through binding.patch', async () => {
const user = userEvent.setup();
const { binding, patches } = makeBinding();
@@ -170,6 +116,7 @@ describe('SettingsDialogBody preferences runtime', () => {
const autoOpenSwitch = screen.getByRole('switch', { name: 'Open preview when agent edits' });
expect(autoOpenSwitch.getAttribute('aria-checked')).toBe('true');
+
await user.click(autoOpenSwitch);
await waitFor(() => {
@@ -178,6 +125,7 @@ describe('SettingsDialogBody preferences runtime', () => {
expect(autoOpenSwitch.getAttribute('aria-checked')).toBe('false');
await user.click(autoOpenSwitch);
+
await waitFor(() => {
expect(patches).toEqual([
{ appearance: { preview: { autoOpen: false } } },
@@ -186,4 +134,47 @@ describe('SettingsDialogBody preferences runtime', () => {
});
expect(autoOpenSwitch.getAttribute('aria-checked')).toBe('true');
});
+
+ test('surfaces L3 config-validation rejections on the matching user field', async () => {
+ const { binding } = makeBinding();
+ const { container } = render(
+ <TooltipProvider>
+ <SettingsDialogBody
+ activeId="preferences"
+ userBinding={binding}
+ okignoreBinding={null}
+ okignoreSynced={false}
+ />
+ </TooltipProvider>,
+ );
+
+ const wordWrapField = container.querySelector('[data-field="editor.wordWrap"]');
+ expect(wordWrapField).toBeTruthy();
+
+ act(() => {
+ emitConfigValidationRejected({
+ v: 1,
+ ch: 'config-validation-rejected',
+ seq: 1,
+ docName: CONFIG_DOC_NAME_USER,
+ error: {
+ code: 'SCHEMA_INVALID',
+ issues: [
+ {
+ path: ['editor', 'wordWrap'],
+ message: 'Expected boolean',
+ issueCode: 'invalid_type',
+ },
+ ],
+ },
+ });
+ });
+
+ await waitFor(() => {
+ expect(container.querySelector('[data-field-error="editor.wordWrap"]')?.textContent).toBe(
+ 'Expected boolean',
+ );
+ });
+ expectVisualClassTokens(wordWrapField?.className, ['animate-settings-flash']);
+ });
});
diff --git a/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsx
new file mode 100644
index 000000000..80087c84b
--- /dev/null
+++ b/packages/app/src/components/settings/SettingsDialogBody.sections.dom.test.tsx
@@ -0,0 +1,417 @@
+import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { type ReactNode, useState } from 'react';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+type SyncStatus = {
+ state: string;
+ hasRemote: boolean;
+ pausedReason?: string;
+ pushPermission?: {
+ checkStatus: 'allowed' | 'denied' | 'unknown';
+ deniedReason?: string;
+ unknownError?: string;
+ };
+ syncEnabled?: boolean;
+ remote?: { label: string; webUrl: string | null } | null;
+} | null;
+
+let syncStatus: SyncStatus = null;
+let projectLocalConfig: { autoSync?: { enabled?: boolean } } | null = {
+ autoSync: { enabled: true },
+};
+let projectLocalSynced = true;
+let syncWriterCalls: boolean[] = [];
+let okignoreProps: Array<{ binding: unknown; synced: boolean }> = [];
+let installDialogProps: Array<{
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ reinstall: boolean;
+}> = [];
+let publishDialogProps: Array<{ open: boolean }> = [];
+let claudeRefreshCalls = 0;
+let claudeSkillInstalled = false;
+
+const actualCore = await import('@inkeep/open-knowledge-core');
+
+mock.module('@inkeep/open-knowledge-core', () => ({
+ ...actualCore,
+ SHOW_INSTALL_SKILL: true,
+}));
+
+mock.module('@lingui/react/macro', () => ({
+ Plural: ({ value, one, other }: { value: number; one: string; other: string }) => (
+ <>{(value === 1 ? one : other).replace('#', String(value))}</>
+ ),
+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+mock.module('@lingui/core/macro', () => ({
+ msg: renderLinguiTemplate,
+ plural: (value: number, options: { one: string; other: string }) =>
+ (value === 1 ? options.one : options.other).replace('#', String(value)),
+ t: renderLinguiTemplate,
+}));
+
+mock.module('@/components/ui/button', () => ({
+ Button: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <button type="button" {...props}>
+ {children}
+ </button>
+ ),
+}));
+
+mock.module('@/components/ui/collapsible', () => ({
+ Collapsible: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ CollapsibleContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ CollapsibleTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,
+}));
+
+mock.module('@/components/ui/switch', () => ({
+ Switch: ({
+ checked,
+ disabled,
+ onCheckedChange,
+ ...props
+ }: {
+ checked?: boolean;
+ disabled?: boolean;
+ onCheckedChange?: (checked: boolean) => void;
+ [key: string]: unknown;
+ }) => (
+ <button
+ type="button"
+ role="switch"
+ aria-checked={checked ? 'true' : 'false'}
+ disabled={disabled}
+ onClick={() => onCheckedChange?.(!checked)}
+ {...props}
+ />
+ ),
+}));
+
+mock.module('@/components/ui/skeleton', () => ({
+ Skeleton: ({ className }: { className?: string }) => <div className={className} />,
+}));
+
+mock.module('@/components/ui/form', () => ({
+ Form: ({ children }: { children?: ReactNode }) => <form>{children}</form>,
+ FormControl: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ FormDescription: ({ children }: { children?: ReactNode }) => <p>{children}</p>,
+ FormField: () => null,
+ FormItem: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ FormLabel: ({ children }: { children?: ReactNode }) => <span>{children}</span>,
+ FormMessage: () => null,
+}));
+
+mock.module('@/components/ui/input', () => ({
+ Input: (props: React.InputHTMLAttributes<HTMLInputElement>) => <input {...props} />,
+}));
+
+mock.module('@/components/ui/toggle-group', () => ({
+ ToggleGroup: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ ToggleGroupItem: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <button type="button" {...props}>
+ {children}
+ </button>
+ ),
+}));
+
+mock.module('@/components/ui/tooltip', () => ({
+ Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ TooltipContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
+ TooltipTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,
+}));
+
+mock.module('@/components/PublishToGitHubDialog', () => ({
+ PublishToGitHubDialog: (props: { open: boolean }) => {
+ publishDialogProps.push(props);
+ return <div data-open={String(props.open)} data-testid="publish-dialog" />;
+ },
+}));
+
+mock.module('@/components/InstallInClaudeDesktopDialog', () => ({
+ InstallInClaudeDesktopDialog: (props: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ reinstall: boolean;
+ }) => {
+ installDialogProps.push(props);
+ return (
+ <div
+ data-open={String(props.open)}
+ data-reinstall={String(props.reinstall)}
+ data-testid="install-claude-dialog"
+ />
+ );
+ },
+}));
+
+mock.module('./OkignoreSection', () => ({
+ OkignoreSection: (props: { binding: unknown; synced: boolean }) => {
+ okignoreProps.push(props);
+ return <div data-testid="okignore-section">okignore synced: {String(props.synced)}</div>;
+ },
+}));
+
+mock.module('./ProjectTemplatesSection', () => ({
+ ProjectTemplatesSection: () => <div data-testid="project-templates-section" />,
+}));
+
+mock.module('@/hooks/use-git-sync-status', () => ({
+ useGitSyncStatus: () => syncStatus,
+ useGitSyncStatusDetailed: () => ({ status: syncStatus, fetchError: null }),
+}));
+
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ projectLocalConfig,
+ projectLocalSynced,
+ }),
+}));
+
+mock.module('@/hooks/use-enable-sync-with-confirm', () => ({
+ useSyncEnabledWriter: () => ({
+ write: (enabled: boolean) => {
+ syncWriterCalls.push(enabled);
+ return true;
+ },
+ }),
+ useEnableSyncWithConfirm: (writer: { write: (enabled: boolean) => boolean }) => {
+ const [confirmOpen, setConfirmOpen] = useState(false);
+ return {
+ confirmOpen,
+ setConfirmOpen,
+ onToggleRequest: (enabled: boolean) => {
+ if (enabled) {
+ setConfirmOpen(true);
+ return;
+ }
+ writer.write(false);
+ },
+ onConfirm: () => {
+ writer.write(true);
+ setConfirmOpen(false);
+ },
+ };
+ },
+ EnableSyncConfirmDialog: () => null,
+}));
+
+mock.module('@/components/EnableSyncConfirmDialog', () => ({
+ EnableSyncConfirmDialog: ({ open, onConfirm }: { open: boolean; onConfirm: () => void }) => (
+ <div data-open={String(open)} data-testid="sync-confirm-dialog">
+ <button type="button" onClick={onConfirm}>
+ Confirm sync
+ </button>
+ </div>
+ ),
+}));
+
+mock.module('@/lib/handoff/use-claude-desktop-integration', () => ({
+ useClaudeDesktopIntegration: () => ({
+ desktopPresent: true,
+ skillInstalled: claudeSkillInstalled,
+ skillVersion: claudeSkillInstalled ? '1.0.0' : null,
+ refresh: () => {
+ claudeRefreshCalls += 1;
+ },
+ }),
+}));
+
+async function renderBody(
+ props: {
+ activeId: string;
+ userBinding?: unknown;
+ okignoreBinding?: unknown;
+ okignoreSynced?: boolean;
+ } = { activeId: 'sync' },
+) {
+ const { SettingsDialogBody } = await import('./SettingsDialogBody');
+ render(
+ <SettingsDialogBody
+ activeId={props.activeId}
+ userBinding={(props.userBinding ?? null) as never}
+ okignoreBinding={(props.okignoreBinding ?? null) as never}
+ okignoreSynced={props.okignoreSynced ?? false}
+ />,
+ );
+}
+
+describe('SettingsDialogBody section runtime dispatch', () => {
+ beforeEach(() => {
+ cleanup();
+ syncStatus = null;
+ projectLocalConfig = { autoSync: { enabled: true } };
+ projectLocalSynced = true;
+ syncWriterCalls = [];
+ okignoreProps = [];
+ installDialogProps = [];
+ publishDialogProps = [];
+ claudeRefreshCalls = 0;
+ claudeSkillInstalled = false;
+ });
+
+ test('body dispatches heavy project sections without owning a Dialog frame', async () => {
+ const okignoreBinding = { id: 'okignore-binding' };
+
+ await renderBody({ activeId: 'okignore', okignoreBinding, okignoreSynced: true });
+
+ expect(screen.getByTestId('okignore-section').textContent).toContain('true');
+ expect(okignoreProps.at(-1)).toEqual({ binding: okignoreBinding, synced: true });
+ expect(screen.queryByRole('dialog')).toBeNull();
+
+ cleanup();
+ await renderBody({ activeId: 'project-templates' });
+ expect(screen.getByTestId('project-templates-section')).not.toBeNull();
+ expect(screen.queryByRole('dialog')).toBeNull();
+ });
+
+ test('hotkeys section renders from the shared shortcut registry', async () => {
+ await renderBody({ activeId: 'hotkeys' });
+
+ expect(screen.getByTestId('settings-hotkeys')).not.toBeNull();
+ expect(screen.getByTestId('settings-hotkeys-list').textContent).toContain('Editor');
+ expect(screen.getAllByText('Workspace').length).toBeGreaterThan(0);
+ });
+
+ test('sync section reads checked state from project-local config and keeps the writer/confirm path', async () => {
+ syncStatus = {
+ state: 'enabled',
+ hasRemote: true,
+ syncEnabled: false,
+ remote: {
+ label: 'inkeep/open-knowledge',
+ webUrl: 'https://github.com/inkeep/open-knowledge',
+ },
+ };
+ projectLocalConfig = { autoSync: { enabled: true } };
+
+ await renderBody({ activeId: 'sync' });
+
+ const toggle = screen.getByTestId('settings-sync-toggle');
+ expect(toggle.getAttribute('aria-checked')).toBe('true');
+ expect(screen.getByTestId('settings-sync-remote-link').getAttribute('href')).toBe(
+ 'https://github.com/inkeep/open-knowledge',
+ );
+ expect(screen.getByTestId('settings-sync-remote-link').getAttribute('rel')).toBe(
+ 'noopener noreferrer',
+ );
+
+ fireEvent.click(toggle);
+ expect(syncWriterCalls).toEqual([false]);
+
+ cleanup();
+ syncStatus = {
+ state: 'enabled',
+ hasRemote: true,
+ syncEnabled: true,
+ remote: { label: 'ssh://git.example/repo.git', webUrl: null },
+ };
+ projectLocalConfig = { autoSync: { enabled: false } };
+ projectLocalSynced = false;
+
+ await renderBody({ activeId: 'sync' });
+
+ expect(screen.getByTestId('settings-sync-toggle').getAttribute('aria-checked')).toBe('false');
+ expect(screen.getByTestId('settings-sync-toggle').hasAttribute('disabled')).toBe(true);
+ expect(screen.getByTestId('settings-sync-remote-label').textContent).toBe(
+ 'ssh://git.example/repo.git',
+ );
+ });
+
+ test('sync section disables the toggle with denied-specific accessible copy when push permission is denied', async () => {
+ syncStatus = {
+ state: 'idle',
+ hasRemote: true,
+ syncEnabled: false,
+ pushPermission: { checkStatus: 'denied', deniedReason: 'no-collaborator' },
+ remote: {
+ label: 'inkeep/open-knowledge',
+ webUrl: 'https://github.com/inkeep/open-knowledge',
+ },
+ };
+ projectLocalConfig = { autoSync: { enabled: false } };
+ projectLocalSynced = true;
+
+ await renderBody({ activeId: 'sync' });
+
+ const toggle = screen.getByTestId('settings-sync-toggle') as HTMLButtonElement;
+ expect(toggle.disabled).toBe(true);
+ expect(toggle.getAttribute('aria-label')).toBe(
+ "Sync disabled — you don't have permission to push",
+ );
+ expect(screen.getByTestId('settings-sync-body').textContent).toContain(
+ "you don't have permission to push",
+ );
+ expect(screen.queryByTestId('settings-sync-reason')).toBeNull();
+ });
+
+ test('sync section renders shared paused-reason copy for non-permission pause reasons', async () => {
+ syncStatus = {
+ state: 'disabled',
+ hasRemote: true,
+ pausedReason: 'protected-branch',
+ syncEnabled: false,
+ remote: {
+ label: 'inkeep/open-knowledge',
+ webUrl: 'https://github.com/inkeep/open-knowledge',
+ },
+ };
+ projectLocalConfig = { autoSync: { enabled: false } };
+
+ await renderBody({ activeId: 'sync' });
+
+ expect(screen.getByTestId('settings-sync-reason').textContent).toBe(
+ 'Protected branch — cannot push',
+ );
+ });
+
+ test('sync empty state offers Publish wizard and keeps the advanced git remote path', async () => {
+ syncStatus = { state: 'dormant', hasRemote: false, syncEnabled: false };
+
+ await renderBody({ activeId: 'sync' });
+
+ expect(screen.getByTestId('settings-sync-empty').textContent).toContain(
+ 'lives only on this computer',
+ );
+ expect(screen.getByText(/git remote add origin/).textContent).toContain(
+ 'git remote add origin',
+ );
+ expect(screen.getByTestId('publish-dialog').getAttribute('data-open')).toBe('false');
+
+ fireEvent.click(screen.getByTestId('settings-sync-setup'));
+
+ await waitFor(() => {
+ expect(screen.getByTestId('publish-dialog').getAttribute('data-open')).toBe('true');
+ });
+ expect(publishDialogProps.at(-1)?.open).toBe(true);
+ });
+
+ test('integrations row reflects shared Claude Desktop state and refreshes when installer closes', async () => {
+ claudeSkillInstalled = false;
+ await renderBody({ activeId: 'claude-desktop' });
+
+ expect(screen.getByText('Install in Claude Desktop')).not.toBeNull();
+ expect(screen.getByTestId('settings-install-claude-desktop').textContent).toBe('Install');
+
+ fireEvent.click(screen.getByTestId('settings-install-claude-desktop'));
+ await waitFor(() => {
+ expect(screen.getByTestId('install-claude-dialog').getAttribute('data-open')).toBe('true');
+ });
+ expect(installDialogProps.at(-1)?.reinstall).toBe(false);
+
+ act(() => {
+ installDialogProps.at(-1)?.onOpenChange(false);
+ });
+ expect(claudeRefreshCalls).toBe(1);
+
+ cleanup();
+ claudeSkillInstalled = true;
+ await renderBody({ activeId: 'claude-desktop' });
+
+ expect(screen.getByTestId('settings-install-claude-desktop').textContent).toBe('Reinstall');
+ expect(screen.getByTestId('install-claude-dialog').getAttribute('data-reinstall')).toBe('true');
+ });
+});
diff --git a/packages/app/src/components/settings/SettingsDialogBody.test.ts b/packages/app/src/components/settings/SettingsDialogBody.test.ts
index 82f8c8d33..9bf4936f7 100644
--- a/packages/app/src/components/settings/SettingsDialogBody.test.ts
+++ b/packages/app/src/components/settings/SettingsDialogBody.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, test } from 'bun:test';
-import SRC from './SettingsDialogBody?raw';
describe('SettingsDialogBody module', () => {
test('exports SettingsDialogBody component', async () => {
@@ -7,205 +6,3 @@ describe('SettingsDialogBody module', () => {
expect(typeof mod.SettingsDialogBody).toBe('function');
});
});
-
-describe('SettingsDialogBody source-level guards', () => {
- test('consumes the user-scope ConfigBinding via shell-passed props', () => {
- expect(SRC).toMatch(
- /interface\s+SettingsDialogBodyProps[\s\S]*?userBinding:\s*ConfigBinding\s*\|\s*null/,
- );
- expect(SRC).toMatch(/export\s+function\s+SettingsDialogBody/);
- expect(SRC).not.toContain('useUserConfigDocConnection');
- expect(SRC).not.toMatch(/from\s+['"]@hocuspocus\/provider['"]/);
- expect(SRC).not.toMatch(/import\s+\*\s+as\s+Y\s+from\s+['"]yjs['"]/);
- expect(SRC).not.toMatch(/\bbindConfigDoc\(/);
- expect(SRC).toContain('useConfigContext');
- expect(SRC).toContain("from '@inkeep/open-knowledge-core'");
- });
-
- test('admits both well-known config doc names', () => {
- expect(SRC).toContain('CONFIG_DOC_NAME_PROJECT');
- expect(SRC).toContain('CONFIG_DOC_NAME_USER');
- });
-
- test('subscribes to CC1 config-validation-rejected', () => {
- expect(SRC).toContain('subscribeToConfigValidationRejected');
- });
-
- test('L3 rejection wires form.setError + form.setFocus on the rejected field', () => {
- expect(SRC).toContain('form.setError(');
- expect(SRC).toContain('form.setFocus(');
- expect(SRC).toContain("type: 'config-validation-rejected'");
- });
-
- test('does not import the Dialog primitive (it lives in the shell)', () => {
- expect(SRC).not.toMatch(/from\s+['"]@\/components\/ui\/dialog['"]/);
- expect(SRC).not.toMatch(/<Dialog\b/);
- expect(SRC).not.toMatch(/<DialogContent\b/);
- });
-
- test('has Integrations section with Install in Claude Desktop row', () => {
- expect(SRC).toContain('IntegrationsSection');
- expect(SRC).toContain('Install in Claude Desktop');
- expect(SRC).toContain('InstallInClaudeDesktopDialog');
- });
-
- test('has Hotkeys section backed by the shared shortcut registry', () => {
- expect(SRC).toMatch(/from\s+['"]@\/lib\/keyboard-shortcuts['"]/);
- expect(SRC).toContain('KEYBOARD_SHORTCUTS');
- expect(SRC).toMatch(/activeId\s*===\s*['"]hotkeys['"]\s*\)[\s\S]*?<HotkeysSection\s*\/>/);
- });
-
- test('Integrations row consumes the shared useClaudeDesktopIntegration hook', () => {
- expect(SRC).toContain('useClaudeDesktopIntegration');
- expect(SRC).not.toContain('useClaudeDesktopAvailable');
- expect(SRC).not.toMatch(/detectClaudeDesktop\s*\?\.\(/);
- });
-
- test('IntegrationsSection button label branches on skillInstalled', () => {
- expect(SRC).toMatch(
- /skillInstalled\s*\?\s*<Trans>Reinstall<\/Trans>\s*:\s*<Trans>Install<\/Trans>/,
- );
- });
-
- test('IntegrationsSection refreshes the shared hook on dialog close', () => {
- expect(SRC).toMatch(/if\s*\(!next\)\s*refresh\(\)/);
- });
-
- test('uses sonner for L3 rejection toast', () => {
- expect(SRC).toContain("from 'sonner'");
- expect(SRC).toContain('toast.error(');
- });
-
- test('per-field reset writes default OR null-as-clear', () => {
- expect(SRC).toContain('Reset to default');
- expect(SRC).toMatch(/form\.setValue\(/);
- expect(SRC).toContain('shouldDirty: false');
- expect(SRC).toMatch(/defaultValue\s*===\s*undefined\s*\?\s*null/);
- });
-
- test('flash animation uses the settings-flash CSS keyframe', () => {
- expect(SRC).toContain('animate-settings-flash');
- });
-
- test('does not instantiate client-side IndexeddbPersistence', () => {
- expect(SRC).not.toContain('IndexeddbPersistence');
- expect(SRC).not.toContain('createClientPersistence');
- });
-
- test('uses the shadcn Form primitive (FormField / FormControl / FormMessage)', () => {
- expect(SRC).toMatch(/from\s+['"]@\/components\/ui\/form['"]/);
- expect(SRC).toMatch(/<FormField\b/);
- expect(SRC).toMatch(/<FormMessage\b/);
- });
-
- test('consumes the useConfigForm harness hook', () => {
- expect(SRC).toMatch(/from\s+['"]\.\/use-config-form['"]/);
- expect(SRC).toContain('useConfigForm(');
- });
-});
-
-describe('SettingsDialogBody Channel section guards', () => {
- test('no longer renders a channel switcher', () => {
- expect(SRC).not.toContain('ChannelSection');
- });
-});
-
-describe('SettingsDialogBody Okignore section guards', () => {
- test('imports OkignoreSection from a sibling module', () => {
- expect(SRC).toMatch(/from\s+['"]\.\/OkignoreSection['"]/);
- expect(SRC).toContain('OkignoreSection');
- });
-
- test('Okignore section appears under THIS PROJECT in the "Ignore patterns" item', () => {
- expect(SRC).toMatch(/activeId\s*===\s*['"]okignore['"]\s*\)[\s\S]*?<OkignoreSection\b/);
- });
-});
-
-describe('SettingsDialogBody Sync section guards', () => {
- test('Sync section appears under THIS PROJECT as the dedicated "Sync" sidebar item', () => {
- expect(SRC).toMatch(/activeId\s*===\s*['"]sync['"]\s*\)[\s\S]*?<SyncSection\s*\/>/);
- });
-
- test('Sync section toggle goes through the shared confirmation hook', () => {
- expect(SRC).toContain("from '@/hooks/use-enable-sync-with-confirm'");
- expect(SRC).toContain('useEnableSyncWithConfirm');
- expect(SRC).toContain('EnableSyncConfirmDialog');
- });
-
- test('Sync toggle label is associated to the Switch via htmlFor', () => {
- expect(SRC).toMatch(/<label\s+htmlFor="settings-sync-toggle"/);
- expect(SRC).toMatch(/<Switch[\s\S]*?id="settings-sync-toggle"/);
- });
-
- test('Sync section renders an empty state when no git remote is detected', () => {
- expect(SRC).toMatch(/data-testid="settings-sync-empty"/);
- expect(SRC).toContain('lives only on this computer');
- });
-
- test('Sync empty state offers the Publish wizard instead of a CLI dead-end', () => {
- expect(SRC).toContain("from '@/components/PublishToGitHubDialog'");
- expect(SRC).toMatch(/data-testid="settings-sync-setup"/);
- expect(SRC).toMatch(/<PublishToGitHubDialog\s+open={publishOpen}/);
- expect(SRC).toContain('git remote add origin');
- expect(SRC).toMatch(/<Collapsible>[\s\S]*?git remote add origin/);
- });
-
- test('Sync section surfaces the remote repository with a GitHub link', () => {
- expect(SRC).toMatch(/data-testid="settings-sync-remote"/);
- expect(SRC).toContain('status.remote');
- expect(SRC).toMatch(/data-testid="settings-sync-remote-link"/);
- expect(SRC).toMatch(/href={status\.remote\.webUrl}/);
- expect(SRC).toContain('rel="noopener noreferrer"');
- expect(SRC).toMatch(/data-testid="settings-sync-remote-label"/);
- });
-});
-
-describe('SettingsDialogBody SyncSection Switch — bound to local CRDT preference (not server status)', () => {
- const syncSectionStart = SRC.indexOf('function SyncSection()');
- const nextSiblingStart = SRC.indexOf('interface SettingsFieldProps', syncSectionStart);
- const syncSectionSrc = SRC.slice(syncSectionStart, nextSiblingStart);
-
- test('SyncSection isolation slice is non-empty (sanity)', () => {
- expect(syncSectionStart).toBeGreaterThan(-1);
- expect(nextSiblingStart).toBeGreaterThan(syncSectionStart);
- expect(syncSectionSrc.length).toBeGreaterThan(200);
- });
-
- test('Switch.checked derives from the local CRDT preference, not status.syncEnabled', () => {
- expect(syncSectionSrc).toMatch(/useConfigContext|projectLocalConfig/);
- expect(syncSectionSrc).not.toMatch(/const enabled\s*=\s*.*status/);
- });
-
- test('useGitSyncStatus still used for hasRemote + dormant visibility gate', () => {
- expect(syncSectionSrc).toContain('useGitSyncStatus');
- expect(syncSectionSrc).toMatch(/!status\.hasRemote[\s\S]*?status\.state\s*===\s*'dormant'/);
- });
-
- test('Switch disabled prop gates against the cold-start window', () => {
- expect(syncSectionSrc).toMatch(/disabled=\{disabledControl\}/);
- expect(syncSectionSrc).toMatch(
- /projectLocalSynced|projectLocalBinding\s*===\s*null|projectLocalConfig\s*===\s*null/,
- );
- });
-
- test('write path is unchanged — useSyncEnabledWriter + EnableSyncConfirmDialog', () => {
- expect(syncSectionSrc).toContain('useSyncEnabledWriter');
- expect(syncSectionSrc).toContain('useEnableSyncWithConfirm');
- expect(syncSectionSrc).toContain('EnableSyncConfirmDialog');
- });
-
- test('disabledControl flows through the shared shouldDisableSyncSwitch helper', () => {
- expect(syncSectionSrc).toContain('shouldDisableSyncSwitch(');
- expect(syncSectionSrc).toContain('status?.pushPermission?.checkStatus');
- });
-
- test('reuses formatPausedReason from SyncStatusBadge for non-permission pause reasons', () => {
- expect(syncSectionSrc).toContain('formatPausedReason');
- expect(syncSectionSrc).toMatch(/data-testid=\{?["']settings-sync-reason["']\}?/);
- });
-
- test('aria-label updates to a denied-specific label when probe says denied', () => {
- expect(syncSectionSrc).toContain("status?.pushPermission?.checkStatus === 'denied'");
- expect(syncSectionSrc).toMatch(/Sync disabled — you don't have permission to push/);
- });
-});
diff --git a/packages/app/src/components/settings/SettingsDialogShell.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogShell.dom.test.tsx
index 6f1abb218..b4d100d41 100644
--- a/packages/app/src/components/settings/SettingsDialogShell.dom.test.tsx
+++ b/packages/app/src/components/settings/SettingsDialogShell.dom.test.tsx
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
import type { ConfigBinding, OkignoreBinding } from '@inkeep/open-knowledge-core';
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
type WindowGlobals = {
MutationObserver?: typeof MutationObserver;
@@ -40,29 +41,40 @@ interface BodyProps {
okignoreSynced: boolean;
}
const probeProps: BodyProps[] = [];
+type BodyMode = 'probe' | 'suspend' | 'throw';
function resetProbe() {
probeProps.length = 0;
}
+const pendingBodyChunk = new Promise<never>(() => {});
+
let mockUserBinding: ConfigBinding | null = null;
let mockUserSynced = false;
let mockOkignoreBinding: OkignoreBinding | null = null;
let mockOkignoreSynced = false;
+let mockCollabUrl: string | null = 'ws://test.invalid';
+let mockDesktopPresent = false;
+let mockBodyMode: BodyMode = 'probe';
+let mockShowInstallSkill = true;
+
+mock.module('@inkeep/open-knowledge-core', () => ({
+ get SHOW_INSTALL_SKILL() {
+ return mockShowInstallSkill;
+ },
+}));
mock.module('@/components/settings/SettingsDialogBodyLazy', () => ({
SettingsDialogBodyLazy: (props: BodyProps) => {
+ if (mockBodyMode === 'suspend') throw pendingBodyChunk;
+ if (mockBodyMode === 'throw') throw new Error('settings chunk failed');
probeProps.push(props);
return <div data-testid="settings-body-probe" />;
},
}));
-mock.module('@/components/settings/SettingsDialogErrorBoundary', () => ({
- SettingsDialogErrorBoundary: ({ children }: { children: React.ReactNode }) => <>{children}</>,
-}));
-
mock.module('@/editor/DocumentContext', () => ({
- useDocumentContext: () => ({ collabUrl: 'ws://test.invalid' }),
+ useDocumentContext: () => ({ collabUrl: mockCollabUrl }),
DocumentProvider: ({ children }: { children: React.ReactNode }) => children,
}));
@@ -84,7 +96,7 @@ mock.module('@/lib/config-provider', () => ({
mock.module('@/lib/handoff/use-claude-desktop-integration', () => ({
useClaudeDesktopIntegration: () => ({
- desktopPresent: false,
+ desktopPresent: mockDesktopPresent,
skillInstalled: false,
refresh: () => {},
}),
@@ -110,6 +122,10 @@ describe('SettingsDialogShell userBinding gating (Tier-3 mount)', () => {
mockUserSynced = false;
mockOkignoreBinding = null;
mockOkignoreSynced = false;
+ mockCollabUrl = 'ws://test.invalid';
+ mockDesktopPresent = false;
+ mockBodyMode = 'probe';
+ mockShowInstallSkill = true;
consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
});
@@ -150,76 +166,85 @@ describe('SettingsDialogShell userBinding gating (Tier-3 mount)', () => {
const latest = probeProps[probeProps.length - 1];
expect(latest?.userBinding).toBeNull();
});
-});
-
-describe('SettingsDialogShell version footer', () => {
- let consoleErrorSpy: ReturnType<typeof spyOn>;
- type WindowWithOkDesktop = typeof window & { okDesktop?: unknown };
- beforeEach(() => {
- mockUserBinding = null;
- mockUserSynced = true;
- mockOkignoreBinding = null;
- mockOkignoreSynced = false;
- consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
- });
+ test('renders the dialog frame, navigation landmark, and default Preferences section immediately', () => {
+ render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
- afterEach(() => {
- cleanup();
- consoleErrorSpy.mockRestore();
- delete (window as WindowWithOkDesktop).okDesktop;
+ expect(screen.getByTestId('settings-dialog')).toBeTruthy();
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ expect(screen.getByRole('heading', { name: 'Settings' })).toBeTruthy();
+ expect(screen.getByRole('navigation', { name: 'Settings sections' })).toBeTruthy();
+ expect(screen.getByText('User')).toBeTruthy();
+ expect(screen.getByText('This project')).toBeTruthy();
+ expect(screen.queryByText('Integrations') === null).toBe(true);
+ expect(
+ screen.getByTestId('settings-sidebar-item-preferences').getAttribute('aria-current'),
+ ).toBe('page');
+ expect(probeProps.at(-1)?.activeId).toBe('preferences');
});
- test('renders the version + "Release notes" link when bridge.appVersion is set', () => {
- const openExternal = mock(() => Promise.resolve());
- (window as WindowWithOkDesktop).okDesktop = {
- appVersion: '0.7.0',
- shell: { openExternal },
- };
+ test('disables project sections with an announced caption when no project is loaded', () => {
+ mockCollabUrl = null;
render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
- expect(screen.getByTestId('settings-sidebar-version').textContent).toContain('v0.7.0');
- expect(screen.getByTestId('settings-sidebar-release-notes')).toBeTruthy();
+ const sync = screen.getByTestId('settings-sidebar-item-sync') as HTMLButtonElement;
+ expect(sync.disabled).toBe(true);
+ expect(sync.getAttribute('aria-disabled')).toBe('true');
+ expect(sync.getAttribute('aria-describedby')).toBe('settings-group-project-caption');
+ expect(screen.getByText('Open a project to edit.')).toBeTruthy();
});
- test('clicking "Release notes" opens the GitHub Releases tag URL for the running version', () => {
- const openExternal = mock(() => Promise.resolve());
- (window as WindowWithOkDesktop).okDesktop = {
- appVersion: '0.7.0',
- shell: { openExternal },
- };
+ test('hides or shows the Integrations group from desktop availability', () => {
+ const { rerender } = render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
+ expect(screen.queryByTestId('settings-sidebar-item-claude-desktop') === null).toBe(true);
- render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
+ mockDesktopPresent = true;
+ rerender(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
- fireEvent.click(screen.getByTestId('settings-sidebar-release-notes'));
+ expect(screen.getByText('Integrations')).toBeTruthy();
+ expect(screen.getByTestId('settings-sidebar-item-claude-desktop')).toBeTruthy();
+ });
- expect(openExternal).toHaveBeenCalledTimes(1);
- expect(openExternal).toHaveBeenCalledWith(
- 'https://github.com/inkeep/open-knowledge/releases/tag/v0.7.0',
+ test('changes sections through the sidebar and resets to Preferences on each fresh open', async () => {
+ const { rerender } = render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
+
+ await userEvent.click(screen.getByTestId('settings-sidebar-item-sync'));
+ expect(screen.getByTestId('settings-sidebar-item-sync').getAttribute('aria-current')).toBe(
+ 'page',
);
+ expect(probeProps.at(-1)?.activeId).toBe('sync');
+
+ rerender(<SettingsDialogShell open={false} onOpenChange={() => {}} />);
+ rerender(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
+
+ expect(
+ screen.getByTestId('settings-sidebar-item-preferences').getAttribute('aria-current'),
+ ).toBe('page');
+ expect(probeProps.at(-1)?.activeId).toBe('preferences');
});
- test('percent-encodes a malformed version string defensively', () => {
- const openExternal = mock(() => Promise.resolve());
- (window as WindowWithOkDesktop).okDesktop = {
- appVersion: '0.7.0/../evil',
- shell: { openExternal },
- };
+ test('shows a non-null accessible skeleton while the body chunk is pending', () => {
+ mockBodyMode = 'suspend';
render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
- fireEvent.click(screen.getByTestId('settings-sidebar-release-notes'));
-
- expect(openExternal).toHaveBeenCalledWith(
- 'https://github.com/inkeep/open-knowledge/releases/tag/v0.7.0%2F..%2Fevil',
- );
+ const status = screen.getByTestId('settings-content-skeleton');
+ expect(status.getAttribute('role')).toBe('status');
+ expect(status.getAttribute('aria-live')).toBe('polite');
+ expect(status.getAttribute('aria-busy')).toBe('true');
+ expect(status.textContent).toContain('Loading settings');
+ expect(screen.getByTestId('settings-dialog')).toBeTruthy();
+ expect(screen.queryByTestId('settings-body-probe') === null).toBe(true);
});
- test('suppresses the footer entirely in web mode (no bridge → no "vundefined")', () => {
+ test('contains body render failures inside the dialog frame', async () => {
+ mockBodyMode = 'throw';
+
render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
- expect(screen.queryByTestId('settings-sidebar-version')).toBeNull();
- expect(screen.queryByTestId('settings-sidebar-release-notes')).toBeNull();
+ expect((await screen.findByRole('alert')).textContent).toContain('Settings failed to load');
+ expect(screen.getByTestId('settings-dialog')).toBeTruthy();
+ expect(screen.getByRole('navigation', { name: 'Settings sections' })).toBeTruthy();
});
});
diff --git a/packages/app/src/components/settings/SettingsDialogShell.install-flag.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogShell.install-flag.dom.test.tsx
new file mode 100644
index 000000000..d3332fcf9
--- /dev/null
+++ b/packages/app/src/components/settings/SettingsDialogShell.install-flag.dom.test.tsx
@@ -0,0 +1,75 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+
+mock.module('@inkeep/open-knowledge-core', () => ({
+ SHOW_INSTALL_SKILL: false,
+}));
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray | string, ...values: unknown[]) => {
+ if (typeof strings === 'string') return strings;
+ return strings.reduce(
+ (text, chunk, index) =>
+ `${text}${chunk}${index < values.length ? String(values[index]) : ''}`,
+ '',
+ );
+ },
+ }),
+}));
+
+mock.module('@/components/settings/SettingsDialogBodyLazy', () => ({
+ SettingsDialogBodyLazy: () => <div data-testid="settings-body-probe" />,
+}));
+
+mock.module('@/components/ui/dialog', () => ({
+ Dialog: ({ children, open }: { children?: ReactNode; open?: boolean }) =>
+ open ? <div role="dialog">{children}</div> : null,
+ DialogContent: ({ children, ...props }: { children?: ReactNode; [key: string]: unknown }) => (
+ <div {...props}>{children}</div>
+ ),
+ DialogDescription: ({ children }: { children?: ReactNode }) => <p>{children}</p>,
+ DialogTitle: ({ children, id }: { children?: ReactNode; id?: string }) => (
+ <h2 id={id}>{children}</h2>
+ ),
+}));
+
+mock.module('@/components/ui/skeleton', () => ({
+ Skeleton: ({ className }: { className?: string }) => <div className={className} />,
+}));
+
+mock.module('@/editor/DocumentContext', () => ({
+ useDocumentContext: () => ({ collabUrl: 'ws://test.invalid' }),
+}));
+
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({
+ userBinding: null,
+ userSynced: false,
+ okignoreBinding: null,
+ okignoreSynced: false,
+ }),
+}));
+
+mock.module('@/lib/handoff/use-claude-desktop-integration', () => ({
+ useClaudeDesktopIntegration: () => ({
+ desktopPresent: true,
+ }),
+}));
+
+const { SettingsDialogShell } = await import('./SettingsDialogShell');
+
+describe('SettingsDialogShell install-skill feature gate', () => {
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('hides the Claude Desktop integration when the install-skill flag is off', () => {
+ render(<SettingsDialogShell open={true} onOpenChange={() => {}} />);
+
+ expect(screen.queryByTestId('settings-sidebar-item-claude-desktop')).toBeNull();
+ expect(screen.queryByText('Integrations')).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/settings/SettingsDialogShell.test.ts b/packages/app/src/components/settings/SettingsDialogShell.test.ts
index d892aee84..8a5ee80af 100644
--- a/packages/app/src/components/settings/SettingsDialogShell.test.ts
+++ b/packages/app/src/components/settings/SettingsDialogShell.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, test } from 'bun:test';
-import SRC from './SettingsDialogShell?raw';
describe('SettingsDialogShell module', () => {
test('exports SettingsDialogShell component', async () => {
@@ -7,95 +6,3 @@ describe('SettingsDialogShell module', () => {
expect(typeof mod.SettingsDialogShell).toBe('function');
});
});
-
-describe('SettingsDialogShell source-level guards', () => {
- test('renders as a Dialog overlay (matches the redesign IA)', () => {
- expect(SRC).toMatch(/from\s+['"]@\/components\/ui\/dialog['"]/);
- expect(SRC).toMatch(/<Dialog\s+open=\{open\}/);
- expect(SRC).toMatch(/<DialogContent\b[\s\S]*?data-testid="settings-dialog"/);
- });
-
- test('Suspense fallback is a non-null content skeleton wrapping the lazy body', () => {
- expect(SRC).not.toMatch(/<Suspense\s+fallback=\{null\}/);
- expect(SRC).toMatch(/<Suspense\s+fallback=\{<SettingsContentSkeleton\s*\/>\}/);
- expect(SRC).toMatch(/<SettingsDialogBodyLazy\b/);
- expect(SRC).toContain('function SettingsContentSkeleton');
- });
-
- test('the lazy body Suspense is wrapped by SettingsDialogErrorBoundary (failure containment)', () => {
- expect(SRC).toMatch(/from\s+['"]@\/components\/settings\/SettingsDialogErrorBoundary['"]/);
- expect(SRC).toMatch(
- /<SettingsDialogErrorBoundary>\s*<Suspense\s+fallback=\{<SettingsContentSkeleton\s*\/>\}/,
- );
- });
-
- test('consumes the body via the preloadable SettingsDialogBodyLazy module', () => {
- expect(SRC).toMatch(/from\s+['"]@\/components\/settings\/SettingsDialogBodyLazy['"]/);
- expect(SRC).toContain('SettingsDialogBodyLazy');
- expect(SRC).not.toMatch(/\blazy\(/);
- expect(SRC).not.toMatch(/import\(['"]\.\/SettingsDialogBody['"]\)/);
- });
-
- test('consumes the user-scope ConfigBinding via useConfigContext()', () => {
- expect(SRC).toContain('useConfigContext');
- expect(SRC).toContain('userBinding');
- expect(SRC).toContain('userSynced');
- expect(SRC).toMatch(/userBinding=\{userSynced\s*\?\s*userBinding\s*:\s*null\}/);
- expect(SRC).not.toContain('useUserConfigDocConnection');
- expect(SRC).not.toMatch(/from\s+['"]@hocuspocus\/provider['"]/);
- expect(SRC).not.toMatch(/import\s+\*\s+as\s+Y\s+from\s+['"]yjs['"]/);
- expect(SRC).not.toMatch(/\bbindConfigDoc\(/);
- });
-
- test('resets to the Preferences page on each fresh open', () => {
- expect(SRC).toMatch(/useState<string>\(\s*['"]preferences['"]\s*\)/);
- expect(SRC).toMatch(/if\s*\(open\)\s*setActiveId\(\s*['"]preferences['"]\s*\)/);
- });
-
- test('sidebar exposes the three required group labels', () => {
- expect(SRC).toContain('label: t`User`');
- expect(SRC).toContain("id: 'hotkeys'");
- expect(SRC).toContain('label: t`Hotkeys`');
- expect(SRC).toContain('label: t`This project`');
- expect(SRC).toContain('label: t`Integrations`');
- });
-
- test('Integrations sidebar item hides when desktopPresent === false or install-skill flag is off', () => {
- expect(SRC).toMatch(
- /desktopPresent\s*&&\s*SHOW_INSTALL_SKILL[\s\S]*?\[\{[^}]*id:\s*['"]claude-desktop['"]/,
- );
- });
-
- test('no top-level scope toggle in the dialog header', () => {
- expect(SRC).not.toMatch(/value=\{scope\}/);
- expect(SRC).not.toMatch(/aria-label=["']Settings scope["']/);
- });
-
- test('hasProject derives from collabUrl !== null', () => {
- expect(SRC).toMatch(/collabUrl\s*!==\s*null/);
- expect(SRC).toContain('useDocumentContext');
- });
-
- test('sidebar is a single labeled <nav> landmark (no outer <aside>)', () => {
- expect(SRC).toMatch(/<nav\s+aria-label=\{t`Settings sections`\}/);
- expect(SRC).not.toMatch(/<aside\b/);
- expect(SRC).not.toMatch(/<nav>/);
- });
-
- test('active sidebar item uses aria-current="page" (in-dialog navigator)', () => {
- expect(SRC).toMatch(/aria-current=\{activeId === item\.id \? ['"]page['"] : undefined\}/);
- expect(SRC).not.toMatch(/aria-current=\{activeId === item\.id \? ['"]true['"]/);
- });
-
- test('disabled sidebar buttons describe themselves via the group caption', () => {
- expect(SRC).toMatch(/aria-describedby=\{group\.enabled \? undefined : captionId\}/);
- expect(SRC).toContain('captionId');
- });
-
- test('SettingsContentSkeleton announces loading via role=status + aria-busy', () => {
- expect(SRC).toMatch(/role="status"/);
- expect(SRC).toMatch(/aria-live="polite"/);
- expect(SRC).toMatch(/aria-busy="true"/);
- expect(SRC).toContain('Loading settings');
- });
-});
diff --git a/packages/app/src/components/settings/use-config-form.dom.test.tsx b/packages/app/src/components/settings/use-config-form.dom.test.tsx
new file mode 100644
index 000000000..76fe1acbf
--- /dev/null
+++ b/packages/app/src/components/settings/use-config-form.dom.test.tsx
@@ -0,0 +1,89 @@
+import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
+import type { Config, ConfigBinding, ConfigPatch } from '@inkeep/open-knowledge-core';
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { useConfigForm } from './use-config-form';
+
+type ConfigListener = (next: Config) => void;
+
+let subscribeListener: ConfigListener | null = null;
+let unsubscribeMock = mock(() => {});
+let patchMock = mock((_patch: ConfigPatch) => ({
+ ok: true as const,
+ effective: {} as Config,
+ appliedPaths: ['appearance.theme'],
+}));
+let commitResult: boolean | null = null;
+
+function createBinding(initial: Config): ConfigBinding {
+ return {
+ current: () => initial,
+ subscribe: (listener: ConfigListener) => {
+ subscribeListener = listener;
+ return () => {
+ if (subscribeListener === listener) subscribeListener = null;
+ unsubscribeMock();
+ };
+ },
+ patch: patchMock,
+ } as unknown as ConfigBinding;
+}
+
+function Harness({ binding }: { binding: ConfigBinding }) {
+ const { form, commitField } = useConfigForm(binding);
+ return (
+ <form>
+ <label htmlFor="theme-input">Theme</label>
+ <input id="theme-input" {...form.register('appearance.theme')} />
+ <button
+ type="button"
+ onClick={() => {
+ commitResult = commitField('appearance.theme');
+ }}
+ >
+ Commit
+ </button>
+ </form>
+ );
+}
+
+describe('useConfigForm runtime wiring', () => {
+ beforeEach(() => {
+ subscribeListener = null;
+ unsubscribeMock = mock(() => {});
+ patchMock = mock((_patch: ConfigPatch) => ({
+ ok: true as const,
+ effective: {} as Config,
+ appliedPaths: ['appearance.theme'],
+ }));
+ commitResult = null;
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ test('seeds useForm from binding.current, subscribes to external updates, and commits through the binding', () => {
+ const binding = createBinding({ appearance: { theme: 'dark' } } as Config);
+ const { unmount } = render(<Harness binding={binding} />);
+
+ const input = screen.getByLabelText('Theme') as HTMLInputElement;
+ expect(input.value).toBe('dark');
+ expect(subscribeListener).not.toBeNull();
+
+ act(() => {
+ subscribeListener?.({ appearance: { theme: 'light' } } as Config);
+ });
+ expect(input.value).toBe('light');
+
+ fireEvent.change(input, { target: { value: 'system' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Commit' }));
+
+ expect(commitResult).toBe(true);
+ expect(patchMock).toHaveBeenCalledWith({ appearance: { theme: 'system' } });
+
+ unmount();
+
+ expect(unsubscribeMock).toHaveBeenCalledTimes(1);
+ expect(subscribeListener).toBeNull();
+ });
+});
diff --git a/packages/app/src/components/settings/use-config-form.test.ts b/packages/app/src/components/settings/use-config-form.test.ts
index d3c129a23..28ce6da5b 100644
--- a/packages/app/src/components/settings/use-config-form.test.ts
+++ b/packages/app/src/components/settings/use-config-form.test.ts
@@ -13,7 +13,6 @@ import {
type RunCommitForm,
runCommit,
} from './use-config-form';
-import SRC from './use-config-form?raw';
describe('applyExternalUpdate', () => {
test('calls form.reset with keepDirtyValues + keepDirty + keepTouched', () => {
@@ -375,22 +374,3 @@ describe('useConfigForm module shape', () => {
expect(typeof mod.pickFirstIssueForPath).toBe('function');
});
});
-
-describe('useConfigForm source-level guards', () => {
- test('initializes useForm with binding.current() as defaultValues + no resolver', () => {
- expect(SRC).toContain('useForm');
- expect(SRC).toContain('defaultValues: binding.current()');
- expect(SRC).not.toContain('zodResolver');
- expect(SRC).not.toMatch(/resolver:\s/);
- });
-
- test('subscribes to binding and bridges to form via applyExternalUpdate', () => {
- expect(SRC).toContain('binding.subscribe');
- expect(SRC).toContain('applyExternalUpdate');
- });
-
- test('does not instantiate client-side IndexeddbPersistence', () => {
- expect(SRC).not.toContain('IndexeddbPersistence');
- expect(SRC).not.toContain('createClientPersistence');
- });
-});
diff --git a/packages/app/src/components/ui/command.dom.test.tsx b/packages/app/src/components/ui/command.dom.test.tsx
index 3f754a84b..05de8861c 100644
--- a/packages/app/src/components/ui/command.dom.test.tsx
+++ b/packages/app/src/components/ui/command.dom.test.tsx
@@ -1,113 +1,70 @@
-import { afterEach, describe, expect, test } from 'bun:test';
+import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, render } from '@testing-library/react';
-import { CommandDialog, CommandInput, CommandList } from './command';
+import type { ReactNode } from 'react';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
-type WindowGlobals = {
- MutationObserver?: typeof MutationObserver;
- NodeFilter?: typeof NodeFilter;
-};
-type GlobalWithDomShims = typeof globalThis &
- WindowGlobals & {
- window?: WindowGlobals;
- ResizeObserver?: unknown;
- };
-const globalWithDomShims = globalThis as GlobalWithDomShims;
-if (
- globalWithDomShims.MutationObserver === undefined &&
- globalWithDomShims.window?.MutationObserver !== undefined
-) {
- globalWithDomShims.MutationObserver = globalWithDomShims.window.MutationObserver;
-}
-if (
- globalWithDomShims.NodeFilter === undefined &&
- globalWithDomShims.window?.NodeFilter !== undefined
-) {
- globalWithDomShims.NodeFilter = globalWithDomShims.window.NodeFilter;
-}
-if (globalWithDomShims.ResizeObserver === undefined) {
- class NoopResizeObserver {
- observe() {}
- unobserve() {}
- disconnect() {}
- }
- globalWithDomShims.ResizeObserver = NoopResizeObserver;
-}
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
-afterEach(() => {
- cleanup();
-});
+describe('CommandDialog runtime contracts', () => {
+ afterEach(() => cleanup());
-const KEYFRAME_CLASSES = [
- 'animate-in',
- 'fade-in-0',
- 'zoom-in-95',
- 'animate-out',
- 'fade-out-0',
- 'zoom-out-95',
-] as const;
+ test('exports the full Command API surface', async () => {
+ const mod = await import('./command');
+ for (const name of [
+ 'Command',
+ 'CommandDialog',
+ 'CommandEmpty',
+ 'CommandGroup',
+ 'CommandInput',
+ 'CommandItem',
+ 'CommandList',
+ 'CommandSeparator',
+ 'CommandShortcut',
+ ]) {
+ expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
+ }
+ });
-const SNAPPY_TOKENS = [
- 'transition-[opacity,scale]',
- 'transition-opacity',
- 'ease-(--ease-out-strong)',
- 'starting:opacity-0',
- 'starting:scale-95',
- 'data-closed:duration-0',
-] as const;
+ test('top-anchors the dialog content at runtime', async () => {
+ const { CommandDialog, CommandInput, CommandList } = await import('./command');
-function renderPalette() {
- return render(
- <CommandDialog open={true}>
- <CommandInput placeholder="search" />
- <CommandList />
- </CommandDialog>,
- );
-}
+ render(
+ <CommandDialog open={true} showCloseButton={false}>
+ <CommandInput placeholder="Search" />
+ <CommandList />
+ </CommandDialog>,
+ );
-describe('CommandDialog inherits DialogContent upstream keyframe motion', () => {
- test('content carries the animate/fade/zoom keyframe classes', () => {
- renderPalette();
const content = document.querySelector('[data-slot="dialog-content"]');
- expect(content).not.toBeNull();
- const cls = content?.className ?? '';
- for (const keyframeClass of KEYFRAME_CLASSES) {
- expect(cls).toContain(keyframeClass);
- }
+ expect(content).toBeTruthy();
+ const className = content?.getAttribute('class') ?? '';
+ expectVisualClassTokens(className, ['top-[12vh]', 'translate-y-0', 'overflow-hidden', 'p-0']);
+ expectVisualClassTokensAbsent(className, ['top-1/2', '-translate-y-1/2']);
});
- test('overlay carries animate-in/animate-out and the fade siblings', () => {
- renderPalette();
- const overlay = document.querySelector('[data-slot="dialog-overlay"]');
- expect(overlay).not.toBeNull();
- const cls = overlay?.className ?? '';
- expect(cls).toContain('animate-in');
- expect(cls).toContain('animate-out');
- expect(cls).toContain('fade-in-0');
- expect(cls).toContain('fade-out-0');
- });
+ test('does not expose a returned snappy placement tier on runtime surfaces', async () => {
+ const { CommandDialog, CommandInput, CommandList } = await import('./command');
- test('the pruned snappy transition tier is absent from the rendered palette', () => {
- renderPalette();
- const contentCls = document.querySelector('[data-slot="dialog-content"]')?.className ?? '';
- const overlayCls = document.querySelector('[data-slot="dialog-overlay"]')?.className ?? '';
- for (const token of SNAPPY_TOKENS) {
- expect(contentCls).not.toContain(token);
- expect(overlayCls).not.toContain(token);
- }
- });
-});
+ render(
+ <CommandDialog open={true} showCloseButton={false}>
+ <CommandInput placeholder="Search" />
+ <CommandList />
+ </CommandDialog>,
+ );
-describe('CommandDialog is top-anchored (inline className override)', () => {
- test('rendered content anchors near the top, not viewport-center', () => {
- renderPalette();
- const content = document.querySelector('[data-slot="dialog-content"]');
- expect(content).not.toBeNull();
- const cls = content?.className ?? '';
- expect(cls).toContain('top-[12vh]');
- expect(cls).toContain('translate-y-0');
- expect(cls).not.toContain('top-1/2');
- expect(cls).not.toContain('-translate-y-1/2');
- expect(cls).toContain('left-1/2');
- expect(cls).toContain('-translate-x-1/2');
+ const surfaces = [
+ ...document.querySelectorAll('[data-slot="dialog-content"], [data-slot="command"]'),
+ ]
+ .map((el) => el.getAttribute('class') ?? '')
+ .join(' ');
+
+ for (const token of ['transition-[opacity,scale]', 'placement-', 'data-placement']) {
+ expect(surfaces).not.toContain(token);
+ }
});
});
diff --git a/packages/app/src/components/ui/command.test.ts b/packages/app/src/components/ui/command.test.ts
deleted file mode 100644
index d016a1b12..000000000
--- a/packages/app/src/components/ui/command.test.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './command?raw';
-
-describe('Command module', () => {
- test('exports the full Command API surface', async () => {
- const mod = await import('./command');
- for (const name of [
- 'Command',
- 'CommandDialog',
- 'CommandEmpty',
- 'CommandGroup',
- 'CommandInput',
- 'CommandItem',
- 'CommandList',
- 'CommandSeparator',
- 'CommandShortcut',
- ]) {
- expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
- }
- });
-});
-
-describe('CommandDialog top-anchored placement', () => {
- test('CommandDialog applies the top-[12vh] inline override to DialogContent', () => {
- expect(SRC).toMatch(
- /<DialogContent[\s\S]*?className=\{cn\(\s*'top-\[12vh\] translate-y-0 overflow-hidden p-0', className\)\}/,
- );
- });
-
- test('CommandDialog declares no transition or placement prop', () => {
- expect(SRC).not.toMatch(/transition\?:/);
- expect(SRC).not.toMatch(/placement\?:/);
- expect(SRC).not.toMatch(/transition\s*=/);
- expect(SRC).not.toMatch(/placement\s*=/);
- });
-});
diff --git a/packages/app/src/components/ui/context-menu.dom.test.tsx b/packages/app/src/components/ui/context-menu.dom.test.tsx
new file mode 100644
index 000000000..d5a95a4af
--- /dev/null
+++ b/packages/app/src/components/ui/context-menu.dom.test.tsx
@@ -0,0 +1,141 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { act } from 'react';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+const A11Y_OPT_IN = [
+ 'motion-reduce:data-open:animate-none',
+ 'motion-reduce:data-closed:animate-none',
+ 'motion-reduce:duration-0',
+] as const;
+
+const UPSTREAM_MOTION_TOKENS = [
+ 'duration-100',
+ 'data-open:animate-in',
+ 'data-open:fade-in-0',
+ 'data-open:zoom-in-95',
+ 'data-closed:animate-out',
+ 'data-closed:fade-out-0',
+ 'data-closed:zoom-out-95',
+ 'data-[side=bottom]:slide-in-from-top-2',
+ 'data-[side=left]:slide-in-from-right-2',
+ 'data-[side=right]:slide-in-from-left-2',
+ 'data-[side=top]:slide-in-from-bottom-2',
+] as const;
+
+const SNAPPY_TOKENS = [
+ 'transition-[opacity,scale]',
+ 'ease-(--ease-out-strong)',
+ 'starting:opacity-0',
+ 'starting:scale-95',
+ 'data-closed:duration-0',
+ 'FORKED FROM radix-nova',
+] as const;
+
+async function renderContextMenu() {
+ const {
+ ContextMenu,
+ ContextMenuContent,
+ ContextMenuItem,
+ ContextMenuSub,
+ ContextMenuSubContent,
+ ContextMenuSubTrigger,
+ ContextMenuTrigger,
+ } = await import('./context-menu');
+
+ render(
+ <ContextMenu>
+ <ContextMenuTrigger asChild>
+ <button type="button">Target</button>
+ </ContextMenuTrigger>
+ <ContextMenuContent forceMount={true}>
+ <ContextMenuItem>Open</ContextMenuItem>
+ <ContextMenuSub open={true}>
+ <ContextMenuSubTrigger>More</ContextMenuSubTrigger>
+ <ContextMenuSubContent forceMount={true}>
+ <ContextMenuItem>Nested</ContextMenuItem>
+ </ContextMenuSubContent>
+ </ContextMenuSub>
+ </ContextMenuContent>
+ </ContextMenu>,
+ );
+
+ await act(async () => {
+ fireEvent.contextMenu(screen.getByText('Target'));
+ await Promise.resolve();
+ });
+}
+
+describe('ContextMenu runtime class contracts', () => {
+ afterEach(() => cleanup());
+
+ test('exports the full ContextMenu API surface', async () => {
+ const mod = await import('./context-menu');
+ for (const name of [
+ 'ContextMenu',
+ 'ContextMenuCheckboxItem',
+ 'ContextMenuContent',
+ 'ContextMenuGroup',
+ 'ContextMenuItem',
+ 'ContextMenuLabel',
+ 'ContextMenuPortal',
+ 'ContextMenuRadioGroup',
+ 'ContextMenuRadioItem',
+ 'ContextMenuSeparator',
+ 'ContextMenuShortcut',
+ 'ContextMenuSub',
+ 'ContextMenuSubContent',
+ 'ContextMenuSubTrigger',
+ 'ContextMenuTrigger',
+ ]) {
+ expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
+ }
+ });
+
+ test.each([
+ 'context-menu-content',
+ 'context-menu-sub-content',
+ ] as const)('%s carries keyframe motion and reduced-motion opt-in at runtime', async (slot) => {
+ await renderContextMenu();
+
+ const surface = document.querySelector(`[data-slot="${slot}"]`);
+ expect(surface).toBeTruthy();
+ const className = surface?.getAttribute('class') ?? '';
+
+ expectVisualClassTokens(className, [
+ ...UPSTREAM_MOTION_TOKENS,
+ 'origin-(--radix-context-menu-content-transform-origin)',
+ ...A11Y_OPT_IN,
+ ]);
+ });
+
+ test('subtrigger keeps its open-state highlight classes at runtime', async () => {
+ await renderContextMenu();
+
+ const trigger = document.querySelector('[data-slot="context-menu-sub-trigger"]');
+ expectVisualClassTokens(trigger?.getAttribute('class'), [
+ 'data-open:bg-accent',
+ 'data-open:text-accent-foreground',
+ ]);
+ });
+
+ test('snappy transition tier and long-form state drift do not return', async () => {
+ await renderContextMenu();
+
+ const surfaces = [
+ ...document.querySelectorAll(
+ '[data-slot="context-menu-content"], [data-slot="context-menu-sub-content"], [data-slot="context-menu-sub-trigger"]',
+ ),
+ ]
+ .map((el) => el.getAttribute('class') ?? '')
+ .join(' ');
+
+ expectVisualClassTokensAbsent(surfaces, SNAPPY_TOKENS);
+ expect(surfaces).not.toMatch(
+ /data-\[state=(?:open|closed)\]:(?:animate|fade|zoom|slide|bg|text)/,
+ );
+ });
+});
diff --git a/packages/app/src/components/ui/context-menu.test.ts b/packages/app/src/components/ui/context-menu.test.ts
deleted file mode 100644
index 820b16c96..000000000
--- a/packages/app/src/components/ui/context-menu.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './context-menu?raw';
-
-const A11Y_OPT_IN =
- 'motion-reduce:data-open:animate-none motion-reduce:data-closed:animate-none motion-reduce:duration-0';
-
-const UPSTREAM_MOTION_TOKENS = [
- 'duration-100',
- 'data-open:animate-in',
- 'data-open:fade-in-0',
- 'data-open:zoom-in-95',
- 'data-closed:animate-out',
- 'data-closed:fade-out-0',
- 'data-closed:zoom-out-95',
- 'data-[side=bottom]:slide-in-from-top-2',
- 'data-[side=left]:slide-in-from-right-2',
- 'data-[side=right]:slide-in-from-left-2',
- 'data-[side=top]:slide-in-from-bottom-2',
-] as const;
-
-const SNAPPY_TOKENS = [
- 'transition-[opacity,scale]',
- 'ease-(--ease-out-strong)',
- 'starting:opacity-0',
- 'starting:scale-95',
- 'data-closed:duration-0',
- 'FORKED FROM radix-nova',
-] as const;
-
-function contentClassName(slot: string): string {
- const m = SRC.match(new RegExp(`data-slot="${slot}"[\\s\\S]*?'([^']*)'`));
- expect(m).not.toBeNull();
- return m?.[1] ?? '';
-}
-
-describe('ContextMenu module', () => {
- test('exports the full ContextMenu API surface', async () => {
- const mod = await import('./context-menu');
- for (const name of [
- 'ContextMenu',
- 'ContextMenuCheckboxItem',
- 'ContextMenuContent',
- 'ContextMenuGroup',
- 'ContextMenuItem',
- 'ContextMenuLabel',
- 'ContextMenuPortal',
- 'ContextMenuRadioGroup',
- 'ContextMenuRadioItem',
- 'ContextMenuSeparator',
- 'ContextMenuShortcut',
- 'ContextMenuSub',
- 'ContextMenuSubContent',
- 'ContextMenuSubTrigger',
- 'ContextMenuTrigger',
- ]) {
- expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
- }
- });
-});
-
-describe('ContextMenu upstream overlay motion', () => {
- for (const slot of ['context-menu-content', 'context-menu-sub-content']) {
- test(`${slot} carries the upstream keyframe motion block`, () => {
- const cls = contentClassName(slot);
- for (const token of UPSTREAM_MOTION_TOKENS) {
- expect(cls).toContain(token);
- }
- });
-
- test(`${slot} carries the reduced-motion a11y opt-in`, () => {
- expect(contentClassName(slot)).toContain(A11Y_OPT_IN);
- });
-
- test(`${slot} pivots the scale from the trigger origin`, () => {
- expect(contentClassName(slot)).toContain(
- 'origin-(--radix-context-menu-content-transform-origin)',
- );
- });
- }
-
- test('ContextMenuSubTrigger retains its data-open: open-state highlight', () => {
- expect(SRC).toContain('data-open:bg-accent');
- expect(SRC).toContain('data-open:text-accent-foreground');
- });
-
- test('the snappy transition tier cannot silently return', () => {
- for (const token of SNAPPY_TOKENS) {
- expect(SRC).not.toContain(token);
- }
- });
-
- test('no long-form data-[state] animation/highlight drift', () => {
- expect(SRC).not.toMatch(/data-\[state=(?:open|closed)\]:(?:animate|fade|zoom|slide|bg|text)/);
- });
-});
diff --git a/packages/app/src/components/ui/dialog.dom.test.tsx b/packages/app/src/components/ui/dialog.dom.test.tsx
new file mode 100644
index 000000000..0b98d6cc7
--- /dev/null
+++ b/packages/app/src/components/ui/dialog.dom.test.tsx
@@ -0,0 +1,117 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+const A11Y_OPT_IN = [
+ 'motion-reduce:data-open:animate-none',
+ 'motion-reduce:data-closed:animate-none',
+ 'motion-reduce:duration-0',
+] as const;
+
+const SNAPPY_TOKENS = [
+ 'transition-[opacity,scale]',
+ 'transition-opacity',
+ 'ease-(--ease-out-strong)',
+ 'starting:opacity-0',
+ 'starting:scale-95',
+ 'data-closed:duration-0',
+] as const;
+
+async function renderDialogContent() {
+ const { Dialog, DialogContent, DialogDescription, DialogTitle } = await import('./dialog');
+
+ render(
+ <Dialog open={true}>
+ <DialogContent showCloseButton={false}>
+ <DialogTitle>Dialog title</DialogTitle>
+ <DialogDescription>Dialog description</DialogDescription>
+ Body
+ </DialogContent>
+ </Dialog>,
+ );
+}
+
+describe('Dialog runtime class contracts', () => {
+ afterEach(() => cleanup());
+
+ test('exports the full Dialog API surface', async () => {
+ const mod = await import('./dialog');
+ for (const name of [
+ 'Dialog',
+ 'DialogBody',
+ 'DialogClose',
+ 'DialogContent',
+ 'DialogDescription',
+ 'DialogFooter',
+ 'DialogHeader',
+ 'DialogOverlay',
+ 'DialogPortal',
+ 'DialogTitle',
+ 'DialogTrigger',
+ ]) {
+ expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
+ }
+ });
+
+ test('overlay carries drag opt-out, fade motion, and reduced-motion opt-in', async () => {
+ await renderDialogContent();
+
+ const overlay = document.querySelector('[data-slot="dialog-overlay"]');
+ expect(overlay).toBeTruthy();
+ const className = overlay?.getAttribute('class') ?? '';
+ expectVisualClassTokens(className, [
+ 'duration-100',
+ 'data-open:animate-in',
+ 'data-open:fade-in-0',
+ 'data-closed:animate-out',
+ 'data-closed:fade-out-0',
+ '[-webkit-app-region:no-drag]',
+ ...A11Y_OPT_IN,
+ ]);
+ });
+
+ test('content is centered, drag-safe, and uses zoom/fade motion without slides', async () => {
+ await renderDialogContent();
+
+ const content = document.querySelector('[data-slot="dialog-content"]');
+ expect(content).toBeTruthy();
+ const className = content?.getAttribute('class') ?? '';
+ expectVisualClassTokens(className, [
+ 'top-1/2',
+ '-translate-y-1/2',
+ 'left-1/2',
+ '-translate-x-1/2',
+ 'max-h-[calc(100dvh-2rem)]',
+ 'duration-100',
+ 'data-open:animate-in',
+ 'data-open:fade-in-0',
+ 'data-open:zoom-in-95',
+ 'data-closed:animate-out',
+ 'data-closed:fade-out-0',
+ 'data-closed:zoom-out-95',
+ '[-webkit-app-region:no-drag]',
+ ...A11Y_OPT_IN,
+ ]);
+ expectVisualClassTokensAbsent(className, ['slide-in-from']);
+ });
+
+ test('snappy transition tier does not return on runtime surfaces', async () => {
+ await renderDialogContent();
+
+ const surfaces = [
+ ...document.querySelectorAll('[data-slot="dialog-overlay"], [data-slot="dialog-content"]'),
+ ]
+ .map((el) => el.getAttribute('class') ?? '')
+ .join(' ');
+
+ expectVisualClassTokensAbsent(surfaces, SNAPPY_TOKENS);
+ });
+});
diff --git a/packages/app/src/components/ui/dialog.test.ts b/packages/app/src/components/ui/dialog.test.ts
deleted file mode 100644
index 215f9bd4b..000000000
--- a/packages/app/src/components/ui/dialog.test.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import GLOBALS from '../../globals.css?raw';
-import SRC from './dialog?raw';
-
-const A11Y_OPT_IN =
- 'motion-reduce:data-open:animate-none motion-reduce:data-closed:animate-none motion-reduce:duration-0';
-
-const SNAPPY_TOKENS = [
- 'transition-[opacity,scale]',
- 'transition-opacity',
- 'ease-(--ease-out-strong)',
- 'starting:opacity-0',
- 'starting:scale-95',
- 'data-closed:duration-0',
-] as const;
-
-function classNameLiteral(slot: string): string {
- const m = SRC.match(new RegExp(`data-slot="${slot}"[\\s\\S]*?cn\\(\\s*'([^']*)'`));
- return m?.[1] ?? '';
-}
-
-describe('Dialog module', () => {
- test('exports the full Dialog API surface', async () => {
- const mod = await import('./dialog');
- for (const name of [
- 'Dialog',
- 'DialogBody',
- 'DialogClose',
- 'DialogContent',
- 'DialogDescription',
- 'DialogFooter',
- 'DialogHeader',
- 'DialogOverlay',
- 'DialogPortal',
- 'DialogTitle',
- 'DialogTrigger',
- ]) {
- expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
- }
- });
-});
-
-describe('Dialog Electron drag-region opt-out', () => {
- test('DialogContent carries [-webkit-app-region:no-drag]', () => {
- expect(SRC).toContain('[-webkit-app-region:no-drag]');
- const occurrences = SRC.match(/\[-webkit-app-region:no-drag\]/g) ?? [];
- expect(occurrences.length).toBeGreaterThanOrEqual(2);
- });
-});
-
-describe('Dialog upstream keyframe motion', () => {
- test('DialogOverlay uses the upstream duration-100 fade block', () => {
- const overlay = classNameLiteral('dialog-overlay');
- expect(overlay).not.toBe('');
- expect(overlay).toContain('duration-100');
- expect(overlay).toContain('data-open:animate-in');
- expect(overlay).toContain('data-open:fade-in-0');
- expect(overlay).toContain('data-closed:animate-out');
- expect(overlay).toContain('data-closed:fade-out-0');
- });
-
- test('DialogContent uses the upstream duration-100 zoom/fade block', () => {
- const content = classNameLiteral('dialog-content');
- expect(content).not.toBe('');
- expect(content).toContain('duration-100');
- expect(content).toContain('data-open:animate-in');
- expect(content).toContain('data-open:fade-in-0');
- expect(content).toContain('data-open:zoom-in-95');
- expect(content).toContain('data-closed:animate-out');
- expect(content).toContain('data-closed:fade-out-0');
- expect(content).toContain('data-closed:zoom-out-95');
- });
-
- test('DialogContent zooms from center — no slide motion', () => {
- expect(classNameLiteral('dialog-content')).not.toContain('slide-in-from');
- });
-
- test('overlay and content both carry the motion-reduce a11y opt-in', () => {
- expect(classNameLiteral('dialog-overlay')).toContain(A11Y_OPT_IN);
- expect(classNameLiteral('dialog-content')).toContain(A11Y_OPT_IN);
- });
-});
-
-describe('Dialog viewport centering', () => {
- test('DialogContent is unconditionally centered on both axes', () => {
- const content = classNameLiteral('dialog-content');
- expect(content).toContain('top-1/2');
- expect(content).toContain('-translate-y-1/2');
- expect(content).toContain('left-1/2');
- expect(content).toContain('-translate-x-1/2');
- expect(content).toContain('max-h-[calc(100dvh-2rem)]');
- });
-});
-
-describe('Dialog has no snappy tier or transition/placement props', () => {
- test('the snappy transition tier cannot silently return', () => {
- for (const token of SNAPPY_TOKENS) {
- expect(SRC).not.toContain(token);
- }
- });
-
- test('the transition and placement props are gone', () => {
- expect(SRC).not.toMatch(/transition\?:/);
- expect(SRC).not.toMatch(/placement\?:/);
- expect(SRC).not.toMatch(/transition\s*===/);
- expect(SRC).not.toMatch(/placement\s*===/);
- expect(SRC).not.toMatch(/<DialogOverlay\s+transition=/);
- });
-});
-
-describe('Dialog/Sheet reduced-transparency baseline (globals.css)', () => {
- test('a prefers-reduced-transparency block strips backdrop-filter from both overlays', () => {
- const block = GLOBALS.match(
- /@media \(prefers-reduced-transparency: reduce\) \{[^}]*\[data-slot="dialog-overlay"\][\s\S]*?\}\s*\}/,
- );
- expect(block).not.toBeNull();
- const blockText = block?.[0] ?? '';
- expect(blockText).toContain('[data-slot="dialog-overlay"]');
- expect(blockText).toContain('[data-slot="sheet-overlay"]');
- expect(blockText).toContain('backdrop-filter: none');
- expect(blockText).toContain('-webkit-backdrop-filter: none');
- });
-
- test('the electron outer-canvas reduced-transparency block is left intact', () => {
- expect(GLOBALS).toContain('html.electron-mode [data-slot="sidebar-wrapper"]');
- });
-});
diff --git a/packages/app/src/components/ui/dropdown-menu.dom.test.tsx b/packages/app/src/components/ui/dropdown-menu.dom.test.tsx
new file mode 100644
index 000000000..ba2d122ba
--- /dev/null
+++ b/packages/app/src/components/ui/dropdown-menu.dom.test.tsx
@@ -0,0 +1,142 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { cleanup, render } from '@testing-library/react';
+import { act } from 'react';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+const A11Y_OPT_IN = [
+ 'motion-reduce:data-open:animate-none',
+ 'motion-reduce:data-closed:animate-none',
+ 'motion-reduce:duration-0',
+] as const;
+
+const UPSTREAM_MOTION_TOKENS = [
+ 'duration-100',
+ 'data-open:animate-in',
+ 'data-open:fade-in-0',
+ 'data-open:zoom-in-95',
+ 'data-closed:animate-out',
+ 'data-closed:fade-out-0',
+ 'data-closed:zoom-out-95',
+ 'data-[side=bottom]:slide-in-from-top-2',
+ 'data-[side=left]:slide-in-from-right-2',
+ 'data-[side=right]:slide-in-from-left-2',
+ 'data-[side=top]:slide-in-from-bottom-2',
+] as const;
+
+const SNAPPY_TOKENS = [
+ 'transition-[opacity,scale]',
+ 'ease-(--ease-out-strong)',
+ 'starting:opacity-0',
+ 'starting:scale-95',
+ 'data-closed:duration-0',
+ 'FORKED FROM radix-nova',
+] as const;
+
+async function renderDropdownMenu() {
+ const {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+ } = await import('./dropdown-menu');
+
+ await act(async () => {
+ render(
+ <DropdownMenu open={true}>
+ <DropdownMenuTrigger>Target</DropdownMenuTrigger>
+ <DropdownMenuContent forceMount={true}>
+ <DropdownMenuItem>Open</DropdownMenuItem>
+ <DropdownMenuSub open={true}>
+ <DropdownMenuSubTrigger>More</DropdownMenuSubTrigger>
+ <DropdownMenuSubContent forceMount={true}>
+ <DropdownMenuItem>Nested</DropdownMenuItem>
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ </DropdownMenuContent>
+ </DropdownMenu>,
+ );
+ await Promise.resolve();
+ });
+}
+
+describe('DropdownMenu runtime class contracts', () => {
+ afterEach(() => cleanup());
+
+ test('exports the full DropdownMenu API surface', async () => {
+ const mod = await import('./dropdown-menu');
+ for (const name of [
+ 'DropdownMenu',
+ 'DropdownMenuCheckboxItem',
+ 'DropdownMenuContent',
+ 'DropdownMenuGroup',
+ 'DropdownMenuItem',
+ 'DropdownMenuLabel',
+ 'DropdownMenuPortal',
+ 'DropdownMenuRadioGroup',
+ 'DropdownMenuRadioItem',
+ 'DropdownMenuSeparator',
+ 'DropdownMenuShortcut',
+ 'DropdownMenuSub',
+ 'DropdownMenuSubContent',
+ 'DropdownMenuSubTrigger',
+ 'DropdownMenuTrigger',
+ ]) {
+ expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
+ }
+ });
+
+ test.each([
+ 'dropdown-menu-content',
+ 'dropdown-menu-sub-content',
+ ] as const)('%s carries keyframe motion and reduced-motion opt-in at runtime', async (slot) => {
+ await renderDropdownMenu();
+
+ const surface = document.querySelector(`[data-slot="${slot}"]`);
+ expect(surface).toBeTruthy();
+ const className = surface?.getAttribute('class') ?? '';
+
+ expectVisualClassTokens(className, [
+ ...UPSTREAM_MOTION_TOKENS,
+ 'origin-(--radix-dropdown-menu-content-transform-origin)',
+ ...A11Y_OPT_IN,
+ ]);
+ });
+
+ test('content keeps its closed-state overflow clip and subtrigger highlight classes', async () => {
+ await renderDropdownMenu();
+
+ const content = document.querySelector('[data-slot="dropdown-menu-content"]');
+ expectVisualClassTokens(content?.getAttribute('class'), [
+ 'data-[state=closed]:overflow-hidden',
+ ]);
+
+ const trigger = document.querySelector('[data-slot="dropdown-menu-sub-trigger"]');
+ expectVisualClassTokens(trigger?.getAttribute('class'), [
+ 'data-open:bg-accent',
+ 'data-open:text-accent-foreground',
+ ]);
+ });
+
+ test('snappy transition tier and long-form state drift do not return', async () => {
+ await renderDropdownMenu();
+
+ const surfaces = [
+ ...document.querySelectorAll(
+ '[data-slot="dropdown-menu-content"], [data-slot="dropdown-menu-sub-content"], [data-slot="dropdown-menu-sub-trigger"]',
+ ),
+ ]
+ .map((el) => el.getAttribute('class') ?? '')
+ .join(' ');
+
+ expectVisualClassTokensAbsent(surfaces, SNAPPY_TOKENS);
+ expect(surfaces).not.toMatch(
+ /data-\[state=(?:open|closed)\]:(?:animate|fade|zoom|slide|bg|text)/,
+ );
+ });
+});
diff --git a/packages/app/src/components/ui/dropdown-menu.test.ts b/packages/app/src/components/ui/dropdown-menu.test.ts
deleted file mode 100644
index bf0d39b0d..000000000
--- a/packages/app/src/components/ui/dropdown-menu.test.ts
+++ /dev/null
@@ -1,101 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './dropdown-menu?raw';
-
-const A11Y_OPT_IN =
- 'motion-reduce:data-open:animate-none motion-reduce:data-closed:animate-none motion-reduce:duration-0';
-
-const UPSTREAM_MOTION_TOKENS = [
- 'duration-100',
- 'data-open:animate-in',
- 'data-open:fade-in-0',
- 'data-open:zoom-in-95',
- 'data-closed:animate-out',
- 'data-closed:fade-out-0',
- 'data-closed:zoom-out-95',
- 'data-[side=bottom]:slide-in-from-top-2',
- 'data-[side=left]:slide-in-from-right-2',
- 'data-[side=right]:slide-in-from-left-2',
- 'data-[side=top]:slide-in-from-bottom-2',
-] as const;
-
-const SNAPPY_TOKENS = [
- 'transition-[opacity,scale]',
- 'ease-(--ease-out-strong)',
- 'starting:opacity-0',
- 'starting:scale-95',
- 'data-closed:duration-0',
- 'FORKED FROM radix-nova',
-] as const;
-
-function contentClassName(slot: string): string {
- const m = SRC.match(new RegExp(`data-slot="${slot}"[\\s\\S]*?'([^']*)'`));
- expect(m).not.toBeNull();
- return m?.[1] ?? '';
-}
-
-describe('DropdownMenu module', () => {
- test('exports the full DropdownMenu API surface', async () => {
- const mod = await import('./dropdown-menu');
- for (const name of [
- 'DropdownMenu',
- 'DropdownMenuCheckboxItem',
- 'DropdownMenuContent',
- 'DropdownMenuGroup',
- 'DropdownMenuItem',
- 'DropdownMenuLabel',
- 'DropdownMenuPortal',
- 'DropdownMenuRadioGroup',
- 'DropdownMenuRadioItem',
- 'DropdownMenuSeparator',
- 'DropdownMenuShortcut',
- 'DropdownMenuSub',
- 'DropdownMenuSubContent',
- 'DropdownMenuSubTrigger',
- 'DropdownMenuTrigger',
- ]) {
- expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
- }
- });
-});
-
-describe('DropdownMenu upstream overlay motion', () => {
- for (const slot of ['dropdown-menu-content', 'dropdown-menu-sub-content']) {
- test(`${slot} carries the upstream keyframe motion block`, () => {
- const cls = contentClassName(slot);
- for (const token of UPSTREAM_MOTION_TOKENS) {
- expect(cls).toContain(token);
- }
- });
-
- test(`${slot} carries the reduced-motion a11y opt-in`, () => {
- expect(contentClassName(slot)).toContain(A11Y_OPT_IN);
- });
-
- test(`${slot} pivots the scale from the trigger origin`, () => {
- expect(contentClassName(slot)).toContain(
- 'origin-(--radix-dropdown-menu-content-transform-origin)',
- );
- });
- }
-
- test('DropdownMenuContent keeps the data-[state=closed] layout clip', () => {
- expect(contentClassName('dropdown-menu-content')).toContain(
- 'data-[state=closed]:overflow-hidden',
- );
- });
-
- test('DropdownMenuSubTrigger retains its data-open: open-state highlight', () => {
- expect(SRC).toContain('data-open:bg-accent');
- expect(SRC).toContain('data-open:text-accent-foreground');
- });
-
- test('the snappy transition tier cannot silently return', () => {
- for (const token of SNAPPY_TOKENS) {
- expect(SRC).not.toContain(token);
- }
- });
-
- test('no long-form data-[state] animation/highlight drift', () => {
- expect(SRC).not.toMatch(/data-\[state=(?:open|closed)\]:(?:animate|fade|zoom|slide|bg|text)/);
- });
-});
diff --git a/packages/app/src/components/ui/popover.dom.test.tsx b/packages/app/src/components/ui/popover.dom.test.tsx
new file mode 100644
index 000000000..7903b4d99
--- /dev/null
+++ b/packages/app/src/components/ui/popover.dom.test.tsx
@@ -0,0 +1,81 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { cleanup, render } from '@testing-library/react';
+import { act } from 'react';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+const A11Y_OPT_IN = [
+ 'motion-reduce:data-open:animate-none',
+ 'motion-reduce:data-closed:animate-none',
+ 'motion-reduce:duration-0',
+] as const;
+
+const SNAPPY_TOKENS = [
+ 'transition-[opacity,scale]',
+ 'ease-(--ease-out-strong)',
+ 'starting:opacity-0',
+ 'starting:scale-95',
+ 'data-closed:duration-0',
+ 'FORKED FROM radix-nova',
+] as const;
+
+async function renderPopoverContent() {
+ const { Popover, PopoverContent, PopoverTrigger } = await import('./popover');
+
+ await act(async () => {
+ render(
+ <Popover open={true}>
+ <PopoverTrigger>Open</PopoverTrigger>
+ <PopoverContent forceMount={true}>Popover body</PopoverContent>
+ </Popover>,
+ );
+ await Promise.resolve();
+ });
+}
+
+describe('Popover runtime class contracts', () => {
+ afterEach(() => cleanup());
+
+ test('exports the full Popover API surface', async () => {
+ const mod = await import('./popover');
+ for (const name of ['Popover', 'PopoverAnchor', 'PopoverContent', 'PopoverTrigger']) {
+ expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
+ }
+ });
+
+ test('content carries upstream keyframe motion and reduced-motion opt-in at runtime', async () => {
+ await renderPopoverContent();
+
+ const content = document.querySelector('[data-slot="popover-content"]');
+ expect(content).toBeTruthy();
+ const className = content?.getAttribute('class') ?? '';
+
+ expectVisualClassTokens(className, [
+ 'duration-100',
+ 'data-open:animate-in',
+ 'data-open:fade-in-0',
+ 'data-open:zoom-in-95',
+ 'data-closed:animate-out',
+ 'data-closed:fade-out-0',
+ 'data-closed:zoom-out-95',
+ 'data-[side=bottom]:slide-in-from-top-2',
+ 'data-[side=left]:slide-in-from-right-2',
+ 'data-[side=right]:slide-in-from-left-2',
+ 'data-[side=top]:slide-in-from-bottom-2',
+ 'origin-(--radix-popover-content-transform-origin)',
+ ...A11Y_OPT_IN,
+ ]);
+ });
+
+ test('snappy transition tier and long-form state animation drift do not return', async () => {
+ await renderPopoverContent();
+
+ const className =
+ document.querySelector('[data-slot="popover-content"]')?.getAttribute('class') ?? '';
+
+ expectVisualClassTokensAbsent(className, SNAPPY_TOKENS);
+ expect(className).not.toMatch(/data-\[state=(?:open|closed)\]:(?:animate|fade|zoom|slide)/);
+ });
+});
diff --git a/packages/app/src/components/ui/popover.test.ts b/packages/app/src/components/ui/popover.test.ts
deleted file mode 100644
index bb7c0e2f4..000000000
--- a/packages/app/src/components/ui/popover.test.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './popover?raw';
-
-const A11Y_OPT_IN =
- 'motion-reduce:data-open:animate-none motion-reduce:data-closed:animate-none motion-reduce:duration-0';
-
-const SNAPPY_TOKENS = [
- 'transition-[opacity,scale]',
- 'ease-(--ease-out-strong)',
- 'starting:opacity-0',
- 'starting:scale-95',
- 'data-closed:duration-0',
- 'FORKED FROM radix-nova',
-] as const;
-
-describe('Popover module', () => {
- test('exports the full Popover API surface', async () => {
- const mod = await import('./popover');
- for (const name of ['Popover', 'PopoverAnchor', 'PopoverContent', 'PopoverTrigger']) {
- expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
- }
- });
-});
-
-describe('Popover upstream overlay motion', () => {
- test('PopoverContent carries the upstream keyframe motion block', () => {
- for (const token of [
- 'duration-100',
- 'data-open:animate-in',
- 'data-open:fade-in-0',
- 'data-open:zoom-in-95',
- 'data-closed:animate-out',
- 'data-closed:fade-out-0',
- 'data-closed:zoom-out-95',
- 'data-[side=bottom]:slide-in-from-top-2',
- 'data-[side=left]:slide-in-from-right-2',
- 'data-[side=right]:slide-in-from-left-2',
- 'data-[side=top]:slide-in-from-bottom-2',
- ]) {
- expect(SRC).toContain(token);
- }
- });
-
- test('the reduced-motion opt-in is present as the contiguous a11y contract', () => {
- expect(SRC).toContain(A11Y_OPT_IN);
- });
-
- test('scale pivots from the trigger origin', () => {
- expect(SRC).toContain('origin-(--radix-popover-content-transform-origin)');
- });
-
- test('the snappy transition tier cannot silently return', () => {
- for (const token of SNAPPY_TOKENS) {
- expect(SRC).not.toContain(token);
- }
- });
-
- test('no long-form data-[state] animation drift', () => {
- expect(SRC).not.toMatch(/data-\[state=(?:open|closed)\]:(?:animate|fade|zoom|slide)/);
- });
-});
diff --git a/packages/app/src/components/ui/select.dom.test.tsx b/packages/app/src/components/ui/select.dom.test.tsx
new file mode 100644
index 000000000..19f5637dd
--- /dev/null
+++ b/packages/app/src/components/ui/select.dom.test.tsx
@@ -0,0 +1,119 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { cleanup, render } from '@testing-library/react';
+import { act } from 'react';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+const A11Y_OPT_IN = [
+ 'motion-reduce:data-open:animate-none',
+ 'motion-reduce:data-closed:animate-none',
+ 'motion-reduce:duration-0',
+] as const;
+
+const UPSTREAM_MOTION_TOKENS = [
+ 'duration-100',
+ 'data-open:animate-in',
+ 'data-open:fade-in-0',
+ 'data-open:zoom-in-95',
+ 'data-closed:animate-out',
+ 'data-closed:fade-out-0',
+ 'data-closed:zoom-out-95',
+ 'data-[side=bottom]:slide-in-from-top-2',
+ 'data-[side=left]:slide-in-from-right-2',
+ 'data-[side=right]:slide-in-from-left-2',
+ 'data-[side=top]:slide-in-from-bottom-2',
+ 'data-[align-trigger=true]:animate-none',
+] as const;
+
+const POPPER_COLLISION_OFFSETS = [
+ 'data-[side=bottom]:translate-y-1',
+ 'data-[side=left]:-translate-x-1',
+ 'data-[side=right]:translate-x-1',
+ 'data-[side=top]:-translate-y-1',
+] as const;
+
+const SNAPPY_TOKENS = [
+ 'transition-[opacity,scale]',
+ 'ease-(--ease-out-strong)',
+ 'starting:opacity-0',
+ 'starting:scale-95',
+ 'data-closed:duration-0',
+ 'FORKED FROM radix-nova',
+] as const;
+
+async function renderSelectContent() {
+ const { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } = await import(
+ './select'
+ );
+
+ await act(async () => {
+ render(
+ <Select open={true} value="one">
+ <SelectTrigger>
+ <SelectValue placeholder="Choose" />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="one">One</SelectItem>
+ </SelectContent>
+ </Select>,
+ );
+ await Promise.resolve();
+ });
+}
+
+describe('Select runtime class contracts', () => {
+ afterEach(() => cleanup());
+
+ test('exports the full Select API surface', async () => {
+ const mod = await import('./select');
+ for (const name of [
+ 'Select',
+ 'SelectContent',
+ 'SelectGroup',
+ 'SelectItem',
+ 'SelectLabel',
+ 'SelectScrollDownButton',
+ 'SelectScrollUpButton',
+ 'SelectSeparator',
+ 'SelectTrigger',
+ 'SelectValue',
+ ]) {
+ expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
+ }
+ });
+
+ test('content carries keyframe motion, reduced-motion opt-in, and trigger-origin pivot', async () => {
+ await renderSelectContent();
+
+ const content = document.querySelector('[data-slot="select-content"]');
+ expect(content).toBeTruthy();
+ expect(content?.getAttribute('data-ok-layer-spawned')).toBe('');
+ const className = content?.getAttribute('class') ?? '';
+
+ expectVisualClassTokens(className, [
+ ...UPSTREAM_MOTION_TOKENS,
+ 'origin-(--radix-select-content-transform-origin)',
+ ...A11Y_OPT_IN,
+ ]);
+ });
+
+ test('position=popper preserves the collision-offset runtime classes', async () => {
+ await renderSelectContent();
+
+ const className =
+ document.querySelector('[data-slot="select-content"]')?.getAttribute('class') ?? '';
+ expectVisualClassTokens(className, POPPER_COLLISION_OFFSETS);
+ });
+
+ test('snappy transition tier and long-form state drift do not return', async () => {
+ await renderSelectContent();
+
+ const className =
+ document.querySelector('[data-slot="select-content"]')?.getAttribute('class') ?? '';
+
+ expectVisualClassTokensAbsent(className, SNAPPY_TOKENS);
+ expect(className).not.toMatch(/data-\[state=(?:open|closed)\]:(?:animate|fade|zoom|slide)/);
+ });
+});
diff --git a/packages/app/src/components/ui/select.test.ts b/packages/app/src/components/ui/select.test.ts
deleted file mode 100644
index 1fb991936..000000000
--- a/packages/app/src/components/ui/select.test.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './select?raw';
-
-const A11Y_OPT_IN =
- 'motion-reduce:data-open:animate-none motion-reduce:data-closed:animate-none motion-reduce:duration-0';
-
-const SNAPPY_TOKENS = [
- 'transition-[opacity,scale]',
- 'ease-(--ease-out-strong)',
- 'starting:opacity-0',
- 'starting:scale-95',
- 'data-closed:duration-0',
- 'FORKED FROM radix-nova',
-] as const;
-
-describe('Select module', () => {
- test('exports the full Select API surface', async () => {
- const mod = await import('./select');
- for (const name of [
- 'Select',
- 'SelectContent',
- 'SelectGroup',
- 'SelectItem',
- 'SelectLabel',
- 'SelectScrollDownButton',
- 'SelectScrollUpButton',
- 'SelectSeparator',
- 'SelectTrigger',
- 'SelectValue',
- ]) {
- expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
- }
- });
-});
-
-describe('Select upstream overlay motion', () => {
- test('SelectContent carries the upstream keyframe motion block', () => {
- for (const token of [
- 'duration-100',
- 'data-open:animate-in',
- 'data-open:fade-in-0',
- 'data-open:zoom-in-95',
- 'data-closed:animate-out',
- 'data-closed:fade-out-0',
- 'data-closed:zoom-out-95',
- 'data-[side=bottom]:slide-in-from-top-2',
- 'data-[side=left]:slide-in-from-right-2',
- 'data-[side=right]:slide-in-from-left-2',
- 'data-[side=top]:slide-in-from-bottom-2',
- 'data-[align-trigger=true]:animate-none',
- ]) {
- expect(SRC).toContain(token);
- }
- });
-
- test('the reduced-motion opt-in is present as the contiguous a11y contract', () => {
- expect(SRC).toContain(A11Y_OPT_IN);
- });
-
- test('scale pivots from the preserved trigger-origin radix var', () => {
- expect(SRC).toContain('origin-(--radix-select-content-transform-origin)');
- });
-
- test('the position==="popper" collision-offset cn-arg is preserved unchanged', () => {
- expect(SRC).toContain("position === 'popper' &&");
- expect(SRC).toContain('data-[side=bottom]:translate-y-1');
- expect(SRC).toContain('data-[side=left]:-translate-x-1');
- expect(SRC).toContain('data-[side=right]:translate-x-1');
- expect(SRC).toContain('data-[side=top]:-translate-y-1');
- });
-
- test('the snappy transition tier cannot silently return', () => {
- for (const token of SNAPPY_TOKENS) {
- expect(SRC).not.toContain(token);
- }
- });
-
- test('no long-form data-[state] animation drift', () => {
- expect(SRC).not.toMatch(/data-\[state=(?:open|closed)\]:(?:animate|fade|zoom|slide)/);
- });
-});
diff --git a/packages/app/src/components/ui/sheet.dom.test.tsx b/packages/app/src/components/ui/sheet.dom.test.tsx
new file mode 100644
index 000000000..d23a2b14c
--- /dev/null
+++ b/packages/app/src/components/ui/sheet.dom.test.tsx
@@ -0,0 +1,116 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+}));
+
+const OVERLAY_A11Y_OPT_IN = [
+ 'motion-reduce:data-open:animate-none',
+ 'motion-reduce:data-closed:animate-none',
+ 'motion-reduce:duration-0',
+] as const;
+
+const CONTENT_A11Y_OPT_IN = [
+ 'motion-reduce:transition-none',
+ 'motion-reduce:duration-0',
+ 'motion-reduce:data-open:animate-none',
+ 'motion-reduce:data-closed:animate-none',
+] as const;
+
+const CONTENT_SIDES = ['bottom', 'left', 'right', 'top'] as const;
+
+async function renderSheetContent(side: (typeof CONTENT_SIDES)[number] = 'right') {
+ const { Sheet, SheetContent, SheetDescription, SheetTitle } = await import('./sheet');
+
+ render(
+ <Sheet open={true}>
+ <SheetContent forceMount={true} side={side} showCloseButton={false}>
+ <SheetTitle>Sheet title</SheetTitle>
+ <SheetDescription>Sheet description</SheetDescription>
+ Body
+ </SheetContent>
+ </Sheet>,
+ );
+}
+
+describe('Sheet runtime class contracts', () => {
+ afterEach(() => cleanup());
+
+ test('exports the full Sheet API surface', async () => {
+ const mod = await import('./sheet');
+ for (const name of [
+ 'Sheet',
+ 'SheetClose',
+ 'SheetContent',
+ 'SheetDescription',
+ 'SheetFooter',
+ 'SheetHeader',
+ 'SheetTitle',
+ 'SheetTrigger',
+ ]) {
+ expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
+ }
+ });
+
+ test('overlay carries fade keyframes and reduced-motion opt-in at runtime', async () => {
+ await renderSheetContent();
+
+ const overlay = document.querySelector('[data-slot="sheet-overlay"]');
+ expect(overlay).toBeTruthy();
+ const className = overlay?.getAttribute('class') ?? '';
+
+ expectVisualClassTokens(className, [
+ 'duration-100',
+ 'data-open:animate-in',
+ 'data-open:fade-in-0',
+ 'data-closed:animate-out',
+ 'data-closed:fade-out-0',
+ ...OVERLAY_A11Y_OPT_IN,
+ ]);
+ });
+
+ test.each(CONTENT_SIDES)('content side=%s carries hybrid motion contract', async (side) => {
+ await renderSheetContent(side);
+
+ const content = document.querySelector('[data-slot="sheet-content"]');
+ expect(content).toBeTruthy();
+ expect(content?.getAttribute('data-side')).toBe(side);
+ const className = content?.getAttribute('class') ?? '';
+
+ expectVisualClassTokens(className, [
+ 'transition duration-200 ease-in-out',
+ 'data-open:animate-in',
+ 'data-open:fade-in-0',
+ `data-[side=${side}]:data-open:slide-in-from-${side}-10`,
+ 'data-closed:animate-out',
+ 'data-closed:fade-out-0',
+ `data-[side=${side}]:data-closed:slide-out-to-${side}-10`,
+ ...CONTENT_A11Y_OPT_IN,
+ ]);
+ });
+
+ test('snappy transition tier does not return on runtime surfaces', async () => {
+ await renderSheetContent();
+
+ const surfaces = [
+ ...document.querySelectorAll('[data-slot="sheet-overlay"], [data-slot="sheet-content"]'),
+ ]
+ .map((el) => el.getAttribute('class') ?? '')
+ .join(' ');
+
+ expectVisualClassTokensAbsent(surfaces, [
+ 'transition-[opacity,scale]',
+ 'ease-(--ease-out-strong)',
+ 'starting:opacity-0',
+ 'starting:scale-95',
+ 'data-closed:duration-0',
+ 'FORKED FROM radix-nova',
+ ]);
+ });
+});
diff --git a/packages/app/src/components/ui/sheet.test.ts b/packages/app/src/components/ui/sheet.test.ts
deleted file mode 100644
index e4a57a904..000000000
--- a/packages/app/src/components/ui/sheet.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './sheet?raw';
-
-const OVERLAY_A11Y_OPT_IN =
- 'motion-reduce:data-open:animate-none motion-reduce:data-closed:animate-none motion-reduce:duration-0';
-
-const CONTENT_A11Y_OPT_IN =
- 'motion-reduce:transition-none motion-reduce:duration-0 motion-reduce:data-open:animate-none motion-reduce:data-closed:animate-none';
-
-const CONTENT_SIDES = ['bottom', 'left', 'right', 'top'] as const;
-
-const SNAPPY_TOKENS = [
- 'transition-[opacity,scale]',
- 'ease-(--ease-out-strong)',
- 'starting:opacity-0',
- 'starting:scale-95',
- 'data-closed:duration-0',
- 'FORKED FROM radix-nova',
-] as const;
-
-function classNameLiteral(slot: string): string {
- const match = SRC.match(new RegExp(`data-slot="${slot}"[\\s\\S]*?'([^']*)'`));
- if (!match) {
- throw new Error(`Could not extract className for data-slot="${slot}"`);
- }
- return match[1] ?? '';
-}
-
-describe('Sheet module', () => {
- test('exports the full Sheet API surface', async () => {
- const mod = await import('./sheet');
- for (const name of [
- 'Sheet',
- 'SheetClose',
- 'SheetContent',
- 'SheetDescription',
- 'SheetFooter',
- 'SheetHeader',
- 'SheetTitle',
- 'SheetTrigger',
- ]) {
- expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
- }
- });
-});
-
-describe('SheetOverlay upstream + a11y contract', () => {
- const overlay = classNameLiteral('sheet-overlay');
-
- test('uses upstream duration-100 symmetric fade keyframes', () => {
- expect(overlay).toContain('duration-100');
- expect(overlay).toContain('data-open:animate-in');
- expect(overlay).toContain('data-open:fade-in-0');
- expect(overlay).toContain('data-closed:animate-out');
- expect(overlay).toContain('data-closed:fade-out-0');
- });
-
- test('carries the a11y motion-reduce opt-in', () => {
- expect(overlay).toContain(OVERLAY_A11Y_OPT_IN);
- });
-});
-
-describe('SheetContent upstream + a11y contract', () => {
- const content = classNameLiteral('sheet-content');
-
- test('uses upstream hybrid transition duration-200 ease-in-out', () => {
- expect(content).toContain('transition duration-200 ease-in-out');
- });
-
- test('uses upstream open keyframe + slide-in-from on every side', () => {
- expect(content).toContain('data-open:animate-in');
- expect(content).toContain('data-open:fade-in-0');
- for (const side of CONTENT_SIDES) {
- expect(content).toContain(`data-[side=${side}]:data-open:slide-in-from-${side}-10`);
- }
- });
-
- test('uses upstream close keyframe + slide-out-to on every side', () => {
- expect(content).toContain('data-closed:animate-out');
- expect(content).toContain('data-closed:fade-out-0');
- for (const side of CONTENT_SIDES) {
- expect(content).toContain(`data-[side=${side}]:data-closed:slide-out-to-${side}-10`);
- }
- });
-
- test('carries the hybrid a11y motion-reduce opt-in', () => {
- expect(content).toContain(CONTENT_A11Y_OPT_IN);
- });
-});
-
-describe('Sheet snappy-tier negative-drift guard', () => {
- test.each(SNAPPY_TOKENS)('does not contain snappy token: %s', (token) => {
- expect(SRC).not.toContain(token);
- });
-});
diff --git a/packages/app/src/components/ui/sidebar.dom.test.tsx b/packages/app/src/components/ui/sidebar.dom.test.tsx
new file mode 100644
index 000000000..b1ad38f3f
--- /dev/null
+++ b/packages/app/src/components/ui/sidebar.dom.test.tsx
@@ -0,0 +1,159 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { expectVisualClassTokens } from '@/test-utils/visual-contract';
+
+mock.module('@lingui/react/macro', () => ({
+ Trans: ({ children }: { children: ReactNode }) => <>{children}</>,
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+function setViewportWidth(width: number) {
+ Object.defineProperty(window, 'innerWidth', { configurable: true, value: width });
+}
+
+function resetSidebarCookie(value: string) {
+ // biome-ignore lint/suspicious/noDocumentCookie: DOM helper intentionally seeds the cookie API the sidebar reads.
+ document.cookie = `sidebar_width=${value}; path=/`;
+}
+
+async function renderSidebarShell(width: number) {
+ setViewportWidth(width);
+ const { Sidebar, SidebarGroupLabel, SidebarInset, SidebarProvider, SidebarTrigger } =
+ await import('./sidebar');
+
+ render(
+ <SidebarProvider defaultWidth="20rem">
+ <Sidebar collapsible="offcanvas">
+ <SidebarGroupLabel>Files</SidebarGroupLabel>
+ </Sidebar>
+ <SidebarTrigger />
+ <SidebarInset data-testid="sidebar-inset">Main</SidebarInset>
+ </SidebarProvider>,
+ );
+}
+
+describe('Sidebar runtime contracts', () => {
+ afterEach(() => {
+ cleanup();
+ resetSidebarCookie('; max-age=0');
+ setViewportWidth(1400);
+ });
+
+ test('malformed sidebar_width cookie falls back instead of crashing render', async () => {
+ resetSidebarCookie('%');
+ const { SidebarProvider } = await import('./sidebar');
+
+ expect(() => {
+ render(
+ <SidebarProvider defaultWidth="20rem">
+ <div>Content</div>
+ </SidebarProvider>,
+ );
+ }).not.toThrow();
+
+ const wrapper = document.querySelector('[data-slot="sidebar-wrapper"]') as HTMLElement | null;
+ expect(wrapper?.style.getPropertyValue('--sidebar-width')).toBe('20rem');
+ });
+
+ test('valid rem/px sidebar_width cookies are applied and invalid values fall back', async () => {
+ const { SidebarProvider } = await import('./sidebar');
+
+ resetSidebarCookie('17.5rem');
+ const { unmount } = render(
+ <SidebarProvider defaultWidth="20rem">
+ <div>Content</div>
+ </SidebarProvider>,
+ );
+ expect(
+ (
+ document.querySelector('[data-slot="sidebar-wrapper"]') as HTMLElement | null
+ )?.style.getPropertyValue('--sidebar-width'),
+ ).toBe('17.5rem');
+ unmount();
+
+ resetSidebarCookie(encodeURIComponent('calc(100vw)'));
+ render(
+ <SidebarProvider defaultWidth="20rem">
+ <div>Content</div>
+ </SidebarProvider>,
+ );
+ expect(
+ (
+ document.querySelector('[data-slot="sidebar-wrapper"]') as HTMLElement | null
+ )?.style.getPropertyValue('--sidebar-width'),
+ ).toBe('20rem');
+ });
+
+ test('desktop sidebar trigger controls a labeled sidebar landmark', async () => {
+ await renderSidebarShell(1400);
+
+ const trigger = screen.getByRole('button', { name: /Hide Files/ });
+ expect(trigger.getAttribute('aria-controls')).toBe('app-file-sidebar');
+ expect(trigger.getAttribute('aria-expanded')).toBe('true');
+
+ const nav = document.querySelector('[data-slot="sidebar-container"]');
+ expect(nav?.getAttribute('id')).toBe('app-file-sidebar');
+ expect(nav?.getAttribute('aria-label')).toBe('File sidebar');
+ });
+
+ test('mobile sidebar branch keeps the same labeled sidebar landmark', async () => {
+ await renderSidebarShell(500);
+
+ const trigger = screen.getByRole('button', { name: /Show Files/ });
+ expect(trigger.getAttribute('aria-controls')).toBe('app-file-sidebar');
+ expect(trigger.getAttribute('aria-expanded')).toBe('false');
+
+ const nav = document.querySelector('[data-slot="sidebar-container"]');
+ expect(nav?.getAttribute('id')).toBe('app-file-sidebar');
+ expect(nav?.getAttribute('aria-label')).toBe('File sidebar');
+ });
+
+ test('sidebar motion classes preserve duration and reduced-motion gates at runtime', async () => {
+ await renderSidebarShell(500);
+
+ const mobileContainer = document.querySelector('[data-slot="sidebar-container"]');
+ expectVisualClassTokens(mobileContainer?.getAttribute('class'), [
+ 'transition-[left,right,width]',
+ 'duration-200',
+ 'ease-linear',
+ 'motion-reduce:transition-none',
+ ]);
+
+ cleanup();
+ await renderSidebarShell(1400);
+
+ const gap = document.querySelector('[data-slot="sidebar-gap"]');
+ expectVisualClassTokens(gap?.getAttribute('class'), [
+ 'transition-[width]',
+ 'duration-200',
+ 'ease-linear',
+ ]);
+
+ const desktopContainer = document.querySelector('[data-slot="sidebar-container"]');
+ expectVisualClassTokens(desktopContainer?.getAttribute('class'), [
+ 'transition-[left,right,width]',
+ 'duration-200',
+ 'ease-linear',
+ ]);
+
+ const inset = screen.getByTestId('sidebar-inset');
+ expectVisualClassTokens(inset.getAttribute('class'), [
+ 'relative',
+ 'flex',
+ 'w-full',
+ 'flex-1',
+ 'flex-col',
+ ]);
+
+ const label = screen.getByText('Files');
+ expectVisualClassTokens(label.getAttribute('class'), [
+ 'transition-[margin,opacity]',
+ 'duration-200',
+ 'ease-linear',
+ ]);
+ });
+});
diff --git a/packages/app/src/components/ui/sidebar.test.ts b/packages/app/src/components/ui/sidebar.test.ts
deleted file mode 100644
index 9fa579dc3..000000000
--- a/packages/app/src/components/ui/sidebar.test.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './sidebar?raw';
-
-describe('getInitialSidebarWidth source-level guards', () => {
- test('decodeURIComponent is wrapped in a try/catch that returns defaultWidth', () => {
- const start = SRC.indexOf('function getInitialSidebarWidth');
- expect(start).toBeGreaterThan(-1);
- const after = SRC.slice(start);
- const end = after.indexOf('\nfunction ', 1);
- const body = end === -1 ? after : after.slice(0, end);
-
- expect(body).toContain('decodeURIComponent(savedWidth)');
- expect(body).toMatch(/try\s*{[\s\S]*decodeURIComponent[\s\S]*}\s*catch/);
- expect(body).toMatch(/catch\s*(?:\([^)]*\))?\s*{[\s\S]*return defaultWidth/);
- });
-
- test('decoded value is range-checked against SIDEBAR_WIDTH_VALUE_PATTERN', () => {
- expect(SRC).toContain('const SIDEBAR_WIDTH_VALUE_PATTERN = /^\\d+(?:\\.\\d+)?(?:rem|px)$/');
- expect(SRC).toMatch(/SIDEBAR_WIDTH_VALUE_PATTERN\.test\(decodedWidth\)/);
- });
-});
-
-describe('SIDEBAR_ID anchors aria-controls referent', () => {
- test('id={SIDEBAR_ID} is set on the sidebar-container nav', () => {
- const matches = SRC.match(/id=\{SIDEBAR_ID\}/g);
- expect(matches?.length).toBe(1);
- });
-
- test('nav carrying id={SIDEBAR_ID} also carries aria-label="File sidebar"', () => {
- const ariaLabels = SRC.match(/aria-label=\{t`File sidebar`\}/g);
- expect(ariaLabels?.length).toBe(1);
- });
-});
-
-describe('Sidebar motion duration is appropriate for toggle frequency', () => {
- test('sidebar-gap width collapse uses duration-200 ease-linear', () => {
- expect(SRC).toContain(
- 'data-slot="sidebar-gap"\n className={cn(\n \'relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear',
- );
- });
-
- test('sidebar-container layout uses duration-200 ease-linear with reduced-motion gating', () => {
- expect(SRC).toContain(
- 'transition-[left,right,width] duration-200 ease-linear motion-reduce:transition-none',
- );
- });
-
- test('SidebarGroupLabel collapse uses duration-200 ease-linear', () => {
- expect(SRC).toContain('transition-[margin,opacity] duration-200 ease-linear');
- });
-});
diff --git a/packages/app/src/components/ui/tag-pill-input.dom.test.tsx b/packages/app/src/components/ui/tag-pill-input.dom.test.tsx
index c81ca3682..47a665d32 100644
--- a/packages/app/src/components/ui/tag-pill-input.dom.test.tsx
+++ b/packages/app/src/components/ui/tag-pill-input.dom.test.tsx
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, mock, test } from 'bun:test';
import { cleanup, fireEvent, render } from '@testing-library/react';
+import { createRef } from 'react';
import { TooltipProvider } from '@/components/ui/tooltip';
import { TagPillInput } from './tag-pill-input';
@@ -89,6 +90,39 @@ describe('TagPillInput — input-side grammar gate', () => {
expect(input.getAttribute('aria-invalid')).toBeNull();
});
+ test('comma, Tab, and blur commit non-empty drafts while empty comma is swallowed', () => {
+ const onChange = mock(() => {});
+ const { container } = renderInput({ onChange });
+ const input = container.querySelector('input') as HTMLInputElement;
+
+ fireEvent.keyDown(input, { key: ',' });
+ expect(onChange).toHaveBeenCalledTimes(0);
+ expect(input.value).toBe('');
+
+ fireEvent.change(input, { target: { value: 'comma-tag' } });
+ fireEvent.keyDown(input, { key: ',' });
+ expect(onChange).toHaveBeenCalledWith(['comma-tag']);
+
+ fireEvent.change(input, { target: { value: 'tab-tag' } });
+ fireEvent.keyDown(input, { key: 'Tab' });
+ expect(onChange).toHaveBeenCalledWith(['tab-tag']);
+
+ fireEvent.change(input, { target: { value: 'blur-tag' } });
+ fireEvent.blur(input);
+ expect(onChange).toHaveBeenCalledWith(['blur-tag']);
+ });
+
+ test('Backspace on an empty draft removes the last pill', () => {
+ const onChange = mock(() => {});
+ const { container } = renderInput({ value: ['alpha', 'beta'], onChange });
+ const input = container.querySelector('input') as HTMLInputElement;
+
+ fireEvent.keyDown(input, { key: 'Backspace' });
+
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange.mock.calls[0]?.[0]).toEqual(['alpha']);
+ });
+
test('Enter on a digit-leading tag like a year (2026) commits', () => {
const onChange = mock(() => {});
const { container } = renderInput({ onChange });
@@ -218,4 +252,39 @@ describe('TagPillInput — a11y id wiring (regression: PR #1288 review findings)
const input = container.querySelector('input') as HTMLInputElement;
expect(input.getAttribute('aria-describedby')).toBeNull();
});
+
+ test('remove buttons include the tag value in their accessible names', () => {
+ const onChange = mock(() => {});
+ const { container } = renderInput({ value: ['showcase', 'docs'], onChange });
+
+ fireEvent.click(
+ container.querySelector('button[aria-label="Remove docs"]') as HTMLButtonElement,
+ );
+
+ expect(onChange).toHaveBeenCalledWith(['showcase']);
+ });
+
+ test('forwards id, ref, aria-describedby, and aria-invalid to the focusable input and wrapper state', () => {
+ const inputRef = createRef<HTMLInputElement>();
+ const { container } = render(
+ <TooltipProvider>
+ <TagPillInput
+ value={[]}
+ onChange={() => {}}
+ id="frontmatter-tags"
+ ref={inputRef}
+ aria-describedby="frontmatter-tags-error"
+ aria-invalid="true"
+ />
+ </TooltipProvider>,
+ );
+
+ const input = container.querySelector('input') as HTMLInputElement;
+ const wrapper = container.querySelector('[data-slot="tag-pill-input"]');
+ expect(input.id).toBe('frontmatter-tags');
+ expect(inputRef.current).toBe(input);
+ expect(input.getAttribute('aria-describedby')).toBe('frontmatter-tags-error');
+ expect(input.getAttribute('aria-invalid')).toBe('true');
+ expect(wrapper?.getAttribute('aria-invalid')).toBe('true');
+ });
});
diff --git a/packages/app/src/components/ui/tag-pill-input.test.ts b/packages/app/src/components/ui/tag-pill-input.test.ts
deleted file mode 100644
index 50c41adc3..000000000
--- a/packages/app/src/components/ui/tag-pill-input.test.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './tag-pill-input?raw';
-
-describe('TagPillInput module', () => {
- test('exports TagPillInput component', async () => {
- const mod = await import('./tag-pill-input');
- expect(typeof mod.TagPillInput).toBe('function');
- });
-});
-
-describe('TagPillInput source-level guards', () => {
- test('handles Enter / comma / Tab key commits', () => {
- expect(SRC).toContain("e.key === 'Enter'");
- expect(SRC).toContain("e.key === ','");
- expect(SRC).toContain("e.key === 'Tab'");
- });
-
- test('Tab with non-empty draft commits AND prevents default focus shift', () => {
- const tabIdx = SRC.indexOf("e.key === 'Tab'");
- expect(tabIdx).toBeGreaterThan(-1);
- const after = SRC.slice(tabIdx);
- const nextElseIdx = after.indexOf('} else if');
- const branch = nextElseIdx > -1 ? after.slice(0, nextElseIdx) : after;
- expect(branch).toContain('e.preventDefault()');
- expect(branch).toContain('addTag(draft)');
- });
-
- test('comma always prevents default — even on empty draft (no literal comma in input)', () => {
- const commaIdx = SRC.indexOf("e.key === ','");
- expect(commaIdx).toBeGreaterThan(-1);
- const after = SRC.slice(commaIdx);
- const nextElseIdx = after.indexOf('} else if');
- const branch = nextElseIdx > -1 ? after.slice(0, nextElseIdx) : after;
- const preventIdx = branch.indexOf('e.preventDefault()');
- const trimIdx = branch.indexOf('draft.trim()');
- expect(preventIdx).toBeGreaterThan(-1);
- expect(trimIdx).toBeGreaterThan(-1);
- expect(preventIdx).toBeLessThan(trimIdx);
- });
-
- test('handles Backspace-on-empty pill removal', () => {
- expect(SRC).toContain("e.key === 'Backspace'");
- expect(SRC).toContain("draft === ''");
- expect(SRC).toContain('value.length > 0');
- expect(SRC).toContain('removeAt(value.length - 1)');
- });
-
- test('dedupes duplicate tags', () => {
- expect(SRC).toContain('value.includes(normalized)');
- });
-
- test('renders Badge pills with Remove buttons and aria-label', () => {
- expect(SRC).toContain('Badge');
- expect(SRC).toMatch(/aria-label=\{t`Remove \$\{tag\}`\}/);
- });
-
- test('inner input forwards id + ref + aria-describedby + aria-invalid', () => {
- const inputOpen = SRC.search(/<input\n\s+/);
- expect(inputOpen).toBeGreaterThan(-1);
- const inputClose = SRC.indexOf('/>', inputOpen);
- const inputBody = SRC.slice(inputOpen, inputClose);
- expect(inputBody).toContain('id={id}');
- expect(inputBody).toContain('ref={ref}');
- expect(inputBody).toContain('ariaDescribedBy');
- expect(inputBody).toContain('grammarHintId');
- expect(inputBody).toContain("aria-invalid={draftRejected ? 'true' : ariaInvalid}");
- });
-
- test('wrapper carries data-slot="tag-pill-input" and aria-invalid for visual ring', () => {
- expect(SRC).toContain('data-slot="tag-pill-input"');
- expect(SRC).toMatch(
- /<div[\s\S]*?data-slot="tag-pill-input"[\s\S]*?aria-invalid=\{draftRejected \? 'true' : ariaInvalid\}/,
- );
- });
-
- test('auto-commits on blur with non-empty draft and forwards onBlur', () => {
- const blurIdx = SRC.indexOf('onBlur={() =>');
- expect(blurIdx).toBeGreaterThan(-1);
- const after = SRC.slice(blurIdx);
- const blockEnd = after.indexOf('}}');
- const block = after.slice(0, blockEnd);
- expect(block).toContain('addTag(draft)');
- expect(block).toContain('onBlur?.()');
- });
-
- test('addTag clears the draft on dedup hit (no double commit)', () => {
- const includesIdx = SRC.indexOf('value.includes(normalized)');
- expect(includesIdx).toBeGreaterThan(-1);
- const after = SRC.slice(includesIdx);
- const blockEnd = after.indexOf('}\n');
- const block = after.slice(0, blockEnd);
- expect(block).toContain("setDraft('')");
- });
-});
diff --git a/packages/app/src/components/ui/tooltip.dom.test.tsx b/packages/app/src/components/ui/tooltip.dom.test.tsx
new file mode 100644
index 000000000..724832d7e
--- /dev/null
+++ b/packages/app/src/components/ui/tooltip.dom.test.tsx
@@ -0,0 +1,114 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { act } from 'react';
+import {
+ expectVisualClassTokens,
+ expectVisualClassTokensAbsent,
+} from '@/test-utils/visual-contract';
+
+const UPSTREAM_MOTION_TOKENS = [
+ 'data-[side=bottom]:slide-in-from-top-2',
+ 'data-[side=left]:slide-in-from-right-2',
+ 'data-[side=right]:slide-in-from-left-2',
+ 'data-[side=top]:slide-in-from-bottom-2',
+ 'data-[state=delayed-open]:animate-in',
+ 'data-[state=delayed-open]:fade-in-0',
+ 'data-[state=delayed-open]:zoom-in-95',
+ 'data-open:animate-in',
+ 'data-open:fade-in-0',
+ 'data-open:zoom-in-95',
+ 'data-closed:animate-out',
+ 'data-closed:fade-out-0',
+ 'data-closed:zoom-out-95',
+] as const;
+
+const A11Y_OPT_IN_TOKENS = [
+ 'motion-reduce:data-open:animate-none',
+ 'motion-reduce:data-closed:animate-none',
+ 'motion-reduce:data-[state=delayed-open]:animate-none',
+ 'motion-reduce:duration-0',
+] as const;
+
+const SNAPPY_TOKENS = [
+ 'transition-[opacity,scale]',
+ 'ease-(--ease-out-strong)',
+ 'starting:opacity-0',
+ 'starting:scale-95',
+ 'data-closed:duration-0',
+ 'duration-100',
+ 'FORKED FROM radix-nova',
+] as const;
+
+async function renderOpenTooltip() {
+ const { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } = await import('./tooltip');
+
+ await act(async () => {
+ render(
+ <TooltipProvider>
+ <Tooltip open={true}>
+ <TooltipTrigger asChild>
+ <button type="button">Target</button>
+ </TooltipTrigger>
+ <TooltipContent forceMount={true}>Tooltip body</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>,
+ );
+ await Promise.resolve();
+ });
+}
+
+describe('Tooltip runtime contracts', () => {
+ afterEach(() => cleanup());
+
+ test('exports the full Tooltip API surface', async () => {
+ const mod = await import('./tooltip');
+ for (const name of ['Tooltip', 'TooltipContent', 'TooltipProvider', 'TooltipTrigger']) {
+ expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
+ }
+ });
+
+ test('default provider delay opens the first hover without waiting for a timer', async () => {
+ const { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } = await import('./tooltip');
+ const user = userEvent.setup();
+
+ render(
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button type="button">Target</button>
+ </TooltipTrigger>
+ <TooltipContent>Tooltip body</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>,
+ );
+
+ await user.hover(screen.getByRole('button', { name: 'Target' }));
+ await Promise.resolve();
+
+ expect(screen.getByRole('tooltip').textContent).toBe('Tooltip body');
+ });
+
+ test('content carries delayed-open motion and reduced-motion opt-in at runtime', async () => {
+ await renderOpenTooltip();
+
+ const content = document.querySelector('[data-slot="tooltip-content"]');
+ expect(content).toBeTruthy();
+ const className = content?.getAttribute('class') ?? '';
+
+ expectVisualClassTokens(className, [
+ ...UPSTREAM_MOTION_TOKENS,
+ 'origin-(--radix-tooltip-content-transform-origin)',
+ ...A11Y_OPT_IN_TOKENS,
+ ]);
+ });
+
+ test('snappy transition tier does not return', async () => {
+ await renderOpenTooltip();
+
+ const className =
+ document.querySelector('[data-slot="tooltip-content"]')?.getAttribute('class') ?? '';
+
+ expectVisualClassTokensAbsent(className, SNAPPY_TOKENS);
+ });
+});
diff --git a/packages/app/src/components/ui/tooltip.test.ts b/packages/app/src/components/ui/tooltip.test.ts
deleted file mode 100644
index 787a064ef..000000000
--- a/packages/app/src/components/ui/tooltip.test.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './tooltip?raw';
-
-const UPSTREAM_MOTION_TOKENS = [
- 'data-[side=bottom]:slide-in-from-top-2',
- 'data-[side=left]:slide-in-from-right-2',
- 'data-[side=right]:slide-in-from-left-2',
- 'data-[side=top]:slide-in-from-bottom-2',
- 'data-[state=delayed-open]:animate-in',
- 'data-[state=delayed-open]:fade-in-0',
- 'data-[state=delayed-open]:zoom-in-95',
- 'data-open:animate-in',
- 'data-open:fade-in-0',
- 'data-open:zoom-in-95',
- 'data-closed:animate-out',
- 'data-closed:fade-out-0',
- 'data-closed:zoom-out-95',
-] as const;
-
-const A11Y_OPT_IN_TOKENS = [
- 'motion-reduce:data-open:animate-none',
- 'motion-reduce:data-closed:animate-none',
- 'motion-reduce:data-[state=delayed-open]:animate-none',
- 'motion-reduce:duration-0',
-] as const;
-
-const SNAPPY_TOKENS = [
- 'transition-[opacity,scale]',
- 'ease-(--ease-out-strong)',
- 'starting:opacity-0',
- 'starting:scale-95',
- 'data-closed:duration-0',
- 'duration-100',
- 'FORKED FROM radix-nova',
-] as const;
-
-describe('Tooltip module', () => {
- test('exports the full Tooltip API surface', async () => {
- const mod = await import('./tooltip');
- for (const name of ['Tooltip', 'TooltipContent', 'TooltipProvider', 'TooltipTrigger']) {
- expect(typeof (mod as Record<string, unknown>)[name]).toBe('function');
- }
- });
-});
-
-describe('TooltipProvider delayDuration default', () => {
- test('defaults delayDuration to 0 so first hovers open without delay', () => {
- expect(SRC).toMatch(/function\s+TooltipProvider\s*\(\s*\{\s*[\s\S]*?delayDuration\s*=\s*0\b/);
- expect(SRC).toContain('delayDuration={delayDuration}');
- });
-});
-
-describe('Tooltip overlay motion', () => {
- test('TooltipContent carries every upstream keyframe utility', () => {
- for (const token of UPSTREAM_MOTION_TOKENS) {
- expect(SRC).toContain(token);
- }
- });
-
- test('TooltipContent carries the reduced-motion a11y opt-in', () => {
- for (const token of A11Y_OPT_IN_TOKENS) {
- expect(SRC).toContain(token);
- }
- });
-
- test('the zoom entrance pivots from the trigger origin', () => {
- expect(SRC).toContain('origin-(--radix-tooltip-content-transform-origin)');
- });
-
- test('no snappy transition tier drift', () => {
- for (const token of SNAPPY_TOKENS) {
- expect(SRC).not.toContain(token);
- }
- });
-});
diff --git a/packages/app/src/editor/components/Image.dom.test.tsx b/packages/app/src/editor/components/Image.dom.test.tsx
index 309d91e8d..25035c0c8 100644
--- a/packages/app/src/editor/components/Image.dom.test.tsx
+++ b/packages/app/src/editor/components/Image.dom.test.tsx
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { expectVisualClassTokens } from '@/test-utils/visual-contract';
mock.module('react-medium-image-zoom', () => ({
default: ({ children }: { children: React.ReactNode }) => children,
@@ -53,7 +54,7 @@ describe('Image — loading-state placeholder (PRD-6638)', () => {
const slot = screen.queryByTestId('image-slot') as HTMLElement | null;
expect(slot).not.toBeNull();
expect(slot?.style.width).toBeFalsy();
- expect(slot?.className).toContain('aspect-[16/9]');
+ expectVisualClassTokens(slot?.className, ['aspect-[16/9]']);
});
test('removes the placeholder after the inner <img>.load event fires', () => {
diff --git a/packages/app/src/globals.reduced-transparency.test.ts b/packages/app/src/globals.reduced-transparency.test.ts
index 8fc89e50a..abea73a70 100644
--- a/packages/app/src/globals.reduced-transparency.test.ts
+++ b/packages/app/src/globals.reduced-transparency.test.ts
@@ -33,6 +33,18 @@ describe('globals.css — prefers-reduced-transparency revert', () => {
/@media\s*\(\s*prefers-reduced-transparency:\s*reduce\s*\)[\s\S]*?html\.electron-mode\s+\[data-slot="sidebar-inner"\]\s*\{[\s\S]*?background-color:\s*var\(--sidebar\)/,
);
});
+
+ test('strips backdrop-filter from dialog and sheet overlays', () => {
+ const block = CSS.match(
+ /@media \(prefers-reduced-transparency: reduce\) \{[^}]*\[data-slot="dialog-overlay"\][\s\S]*?\}\s*\}/,
+ );
+ expect(block).not.toBeNull();
+ const blockText = block?.[0] ?? '';
+ expect(blockText).toContain('[data-slot="dialog-overlay"]');
+ expect(blockText).toContain('[data-slot="sheet-overlay"]');
+ expect(blockText).toContain('backdrop-filter: none');
+ expect(blockText).toContain('-webkit-backdrop-filter: none');
+ });
});
describe('globals.css — STOP rule preserved (inner surfaces stay opaque)', () => {
diff --git a/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsx b/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsx
new file mode 100644
index 000000000..2011da344
--- /dev/null
+++ b/packages/app/src/hooks/use-enable-sync-with-confirm.dom.test.tsx
@@ -0,0 +1,171 @@
+import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test';
+import { act, cleanup, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+
+mock.module('@lingui/react/macro', () => ({
+ useLingui: () => ({
+ t: (strings: TemplateStringsArray, ...values: unknown[]) =>
+ strings.reduce((acc, part, index) => `${acc}${part}${values[index] ?? ''}`, ''),
+ }),
+}));
+
+const toastErrors: string[] = [];
+mock.module('sonner', () => ({
+ toast: {
+ error: (message: string) => toastErrors.push(message),
+ },
+}));
+
+let projectLocalBinding: null | {
+ patch: (patch: unknown) => { ok: true } | { ok: false; error: unknown };
+} = null;
+
+mock.module('@/lib/config-provider', () => ({
+ useConfigContext: () => ({ projectLocalBinding }),
+}));
+
+type Writer = ((enabled: boolean) => { ok: true } | { ok: false; error: string }) | null;
+type ConfirmState = {
+ confirmOpen: boolean;
+ setConfirmOpen: (open: boolean) => void;
+ onToggleRequest: (next: boolean) => void;
+ onConfirm: () => void;
+};
+let hooks: Awaited<typeof import('./use-enable-sync-with-confirm')> | null = null;
+let latestConfirmState: ConfirmState | null = null;
+let latestWriter: Writer | undefined;
+
+async function loadHooks() {
+ hooks ??= await import('./use-enable-sync-with-confirm');
+ return hooks;
+}
+
+function ConfirmProbe({ writer }: { writer: Writer }) {
+ if (!hooks) throw new Error('hooks not loaded');
+ latestConfirmState = hooks.useEnableSyncWithConfirm(writer);
+ return <div data-testid="confirm-open">{String(latestConfirmState.confirmOpen)}</div>;
+}
+
+function WriterProbe({ children: _children }: { children?: ReactNode }) {
+ if (!hooks) throw new Error('hooks not loaded');
+ latestWriter = hooks.useSyncEnabledWriter();
+ return <div data-testid="writer-present">{String(latestWriter !== null)}</div>;
+}
+
+describe('useEnableSyncWithConfirm runtime behavior', () => {
+ let consoleErrorSpy: ReturnType<typeof spyOn>;
+
+ afterEach(() => {
+ cleanup();
+ latestConfirmState = null;
+ latestWriter = undefined;
+ projectLocalBinding = null;
+ toastErrors.length = 0;
+ consoleErrorSpy?.mockRestore();
+ });
+
+ test('exports the hook and project-local writer adapter', async () => {
+ const mod = await loadHooks();
+ expect(typeof mod.useEnableSyncWithConfirm).toBe('function');
+ expect(typeof mod.useSyncEnabledWriter).toBe('function');
+ });
+
+ test('off to on opens confirmation and writes true only after confirm', async () => {
+ await loadHooks();
+ const writes: boolean[] = [];
+ const writer: Writer = (enabled) => {
+ writes.push(enabled);
+ return { ok: true };
+ };
+ render(<ConfirmProbe writer={writer} />);
+
+ await act(async () => {
+ latestConfirmState?.onToggleRequest(true);
+ });
+ expect(screen.getByTestId('confirm-open').textContent).toBe('true');
+ expect(writes).toEqual([]);
+
+ await act(async () => {
+ latestConfirmState?.onConfirm();
+ });
+ expect(writes).toEqual([true]);
+ expect(screen.getByTestId('confirm-open').textContent).toBe('false');
+ });
+
+ test('on to off commits immediately without opening confirmation', async () => {
+ await loadHooks();
+ const writes: boolean[] = [];
+ const writer: Writer = (enabled) => {
+ writes.push(enabled);
+ return { ok: true };
+ };
+ render(<ConfirmProbe writer={writer} />);
+
+ await act(async () => {
+ latestConfirmState?.onToggleRequest(false);
+ });
+
+ expect(writes).toEqual([false]);
+ expect(screen.getByTestId('confirm-open').textContent).toBe('false');
+ });
+
+ test('confirm keeps the dialog open when enabling fails', async () => {
+ await loadHooks();
+ consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
+ const writer: Writer = () => ({ ok: false, error: 'branch is protected' });
+ render(<ConfirmProbe writer={writer} />);
+
+ await act(async () => {
+ latestConfirmState?.onToggleRequest(true);
+ latestConfirmState?.onConfirm();
+ });
+
+ expect(screen.getByTestId('confirm-open').textContent).toBe('true');
+ expect(toastErrors).toEqual(['Failed to enable sync — branch is protected']);
+ });
+});
+
+describe('useSyncEnabledWriter runtime behavior', () => {
+ afterEach(() => {
+ cleanup();
+ latestWriter = undefined;
+ projectLocalBinding = null;
+ });
+
+ test('returns null until the project-local binding mounts', async () => {
+ await loadHooks();
+ projectLocalBinding = null;
+ render(<WriterProbe />);
+
+ expect(screen.getByTestId('writer-present').textContent).toBe('false');
+ expect(latestWriter).toBeNull();
+ });
+
+ test('patches autoSync.enabled on the project-local binding', async () => {
+ await loadHooks();
+ const patches: unknown[] = [];
+ projectLocalBinding = {
+ patch: (patch: unknown) => {
+ patches.push(patch);
+ return { ok: true };
+ },
+ };
+ render(<WriterProbe />);
+
+ expect(latestWriter?.(true)).toEqual({ ok: true });
+ expect(patches).toEqual([{ autoSync: { enabled: true } }]);
+ });
+
+ test('wraps binding errors into a string result for toast rendering', async () => {
+ await loadHooks();
+ projectLocalBinding = {
+ patch: () => ({ ok: false, error: { code: 'WRITE_ERROR', detail: 'disk denied' } }),
+ };
+ render(<WriterProbe />);
+
+ expect(latestWriter?.(false)).toEqual({
+ ok: false,
+ error: 'Failed to write config file: disk denied',
+ });
+ });
+});
diff --git a/packages/app/src/hooks/use-enable-sync-with-confirm.test.ts b/packages/app/src/hooks/use-enable-sync-with-confirm.test.ts
deleted file mode 100644
index 21e990c17..000000000
--- a/packages/app/src/hooks/use-enable-sync-with-confirm.test.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { describe, expect, test } from 'bun:test';
-import SRC from './use-enable-sync-with-confirm?raw';
-
-describe('useEnableSyncWithConfirm module', () => {
- test('exports the hook + the project-local writer adapter', async () => {
- const mod = await import('./use-enable-sync-with-confirm');
- expect(typeof mod.useEnableSyncWithConfirm).toBe('function');
- expect(typeof mod.useSyncEnabledWriter).toBe('function');
- });
-});
-
-describe('useEnableSyncWithConfirm source-level guards', () => {
- test('off → on opens the confirmation dialog (does NOT call applyEnabled directly)', () => {
- const start = SRC.indexOf('function onToggleRequest');
- expect(start).toBeGreaterThan(-1);
- const tail = SRC.slice(start);
- const end = tail.indexOf('\n }\n');
- const body = tail.slice(0, end);
-
- expect(body).toMatch(/if\s*\(\s*next\s*\)\s*\{[\s\S]*?setConfirmOpen\(true\)/);
- expect(body).not.toMatch(/if\s*\(\s*next\s*\)[\s\S]*?applyEnabled\(true\)/);
- });
-
- test('on → off commits immediately via applyEnabled(false)', () => {
- expect(SRC).toMatch(/applyEnabled\(\s*false\s*\)/);
- });
-
- test('only the confirm callback applies the enable-direction write', () => {
- const onConfirmStart = SRC.indexOf('function onConfirm');
- expect(onConfirmStart).toBeGreaterThan(-1);
- const onConfirmBody = SRC.slice(onConfirmStart);
- expect(onConfirmBody).toMatch(/applyEnabled\(\s*true\s*\)/);
-
- const matches = SRC.match(/applyEnabled\(\s*true\s*\)/g);
- expect(matches).toHaveLength(1);
- });
-
- test('onConfirm applies the write BEFORE closing the dialog', () => {
- const onConfirmStart = SRC.indexOf('function onConfirm');
- expect(onConfirmStart).toBeGreaterThan(-1);
- const onConfirmBody = SRC.slice(onConfirmStart);
- const writeIdx = onConfirmBody.search(/applyEnabled\(\s*true\s*\)/);
- const closeIdx = onConfirmBody.search(/setConfirmOpen\(\s*false\s*\)/);
- expect(writeIdx).toBeGreaterThan(-1);
- expect(closeIdx).toBeGreaterThan(-1);
- expect(writeIdx).toBeLessThan(closeIdx);
- });
-
- test('onConfirm closes the dialog only on success', () => {
- const onConfirmStart = SRC.indexOf('function onConfirm');
- const onConfirmBody = SRC.slice(onConfirmStart);
- expect(onConfirmBody).toMatch(/const\s+\w+\s*=\s*applyEnabled\(\s*true\s*\)/);
- expect(onConfirmBody).toMatch(/if\s*\(\s*\w+\s*\)\s*setConfirmOpen\(\s*false\s*\)/);
- expect(SRC).toMatch(/applyEnabled\([^)]*\):\s*boolean/);
- });
-
- test('writes route through the project-local ConfigBinding, not the deleted HTTP path', () => {
- expect(SRC).not.toContain('postSyncEnabled');
- expect(SRC).not.toContain('/api/sync/set-enabled');
- expect(SRC).not.toContain("'@/lib/sync-api'");
- });
-});
-
-describe('useSyncEnabledWriter — binding adapter', () => {
- test('reads projectLocalBinding from useConfigContext', () => {
- expect(SRC).toContain('useConfigContext');
- expect(SRC).toMatch(/projectLocalBinding/);
- });
-
- test('returns null when the binding has not yet mounted (cold-start window)', () => {
- expect(SRC).toMatch(/if\s*\(\s*projectLocalBinding\s*===\s*null\s*\)\s*return null/);
- });
-
- test('patches { autoSync: { enabled } } on the project-local binding', () => {
- expect(SRC).toMatch(
- /projectLocalBinding\.patch\(\s*\{\s*autoSync:\s*\{\s*enabled\s*\}\s*\}\s*\)/,
- );
- });
-
- test('wraps Result.err via humanFormat so the toast renders a readable string', () => {
- expect(SRC).toContain('humanFormat');
- expect(SRC).toMatch(/error:\s*humanFormat\(result\.error\)/);
- });
-});
diff --git a/packages/app/src/hooks/use-theme-bridge.dom.test.tsx b/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
index 64c5dbd9e..55f072fd2 100644
--- a/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
+++ b/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test';
-import { cleanup, render, waitFor } from '@testing-library/react';
+import { act, cleanup, render, waitFor } from '@testing-library/react';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { useThemeBridge } from './use-theme-bridge';
@@ -44,11 +44,71 @@ function makeRejectingBridge(rejectionError: Error): StubBridge {
};
}
-function HookProbe({ bridge, themeValue }: { bridge: OkDesktopBridge; themeValue: string }) {
+function HookProbe({
+ bridge,
+ themeValue,
+}: {
+ bridge: OkDesktopBridge | undefined;
+ themeValue: string | undefined;
+}) {
useThemeBridge(bridge, themeValue);
return <div data-testid="theme-bridge-probe" />;
}
+function installControllableMatchMedia(initialMatches: boolean) {
+ const originalWindowMatchMedia = window.matchMedia;
+ const originalGlobalMatchMedia = globalThis.matchMedia;
+ const listeners = new Set<(event: MediaQueryListEvent) => void>();
+ const queries: string[] = [];
+ let matches = initialMatches;
+ const mql = {
+ get matches() {
+ return matches;
+ },
+ media: '',
+ onchange: null,
+ addEventListener: (type: string, listener: EventListenerOrEventListenerObject) => {
+ if (type !== 'change') return;
+ listeners.add(listener as (event: MediaQueryListEvent) => void);
+ },
+ removeEventListener: (type: string, listener: EventListenerOrEventListenerObject) => {
+ if (type !== 'change') return;
+ listeners.delete(listener as (event: MediaQueryListEvent) => void);
+ },
+ addListener: (listener: (event: MediaQueryListEvent) => void) => {
+ listeners.add(listener);
+ },
+ removeListener: (listener: (event: MediaQueryListEvent) => void) => {
+ listeners.delete(listener);
+ },
+ dispatchEvent: () => false,
+ } as unknown as MediaQueryList;
+ const matchMedia = (query: string) => {
+ queries.push(query);
+ (mql as { media: string }).media = query;
+ return mql;
+ };
+
+ window.matchMedia = matchMedia;
+ globalThis.matchMedia = matchMedia;
+
+ return {
+ queries,
+ get listenerCount() {
+ return listeners.size;
+ },
+ dispatchChange(nextMatches: boolean) {
+ matches = nextMatches;
+ const event = { matches: nextMatches, media: mql.media } as MediaQueryListEvent;
+ for (const listener of listeners) listener(event);
+ },
+ restore() {
+ window.matchMedia = originalWindowMatchMedia;
+ globalThis.matchMedia = originalGlobalMatchMedia;
+ },
+ };
+}
+
describe('useThemeBridge (Tier-3 mount)', () => {
let consoleErrorSpy: ReturnType<typeof spyOn>;
let consoleWarnSpy: ReturnType<typeof spyOn>;
@@ -64,6 +124,33 @@ describe('useThemeBridge (Tier-3 mount)', () => {
consoleWarnSpy.mockRestore();
});
+ test('exports the hook', async () => {
+ const mod = await import('./use-theme-bridge');
+ expect(typeof mod.useThemeBridge).toBe('function');
+ });
+
+ test('no-ops without a bridge or a valid theme value', async () => {
+ const stubBridge = makeStubBridge();
+ let view!: ReturnType<typeof render>;
+ await act(async () => {
+ view = render(<HookProbe bridge={undefined} themeValue="system" />);
+ await Promise.resolve();
+ });
+
+ expect(stubBridge.setThemeSourceCalls).toHaveLength(0);
+ expect(stubBridge.signalThemeAppliedCalls).toHaveLength(0);
+
+ await act(async () => {
+ view.rerender(
+ <HookProbe bridge={stubBridge as unknown as OkDesktopBridge} themeValue="solarized" />,
+ );
+ await Promise.resolve();
+ });
+
+ expect(stubBridge.setThemeSourceCalls).toHaveLength(0);
+ expect(stubBridge.signalThemeAppliedCalls).toHaveLength(0);
+ });
+
test('forwards themeValue verbatim to setThemeSource on mount', async () => {
const stubBridge = makeStubBridge();
render(<HookProbe bridge={stubBridge as unknown as OkDesktopBridge} themeValue="system" />);
@@ -99,7 +186,10 @@ describe('useThemeBridge (Tier-3 mount)', () => {
);
unmount();
- await new Promise((resolve) => setTimeout(resolve, 100));
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
expect(stubBridge.signalThemeAppliedCalls.length).toBe(0);
@@ -126,7 +216,9 @@ describe('useThemeBridge (Tier-3 mount)', () => {
rerender(<HookProbe bridge={stubBridge as unknown as OkDesktopBridge} themeValue="system" />);
- await new Promise((resolve) => setTimeout(resolve, 100));
+ await act(async () => {
+ await Promise.resolve();
+ });
expect(stubBridge.setThemeSourceCalls.length).toBe(1);
expect(stubBridge.setThemeSourceCalls[0]).toBe('system');
@@ -187,4 +279,35 @@ describe('useThemeBridge (Tier-3 mount)', () => {
});
expect(sawStructuredWarn).toBe(true);
});
+
+ test('reduced-transparency changes signal main and the listener is removed on unmount', async () => {
+ const media = installControllableMatchMedia(false);
+ try {
+ const stubBridge = makeStubBridge();
+ const { unmount } = render(
+ <HookProbe bridge={stubBridge as unknown as OkDesktopBridge} themeValue="system" />,
+ );
+
+ await waitFor(
+ () => {
+ expect(stubBridge.signalThemeAppliedCalls.length).toBe(1);
+ },
+ { timeout: ASYNC_EFFECT_TIMEOUT_MS },
+ );
+ expect(media.queries).toContain('(prefers-reduced-transparency: reduce)');
+ expect(media.listenerCount).toBe(1);
+
+ media.dispatchChange(true);
+ expect(stubBridge.signalThemeAppliedCalls.at(-1)).toEqual({
+ reducedTransparency: true,
+ });
+
+ unmount();
+ expect(media.listenerCount).toBe(0);
+ media.dispatchChange(false);
+ expect(stubBridge.signalThemeAppliedCalls).toHaveLength(2);
+ } finally {
+ media.restore();
+ }
+ });
});
diff --git a/packages/app/src/hooks/use-theme-bridge.test.ts b/packages/app/src/hooks/use-theme-bridge.test.ts
index f2b142270..9ee3832ea 100644
--- a/packages/app/src/hooks/use-theme-bridge.test.ts
+++ b/packages/app/src/hooks/use-theme-bridge.test.ts
@@ -1,9 +1,4 @@
import { describe, expect, test } from 'bun:test';
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
-
-const SRC_PATH = join(__dirname, 'use-theme-bridge.ts');
-const src = readFileSync(SRC_PATH, 'utf-8');
describe('useThemeBridge — module surface', () => {
test('exports the useThemeBridge hook', async () => {
@@ -11,57 +6,3 @@ describe('useThemeBridge — module surface', () => {
expect(typeof mod.useThemeBridge).toBe('function');
});
});
-
-describe('useThemeBridge — setThemeSource wiring (1-way contract)', () => {
- test('pushes the unresolved themeValue through setThemeSource', () => {
- expect(src).toMatch(/setThemeSource\s*\(\s*themeValue\s*\)/);
- });
-
- test('guards on themeValue before invoking setThemeSource', () => {
- expect(src).toMatch(
- /themeValue\s*!==\s*['"]light['"]\s*&&\s*themeValue\s*!==\s*['"]dark['"]\s*&&\s*themeValue\s*!==\s*['"]system['"]/,
- );
- });
-
- test('reads the bridge through the parameter so web / CLI no-ops gracefully', () => {
- expect(src).toMatch(/if \(!bridge\) return/);
- });
-});
-
-describe('useThemeBridge — show-gate release contract', () => {
- test('signalThemeApplied fires in .finally() so IPC failure still releases the show-gate', () => {
- expect(src).toMatch(/signalThemeApplied/);
- expect(src).toMatch(/setThemeSource[\s\S]*?\.finally\([\s\S]*?signalThemeApplied/);
- });
-
- test('IPC failure handler emits a structured warn and does not throw', () => {
- expect(src).toMatch(/\.catch\(/);
- expect(src).toMatch(/['"]theme-source-set-failed['"]/);
- expect(src).toMatch(/console\.warn\(\s*JSON\.stringify\(/);
- });
-
- test('cancellation flag prevents stale signalThemeApplied across re-runs / unmount', () => {
- expect(src).toMatch(/let cancelled = false/);
- expect(src).toMatch(/if \(cancelled\) return/);
- expect(src).toMatch(/cancelled = true/);
- });
-});
-
-describe('useThemeBridge — prefers-reduced-transparency wiring', () => {
- test('reads matchMedia prefers-reduced-transparency at signal time', () => {
- expect(src).toMatch(/matchMedia\(\s*['"]\(prefers-reduced-transparency: reduce\)['"]/);
- });
-
- test('passes the reducedTransparency boolean through signalThemeApplied opts', () => {
- expect(src).toMatch(/signalThemeApplied\(\s*\{\s*reducedTransparency\b/);
- });
-
- test('subscribes to prefers-reduced-transparency change events for mid-session toggles', () => {
- expect(src).toMatch(/addEventListener\(\s*['"]change['"]/);
- expect(src).toMatch(/removeEventListener\(\s*['"]change['"]/);
- });
-
- test('the change listener cleans up on unmount (no leaks across re-mounts)', () => {
- expect(src).toMatch(/return\s*\(\)\s*=>\s*\{[\s\S]*?removeEventListener/);
- });
-});
diff --git a/packages/app/src/hooks/use-update-channel.dom.test.tsx b/packages/app/src/hooks/use-update-channel.dom.test.tsx
new file mode 100644
index 000000000..14238ae27
--- /dev/null
+++ b/packages/app/src/hooks/use-update-channel.dom.test.tsx
@@ -0,0 +1,100 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
+import { useUpdateChannel } from './use-update-channel';
+
+function setBridge(bridge: unknown) {
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ writable: true,
+ value: bridge,
+ });
+}
+
+function makeBridge({
+ channel = 'beta',
+ queryDelayMs = 0,
+}: {
+ channel?: 'beta' | 'latest';
+ queryDelayMs?: number;
+} = {}) {
+ const queryCalls: string[] = [];
+ const onChannelChangedCalls: string[] = [];
+ const bridge = {
+ state: {
+ query: () => {
+ queryCalls.push('query');
+ return new Promise((resolve) => {
+ setTimeout(
+ () =>
+ resolve({
+ channel,
+ schemaIncompatibility: null,
+ }),
+ queryDelayMs,
+ );
+ });
+ },
+ resetIncompatible: () => Promise.resolve(),
+ onChannelChanged: () => {
+ onChannelChangedCalls.push('subscribe');
+ return () => {};
+ },
+ },
+ } as unknown as OkDesktopBridge & {
+ state: OkDesktopBridge['state'] & { onChannelChanged: () => () => void };
+ };
+
+ return { bridge, queryCalls, onChannelChangedCalls };
+}
+
+function ChannelProbe() {
+ const { channel } = useUpdateChannel();
+ return <output data-testid="update-channel">{channel ?? 'null'}</output>;
+}
+
+describe('useUpdateChannel runtime behavior', () => {
+ afterEach(() => {
+ cleanup();
+ setBridge(undefined);
+ });
+
+ test('exports the hook', () => {
+ expect(typeof useUpdateChannel).toBe('function');
+ });
+
+ test('returns null and does not query when the desktop bridge is absent', async () => {
+ setBridge(undefined);
+
+ render(<ChannelProbe />);
+
+ expect(screen.getByTestId('update-channel').textContent).toBe('null');
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(screen.getByTestId('update-channel').textContent).toBe('null');
+ });
+
+ test('queries the desktop bridge once and updates the channel when it resolves', async () => {
+ const { bridge, queryCalls } = makeBridge({ channel: 'beta' });
+ setBridge(bridge);
+
+ render(<ChannelProbe />);
+
+ expect(screen.getByTestId('update-channel').textContent).toBe('null');
+ await waitFor(() => {
+ expect(screen.getByTestId('update-channel').textContent).toBe('beta');
+ });
+ expect(queryCalls).toEqual(['query']);
+ });
+
+ test('does not subscribe to runtime channel changes', async () => {
+ const { bridge, onChannelChangedCalls } = makeBridge({ channel: 'latest' });
+ setBridge(bridge);
+
+ render(<ChannelProbe />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('update-channel').textContent).toBe('latest');
+ });
+ expect(onChannelChangedCalls).toEqual([]);
+ });
+});
diff --git a/packages/app/src/hooks/use-update-channel.test.ts b/packages/app/src/hooks/use-update-channel.test.ts
index 5fd11c373..d465c074b 100644
--- a/packages/app/src/hooks/use-update-channel.test.ts
+++ b/packages/app/src/hooks/use-update-channel.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, test } from 'bun:test';
-import SRC from './use-update-channel?raw';
describe('useUpdateChannel module', () => {
test('exports the hook + the UpdateChannel union', async () => {
@@ -7,26 +6,3 @@ describe('useUpdateChannel module', () => {
expect(typeof mod.useUpdateChannel).toBe('function');
});
});
-
-describe('useUpdateChannel source-level guards', () => {
- test('side-effect imports the desktop bridge type augmentation', () => {
- expect(SRC).toMatch(/import\s+['"]@\/lib\/desktop-bridge-types['"]/);
- });
-
- test('queries the channel via state.query()', () => {
- expect(SRC).toMatch(/state[\s\n]*\.query\(\)/);
- });
-
- test('is read-only — no setter, no channel-change subscription', () => {
- expect(SRC).not.toContain('onChannelChanged');
- expect(SRC).not.toMatch(/setChannel\b/);
- });
-
- test('returns null channel + no subscription when bridge is absent', () => {
- expect(SRC).toMatch(/if\s*\(\s*!bridge\s*\)\s*return/);
- });
-
- test('useState initializes channel to null until the query resolves', () => {
- expect(SRC).toMatch(/useState<UpdateChannel\s*\|\s*null>\(null\)/);
- });
-});
diff --git a/packages/app/src/lib/config-provider.test.tsx b/packages/app/src/lib/config-provider.test.tsx
index 6364b668c..8052bac71 100644
--- a/packages/app/src/lib/config-provider.test.tsx
+++ b/packages/app/src/lib/config-provider.test.tsx
@@ -1,9 +1,4 @@
import { describe, expect, test } from 'bun:test';
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
-
-const SRC_PATH = join(__dirname, 'config-provider.tsx');
-const src = readFileSync(SRC_PATH, 'utf-8');
describe('ConfigProvider module surface', () => {
test('exports ConfigProvider component and useConfigContext hook', async () => {
@@ -12,116 +7,3 @@ describe('ConfigProvider module surface', () => {
expect(typeof mod.useConfigContext).toBe('function');
});
});
-
-describe('ConfigProvider — project-local binding wiring', () => {
- test('imports the project-local doc name constant', () => {
- expect(src).toContain('CONFIG_DOC_NAME_PROJECT_LOCAL');
- expect(src).toMatch(/from\s*'@inkeep\/open-knowledge-core'/);
- });
-
- test('opens a third binding for the project-local scope', () => {
- expect(src).toMatch(
- /makeBinding\(\s*collabUrl,\s*CONFIG_DOC_NAME_PROJECT_LOCAL,\s*'project-local'/,
- );
- });
-
- test('makeBinding signature accepts the WriteScope type (covers all three scopes)', () => {
- expect(src).toMatch(/scope:\s*WriteScope/);
- });
-
- test('subscribes to subscribeSynced on the project-local binding', () => {
- expect(src).toContain('subscribeSynced');
- expect(src).toMatch(/projectLocalScoped\.binding\.subscribeSynced/);
- });
-
- test('seeds initial synced state from hasSynced() at mount time', () => {
- expect(src).toMatch(/projectLocalScoped\.binding\.hasSynced\(\)/);
- });
-
- test('cleans up the project-local binding + provider on unmount', () => {
- expect(src).toMatch(/for \(const scoped of \[[^\]]*\bprojectLocalScoped\b[^\]]*\]\)/);
- expect(src).toMatch(/scoped\.cleanup\(\)/);
- expect(src).toContain('unsubProjectLocalSynced');
- });
-});
-
-describe('ConfigProvider — user binding synced wiring', () => {
- test('subscribes via binding.subscribeSynced (matches projectLocal wiring)', () => {
- expect(src).toMatch(/userScoped\.binding\.subscribeSynced\(/);
- expect(src).not.toMatch(/userScoped\.provider\.on\(\s*['"]synced['"]/);
- });
-
- test('seeds initial userSynced from hasSynced() and unsubscribes on unmount', () => {
- expect(src).toMatch(
- /setUserState\(\{\s*binding:\s*userScoped\.binding,\s*config:\s*userScoped\.config,\s*synced:\s*userScoped\.binding\.hasSynced\(\),?\s*\}\)/,
- );
- expect(src).toMatch(/unsubUserSynced\(\)/);
- });
-});
-
-describe('ConfigProvider — context value shape', () => {
- test('exposes projectLocalBinding alongside the existing two bindings', () => {
- expect(src).toMatch(/projectLocalBinding:\s*projectLocalState\?\.binding\s*\?\?\s*null/);
- });
-
- test('exposes projectLocalConfig alongside the existing two configs', () => {
- expect(src).toMatch(/projectLocalConfig:\s*projectLocalState\?\.config\s*\?\?\s*null/);
- });
-
- test('exposes projectLocalSynced with a false default until first sync', () => {
- expect(src).toMatch(/projectLocalSynced:\s*projectLocalState\?\.synced\s*\?\?\s*false/);
- });
-
- test('exposes userSynced with a false default until first sync', () => {
- expect(src).toMatch(/userSynced:\s*userState\?\.synced\s*\?\?\s*false/);
- });
-});
-
-describe('ConfigProvider — mergeLayered call', () => {
- test('passes three layers to mergeLayered (user, project, projectLocal)', () => {
- expect(src).toMatch(
- /mergeLayered\(\s*userState\.config,\s*projectState\.config,\s*projectLocalState\?\.config\s*\)/,
- );
- });
-});
-
-describe('ConfigProvider — Electron theme bridge wiring', () => {
- test('delegates the theme bridge wiring to the shared useThemeBridge hook', () => {
- expect(src).toMatch(
- /import\s*\{\s*useThemeBridge\s*\}\s*from\s*['"]@\/hooks\/use-theme-bridge['"]/,
- );
- expect(src).toMatch(/useThemeBridge\(/);
- expect(src).toContain('window.okDesktop');
- expect(src).toMatch(/themeValue/);
- });
-
- test('falls back to "system" when CRDT theme is unset (cold-launch show-gate release)', () => {
- expect(src).toMatch(/themeValue\s*\?\?\s*['"]system['"]/);
- });
-});
-
-describe('ConfigProvider — provider event logging', () => {
- test('makeBinding passes onDisconnect and onClose to HocuspocusProvider', () => {
- expect(src).toMatch(/new HocuspocusProvider\(\{[\s\S]*?onDisconnect:[\s\S]*?onClose:/);
- });
-
- test('config-provider role uses ok-config-provider-* event names', () => {
- expect(src).toMatch(/['"]config-provider['"]/);
- });
-
- test('okignore-provider role uses ok-okignore-provider-* event names', () => {
- expect(src).toMatch(/['"]okignore-provider['"]/);
- });
-
- test('logProviderEvent helper exists and is the single emission site', () => {
- expect(src).toMatch(/function logProviderEvent\(/);
- expect(src).toMatch(/console\.warn\(\s*JSON\.stringify\(/);
- });
-
- test('log payload includes event, docName, and CloseEvent code/reason', () => {
- expect(src).toContain('event:');
- expect(src).toContain('docName,');
- expect(src).toContain('code:');
- expect(src).toContain('reason:');
- });
-});
diff --git a/packages/app/src/lib/config-provider.user-synced.dom.test.tsx b/packages/app/src/lib/config-provider.user-synced.dom.test.tsx
index ec5f14e70..c28d9a31f 100644
--- a/packages/app/src/lib/config-provider.user-synced.dom.test.tsx
+++ b/packages/app/src/lib/config-provider.user-synced.dom.test.tsx
@@ -1,30 +1,66 @@
import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from 'bun:test';
import type { ConfigBinding, OkignoreBinding, WriteScope } from '@inkeep/open-knowledge-core';
-import { act, cleanup, render, screen } from '@testing-library/react';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import { __resetServerInstanceStoreForTests, setServerInstanceId } from './server-instance-store';
type SyncedListener = () => void;
type ScopeKey = WriteScope;
+type FakeConfig = { scope: ScopeKey; appearance?: { theme?: 'light' | 'dark' | 'system' } };
+type ProviderEvent = { event?: { code: number; reason: string } };
+type ProviderOptions = {
+ name: string;
+ onDisconnect?: (payload: ProviderEvent) => void;
+ onClose?: (payload: ProviderEvent) => void;
+};
+type ProviderRecord = {
+ name: string;
+ options: ProviderOptions;
+ destroyed: boolean;
+};
const captures = new Map<
ScopeKey,
{
syncedListener: SyncedListener | null;
hasSyncedSeed: boolean;
+ config: FakeConfig;
+ disposed: boolean;
+ syncedUnsubscribed: boolean;
}
>();
let okignoreSyncedHandler: (() => void) | null = null;
+let okignoreDisposed = false;
+let providerRecords: ProviderRecord[] = [];
+let mergeLayeredCalls: Array<[unknown, unknown, unknown]> = [];
+let mergedConfig: unknown = {};
+let useThemeBridgeCalls: Array<[unknown, string]> = [];
+let setThemeCalls: string[] = [];
+const buildAuthTokenCalls: Array<readonly unknown[]> = [];
function resetCaptures() {
captures.clear();
okignoreSyncedHandler = null;
+ okignoreDisposed = false;
+ providerRecords = [];
+ mergeLayeredCalls = [];
+ mergedConfig = {};
+ useThemeBridgeCalls = [];
+ setThemeCalls = [];
+ buildAuthTokenCalls.length = 0;
}
function makeFakeConfigBinding(scope: ScopeKey, hasSyncedSeed: boolean): ConfigBinding {
- captures.set(scope, { syncedListener: null, hasSyncedSeed });
+ const config: FakeConfig = { scope };
+ captures.set(scope, {
+ syncedListener: null,
+ hasSyncedSeed,
+ config,
+ disposed: false,
+ syncedUnsubscribed: false,
+ });
return {
- current: () => ({}) as never,
+ current: () => config as never,
patch: () => ({ ok: true, value: { applied: [], effective: {} } }) as never,
subscribe: () => () => {},
hasSynced: () => captures.get(scope)?.hasSyncedSeed ?? false,
@@ -34,9 +70,13 @@ function makeFakeConfigBinding(scope: ScopeKey, hasSyncedSeed: boolean): ConfigB
return () => {
const e = captures.get(scope);
if (e?.syncedListener === listener) e.syncedListener = null;
+ if (e) e.syncedUnsubscribed = true;
};
},
- dispose: () => {},
+ dispose: () => {
+ const entry = captures.get(scope);
+ if (entry) entry.disposed = true;
+ },
};
}
@@ -45,7 +85,9 @@ function makeFakeOkignoreBinding(): OkignoreBinding {
current: () => ({}) as never,
patch: () => ({ ok: true, value: { applied: [], effective: {} } }) as never,
subscribe: () => () => {},
- dispose: () => {},
+ dispose: () => {
+ okignoreDisposed = true;
+ },
} as unknown as OkignoreBinding;
}
@@ -55,15 +97,28 @@ mock.module('@/editor/DocumentContext', () => ({
}));
mock.module('@/hooks/use-theme-bridge', () => ({
- useThemeBridge: () => {},
+ useThemeBridge: (bridge: unknown, theme: string) => {
+ useThemeBridgeCalls.push([bridge, theme]);
+ },
}));
mock.module('next-themes', () => ({
- useTheme: () => ({ setTheme: () => {} }),
+ useTheme: () => ({
+ setTheme: (theme: string) => {
+ setThemeCalls.push(theme);
+ },
+ }),
}));
mock.module('@hocuspocus/provider', () => {
class FakeHocuspocusProvider {
+ private readonly record: ProviderRecord;
+
+ constructor(options: ProviderOptions) {
+ this.record = { name: options.name, options, destroyed: false };
+ providerRecords.push(this.record);
+ }
+
on(event: string, handler: () => void) {
if (event === 'synced') okignoreSyncedHandler = handler;
}
@@ -72,12 +127,13 @@ mock.module('@hocuspocus/provider', () => {
okignoreSyncedHandler = null;
}
}
- destroy() {}
+ destroy() {
+ this.record.destroyed = true;
+ }
}
return { HocuspocusProvider: FakeHocuspocusProvider };
});
-const buildAuthTokenCalls: Array<readonly unknown[]> = [];
mock.module('@/editor/provider-pool', () => ({
buildAuthToken: (...args: readonly unknown[]) => {
buildAuthTokenCalls.push(args);
@@ -93,32 +149,54 @@ mock.module('@inkeep/open-knowledge-core', () => ({
CONFIG_DOC_NAME_PROJECT: '__config__/project',
CONFIG_DOC_NAME_PROJECT_LOCAL: '__local__/project',
CONFIG_DOC_NAME_OKIGNORE: '__config__/okignore',
- mergeLayered: (user: unknown) => user,
+ mergeLayered: (user: unknown, project: unknown, projectLocal: unknown) => {
+ mergeLayeredCalls.push([user, project, projectLocal]);
+ return mergedConfig;
+ },
}));
let userHasSyncedSeed = false;
const { ConfigProvider, useConfigContext } = await import('./config-provider');
+let lastContext: ReturnType<typeof useConfigContext> | null = null;
+
function UserSyncedConsumer() {
const ctx = useConfigContext();
return <span data-testid="user-synced">{String(ctx.userSynced)}</span>;
}
+function ConfigContextProbe() {
+ const ctx = useConfigContext();
+ lastContext = ctx;
+ return (
+ <div>
+ <span data-testid="user-synced">{String(ctx.userSynced)}</span>
+ <span data-testid="project-local-synced">{String(ctx.projectLocalSynced)}</span>
+ <span data-testid="has-project-local-binding">
+ {String(ctx.projectLocalBinding !== null)}
+ </span>
+ <span data-testid="has-project-local-config">{String(ctx.projectLocalConfig !== null)}</span>
+ <span data-testid="has-merged-config">{String(ctx.merged === mergedConfig)}</span>
+ </div>
+ );
+}
+
describe('ConfigProvider — userSynced behavioral wiring (Tier-3)', () => {
let consoleErrorSpy: ReturnType<typeof spyOn>;
beforeEach(() => {
resetCaptures();
+ lastContext = null;
userHasSyncedSeed = false;
__resetServerInstanceStoreForTests();
- buildAuthTokenCalls.length = 0;
consoleErrorSpy = spyOn(console, 'error').mockImplementation(() => {});
});
afterEach(() => {
cleanup();
consoleErrorSpy.mockRestore();
+ Reflect.deleteProperty(window, 'okDesktop');
});
test('userSynced reads false until the binding fires its synced listener, then flips to true', () => {
@@ -152,18 +230,145 @@ describe('ConfigProvider — userSynced behavioral wiring (Tier-3)', () => {
expect(screen.getByTestId('user-synced').textContent).toBe('true');
});
- test('threads the server epoch from the store into every provider auth-token claim (PRD-6881)', () => {
+ test('opens user, project, and project-local bindings and exposes the merged context shape', async () => {
+ render(
+ <ConfigProvider>
+ <ConfigContextProbe />
+ </ConfigProvider>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('has-project-local-binding').textContent).toBe('true');
+ });
+
+ expect(providerRecords.map((record) => record.name)).toEqual([
+ '__user__/config.yml',
+ '__config__/project',
+ '__local__/project',
+ '__config__/okignore',
+ ]);
+ expect([...captures.keys()]).toEqual(['user', 'project', 'project-local']);
+
+ const latestMerge = mergeLayeredCalls.at(-1);
+ expect(latestMerge?.[0]).toBe(captures.get('user')?.config);
+ expect(latestMerge?.[1]).toBe(captures.get('project')?.config);
+ expect(latestMerge?.[2]).toBe(captures.get('project-local')?.config);
+
+ expect(lastContext?.projectLocalBinding).not.toBeNull();
+ expect(lastContext?.projectLocalConfig).toBe(captures.get('project-local')?.config);
+ expect(lastContext?.projectLocalSynced).toBe(false);
+ expect(lastContext?.merged).toBe(mergedConfig);
+ expect(screen.getByTestId('has-project-local-config').textContent).toBe('true');
+ expect(screen.getByTestId('has-merged-config').textContent).toBe('true');
+ });
+
+ test('projectLocalSynced flips from its hasSynced seed and cleans up on unmount', async () => {
+ const { unmount } = render(
+ <ConfigProvider>
+ <ConfigContextProbe />
+ </ConfigProvider>,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('project-local-synced').textContent).toBe('false');
+ });
+
+ const projectLocalEntry = captures.get('project-local');
+ expect(projectLocalEntry?.syncedListener).not.toBeNull();
+
+ act(() => {
+ projectLocalEntry?.syncedListener?.();
+ });
+
+ expect(screen.getByTestId('project-local-synced').textContent).toBe('true');
+
+ unmount();
+
+ expect(projectLocalEntry?.syncedListener).toBeNull();
+ expect(projectLocalEntry?.syncedUnsubscribed).toBe(true);
+ expect(projectLocalEntry?.disposed).toBe(true);
+ expect(okignoreSyncedHandler).toBeNull();
+ expect(okignoreDisposed).toBe(true);
+ expect(providerRecords.find((record) => record.name === '__local__/project')?.destroyed).toBe(
+ true,
+ );
+ });
+
+ test('passes the Electron theme bridge a system fallback when merged config has no theme', async () => {
+ const bridge = { nativeTheme: {} };
+ Object.defineProperty(window, 'okDesktop', {
+ configurable: true,
+ value: bridge,
+ });
+
+ mergedConfig = { appearance: {} };
+
+ render(
+ <ConfigProvider>
+ <ConfigContextProbe />
+ </ConfigProvider>,
+ );
+
+ await waitFor(() => {
+ expect(mergeLayeredCalls.length).toBeGreaterThan(0);
+ });
+
+ expect(useThemeBridgeCalls.at(-1)).toEqual([bridge, 'system']);
+ expect(setThemeCalls).toEqual([]);
+ });
+
+ test('threads the server epoch from the store into every provider auth-token claim', async () => {
setServerInstanceId('epoch-threading-test');
render(
<ConfigProvider>
- <UserSyncedConsumer />
+ <ConfigContextProbe />
</ConfigProvider>,
);
- expect(buildAuthTokenCalls.length).toBeGreaterThan(0);
+ await waitFor(() => {
+ expect(providerRecords.length).toBe(4);
+ });
+ expect(buildAuthTokenCalls.length).toBe(4);
expect(
buildAuthTokenCalls.every((args) => args[0] === null && args[1] === 'epoch-threading-test'),
).toBe(true);
});
+
+ test('provider disconnect and close callbacks emit structured role logs', async () => {
+ const consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
+
+ render(
+ <ConfigProvider>
+ <ConfigContextProbe />
+ </ConfigProvider>,
+ );
+
+ await waitFor(() => {
+ expect(providerRecords.length).toBe(4);
+ });
+
+ providerRecords
+ .find((record) => record.name === '__user__/config.yml')
+ ?.options.onDisconnect?.({ event: { code: 4001, reason: 'network down' } });
+ providerRecords
+ .find((record) => record.name === '__config__/okignore')
+ ?.options.onClose?.({ event: { code: 1006, reason: 'socket closed' } });
+
+ const payloads = consoleWarnSpy.mock.calls.map(([line]) => JSON.parse(String(line)));
+ expect(payloads).toContainEqual({
+ event: 'ok-config-provider-disconnect',
+ docName: '__user__/config.yml',
+ code: 4001,
+ reason: 'network down',
+ });
+ expect(payloads).toContainEqual({
+ event: 'ok-okignore-provider-close',
+ docName: '__config__/okignore',
+ code: 1006,
+ reason: 'socket closed',
+ });
+
+ consoleWarnSpy.mockRestore();
+ });
});
diff --git a/packages/app/src/lib/update-notices-store.test.ts b/packages/app/src/lib/update-notices-store.test.ts
index 303f124c7..a3cd62e83 100644
--- a/packages/app/src/lib/update-notices-store.test.ts
+++ b/packages/app/src/lib/update-notices-store.test.ts
@@ -1,32 +1,86 @@
-import { describe, expect, test } from 'bun:test';
-import { readFileSync } from 'node:fs';
-import { join } from 'node:path';
+import { afterAll, describe, expect, mock, test } from 'bun:test';
-const STORE_SRC = readFileSync(join(__dirname, 'update-notices-store.ts'), 'utf-8');
+const store = await import('./update-notices-store');
-describe('update-notices-store install-time wiring', () => {
- test('imports addSchemaIncompatibilityNotice from UpdateNotices.shared', () => {
- expect(STORE_SRC).toMatch(/addSchemaIncompatibilityNotice/);
- expect(STORE_SRC).toMatch(/from ['"]@\/components\/UpdateNotices\.shared['"]/);
- });
+afterAll(() => {
+ store.dismissNotice('schema-incompatibility-99');
+ Reflect.deleteProperty(globalThis, 'window');
+});
- test('installUpdateNoticesBridge calls bridge.state.query()', () => {
- expect(STORE_SRC).toMatch(/bridge\.state\.query\(\)/);
- });
+describe('update-notices-store install-time runtime wiring', () => {
+ test('installs subscribers once and surfaces boot schema-incompatibility state through the store', async () => {
+ const queryMock = mock(() =>
+ Promise.resolve({
+ channel: 'latest',
+ schemaIncompatibility: {
+ currentBuild: '1.2.3',
+ persistedSchemaVersion: 99,
+ supportedSchemaVersion: 1,
+ },
+ }),
+ );
+ const downloadedUnsub = mock(() => {});
+ const relaunchingUnsub = mock(() => {});
+ const relaunchFailedUnsub = mock(() => {});
+ const whatsNewUnsub = mock(() => {});
+ const whatsNewDismissedUnsub = mock(() => {});
+ const stuckHintUnsub = mock(() => {});
+ const bridge = {
+ onUpdateDownloaded: mock(() => downloadedUnsub),
+ onUpdateRelaunching: mock(() => relaunchingUnsub),
+ onUpdateRelaunchFailed: mock(() => relaunchFailedUnsub),
+ onWhatsNew: mock(() => whatsNewUnsub),
+ onWhatsNewDismissed: mock(() => whatsNewDismissedUnsub),
+ onUpdateStuckHint: mock(() => stuckHintUnsub),
+ update: {
+ relaunchNow: mock(() => Promise.resolve(undefined)),
+ dismissWhatsNew: mock(() => Promise.resolve(undefined)),
+ },
+ state: {
+ query: queryMock,
+ resetIncompatible: mock(() => Promise.resolve(undefined)),
+ },
+ shell: { openExternal: mock(() => Promise.resolve(undefined)) },
+ };
+ const testWindow = {} as Window & typeof globalThis;
+ Object.defineProperty(globalThis, 'window', {
+ configurable: true,
+ value: testWindow,
+ });
+ Object.defineProperty(testWindow, 'okDesktop', {
+ configurable: true,
+ value: bridge,
+ });
+
+ store.installUpdateNoticesBridge();
- test('non-null schemaIncompatibility branch invokes addSchemaIncompatibilityNotice', () => {
- expect(STORE_SRC).toMatch(/snapshot\.schemaIncompatibility/);
- expect(STORE_SRC).toMatch(
- /addSchemaIncompatibilityNotice\([\s\S]*?bridge[\s\S]*?addNotice[\s\S]*?dismissNotice/,
+ expect(bridge.onUpdateDownloaded).toHaveBeenCalledWith(expect.any(Function));
+ expect(bridge.onUpdateRelaunching).toHaveBeenCalledWith(expect.any(Function));
+ expect(bridge.onUpdateRelaunchFailed).toHaveBeenCalledWith(expect.any(Function));
+ expect(bridge.onWhatsNew).toHaveBeenCalledWith(expect.any(Function));
+ expect(bridge.onWhatsNewDismissed).toHaveBeenCalledWith(expect.any(Function));
+ expect(bridge.onUpdateStuckHint).toHaveBeenCalledWith(expect.any(Function));
+ expect(queryMock).toHaveBeenCalledTimes(1);
+
+ await Promise.resolve();
+
+ const [notice] = store.getNoticesSnapshot();
+ expect(notice?.id).toBe('schema-incompatibility-99');
+ expect(notice?.body).toBe(
+ 'Your settings and recent projects were saved by a newer build than this one (v1.2.3). Reset to defaults to continue.',
);
- });
+ expect(notice?.priority).toBe(0);
+ expect(notice?.action?.label).toBe('Reset to defaults');
+ expect(typeof notice?.action?.onClick).toBe('function');
- test('still installs the event subscribers via attachUpdateSubscribers', () => {
- expect(STORE_SRC).toMatch(/attachUpdateSubscribers\(bridge, addNotice, dismissNotice\)/);
- });
+ store.installUpdateNoticesBridge();
- test('idempotent attached guard is preserved (HMR-safe)', () => {
- expect(STORE_SRC).toMatch(/if \(attached\) return;/);
- expect(STORE_SRC).toMatch(/attached = true;/);
+ expect(bridge.onUpdateDownloaded).toHaveBeenCalledTimes(1);
+ expect(bridge.onUpdateRelaunching).toHaveBeenCalledTimes(1);
+ expect(bridge.onUpdateRelaunchFailed).toHaveBeenCalledTimes(1);
+ expect(bridge.onWhatsNew).toHaveBeenCalledTimes(1);
+ expect(bridge.onWhatsNewDismissed).toHaveBeenCalledTimes(1);
+ expect(bridge.onUpdateStuckHint).toHaveBeenCalledTimes(1);
+ expect(queryMock).toHaveBeenCalledTimes(1);
});
});
diff --git a/packages/app/src/lib/use-settings-route.dom.test.tsx b/packages/app/src/lib/use-settings-route.dom.test.tsx
new file mode 100644
index 000000000..f7824d49d
--- /dev/null
+++ b/packages/app/src/lib/use-settings-route.dom.test.tsx
@@ -0,0 +1,44 @@
+import { afterEach, describe, expect, mock, test } from 'bun:test';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import * as React from 'react';
+
+const realStartTransition = React.startTransition;
+const startTransitionMock = mock((callback: React.TransitionFunction) => {
+ realStartTransition(callback);
+});
+
+mock.module('react', () => ({
+ ...React,
+ startTransition: startTransitionMock,
+}));
+
+describe('useSettingsRoute runtime routing', () => {
+ afterEach(() => {
+ cleanup();
+ startTransitionMock.mockClear();
+ window.history.replaceState(null, '', '/');
+ });
+
+ async function renderProbe() {
+ const { useSettingsRoute } = await import('./use-settings-route');
+
+ function Probe() {
+ const route = useSettingsRoute();
+ return <output data-testid="settings-open">{route.open ? 'open' : 'closed'}</output>;
+ }
+
+ render(<Probe />);
+ }
+
+ test('hashchange open-state update is scheduled through startTransition', async () => {
+ window.location.hash = '';
+ await renderProbe();
+ expect(screen.getByTestId('settings-open').textContent).toBe('closed');
+
+ window.history.pushState(null, '', '#settings');
+ fireEvent(window, new Event('hashchange'));
+
+ expect(startTransitionMock).toHaveBeenCalledTimes(1);
+ expect(screen.getByTestId('settings-open').textContent).toBe('open');
+ });
+});
diff --git a/packages/app/src/lib/use-settings-route.test.ts b/packages/app/src/lib/use-settings-route.test.ts
index 125102781..eed8e9cfe 100644
--- a/packages/app/src/lib/use-settings-route.test.ts
+++ b/packages/app/src/lib/use-settings-route.test.ts
@@ -1,6 +1,5 @@
import { describe, expect, test } from 'bun:test';
import { isSettingsHashOpen, isSettingsShortcut, SETTINGS_OPEN_HASH } from './use-settings-route';
-import SRC from './use-settings-route?raw';
describe('isSettingsHashOpen', () => {
test('empty hash → false', () => {
@@ -90,10 +89,3 @@ describe('isSettingsShortcut', () => {
expect(isSettingsShortcut(ev({ metaKey: true, target: null }))).toBe(true);
});
});
-
-describe('useSettingsRoute source-level guards', () => {
- test('wraps the hashchange setOpen flip in startTransition', () => {
- expect(SRC).toMatch(/import\s+\{[^}]*\bstartTransition\b[^}]*\}\s+from\s+['"]react['"]/);
- expect(SRC).toMatch(/startTransition\(\s*\(\s*\)\s*=>\s*\{\s*setOpen\(\s*isSettingsHashOpen\(/);
- });
-});
diff --git a/packages/app/src/presence/PresenceBar-avatar-click.test.tsx b/packages/app/src/presence/PresenceBar-avatar-click.test.tsx
index 8de7f28b3..ae27e4731 100644
--- a/packages/app/src/presence/PresenceBar-avatar-click.test.tsx
+++ b/packages/app/src/presence/PresenceBar-avatar-click.test.tsx
@@ -3,6 +3,7 @@ import type { AgentPresenceEntry } from '@inkeep/open-knowledge-core';
import { renderToString } from 'react-dom/server';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { AgentParticipant } from './use-presence';
+import { isSelfAwarenessEntry } from './use-presence.ts';
const openActivityPanelCalls: Array<[string, string | null]> = [];
const openActivityPanel = (connectionId: string, targetDoc: string | null): void => {
@@ -27,6 +28,7 @@ mock.module('@/editor/DocumentContext', () => ({
}));
mock.module('./use-presence', () => ({
+ isSelfAwarenessEntry,
usePresence: () => ({ current: currentAgents, crossDoc: crossDocAgents }),
}));
diff --git a/packages/app/src/presence/use-presence.dom.test.tsx b/packages/app/src/presence/use-presence.dom.test.tsx
new file mode 100644
index 000000000..40eeea487
--- /dev/null
+++ b/packages/app/src/presence/use-presence.dom.test.tsx
@@ -0,0 +1,139 @@
+import { afterEach, describe, expect, test } from 'bun:test';
+import type { HocuspocusProvider } from '@hocuspocus/provider';
+import type { AgentPresenceEntry } from '@inkeep/open-knowledge-core';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import type { AwarenessUser } from './identity';
+import { usePresence } from './use-presence';
+
+interface FakeAwarenessState {
+ user?: AwarenessUser;
+ mode?: 'wysiwyg' | 'source';
+ agentPresence?: Record<string, AgentPresenceEntry>;
+}
+
+interface FakeAwareness {
+ clientID: number;
+ getLocalState: () => FakeAwarenessState | undefined;
+ getStates: () => Map<number, FakeAwarenessState>;
+ on: (_event: 'change', _handler: () => void) => void;
+ off: (_event: 'change', _handler: () => void) => void;
+}
+
+function makeHuman(name: string, principalId?: string): AwarenessUser {
+ return {
+ type: 'human',
+ name,
+ color: '#fff',
+ tabId: `tab-${name}`,
+ ...(principalId !== undefined ? { principalId } : {}),
+ };
+}
+
+function makeAgent(overrides: Partial<AgentPresenceEntry> = {}): AgentPresenceEntry {
+ return {
+ displayName: 'Claude',
+ icon: 'claude',
+ color: '#d97757',
+ currentDoc: 'doc.md',
+ mode: 'writing',
+ ts: Date.now(),
+ ...overrides,
+ };
+}
+
+function makeAwareness(args: {
+ clientID?: number;
+ localState?: FakeAwarenessState;
+ states?: Array<[number, FakeAwarenessState]>;
+}): FakeAwareness {
+ return {
+ clientID: args.clientID ?? 1,
+ getLocalState: () => args.localState,
+ getStates: () => new Map(args.states ?? []),
+ on: () => {},
+ off: () => {},
+ };
+}
+
+function asProvider(awareness: FakeAwareness): HocuspocusProvider {
+ return { awareness } as unknown as HocuspocusProvider;
+}
+
+function PresenceProbe({
+ activeProvider,
+ systemProvider = null,
+}: {
+ activeProvider: HocuspocusProvider | null;
+ systemProvider?: HocuspocusProvider | null;
+}) {
+ const presence = usePresence(activeProvider, systemProvider, 'doc.md');
+ const current = presence.current
+ .map((participant) =>
+ participant.kind === 'human'
+ ? `human:${participant.clientId}:${participant.tabCount}`
+ : `agent:${participant.agentId}:${participant.presence.currentDoc}`,
+ )
+ .join('|');
+ return <output data-testid="presence-current">{current}</output>;
+}
+
+describe('usePresence runtime self-filtering', () => {
+ afterEach(() => cleanup());
+
+ test('filters local principal before human dedupe', async () => {
+ const activeAwareness = makeAwareness({
+ clientID: 101,
+ localState: { user: makeHuman('Me', 'principal-me') },
+ states: [
+ [101, { user: makeHuman('Me current tab', 'principal-me'), mode: 'wysiwyg' }],
+ [202, { user: makeHuman('Me second tab', 'principal-me'), mode: 'source' }],
+ [303, { user: makeHuman('Remote', 'principal-remote'), mode: 'wysiwyg' }],
+ ],
+ });
+
+ render(<PresenceProbe activeProvider={asProvider(activeAwareness)} />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('presence-current').textContent).toBe('human:303:1');
+ });
+ });
+
+ test('falls back to active awareness clientID when local principal is absent', async () => {
+ const activeAwareness = makeAwareness({
+ clientID: 101,
+ localState: { user: makeHuman('Me') },
+ states: [
+ [101, { user: makeHuman('Me current tab'), mode: 'wysiwyg' }],
+ [202, { user: makeHuman('Synthesized remote tab'), mode: 'source' }],
+ ],
+ });
+
+ render(<PresenceProbe activeProvider={asProvider(activeAwareness)} />);
+
+ await waitFor(() => {
+ expect(screen.getByTestId('presence-current').textContent).toBe('human:202:1');
+ });
+ });
+
+ test('agent presence is not filtered by the human self discriminator', async () => {
+ const activeAwareness = makeAwareness({
+ clientID: 101,
+ localState: { user: makeHuman('Me', 'agent-1') },
+ states: [],
+ });
+ const systemAwareness = makeAwareness({
+ states: [[1, { agentPresence: { 'agent-1': makeAgent() } }]],
+ });
+
+ render(
+ <PresenceProbe
+ activeProvider={asProvider(activeAwareness)}
+ systemProvider={asProvider(systemAwareness)}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(screen.getByTestId('presence-current').textContent).toBe('agent:agent-1:doc.md');
+ });
+ });
+});
diff --git a/packages/app/src/presence/use-presence.test.ts b/packages/app/src/presence/use-presence.test.ts
index 352d4fca0..3809603d9 100644
--- a/packages/app/src/presence/use-presence.test.ts
+++ b/packages/app/src/presence/use-presence.test.ts
@@ -5,7 +5,6 @@ import {
type Participant,
participantsEqual,
} from './participant-model.ts';
-import SRC from './use-presence?raw';
import { isSelfAwarenessEntry } from './use-presence.ts';
function makeHuman(
@@ -250,25 +249,3 @@ describe('isSelfAwarenessEntry — presence self-filter discriminator', () => {
).toBe(true);
});
});
-
-describe('usePresence source-level guards — self-filter wiring', () => {
- test('self-filter runs INSIDE the human-iteration loop, BEFORE dedupeHumansByPrincipalId', () => {
- const filterIdx = SRC.indexOf('isSelfAwarenessEntry(');
- const dedupeIdx = SRC.indexOf('dedupeHumansByPrincipalId(');
- expect(filterIdx).toBeGreaterThan(0);
- expect(dedupeIdx).toBeGreaterThan(0);
- expect(filterIdx).toBeLessThan(dedupeIdx);
- });
-
- test('local identity comes from `activeAwareness` — principalId via getLocalState, clientID direct', () => {
- expect(SRC).toMatch(/activeAwareness\??\.getLocalState\(\)/);
- expect(SRC).toMatch(/activeAwareness\??\.clientID/);
- });
-
- test('agent loop is unaffected — no self-filter call in the agent branch', () => {
- const pickAgentsIdx = SRC.indexOf('pickAgentsForDoc(');
- expect(pickAgentsIdx).toBeGreaterThan(0);
- const filterIdx = SRC.indexOf('isSelfAwarenessEntry(');
- expect(filterIdx).toBeLessThan(pickAgentsIdx);
- });
-});
diff --git a/packages/app/src/test-utils/lingui-mock.ts b/packages/app/src/test-utils/lingui-mock.ts
new file mode 100644
index 000000000..18609731e
--- /dev/null
+++ b/packages/app/src/test-utils/lingui-mock.ts
@@ -0,0 +1,10 @@
+export function renderLinguiTemplate(
+ strings: TemplateStringsArray | string,
+ ...values: unknown[]
+): string {
+ if (typeof strings === 'string') return strings;
+ return strings.reduce(
+ (text, chunk, index) => `${text}${chunk}${index < values.length ? String(values[index]) : ''}`,
+ '',
+ );
+}
diff --git a/packages/app/src/test-utils/visual-contract.ts b/packages/app/src/test-utils/visual-contract.ts
new file mode 100644
index 000000000..c37f0b34d
--- /dev/null
+++ b/packages/app/src/test-utils/visual-contract.ts
@@ -0,0 +1,22 @@
+import { expect } from 'bun:test';
+
+type ClassNameValue = string | null | undefined;
+
+export function expectVisualClassTokens(className: ClassNameValue, tokens: readonly string[]) {
+ const actualClassName = className ?? '';
+
+ for (const token of tokens) {
+ expect(actualClassName).toContain(token);
+ }
+}
+
+export function expectVisualClassTokensAbsent(
+ className: ClassNameValue,
+ tokens: readonly string[],
+) {
+ const actualClassName = className ?? '';
+
+ for (const token of tokens) {
+ expect(actualClassName).not.toContain(token);
+ }
+}
diff --git a/packages/app/tests/dom/jsdom-preload.ts b/packages/app/tests/dom/jsdom-preload.ts
index 942462737..c15c77fd9 100644
--- a/packages/app/tests/dom/jsdom-preload.ts
+++ b/packages/app/tests/dom/jsdom-preload.ts
@@ -25,6 +25,8 @@ Object.assign(globalThis, {
Node: win.Node,
NodeList: win.NodeList,
NodeFilter: win.NodeFilter,
+ DocumentFragment: win.DocumentFragment,
+ DOMRect: win.DOMRect,
Event: win.Event,
CustomEvent: win.CustomEvent,
EventTarget: win.EventTarget,
@@ -35,6 +37,11 @@ Object.assign(globalThis, {
PointerEvent: win.PointerEvent,
DataTransfer: win.DataTransfer,
MutationObserver: win.MutationObserver,
+ ResizeObserver: class MinimalResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ },
getComputedStyle: win.getComputedStyle.bind(win),
requestAnimationFrame: win.requestAnimationFrame.bind(win),
cancelAnimationFrame: win.cancelAnimationFrame.bind(win),
@@ -55,6 +62,10 @@ const matchMediaStub = (query: string): MediaQueryList =>
(globalThis as { matchMedia?: typeof matchMediaStub }).matchMedia = matchMediaStub;
(win as { matchMedia?: typeof matchMediaStub }).matchMedia = matchMediaStub;
+if (!win.HTMLElement.prototype.scrollIntoView) {
+ win.HTMLElement.prototype.scrollIntoView = () => {};
+}
+
if (typeof (globalThis as { MessageChannel?: unknown }).MessageChannel === 'undefined') {
class MinimalMessagePort {
onmessage: ((ev: { data: unknown }) => void) | null = null;