Skip to content

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

fix(web): a refused command-policy Save says which policy is still in force

lmlihenga085c2ada5ef
diff --git a/changelog/unreleased/2026-11-14-command-policy-save-refusal.md b/changelog/unreleased/2026-11-14-command-policy-save-refusal.md
new file mode 100644
index 00000000..3c3e6cc8
--- /dev/null
+++ b/changelog/unreleased/2026-11-14-command-policy-save-refusal.md
@@ -0,0 +1,66 @@
+# A refused Save on the security-policy page says which policy is still in force
+
+- **Date:** 2026-11-14
+- **Type:** fix
+- **Scope:** `web`
+- **Breaking:** no
+
+[中文版](2026-11-14-command-policy-save-refusal.zh.md)
+
+One Save on Project settings → Security policy PUTs the whole `[command_policy]` block — the master
+switch and every rule — so a refusal leaves the controls on screen showing a state the engine is
+not running: the reader who just switched command blocking off believes the next command runs
+unguarded, and the reader who just added a deny rule believes it is enforced. The refusal was a
+notification carrying the error's own words and nothing else, and it was gone six seconds later —
+leaving a list that looked saved. That is the rule every write refusal in the app follows (the
+sentence belongs where the attempt was made), and the security-policy page was the last one in
+Project settings still sending a toast.
+
+The sentence now sits in the Save button's own row, and it says what the Project still enforces:
+with the master switch part of the attempt it names the state that stays in force (blocking still
+on, or still off, with the rules from the last save); with only the rule list touched it says the
+stored policy is untouched and never claims the switch moved. Each attempt clears the sentence
+from the attempt before it, and the Save button is still the retry.
+
+The rule list is the one thing here a reader can overflow without being told: the route caps a
+policy at 64 rules and the page neither says so nor stops at it. That is how the refusal is
+reachable — and what the sentence is worth, since a 65th rule silently missing from the file is
+exactly the state this page used to leave unexplained.
+
+## Details
+
+- `packages/web/src/lib/command-policy-save-refusal.ts` (new): `commandPolicySaveRefused(attempt,
+ error)` — `{ enabled, savedEnabled }` plus the sentence, read through `refusalText` (an answer
+ the server gave is spoken through its code's own localized words; a failure this codebase raised
+ is shown as written). The attempt comes back with the sentence so a caller can tell which of the
+ three cases it was.
+- `packages/web/src/components/layout/project-dialogs.tsx`: `SecurityPolicySection` keeps the
+ sentence in a `saveRefusal` slot instead of calling `toastError`, clears it at the start of every
+ attempt, and drops it when the dialog switches Project. The sentence is drawn `role="alert"`
+ (`data-testid="command-policy-refusal"`, two lines max, the whole text on hover) beside the Save
+ button — in the button's own row, not stacked above it: the rule list alone overflows this
+ dialog's scroll box, and a sentence over the button pushed the retry out of view exactly when it
+ was needed.
+- Dictionaries (`strings.ts` / `strings-en.ts`): three sentences — the switch still on, the switch
+ still off, and the stored policy untouched.
+- No API change, no new dependency, no server-side behaviour change.
+
+## Tests
+
+- `packages/web/test/command-policy-save-refusal.test.ts` (new, 6 cases): a refused switch-off says
+ blocking is still on; a refused switch-on says it is still off; an untouched switch is never
+ reported as flipped; a mapped error code is spoken in the interface's own words instead of the
+ wire message; a value with nothing to say falls back to the generic text; the sentence follows
+ the active dictionary.
+- `packages/web/e2e/command-policy-save-refusal.spec.mjs` (new, 2 cases, real server + real
+ browser): the Project holds 64 rules (the route's ceiling) and the draft adds the 65th through
+ the form — with the switch also switched off, the sentence names the engine's state and the
+ server's own reason, nothing lands in the notification region, the stored policy is still the
+ 64 rules it was, and the sentence is still there after seven seconds; the same button then lands
+ the save once the list is back under the ceiling. A refused rule-list edit alone claims neither
+ switch state, and the stored policy is byte-for-byte the earlier read.
+
+## Compatibility
+
+No wire change: the same PUT, the same validation. What changes is what a refused Save tells the
+reader, and it tells it next to the control that asked.
diff --git a/changelog/unreleased/2026-11-14-command-policy-save-refusal.zh.md b/changelog/unreleased/2026-11-14-command-policy-save-refusal.zh.md
new file mode 100644
index 00000000..37e73be8
--- /dev/null
+++ b/changelog/unreleased/2026-11-14-command-policy-save-refusal.zh.md
@@ -0,0 +1,48 @@
+# 安全策略页的一次保存被拒时,说清仍在执行的是哪一份策略
+
+- **日期:** 2026-11-14
+- **类型:** 修复
+- **范围:** `web`
+- **破坏性变更:** 否
+
+[English](2026-11-14-command-policy-save-refusal.md)
+
+项目设置「安全策略」页的一次保存,整块 PUT `[command_policy]` —— 主开关与全部规则,所以被拒时屏幕上的控件
+显示的是**引擎没有在跑**的那一份:刚关掉命令拦截的人以为下一条命令不会被挡,刚加了一条 deny 规则的人以为它
+在生效。而那条拒绝只落在一句通知里,念的是错误自己的话,六秒后就自己消失,留下一张看起来已经保存的列表。
+这正是全应用那条「被拒的原因留在发问的地方」的规则,而这一页是项目设置里最后一处还在发通知的写。
+
+现在这句话画在保存按钮自己那一行里,并且说清项目仍在执行什么:主开关是这次尝试的一部分时,它点名仍在生效的
+那一个状态(命令拦截仍是启用、或仍是停用,规则也还是上一次保存的);只动了规则表时,它说存下来的策略没有被
+动过,绝口不提开关变过。每次尝试先清掉上一次那句,保存按钮仍然是重试。
+
+规则表是这一页唯一能悄悄撑破的东西:路由把一份策略限制在 64 条规则,而页面既不说明也不在此拦下 —— 这既是这条
+拒绝能走到的地方,也是这句话的价值所在:第 65 条规则无声无息地没进文件,正是这一页过去留下的那种不解释的状态。
+
+## 细节
+
+- `packages/web/src/lib/command-policy-save-refusal.ts`(新增):`commandPolicySaveRefused(attempt,
+ error)` —— `{ enabled, savedEnabled }` 加上那句话,原因走 `refusalText`(服务端给的答案念它自己
+ 错误码的本地化句子,本仓库自己抛出的失败按它写的原样显示)。这次尝试随句子一起返回,调用方因此能分辨
+ 三种情形里的哪一种。
+- `packages/web/src/components/layout/project-dialogs.tsx`:`SecurityPolicySection` 把这句话放进
+ `saveRefusal` 槽,不再 `toastError`;每次尝试开始时先清掉上一次那句,切 Project 时一并清掉。句子是
+ `role="alert"`(`data-testid="command-policy-refusal"`、最多两行、悬停看全文),画在保存按钮旁边 ——
+ 在按钮**那一行**里,而不是压在它上方:规则表本身就已经撑出这个对话框的滚动框,压在按钮上方的句子会把
+ 「重试」正好在需要它的时候推出视野。
+- 词典(`strings.ts` / `strings-en.ts`):三句 —— 开关仍是启用、开关仍是停用、存下来的策略没被动过。
+- 没有接口变化、没有新依赖、服务端行为没变。
+
+## 测试
+
+- `packages/web/test/command-policy-save-refusal.test.ts`(新增,6 条):被拒的「关掉」说拦截仍启用;
+ 被拒的「打开」说仍停用;开关没动时绝不声称它变过;映射过的错误码念界面的语言而不是线上那句话;无话可说的
+ 值落到通用文案;句子跟随当前词典。
+- `packages/web/e2e/command-policy-save-refusal.spec.mjs`(新增,2 条,真服务端 + 真浏览器):项目里已有
+ 64 条规则(路由的上限),草稿通过表单加进第 65 条 —— 同时把开关也关掉时,句子点名引擎的状态与服务器自己的
+ 原因,通知区 0 个按钮,存下来的策略仍是那 64 条,七秒后句子仍在;把表恢复到上限以内后按**同一个按钮**即落地。
+ 只动规则表的那一次不声称开关的任何状态,存下来的策略与之前读到的一模一样。
+
+## 兼容性
+
+线上协议没变:同一个 PUT、同一套校验。变的是被拒的一次保存告诉读者什么,以及它在发问的那个控件旁边告诉。
diff --git a/packages/web/e2e/command-policy-save-refusal.spec.mjs b/packages/web/e2e/command-policy-save-refusal.spec.mjs
new file mode 100644
index 00000000..c85f2db5
--- /dev/null
+++ b/packages/web/e2e/command-policy-save-refusal.spec.mjs
@@ -0,0 +1,177 @@
+/**
+ * Regression: a refused Save on Project settings → Security policy keeps its reason above the
+ * Save button that asked, and says which policy the engine is still running.
+ *
+ * One Save PUTs the whole `[command_policy]` block — the master switch and every rule — so a
+ * refusal leaves the controls on screen showing a state the engine is not running. Before, the
+ * reason was a six-second notification repeating the error's own words: the reader who had just
+ * switched blocking off believed the next command ran unguarded, and the reader who had just added
+ * the 65th rule believed it was enforced.
+ *
+ * The refusal here is the server's own answer: the route caps the rule list at 64 entries
+ * (`MAX_RULES`, `http/routes/command-policy.ts`) and the page never says so and never stops you at
+ * it. The spec materializes the 64-rule list through the API — exactly what a Project with a long
+ * deny list already holds — then adds the 65th one through the form, the way a user does.
+ */
+import { test, expect } from "@playwright/test";
+import { ADMIN_ID, ADMIN_PASSWORD, login } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+
+/** The shared notification region: a refusal must not also land in it. */
+const notices = (page) => page.getByRole("region", { name: "通知" });
+
+/** The route's own ceiling, mirrored here as the situation being tested. */
+const MAX_RULES = 64;
+
+async function projectIdOf(page) {
+ return (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0].projectId;
+}
+
+async function policyOf(page, projectId) {
+ return (await page.request.get(`${BASE}/api/projects/${projectId}/command-policy`)).json();
+}
+
+/**
+ * A rule list at the ceiling: the Project's own defaults, each cloned under a distinct name until
+ * there are exactly `MAX_RULES` of them. Counted rather than pinned, so a data root that outlives
+ * a rerun and a factory set that grows both stay valid.
+ */
+function fullList(defaults) {
+ const rules = [];
+ for (let i = 0; rules.length < MAX_RULES; i += 1) {
+ const base = defaults[i % defaults.length];
+ const name = i < defaults.length ? base.name : `${base.name}-${i}`;
+ rules.push({
+ name,
+ pattern: `\\b${name.replace(/[^a-zA-Z0-9-]/g, "-")}\\b`,
+ enabled: true,
+ });
+ }
+ return rules;
+}
+
+/** Stores a policy directly (the state a Project with a long deny list is already in). */
+async function storePolicy(page, projectId, body) {
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/command-policy`, {
+ data: body,
+ });
+ expect(put.ok(), await put.text()).toBeTruthy();
+ return put.json();
+}
+
+/** Opens Project settings → Security policy through the sidebar, the way a user gets there. */
+async function openSecurity(page) {
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const project = projects.projects[0];
+ const sidebar = page.getByRole("complementary");
+ await expect(sidebar).toBeVisible({ timeout: 20000 });
+ await sidebar.getByRole("button", { name: project.name ?? project.projectId }).click();
+ // Same DOM click as the members spec: the row closes its menu as it opens the dialog.
+ await page.getByRole("button", { name: "项目设置" }).evaluate((el) => el.click());
+ const dialog = page.getByRole("dialog", { name: "项目设置" });
+ await expect(dialog).toBeVisible();
+ await dialog.getByRole("button", { name: "安全策略" }).click();
+ // The section arrives with its read: the master switch and the rule count are both there.
+ await expect(dialog.getByRole("switch").first()).toBeVisible();
+ await expect(dialog.getByText(/^规则 · \d+$/)).toBeVisible();
+ await expect(dialog.getByRole("button", { name: "保存" })).toBeVisible();
+ return dialog;
+}
+
+/** The master switch is the first switch on the page — the rule rows have one each, below it. */
+const masterSwitch = (dialog) => dialog.getByRole("switch").first();
+
+/** Adds one rule through the form at the top of the list. */
+async function addRule(page, dialog, name) {
+ await dialog.getByRole("button", { name: "添加规则" }).click();
+ // The required mark puts a "*" inside each label, so the name is matched by prefix.
+ await page.getByLabel(/^名称/).fill(name);
+ await page.getByLabel(/^正则表达式/).fill(`\\b${name}\\b`);
+ await dialog.getByRole("button", { name: "确定" }).click();
+ await expect(dialog.getByRole("button", { name: "保存" })).toBeEnabled();
+}
+
+test("a refused Save that would have switched blocking off says it is still on", async ({
+ page,
+}) => {
+ await login(page.request, ADMIN_ID, ADMIN_PASSWORD);
+ const projectId = await projectIdOf(page);
+ const factory = await policyOf(page, projectId);
+ // Normalized first, so a rerun starts from the switch ON and the list at the ceiling.
+ await storePolicy(page, projectId, { enabled: true, rules: fullList(factory.defaultRules) });
+ const storedBefore = await policyOf(page, projectId);
+ expect(storedBefore.rules).toHaveLength(MAX_RULES);
+
+ await page.goto(`${BASE}/chat`);
+ const dialog = await openSecurity(page);
+ await expect(masterSwitch(dialog)).toHaveAttribute("aria-checked", "true");
+
+ // The draft asks for two things: a rule past the ceiling, and blocking off. The rule comes
+ // first because the list goes inert the moment the master switch is off.
+ await addRule(page, dialog, "past-the-ceiling");
+ await masterSwitch(dialog).click();
+ await expect(masterSwitch(dialog)).toHaveAttribute("aria-checked", "false");
+
+ await dialog.getByRole("button", { name: "保存" }).click();
+
+ const refusal = dialog.getByTestId("command-policy-refusal");
+ await expect(refusal).toBeVisible();
+ await expect(refusal).toHaveAttribute("role", "alert");
+ // The state the engine is in — the switch on screen says the opposite.
+ await expect(refusal).toContainText("命令拦截仍处于启用状态");
+ // …and the server's own reason.
+ await expect(refusal).toContainText(`rules exceeds ${MAX_RULES} entries.`);
+ // Nothing was reported through a notification instead.
+ await expect(notices(page).getByRole("button")).toHaveCount(0);
+
+ // Nothing was written: still ON, still exactly the 64 rules read before.
+ expect(await policyOf(page, projectId)).toEqual(storedBefore);
+
+ // Six seconds is how long a toast lives: the sentence has to outlive it.
+ await page.waitForTimeout(7000);
+ await expect(refusal).toBeVisible();
+
+ // Back to a list the route accepts, then press the same button: it lands, the sentence goes.
+ await masterSwitch(dialog).click();
+ await expect(masterSwitch(dialog)).toHaveAttribute("aria-checked", "true");
+ await dialog.getByRole("button", { name: "恢复默认" }).click();
+ await expect(dialog.getByRole("button", { name: "保存" })).toBeEnabled();
+ await dialog.getByRole("button", { name: "保存" }).click();
+ await expect(refusal).toHaveCount(0);
+ const retried = await policyOf(page, projectId);
+ expect(retried.enabled).toBe(true);
+ expect(retried.rules).toHaveLength(factory.defaultRules.length);
+});
+
+test("a refused rule-list edit does not claim the switch moved", async ({ page }) => {
+ await login(page.request, ADMIN_ID, ADMIN_PASSWORD);
+ const projectId = await projectIdOf(page);
+ const factory = await policyOf(page, projectId);
+ await storePolicy(page, projectId, { enabled: true, rules: fullList(factory.defaultRules) });
+ const storedBefore = await policyOf(page, projectId);
+
+ await page.goto(`${BASE}/chat`);
+ const dialog = await openSecurity(page);
+ await expect(masterSwitch(dialog)).toHaveAttribute("aria-checked", "true");
+
+ // Only the rule list changes: the switch stays where the Project has it.
+ await addRule(page, dialog, "one-too-many");
+ await dialog.getByRole("button", { name: "保存" }).click();
+
+ const refusal = dialog.getByTestId("command-policy-refusal");
+ await expect(refusal).toBeVisible();
+ await expect(refusal).toContainText("项目里仍是上一次保存的那一份");
+ // Neither switch sentence: this attempt never tried to change the switch.
+ await expect(refusal).not.toContainText("启用状态");
+ await expect(refusal).not.toContainText("停用状态");
+ await expect(notices(page).getByRole("button")).toHaveCount(0);
+ expect(await policyOf(page, projectId)).toEqual(storedBefore);
+
+ // "Restore defaults" brings the list back under the ceiling; the same button lands it.
+ await dialog.getByRole("button", { name: "恢复默认" }).click();
+ await dialog.getByRole("button", { name: "保存" }).click();
+ await expect(refusal).toHaveCount(0);
+ const retried = await policyOf(page, projectId);
+ expect(retried.rules).toHaveLength(factory.defaultRules.length);
+});
diff --git a/packages/web/src/components/layout/project-dialogs.tsx b/packages/web/src/components/layout/project-dialogs.tsx
index fa54d361..8a5323a2 100644
--- a/packages/web/src/components/layout/project-dialogs.tsx
+++ b/packages/web/src/components/layout/project-dialogs.tsx
@@ -37,6 +37,7 @@ import {
chatDefaultsSaveRefused,
type ChatDefaultsWrite,
} from "../../lib/chat-defaults-save-refusal";
+import { commandPolicySaveRefused } from "../../lib/command-policy-save-refusal";
import { memberWriteRefused, type MemberRefusal } from "../../lib/member-write-refusal";
import { toneInk } from "../../lib/tone";
import {
@@ -983,6 +984,8 @@ function SecurityPolicySection({ projectId, isOwner }: { projectId: string; isOw
const [busy, setBusy] = useState(false);
const [enabled, setEnabled] = useState(true);
const [rules, setRules] = useState<CommandPolicyRuleDto[]>([]);
+ /** The sentence the last refused Save left (command-policy-save-refusal.ts), if any. */
+ const [saveRefusal, setSaveRefusal] = useState<string | null>(null);
/** Index being edited inline, "new" for the add form, null when idle. */
const [editing, setEditing] = useState<number | "new" | null>(null);
@@ -993,6 +996,8 @@ function SecurityPolicySection({ projectId, isOwner }: { projectId: string; isOw
setSaved(null);
setLoadError(null);
setEditing(null);
+ // A sentence about THIS project's refused Save must not outlive the switch to another one.
+ setSaveRefusal(null);
api
.getCommandPolicy(projectId)
.then((res) => {
@@ -1018,6 +1023,8 @@ function SecurityPolicySection({ projectId, isOwner }: { projectId: string; isOw
const save = async () => {
if (busy || !dirty) return;
setBusy(true);
+ // Cleared first: an earlier refusal must not hang over a later attempt that may well land.
+ setSaveRefusal(null);
try {
const stored = await api.putCommandPolicy(projectId, { enabled, rules });
setSaved(stored);
@@ -1025,7 +1032,14 @@ function SecurityPolicySection({ projectId, isOwner }: { projectId: string; isOw
setRules(stored.rules);
toastSuccess(S.common.saved);
} catch (e) {
- toastError(apiErrorText(e));
+ // Not a toast: the switch and the list above now show the draft, and the sentence is what
+ // says which policy the engine is still running (command-policy-save-refusal.ts).
+ setSaveRefusal(
+ commandPolicySaveRefused(
+ { enabled, savedEnabled: saved === null ? enabled : saved.enabled },
+ e,
+ ).text,
+ );
} finally {
setBusy(false);
}
@@ -1169,17 +1183,36 @@ function SecurityPolicySection({ projectId, isOwner }: { projectId: string; isOw
</div>
</div>
{isOwner && (
- <div className="mt-2 flex justify-end border-t border-gray-100 pt-3 dark:border-gray-800/60">
- {/* Blocked while a rule editor is open, like every other control here: the
- editor is keyed by index, so a save that replaced the list underneath it
- would leave a stale draft that Apply then writes over the wrong rule. */}
- <Button
- size="sm"
- disabled={busy || !dirty || editing !== null}
- onClick={() => void save()}
- >
- {S.common.save}
- </Button>
+ <div className="mt-2 flex items-end gap-3 border-t border-gray-100 pt-3 dark:border-gray-800/60">
+ {/* A refused Save belongs beside the button that asked, saying which policy the
+ engine is still running (command-policy-save-refusal.ts): the switch and the list
+ above show the buffered draft, and the toast this replaced could not say so. It
+ sits in the button's OWN row rather than above it — the rule list alone overflows
+ this dialog's scroll box, and a sentence stacked over the button pushed the
+ retry out of view at exactly the moment it was needed. */}
+ {saveRefusal !== null && (
+ <p
+ role="alert"
+ data-testid="command-policy-refusal"
+ data-tooltip={saveRefusal}
+ data-tooltip-content="text"
+ className={`line-clamp-2 min-w-0 flex-1 break-words text-xs ${toneInk.danger}`}
+ >
+ {saveRefusal}
+ </p>
+ )}
+ <div className="ml-auto shrink-0">
+ {/* Blocked while a rule editor is open, like every other control here: the
+ editor is keyed by index, so a save that replaced the list underneath it
+ would leave a stale draft that Apply then writes over the wrong rule. */}
+ <Button
+ size="sm"
+ disabled={busy || !dirty || editing !== null}
+ onClick={() => void save()}
+ >
+ {S.common.save}
+ </Button>
+ </div>
</div>
)}
</>
diff --git a/packages/web/src/lib/command-policy-save-refusal.ts b/packages/web/src/lib/command-policy-save-refusal.ts
new file mode 100644
index 00000000..224c2183
--- /dev/null
+++ b/packages/web/src/lib/command-policy-save-refusal.ts
@@ -0,0 +1,51 @@
+/**
+ * The Security-policy page of the Project settings dialog
+ * (`components/layout/project-dialogs.tsx`) and the sentence one refused Save leaves above its
+ * Save button.
+ *
+ * That page buffers the whole `[command_policy]` block — the master switch and every rule — and
+ * one Save PUTs it as a unit, so a refusal lands on a form whose controls show a state the engine
+ * is NOT running. Two readers get it wrong in the same way: the one who just switched blocking
+ * off believes the next command runs unblocked, and the one who just added a deny rule believes it
+ * is enforced. The notification that used to carry the reason repeated the error's own words and
+ * dismissed itself after six seconds, over a list that looked saved (7.19's rule, app-wide: the
+ * sentence belongs where the attempt was made).
+ *
+ * The sentence therefore says what the Project is still enforcing: the master switch as the last
+ * read reported it when this Save would have flipped it, or that the stored rule list is
+ * untouched. `refusalText` decides the words for the reason — an answer the server gave is spoken
+ * through its code's own localized sentence.
+ */
+import { refusalText } from "./api-error";
+import { S } from "./strings";
+
+/** The master switch as this Save would have stored it, and the one still in force. */
+export interface CommandPolicySaveAttempt {
+ /** `enabled` as the buffered draft would save it. */
+ readonly enabled: boolean;
+ /** `enabled` the Project still enforces — the value the last read returned. */
+ readonly savedEnabled: boolean;
+}
+
+/** The sentence one refused Save left, and the attempt it was for. */
+export interface CommandPolicySaveRefusal {
+ readonly attempt: CommandPolicySaveAttempt;
+ readonly text: string;
+}
+
+/** The sentence: what the Project is still enforcing, and why this Save was refused. */
+export function commandPolicySaveRefused(
+ attempt: CommandPolicySaveAttempt,
+ error: unknown,
+): CommandPolicySaveRefusal {
+ const reason = refusalText(error);
+ return {
+ attempt,
+ text:
+ attempt.enabled === attempt.savedEnabled
+ ? S.project.commandPolicyRefused(reason)
+ : attempt.savedEnabled
+ ? S.project.commandPolicyRefusedStillOn(reason)
+ : S.project.commandPolicyRefusedStillOff(reason),
+ };
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index faacb446..838be352 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1647,6 +1647,17 @@ export const en: Strings = {
commandPolicyRulePattern: "Regular expression",
commandPolicyRuleDesc: "Description",
commandPolicyInvalidPattern: "Invalid regular expression",
+ /**
+ * A Save this page was refused (command-policy-save-refusal.ts), drawn above the Save button
+ * that asked: one Save writes the switch and the whole rule list, so the sentence says which
+ * policy the engine is still running — the controls above show the buffered draft.
+ */
+ commandPolicyRefused: (reason: string): string =>
+ `Could not save the command policy — the Project still holds the last one it saved: ${reason}`,
+ commandPolicyRefusedStillOn: (reason: string): string =>
+ `Could not save the command policy — command blocking is still ON, with the rules from the last save: ${reason}`,
+ commandPolicyRefusedStillOff: (reason: string): string =>
+ `Could not save the command policy — command blocking is still OFF, with the rules from the last save: ${reason}`,
deleteProject: "Delete Project",
deleteConfirm:
"Delete this Project? Its directory will be removed recursively and cannot be recovered.",
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 5902744d..970fe607 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1693,6 +1693,18 @@ export const zh = {
commandPolicyRulePattern: "正则表达式",
commandPolicyRuleDesc: "描述",
commandPolicyInvalidPattern: "正则表达式无效",
+ /**
+ * A Save this page was refused (command-policy-save-refusal.ts), drawn above the Save button
+ * that asked: one Save writes the switch and the whole rule list, so the sentence has to say
+ * which policy the engine is still running — the controls above show the buffered draft, not
+ * the one in force.
+ */
+ commandPolicyRefused: (reason: string): string =>
+ `没能保存命令策略,项目里仍是上一次保存的那一份:${reason}`,
+ commandPolicyRefusedStillOn: (reason: string): string =>
+ `没能保存命令策略,命令拦截仍处于启用状态(规则也还是上一次保存的):${reason}`,
+ commandPolicyRefusedStillOff: (reason: string): string =>
+ `没能保存命令策略,命令拦截仍处于停用状态(规则也还是上一次保存的):${reason}`,
deleteProject: "删除项目",
deleteConfirm: "确认删除该项目?项目目录将被递归删除,不可恢复。",
deleteDefaultForbidden: "default_project 与 CLI 共用,不允许在 Web 端删除",
diff --git a/packages/web/test/command-policy-save-refusal.test.ts b/packages/web/test/command-policy-save-refusal.test.ts
new file mode 100644
index 00000000..7d4eedd0
--- /dev/null
+++ b/packages/web/test/command-policy-save-refusal.test.ts
@@ -0,0 +1,75 @@
+/**
+ * A Save the Project settings dialog refused (src/lib/command-policy-save-refusal.ts): the
+ * sentence the security-policy page draws above its Save button.
+ *
+ * One Save PUTs the whole `[command_policy]` block — the master switch and every rule — so a
+ * refusal leaves controls on screen that show a state the engine is not running. Three things the
+ * sentence has to get right: which policy is still in force when the switch was part of the
+ * attempt, that an untouched switch is never reported as flipped, and that an answer the server
+ * gave speaks the interface's own language rather than the wire message where a code is mapped.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import { ApiError } from "../src/api/client";
+import { S, setActiveStrings, zh as ZH } from "../src/lib/strings";
+import { en as EN } from "../src/lib/strings-en";
+import { commandPolicySaveRefused } from "../src/lib/command-policy-save-refusal";
+
+afterEach(() => {
+ setActiveStrings(ZH);
+});
+
+describe("commandPolicySaveRefused", () => {
+ it("a refused switch-off says blocking is still on", () => {
+ const refusal = commandPolicySaveRefused(
+ { enabled: false, savedEnabled: true },
+ new ApiError(500, "internal", "Internal server error."),
+ );
+ expect(refusal.attempt).toEqual({ enabled: false, savedEnabled: true });
+ // The engine's own state, not the draft the switch shows: the port is still guarded.
+ expect(refusal.text).toBe(S.project.commandPolicyRefusedStillOn(S.errors.byCode.internal!));
+ });
+
+ it("a refused switch-on says blocking is still off", () => {
+ const refusal = commandPolicySaveRefused(
+ { enabled: true, savedEnabled: false },
+ new Error("Failed to write .project_config.toml"),
+ );
+ expect(refusal.text).toBe(
+ S.project.commandPolicyRefusedStillOff("Failed to write .project_config.toml"),
+ );
+ });
+
+ it("a refused rule-list edit does not claim the switch moved either way", () => {
+ const reason = 'Rule "rm" has an invalid regular expression: (';
+ const refusal = commandPolicySaveRefused(
+ { enabled: true, savedEnabled: true },
+ new ApiError(400, "invalid_rule_pattern", reason),
+ );
+ expect(refusal.text).toBe(S.project.commandPolicyRefused(reason));
+ // Neither of the two switch sentences, which name a state this attempt never tried to change.
+ expect(refusal.text).not.toBe(S.project.commandPolicyRefusedStillOn(reason));
+ expect(refusal.text).not.toBe(S.project.commandPolicyRefusedStillOff(reason));
+ });
+
+ it("reads a mapped code through the interface's own words, not the wire message", () => {
+ const refusal = commandPolicySaveRefused(
+ { enabled: true, savedEnabled: true },
+ new ApiError(500, "internal", "Internal server error."),
+ );
+ expect(refusal.text).not.toContain("Internal server error.");
+ expect(refusal.text).toBe(S.project.commandPolicyRefused(S.errors.byCode.internal!));
+ });
+
+ it("falls back to the generic text when the value has nothing to say", () => {
+ expect(commandPolicySaveRefused({ enabled: true, savedEnabled: true }, undefined).text).toBe(
+ S.project.commandPolicyRefused(S.common.unknownError),
+ );
+ });
+
+ it("speaks the language the interface is in, not the one it was built in", () => {
+ setActiveStrings(EN);
+ expect(
+ commandPolicySaveRefused({ enabled: false, savedEnabled: true }, new Error("boom")).text,
+ ).toBe(EN.project.commandPolicyRefusedStillOn("boom"));
+ });
+});