A local-first multi-agent app development platform, built on PenguinHarness
fix(web,server): split thinking-level labels and title the compaction row by mode (#340)
Yaowei Zheng00d7934d39e1
diff --git a/changelog/unreleased/2026-08-19-thinking-label-and-compaction-notice.md b/changelog/unreleased/2026-08-19-thinking-label-and-compaction-notice.mdnew file mode 100644index 00000000..d41d7294--- /dev/null+++ b/changelog/unreleased/2026-08-19-thinking-label-and-compaction-notice.md@@ -0,0 +1,30 @@+# Thinking-level labels split by surface, and the compaction row names its mode++- **Date:** 2026-08-19+- **Type:** fix+- **Scope:** `web`, `server`+- **PR:** [#340](https://github.com/Prism-Shadow/penguin-harness/pull/340)++[中文版](2026-08-19-thinking-label-and-compaction-notice.zh.md)++Two corrections to what the UI prints. The Chinese thinking-level label stopped carrying the wire value on every surface and now carries it only where a tier is picked, and the compaction step started naming what it actually did — a step that clears the context is no longer announced as compaction — which left neither mode with an outcome line to write. The Trace page's round badge follows the same naming, which took the mode through the analysis DTO.++## Thinking-level labels++- `S.chat.thinkingLevelNames` became the plain tier name: zh reads 低 / 中 / 高 / 极高 / 最高, plus 无 for a stored legacy `none`; en keeps the wire value that has always been its name. Every surface showing a level that is already chosen reads it — the composer picker's trigger and tooltip in the draft and active-session controls alike, the mid-chat switch dialog and its toasts, and the Project chat-defaults control and its read-only row.+- `S.chat.thinkingLevelMenuName` composes the dropdown-row variant, appending the wire value the pick will send (`极高 (xhigh)`). The composer's own dropdown is its only caller: the Project chat-defaults control is a native `<select>`, which paints the picked option's own text onto the collapsed control, so annotating its rows would land the wire value back on a trigger.+- English gained no split. Its tier name already is the wire value, so `thinkingLevelMenuName` takes just the name and returns it unchanged instead of duplicating the table.+- A drift guard walks core's `DEFAULT_CHAT_THINKING_LEVELS` against both real dictionaries — previously the web tests only exercised a hand-written stub: every tier is named in both locales, no zh name carries latin letters or parentheses, and the menu variant carries the wire value.++## Compaction row++- The row's title names its mode. A `summarize` step stays 压缩 / "Compaction"; a `discard` step became 清空 / "Clear", because it drops the old context rather than compacting it, and labelling that compaction was the confusing part.+- With the mode in the title, a settled row writes no outcome text in either mode: it renders as status icon, title and wall time, plus — on a `summarize` — the chevron that opens the adopted summary. The `已丢弃旧上下文` / "old context discarded" strings and the `compactionDone` helper that chose between them were deleted from both catalogs.+- The running row stopped repeating the mode as a raw `summarize` / `discard` in its detail slot; that was the untranslated wire value, and the title carries it now.+- A failed or aborted compaction still states why, in both modes: the reason is the one thing the title cannot carry.++## Trace page++- The round card's compaction badge names the mode too, reusing the conversation row's title rather than a Trace-local string so the two surfaces cannot drift apart: a discarded round reads 清空 / "Clear". The Trace-only `compactionRound` string was deleted rather than left as a second copy of the word.+- `TraceTaskStats` gained `compactionMode`, carried **beside** the existing `compaction` flag rather than replacing it. The flag stays the sole gate on "is this a compaction turn", so a client reading only the boolean is unaffected; an absent mode reads as `summarize`, which is what the badge always showed.+- A discarded round is flagged as a compaction turn at all now. It issues no model request — core emits `compaction_begin` and `compaction_end` back to back — and the flag was only ever set from the compaction request, so such a round used to render as a bare card carrying no badge and no stats. It is flagged from its own `compaction_begin` instead, which lands on the same turn for a summarize.diff --git a/changelog/unreleased/2026-08-19-thinking-label-and-compaction-notice.zh.md b/changelog/unreleased/2026-08-19-thinking-label-and-compaction-notice.zh.mdnew file mode 100644index 00000000..fb33d315--- /dev/null+++ b/changelog/unreleased/2026-08-19-thinking-label-and-compaction-notice.zh.md@@ -0,0 +1,30 @@+# 思考等级标签按界面分化,压缩行改为按模式命名++- **Date:** 2026-08-19+- **Type:** fix+- **Scope:** `web`, `server`+- **PR:** [#340](https://github.com/Prism-Shadow/penguin-harness/pull/340)++[English](2026-08-19-thinking-label-and-compaction-notice.md)++界面上的两处显示修正。中文的思考等级标签不再处处带上线路值,只在挑选档位的地方带;压缩步骤则改为如实说明它做了什么——清空上下文的那一步不再被报成压缩——两种模式因此都不必再写结果文案。Trace 页的轮次徽标沿用同一套命名,为此把模式一路带过了分析 DTO。++## 思考等级标签++- `S.chat.thinkingLevelNames` 改为纯粹的档位名:中文读作 低 / 中 / 高 / 极高 / 最高,历史遗留的 `none` 另有 无;英文仍是它一贯的名字,即线路值本身。凡是展示「已选定档位」的界面都读它——草稿态与活动会话两个输入框选择器的按钮与悬浮提示、对话中途的切换确认框及其 toast,以及 Project 对话缺省值的控件与其只读视图。+- `S.chat.thinkingLevelMenuName` 负责组合下拉行的变体,在名字后附上这次挑选将要发送的线路值(`极高 (xhigh)`)。只有输入框自己的下拉菜单调用它:Project 对话缺省值用的是原生 `<select>`,它会把选中项自身的文字画到收起后的控件上,给行加注解等于把线路值又送回了按钮。+- 英文没有分化。它的档位名本就是线路值,所以 `thinkingLevelMenuName` 只接名字并原样返回,不去复制一份表。+- 新增一道防漂移测试,用 core 的 `DEFAULT_CHAT_THINKING_LEVELS` 去核对两份真实词典——此前 Web 的测试只跑一个手写替身:每个档位在两种语言下都有名字,中文名一律不含拉丁字母与圆括号,而带注解的变体必须含有线路值。++## 压缩行++- 该行的标题改为标明自身模式。`summarize` 一步仍叫 压缩 / "Compaction";`discard` 一步改叫 清空 / "Clear"——它丢的是旧上下文,并没有压缩什么,把这一步称作压缩正是让人困惑的地方。+- 模式落到标题上之后,settled 状态两种模式都不再写结果文案:只呈现状态图标、标题与耗时,`summarize` 另有那个点开就是既得摘要的折叠箭头。`已丢弃旧上下文` / "old context discarded" 两条文案,连同在它们之间做选择的 `compactionDone`,一并从两份词典中删除。+- 运行中的那一行也不再把模式作为原始的 `summarize` / `discard` 重复到 detail 槽位;那是未翻译的线路值,如今标题已经承担了它。+- 失败或中断的压缩仍会说明原因,两种模式皆然:原因正是标题带不了的那部分。++## Trace 页++- 轮次卡片上的压缩徽标同样标明模式,且直接复用对话行的标题、不再另起一份 Trace 专用文案,两处便无从走样:被丢弃的那一轮读作 清空 / "Clear"。Trace 专用的 `compactionRound` 一条随之删除,不留第二份同义文案。+- `TraceTaskStats` 新增 `compactionMode`,**并列**在既有的 `compaction` 标志旁边,而非取而代之。标志仍是判定「这是不是压缩轮」的唯一依据,只读布尔值的旧客户端不受影响;模式缺失时按 `summarize` 理解,也就是徽标一贯显示的那个。+- 被丢弃的那一轮现在才真正被标记为压缩轮。它不发起任何模型请求——core 把 `compaction_begin` 与 `compaction_end` 背靠背地发出——而此前该标志只在压缩请求处设置,于是这样一轮渲染出来是一张既无徽标也无统计的空卡片。改为依据它自己的 `compaction_begin` 标记,`summarize` 的情形落在同一轮上。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 53bcefe7..d34465e2 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -13,7 +13,11 @@* Docs: packages/docs/content/server-api.{zh,en}.md (site path /docs/server-api) is the* public route/SSE reference for this contract — keep it in sync when changing DTOs.*/-import type { OmniMessage, ToolCallPayload } from "@prismshadow/penguin-core/omnimessage";+import type {+ CompactionMode,+ OmniMessage,+ ToolCallPayload,+} from "@prismshadow/penguin-core/omnimessage";import type {MCPServerConfig,ThinkingLevelName,@@ -1408,12 +1412,22 @@ export interface TraceTaskStats {taskIndex: number;/*** This turn is a **compaction turn** (compaction forms its own turn); the UI marks it with- * a "Compaction" badge accordingly. It's treated the same as a user turn: it has Token /+ * a badge accordingly. It's treated the same as a user turn: it has Token /* cost / duration / TPS, and **counts normally toward global stats** — the global totals are* just the sum of the per-turn cards below, the two scopes match, so adding up the per-turn* numbers must equal the total.*/compaction?: boolean;+ /**+ * Which kind of compaction turn it is, from the turn's `compaction_begin`. Additive beside+ * the flag rather than folded into it: `compaction` stays the sole gate on "is this a+ * compaction turn", so a client that only knows the boolean keeps working unchanged, and one+ * that reads this can name the turn for what it did — the two modes are different operations,+ * and only `summarize` actually compacts anything (`discard` drops the old context outright).+ * Absent on a turn analyzed before this field existed, or whose `compaction_begin` carried no+ * mode; treat an absent value as `summarize`, which is what the badge said before the split.+ */+ compactionMode?: CompactionMode;/*** This turn's message index range within the **entire file** (inclusive). A single* sequential scan on the server tells which turn each message belongs to; the frontenddiff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.tsindex 921d9762..084d93f0 100644--- a/packages/server/src/services/trace-service.ts+++ b/packages/server/src/services/trace-service.ts@@ -27,7 +27,7 @@ import {scratchpadDir,tracesDir,} from "@prismshadow/penguin-core";-import type { OmniMessage } from "@prismshadow/penguin-core";+import type { CompactionMode, OmniMessage } from "@prismshadow/penguin-core";import type {AgentTraceSessionEntry,AgentTracesResponse,@@ -843,6 +843,12 @@ export class TraceService {// compaction request entirely from TPS — matching the same convention as// compactionActive in the Chat page's task-stats.let compactionActive = false;+ // The active compaction's mode, read off its `compaction_begin`, so the turn can be+ // reported as the operation it actually was: `discard` drops the old context outright and+ // compacts nothing, so calling it a compaction turn in the UI reads wrong. Null outside a+ // compaction and for a `compaction_begin` carrying no recognizable mode — the DTO field is+ // then simply left absent, which consumers read as the historical `summarize`.+ let compactionMode: CompactionMode | null = null;// Token / duration totals per Task (computed server-side over the whole file:// frontend events are fetched in pages, so summing them there would be// mismatched).@@ -963,7 +969,12 @@ export class TraceService {requests.push(openRequest);if (!hasOrigin) {const t = ensureTask(taskIndex);- if (compactionActive) t.compaction = true; // This turn is a compaction turn+ if (compactionActive) {+ t.compaction = true; // This turn is a compaction turn+ // Carried alongside the flag, never instead of it: the flag stays the sole gate+ // on "is this a compaction turn" for clients that predate the mode.+ if (compactionMode !== null) t.compactionMode = compactionMode;+ }// This turn's duration starts at the first request_begin. It doesn't// use the timestamp of the user Prompt / compaction summary or other// user text: `[context_summary]` is created during compaction but only@@ -1073,6 +1084,8 @@ export class TraceService {if (!hasOrigin) {continuation = false;compactionActive = true;+ const mode = p.mode;+ compactionMode = mode === "summarize" || mode === "discard" ? mode : null;}} else if (p.type === "compaction_end") {// Both ends of compaction break a continuation. This closing one can't@@ -1083,6 +1096,7 @@ export class TraceService {if (!hasOrigin) {continuation = false;compactionActive = false;+ compactionMode = null;}} else if (p.type === "token_usage") {const request = p.request as@@ -1219,6 +1233,20 @@ export class TraceService {const t = ensureTask(ti);if (t.messageFrom < 0 || k < t.messageFrom) t.messageFrom = k;if (k > t.messageTo) t.messageTo = k;+ // Flag the compaction turn from its own `compaction_begin` rather than only from the+ // compaction request: a `discard` issues no request at all (core emits begin/end+ // back-to-back, see context-engine's discardContext), so keying off request_begin alone+ // left a discarded round as a bare, unlabelled card. Attribution has resolved the owning+ // turn by this pass, and for `summarize` it lands on the same turn the request-side path+ // already flagged. Subagent messages are skipped for the same reason the main loop skips+ // them — a child's compaction is not this turn's.+ const cur = messages[k]!;+ const cp = cur.payload as { type?: string; mode?: unknown };+ const fromSubagent = cur.origin !== undefined && cur.origin.length > 0;+ if (!fromSubagent && cur.type === "event_msg" && cp.type === "compaction_begin") {+ t.compaction = true;+ if (cp.mode === "summarize" || cp.mode === "discard") t.compactionMode = cp.mode;+ }// session_meta is only **listed** in the first turn, and doesn't count// toward the end-of-turn time: it's metadata written when the session was// created, and its timestamp has nothing to do with this turn (it also getsdiff --git a/packages/server/test/trace-service.test.ts b/packages/server/test/trace-service.test.tsindex 830a9912..5e36d798 100644--- a/packages/server/test/trace-service.test.ts+++ b/packages/server/test/trace-service.test.ts@@ -306,7 +306,12 @@ describe("trace-service", () => {// The compaction turn is flagged (the UI shows a "compaction" badge); its// duration is measured from its request_begin (10:00:05) to compaction_end (10:00:16).expect(ct.compaction).toBe(true);+ // ...and carries WHICH compaction it was, so the round card can name the operation rather+ // than calling every mode "compaction". The flag stays the sole gate on "is this a+ // compaction turn", so a client that only knows the boolean is unaffected.+ expect(ct.compactionMode).toBe("summarize");expect(t.compaction).toBeUndefined();+ expect(t.compactionMode).toBeUndefined();expect(Date.parse(ct.endTs) - Date.parse(ct.startTs)).toBe(11_000);// Overall elapsed time = **the sum of every turn (including compaction turns)**,// matching the same scope as the per-turn display — adding up the durations@@ -316,6 +321,44 @@ describe("trace-service", () => {expect(a.elapsedMs).toBe(2_100 + 11_000);});+ it("a discard compaction turn is flagged and carries mode 'discard', though it issues no request", async () => {+ // `discard` drops the old context outright instead of summarizing it, and core emits+ // compaction_begin/compaction_end back-to-back with **no request in between** (see+ // context-engine's discardContext). It still forms its own turn — so the round card must+ // be flagged from the compaction_begin itself, not from a compaction request that never+ // happens, or a discarded round renders as a bare unlabelled card with no stats.+ await writeTraceFile(root, P, A, "2026-07-06", S, 1, [+ sessionMeta(metaPayload()),+ at("2026-07-06T10:00:00.000Z", userText("hi")),+ at("2026-07-06T10:00:01.000Z", requestBegin()),+ at("2026-07-06T10:00:03.000Z", requestEnd("completed")),+ at("2026-07-06T10:00:03.100Z", tokenUsage(counts(30_000), buckets(20_000, 9_000, 1_000))),+ at(+ "2026-07-06T10:00:04.000Z",+ compactionBegin({ reason: "context", mode: "discard", context: 30_000, turns: 2 }),+ ),+ at(+ "2026-07-06T10:00:04.100Z",+ compactionEnd({ reason: "context", mode: "discard", status: "completed" }),+ ),+ ]);+ const a = await service.analyze(P, A, S, 1);++ expect(a.compactionCount).toBe(1);+ expect(a.tasks.map((t) => t.taskIndex)).toEqual([0, 1]);+ // The user turn is untouched...+ expect(a.tasks[0]!.compaction).toBeUndefined();+ expect(a.tasks[0]!.compactionMode).toBeUndefined();+ // ...and the discard turn is flagged and named, so the badge reads "clear", not "compaction".+ const ct = a.tasks[1]!;+ expect(ct.compaction).toBe(true);+ expect(ct.compactionMode).toBe("discard");+ // It really did run no request: no duration to report, which is exactly why the badge is+ // the only thing on the card that explains what the round was.+ expect(ct.startTs).toBe("");+ expect(ct.llmMs).toBe(0);+ });+it("a compaction request exhausting retries (ending in timeout) doesn't fold the next user turn into the compaction Task", async () => {// The intersection of "timeout → continuation" and "compaction is its own// turn": when a compaction request exhausts its retries and ends in timeout,diff --git a/packages/web/e2e/compaction.spec.mjs b/packages/web/e2e/compaction.spec.mjsindex aa68dd31..cf87400a 100644--- a/packages/web/e2e/compaction.spec.mjs+++ b/packages/web/e2e/compaction.spec.mjs@@ -67,10 +67,13 @@ test("compaction mid-turn: the reply's stats line is still reachable by hoveringconst reply = page.getByText("Command finished; the result looks as expected.").first();await expect(reply).toBeVisible();- // The compaction row is a step banner: a disclosure button reading "压缩" plus its outcome.+ // The compaction row is a step banner: a disclosure button titled by its MODE — "压缩" for+ // this summarize, "清空" for a discard, which drops the context rather than compacting it.const banner = page.locator("button[aria-expanded]").filter({ hasText: "压缩" }).first();await expect(banner).toBeVisible();- await expect(banner).toContainText("已切换到摘要后的新上下文");+ // A succeeded row writes no outcome text: the title, the wall time and the chevron say it all,+ // and the summary itself is behind the disclosure.+ await expect(banner).not.toContainText("已切换到摘要后的新上下文");// The row doesn't show Token counts: compaction at round end isn't attributed to this round// (its usage shows up in the Session total and the Trace page's compaction-round carddiff --git a/packages/web/e2e/draft.spec.mjs b/packages/web/e2e/draft.spec.mjsindex 17bb3f40..61c8606b 100644--- a/packages/web/e2e/draft.spec.mjs+++ b/packages/web/e2e/draft.spec.mjs@@ -99,18 +99,22 @@ test("draft: pick model/approval -> reload restores them -> send creates the ses// Conversation-time thinking level (backed by the Agent settings): the picker shows the// seeded default (medium); the menu carries a title bar and the rows 低/中/高/极高/最高// only — no descriptions, no default row, and no 无 (many models cannot disable thinking).- // Each row is labelled with the wire value it sends, so the names read "高 (high)".- // Picking 高 (high) writes straight through to the Agent config, so the session created on- // send runs with it and it becomes the Agent's new default.+ // The label splits by surface: a MENU ROW is where the tier is chosen, so it annotates the+ // name with the wire value it sends ("高 (high)"), while the TRIGGER shows the plain Chinese+ // name alone ("高") — asserted both ways below, since a trigger that kept the annotation is+ // how this split silently half-lands. Picking 高 writes straight through to the Agent config,+ // so the session created on send runs with it and it becomes the Agent's new default.const thinkingBtn = page.getByRole("button", { name: "思考等级" });- await expect(thinkingBtn).toContainText("中 (medium)");+ await expect(thinkingBtn).toContainText("中");+ await expect(thinkingBtn).not.toContainText("medium");await thinkingBtn.click();await expect(page.getByText("思考等级", { exact: true })).toBeVisible(); // menu title barawait expect(page.getByRole("button", { name: "低 (low)", exact: true })).toBeVisible();await expect(page.getByRole("button", { name: "最高 (max)", exact: true })).toBeVisible();await expect(page.getByRole("button", { name: "无 (none)", exact: true })).toHaveCount(0);await page.getByRole("button", { name: "高 (high)", exact: true }).click();- await expect(thinkingBtn).toContainText("高 (high)");+ await expect(thinkingBtn).toContainText("高");+ await expect(thinkingBtn).not.toContainText("high");await expect.poll(async () => {const cfg = await (diff --git a/packages/web/e2e/reloaded-followup.spec.mjs b/packages/web/e2e/reloaded-followup.spec.mjsindex 992910ef..9602754b 100644--- a/packages/web/e2e/reloaded-followup.spec.mjs+++ b/packages/web/e2e/reloaded-followup.spec.mjs@@ -87,22 +87,25 @@ test("a stale steer response after reload queues the follow-up instead of strand// This conversation already has history, so the mid-chat switch guard (#310) stages the// pick behind its dialog instead of applying it. Cancel first: the guard must leave the// displayed level exactly where it was, never half-applied.+ // The trigger carries the plain Chinese name ("中"); only the menu rows annotate it with the+ // wire value ("高 (high)"), which is why the two are matched differently here.const thinkingBtn = page.getByRole("button", { name: "思考等级" });- await expect(thinkingBtn).toContainText("中 (medium)");+ await expect(thinkingBtn).toContainText("中");+ await expect(thinkingBtn).not.toContainText("medium");await thinkingBtn.click();await page.getByRole("button", { name: "高 (high)", exact: true }).click();// The dialog's title is its accessible name, not body text — assert on its choices.await expect(page.getByRole("button", { name: "仍要切换", exact: true })).toBeVisible();await expect(page.getByRole("button", { name: "压缩后切换", exact: true })).toBeDisabled();await page.getByRole("button", { name: "取消", exact: true }).click();- await expect(thinkingBtn).toContainText("中 (medium)");+ await expect(thinkingBtn).toContainText("中");// Now switch for real: a compaction cannot start while the task runs, so "压缩后切换" is// disabled here and "仍要切换" is the applying choice.await thinkingBtn.click();await page.getByRole("button", { name: "高 (high)", exact: true }).click();await page.getByRole("button", { name: "仍要切换", exact: true }).click();- await expect(thinkingBtn).toContainText("高 (high)");+ await expect(thinkingBtn).toContainText("高");await composer.fill("hello after reload");const followUpPost = page.waitForResponse((response) =>diff --git a/packages/web/src/components/layout/project-dialogs.tsx b/packages/web/src/components/layout/project-dialogs.tsxindex 28bc98dc..13855b99 100644--- a/packages/web/src/components/layout/project-dialogs.tsx+++ b/packages/web/src/components/layout/project-dialogs.tsx@@ -600,6 +600,11 @@ function ChatDefaultsSection({ projectId, isOwner }: { projectId: string; isOwne</option>))}</Select>+ {/* Plain tier names, not the composer dropdown's annotated variant: a native+ <select> paints the picked option's own text on the collapsed control, so+ annotating the rows here would also put "(xhigh)" on what is, once closed,+ a trigger. Matches the approval-mode select directly above, whose options+ are plain localized names too. */}<Selectlabel={S.chat.thinkingLevel}size="sm"diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsxindex fcccce5e..fc6564f6 100644--- a/packages/web/src/features/chat/chat-input.tsx+++ b/packages/web/src/features/chat/chat-input.tsx@@ -404,7 +404,7 @@ function ThinkingLevelSelect({</button>}>- {/* Title bar: names the control (the rows themselves are just the short names). */}+ {/* Title bar: names the control (the rows themselves are just the tier names). */}<div className="border-b border-gray-100 px-3 pb-1.5 pt-0.5 text-xs font-semibold text-gray-500 dark:border-gray-800 dark:text-gray-400">{S.chat.thinkingLevel}</div>@@ -422,8 +422,11 @@ function ThinkingLevelSelect({: "text-gray-600 dark:text-gray-400"}`}>+ {/* The one surface that annotates: a menu row is where the tier is CHOSEN, so it+ names the wire value the pick will send. The trigger above stays the plain+ name — in zh that is 低/中/高/极高/最高, in en the annotation is a no-op. */}<span className="min-w-0 flex-1 truncate">- {S.chat.thinkingLevelNames[level] ?? level}+ {S.chat.thinkingLevelMenuName(S.chat.thinkingLevelNames[level] ?? level, level)}</span><span className="w-3 shrink-0 text-center">{level === value ? "✓" : ""}</span></button>diff --git a/packages/web/src/features/chat/compaction-banner.tsx b/packages/web/src/features/chat/compaction-banner.tsxindex a4d75e14..fb7227d1 100644--- a/packages/web/src/features/chat/compaction-banner.tsx+++ b/packages/web/src/features/chat/compaction-banner.tsx@@ -1,7 +1,14 @@/*** Compaction row: one StepBanner across running/done/failed (same shell as the MCP- * connect row and the reasoning-&-tools group header) — mode while running, outcome plus- * wall time once settled, failures on a single line.+ * connect row and the reasoning-&-tools group header) — wall time once settled, failures+ * on a single line.+ *+ * **The title names the mode**, so the two modes read as the two different things they are:+ * a `summarize` row is 压缩 / "Compaction", a `discard` row is 清空 / "Clear" — it drops the+ * old context rather than compacting it, and calling that "compaction" was the confusing part+ * (per maintainer request). With the mode in the title neither outcome needs a detail line:+ * a succeeded row is icon + title + wall time (+ chevron on a summarize), and the detail slot+ * is left for the one thing the title cannot say — why a compaction failed.** The summary is **collapsed by default, exactly like a thinking block**: the row carries* the chevron from the moment a summarize compaction starts, and the text the compaction@@ -41,12 +48,13 @@ export function CompactionBanner({ item }: { item: CompactionItem }) {const expandable = summary !== "" || (item.running && item.mode === "summarize");const body = expandable ? <SummaryBody text={summary} streaming={item.running} /> : null;+ // The title carries the mode in both states, so the running row no longer repeats it as a+ // raw `summarize`/`discard` in the detail slot — that was the untranslated wire value.if (item.running) {return (<StepBannerstate="running"- title={S.chat.compactionTitle}- detail={item.mode}+ title={S.chat.compactionTitle(item.mode)}{...(item.beginTsMs !== undefined ? { liveSinceMs: item.beginTsMs } : {})}>{body}@@ -57,12 +65,10 @@ export function CompactionBanner({ item }: { item: CompactionItem }) {return (<StepBannerstate={ok ? "done" : "failed"}- title={S.chat.compactionTitle}- detail={- ok- ? S.chat.compactionDone(item.mode)- : S.chat.compactionFailed(item.status ?? "failed", item.errorMessage)- }+ title={S.chat.compactionTitle(item.mode)}+ // Success says everything through the title, the icon and the wall time; only a failure+ // still needs a line, because its reason is the part the title cannot carry.+ detail={ok ? undefined : S.chat.compactionFailed(item.status ?? "failed", item.errorMessage)}{...(item.durationMs !== undefined ? { durationMs: item.durationMs } : {})}>{body}diff --git a/packages/web/src/features/chat/thinking-level.ts b/packages/web/src/features/chat/thinking-level.tsindex fc88f6d2..a7291ca1 100644--- a/packages/web/src/features/chat/thinking-level.ts+++ b/packages/web/src/features/chat/thinking-level.ts@@ -17,6 +17,12 @@* "default" row) under a title bar naming the control — and they do **not** offer "none"* (many models cannot disable thinking): "none" stays a valid stored/wire value, so a* legacy config or trace that carries it still displays via the label table below.+ *+ * The name comes in two variants, split by surface: `S.chat.thinkingLevelNames` is the plain+ * tier name and belongs on anything DISPLAYING a settled level (trigger, tooltip, switch+ * dialog, toasts, the Project read-only row), while `S.chat.thinkingLevelMenuName` composes+ * the dropdown-row variant that also names the wire value being picked. Only zh actually+ * differs between the two — an English name already is its wire value.*//** All stored/wire levels, for display lookup (mirrors core's ThinkingLevelName). */@@ -49,7 +55,9 @@ export function effectiveThinkingLevel(}/**- * Short display label for a level from the localized name table (S.chat.thinkingLevelNames).+ * Plain display label for a level from the localized name table (S.chat.thinkingLevelNames) —+ * the variant for surfaces that show a level already chosen, so it carries no wire-value+ * annotation; a dropdown row wraps this through `S.chat.thinkingLevelMenuName` instead.* Covers every stored level including "none" (so a legacy value displays sanely instead* of being rewritten or hidden). Returns null for anything else — including "" (an Agent* without an explicit override) and session_meta's "default" — so callers can render adiff --git a/packages/web/src/features/traces/trace-file-view.tsx b/packages/web/src/features/traces/trace-file-view.tsxindex 34a04404..675f7a46 100644--- a/packages/web/src/features/traces/trace-file-view.tsx+++ b/packages/web/src/features/traces/trace-file-view.tsx@@ -54,6 +54,21 @@ import { TimelineChart } from "./timeline-chart";import type { TraceHighlight } from "./timeline-chart";import { EventRow } from "./trace-event-row";+/**+ * Badge text for a round card, or null when the round is not a compaction turn.+ *+ * Reuses the chat stream's mode-aware row title rather than a Trace-local string, so the two+ * surfaces cannot drift apart: a `discard` round reads 清空 / "Clear" here exactly as it does+ * in the conversation, because it drops the old context instead of compacting it.+ *+ * `compaction` stays the sole gate — a round analyzed before the server carried the mode has+ * no `compactionMode`, and falls back to the compaction title the badge always showed.+ */+export function compactionBadgeLabel(st: TraceTaskStats | undefined): string | null {+ if (st?.compaction !== true) return null;+ return S.chat.compactionTitle(st.compactionMode ?? "summarize");+}+/*** The three Token buckets (token_usage.request). No `total` field: usage is* always shown broken down, and the total = input (cacheRead + cacheWrite) +@@ -460,6 +475,7 @@ export function TraceFileView({const st = statsByTask.get(t.taskIndex);const ctx = st?.context;const tokens = st?.tokens ?? zeroBuckets();+ const compactionBadge = compactionBadgeLabel(st);return (<divkey={t.taskIndex}@@ -477,10 +493,12 @@ export function TraceFileView({</span>{/* Compaction rounds are explicitly flagged: their Token /cost / duration / TPS count toward the global summary just- like user rounds do, and this badge answers "this round isn't answering the user, it's compacting context". */}- {st?.compaction === true && (+ like user rounds do, and this badge answers "this round isn't answering the+ user, it's housekeeping" — naming which housekeeping, since a discard round+ clears the context rather than compacting it. */}+ {compactionBadge !== null && (<span className="shrink-0 rounded bg-gray-100 px-1.5 py-0.5 text-[10px] font-medium text-gray-500 dark:bg-gray-800 dark:text-gray-400">- {S.traces.compactionRound}+ {compactionBadge}</span>)}<span className="min-w-0 flex-1" />diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 66f292f3..b5249e61 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -903,6 +903,8 @@ export const en: Strings = {xhigh: "xhigh",max: "max",},+ /** English has no trigger/menu split to make: the name above already IS the wire value, so a menu row annotating it would only repeat itself. Taking just the name (the second parameter is dropped) is how this locale says "same text on every surface". */+ thinkingLevelMenuName: (name: string): string => name,thinkingSwitchTitle: "Switch thinking level",thinkingSwitchBody: (to: string): string =>`Switch the thinking level to "${to}"? Switching mid-conversation lowers the prompt-cache hit rate and raises cost; compacting the context first is cheaper.`,@@ -1284,9 +1286,7 @@ Scenarios:mcpToolsCount: (n: number): string => `${n} tool${n === 1 ? "" : "s"}`,mcpServerFailed: "connection failed",mcpConnectAborted: "interrupted — reconnects on the next send",- compactionTitle: "Compaction",- compactionDone: (mode: string) =>- mode === "discard" ? "old context discarded" : "switched to the summarized context",+ compactionTitle: (mode: string): string => (mode === "discard" ? "Clear" : "Compaction"),compactionFailed: (status: string, errorMessage?: string): string => {if (status === "aborted") return "aborted, keeping current context";return errorMessage !== undefined@@ -1477,7 +1477,6 @@ Scenarios:cacheHit: "Cache hits",hitRate: "Hit rate",compactions: "compactions",- compactionRound: "Compaction",empty: "No Traces for this agent",inProgress: "in progress",systemPrompt: "System prompt",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex b10b94cb..e07a3139 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -853,15 +853,17 @@ export const zh = {chooseAgent: "选择 Agent",chooseModel: "选择模型",thinkingLevel: "思考等级",- /** Tier names for the thinking-level controls: the Chinese name followed by the wire value in parentheses, so the label names the value actually sent (per maintainer request). `none` exists purely to display a stored legacy value — it is never offered as a choice (many models cannot disable thinking). */+ /** Tier names for every surface that DISPLAYS an already-chosen level — the composer picker's trigger and tooltip, the mid-chat switch dialog and its toasts, the Project chat-defaults control and its read-only row. Chinese only, no wire value (per maintainer request): once the tier is picked, the English spelling is noise on a control this narrow, and it reads badly inside the 「…」 of the switch prose. `none` exists purely to display a stored legacy value — it is never offered as a choice (many models cannot disable thinking). */thinkingLevelNames: {- none: "无 (none)",- low: "低 (low)",- medium: "中 (medium)",- high: "高 (high)",- xhigh: "极高 (xhigh)",- max: "最高 (max)",+ none: "无",+ low: "低",+ medium: "中",+ high: "高",+ xhigh: "极高",+ max: "最高",} as Readonly<Record<string, string>>,+ /** Dropdown-row variant of the name above: choosing is where the wire value earns its place, so a menu row annotates the Chinese name with the value the pick will send. Only the composer's own dropdown uses it — a native `<select>` renders the picked option's text on the collapsed control too, which would put the annotation straight back onto a trigger. */+ thinkingLevelMenuName: (name: string, level: string): string => `${name} (${level})`,/** Mid-chat switch guard (issue #310): confirm before a level change that costs prompt-cache hits over the existing history. Title is the dialog's accessible name only. */thinkingSwitchTitle: "切换思考等级",thinkingSwitchBody: (to: string): string =>@@ -1242,9 +1244,8 @@ Benchmark:mcpToolsCount: (n: number): string => `${n} 个工具`,mcpServerFailed: "连接失败",mcpConnectAborted: "已中断,下次发送时重新连接",- compactionTitle: "压缩",- compactionDone: (mode: string): string =>- mode === "discard" ? "已丢弃旧上下文" : "已切换到摘要后的新上下文",+ /** The row title names the step by what it actually did, so a `discard` is never announced as compaction: it clears the context rather than compacting it. Naming the mode in the title leaves nothing for a success line to add, which is why there is no outcome string beside this one; a `summarize` row needs none either, since it shows its adopted summary in its own expandable body. Only `compactionFailed` remains, carrying the one thing a title cannot. */+ compactionTitle: (mode: string): string => (mode === "discard" ? "清空" : "压缩"),compactionFailed: (status: string, errorMessage?: string): string => {if (status === "aborted") return "已中断,保留当前上下文";return errorMessage !== undefined@@ -1429,7 +1430,7 @@ Benchmark:cacheHit: "命中缓存",hitRate: "命中率",compactions: "压缩次数",- compactionRound: "压缩",+ /** The round-card badge reuses `chat.compactionTitle`, which names the mode (压缩 / 清空), so the Trace page and the conversation cannot drift apart; there is deliberately no Trace-local copy of that word. */empty: "该 Agent 暂无 Trace",inProgress: "进行中",systemPrompt: "系统提示词",diff --git a/packages/web/test/compaction-summary.test.ts b/packages/web/test/compaction-summary.test.tsindex 11e03be3..f2836577 100644--- a/packages/web/test/compaction-summary.test.ts+++ b/packages/web/test/compaction-summary.test.ts@@ -1,5 +1,6 @@/**- * compaction-summary.ts: the text a compaction row shows inside its collapsed body.+ * What a compaction row shows: the text inside its collapsed body (compaction-summary.ts)+ * and the title above it (the dictionaries' mode-aware `compactionTitle`).** The row itself is a StepBanner with the summary as its `children`, so it is collapsed by* default and carries the chevron exactly like a thinking block — the reader expands it to@@ -8,6 +9,8 @@* and renders no React).*/import { describe, expect, it } from "vitest";+import { en } from "../src/lib/strings-en";+import { zh } from "../src/lib/strings";import { compactionSummaryText } from "../src/lib/omni/compaction-summary";describe("compactionSummaryText", () => {@@ -33,3 +36,29 @@ describe("compactionSummaryText", () => {expect(compactionSummaryText({ summaryText: " " })).toBe("");});});++describe("compactionTitle (the row is titled by its mode)", () => {+ it("names a summarize row compaction and a discard row clear, in both locales", () => {+ expect(zh.chat.compactionTitle("summarize")).toBe("压缩");+ expect(zh.chat.compactionTitle("discard")).toBe("清空");+ expect(en.chat.compactionTitle("summarize")).toBe("Compaction");+ expect(en.chat.compactionTitle("discard")).toBe("Clear");+ });++ it("never labels a discard as compaction — the whole point of titling by mode", () => {+ for (const [locale, dict] of [+ ["zh", zh],+ ["en", en],+ ] as const) {+ expect(+ dict.chat.compactionTitle("discard"),+ `${locale} still calls a discard a compaction`,+ ).not.toBe(dict.chat.compactionTitle("summarize"));+ }+ });++ it("falls back to the compaction title for any other mode (an unknown/legacy value)", () => {+ expect(zh.chat.compactionTitle("")).toBe("压缩");+ expect(en.chat.compactionTitle("future-mode")).toBe("Compaction");+ });+});diff --git a/packages/web/test/thinking-level.test.ts b/packages/web/test/thinking-level.test.tsindex 1f22e324..7160ed34 100644--- a/packages/web/test/thinking-level.test.ts+++ b/packages/web/test/thinking-level.test.ts@@ -10,8 +10,16 @@* dialog's "compact, then switch" choice decides — from the transcript alone — whether the* compaction it started completed (apply the pick), settled without completing (keep the* level and say so), or is still in flight.+ *+ * Plus a drift guard over the REAL dictionaries (the rest of this file works against the+ * local NAMES stub): every tier core accepts has to be named in both locales, and the+ * trigger/menu split has to hold — no tier can go unlabelled, and no wire value can leak+ * back onto a trigger, without a test failing here.*/import { describe, expect, it } from "vitest";+import { DEFAULT_CHAT_THINKING_LEVELS } from "@prismshadow/penguin-core";+import { en } from "../src/lib/strings-en";+import { zh } from "../src/lib/strings";import {SELECTABLE_THINKING_LEVELS,THINKING_LEVELS,@@ -56,6 +64,46 @@ describe("thinking level lists", () => {});});+describe("tier names track core, and the trigger/menu split holds", () => {+ const dictionaries: ReadonlyArray<readonly [string, typeof zh]> = [+ ["zh", zh],+ ["en", en],+ ];++ it("offers exactly the tiers core accepts as a chat default", () => {+ expect([...SELECTABLE_THINKING_LEVELS]).toEqual([...DEFAULT_CHAT_THINKING_LEVELS]);+ });++ it("names every stored level in both locales — a new tier cannot ship unlabelled", () => {+ for (const [locale, dict] of dictionaries) {+ // THINKING_LEVELS ⊇ DEFAULT_CHAT_THINKING_LEVELS: the extra "none" is never offered+ // but still has to display, so the table has to cover it too.+ for (const level of THINKING_LEVELS) {+ const name = dict.chat.thinkingLevelNames[level];+ expect(name, `${locale} has no name for the ${level} tier`).toBeTruthy();+ }+ }+ });++ it("keeps the wire value off the zh trigger name and puts it on the zh menu row", () => {+ for (const level of THINKING_LEVELS) {+ const name = zh.chat.thinkingLevelNames[level] ?? "";+ // The maintainer's rule for the trigger: Chinese only — no latin letters, no parens.+ expect(name, `zh ${level} must not carry the wire value`).not.toMatch(/[A-Za-z()]/);+ // ...and the menu row is where that value belongs.+ expect(zh.chat.thinkingLevelMenuName(name, level)).toBe(`${name} (${level})`);+ }+ });++ it("leaves en unsplit: its name already is the wire value, so the menu adds nothing", () => {+ for (const level of THINKING_LEVELS) {+ const name = en.chat.thinkingLevelNames[level] ?? "";+ expect(name).toBe(level);+ expect(en.chat.thinkingLevelMenuName(name, level)).toBe(name);+ }+ });+});+describe("thinkingLevelLabel", () => {it("returns null for non-levels: '' (untouched/no override), a legacy meta's 'default', unknown, null", () => {expect(thinkingLevelLabel(NAMES, "")).toBeNull();diff --git a/packages/web/test/trace-compaction-badge.test.ts b/packages/web/test/trace-compaction-badge.test.tsnew file mode 100644index 00000000..863d584e--- /dev/null+++ b/packages/web/test/trace-compaction-badge.test.ts@@ -0,0 +1,52 @@+/**+ * The Trace round card's compaction badge (trace-file-view's `compactionBadgeLabel`).+ *+ * The badge deliberately reuses the chat stream's mode-aware row title instead of a+ * Trace-local string, so a discarded round is named the same thing in both places. These+ * tests pin that reuse, the backward-compatible fallback for a round analyzed before the+ * server carried the mode, and the fact that `compaction` alone still gates the badge.+ * (The Web suite runs in a node environment and renders no React, so the pure helper is+ * what gets exercised — the same approach as agent-settings-options.test.ts.)+ */+import { afterEach, describe, expect, it } from "vitest";+import { en } from "../src/lib/strings-en";+import { setActiveStrings, zh } from "../src/lib/strings";+import { compactionBadgeLabel } from "../src/features/traces/trace-file-view";++// S is a live binding shared across the suite: always hand it back the default.+afterEach(() => setActiveStrings(zh));++describe("compactionBadgeLabel", () => {+ it("shows nothing for a round that is not a compaction turn", () => {+ expect(compactionBadgeLabel(undefined)).toBeNull();+ expect(compactionBadgeLabel({ taskIndex: 0 } as never)).toBeNull();+ // The flag is the sole gate: a mode without the flag is not a compaction round.+ expect(compactionBadgeLabel({ taskIndex: 0, compactionMode: "discard" } as never)).toBeNull();+ });++ it("names the mode, so a discarded round is never badged as compaction", () => {+ const summarize = { taskIndex: 1, compaction: true, compactionMode: "summarize" } as never;+ const discard = { taskIndex: 1, compaction: true, compactionMode: "discard" } as never;++ expect(compactionBadgeLabel(summarize)).toBe("压缩");+ expect(compactionBadgeLabel(discard)).toBe("清空");++ setActiveStrings(en);+ expect(compactionBadgeLabel(summarize)).toBe("Compaction");+ expect(compactionBadgeLabel(discard)).toBe("Clear");+ });++ it("reuses the chat row's title rather than a second Trace-local pair of strings", () => {+ const discard = { taskIndex: 1, compaction: true, compactionMode: "discard" } as never;+ expect(compactionBadgeLabel(discard)).toBe(zh.chat.compactionTitle("discard"));+ setActiveStrings(en);+ expect(compactionBadgeLabel(discard)).toBe(en.chat.compactionTitle("discard"));+ });++ it("falls back to the compaction title when the mode is absent (a round analyzed by an older server)", () => {+ const legacy = { taskIndex: 1, compaction: true } as never;+ expect(compactionBadgeLabel(legacy)).toBe("压缩");+ setActiveStrings(en);+ expect(compactionBadgeLabel(legacy)).toBe("Compaction");+ });+});