Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(web): keyboard shortcuts follow the platform, from one registry (#787)

Yaowei Zhengc5e0f8d7d227
diff --git a/changelog/unreleased/2026-09-18-keyboard-shortcuts.md b/changelog/unreleased/2026-09-18-keyboard-shortcuts.md
new file mode 100644
index 00000000..3d62a896
--- /dev/null
+++ b/changelog/unreleased/2026-09-18-keyboard-shortcuts.md
@@ -0,0 +1,48 @@
+# Keyboard shortcuts follow the platform, from one registry
+
+- **Date:** 2026-09-18
+- **Type:** feature
+- **Scope:** `web`
+- **PR:** [#787](https://github.com/Prism-Shadow/penguin-harness/pull/787)
+
+[中文版](2026-09-18-keyboard-shortcuts.zh.md)
+
+The Web App's shortcuts now come from one registry (`lib/shortcuts/`) instead of four hand-written
+modifier checks, and the modifier follows the platform: ⌘ on macOS, Ctrl elsewhere. No default sits
+on a chord the browser keeps for itself, so each one works in a browser tab as well as in the desktop
+app. The focused terminal closes on `` Ctrl+Alt+` `` (`` ⌃⌥` `` on a Mac), beside the terminal
+toggle, and Ctrl+W passes to the shell as readline's delete-word on every platform. The editors in
+the Files panel and the handbook save on ⌘S on a Mac and Ctrl+S elsewhere, instead of accepting both
+everywhere. The terminal toggle stays `` Ctrl+` `` on every platform (`` ⌘` `` is macOS's own window
+cycling). Chords match on the physical key (`KeyboardEvent.code`), so a CJK IME, Shift, Caps Lock
+and a macOS Option chord no longer change what a key means, and defaults move to the key that types
+their letter on a non-US layout where the browser exposes one.
+
+## Details
+
+- Registry: `palette.toggle` (⌥⌘P / Ctrl+Alt+P, reserved for the command palette),
+ `terminal.toggle` (`` Ctrl+` ``), `terminal.close` (`` Ctrl+Alt+` ``, literal Control on a Mac
+ too), `editor.save` (⌘S / Ctrl+S). Each has a scope (global, terminal, editor); a focus scope
+ beats global on the same chord, then registry order.
+- Defaults stay off the browsers' own shortcuts: ⌘P / Ctrl+P prints and ⌘W / Ctrl+W closes the
+ browser tab, hence Mod+Alt and the backquote key. Save keeps ⌘S / Ctrl+S and takes the browser's
+ Save Page while an editor has focus. On a Mac, Chrome binds ⌥⌘P to Page Setup, which the palette
+ takes over.
+- The command palette ([#768](https://github.com/Prism-Shadow/penguin-harness/pull/768)) opens
+ on `palette.toggle` and nothing else: its own Ctrl+P / Ctrl+Shift+P listener is gone, its footer
+ and the workflow page's "fill the app" hints name the current binding, and a key pressed inside a
+ workflow page still reaches the palette (the frame re-raises it with the key's code).
+- Overrides are read from the browser mirror `penguin.keybindings` (versioned, per-platform
+ sections, only rows that differ from the default), and every open tab follows a change live.
+ The settings page that writes them, and the per-account server copy, follow in a later change.
+- Every place that shows a chord — the terminal tab's × tooltip, the panel picker's kbd, the save
+ button's title, the handbook's editor hint — formats it from the registry the way the platform
+ writes it (`⌥⌘P`, `` ⌃` ``; `Ctrl+Alt+P`), and updates when the binding changes. A browser tab
+ shows no chord the browser itself reserves (a binding on ⌘W / Ctrl+W closes the browser tab
+ there), so no tooltip promises a key that does the opposite.
+- A held chord repeats: every repeat is kept from the browser's own action (Save Page, Print), and
+ the command runs once.
+- macOS terminal clipboard: ⌘C and ⌘V are the native copy and paste; Ctrl+C is always SIGINT and
+ Ctrl+V reaches the shell. Windows and Linux keep Ctrl+Shift+C / Ctrl+Insert / Ctrl+C-over-a-selection
+ and Ctrl+V / Shift+Insert.
+- A guard test fails on any `ctrlKey` / `metaKey` read outside `lib/shortcuts/`.
diff --git a/changelog/unreleased/2026-09-18-keyboard-shortcuts.zh.md b/changelog/unreleased/2026-09-18-keyboard-shortcuts.zh.md
new file mode 100644
index 00000000..75a56f19
--- /dev/null
+++ b/changelog/unreleased/2026-09-18-keyboard-shortcuts.zh.md
@@ -0,0 +1,21 @@
+# 快捷键随平台而定,统一出自一张注册表
+
+- **Date:** 2026-09-18
+- **Type:** feature
+- **Scope:** `web`
+- **PR:** [#787](https://github.com/Prism-Shadow/penguin-harness/pull/787)
+
+[English](2026-09-18-keyboard-shortcuts.md)
+
+Web App 的快捷键改为出自一张注册表(`lib/shortcuts/`),取代此前四处手写的修饰键判断,修饰键随平台:macOS 用 ⌘,其余平台用 Ctrl。缺省组合都不落在浏览器自己保留的组合上,因而在浏览器标签页与桌面应用里同样可用。当前终端以 `` Ctrl+Alt+` `` 关闭(Mac 上为 `` ⌃⌥` ``),与显示 / 隐藏终端同在一个键上;Ctrl+W 在所有平台都原样送 shell(readline 的删词)。文件面板与手册的编辑器在 Mac 上以 ⌘S、其余平台以 Ctrl+S 保存,不再在所有平台都接受两者。显示 / 隐藏终端在所有平台都保持 `` Ctrl+` ``(`` ⌘` `` 是 macOS 自己的窗口切换)。组合按物理键位(`KeyboardEvent.code`)匹配,中文输入法、Shift、Caps Lock 与 macOS 的 Option 组合不再改变一个键的含义;浏览器暴露键盘布局时,缺省组合会移到实际敲出该字母的键上。
+
+## 细节
+
+- 注册表:`palette.toggle`(⌥⌘P / Ctrl+Alt+P,为命令面板预留)、`terminal.toggle`(`` Ctrl+` ``)、`terminal.close`(`` Ctrl+Alt+` ``,Mac 上同样是 Control 键)、`editor.save`(⌘S / Ctrl+S)。每条命令有作用域(全局、终端、编辑器);同一组合下焦点作用域优先于全局,其次按注册顺序。
+- 缺省组合避开浏览器自身的快捷键:⌘P / Ctrl+P 是打印,⌘W / Ctrl+W 关闭浏览器标签页,因此改用 Mod+Alt 与反引号键。保存仍是 ⌘S / Ctrl+S,编辑器有焦点时接管浏览器的「另存网页」。Mac 上 Chrome 把 ⌥⌘P 用作「页面设置」,命令面板会接管它。
+- 命令面板([#768](https://github.com/Prism-Shadow/penguin-harness/pull/768))只由 `palette.toggle` 打开:它自带的 Ctrl+P / Ctrl+Shift+P 监听已移除,面板脚注与 workflow 页面「占满应用」的提示写的是当前绑定;在 workflow 页面里按下的键仍能到达命令面板(frame 连同键位 code 一起重新抛出)。
+- 覆盖项读自浏览器镜像 `penguin.keybindings`(带版本号、按平台分节、只存与缺省不同的行),改动即刻同步到已打开的全部标签页。写入它的设置页与按账号保存的服务端副本在后续改动中跟上。
+- 所有显示快捷键的位置——终端标签 × 的提示、面板选单的 kbd、保存按钮的标题、手册编辑器的提示——都从注册表按平台写法格式化(`⌥⌘P`、`` ⌃` ``;`Ctrl+Alt+P`),并随绑定变化更新。浏览器标签页里不显示浏览器自身保留的组合(绑在 ⌘W / Ctrl+W 上时,那里关闭的是浏览器标签页),提示不会许诺一个效果相反的按键。
+- 按住组合会连续触发:每次重复都不交给浏览器自己的动作(另存网页、打印),命令只执行一次。
+- macOS 终端剪贴板:⌘C 与 ⌘V 为系统原生复制粘贴;Ctrl+C 一律送 SIGINT,Ctrl+V 原样送 shell。Windows 与 Linux 沿用 Ctrl+Shift+C / Ctrl+Insert / 有选区时 Ctrl+C 复制,以及 Ctrl+V / Shift+Insert 粘贴。
+- 新增守卫测试:`lib/shortcuts/` 之外任何读取 `ctrlKey` / `metaKey` 的代码都会使其失败。
diff --git a/packages/web/src/components/ui/kbd.tsx b/packages/web/src/components/ui/kbd.tsx
new file mode 100644
index 00000000..bd84c09b
--- /dev/null
+++ b/packages/web/src/components/ui/kbd.tsx
@@ -0,0 +1,28 @@
+/**
+ * A keyboard chord drawn the way the platform writes it: one glyph run on macOS (`⌘W`), one
+ * `<kbd>` per token joined by `+` elsewhere (`Ctrl+W`). The size is the picker's existing kbd
+ * size; the caller supplies the colour.
+ */
+import { Fragment } from "react";
+import { formatChord } from "../../lib/shortcuts/format";
+import { currentPlatform } from "../../lib/shortcuts/platform";
+import { keyboardLayout } from "../../lib/shortcuts/store";
+import type { Chord } from "../../lib/shortcuts/types";
+
+export function Kbd({ chord, className = "" }: { chord: Chord; className?: string }) {
+ const platform = currentPlatform();
+ const label = formatChord(chord, platform, keyboardLayout() ?? undefined);
+ const size = "font-mono text-[10px]";
+ if (platform === "mac") return <kbd className={`${size} ${className}`}>{label}</kbd>;
+ const tokens = label.split("+");
+ return (
+ <span className={`inline-flex items-center ${size} ${className}`}>
+ {tokens.map((token, i) => (
+ <Fragment key={i}>
+ {i > 0 && <span aria-hidden>+</span>}
+ <kbd>{token}</kbd>
+ </Fragment>
+ ))}
+ </span>
+ );
+}
diff --git a/packages/web/src/features/chat/workspace-browser.tsx b/packages/web/src/features/chat/workspace-browser.tsx
index 8def7d1f..f8771611 100644
--- a/packages/web/src/features/chat/workspace-browser.tsx
+++ b/packages/web/src/features/chat/workspace-browser.tsx
@@ -55,6 +55,7 @@ import { useAuth } from "../../state/auth";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { isDesktopShellWindow } from "../../lib/account-menu";
+import { useShortcutLabel } from "../../lib/shortcuts/use-keymap";
import { joinWorkspacePath } from "../../lib/file-path";
import { dropRegionAction, isFileDrag } from "../../lib/file-drop";
import type { DragSignal } from "../../lib/file-drop";
@@ -493,6 +494,7 @@ export function WorkspaceBrowser({
// the new tab to the same-origin sandbox (which the link flags rather than failing
// silently in the page) and the in-app rendered view to the srcDoc fallback.
const { previewIsolated, desktopMode, sessionVia } = useAuth();
+ const saveShortcut = useShortcutLabel("editor.save");
// The desktop app's own window is the one page whose machine IS the server's, so it is the
// only one offered "show in folder" — see lib/account-menu.ts for why a browser signed into
// the same server, even on this machine, must not be.
@@ -2357,7 +2359,11 @@ export function WorkspaceBrowser({
</button>
</Tooltip>
<Tooltip
- label={saving ? S.common.saving : S.files.saveTitle}
+ label={
+ saving
+ ? S.common.saving
+ : `${S.common.save}${saveShortcut !== null ? ` (${saveShortcut})` : ""}`
+ }
placement="bottom"
className="shrink-0"
>
diff --git a/packages/web/src/features/chat/workspace-editor.tsx b/packages/web/src/features/chat/workspace-editor.tsx
index 356c932a..fcad2384 100644
--- a/packages/web/src/features/chat/workspace-editor.tsx
+++ b/packages/web/src/features/chat/workspace-editor.tsx
@@ -12,14 +12,18 @@
* size, line height, letter spacing, tab size, padding, wrap mode — and those are stated once,
* for both layers, in `.code-surface`.
*
- * No spell-check or autocorrect, and Ctrl+S / Cmd+S saves — the browser's own "save page"
- * default is suppressed while the focus is here. Long lines scroll sideways, as code should,
+ * No spell-check or autocorrect, and the `editor.save` shortcut (⌘S / Ctrl+S by default) saves —
+ * the browser's own "save page" default is suppressed while the focus is here. Long lines scroll
+ * sideways, as code should,
* unless the Wrap toggle soft-wraps them; the toggle, Save and Cancel all live in the panel's
* preview header, and this component owns only the text.
*/
import { useEffect, useRef, useState } from "react";
import type { KeyboardEvent as ReactKeyboardEvent } from "react";
import { S } from "../../lib/strings";
+import { isShortcut } from "../../lib/shortcuts/match";
+import { currentPlatform } from "../../lib/shortcuts/platform";
+import { keymap } from "../../lib/shortcuts/store";
import { TEXT_PREVIEW_LIMIT, baseName, extOf } from "../../lib/workspace-tree";
import { CodeSurface } from "./code-block";
import { languageForExtension } from "./code-languages";
@@ -50,9 +54,10 @@ export function WorkspaceFileEditor({
const [composing, setComposing] = useState(false);
const onKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>): void => {
- if ((e.ctrlKey || e.metaKey) && !e.altKey && e.key.toLowerCase() === "s") {
+ if (isShortcut(e.nativeEvent, keymap(), "editor.save", currentPlatform())) {
+ // A held chord repeats: every repeat is kept from the browser (Save Page), one save runs.
e.preventDefault();
- onSave();
+ if (!e.repeat) onSave();
}
};
diff --git a/packages/web/src/features/company/handbook-page.tsx b/packages/web/src/features/company/handbook-page.tsx
index 7dc900a6..36109b3c 100644
--- a/packages/web/src/features/company/handbook-page.tsx
+++ b/packages/web/src/features/company/handbook-page.tsx
@@ -24,6 +24,10 @@ import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { formatBytes, formatDateTime, formatRelativeShort } from "../../lib/format";
+import { isShortcut } from "../../lib/shortcuts/match";
+import { currentPlatform } from "../../lib/shortcuts/platform";
+import { keymap } from "../../lib/shortcuts/store";
+import { useShortcutLabel } from "../../lib/shortcuts/use-keymap";
import { useDocumentTitle } from "../../lib/use-document-title";
import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
import { useLocale } from "../../state/locale";
@@ -237,11 +241,13 @@ export function HandbookPage() {
};
const onEditorKey = (e: ReactKeyboardEvent<HTMLTextAreaElement>) => {
- if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "s") {
+ if (isShortcut(e.nativeEvent, keymap(), "editor.save", currentPlatform())) {
+ // A held chord repeats: every repeat is kept from the browser (Save Page), one save runs.
e.preventDefault();
- void save();
+ if (!e.repeat) void save();
}
};
+ const saveShortcut = useShortcutLabel("editor.save");
const tree = useMemo(() => (files === null ? null : buildHandbookTree(files)), [files]);
const rows = useMemo(
@@ -359,7 +365,7 @@ export function HandbookPage() {
{editing ? (
<>
<span className="hidden text-[11px] text-gray-400 sm:inline dark:text-gray-500">
- {S.company.handbook.editorHint}
+ {S.company.handbook.editorHint(saveShortcut)}
</span>
<Button size="sm" disabled={saving} onClick={() => setEditing(false)}>
{S.common.cancel}
diff --git a/packages/web/src/features/dock/dock-panel.tsx b/packages/web/src/features/dock/dock-panel.tsx
index c545b0e5..e42ca1f3 100644
--- a/packages/web/src/features/dock/dock-panel.tsx
+++ b/packages/web/src/features/dock/dock-panel.tsx
@@ -42,7 +42,9 @@ import {
import { ConfirmModal } from "../../components/ui/confirm-modal";
import { Dropdown } from "../../components/ui/dropdown";
import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { Kbd } from "../../components/ui/kbd";
import { ICON_SIZE } from "../../lib/icon-scale";
+import { useDisplayedBinding, useShortcutLabel } from "../../lib/shortcuts/use-keymap";
import { toneDot } from "../../lib/tone";
import { useTerminalChrome } from "../terminal/terminal-appearance";
import {
@@ -250,6 +252,7 @@ function DockPicker({
/** The bottom (and merged) surface lays its choices out in a row, the right one as a list. */
horizontal: boolean;
}) {
+ const toggleChord = useDisplayedBinding("terminal.toggle");
const rowClass =
"flex items-center gap-2.5 rounded-md px-3 py-2 text-left text-sm text-gray-600 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-900 dark:text-gray-300 dark:hover:bg-gray-800 dark:hover:text-gray-100";
const row = (kind: PanelKind) => (
@@ -288,9 +291,9 @@ function DockPicker({
<GlyphIcon d={NAV_ICONS.terminal} size={ICON_SIZE.iconButton} />
</span>
<span className="min-w-0 flex-1 truncate">{S.terminal.title}</span>
- <kbd className="shrink-0 font-mono text-[10px] text-gray-400 dark:text-gray-500">
- Ctrl+`
- </kbd>
+ {toggleChord !== null && (
+ <Kbd chord={toggleChord} className="shrink-0 text-gray-400 dark:text-gray-500" />
+ )}
</button>
)}
{browserOffered && row("builtin-browser")}
@@ -328,6 +331,7 @@ export function DockPanel({
}: DockPanelProps) {
useSyncExternalStore(subscribeDock, dockVersion);
const terminals = useSyncExternalStore(subscribeTerminals, liveTerminals);
+ const closeShortcut = useShortcutLabel("terminal.close");
const browserOffered = useSyncExternalStore(subscribeBrowser, isBrowserOffered);
const terminalById = new Map(terminals.map((t) => [t.id, t]));
const { position, merged, tabs, activeKey } = view;
@@ -685,7 +689,8 @@ export function DockPanel({
if (tab.kind === "terminal") terminalOrdinals.set(tab.terminalId, terminalOrdinals.size + 1);
});
- // Ctrl+W inside a shown terminal asks for its tab to close, and takes the × path above,
+ // The terminal.close shortcut (⌃⌥` / Ctrl+Alt+` by default) inside a shown terminal asks for its
+ // tab to close, and takes the × path above,
// confirmation included. Only the dock holding that tab answers — and not while it is
// collapsing out, when the merged view may list the same tab — so no request is answered
// twice. The ref keeps one subscription per mount while the handler reads the current tabs.
@@ -749,7 +754,7 @@ export function DockPanel({
active={key === activeKey}
badge={false}
closeLabel={S.terminal.killShell}
- closeShortcut="Ctrl+W"
+ closeShortcut={closeShortcut ?? undefined}
onSelect={() => activateTab(key)}
onClose={() => closeTab(tab, label)}
/>
diff --git a/packages/web/src/features/dock/dock-terminal.ts b/packages/web/src/features/dock/dock-terminal.ts
index 104c24f9..49def4ef 100644
--- a/packages/web/src/features/dock/dock-terminal.ts
+++ b/packages/web/src/features/dock/dock-terminal.ts
@@ -1,9 +1,10 @@
/**
* The dock's terminal-side helpers: creating/adopting shells for terminal tabs, and the
- * global Ctrl+` hotkey. Split from dock-state.ts so the store stays pure (unit-testable
+ * global `terminal.toggle` command. Split from dock-state.ts so the store stays pure (unit-testable
* without fetch); this module owns every server round-trip a terminal tab needs.
*/
import { S } from "../../lib/strings";
+import { onCommand } from "../../lib/shortcuts/dispatcher";
import { toastError } from "../../components/ui/toast";
import {
HttpStatusError,
@@ -31,8 +32,8 @@ const HOME_CWD = "~";
* The Workspace a new shell should start in — the conversation's own directory, which is
* where its files are and what the agent has been working in. Published by the surface
* that knows it (the chat page for a Session, the draft page for the Workspace picked
- * there) rather than read from a store, because the Ctrl+` hotkey creates shells from a
- * module-scope listener with no React context to consult. Null = none known; the shell
+ * there) rather than read from a store, because the terminal toggle creates shells from a
+ * module-scope command handler with no React context to consult. Null = none known; the shell
* falls back to home.
*/
let workspaceCwd: string | null = null;
@@ -168,8 +169,8 @@ export function detachTerminal(id: string, position: DockPosition): void {
}
/**
- * Ctrl+`: hide the shown terminals, or bring them back — and with no terminal tab in
- * this conversation, adopt or create a shell (the async tail the store's synchronous
+ * The terminal toggle: hide the shown terminals, or bring them back — and with no terminal
+ * tab in this conversation, adopt or create a shell (the async tail the store's synchronous
* toggle hands off).
*/
export function toggleTerminal(): void {
@@ -179,15 +180,12 @@ export function toggleTerminal(): void {
/** Re-exported for callers that already know which shell they want on screen. */
export { showTerminal };
-// Ctrl+` (the Codex/VS Code binding), registered at module scope: a React-effect listener
-// leaves a window after first paint where the shortcut is silently dead — an effect runs
-// after paint, and a keypress can land in between. The store is page-global anyway; on
-// routes without the docks (login, /terminal) the toggle just flips hidden state.
-if (typeof window !== "undefined") {
- window.addEventListener("keydown", (event) => {
- if (!event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return;
- if (event.key !== "`" && event.code !== "Backquote") return;
- event.preventDefault();
- toggleTerminal();
- });
-}
+// `terminal.toggle` (Ctrl+` on every platform by default — the Codex/VS Code binding),
+// registered at module scope: a React-effect registration leaves a window after first paint
+// where the shortcut is silently dead — an effect runs after paint, and a keypress can land
+// in between. The store is page-global anyway; on routes without the docks (login,
+// /terminal) the toggle just flips hidden state. The chord itself is the keymap's: the
+// window dispatcher matches it and calls this handler.
+onCommand("terminal.toggle", () => {
+ toggleTerminal();
+});
diff --git a/packages/web/src/features/palette/command-palette.tsx b/packages/web/src/features/palette/command-palette.tsx
index d5268f27..717e113b 100644
--- a/packages/web/src/features/palette/command-palette.tsx
+++ b/packages/web/src/features/palette/command-palette.tsx
@@ -1,8 +1,8 @@
/**
- * Ctrl+P / Cmd+P command palette, VSCode-style: a top-centered input filtering a list of
- * actions; Enter (or click) runs the selected one. The palette is mechanism only — its
- * actions come from the mount point (app-palette.tsx), so a new capability registers an
- * action instead of claiming another global shortcut.
+ * The command palette (the `palette.toggle` shortcut, ⌥⌘P / Ctrl+Alt+P by default), VSCode-style:
+ * a top-centered input filtering a list of actions; Enter (or click) runs the selected one. The
+ * palette is mechanism only — its actions come from the mount point (app-palette.tsx), so a new
+ * capability registers an action instead of claiming another global shortcut.
*
* Keyboard model: ArrowUp/ArrowDown move the selection (wrapping), Enter runs, Escape
* closes through the shared esc-layer stack (modal.tsx), and the shortcut that opened it
@@ -11,37 +11,29 @@
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { useDialogLayer } from "../../components/ui/modal";
-import {
- filterPaletteActions,
- isCommandPaletteShortcut,
- type PaletteAction,
-} from "../../lib/command-palette";
+import { filterPaletteActions, type PaletteAction } from "../../lib/command-palette";
+import { onCommand } from "../../lib/shortcuts/dispatcher";
+import { useShortcutLabel } from "../../lib/shortcuts/use-keymap";
import { S } from "../../lib/strings";
-function isMacPlatform(): boolean {
- if (typeof navigator === "undefined") return false;
- return /Mac|iPhone|iPad|iPod/.test(navigator.userAgent);
-}
-
export function CommandPalette({ actions }: { actions: readonly PaletteAction[] }) {
const [open, setOpen] = useState(false);
const [query, setQuery] = useState("");
const [selected, setSelected] = useState(0);
- // Global shortcut, registered once (a functional update reads the latest `open`).
- // preventDefault on every match — otherwise the browser's print dialog opens underneath.
- useEffect(() => {
- const isMac = isMacPlatform();
- const onKey = (e: KeyboardEvent) => {
- if (!isCommandPaletteShortcut(e, isMac)) return;
- e.preventDefault();
- setOpen((o) => !o);
- setQuery("");
- setSelected(0);
- };
- window.addEventListener("keydown", onKey);
- return () => window.removeEventListener("keydown", onKey);
- }, []);
+ // The chord is the keymap's (lib/shortcuts): the window dispatcher matches it, calls this
+ // handler and prevents the browser default once it is handled. A functional update reads
+ // the latest `open`, so the handler registers once.
+ useEffect(
+ () =>
+ onCommand("palette.toggle", () => {
+ setOpen((o) => !o);
+ setQuery("");
+ setSelected(0);
+ }),
+ [],
+ );
+ const toggleShortcut = useShortcutLabel("palette.toggle");
// Escape closes it only while it is the topmost esc-consuming layer (shared with Modal /
// Dropdown, see modal.tsx), so an action's own dialog above it gets its Escape first; Tab
@@ -127,7 +119,7 @@ export function CommandPalette({ actions }: { actions: readonly PaletteAction[]
</ul>
)}
<div className="border-t border-gray-200 px-4 py-2 text-right text-xs text-gray-400 dark:border-gray-800 dark:text-gray-500">
- {S.commandPalette.hint}
+ {S.commandPalette.hint(toggleShortcut)}
</div>
</div>
</div>,
diff --git a/packages/web/src/features/terminal/terminal-page.tsx b/packages/web/src/features/terminal/terminal-page.tsx
index ed7b6adb..498e039d 100644
--- a/packages/web/src/features/terminal/terminal-page.tsx
+++ b/packages/web/src/features/terminal/terminal-page.tsx
@@ -155,7 +155,8 @@ export function TerminalPage() {
}, []);
/**
- * Ctrl+W inside the terminal takes the dock tab's × path — confirm, then end the shell —
+ * The terminal.close shortcut (⌃⌥` / Ctrl+Alt+` by default) inside the terminal takes the dock
+ * tab's × path — confirm, then end the shell —
* and then closes this window, which exists only to host that shell. A window the browser
* will not let a script close (one opened by address rather than by the dock's detach)
* stays, showing the exited shell with "New terminal" one click away. The kill is awaited
diff --git a/packages/web/src/features/terminal/terminal-view-pool.tsx b/packages/web/src/features/terminal/terminal-view-pool.tsx
index b52b9587..92641133 100644
--- a/packages/web/src/features/terminal/terminal-view-pool.tsx
+++ b/packages/web/src/features/terminal/terminal-view-pool.tsx
@@ -38,7 +38,8 @@ export function subscribeTerminalViewStates(listener: () => void): () => void {
const IDLE_STATE: TerminalViewState = { status: "connecting", info: null };
/**
- * Listeners for a shown terminal asking to be closed (Ctrl+W inside it). A view knows only
+ * Listeners for a shown terminal asking to be closed (the terminal.close shortcut inside it,
+ * ⌃⌥` / Ctrl+Alt+` by default). A view knows only
* its own id, while the dock holding the tab owns the close path — the confirm-then-kill
* its × runs — so the request is relayed by id to whichever dock has that tab.
*/
@@ -116,7 +117,7 @@ function shownIdsSnapshot(): string[] {
export function TerminalDockRuntime() {
const ids = useSyncExternalStore(subscribeDock, shownIdsSnapshot);
- // (The Ctrl+` hotkey is a module-scope listener in dock-terminal.ts — binding it
+ // (The terminal toggle is a module-scope command handler in dock-terminal.ts — binding it
// in an effect here left a post-paint window where the shortcut was dead.)
// Containers and view state of terminals that are no longer shown can go; a re-shown
diff --git a/packages/web/src/features/terminal/terminal-view.tsx b/packages/web/src/features/terminal/terminal-view.tsx
index b8fafd81..4d0bcfeb 100644
--- a/packages/web/src/features/terminal/terminal-view.tsx
+++ b/packages/web/src/features/terminal/terminal-view.tsx
@@ -18,6 +18,11 @@ import type { ITheme, Terminal as XTerminal } from "@xterm/xterm";
import { TerminalOpcode, decodeFrame, encodeFrame, encodeResize } from "./terminal-frames";
import { LinkClickTracker, openTerminalLink, positionFromPointer } from "./terminal-links";
import { useTheme } from "../../state/theme";
+import { hasCommandHandler } from "../../lib/shortcuts/dispatcher";
+import { currentPlatform } from "../../lib/shortcuts/platform";
+import { keymap } from "../../lib/shortcuts/store";
+import { terminalClipboardAction } from "../../lib/shortcuts/terminal-clipboard";
+import { terminalKeyAction } from "../../lib/shortcuts/terminal-keys";
import { useAuth } from "../../state/auth";
import { machineForTerminal, terminalUrl } from "../../lib/terminal-machines";
@@ -207,9 +212,9 @@ export interface TerminalViewProps {
/** OSC window-title changes, parsed by this client's own xterm from the byte stream. */
onTitle?: (title: string) => void;
/**
- * Ctrl+W pressed inside this terminal. The host decides what a close is — the dock tab's
- * confirm-then-kill, the standalone page's kill-then-close-window; with no handler the key
- * goes to the shell like any other.
+ * The `terminal.close` shortcut (⌃⌥` / Ctrl+Alt+` by default) pressed inside this terminal. The
+ * host decides what a close is — the dock tab's confirm-then-kill, the standalone page's
+ * kill-then-close-window; with no handler the key goes to the shell like any other.
*/
onCloseRequest?: () => void;
className?: string;
@@ -378,47 +383,53 @@ export function TerminalView({
};
/**
- * Terminal clipboard keys (the Windows Terminal / VS Code conventions — the single
- * Ctrl+Shift+C of the first cut was unreliable: Chrome grabs it for DevTools):
- * - copy: Ctrl+Shift+C, Ctrl+Insert, or plain Ctrl+C while a selection exists
- * (SIGINT still goes through when nothing is selected);
- * - paste: Ctrl+V, Ctrl+Shift+V and Shift+Insert all ride the browser's NATIVE paste
- * event into xterm's textarea (no clipboard permission involved) — the browser
- * fires `paste` for every one of these, so returning false (skip xterm's own key
- * handling, keep the browser default) is the whole implementation; calling the
- * async clipboard API here as well double-pastes.
+ * Keys the terminal decides before xterm does. xterm hands this handler its own
+ * textarea's events and nothing else, so everything here is seen only by the terminal
+ * that has focus.
+ *
+ * 1. Clipboard keys, a fixed platform convention (lib/shortcuts/terminal-clipboard.ts):
+ * a copy writes the selection here; a paste rides the browser's NATIVE paste event
+ * into xterm's textarea (no clipboard permission involved), so returning false —
+ * skip xterm's own key handling, keep the browser default — is the whole
+ * implementation, and calling the async clipboard API as well would double-paste.
+ * 2. The keymap (lib/shortcuts/terminal-keys.ts decides). A terminal-scope command
+ * (`terminal.close`, ⌃⌥` / Ctrl+Alt+` by default) is consumed here so it never
+ * reaches the shell. A global-scope command with a handler (Ctrl+` toggling the docks)
+ * is not sent to the shell either, but is left un-prevented so it bubbles to the
+ * window dispatcher that owns it — VS Code's "commands to skip shell". Anything else,
+ * including a chord no surface answers and Ctrl+W (readline's delete-word), goes to
+ * the shell as typed.
*/
+ const platform = currentPlatform();
term.attachCustomKeyEventHandler((event) => {
if (event.type !== "keydown") return true;
- const key = event.key.toLowerCase();
- const copyCombo =
- (event.ctrlKey && event.shiftKey && key === "c") ||
- (event.ctrlKey && !event.shiftKey && event.key === "Insert") ||
- (event.ctrlKey && !event.shiftKey && !event.altKey && key === "c" && term.hasSelection());
- if (copyCombo) {
+ const clipboard = terminalClipboardAction(event, platform, term.hasSelection());
+ if (clipboard === "copy") {
copySelection();
return false;
}
- const pasteCombo =
- (event.ctrlKey && !event.altKey && key === "v") ||
- (!event.ctrlKey && event.shiftKey && event.key === "Insert");
- if (pasteCombo) {
+ if (clipboard === "paste") {
return false; // native paste path (see above)
}
- // Ctrl+W closes this terminal when the host offers a close (the dock tab's ×, the
- // standalone page). Consumed here so it never reaches the shell, where it is
- // readline's delete-word, and seen only by the terminal that has focus — xterm hands
- // this handler its own textarea's events and nothing else, so no window-level
- // listener is involved. Browsers keep Ctrl+W for closing the browser tab and may act
- // first; the desktop shell delivers it here.
- const closeCombo =
- event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey && key === "w";
- if (closeCombo && callbacks.current.onCloseRequest) {
- event.preventDefault();
- callbacks.current.onCloseRequest();
- return false;
+ const action = terminalKeyAction(event, keymap(), platform, {
+ canClose: callbacks.current.onCloseRequest !== undefined,
+ hasHandler: hasCommandHandler,
+ });
+ switch (action) {
+ case "shell":
+ return true;
+ case "skip-shell":
+ return false;
+ case "consume":
+ event.preventDefault();
+ event.stopPropagation();
+ return false;
+ case "close":
+ event.preventDefault();
+ event.stopPropagation();
+ callbacks.current.onCloseRequest?.();
+ return false;
}
- return true;
});
/**
diff --git a/packages/web/src/features/workflows/workflow-app-page.tsx b/packages/web/src/features/workflows/workflow-app-page.tsx
index 2d8189a7..78412d92 100644
--- a/packages/web/src/features/workflows/workflow-app-page.tsx
+++ b/packages/web/src/features/workflows/workflow-app-page.tsx
@@ -4,9 +4,9 @@
*
* No sidebar, no chat, no tab strip — the page fills the window, which is what
* `penguin web --app …` opens and what a tab's "fill the app" action navigates to. There is
- * deliberately no chrome to leave by: the command palette (Ctrl+P / Ctrl+Shift+P, both, in
- * case the page takes one) carries the way out, "Exit full page", which lands on the chat of
- * that same Agent. The route sits outside the app shell (no ProjectProvider), so the exit
+ * deliberately no chrome to leave by: the command palette (the `palette.toggle` chord, re-raised
+ * from inside the page by forwardFrameKeys) carries the way out, "Exit full page", which lands
+ * on the chat of that same Agent. The route sits outside the app shell (no ProjectProvider), so the exit
* remembers the Project and Agent the way the shell does — its localStorage keys — before
* navigating.
*/
@@ -14,6 +14,7 @@ import { useEffect, useMemo, useState } from "react";
import { useNavigate, useParams, useSearchParams } from "react-router";
import * as api from "../../api/endpoints";
import type { PaletteAction } from "../../lib/command-palette";
+import { useShortcutLabel } from "../../lib/shortcuts/use-keymap";
import { S } from "../../lib/strings";
import {
appPageTab,
@@ -37,6 +38,7 @@ export function WorkflowAppPage() {
const navigate = useNavigate();
const [tab, setTab] = useState<WorkflowTab | null | undefined>(undefined);
const [failure, setFailure] = useState<string | null>(null);
+ const paletteShortcut = useShortcutLabel("palette.toggle");
useEffect(() => {
let alive = true;
@@ -116,7 +118,7 @@ export function WorkflowAppPage() {
? S.workflows.loadingPage
: (failure ?? S.workflows.noSuchPage)}
</span>
- <span>{S.workflows.exitHint}</span>
+ <span>{S.workflows.exitHint(paletteShortcut)}</span>
</div>
)}
<AppPalette extra={exit} />
diff --git a/packages/web/src/features/workflows/workflow-tabs.tsx b/packages/web/src/features/workflows/workflow-tabs.tsx
index 66250dec..d56f1dc0 100644
--- a/packages/web/src/features/workflows/workflow-tabs.tsx
+++ b/packages/web/src/features/workflows/workflow-tabs.tsx
@@ -14,6 +14,7 @@ import type { WorkflowInfo, WorkflowVersion } from "@prismshadow/penguin-server/
import * as api from "../../api/endpoints";
import { Button } from "../../components/ui/button";
import { formatDateTime } from "../../lib/format";
+import { useShortcutLabel } from "../../lib/shortcuts/use-keymap";
import { S } from "../../lib/strings";
import { toneInk, toneStrip } from "../../lib/tone";
import { forwardFrameKeys, readDocumentTheme, themeWorkflowFrame } from "../../lib/workflow-theme";
@@ -286,6 +287,7 @@ export function WorkflowFrame({
// Filling the app: the bar's button, or the page asking for it itself
// (`parent.postMessage({ type: "penguin:fill-app" }, "*")`) — only from our own frame.
const navigate = useNavigate();
+ const paletteShortcut = useShortcutLabel("palette.toggle");
const fillApp = useCallback(
() =>
void navigate(workflowAppPath(projectId, agentId, tab.workflowId, tab.key, tab.machineId)),
@@ -312,7 +314,12 @@ export function WorkflowFrame({
{tab.version !== null && <span>v{tab.version}</span>}
<span className="font-mono">{tab.revision}</span>
<span className="flex-1" />
- <Button variant="secondary" size="sm" title={S.workflows.fillAppHint} onClick={fillApp}>
+ <Button
+ variant="secondary"
+ size="sm"
+ title={S.workflows.fillAppHint(paletteShortcut)}
+ onClick={fillApp}
+ >
{S.workflows.fillApp}
</Button>
<Button
diff --git a/packages/web/src/lib/command-palette.ts b/packages/web/src/lib/command-palette.ts
index 3e550546..0219a52d 100644
--- a/packages/web/src/lib/command-palette.ts
+++ b/packages/web/src/lib/command-palette.ts
@@ -1,27 +1,9 @@
/**
- * Command palette (Ctrl+P / Cmd+P) pure logic: the shortcut matcher and the action
- * filter, kept apart from the component so they are testable without a DOM.
+ * Command palette pure logic: the action filter, kept apart from the component so it is
+ * testable without a DOM. The chord that opens the palette is the registry's `palette.toggle`
+ * (lib/shortcuts), matched by the window dispatcher.
*/
-/** Keyboard-event shape the matcher needs (a subset of KeyboardEvent, for easy testing). */
-export type ShortcutKeyEvent = Pick<
- KeyboardEvent,
- "key" | "ctrlKey" | "metaKey" | "altKey" | "shiftKey"
->;
-
-/**
- * Ctrl+P and Ctrl+Shift+P on Windows/Linux, Cmd+P and Cmd+Shift+P on macOS — the platform
- * is a parameter (read once at the call site) so the matcher stays a pure function. Shift is
- * accepted because a workflow page that fills the app may itself take Ctrl+P (print, its
- * own shortcut); the palette is that page's only way out, so it has to answer both chords.
- * A chord with Alt is never ours.
- */
-export function isCommandPaletteShortcut(e: ShortcutKeyEvent, isMac: boolean): boolean {
- if (e.key !== "p" && e.key !== "P") return false;
- if (e.altKey) return false;
- return isMac ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey;
-}
-
export interface PaletteAction {
id: string;
label: string;
diff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.ts
index 947b8d87..02ec12d8 100644
--- a/packages/web/src/lib/install-scope.ts
+++ b/packages/web/src/lib/install-scope.ts
@@ -295,6 +295,12 @@ export const KEY_RULES: readonly KeyRule[] = [
scope: "browser",
why: "Development vs company mode — the MODE, mirrored from ui_prefs; valid against any root.",
},
+ {
+ kind: "exact",
+ key: "penguin.keybindings",
+ scope: "browser",
+ why: "The account's shortcut overrides, mirrored from ui_prefs for the first keystroke and for cross-tab sync; names nothing on the server, and the server copy is the truth.",
+ },
{
kind: "exact",
key: "penguin.companyBetaNoticeShown",
diff --git a/packages/web/src/lib/shortcuts/chord.ts b/packages/web/src/lib/shortcuts/chord.ts
new file mode 100644
index 00000000..39514ea5
--- /dev/null
+++ b/packages/web/src/lib/shortcuts/chord.ts
@@ -0,0 +1,130 @@
+/**
+ * Chords as strings and as events. The string grammar is
+ * `(Mod\+|Ctrl\+|Alt\+|Shift\+)*<code>`, modifier tokens in that fixed order and at most one of
+ * each, `<code>` a `KeyboardEvent.code` value: "Mod+KeyW", "Ctrl+Backquote", "F5". It is what the
+ * registry authors, what the store persists and what the server validates, so `parseChord` and
+ * `serializeChord` round-trip exactly and anything malformed parses to null rather than to a
+ * guess.
+ */
+import type { Chord, KeyLike, Platform } from "./types";
+
+const CHORD_RE = /^(Mod\+)?(Ctrl\+)?(Alt\+)?(Shift\+)?([A-Za-z][A-Za-z0-9]*)$/;
+
+/** Parses the persisted form; null for anything outside the grammar (including an empty code). */
+export function parseChord(text: string): Chord | null {
+ const m = CHORD_RE.exec(text);
+ if (m === null) return null;
+ return {
+ code: m[5]!,
+ mod: m[1] !== undefined,
+ ctrl: m[2] !== undefined,
+ alt: m[3] !== undefined,
+ shift: m[4] !== undefined,
+ };
+}
+
+export function serializeChord(chord: Chord): string {
+ return `${chord.mod ? "Mod+" : ""}${chord.ctrl ? "Ctrl+" : ""}${chord.alt ? "Alt+" : ""}${
+ chord.shift ? "Shift+" : ""
+ }${chord.code}`;
+}
+
+/**
+ * Folds the platform into a chord: on Windows and Linux Control IS Mod, so a `Ctrl+` token there
+ * means the same key as `Mod+` and is recorded as Mod. On macOS the two stay distinct (⌃ vs ⌘).
+ */
+export function normalizeChord(chord: Chord, platform: Platform): Chord {
+ if (platform === "mac" || !chord.ctrl) return chord;
+ return { ...chord, mod: true, ctrl: false };
+}
+
+export function chordEquals(a: Chord | null, b: Chord | null): boolean {
+ if (a === null || b === null) return a === b;
+ return (
+ a.code === b.code &&
+ a.mod === b.mod &&
+ a.ctrl === b.ctrl &&
+ a.alt === b.alt &&
+ a.shift === b.shift
+ );
+}
+
+/** `KeyboardEvent.code` values of the modifier keys themselves; a press of one is never a chord. */
+const MODIFIER_CODES = new Set([
+ "ControlLeft",
+ "ControlRight",
+ "ShiftLeft",
+ "ShiftRight",
+ "AltLeft",
+ "AltRight",
+ "MetaLeft",
+ "MetaRight",
+ "OSLeft",
+ "OSRight",
+ "CapsLock",
+ "Fn",
+ "FnLock",
+]);
+
+export function isModifierCode(code: string): boolean {
+ return MODIFIER_CODES.has(code);
+}
+
+/**
+ * A `code` for events that carry none (some virtual keyboards and synthetic events): a letter
+ * maps to its US position, a digit to `DigitN`, the punctuation the registry uses to its code,
+ * and a named key (Escape, F5, ArrowUp) passes through. Anything else stays empty.
+ */
+export function codeFromKey(key: string): string {
+ if (key.length === 1) {
+ if (/[a-z]/i.test(key)) return `Key${key.toUpperCase()}`;
+ if (/[0-9]/.test(key)) return `Digit${key}`;
+ const punct: Record<string, string> = {
+ "`": "Backquote",
+ "-": "Minus",
+ "=": "Equal",
+ "[": "BracketLeft",
+ "]": "BracketRight",
+ "\\": "Backslash",
+ ";": "Semicolon",
+ "'": "Quote",
+ ",": "Comma",
+ ".": "Period",
+ "/": "Slash",
+ " ": "Space",
+ };
+ return punct[key] ?? "";
+ }
+ // "Unidentified", "Dead" and "Process" are the browser saying it does not know the key.
+ if (key === "Unidentified" || key === "Dead" || key === "Process") return "";
+ return /^[A-Z][A-Za-z0-9]*$/.test(key) ? key : "";
+}
+
+/**
+ * The chord an event IS, or null when it is not one: a modifier-only press, a key inside an IME
+ * composition (the IME owns it), a Meta chord on Windows/Linux (the Super key belongs to the
+ * OS), or an event with no usable code. An auto-repeat IS the chord: the caller still has to
+ * prevent the browser's own action for it (a held ⌘S would otherwise open Save Page from the
+ * first repeat on), and decides for itself not to run the command again.
+ */
+export function chordOf(e: KeyLike, platform: Platform): Chord | null {
+ if (e.isComposing === true) return null;
+ const code = e.code !== "" ? e.code : codeFromKey(e.key);
+ if (code === "" || isModifierCode(code)) return null;
+ if (platform === "mac") {
+ return { code, mod: e.metaKey, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey };
+ }
+ if (e.metaKey) return null;
+ return { code, mod: e.ctrlKey, ctrl: false, alt: e.altKey, shift: e.shiftKey };
+}
+
+/** True when the chord can be a user binding: it carries a modifier, or its key is a function key. */
+export function hasModifierOrFKey(chord: Chord): boolean {
+ return (
+ chord.mod ||
+ chord.ctrl ||
+ chord.alt ||
+ chord.shift ||
+ /^F([1-9]|1[0-9]|2[0-4])$/.test(chord.code)
+ );
+}
diff --git a/packages/web/src/lib/shortcuts/conflicts.ts b/packages/web/src/lib/shortcuts/conflicts.ts
new file mode 100644
index 00000000..112a4e8f
--- /dev/null
+++ b/packages/web/src/lib/shortcuts/conflicts.ts
@@ -0,0 +1,44 @@
+/**
+ * Two commands on one chord. Because the matcher's resolution is deterministic (focus scope
+ * first, then registry order) a conflict is a warning about which one will fire, not an error.
+ */
+import { chordEquals } from "./chord";
+import type { Chord, CommandId, Keymap, ShortcutCommand } from "./types";
+
+export type ConflictKind =
+ /** Same scope (or both global): only the first in registry order ever fires. */
+ | "same-scope"
+ /** One global, one focus-scoped: the focus command wins while its surface has focus, and the global one is unreachable there. */
+ | "shadowed";
+
+export interface Conflict {
+ chord: Chord;
+ /** The two ids in registry order: `a` is the one that fires in a same-scope conflict. */
+ a: CommandId;
+ b: CommandId;
+ kind: ConflictKind;
+}
+
+/** Every pair of commands bound to the same chord. Two different focus scopes never hold focus together and do not conflict. */
+export function findConflicts(keymap: Keymap, commands: readonly ShortcutCommand[]): Conflict[] {
+ const out: Conflict[] = [];
+ for (let i = 0; i < commands.length; i++) {
+ const a = commands[i]!;
+ const chordA = keymap.get(a.id) ?? null;
+ if (chordA === null) continue;
+ for (let j = i + 1; j < commands.length; j++) {
+ const b = commands[j]!;
+ if (!chordEquals(chordA, keymap.get(b.id) ?? null)) continue;
+ if (a.scope === b.scope) {
+ out.push({ chord: chordA, a: a.id, b: b.id, kind: "same-scope" });
+ } else if (a.scope === "global" || b.scope === "global") {
+ out.push({ chord: chordA, a: a.id, b: b.id, kind: "shadowed" });
+ }
+ }
+ }
+ return out;
+}
+
+export function conflictsOf(id: CommandId, conflicts: readonly Conflict[]): Conflict[] {
+ return conflicts.filter((c) => c.a === id || c.b === id);
+}
diff --git a/packages/web/src/lib/shortcuts/dispatcher.ts b/packages/web/src/lib/shortcuts/dispatcher.ts
new file mode 100644
index 00000000..35b03e95
--- /dev/null
+++ b/packages/web/src/lib/shortcuts/dispatcher.ts
@@ -0,0 +1,67 @@
+/**
+ * Global-scope shortcuts: one `window` keydown listener in the bubble phase, installed at module
+ * evaluation rather than in a React effect — an effect runs after paint, and a key can land in
+ * between (the reason dock-terminal.ts already gave for its own listener). Surfaces that own an
+ * action register a handler for the command id; the listener matches the event against the
+ * keymap and runs the handler, and `preventDefault`s only what was handled.
+ *
+ * Focus-scoped commands never come through here: the terminal decides its own keys inside
+ * xterm's key handler and stops their propagation, and the editors match `editor.save` in their
+ * own onKeyDown and prevent the default, which this listener respects by skipping any event that
+ * arrives already `defaultPrevented`.
+ */
+import { matchShortcut } from "./match";
+import { currentPlatform } from "./platform";
+import { keymap } from "./store";
+import type { CommandId } from "./types";
+
+/** Returning false declines the command so an earlier-registered handler may take it; anything else handles it. */
+export type CommandHandler = () => boolean | void;
+
+const handlers = new Map<CommandId, CommandHandler[]>();
+
+/** Registers a handler; the last registered runs first. Returns the unregister function. */
+export function onCommand(id: CommandId, handler: CommandHandler): () => void {
+ const list = handlers.get(id) ?? [];
+ list.push(handler);
+ handlers.set(id, list);
+ return () => {
+ const current = handlers.get(id);
+ if (current === undefined) return;
+ const index = current.lastIndexOf(handler);
+ if (index >= 0) current.splice(index, 1);
+ };
+}
+
+/** Whether any surface currently answers the command (a chord with no handler goes on to whatever it meant before). */
+export function hasCommandHandler(id: CommandId): boolean {
+ return (handlers.get(id)?.length ?? 0) > 0;
+}
+
+/** Runs the command; true when some handler took it. */
+export function runCommand(id: CommandId): boolean {
+ const list = handlers.get(id);
+ if (list === undefined) return false;
+ for (let i = list.length - 1; i >= 0; i--) {
+ if (list[i]!() !== false) return true;
+ }
+ return false;
+}
+
+/**
+ * The window's keydown listener. A held chord auto-repeats: a repeat of a command that has a
+ * handler is kept from the browser's own action (a binding on ⌘P would print from the first
+ * repeat on) but does not run the command again, so a held ⌥⌘1 toggles the sidebar once.
+ */
+export function handleShortcutKeydown(event: KeyboardEvent): void {
+ if (event.defaultPrevented) return;
+ const id = matchShortcut(event, keymap(), ["global"], currentPlatform());
+ if (id === null) return;
+ if (event.repeat) {
+ if (hasCommandHandler(id)) event.preventDefault();
+ return;
+ }
+ if (runCommand(id)) event.preventDefault();
+}
+
+if (typeof window !== "undefined") window.addEventListener("keydown", handleShortcutKeydown);
diff --git a/packages/web/src/lib/shortcuts/format.ts b/packages/web/src/lib/shortcuts/format.ts
new file mode 100644
index 00000000..44f0de54
--- /dev/null
+++ b/packages/web/src/lib/shortcuts/format.ts
@@ -0,0 +1,124 @@
+/**
+ * Chords as the platform writes them: Apple's glyph run on macOS (`⌘W`, `⌃⇧\``, `⌥⌘I` — the
+ * order Apple's menus use, no separators), `Ctrl+Alt+Shift+W` elsewhere. Pure; the layout map,
+ * when the browser exposes one, turns a physical letter code into the character the key types.
+ */
+import type { Chord, CommandId, Keymap, Platform } from "./types";
+
+const MAC_KEY_GLYPHS: Record<string, string> = {
+ Escape: "⎋",
+ Enter: "↩",
+ NumpadEnter: "↩",
+ Tab: "⇥",
+ Backspace: "⌫",
+ Delete: "⌦",
+ ArrowLeft: "←",
+ ArrowUp: "↑",
+ ArrowRight: "→",
+ ArrowDown: "↓",
+ Space: "Space",
+ Home: "↖",
+ End: "↘",
+ PageUp: "⇞",
+ PageDown: "⇟",
+};
+
+const OTHER_KEY_NAMES: Record<string, string> = {
+ Escape: "Esc",
+ Enter: "Enter",
+ NumpadEnter: "Enter",
+ Tab: "Tab",
+ Backspace: "Backspace",
+ Delete: "Delete",
+ Insert: "Insert",
+ ArrowLeft: "←",
+ ArrowUp: "↑",
+ ArrowRight: "→",
+ ArrowDown: "↓",
+ Space: "Space",
+ Home: "Home",
+ End: "End",
+ PageUp: "PgUp",
+ PageDown: "PgDn",
+};
+
+const PUNCTUATION: Record<string, string> = {
+ Backquote: "`",
+ Minus: "-",
+ Equal: "=",
+ BracketLeft: "[",
+ BracketRight: "]",
+ Backslash: "\\",
+ Semicolon: ";",
+ Quote: "'",
+ Comma: ",",
+ Period: ".",
+ Slash: "/",
+ IntlBackslash: "\\",
+};
+
+/**
+ * The character a code types on the US layout, lower-case, or null for a key that types none
+ * (Escape, F5, the arrows). What layout relocation looks for on another layout.
+ */
+export function usCharacter(code: string): string | null {
+ const letter = /^Key([A-Z])$/.exec(code)?.[1];
+ if (letter !== undefined) return letter.toLowerCase();
+ const digit = /^Digit([0-9])$/.exec(code)?.[1];
+ if (digit !== undefined) return digit;
+ return PUNCTUATION[code] ?? null;
+}
+
+/**
+ * The text for the non-modifier key: what the key types on the current layout when the browser
+ * exposes one (a relocated `Semicolon` on Dvorak reads "S"), else its US character or name; the
+ * code itself when nothing better is known.
+ */
+export function keyLabel(
+ code: string,
+ platform: Platform,
+ layout?: ReadonlyMap<string, string>,
+): string {
+ const typed = layout?.get(code);
+ if (typed !== undefined && typed.length === 1 && typed.trim() !== "") return typed.toUpperCase();
+ const letter = /^Key([A-Z])$/.exec(code)?.[1];
+ if (letter !== undefined) return letter;
+ const digit = /^Digit([0-9])$/.exec(code)?.[1];
+ if (digit !== undefined) return digit;
+ const numpad = /^Numpad([0-9])$/.exec(code)?.[1];
+ if (numpad !== undefined) return `Num ${numpad}`;
+ const punct = PUNCTUATION[code];
+ if (punct !== undefined) return punct;
+ const named = platform === "mac" ? MAC_KEY_GLYPHS[code] : OTHER_KEY_NAMES[code];
+ return named ?? code;
+}
+
+export function formatChord(
+ chord: Chord,
+ platform: Platform,
+ layout?: ReadonlyMap<string, string>,
+): string {
+ const key = keyLabel(chord.code, platform, layout);
+ if (platform === "mac") {
+ return `${chord.ctrl ? "⌃" : ""}${chord.alt ? "⌥" : ""}${chord.shift ? "⇧" : ""}${
+ chord.mod ? "⌘" : ""
+ }${key}`;
+ }
+ const parts: string[] = [];
+ if (chord.mod || chord.ctrl) parts.push("Ctrl");
+ if (chord.alt) parts.push("Alt");
+ if (chord.shift) parts.push("Shift");
+ parts.push(key);
+ return parts.join("+");
+}
+
+/** The command's current chord as text, or null when it is unbound. */
+export function formatBinding(
+ id: CommandId,
+ keymap: Keymap,
+ platform: Platform,
+ layout?: ReadonlyMap<string, string>,
+): string | null {
+ const chord = keymap.get(id) ?? null;
+ return chord === null ? null : formatChord(chord, platform, layout);
+}
diff --git a/packages/web/src/lib/shortcuts/match.ts b/packages/web/src/lib/shortcuts/match.ts
new file mode 100644
index 00000000..1d2b8c80
--- /dev/null
+++ b/packages/web/src/lib/shortcuts/match.ts
@@ -0,0 +1,62 @@
+/**
+ * Matching an event against the resolved keymap. Pure: the caller supplies the keymap, the
+ * scopes that currently hold focus and the platform, and gets back a command id or null.
+ */
+import { chordEquals, chordOf } from "./chord";
+import { usCharacter } from "./format";
+import { SHORTCUT_COMMANDS } from "./registry";
+import type { Chord, CommandId, KeyLike, Keymap, Platform, ShortcutScope } from "./types";
+
+/**
+ * The command the event runs among the commands whose scope is in `scopes`: a focus scope
+ * (terminal, editor) beats global, and among equals the registry order decides. Deterministic,
+ * which is what lets a conflicting user binding be a warning rather than an error.
+ */
+export function matchShortcut(
+ e: KeyLike,
+ keymap: Keymap,
+ scopes: readonly ShortcutScope[],
+ platform: Platform,
+): CommandId | null {
+ const chord = chordOf(e, platform);
+ if (chord === null) return null;
+ let global: CommandId | null = null;
+ for (const cmd of SHORTCUT_COMMANDS) {
+ if (!scopes.includes(cmd.scope)) continue;
+ if (!chordEquals(keymap.get(cmd.id) ?? null, chord)) continue;
+ if (cmd.scope !== "global") return cmd.id;
+ global ??= cmd.id;
+ }
+ return global;
+}
+
+/** One command's own test, for a surface that owns the action (the editors' save). */
+export function isShortcut(e: KeyLike, keymap: Keymap, id: CommandId, platform: Platform): boolean {
+ const bound = keymap.get(id) ?? null;
+ if (bound === null) return false;
+ return chordEquals(chordOf(e, platform), bound);
+}
+
+/**
+ * Defaults are authored in US key positions. Where the browser exposes the keyboard layout
+ * (`navigator.keyboard.getLayoutMap()`, a `code → character` map), a default whose key types a
+ * different character than it does on US is moved to the key that types the US character, so
+ * "the S key" means the key that types S: `KeyZ` on AZERTY for W, `Semicolon` on US-Dvorak for
+ * S. Every code in the map is a candidate — Dvorak puts letters on the punctuation positions.
+ * User-recorded chords are physical and are never relocated.
+ *
+ * One layout the map cannot describe: macOS's "Dvorak – QWERTY ⌘" input source types Dvorak
+ * but switches to QWERTY while ⌘ is held, so relocation moves ⌘S to `Semicolon` there while the
+ * user's ⌘S arrives on `KeyS`. That source wants relocation off for Mod chords; nothing exposes
+ * it, so it is not handled.
+ */
+export function relocateChord(chord: Chord, layout: ReadonlyMap<string, string>): Chord {
+ const wanted = usCharacter(chord.code);
+ if (wanted === null) return chord;
+ const produced = layout.get(chord.code);
+ if (produced === undefined || produced.toLowerCase() === wanted) return chord;
+ for (const [code, char] of layout) {
+ if (char.toLowerCase() === wanted) return { ...chord, code };
+ }
+ return chord;
+}
diff --git a/packages/web/src/lib/shortcuts/platform.ts b/packages/web/src/lib/shortcuts/platform.ts
new file mode 100644
index 00000000..1ab4591a
--- /dev/null
+++ b/packages/web/src/lib/shortcuts/platform.ts
@@ -0,0 +1,64 @@
+/**
+ * Which platform's modifier conventions apply, and which host runs the page. Detected once from
+ * `navigator` and cached; the tests set it explicitly. Electron's renderer leaves the user agent
+ * alone and exposes `userAgentData`, so the same detection serves the desktop app.
+ */
+import type { HostKind, Platform } from "./types";
+
+export interface NavigatorLike {
+ userAgentData?: { platform?: string };
+ platform?: string;
+ userAgent?: string;
+}
+
+/**
+ * `userAgentData.platform` first, then `navigator.platform`, then the user agent. iPadOS reports
+ * itself as a Mac and its hardware keyboards use ⌘, so it is a mac here. Everything that is not
+ * a Mac or Windows — Linux, Chrome OS, Android — takes the Ctrl conventions.
+ */
+export function detectPlatform(nav: NavigatorLike | undefined): Platform {
+ if (nav === undefined) return "linux";
+ const uaPlatform = nav.userAgentData?.platform;
+ if (uaPlatform !== undefined && uaPlatform !== "") {
+ if (/^mac/i.test(uaPlatform)) return "mac";
+ if (/^win/i.test(uaPlatform)) return "windows";
+ return "linux";
+ }
+ const platform = nav.platform ?? "";
+ if (/^(Mac|iPhone|iPad|iPod)/.test(platform)) return "mac";
+ if (/^Win/.test(platform)) return "windows";
+ if (platform !== "") return "linux";
+ const ua = nav.userAgent ?? "";
+ if (/Mac|iPhone|iPad/.test(ua)) return "mac";
+ if (/Windows/.test(ua)) return "windows";
+ return "linux";
+}
+
+/** The desktop shell is Electron, which names itself in the user agent. Only the reserved-chord notice reads this. */
+export function detectHost(nav: NavigatorLike | undefined): HostKind {
+ return /Electron\//.test(nav?.userAgent ?? "") ? "desktop" : "browser";
+}
+
+let platformOverride: Platform | null = null;
+let detectedPlatform: Platform | null = null;
+let detectedHost: HostKind | null = null;
+
+function currentNavigator(): NavigatorLike | undefined {
+ return typeof navigator === "undefined" ? undefined : (navigator as NavigatorLike);
+}
+
+export function currentPlatform(): Platform {
+ if (platformOverride !== null) return platformOverride;
+ detectedPlatform ??= detectPlatform(currentNavigator());
+ return detectedPlatform;
+}
+
+export function currentHost(): HostKind {
+ detectedHost ??= detectHost(currentNavigator());
+ return detectedHost;
+}
+
+/** Tests pin the platform; null goes back to detection. */
+export function setPlatformForTests(platform: Platform | null): void {
+ platformOverride = platform;
+}
diff --git a/packages/web/src/lib/shortcuts/registry.ts b/packages/web/src/lib/shortcuts/registry.ts
new file mode 100644
index 00000000..d05e5938
--- /dev/null
+++ b/packages/web/src/lib/shortcuts/registry.ts
@@ -0,0 +1,69 @@
+/**
+ * The command registry: every user-rebindable shortcut, with its scope, its settings-page group
+ * and its default chord per platform. This is the one place a default is authored; every surface
+ * that shows a chord formats it from here, and the surface that owns an action asks the matcher
+ * whether an event is that command rather than reading modifier keys itself.
+ *
+ * Defaults are written with `Mod`, which resolves to ⌘ on macOS and Ctrl elsewhere. A literal
+ * `Ctrl+` token is reserved for the case where the macOS binding must NOT follow ⌘, and the
+ * registry test holds that line. Defaults also stay off the browsers' own shortcuts
+ * (reserved.ts), which is why most sit on Mod+Alt — ⌥⌘ on macOS, Ctrl+Alt elsewhere; the registry
+ * test holds that line too, and names the defaults that still share a chord with a browser.
+ */
+import { normalizeChord, parseChord } from "./chord";
+import type { Chord, CommandId, Platform, ShortcutCommand, ShortcutGroup } from "./types";
+
+export const SHORTCUT_COMMANDS: readonly ShortcutCommand[] = [
+ {
+ id: "palette.toggle",
+ scope: "global",
+ group: "general",
+ // Mod+P is the browser's Print. On macOS this takes over Chrome's ⌥⌘P (Page Setup).
+ defaults: { default: "Mod+Alt+KeyP" },
+ },
+ {
+ id: "terminal.toggle",
+ scope: "global",
+ group: "terminal",
+ // ⌃` on macOS too: ⌘` is macOS's own window cycling, and VS Code and Codex use ⌃` there.
+ defaults: { default: "Ctrl+Backquote" },
+ },
+ {
+ id: "terminal.close",
+ scope: "terminal",
+ group: "terminal",
+ // Mod+W closes the browser tab. The toggle's key plus Alt, literal Control like the toggle.
+ defaults: { default: "Ctrl+Alt+Backquote" },
+ },
+ {
+ id: "editor.save",
+ scope: "editor",
+ group: "editor",
+ // Every editor's save chord: the editors take it from the browser's Save Page on purpose.
+ defaults: { default: "Mod+KeyS" },
+ },
+];
+
+/** The settings page draws groups in this order. */
+export const SHORTCUT_GROUPS: readonly ShortcutGroup[] = [
+ "general",
+ "panels",
+ "terminal",
+ "editor",
+];
+
+const BY_ID = new Map(SHORTCUT_COMMANDS.map((cmd) => [cmd.id, cmd]));
+
+export function commandById(id: CommandId): ShortcutCommand {
+ const cmd = BY_ID.get(id);
+ if (cmd === undefined) throw new Error(`unknown shortcut command: ${id}`);
+ return cmd;
+}
+
+/** The platform's own default when the command has one, else the shared default; normalized for the platform. */
+export function defaultChord(cmd: ShortcutCommand, platform: Platform): Chord | null {
+ const text = cmd.defaults[platform] !== undefined ? cmd.defaults[platform] : cmd.defaults.default;
+ if (text === null || text === undefined) return null;
+ const chord = parseChord(text);
+ return chord === null ? null : normalizeChord(chord, platform);
+}
diff --git a/packages/web/src/lib/shortcuts/reserved.ts b/packages/web/src/lib/shortcuts/reserved.ts
new file mode 100644
index 00000000..3ed45f13
--- /dev/null
+++ b/packages/web/src/lib/shortcuts/reserved.ts
@@ -0,0 +1,331 @@
+/**
+ * Chords the page never receives, or receives at a price. `browserReserved` names the chords
+ * Chromium, Firefox and Safari act on before the page sees them (a binding to one of these is dead
+ * in a browser tab and only works in the desktop app). `browserCommon` names the chords a browser
+ * binds but acts on only when the page leaves the key alone (a binding to one of these works in a
+ * browser tab and takes over that browser function there, as ⌘P would take over Print).
+ * `desktopReserved` names what the desktop shell itself binds: "shell" for the keys it takes on
+ * `before-input-event` before the page, "menu" for its menu-role accelerators, which the page CAN
+ * take (an accelerator fires only for a key the page left alone) at the cost of shadowing that
+ * menu action.
+ */
+import { chordEquals, normalizeChord, parseChord } from "./chord";
+import type { Chord, HostKind, Platform } from "./types";
+
+/** Chord strings are written in the registry grammar; `Ctrl+` is the literal Control key (macOS only differs). */
+const BROWSER_ALL = [
+ "Mod+KeyW", // close tab
+ "Mod+Shift+KeyW", // close window
+ "Mod+KeyT", // new tab
+ "Mod+Shift+KeyT", // reopen closed tab
+ "Mod+KeyN", // new window
+ "Mod+Shift+KeyN", // new private / incognito window
+ "Mod+Digit1", // switch to tab 1…
+ "Mod+Digit2",
+ "Mod+Digit3",
+ "Mod+Digit4",
+ "Mod+Digit5",
+ "Mod+Digit6",
+ "Mod+Digit7",
+ "Mod+Digit8",
+ "Mod+Digit9", // …last tab
+ "Ctrl+Tab", // next tab
+ "Ctrl+Shift+Tab", // previous tab
+ "Ctrl+PageUp", // previous tab
+ "Ctrl+PageDown", // next tab
+];
+
+const BROWSER_BY_PLATFORM: Record<Platform, readonly string[]> = {
+ windows: [
+ "F11", // full screen
+ "Alt+F4", // close window (the OS)
+ ],
+ linux: [
+ "F11", // full screen
+ "Alt+F4", // close window (the desktop environment)
+ ],
+ mac: [
+ "Mod+KeyQ", // quit
+ "Mod+KeyH", // hide
+ "Mod+Alt+KeyH", // hide others
+ "Mod+KeyM", // minimize
+ "Mod+Space", // Spotlight
+ "Mod+Tab", // app switcher
+ "Mod+Backquote", // next window of the app
+ "Ctrl+ArrowUp", // Mission Control
+ "Ctrl+ArrowDown", // application windows
+ "Ctrl+ArrowLeft", // previous space
+ "Ctrl+ArrowRight", // next space
+ "Ctrl+Space", // input source switch
+ ],
+};
+
+/**
+ * The browsers' own functions on chords the page can take, read from Chrome's and Safari's
+ * published shortcut tables and from Firefox's key definitions (browser-sets.inc.xhtml) and
+ * DevTools table; a browser in parentheses is the one that binds the chord for that function.
+ * Chords the reserved tables above hold are not repeated.
+ */
+const COMMON_ALL = [
+ "Mod+KeyP", // print
+ "Mod+KeyS", // save page
+ "Mod+KeyO", // open a file
+ "Mod+KeyF", // find
+ "Mod+KeyG", // find next
+ "Mod+Shift+KeyG", // find previous
+ "Mod+KeyE", // search (on macOS: find the selection)
+ "Mod+KeyK", // search the web
+ "Mod+KeyL", // address bar
+ "Mod+KeyR", // reload
+ "Mod+Shift+KeyR", // reload, ignoring the cache (Safari: Reader)
+ "Mod+KeyD", // bookmark this page
+ "Mod+Shift+KeyD", // bookmark all tabs (Safari: add to Reading List)
+ "Mod+KeyB", // bookmarks sidebar (Firefox)
+ "Mod+Shift+KeyB", // bookmarks bar
+ "Mod+Shift+KeyO", // bookmark manager
+ "Mod+KeyJ", // downloads
+ "Mod+Shift+KeyH", // history (on macOS also the home page, Chrome and Safari)
+ "Mod+KeyU", // view source
+ "Mod+KeyI", // page info (Firefox)
+ "Mod+Shift+KeyI", // developer tools (on macOS: Chrome's email a link)
+ "Mod+Shift+KeyJ", // console (on macOS: Chrome's downloads)
+ "Mod+Alt+Shift+KeyI", // browser toolbox
+ "Mod+Alt+KeyZ", // sidebar (Firefox; on macOS its debugger)
+ "Mod+Shift+KeyM", // switch profile (Chrome)
+ "Mod+Shift+KeyA", // add-ons (Firefox)
+ "Mod+Shift+KeyS", // screenshot (Firefox)
+ "Mod+Shift+KeyX", // text direction (Firefox)
+ "Mod+Shift+Delete", // clear browsing data
+ "Mod+Equal", // zoom in
+ "Mod+Shift+Equal", // zoom in (+)
+ "Mod+Minus", // zoom out
+ "Mod+Shift+Minus", // zoom out (_, Firefox)
+ "Mod+Digit0", // actual size
+ "Mod+KeyZ", // undo
+ "Mod+Shift+KeyZ", // redo (on Windows: Firefox's debugger)
+ "Mod+KeyX", // cut
+ "Mod+KeyC", // copy
+ "Mod+KeyV", // paste
+ "Mod+KeyA", // select all
+ "Ctrl+KeyM", // mute the tab (Firefox)
+ "Ctrl+Shift+PageUp", // move the tab left (Chrome)
+ "Ctrl+Shift+PageDown", // move the tab right (Chrome)
+ "F3", // find next
+ "Shift+F3", // find previous (Firefox)
+ "F5", // reload
+ "Shift+F5", // reload, ignoring the cache (Firefox: profiler)
+ "F7", // caret browsing
+ "Shift+F7", // style editor (Firefox)
+ "Shift+F9", // storage inspector (Firefox)
+ "F12", // developer tools
+];
+
+/** Shared by Windows and Linux; macOS spells these functions with ⌘ and ⌥ instead. */
+const COMMON_OFF_MAC = [
+ "Mod+KeyH", // history
+ "Alt+ArrowLeft", // back
+ "Alt+ArrowRight", // forward
+ "Alt+Home", // home page
+ "Alt+KeyD", // address bar
+ "Alt+KeyE", // browser menu (Chrome)
+ "Alt+KeyF", // browser menu (Chrome)
+ "Alt+Shift+KeyA", // focus inactive dialogs (Chrome)
+ "Alt+Shift+KeyI", // feedback (Chrome)
+ "Alt+Shift+KeyN", // split view (Chrome)
+ "Alt+Shift+KeyT", // toolbar focus (Chrome)
+ "Mod+Shift+KeyC", // pick an element (Firefox)
+ "Mod+Shift+KeyE", // network monitor (Firefox)
+ "Mod+Shift+KeyK", // web console (Firefox)
+ "Mod+Shift+BracketRight", // picture-in-picture (Firefox)
+ "Mod+Alt+KeyU", // open tabs sidebar (Firefox)
+ "Mod+Alt+KeyX", // AI chatbot sidebar (Firefox)
+ "Mod+F5", // reload, ignoring the cache (Firefox)
+ "Mod+F6", // skip to the page (Chrome)
+ "F1", // help (Chrome)
+ "F6", // address bar (Chrome)
+ "F10", // toolbar focus (Chrome)
+];
+
+const COMMON_BY_PLATFORM: Record<Platform, readonly string[]> = {
+ windows: [
+ "Mod+KeyY", // redo (Firefox)
+ "F9", // reader view (Firefox)
+ ],
+ linux: [
+ "Mod+Shift+KeyY", // downloads (Firefox)
+ "Mod+Alt+KeyR", // reader view (Firefox)
+ "Mod+BracketLeft", // back (Firefox)
+ "Mod+BracketRight", // forward (Firefox)
+ "Alt+Digit1", // switch to tab 1… (Firefox)
+ "Alt+Digit2",
+ "Alt+Digit3",
+ "Alt+Digit4",
+ "Alt+Digit5",
+ "Alt+Digit6",
+ "Alt+Digit7",
+ "Alt+Digit8",
+ "Alt+Digit9", // …last tab
+ ],
+ mac: [
+ "Mod+KeyY", // history
+ "Mod+Comma", // settings
+ "Mod+Period", // stop loading (Firefox)
+ "Mod+BracketLeft", // back
+ "Mod+BracketRight", // forward
+ "Mod+ArrowLeft", // back
+ "Mod+ArrowRight", // forward
+ "Mod+Shift+Backslash", // tab overview (Safari)
+ "Mod+Shift+Backspace", // clear browsing data
+ "Mod+Shift+KeyF", // full screen (Firefox)
+ "Mod+Ctrl+KeyF", // full screen
+ "Mod+Ctrl+Digit1", // bookmarks sidebar (Safari)
+ "Mod+Ctrl+Digit2", // Reading List sidebar (Safari)
+ "Mod+Alt+KeyB", // bookmark manager (Chrome)
+ "Mod+Alt+KeyC", // inspect an element
+ "Mod+Alt+KeyE", // network monitor (Firefox)
+ "Mod+Alt+KeyF", // search the web
+ "Mod+Alt+KeyI", // developer tools
+ "Mod+Alt+KeyJ", // JavaScript console
+ "Mod+Alt+KeyK", // web console (Firefox)
+ "Mod+Alt+KeyM", // responsive design mode (Firefox)
+ "Mod+Alt+KeyN", // split view (Chrome)
+ "Mod+Alt+KeyP", // page setup (Chrome)
+ "Mod+Alt+KeyR", // reader view (Firefox)
+ "Mod+Alt+KeyU", // view source
+ "Mod+Alt+Shift+KeyA", // focus inactive dialogs (Chrome)
+ "Mod+Alt+Shift+BracketRight", // picture-in-picture (Firefox)
+ "Mod+Alt+ArrowUp", // cycle the focus through the toolbars (Chrome)
+ "Mod+Alt+ArrowDown",
+ "Ctrl+KeyU", // open tabs sidebar (Firefox)
+ "Ctrl+KeyX", // AI chatbot sidebar (Firefox)
+ "Ctrl+KeyZ", // sidebar (Firefox)
+ ],
+};
+
+/**
+ * Keys the shell takes on `before-input-event`, before the page sees them. None today: the
+ * shell (packages/desktop/src/main.ts) binds nothing there, so F10 and F12 reach the page and
+ * DevTools is the View menu's accelerator below. The table stays so a shell that does start
+ * taking keys has one place to say so.
+ */
+const SHELL_BY_PLATFORM: Record<Platform, readonly string[]> = {
+ windows: [],
+ linux: [],
+ mac: [],
+};
+
+/**
+ * Electron's role accelerators in the shell's menu template (packages/desktop/src/menu.ts:
+ * mac app menu, `editMenu`, `viewMenu`, `windowMenu`, plus `quit` in the Windows/Linux File
+ * menu), read from Electron 43.2's lib/browser/api/menu-item-roles.ts. `zoomIn` is
+ * `CommandOrControl+Plus`, which Electron's accelerator parser turns into Shift+= (the plus is a
+ * shifted character); `quit` has no accelerator on Windows; `redo` is Control+Y on Windows only.
+ */
+const MENU_BY_PLATFORM: Record<Platform, readonly string[]> = {
+ mac: [
+ "Mod+KeyZ", // undo
+ "Mod+Shift+KeyZ", // redo
+ "Mod+KeyX", // cut
+ "Mod+KeyC", // copy
+ "Mod+KeyV", // paste
+ "Mod+Alt+Shift+KeyV", // paste and match style
+ "Mod+KeyA", // select all
+ "Mod+KeyR", // reload
+ "Mod+Shift+KeyR", // force reload
+ "Mod+Alt+KeyI", // toggle DevTools
+ "Mod+Digit0", // actual size
+ "Mod+Shift+Equal", // zoom in
+ "Mod+Minus", // zoom out
+ "Mod+Ctrl+KeyF", // toggle full screen
+ "Mod+KeyM", // minimize
+ "Mod+KeyH", // hide
+ "Mod+Alt+KeyH", // hide others
+ "Mod+KeyQ", // quit
+ ],
+ windows: [
+ "Ctrl+KeyZ", // undo
+ "Ctrl+KeyY", // redo
+ "Ctrl+KeyX", // cut
+ "Ctrl+KeyC", // copy
+ "Ctrl+KeyV", // paste
+ "Ctrl+KeyA", // select all
+ "Ctrl+KeyR", // reload
+ "Ctrl+Shift+KeyR", // force reload
+ "Ctrl+Shift+KeyI", // toggle DevTools
+ "Ctrl+Digit0", // actual size
+ "Ctrl+Shift+Equal", // zoom in
+ "Ctrl+Minus", // zoom out
+ "F11", // toggle full screen
+ "Ctrl+KeyM", // minimize
+ "Ctrl+KeyW", // close (hides the window to the tray)
+ ],
+ linux: [
+ "Ctrl+KeyZ", // undo
+ "Ctrl+Shift+KeyZ", // redo
+ "Ctrl+KeyX", // cut
+ "Ctrl+KeyC", // copy
+ "Ctrl+KeyV", // paste
+ "Ctrl+KeyA", // select all
+ "Ctrl+KeyR", // reload
+ "Ctrl+Shift+KeyR", // force reload
+ "Ctrl+Shift+KeyI", // toggle DevTools
+ "Ctrl+Digit0", // actual size
+ "Ctrl+Shift+Equal", // zoom in
+ "Ctrl+Minus", // zoom out
+ "F11", // toggle full screen
+ "Ctrl+KeyM", // minimize
+ "Ctrl+KeyW", // close (hides the window to the tray)
+ "Ctrl+KeyQ", // quit
+ ],
+};
+
+const cache = new Map<string, Chord[]>();
+
+function table(name: string, texts: readonly string[], platform: Platform): Chord[] {
+ const key = `${name}:${platform}`;
+ let parsed = cache.get(key);
+ if (parsed === undefined) {
+ parsed = [];
+ for (const text of texts) {
+ const chord = parseChord(text);
+ if (chord === null) throw new Error(`malformed reserved chord: ${text}`);
+ parsed.push(normalizeChord(chord, platform));
+ }
+ cache.set(key, parsed);
+ }
+ return parsed;
+}
+
+function inTable(chord: Chord, parsed: readonly Chord[]): boolean {
+ return parsed.some((entry) => chordEquals(entry, chord));
+}
+
+export function browserReserved(chord: Chord, platform: Platform): boolean {
+ return (
+ inTable(chord, table("browser", BROWSER_ALL, platform)) ||
+ inTable(chord, table("browser-platform", BROWSER_BY_PLATFORM[platform], platform))
+ );
+}
+
+export function browserCommon(chord: Chord, platform: Platform): boolean {
+ return (
+ inTable(chord, table("common", COMMON_ALL, platform)) ||
+ (platform !== "mac" && inTable(chord, table("common-off-mac", COMMON_OFF_MAC, platform))) ||
+ inTable(chord, table("common-platform", COMMON_BY_PLATFORM[platform], platform))
+ );
+}
+
+export function desktopReserved(chord: Chord, platform: Platform): "shell" | "menu" | null {
+ if (inTable(chord, table("shell", SHELL_BY_PLATFORM[platform], platform))) return "shell";
+ if (inTable(chord, table("menu", MENU_BY_PLATFORM[platform], platform))) return "menu";
+ return null;
+}
+
+/**
+ * Whether a chord is worth showing as the way to run a command on this host. A browser tab
+ * never receives a chord the browser reserves (⌘W closes the tab itself), so a tooltip naming it
+ * there would promise a key that does the opposite; the desktop app receives every chord.
+ */
+export function shownOnHost(chord: Chord, platform: Platform, host: HostKind): boolean {
+ return host !== "browser" || !browserReserved(chord, platform);
+}
diff --git a/packages/web/src/lib/shortcuts/store.ts b/packages/web/src/lib/shortcuts/store.ts
new file mode 100644
index 00000000..0a5a2268
--- /dev/null
+++ b/packages/web/src/lib/shortcuts/store.ts
@@ -0,0 +1,239 @@
+/**
+ * The resolved keymap and where the user's overrides live.
+ *
+ * Resolution = the registry's defaults for the current platform, overlaid by the stored
+ * platform section's known ids (`null` = explicitly unbound). The stored document is the
+ * account's `ui_prefs.keybindings`, mirrored to `localStorage["penguin.keybindings"]`: the
+ * dispatcher installs at module evaluation, before auth and before any prefs request answers,
+ * so the first keystroke needs a synchronous read, and the mirror's `storage` event is what
+ * lets every other same-origin tab follow a change live. Only overrides are stored — a row set
+ * back to its default is deleted from the section, so a later default change reaches users who
+ * never touched that row — and ids the registry does not know are carried through untouched.
+ *
+ * Storage is injectable (the install-scope.ts convention: vitest runs in Node with no
+ * localStorage), and every read degrades to the defaults on anything unexpected.
+ */
+import { chordEquals, normalizeChord, parseChord, serializeChord } from "./chord";
+import { relocateChord } from "./match";
+import { currentPlatform } from "./platform";
+import { SHORTCUT_COMMANDS, commandById, defaultChord } from "./registry";
+import type {
+ Chord,
+ CommandId,
+ Keymap,
+ Platform,
+ ShortcutCommand,
+ StoredKeybindings,
+} from "./types";
+
+/** The browser mirror of the account's overrides (a `browser`-scoped key in install-scope's KEY_RULES). */
+export const KEYBINDINGS_KEY = "penguin.keybindings";
+
+/** Minimal storage interface (the subset of localStorage used here); tests inject an in-memory one. */
+export interface KeybindingsStorage {
+ getItem(key: string): string | null;
+ setItem(key: string, value: string): void;
+ removeItem(key: string): void;
+}
+
+const SECTIONS: readonly Platform[] = ["mac", "windows", "linux"];
+
+let storageOverride: KeybindingsStorage | null = null;
+let layout: ReadonlyMap<string, string> | null = null;
+let cache: { platform: Platform; keymap: Keymap } | null = null;
+let version = 0;
+const listeners = new Set<() => void>();
+
+function storage(): KeybindingsStorage | null {
+ if (storageOverride !== null) return storageOverride;
+ try {
+ return typeof localStorage === "undefined" ? null : localStorage;
+ } catch {
+ return null; // access denied (sandboxed frame, disabled storage)
+ }
+}
+
+/**
+ * The document shape, enforced: `v` must be 1 and only the three platform sections are kept,
+ * each holding string-or-null values. Chord grammar is NOT checked here — an unparseable chord
+ * is skipped at apply time and kept in the document, like an unknown id.
+ */
+export function sanitizeStored(value: unknown): StoredKeybindings {
+ if (typeof value !== "object" || value === null || (value as { v?: unknown }).v !== 1) {
+ return { v: 1 };
+ }
+ const out: StoredKeybindings = { v: 1 };
+ for (const section of SECTIONS) {
+ const raw = (value as Record<string, unknown>)[section];
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) continue;
+ const entries: Record<string, string | null> = {};
+ for (const [id, chord] of Object.entries(raw as Record<string, unknown>)) {
+ if (chord === null || typeof chord === "string") entries[id] = chord;
+ }
+ out[section] = entries;
+ }
+ return out;
+}
+
+/** The stored document; malformed JSON, a foreign shape or a wrong `v` all read as "no overrides". */
+export function readStored(store: KeybindingsStorage | null = storage()): StoredKeybindings {
+ try {
+ const raw = store?.getItem(KEYBINDINGS_KEY);
+ if (raw === null || raw === undefined || raw === "") return { v: 1 };
+ return sanitizeStored(JSON.parse(raw));
+ } catch {
+ return { v: 1 };
+ }
+}
+
+function writeStored(doc: StoredKeybindings): void {
+ const compact: StoredKeybindings = { v: 1 };
+ for (const section of SECTIONS) {
+ const entries = doc[section];
+ if (entries !== undefined && Object.keys(entries).length > 0) compact[section] = entries;
+ }
+ try {
+ storage()?.setItem(KEYBINDINGS_KEY, JSON.stringify(compact));
+ } catch {
+ /* best-effort persistence (quota limits / private browsing) */
+ }
+ invalidate();
+}
+
+function invalidate(): void {
+ cache = null;
+ version++;
+ for (const listener of [...listeners]) listener();
+}
+
+/** The registry default after the keyboard layout relocation, when a layout is known. */
+function effectiveDefault(cmd: ShortcutCommand, platform: Platform): Chord | null {
+ const chord = defaultChord(cmd, platform);
+ return chord !== null && layout !== null ? relocateChord(chord, layout) : chord;
+}
+
+function resolve(platform: Platform): Keymap {
+ const section = readStored()[platform] ?? {};
+ const out = new Map<CommandId, Chord | null>();
+ for (const cmd of SHORTCUT_COMMANDS) {
+ const fallback = effectiveDefault(cmd, platform);
+ if (!Object.hasOwn(section, cmd.id)) {
+ out.set(cmd.id, fallback);
+ continue;
+ }
+ const stored = section[cmd.id];
+ if (stored === null || stored === undefined) {
+ out.set(cmd.id, null);
+ continue;
+ }
+ const parsed = parseChord(stored);
+ out.set(cmd.id, parsed === null ? fallback : normalizeChord(parsed, platform));
+ }
+ return out;
+}
+
+/** The keymap for the current platform; cached until a write, a `storage` event or a layout arrives. */
+export function keymap(): Keymap {
+ const platform = currentPlatform();
+ if (cache === null || cache.platform !== platform)
+ cache = { platform, keymap: resolve(platform) };
+ return cache.keymap;
+}
+
+export function bindingOf(id: CommandId): Chord | null {
+ return keymap().get(id) ?? null;
+}
+
+/** True while the stored platform section carries an entry for the id (including an explicit unbind). */
+export function isOverridden(id: CommandId): boolean {
+ const section = readStored()[currentPlatform()];
+ return section !== undefined && Object.hasOwn(section, id);
+}
+
+/** Binds (or, with null, unbinds) a command; a chord equal to the default removes the override instead. */
+export function setBinding(id: CommandId, chord: Chord | null): void {
+ const platform = currentPlatform();
+ const doc = readStored();
+ const section = { ...(doc[platform] ?? {}) };
+ const normalized = chord === null ? null : normalizeChord(chord, platform);
+ if (chordEquals(normalized, effectiveDefault(commandById(id), platform))) {
+ delete section[id];
+ } else {
+ section[id] = normalized === null ? null : serializeChord(normalized);
+ }
+ writeStored({ ...doc, [platform]: section });
+}
+
+export function resetBinding(id: CommandId): void {
+ const platform = currentPlatform();
+ const doc = readStored();
+ const section = { ...(doc[platform] ?? {}) };
+ delete section[id];
+ writeStored({ ...doc, [platform]: section });
+}
+
+/** Drops every override of the current platform; the other platforms' sections stay. */
+export function resetAll(): void {
+ const doc = readStored();
+ delete doc[currentPlatform()];
+ writeStored(doc);
+}
+
+/** The mirror changed underneath us (another tab's `storage` event, or a whole-store clear): re-read on the next access. */
+export function noteExternalChange(key: string | null): void {
+ if (key === null || key === KEYBINDINGS_KEY) invalidate();
+}
+
+/** `useSyncExternalStore` pair: subscribe, and a version that changes whenever the keymap may have. */
+export function subscribeKeymap(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+export function keymapVersion(): number {
+ return version;
+}
+
+/**
+ * The browser's `code → character` map, when it exposes one: defaults move to the key that types
+ * their US character, and labels show the character a key actually types.
+ */
+export function applyKeyboardLayout(map: ReadonlyMap<string, string> | null): void {
+ layout = map;
+ invalidate();
+}
+
+export function keyboardLayout(): ReadonlyMap<string, string> | null {
+ return layout;
+}
+
+/** Tests inject a storage and a layout; both null restores the browser defaults. */
+export function configureKeybindingsStoreForTests(options: {
+ storage?: KeybindingsStorage | null;
+ layout?: ReadonlyMap<string, string> | null;
+}): void {
+ if (options.storage !== undefined) storageOverride = options.storage;
+ if (options.layout !== undefined) layout = options.layout;
+ invalidate();
+}
+
+interface NavigatorKeyboard {
+ keyboard?: {
+ getLayoutMap?: () => Promise<{ forEach(cb: (value: string, key: string) => void): void }>;
+ };
+}
+
+if (typeof window !== "undefined") {
+ // Another tab wrote the mirror (the event never fires in the writing tab; writeStored notifies that one itself).
+ window.addEventListener("storage", (event) => noteExternalChange(event.key));
+ // Chromium and Electron expose the layout; Firefox and Safari do not and keep US positions.
+ const keyboard = (navigator as NavigatorKeyboard).keyboard;
+ keyboard
+ ?.getLayoutMap?.()
+ .then((map) => {
+ const copy = new Map<string, string>();
+ map.forEach((value, key) => copy.set(key, value));
+ applyKeyboardLayout(copy);
+ })
+ .catch(() => {});
+}
diff --git a/packages/web/src/lib/shortcuts/terminal-clipboard.ts b/packages/web/src/lib/shortcuts/terminal-clipboard.ts
new file mode 100644
index 00000000..58b5496e
--- /dev/null
+++ b/packages/web/src/lib/shortcuts/terminal-clipboard.ts
@@ -0,0 +1,36 @@
+/**
+ * The terminal's clipboard keys — a fixed platform convention, not a rebindable chord.
+ *
+ * Windows / Linux (the Windows Terminal and VS Code conventions): copy on Ctrl+Shift+C,
+ * Ctrl+Insert, or plain Ctrl+C while a selection exists (SIGINT still goes through when nothing
+ * is selected); paste on Ctrl+V and Shift+Insert, which ride the browser's NATIVE paste event
+ * into xterm's textarea — the caller only has to keep the browser default.
+ *
+ * macOS: ⌘C and ⌘V are the browser's native copy and paste, which xterm already serves, so
+ * nothing is intercepted for them; Ctrl+C is always SIGINT and Ctrl+V is the shell's verbatim
+ * insert, so neither is a clipboard key. Ctrl+Shift+C stays as a copy for terminal habit.
+ *
+ * Letters are matched by `key`, as xterm itself decides what Ctrl+<letter> sends.
+ */
+import type { KeyLike, Platform } from "./types";
+
+export type TerminalClipboardAction = "copy" | "paste";
+
+export function terminalClipboardAction(
+ e: KeyLike,
+ platform: Platform,
+ hasSelection: boolean,
+): TerminalClipboardAction | null {
+ const key = e.key.toLowerCase();
+ if (platform === "mac") {
+ if (e.ctrlKey && e.shiftKey && !e.metaKey && !e.altKey && key === "c") return "copy";
+ return null;
+ }
+ if (e.metaKey) return null;
+ if (e.ctrlKey && e.shiftKey && key === "c") return "copy";
+ if (e.ctrlKey && !e.shiftKey && e.key === "Insert") return "copy";
+ if (e.ctrlKey && !e.shiftKey && !e.altKey && key === "c" && hasSelection) return "copy";
+ if (e.ctrlKey && !e.altKey && key === "v") return "paste";
+ if (!e.ctrlKey && e.shiftKey && e.key === "Insert") return "paste";
+ return null;
+}
diff --git a/packages/web/src/lib/shortcuts/terminal-keys.ts b/packages/web/src/lib/shortcuts/terminal-keys.ts
new file mode 100644
index 00000000..380da086
--- /dev/null
+++ b/packages/web/src/lib/shortcuts/terminal-keys.ts
@@ -0,0 +1,40 @@
+/**
+ * What a focused terminal does with a keydown after the clipboard keys have had their turn.
+ * Pure: the surface passes what it knows (whether it offers a close, which global commands have a
+ * handler) and acts on the answer: the close chord (⌃⌥` / Ctrl+Alt+` by default) closes while
+ * Ctrl+W reaches readline; the terminal toggle pressed inside xterm runs without reaching the
+ * pty; a chord nothing answers (Ctrl+Alt+P before the palette exists) is the shell's.
+ */
+import { matchShortcut } from "./match";
+import type { CommandId, KeyLike, Keymap, Platform } from "./types";
+
+export type TerminalKeyAction =
+ /** Run the host's close: prevent, stop propagation, do not send to the shell. */
+ | "close"
+ /** A repeat of the close chord: prevent and stop as for "close", but run nothing. */
+ | "consume"
+ /** A global command some surface answers: not the shell's, and left un-prevented so it bubbles to the window dispatcher. */
+ | "skip-shell"
+ /** Everything else, including a chord nothing answers: xterm sends it to the shell. */
+ | "shell";
+
+export interface TerminalKeyHost {
+ /** Whether this terminal offers a close at all (the dock tab and the standalone page do). */
+ canClose: boolean;
+ hasHandler: (id: CommandId) => boolean;
+}
+
+export function terminalKeyAction(
+ e: KeyLike,
+ keymap: Keymap,
+ platform: Platform,
+ host: TerminalKeyHost,
+): TerminalKeyAction {
+ const command = matchShortcut(e, keymap, ["terminal", "global"], platform);
+ if (command === null) return "shell";
+ if (command === "terminal.close") {
+ if (!host.canClose) return "shell";
+ return e.repeat === true ? "consume" : "close";
+ }
+ return host.hasHandler(command) ? "skip-shell" : "shell";
+}
diff --git a/packages/web/src/lib/shortcuts/types.ts b/packages/web/src/lib/shortcuts/types.ts
new file mode 100644
index 00000000..f85e3763
--- /dev/null
+++ b/packages/web/src/lib/shortcuts/types.ts
@@ -0,0 +1,91 @@
+/**
+ * The vocabulary of the keyboard shortcut system. Everything under lib/shortcuts/ is written
+ * against these types and, except for the store's storage edge and the dispatcher's window
+ * listener, touches no DOM: the matcher, formatter, conflict finder and reserved-chord tables
+ * are pure functions over a `Chord`, so they run unchanged in Node for the tests.
+ */
+
+export type Platform = "mac" | "windows" | "linux";
+
+/** Which host runs the page: the reserved-chord notice differs, nothing else does. */
+export type HostKind = "browser" | "desktop";
+
+/**
+ * The focus scope a command is matched in. `global` matches anywhere; `terminal` only while an
+ * xterm has focus; `editor` only inside a text editor's own key handler. Two focus scopes never
+ * hold focus at once, which is what makes the resolution order deterministic.
+ */
+export type ShortcutScope = "global" | "terminal" | "editor";
+
+/**
+ * Settings-page grouping, display only. `panels` holds the dock and sidebar toggles, which are
+ * global-scope commands grouped by what they act on rather than by where they fire.
+ */
+export type ShortcutGroup = "general" | "panels" | "terminal" | "editor";
+
+/**
+ * The rebindable commands. `palette.toggle` is owned by the command palette; its id and default
+ * are reserved here so the settings page lists it before the palette lands.
+ */
+export type CommandId = "palette.toggle" | "terminal.close" | "terminal.toggle" | "editor.save";
+
+/**
+ * One key combination. `code` is the `KeyboardEvent.code` of the non-modifier key ("KeyW",
+ * "Backquote", "F12"): a physical position, so a chord survives a CJK IME, Shift, Caps Lock and a
+ * macOS Option chord, none of which change `code`.
+ */
+export interface Chord {
+ code: string;
+ /** Mod = ⌘ on macOS, Ctrl elsewhere. */
+ mod: boolean;
+ /**
+ * Literal Control. Only ever true on macOS; on the other platforms Control IS Mod and is
+ * recorded as such, so a chord read back from an event never has both set there.
+ */
+ ctrl: boolean;
+ alt: boolean;
+ shift: boolean;
+}
+
+export interface ShortcutCommand {
+ id: CommandId;
+ scope: ShortcutScope;
+ group: ShortcutGroup;
+ /**
+ * Serialized chords ("Mod+Shift+KeyW"); null = unbound by default. `default` covers every
+ * platform without an entry of its own.
+ */
+ defaults: {
+ default: string | null;
+ mac?: string | null;
+ windows?: string | null;
+ linux?: string | null;
+ };
+}
+
+/** id → chord (null = unbound), fully resolved for the current platform. */
+export type Keymap = ReadonlyMap<CommandId, Chord | null>;
+
+/**
+ * The persisted form, shared by the server's `ui_prefs.keybindings` and the browser mirror.
+ * Only overrides are stored; a row equal to its default is absent. Unknown ids are carried
+ * through on write and never applied, so a build that predates a command keeps its binding.
+ */
+export interface StoredKeybindings {
+ v: 1;
+ mac?: Record<string, string | null>;
+ windows?: Record<string, string | null>;
+ linux?: Record<string, string | null>;
+}
+
+/** The fields of a `KeyboardEvent` the matcher reads; React's synthetic event and a test literal both fit. */
+export interface KeyLike {
+ code: string;
+ key: string;
+ ctrlKey: boolean;
+ metaKey: boolean;
+ altKey: boolean;
+ shiftKey: boolean;
+ repeat?: boolean;
+ isComposing?: boolean;
+}
diff --git a/packages/web/src/lib/shortcuts/use-keymap.ts b/packages/web/src/lib/shortcuts/use-keymap.ts
new file mode 100644
index 00000000..5d099151
--- /dev/null
+++ b/packages/web/src/lib/shortcuts/use-keymap.ts
@@ -0,0 +1,38 @@
+/**
+ * React reads of the keymap. Every display site of a chord goes through these, so a change made
+ * in the settings dialog — or in another tab, through the mirror's `storage` event — redraws the
+ * tooltip, the kbd and the button title without a reload. A display read also drops a chord the
+ * host cannot deliver (⌘W in a browser tab closes the tab, whatever it is bound to), so no tooltip
+ * promises a key that does the opposite; the settings page reads the raw keymap and says why.
+ */
+import { useSyncExternalStore } from "react";
+import { formatChord } from "./format";
+import { currentHost, currentPlatform } from "./platform";
+import { shownOnHost } from "./reserved";
+import { bindingOf, keyboardLayout, keymap, keymapVersion, subscribeKeymap } from "./store";
+import type { Chord, CommandId, Keymap } from "./types";
+
+export function useKeymap(): Keymap {
+ useSyncExternalStore(subscribeKeymap, keymapVersion, keymapVersion);
+ return keymap();
+}
+
+/** The command's chord as bound, whether or not this host can deliver it. */
+export function useBinding(id: CommandId): Chord | null {
+ useKeymap();
+ return bindingOf(id);
+}
+
+/** The command's chord for display: null while unbound, and null for a chord this host reserves. */
+export function useDisplayedBinding(id: CommandId): Chord | null {
+ const chord = useBinding(id);
+ return chord !== null && shownOnHost(chord, currentPlatform(), currentHost()) ? chord : null;
+}
+
+/** The displayed chord as the platform writes it, or null when there is nothing to show. */
+export function useShortcutLabel(id: CommandId): string | null {
+ const chord = useDisplayedBinding(id);
+ return chord === null
+ ? null
+ : formatChord(chord, currentPlatform(), keyboardLayout() ?? undefined);
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index bdf56dbe..5328079e 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -138,6 +138,22 @@ export const en: Strings = {
adminOnly: "Only an admin can manage machines.",
},
+ /** Keyboard shortcuts: the registry's command and group labels (lib/shortcuts/registry.ts). */
+ shortcuts: {
+ commands: {
+ "palette.toggle": "Command palette",
+ "terminal.toggle": "Show or hide the terminal",
+ "terminal.close": "Close the focused terminal",
+ "editor.save": "Save",
+ },
+ groups: {
+ general: "General",
+ panels: "Panels",
+ terminal: "Terminal",
+ editor: "Editor",
+ },
+ },
+
/** Server-side terminal (the in-app dock and the standalone /terminal page). */
terminal: {
title: "Terminal",
@@ -436,7 +452,11 @@ export const en: Strings = {
title: "Command Palette",
placeholder: "Type to filter commands…",
noResults: "No matching commands",
- hint: "Ctrl+P / Ctrl+Shift+P (⌘P) to toggle · ↑↓ to select · Enter to run",
+ /** Footer of the palette; `toggle` is the formatted palette.toggle chord, null while unbound. */
+ hint: (toggle: string | null): string =>
+ toggle === null
+ ? "↑↓ to select · Enter to run"
+ : `${toggle} to toggle · ↑↓ to select · Enter to run`,
harnessHistory: "Harness history",
},
modelPicker: {
@@ -460,10 +480,16 @@ export const en: Strings = {
restore: "Restore",
remove: "Remove",
fillApp: "Fill the app",
- fillAppHint:
- "Show this page as the whole app; Ctrl+P / Ctrl+Shift+P opens the command palette to leave",
+ /** `palette` is the formatted palette.toggle chord, null while unbound. */
+ fillAppHint: (palette: string | null): string =>
+ palette === null
+ ? "Show this page as the whole app; the command palette is the way to leave"
+ : `Show this page as the whole app; ${palette} opens the command palette to leave`,
exitFullPage: "Exit full page (back to chat)",
- exitHint: "Press Ctrl+P or Ctrl+Shift+P for the command palette to get back to the chat.",
+ exitHint: (palette: string | null): string =>
+ palette === null
+ ? "Open the command palette to get back to the chat."
+ : `Press ${palette} for the command palette to get back to the chat.`,
noSuchPage: "This workflow does not exist or has no page.",
removeConfirm: "Delete this workflow and all its recorded versions?",
removeYes: "Remove",
@@ -3321,7 +3347,6 @@ Scenarios:
/** Soft-wrap toggle, shared by the source view and the editor: off means long lines scroll sideways. */
wrapLines: "Wrap",
unsaved: "Unsaved changes",
- saveTitle: "Save (Ctrl+S / ⌘S)",
saveConfirmTitle: "Save file",
saveConfirm: (name: string): string =>
`Save changes to ${name}? The file in the Workspace will be overwritten.`,
@@ -4577,8 +4602,9 @@ Scenarios:
documentLoadFailed: "Could not load the document",
/** A row's tooltip: when the file was last written, and its size. */
updatedAt: (time: string, size: string): string => `Updated ${time} · ${size}`,
- /** Beside the editor's buttons: what the text is, and the shortcut. */
- editorHint: "Markdown · Ctrl/⌘+S to save",
+ /** Beside the editor's buttons: what the text is, and the save shortcut (null while unbound). */
+ editorHint: (shortcut: string | null): string =>
+ shortcut === null ? "Markdown" : `Markdown · ${shortcut} to save`,
},
},
errors: {
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index ddc90d15..c7fcbfb9 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -160,6 +160,22 @@ export const zh = {
adminOnly: "只有管理员可以管理机器。",
},
+ /** Keyboard shortcuts: the registry's command and group labels (lib/shortcuts/registry.ts). */
+ shortcuts: {
+ commands: {
+ "palette.toggle": "命令面板",
+ "terminal.toggle": "显示或隐藏终端",
+ "terminal.close": "关闭当前终端",
+ "editor.save": "保存",
+ },
+ groups: {
+ general: "通用",
+ panels: "面板",
+ terminal: "终端",
+ editor: "编辑器",
+ },
+ },
+
/** Server-side terminal (the in-app dock and the standalone /terminal page). */
terminal: {
title: "终端",
@@ -492,7 +508,9 @@ export const zh = {
title: "命令面板",
placeholder: "输入以筛选命令…",
noResults: "没有匹配的命令",
- hint: "Ctrl+P / Ctrl+Shift+P(⌘P)切换 · ↑↓ 选择 · Enter 执行",
+ /** Footer of the palette; `toggle` is the formatted palette.toggle chord, null while unbound. */
+ hint: (toggle: string | null): string =>
+ toggle === null ? "↑↓ 选择 · Enter 执行" : `${toggle} 切换 · ↑↓ 选择 · Enter 执行`,
harnessHistory: "Harness 历史",
},
modelPicker: {
@@ -523,9 +541,14 @@ export const zh = {
restore: "恢复",
remove: "移除",
fillApp: "占满应用",
- fillAppHint: "让这个页面占满整个应用;Ctrl+P / Ctrl+Shift+P 打开命令面板可退出",
+ /** `palette` is the formatted palette.toggle chord, null while unbound. */
+ fillAppHint: (palette: string | null): string =>
+ palette === null
+ ? "让这个页面占满整个应用;打开命令面板可退出"
+ : `让这个页面占满整个应用;${palette} 打开命令面板可退出`,
exitFullPage: "退出全页模式(回到聊天)",
- exitHint: "按 Ctrl+P 或 Ctrl+Shift+P 打开命令面板可回到聊天。",
+ exitHint: (palette: string | null): string =>
+ palette === null ? "打开命令面板可回到聊天。" : `按 ${palette} 打开命令面板可回到聊天。`,
noSuchPage: "这个 workflow 不存在或没有页面。",
removeConfirm: "删除这个工作流及其全部已记录版本?",
removeYes: "确认移除",
@@ -3360,7 +3383,6 @@ Benchmark:
/** Soft-wrap toggle, shared by the source view and the editor: off means long lines scroll sideways. */
wrapLines: "自动换行",
unsaved: "有未保存的修改",
- saveTitle: "保存(Ctrl+S / ⌘S)",
saveConfirmTitle: "保存文件",
saveConfirm: (name: string): string => `保存对 ${name} 的修改?Workspace 中的该文件将被覆盖。`,
editTooLarge: (kb: number): string => `文件超过 ${kb}KB,无法在此编辑,请下载后编辑`,
@@ -4591,8 +4613,9 @@ Benchmark:
documentLoadFailed: "文档加载失败",
/** A row's tooltip: when the file was last written, and its size. */
updatedAt: (time: string, size: string): string => `更新于 ${time} · ${size}`,
- /** Beside the editor's buttons: what the text is, and the shortcut. */
- editorHint: "Markdown · Ctrl/⌘+S 保存",
+ /** Beside the editor's buttons: what the text is, and the save shortcut (null while unbound). */
+ editorHint: (shortcut: string | null): string =>
+ shortcut === null ? "Markdown" : `Markdown · ${shortcut} 保存`,
},
},
errors: {
diff --git a/packages/web/src/lib/workflow-tabs.ts b/packages/web/src/lib/workflow-tabs.ts
index c2c85ffe..61e32a40 100644
--- a/packages/web/src/lib/workflow-tabs.ts
+++ b/packages/web/src/lib/workflow-tabs.ts
@@ -119,7 +119,7 @@ export function settleActiveTab(
* The route that shows one workflow page as the whole app (no sidebar, no chat, no tab
* strip): what `penguin web --app <project>/<agent>/<workflow>[/<tab>]` opens, and what a
* tab's "fill the app" action navigates to. Without a tab key the workflow's first tab is
- * shown. The palette (Ctrl+P / Ctrl+Shift+P) is the way out.
+ * shown. The command palette is the way out.
*/
export function workflowAppPath(
projectId: string,
diff --git a/packages/web/src/main.tsx b/packages/web/src/main.tsx
index 0ecf1f0b..c4183c6e 100644
--- a/packages/web/src/main.tsx
+++ b/packages/web/src/main.tsx
@@ -23,6 +23,9 @@ import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { App } from "./app";
import { bootInstallScope, watchInstallScope } from "./lib/install-scope";
+// The global shortcut dispatcher installs itself at module evaluation (a React effect would
+// leave a post-paint window where a chord is dead); the import is what evaluates it.
+import "./lib/shortcuts/dispatcher";
// KaTeX's stylesheet and its woff2 faces, resolved out of node_modules so Vite emits them as local
// assets: the desktop app has to render math with no network, and a CDN <link> would leave every
// formula as unstyled markup offline. Imported before styles.css so the app's own `.katex` rules
diff --git a/packages/web/test/command-palette.test.ts b/packages/web/test/command-palette.test.ts
index 8bee8f77..05c2c2fb 100644
--- a/packages/web/test/command-palette.test.ts
+++ b/packages/web/test/command-palette.test.ts
@@ -1,32 +1,8 @@
import { describe, expect, it } from "vitest";
-import { filterPaletteActions, isCommandPaletteShortcut } from "../src/lib/command-palette";
+import { filterPaletteActions } from "../src/lib/command-palette";
-const key = (
- k: string,
- mods: Partial<Record<"ctrlKey" | "metaKey" | "altKey" | "shiftKey", boolean>> = {},
-) => ({
- key: k,
- ctrlKey: false,
- metaKey: false,
- altKey: false,
- shiftKey: false,
- ...mods,
-});
-
-describe("command palette shortcut", () => {
- it("is Ctrl+P off macOS and Cmd+P on it, and nothing else", () => {
- expect(isCommandPaletteShortcut(key("p", { ctrlKey: true }), false)).toBe(true);
- expect(isCommandPaletteShortcut(key("P", { ctrlKey: true }), false)).toBe(true);
- expect(isCommandPaletteShortcut(key("p", { metaKey: true }), false)).toBe(false);
- expect(isCommandPaletteShortcut(key("p", { metaKey: true }), true)).toBe(true);
- expect(isCommandPaletteShortcut(key("p", { ctrlKey: true }), true)).toBe(false);
- // Ctrl+Shift+P too: a page filling the app may own Ctrl+P, and the palette is its way out.
- expect(isCommandPaletteShortcut(key("P", { ctrlKey: true, shiftKey: true }), false)).toBe(true);
- expect(isCommandPaletteShortcut(key("P", { metaKey: true, shiftKey: true }), true)).toBe(true);
- expect(isCommandPaletteShortcut(key("p", { ctrlKey: true, altKey: true }), false)).toBe(false);
- expect(isCommandPaletteShortcut(key("o", { ctrlKey: true }), false)).toBe(false);
- });
-});
+// The chord that opens the palette is the registry's `palette.toggle`; its matching per
+// platform is covered by test/shortcuts-match.test.ts.
describe("command palette filter", () => {
const actions = [
diff --git a/packages/web/test/install-scope.test.ts b/packages/web/test/install-scope.test.ts
index c2e21ae5..048f6940 100644
--- a/packages/web/test/install-scope.test.ts
+++ b/packages/web/test/install-scope.test.ts
@@ -85,6 +85,7 @@ function populated(): ReturnType<typeof memStorage> {
"penguin.files.treeWidth": "220",
"penguin.files.editorWrap": "1",
"penguin.notifications": "1",
+ "penguin.keybindings": '{"v":1,"linux":{"terminal.close":"Mod+Alt+KeyW"}}',
});
}
@@ -112,6 +113,7 @@ const PREFERENCE_KEYS = [
"penguin.files.treeWidth",
"penguin.files.editorWrap",
"penguin.notifications",
+ "penguin.keybindings",
];
const WEB_SRC = fileURLToPath(new URL("../src", import.meta.url));
diff --git a/packages/web/test/shortcut-guard.test.ts b/packages/web/test/shortcut-guard.test.ts
new file mode 100644
index 00000000..4e16ecd9
--- /dev/null
+++ b/packages/web/test/shortcut-guard.test.ts
@@ -0,0 +1,77 @@
+/**
+ * No surface reads modifier keys itself. A shortcut is a chord in the registry, matched by
+ * lib/shortcuts/ against the user's keymap with the platform's modifier mapping; a hand-written
+ * `event.ctrlKey` check is a binding the settings page cannot see, and one that is wrong on a
+ * Mac. This scans the web source for `.ctrlKey` and `.metaKey` reads and allows them only under
+ * src/lib/shortcuts/, plus the few files named below. (`shiftKey` and `altKey` are not scanned:
+ * fixed interaction keys legitimately read them — Shift+Enter, Shift+F10, Shift-multiplied
+ * arrows.)
+ */
+import { describe, expect, it } from "vitest";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const WEB_SRC = fileURLToPath(new URL("../src", import.meta.url));
+const ALLOWED_DIR = "lib/shortcuts";
+
+/**
+ * Files that read the modifiers for something other than a chord of their own, and are
+ * therefore excused: the Workspace picker's fixed file-browser keys (Finder's ⌘↑ / ⌘[ / ⌘],
+ * Explorer's Alt+←) and its type-to-select, the model picker's Alt+digit group jump and its
+ * type-to-focus (both "is this a bare key" tests), and the workflow frame's key forwarding,
+ * which copies an event to re-raise it on the app's window. None is an app command a user
+ * would rebind. A new entry here needs a reason of the same kind.
+ */
+const EXCUSED_FILES = new Set([
+ "features/chat/workspace-finder-model.ts",
+ "features/chat/model-picker-logic.ts",
+ "features/chat/model-picker-modal.tsx",
+ "lib/workflow-theme.ts",
+]);
+
+/** Every `.ctrlKey` / `.metaKey` read outside a comment, as `file:line`. */
+function modifierReads(): { allowed: string[]; elsewhere: string[] } {
+ const allowed: string[] = [];
+ const elsewhere: string[] = [];
+ const walk = (dir: string): void => {
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ walk(full);
+ continue;
+ }
+ if (!/\.tsx?$/.test(entry.name)) continue;
+ const rel = path.relative(WEB_SRC, full).replaceAll(path.sep, "/");
+ if (EXCUSED_FILES.has(rel)) continue;
+ const code = fs
+ .readFileSync(full, "utf8")
+ .replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " "))
+ .replace(
+ /(^|[^:])\/\/[^\n]*/g,
+ (m, lead: string) => lead + " ".repeat(m.length - lead.length),
+ );
+ code.split("\n").forEach((line, i) => {
+ if (!/\.(ctrlKey|metaKey)\b/.test(line)) return;
+ (rel.startsWith(ALLOWED_DIR) ? allowed : elsewhere).push(`src/${rel}:${i + 1}`);
+ });
+ }
+ };
+ walk(WEB_SRC);
+ return { allowed, elsewhere };
+}
+
+describe("modifier-key reads", () => {
+ const reads = modifierReads();
+
+ it("happen only under src/lib/shortcuts/", () => {
+ expect(
+ reads.elsewhere,
+ "Match the event against the keymap (lib/shortcuts/match.ts) instead of reading ctrlKey / metaKey; a hand-written check is a shortcut the settings page cannot rebind.",
+ ).toEqual([]);
+ });
+
+ it("are still found where they belong, so the scan is not vacuous", () => {
+ expect(reads.allowed.length).toBeGreaterThan(0);
+ });
+});
diff --git a/packages/web/test/shortcuts-chord.test.ts b/packages/web/test/shortcuts-chord.test.ts
new file mode 100644
index 00000000..000f50b9
--- /dev/null
+++ b/packages/web/test/shortcuts-chord.test.ts
@@ -0,0 +1,166 @@
+/**
+ * Chords as strings and as events (src/lib/shortcuts/chord.ts): the persisted grammar
+ * round-trips, and an event becomes a chord by physical key with the platform's modifier
+ * mapping — or does not become one at all.
+ */
+import { describe, expect, it } from "vitest";
+import {
+ chordOf,
+ codeFromKey,
+ hasModifierOrFKey,
+ normalizeChord,
+ parseChord,
+ serializeChord,
+} from "../src/lib/shortcuts/chord";
+import type { KeyLike } from "../src/lib/shortcuts/types";
+
+function key(overrides: Partial<KeyLike> & { code: string }): KeyLike {
+ return {
+ key: "",
+ ctrlKey: false,
+ metaKey: false,
+ altKey: false,
+ shiftKey: false,
+ ...overrides,
+ };
+}
+
+describe("chord grammar", () => {
+ it("round-trips every modifier in the fixed order", () => {
+ for (const text of [
+ "Mod+KeyW",
+ "Ctrl+Backquote",
+ "Mod+Shift+KeyO",
+ "Mod+Alt+KeyB",
+ "F5",
+ "Mod+Ctrl+Alt+Shift+Digit1",
+ ]) {
+ const chord = parseChord(text);
+ expect(chord, text).not.toBeNull();
+ expect(serializeChord(chord!)).toBe(text);
+ }
+ });
+
+ it("rejects modifiers out of order, repeated, lower-cased, or with no key", () => {
+ for (const text of [
+ "Shift+Mod+KeyW",
+ "Mod+Mod+KeyW",
+ "mod+KeyW",
+ "Mod+",
+ "",
+ "Mod+Key W",
+ "Meta+KeyW",
+ "Ctrl+Mod+KeyW",
+ ]) {
+ expect(parseChord(text), text).toBeNull();
+ }
+ });
+
+ it("folds literal Ctrl into Mod on Windows and Linux only", () => {
+ const chord = parseChord("Ctrl+Backquote")!;
+ expect(normalizeChord(chord, "mac")).toEqual(chord);
+ expect(normalizeChord(chord, "windows")).toEqual({ ...chord, mod: true, ctrl: false });
+ expect(normalizeChord(chord, "linux")).toEqual({ ...chord, mod: true, ctrl: false });
+ });
+});
+
+describe("chordOf", () => {
+ it("maps Mod to the Command key on a Mac and keeps Control literal there", () => {
+ expect(chordOf(key({ code: "KeyW", key: "w", metaKey: true }), "mac")).toEqual({
+ code: "KeyW",
+ mod: true,
+ ctrl: false,
+ alt: false,
+ shift: false,
+ });
+ expect(chordOf(key({ code: "Backquote", key: "`", ctrlKey: true }), "mac")).toMatchObject({
+ mod: false,
+ ctrl: true,
+ });
+ });
+
+ it("maps Mod to Control elsewhere and never reports a literal ctrl", () => {
+ for (const platform of ["windows", "linux"] as const) {
+ expect(chordOf(key({ code: "KeyW", key: "w", ctrlKey: true }), platform)).toEqual({
+ code: "KeyW",
+ mod: true,
+ ctrl: false,
+ alt: false,
+ shift: false,
+ });
+ }
+ });
+
+ it("leaves the Windows / Super key to the OS", () => {
+ expect(chordOf(key({ code: "KeyW", key: "w", metaKey: true }), "windows")).toBeNull();
+ expect(chordOf(key({ code: "KeyW", key: "w", metaKey: true }), "linux")).toBeNull();
+ });
+
+ it("is null for a modifier-only press and an IME composition", () => {
+ expect(
+ chordOf(key({ code: "ControlLeft", key: "Control", ctrlKey: true }), "linux"),
+ ).toBeNull();
+ expect(chordOf(key({ code: "MetaLeft", key: "Meta", metaKey: true }), "mac")).toBeNull();
+ expect(
+ chordOf(key({ code: "KeyW", key: "w", ctrlKey: true, isComposing: true }), "linux"),
+ ).toBeNull();
+ });
+
+ it("still reads an auto-repeat as the chord, so the caller can prevent the browser's action for it", () => {
+ expect(chordOf(key({ code: "KeyW", key: "w", metaKey: true, repeat: true }), "mac")).toEqual({
+ code: "KeyW",
+ mod: true,
+ ctrl: false,
+ alt: false,
+ shift: false,
+ });
+ });
+
+ it("reads the physical key, so an IME, Option and Shift do not change the chord", () => {
+ // A CJK IME reports key "Process" while active; macOS Option reports the composed glyph; Shift upper-cases.
+ expect(chordOf(key({ code: "KeyW", key: "Process", ctrlKey: true }), "linux")?.code).toBe(
+ "KeyW",
+ );
+ expect(chordOf(key({ code: "KeyW", key: "∑", altKey: true, metaKey: true }), "mac")?.code).toBe(
+ "KeyW",
+ );
+ expect(
+ chordOf(key({ code: "KeyW", key: "W", shiftKey: true, ctrlKey: true }), "linux"),
+ ).toMatchObject({
+ code: "KeyW",
+ shift: true,
+ });
+ });
+
+ it("falls back to the key when the event carries no code", () => {
+ expect(chordOf(key({ code: "", key: "w", ctrlKey: true }), "linux")?.code).toBe("KeyW");
+ expect(chordOf(key({ code: "", key: "1", ctrlKey: true }), "linux")?.code).toBe("Digit1");
+ expect(chordOf(key({ code: "", key: "`", ctrlKey: true }), "linux")?.code).toBe("Backquote");
+ expect(chordOf(key({ code: "", key: "F5" }), "linux")?.code).toBe("F5");
+ expect(chordOf(key({ code: "", key: "Unidentified", ctrlKey: true }), "linux")).toBeNull();
+ });
+});
+
+describe("codeFromKey", () => {
+ it("names the US position of a character and passes named keys through", () => {
+ expect(codeFromKey("a")).toBe("KeyA");
+ expect(codeFromKey("Z")).toBe("KeyZ");
+ expect(codeFromKey("7")).toBe("Digit7");
+ expect(codeFromKey("Escape")).toBe("Escape");
+ expect(codeFromKey("ArrowUp")).toBe("ArrowUp");
+ expect(codeFromKey("Unidentified")).toBe("");
+ expect(codeFromKey("Dead")).toBe("");
+ expect(codeFromKey("Process")).toBe("");
+ expect(codeFromKey("é")).toBe("");
+ });
+});
+
+describe("hasModifierOrFKey", () => {
+ it("accepts a modifier chord or a bare function key and refuses a bare letter", () => {
+ expect(hasModifierOrFKey(parseChord("Mod+KeyW")!)).toBe(true);
+ expect(hasModifierOrFKey(parseChord("F5")!)).toBe(true);
+ expect(hasModifierOrFKey(parseChord("F24")!)).toBe(true);
+ expect(hasModifierOrFKey(parseChord("KeyW")!)).toBe(false);
+ expect(hasModifierOrFKey(parseChord("F25")!)).toBe(false);
+ });
+});
diff --git a/packages/web/test/shortcuts-conflicts.test.ts b/packages/web/test/shortcuts-conflicts.test.ts
new file mode 100644
index 00000000..4d3fd3dd
--- /dev/null
+++ b/packages/web/test/shortcuts-conflicts.test.ts
@@ -0,0 +1,191 @@
+/**
+ * Conflicts between bindings (src/lib/shortcuts/conflicts.ts) and the chords the host keeps for
+ * itself or also uses (src/lib/shortcuts/reserved.ts).
+ */
+import { describe, expect, it } from "vitest";
+import { parseChord } from "../src/lib/shortcuts/chord";
+import { conflictsOf, findConflicts } from "../src/lib/shortcuts/conflicts";
+import { SHORTCUT_COMMANDS } from "../src/lib/shortcuts/registry";
+import {
+ browserCommon,
+ browserReserved,
+ desktopReserved,
+ shownOnHost,
+} from "../src/lib/shortcuts/reserved";
+import type { Chord, CommandId, Platform } from "../src/lib/shortcuts/types";
+
+const chord = (text: string, platform: Platform = "linux"): Chord => {
+ const parsed = parseChord(text)!;
+ return platform === "mac" || !parsed.ctrl ? parsed : { ...parsed, mod: true, ctrl: false };
+};
+
+describe("findConflicts", () => {
+ it("reports two globals on one chord as same-scope, first in registry order winning", () => {
+ const keymap = new Map<CommandId, Chord | null>([
+ ["palette.toggle", chord("Mod+KeyK")],
+ ["terminal.toggle", chord("Mod+KeyK")],
+ ]);
+ expect(findConflicts(keymap, SHORTCUT_COMMANDS)).toEqual([
+ { chord: chord("Mod+KeyK"), a: "palette.toggle", b: "terminal.toggle", kind: "same-scope" },
+ ]);
+ });
+
+ it("reports a global and a focus-scoped command on one chord as shadowed", () => {
+ const keymap = new Map<CommandId, Chord | null>([
+ ["palette.toggle", chord("Mod+KeyW")],
+ ["terminal.close", chord("Mod+KeyW")],
+ ]);
+ const found = findConflicts(keymap, SHORTCUT_COMMANDS);
+ expect(found).toHaveLength(1);
+ expect(found[0]).toMatchObject({ a: "palette.toggle", b: "terminal.close", kind: "shadowed" });
+ });
+
+ it("does not report two different focus scopes: they never hold focus together", () => {
+ const keymap = new Map<CommandId, Chord | null>([
+ ["terminal.close", chord("Mod+KeyS")],
+ ["editor.save", chord("Mod+KeyS")],
+ ]);
+ expect(findConflicts(keymap, SHORTCUT_COMMANDS)).toEqual([]);
+ });
+
+ it("ignores unbound commands and filters by id", () => {
+ const keymap = new Map<CommandId, Chord | null>([
+ ["palette.toggle", null],
+ ["terminal.toggle", null],
+ ["terminal.close", chord("Mod+KeyW")],
+ ["editor.save", chord("Mod+KeyW")],
+ ]);
+ expect(findConflicts(keymap, SHORTCUT_COMMANDS)).toEqual([]);
+ const both = new Map<CommandId, Chord | null>([
+ ["palette.toggle", chord("Mod+KeyK")],
+ ["terminal.toggle", chord("Mod+KeyK")],
+ ["terminal.close", chord("Mod+KeyK")],
+ ]);
+ const all = findConflicts(both, SHORTCUT_COMMANDS);
+ expect(all).toHaveLength(3);
+ expect(conflictsOf("editor.save", all)).toEqual([]);
+ expect(conflictsOf("terminal.close", all).map((c) => c.kind)).toEqual(["shadowed", "shadowed"]);
+ });
+});
+
+describe("browserReserved", () => {
+ it("names the tab and window chords every browser takes first", () => {
+ expect(browserReserved(chord("Mod+KeyW"), "linux")).toBe(true);
+ expect(browserReserved(chord("Mod+KeyW", "mac"), "mac")).toBe(true);
+ expect(browserReserved(chord("Mod+Shift+KeyW"), "windows")).toBe(true);
+ expect(browserReserved(chord("Mod+KeyT"), "linux")).toBe(true);
+ expect(browserReserved(chord("Mod+KeyN"), "linux")).toBe(true);
+ expect(browserReserved(chord("Mod+Digit1"), "linux")).toBe(true);
+ expect(browserReserved(chord("Mod+Digit9"), "linux")).toBe(true);
+ expect(browserReserved(chord("Ctrl+Tab"), "windows")).toBe(true);
+ expect(browserReserved(chord("Ctrl+Tab", "mac"), "mac")).toBe(true);
+ expect(browserReserved(chord("Ctrl+PageDown"), "linux")).toBe(true);
+ });
+
+ it("adds the platform's own: F11 and Alt+F4 off a Mac, the OS chords on one", () => {
+ expect(browserReserved(chord("F11"), "windows")).toBe(true);
+ expect(browserReserved(chord("Alt+F4"), "linux")).toBe(true);
+ expect(browserReserved(chord("F11", "mac"), "mac")).toBe(false);
+ expect(browserReserved(chord("Mod+KeyQ", "mac"), "mac")).toBe(true);
+ expect(browserReserved(chord("Mod+KeyH", "mac"), "mac")).toBe(true);
+ expect(browserReserved(chord("Mod+Alt+KeyH", "mac"), "mac")).toBe(true);
+ expect(browserReserved(chord("Mod+KeyM", "mac"), "mac")).toBe(true);
+ expect(browserReserved(chord("Mod+Backquote", "mac"), "mac")).toBe(true);
+ expect(browserReserved(chord("Ctrl+ArrowUp", "mac"), "mac")).toBe(true);
+ expect(browserReserved(chord("Mod+KeyQ"), "linux")).toBe(false);
+ });
+
+ it("leaves the registry's defaults and ordinary chords alone", () => {
+ expect(browserReserved(chord("Ctrl+Backquote"), "linux")).toBe(false);
+ expect(browserReserved(chord("Ctrl+Backquote", "mac"), "mac")).toBe(false);
+ expect(browserReserved(chord("Ctrl+Alt+Backquote"), "linux")).toBe(false);
+ expect(browserReserved(chord("Ctrl+Alt+Backquote", "mac"), "mac")).toBe(false);
+ expect(browserReserved(chord("Mod+KeyS"), "linux")).toBe(false);
+ expect(browserReserved(chord("Mod+Alt+KeyP", "mac"), "mac")).toBe(false);
+ expect(browserReserved(chord("Mod+KeyP", "mac"), "mac")).toBe(false);
+ expect(browserReserved(chord("Mod+Alt+KeyW"), "linux")).toBe(false);
+ });
+});
+
+describe("browserCommon", () => {
+ it("names the browser functions a page can take over on every platform", () => {
+ for (const platform of ["mac", "windows", "linux"] as const) {
+ for (const text of [
+ "Mod+KeyP", // print
+ "Mod+KeyS", // save page
+ "Mod+KeyF", // find
+ "Mod+KeyL", // address bar
+ "Mod+KeyJ", // downloads
+ "Mod+Shift+KeyO", // bookmark manager
+ "Mod+KeyR", // reload
+ "Mod+KeyU", // view source
+ "F12", // developer tools
+ ]) {
+ expect(browserCommon(chord(text, platform), platform), `${text} on ${platform}`).toBe(true);
+ }
+ }
+ });
+
+ it("adds each platform's own spelling", () => {
+ expect(browserCommon(chord("Mod+KeyH"), "windows")).toBe(true); // history
+ expect(browserCommon(chord("Alt+ArrowLeft"), "linux")).toBe(true); // back
+ expect(browserCommon(chord("Mod+Shift+KeyY"), "linux")).toBe(true); // Firefox's downloads
+ expect(browserCommon(chord("Mod+Shift+KeyY"), "windows")).toBe(false);
+ expect(browserCommon(chord("Mod+KeyY", "mac"), "mac")).toBe(true); // history
+ expect(browserCommon(chord("Mod+Alt+KeyI", "mac"), "mac")).toBe(true); // developer tools
+ expect(browserCommon(chord("Mod+Alt+KeyP", "mac"), "mac")).toBe(true); // Chrome's page setup
+ expect(browserCommon(chord("Mod+Alt+KeyP"), "linux")).toBe(false);
+ expect(browserCommon(chord("Alt+ArrowLeft", "mac"), "mac")).toBe(false);
+ });
+
+ it("leaves the reserved chords to browserReserved, and the free ones alone", () => {
+ expect(browserCommon(chord("Mod+KeyW"), "linux")).toBe(false);
+ expect(browserCommon(chord("Mod+KeyH", "mac"), "mac")).toBe(false); // hide, reserved on macOS
+ expect(browserCommon(chord("Ctrl+Alt+Backquote"), "linux")).toBe(false);
+ expect(browserCommon(chord("Ctrl+Alt+Backquote", "mac"), "mac")).toBe(false);
+ expect(browserCommon(chord("Ctrl+Backquote"), "windows")).toBe(false);
+ expect(browserCommon(chord("Mod+Alt+KeyS"), "windows")).toBe(false);
+ expect(browserCommon(chord("Mod+Alt+Digit1", "mac"), "mac")).toBe(false);
+ });
+});
+
+describe("desktopReserved", () => {
+ it("takes no key before the page: the shell binds nothing on before-input-event today", () => {
+ expect(desktopReserved(chord("F12"), "windows")).toBeNull();
+ expect(desktopReserved(chord("F10"), "linux")).toBeNull();
+ expect(desktopReserved(chord("F12", "mac"), "mac")).toBeNull();
+ });
+
+ it("marks the menu role accelerators of each platform, as Electron 43.2 defines them", () => {
+ expect(desktopReserved(chord("Mod+KeyR", "mac"), "mac")).toBe("menu");
+ expect(desktopReserved(chord("Mod+Alt+KeyI", "mac"), "mac")).toBe("menu");
+ expect(desktopReserved(chord("Mod+Ctrl+KeyF", "mac"), "mac")).toBe("menu");
+ expect(desktopReserved(chord("Mod+Alt+Shift+KeyV", "mac"), "mac")).toBe("menu");
+ expect(desktopReserved(chord("Mod+KeyR"), "windows")).toBe("menu");
+ expect(desktopReserved(chord("Ctrl+Shift+KeyI"), "windows")).toBe("menu");
+ expect(desktopReserved(chord("Mod+KeyW"), "linux")).toBe("menu");
+ expect(desktopReserved(chord("F11"), "linux")).toBe("menu");
+ // Zoom in is CommandOrControl+Plus, which Electron reads as Shift+=.
+ expect(desktopReserved(chord("Mod+Shift+Equal"), "windows")).toBe("menu");
+ expect(desktopReserved(chord("Mod+Equal"), "windows")).toBeNull();
+ // Redo: Control+Y on Windows only; Linux and macOS use Shift+Mod+Z.
+ expect(desktopReserved(chord("Mod+KeyY"), "windows")).toBe("menu");
+ expect(desktopReserved(chord("Mod+KeyY"), "linux")).toBeNull();
+ expect(desktopReserved(chord("Mod+Shift+KeyZ"), "linux")).toBe("menu");
+ // Quit has no accelerator on Windows.
+ expect(desktopReserved(chord("Mod+KeyQ"), "windows")).toBeNull();
+ expect(desktopReserved(chord("Mod+KeyQ"), "linux")).toBe("menu");
+ expect(desktopReserved(chord("Mod+KeyW", "mac"), "mac")).toBeNull();
+ expect(desktopReserved(chord("Mod+KeyS"), "linux")).toBeNull();
+ });
+});
+
+describe("shownOnHost", () => {
+ it("hides a browser-reserved chord in a browser and shows everything in the desktop app", () => {
+ expect(shownOnHost(chord("Mod+KeyW", "mac"), "mac", "browser")).toBe(false);
+ expect(shownOnHost(chord("Mod+KeyW"), "linux", "browser")).toBe(false);
+ expect(shownOnHost(chord("Mod+KeyW", "mac"), "mac", "desktop")).toBe(true);
+ expect(shownOnHost(chord("Ctrl+Backquote"), "linux", "browser")).toBe(true);
+ expect(shownOnHost(chord("Mod+KeyS", "mac"), "mac", "browser")).toBe(true);
+ });
+});
diff --git a/packages/web/test/shortcuts-dispatcher.test.ts b/packages/web/test/shortcuts-dispatcher.test.ts
new file mode 100644
index 00000000..4dba2d1b
--- /dev/null
+++ b/packages/web/test/shortcuts-dispatcher.test.ts
@@ -0,0 +1,116 @@
+/**
+ * The global dispatcher (src/lib/shortcuts/dispatcher.ts): handler order, the declined-command
+ * path, and the window listener fed a fake event — it runs the bound global command, prevents the
+ * default only when handled, keeps a repeat from the browser without re-running, and leaves an
+ * already-prevented event alone.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ handleShortcutKeydown,
+ hasCommandHandler,
+ onCommand,
+ runCommand,
+} from "../src/lib/shortcuts/dispatcher";
+import { setPlatformForTests } from "../src/lib/shortcuts/platform";
+import { configureKeybindingsStoreForTests } from "../src/lib/shortcuts/store";
+
+function fire(init: Partial<KeyboardEvent> & { code: string }): { defaultPrevented: boolean } {
+ const state = { defaultPrevented: false, ...init };
+ const event = {
+ key: "",
+ ctrlKey: false,
+ metaKey: false,
+ altKey: false,
+ shiftKey: false,
+ repeat: false,
+ isComposing: false,
+ ...state,
+ preventDefault: () => {
+ state.defaultPrevented = true;
+ },
+ } as unknown as KeyboardEvent;
+ handleShortcutKeydown(event);
+ return state;
+}
+
+const unregisters: Array<() => void> = [];
+
+beforeEach(() => {
+ setPlatformForTests("linux");
+ configureKeybindingsStoreForTests({
+ storage: { getItem: () => null, setItem: () => {}, removeItem: () => {} },
+ layout: null,
+ });
+});
+
+afterEach(() => {
+ for (const off of unregisters.splice(0)) off();
+ setPlatformForTests(null);
+ configureKeybindingsStoreForTests({ storage: null, layout: null });
+});
+
+describe("command handlers", () => {
+ it("runs the last registered handler first and lets it decline to the previous one", () => {
+ const order: string[] = [];
+ unregisters.push(onCommand("terminal.toggle", () => void order.push("first")));
+ unregisters.push(
+ onCommand("terminal.toggle", () => {
+ order.push("second");
+ return false;
+ }),
+ );
+ expect(hasCommandHandler("terminal.toggle")).toBe(true);
+ expect(runCommand("terminal.toggle")).toBe(true);
+ expect(order).toEqual(["second", "first"]);
+ });
+
+ it("reports an unhandled command, and forgets an unregistered handler", () => {
+ expect(hasCommandHandler("palette.toggle")).toBe(false);
+ expect(runCommand("palette.toggle")).toBe(false);
+ const off = onCommand("palette.toggle", () => {});
+ expect(hasCommandHandler("palette.toggle")).toBe(true);
+ off();
+ expect(hasCommandHandler("palette.toggle")).toBe(false);
+ off(); // idempotent
+ });
+});
+
+describe("the window listener", () => {
+ it("runs the bound global command and prevents the default", () => {
+ let toggled = 0;
+ unregisters.push(onCommand("terminal.toggle", () => void toggled++));
+ const event = fire({ code: "Backquote", key: "`", ctrlKey: true });
+ expect(toggled).toBe(1);
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it("keeps a repeat from the browser without running the command again", () => {
+ let toggled = 0;
+ unregisters.push(onCommand("terminal.toggle", () => void toggled++));
+ fire({ code: "Backquote", key: "`", ctrlKey: true });
+ const repeat = fire({ code: "Backquote", key: "`", ctrlKey: true, repeat: true });
+ expect(toggled).toBe(1);
+ expect(repeat.defaultPrevented).toBe(true);
+ // A repeat of a chord nothing answers is left to the browser, like its first press.
+ expect(
+ fire({ code: "KeyP", key: "p", ctrlKey: true, altKey: true, repeat: true }).defaultPrevented,
+ ).toBe(false);
+ });
+
+ it("leaves a chord with no handler, a focus-scoped chord and an already-prevented event to their defaults", () => {
+ // palette.toggle is bound to Ctrl+Alt+P but nothing answers it yet.
+ expect(fire({ code: "KeyP", key: "p", ctrlKey: true, altKey: true }).defaultPrevented).toBe(
+ false,
+ );
+ // editor.save is editor-scoped: the editor's own handler decides it, never the window.
+ let saved = 0;
+ unregisters.push(onCommand("editor.save", () => void saved++));
+ expect(fire({ code: "KeyS", key: "s", ctrlKey: true }).defaultPrevented).toBe(false);
+ expect(saved).toBe(0);
+ // A surface that handled the key already.
+ let toggled = 0;
+ unregisters.push(onCommand("terminal.toggle", () => void toggled++));
+ fire({ code: "Backquote", key: "`", ctrlKey: true, defaultPrevented: true });
+ expect(toggled).toBe(0);
+ });
+});
diff --git a/packages/web/test/shortcuts-format.test.ts b/packages/web/test/shortcuts-format.test.ts
new file mode 100644
index 00000000..a7c31255
--- /dev/null
+++ b/packages/web/test/shortcuts-format.test.ts
@@ -0,0 +1,94 @@
+/**
+ * Chord labels (src/lib/shortcuts/format.ts): Apple's glyph run on a Mac, `Ctrl+…` names
+ * elsewhere, the layout map's letters, and the code itself for anything unknown.
+ */
+import { describe, expect, it } from "vitest";
+import { parseChord } from "../src/lib/shortcuts/chord";
+import { formatBinding, formatChord, keyLabel } from "../src/lib/shortcuts/format";
+import type { Chord, CommandId } from "../src/lib/shortcuts/types";
+
+const chord = (text: string): Chord => parseChord(text)!;
+
+describe("macOS", () => {
+ it("writes the glyphs in Apple's order with no separators", () => {
+ expect(formatChord(chord("Mod+KeyW"), "mac")).toBe("⌘W");
+ expect(formatChord(chord("Ctrl+Backquote"), "mac")).toBe("⌃`");
+ expect(formatChord(chord("Ctrl+Shift+Backquote"), "mac")).toBe("⌃⇧`");
+ expect(formatChord(chord("Mod+Alt+KeyI"), "mac")).toBe("⌥⌘I");
+ expect(formatChord(chord("Mod+Ctrl+Alt+Shift+KeyA"), "mac")).toBe("⌃⌥⇧⌘A");
+ });
+
+ it("uses the Apple key glyphs", () => {
+ expect(formatChord(chord("Mod+Escape"), "mac")).toBe("⌘⎋");
+ expect(formatChord(chord("Mod+Enter"), "mac")).toBe("⌘↩");
+ expect(formatChord(chord("Mod+Tab"), "mac")).toBe("⌘⇥");
+ expect(formatChord(chord("Mod+Backspace"), "mac")).toBe("⌘⌫");
+ expect(formatChord(chord("Mod+Delete"), "mac")).toBe("⌘⌦");
+ expect(formatChord(chord("Mod+ArrowLeft"), "mac")).toBe("⌘←");
+ expect(formatChord(chord("Mod+Home"), "mac")).toBe("⌘↖");
+ expect(formatChord(chord("Mod+PageDown"), "mac")).toBe("⌘⇟");
+ expect(formatChord(chord("Mod+Space"), "mac")).toBe("⌘Space");
+ expect(formatChord(chord("F12"), "mac")).toBe("F12");
+ });
+});
+
+describe("Windows and Linux", () => {
+ it("writes Ctrl, Alt, Shift and the key joined by +", () => {
+ expect(formatChord(chord("Mod+KeyW"), "windows")).toBe("Ctrl+W");
+ expect(formatChord(chord("Mod+Alt+Shift+KeyW"), "linux")).toBe("Ctrl+Alt+Shift+W");
+ // A literal Ctrl token reads as Ctrl there too (it IS Mod on these platforms).
+ expect(formatChord(chord("Ctrl+Backquote"), "linux")).toBe("Ctrl+`");
+ });
+
+ it("uses the conventional key names", () => {
+ expect(formatChord(chord("Mod+Escape"), "windows")).toBe("Ctrl+Esc");
+ expect(formatChord(chord("Mod+Enter"), "windows")).toBe("Ctrl+Enter");
+ expect(formatChord(chord("Shift+Insert"), "windows")).toBe("Shift+Insert");
+ expect(formatChord(chord("Mod+PageUp"), "linux")).toBe("Ctrl+PgUp");
+ expect(formatChord(chord("Mod+ArrowUp"), "linux")).toBe("Ctrl+↑");
+ expect(formatChord(chord("Alt+F4"), "windows")).toBe("Alt+F4");
+ });
+});
+
+describe("key text", () => {
+ it("names digits, punctuation and the numpad, and falls back to the code", () => {
+ expect(keyLabel("Digit3", "linux")).toBe("3");
+ expect(keyLabel("Minus", "linux")).toBe("-");
+ expect(keyLabel("Equal", "linux")).toBe("=");
+ expect(keyLabel("BracketLeft", "linux")).toBe("[");
+ expect(keyLabel("Backslash", "linux")).toBe("\\");
+ expect(keyLabel("Semicolon", "linux")).toBe(";");
+ expect(keyLabel("Quote", "linux")).toBe("'");
+ expect(keyLabel("Comma", "linux")).toBe(",");
+ expect(keyLabel("Period", "linux")).toBe(".");
+ expect(keyLabel("Slash", "linux")).toBe("/");
+ expect(keyLabel("Numpad7", "linux")).toBe("Num 7");
+ expect(keyLabel("MediaPlayPause", "linux")).toBe("MediaPlayPause");
+ });
+
+ it("shows the character the key types when a layout map is given", () => {
+ const azerty = new Map([["KeyZ", "w"]]);
+ expect(keyLabel("KeyZ", "linux", azerty)).toBe("W");
+ expect(keyLabel("KeyZ", "linux")).toBe("Z");
+ expect(formatChord(chord("Mod+KeyZ"), "mac", azerty)).toBe("⌘W");
+ // Dvorak relocates the save chord onto the semicolon position, which then reads S.
+ expect(keyLabel("Semicolon", "linux", new Map([["Semicolon", "s"]]))).toBe("S");
+ expect(formatChord(chord("Mod+Semicolon"), "windows", new Map([["Semicolon", "s"]]))).toBe(
+ "Ctrl+S",
+ );
+ // A dead key or a multi-character entry is not a label; the US letter stands.
+ expect(keyLabel("KeyZ", "linux", new Map([["KeyZ", ""]]))).toBe("Z");
+ });
+});
+
+describe("formatBinding", () => {
+ it("formats the bound chord and is null when unbound", () => {
+ const keymap = new Map<CommandId, Chord | null>([
+ ["terminal.close", chord("Mod+KeyW")],
+ ["editor.save", null],
+ ]);
+ expect(formatBinding("terminal.close", keymap, "mac")).toBe("⌘W");
+ expect(formatBinding("editor.save", keymap, "mac")).toBeNull();
+ expect(formatBinding("palette.toggle", keymap, "mac")).toBeNull();
+ });
+});
diff --git a/packages/web/test/shortcuts-match.test.ts b/packages/web/test/shortcuts-match.test.ts
new file mode 100644
index 00000000..ed4d8a32
--- /dev/null
+++ b/packages/web/test/shortcuts-match.test.ts
@@ -0,0 +1,172 @@
+/**
+ * The matcher (src/lib/shortcuts/match.ts) against the registry's defaults: which platform
+ * chord runs which command, how a focus scope beats global, and how defaults relocate on a
+ * non-US layout while user chords stay physical.
+ */
+import { describe, expect, it } from "vitest";
+import { parseChord } from "../src/lib/shortcuts/chord";
+import { isShortcut, matchShortcut, relocateChord } from "../src/lib/shortcuts/match";
+import { SHORTCUT_COMMANDS, defaultChord } from "../src/lib/shortcuts/registry";
+import type { Chord, CommandId, KeyLike, Keymap, Platform } from "../src/lib/shortcuts/types";
+
+function defaults(platform: Platform): Map<CommandId, Chord | null> {
+ return new Map(SHORTCUT_COMMANDS.map((cmd) => [cmd.id, defaultChord(cmd, platform)]));
+}
+
+function key(overrides: Partial<KeyLike> & { code: string }): KeyLike {
+ return { key: "", ctrlKey: false, metaKey: false, altKey: false, shiftKey: false, ...overrides };
+}
+
+const ALL = ["global", "terminal", "editor"] as const;
+
+describe("the default table per platform", () => {
+ it("closes the terminal on Ctrl+Alt+` on every platform, and leaves ⌘W and Ctrl+W unbound", () => {
+ const close = { code: "Backquote", ctrlKey: true, altKey: true };
+ for (const platform of ["mac", "windows", "linux"] as const) {
+ expect(matchShortcut(key(close), defaults(platform), ALL, platform)).toBe("terminal.close");
+ expect(
+ matchShortcut(key({ code: "KeyW", ctrlKey: true }), defaults(platform), ALL, platform),
+ ).toBeNull();
+ }
+ expect(
+ matchShortcut(
+ key({ code: "Backquote", metaKey: true, altKey: true }),
+ defaults("mac"),
+ ALL,
+ "mac",
+ ),
+ ).toBeNull();
+ expect(
+ matchShortcut(key({ code: "KeyW", metaKey: true }), defaults("mac"), ALL, "mac"),
+ ).toBeNull();
+ });
+
+ it("toggles the terminal on Ctrl+` on every platform, and not on ⌘`", () => {
+ for (const platform of ["mac", "windows", "linux"] as const) {
+ expect(
+ matchShortcut(key({ code: "Backquote", ctrlKey: true }), defaults(platform), ALL, platform),
+ ).toBe("terminal.toggle");
+ }
+ expect(
+ matchShortcut(key({ code: "Backquote", metaKey: true }), defaults("mac"), ALL, "mac"),
+ ).toBeNull();
+ });
+
+ it("saves on ⌘S / Ctrl+S and opens the palette on ⌥⌘P / Ctrl+Alt+P, not on ⌘P / Ctrl+P", () => {
+ expect(matchShortcut(key({ code: "KeyS", metaKey: true }), defaults("mac"), ALL, "mac")).toBe(
+ "editor.save",
+ );
+ expect(
+ matchShortcut(key({ code: "KeyS", ctrlKey: true }), defaults("linux"), ALL, "linux"),
+ ).toBe("editor.save");
+ expect(
+ matchShortcut(
+ key({ code: "KeyP", metaKey: true, altKey: true }),
+ defaults("mac"),
+ ALL,
+ "mac",
+ ),
+ ).toBe("palette.toggle");
+ expect(
+ matchShortcut(
+ key({ code: "KeyP", ctrlKey: true, altKey: true }),
+ defaults("windows"),
+ ALL,
+ "windows",
+ ),
+ ).toBe("palette.toggle");
+ expect(
+ matchShortcut(key({ code: "KeyP", metaKey: true }), defaults("mac"), ALL, "mac"),
+ ).toBeNull();
+ expect(
+ matchShortcut(key({ code: "KeyP", ctrlKey: true }), defaults("windows"), ALL, "windows"),
+ ).toBeNull();
+ });
+
+ it("matches only the scopes that hold focus", () => {
+ const e = key({ code: "KeyS", ctrlKey: true });
+ expect(matchShortcut(e, defaults("linux"), ["global"], "linux")).toBeNull();
+ expect(matchShortcut(e, defaults("linux"), ["terminal", "global"], "linux")).toBeNull();
+ expect(matchShortcut(e, defaults("linux"), ["editor"], "linux")).toBe("editor.save");
+ });
+});
+
+describe("resolution", () => {
+ it("lets the focus scope beat global on the same chord, and registry order break a tie", () => {
+ const chord = parseChord("Mod+KeyW")!;
+ const keymap: Keymap = new Map<CommandId, Chord | null>([
+ ["palette.toggle", chord], // global, first in registry order
+ ["terminal.toggle", chord], // global
+ ["terminal.close", chord], // terminal scope
+ ["editor.save", null],
+ ]);
+ const e = key({ code: "KeyW", ctrlKey: true });
+ expect(matchShortcut(e, keymap, ["terminal", "global"], "linux")).toBe("terminal.close");
+ expect(matchShortcut(e, keymap, ["global"], "linux")).toBe("palette.toggle");
+ });
+
+ it("never matches an unbound command", () => {
+ const keymap: Keymap = new Map<CommandId, Chord | null>([["terminal.close", null]]);
+ expect(matchShortcut(key({ code: "KeyW", ctrlKey: true }), keymap, ALL, "linux")).toBeNull();
+ expect(
+ isShortcut(key({ code: "KeyW", ctrlKey: true }), keymap, "terminal.close", "linux"),
+ ).toBe(false);
+ });
+
+ it("isShortcut is one command's own test", () => {
+ expect(
+ isShortcut(key({ code: "KeyS", metaKey: true }), defaults("mac"), "editor.save", "mac"),
+ ).toBe(true);
+ expect(
+ isShortcut(key({ code: "KeyS", ctrlKey: true }), defaults("mac"), "editor.save", "mac"),
+ ).toBe(false);
+ expect(
+ isShortcut(
+ key({ code: "KeyS", metaKey: true, shiftKey: true }),
+ defaults("mac"),
+ "editor.save",
+ "mac",
+ ),
+ ).toBe(false);
+ });
+});
+
+describe("layout relocation", () => {
+ // The AZERTY keys that differ from US: the physical W position types Z and vice versa.
+ const azerty = new Map<string, string>([
+ ["KeyW", "z"],
+ ["KeyZ", "w"],
+ ["KeyA", "q"],
+ ["KeyQ", "a"],
+ ["KeyS", "s"],
+ ]);
+
+ it("moves a default letter to the key that types it, and leaves the rest alone", () => {
+ expect(relocateChord(parseChord("Mod+KeyW")!, azerty).code).toBe("KeyZ");
+ expect(relocateChord(parseChord("Mod+KeyS")!, azerty).code).toBe("KeyS");
+ expect(relocateChord(parseChord("Ctrl+Backquote")!, azerty).code).toBe("Backquote");
+ // A letter the map does not know keeps its US position (Firefox and Safari expose no map at all).
+ expect(relocateChord(parseChord("Mod+KeyP")!, new Map()).code).toBe("KeyP");
+ });
+
+ it("looks past the letter keys: US-Dvorak types s on Semicolon and w on Comma", () => {
+ const dvorak = new Map<string, string>([
+ ["KeyS", "o"],
+ ["Semicolon", "s"],
+ ["KeyW", ","],
+ ["Comma", "w"],
+ ["KeyP", "r"],
+ ["KeyR", "p"],
+ ["KeyB", "x"],
+ ["KeyN", "b"],
+ ["Backquote", "`"],
+ ]);
+ expect(relocateChord(parseChord("Mod+KeyS")!, dvorak).code).toBe("Semicolon");
+ expect(relocateChord(parseChord("Mod+KeyW")!, dvorak).code).toBe("Comma");
+ expect(relocateChord(parseChord("Mod+KeyP")!, dvorak).code).toBe("KeyR");
+ expect(relocateChord(parseChord("Mod+KeyB")!, dvorak).code).toBe("KeyN");
+ expect(relocateChord(parseChord("Ctrl+Backquote")!, dvorak).code).toBe("Backquote");
+ // A key that types no character (an F key) has nothing to relocate by.
+ expect(relocateChord(parseChord("F5")!, dvorak).code).toBe("F5");
+ });
+});
diff --git a/packages/web/test/shortcuts-registry.test.ts b/packages/web/test/shortcuts-registry.test.ts
new file mode 100644
index 00000000..56f1de6f
--- /dev/null
+++ b/packages/web/test/shortcuts-registry.test.ts
@@ -0,0 +1,120 @@
+/**
+ * The registry (src/lib/shortcuts/registry.ts) holds the line on what a default may be: it
+ * parses, it carries a modifier or is an F key, no two same-scope defaults collide on any
+ * platform, a literal Ctrl token is used only where macOS must not follow ⌘, no default sits on
+ * a browser-reserved chord, the defaults on a chord a browser also uses are named one by one, and
+ * every id passes the server's grammar.
+ */
+import { describe, expect, it } from "vitest";
+import { hasModifierOrFKey, parseChord } from "../src/lib/shortcuts/chord";
+import { findConflicts } from "../src/lib/shortcuts/conflicts";
+import {
+ SHORTCUT_COMMANDS,
+ SHORTCUT_GROUPS,
+ commandById,
+ defaultChord,
+} from "../src/lib/shortcuts/registry";
+import { browserCommon, browserReserved } from "../src/lib/shortcuts/reserved";
+import { S } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+import type { Chord, CommandId, Platform } from "../src/lib/shortcuts/types";
+
+const PLATFORMS: readonly Platform[] = ["mac", "windows", "linux"];
+/** The id grammar the server enforces on `ui_prefs.keybindings`. */
+const ID_RE = /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)+$/;
+
+function defaultsFor(platform: Platform): Map<CommandId, Chord | null> {
+ return new Map(SHORTCUT_COMMANDS.map((cmd) => [cmd.id, defaultChord(cmd, platform)]));
+}
+
+describe("registry defaults", () => {
+ it("every default string parses", () => {
+ for (const cmd of SHORTCUT_COMMANDS) {
+ for (const text of Object.values(cmd.defaults)) {
+ if (text === null || text === undefined) continue;
+ expect(parseChord(text), `${cmd.id}: ${text}`).not.toBeNull();
+ }
+ }
+ });
+
+ it("no default is a bare key: a modifier or an F key, so nothing steals typing from an input", () => {
+ for (const cmd of SHORTCUT_COMMANDS) {
+ for (const platform of PLATFORMS) {
+ const chord = defaultChord(cmd, platform);
+ if (chord !== null) expect(hasModifierOrFKey(chord), `${cmd.id} on ${platform}`).toBe(true);
+ }
+ }
+ });
+
+ it("no two defaults collide in the same scope on any platform", () => {
+ for (const platform of PLATFORMS) {
+ const conflicts = findConflicts(defaultsFor(platform), SHORTCUT_COMMANDS).filter(
+ (c) => c.kind === "same-scope",
+ );
+ expect(conflicts, platform).toEqual([]);
+ }
+ });
+
+ it("uses a literal Ctrl token only where the macOS default must not follow ⌘", () => {
+ const literalCtrl = SHORTCUT_COMMANDS.filter((cmd) =>
+ Object.values(cmd.defaults).some(
+ (text) => typeof text === "string" && text.includes("Ctrl+"),
+ ),
+ ).map((cmd) => cmd.id);
+ expect(literalCtrl).toEqual(["terminal.toggle", "terminal.close"]);
+ });
+
+ it("puts no default on a browser-reserved chord", () => {
+ for (const platform of PLATFORMS) {
+ const reserved = SHORTCUT_COMMANDS.filter((cmd) => {
+ const chord = defaultChord(cmd, platform);
+ return chord !== null && browserReserved(chord, platform);
+ }).map((cmd) => cmd.id);
+ expect(reserved, platform).toEqual([]);
+ }
+ });
+
+ it("names every default that shares a chord with a browser function", () => {
+ // Save takes the browser's Save Page on purpose; on macOS Chrome binds ⌥⌘P to Page Setup.
+ const expected: Record<Platform, CommandId[]> = {
+ mac: ["palette.toggle", "editor.save"],
+ windows: ["editor.save"],
+ linux: ["editor.save"],
+ };
+ for (const platform of PLATFORMS) {
+ const common = SHORTCUT_COMMANDS.filter((cmd) => {
+ const chord = defaultChord(cmd, platform);
+ return chord !== null && browserCommon(chord, platform);
+ }).map((cmd) => cmd.id);
+ expect(common, platform).toEqual(expected[platform]);
+ }
+ });
+
+ it("ids match the server grammar and are unique", () => {
+ const ids = SHORTCUT_COMMANDS.map((cmd) => cmd.id);
+ for (const id of ids) expect(id).toMatch(ID_RE);
+ expect(new Set(ids).size).toBe(ids.length);
+ });
+
+ it("groups every command under a drawn group", () => {
+ for (const cmd of SHORTCUT_COMMANDS) expect(SHORTCUT_GROUPS).toContain(cmd.group);
+ });
+
+ it("looks commands up by id and refuses unknown ones", () => {
+ expect(commandById("terminal.close").scope).toBe("terminal");
+ expect(() => commandById("terminal.explode" as CommandId)).toThrow(/unknown shortcut command/);
+ });
+});
+
+describe("registry labels", () => {
+ it("has a label for every command and group in both dictionaries", () => {
+ for (const cmd of SHORTCUT_COMMANDS) {
+ expect(S.shortcuts.commands[cmd.id], `zh ${cmd.id}`).toBeTruthy();
+ expect(en.shortcuts.commands[cmd.id], `en ${cmd.id}`).toBeTruthy();
+ }
+ for (const group of SHORTCUT_GROUPS) {
+ expect(S.shortcuts.groups[group], `zh ${group}`).toBeTruthy();
+ expect(en.shortcuts.groups[group], `en ${group}`).toBeTruthy();
+ }
+ });
+});
diff --git a/packages/web/test/shortcuts-store.test.ts b/packages/web/test/shortcuts-store.test.ts
new file mode 100644
index 00000000..1df20374
--- /dev/null
+++ b/packages/web/test/shortcuts-store.test.ts
@@ -0,0 +1,220 @@
+/**
+ * The keymap store (src/lib/shortcuts/store.ts) over an in-memory mirror: overrides resolve
+ * over the defaults, an explicit null unbinds, unknown ids ride along, malformed input reads as
+ * defaults, a row set back to its default disappears, and an external change re-reads.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { parseChord } from "../src/lib/shortcuts/chord";
+import { setPlatformForTests } from "../src/lib/shortcuts/platform";
+import {
+ KEYBINDINGS_KEY,
+ bindingOf,
+ configureKeybindingsStoreForTests,
+ isOverridden,
+ keymap,
+ keymapVersion,
+ noteExternalChange,
+ readStored,
+ resetAll,
+ resetBinding,
+ sanitizeStored,
+ setBinding,
+ subscribeKeymap,
+ type KeybindingsStorage,
+} from "../src/lib/shortcuts/store";
+
+function memStorage(
+ initial: Record<string, string> = {},
+): KeybindingsStorage & { map: Map<string, string> } {
+ const map = new Map(Object.entries(initial));
+ return {
+ map,
+ getItem: (k) => map.get(k) ?? null,
+ setItem: (k, v) => void map.set(k, v),
+ removeItem: (k) => void map.delete(k),
+ };
+}
+
+let storage = memStorage();
+
+beforeEach(() => {
+ storage = memStorage();
+ setPlatformForTests("linux");
+ configureKeybindingsStoreForTests({ storage, layout: null });
+});
+
+afterEach(() => {
+ setPlatformForTests(null);
+ configureKeybindingsStoreForTests({ storage: null, layout: null });
+});
+
+const stored = (): unknown => JSON.parse(storage.map.get(KEYBINDINGS_KEY) ?? "null");
+
+describe("resolution", () => {
+ it("starts from the registry defaults for the platform", () => {
+ expect(bindingOf("terminal.close")).toEqual(parseChord("Mod+Alt+Backquote"));
+ expect(bindingOf("terminal.toggle")).toEqual({
+ ...parseChord("Ctrl+Backquote")!,
+ mod: true,
+ ctrl: false,
+ });
+ setPlatformForTests("mac");
+ configureKeybindingsStoreForTests({});
+ expect(bindingOf("terminal.toggle")).toEqual(parseChord("Ctrl+Backquote"));
+ expect(isOverridden("terminal.close")).toBe(false);
+ });
+
+ it("overlays the platform's stored section, and an explicit null unbinds", () => {
+ storage.map.set(
+ KEYBINDINGS_KEY,
+ JSON.stringify({
+ v: 1,
+ linux: { "terminal.close": "Mod+Alt+KeyW", "editor.save": null },
+ mac: { "terminal.close": "Mod+KeyE" },
+ }),
+ );
+ configureKeybindingsStoreForTests({});
+ expect(bindingOf("terminal.close")).toEqual(parseChord("Mod+Alt+KeyW"));
+ expect(bindingOf("editor.save")).toBeNull();
+ expect(bindingOf("terminal.toggle")).not.toBeNull();
+ expect(isOverridden("terminal.close")).toBe(true);
+ expect(isOverridden("editor.save")).toBe(true);
+ expect(isOverridden("terminal.toggle")).toBe(false);
+ });
+
+ it("ignores an unknown id and an unparseable chord when applying, keeping the default", () => {
+ storage.map.set(
+ KEYBINDINGS_KEY,
+ JSON.stringify({ v: 1, linux: { "future.command": "Mod+KeyZ", "terminal.close": "Cmd-W" } }),
+ );
+ configureKeybindingsStoreForTests({});
+ expect(bindingOf("terminal.close")).toEqual(parseChord("Mod+Alt+Backquote"));
+ expect(keymap().has("future.command" as never)).toBe(false);
+ });
+
+ it("reads malformed JSON, a foreign shape and a wrong version as no overrides", () => {
+ for (const raw of [
+ "{not json",
+ '"a string"',
+ "[]",
+ '{"v":2,"linux":{"terminal.close":null}}',
+ '{"linux":{"terminal.close":null}}',
+ ]) {
+ storage.map.set(KEYBINDINGS_KEY, raw);
+ configureKeybindingsStoreForTests({});
+ expect(bindingOf("terminal.close"), raw).toEqual(parseChord("Mod+Alt+Backquote"));
+ expect(readStored(storage), raw).toEqual({ v: 1 });
+ }
+ });
+
+ it("sanitizes the document shape: only the three sections, only string-or-null values", () => {
+ expect(
+ sanitizeStored({
+ v: 1,
+ linux: { a: "Mod+KeyA", b: null, c: 3 },
+ ios: { a: "Mod+KeyA" },
+ mac: [],
+ extra: true,
+ }),
+ ).toEqual({ v: 1, linux: { a: "Mod+KeyA", b: null } });
+ });
+});
+
+describe("writes", () => {
+ it("stores an override in the platform section and notifies subscribers", () => {
+ let notified = 0;
+ const unsubscribe = subscribeKeymap(() => notified++);
+ const before = keymapVersion();
+ setBinding("terminal.close", parseChord("Mod+Alt+KeyW"));
+ expect(bindingOf("terminal.close")).toEqual(parseChord("Mod+Alt+KeyW"));
+ expect(stored()).toEqual({ v: 1, linux: { "terminal.close": "Mod+Alt+KeyW" } });
+ expect(notified).toBe(1);
+ expect(keymapVersion()).toBeGreaterThan(before);
+ unsubscribe();
+ });
+
+ it("stores an explicit unbind as null", () => {
+ setBinding("editor.save", null);
+ expect(bindingOf("editor.save")).toBeNull();
+ expect(stored()).toEqual({ v: 1, linux: { "editor.save": null } });
+ });
+
+ it("removes a row set back to its default, and drops an emptied section", () => {
+ setBinding("terminal.close", parseChord("Mod+Alt+KeyW"));
+ setBinding("terminal.close", parseChord("Ctrl+Alt+Backquote"));
+ expect(isOverridden("terminal.close")).toBe(false);
+ expect(stored()).toEqual({ v: 1 });
+ });
+
+ it("treats a literal Ctrl chord as Mod on Linux, so Ctrl+` is the terminal toggle's default there", () => {
+ setBinding("terminal.toggle", parseChord("Ctrl+Backquote"));
+ expect(isOverridden("terminal.toggle")).toBe(false);
+ });
+
+ it("preserves unknown ids and the other platforms' sections on write", () => {
+ storage.map.set(
+ KEYBINDINGS_KEY,
+ JSON.stringify({
+ v: 1,
+ linux: { "future.command": "Mod+KeyZ" },
+ mac: { "terminal.close": "Mod+KeyE" },
+ }),
+ );
+ configureKeybindingsStoreForTests({});
+ setBinding("editor.save", parseChord("Mod+Shift+KeyS"));
+ expect(stored()).toEqual({
+ v: 1,
+ linux: { "future.command": "Mod+KeyZ", "editor.save": "Mod+Shift+KeyS" },
+ mac: { "terminal.close": "Mod+KeyE" },
+ });
+ resetBinding("editor.save");
+ expect(stored()).toEqual({
+ v: 1,
+ linux: { "future.command": "Mod+KeyZ" },
+ mac: { "terminal.close": "Mod+KeyE" },
+ });
+ });
+
+ it("resetAll clears the current platform's section only", () => {
+ storage.map.set(
+ KEYBINDINGS_KEY,
+ JSON.stringify({ v: 1, linux: { "editor.save": null }, mac: { "editor.save": null } }),
+ );
+ configureKeybindingsStoreForTests({});
+ resetAll();
+ expect(stored()).toEqual({ v: 1, mac: { "editor.save": null } });
+ expect(bindingOf("editor.save")).toEqual(parseChord("Mod+KeyS"));
+ });
+});
+
+describe("external changes and the keyboard layout", () => {
+ it("re-reads the mirror when another tab wrote it, and only for its own key", () => {
+ expect(bindingOf("editor.save")).toEqual(parseChord("Mod+KeyS"));
+ storage.map.set(KEYBINDINGS_KEY, JSON.stringify({ v: 1, linux: { "editor.save": null } }));
+ expect(bindingOf("editor.save")).toEqual(parseChord("Mod+KeyS")); // still cached
+ noteExternalChange("penguin.theme");
+ expect(bindingOf("editor.save")).toEqual(parseChord("Mod+KeyS"));
+ noteExternalChange(KEYBINDINGS_KEY);
+ expect(bindingOf("editor.save")).toBeNull();
+ storage.map.delete(KEYBINDINGS_KEY);
+ noteExternalChange(null); // a whole-store clear
+ expect(bindingOf("editor.save")).toEqual(parseChord("Mod+KeyS"));
+ });
+
+ it("relocates defaults to the layout's keys and treats the relocated chord as the default", () => {
+ // US-Dvorak types p on the physical R key and r on the P key.
+ const dvorak = new Map([
+ ["KeyP", "r"],
+ ["KeyR", "p"],
+ ]);
+ configureKeybindingsStoreForTests({ layout: dvorak });
+ expect(bindingOf("palette.toggle")?.code).toBe("KeyR");
+ // The user records the key labelled P (physically KeyR): that is the default, not an override.
+ setBinding("palette.toggle", parseChord("Mod+Alt+KeyR"));
+ expect(isOverridden("palette.toggle")).toBe(false);
+ // A stored user chord is physical and does not move.
+ setBinding("palette.toggle", parseChord("Mod+Alt+KeyP"));
+ expect(bindingOf("palette.toggle")?.code).toBe("KeyP");
+ expect(stored()).toEqual({ v: 1, linux: { "palette.toggle": "Mod+Alt+KeyP" } });
+ });
+});
diff --git a/packages/web/test/terminal-clipboard.test.ts b/packages/web/test/terminal-clipboard.test.ts
new file mode 100644
index 00000000..ba3162d1
--- /dev/null
+++ b/packages/web/test/terminal-clipboard.test.ts
@@ -0,0 +1,122 @@
+/**
+ * The terminal's clipboard keys (src/lib/shortcuts/terminal-clipboard.ts), split by platform:
+ * the Windows Terminal conventions off a Mac; on a Mac the native ⌘C / ⌘V only, so Ctrl+C is
+ * always SIGINT and Ctrl+V reaches the shell.
+ */
+import { describe, expect, it } from "vitest";
+import { terminalClipboardAction } from "../src/lib/shortcuts/terminal-clipboard";
+import type { KeyLike } from "../src/lib/shortcuts/types";
+
+function key(overrides: Partial<KeyLike> & { key: string }): KeyLike {
+ return { code: "", ctrlKey: false, metaKey: false, altKey: false, shiftKey: false, ...overrides };
+}
+
+describe("Windows and Linux", () => {
+ for (const platform of ["windows", "linux"] as const) {
+ it(`${platform}: copies on Ctrl+Shift+C, Ctrl+Insert and Ctrl+C over a selection`, () => {
+ expect(
+ terminalClipboardAction(
+ key({ key: "C", code: "KeyC", ctrlKey: true, shiftKey: true }),
+ platform,
+ false,
+ ),
+ ).toBe("copy");
+ expect(
+ terminalClipboardAction(
+ key({ key: "Insert", code: "Insert", ctrlKey: true }),
+ platform,
+ false,
+ ),
+ ).toBe("copy");
+ expect(
+ terminalClipboardAction(key({ key: "c", code: "KeyC", ctrlKey: true }), platform, true),
+ ).toBe("copy");
+ // No selection: Ctrl+C is SIGINT.
+ expect(
+ terminalClipboardAction(key({ key: "c", code: "KeyC", ctrlKey: true }), platform, false),
+ ).toBeNull();
+ // Ctrl+Alt+C is neither.
+ expect(
+ terminalClipboardAction(
+ key({ key: "c", code: "KeyC", ctrlKey: true, altKey: true }),
+ platform,
+ true,
+ ),
+ ).toBeNull();
+ });
+
+ it(`${platform}: pastes on Ctrl+V, Ctrl+Shift+V and Shift+Insert`, () => {
+ expect(
+ terminalClipboardAction(key({ key: "v", code: "KeyV", ctrlKey: true }), platform, false),
+ ).toBe("paste");
+ expect(
+ terminalClipboardAction(
+ key({ key: "V", code: "KeyV", ctrlKey: true, shiftKey: true }),
+ platform,
+ false,
+ ),
+ ).toBe("paste");
+ expect(
+ terminalClipboardAction(
+ key({ key: "Insert", code: "Insert", shiftKey: true }),
+ platform,
+ false,
+ ),
+ ).toBe("paste");
+ expect(
+ terminalClipboardAction(
+ key({ key: "v", code: "KeyV", ctrlKey: true, altKey: true }),
+ platform,
+ false,
+ ),
+ ).toBeNull();
+ // The Windows / Super key belongs to the OS.
+ expect(
+ terminalClipboardAction(key({ key: "v", code: "KeyV", metaKey: true }), platform, false),
+ ).toBeNull();
+ });
+ }
+});
+
+describe("macOS", () => {
+ it("does not treat Ctrl+C over a selection as a copy: it is SIGINT", () => {
+ expect(
+ terminalClipboardAction(key({ key: "c", code: "KeyC", ctrlKey: true }), "mac", true),
+ ).toBeNull();
+ });
+
+ it("does not swallow Ctrl+V: it is the shell's verbatim insert", () => {
+ expect(
+ terminalClipboardAction(key({ key: "v", code: "KeyV", ctrlKey: true }), "mac", false),
+ ).toBeNull();
+ expect(
+ terminalClipboardAction(key({ key: "Insert", code: "Insert", shiftKey: true }), "mac", false),
+ ).toBeNull();
+ });
+
+ it("leaves ⌘C and ⌘V to the browser's native copy and paste", () => {
+ expect(
+ terminalClipboardAction(key({ key: "c", code: "KeyC", metaKey: true }), "mac", true),
+ ).toBeNull();
+ expect(
+ terminalClipboardAction(key({ key: "v", code: "KeyV", metaKey: true }), "mac", false),
+ ).toBeNull();
+ });
+
+ it("keeps Ctrl+Shift+C as a copy", () => {
+ expect(
+ terminalClipboardAction(
+ key({ key: "C", code: "KeyC", ctrlKey: true, shiftKey: true }),
+ "mac",
+ false,
+ ),
+ ).toBe("copy");
+ expect(
+ terminalClipboardAction(
+ key({ key: "C", code: "KeyC", ctrlKey: true, shiftKey: true, metaKey: true }),
+ "mac",
+ false,
+ ),
+ ).toBeNull();
+ });
+});
diff --git a/packages/web/test/terminal-keys.test.ts b/packages/web/test/terminal-keys.test.ts
new file mode 100644
index 00000000..f167a64a
--- /dev/null
+++ b/packages/web/test/terminal-keys.test.ts
@@ -0,0 +1,136 @@
+/**
+ * The focused terminal's key decision (src/lib/shortcuts/terminal-keys.ts) as a table: the close
+ * chord (⌃⌥` on a Mac, Ctrl+Alt+` elsewhere) closing while Ctrl+W reaches readline everywhere, the
+ * toggle skipping the shell, the unanswered chord reaching the shell, the missing-close fallback,
+ * and the repeat.
+ */
+import { describe, expect, it } from "vitest";
+import { SHORTCUT_COMMANDS, defaultChord } from "../src/lib/shortcuts/registry";
+import { terminalKeyAction, type TerminalKeyHost } from "../src/lib/shortcuts/terminal-keys";
+import type { Chord, CommandId, KeyLike, Platform } from "../src/lib/shortcuts/types";
+
+function defaults(platform: Platform): Map<CommandId, Chord | null> {
+ return new Map(SHORTCUT_COMMANDS.map((cmd) => [cmd.id, defaultChord(cmd, platform)]));
+}
+
+function key(overrides: Partial<KeyLike> & { code: string }): KeyLike {
+ return { key: "", ctrlKey: false, metaKey: false, altKey: false, shiftKey: false, ...overrides };
+}
+
+const host = (overrides: Partial<TerminalKeyHost> = {}): TerminalKeyHost => ({
+ canClose: true,
+ hasHandler: (id) => id === "terminal.toggle",
+ ...overrides,
+});
+
+describe("terminalKeyAction", () => {
+ const table: Array<[string, Platform, KeyLike, TerminalKeyHost, string]> = [
+ [
+ "⌃⌥` closes on a Mac",
+ "mac",
+ key({ code: "Backquote", ctrlKey: true, altKey: true }),
+ host(),
+ "close",
+ ],
+ [
+ "Ctrl+Alt+` closes off a Mac",
+ "linux",
+ key({ code: "Backquote", ctrlKey: true, altKey: true }),
+ host(),
+ "close",
+ ],
+ [
+ "Ctrl+Alt+` closes on Windows",
+ "windows",
+ key({ code: "Backquote", ctrlKey: true, altKey: true }),
+ host(),
+ "close",
+ ],
+ [
+ "⌥⌘` is not the close: the chord is literal Control on a Mac too",
+ "mac",
+ key({ code: "Backquote", metaKey: true, altKey: true }),
+ host(),
+ "shell",
+ ],
+ ["Ctrl+W is readline's on a Mac", "mac", key({ code: "KeyW", ctrlKey: true }), host(), "shell"],
+ [
+ "Ctrl+W is readline's off a Mac",
+ "linux",
+ key({ code: "KeyW", ctrlKey: true }),
+ host(),
+ "shell",
+ ],
+ [
+ "Ctrl+W is readline's on Windows",
+ "windows",
+ key({ code: "KeyW", ctrlKey: true }),
+ host(),
+ "shell",
+ ],
+ ["⌘W is not the close on a Mac", "mac", key({ code: "KeyW", metaKey: true }), host(), "shell"],
+ [
+ "the toggle skips the shell everywhere",
+ "mac",
+ key({ code: "Backquote", ctrlKey: true }),
+ host(),
+ "skip-shell",
+ ],
+ [
+ "the toggle skips the shell on Linux",
+ "linux",
+ key({ code: "Backquote", ctrlKey: true }),
+ host(),
+ "skip-shell",
+ ],
+ [
+ "an unanswered chord is the shell's (Ctrl+Alt+P before the palette)",
+ "linux",
+ key({ code: "KeyP", ctrlKey: true, altKey: true }),
+ host(),
+ "shell",
+ ],
+ [
+ "an editor-scoped chord is the shell's",
+ "linux",
+ key({ code: "KeyS", ctrlKey: true }),
+ host(),
+ "shell",
+ ],
+ ["plain typing is the shell's", "mac", key({ code: "KeyW", key: "w" }), host(), "shell"],
+ [
+ "a plain Ctrl+C is the shell's",
+ "linux",
+ key({ code: "KeyC", ctrlKey: true }),
+ host(),
+ "shell",
+ ],
+ [
+ "with no close on offer the chord goes to the shell",
+ "linux",
+ key({ code: "Backquote", ctrlKey: true, altKey: true }),
+ host({ canClose: false }),
+ "shell",
+ ],
+ [
+ "a held close chord is consumed, not re-run",
+ "mac",
+ key({ code: "Backquote", ctrlKey: true, altKey: true, repeat: true }),
+ host(),
+ "consume",
+ ],
+ [
+ "a held toggle still skips the shell (the dispatcher swallows the repeat)",
+ "linux",
+ key({ code: "Backquote", ctrlKey: true, repeat: true }),
+ host(),
+ "skip-shell",
+ ],
+ ];
+
+ for (const [name, platform, e, h, expected] of table) {
+ it(name, () => {
+ expect(terminalKeyAction(e, defaults(platform), platform, h)).toBe(expected);
+ });
+ }
+});