Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Implement Cmd+W tab-close behavior for Open Knowledge (#1655)

Dimitri POSTOLOV772a4c87a972
diff --git a/packages/app/src/components/FileSidebar.tsx b/packages/app/src/components/FileSidebar.tsx
index 7a7549134..08f3e34dc 100644
--- a/packages/app/src/components/FileSidebar.tsx
+++ b/packages/app/src/components/FileSidebar.tsx
@@ -415,6 +415,7 @@ function FileSidebarInner({ onOpenSearch }: FileSidebarProps) {
case 'version-history':
case 'focus-search':
case 'focus-command-palette':
+ case 'close-active-tab-or-window':
case 'toggle-doc-panel':
return;
}
diff --git a/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx b/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
index c40e79e1f..03d328800 100644
--- a/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
+++ b/packages/app/src/components/NavigatorApp.menu-action.dom.test.tsx
@@ -33,7 +33,7 @@ if (globalWithDomShims.ResizeObserver === undefined) {
const ASYNC_TIMEOUT_MS = 2000;
-type MenuActionLike = 'new-project' | 'new-doc' | 'toggle-sidebar';
+type MenuActionLike = 'new-project' | 'new-doc' | 'toggle-sidebar' | 'close-active-tab-or-window';
interface NavigatorBridgeStub {
bridge: OkDesktopBridge;
@@ -147,4 +147,17 @@ describe('NavigatorApp new-project menu-action subscription', () => {
await new Promise((r) => setTimeout(r, 50));
expect(screen.queryByTestId('create-project-dialog') !== null).toBe(false);
});
+
+ test('close-active-tab-or-window menu action closes the navigator window', async () => {
+ const closeSpy = spyOn(window, 'close').mockImplementation(() => {});
+ const stub = makeNavigatorBridge();
+ render(<NavigatorApp bridge={stub.bridge} />);
+
+ await new Promise((r) => setTimeout(r, 0));
+
+ stub.fire('close-active-tab-or-window');
+
+ expect(closeSpy).toHaveBeenCalledTimes(1);
+ closeSpy.mockRestore();
+ });
});
diff --git a/packages/app/src/components/NavigatorApp.tsx b/packages/app/src/components/NavigatorApp.tsx
index 2e5eda84d..129539bc5 100644
--- a/packages/app/src/components/NavigatorApp.tsx
+++ b/packages/app/src/components/NavigatorApp.tsx
@@ -107,6 +107,7 @@ export function NavigatorApp({ bridge }: { bridge: OkDesktopBridge }) {
useEffect(() => {
return bridge.onMenuAction((action) => {
if (action === 'new-project') setCreateDialogOpen(true);
+ if (action === 'close-active-tab-or-window') window.close();
});
}, [bridge]);
diff --git a/packages/app/src/editor/DocumentContext.dom.test.tsx b/packages/app/src/editor/DocumentContext.dom.test.tsx
index 25a80c80b..b7970ca78 100644
--- a/packages/app/src/editor/DocumentContext.dom.test.tsx
+++ b/packages/app/src/editor/DocumentContext.dom.test.tsx
@@ -1,7 +1,8 @@
-import { afterEach, describe, expect, mock, test } from 'bun:test';
-import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, mock, spyOn, test } from 'bun:test';
+import { act, cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
-import type { ReactNode } from 'react';
+import { type ReactNode, useLayoutEffect, useState } from 'react';
+import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { docTabId, localTabSessionStorageKey } from './editor-tabs';
mock.module('@/lib/use-collab-url', () => ({
@@ -32,6 +33,75 @@ function seedTabSession() {
);
}
+function seedActiveOtherTabSession() {
+ window.localStorage.setItem(
+ localTabSessionStorageKey(window.location.origin),
+ JSON.stringify({
+ openTabs: [PINNED_TAB_ID, OTHER_TAB_ID],
+ pinnedTabIds: [],
+ activeDocName: 'Other.md',
+ activeTabId: OTHER_TAB_ID,
+ updatedAt: new Date('2026-05-13T00:00:00.000Z').toISOString(),
+ }),
+ );
+}
+
+function seedOnlyPinnedTabSession() {
+ window.localStorage.setItem(
+ localTabSessionStorageKey(window.location.origin),
+ JSON.stringify({
+ openTabs: [PINNED_TAB_ID],
+ pinnedTabIds: [PINNED_TAB_ID],
+ activeDocName: 'Pinned.md',
+ activeTabId: PINNED_TAB_ID,
+ updatedAt: new Date('2026-05-13T00:00:00.000Z').toISOString(),
+ }),
+ );
+}
+
+type MenuActionLike = 'close-active-tab-or-window' | 'new-doc';
+
+interface EditorBridgeStub {
+ bridge: OkDesktopBridge;
+ fire(action: MenuActionLike): void;
+}
+
+function makeEditorBridgeStub(): EditorBridgeStub {
+ let captured: ((action: MenuActionLike) => void) | null = null;
+ const bridge = {
+ config: {
+ mode: 'editor',
+ collabUrl: '',
+ apiOrigin: '',
+ projectPath: '',
+ projectName: 'Test Project',
+ },
+ onMenuAction: (cb: (action: MenuActionLike) => void) => {
+ captured = cb;
+ return () => {
+ captured = null;
+ };
+ },
+ project: {
+ getSessionState: async () => ({
+ openTabs: [],
+ pinnedTabIds: [],
+ activeDocName: null,
+ activeTabId: null,
+ updatedAt: null,
+ }),
+ setSessionState: async () => undefined,
+ },
+ } as unknown as OkDesktopBridge;
+
+ return {
+ bridge,
+ fire: (action) => {
+ act(() => captured?.(action));
+ },
+ };
+}
+
function Harness() {
const ctx = useDocumentContext();
return (
@@ -48,6 +118,36 @@ function Harness() {
);
}
+function CloseActiveHarness() {
+ const ctx = useDocumentContext();
+ const [handled, setHandled] = useState<string>('');
+ return (
+ <>
+ <span data-testid="open-tabs">{ctx.openTabs.join('|')}</span>
+ <span data-testid="active-tab">{ctx.activeTabId ?? ''}</span>
+ <span data-testid="new-tabs">{ctx.newTabIds.join('|')}</span>
+ <span data-testid="active-new-tab">{ctx.activeNewTabId ?? ''}</span>
+ <span data-testid="close-handled">{handled}</span>
+ <button type="button" onClick={() => ctx.openNewTab()}>
+ Open new
+ </button>
+ <button type="button" onClick={() => setHandled(String(ctx.closeActiveTabOrWindow()))}>
+ Close active
+ </button>
+ </>
+ );
+}
+
+function BridgeCloseActiveHarness({ bridge }: { bridge: OkDesktopBridge }) {
+ useLayoutEffect(() => {
+ window.okDesktop = bridge;
+ return () => {
+ delete window.okDesktop;
+ };
+ }, [bridge]);
+ return <CloseActiveHarness />;
+}
+
function ProviderHarness({ children }: { children: ReactNode }) {
return <DocumentProvider>{children}</DocumentProvider>;
}
@@ -55,6 +155,7 @@ function ProviderHarness({ children }: { children: ReactNode }) {
describe('DocumentContext tab close force contract', () => {
afterEach(() => {
cleanup();
+ delete window.okDesktop;
window.localStorage.clear();
window.location.hash = '';
});
@@ -77,6 +178,105 @@ describe('DocumentContext tab close force contract', () => {
expect(screen.getByTestId('open-tabs').textContent).toBe(OTHER_TAB_ID);
expect(screen.getByTestId('pinned-tabs').textContent).toBe('');
});
+
+ test('closeActiveTabOrWindow closes one active tab and reports the menu action handled', async () => {
+ seedActiveOtherTabSession();
+ render(<CloseActiveHarness />, { wrapper: ProviderHarness });
+
+ expect(screen.getByTestId('open-tabs').textContent).toBe(`${PINNED_TAB_ID}|${OTHER_TAB_ID}`);
+ expect(screen.getByTestId('active-tab').textContent).toBe(OTHER_TAB_ID);
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Close active' }));
+
+ expect(screen.getByTestId('close-handled').textContent).toBe('true');
+ expect(screen.getByTestId('open-tabs').textContent).toBe(PINNED_TAB_ID);
+ expect(screen.getByTestId('active-tab').textContent).toBe(PINNED_TAB_ID);
+ });
+
+ test('closeActiveTabOrWindow skips active pinned tab and closes the next visible unpinned tab', async () => {
+ seedTabSession();
+ render(<CloseActiveHarness />, { wrapper: ProviderHarness });
+
+ expect(screen.getByTestId('open-tabs').textContent).toBe(`${PINNED_TAB_ID}|${OTHER_TAB_ID}`);
+ expect(screen.getByTestId('active-tab').textContent).toBe(PINNED_TAB_ID);
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Close active' }));
+
+ expect(screen.getByTestId('close-handled').textContent).toBe('true');
+ expect(screen.getByTestId('open-tabs').textContent).toBe(PINNED_TAB_ID);
+ expect(screen.getByTestId('active-tab').textContent).toBe(PINNED_TAB_ID);
+ });
+
+ test('closeActiveTabOrWindow reports unhandled when only pinned tabs remain', async () => {
+ seedOnlyPinnedTabSession();
+ render(<CloseActiveHarness />, { wrapper: ProviderHarness });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Close active' }));
+
+ expect(screen.getByTestId('close-handled').textContent).toBe('false');
+ expect(screen.getByTestId('open-tabs').textContent).toBe(PINNED_TAB_ID);
+ expect(screen.getByTestId('active-tab').textContent).toBe(PINNED_TAB_ID);
+ });
+
+ test('closeActiveTabOrWindow closes an active new tab before falling back to the window', async () => {
+ render(<CloseActiveHarness />, { wrapper: ProviderHarness });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Open new' }));
+
+ expect(screen.getByTestId('new-tabs').textContent).toBe('new-tab:1');
+ expect(screen.getByTestId('active-new-tab').textContent).toBe('new-tab:1');
+
+ await user.click(screen.getByRole('button', { name: 'Close active' }));
+
+ expect(screen.getByTestId('close-handled').textContent).toBe('true');
+ expect(screen.getByTestId('new-tabs').textContent).toBe('');
+ expect(screen.getByTestId('active-new-tab').textContent).toBe('');
+ });
+
+ test('closeActiveTabOrWindow reports unhandled when no visible tabs remain', async () => {
+ render(<CloseActiveHarness />, { wrapper: ProviderHarness });
+
+ const user = userEvent.setup();
+ await user.click(screen.getByRole('button', { name: 'Close active' }));
+
+ expect(screen.getByTestId('close-handled').textContent).toBe('false');
+ expect(screen.getByTestId('open-tabs').textContent).toBe('');
+ expect(screen.getByTestId('active-tab').textContent).toBe('');
+ });
+
+ test('desktop close-active-tab-or-window action closes tabs before closing the editor window', async () => {
+ seedActiveOtherTabSession();
+ const closeSpy = spyOn(window, 'close').mockImplementation(() => {});
+ const stub = makeEditorBridgeStub();
+
+ render(<BridgeCloseActiveHarness bridge={stub.bridge} />, { wrapper: ProviderHarness });
+ await new Promise((r) => setTimeout(r, 0));
+
+ expect(screen.getByTestId('open-tabs').textContent).toBe(`${PINNED_TAB_ID}|${OTHER_TAB_ID}`);
+
+ stub.fire('close-active-tab-or-window');
+
+ expect(closeSpy).toHaveBeenCalledTimes(0);
+ expect(screen.getByTestId('open-tabs').textContent).toBe(PINNED_TAB_ID);
+
+ cleanup();
+ delete window.okDesktop;
+ window.localStorage.clear();
+
+ const emptyStub = makeEditorBridgeStub();
+ render(<BridgeCloseActiveHarness bridge={emptyStub.bridge} />, { wrapper: ProviderHarness });
+ await new Promise((r) => setTimeout(r, 0));
+
+ emptyStub.fire('close-active-tab-or-window');
+
+ expect(closeSpy).toHaveBeenCalledTimes(1);
+ expect(screen.getByTestId('open-tabs').textContent).toBe('');
+ closeSpy.mockRestore();
+ });
});
const REORDER_A = docTabId('A.md');
diff --git a/packages/app/src/editor/DocumentContext.tsx b/packages/app/src/editor/DocumentContext.tsx
index 5d5d4ff0c..2f3480679 100644
--- a/packages/app/src/editor/DocumentContext.tsx
+++ b/packages/app/src/editor/DocumentContext.tsx
@@ -88,6 +88,7 @@ interface DocumentContextValue {
openTargetTransition: (target: ResolvedNavigationTarget, options?: OpenTargetOptions) => void;
clearTarget: () => void;
closeDocument: (docName: string) => void;
+ closeActiveTabOrWindow: () => boolean;
closeTab: (tabId: string) => void;
pinTab: (tabId: string) => void;
unpinTab: (tabId: string) => void;
@@ -883,6 +884,119 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
openTargetWithOptions(target, options);
};
+ const closeTabById = (tabId: string) => {
+ if (pinnedTabIdsRef.current.includes(tabId)) return;
+ markTabSessionClosedDuringRestore();
+ let nextActiveTabId: string | null = null;
+ const closingDocName = docNameForTabId(tabId);
+ if (collabUrl !== null) {
+ const p = getPool(collabUrl);
+ if (closingDocName && !hasOpenDocTab(openTabsRef.current, closingDocName, new Set([tabId]))) {
+ p.close(closingDocName);
+ }
+ }
+ const currentActiveTabId =
+ activeTabId ?? activeTabIdForTarget(activeTarget, snapshot.activeDocName);
+ updateOpenTabs((current) => {
+ nextActiveTabId = nextActiveTabAfterClose(current, currentActiveTabId, tabId);
+ return removeOpenTab(current, tabId);
+ });
+ if (currentActiveTabId !== tabId) return;
+ if (nextActiveTabId) {
+ commitActiveTabId(nextActiveTabId);
+ window.location.hash = hashFromTabId(nextActiveTabId);
+ return;
+ }
+ if (collabUrl !== null) {
+ const p = getPool(collabUrl);
+ p.clearActive();
+ }
+ setActiveTarget(null);
+ commitActiveTabId(null);
+ window.location.hash = '';
+ };
+
+ const closeNewTabById = (tabId: string) => {
+ markTabSessionClosedDuringRestore();
+ const currentNewTabIds = newTabIdsRef.current;
+ if (!currentNewTabIds.includes(tabId)) return;
+ const nextNewTabIds = currentNewTabIds.filter((id) => id !== tabId);
+ commitNewTabIds(nextNewTabIds);
+ if (activeNewTabIdRef.current !== tabId) return;
+
+ const closedIndex = currentNewTabIds.indexOf(tabId);
+ const nextNewTabId = nextNewTabIds[closedIndex] ?? nextNewTabIds[closedIndex - 1] ?? null;
+ if (nextNewTabId) {
+ commitActiveNewTabId(nextNewTabId);
+ if (collabUrl !== null) {
+ const p = getPool(collabUrl);
+ p.clearActive();
+ }
+ setActiveTarget(null);
+ commitActiveTabId(null);
+ if (window.location.hash !== '') {
+ window.location.hash = '';
+ }
+ return;
+ }
+
+ commitActiveNewTabId(null);
+ const nextActiveTabId = openTabsRef.current[openTabsRef.current.length - 1] ?? null;
+ if (nextActiveTabId) {
+ commitActiveTabId(nextActiveTabId);
+ window.location.hash = hashFromTabId(nextActiveTabId);
+ return;
+ }
+ if (collabUrl !== null) {
+ const p = getPool(collabUrl);
+ p.clearActive();
+ }
+ setActiveTarget(null);
+ commitActiveTabId(null);
+ window.location.hash = '';
+ };
+
+ const closeActiveTabOrWindow = (): boolean => {
+ const activeNewTab = activeNewTabIdRef.current;
+ if (activeNewTab) {
+ closeNewTabById(activeNewTab);
+ return true;
+ }
+
+ const pinnedTabSet = new Set(pinnedTabIdsRef.current);
+ const openTabSet = new Set(openTabsRef.current.filter((id) => !pinnedTabSet.has(id)));
+ const activeOpenTab =
+ activeTabIdRef.current && openTabSet.has(activeTabIdRef.current)
+ ? activeTabIdRef.current
+ : null;
+ const targetTabId = activeOpenTab ?? visibleTabIdsRef.current.find((id) => openTabSet.has(id));
+ if (targetTabId) {
+ closeTabById(targetTabId);
+ return true;
+ }
+
+ const newTabSet = new Set(newTabIdsRef.current);
+ const targetNewTabId = visibleTabIdsRef.current.find((id) => newTabSet.has(id));
+ if (targetNewTabId) {
+ closeNewTabById(targetNewTabId);
+ return true;
+ }
+
+ return false;
+ };
+
+ useEffect(() => {
+ const bridge = getDesktopBridge();
+ if (!bridge) return;
+ return bridge.onMenuAction((action) => {
+ if (action !== 'close-active-tab-or-window') return;
+ if (!closeActiveTabOrWindow()) window.close();
+ });
+ }, [
+ // biome-ignore lint/correctness/useExhaustiveDependencies: closeActiveTabOrWindow is render-bound; re-subscribing keeps the desktop menu handler fresh for current tab state.
+ closeActiveTabOrWindow,
+ ]);
+
const value: DocumentContextValue = {
principal,
activeTarget,
@@ -929,40 +1043,8 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
return docNameForNavigationTarget(current) === docName ? null : current;
});
},
- closeTab: (tabId: string) => {
- if (pinnedTabIdsRef.current.includes(tabId)) return;
- markTabSessionClosedDuringRestore();
- let nextActiveTabId: string | null = null;
- const closingDocName = docNameForTabId(tabId);
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- if (
- closingDocName &&
- !hasOpenDocTab(openTabsRef.current, closingDocName, new Set([tabId]))
- ) {
- p.close(closingDocName);
- }
- }
- const currentActiveTabId =
- activeTabId ?? activeTabIdForTarget(activeTarget, snapshot.activeDocName);
- updateOpenTabs((current) => {
- nextActiveTabId = nextActiveTabAfterClose(current, currentActiveTabId, tabId);
- return removeOpenTab(current, tabId);
- });
- if (currentActiveTabId !== tabId) return;
- if (nextActiveTabId) {
- commitActiveTabId(nextActiveTabId);
- window.location.hash = hashFromTabId(nextActiveTabId);
- return;
- }
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- p.clearActive();
- }
- setActiveTarget(null);
- commitActiveTabId(null);
- window.location.hash = '';
- },
+ closeActiveTabOrWindow,
+ closeTab: closeTabById,
pinTab: (tabId: string) => {
const nextPinnedTabIds = addPinnedTab(pinnedTabIdsRef.current, tabId, openTabsRef.current);
if (sameTabIds(pinnedTabIdsRef.current, nextPinnedTabIds)) return;
@@ -1084,45 +1166,7 @@ export function DocumentProvider({ children }: { children: ReactNode }) {
window.location.hash = '';
}
},
- closeNewTab: (tabId: string) => {
- markTabSessionClosedDuringRestore();
- const currentNewTabIds = newTabIdsRef.current;
- if (!currentNewTabIds.includes(tabId)) return;
- const nextNewTabIds = currentNewTabIds.filter((id) => id !== tabId);
- commitNewTabIds(nextNewTabIds);
- if (activeNewTabIdRef.current !== tabId) return;
-
- const closedIndex = currentNewTabIds.indexOf(tabId);
- const nextNewTabId = nextNewTabIds[closedIndex] ?? nextNewTabIds[closedIndex - 1] ?? null;
- if (nextNewTabId) {
- commitActiveNewTabId(nextNewTabId);
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- p.clearActive();
- }
- setActiveTarget(null);
- commitActiveTabId(null);
- if (window.location.hash !== '') {
- window.location.hash = '';
- }
- return;
- }
-
- commitActiveNewTabId(null);
- const nextActiveTabId = openTabsRef.current[openTabsRef.current.length - 1] ?? null;
- if (nextActiveTabId) {
- commitActiveTabId(nextActiveTabId);
- window.location.hash = hashFromTabId(nextActiveTabId);
- return;
- }
- if (collabUrl !== null) {
- const p = getPool(collabUrl);
- p.clearActive();
- }
- setActiveTarget(null);
- commitActiveTabId(null);
- window.location.hash = '';
- },
+ closeNewTab: closeNewTabById,
closeTabs: (tabIds: readonly string[], options: CloseTabsOptions = {}) => {
const requestedTabIds = tabIds.filter((tabId) => tabId.length > 0);
const closingTabIds = new Set(
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index 44102d17d..6fdd5eb2c 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -121,6 +121,7 @@ type OkMenuAction =
| 'new-project'
| 'rename'
| 'delete'
+ | 'close-active-tab-or-window'
| 'toggle-sidebar'
| 'toggle-source'
| 'save-version'
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index f722a0240..63e83025d 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -21,6 +21,7 @@ type OkMenuAction =
| 'new-project'
| 'rename'
| 'delete'
+ | 'close-active-tab-or-window'
| 'toggle-sidebar'
| 'toggle-source'
| 'save-version'
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 95aef972f..03e92785d 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -1071,6 +1071,7 @@ async function runApplicationMenuRefresh(): Promise<void> {
onRename: () => sendMenuActionToFocused('rename'),
onDuplicate: () => sendMenuActionToFocused('duplicate'),
onMoveToTrash: () => sendMenuActionToFocused('move-to-trash'),
+ onCloseActiveTabOrWindow: () => sendMenuActionToFocused('close-active-tab-or-window'),
onRevealInFinder: () => sendMenuActionToFocused('reveal-in-finder'),
onOpenInTerminal: () => sendMenuActionToFocused('open-in-terminal'),
onSendToAi: () => sendMenuActionToFocused('send-to-ai'),
diff --git a/packages/desktop/src/main/menu.ts b/packages/desktop/src/main/menu.ts
index 4d0da9039..93bff48fc 100644
--- a/packages/desktop/src/main/menu.ts
+++ b/packages/desktop/src/main/menu.ts
@@ -29,6 +29,7 @@ export interface MenuDeps {
onRename?(): void;
onDuplicate?(): void;
onMoveToTrash?(): void;
+ onCloseActiveTabOrWindow?(): void;
onRevealInFinder?(): void;
onOpenInTerminal?(): void;
onSendToAi?(): void;
@@ -238,7 +239,14 @@ export function buildMenuTemplate(deps: MenuDeps): MenuItemConstructorOptions[]
{ type: 'separator' as const },
] satisfies MenuItemConstructorOptions[])
: []),
- isMac ? { role: 'close' } : { role: 'quit' },
+ isMac
+ ? {
+ label: 'Close Tab',
+ accelerator: 'CmdOrCtrl+W',
+ enabled: deps.onCloseActiveTabOrWindow !== undefined,
+ click: () => deps.onCloseActiveTabOrWindow?.(),
+ }
+ : { role: 'quit' },
],
},
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index 11196210e..dd9f07ec9 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -85,6 +85,7 @@ export type OkMenuAction =
| 'new-project'
| 'rename'
| 'delete'
+ | 'close-active-tab-or-window'
| 'toggle-sidebar'
| 'toggle-source'
| 'save-version'
diff --git a/packages/desktop/tests/integration/m1-smoke.test.ts b/packages/desktop/tests/integration/m1-smoke.test.ts
index 80ff26e9a..5c1e52531 100644
--- a/packages/desktop/tests/integration/m1-smoke.test.ts
+++ b/packages/desktop/tests/integration/m1-smoke.test.ts
@@ -384,8 +384,9 @@ describe('M1 smoke', () => {
const { readFileSync } = await import('node:fs');
const extractLiteralUnion = (src: string, typeName: string): Set<string> => {
- const declRegex = new RegExp(`type\\s+${typeName}\\s*=([^;]+);`, 'm');
- const match = src.match(declRegex);
+ const srcWithoutLineComments = src.replace(/\/\/.*$/gm, '');
+ const declRegex = new RegExp(`type\\s+${typeName}\\s*=([\\s\\S]*?);`, 'm');
+ const match = srcWithoutLineComments.match(declRegex);
if (!match?.[1]) return new Set();
const body = match[1];
const literals = body.match(/'([^']+)'/g) ?? [];
@@ -406,6 +407,43 @@ describe('M1 smoke', () => {
expect(desktopMembers).toEqual(appMembers);
});
+ test('M1 invariant: OkMenuAction literal-union drift catcher', async () => {
+ const desktopPath = join(__dirname, '..', '..', 'src', 'shared', 'bridge-contract.ts');
+ const corePath = join(__dirname, '..', '..', '..', 'core', 'src', 'desktop-bridge.ts');
+ const appPath = join(
+ __dirname,
+ '..',
+ '..',
+ '..',
+ 'app',
+ 'src',
+ 'lib',
+ 'desktop-bridge-types.ts',
+ );
+ const { readFileSync } = await import('node:fs');
+
+ const extractLiteralUnion = (src: string, typeName: string): Set<string> => {
+ const srcWithoutComments = src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, '');
+ const declRegex = new RegExp(`type\\s+${typeName}\\s*=([\\s\\S]*?);`, 'm');
+ const match = srcWithoutComments.match(declRegex);
+ if (!match?.[1]) return new Set();
+ const body = match[1];
+ const literals = body.match(/'([^']+)'/g) ?? [];
+ return new Set(literals.map((l) => l.slice(1, -1)));
+ };
+
+ const desktopMembers = extractLiteralUnion(readFileSync(desktopPath, 'utf-8'), 'OkMenuAction');
+ const coreMembers = extractLiteralUnion(readFileSync(corePath, 'utf-8'), 'OkMenuAction');
+ const appMembers = extractLiteralUnion(readFileSync(appPath, 'utf-8'), 'OkMenuAction');
+
+ expect(desktopMembers.size).toBeGreaterThan(0);
+ expect(coreMembers.size).toBeGreaterThan(0);
+ expect(appMembers.size).toBeGreaterThan(0);
+ expect(desktopMembers.size).toBe(25);
+ expect(desktopMembers).toEqual(coreMembers);
+ expect(desktopMembers).toEqual(appMembers);
+ });
+
test('M1 invariant: EntryPoint / OkProjectEntryPoint literal-union drift catcher', async () => {
const desktopPath = join(__dirname, '..', '..', 'src', 'shared', 'entry-point.ts');
const corePath = join(__dirname, '..', '..', '..', 'core', 'src', 'desktop-bridge.ts');
diff --git a/packages/desktop/tests/main/menu.test.ts b/packages/desktop/tests/main/menu.test.ts
index 9feced34d..53b0c5c16 100644
--- a/packages/desktop/tests/main/menu.test.ts
+++ b/packages/desktop/tests/main/menu.test.ts
@@ -329,13 +329,19 @@ describe('buildMenuTemplate', () => {
});
});
- test('macOS-branch behavior for the current test host', () => {
+ test('File close item follows the current test host branch', () => {
const template = buildMenuTemplate(makeDeps());
const file = findByLabel(template, 'File');
const fileSub = file?.submenu as MenuItemConstructorOptions[] | undefined;
const last = fileSub?.[fileSub.length - 1];
expect(last).toBeDefined();
- expect(['close', 'quit']).toContain(last?.role);
+ if (process.platform === 'darwin') {
+ expect(last?.label).toBe('Close Tab');
+ expect(last?.accelerator).toBe('CmdOrCtrl+W');
+ expect(last?.role).toBeUndefined();
+ } else {
+ expect(last?.role).toBe('quit');
+ }
const windowMenu = findByLabel(template, 'Window');
const windowSub = windowMenu?.submenu as MenuItemConstructorOptions[] | undefined;
@@ -348,6 +354,16 @@ describe('buildMenuTemplate', () => {
expect(isMacBranch || isOtherBranch).toBe(true);
expect(roles).toContain('minimize');
});
+
+ test('Close Tab click dispatches deps.onCloseActiveTabOrWindow on macOS', () => {
+ if (process.platform !== 'darwin') return;
+ const onCloseActiveTabOrWindow = mock(() => {});
+ const template = buildMenuTemplate(makeDeps({ onCloseActiveTabOrWindow }));
+ const closeTab = findByLabel(template, 'Close Tab');
+ expect(closeTab?.enabled).toBe(true);
+ (closeTab?.click as (() => void) | undefined)?.();
+ expect(onCloseActiveTabOrWindow).toHaveBeenCalledTimes(1);
+ });
});
describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR19)', () => {
@@ -475,6 +491,9 @@ describe('buildMenuTemplate — File menu state-aware items (US-020 / FR16 + FR1
expect(findByLabel(template, 'Open in Terminal')?.enabled).toBe(false);
expect(findByLabel(template, 'Open with AI')?.enabled).toBe(false);
expect(findByLabel(template, 'Copy Path')?.enabled).toBe(false);
+ if (process.platform === 'darwin') {
+ expect(findByLabel(template, 'Close Tab')?.enabled).toBe(false);
+ }
});
test('Copy Path submenu renders Full Path + Relative Path (FR9 parity with sidebar)', () => {