The best way to control Claude Code, Codex and more from any computer or phone
refactor(web): app shell shortcuts register once through one command dispatcher (#25016)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 25, 2026 at 15:31 UTC
b457b64a76d77db92b0fd90ed7c195c945c6a044
4 files changed
+465
-142
apps/web/src/components/AppSidebarLayout.tsx
+149
-140
@@ -2,13 +2,12 @@ import { useAtomValue } from "@effect/atom-react";
2
import * as Schema from "effect/Schema";
3
import {
4
useEffect,
5
- useRef,
5
useState,
6
useSyncExternalStore,
7
type CSSProperties,
8
type ReactNode,
9
} from "react";
11
-import { useLocation, useNavigate } from "@tanstack/react-router";
10
+import { useLocation, useRouter, type AnyRouter } from "@tanstack/react-router";
11
12
import { isCommandPaletteOpen } from "../commandPaletteBus";
13
import { isElectron } from "../env";
@@ -62,7 +61,9 @@ import {
61
useSidebarVisibility,
62
} from "./ui/sidebar";
63
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
65
-import { useThreadRouteRef } from "../hooks/useThreadRouteTarget";
64
+import { appAtomRegistry } from "../rpc/atomRegistry";
65
+import { registerCommands, registerMenuAction } from "../shortcuts/dispatcher";
66
+import { resolveThreadRouteRef } from "../threadRoutes";
67
68
const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "var(--desktop-window-controls-inset, 90px)";
69
@@ -124,7 +125,144 @@ function readInitialThreadSidebarWidth(): number {
125
}
126
}
127
128
+function readUsagePageOpen(router: AnyRouter) {
129
+ return router.state.location.pathname === "/usage";
130
+}
131
+
132
+function isKeybindingCaptureTarget(event: KeyboardEvent) {
133
+ return event.target instanceof HTMLElement && event.target.closest("[data-keybinding-capture]");
134
+}
135
+
136
+function readRoutePanelsOpen(router: AnyRouter) {
137
+ const routeThreadRef = resolveThreadRouteRef(router.state.matches.at(-1)?.params ?? {});
138
+ if (!routeThreadRef) return { terminalOpen: false, previewOpen: false };
139
+ return {
140
+ terminalOpen: selectThreadTerminalUiState(
141
+ useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
142
+ routeThreadRef,
143
+ ).terminalOpen,
144
+ previewOpen:
145
+ selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
146
+ "preview",
147
+ };
148
+}
149
+
150
+export function registerNavigationHistoryCommands(router: AnyRouter): () => void {
151
+ return registerCommands(
152
+ {
153
+ "navigation.back": (event) => {
154
+ event.preventDefault();
155
+ event.stopPropagation();
156
+ window.history.back();
157
+ },
158
+ "navigation.forward": (event) => {
159
+ event.preventDefault();
160
+ event.stopPropagation();
161
+ window.history.forward();
162
+ },
163
+ },
164
+ {
165
+ when: (event) => !isKeybindingCaptureTarget(event),
166
+ context: () => ({
167
+ ...readRoutePanelsOpen(router),
168
+ usagePageOpen: readUsagePageOpen(router),
169
+ }),
170
+ },
171
+ );
172
+}
173
+
174
+const MODIFIER_KEYS = new Set(["Alt", "Control", "Meta", "Shift"]);
175
+
176
+// A held key undoes once. Module state: undoing an archive navigates, and the
177
+// hold must survive whatever that re-renders.
178
+let heldUndoKey: string | null = null;
179
+
180
+// Undoes the thread actions in the sidebar's notice. Settings and Usage own
181
+// mod+z while open. Captured so mod+z reaches it before the composer's own
182
+// undo handler consumes the key.
183
+function registerThreadUndoCommands(
184
+ router: AnyRouter,
185
+ readSidebarVisible: () => boolean,
186
+): () => void {
187
+ const threadSidebarShown = () => !isAppModalPage(router.state.location.pathname);
188
+ const unregister = registerCommands(
189
+ {},
190
+ {
191
+ capture: true,
192
+ when: threadSidebarShown,
193
+ onKeyDown: (event) => {
194
+ // Cancel a held key's repeats so they cannot fall through to the
195
+ // editor's own undo, even after the last notice is gone.
196
+ if (event.repeat) {
197
+ if (event.code !== heldUndoKey) return false;
198
+ event.preventDefault();
199
+ event.stopPropagation();
200
+ return true;
201
+ }
202
+ // A modifier tapped mid-hold leaves the held key repeating.
203
+ if (!MODIFIER_KEYS.has(event.key)) heldUndoKey = null;
204
+ const command = resolveShortcutCommand(
205
+ event,
206
+ appAtomRegistry.get(primaryServerKeybindingsAtom),
207
+ {
208
+ context: {
209
+ terminalFocus: isTerminalFocused(),
210
+ previewFocus: isPreviewFocused(),
211
+ ...readRoutePanelsOpen(router),
212
+ // A collapsed sidebar hides the notice, so text fields keep their own undo.
213
+ editableFocus:
214
+ isEditableFocused(event.target) &&
215
+ !(readSidebarVisible() && threadUndoClaimsShortcut()),
216
+ modelPickerOpen: isModelPickerOpen(),
217
+ },
218
+ },
219
+ );
220
+ if (command !== "thread.undo") {
221
+ if (!MODIFIER_KEYS.has(event.key)) releaseThreadUndoShortcut();
222
+ return false;
223
+ }
224
+ if (isCommandPaletteOpen() || isModelPickerOpen()) return false;
225
+ if (!undoLatestThreadAction()) return false;
226
+ heldUndoKey = event.code;
227
+ event.preventDefault();
228
+ event.stopPropagation();
229
+ return true;
230
+ },
231
+ },
232
+ );
233
+ // Pastes from a menu, dictation and drops edit text without a keypress.
234
+ const onInput = () => {
235
+ if (threadSidebarShown()) releaseThreadUndoShortcut();
236
+ };
237
+ window.addEventListener("input", onInput, true);
238
+ return () => {
239
+ unregister();
240
+ window.removeEventListener("input", onInput, true);
241
+ };
242
+}
243
+
244
+/** Keyboard and menu commands that live as long as the app shell. */
245
+function registerAppShellCommands(router: AnyRouter, shellElement: Element): () => void {
246
+ // The provider mirrors the visibility it renders onto its wrapper, so the
247
+ // committed state is readable when a key arrives.
248
+ const readSidebarVisible = () =>
249
+ shellElement.closest('[data-slot="sidebar-wrapper"]')?.getAttribute("data-sidebar-state") ===
250
+ "expanded";
251
+ const disposers = [
252
+ registerThreadUndoCommands(router, readSidebarVisible),
253
+ registerNavigationHistoryCommands(router),
254
+ registerMenuAction("open-settings", () => {
255
+ if (!/^\/settings(\/|$)/.test(router.state.location.pathname))
256
+ void router.navigate({ to: "/settings" });
257
+ }),
258
+ ];
259
+ return () => {
260
+ for (const dispose of disposers) dispose();
261
+ };
262
+}
263
+
264
function SidebarControl() {
265
+ const router = useRouter();
266
const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
267
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
268
const { toggleSidebar, isMobile, mobileSheetMounted } = useSidebar();
@@ -176,8 +314,16 @@ function SidebarControl() {
314
};
315
}, [keybindings, toggleSidebar, usagePageOpen]);
316
317
+ // The control lives as long as the shell, so it carries the shell's commands. Created
318
+ // once so re-renders never re-register them.
319
+ const [appShellCommandsRef] = useState(
320
+ () => (node: HTMLDivElement | null) =>
321
+ node === null ? undefined : registerAppShellCommands(router, node),
322
+ );
323
+
324
return (
325
<div
326
+ ref={appShellCommandsRef}
327
className={cn(
328
"pointer-events-none fixed left-[var(--workspace-controls-left)] top-[var(--workspace-controls-top)] z-50 ml-px flex h-[var(--workspace-topbar-height)] items-center",
329
isMobile && mobileSheetMounted && "hidden",
@@ -205,121 +351,7 @@ function SidebarControl() {
351
);
352
}
353
208
-function routePanelsOpen(routeThreadRef: ReturnType<typeof useThreadRouteRef>) {
209
- if (!routeThreadRef) return { terminalOpen: false, previewOpen: false };
210
- return {
211
- terminalOpen: selectThreadTerminalUiState(
212
- useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
213
- routeThreadRef,
214
- ).terminalOpen,
215
- previewOpen:
216
- selectActiveRightPanel(useRightPanelStore.getState().byThreadKey, routeThreadRef) ===
217
- "preview",
218
- };
219
-}
220
-
221
-export function NavigationHistoryShortcuts() {
222
- const usagePageOpen = useLocation({ select: (location) => location.pathname === "/usage" });
223
- const keybindings = useAtomValue(primaryServerKeybindingsAtom);
224
- const routeThreadRef = useThreadRouteRef();
225
-
226
- useEffect(() => {
227
- const onKeyDown = (event: KeyboardEvent) => {
228
- if (event.defaultPrevented) return;
229
- if (
230
- event.target instanceof HTMLElement &&
231
- event.target.closest("[data-keybinding-capture]")
232
- ) {
233
- return;
234
- }
235
- const command = resolveShortcutCommand(event, keybindings, {
236
- context: {
237
- terminalFocus: isTerminalFocused(),
238
- previewFocus: isPreviewFocused(),
239
- ...routePanelsOpen(routeThreadRef),
240
- editableFocus: isEditableFocused(event.target),
241
- modelPickerOpen: isModelPickerOpen(),
242
- usagePageOpen,
243
- },
244
- });
245
- if (command !== "navigation.back" && command !== "navigation.forward") return;
246
-
247
- event.preventDefault();
248
- event.stopPropagation();
249
- if (command === "navigation.back") window.history.back();
250
- else window.history.forward();
251
- };
252
-
253
- window.addEventListener("keydown", onKeyDown);
254
- return () => window.removeEventListener("keydown", onKeyDown);
255
- }, [keybindings, routeThreadRef, usagePageOpen]);
256
-
257
- return null;
258
-}
259
-
260
-const MODIFIER_KEYS = new Set(["Alt", "Control", "Meta", "Shift"]);
261
-
262
-// Undoes the thread actions in the sidebar's notice. Settings and Usage own
263
-// mod+z while open. Listens in the capture phase
264
-// so mod+z reaches it before the composer's own undo handler consumes the key.
265
-function ThreadUndoShortcut() {
266
- const keybindings = useAtomValue(primaryServerKeybindingsAtom);
267
- const routeThreadRef = useThreadRouteRef();
268
- // A collapsed sidebar hides the notice, so text fields keep their own undo.
269
- const noticeVisible = useSidebarVisibility();
270
- // Outlives the effect: undoing an archive navigates, which re-runs it mid-hold.
271
- const heldUndoKey = useRef<string | null>(null);
272
-
273
- useEffect(() => {
274
- const onKeyDown = (event: KeyboardEvent) => {
275
- // A held key undoes once. Cancel its repeats so they cannot fall through
276
- // to the editor's own undo, even after the last notice is gone.
277
- if (event.repeat) {
278
- if (event.code === heldUndoKey.current) {
279
- event.preventDefault();
280
- event.stopPropagation();
281
- }
282
- return;
283
- }
284
- // A modifier tapped mid-hold leaves the held key repeating.
285
- if (!MODIFIER_KEYS.has(event.key)) heldUndoKey.current = null;
286
- const command = resolveShortcutCommand(event, keybindings, {
287
- context: {
288
- terminalFocus: isTerminalFocused(),
289
- previewFocus: isPreviewFocused(),
290
- ...routePanelsOpen(routeThreadRef),
291
- editableFocus:
292
- isEditableFocused(event.target) && !(noticeVisible && threadUndoClaimsShortcut()),
293
- modelPickerOpen: isModelPickerOpen(),
294
- },
295
- });
296
- if (command !== "thread.undo") {
297
- if (!MODIFIER_KEYS.has(event.key)) releaseThreadUndoShortcut();
298
- return;
299
- }
300
- if (isCommandPaletteOpen() || isModelPickerOpen()) return;
301
- if (undoLatestThreadAction()) {
302
- heldUndoKey.current = event.code;
303
- event.preventDefault();
304
- event.stopPropagation();
305
- }
306
- };
307
- // Pastes from a menu, dictation and drops edit text without a keypress.
308
- const onInput = () => releaseThreadUndoShortcut();
309
-
310
- window.addEventListener("keydown", onKeyDown, true);
311
- window.addEventListener("input", onInput, true);
312
- return () => {
313
- window.removeEventListener("keydown", onKeyDown, true);
314
- window.removeEventListener("input", onInput, true);
315
- };
316
- }, [keybindings, noticeVisible, routeThreadRef]);
317
-
318
- return null;
319
-}
320
-
354
export function AppSidebarLayout({ children }: { children: ReactNode }) {
322
- const navigate = useNavigate();
355
const legacySidebarEnabled = useLegacySidebarEnabled();
356
const [sidebarRouteReveal] = useState<SidebarRouteReveal>(() => ({
357
observedKey: null,
@@ -331,7 +363,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
363
const pathname = useLocation({ select: (location) => location.pathname });
364
const panelAnimationsSuppressed = usePanelNavigationSuppression(pathname);
365
const routePanelAnimationsActive = panelAnimationsActive && !panelAnimationsSuppressed;
334
- const appModalOpen = isAppModalPage(pathname);
366
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
367
const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);
368
// A clamped drag may not change width, so viewport changes need a separate subscription.
@@ -362,26 +393,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
393
...windowControlsInsetStyle,
394
} as CSSProperties;
395
365
- useEffect(() => {
366
- const onMenuAction = window.desktopBridge?.onMenuAction;
367
- if (typeof onMenuAction !== "function") {
368
- return;
369
- }
370
-
371
- const unsubscribe = onMenuAction((action) => {
372
- if (action === "open-settings") {
373
- const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
374
- if (!isSettingsRoute) {
375
- void navigate({ to: "/settings" });
376
- }
377
- }
378
- });
379
-
380
- return () => {
381
- unsubscribe?.();
382
- };
383
- }, [navigate, pathname]);
384
-
396
return (
397
<PanelAnimationSuppressionProvider value={panelAnimationsSuppressed}>
398
<SidebarProvider
@@ -418,8 +429,6 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
429
{children}
430
<BackgroundThreadAnnouncer />
431
<SidebarControl />
421
- <NavigationHistoryShortcuts />
422
- {appModalOpen ? null : <ThreadUndoShortcut />}
432
<MainAppLocationTracker />
433
</SidebarProvider>
434
</PanelAnimationSuppressionProvider>
apps/web/src/components/UsageToggleShortcut.browser.test.tsx
+14
-2
@@ -16,12 +16,23 @@ vi.mock(import("@effect/atom-react"), async (original) => ({
16
...(await original()),
17
useAtomValue: (() => keybindings) as never,
18
}));
19
+vi.mock(import("../state/server"), async (original) => {
20
+ const actual = await original();
21
+ const { Atom } = await import("effect/reactivity");
22
+ const { compileResolvedKeybindingsConfig: compile } = await import("@t3tools/shared/keybindings");
23
+ // Factories are hoisted above the module's own constants.
24
+ const compiled = compile([
25
+ { key: "mod+u", command: "navigation.back", when: "usagePageOpen" },
26
+ { key: "mod+u", command: "usage.open", when: "!usagePageOpen" },
27
+ ]);
28
+ return { ...actual, primaryServerKeybindingsAtom: Atom.make(compiled) };
29
+});
30
vi.mock(import("@tanstack/react-router"), async (original) => ({
31
...(await original()),
32
useNavigate: (() => state.navigate) as never,
33
}));
34
24
-import { NavigationHistoryShortcuts } from "./AppSidebarLayout";
35
+import { registerNavigationHistoryCommands } from "./AppSidebarLayout";
36
import { CommandPalette } from "./CommandPalette";
37
38
// regression: #21357
@@ -29,7 +40,8 @@ describe("usage toggle shortcut on Usage", () => {
40
it("goes back", async () => {
41
vi.clearAllMocks();
42
using _platform = vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux x86_64");
32
- await using _screen = await render(<NavigationHistoryShortcuts />, { router: "/usage" });
43
+ await using screen = await render(null, { router: "/usage" });
44
+ using _commands = { [Symbol.dispose]: registerNavigationHistoryCommands(screen.router!) };
45
46
using back = vi.spyOn(window.history, "back").mockImplementation(() => undefined);
47
await userEvent.keyboard("{Control>}u{/Control}");
apps/web/src/shortcuts/dispatcher.browser.test.ts
new
+148
@@ -0,0 +1,148 @@
1
+import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts";
2
+import { describe, expect, it, vi } from "vite-plus/test";
3
+
4
+import {
5
+ commandScopeRef,
6
+ dispatchMenuAction,
7
+ registerCommands,
8
+ registerMenuAction,
9
+} from "./dispatcher";
10
+
11
+function bindings(entries: ReadonlyArray<[string, KeybindingCommand]>): ResolvedKeybindingsConfig {
12
+ return entries.map(([key, command]) => ({
13
+ command,
14
+ shortcut: {
15
+ key,
16
+ metaKey: false,
17
+ ctrlKey: false,
18
+ shiftKey: false,
19
+ altKey: false,
20
+ modKey: false,
21
+ },
22
+ }));
23
+}
24
+
25
+const keybindings = () =>
26
+ bindings([
27
+ ["k", "chat.new"],
28
+ ["j", "chat.newLocal"],
29
+ ]);
30
+
31
+function press(key: string): KeyboardEvent {
32
+ const event = new KeyboardEvent("keydown", { key, cancelable: true, bubbles: true });
33
+ window.dispatchEvent(event);
34
+ return event;
35
+}
36
+
37
+function mountScope(...args: Parameters<typeof commandScopeRef>): () => void {
38
+ return commandScopeRef(...args)(document.body) ?? (() => {});
39
+}
40
+
41
+describe("command dispatcher", () => {
42
+ it("runs the newest scope's handler and nothing below it", () => {
43
+ const global = vi.fn();
44
+ const outer = vi.fn();
45
+ const inner = vi.fn();
46
+ using stack = new DisposableStack();
47
+ stack.defer(registerCommands({ "chat.new": global }, { keybindings }));
48
+ stack.defer(mountScope({ "chat.new": outer }, { keybindings }));
49
+ stack.defer(mountScope({ "chat.new": inner }, { keybindings }));
50
+
51
+ press("k");
52
+
53
+ expect(inner).toHaveBeenCalledOnce();
54
+ expect(outer).not.toHaveBeenCalled();
55
+ expect(global).not.toHaveBeenCalled();
56
+ });
57
+
58
+ it("falls through scopes that return false, skip the command, or fail their guard", () => {
59
+ const global = vi.fn();
60
+ const declined = vi.fn(() => false);
61
+ const guarded = vi.fn();
62
+ using stack = new DisposableStack();
63
+ stack.defer(registerCommands({ "chat.new": global }, { keybindings }));
64
+ stack.defer(mountScope({ "chat.new": declined }, { keybindings }));
65
+ stack.defer(mountScope({ "chat.newLocal": vi.fn() }, { keybindings }));
66
+ stack.defer(mountScope({ "chat.new": guarded }, { keybindings, when: () => false }));
67
+
68
+ press("k");
69
+
70
+ expect(guarded).not.toHaveBeenCalled();
71
+ expect(declined).toHaveBeenCalledOnce();
72
+ expect(global).toHaveBeenCalledOnce();
73
+ });
74
+
75
+ it("element scopes win over global commands registered after them", () => {
76
+ const element = vi.fn();
77
+ const global = vi.fn();
78
+ using stack = new DisposableStack();
79
+ stack.defer(mountScope({ "chat.new": element }, { keybindings }));
80
+ stack.defer(registerCommands({ "chat.new": global }, { keybindings }));
81
+
82
+ press("k");
83
+
84
+ expect(element).toHaveBeenCalledOnce();
85
+ expect(global).not.toHaveBeenCalled();
86
+ });
87
+
88
+ it("stops once a handler prevents default, and unregisters on cleanup", () => {
89
+ const lower = vi.fn();
90
+ const upper = vi.fn((event: KeyboardEvent) => {
91
+ event.preventDefault();
92
+ return false;
93
+ });
94
+ using stack = new DisposableStack();
95
+ stack.defer(mountScope({ "chat.new": lower }, { keybindings }));
96
+ const unmountUpper = mountScope({ "chat.new": upper }, { keybindings });
97
+
98
+ press("k");
99
+ expect(lower).not.toHaveBeenCalled();
100
+
101
+ unmountUpper();
102
+ press("k");
103
+ expect(upper).toHaveBeenCalledOnce();
104
+ expect(lower).toHaveBeenCalledOnce();
105
+ });
106
+
107
+ it("lets a scope claim raw keys before command lookup", () => {
108
+ const onEscape = vi.fn((event: KeyboardEvent) => (event.key === "Escape" ? undefined : false));
109
+ const command = vi.fn();
110
+ using stack = new DisposableStack();
111
+ stack.defer(mountScope({ "chat.new": command }, { keybindings, onKeyDown: onEscape }));
112
+
113
+ press("Escape");
114
+ press("k");
115
+
116
+ expect(onEscape).toHaveBeenCalledTimes(2);
117
+ expect(command).toHaveBeenCalledOnce();
118
+ });
119
+
120
+ it("tells observers whether a scope consumed the key, after the scopes ran", () => {
121
+ const calls: Array<string> = [];
122
+ using stack = new DisposableStack();
123
+ stack.defer(
124
+ registerCommands({}, { observe: (_event, consumed) => calls.push(`observe:${consumed}`) }),
125
+ );
126
+ stack.defer(mountScope({ "chat.new": () => void calls.push("command") }, { keybindings }));
127
+
128
+ press("k");
129
+ press("x");
130
+
131
+ expect(calls).toEqual(["command", "observe:true", "observe:false"]);
132
+ });
133
+
134
+ it("routes a menu action to its newest handler", () => {
135
+ const older = vi.fn();
136
+ const newer = vi.fn();
137
+ using stack = new DisposableStack();
138
+ stack.defer(registerMenuAction("test-action", older));
139
+ const unregisterNewer = registerMenuAction("test-action", newer);
140
+
141
+ dispatchMenuAction("test-action");
142
+ unregisterNewer();
143
+ dispatchMenuAction("test-action");
144
+
145
+ expect(newer).toHaveBeenCalledOnce();
146
+ expect(older).toHaveBeenCalledOnce();
147
+ });
148
+});
apps/web/src/shortcuts/dispatcher.ts
new
+154
@@ -0,0 +1,154 @@
1
+import type { KeybindingCommand, ResolvedKeybindingsConfig } from "@t3tools/contracts";
2
+
3
+import { resolveShortcutCommand, type ShortcutMatchContext } from "../keybindings";
4
+import { isEditableFocused } from "../lib/editableFocus";
5
+import { isPreviewFocused } from "../lib/previewFocus";
6
+import { isTerminalFocused } from "../lib/terminalFocus";
7
+import { isModelPickerOpen } from "../modelPickerVisibility";
8
+import { appAtomRegistry } from "../rpc/atomRegistry";
9
+import { primaryServerKeybindingsAtom } from "../state/server";
10
+
11
+/** Return `false` to let the next scope handle the event. */
12
+export type CommandHandler = (event: KeyboardEvent) => boolean | void;
13
+
14
+export type CommandHandlers = Partial<Record<KeybindingCommand, CommandHandler>>;
15
+
16
+export interface CommandScopeOptions {
17
+ /** Read at event time; a scope whose guard fails is skipped. */
18
+ readonly when?: (event: KeyboardEvent) => boolean;
19
+ /** When-clause context the dispatcher cannot know (terminalOpen, previewOpen), read at event time. */
20
+ readonly context?: () => Partial<ShortcutMatchContext>;
21
+ readonly keybindings?: () => ResolvedKeybindingsConfig;
22
+ /** For shortcuts that are not keybinding commands (Escape, "/"); runs before command lookup. */
23
+ readonly onKeyDown?: CommandHandler;
24
+ /**
25
+ * App-global only: run in the capture phase, ahead of focused widgets that consume the key
26
+ * themselves (the terminal encodes Ctrl+Shift+T and stops propagation).
27
+ */
28
+ readonly capture?: boolean;
29
+ /**
30
+ * App-global only: hear every bubbling keydown after the scopes ran, with whether one of them
31
+ * (or the page) consumed it. Observers never consume. For listeners that react to keys other
32
+ * scopes may also handle, such as scroll keys.
33
+ */
34
+ readonly observe?: (event: KeyboardEvent, consumed: boolean) => void;
35
+}
36
+
37
+interface CommandScope {
38
+ readonly commands: CommandHandlers;
39
+ readonly options: CommandScopeOptions;
40
+}
41
+
42
+// Element scopes sit above app-global scopes; within each list the newest wins.
43
+const elementScopes: CommandScope[] = [];
44
+const globalScopes: CommandScope[] = [];
45
+const captureScopes: CommandScope[] = [];
46
+const observerScopes: CommandScope[] = [];
47
+
48
+function readFocusContext(event: KeyboardEvent): Partial<ShortcutMatchContext> {
49
+ return {
50
+ terminalFocus: isTerminalFocused(),
51
+ previewFocus: isPreviewFocused(),
52
+ editableFocus: isEditableFocused(event.target),
53
+ modelPickerOpen: isModelPickerOpen(),
54
+ };
55
+}
56
+
57
+function runScope(scope: CommandScope, event: KeyboardEvent): boolean {
58
+ const { commands, options } = scope;
59
+ if (options.when && !options.when(event)) return false;
60
+ if (options.onKeyDown && options.onKeyDown(event) !== false) return true;
61
+ const command = resolveShortcutCommand(
62
+ event,
63
+ options.keybindings?.() ?? appAtomRegistry.get(primaryServerKeybindingsAtom),
64
+ { context: { ...readFocusContext(event), ...options.context?.() } },
65
+ );
66
+ const handler = command === null ? undefined : commands[command];
67
+ return handler !== undefined && handler(event) !== false;
68
+}
69
+
70
+function runScopes(scopes: readonly CommandScope[], event: KeyboardEvent): boolean {
71
+ for (let index = scopes.length - 1; index >= 0; index -= 1) {
72
+ if (event.defaultPrevented) return true;
73
+ const scope = scopes[index];
74
+ if (scope && runScope(scope, event)) return true;
75
+ }
76
+ return false;
77
+}
78
+
79
+function dispatchCaptureKeyDown(event: KeyboardEvent): void {
80
+ runScopes(captureScopes, event);
81
+}
82
+
83
+function dispatchKeyDown(event: KeyboardEvent): void {
84
+ const consumed =
85
+ runScopes(elementScopes, event) || runScopes(globalScopes, event) || event.defaultPrevented;
86
+ for (const scope of observerScopes.slice()) scope.options.observe?.(event, consumed);
87
+}
88
+
89
+let keydownInstalled = false;
90
+function ensureKeydownListener() {
91
+ if (keydownInstalled || typeof window === "undefined") return;
92
+ keydownInstalled = true;
93
+ window.addEventListener("keydown", dispatchCaptureKeyDown, true);
94
+ window.addEventListener("keydown", dispatchKeyDown);
95
+}
96
+
97
+function pushScope(list: CommandScope[], scope: CommandScope): () => void {
98
+ ensureKeydownListener();
99
+ list.push(scope);
100
+ return () => {
101
+ const index = list.lastIndexOf(scope);
102
+ if (index !== -1) list.splice(index, 1);
103
+ };
104
+}
105
+
106
+/** App-global commands, registered once at module level or bootstrap. */
107
+export function registerCommands(
108
+ commands: CommandHandlers,
109
+ options: CommandScopeOptions = {},
110
+): () => void {
111
+ const scopes = options.observe ? observerScopes : options.capture ? captureScopes : globalScopes;
112
+ return pushScope(scopes, { commands, options });
113
+}
114
+
115
+/**
116
+ * Ref callback that keeps a command scope registered while its element is
117
+ * mounted. Handlers should read changing values from stores at event time so
118
+ * the callback stays stable across renders.
119
+ */
120
+export function commandScopeRef(
121
+ commands: CommandHandlers,
122
+ options: CommandScopeOptions = {},
123
+): (node: Element | null) => (() => void) | undefined {
124
+ return (node) => (node === null ? undefined : pushScope(elementScopes, { commands, options }));
125
+}
126
+
127
+type MenuActionHandler = () => void;
128
+const menuActionHandlers = new Map<string, MenuActionHandler[]>();
129
+let menuActionInstalled = false;
130
+
131
+export function dispatchMenuAction(action: string): void {
132
+ const handlers = menuActionHandlers.get(action);
133
+ handlers?.at(-1)?.();
134
+}
135
+
136
+function ensureMenuActionListener() {
137
+ if (menuActionInstalled || typeof window === "undefined") return;
138
+ const bridge = window.desktopBridge;
139
+ if (typeof bridge?.onMenuAction !== "function") return;
140
+ menuActionInstalled = true;
141
+ bridge.onMenuAction(dispatchMenuAction);
142
+}
143
+
144
+/** Desktop menu actions; the newest handler for an action wins. */
145
+export function registerMenuAction(action: string, handler: MenuActionHandler): () => void {
146
+ ensureMenuActionListener();
147
+ const handlers = menuActionHandlers.get(action) ?? [];
148
+ handlers.push(handler);
149
+ menuActionHandlers.set(action, handlers);
150
+ return () => {
151
+ const index = handlers.lastIndexOf(handler);
152
+ if (index !== -1) handlers.splice(index, 1);
153
+ };
154
+}