Skip to content

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

fix(web): 保存被拒时确认框留在原地说明原因,不再关掉之后只剩一条六秒的通知

lmlihengc42d5022df16
diff --git a/changelog/unreleased/2026-11-03-agent-save-refusal.md b/changelog/unreleased/2026-11-03-agent-save-refusal.md
new file mode 100644
index 00000000..2dd3e69d
--- /dev/null
+++ b/changelog/unreleased/2026-11-03-agent-save-refusal.md
@@ -0,0 +1,66 @@
+# A refused save keeps its confirmation and says why, instead of closing on the click
+
+- **Date:** 2026-11-03
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[中文](2026-11-03-agent-save-refusal.zh.md)
+
+Every "save" in the Agent settings asks first, through one shared card, and confirming it starts the
+write. The card used to dismiss itself in that same click: a refusal left the unsaved edit exactly
+where it was, the card gone, and the reason only in a six-second notification sitting above where
+the card had been. Six seconds on, nothing on the page remembered that the save had failed — the
+retry was finding the Save button again. One card stands behind four forms (Overview's name and
+description, System Prompt, Runtime, Tools) and two prompt writers (Memory's own, and the Skills /
+Vault / Schedules sections), all with the same shape.
+
+The card now waits for the answer: both its buttons are locked while the write is on the wire (a
+second click cannot fire a rival write against the same sentence), and a refusal draws the server's
+own words under the card's sentence — `ConfirmModal`'s `refusal` slot, the rule "restore the
+defaults" and the model library's confirmations already follow. That sentence stays until this
+write lands, and the card's own confirm button is the retry. Only a written change closes it. The
+failure notification stays: this adds the account that outlives it, it does not take one away.
+
+## Details
+
+- `packages/web/src/features/agents/save-confirm-outcome.ts` (new): `awaitSave(run)` — a synchronous
+ or asynchronous write alike (a `void`-ed promise cannot be waited on, so call sites must hand it
+ back), answering `{ ok: true }` when it lands and `{ ok: false, reason }` when it does not, with
+ the reason read the way every refusal slot reads one (`refusalText`: the server's answer, else a
+ sentence the codebase raised itself, else the generic failure). The verdict reuses the model
+ library's `WriteOutcome` (`features/models/write-outcome.ts`, already shared with the plugins
+ page).
+- `packages/web/src/features/agents/save-confirm.tsx`: a `busy` (write on the wire) and a `refusal`
+ (the server's words), cleared when the card opens — that sentence belonged to the write that was
+ refused.
+- `packages/web/src/features/agents/agent-settings-page.tsx`: the four call sites hand the promise
+ back (they were `requestSave(() => void onSave(...))`, and `void` left the card with `undefined`,
+ as if there were no write to wait for), and the page-level `save` rethrows after its failure
+ notification.
+- `packages/web/src/features/agents/memory-tab.tsx` and `prompt-injection-controls.tsx`: the same
+ thing for their own `.then/.catch` chains — the chain is returned, and its catch rethrows after
+ the notification.
+
+## Tests
+
+- `packages/web/test/save-confirm-outcome.test.ts` (new, 6 cases): a landed write counts as `ok`,
+ synchronous or not; a refusal carries the localized reason (a Chinese UI never shows the server's
+ raw English); an unmapped code passes through as worded; a sentence the codebase raised is shown
+ as it stands; a value with nothing to say falls back to the generic failure; the write runs once.
+- `packages/web/e2e/agent-save-refusal.spec.mjs` (new, two cases on a real server): the System
+ Prompt tab and the Memory tab, one case each — two different ways to build the promise (the
+ page's shared `save` / the Memory tab's own writer). The write is refused with a 500 at
+ `page.route`: the card is still there, the reason is inside it (`操作被拒绝:agent state is
+ read-only`), the notification region holds no dismissible entry, and the server still holds the
+ old value; seven seconds later the sentence is still there; with the refusal lifted, the same
+ confirm button lands, the card closes and the server has the new value. **Counter-check**: the
+ same spec against the previous build fails both cases (the card is gone right after the click).
+- Adjacent regression (four specs in a real browser): `agent-config-refusal` 2 +
+ `agent-switch-refusal` 2 + `memory-write-refusal` 3 + `placeholder-insert-refusal` 2 — 9 passed.
+
+## Compatibility
+
+- No interface, request or storage change: the same `PUT …/agents/<agent>/config`. Only where a
+ refused one is drawn has moved — the card stays up and says why, instead of closing with the
+ reason left to a notification.
diff --git a/changelog/unreleased/2026-11-03-agent-save-refusal.zh.md b/changelog/unreleased/2026-11-03-agent-save-refusal.zh.md
new file mode 100644
index 00000000..3c8bf522
--- /dev/null
+++ b/changelog/unreleased/2026-11-03-agent-save-refusal.zh.md
@@ -0,0 +1,52 @@
+# 保存确认框被拒时留在原地说明原因,不再关掉之后只剩一条六秒的通知
+
+- **日期:** 2026-11-03
+- **类型:** fix
+- **范围:** `web`
+- **破坏性:** 无
+
+[English](2026-11-03-agent-save-refusal.md)
+
+Agent 设置里每一次「保存」都先弹同一张卡片问一句,卡片点下确认就开始写。过去它在同一次点击里
+就把自己关掉:写被拒之后表单里那条没保存的修改还在原处,卡片没了,原因只剩提示区里一条六秒的通知,
+而它盖在卡片原来待的地方上方。六秒一到,页面上没有任何东西还记得那次保存失败过 —— 想重试得自己
+再找到那颗「保存」。这一个卡片背后是四份表单(概览的名字与描述、系统提示词、运行时、工具)与两个
+提示词写入(记忆页自己的、技能 / 保险柜 / 定时任务小节的),形状都一样。
+
+现在卡片等到服务器答复才关:写入在途时两颗按钮都锁着(第二次点击不会对同一句话发出竞价的写入),
+被拒时把服务端的原话画在自己那句话下面 —— `ConfirmModal` 的 `refusal` 槽,与「还原为默认配置」和
+模型库里那些确认框同一条规则 —— 那句话留到这次写入落地为止,卡片上那颗确认按钮就是重试。只有真的
+写进去才关。失败通知保留:本笔补上的是活得下去的那条说法,没有撤掉任何一条。
+
+## 细节
+
+- `packages/web/src/features/agents/save-confirm-outcome.ts`(新):`awaitSave(run)` —— 同步或异步
+ 的写入都等(`void` 掉的 promise 等不到,所以调用点必须把它交回来),落地给 `{ ok: true }`,被拒给
+ `{ ok: false, reason }`,原因按每处拒绝槽同一条规则读(`refusalText`:服务端答复 → 代码自己抛出、
+ 本来就是给人看的那句 → 通用失败)。判定词复用模型库那份 `WriteOutcome`(`features/models/
+ write-outcome.ts`,插件页也已经在用它)。
+- `packages/web/src/features/agents/save-confirm.tsx`:多一个 `busy`(写入在途)与一个 `refusal`
+ (服务端原话),打开卡片时清空 —— 那句话属于上一次被拒的写入。
+- `packages/web/src/features/agents/agent-settings-page.tsx`:四处调用改成把 promise 交回
+ (原来是 `requestSave(() => void onSave(...))`,`void` 让卡片拿到 `undefined`、以为没有写入要等),
+ 页面级 `save` 的 catch 里在发通知之后把错误再抛出去。
+- `packages/web/src/features/agents/memory-tab.tsx` 与 `prompt-injection-controls.tsx`:同一件事,
+ 这两处是各自 `.then/.catch` 的写入链 —— 交回链本身,并在 catch 里发完通知后 rethrow。
+
+## 测试
+
+- `packages/web/test/save-confirm-outcome.test.ts`(新,6 条):同步与异步的落地都算 `ok`、被拒带
+ 本地化后的原因(中文界面不显示服务端英文原话)、未映射的码原样带过、代码自己抛的那句原样显示、
+ 没有话说的值落到通用失败、写入只跑一次。
+- `packages/web/e2e/agent-save-refusal.spec.mjs`(新,真服务端两条):系统提示词页与记忆页各一条,
+ 各走一条不同的调用路径(页面的共享 `save` / 记忆页自己的写入链)。写入在 `page.route` 上被拒成
+ 500:卡片仍在、原因在卡里(`操作被拒绝:agent state is read-only`)、通知区没有可点的条目、服务端
+ 仍是旧值;七秒后那句话仍在;放开拒绝再按同一颗确认按钮,卡片关闭、服务端拿到新值。**反证**:同一
+ 份 spec 跑改前产物两条都红(卡片在点下确认后就不见了)。
+- 相邻回归(真浏览器四份 spec):`agent-config-refusal` 2 + `agent-switch-refusal` 2 +
+ `memory-write-refusal` 3 + `placeholder-insert-refusal` 2 —— 9 条全过。
+
+## 兼容
+
+- 接口、请求与存储都没变:还是那记 `PUT …/agents/<agent>/config`。改变的只有被拒之后画在哪 ——
+ 卡片自己留着并说明原因,而不是关掉之后只剩通知。
diff --git a/packages/web/e2e/agent-save-refusal.spec.mjs b/packages/web/e2e/agent-save-refusal.spec.mjs
new file mode 100644
index 00000000..152afd77
--- /dev/null
+++ b/packages/web/e2e/agent-save-refusal.spec.mjs
@@ -0,0 +1,167 @@
+/**
+ * Regression: the save confirmation waits for the write it asked for, and a refused one keeps the
+ * card — with the server's words inside it — instead of closing on the click.
+ *
+ * Every settings form shares that card (`useSaveConfirm`): the Overview's name/description, the
+ * System Prompt, Runtime and Tools forms, and the two prompt writers (Memory's own, and the
+ * Skills / Vault / Schedules prompt sections). It used to run the write and dismiss itself in the
+ * same click, so a refusal left the card gone, the form still holding the unsaved edit, and the
+ * reason only in a toast that dismissed itself after six seconds — nothing left to retry from
+ * except finding the Save button again. Now Confirm is that retry: it stays pressed-not-finished
+ * (both card buttons locked) until the server answers, and a refusal draws `ConfirmModal`'s
+ * `refusal` strip under the card's own sentence, cleared when the write finally lands.
+ *
+ * Two different call sites are covered, because they build the promise differently: the page's
+ * shared `save` (Prompt tab) rethrows from its catch, and the Memory tab's own writer returns its
+ * chain. Both are refused at `page.route`; the config the tests write to is the server's own.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const P = "password123";
+const AGENT = "default_agent";
+
+/** What a refused save answers: its own words prove the reason came back into the card. */
+const REFUSAL = { code: "agent_state_read_only", message: "agent state is read-only" };
+
+const configPath = (projectId) => `/api/projects/${projectId}/agents/${AGENT}/config`;
+
+/** The notification region: a refused save must not be announced there instead of in the card. */
+const notifications = (page) => page.getByRole("region", { name: "通知" });
+
+/**
+ * Provision the user and give the Project a model (the onboarding overlay covers the page without
+ * one), returning the Project id and a reader for the Agent's config as the server holds it.
+ */
+async function projectWithModel(page, user) {
+ await provisionAndLogin(page.request, user, 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();
+ const stored = async () =>
+ await (await page.request.get(`${BASE}${configPath(projectId)}`)).json();
+ /** Write the baseline straight to the server (before any route is stubbed) so a rerun starts even. */
+ const seed = async (update) => {
+ const res = await page.request.put(`${BASE}${configPath(projectId)}`, { data: update });
+ expect(res.ok(), "seed the baseline").toBeTruthy();
+ };
+ return { projectId, stored, seed };
+}
+
+/**
+ * Take over the config write: every PUT is counted, and while `state.refuse` is set it is answered
+ * with the server's refusal instead of reaching the real route. Reads fall through untouched.
+ */
+async function interceptSave(page, state) {
+ await page.route(`**/api/projects/*/agents/*/config`, async (route) => {
+ if (route.request().method() !== "PUT") return route.fallback();
+ state.sent.push(route.request().postDataJSON());
+ if (!state.refuse) return route.fallback();
+ await route.fulfill({
+ status: 500,
+ contentType: "application/json",
+ body: JSON.stringify({ error: REFUSAL }),
+ });
+ });
+}
+
+/** The card's own text with the refusal strip dropped — the only thing a refusal may change. */
+async function cardText(card) {
+ return (await card.innerText()).replace(/\n操作被拒绝:[^\n]*/, "");
+}
+
+test("a refused prompt save keeps the card, its sentence, and says why", async ({ page }) => {
+ const { stored, seed } = await projectWithModel(page, "r188prompt");
+ const NEXT = "You are a probe agent answering the save-refusal test.\n";
+ // Reruns share the data root: rewind the field first so `before` is never what a past run saved.
+ await seed({ config: { systemPrompt: "A prompt left by the baseline seed.\n" } });
+ const before = await stored();
+ expect(before.config.systemPrompt).not.toBe(NEXT);
+
+ const state = { sent: [], refuse: true };
+ await interceptSave(page, state);
+
+ await page.goto(`/agents/${AGENT}?tab=prompt`);
+ await page.getByLabel("system_prompt 模板").fill(NEXT);
+ await page.getByRole("button", { name: "保存", exact: true }).click();
+
+ const dialog = page.getByRole("dialog", { name: "保存修改" });
+ await expect(dialog).toBeVisible();
+ const sentence = await cardText(dialog);
+ expect(sentence).not.toContain("操作被拒绝");
+
+ await dialog.getByRole("button", { name: "保存", exact: true }).click();
+
+ // The reason is in the card that asked, and the card is still there to retry from.
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByText(REFUSAL.message)).toBeVisible();
+ await expect(dialog.getByText(/^操作被拒绝:agent state is read-only$/)).toBeVisible();
+ expect(await cardText(dialog)).toBe(sentence);
+ expect(state.sent).toHaveLength(1);
+ expect(state.sent[0].config.systemPrompt).toBe(NEXT);
+ // The server still holds what it held, and the toast is not the only trace of the refusal.
+ expect((await stored()).config.systemPrompt).toBe(before.config.systemPrompt);
+ await expect(notifications(page).getByRole("button")).toHaveCount(0);
+
+ // Seven seconds later the sentence is still in the card (a toast would be long gone by now).
+ await page.waitForTimeout(7000);
+ await expect(dialog.getByText(/^操作被拒绝:agent state is read-only$/)).toBeVisible();
+
+ // The retry is that same Confirm button: it lands, so the card closes and the server has it.
+ state.refuse = false;
+ await dialog.getByRole("button", { name: "保存", exact: true }).click();
+ await expect(dialog).toBeHidden();
+ await expect.poll(async () => (await stored()).config.systemPrompt).toBe(NEXT);
+ expect(state.sent).toHaveLength(2);
+});
+
+test("a refused memory prompt save keeps the card too", async ({ page }) => {
+ const { stored, seed } = await projectWithModel(page, "r188memory");
+ const NEXT = "A memory prompt written by the save-refusal test.\n";
+ await seed({ config: { memory: { prompt: "A memory prompt left by the baseline seed.\n" } } });
+ const before = await stored();
+ expect(before.config.memory.prompt).not.toBe(NEXT);
+
+ const state = { sent: [], refuse: true };
+ await interceptSave(page, state);
+
+ await page.goto(`/agents/${AGENT}?tab=memory`);
+ await page.getByLabel("主提示词").fill(NEXT);
+ await page.getByRole("button", { name: "保存", exact: true }).click();
+
+ const dialog = page.getByRole("dialog", { name: "保存修改" });
+ await expect(dialog).toBeVisible();
+ const sentence = await cardText(dialog);
+
+ await dialog.getByRole("button", { name: "保存", exact: true }).click();
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByText(/^操作被拒绝:agent state is read-only$/)).toBeVisible();
+ expect(await cardText(dialog)).toBe(sentence);
+ expect(state.sent).toHaveLength(1);
+ expect(state.sent[0].config.memory.prompt).toBe(NEXT);
+ // The Memory tab keeps its own writer, so this pins the second shape of the promise.
+ expect((await stored()).config.memory.prompt).toBe(before.config.memory.prompt);
+ await expect(notifications(page).getByRole("button")).toHaveCount(0);
+
+ state.refuse = false;
+ await dialog.getByRole("button", { name: "保存", exact: true }).click();
+ await expect(dialog).toBeHidden();
+ await expect.poll(async () => (await stored()).config.memory.prompt).toBe(NEXT);
+ expect(state.sent).toHaveLength(2);
+});
diff --git a/packages/web/src/features/agents/agent-settings-page.tsx b/packages/web/src/features/agents/agent-settings-page.tsx
index e8b19608..e980606e 100644
--- a/packages/web/src/features/agents/agent-settings-page.tsx
+++ b/packages/web/src/features/agents/agent-settings-page.tsx
@@ -266,6 +266,9 @@ export function AgentSettingsPage() {
}
} catch (e) {
toastError(apiErrorText(e));
+ // The save card asked for this write, so it is the card that says why (save-confirm.tsx):
+ // it waits on this promise and keeps the refusal under its own sentence.
+ throw e;
}
},
[projectId, agentId, reloadAgents],
@@ -346,6 +349,10 @@ export function AgentSettingsPage() {
);
}
+/**
+ * A tab's write, handed to the save confirmation: the card awaits it, so every tab passes the
+ * promise on rather than `void`-ing it (save-confirm.tsx keeps a refused write in the card).
+ */
type SaveFn = (update: AgentConfigUpdateRequest) => Promise<void>;
function OverviewTab({
@@ -428,7 +435,7 @@ function OverviewTab({
toastInfo(S.common.noChangesToSave);
return;
}
- requestSave(() => void onSave({ config }));
+ requestSave(() => onSave({ config }));
};
const runImport = async (dataBase64: string, confirm: boolean) => {
@@ -717,7 +724,7 @@ function PromptTab({ data, onSave }: { data: AgentConfigResponse; onSave: SaveFn
toastInfo(S.common.noChangesToSave);
return;
}
- requestSave(() => void onSave(update));
+ requestSave(() => onSave(update));
};
/**
@@ -855,7 +862,7 @@ function RuntimeTab({ data, onSave }: { data: AgentConfigResponse; onSave: SaveF
toastInfo(S.common.noChangesToSave);
return;
}
- requestSave(() => void onSave({ config }));
+ requestSave(() => onSave({ config }));
};
// S is reassigned on language switch (live binding), so read it during render rather than hoisting to a module-level constant.
@@ -1083,7 +1090,7 @@ function ToolsTab({ data, onSave }: { data: AgentConfigResponse; onSave: SaveFn
toastInfo(S.common.noChangesToSave);
return;
}
- requestSave(() => void onSave({ config: { toolsBuiltin: tools } }));
+ requestSave(() => onSave({ config: { toolsBuiltin: tools } }));
};
/** Whether a tool's config schema declares the optional `description` call argument (only then does the per-row switch make sense). */
diff --git a/packages/web/src/features/agents/memory-tab.tsx b/packages/web/src/features/agents/memory-tab.tsx
index d2745da5..473ead86 100644
--- a/packages/web/src/features/agents/memory-tab.tsx
+++ b/packages/web/src/features/agents/memory-tab.tsx
@@ -335,7 +335,7 @@ export function MemoryTab({
const savePrompts = () =>
requestSave(() => {
if (!projectId) return;
- void api
+ return api
.putAgentConfig(projectId, agentId, {
config: { memory: { prompt: memoryPrompt, workspacePrompt } },
})
@@ -345,7 +345,12 @@ export function MemoryTab({
toastSuccess(S.agent.savedTakesEffect);
onConfigChanged?.();
})
- .catch((e: unknown) => toastError(apiErrorText(e)));
+ .catch((e: unknown) => {
+ toastError(apiErrorText(e));
+ // Handed back to the save card, which keeps the reason under its own sentence
+ // (save-confirm.tsx) — the toast above would otherwise be the only trace of it.
+ throw e;
+ });
});
const openView = async (scope: MemoryScopeInfo, file: MemoryFileInfo) => {
diff --git a/packages/web/src/features/agents/prompt-injection-controls.tsx b/packages/web/src/features/agents/prompt-injection-controls.tsx
index 84ebaf98..04406e21 100644
--- a/packages/web/src/features/agents/prompt-injection-controls.tsx
+++ b/packages/web/src/features/agents/prompt-injection-controls.tsx
@@ -226,14 +226,19 @@ export function usePromptInjection({
const savePrompt = () =>
requestSave(() => {
if (!projectId) return;
- void api
+ return api
.putAgentConfig(projectId, agentId, featurePatch({ prompt }))
.then((res) => {
applyConfig(res.config);
toastSuccess(S.agent.savedTakesEffect);
onConfigChanged?.();
})
- .catch((e: unknown) => toastError(apiErrorText(e)));
+ .catch((e: unknown) => {
+ toastError(apiErrorText(e));
+ // Handed back to the save card, which keeps the reason under its own sentence
+ // (save-confirm.tsx) — the toast above would otherwise be the only trace of it.
+ throw e;
+ });
});
const toggleCard = state !== null && (
diff --git a/packages/web/src/features/agents/save-confirm-outcome.ts b/packages/web/src/features/agents/save-confirm-outcome.ts
new file mode 100644
index 00000000..5c858f7a
--- /dev/null
+++ b/packages/web/src/features/agents/save-confirm-outcome.ts
@@ -0,0 +1,34 @@
+/**
+ * What the save confirmation's Confirm button got back (`useSaveConfirm`, save-confirm.tsx).
+ *
+ * Only a written change dismisses the card that asked for it — the rule the model library settled
+ * on (features/models/write-outcome.ts, whose verdict this reuses). The card used to close on the
+ * click and leave a refusal to a toast alone: the same sentence, in a box that dismisses itself
+ * after six seconds and sits above the card rather than in it, so the one thing the user needs
+ * while retrying was also the first thing to leave. Every settings form behind this card had that
+ * shape — the Overview's name/description, the System Prompt, Runtime and Tools forms, and the two
+ * prompt writers (Memory's, and the sections' enable prompts).
+ *
+ * The write is awaited, not fired and forgotten. A caller that still catches for itself (each one
+ * keeps its own failure toast) therefore has to rethrow, or the card would close on a write the
+ * server never took.
+ */
+import { refusalText } from "../../lib/api-error";
+import type { WriteOutcome } from "../models/write-outcome";
+
+/** One confirmed save: the caller's write, synchronous or not. */
+export type SaveRun = () => void | Promise<unknown>;
+
+/**
+ * Await a confirmed save. `ok` only when the write landed; otherwise the reason the card draws,
+ * read the way every other refusal slot reads one (`refusalText`: a server answer, else a
+ * codebase-raised sentence meant for the user, else the generic failure).
+ */
+export async function awaitSave(run: SaveRun): Promise<WriteOutcome> {
+ try {
+ await run();
+ return { ok: true };
+ } catch (e) {
+ return { ok: false, reason: refusalText(e) };
+ }
+}
diff --git a/packages/web/src/features/agents/save-confirm.tsx b/packages/web/src/features/agents/save-confirm.tsx
index 4e385191..df2d6c76 100644
--- a/packages/web/src/features/agents/save-confirm.tsx
+++ b/packages/web/src/features/agents/save-confirm.tsx
@@ -3,32 +3,70 @@
* standard "save these changes?" dialog and Confirm executes `run`. The caller decides beforehand
* whether there is anything to save (no changes → an info toast, not a dialog). Render `element`
* once per surface.
+ *
+ * The card waits for the write instead of closing on the click (see `awaitSave`): Confirm locks
+ * both buttons for as long as the request is out, so a second click cannot fire a rival write
+ * against the same sentence, and a refusal keeps the card — with the server's words under its
+ * sentence — because that Confirm button is the retry. A toast alone used to be the only account
+ * of a refused save, and it dismissed itself out of the card the user was still looking at.
*/
import { useState } from "react";
import type { ReactNode } from "react";
import { ConfirmModal } from "@adelie/ui";
import { S } from "../../lib/strings";
+import { refusalOf } from "../models/write-outcome";
+import { awaitSave, type SaveRun } from "./save-confirm-outcome";
export function useSaveConfirm(): {
- requestSave: (run: () => void) => void;
+ requestSave: (run: SaveRun) => void;
element: ReactNode;
} {
- const [pending, setPending] = useState<(() => void) | null>(null);
+ const [pending, setPending] = useState<SaveRun | null>(null);
+ /** The confirmed write is on the wire: the card stays up with its buttons locked. */
+ const [busy, setBusy] = useState(false);
+ /**
+ * The server's words for the last refused save, drawn in the card's `refusal` slot. It lives
+ * with the card because that is what the user is looking at while they press Confirm again;
+ * opening the card anew clears it — that sentence belonged to the write that was refused.
+ */
+ const [refusal, setRefusal] = useState<string | null>(null);
+
+ const close = () => {
+ setPending(null);
+ setRefusal(null);
+ };
+
const element = (
<ConfirmModal
open={pending !== null}
title={S.common.confirmSaveTitle}
tone="primary"
+ busy={busy}
+ {...(refusal === null ? {} : { refusal: S.common.refused(refusal) })}
confirmLabel={S.common.save}
cancelLabel={S.common.cancel}
- onClose={() => setPending(null)}
+ onClose={close}
onConfirm={() => {
- pending?.();
- setPending(null);
+ if (pending === null || busy) return;
+ setBusy(true);
+ setRefusal(null);
+ void awaitSave(pending).then((outcome) => {
+ setBusy(false);
+ // A refusal leaves the card open on purpose: the reason is drawn beside the button that
+ // retries the same write, and the sentence stays until that write lands.
+ if (outcome.ok) close();
+ else setRefusal(refusalOf(outcome));
+ });
}}
>
<p className="text-sm text-gray-600 dark:text-gray-300">{S.common.confirmSaveBody}</p>
</ConfirmModal>
);
- return { requestSave: (run: () => void) => setPending(() => run), element };
+ return {
+ requestSave: (run: SaveRun) => {
+ setRefusal(null);
+ setPending(() => run);
+ },
+ element,
+ };
}
diff --git a/packages/web/test/save-confirm-outcome.test.ts b/packages/web/test/save-confirm-outcome.test.ts
new file mode 100644
index 00000000..d7451d2a
--- /dev/null
+++ b/packages/web/test/save-confirm-outcome.test.ts
@@ -0,0 +1,80 @@
+/**
+ * The save confirmation's verdict (`awaitSave`, features/agents/save-confirm-outcome.ts): only a
+ * write that landed closes the card that asked for it, and a refusal carries the reason back so
+ * that card can draw it under its own sentence.
+ *
+ * - A form with nothing to wait for (a caller that returns early) closes: `ok`.
+ * - A write the server refused answers `ok: false` with the sentence every refusal slot reads —
+ * localized from the code, the server's raw English never reaching a Chinese UI.
+ * - A sentence the codebase raised itself (the request never left) is shown as it stands.
+ * - A value with nothing to say falls back to the generic failure, as everywhere else.
+ * - The run is called exactly once: the card's Confirm is that single call, retried by pressing it
+ * again rather than by replaying anything here.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { ApiError } from "../src/api/client";
+import { awaitSave } from "../src/features/agents/save-confirm-outcome";
+import { refusalOf } from "../src/features/models/write-outcome";
+import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";
+import { en as EN } from "../src/lib/strings-en";
+
+afterEach(() => {
+ setActiveStrings(ZH);
+});
+
+/** A server refusal: the code decides the wording, the message stays the server's own English. */
+const serverRefusal = (code: string): ApiError => new ApiError(409, code, "RAW SERVER MESSAGE");
+
+describe("awaitSave", () => {
+ it("closes on a landed write, synchronous or not", async () => {
+ expect(await awaitSave(() => {})).toEqual({ ok: true });
+ expect(await awaitSave(async () => {})).toEqual({ ok: true });
+ expect(await awaitSave(() => Promise.resolve({ saved: true }))).toEqual({ ok: true });
+ });
+
+ it("keeps the card with the server's reason, localized from the code", async () => {
+ for (const dict of [ZH, EN]) {
+ setActiveStrings(dict);
+ const outcome = await awaitSave(() => Promise.reject(serverRefusal("internal")));
+ expect(outcome.ok).toBe(false);
+ // The server's English message is not what a Chinese UI shows for a code it knows.
+ expect(refusalOf(outcome)).not.toBe("RAW SERVER MESSAGE");
+ expect(refusalOf(outcome)).toBe(S.errors.byCode.internal);
+ // Which is what the card then draws behind its lead-in.
+ expect(S.common.refused(refusalOf(outcome) ?? "")).toContain(S.errors.byCode.internal);
+ }
+ });
+
+ it("passes an unmapped code through as the server worded it", async () => {
+ const outcome = await awaitSave(() => Promise.reject(serverRefusal("nobody_mapped_this")));
+ expect(refusalOf(outcome)).toBe("RAW SERVER MESSAGE");
+ });
+
+ it("shows a sentence the codebase raised itself as it stands", async () => {
+ // A write the page refuses before sending (nothing to write, a missing id) has no server
+ // answer to quote, and its own message is already meant for the user.
+ const outcome = await awaitSave(() => {
+ throw new Error("保存位置还没确定");
+ });
+ expect(refusalOf(outcome)).toBe("保存位置还没确定");
+ });
+
+ it("falls back to the generic failure when the value has nothing to say", async () => {
+ expect(refusalOf(await awaitSave(() => Promise.reject({} as unknown as Error)))).toBe(
+ S.common.unknownError,
+ );
+ expect(refusalOf(await awaitSave(() => Promise.reject(new Error(" "))))).toBe(
+ S.common.unknownError,
+ );
+ });
+
+ it("runs the caller's write exactly once", async () => {
+ let runs = 0;
+ const run = () => {
+ runs += 1;
+ return Promise.reject(serverRefusal("internal"));
+ };
+ await awaitSave(run);
+ expect(runs).toBe(1);
+ });
+});