A local-first multi-agent app development platform, built on PenguinHarness
The compaction row shows the request's thinking beside its result, both streaming, with the wall time (#582)
Yaowei Zheng28d25ba62f7a
diff --git a/changelog/unreleased/2026-09-02-compaction-banner-thinking.md b/changelog/unreleased/2026-09-02-compaction-banner-thinking.mdnew file mode 100644index 00000000..6982587b--- /dev/null+++ b/changelog/unreleased/2026-09-02-compaction-banner-thinking.md@@ -0,0 +1,20 @@+# The compaction row streams the request's thinking beside its result++- **Date:** 2026-09-02+- **Type:** feature+- **Scope:** `core`, `web`, `cli`, `docs`+- **PR:** [#582](https://github.com/Prism-Shadow/penguin-harness/pull/582)++[中文版](2026-09-02-compaction-banner-thinking.zh.md)++The Web App's compaction row took the shape of a running work group: the header's title doubles as its status (Compacting, then Compacted) and carries the wall time, and while the compaction runs the row is open and its sections arrive in the order the request produces them: the compaction request's thinking as soon as any lands, and the summary it produced only once that thinking has finished, with the first summary text — each closed by default, each with its own wall time, streaming while the request writes it++## Details++- Core forwards the compaction request's thinking on the output stream between the paired compaction events, the same way it already forwarded the summary text: `partial_thinking` fragments verbatim, or the complete `thinking` when no fragment carried content, never both. The request keeps the thinking level its model context already had; nothing switches thinking on for it. The Trace is unchanged.+- The Web reducer accumulates that thinking onto the running compaction item (`thinkingText`, with `thinkingStreaming` tracking the open fragment) beside the summary, rebuilds it identically from the span's recorded thinking on history replay, and drops both drafts when a compaction does not complete.+- The compaction row's body became two stacked disclosure rows, **Thinking** (present only once any thinking arrived) and **Result** (present only after that thinking finishes, from the first summary text — a result row beside a thought still being written read as two things at once), both rendered with the thinking block's body and streaming renderer. Each carries its own status icon and wall time in the thinking block's own slot, so a compaction section, a thinking block and the row above them read identically.+- Step rows (compaction, the first-run MCP connect) now follow the work group's expand policy: the row opens while it runs, so its body rows are on screen as they are appended, and closes itself once it settles — the body's own rows never open with it. A manual toggle pins the row, so a finished row the reader opened stays open. The work group's own policy moved from "is this the last segment" to its header's Running/Done state, which closes it on a turn that ends on the group itself. The header keeps its chevron from the start of a summarize compaction, and its title doubles as the status the way the work group's Running/Done header does: **Compacting** while the request runs, **Compacted** once it settles (Clearing/Cleared for a `discard`) — no separate "streaming" hint — with the wall time ticking live before settling to the same formatting the run-finished stats line uses. A failed compaction keeps the bare mode word over its single-line reason, and a `discard` row stays chevron-less.+- Each section is timed over exactly the window in which it shows itself running: thinking from its first content to the stop that closes its fragment, the result from its first summary text to the compaction's own end. History replay approximates each start with the previous message's time, the convention an ordinary thinking block already uses. A retried compaction concatenates its attempts into one draft, so a start is recorded once and a later stop only extends it — the wall time covers the whole span that produced the text on screen rather than the last attempt alone.+- The CLI prints none of the streamed thinking, as it already printed none of the streamed summary.+- The agent-loop and Web App docs describe the row's new shape.diff --git a/changelog/unreleased/2026-09-02-compaction-banner-thinking.zh.md b/changelog/unreleased/2026-09-02-compaction-banner-thinking.zh.mdnew file mode 100644index 00000000..c5a4ed9c--- /dev/null+++ b/changelog/unreleased/2026-09-02-compaction-banner-thinking.zh.md@@ -0,0 +1,20 @@+# 压缩行在压缩结果旁流式呈现压缩请求的思考++- **Date:** 2026-09-02+- **Type:** feature+- **Scope:** `core`, `web`, `cli`, `docs`+- **PR:** [#582](https://github.com/Prism-Shadow/penguin-harness/pull/582)++[English](2026-09-02-compaction-banner-thinking.md)++Web App 的压缩行改为按运行中的工作分组的形态呈现:组头以「压缩中」→「压缩完毕」兼作状态并带 wall time;压缩运行期间该行展开,两节按请求产出的先后出现——压缩请求的思考一到就出现,它产出的摘要要等思考结束、第一段摘要文本抵达后才出现——两节默认折叠、各带自己的 wall time,请求写出时流式呈现。压缩结束后该行自行收起。++## 细节++- Core 在成对压缩事件之间把压缩请求的思考推上输出流,方式与此前推送摘要文本相同:`partial_thinking` 片段原样转发,没有片段承载内容时改推完整的 `thinking`,二者绝不同时出现。压缩请求沿用模型上下文既有的思考等级,不会为它单独开启思考。Trace 不变。+- Web 端的 reducer 把这段思考累积到进行中的压缩条目上(`thinkingText`,并以 `thinkingStreaming` 记录片段是否仍打开),与摘要并列;历史重建从压缩区间已记录的思考读回同一内容;未完成的压缩把两份草稿一并丢弃。+- 压缩行的正文改为两条上下堆叠的折叠行:**思考**(有思考抵达后才出现)与**压缩结果**(思考结束、第一段摘要文本抵达后才出现——思考还在写时旁边就摆一条空的结果行,读起来像两件事同时发生),都用思考块的正文样式与流式渲染器。两节各在思考块原有的位置带上自己的状态图标与 wall time,因此压缩的一节、思考块、以及它们上方的那一行读起来完全一致。+- 步骤行(压缩、首次 MCP 连接)改用工作分组的展开策略:运行期间该行展开,正文里的行随产生逐条出现在屏幕上;结束后该行自行收起,而正文里的行始终不随之展开。手动切换会把该行钉住,读者展开的已完成行保持展开。工作分组自身的策略也从「是否为最后一段」改为组头的运行中/运行完毕状态,因此以该分组收尾的一轮同样会收起。组头从 summarize 压缩开始就带折叠箭头,标题兼作状态,与工作分组组头的「运行中」/「运行完毕」同一写法:请求运行期间为**「压缩中」**、结束后为**「压缩完毕」**(`discard` 为「清空中」/「清空完毕」),不再另设「生成中」提示;实时计时的 wall time 在结束后定格为与运行结束统计行相同的格式。失败的压缩保留裸的模式标题与一行原因,`discard` 行仍不带折叠箭头。+- 每一节的计时范围恰好是它显示自己「运行中」的那段窗口:思考从第一段思考内容起、到收束其片段的 stop 止;压缩结果从第一段摘要文本起、到压缩自身结束止。历史重建以上一条消息的时间近似各自的起点,沿用普通思考块既有的约定。重试的压缩会把各次尝试拼成一份草稿,因此起点只记录一次、之后的 stop 只延长它——wall time 覆盖产出屏幕上这段文字的整段时间,而不是只算最后一次尝试。+- CLI 不打印流式思考,一如它此前不打印流式摘要。+- agent-loop 与 Web App 文档描述了压缩行的新形态。diff --git a/packages/cli/src/render.ts b/packages/cli/src/render.tsindex b36c609e..8c8ebfe6 100644--- a/packages/cli/src/render.ts+++ b/packages/cli/src/render.ts@@ -1026,6 +1026,10 @@ export class StreamRenderer {}private handlePartialThinking(p: PartialThinkingPayload): void {+ // Between the paired compaction events the stream carries the compaction request's+ // thinking as ordinary partial_thinking, beside its summary (see handlePartialText): the+ // CLI keeps its one-line compaction progress and prints none of it.+ if (this.compactionActive) return;if (p.event_type === "stop") {this.finishLine();return;diff --git a/packages/cli/test/render.test.ts b/packages/cli/test/render.test.tsindex f5945402..c1b91668 100644--- a/packages/cli/test/render.test.ts+++ b/packages/cli/test/render.test.ts@@ -529,23 +529,32 @@ describe("StreamRenderer", () => {);});- it("the summary streamed inside a compaction span stays off the terminal (issue #290)", () => {- // Between the paired events the stream now carries the summary being written as- // ordinary partial_text; the CLI keeps its one-line progress and prints none of it,- // while text after the span renders as usual.+ it("the thinking and summary streamed inside a compaction span stay off the terminal (issue #290)", () => {+ // Between the paired events the stream carries the compaction request's thinking and the+ // summary being written as ordinary partial_thinking / partial_text; the CLI keeps its+ // one-line progress and prints none of either, while thinking and text after the span+ // render as usual.const { stream, text } = collector();const r = new StreamRenderer(stream, t);r.handle(compactionBegin({ reason: "context", mode: "summarize", context: 150, turns: 3 }));+ r.handle(partialThinking("start"));+ r.handle(partialThinking("delta", "weighing the transcript"));+ r.handle(partialThinking("stop"));r.handle(partialText("start"));r.handle(partialText("delta", "[summary]the plan"));r.handle(partialText("delta", "[/summary]"));r.handle(partialText("stop"));r.handle(compactionEnd({ reason: "context", mode: "summarize", status: "completed" }));+ r.handle(partialThinking("start"));+ r.handle(partialThinking("delta", "thinking again"));+ r.handle(partialThinking("stop"));r.handle(partialText("start"));r.handle(partialText("delta", "back to the task"));r.handle(partialText("stop"));const out = stripAnsi(text());+ expect(out).not.toContain("weighing the transcript");expect(out).not.toContain("the plan");+ expect(out).toContain("thinking again");expect(out).toContain("back to the task");});diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.tsindex fb1edff1..d35a7d87 100644--- a/packages/core/src/engine/context-engine.ts+++ b/packages/core/src/engine/context-engine.ts@@ -1498,9 +1498,10 @@ export class ContextEngine {* compaction request's raw messages are not pushed to the Human output stream, with two* exceptions between the paired compaction events: every attempt's `token_usage` (so the* frontend stats and the server's usage records count the compaction's true spend,- * rejected attempts included), and the summary text being generated, as ordinary- * `partial_text`/`text` messages (issue #290 — see runCompactionRequest); everything is- * written to the old Trace as before. Compaction succeeds only with a **valid summary** — non-empty extracted+ * rejected attempts included), and the thinking and summary text being generated, as+ * ordinary `partial_thinking`/`thinking` and `partial_text`/`text` messages (issue #290 —+ * see runCompactionRequest); everything is written to the old Trace as before. Compaction+ * succeeds only with a **valid summary** — non-empty extracted* text and no tool calls in the response. Everything short of that is one kind of failure,* handled exactly like an ordinary LLM request's (issue #170): an unusable committed* response (empty summary, or tool calls — answered with synthesized failed outputs and@@ -1720,11 +1721,12 @@ export class ContextEngine {* the moment the context is largest, issue #84). Consumes the old LLM object's streamed* output; raw model messages are **not pushed to the Human output stream** (`token_usage`* is captured and handed back via the return value for summarizeContext to yield), with- * one exception: the text being generated rides the stream as its own ordinary- * `partial_text`/`text` messages (issue #290) so the frontend can show the summary while- * it is written — readers already treat model messages between the paired compaction- * events as compaction-internal, and history rebuild reads the identical text back from- * the span's complete assistant messages. Complete+ * one exception: the thinking and the text being generated ride the stream as their own+ * ordinary `partial_thinking`/`thinking` and `partial_text`/`text` messages (issue #290)+ * so the frontend can show the compaction request working while it runs — readers already+ * treat model messages between the paired compaction events as compaction-internal, and+ * history rebuild reads the identical content back from the span's complete assistant+ * messages. Complete* messages and events are written to the old Trace; complete text segments are collected as* the compaction output, and `toolCalls` collects the response's real tool requests (never* dispatched — summarizeContext rejects such a response as not-a-summary and answers each@@ -1760,11 +1762,14 @@ export class ContextEngine {let text = "";const toolCalls: OmniMessage<ToolCallPayload>[] = [];let usage: OmniMessage | null = null;- // Whether this attempt streamed any partial_text content: real LLM objects stream the- // summary as partial fragments (forwarded verbatim), and the complete text message that- // follows must then stay off the stream or consumers would see the content twice; an- // implementation that yields only complete messages streams those instead.+ // Whether this attempt streamed any partial_text / partial_thinking content: real LLM+ // objects stream the summary (and the thinking ahead of it) as partial fragments+ // (forwarded verbatim), and the complete message that follows must then stay off the+ // stream or consumers would see the content twice; an implementation that yields only+ // complete messages streams those instead. Tracked per kind, so a model that streams its+ // thinking but delivers its text whole still gets that text forwarded once.let sawPartialText = false;+ let sawPartialThinking = false;for (;;) {const res = await gen.next();if (res.done) {@@ -1807,21 +1812,25 @@ export class ContextEngine {// Stamped with the Session series before the write, exactly like a turn's (runTurn).if (this.observeTokenUsage(msg)) usage = msg;await this.write(msg);- // Streamed compaction progress (issue #290): the summary's own text rides the output- // stream between the paired compaction events — partial_text fragments verbatim (all- // three phases, so the server's live tail opens and closes its fragment and a join- // mid-compaction is seeded with the accumulated prefix), or the complete text when no- // partial carried content (implementations that yield only complete messages) — never- // both, so consumers see each character once. The request's other raw messages- // (thinking, the compaction Prompt, request events) stay Trace-only as before.- // Rejected attempts stream too: the frontend shows whatever the compaction request is- // really producing, and history rebuild reads the same text back from the span's- // complete assistant messages.+ // Streamed compaction progress (issue #290): the request's thinking and the summary's+ // own text ride the output stream between the paired compaction events —+ // partial_thinking / partial_text fragments verbatim (all three phases, so the server's+ // live tail opens and closes its fragment and a join mid-compaction is seeded with the+ // accumulated prefix), or the complete thinking / text when no partial of that kind+ // carried content (implementations that yield only complete messages) — never both,+ // so consumers see each character once. The request's other raw messages (the+ // compaction Prompt, request events) stay Trace-only as before. Rejected attempts+ // stream too: the frontend shows whatever the compaction request is really producing,+ // and history rebuild reads the same content back from the span's complete assistant+ // messages.{- const p = msg.payload as { type?: string; text?: string };+ const p = msg.payload as { type?: string; text?: string; thinking?: string };if (p.type === "partial_text") {if (typeof p.text === "string" && p.text !== "") sawPartialText = true;yield msg;+ } else if (p.type === "partial_thinking") {+ if (typeof p.thinking === "string" && p.thinking !== "") sawPartialThinking = true;+ yield msg;}}if (isCompleteModelMessage(msg)) {@@ -1829,6 +1838,12 @@ export class ContextEngine {const body = (msg.payload as TextPayload).text;text += body;if (!sawPartialText && body !== "") yield msg;+ } else if (msg.payload.type === "thinking") {+ // Forwarded for the banner only — the thinking is never summary material (the+ // extraction reads `text` alone) — and a fidelity-only blank body has nothing to+ // show.+ const body = (msg.payload as ThinkingPayload).thinking;+ if (!sawPartialThinking && body !== "") yield msg;} else if (msg.payload.type === "tool_call") {// Same filter as the turn loop: a tool_call synthesized to close out an interruption// carries a non-completed stop_reason — it is structural closure, not a real request,diff --git a/packages/core/test/compaction.test.ts b/packages/core/test/compaction.test.tsindex 0d902ec5..bc3590a7 100644--- a/packages/core/test/compaction.test.ts+++ b/packages/core/test/compaction.test.ts@@ -32,6 +32,7 @@ import {mcpConnectBegin,mcpConnectEnd,partialText,+ partialThinking,requestBegin,requestEnd,sessionMeta,@@ -2085,6 +2086,97 @@ describe("compaction summary streaming (issue #290)", () => {const end = types.indexOf("compaction_end");expect(streamedTexts(out.slice(begin + 1, end))).toEqual(["[summary]whole[/summary]"]);});++ /** The thinking messages the compaction span pushed to the stream, in order. */+ const streamedThinking = (msgs: OmniMessage[]): string[] =>+ msgs+ .filter((m) => {+ const t = (m.payload as { type?: string }).type;+ return t === "partial_thinking" || t === "thinking";+ })+ .map((m) => (m.payload as { thinking?: string }).thinking ?? "");++ it("streams the request's partial_thinking ahead of the summary the same way; the complete thinking stays off the stream", async () => {+ const llm1 = new ScriptedLLM(+ [+ { messages: [assistantText("answer one"), usage(150, 150)] },+ {+ messages: [+ partialThinking("start"),+ partialThinking("delta", "what matters is "),+ partialThinking("delta", "the plan"),+ partialThinking("stop"),+ thinkingMessage("what matters is the plan"),+ partialText("start"),+ partialText("delta", "[summary]the plan[/summary]"),+ partialText("stop"),+ assistantText("[summary]the plan[/summary]"),+ usage(160, 310),+ ],+ },+ ],+ "llm1",+ );+ const trace = new Writer({ tracesDir: traces, sessionId: "sess_stream_thinking" });+ const engine = new ContextEngine({+ llm: llm1,+ environment: fakeEnvironment,+ trace,+ sessionMeta: metaMessage,+ compaction: settings(),+ openNextContext: () => ({ llm: new ScriptedLLM([], "llm2") }),+ });+ const oldPath = trace.currentPath();++ const out = await collect(engine.run([userText("task one")], { approve: allowAll }));++ const types = payloadTypes(out);+ const begin = types.indexOf("compaction_begin");+ const end = types.indexOf("compaction_end");+ const span = out.slice(begin + 1, end);+ const spanTypes = payloadTypes(span);+ // Every phase of the thinking fragment rides the stream, in front of the summary's own+ // fragments, and the complete thinking that follows does not re-emit.+ expect(spanTypes.filter((t) => t === "partial_thinking")).toHaveLength(4);+ expect(spanTypes).not.toContain("thinking");+ expect(spanTypes.indexOf("partial_thinking")).toBeLessThan(spanTypes.indexOf("partial_text"));+ expect(streamedThinking(span)).toEqual(["", "what matters is ", "the plan", ""]);+ expect(streamedTexts(span)).toEqual(["", "[summary]the plan[/summary]", ""]);+ // The old Trace records the complete thinking as before; partials never persist.+ const recorded = await readTrace(oldPath);+ expect(streamedThinking(recorded)).toContain("what matters is the plan");+ expect(payloadTypes(recorded)).not.toContain("partial_thinking");+ });++ it("an LLM that yields only complete thinking streams that thinking instead; a blank fidelity-only thinking stays off the stream", async () => {+ const llm1 = new ScriptedLLM(+ [+ { messages: [assistantText("answer one"), usage(150, 150)] },+ {+ messages: [+ thinkingMessage("whole thought"),+ thinkingMessage("", "completed", { signature: "opaque" }),+ assistantText("[summary]whole[/summary]"),+ usage(160, 310),+ ],+ },+ ],+ "llm1",+ );+ const engine = new ContextEngine({+ llm: llm1,+ environment: fakeEnvironment,+ sessionMeta: metaMessage,+ compaction: settings(),+ openNextContext: () => ({ llm: new ScriptedLLM([], "llm2") }),+ });++ const out = await collect(engine.run([userText("task one")], { approve: allowAll }));+ const types = payloadTypes(out);+ const begin = types.indexOf("compaction_begin");+ const end = types.indexOf("compaction_end");+ expect(streamedThinking(out.slice(begin + 1, end))).toEqual(["whole thought"]);+ });});describe("a compaction the user quit out of (issue #288)", () => {diff --git a/packages/docs/content/agent-loop.en.md b/packages/docs/content/agent-loop.en.mdindex 983c2170..6868449d 100644--- a/packages/docs/content/agent-loop.en.md+++ b/packages/docs/content/agent-loop.en.md@@ -198,7 +198,7 @@ An abandoned compaction is **made up later**, never patched over. Mid-Task the rCompaction triggered **mid-Task** never preempts the tools: `runTurn` returns only once every tool call of the turn has completed, so the results are ready and paired before the checkpoint is even reached. They then ride the compaction request itself, ahead of the compaction Prompt, in their original call order — whatever a tool produced (a normal result, a `[tool error]`, a denial) is what the summary is written from. A tool that waits on approval or runs for minutes simply delays the compaction; no clock is running on it, because the compaction request has not been issued yet. Nothing synthetic is inserted to close the exchange.-While the summary is being generated it rides the output stream as ordinary `partial_text` (or the complete `text`, for LLM implementations that stream nothing), positioned between the paired compaction events — no separate event type, and the compaction request's other raw messages stay Trace-only as before. The Web App renders the compaction row **collapsed by default, exactly like a thinking block**: the chevron is there from the start of a summarize compaction and the summary streams inside the collapsed body, which the reader expands to watch it being written or to read it afterwards. A history rebuild reads the same text back from the compaction span's recorded output, so a reload shows exactly what the live viewer saw. Consumers that render a transcript already treat model messages inside the span as compaction-internal, so nothing leaks into the conversation.+While the compaction request runs, its thinking and the summary it writes ride the output stream as ordinary `partial_thinking` and `partial_text` (or the complete `thinking` / `text`, for LLM implementations that stream nothing), positioned between the paired compaction events — no separate event type, and the compaction request's other raw messages stay Trace-only as before. The request runs at the thinking level its model context already has; nothing turns thinking on for it. The Web App renders the compaction row like a running work group, and expands exactly one of its two layers: the header's title doubles as its status — Compacting (or Clearing) while it runs, Compacted (or Cleared) once done, the work-group header's own Running/Done idiom — and carries the wall time (ticking while it runs, settled once done); **while the compaction runs the row is open and its sections are not** — **Thinking** (present only when the request produced any) and **Result**, each a closed row carrying its own label and its own wall time, so the reader can see that they are there and how long each is taking without the request's raw workings landing in the transcript. Once the compaction settles the row closes itself again, leaving the one-line summary. The chevron is there from the start of a summarize compaction, so the reader can open either section to watch the request work, or read the outcome afterwards. A history rebuild reads the same content back from the compaction span's recorded thinking and output, so a reload shows exactly what the live viewer saw. Consumers that render a transcript already treat model messages inside the span as compaction-internal, so nothing leaks into the conversation, and the CLI prints none of it.A compaction the user quit out of — the process died mid-request, leaving a `compaction_begin` with no matching end — is simply a **failed compaction**. When the session next loads, resume closes the span with a `failed` `compaction_end` before appending anything else and **discards the half-written summary**: nothing is reconstructed from it, the original context stands, and the standing threshold makes the compaction up at the next trigger. Closing the span is what keeps the conversation that follows visible — every reader treats messages between the paired events as compaction-internal — and the Web App drops the partial draft from the row rather than showing a truncated summary as if it had been adopted.diff --git a/packages/docs/content/agent-loop.zh.md b/packages/docs/content/agent-loop.zh.mdindex bc4f6545..6017c91f 100644--- a/packages/docs/content/agent-loop.zh.md+++ b/packages/docs/content/agent-loop.zh.md@@ -191,7 +191,7 @@ interface CompactionSettings {任务中途触发的压缩绝不抢在工具前面:`runTurn` 要等本轮**全部**工具调用执行完毕才返回,因此到达压缩检查点时结果已经就绪、也已与 `tool_call` 配对。这些结果随后**随压缩请求本身**发出,排在压缩 Prompt 之前、保持原始调用顺序——工具产出什么(正常结果、`[tool error]`、被拒绝的回执),摘要就据此写成。需要审批或耗时数分钟的工具只是让压缩延后:压缩请求尚未发出,也就没有任何计时在跑。全程不插入任何合成消息去闭合该交换。-摘要生成期间,文本以普通的 `partial_text`(不产出流式消息的 LLM 实现则为完整 `text`)在成对压缩事件之间上行——不新增事件类型,压缩请求的其他原始消息一如既往只写 Trace。Web App 的压缩行**默认折叠,与思考块完全一致**:summarize 压缩一开始就带上折叠箭头,摘要在折叠的正文内流式写出,读者展开即可实时观看或事后阅读。历史重建从压缩区间已记录的输出读回同一段文本,刷新后与实时视图一致。渲染对话的消费方本就把压缩区间内的模型消息视为压缩内部消息,因此不会漏进正文。+压缩请求运行期间,它的思考与它写出的摘要以普通的 `partial_thinking` 与 `partial_text`(不产出流式消息的 LLM 实现则为完整 `thinking` / `text`)在成对压缩事件之间上行——不新增事件类型,压缩请求的其他原始消息一如既往只写 Trace。压缩请求沿用模型上下文本来的思考等级,不会为它单独开启思考。Web App 的压缩行按运行中的工作分组呈现,且两层里只展开一层:组头的标题兼作状态——进行中为「压缩中」/「清空中」、结束后为「压缩完毕」/「清空完毕」,与工作分组组头的「运行中」/「运行完毕」同一写法——并带 wall time(进行中实时计时、结束后定格);**压缩运行期间该行展开、其中两节不展开**——「思考」(请求产出了思考时才有)与「压缩结果」各是一条折叠的行,各自带标签与自己的 wall time,读者能看到它们存在、各花了多久,而压缩请求的原始过程不会落进正文。压缩结束后该行自行收起,只留下一行摘要。summarize 压缩一开始就带上折叠箭头,读者展开任一节即可实时观看或事后阅读。历史重建从压缩区间已记录的思考与输出读回同一段内容,刷新后与实时视图一致。渲染对话的消费方本就把压缩区间内的模型消息视为压缩内部消息,因此不会漏进正文,CLI 也不打印其中任何内容。用户中途退出程序导致没写完的压缩(留下没有配对 end 的 `compaction_begin`),就是一次**压缩失败**。会话下次加载时,恢复流程在续写任何内容之前先以 `failed` 收束该区间,并**直接丢弃写了一半的摘要**:不做任何重建,原上下文照旧,阈值依然超标、压缩留待下次触发时补做。收束区间正是让其后对话保持可见的关键——所有读取方都把成对事件之间的消息当作压缩内部消息;Web 端同时丢掉那段半成品草稿,不把截断的摘要摆成像是已被采纳的样子。diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex a2452381..a8441c87 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -56,6 +56,7 @@ Pinning is offered only in the active list — the archived, subagent and schedu- Model text renders token by token; thinking blocks are collapsible;- Tool cards expand to show arguments and output, with a live timer while running; a call made with `run_in_background` carries the same activity trace as the conversation list, right of its duration ("Runs in the background") — the call returns at once, and the mark says its work did not;+- A context compaction leaves a row whose title doubles as its status, the work-group header's Running/Done idiom: Compacting while it runs and Compacted once it settles (Clearing/Cleared for a discard), with its wall time; while a summarize runs the row is open: its thinking section appears once the request's thinking arrives, and its result section only after that thinking finishes, when the first summary text lands — each closed by default, each with its own wall time — and the row closes itself again once the compaction settles, leaving the one line; a failed compaction keeps the bare mode word (Compaction, or Clear) over a one-line reason instead;- Subagents leave a full-width row in the stream, styled like the other collapsed step rows (agent avatar, name, short session id, running spinner, and an amber dot while one of their tool calls awaits approval); clicking it opens the agents side panel — a call graph of that row's Task on top (each node shows its elapsed time; click a node to switch) and the selected child's live conversation below — the child's own user prompts included — where nested tool cards and approvals work exactly as in the main chat. Panel visibility is task-scoped: sending a message that starts a new task closes it by default (entering a session starts closed too), and it comes back when you open it yourself or — on desktop — when the current task spawns a subagent (one auto-open per task; a manual close holds until the next task; never over an open files panel). Opening the panel from the toolbar, or switching sessions, shows the latest Task's graph; a row on an older turn brings back that turn's graph. The agents panel and the Workspace files panel never show together — opening one closes the other. Context compaction and the first-run MCP connect show a unified step row (the work-group header shell, sticky title bar included — running/success/failure only swap the icon and the one-line detail, with the wall time on the result; the MCP row leads with the discovered-tool count and names unavailable servers, and expands into one group per server — status, tool count and that server's connect time — each opening into its tool list or the failure detail);- After each Task, a stats line shows tokens, TPS, elapsed time, cost, copy, and a **Fork** action to the right of copy. Fork asks for confirmation first — it duplicates the conversation into a new chat — and only then opens a new Session at that completed assistant reply with the same Agent, model, Workspace, approval mode, and retained transcript. Forks from different replies in one source chat share an increasing, language-neutral title sequence (`Source title (1)`, `Source title (2)`). Its Trace and scratchpad are independent snapshots: local images/files keep rendering even after the source chat is deleted;diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex af34fe69..740c0587 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -56,6 +56,7 @@ penguin web- 模型文本逐 Token 渲染,思考块可折叠;- 工具卡片可展开查看参数与输出,执行中显示实时计时;以 `run_in_background` 发起的调用在用时右侧带与会话列表同一枚活动波形标记(「在后台运行」)——调用本身立刻返回,标记说明它的工作没有;+- 上下文压缩在消息流中留下一行,标题兼作状态、与工作分组组头的「运行中」/「运行完毕」同一写法:按实际动作写作「压缩中」/「压缩完毕」,discard 则为「清空中」/「清空完毕」,并带用时;summarize 运行期间该行展开:压缩请求的思考一到就出现「思考」一节,「压缩结果」一节要等思考结束、第一段摘要文本抵达后才出现——两节默认折叠、各带自己的用时——压缩结束后该行自行收起,只留下这一行;失败的压缩保留裸的「压缩」或「清空」标题与一行原因;- 子 Agent 在消息流中只留下一条通栏行,样式与其他折叠步骤行一致(头像、名称、短会话号、运行中转圈,子会话内有待审批时带琥珀色圆点);点击打开右侧智能体面板——上方是该行所属 Task 派生关系的调用图(节点上显示运行时长,点节点切换),下方是所选子会话的实时对话(含子会话自己的用户消息),嵌套工具卡片与审批与主对话完全一致;面板的显示以任务为界:发送消息开启新任务时默认关闭(进入会话时同样默认关闭),仅在手动打开、或(桌面端)当前任务派生子智能体时重新显示(每个任务自动打开一次,任务内手动关闭后保持关闭到下个任务,且不抢占已打开的工作区面板);从工具条打开面板或切换 Session 时默认展示最新 Task 的调用图,点旧轮次的行则回看那一轮的调用图;智能体面板与工作区面板不会同时显示,打开一个即关闭另一个;上下文压缩与首次 MCP 连接以统一样式的步骤行提示(与运行分组头同款外壳,含吸顶标题栏,连接中/成功/失败仅切换图标与单行详情,结果行含耗时;MCP 行主显发现的工具数并点名不可用的 Server,展开后按 Server 分组——每组一行状态、工具数与该 Server 的连接耗时,点开组内是工具列表或失败原因);- 每个 Task 结束后显示统计行:Token 用量、TPS、耗时、费用、复制以及位于复制按钮右侧的**分叉**操作。分叉会先弹出确认框(该操作会把对话复制为一个新对话),确认后才在该条已完成的模型回复处新建 Session,沿用 Agent、模型、Workspace、审批模式和保留范围内的历史;同一源对话从不同回复分叉时,标题使用不依赖界面语言的编号后缀,按 `原标题 (1)`、`原标题 (2)` 递增。新旧会话的 Trace 与 scratchpad 是独立快照,即使删除源对话,本地图片和附件仍可显示;diff --git a/packages/web/src/features/chat/compaction-banner.tsx b/packages/web/src/features/chat/compaction-banner.tsxindex fb7227d1..ae07abd5 100644--- a/packages/web/src/features/chat/compaction-banner.tsx+++ b/packages/web/src/features/chat/compaction-banner.tsx@@ -1,23 +1,42 @@/*** Compaction row: one StepBanner across running/done/failed (same shell as the MCP- * connect row and the reasoning-&-tools group header) — wall time once settled, failures- * on a single line.+ * connect row and the reasoning-&-tools group header) — the wall time ticks while it runs+ * and settles once finished, failures stay 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 title names the mode and doubles as the status**, the work-group header's idiom+ * (运行中 → 运行完毕): a `summarize` row reads 压缩中 / "Compacting" while it runs and+ * 压缩完毕 / "Compacted" once it settles; a `discard` row 清空中 → 清空完毕 ("Clearing" →+ * "Cleared") — it drops the old context rather than compacting it, and calling that+ * "compaction" was the confusing part (per maintainer request). With mode and state both in+ * the title neither outcome needs a detail line: a running row is icon + title + ticking wall+ * time (+ chevron on a summarize), a succeeded row the same with the time settled, and the+ * detail slot is left for the one thing a title cannot say — why a compaction failed, under+ * the bare mode word.*- * 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- * request is writing streams inside the collapsed body (same `md-body` treatment and the- * same streaming `Md` as thinking-block.tsx) — the reader expands it to watch the summary- * being written, or to read it afterwards. A `discard` compaction produces no text at all- * and stays chevron-less, as does a failed one: a compaction that did not complete wrote- * no adopted summary, and the reducer discards its half-written draft (see stream-model's- * compaction_end handling), so there is nothing left to show.+ * The body follows the work group: **two stacked disclosure rows, each with its own status+ * icon and wall time exactly like a thinking block** — 「思考」/ "Thinking", what the+ * compaction request thought ahead of its summary (present only once any arrived; a model+ * that does not think leaves no empty row), and 「压缩结果」/ "Result", the summary itself.+ * Both carry the thinking block's own body (`md-body` + the streaming `Md`) and stream while+ * the request writes them.+ *+ * Two layers, and the running row opens exactly one of them (StepBanner's expand policy, the+ * work group's): while the compaction runs the banner is open, so the two section rows are on+ * screen with their labels and their ticking times — the reader can see that they are there+ * and how long each is taking — while the sections themselves stay closed (DisclosureRow's+ * default), because their contents are the compaction's raw workings and not what the row is+ * for. Once the compaction settles the banner closes itself again, leaving the one-line+ * summary. The sections arrive in the order the request produces them: the thinking section+ * once any thinking lands, the result section only after that thinking finishes — its first+ * summary token is what settles the thinking section — so a running row never shows a result+ * row beside a thought still being written (compactionResultVisible decides).+ *+ * The header's chevron is there from the moment a summarize compaction starts, so the reader+ * can reopen it to watch the request work, or read the outcome afterwards. A `discard`+ * compaction produces no text at all and stays chevron-less, as does a failed one: a+ * compaction that did not complete wrote no adopted summary, and the reducer discards its+ * half-written drafts (see stream-model's compaction_end handling), so there is nothing left+ * to show.** Doesn't show Tokens: the row only needs to state whether compaction happened and whether it* succeeded. Compaction's cost lands in different places depending on when it occurs — compaction@@ -26,35 +45,103 @@* compaction turns separately); see the task-stats module comments.*/import { S } from "../../lib/strings";+import { humanizeDuration } from "../../lib/format";import type { CompactionItem } from "../../lib/omni/stream-model";-import { compactionSummaryText } from "../../lib/omni/compaction-summary";+import { compactionResultVisible, compactionSummaryText } from "../../lib/omni/compaction-summary";+import { StatusIcon } from "../../components/ui/status-icon";+import { DisclosureRow } from "./disclosure-row";+import { LiveDuration } from "./live-duration";import { Md } from "./md";import { StepBanner } from "./step-banner";-/** The expandable body: the same shell thinking uses for its own text (md-body + streaming Md). */-function SummaryBody({ text, streaming }: { text: string; streaming: boolean }) {+/**+ * One body section: the thinking block's row (status icon + label + wall time + chevron) over+ * the thinking block's text body — the same three marks in the same order, so a compaction+ * section and a thinking block read as the one thing they are. Sticky like a row inside the+ * work group, so a long expanded section keeps its own label pinned under the stuck banner+ * header.+ */+function CompactionSection({+ label,+ text,+ streaming,+ startedAtMs,+ durationMs,+}: {+ label: string;+ text: string;+ streaming: boolean;+ /** Ticks from here while the section streams (`…` until its first content lands). */+ startedAtMs?: number;+ /** Settled wall time once the section closes (see CompactionItem for the boundaries). */+ durationMs?: number;+}) {return (- <div className="md-body px-3 py-2 text-sm leading-relaxed text-gray-600 dark:text-gray-400">- <Md text={text} streaming={streaming} />- </div>+ <DisclosureRow+ sticky+ icon={+ <StatusIcon+ state={streaming ? "running" : "done"}+ label={streaming ? S.chat.workRunning : S.chat.workDone}+ />+ }+ label={label}+ trailing={+ <span className="shrink-0 font-mono text-xs text-gray-500 dark:text-gray-400">+ {streaming ? (+ <LiveDuration sinceMs={startedAtMs} />+ ) : durationMs !== undefined ? (+ humanizeDuration(durationMs)+ ) : null}+ </span>+ }+ >+ <div className="md-body anim-fade mx-3 mb-2 rounded-md bg-gray-50 px-3 py-2 text-sm leading-relaxed text-gray-600 dark:bg-gray-900/60 dark:text-gray-400">+ <Md text={text} streaming={streaming} />+ </div>+ </DisclosureRow>);}export function CompactionBanner({ item }: { item: CompactionItem }) {const summary = compactionSummaryText(item);+ const thinking = item.thinkingText?.trim() ? item.thinkingText : "";// The chevron is stable for the whole life of a summarize compaction: present from the- // start (before the first token arrives the body is simply empty, as a thinking block's- // is) rather than appearing mid-stream and shifting the row.- const expandable = summary !== "" || (item.running && item.mode === "summarize");- const body = expandable ? <SummaryBody text={summary} streaming={item.running} /> : null;+ // start (before the first token arrives the result body is simply empty, as a thinking+ // block's is) rather than appearing mid-stream and shifting the row.+ const expandable =+ summary !== "" || thinking !== "" || (item.running && item.mode === "summarize");+ const body = expandable ? (+ <>+ {thinking !== "" && (+ <CompactionSection+ label={S.chat.thinking}+ text={thinking}+ streaming={item.thinkingStreaming === true}+ startedAtMs={item.thinkingStartedAtMs}+ durationMs={item.thinkingDurationMs}+ />+ )}+ {compactionResultVisible(item) && (+ <CompactionSection+ label={S.chat.compactionResult}+ text={summary}+ streaming={item.running}+ startedAtMs={item.summaryStartedAtMs}+ durationMs={item.summaryDurationMs}+ />+ )}+ </>+ ) : 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.+ // The title says both what runs and that it is running (压缩中 / "Compacting"), as the+ // work-group header's does; no detail line — the body streams behind the chevron, and the+ // raw `summarize`/`discard` wire value never shows.if (item.running) {return (<StepBannerstate="running"- title={S.chat.compactionTitle(item.mode)}+ title={S.chat.compactionRunning(item.mode)}{...(item.beginTsMs !== undefined ? { liveSinceMs: item.beginTsMs } : {})}>{body}@@ -65,9 +152,10 @@ export function CompactionBanner({ item }: { item: CompactionItem }) {return (<StepBannerstate={ok ? "done" : "failed"}- 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.+ // Success says everything through the title (压缩完毕 / "Compacted"), the icon and the+ // wall time; a failure keeps the bare mode word and needs a line, because its reason is+ // the part a title cannot carry.+ title={ok ? S.chat.compactionDone(item.mode) : S.chat.compactionTitle(item.mode)}detail={ok ? undefined : S.chat.compactionFailed(item.status ?? "failed", item.errorMessage)}{...(item.durationMs !== undefined ? { durationMs: item.durationMs } : {})}>diff --git a/packages/web/src/features/chat/step-banner.tsx b/packages/web/src/features/chat/step-banner.tsxindex 32a286ef..7c1f0399 100644--- a/packages/web/src/features/chat/step-banner.tsx+++ b/packages/web/src/features/chat/step-banner.tsx@@ -6,11 +6,16 @@* one-line detail changing. Duration sits right after the detail like the group header's* count+duration slots (LiveDuration ticking while running, the settled span with* decimals once finished); the flexible spacer keeps the chevron pinned at the right- * edge. A body (e.g. the discovered-tool groups) makes the row expandable, collapsed by- * default; collapsing while the sticky header is stuck scrolls the row back into view —- * the exact behavior of the work-group header.+ * edge. A body (e.g. the discovered-tool groups) makes the row expandable; collapsing while+ * the sticky header is stuck scrolls the row back into view — the exact behavior of the+ * work-group header.+ *+ * Expand policy, also the work group's (work-group.tsx): the body opens while the step runs,+ * so its rows are visible as they are appended, and closes itself once the step settles —+ * leaving the one-line summary the row exists to be. The body's own rows never open with it:+ * the reader is shown that they are there, not their contents.*/-import { useRef, useState } from "react";+import { useEffect, useRef, useState } from "react";import type { ReactNode } from "react";import { humanizeDuration } from "../../lib/format";import { Chevron } from "../../components/ui/chevron";@@ -36,14 +41,22 @@ export function StepBanner({liveSinceMs?: number;/** Settled wall time once finished. */durationMs?: number;- /** Expandable body; its presence adds the chevron (collapsed by default, streaming included). */+ /** Expandable body; its presence adds the chevron (open while running, closed once settled). */children?: ReactNode;}) {- const [open, setOpen] = useState(false);- const rootRef = useRef<HTMLDivElement>(null);const running = state === "running";+ const [open, setOpen] = useState(running);+ const userToggled = useRef(false);+ const rootRef = useRef<HTMLDivElement>(null);const expandable = children !== undefined && children !== null;+ // Before any manual toggle, follow "is this step still running". Afterwards the row is the+ // reader's: a later auto transition never fights them, so a finished row they opened to read+ // stays open, and one they closed mid-run stays closed.+ useEffect(() => {+ if (!userToggled.current) setOpen(running);+ }, [running]);+const header = (<><StatusIcon state={state} />@@ -94,6 +107,7 @@ export function StepBanner({type="button"aria-expanded={open}onClick={() => {+ userToggled.current = true;// Collapsing while the header is stuck: bring the (now header-only) card back// into view once React commits — `nearest` makes every other case a no-op.const willClose = open;diff --git a/packages/web/src/features/chat/work-group.tsx b/packages/web/src/features/chat/work-group.tsxindex a6cccfe5..49fa39f8 100644--- a/packages/web/src/features/chat/work-group.tsx+++ b/packages/web/src/features/chat/work-group.tsx@@ -1,10 +1,11 @@/*** "Reasoning & Tools" group: collapses a run of consecutive thinking +* tool-call items into one aggregated group.- * Expand policy: the group defaults to expanded while it's the last segment of the message- * stream (the current turn still in progress), and defaults to collapsed once later messages- * push it away from the end (turn finished); a manual toggle by the user is respected afterward.- * A pending approval **forces it open** — otherwise the approval buttons would be unreachable.+ * Expand policy, two layers deep: the group opens while it is running and closes itself once+ * it is done, and the thinking/tool rows inside it are appended one at a time and stay closed+ * — the reader is shown that a step happened and how long it took, not its contents, until+ * they ask. A manual toggle by the user is respected afterward. A pending approval **forces it+ * open** — otherwise the approval buttons would be unreachable.** Hierarchy: the group header is **a distinct title bar** (solid light-gray background + small* uppercase status text), and the thinking/tool-call rows inside the group sit on the white@@ -76,18 +77,20 @@ export function WorkGroup({// Last segment + Task running = the model might still call another tool → show Running (even if there's no active item right now).const active = (isLast && ctx.taskRunning) || itemsRunning;const pending = hasPendingApproval(items, ctx);- const [open, setOpen] = useState(isLast);+ const [open, setOpen] = useState(active);const userToggled = useRef(false);const rootRef = useRef<HTMLDivElement>(null);- // Before any manual toggle, follow "is last segment": expanded while in progress (last- // segment), collapsed once pushed away from the end by later messages (turn finished).- // Deliberately not driven by per-item active — there can be a brief gap with no active item- // between two steps within a turn, and collapsing on that basis would flicker on every step- // and lose the internal expanded state.+ // Before any manual toggle, follow the header's own Running/Done state: expanded while the+ // group is working, collapsed the moment it is done — whether that is later messages pushing+ // it away from the end mid-turn, or the Task ending on it. Deliberately `active` and not+ // per-item `itemsRunning`: there can be a brief gap with no active item between two steps+ // within a turn, and collapsing on that basis would flicker on every step and lose the+ // internal expanded state — the "last segment + Task running" half of `active` bridges those+ // gaps, so the group closes once and stays closed.useEffect(() => {- if (!userToggled.current) setOpen(isLast);- }, [isLast]);+ if (!userToggled.current) setOpen(active);+ }, [active]);// A pending approval must stay actionable: expand the group body regardless of collapsed state (the approval row lives inside it).const shown = open || pending;diff --git a/packages/web/src/lib/omni/compaction-summary.ts b/packages/web/src/lib/omni/compaction-summary.tsindex f5542a98..729d09ce 100644--- a/packages/web/src/lib/omni/compaction-summary.ts+++ b/packages/web/src/lib/omni/compaction-summary.ts@@ -12,6 +12,21 @@import { extractSummary } from "@prismshadow/penguin-core/markers";import type { CompactionItem } from "./stream-model";+/**+ * Whether the row's result section is on screen yet. It appears only once the request has+ * moved past its thinking: the first summary text lands (which is also what settles the+ * thinking section), or the compaction has completed with a summary. While the request is+ * still thinking the body shows the thinking section alone — a result row with nothing in it+ * beside a streaming thought read as two things happening at once, when only one was.+ */+export function compactionResultVisible(+ item: Pick<CompactionItem, "summaryText" | "summaryStartedAtMs" | "running" | "status">,+): boolean {+ if (compactionSummaryText(item) !== "") return true;+ if (item.summaryStartedAtMs !== undefined) return true;+ return !item.running && item.status === "completed";+}+export function compactionSummaryText(item: Pick<CompactionItem, "summaryText">): string {const raw = item.summaryText;if (!raw) return "";diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.tsindex 6ce43f96..ebb4527f 100644--- a/packages/web/src/lib/omni/stream-model.ts+++ b/packages/web/src/lib/omni/stream-model.ts@@ -30,11 +30,12 @@* performance analysis); compaction_begin/end → a banner item;* token_usage → fed into stats (task-stats.ts).* - Compaction-internal messages: model_msg within a- * compaction_begin↔end range (the compaction prompt and summary output)+ * compaction_begin↔end range (the compaction prompt, thinking and summary output)* are never rendered as transcript items and never counted toward Task- * segmentation; the summary's own text (live partial_text fragments, or- * the span's complete assistant text on rebuild) accumulates onto the- * running compaction banner instead (issue #290);+ * segmentation; the request's thinking and the summary's own text (live+ * partial_thinking / partial_text fragments, or the span's complete thinking+ * and assistant text on rebuild) accumulate onto the running compaction+ * banner instead (issue #290);* user text prefixed with `[context_summary]` is a compaction-summary* injection, treated as internal input (not rendered, doesn't start a new Task).* - Task segmentation: a complete text/image message on the main@@ -313,6 +314,44 @@ export interface CompactionItem {* the banner strips them for display); absent when nothing streamed (e.g. discard mode).*/summaryText?: string;+ /**+ * Raw text of the thinking the compaction request produced ahead of its summary:+ * accumulated live from the span's own partial_thinking fragments, and rebuilt identically+ * on history replay from the span's complete thinking messages — the banner shows it in a+ * collapsed section of its own. Absent when the request produced none (a model that does+ * not think, or discard mode).+ */+ thinkingText?: string;+ /** True while a thinking fragment of the compaction request is open (the section streams); settled by its stop, or by the end event. */+ thinkingStreaming?: boolean;+ /**+ * Start of the thinking section's wall time, and with it the rule both sections follow:+ * **a section is timed over exactly the window in which it shows itself running**, so the+ * number and the spinner beside it can never disagree.+ *+ * Thinking therefore starts at the first fragment that carried thinking and settles at that+ * fragment's stop — the moment the section stops spinning. The result section shows itself+ * running for the whole compaction (it has no fragment flag of its own), so it starts at the+ * first summary text and settles at `compaction_end`; its share of the header's begin-to-end+ * span is what the request spent writing plus the adoption behind it.+ *+ * History rebuild has no fragments: the previous message's time approximates each start and+ * the complete message's own time settles it — the ThinkingItem convention (see+ * `settleThinkingDuration`), so a reload lands within a message hop of the live numbers.+ *+ * A retried compaction concatenates every attempt into one draft (`thinkingText` and+ * `summaryText` both), so a start is recorded once and a later stop only extends the settled+ * value: the wall time covers the whole span that produced the prose on screen, the failed+ * attempts and the gaps between them included. Timing the last attempt alone would print a+ * short number against text it did not write.+ */+ thinkingStartedAtMs?: number;+ /** Settled thinking wall time (boundaries: see thinkingStartedAtMs). */+ thinkingDurationMs?: number;+ /** Start of the result section's wall time (boundaries: see thinkingStartedAtMs). */+ summaryStartedAtMs?: number;+ /** Settled result wall time (boundaries: see thinkingStartedAtMs). */+ summaryDurationMs?: number;}/** One MCP tool for the connect row's expandable list (from tool_list_ready, `mcp__` entries only). */@@ -619,26 +658,44 @@ export function pushMessage(if (!isCompleteUserImage(msg)) model.openSteering = null;if (msg.type === "model_msg") {// Internal messages within a compaction range (between begin and end)- // (the compaction prompt, summary output): never rendered as transcript items, never- // counted toward Task segmentation. The summary being written is the one exception- // (issue #290): live it arrives as its own partial_text fragments (the engine forwards- // them between the paired events; the complete text stays off the stream once partials- // carried it), and history rebuild reads the identical content back from the span's- // complete assistant text — both accumulate onto the running banner, so a reload shows- // the same text the live viewer watched being written.+ // (the compaction prompt, thinking, summary output): never rendered as transcript items,+ // never counted toward Task segmentation. The request's thinking and the summary being+ // written are the exception (issue #290): live they arrive as their own partial_thinking+ // / partial_text fragments (the engine forwards them between the paired events; the+ // complete messages stay off the stream once partials carried them), and history rebuild+ // reads the identical content back from the span's complete thinking and assistant text+ // — both accumulate onto the running banner, so a reload shows the same text the live+ // viewer watched being written.if (model.stats.compactionActive) {touchTask(model, msg.timestamp);+ const tsMs = tsOf(msg.timestamp);if (isPartialPayload(msg.payload)) {- const p = msg.payload as { type?: string; text?: string };- if (p.type === "partial_text" && p.text) appendCompactionSummaryText(model, p.text);+ const p = msg.payload as {+ type?: string;+ event_type?: string;+ text?: string;+ thinking?: string;+ };+ // Live, a section is timed by its own fragment, so this one timestamp both starts it+ // (its first content) and, on the stop phase, settles it.+ if (p.type === "partial_text" && p.text) appendCompactionSummaryText(model, p.text, tsMs);+ else if (p.type === "partial_thinking") {+ appendCompactionThinking(model, p.thinking ?? "", p.event_type !== "stop", tsMs, tsMs);+ }// Partials never advance lastTs (same rule as the normal path below).return;}- advanceLastTs(model, msg.timestamp);- const p = msg.payload as { type?: string; role?: string; text?: string };+ const p = msg.payload as { type?: string; role?: string; text?: string; thinking?: string };+ // History rebuild has no fragments: the previous message's time approximates the+ // section's start (the ThinkingItem convention), this message's own time settles it.+ // Read before advanceLastTs below, exactly as the ordinary complete path reads it.+ const startMs = model.lastTsMs > 0 ? model.lastTsMs : undefined;if (p.type === "text" && p.role === "assistant" && p.text) {- appendCompactionSummaryText(model, p.text);+ appendCompactionSummaryText(model, p.text, startMs);+ } else if (p.type === "thinking" && p.thinking) {+ appendCompactionThinking(model, p.thinking, false, startMs, tsMs);}+ advanceLastTs(model, msg.timestamp);return;}if (isPartialPayload(msg.payload)) {@@ -1636,11 +1693,29 @@ function handleEvent(model: StreamModel, p: EventPayload, tsMs?: number, nowMs?:if (tsMs !== undefined && item.beginTsMs !== undefined) {item.durationMs = Math.max(0, tsMs - item.beginTsMs);}+ // The result section runs for as long as the row does, so its wall time ends here too.+ if (tsMs !== undefined && item.summaryStartedAtMs !== undefined) {+ item.summaryDurationMs = Math.max(0, tsMs - item.summaryStartedAtMs);+ }// A compaction that did not complete produced no summary — only a half-written// draft that was never adopted (a user quitting mid-compaction is the common case,- // closed as `failed` when the session next loads). Discard it rather than leave a- // truncated summary on screen implying the context was replaced by it.- if (p.status !== "completed") delete item.summaryText;+ // closed as `failed` when the session next loads). Discard it, and the thinking that+ // led to it, rather than leave a truncated summary on screen implying the context+ // was replaced by it.+ if (p.status !== "completed") {+ delete item.summaryText;+ delete item.thinkingText;+ delete item.thinkingStreaming;+ delete item.thinkingStartedAtMs;+ delete item.thinkingDurationMs;+ delete item.summaryStartedAtMs;+ delete item.summaryDurationMs;+ } else if (item.thinkingStreaming) {+ // Nothing streams past the end: a fragment whose stop never arrived settles here,+ // and its wall time settles with it rather than leaving the row without a number.+ item.thinkingStreaming = false;+ settleCompactionThinking(item, tsMs);+ }} else {// Mid-stream join (missed the begin): append a completed banner directly.const created: CompactionItem = {@@ -1782,11 +1857,55 @@ function findLastRunningCompaction(model: StreamModel): CompactionItem | null {return null;}-/** Appends streamed/replayed summary text onto the running compaction banner (no-op without one). */-function appendCompactionSummaryText(model: StreamModel, text: string): void {+/**+ * Appends streamed/replayed summary text onto the running compaction banner and starts the+ * result section's wall time on its first content (no-op without a running banner); the+ * section settles at compaction_end, where it stops showing itself as running.+ */+function appendCompactionSummaryText(+ model: StreamModel,+ text: string,+ startMs: number | undefined,+): void {if (!text) return;const item = findLastRunningCompaction(model);- if (item) item.summaryText = (item.summaryText ?? "") + text;+ if (!item) return;+ item.summaryText = (item.summaryText ?? "") + text;+ if (startMs !== undefined && item.summaryStartedAtMs === undefined) {+ item.summaryStartedAtMs = startMs;+ }+}++/**+ * Appends streamed/replayed thinking onto the running compaction banner, records whether its+ * fragment is still open, and times the section from its first content to the stop that closes+ * it (no-op without a running banner). A content-free phase (the start, the stop) only moves+ * the streaming flag, so a request that never thought leaves no empty draft — and no stray+ * wall time — behind.+ */+function appendCompactionThinking(+ model: StreamModel,+ text: string,+ streaming: boolean,+ startMs: number | undefined,+ endMs: number | undefined,+): void {+ const item = findLastRunningCompaction(model);+ if (!item) return;+ if (text) {+ item.thinkingText = (item.thinkingText ?? "") + text;+ if (startMs !== undefined && item.thinkingStartedAtMs === undefined) {+ item.thinkingStartedAtMs = startMs;+ }+ }+ item.thinkingStreaming = streaming;+ if (!streaming) settleCompactionThinking(item, endMs);+}++/** Settle the thinking section: end time - its recorded start (a later attempt's stop extends the same span). */+function settleCompactionThinking(item: CompactionItem, endMs: number | undefined): void {+ if (endMs === undefined || item.thinkingStartedAtMs === undefined) return;+ item.thinkingDurationMs = Math.max(0, endMs - item.thinkingStartedAtMs);}/**diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex a5e23f7d..6b3c50e1 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1830,6 +1830,9 @@ Scenarios:mcpServerFailed: "connection failed",mcpConnectAborted: "interrupted — reconnects on the next send",compactionTitle: (mode: string): string => (mode === "discard" ? "Clear" : "Compaction"),+ compactionRunning: (mode: string): string => (mode === "discard" ? "Clearing" : "Compacting"),+ compactionDone: (mode: string): string => (mode === "discard" ? "Cleared" : "Compacted"),+ compactionResult: "Result",compactionFailed: (status: string, errorMessage?: string): string => {if (status === "aborted") return "aborted, keeping current context";const detail = errorMessage !== undefined ? ` (${errorMessage})` : "";diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex bca0d484..3233e642 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1802,8 +1802,13 @@ Benchmark:mcpToolsCount: (n: number): string => `${n} 个工具`,mcpServerFailed: "连接失败",mcpConnectAborted: "已中断,下次发送时重新连接",- /** 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. */+ /** The bare mode word — the Trace view's round badge, the failed row's title, and the stem of the two state titles below — so a `discard` is never announced as compaction: it clears the context rather than compacting it. */compactionTitle: (mode: string): string => (mode === "discard" ? "清空" : "压缩"),+ /** The row's title doubles as its status, the work-group header's idiom (`workRunning` / `workDone`): 压缩中 / 清空中 while the step runs, 压缩完毕 / 清空完毕 once it settles. With mode and state both in the title nothing is left for a detail line on either side — a `summarize` shows its summary in its own expandable body — so only `compactionFailed` keeps the detail slot, carrying the one thing a title cannot. */+ compactionRunning: (mode: string): string => (mode === "discard" ? "清空中" : "压缩中"),+ compactionDone: (mode: string): string => (mode === "discard" ? "清空完毕" : "压缩完毕"),+ /** The summarize row's second body section (the first reuses `thinking`): the summary the compaction request wrote. */+ compactionResult: "压缩结果",compactionFailed: (status: string, errorMessage?: string): string => {if (status === "aborted") return "已中断,保留当前上下文";const detail = errorMessage !== undefined ? `(${errorMessage})` : "";@@ -2330,7 +2335,7 @@ Benchmark:cacheHit: "命中缓存",hitRate: "命中率",compactions: "压缩次数",- /** The round-card badge reuses `chat.compactionTitle`, which names the mode (压缩 / 清空), so the Trace view and the conversation cannot drift apart; there is deliberately no Trace-local copy of that word. */+ /** The round-card badge reuses `chat.compactionTitle`, which names the mode (压缩 / 清空) and is the stem of the conversation row's state titles (压缩中 / 压缩完毕), so the Trace view and the conversation cannot drift apart; there is deliberately no Trace-local copy of that word. */inProgress: "进行中",systemPrompt: "系统提示词",toolDefs: (n: number) => `工具定义(${n})`,diff --git a/packages/web/test/compaction-summary.test.ts b/packages/web/test/compaction-summary.test.tsindex 7c52ed30..a746faf1 100644--- a/packages/web/test/compaction-summary.test.ts+++ b/packages/web/test/compaction-summary.test.ts@@ -1,17 +1,21 @@/**- * What a compaction row shows: the text inside its collapsed body (compaction-summary.ts)- * and the title above it (the dictionaries' mode-aware `compactionTitle`).+ * What a compaction row shows: the text inside its result section (compaction-summary.ts)+ * and the titles above it (the dictionaries' mode-aware `compactionTitle`, and the state+ * titles `compactionRunning` / `compactionDone` the header shows while the step runs and once+ * it settles, the work-group header's own Running/Done idiom).*- * 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- * watch the summary stream or to read it afterwards. What that body contains is this pure- * helper's job, and it is what these tests pin (the Web suite runs in a node environment- * and renders no React).+ * The row itself is a StepBanner whose body stacks a thinking section and a result section.+ * The banner opens while the compaction runs and closes itself once it settles; the two+ * sections stay closed throughout, showing only their labels and their wall times — the+ * reader expands one to watch the request think or write, or to read the outcome afterwards.+ * What the result section then contains is this pure helper's job, and it is what these tests+ * pin; the section timings behind those wall times are pinned in stream-model.test.ts (the+ * Web suite runs in a node environment 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";+import { compactionResultVisible, compactionSummaryText } from "../src/lib/omni/compaction-summary";describe("compactionSummaryText", () => {it("strips the summary tags so the body reads as prose", () => {@@ -37,6 +41,26 @@ describe("compactionSummaryText", () => {});});+describe("compactionResultVisible (the result section waits for the thinking to finish)", () => {+ it("stays hidden while the request is still thinking and no summary has started", () => {+ expect(+ compactionResultVisible({ running: true, summaryText: "", summaryStartedAtMs: undefined }),+ ).toBe(false);+ expect(compactionResultVisible({ running: true })).toBe(false);+ });++ it("appears with the first summary text, which is what ends the thinking", () => {+ expect(compactionResultVisible({ running: true, summaryStartedAtMs: 1000 })).toBe(true);+ expect(compactionResultVisible({ running: true, summaryText: "<summary>x" })).toBe(true);+ });++ it("is shown on a completed row, and never on one that failed with its drafts discarded", () => {+ expect(compactionResultVisible({ running: false, status: "completed" })).toBe(true);+ expect(compactionResultVisible({ running: false, status: "fatal" })).toBe(false);+ expect(compactionResultVisible({ running: false, status: "aborted" })).toBe(false);+ });+});+describe("compactionTitle (the row is titled by its mode)", () => {it("never labels a discard as compaction — the whole point of titling by mode", () => {for (const [locale, dict] of [@@ -64,3 +88,32 @@ describe("compactionTitle (the row is titled by its mode)", () => {}});});++describe("compactionRunning / compactionDone (the title doubles as the status, as the work group's does)", () => {+ it("reads 压缩中 while a compaction runs and 压缩完毕 once it settles", () => {+ expect(zh.chat.compactionRunning("summarize")).toBe("压缩中");+ expect(zh.chat.compactionDone("summarize")).toBe("压缩完毕");+ });++ it("keeps the two states and the two modes apart in both dictionaries", () => {+ for (const [locale, dict] of [+ ["zh", zh],+ ["en", en],+ ] as const) {+ for (const mode of ["summarize", "discard"]) {+ expect(dict.chat.compactionRunning(mode), `${locale} ${mode}`).toBeTruthy();+ expect(+ dict.chat.compactionRunning(mode),+ `${locale} ${mode} running reads as settled`,+ ).not.toBe(dict.chat.compactionDone(mode));+ }+ // A discard never reads as compacting, in either state — the point of titling by mode.+ expect(dict.chat.compactionRunning("discard"), locale).not.toBe(+ dict.chat.compactionRunning("summarize"),+ );+ expect(dict.chat.compactionDone("discard"), locale).not.toBe(+ dict.chat.compactionDone("summarize"),+ );+ }+ });+});diff --git a/packages/web/test/stream-model.test.ts b/packages/web/test/stream-model.test.tsindex 0b3350f9..a8e2dfdf 100644--- a/packages/web/test/stream-model.test.ts+++ b/packages/web/test/stream-model.test.ts@@ -490,6 +490,164 @@ describe("approvals and events", () => {expect(after[0]!.text).toBe("next answer");});+ it("the span's partial_thinking accumulates the request's thinking onto the running banner, streaming until its stop", () => {+ const m = createStreamModel();+ pushMessage(+ m,+ compactionBegin({ reason: "context", mode: "summarize", context: 1000, turns: 3 }),+ );+ const banner = items(m)[0] as CompactionItem;+ // A content-free start opens the fragment without leaving an empty draft behind.+ pushMessage(m, partialThinking("start"));+ expect(banner.thinkingText).toBeUndefined();+ expect(banner.thinkingStreaming).toBe(true);+ pushMessage(m, partialThinking("delta", "what matters "));+ pushMessage(m, partialThinking("delta", "is the plan"));+ expect(banner.thinkingText).toBe("what matters is the plan");+ expect(banner.thinkingStreaming).toBe(true);+ pushMessage(m, partialThinking("stop"));+ expect(banner.thinkingStreaming).toBe(false);+ // The summary follows on its own draft; the thinking is never summary material.+ pushMessage(m, partialText("start"));+ pushMessage(m, partialText("delta", "[summary]the plan[/summary]"));+ pushMessage(m, partialText("stop"));+ expect(banner.summaryText).toBe("[summary]the plan[/summary]");+ expect(banner.thinkingText).toBe("what matters is the plan");+ // The span's thinking renders no transcript item of its own.+ expect(items(m).filter((i) => i.kind === "thinking")).toHaveLength(0);+ pushMessage(m, compactionEnd({ reason: "context", mode: "summarize", status: "completed" }));+ expect(banner).toMatchObject({+ thinkingText: "what matters is the plan",+ thinkingStreaming: false,+ });+ // After the span, partial_thinking is ordinary model output again: a thinking item.+ pushMessage(m, partialThinking("start"));+ pushMessage(m, partialThinking("delta", "next thought"));+ expect(banner.thinkingText).toBe("what matters is the plan");+ const after = items(m).filter((i) => i.kind === "thinking") as ThinkingItem[];+ expect(after).toHaveLength(1);+ expect(after[0]!.thinking).toBe("next thought");+ });++ it("the end event settles a thinking fragment whose stop never arrived", () => {+ const m = createStreamModel();+ pushMessage(+ m,+ compactionBegin({ reason: "manual", mode: "summarize", context: 1000, turns: 3 }),+ );+ const banner = items(m)[0] as CompactionItem;+ pushMessage(m, partialThinking("start"));+ pushMessage(m, partialThinking("delta", "half a thought"));+ pushMessage(m, partialText("start"));+ pushMessage(m, partialText("delta", "[summary]the plan[/summary]"));+ pushMessage(m, compactionEnd({ reason: "manual", mode: "summarize", status: "completed" }));+ expect(banner).toMatchObject({ thinkingText: "half a thought", thinkingStreaming: false });+ // Its wall time settles with the flag, so the row never shows a settled section with no number.+ expect(banner.thinkingDurationMs).toBeGreaterThanOrEqual(0);+ });++ it("times each body section over exactly the window it shows itself running (live fragments)", () => {+ const m = createStreamModel();+ const t = (sec: number) => `2026-01-01T00:00:${String(sec).padStart(2, "0")}.000Z`;+ const ms = (sec: number) => Date.parse(t(sec));+ pushMessage(+ m,+ at(compactionBegin({ reason: "context", mode: "summarize", context: 1000, turns: 3 }), t(0)),+ );+ const banner = items(m)[0] as CompactionItem;+ // A content-free start opens the fragment but starts no clock: the section is not on+ // screen yet, and a request that never thinks must leave no stray wall time behind.+ pushMessage(m, at(partialThinking("start"), t(1)));+ expect(banner.thinkingStartedAtMs).toBeUndefined();+ pushMessage(m, at(partialThinking("delta", "weighing "), t(2)));+ pushMessage(m, at(partialThinking("delta", "the transcript"), t(3)));+ expect(banner.thinkingStartedAtMs).toBe(ms(2));+ expect(banner.thinkingDurationMs).toBeUndefined();+ // Thinking settles at its own stop — the moment its spinner stops.+ pushMessage(m, at(partialThinking("stop"), t(6)));+ expect(banner.thinkingDurationMs).toBe(4000);+ // The result section's clock starts at its first token, not at its fragment's start.+ pushMessage(m, at(partialText("start"), t(6)));+ expect(banner.summaryStartedAtMs).toBeUndefined();+ pushMessage(m, at(partialText("delta", "[summary]the plan[/summary]"), t(7)));+ expect(banner.summaryStartedAtMs).toBe(ms(7));+ // ...and runs on past its own stop, because the section keeps showing itself running+ // until the row does: settling earlier would print a number the spinner contradicts.+ pushMessage(m, at(partialText("stop"), t(8)));+ expect(banner.summaryDurationMs).toBeUndefined();+ pushMessage(+ m,+ at(compactionEnd({ reason: "context", mode: "summarize", status: "completed" }), t(10)),+ );+ expect(banner).toMatchObject({+ durationMs: 10000,+ thinkingDurationMs: 4000,+ summaryDurationMs: 3000,+ });+ });++ it("a retried compaction times the whole span its concatenated draft covers", () => {+ const m = createStreamModel();+ const t = (sec: number) => `2026-01-01T00:00:${String(sec).padStart(2, "0")}.000Z`;+ pushMessage(+ m,+ at(compactionBegin({ reason: "context", mode: "summarize", context: 1000, turns: 3 }), t(0)),+ );+ const banner = items(m)[0] as CompactionItem;+ // Attempt 1: thinks, starts writing, then the request dies and the engine resends.+ pushMessage(m, at(partialThinking("start"), t(1)));+ pushMessage(m, at(partialThinking("delta", "first pass"), t(2)));+ pushMessage(m, at(partialThinking("stop"), t(3)));+ pushMessage(m, at(partialText("delta", "[summary]half"), t(4)));+ // Attempt 2 continues the same span, so both drafts concatenate.+ pushMessage(m, at(partialThinking("start"), t(5)));+ pushMessage(m, at(partialThinking("delta", " second pass"), t(6)));+ pushMessage(m, at(partialThinking("stop"), t(9)));+ pushMessage(m, at(partialText("delta", " the plan[/summary]"), t(10)));+ pushMessage(+ m,+ at(compactionEnd({ reason: "context", mode: "summarize", status: "completed" }), t(12)),+ );+ // Each start is recorded once and each later stop only extends it: the wall time covers+ // the span that produced the prose on screen, the failed attempt included. Timing the+ // last attempt alone would print 3s against text that took nine.+ expect(banner).toMatchObject({+ thinkingText: "first pass second pass",+ thinkingStartedAtMs: Date.parse(t(2)),+ thinkingDurationMs: 7000,+ summaryStartedAtMs: Date.parse(t(4)),+ summaryDurationMs: 8000,+ });+ });++ it("history replay rebuilds the same section timings from the span's complete messages", () => {+ // The Trace records no fragments, so each section's start is approximated by the previous+ // message's time — the ThinkingItem convention — and a reload lands within a message hop+ // of what the live viewer watched tick.+ const m = createStreamModel();+ const t = (sec: number) => `2026-01-01T00:00:${String(sec).padStart(2, "0")}.000Z`;+ pushMessage(+ m,+ at(compactionBegin({ reason: "context", mode: "summarize", context: 1000, turns: 3 }), t(0)),+ );+ pushMessage(m, at(userText("COMPACT NOW"), t(1)));+ pushMessage(m, at(requestBegin(), t(2)));+ pushMessage(m, at(thinkingMessage("planning"), t(6)));+ pushMessage(m, at(assistantText("[summary]the plan[/summary]"), t(9)));+ pushMessage(m, at(requestEnd("completed"), t(9)));+ pushMessage(+ m,+ at(compactionEnd({ reason: "context", mode: "summarize", status: "completed" }), t(10)),+ );+ const banner = items(m).find((i) => i.kind === "compaction") as CompactionItem;+ expect(banner).toMatchObject({+ thinkingStartedAtMs: Date.parse(t(2)),+ thinkingDurationMs: 4000,+ summaryStartedAtMs: Date.parse(t(6)),+ summaryDurationMs: 4000,+ });+ });+it("history replay rebuilds the banner's summary text from the compaction span's assistant output", () => {// Live, the deltas carried the text; the Trace records the same text as the span's// complete assistant messages. A reload must show the same summary the live viewer saw.@@ -505,14 +663,16 @@ describe("approvals and events", () => {);pushMessage(m, userText("COMPACT NOW")); // the compaction prompt: user text, never summary materialpushMessage(m, requestBegin());- pushMessage(m, thinkingMessage("planning")); // thinking is not summary text either+ pushMessage(m, thinkingMessage("planning")); // thinking is not summary text: it rebuilds the thinking sectionpushMessage(m, assistantText("[summary]the plan[/summary]"));pushMessage(m, requestEnd("completed"));pushMessage(m, compactionEnd({ reason: "context", mode: "summarize", status: "completed" }));const banner = items(m).find((i) => i.kind === "compaction") as CompactionItem;expect(banner.summaryText).toBe("[summary]the plan[/summary]");+ expect(banner).toMatchObject({ thinkingText: "planning", thinkingStreaming: false });// Span-internal messages still render nothing of their own.expect(items(m).filter((i) => i.kind === "assistant_text")).toHaveLength(1);+ expect(items(m).filter((i) => i.kind === "thinking")).toHaveLength(0);});it("a compaction the user quit out of is closed as failed on load; the conversation after it renders (issue #288)", () => {@@ -527,6 +687,7 @@ describe("approvals and events", () => {);pushMessage(m, userText("COMPACT NOW"));pushMessage(m, requestBegin());+ pushMessage(m, thinkingMessage("weighing the transcript"));pushMessage(m, assistantText("[summary]half-writ")); // the draft the crash interrupted// ...process died here; the resume closes the span as retryable before writing anything else:pushMessage(m, compactionEnd({ reason: "context", mode: "summarize", status: "retryable" }));@@ -545,25 +706,37 @@ describe("approvals and events", () => {expect(cards[0]!.name).toBe("exec");expect(cards[0]!.output).toBe("ok");// The interrupted compaction reads as failed, and its half-written draft is discarded- // rather than shown as if it were the adopted summary.+ // rather than shown as if it were the adopted summary — the thinking behind it too.const banner = items(m).find((i) => i.kind === "compaction") as CompactionItem;expect(banner).toMatchObject({ running: false, status: "retryable" });expect(banner.summaryText).toBeUndefined();+ expect(banner.thinkingText).toBeUndefined();});- it("an aborted compaction discards its partial summary too (live interrupt)", () => {+ it("an aborted compaction discards its partial summary and thinking too (live interrupt)", () => {const m = createStreamModel();pushMessage(m,compactionBegin({ reason: "manual", mode: "summarize", context: 1000, turns: 3 }),);+ pushMessage(m, partialThinking("start"));+ pushMessage(m, partialThinking("delta", "half a thought"));+ pushMessage(m, partialThinking("stop"));pushMessage(m, partialText("start"));pushMessage(m, partialText("delta", "[summary]partial draft"));const banner = items(m)[0] as CompactionItem;expect(banner.summaryText).toBe("[summary]partial draft");+ expect(banner.thinkingText).toBe("half a thought");pushMessage(m, compactionEnd({ reason: "manual", mode: "summarize", status: "aborted" }));expect(banner.status).toBe("aborted");expect(banner.summaryText).toBeUndefined();+ expect(banner.thinkingText).toBeUndefined();+ expect(banner.thinkingStreaming).toBeUndefined();+ // Nothing is left to time either: no section renders, so no wall time may survive it.+ expect(banner.thinkingStartedAtMs).toBeUndefined();+ expect(banner.thinkingDurationMs).toBeUndefined();+ expect(banner.summaryStartedAtMs).toBeUndefined();+ expect(banner.summaryDurationMs).toBeUndefined();});it("a completed compaction keeps its summary for the collapsed body", () => {