A local-first multi-agent app development platform, built on PenguinHarness
fix(web): a refused shortcut save keeps its reason on the settings page
lmliheng7dbf5e74ca88
diff --git a/changelog/unreleased/2026-11-12-shortcut-save-refusal.md b/changelog/unreleased/2026-11-12-shortcut-save-refusal.mdnew file mode 100644index 00000000..15b52db4--- /dev/null+++ b/changelog/unreleased/2026-11-12-shortcut-save-refusal.md@@ -0,0 +1,52 @@+# A refused shortcut save keeps its reason on the page++- **Date:** 2026-11-12+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文版](2026-11-12-shortcut-save-refusal.zh.md)++Shortcut edits apply at once: the browser mirror is written first, so the chord in the input box and+every tooltip follow the edit before any request leaves. The account's copy is a second write, and a+refusal used to live only in a notification that dismissed itself after six seconds — while the row+kept showing the chord the account never heard, and the next load silently hydrated the account's+copy over the mirror, which was that change disappearing with nothing left to explain it.++The sentence now sits at the top of the Shortcuts page: `快捷键没能保存到账号;这一改动只在这个浏览器里+生效,重新加载后会退回账号上原来的快捷键:<reason>`. It stays until the next edit replaces it — any edit+is the retry, since one PUT carries the whole document — and nothing is toasted for it any more.++## Details++- `packages/web/src/lib/shortcuts/store.ts`: the persister's answer is watched. A write that throws,+ or a promise that rejects, is remembered (`shortcutSaveFailure()`), and cleared by the next attempt,+ by a hydrate (the screen is the account's copy again) and at an account boundary. Kept as the raw+ value, so a language switch re-words the sentence.+- `packages/web/src/lib/shortcuts/use-keymap.ts`: `useShortcutSaveFailure()` — the page that holds the+ edits reads it.+- `packages/web/src/features/settings/shortcut-runtime.tsx`: installs `PUT /api/me/prefs` itself and no+ longer toasts the refusal.+- `packages/web/src/features/settings/shortcuts-section.tsx`: draws it above the rows (`role="alert"`,+ `data-testid="shortcut-save-refusal"`, danger colour, two lines, the whole sentence on hover). Not on+ a row: a row cannot say it — it shows the new chord either way — and the write is the whole document,+ "Reset all" included.+- `packages/web/src/lib/strings{,-en}.ts`: `saveFailed` (the toast's line, now unused) becomes+ `saveRefused(reason)`; the reason ends the sentence, the app-wide shape.++## Tests++- `packages/web/test/shortcut-save-failure.test.ts`: a rejected write and a throwing writer are both+ remembered, subscribers hear about it once, a landed edit / a hydrate / Reset all / the next account+ clear it, a writer that answers with nothing invents nothing, and both dictionaries carry the cause+ and the "reverts on the next load" promise.+- `packages/web/e2e/shortcut-save-refusal.spec.mjs`: a real server and a real browser — a refused+ rebind leaves the sentence above the rows with the reason the interface translates (never the wire's+ English), nothing in the notification region, still there after seven seconds, the row showing the+ new chord, and the account's copy exactly as it was; the next edit lands, the sentence goes and the+ account follows.++## Compatibility++No wire change, no new dependency, no Project config change. Successful writes, every other+notification and the rows' hints are untouched.diff --git a/changelog/unreleased/2026-11-12-shortcut-save-refusal.zh.md b/changelog/unreleased/2026-11-12-shortcut-save-refusal.zh.mdnew file mode 100644index 00000000..a9c81cc7--- /dev/null+++ b/changelog/unreleased/2026-11-12-shortcut-save-refusal.zh.md@@ -0,0 +1,42 @@+# 快捷键没能保存到账号时,原因留在设置页上,不再只活六秒++- **日期:** 2026-11-12+- **类型:** 修复+- **范围:** `web`+- **破坏性变更:** 否++[English](2026-11-12-shortcut-save-refusal.md)++改一条快捷键是**立刻生效**的:浏览器镜像先写,所以请求还没发出去,输入区与各处提示里的组合就已经跟着变了。+账号上那一份是第二个写;此前它被拒时,原因只在一条六秒后自己消失的通知里 —— 而那一行照样显示账号从没收到过的+组合,下一次加载又把账号的那份盖回镜像,看起来就是这次改动悄悄没了、也没留下一句解释。++现在那句话画在**快捷键页的顶部**:`快捷键没能保存到账号;这一改动只在这个浏览器里生效,重新加载后会退回账号上+原来的快捷键:<原因>`。它留到下一次改动为止 —— 任何一次改动都是重试,因为一次 PUT 带的是整份文档;这件事不再+另弹通知。++## 细节++- `packages/web/src/lib/shortcuts/store.ts`:开始看写入方的回答 —— 抛出的、或被拒的 Promise 都记下来+ (`shortcutSaveFailure()`),由下一次尝试、一次 hydrate(屏幕又是账号那一份)与账号边界清掉;记的是原始值,+ 切换语言会重新造句。+- `packages/web/src/lib/shortcuts/use-keymap.ts`:`useShortcutSaveFailure()` —— 由持有这些改动的那一页来读。+- `packages/web/src/features/settings/shortcut-runtime.tsx`:自己装 `PUT /api/me/prefs`,不再把拒绝弹成通知。+- `packages/web/src/features/settings/shortcuts-section.tsx`:画在列表**上方**(`role="alert"`、+ `data-testid="shortcut-save-refusal"`、危险色、限两行、整句挂悬停)。不放在某一行:那一行说不出来 —— 它+ 本来就显示新的组合 —— 而且这次写的是整份文档,「全部恢复默认」也走同一条。+- `packages/web/src/lib/strings{,-en}.ts`:`saveFailed`(通知那一句,现已无人使用)换成 `saveRefused(reason)`;+ 原因收在句子末尾,与全应用一致。++## 测试++- `packages/web/test/shortcut-save-failure.test.ts`:被拒的写与直接抛出的写都记下来、订阅者只被通知一次、落下+ 的一次写入 / 一次 hydrate / 全部恢复默认 / 换一个账号都会清掉、只带回执不给值的写入不会凭空造出失败,以及+ 两份词典都带上原因与「重新加载会退回」这个承诺。+- `packages/web/e2e/shortcut-save-refusal.spec.mjs`:真服务端 + 真浏览器 —— 被拒的改键把句子留在列表上方、+ 用的是界面自己的那句(绝不是线上英文原文)、通知区没有东西、七秒后仍在、那一行仍显示新组合、账号那份原样未动;+ 紧接着的一次改动落定,句子归零、账号跟上。++## 兼容性++线上接口没变、没有新依赖、Project 配置没变。成功的写入、其余通知与行上的提示都一字未改。diff --git a/packages/web/e2e/shortcut-save-refusal.spec.mjs b/packages/web/e2e/shortcut-save-refusal.spec.mjsnew file mode 100644index 00000000..4f8ec8fd--- /dev/null+++ b/packages/web/e2e/shortcut-save-refusal.spec.mjs@@ -0,0 +1,148 @@+/**+ * Regression: a shortcut edit the account refused keeps the reason on the page instead of in a+ * notification that dismisses itself after six seconds.+ *+ * The edit applies at once — the browser mirror is written before any request — so the row keeps+ * showing the new chord either way, and a refusal is invisible on the row itself. The write is one+ * PUT for the whole document (every row's edit, and "Reset all"), so the sentence belongs to the+ * page: at its top, above the rows it contradicts, until the next edit replaces it. Before this+ * the reason lived only in a toast, and the next load quietly hydrated the account's copy over the+ * mirror — the change disappearing with nothing left to explain it.+ *+ * The write 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 = "shortcutsave";+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 a write that never reached the account (reason last, app-wide shape). */+const HEAD = "快捷键没能保存到账号";++const notifications = (page) => page.getByRole("region", { name: "通知" });++/** Fail every write to the prefs route from now on; `off()` lets the same kind of edit land. */+async function refusePrefsWrites(page) {+ await page.route("**/api/me/prefs", async (route) => {+ if (route.request().method() !== "PUT") 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, 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 overrides are replaced whole on every write and this user may survive from an earlier run,+ // so the page starts from the registry defaults: the rows the test rebinds are 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;+}++/** The recorder buttons, one per command, in list order. */+const recorders = (settings) => settings.locator('button[data-tooltip="更改快捷键"]');++/** What the shortcuts page itself says when the account did not take the edit: the server's prefs row. */+async function storedKeybindings(page) {+ const prefs = await (await page.request.get(`${BASE}/api/me/prefs`)).json();+ return prefs.prefs.keybindings ?? null;+}++/** Record a chord on the nth row: activate its recorder, press the combination, wait for the write. */+async function record(page, settings, index, chord) {+ const row = recorders(settings).nth(index);+ const before = await row.textContent();+ const write = page.waitForRequest(+ (req) => req.url().includes("/api/me/prefs") && req.method() === "PUT",+ );+ await row.click();+ await expect(row).toHaveAttribute("aria-pressed", "true");+ await page.keyboard.press(chord);+ await expect(row).not.toHaveAttribute("aria-pressed", "true");+ await write;+ // The row shows the new chord straight away — that is the whole reason the refusal needs its own+ // place: nothing on the row can say the account never heard.+ await expect+ .poll(async () => (await row.textContent())?.trim() ?? "")+ .not.toBe((before ?? "").trim());+}++test("a refused shortcut save keeps the reason on the page, and the account keeps its old copy", async ({+ page,+}) => {+ await signedInWithModel(page);+ await page.goto(`${BASE}/chat/new`);+ const settings = await openShortcutsPage(page);+ await expect(recorders(settings).first()).toBeVisible();++ const turnOff = await refusePrefsWrites(page);+ const beforeWrite = await storedKeybindings(page);+ await record(page, settings, 0, "Control+Shift+9");++ const refusal = settings.getByTestId("shortcut-save-refusal");+ 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");+ // Nothing is toasted for it any more.+ await expect(notifications(page).getByText(REASON)).toHaveCount(0);+ // The account's copy is exactly what it was before the refused edit: the write bought nothing.+ expect(beforeWrite).toEqual({ v: 1 });+ expect(await storedKeybindings(page)).toEqual(beforeWrite);++ // It is not a six-second notification: it is still there after one.+ await page.waitForTimeout(7000);+ await expect(refusal).toBeVisible();++ // The next edit is the retry — and this one lands, so the sentence goes.+ await turnOff();+ await record(page, settings, 1, "Control+Shift+8");+ await expect(refusal).toHaveCount(0);+ const saved = await storedKeybindings(page);+ expect(saved?.linux, "the landed edit reached the account").toBeTruthy();+});diff --git a/packages/web/src/features/settings/shortcut-runtime.tsx b/packages/web/src/features/settings/shortcut-runtime.tsxindex ac864d9d..d0d6ec2a 100644--- a/packages/web/src/features/settings/shortcut-runtime.tsx+++ b/packages/web/src/features/settings/shortcut-runtime.tsx@@ -3,13 +3,12 @@* 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.+ * 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.*/import { useEffect } from "react";-import { toastError } from "@adelie/ui";import * as api from "../../api/endpoints";-import { S } from "../../lib/strings";import { hydrateFromServer, setKeybindingsPersister } from "../../lib/shortcuts/store";import { useAuth } from "../../state/auth";@@ -18,9 +17,7 @@ export function ShortcutRuntime() {const userId = user?.userId ?? null;useEffect(() => {if (userId === null) return;- setKeybindingsPersister((doc) => {- void api.putPrefs({ keybindings: doc }).catch(() => toastError(S.shortcuts.saveFailed));- });+ setKeybindingsPersister((doc) => api.putPrefs({ keybindings: doc }));let cancelled = false;void api.getPrefs()diff --git a/packages/web/src/features/settings/shortcuts-section.tsx b/packages/web/src/features/settings/shortcuts-section.tsxindex 76a816d8..f88a2e3c 100644--- a/packages/web/src/features/settings/shortcuts-section.tsx+++ b/packages/web/src/features/settings/shortcuts-section.tsx@@ -6,9 +6,17 @@* 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).+ *+ * A write the account refused says so at the top of the page rather than in a notification that+ * dismisses itself (7.114, the rule every write refusal follows). Not on a row: one PUT carries the+ * whole document — every row's edit, and "Reset all" — so the failure is about the page, and a row+ * 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.*/import { useState } from "react";import { Button, ConfirmModal, GlyphIcon, ICON_SIZE, SettingsSection } from "@adelie/ui";+import { refusalText } from "../../lib/api-error";import { S } from "../../lib/strings";import { conflictsOf, findConflicts, type Conflict } from "../../lib/shortcuts/conflicts";import { currentHost, currentPlatform } from "../../lib/shortcuts/platform";@@ -16,7 +24,7 @@ import { SHORTCUT_COMMANDS, SHORTCUT_GROUPS, commandById } from "../../lib/shortimport { 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 { useKeymap, useShortcutSaveFailure } from "../../lib/shortcuts/use-keymap";import { toneInk } from "../../lib/tone";import { ShortcutRecorder } from "./shortcut-recorder";@@ -113,6 +121,7 @@ function ShortcutRow({export function ShortcutsSection() {const keymap = useKeymap();+ const saveFailure = useShortcutSaveFailure();const conflicts = findConflicts(keymap, SHORTCUT_COMMANDS);const overriddenCount = SHORTCUT_COMMANDS.filter((cmd) => isOverridden(cmd.id)).length;const [confirmReset, setConfirmReset] = useState(false);@@ -137,6 +146,17 @@ export function ShortcutsSection() {</Button>}>+ {saveFailure !== null && (+ <p+ role="alert"+ data-testid="shortcut-save-refusal"+ data-tooltip={S.shortcuts.saveRefused(refusalText(saveFailure))}+ data-tooltip-content="text"+ className={`line-clamp-2 break-words text-xs ${toneInk.danger}`}+ >+ {S.shortcuts.saveRefused(refusalText(saveFailure))}+ </p>+ )}{groups.map(({ group, commands }) => (<div key={group}><h3 className="mb-1 text-xs font-medium text-gray-500 dark:text-gray-400">diff --git a/packages/web/src/lib/shortcuts/store.ts b/packages/web/src/lib/shortcuts/store.tsindex 554c5d0b..d57f05e0 100644--- a/packages/web/src/lib/shortcuts/store.ts+++ b/packages/web/src/lib/shortcuts/store.ts@@ -46,7 +46,36 @@ 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;+let persister: ((doc: StoredKeybindings) => unknown) | null = null;++/**+ * Why the last write to the account's copy failed (`null` while the account holds every edit).+ *+ * The mirror is written first, so a refused write leaves each row showing the chord the edit just+ * made: the rows cannot say that the account never heard, and the next load hydrates the account's+ * copy over the mirror, which is exactly the change disappearing. So the store remembers the+ * failure — kept as the raw value, not a sentence, so a language switch re-words it — and the page+ * that holds the edits reads it (7.114). Its own version counter keeps `useSyncExternalStore`'s+ * snapshot memoization honest.+ */+let saveFailure: unknown = null;+let saveFailureVersion = 0;+const saveFailureListeners = new Set<() => void>();++function publishSaveFailure(next: unknown): void {+ saveFailure = next;+ saveFailureVersion++;+ for (const listener of [...saveFailureListeners]) listener();+}++/** Each attempt supersedes the last sentence: this edit may be the one that lands. */+function clearSaveFailure(): void {+ if (saveFailure !== null) publishSaveFailure(null);+}++function noteSaveFailure(error: unknown): void {+ publishSaveFailure(error);+}function storage(): KeybindingsStorage | null {if (storageOverride !== null) return storageOverride;@@ -108,12 +137,28 @@ 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.+ */+function sendToAccount(compact: StoredKeybindings): void {+ if (persister === null) return;+ try {+ const sent = persister(compact);+ if (sent instanceof Promise) void sent.catch(noteSaveFailure);+ } catch (error) {+ noteSaveFailure(error);+ }+}+/** 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);+ clearSaveFailure();+ sendToAccount(compact);invalidate();}@@ -124,9 +169,11 @@ function writeStored(doc: StoredKeybindings): void {* 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 {+export function setKeybindingsPersister(fn: ((doc: StoredKeybindings) => unknown) | null): void {persister = fn;writtenThisSession = false;+ // Another account's failed write is not this one's news.+ clearSaveFailure();}/**@@ -138,6 +185,8 @@ export function setKeybindingsPersister(fn: ((doc: StoredKeybindings) => void) |* account does not resurrect the previous account's bindings.*/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();if (stored !== undefined && stored !== null) {storeMirror(compactDoc(sanitizeStored(stored)));invalidate();@@ -242,6 +291,20 @@ export function keymapVersion(): number {return version;}+/** The last refused write to the account's copy, as it arrived — `null` once one lands or a hydrate arrives. */+export function shortcutSaveFailure(): unknown {+ return saveFailure;+}++export function subscribeShortcutSaveFailure(listener: () => void): () => void {+ saveFailureListeners.add(listener);+ return () => saveFailureListeners.delete(listener);+}++export function shortcutSaveFailureVersion(): number {+ return saveFailureVersion;+}+/*** 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.@@ -264,6 +327,7 @@ export function configureKeybindingsStoreForTests(options: {if (options.layout !== undefined) layout = options.layout;writtenThisSession = false;persister = null;+ clearSaveFailure();invalidate();}diff --git a/packages/web/src/lib/shortcuts/use-keymap.ts b/packages/web/src/lib/shortcuts/use-keymap.tsindex c131a756..d5ea195f 100644--- a/packages/web/src/lib/shortcuts/use-keymap.ts+++ b/packages/web/src/lib/shortcuts/use-keymap.ts@@ -9,7 +9,16 @@ import { useSyncExternalStore } from "react";import { formatChord } from "./format";import { currentHost, currentPlatform } from "./platform";import { shownOnHost } from "./reserved";-import { bindingOf, keyboardLayout, keymap, keymapVersion, subscribeKeymap } from "./store";+import {+ bindingOf,+ keyboardLayout,+ keymap,+ keymapVersion,+ shortcutSaveFailure,+ shortcutSaveFailureVersion,+ subscribeKeymap,+ subscribeShortcutSaveFailure,+} from "./store";import type { Chord, CommandId, Keymap } from "./types";export function useKeymap(): Keymap {@@ -17,6 +26,20 @@ export function useKeymap(): Keymap {return keymap();}+/**+ * Why the last edit never reached the account (null while it did). The settings page's row cannot+ * say this — the mirror was written first, so the row shows the new chord either way — which is+ * why the page that holds the edits reads it here.+ */+export function useShortcutSaveFailure(): unknown {+ useSyncExternalStore(+ subscribeShortcutSaveFailure,+ shortcutSaveFailureVersion,+ shortcutSaveFailureVersion,+ );+ return shortcutSaveFailure();+}+/** 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.tsindex f50af4e9..0fff1b02 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -185,7 +185,8 @@ export const en: Strings = {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",+ 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}`,},/** 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.tsindex 0995f62a..ae68c620 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -204,7 +204,9 @@ export const zh = {browserReserved: "浏览器保留了这个组合,只在桌面应用里生效",browserCommon: "浏览器本身也用这个组合,在浏览器里会取代它的那个功能",desktopMenuReserved: "会覆盖桌面应用菜单里使用同一组合的快捷键",- saveFailed: "快捷键未能保存到账号",+ /** 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}`,},/** Server-side terminal (the in-app dock and the standalone /terminal page). */diff --git a/packages/web/test/shortcut-save-failure.test.ts b/packages/web/test/shortcut-save-failure.test.tsnew file mode 100644index 00000000..dfde158d--- /dev/null+++ b/packages/web/test/shortcut-save-failure.test.ts@@ -0,0 +1,170 @@+/**+ * A refused write to the account's copy is remembered, so the shortcuts page can say why instead+ * of leaving the rows looking as though the edit had landed (7.114).+ *+ * The mirror is written first — that is what makes an edit apply at once, before any request — so+ * the failure cannot be read off the rows: they show the new chord either way, and the next load+ * hydrates the account's copy over the mirror, which is the change quietly disappearing. What the+ * store owes the page is therefore only the fact: the raw value that failed, cleared by the next+ * attempt (that edit may be the one that lands), by a hydrate (the screen is the account's copy+ * again) and at an account boundary (another account's failure is not this one's news).+ *+ * The sentence itself is built at render time from `refusalText`, so the last test holds both+ * dictionaries to what the sentence has to promise: the cause, and that the next load reverts.+ */+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,+ resetAll,+ setBinding,+ setKeybindingsPersister,+ shortcutSaveFailure,+ shortcutSaveFailureVersion,+ subscribeShortcutSaveFailure,+} 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 rejection the store only watched settle. */+const settle = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));++describe("a refused write to the account's copy", () => {+ it("is remembered, and subscribers hear about it once", async () => {+ const seen: unknown[] = [];+ const unsubscribe = subscribeShortcutSaveFailure(() => seen.push(shortcutSaveFailure()));+ const version = shortcutSaveFailureVersion();+ setKeybindingsPersister(() => Promise.reject(SERVER_SAID));++ setBinding("editor.save", null);+ await settle();++ expect(shortcutSaveFailure()).toBe(SERVER_SAID);+ expect(seen).toEqual([SERVER_SAID]);+ expect(shortcutSaveFailureVersion()).toBeGreaterThan(version);+ unsubscribe();+ });++ it("is remembered when the writer throws before it ever answers", () => {+ setKeybindingsPersister(() => {+ throw SERVER_SAID;+ });++ setBinding("editor.save", null);++ expect(shortcutSaveFailure()).toBe(SERVER_SAID);+ // The edit still applies here: the mirror is what the page reads.+ expect(bindingOf("editor.save")).toBeNull();+ });++ it("is not invented for a writer that carries the document and answers with nothing", () => {+ const sent: unknown[] = [];+ setKeybindingsPersister((doc) => {+ sent.push(doc);+ });++ setBinding("editor.save", null);++ expect(sent).toHaveLength(1);+ expect(shortcutSaveFailure()).toBeNull();+ });++ it("is replaced by the next edit's answer — an attempt that lands leaves nothing to say", async () => {+ let refusing = true;+ setKeybindingsPersister(() => (refusing ? Promise.reject(SERVER_SAID) : Promise.resolve()));+ setBinding("editor.save", null);+ await settle();+ expect(shortcutSaveFailure()).toBe(SERVER_SAID);++ refusing = false;+ setBinding("terminal.close", parseChord("Mod+Alt+KeyW"));+ // The attempt itself supersedes the sentence, before its answer is known: this edit may land.+ expect(shortcutSaveFailure()).toBeNull();+ await settle();+ expect(shortcutSaveFailure()).toBeNull();+ });++ it("is dropped by a hydrate: the screen is the account's copy again", async () => {+ setKeybindingsPersister(() => Promise.reject(SERVER_SAID));+ setBinding("editor.save", null);+ await settle();++ hydrateFromServer({ v: 1, linux: { "terminal.close": "Mod+Alt+KeyW" } });++ expect(shortcutSaveFailure()).toBeNull();+ expect(storage.map.get(KEYBINDINGS_KEY)).toBe(+ JSON.stringify({ v: 1, linux: { "terminal.close": "Mod+Alt+KeyW" } }),+ );+ });++ it("does not follow the tab into the next account signed in", async () => {+ setKeybindingsPersister(() => Promise.reject(SERVER_SAID));+ setBinding("editor.save", null);+ await settle();+ expect(shortcutSaveFailure()).toBe(SERVER_SAID);++ setKeybindingsPersister(null); // account A signs out+ setKeybindingsPersister(() => Promise.resolve()); // account B signs in++ expect(shortcutSaveFailure()).toBeNull();+ });++ it("is dropped by Reset all as well — it is a write like any other", async () => {+ let refusing = true;+ setKeybindingsPersister(() => (refusing ? Promise.reject(SERVER_SAID) : Promise.resolve()));+ setBinding("editor.save", null);+ await settle();+ expect(shortcutSaveFailure()).toBe(SERVER_SAID);++ refusing = false;+ resetAll();++ expect(shortcutSaveFailure()).toBeNull();+ });+});++describe("the sentence the page draws for it", () => {+ it("carries the localized reason and says the change reverts on the next load, in both languages", () => {+ const zh = S.shortcuts.saveRefused(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).toContain("重新加载");+ expect(zh.startsWith("快捷键没能保存到账号")).toBe(true);+ // 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.saveRefused(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("Shortcuts could not be saved to the account")).toBe(true);+ expect(en).toContain("next load");+ });+});