diff --git a/dev-docs/TRANSCRIPT.md b/dev-docs/TRANSCRIPT.md
index 2323c23e88..a1770550a8 100644
--- a/dev-docs/TRANSCRIPT.md
+++ b/dev-docs/TRANSCRIPT.md
@@ -15,7 +15,7 @@ Message content visibility and presets, token lines, tool renderers, native sess
- Markdown images of local file paths (`C:/…`, `file://`, absolute or relative POSIX paths) cannot load in the renderer. `lib/markdown.ts` renders them as their alt text in a `span.markdown-local-image`, and `components/markdown.tsx` swaps the label for an `
` with the source of a completed tool image of the same path already in the session's loaded messages (`lib/markdown-local-images.ts`: the image's file name or its single-image tool's `filePath`; Windows paths compare case-insensitively, a relative path must match one known path's end). Only blocks containing such a label read and track the session's tool parts. Never fetch local paths through a backend route for this; an unmatched path keeps its alt text.
- Code Mode reads native `metadata.toolCalls` in `tool-call/renderers/execute-data.ts`; keep call-list styling in `styles/messaging/tool-call/execute.css`, with native image/output ownership in the shared tool shell.
- Native websearch text is parsed conservatively by `tool-call/renderers/websearch-data.ts`; unknown/oversized responses use the shared raw renderer. Recognized provider-consent Forms retain the generic schema/answer path, with layout in `styles/messaging/tool-call/websearch.css`.
-- Session lifecycle features use OpenCode V2's published signals: one `session.execution.{succeeded,failed,interrupted}` per busy period (`lib/native-execution-events.ts`) and `session.retry.scheduled` for provider backoff. The schema-declared `session.idle`/`session.status` are never published; never wire a feature only to them. A terminal event is a hint until `session.active` confirms settlement, which alone announces "A session finished", only for root sessions ending in success, failure or an inactivity stop. Transcript reducers retire at settlement, deferred while prompts stay parked in their inbox or a user shell or unsettled tool call still needs reconciling there. A tool part still `streaming` (rendered "pending") once a settlement drained has lost its `called` transition: `session.tool.success` reduces solely from the running status (a later `failed` can still settle it). Symmetrically, admission drops a `session.tool.called` whose newest matching part already holds a terminal status: the reducer would overwrite the settled state wholesale (flipping completed tool images back to "running" until a settlement read healed them), while a legitimate re-call is always preceded by a fresh `session.tool.input.started` part that becomes the reducer's match. The SDK reducer already answers a terminal event whose transcript holds a streaming or running tool by invalidating and re-reading messages, but that refresh is dropped while the stream is not connected and never publishes its result; the terminal event therefore finishes the read itself (`finishOpenCodeDataEvent`: one `message.sync` that shares the SDK's in-flight read when connected and starts it when not) and projects the reconciled page, which keeps the display window's membership. Only a newer admitted execution suppresses that publication — same-round activity such as a late terminal tool event must not leave the repair unpublished. Non-event settlement evidence finishes the same read through the same fence: the liveness activity read observing that a run the UI still believed working has settled (`observeNonEventSettlement`, reported by `session-api`), and an authoritative inbox sync that drops an item the reducer admitted (a delivery or cancellation without events, whose user message may never be admitted either). Token/cost lines (`components/message-usage.tsx`) appear once per agent message: the row of an assistant message's final text (the one carrying "delete tools and reasoning") renders, once that message has native usage, the sum (`sumMessageUsage`) of its own usage and of every message holding a tool or reasoning part that cleanup selects (`technicalCleanupParts`). Reuse that selection rather than a separate projection. The line renders inside the content row, so it never shifts `` items or splits a technical group (whose Delete needs two tools); tool-only steps get no line. A message whose text is followed by tools also counts in the next message's line, as its tools belong to that selection. Sums cover the loaded transcript window only, like cleanup. Capture real streams with `scripts/test-session-lifecycle-native.mjs`.
+- Session lifecycle features use OpenCode V2's published signals: one `session.execution.{succeeded,failed,interrupted}` per busy period (`lib/native-execution-events.ts`) and `session.retry.scheduled` for provider backoff. The schema-declared `session.idle`/`session.status` are never published; never wire a feature only to them. A terminal event is a hint until `session.active` confirms settlement, which alone announces "A session finished", only for root sessions ending in success, failure or an inactivity stop. Transcript reducers retire at settlement, deferred while prompts stay parked in their inbox or a user shell or unsettled tool call still needs reconciling there. A tool part still `streaming` (rendered "pending") once a settlement drained has lost its `called` transition: `session.tool.success` reduces solely from the running status (a later `failed` can still settle it). Symmetrically, admission drops a `session.tool.called` whose newest matching part already holds a terminal status: the reducer would overwrite the settled state wholesale (flipping completed tool images back to "running" until a settlement read healed them), while a legitimate re-call is always preceded by a fresh `session.tool.input.started` part that becomes the reducer's match. The SDK reducer already answers a terminal event whose transcript holds a streaming or running tool by invalidating and re-reading messages, but that refresh is dropped while the stream is not connected and never publishes its result; the terminal event therefore finishes the read itself (`finishOpenCodeDataEvent`: one `message.sync` that shares the SDK's in-flight read when connected and starts it when not) and projects the reconciled page, which keeps the display window's membership. Only a newer admitted execution suppresses that publication — same-round activity such as a late terminal tool event must not leave the repair unpublished. Non-event settlement evidence finishes the same read through the same fence: the liveness activity read observing that a run the UI still believed working has settled (`observeNonEventSettlement`, reported by `session-api`), and an authoritative inbox sync that drops an item the reducer admitted (a delivery or cancellation without events, whose user message may never be admitted either). A tool still streaming or running in a finished round once a later `session.step.started` reduced (`reconcileStrandedRoundTools`, hooked after both the direct emit and the queued replay, where the scan runs at the task boundary between replay chunks) lost its terminal event mid-execution: the loop feeds every tool result back before it continues, so waiting for the settlement read would keep its spinner live through later rounds (and a quickly following execution would suppress that repair). That reconcile and every settlement read share one in-flight reconciliation per transcript (`settlementReadPending`); covered by `opencode-data-settlement.test.ts`. Token/cost lines (`components/message-usage.tsx`) appear once per agent message: the row of an assistant message's final text (the one carrying "delete tools and reasoning") renders, once that message has native usage, the sum (`sumMessageUsage`) of its own usage and of every message holding a tool or reasoning part that cleanup selects (`technicalCleanupParts`). Reuse that selection rather than a separate projection. The line renders inside the content row, so it never shifts `` items or splits a technical group (whose Delete needs two tools); tool-only steps get no line. A message whose text is followed by tools also counts in the next message's line, as its tools belong to that selection. Sums cover the loaded transcript window only, like cleanup. Capture real streams with `scripts/test-session-lifecycle-native.mjs`.
- Native transcript events reduce only through `stores/opencode-data.ts` (never add another partial-part reducer), which publishes bounded snapshots through `hydrateMessages` (message-v2/instance-store.ts); these per-event re-projections must not invalidate unchanged messages: `hydrateMessages` reuses the resident `MessageRecord` object whenever content, explicit timestamps and prompt-display metadata are unchanged, and an identical whole snapshot returns before any store write or session-revision bump. Part/info comparisons use allocation-free structural equality (`partDataEqual`), never `JSON.stringify`. The SDK reduce mutates rows in place, so reference identity can never prove a session unchanged — never add a reference-anchored projection skip. A session's reducer is replaced (authoritative resync after an overflow, rotation failure or reconnect; pruning invalidation) only through `replaceTranscriptEntry`, which bumps the transcript's `entryRevision`; reactive readers of the reducer, such as the inbox behind queued badges (`getOpenCodeSessionInbox`), track it so they rebind instead of keeping the disposed reducer's last state (`opencode-inbox-rebinding.test.ts`, `tests/browser/session-rendering.test.ts`).
- Event-driven projections coalesce to the frame level through `stores/opencode-projection-frame.ts`: events still reduce synchronously and in order, but the projection into the message store runs at most once per animation frame per session, always from the reducer's newest state (a bounded timer while the window is hidden, since hidden windows pause animation frames; environments without a frame scheduler keep the previous synchronous projection). Store readers lag at most one frame. Session selection writes (`writeSessionSelection`) and visibility transitions flush pending pages; transcript eviction and instance teardown cancel them; destructive events (`session.deleted`, `session.inbox.cancelled`, `session.revert.committed`) and forced authoritative publications still project synchronously and subsume the pending frame. An event admitted while its session was active but no longer active at frame time invalidates the loaded page so the next activation reads authoritatively. Covered by `opencode-projection-frame.test.ts` and `tests/browser/streaming-projection.test.ts`.
- Reducer page reads (the SDK's `message.sync` through the `message.list` proxy in `createDataEntry`) flush buffered compaction text, snapshot the session's live rows, fetch, flush again and answer with the page merged against that snapshot (`stores/opencode-data-read-merge.ts`), so buffered text is reduced exactly once: the page is the base and keeps its cursor, a live row new or changed since the snapshot keeps its live version (a row changed only in its root `time.completed`, which SDK step boundaries stamp, takes the page's version) except for its identified content parts, such as tool calls, left unchanged since the snapshot, which take the page's version so progress on one tool never hides authority for another, and rows created during the fetch and absent from the page ride along newest-first. Only events that remove or replace content (`invalidatesFetchedPage`: deletion, revert commit, inbox cancellation, compaction start/end/failure) restart the read; streamed text, reasoning, tool progress, compaction text and new rows merge, so a continuously streaming session completes its read in one fetch. Live versions are reconciled by the native full-text endings and the SDK's end-of-round refresh. A first latest-window load (`loadMessages` with no resident rows and no stored window) merges its 200-row page the same way and commits it while live revisions advance, then, unless the session is known idle, seeds a session reducer that holds no rows with the page's newest 20 rows, the SDK's own page size, without another read (`seedOpenCodeSessionMessages`), because the reducer applies streamed events only to messages it holds. Reloads and history windows keep the revision checks. Covered by `opencode-data-trailing-read.test.ts`, `opencode-data-read-merge.test.ts` and `session-api-running-open.test.ts`.
diff --git a/packages/ui/src/stores/opencode-data-settlement.test.ts b/packages/ui/src/stores/opencode-data-settlement.test.ts
index 4f3dd736a0..6b40c76912 100644
--- a/packages/ui/src/stores/opencode-data-settlement.test.ts
+++ b/packages/ui/src/stores/opencode-data-settlement.test.ts
@@ -5,7 +5,7 @@ import { sdkManager } from "../lib/sdk-manager.ts"
import { sseManager } from "../lib/sse-manager.ts"
import { addInstance, handleInstanceInvalidation, removeInstance } from "./instances.ts"
import { messageStoreBus } from "./message-v2/bus.ts"
-import { destroyOpenCodeData } from "./opencode-data.ts"
+import { destroyOpenCodeData, invalidateOpenCodeSessionContent } from "./opencode-data.ts"
import { handleNativeSessionEvent } from "./session-events.ts"
import { setActiveSession, setSessions } from "./session-state.ts"
@@ -35,7 +35,10 @@ function fixture(instanceId: string) {
session: {
active: () => active.promise,
get: async () => ({ id: sessionId, location: { directory: "/fixture" }, time: { created: 1, updated: 5 } }),
+ inbox: { list: async () => [] },
+ form: { list: async () => [] },
},
+ permission: { list: async () => [] },
message: { list: (input: { limit?: number }) => {
assert.equal(input.limit, 20, "this race must exercise the native reducer's history read")
const read = deferred()
@@ -59,7 +62,7 @@ function fixture(instanceId: string) {
}
const next = { sessionID: sessionId, assistantMessageID: "m2" }
return {
- reads, emit, next,
+ reads, emit, next, active,
start() {
const base = { sessionID: sessionId, assistantMessageID: "m1" }
emit("session.step.started", { ...base, agent: "build", model, started: 1 })
@@ -116,6 +119,106 @@ test("native terminal history settles under a newer streaming assistant in one r
} finally { f.cleanup() }
})
+test("a stranded running tool is reconciled when the next round begins", async () => {
+ const f = fixture("native-settlement-stranded-round")
+ try {
+ const base = { sessionID: "s", assistantMessageID: "m1" }
+ f.emit("session.step.started", { ...base, agent: "build", model, started: 1 })
+ f.emit("session.tool.input.started", { ...base, id: "tool", name: "read" })
+ f.emit("session.tool.called", { ...base, id: "tool", input: {} })
+ // The daemon's loop fed the tool's result back and continued with a new
+ // round, but the terminal tool event never arrived: the part is stranded
+ // running in a finished round while the execution keeps going.
+ f.emit("session.step.started", { ...f.next, agent: "build", model, started: 6 })
+ assert.equal(f.reads.length, 1, "the next round's start must reconcile the stranded tool without waiting for settlement")
+ f.reads[0].resolve({ data: [completed], cursor: {} })
+ await flush()
+ const m1 = messageStoreBus.getOrCreate("native-settlement-stranded-round").getMessage("m1")
+ const tool = Object.values(m1?.parts ?? {}).map((part: any) => part.data).find((part: any) => part.type === "tool")
+ assert.equal((tool as any)?.state?.status, "completed", "the stranded tool stayed running through the next round")
+ } finally { f.cleanup() }
+})
+
+test("a tool running inside its own round is not reconciled", async () => {
+ const f = fixture("native-settlement-active-round")
+ try {
+ const base = { sessionID: "s", assistantMessageID: "m1" }
+ f.emit("session.step.started", { ...base, agent: "build", model, started: 1 })
+ f.emit("session.tool.input.started", { ...base, id: "tool", name: "read" })
+ f.emit("session.tool.called", { ...base, id: "tool", input: {} })
+ f.emit("session.tool.progress", { ...base, id: "tool", metadata: {} })
+ assert.equal(f.reads.length, 0, "a tool running inside the active round is normal")
+ } finally { f.cleanup() }
+})
+
+test("a settlement arriving while a shared read is in flight still publishes", async () => {
+ const f = fixture("native-settlement-shared-epoch")
+ const running = { ...completed, content: [{ ...(completed.content[0] as any), state: { status: "running", input: { command: "pwd" }, metadata: {} } }] }
+ try {
+ const base = { sessionID: "s", assistantMessageID: "m1" }
+ f.emit("session.step.started", { ...base, agent: "build", model, started: 1 })
+ f.emit("session.tool.input.started", { ...base, id: "tool", name: "read" })
+ f.emit("session.tool.called", { ...base, id: "tool", input: {} })
+ // Execution N settles with the tool stranded running; its reconciliation
+ // read A starts and stays in flight.
+ f.emit("session.execution.succeeded", { sessionID: "s" })
+ assert.ok(f.reads.length >= 1, "settlement read A started")
+ // A newer execution starts and settles before A resolves; its terminal
+ // event invalidates the SDK message key and queues a trailing read B.
+ f.emit("session.execution.started", { sessionID: "s" })
+ f.emit("session.execution.succeeded", { sessionID: "s" })
+ // A resolves with the tool still running: only the trailing B carries
+ // the completed truth, so the publication must follow B, not A.
+ f.reads[0].resolve({ data: [running], cursor: {} })
+ for (let index = 0; index < 100 && f.reads.length < 2; index++) await flush()
+ assert.equal(f.reads.length, 2, "the trailing read B dispatched after A settled")
+ f.reads[1].resolve({ data: [completed], cursor: {} })
+ await flush()
+ const m1 = messageStoreBus.getOrCreate("native-settlement-shared-epoch").getMessage("m1")
+ const tool = Object.values(m1?.parts ?? {}).map((part: any) => part.data).find((part: any) => part.type === "tool")
+ assert.equal((tool as any)?.state?.status, "completed", "the latest read's publication must heal the tool without another event")
+ } finally { f.cleanup() }
+})
+
+test("a replaced reducer abandons its pending reconciliation read", async () => {
+ const f = fixture("native-settlement-replaced-entry")
+ const completedM2 = { ...completed, id: "m2", content: [{ type: "tool", id: "tool2", name: "read", time: { created: 8, ran: 9, completed: 10 }, state: { status: "completed", input: {}, content: [{ type: "text", text: "ok" }], metadata: {} } }] }
+ const runningM2 = { ...completedM2, content: [{ ...(completedM2.content[0] as any), state: { status: "running", input: {}, metadata: {} } }] }
+ try {
+ const base = { sessionID: "s", assistantMessageID: "m1" }
+ f.emit("session.step.started", { ...base, agent: "build", model, started: 1 })
+ f.emit("session.tool.input.started", { ...base, id: "tool", name: "read" })
+ f.emit("session.tool.called", { ...base, id: "tool", input: {} })
+ // The step boundary reconciles the stranded tool; its read stays
+ // unresolved against the reducer that started it.
+ f.emit("session.step.started", { ...f.next, agent: "build", model, started: 6 })
+ assert.equal(f.reads.length, 1)
+ // A second tool runs in the active round before the reducer is replaced.
+ f.emit("session.tool.input.started", { ...f.next, id: "tool2", name: "read" })
+ f.emit("session.tool.called", { ...f.next, id: "tool2", input: {} })
+ // Replace the reducer the way pruning does; its authoritative resync
+ // answers with the daemon's persisted rows, m2's tool still running.
+ invalidateOpenCodeSessionContent("native-settlement-replaced-entry", "s")
+ await new Promise(resolve => setTimeout(resolve, 60))
+ await flush()
+ assert.ok(f.reads.length >= 2, "the replacement reducer resynced authoritatively")
+ f.active.resolve({})
+ for (const read of f.reads.slice(1)) read.resolve({ data: [completed, runningM2], cursor: {} })
+ await flush()
+ // The next round finishing strands m2's tool on the healthy replacement:
+ // it must reconcile with its own read, not inherit the abandoned read's
+ // pending flag.
+ f.emit("session.step.started", { sessionID: "s", assistantMessageID: "m3", agent: "build", model, started: 12 })
+ await flush()
+ assert.equal(f.reads.length, 3, "the replacement's reconciliation must start its own read")
+ f.reads[2].resolve({ data: [completedM2], cursor: {} })
+ await flush()
+ const m2 = messageStoreBus.getOrCreate("native-settlement-replaced-entry").getMessage("m2")
+ const tool2 = Object.values(m2?.parts ?? {}).map((part: any) => part.data).find((part: any) => part.type === "tool")
+ assert.equal((tool2 as any)?.state?.status, "completed", "the replacement reconciled the second stranded tool")
+ } finally { f.cleanup() }
+})
+
test("a disposed native projection does not retry a delayed terminal history read", async () => {
const f = fixture("native-settlement-disposed")
try {
diff --git a/packages/ui/src/stores/opencode-data.ts b/packages/ui/src/stores/opencode-data.ts
index a9e594063a..9d7f06373d 100644
--- a/packages/ui/src/stores/opencode-data.ts
+++ b/packages/ui/src/stores/opencode-data.ts
@@ -71,6 +71,20 @@ type TranscriptEntry = {
/** Admitted `session.execution.started` events; a settlement's publication
* fence is a newer execution, not same-round activity. */
executionEpoch: number
+ /** A settlement-style reconciliation read in flight, scoped to the reducer
+ * entry that started it: replacing the entry abandons the read and its
+ * flag, and the abandoned completion can neither clear a successor's flag
+ * nor publish against it. */
+ settlementReadPending: boolean
+ settlementReadEntry?: DataEntry
+ /** The SDK reconciliation promise publication currently follows: a demand
+ * arriving mid-read may invalidate the message key and chain a trailing
+ * read, and the newest read's completion owns the publication. */
+ settlementReadPromise?: Promise
+ /** The execution epoch the followed read owes a publication for; a newer
+ * settlement arriving mid-read upgrades it, so sharing the fetch never
+ * drops the newest publication demand. */
+ settlementReadEpoch: number
queue: QueuedTranscriptEvent[]
onResynced?: (data: Data) => void
}
@@ -310,6 +324,8 @@ function ensureTranscript(instanceId: string, sessionId: string, directory: stri
retryCount: 0,
retireWhenDrained: false,
executionEpoch: 0,
+ settlementReadPending: false,
+ settlementReadEpoch: 0,
queue: [],
}
transcriptEntries.set(key, transcript)
@@ -320,6 +336,11 @@ function ensureTranscript(instanceId: string, sessionId: string, directory: stri
* one would keep its last state, e.g. a delivered prompt shown as queued. */
function replaceTranscriptEntry(transcript: TranscriptEntry, next: DataEntry): void {
const previous = transcript.entry
+ // The successor owns reconciliation from here; a read the previous entry
+ // started is abandoned with it.
+ transcript.settlementReadPending = false
+ transcript.settlementReadEntry = undefined
+ transcript.settlementReadPromise = undefined
transcript.entry = next
previous.dispose()
transcript.entryRevision[1]((value) => value + 1)
@@ -569,6 +590,11 @@ async function drainTranscriptQueue(
}
transcript.queue.shift()
entry.emit(queued.event)
+ if (queued.event.type === "session.step.started") {
+ // Keep each replay chunk's synchronous budget untouched: the scan runs
+ // at the next task boundary, never inside a chunk.
+ queueMicrotask(() => reconcileStrandedRoundTools(instanceId, sessionId, transcript))
+ }
if (!current()) return false
if (queued.publication) events.push(queued.event)
if (queued.onApplied) {
@@ -769,6 +795,12 @@ export function applyOpenCodeDataEvent(
}
}
entry.emit(event)
+ // A finished round's tool still running or streaming once a later round
+ // began lost its terminal event mid-execution: reconcile it at this step
+ // boundary instead of waiting for the execution's settlement.
+ if (event.type === "session.step.started" && transcript && typeof sessionId === "string") {
+ reconcileStrandedRoundTools(instanceId, sessionId, transcript)
+ }
if (coalesced) {
onDeferred?.(entry.data)
if (!transcript || (isTranscriptCurrent(instanceId, sessionId!, transcript) && transcript.entry === entry)) {
@@ -966,16 +998,35 @@ export function finishOpenCodeDataEvent(instanceId: string, event: OpenCodeEvent
* admitted execution supersedes the publication; same-round activity does
* not. */
function completeSettlementRead(instanceId: string, sessionId: string, transcript: TranscriptEntry): void {
- const epoch = transcript.executionEpoch
- void transcript.entry.data.session.message.sync(sessionId)
+ const entry = transcript.entry
+ // A reconciliation read in flight against this reducer reconciles the same
+ // rows: share its fetch instead of chaining a duplicate beneath it. The
+ // demand still upgrades the recorded epoch, and publication follows the
+ // SDK's current promise: a settlement that invalidated the message key
+ // chained a trailing read, and the newest read's completion — not the one
+ // already resolving — owns publishing the reconciled page.
+ transcript.settlementReadPending = true
+ transcript.settlementReadEntry = entry
+ transcript.settlementReadEpoch = transcript.executionEpoch
+ const promise = entry.data.session.message.sync(sessionId)
+ if (transcript.settlementReadPromise === promise) return
+ transcript.settlementReadPromise = promise
+ const followed = promise
+ void followed
.catch(() => undefined)
.then(() => {
- // Publish unless a newer execution superseded this settlement:
- // same-round activity (a late terminal tool event) must not
- // suppress the repair.
+ // A newer demand re-followed a later read, or a replaced reducer
+ // abandoned this one: only the followed promise's owner publishes.
+ if (transcript.settlementReadEntry !== entry || transcript.settlementReadPromise !== followed) return
+ transcript.settlementReadPending = false
+ transcript.settlementReadEntry = undefined
+ transcript.settlementReadPromise = undefined
+ // Publish unless an execution newer than every recorded demand
+ // superseded this settlement: same-round activity (a late terminal tool
+ // event) must not suppress the repair.
if (!isTranscriptCurrent(instanceId, sessionId, transcript)
- || transcript.executionEpoch !== epoch) return
- projectOpenCodeMessages(instanceId, sessionId, transcript.entry.data, true)
+ || transcript.executionEpoch !== transcript.settlementReadEpoch) return
+ projectOpenCodeMessages(instanceId, sessionId, entry.data, true)
retireDrainedTranscript(instanceId, sessionId, transcript)
})
}
@@ -1002,6 +1053,38 @@ function hasUnsettledToolRow(messages: SessionMessageInfo[]): boolean {
&& (part.state.status === "streaming" || part.state.status === "running")))
}
+/** Streaming or running tool parts in assistant rounds the native loop already
+ * completed; the active round's parallel tools are excluded. */
+function hasStrandedFinishedRoundTool(messages: SessionMessageInfo[]): boolean {
+ return messages.some((message) => message.type === "assistant" && message.time?.completed !== undefined
+ && message.content.some((part) => part.type === "tool"
+ && (part.state.status === "streaming" || part.state.status === "running")))
+}
+
+/** A finished round's tool still streaming or running once a later round
+ * began: the loop feeds every tool result back before it continues, so the
+ * terminal event was lost mid-execution. The settlement read that reconciles
+ * it must not wait for the execution to end — later rounds keep its spinner
+ * live, and a quickly following execution would suppress that repair.
+ *
+ * Re-reading is event-driven and bounded: an authoritative page that keeps
+ * the tool running makes each later step boundary issue one further read,
+ * never a loop — the daemon's own state is the progress guard. */
+function reconcileStrandedRoundTools(instanceId: string, sessionId: string, transcript: TranscriptEntry): void {
+ if (!isTranscriptCurrent(instanceId, sessionId, transcript)
+ || transcript.needsAuthoritativeResync || transcript.resyncing) return
+ // A settlement read already in flight against this reducer reconciles the
+ // same rows; invalidating beneath it would only chain a duplicate fetch.
+ // One started by a replaced reducer is abandoned with it and does not
+ // suppress this demand.
+ if (transcript.settlementReadPending && transcript.settlementReadEntry === transcript.entry) return
+ if (!hasStrandedFinishedRoundTool(transcript.entry.data.session.message.list(sessionId))) return
+ // Nothing invalidated the SDK's message key at a step boundary; a key an
+ // earlier sync completed would make this read a no-op.
+ transcript.entry.data.session.message.invalidate(sessionId)
+ completeSettlementRead(instanceId, sessionId, transcript)
+}
+
/** A `session.tool.called` whose newest matching part already settled. The
* daemon never publishes `called` for a settled call (its runner dies on the
* duplicate), and a legitimate re-call is always preceded by a fresh
diff --git a/packages/ui/src/stores/opencode-transcript-replay.test.ts b/packages/ui/src/stores/opencode-transcript-replay.test.ts
index d2d12de458..21eebb1003 100644
--- a/packages/ui/src/stores/opencode-transcript-replay.test.ts
+++ b/packages/ui/src/stores/opencode-transcript-replay.test.ts
@@ -168,6 +168,53 @@ test("real dispatcher skips queued ingress hydration and publishes bounded chunk
} finally { f.cleanup() }
})
+test("a stranded tool behind a full window reconciles through the queued replay", async ctx => {
+ ctx.mock.timers.enable({ apis: ["setTimeout"] })
+ const f = fixture("replay-stranded-tool", true)
+ const completedRow = {
+ id: "msg_tool", type: "assistant", agent: "build", model,
+ time: { created: 1, completed: 5 }, content: [{
+ type: "tool", id: "tool", name: "read", time: { created: 2, ran: 3, completed: 4 },
+ state: { status: "completed", input: { path: "a" }, metadata: {}, content: [{ type: "text", text: "ok" }] },
+ }],
+ }
+ let reads = 0
+ ;(f.client as any).message.list = async () => { reads += 1; return { data: [completedRow], cursor: {} } }
+ const base = { assistantMessageID: "msg_tool", ordinal: 0 }
+ try {
+ f.dispatch("session.step.started", { ...base, agent: "build", model, started: 1 })
+ f.dispatch("session.tool.input.started", { ...base, id: "tool", name: "read" })
+ f.dispatch("session.tool.called", { ...base, id: "tool", input: { path: "a" }, executed: false })
+ // The next round's start behind the full window is the stranded tool's
+ // reconciliation trigger inside the queued replay.
+ f.dispatch("session.step.started", { assistantMessageID: "msg_next", agent: "build", model, started: 6 })
+ await finish(ctx, () => (f.data().session.message.get(sessionId, "msg_tool") as any)
+ ?.content.find((part: any) => part.type === "tool")?.state.status === "completed")
+ assert.ok(reads >= 1, "the replay's step-boundary reconciliation read ran")
+ } finally { f.cleanup() }
+})
+
+test("an active round's running tool does not reconcile at the replay boundary", async ctx => {
+ ctx.mock.timers.enable({ apis: ["setTimeout"] })
+ const f = fixture("replay-active-round", true)
+ let reads = 0
+ ;(f.client as any).message.list = async () => { reads += 1; return { data: [], cursor: {} } }
+ const base = { assistantMessageID: "msg_live", ordinal: 0 }
+ try {
+ f.dispatch("session.step.started", { ...base, agent: "build", model, started: 1 })
+ f.dispatch("session.tool.input.started", { ...base, id: "tool", name: "read" })
+ f.dispatch("session.tool.called", { ...base, id: "tool", input: { path: "a" }, executed: false })
+ // The burst drains inside one replay; at its task boundary the active
+ // round legitimately holds the running tool.
+ await finish(ctx, () => Boolean((f.data().session.message.get(sessionId, "msg_live") as any)
+ ?.content.some((part: any) => part.type === "tool" && part.state.status === "running")))
+ ctx.mock.timers.tick(0); await microtasks(); ctx.mock.timers.tick(0); await microtasks()
+ const tool = (f.data().session.message.get(sessionId, "msg_live") as any).content.find((part: any) => part.type === "tool")
+ assert.equal(tool.state.status, "running", "no reconciliation may fire for the active round")
+ assert.equal(reads, 0, "no reconciliation read may run for the active round")
+ } finally { f.cleanup() }
+})
+
test("time budget wins before the count backstop; legacy callbacks remain ordered and distinct", async ctx => {
ctx.mock.timers.enable({ apis: ["setTimeout"] })
const f = fixture("replay-callbacks")