A local-first multi-agent app development platform, built on PenguinHarness
fix(web): 设置 › 服务器 › Agent API 的关闭确认框被拒时留着,原因也留在框里(7.36)
lmliheng0071572b061e
diff --git a/changelog/unreleased/2026-10-24-server-api-off-refusal.md b/changelog/unreleased/2026-10-24-server-api-off-refusal.mdnew file mode 100644index 00000000..0a418cd5--- /dev/null+++ b/changelog/unreleased/2026-10-24-server-api-off-refusal.md@@ -0,0 +1,41 @@+# Agent API: a refused server-wide off-switch keeps its question — and the reason++- **Date:** 2026-10-24+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文](2026-10-24-server-api-off-refusal.zh.md)++Settings › Server › Agent API carries the admin's server-wide switch: while it is off, every program+calling any Agent is refused. Turning it off asks first, in the danger tone. That question used to+close the moment its confirm button was pressed and write afterwards, so a refusal was reported+under the switch the card had already left behind: the retry meant opening the card again, and the+line that explained the failure read as page-level news rather than as part of the question.++The card now stays until its write lands; a refusal leaves it open with the server's words drawn+under its sentence (`ConfirmModal`'s `refusal` slot, same "Refused:" lead-in as the other cards in+the app), so the retry is the same button. While the write is in flight the card's buttons are+disabled, and opening the card again drops the previous reason, which belonged to the attempt it+named.++## Details++- `features/settings/agent-api-section.tsx`: `AgentApiServerOffConfirm` no longer calls `onClose()`+ before writing — it hands the outcome on, and the page closes the card only when the write landed+ (`settleOff`). A refusal sets `offRefusal`, rendered through `S.common.refused`; the switch goes+ back to the value the server still holds. The card takes `busy` (both buttons disabled while the+ write is in flight) and `refusal`, and the switch's own opener clears the refusal as it opens.+- Turning the switch **on** has no question of its own and keeps its old report: a refused write+ puts the knob back on the stored value and says why under it.+- New browser test `e2e/server-api-off-refusal.spec.mjs`: with the write refused at `page.route`+ 500, the card, its sentence and the server's `agentApiEnabled: true` all stay (nothing to dismiss+ in the notification region); reopening shows no stale reason; the retry on the same card writes+ it — the card closes, the switch flips, and the server answers `false`. The switch is left on at+ the end, since the other specs call Agent APIs with it on.++## Compatibility++- No interface, wire-format, stored-data or dependency change: only *when* the card closes, *where*+ the reason is drawn, and that its buttons are disabled while the write is in flight. No new copy+ beyond the existing `S.common.refused` lead-in.diff --git a/changelog/unreleased/2026-10-24-server-api-off-refusal.zh.md b/changelog/unreleased/2026-10-24-server-api-off-refusal.zh.mdnew file mode 100644index 00000000..97494521--- /dev/null+++ b/changelog/unreleased/2026-10-24-server-api-off-refusal.zh.md@@ -0,0 +1,33 @@+# 智能体 API:全服务器的关闭开关被拒时,框留着,原因也留在框里++- **Date:** 2026-10-24+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[English](2026-10-24-server-api-off-refusal.md)++设置 › 服务器 › Agent API 上那个开关是管理员的:关掉之后,所有 Agent 的 API 请求一律被拒。关闭它会先问一句+(危险色)。这句问话过去在按下确认的那一刻就自己关掉、然后再发请求,于是写入被拒的时候,原因落在**框已经离开+的**那个开关下面 —— 想重试得重新打开这张框,而那句说明读起来像是页面级的一条消息,而不是这次提问的一部分。++现在框留到自己的写入落地;被拒时框留着,服务端的原话画在它自己那句话下面(`ConfirmModal` 的 `refusal` 槽,+用的是应用既有的「操作被拒绝:」前缀),重试就是同一个按钮。写入在途时框上两个按钮置灰;重开这张框会先清掉+上一次的原因 —— 那句话属于上次那次尝试。++## 细节++- `features/settings/agent-api-section.tsx`:`AgentApiServerOffConfirm` 不再在写之前调 `onClose()`,而是把+ 结果交回去,由这一页只在写入落地时才关框(`settleOff`)。被拒时把 `offRefusal` 画进框里(经+ `S.common.refused`),开关回到服务端仍然持有的那个值。框新增 `busy`(写入在途时两个按钮置灰)与 `refusal`+ 两个 prop;开关自己那个入口在打开框时先清掉上一次的原因。+- **打开**开关没有自己的框,仍按原来的方式报:写入被拒就把开关放回存储值、在它下面说明原因。+- 新增浏览器用例 `e2e/server-api-off-refusal.spec.mjs`:用 `page.route` 把写入拒成 500 之后,框、框里那句话+ 与服务端的 `agentApiEnabled: true` 都不变(通知区没有可点的按钮),重开不带旧原因;在同一张框上重试才真正+ 写入 —— 框关、开关翻到 false、服务端回 `false`。用例结束时把开关留在打开状态,其他用例是在它打开的前提下+ 调用各 Agent 的 API 的。++## 兼容性++- 没有接口、传输格式、已存数据或依赖变化:只改了「框什么时候关」「原因画在哪」,以及写入在途时框上的按钮+ 置灰。除既有的 `S.common.refused` 前缀外没有新文案。diff --git a/packages/web/e2e/server-api-off-refusal.spec.mjs b/packages/web/e2e/server-api-off-refusal.spec.mjsnew file mode 100644index 00000000..03c01c18--- /dev/null+++ b/packages/web/e2e/server-api-off-refusal.spec.mjs@@ -0,0 +1,120 @@+/**+ * Regression: the admin's server-wide "Agent API" switch (Settings › Server › Agent API) asks+ * before it goes off, and that question closes only once its write landed — one the server+ * refused keeps the card with the reason inside it.+ *+ * The card used to close first and write second: when the write came back refused, the server+ * was exactly as it had been (every Agent's API still on), yet the reason arrived as a line+ * under the switch the card had already left behind, and the retry meant opening the card again.+ * It now stays until the outcome is known, drawing a refusal under the sentence it asked with+ * (`ConfirmModal`'s `refusal` slot), so the retry is the same button.+ *+ * The write is the page's own — refused at `page.route` — and every check reads the settings+ * back from the server, so both halves of the contract are covered. The switch is left on at the+ * end: other specs call every Agent's API with the server-wide switch on.+ */+import { test, expect } from "@playwright/test";+import { ADMIN_ID, ADMIN_PASSWORD, login } from "./auth.mjs";++const BASE = process.env.BASE_URL;++/** The refusal the write answers with: its own words prove the reason came back into the card. */+const REFUSAL = { code: "server_settings_read_only", message: "server settings are read-only" };++/** The server-wide switch as the server holds it. */+const stored = async (request) =>+ (await (await request.get(`${BASE}/api/admin/settings`)).json()).settings.agentApiEnabled;++/**+ * Take over the switch's write: `state.seen` keeps every one of them, and while `state.refuse`+ * is set the write is answered with the refusal instead of reaching the real route.+ */+async function interceptWrite(page, state) {+ await page.route("**/api/admin/settings", async (route) => {+ if (route.request().method() !== "PUT") return route.fallback();+ state.seen.push(route.request().postData() ?? "");+ if (!state.refuse) return route.fallback();+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: REFUSAL }),+ });+ });+}++/** Settings opens on the account menu's row; the switch lives on its Server group. */+async function openServerApiPage(page) {+ // The changes a Project without a model key asks for on the chat page are not part of this+ // test, so the page it starts from is the Agents list — the shell and its account menu with no+ // chat page behind them.+ await page.goto("/agents");+ // The sidebar's user row shares its name with the Project switcher (the initial Project is+ // named after the user), so take the last match — the bottom account menu.+ 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: "Agent API", exact: true }).click();+ return settings;+}++/** The card's own text with the refusal line dropped — the only thing a refusal may change. */+async function cardText(card) {+ return (await card.innerText()).replace(/\n操作被拒绝:[^\n]*/, "");+}++/** 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 server-wide API-off keeps the card, its sentence and every Agent's API on", async ({+ page,+}) => {+ await login(page.request, ADMIN_ID, ADMIN_PASSWORD);+ expect(await stored(page.request)).toBe(true);++ const state = { seen: [], refuse: true };+ await interceptWrite(page, state);++ await openServerApiPage(page);+ const apiSwitch = page.getByRole("switch", { name: "允许 Agent API" });+ await expect(apiSwitch).toHaveAttribute("aria-checked", "true");+ await apiSwitch.click();+ const dialog = page.getByRole("dialog", { name: "关闭 Agent API?" });+ await expect(dialog).toBeVisible();+ const sentence = await cardText(dialog);++ await dialog.getByRole("button", { name: "关闭", exact: true }).click();++ // The reason is in the card that asked, and it is not a toast.+ await expect(dialog.getByText(REFUSAL.message)).toBeVisible();+ await expect(notifications(page).getByRole("button")).toHaveCount(0);+ expect(state.seen).toHaveLength(1);+ await expect(dialog).toBeVisible();+ expect(await cardText(dialog)).toBe(sentence);++ // The switch never flipped and the server still has every Agent's API on.+ await expect(apiSwitch).toHaveAttribute("aria-checked", "true");+ expect(await stored(page.request)).toBe(true);++ // Closing the card decides nothing, and opening it again does not carry the old reason over.+ await dialog.getByRole("button", { name: "取消" }).click();+ await expect(dialog).toHaveCount(0);+ await apiSwitch.click();+ const reopened = page.getByRole("dialog", { name: "关闭 Agent API?" });+ await expect(reopened).toBeVisible();+ await expect(reopened.getByText(REFUSAL.message)).toHaveCount(0);++ // The retry is the same card; this time the write lands, and the card closes.+ state.refuse = false;+ await reopened.getByRole("button", { name: "关闭", exact: true }).click();+ await expect(reopened).toHaveCount(0);+ expect(state.seen).toHaveLength(2);+ expect(JSON.parse(state.seen[1])).toEqual({ agentApiEnabled: false });+ await expect(apiSwitch).toHaveAttribute("aria-checked", "false");+ expect(await stored(page.request)).toBe(false);++ // Leave the switch on for the specs that call an Agent's API after this one.+ await apiSwitch.click();+ await expect(apiSwitch).toHaveAttribute("aria-checked", "true");+ expect(await stored(page.request)).toBe(true);+});diff --git a/packages/web/src/features/settings/agent-api-section.tsx b/packages/web/src/features/settings/agent-api-section.tsxindex 49e67803..601f25f9 100644--- a/packages/web/src/features/settings/agent-api-section.tsx+++ b/packages/web/src/features/settings/agent-api-section.tsx@@ -5,8 +5,10 @@** The switch applies on the flip, like Chrome extension connections'. Turning it on writes at* once. Turning it off asks first, in the danger tone — every program calling an Agent fails from- * then on — and the knob stays on until the answer is yes. A write that fails puts the knob back- * on the stored value and says why under it.+ * then on — and the knob stays on until the answer is yes. That card closes only once its write+ * landed; one the server refused keeps the card with the reason drawn inside it, so the retry is+ * the button that was just pressed rather than a line under the switch the card had left behind.+ * A write that fails on the way on puts the knob back on the stored value and says why under it.*/import { useEffect, useState } from "react";import type { ServerSettingsResponse } from "@adelie/server/api";@@ -23,26 +25,31 @@ const switchOffAgentApiServer = (): Promise<ServerSettingsResponse> =>/*** The question before the switch goes off: the danger tone and what follows. Answered yes, it* says the write began, writes the switch off, and hands the outcome on: the stored value, or- * the failure.+ * the failure. The card stays until that outcome arrives — a refusal is drawn inside it.*/export function AgentApiServerOffConfirm({open,onClose,onWriting,onSettled,+ busy,+ refusal,}: {open: boolean;onClose: () => void;onWriting: () => void;onSettled: (outcome: { enabled: boolean } | { error: unknown }) => void;+ busy: boolean;+ refusal?: string;}) {return (<ConfirmModalopen={open}title={S.settings.agentApiOffTitle}onClose={onClose}+ busy={busy}+ {...(refusal !== undefined ? { refusal } : {})}onConfirm={() => {- onClose();onWriting();switchOffAgentApiServer().then((res) => onSettled({ enabled: res.settings.agentApiEnabled }),@@ -65,6 +72,8 @@ export function AgentApiSection() {const [busy, setBusy] = useState(false);const [error, setError] = useState<string | undefined>(undefined);const [confirmOff, setConfirmOff] = useState(false);+ /** The reason the last off-write was refused; drawn inside the card that asked, not under it. */+ const [offRefusal, setOffRefusal] = useState<string | null>(null);useEffect(() => {let cancelled = false;@@ -95,6 +104,23 @@ export function AgentApiSection() {setBusy(false);};+ /**+ * Where the off-write landed: the card closes only on the landing (off), and a refusal keeps it+ * open with the server's words inside it — the switch goes back to the stored value meanwhile,+ * which is what the server still holds.+ */+ const settleOff = (outcome: { enabled: boolean } | { error: unknown }, previous: boolean) => {+ setBusy(false);+ if ("enabled" in outcome) {+ setStored(outcome.enabled);+ setEnabled(outcome.enabled);+ setConfirmOff(false);+ } else {+ setEnabled(previous);+ setOffRefusal(apiErrorText(outcome.error));+ }+ };+const turnOn = () => {if (stored === null || busy) return;setEnabled(true);@@ -114,7 +140,12 @@ export function AgentApiSection() {checked={enabled}onChange={(next) => {if (next) turnOn();- else setConfirmOff(true);+ else {+ // Open first, then drop the previous reason: that sentence belonged to the attempt+ // it named, not to the question about to be asked.+ setConfirmOff(true);+ setOffRefusal(null);+ }}}disabled={stored === null || busy}/>@@ -128,7 +159,9 @@ export function AgentApiSection() {setError(undefined);setBusy(true);}}- onSettled={(outcome) => settle(outcome, stored ?? true)}+ onSettled={(outcome) => settleOff(outcome, stored ?? true)}+ busy={busy}+ {...(offRefusal !== null ? { refusal: S.common.refused(offRefusal) } : {})}/></SettingsSection>);diff --git a/packages/web/test/agent-api-tab.test.ts b/packages/web/test/agent-api-tab.test.tsindex 697e9a56..df4278b2 100644--- a/packages/web/test/agent-api-tab.test.ts+++ b/packages/web/test/agent-api-tab.test.ts@@ -22,7 +22,8 @@* - The Agents list carries the plug mark, named for screen readers, only on an Agent whose API* is on.* - Turning the Agent API off server-wide asks first, in the danger tone; answered yes, it writes- * the switch off and hands on what the server stored.+ * the switch off and hands on what the server stored — without closing the card itself, and a+ * refusal it asked for is drawn inside that card while its buttons wait for the write.* - The owner's tab ends with Try it, its input holding the example question; a member's tab has* no Try it.* - With the admin's server-wide switch off, Try it's input and Run are disabled, and Run carries@@ -121,6 +122,8 @@ type Confirm = ReactElement<{confirmLabel: string;children: ReactNode;onConfirm: () => void;+ /** True while the card's write is in flight: both buttons are then disabled. */+ busy?: boolean;/** The server's words for a write the card asked for and it refused (confirm-modal's slot). */refusal?: string;}>;@@ -414,18 +417,39 @@ describe("the server-wide switch", () => {it("asks first in the danger tone; answered yes, writes it off and hands on what was stored", async () => {const fetch = stubFetch(() => json({ settings: { agentApiEnabled: false } }));const onSettled = vi.fn();+ const onClose = vi.fn();const question = AgentApiServerOffConfirm({open: true,- onClose: noop,+ onClose,onWriting: noop,onSettled,+ busy: false,}) as Confirm;expect(question.props.tone).toBeUndefined();expect(fetch.requests).toEqual([]);question.props.onConfirm();await vi.waitFor(() => expect(onSettled).toHaveBeenCalledExactlyOnceWith({ enabled: false }));+ // Whether the card closes is the page's call, made once the outcome is known — not the+ // card's own move on the way out of the request.+ expect(onClose).not.toHaveBeenCalled();expect(fetch.requests.map((r) => [r.method, r.path, r.body])).toEqual([["PUT", "/api/admin/settings", { agentApiEnabled: false }],]);});++ it("draws a refusal inside the card, and greys its buttons while the write is in flight", () => {+ const base = { open: true, onClose: noop, onWriting: noop, onSettled: noop };+ const refused = AgentApiServerOffConfirm({+ ...base,+ busy: false,+ refusal: S.common.refused("admin settings are read-only"),+ }) as Confirm;+ expect(refused.props.refusal).toBe(S.common.refused("admin settings are read-only"));+ expect(refused.props.busy).toBe(false);++ const inFlight = AgentApiServerOffConfirm({ ...base, busy: true }) as Confirm;+ expect(inFlight.props.busy).toBe(true);+ // Nothing refused yet: the slot is absent rather than empty, so it is simply not drawn.+ expect(inFlight.props.refusal).toBeUndefined();+ });});