A local-first multi-agent app development platform, built on PenguinHarness
fix(web): 两个服务器开关读不出来时,原因留在开关下面
lmlihengd4549d2eef84
diff --git a/changelog/unreleased/2026-11-02-server-switch-read-refusal.md b/changelog/unreleased/2026-11-02-server-switch-read-refusal.mdnew file mode 100644index 00000000..7c96e262--- /dev/null+++ b/changelog/unreleased/2026-11-02-server-switch-read-refusal.md@@ -0,0 +1,46 @@+# A server-wide switch whose settings fail to load says why under the switch++- **Date:** 2026-11-02+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文](2026-11-02-server-switch-read-refusal.zh.md)++Two settings pages are one server-wide switch each — Settings → Server → Agent API and Settings → Server+→ company mode. Both keep their switch disabled until a stored value arrives, so a read that fails+leaves a dead knob under a value nobody read; the page said so in a toast, which was gone six seconds+later while the knob stayed dead and the page offered no reason at all.++The reason is drawn under the switch now, on the line a refused write already uses: danger-toned,+`role="alert"`, clamped to two lines with the whole sentence on hover, and it stays until the page is+left and opened again — a remount re-reads, and that is the retry. Neither switch carries a button of+its own.++## Details++- `packages/web/src/features/settings/server-switch-read.ts` (new): `readServerSwitch(pick)` reads+ `GET /api/admin/settings` once and answers `{ status: "read", value }` or `{ status: "unread",+ reason }` — the failure never throws, because these sections have nothing to retry on their own.+ `serverSwitchRefusal(read)` turns the latter into the localized sentence (shared `refusalText()`+ behind the shared "refused" lead-in) or `null`. What a failed read becomes is one function with a+ test, used by both pages.+- `packages/web/src/features/settings/agent-api-section.tsx` and `company-section.tsx`: a `loadRefusal`+ state beside the write-failure one, drawn under the switch; neither read path uses `toastError` any+ more. The write paths are untouched.++## Tests++- `packages/web/test/server-switch-read.test.ts` (new, 6 cases): the pick decides which switch comes+ back; a refused read answers with the app's own sentence for the code (not the English original),+ behind the lead-in; the sentence follows the active language; a read that never reached the server+ names the client's network failure; a sentence handed in as-is is kept; a landed read draws nothing.+- `packages/web/e2e/server-switch-read-refusal.spec.mjs` (new, two cases on a real server): with the+ read refused — one sentence in the section, the switch disabled, no toast at all, still there after+ seven seconds; leaving the page and coming back (a remount is the retry) clears it, opens the switch+ and shows what the server holds.++## Compatibility++- No interface, request or storage change: the same `GET /api/admin/settings`. Only where the sentence+ is drawn on failure has moved.diff --git a/changelog/unreleased/2026-11-02-server-switch-read-refusal.zh.md b/changelog/unreleased/2026-11-02-server-switch-read-refusal.zh.mdnew file mode 100644index 00000000..9d08b8c2--- /dev/null+++ b/changelog/unreleased/2026-11-02-server-switch-read-refusal.zh.md@@ -0,0 +1,38 @@+# 两个服务器开关读不出来时,原因留在开关下面,不再只活六秒++- **日期:** 2026-11-02+- **类型:** fix+- **范围:** `web`+- **破坏性:** 无++[English](2026-11-02-server-switch-read-refusal.md)++设置 →「服务器」里的两页各是一个服务端级的开关 ——「Agent API」与「公司模式」。两个开关都要等到服务端+的值到达才能用,所以一次读失败留下的是一个谁都读不到的、灰着的开关;页面对此只说过一句六秒的通知,+六秒后开关还是灰着,而屏上没有任何理由。++现在那句话画在开关下面,用的正是被拒的写入已经在用的那一行:danger 色、`role="alert"`、限两行、整句挂+悬停,并且一直留到离开这一页再回来 —— 重新挂载即重新拉取,那就是重试。两个开关都没有自己的按钮。++## 细节++- `packages/web/src/features/settings/server-switch-read.ts`(新):`readServerSwitch(pick)` 读一次+ `GET /api/admin/settings`,答 `{ status: "read", value }` 或 `{ status: "unread", reason }` —— 失败从不+ 抛出,因为这两页自己没有什么可重试的;`serverSwitchRefusal(read)` 把后者变成本地化的那句(走共享的+ `refusalText()`,外面套共享的「被拒」引子),读到了就什么都不画。一次失败的读取变成哪句话,是一句话+ 加一条用例,两页共用。+- `packages/web/src/features/settings/agent-api-section.tsx` 与 `company-section.tsx`:写入失败那个状态+ 之外多一个 `loadRefusal`,画在开关下面;读那条路不再 `toastError`。写的那条路一个字没动。++## 测试++- `packages/web/test/server-switch-read.test.ts`(新,6 条):取哪个开关由 pick 决定;被拒的读回答应用的+ 那句话(不是英文原文),外面套着引子;句子跟着当前语言;根本没连上服务端时说的是客户端那句网络错误;+ 传进来的句子原样保留;读到了就什么都不画。+- `packages/web/e2e/server-switch-read-refusal.spec.mjs`(新,真服务端两条):读被拒时 —— 句子在设置区里+ 一条、开关停用、完全没有 toast、七秒后仍在;离开这一页再回来(重新挂载即重试)后句子消失、开关打开、+ 显示的是服务端真正存着的值。++## 兼容++- 接口、请求与存储都没变:还是同一个 `GET /api/admin/settings`。改变的只有失败时那句话画在哪里。diff --git a/packages/web/e2e/server-switch-read-refusal.spec.mjs b/packages/web/e2e/server-switch-read-refusal.spec.mjsnew file mode 100644index 00000000..1751071c--- /dev/null+++ b/packages/web/e2e/server-switch-read-refusal.spec.mjs@@ -0,0 +1,161 @@+/**+ * Regression: the two server-wide switches — Settings → 服务器 → Agent API and 公司模式 — say why+ * they are shut when `GET /api/admin/settings` fails, on the same line a refused write uses, and+ * that sentence outlives the six seconds a toast lives.+ *+ * Both switches stay disabled until a stored value arrives, so a failed read leaves a dead knob+ * under a value nobody read; the page used to say so in a notification that dismissed itself,+ * leaving the knob dead with nothing on screen about it.+ *+ * The read is stubbed at `page.route` rather than provoked from the server: what is under test is+ * what the page does with an answer, and the sentence asserted is the app's own for the code the+ * server would send (`internal`), behind the shared lead-in. Leaving the page and coming back is+ * the retry — the sections are mounted only while they are the open page.+ */+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;++/** The line the section draws: the shared lead-in plus the app's sentence for `internal`. */+const REFUSED = "操作被拒绝:服务器内部错误,请稍后重试。";++/**+ * Sign in as the seeded administrator (both pages are 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 section element holding the switch, so both the switch and its line are read together. */+function sectionOf(settings, switchName) {+ return settings.locator("section").filter({ hasText: switchName });+}++/**+ * 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');+}++/**+ * Answer `GET /api/admin/settings` with a refusal (500 `internal`) until `letThrough()`.+ * Counted, so the spec can tell whether a request was really sent at all.+ */+async function stubRead(page, seen) {+ let refuse = true;+ await page.route("**/api/admin/settings", async (route) => {+ if (route.request().method() !== "GET") return route.fallback();+ seen.push(route.request().url());+ if (!refuse) return route.fallback();+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: { code: "internal", message: "Internal server error" } }),+ });+ });+ return () => {+ refuse = false;+ };+}++test("the Agent API switch says why it is shut, past the toast it used to be", async ({ page }) => {+ await ready(page);+ const reads = [];+ const letThrough = await stubRead(page, reads);++ await page.goto("/");+ const settings = await openSettings(page, "Agent API");+ const section = sectionOf(settings, "允许 Agent API");++ // The sentence, under the switch it left shut — once, and not as a notification over it.+ await expect(section.getByRole("alert")).toHaveText(REFUSED);+ await expect(section.getByRole("alert")).toHaveCount(1);+ await expect(section.getByRole("switch", { name: "允许 Agent API" })).toBeDisabled();+ expect(reads.length).toBeGreaterThanOrEqual(1);+ await expect(toasts(page)).toHaveCount(0);++ // Six seconds is how long a toast lives; this sentence has to still be there after it.+ await page.waitForTimeout(7_000);+ await expect(section.getByRole("alert")).toHaveText(REFUSED);+ await expect(section.getByRole("switch", { name: "允许 Agent API" })).toBeDisabled();++ // Leaving the page and coming back is the retry: the read lands, the sentence goes, the switch+ // opens on what the server holds (on by default).+ letThrough();+ const remountAt = reads.length;+ await settings.getByRole("button", { name: "通用", exact: true }).click();+ await settings.getByRole("button", { name: "Agent API", exact: true }).click();+ const again = sectionOf(settings, "允许 Agent API");+ await expect(again.getByRole("alert")).toHaveCount(0);+ await expect(again.getByRole("switch", { name: "允许 Agent API" })).toBeEnabled();+ await expect(again.getByRole("switch", { name: "允许 Agent API" })).toBeChecked();+ expect(reads.length).toBeGreaterThan(remountAt);+});++test("the company-mode switch says why it is shut, past the toast it used to be", async ({+ page,+}) => {+ await ready(page);+ const reads = [];+ const letThrough = await stubRead(page, reads);++ await page.goto("/");+ const settings = await openSettings(page, "公司模式");+ const section = sectionOf(settings, "启用公司模式");++ await expect(section.getByRole("alert")).toHaveText(REFUSED);+ await expect(section.getByRole("alert")).toHaveCount(1);+ await expect(section.getByRole("switch", { name: "启用公司模式" })).toBeDisabled();+ expect(reads.length).toBeGreaterThanOrEqual(1);+ await expect(toasts(page)).toHaveCount(0);++ await page.waitForTimeout(7_000);+ await expect(section.getByRole("alert")).toHaveText(REFUSED);+ await expect(section.getByRole("switch", { name: "启用公司模式" })).toBeDisabled();++ // The retry is the same: another page and back. The server holds the mode off, and the switch+ // now shows that rather than the disabled default it was stuck on.+ letThrough();+ const remountAt = reads.length;+ await settings.getByRole("button", { name: "通用", exact: true }).click();+ await settings.getByRole("button", { name: "公司模式", exact: true }).click();+ const again = sectionOf(settings, "启用公司模式");+ await expect(again.getByRole("alert")).toHaveCount(0);+ await expect(again.getByRole("switch", { name: "启用公司模式" })).toBeEnabled();+ await expect(again.getByRole("switch", { name: "启用公司模式" })).not.toBeChecked();+ expect(reads.length).toBeGreaterThan(remountAt);+});diff --git a/packages/web/src/features/settings/agent-api-section.tsx b/packages/web/src/features/settings/agent-api-section.tsxindex 601f25f9..3be1e6be 100644--- a/packages/web/src/features/settings/agent-api-section.tsx+++ b/packages/web/src/features/settings/agent-api-section.tsx@@ -9,14 +9,17 @@* 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.+ * A settings read that fails says why under the switch too: the knob stays shut until a stored+ * value arrives, and leaving the page and coming back is the retry.*/import { useEffect, useState } from "react";import type { ServerSettingsResponse } from "@adelie/server/api";-import { ConfirmModal, SettingsSection, ToggleRow, toastError } from "@adelie/ui";+import { ConfirmModal, SettingsSection, ToggleRow } from "@adelie/ui";import * as api from "../../api/endpoints";import { apiErrorText } from "../../lib/api-error";import { S } from "../../lib/strings";import { toneInk } from "../../lib/tone";+import { readServerSwitch, serverSwitchRefusal } from "./server-switch-read";/** Turns the switch off on the server. Reached only through the confirm. */const switchOffAgentApiServer = (): Promise<ServerSettingsResponse> =>@@ -74,19 +77,20 @@ export function AgentApiSection() {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);+ /** Why the settings could not be read, drawn under the switch it left shut (null once read). */+ const [loadRefusal, setLoadRefusal] = useState<string | null>(null);useEffect(() => {let cancelled = false;- void api- .adminGetSettings()- .then((res) => {- if (cancelled) return;- setStored(res.settings.agentApiEnabled);- setEnabled(res.settings.agentApiEnabled);- })- .catch((e: unknown) => {- if (!cancelled) toastError(apiErrorText(e));- });+ void readServerSwitch((settings) => settings.agentApiEnabled).then((read) => {+ if (cancelled) return;+ if (read.status === "read") {+ setStored(read.value);+ setEnabled(read.value);+ } else {+ setLoadRefusal(serverSwitchRefusal(read));+ }+ });return () => {cancelled = true;};@@ -149,6 +153,18 @@ export function AgentApiSection() {}}disabled={stored === null || busy}/>+ {/* Why the switch is shut, under the switch — this is the only thing that says so once+ the read failed, and it stays until the page is entered again. */}+ {loadRefusal !== null && (+ <p+ role="alert"+ data-tooltip={loadRefusal}+ data-tooltip-content="text"+ className={`mt-2 line-clamp-2 break-words text-xs ${toneInk.danger}`}+ >+ {loadRefusal}+ </p>+ )}{error !== undefined && <p className={`mt-2 text-xs ${toneInk.danger}`}>{error}</p>}</div><AgentApiServerOffConfirmdiff --git a/packages/web/src/features/settings/company-section.tsx b/packages/web/src/features/settings/company-section.tsxindex badbb358..4eb69352 100644--- a/packages/web/src/features/settings/company-section.tsx+++ b/packages/web/src/features/settings/company-section.tsx@@ -8,18 +8,21 @@* backfilling what was missed, and only brings the mode switch back — nobody's shell moves into* company mode by it (state/company.tsx). A write that fails puts the switch back on the stored* value and names the reason on a line under it (a toast would leave the switch and the message- * on separate surfaces). The auth context is refreshed afterwards because the shell reads the+ * on separate surfaces). A settings read that fails names the reason on that same line: the+ * switch stays disabled until a stored value arrives, and leaving the page and coming back is+ * the retry. The auth context is refreshed afterwards because the shell reads the* flag from /api/me, not from this page. The mode is a beta; the line under the switch says so* wherever the switch stands.*/import { useEffect, useState } from "react";-import { SettingsSection, ToggleRow, toastError } from "@adelie/ui";+import { SettingsSection, ToggleRow } from "@adelie/ui";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { toneInk } from "../../lib/tone";import { useAuth } from "../../state/auth";import { writeCompanyMode } from "./company-mode-write";+import { readServerSwitch, serverSwitchRefusal } from "./server-switch-read";export function CompanySection() {const { refresh } = useAuth();@@ -29,19 +32,20 @@ export function CompanySection() {const [companyMode, setCompanyMode] = useState(false);const [busy, setBusy] = useState(false);const [error, setError] = useState<string | undefined>(undefined);+ /** Why the settings could not be read, drawn on the same line under the switch (null once read). */+ const [loadRefusal, setLoadRefusal] = useState<string | null>(null);useEffect(() => {let cancelled = false;- void api- .adminGetSettings()- .then((res) => {- if (cancelled) return;- setStored(res.settings.companyMode);- setCompanyMode(res.settings.companyMode);- })- .catch((e: unknown) => {- if (!cancelled) toastError(apiErrorText(e));- });+ void readServerSwitch((settings) => settings.companyMode).then((read) => {+ if (cancelled) return;+ if (read.status === "read") {+ setStored(read.value);+ setCompanyMode(read.value);+ } else {+ setLoadRefusal(serverSwitchRefusal(read));+ }+ });return () => {cancelled = true;};@@ -83,6 +87,17 @@ export function CompanySection() {/>{/* The reason the switch went back, under the switch it went back on. */}{error !== undefined && <p className={`mt-2 text-xs ${toneInk.danger}`}>{error}</p>}+ {/* Why the switch never came on: the read failed, so it has no stored value to show. */}+ {loadRefusal !== null && (+ <p+ role="alert"+ data-tooltip={loadRefusal}+ data-tooltip-content="text"+ className={`mt-2 line-clamp-2 break-words text-xs ${toneInk.danger}`}+ >+ {loadRefusal}+ </p>+ )}{/* The mode is a beta, and this switch signs a whole server up for it: the warningstands under it unconditionally rather than behind the page's "?", which is aclick away and is read once. */}diff --git a/packages/web/src/features/settings/server-switch-read.ts b/packages/web/src/features/settings/server-switch-read.tsnew file mode 100644index 00000000..ab4e8c09--- /dev/null+++ b/packages/web/src/features/settings/server-switch-read.ts@@ -0,0 +1,42 @@+/**+ * Reading one server-wide switch for the settings section that owns it (Agent API, company+ * mode): a single boolean out of `GET /api/admin/settings`.+ *+ * Both sections keep their switch disabled until the stored value is known, so a read that+ * fails leaves a dead knob under a value nobody read — and the page used to say so in a toast,+ * which is gone six seconds later while the knob stays dead (7.19's rule, app-wide: a refusal+ * lives where the control it is about lives). The failure is therefore handed back as a sentence+ * for the section to draw under the switch, the same slot these two switches already use for a+ * write the server refused.+ *+ * The read and the sentence live here rather than in each component so that both sections keep+ * doing it the same way, and so what a failed read becomes is one function with a test.+ */+import type { ServerSettingsResponse } from "@adelie/server/api";+import * as api from "../../api/endpoints";+import { refusalText } from "../../lib/api-error";+import { S } from "../../lib/strings";++/** The stored value of one switch, or why it could not be read. */+export type ServerSwitchRead =+ { status: "read"; value: boolean } | { status: "unread"; reason: string };++/**+ * Reads one switch out of the admin settings. A failure never throws: the section has nothing to+ * retry on its own — leaving and re-entering the page is the retry — so all it can do is say why.+ */+export async function readServerSwitch(+ pick: (settings: ServerSettingsResponse["settings"]) => boolean,+): Promise<ServerSwitchRead> {+ try {+ const res = await api.adminGetSettings();+ return { status: "read", value: pick(res.settings) };+ } catch (e: unknown) {+ return { status: "unread", reason: refusalText(e) };+ }+}++/** The line under the switch: why it is dead, already localized — null when the value was read. */+export function serverSwitchRefusal(read: ServerSwitchRead): string | null {+ return read.status === "unread" ? S.common.refused(read.reason) : null;+}diff --git a/packages/web/test/server-switch-read.test.ts b/packages/web/test/server-switch-read.test.tsnew file mode 100644index 00000000..5849db86--- /dev/null+++ b/packages/web/test/server-switch-read.test.ts@@ -0,0 +1,74 @@+/**+ * Reading one server-wide switch for its settings section (`readServerSwitch` /+ * `serverSwitchRefusal`): the Agent API and company-mode sections both keep their switch disabled+ * until a stored value arrives, so a failed read has to hand the section a sentence instead of+ * throwing — a toast would be gone six seconds later while the switch stays shut.+ *+ * - A read that lands hands back the value the pick chose, out of the settings the server sent.+ * - A server refusal comes back as the app's own sentence for that code, already behind the+ * shared "refused" lead-in — never the raw English message.+ * - A failure the client raised itself keeps its own sentence; one with nothing to say falls back+ * to the generic text.+ * - Nothing is thrown: `.then` runs even when the read failed.+ */+import { afterEach, describe, expect, it } from "vitest";+import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";+import { en as EN } from "../src/lib/strings-en";+import { readServerSwitch, serverSwitchRefusal } from "../src/features/settings/server-switch-read";+import { apiError, json, stubFetch } from "./helpers/fetch";++const serverSettings = (overrides: Record<string, unknown> = {}) =>+ json({ settings: { agentApiEnabled: true, companyMode: false, ...overrides } });++afterEach(() => {+ setActiveStrings(ZH);+});++describe("readServerSwitch", () => {+ it("hands back the one switch the pick chose", async () => {+ stubFetch(() => serverSettings({ agentApiEnabled: false, companyMode: true }));+ const agentApi = await readServerSwitch((settings) => settings.agentApiEnabled);+ const company = await readServerSwitch((settings) => settings.companyMode);+ expect(agentApi).toEqual({ status: "read", value: false });+ expect(company).toEqual({ status: "read", value: true });+ });++ it("answers a failed read with a sentence, not a throw", async () => {+ const fake = stubFetch(() => apiError(500, "internal", "RAW ENGLISH SERVER MESSAGE"));+ const read = await readServerSwitch((settings) => settings.agentApiEnabled);+ expect(read.status).toBe("unread");+ // Localized from the code, behind the shared lead-in — the raw message never reaches the reader.+ expect(serverSwitchRefusal(read)).toBe(S.common.refused(S.errors.byCode.internal));+ expect(serverSwitchRefusal(read)).not.toContain("RAW ENGLISH SERVER MESSAGE");+ expect(fake.requests.map((r) => r.path)).toEqual(["/api/admin/settings"]);+ });++ it("speaks English when the interface does", async () => {+ setActiveStrings(EN);+ stubFetch(() => apiError(404, "not_found"));+ const read = await readServerSwitch((settings) => settings.companyMode);+ expect(serverSwitchRefusal(read)).toBe(EN.common.refused(EN.errors.byCode.not_found));+ expect(serverSwitchRefusal(read)).not.toBe(ZH.common.refused(ZH.errors.byCode.not_found));+ });++ it("names a read that never reached the server as the client's network failure", async () => {+ stubFetch(() => {+ throw new TypeError("network down");+ });+ expect(serverSwitchRefusal(await readServerSwitch(() => true))).toBe(+ S.common.refused(S.errors.networkError),+ );+ });++ it("keeps a sentence the pick itself raised", () => {+ // The read lands, but taking the switch out of it is the caller's code — a body without the+ // field is a bug there, and what it says is still a sentence rather than a throw.+ expect(serverSwitchRefusal({ status: "unread", reason: "设置里没有这个开关" })).toBe(+ S.common.refused("设置里没有这个开关"),+ );+ });++ it("draws nothing once the value was read", () => {+ expect(serverSwitchRefusal({ status: "read", value: false })).toBeNull();+ });+});