Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(app): stop global shortcuts firing under an open overlay (#2996)

Andrew Mikofalvye53eeeb71bd2
diff --git a/.changeset/overlay-global-shortcut-gate.md b/.changeset/overlay-global-shortcut-gate.md
new file mode 100644
index 000000000..f2b25ddea
--- /dev/null
+++ b/.changeset/overlay-global-shortcut-gate.md
@@ -0,0 +1,7 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Keyboard shortcuts no longer fire underneath an open dialog, command palette, or menu. Pressing ⌘T with the ⌘K palette up opened a new editor tab behind it, and the same leak affected ⇧⌘T, ⌃Tab, ⌘1–⌘9, ⌘L, ⇧⌘J, ⌘F, ⌘G, ⌘Z and ⌘⇧I — these are registered on the window, most of them in capture phase, so an overlay had no way to stop them from underneath. Every app-global shortcut now declines while a layer that owns the keyboard is open. Escape likewise dismisses only the topmost layer instead of also collapsing the graph panel or closing a diff pane behind it, and ⌘K no longer stacks the palette on top of another dialog while still dismissing the palette when it is the top layer. Editing keys the app never claimed — copy, paste, cut, select-all, undo, and arrow/Enter navigation inside the overlay — are untouched, and a hover-opened link panel no longer counts as owning the keyboard, so shortcuts keep working while the pointer rests on a link.
+
+On the desktop app, ⌘N, ⌘,, ⌥⌘S, ⌥⌘B and ⌘J arrive as native menu accelerators rather than as renderer key presses, so they can still fire while an overlay is open; those five are fixed in the browser only.
diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsx
index 86c1aed9d..22e679431 100644
--- a/packages/app/src/App.tsx
+++ b/packages/app/src/App.tsx
@@ -49,6 +49,7 @@ import {
skillFileFromHash,
} from '@/lib/doc-hash';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { mark, ProfilerBoundary } from '@/lib/perf';
import { SingleFileModeProvider, useSingleFileMode } from '@/lib/single-file-mode';
import { useServerKeepalive } from '@/lib/use-server-keepalive';
@@ -348,6 +349,7 @@ function InstallInClaudeDesktopTrigger() {
function SettingsShortcutHandler() {
useEffect(() => {
function onKeyDown(e: KeyboardEvent) {
+ if (isOverlayLayerOpen()) return;
const target = e.target as { tagName?: string; isContentEditable?: boolean } | null;
if (
isSettingsShortcut({
@@ -436,6 +438,7 @@ function NewItemShortcutHandler() {
useEffect(() => {
function onKeyDown(e: KeyboardEvent) {
+ if (isOverlayLayerOpen()) return;
// KeyboardEvent.target is EventTarget|null — widen to the duck-typed
// ShortcutEventLike shape used by the pure predicate.
const target = e.target as { tagName?: string; isContentEditable?: boolean } | null;
diff --git a/packages/app/src/components/AgentDiffPane.overlay-gate.dom.test.tsx b/packages/app/src/components/AgentDiffPane.overlay-gate.dom.test.tsx
new file mode 100644
index 000000000..307492854
--- /dev/null
+++ b/packages/app/src/components/AgentDiffPane.overlay-gate.dom.test.tsx
@@ -0,0 +1,159 @@
+/**
+ * RTL behavior tests for the AgentDiffPane keyboard gate.
+ *
+ * This pane is the one guarded listener that stays on BUBBLE phase, so it
+ * carries two arms the capture-phase sites do not need, and neither is
+ * exercised anywhere else:
+ *
+ * - `event.defaultPrevented` covers Escape. A dismissable layer claims Escape
+ * from a capture-phase listener on `document`, which also flips its
+ * `data-state` before this bubble-phase handler runs — so by then the layer
+ * probe alone reads "nothing open" and the pane would close out from under
+ * the dialog the user was dismissing.
+ * - the layer probe covers the review chords (j / k / ← / →), which no layer
+ * cancels.
+ *
+ * The overlay is a REAL Radix Dialog rather than a stub, because the
+ * `defaultPrevented` arm is a claim about what Radix's DismissableLayer
+ * actually does to the event.
+ *
+ * Substrate: jsdom via `pnpm run test:dom`.
+ */
+
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
+import { TooltipProvider } from '@/components/ui/tooltip';
+import { renderLinguiTemplate } from '@/test-utils/lingui-mock';
+
+const closeAgentDiff = vi.fn(() => {});
+const setAgentDiffKept = vi.fn(() => {});
+
+import * as actualLinguiMacro from '@lingui/react/macro';
+
+vi.doMock('@lingui/react/macro', () => ({
+ ...actualLinguiMacro,
+ Trans: ({ children }: { children?: ReactNode }) => <>{children}</>,
+ useLingui: () => ({ t: renderLinguiTemplate }),
+}));
+
+vi.doMock('@/lib/agent-diff-store', () => ({
+ closeAgentDiff,
+ setAgentDiffKept,
+}));
+
+vi.doMock('@/lib/use-activity-panel', () => ({
+ fetchAgentBurstDiff: () => Promise.resolve({ diff: '', before: '', after: '' }),
+}));
+
+const view = {
+ agentId: 'agent-1',
+ agentName: 'Agent',
+ agentColor: '#888888',
+ docName: 'docs/team/spec',
+ keptCount: 1,
+ maxVersions: 3,
+};
+
+async function renderPane({ withOverlay }: { withOverlay: boolean }) {
+ const { AgentDiffPane } = await import('./AgentDiffPane');
+ const { Dialog, DialogContent, DialogDescription, DialogTitle } = await import(
+ '@/components/ui/dialog'
+ );
+ render(
+ <TooltipProvider>
+ <AgentDiffPane view={view} isPanelCollapsed={false} onTogglePanel={() => {}} />
+ {withOverlay ? (
+ <Dialog open>
+ <DialogContent>
+ <DialogTitle>Command palette</DialogTitle>
+ <DialogDescription>Search files and commands</DialogDescription>
+ </DialogContent>
+ </Dialog>
+ ) : null}
+ </TooltipProvider>,
+ );
+ if (withOverlay) {
+ await waitFor(() => expect(screen.getByRole('dialog')).not.toBeNull());
+ }
+}
+
+function press(key: string) {
+ act(() => {
+ fireEvent.keyDown(document.body, { key });
+ });
+}
+
+describe('AgentDiffPane keyboard gate', () => {
+ beforeEach(() => {
+ closeAgentDiff.mockClear();
+ setAgentDiffKept.mockClear();
+ });
+
+ afterEach(cleanup);
+
+ test('Escape closes the pane with no overlay open', async () => {
+ await renderPane({ withOverlay: false });
+
+ press('Escape');
+
+ expect(closeAgentDiff).toHaveBeenCalledTimes(1);
+ });
+
+ test('Escape does not close the pane while a dialog owns the keyboard', async () => {
+ await renderPane({ withOverlay: true });
+
+ press('Escape');
+
+ expect(closeAgentDiff).not.toHaveBeenCalled();
+ });
+
+ test('Escape already claimed by a dismissed layer does not also close the pane', async () => {
+ // jsdom dispatches synchronously, so a real Radix layer is still in the DOM
+ // when this bubble-phase handler runs and the layer probe alone would cover
+ // it. A real browser runs a microtask checkpoint between listeners, so React
+ // has already unmounted the layer by then and the probe reads "nothing
+ // open" — leaving `defaultPrevented` as the only thing standing between the
+ // user and a pane that closes out from under the dialog they dismissed.
+ // Reproduce that end state: cancelled Escape, no layer left in the DOM.
+ await renderPane({ withOverlay: false });
+
+ const claimEscape = (event: Event) => {
+ if ((event as KeyboardEvent).key === 'Escape') event.preventDefault();
+ };
+ document.addEventListener('keydown', claimEscape, { capture: true });
+
+ try {
+ press('Escape');
+ } finally {
+ document.removeEventListener('keydown', claimEscape, { capture: true });
+ }
+
+ expect(closeAgentDiff).not.toHaveBeenCalled();
+ });
+
+ test('j steps the version with no overlay open', async () => {
+ await renderPane({ withOverlay: false });
+
+ press('j');
+
+ expect(setAgentDiffKept).toHaveBeenCalledWith(2);
+ });
+
+ test('j and ArrowRight do not step the version while a dialog is open', async () => {
+ await renderPane({ withOverlay: true });
+
+ press('j');
+ press('ArrowRight');
+
+ expect(setAgentDiffKept).not.toHaveBeenCalled();
+ });
+
+ test('k does not step the version while a dialog is open', async () => {
+ await renderPane({ withOverlay: true });
+
+ press('k');
+
+ expect(setAgentDiffKept).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/app/src/components/AgentDiffPane.tsx b/packages/app/src/components/AgentDiffPane.tsx
index 2b647a5e2..6e7d925a3 100644
--- a/packages/app/src/components/AgentDiffPane.tsx
+++ b/packages/app/src/components/AgentDiffPane.tsx
@@ -22,6 +22,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
import { type AgentDiffView, closeAgentDiff, setAgentDiffKept } from '@/lib/agent-diff-store';
import { collectChangeAnchors } from '@/lib/diff-change-nav';
import { LruStringCache } from '@/lib/lru-string-cache';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { RENDERED_DIFF_CHANGE_SELECTOR } from '@/lib/rendered-diff/diff-decorations';
import { fetchAgentBurstDiff } from '@/lib/use-activity-panel';
import { countDiffStat } from '@/lib/use-timeline-entry-diff';
@@ -158,11 +159,30 @@ export function AgentDiffPane({ view, isPanelCollapsed, onTogglePanel }: AgentDi
};
}, [diffKey]);
- // Keyboard: Esc closes; J/K (or ←/→) step through versions.
+ // Keyboard: Esc closes; J/K (or ←/→) step through versions. Bubble phase is
+ // sufficient here — nothing this handler does needs to observe the DOM ahead
+ // of a dismissable layer, because Escape arrives already cancelled.
useEffect(() => {
const onKey = (e: KeyboardEvent): void => {
+ // A layer above the pane owns the keyboard: Escape belongs to it, and the
+ // review chords must not step its arrow-key navigation. `defaultPrevented`
+ // is what covers Escape — a dismissable layer cancels it from a
+ // capture-phase listener on `document`, and that same listener has already
+ // flipped `data-state` by the time this bubble-phase handler runs. Scoped
+ // to Escape: the editor cancels ←/→ in its own gap-cursor and node-view
+ // paths, and those must not silently disable version stepping.
+ if (e.key === 'Escape' && e.defaultPrevented) return;
+ if (isOverlayLayerOpen()) return;
+ // The editor stays mounted and live behind the pane, so a text surface
+ // with the caret in it keeps its own letters — `preventDefault` on "j"
+ // cancels the insertion no matter which phase this handler runs in.
const target = e.target as HTMLElement | null;
- if (target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA')) return;
+ if (
+ target &&
+ (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable)
+ ) {
+ return;
+ }
if (e.key === 'Escape') {
closeAgentDiff();
} else if (e.key === 'j' || e.key === 'ArrowRight') {
diff --git a/packages/app/src/components/BottomComposer.dom.test.tsx b/packages/app/src/components/BottomComposer.dom.test.tsx
index 6fadf6a43..98058d797 100644
--- a/packages/app/src/components/BottomComposer.dom.test.tsx
+++ b/packages/app/src/components/BottomComposer.dom.test.tsx
@@ -1362,3 +1362,64 @@ describe('BottomComposer (failure + defensive guards)', () => {
await waitFor(() => expect(dispatchCalls).toHaveLength(1));
});
});
+
+/**
+ * ⌘L is registered capture-phase on `window`, so it also outruns anything an
+ * overlay installs. `defaultPrevented` is the load-bearing signal here: the
+ * handler cancels the keystroke before emitting, so an uncancelled ⌘L proves
+ * the handler declined rather than proving the focus trap bounced it back.
+ */
+describe('BottomComposer ⌘L — overlay gate', () => {
+ function askAiEvent() {
+ const meta = new KeyboardEvent('keydown', {
+ key: 'l',
+ metaKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ return matchesKeyboardShortcut(meta, 'open-ask-ai')
+ ? meta
+ : new KeyboardEvent('keydown', { key: 'l', ctrlKey: true, bubbles: true, cancelable: true });
+ }
+
+ test('claims ⌘L with no overlay open', async () => {
+ await renderComposer();
+
+ const event = askAiEvent();
+ act(() => {
+ document.body.dispatchEvent(event);
+ });
+
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ test('declines ⌘L while an overlay owns the keyboard', async () => {
+ enableInstalledDesktopTargets();
+ const { BottomComposer } = await import('./BottomComposer');
+ const { Dialog, DialogContent, DialogDescription, DialogTitle } = await import(
+ '@/components/ui/dialog'
+ );
+ render(
+ <>
+ <BottomComposer docName="notes" surface="wysiwyg" />
+ <Dialog open>
+ <DialogContent>
+ <DialogTitle>Command palette</DialogTitle>
+ <DialogDescription>Search files and commands</DialogDescription>
+ </DialogContent>
+ </Dialog>
+ </>,
+ );
+ await waitFor(() => expect(screen.getByRole('dialog')).not.toBeNull());
+ const composerInput = document.querySelector('textarea');
+ expect(composerInput).not.toBeNull();
+
+ const event = askAiEvent();
+ act(() => {
+ document.body.dispatchEvent(event);
+ });
+
+ expect(event.defaultPrevented).toBe(false);
+ expect(document.activeElement).not.toBe(composerInput);
+ });
+});
diff --git a/packages/app/src/components/BottomComposer.tsx b/packages/app/src/components/BottomComposer.tsx
index 8e3939c72..bd3424531 100644
--- a/packages/app/src/components/BottomComposer.tsx
+++ b/packages/app/src/components/BottomComposer.tsx
@@ -74,6 +74,7 @@ import {
import { VISIBLE_TARGETS } from '@/lib/handoff/targets';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
import { recordOnboardingAskedAi } from '@/lib/onboarding-signals';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import {
IN_APP_THREAD_ID,
loadStickyAgent,
@@ -381,6 +382,7 @@ export function BottomComposer({
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
if (!matchesKeyboardShortcut(event, 'open-ask-ai')) return;
+ if (isOverlayLayerOpen()) return;
// Don't hijack ⌘L when the caret is in a native form field (rename input,
// search box, …) — only swallow it for the editor body / global context.
if (isNativeTextControl(event.target)) return;
diff --git a/packages/app/src/components/CloneDialog.tsx b/packages/app/src/components/CloneDialog.tsx
index 721cbb276..e66684b75 100644
--- a/packages/app/src/components/CloneDialog.tsx
+++ b/packages/app/src/components/CloneDialog.tsx
@@ -480,6 +480,7 @@ export function CloneDialog({
// Keep focus in the input — the list is a passive suggestion
// surface, not a focus target. And don't let a pointer-down on
// the input itself (the anchor) count as an outside-click close.
+ data-ok-declines-keyboard=""
onOpenAutoFocus={(e) => e.preventDefault()}
onCloseAutoFocus={(e) => e.preventDefault()}
onInteractOutside={(e) => {
diff --git a/packages/app/src/components/CommandPalette.dom.test.tsx b/packages/app/src/components/CommandPalette.dom.test.tsx
index b5a4e10bb..f932d6cbd 100644
--- a/packages/app/src/components/CommandPalette.dom.test.tsx
+++ b/packages/app/src/components/CommandPalette.dom.test.tsx
@@ -1278,3 +1278,71 @@ describe('Cmd+K menu-parity backfill', () => {
expect(screen.queryByTestId('command-palette-new-terminal')).toBeNull();
});
});
+
+/**
+ * ⌘K is a toggle, so its gate is asymmetric: any other open layer owns the
+ * keyboard and must keep the palette from stacking on top of it, but once the
+ * palette is up it IS the top layer and ⌘K has to keep dismissing it.
+ */
+describe('CommandPalette ⌘K — overlay gate', () => {
+ beforeEach(() => {
+ cleanup();
+ activeDocName = 'docs/active';
+ activeTarget = { kind: 'doc', docName: 'docs/active' };
+ pageListLoading = false;
+ commandDialogProps = [];
+ window.location.hash = '';
+ globalThis.fetch = vi.fn(() =>
+ Promise.resolve(new Response(JSON.stringify({ results: [] }), { status: 200 })),
+ ) as never;
+ });
+
+ function pressCommandK() {
+ fireEvent.keyDown(document.body, { key: 'k', metaKey: true });
+ fireEvent.keyDown(document.body, { key: 'k', ctrlKey: true });
+ }
+
+ test('closes itself on ⌘K while it is the open layer', async () => {
+ const { onOpenChange } = await renderPalette({ bridge: createBridge() });
+
+ pressCommandK();
+
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ });
+
+ test('does not open on ⌘K while another dialog owns the keyboard', async () => {
+ const { Dialog, DialogContent, DialogDescription, DialogTitle } = await import(
+ '@/components/ui/dialog'
+ );
+ const { CommandPalette } = await import('./CommandPalette');
+ const onOpenChange = vi.fn(() => {});
+ render(
+ <>
+ <CommandPalette bridge={createBridge() as never} open={false} onOpenChange={onOpenChange} />
+ <Dialog open>
+ <DialogContent>
+ <DialogTitle>Settings</DialogTitle>
+ <DialogDescription>Settings body</DialogDescription>
+ </DialogContent>
+ </Dialog>
+ </>,
+ );
+ await waitFor(() => expect(screen.getByRole('dialog')).not.toBeNull());
+
+ pressCommandK();
+
+ expect(onOpenChange).not.toHaveBeenCalled();
+ });
+
+ test('opens on ⌘K with nothing else open', async () => {
+ const { CommandPalette } = await import('./CommandPalette');
+ const onOpenChange = vi.fn(() => {});
+ render(
+ <CommandPalette bridge={createBridge() as never} open={false} onOpenChange={onOpenChange} />,
+ );
+
+ pressCommandK();
+
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ });
+});
diff --git a/packages/app/src/components/CommandPalette.tsx b/packages/app/src/components/CommandPalette.tsx
index 7b7de8193..c398bb88e 100644
--- a/packages/app/src/components/CommandPalette.tsx
+++ b/packages/app/src/components/CommandPalette.tsx
@@ -90,6 +90,7 @@ import {
matchesKeyboardShortcut,
} from '@/lib/keyboard-shortcuts';
import { emitLocalMenuAction } from '@/lib/local-menu-action-bus';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { useSingleFileMode } from '@/lib/single-file-mode';
import { useWorkspace } from '@/lib/use-workspace';
import { cn } from '@/lib/utils.ts';
@@ -466,6 +467,11 @@ export function CommandPalette({ bridge = null, open, onOpenChange }: CommandPal
function onKey(e: KeyboardEvent) {
const isTrigger = matchesKeyboardShortcut(e, 'command-palette');
if (!isTrigger) return;
+ // Asymmetric gate, because ⌘K is a toggle: while the palette is up it IS
+ // the top layer and the chord has to keep dismissing it, but while it is
+ // closed any other open layer owns the keyboard and the palette must not
+ // stack on top of it.
+ if (!open && isOverlayLayerOpen()) return;
e.preventDefault();
onOpenChange(!open);
}
diff --git a/packages/app/src/components/EditorArea.tsx b/packages/app/src/components/EditorArea.tsx
index b9a700720..6002494b4 100644
--- a/packages/app/src/components/EditorArea.tsx
+++ b/packages/app/src/components/EditorArea.tsx
@@ -46,6 +46,7 @@ import { docNameFromHash, hashFromDocName } from '@/lib/doc-hash';
import { getInitialDocPanelWidth, writeDocPanelWidth } from '@/lib/doc-panel-width-store';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { ProfilerBoundary } from '@/lib/perf';
import {
matchesShareReceiveMiss,
@@ -794,10 +795,10 @@ function EditorAreaInner({
useEffect(() => {
if (window.okDesktop != null) return;
const handleKeyDown = (event: KeyboardEvent) => {
- if (matchesKeyboardShortcut(event, 'toggle-document-panel')) {
- event.preventDefault();
- togglePanel();
- }
+ if (!matchesKeyboardShortcut(event, 'toggle-document-panel')) return;
+ if (isOverlayLayerOpen()) return;
+ event.preventDefault();
+ togglePanel();
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
diff --git a/packages/app/src/components/EditorPane.tsx b/packages/app/src/components/EditorPane.tsx
index c50508ed3..2b8f4b1a7 100644
--- a/packages/app/src/components/EditorPane.tsx
+++ b/packages/app/src/components/EditorPane.tsx
@@ -14,6 +14,7 @@ import { useWorktreeAutoSyncNotice } from '@/hooks/use-worktree-autosync-notice'
import { useConfigContext } from '@/lib/config-provider';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import {
getInitialTerminalDock,
type TerminalDockPosition,
@@ -296,11 +297,11 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
useEffect(() => {
if (window.okDesktop != null) return;
function handleKeyDown(event: KeyboardEvent) {
- if (matchesKeyboardShortcut(event, 'toggle-terminal-panel')) {
- event.preventDefault();
- if (sendSelectionToTerminalEvent(false)) return;
- setTerminalVisible((visible) => !visible);
- }
+ if (!matchesKeyboardShortcut(event, 'toggle-terminal-panel')) return;
+ if (isOverlayLayerOpen()) return;
+ event.preventDefault();
+ if (sendSelectionToTerminalEvent(false)) return;
+ setTerminalVisible((visible) => !visible);
}
// Capture phase so a focused xterm textarea can't swallow ⌘J first.
window.addEventListener('keydown', handleKeyDown, { capture: true });
@@ -318,6 +319,7 @@ export function EditorPane({ onOpenSearch }: EditorPaneProps = {}) {
if (!terminalAvailable) return;
function handleKeyDown(event: KeyboardEvent) {
if (!matchesKeyboardShortcut(event, 'new-terminal-tab')) return;
+ if (isOverlayLayerOpen()) return;
event.preventDefault();
if (!sendSelectionToTerminalEvent(true)) launchNewChatEvent();
}
diff --git a/packages/app/src/components/EditorTabs.dom.test.tsx b/packages/app/src/components/EditorTabs.dom.test.tsx
index 1611c7d2c..4dcd047c5 100644
--- a/packages/app/src/components/EditorTabs.dom.test.tsx
+++ b/packages/app/src/components/EditorTabs.dom.test.tsx
@@ -722,3 +722,141 @@ describe('EditorTabs runtime behavior', () => {
]);
});
});
+
+/**
+ * The tab chords are registered capture-phase on `window`, so they run before
+ * anything an overlay could install — an open command palette or dialog cannot
+ * stop them from underneath and the listener has to decline for itself.
+ *
+ * Each suppression case is paired with the same chord fired without an overlay,
+ * so a test that goes green because the shortcut stopped working outright is
+ * distinguishable from one that goes green because the gate works.
+ *
+ * Keys the app never claims (⌘C/⌘V/⌘X/⌘A/⌘Z) are pinned as untouched while an
+ * overlay is up: the gate must decline these chords, not swallow the whole
+ * keyboard, or pasting into the palette's own search field breaks.
+ */
+describe('EditorTabs global chords — overlay gate', () => {
+ beforeEach(() => {
+ resetState();
+ });
+
+ afterEach(() => {
+ cleanup();
+ });
+
+ async function renderTabsUnderOverlay() {
+ const { EditorTabs } = await import('./EditorTabs');
+ const { Dialog, DialogContent, DialogDescription, DialogTitle } = await import(
+ '@/components/ui/dialog'
+ );
+ const view = render(
+ <TooltipProvider>
+ <EditorTabs />
+ <Dialog open>
+ <DialogContent>
+ <DialogTitle>Command palette</DialogTitle>
+ <DialogDescription>Search files and commands</DialogDescription>
+ </DialogContent>
+ </Dialog>
+ </TooltipProvider>,
+ );
+ await waitFor(() => expect(screen.getByRole('dialog')).not.toBeNull());
+ return view;
+ }
+
+ function press(init: KeyboardEventInit): boolean {
+ let notPrevented = true;
+ act(() => {
+ notPrevented = fireEvent.keyDown(document.body, init);
+ });
+ return notPrevented;
+ }
+
+ const newTab = () => ({ key: 't', ...primaryShortcutModifier() });
+ const reopenClosed = () => ({ key: 't', shiftKey: true, ...primaryShortcutModifier() });
+ const jumpToFirst = () => ({ key: '1', ...primaryShortcutModifier() });
+ const nextTab = () => ({ key: 'Tab', ctrlKey: true });
+
+ test('⌘T opens a tab with no overlay, and does not while one is open', async () => {
+ await renderEditorTabs();
+ press(newTab());
+ expect(openNewTab).toHaveBeenCalledTimes(1);
+
+ cleanup();
+ resetState();
+
+ await renderTabsUnderOverlay();
+ press(newTab());
+ expect(openNewTab).not.toHaveBeenCalled();
+ });
+
+ test('⇧⌘T reopens a closed tab with no overlay, and does not while one is open', async () => {
+ await renderEditorTabs();
+ press(reopenClosed());
+ expect(reopenClosedTab).toHaveBeenCalledTimes(1);
+
+ cleanup();
+ resetState();
+
+ await renderTabsUnderOverlay();
+ press(reopenClosed());
+ expect(reopenClosedTab).not.toHaveBeenCalled();
+ });
+
+ test('⌘1 jumps to a tab with no overlay, and does not while one is open', async () => {
+ await renderEditorTabs();
+ press(jumpToFirst());
+ expect(activateTab).toHaveBeenCalledTimes(1);
+
+ cleanup();
+ resetState();
+
+ await renderTabsUnderOverlay();
+ press(jumpToFirst());
+ expect(activateTab).not.toHaveBeenCalled();
+ });
+
+ test('⌃Tab cycles tabs with no overlay, and does not while one is open', async () => {
+ await renderEditorTabs();
+ press(nextTab());
+ expect(activateTab).toHaveBeenCalledTimes(1);
+
+ cleanup();
+ resetState();
+
+ await renderTabsUnderOverlay();
+ press(nextTab());
+ expect(activateTab).not.toHaveBeenCalled();
+ });
+
+ test('leaves unclaimed chords alone while an overlay is open', async () => {
+ await renderTabsUnderOverlay();
+
+ const seen: string[] = [];
+ const spy = (event: Event) => seen.push((event as KeyboardEvent).key);
+ document.addEventListener('keydown', spy);
+
+ try {
+ // Clipboard, select-all, and undo/redo have to reach the overlay's own
+ // input, so nothing may cancel them.
+ for (const key of ['c', 'v', 'x', 'a', 'z']) {
+ expect(press({ key, ...primaryShortcutModifier() })).toBe(true);
+ }
+ expect(press({ key: 'z', shiftKey: true, ...primaryShortcutModifier() })).toBe(true);
+ for (const key of ['ArrowDown', 'ArrowUp', 'Enter']) {
+ expect(press({ key })).toBe(true);
+ }
+ // Escape is cancelled by the dialog itself (that is the dismiss); the
+ // property under test is only that it still reaches every listener.
+ press({ key: 'Escape' });
+ } finally {
+ document.removeEventListener('keydown', spy);
+ }
+
+ expect(seen).toEqual(['c', 'v', 'x', 'a', 'z', 'z', 'ArrowDown', 'ArrowUp', 'Enter', 'Escape']);
+ expect(openNewTab).not.toHaveBeenCalled();
+ expect(activateTab).not.toHaveBeenCalled();
+ expect(reopenClosedTab).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/app/src/components/EditorTabs.tsx b/packages/app/src/components/EditorTabs.tsx
index 6e386befc..ac5384746 100644
--- a/packages/app/src/components/EditorTabs.tsx
+++ b/packages/app/src/components/EditorTabs.tsx
@@ -61,6 +61,7 @@ import { useLifecycleStatus } from '@/hooks/use-lifecycle-status';
import { hashFromDocName } from '@/lib/doc-hash';
import { emitDocumentsChanged } from '@/lib/documents-events';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { parseServerResponse, parseSuccessOrWarn } from '@/lib/parse-server-response';
import { cn } from '@/lib/utils';
import {
@@ -762,7 +763,13 @@ export function EditorTabs() {
}
function onKeyDown(event: globalThis.KeyboardEvent) {
- if (hasTabShortcutModifier(event)) scheduleTabShortcutHintReveal();
+ // Every branch below needs the modifier, so bail on it first — this runs on
+ // every keystroke in the app, and the overlay probe queries the DOM.
+ if (!hasTabShortcutModifier(event)) return;
+ // Capture phase on `window` outruns anything an overlay installs, so an
+ // open palette / dialog / menu cannot stop these chords from underneath.
+ if (isOverlayLayerOpen()) return;
+ scheduleTabShortcutHintReveal();
if (matchesKeyboardShortcut(event, 'tab-new')) {
event.preventDefault();
diff --git a/packages/app/src/components/FileTree.tsx b/packages/app/src/components/FileTree.tsx
index 52c4fedb0..943c5d016 100644
--- a/packages/app/src/components/FileTree.tsx
+++ b/packages/app/src/components/FileTree.tsx
@@ -213,6 +213,7 @@ import {
subscribeToFileTreeMenuActionRename,
} from '@/lib/file-tree-menu-action-events';
import { importTemplate } from '@/lib/folder-config-api';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { parseServerResponse, parseSuccessOrWarn } from '@/lib/parse-server-response';
import { createRefreshScheduler } from '@/lib/refresh-scheduler';
import { getRelaunchInFlightSnapshot, useRelaunchInFlight } from '@/lib/relaunch-store';
@@ -3133,6 +3134,10 @@ export function FileTree({
let disposed = false;
const handleCommitKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Enter') return;
+ // Unlike its sibling below, this listener has no focus gate — the
+ // pending placeholder is its only condition, so an Enter pressed in a
+ // layer above would otherwise commit it.
+ if (isOverlayLayerOpen()) return;
const pending = pendingCreateRef.current;
if (!pending || pending.renamePath !== placeholder.renamePath) return;
queueMicrotask(() => clearPendingCreate(pending));
diff --git a/packages/app/src/components/GraphPanel.tsx b/packages/app/src/components/GraphPanel.tsx
index 69fad6c14..58b44837f 100644
--- a/packages/app/src/components/GraphPanel.tsx
+++ b/packages/app/src/components/GraphPanel.tsx
@@ -43,6 +43,7 @@ import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { hashFromDocName } from '@/lib/doc-hash';
import { openExternalUrl } from '@/lib/external-link';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { cn } from '@/lib/utils';
const FULLSCREEN_HUB_LIMIT = 50;
@@ -313,11 +314,17 @@ export function GraphPanel({ activeDocName }: { activeDocName: string }) {
useEffect(() => {
if (!isExpanded) return;
+ // Capture phase on `window` so the open-layer probe runs before Radix's
+ // DismissableLayer (capture phase on `document`) flips `data-state` —
+ // otherwise Escape collapses the graph out from under the layer it was
+ // meant to dismiss.
const onKeyDown = (e: KeyboardEvent) => {
- if (e.key === 'Escape') setIsExpanded(false);
+ if (e.key !== 'Escape') return;
+ if (isOverlayLayerOpen()) return;
+ setIsExpanded(false);
};
- document.addEventListener('keydown', onKeyDown);
- return () => document.removeEventListener('keydown', onKeyDown);
+ window.addEventListener('keydown', onKeyDown, { capture: true });
+ return () => window.removeEventListener('keydown', onKeyDown, { capture: true });
}, [isExpanded]);
useEffect(() => {
diff --git a/packages/app/src/components/InteractionPropPanel.tsx b/packages/app/src/components/InteractionPropPanel.tsx
index 426a050bb..9cd6b76c4 100644
--- a/packages/app/src/components/InteractionPropPanel.tsx
+++ b/packages/app/src/components/InteractionPropPanel.tsx
@@ -124,6 +124,9 @@ export const InteractionPropPanel: FC<InteractionPropPanelProps> = ({
collisionPadding={8}
aria-label={ariaLabel}
data-ok-prop-panel={kind}
+ // Hover-opened and focus-declining: the caret stays in the document,
+ // so this panel must not count as owning app-global shortcuts.
+ data-ok-declines-keyboard=""
data-slot={dataSlot}
// Hover-triggered open should NOT pull focus out of the editor — the
// chip stays the active tabstop. Keyboard Tab into popover content
diff --git a/packages/app/src/components/MermaidDocEditor.tsx b/packages/app/src/components/MermaidDocEditor.tsx
index 2633c422d..3c4e3f77e 100644
--- a/packages/app/src/components/MermaidDocEditor.tsx
+++ b/packages/app/src/components/MermaidDocEditor.tsx
@@ -34,6 +34,7 @@ import { yCollab } from 'y-codemirror.next';
import * as Y from 'yjs';
import { propEditorHighlight } from '@/editor/components/CodeMirrorPropInput';
import { type MermaidSourceBinding, MermaidView } from '@/editor/components/Mermaid';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
const darkTheme = basicDarkInit({
settings: { background: 'var(--background)', gutterBackground: 'var(--muted)' },
@@ -173,6 +174,8 @@ export function MermaidDocEditor({
const onKey = (e: KeyboardEvent) => {
const mod = e.metaKey || e.ctrlKey;
if (!mod || e.key.toLowerCase() !== 'z') return;
+ // Undo belongs to whatever layer sits above the diagram.
+ if (isOverlayLayerOpen()) return;
// If the user is typing in an input overlay (label editor) or any
// contenteditable, let the platform undo handle that input instead.
const target = e.target;
diff --git a/packages/app/src/components/TerminalSessionsHost.tsx b/packages/app/src/components/TerminalSessionsHost.tsx
index e94b192de..87795da94 100644
--- a/packages/app/src/components/TerminalSessionsHost.tsx
+++ b/packages/app/src/components/TerminalSessionsHost.tsx
@@ -43,6 +43,7 @@ import {
} from '@/lib/dock-session-persistence';
import { subscribeLocalMenuAction } from '@/lib/local-menu-action-bus';
import type { NewSessionChoice } from '@/lib/new-session-choice';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import type { TerminalDockPosition } from '@/lib/terminal-dock-store';
import {
getInitialPreferBareTerminal,
@@ -1081,6 +1082,9 @@ export function TerminalSessionsHost({
if (!event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;
if (!/^[1-9]$/.test(event.key)) return;
if (!chordTargetsHost(hostEl, variant)) return;
+ // `chordTargetsHost` short-circuits to true in the dedicated terminal
+ // window, so focus alone does not gate this there.
+ if (isOverlayLayerOpen()) return;
const target = sessionsRef.current[Number(event.key) - 1];
if (target == null) return;
event.preventDefault();
@@ -1099,6 +1103,7 @@ export function TerminalSessionsHost({
const direction = event.key === 'ArrowLeft' ? -1 : event.key === 'ArrowRight' ? 1 : 0;
if (direction === 0) return;
if (!chordTargetsHost(hostEl, variant)) return;
+ if (isOverlayLayerOpen()) return;
if (dragActiveRef.current) return;
const target = event.target as HTMLElement | null;
if (target?.tagName === 'INPUT' || target?.isContentEditable) return;
diff --git a/packages/app/src/components/TimelineDiffPane.tsx b/packages/app/src/components/TimelineDiffPane.tsx
index 3bcd94c5d..8bc1d9da1 100644
--- a/packages/app/src/components/TimelineDiffPane.tsx
+++ b/packages/app/src/components/TimelineDiffPane.tsx
@@ -36,6 +36,7 @@ import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { collectChangeAnchors, countChangeGroups } from '@/lib/diff-change-nav';
import { LruStringCache } from '@/lib/lru-string-cache';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import {
countRenderedDiffAnchors,
RENDERED_DIFF_CHANGE_SELECTOR,
@@ -166,13 +167,24 @@ export function TimelineDiffPane({ view, isPanelCollapsed, onTogglePanel }: Time
};
}, [diffKey]);
- // Esc closes the pane — parity with a full-screen overlay's expected dismiss.
+ // Esc closes the pane — parity with a full-screen overlay's expected dismiss,
+ // but only when no layer sits above it (the restore-confirm dialog, the
+ // command palette, a menu). Capture phase on `window` so the probe runs
+ // before Radix's DismissableLayer (capture phase on `document`) flips
+ // `data-state` and the pane closes out from under the layer Escape targeted.
useEffect(() => {
const onKey = (e: KeyboardEvent): void => {
- if (e.key === 'Escape' && !dialogOpen) closeTimelineDiff();
+ if (e.key !== 'Escape') return;
+ // `dialogOpen` is kept alongside the DOM probe rather than replaced by it:
+ // the restore-confirm is this pane's own state, so reading it cannot fail,
+ // and closing the pane out from under that particular dialog would lose
+ // the user's place in a restore they were part-way through confirming.
+ if (dialogOpen) return;
+ if (isOverlayLayerOpen()) return;
+ closeTimelineDiff();
};
- window.addEventListener('keydown', onKey);
- return () => window.removeEventListener('keydown', onKey);
+ window.addEventListener('keydown', onKey, { capture: true });
+ return () => window.removeEventListener('keydown', onKey, { capture: true });
}, [dialogOpen]);
// No try/finally: the React Compiler cannot lower a `finally` clause in a
diff --git a/packages/app/src/components/ui/sidebar.tsx b/packages/app/src/components/ui/sidebar.tsx
index fb7284b68..16b4c9369 100644
--- a/packages/app/src/components/ui/sidebar.tsx
+++ b/packages/app/src/components/ui/sidebar.tsx
@@ -11,6 +11,7 @@ import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { useSidebarResize } from '@/hooks/use-sidebar-resize';
import { formatShortcutLabel, matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { LEFT_COLLAPSE_THRESHOLD, resolvePartition } from '@/lib/sidebar-partition';
import { applyToggle, readPins, resolveEffectiveState } from '@/lib/sidebar-pin-store';
import { cn } from '@/lib/utils';
@@ -192,14 +193,7 @@ function SidebarProvider({
if (partition === 'above' || !open) return;
const onEscape = (event: KeyboardEvent) => {
if (event.key !== 'Escape') return;
- const openLayer = document.querySelector(
- '[data-state="open"][role="dialog"], ' +
- '[data-state="open"][role="alertdialog"], ' +
- '[data-state="open"][role="menu"], ' +
- '[data-state="open"][role="listbox"], ' +
- '[data-radix-popper-content-wrapper] [data-state="open"]',
- );
- if (openLayer) return;
+ if (isOverlayLayerOpen()) return;
setOpen(false);
};
window.addEventListener('keydown', onEscape, { capture: true });
@@ -213,10 +207,10 @@ function SidebarProvider({
React.useEffect(() => {
if (typeof window !== 'undefined' && window.okDesktop != null) return;
const handleKeyDown = (event: KeyboardEvent) => {
- if (matchesKeyboardShortcut(event, 'toggle-files-sidebar')) {
- event.preventDefault();
- toggleSidebar();
- }
+ if (!matchesKeyboardShortcut(event, 'toggle-files-sidebar')) return;
+ if (isOverlayLayerOpen()) return;
+ event.preventDefault();
+ toggleSidebar();
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
diff --git a/packages/app/src/components/ui/sidebar.web-shortcut-gate.dom.test.tsx b/packages/app/src/components/ui/sidebar.web-shortcut-gate.dom.test.tsx
index e70b57053..18529b9e0 100644
--- a/packages/app/src/components/ui/sidebar.web-shortcut-gate.dom.test.tsx
+++ b/packages/app/src/components/ui/sidebar.web-shortcut-gate.dom.test.tsx
@@ -11,12 +11,12 @@
* interface (`useSidebar().state` flips on toggle), so a refactor that drops
* the gate fails here instead of shipping a double-toggle.
*
- * Substrate: jsdom via `bun run test:dom`. `window.innerWidth` is pinned to a
+ * Substrate: jsdom via `pnpm run test:dom`. `window.innerWidth` is pinned to a
* desktop width so `toggleSidebar` takes the `setOpen` branch and the derived
* state is `expanded` → `collapsed` on a single toggle.
*/
-import { act, cleanup, render, screen } from '@testing-library/react';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import { SIDEBAR_PINS_KEY } from '@/lib/sidebar-pin-store';
import { SidebarProvider, useSidebar } from './sidebar';
@@ -80,6 +80,29 @@ describe('SidebarProvider web-mode ⌥⌘S shortcut — Electron gate', () => {
expect(screen.getByTestId('sidebar-state').textContent).toBe('expanded');
});
+ test('web host: ⌥⌘S does NOT toggle while an overlay owns the keyboard', async () => {
+ const { Dialog, DialogContent, DialogDescription, DialogTitle } = await import(
+ '@/components/ui/dialog'
+ );
+ render(
+ <SidebarProvider>
+ <StateProbe />
+ <Dialog open>
+ <DialogContent>
+ <DialogTitle>Command palette</DialogTitle>
+ <DialogDescription>Search files and commands</DialogDescription>
+ </DialogContent>
+ </Dialog>
+ </SidebarProvider>,
+ );
+ await waitFor(() => expect(screen.getByRole('dialog')).not.toBeNull());
+ expect(screen.getByTestId('sidebar-state').textContent).toBe('expanded');
+
+ pressSidebarShortcut();
+
+ expect(screen.getByTestId('sidebar-state').textContent).toBe('expanded');
+ });
+
test('web host (Win/Linux modifier): Ctrl+Alt+S also toggles the sidebar', () => {
// The Electron accelerator is `CmdOrCtrl+Alt+S` — cross-platform by intent.
// The renderer listener mirrors that with `(metaKey || ctrlKey)` so Windows
diff --git a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx
index 9843052aa..f3feedc4c 100644
--- a/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx
+++ b/packages/app/src/editor/bubble-menu/EditWithAiBubbleButton.tsx
@@ -38,6 +38,7 @@ import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import { useIsEmbedded } from '@/hooks/use-is-embedded';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { serializeWysiwygSelection } from '../edit-with-ai-selection';
import { getEditorDocName } from '../extensions/doc-context';
@@ -81,6 +82,9 @@ function EditWithAiBubbleMenu({
const handleKeyDown = (event: KeyboardEvent): void => {
if (!shortcutEnabled) return;
if (!matchesKeyboardShortcut(event, 'edit-with-ai')) return;
+ // `shortcutEnabled` only means "this is the active doc's editor", so it
+ // stays true under an overlay — the layer above owns the keyboard.
+ if (isOverlayLayerOpen()) return;
if (isNativeTextControl(event.target)) return;
event.preventDefault();
diff --git a/packages/app/src/editor/components/SrcAutocomplete.tsx b/packages/app/src/editor/components/SrcAutocomplete.tsx
index 6c9aabf79..03d6d2b38 100644
--- a/packages/app/src/editor/components/SrcAutocomplete.tsx
+++ b/packages/app/src/editor/components/SrcAutocomplete.tsx
@@ -324,6 +324,9 @@ export function SrcAutocomplete({
// parent prop panel, swallows the upload affordance, and makes
// the whole row read as broken).
className="z-70 w-(--radix-popover-trigger-width) p-1"
+ // Focus stays on the input below, so this list must not count as
+ // owning app-global shortcuts.
+ data-ok-declines-keyboard=""
onOpenAutoFocus={(e) => {
// Default Radix behavior moves focus into the PopoverContent
// on open — that would yank focus off the input and visually
diff --git a/packages/app/src/editor/find-replace/FindReplaceController.tsx b/packages/app/src/editor/find-replace/FindReplaceController.tsx
index 4656b2641..a4a101078 100644
--- a/packages/app/src/editor/find-replace/FindReplaceController.tsx
+++ b/packages/app/src/editor/find-replace/FindReplaceController.tsx
@@ -9,6 +9,7 @@ import {
} from 'react';
import { getEditorForDoc, subscribeEditorRegistry } from '@/editor/active-editor';
import { matchesKeyboardShortcut } from '@/lib/keyboard-shortcuts';
+import { isOverlayLayerOpen } from '@/lib/overlay-layers';
import { getEditorView } from '../utils/get-editor-view';
import { FindReplaceBar } from './FindReplaceBar';
import { getFindReplaceState } from './tiptap-find-replace-extension';
@@ -213,6 +214,10 @@ export function FindReplaceController({ activeDocName, isSourceMode }: FindRepla
function onKeyDown(event: KeyboardEvent) {
if (!activeDocName || isSourceMode || event.defaultPrevented) return;
+ // A layer above the editor owns the keyboard. Escape already falls out
+ // via `defaultPrevented` above (a dismissable layer cancels it), but the
+ // find chords are not cancelled by anything and need this arm.
+ if (isOverlayLayerOpen()) return;
if (matchesKeyboardShortcut(event, 'find')) {
event.preventDefault();
diff --git a/packages/app/src/lib/overlay-layers.dom.test.tsx b/packages/app/src/lib/overlay-layers.dom.test.tsx
new file mode 100644
index 000000000..54c37d9a1
--- /dev/null
+++ b/packages/app/src/lib/overlay-layers.dom.test.tsx
@@ -0,0 +1,205 @@
+/**
+ * Pins `isOverlayLayerOpen` against the DOM the real Radix primitives emit.
+ *
+ * The predicate is a selector probe, so its correctness is entirely a claim
+ * about what Radix renders. These tests render each primitive for real rather
+ * than asserting against hand-built markup — a Radix upgrade that renames
+ * `data-state` or drops the popper wrapper fails here instead of silently
+ * disarming every app-global shortcut gate that depends on it.
+ *
+ * The negative cases matter as much as the positive ones: a tooltip and a
+ * collapsible both carry an "open" notion, and suppressing shortcuts for
+ * either would be an over-reach.
+ */
+
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { afterEach, describe, expect, test } from 'vitest';
+import { Collapsible, CollapsibleContent } from '@/components/ui/collapsible';
+import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog';
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu';
+import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
+import { isOverlayLayerOpen } from './overlay-layers';
+
+afterEach(cleanup);
+
+describe('isOverlayLayerOpen', () => {
+ test('false with nothing open', () => {
+ render(<div>plain content</div>);
+
+ expect(isOverlayLayerOpen()).toBe(false);
+ });
+
+ test('true while a modal dialog is open', async () => {
+ render(
+ <Dialog open>
+ <DialogContent>
+ <DialogTitle>Overlay</DialogTitle>
+ <DialogDescription>Overlay body</DialogDescription>
+ </DialogContent>
+ </Dialog>,
+ );
+ await waitFor(() => expect(screen.getByRole('dialog')).not.toBeNull());
+
+ expect(isOverlayLayerOpen()).toBe(true);
+ });
+
+ test('false once the dialog closes', async () => {
+ const view = render(
+ <Dialog open>
+ <DialogContent>
+ <DialogTitle>Overlay</DialogTitle>
+ <DialogDescription>Overlay body</DialogDescription>
+ </DialogContent>
+ </Dialog>,
+ );
+ await waitFor(() => expect(screen.getByRole('dialog')).not.toBeNull());
+
+ view.rerender(
+ <Dialog open={false}>
+ <DialogContent>
+ <DialogTitle>Overlay</DialogTitle>
+ <DialogDescription>Overlay body</DialogDescription>
+ </DialogContent>
+ </Dialog>,
+ );
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
+
+ expect(isOverlayLayerOpen()).toBe(false);
+ });
+
+ test('true while a dropdown menu is open', async () => {
+ render(
+ <DropdownMenu open>
+ <DropdownMenuContent>
+ <DropdownMenuItem>Item</DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>,
+ );
+ await waitFor(() => expect(screen.getByRole('menu')).not.toBeNull());
+
+ expect(isOverlayLayerOpen()).toBe(true);
+ });
+
+ test('true while a popover is open', async () => {
+ render(
+ <Popover open>
+ <PopoverTrigger>Open</PopoverTrigger>
+ <PopoverContent>Popover body</PopoverContent>
+ </Popover>,
+ );
+ await waitFor(() => expect(screen.getByText('Popover body')).not.toBeNull());
+
+ expect(isOverlayLayerOpen()).toBe(true);
+ });
+
+ test('false while a tooltip is showing — a tooltip takes no focus', async () => {
+ render(
+ <TooltipProvider>
+ <Tooltip open>
+ <TooltipTrigger>Trigger</TooltipTrigger>
+ <TooltipContent>Tooltip body</TooltipContent>
+ </Tooltip>
+ </TooltipProvider>,
+ );
+ await waitFor(() => expect(screen.getAllByText('Tooltip body').length).toBeGreaterThan(0));
+
+ expect(isOverlayLayerOpen()).toBe(false);
+ });
+
+ test('false while a layer that leaves focus outside itself is open', async () => {
+ // The shape the InteractionLayer's chip prop-panel uses: a Radix Popover
+ // opened by pointerover that prevents `onOpenAutoFocus`, so the caret stays
+ // in the document. Treating that as owning the keyboard would make every
+ // global shortcut depend on where the mouse is resting.
+ render(
+ <Popover open>
+ <PopoverAnchor>
+ <span />
+ </PopoverAnchor>
+ <PopoverContent
+ data-ok-declines-keyboard=""
+ onOpenAutoFocus={(event) => event.preventDefault()}
+ >
+ Hover panel body
+ </PopoverContent>
+ </Popover>,
+ );
+ await waitFor(() => expect(screen.getByText('Hover panel body')).not.toBeNull());
+
+ expect(isOverlayLayerOpen()).toBe(false);
+ });
+
+ test('true while a dialog is open even with focus fallen back to the body', async () => {
+ // Focus can sit on `<body>` with a modal wide open — a programmatic blur, or
+ // a focused node removed before the focus scope heals it. Ownership must not
+ // depend on that, or the shortcut goes straight back to the app underneath.
+ render(
+ <Dialog open>
+ <DialogContent>
+ <DialogTitle>Overlay</DialogTitle>
+ <DialogDescription>Overlay body</DialogDescription>
+ </DialogContent>
+ </Dialog>,
+ );
+ await waitFor(() => expect(screen.getByRole('dialog')).not.toBeNull());
+
+ act(() => (document.activeElement as HTMLElement | null)?.blur());
+ expect(document.activeElement).toBe(document.body);
+
+ expect(isOverlayLayerOpen()).toBe(true);
+ });
+
+ test('an Escape handler can read the layer capture-phase, or bail on defaultPrevented', async () => {
+ // The two arms the helper's contract offers Escape handlers, pinned against
+ // a real dismissable layer. `GraphPanel` / `TimelineDiffPane` / the sidebar
+ // take the capture arm; `AgentDiffPane` / `FindReplaceController` take the
+ // defaultPrevented one. A Radix change that stopped cancelling Escape, or
+ // that moved its dismissal ahead of window capture, breaks this.
+ render(
+ <Dialog open>
+ <DialogContent>
+ <DialogTitle>Overlay</DialogTitle>
+ <DialogDescription>Overlay body</DialogDescription>
+ </DialogContent>
+ </Dialog>,
+ );
+ await waitFor(() => expect(screen.getByRole('dialog')).not.toBeNull());
+
+ let sawLayerInCapture: boolean | null = null;
+ let cancelledByBubble: boolean | null = null;
+ const onCapture = () => {
+ sawLayerInCapture = isOverlayLayerOpen();
+ };
+ const onBubble = (event: Event) => {
+ cancelledByBubble = event.defaultPrevented;
+ };
+ window.addEventListener('keydown', onCapture, { capture: true });
+ window.addEventListener('keydown', onBubble);
+
+ try {
+ act(() => {
+ document.body.dispatchEvent(
+ new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }),
+ );
+ });
+ } finally {
+ window.removeEventListener('keydown', onCapture, { capture: true });
+ window.removeEventListener('keydown', onBubble);
+ }
+
+ expect(sawLayerInCapture).toBe(true);
+ expect(cancelledByBubble).toBe(true);
+ });
+
+ test('false while a collapsible is expanded — inline disclosure, not a layer', async () => {
+ render(
+ <Collapsible open>
+ <CollapsibleContent>Collapsible body</CollapsibleContent>
+ </Collapsible>,
+ );
+ await waitFor(() => expect(screen.getByText('Collapsible body')).not.toBeNull());
+
+ expect(isOverlayLayerOpen()).toBe(false);
+ });
+});
diff --git a/packages/app/src/lib/overlay-layers.ts b/packages/app/src/lib/overlay-layers.ts
new file mode 100644
index 000000000..69e7e4a00
--- /dev/null
+++ b/packages/app/src/lib/overlay-layers.ts
@@ -0,0 +1,59 @@
+/**
+ * Candidate layers: dialogs, alert dialogs, menus, listboxes, and anything
+ * Radix renders through a popper wrapper (popovers, dropdown and context
+ * menus, selects).
+ *
+ * Tooltips deliberately do not match — Radix marks tooltip content
+ * `data-state="delayed-open" | "instant-open"`, never `"open"`. Inline
+ * disclosures (collapsibles, accordions) carry `data-state="open"` but neither
+ * a matching role nor a popper wrapper, so they do not match either.
+ */
+const OPEN_OVERLAY_LAYER_SELECTOR =
+ '[data-state="open"][role="dialog"], ' +
+ '[data-state="open"][role="alertdialog"], ' +
+ '[data-state="open"][role="menu"], ' +
+ '[data-state="open"][role="listbox"], ' +
+ '[data-radix-popper-content-wrapper] [data-state="open"]';
+
+/**
+ * Being open is not the same as owning the keyboard. A hover-triggered panel or
+ * a passive suggestion list leaves the caret where it was, so the user is still
+ * typing in the document underneath it and their shortcuts have to keep working
+ * — treating those as owning the keys would make the keyboard a function of
+ * where the mouse happens to rest.
+ *
+ * Any layer that leaves focus outside itself opts out with
+ * `data-ok-declines-keyboard`. That is deliberately a property of the LAYER
+ * rather than a reading of `document.activeElement`: live focus can sit on
+ * `<body>` while a modal is wide open (a programmatic blur, or a focused node
+ * being removed before Radix's focus scope heals it), and a probe that went by
+ * focus alone would hand the shortcut straight back to the app in exactly the
+ * case this module exists to prevent.
+ */
+function ownsKeyboard(layer: Element): boolean {
+ return layer.closest('[data-ok-declines-keyboard]') === null;
+}
+
+/**
+ * Does a layer that owns the keyboard currently sit above the app?
+ *
+ * App-global shortcuts (⌘T, ⌘N, ⌘L, ⌥⌘S, …) are registered on `window` and
+ * fire regardless of focus, so an overlay has no way to stop them from
+ * underneath — the listeners have to decline for themselves. Every app-global
+ * keydown listener gates on this; focus-scoped listeners do not need it,
+ * because an overlay's focus trap already makes them inert.
+ *
+ * Read this from a CAPTURE-phase listener on `window` whenever the key being
+ * handled can itself dismiss a layer (Escape), so the open-layer DOM state is
+ * observed before Radix's DismissableLayer (capture phase on `document`) flips
+ * `data-state`. A bubble-phase listener can instead bail on
+ * `event.defaultPrevented`, which a dismissable layer sets when it claims the
+ * Escape.
+ */
+export function isOverlayLayerOpen(): boolean {
+ if (typeof document === 'undefined') return false;
+ for (const layer of document.querySelectorAll(OPEN_OVERLAY_LAYER_SELECTOR)) {
+ if (ownsKeyboard(layer)) return true;
+ }
+ return false;
+}