From f3f048c77e0b0e35192799b02d33364fd3bbd261 Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Thu, 19 Nov 2026 21:26:28 +0000 Subject: [PATCH 01/17] Mark Claude child-session assistant output as commentary at ingress Task tool (subagent) assistant messages and stream deltas arrived with no item phase, so when one was the last assistant text before the parent's result the projector selected it as the run's answer and it was sealed as an immutable Result. Mark such items phase=commentary so the projector keeps excluding them from answer selection while their text stays visible as progress on the run. --- src/adapters/claude.ts | 39 ++++++++-- test/fixtures/harness.mjs | 53 +++++++++++--- test/native-activity-ingress.test.ts | 104 +++++++++++++++++++++++++++ test/native-turn-recovery.test.ts | 80 +++++++++++++++++++++ 4 files changed, 261 insertions(+), 15 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index b7293039..6490a761 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -63,6 +63,10 @@ export class Claude extends DirectAdapter implements Adapter { private requests = new Map(); private session: string; private messageIds = new Map(); + // Assistant items established from child-session (Task tool) streams. + // Keyed by the item id, because a stream's id can switch before + // `message_start` arrives; every distinct id needs its own commentary item. + private childItems = new Set(); private interrupted = false; private active = false; private steering = new ClaudeSteering(); @@ -526,12 +530,24 @@ export class Claude extends DirectAdapter implements Adapter { if (this.messageIds.size > 128) this.messageIds.delete(this.messageIds.keys().next().value!); } - if (e.type === "content_block_delta" && e.delta.type === "text_delta") - this.emit({ - type: "delta", - id: this.messageIds.get(stream) ?? m.uuid, - text: e.delta.text, - }); + if (e.type === "content_block_delta" && e.delta.type === "text_delta") { + const id = this.messageIds.get(stream) ?? m.uuid; + // A child stream's deltas must never leave a phase-less assistant + // item the projector could pick as the run's answer. Establish the + // commentary item before the first delta so the projector merges the + // deltas into it and keeps the child's text as progress only. + if (m.parent_tool_use_id && !this.childItems.has(id)) { + this.childItems.add(id); + // Re-emitting a commentary item for an evicted id is idempotent. + if (this.childItems.size > 128) + this.childItems.delete(this.childItems.values().next().value!); + this.emit({ + type: "item", + item: { id, kind: "assistant", text: "", phase: "commentary" }, + }); + } + this.emit({ type: "delta", id, text: e.delta.text }); + } if ( e.type === "content_block_start" && e.content_block.type === "tool_use" @@ -561,7 +577,15 @@ export class Claude extends DirectAdapter implements Adapter { if (text) this.emit({ type: "item", - item: { id: m.message.id, kind: "assistant", text }, + item: { + id: m.message.id, + kind: "assistant", + text, + // A Task tool (subagent) session's assistant message must not + // become the parent run's answer; commentary keeps it visible + // as progress while the projector excludes it from selection. + ...(m.parent_tool_use_id ? { phase: "commentary" as const } : {}), + }, }); for (const b of content) if (b.type === "tool_use") { @@ -605,6 +629,7 @@ export class Claude extends DirectAdapter implements Adapter { if (this.steering.result()) return; this.active = false; this.messageIds.clear(); + this.childItems.clear(); for (const id of this.requests.keys()) this.emit({ type: "resolved", id }); this.requests.clear(); diff --git a/test/fixtures/harness.mjs b/test/fixtures/harness.mjs index 9cb54b75..c8e5ab0b 100755 --- a/test/fixtures/harness.mjs +++ b/test/fixtures/harness.mjs @@ -155,9 +155,45 @@ function finish(status = "completed", failure = "Fixture native turn failed") { type: "assistant", message: { id: active, - content: [{ type: "text", text: "Fixture done" }], + content: process.env.LOOP_TEST_CLAUDE_PARENT_BLANK + ? [] + : [{ type: "text", text: "Fixture done" }], }, }); + // Child-session (Task tool) output between the parent's final assistant + // message and the parent result. LOOP_TEST_CLAUDE_CHILD_TEXT also sends + // the full child assistant message; LOOP_TEST_CLAUDE_CHILD_DELTA_ONLY + // sends only the child stream, which can outlive its assistant message. + const childText = process.env.LOOP_TEST_CLAUDE_CHILD_TEXT; + const childDeltaOnly = process.env.LOOP_TEST_CLAUDE_CHILD_DELTA_ONLY; + if (childText || childDeltaOnly) { + const childId = "child-" + count; + const childParent = "task-" + count; + const text = childText || childDeltaOnly; + out({ + type: "stream_event", + parent_tool_use_id: childParent, + event: { type: "message_start", message: { id: childId } }, + }); + out({ + type: "stream_event", + parent_tool_use_id: childParent, + event: { + type: "content_block_delta", + delta: { type: "text_delta", text }, + }, + }); + if (childText) + out({ + type: "assistant", + parent_tool_use_id: childParent, + message: { + id: childId, + role: "assistant", + content: [{ type: "text", text: childText }], + }, + }); + } out({ type: "result", subtype: "success", @@ -789,13 +825,14 @@ if (kind !== "opencode") { type: "stream_event", event: { type: "message_start", message: { id: active } }, }); - out({ - type: "stream_event", - event: { - type: "content_block_delta", - delta: { type: "text_delta", text: "Fixture " }, - }, - }); + if (!process.env.LOOP_TEST_CLAUDE_PARENT_BLANK) + out({ + type: "stream_event", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: "Fixture " }, + }, + }); out({ type: "assistant", message: { diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index 27e7007a..6ec8be96 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -306,6 +306,110 @@ it("records Claude result usage including cached inputs, excluding foreign resul cache_read_tokens: 50, }); }); + +// The projector picks the last non-commentary assistant item with text as a +// completed run's answer (projectOutput), so child-session output must carry +// phase "commentary" at ingress to stay out of that selection. +const retainedAnswer = (live: Live) => + [...live.items.values()].findLast( + (i) => i.kind === "assistant" && i.phase !== "commentary" && i.text.trim(), + ); + +it("marks Claude child-session assistant messages as commentary so they cannot become the run's answer", () => { + const sessions = new NativeSessions(); + const run = turn("conv", "claude-child-commentary"); + const current = start(sessions, "claude-child-generation", run); + sessions.state.startTurn(current.live, run); + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-child-commentary", + }, + current.emit, + ) as any; + adapter.active = true; + const send = (m: any) => + adapter.message({ session_id: "claude-child-commentary", ...m }); + send({ + type: "assistant", + parent_tool_use_id: null, + message: { + id: "parent-msg", + role: "assistant", + content: [{ type: "text", text: "Parent final" }], + }, + }); + send({ + type: "assistant", + parent_tool_use_id: "task-1", + message: { + id: "child-msg", + role: "assistant", + content: [{ type: "text", text: "Child text" }], + }, + }); + // Parent-session items keep their exact shape; the child is commentary. + expect(current.live.items.get("parent-msg")).toEqual({ + id: "parent-msg", + kind: "assistant", + text: "Parent final", + }); + expect(current.live.items.get("child-msg")).toEqual({ + id: "child-msg", + kind: "assistant", + text: "Child text", + phase: "commentary", + }); + expect(retainedAnswer(current.live)?.id).toBe("parent-msg"); +}); + +it("establishes a commentary item before a child stream's first delta", () => { + const sessions = new NativeSessions(); + const run = turn("conv", "claude-child-delta"); + const current = start(sessions, "claude-child-delta-generation", run); + sessions.state.startTurn(current.live, run); + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-child-delta", + }, + current.emit, + ) as any; + adapter.active = true; + const send = (m: any) => + adapter.message({ session_id: "claude-child-delta", ...m }); + send({ + type: "stream_event", + parent_tool_use_id: "task-2", + event: { type: "message_start", message: { id: "child-stream" } }, + }); + send({ + type: "stream_event", + parent_tool_use_id: "task-2", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: "Child stream text" }, + }, + }); + // The delta merged into the commentary item the adapter established first; + // a turn ending here (no parent text) must not select the child stream. + expect(current.live.items.get("child-stream")).toEqual({ + id: "child-stream", + kind: "assistant", + text: "Child stream text", + phase: "commentary", + }); + expect(retainedAnswer(current.live)).toBeUndefined(); +}); + const option = (id: string, confirmed: string) => ({ id, label: id, diff --git a/test/native-turn-recovery.test.ts b/test/native-turn-recovery.test.ts index 8ebad8a9..fbb55e3b 100644 --- a/test/native-turn-recovery.test.ts +++ b/test/native-turn-recovery.test.ts @@ -26,6 +26,8 @@ seedAgent(db, { const { enqueue } = await import("../src/server/queue"); const { tick, execute } = await import("../src/server/worker"); const { nativeSessions } = await import("../src/server/native-sessions"); +const { publishCompletedRunResult } = + await import("../src/server/result-publication"); for (const harness of ["claude", "codex"]) { db.prepare("INSERT INTO harnesses VALUES(?,?,'{}','{}','[]',0)").run( harness, @@ -51,6 +53,9 @@ for (const harness of ["claude", "codex"]) { afterEach(() => { delete process.env.LOOP_TEST_HARNESS; delete process.env.LOOP_TEST_CLAUDE_INJECTED_RESULTS; + delete process.env.LOOP_TEST_CLAUDE_CHILD_TEXT; + delete process.env.LOOP_TEST_CLAUDE_CHILD_DELTA_ONLY; + delete process.env.LOOP_TEST_CLAUDE_PARENT_BLANK; delete process.env.LOOP_TEST_CODEX_WRITER_BUSY; delete process.env.LOOP_TEST_AUDIT; }); @@ -130,6 +135,81 @@ it("keeps the user run open across injected Claude results and saves its actual expect(readFileSync(audit, "utf8")).toBe("prompt\n"); }); +// Child-session (Task tool) assistant output arrives between the parent's +// final assistant message and the parent `result`. It must stay visible as +// progress but never become the run's answer or the sealed Result body. +function sealedBody(runId: string) { + return publishCompletedRunResult(runId, "local-workspace", db)!.outcome.body; +} +function progressContent(runId: string, key: string) { + return ( + db + .prepare("SELECT content FROM messages WHERE run_id=? AND update_key=?") + .get(runId, key) as { content: string } | undefined + )?.content; +} + +it("seals the parent's text as the answer when a child assistant message follows it", async () => { + process.env.LOOP_TEST_HARNESS = "claude"; + process.env.LOOP_TEST_CLAUDE_CHILD_TEXT = "Subagent result text"; + const run = submit("claude-child-answer", "claude", "claude-child-answer"); + expect(await tick(execute)).toBe(true); + expect( + db.prepare("SELECT state,result,error FROM runs WHERE id=?").get(run.id), + ).toEqual({ state: "completed", result: "Fixture done", error: null }); + expect(sealedBody(run.id)).toBe("Fixture done"); + // The child's text is still recorded as a progress update on the run. + expect(progressContent(run.id, "native-message:child-1")).toBe( + "Subagent result text", + ); +}); + +it("does not seal child stream deltas when the child assistant message never arrives", async () => { + process.env.LOOP_TEST_HARNESS = "claude"; + process.env.LOOP_TEST_CLAUDE_CHILD_DELTA_ONLY = "Subagent stream text"; + const run = submit( + "claude-child-delta-only", + "claude", + "claude-child-delta-only", + ); + expect(await tick(execute)).toBe(true); + expect( + db.prepare("SELECT state,result,error FROM runs WHERE id=?").get(run.id), + ).toEqual({ state: "completed", result: "Fixture done", error: null }); + expect(sealedBody(run.id)).toBe("Fixture done"); + // The child stream's deltas still surface as progress on the run. + expect(progressContent(run.id, "native-message:child-1")).toBe( + "Subagent stream text", + ); +}); + +it("seals no result when the parent's final message has no text and only a child message does", async () => { + process.env.LOOP_TEST_HARNESS = "claude"; + process.env.LOOP_TEST_CLAUDE_PARENT_BLANK = "1"; + process.env.LOOP_TEST_CLAUDE_CHILD_TEXT = "Only the subagent speaks"; + const run = submit("claude-child-blank", "claude", "claude-child-blank"); + expect(await tick(execute)).toBe(true); + // No parent text is eligible, so the run's answer is empty and nothing is + // sealed from the child's text. + expect( + db.prepare("SELECT state,result FROM runs WHERE id=?").get(run.id), + ).toEqual({ + state: "completed", + result: "", + }); + expect(publishCompletedRunResult(run.id, "local-workspace", db)).toBeNull(); +}); + +it("keeps the same answer for a Claude turn without child sessions", async () => { + process.env.LOOP_TEST_HARNESS = "claude"; + const run = submit("claude-plain", "claude", "claude-plain"); + expect(await tick(execute)).toBe(true); + expect( + db.prepare("SELECT state,result,error FROM runs WHERE id=?").get(run.id), + ).toEqual({ state: "completed", result: "Fixture done", error: null }); + expect(sealedBody(run.id)).toBe("Fixture done"); +}); + it("reports a Codex writer conflict without dispatch, takeover or raw native error disclosure", async () => { process.env.LOOP_TEST_HARNESS = "codex"; process.env.LOOP_TEST_CODEX_WRITER_BUSY = "1"; From 86986ae66cc9b061e63323717b28ab15982d7d43 Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:36:25 +0000 Subject: [PATCH 02/17] Never re-establish a child commentary item that would overwrite text The first delta of a child stream establishes an empty commentary item so the projector merges deltas into it, but the projector replaces an item by id. If the full child assistant message arrived first (or the id was known from an earlier emit), re-establishing an empty item discarded the child's saved text. Remember every emitted child item id so a later delta merges into the existing item, establish only while a user turn is open so post-result deltas cannot clobber saved native history, and drop the eviction cap that could recreate the overwrite for resumed streams. Fixes the review finding on the first revision. --- src/adapters/claude.ts | 22 +++++++----- test/native-activity-ingress.test.ts | 53 ++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 8 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index 6490a761..d4db8290 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -63,9 +63,11 @@ export class Claude extends DirectAdapter implements Adapter { private requests = new Map(); private session: string; private messageIds = new Map(); - // Assistant items established from child-session (Task tool) streams. + // Assistant item ids already emitted for child-session (Task tool) streams. // Keyed by the item id, because a stream's id can switch before - // `message_start` arrives; every distinct id needs its own commentary item. + // `message_start` arrives. An id already emitted must never be established + // again: the projector replaces an item by id, so an empty re-established + // item would overwrite the child's saved text. private childItems = new Set(); private interrupted = false; private active = false; @@ -535,12 +537,12 @@ export class Claude extends DirectAdapter implements Adapter { // A child stream's deltas must never leave a phase-less assistant // item the projector could pick as the run's answer. Establish the // commentary item before the first delta so the projector merges the - // deltas into it and keeps the child's text as progress only. - if (m.parent_tool_use_id && !this.childItems.has(id)) { + // deltas into it and keeps the child's text as progress only. Only + // while a user turn is open: after the result the projector drops + // deltas, so an empty item emitted then could only clobber saved + // native history. + if (m.parent_tool_use_id && this.active && !this.childItems.has(id)) { this.childItems.add(id); - // Re-emitting a commentary item for an evicted id is idempotent. - if (this.childItems.size > 128) - this.childItems.delete(this.childItems.values().next().value!); this.emit({ type: "item", item: { id, kind: "assistant", text: "", phase: "commentary" }, @@ -574,7 +576,10 @@ export class Claude extends DirectAdapter implements Adapter { .filter((b: any) => b.type === "text") .map((b: any) => b.text) .join("\n"); - if (text) + if (text) { + // Remember the emitted id so a later delta merges into this item + // instead of establishing an empty one that replaces its text. + if (m.parent_tool_use_id) this.childItems.add(m.message.id); this.emit({ type: "item", item: { @@ -587,6 +592,7 @@ export class Claude extends DirectAdapter implements Adapter { ...(m.parent_tool_use_id ? { phase: "commentary" as const } : {}), }, }); + } for (const b of content) if (b.type === "tool_use") { this.activityInputs.set(b.id, { name: b.name, input: b.input }); diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index 6ec8be96..9b5a1eae 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -410,6 +410,59 @@ it("establishes a commentary item before a child stream's first delta", () => { expect(retainedAnswer(current.live)).toBeUndefined(); }); +it("merges a child delta into an earlier child assistant message instead of replacing its text", () => { + const sessions = new NativeSessions(); + const run = turn("conv", "claude-child-late-delta"); + const current = start(sessions, "claude-child-late-delta-generation", run); + sessions.state.startTurn(current.live, run); + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-child-late-delta", + }, + current.emit, + ) as any; + adapter.active = true; + const send = (m: any) => + adapter.message({ session_id: "claude-child-late-delta", ...m }); + // Full child assistant message arrives first, then its stream's delta. + send({ + type: "assistant", + parent_tool_use_id: "task-3", + message: { + id: "child-late", + role: "assistant", + content: [{ type: "text", text: "Full child text" }], + }, + }); + send({ + type: "stream_event", + parent_tool_use_id: "task-3", + event: { type: "message_start", message: { id: "child-late" } }, + }); + send({ + type: "stream_event", + parent_tool_use_id: "task-3", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: " and more" }, + }, + }); + // The delta merged into the existing commentary item; the earlier text is + // not overwritten by an empty re-established item. + expect(current.live.items.get("child-late")).toEqual({ + id: "child-late", + kind: "assistant", + text: "Full child text and more", + phase: "commentary", + }); + expect(retainedAnswer(current.live)).toBeUndefined(); +}); + const option = (id: string, confirmed: string) => ({ id, label: id, From 2a2fc501b952beefc9b2cd771bb807f65f37fb18 Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Thu, 19 Nov 2026 22:55:48 +0000 Subject: [PATCH 03/17] Keep child commentary phase across turns; note the fallback SQL bound A child message received between turns added its id to the adapter's child id set, and the next turn cleared the projector's item window, so a delayed child delta for that id skipped the establishing emit and left a phase-less assistant fragment that could be selected as the new run's answer. Clear the child id set at the start of a new user turn (mid-turn steering prompt keeps it), so a delayed delta re-establishes its commentary item. The stored-history fallback in projectOutput already excludes commentary through assistantHistory's SQL; add a comment recording that invariant. --- src/adapters/claude.ts | 6 +++ src/server/native/projector.ts | 3 ++ test/native-activity-ingress.test.ts | 72 ++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index d4db8290..86b4d44f 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -305,6 +305,12 @@ export class Claude extends DirectAdapter implements Adapter { async prompt(text: string, beforeDispatch?: () => void) { beforeDispatch?.(); this.interrupted = false; + // A new user turn clears the previous turn's child ids so a delayed + // child delta re-establishes its commentary item in the fresh projector + // window instead of leaving a phase-less fragment. Mid-turn steering + // follow-ups also call prompt() while a turn is active; they must keep + // the ids so their deltas still merge into the open items. + if (!this.active) this.childItems.clear(); this.active = true; await this.native.write({ type: "user", diff --git a/src/server/native/projector.ts b/src/server/native/projector.ts index 88e0138f..02777324 100644 --- a/src/server/native/projector.ts +++ b/src/server/native/projector.ts @@ -536,6 +536,9 @@ export class NativeProjector { live.binding.conversation_id, run.id, ); + // assistantHistory's SQL excludes phase "commentary" (and this in-memory + // pass already excluded anything still in the window), so this fallback + // only ever sees evicted non-commentary assistant items. for (const row of stored) { const item = JSON.parse(row.item) as Item; // A pending in-memory replacement may have cleared this saved reply diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index 9b5a1eae..abd7d9d1 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -463,6 +463,78 @@ it("merges a child delta into an earlier child assistant message instead of repl expect(retainedAnswer(current.live)).toBeUndefined(); }); +it("keeps a delayed child stream delta commentary across turn boundaries", async () => { + const sessions = new NativeSessions(); + const first = turn("conv", "claude-cross-turn-1"); + const current = start(sessions, "claude-cross-turn-generation", first); + sessions.state.startTurn(current.live, first); + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-cross-turn", + }, + current.emit, + ) as any; + adapter.active = true; + adapter.native = { write: async () => undefined }; + const send = (m: any) => + adapter.message({ session_id: "claude-cross-turn", ...m }); + // Turn 1: the child session emits an assistant message, then the turn ends. + send({ + type: "assistant", + parent_tool_use_id: "task-1", + message: { + id: "child-cross", + role: "assistant", + content: [{ type: "text", text: "Child text one" }], + }, + }); + adapter.message({ + type: "result", + session_id: "claude-cross-turn", + is_error: false, + }); + // Between turns the child emits another assistant message for the stream. + send({ + type: "assistant", + parent_tool_use_id: "task-1", + message: { + id: "child-cross", + role: "assistant", + content: [{ type: "text", text: "Child text two" }], + }, + }); + // Turn 2 starts and the child stream's delayed delta finally arrives. + await adapter.prompt("next"); + sessions.state.startTurn(current.live, turn("conv", "claude-cross-turn-2")); + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { type: "message_start", message: { id: "child-cross" } }, + }); + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: " late" }, + }, + }); + // The fragment re-establishes a commentary item in the fresh window rather + // than a phase-less one that could become the new run's answer. + expect(current.live.items.get("child-cross")).toEqual({ + id: "child-cross", + kind: "assistant", + text: " late", + phase: "commentary", + }); + expect(retainedAnswer(current.live)).toBeUndefined(); +}); + const option = (id: string, confirmed: string) => ({ id, label: id, From 12f54e921c87e1ca805f4f612394e18f8efef0dc Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Thu, 19 Nov 2026 23:58:47 +0000 Subject: [PATCH 04/17] Seed a re-established child item with its known text The supervisor attaches the next run before prompt(); a delayed full child message arriving in that recall window records its id, and prompt() then clears the id set so a later delta re-establishes the commentary item. The empty re-established item replaced the retained text before the delta appended, so progress showed only the trailing fragment. Keep the last-known text per child id across prompt() (cleared with the id set at the result) and seed the re-established item with it, so the replacement is content-identical and the delta appends to the full text. --- src/adapters/claude.ts | 29 ++++++++++-- test/native-activity-ingress.test.ts | 71 ++++++++++++++++++++++++++-- 2 files changed, 92 insertions(+), 8 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index 86b4d44f..9bf7729f 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -67,8 +67,15 @@ export class Claude extends DirectAdapter implements Adapter { // Keyed by the item id, because a stream's id can switch before // `message_start` arrives. An id already emitted must never be established // again: the projector replaces an item by id, so an empty re-established - // item would overwrite the child's saved text. + // item would overwrite the child's saved text. Cleared at the result and + // again at the next new user turn, so a delayed delta re-establishes its + // commentary item in the fresh projector window. private childItems = new Set(); + // Last-known full text per child item id, from the child assistant message. + // Kept across prompt() (unlike childItems) so a re-established item in the + // fresh window carries the known text instead of replacing it with empty; + // cleared with childItems at the result, so it stays bounded per turn. + private childText = new Map(); private interrupted = false; private active = false; private steering = new ClaudeSteering(); @@ -551,7 +558,15 @@ export class Claude extends DirectAdapter implements Adapter { this.childItems.add(id); this.emit({ type: "item", - item: { id, kind: "assistant", text: "", phase: "commentary" }, + item: { + id, + kind: "assistant", + // Seed with any text already known for this id (a full child + // assistant message seen earlier, possibly before prompt()); + // the projector replaces by id, so an empty item would drop it. + text: this.childText.get(id) ?? "", + phase: "commentary", + }, }); } this.emit({ type: "delta", id, text: e.delta.text }); @@ -583,9 +598,12 @@ export class Claude extends DirectAdapter implements Adapter { .map((b: any) => b.text) .join("\n"); if (text) { - // Remember the emitted id so a later delta merges into this item - // instead of establishing an empty one that replaces its text. - if (m.parent_tool_use_id) this.childItems.add(m.message.id); + // Remember the emitted id and its text so a later delta merges into + // this item instead of establishing an empty one that replaces it. + if (m.parent_tool_use_id) { + this.childItems.add(m.message.id); + this.childText.set(m.message.id, text); + } this.emit({ type: "item", item: { @@ -642,6 +660,7 @@ export class Claude extends DirectAdapter implements Adapter { this.active = false; this.messageIds.clear(); this.childItems.clear(); + this.childText.clear(); for (const id of this.requests.keys()) this.emit({ type: "resolved", id }); this.requests.clear(); diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index abd7d9d1..0b1990f8 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -524,12 +524,77 @@ it("keeps a delayed child stream delta commentary across turn boundaries", async delta: { type: "text_delta", text: " late" }, }, }); - // The fragment re-establishes a commentary item in the fresh window rather - // than a phase-less one that could become the new run's answer. + // The fragment re-establishes a commentary item in the fresh window (the + // between-turns text is carried over, not dropped) rather than a phase-less + // one that could become the new run's answer. expect(current.live.items.get("child-cross")).toEqual({ id: "child-cross", kind: "assistant", - text: " late", + text: "Child text two late", + phase: "commentary", + }); + expect(retainedAnswer(current.live)).toBeUndefined(); +}); + +it("does not overwrite a recall-window child message with a later delta's empty item", async () => { + const sessions = new NativeSessions(); + const first = turn("conv", "claude-recall-1"); + const current = start(sessions, "claude-recall-generation", first); + sessions.state.startTurn(current.live, first); + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-recall", + }, + current.emit, + ) as any; + adapter.active = true; + adapter.native = { write: async () => undefined }; + const send = (m: any) => + adapter.message({ session_id: "claude-recall", ...m }); + // Turn 1 ends. + adapter.message({ + type: "result", + session_id: "claude-recall", + is_error: false, + }); + // The next run attaches; a delayed full child message arrives during the + // recall window, before the next prompt is dispatched. + sessions.state.startTurn(current.live, turn("conv", "claude-recall-2")); + send({ + type: "assistant", + parent_tool_use_id: "task-1", + message: { + id: "child-recall", + role: "assistant", + content: [{ type: "text", text: "Full recall text" }], + }, + }); + await adapter.prompt("next"); + // The child stream's delta arrives after the new prompt. + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { type: "message_start", message: { id: "child-recall" } }, + }); + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: " and more" }, + }, + }); + // The re-established item carried the known text, so the delta appended + // instead of replacing the recall message's text with the empty fragment. + expect(current.live.items.get("child-recall")).toEqual({ + id: "child-recall", + kind: "assistant", + text: "Full recall text and more", phase: "commentary", }); expect(retainedAnswer(current.live)).toBeUndefined(); From 1d16995e6cb61207bf3ebe76a55a6f3aaf2728a5 Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:52:16 +0000 Subject: [PATCH 05/17] Keep the recall seed current with pre-dispatch deltas and bound it A full child message and a delta both arriving before the next prompt left the cached seed stale at the full text, so the post-dispatch re-established item replaced the projector's merged text and the first delta was lost. Accumulate no-turn (recall/between-turns) deltas into the seed so a later delta appends to everything seen so far. Write the seed only while no turn is open (mid-turn entries are never read back) and byte-cap it, so a long turn with many child messages cannot grow adapter memory with copies of full child output; the projector truncates its own display at a similar scale. --- src/adapters/claude.ts | 42 +++++++++++++++++++++++----- test/native-activity-ingress.test.ts | 21 ++++++++++---- 2 files changed, 50 insertions(+), 13 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index 9bf7729f..3865292d 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -71,11 +71,28 @@ export class Claude extends DirectAdapter implements Adapter { // again at the next new user turn, so a delayed delta re-establishes its // commentary item in the fresh projector window. private childItems = new Set(); - // Last-known full text per child item id, from the child assistant message. - // Kept across prompt() (unlike childItems) so a re-established item in the - // fresh window carries the known text instead of replacing it with empty; - // cleared with childItems at the result, so it stays bounded per turn. + // Last-known text per child item id for the recall window (while no turn + // is open: the full assistant message plus any deltas seen before the next + // prompt). Kept across prompt() (unlike childItems) so a re-established + // item in the fresh window carries the known text instead of replacing it + // with empty; cleared with childItems at the result. Entries are written + // only while no turn is open (mid-turn writes are never read back), and + // the total is byte-capped to keep recall memory bounded. private childText = new Map(); + private childTextBytes = 0; + private rememberChildText(id: string, text: string) { + const previous = this.childText.get(id); + const bytes = Buffer.byteLength(text); + this.childTextBytes += bytes - (previous ? Buffer.byteLength(previous) : 0); + this.childText.set(id, text); + // The projector truncates its own display window at a similar scale; + // beyond the budget the seed for an evicted id degrades to the fragment. + while (this.childTextBytes > 4 * 1024 * 1024 && this.childText.size > 1) { + const oldest = this.childText.keys().next().value!; + this.childTextBytes -= Buffer.byteLength(this.childText.get(oldest)!); + this.childText.delete(oldest); + } + } private interrupted = false; private active = false; private steering = new ClaudeSteering(); @@ -554,6 +571,14 @@ export class Claude extends DirectAdapter implements Adapter { // while a user turn is open: after the result the projector drops // deltas, so an empty item emitted then could only clobber saved // native history. + if (m.parent_tool_use_id && !this.active) + // Keep the recall seed current: the projector may merge or drop + // these deltas, but the next turn's re-established item must carry + // them so a later delta appends instead of overwriting them. + this.rememberChildText( + id, + (this.childText.get(id) ?? "") + e.delta.text, + ); if (m.parent_tool_use_id && this.active && !this.childItems.has(id)) { this.childItems.add(id); this.emit({ @@ -598,11 +623,13 @@ export class Claude extends DirectAdapter implements Adapter { .map((b: any) => b.text) .join("\n"); if (text) { - // Remember the emitted id and its text so a later delta merges into - // this item instead of establishing an empty one that replaces it. + // Remember the emitted id (and its recall-window text) so a later + // delta merges into this item instead of establishing an empty one + // that replaces it. Mid-turn writes are never read back, so only + // the no-turn (recall/between-turns) text is cached. if (m.parent_tool_use_id) { this.childItems.add(m.message.id); - this.childText.set(m.message.id, text); + if (!this.active) this.rememberChildText(m.message.id, text); } this.emit({ type: "item", @@ -661,6 +688,7 @@ export class Claude extends DirectAdapter implements Adapter { this.messageIds.clear(); this.childItems.clear(); this.childText.clear(); + this.childTextBytes = 0; for (const id of this.requests.keys()) this.emit({ type: "resolved", id }); this.requests.clear(); diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index 0b1990f8..741734ef 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -574,8 +574,7 @@ it("does not overwrite a recall-window child message with a later delta's empty content: [{ type: "text", text: "Full recall text" }], }, }); - await adapter.prompt("next"); - // The child stream's delta arrives after the new prompt. + // A first delta also arrives during recall, before the prompt is sent. send({ type: "stream_event", parent_tool_use_id: "task-1", @@ -586,15 +585,25 @@ it("does not overwrite a recall-window child message with a later delta's empty parent_tool_use_id: "task-1", event: { type: "content_block_delta", - delta: { type: "text_delta", text: " and more" }, + delta: { type: "text_delta", text: " A" }, + }, + }); + await adapter.prompt("next"); + // The child stream's second delta arrives after the new prompt. + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: " B" }, }, }); - // The re-established item carried the known text, so the delta appended - // instead of replacing the recall message's text with the empty fragment. + // The re-established item carried the recall text including its first + // delta, so the second delta appended instead of overwriting either. expect(current.live.items.get("child-recall")).toEqual({ id: "child-recall", kind: "assistant", - text: "Full recall text and more", + text: "Full recall text A B", phase: "commentary", }); expect(retainedAnswer(current.live)).toBeUndefined(); From 033496081c38c01f4162d6abac0ce106d5580823 Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:00:00 +0000 Subject: [PATCH 06/17] Bound the recall seed cache and merge for evicted ids A single long-lived child stream could grow its recall cache entry without bound (the eviction loop keeps one entry even past the budget), and eviction could erase retained progress: a post-prompt delta for an evicted id re-established an empty item over the projector's retained text. Cap each entry at the projector's display-preview limit (keeping the tail), and keep a never-evicting set of ids whose commentary item was emitted while no turn was open, so a delta for an evicted id merges into the retained item instead of replacing it. --- src/adapters/claude.ts | 67 ++++++++++++----- test/native-activity-ingress.test.ts | 108 +++++++++++++++++++++++++++ 2 files changed, 156 insertions(+), 19 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index 3865292d..8f2c7f58 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -76,17 +76,39 @@ export class Claude extends DirectAdapter implements Adapter { // prompt). Kept across prompt() (unlike childItems) so a re-established // item in the fresh window carries the known text instead of replacing it // with empty; cleared with childItems at the result. Entries are written - // only while no turn is open (mid-turn writes are never read back), and - // the total is byte-capped to keep recall memory bounded. + // only while no turn is open (mid-turn writes are never read back). Each + // entry is capped at the projector's display-preview limit and the total + // is byte-capped, so neither one long-lived stream nor many streams can + // grow adapter memory with copies of full child output. private childText = new Map(); + // Ids written to childText while no turn was open. Unlike childText this + // never evicts, so a delta for an evicted id can still tell that its full + // item was emitted: the projector retains it (a full message is always + // commentary), and the delta merges into it instead of re-establishing an + // empty item over it. + private childSeen = new Set(); private childTextBytes = 0; private rememberChildText(id: string, text: string) { const previous = this.childText.get(id); - const bytes = Buffer.byteLength(text); - this.childTextBytes += bytes - (previous ? Buffer.byteLength(previous) : 0); + const previousBytes = previous ? Buffer.byteLength(previous) : 0; + // Keep only a display-sized tail, mirroring the projector's own preview + // bound, so one long-lived stream cannot grow its entry without limit. + if (Buffer.byteLength(text) > 64000) { + let low = 0; + let high = text.length; + while (low < high) { + const keep = Math.ceil((low + high) / 2); + if (Buffer.byteLength(text.slice(-keep)) <= 64000) low = keep; + else high = keep - 1; + } + text = text.slice(-low); + } + this.childTextBytes += Buffer.byteLength(text) - previousBytes; this.childText.set(id, text); - // The projector truncates its own display window at a similar scale; - // beyond the budget the seed for an evicted id degrades to the fragment. + this.childSeen.add(id); + // Hard bound on recall-window seeding memory. Eviction is safe for the + // retained display: the evicted id stays in childSeen, so a later delta + // merges into the projector's item instead of replacing its text. while (this.childTextBytes > 4 * 1024 * 1024 && this.childText.size > 1) { const oldest = this.childText.keys().next().value!; this.childTextBytes -= Buffer.byteLength(this.childText.get(oldest)!); @@ -580,19 +602,25 @@ export class Claude extends DirectAdapter implements Adapter { (this.childText.get(id) ?? "") + e.delta.text, ); if (m.parent_tool_use_id && this.active && !this.childItems.has(id)) { - this.childItems.add(id); - this.emit({ - type: "item", - item: { - id, - kind: "assistant", - // Seed with any text already known for this id (a full child - // assistant message seen earlier, possibly before prompt()); - // the projector replaces by id, so an empty item would drop it. - text: this.childText.get(id) ?? "", - phase: "commentary", - }, - }); + if (this.childText.has(id) || !this.childSeen.has(id)) { + this.childItems.add(id); + this.emit({ + type: "item", + item: { + id, + kind: "assistant", + // Seed with any text already known for this id (a full child + // assistant message seen earlier, possibly before prompt()); + // the projector replaces by id, so an empty item would drop it. + text: this.childText.get(id) ?? "", + phase: "commentary", + }, + }); + } + // An id seen while no turn was open whose seed was evicted: its + // full item is still retained by the projector (commentary), so + // emit only the delta and let it merge into that item instead of + // re-establishing an empty one over its text. } this.emit({ type: "delta", id, text: e.delta.text }); } @@ -688,6 +716,7 @@ export class Claude extends DirectAdapter implements Adapter { this.messageIds.clear(); this.childItems.clear(); this.childText.clear(); + this.childSeen.clear(); this.childTextBytes = 0; for (const id of this.requests.keys()) this.emit({ type: "resolved", id }); diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index 741734ef..353d71b6 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -609,6 +609,114 @@ it("does not overwrite a recall-window child message with a later delta's empty expect(retainedAnswer(current.live)).toBeUndefined(); }); +it("caps a single recall stream's cached seed at the display limit", () => { + const sessions = new NativeSessions(); + const run = turn("conv", "claude-cache-cap"); + const current = start(sessions, "claude-cache-cap-generation", run); + sessions.state.startTurn(current.live, run); + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-cache-cap", + }, + current.emit, + ) as any; + adapter.active = true; + const send = (m: any) => + adapter.message({ session_id: "claude-cache-cap", ...m }); + // Turn 1 ends; one long-lived child stream keeps streaming while no turn + // is open. + adapter.message({ + type: "result", + session_id: "claude-cache-cap", + is_error: false, + }); + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { type: "message_start", message: { id: "child-big" } }, + }); + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: "x".repeat(200_000) }, + }, + }); + const stored = adapter.childText.get("child-big") as string; + expect(Buffer.byteLength(stored)).toBeLessThanOrEqual(64000); + expect(stored.endsWith("x".repeat(1000))).toBe(true); +}); + +it("merges a post-prompt delta for an evicted recall id instead of re-establishing over it", async () => { + const sessions = new NativeSessions(); + const run = turn("conv", "claude-seen-evicted"); + const current = start(sessions, "claude-seen-evicted-generation", run); + sessions.state.startTurn(current.live, run); + const emitted: AdapterEvent[] = []; + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-seen-evicted", + }, + (e) => { + emitted.push(e); + current.emit(e); + }, + ) as any; + adapter.active = true; + adapter.native = { write: async () => undefined }; + const send = (m: any) => + adapter.message({ session_id: "claude-seen-evicted", ...m }); + // Turn 1 ends; the child's full message arrives while no turn is open. + adapter.message({ + type: "result", + session_id: "claude-seen-evicted", + is_error: false, + }); + send({ + type: "assistant", + parent_tool_use_id: "task-1", + message: { + id: "child-seen", + role: "assistant", + content: [{ type: "text", text: "Retained text" }], + }, + }); + // The seed cache evicts the id (as >4 MiB of other recall output would), + // while childSeen still records that its commentary item was emitted. + adapter.childText.delete("child-seen"); + expect(adapter.childSeen.has("child-seen")).toBe(true); + await adapter.prompt("next"); + sessions.state.startTurn(current.live, turn("conv", "claude-seen-evicted-2")); + emitted.length = 0; + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { type: "message_start", message: { id: "child-seen" } }, + }); + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: " more" }, + }, + }); + // No establishing item is emitted for the evicted-but-seen id: the delta + // alone merges into the retained commentary item instead of replacing it. + expect(emitted).toEqual([{ type: "delta", id: "child-seen", text: " more" }]); +}); + const option = (id: string, confirmed: string) => ({ id, label: id, From 02ad50ce21ca07162c636939c08362b66b6c621d Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:54:49 +0000 Subject: [PATCH 07/17] Always establish a commentary item for post-prompt child deltas Skipping the establishing item for an id whose recall seed was evicted let a between-turns delta reach the projector alone: the next turn clears the item window, the fallback finds nothing for the current run, and a phase-less assistant item was created that completion could select as the answer. Establish the commentary item unconditionally (phase is always safe) and never evict the recall seed (its text then never degrades to empty); each entry stays capped at the projector's display-preview limit, so one long-lived stream cannot grow it without bound. --- src/adapters/claude.ts | 66 ++++++++++------------------ test/native-activity-ingress.test.ts | 49 ++++++++++++++------- 2 files changed, 55 insertions(+), 60 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index 8f2c7f58..1b8c27d7 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -76,21 +76,15 @@ export class Claude extends DirectAdapter implements Adapter { // prompt). Kept across prompt() (unlike childItems) so a re-established // item in the fresh window carries the known text instead of replacing it // with empty; cleared with childItems at the result. Entries are written - // only while no turn is open (mid-turn writes are never read back). Each - // entry is capped at the projector's display-preview limit and the total - // is byte-capped, so neither one long-lived stream nor many streams can - // grow adapter memory with copies of full child output. + // only while no turn is open (mid-turn writes are never read back), and + // each entry is capped at the projector's display-preview limit. Never + // evicted: dropping a seed would make a later re-established item empty + // and erase the projector's retained text, while keeping the id and + // skipping the item would let a delta create a phase-less item that could + // be selected as the answer. Memory is bounded per entry and only grows + // with the distinct child ids seen between turns. private childText = new Map(); - // Ids written to childText while no turn was open. Unlike childText this - // never evicts, so a delta for an evicted id can still tell that its full - // item was emitted: the projector retains it (a full message is always - // commentary), and the delta merges into it instead of re-establishing an - // empty item over it. - private childSeen = new Set(); - private childTextBytes = 0; private rememberChildText(id: string, text: string) { - const previous = this.childText.get(id); - const previousBytes = previous ? Buffer.byteLength(previous) : 0; // Keep only a display-sized tail, mirroring the projector's own preview // bound, so one long-lived stream cannot grow its entry without limit. if (Buffer.byteLength(text) > 64000) { @@ -103,17 +97,7 @@ export class Claude extends DirectAdapter implements Adapter { } text = text.slice(-low); } - this.childTextBytes += Buffer.byteLength(text) - previousBytes; this.childText.set(id, text); - this.childSeen.add(id); - // Hard bound on recall-window seeding memory. Eviction is safe for the - // retained display: the evicted id stays in childSeen, so a later delta - // merges into the projector's item instead of replacing its text. - while (this.childTextBytes > 4 * 1024 * 1024 && this.childText.size > 1) { - const oldest = this.childText.keys().next().value!; - this.childTextBytes -= Buffer.byteLength(this.childText.get(oldest)!); - this.childText.delete(oldest); - } } private interrupted = false; private active = false; @@ -602,25 +586,21 @@ export class Claude extends DirectAdapter implements Adapter { (this.childText.get(id) ?? "") + e.delta.text, ); if (m.parent_tool_use_id && this.active && !this.childItems.has(id)) { - if (this.childText.has(id) || !this.childSeen.has(id)) { - this.childItems.add(id); - this.emit({ - type: "item", - item: { - id, - kind: "assistant", - // Seed with any text already known for this id (a full child - // assistant message seen earlier, possibly before prompt()); - // the projector replaces by id, so an empty item would drop it. - text: this.childText.get(id) ?? "", - phase: "commentary", - }, - }); - } - // An id seen while no turn was open whose seed was evicted: its - // full item is still retained by the projector (commentary), so - // emit only the delta and let it merge into that item instead of - // re-establishing an empty one over its text. + this.childItems.add(id); + this.emit({ + type: "item", + item: { + id, + kind: "assistant", + // Seed with any text already known for this id (a full child + // assistant message or deltas seen earlier, possibly before + // prompt()); the projector replaces by id, so an empty item + // would drop it. Never skipped: a delta alone could create a + // phase-less item that becomes the run's answer. + text: this.childText.get(id) ?? "", + phase: "commentary", + }, + }); } this.emit({ type: "delta", id, text: e.delta.text }); } @@ -716,8 +696,6 @@ export class Claude extends DirectAdapter implements Adapter { this.messageIds.clear(); this.childItems.clear(); this.childText.clear(); - this.childSeen.clear(); - this.childTextBytes = 0; for (const id of this.requests.keys()) this.emit({ type: "resolved", id }); this.requests.clear(); diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index 353d71b6..7ae2a28b 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -653,10 +653,10 @@ it("caps a single recall stream's cached seed at the display limit", () => { expect(stored.endsWith("x".repeat(1000))).toBe(true); }); -it("merges a post-prompt delta for an evicted recall id instead of re-establishing over it", async () => { +it("still establishes a commentary item when a post-prompt delta's recall seed was lost", async () => { const sessions = new NativeSessions(); - const run = turn("conv", "claude-seen-evicted"); - const current = start(sessions, "claude-seen-evicted-generation", run); + const run = turn("conv", "claude-seed-lost"); + const current = start(sessions, "claude-seed-lost-generation", run); sessions.state.startTurn(current.live, run); const emitted: AdapterEvent[] = []; const adapter = new Claude( @@ -666,7 +666,7 @@ it("merges a post-prompt delta for an evicted recall id instead of re-establishi project: dir, version: "fixture", billing: "existing", - resume: "claude-seen-evicted", + resume: "claude-seed-lost", }, (e) => { emitted.push(e); @@ -676,33 +676,32 @@ it("merges a post-prompt delta for an evicted recall id instead of re-establishi adapter.active = true; adapter.native = { write: async () => undefined }; const send = (m: any) => - adapter.message({ session_id: "claude-seen-evicted", ...m }); + adapter.message({ session_id: "claude-seed-lost", ...m }); // Turn 1 ends; the child's full message arrives while no turn is open. adapter.message({ type: "result", - session_id: "claude-seen-evicted", + session_id: "claude-seed-lost", is_error: false, }); send({ type: "assistant", parent_tool_use_id: "task-1", message: { - id: "child-seen", + id: "child-seed-lost", role: "assistant", content: [{ type: "text", text: "Retained text" }], }, }); - // The seed cache evicts the id (as >4 MiB of other recall output would), - // while childSeen still records that its commentary item was emitted. - adapter.childText.delete("child-seen"); - expect(adapter.childSeen.has("child-seen")).toBe(true); + // The recall seed is missing for this id (as after extreme cache + // pressure); the id is also not in the new turn's cleared item window. + adapter.childText.delete("child-seed-lost"); await adapter.prompt("next"); - sessions.state.startTurn(current.live, turn("conv", "claude-seen-evicted-2")); + sessions.state.startTurn(current.live, turn("conv", "claude-seed-lost-2")); emitted.length = 0; send({ type: "stream_event", parent_tool_use_id: "task-1", - event: { type: "message_start", message: { id: "child-seen" } }, + event: { type: "message_start", message: { id: "child-seed-lost" } }, }); send({ type: "stream_event", @@ -712,9 +711,27 @@ it("merges a post-prompt delta for an evicted recall id instead of re-establishi delta: { type: "text_delta", text: " more" }, }, }); - // No establishing item is emitted for the evicted-but-seen id: the delta - // alone merges into the retained commentary item instead of replacing it. - expect(emitted).toEqual([{ type: "delta", id: "child-seen", text: " more" }]); + // The delta is still preceded by a commentary item, so the fresh window's + // item is never phase-less and cannot become the new run's answer. + expect(emitted).toEqual([ + { + type: "item", + item: { + id: "child-seed-lost", + kind: "assistant", + text: "", + phase: "commentary", + }, + }, + { type: "delta", id: "child-seed-lost", text: " more" }, + ]); + expect(current.live.items.get("child-seed-lost")).toEqual({ + id: "child-seed-lost", + kind: "assistant", + text: " more", + phase: "commentary", + }); + expect(retainedAnswer(current.live)).toBeUndefined(); }); const option = (id: string, confirmed: string) => ({ From f5170cbc30d36743cdfbe9128b402430af1e5160 Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Fri, 20 Nov 2026 03:48:09 +0000 Subject: [PATCH 08/17] Retain child text across turns so a delayed delta appends, not replaces A full child message received during an active turn was not cached and the result handler cleared the cache, so a delayed delta for that id in the next turn re-established with an empty seed and the projector's upsert replaced the stored child text with the fragment. Cache every child assistant message's text (whether a turn is open or not) and keep it across the result and prompt, so a re-established item carries the earlier text and the delta appends to it. Entries stay capped at the projector's display-preview limit; the entry count tracks the session's distinct child message ids. --- src/adapters/claude.ts | 34 +++++++------- test/native-activity-ingress.test.ts | 66 ++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+), 18 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index 1b8c27d7..20798e0b 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -71,18 +71,18 @@ export class Claude extends DirectAdapter implements Adapter { // again at the next new user turn, so a delayed delta re-establishes its // commentary item in the fresh projector window. private childItems = new Set(); - // Last-known text per child item id for the recall window (while no turn - // is open: the full assistant message plus any deltas seen before the next - // prompt). Kept across prompt() (unlike childItems) so a re-established - // item in the fresh window carries the known text instead of replacing it - // with empty; cleared with childItems at the result. Entries are written - // only while no turn is open (mid-turn writes are never read back), and - // each entry is capped at the projector's display-preview limit. Never - // evicted: dropping a seed would make a later re-established item empty - // and erase the projector's retained text, while keeping the id and - // skipping the item would let a delta create a phase-less item that could - // be selected as the answer. Memory is bounded per entry and only grows - // with the distinct child ids seen between turns. + // Last-known text per child item id: the full assistant message (written + // whether a turn is open or not) plus any deltas seen before the next + // prompt. Kept across prompt() and the result (unlike childItems) so a + // re-established item in a fresh window carries the known text instead of + // replacing it with empty — a delayed delta for an earlier message id must + // append, not overwrite its stored text. Each entry is capped at the + // projector's display-preview limit. Never evicted: dropping a seed would + // make a later re-established item empty and erase the projector's + // retained text, while keeping the id and skipping the item would let a + // delta create a phase-less item that could be selected as the answer. + // Memory is bounded per entry; the entry count tracks the session's + // distinct child message ids (live volume unverified). private childText = new Map(); private rememberChildText(id: string, text: string) { // Keep only a display-sized tail, mirroring the projector's own preview @@ -631,13 +631,12 @@ export class Claude extends DirectAdapter implements Adapter { .map((b: any) => b.text) .join("\n"); if (text) { - // Remember the emitted id (and its recall-window text) so a later - // delta merges into this item instead of establishing an empty one - // that replaces it. Mid-turn writes are never read back, so only - // the no-turn (recall/between-turns) text is cached. + // Remember the emitted id and its text so a later delta merges into + // this item instead of establishing an empty one that replaces it, + // even when the delta arrives in a later turn. if (m.parent_tool_use_id) { this.childItems.add(m.message.id); - if (!this.active) this.rememberChildText(m.message.id, text); + this.rememberChildText(m.message.id, text); } this.emit({ type: "item", @@ -695,7 +694,6 @@ export class Claude extends DirectAdapter implements Adapter { this.active = false; this.messageIds.clear(); this.childItems.clear(); - this.childText.clear(); for (const id of this.requests.keys()) this.emit({ type: "resolved", id }); this.requests.clear(); diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index 7ae2a28b..74b59fbb 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -734,6 +734,72 @@ it("still establishes a commentary item when a post-prompt delta's recall seed w expect(retainedAnswer(current.live)).toBeUndefined(); }); +it("keeps an active-turn child message's text when a delayed delta arrives in the next turn", async () => { + const sessions = new NativeSessions(); + const run = turn("conv", "claude-delayed-delta"); + const current = start(sessions, "claude-delayed-delta-generation", run); + sessions.state.startTurn(current.live, run); + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-delayed-delta", + }, + current.emit, + ) as any; + adapter.active = true; + adapter.native = { write: async () => undefined }; + const send = (m: any) => + adapter.message({ session_id: "claude-delayed-delta", ...m }); + // Turn 1, while active: the child's full assistant message arrives. + send({ + type: "assistant", + parent_tool_use_id: "task-1", + message: { + id: "child-old", + role: "assistant", + content: [{ type: "text", text: "Full active text" }], + }, + }); + // Turn 1 ends with no further child content; turn 2 starts fresh. + adapter.message({ + type: "result", + session_id: "claude-delayed-delta", + is_error: false, + }); + await adapter.prompt("next"); + sessions.state.startTurn( + current.live, + turn("conv", "claude-delayed-delta-2"), + ); + // A delayed delta for the same child message id finally arrives. + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { type: "message_start", message: { id: "child-old" } }, + }); + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: " more" }, + }, + }); + // The re-established item carries the earlier full text; the delta appends + // instead of overwriting the retained child history. + expect(current.live.items.get("child-old")).toEqual({ + id: "child-old", + kind: "assistant", + text: "Full active text more", + phase: "commentary", + }); + expect(retainedAnswer(current.live)).toBeUndefined(); +}); + const option = (id: string, confirmed: string) => ({ id, label: id, From 8ea1f1d673f2bea41619a574a461d574c3a354a1 Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Fri, 20 Nov 2026 04:45:11 +0000 Subject: [PATCH 09/17] Cache active child deltas so a delayed delta never drops them Child deltas updated the recall seed only while no turn was open, so an active turn's delta-only stream was projected but never cached: a delayed delta for that id in the next turn re-established from an incomplete seed and the earlier streamed text was dropped (A plus B became A plus C). Keep the seed current with every child delta, open turn or not, so a later re-established item carries everything the stream has said so far. --- src/adapters/claude.ts | 16 +++---- test/native-activity-ingress.test.ts | 66 ++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 8 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index 20798e0b..dd549130 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -577,14 +577,6 @@ export class Claude extends DirectAdapter implements Adapter { // while a user turn is open: after the result the projector drops // deltas, so an empty item emitted then could only clobber saved // native history. - if (m.parent_tool_use_id && !this.active) - // Keep the recall seed current: the projector may merge or drop - // these deltas, but the next turn's re-established item must carry - // them so a later delta appends instead of overwriting them. - this.rememberChildText( - id, - (this.childText.get(id) ?? "") + e.delta.text, - ); if (m.parent_tool_use_id && this.active && !this.childItems.has(id)) { this.childItems.add(id); this.emit({ @@ -602,6 +594,14 @@ export class Claude extends DirectAdapter implements Adapter { }, }); } + // Keep the seed current with every delta, open turn or not, so a + // later re-established item carries everything the stream has said + // so far and a subsequent delta appends instead of overwriting it. + if (m.parent_tool_use_id) + this.rememberChildText( + id, + (this.childText.get(id) ?? "") + e.delta.text, + ); this.emit({ type: "delta", id, text: e.delta.text }); } if ( diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index 74b59fbb..7553d7b9 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -800,6 +800,72 @@ it("keeps an active-turn child message's text when a delayed delta arrives in th expect(retainedAnswer(current.live)).toBeUndefined(); }); +it("keeps an active-turn child stream's text when a delayed delta arrives in the next turn", async () => { + const sessions = new NativeSessions(); + const run = turn("conv", "claude-active-delta"); + const current = start(sessions, "claude-active-delta-generation", run); + sessions.state.startTurn(current.live, run); + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-active-delta", + }, + current.emit, + ) as any; + adapter.active = true; + adapter.native = { write: async () => undefined }; + const send = (m: any) => + adapter.message({ session_id: "claude-active-delta", ...m }); + // Turn 1, while active: a delta-only child stream (no full message). + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { type: "message_start", message: { id: "child-delta" } }, + }); + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: "A" }, + }, + }); + adapter.message({ + type: "result", + session_id: "claude-active-delta", + is_error: false, + }); + // Turn 2 starts; a delayed delta for the same stream arrives. + await adapter.prompt("next"); + sessions.state.startTurn(current.live, turn("conv", "claude-active-delta-2")); + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { type: "message_start", message: { id: "child-delta" } }, + }); + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: "B" }, + }, + }); + // The re-established item carries the streamed "A" from the earlier turn; + // the delayed "B" appends instead of replacing it. + expect(current.live.items.get("child-delta")).toEqual({ + id: "child-delta", + kind: "assistant", + text: "AB", + phase: "commentary", + }); + expect(retainedAnswer(current.live)).toBeUndefined(); +}); + const option = (id: string, confirmed: string) => ({ id, label: id, From f595d08421e21c8ba54ee60b3fa7f1cc6bf29bae Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Fri, 20 Nov 2026 05:38:39 +0000 Subject: [PATCH 10/17] Bound the child text cache for the adapter's lifetime The child text cache was never cleared, so a long session that repeatedly uses subagents retained an entry per distinct child message id and could grow server memory until the adapter was disposed. Byte-cap the cache at the projector's own display-window scale (4 MiB), evicting the oldest ids. Eviction only ever drops the oldest ids, the least likely to still receive a delayed delta; a re-established item for an evicted id starts from the fragment while its earlier text stays in its own run's progress rows. --- src/adapters/claude.ts | 22 ++++++++++++++++------ test/native-activity-ingress.test.ts | 25 +++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index dd549130..9f5f487f 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -77,13 +77,15 @@ export class Claude extends DirectAdapter implements Adapter { // re-established item in a fresh window carries the known text instead of // replacing it with empty — a delayed delta for an earlier message id must // append, not overwrite its stored text. Each entry is capped at the - // projector's display-preview limit. Never evicted: dropping a seed would - // make a later re-established item empty and erase the projector's - // retained text, while keeping the id and skipping the item would let a - // delta create a phase-less item that could be selected as the answer. - // Memory is bounded per entry; the entry count tracks the session's - // distinct child message ids (live volume unverified). + // projector's display-preview limit and the total is byte-capped at the + // projector's own display-window scale, evicting the oldest ids, so a + // long session that repeatedly uses subagents cannot grow adapter memory + // with copies of child output. Eviction only ever drops the oldest ids + // (the least likely to still receive a delayed delta); a re-established + // item for an evicted id starts from the fragment, while its earlier text + // stays in that id's own run's progress rows. private childText = new Map(); + private childTextBytes = 0; private rememberChildText(id: string, text: string) { // Keep only a display-sized tail, mirroring the projector's own preview // bound, so one long-lived stream cannot grow its entry without limit. @@ -97,7 +99,15 @@ export class Claude extends DirectAdapter implements Adapter { } text = text.slice(-low); } + const previous = this.childText.get(id); + const previousBytes = previous ? Buffer.byteLength(previous) : 0; + this.childTextBytes += Buffer.byteLength(text) - previousBytes; this.childText.set(id, text); + while (this.childTextBytes > 4 * 1024 * 1024 && this.childText.size > 1) { + const oldest = this.childText.keys().next().value!; + this.childTextBytes -= Buffer.byteLength(this.childText.get(oldest)!); + this.childText.delete(oldest); + } } private interrupted = false; private active = false; diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index 7553d7b9..4c2866d8 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -653,6 +653,31 @@ it("caps a single recall stream's cached seed at the display limit", () => { expect(stored.endsWith("x".repeat(1000))).toBe(true); }); +it("bounds the child text cache so a long session cannot accumulate child output", () => { + const sessions = new NativeSessions(); + const run = turn("conv", "claude-cache-bound"); + const current = start(sessions, "claude-cache-bound-generation", run); + sessions.state.startTurn(current.live, run); + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-cache-bound", + }, + current.emit, + ) as any; + // Enough 64,000-byte entries to exceed the 4 MiB budget, so the oldest + // ids are evicted and the cache stays bounded for the adapter's lifetime. + for (let i = 0; i < 70; i++) + adapter.rememberChildText("bound-" + i, "x".repeat(64000)); + expect(adapter.childText.has("bound-0")).toBe(false); + expect(adapter.childText.size).toBeLessThanOrEqual(66); + expect(adapter.childTextBytes).toBeLessThanOrEqual(4 * 1024 * 1024 + 64000); +}); + it("still establishes a commentary item when a post-prompt delta's recall seed was lost", async () => { const sessions = new NativeSessions(); const run = turn("conv", "claude-seed-lost"); From 1789d988bc597bd612cf940c76df4dc11266a6e8 Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Fri, 20 Nov 2026 06:32:40 +0000 Subject: [PATCH 11/17] Bound the child text cache by entry count, not just bytes Distinct child ids carrying empty-text deltas added cache entries without moving the byte counter, so a long-lived session could grow the map's entry overhead without triggering byte-based eviction. Skip empty deltas (they contribute nothing to the seed) and evict by entry count too (bound at 512), so both byte volume and entry count stay bounded. --- src/adapters/claude.ts | 18 ++++++++++++------ test/native-activity-ingress.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index 9f5f487f..ebbc3f54 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -80,10 +80,12 @@ export class Claude extends DirectAdapter implements Adapter { // projector's display-preview limit and the total is byte-capped at the // projector's own display-window scale, evicting the oldest ids, so a // long session that repeatedly uses subagents cannot grow adapter memory - // with copies of child output. Eviction only ever drops the oldest ids - // (the least likely to still receive a delayed delta); a re-established - // item for an evicted id starts from the fragment, while its earlier text - // stays in that id's own run's progress rows. + // with copies of child output. The map is bounded by both bytes and entry + // count: empty or tiny deltas would otherwise add entries without moving + // the byte counter. Eviction only ever drops the oldest ids (the least + // likely to still receive a delayed delta); a re-established item for an + // evicted id starts from the fragment, while its earlier text stays in + // that id's own run's progress rows. private childText = new Map(); private childTextBytes = 0; private rememberChildText(id: string, text: string) { @@ -103,7 +105,10 @@ export class Claude extends DirectAdapter implements Adapter { const previousBytes = previous ? Buffer.byteLength(previous) : 0; this.childTextBytes += Buffer.byteLength(text) - previousBytes; this.childText.set(id, text); - while (this.childTextBytes > 4 * 1024 * 1024 && this.childText.size > 1) { + while ( + (this.childTextBytes > 4 * 1024 * 1024 || this.childText.size > 512) && + this.childText.size > 1 + ) { const oldest = this.childText.keys().next().value!; this.childTextBytes -= Buffer.byteLength(this.childText.get(oldest)!); this.childText.delete(oldest); @@ -607,7 +612,8 @@ export class Claude extends DirectAdapter implements Adapter { // Keep the seed current with every delta, open turn or not, so a // later re-established item carries everything the stream has said // so far and a subsequent delta appends instead of overwriting it. - if (m.parent_tool_use_id) + // Empty deltas contribute nothing, so they do not add a cache entry. + if (m.parent_tool_use_id && e.delta.text) this.rememberChildText( id, (this.childText.get(id) ?? "") + e.delta.text, diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index 4c2866d8..2e70734d 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -678,6 +678,28 @@ it("bounds the child text cache so a long session cannot accumulate child output expect(adapter.childTextBytes).toBeLessThanOrEqual(4 * 1024 * 1024 + 64000); }); +it("bounds the child text cache by entry count even for empty-text streams", () => { + const sessions = new NativeSessions(); + const run = turn("conv", "claude-cache-count"); + const current = start(sessions, "claude-cache-count-generation", run); + sessions.state.startTurn(current.live, run); + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-cache-count", + }, + current.emit, + ) as any; + // Many distinct ids whose text is empty or near-empty: the byte counter + // never moves, so eviction must also bound the entry count. + for (let i = 0; i < 600; i++) adapter.rememberChildText("empty-" + i, ""); + expect(adapter.childText.size).toBeLessThanOrEqual(512); +}); + it("still establishes a commentary item when a post-prompt delta's recall seed was lost", async () => { const sessions = new NativeSessions(); const run = turn("conv", "claude-seed-lost"); From c780c0510e240de8bed3abb80391541de7ebbd66 Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Fri, 20 Nov 2026 07:38:36 +0000 Subject: [PATCH 12/17] Establish commentary for child deltas during recall too The adapter established the commentary item only while a user turn was open, but a child delta arriving during recall (the next run already attached, active still false) was emitted alone, and the projector created a phase-less assistant item that could be selected as the parent run's answer. Establish the commentary item for every child delta when its id has not been seen, active or not: during recall it reaches the run path as commentary, and when no run is attached the projector drops the delta and only upserts the seeded commentary item, which cannot be selected. --- src/adapters/claude.ts | 12 ++++--- test/native-activity-ingress.test.ts | 50 ++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index ebbc3f54..fd494932 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -588,11 +588,13 @@ export class Claude extends DirectAdapter implements Adapter { // A child stream's deltas must never leave a phase-less assistant // item the projector could pick as the run's answer. Establish the // commentary item before the first delta so the projector merges the - // deltas into it and keeps the child's text as progress only. Only - // while a user turn is open: after the result the projector drops - // deltas, so an empty item emitted then could only clobber saved - // native history. - if (m.parent_tool_use_id && this.active && !this.childItems.has(id)) { + // deltas into it and keeps the child's text as progress only — even + // during recall, when the next run is already attached but active is + // still false: a delta alone there would create a phase-less item + // the projector could select as the answer. When no run is attached + // the projector drops the delta and only upserts this seeded + // commentary item, which cannot be selected. + if (m.parent_tool_use_id && !this.childItems.has(id)) { this.childItems.add(id); this.emit({ type: "item", diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index 2e70734d..313b480b 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -913,6 +913,56 @@ it("keeps an active-turn child stream's text when a delayed delta arrives in the expect(retainedAnswer(current.live)).toBeUndefined(); }); +it("marks a delta-only child stream commentary when it arrives during recall", async () => { + const sessions = new NativeSessions(); + const run = turn("conv", "claude-recall-delta"); + const current = start(sessions, "claude-recall-delta-generation", run); + sessions.state.startTurn(current.live, run); + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-recall-delta", + }, + current.emit, + ) as any; + adapter.active = true; + // Turn 1 ends; the next run attaches during recall, before prompt() would + // mark the adapter active again. + adapter.message({ + type: "result", + session_id: "claude-recall-delta", + is_error: false, + }); + sessions.state.startTurn(current.live, turn("conv", "claude-recall-delta-2")); + // A delta-only child stream arrives in that recall window (no full message). + adapter.message({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { type: "message_start", message: { id: "recall-delta" } }, + }); + adapter.message({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: "Recall fragment" }, + }, + }); + // The item is commentary, never phase-less: it cannot become the answer + // even though the run is already attached and the adapter is inactive. + expect(current.live.items.get("recall-delta")).toEqual({ + id: "recall-delta", + kind: "assistant", + text: "Recall fragment", + phase: "commentary", + }); + expect(retainedAnswer(current.live)).toBeUndefined(); +}); + const option = (id: string, confirmed: string) => ({ id, label: id, From c4bf745cee22edf29c1e458b321f0cd942d91252 Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:38:49 +0000 Subject: [PATCH 13/17] Fold inactive child deltas into a seeded commentary item Two between-run deltas could still leave a phase-less, answer-eligible item: the first established the id (recording it in childItems), the next window reset cleared the projector items, and a pre-prompt delta skipped the establishment and was emitted alone. While no turn is open, fold each child delta into a single commentary item carrying the accumulated seed instead of emitting a bare delta: the item is never phase-less (so it cannot be selected as the answer) and it carries the stream text (so an evicted id's item holds the fragment, not an empty seed). Root-stream deltas and the active-turn establish-and-merge path are unchanged. --- src/adapters/claude.ts | 56 ++++++++++++++++--------- test/native-activity-ingress.test.ts | 63 ++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 20 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index fd494932..c19553af 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -585,16 +585,29 @@ export class Claude extends DirectAdapter implements Adapter { } if (e.type === "content_block_delta" && e.delta.type === "text_delta") { const id = this.messageIds.get(stream) ?? m.uuid; - // A child stream's deltas must never leave a phase-less assistant - // item the projector could pick as the run's answer. Establish the - // commentary item before the first delta so the projector merges the - // deltas into it and keeps the child's text as progress only — even - // during recall, when the next run is already attached but active is - // still false: a delta alone there would create a phase-less item - // the projector could select as the answer. When no run is attached - // the projector drops the delta and only upserts this seeded - // commentary item, which cannot be selected. - if (m.parent_tool_use_id && !this.childItems.has(id)) { + if (m.parent_tool_use_id && !this.active) { + // Between turns the projector may drop a bare delta (no run) or + // attach the next run during recall before active flips true. In + // both cases a bare delta could leave a phase-less item that is + // selectable as the answer, so fold the delta into a single + // commentary item carrying the accumulated seed: the item is + // never phase-less and its text preserves the stream (including + // an evicted seed's id — the item then carries the fragment, not + // an empty seed). No separate delta is emitted here. + this.rememberChildText( + id, + (this.childText.get(id) ?? "") + e.delta.text, + ); + this.emit({ + type: "item", + item: { + id, + kind: "assistant", + text: this.childText.get(id) ?? "", + phase: "commentary", + }, + }); + } else if (m.parent_tool_use_id && !this.childItems.has(id)) { this.childItems.add(id); this.emit({ type: "item", @@ -602,25 +615,28 @@ export class Claude extends DirectAdapter implements Adapter { id, kind: "assistant", // Seed with any text already known for this id (a full child - // assistant message or deltas seen earlier, possibly before - // prompt()); the projector replaces by id, so an empty item - // would drop it. Never skipped: a delta alone could create a - // phase-less item that becomes the run's answer. + // assistant message or deltas seen earlier); the projector + // replaces by id, so an empty item would drop it. text: this.childText.get(id) ?? "", phase: "commentary", }, }); } - // Keep the seed current with every delta, open turn or not, so a - // later re-established item carries everything the stream has said - // so far and a subsequent delta appends instead of overwriting it. - // Empty deltas contribute nothing, so they do not add a cache entry. - if (m.parent_tool_use_id && e.delta.text) + // Keep the seed current with every active delta (the inactive fold + // above already accumulated its delta), so a later re-established + // item carries everything the stream has said so far and a + // subsequent delta appends instead of overwriting it. Empty deltas + // contribute nothing, so they do not add a cache entry. + if (m.parent_tool_use_id && this.active && e.delta.text) this.rememberChildText( id, (this.childText.get(id) ?? "") + e.delta.text, ); - this.emit({ type: "delta", id, text: e.delta.text }); + // Root (parent) streams always emit deltas; child streams emit them + // only while a turn is open (while inactive their delta was folded + // into the commentary item above). + if (!m.parent_tool_use_id || this.active) + this.emit({ type: "delta", id, text: e.delta.text }); } if ( e.type === "content_block_start" && diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index 313b480b..957e8f01 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -963,6 +963,69 @@ it("marks a delta-only child stream commentary when it arrives during recall", a expect(retainedAnswer(current.live)).toBeUndefined(); }); +it("keeps between-run child deltas commentary even across a window reset", async () => { + const sessions = new NativeSessions(); + const run = turn("conv", "claude-between-2"); + const current = start(sessions, "claude-between-2-generation", run); + sessions.state.startTurn(current.live, run); + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-between-2", + }, + current.emit, + ) as any; + adapter.active = true; + // Turn 1 ends; the first child delta arrives between runs. + adapter.message({ + type: "result", + session_id: "claude-between-2", + is_error: false, + }); + adapter.message({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { type: "message_start", message: { id: "between-2" } }, + }); + adapter.message({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: "A" }, + }, + }); + // The next run attaches, resetting the projector's item window, and the + // second child delta arrives pre-prompt. + sessions.state.startTurn(current.live, turn("conv", "claude-between-2b")); + adapter.message({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { type: "message_start", message: { id: "between-2" } }, + }); + adapter.message({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: "B" }, + }, + }); + // Each between-run delta produced a commentary item; the fragment joined + // and is never phase-less, so it cannot become the run's answer. + expect(current.live.items.get("between-2")).toEqual({ + id: "between-2", + kind: "assistant", + text: "AB", + phase: "commentary", + }); + expect(retainedAnswer(current.live)).toBeUndefined(); +}); + const option = (id: string, confirmed: string) => ({ id, label: id, From e7c8b75f844b554c6251eb8f1612b9fed12fb3e9 Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Fri, 20 Nov 2026 18:10:18 +0000 Subject: [PATCH 14/17] Close native sessions in the Claude ingress regressions The tests emit items and deltas, which schedule a one-second output flush timer; when the file's afterAll closed the database first, a pending timer fired on the closed connection and surfaced as an intermittent unhandled error (exit 1 despite all tests passing). Close each session so its flush timer is cancelled before the database shuts down. --- test/native-activity-ingress.test.ts | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index 957e8f01..11f89389 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -263,7 +263,7 @@ it("records native turn tokens through adapter ingress without replay or cross-t expect(() => conversationUsage("intruder", "conv")).toThrow(); }); -it("records Claude result usage including cached inputs, excluding foreign results", () => { +it("records Claude result usage including cached inputs, excluding foreign results", async () => { const run = turn("conv", "usage-claude"); const sessions = new NativeSessions(); const current = start(sessions, "usage-claude-generation", run); @@ -305,6 +305,7 @@ it("records Claude result usage including cached inputs, excluding foreign resul output_tokens: 20, cache_read_tokens: 50, }); + await sessions.close(); }); // The projector picks the last non-commentary assistant item with text as a @@ -315,7 +316,7 @@ const retainedAnswer = (live: Live) => (i) => i.kind === "assistant" && i.phase !== "commentary" && i.text.trim(), ); -it("marks Claude child-session assistant messages as commentary so they cannot become the run's answer", () => { +it("marks Claude child-session assistant messages as commentary so they cannot become the run's answer", async () => { const sessions = new NativeSessions(); const run = turn("conv", "claude-child-commentary"); const current = start(sessions, "claude-child-generation", run); @@ -365,9 +366,10 @@ it("marks Claude child-session assistant messages as commentary so they cannot b phase: "commentary", }); expect(retainedAnswer(current.live)?.id).toBe("parent-msg"); + await sessions.close(); }); -it("establishes a commentary item before a child stream's first delta", () => { +it("establishes a commentary item before a child stream's first delta", async () => { const sessions = new NativeSessions(); const run = turn("conv", "claude-child-delta"); const current = start(sessions, "claude-child-delta-generation", run); @@ -408,9 +410,10 @@ it("establishes a commentary item before a child stream's first delta", () => { phase: "commentary", }); expect(retainedAnswer(current.live)).toBeUndefined(); + await sessions.close(); }); -it("merges a child delta into an earlier child assistant message instead of replacing its text", () => { +it("merges a child delta into an earlier child assistant message instead of replacing its text", async () => { const sessions = new NativeSessions(); const run = turn("conv", "claude-child-late-delta"); const current = start(sessions, "claude-child-late-delta-generation", run); @@ -461,6 +464,7 @@ it("merges a child delta into an earlier child assistant message instead of repl phase: "commentary", }); expect(retainedAnswer(current.live)).toBeUndefined(); + await sessions.close(); }); it("keeps a delayed child stream delta commentary across turn boundaries", async () => { @@ -534,6 +538,7 @@ it("keeps a delayed child stream delta commentary across turn boundaries", async phase: "commentary", }); expect(retainedAnswer(current.live)).toBeUndefined(); + await sessions.close(); }); it("does not overwrite a recall-window child message with a later delta's empty item", async () => { @@ -607,9 +612,10 @@ it("does not overwrite a recall-window child message with a later delta's empty phase: "commentary", }); expect(retainedAnswer(current.live)).toBeUndefined(); + await sessions.close(); }); -it("caps a single recall stream's cached seed at the display limit", () => { +it("caps a single recall stream's cached seed at the display limit", async () => { const sessions = new NativeSessions(); const run = turn("conv", "claude-cache-cap"); const current = start(sessions, "claude-cache-cap-generation", run); @@ -651,9 +657,10 @@ it("caps a single recall stream's cached seed at the display limit", () => { const stored = adapter.childText.get("child-big") as string; expect(Buffer.byteLength(stored)).toBeLessThanOrEqual(64000); expect(stored.endsWith("x".repeat(1000))).toBe(true); + await sessions.close(); }); -it("bounds the child text cache so a long session cannot accumulate child output", () => { +it("bounds the child text cache so a long session cannot accumulate child output", async () => { const sessions = new NativeSessions(); const run = turn("conv", "claude-cache-bound"); const current = start(sessions, "claude-cache-bound-generation", run); @@ -676,9 +683,10 @@ it("bounds the child text cache so a long session cannot accumulate child output expect(adapter.childText.has("bound-0")).toBe(false); expect(adapter.childText.size).toBeLessThanOrEqual(66); expect(adapter.childTextBytes).toBeLessThanOrEqual(4 * 1024 * 1024 + 64000); + await sessions.close(); }); -it("bounds the child text cache by entry count even for empty-text streams", () => { +it("bounds the child text cache by entry count even for empty-text streams", async () => { const sessions = new NativeSessions(); const run = turn("conv", "claude-cache-count"); const current = start(sessions, "claude-cache-count-generation", run); @@ -698,6 +706,7 @@ it("bounds the child text cache by entry count even for empty-text streams", () // never moves, so eviction must also bound the entry count. for (let i = 0; i < 600; i++) adapter.rememberChildText("empty-" + i, ""); expect(adapter.childText.size).toBeLessThanOrEqual(512); + await sessions.close(); }); it("still establishes a commentary item when a post-prompt delta's recall seed was lost", async () => { @@ -779,6 +788,7 @@ it("still establishes a commentary item when a post-prompt delta's recall seed w phase: "commentary", }); expect(retainedAnswer(current.live)).toBeUndefined(); + await sessions.close(); }); it("keeps an active-turn child message's text when a delayed delta arrives in the next turn", async () => { @@ -845,6 +855,7 @@ it("keeps an active-turn child message's text when a delayed delta arrives in th phase: "commentary", }); expect(retainedAnswer(current.live)).toBeUndefined(); + await sessions.close(); }); it("keeps an active-turn child stream's text when a delayed delta arrives in the next turn", async () => { @@ -911,6 +922,7 @@ it("keeps an active-turn child stream's text when a delayed delta arrives in the phase: "commentary", }); expect(retainedAnswer(current.live)).toBeUndefined(); + await sessions.close(); }); it("marks a delta-only child stream commentary when it arrives during recall", async () => { @@ -961,6 +973,7 @@ it("marks a delta-only child stream commentary when it arrives during recall", a phase: "commentary", }); expect(retainedAnswer(current.live)).toBeUndefined(); + await sessions.close(); }); it("keeps between-run child deltas commentary even across a window reset", async () => { @@ -1024,6 +1037,7 @@ it("keeps between-run child deltas commentary even across a window reset", async phase: "commentary", }); expect(retainedAnswer(current.live)).toBeUndefined(); + await sessions.close(); }); const option = (id: string, confirmed: string) => ({ From 44744720a933dba9f102dae45b6aada199394d39 Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:12:33 +0000 Subject: [PATCH 15/17] Freeze completed child streams: ignore late child events A delayed delta or assistant message for a child stream whose turn already completed was re-established in the next run with the cached text. The projector recorded it as the next run's progress and its native_items upsert moved the row from the earlier run (misattributing the output and removing it from that run's stored history), and an idle delta could overwrite the saved preview after cache eviction. Ids are harvested at each turn's result into a bounded prior-ids set; any later child event for them is ignored entirely, so a completed stream's native history stays as it was and no child output is ever re-attributed to a later run. New ids in the recall or between-turn window still fold or establish commentary items, so a child fragment can never become a phase-less, answer-eligible item. --- src/adapters/claude.ts | 50 +++++++++++++++++-------- test/native-activity-ingress.test.ts | 56 +++++++++++++--------------- 2 files changed, 59 insertions(+), 47 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index c19553af..d75dc114 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -71,21 +71,22 @@ export class Claude extends DirectAdapter implements Adapter { // again at the next new user turn, so a delayed delta re-establishes its // commentary item in the fresh projector window. private childItems = new Set(); - // Last-known text per child item id: the full assistant message (written - // whether a turn is open or not) plus any deltas seen before the next - // prompt. Kept across prompt() and the result (unlike childItems) so a - // re-established item in a fresh window carries the known text instead of - // replacing it with empty — a delayed delta for an earlier message id must - // append, not overwrite its stored text. Each entry is capped at the - // projector's display-preview limit and the total is byte-capped at the - // projector's own display-window scale, evicting the oldest ids, so a - // long session that repeatedly uses subagents cannot grow adapter memory - // with copies of child output. The map is bounded by both bytes and entry - // count: empty or tiny deltas would otherwise add entries without moving - // the byte counter. Eviction only ever drops the oldest ids (the least - // likely to still receive a delayed delta); a re-established item for an - // evicted id starts from the fragment, while its earlier text stays in - // that id's own run's progress rows. + // Child item ids whose stream completed in an earlier turn. A completed + // child stream is frozen: a late delta or assistant message for it must + // never re-create its item in a later run (that would move or overwrite + // the earlier run's native row and misattribute the output), so such + // events are ignored entirely. Ids are harvested at each turn's result + // and bounded so the set stays small for the adapter's lifetime. + private priorChildIds = new Set(); + // Last-known text per child item id for the current (or upcoming) turn: + // the full assistant message (written whether a turn is open or not) plus + // any deltas seen before the next prompt. Kept across prompt() (unlike + // childItems) so a re-established item in a fresh window carries the known + // text instead of replacing it with empty; cleared at the result, where + // its ids move into priorChildIds. Each entry is capped at the projector's + // display-preview limit and the map is bounded by both bytes and entry + // count, so a long session cannot grow adapter memory with copies of + // child output. private childText = new Map(); private childTextBytes = 0; private rememberChildText(id: string, text: string) { @@ -585,6 +586,10 @@ export class Claude extends DirectAdapter implements Adapter { } if (e.type === "content_block_delta" && e.delta.type === "text_delta") { const id = this.messageIds.get(stream) ?? m.uuid; + // A child stream whose turn completed is frozen; a late delta must + // not re-create its item in this run (it would move or overwrite + // the earlier run's native row), so ignore it entirely. + if (m.parent_tool_use_id && this.priorChildIds.has(id)) return; if (m.parent_tool_use_id && !this.active) { // Between turns the projector may drop a bare delta (no run) or // attach the next run during recall before active flips true. In @@ -667,8 +672,11 @@ export class Claude extends DirectAdapter implements Adapter { if (text) { // Remember the emitted id and its text so a later delta merges into // this item instead of establishing an empty one that replaces it, - // even when the delta arrives in a later turn. + // even when the delta arrives in a later turn. A child stream whose + // turn completed is frozen: ignore late assistant messages for it so + // its recorded history stays as it is. if (m.parent_tool_use_id) { + if (this.priorChildIds.has(m.message.id)) return; this.childItems.add(m.message.id); this.rememberChildText(m.message.id, text); } @@ -726,8 +734,18 @@ export class Claude extends DirectAdapter implements Adapter { if (usage) this.emit({ type: "usage", usage }); if (this.steering.result()) return; this.active = false; + // The turn's child streams are now complete; freeze their ids so late + // events for them cannot move or overwrite this run's native history. + for (const id of this.childItems) this.priorChildIds.add(id); + for (const id of this.childText.keys()) this.priorChildIds.add(id); + while (this.priorChildIds.size > 4096) { + const oldest = this.priorChildIds.keys().next().value!; + this.priorChildIds.delete(oldest); + } this.messageIds.clear(); this.childItems.clear(); + this.childText.clear(); + this.childTextBytes = 0; for (const id of this.requests.keys()) this.emit({ type: "resolved", id }); this.requests.clear(); diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index 11f89389..e213b88d 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -467,11 +467,12 @@ it("merges a child delta into an earlier child assistant message instead of repl await sessions.close(); }); -it("keeps a delayed child stream delta commentary across turn boundaries", async () => { +it("ignores late child events for a stream whose turn already completed", async () => { const sessions = new NativeSessions(); const first = turn("conv", "claude-cross-turn-1"); const current = start(sessions, "claude-cross-turn-generation", first); sessions.state.startTurn(current.live, first); + const emitted: AdapterEvent[] = []; const adapter = new Claude( { harness: "claude", @@ -481,7 +482,10 @@ it("keeps a delayed child stream delta commentary across turn boundaries", async billing: "existing", resume: "claude-cross-turn", }, - current.emit, + (e) => { + emitted.push(e); + current.emit(e); + }, ) as any; adapter.active = true; adapter.native = { write: async () => undefined }; @@ -502,7 +506,11 @@ it("keeps a delayed child stream delta commentary across turn boundaries", async session_id: "claude-cross-turn", is_error: false, }); - // Between turns the child emits another assistant message for the stream. + // Between turns the child re-emits content for the completed stream, and + // after the next prompt a delayed delta arrives. Both are late events for + // a frozen stream and must be ignored: re-creating the item would move or + // overwrite turn 1's native row and misattribute the output. + emitted.length = 0; send({ type: "assistant", parent_tool_use_id: "task-1", @@ -512,7 +520,6 @@ it("keeps a delayed child stream delta commentary across turn boundaries", async content: [{ type: "text", text: "Child text two" }], }, }); - // Turn 2 starts and the child stream's delayed delta finally arrives. await adapter.prompt("next"); sessions.state.startTurn(current.live, turn("conv", "claude-cross-turn-2")); send({ @@ -528,15 +535,10 @@ it("keeps a delayed child stream delta commentary across turn boundaries", async delta: { type: "text_delta", text: " late" }, }, }); - // The fragment re-establishes a commentary item in the fresh window (the - // between-turns text is carried over, not dropped) rather than a phase-less - // one that could become the new run's answer. - expect(current.live.items.get("child-cross")).toEqual({ - id: "child-cross", - kind: "assistant", - text: "Child text two late", - phase: "commentary", - }); + expect( + emitted.filter((e) => e.type === "item" || e.type === "delta"), + ).toEqual([]); + expect(current.live.items.get("child-cross")).toBeUndefined(); expect(retainedAnswer(current.live)).toBeUndefined(); await sessions.close(); }); @@ -832,7 +834,9 @@ it("keeps an active-turn child message's text when a delayed delta arrives in th current.live, turn("conv", "claude-delayed-delta-2"), ); - // A delayed delta for the same child message id finally arrives. + // A delayed delta for the same child message id finally arrives. The + // stream's turn completed, so the event is ignored: re-creating the item + // would move turn 1's native row to this run and misattribute its text. send({ type: "stream_event", parent_tool_use_id: "task-1", @@ -846,14 +850,9 @@ it("keeps an active-turn child message's text when a delayed delta arrives in th delta: { type: "text_delta", text: " more" }, }, }); - // The re-established item carries the earlier full text; the delta appends - // instead of overwriting the retained child history. - expect(current.live.items.get("child-old")).toEqual({ - id: "child-old", - kind: "assistant", - text: "Full active text more", - phase: "commentary", - }); + // Turn 1's recorded child text is left alone; nothing is attributed to + // this run for the completed stream. + expect(current.live.items.get("child-old")).toBeUndefined(); expect(retainedAnswer(current.live)).toBeUndefined(); await sessions.close(); }); @@ -897,7 +896,9 @@ it("keeps an active-turn child stream's text when a delayed delta arrives in the session_id: "claude-active-delta", is_error: false, }); - // Turn 2 starts; a delayed delta for the same stream arrives. + // A delayed delta for the same stream arrives. The stream's turn + // completed, so the event is ignored: the earlier text stays with its own + // run instead of being attributed to this one. await adapter.prompt("next"); sessions.state.startTurn(current.live, turn("conv", "claude-active-delta-2")); send({ @@ -913,14 +914,7 @@ it("keeps an active-turn child stream's text when a delayed delta arrives in the delta: { type: "text_delta", text: "B" }, }, }); - // The re-established item carries the streamed "A" from the earlier turn; - // the delayed "B" appends instead of replacing it. - expect(current.live.items.get("child-delta")).toEqual({ - id: "child-delta", - kind: "assistant", - text: "AB", - phase: "commentary", - }); + expect(current.live.items.get("child-delta")).toBeUndefined(); expect(retainedAnswer(current.live)).toBeUndefined(); await sessions.close(); }); From 69781245d8d7b5b6366be7dfe8a6fa240e3105a5 Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:10:47 +0000 Subject: [PATCH 16/17] Keep completed-stream ids forever; merge recall deltas; keep tool updates Three review findings: the prior-ids set's 4,096 cap let an old id's late event be treated as new and overwrite its completed history (the set is now ids-only and never evicted); a post-prompt delta after recall-window cache eviction re-established an empty item over the retained text (childItems is now kept across prompt so the delta merges into the retained commentary item instead); and a frozen mixed assistant frame dropped its tool update alongside the intended text suppression (only the text item is suppressed; tool_use blocks still emit). --- src/adapters/claude.ts | 40 +++--- test/native-activity-ingress.test.ts | 193 ++++++++++++++++++++++++--- 2 files changed, 198 insertions(+), 35 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index d75dc114..ad9a14f4 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -76,7 +76,8 @@ export class Claude extends DirectAdapter implements Adapter { // never re-create its item in a later run (that would move or overwrite // the earlier run's native row and misattribute the output), so such // events are ignored entirely. Ids are harvested at each turn's result - // and bounded so the set stays small for the adapter's lifetime. + // and kept for the adapter's lifetime — they are ids only, and evicting + // one would let a late event treat a completed stream as new. private priorChildIds = new Set(); // Last-known text per child item id for the current (or upcoming) turn: // the full assistant message (written whether a turn is open or not) plus @@ -351,12 +352,12 @@ export class Claude extends DirectAdapter implements Adapter { async prompt(text: string, beforeDispatch?: () => void) { beforeDispatch?.(); this.interrupted = false; - // A new user turn clears the previous turn's child ids so a delayed - // child delta re-establishes its commentary item in the fresh projector - // window instead of leaving a phase-less fragment. Mid-turn steering - // follow-ups also call prompt() while a turn is active; they must keep - // the ids so their deltas still merge into the open items. - if (!this.active) this.childItems.clear(); + // childItems is kept across prompt(): an id folded or established for + // this cycle stays known, so a post-prompt delta for it merges into its + // retained commentary item instead of re-establishing an empty one over + // it (which could erase the retained text after cache eviction). The + // set is cleared at the turn's result, and late events for prior-turn + // ids are dropped, so keeping it cannot leave a phase-less fragment. this.active = true; await this.native.write({ type: "user", @@ -598,7 +599,10 @@ export class Claude extends DirectAdapter implements Adapter { // commentary item carrying the accumulated seed: the item is // never phase-less and its text preserves the stream (including // an evicted seed's id — the item then carries the fragment, not - // an empty seed). No separate delta is emitted here. + // an empty seed). No separate delta is emitted here. The id is + // remembered so a post-prompt delta merges into this item instead + // of re-establishing an empty one over it. + this.childItems.add(id); this.rememberChildText( id, (this.childText.get(id) ?? "") + e.delta.text, @@ -669,14 +673,15 @@ export class Claude extends DirectAdapter implements Adapter { .filter((b: any) => b.type === "text") .map((b: any) => b.text) .join("\n"); - if (text) { + // A child stream whose turn completed is frozen: a late assistant + // message for it must not re-create its item, but its tool updates are + // still emitted below so the trace keeps the tool arguments. + const frozen = + m.parent_tool_use_id && this.priorChildIds.has(m.message.id); + if (text && !frozen) { // Remember the emitted id and its text so a later delta merges into - // this item instead of establishing an empty one that replaces it, - // even when the delta arrives in a later turn. A child stream whose - // turn completed is frozen: ignore late assistant messages for it so - // its recorded history stays as it is. + // this item instead of establishing an empty one that replaces it. if (m.parent_tool_use_id) { - if (this.priorChildIds.has(m.message.id)) return; this.childItems.add(m.message.id); this.rememberChildText(m.message.id, text); } @@ -736,12 +741,11 @@ export class Claude extends DirectAdapter implements Adapter { this.active = false; // The turn's child streams are now complete; freeze their ids so late // events for them cannot move or overwrite this run's native history. + // The set is ids-only and kept for the adapter's lifetime: evicting an + // id would let a late event treat a completed stream as new and + // overwrite its recorded history. for (const id of this.childItems) this.priorChildIds.add(id); for (const id of this.childText.keys()) this.priorChildIds.add(id); - while (this.priorChildIds.size > 4096) { - const oldest = this.priorChildIds.keys().next().value!; - this.priorChildIds.delete(oldest); - } this.messageIds.clear(); this.childItems.clear(); this.childText.clear(); diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index e213b88d..bbbd15ab 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -711,7 +711,7 @@ it("bounds the child text cache by entry count even for empty-text streams", asy await sessions.close(); }); -it("still establishes a commentary item when a post-prompt delta's recall seed was lost", async () => { +it("does not erase a recall item's text when its seed is evicted before a later delta", async () => { const sessions = new NativeSessions(); const run = turn("conv", "claude-seed-lost"); const current = start(sessions, "claude-seed-lost-generation", run); @@ -735,12 +735,14 @@ it("still establishes a commentary item when a post-prompt delta's recall seed w adapter.native = { write: async () => undefined }; const send = (m: any) => adapter.message({ session_id: "claude-seed-lost", ...m }); - // Turn 1 ends; the child's full message arrives while no turn is open. + // Turn 1 ends; the next run attaches and, during recall, the child's full + // message is retained in this run's window. adapter.message({ type: "result", session_id: "claude-seed-lost", is_error: false, }); + sessions.state.startTurn(current.live, turn("conv", "claude-seed-lost-2")); send({ type: "assistant", parent_tool_use_id: "task-1", @@ -750,11 +752,10 @@ it("still establishes a commentary item when a post-prompt delta's recall seed w content: [{ type: "text", text: "Retained text" }], }, }); - // The recall seed is missing for this id (as after extreme cache - // pressure); the id is also not in the new turn's cleared item window. + // The recall seed is evicted here (as after extreme cache pressure), but + // the retained commentary item in this run's window still holds the text. adapter.childText.delete("child-seed-lost"); await adapter.prompt("next"); - sessions.state.startTurn(current.live, turn("conv", "claude-seed-lost-2")); emitted.length = 0; send({ type: "stream_event", @@ -769,24 +770,16 @@ it("still establishes a commentary item when a post-prompt delta's recall seed w delta: { type: "text_delta", text: " more" }, }, }); - // The delta is still preceded by a commentary item, so the fresh window's - // item is never phase-less and cannot become the new run's answer. + // The delta merges into the retained commentary item (no empty item is + // re-established over its text), so the later fragment appends and the + // item stays commentary. expect(emitted).toEqual([ - { - type: "item", - item: { - id: "child-seed-lost", - kind: "assistant", - text: "", - phase: "commentary", - }, - }, { type: "delta", id: "child-seed-lost", text: " more" }, ]); expect(current.live.items.get("child-seed-lost")).toEqual({ id: "child-seed-lost", kind: "assistant", - text: " more", + text: "Retained text more", phase: "commentary", }); expect(retainedAnswer(current.live)).toBeUndefined(); @@ -1034,6 +1027,172 @@ it("keeps between-run child deltas commentary even across a window reset", async await sessions.close(); }); +it("drops late events for a completed child stream even after thousands of other ids", async () => { + const sessions = new NativeSessions(); + const run = turn("conv", "claude-prior-many"); + const current = start(sessions, "claude-prior-many-generation", run); + sessions.state.startTurn(current.live, run); + const emitted: AdapterEvent[] = []; + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-prior-many", + }, + (e) => { + emitted.push(e); + current.emit(e); + }, + ) as any; + adapter.active = true; + adapter.native = { write: async () => undefined }; + const send = (m: any) => + adapter.message({ session_id: "claude-prior-many", ...m }); + // One turn completes thousands of child streams; the first id must stay + // frozen no matter how many others complete after it. + send({ + type: "assistant", + parent_tool_use_id: "task-1", + message: { + id: "child-first", + role: "assistant", + content: [{ type: "text", text: "First child text" }], + }, + }); + for (let i = 0; i < 6005; i++) + send({ + type: "assistant", + parent_tool_use_id: "task-" + (2 + i), + message: { + id: "overflow-" + i, + role: "assistant", + content: [{ type: "text", text: "x" }], + }, + }); + adapter.message({ + type: "result", + session_id: "claude-prior-many", + is_error: false, + }); + await adapter.prompt("next"); + sessions.state.startTurn(current.live, turn("conv", "claude-prior-many-2")); + emitted.length = 0; + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { type: "message_start", message: { id: "child-first" } }, + }); + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: " late" }, + }, + }); + // The completed stream stays frozen — its id is never evicted from the + // prior-id set, so the late delta cannot re-create or overwrite it. + expect( + emitted.filter((e) => e.type === "item" || e.type === "delta"), + ).toEqual([]); + expect(current.live.items.get("child-first")).toBeUndefined(); + expect(retainedAnswer(current.live)).toBeUndefined(); + await sessions.close(); +}); + +it("still emits a frozen child frame's tool update while suppressing its text", async () => { + const conversation = "claude-frozen-tool"; + seedConversation(db, { + id: conversation, + owner_id: "owner", + title: "t", + created_at: 0, + }); + db.prepare( + "INSERT INTO companion_sessions(worktree_agent_id,conversation_id,harness,project,updated_at) VALUES('fixture-agent',?,'codex',?,0)", + ).run(conversation, dir); + const sessions = new NativeSessions(); + const run = turn(conversation, "claude-frozen-tool"); + const current = start( + sessions, + "claude-frozen-tool-generation", + run, + conversation, + ); + sessions.state.startTurn(current.live, run); + const emitted: AdapterEvent[] = []; + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-frozen-tool", + }, + (e) => { + emitted.push(e); + current.emit(e); + }, + ) as any; + adapter.active = true; + const send = (m: any) => + adapter.message({ session_id: "claude-frozen-tool", ...m }); + // Turn 1 records the completed stream; a late frame re-emits it WITH a + // tool_use block alongside its text. + send({ + type: "assistant", + parent_tool_use_id: "task-1", + message: { + id: "child-tool", + role: "assistant", + content: [{ type: "text", text: "Late text" }], + }, + }); + adapter.message({ + type: "result", + session_id: "claude-frozen-tool", + is_error: false, + }); + emitted.length = 0; + send({ + type: "assistant", + parent_tool_use_id: "task-1", + message: { + id: "child-tool", + role: "assistant", + content: [ + { type: "text", text: "Late text again" }, + { + type: "tool_use", + id: "tool-late", + name: "Read", + input: { file_path: "README.md" }, + }, + ], + }, + }); + // The frozen stream's text item is suppressed, but the frame's tool_use + // still yields its running item so the trace keeps the tool arguments. + expect( + emitted.filter((e) => e.type === "item" && e.item.kind === "assistant"), + ).toEqual([]); + expect(emitted).toContainEqual({ + type: "item", + item: { + id: "tool-late", + kind: "tool", + title: "Read", + text: JSON.stringify({ file_path: "README.md" }, null, 2), + status: "running", + }, + }); + await sessions.close(); +}); + const option = (id: string, confirmed: string) => ({ id, label: id, From c18012904d30ed9f2da6cae37151954d579cc167 Mon Sep 17 00:00:00 2001 From: Jamie Asefa <13409617+j-asefa@users.noreply.github.com> Date: Fri, 20 Nov 2026 21:50:34 +0000 Subject: [PATCH 17/17] Clear child ids at a new turn so post-dispatch deltas stay commentary Review of 69781245d found that keeping childItems across prompt() let a child stream folded between runs skip its commentary item after the next dispatch: attaching the run resets the projector window and the folded item has no run, so the post-dispatch delta created a phase-less fragment that was eligible as the answer. prompt() again clears the ids when no turn is open, so the delta re-establishes its seeded commentary item. Trade-off, documented in the adapter: when a stream's seed was evicted (over 512 streams or 4 MiB in one turn cycle) the re-established item carries only the new fragment, so that progress preview loses earlier text. It is never phase-less. Co-Authored-By: Claude Opus 5.5 --- src/adapters/claude.ts | 22 +++---- test/native-activity-ingress.test.ts | 85 ++++++++++++++++++++++++++-- 2 files changed, 92 insertions(+), 15 deletions(-) diff --git a/src/adapters/claude.ts b/src/adapters/claude.ts index ad9a14f4..80976625 100644 --- a/src/adapters/claude.ts +++ b/src/adapters/claude.ts @@ -352,12 +352,17 @@ export class Claude extends DirectAdapter implements Adapter { async prompt(text: string, beforeDispatch?: () => void) { beforeDispatch?.(); this.interrupted = false; - // childItems is kept across prompt(): an id folded or established for - // this cycle stays known, so a post-prompt delta for it merges into its - // retained commentary item instead of re-establishing an empty one over - // it (which could erase the retained text after cache eviction). The - // set is cleared at the turn's result, and late events for prior-turn - // ids are dropped, so keeping it cannot leave a phase-less fragment. + // A new user turn clears the child ids: attaching the run resets the + // projector's item window, and an item folded between runs has no run, + // so a post-dispatch delta must re-establish its commentary item (seeded + // from childText) or the projector would create a phase-less fragment + // that is eligible as the answer. Mid-turn steering follow-ups also call + // prompt() while a turn is active; they keep the ids so their deltas + // still merge into the open items. Trade-off: if a stream's seed was + // evicted from childText (over 512 streams or 4 MiB in one turn cycle), + // the re-established item carries only the new fragment, so that + // stream's progress preview loses earlier text. It is never phase-less. + if (!this.active) this.childItems.clear(); this.active = true; await this.native.write({ type: "user", @@ -599,10 +604,7 @@ export class Claude extends DirectAdapter implements Adapter { // commentary item carrying the accumulated seed: the item is // never phase-less and its text preserves the stream (including // an evicted seed's id — the item then carries the fragment, not - // an empty seed). No separate delta is emitted here. The id is - // remembered so a post-prompt delta merges into this item instead - // of re-establishing an empty one over it. - this.childItems.add(id); + // an empty seed). No separate delta is emitted here. this.rememberChildText( id, (this.childText.get(id) ?? "") + e.delta.text, diff --git a/test/native-activity-ingress.test.ts b/test/native-activity-ingress.test.ts index bbbd15ab..57e80c72 100644 --- a/test/native-activity-ingress.test.ts +++ b/test/native-activity-ingress.test.ts @@ -711,7 +711,7 @@ it("bounds the child text cache by entry count even for empty-text streams", asy await sessions.close(); }); -it("does not erase a recall item's text when its seed is evicted before a later delta", async () => { +it("keeps a post-prompt delta commentary even when its recall seed was evicted", async () => { const sessions = new NativeSessions(); const run = turn("conv", "claude-seed-lost"); const current = start(sessions, "claude-seed-lost-generation", run); @@ -770,16 +770,27 @@ it("does not erase a recall item's text when its seed is evicted before a later delta: { type: "text_delta", text: " more" }, }, }); - // The delta merges into the retained commentary item (no empty item is - // re-established over its text), so the later fragment appends and the - // item stays commentary. + // A new turn cleared the child ids, so the delta re-establishes its + // commentary item before appending. With the seed evicted, the item + // carries only the fragment (the documented eviction trade-off: the + // progress preview loses earlier text), but it is never phase-less, so it + // cannot become the run's answer. expect(emitted).toEqual([ + { + type: "item", + item: { + id: "child-seed-lost", + kind: "assistant", + text: "", + phase: "commentary", + }, + }, { type: "delta", id: "child-seed-lost", text: " more" }, ]); expect(current.live.items.get("child-seed-lost")).toEqual({ id: "child-seed-lost", kind: "assistant", - text: "Retained text more", + text: " more", phase: "commentary", }); expect(retainedAnswer(current.live)).toBeUndefined(); @@ -1027,6 +1038,70 @@ it("keeps between-run child deltas commentary even across a window reset", async await sessions.close(); }); +it("re-establishes a between-run child stream as commentary after the next prompt", async () => { + const sessions = new NativeSessions(); + const run = turn("conv", "claude-between-3"); + const current = start(sessions, "claude-between-3-generation", run); + sessions.state.startTurn(current.live, run); + const adapter = new Claude( + { + harness: "claude", + executable: "", + project: dir, + version: "fixture", + billing: "existing", + resume: "claude-between-3", + }, + current.emit, + ) as any; + adapter.active = true; + adapter.native = { write: async () => undefined }; + const send = (m: any) => + adapter.message({ session_id: "claude-between-3", ...m }); + // Turn 1 ends; the child's first delta arrives between runs and is folded + // into a commentary item that no run owns. + adapter.message({ + type: "result", + session_id: "claude-between-3", + is_error: false, + }); + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { type: "message_start", message: { id: "between-3" } }, + }); + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: "A" }, + }, + }); + // The next run attaches (resetting the item window) and is dispatched; + // only then does the child's next delta arrive. + sessions.state.startTurn(current.live, turn("conv", "claude-between-3b")); + await adapter.prompt("next"); + send({ + type: "stream_event", + parent_tool_use_id: "task-1", + event: { + type: "content_block_delta", + delta: { type: "text_delta", text: "B" }, + }, + }); + // The delta re-established its seeded commentary item in the new window + // instead of leaving a phase-less fragment eligible as the answer. + expect(current.live.items.get("between-3")).toEqual({ + id: "between-3", + kind: "assistant", + text: "AB", + phase: "commentary", + }); + expect(retainedAnswer(current.live)).toBeUndefined(); + await sessions.close(); +}); + it("drops late events for a completed child stream even after thousands of other ids", async () => { const sessions = new NativeSessions(); const run = turn("conv", "claude-prior-many");