A local-first multi-agent app development platform, built on PenguinHarness
fix(web): 远程控制卡片里保存被拒时,原因留在表单里,不再只活六秒
lmliheng864f7852d09f
diff --git a/changelog/unreleased/2026-11-07-messaging-save-refusal.md b/changelog/unreleased/2026-11-07-messaging-save-refusal.mdnew file mode 100644index 00000000..2b0d4289--- /dev/null+++ b/changelog/unreleased/2026-11-07-messaging-save-refusal.md@@ -0,0 +1,59 @@+# A refused Save in the messaging card says why, in the card, not in a six-second toast++- **Date:** 2026-11-07+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文](2026-11-07-messaging-save-refusal.zh.md)++The messaging card's Save persists the selected channel's credentials and writes nothing+optimistically: while the request is in flight the form keeps every value that was typed, the saved+baseline it is compared against does not move, and it is the **success** answer that pops the+"saved" toast. A refused write therefore left a form that looked exactly as it had before the+press — still unsaved, no success toast — with the only explanation in a notification that+dismissed itself after six seconds. Whoever was looking at the button rather than at the+notification region was left with a form that still read "unsaved" and no reason for it, while the+credential the server had just rejected is a field on that same form.++That sentence now renders at the end of the card with `role="alert"`, the danger colour, two lines,+and the whole sentence on hover, and it stays until the next save starts or the channel is switched:+Save itself is the retry. The two hosts place Save differently — the session-row dialog keeps it in+its footer, the conversation's Messaging panel keeps it under the form — so the slot lives at the+end of the shared body, which is above Save in both, rather than being duplicated per host.++## Details++- `packages/web/src/features/messaging/messaging-save-refusal.ts` (new): `messagingSaveRefusal(error)`+ — the reason goes through `refusalText` (7.19's rule: an answer the server gave is read through+ its code's own localized sentence rather than the English wire message, a value this codebase+ raised itself is shown as it wrote it, and anything with nothing to say falls back to the generic+ text), and `S.messaging.saveRefused(reason)` completes the line.+- `packages/web/src/features/messaging/messaging-binding-editor.tsx`: the hook gains `saveRefusal`+ (cleared when the next save starts, when the channel is switched, and when the editor is pointed+ at another Session); Save's failure branch no longer goes to a notification but writes it, and+ `MessagingBindingBody` draws it as its last element. Validation failures keep answering through+ `fieldErrors` — the fields that block the save name themselves, and saying it twice would read as+ two problems.+- `packages/web/src/lib/strings{,-en}.ts`: one new sentence, `messaging.saveRefused(reason)`.++## Tests++- `packages/web/test/messaging-save-refusal.test.ts` (new, 5 cases): a server answer is read through+ its code's own sentence rather than the English wire message (including a 409 whose code the+ interface has its own copy for); an error this codebase raised keeps its message; nothing to say+ falls back to the generic text; both languages.+- `packages/web/e2e/messaging-save-refusal.spec.mjs` (new, real server + real browser, 3 cases): the+ write is stubbed to a 500 (a code the interface has its own sentence for, plus an English wire+ message). A refused save in the row dialog puts the sentence in the card, verbatim, once, in the+ interface's words, leaves the notification region out of it, and **seven seconds later** it is+ still there with the edited field untouched and Save still pressable. The second case: the same+ button, once the write is allowed, clears the sentence and pops the ordinary saved toast, with+ both request bodies recorded. The third travels the other host — the conversation's Messaging dock+ panel — and checks that the sentence sits **above that panel's own Save**, which is what the+ shared slot at the end of the body buys.++## Compatibility++No interface change, no new dependency, no Project config change. The success path, the enable+switch's own refusal, the credential probe's refusal and the "send test message" path are untouched.diff --git a/changelog/unreleased/2026-11-07-messaging-save-refusal.zh.md b/changelog/unreleased/2026-11-07-messaging-save-refusal.zh.mdnew file mode 100644index 00000000..ba020c03--- /dev/null+++ b/changelog/unreleased/2026-11-07-messaging-save-refusal.zh.md@@ -0,0 +1,48 @@+# 远程控制卡片里保存被拒时,原因写在卡片里,不再只活六秒++- **日期:** 2026-11-07+- **类型:** 修复+- **范围:** `web`+- **破坏性变更:** 无++[English](2026-11-07-messaging-save-refusal.md)++远程控制卡片的「保存」把所选渠道的凭证写进服务端,不做任何乐观写入:请求在飞时表单保留已填的+每一个值,用来判「未保存」的基线也不动,弹「已保存」的是**成功**那一次。于是一次被拒的写入留下+的表单与按下之前一模一样 —— 仍写着未保存、没有成功提示 —— 唯一的解释在那条六秒后自己消失的+通知里。眼睛看着按钮而不是通知区的人,手上就剩一张仍写着「未保存」的表单和一句没读到的原因,+而服务端刚拒掉的那个凭证,正是这张表单上的一个字段。++那句话现在画在卡片末尾:`role="alert"`、危险色、限两行、整句挂悬停,并且一直留到下一次保存+开始或切换渠道为止 —— 保存按钮自己就是重试。两个宿主放「保存」的位置不同(会话行对话框在页脚,+对话里的远程控制面板在表单下面),所以这个槽位放在共享 body 的末尾,两个宿主里它都在「保存」+上方,而不是每个宿主各写一份。++## 细节++- 新增 `packages/web/src/features/messaging/messaging-save-refusal.ts`:`messagingSaveRefusal(error)`+ —— 原因走 `refusalText`(7.19 的规则:服务端答复的按错误码念界面自己的本地化句子、不念线上+ 英文原文;本仓自己抛的值按它写的念;什么都没答复的落到通用文案),整句由+ `S.messaging.saveRefused(reason)` 补成「保存失败:…」。+- `packages/web/src/features/messaging/messaging-binding-editor.tsx`:hook 多一个 `saveRefusal`+ (下一次保存开始时、切换渠道时、编辑器改指另一个会话时清掉);保存的失败分支不再走通知,+ 而是写上它;`MessagingBindingBody` 把它画成 body 的最后一个元素。表单校验失败仍走+ `fieldErrors` —— 挡下保存的字段自己会说话,再说一遍会读成两个问题。+- `packages/web/src/lib/strings{,-en}.ts`:一条新文案 `messaging.saveRefused(reason)`。++## 测试++- 新增 `packages/web/test/messaging-save-refusal.test.ts`(5 条):服务端答复按错误码念界面自己的+ 句子、不念线上英文原文(含一个界面自己有文案的 409);本仓自己抛的错误保留原话;没有任何话可+ 说的落到通用文案;中英两种界面语言。+- 新增 `packages/web/e2e/messaging-save-refusal.spec.mjs`(真服务端 + 真浏览器,3 条):把写入桩成+ 500(界面自己有句子的错误码 + 一句英文原文)。会话行对话框里保存被拒:句子在卡片里、逐字、+ 只有一条、念的是界面自己的话,通知区里没有它,**七秒后**仍在,改过的字段原样、保存按钮仍可用。+ 第二条:等写入放行后重按同一个按钮,句子消失、弹出普通的「已保存」提示,两次请求体都记下来了。+ 第三条走另一个宿主 —— 对话里的远程控制停靠面板 —— 并核对句子落在**那个面板自己的「保存」上方**,+ 这正是「共享 body 末尾一个槽位」换来的东西。++## 兼容性++不改接口、不引入新依赖、不改 Project 配置。成功路径、启用开关自己的拒绝、凭证探测的拒绝、以及+「发送测试消息」那条路都没动。diff --git a/packages/web/e2e/messaging-save-refusal.spec.mjs b/packages/web/e2e/messaging-save-refusal.spec.mjsnew file mode 100644index 00000000..feda52ae--- /dev/null+++ b/packages/web/e2e/messaging-save-refusal.spec.mjs@@ -0,0 +1,262 @@+/**+ * Regression: the messaging card's Save says why a write did not land — in the card, above that+ * button — instead of leaving the form exactly as it was with the reason in a notification that+ * dismissed itself after six seconds.+ *+ * Save persists the selected channel's credentials and writes nothing optimistically: the fields+ * keep every value that was typed, the saved baseline does not move (so the form still reads as+ * unsaved), and the success toast never comes. Six seconds later the screen therefore read exactly+ * as it had before the press, while the credential the server rejected is a field on that same+ * form. The sentence now stays at the end of the card — above Save in both hosts, which is what+ * lets the dialog (footer Save) and the conversation's Messaging panel (Save under the form) share+ * one slot — until the next save or a channel switch.+ *+ * Both hosts are travelled: the first two tests use the session-row dialog, the third opens the+ * dock panel. Only the write that must be refused is taken over; the login, the Session and the+ * stored binding are real. The binding points at a closed local port, so nothing here reaches the+ * internet.+ */+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";++/** Where this channel's connector dials: nothing listens on port 9, so nothing leaves the machine. */+const DEAD_ORIGIN = "http://127.0.0.1:9";+/** The row menu action that opens the dialog (`S.messaging.bindAction`). */+const OPEN = "远程控制";+/** The labels of the two Save actions this spec presses (dialog footer and panel body). */+const SAVE = "保存";+/** The app's own sentence for a failed request (`internal`), not the server's wire message. */+const REFUSED_LINE = "保存失败:服务器内部错误,请稍后重试。";+/** The toast a save that landed pops (`S.common.saved`). */+const SAVED_TOAST = "已保存";++/**+ * Run one action from a Session row's "更多" menu. The trigger is a hover-revealed icon sitting+ * over the row's own clickable surface: when the click lands a frame before the row has re-laid+ * itself out, it hits the row (which navigates) and the menu never opens. So the open is retried+ * and verified — the same helper chat.spec.mjs uses for the same menu.+ */+async function pickRowAction(page, row, name) {+ for (let attempt = 0; attempt < 4; attempt += 1) {+ await row.hover();+ await row.getByRole("button", { name: "更多" }).click();+ const item = page.getByRole("button", { name, exact: true });+ if (await item.count()) {+ await item.first().click();+ return;+ }+ await page.keyboard.press("Escape");+ }+ throw new Error(`the row menu never offered "${name}"`);+}++/**+ * Configure the mock model, create one titled conversation and bind Feishu to it; returns its id.+ *+ * `appId` is unique per test: one account may hold only one enabled connection, and these tests+ * share a data root, so a fixed id would let an earlier run's leftover row answer the later one+ * with a 409 that has nothing to do with what is being measured.+ */+async function seed(page, projectId, title, appId) {+ const put = 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,+ pricing: { cacheRead: 1, cacheWrite: 5, output: 10 },+ },+ ],+ },+ });+ expect(put.ok(), "put models").toBeTruthy();++ const created = await page.request.post(+ `${BASE}/api/projects/${projectId}/agents/default_agent/sessions`,+ { data: { provider: "custom", modelId: "claude-4-8" } },+ );+ expect(created.ok(), "create session").toBeTruthy();+ const sessionId = (await created.json()).session.sessionId;++ const renamed = await page.request.patch(`${BASE}/api/sessions/${sessionId}`, {+ data: { title },+ });+ expect(renamed.ok(), "rename session").toBeTruthy();++ // The stored binding is what the form opens on; the write this spec measures is a NEW one.+ const bound = await page.request.put(`${BASE}/api/sessions/${sessionId}/messaging/feishu`, {+ data: { appId, appSecret: "saved-app-secret", baseDomain: DEAD_ORIGIN },+ });+ expect(bound.ok(), "bind feishu").toBeTruthy();+ return sessionId;+}++/**+ * Take over the Feishu binding write. `state.answer` picks what it does: `"refuse"` (the request+ * itself failing) or `"accept"` (letting the real route run); every call records the body, so a+ * test can check it carried the form's values.+ */+async function stubSave(page, state) {+ await page.route("**/api/sessions/*/messaging/feishu", async (route) => {+ if (route.request().method() !== "PUT") return route.fallback();+ state.seen.push(route.request().postDataJSON());+ if (state.answer === "accept") return route.fallback();+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: { code: "internal", message: "RAW ENGLISH MESSAGE" } }),+ });+ });+}++/**+ * Collect the page's console errors. The editor's own poll touches `/api/projects/…/machines`,+ * which answers 403 to anyone but an administrator, and this spec stubs a 500 on purpose — the+ * app's normal behaviour for this account and the answer under test — so those are recognised by+ * status and path and everything else fails.+ */+function watchConsole(page) {+ const errors = [];+ page.on("console", (msg) => {+ if (msg.type() !== "error") return;+ errors.push({ text: msg.text(), url: msg.location()?.url ?? "" });+ });+ return {+ unexpected: () =>+ errors.filter(({ text, url }) => {+ const status = /status of (\d{3})/.exec(text)?.[1];+ if (status === "403" && url.includes("/machines")) return false;+ if (status === "500" && url.includes("/messaging/")) return false;+ return true;+ }),+ };+}++/** Open the binding dialog from the seeded row (it opens on Feishu, the only bound channel). */+async function openDialog(page, title) {+ await page.goto("/chat");+ const sidebar = page.getByRole("complementary");+ const row = sidebar.locator("li", { hasText: title }).first();+ await expect(row).toBeVisible();+ await pickRowAction(page, row, OPEN);+ const dialog = page.getByRole("dialog");+ await expect(dialog).toBeVisible();+ return dialog;+}++/** The notification region: a refusal must not be announced there (that is the old toast). */+const notifications = (page) => page.getByRole("region", { name: "通知" });++test("a refused save keeps the reason in the form, and only there", async ({ page }) => {+ const console_ = watchConsole(page);+ await provisionAndLogin(page.request, "savetest", P);+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects.projects[0].projectId;+ const title = `e2e refused save ${Date.now()}`;+ await seed(page, projectId, title, `save-refused-${Date.now()}`);++ const state = { seen: [], answer: "refuse" };+ await stubSave(page, state);+ const dialog = await openDialog(page, title);++ // A real edit, so the form is dirty when the write is refused and the test can tell that the+ // refusal changed nothing on it.+ const appId = dialog.getByLabel("App ID", { exact: true });+ await appId.fill("cli_save_edited");+ await dialog.getByRole("button", { name: SAVE, exact: true }).click();++ // The sentence sits in the card, exactly once, in the interface's own words.+ await expect(dialog.getByRole("alert")).toHaveText(REFUSED_LINE);+ await expect(dialog.getByRole("alert")).toHaveCount(1);+ await expect(dialog.getByRole("alert")).not.toContainText("RAW ENGLISH MESSAGE");+ // Not a toast: the notification region holds nothing to dismiss.+ await expect(notifications(page).getByRole("button")).toHaveCount(0);+ // The write travelled, carrying the edited value.+ expect(state.seen).toHaveLength(1);+ expect(state.seen[0].appId).toBe("cli_save_edited");++ // Six seconds is how long a toast lives; this line has to still be there after it.+ await page.waitForTimeout(7_000);+ await expect(dialog.getByRole("alert")).toHaveText(REFUSED_LINE);+ // And the form is untouched: the edit is still in the field, Save is still pressable.+ await expect(appId).toHaveValue("cli_save_edited");+ await expect(dialog.getByRole("button", { name: SAVE, exact: true })).toBeEnabled();+ expect(console_.unexpected()).toEqual([]);+});++test("the next save replaces the sentence, and a write that lands clears it", async ({ page }) => {+ const console_ = watchConsole(page);+ await provisionAndLogin(page.request, "saveretry", P);+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects.projects[0].projectId;+ const title = `e2e retried save ${Date.now()}`;+ await seed(page, projectId, title, `save-retried-${Date.now()}`);++ const state = { seen: [], answer: "refuse" };+ await stubSave(page, state);+ const dialog = await openDialog(page, title);+ await dialog.getByLabel("App ID", { exact: true }).fill("cli_save_retried");+ await dialog.getByRole("button", { name: SAVE, exact: true }).click();+ await expect(dialog.getByRole("alert")).toHaveText(REFUSED_LINE);++ // Same button, second press: this time the write lands, so the sentence goes and the ordinary+ // saved toast arrives — the refusal was about the attempt, not about the credential.+ state.answer = "accept";+ await dialog.getByRole("button", { name: SAVE, exact: true }).click();+ await expect(notifications(page).getByText(SAVED_TOAST)).toBeVisible();+ await expect(dialog.getByRole("alert")).toHaveCount(0);+ expect(state.seen).toHaveLength(2);+ expect(state.seen[1].appId).toBe("cli_save_retried");+ expect(console_.unexpected()).toEqual([]);+});++test("the conversation's Messaging panel draws the same sentence above its own Save", async ({+ page,+}) => {+ const console_ = watchConsole(page);+ await provisionAndLogin(page.request, "savepanel", P);+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();+ const projectId = projects.projects[0].projectId;+ const title = `e2e panel save ${Date.now()}`;+ const sessionId = await seed(page, projectId, title, `save-panel-${Date.now()}`);++ const state = { seen: [], answer: "refuse" };+ await stubSave(page, state);+ await page.goto(`${BASE}/chat/${sessionId}`);+ await page.getByPlaceholder(/输入消息/).waitFor();+ // The dock's picker opens the panel on the Session the route names. The panel is a tab in the+ // right dock, and a dock that is hidden stays in the DOM at zero size — so "on screen" is+ // `data-open`, the same reading dock.spec.mjs uses.+ await page.getByTestId("dock-toggle-right").click();+ await page.getByTestId("dock-pick-messaging").click();+ const panel = page.locator('[data-testid="dock"][data-position="right"][data-open="true"]');+ await expect(panel.locator('[data-tab-id="messaging"][data-active="true"]')).toBeVisible();++ const appId = panel.getByLabel("App ID", { exact: true });+ await appId.fill("cli_save_panel");+ const save = panel.getByRole("button", { name: SAVE, exact: true });+ await save.click();++ // One slot in the shared body is above Save in both hosts: this is the panel's Save, and the+ // sentence has to sit over it rather than under it.+ const alert = panel.getByRole("alert");+ await expect(alert).toHaveText(REFUSED_LINE);+ const alertBox = await alert.boundingBox();+ const saveBox = await save.boundingBox();+ expect(alertBox.y + alertBox.height).toBeLessThanOrEqual(saveBox.y + 1);+ await expect(notifications(page).getByRole("button")).toHaveCount(0);++ // Past the six seconds a toast would have lived.+ await page.waitForTimeout(7_000);+ await expect(alert).toHaveText(REFUSED_LINE);+ await expect(appId).toHaveValue("cli_save_panel");+ expect(console_.unexpected()).toEqual([]);+});diff --git a/packages/web/src/features/messaging/messaging-binding-editor.tsx b/packages/web/src/features/messaging/messaging-binding-editor.tsxindex 5a395765..08c7071c 100644--- a/packages/web/src/features/messaging/messaging-binding-editor.tsx+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx@@ -70,6 +70,7 @@ import { toneInk, type Tone } from "../../lib/tone";import { QQScanConnect } from "./qq-scan-connect";import { WeChatScanConnect } from "./wechat-scan-connect";import { messagingTestRefusal } from "./messaging-test-refusal";+import { messagingSaveRefusal } from "./messaging-save-refusal";import {bindingsToForm,emptyMessagingForm,@@ -245,6 +246,12 @@ export interface MessagingBindingEditorState {* next probe starts — see `messaging-test-refusal.ts`.*/testRefusal: string | null;+ /**+ * Why the last save did not land (null when nothing was refused). It stays at the end of the+ * card — above Save in both hosts — until the next save starts or the channel is switched,+ * which is what makes it readable after the attempt — see `messaging-save-refusal.ts`.+ */+ saveRefusal: string | null;/** The id hosts give their Save action, so a switch gated on unsaved edits can focus it. */saveButtonId: string;/**@@ -377,6 +384,12 @@ export function useMessagingBinding(const [sendingTest, setSendingTest] = useState(false);/** The last refused credential probe, under the button that asked (see `messaging-test-refusal.ts`). */const [testRefusal, setTestRefusal] = useState<string | null>(null);+ /**+ * The last refused save, at the end of the card (see `messaging-save-refusal.ts`). Separate from+ * `testRefusal` because it is about a write that was supposed to change something, not about a+ * probe: the two are answered by different buttons and one never stands for the other.+ */+ const [saveRefusal, setSaveRefusal] = useState<string | null>(null);const saveButtonId = useId();/** Which session the form was loaded for (the initial load runs once per session, not per poll flip). */@@ -416,6 +429,8 @@ export function useMessagingBinding(setBaseline(null);// Nor the previous session's probe answer: its fields are about to leave the screen.setTestRefusal(null);+ // Nor why that other conversation's save failed: this form is a different one.+ setSaveRefusal(null);void refresh(true);}const timer = poll ? setInterval(() => void refresh(false), STATUS_POLL_MS) : null;@@ -445,6 +460,8 @@ export function useMessagingBinding(setToggleRefusal(null);// Same rule for the probe: another channel's credentials are not what that button tested.setTestRefusal(null);+ // And for the save: another channel's form is not the one that failed to write.+ setSaveRefusal(null);patchForm({ channel });};@@ -541,7 +558,15 @@ export function useMessagingBinding(}};- /** Save = persist the selected channel's credentials (no connection side effect; the toggle owns that). */+ /**+ * Save = persist the selected channel's credentials (no connection side effect; the toggle owns that).+ *+ * A refused write leaves its reason at the end of the card and NOT in a toast: the fields keep+ * every value that was typed, the saved baseline does not move (so the form still reads as+ * unsaved), and the success toast never comes — six seconds later nothing on screen would say+ * the button had been pressed, while the credential the server rejected is a field on this very+ * form. Save is the retry, so the sentence stays until the next press.+ */const save = async () => {if (!form) return;const built = formToPut(form, channels[form.channel].secretConfigured);@@ -550,6 +575,8 @@ export function useMessagingBinding(return;}setBusy(true);+ // This save's answer replaces the last one's.+ setSaveRefusal(null);try {const res =built.channel === "telegram"@@ -562,7 +589,7 @@ export function useMessagingBinding(applyChannel(built.channel, res.binding, res.status);toastSuccess(S.common.saved);} catch (e) {- toastError(apiErrorText(e));+ setSaveRefusal(messagingSaveRefusal(e));} finally {setBusy(false);}@@ -614,6 +641,7 @@ export function useMessagingBinding(enableGate,toggleRefusal,testRefusal,+ saveRefusal,saveButtonId,adoptBinding: (binding) =>applyChannel(binding.channel, binding, channels[binding.channel].status),@@ -1275,6 +1303,23 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState })checked={delivery.renderMarkdown}onChange={(v) => patchDelivery({ renderMarkdown: v })}/>+ {/* The refused save closes the card, which is where Save sits in both hosts: the dock panel+ puts its own Save row right below this body, and the dialog's footer follows the body and+ the FAQ folds — so one slot here is above that button in either host, and the two hosts+ stay free to place their action where they already do. `role="alert"` so the sentence is+ announced when it arrives (a toast was announced once and then left), `line-clamp-2` so a+ long server sentence cannot push the form around, and the whole text on hover the way+ every other refusal slot carries its longer form. */}+ {b.saveRefusal !== null && (+ <p+ role="alert"+ data-tooltip={b.saveRefusal}+ data-tooltip-content="text"+ className={`line-clamp-2 text-xs break-words ${toneInk.danger}`}+ >+ {b.saveRefusal}+ </p>+ )}</div>);}diff --git a/packages/web/src/features/messaging/messaging-save-refusal.ts b/packages/web/src/features/messaging/messaging-save-refusal.tsnew file mode 100644index 00000000..6526e39b--- /dev/null+++ b/packages/web/src/features/messaging/messaging-save-refusal.ts@@ -0,0 +1,33 @@+/**+ * The messaging card's Save: the sentence a refused write leaves in the form, and why it is a+ * line there rather than a toast.+ *+ * Save persists the selected channel's credentials and writes nothing optimistically — the+ * fields keep every value that was typed, the baseline they are compared against does not move,+ * and a successful save is what would have popped the "saved" toast. A refused one therefore+ * leaves a form that looks exactly as it did before the press, with the one sentence that+ * explains it in a notification that dismisses itself after six seconds. Whoever looked at the+ * button rather than at the notification region is left with a form that still reads "unsaved"+ * and no reason for it — and the credential they were told to fix is a field on that same form.+ *+ * So the refusal is drawn at the end of the card, above the Save action in both hosts, and it+ * stays until the next save starts or the channel is switched: Save itself is the retry.+ */+import { S } from "../../lib/strings";+import { refusalText } from "../../lib/api-error";++/**+ * The line the card draws after a save that did not land.+ *+ * One shape reaches it — the request failed — and it keeps the rule every other refusal slot in+ * the app follows (`refusalText`, 7.19's rule): an answer the server gave is read through its+ * code's own localized sentence rather than the English wire message, a value this codebase+ * raised itself is shown as it wrote it, and anything with nothing to say falls back to the+ * generic text, because an empty line under the button would say less than the toast it replaced.+ *+ * A validation failure is NOT this: the fields that block the save answer for themselves+ * (`fieldErrors`), and naming them twice would read as two problems.+ */+export function messagingSaveRefusal(error: unknown): string {+ return S.messaging.saveRefused(refusalText(error));+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 81dba308..dddba021 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -4301,6 +4301,12 @@ export const en: Strings = {sendTestMessage: "Send test message",sendingTestMessage: "Sending…",testMessageSent: "Test message sent",+ /**+ * A save the server refused, drawn at the end of the card, above Save (messaging-save-refusal.ts):+ * the form still holds what was typed and still reads as unsaved, so this line is the only+ * thing that says the write did not land once the six-second notification is gone.+ */+ saveRefused: (reason: string): string => `Save failed: ${reason}`,statusLabel: "Connection status",status: {disconnected: "Not connected",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 31c99f6b..2bfbdb72 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -4366,6 +4366,12 @@ export const zh = {sendTestMessage: "发送测试消息",sendingTestMessage: "发送中…",testMessageSent: "测试消息已发送",+ /**+ * A save the server refused, drawn at the end of the card, above Save (messaging-save-refusal.ts):+ * the form still holds what was typed and still reads as unsaved, so this line is the only+ * thing that says the write did not land once the six-second notification is gone.+ */+ saveRefused: (reason: string): string => `保存失败:${reason}`,statusLabel: "连接状态",status: {disconnected: "未连接",diff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.tsindex c0934e6b..f34682a6 100644--- a/packages/web/test/messaging-binding-editor.test.ts+++ b/packages/web/test/messaging-binding-editor.test.ts@@ -86,6 +86,7 @@ function stateOf(enableGate: null,toggleRefusal: null,testRefusal: null,+ saveRefusal: null,saveButtonId: "save-under-test",adoptBinding: () => {},save: noop,@@ -251,6 +252,25 @@ describe("MessagingBindingBody", () => {expect(render(stateOf("telegram"))).not.toContain('role="alert"');});+ it("keeps a refused save at the form's foot, where both hosts put their Save action", () => {+ // Save writes nothing optimistically, so a refusal leaves the card exactly as it was — still+ // unsaved, no success toast — and the sentence is the only account of the press. It closes+ // the body because that is above Save in BOTH hosts (the dialog's footer, the panel's own+ // row under the form), which is why the slot lives here rather than in either host.+ const line = S.messaging.saveRefused(S.errors.byCode["internal"] as string);+ const html = render(stateOf("telegram", {}, { saveRefusal: line }));+ expect(html).toContain(`>${line}</p>`);+ expect(html).toContain('role="alert"');+ // At the foot: after the delivery options that close the form, not among the controls.+ expect(html.indexOf(line)).toBeGreaterThan(html.indexOf(S.messaging.renderMarkdown));+ expect(html.indexOf(line)).toBeGreaterThan(html.indexOf(S.telegram.botToken));+ // Bounded, with the whole sentence on hover.+ expect(html).toContain(`data-tooltip="${line}"`);+ expect(html).toContain("line-clamp-2");+ // And it is that save's own line: with nothing refused, the card draws none.+ expect(render(stateOf("telegram"))).not.toContain('role="alert"');+ });+it('closes the form with the delivery options, each explanation behind its label\'s "?"', () => {for (const channel of ["feishu", "telegram", "qq", "wechat"] as MessagingChannel[]) {const html = render(stateOf(channel));diff --git a/packages/web/test/messaging-save-refusal.test.ts b/packages/web/test/messaging-save-refusal.test.tsnew file mode 100644index 00000000..7fd7e35d--- /dev/null+++ b/packages/web/test/messaging-save-refusal.test.ts@@ -0,0 +1,62 @@+/**+ * The messaging card's save line (src/features/messaging/messaging-save-refusal.ts): whose words+ * the sentence uses, and that it never comes back empty.+ *+ * A refused save changes nothing else on the card — the fields keep every value, the baseline does+ * not move, and the success toast never comes — so this line is the only thing that accounts for+ * the failure once the six-second notification is gone. The cases below are the shapes the failure+ * comes in plus the two languages.+ */+import { afterEach, describe, expect, it } from "vitest";+import { ApiError } from "../src/api/client";+import { en as EN } from "../src/lib/strings-en";+import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";+import { messagingSaveRefusal } from "../src/features/messaging/messaging-save-refusal";++afterEach(() => {+ setActiveStrings(ZH);+});++describe("messagingSaveRefusal", () => {+ it("reads a refused write through its code, so the line is the localized one", () => {+ const line = messagingSaveRefusal(new ApiError(500, "internal", "RAW ENGLISH SERVER MESSAGE"));+ expect(line).toBe(S.messaging.saveRefused(S.errors.byCode["internal"] as string));+ expect(line).not.toContain("RAW ENGLISH SERVER MESSAGE");+ expect(line.startsWith(S.messaging.saveRefused(""))).toBe(true);+ });++ it("carries a server code the map knows in its own words", () => {+ // The shape a refused credential write actually arrives in: the message is English, the code+ // is what the interface has a sentence for.+ const line = messagingSaveRefusal(+ new ApiError(409, "account_enabled_elsewhere", "Another Session has this bot enabled."),+ );+ expect(line).toBe(+ S.messaging.saveRefused(S.errors.byCode["account_enabled_elsewhere"] as string),+ );+ expect(line).not.toContain("Another Session has this bot enabled.");+ });++ it("keeps the message of an error the client itself raised", () => {+ // `refusalText`'s rule: only an ApiError goes through the code table; anything else with+ // something to say is shown as it is (a dropped connection, say), not as "unknown".+ expect(messagingSaveRefusal(new Error("network down"))).toBe(+ S.messaging.saveRefused("network down"),+ );+ });++ it("still says something when the failure carries nothing to say", () => {+ // An empty line above Save would say less than the toast it replaced.+ expect(messagingSaveRefusal(undefined)).toBe(S.messaging.saveRefused(S.common.unknownError));+ expect(messagingSaveRefusal(new Error(" "))).toBe(+ S.messaging.saveRefused(S.common.unknownError),+ );+ });++ it("follows the interface language", () => {+ setActiveStrings(EN);+ expect(messagingSaveRefusal(new Error("network down"))).toBe("Save failed: network down");+ setActiveStrings(ZH);+ expect(messagingSaveRefusal(new Error("network down"))).toBe("保存失败:network down");+ });+});