A local-first multi-agent app development platform, built on PenguinHarness
fix(web): 压缩阈值被拒时,原因留在发问的那张卡片里,不再只活六秒
lmliheng622d59b75e73
diff --git a/changelog/unreleased/2026-11-08-context-threshold-refusal.md b/changelog/unreleased/2026-11-08-context-threshold-refusal.mdnew file mode 100644index 00000000..3c2bd9ed--- /dev/null+++ b/changelog/unreleased/2026-11-08-context-threshold-refusal.md@@ -0,0 +1,57 @@+# A refused compaction-threshold change says why inside the card that asked for it++- **Date:** 2026-11-08+- **Type:** fix+- **Scope:** `web`+- **Breaking:** no++[中文](2026-11-08-context-threshold-refusal.zh.md)++The context panel's dashed cutter never writes straight through: a release (or Enter on it) opens a+confirmation naming the Agent and the threshold it is about to replace, and the card's Save performs+the write. When the server refused that write, the card stayed open on the edited number — the Save+is the retry — but the only account of why was a notification above it, gone after six seconds. What+was left looked like a question nobody had answered.++That is the shape 7.19 bans, and on this card it costs more than usual: the field still holds the+number the person asked for, so nothing on screen says whether that number is in force. It is not —+the Agent still holds the old threshold.++The reason now renders inside the same card, under its sentence and above the buttons+(`role="alert"`, the danger tone, the whole sentence wrapping), until the next attempt or until the+card is closed. It names the threshold that was asked for, because that number lives nowhere else+once the dialog is gone, and says outright that the Agent still has the old value.++## Details++- `packages/web/src/features/chat/context-threshold-refusal.ts` (new): `contextThresholdRefused(tokens, error)`.+ 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); the figures go through+ `humanizeTokens`, so the sentence reads the same as the field and the ring above it.+- `packages/web/src/features/chat/context-gauge.tsx`: `confirmThreshold` keeps a refusal in+ `thresholdRefusal` instead of leaving it to the caller, and hands it to `ThresholdDialog`, which+ passes it to the shared `ConfirmModal`'s `refusal` slot. A newly proposed value and a closed card+ both clear it. The `onChangeCompactionLimit` contract now says the rejection is drawn here.+- `packages/web/src/features/chat/chat-page.tsx`: `onChangeCompactionLimit` no longer posts a toast+ before rethrowing — the card that asked is what says why, and a toast there sits above a dialog+ the person is still looking at.+- `packages/web/src/lib/strings{,-en}.ts`: one new sentence, `chat.contextThresholdRefused(n, reason)`.++## Tests++- `packages/web/test/context-threshold-refusal.test.ts` (new, 6 cases): the server's reason read+ through its code (never the wire message), a sentence this codebase raised itself kept as written,+ the generic text when nothing was said, the requested threshold named in `humanizeTokens` figures,+ the Agent's old value called out, and the English sentence.+- `packages/web/e2e/context-threshold-refusal.spec.mjs` (new, real server + real browser): one round+ through the mock model so the panel has a measured context, then the cutter moved two steps left+ and released, then Save refused at `page.route` and read back from server through the API. The+ sentence appears once, inside the card, in the interface's words; the notification region stays+ empty; the card keeps the edited number; the Agent still holds the old threshold — and **seven+ seconds later** the sentence is still there. Allowed, the same Save clears it, closes the card,+ writes the threshold and moves the cutter onto it.++## Compatibility++No interface change, no new dependency, no Project config change. The card's other behaviours — the+field's own validation, the window-cap hint, the success toast — are unchanged.diff --git a/changelog/unreleased/2026-11-08-context-threshold-refusal.zh.md b/changelog/unreleased/2026-11-08-context-threshold-refusal.zh.mdnew file mode 100644index 00000000..9be8b9bb--- /dev/null+++ b/changelog/unreleased/2026-11-08-context-threshold-refusal.zh.md@@ -0,0 +1,45 @@+# 压缩阈值没有改成时,原因留在发问的那张卡片里++- **日期:** 2026-11-08+- **类型:** 修复+- **范围:** `web`+- **破坏性变更:** 无++[English](2026-11-08-context-threshold-refusal.md)++上下文面板上那条虚线裁剪器从不直接写:松手(或在它上面按回车)会打开一个确认框,念出是哪个 Agent、要把阈值+从多少改掉,卡片里的「保存」才去写。服务端拒了这次写之后,卡片带着改过的数字原样留着 —— 保存就是重试 ——+但唯一解释原因的那句话在它上面的一条通知里,六秒后自己消失。留下的那张卡片看起来像个没人回答的问题。++这正是 7.19 禁止的形状,而在这张卡片上代价更大:字段里还留着那个人要的数字,屏幕上却没有一个字说它生效了+没有。它没有 —— Agent 手里仍是原来的阈值。++原因现在画在同一张卡片里,在它那句话下面、按钮上面(`role="alert"`、危险色、整句换行),留到下一次尝试或+卡片被关掉为止。句子念出被要求的那个阈值(对话一关,那个数字就没有别的落点),并明说 Agent 上仍然是原来的值。++## 细节++- 新增 `packages/web/src/features/chat/context-threshold-refusal.ts`:`contextThresholdRefused(tokens, error)`。+ 原因走 `refusalText`(7.19 的规则:服务端答复的按错误码念界面自己的本地化句子,不念线上英文原文);数字走+ `humanizeTokens`,所以这句话读起来与字段、与它上面的环一致。+- `packages/web/src/features/chat/context-gauge.tsx`:`confirmThreshold` 把拒绝留在 `thresholdRefusal` 里,+ 不再交给调用方;`ThresholdDialog` 把它交给共享的 `ConfirmModal` 的 `refusal` 槽。新提案与被关掉的卡片都会+ 清掉它。`onChangeCompactionLimit` 的契约改为「拒绝由这里画出来」。+- `packages/web/src/features/chat/chat-page.tsx`:`onChangeCompactionLimit` 不再在 reject 之前弹一条通知 ——+ 说原因的是发问的那张卡片,而通知会浮在读者正看着的对话框上面。+- `packages/web/src/lib/strings{,-en}.ts`:新增一句 `chat.contextThresholdRefused(n, reason)`。++## 测试++- `packages/web/test/context-threshold-refusal.test.ts`(新增,6 条):服务端的原因按错误码念(绝不念线上+ 原文)、界面自己抛出的句子原样保留、什么都没说时落到通用文案、念出被要求的阈值且用的是 `humanizeTokens`+ 的写法、点明 Agent 上仍是原来的值、以及英文那一句。+- `packages/web/e2e/context-threshold-refusal.spec.mjs`(新增,真服务端 + 真浏览器):先通过 mock 模型走一轮,+ 让面板有一次测得的上下文;再把裁剪器向左移两步并松手;保存由 `page.route` 拒掉,并从 API 读回服务端状态。+ 句子出现一次、在卡片里、念的是界面的话;通知区为空;卡片留着改过的数字;Agent 仍是原来的阈值 —— 而且+ **七秒之后**那句话还在。放行后同一颗保存清掉它、关掉卡片、写下阈值,裁剪器也停到新值上。++## 兼容性++不改接口、不引入新依赖、不改 Project 配置。这张卡片的其它行为 —— 字段自己的校验、超出模型窗口的提示、+成功时的通知 —— 原样不变。diff --git a/packages/web/e2e/context-threshold-refusal.spec.mjs b/packages/web/e2e/context-threshold-refusal.spec.mjsnew file mode 100644index 00000000..206b6de0--- /dev/null+++ b/packages/web/e2e/context-threshold-refusal.spec.mjs@@ -0,0 +1,168 @@+/**+ * Regression: a compaction threshold the server refused leaves its reason **inside** the+ * confirmation that asked for it, next to the Save that retries, and it stays there.+ *+ * The context panel's cutter never writes straight through: a release (or Enter on it) opens a+ * confirmation naming the Agent and the threshold it is about to replace, and that card's Save+ * performs the write. The card stays open on the edited value when the write is refused — so the+ * one sentence explaining it used to arrive as a notification above a dialog the person was still+ * looking at, and vanished after six seconds, leaving a question that looked unanswered.+ *+ * The write is refused at `page.route` and every check reads the server through the API as well,+ * so the sentence and the Agent'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 model's window, large enough that the cutter's lattice stays well below it. */+const CONTEXT_WINDOW = 200000;+/** What the Agent holds before the write under test, and what it must still hold while refused. */+const THRESHOLD = 100000;+/** One arrow press on the cutter. */+const STEP = 1000;++/** 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 configUrl = (projectId) => `${BASE}/api/projects/${projectId}/agents/${AGENT}/config`;++/**+ * Provision the user, give the Project a model (the onboarding overlay covers the page without+ * one) and put the Agent's compaction threshold on a known value. Every write is absolute, so+ * rerunning this file alone on one data root stays clean.+ */+async function projectWithThreshold(page, user) {+ 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: CONTEXT_WINDOW,+ },+ ],+ },+ });+ expect(models.ok(), "put models").toBeTruthy();+ const written = await page.request.put(configUrl(projectId), {+ data: { config: { compaction: { maxContextLength: THRESHOLD } } },+ });+ expect(written.ok(), "put the threshold").toBeTruthy();+ const sess = await (+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/${AGENT}/sessions`, {+ data: { provider: "custom", modelId: "claude-4-8", approvalMode: "allow-all" },+ })+ ).json();+ /** The threshold the Agent holds right now: what the panel reads and the write changes. */+ const stored = async () =>+ (await (await page.request.get(configUrl(projectId))).json()).config.compaction+ .maxContextLength;+ return { sessionId: sess.session.sessionId, stored };+}++/**+ * Take over the config write: every PUT 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, state) {+ await page.route("**/api/projects/*/agents/*/config", async (route) => {+ if (route.request().method() !== "PUT") return route.fallback();+ state.seen.push(route.request().postData() ?? "");+ if (!state.refuse) return route.fallback();+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: REFUSAL }),+ });+ });+}++/** 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 threshold change keeps the reason inside the card, and the threshold where it was", async ({+ page,+}) => {+ const { sessionId, stored } = await projectWithThreshold(page, "r211threshold");+ expect(await stored()).toBe(THRESHOLD);++ const state = { seen: [], refuse: true };+ await interceptWrite(page, state);++ await page.goto(`/chat/${sessionId}`);+ // The panel's bar (and the cutter on it) is drawn from a measured context, so the Session needs+ // one round in it first. The mock answers this prompt with a command and a closing line, and+ // `allow-all` on the Session keeps the approval out of the way.+ const composer = page.getByPlaceholder(/输入消息/);+ await composer.waitFor();+ await composer.fill("Help me set up @theme");+ await page.getByRole("button", { name: "发送" }).click();+ await expect(+ page.getByText("Command finished; the result looks as expected.").first(),+ ).toBeVisible();++ // The composer's context ring is the panel's trigger; its accessible name carries the figures.+ const ring = page.getByRole("button", { name: /上下文占用/ }).first();+ await ring.waitFor();+ await ring.click();++ // The cutter is a slider on the threshold's own lattice: two steps left, then a release.+ const cutter = page.getByRole("slider", { name: "压缩阈值" });+ await cutter.waitFor();+ expect(await cutter.getAttribute("aria-valuenow")).toBe(String(THRESHOLD));+ await cutter.focus();+ await cutter.press("ArrowLeft");+ await cutter.press("ArrowLeft");+ const asked = THRESHOLD - 2 * STEP;+ await expect(cutter).toHaveAttribute("aria-valuenow", String(asked));+ await cutter.press("Enter");++ // The card that asked: its field holds the proposed number, and Save writes it.+ const field = page.getByLabel("压缩阈值(token)");+ await expect(field).toHaveValue(String(asked));+ await page.getByRole("button", { name: "保存" }).click();++ // The reason is inside the card, in the interface's words, and only once.+ const line = page.getByRole("alert");+ await expect(line).toHaveCount(1);+ await expect(line).toHaveText(`压缩阈值没有改成 98k,Agent 上仍然是原来的值:${REASON}`);+ await expect(notifications(page).getByRole("button")).toHaveCount(0);+ expect(state.seen).toHaveLength(1);+ expect(JSON.parse(state.seen[0])).toEqual({+ config: { compaction: { maxContextLength: asked } },+ });++ // The card is still the question it was — same field, same value — and the Agent did not move.+ await expect(field).toHaveValue(String(asked));+ expect(await stored()).toBe(THRESHOLD);++ // Seven seconds later (the toast would be long gone) the sentence is still in the card.+ await page.waitForTimeout(7000);+ await expect(line).toHaveText(`压缩阈值没有改成 98k,Agent 上仍然是原来的值:${REASON}`);+ await expect(field).toBeVisible();++ // The Save is the retry: allowed now, the sentence goes, the card closes and the write lands.+ state.refuse = false;+ await page.getByRole("button", { name: "保存" }).click();+ await expect(page.getByRole("alert")).toHaveCount(0);+ await expect(field).toHaveCount(0);+ expect(state.seen).toHaveLength(2);+ expect(await stored()).toBe(asked);+ // The cutter now stands on the value that was written, not on the one it started from.+ await expect(page.getByRole("slider", { name: "压缩阈值" })).toHaveAttribute(+ "aria-valuenow",+ String(asked),+ );+});diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 82dc8368..2a7a87cb 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -800,19 +800,17 @@ export function ChatPage() {* Compaction settings are re-read by the engine at every compaction checkpoint, so this* applies to the conversation on screen without waiting for a rotation — which is what the* toast says. Rejecting rather than swallowing the failure is what keeps the dialog open on- * the value the user typed.+ * the value the user typed, and the dialog is what says why: it draws the reason in its own+ * card next to the Save that retries it (context-gauge.tsx), instead of a toast above it.*/const onChangeCompactionLimit = useCallback(async (maxContextLength: number): Promise<void> => {if (!projectId || !selectedAgentId) return;- try {- await api.putAgentConfig(projectId, selectedAgentId, {- config: { compaction: { maxContextLength } },- });- } catch (e) {- toastError(apiErrorText(e));- throw e;- }+ // Rejects when the write was refused, which is what keeps the confirmation that asked for+ // it open on the typed number — and that card is what draws the reason (context-gauge.tsx).+ await api.putAgentConfig(projectId, selectedAgentId, {+ config: { compaction: { maxContextLength } },+ });setCompactionLimit(configuredCompactionLimit(maxContextLength));setAgentConfigTick((n) => n + 1);toastSuccess(S.chat.contextThresholdSaved(humanizeTokens(maxContextLength)));diff --git a/packages/web/src/features/chat/context-gauge.tsx b/packages/web/src/features/chat/context-gauge.tsxindex 7166b814..988a2a36 100644--- a/packages/web/src/features/chat/context-gauge.tsx+++ b/packages/web/src/features/chat/context-gauge.tsx@@ -93,6 +93,7 @@ import { formatPercent, humanizeTokens } from "../../lib/format";import { S } from "../../lib/strings";import { contextComposition } from "./context-parts";import type { ContextPartKey } from "./context-parts";+import { contextThresholdRefused } from "./context-threshold-refusal";/*** Panel geometry. The width is applied inline rather than as a `w-*` class because the same@@ -166,9 +167,9 @@ export function ContextGauge({agentName?: string;/*** Writes a new `compaction.max_context_length` to the Agent and re-reads the config this- * gauge was given, rejecting when the write failed (the caller reports it). Its absence- * leaves the cutter a readout: a composer with no Agent config to write back to must not- * offer to change one.+ * gauge was given, rejecting when the write failed — this file draws that reason inside the+ * confirmation that asked, next to the Save that retries. Its absence leaves the cutter a+ * readout: a composer with no Agent config to write back to must not offer to change one.*/onChangeCompactionLimit?: (maxContextLength: number) => Promise<void>;}) {@@ -184,6 +185,13 @@ export function ContextGauge({const [pendingThreshold, setPendingThreshold] = useState<number | null>(null);const [proposal, setProposal] = useState<number | null>(null);const [savingThreshold, setSavingThreshold] = useState(false);+ /**+ * The confirmation's own account of a write it asked for and the server refused, kept until+ * the next attempt: the card stays open on the edited value (the Save in it is the retry), so+ * the reason belongs in that card — a toast would sit above a dialog the person is still+ * looking at, and be gone before the second press (7.19's rule, app-wide).+ */+ const [thresholdRefusal, setThresholdRefusal] = useState<string | null>(null);// Bumped after a successful write: the panel's data is a snapshot from when it opened, and// its `compactionThreshold` would otherwise keep overriding the fresher value the config// refetch just produced.@@ -211,16 +219,30 @@ export function ContextGauge({const confirmThreshold = async (tokens: number): Promise<void> => {if (!onChangeCompactionLimit) return;setSavingThreshold(true);+ // The card's previous answer belonged to the attempt before this press, not to this one.+ setThresholdRefusal(null);try {await onChangeCompactionLimit(tokens);setProposal(null);setReloadTick((n) => n + 1);- } catch {- // Reported by the caller; the dialog stays open on its edited value.+ } catch (e) {+ // The dialog stays open on its edited value, and it is the dialog that says why: the+ // cutter proposed a number, the Save wrote it, and neither moved.+ setThresholdRefusal(contextThresholdRefused(tokens, e));} finally {setSavingThreshold(false);}};+ /** A newly proposed value starts without the previous attempt's reason. */+ const proposeThreshold = (tokens: number): void => {+ setThresholdRefusal(null);+ setProposal(tokens);+ };+ /** Closing the card ends the question: the reason it held has nothing left to sit under. */+ const closeThresholdDialog = (): void => {+ setProposal(null);+ setThresholdRefusal(null);+ };// The ring draws no numbers, so its accessible name carries them: the ratio AND the figures it// was computed from, which is all the subagent composer's panel-less ring can offer.@@ -272,7 +294,7 @@ export function ContextGauge({editable={onChangeCompactionLimit !== undefined}pendingThreshold={pendingThreshold}onPendingThreshold={setPendingThreshold}- onProposeThreshold={(tokens) => setProposal(tokens)}+ onProposeThreshold={proposeThreshold}/></div>,document.body,@@ -284,7 +306,8 @@ export function ContextGauge({proposed={proposal}contextWindow={win}busy={savingThreshold}- onClose={() => setProposal(null)}+ refusal={thresholdRefusal}+ onClose={closeThresholdDialog}onConfirm={confirmThreshold}/>)}@@ -752,6 +775,7 @@ function ThresholdDialog({proposed,contextWindow,busy,+ refusal,onClose,onConfirm,}: {@@ -762,6 +786,8 @@ function ThresholdDialog({proposed: number;contextWindow: number | undefined;busy: boolean;+ /** The words for a write this card asked for and the server refused, or null when nothing was. */+ refusal: string | null;onClose: () => void;onConfirm: (tokens: number) => void;}) {@@ -779,6 +805,7 @@ function ThresholdDialog({cancelLabel={S.common.cancel}confirmDisabled={!valid}busy={busy}+ {...(refusal !== null ? { refusal } : {})}onClose={onClose}onConfirm={() => {if (valid) onConfirm(tokens);diff --git a/packages/web/src/features/chat/context-threshold-refusal.ts b/packages/web/src/features/chat/context-threshold-refusal.tsnew file mode 100644index 00000000..1d59cf4b--- /dev/null+++ b/packages/web/src/features/chat/context-threshold-refusal.ts@@ -0,0 +1,24 @@+/**+ * The context panel's threshold cutter: the sentence a refused write leaves inside the+ * confirmation that asked for it, and why it is drawn there instead of arriving as a toast.+ *+ * The cutter never writes straight through: a release (or Enter) opens a confirmation naming the+ * Agent and the threshold it is about to replace, and the Save in that card performs the write.+ * The card stays open on the edited value when the write is refused — the Save is the retry — so+ * the reason belongs inside the same card, right under its sentence. It used to arrive only as a+ * notification: the card that asked the question then sat there looking unanswered, and after six+ * seconds nothing on screen said why the threshold had not moved (7.19's rule, app-wide).+ *+ * Which words: `refusalText`, the rule every refusal slot in the app follows — an answer the+ * server gave is read through its code's own localized sentence, and a value this codebase raised+ * itself is shown as it wrote it. The sentence names the threshold that was asked for, because the+ * Agent still holds the old one and the dialog's field is the only place the new number lives.+ */+import { refusalText } from "../../lib/api-error";+import { humanizeTokens } from "../../lib/format";+import { S } from "../../lib/strings";++/** The line the threshold confirmation draws under its sentence after a refused write. */+export function contextThresholdRefused(tokens: number, error: unknown): string {+ return S.chat.contextThresholdRefused(humanizeTokens(tokens), refusalText(error));+}diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 90a14d9a..d681356f 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -3836,6 +3836,9 @@ export const en: Strings = {`Above the model window — the threshold in force will be ${n}`,contextThresholdSaved: (n: string): string =>`Compaction threshold changed to ${n}; it applies immediately`,+ /** Refused write, drawn inside the confirmation that asked: n = the threshold that was asked for, reason = the server's words (or ours). */+ contextThresholdRefused: (n: string, reason: string): string =>+ `The compaction threshold was not changed to ${n} — the Agent still has the old value: ${reason}`,contextWindowUnderThreshold: (n: string, m: string): string =>`This model's context window ${n} is smaller than this agent's compaction threshold ${m}, so compaction actually fires at the edge of the window. Drag the dashed mark in the context panel, or set the threshold below the window in the agent settings — it applies immediately.`,contextWindowUnderThresholdAction: "Open agent settings",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex f171906a..3d163c62 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -3903,6 +3903,9 @@ export const zh = {contextThresholdInvalid: "必须是大于 0 的整数",contextThresholdCapped: (n: string): string => `超出模型窗口,实际生效的阈值是 ${n}`,contextThresholdSaved: (n: string): string => `压缩阈值已改为 ${n},立即生效`,+ /** Refused write, drawn inside the confirmation that asked: n = the threshold that was asked for, reason = the server's words (or ours). */+ contextThresholdRefused: (n: string, reason: string): string =>+ `压缩阈值没有改成 ${n},Agent 上仍然是原来的值:${reason}`,/** Composer notice: the model's window is below the Agent's configured compaction threshold; n = window, m = threshold. */contextWindowUnderThreshold: (n: string, m: string): string =>`当前模型的上下文窗口 ${n} 小于本 Agent 的压缩阈值 ${m},压缩实际会在窗口边缘触发。拖动上下文面板里的虚线或在 Agent 设置中把阈值调到窗口以下,立即生效。`,diff --git a/packages/web/test/context-threshold-refusal.test.ts b/packages/web/test/context-threshold-refusal.test.tsnew file mode 100644index 00000000..558866c9--- /dev/null+++ b/packages/web/test/context-threshold-refusal.test.ts@@ -0,0 +1,65 @@+/**+ * A compaction threshold the write refused (src/features/chat/context-threshold-refusal.ts):+ * which words the confirmation that asked for the write uses.+ *+ * The card stays open on the edited value and the Agent keeps the threshold it had, so the+ * sentence is the only thing saying the write did not land — and it must name the number that was+ * asked for, because that number lives nowhere else once the card is closed. Three things it has+ * to get right: a server answer speaks the interface's own language rather than the wire message,+ * a write that never reached the route keeps what it knows (7.19's rule), and an error with+ * nothing to say falls back to the generic text. The figures go through `humanizeTokens`, so the+ * sentence reads the same as the field and the ring above it.+ */+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 { humanizeTokens } from "../src/lib/format";+import { contextThresholdRefused } from "../src/features/chat/context-threshold-refusal";++afterEach(() => {+ setActiveStrings(ZH);+});++describe("contextThresholdRefused", () => {+ it("reads a refusal through the code's own sentence, not the wire message", () => {+ const line = contextThresholdRefused(180000, new ApiError(500, "internal", "RAW ENGLISH"));+ expect(line).not.toContain("RAW ENGLISH");+ expect(line).toBe(+ S.chat.contextThresholdRefused(humanizeTokens(180000), S.errors.byCode.internal as string),+ );+ });++ it("keeps what a write that never reached the route has to say", () => {+ expect(contextThresholdRefused(60000, new Error("Failed to fetch"))).toBe(+ S.chat.contextThresholdRefused(humanizeTokens(60000), "Failed to fetch"),+ );+ });++ it("falls back to the generic text when the value has nothing to say", () => {+ expect(contextThresholdRefused(60000, undefined)).toBe(+ S.chat.contextThresholdRefused(humanizeTokens(60000), S.common.unknownError),+ );+ });++ it("names the threshold that was asked for, in the figures the field shows", () => {+ const line = contextThresholdRefused(180000, new Error("boom"));+ expect(line).toContain(humanizeTokens(180000));+ // The plain number would be unreadable next to a field that says 180k.+ expect(line).not.toContain("180000");+ });++ it("says the Agent still holds the old value", () => {+ expect(contextThresholdRefused(60000, new Error("boom"))).toContain("原来的值");+ });++ it("speaks the active language", () => {+ setActiveStrings(EN);+ expect(contextThresholdRefused(180000, new Error("boom"))).toBe(+ `The compaction threshold was not changed to ${humanizeTokens(180000)} — the Agent still has the old value: boom`,+ );+ expect(contextThresholdRefused(180000, new ApiError(500, "internal", "RAW"))).toBe(+ EN.chat.contextThresholdRefused(humanizeTokens(180000), EN.errors.byCode.internal as string),+ );+ });+});