A local-first multi-agent app development platform, built on PenguinHarness
fix(core,server,web,cli): compaction continuity, collapsed streamed summaries, and interrupted-run discard (#329)
Yaowei Zheng207b2bf48f96
diff --git a/changelog/unreleased/2026-08-18-compaction-continuity-and-streaming.md b/changelog/unreleased/2026-08-18-compaction-continuity-and-streaming.mdnew file mode 100644index 00000000..5f63b655--- /dev/null+++ b/changelog/unreleased/2026-08-18-compaction-continuity-and-streaming.md@@ -0,0 +1,44 @@+# Compaction: tool-first ordering, interrupted compactions fail cleanly, and a collapsed streaming summary++- **Date:** 2026-08-18+- **Type:** fix+- **Scope:** `core`, `server`, `web`, `cli`+- **PR:** [#329](https://github.com/Prism-Shadow/penguin-harness/pull/329)+- **Issue:** [#288](https://github.com/Prism-Shadow/penguin-harness/issues/288), [#290](https://github.com/Prism-Shadow/penguin-harness/issues/290)++[中文版](2026-08-18-compaction-continuity-and-streaming.zh.md)++Two compaction defects were fixed and the compaction row gained a live, collapsed summary. A compaction triggered after a tool call now runs the tools to completion and compacts with their results, inventing nothing synthetic; a compaction the user quit out of is closed as failed when the session next loads, with its half-written draft discarded, so messages sent after a compaction survive a reload and stale `(unknown tool)` cards are gone; and the summary reaches the Web App as it is written, inside a block that is collapsed by default exactly like a thinking block.++## A compaction triggered after a tool call runs the tools first++The engine reaches its compaction checkpoint only after `runTurn` has returned, which happens once every tool call of the turn has completed — so a compaction that triggers on a turn ending in tool calls never preempts them.++- All of the turn's results ride the compaction request itself, ahead of the compaction Prompt and in their original call order, whatever they carry: a normal result, a `[tool error]`, or a denial.+- A tool waiting on approval or running for minutes only 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 pending exchange, and the `LLMInterface` is unchanged.+- Manual `/compact` keeps its own semantics: it has no pending turn, so only the Prompt (plus any interruption carry-over it folds in) goes out.++## A compaction the user quit out of is simply a failed compaction++Quitting mid-compaction left a `compaction_begin` with no matching end in the shard. Core's replay tolerated it and appended the follow-up conversation to the same file, but every reader treats messages between the pair as compaction-internal, so everything sent after the compaction vanished on reload; once a later `compaction_end` un-wedged the state mid-Task, tool outputs rendered without their swallowed calls as "(unknown tool)" cards.++- `resumeTrace` reports the unmatched begin, and `resumeSession` closes the span with a `failed` `compaction_end` before any new record lands, leaving the file well-formed for every later reader. It is idempotent and skipped for healthy traces.+- The interrupted compaction's half-written summary is **discarded**, never reconstructed: no `[context_summary]` is injected, the original context stands, and the standing threshold makes the compaction up at the next trigger.+- The Web reducer drops the partial draft from any compaction that did not complete, so a truncated summary is never shown as if it had been adopted.+- The reader-side stale-span heuristics added earlier in this PR were removed along with the scanner cache-version bump: closing the span at load is enough, and the readers stay simple.++## An abandoned compaction ends the run and is made up later++A mid-Task compaction that failed used to leave the loop in an ill-defined state: the run either ended empty-handed right after the compaction, or continued on bare `[tool error]` repair outputs the model had no instruction to act on.++- A failed or aborted mid-Task compaction now ends the run the way any interruption does: the turn's pending state is held as carry-over under the existing committed/not-committed rule ([#85](https://github.com/Prism-Shadow/penguin-harness/issues/85)), an `abort` event closes the run (`compaction failed` for the failure case), and the next message resends that carry-over merged with the user's input — where the still-standing threshold triggers the compaction again.+- At a Task boundary a failed compaction keeps the original context and simply ends the run, as before.++## The compaction summary streams live++The compaction request's raw messages stay Trace-only, with one exception: the summary being generated 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 new protocol type is involved, and the Trace is unchanged.++- The Web App's compaction row is **collapsed by default, exactly like a thinking block**: the chevron is present from the start of a summarize compaction, and the summary streams inside the collapsed body (same `md-body` treatment and streaming renderer thinking uses), which the reader expands to watch it being written or to read it afterwards. Tags are stripped by the same lenient extractor core uses, so a summary still mid-stream reads as prose. A history rebuild reads the same text back from the span's recorded assistant output, so a reload shows what the live viewer saw.+- Because the text is an ordinary streamed message, the server's live tail seeds it too: joining or refreshing mid-compaction picks up the summary prefix generated so far instead of starting blank.+- The CLI keeps its one-line compaction progress and prints none of the streamed summary.diff --git a/changelog/unreleased/2026-08-18-compaction-continuity-and-streaming.zh.md b/changelog/unreleased/2026-08-18-compaction-continuity-and-streaming.zh.mdnew file mode 100644index 00000000..9760f90d--- /dev/null+++ b/changelog/unreleased/2026-08-18-compaction-continuity-and-streaming.zh.md@@ -0,0 +1,44 @@+# 压缩:先执行工具再压缩、中途退出即判失败、摘要默认折叠流式呈现++- **Date:** 2026-08-18+- **Type:** fix+- **Scope:** `core`, `server`, `web`, `cli`+- **PR:** [#329](https://github.com/Prism-Shadow/penguin-harness/pull/329)+- **Issue:** [#288](https://github.com/Prism-Shadow/penguin-harness/issues/288), [#290](https://github.com/Prism-Shadow/penguin-harness/issues/290)++[English](2026-08-18-compaction-continuity-and-streaming.md)++修复了两个压缩缺陷,并让压缩行以默认折叠的方式实时呈现摘要。工具调用之后触发的压缩,现在先把工具执行完,再带着工具结果开始压缩,全程不合成任何东西;用户中途退出程序导致没写完的压缩,会在会话下次加载时以失败收束、并丢弃写了一半的草稿,因此压缩之后发出的消息不再因刷新而消失,过期的 `(unknown tool)` 卡片也随之消失;摘要则在写出的同时抵达 Web App,并且像思考块一样默认折叠。++## 工具调用之后触发的压缩,先把工具执行完++引擎只有在 `runTurn` 返回之后才会走到压缩检查点,而 `runTurn` 要等本轮全部工具调用执行完毕才返回——所以在以工具调用收尾的一轮上触发的压缩,绝不会抢在工具前面。++- 本轮所有工具结果都随压缩请求本身发出,排在压缩 Prompt 之前、保持原始调用顺序,无论它们承载的是正常结果、`[tool error]` 还是被拒绝的回执。+- 需要审批或耗时数分钟的工具只是让压缩延后:压缩请求尚未发出,也就没有任何计时在跑。+- 全程不插入任何合成消息去闭合待决的交换,`LLMInterface` 保持不变。+- 手动 `/compact` 保留自己的语义:它没有待决的轮次,因此只发出 Prompt(以及它折叠进来的打断 carry-over)。++## 用户中途退出导致的压缩,就是一次压缩失败++压缩进行到一半时退出程序,会在分片里留下一个没有对应结束事件的 `compaction_begin`。核心的重放能够容忍它,并把后续对话继续追加到同一个文件,但每一个读取方都会把这一对事件之间的消息当作压缩内部内容,于是压缩之后发出的一切都会在重新加载时消失;等到后来某个 `compaction_end` 在 Task 中途把状态解开,工具输出便会因为其调用被吞掉而渲染成 `(unknown tool)` 卡片。++- `resumeTrace` 会报告这个未配对的 begin,`resumeSession` 则在任何新记录落盘之前以 `failed` 收束该区间,使文件对此后每一个读取方都是良构的。该处理是幂等的,健康的 Trace 会被跳过。+- 这次压缩写了一半的摘要会被**直接丢弃**,绝不重建:不注入任何 `[context_summary]`,原上下文照旧,阈值依然超标、压缩留待下次触发时补做。+- Web 侧的 reducer 会丢掉任何未完成压缩的半成品草稿,绝不把截断的摘要摆成像是已被采纳的样子。+- 本 PR 早先加入的读取方侧「过期区间」启发式规则,连同扫描器缓存版本的提升一并移除:在加载时收束区间已经足够,读取方因此保持简单。++## 被放弃的压缩结束本次运行、留待补做++Task 中途的压缩一旦失败,此前的循环会陷入一个说不清的状态:整个运行要么在压缩之后空手而归地结束,要么只带着几条光秃秃的 `[tool error]` 修复输出继续,而模型并没有收到任何据以行动的指示。++- Task 中途的压缩失败或被中止时,现在按普通打断的同一套流程收场:本轮尚未了结的状态按既有的「是否已提交」规则转入 carry-over([#85](https://github.com/Prism-Shadow/penguin-harness/issues/85)),以 `abort` 事件结束本次运行(失败一路的原因为 `compaction failed`),下一条消息把 carry-over 与用户输入合并重发——阈值依然超标,压缩在那里再次触发。+- Task 边界上的压缩失败一如既往:保留原上下文,直接结束本次运行。++## 压缩摘要实时流式呈现++压缩请求的原始消息仍然只存在于 Trace 中,唯一的例外是正在生成的摘要:它以普通的 `partial_text`(不产出流式消息的 LLM 实现则为完整 `text`)在成对的压缩事件之间上行。整个过程不涉及新的协议类型,Trace 的内容也没有变化。++- Web App 的压缩行**默认折叠,与思考块完全一致**:summarize 压缩一开始就带上折叠箭头,摘要在折叠的正文内流式写出(沿用思考块的 `md-body` 样式与同一个流式渲染器),读者展开即可实时观看或事后阅读。标签由核心所用的同一个宽松抽取器剥掉,因此仍在流式过程中的摘要读起来就是正文。历史重建从压缩区间已记录的助手输出读回同一段文本,因此重新加载后看到的与实时观看者看到的一致。+- 由于这段文本就是普通的流式消息,服务端的实时尾巴(live tail)也会记录它:在压缩过程中加入或刷新页面,能接上此前已生成的摘要前缀,而不是从空白开始。+- CLI 保留它那一行压缩进度提示,不打印流式摘要的任何内容。diff --git a/packages/cli/src/render.ts b/packages/cli/src/render.tsindex 66a293ca..6d3aa88c 100644--- a/packages/cli/src/render.ts+++ b/packages/cli/src/render.ts@@ -900,6 +900,10 @@ export class StreamRenderer {}private handlePartialText(p: PartialTextPayload): void {+ // Between the paired compaction events the stream carries the summary being written as+ // ordinary partial_text (issue #290): the CLI keeps its one-line compaction progress and+ // stays quiet — the Web banner is where the streamed text shows.+ 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 ed67b237..98d441e9 100644--- a/packages/cli/test/render.test.ts+++ b/packages/cli/test/render.test.ts@@ -499,6 +499,26 @@ 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.+ const { stream, text } = collector();+ const r = new StreamRenderer(stream, t);+ r.handle(compactionBegin({ reason: "context", mode: "summarize", context: 150, turns: 3 }));+ 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(partialText("start"));+ r.handle(partialText("delta", "back to the task"));+ r.handle(partialText("stop"));+ const out = stripAnsi(text());+ expect(out).not.toContain("the plan");+ expect(out).toContain("back to the task");+ });+it("compaction after the turn ends: the completion line shows its own cost, excluded from the turn stats delta; context not updated", () => {const { stream, text } = collector();const r = new StreamRenderer(stream, t);diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.tsindex 4db0809b..385eb100 100644--- a/packages/core/src/agent.ts+++ b/packages/core/src/agent.ts@@ -47,7 +47,7 @@ import {formatSessionId,sessionEnvironment,} from "./internal/session-support.js";-import { userText, withOrigin } from "./omnimessage/index.js";+import { compactionEnd, userText, withOrigin } from "./omnimessage/index.js";import type {McpServerConnectResult,MessageOrigin,@@ -485,6 +485,25 @@ export class Agent {startIndex: located.index,});+ // A compaction the user quit out of (a compaction_begin with no end — the process died+ // mid-request) is simply a **failed** compaction: close the span with a `failed`+ // compaction_end before any new record lands, and discard whatever half-summary it had+ // written — nothing is reconstructed from it (the original context is intact and the+ // standing threshold makes the compaction up at the next trigger). Closing the span is+ // what keeps the rest of the conversation visible: readers treat messages between the+ // paired events as compaction-internal, so an unclosed span would hide everything the+ // user sends afterwards, and tool outputs whose calls it swallowed would render as+ // "unknown tool" cards (issue #288). Best-effort like every Trace write: a failure here+ // must not block the resume itself.+ if (resumed.danglingCompaction) {+ try {+ await trace.write(compactionEnd({ ...resumed.danglingCompaction, status: "failed" }));+ } catch (err) {+ const detail = err instanceof Error ? err.message : String(err);+ process.stderr.write(`[trace] interrupted-compaction closure failed: ${detail}\n`);+ }+ }+return new Session({// Invariants only — meta writes never contain a thinking level.meta: {diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.tsindex 68074e60..82b2ffe7 100644--- a/packages/core/src/engine/context-engine.ts+++ b/packages/core/src/engine/context-engine.ts@@ -723,9 +723,6 @@ export class ContextEngine {// applies mid-Task — when runTurn returns, all of this turn's// tool results are ready and paired with their tool_call.const midTask = turn.toolOutputs.length > 0;- // Outputs this turn still owes the model: dropped when a committed compaction attempt- // consumes them into history (the two-case carry rule below, issue #85).- let turnOutputs = turn.toolOutputs;const compactionReason = this.compactionTrigger();if (compactionReason) {const mode = this.deps.compaction!.mode;@@ -743,25 +740,6 @@ export class ContextEngine {midTask ? turn.toolOutputs : [],signal,);- if (result.status === "aborted") {- // User interrupted compaction: keep the original context. The carry rule is the- // same two-case binary as everywhere (issue #85): a committed attempt consumed- // this turn's outputs into history — only the repair stash summarizeContext left- // in pendingCarryOver still needs resending; otherwise the outputs are untouched- // and are appended behind the stash as case-A carry-over. Abort is the one path- // that discards the steering queue (run's finally — control goes back to the- // user).- if (midTask) {- if (!result.committed) {- this.pendingCarryOver = [- ...this.pendingCarryOver,- ...this.buildCarryOver(attemptInput, turn),- ];- }- yield* this.emitAbort("aborted during compaction");- }- return;- }if (result.status === "completed") {// Boundary check against the **live** queue: steering may have arrived during// the multi-second compaction request and must not be swallowed (no await sits@@ -783,14 +761,33 @@ export class ContextEngine {nextInput = [result.summary!, ...steering];continue;}- // failed: keep the original context and Trace index; the current Task continues and- // retries on the next trigger (no fallback to discard). The carry rule (issue #85):- if (result.committed) {- // A committed attempt consumed this turn's outputs into history — drop them from- // the continuation; only the repair stash remains pending.- turnOutputs = [];+ // failed or aborted: keep the original context and Trace index — the compaction is+ // made up later, at the next trigger or a manual /compact (no fallback to+ // discard). Mid-Task the run ends through the interruption flow: this turn's+ // pending state is held as carry-over under the same two-case binary as everywhere+ // (issue #85) — a committed attempt consumed the turn's outputs into history, so+ // only the repair stash summarizeContext left in pendingCarryOver still needs+ // resending; otherwise the outputs are untouched and are appended behind the stash+ // as case-A carry-over. The next run resends that carry-over merged with the+ // user's message, exactly like any interrupted turn, and the still-standing+ // threshold re-triggers the compaction there. The abort also discards the steering+ // queue (run's finally — control goes back to the user).+ if (midTask) {+ if (!result.committed) {+ this.pendingCarryOver = [+ ...this.pendingCarryOver,+ ...this.buildCarryOver(attemptInput, turn),+ ];+ }+ yield* this.emitAbort(+ result.status === "aborted" ? "aborted during compaction" : "compaction failed",+ );+ return;}- // else: nothing committed — the outputs are untouched and resent below as always.+ // Task boundary: the final reply has already streamed out. A user abort hands+ // control straight back; a failure falls through — queued steering may still+ // continue the loop, and the assembly below otherwise ends the run.+ if (result.status === "aborted") return;}}@@ -802,15 +799,12 @@ export class ContextEngine {// No tool_call this turn and no steering left -> the Task ends (the final reply has// already been streamed out). A compaction stash, if any, rides the next run.if (!midTask && steering.length === 0) return;- // Anything a failed compaction stashed mid-run (synthesized repair outputs from+ // Anything a failed boundary compaction stashed (synthesized repair outputs from// rejected attempts) rides the very next request, ahead of the turn outputs so// tool_results stay contiguous and first.const stashed = this.pendingCarryOver;this.pendingCarryOver = [];- nextInput = [...stashed, ...turnOutputs, ...steering];- // Mid-task, but a committed compaction consumed the outputs and nothing else remains- // to send: the run ends here — the failure was surfaced via compaction_end(failed),- // the context is intact, and the next prompt continues from the committed state.+ nextInput = [...stashed, ...turn.toolOutputs, ...steering];if (nextInput.length === 0) return;}}@@ -1287,11 +1281,12 @@ export class ContextEngine {* compaction runs exactly when the context is largest, where re-billing the whole* transcript uncached costs tens of times more (issue #84 — this is why tools are *not** omitted and no `tool_choice` override is used). The- * compaction request's streamed output is not pushed to the Human output stream (it emits- * paired compaction events, plus every attempt's `token_usage` — positioned between the two- * events, so the frontend stats and the server's usage records count the compaction's true- * spend, rejected attempts included), but it is written- * to the old Trace. Compaction succeeds only with a **valid summary** — non-empty extracted+ * 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* 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@@ -1314,10 +1309,13 @@ export class ContextEngine {yield* this.emitCompactionBegin(reason, "summarize");// Compaction request input: this turn's tool results (mid-Task) or leftover interruption- // carry-over, plus the compaction Prompt. The compaction exchange is written to the old- // Trace (traceable but not pushed to the user); tool results were already written when- // executed and aren't recorded again, while carry-over's not-yet-written synthetic content- // (flatten text, backfilled placeholders) and the compaction Prompt are written now.+ // carry-over, appended to the old object together with the compaction Prompt as one user+ // turn — keeping tool_use/tool_result pairing intact, since an unanswered tool_use would+ // get the compaction request itself rejected (issue #33). The compaction exchange is+ // written to the old Trace (traceable but not pushed to the user); tool results were+ // already written when executed and aren't recorded again, while carry-over's+ // not-yet-written synthetic content (flatten text, backfilled placeholders) and the+ // compaction Prompt are written now.const prompt = userText(settings.prompt);// The resend base: shrinks to the Prompt alone once an attempt commits — the folded turn// input then lives in the old LLM object's history, and resending it would make strict@@ -1326,10 +1324,11 @@ export class ContextEngine {let input = base;await this.write(prompt);- // Whether any attempt was committed by AgentHub (only `completed` commits: timeout and+ // Whether the folded input was absorbed into the old object's history — true once any+ // attempt was committed by AgentHub (only `completed` commits: timeout and// malformed end an incomplete stream, and failed/auth/aborted throw or cut off before a- // clean end — none of those reach the stateful commit). Returned as `committed`: the- // callers' two-case carry rule branches on it.+ // clean end — none of those reach the stateful commit). Returned as+ // `committed`: the callers' two-case carry rule branches on it.let committed = false;// Synthesized outputs answering the latest unusable attempt's tool calls, not yet carried// by a committed request: prepended to the retry input, and stashed as carry-over should@@ -1354,7 +1353,7 @@ export class ContextEngine {);return { status: "aborted", committed };}- const attempt = await this.runCompactionRequest(input, signal, reconnects);+ const attempt = yield* this.runCompactionRequest(input, signal, reconnects);attempts += 1;// Every attempt's token_usage is pushed to the Human output stream (already written to// Trace in runCompactionRequest, so it's only yielded here, never rewritten): the frontend@@ -1487,8 +1486,13 @@ export class ContextEngine {* same frozen config as every other turn (the toolset is deliberately identical: a changed* tool list would change the request prefix and invalidate the provider's prompt cache at* the moment the context is largest, issue #84). Consumes the old LLM object's streamed- * output but **does not push it to the Human output stream** (except `token_usage` —- * captured and handed back via the return value for summarizeContext to yield); complete+ * 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* 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@@ -1496,19 +1500,22 @@ export class ContextEngine {* Token usage is counted into the Session* cumulative totals (recorded via observeTokenUsage, for the new object to carry forward).*/- private async runCompactionRequest(+ private async *runCompactionRequest(input: OmniMessage[],signal?: AbortSignal,/** Transport retries already performed by the compaction loop (its request_end announces the next planned backoff too). */reconnectsSoFar = 0,- ): Promise<{- status: StopReason;- text: string;- toolCalls: OmniMessage<ToolCallPayload>[];- usage: OmniMessage | null;- /** Error detail (LLMOutcome.errorMessage) on non-completed statuses — becomes compaction_end.error_message when this failure ends the compaction. */- errorMessage?: string;- }> {+ ): AsyncGenerator<+ OmniMessage,+ {+ status: StopReason;+ text: string;+ toolCalls: OmniMessage<ToolCallPayload>[];+ usage: OmniMessage | null;+ /** Error detail (LLMOutcome.errorMessage) on non-completed statuses — becomes compaction_end.error_message when this failure ends the compaction. */+ errorMessage?: string;+ }+ > {// The compaction request is itself an ordinary Request, emitting paired request events —// written to the (old) Trace only, not pushed to the stream, keeping the compaction process// invisible to Human.@@ -1520,6 +1527,11 @@ 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.+ let sawPartialText = false;for (;;) {const res = await gen.next();if (res.done) {@@ -1560,9 +1572,28 @@ export class ContextEngine {const msg = res.value;await this.write(msg);if (this.observeTokenUsage(msg)) usage = 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.+ {+ const p = msg.payload as { type?: string; text?: string };+ if (p.type === "partial_text") {+ if (typeof p.text === "string" && p.text !== "") sawPartialText = true;+ yield msg;+ }+ }if (isCompleteModelMessage(msg)) {if (msg.payload.type === "text") {- text += (msg.payload as TextPayload).text;+ const body = (msg.payload as TextPayload).text;+ text += body;+ if (!sawPartialText && 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/src/omnimessage/types.ts b/packages/core/src/omnimessage/types.tsindex c734813d..3ae0f010 100644--- a/packages/core/src/omnimessage/types.ts+++ b/packages/core/src/omnimessage/types.ts@@ -331,8 +331,10 @@ export type CompactionReason = "context" | "turns" | "manual";export type CompactionMode = "summarize" | "discard";/**- * Compaction boundary event: the compaction process exposes- * only this event pair to Human, produced **in pairs** by `context_engine`. Both `reason` and+ * Compaction boundary event, produced **in pairs** by `context_engine`. Between the pair+ * the stream carries only each attempt's `token_usage` and the summary being written as+ * ordinary `partial_text` fragments (or the complete text when nothing streamed) — the+ * compaction request's other raw messages stay Trace-only. Both `reason` and* `mode` are carried on both events, for stateless frontend rendering; `status` reuses the* six-value `StopReason` protocol (compaction converges to a terminal state, taking* `completed` / `failed` / `aborted` in practice — `timeout` / `malformed` are handled internallydiff --git a/packages/core/src/trace/resume.ts b/packages/core/src/trace/resume.tsindex 971943db..7cf4fd2e 100644--- a/packages/core/src/trace/resume.ts+++ b/packages/core/src/trace/resume.ts@@ -36,7 +36,10 @@ import {userText,} from "../omnimessage/index.js";import type {+ CompactionBeginPayload,CompactionEndPayload,+ CompactionMode,+ CompactionReason,CompleteModelMessage,OmniMessage,RequestBeginPayload,@@ -72,6 +75,17 @@ export interface ResumeResult {renderMessages: OmniMessage[];/** The file's first session_meta; null if missing (unresumable — the caller reports the error). */meta: SessionMetaMessage | null;+ /**+ * A `compaction_begin` in this file has no matching `compaction_end`: the user quit (or the+ * process died) while the compaction ran. That compaction simply **failed** — the resume+ * path closes the span with a `failed` `compaction_end` before any new record lands, and+ * its half-written summary is discarded rather than reconstructed (best-effort: the+ * original context is still intact, 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, so an+ * unclosed span would hide everything appended after it (issue #288).+ */+ danglingCompaction?: { reason: CompactionReason; mode: CompactionMode };}/** Content of the pairing-backfill placeholder output (the tool hadn't finished and no output was persisted before the process exited). */@@ -305,6 +319,8 @@ export function resumeTrace(messages: OmniMessage[]): ResumeResult {/** Whether we're between a matched pair of compaction events: the compaction prompt in this* span is not conversational input and must not be resent as-is if uncommitted. */let inCompaction = false;+ /** The last compaction_begin still waiting for its end (null once matched): a non-null value at the end of the file is a compaction the user quit out of, closed as failed by the resume path (see ResumeResult.danglingCompaction). */+ let danglingBegin: OmniMessage<CompactionBeginPayload> | null = null;/** Ids of tool_calls that are committed (in history) and ids of outputs that are paired (in* history input). */const committedCallIds = new Set<string>();@@ -407,9 +423,13 @@ export function resumeTrace(messages: OmniMessage[]): ResumeResult {}if (isEventMessage(msg)) {const t = (msg.payload as { type?: string }).type;- if (t === "compaction_begin") inCompaction = true;- else if (t === "compaction_end") inCompaction = false;- else if (t === "abort" && (msg.origin?.length ?? 0) === 0) renderMessages.push(msg);+ if (t === "compaction_begin") {+ inCompaction = true;+ danglingBegin = msg as OmniMessage<CompactionBeginPayload>;+ } else if (t === "compaction_end") {+ inCompaction = false;+ danglingBegin = null;+ } else if (t === "abort" && (msg.origin?.length ?? 0) === 0) renderMessages.push(msg);// Other events (token_usage / approval_decision / tool_list_ready / mcp_connect_*,// etc.) don't participate in turn determination and stay out of the render view —// the bootstrap records are re-emitted live by the next run when they matter.@@ -455,6 +475,14 @@ export function resumeTrace(messages: OmniMessage[]): ResumeResult {sessionTurns,renderMessages,meta,+ ...(danglingBegin !== null+ ? {+ danglingCompaction: {+ reason: danglingBegin.payload.reason,+ mode: danglingBegin.payload.mode,+ },+ }+ : {}),};}diff --git a/packages/core/test/compaction.test.ts b/packages/core/test/compaction.test.tsindex e8ea211e..c79f41c2 100644--- a/packages/core/test/compaction.test.ts+++ b/packages/core/test/compaction.test.ts@@ -27,6 +27,11 @@ import { dirname, join } from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";import {assistantText,+ compactionBegin,+ compactionEnd,+ partialText,+ requestBegin,+ requestEnd,sessionMeta,thinkingMessage,tokenUsage,@@ -53,7 +58,7 @@ import { ContextEngine, SUMMARY_RETRY_GUIDANCE } from "../src/engine/context-engimport type { CompactionSettings } from "../src/engine/context-engine.js";import { GenerativeModel } from "../src/llm/index.js";import type { UniConfig, UniEvent, UniMessage } from "@prismshadow/agenthub";-import { Writer, readTrace } from "../src/trace/index.js";+import { Writer, readTrace, resumeTrace } from "../src/trace/index.js";// ---------------------------------------------------------------------------// Test fixtures@@ -208,11 +213,13 @@ describe("context compaction", () => {turns: 1,});expect(events[1]).toMatchObject({ type: "compaction_end", status: "completed" });- // The compaction process is invisible to the human: the compaction prompt and summary text are never pushed to the output stream.+ // The compaction request's own input is invisible to the human: the compaction prompt is+ // never pushed to the output stream.const texts = out1.filter((m) => (m.payload as { type?: string }).type === "text").map(textOf);expect(texts.some((t) => t.includes("COMPACT NOW"))).toBe(false);- expect(texts.some((t) => t.includes("distilled"))).toBe(false);- // Exception: the compaction request's token_usage IS pushed to the output stream, sitting between the paired compaction events (the frontend counts it in stats).+ // Two exceptions ride the stream between the paired compaction events: the compaction+ // request's token_usage (the frontend counts it in stats), and the summary being written+ // (issue #290 — this LLM yields only complete messages, so the complete text streams).const types1 = payloadTypes(out1);const between = out1.slice(types1.indexOf("compaction_begin") + 1,@@ -223,6 +230,10 @@ describe("context compaction", () => {);expect(usageBetween).toHaveLength(1);expect((usageBetween[0]!.payload as TokenUsagePayload).request.total).toBe(160);+ const textBetween = between+ .filter((m) => (m.payload as { type?: string }).type === "text")+ .map(textOf);+ expect(textBetween).toEqual(["[summary]the distilled summary[/summary]"]);// The new LLM instance carries over the session's cumulative tokens (including compaction request usage).expect(factoryTokens).toMatchObject({ total: 310 });@@ -308,9 +319,12 @@ describe("context compaction", () => {},// Compaction request fails on the one status no ladder can fix (a rejected credential).{ messages: [], outcome: { status: "auth", errorMessage: "auth error" } },- // Original context is kept: the task continues, tool outputs feed back into the old instance as usual (context usage keeps growing).+ // Original context is kept. The mid-task failure ends the run by the interruption+ // flow, so the next run resends this round's tool output with the user's message and+ // the task finishes on the old instance (context usage keeps growing).{ messages: [assistantText("finished on old context"), usage(190, 340)] },- // Second trigger (context still over the limit) -> retries compaction at the boundary, this time succeeding.+ // Second trigger (context still over the limit) -> compaction is made up at that+ // run's task boundary, this time succeeding.{ messages: [assistantText("[summary]second try[/summary]")] },],"llm1",@@ -332,22 +346,28 @@ describe("context compaction", () => {const oldPath = trace.currentPath();const out = await collect(engine.run([userText("go")], { approve: allowAll }));+ // The mid-task failure ends this run: stop=failed, original context kept, no LLM swap.+ expect(+ compactionEvents(out).map(+ (e) => `${e.type}:${(e as Partial<CompactionEndPayload>).status ?? ""}`,+ ),+ ).toEqual(["compaction_begin:", "compaction_end:failed"]);+ expect(payloadTypes(out)).toContain("abort");+ expect(created).toBe(0);- // Two event pairs: the first has stop=failed (abandoned, original context kept), the second succeeds.- const events = compactionEvents(out);+ // The next run resends the held tool output with the new message, and the compaction is+ // made up at that run's boundary — the second pair completes.+ const out2 = await collect(engine.run([userText("continue")], { approve: allowAll }));expect(- events.map((e) => `${e.type}:${(e as Partial<CompactionEndPayload>).status ?? ""}`),- ).toEqual([- "compaction_begin:",- "compaction_end:failed",- "compaction_begin:",- "compaction_end:completed",- ]);- // No LLM swap and no trace file split at the moment of failure; rotation happens only after success.+ compactionEvents(out2).map(+ (e) => `${e.type}:${(e as Partial<CompactionEndPayload>).status ?? ""}`,+ ),+ ).toEqual(["compaction_begin:", "compaction_end:completed"]);+ // The LLM swap happens only after success.expect(created).toBe(1);expect(llm1.calls).toHaveLength(4);- // After the failure, the input fed back into the old instance is this round's tool output.- expect(payloadTypes(llm1.calls[2]!)).toEqual(["tool_call_output"]);+ // The resent input leads with this round's tool output (pairing intact), then the message.+ expect(payloadTypes(llm1.calls[2]!)).toEqual(["tool_call_output", "text"]);const oldTrace = await readTrace(oldPath);// Still written to the same file after a failed stop (the failed compaction attempt stays auditable); the old file is closed off only after success.expect(payloadTypes(oldTrace).filter((t) => t?.startsWith("compaction_"))).toHaveLength(4);@@ -921,14 +941,15 @@ describe("context compaction", () => {expect(closureRepairs).toEqual([]);});- it("mid-task: a committed rejection absorbs the turn's tool outputs — retries never resend them, and an empty-handed abandonment ends the run", async () => {+ it("mid-task: a committed rejection absorbs the turn's tool outputs — retries never resend them, and an empty-handed abandonment ends the run by the interruption flow", async () => {// Issue #85, strict-provider scenario: the first committed attempt puts the turn's tool// outputs (folded into the compaction input) into the old LLM object's history. From then// on the retries must carry only the repairs and the Prompt — resending the outputs would- // be rejected as stale tool_results — and after the compaction is abandoned the- // continuation must not resend them either. Here the final rejection is empty (no repairs- // left to deliver) and no steering is queued, so the run ends at the failure: the context- // is intact and the next prompt continues from the committed state.+ // be rejected as stale tool_results — and after the compaction is abandoned the next run+ // must not resend them either. Here the final rejection is empty (no repairs left to+ // stash), so the run ends at the abort with nothing pending: the context is intact and+ // the next prompt continues from the committed state, where the still-standing threshold+ // makes the compaction up at its next trigger.const llm1 = new ScriptedLLM([// Turn 1: a tool call, over the threshold -> mid-task compaction.@@ -947,8 +968,8 @@ describe("context compaction", () => {{ messages: [thinkingMessage("blank 3")] },{ messages: [thinkingMessage("blank 4")] },{ messages: [thinkingMessage("blank 5")] },- // Next run after the abandonment: served by the same instance, plain prompt.- { messages: [assistantText("continuing"), usage(60, 900)] },+ // Next run: served by the same instance, plain prompt.+ { messages: [assistantText("next task"), usage(70, 970)] },],"llm1",);@@ -972,9 +993,10 @@ describe("context compaction", () => {const out1 = await collect(engine.run([userText("task one")], { approve: allowAll }));expect(compactionEvents(out1)[1]).toMatchObject({ type: "compaction_end", status: "failed" });- // The run ends at the empty-handed abandonment without an abort: the compaction failure- // is the whole story.- expect(payloadTypes(out1)).not.toContain("abort");+ // The abandonment ends the run through the interruption flow: an abort follows the+ // failed compaction_end, and no further request is issued in this run.+ const abort = out1.find((m) => (m.payload as { type?: string }).type === "abort");+ expect(abort?.payload).toMatchObject({ reason: "compaction failed" });expect(llm1.calls).toHaveLength(6);// Attempt 1 folds the turn's tool output in; attempt 2 carries the repair + note + Prompt// but NOT the absorbed output; attempts 3-5 are note + Prompt.@@ -997,11 +1019,11 @@ describe("context compaction", () => {expect(llm1.calls[6]!.map(textOf)).toEqual(["task two"]);});- it("mid-task: abandonment with a trailing tool-calling rejection continues the task with the repair alone", async () => {+ it("mid-task: abandonment with a trailing tool-calling rejection stashes the repair for the next run", async () => {// Any committed attempt absorbs — here the FIRST (empty) rejection commits the turn- // outputs, and the FINAL rejection leaves unanswered tool calls. The continuation after- // the failure delivers exactly the stashed repairs (never the absorbed outputs), keeping- // the live object's history well-formed while the task keeps running.+ // outputs, and the FINAL rejection leaves unanswered tool calls. The run ends through+ // the interruption flow with the repair stashed as carry-over (never the absorbed+ // outputs): the next run leads with it, keeping the live object's history well-formed.const llm1 = new ScriptedLLM([{@@ -1014,7 +1036,7 @@ describe("context compaction", () => {{ messages: [thinkingMessage("blank 4")] },// Attempt 5: rejected with a tool call -> its repair is stashed at the abandonment.{ messages: [toolCall({ name: "t", arguments: "{}", toolCallId: "c5" })] },- // Continuation: the repair alone; the model wraps the task up (under the threshold).+ // Next run: the stashed repair leads, then the new prompt.{ messages: [assistantText("recovered"), usage(60, 900)] },],"llm1",@@ -1030,30 +1052,30 @@ describe("context compaction", () => {const out = await collect(engine.run([userText("go")], { approve: allowAll }));expect(compactionEvents(out)[1]).toMatchObject({ type: "compaction_end", status: "failed" });- expect(llm1.calls).toHaveLength(7);+ expect(payloadTypes(out)).toContain("abort");+ expect(llm1.calls).toHaveLength(6);// Attempt 1 folds the outputs; attempts 2-5 are note + Prompt (absorbed by the first commit).expect(payloadTypes(llm1.calls[1]!)).toEqual(["tool_call_output", "text"]);for (let attempt = 2; attempt <= 5; attempt += 1) {expect(llm1.calls[attempt]!.map(textOf)).toEqual([SUMMARY_RETRY_GUIDANCE, "COMPACT NOW"]);}- // The continuation input is the repair answering c5 — nothing else: no absorbed outputs,- // no prompt.- expect(payloadTypes(llm1.calls[6]!)).toEqual(["tool_call_output"]);+ // The next run leads with the repair answering c5 — no absorbed outputs — followed by+ // the new prompt.+ await collect(engine.run([userText("again")], { approve: allowAll }));+ expect(payloadTypes(llm1.calls[6]!)).toEqual(["tool_call_output", "text"]);const cont = llm1.calls[6]![0]!.payload as { tool_call_id: string; output: string };expect(cont.tool_call_id).toBe("c5");expect(cont.output).toBe("[tool error] the compaction request expects a summary, not tool calls",);- // The task finished on the continuation; the stash is spent for later runs.- expect(out.map((m) => (m.payload as { text?: string }).text)).toContain("recovered");- await collect(engine.run([userText("again")], { approve: allowAll }));- expect(llm1.calls[7]!.map(textOf)).toEqual(["again"]);+ expect(textOf(llm1.calls[6]![1]!)).toBe("again");});- it("mid-task: an all-transport abandonment absorbs nothing — the outputs are resent as before", async () => {+ it("mid-task: an all-transport abandonment absorbs nothing — the outputs carry to the next run", async () => {// Counter-case: timeout/malformed attempts never commit, so the turn's tool outputs were- // never absorbed and the post-failure continuation must resend them exactly as before- // (their tool_use pairing is still unanswered on the live object).+ // never absorbed. The run ends through the interruption flow with the outputs held as+ // case-A carry-over (their tool_use pairing is still unanswered on the live object), and+ // the next run resends them exactly as before, ahead of the new prompt.const llm1 = new ScriptedLLM([{@@ -1061,7 +1083,7 @@ describe("context compaction", () => {},{ messages: [], outcome: { status: "timeout" } },{ messages: [], outcome: { status: "timeout" } },- // Continuation: the resent tool output; the model wraps up under the threshold.+ // Next run: the carried outputs lead, then the new prompt (under the threshold).{ messages: [assistantText("done on old context"), usage(60, 400)] },],"llm1",@@ -1077,9 +1099,13 @@ describe("context compaction", () => {const out = await collect(engine.run([userText("go")], { approve: allowAll }));expect(compactionEvents(out)[1]).toMatchObject({ type: "compaction_end", status: "failed" });- expect(llm1.calls).toHaveLength(4);- expect(payloadTypes(llm1.calls[3]!)).toEqual(["tool_call_output"]);+ expect(payloadTypes(out)).toContain("abort");+ expect(llm1.calls).toHaveLength(3);++ await collect(engine.run([userText("carry on")], { approve: allowAll }));+ expect(payloadTypes(llm1.calls[3]!)).toEqual(["tool_call_output", "text"]);expect((llm1.calls[3]![0]!.payload as { tool_call_id?: string }).tool_call_id).toBe("ct");+ expect(textOf(llm1.calls[3]![1]!)).toBe("carry on");});it("mid-task: an abort after a committed rejection merges the stash — repairs ride, absorbed outputs do not", async () => {@@ -1600,3 +1626,379 @@ describe("context compaction", () => {expect(payloadTypes(out)).toContain("abort");});});++describe("compaction summary streaming (issue #290)", () => {+ let traces: string;++ beforeEach(async () => {+ traces = await mkdtemp(join(tmpdir(), "penguin-compaction-s-"));+ });++ afterEach(async () => {+ await rm(traces, { recursive: true, force: true });+ });++ /** The text messages the compaction span pushed to the stream, in order. */+ const streamedTexts = (msgs: OmniMessage[]): string[] =>+ msgs+ .filter((m) => {+ const t = (m.payload as { type?: string }).type;+ return t === "partial_text" || t === "text";+ })+ .map((m) => (m.payload as { text?: string }).text ?? "");++ it("streams the summary's own partial_text between the paired events; the complete text stays off the stream", async () => {+ const llm1 = new ScriptedLLM(+ [+ { messages: [assistantText("answer one"), usage(150, 150)] },+ {+ messages: [+ partialText("start"),+ partialText("delta", "[summary]the "),+ partialText("delta", "plan[/summary]"),+ partialText("stop"),+ assistantText("[summary]the plan[/summary]"),+ usage(160, 310),+ ],+ },+ ],+ "llm1",+ );+ const trace = new Writer({ tracesDir: traces, sessionId: "sess_stream" });+ const engine = new ContextEngine({+ llm: llm1,+ environment: fakeEnvironment,+ trace,+ sessionMeta: metaMessage,+ compaction: settings(),+ createLLM: () => new ScriptedLLM([], "llm2"),+ });+ const oldPath = trace.currentPath();++ const out = await collect(engine.run([userText("task one")], { approve: allowAll }));++ // The span's fragments ride the stream verbatim — every phase, and the complete text+ // that follows them does NOT re-emit (each character reaches consumers once). The+ // task's own first-turn reply ("answer one") streams no partials in this fixture, so+ // its complete text is the only other entry.+ const types = payloadTypes(out);+ const begin = types.indexOf("compaction_begin");+ const end = types.indexOf("compaction_end");+ const spanTypes = types.slice(begin + 1, end);+ expect(spanTypes.filter((t) => t === "partial_text")).toHaveLength(4);+ expect(spanTypes).not.toContain("text");+ expect(streamedTexts(out.slice(begin + 1, end))).toEqual([+ "",+ "[summary]the ",+ "plan[/summary]",+ "",+ ]);+ // The compaction dialogue is recorded in the old Trace as before — the complete text+ // included (that is what history rebuild reads back), and partials never persist.+ const recorded = await readTrace(oldPath);+ const recordedTexts = recorded+ .filter((m) => (m.payload as { type?: string }).type === "text")+ .map((m) => (m.payload as { text?: string }).text);+ expect(recordedTexts).toContain("[summary]the plan[/summary]");+ expect(payloadTypes(recorded)).not.toContain("partial_text");+ });++ it("an LLM that yields only complete text streams that text instead", async () => {+ const llm1 = new ScriptedLLM(+ [+ { messages: [assistantText("answer one"), usage(150, 150)] },+ { messages: [assistantText("[summary]whole[/summary]"), usage(160, 310)] },+ ],+ "llm1",+ );+ const engine = new ContextEngine({+ llm: llm1,+ environment: fakeEnvironment,+ sessionMeta: metaMessage,+ compaction: settings(),+ createLLM: () => 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(streamedTexts(out.slice(begin + 1, end))).toEqual(["[summary]whole[/summary]"]);+ });+});++describe("a compaction the user quit out of (issue #288)", () => {+ it("resumeTrace reports the unmatched compaction_begin, and discards the interrupted draft", () => {+ // The interrupted compaction's half-written summary is never adopted: the replay+ // reconstructs no [context_summary] and the original context stands (best-effort).+ const interrupted = resumeTrace([+ metaMessage,+ userText("q1"),+ requestBegin(),+ assistantText("a1"),+ usage(150, 150),+ requestEnd("completed"),+ compactionBegin({ reason: "context", mode: "summarize", context: 150, turns: 1 }),+ userText("COMPACT NOW"),+ requestBegin(),+ assistantText("[summary]half-writ"),+ ]);+ expect(interrupted.danglingCompaction).toEqual({ reason: "context", mode: "summarize" });+ expect(interrupted.contextClosed).toBe(false);+ expect(interrupted.pendingSummary).toBeUndefined();+ // The compaction Prompt is not conversational input and is not resent as carry-over.+ expect(interrupted.carryOver.map((m) => (m.payload as TextPayload).text)).not.toContain(+ "COMPACT NOW",+ );+ // The context before the compaction is intact: the committed turn is still history.+ expect(interrupted.history.map((m) => (m.payload as TextPayload).text)).toEqual(["q1", "a1"]);+ });++ it("resumeTrace reports an unmatched compaction_begin for the resume path to close", () => {+ const dangling = resumeTrace([+ metaMessage,+ userText("q1"),+ requestBegin(),+ assistantText("a1"),+ usage(150, 150),+ requestEnd("completed"),+ compactionBegin({ reason: "context", mode: "summarize", context: 150, turns: 1 }),+ userText("COMPACT NOW"),+ requestBegin(),+ ]);+ expect(dangling.danglingCompaction).toEqual({ reason: "context", mode: "summarize" });++ // A matched pair reports nothing — no heal write on healthy traces.+ const closed = resumeTrace([+ metaMessage,+ userText("q1"),+ requestBegin(),+ assistantText("a1"),+ usage(150, 150),+ requestEnd("completed"),+ compactionBegin({ reason: "context", mode: "summarize", context: 150, turns: 1 }),+ userText("COMPACT NOW"),+ requestBegin(),+ requestEnd("aborted"),+ compactionEnd({ reason: "context", mode: "summarize", status: "aborted" }),+ ]);+ expect(closed.danglingCompaction).toBeUndefined();+ });+});++describe("mid-task compaction runs the tools first (issue #288)", () => {+ /** Environment whose tools resolve only when released, recording dispatch order. */+ function gatedEnvironment(): {+ env: EnvironmentInterface;+ dispatched: string[];+ release: () => void;+ } {+ const dispatched: string[] = [];+ let unblock: () => void = () => {};+ const gate = new Promise<void>((resolve) => {+ unblock = resolve;+ });+ return {+ dispatched,+ release: () => unblock(),+ env: {+ async listTools() {+ return [];+ },+ async *executeTool({ toolCall: tc }) {+ dispatched.push(tc.payload.tool_call_id);+ await gate;+ yield toolCallOutput({ output: "tool ran", toolCallId: tc.payload.tool_call_id });+ },+ toolPermission() {+ return "rw";+ },+ },+ };+ }++ it("every tool of the turn completes before the compaction request goes out, and all results ride it", async () => {+ const llm1 = new ScriptedLLM(+ [+ // One turn, three parallel tool calls, then usage over the threshold.+ {+ messages: [+ toolCall({ name: "t", arguments: "{}", toolCallId: "c1" }),+ toolCall({ name: "t", arguments: "{}", toolCallId: "c2" }),+ toolCall({ name: "t", arguments: "{}", toolCallId: "c3" }),+ usage(150, 150),+ ],+ },+ { messages: [assistantText("[summary]continue: step 2[/summary]"), usage(160, 320)] },+ ],+ "llm1",+ );+ const llm2 = new ScriptedLLM([{ messages: [assistantText("done"), usage(30, 360)] }], "llm2");+ const engine = new ContextEngine({+ llm: llm1,+ environment: fakeEnvironment,+ sessionMeta: metaMessage,+ compaction: settings(),+ createLLM: () => llm2,+ });++ const out = await collect(engine.run([userText("go")], { approve: allowAll }));++ // The compaction request carries all three results, in the original call order, ahead+ // of the compaction Prompt — the tools ran to completion first.+ expect(llm1.calls).toHaveLength(2);+ const compactionInput = llm1.calls[1]!;+ expect(payloadTypes(compactionInput)).toEqual([+ "tool_call_output",+ "tool_call_output",+ "tool_call_output",+ "text",+ ]);+ expect(+ compactionInput.slice(0, 3).map((m) => (m.payload as { tool_call_id?: string }).tool_call_id),+ ).toEqual(["c1", "c2", "c3"]);+ expect(textOf(compactionInput[3]!)).toBe("COMPACT NOW");+ // No synthetic assistant text was invented anywhere in the exchange.+ expect(compactionInput.map((m) => (m.payload as { role?: string }).role)).toEqual([+ "user",+ "user",+ "user",+ "user",+ ]);+ // The loop resumes the task on the new context.+ expect(llm2.calls[0]!.map(textOf)).toEqual([+ "[context_summary]\ncontinue: step 2\n[/context_summary]",+ ]);+ expect(out.map((m) => (m.payload as { text?: string }).text)).toContain("done");+ });++ it("a slow tool simply delays the compaction: nothing starts (or times out) until its result is in", async () => {+ const { env, dispatched, release } = gatedEnvironment();+ const llm1 = new ScriptedLLM(+ [+ {+ messages: [toolCall({ name: "t", arguments: "{}", toolCallId: "slow" }), usage(150, 150)],+ },+ { messages: [assistantText("[summary]s[/summary]"), usage(160, 320)] },+ ],+ "llm1",+ );+ const engine = new ContextEngine({+ llm: llm1,+ environment: env,+ sessionMeta: metaMessage,+ compaction: settings(),+ createLLM: () => new ScriptedLLM([{ messages: [assistantText("done"), usage(1, 1)] }], "l2"),+ });++ const gen = engine.run([userText("go")], { approve: allowAll });+ const seen: OmniMessage[] = [];+ // Drive until the tool has been dispatched but not yet answered.+ for (;;) {+ const next = gen.next();+ const settled = await Promise.race([+ next.then((r) => ({ r })),+ new Promise<null>((resolve) => setTimeout(() => resolve(null), 30)),+ ]);+ if (settled === null) break; // the loop is parked on the pending tool+ if (settled.r.done) break;+ seen.push(settled.r.value);+ }+ expect(dispatched).toEqual(["slow"]);+ // The compaction has NOT started while the tool is outstanding: no compaction event,+ // and the compaction request was never issued (the LLM saw only the first turn).+ expect(payloadTypes(seen)).not.toContain("compaction_begin");+ expect(llm1.calls).toHaveLength(1);++ release();+ for await (const msg of gen) seen.push(msg);+ // Once the result lands, the compaction runs and carries it.+ expect(compactionEvents(seen).map((e) => e.type)).toEqual([+ "compaction_begin",+ "compaction_end",+ ]);+ expect(payloadTypes(llm1.calls[1]!)).toEqual(["tool_call_output", "text"]);+ });++ it("a failing tool's error output is what rides the compaction request", async () => {+ const failingEnv: EnvironmentInterface = {+ async listTools() {+ return [];+ },+ async *executeTool({ toolCall: tc }) {+ yield toolCallOutput({+ output: "[tool error] boom",+ toolCallId: tc.payload.tool_call_id,+ stopReason: "failed",+ });+ },+ toolPermission() {+ return "rw";+ },+ };+ const llm1 = new ScriptedLLM(+ [+ { messages: [toolCall({ name: "t", arguments: "{}", toolCallId: "c1" }), usage(150, 150)] },+ { messages: [assistantText("[summary]after the failure[/summary]"), usage(160, 320)] },+ ],+ "llm1",+ );+ const engine = new ContextEngine({+ llm: llm1,+ environment: failingEnv,+ sessionMeta: metaMessage,+ compaction: settings(),+ createLLM: () => new ScriptedLLM([{ messages: [assistantText("ok"), usage(1, 1)] }], "l2"),+ });++ await collect(engine.run([userText("go")], { approve: allowAll }));+ const compactionInput = llm1.calls[1]!;+ expect(payloadTypes(compactionInput)).toEqual(["tool_call_output", "text"]);+ const out = compactionInput[0]!.payload as { output: string; stop_reason?: string };+ expect(out.output).toBe("[tool error] boom");+ expect(out.stop_reason).toBe("failed");+ });++ it("a denied tool still pairs: the denial output rides the compaction request", async () => {+ const llm1 = new ScriptedLLM(+ [+ { messages: [toolCall({ name: "t", arguments: "{}", toolCallId: "c1" }), usage(150, 150)] },+ { messages: [assistantText("[summary]after the denial[/summary]"), usage(160, 320)] },+ ],+ "llm1",+ );+ const engine = new ContextEngine({+ llm: llm1,+ environment: fakeEnvironment,+ sessionMeta: metaMessage,+ compaction: settings(),+ createLLM: () => new ScriptedLLM([{ messages: [assistantText("ok"), usage(1, 1)] }], "l2"),+ });++ await collect(engine.run([userText("go")], { approve: async () => "deny" }));+ expect(payloadTypes(llm1.calls[1]!)).toEqual(["tool_call_output", "text"]);+ expect((llm1.calls[1]![0]!.payload as { output: string }).output).toBe(+ "Tool call denied by user.",+ );+ });++ it("manual /compact keeps its own semantics: no turn is pending, so only the Prompt goes out", async () => {+ const llm1 = new ScriptedLLM(+ [+ { messages: [assistantText("first answer"), usage(50, 50)] },+ { messages: [assistantText("[summary]manual[/summary]"), usage(60, 110)] },+ ],+ "llm1",+ );+ const engine = new ContextEngine({+ llm: llm1,+ environment: fakeEnvironment,+ sessionMeta: metaMessage,+ compaction: settings({ maxContextLength: 100000 }),+ createLLM: () => new ScriptedLLM([], "llm2"),+ });+ await collect(engine.run([userText("hi")], { approve: allowAll }));+ await collect(engine.compact());+ expect(llm1.calls[1]!.map(textOf)).toEqual(["COMPACT NOW"]);+ });+});diff --git a/packages/core/test/resume.test.ts b/packages/core/test/resume.test.tsindex 40adbafd..ec3c4c08 100644--- a/packages/core/test/resume.test.ts+++ b/packages/core/test/resume.test.ts@@ -16,6 +16,7 @@ import { createAgent } from "../src/index.js";import {abortEvent,assistantText,+ compactionBegin,requestBegin,requestEnd,sessionMeta,@@ -174,6 +175,49 @@ describe("agent.resumeSession", () => {).toEqual(["text", "text", "abort"]);});+ it("closes a compaction the user quit out of as failed, discarding its draft (issue #288)", async () => {+ // The process died while a compaction ran: the shard ends inside the span (begin ++ // prompt + an unfinished request that had started writing a summary). That compaction+ // simply failed — resume closes the span before appending anything else, so the+ // conversation that follows is not hidden as compaction-internal, and the half-written+ // draft is discarded rather than adopted as a summary.+ const agent = await createAgent({});+ const file = await writeTraceFile(tmpRoot, SID, [+ metaFor(SID, workspace),+ userText("q1"),+ requestBegin(),+ assistantText("a1"),+ tokenUsage(usage(150), usage(150)),+ requestEnd("completed"),+ compactionBegin({ reason: "context", mode: "summarize", context: 150, turns: 1 }),+ userText("COMPACT NOW"),+ requestBegin(),+ assistantText("[summary]half-writ"),+ ]);++ const session = await agent.resumeSession({ sessionId: SID });+ const closed = await readTrace(file);+ const last = closed[closed.length - 1]!;+ expect(last.payload).toMatchObject({+ type: "compaction_end",+ reason: "context",+ mode: "summarize",+ status: "failed",+ });+ // Nothing was reconstructed from the interrupted compaction: the original context is+ // resumed as it stood before it, with no `[context_summary]` injected.+ const injected = (session.resumedHistory ?? []).some((m) =>+ ((m.payload as { text?: string }).text ?? "").includes("[context_summary]"),+ );+ expect(injected).toBe(false);+ session.dispose();++ // Idempotent: a second resume sees the matched pair and appends nothing.+ const again = await agent.resumeSession({ sessionId: SID });+ again.dispose();+ expect((await readTrace(file)).length).toBe(closed.length);+ });+it("ignores a legacy trace's recorded thinking_level; the Agent config always wins", async () => {// session_meta no longer carries a thinking level (it became a per-turn run parameter);// a `thinking_level` still present in an OLD trace's meta JSON is deliberately ignored —diff --git a/packages/docs/content/agent-loop.en.md b/packages/docs/content/agent-loop.en.mdindex 2b19af38..b40aa0f4 100644--- a/packages/docs/content/agent-loop.en.md+++ b/packages/docs/content/agent-loop.en.md@@ -128,7 +128,15 @@ Three triggers (`compaction_begin.reason`):Two modes: `summarize` (default) appends the compaction Prompt to the old context, extracts the `[summary]`, wraps it as a `[context_summary]` user text and continues in a **fresh model context**; `discard` simply drops the old context. System markers are written as `[tag]…[/tag]`; the earlier angle-bracket form (`<summary>`, `<context_summary>`, …) is still recognized when reading old Traces and old persisted compaction prompts. Summary extraction applies a tolerance ladder: the first non-empty `[summary]` tag pair wins; when every pair is empty, the text left after stripping the tags is used instead (rescuing models that write the body after the closing tag); with no tags at all, the whole output is used verbatim. Compaction rotates the [Trace file](/sessions-and-traces) (`_002`, `_003`, …) — one Trace file always equals one complete model context. `compactability()` probes feasibility before `session.compact()` (`ok | unsupported | empty | just_compacted`).-The compaction request keeps the session's toolset **unchanged** — the request prefix (tool list included) stays byte-identical to ordinary turns, so the provider's prompt cache remains valid at the moment the context is largest. Compaction still succeeds only with a valid summary: a response that calls a tool or whose extracted summary is empty counts as one more failed attempt — any tool calls are answered with synthesized failed outputs (keeping `tool_use`/`tool_result` pairing intact), and the resent request carries a corrective note ahead of the compaction Prompt (committed history can only be appended to; rewriting it would invalidate the prompt cache). Every failure — unusable summaries and the `failed`/`timeout`/`malformed` transport statuses alike — draws on the one reconnect budget and backoff ladder described under "Automatic reconnect" above; only `auth` stops the compaction at once. Once the budget is exhausted the compaction ends `failed`, keeping the original context and Trace file until the next trigger; `compaction_end` reuses the unified retry detail block — `attempt` (the final attempt's ordinal, failed attempts included) and, on failure, the last `error_message` detail (shown on the chat banner and the CLI line) — and a failed compaction also lands in the cost center as a `compaction_failed` error record. The first **committed** attempt — adopted or rejected — also absorbs whatever turn input was folded into the compaction request (mid-task tool results, or the carry-over a manual `/compact` folds in) into the old context's history: retries resend only the repairs and the Prompt, and the continuation after an abandoned compaction never resends the absorbed input.+The compaction request keeps the session's toolset **unchanged** — the request prefix (tool list included) stays byte-identical to ordinary turns, so the provider's prompt cache remains valid at the moment the context is largest. Compaction still succeeds only with a valid summary: a response that calls a tool or whose extracted summary is empty counts as one more failed attempt — any tool calls are answered with synthesized failed outputs (keeping `tool_use`/`tool_result` pairing intact), and the resent request carries a corrective note ahead of the compaction Prompt (committed history can only be appended to; rewriting it would invalidate the prompt cache). Every failure — unusable summaries and the `failed`/`timeout`/`malformed` transport statuses alike — draws on the one reconnect budget and backoff ladder described under "Automatic reconnect" above; only `auth` stops the compaction at once. Once the budget is exhausted the compaction ends `failed`, keeping the original context and Trace file until the next trigger; `compaction_end` reuses the unified retry detail block — `attempt` (the final attempt's ordinal, failed attempts included) and, on failure, the last `error_message` detail (shown on the chat banner and the CLI line) — and a failed compaction also lands in the cost center as a `compaction_failed` error record. The first **committed** attempt — adopted or rejected — also absorbs whatever turn input was folded into the compaction request (mid-Task tool results, or the carry-over a manual `/compact` folds in) into the old context's history: retries resend only the repairs and the Prompt, and nothing resends the absorbed input afterwards.++An abandoned compaction is **made up later**, never patched over. Mid-Task the run ends the way any interruption does: the turn's still-pending state is held as carry-over under the same committed/not-committed rule, an `abort` event closes the run, and the next message resends that carry-over merged with the user's input — where the still-standing threshold triggers the compaction again. At a Task boundary the run simply ends with the original context kept. Either way nothing synthetic is invented to keep the loop running on a context that was supposed to shrink.++Compaction 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.++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.## Concurrency modeldiff --git a/packages/docs/content/agent-loop.zh.md b/packages/docs/content/agent-loop.zh.mdindex dc2fafaa..6e3f0c41 100644--- a/packages/docs/content/agent-loop.zh.md+++ b/packages/docs/content/agent-loop.zh.md@@ -125,7 +125,15 @@ interface CompactionSettings {两种模式:`summarize`(默认)向旧上下文追加压缩 Prompt,提取 `[summary]` 后包装为 `[context_summary]` 用户文本,在**全新的模型上下文**中继续;`discard` 直接丢弃旧上下文。系统标记统一写作 `[tag]…[/tag]`;读取旧 Trace 与旧压缩 Prompt 时仍识别早期的尖括号形式(`<summary>`、`<context_summary>` 等)。摘要提取自带容忍阶梯:优先取第一个非空的 `[summary]` 标签对;标签对全为空时,改取剥离标签后剩余的全部文本(兼容把正文写在闭合标签之后的模型);完全没有标签则整段输出照用。压缩时 [Trace 文件随之轮转](/sessions-and-traces)(`_002`、`_003`……),一个 Trace 文件恒等于一个完整模型上下文。`session.compact()` 前可用 `compactability()` 探询可行性(`ok | unsupported | empty | just_compacted`)。-压缩请求**保持会话工具集不变**——请求前缀(含工具列表)与普通轮次逐字节一致,确保上下文最大的时刻提供商的提示词缓存依然有效。只有得到有效摘要,压缩才算成功:若响应中出现工具调用、或提取出的摘要为空,视同一次普通的失败尝试——工具调用先以合成的失败输出逐一应答(保持 `tool_use`/`tool_result` 配对完整),重发的请求在压缩 Prompt 前附加一条纠正说明(已提交的历史只能追加、不能改写,改写会使提示词缓存失效)。所有失败——无效摘要与 `failed`/`timeout`/`malformed` 传输失败——共用上文「自动重连」一节的同一重连预算与退避阶梯;只有 `auth` 会让压缩当场停止。预算耗尽后压缩以 `failed` 结束,保留原上下文与 Trace 文件,等待下次触发;`compaction_end` 复用统一的重试详情块——`attempt`(最终尝试序号,失败尝试也计入)与失败时的 `error_message` 详情(聊天横幅与 CLI 直接展示),压缩失败还会作为一条 `compaction_failed` 错误记录进入成本中心。首个**已提交**的尝试(无论被采纳还是被判无效)同时会把折叠进压缩请求的本轮输入(任务中途的工具结果、手动 `/compact` 折叠的补发内容)吸收进旧上下文:重试只重发修复输出与压缩 Prompt,压缩放弃后的续跑也不再重发已吸收的输入。+压缩请求**保持会话工具集不变**——请求前缀(含工具列表)与普通轮次逐字节一致,确保上下文最大的时刻提供商的提示词缓存依然有效。只有得到有效摘要,压缩才算成功:若响应中出现工具调用、或提取出的摘要为空,视同一次普通的失败尝试——工具调用先以合成的失败输出逐一应答(保持 `tool_use`/`tool_result` 配对完整),重发的请求在压缩 Prompt 前附加一条纠正说明(已提交的历史只能追加、不能改写,改写会使提示词缓存失效)。所有失败——无效摘要与 `failed`/`timeout`/`malformed` 传输失败——共用上文「自动重连」一节的同一重连预算与退避阶梯;只有 `auth` 会让压缩当场停止。预算耗尽后压缩以 `failed` 结束,保留原上下文与 Trace 文件,等待下次触发;`compaction_end` 复用统一的重试详情块——`attempt`(最终尝试序号,失败尝试也计入)与失败时的 `error_message` 详情(聊天横幅与 CLI 直接展示),压缩失败还会作为一条 `compaction_failed` 错误记录进入成本中心。首个**已提交**的尝试(无论被采纳还是被判无效)同时会把折叠进压缩请求的本轮输入(任务中途的工具结果、手动 `/compact` 折叠的补发内容)吸收进旧上下文:重试只重发修复输出与压缩 Prompt,此后也不再重发已吸收的输入。++被放弃的压缩**留待补做**,而不是就地兜底。任务中途按打断的同一套流程收场:本轮尚未了结的状态按同一条「是否已提交」规则转入 carry-over,以 `abort` 事件结束本次运行,下一条消息把 carry-over 与用户输入合并重发——阈值依然超标,压缩在那里再次触发。Task 边界上则直接结束本次运行、保留原上下文。两种情形都不合成任何东西去让循环在本该缩小的上下文上硬跑下去。++任务中途触发的压缩绝不抢在工具前面:`runTurn` 要等本轮**全部**工具调用执行完毕才返回,因此到达压缩检查点时结果已经就绪、也已与 `tool_call` 配对。这些结果随后**随压缩请求本身**发出,排在压缩 Prompt 之前、保持原始调用顺序——工具产出什么(正常结果、`[tool error]`、被拒绝的回执),摘要就据此写成。需要审批或耗时数分钟的工具只是让压缩延后:压缩请求尚未发出,也就没有任何计时在跑。全程不插入任何合成消息去闭合该交换。++摘要生成期间,文本以普通的 `partial_text`(不产出流式消息的 LLM 实现则为完整 `text`)在成对压缩事件之间上行——不新增事件类型,压缩请求的其他原始消息一如既往只写 Trace。Web App 的压缩行**默认折叠,与思考块完全一致**:summarize 压缩一开始就带上折叠箭头,摘要在折叠的正文内流式写出,读者展开即可实时观看或事后阅读。历史重建从压缩区间已记录的输出读回同一段文本,刷新后与实时视图一致。渲染对话的消费方本就把压缩区间内的模型消息视为压缩内部消息,因此不会漏进正文。++用户中途退出程序导致没写完的压缩(留下没有配对 end 的 `compaction_begin`),就是一次**压缩失败**。会话下次加载时,恢复流程在续写任何内容之前先以 `failed` 收束该区间,并**直接丢弃写了一半的摘要**:不做任何重建,原上下文照旧,阈值依然超标、压缩留待下次触发时补做。收束区间正是让其后对话保持可见的关键——所有读取方都把成对事件之间的消息当作压缩内部消息;Web 端同时丢掉那段半成品草稿,不把截断的摘要摆成像是已被采纳的样子。## 并发模型diff --git a/packages/docs/content/message-flow.en.md b/packages/docs/content/message-flow.en.mdindex 3d45c473..134ab550 100644--- a/packages/docs/content/message-flow.en.md+++ b/packages/docs/content/message-flow.en.md@@ -103,7 +103,7 @@ Therefore **a renderer must never reconstruct the context from arrival order**| --- | --- || User interrupt | (messages produced so far) → the `abort` event — the last message before `run` returns; carry-over goes to the model context only, never streamed, never written to Trace || Automatic reconnect | `request_end(failed \| timeout \| malformed)` → a fresh `request_begin` (up to 5 times, exponential backoff with a 30s ceiling; only `auth` skips the ladder); the `[turn_retried]` block is model-visible only |-| Compaction | `compaction_begin` → the compaction request runs against the old context (its streamed output is **not** forwarded, only written to Trace) → that request's `token_usage` → `compaction_end(status)` |+| Compaction | `compaction_begin` → the compaction request runs against the old context (its raw messages are written to Trace only, except the summary text being generated, which is forwarded as ordinary `partial_text`/`text` inside the span) → that request's `token_usage` → `compaction_end(status)` || max_turns reached | a length notice → the run ends; unsubmitted input is kept as carry-over || The Prompt itself | written to Trace, not echoed back onto the stream (the caller already has it) || session_meta | never emitted on the main Session's stream (it lives in the Trace and the history API); a Subagent child stream's **first** message is the child's `session_meta` |diff --git a/packages/docs/content/message-flow.zh.md b/packages/docs/content/message-flow.zh.mdindex 97403c95..c394b8f5 100644--- a/packages/docs/content/message-flow.zh.md+++ b/packages/docs/content/message-flow.zh.md@@ -102,7 +102,7 @@ Human ──run(newMessages)──► engine| --- | --- || 用户中断 | (已产出的消息)→ `abort` 事件——`run` 返回前的最后一条;补发内容只进模型上下文,不上流、不进 Trace || 自动重连 | `request_end(failed \| timeout \| malformed)` → 新的 `request_begin`(至多 5 次,指数退避、上限 30s;只有 `auth` 不走梯度);`[turn_retried]` 块仅模型可见 |-| 上下文压缩 | `compaction_begin` → 压缩请求在旧上下文中执行(其流式输出**不上行**,只写 Trace)→ 该请求的 `token_usage` → `compaction_end(status)` |+| 上下文压缩 | `compaction_begin` → 压缩请求在旧上下文中执行(原始消息只写 Trace,唯一例外是正在生成的摘要文本——以普通 `partial_text`/`text` 在区间内上行)→ 该请求的 `token_usage` → `compaction_end(status)` || 达到 max_turns | 长度提示消息 → 结束;未提交的输入按补发保留 || Prompt 本身 | 写入 Trace,但不回流(输入方已有) || session_meta | 主 Session 的输出流不产出它(存在于 Trace 与历史接口中);Subagent 子流的**第一条**是子 Session 的 `session_meta` |diff --git a/packages/server/src/services/message-window.ts b/packages/server/src/services/message-window.tsindex e2551198..30a127ea 100644--- a/packages/server/src/services/message-window.ts+++ b/packages/server/src/services/message-window.ts@@ -298,7 +298,10 @@ export async function scanMessages(continue;}if (t === "compaction_end") {- // Closes the banner opened by the begin (no new item mid-window).+ // Closes the banner opened by the begin (no new item mid-window). A compaction the+ // user quit out of is closed as `failed` by the resume path before the session+ // appends anything else (see core's resumeSession), so a span is never left open+ // across the conversation that follows it.state.compactionActive = false;continue;}diff --git a/packages/server/test/messages-page.test.ts b/packages/server/test/messages-page.test.tsindex e401606e..356ffb1b 100644--- a/packages/server/test/messages-page.test.ts+++ b/packages/server/test/messages-page.test.ts@@ -15,6 +15,7 @@import fs from "node:fs/promises";import { afterEach, beforeEach, describe, expect, it } from "vitest";import {+ abortEvent,assistantText,compactionBegin,compactionEnd,@@ -201,6 +202,75 @@ describe("messages windowed reads", () => {expect([...older.messages, ...tail.messages]).toEqual(full);});+ it("a compaction the user quit out of keeps the conversation after it visible (issue #288)", async () => {+ // The process died mid-compaction, leaving compaction_begin with no end; core's resume+ // closes the span as `failed` before the session continues the shard. The scanner must+ // treat everything after the closure as ordinary conversation again — before the fix,+ // the unclosed begin kept `compactionActive` set for the rest of the shard and every+ // later prompt vanished from the window (no boundary, no unit, no messages).+ await writeTraceFile(root, P, A, "2026-07-20", S, 1, [+ sessionMeta(metaPayload()),+ ...turn(0, 1, 1000),+ at(+ "2026-07-20T10:01:00.000Z",+ compactionBegin({ reason: "context", mode: "summarize", context: 900, turns: 1 }),+ ),+ at("2026-07-20T10:01:01.000Z", userText("COMPACT NOW")),+ at("2026-07-20T10:01:02.000Z", requestBegin()),+ // ...process died; the resume closed the span before writing anything else:+ at(+ "2026-07-20T10:01:30.000Z",+ compactionEnd({ reason: "context", mode: "summarize", status: "failed" }),+ ),+ ...turn(2, 2, 2000),+ ]);++ const tail = await service.readMessagesPage(P, A, S, { kind: "tail", limit: 1 });+ // The post-crash prompt is a unit of its own and stays visible.+ expect(userTexts(tail.messages)).toEqual(["q2"]);+ expect(tail.prior.turns).toBe(1);++ // The windows still tile the transcript exactly.+ const older = await service.readMessagesPage(P, A, S, {+ kind: "before",+ cursor: decodeCursor(tail.before!)!,+ limit: 10,+ });+ const full = await service.readMessages(P, A, S);+ expect([...older.messages, ...tail.messages]).toEqual(full);+ });++ it("a mid-task compaction the user interrupted keeps its own turn's messages in the window", async () => {+ // The user hit stop during a mid-task compaction: the engine closes the pair and ends+ // the run with an abort, all inside the turn that q1 opened. The abort does not cut a+ // window of its own, and the interrupted compaction stays attached to its turn.+ await writeTraceFile(root, P, A, "2026-07-20", S, 1, [+ sessionMeta(metaPayload()),+ ...turn(0, 1, 1000),+ at(+ "2026-07-20T10:01:00.000Z",+ compactionBegin({ reason: "context", mode: "summarize", context: 900, turns: 1 }),+ ),+ at("2026-07-20T10:01:01.000Z", userText("COMPACT NOW")),+ at(+ "2026-07-20T10:01:02.000Z",+ compactionEnd({ reason: "context", mode: "summarize", status: "aborted" }),+ ),+ at("2026-07-20T10:01:03.000Z", abortEvent("aborted during compaction")),+ ...turn(2, 2, 2000),+ ]);++ const tail = await service.readMessagesPage(P, A, S, { kind: "tail", limit: 1 });+ expect(userTexts(tail.messages)).toEqual(["q2"]);+ const older = await service.readMessagesPage(P, A, S, {+ kind: "before",+ cursor: decodeCursor(tail.before!)!,+ limit: 10,+ });+ const full = await service.readMessages(P, A, S);+ expect([...older.messages, ...tail.messages]).toEqual(full);+ });+it("cuts are pairing-safe: a tool_call and its output never split, steering images stay with their chip", async () => {await writeTraceFile(root, P, A, "2026-07-20", S, 1, [sessionMeta(metaPayload()),diff --git a/packages/web/e2e/compaction.spec.mjs b/packages/web/e2e/compaction.spec.mjsindex 0af91994..aa68dd31 100644--- a/packages/web/e2e/compaction.spec.mjs+++ b/packages/web/e2e/compaction.spec.mjs@@ -1,17 +1,20 @@/*** Auto-compaction triggered at the **end** of a round: item order is- * assistant_text -> compaction -> task_stats, with the compaction banner sandwiched between- * the reply and its stats line.+ * assistant_text -> task_stats -> compaction, and the compaction row itself is collapsed by+ * default with the generated summary inside it.*- * This ordering used to break the "reply + stats line" pairing, leaving the stats line+ * The ordering used to break the "reply + stats line" pairing, leaving the stats line* orphaned — and since the whole line is transparent by default, being orphaned meant it was* neither visible nor hoverable (the element's own `group` class has no effect on itself:* group-hover is a descendant selector). Now the entire round's AI-side content, stats line* included, is wrapped in the same group, so hovering any content in the round reveals it.*- * Trigger mechanism: the mock's usage grows with context length, pinning the threshold between- * "below the first request" and "above the second request (which carries the tool result)", so- * compaction only happens once, at the end of the round.+ * Trigger mechanism: the mock's usage grows with context length, and the Agent's+ * `compaction.max_context_length` is pinned between "below the first request" and "above the+ * second request (which carries the tool result)", so compaction happens once, at the end of+ * the round. The threshold is set on the **Agent config** rather than derived from the model's+ * context window: the engine's window-derived cap (`context_window - 2048`, and windows under+ * 4096 are ignored as implausible) cannot express a threshold this small.*/import { test, expect } from "@playwright/test";import { provisionAndLogin } from "./auth.mjs";@@ -20,8 +23,10 @@ const BASE = process.env.BASE_URL;const MOCK = process.env.MOCK_URL;const U = "compactuser";const P = "password123";-/** Context window: the engine takes 75% as the compaction threshold (240 x 0.75 = 180), landing between the two requests' usage. */+/** Displayed in the composer's context ring; large enough that only the Agent threshold below decides when compaction fires. */const CONTEXT_WINDOW = 240;+/** Compaction threshold: above the first request's reported usage, below the second's (which carries the tool result). */+const COMPACT_AT = 180;test("compaction mid-turn: the reply's stats line is still reachable by hovering the reply", async ({page,@@ -44,6 +49,10 @@ test("compaction mid-turn: the reply's stats line is still reachable by hovering],},});+ // The compaction threshold lives on the Agent, not the model entry (see the header note).+ await page.request.put(`${BASE}/api/projects/${projectId}/agents/default_agent/config`, {+ data: { config: { compaction: { maxContextLength: COMPACT_AT } } },+ });const sess = await (await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {data: { provider: "custom", modelId: "claude-4-8", approvalMode: "allow-all" },@@ -58,13 +67,15 @@ 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();- const banner = page.getByText(/\[压缩\]/).first();+ // The compaction row is a step banner: a disclosure button reading "压缩" plus its outcome.+ const banner = page.locator("button[aria-expanded]").filter({ hasText: "压缩" }).first();await expect(banner).toBeVisible();+ await expect(banner).toContainText("已切换到摘要后的新上下文");- // The compaction banner 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- // card instead) — the banner only states "compaction happened, succeeded or not."- await expect(page.getByText(/\[压缩\].*tokens/)).toHaveCount(0);+ // 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 card+ // instead) — the row only states "compaction happened, succeeded or not."+ await expect(banner).not.toContainText("tokens");// Order: reply -> **this round's stats line** -> compaction banner. The stats line is about// this round of conversation; compaction is housekeeping outside this round, listed after this@@ -91,6 +102,27 @@ test("compaction mid-turn: the reply's stats line is still reachable by hoveringawait expect(page.getByText(`—/${CONTEXT_WINDOW}`)).toBeVisible();await expect(page.getByText(`0/${CONTEXT_WINDOW}`)).toHaveCount(0);+ // —— The summary is collapsed by default, exactly like a thinking block ——+ // The generated summary must not be on screen until the reader asks for it: the row starts+ // collapsed and its body is not rendered at all. The mock answers the compaction request+ // with the same prose it used for the reply, so the summary's presence is counted rather+ // than matched by text alone (1 = the reply only, 2 = the reply + the expanded summary).+ const card = banner.locator("xpath=..");+ const summaryLine = /the result looks as expected/;+ await expect(banner).toHaveAttribute("aria-expanded", "false");+ await expect(card.getByText(summaryLine)).toHaveCount(0);+ await expect(page.getByText(summaryLine)).toHaveCount(1);++ await banner.click();+ await expect(banner).toHaveAttribute("aria-expanded", "true");+ await expect(card.getByText(summaryLine).first()).toBeVisible();+ await expect(page.getByText(summaryLine)).toHaveCount(2);++ // Collapsing puts it away again (the body leaves the DOM, not just the viewport).+ await banner.click();+ await expect(banner).toHaveAttribute("aria-expanded", "false");+ await expect(card.getByText(summaryLine)).toHaveCount(0);+// —— Trace page ——// Compaction is its own round: the user round's elapsed time and TPS don't include compaction// (matching the chat page's convention), and the compaction round has **its own TPS** (how@@ -214,7 +246,11 @@ test("manual /compact between turns: reloading must not fold the compaction intoawait page.waitForTimeout(3000);await ta.fill("/compact");await ta.press("Enter");- await expect(page.getByText(/\[压缩\]/)).toBeVisible();+ const banner = page.locator("button[aria-expanded]").filter({ hasText: "压缩" }).first();+ await expect(banner).toBeVisible();+ // Collapsed by default here too: a manual compaction reports itself in one line and keeps+ // its summary behind the disclosure.+ await expect(banner).toHaveAttribute("aria-expanded", "false");await expect(page.getByRole("button", { name: "停止" })).toHaveCount(0);expect(await statsText(), "compaction must not touch the already-closed prior turn").toBe(live);diff --git a/packages/web/src/features/chat/compaction-banner.tsx b/packages/web/src/features/chat/compaction-banner.tsxindex 8da59480..a4d75e14 100644--- a/packages/web/src/features/chat/compaction-banner.tsx+++ b/packages/web/src/features/chat/compaction-banner.tsx@@ -2,6 +2,16 @@* 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.+ *+ * 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.+ ** 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* that happens **mid-turn** counts toward that turn's stats line and cost; compaction **after a@@ -10,9 +20,27 @@*/import { S } from "../../lib/strings";import type { CompactionItem } from "../../lib/omni/stream-model";+import { compactionSummaryText } from "../../lib/omni/compaction-summary";+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 }) {+ 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>+ );+}+export function CompactionBanner({ item }: { item: CompactionItem }) {+ const summary = compactionSummaryText(item);+ // 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;+if (item.running) {return (<StepBanner@@ -20,7 +48,9 @@ export function CompactionBanner({ item }: { item: CompactionItem }) {title={S.chat.compactionTitle}detail={item.mode}{...(item.beginTsMs !== undefined ? { liveSinceMs: item.beginTsMs } : {})}- />+ >+ {body}+ </StepBanner>);}const ok = item.status === "completed";@@ -34,6 +64,8 @@ export function CompactionBanner({ item }: { item: CompactionItem }) {: S.chat.compactionFailed(item.status ?? "failed", item.errorMessage)}{...(item.durationMs !== undefined ? { durationMs: item.durationMs } : {})}- />+ >+ {body}+ </StepBanner>);}diff --git a/packages/web/src/features/chat/step-banner.tsx b/packages/web/src/features/chat/step-banner.tsxindex fb7a8385..352118ee 100644--- a/packages/web/src/features/chat/step-banner.tsx+++ b/packages/web/src/features/chat/step-banner.tsx@@ -35,7 +35,7 @@ export function StepBanner({liveSinceMs?: number;/** Settled wall time once finished. */durationMs?: number;- /** Expandable body; its presence adds the chevron (collapsed by default). */+ /** Expandable body; its presence adds the chevron (collapsed by default, streaming included). */children?: ReactNode;}) {const [open, setOpen] = useState(false);diff --git a/packages/web/src/lib/omni/compaction-summary.ts b/packages/web/src/lib/omni/compaction-summary.tsnew file mode 100644index 00000000..f5542a98--- /dev/null+++ b/packages/web/src/lib/omni/compaction-summary.ts@@ -0,0 +1,19 @@+/**+ * Display text for a compaction row's expandable body: the summary the compaction request+ * wrote, with the `[summary]` tags stripped.+ *+ * Split out of the banner component so it can be unit-tested (the Web test suite runs in a+ * node environment and renders no React). Extraction uses core's own lenient extractor, so+ * what the row shows is what the engine would adopt: the first non-empty tag pair, else the+ * text left after stripping empty tags, else the raw output verbatim — a summary still+ * mid-stream (opening tag written, closing tag not yet) therefore reads as plain text+ * rather than disappearing until the model closes the block.+ */+import { extractSummary } from "@prismshadow/penguin-core/markers";+import type { CompactionItem } from "./stream-model";++export function compactionSummaryText(item: Pick<CompactionItem, "summaryText">): string {+ const raw = item.summaryText;+ if (!raw) return "";+ return extractSummary(raw).trim();+}diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.tsindex f94119da..5ffb715e 100644--- a/packages/web/src/lib/omni/stream-model.ts+++ b/packages/web/src/lib/omni/stream-model.ts@@ -29,10 +29,12 @@* events aren't rendered (Request duration is covered by Trace* performance analysis); compaction_begin/end → a banner item;* token_usage → fed into stats (task-stats.ts).- * - Compaction-internal messages (history rebuild): model_msg within a+ * - Compaction-internal messages: model_msg within a* compaction_begin↔end range (the compaction prompt and summary output)- * are never rendered and never counted toward Task segmentation — aligned- * with the live stream (which only pushes the event pair + token_usage);+ * 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);* 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@@ -257,6 +259,14 @@ export interface CompactionItem {beginTsMs?: number;/** Wall time derived from the begin/end message timestamps (absent on a mid-stream join). */durationMs?: number;+ /**+ * Raw text of the summary the compaction request is generating (issue #290): accumulated+ * live from the span's own partial_text fragments, and rebuilt identically on history+ * replay from the span's complete assistant text — the banner shows the summary being+ * written and keeps it readable after a reload. Raw model output (summary tags included;+ * the banner strips them for display); absent when nothing streamed (e.g. discard mode).+ */+ summaryText?: string;}/** One MCP tool for the connect row's expandable list (from tool_list_ready, `mcp__` entries only). */@@ -583,12 +593,26 @@ 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, never- // counted toward Task segmentation — aligned with the live stream- // (which only pushes the event pair and token_usage). Only encountered during history rebuild.+ // (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.if (model.stats.compactionActive) {touchTask(model, 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);+ // 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 };+ if (p.type === "text" && p.role === "assistant" && p.text) {+ appendCompactionSummaryText(model, p.text);+ }return;}if (isPartialPayload(msg.payload)) {@@ -1468,6 +1492,11 @@ function handleEvent(model: StreamModel, p: EventPayload, tsMs?: number, nowMs?:if (tsMs !== undefined && item.beginTsMs !== undefined) {item.durationMs = Math.max(0, tsMs - item.beginTsMs);}+ // 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;} else {// Mid-stream join (missed the begin): append a completed banner directly.const created: CompactionItem = {@@ -1589,6 +1618,13 @@ 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 {+ if (!text) return;+ const item = findLastRunningCompaction(model);+ if (item) item.summaryText = (item.summaryText ?? "") + text;+}+/*** Whether a compaction starting right now wraps the round up rather than interrupting it* mid-Task — the test for settling the round's stats row ahead of the banner.diff --git a/packages/web/test/compaction-summary.test.ts b/packages/web/test/compaction-summary.test.tsnew file mode 100644index 00000000..11e03be3--- /dev/null+++ b/packages/web/test/compaction-summary.test.ts@@ -0,0 +1,35 @@+/**+ * compaction-summary.ts: the text a compaction row shows inside its collapsed body.+ *+ * 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).+ */+import { describe, expect, it } from "vitest";+import { compactionSummaryText } from "../src/lib/omni/compaction-summary";++describe("compactionSummaryText", () => {+ it("strips the summary tags so the body reads as prose", () => {+ expect(compactionSummaryText({ summaryText: "[summary]the plan[/summary]" })).toBe("the plan");+ });++ it("shows a summary still mid-stream, before the model closes the block", () => {+ // The body streams while collapsed: an unclosed `[summary]` must read as the text so+ // far, not vanish until the closing tag arrives.+ expect(compactionSummaryText({ summaryText: "[summary]writing the pl" })).toBe(+ "writing the pl",+ );+ });++ it("uses tagless output verbatim (core's lenient extraction)", () => {+ expect(compactionSummaryText({ summaryText: "no tags at all" })).toBe("no tags at all");+ });++ it("is empty when nothing streamed — a discard compaction, or a failed one whose draft was discarded", () => {+ expect(compactionSummaryText({})).toBe("");+ expect(compactionSummaryText({ summaryText: "" })).toBe("");+ expect(compactionSummaryText({ summaryText: " " })).toBe("");+ });+});diff --git a/packages/web/test/stream-model.test.ts b/packages/web/test/stream-model.test.tsindex f8a65fd6..d30e87a8 100644--- a/packages/web/test/stream-model.test.ts+++ b/packages/web/test/stream-model.test.ts@@ -505,6 +505,123 @@ describe("approvals and events", () => {expect(banner.durationMs).toBe(4500);});+ it("the span's partial_text accumulates the streamed summary onto the running banner (issue #290)", () => {+ const m = createStreamModel();+ pushMessage(+ m,+ compactionBegin({ reason: "context", mode: "summarize", context: 1000, turns: 3 }),+ );+ const banner = items(m)[0] as CompactionItem;+ pushMessage(m, partialText("start"));+ pushMessage(m, partialText("delta", "[summary]the "));+ pushMessage(m, partialText("delta", "plan[/summary]"));+ pushMessage(m, partialText("stop"));+ expect(banner.summaryText).toBe("[summary]the plan[/summary]");+ // The span's text renders no transcript item of its own.+ expect(items(m).filter((i) => i.kind === "assistant_text")).toHaveLength(0);+ pushMessage(m, compactionEnd({ reason: "context", mode: "summarize", status: "completed" }));+ // The accumulated text survives the end: the settled banner still shows the summary.+ expect(banner.summaryText).toBe("[summary]the plan[/summary]");+ // After the span, partial_text is ordinary model output again — it opens an assistant+ // text item instead of appending to the settled banner.+ pushMessage(m, partialText("start"));+ pushMessage(m, partialText("delta", "next answer"));+ expect(banner.summaryText).toBe("[summary]the plan[/summary]");+ const after = items(m).filter((i) => i.kind === "assistant_text") as AssistantTextItem[];+ expect(after).toHaveLength(1);+ expect(after[0]!.text).toBe("next answer");+ });++ 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.+ const m = createStreamModel();+ pushMessage(m, userText("q1"));+ pushMessage(m, requestBegin());+ pushMessage(m, assistantText("a1"));+ pushMessage(m, tokenUsage(counts(1000), counts(1000)));+ pushMessage(m, requestEnd("completed"));+ pushMessage(+ m,+ compactionBegin({ reason: "context", mode: "summarize", context: 1000, turns: 1 }),+ );+ pushMessage(m, userText("COMPACT NOW")); // the compaction prompt: user text, never summary material+ pushMessage(m, requestBegin());+ pushMessage(m, thinkingMessage("planning")); // thinking is not summary text either+ pushMessage(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]");+ // Span-internal messages still render nothing of their own.+ expect(items(m).filter((i) => i.kind === "assistant_text")).toHaveLength(1);+ });++ it("a compaction the user quit out of is closed as failed on load; the conversation after it renders (issue #288)", () => {+ // The process died mid-compaction, leaving compaction_begin with no end. Core's resume+ // closes the span with a `failed` compaction_end before appending anything else, so+ // everything after it is ordinary conversation again — not hidden as compaction-internal.+ const m = createStreamModel();+ pushMessage(m, userText("q1"));+ pushMessage(+ m,+ compactionBegin({ reason: "context", mode: "summarize", context: 1000, turns: 1 }),+ );+ pushMessage(m, userText("COMPACT NOW"));+ pushMessage(m, requestBegin());+ pushMessage(m, assistantText("[summary]half-writ")); // the draft the crash interrupted+ // ...process died here; the resume closes the span as failed before writing anything else:+ pushMessage(m, compactionEnd({ reason: "context", mode: "summarize", status: "failed" }));+ // The conversation continues and must render.+ pushMessage(m, userText("q2 after the crash"));+ pushMessage(m, requestBegin());+ pushMessage(m, toolCall({ name: "exec", arguments: "{}", toolCallId: "t1" }));+ pushMessage(m, requestEnd("completed"));+ pushMessage(m, toolCallOutput({ output: "ok", toolCallId: "t1" }));++ const users = items(m).filter((i) => i.kind === "user_text") as UserTextItem[];+ expect(users.map((u) => u.text)).toContain("q2 after the crash");+ // The tool card carries its real name — no "(unknown tool)" orphan output card.+ const cards = items(m).filter((i) => i.kind === "tool_call") as ToolCallItem[];+ expect(cards).toHaveLength(1);+ 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.+ const banner = items(m).find((i) => i.kind === "compaction") as CompactionItem;+ expect(banner).toMatchObject({ running: false, status: "failed" });+ expect(banner.summaryText).toBeUndefined();+ });++ it("an aborted compaction discards its partial summary too (live interrupt)", () => {+ const m = createStreamModel();+ pushMessage(+ m,+ compactionBegin({ reason: "manual", mode: "summarize", context: 1000, turns: 3 }),+ );+ 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");+ pushMessage(m, compactionEnd({ reason: "manual", mode: "summarize", status: "aborted" }));+ expect(banner.status).toBe("aborted");+ expect(banner.summaryText).toBeUndefined();+ });++ it("a completed compaction keeps its summary for the collapsed body", () => {+ const m = createStreamModel();+ pushMessage(+ m,+ compactionBegin({ reason: "manual", mode: "summarize", context: 1000, turns: 3 }),+ );+ pushMessage(m, partialText("start"));+ pushMessage(m, partialText("delta", "[summary]the plan[/summary]"));+ pushMessage(m, compactionEnd({ reason: "manual", mode: "summarize", status: "completed" }));+ const banner = items(m)[0] as CompactionItem;+ expect(banner.status).toBe("completed");+ expect(banner.summaryText).toBe("[summary]the plan[/summary]");+ });+it("mcp connect row: end sums the discovered-tool count, keeps per-server outcomes, and derives the wall time", () => {const m = createStreamModel();pushMessage(m, at(mcpConnectBegin(["fx", "bad"]), "2026-01-01T00:00:00.000Z"));