Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

fix(web): Agent 的 API 页里写不进去时,原因留在按下去的那个控件下面

lmliheng0797c368bcc6
diff --git a/changelog/unreleased/2026-11-08-api-write-refusal.md b/changelog/unreleased/2026-11-08-api-write-refusal.md
new file mode 100644
index 00000000..a1dbad09
--- /dev/null
+++ b/changelog/unreleased/2026-11-08-api-write-refusal.md
@@ -0,0 +1,59 @@
+# A refused write in the Agent's API tab says why under the switch or the select that asked
+
+- **Date:** 2026-11-08
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[中文](2026-11-08-api-write-refusal.zh.md)
+
+The API tab has three writes that apply on the press with no question first: turning the API on, the
+approval mode its conversations start with, and turning keyless access off. None of the three
+controls moves optimistically — the switch and the select show the position the server answered
+with — so a refused write left the tab looking exactly as it had before the press. The one sentence
+that explained it arrived as a notification that dismissed itself after six seconds; after that the
+control simply looked as if it had been pressed and come back.
+
+That is the shape 7.19 bans, and on this tab it costs the most: a keyless-off that did not land
+leaves anything that can reach the address calling the Agent without a key, while the switch the
+reader just pressed reads "off" in their memory.
+
+Each of the three now keeps its reason under its own control, with `role="alert"`, the danger colour
+and the whole sentence wrapping, until that control is used again — the switch and the select are
+the retry. The three sentences say different things on purpose: the API is still off; the approval
+mode was not changed, naming the mode that was asked for because the select fell back to the stored
+one; and keyless access is still open.
+
+## Details
+
+- `packages/web/src/features/agents/api-write-refusal.ts` (new): `apiEnabledRefused(err)`,
+ `apiApprovalModeRefused(mode, err)` and `apiKeylessOffRefused(err)`. The reason goes through
+ `refusalText` (7.19's rule: an answer the server gave is read through its code's own localized
+ sentence, never the English wire message), and the approval-mode sentence resolves the mode's
+ display name itself, so the sentence reads the same in both languages.
+- `packages/web/src/features/agents/api-tab.tsx`: `write()` hands a refused write back to the
+ control that asked for it instead of a notification; the three slots are cleared when that control
+ is pressed again; `ApiTabView` draws one `role="alert"` line under the switch, under the approval
+ select and under the keyless switch. The import of `toastError` is gone from this file.
+- `packages/web/src/lib/strings{,-en}.ts`: three new sentences, `agent.apiEnableRefused(reason)`,
+ `agent.apiApprovalModeRefused(mode, reason)` and `agent.apiKeylessOffRefused(reason)`.
+
+## Tests
+
+- `packages/web/test/api-write-refusal.test.ts` (new, 9 cases): each sentence keeps the server's
+ reason read through its code (never the wire message), keeps a sentence the interface raised
+ itself, falls back to the generic text when there is nothing to say, says the API is still off /
+ keyless access is still open, and names the mode that was asked for — in both languages.
+- `packages/web/test/agent-api-tab.test.ts` (+1 render case): three alerts, each in its own place,
+ and none at all when nothing was refused.
+- `packages/web/e2e/agent-api-write-refusal.spec.mjs` (new, real server + real browser): each write
+ is refused at `page.route` and read back from the server through the API. The sentence appears
+ once, in the interface's words, the notification region stays empty, the control stays in its old
+ position and the server stored nothing — and **seven seconds later** the sentence is still there.
+ Pressing the same control again with the write allowed clears it and lands the change.
+
+## Compatibility
+
+No interface change, no new dependency, no Project config change. The three confirmations that ask
+first (turn the API off, allow keyless access, delete a key) keep their refusal inside the card, and
+their spec still passes unchanged.
diff --git a/changelog/unreleased/2026-11-08-api-write-refusal.zh.md b/changelog/unreleased/2026-11-08-api-write-refusal.zh.md
new file mode 100644
index 00000000..4943415a
--- /dev/null
+++ b/changelog/unreleased/2026-11-08-api-write-refusal.zh.md
@@ -0,0 +1,48 @@
+# Agent 的 API 页里写不进去时,原因留在按下去的那个开关或下拉下面
+
+- **日期:** 2026-11-08
+- **类型:** 修复
+- **范围:** `web`
+- **破坏性变更:** 无
+
+[English](2026-11-08-api-write-refusal.md)
+
+API 页有三处写是不问就写的:打开 API、API 会话的审批模式、关掉无密钥访问。这三个控件都不做
+乐观更新 —— 开关与下拉显示的是服务端答复的位置 —— 所以一次被拒的写之后,页面与按下之前一模一样。
+唯一解释它的那句话在六秒后自己消失的通知里;此后那个控件看上去就像按了一下又弹回来了。
+
+这正是 7.19 禁止的形状,而在这张页面上它的代价最大:没关掉的无密钥访问意味着任何能访问这个地址
+的程序都能无密钥调用这个 Agent,而读者记忆里那个开关还停在「已关」。
+
+这三处现在各自把原因留在自己的控件下面:`role="alert"`、危险色、整句换行,一直留到这个控件再次
+被使用为止 —— 开关和下拉自己就是重试。三句话故意说得不一样:API 仍然没有打开;审批方式没有改,
+并念出被要求的那一档(因为下拉已经退回存着的那一档);以及无密钥访问仍然开着。
+
+## 细节
+
+- 新增 `packages/web/src/features/agents/api-write-refusal.ts`:`apiEnabledRefused(err)`、
+ `apiApprovalModeRefused(mode, err)` 与 `apiKeylessOffRefused(err)`。原因走 `refusalText`
+ (7.19 的规则:服务端答复的按错误码念界面自己的本地化句子,不念线上英文原文);审批模式那一句
+ 自己解析模式的显示名,所以中英文读起来都是界面的话。
+- `packages/web/src/features/agents/api-tab.tsx`:`write()` 把被拒的写交还给按下它的那个控件,
+ 不再交给人一眼看不见的通知;三个槽位在该控件再次按下时先清掉;`ApiTabView` 在开关下、审批下拉下
+ 与无密钥开关下各画一条 `role="alert"` 行,这个文件不再引用 `toastError`。
+- `packages/web/src/lib/strings{,-en}.ts`:三条新文案 `agent.apiEnableRefused(reason)`、
+ `agent.apiApprovalModeRefused(mode, reason)` 与 `agent.apiKeylessOffRefused(reason)`。
+
+## 测试
+
+- `packages/web/test/api-write-refusal.test.ts`(新增,9 条):三句话都保留服务端的原因但按错误码
+ 念(绝不念线上原文)、保留界面自己抛出的句子、什么都没说时落到通用文案、明说「API 仍然没打开」与
+ 「无密钥访问仍然开着」、并念出被要求的那一档审批方式 —— 中英双语各一条。
+- `packages/web/test/agent-api-tab.test.ts`(+1 条渲染断言):三条 `role="alert"` 各在各的位置,
+ 没有被拒时一条都不画。
+- `packages/web/e2e/agent-api-write-refusal.spec.mjs`(新增,真服务端 + 真浏览器):三处写都在
+ `page.route` 上被拒,并且再从 API 读回服务端的状态。句子只出现一次、念的是界面的话、通知区为空、
+ 控件停在原位、服务端什么都没写 —— 而且**七秒之后**那句话还留着。放行后按同一个控件,句子消失、
+ 改动落地。
+
+## 兼容性
+
+不改接口、不引入新依赖、不改 Project 配置。三处先问再写的确认框(关掉 API、允许无密钥访问、
+删除密钥)仍然把拒绝画在卡片里,它们那一份 spec 原样通过。
diff --git a/packages/web/e2e/agent-api-write-refusal.spec.mjs b/packages/web/e2e/agent-api-write-refusal.spec.mjs
new file mode 100644
index 00000000..349b65c5
--- /dev/null
+++ b/packages/web/e2e/agent-api-write-refusal.spec.mjs
@@ -0,0 +1,212 @@
+/**
+ * Regression: the API tab's three writes that ask nothing first — turning the API on, the approval
+ * mode its conversations start with, and turning keyless access off — draw a refusal under the
+ * control that asked for it, and it stays there.
+ *
+ * None of these controls moves optimistically: the switch and the select show what the server
+ * answered with, so a refused write leaves the tab exactly as it was. The reason used to arrive as
+ * a notification that dismissed itself after six seconds, which left the control looking as if it
+ * had been pressed and come back with nothing on screen explaining why — and the worst of the three
+ * is keyless access: a refused off leaves anything that can reach the address calling the Agent
+ * without a key.
+ *
+ * Every write is refused at `page.route`, and every check reads the server through the API as
+ * well, so the sentence and the server's own state are both covered.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const P = "password123";
+const AGENT = "default_agent";
+
+/** The refusal the stubbed route answers with: its own code resolves to the interface's sentence. */
+const REFUSAL = { code: "internal", message: "RAW ENGLISH SERVER MESSAGE" };
+/** What that code says in Chinese — the interface's words, never the wire message above. */
+const REASON = "服务器内部错误,请稍后重试。";
+
+const apiUrl = (projectId) => `${BASE}/api/projects/${projectId}/agents/${AGENT}/api`;
+
+/**
+ * Provision the user, give the Project a model (the onboarding overlay covers the page without
+ * one), and put the Agent's API in a known state. The write is absolute, so rerunning this file
+ * alone on one data root stays clean.
+ */
+async function projectWithApi(page, user, state) {
+ await provisionAndLogin(page.request, user, P);
+ const projectId = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0]
+ .projectId;
+ const models = 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(models.ok(), "put models").toBeTruthy();
+
+ const written = await page.request.put(apiUrl(projectId), { data: state });
+ expect(written.ok(), "put the API state").toBeTruthy();
+
+ /** The Agent's API as the server holds it: what the tab reads and writes back. */
+ const stored = async () => (await (await page.request.get(apiUrl(projectId))).json()).api;
+ return { projectId, stored };
+}
+
+/**
+ * Take over one write: every request of that method is kept in `seen`, and while `state.refuse`
+ * is set it is answered with the server's refusal instead of reaching the real route.
+ */
+async function interceptWrite(page, pattern, method, state) {
+ await page.route(pattern, async (route) => {
+ if (route.request().method() !== method) 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 }),
+ });
+ });
+}
+
+/** 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 API-on keeps the reason under the switch, and the API off", async ({ page }) => {
+ const { stored } = await projectWithApi(page, "r209on", {
+ enabled: false,
+ open: false,
+ approvalMode: "read-only",
+ });
+ expect((await stored()).enabled).toBe(false);
+
+ const state = { seen: [], refuse: true };
+ await interceptWrite(page, "**/api/projects/*/agents/*/api", "PUT", state);
+
+ await page.goto(`/agents/${AGENT}?tab=api`);
+ const apiSwitch = page.getByRole("switch", { name: "开启 API 访问" });
+ await expect(apiSwitch).toHaveAttribute("aria-checked", "false");
+ await apiSwitch.click();
+
+ // The reason is under the switch, in the interface's words, and only once.
+ const line = page.getByRole("alert");
+ await expect(line).toHaveCount(1);
+ await expect(line).toHaveText(`API 访问没有打开,外部程序仍然无法调用:${REASON}`);
+ await expect(notifications(page).getByRole("button")).toHaveCount(0);
+ expect(state.seen).toHaveLength(1);
+ expect(JSON.parse(state.seen[0])).toEqual({ enabled: true });
+
+ // The switch never flipped and the server still has the API off.
+ await expect(apiSwitch).toHaveAttribute("aria-checked", "false");
+ expect((await stored()).enabled).toBe(false);
+
+ // Seven seconds later (the toast would be long gone) the sentence is still there.
+ await page.waitForTimeout(7000);
+ await expect(line).toHaveText(`API 访问没有打开,外部程序仍然无法调用:${REASON}`);
+
+ // The switch is the retry: allowed now, the sentence goes and the API comes on.
+ state.refuse = false;
+ await apiSwitch.click();
+ await expect(page.getByRole("alert")).toHaveCount(0);
+ expect(state.seen).toHaveLength(2);
+ await expect(apiSwitch).toHaveAttribute("aria-checked", "true");
+ expect((await stored()).enabled).toBe(true);
+ await expect(page.getByText("API 会话的审批模式")).toBeVisible();
+});
+
+test("a refused approval-mode change names the mode asked for, under the select", async ({
+ page,
+}) => {
+ const { stored } = await projectWithApi(page, "r209mode", {
+ enabled: true,
+ open: false,
+ approvalMode: "read-only",
+ });
+ expect((await stored()).approvalMode).toBe("read-only");
+
+ const state = { seen: [], refuse: true };
+ await interceptWrite(page, "**/api/projects/*/agents/*/api", "PUT", state);
+
+ await page.goto(`/agents/${AGENT}?tab=api`);
+ // The trigger reads the stored mode (the custom select draws a button, not a real <select>).
+ const trigger = page.getByRole("button", { name: /审批模式/ });
+ await expect(trigger).toContainText("放行只读");
+ await trigger.click();
+ await page.getByRole("option", { name: "总是询问" }).click();
+
+ const line = page.getByRole("alert");
+ await expect(line).toHaveCount(1);
+ await expect(line).toHaveText(`审批方式没有改成「总是询问」:${REASON}`);
+ await expect(notifications(page).getByRole("button")).toHaveCount(0);
+ expect(state.seen).toHaveLength(1);
+ expect(JSON.parse(state.seen[0])).toEqual({ approvalMode: "always-ask" });
+
+ // The select fell back to the stored mode, and so did the server.
+ await expect(page.getByRole("button", { name: /审批模式/ })).toContainText("放行只读");
+ expect((await stored()).approvalMode).toBe("read-only");
+
+ await page.waitForTimeout(7000);
+ await expect(line).toHaveText(`审批方式没有改成「总是询问」:${REASON}`);
+
+ // The select is the retry.
+ state.refuse = false;
+ await page.getByRole("button", { name: /审批模式/ }).click();
+ await page.getByRole("option", { name: "总是询问" }).click();
+ await expect(page.getByRole("alert")).toHaveCount(0);
+ expect(state.seen).toHaveLength(2);
+ await expect(page.getByRole("button", { name: /审批模式/ })).toContainText("总是询问");
+ expect((await stored()).approvalMode).toBe("always-ask");
+});
+
+test("a refused keyless-off says the access is still open, under that switch", async ({ page }) => {
+ const { stored } = await projectWithApi(page, "r209open", {
+ enabled: true,
+ open: true,
+ approvalMode: "read-only",
+ });
+ expect((await stored()).open).toBe(true);
+
+ const state = { seen: [], refuse: true };
+ await interceptWrite(page, "**/api/projects/*/agents/*/api", "PUT", state);
+
+ await page.goto(`/agents/${AGENT}?tab=api`);
+ const openSwitch = page.getByRole("switch", { name: "允许无密钥访问" });
+ await expect(openSwitch).toHaveAttribute("aria-checked", "true");
+ // Turning keyless off asks nothing: it is the write with no card, so its sentence goes under it.
+ await openSwitch.click();
+
+ const line = page.getByRole("alert");
+ await expect(line).toHaveCount(1);
+ await expect(line).toHaveText(
+ `无密钥访问没有关掉,任何能访问此地址的程序仍然无需密钥就能调用:${REASON}`,
+ );
+ await expect(notifications(page).getByRole("button")).toHaveCount(0);
+ expect(state.seen).toHaveLength(1);
+ expect(JSON.parse(state.seen[0])).toEqual({ open: false });
+
+ // The exposure the press tried to close is still open, here and on the server.
+ await expect(openSwitch).toHaveAttribute("aria-checked", "true");
+ expect((await stored()).open).toBe(true);
+
+ await page.waitForTimeout(7000);
+ await expect(line).toHaveText(
+ `无密钥访问没有关掉,任何能访问此地址的程序仍然无需密钥就能调用:${REASON}`,
+ );
+
+ // The switch is the retry: allowed now, the sentence goes and keyless access closes.
+ state.refuse = false;
+ await openSwitch.click();
+ await expect(page.getByRole("alert")).toHaveCount(0);
+ expect(state.seen).toHaveLength(2);
+ await expect(openSwitch).toHaveAttribute("aria-checked", "false");
+ expect((await stored()).open).toBe(false);
+});
diff --git a/packages/web/src/features/agents/api-tab.tsx b/packages/web/src/features/agents/api-tab.tsx
index 7a0b273d..4ca95bc5 100644
--- a/packages/web/src/features/agents/api-tab.tsx
+++ b/packages/web/src/features/agents/api-tab.tsx
@@ -9,9 +9,12 @@
* Save: turning the API on writes at once, while turning it off and deleting a key ask first,
* because a program using them is refused from then on. Those three questions close only once
* their write landed; one the server refused keeps the card open with the reason drawn inside it,
- * so the retry is the button that was just pressed rather than a toast that has already left. A
- * new key's secret exists only in the create response: it is shown once, in a panel with its copy
- * button, until Done, and afterwards the list names the key by its prefix alone.
+ * so the retry is the button that was just pressed rather than a toast that has already left. The
+ * writes that ask nothing first (turning the API on, the approval mode, turning keyless access off)
+ * have no card to keep a reason in, so theirs is drawn under the switch or the select that made it
+ * — which never moved, and is the retry. A new key's secret exists only in the create response: it
+ * is shown once, in a panel with its copy button, until Done, and afterwards the list names the key
+ * by its prefix alone.
*
* The admin's server-wide switch (Settings › Server › Agent API) overrides every Agent: when it is
* off the switch here is disabled and says so, and nothing is lost. The tab's own read carries that
@@ -42,7 +45,6 @@ import {
Select,
SkeletonList,
ToggleRow,
- toastError,
} from "@adelie/ui";
import * as api from "../../api/endpoints";
import { apiErrorText } from "../../lib/api-error";
@@ -51,6 +53,11 @@ import { S } from "../../lib/strings";
import { toneInk } from "../../lib/tone";
import { useProject } from "../../state/project";
import { APPROVAL_MODES } from "../chat/approval-mode";
+import {
+ apiApprovalModeRefused,
+ apiEnabledRefused,
+ apiKeylessOffRefused,
+} from "./api-write-refusal";
import { ApiTryPanel } from "./api-try-panel";
/** The public API's root on the server this page was served from. */
@@ -335,6 +342,12 @@ export interface ApiTabViewProps {
draftError?: string;
/** A just-created key's secret, until Done; null otherwise. */
secret: string | null;
+ /** The switch's own refusal, drawn under it: the API is still off and the switch is the retry. */
+ enableRefusal?: string;
+ /** The select's refusal, naming the mode asked for: the select is back on the stored mode. */
+ approvalRefusal?: string;
+ /** The keyless switch's refusal: keyless access is still open, and the switch is the retry. */
+ keylessOffRefusal?: string;
onToggleEnabled: (next: boolean) => void;
onApprovalMode: (mode: ApprovalMode) => void;
onToggleOpen: (next: boolean) => void;
@@ -365,6 +378,11 @@ export function ApiTabView(p: ApiTabViewProps) {
onChange={p.onToggleEnabled}
disabled={!p.isOwner || serverOff || p.busy}
/>
+ {p.enableRefusal !== undefined && (
+ <p role="alert" className={`text-xs break-words ${toneInk.danger}`}>
+ {p.enableRefusal}
+ </p>
+ )}
{serverOff && <p className="text-xs text-fg-muted">{S.agent.apiAdminOff}</p>}
{!p.isOwner && <p className="text-xs text-fg-muted">{S.agent.apiOwnerOnly}</p>}
</div>
@@ -390,6 +408,11 @@ export function ApiTabView(p: ApiTabViewProps) {
</option>
))}
</Select>
+ {p.approvalRefusal !== undefined && (
+ <p role="alert" className={`mt-1 text-xs break-words ${toneInk.danger}`}>
+ {p.approvalRefusal}
+ </p>
+ )}
</div>
<RuledSection title={S.agent.apiConnection}>
@@ -457,6 +480,11 @@ export function ApiTabView(p: ApiTabViewProps) {
disabled={!p.isOwner || p.busy}
/>
<p className={`text-xs ${toneInk.attention}`}>{S.agent.apiOpenHint}</p>
+ {p.keylessOffRefusal !== undefined && (
+ <p role="alert" className={`text-xs break-words ${toneInk.danger}`}>
+ {p.keylessOffRefusal}
+ </p>
+ )}
</div>
</RuledSection>
@@ -491,9 +519,9 @@ export function ApiTab({
}) {
const { reloadAgents } = useProject();
const [settings, setSettings] = useState<AgentApiSettings | null>(null);
- // Only the initial load failure renders inline; a write with no question of its own (turning the
- // API on, the approval mode, keyless off) reports via toast; a write asked for in a card reports
- // inside that card (the three refusals below).
+ // Only the initial load failure renders inline; a write with no question of its own reports under
+ // the control that asked for it; a write asked for in a card reports inside that card (the three
+ // refusals below).
const [loadError, setLoadError] = useState<string | null>(null);
const [serverEnabled, setServerEnabled] = useState(true);
const [busy, setBusy] = useState(false);
@@ -505,6 +533,11 @@ export function ApiTab({
const [offRefusal, setOffRefusal] = useState<string | null>(null);
const [keylessRefusal, setKeylessRefusal] = useState<string | null>(null);
const [deleteRefusal, setDeleteRefusal] = useState<string | null>(null);
+ // The same reason for the three writes no card holds: each stays under its own control, which is
+ // still in its old position and is the retry.
+ const [enableRefusal, setEnableRefusal] = useState<string | null>(null);
+ const [approvalRefusal, setApprovalRefusal] = useState<string | null>(null);
+ const [keylessOffRefusal, setKeylessOffRefusal] = useState<string | null>(null);
const [draftName, setDraftName] = useState<string | null>(null);
const [draftError, setDraftError] = useState<string | undefined>(undefined);
const [secret, setSecret] = useState<string | null>(null);
@@ -528,9 +561,12 @@ export function ApiTab({
};
}, [projectId, agentId]);
- /** One settings write: the stored answer replaces the view, a failure says why. */
+ /**
+ * One settings write that asks nothing first: the stored answer replaces the view, and a refused
+ * one is handed back to the control that asked for it, where it stays.
+ */
const write = useCallback(
- async (patch: AgentApiUpdateRequest) => {
+ async (patch: AgentApiUpdateRequest, refused: (error: unknown) => void) => {
setBusy(true);
try {
const res = await api.putAgentApi(projectId, agentId, patch);
@@ -539,7 +575,7 @@ export function ApiTab({
// The Agents list marks an Agent whose API is on.
if (patch.enabled !== undefined) void reloadAgents();
} catch (e) {
- toastError(apiErrorText(e));
+ refused(e);
} finally {
setBusy(false);
}
@@ -584,21 +620,35 @@ export function ApiTab({
draftName={draftName}
{...(draftError !== undefined ? { draftError } : {})}
secret={secret}
+ {...(enableRefusal !== null ? { enableRefusal } : {})}
+ {...(approvalRefusal !== null ? { approvalRefusal } : {})}
+ {...(keylessOffRefusal !== null ? { keylessOffRefusal } : {})}
onToggleEnabled={(next) => {
- if (next) void write({ enabled: true });
- else {
+ if (next) {
+ // The press that follows is the retry, so the sentence from the last one goes first.
+ setEnableRefusal(null);
+ void write({ enabled: true }, (e) => setEnableRefusal(apiEnabledRefused(e)));
+ } else {
// Open first, then drop the previous refusal: that sentence belonged to the attempt
// before this one.
setConfirmOff(true);
setOffRefusal(null);
}
}}
- onApprovalMode={(approvalMode) => void write({ approvalMode })}
+ onApprovalMode={(approvalMode) => {
+ setApprovalRefusal(null);
+ void write({ approvalMode }, (e) =>
+ setApprovalRefusal(apiApprovalModeRefused(approvalMode, e)),
+ );
+ }}
onToggleOpen={(open) => {
if (open) {
setConfirmKeyless(true);
setKeylessRefusal(null);
- } else void write({ open: false });
+ } else {
+ setKeylessOffRefusal(null);
+ void write({ open: false }, (e) => setKeylessOffRefusal(apiKeylessOffRefused(e)));
+ }
}}
onStartKey={() => {
setDraftName("");
diff --git a/packages/web/src/features/agents/api-write-refusal.ts b/packages/web/src/features/agents/api-write-refusal.ts
new file mode 100644
index 00000000..ab66ea93
--- /dev/null
+++ b/packages/web/src/features/agents/api-write-refusal.ts
@@ -0,0 +1,43 @@
+/**
+ * The API tab's three writes that ask nothing first — turning the API on, the approval mode its
+ * conversations start with, and turning keyless access off — and the line a refusal leaves under
+ * the control that asked for it.
+ *
+ * None of these controls moves optimistically: the switch and the select show what the server
+ * answered with, so a refused write leaves the tab exactly as it was — the switch in its old
+ * position, the select back on the stored mode. Until 7.98 the reason lived only in a notification
+ * that dismissed itself after six seconds; after it the control simply looked as if it had been
+ * pressed and come back, with nothing on screen saying why. That is the shape 7.19 bans, and this
+ * tab is where the refusal carries the most weight of all: a keyless-off that did not land leaves
+ * anything that can reach the address talking to the Agent without a key.
+ *
+ * The three sentences differ on purpose.
+ *
+ * - Turning the API on: it is still off, so external programs are still refused. The switch is the
+ * retry.
+ * - The approval mode: the select falls back to the stored mode, so the sentence has to name the
+ * mode that was asked for — otherwise it describes a change the reader no longer sees on screen.
+ * - Turning keyless access off: the sentence says the exposure is still open. That is the fact the
+ * reader has to act on, and it is the opposite of what pressing the switch looks like.
+ *
+ * The reason goes through `refusalText` (7.19's rule): what the server answered is read by its
+ * code's own localized sentence, never the English wire message.
+ */
+import type { ApprovalMode } from "@adelie/server/api";
+import { refusalText } from "../../lib/api-error";
+import { S } from "../../lib/strings";
+
+/** The switch at the top of the tab: still off, so nothing external got in. */
+export function apiEnabledRefused(err: unknown): string {
+ return S.agent.apiEnableRefused(refusalText(err));
+}
+
+/** The approval mode: still the stored one, so the sentence names the mode that was asked for. */
+export function apiApprovalModeRefused(mode: ApprovalMode, err: unknown): string {
+ return S.agent.apiApprovalModeRefused(S.chat.approvalModeNames[mode] ?? mode, refusalText(err));
+}
+
+/** Keyless access: still open — anything that reaches the address still gets in without a key. */
+export function apiKeylessOffRefused(err: unknown): string {
+ return S.agent.apiKeylessOffRefused(refusalText(err));
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index fb342a2a..f4c751d1 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1997,9 +1997,18 @@ export const en: Strings = {
apiOwnerOnly: "Only the Project owner can change these settings.",
apiAdminOff:
"An admin has turned the Agent API off for this server: every API request is refused, and the settings and keys here are kept.",
+ /**
+ * A refused flip of the switch above: it never moved, so external programs are still refused —
+ * and the switch itself is the retry.
+ */
+ apiEnableRefused: (reason: string): string =>
+ `API access was not turned on; external programs still cannot call it: ${reason}`,
apiApprovalMode: "Approval mode for API conversations",
apiApprovalModeHint:
"Applies to API conversations created from now on; when a mode asks, the request goes to the caller and can also be answered here.",
+ /** A refused change: the select fell back to the stored mode, so the sentence names the one asked for. */
+ apiApprovalModeRefused: (mode: string, reason: string): string =>
+ `The approval mode was not changed to "${mode}": ${reason}`,
apiConnection: "Connection",
apiBaseUrl: "Base URL",
apiAgentId: "Agent ID",
@@ -2020,6 +2029,12 @@ export const en: Strings = {
apiOpen: "Allow keyless access",
apiOpenHint:
"Anything that can reach this address can talk to the agent; recommended for loopback use only.",
+ /**
+ * A refused keyless-off: the switch never moved, so the exposure the reader just tried to close
+ * is still open — and that half is what they have to act on.
+ */
+ apiKeylessOffRefused: (reason: string): string =>
+ `Keyless access was not turned off; anything that can reach this address can still call it without a key: ${reason}`,
apiExamples: "Examples",
apiOpenTitle: "Allow keyless access?",
apiOpenBody:
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 686cbb2e..96f34513 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -2027,9 +2027,18 @@ export const zh = {
apiOwnerOnly: "只有 Project 所有者可以更改这些设置。",
apiAdminOff:
"管理员已在服务器设置中关闭 Agent API:所有 API 请求都会被拒绝,这里的设置与密钥保留。",
+ /**
+ * A refused flip of the switch above: it never moved, so external programs are still refused —
+ * and the switch itself is the retry.
+ */
+ apiEnableRefused: (reason: string): string =>
+ `API 访问没有打开,外部程序仍然无法调用:${reason}`,
apiApprovalMode: "API 会话的审批模式",
apiApprovalModeHint:
"应用于之后新建的 API 会话;需要确认时,确认请求会发给调用方,也可在 Web App 中回答。",
+ /** A refused change: the select fell back to the stored mode, so the sentence names the one asked for. */
+ apiApprovalModeRefused: (mode: string, reason: string): string =>
+ `审批方式没有改成「${mode}」:${reason}`,
apiConnection: "连接",
apiBaseUrl: "Base URL",
apiAgentId: "Agent ID",
@@ -2050,6 +2059,12 @@ export const zh = {
`删除密钥「${name}」?使用它的程序会立即被拒绝,此操作不可撤销。`,
apiOpen: "允许无密钥访问",
apiOpenHint: "任何能访问此地址的程序都能与该 Agent 对话;仅建议本机使用。",
+ /**
+ * A refused keyless-off: the switch never moved, so the exposure the reader just tried to close
+ * is still open — and that half is what they have to act on.
+ */
+ apiKeylessOffRefused: (reason: string): string =>
+ `无密钥访问没有关掉,任何能访问此地址的程序仍然无需密钥就能调用:${reason}`,
apiExamples: "示例",
/** Turning the Agent's API off asks first: every program using it is refused from then on. */
apiOpenTitle: "允许无密钥访问?",
diff --git a/packages/web/test/agent-api-tab.test.ts b/packages/web/test/agent-api-tab.test.ts
index df4278b2..0f946948 100644
--- a/packages/web/test/agent-api-tab.test.ts
+++ b/packages/web/test/agent-api-tab.test.ts
@@ -15,6 +15,9 @@
* - With the admin's server-wide switch off, the tab's switch is disabled and says why, to every
* member and not only an admin (the tab's own read carries the switch); a member who is not the
* owner finds every control disabled, no key actions, and is told why.
+ * - The three writes that ask nothing first draw a refused reason under the control that asked:
+ * the API switch, the approval select and the keyless switch — one alert each, in its own place,
+ * and none at all when nothing was refused.
* - Turning the API off asks first, in the danger tone. Answered yes, it writes the switch off
* and hands on what the server stored; a failed write is handed on as the failure.
* - Deleting a key asks first, naming it. Answered yes, it deletes that key and hands on its id;
@@ -220,6 +223,28 @@ describe("the API tab", () => {
expect(enabled).not.toMatch(/<input[^>]*disabled=""/);
});
+ it("draws each refused write's reason under the control that asked, and no alert when none was refused", () => {
+ // Nothing refused: the tab has no alert at all — the sentences appear only when asked for.
+ expect(render()).not.toContain('role="alert"');
+
+ const enable = S.agent.apiEnableRefused("write refused");
+ const mode = S.agent.apiApprovalModeRefused(
+ S.chat.approvalModeNames["always-ask"] as string,
+ "write refused",
+ );
+ const keyless = S.agent.apiKeylessOffRefused("write refused");
+ const html = render({
+ enableRefusal: enable,
+ approvalRefusal: mode,
+ keylessOffRefusal: keyless,
+ });
+ expect(html.split('role="alert"').length - 1).toBe(3);
+ // Each one sits under its own control: the switch, the approval select, the keyless switch.
+ expect(html.indexOf(enable)).toBeLessThan(html.indexOf(S.agent.apiApprovalMode));
+ expect(html.indexOf(mode)).toBeGreaterThan(html.indexOf(S.agent.apiApprovalMode));
+ expect(html.indexOf(keyless)).toBeGreaterThan(html.indexOf(S.agent.apiOpenHint));
+ });
+
it("leaves a member who is not the owner every control disabled and no key action", () => {
const tree = ApiTabView(props({ isOwner: false }));
const toggles = find(tree, ToggleRow);
diff --git a/packages/web/test/api-write-refusal.test.ts b/packages/web/test/api-write-refusal.test.ts
new file mode 100644
index 00000000..0d78e7eb
--- /dev/null
+++ b/packages/web/test/api-write-refusal.test.ts
@@ -0,0 +1,97 @@
+/**
+ * The API tab's three ask-nothing-first writes (src/features/agents/api-write-refusal.ts): which
+ * words a refusal leaves under the switch or the select that asked, and which fact each of those
+ * sentences has to carry.
+ *
+ * The controls never move on their own — they show what the server stored — so a refused write
+ * leaves them exactly where they were. Each sentence therefore names the state the reader is
+ * actually in: the API still off, the mode still the stored one (with the mode asked for, which is
+ * what fell back), and keyless access still open.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { ApiError } from "../src/api/client";
+import { en as EN } from "../src/lib/strings-en";
+import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";
+import {
+ apiApprovalModeRefused,
+ apiEnabledRefused,
+ apiKeylessOffRefused,
+} from "../src/features/agents/api-write-refusal";
+
+afterEach(() => {
+ setActiveStrings(ZH);
+});
+
+describe("apiEnabledRefused", () => {
+ it("says the API is still off, with the server's reason", () => {
+ const line = apiEnabledRefused(new ApiError(500, "internal", "RAW ENGLISH SERVER MESSAGE"));
+ expect(line).toBe(S.agent.apiEnableRefused(S.errors.byCode["internal"] as string));
+ expect(line).toContain(S.errors.byCode["internal"] as string);
+ expect(line).not.toContain("RAW ENGLISH SERVER MESSAGE");
+ });
+
+ it("keeps a sentence the interface raised itself", () => {
+ expect(apiEnabledRefused(new Error("位置没有找到"))).toBe(
+ S.agent.apiEnableRefused("位置没有找到"),
+ );
+ });
+
+ it("falls back to the generic text when the value has nothing to say", () => {
+ expect(apiEnabledRefused(undefined)).toBe(S.agent.apiEnableRefused(S.common.unknownError));
+ });
+
+ it("speaks the interface's own language in English too", () => {
+ setActiveStrings(EN);
+ expect(apiEnabledRefused(new ApiError(500, "internal", "RAW ENGLISH SERVER MESSAGE"))).toBe(
+ EN.agent.apiEnableRefused(EN.errors.byCode["internal"] as string),
+ );
+ });
+});
+
+describe("apiApprovalModeRefused", () => {
+ it("names the mode that was asked for, because the select fell back to the stored one", () => {
+ const line = apiApprovalModeRefused(
+ "always-ask",
+ new ApiError(500, "internal", "RAW ENGLISH SERVER MESSAGE"),
+ );
+ expect(line).toBe(
+ S.agent.apiApprovalModeRefused(
+ S.chat.approvalModeNames["always-ask"] as string,
+ S.errors.byCode["internal"] as string,
+ ),
+ );
+ expect(line).toContain(S.chat.approvalModeNames["always-ask"] as string);
+ });
+
+ it("reads the reason through its code rather than the wire message", () => {
+ const line = apiApprovalModeRefused("read-only", new ApiError(409, "internal", "RAW ENGLISH"));
+ expect(line).not.toContain("RAW ENGLISH");
+ });
+
+ it("names the mode in English as well", () => {
+ setActiveStrings(EN);
+ expect(apiApprovalModeRefused("read-only", new ApiError(500, "internal", "RAW ENGLISH"))).toBe(
+ EN.agent.apiApprovalModeRefused(
+ EN.chat.approvalModeNames["read-only"] as string,
+ EN.errors.byCode["internal"] as string,
+ ),
+ );
+ });
+});
+
+describe("apiKeylessOffRefused", () => {
+ it("says keyless access is still open — the exposure the press tried to close", () => {
+ const line = apiKeylessOffRefused(new ApiError(500, "internal", "RAW ENGLISH SERVER MESSAGE"));
+ expect(line).toBe(S.agent.apiKeylessOffRefused(S.errors.byCode["internal"] as string));
+ // The half a reader has to act on: the switch never moved, so anything reaching the address
+ // still gets in without a key.
+ expect(line).toContain("仍然");
+ expect(line).not.toContain("RAW ENGLISH SERVER MESSAGE");
+ });
+
+ it("keeps a sentence the interface raised itself", () => {
+ expect(apiKeylessOffRefused(new Error("网络不通"))).toBe(
+ S.agent.apiKeylessOffRefused("网络不通"),
+ );
+ });
+});