A local-first multi-agent app development platform, built on PenguinHarness
feat(web,server): a Shortcuts settings page, with bindings stored per account (#789)
Yaowei Zhengccf6d70c5e07
diff --git a/changelog/unreleased/2026-09-18-shortcut-settings.md b/changelog/unreleased/2026-09-18-shortcut-settings.mdnew file mode 100644index 00000000..8c5e5020--- /dev/null+++ b/changelog/unreleased/2026-09-18-shortcut-settings.md@@ -0,0 +1,34 @@+# A Shortcuts settings page, with bindings stored per account++- **Date:** 2026-09-18+- **Type:** feature+- **Scope:** `web`, `server`+- **PR:** [#789](https://github.com/Prism-Shadow/penguin-harness/pull/789)++[中文版](2026-09-18-shortcut-settings.zh.md)++The System settings dialog gained a **Keyboard shortcuts** page in the personal group, after+Appearance. It lists every rebindable command by group, in a compact list with no rule between rows,+with its current chord written the way the platform writes it (`⌥⌘P` on a Mac, `Ctrl+Alt+P`+elsewhere). Clicking a chord records the next combination pressed: Esc cancels, Backspace or Delete+clears the binding, and a key without Ctrl or Alt (⌘ or ⌃ on macOS; Shift alone is typing) is+refused unless it is an F key. Each row can go back to its default, and the page can reset every+override at once. Bindings are stored per account in `ui_prefs.keybindings`; a change applies at+once in every tab of the same browser, and the account's other browsers and the desktop app pick it+up the next time they load.++## Details++- A row says what stands in its binding's way, from the moment the binding lands: another command+ on the same chord (which one wins is stated), a chord the browser keeps for itself (it only works+ in the desktop app; in the attention tone), a chord the desktop app's menu also carries (shown in+ the desktop app), or a chord the browser also uses (in a browser tab the binding takes that+ browser function over). Bindings are shared by the browser and the desktop app, so the browser's+ notes show in either.+- `PUT /api/me/prefs` validates `keybindings`: version 1, per-platform sections (`mac`, `windows`,+ `linux`) of at most 64 entries, command ids and chord strings checked against their grammar and+ length caps, the whole document at most 8 KiB. An invalid document is refused with+ `invalid_keybindings` and nothing from that request is stored.+- After sign-in the account's copy replaces the browser mirror; a mirror the account knows nothing+ about is cleared, and an edit made under the previous account is never read as this account's.+ A write that fails to reach the server is reported and leaves the mirror in place.diff --git a/changelog/unreleased/2026-09-18-shortcut-settings.zh.md b/changelog/unreleased/2026-09-18-shortcut-settings.zh.mdnew file mode 100644index 00000000..2ce80379--- /dev/null+++ b/changelog/unreleased/2026-09-18-shortcut-settings.zh.md@@ -0,0 +1,16 @@+# 新增「快捷键」设置页,绑定按账号保存++- **Date:** 2026-09-18+- **Type:** feature+- **Scope:** `web`, `server`+- **PR:** [#789](https://github.com/Prism-Shadow/penguin-harness/pull/789)++[English](2026-09-18-shortcut-settings.md)++系统设置对话框的「个人」分组在「外观」之后新增**快捷键**页:以紧凑列表(行间不加分隔线)按分组列出全部可改绑的命令及其当前组合,按平台写法显示(Mac 上为 `⌥⌘P`,其余平台为 `Ctrl+Alt+P`)。点击组合即录制下一次按下的组合:Esc 取消,Backspace 或 Delete 清除绑定,不带 Ctrl 或 Alt(macOS 为 ⌘ 或 ⌃;单独的 Shift 只是输入)的按键除 F 键外不接受。每行可恢复默认,整页可一次清除全部覆盖。绑定按账号存于 `ui_prefs.keybindings`;改动在同一浏览器的其他标签页即刻跟随,该账号的其他浏览器与桌面应用在下次加载时取得。++## 细节++- 绑定一落定,该行即说明挡在它前面的东西:另一条命令使用同一组合(并说明谁生效)、浏览器自己保留的组合(只在桌面应用里生效,以 attention 色调提示)、桌面应用菜单同样带有的组合(在桌面应用中提示),或浏览器本身也用的组合(在浏览器标签页里,绑定会取代浏览器的那个功能)。绑定由浏览器与桌面应用共用,浏览器相关的提示在两边都会显示。+- `PUT /api/me/prefs` 校验 `keybindings`:版本号 1,按平台分节(`mac`、`windows`、`linux`),每节至多 64 条,命令 id 与组合串按文法与长度上限检查,整体不超过 8 KiB。不合法的文档以 `invalid_keybindings` 拒绝,该请求不落库任何内容。+- 登录后账号的副本覆盖浏览器镜像;账号中不存在的镜像会被清除,上一个账号做出的修改不会被当作本账号的。写入服务端失败时给出提示并保留镜像。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex ccf68e68..701bb75e 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -358,6 +358,20 @@ export interface DraftShortcut {prompt: string;}+/**+ * The account's keyboard shortcut overrides, one section per platform (the Web App's `Mod` token+ * is ⌘ on macOS and Ctrl elsewhere, so a deliberate macOS-only binding must not leak to Windows).+ * Each section maps a command id to a chord string ("Mod+Shift+KeyW") or null (explicitly+ * unbound); only rows that differ from the Web App's default are present. Bounded on write by+ * services/keybindings.ts.+ */+export interface StoredKeybindings {+ v: 1;+ mac?: Record<string, string | null>;+ windows?: Record<string, string | null>;+ linux?: Record<string, string | null>;+}+/** User UI preferences (SQLite ui_prefs, free-form JSON; known keys declared here). */export interface UiPrefs {theme?: "light" | "dark";@@ -381,6 +395,8 @@ export interface UiPrefs {* known key holding user-authored text rather than a flag or an id.*/draftShortcuts?: DraftShortcut[];+ /** Keyboard shortcut overrides, replaced whole on every write and validated by services/keybindings.ts. */+ keybindings?: StoredKeybindings;/** Personal company-mode switch (default on): off only hides this user's mode switch; organizations keep running. */companyMode?: boolean;/** The work mode the user last chose in the shell: development (default) or company. */diff --git a/packages/server/src/http/routes/me.ts b/packages/server/src/http/routes/me.tsindex 9632bd8b..2b03b9cf 100644--- a/packages/server/src/http/routes/me.ts+++ b/packages/server/src/http/routes/me.ts@@ -40,6 +40,7 @@ export interface MeRouteDeps {}import { resolvePreviewTarget } from "../../services/preview-token.js";import { validateDraftShortcuts } from "../../services/draft-shortcuts.js";+import { validateKeybindings } from "../../services/keybindings.js";import {INLINE_IMAGE_MAX_MB,MAX_ATTACHMENT_COUNT,@@ -234,6 +235,9 @@ export function meRoutes(deps: MeRouteDeps): Hono<AppEnv> {if (body.draftShortcuts !== undefined) {body.draftShortcuts = validateDraftShortcuts(body.draftShortcuts);}+ if (body.keybindings !== undefined) {+ body.keybindings = validateKeybindings(body.keybindings);+ }const raw = deps.prefsRepo.get(c.var.user.userId);let current: UiPrefs = {};if (raw !== null) {diff --git a/packages/server/src/services/keybindings.ts b/packages/server/src/services/keybindings.tsnew file mode 100644index 00000000..9419e3d9--- /dev/null+++ b/packages/server/src/services/keybindings.ts@@ -0,0 +1,76 @@+/**+ * Bounds on the account's keyboard shortcut overrides (`ui_prefs.keybindings`).+ *+ * `ui_prefs` is free-form JSON shallow-merged by `PUT /api/me/prefs`, so a key that holds a+ * structured document has to be bounded on the write path (the `draftShortcuts` precedent): the+ * Web App's settings page is the normal producer, but a request that never went through it must+ * not be able to store more than this either. The shape is the Web App's `StoredKeybindings`:+ * `{ v: 1, mac?: {...}, windows?: {...}, linux?: {...} }`, each section mapping a command id to a+ * chord string or null (explicitly unbound). Ids the server does not know are accepted — the+ * registry lives in the Web App and grows without a server release — as long as they fit the id+ * grammar, and chords are checked against the grammar only, never against a key list.+ */+import { HttpError } from "../http/errors.js";+import type { StoredKeybindings } from "../api/types.js";++export const KEYBINDINGS_SECTION_MAX = 64;+export const KEYBINDINGS_ID_MAX = 64;+export const KEYBINDINGS_CHORD_MAX = 48;+/** Serialized size of the whole document. */+export const KEYBINDINGS_BYTES_MAX = 8 * 1024;++const SECTIONS = ["mac", "windows", "linux"] as const;+/** Dotted segments, each starting lower-case; camelCase inside a segment is allowed (`dock.toggleRight`). */+const ID_RE = /^[a-z][a-zA-Z0-9]*(\.[a-z][a-zA-Z0-9]*)+$/;+/** The Web App's chord grammar: modifier tokens in a fixed order, then a KeyboardEvent.code. */+const CHORD_RE = /^(Mod\+)?(Ctrl\+)?(Alt\+)?(Shift\+)?[A-Za-z][A-Za-z0-9]*$/;++function invalid(message: string): HttpError {+ return new HttpError(400, "invalid_keybindings", message);+}++/**+ * Validates an incoming `keybindings` value and returns the normalized document to store: only+ * the known sections, only string-or-null values, nothing else riding along. Anything invalid is+ * a 400 that writes nothing, since the document is replaced whole.+ */+export function validateKeybindings(value: unknown): StoredKeybindings {+ if (value === null || typeof value !== "object" || Array.isArray(value)) {+ throw invalid("keybindings must be an object.");+ }+ const raw = value as Record<string, unknown>;+ if (raw.v !== 1) throw invalid("keybindings.v must be 1.");+ const out: StoredKeybindings = { v: 1 };+ for (const section of SECTIONS) {+ const entries = raw[section];+ if (entries === undefined) continue;+ if (entries === null || typeof entries !== "object" || Array.isArray(entries)) {+ throw invalid(`keybindings.${section} must be an object.`);+ }+ const pairs = Object.entries(entries as Record<string, unknown>);+ if (pairs.length > KEYBINDINGS_SECTION_MAX) {+ throw invalid(`keybindings.${section} must hold at most ${KEYBINDINGS_SECTION_MAX} entries.`);+ }+ const clean: Record<string, string | null> = {};+ for (const [id, chord] of pairs) {+ if (id.length > KEYBINDINGS_ID_MAX || !ID_RE.test(id)) {+ throw invalid(`keybindings.${section} has an invalid command id.`);+ }+ if (chord !== null) {+ if (+ typeof chord !== "string" ||+ chord.length > KEYBINDINGS_CHORD_MAX ||+ !CHORD_RE.test(chord)+ ) {+ throw invalid(`keybindings.${section}.${id} must be null or a chord string.`);+ }+ }+ clean[id] = chord;+ }+ out[section] = clean;+ }+ if (JSON.stringify(out).length > KEYBINDINGS_BYTES_MAX) {+ throw invalid(`keybindings must serialize to at most ${KEYBINDINGS_BYTES_MAX} bytes.`);+ }+ return out;+}diff --git a/packages/server/test/keybindings.test.ts b/packages/server/test/keybindings.test.tsnew file mode 100644index 00000000..3d6c1c89--- /dev/null+++ b/packages/server/test/keybindings.test.ts@@ -0,0 +1,151 @@+/**+ * The account's keyboard shortcut overrides, stored under `ui_prefs.keybindings`.+ *+ * The validator's cases pin the documented shape and each bound; the route cases go through the+ * real `PUT /api/me/prefs`, because the two claims that matter are about the route: a rejected+ * write stores nothing, and an accepted one round-trips through GET without disturbing the other+ * preferences merged into the same object.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { apiClient, createTestApp, provisionUser } from "./helpers.js";+import type { TestApp } from "./helpers.js";+import {+ KEYBINDINGS_BYTES_MAX,+ KEYBINDINGS_CHORD_MAX,+ KEYBINDINGS_ID_MAX,+ KEYBINDINGS_SECTION_MAX,+ validateKeybindings,+} from "../src/services/keybindings.js";+import { HttpError } from "../src/http/errors.js";++const rejects = (value: unknown, pattern: RegExp): void => {+ try {+ validateKeybindings(value);+ } catch (err) {+ expect(err).toBeInstanceOf(HttpError);+ expect((err as HttpError).status).toBe(400);+ expect((err as HttpError).code).toBe("invalid_keybindings");+ expect((err as HttpError).message).toMatch(pattern);+ return;+ }+ throw new Error(`expected ${JSON.stringify(value)} to be rejected`);+};++describe("validateKeybindings", () => {+ it("accepts the documented shape and returns it normalized", () => {+ const doc = {+ v: 1,+ mac: { "terminal.close": "Mod+Alt+KeyW", "editor.save": null },+ windows: { "dock.toggleRight": "Mod+Alt+KeyB" },+ linux: { "future.command.here": "F5" },+ };+ expect(validateKeybindings(doc)).toEqual(doc);+ expect(validateKeybindings({ v: 1 })).toEqual({ v: 1 });+ });++ it("drops sections it does not know rather than storing them", () => {+ expect(validateKeybindings({ v: 1, ios: { "terminal.close": "Mod+KeyW" }, extra: 1 })).toEqual({+ v: 1,+ });+ });++ it("rejects a non-object, a wrong version and a malformed section", () => {+ rejects(null, /must be an object/);+ rejects([], /must be an object/);+ rejects("Mod+KeyW", /must be an object/);+ rejects({ v: 2 }, /v must be 1/);+ rejects({}, /v must be 1/);+ rejects({ v: 1, mac: [] }, /mac must be an object/);+ rejects({ v: 1, mac: null }, /mac must be an object/);+ });++ it("rejects an id outside the grammar or over the length cap", () => {+ rejects({ v: 1, mac: { terminal: null } }, /invalid command id/);+ rejects({ v: 1, mac: { "Terminal.close": null } }, /invalid command id/);+ rejects({ v: 1, mac: { "terminal..close": null } }, /invalid command id/);+ rejects({ v: 1, mac: { "terminal.close ": null } }, /invalid command id/);+ const long = `a.${"b".repeat(KEYBINDINGS_ID_MAX)}`;+ rejects({ v: 1, mac: { [long]: null } }, /invalid command id/);+ });++ it("rejects a chord outside the grammar, a non-string, or one over the length cap", () => {+ rejects({ v: 1, mac: { "terminal.close": "Cmd-W" } }, /must be null or a chord string/);+ rejects(+ { v: 1, mac: { "terminal.close": "Shift+Mod+KeyW" } },+ /must be null or a chord string/,+ );+ rejects({ v: 1, mac: { "terminal.close": 7 } }, /must be null or a chord string/);+ rejects({ v: 1, mac: { "terminal.close": "" } }, /must be null or a chord string/);+ rejects(+ { v: 1, mac: { "terminal.close": `Mod+${"K".repeat(KEYBINDINGS_CHORD_MAX)}` } },+ /must be null or a chord string/,+ );+ });++ it("rejects more entries than a section may hold, and a document over the byte cap", () => {+ const tooMany = Object.fromEntries(+ Array.from({ length: KEYBINDINGS_SECTION_MAX + 1 }, (_, i) => [`cmd.c${i}`, null]),+ );+ rejects({ v: 1, mac: tooMany }, /at most/);+ // Three full sections of maximal ids and chords exceed the byte cap while each stays legal.+ const id = (i: number) =>+ `a.${"b".repeat(KEYBINDINGS_ID_MAX - 4)}${String(i).padStart(2, "0")}`;+ const chord = `Mod+${"K".repeat(KEYBINDINGS_CHORD_MAX - 4)}`;+ const big = Object.fromEntries(+ Array.from({ length: KEYBINDINGS_SECTION_MAX }, (_, i) => [id(i), chord]),+ );+ expect(JSON.stringify({ v: 1, mac: big, windows: big, linux: big }).length).toBeGreaterThan(+ KEYBINDINGS_BYTES_MAX,+ );+ rejects({ v: 1, mac: big, windows: big, linux: big }, /bytes/);+ });+});++describe("PUT /api/me/prefs keybindings", () => {+ let t: TestApp;+ let api: ReturnType<typeof apiClient>;++ beforeEach(async () => {+ t = await createTestApp();+ const { cookie } = await provisionUser(t.app, "kira");+ api = apiClient(t.app, cookie);+ });+ afterEach(async () => {+ await t.cleanup();+ });++ const readPrefs = async (): Promise<Record<string, unknown>> => {+ const body = (await (await api.get("/api/me/prefs")).json()) as {+ prefs: Record<string, unknown>;+ };+ return body.prefs;+ };++ it("round-trips a valid document and leaves the other preferences alone", async () => {+ await api.put("/api/me/prefs", { lastProjectId: "default_project" });+ const doc = { v: 1, linux: { "terminal.close": "Mod+Alt+KeyW", "editor.save": null } };+ const res = await api.put("/api/me/prefs", { keybindings: doc });+ expect(res.status).toBe(200);+ expect(await readPrefs()).toEqual({ lastProjectId: "default_project", keybindings: doc });+ });++ it("stores nothing from a request whose document is invalid", async () => {+ await api.put("/api/me/prefs", { keybindings: { v: 1, linux: { "editor.save": null } } });+ const res = await api.put("/api/me/prefs", {+ lastProjectId: "other",+ keybindings: { v: 1, linux: { "editor.save": "Cmd-S" } },+ });+ expect(res.status).toBe(400);+ expect(await res.text()).toContain("invalid_keybindings");+ const prefs = await readPrefs();+ expect(prefs.keybindings).toEqual({ v: 1, linux: { "editor.save": null } });+ expect(prefs.lastProjectId).toBeUndefined();+ });++ it("is per user", async () => {+ await api.put("/api/me/prefs", { keybindings: { v: 1, mac: { "editor.save": null } } });+ const other = apiClient(t.app, (await provisionUser(t.app, "liam")).cookie);+ const theirs = (await (await other.get("/api/me/prefs")).json()) as { prefs: object };+ expect(theirs.prefs).toEqual({});+ });+});diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsxindex 1804a2a9..714af7fe 100644--- a/packages/web/src/components/layout/app-layout.tsx+++ b/packages/web/src/components/layout/app-layout.tsx@@ -39,6 +39,7 @@ import { prepareNewChatDraft } from "../../features/chat/new-chat";import { ChangePasswordDialog } from "../account/change-password-dialog";import { UpdateModal } from "../account/update-modal";import { TerminalDockRuntime } from "../../features/terminal/terminal-view-pool";+import { ShortcutRuntime } from "../../features/settings/shortcut-runtime";import { BuiltinBrowserLayer } from "../../features/builtin-browser/browser-layer";import { setDockScope } from "../../features/dock/dock-state";import { AppPalette } from "../../features/palette/app-palette";@@ -522,6 +523,8 @@ export function AppLayout() {views live in this pool and are adopted into dock tab bodies by DOM handoff,so navigating between pages never reconnects a terminal. */}<TerminalDockRuntime />+ {/* Reconciles the shortcut mirror with the account's prefs and carries edits back. */}+ <ShortcutRuntime />{/* The built-in browser's pages (desktop app only): they live here, outside every page,and are laid over the dock's browser tab by coordinates — a webview moved in the DOMreloads, so navigating the app must never re-parent one. */}diff --git a/packages/web/src/components/ui/kbd.tsx b/packages/web/src/components/ui/kbd.tsxindex bd84c09b..0d89d030 100644--- a/packages/web/src/components/ui/kbd.tsx+++ b/packages/web/src/components/ui/kbd.tsx@@ -9,10 +9,24 @@ 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 }) {+/** `picker`: the dock picker's small kbd beside a row label; `control`: inside a settings control, at the form rung. */+const sizeClass = {+ picker: "font-mono text-[10px]",+ control: "font-mono text-xs",+};++export function Kbd({+ chord,+ size: rung = "picker",+ className = "",+}: {+ chord: Chord;+ size?: keyof typeof sizeClass;+ className?: string;+}) {const platform = currentPlatform();const label = formatChord(chord, platform, keyboardLayout() ?? undefined);- const size = "font-mono text-[10px]";+ const size = sizeClass[rung];if (platform === "mac") return <kbd className={`${size} ${className}`}>{label}</kbd>;const tokens = label.split("+");return (diff --git a/packages/web/src/features/settings/settings-dialog.tsx b/packages/web/src/features/settings/settings-dialog.tsxindex 544cda92..f6c3aebb 100644--- a/packages/web/src/features/settings/settings-dialog.tsx+++ b/packages/web/src/features/settings/settings-dialog.tsx@@ -23,6 +23,7 @@ import { COMPANY_MODE_ICON, GEAR_ICON } from "../../components/ui/icons";import { ProfileSection } from "./profile-section";import { GeneralSection } from "./general-section";import { AppearanceSection } from "./appearance-section";+import { ShortcutsSection } from "./shortcuts-section";import { AccountSection } from "./account-section";import { ProxySection } from "./proxy-section";import { UploadsSection } from "./uploads-section";@@ -39,6 +40,9 @@ const SECTION_ICONS: Record<SettingsSectionKey, string> = {/** Sun: appearance. */appearance:"M12 17a5 5 0 1 0 0-10 5 5 0 0 0 0 10zM12 2v2m0 16v2M4.9 4.9l1.4 1.4m11.4 11.4l1.4 1.4M2 12h2m16 0h2M4.9 19.1l1.4-1.4m11.4-11.4l1.4-1.4",+ /** Keyboard: a rounded plate, two rows of keys and a space bar. */+ shortcuts:+ "M3 6h18a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1zM6 9.5h.01M9.5 9.5h.01M13 9.5h.01M16.5 9.5h.01M6 12.5h.01M9.5 12.5h.01M13 12.5h.01M16.5 12.5h.01M8.5 15.5h7",/** Single person: the signed-in account. */account: "M20 21a8 8 0 0 0-16 0M12 13a5 5 0 1 0 0-10 5 5 0 0 0 0 10z",/** Globe: outbound traffic. */@@ -94,6 +98,7 @@ export function SettingsDialog({profile: S.settings.profile,general: S.settings.generalTitle,appearance: S.settings.appearanceTitle,+ shortcuts: S.settings.shortcutsTitle,account: S.settings.accountTitle,proxy: S.settings.proxyTitle,uploads: S.settings.uploadLimitsTitle,@@ -108,6 +113,7 @@ export function SettingsDialog({// Page-level explanations, disclosed by the "?" the shell draws beside the pane heading.// Pages whose rows explain themselves one by one carry none.const sectionInfo: Partial<Record<SettingsSectionKey, string>> = {+ shortcuts: S.settings.shortcutsInfo,proxy: S.settings.proxyInfo,uploads: S.settings.uploadLimitsInfo(uploadLimits.attachmentMaxCount, uploadLimits.imageMaxMb),company: S.settings.companyModeServerInfo,@@ -141,6 +147,7 @@ export function SettingsDialog({{current === "profile" && <ProfileSection />}{current === "general" && <GeneralSection />}{current === "appearance" && <AppearanceSection />}+ {current === "shortcuts" && <ShortcutsSection />}{current === "account" && <AccountSection />}{current === "proxy" && <ProxySection />}{current === "uploads" && <UploadsSection />}diff --git a/packages/web/src/features/settings/shortcut-recorder.tsx b/packages/web/src/features/settings/shortcut-recorder.tsxnew file mode 100644index 00000000..2fb0f9d6--- /dev/null+++ b/packages/web/src/features/settings/shortcut-recorder.tsx@@ -0,0 +1,110 @@+/**+ * The control on a Shortcuts settings row: a button showing the current chord (or "not set"),+ * which on activation records the next key combination pressed. While recording it owns the+ * keyboard through a window capture listener that stops propagation — the portal-panel trick —+ * so Escape cancels the recording without also closing the settings dialog. The state machine+ * is lib/shortcuts/recorder.ts; this component only draws it and wires the DOM.+ */+import { useCallback, useEffect, useRef, useState } from "react";+import type { ReactNode } from "react";+import { S } from "../../lib/strings";+import { Kbd } from "../../components/ui/kbd";+import { isModifierCode } from "../../lib/shortcuts/chord";+import { formatChord } from "../../lib/shortcuts/format";+import { currentPlatform } from "../../lib/shortcuts/platform";+import {+ RECORDER_IDLE,+ recorderRelease,+ recorderStart,+ recorderStep,+ type RecorderState,+} from "../../lib/shortcuts/recorder";+import type { Chord } from "../../lib/shortcuts/types";++export function ShortcutRecorder({+ chord,+ onCommit,+}: {+ chord: Chord | null;+ /** A new chord, or null to unbind. */+ onCommit: (chord: Chord | null) => void;+}) {+ const [state, setState] = useState<RecorderState>(RECORDER_IDLE);+ // The listeners below read the live state without re-registering on every keystroke.+ const stateRef = useRef<RecorderState>(state);+ const buttonRef = useRef<HTMLButtonElement | null>(null);+ const recording = state.phase === "recording";++ const update = useCallback((next: RecorderState): void => {+ stateRef.current = next;+ setState(next);+ }, []);++ useEffect(() => {+ if (!recording) return;+ const platform = currentPlatform();+ const onKeyDown = (e: KeyboardEvent): void => {+ e.preventDefault();+ e.stopPropagation();+ const step = recorderStep(stateRef.current, e, platform);+ update(step.state);+ if (step.commit !== undefined) onCommit(step.commit);+ };+ const onKeyUp = (e: KeyboardEvent): void => {+ if (isModifierCode(e.code)) update(recorderRelease(stateRef.current));+ };+ const onPointerDown = (e: PointerEvent): void => {+ if (!buttonRef.current?.contains(e.target as Node)) update(RECORDER_IDLE);+ };+ window.addEventListener("keydown", onKeyDown, true);+ window.addEventListener("keyup", onKeyUp, true);+ window.addEventListener("pointerdown", onPointerDown, true);+ return () => {+ window.removeEventListener("keydown", onKeyDown, true);+ window.removeEventListener("keyup", onKeyUp, true);+ window.removeEventListener("pointerdown", onPointerDown, true);+ };+ }, [recording, onCommit, update]);++ const platform = currentPlatform();+ let content: ReactNode;+ if (state.phase === "recording") {+ content =+ state.preview !== null ? (+ <span className="font-mono">{`${formatChord(state.preview, platform)}…`}</span>+ ) : (+ S.shortcuts.record+ );+ } else if (chord !== null) {+ content = <Kbd chord={chord} size="control" />;+ } else {+ content = <span className="text-gray-400 dark:text-gray-500">{S.shortcuts.unbound}</span>;+ }++ return (+ <div className="flex flex-col items-end gap-0.5">+ <button+ ref={buttonRef}+ type="button"+ title={S.shortcuts.rebind}+ aria-pressed={recording}+ onClick={() => {+ if (!recording) update(recorderStart());+ }}+ onBlur={() => update(RECORDER_IDLE)}+ className={`min-w-28 rounded-md border px-2 py-1 text-xs transition-colors duration-150 ${+ recording+ ? "border-gray-500 text-gray-500 ring-2 ring-gray-400/40 dark:border-gray-400 dark:text-gray-400"+ : "border-gray-300 text-gray-800 hover:bg-gray-50 dark:border-gray-700 dark:text-gray-200 dark:hover:bg-gray-800"+ }`}+ >+ {content}+ </button>+ {state.phase === "recording" && (+ <p className="text-[11px] text-gray-500 dark:text-gray-400">+ {state.notice === "needsModifier" ? S.shortcuts.needsModifier : S.shortcuts.recordHint}+ </p>+ )}+ </div>+ );+}diff --git a/packages/web/src/features/settings/shortcut-runtime.tsx b/packages/web/src/features/settings/shortcut-runtime.tsxnew file mode 100644index 00000000..edb227c1--- /dev/null+++ b/packages/web/src/features/settings/shortcut-runtime.tsx@@ -0,0 +1,39 @@+/**+ * Ties the keymap store to the signed-in account. Mounted once by AppLayout, next to the+ * terminal pool: after sign-in it reads the account's prefs and reconciles the browser mirror+ * against `keybindings` (the server wins; an edit made before the answer is pushed; an absent+ * copy clears a mirror that may belong to another account), and it installs the writer that+ * carries every later edit to `PUT /api/me/prefs`. A failed write is reported and leaves the+ * mirror standing — the next hydrate reconciles.+ */+import { useEffect } from "react";+import * as api from "../../api/endpoints";+import { S } from "../../lib/strings";+import { toastError } from "../../components/ui/toast";+import { hydrateFromServer, setKeybindingsPersister } from "../../lib/shortcuts/store";+import { useAuth } from "../../state/auth";++export function ShortcutRuntime() {+ const { user } = useAuth();+ const userId = user?.userId ?? null;+ useEffect(() => {+ if (userId === null) return;+ setKeybindingsPersister((doc) => {+ void api.putPrefs({ keybindings: doc }).catch(() => toastError(S.shortcuts.saveFailed));+ });+ let cancelled = false;+ void api+ .getPrefs()+ .then((res) => {+ if (!cancelled) hydrateFromServer(res.prefs.keybindings);+ })+ .catch(() => {+ // Unreachable preferences leave the mirror standing; the first keystroke still works.+ });+ return () => {+ cancelled = true;+ setKeybindingsPersister(null);+ };+ }, [userId]);+ return null;+}diff --git a/packages/web/src/features/settings/shortcuts-section.tsx b/packages/web/src/features/settings/shortcuts-section.tsxnew file mode 100644index 00000000..f9ae297f--- /dev/null+++ b/packages/web/src/features/settings/shortcuts-section.tsx@@ -0,0 +1,175 @@+/**+ * Shortcuts page of the System settings dialog: every rebindable command, grouped, each row a+ * recorder showing the current chord. Everything applies on the spot — the store writes the+ * browser mirror and the account's prefs — so there is no Save button; the trailing action row+ * only holds "Reset all". The rows form a dense list: small type, no rule between rows, the group+ * heading the only divider. A row's hint is a fact about its current state, kept on screen: a+ * conflict with another command first, then a claim on the chord from outside the page (a browser+ * tab never receives ⌘W; ⌘P takes over the browser's Print; the desktop menu also carries ⌘R).+ */+import { useState } from "react";+import { S } from "../../lib/strings";+import { Button } from "../../components/ui/button";+import { ConfirmModal } from "../../components/ui/confirm-modal";+import { GlyphIcon } from "../../components/ui/glyph-icon";+import { ICON_SIZE } from "../../lib/icon-scale";+import { conflictsOf, findConflicts, type Conflict } from "../../lib/shortcuts/conflicts";+import { currentHost, currentPlatform } from "../../lib/shortcuts/platform";+import { SHORTCUT_COMMANDS, SHORTCUT_GROUPS, commandById } from "../../lib/shortcuts/registry";+import { browserCommon, browserReserved, desktopReserved } from "../../lib/shortcuts/reserved";+import { isOverridden, resetAll, resetBinding, setBinding } from "../../lib/shortcuts/store";+import type { Chord, CommandId, ShortcutCommand } from "../../lib/shortcuts/types";+import { useKeymap } from "../../lib/shortcuts/use-keymap";+import { toneInk } from "../../lib/tone";+import { SectionShell } from "./section-shell";+import { ShortcutRecorder } from "./shortcut-recorder";++/** Counter-clockwise arrow: back to the default. */+const RESET_ICON = "M3 12a9 9 0 1 0 2.64-6.36M3 4v5h5";++interface RowHint {+ text: string;+ tone?: "attention";+}++/**+ * The one line under a row, in priority order: a conflict (the row may not fire), then a chord a+ * browser keeps for itself (dead in every browser tab), then one the host also uses (the binding+ * takes that function over). A conflict shows only from the side that loses: both rows of a+ * same-scope clash, but only the global row of a shadowed one — the focus-scoped command wins+ * there. Bindings are per account and shared by the browser and the desktop app, so the browser's+ * claims show on either host; in the desktop app its own menu's claim is named first.+ */+function rowHint(+ cmd: ShortcutCommand,+ chord: Chord | null,+ conflicts: readonly Conflict[],+): RowHint | null {+ const mine = conflictsOf(cmd.id, conflicts);+ const other = (c: Conflict): CommandId => (c.a === cmd.id ? c.b : c.a);+ const same = mine.find((c) => c.kind === "same-scope");+ if (same !== undefined) {+ return { text: S.shortcuts.conflictSame(S.shortcuts.commands[other(same)]), tone: "attention" };+ }+ const shadowed = mine.find((c) => c.kind === "shadowed" && cmd.scope === "global");+ if (shadowed !== undefined) {+ const winner = commandById(other(shadowed));+ const surface = winner.scope === "global" ? "" : S.shortcuts.scopes[winner.scope];+ return {+ text: S.shortcuts.conflictShadowed(S.shortcuts.commands[winner.id], surface),+ tone: "attention",+ };+ }+ if (chord === null) return null;+ const platform = currentPlatform();+ if (browserReserved(chord, platform)) {+ return { text: S.shortcuts.browserReserved, tone: "attention" };+ }+ // The shell binds no key before the page today, so only the menu case can arise here.+ if (currentHost() === "desktop" && desktopReserved(chord, platform) === "menu") {+ return { text: S.shortcuts.desktopMenuReserved };+ }+ return browserCommon(chord, platform) ? { text: S.shortcuts.browserCommon } : null;+}++function ShortcutRow({+ cmd,+ chord,+ conflicts,+}: {+ cmd: ShortcutCommand;+ chord: Chord | null;+ conflicts: readonly Conflict[];+}) {+ const hint = rowHint(cmd, chord, conflicts);+ const overridden = isOverridden(cmd.id);+ return (+ <div className="flex items-center justify-between gap-4 py-1.5">+ <div className="min-w-0">+ <p className="text-xs font-medium">{S.shortcuts.commands[cmd.id]}</p>+ {hint !== null && (+ <p+ className={`mt-0.5 text-[11px] ${+ hint.tone === "attention" ? toneInk.attention : "text-gray-500 dark:text-gray-400"+ }`}+ >+ {hint.text}+ </p>+ )}+ </div>+ <div className="flex shrink-0 items-center gap-1.5">+ {overridden && (+ <button+ type="button"+ title={S.shortcuts.resetRow}+ aria-label={`${S.shortcuts.resetRow}: ${S.shortcuts.commands[cmd.id]}`}+ onClick={() => resetBinding(cmd.id)}+ className="flex h-6 w-6 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"+ >+ <GlyphIcon d={RESET_ICON} size={ICON_SIZE.iconButton} />+ </button>+ )}+ <ShortcutRecorder chord={chord} onCommit={(next) => setBinding(cmd.id, next)} />+ </div>+ </div>+ );+}++export function ShortcutsSection() {+ const keymap = useKeymap();+ const conflicts = findConflicts(keymap, SHORTCUT_COMMANDS);+ const overriddenCount = SHORTCUT_COMMANDS.filter((cmd) => isOverridden(cmd.id)).length;+ const [confirmReset, setConfirmReset] = useState(false);+ const groups = SHORTCUT_GROUPS.map((group) => ({+ group,+ commands: SHORTCUT_COMMANDS.filter((cmd) => cmd.group === group),+ })).filter(({ commands }) => commands.length > 0);++ return (+ <SectionShell+ actions={+ <Button+ size="sm"+ disabled={overriddenCount === 0}+ onClick={() => {+ // One override goes back without a question; several are worth a look first.+ if (overriddenCount > 1) setConfirmReset(true);+ else resetAll();+ }}+ >+ {S.shortcuts.resetAll}+ </Button>+ }+ >+ {groups.map(({ group, commands }) => (+ <div key={group}>+ <h3 className="mb-1 text-xs font-medium text-gray-500 dark:text-gray-400">+ {S.shortcuts.groups[group]}+ </h3>+ {commands.map((cmd) => (+ <ShortcutRow+ key={cmd.id}+ cmd={cmd}+ chord={keymap.get(cmd.id) ?? null}+ conflicts={conflicts}+ />+ ))}+ </div>+ ))}+ {confirmReset && (+ <ConfirmModal+ open+ title={S.shortcuts.resetAll}+ onClose={() => setConfirmReset(false)}+ onConfirm={() => {+ resetAll();+ setConfirmReset(false);+ }}+ confirmLabel={S.shortcuts.resetAll}+ >+ {S.shortcuts.resetAllBody(overriddenCount)}+ </ConfirmModal>+ )}+ </SectionShell>+ );+}diff --git a/packages/web/src/lib/settings-sections.ts b/packages/web/src/lib/settings-sections.tsindex 0ac4d9a6..56025a7d 100644--- a/packages/web/src/lib/settings-sections.ts+++ b/packages/web/src/lib/settings-sections.ts@@ -28,6 +28,7 @@ export type SettingsSectionKey =| "profile"| "general"| "appearance"+ | "shortcuts"| "account"| "proxy"| "uploads"@@ -60,6 +61,8 @@ const SECTION_RULES: ReadonlyArray<SettingsSection & { visible(viewer: SettingsV{ key: "profile", group: "personal", visible: () => true },{ key: "general", group: "personal", visible: () => true },{ key: "appearance", group: "personal", visible: () => true },+ // Keyboard shortcuts are the account's, and apply in every session of it.+ { key: "shortcuts", group: "personal", visible: () => true },// The desktop shell's own window has no password to change; a password-established// session against the same server still does. Same predicate as the old menu row.{ key: "account", group: "personal", visible: (v) => offersChangePassword(v) },diff --git a/packages/web/src/lib/shortcuts/chord.ts b/packages/web/src/lib/shortcuts/chord.tsindex 39514ea5..7e3a2b6f 100644--- a/packages/web/src/lib/shortcuts/chord.ts+++ b/packages/web/src/lib/shortcuts/chord.ts@@ -118,13 +118,18 @@ export function chordOf(e: KeyLike, platform: Platform): Chord | 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 {+/**+ * True when the chord can be a binding without stealing typing from an input: it holds Mod or+ * literal Control, or Alt off a Mac (⌥+letter types characters on macOS — ⌥E is the accent key,+ * `@` is ⌥L on a German Mac), or its key is a function key. Shift on its own does not qualify —+ * Shift+B is a capital B, Shift+Enter a newline in the composer — and only counts alongside one+ * of the others.+ */+export function isBindableChord(chord: Chord, platform: Platform): boolean {return (chord.mod ||chord.ctrl ||- chord.alt ||- chord.shift ||+ (chord.alt && platform !== "mac") ||/^F([1-9]|1[0-9]|2[0-4])$/.test(chord.code));}diff --git a/packages/web/src/lib/shortcuts/platform.ts b/packages/web/src/lib/shortcuts/platform.tsindex 1ab4591a..88ea48ae 100644--- a/packages/web/src/lib/shortcuts/platform.ts+++ b/packages/web/src/lib/shortcuts/platform.ts@@ -34,12 +34,13 @@ export function detectPlatform(nav: NavigatorLike | undefined): Platform {return "linux";}-/** The desktop shell is Electron, which names itself in the user agent. Only the reserved-chord notice reads this. */+/** The desktop shell is Electron, which names itself in the user agent. Tooltips and the desktop-menu notice read this. */export function detectHost(nav: NavigatorLike | undefined): HostKind {return /Electron\//.test(nav?.userAgent ?? "") ? "desktop" : "browser";}let platformOverride: Platform | null = null;+let hostOverride: HostKind | null = null;let detectedPlatform: Platform | null = null;let detectedHost: HostKind | null = null;@@ -54,6 +55,7 @@ export function currentPlatform(): Platform {}export function currentHost(): HostKind {+ if (hostOverride !== null) return hostOverride;detectedHost ??= detectHost(currentNavigator());return detectedHost;}@@ -62,3 +64,8 @@ export function currentHost(): HostKind {export function setPlatformForTests(platform: Platform | null): void {platformOverride = platform;}++/** Tests pin the host; null goes back to detection. */+export function setHostForTests(host: HostKind | null): void {+ hostOverride = host;+}diff --git a/packages/web/src/lib/shortcuts/recorder.ts b/packages/web/src/lib/shortcuts/recorder.tsnew file mode 100644index 00000000..01e56fe8--- /dev/null+++ b/packages/web/src/lib/shortcuts/recorder.ts@@ -0,0 +1,71 @@+/**+ * The shortcut recorder's state machine, pure: `idle → recording → idle`. The settings page's+ * recorder button feeds it every keydown while recording and acts on what comes back — a+ * committed chord (bind), a committed null (unbind), or nothing yet.+ */+import { chordOf, codeFromKey, isBindableChord, isModifierCode } from "./chord";+import type { Chord, KeyLike, Platform } from "./types";++export type RecorderNotice = "needsModifier";++export type RecorderState =+ | { phase: "idle" }+ | {+ phase: "recording";+ /** The modifiers held so far, previewed as "⌘…" / "Ctrl+…"; null while none is held. */+ preview: Chord | null;+ notice: RecorderNotice | null;+ };++export interface RecorderStep {+ state: RecorderState;+ /** Absent = nothing committed; null = unbind; a chord = bind. */+ commit?: Chord | null;+}++export const RECORDER_IDLE: RecorderState = { phase: "idle" };++export function recorderStart(): RecorderState {+ return { phase: "recording", preview: null, notice: null };+}++/** The modifiers an event holds, as a code-less chord, with the platform's Mod mapping. */+function modifiersOf(e: KeyLike, platform: Platform): Chord | null {+ const chord: Chord =+ platform === "mac"+ ? { code: "", mod: e.metaKey, ctrl: e.ctrlKey, alt: e.altKey, shift: e.shiftKey }+ : { code: "", mod: e.ctrlKey, ctrl: false, alt: e.altKey, shift: e.shiftKey };+ return chord.mod || chord.ctrl || chord.alt || chord.shift ? chord : null;+}++/**+ * One keydown while recording. Escape alone cancels; Backspace or Delete alone unbinds; a+ * modifier-only press previews; a key without a real modifier (Mod, Ctrl, Alt off a Mac; Shift+ * alone is typing) that is not an F key is refused with a notice, since a global chord on it+ * would steal typing from every input; anything else commits.+ */+export function recorderStep(state: RecorderState, e: KeyLike, platform: Platform): RecorderStep {+ if (state.phase !== "recording") return { state };+ if (e.repeat === true || e.isComposing === true) return { state };+ const code = e.code !== "" ? e.code : codeFromKey(e.key);+ if (code === "") return { state };+ if (isModifierCode(code)) {+ return { state: { phase: "recording", preview: modifiersOf(e, platform), notice: null } };+ }+ const bare = !e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey;+ if (bare && code === "Escape") return { state: RECORDER_IDLE };+ if (bare && (code === "Backspace" || code === "Delete"))+ return { state: RECORDER_IDLE, commit: null };+ const chord = chordOf(e, platform);+ if (chord === null) return { state }; // Meta on Windows/Linux belongs to the OS+ if (!isBindableChord(chord, platform)) {+ return { state: { phase: "recording", preview: null, notice: "needsModifier" } };+ }+ return { state: RECORDER_IDLE, commit: chord };+}++/** A modifier was released without a key: the preview goes back to empty. */+export function recorderRelease(state: RecorderState): RecorderState {+ if (state.phase !== "recording" || state.preview === null) return state;+ return { ...state, preview: null };+}diff --git a/packages/web/src/lib/shortcuts/store.ts b/packages/web/src/lib/shortcuts/store.tsindex 0a5a2268..554c5d0b 100644--- a/packages/web/src/lib/shortcuts/store.ts+++ b/packages/web/src/lib/shortcuts/store.ts@@ -43,6 +43,10 @@ let layout: ReadonlyMap<string, string> | null = null;let cache: { platform: Platform; keymap: Keymap } | null = null;let version = 0;const listeners = new Set<() => void>();+/** Whether this tab edited the bindings since it loaded: what decides an absent server copy's fate on hydrate. */+let writtenThisSession = false;+/** Where a write goes after the mirror: the account's prefs, installed once the session is signed in. */+let persister: ((doc: StoredKeybindings) => void) | null = null;function storage(): KeybindingsStorage | null {if (storageOverride !== null) return storageOverride;@@ -86,17 +90,61 @@ export function readStored(store: KeybindingsStorage | null = storage()): Stored}}-function writeStored(doc: StoredKeybindings): void {+/** The document without empty sections, which is the form both the mirror and the server hold. */+function compactDoc(doc: StoredKeybindings): StoredKeybindings {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;}+ return compact;+}++function storeMirror(compact: StoredKeybindings): void {try {storage()?.setItem(KEYBINDINGS_KEY, JSON.stringify(compact));} catch {/* best-effort persistence (quota limits / private browsing) */}+}++/** A user edit: mirror first, so it applies at once here and in every other tab, then the account. */+function writeStored(doc: StoredKeybindings): void {+ const compact = compactDoc(doc);+ storeMirror(compact);+ writtenThisSession = true;+ persister?.(compact);+ invalidate();+}++/**+ * Installs (or, with null, removes) the writer that carries an edit to the account's prefs. The+ * store stays free of the API client: the runtime that knows the session is signed in installs+ * it, and nothing is sent before then. Either call is an account boundary — sign-out is+ * client-side and reloads nothing — so the "edited this session" mark starts over here: an edit+ * made under the previous account must never be read as pending for the next one.+ */+export function setKeybindingsPersister(fn: ((doc: StoredKeybindings) => void) | null): void {+ persister = fn;+ writtenThisSession = false;+}++/**+ * Reconciles the mirror with the account's copy once it arrives. The server wins: its document+ * replaces the mirror. An absent server copy means one of two things — this account edited the+ * bindings in this tab before the prefs answered, in which case the mirror is that edit and+ * stays (the persister already carried it, so nothing is sent again); or nothing was ever stored+ * for this account, in which case the mirror is cleared, so a browser that signs into another+ * account does not resurrect the previous account's bindings.+ */+export function hydrateFromServer(stored: unknown): void {+ if (stored !== undefined && stored !== null) {+ storeMirror(compactDoc(sanitizeStored(stored)));+ invalidate();+ return;+ }+ if (writtenThisSession) return;+ storage()?.removeItem(KEYBINDINGS_KEY);invalidate();}@@ -214,6 +262,8 @@ export function configureKeybindingsStoreForTests(options: {}): void {if (options.storage !== undefined) storageOverride = options.storage;if (options.layout !== undefined) layout = options.layout;+ writtenThisSession = false;+ persister = null;invalidate();}diff --git a/packages/web/src/lib/shortcuts/types.ts b/packages/web/src/lib/shortcuts/types.tsindex f85e3763..75cb8572 100644--- a/packages/web/src/lib/shortcuts/types.ts+++ b/packages/web/src/lib/shortcuts/types.ts@@ -7,7 +7,7 @@export type Platform = "mac" | "windows" | "linux";-/** Which host runs the page: the reserved-chord notice differs, nothing else does. */+/** Which host runs the page: tooltips drop a browser-reserved chord, and the settings page names the desktop menu's claims. */export type HostKind = "browser" | "desktop";/**@@ -67,16 +67,12 @@ export interface ShortcutCommand {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.+ * The persisted form, shared by the server's `ui_prefs.keybindings` and the browser mirror, is+ * declared once, with the other prefs types the server validates. 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>;-}+export type { StoredKeybindings } from "@prismshadow/penguin-server/api";/** The fields of a `KeyboardEvent` the matcher reads; React's synthetic event and a test literal both fit. */export interface KeyLike {diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 2fa17564..87b6de9e 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -152,6 +152,31 @@ export const en: Strings = {terminal: "Terminal",editor: "Editor",},+ /** Where a focus-scoped command wins, for the shadowed-conflict hint. */+ scopes: {+ terminal: "the terminal",+ editor: "the editor",+ },+ unbound: "Not set",+ /** The recorder button's tooltip. */+ rebind: "Change shortcut",+ record: "Press the new shortcut…",+ recordHint: "Esc cancels · Backspace clears",+ needsModifier:+ "Hold Ctrl or Alt (⌘ or ⌃ on macOS); Shift only together with them. Or use an F key",+ resetRow: "Restore default",+ resetAll: "Reset all",+ resetAllBody: (n: number): string => `Restore ${n} shortcuts to their defaults?`,+ conflictSame: (other: string): string =>+ `Shares its shortcut with "${other}"; only the first in the list fires`,+ conflictShadowed: (other: string, surface: string): string =>+ `In ${surface}, "${other}" takes this shortcut first`,+ browserReserved:+ "The browser keeps this combination for itself; it only works in the desktop app",+ browserCommon:+ "The browser also uses this combination; in a browser tab it takes over that browser function",+ desktopMenuReserved: "Overrides the desktop app's menu shortcut of the same keys",+ saveFailed: "Shortcuts could not be saved to the account",},/** Server-side terminal (the in-app dock and the standalone /terminal page). */@@ -320,6 +345,10 @@ export const en: Strings = {profile: "Profile",generalTitle: "General",appearanceTitle: "Appearance",+ shortcutsTitle: "Keyboard shortcuts",+ /** The Shortcuts page's "?": what follows the platform, where bindings live, and the browser's own claims. */+ shortcutsInfo:+ "Shortcuts follow the platform: ⌘ on macOS, Ctrl elsewhere. A change applies at once in every tab of this browser; the account's other browsers and the desktop app pick it up the next time they load. Bindings are stored per account and per platform, so a Mac and a Windows machine each keep their own. A browser tab cannot receive the chords the browser itself reserves (Ctrl+W / ⌘W, for example), so those work in the desktop app only; a chord the browser also uses (Ctrl+P / ⌘P prints) takes over that browser function in a browser tab. The list marks both.",accountTitle: "Account",/** Trace import: the two pickers' accessible names, the pick-a-file action, and its outcomes. */importTrace: "Import Trace",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex c1ba8a7b..cf0a3cf0 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -174,6 +174,27 @@ export const zh = {terminal: "终端",editor: "编辑器",},+ /** Where a focus-scoped command wins, for the shadowed-conflict hint. */+ scopes: {+ terminal: "终端",+ editor: "编辑器",+ },+ unbound: "未设置",+ /** The recorder button's tooltip. */+ rebind: "更改快捷键",+ record: "按下新的快捷键…",+ recordHint: "Esc 取消 · Backspace 清除",+ needsModifier: "需要配合 Ctrl 或 Alt(macOS 为 ⌘ 或 ⌃),Shift 只能与它们一起使用;或使用 F 键",+ resetRow: "恢复默认",+ resetAll: "全部恢复默认",+ resetAllBody: (n: number): string => `将 ${n} 条快捷键恢复为默认值?`,+ conflictSame: (other: string): string => `与「${other}」使用同一个快捷键,只有排在前面的生效`,+ conflictShadowed: (other: string, surface: string): string =>+ `在${surface}里会被「${other}」抢先`,+ browserReserved: "浏览器保留了这个组合,只在桌面应用里生效",+ browserCommon: "浏览器本身也用这个组合,在浏览器里会取代它的那个功能",+ desktopMenuReserved: "会覆盖桌面应用菜单里使用同一组合的快捷键",+ saveFailed: "快捷键未能保存到账号",},/** Server-side terminal (the in-app dock and the standalone /terminal page). */@@ -382,6 +403,10 @@ export const zh = {profile: "个人资料",generalTitle: "通用",appearanceTitle: "外观",+ shortcutsTitle: "快捷键",+ /** The Shortcuts page's "?": what follows the platform, where bindings live, and the browser's own claims. */+ shortcutsInfo:+ "快捷键随平台:macOS 用 ⌘,其余平台用 Ctrl。改动即刻生效,本浏览器的其他标签页同步跟随;本账号的其他浏览器与桌面应用在下次加载时取得。按账号并按平台分别保存,Mac 与 Windows 各有一套。浏览器自身保留的组合(如 Ctrl+W / ⌘W)在浏览器标签页里收不到,只在桌面应用里生效;浏览器本身也用的组合(如打印的 Ctrl+P / ⌘P)在浏览器标签页里会取代它的那个功能。两者都在列表中标出。",accountTitle: "账户",/** Trace import: the two pickers' accessible names, the pick-a-file action, and its outcomes. */importTrace: "导入 Trace",diff --git a/packages/web/test/control-size.test.ts b/packages/web/test/control-size.test.tsindex 86ade8a6..c3dc1e79 100644--- a/packages/web/test/control-size.test.ts+++ b/packages/web/test/control-size.test.ts@@ -140,6 +140,8 @@ const DIALOG_BODY_MODULES = new Set(["features/settings/proxy-section.tsx","features/settings/section-shell.tsx","features/settings/setting-row.tsx",+ "features/settings/shortcut-recorder.tsx",+ "features/settings/shortcuts-section.tsx","features/settings/trace-import-row.tsx","features/settings/uploads-section.tsx","features/admin/admin-users-page.tsx",diff --git a/packages/web/test/settings-sections.test.ts b/packages/web/test/settings-sections.test.tsindex 664aac52..723939cc 100644--- a/packages/web/test/settings-sections.test.ts+++ b/packages/web/test/settings-sections.test.ts@@ -55,6 +55,7 @@ describe("visibleSettingsSections", () => {"profile","general","appearance",+ "shortcuts","account","proxy","uploads",@@ -69,7 +70,13 @@ describe("visibleSettingsSections", () => {// switch and user management are admin surfaces, and the whole point of dropping them is that a non-admin is never// told they exist. Updating is not among them either way: it lives in the sidebar user// menu, outside this dialog, for every account.- expect(plain.map((s) => s.key)).toEqual(["profile", "general", "appearance", "account"]);+ expect(plain.map((s) => s.key)).toEqual([+ "profile",+ "general",+ "appearance",+ "shortcuts",+ "account",+ ]);});it("strips the desktop shell's window down to what a token session can use", () => {@@ -80,6 +87,7 @@ describe("visibleSettingsSections", () => {"profile","general","appearance",+ "shortcuts","proxy","uploads","company",@@ -94,6 +102,7 @@ describe("visibleSettingsSections", () => {"profile","general","appearance",+ "shortcuts","account","proxy","uploads",diff --git a/packages/web/test/shortcuts-chord.test.ts b/packages/web/test/shortcuts-chord.test.tsindex 000f50b9..4f1fb5fb 100644--- a/packages/web/test/shortcuts-chord.test.ts+++ b/packages/web/test/shortcuts-chord.test.ts@@ -7,7 +7,7 @@ import { describe, expect, it } from "vitest";import {chordOf,codeFromKey,- hasModifierOrFKey,+ isBindableChord,normalizeChord,parseChord,serializeChord,@@ -155,12 +155,23 @@ describe("codeFromKey", () => {});});-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);+describe("isBindableChord", () => {+ it("accepts Mod, literal Ctrl, Alt off a Mac, and a bare function key", () => {+ expect(isBindableChord(parseChord("Mod+KeyW")!, "mac")).toBe(true);+ expect(isBindableChord(parseChord("Ctrl+Backquote")!, "mac")).toBe(true);+ expect(isBindableChord(parseChord("Alt+KeyW")!, "linux")).toBe(true);+ expect(isBindableChord(parseChord("Alt+KeyW")!, "windows")).toBe(true);+ expect(isBindableChord(parseChord("F5")!, "linux")).toBe(true);+ expect(isBindableChord(parseChord("F24")!, "mac")).toBe(true);+ expect(isBindableChord(parseChord("Mod+Shift+KeyO")!, "linux")).toBe(true);+ });++ it("refuses typing: a bare key, Shift alone, and Option alone on a Mac", () => {+ expect(isBindableChord(parseChord("KeyW")!, "linux")).toBe(false);+ expect(isBindableChord(parseChord("F25")!, "linux")).toBe(false);+ expect(isBindableChord(parseChord("Shift+KeyB")!, "linux")).toBe(false);+ expect(isBindableChord(parseChord("Shift+Enter")!, "mac")).toBe(false);+ expect(isBindableChord(parseChord("Alt+KeyE")!, "mac")).toBe(false);+ expect(isBindableChord(parseChord("Alt+Shift+KeyE")!, "mac")).toBe(false);});});diff --git a/packages/web/test/shortcuts-recorder.test.ts b/packages/web/test/shortcuts-recorder.test.tsnew file mode 100644index 00000000..54ca9503--- /dev/null+++ b/packages/web/test/shortcuts-recorder.test.ts@@ -0,0 +1,137 @@+/**+ * The recorder's state machine (src/lib/shortcuts/recorder.ts): a modifier previews, Escape+ * cancels, Backspace clears, a bare letter is refused with a notice, a bare F key and any+ * modifier chord commit.+ */+import { describe, expect, it } from "vitest";+import {+ RECORDER_IDLE,+ recorderRelease,+ recorderStart,+ recorderStep,+} from "../src/lib/shortcuts/recorder";+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("recorderStep", () => {+ it("does nothing while idle", () => {+ expect(recorderStep(RECORDER_IDLE, key({ code: "KeyW", ctrlKey: true }), "linux")).toEqual({+ state: RECORDER_IDLE,+ });+ });++ it("previews the modifiers held so far, with the platform's Mod mapping, and clears on release", () => {+ const held = recorderStep(recorderStart(), key({ code: "MetaLeft", metaKey: true }), "mac");+ expect(held.state).toEqual({+ phase: "recording",+ preview: { code: "", mod: true, ctrl: false, alt: false, shift: false },+ notice: null,+ });+ expect(held.commit).toBeUndefined();+ const both = recorderStep(+ held.state,+ key({ code: "ShiftLeft", metaKey: true, shiftKey: true }),+ "mac",+ );+ expect(both.state).toMatchObject({ preview: { mod: true, shift: true } });+ // On Linux the Control key IS Mod, and the Super key previews nothing.+ expect(+ recorderStep(recorderStart(), key({ code: "ControlLeft", ctrlKey: true }), "linux").state,+ ).toMatchObject({ preview: { mod: true, ctrl: false } });+ expect(+ recorderStep(recorderStart(), key({ code: "MetaLeft", metaKey: true }), "linux").state,+ ).toMatchObject({ preview: null });+ expect(recorderRelease(held.state)).toEqual(recorderStart());+ expect(recorderRelease(RECORDER_IDLE)).toBe(RECORDER_IDLE);+ });++ it("cancels on Escape and commits an unbind on Backspace or Delete", () => {+ expect(recorderStep(recorderStart(), key({ code: "Escape", key: "Escape" }), "linux")).toEqual({+ state: RECORDER_IDLE,+ });+ expect(recorderStep(recorderStart(), key({ code: "Backspace" }), "linux")).toEqual({+ state: RECORDER_IDLE,+ commit: null,+ });+ expect(recorderStep(recorderStart(), key({ code: "Delete" }), "mac")).toEqual({+ state: RECORDER_IDLE,+ commit: null,+ });+ // With a modifier held they are ordinary chords.+ expect(+ recorderStep(recorderStart(), key({ code: "Escape", ctrlKey: true }), "linux").commit,+ ).toEqual({+ code: "Escape",+ mod: true,+ ctrl: false,+ alt: false,+ shift: false,+ });+ });++ it("refuses typing — a bare key, Shift alone, Option alone on a Mac — and stays recording with a notice", () => {+ const refusedState = { phase: "recording", preview: null, notice: "needsModifier" };+ const refused = recorderStep(recorderStart(), key({ code: "KeyW", key: "w" }), "linux");+ expect(refused).toEqual({ state: refusedState });+ expect(recorderStep(recorderStart(), key({ code: "KeyB", shiftKey: true }), "linux")).toEqual({+ state: refusedState,+ });+ expect(recorderStep(recorderStart(), key({ code: "Enter", shiftKey: true }), "mac")).toEqual({+ state: refusedState,+ });+ expect(recorderStep(recorderStart(), key({ code: "KeyE", altKey: true }), "mac")).toEqual({+ state: refusedState,+ });+ // Alt is a real modifier off a Mac (the design's Alt+W rebinding stays possible).+ expect(+ recorderStep(recorderStart(), key({ code: "KeyW", altKey: true }), "linux").commit,+ ).toEqual({ code: "KeyW", mod: false, ctrl: false, alt: true, shift: false });+ // The notice clears once a modifier is held again.+ expect(+ recorderStep(refused.state, key({ code: "ControlLeft", ctrlKey: true }), "linux").state,+ ).toMatchObject({ notice: null });+ });++ it("commits a bare F key and any modifier chord", () => {+ expect(recorderStep(recorderStart(), key({ code: "F5", key: "F5" }), "linux")).toEqual({+ state: RECORDER_IDLE,+ commit: { code: "F5", mod: false, ctrl: false, alt: false, shift: false },+ });+ expect(+ recorderStep(recorderStart(), key({ code: "KeyW", metaKey: true, altKey: true }), "mac")+ .commit,+ ).toEqual({ code: "KeyW", mod: true, ctrl: false, alt: true, shift: false });+ expect(+ recorderStep(recorderStart(), key({ code: "KeyW", ctrlKey: true }), "linux").commit,+ ).toEqual({+ code: "KeyW",+ mod: true,+ ctrl: false,+ alt: false,+ shift: false,+ });+ });++ it("ignores auto-repeat, IME composition, a missing code and the Super key on Linux", () => {+ const recording = recorderStart();+ expect(+ recorderStep(recording, key({ code: "KeyW", ctrlKey: true, repeat: true }), "linux"),+ ).toEqual({+ state: recording,+ });+ expect(+ recorderStep(recording, key({ code: "KeyW", ctrlKey: true, isComposing: true }), "linux"),+ ).toEqual({+ state: recording,+ });+ expect(recorderStep(recording, key({ code: "", key: "Unidentified" }), "linux")).toEqual({+ state: recording,+ });+ expect(recorderStep(recording, key({ code: "KeyW", metaKey: true }), "windows")).toEqual({+ state: recording,+ });+ });+});diff --git a/packages/web/test/shortcuts-registry.test.ts b/packages/web/test/shortcuts-registry.test.tsindex 56f1de6f..eeda8bfd 100644--- a/packages/web/test/shortcuts-registry.test.ts+++ b/packages/web/test/shortcuts-registry.test.ts@@ -6,7 +6,7 @@* every id passes the server's grammar.*/import { describe, expect, it } from "vitest";-import { hasModifierOrFKey, parseChord } from "../src/lib/shortcuts/chord";+import { isBindableChord, parseChord } from "../src/lib/shortcuts/chord";import { findConflicts } from "../src/lib/shortcuts/conflicts";import {SHORTCUT_COMMANDS,@@ -37,11 +37,12 @@ describe("registry defaults", () => {}});- it("no default is a bare key: a modifier or an F key, so nothing steals typing from an input", () => {+ it("every default is bindable: a real 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);+ if (chord !== null)+ expect(isBindableChord(chord, platform), `${cmd.id} on ${platform}`).toBe(true);}}});diff --git a/packages/web/test/shortcuts-section.test.ts b/packages/web/test/shortcuts-section.test.tsnew file mode 100644index 00000000..31ea8473--- /dev/null+++ b/packages/web/test/shortcuts-section.test.ts@@ -0,0 +1,158 @@+/**+ * The Shortcuts settings page (src/features/settings/shortcuts-section.tsx) rendered to static+ * markup against an injected keymap: groups and rows in both dictionaries with no rule between+ * rows, the chord text per platform, the reset affordance only on an overridden row, the+ * browser's notes on either host (a reserved chord in the attention tone, a shared one muted),+ * the desktop menu's note in the desktop app, a note that follows a new binding at once, and a+ * conflict hint in the attention tone.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { ShortcutsSection } from "../src/features/settings/shortcuts-section";+import { S, setActiveStrings, zh } from "../src/lib/strings";+import { en } from "../src/lib/strings-en";+import { parseChord } from "../src/lib/shortcuts/chord";+import { setHostForTests, setPlatformForTests } from "../src/lib/shortcuts/platform";+import { SHORTCUT_COMMANDS } from "../src/lib/shortcuts/registry";+import {+ KEYBINDINGS_KEY,+ configureKeybindingsStoreForTests,+ setBinding,+ type KeybindingsStorage,+} from "../src/lib/shortcuts/store";+import { toneInk } from "../src/lib/tone";++function memStorage(doc?: object): KeybindingsStorage {+ const map = new Map<string, string>();+ if (doc !== undefined) map.set(KEYBINDINGS_KEY, JSON.stringify(doc));+ return {+ getItem: (k) => map.get(k) ?? null,+ setItem: (k, v) => void map.set(k, v),+ removeItem: (k) => void map.delete(k),+ };+}++const render = (): string => renderToStaticMarkup(createElement(ShortcutsSection));+const count = (html: string, needle: string): number => html.split(needle).length - 1;++beforeEach(() => {+ setPlatformForTests("linux");+ setHostForTests("browser");+ configureKeybindingsStoreForTests({ storage: memStorage(), layout: null });+});++afterEach(() => {+ setActiveStrings(zh);+ setPlatformForTests(null);+ setHostForTests(null);+ configureKeybindingsStoreForTests({ storage: null, layout: null });+});++describe("ShortcutsSection", () => {+ it("lists every command under its group, in both dictionaries", () => {+ for (const dict of [zh, en]) {+ setActiveStrings(dict);+ const html = render();+ for (const cmd of SHORTCUT_COMMANDS) expect(html).toContain(dict.shortcuts.commands[cmd.id]);+ for (const group of ["general", "terminal", "editor"] as const) {+ expect(html).toContain(dict.shortcuts.groups[group]);+ }+ // No command sits in the panels group yet, so its heading is not drawn.+ expect(count(html, `>${dict.shortcuts.groups.panels}<`)).toBe(0);+ }+ });++ it("lists the rows without a rule between them", () => {+ expect(render()).not.toContain("divide-y");+ });++ it("draws the chord the platform writes", () => {+ const linux = render();+ expect(linux).toContain("<kbd>Ctrl</kbd>");+ expect(linux).toContain("<kbd>Alt</kbd>");+ expect(linux).toContain("<kbd>P</kbd>");+ setPlatformForTests("mac");+ configureKeybindingsStoreForTests({});+ const mac = render();+ expect(mac).toContain("⌥⌘P");+ expect(mac).toContain("⌃⌥`");+ expect(mac).toContain("⌘S");+ expect(mac).not.toContain("Ctrl");+ });++ it("offers the per-row reset only on an overridden row, and Reset all only when something is", () => {+ const clean = render();+ expect(count(clean, `title="${S.shortcuts.resetRow}"`)).toBe(0);+ expect(clean).toMatch(/<button[^>]* disabled=""[^>]*>[^<]*全部恢复默认/);++ configureKeybindingsStoreForTests({+ storage: memStorage({ v: 1, linux: { "editor.save": null } }),+ });+ const one = render();+ expect(count(one, `title="${S.shortcuts.resetRow}"`)).toBe(1);+ expect(one).toContain(S.shortcuts.unbound);+ expect(one).not.toMatch(/<button[^>]* disabled=""[^>]*>[^<]*全部恢复默认/);+ });++ it("puts no default on a chord the browser keeps, and marks a binding on one in the attention tone on either host", () => {+ expect(render()).not.toContain(S.shortcuts.browserReserved);+ configureKeybindingsStoreForTests({+ storage: memStorage({ v: 1, linux: { "terminal.close": "Mod+KeyW" } }),+ });+ for (const host of ["browser", "desktop"] as const) {+ setHostForTests(host);+ const html = render();+ expect(count(html, S.shortcuts.browserReserved), host).toBe(1);+ expect(html, host).toContain(toneInk.attention);+ }+ });++ it("notes a chord the browser also uses, muted, and names the desktop menu's claim first in the desktop app", () => {+ // Save's default takes over the browser's Save Page; no other default touches the browser.+ expect(count(render(), S.shortcuts.browserCommon)).toBe(1);+ configureKeybindingsStoreForTests({+ storage: memStorage({ v: 1, linux: { "palette.toggle": "Mod+KeyR" } }),+ });+ const browser = render();+ expect(count(browser, S.shortcuts.browserCommon)).toBe(2);+ expect(browser).not.toContain(toneInk.attention);+ setHostForTests("desktop");+ const desktop = render();+ // Reload is the desktop menu's too, so that row names the menu; Save keeps the browser's note.+ expect(count(desktop, S.shortcuts.desktopMenuReserved)).toBe(1);+ expect(count(desktop, S.shortcuts.browserCommon)).toBe(1);+ });++ it("shows a binding's note as soon as the binding lands", () => {+ expect(count(render(), S.shortcuts.browserReserved)).toBe(0);+ setBinding("palette.toggle", parseChord("Mod+KeyT"));+ expect(count(render(), S.shortcuts.browserReserved)).toBe(1);+ });++ it("says which command shadows a global one, in the attention tone", () => {+ configureKeybindingsStoreForTests({+ storage: memStorage({ v: 1, linux: { "palette.toggle": "Ctrl+Alt+Backquote" } }),+ });+ const html = render();+ expect(+ count(+ html,+ S.shortcuts.conflictShadowed(+ S.shortcuts.commands["terminal.close"],+ S.shortcuts.scopes.terminal,+ ),+ ),+ ).toBe(1);+ expect(html).toContain(toneInk.attention);+ });++ it("reports a same-scope clash on both rows", () => {+ configureKeybindingsStoreForTests({+ storage: memStorage({ v: 1, linux: { "palette.toggle": "Ctrl+Backquote" } }),+ });+ const html = render();+ expect(html).toContain(S.shortcuts.conflictSame(S.shortcuts.commands["terminal.toggle"]));+ expect(html).toContain(S.shortcuts.conflictSame(S.shortcuts.commands["palette.toggle"]));+ });+});diff --git a/packages/web/test/shortcuts-store.test.ts b/packages/web/test/shortcuts-store.test.tsindex 1df20374..4fd05e37 100644--- a/packages/web/test/shortcuts-store.test.ts+++ b/packages/web/test/shortcuts-store.test.ts@@ -10,6 +10,7 @@ import {KEYBINDINGS_KEY,bindingOf,configureKeybindingsStoreForTests,+ hydrateFromServer,isOverridden,keymap,keymapVersion,@@ -19,9 +20,11 @@ import {resetBinding,sanitizeStored,setBinding,+ setKeybindingsPersister,subscribeKeymap,type KeybindingsStorage,} from "../src/lib/shortcuts/store";+import type { StoredKeybindings } from "../src/lib/shortcuts/types";function memStorage(initial: Record<string, string> = {},@@ -218,3 +221,61 @@ describe("external changes and the keyboard layout", () => {expect(stored()).toEqual({ v: 1, linux: { "palette.toggle": "Mod+Alt+KeyP" } });});});++describe("the account's copy", () => {+ it("carries every edit to the persister as the compact document, and nothing before one is installed", () => {+ const sent: StoredKeybindings[] = [];+ setBinding("editor.save", null);+ setKeybindingsPersister((doc) => sent.push(doc));+ setBinding("terminal.close", parseChord("Mod+Alt+KeyW"));+ resetBinding("editor.save");+ expect(sent).toEqual([+ { v: 1, linux: { "editor.save": null, "terminal.close": "Mod+Alt+KeyW" } },+ { v: 1, linux: { "terminal.close": "Mod+Alt+KeyW" } },+ ]);+ setKeybindingsPersister(null);+ resetAll();+ expect(sent).toHaveLength(2);+ });++ it("applies the server document over the mirror, even over an edit made this session", () => {+ setBinding("editor.save", null);+ hydrateFromServer({ v: 1, linux: { "terminal.close": "Mod+Alt+KeyW" }, mac: {} });+ expect(bindingOf("editor.save")).toEqual(parseChord("Mod+KeyS"));+ expect(bindingOf("terminal.close")).toEqual(parseChord("Mod+Alt+KeyW"));+ expect(stored()).toEqual({ v: 1, linux: { "terminal.close": "Mod+Alt+KeyW" } });+ });++ it("keeps the mirror when the server has no copy but this account edited it here, sending nothing again", () => {+ const sent: StoredKeybindings[] = [];+ setKeybindingsPersister((doc) => sent.push(doc));+ setBinding("editor.save", null);+ hydrateFromServer(undefined);+ expect(sent).toEqual([{ v: 1, linux: { "editor.save": null } }]);+ expect(bindingOf("editor.save")).toBeNull();+ expect(stored()).toEqual({ v: 1, linux: { "editor.save": null } });+ });++ it("does not carry one account's edit into the next account signed in on the same tab", () => {+ const first: StoredKeybindings[] = [];+ setKeybindingsPersister((doc) => first.push(doc));+ setBinding("editor.save", null); // account A edits, then signs out (no reload)+ setKeybindingsPersister(null);+ const second: StoredKeybindings[] = [];+ setKeybindingsPersister((doc) => second.push(doc)); // account B signs in+ hydrateFromServer(undefined); // B has no keybindings+ expect(first).toHaveLength(1);+ expect(second).toEqual([]);+ expect(storage.map.has(KEYBINDINGS_KEY)).toBe(false);+ expect(bindingOf("editor.save")).toEqual(parseChord("Mod+KeyS"));+ });++ it("clears a mirror the server knows nothing about when this session did not write it", () => {+ storage.map.set(KEYBINDINGS_KEY, JSON.stringify({ v: 1, linux: { "editor.save": null } }));+ configureKeybindingsStoreForTests({});+ expect(bindingOf("editor.save")).toBeNull();+ hydrateFromServer(undefined);+ expect(storage.map.has(KEYBINDINGS_KEY)).toBe(false);+ expect(bindingOf("editor.save")).toEqual(parseChord("Mod+KeyS"));+ });+});