A local-first multi-agent app development platform, built on PenguinHarness
feat: background completion reports steer into the running task (#407)
Yaowei Zheng4cfaccb9454d
diff --git a/changelog/unreleased/2026-08-23-steered-background-notices.md b/changelog/unreleased/2026-08-23-steered-background-notices.mdnew file mode 100644index 00000000..0bab3040--- /dev/null+++ b/changelog/unreleased/2026-08-23-steered-background-notices.md@@ -0,0 +1,19 @@+# Background completion reports steer into the running task++- **Date:** 2026-08-23+- **Type:** feature+- **Scope:** `core`, `server`, `web`+- **PR:** [#407](https://github.com/Prism-Shadow/penguin-harness/pull/407)++[中文版](2026-08-23-steered-background-notices.zh.md)++Normalized how `run_in_background` completion reports reach the conversation. When the agent loop is running, the report is injected at the next input-assembly boundary — the same mechanism as mid-run steering — and now records that fact on the wire: the `[background_task_done]` block carries a `delivery: steering` field line, stamped at delivery time. A report delivered while the session sat idle stays a task's own starting input and carries no stamp. The two deliveries are positionally identical in the Trace (both sit between a `request_end` and the next `request_begin`), so the recorded stamp is what lets every render and stats layer tell "inside the same turn" from "an independent turn".++## Details++- Core's Session now queues raw completion events and builds the harness user message at the consuming end: the engine's mid-run drain stamps `delivery: steering`, the host's idle take leaves the field off. `parseBackgroundTaskDoneMessage` reads the field back, and a shared `isSteeredBackgroundNotice` predicate serves every turn-segmentation implementation.+- All four "what is one turn" implementations treat a steered report like steering — inside the current turn, never starting a new one: the chat stream reducer gives it a dedicated `background_notice` item (rendered as the same collapsible completion banner, now in-flow), the conversation outline opens no entry for it, the server's message-window scanner neither cuts a window nor counts a turn at it (`CACHE_VERSION` bumped to 2 — cached page stats recompute on first read), and trace analysis merges the continuation request into the current round on the trajectories page, with the injected message's timestamp excluded from the round's duration. The session-fork cut point applies the same exemption.+- The per-turn statistics row no longer appears mid-task at the injection point: it still arrives exactly once, when the whole task ends. A steered report that continues a task past a wrap-up compaction reopens the continuation's own round, exactly as a steering chip does.+- Reports drained at a run's start ride behind the fresh prompt inside that prompt's turn: the injection forces a continuation only when delivered in the gap between two requests, so a ride-along report can no longer merge the new turn into the previous one. With the same rule, a steering message or steered report delivered right after a completed mid-task compaction now opens the continuation's own round on the trajectories page instead of being folded into the compaction round.+- Idle-delivered reports keep their documented behavior — an independent round on every surface. Their outline entry is now titled by the readable report body instead of the raw marker block, and completion reports (either delivery) no longer enter the composer's input history: they are harness-written, not something the user typed.+- Legacy Traces (recorded before the stamp existed) get a positional fallback: a stamp-less report sitting between a turn's paired tool outputs and the continuation request is provably in-task — a task can never end in that gap — so the chat reducer, the message-window scanner and trace analysis all treat it as injected, keeping the four turn implementations in agreement on old data. A stamp-less report after a no-tool turn keeps its independent round (there an idle launch is genuinely possible, and only the stamp — written by new cores — can tell the two apart). The extra field line is ignored by older parsers.diff --git a/changelog/unreleased/2026-08-23-steered-background-notices.zh.md b/changelog/unreleased/2026-08-23-steered-background-notices.zh.mdnew file mode 100644index 00000000..baea13ff--- /dev/null+++ b/changelog/unreleased/2026-08-23-steered-background-notices.zh.md@@ -0,0 +1,19 @@+# 后台完成回报以 steering 注入运行中任务++- **Date:** 2026-08-23+- **Type:** feature+- **Scope:** `core`, `server`, `web`+- **PR:** [#407](https://github.com/Prism-Shadow/penguin-harness/pull/407)++[English](2026-08-23-steered-background-notices.md)++规范了 `run_in_background` 完成回报进入对话的方式。前台 agent loop 运行中时,回报在下一次输入组装边界注入——与运行中 steering 同一机制——并且这一事实现在落在线上:`[background_task_done]` 块携带 `delivery: steering` 字段行,于投递时打上。会话空闲时投递的回报仍是新任务自己的起始输入,不带该标记。两种投递在轨迹里位置同构(都落在 `request_end` 与下一个 `request_begin` 之间),因此各渲染层与统计层区分「同一轮之内」与「独立一轮」的依据就是这枚落盘标记。++## 细节++- core 的 Session 改为排队原始完成事件,由消费端构建 harness user 消息:引擎的运行中排空打上 `delivery: steering`,宿主的空闲取走不带该字段。`parseBackgroundTaskDoneMessage` 读回该字段,共享判定 `isSteeredBackgroundNotice` 供各处轮次切分实现取用。+- 四处「什么是一轮」的实现一致把 steered 回报按 steering 对待——留在当前轮之内、绝不开新轮:聊天流 reducer 给它专属的 `background_notice` 条目(仍渲染为同款可折叠完成横幅,只是随流内嵌),对话索引不为它开条目,服务端窗口扫描器在它处既不切窗口也不计轮(`CACHE_VERSION` 升至 2——缓存的分页统计首次读取时重算),轨迹观测页的分析把续起的请求并入当前轮、注入消息的时间戳不参与该轮用时。会话 fork 的切点判定同样豁免。+- 逐轮统计行不再在注入点于任务中途出现:仍然只出现一次,在整个任务结束时。steered 回报使任务越过收尾压缩继续时,为续段开出自己的一轮,与 steering 插话完全同规。+- 运行起点排空的回报跟在新 Prompt 之后、属于该 Prompt 的一轮:注入只在两次请求之间的空档投递时才强制续轮,因此搭车投递的回报不再把新轮并进上一轮。同一规则下,紧随任务中途压缩完成之后投递的 steering 插话或 steered 回报,在轨迹观测页也改为开出续段自己的一轮,不再被并入压缩轮。+- 空闲投递的回报保持既有口径——在所有观测面独立一轮。其对话索引条目现在以可读的回报正文为题,不再是原始标记块;完成回报(两种投递)也不再进入输入区的输入历史:它们是 harness 写就的,不是用户键入的内容。+- 存量轨迹(打标之前记录)获得位置兜底:未打标的回报若落在本轮已配对工具输出与续起 Request 之间,凭位置即可证明在任务中——Task 不可能在这个空档结束——聊天 reducer、窗口扫描器与轨迹分析统一按注入处理,四处轮次实现对旧数据保持一致。无工具收尾之后的未打标回报保持独立一轮(那里空闲投递真实可能,只有新 core 写下的标记能区分两者)。新增字段行会被旧解析器忽略。diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.tsindex c12542d8..422614c3 100644--- a/packages/core/src/engine/context-engine.ts+++ b/packages/core/src/engine/context-engine.ts@@ -244,8 +244,11 @@ export interface ContextEngineDeps {* drains at every input-assembly point — run start included — yielding each message to the* output stream and writing it to Trace (like steering, this text never reached the* consumer any other way); `pending` is the boundary peek that keeps a discard/summary- * from ending the run while notices still wait. Absent = no notice source (tests,- * standalone embedders).+ * from ending the run while notices still wait. This drain IS the steering delivery path:+ * the source builds each message with `delivery: steering` on its block, marking it as+ * injected into an already-started Task rather than a task-starting input (only the host's+ * idle take produces the unstamped form). Absent = no notice source (tests, standalone+ * embedders).*/backgroundNotices?: { drain(): OmniMessage[]; pending(): number };}@@ -885,7 +888,11 @@ export class ContextEngine {// (harness user messages) and steering ([user_steering] user messages) ride alongside// this turn's tool outputs (or alone as the continuation input when the turn produced// no tool calls, instead of ending the Task — subject to the max-turns guard at the- // top of the loop). Notices first; the user's own words come last.+ // top of the loop). Notices first; the user's own words come last. The whole batch is+ // user-side and reaches AgentHub as ONE user message (streamGenerate merges a+ // request's input into a single UniMessage), so injections never put two adjacent+ // user messages on the wire — the per-message granularity exists only in the+ // OmniMessage stream and the Trace.const injected = [...(yield* this.deliverBackgroundNotices()),...(yield* this.deliverSteering()),diff --git a/packages/core/src/omnimessage/markers/index.ts b/packages/core/src/omnimessage/markers/index.tsindex 73eccd89..bc70cbc2 100644--- a/packages/core/src/omnimessage/markers/index.ts+++ b/packages/core/src/omnimessage/markers/index.ts@@ -24,6 +24,15 @@* dual-form (square + legacy angle) matching every parser applies, because markers persist in* Traces and in each agent's stored compaction prompt. `tags.ts` owns the tag list.*+ * **Consumption boundary**: marker text is addressed to the model and to the render /+ * observation layers (chat folding, the trace page, turn segmentation) — those may parse it+ * freely. Core's runtime path (engine, Session, LLM translation, resume replay) must never+ * parse marker text to tell where a message came from: source decisions there ride on+ * structured facts only — payload fields such as `sender`, and the explicit queue/state that+ * delivered the message — so core BUILDS markers but never branches on them. Transforming a+ * protocol block core itself authored (the goal-round downgrade, the compaction `[summary]`+ * extraction) is not source discrimination and stays legitimate.+ ** Everything here is pure string work: no OmniMessage envelopes, no I/O — the callers wrap* the result in `userText(...)` (or match against a payload's text) themselves.*/diff --git a/packages/core/src/omnimessage/markers/origin-blocks.ts b/packages/core/src/omnimessage/markers/origin-blocks.tsindex e540260f..4545ac3f 100644--- a/packages/core/src/omnimessage/markers/origin-blocks.ts+++ b/packages/core/src/omnimessage/markers/origin-blocks.ts@@ -296,6 +296,16 @@ export interface BackgroundTaskDone {status: "completed" | "failed";/** One-line terminal detail (exit code / signal / subagent note); empty when there is none. */detail: string;+ /**+ * How the notice reached the conversation. `"steering"` = the engine injected it into an+ * already-started Task at an input-assembly boundary (the steering delivery path — stamped+ * at delivery time, since a queued notice does not know yet which path will consume it);+ * absent = the notice IS a task's starting input (the host launched a task with it while+ * the session sat idle). The two deliveries are positionally identical in the Trace — both+ * sit between a `request_end` and the next `request_begin` — so this recorded field is the+ * only way render and stats layers can tell "same turn" from "independent turn".+ */+ delivery?: "steering";}/**@@ -315,6 +325,7 @@ export function buildBackgroundTaskDoneMessage(done: BackgroundTaskDone, body: s`id: ${done.id}`,`status: ${done.status}`,...(done.detail ? [`detail: ${done.detail}`] : []),+ ...(done.delivery ? [`delivery: ${done.delivery}`] : []),].join("\n"),);return body ? `${block}\n\n${body}` : block;@@ -336,16 +347,29 @@ export function parseBackgroundTaskDoneMessage(const m = matchDualForm(BACKGROUND_DONE_PATTERNS, text);if (!m || m.index !== 0) return null;const done: BackgroundTaskDone = { kind: "command", id: "", status: "completed", detail: "" };- for (const [key, value] of fieldLines(m[1]!, ["kind", "id", "status", "detail"])) {+ for (const [key, value] of fieldLines(m[1]!, ["kind", "id", "status", "detail", "delivery"])) {if (key === "kind" && (value === "command" || value === "subagent")) done.kind = value;else if (key === "id") done.id = value;else if (key === "status" && (value === "completed" || value === "failed")) done.status = value;else if (key === "detail") done.detail = value;+ else if (key === "delivery" && value === "steering") done.delivery = value;}if (!done.id) return null;return { done, rest: text.slice(m[0].length).replace(/^\n+/, "") };}+/**+ * Whether a user text is a background completion notice that was steered into a running Task+ * (`delivery: steering` on its `[background_task_done]` block). The shared predicate behind+ * every "what is one turn" implementation — the Web stream reducer, the outline, the server's+ * message-window scanner and trace analysis — which all must treat such a notice like+ * steering: inside the current Task, never starting a new one. A notice without the field is+ * a task's own starting input and keeps its independent turn.+ */+export function isSteeredBackgroundNotice(text: string): boolean {+ return parseBackgroundTaskDoneMessage(text)?.done.delivery === "steering";+}+// ---------------------------------------------------------------------------// Shared predicate over the whole-message origin blocks// ---------------------------------------------------------------------------diff --git a/packages/core/src/session.ts b/packages/core/src/session.tsindex ac0db942..d549cade 100644--- a/packages/core/src/session.ts+++ b/packages/core/src/session.ts@@ -179,8 +179,15 @@ const TITLE_ASSISTANT_MATERIAL_LIMIT = 1000;* `[background_task_done]` block carries the structured facts, the body the display text —* what settled, then the tail of its yet-undelivered output. `sender: "harness"` marks the* non-human origin in the Trace.+ *+ * Built at DELIVERY time, not queue time, because the message must record how it reached the+ * conversation and a queued event does not know that yet: the engine's mid-run drain stamps+ * `delivery: "steering"` (injected into an already-started Task — the render and stats layers+ * keep it inside that turn), while the host's idle take leaves the field off (the notice is+ * the new task's own starting input and keeps its independent turn). The two deliveries are+ * positionally identical in the Trace, so only this recorded stamp can tell them apart.*/-function backgroundDoneNotice(event: BackgroundTaskDoneEvent): OmniMessage {+function backgroundDoneNotice(event: BackgroundTaskDoneEvent, delivery?: "steering"): OmniMessage {const what = event.kind === "command" ? "Background command" : "Background subagent";const idField = event.kind === "command" ? "process_id" : "subagent_id";const verb = event.status === "completed" ? "finished" : "failed";@@ -189,7 +196,13 @@ function backgroundDoneNotice(event: BackgroundTaskDoneEvent): OmniMessage {const body = event.output.trim() ? `${head}\n\n${event.output}` : head;return userText(buildBackgroundTaskDoneMessage(- { kind: event.kind, id: event.id, status: event.status, detail: event.detail },+ {+ kind: event.kind,+ id: event.id,+ status: event.status,+ detail: event.detail,+ ...(delivery ? { delivery } : {}),+ },body,),"harness",@@ -271,14 +284,16 @@ export class Session {/** Material-frozen flag: becomes true once the first Task containing user text finishes; subsequent runs stop accumulating. */private titleMaterialFrozen = false;/**- * Background-task completion notices not yet delivered (harness user messages built from- * the Environment's completion events). Single source of truth for delivery: a running- * Task's engine drains it at every input-assembly boundary (yield + Trace write + request- * input); an idle Session fires `noticeListener` so the host can take the queue- * (`takeBackgroundNotices`) and submit it as an ordinary task — whichever consumes first,- * each notice is delivered exactly once. With neither, the next run's start drains it.+ * Background-task completion events not yet delivered. Single source of truth for+ * delivery: a running Task's engine drains it at every input-assembly boundary (yield ++ * Trace write + request input); an idle Session fires `noticeListener` so the host can+ * take the queue (`takeBackgroundNotices`) and submit it as an ordinary task — whichever+ * consumes first, each notice is delivered exactly once. With neither, the next run's+ * start drains it. The queue holds raw EVENTS: the harness user message is built by the+ * consuming path, which is when the delivery mode is known (see backgroundDoneNotice —+ * the engine drain stamps `delivery: steering`, the host take does not).*/- private pendingNotices: OmniMessage[] = [];+ private pendingNotices: BackgroundTaskDoneEvent[] = [];/** Idle-arrival signal for the host (see `onBackgroundNotice`); null until a host subscribes. */private noticeListener: (() => void) | null = null;/** Live background-subagent message subscriber (see `onBackgroundMessage`); null until a host subscribes — messages are display copies and drop without one. */@@ -322,9 +337,11 @@ export class Session {...(config.modelHasVision ? {} : { foldInputImages: this.foldImages }),sessionMeta: this.meta,// Background completion notices: the engine pulls from the Session's queue at every- // input-assembly boundary (see pendingNotices for the exactly-once contract).+ // input-assembly boundary (see pendingNotices for the exactly-once contract). This is+ // the steering delivery path — the notice joins a Task that already exists — so the+ // built message carries the `delivery: steering` stamp.backgroundNotices: {- drain: () => this.pendingNotices.splice(0),+ drain: () => this.pendingNotices.splice(0).map((e) => backgroundDoneNotice(e, "steering")),pending: () => this.pendingNotices.length,},};@@ -783,9 +800,9 @@ export class Session {return this.environment.hasRunningBackgroundSubagents?.() ?? false;}- /** Queues a background completion event as a harness user notice; a running Task delivers it at the next boundary, otherwise the host is signaled (see pendingNotices). */+ /** Queues a background completion event; a running Task delivers it at the next boundary, otherwise the host is signaled (see pendingNotices). */private handleBackgroundDone(event: BackgroundTaskDoneEvent): void {- this.pendingNotices.push(backgroundDoneNotice(event));+ this.pendingNotices.push(event);if (!(this.engine?.isTaskRunning ?? false)) this.noticeListener?.();}@@ -802,11 +819,13 @@ export class Session {/*** Takes the queued background completion notices (harness user messages) for submission as- * a task's input. Empties the queue — the caller owns delivery of what it took; anything- * queued after this call is signaled/drained separately.+ * a task's input — the notices become that task's starting input, so they carry no+ * `delivery` stamp and keep their independent turn in every render layer. Empties the+ * queue — the caller owns delivery of what it took; anything queued after this call is+ * signaled/drained separately.*/takeBackgroundNotices(): OmniMessage[] {- return this.pendingNotices.splice(0);+ return this.pendingNotices.splice(0).map((e) => backgroundDoneNotice(e));}/** Whether completion notices are still queued (hosts use it to keep a Session's runtime entry alive until they are delivered). */diff --git a/packages/core/test/background-execution.test.ts b/packages/core/test/background-execution.test.tsindex f9df3794..764c28f7 100644--- a/packages/core/test/background-execution.test.ts+++ b/packages/core/test/background-execution.test.ts@@ -20,6 +20,7 @@ import {assistantText,buildBackgroundTaskDoneMessage,emptyTokenCounts,+ isSteeredBackgroundNotice,parseBackgroundTaskDoneMessage,partialText,stripLeadingMarkerBlocks,@@ -149,6 +150,24 @@ describe("[background_task_done] marker and the sender field", () => {expect(parseBackgroundTaskDoneMessage(bare)!.done.detail).toBe("");});+ it("stamps and parses the steering delivery field; unstamped blocks read as task input", () => {+ const steered = buildBackgroundTaskDoneMessage(+ { kind: "command", id: "proc-1", status: "completed", detail: "", delivery: "steering" },+ "body",+ );+ expect(parseBackgroundTaskDoneMessage(steered)!.done.delivery).toBe("steering");+ expect(isSteeredBackgroundNotice(steered)).toBe(true);+ // The unstamped form (idle delivery, and every pre-stamp Trace) has no delivery field.+ const plain = buildBackgroundTaskDoneMessage(+ { kind: "command", id: "proc-1", status: "completed", detail: "" },+ "body",+ );+ expect(plain).not.toContain("delivery:");+ expect(parseBackgroundTaskDoneMessage(plain)!.done.delivery).toBeUndefined();+ expect(isSteeredBackgroundNotice(plain)).toBe(false);+ expect(isSteeredBackgroundNotice("plain user text")).toBe(false);+ });+it("only parses as a leading block, and the title stripper removes it", () => {const block = buildBackgroundTaskDoneMessage({ kind: "command", id: "proc-1", status: "completed", detail: "" },@@ -622,6 +641,9 @@ describe("Session background notices", () => {expect(p.sender).toBe("harness");const parsed = parseBackgroundTaskDoneMessage(p.text);expect(parsed!.done).toMatchObject({ kind: "command", id: "proc-11aa22bb" });+ // The host take is the idle path: the notice is the new task's own starting input, so it+ // carries no delivery stamp and keeps its independent turn in every render layer.+ expect(parsed!.done.delivery).toBeUndefined();expect(parsed!.rest).toContain("`sleep 1`");expect(parsed!.rest).toContain("done!");// Taking empties the queue, and the pending flag (the host's eviction pin) tracks it.@@ -650,5 +672,8 @@ describe("Session background notices", () => {const texts = llm.inputs[0]!.map((m) => (m.payload as { text?: string }).text ?? "");expect(texts[0]).toBe("hi");expect(texts[1]).toContain("[background_task_done]");+ // Engine drains are the steering delivery path — the notice joined a Task the user's+ // prompt started, so it must carry the steering stamp and never open a turn of its own.+ expect(isSteeredBackgroundNotice(texts[1]!)).toBe(true);});});diff --git a/packages/core/test/llm.test.ts b/packages/core/test/llm.test.tsindex e5d04c92..1b7ab5f7 100644--- a/packages/core/test/llm.test.ts+++ b/packages/core/test/llm.test.ts@@ -40,12 +40,14 @@ import {} from "../src/llm/index.js";import {assistantText,+ buildBackgroundTaskDoneMessage,imageUrlMessage,inlineData,inlineThinking,thinkingMessage,toolCall,toolCallOutput,+ userSteeringText,userText,} from "../src/omnimessage/index.js";import type {@@ -154,6 +156,34 @@ describe("mergeOmniToUniMessage", () => {});});+ it("an injected request input (tool outputs + steered notice + steering) collapses into ONE user message", () => {+ // The engine's next-input assembly appends background notices and steering behind the+ // turn's tool outputs — several user-side OmniMessages. On the wire they must be a+ // single user UniMessage (content_items in input order): what AgentHub receives always+ // alternates user / assistant, and an injection can never produce two adjacent user+ // messages. The per-message granularity exists only at the OmniMessage/Trace layer.+ const notice = buildBackgroundTaskDoneMessage(+ {+ kind: "command",+ id: "proc-1",+ status: "completed",+ detail: "exit code 0",+ delivery: "steering",+ },+ "Background command finished",+ );+ const uni = mergeOmniToUniMessage([+ toolCallOutput({ output: "total 0", toolCallId: "call_1" }),+ userText(notice, "harness"),+ userText(userSteeringText("also check the tests")),+ ]);+ expect(uni.role).toBe("user");+ expect(uni.content_items.map((c) => c.type)).toEqual(["tool_result", "text", "text"]);+ const texts = uni.content_items.filter((c) => c.type === "text");+ expect((texts[0] as { text: string }).text).toBe(notice);+ expect((texts[1] as { text: string }).text).toContain("[user_steering]");+ });+it("throws on mixed roles", () => {expect(() => mergeOmniToUniMessage([userText("hi"), thinkingMessage("reasoning")])).toThrow(/mixed roles/,diff --git a/packages/server/src/services/message-window.ts b/packages/server/src/services/message-window.tsindex 30a127ea..d7d6d6ea 100644--- a/packages/server/src/services/message-window.ts+++ b/packages/server/src/services/message-window.ts@@ -38,6 +38,7 @@*/import { parseUserSteeringText } from "@prismshadow/penguin-core";import {+ parseBackgroundTaskDoneMessage,parseGoalMessage,parseHandoffMessage,parseModelSwitchMessage,@@ -45,7 +46,7 @@ import {import type { OmniMessage } from "@prismshadow/penguin-core";/** Bump when any counting/boundary rule changes: cached page_stats records with an older version are recomputed. */-export const CACHE_VERSION = 1;+export const CACHE_VERSION = 3;/** Cumulative totals at a point in the trace (all values are "before this point"). */export interface WindowPriorStats {@@ -74,6 +75,14 @@ interface TaskCarry {sawReply: boolean;/** Compaction usage held pending (committed to the Task by a later non-compaction request_end — mirrors task-stats.ts pendingCompaction*). */pendingCompactionUsage: boolean;+ /**+ * A tool output of the current turn has arrived and is still owed to the model (mirrors+ * StreamModel.turnToolOutputs: set by a complete tool_call_output, cleared when the next+ * request opens or a Task starts). A Task can never end in that window, so a background+ * completion notice landing there is in-task by position — the recognizer for notices+ * written by a pre-stamp core (see the user-text branch).+ */+ turnToolOutputs: boolean;}/** Full scanner state, serializable into a shard's cached prefix record. */@@ -105,6 +114,7 @@ export function initialScanState(): ScanState {sawUsage: false,sawReply: false,pendingCompactionUsage: false,+ turnToolOutputs: false,},compactionActive: false,steeringOpen: false,@@ -161,6 +171,7 @@ function startTask(state: ScanState, ms: number | null): void {t.sawUsage = false;t.sawReply = false;t.pendingCompactionUsage = false;+ t.turnToolOutputs = false;}/** A non-user item entered the stream: the user-item run breaks (buildOutline's lastWasUser = false). */@@ -253,6 +264,24 @@ export async function scanMessages(state.steeringOpen = true;continue;}+ // A background completion notice injected into the running Task rides inside it+ // like steering — a banner item, no Task start, no cut, no entry — but opens no+ // trailing-image window (notices carry none). Recognized by the delivery stamp,+ // or by POSITION for notices written by a pre-stamp core: a Task never ends while+ // this turn's tool outputs are still owed to the model (turnToolOutputs), so a+ // notice landing there is in-task even without the stamp — the same rule trace+ // analysis applies, and the same fallback the Web reducer applies (the two must+ // stay in step). An unstamped notice after a no-tool turn falls through to+ // onTaskStart: an idle-launched notice task keeps its independent turn.+ const notice = parseBackgroundTaskDoneMessage(text);+ if (+ notice !== null &&+ (notice.done.delivery === "steering" || state.task.turnToolOutputs)+ ) {+ touchTask(state, ms);+ breakRuns(state);+ continue;+ }onTaskStart(state, ms, outlineEligibleText(text), (stats) => onBoundary(i, stats));continue;}@@ -284,7 +313,14 @@ export async function scanMessages(breakRuns(state);continue;}- // tool_call_output updates an existing card (no new item); inline_* render nothing.+ if (p.type === "tool_call_output") {+ // Updates an existing card (no new item); the turn now owes the model its results+ // — the window a positionally-recognized notice keys on (see turnToolOutputs).+ touchTask(state, ms);+ state.task.turnToolOutputs = true;+ continue;+ }+ // inline_* render nothing.touchTask(state, ms);continue;}@@ -350,7 +386,14 @@ export async function scanMessages(}continue;}- // approval_decision / request_begin / unexpanded pointers: no items, no run change.+ if (t === "request_begin") {+ // No item, no run change — but a new request means the previous turn's tool+ // outputs have been sent with it (mirrors stream-model's request_begin reset;+ // compaction requests don't consume the pending turn state).+ if (!state.compactionActive) state.task.turnToolOutputs = false;+ continue;+ }+ // approval_decision / unexpanded pointers: no items, no run change.continue;}// session_meta: no item (steering window already closed above).diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.tsindex 084d93f0..7a1117b8 100644--- a/packages/server/src/services/trace-service.ts+++ b/packages/server/src/services/trace-service.ts@@ -17,9 +17,11 @@ import {attachedFileLine,attachedImageLine,isSessionMeta,+ isSteeredBackgroundNotice,matchAttachedFileLine,matchAttachedImageLine,modelVisiblePath,+ parseBackgroundTaskDoneMessage,parseTraceLines,parseUserSteeringText,readTraceTolerant,@@ -103,6 +105,9 @@ function isTaskStartingUser(msg: OmniMessage): boolean {if (p.type === "image_url") return true;if (p.type !== "text" || p.role !== "user" || typeof p.text !== "string") return false;if (parseUserSteeringText(p.text) !== null) return false;+ // A steered background notice rides inside the running Task exactly like steering; only+ // the unstamped form (an idle-launched notice task's own input) starts a Task.+ if (isSteeredBackgroundNotice(p.text)) return false;return !p.text.startsWith("[context_summary]") && !p.text.startsWith("<context_summary>");}@@ -913,14 +918,32 @@ export class TraceService {// running Task): never a turn starter — same exclusion idea as the compaction summary —// and it forces the next request to be a continuation (a steering-only continuation// turn has no preceding tool call, but it is still the same Task).- const isSteeringText =+ const isMainUserText =!hasOrigin &&msg.type === "model_msg" &&p.type === "text" &&p.role === "user" &&- typeof p.text === "string" &&- parseUserSteeringText(p.text) !== null;- if (isSteeringText) continuation = true;+ typeof p.text === "string";+ const isSteeringText = isMainUserText && parseUserSteeringText(p.text as string) !== null;+ // A background completion notice injected into the running Task gets the same+ // treatment as steering. Recognized by the delivery stamp (`delivery: steering` on+ // its block), or by POSITION for notices written by a pre-stamp core: a Task never+ // ends while the just-ended request's tool calls still await their continuation+ // (sawToolCallThisRequest — the same fact that forces the continuation below), so a+ // notice landing in that gap is in-task even without the stamp. The Web reducer and+ // the message-window scanner apply the identical fallback — the four turn+ // implementations must agree on legacy data too. An unstamped notice after a+ // no-tool turn keeps its independent turn: there an idle launch is genuinely+ // possible and only the stamp (written by new cores) can tell the two apart.+ const noticeParsed = isMainUserText ? parseBackgroundTaskDoneMessage(p.text as string) : null;+ const isInjectedNotice =+ noticeParsed !== null &&+ (noticeParsed.done.delivery === "steering" || sawToolCallThisRequest);+ // The continuation force only applies to a gap delivery (between two requests of the+ // running Task). A notice drained at run start rides behind a fresh user Prompt —+ // pendingFrom is then already open for the new turn, whose own `continuation = false`+ // must win, or the new turn would merge into the previous one.+ if ((isSteeringText || isInjectedNotice) && pendingFrom === null) continuation = true;// Images sent with a steering message ride immediately behind its text, exactly as a// Prompt's images ride behind theirs — and they inherit its exclusion: still the same// Task, so `steeringImages` keeps the window open across the whole run of them and@@ -936,6 +959,7 @@ export class TraceService {!hasOrigin &&!compactionActive &&!isSteeringText &&+ !isInjectedNotice &&!steeringImages &&msg.type === "model_msg" &&((p.type === "text" && p.role === "user") || p.type === "image_url");diff --git a/packages/server/test/messages-page.test.ts b/packages/server/test/messages-page.test.tsindex 356ffb1b..fe38adef 100644--- a/packages/server/test/messages-page.test.ts+++ b/packages/server/test/messages-page.test.ts@@ -29,7 +29,10 @@ import {toolCallOutput,userText,} from "@prismshadow/penguin-core";-import { buildHandoffMessage } from "@prismshadow/penguin-core/markers";+import {+ buildBackgroundTaskDoneMessage,+ buildHandoffMessage,+} from "@prismshadow/penguin-core/markers";import type { OmniMessage, SessionMetaPayload, TokenCounts } from "@prismshadow/penguin-core";import { decodeCursor, encodeCursor } from "../src/services/message-window.js";import type { TraceService } from "../src/services/trace-service.js";@@ -306,6 +309,93 @@ describe("messages windowed reads", () => {expect(userTexts(older.messages)).toEqual(["q1"]);});+ it("a steered background notice never cuts a window; an idle-launched notice cuts and counts a turn", async () => {+ // Twin of the trace-service and stream-model steered-notice cases: the four "what is one+ // turn" implementations must agree. The steered form (delivery: steering) stays inside+ // its unit; the unstamped form is a task's own input — a unit boundary AND an outline+ // entry (its question is the report body, so the entry is real).+ const steered = buildBackgroundTaskDoneMessage(+ {+ kind: "command",+ id: "proc-1",+ status: "completed",+ detail: "exit code 0",+ delivery: "steering",+ },+ "Background command finished",+ );+ const plain = buildBackgroundTaskDoneMessage(+ { kind: "command", id: "proc-2", status: "failed", detail: "exit code 1" },+ "Background command failed",+ );+ await writeTraceFile(root, P, A, "2026-07-20", S, 1, [+ sessionMeta(metaPayload()),+ ...turn(0, 1, 1000),+ // Turn 2: reply lands, then the steered notice continues the same Task with one more request.+ at("2026-07-20T10:01:00.000Z", userText("q2")),+ at("2026-07-20T10:01:01.000Z", requestBegin()),+ at("2026-07-20T10:01:02.000Z", assistantText("a2")),+ at("2026-07-20T10:01:03.000Z", requestEnd("completed")),+ at("2026-07-20T10:01:04.000Z", userText(steered, "harness")),+ at("2026-07-20T10:01:05.000Z", requestBegin()),+ at("2026-07-20T10:01:06.000Z", assistantText("noted the finish")),+ at("2026-07-20T10:01:07.000Z", requestEnd("completed")),+ at("2026-07-20T10:01:07.500Z", tokenUsage(counts(2000), counts(200))),+ // Turn 3: the idle-launched notice task.+ at("2026-07-20T10:02:00.000Z", userText(plain, "harness")),+ at("2026-07-20T10:02:01.000Z", requestBegin()),+ at("2026-07-20T10:02:02.000Z", assistantText("a3")),+ at("2026-07-20T10:02:03.000Z", requestEnd("completed")),+ at("2026-07-20T10:02:03.500Z", tokenUsage(counts(3000), counts(300))),+ ]);++ // The newest unit is the idle notice's own turn, with two entries (q1, q2) before it —+ // the steered notice opened neither a unit nor an entry.+ const tail = await service.readMessagesPage(P, A, S, { kind: "tail", limit: 1 });+ expect(userTexts(tail.messages)[0]).toContain("proc-2");+ expect(tail.prior.turns).toBe(2);+ // The previous window is the WHOLE second turn: the cut lands at q2, never at the+ // steered notice.+ const older = await service.readMessagesPage(P, A, S, {+ kind: "before",+ cursor: decodeCursor(tail.before!)!,+ limit: 1,+ });+ expect(userTexts(older.messages)[0]).toBe("q2");+ expect(userTexts(older.messages).some((t) => t.includes("proc-1"))).toBe(true);+ expect(older.prior.turns).toBe(1);+ });++ it("an UNSTAMPED notice in a tool-continuation gap neither cuts nor counts (pre-stamp traces)", async () => {+ // Legacy shape: no delivery stamp, but the notice sits between a turn's tool output and+ // the continuation request — in-task by position, mirroring the reducer and trace+ // analysis. The window must keep the whole turn together.+ const plain = buildBackgroundTaskDoneMessage(+ { kind: "command", id: "proc-9", status: "completed", detail: "exit code 0" },+ "Background command finished",+ );+ await writeTraceFile(root, P, A, "2026-07-20", S, 1, [+ sessionMeta(metaPayload()),+ ...turn(0, 1, 1000),+ at("2026-07-20T10:01:00.000Z", userText("q2")),+ at("2026-07-20T10:01:01.000Z", requestBegin()),+ at("2026-07-20T10:01:02.000Z", toolCall({ name: "exec", arguments: "{}", toolCallId: "t1" })),+ at("2026-07-20T10:01:03.000Z", requestEnd("completed")),+ at("2026-07-20T10:01:04.000Z", toolCallOutput({ output: "launched", toolCallId: "t1" })),+ at("2026-07-20T10:01:05.000Z", userText(plain, "harness")),+ at("2026-07-20T10:01:06.000Z", requestBegin()),+ at("2026-07-20T10:01:07.000Z", assistantText("done")),+ at("2026-07-20T10:01:08.000Z", requestEnd("completed")),+ at("2026-07-20T10:01:08.500Z", tokenUsage(counts(2000), counts(200))),+ ]);+ const tail = await service.readMessagesPage(P, A, S, { kind: "tail", limit: 1 });+ // The newest unit is the WHOLE second turn — the cut lands at q2, not at the notice —+ // and only q1 precedes it in the outline numbering.+ expect(userTexts(tail.messages)[0]).toBe("q2");+ expect(userTexts(tail.messages).some((t) => t.includes("proc-9"))).toBe(true);+ expect(tail.prior.turns).toBe(1);+ });+it("a text+images send is one unit and one outline turn; banner and goal-round prompts cut but never count", async () => {await writeTraceFile(root, P, A, "2026-07-20", S, 1, [sessionMeta(metaPayload()),diff --git a/packages/server/test/trace-service.test.ts b/packages/server/test/trace-service.test.tsindex 5e36d798..962900f5 100644--- a/packages/server/test/trace-service.test.ts+++ b/packages/server/test/trace-service.test.ts@@ -9,6 +9,7 @@ import {abortEvent,approvalDecision,assistantText,+ buildBackgroundTaskDoneMessage,compactionBegin,compactionEnd,imageUrlMessage,@@ -931,6 +932,111 @@ describe("trace-service", () => {});// The Web's live-stream twin of this case lives in stream-model.test.ts.+ it("Task grouping: a steered background notice stays in the same Task; an unstamped notice task keeps its own turn", async () => {+ const T = (sec: string) => `2026-07-05T10:05:${sec}Z`;+ const steered = buildBackgroundTaskDoneMessage(+ {+ kind: "command",+ id: "proc-1",+ status: "completed",+ detail: "exit code 0",+ delivery: "steering",+ },+ "Background command finished",+ );+ const plain = buildBackgroundTaskDoneMessage(+ { kind: "command", id: "proc-2", status: "failed", detail: "exit code 1" },+ "Background command failed",+ );+ await writeTraceFile(root, P, A, "2026-07-05", S, 14, [+ sessionMeta(metaPayload()),+ // Task 0: the reply round produced no tool call — the steered notice is exactly what+ // continues the loop, and it must not open a turn of its own.+ at(T("00.000"), userText("build it")),+ at(T("01.000"), requestBegin()),+ at(T("02.000"), assistantText("kicked off")),+ at(T("02.500"), requestEnd("completed")),+ at(T("08.000"), userText(steered, "harness")),+ at(T("08.500"), requestBegin()),+ at(T("09.000"), assistantText("finished cleanly")),+ at(T("09.500"), requestEnd("completed")),+ // Idle delivery later: the unstamped notice is a task's own input — independent turn.+ at(T("20.000"), userText(plain, "harness")),+ at(T("21.000"), requestBegin()),+ at(T("22.000"), assistantText("reacting to the failure")),+ at(T("22.500"), requestEnd("completed")),+ ]);+ const a = await service.analyze(P, A, S, 14);+ expect(a.requests.map((r) => r.taskIndex)).toEqual([0, 0, 1]);+ expect(a.tasks.map((t) => t.taskIndex)).toEqual([0, 1]);+ // Injected messages never move the duration start (first request_begin rule).+ expect(a.tasks[0]!.startTs).toBe(T("01.000"));+ expect(a.tasks[1]!.startTs).toBe(T("21.000"));+ });++ it("Task grouping: an UNSTAMPED notice in a tool-continuation gap merges too (pre-stamp traces)", async () => {+ // Legacy shape (0.2.4 core, no delivery stamp): the notice sits between a tool-calling+ // request and its continuation, where a Task cannot end — position alone proves it is+ // in-task, and the round must not split at it (the reducer and the window scanner apply+ // the identical fallback).+ const T = (sec: string) => `2026-07-05T10:07:${sec}Z`;+ const plain = buildBackgroundTaskDoneMessage(+ { kind: "command", id: "proc-4", status: "completed", detail: "exit code 0" },+ "Background command finished",+ );+ await writeTraceFile(root, P, A, "2026-07-05", S, 16, [+ sessionMeta(metaPayload()),+ at(T("00.000"), userText("build it")),+ at(T("01.000"), requestBegin()),+ at(T("02.000"), toolCall({ name: "exec_command", arguments: "{}", toolCallId: "t1" })),+ at(T("02.500"), requestEnd("completed")),+ at(T("03.000"), toolCallOutput({ output: "launched", toolCallId: "t1" })),+ at(T("08.000"), userText(plain, "harness")),+ at(T("08.500"), requestBegin()),+ at(T("09.000"), assistantText("finished cleanly")),+ at(T("09.500"), requestEnd("completed")),+ ]);+ const a = await service.analyze(P, A, S, 16);+ expect(a.requests.map((r) => r.taskIndex)).toEqual([0, 0]);+ expect(a.tasks.map((t) => t.taskIndex)).toEqual([0]);+ });++ it("Task grouping: a notice drained at run start rides behind the fresh Prompt without merging turns", async () => {+ // A notice queued while the session sat idle can be consumed by a user run's start+ // instead of the idle launcher: core writes it right after the Prompt, steering-stamped.+ // The Prompt's own continuation break must win — the new turn opens normally, with the+ // notice inside its span rather than gluing it onto the previous turn.+ const T = (sec: string) => `2026-07-05T10:06:${sec}Z`;+ const steered = buildBackgroundTaskDoneMessage(+ {+ kind: "command",+ id: "proc-3",+ status: "completed",+ detail: "exit code 0",+ delivery: "steering",+ },+ "Background command finished",+ );+ await writeTraceFile(root, P, A, "2026-07-05", S, 15, [+ sessionMeta(metaPayload()),+ at(T("00.000"), userText("q1")),+ at(T("01.000"), requestBegin()),+ at(T("02.000"), assistantText("a1")),+ at(T("02.500"), requestEnd("completed")),+ // The next send: Prompt, then the ride-along notice, then the request.+ at(T("10.000"), userText("q2")),+ at(T("10.100"), userText(steered, "harness")),+ at(T("11.000"), requestBegin()),+ at(T("12.000"), assistantText("a2")),+ at(T("12.500"), requestEnd("completed")),+ ]);+ const a = await service.analyze(P, A, S, 15);+ expect(a.requests.map((r) => r.taskIndex)).toEqual([0, 1]);+ expect(a.tasks.map((t) => t.taskIndex)).toEqual([0, 1]);+ // Both the Prompt and the ride-along notice belong to the second turn's span.+ expect(a.tasks[1]!.messageFrom).toBe(5);+ });+it("Task grouping: images sent with a steering message don't start a Task either (a Prompt's do)", async () => {const T = (sec: string) => `2026-07-05T10:04:${sec}Z`;await writeTraceFile(root, P, A, "2026-07-05", S, 13, [diff --git a/packages/web/src/features/chat/agent-topology.ts b/packages/web/src/features/chat/agent-topology.tsindex e519cb01..ee191993 100644--- a/packages/web/src/features/chat/agent-topology.ts+++ b/packages/web/src/features/chat/agent-topology.ts@@ -58,10 +58,12 @@ export interface TopologyNode {/*** Whether an item opens a new PANEL scope. The reducer's "starts a new Task" predicate- * (user_text/user_image), minus one exception: a `[background_task_done]` harness notice does- * start a chat Task (its auto-run answers it), but for the topology it belongs to the Task- * that launched the background work — slicing there would split a background subagent's spawn- * from its completion and reset the panel the moment the report lands.+ * (user_text/user_image), minus one exception: an idle-launched `[background_task_done]`+ * notice does start a chat Task (its auto-run answers it), but for the topology it belongs+ * to the Task that launched the background work — slicing there would split a background+ * subagent's spawn from its completion and reset the panel the moment the report lands. A+ * STEERED notice never gets here as user_text at all: the reducer gives it its own+ * `background_notice` kind, which starts nothing anywhere.*/function isScopeStart(item: ChatItem): boolean {if (item.kind === "user_image") return true;@@ -81,11 +83,13 @@ export function latestTaskStart(items: readonly ChatItem[]): number {}/**- * Task starts as the STREAM MODEL counts them — every user_text/user_image, notices included,- * so the number stays 1:1 with the reducer's own `startTask` calls. The header's cost tracker- * keys its Task-boundary fold on exactly that (see header-stats.ts): a notice-triggered task- * zeroes the model's per-Task usage buckets, so a count that skipped it would drop the finished- * Task's live cost without ever folding it into the settled base.+ * Task starts as the STREAM MODEL counts them — every user_text/user_image, idle-launched+ * notices included, so the number stays 1:1 with the reducer's own `startTask` calls (a+ * steered notice is a `background_notice` item, which the reducer never startTasks — so it+ * is rightly not counted here either). The header's cost tracker keys its Task-boundary fold+ * on exactly that (see header-stats.ts): a notice-triggered task zeroes the model's per-Task+ * usage buckets, so a count that skipped it would drop the finished Task's live cost without+ * ever folding it into the settled base.*/export function modelTaskStartCount(items: readonly ChatItem[]): number {let n = 0;@@ -208,7 +212,9 @@ const BG_SUBAGENT_LAUNCH_RE =function backgroundSubagentStates(slice: readonly ChatItem[]): Map<string, "running" | "done"> {const states = new Map<string, "running" | "done">();for (const item of slice) {- if (item.kind === "user_text") {+ // Both notice deliveries settle a handle: the steered form is its own item kind, the+ // idle-launched form arrives as ordinary user_text carrying the same block.+ if (item.kind === "user_text" || item.kind === "background_notice") {const done = parseBackgroundTaskDoneMessage(item.text);if (done !== null && done.done.kind === "subagent") states.set(done.done.id, "done");continue;diff --git a/packages/web/src/features/chat/input-history.ts b/packages/web/src/features/chat/input-history.tsindex fa15b936..8c89be45 100644--- a/packages/web/src/features/chat/input-history.ts+++ b/packages/web/src/features/chat/input-history.ts@@ -51,7 +51,9 @@ export function buildInputHistory(items: readonly ChatItem[]): string[] {for (const item of items) {if (item.kind === "user_text") {const parsed = parseUserMessageBody(item.text);- if (!parsed || parsed.scheduled) continue;+ // Background completion notices are harness-written, never typed here — recalling one+ // into the composer would resend a machine report as user input.+ if (!parsed || parsed.scheduled || parsed.backgroundDone) continue;if (parsed.goalRound !== undefined && parsed.goalRound > 1) continue;push(parsed.body);} else if (item.kind === "user_steering") {diff --git a/packages/web/src/features/chat/message-item.tsx b/packages/web/src/features/chat/message-item.tsxindex b669f517..1cdc90f3 100644--- a/packages/web/src/features/chat/message-item.tsx+++ b/packages/web/src/features/chat/message-item.tsx@@ -258,6 +258,15 @@ export function MessageItem({ item, ctx }: { item: ChatItem; ctx: StreamRenderCo</>);}+ case "background_notice": {+ // A background completion notice steered into the running Task (delivery: steering on+ // its block): the same collapsed banner as a task-starting notice, but the dedicated+ // item kind keeps it inside the running Task — no new turn, no outline entry, and the+ // stats row still arrives once, at task end.+ const done = parseBackgroundTaskDoneMessage(item.text);+ if (done) return <BackgroundDoneBanner done={done.done} body={done.rest} />;+ return null; // unreachable: the reducer only creates this kind from a parsed notice+ }case "user_steering": {// Mid-run steering ([user_steering]-wrapped user text delivered between turns): a// compact right-aligned user-styled chip inside the running Task's flow — visuallydiff --git a/packages/web/src/features/chat/user-message-body.ts b/packages/web/src/features/chat/user-message-body.tsindex 8ff521eb..9ec2a291 100644--- a/packages/web/src/features/chat/user-message-body.ts+++ b/packages/web/src/features/chat/user-message-body.ts@@ -6,6 +6,7 @@* moment a new protocol block is added — this module is the single non-rendering copy.*/import {+ parseBackgroundTaskDoneMessage,parseHandoffMessage,parseModelSwitchMessage,parseScheduledMessage,@@ -21,6 +22,12 @@ export interface UserMessageBody {goalRound?: number;/** True when the message was injected by a scheduled-task trigger rather than typed into the composer. */scheduled: boolean;+ /**+ * True when the message is a background completion notice ([background_task_done] block);+ * `body` is then the harness-written report text after the block — a readable outline+ * title for the notice's turn, but never something the user typed (input history skips it).+ */+ backgroundDone?: boolean;}/**@@ -30,6 +37,12 @@ export interface UserMessageBody {*/export function parseUserMessageBody(raw: string): UserMessageBody | null {if (parseHandoffMessage(raw) || parseModelSwitchMessage(raw)) return null;+ // Same position as MessageItem's chain: a completion notice renders as a banner and+ // carries no goal/scheduled/skills blocks — the report text is all there is.+ const backgroundDone = parseBackgroundTaskDoneMessage(raw);+ if (backgroundDone) {+ return { body: backgroundDone.rest.trim(), scheduled: false, backgroundDone: true };+ }const goal = parseGoalMessage(raw);const afterGoal = goal ? goal.rest : raw;const scheduled = parseScheduledMessage(afterGoal);diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.tsindex 7859c801..f053f2bd 100644--- a/packages/web/src/lib/omni/stream-model.ts+++ b/packages/web/src/lib/omni/stream-model.ts@@ -52,6 +52,7 @@import {isEventMessage,isPartialPayload,+ parseBackgroundTaskDoneMessage,parseUserSteeringText,} from "@prismshadow/penguin-core/omnimessage";import type {@@ -119,6 +120,24 @@ export interface UserSteeringItem {atMs?: number;}+/**+ * A background completion notice steered into the running Task (`delivery: steering` on its+ * `[background_task_done]` block — see core's Session notice queue): rendered as the+ * completion banner **inside** the running Task's flow, like a steering chip it never starts+ * a new Task — so the turn's stats row still arrives exactly once, at task end. An unstamped+ * notice (an idle-launched notice task's own input) stays an ordinary `user_text` item and+ * keeps its independent turn. `text` is the raw message text (block included): the renderer+ * and the topology's terminal-state scan both re-parse it, exactly as they do for the+ * unstamped form.+ */+export interface BackgroundNoticeItem {+ kind: "background_notice";+ id: number;+ text: string;+ /** Message timestamp (milliseconds): shown on footer hover. */+ atMs?: number;+}+export interface UserImageItem {kind: "user_image";id: number;@@ -345,6 +364,7 @@ export interface TaskStatsItem {export type ChatItem =| UserTextItem| UserSteeringItem+ | BackgroundNoticeItem| UserImageItem| AssistantTextItem| ThinkingItem@@ -1147,6 +1167,37 @@ function handleComplete(model.openSteering = item;return;}+ // A background completion notice ([background_task_done] block) injected into the+ // running Task: same exclusion as steering — rendered inside the Task as the+ // completion banner, never a Task starter, so no stats row is flushed at the+ // injection point. Two ways to recognize the injection:+ // - the delivery stamp (`delivery: steering`), written by the engine's drain;+ // - POSITION, for notices written by a pre-stamp core (0.2.4 traces): a Task can+ // never end between a turn's paired tool outputs and the continuation request,+ // so a notice arriving while this turn's tool outputs are still owed to the+ // model (turnToolOutputs) is provably in-task even without the stamp. This is+ // the same rule trace analysis has always applied (a tool-calling request+ // forces a continuation), so the two pages agree on legacy data.+ // An unstamped notice after a NO-tool final turn still falls through to the+ // user_text branch below: there an idle-launched notice task is genuinely possible+ // and position cannot tell the two apart — only the stamp can, and new cores write+ // it.+ const notice = parseBackgroundTaskDoneMessage(p.text);+ if (notice !== null && (notice.done.delivery === "steering" || model.turnToolOutputs)) {+ // A wrap-up compaction may have settled the round early; an injected notice is+ // exactly what keeps the Task going past it, so it opens the continuation's own+ // round rather than joining a closed one (same rule as the steering chip above).+ if (model.reopenTaskAtSteering && !model.taskOpen) startTask(model, timestamp, nowMs);+ touchTask(model, timestamp);+ const noticeMs = tsOf(timestamp);+ model.items.push({+ kind: "background_notice",+ id: nextId(model),+ text: p.text,+ ...(noticeMs !== undefined ? { atMs: noticeMs } : {}),+ });+ return;+ }// A complete text message on the main session's user side: starts a new Task.startTask(model, timestamp, nowMs);const atMs = tsOf(timestamp);diff --git a/packages/web/test/agent-topology.test.ts b/packages/web/test/agent-topology.test.tsindex cc5dc04c..fffd967d 100644--- a/packages/web/test/agent-topology.test.ts+++ b/packages/web/test/agent-topology.test.ts@@ -568,4 +568,37 @@ describe("background subagents in the topology", () => {// per-Task usage buckets), which is what the header's cost fold keys on.expect(modelTaskStartCount(m.items)).toBe(2);});++ it("a steered notice settles the child too, and counts as a task start nowhere", () => {+ const m = createStreamModel();+ pushMessage(m, userText("go"));+ spawnBackground(m, "t1", "session-child-55cc66dd", "subagent-55cc66dd");+ // The engine-injected form: delivery: steering on the block, arriving mid-run.+ pushMessage(+ m,+ userText(+ buildBackgroundTaskDoneMessage(+ {+ kind: "subagent",+ id: "subagent-55cc66dd",+ status: "completed",+ detail: "",+ delivery: "steering",+ },+ "Background subagent finished",+ ),+ "harness",+ ),+ );+ // The reducer keeps it inside the Task as its own item kind; the terminal-state scan+ // still reads the handle off it, so the node settles.+ expect(m.items.some((i) => i.kind === "background_notice")).toBe(true);+ const nodes = extractTopology(m, "root", false);+ expect(nodes).toHaveLength(2);+ expect(nodes[1]!.running).toBe(false);+ // Steered delivery starts nothing: not a panel scope, and not a reducer Task either —+ // modelTaskStartCount stays 1:1 with the reducer's startTask calls by not counting it.+ expect(taskStartCount(m.items)).toBe(1);+ expect(modelTaskStartCount(m.items)).toBe(1);+ });});diff --git a/packages/web/test/input-history.test.ts b/packages/web/test/input-history.test.tsindex 8d251da1..e29433ea 100644--- a/packages/web/test/input-history.test.ts+++ b/packages/web/test/input-history.test.ts@@ -7,7 +7,10 @@ import { describe, expect, it } from "vitest";import type { ChatItem } from "../src/lib/omni/stream-model";import { buildSkillsMessage } from "../src/features/chat/skill-use";import { handoffMessage } from "../src/features/chat/agent-handoff";-import { buildScheduledMessage } from "@prismshadow/penguin-core/markers";+import {+ buildBackgroundTaskDoneMessage,+ buildScheduledMessage,+} from "@prismshadow/penguin-core/markers";import {buildInputHistory,caretOnFirstLine,@@ -39,6 +42,14 @@ describe("buildInputHistory", () => {user(goalRound1),user(goalRound2),steering("please also check the tests"),+ // An idle-launched background completion notice arrives as user_text but is+ // harness-written — recalling it would resend a machine report as user input.+ user(+ buildBackgroundTaskDoneMessage(+ { kind: "command", id: "proc-1", status: "completed", detail: "exit code 0" },+ "Background command finished",+ ),+ ),user(buildSkillsMessage(["my-skill"], "with a skill")),user("first question"),];diff --git a/packages/web/test/outline-model.test.ts b/packages/web/test/outline-model.test.tsindex 29363601..a7c435e7 100644--- a/packages/web/test/outline-model.test.ts+++ b/packages/web/test/outline-model.test.ts@@ -6,7 +6,10 @@import { describe, expect, it } from "vitest";import type { ChatItem } from "../src/lib/omni/stream-model";import { handoffMessage } from "../src/features/chat/agent-handoff";-import { buildScheduledMessage } from "@prismshadow/penguin-core/markers";+import {+ buildBackgroundTaskDoneMessage,+ buildScheduledMessage,+} from "@prismshadow/penguin-core/markers";import {OUTLINE_MIN_TURNS,OUTLINE_WINDOW_AFTER,@@ -77,6 +80,43 @@ describe("buildOutline", () => {expect(outline[0]).toMatchObject({ question: "real question", answer: "answer" });});+ it("background notices: the steered item stays inside the turn, the idle-launched turn titles its entry with the report", () => {+ const report = "Background command finished: `sleep 5` (process_id proc-1) — exit code 0";+ const steered: ChatItem = {+ kind: "background_notice",+ id: nextId++,+ text: buildBackgroundTaskDoneMessage(+ {+ kind: "command",+ id: "proc-1",+ status: "completed",+ detail: "exit code 0",+ delivery: "steering",+ },+ report,+ ),+ };+ const items: ChatItem[] = [+ user("build it"),+ steered,+ assistant("it finished"),+ stats(),+ // The idle path: the notice arrives as ordinary user_text and opens its own entry —+ // titled by the harness report body, not the raw marker block.+ user(+ buildBackgroundTaskDoneMessage(+ { kind: "command", id: "proc-2", status: "completed", detail: "exit code 0" },+ report,+ ),+ ),+ assistant("reacted"),+ ];+ const outline = buildOutline(items);+ expect(outline).toHaveLength(2);+ expect(outline[0]).toMatchObject({ question: "build it", answer: "it finished" });+ expect(outline[1]).toMatchObject({ question: report, answer: "reacted" });+ });+it("keeps one entry per goal run (later rounds merge into round 1) and includes scheduled turns", () => {const round = (n: number) => `[goal]\nround: ${n}\nobjective: o\n[/goal]\ndo the thing`;const items: ChatItem[] = [diff --git a/packages/web/test/stream-model.test.ts b/packages/web/test/stream-model.test.tsindex dbd51cee..386e2fea 100644--- a/packages/web/test/stream-model.test.ts+++ b/packages/web/test/stream-model.test.ts@@ -8,6 +8,7 @@ import {abortEvent,approvalDecision,assistantText,+ buildBackgroundTaskDoneMessage,compactionBegin,compactionEnd,imageUrlMessage,@@ -50,6 +51,7 @@ import {import { liveSessionElapsedMs } from "../src/lib/omni/task-stats";import type {AssistantTextItem,+ BackgroundNoticeItem,CompactionItem,McpConnectItem,ReconnectItem,@@ -62,6 +64,20 @@ import type {UserTextItem,} from "../src/lib/omni/stream-model";+/** A completion notice as core delivers it: steered (engine drain) or unstamped (idle take). */+function noticeText(delivery?: "steering"): string {+ return buildBackgroundTaskDoneMessage(+ {+ kind: "command",+ id: "proc-11aa22bb",+ status: "completed",+ detail: "exit code 0",+ ...(delivery ? { delivery } : {}),+ },+ "Background command finished: `sleep 5` (process_id proc-11aa22bb) — exit code 0",+ );+}+/** Override a message timestamp (constructor defaults to the current time). */function at<M extends OmniMessage>(msg: M, ts: string): M {return { ...msg, timestamp: ts };@@ -1645,6 +1661,134 @@ describe("compaction-internal messages (#17: history rebuild aligned with the li});// The server's Trace twin of this case lives in trace-service.test.ts.+ it("a steered background notice (delivery: steering) rides inside the running Task — banner item, no new Task, one stats row", () => {+ // A run_in_background completion delivered while the loop runs: core stamps+ // `delivery: steering` on the block and the reducer must treat it like steering — the+ // round keeps going, and its ledger still lands exactly once, at task end.+ const m = createStreamModel();+ pushMessages(m, [+ at(userText("build it"), "2026-07-05T00:00:00.000Z"),+ at(requestBegin(), "2026-07-05T00:00:01.000Z"),+ at(assistantText("kicked off, waiting"), "2026-07-05T00:00:02.000Z"),+ at(tokenUsage(counts(100), counts(100)), "2026-07-05T00:00:02.500Z"),+ at(requestEnd("completed"), "2026-07-05T00:00:03.000Z"),+ at(userText(noticeText("steering"), "harness"), "2026-07-05T00:00:08.000Z"),+ at(requestBegin(), "2026-07-05T00:00:09.000Z"),+ at(assistantText("it finished cleanly"), "2026-07-05T00:00:10.000Z"),+ at(tokenUsage(counts(200), counts(100)), "2026-07-05T00:00:10.500Z"),+ at(requestEnd("completed"), "2026-07-05T00:00:11.000Z"),+ ]);+ finalizeHistory(m);+ // One Task: the notice is a banner item inside it, and only one stats row closes it.+ expect(items(m).map((i) => i.kind)).toEqual([+ "user_text",+ "assistant_text",+ "background_notice",+ "assistant_text",+ "task_stats",+ ]);+ // The item keeps the raw text: the renderer and the topology scan re-parse the block.+ const notice = items(m).find((i) => i.kind === "background_notice") as BackgroundNoticeItem;+ expect(notice.text).toContain("[background_task_done]");+ expect(notice.text).toContain("delivery: steering");+ });++ it("an UNSTAMPED notice landing while tool outputs are pending stays in-task (pre-stamp traces)", () => {+ // Legacy shape: a 0.2.4 core wrote no delivery stamp. A Task can never end between a+ // turn's paired tool outputs and the continuation request, so position alone proves the+ // notice is in-task — the reducer must not flush a mid-task stats row for it (the same+ // rule trace analysis applies via its tool-call continuation).+ const m = createStreamModel();+ pushMessages(m, [+ at(userText("build it"), "2026-07-05T00:00:00.000Z"),+ at(requestBegin(), "2026-07-05T00:00:01.000Z"),+ at(+ toolCall({ name: "exec_command", arguments: "{}", toolCallId: "t1" }),+ "2026-07-05T00:00:02.000Z",+ ),+ at(tokenUsage(counts(100), counts(100)), "2026-07-05T00:00:02.500Z"),+ at(requestEnd("completed"), "2026-07-05T00:00:03.000Z"),+ at(toolCallOutput({ output: "launched", toolCallId: "t1" }), "2026-07-05T00:00:04.000Z"),+ at(userText(noticeText(), "harness"), "2026-07-05T00:00:08.000Z"),+ at(requestBegin(), "2026-07-05T00:00:09.000Z"),+ at(assistantText("it finished cleanly"), "2026-07-05T00:00:10.000Z"),+ at(tokenUsage(counts(200), counts(100)), "2026-07-05T00:00:10.500Z"),+ at(requestEnd("completed"), "2026-07-05T00:00:11.000Z"),+ ]);+ finalizeHistory(m);+ expect(items(m).map((i) => i.kind)).toEqual([+ "user_text",+ "tool_call",+ "background_notice",+ "assistant_text",+ "task_stats",+ ]);+ });++ it("an unstamped completion notice (idle-launched notice task input) still starts its own Task", () => {+ // The idle path launches a task whose input IS the notice — no delivery stamp, and the+ // independent turn (its own stats row) is exactly the intended rendering.+ const m = createStreamModel();+ pushMessages(m, [+ at(userText("build it"), "2026-07-05T00:00:00.000Z"),+ at(assistantText("kicked off"), "2026-07-05T00:00:02.000Z"),+ at(tokenUsage(counts(100), counts(100)), "2026-07-05T00:00:02.500Z"),+ at(userText(noticeText(), "harness"), "2026-07-05T00:01:00.000Z"),+ at(assistantText("it finished cleanly"), "2026-07-05T00:01:02.000Z"),+ at(tokenUsage(counts(200), counts(100)), "2026-07-05T00:01:02.500Z"),+ ]);+ finalizeHistory(m);+ expect(items(m).map((i) => i.kind)).toEqual([+ "user_text",+ "assistant_text",+ "task_stats",+ "user_text",+ "assistant_text",+ "task_stats",+ ]);+ });++ it("a steered notice delivered during a wrap-up compaction reopens the continuation's own round", () => {+ // Notices drain before steering at the same boundary, so a notice alone can be what+ // keeps the Task going past a wrap-up compaction — same reopen rule as the steering chip.+ 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(noticeText("steering"), "harness"), "2026-07-05T00:00:22.000Z"),+ at(requestBegin(), "2026-07-05T00:00:23.000Z"),+ at(assistantText("noted"), "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",+ "background_notice",+ "assistant_text",+ "task_stats",+ ]);+ const rows = items(m).filter((i) => i.kind === "task_stats") as TaskStatsItem[];+ // The continuation's ledger measures from the notice that started it.+ expect(rows[1]!.stats!.elapsedDeltaMs).toBe(3_000);+ expect(rows[1]!.assistantText).toBe("noted");+ });+it("images sent with a steering message join its chip; a later standalone image still starts a Task", () => {// Core delivers a steering message's images as user image messages right behind its text.// They belong to that chip — no bubble of their own and, crucially, no new Task — while an