From b4ebfcd4b623036e79de0d45eaaefecc6f25af74 Mon Sep 17 00:00:00 2001 From: heunghingwan Date: Mon, 9 Nov 2026 14:56:54 +0800 Subject: [PATCH 1/3] fix(transcript): reconcile tools stranded running at the next round's start MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A tool whose terminal event never reached the UI mid-execution (lost across a disconnect window, or never published by the daemon) kept its "running" spinner through every later agent round: the SDK reducer drops session.tool.success unless the part is exactly running, and CodeNomad only reconciled at execution settlement — which a quickly following execution could also suppress, leaving the spinner stuck through that whole execution as well. When a session.step.started reduces (both the direct emit and the queued replay; the replay scan runs at the task boundary between chunks so a chunk's synchronous budget stays untouched), scan finished rounds — assistant rows whose time.completed is stamped — for tool parts still streaming or running. The loop feeds every tool result back before it continues, so such a part definitively lost its terminal event: reconcile it immediately with the same read the settlement uses (message key invalidate + completeSettlementRead). The active round's parallel tools are excluded, and a resyncing transcript leaves the repair to its authoritative read. A new settlementReadPending flag makes every reconciliation caller share one in-flight read instead of chaining a duplicate fetch: the SDK's invalidate marks an in-flight read to re-run, so skipping also avoids the invalidation that would chain it. A settlement publication suppressed by a newer execution still heals through later per-event projections of the reconciled reducer, so the repair converges in every ordering. Validated with two new cases in opencode-data-settlement.test.ts (reconcile at the next round's start; no reconcile for a tool running inside its own round), the full store test group (316 passing), and tsc. --- dev-docs/TRANSCRIPT.md | 2 +- .../stores/opencode-data-settlement.test.ts | 32 +++++++++++++ packages/ui/src/stores/opencode-data.ts | 47 +++++++++++++++++++ 3 files changed, 80 insertions(+), 1 deletion(-) 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..0d88aa1c9d 100644 --- a/packages/ui/src/stores/opencode-data-settlement.test.ts +++ b/packages/ui/src/stores/opencode-data-settlement.test.ts @@ -116,6 +116,38 @@ 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 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..d145d8d546 100644 --- a/packages/ui/src/stores/opencode-data.ts +++ b/packages/ui/src/stores/opencode-data.ts @@ -71,6 +71,9 @@ 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 started but not yet finished; a + * step-boundary reconcile shares it instead of chaining a second read. */ + settlementReadPending: boolean queue: QueuedTranscriptEvent[] onResynced?: (data: Data) => void } @@ -310,6 +313,7 @@ function ensureTranscript(instanceId: string, sessionId: string, directory: stri retryCount: 0, retireWhenDrained: false, executionEpoch: 0, + settlementReadPending: false, queue: [], } transcriptEntries.set(key, transcript) @@ -569,6 +573,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 +778,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,10 +981,16 @@ 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 { + // A reconciliation read already in flight reconciles the same rows and + // publishes them under the same fence; chaining another beneath it only + // duplicates the fetch. + if (transcript.settlementReadPending) return const epoch = transcript.executionEpoch + transcript.settlementReadPending = true void transcript.entry.data.session.message.sync(sessionId) .catch(() => undefined) .then(() => { + transcript.settlementReadPending = false // Publish unless a newer execution superseded this settlement: // same-round activity (a late terminal tool event) must not // suppress the repair. @@ -1002,6 +1023,32 @@ 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. */ +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 reconciles the same rows; invalidating + // beneath it would only chain a duplicate fetch. + if (transcript.settlementReadPending) 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 From d4decacf2aba07bd58c2358f4b158a0b572ecc7a Mon Sep 17 00:00:00 2001 From: heunghingwan Date: Mon, 9 Nov 2026 16:14:18 +0800 Subject: [PATCH 2/3] fix(transcript): scope shared reconciliation reads to their reducer and epoch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two regressions in the shared pending-read block, both from the PR review: Sharing an in-flight settlement read dropped a newer settlement's publication: a read A started by execution N's settlement, then a newer execution started and settled before A resolved — its terminal event's demand hit settlementReadPending and returned, and A's continuation refused to publish because its captured epoch was older, leaving the stranded tool running with nothing to repair it. The shared read now upgrades settlementReadEpoch to the demand's execution and publishes for the newest one when it resolves; only an execution newer than every recorded demand still suppresses publication. The pending flag also outlived the reducer that owned it: a read left unresolved against a replaced entry (pruning invalidation, authoritative resync) kept suppressing the healthy replacement's reconciliation until the abandoned request settled. The pending read is now scoped to the DataEntry that started it — replaceTranscriptEntry releases it, a stale flag no longer blocks a new read, and an abandoned completion is fenced by owner identity so it can neither clear a successor's flag nor publish against it. The replay hook also gets its regression coverage: a stranded tool queued behind a full 200-message window reconciles through the drained step.started (fails when the drain hook is removed), and an active round's running tool does not reconcile at the replay's task boundary (fails when the scan drops the finished-round check). A comment records the bounded no-progress behavior of re-reading at later boundaries. Validated with the new settlement cases (shared-read publication, replaced-reducer abandonment; red on the unpatched head) and the full CI store group (324 passing) plus tsc. --- .../stores/opencode-data-settlement.test.ts | 68 ++++++++++++++++++- packages/ui/src/stores/opencode-data.ts | 61 ++++++++++++----- .../stores/opencode-transcript-replay.test.ts | 47 +++++++++++++ 3 files changed, 158 insertions(+), 18 deletions(-) diff --git a/packages/ui/src/stores/opencode-data-settlement.test.ts b/packages/ui/src/stores/opencode-data-settlement.test.ts index 0d88aa1c9d..f21a80f750 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 }) @@ -148,6 +151,67 @@ test("a tool running inside its own round is not reconciled", async () => { } finally { f.cleanup() } }) +test("a settlement arriving while a shared read is in flight still publishes", async () => { + const f = fixture("native-settlement-shared-epoch") + 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. + f.emit("session.execution.started", { sessionID: "s" }) + f.emit("session.execution.succeeded", { sessionID: "s" }) + for (const read of f.reads) read.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 shared read must publish for the newer settlement's demand") + } 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 d145d8d546..18e29f6c05 100644 --- a/packages/ui/src/stores/opencode-data.ts +++ b/packages/ui/src/stores/opencode-data.ts @@ -71,9 +71,16 @@ 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 started but not yet finished; a - * step-boundary reconcile shares it instead of chaining a second read. */ + /** 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 execution epoch the pending read owes a publication for; a demand + * arriving mid-read — a newer settlement or a step boundary — upgrades it, + * so sharing the fetch never drops the newest publication demand. */ + settlementReadEpoch: number queue: QueuedTranscriptEvent[] onResynced?: (data: Data) => void } @@ -314,6 +321,7 @@ function ensureTranscript(instanceId: string, sessionId: string, directory: stri retireWhenDrained: false, executionEpoch: 0, settlementReadPending: false, + settlementReadEpoch: 0, queue: [], } transcriptEntries.set(key, transcript) @@ -324,6 +332,10 @@ 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.entry = next previous.dispose() transcript.entryRevision[1]((value) => value + 1) @@ -981,22 +993,33 @@ 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 { - // A reconciliation read already in flight reconciles the same rows and - // publishes them under the same fence; chaining another beneath it only - // duplicates the fetch. - if (transcript.settlementReadPending) return + // A reconciliation read in flight against this reducer reconciles the same + // rows: share the fetch instead of chaining a duplicate beneath it. The + // demand still upgrades to the current execution epoch, so the shared read + // resolves publishing for the newest settlement rather than dropping it. + if (transcript.settlementReadPending && transcript.settlementReadEntry === transcript.entry) { + transcript.settlementReadEpoch = transcript.executionEpoch + return + } + const entry = transcript.entry const epoch = transcript.executionEpoch transcript.settlementReadPending = true - void transcript.entry.data.session.message.sync(sessionId) + transcript.settlementReadEntry = entry + transcript.settlementReadEpoch = epoch + void entry.data.session.message.sync(sessionId) .catch(() => undefined) .then(() => { + // A replaced reducer abandons its read: the completion cannot clear a + // successor's flag or publish against it. + if (transcript.settlementReadEntry !== entry) return transcript.settlementReadPending = false - // Publish unless a newer execution superseded this settlement: - // same-round activity (a late terminal tool event) must not - // suppress the repair. + transcript.settlementReadEntry = 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) }) } @@ -1035,13 +1058,19 @@ function hasStrandedFinishedRoundTool(messages: SessionMessageInfo[]): boolean { * 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. */ + * 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 reconciles the same rows; invalidating - // beneath it would only chain a duplicate fetch. - if (transcript.settlementReadPending) 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. 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") From 086992265e7587e3edcb638a499b7ffab1d8e7a6 Mon Sep 17 00:00:00 2001 From: heunghingwan Date: Mon, 9 Nov 2026 21:22:35 +0800 Subject: [PATCH 3/3] fix(transcript): follow the SDK's current reconciliation promise to publication MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A demand arriving while a reconciliation read A was in flight upgraded the recorded epoch but left publication bound to A's own continuation. When the newer settlement had invalidated the SDK message key, the SDK chained a trailing read B after A; A then resolved with stale data, published it and released the pending flag, and B — carrying the completed truth — merged into the reducer with no publication continuation of its own. The display kept the running spinner with no further event to repair it. completeSettlementRead now follows the SDK's current message.sync promise each time demand arrives: a shared in-flight fetch returns the same promise (no extra fetch, no re-follow), while a settlement that invalidated the key returns the trailing promise, and only the followed promise's owner publishes, releases the pending flag and runs retirement. The step-boundary reconcile still declines to re-enter while the current reducer's read is in flight (re-invalidating beneath it would chain a duplicate fetch), and the epoch comment no longer claims that path upgrades the demand. The shared-read regression now reproduces the reviewer's sequence: A resolves with the tool still running, the trailing B dispatches only after A settles, and B's resolution must heal the visible tool without another event — red on the previous head. Validated with the full CI store group (324 passing) and tsc. --- .../stores/opencode-data-settlement.test.ts | 13 ++++-- packages/ui/src/stores/opencode-data.ts | 41 +++++++++++-------- 2 files changed, 34 insertions(+), 20 deletions(-) diff --git a/packages/ui/src/stores/opencode-data-settlement.test.ts b/packages/ui/src/stores/opencode-data-settlement.test.ts index f21a80f750..6b40c76912 100644 --- a/packages/ui/src/stores/opencode-data-settlement.test.ts +++ b/packages/ui/src/stores/opencode-data-settlement.test.ts @@ -153,6 +153,7 @@ test("a tool running inside its own round is not reconciled", async () => { 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 }) @@ -162,14 +163,20 @@ test("a settlement arriving while a shared read is in flight still publishes", a // 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. + // 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" }) - for (const read of f.reads) read.resolve({ data: [completed], cursor: {} }) + // 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 shared read must publish for the newer settlement's demand") + assert.equal((tool as any)?.state?.status, "completed", "the latest read's publication must heal the tool without another event") } finally { f.cleanup() } }) diff --git a/packages/ui/src/stores/opencode-data.ts b/packages/ui/src/stores/opencode-data.ts index 18e29f6c05..9d7f06373d 100644 --- a/packages/ui/src/stores/opencode-data.ts +++ b/packages/ui/src/stores/opencode-data.ts @@ -77,9 +77,13 @@ type TranscriptEntry = { * nor publish against it. */ settlementReadPending: boolean settlementReadEntry?: DataEntry - /** The execution epoch the pending read owes a publication for; a demand - * arriving mid-read — a newer settlement or a step boundary — upgrades it, - * so sharing the fetch never drops the newest publication demand. */ + /** 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 @@ -336,6 +340,7 @@ function replaceTranscriptEntry(transcript: TranscriptEntry, next: DataEntry): v // 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) @@ -993,27 +998,29 @@ 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 { - // A reconciliation read in flight against this reducer reconciles the same - // rows: share the fetch instead of chaining a duplicate beneath it. The - // demand still upgrades to the current execution epoch, so the shared read - // resolves publishing for the newest settlement rather than dropping it. - if (transcript.settlementReadPending && transcript.settlementReadEntry === transcript.entry) { - transcript.settlementReadEpoch = transcript.executionEpoch - return - } const entry = transcript.entry - const epoch = transcript.executionEpoch + // 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 = epoch - void entry.data.session.message.sync(sessionId) + 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(() => { - // A replaced reducer abandons its read: the completion cannot clear a - // successor's flag or publish against it. - if (transcript.settlementReadEntry !== entry) return + // 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.