Skip to content

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

fix(web): settle a round's stats row when its wrap-up compaction begins (#338)

Yaowei Zheng3a155e434f9d
diff --git a/changelog/unreleased/2026-08-19-compaction-stats-row-order.md b/changelog/unreleased/2026-08-19-compaction-stats-row-order.md
new file mode 100644
index 00000000..0a432f78
--- /dev/null
+++ b/changelog/unreleased/2026-08-19-compaction-stats-row-order.md
@@ -0,0 +1,17 @@
+# A wrap-up compaction settles the round's stats row before its banner appears
+
+- **Date:** 2026-08-19
+- **Type:** fix
+- **Scope:** `web`
+
+[中文版](2026-08-19-compaction-stats-row-order.zh.md)
+
+A compaction that runs once a Task's conversation is over now settles that round's stats row as it begins, so its banner is created underneath the row instead of being moved below it afterwards.
+
+## Details
+
+The stats row already ended up above a trailing compaction banner — compaction is its own round, so the row reporting the conversation belongs first — but the row was placed there at task-idle, once the compaction had finished. A compaction request runs against the largest context of the session, so for those seconds the banner sat directly under the reply and then jumped down as the row slid in above it.
+
+- A compaction beginning while a Task is open is treated as wrapping the round up when the turn that just ran produced no tool outputs (the engine's own criterion for a mid-Task compaction) **and** the round's last item is the model's reply. Both signals must agree; either one being unsure keeps the previous placement-at-finalization behavior, which still covers a mid-stream join and a round whose reply never landed as an item.
+- A mid-Task compaction is unaffected: the round stays open, and its ledger — including that compaction's tokens — still settles at the end of the Task.
+- Steering queued while a wrap-up compaction runs is delivered after it and keeps the Task going; the steering chip opens the continuation's own round, so its reply keeps a footer of its own rather than joining a round that was already settled.
diff --git a/changelog/unreleased/2026-08-19-compaction-stats-row-order.zh.md b/changelog/unreleased/2026-08-19-compaction-stats-row-order.zh.md
new file mode 100644
index 00000000..b092cda1
--- /dev/null
+++ b/changelog/unreleased/2026-08-19-compaction-stats-row-order.zh.md
@@ -0,0 +1,17 @@
+# 收尾压缩在横幅出现之前就结算本轮统计行
+
+- **Date:** 2026-08-19
+- **Type:** fix
+- **Scope:** `web`
+
+[English](2026-08-19-compaction-stats-row-order.md)
+
+对话结束之后才跑的压缩,现在在压缩开始的那一刻就结算本轮的统计行,横幅因此直接诞生在统计行下方,而不是事后再被挪到它下面。
+
+## 详情
+
+统计行原本最终也会排在收尾压缩横幅之上——压缩自成一轮,负责陈述这轮对话的统计行理应在前——但它是在 Task 转入 idle、也就是压缩跑完之后才被放到那个位置的。压缩请求面对的是整个会话最大的上下文,那几秒里横幅就紧贴在回复下面,等统计行插到它上面时再往下跳一格。
+
+- Task 仍打开时开始的压缩,若刚跑完的这一轮没有产生工具输出(引擎判定「任务中途压缩」用的同一条依据),**且**本轮最后一个条目是模型的回复,即视为收尾压缩。两个信号必须一致;任何一个拿不准就沿用此前「结算时再定位」的行为,它仍然覆盖中途加入的流和回复未落成条目的轮次。
+- 任务中途的压缩不受影响:该轮保持打开,其账目(含这次压缩的 Token)照旧在 Task 结束时结算。
+- 收尾压缩期间排队的 steering 会在压缩之后送达并让 Task 继续;此时 steering 小块会开启续跑自己的一轮,续跑的回复因而保有自己的页脚,而不是并入一个已经结算的轮次。
diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.ts
index 289e471d..f94119da 100644
--- a/packages/web/src/lib/omni/stream-model.ts
+++ b/packages/web/src/lib/omni/stream-model.ts
@@ -484,6 +484,22 @@ export interface StreamModel {
* null = this round has no request_end yet (a degenerate round, falls back to taskLastTsMs).
*/
taskLastReqEndMs: number | null;
+ /**
+ * Whether the turn that ran most recently produced tool outputs — the same
+ * question the engine asks to tell a mid-Task compaction from a wrap-up one
+ * (`turn.toolOutputs.length > 0`). Set by a complete tool_call_output, cleared
+ * when the next Request opens, and read at `compaction_begin` (see
+ * `isWrapUpCompaction`).
+ */
+ turnToolOutputs: boolean;
+ /**
+ * A wrap-up compaction closed the round before its banner was created (see
+ * `compaction_begin`), yet the Task can still continue: steering queued while
+ * that compaction ran is delivered right after it and keeps the loop going.
+ * The steering chip reopens a Task for that continuation, so its reply gets a
+ * ledger of its own instead of no footer at all.
+ */
+ reopenTaskAtSteering: boolean;
nextItemId: number;
}
@@ -512,6 +528,8 @@ function newModel(nested: boolean, localDecisions: Set<string>): StreamModel {
taskFirstTsMs: 0,
taskLastTsMs: 0,
taskLastReqEndMs: null,
+ turnToolOutputs: false,
+ reopenTaskAtSteering: false,
nextItemId: 1,
};
}
@@ -775,6 +793,8 @@ function startTask(model: StreamModel, timestamp: string, nowMs: number): void {
// Any unclosed Request start / approval wait left over from the previous Task isn't carried into this Task's LLM timing.
model.openRequestBeginMs = null;
model.openApprovalWaitMs = 0;
+ model.turnToolOutputs = false;
+ model.reopenTaskAtSteering = false;
model.taskOpen = true;
model.taskStartLocalMs = nowMs;
const ts = Date.parse(timestamp);
@@ -826,13 +846,14 @@ function finalizeOpenTask(model: StreamModel): void {
assistantText: reply.text,
...(reply.atMs !== undefined ? { atMs: reply.atMs } : {}),
};
- // The stats row is inserted **before this trailing run of compaction
- // banners**: an automatic compaction triggered while finalizing a round
- // would otherwise sandwich its banner between the reply and the stats row
- // (items: assistant_text → compaction → task_stats), leaving the stats
- // row underneath the banner, reading as if it were "the compaction's
- // stats" when it's actually reporting this round's conversation.
- // Compaction is housekeeping outside this round, so it belongs after this round's ledger, not before it.
+ // The stats row is inserted **before any trailing run of compaction banners**: compaction
+ // is its own round, housekeeping outside this one, so it belongs after this round's ledger
+ // — a banner sandwiched between the reply and the row (assistant_text → compaction →
+ // task_stats) reads as if the row were the compaction's own stats.
+ // A wrap-up compaction normally settles the round on arrival, before its banner exists
+ // (see isWrapUpCompaction), so this loop is what still places the row correctly in the
+ // cases that test declines to judge — a mid-stream join, or a round whose reply never
+ // landed as an item.
let at = model.items.length;
while (at > 0 && model.items[at - 1]!.kind === "compaction") at--;
model.items.splice(at, 0, statsItem);
@@ -1002,6 +1023,11 @@ function handleComplete(
// user-styled steering chip in-flow.
const steering = parseUserSteeringText(p.text);
if (steering !== null) {
+ // Unless a wrap-up compaction already settled the round it belongs to: this
+ // steering is exactly why the Task went on past that compaction, so it opens the
+ // continuation's own round rather than joining a closed one (see
+ // reopenTaskAtSteering).
+ if (model.reopenTaskAtSteering && !model.taskOpen) startTask(model, timestamp, nowMs);
touchTask(model, timestamp);
const steerMs = tsOf(timestamp);
const item: UserSteeringItem = {
@@ -1195,6 +1221,9 @@ function handleComplete(
card.outputComplete = true;
if (p.stop_reason !== undefined) card.outputStopReason = p.stop_reason;
settleToolDuration(card, tsOf(timestamp));
+ // This turn owes the model its results, so a compaction triggering now is mid-Task
+ // and the round is not over (see turnToolOutputs).
+ model.turnToolOutputs = true;
return;
}
// inline_data / inline_thinking: same convention as the CLI's history rendering — not shown for now.
@@ -1408,6 +1437,15 @@ function handleEvent(model: StreamModel, p: EventPayload, tsMs?: number, nowMs?:
return;
}
case "compaction_begin": {
+ // A wrap-up compaction is its own round, so the round it follows is over: settle that
+ // round's ledger NOW, before the banner exists, and the banner is created underneath
+ // it. Settling at task-idle instead would put the banner on screen first and slide the
+ // stats row in above it once the compaction finished — a jump, since a compaction
+ // request against the largest context of the session takes seconds.
+ if (isWrapUpCompaction(model)) {
+ finalizeOpenTask(model);
+ model.reopenTaskAtSteering = true;
+ }
beginCompaction(model.stats);
model.items.push({
kind: "compaction",
@@ -1453,6 +1491,8 @@ function handleEvent(model: StreamModel, p: EventPayload, tsMs?: number, nowMs?:
if (!model.stats.compactionActive) {
model.openRequestBeginMs = tsMs ?? null;
model.openApprovalWaitMs = 0;
+ // A new turn: whatever the previous one owed the model has been sent with it.
+ model.turnToolOutputs = false;
}
return;
}
@@ -1549,6 +1589,26 @@ function findLastRunningCompaction(model: StreamModel): CompactionItem | null {
return null;
}
+/**
+ * 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.
+ *
+ * Two signals must agree, and either one being unsure simply leaves the old behavior (the row
+ * is placed above the trailing banners at finalization instead, see finalizeOpenTask):
+ * - the turn that just ran produced no tool outputs — the engine's own criterion for a
+ * mid-Task compaction (`turn.toolOutputs.length > 0`);
+ * - the round's last item is the model's reply, which is what "the conversation ended" looks
+ * like on screen. A client that joined mid-Task, or a history window paged in after this
+ * round's tool outputs, can satisfy the first signal without ever having seen them, while a
+ * tool card sitting at the end says the round is still working.
+ * A manual `/compact` between Tasks needs neither: no Task is open, so there is nothing to
+ * settle and the banner already lands after the previous round's row.
+ */
+function isWrapUpCompaction(model: StreamModel): boolean {
+ if (!model.taskOpen || model.turnToolOutputs) return false;
+ return model.items[model.items.length - 1]?.kind === "assistant_text";
+}
+
function findLastWaitingReconnect(model: StreamModel): ReconnectItem | null {
for (let i = model.items.length - 1; i >= 0; i--) {
const item = model.items[i]!;
diff --git a/packages/web/test/stream-model.test.ts b/packages/web/test/stream-model.test.ts
index c14b83c2..f8a65fd6 100644
--- a/packages/web/test/stream-model.test.ts
+++ b/packages/web/test/stream-model.test.ts
@@ -1150,6 +1150,139 @@ describe("compaction attribution by position: in-round counts toward the round,
expect(stats.stats!.elapsedDeltaMs).toBe(3_000);
});
+ it("a wrap-up compaction settles the round's stats row as it begins, so the banner is born below it", () => {
+ // The row's final position was already right, but it used to be spliced in at task-idle —
+ // after the compaction request had finished. A compaction runs against the largest
+ // context of the session, so for those seconds the banner sat directly under the reply
+ // and then jumped down once the row appeared above it. The round is over the moment a
+ // wrap-up compaction starts, so its ledger is settled right there.
+ const m = createStreamModel();
+ pushMessages(m, [
+ at(userText("Q"), "2026-07-05T00:00:00.000Z"),
+ at(requestBegin(), "2026-07-05T00:00:01.000Z"),
+ at(assistantText("A"), "2026-07-05T00:00:02.500Z"),
+ at(tokenUsage(out(600), out(600)), "2026-07-05T00:00:02.900Z"),
+ at(requestEnd("completed"), "2026-07-05T00:00:03.000Z"),
+ at(
+ compactionBegin({ reason: "context", mode: "summarize", context: 600, turns: 1 }),
+ "2026-07-05T00:00:04.000Z",
+ ),
+ ]);
+
+ // Already in place while the compaction is still running — no later reordering.
+ expect(items(m).map((i) => i.kind)).toEqual([
+ "user_text",
+ "assistant_text",
+ "task_stats",
+ "compaction",
+ ]);
+ expect((items(m)[3] as CompactionItem).running).toBe(true);
+ expect((items(m)[2] as TaskStatsItem).stats!.elapsedDeltaMs).toBe(3_000);
+
+ // Finishing the compaction adds nothing and moves nothing.
+ pushMessage(
+ m,
+ at(
+ compactionEnd({ reason: "context", mode: "summarize", status: "completed" }),
+ "2026-07-05T00:00:24.000Z",
+ ),
+ );
+ finalizeHistory(m);
+ expect(items(m).map((i) => i.kind)).toEqual([
+ "user_text",
+ "assistant_text",
+ "task_stats",
+ "compaction",
+ ]);
+ });
+
+ it("a compaction after tool outputs is mid-Task: the round stays open and keeps one ledger, at the end", () => {
+ // The counter-case for the rule above: this turn owes the model its tool results, so the
+ // Task continues after the compaction and its row must not be settled early.
+ const m = createStreamModel();
+ pushMessages(m, [
+ at(userText("Q"), "2026-07-05T00:00:00.000Z"),
+ at(requestBegin(), "2026-07-05T00:00:01.000Z"),
+ at(toolCall({ name: "exec", arguments: "{}", toolCallId: "t1" }), "2026-07-05T00:00:02.000Z"),
+ at(tokenUsage(out(100), out(100)), "2026-07-05T00:00:02.500Z"),
+ at(requestEnd("completed"), "2026-07-05T00:00:03.000Z"),
+ at(toolCallOutput({ output: "ok", toolCallId: "t1" }), "2026-07-05T00:00:04.000Z"),
+ at(
+ compactionBegin({ reason: "context", mode: "summarize", context: 100, turns: 1 }),
+ "2026-07-05T00:00:05.000Z",
+ ),
+ ]);
+ // No ledger yet: the round is still working.
+ expect(items(m).filter((i) => i.kind === "task_stats")).toHaveLength(0);
+
+ pushMessages(m, [
+ at(
+ compactionEnd({ reason: "context", mode: "summarize", status: "completed" }),
+ "2026-07-05T00:00:06.000Z",
+ ),
+ at(requestBegin(), "2026-07-05T00:00:07.000Z"),
+ at(assistantText("done"), "2026-07-05T00:00:08.000Z"),
+ at(tokenUsage(out(200), out(200)), "2026-07-05T00:00:08.500Z"),
+ at(requestEnd("completed"), "2026-07-05T00:00:09.000Z"),
+ ]);
+ finalizeHistory(m);
+ expect(items(m).map((i) => i.kind)).toEqual([
+ "user_text",
+ "tool_call",
+ "compaction",
+ "assistant_text",
+ "task_stats",
+ ]);
+ });
+
+ it("steering delivered during a wrap-up compaction opens the continuation's own round", () => {
+ // The one way a Task outlives a wrap-up compaction: steering queued while it ran is
+ // delivered afterwards and the loop keeps going. The settled row stands, and the
+ // continuation gets a ledger of its own rather than a reply with no footer.
+ const m = createStreamModel();
+ pushMessages(m, [
+ at(userText("Q"), "2026-07-05T00:00:00.000Z"),
+ at(requestBegin(), "2026-07-05T00:00:01.000Z"),
+ at(assistantText("A"), "2026-07-05T00:00:02.000Z"),
+ at(tokenUsage(out(600), out(600)), "2026-07-05T00:00:02.500Z"),
+ at(requestEnd("completed"), "2026-07-05T00:00:03.000Z"),
+ at(
+ compactionBegin({ reason: "context", mode: "summarize", context: 600, turns: 1 }),
+ "2026-07-05T00:00:04.000Z",
+ ),
+ at(
+ compactionEnd({ reason: "context", mode: "summarize", status: "completed" }),
+ "2026-07-05T00:00:20.000Z",
+ ),
+ at(userText("[context_summary]\nsummary\n[/context_summary]"), "2026-07-05T00:00:21.000Z"),
+ at(
+ userText("[user_steering]\nalso check the tests\n[/user_steering]"),
+ "2026-07-05T00:00:22.000Z",
+ ),
+ at(requestBegin(), "2026-07-05T00:00:23.000Z"),
+ at(assistantText("checked"), "2026-07-05T00:00:24.000Z"),
+ at(tokenUsage(out(100), out(700)), "2026-07-05T00:00:24.500Z"),
+ at(requestEnd("completed"), "2026-07-05T00:00:25.000Z"),
+ ]);
+ finalizeHistory(m);
+
+ expect(items(m).map((i) => i.kind)).toEqual([
+ "user_text",
+ "assistant_text",
+ "task_stats",
+ "compaction",
+ "user_steering",
+ "assistant_text",
+ "task_stats",
+ ]);
+ const rows = items(m).filter((i) => i.kind === "task_stats") as TaskStatsItem[];
+ // The first round's ledger stops at its own request_end; the continuation measures from
+ // the steering that started it.
+ expect(rows[0]!.stats!.elapsedDeltaMs).toBe(3_000);
+ expect(rows[1]!.stats!.elapsedDeltaMs).toBe(3_000);
+ expect(rows[1]!.assistantText).toBe("checked");
+ });
+
it("**mid-round** compaction: inside the round's span, both elapsed time and Tokens count toward the round", () => {
// After compaction, the engine keeps running with the carry-over, and this round still has a
// normal Request after compaction — so compaction sits between two of this round's