A local-first multi-agent app development platform, built on PenguinHarness
fix(web): 上传限额读不出来时,原因留在两个输入框上面
lmlihengd8c1f6f80a06
diff --git a/changelog/unreleased/2026-11-02-uploads-read-refusal.md b/changelog/unreleased/2026-11-02-uploads-read-refusal.mdnew file mode 100644index 00000000..01709b30--- /dev/null+++ b/changelog/unreleased/2026-11-02-uploads-read-refusal.md@@ -0,0 +1,49 @@+# Upload limits that fail to load say why above their two fields++- **Date:** 2026-11-02+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文](2026-11-02-uploads-read-refusal.zh.md)++The two numbers on Settings → Server → Upload limits (max attachment size, max total per message) are+filled from what the server stores. A read that fails leaves both fields disabled and empty; the page+said so in a toast, which was gone six seconds later while the fields stayed dead and the page offered+no reason at all.++That reason is drawn above the two fields now — read first, because neither field below it represents+the server in that state. It uses 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. The page has no retry button of its own.++## Details++- `packages/web/src/features/settings/settings-read.ts` (renamed from last round's+ `server-switch-read.ts`): a third page now asks the same question, so the module is no longer about+ one switch — `readServerSettings(pick)` reads `GET /api/admin/settings` once and hands back whatever+ the pick took out of it (one boolean, or the pair this page is about), and a failure still comes back+ as `{ status: "unread", reason }` rather than a throw. `settingsReadRefusal(read)` turns the latter+ into the localized sentence (shared `refusalText()` behind the shared "refused" lead-in), or `null`.+- `packages/web/src/features/settings/uploads-section.tsx`: the whole-`settings` state narrows to+ `stored` — the pair this page is actually about — so `adopt()` takes just those two numbers; the read+ path no longer uses `toastError` and instead keeps a `loadRefusal` drawn above the two fields. The+ write path is untouched.+- `agent-api-section.tsx` and `company-section.tsx` only follow the rename (same function, same+ meaning).++## Tests++- `packages/web/test/settings-read.test.ts` (renamed from `server-switch-read.test.ts`, 8 cases): on top+ of last round's 6, two new ones — a pick that takes a pair of numbers out of the settings, and the same+ refusal sentence when a pair was asked for. What the pick returns and what a failed read says are each+ pinned by a case.+- `packages/web/e2e/uploads-read-refusal.spec.mjs` (new, one case on a real server): with the read+ refused — one sentence in the section, both fields disabled, no toast at all, still there after seven+ seconds; leaving the page and coming back (a remount is the retry) clears it, enables both fields and+ shows the server's 100 and 120.++## 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-uploads-read-refusal.zh.md b/changelog/unreleased/2026-11-02-uploads-read-refusal.zh.mdnew file mode 100644index 00000000..c7b1a62e--- /dev/null+++ b/changelog/unreleased/2026-11-02-uploads-read-refusal.zh.md@@ -0,0 +1,41 @@+# 上传限额读不出来时,原因留在两个输入框上面,不再只活六秒++- **日期:** 2026-11-02+- **类型:** fix+- **范围:** `web`+- **破坏性:** 无++[English](2026-11-02-uploads-read-refusal.md)++设置 →「服务器」→「上传限制」的两个数字(单个附件上限、单条消息附件合计上限)都要等服务端存着的值到达+才能填。一次读失败留下的是两个灰着、空着的输入框,而页面对此只说过一句六秒的通知:六秒后框还是灰着,+屏上没有任何理由。++现在那句话画在两个输入框上面 —— 先读到它,因为下面这两个数此刻不代表服务端。用的正是被拒的写入已经在+用的那一行:danger 色、`role="alert"`、限两行、整句挂悬停,并且一直留到离开这一页再回来:重新挂载即重新+拉取,那就是重试。这一页没有自己的重试按钮。++## 细节++- `packages/web/src/features/settings/settings-read.ts`(由上一轮的 `server-switch-read.ts` 改名):+ 第三个页面开始问同一个问题,于是模块不再只管「一个开关」—— `readServerSettings(pick)` 读一次+ `GET /api/admin/settings` 并把 pick 出来的那部分交回(一个布尔,或者这一页要的那对数),失败仍收成+ `{ status: "unread", reason }` 而从不抛出;`settingsReadRefusal(read)` 把后者变成本地化的那句(走共享的+ `refusalText()`,外面套共享的「被拒」引子),读到了就什么都不画。+- `packages/web/src/features/settings/uploads-section.tsx`:`settings`(整份设置)收成 `stored`(这一页+ 真正要的那对数),`adopt()` 因此只认这两个数;读那条路不再 `toastError`,改为多一个 `loadRefusal` 状态,+ 画在两个输入框上面。写的那条路一个字没动。+- `agent-api-section.tsx` 与 `company-section.tsx` 只跟着改名(同一个函数、同一个语义)。++## 测试++- `packages/web/test/settings-read.test.ts`(原 `server-switch-read.test.ts` 改名,8 条):除上一轮那 6 条+ 之外,新增「这一页要的是一对数」与「要一对数时读失败同样变成那句话」两条 —— pick 交回什么、失败时说的是+ 什么,各由一条用例钉住。+- `packages/web/e2e/uploads-read-refusal.spec.mjs`(新,真服务端一条):读被拒时 —— 句子在设置区里一条、+ 两个输入框都停用、完全没有 toast、七秒后仍在;离开这一页再回来(重新挂载即重试)后句子消失、两个框可用,+ 显示的是服务端存着的 100 与 120。++## 兼容++- 接口、请求与存储都没变:还是同一个 `GET /api/admin/settings`。改变的只有失败时那句话画在哪里。diff --git a/packages/web/e2e/uploads-read-refusal.spec.mjs b/packages/web/e2e/uploads-read-refusal.spec.mjsnew file mode 100644index 00000000..7c05cd64--- /dev/null+++ b/packages/web/e2e/uploads-read-refusal.spec.mjs@@ -0,0 +1,139 @@+/**+ * Regression: Settings → 服务器 → 上传限制 says why its two fields are dead when+ * `GET /api/admin/settings` fails, on the line above them, and that sentence outlives the six+ * seconds a toast lives.+ *+ * Both fields stay disabled until the stored numbers arrive, so a failed read leaves two dead+ * fields showing nothing — the page used to say so in a notification that dismissed itself,+ * leaving the fields 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 section is mounted only while it is 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 = "操作被拒绝:服务器内部错误,请稍后重试。";++/** The stored defaults, which is what the fields show once the read lands. */+const MAX_MB = 100;+const TOTAL_MB = 120;++/**+ * 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 section element holding the two fields, so the fields and their line are read together. */+function sectionOf(settings) {+ return settings.locator("section").filter({ hasText: "单条消息附件合计上限" });+}++/**+ * 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 upload limits say why they are dead, past the toast they 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);+ const maxField = section.getByLabel("单个附件上限(MB)");+ const totalField = section.getByLabel("单条消息附件合计上限(MB)");++ // The sentence, above the fields it left dead — once, and not as a notification over them.+ await expect(section.getByRole("alert")).toHaveText(REFUSED);+ await expect(section.getByRole("alert")).toHaveCount(1);+ await expect(maxField).toBeDisabled();+ await expect(totalField).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(maxField).toBeDisabled();+ await expect(totalField).toBeDisabled();++ // Leaving the page and coming back is the retry: the read lands, the sentence goes, both+ // fields open on what the server holds.+ 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.getByLabel("单个附件上限(MB)")).toBeEnabled();+ await expect(again.getByLabel("单条消息附件合计上限(MB)")).toBeEnabled();+ await expect(again.getByLabel("单个附件上限(MB)")).toHaveValue(String(MAX_MB));+ await expect(again.getByLabel("单条消息附件合计上限(MB)")).toHaveValue(String(TOTAL_MB));+ 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 3be1e6be..bf38f15f 100644--- a/packages/web/src/features/settings/agent-api-section.tsx+++ b/packages/web/src/features/settings/agent-api-section.tsx@@ -19,7 +19,7 @@ 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";+import { readServerSettings, settingsReadRefusal } from "./settings-read";/** Turns the switch off on the server. Reached only through the confirm. */const switchOffAgentApiServer = (): Promise<ServerSettingsResponse> =>@@ -82,13 +82,13 @@ export function AgentApiSection() {useEffect(() => {let cancelled = false;- void readServerSwitch((settings) => settings.agentApiEnabled).then((read) => {+ void readServerSettings((settings) => settings.agentApiEnabled).then((read) => {if (cancelled) return;if (read.status === "read") {setStored(read.value);setEnabled(read.value);} else {- setLoadRefusal(serverSwitchRefusal(read));+ setLoadRefusal(settingsReadRefusal(read));}});return () => {diff --git a/packages/web/src/features/settings/company-section.tsx b/packages/web/src/features/settings/company-section.tsxindex 4eb69352..f647a38e 100644--- a/packages/web/src/features/settings/company-section.tsx+++ b/packages/web/src/features/settings/company-section.tsx@@ -22,7 +22,7 @@ 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";+import { readServerSettings, settingsReadRefusal } from "./settings-read";export function CompanySection() {const { refresh } = useAuth();@@ -37,13 +37,13 @@ export function CompanySection() {useEffect(() => {let cancelled = false;- void readServerSwitch((settings) => settings.companyMode).then((read) => {+ void readServerSettings((settings) => settings.companyMode).then((read) => {if (cancelled) return;if (read.status === "read") {setStored(read.value);setCompanyMode(read.value);} else {- setLoadRefusal(serverSwitchRefusal(read));+ setLoadRefusal(settingsReadRefusal(read));}});return () => {diff --git a/packages/web/src/features/settings/server-switch-read.ts b/packages/web/src/features/settings/server-switch-read.tsdeleted file mode 100644index ab4e8c09..00000000--- a/packages/web/src/features/settings/server-switch-read.ts+++ /dev/null@@ -1,42 +0,0 @@-/**- * 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/src/features/settings/settings-read.ts b/packages/web/src/features/settings/settings-read.tsnew file mode 100644index 00000000..932de9f1--- /dev/null+++ b/packages/web/src/features/settings/settings-read.ts@@ -0,0 +1,43 @@+/**+ * Reading what a Settings page hydrates from `GET /api/admin/settings` — one switch, a pair of+ * limits, anything that page is about — and, when that read fails, the sentence saying so.+ *+ * Every such page keeps its controls disabled until the stored value arrives, so a read that+ * fails leaves dead controls under values nobody read — and the page used to say so in a toast,+ * which is gone six seconds later while the controls stay dead (7.19's rule, app-wide: a refusal+ * lives where the thing it is about lives). The failure is therefore handed back as a sentence+ * for the page to draw where its controls are, the same slot the write-side refusals use.+ *+ * What this page asks for is a `pick` over the settings rather than a field name, so the same+ * module serves a switch (Agent API, company mode) and a form of several numbers (upload limits)+ * without either page re-deriving its own read. A failed read never throws: these pages have+ * nothing to retry on their own — leaving and re-entering the page is the retry — so all they can+ * do is say why.+ *+ * The read and the sentence live here rather than in each component so that every page keeps+ * 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";++/** What one page takes out of the stored settings, or why it could not be read. */+export type SettingsRead<T> = { status: "read"; value: T } | { status: "unread"; reason: string };++/** Reads the admin settings once and hands back the `pick`ed part of them. */+export async function readServerSettings<T>(+ pick: (settings: ServerSettingsResponse["settings"]) => T,+): Promise<SettingsRead<T>> {+ 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 controls: why they are dead, already localized — null when the read landed. */+export function settingsReadRefusal(read: SettingsRead<unknown>): string | null {+ return read.status === "unread" ? S.common.refused(read.reason) : null;+}diff --git a/packages/web/src/features/settings/uploads-section.tsx b/packages/web/src/features/settings/uploads-section.tsxindex 91be2119..5bbe3513 100644--- a/packages/web/src/features/settings/uploads-section.tsx+++ b/packages/web/src/features/settings/uploads-section.tsx@@ -9,22 +9,39 @@* that goes stale. A value outside it is refused by the server with `invalid_attachment_limit`* and rendered inline under the field, the same way the proxy section handles a bad address.*+ * Both fields stay disabled until the stored numbers arrive, so a read that fails leaves two dead+ * fields showing nothing — which is why the reason is drawn above them rather than in a toast that+ * dismisses itself: the reader has to be told why, and leaving the page and coming back is the+ * retry (`readServerSettings`).+ ** Saving takes effect immediately — the attachment validators and the request body cap both* read the setting per request — so there is nothing to restart and nothing to warn about.*/import { useEffect, useState } from "react";-import type { ServerSettings } from "@adelie/server/api";import { Button, Input, SettingsSection, toastError, toastInfo, toastSuccess } from "@adelie/ui";import * as api from "../../api/endpoints";import { ApiError } from "../../api/client";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";+import { toneInk } from "../../lib/tone";import { useAuth } from "../../state/auth";+import { readServerSettings, settingsReadRefusal } from "./settings-read";++/** The two numbers this page is about, as they are stored. */+interface StoredLimits {+ maxMb: number;+ totalMb: number;+}++const limitsOf = (settings: {+ attachmentMaxMb: number;+ attachmentTotalMb: number;+}): StoredLimits => ({ maxMb: settings.attachmentMaxMb, totalMb: settings.attachmentTotalMb });export function UploadsSection() {const { uploadLimits, refresh } = useAuth();- /** Stored settings as hydrated on mount (null until then) — the no-change baseline. */- const [settings, setSettings] = useState<ServerSettings | null>(null);+ /** Stored limits as hydrated on mount (null until then) — the no-change baseline. */+ const [stored, setStored] = useState<StoredLimits | null>(null);// Kept as strings: a number input that clears to NaN cannot be typed into (backspacing the// last digit would snap the field back to a value the user is in the middle of replacing).const [maxMb, setMaxMb] = useState("");@@ -38,33 +55,31 @@ export function UploadsSection() {max: boolean;total: boolean;} | null>(null);+ /** Why the settings could not be read, drawn above the fields it left dead (null once read). */+ const [loadRefusal, setLoadRefusal] = useState<string | null>(null);const [busy, setBusy] = useState(false);/** Adopt server-side truth: the baseline and the drafts move together. */- const adopt = (next: ServerSettings) => {- setSettings(next);- setMaxMb(String(next.attachmentMaxMb));- setTotalMb(String(next.attachmentTotalMb));+ const adopt = (next: StoredLimits) => {+ setStored(next);+ setMaxMb(String(next.maxMb));+ setTotalMb(String(next.totalMb));};useEffect(() => {let cancelled = false;- void api- .adminGetSettings()- .then((res) => {- if (!cancelled) adopt(res.settings);- })- .catch((e: unknown) => {- // Controls stay disabled; leaving and returning to the section retries the fetch.- if (!cancelled) toastError(apiErrorText(e));- });+ void readServerSettings(limitsOf).then((read) => {+ if (cancelled) return;+ if (read.status === "read") adopt(read.value);+ else setLoadRefusal(settingsReadRefusal(read));+ });return () => {cancelled = true;};}, []);const save = async () => {- if (settings === null || busy) return;+ if (stored === null || busy) return;const parsedMax = Number(maxMb.trim());const parsedTotal = Number(totalMb.trim());// Shape-check locally so an empty or non-numeric field never becomes a NaN in the request@@ -79,7 +94,7 @@ export function UploadsSection() {});return;}- if (parsedMax === settings.attachmentMaxMb && parsedTotal === settings.attachmentTotalMb) {+ if (parsedMax === stored.maxMb && parsedTotal === stored.totalMb) {toastInfo(S.common.noChangesToSave);return;}@@ -90,7 +105,7 @@ export function UploadsSection() {attachmentMaxMb: parsedMax,attachmentTotalMb: parsedTotal,});- adopt(res.settings);+ adopt(limitsOf(res.settings));// The composer reads the limits from /api/me, so re-pull them: without this the tab that// just raised the cap would keep refusing files at the old number until the next reload.await refresh().catch(() => {});@@ -106,7 +121,7 @@ export function UploadsSection() {}};- const hydrated = settings !== null;+ const hydrated = stored !== null;return (<SettingsSectionactions={@@ -120,6 +135,18 @@ export function UploadsSection() {</Button>}>+ {/* Why the two fields are dead: the read failed, so neither holds a stored number. Drawn+ first, because the fields below it do not represent the server in this state. */}+ {loadRefusal !== null && (+ <p+ role="alert"+ data-tooltip={loadRefusal}+ data-tooltip-content="text"+ className={`line-clamp-2 break-words text-xs ${toneInk.danger}`}+ >+ {loadRefusal}+ </p>+ )}<Inputlabel={S.settings.attachmentMaxMb}requireddiff --git a/packages/web/test/server-switch-read.test.ts b/packages/web/test/server-switch-read.test.tsdeleted file mode 100644index 5849db86..00000000--- a/packages/web/test/server-switch-read.test.ts+++ /dev/null@@ -1,74 +0,0 @@-/**- * 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();- });-});diff --git a/packages/web/test/settings-read.test.ts b/packages/web/test/settings-read.test.tsnew file mode 100644index 00000000..6eb96040--- /dev/null+++ b/packages/web/test/settings-read.test.ts@@ -0,0 +1,102 @@+/**+ * Reading what a settings page hydrates from `GET /api/admin/settings` (`readServerSettings` /+ * `settingsReadRefusal`): the Agent API and company-mode switches and the upload-limits form all+ * keep their controls disabled until a stored value arrives, so a failed read has to hand the page+ * a sentence instead of throwing — a toast would be gone six seconds later while the controls+ * stay dead.+ *+ * - A read that lands hands back whatever the pick chose out of the settings the server sent —+ * one switch, or the pair of numbers the limits form is about.+ * - 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 { readServerSettings, settingsReadRefusal } from "../src/features/settings/settings-read";+import { apiError, json, stubFetch } from "./helpers/fetch";++const serverSettings = (overrides: Record<string, unknown> = {}) =>+ json({+ settings: {+ agentApiEnabled: true,+ companyMode: false,+ attachmentMaxMb: 25,+ attachmentTotalMb: 100,+ ...overrides,+ },+ });++afterEach(() => {+ setActiveStrings(ZH);+});++describe("readServerSettings", () => {+ it("hands back the one switch the pick chose", async () => {+ stubFetch(() => serverSettings({ agentApiEnabled: false, companyMode: true }));+ const agentApi = await readServerSettings((settings) => settings.agentApiEnabled);+ const company = await readServerSettings((settings) => settings.companyMode);+ expect(agentApi).toEqual({ status: "read", value: false });+ expect(company).toEqual({ status: "read", value: true });+ });++ it("hands back the pair of numbers the limits form is about", async () => {+ stubFetch(() => serverSettings({ attachmentMaxMb: 40, attachmentTotalMb: 160 }));+ const read = await readServerSettings((settings) => ({+ maxMb: settings.attachmentMaxMb,+ totalMb: settings.attachmentTotalMb,+ }));+ expect(read).toEqual({ status: "read", value: { maxMb: 40, totalMb: 160 } });+ });++ 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 readServerSettings((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(settingsReadRefusal(read)).toBe(S.common.refused(S.errors.byCode.internal));+ expect(settingsReadRefusal(read)).not.toContain("RAW ENGLISH SERVER MESSAGE");+ expect(fake.requests.map((r) => r.path)).toEqual(["/api/admin/settings"]);+ });++ it("answers a failed read the same way when several values were asked for", async () => {+ stubFetch(() => apiError(500, "internal"));+ const read = await readServerSettings((settings) => ({+ maxMb: settings.attachmentMaxMb,+ totalMb: settings.attachmentTotalMb,+ }));+ expect(settingsReadRefusal(read)).toBe(S.common.refused(S.errors.byCode.internal));+ });++ it("speaks English when the interface does", async () => {+ setActiveStrings(EN);+ stubFetch(() => apiError(404, "not_found"));+ const read = await readServerSettings((settings) => settings.companyMode);+ expect(settingsReadRefusal(read)).toBe(EN.common.refused(EN.errors.byCode.not_found));+ expect(settingsReadRefusal(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(settingsReadRefusal(await readServerSettings(() => true))).toBe(+ S.common.refused(S.errors.networkError),+ );+ });++ it("keeps a sentence the pick itself raised", () => {+ // The read lands, but taking the value 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(settingsReadRefusal({ status: "unread", reason: "设置里没有这个开关" })).toBe(+ S.common.refused("设置里没有这个开关"),+ );+ });++ it("draws nothing once the value was read", () => {+ expect(settingsReadRefusal({ status: "read", value: false })).toBeNull();+ });+});