A local-first multi-agent app development platform, built on PenguinHarness
fix(web): 插件卡片保存被拒时,原因留在卡片上
lmliheng19e42b9c49f9
diff --git a/changelog/unreleased/2026-11-02-plugin-config-save-refusal.md b/changelog/unreleased/2026-11-02-plugin-config-save-refusal.mdnew file mode 100644index 00000000..03f047d0--- /dev/null+++ b/changelog/unreleased/2026-11-02-plugin-config-save-refusal.md@@ -0,0 +1,54 @@+# A plugin card whose save was refused says why, past the toast it used to be++- **Date:** 2026-11-02+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文](2026-11-02-plugin-config-save-refusal.zh.md)++Settings → Plugins saves one card at a time. When the server's schema turns a value down it names+the field, and that sentence renders under it — that half has always been right. A save can fail in+other ways too: the settings group went away under the page (a plugin or a backend was removed,+404 `plugin_config_unknown`), the session expired, the server errored, the machine is unreachable.+None of those names a field, and they only ever reached a notification that dismissed itself after+six seconds — after which every box on the card stood exactly as it was, so the save looked like a+click that did nothing.++Such a failure now stays on the card, just above the Save button that is its retry: `role="alert"`,+danger ink, clamped to two lines with the whole sentence on hover, and the shared "Refused:" lead-in.+It stays until Save is pressed again (which clears it first) or another machine is picked or the+page is opened again (a fresh read).++## Details++- `packages/web/src/features/settings/plugin-config-save.ts` (new): `pluginSaveRefusal(error)` —+ which slot a refused save belongs in: `plugin_config_invalid` whose message opens with+ `"<field>"` hands that field name back (a table cell's `<field>.<row>.<column>` travels as given,+ and the table lists it under itself); everything else belongs to the card. The words still come+ from `refusalText()`: a code the app has a sentence for is said in its words, one it has not in+ the server's.+- `packages/web/src/features/settings/plugins-section.tsx`: a `saveRefusals` map keyed by card+ name — cleared for that card as a save starts, set when a save fails without naming a field, and+ dropped wholesale when the machine changes or the section mounts; `toastError` is gone from this+ path (the install path is untouched). The named-field branch is unchanged; its decision moved+ into the module above.+- No new text, no interface and no dependency: the sentence uses the shared `S.common.refused()`+ lead-in.++## Tests++- `packages/web/test/plugin-config-save.test.ts` (new, 7 cases): a named field; a cell's full name+ travelling as given; `plugin_config_invalid` without a leading name; 404 / 500 / 401 on the card+ (a translated code in the app's words); a failure the client raised itself; nothing to say; the+ active language.+- `packages/web/e2e/plugin-config-save-refusal.spec.mjs` (new, one case on a real server): the read+ stubbed to a card with one text box and the write stubbed to a 500 `internal` — after Save there is+ one sentence on the card, no toast at all, the typed value is still in the box, and it is still+ there seven seconds later; with the refusal lifted, the same Save clears the sentence, sends the+ second request and lands.++## Compatibility++- No interface, request or storage change: the same `PUT /api/admin/plugin-config`. Only where a+ failure that names no field is drawn has moved — from a notification onto the card.diff --git a/changelog/unreleased/2026-11-02-plugin-config-save-refusal.zh.md b/changelog/unreleased/2026-11-02-plugin-config-save-refusal.zh.mdnew file mode 100644index 00000000..5edbd5f0--- /dev/null+++ b/changelog/unreleased/2026-11-02-plugin-config-save-refusal.zh.md@@ -0,0 +1,42 @@+# 插件卡片保存被拒(而服务端没点名字段)时,原因留在卡片上,不再只活六秒++- **日期:** 2026-11-02+- **类型:** fix+- **范围:** `web`+- **破坏性:** 无++[English](2026-11-02-plugin-config-save-refusal.md)++设置 →「插件」每张卡片自己保存。服务端校验不过时会点名字段,那句话画在字段下面 —— 这一半一直+是对的。但保存还能以别的方式失败:这个配置组在页面底下没了(插件或后端被卸掉,404+`plugin_config_unknown`)、登录过期、服务端出错、机器连不上。这些都不点名任何字段,而此前它们只进+了一条六秒的通知 —— 通知一走,卡片上每一个输入框都还是原样,看上去就像「点了没反应」。++现在这类失败那句话画在卡片里、保存按钮的正上方(保存按钮就是重试):`role="alert"`、危险色、限两行、+整句挂悬停,引子复用共享的「操作被拒绝:」。它留到下一次点保存(那时先清空)或换了机器 / 重新打开+这一页(一次新的读)。++## 细节++- `packages/web/src/features/settings/plugin-config-save.ts`(新):`pluginSaveRefusal(error)` ——+ 一次被拒的保存该落在哪一格:`plugin_config_invalid` 且消息以 `"<字段>"` 开头就交回那个字段名+ (表格单元格的 `<字段>.<行>.<列>` 原样带过去,表格自己会在下面列出来),其余一律交回卡片。+ 文案仍走 `refusalText()`:应用有说的按码说,没有的就照服务端写的那样说。+- `packages/web/src/features/settings/plugins-section.tsx`:多一个 `saveRefusals`(按卡片名记),+ 保存开始时清掉这一张的、失败且没点名字段时写上、改动机器或重新挂载时整体清空;`toastError` 从这+ 条路上撤掉(安装那条路一个字节没动)。点名字段那一支原样保留,只是判定搬进了上面那个纯函数。+- 没有新文案、没有新接口、没有新依赖:那句话用的是共享的 `S.common.refused()` 引子。++## 测试++- `packages/web/test/plugin-config-save.test.ts`(新,7 条):点名字段 → 字段格;单元格全名原样带过去;+ `plugin_config_invalid` 却不在开头点名 → 卡片;404 / 500 / 401 → 卡片(有译文的码按译文说);+ 客户端自己抛的失败用它自己的句子;什么都没有时用通用失败;跟着界面语言走。+- `packages/web/e2e/plugin-config-save-refusal.spec.mjs`(新,真服务端一条):读桩成一张只有文本框的+ 卡片、写桩成 500 `internal` —— 点保存后卡片上一条句子、完全没有通知、输入框里的值没变、七秒后仍在;+ 放开拒绝再点一次同一颗保存按钮:句子消失、第二次请求发出、保存落地。++## 兼容++- 接口、请求与存储都没变:还是同一个 `PUT /api/admin/plugin-config`。改变的只有「没点名字段的失败」+ 画在哪里 —— 从通知里挪到卡片上。diff --git a/packages/web/e2e/plugin-config-save-refusal.spec.mjs b/packages/web/e2e/plugin-config-save-refusal.spec.mjsnew file mode 100644index 00000000..29f73382--- /dev/null+++ b/packages/web/e2e/plugin-config-save-refusal.spec.mjs@@ -0,0 +1,156 @@+/**+ * Regression: a plugin card whose Save the server refused for a reason that names no field says+ * why on the card, above the Save button that is its retry — not in a toast that dismisses itself+ * after six seconds over a form that looks untouched.+ *+ * The server names the field it validated and turned down (`plugin_config_invalid`), and that+ * sentence renders under the field. Every other way a save can fail is about the card as a whole:+ * the settings group went away under the page (a plugin or a backend was removed),+ * the session expired, the server errored, the machine is unreachable. Those used to go to a+ * notification, which was gone six seconds later while every draft sat exactly as it was.+ *+ * The configuration under test is stubbed at the read (`GET /api/admin/plugin-config`): the real+ * sandbox card hides its fields while the switch is off and offers to install a backend the moment+ * it is turned on, which is another dialog's business. The write under test is the page's own+ * request — `PUT /api/admin/plugin-config` — and the refusal is the app's own sentence for the+ * code the server would answer with (`internal`).+ */+import { test, expect } from "@playwright/test";+import { ADMIN_ID, ADMIN_PASSWORD, login } from "./auth.mjs";++const BASE = process.env.BASE_URL;+const MOCK = process.env.MOCK_URL;++/** One entry with a single text field, so the card is a box and its Save. */+const ENTRY = {+ name: "probe",+ configuration: {+ title: "Probe",+ titleZh: "探针",+ properties: { label: { type: "string", title: "Label", titleZh: "名称" } },+ },+ values: {},+};++/** The refusal the server answers with, and what the card draws for that code. */+const REFUSAL = { code: "internal", message: "Internal server error" };+const SHOWN = "操作被拒绝:服务器内部错误,请稍后重试。";+const TYPED = "探针取值";++/**+ * Sign in as the seeded administrator (the page is admin-only) and give the Project a model —+ * the onboarding overlay covers the page without one.+ */+async function ready(page) {+ await login(page.request, ADMIN_ID, ADMIN_PASSWORD);+ const projectId = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0]+ .projectId;+ 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,+ },+ ],+ },+ });+ expect(put.ok(), "put models").toBeTruthy();+}++/** The settings dialog, opened the way a person opens it: the user menu, then a page. */+async function openSettings(page, section) {+ // The user menu shares its name with the Project switcher, so take the last match (as chat.spec).+ await page.getByRole("button", { name: ADMIN_ID }).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: section, exact: true }).click();+ return settings;+}++/**+ * The toast stack by its own hook rather than by role: the modal marks the rest of the page+ * aria-hidden, and a toast is exactly the surface this spec is about — read the DOM, so a toast+ * that is on screen still counts.+ */+function toasts(page) {+ return page.locator('section[aria-label="通知"] button');+}++/**+ * Serve the one entry, and take over its save: every `PUT` is counted, refused while `state.refuse`+ * holds, and answered with the entry as the page's own save would leave it.+ */+async function stubConfig(page, state) {+ await page.route("**/api/admin/plugin-config", async (route) => {+ const url = new URL(route.request().url());+ if (url.pathname !== "/api/admin/plugin-config") return route.fallback();+ if (route.request().method() === "GET") {+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({ plugins: [ENTRY] }),+ });+ return;+ }+ if (route.request().method() !== "PUT") return route.fallback();+ state.writes.push(route.request().postDataJSON());+ if (state.refuse) {+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: REFUSAL }),+ });+ return;+ }+ await route.fulfill({+ status: 200,+ contentType: "application/json",+ body: JSON.stringify({ plugins: [{ ...ENTRY, values: { label: TYPED } }] }),+ });+ });+}++test("a refused plugin save says why on its card, past the toast it used to be", async ({+ page,+}) => {+ await ready(page);+ const state = { writes: [], refuse: true };+ await stubConfig(page, state);++ await page.goto("/");+ const settings = await openSettings(page, "插件");+ const card = settings.locator('[data-plugin-config="probe"]');+ await expect(card).toBeVisible();+ await expect(card.getByRole("alert")).toHaveCount(0);++ const box = card.getByRole("textbox", { name: "名称" });+ await box.fill(TYPED);+ await card.getByRole("button", { name: "保存", exact: true }).click();++ // The reason is on the card, above the button that sent it, and it is not a toast.+ await expect(card.getByRole("alert")).toHaveText(SHOWN);+ await expect(card.getByRole("alert")).toHaveCount(1);+ await expect(toasts(page)).toHaveCount(0);+ expect(state.writes).toEqual([{ name: "probe", values: { label: TYPED } }]);+ // Nothing was written: the draft the person typed is still there to retry with.+ await expect(box).toHaveValue(TYPED);++ // Six seconds is how long a toast lives; this sentence has to still be there after it.+ await page.waitForTimeout(7_000);+ await expect(card.getByRole("alert")).toHaveText(SHOWN);++ // The same Save retries the same write; the sentence goes as the attempt starts and the save+ // lands this time.+ state.refuse = false;+ await card.getByRole("button", { name: "保存", exact: true }).click();+ await expect(card.getByRole("alert")).toHaveCount(0);+ expect(state.writes).toHaveLength(2);+ // The answer's values are adopted: the box shows what the server now holds.+ await expect(box).toHaveValue(TYPED);+});diff --git a/packages/web/src/features/settings/plugin-config-save.ts b/packages/web/src/features/settings/plugin-config-save.tsnew file mode 100644index 00000000..f1a28eb3--- /dev/null+++ b/packages/web/src/features/settings/plugin-config-save.ts@@ -0,0 +1,35 @@+/**+ * Where a refused save of one plugin card's settings is drawn, and what it says.+ *+ * A value the server's schema turned down is named in its answer (`plugin_config_invalid`, the+ * message opening with `"<field>"`), and that sentence belongs under that field — a cell's+ * refusal is named `<field>.<row>.<column>` and the table lists them under itself.+ *+ * Every other way a save can fail is about the card as a whole: the group went away under the page+ * (404 `plugin_config_unknown` — a plugin or a backend was removed in the meantime), the session+ * expired, the server errored, the machine is unreachable. Nothing was written, every draft is+ * exactly as it was, and the card's own Save is the retry. Those used to go to a toast, which+ * dismisses itself after six seconds and leaves a card that looks untouched (7.19's rule,+ * app-wide: a refusal lives where the thing it is about lives).+ *+ * The branch lives here rather than in the component so that which slot a failure lands in is one+ * sentence of code with a test, not a condition inside a render.+ */+import { ApiError } from "../../api/client";+import { refusalText } from "../../lib/api-error";++export type PluginSaveRefusal = {+ /** The field the server named, drawn under it; `null` when the failure is the card's own. */+ field: string | null;+ text: string;+};++/** Which slot a failed card save's sentence goes to, already localized. */+export function pluginSaveRefusal(error: unknown): PluginSaveRefusal {+ const text = refusalText(error);+ const named =+ error instanceof ApiError && error.code === "plugin_config_invalid"+ ? /^"([^"]+)"/.exec(error.message)?.[1]+ : undefined;+ return { field: named ?? null, text };+}diff --git a/packages/web/src/features/settings/plugins-section.tsx b/packages/web/src/features/settings/plugins-section.tsxindex e487fd08..3be2791c 100644--- a/packages/web/src/features/settings/plugins-section.tsx+++ b/packages/web/src/features/settings/plugins-section.tsx@@ -12,7 +12,10 @@* nothing is written until its Save, which sends each changed entry of the card in one PUT. A secret field always starts empty and shows* the stored value's mask under it: blank keeps what is stored, typing replaces it, and the* clear checkbox drops it. The server validates against the same schema and answers a- * rejected field by name, which renders under that field.+ * rejected field by name, which renders under that field; a save it refuses for any other+ * reason (the group went away, the session expired, the machine is unreachable) keeps the+ * reason on the card, above its Save — the drafts are untouched, so that button is the retry+ * (plugin-config-save.ts).** Each server keeps its own values, so the page edits one machine at a time: a picker at the* top switches between this server and the machines the Project holds a connection to, and@@ -26,8 +29,8 @@import { useEffect, useRef, useState } from "react";import type { PluginConfigEntry, PluginConfigField } from "@adelie/server/api";import * as api from "../../api/endpoints";-import { ApiError } from "../../api/client";import { S } from "../../lib/strings";+import { toneInk } from "../../lib/tone";import { useLocale } from "../../state/locale";import { localizedText } from "../chat/skill-use";import { apiErrorText } from "../../lib/api-error";@@ -55,6 +58,7 @@ import { ConfigField } from "./plugin-config-field";import { ConfigHeading } from "./plugin-config-heading";import { withLiveParts } from "./plugin-config-live";import { pluginConfigUnreadable } from "./plugin-config-read";+import { pluginSaveRefusal } from "./plugin-config-save";import { SandboxBackendPrompt } from "./sandbox-backend-prompt";import {Button,@@ -96,6 +100,13 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {/** Secret fields whose stored value the next Save drops, keyed `<plugin>\0<field>`. */const [clearing, setClearing] = useState<Set<string>>(new Set());const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});+ /**+ * Why a card's save was refused for a reason that names no field — the group went away under+ * the page, the session expired, the server errored, the machine is unreachable — keyed by the+ * card's name. Drawn just above the Save button that is its retry, rather than as a toast: the+ * drafts are exactly as they were, so a card that looks untouched is the worse answer.+ */+ const [saveRefusals, setSaveRefusals] = useState<Record<string, string>>({});const [busy, setBusy] = useState<string | null>(null);/*** A group action awaiting confirmation, with its own title. A plugin cannot mark an action@@ -150,6 +161,8 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {setEntries(null);setLoadError(null);setFieldErrors({});+ // A sentence about a save describes the values another machine (or another mount) held.+ setSaveRefusals({});void api.adminGetPluginConfig(machine).then((config) => {if (!cancelled) adopt(config.plugins);@@ -265,6 +278,12 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {return;}setBusy(card.name);+ // Another attempt: the sentence about the last one is stale from this moment on.+ setSaveRefusals((prev) => {+ const next = { ...prev };+ delete next[card.name];+ return next;+ });for (const [entry] of updates) clearErrorsOf(entry.name);try {for (const [entry, values] of updates) {@@ -274,14 +293,14 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {if (saved !== undefined) adoptOne(saved);else adopt(res.plugins);} catch (e) {- // A rejected field is named in the message as `"field" …`; it renders under that field.- const named =- e instanceof ApiError && e.code === "plugin_config_invalid"- ? /^"([^"]+)"/.exec(e.message)?.[1]- : undefined;- if (named !== undefined) {- setFieldErrors({ [`${entry.name}\0${named}`]: apiErrorText(e) });- } else toastError(apiErrorText(e));+ // A rejected field is named in the message as `"field" …`, and renders under that+ // field; anything else is about the card that asked, and stays there (7.71).+ const refusal = pluginSaveRefusal(e);+ if (refusal.field !== null) {+ setFieldErrors({ [`${entry.name}\0${refusal.field}`]: refusal.text });+ } else {+ setSaveRefusals((prev) => ({ ...prev, [card.name]: refusal.text }));+ }return;}}@@ -497,6 +516,7 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {<FocusCard focus={focus} ready={entries.length > 0} />{cards.map((card) => {const children = entries.filter((e) => e.parent === card.name);+ const saveRefusal = saveRefusals[card.name] ?? null;return (<sectionkey={card.name}@@ -528,6 +548,19 @@ export function PluginsSection({ focus }: { focus?: string } = {}) {{fields(child)}</div>))}+ {/* The save's own failure, above the button that is its retry — the fields are+ exactly as they were, so nothing else on this card would say it. Clamped to two+ lines with the whole of it on hover, because a server's words run long. */}+ {saveRefusal !== null && (+ <p+ role="alert"+ data-tooltip={S.common.refused(saveRefusal)}+ data-tooltip-content="text"+ className={`line-clamp-2 break-words text-xs ${toneInk.danger}`}+ >+ {S.common.refused(saveRefusal)}+ </p>+ )}<div className="flex justify-end"><Buttonsize="sm"diff --git a/packages/web/test/plugin-config-save.test.ts b/packages/web/test/plugin-config-save.test.tsnew file mode 100644index 00000000..638e2aef--- /dev/null+++ b/packages/web/test/plugin-config-save.test.ts@@ -0,0 +1,92 @@+/**+ * Where a refused save of one plugin card lands (`pluginSaveRefusal`). The server names the field+ * its schema turned down, so that rejection belongs under the field; every other way a save can+ * fail is about the card, and a toast would dismiss itself over a card that looks untouched.+ *+ * - A named field of `plugin_config_invalid` → that field's slot.+ * - A cell name (`<field>.<row>.<column>`) travels as given; the table lists it under itself.+ * - `plugin_config_invalid` with no leading name, and every other code → the card.+ * - A value the client raised itself → the card, with its own sentence.+ * - Nothing to say → the card, with the generic failure.+ */+import { afterEach, describe, expect, it } from "vitest";+import { ApiError } from "../src/api/client";+import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";+import { en as EN } from "../src/lib/strings-en";+import { pluginSaveRefusal } from "../src/features/settings/plugin-config-save";++const serverError = (status: number, code: string, message: string): ApiError =>+ new ApiError(status, code, message);++afterEach(() => {+ setActiveStrings(ZH);+});++describe("pluginSaveRefusal", () => {+ it("draws a named field's rejection under that field", () => {+ const refusal = pluginSaveRefusal(+ serverError(400, "plugin_config_invalid", '"maskPaths" must be a list of strings'),+ );+ expect(refusal.field).toBe("maskPaths");+ // The words travel through the app's own error text, which keeps a code it has no sentence+ // for as the server wrote it — the field line has always read this way.+ expect(refusal.text).toBe('"maskPaths" must be a list of strings');+ });++ it("keeps a refused cell's full name, so the table can list it under itself", () => {+ const refusal = pluginSaveRefusal(+ serverError(+ 400,+ "plugin_config_invalid",+ '"presets.extra.mode" is not a column of this table',+ ),+ );+ expect(refusal.field).toBe("presets.extra.mode");+ });++ it("draws an invalid answer that names no field on the card", () => {+ const refusal = pluginSaveRefusal(+ serverError(400, "plugin_config_invalid", "sandbox settings are locked"),+ );+ expect(refusal.field).toBeNull();+ expect(refusal.text).toBe("sandbox settings are locked");+ });++ it("draws every other server refusal on the card", () => {+ for (const error of [+ // The group went away under the page: a plugin or a backend was removed.+ serverError(404, "plugin_config_unknown", 'no settings group named "sandbox"'),+ serverError(500, "internal", "Internal server error"),+ serverError(401, "unauthorized", "Sign in again."),+ ]) {+ const refusal = pluginSaveRefusal(error);+ expect(refusal.field).toBeNull();+ expect(refusal.text.length).toBeGreaterThan(0);+ }+ // A code the app has words for is said in its words, not the server's.+ expect(pluginSaveRefusal(serverError(500, "internal", "Internal server error")).text).toBe(+ S.errors.byCode.internal,+ );+ });++ it("keeps the app's own sentence for a failure raised here", () => {+ const refusal = pluginSaveRefusal(new Error("连接已断开"));+ expect(refusal.field).toBeNull();+ expect(refusal.text).toBe("连接已断开");+ });++ it("falls back to the generic text when the value says nothing", () => {+ for (const value of [undefined, null, "boom", {}]) {+ const refusal = pluginSaveRefusal(value);+ expect(refusal.field).toBeNull();+ expect(refusal.text).toBe(S.common.unknownError);+ }+ });++ it("follows the active language", () => {+ setActiveStrings(EN);+ const refusal = pluginSaveRefusal(serverError(500, "internal", "Internal server error"));+ expect(refusal.text).toBe(EN.errors.byCode.internal);+ expect(refusal.text).not.toBe(ZH.errors.byCode.internal);+ });+});