Skip to content

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

fix(web): a refused shortcut read keeps its reason on the shortcuts page

lmlihengadf9486d2149
diff --git a/changelog/unreleased/2026-11-12-shortcut-load-refusal.md b/changelog/unreleased/2026-11-12-shortcut-load-refusal.md
new file mode 100644
index 00000000..dd28c84f
--- /dev/null
+++ b/changelog/unreleased/2026-11-12-shortcut-load-refusal.md
@@ -0,0 +1,53 @@
+# A refused shortcut read keeps its reason on the page
+
+- **Date:** 2026-11-12
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[中文版](2026-11-12-shortcut-load-refusal.zh.md)
+
+The keymap has to exist before any request answers — the shortcut dispatcher installs at module
+evaluation — so the rows read the browser mirror until `GET /api/me/prefs` arrives, and the account's
+copy replaces it then. A refused read left the mirror standing with nothing said about it: rows that
+were the previous account's document, or just the defaults, looking exactly like the account's
+shortcuts. Worse, one edit is one PUT of the whole document (the server replaces `keybindings` rather
+than merging), so a rebind under a refused read could take away overrides the account still held.
+
+The Shortcuts page now says so at its top, above the rows it explains: `没能从账号读取快捷键;下面这一份
+来自这个浏览器(可能属于上一个账号,也可能只是默认值),改动会整份写回账号、盖掉账号上原来的按键。重新加载
+这一页会再读一次:<reason>`. It goes away as soon as the question is settled — a hydrate, or a write
+that lands (the account then holds what is on screen) — and is never toasted.
+
+## Details
+
+- `packages/web/src/lib/shortcuts/store.ts`: `noteHydrateFailure(error)` records the raw value (a
+ sentence is built at render time, so a language switch re-words it) and
+ `shortcutLoadFailure()` / `subscribeShortcutLoadFailure()` / `shortcutLoadFailureVersion()` read it.
+ Cleared by `hydrateFromServer` (the account answered, even with "nothing stored"), by a write that
+ lands, at an account boundary, and by the test configuration reset.
+- `packages/web/src/lib/shortcuts/use-keymap.ts`: `useShortcutLoadFailure()`.
+- `packages/web/src/features/settings/shortcut-runtime.tsx`: the prefs read's rejection is handed to
+ the store instead of being swallowed by an empty `catch`.
+- `packages/web/src/features/settings/shortcuts-section.tsx`: draws it first, above the refused-write
+ line (`role="alert"`, `data-testid="shortcut-load-failure"`, attention tone — nothing failed, but
+ the page cannot vouch for what it shows), two lines, the whole sentence on hover.
+- `packages/web/src/lib/strings{,-en}.ts`: `loadRefused(reason)`, reason last, the app-wide shape.
+
+## Tests
+
+- `packages/web/test/shortcut-load-failure.test.ts`: the refused read is remembered once with its raw
+ value, the mirror keeps the keyboard working, it is not confused with a refused write (and survives
+ one), a hydrate with or without a stored copy drops it, a landed write drops it, a refused or
+ in-flight write does not, another account does not inherit it, and both dictionaries carry where the
+ rows came from, what an edit does to the account, the reload, and the reason.
+- `packages/web/e2e/shortcut-load-refusal.spec.mjs`: a real server and a real browser — with the read
+ stubbed to a 500 the page shows the sentence with the reason the interface translates (never the
+ wire's English), one row reads the mirror's `未设置`, nothing is in the notification region, the
+ account's copy is untouched, it is still there after seven seconds; after a reload with the read
+ restored the sentence and the mirror's row are both gone.
+
+## Compatibility
+
+No wire change, no new dependency, no Project config change. A successful read and every other prefs
+consumer behave as before.
diff --git a/changelog/unreleased/2026-11-12-shortcut-load-refusal.zh.md b/changelog/unreleased/2026-11-12-shortcut-load-refusal.zh.md
new file mode 100644
index 00000000..2a3b92cd
--- /dev/null
+++ b/changelog/unreleased/2026-11-12-shortcut-load-refusal.zh.md
@@ -0,0 +1,46 @@
+# 快捷键没能从账号读取时,原因留在设置页上
+
+- **日期:** 2026-11-12
+- **类型:** 修复
+- **范围:** `web`
+- **破坏性变更:** 否
+
+[English](2026-11-12-shortcut-load-refusal.md)
+
+快捷键的分发器在模块求值时就装上了 —— 任何请求回答之前就得有一份键位表 —— 所以在 `GET /api/me/prefs`
+回来之前,各行读的是浏览器镜像,回来之后才换成账号上的那一份。此前这次读被拒时,镜像就那么留着、页面上一个字都不说:
+那些行可能是上一个账号留下的文档,也可能只是默认值,看上去却与账号上的快捷键一模一样。更糟的是,一次改动就是一次
+整份文档的 PUT(服务端对 `keybindings` 是整份替换、不是合并),所以读失败时改一条,可能把账号上还留着的那些覆盖
+一起抹掉。
+
+现在快捷键页的顶部会说明这件事,画在它所解释的那些行之上:`没能从账号读取快捷键;下面这一份来自这个浏览器(可能
+属于上一个账号,也可能只是默认值),改动会整份写回账号、盖掉账号上原来的按键。重新加载这一页会再读一次:<原因>`。
+问题一旦落定它就消失 —— 一次 hydrate(账号那份读到了),或一次真正落地的写入(账号此后就持有屏幕上的这一份);
+它从不另弹通知。
+
+## 细节
+
+- `packages/web/src/lib/shortcuts/store.ts`:`noteHydrateFailure(error)` 记下原始值(句子在渲染时造,切换语言
+ 会重新措辞),`shortcutLoadFailure()` / `subscribeShortcutLoadFailure()` /
+ `shortcutLoadFailureVersion()` 供页面读。清掉它的是 `hydrateFromServer`(账号答了,哪怕是「什么都没存」)、
+ 一次落地的写入、账号边界,以及测试用的重置。
+- `packages/web/src/lib/shortcuts/use-keymap.ts`:`useShortcutLoadFailure()`。
+- `packages/web/src/features/settings/shortcut-runtime.tsx`:读 prefs 的拒绝交给 store,不再被一个空的 `catch`
+ 吞掉。
+- `packages/web/src/features/settings/shortcuts-section.tsx`:画在最前,在被拒的写入那一句之上(`role="alert"`、
+ `data-testid="shortcut-load-failure"`、attention 色 —— 没有东西坏掉,只是这一页没法为它显示的内容作保)、
+ 限两行、整句挂悬停。
+- `packages/web/src/lib/strings{,-en}.ts`:`loadRefused(reason)`,原因收在句末,与全应用一致。
+
+## 测试
+
+- `packages/web/test/shortcut-load-failure.test.ts`:被拒的读只记一次原始值、镜像让键盘照常工作、不会与被拒的
+ 写入混淆(并且能挺过一次被拒的写入)、有或没有已存副本的 hydrate 都会清掉它、落地的写入会清掉它、被拒或仍在飞
+ 的写入不会、换一个账号不会继承它,两份词典都带上「这些行从哪来」「改动会对账号做什么」「重新加载」与原因。
+- `packages/web/e2e/shortcut-load-refusal.spec.mjs`:真服务端 + 真浏览器 —— 读被桩成 500 时页面显示那句话、用
+ 的是界面自己的译文(绝不是线上英文原文)、有一行读的是镜像里的「未设置」、通知区没有东西、账号那份原样未动、
+ 七秒后仍在;读恢复后重新加载,句子与镜像那一行都不见了。
+
+## 兼容性
+
+线上接口没变、没有新依赖、Project 配置没变。成功的读取与其余读 prefs 的地方行为照旧。
diff --git a/packages/web/e2e/shortcut-load-refusal.spec.mjs b/packages/web/e2e/shortcut-load-refusal.spec.mjs
new file mode 100644
index 00000000..259a3e80
--- /dev/null
+++ b/packages/web/e2e/shortcut-load-refusal.spec.mjs
@@ -0,0 +1,125 @@
+/**
+ * Regression: a shortcut read the account refused keeps the reason on the page, instead of leaving
+ * the rows looking like the account's own shortcuts.
+ *
+ * The keymap has to exist before any request answers (the dispatcher installs at module evaluation),
+ * so the browser mirror is what the rows read until `GET /api/me/prefs` arrives. When that read is
+ * refused the mirror simply stands — here the previous session's document, so one row reads
+ * "未设置" — and an edit would write that document back whole, because one PUT replaces
+ * `keybindings` rather than merging. Before this the page said nothing: no notification, no line,
+ * just rows that were not the account's.
+ *
+ * The read is stubbed with a 500 carrying a code the interface translates plus an English wire
+ * message, which is how the test tells the localized sentence from the raw one.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const U = "shortcutread";
+const P = "password123";
+
+/** The refusal: a code the interface has its own words for, plus a message that must not reach the page. */
+const REFUSAL = { code: "internal", message: "RAW ENGLISH SERVER MESSAGE" };
+/** The line the page draws for that code (S.errors.byCode), after what failed. */
+const REASON = "服务器内部错误,请稍后重试。";
+/** What the sentence says about the rows it stands above (reason last, app-wide shape). */
+const HEAD = "没能从账号读取快捷键";
+
+const notifications = (page) => page.getByRole("region", { name: "通知" });
+
+/** Fail every read of the prefs route until the returned `off()` restores it. */
+async function refusePrefsReads(page) {
+ await page.route("**/api/me/prefs", async (route) => {
+ if (route.request().method() !== "GET") return route.continue();
+ return route.fulfill({
+ status: 500,
+ contentType: "application/json",
+ body: JSON.stringify({ error: REFUSAL }),
+ });
+ });
+ return async () => {
+ await page.unroute("**/api/me/prefs");
+ };
+}
+
+/** Provision a user and give the Project a model (without one the onboarding overlay covers the page). */
+async function signedInWithModel(page) {
+ await provisionAndLogin(page.request, U, P);
+ const projectId = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0]
+ .projectId;
+ const models = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ },
+ ],
+ },
+ });
+ expect(models.ok(), "put models").toBeTruthy();
+ // The account holds no overrides, and this user may survive from an earlier run: both the stored
+ // copy and the rows are then predictable.
+ const cleared = await page.request.put(`${BASE}/api/me/prefs`, {
+ data: { keybindings: { v: 1 } },
+ });
+ expect(cleared.ok(), "clear keybindings").toBeTruthy();
+}
+
+/** The settings dialog, on its Shortcuts page. */
+async function openShortcutsPage(page) {
+ await page.getByRole("button", { name: U }).last().click();
+ await page.getByRole("menuitem", { name: "设置", exact: true }).click();
+ const settings = page.getByRole("dialog", { name: "设置" });
+ await expect(settings).toBeVisible();
+ await settings.getByRole("button", { name: "快捷键", exact: true }).click();
+ return settings;
+}
+
+test("a refused shortcut read says the rows came from this browser, and a reload retries", async ({
+ page,
+}) => {
+ await signedInWithModel(page);
+
+ // What the previous session left in this browser: one unbound command the account never held.
+ const mirror = { v: 1, linux: { "editor.save": null } };
+ await page.addInitScript(
+ (doc) => localStorage.setItem("penguin.keybindings", JSON.stringify(doc)),
+ mirror,
+ );
+ const turnOff = await refusePrefsReads(page);
+
+ await page.goto(`${BASE}/chat/new`);
+ const settings = await openShortcutsPage(page);
+
+ const refusal = settings.getByTestId("shortcut-load-failure");
+ await expect(refusal).toBeVisible();
+ await expect(refusal).toContainText(HEAD);
+ await expect(refusal).toContainText(REASON);
+ await expect(refusal).toContainText("盖掉账号上原来的按键");
+ // The wire's English message never reaches the page: the sentence is the interface's own.
+ await expect(refusal).not.toContainText("RAW ENGLISH SERVER MESSAGE");
+ // The rows below it are the mirror, not the account's copy: that is what the sentence is about.
+ await expect(settings.getByText("未设置", { exact: true })).toHaveCount(1);
+ // Nothing is toasted for it, and the account's copy is untouched.
+ await expect(notifications(page).getByText(REASON)).toHaveCount(0);
+ const prefs = await (await page.request.get(`${BASE}/api/me/prefs`)).json();
+ expect(prefs.prefs.keybindings).toEqual({ v: 1 });
+
+ // It is not a six-second notification: it is still there after one.
+ await page.waitForTimeout(7000);
+ await expect(refusal).toBeVisible();
+
+ // A reload is the retry — the read now answers, so the account's copy replaces the mirror.
+ await turnOff();
+ await page.reload();
+ const again = await openShortcutsPage(page);
+ await expect(again.getByTestId("shortcut-load-failure")).toHaveCount(0);
+ await expect(again.getByText("未设置", { exact: true })).toHaveCount(0);
+});
diff --git a/packages/web/src/features/settings/shortcut-runtime.tsx b/packages/web/src/features/settings/shortcut-runtime.tsx
index d0d6ec2a..2340ca14 100644
--- a/packages/web/src/features/settings/shortcut-runtime.tsx
+++ b/packages/web/src/features/settings/shortcut-runtime.tsx
@@ -5,11 +5,17 @@
* 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`. The request itself is handed over — the store
* remembers a refused write and the shortcuts page draws it (7.114), because the mirror was
- * already written and still stands: the next hydrate reconciles.
+ * already written and still stands: the next hydrate reconciles. A read that never answers is
+ * remembered the same way (7.115): the mirror then stands in for the account's copy, and every
+ * edit writes it back whole.
*/
import { useEffect } from "react";
import * as api from "../../api/endpoints";
-import { hydrateFromServer, setKeybindingsPersister } from "../../lib/shortcuts/store";
+import {
+ hydrateFromServer,
+ noteHydrateFailure,
+ setKeybindingsPersister,
+} from "../../lib/shortcuts/store";
import { useAuth } from "../../state/auth";
export function ShortcutRuntime() {
@@ -24,8 +30,10 @@ export function ShortcutRuntime() {
.then((res) => {
if (!cancelled) hydrateFromServer(res.prefs.keybindings);
})
- .catch(() => {
- // Unreachable preferences leave the mirror standing; the first keystroke still works.
+ .catch((error: unknown) => {
+ // The mirror keeps the keyboard working, but nothing has read the account's copy: say so on
+ // the page that holds the edits rather than leave the rows looking like the account's.
+ if (!cancelled) noteHydrateFailure(error);
});
return () => {
cancelled = true;
diff --git a/packages/web/src/features/settings/shortcuts-section.tsx b/packages/web/src/features/settings/shortcuts-section.tsx
index f88a2e3c..389363e3 100644
--- a/packages/web/src/features/settings/shortcuts-section.tsx
+++ b/packages/web/src/features/settings/shortcuts-section.tsx
@@ -13,6 +13,11 @@
* cannot show it anyway: the browser mirror was written first, so the row keeps showing the chord
* the edit just made. The sentence is up there so that it is read before the rows it contradicts,
* and the next edit — any edit — replaces it.
+ *
+ * A read that was refused says so there too, and first (7.115): the rows then come from the browser
+ * mirror, which is the previous account's document or the defaults, and an edit writes that document
+ * back whole. Neither line is a notification — both are facts about this page that survive as long
+ * as they hold.
*/
import { useState } from "react";
import { Button, ConfirmModal, GlyphIcon, ICON_SIZE, SettingsSection } from "@adelie/ui";
@@ -24,7 +29,11 @@ import { SHORTCUT_COMMANDS, SHORTCUT_GROUPS, commandById } from "../../lib/short
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, useShortcutSaveFailure } from "../../lib/shortcuts/use-keymap";
+import {
+ useKeymap,
+ useShortcutLoadFailure,
+ useShortcutSaveFailure,
+} from "../../lib/shortcuts/use-keymap";
import { toneInk } from "../../lib/tone";
import { ShortcutRecorder } from "./shortcut-recorder";
@@ -122,6 +131,7 @@ function ShortcutRow({
export function ShortcutsSection() {
const keymap = useKeymap();
const saveFailure = useShortcutSaveFailure();
+ const loadFailure = useShortcutLoadFailure();
const conflicts = findConflicts(keymap, SHORTCUT_COMMANDS);
const overriddenCount = SHORTCUT_COMMANDS.filter((cmd) => isOverridden(cmd.id)).length;
const [confirmReset, setConfirmReset] = useState(false);
@@ -146,6 +156,17 @@ export function ShortcutsSection() {
</Button>
}
>
+ {loadFailure !== null && (
+ <p
+ role="alert"
+ data-testid="shortcut-load-failure"
+ data-tooltip={S.shortcuts.loadRefused(refusalText(loadFailure))}
+ data-tooltip-content="text"
+ className={`line-clamp-2 break-words text-xs ${toneInk.attention}`}
+ >
+ {S.shortcuts.loadRefused(refusalText(loadFailure))}
+ </p>
+ )}
{saveFailure !== null && (
<p
role="alert"
diff --git a/packages/web/src/lib/shortcuts/store.ts b/packages/web/src/lib/shortcuts/store.ts
index d57f05e0..43f4cc90 100644
--- a/packages/web/src/lib/shortcuts/store.ts
+++ b/packages/web/src/lib/shortcuts/store.ts
@@ -77,6 +77,38 @@ function noteSaveFailure(error: unknown): void {
publishSaveFailure(error);
}
+/**
+ * Why the account's copy was never read (`null` while it was).
+ *
+ * The dispatcher installs at module evaluation — before auth, before any prefs request answers — so
+ * the keymap comes from the browser mirror until `GET /api/me/prefs` arrives. When that read is
+ * refused the mirror simply stands, and it is the previous account's document or nothing at all;
+ * worse, an edit then writes that document back **whole**, because one PUT replaces `keybindings`
+ * instead of merging, so it can take away overrides the account held. No row can say any of this:
+ * they read the mirror and look exactly like the account's copy. So the store keeps the raw failure
+ * (not a sentence, so a language switch re-words it) for the page that holds the edits (7.115), and
+ * drops it the moment the question is settled — a hydrate, or a write that lands (the account then
+ * holds what is on screen).
+ */
+let loadFailure: unknown = null;
+let loadFailureVersion = 0;
+const loadFailureListeners = new Set<() => void>();
+
+function publishLoadFailure(next: unknown): void {
+ loadFailure = next;
+ loadFailureVersion++;
+ for (const listener of [...loadFailureListeners]) listener();
+}
+
+function clearLoadFailure(): void {
+ if (loadFailure !== null) publishLoadFailure(null);
+}
+
+/** The prefs read the runtime asked for was refused: what the page shows is the mirror, not the account's copy. */
+export function noteHydrateFailure(error: unknown): void {
+ publishLoadFailure(error);
+}
+
function storage(): KeybindingsStorage | null {
if (storageOverride !== null) return storageOverride;
try {
@@ -140,13 +172,14 @@ function storeMirror(compact: StoredKeybindings): void {
/**
* Hands the compact document to the account. A writer that answers with a promise is watched: a
* rejection (or a synchronous throw) is remembered rather than swallowed, because nothing awaits
- * an edit — the mirror already carries it.
+ * an edit — the mirror already carries it. A write that lands also settles the earlier question of
+ * what the account held: from then on it holds this document.
*/
function sendToAccount(compact: StoredKeybindings): void {
if (persister === null) return;
try {
const sent = persister(compact);
- if (sent instanceof Promise) void sent.catch(noteSaveFailure);
+ if (sent instanceof Promise) void sent.then(clearLoadFailure, noteSaveFailure);
} catch (error) {
noteSaveFailure(error);
}
@@ -174,6 +207,8 @@ export function setKeybindingsPersister(fn: ((doc: StoredKeybindings) => unknown
writtenThisSession = false;
// Another account's failed write is not this one's news.
clearSaveFailure();
+ // Nor is what the previous account's read said: this one's read is about to be asked for.
+ clearLoadFailure();
}
/**
@@ -187,6 +222,8 @@ export function setKeybindingsPersister(fn: ((doc: StoredKeybindings) => unknown
export function hydrateFromServer(stored: unknown): void {
// The screen is the account's copy again, so a sentence about a write it never got is stale.
clearSaveFailure();
+ // And the account's copy has now been read, so nothing is left to warn about.
+ clearLoadFailure();
if (stored !== undefined && stored !== null) {
storeMirror(compactDoc(sanitizeStored(stored)));
invalidate();
@@ -305,6 +342,20 @@ export function shortcutSaveFailureVersion(): number {
return saveFailureVersion;
}
+/** Why the account's copy was never read, as it arrived — `null` once a read or a write settles it. */
+export function shortcutLoadFailure(): unknown {
+ return loadFailure;
+}
+
+export function subscribeShortcutLoadFailure(listener: () => void): () => void {
+ loadFailureListeners.add(listener);
+ return () => loadFailureListeners.delete(listener);
+}
+
+export function shortcutLoadFailureVersion(): number {
+ return loadFailureVersion;
+}
+
/**
* 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.
@@ -328,6 +379,7 @@ export function configureKeybindingsStoreForTests(options: {
writtenThisSession = false;
persister = null;
clearSaveFailure();
+ clearLoadFailure();
invalidate();
}
diff --git a/packages/web/src/lib/shortcuts/use-keymap.ts b/packages/web/src/lib/shortcuts/use-keymap.ts
index d5ea195f..0ebc2264 100644
--- a/packages/web/src/lib/shortcuts/use-keymap.ts
+++ b/packages/web/src/lib/shortcuts/use-keymap.ts
@@ -14,9 +14,12 @@ import {
keyboardLayout,
keymap,
keymapVersion,
+ shortcutLoadFailure,
+ shortcutLoadFailureVersion,
shortcutSaveFailure,
shortcutSaveFailureVersion,
subscribeKeymap,
+ subscribeShortcutLoadFailure,
subscribeShortcutSaveFailure,
} from "./store";
import type { Chord, CommandId, Keymap } from "./types";
@@ -40,6 +43,20 @@ export function useShortcutSaveFailure(): unknown {
return shortcutSaveFailure();
}
+/**
+ * Why the account's copy was never read (null once it was). What the page shows is then the browser
+ * mirror — possibly a previous account's document — and an edit writes that document back whole, so
+ * the page that holds the edits is where the sentence belongs.
+ */
+export function useShortcutLoadFailure(): unknown {
+ useSyncExternalStore(
+ subscribeShortcutLoadFailure,
+ shortcutLoadFailureVersion,
+ shortcutLoadFailureVersion,
+ );
+ return shortcutLoadFailure();
+}
+
/** The command's chord as bound, whether or not this host can deliver it. */
export function useBinding(id: CommandId): Chord | null {
useKeymap();
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 0fff1b02..657d97fe 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -187,6 +187,12 @@ export const en: Strings = {
desktopMenuReserved: "Overrides the desktop app's menu shortcut of the same keys",
saveRefused: (reason: string): string =>
`Shortcuts could not be saved to the account; the change applies in this browser only and reverts to the account's shortcuts on the next load: ${reason}`,
+ /**
+ * A read the account refused: the rows below are the browser mirror, not the account's copy, and a
+ * write would replace the account's whole document with it — so the sentence names both costs.
+ */
+ loadRefused: (reason: string): string =>
+ `The account's shortcuts could not be read; these come from this browser instead (a previous account's, or just the defaults), and an edit is written back as the whole document, replacing the account's own bindings. Reloading this page reads them again: ${reason}`,
},
/** Server-side terminal (the in-app dock and the standalone /terminal page). */
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index ae68c620..52392898 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -207,6 +207,12 @@ export const zh = {
/** A write the account refused: the row still shows the new chord, so the sentence says what the account holds. */
saveRefused: (reason: string): string =>
`快捷键没能保存到账号;这一改动只在这个浏览器里生效,重新加载后会退回账号上原来的快捷键:${reason}`,
+ /**
+ * A read the account refused: the rows below are the browser mirror, not the account's copy, and a
+ * write would replace the account's whole document with it — so the sentence names both costs.
+ */
+ loadRefused: (reason: string): string =>
+ `没能从账号读取快捷键;下面这一份来自这个浏览器(可能属于上一个账号,也可能只是默认值),改动会整份写回账号、盖掉账号上原来的按键。重新加载这一页会再读一次:${reason}`,
},
/** Server-side terminal (the in-app dock and the standalone /terminal page). */
diff --git a/packages/web/test/shortcut-load-failure.test.ts b/packages/web/test/shortcut-load-failure.test.ts
new file mode 100644
index 00000000..aa391518
--- /dev/null
+++ b/packages/web/test/shortcut-load-failure.test.ts
@@ -0,0 +1,174 @@
+/**
+ * A refused read of the account's copy is remembered, so the shortcuts page can say that what it
+ * shows is the browser mirror rather than the account's shortcuts (7.115).
+ *
+ * The keymap must exist before any request answers — the dispatcher installs at module evaluation —
+ * so the mirror is what the first keystroke reads, and the account's copy replaces it only when
+ * `GET /api/me/prefs` answers. A refused read leaves the mirror standing, which is the previous
+ * account's document or the defaults, and an edit then writes it back whole (one PUT replaces
+ * `keybindings` rather than merging), so the page has to say both things. What the store owes it is
+ * the raw value plus when to stop saying it: a hydrate settles the question, a write that lands makes
+ * the account hold what is on screen, and an account boundary starts a new question.
+ *
+ * The sentence is built at render time from `refusalText`, so the last test holds both dictionaries
+ * to what it has to promise: where the rows came from, what an edit does to the account, that a
+ * reload retries, and the reason last.
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { ApiError } from "../src/api/client";
+import { refusalText } from "../src/lib/api-error";
+import { parseChord } from "../src/lib/shortcuts/chord";
+import { setPlatformForTests } from "../src/lib/shortcuts/platform";
+import {
+ KEYBINDINGS_KEY,
+ bindingOf,
+ configureKeybindingsStoreForTests,
+ hydrateFromServer,
+ noteHydrateFailure,
+ setBinding,
+ setKeybindingsPersister,
+ shortcutLoadFailure,
+ shortcutLoadFailureVersion,
+ shortcutSaveFailure,
+ subscribeShortcutLoadFailure,
+} from "../src/lib/shortcuts/store";
+import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";
+import { en as EN } from "../src/lib/strings-en";
+import { memoryStorage } from "./helpers/storage";
+
+let storage = memoryStorage();
+
+beforeEach(() => {
+ storage = memoryStorage();
+ setPlatformForTests("linux");
+ configureKeybindingsStoreForTests({ storage, layout: null });
+ setActiveStrings(ZH);
+});
+
+afterEach(() => {
+ setPlatformForTests(null);
+ configureKeybindingsStoreForTests({ storage: null, layout: null });
+ setActiveStrings(ZH);
+});
+
+/** A 500 the interface has its own words for — so the sentence that shows is not the wire's. */
+const SERVER_SAID = new ApiError(500, "internal", "RAW ENGLISH SERVER MESSAGE");
+
+/** Let the answer the store only watched settle. */
+const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));
+
+describe("a refused read of the account's copy", () => {
+ it("is remembered, and subscribers hear about it once", () => {
+ const seen: unknown[] = [];
+ const unsubscribe = subscribeShortcutLoadFailure(() => seen.push(shortcutLoadFailure()));
+ const version = shortcutLoadFailureVersion();
+
+ noteHydrateFailure(SERVER_SAID);
+
+ expect(shortcutLoadFailure()).toBe(SERVER_SAID);
+ expect(seen).toEqual([SERVER_SAID]);
+ expect(shortcutLoadFailureVersion()).toBeGreaterThan(version);
+ unsubscribe();
+ });
+
+ it("leaves the mirror standing, so the keyboard keeps working", () => {
+ storage.map.set(KEYBINDINGS_KEY, JSON.stringify({ v: 1, linux: { "editor.save": null } }));
+
+ noteHydrateFailure(SERVER_SAID);
+
+ expect(bindingOf("editor.save")).toBeNull();
+ expect(storage.map.get(KEYBINDINGS_KEY)).toBe(
+ JSON.stringify({ v: 1, linux: { "editor.save": null } }),
+ );
+ });
+
+ it("is not a save failure: nothing was written, and a later edit still has its own line", async () => {
+ setKeybindingsPersister(() => Promise.reject(SERVER_SAID));
+ noteHydrateFailure(SERVER_SAID);
+ expect(shortcutSaveFailure()).toBeNull();
+
+ setBinding("editor.save", null);
+ await settle();
+
+ expect(shortcutSaveFailure()).toBe(SERVER_SAID);
+ // The refused write answered nothing about what the account holds: the read is still unread.
+ expect(shortcutLoadFailure()).toBe(SERVER_SAID);
+ });
+
+ it("is dropped by a hydrate — the account's copy has now been read", () => {
+ noteHydrateFailure(SERVER_SAID);
+
+ hydrateFromServer({ v: 1, linux: { "terminal.close": "Mod+Alt+KeyW" } });
+
+ expect(shortcutLoadFailure()).toBeNull();
+ });
+
+ it("is dropped by a hydrate that answers with no copy at all", () => {
+ noteHydrateFailure(SERVER_SAID);
+
+ hydrateFromServer(undefined);
+
+ // "Nothing stored" is still an answer: the page is the account's copy (the defaults).
+ expect(shortcutLoadFailure()).toBeNull();
+ });
+
+ it("is dropped by a write that lands: the account now holds what is on screen", async () => {
+ setKeybindingsPersister(() => Promise.resolve());
+ noteHydrateFailure(SERVER_SAID);
+
+ setBinding("editor.save", null);
+ await settle();
+
+ expect(shortcutLoadFailure()).toBeNull();
+ });
+
+ it("is not dropped by a write that was refused, or by one that never answers", async () => {
+ let answer: () => unknown = () => Promise.reject(SERVER_SAID);
+ setKeybindingsPersister(() => answer());
+ noteHydrateFailure(SERVER_SAID);
+
+ setBinding("editor.save", null);
+ await settle();
+ expect(shortcutLoadFailure()).toBe(SERVER_SAID);
+
+ // A writer still in flight has answered nothing about what the account holds: the question is
+ // exactly as unsettled as it was.
+ answer = () => new Promise(() => {});
+ setBinding("terminal.close", parseChord("Mod+Alt+KeyW"));
+ await settle();
+ expect(shortcutLoadFailure()).toBe(SERVER_SAID);
+ });
+
+ it("does not follow the tab into the next account signed in", () => {
+ noteHydrateFailure(SERVER_SAID);
+
+ setKeybindingsPersister(null); // account A signs out
+ setKeybindingsPersister(() => Promise.resolve()); // account B signs in
+
+ expect(shortcutLoadFailure()).toBeNull();
+ });
+});
+
+describe("the sentence the page draws for it", () => {
+ it("says where the rows came from, what an edit does to the account, and that a reload retries", () => {
+ const zh = S.shortcuts.loadRefused(refusalText(SERVER_SAID));
+ // The interface's own words for `internal`, not the wire message.
+ expect(zh).toContain("服务器内部错误,请稍后重试。");
+ expect(zh).not.toContain("RAW ENGLISH SERVER MESSAGE");
+ expect(zh.startsWith("没能从账号读取快捷键")).toBe(true);
+ expect(zh).toContain("来自这个浏览器");
+ expect(zh).toContain("盖掉账号上原来的按键");
+ expect(zh).toContain("重新加载");
+ // The reason ends the sentence — the app-wide shape — and the reason's own full stop is not doubled.
+ expect(zh.endsWith("服务器内部错误,请稍后重试。")).toBe(true);
+ expect(zh).not.toContain("。。");
+
+ setActiveStrings(EN);
+ const en = S.shortcuts.loadRefused(refusalText(SERVER_SAID));
+ expect(en).toContain("The server hit an internal error. Please try again shortly.");
+ expect(en).not.toContain("RAW ENGLISH SERVER MESSAGE");
+ expect(en.startsWith("The account's shortcuts could not be read")).toBe(true);
+ expect(en).toContain("from this browser");
+ expect(en).toContain("Reloading this page");
+ });
+});