From cc63492c513f9b1960cf41d0ab4ddeb32b081eda Mon Sep 17 00:00:00 2001 From: heunghingwan Date: Mon, 9 Nov 2026 15:15:08 +0800 Subject: [PATCH 1/8] fix(transcript): keep a delivered prompt above the reply it triggers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A client watching a session that another client prompted showed the sent message hanging at the very bottom, below the streaming reply: with two pages open, the prompt arrived through session.inbox.enqueued, the reply's assistant row was appended while the prompt was still parked, and session.inbox.delivered then answered by moving the prompt's row to the reducer's tail — below its own reply. Every later live projection carried that order, so the message stayed sunk until an authoritative read replaced the reducer. Record, at delivered admission, the reducer row that followed the prompt's row; live projections restore each delivered prompt directly above that row, which matches the native page order (verified against the running service's message list). The record lives on the transcript entry and is consumed once both rows hold that order or either is gone; parked prompts and queued deliveries render exactly as before. Validation: a new browser test through the real SessionView and native dispatcher covers both the faithful admission order and admission after the reply started streaming (failed on dev, passes now); 253 focused store tests, UI typecheck and the session-rendering browser suite stay green. --- dev-docs/TRANSCRIPT.md | 2 +- packages/ui/src/stores/opencode-data.test.ts | 6 +- packages/ui/src/stores/opencode-data.ts | 43 ++++++ .../ui/tests/browser/fixtures/session.tsx | 14 ++ .../browser/inbox-delivery-order.test.ts | 122 ++++++++++++++++++ 5 files changed, 185 insertions(+), 2 deletions(-) create mode 100644 packages/ui/tests/browser/inbox-delivery-order.test.ts diff --git a/dev-docs/TRANSCRIPT.md b/dev-docs/TRANSCRIPT.md index 324a4a46af..98a9e51461 100644 --- a/dev-docs/TRANSCRIPT.md +++ b/dev-docs/TRANSCRIPT.md @@ -4,7 +4,7 @@ Message content visibility and presets, token lines, tool renderers, native sess ## Agent conventions -- Partial live projections preserve omitted resident message runs beside their preceding shared row, with leading history before the snapshot and pending optimistic sends at the tail. Shared rows follow the incoming native order. HTTP pages can contain later steps whose events are still in transit; message IDs and wall-clock timestamps remain identity/display data rather than transcript sort keys. +- Partial live projections preserve omitted resident message runs beside their preceding shared row, with leading history before the snapshot and pending optimistic sends at the tail. Shared rows follow the incoming native order. A prompt delivered from the session inbox keeps the row it held at admission: the SDK's `session.inbox.delivered` moves the prompt's row to the reducer's tail, so the projection restores each delivered prompt above the row that followed it at admission (recorded per transcript, consumed once both rows hold that order or either is gone); a reply appended between enqueue and admission must never render above the prompt that triggered it. HTTP pages can contain later steps whose events are still in transit; message IDs and wall-clock timestamps remain identity/display data rather than transcript sort keys. - The message-content popup and Chat settings share `components/transcript-visibility.ts` and the semantic icons from `components/message-content-icons.ts`; tool presentation metadata lives independently of renderers in `components/tool-call/tool-presentation.ts`. Popup styles live in `styles/components/transcript-filters.css`. Popup rows show a requested state at once and keep it until the save carrying it settles. Each save re-renders the transcript, so a drag sweep (`dev-docs/UI_CONVENTIONS.md`) saves its rows once, on release (`afterSweep`). Saves run in order, each built from the preferences the previous one returned; a batch of rows is sealed as it joins the queue, so a later click never jumps ahead of a preset change nor rides along with a sweep still held. - Transcript presets are Nothing (hides every row, including all tools), Minimal, Balanced and Everything (`TRANSCRIPT_PRESETS`); saved Detailed choices load as Custom with their effective tool column. Chat settings shows the four as buttons; the popup shows the same choice as a native select under its title, where a disabled Custom entry appears only after a manual row change. Escape closes an open list before the popup. Preset names and descriptions are localized in every locale; covered by `tests/browser/transcript-presets.test.ts`. diff --git a/packages/ui/src/stores/opencode-data.test.ts b/packages/ui/src/stores/opencode-data.test.ts index c780935f36..4ecb82e0e5 100644 --- a/packages/ui/src/stores/opencode-data.test.ts +++ b/packages/ui/src/stores/opencode-data.test.ts @@ -1618,7 +1618,11 @@ describe("OpenCode data projection", () => { } }) apply({ id: "delivered", type: "session.inbox.delivered", created: 3, data: { sessionID: sessionId, inboxID: "queued" } }) - assert.deepEqual(messageStoreBus.getOrCreate(instanceId).getSessionMessageIds(sessionId), ["other", "queued"]) + // The delivered prompt keeps the row it held at admission; the parked + // prompt stays a pending tail the transcript pins for display either way. + // Sinking the delivered prompt below later rows is what the native page + // order never carries. + assert.deepEqual(messageStoreBus.getOrCreate(instanceId).getSessionMessageIds(sessionId), ["queued", "other"]) } finally { destroyOpenCodeData(instanceId) if (messageStoreBus.getInstance(instanceId)) messageStoreBus.unregisterInstance(instanceId) diff --git a/packages/ui/src/stores/opencode-data.ts b/packages/ui/src/stores/opencode-data.ts index 9d7f06373d..8d1c0979d5 100644 --- a/packages/ui/src/stores/opencode-data.ts +++ b/packages/ui/src/stores/opencode-data.ts @@ -86,6 +86,11 @@ type TranscriptEntry = { * drops the newest publication demand. */ settlementReadEpoch: number queue: QueuedTranscriptEvent[] + /** Delivered prompts (inbox id → the row that followed the prompt's row at + * admission). The SDK reducer answers `session.inbox.delivered` by moving + * the prompt's row to the tail, which sinks it below a reply row appended + * between enqueue and admission; projections restore the recorded pair. */ + deliveredPromptAnchors: Map onResynced?: (data: Data) => void } @@ -327,6 +332,7 @@ function ensureTranscript(instanceId: string, sessionId: string, directory: stri settlementReadPending: false, settlementReadEpoch: 0, queue: [], + deliveredPromptAnchors: new Map(), } transcriptEntries.set(key, transcript) return transcript @@ -346,6 +352,40 @@ function replaceTranscriptEntry(transcript: TranscriptEntry, next: DataEntry): v transcript.entryRevision[1]((value) => value + 1) } +/** Records, before admitting `session.inbox.delivered`, the reducer row that + * follows the delivered prompt. The SDK's delivery handler moves the prompt's + * row to the tail of its list; when a reply row was appended between the + * prompt's enqueue and its admission, that move would sink the prompt below + * the reply it triggered until an authoritative read replaces the reducer. */ +function captureDeliveredPromptAnchor(transcript: TranscriptEntry, entry: DataEntry, event: OpenCodeEvent): void { + if (event.type !== "session.inbox.delivered") return + const sessionId = eventSessionId(event) + const inboxID = (event.data as { inboxID?: unknown }).inboxID + if (!sessionId || typeof inboxID !== "string") return + const rows = entry.data.session.message.list(sessionId) + const index = rows.findIndex(row => row.id === inboxID) + if (index < 0) return + const follower = rows[index + 1] + if (follower && follower.id !== inboxID) transcript.deliveredPromptAnchors.set(inboxID, follower.id) +} + +/** Restores each recorded prompt directly above the row that followed it at + * admission, matching the native order the authoritative page carries. The + * record is consumed once both rows sit in that order or either is gone. */ +function applyDeliveredPromptAnchors(anchors: Map, rows: SessionMessageInfo[]): void { + if (!anchors.size) return + for (const [promptId, followerId] of anchors) { + const promptIndex = rows.findIndex(row => row.id === promptId) + const followerIndex = rows.findIndex(row => row.id === followerId) + if (promptIndex < 0 || followerIndex < 0 || promptIndex < followerIndex) { + anchors.delete(promptId) + continue + } + const [prompt] = rows.splice(promptIndex, 1) + rows.splice(rows.findIndex(row => row.id === followerId), 0, prompt) + } +} + function getOpenCodeFullDataRevision(instanceId: string, sessionId: string): number { return fullDataRevisions.get(messageRevisionKey(instanceId, sessionId)) ?? 0 } @@ -589,6 +629,7 @@ async function drainTranscriptQueue( break } transcript.queue.shift() + captureDeliveredPromptAnchor(transcript, entry, queued.event) entry.emit(queued.event) if (queued.event.type === "session.step.started") { // Keep each replay chunk's synchronous budget untouched: the scan runs @@ -794,6 +835,7 @@ export function applyOpenCodeDataEvent( return transcript.entry.data } } + if (transcript) captureDeliveredPromptAnchor(transcript, entry, event) 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 @@ -919,6 +961,7 @@ export function projectOpenCodeMessages( || transcript.needsAuthoritativeResync || (transcript.resyncing && !transcript.reconnectResync))) return const source = data.session.message.list(sessionId).slice(-MESSAGE_WINDOW_PAGE_SIZE) + if (transcript) applyDeliveredPromptAnchors(transcript.deliveredPromptAnchors, source) const store = messageStoreBus.getOrCreate(instanceId) // During pruning reconciliation, only loadMessages owns native page // membership and pagination. The SDK seed may update resident messages, not diff --git a/packages/ui/tests/browser/fixtures/session.tsx b/packages/ui/tests/browser/fixtures/session.tsx index c30ad86f95..05e749c9c2 100644 --- a/packages/ui/tests/browser/fixtures/session.tsx +++ b/packages/ui/tests/browser/fixtures/session.tsx @@ -97,6 +97,20 @@ render(() => nativeInbox.push({ id, sessionID: sessionId, type: "user", payload: { text }, delivery: "queue", time: { created: ++time } }) emit("session.inbox.enqueued", { inboxID: id, item: { type: "user", payload: { text }, delivery: "queue" } }) }, + /** Another client sends to the idle session: the daemon parks the prompt in + * the inbox (delivery steer) and the execution starts before admission, so + * `session.inbox.delivered` lands only once the engine admits the prompt. */ + remoteEnqueue: (id: string, text: string) => { + nativeInbox.push({ id, sessionID: sessionId, type: "user", payload: { text }, delivery: "steer", time: { created: ++time } }) + emit("session.inbox.enqueued", { inboxID: id, item: { type: "user", payload: { text }, delivery: "steer" } }) + emit("session.execution.started", {}) + }, + /** The engine admits the parked prompt: it leaves the inbox and its row persists. */ + remoteDeliver: (id: string) => { + const [item] = nativeInbox.splice(nativeInbox.findIndex(entry => entry.id === id), 1) + nativeMessages.push({ type: "user", text: item.payload.text, id, time: { created: ++time } }) + emit("session.inbox.delivered", { inboxID: id }) + }, /** The engine starts the parked follow-up: its native row persists and it leaves the inbox. */ deliverQueued: (id: string) => { const [item] = nativeInbox.splice(nativeInbox.findIndex(entry => entry.id === id), 1) diff --git a/packages/ui/tests/browser/inbox-delivery-order.test.ts b/packages/ui/tests/browser/inbox-delivery-order.test.ts new file mode 100644 index 0000000000..cdcb138460 --- /dev/null +++ b/packages/ui/tests/browser/inbox-delivery-order.test.ts @@ -0,0 +1,122 @@ +import assert from "node:assert/strict" +import { after, before, test } from "node:test" +import { fileURLToPath } from "node:url" +import { chromium, type Browser, type Page } from "playwright" +import { createFixtureShutdown } from "./fixture-shutdown" +import { armFixtureNavigationBudget } from "./fixture-navigation-budget" +import { createServer, type ViteDevServer } from "vite" +import solid from "vite-plugin-solid" +import { runWithDiagnosticCleanup } from "./fixture-diagnostic-boundary" +import { createFixtureCache } from "./fixture-cache" + +const root = fileURLToPath(new URL("../..", import.meta.url)) +let server: ViteDevServer, browser: Browser, baseUrl: string +let fixtureCache: Awaited> | undefined +before(async () => { + fixtureCache = await createFixtureCache() + const shutdown = createFixtureShutdown(fixtureCache) + server = await createServer({ + cacheDir: fixtureCache.cacheDir, + configFile: false, root, logLevel: "error", plugins: [shutdown.plugin, solid(), { + name: "browser-fixture", + configureServer(server) { + server.middlewares.use("/fixture", async (req, res) => { + res.setHeader("Content-Type", "text/html") + res.end(await server.transformIndexHtml("/fixture", `
`)) + }) + }, + }], + resolve: { dedupe: ["solid-js"] }, + optimizeDeps: { exclude: ["lucide-solid"] }, + server: { host: "127.0.0.1", port: 0, hmr: false, watch: null }, + }) + shutdown.own(server) + await server.listen() + baseUrl = `http://127.0.0.1:${(server.httpServer!.address() as { port: number }).port}` + browser = await chromium.launch({ executablePath: process.env.CODENOMAD_BROWSER_PATH || undefined }) + armFixtureNavigationBudget(browser) +}) +after(async () => { await browser?.close(); await server?.close(); await fixtureCache?.dispose() }) + +async function open(run: (page: Page) => Promise) { + const page = await browser.newPage({ viewport: { width: 1100, height: 700 }, locale: "en-US" }) + const errors: string[] = [] + page.on("pageerror", error => errors.push(error.message)) + await page.route("**/api/**", route => { + if (new URL(route.request().url()).pathname.endsWith("/permission-receipts")) { + return route.fulfill({ contentType: "application/json", body: JSON.stringify({ receipts: [] }) }) + } + return route.fulfill({ contentType: route.request().url().includes("events") ? "text/event-stream" : "application/json", body: "" }) + }) + await runWithDiagnosticCleanup({ + run: async () => { + await page.goto(`${baseUrl}/fixture`) + await page.waitForFunction(() => Boolean((window as any).fixture)) + await run(page) + assert.deepEqual(errors, []) + }, + diagnose: async () => { + console.error("Browser fixture failure", await page.evaluate(() => ({ + state: (window as any).fixture?.snapshot?.(), + }))) + }, + cleanup: () => page.close(), + onObservationError: error => console.error("Browser fixture diagnostic capture failed", error), + onCleanupError: error => console.error("Browser fixture cleanup failed", error), + }) +} + +/** The prompt-queue action row shows while the engine still holds the prompt parked. */ +function pendingActions(page: Page, marker: string) { + return page.locator(".message-stream-block").filter({ hasText: marker }) + .locator('button[aria-label="Move to queue"], button[aria-label="Steer now"]') +} +/** DOM order of the transcript rows, as the reader sees them. */ +async function rowOrder(page: Page): Promise { + return page.evaluate(() => Array.from(document.querySelectorAll(".message-stream-block")) + .map(row => row.textContent ?? "")) +} + +async function assertPromptAboveReply(page: Page, marker: string, reply: string) { + const rows = await rowOrder(page) + const promptIndex = rows.findIndex(row => row.includes(marker)) + const replyIndex = rows.findIndex(row => row.includes(reply)) + assert.ok(promptIndex >= 0, `the delivered prompt must render (rows: ${JSON.stringify(rows.map(row => row.slice(0, 40)))})`) + assert.ok(replyIndex >= 0, `the streaming reply must render (rows: ${JSON.stringify(rows.map(row => row.slice(0, 40)))})`) + assert.ok(promptIndex < replyIndex, `the delivered prompt must sit above its reply, got prompt at ${promptIndex} and reply at ${replyIndex} of ${rows.length} rows`) +} + +test("another client's prompt keeps its place above the reply once the engine admits it", async () => { + await open(async page => { + const marker = "Prompt from the other terminal" + // The daemon parks the prompt in the inbox and starts the execution before + // admission; the delivered event lands before the first model step. + await page.evaluate(text => (window as any).fixture.remoteEnqueue("msg_remote", text), marker) + await pendingActions(page, marker).first().waitFor() + await page.evaluate(() => (window as any).fixture.remoteDeliver("msg_remote")) + await pendingActions(page, marker).waitFor({ state: "detached", timeout: 3000 }) + const reply = "Reply marker admitted first" + await page.evaluate(reply => { (window as any).fixture.start(); (window as any).fixture.delta(reply) }, reply) + await page.locator(".message-stream-block").filter({ hasText: reply }).waitFor() + await assertPromptAboveReply(page, marker, reply) + }) +}) + +test("a delivered prompt admitted after the reply started streaming does not sink below it", async () => { + await open(async page => { + const marker = "Steered prompt admitted late" + await page.evaluate(text => (window as any).fixture.remoteEnqueue("msg_late", text), marker) + await pendingActions(page, marker).first().waitFor() + // Admission lands while the reply is already streaming on the same session. + const reply = "Streaming reply before admission" + await page.evaluate(reply => { (window as any).fixture.start(); (window as any).fixture.delta(reply) }, reply) + await page.locator(".message-stream-block").filter({ hasText: reply }).waitFor() + await page.evaluate(() => (window as any).fixture.remoteDeliver("msg_late")) + await pendingActions(page, marker).waitFor({ state: "detached", timeout: 3000 }) + await assertPromptAboveReply(page, marker, reply) + // It stays put while the reply keeps streaming. + await page.evaluate(more => (window as any).fixture.delta(more), " more streamed text") + await page.waitForTimeout(300) + await assertPromptAboveReply(page, marker, reply) + }) +}) From 49cabff7765e48e3c9321c2fdfc673c41e7ece28 Mon Sep 17 00:00:00 2001 From: heunghingwan Date: Mon, 9 Nov 2026 21:37:14 +0800 Subject: [PATCH 2/8] fix(transcript): reconcile a delivered prompt through its native page MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of 038e783a (thanks @pascalandr): the recorded follower of an enqueued prompt does not establish its native delivery order — with two steers the restored pair reversed the page order, an authoritative replacement kept projecting an obsolete anchor, and a verified reconnect re-seeded the corrupted order the correction no longer covered. The new browser file also spun its own Vite server, failing the fixture-wiring gate in shard 1. The native message page owns a delivered prompt's position. A delivery that relocates a row which is not the reducer's last (the SDK's tail move) now owes an authoritative read: the message key is invalidated and the read finishes exactly like a settlement read — shared with any in-flight one, published under the same newer-execution fence. No ordering state survives the delivery; the reducer itself is healed, so reconnect seeding and authoritative replacement carry the corrected order. The ordinary idle-session delivery stays at the tail and reads nothing. The browser test now borrows the shared fixture, keeps a persistent fixture event stream, and drives the daemon's real event order: a parked steer burst reconciles to [Q1,Q2,Q3,reply], a mid-stream admission settles after the earlier reply per the page, and an idle prompt renders above its reply. Store regressions cover the burst, the pruning-shaped replacement and a verified reconnect. Validation: 235 focused store tests, UI typecheck, the fixture-wiring gate, the three borrowed-fixture runs and the 48-test session-rendering suite all pass. --- dev-docs/TRANSCRIPT.md | 2 +- .../stores/opencode-data-reconnect.test.ts | 45 ++++++ packages/ui/src/stores/opencode-data.test.ts | 46 +++++-- packages/ui/src/stores/opencode-data.ts | 59 ++++---- .../ui/tests/browser/fixtures/session.tsx | 13 ++ .../browser/inbox-delivery-order.test.ts | 130 +++++++++--------- 6 files changed, 185 insertions(+), 110 deletions(-) diff --git a/dev-docs/TRANSCRIPT.md b/dev-docs/TRANSCRIPT.md index 98a9e51461..4a7ff6c15f 100644 --- a/dev-docs/TRANSCRIPT.md +++ b/dev-docs/TRANSCRIPT.md @@ -4,7 +4,7 @@ Message content visibility and presets, token lines, tool renderers, native sess ## Agent conventions -- Partial live projections preserve omitted resident message runs beside their preceding shared row, with leading history before the snapshot and pending optimistic sends at the tail. Shared rows follow the incoming native order. A prompt delivered from the session inbox keeps the row it held at admission: the SDK's `session.inbox.delivered` moves the prompt's row to the reducer's tail, so the projection restores each delivered prompt above the row that followed it at admission (recorded per transcript, consumed once both rows hold that order or either is gone); a reply appended between enqueue and admission must never render above the prompt that triggered it. HTTP pages can contain later steps whose events are still in transit; message IDs and wall-clock timestamps remain identity/display data rather than transcript sort keys. +- Partial live projections preserve omitted resident message runs beside their preceding shared row, with leading history before the snapshot and pending optimistic sends at the tail. Shared rows follow the incoming native order. A prompt delivered from the session inbox takes the position the native message page owns: the SDK's `session.inbox.delivered` moves the prompt's row to the reducer's tail, so a delivery that relocates a row which is not the reducer's last owes an authoritative page read — invalidated and finished like a settlement read, shared with any in-flight read and superseded only by a newer admitted execution. No client-side ordering state survives the delivery: the reducer itself is healed, so reconnect seeding and authoritative replacement carry the corrected order. HTTP pages can contain later steps whose events are still in transit; message IDs and wall-clock timestamps remain identity/display data rather than transcript sort keys. - The message-content popup and Chat settings share `components/transcript-visibility.ts` and the semantic icons from `components/message-content-icons.ts`; tool presentation metadata lives independently of renderers in `components/tool-call/tool-presentation.ts`. Popup styles live in `styles/components/transcript-filters.css`. Popup rows show a requested state at once and keep it until the save carrying it settles. Each save re-renders the transcript, so a drag sweep (`dev-docs/UI_CONVENTIONS.md`) saves its rows once, on release (`afterSweep`). Saves run in order, each built from the preferences the previous one returned; a batch of rows is sealed as it joins the queue, so a later click never jumps ahead of a preset change nor rides along with a sweep still held. - Transcript presets are Nothing (hides every row, including all tools), Minimal, Balanced and Everything (`TRANSCRIPT_PRESETS`); saved Detailed choices load as Custom with their effective tool column. Chat settings shows the four as buttons; the popup shows the same choice as a native select under its title, where a disabled Custom entry appears only after a manual row change. Escape closes an open list before the popup. Preset names and descriptions are localized in every locale; covered by `tests/browser/transcript-presets.test.ts`. diff --git a/packages/ui/src/stores/opencode-data-reconnect.test.ts b/packages/ui/src/stores/opencode-data-reconnect.test.ts index 45093b9e47..7049e11eae 100644 --- a/packages/ui/src/stores/opencode-data-reconnect.test.ts +++ b/packages/ui/src/stores/opencode-data-reconnect.test.ts @@ -287,6 +287,51 @@ test("a mid-stream reconnect keeps live deltas displaying and reconciles once qu } finally { f.cleanup() } }) +test("a verified reconnect keeps a delivered prompt's reconciled position", async ctx => { + ctx.mock.timers.enable({ apis: ["setTimeout"] }) + const f = fixture("reconnect-delivery-order", true) + try { + // Native storage, oldest first: the page owns the delivered prompt's + // position, here above the reply its admission started. + const stored: any[] = [] + let pageReads = 0 + f.client.message.list = async () => { pageReads += 1; return { data: [...stored].reverse(), cursor: {} } } + + f.dispatch("session.inbox.enqueued", { inboxID: "msg_q", item: { type: "user", payload: { text: "steer" }, delivery: "steer" } }) + f.start() + stored.push({ id: "msg_q", type: "user", text: "steer", time: { created: 501 } }) + stored.push({ id: "msg_live", type: "assistant", agent: "build", model, content: [], time: { created: 500 } }) + // Admission lands after the reply's row exists: the SDK's tail move sinks + // the prompt below it, and the owed authoritative read restores the page's + // order into the reducer itself. + f.dispatch("session.inbox.delivered", { inboxID: "msg_q" }) + const promptAboveReply = () => { + const ids = f.store.getSessionMessageIds(sessionId) + return ids.includes("msg_q") && ids.includes("msg_live") && ids.indexOf("msg_q") < ids.indexOf("msg_live") + } + await converge(ctx, promptAboveReply) + + // A same-daemon reconnect seeds a fresh reducer from the live rows; the + // healed order must ride along instead of the corrupted one. + f.dispatch("server.connected", { daemon: "daemon-a" }) + await microtasks() + ctx.mock.timers.tick(0) + await microtasks() + assert.ok(promptAboveReply(), "reconnect seeding keeps the delivered prompt above its reply") + + // Once quiet, the authoritative snapshot replaces the seed and must keep + // the same order (the delivery read is the first page read; the resync's + // is the second). + for (let index = 0; index < 200 && pageReads < 2; index++) { + ctx.mock.timers.tick(1000) + await microtasks() + } + assert.ok(pageReads >= 2, "the quiet reconnect resync read the page") + await converge(ctx, promptAboveReply) + assert.ok(promptAboveReply(), "the quiet reconnect resync keeps the reconciled order") + } finally { f.cleanup() } +}) + test("arrivals during a pending reconnect read are ordered and drained when it settles", async ctx => { ctx.mock.timers.enable({ apis: ["setTimeout"] }) const f = fixture("reconnect-pending-read", true) diff --git a/packages/ui/src/stores/opencode-data.test.ts b/packages/ui/src/stores/opencode-data.test.ts index 4ecb82e0e5..12d8a654bb 100644 --- a/packages/ui/src/stores/opencode-data.test.ts +++ b/packages/ui/src/stores/opencode-data.test.ts @@ -4,7 +4,7 @@ import { createEffect, createRoot } from "solid-js" import { messageStoreBus } from "./message-v2/bus.ts" import { seedSessionMessagesV2 } from "./message-v2/bridge.ts" import { normalizeSessionMessage } from "./message-v2/normalizers.ts" -import { applyOpenCodeDataEvent, destroyOpenCodeData, finishOpenCodeDataEvent, getOpenCodeMessageRevision, getOpenCodeMutationRevision, getOpenCodeSessionInbox, observeNonEventSettlement, projectOpenCodeMessages, seedOpenCodeSessionMessages, syncOpenCodeSessionInbox } from "./opencode-data.ts" +import { applyOpenCodeDataEvent, destroyOpenCodeData, finishOpenCodeDataEvent, getOpenCodeMessageRevision, getOpenCodeMutationRevision, getOpenCodeSessionInbox, invalidateOpenCodeSessionContent, observeNonEventSettlement, projectOpenCodeMessages, seedOpenCodeSessionMessages, syncOpenCodeSessionInbox } from "./opencode-data.ts" import { emptyLatestWindow } from "./message-v2/message-window.ts" import { getRootClient } from "./opencode-client.ts" import { sdkManager } from "../lib/sdk-manager.ts" @@ -1602,30 +1602,52 @@ describe("OpenCode data projection", () => { } }) - it("projects native inbox delivery order", () => { + it("reconciles delivered prompts to the authoritative page order", async () => { const instanceId = "opencode-data-delivery-order" const sessionId = "session" + const client = getRootClient(instanceId) + // Native storage, oldest first; the daemon appends a prompt's row at its + // delivery, so the page owns the delivered prompt's position. + const stored: any[] = [] + stubAuthoritativeSession(client, sessionId, async () => ({ data: [...stored].reverse(), cursor: {} })) const apply = (event: any) => { const data = applyOpenCodeDataEvent(instanceId, "/work", event) projectOpenCodeMessages(instanceId, sessionId, data) } try { - apply({ id: "queued", type: "session.inbox.enqueued", created: 1, data: { - sessionID: sessionId, inboxID: "queued", item: { type: "user", payload: { text: "queued" }, delivery: "queue" }, + apply({ id: "enqueue-1", type: "session.inbox.enqueued", created: 1, data: { + sessionID: sessionId, inboxID: "q1", item: { type: "user", payload: { text: "first" }, delivery: "steer" }, + } }) + apply({ id: "enqueue-2", type: "session.inbox.enqueued", created: 2, data: { + sessionID: sessionId, inboxID: "q2", item: { type: "user", payload: { text: "second" }, delivery: "steer" }, } }) - apply({ id: "other", type: "session.inbox.enqueued", created: 2, data: { - sessionID: sessionId, inboxID: "other", item: { type: "user", payload: { text: "other" }, delivery: "queue" }, + apply({ id: "enqueue-3", type: "session.inbox.enqueued", created: 3, data: { + sessionID: sessionId, inboxID: "q3", item: { type: "user", payload: { text: "third" }, delivery: "steer" }, } }) - apply({ id: "delivered", type: "session.inbox.delivered", created: 3, data: { sessionID: sessionId, inboxID: "queued" } }) + assert.deepEqual(messageStoreBus.getOrCreate(instanceId).getSessionMessageIds(sessionId), ["q1", "q2", "q3"]) + + for (const [index, id] of ["q1", "q2", "q3"].entries()) { + stored.push({ id, type: "user", text: `${["first", "second", "third"][index]} prompt`, time: { created: 10 + index } }) + apply({ id: `deliver-${id}`, type: "session.inbox.delivered", created: 10 + index, data: { sessionID: sessionId, inboxID: id } }) + } + await waitForReplay(() => messageStoreBus.getOrCreate(instanceId).getSessionMessageIds(sessionId).join() === "q1,q2,q3") - // The delivered prompt keeps the row it held at admission; the parked - // prompt stays a pending tail the transcript pins for display either way. - // Sinking the delivered prompt below later rows is what the native page - // order never carries. - assert.deepEqual(messageStoreBus.getOrCreate(instanceId).getSessionMessageIds(sessionId), ["queued", "other"]) + apply({ id: "reply", type: "session.step.started", created: 20, data: { + sessionID: sessionId, assistantMessageID: "reply", agent: "build", model: { providerID: "provider", id: "model" }, started: 20, + } }) + assert.deepEqual(messageStoreBus.getOrCreate(instanceId).getSessionMessageIds(sessionId), ["q1", "q2", "q3", "reply"], + "the burst's steers keep the authoritative page order above the reply") + + // An authoritative content replacement (pruning shape) carries no + // ordering side state into the next projection. + invalidateOpenCodeSessionContent(instanceId, sessionId) + apply({ id: "after-replacement", type: "session.text.started", created: 21, data: { sessionID: sessionId, assistantMessageID: "reply" } }) + assert.deepEqual(messageStoreBus.getOrCreate(instanceId).getSessionMessageIds(sessionId), ["q1", "q2", "q3", "reply"], + "an authoritative replacement keeps the reconciled order") } finally { destroyOpenCodeData(instanceId) if (messageStoreBus.getInstance(instanceId)) messageStoreBus.unregisterInstance(instanceId) + sdkManager.destroyClientsForInstance(instanceId) } }) }) diff --git a/packages/ui/src/stores/opencode-data.ts b/packages/ui/src/stores/opencode-data.ts index 8d1c0979d5..c6d7654549 100644 --- a/packages/ui/src/stores/opencode-data.ts +++ b/packages/ui/src/stores/opencode-data.ts @@ -86,11 +86,6 @@ type TranscriptEntry = { * drops the newest publication demand. */ settlementReadEpoch: number queue: QueuedTranscriptEvent[] - /** Delivered prompts (inbox id → the row that followed the prompt's row at - * admission). The SDK reducer answers `session.inbox.delivered` by moving - * the prompt's row to the tail, which sinks it below a reply row appended - * between enqueue and admission; projections restore the recorded pair. */ - deliveredPromptAnchors: Map onResynced?: (data: Data) => void } @@ -332,7 +327,6 @@ function ensureTranscript(instanceId: string, sessionId: string, directory: stri settlementReadPending: false, settlementReadEpoch: 0, queue: [], - deliveredPromptAnchors: new Map(), } transcriptEntries.set(key, transcript) return transcript @@ -352,38 +346,30 @@ function replaceTranscriptEntry(transcript: TranscriptEntry, next: DataEntry): v transcript.entryRevision[1]((value) => value + 1) } -/** Records, before admitting `session.inbox.delivered`, the reducer row that - * follows the delivered prompt. The SDK's delivery handler moves the prompt's - * row to the tail of its list; when a reply row was appended between the - * prompt's enqueue and its admission, that move would sink the prompt below - * the reply it triggered until an authoritative read replaces the reducer. */ -function captureDeliveredPromptAnchor(transcript: TranscriptEntry, entry: DataEntry, event: OpenCodeEvent): void { - if (event.type !== "session.inbox.delivered") return +/** True when admitting `event` relocates an already-materialized prompt row + * that is not the reducer's last row: the SDK's delivery handler moves the + * admitted prompt to the tail of its list, reordering rows whose position the + * native message page owns. Such a delivery owes an authoritative read. */ +function deliveryRelocatesRow(entry: DataEntry, event: OpenCodeEvent): boolean { + if (event.type !== "session.inbox.delivered") return false const sessionId = eventSessionId(event) const inboxID = (event.data as { inboxID?: unknown }).inboxID - if (!sessionId || typeof inboxID !== "string") return + if (!sessionId || typeof inboxID !== "string") return false const rows = entry.data.session.message.list(sessionId) const index = rows.findIndex(row => row.id === inboxID) - if (index < 0) return - const follower = rows[index + 1] - if (follower && follower.id !== inboxID) transcript.deliveredPromptAnchors.set(inboxID, follower.id) + return index >= 0 && index !== rows.length - 1 } -/** Restores each recorded prompt directly above the row that followed it at - * admission, matching the native order the authoritative page carries. The - * record is consumed once both rows sit in that order or either is gone. */ -function applyDeliveredPromptAnchors(anchors: Map, rows: SessionMessageInfo[]): void { - if (!anchors.size) return - for (const [promptId, followerId] of anchors) { - const promptIndex = rows.findIndex(row => row.id === promptId) - const followerIndex = rows.findIndex(row => row.id === followerId) - if (promptIndex < 0 || followerIndex < 0 || promptIndex < followerIndex) { - anchors.delete(promptId) - continue - } - const [prompt] = rows.splice(promptIndex, 1) - rows.splice(rows.findIndex(row => row.id === followerId), 0, prompt) - } +/** The native message page owns a delivered prompt's position; the reducer's + * list position does not. Invalidate the SDK's message key and finish the + * authoritative read — sharing any in-flight one — then publish the reconciled + * order exactly like a settlement read: a newer admitted execution supersedes + * the publication, same-round activity does not. No ordering state survives + * here: the reducer itself is healed, so reconnect seeding and authoritative + * replacement carry the corrected order. */ +function reconcileDeliveredPromptPage(instanceId: string, sessionId: string, transcript: TranscriptEntry): void { + transcript.entry.data.session.message.invalidate(sessionId) + completeSettlementRead(instanceId, sessionId, transcript) } function getOpenCodeFullDataRevision(instanceId: string, sessionId: string): number { @@ -629,13 +615,14 @@ async function drainTranscriptQueue( break } transcript.queue.shift() - captureDeliveredPromptAnchor(transcript, entry, queued.event) + const relocatesDelivery = deliveryRelocatesRow(entry, queued.event) 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 (relocatesDelivery && current()) reconcileDeliveredPromptPage(instanceId, sessionId, transcript) if (!current()) return false if (queued.publication) events.push(queued.event) if (queued.onApplied) { @@ -835,7 +822,7 @@ export function applyOpenCodeDataEvent( return transcript.entry.data } } - if (transcript) captureDeliveredPromptAnchor(transcript, entry, event) + const relocatesDelivery = transcript ? deliveryRelocatesRow(entry, event) : false 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 @@ -843,6 +830,9 @@ export function applyOpenCodeDataEvent( if (event.type === "session.step.started" && transcript && typeof sessionId === "string") { reconcileStrandedRoundTools(instanceId, sessionId, transcript) } + if (relocatesDelivery && transcript && isTranscriptCurrent(instanceId, sessionId!, transcript)) { + reconcileDeliveredPromptPage(instanceId, sessionId!, transcript) + } if (coalesced) { onDeferred?.(entry.data) if (!transcript || (isTranscriptCurrent(instanceId, sessionId!, transcript) && transcript.entry === entry)) { @@ -961,7 +951,6 @@ export function projectOpenCodeMessages( || transcript.needsAuthoritativeResync || (transcript.resyncing && !transcript.reconnectResync))) return const source = data.session.message.list(sessionId).slice(-MESSAGE_WINDOW_PAGE_SIZE) - if (transcript) applyDeliveredPromptAnchors(transcript.deliveredPromptAnchors, source) const store = messageStoreBus.getOrCreate(instanceId) // During pruning reconciliation, only loadMessages owns native page // membership and pagination. The SDK seed may update resident messages, not diff --git a/packages/ui/tests/browser/fixtures/session.tsx b/packages/ui/tests/browser/fixtures/session.tsx index 05e749c9c2..a76cd806e3 100644 --- a/packages/ui/tests/browser/fixtures/session.tsx +++ b/packages/ui/tests/browser/fixtures/session.tsx @@ -111,6 +111,19 @@ render(() => nativeMessages.push({ type: "user", text: item.payload.text, id, time: { created: ++time } }) emit("session.inbox.delivered", { inboxID: id }) }, + /** Streams a reply whose native row is stored from its first step, as the + * daemon stores it: an authoritative read mid-stream still serves the row. */ + startStored: () => { + nativeMessages.push({ id: assistantId, type: "assistant", agent: "build", model, time: { created: ++time }, content: [{ type: "text", text: "" }] }) + emit("session.step.started", { assistantMessageID: assistantId, agent: "build", model }) + emit("session.text.started", { assistantMessageID: assistantId }) + }, + /** Streams text into the stored reply row alongside the live delta. */ + deltaStored: (delta: string) => { + const row = nativeMessages.find(message => message.id === assistantId) + if (row) row.content[0].text += delta + emit("session.text.delta", { assistantMessageID: assistantId, ordinal: 0, delta }) + }, /** The engine starts the parked follow-up: its native row persists and it leaves the inbox. */ deliverQueued: (id: string) => { const [item] = nativeInbox.splice(nativeInbox.findIndex(entry => entry.id === id), 1) diff --git a/packages/ui/tests/browser/inbox-delivery-order.test.ts b/packages/ui/tests/browser/inbox-delivery-order.test.ts index cdcb138460..f54abddcf5 100644 --- a/packages/ui/tests/browser/inbox-delivery-order.test.ts +++ b/packages/ui/tests/browser/inbox-delivery-order.test.ts @@ -1,42 +1,34 @@ import assert from "node:assert/strict" import { after, before, test } from "node:test" -import { fileURLToPath } from "node:url" import { chromium, type Browser, type Page } from "playwright" -import { createFixtureShutdown } from "./fixture-shutdown" +import { borrowFixture } from "./fixture-borrow" import { armFixtureNavigationBudget } from "./fixture-navigation-budget" -import { createServer, type ViteDevServer } from "vite" -import solid from "vite-plugin-solid" +import { fixtureEventStream } from "./fixture-event-stream" import { runWithDiagnosticCleanup } from "./fixture-diagnostic-boundary" -import { createFixtureCache } from "./fixture-cache" -const root = fileURLToPath(new URL("../..", import.meta.url)) -let server: ViteDevServer, browser: Browser, baseUrl: string -let fixtureCache: Awaited> | undefined +// Another client's prompts reach this page through the session inbox: the +// engine parks each prompt on enqueue, admits it on delivery, and the native +// page owns the delivered prompt's position. These runs drive the daemon's +// real event order through the real SessionView and native dispatcher. + +let browser: Browser, url: string, events: Awaited> before(async () => { - fixtureCache = await createFixtureCache() - const shutdown = createFixtureShutdown(fixtureCache) - server = await createServer({ - cacheDir: fixtureCache.cacheDir, - configFile: false, root, logLevel: "error", plugins: [shutdown.plugin, solid(), { - name: "browser-fixture", - configureServer(server) { - server.middlewares.use("/fixture", async (req, res) => { - res.setHeader("Content-Type", "text/html") - res.end(await server.transformIndexHtml("/fixture", `
`)) - }) - }, - }], - resolve: { dedupe: ["solid-js"] }, - optimizeDeps: { exclude: ["lucide-solid"] }, - server: { host: "127.0.0.1", port: 0, hmr: false, watch: null }, - }) - shutdown.own(server) - await server.listen() - baseUrl = `http://127.0.0.1:${(server.httpServer!.address() as { port: number }).port}` - browser = await chromium.launch({ executablePath: process.env.CODENOMAD_BROWSER_PATH || undefined }) - armFixtureNavigationBudget(browser) + const fixture = await borrowFixture({ name: "inbox-delivery-order", routes: [{ + path: "/fixture", + html: '
', + }] }) + url = fixture.url + let ready = false + await runWithDiagnosticCleanup({ run: async () => { + events = await fixtureEventStream(url) + browser = await chromium.launch({ executablePath: process.env.CODENOMAD_BROWSER_PATH || undefined }) + armFixtureNavigationBudget(browser) + ready = true + }, diagnose: async () => {}, cleanup: async () => { + if (!ready) { try { await browser?.close() } finally { await events?.close() } } + }, onObservationError: () => console.error("delivery-order-startup-observation-failed"), onCleanupError: () => console.error("delivery-order-startup-cleanup-failed") }) }) -after(async () => { await browser?.close(); await server?.close(); await fixtureCache?.dispose() }) +after(async () => { try { await browser?.close() } finally { await events?.close() } }) async function open(run: (page: Page) => Promise) { const page = await browser.newPage({ viewport: { width: 1100, height: 700 }, locale: "en-US" }) @@ -48,9 +40,10 @@ async function open(run: (page: Page) => Promise) { } return route.fulfill({ contentType: route.request().url().includes("events") ? "text/event-stream" : "application/json", body: "" }) }) + await events.route(page) await runWithDiagnosticCleanup({ run: async () => { - await page.goto(`${baseUrl}/fixture`) + await page.goto(url) await page.waitForFunction(() => Boolean((window as any).fixture)) await run(page) assert.deepEqual(errors, []) @@ -66,57 +59,70 @@ async function open(run: (page: Page) => Promise) { }) } -/** The prompt-queue action row shows while the engine still holds the prompt parked. */ -function pendingActions(page: Page, marker: string) { - return page.locator(".message-stream-block").filter({ hasText: marker }) - .locator('button[aria-label="Move to queue"], button[aria-label="Steer now"]') -} /** DOM order of the transcript rows, as the reader sees them. */ async function rowOrder(page: Page): Promise { return page.evaluate(() => Array.from(document.querySelectorAll(".message-stream-block")) .map(row => row.textContent ?? "")) } -async function assertPromptAboveReply(page: Page, marker: string, reply: string) { +/** The prompt-queue action row shows while the engine still holds the prompt parked. */ +function pendingActions(page: Page, marker: string) { + return page.locator(".message-stream-block").filter({ hasText: marker }) + .locator('button[aria-label="Move to queue"], button[aria-label="Steer now"]') +} + +async function assertOrder(page: Page, expected: string[]) { const rows = await rowOrder(page) - const promptIndex = rows.findIndex(row => row.includes(marker)) - const replyIndex = rows.findIndex(row => row.includes(reply)) - assert.ok(promptIndex >= 0, `the delivered prompt must render (rows: ${JSON.stringify(rows.map(row => row.slice(0, 40)))})`) - assert.ok(replyIndex >= 0, `the streaming reply must render (rows: ${JSON.stringify(rows.map(row => row.slice(0, 40)))})`) - assert.ok(promptIndex < replyIndex, `the delivered prompt must sit above its reply, got prompt at ${promptIndex} and reply at ${replyIndex} of ${rows.length} rows`) + let cursor = 0 + for (const marker of expected) { + const index = rows.slice(cursor).findIndex(row => row.includes(marker)) + assert.ok(index >= 0, `${marker} must render after the previous marker (rows: ${JSON.stringify(rows.map(row => row.slice(0, 30)))})`) + cursor += index + } } -test("another client's prompt keeps its place above the reply once the engine admits it", async () => { +test("another client's prompt renders above the reply the engine starts for it", async () => { await open(async page => { const marker = "Prompt from the other terminal" - // The daemon parks the prompt in the inbox and starts the execution before - // admission; the delivered event lands before the first model step. await page.evaluate(text => (window as any).fixture.remoteEnqueue("msg_remote", text), marker) await pendingActions(page, marker).first().waitFor() await page.evaluate(() => (window as any).fixture.remoteDeliver("msg_remote")) await pendingActions(page, marker).waitFor({ state: "detached", timeout: 3000 }) - const reply = "Reply marker admitted first" - await page.evaluate(reply => { (window as any).fixture.start(); (window as any).fixture.delta(reply) }, reply) + const reply = "Reply marker for the admitted prompt" + await page.evaluate(reply => { (window as any).fixture.startStored(); (window as any).fixture.deltaStored(reply) }, reply) await page.locator(".message-stream-block").filter({ hasText: reply }).waitFor() - await assertPromptAboveReply(page, marker, reply) + await assertOrder(page, [marker, reply]) }) }) -test("a delivered prompt admitted after the reply started streaming does not sink below it", async () => { +test("a steer burst delivered while parked keeps the native page order", async () => { await open(async page => { - const marker = "Steered prompt admitted late" - await page.evaluate(text => (window as any).fixture.remoteEnqueue("msg_late", text), marker) - await pendingActions(page, marker).first().waitFor() - // Admission lands while the reply is already streaming on the same session. - const reply = "Streaming reply before admission" - await page.evaluate(reply => { (window as any).fixture.start(); (window as any).fixture.delta(reply) }, reply) + const first = "Burst steer one", second = "Burst steer two", third = "Burst steer three" + await page.evaluate(text => (window as any).fixture.remoteEnqueue("msg_b1", text), first) + await pendingActions(page, first).first().waitFor() + await page.evaluate(text => (window as any).fixture.remoteEnqueue("msg_b2", text), second) + await page.evaluate(text => (window as any).fixture.remoteEnqueue("msg_b3", text), third) + for (const id of ["msg_b1", "msg_b2", "msg_b3"]) { + await page.evaluate(id => (window as any).fixture.remoteDeliver(id), id) + } + await pendingActions(page, third).waitFor({ state: "detached", timeout: 3000 }) + const reply = "Reply marker after the burst" + await page.evaluate(reply => { (window as any).fixture.startStored(); (window as any).fixture.deltaStored(reply) }, reply) await page.locator(".message-stream-block").filter({ hasText: reply }).waitFor() - await page.evaluate(() => (window as any).fixture.remoteDeliver("msg_late")) + await assertOrder(page, [first, second, third, reply]) + }) +}) + +test("a steer admitted mid-stream settles after the earlier reply, per the native page", async () => { + await open(async page => { + const earlier = "Earlier reply still streaming" + await page.evaluate(reply => { (window as any).fixture.startStored(); (window as any).fixture.deltaStored(reply) }, earlier) + await page.locator(".message-stream-block").filter({ hasText: earlier }).waitFor() + const marker = "Steer admitted mid-stream" + await page.evaluate(text => (window as any).fixture.remoteEnqueue("msg_mid", text), marker) + await pendingActions(page, marker).first().waitFor() + await page.evaluate(() => (window as any).fixture.remoteDeliver("msg_mid")) await pendingActions(page, marker).waitFor({ state: "detached", timeout: 3000 }) - await assertPromptAboveReply(page, marker, reply) - // It stays put while the reply keeps streaming. - await page.evaluate(more => (window as any).fixture.delta(more), " more streamed text") - await page.waitForTimeout(300) - await assertPromptAboveReply(page, marker, reply) + await assertOrder(page, [earlier, marker]) }) }) From b2224c16eef2b0e29d4a3b4bd0c52f0d2e05744c Mon Sep 17 00:00:00 2001 From: heunghingwan Date: Mon, 9 Nov 2026 22:20:16 +0800 Subject: [PATCH 3/8] fix(transcript): give a delivery repair the gates, barriers and carry-over of a live read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of 8af56a77 (thanks @pascalandr): the delivery repair's completion published directly, ignoring the active-session and latest-window gates live projections pass through, so a repair landing on a history window rewrote that window's membership; a drained settlement destroyed the reducer beneath an outstanding repair, leaving the sunk prompt unreconciled; and a verified reconnect abandoned a pending repair behind the quiet timer, which continued streaming kept postponing. The repair now publishes through the instance layer's frame gates (a gate-free context keeps the direct projection), its outstanding read is a retirement barrier beside parked prompts and unsettled rows, and reconnect carries the demand: the capture records it, the seeded page resuming it immediately after it lands. The natural HTTP-ahead crossing — a settlement read returning the delivered prompt above its reply before the delivery's own SSE arrives — now has a regression that fails on the base (the late delivery sinks the prompt below the reply), plus settlement-during-repair and reconnect-during-repair lifetime regressions, and the browser fixture fails on request, HTTP and console errors like its neighbors. Validation: 211 focused store tests, UI typecheck, the fixture-wiring gate, the three borrowed-fixture runs with strict error collection. --- dev-docs/TRANSCRIPT.md | 2 +- .../stores/opencode-data-reconnect.test.ts | 38 ++++++++++++ .../stores/opencode-data-settlement.test.ts | 56 +++++++++++++++++ packages/ui/src/stores/opencode-data.ts | 62 +++++++++++++++---- .../src/stores/opencode-projection-frame.ts | 7 +++ packages/ui/src/stores/opencode-reconnect.ts | 13 +++- .../browser/inbox-delivery-order.test.ts | 9 +++ 7 files changed, 172 insertions(+), 15 deletions(-) diff --git a/dev-docs/TRANSCRIPT.md b/dev-docs/TRANSCRIPT.md index 4a7ff6c15f..3ab2a0d2a0 100644 --- a/dev-docs/TRANSCRIPT.md +++ b/dev-docs/TRANSCRIPT.md @@ -4,7 +4,7 @@ Message content visibility and presets, token lines, tool renderers, native sess ## Agent conventions -- Partial live projections preserve omitted resident message runs beside their preceding shared row, with leading history before the snapshot and pending optimistic sends at the tail. Shared rows follow the incoming native order. A prompt delivered from the session inbox takes the position the native message page owns: the SDK's `session.inbox.delivered` moves the prompt's row to the reducer's tail, so a delivery that relocates a row which is not the reducer's last owes an authoritative page read — invalidated and finished like a settlement read, shared with any in-flight read and superseded only by a newer admitted execution. No client-side ordering state survives the delivery: the reducer itself is healed, so reconnect seeding and authoritative replacement carry the corrected order. HTTP pages can contain later steps whose events are still in transit; message IDs and wall-clock timestamps remain identity/display data rather than transcript sort keys. +- Partial live projections preserve omitted resident message runs beside their preceding shared row, with leading history before the snapshot and pending optimistic sends at the tail. Shared rows follow the incoming native order. A prompt delivered from the session inbox takes the position the native message page owns: the SDK's `session.inbox.delivered` moves the prompt's row to the reducer's tail, so a delivery that relocates a row which is not the reducer's last owes an authoritative page read — invalidated and finished like a settlement read, shared with any in-flight read and superseded only by a newer admitted execution, and published through the instance layer's frame gates (active session, latest window) exactly as live events' projections are. The outstanding read is a retirement barrier, and a verified reconnect carries the demand: after the seeded page lands, the repair resumes immediately instead of trailing behind the quiet reconciliation. No client-side ordering state survives the delivery: the reducer itself is healed, so reconnect seeding and authoritative replacement carry the corrected order. HTTP pages can contain later steps whose events are still in transit; message IDs and wall-clock timestamps remain identity/display data rather than transcript sort keys. - The message-content popup and Chat settings share `components/transcript-visibility.ts` and the semantic icons from `components/message-content-icons.ts`; tool presentation metadata lives independently of renderers in `components/tool-call/tool-presentation.ts`. Popup styles live in `styles/components/transcript-filters.css`. Popup rows show a requested state at once and keep it until the save carrying it settles. Each save re-renders the transcript, so a drag sweep (`dev-docs/UI_CONVENTIONS.md`) saves its rows once, on release (`afterSweep`). Saves run in order, each built from the preferences the previous one returned; a batch of rows is sealed as it joins the queue, so a later click never jumps ahead of a preset change nor rides along with a sweep still held. - Transcript presets are Nothing (hides every row, including all tools), Minimal, Balanced and Everything (`TRANSCRIPT_PRESETS`); saved Detailed choices load as Custom with their effective tool column. Chat settings shows the four as buttons; the popup shows the same choice as a native select under its title, where a disabled Custom entry appears only after a manual row change. Escape closes an open list before the popup. Preset names and descriptions are localized in every locale; covered by `tests/browser/transcript-presets.test.ts`. diff --git a/packages/ui/src/stores/opencode-data-reconnect.test.ts b/packages/ui/src/stores/opencode-data-reconnect.test.ts index 7049e11eae..e96ad894fa 100644 --- a/packages/ui/src/stores/opencode-data-reconnect.test.ts +++ b/packages/ui/src/stores/opencode-data-reconnect.test.ts @@ -287,6 +287,44 @@ test("a mid-stream reconnect keeps live deltas displaying and reconciles once qu } finally { f.cleanup() } }) +test("a verified reconnect resumes an outstanding delivery repair after seeding", async ctx => { + ctx.mock.timers.enable({ apis: ["setTimeout"] }) + const f = fixture("reconnect-delivery-resume", true) + try { + // The daemon's page: the delivered prompt above its reply. + const stored = [ + { id: "msg_q", type: "user", text: "steer", time: { created: 501 } }, + { id: "msg_live", type: "assistant", agent: "build", model, content: [{ type: "reasoning", text: "" }], time: { created: 500 } }, + ] + const control = f.controlledList(() => [...stored].reverse()) + const promptAboveReply = () => { + const ids = f.store.getSessionMessageIds(sessionId) + return ids.includes("msg_q") && ids.includes("msg_live") && ids.indexOf("msg_q") < ids.indexOf("msg_live") + } + f.dispatch("session.inbox.enqueued", { inboxID: "msg_q", item: { type: "user", payload: { text: "steer" }, delivery: "steer" } }) + f.start() + f.dispatch("session.reasoning.started", live) + // The delivery relocates the prompt below the reply; its repair read holds. + f.dispatch("session.inbox.delivered", { inboxID: "msg_q" }) + await converge(ctx, () => control.calls >= 1 && control.pending()) + + // A verified reconnect lands mid-repair while the stream keeps arriving, + // so the quiet reconciliation keeps trailing behind live activity. + f.dispatch("server.connected", { daemon: "daemon-a" }) + await microtasks() + f.dispatch("session.reasoning.delta", { ...live, delta: "streaming " }) + ctx.mock.timers.tick(0) + await microtasks() + + // Seeding landed; the carried demand resumes a fresh repair read at once + // instead of waiting for the quiet resync. + await converge(ctx, () => control.calls >= 2) + control.settle() + await converge(ctx, promptAboveReply) + assert.ok(promptAboveReply(), "the resumed repair reconciles the prompt above its reply while streaming continues") + } finally { f.cleanup() } +}) + test("a verified reconnect keeps a delivered prompt's reconciled position", async ctx => { ctx.mock.timers.enable({ apis: ["setTimeout"] }) const f = fixture("reconnect-delivery-order", true) diff --git a/packages/ui/src/stores/opencode-data-settlement.test.ts b/packages/ui/src/stores/opencode-data-settlement.test.ts index 6b40c76912..c7bab89479 100644 --- a/packages/ui/src/stores/opencode-data-settlement.test.ts +++ b/packages/ui/src/stores/opencode-data-settlement.test.ts @@ -230,3 +230,59 @@ test("a disposed native projection does not retry a delayed terminal history rea assert.equal(f.text(), "hello", "disposal must preserve the separately owned visible snapshot") } finally { f.cleanup() } }) + +test("a delivery crossing an HTTP-ahead settlement read reconciles through its own read and outlives the round's settlement", async () => { + const f = fixture("native-delivery-http-ahead") + const sessionId = "s" + const order = () => messageStoreBus.getOrCreate("native-delivery-http-ahead") + .getSessionMessageIds(sessionId) + try { + // Round one is interrupted with a tool still running: its settlement read + // is owed and holds. + const base = { sessionID: sessionId, 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.execution.interrupted", { sessionID: sessionId }) + assert.equal(f.reads.length, 1) + + // The prompt is parked over SSE before that read resolves. + f.emit("session.inbox.enqueued", { sessionID: sessionId, inboxID: "msg_user", item: { type: "user", payload: { text: "crossing prompt" }, delivery: "steer" } }) + + // The held read returns the daemon's page, which already carries the + // delivered prompt above its reply: the delivery's own SSE still trails. + // Round one's rows appear in their terminal native shapes, as the daemon + // stored them (its idle record's id derives from the terminal event). + const page = [ + { id: "m1", type: "assistant", agent: "build", model, time: { created: 1, completed: 2 }, content: [{ + type: "tool", id: "tool", name: "read", time: { created: 2, ran: 3, completed: 4 }, + state: { status: "completed", input: {}, content: [{ type: "text", text: "settled" }], metadata: {} }, + }] }, + { id: "msg_4", type: "idle", outcome: "interrupted", time: { created: 4 } }, + { id: "msg_user", type: "user", text: "crossing prompt", time: { created: 5 } }, + { id: "reply", type: "assistant", agent: "build", model, time: { created: 6 }, content: [{ type: "text", text: "answer" }] }, + ] + f.reads[0].resolve({ data: [...page].reverse(), cursor: {} }) + await flush() + assert.deepEqual(order(), ["m1", "msg_4", "msg_user", "reply"]) + + // The delivery event finally arrives over SSE: the SDK relocates the + // prompt below the reply, and the delivery owes its own authoritative + // read, which holds. + f.emit("session.inbox.delivered", { sessionID: sessionId, inboxID: "msg_user" }) + assert.equal(f.reads.length, 2, "the relocating delivery owed a repair read") + + // The reply's round settles while the repair is outstanding: the reducer + // must survive as the repair's publication owner. + f.emit("session.step.ended", { sessionID: sessionId, assistantMessageID: "reply", finish: "stop", cost: 0, tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } } }) + f.emit("session.execution.succeeded", { sessionID: sessionId }) + assert.equal(f.reads.length, 2, "the settlement must not start a second read beneath the repair") + + // Resolving the repair publishes the page's order through the surviving + // reducer instead of leaving the sunk prompt behind. (msg_8 is the round's + // own idle record, inserted by its terminal event.) + f.reads[1].resolve({ data: [...page].reverse(), cursor: {} }) + await flush() + assert.deepEqual(order(), ["m1", "msg_4", "msg_user", "reply", "msg_8"], "the crossing prompt reconciles above its reply") + } finally { f.cleanup() } +}) diff --git a/packages/ui/src/stores/opencode-data.ts b/packages/ui/src/stores/opencode-data.ts index c6d7654549..86aabd6f49 100644 --- a/packages/ui/src/stores/opencode-data.ts +++ b/packages/ui/src/stores/opencode-data.ts @@ -16,6 +16,7 @@ import { } from "./opencode-data-events" import { mergePageWithSnapshot, snapshotRows, type OpenCodeRowSnapshot } from "./opencode-data-read-merge" import { createReconnect, type ReconnectCapture } from "./opencode-reconnect" +import { hasTranscriptProjectionGates, scheduleTranscriptProjection } from "./opencode-projection-frame" import { cancelTranscriptProjections, flushTranscriptProjections } from "./opencode-projection-frame" const log = getLogger("session") @@ -86,6 +87,12 @@ type TranscriptEntry = { * drops the newest publication demand. */ settlementReadEpoch: number queue: QueuedTranscriptEvent[] + /** Inbox-delivery repairs (authoritative reads a relocating delivery owes) + * that started and not settled: a retirement barrier. */ + deliveryRepairPending: number + /** A repair demand reconnect carried across its reset; seeding owes it a new + * read instead of trailing behind the quiet reconciliation. */ + deliveryRepairOwed: boolean onResynced?: (data: Data) => void } @@ -327,6 +334,8 @@ function ensureTranscript(instanceId: string, sessionId: string, directory: stri settlementReadPending: false, settlementReadEpoch: 0, queue: [], + deliveryRepairPending: 0, + deliveryRepairOwed: false, } transcriptEntries.set(key, transcript) return transcript @@ -362,14 +371,17 @@ function deliveryRelocatesRow(entry: DataEntry, event: OpenCodeEvent): boolean { /** The native message page owns a delivered prompt's position; the reducer's * list position does not. Invalidate the SDK's message key and finish the - * authoritative read — sharing any in-flight one — then publish the reconciled - * order exactly like a settlement read: a newer admitted execution supersedes - * the publication, same-round activity does not. No ordering state survives - * here: the reducer itself is healed, so reconnect seeding and authoritative - * replacement carry the corrected order. */ + * authoritative read — sharing any in-flight one — then publish through the + * gated frame path live events use (a missing gate registration keeps the + * direct projection), fenced like a settlement read: a newer admitted + * execution supersedes the publication, same-round activity does not. The + * outstanding read is a retirement barrier, and reconnect carries the demand. */ function reconcileDeliveredPromptPage(instanceId: string, sessionId: string, transcript: TranscriptEntry): void { + transcript.deliveryRepairPending += 1 + transcript.deliveryRepairOwed = false transcript.entry.data.session.message.invalidate(sessionId) - completeSettlementRead(instanceId, sessionId, transcript) + void completeSettlementRead(instanceId, sessionId, transcript, { publishGated: true }) + ?.finally(() => { transcript.deliveryRepairPending = Math.max(0, transcript.deliveryRepairPending - 1) }) } function getOpenCodeFullDataRevision(instanceId: string, sessionId: string): number { @@ -450,6 +462,7 @@ const reconnect = createReconnect({ // A settlement still waiting on running work (e.g. a user shell) must // keep waiting after the reconnect, not strand its reducer forever. retireWhenDrained: transcript.retireWhenDrained, + deliveryRepairOwed: transcript.deliveryRepairPending > 0 || transcript.deliveryRepairOwed, onResynced: transcript.onResynced, }) } @@ -461,6 +474,7 @@ const reconnect = createReconnect({ const transcript = ensureTranscript(instanceId, capture.sessionId, capture.directory) transcript.reconnectResync = true transcript.retireWhenDrained = capture.retireWhenDrained + transcript.deliveryRepairOwed = capture.deliveryRepairOwed // Without a later admitted event, nothing re-registers the publication // callback; carry it so a quiet snapshot still reaches the display. transcript.onResynced = capture.onResynced @@ -469,6 +483,11 @@ const reconnect = createReconnect({ seedPage: (instanceId, capture) => ensureTranscript(instanceId, capture.sessionId, capture.directory) .entry.syncMessages(capture.sessionId, boundedTranscript(capture.messages), () => true), + resumeDeliveryRepair: (instanceId, sessionId, transcript) => { + transcript.deliveryRepairOwed = false + if (!isTranscriptCurrent(instanceId, sessionId, transcript)) return + reconcileDeliveredPromptPage(instanceId, sessionId, transcript) + }, scheduleDroppingResync: scheduleAuthoritativeResync, isCurrent: isTranscriptCurrent, fullDataRevision: getOpenCodeFullDataRevision, @@ -981,10 +1000,11 @@ function retireDrainedTranscript(instanceId: string, sessionId: string, transcri || transcript.rotating || transcript.resyncing || transcript.needsAuthoritativeResync || transcript.retryTimer || transcript.queue.length) return // Work that outlives the settlement still needs this reducer: prompts parked in - // its inbox (e.g. after an interruption) are listed from it, and unsettled rows - // settle only in it. + // its inbox (e.g. after an interruption) are listed from it, unsettled rows + // settle only in it, and an outstanding delivery repair publishes through it. const data = transcript.entry.data - if (data.session.pending.list(sessionId).length || data.session.message.list(sessionId).some(isUnsettledAtSettlement)) return + if (transcript.deliveryRepairPending > 0 || transcript.deliveryRepairOwed + || data.session.pending.list(sessionId).length || data.session.message.list(sessionId).some(isUnsettledAtSettlement)) return // The reducer's final coalesced page — e.g. a tool that settled after the // execution did — publishes here, before normal retirement destroys the // entry; resets, eviction and destructive teardown cancel instead. @@ -1028,8 +1048,15 @@ export function finishOpenCodeDataEvent(instanceId: string, event: OpenCodeEvent * in-flight read when connected, start it when not, then project the * reconciled page without touching the display window's membership. A newer * admitted execution supersedes the publication; same-round activity does - * not. */ -function completeSettlementRead(instanceId: string, sessionId: string, transcript: TranscriptEntry): void { + * not. `publishGated` routes the publication through the instance layer's + * frame gates instead of projecting directly. Returns the SDK read promise it + * followed, so a caller holding obligations on the read settles with it. */ +function completeSettlementRead( + instanceId: string, + sessionId: string, + transcript: TranscriptEntry, + options?: { publishGated?: boolean }, +): Promise { 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 @@ -1041,7 +1068,7 @@ function completeSettlementRead(instanceId: string, sessionId: string, transcrip transcript.settlementReadEntry = entry transcript.settlementReadEpoch = transcript.executionEpoch const promise = entry.data.session.message.sync(sessionId) - if (transcript.settlementReadPromise === promise) return + if (transcript.settlementReadPromise === promise) return promise transcript.settlementReadPromise = promise const followed = promise void followed @@ -1058,9 +1085,18 @@ function completeSettlementRead(instanceId: string, sessionId: string, transcrip // event) must not suppress the repair. if (!isTranscriptCurrent(instanceId, sessionId, transcript) || transcript.executionEpoch !== transcript.settlementReadEpoch) return - projectOpenCodeMessages(instanceId, sessionId, entry.data, true) + if (options?.publishGated) { + // The instance layer's gates own active-session and latest-window + // admission exactly as live events' projections do; a registration-free + // context (unit tests) keeps the direct projection. + if (hasTranscriptProjectionGates()) scheduleTranscriptProjection(instanceId, sessionId, entry.data) + else projectOpenCodeMessages(instanceId, sessionId, entry.data, true) + } else { + projectOpenCodeMessages(instanceId, sessionId, entry.data, true) + } retireDrainedTranscript(instanceId, sessionId, transcript) }) + return promise } /** Non-event settlement evidence: the liveness activity read observed a run diff --git a/packages/ui/src/stores/opencode-projection-frame.ts b/packages/ui/src/stores/opencode-projection-frame.ts index 11a8535079..60ff4f2d43 100644 --- a/packages/ui/src/stores/opencode-projection-frame.ts +++ b/packages/ui/src/stores/opencode-projection-frame.ts @@ -57,6 +57,13 @@ export function setTranscriptProjectionGates(next: TranscriptProjectionGates): v gates = next } +/** Whether the instance layer registered its projection gates: a publisher + * outside the dispatcher routes through the scheduler when it did and falls + * back to a direct projection otherwise (unit contexts). */ +export function hasTranscriptProjectionGates(): boolean { + return gates !== undefined +} + function projectionKey(instanceId: string, sessionId: string): string { return `${instanceId}\u0000${sessionId}` } diff --git a/packages/ui/src/stores/opencode-reconnect.ts b/packages/ui/src/stores/opencode-reconnect.ts index c44642a771..6fe4879142 100644 --- a/packages/ui/src/stores/opencode-reconnect.ts +++ b/packages/ui/src/stores/opencode-reconnect.ts @@ -11,6 +11,10 @@ export interface ReconnectCapture { directory: string messages: SessionMessageInfo[] retireWhenDrained: boolean + /** An inbox-delivery repair whose read was still outstanding at the reset: + * the seeded page may carry the unreconciled order, so seeding owes it a new + * read rather than waiting for the quiet reconciliation. */ + deliveryRepairOwed: boolean onResynced?: (data: Data) => void } @@ -26,6 +30,8 @@ export interface ReconnectHost { recreateTranscript(instanceId: string, capture: ReconnectCapture): TranscriptEntry /** Seed the recreated entry with the captured page. */ seedPage(instanceId: string, capture: ReconnectCapture): Promise + /** Resume a captured delivery repair after the seeded page landed. */ + resumeDeliveryRepair(instanceId: string, sessionId: string, transcript: TranscriptEntry): void /** Dropping-mode recovery, used when seeding fails. */ scheduleDroppingResync(instanceId: string, sessionId: string, transcript: TranscriptEntry): void isCurrent(instanceId: string, sessionId: string, transcript: TranscriptEntry): boolean @@ -71,7 +77,12 @@ export function createReconnect(host: ReconnectHost) { // Arm the trailing timer before seeding: while it is pending, deferred // retirement cannot fire on a transcript whose page has not landed yet. scheduleTrailing(instanceId, capture.sessionId, transcript) - void host.seedPage(instanceId, capture).catch(() => { + void host.seedPage(instanceId, capture).then(() => { + // The seeded page carries whatever order the reset caught, including + // an unreconciled delivery; a captured repair resumes now instead of + // trailing behind the quiet reconciliation. + if (capture.deliveryRepairOwed) host.resumeDeliveryRepair(instanceId, capture.sessionId, transcript) + }).catch(() => { // Seeding failed: fall back to dropping-mode recovery so the transcript // still reconciles from one quiet authoritative snapshot. transcript.reconnectResync = false diff --git a/packages/ui/tests/browser/inbox-delivery-order.test.ts b/packages/ui/tests/browser/inbox-delivery-order.test.ts index f54abddcf5..00c6f07a15 100644 --- a/packages/ui/tests/browser/inbox-delivery-order.test.ts +++ b/packages/ui/tests/browser/inbox-delivery-order.test.ts @@ -34,12 +34,21 @@ async function open(run: (page: Page) => Promise) { const page = await browser.newPage({ viewport: { width: 1100, height: 700 }, locale: "en-US" }) const errors: string[] = [] page.on("pageerror", error => errors.push(error.message)) + page.on("console", message => { if (message.type() === "error") errors.push(message.text()) }) + page.on("requestfailed", request => { + // A canceled in-flight receipts read is the UI superseding it, not a failure. + if (request.url().includes("/permission-receipts") && request.failure()?.errorText === "net::ERR_ABORTED") return + errors.push(`request failed: ${request.url()} ${request.failure()?.errorText ?? ""}`) + }) + page.on("response", response => { if (response.status() >= 400) errors.push(`http ${response.status()}: ${response.url()}`) }) await page.route("**/api/**", route => { if (new URL(route.request().url()).pathname.endsWith("/permission-receipts")) { return route.fulfill({ contentType: "application/json", body: JSON.stringify({ receipts: [] }) }) } return route.fulfill({ contentType: route.request().url().includes("events") ? "text/event-stream" : "application/json", body: "" }) }) + await page.route("**/workspaces/browser-instance/yolo/sessions/browser-session", route => + route.request().method() === "GET" ? route.fulfill({ json: { enabled: false } }) : route.continue()) await events.route(page) await runWithDiagnosticCleanup({ run: async () => { From 4b54769c215c2f14371159ea9ed992690701a766 Mon Sep 17 00:00:00 2001 From: heunghingwan Date: Mon, 9 Nov 2026 22:42:54 +0800 Subject: [PATCH 4/8] fix(transcript): retire a settled reducer once its delivery repair settles MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of 5cd1a058 (thanks @pascalandr): the repair counter's decrement ran after the read's own publication pass, whose retirement check still saw the barrier — so a reducer whose round had settled stayed resident with its rows after the repair completed, rejected or aborted, and no later event existed to retry the retirement. The counter's finally now retries retireDrainedTranscript right after decrementing; abandoned scopes stay protected by the current-transcript guard. The receipts-abort exclusion in the browser fixture is gone (the strict collection passes without it), and the publication gates gain authored regressions: a repair completing over a history window keeps that window's membership and cursors, and a repair completing for an inactive session leaves its display to the next activation read. Validation: 253 focused store tests, UI typecheck, the delivery browser file twice with strict request/HTTP/console error collection. --- .../stores/opencode-data-settlement.test.ts | 58 +++++++++++++++++++ packages/ui/src/stores/opencode-data.ts | 9 ++- .../browser/inbox-delivery-order.test.ts | 6 +- 3 files changed, 67 insertions(+), 6 deletions(-) diff --git a/packages/ui/src/stores/opencode-data-settlement.test.ts b/packages/ui/src/stores/opencode-data-settlement.test.ts index c7bab89479..9adf9f93cd 100644 --- a/packages/ui/src/stores/opencode-data-settlement.test.ts +++ b/packages/ui/src/stores/opencode-data-settlement.test.ts @@ -286,3 +286,61 @@ test("a delivery crossing an HTTP-ahead settlement read reconciles through its o assert.deepEqual(order(), ["m1", "msg_4", "msg_user", "reply", "msg_8"], "the crossing prompt reconciles above its reply") } finally { f.cleanup() } }) + +test("a delivery repair completing over a history window leaves that window's membership alone", async () => { + const instanceId = "native-delivery-history-window" + const f = fixture(instanceId) + const store = messageStoreBus.getOrCreate(instanceId) + const sessionId = "s" + try { + f.emit("session.inbox.enqueued", { sessionID: sessionId, inboxID: "msg_h", item: { type: "user", payload: { text: "parked" }, delivery: "steer" } }) + f.emit("session.step.started", { sessionID: sessionId, assistantMessageID: "h_reply", agent: "build", model, started: 2 }) + f.emit("session.inbox.delivered", { sessionID: sessionId, inboxID: "msg_h" }) + assert.equal(f.reads.length, 1, "the relocating delivery owed a repair read") + await flush() + const sunk = store.getSessionMessageIds(sessionId) + assert.deepEqual(sunk, ["h_reply", "msg_h"], "the late delivery sinks the prompt until the repair lands") + + // The reader moves to a history window before the repair completes: the + // repair must not rewrite that window's membership or cursors. + store.setMessageWindow(sessionId, { kind: "history", resumeCursor: "c1", newerCursors: [null] }) + f.reads[0].resolve({ + data: [ + { id: "msg_h", type: "user", text: "parked", time: { created: 3 } }, + { id: "h_reply", type: "assistant", agent: "build", model, time: { created: 2 }, content: [] }, + ].reverse(), + cursor: {}, + }) + await flush() + assert.deepEqual(store.getSessionMessageIds(sessionId), sunk, "the history window keeps its membership") + assert.equal(store.getMessageWindow(sessionId)?.kind, "history", "the window keeps its cursors") + } finally { f.cleanup() } +}) + +test("a delivery repair completing for an inactive session does not project into its display", async () => { + const instanceId = "native-delivery-inactive" + const f = fixture(instanceId) + const store = messageStoreBus.getOrCreate(instanceId) + const sessionId = "s" + try { + f.emit("session.inbox.enqueued", { sessionID: sessionId, inboxID: "msg_i", item: { type: "user", payload: { text: "parked" }, delivery: "steer" } }) + f.emit("session.step.started", { sessionID: sessionId, assistantMessageID: "i_reply", agent: "build", model, started: 2 }) + f.emit("session.inbox.delivered", { sessionID: sessionId, inboxID: "msg_i" }) + assert.equal(f.reads.length, 1, "the relocating delivery owed a repair read") + await flush() + const before = store.getSessionMessageIds(sessionId) + + // The reader switches sessions before the repair completes: the inactive + // session's display is left to its next activation read. + setActiveSession(instanceId, "other") + f.reads[0].resolve({ + data: [ + { id: "msg_i", type: "user", text: "parked", time: { created: 3 } }, + { id: "i_reply", type: "assistant", agent: "build", model, time: { created: 2 }, content: [] }, + ].reverse(), + cursor: {}, + }) + await flush() + assert.deepEqual(store.getSessionMessageIds(sessionId), before, "an inactive session's display keeps its projected page") + } finally { f.cleanup() } +}) diff --git a/packages/ui/src/stores/opencode-data.ts b/packages/ui/src/stores/opencode-data.ts index 86aabd6f49..9a13858f39 100644 --- a/packages/ui/src/stores/opencode-data.ts +++ b/packages/ui/src/stores/opencode-data.ts @@ -381,7 +381,14 @@ function reconcileDeliveredPromptPage(instanceId: string, sessionId: string, tra transcript.deliveryRepairOwed = false transcript.entry.data.session.message.invalidate(sessionId) void completeSettlementRead(instanceId, sessionId, transcript, { publishGated: true }) - ?.finally(() => { transcript.deliveryRepairPending = Math.max(0, transcript.deliveryRepairPending - 1) }) + ?.finally(() => { + transcript.deliveryRepairPending = Math.max(0, transcript.deliveryRepairPending - 1) + // The read's own publication pass ran its retirement check while this + // counter still held the barrier; retry it now that the repair settled, + // so a drained settlement is not left resident. Abandoned scopes are + // already guarded by the current-transcript check. + retireDrainedTranscript(instanceId, sessionId, transcript) + }) } function getOpenCodeFullDataRevision(instanceId: string, sessionId: string): number { diff --git a/packages/ui/tests/browser/inbox-delivery-order.test.ts b/packages/ui/tests/browser/inbox-delivery-order.test.ts index 00c6f07a15..fb3a547827 100644 --- a/packages/ui/tests/browser/inbox-delivery-order.test.ts +++ b/packages/ui/tests/browser/inbox-delivery-order.test.ts @@ -35,11 +35,7 @@ async function open(run: (page: Page) => Promise) { const errors: string[] = [] page.on("pageerror", error => errors.push(error.message)) page.on("console", message => { if (message.type() === "error") errors.push(message.text()) }) - page.on("requestfailed", request => { - // A canceled in-flight receipts read is the UI superseding it, not a failure. - if (request.url().includes("/permission-receipts") && request.failure()?.errorText === "net::ERR_ABORTED") return - errors.push(`request failed: ${request.url()} ${request.failure()?.errorText ?? ""}`) - }) + page.on("requestfailed", request => errors.push(`request failed: ${request.url()} ${request.failure()?.errorText ?? ""}`)) page.on("response", response => { if (response.status() >= 400) errors.push(`http ${response.status()}: ${response.url()}`) }) await page.route("**/api/**", route => { if (new URL(route.request().url()).pathname.endsWith("/permission-receipts")) { From dd5dc9d5788205d9728025e4ba38ce9debdf5a81 Mon Sep 17 00:00:00 2001 From: heunghingwan Date: Mon, 9 Nov 2026 23:05:09 +0800 Subject: [PATCH 5/8] fix(transcript): keep the retirement flush behind the active-session gate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of c0412d1f (thanks @pascalandr): the retirement retry's scoped flush drained with the active gate bypassed, so a repair settling for an inactive session rewrote its display and left it marked loaded — the next activation could then skip the authoritative read. A scoped flushTranscriptProjections now keeps the gate: an inactive session's pending page is invalidated for its next activation read exactly as a normal frame does, while the unscoped selection-change flush still lands pages admitted under the previous selection. The HTTP-ahead regression now also asserts the settled reducer retired once the repair settled (the next event lands on a fresh one), and the browser fixture correlates receipts aborts to the cache's own supersession — an abort with no successor read for the same message still fails the test. Validation: 253 focused store tests, UI typecheck, the delivery browser file twice with strict error collection. --- .../stores/opencode-data-settlement.test.ts | 14 ++++++++++- .../src/stores/opencode-projection-frame.ts | 7 ++++-- .../browser/inbox-delivery-order.test.ts | 25 ++++++++++++++++++- 3 files changed, 42 insertions(+), 4 deletions(-) diff --git a/packages/ui/src/stores/opencode-data-settlement.test.ts b/packages/ui/src/stores/opencode-data-settlement.test.ts index 9adf9f93cd..4640b3b0b1 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, invalidateOpenCodeSessionContent } from "./opencode-data.ts" +import { destroyOpenCodeData, applyOpenCodeDataEvent, invalidateOpenCodeSessionContent } from "./opencode-data.ts" import { handleNativeSessionEvent } from "./session-events.ts" import { setActiveSession, setSessions } from "./session-state.ts" @@ -284,6 +284,18 @@ test("a delivery crossing an HTTP-ahead settlement read reconciles through its o f.reads[1].resolve({ data: [...page].reverse(), cursor: {} }) await flush() assert.deepEqual(order(), ["m1", "msg_4", "msg_user", "reply", "msg_8"], "the crossing prompt reconciles above its reply") + + // The settled reducer retired once the repair settled: the next event + // lands on a fresh one, holding only its own row. + const after = applyOpenCodeDataEvent("native-delivery-http-ahead", "/fixture", { + id: "evt_probe", type: "session.step.started", created: 99, location: { directory: "/fixture" }, + data: { sessionID: sessionId, assistantMessageID: "m3", agent: "build", model, started: 9 }, + } as any) + await flush() + assert.deepEqual( + after.session.message.list(sessionId).map((row: { id: string }) => row.id), + ["m3"], + "the settled reducer retired once the repair settled") } finally { f.cleanup() } }) diff --git a/packages/ui/src/stores/opencode-projection-frame.ts b/packages/ui/src/stores/opencode-projection-frame.ts index 60ff4f2d43..f41ef01274 100644 --- a/packages/ui/src/stores/opencode-projection-frame.ts +++ b/packages/ui/src/stores/opencode-projection-frame.ts @@ -99,7 +99,10 @@ export function scheduleTranscriptProjection( * a normal reducer retirement publishes its session's final page (including * usage obligations) before the reducer goes away, while resets, eviction and * destructive teardown stay cancel-only. An optional scope publishes only the - * matching sessions and leaves the rest on their frame. */ + * matching sessions and leaves the rest on their frame; a scoped flush keeps + * the active-session gate, so a retirement landing on an inactive session + * invalidates its loaded page for the next activation read instead of + * rewriting its display. */ export function flushTranscriptProjections(instanceId?: string, sessionId?: string): void { if (instanceId === undefined) { drain(true) @@ -109,7 +112,7 @@ export function flushTranscriptProjections(instanceId?: string, sessionId?: stri const matches = sessionId === undefined ? (key: string) => key.startsWith(prefix) : (key: string) => key === projectionKey(instanceId, sessionId) - drain(true, matches) + drain(false, matches) } /** Removes and returns a session's pending projection. A synchronous diff --git a/packages/ui/tests/browser/inbox-delivery-order.test.ts b/packages/ui/tests/browser/inbox-delivery-order.test.ts index fb3a547827..9226bc28e2 100644 --- a/packages/ui/tests/browser/inbox-delivery-order.test.ts +++ b/packages/ui/tests/browser/inbox-delivery-order.test.ts @@ -35,8 +35,27 @@ async function open(run: (page: Page) => Promise) { const errors: string[] = [] page.on("pageerror", error => errors.push(error.message)) page.on("console", message => { if (message.type() === "error") errors.push(message.text()) }) - page.on("requestfailed", request => errors.push(`request failed: ${request.url()} ${request.failure()?.errorText ?? ""}`)) page.on("response", response => { if (response.status() >= 400) errors.push(`http ${response.status()}: ${response.url()}`) }) + // The receipts cache aborts an in-flight read exactly when a newer read for + // the same message supersedes it; an abort with no successor is a failure. + let requestSequence = 0 + const receiptsReads = new Map() + const abortedReceipts: Array<{ marker: string; seq: number; message: string }> = [] + page.on("request", request => { + const url = new URL(request.url()) + if (!url.pathname.endsWith("/permission-receipts")) return + const marker = url.searchParams.get("messageId") ?? "" + const seq = ++requestSequence + receiptsReads.set(marker, [...receiptsReads.get(marker) ?? [], seq]) + }) + page.on("requestfailed", request => { + const url = new URL(request.url()) + if (url.pathname.endsWith("/permission-receipts") && request.failure()?.errorText === "net::ERR_ABORTED") { + abortedReceipts.push({ marker: url.searchParams.get("messageId") ?? "", seq: ++requestSequence, message: `request failed: ${request.url()} net::ERR_ABORTED` }) + return + } + errors.push(`request failed: ${request.url()} ${request.failure()?.errorText ?? ""}`) + }) await page.route("**/api/**", route => { if (new URL(route.request().url()).pathname.endsWith("/permission-receipts")) { return route.fulfill({ contentType: "application/json", body: JSON.stringify({ receipts: [] }) }) @@ -51,6 +70,10 @@ async function open(run: (page: Page) => Promise) { await page.goto(url) await page.waitForFunction(() => Boolean((window as any).fixture)) await run(page) + for (const abort of abortedReceipts) { + const superseded = (receiptsReads.get(abort.marker) ?? []).some(seq => seq > abort.seq) + if (!superseded) errors.push(abort.message) + } assert.deepEqual(errors, []) }, diagnose: async () => { From 864eb987e88f2a8fe176a175af8461b0d3e1897d Mon Sep 17 00:00:00 2001 From: heunghingwan Date: Mon, 9 Nov 2026 23:27:35 +0800 Subject: [PATCH 6/8] test(transcript): classify a receipts abort by its own AbortSignal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of 87c035a9 (thanks @pascalandr): the successor-read heuristic both flaked (an abort is numbered when it fails, so a successor issued between request and failure was missed) and accepted a foreign abort whose messageId an unrelated later request reused — and the cache also cancels on last-subscriber release, with no successor at all. The fixture now tags each receipts read's fetch with a per-read header and records whether its own AbortSignal fired (the panel-read pattern); the test tolerates exactly an abort whose tagged request the cache's signal owned, and every foreign or unclassified failure stays an error. Validation: the delivery browser file passes three consecutive runs with the strict collector; session rendering (48) and UI typecheck unchanged. --- .../ui/tests/browser/fixtures/session.tsx | 29 +++++++++++++++++ .../browser/inbox-delivery-order.test.ts | 32 ++++++++----------- 2 files changed, 43 insertions(+), 18 deletions(-) diff --git a/packages/ui/tests/browser/fixtures/session.tsx b/packages/ui/tests/browser/fixtures/session.tsx index a76cd806e3..8a3df37d68 100644 --- a/packages/ui/tests/browser/fixtures/session.tsx +++ b/packages/ui/tests/browser/fixtures/session.tsx @@ -9,6 +9,7 @@ import { addInstance } from "../../../src/stores/instances" import { sessions, setSessions, setActiveSession, setProviders } from "../../../src/stores/session-state" import { messageStoreBus } from "../../../src/stores/message-v2/bus" import { sseManager } from "../../../src/lib/sse-manager" +import { serverApi } from "../../../src/lib/api-client" import { loadMessages } from "../../../src/stores/session-api" import { applyUiSettings } from "./ui-settings" import "../../../src/index.css" @@ -78,6 +79,34 @@ setActiveSession(instanceId, sessionId) const [visible, setVisible] = createSignal(true) const [active, setActive] = createSignal(true) const store = messageStoreBus.getOrCreate(instanceId) + +// The receipts cache cancels its own in-flight reads (a joining read aborts +// the one it replaces; the last subscriber releasing aborts its read). Tag +// each read's fetch and record whether its own AbortSignal fired, so tests +// can tell an owned cancellation from a foreign failure. +const receiptsOutcomes = new Map>() +{ + const original = serverApi.fetchPermissionReceipts.bind(serverApi) + let readSequence = 0 + serverApi.fetchPermissionReceipts = ((instanceId: string, sessionId: string, scope: { messageId: string } | { unanchored: true }, cursor?: string, signal?: AbortSignal) => { + const id = String(++readSequence) + const originalFetch = window.fetch + window.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { + const headers = new Headers(init?.headers) + headers.set("x-codenomad-fixture-receipts-read", id) + return originalFetch.call(window, input, { ...init, headers }) + }) as typeof window.fetch + try { + const result = original(instanceId, sessionId, scope, cursor, signal) + receiptsOutcomes.set(id, result.then(() => false, error => + signal?.aborted === true && error instanceof DOMException && error.name === "AbortError")) + return result + } finally { + window.fetch = originalFetch + } + }) as typeof serverApi.fetchPermissionReceipts +} +;(window as any).fixtureReceiptsReadCancelled = async (id: string) => await receiptsOutcomes.get(id) ?? false render(() => , document.getElementById("root")!) diff --git a/packages/ui/tests/browser/inbox-delivery-order.test.ts b/packages/ui/tests/browser/inbox-delivery-order.test.ts index 9226bc28e2..56c7a5deb1 100644 --- a/packages/ui/tests/browser/inbox-delivery-order.test.ts +++ b/packages/ui/tests/browser/inbox-delivery-order.test.ts @@ -36,25 +36,24 @@ async function open(run: (page: Page) => Promise) { page.on("pageerror", error => errors.push(error.message)) page.on("console", message => { if (message.type() === "error") errors.push(message.text()) }) page.on("response", response => { if (response.status() >= 400) errors.push(`http ${response.status()}: ${response.url()}`) }) - // The receipts cache aborts an in-flight read exactly when a newer read for - // the same message supersedes it; an abort with no successor is a failure. - let requestSequence = 0 - const receiptsReads = new Map() - const abortedReceipts: Array<{ marker: string; seq: number; message: string }> = [] + // Keep every raw failure; classify only an abort the receipts cache's own + // AbortSignal owns (the fixture tags each read and records its outcome). + const receiptsIdentities = new Map() + const receiptsChecks: Array> = [] page.on("request", request => { - const url = new URL(request.url()) - if (!url.pathname.endsWith("/permission-receipts")) return - const marker = url.searchParams.get("messageId") ?? "" - const seq = ++requestSequence - receiptsReads.set(marker, [...receiptsReads.get(marker) ?? [], seq]) + const id = request.headers()["x-codenomad-fixture-receipts-read"] + if (id && !receiptsIdentities.has(id)) receiptsIdentities.set(id, request) }) page.on("requestfailed", request => { - const url = new URL(request.url()) - if (url.pathname.endsWith("/permission-receipts") && request.failure()?.errorText === "net::ERR_ABORTED") { - abortedReceipts.push({ marker: url.searchParams.get("messageId") ?? "", seq: ++requestSequence, message: `request failed: ${request.url()} net::ERR_ABORTED` }) + const failure = `request failed: ${request.url()} ${request.failure()?.errorText ?? ""}` + const id = request.headers()["x-codenomad-fixture-receipts-read"] + if (request.failure()?.errorText !== "net::ERR_ABORTED" || !id || receiptsIdentities.get(id) !== request) { + errors.push(failure) return } - errors.push(`request failed: ${request.url()} ${request.failure()?.errorText ?? ""}`) + receiptsChecks.push(page.evaluate(id => (window as any).fixtureReceiptsReadCancelled(id), id).then(cancelled => { + if (!cancelled) errors.push(failure) + })) }) await page.route("**/api/**", route => { if (new URL(route.request().url()).pathname.endsWith("/permission-receipts")) { @@ -70,10 +69,7 @@ async function open(run: (page: Page) => Promise) { await page.goto(url) await page.waitForFunction(() => Boolean((window as any).fixture)) await run(page) - for (const abort of abortedReceipts) { - const superseded = (receiptsReads.get(abort.marker) ?? []).some(seq => seq > abort.seq) - if (!superseded) errors.push(abort.message) - } + await Promise.all(receiptsChecks) assert.deepEqual(errors, []) }, diagnose: async () => { From b24e23b56013b4b7e9af17562cd2719131f92f67 Mon Sep 17 00:00:00 2001 From: heunghingwan Date: Mon, 9 Nov 2026 23:47:40 +0800 Subject: [PATCH 7/8] fix(transcript): settle repair obligations with the publishing chain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rebase onto #1414 (9f00cffb) surfaced an ordering hazard in the merged completeSettlementRead: the SDK read promise settles one microtask hop before the publishing chain (which passes through .catch), so a caller holding obligations on the returned promise — the delivery repair's counter decrement and retirement retry — ran its retirement before the chain published, destroying the reducer and fencing out the repair's publication. completeSettlementRead now records and returns the publishing chain itself; the shared in-flight path returns the recorded chain, and replaceTranscriptEntry releases it with the other read state. Validation: 259 focused store tests on the rebased tree, UI typecheck, the delivery browser file and the fixture-wiring gate. --- packages/ui/src/stores/opencode-data.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/ui/src/stores/opencode-data.ts b/packages/ui/src/stores/opencode-data.ts index 9a13858f39..26bd747b5d 100644 --- a/packages/ui/src/stores/opencode-data.ts +++ b/packages/ui/src/stores/opencode-data.ts @@ -82,6 +82,9 @@ type TranscriptEntry = { * 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 publishing chain the recorded read armed; callers holding obligations + * on the read settle with it (the SDK promise settles one hop earlier). */ + settlementReadChain?: 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. */ @@ -350,6 +353,7 @@ function replaceTranscriptEntry(transcript: TranscriptEntry, next: DataEntry): v transcript.settlementReadPending = false transcript.settlementReadEntry = undefined transcript.settlementReadPromise = undefined + transcript.settlementReadChain = undefined transcript.entry = next previous.dispose() transcript.entryRevision[1]((value) => value + 1) @@ -1075,10 +1079,10 @@ function completeSettlementRead( transcript.settlementReadEntry = entry transcript.settlementReadEpoch = transcript.executionEpoch const promise = entry.data.session.message.sync(sessionId) - if (transcript.settlementReadPromise === promise) return promise + if (transcript.settlementReadPromise === promise) return transcript.settlementReadChain ?? promise transcript.settlementReadPromise = promise const followed = promise - void followed + const chain = followed .catch(() => undefined) .then(() => { // A newer demand re-followed a later read, or a replaced reducer @@ -1087,6 +1091,7 @@ function completeSettlementRead( transcript.settlementReadPending = false transcript.settlementReadEntry = undefined transcript.settlementReadPromise = undefined + transcript.settlementReadChain = 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. @@ -1103,7 +1108,8 @@ function completeSettlementRead( } retireDrainedTranscript(instanceId, sessionId, transcript) }) - return promise + transcript.settlementReadChain = chain + return chain } /** Non-event settlement evidence: the liveness activity read observed a run From 32d03085cb6373aeb66e5920a962a3fba18125fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pascal=20Andr=C3=A9?= Date: Mon, 9 Nov 2026 17:10:56 +0100 Subject: [PATCH 8/8] fix(transcript): keep a reducer until a superseding reconciliation read publishes A delivery repair settles its counter when the read chain it started ends. When a later settlement (an execution terminal event, or an observed settlement followed by one) invalidates beneath that read, the SDK starts a trailing read that owns the publication; the repair's chain then ends early and its retirement retry destroyed the reducer before the trailing read published. A tool whose terminal event was missed stayed visibly running even though the authoritative page had it completed. Retirement now also waits while a reconciliation read is pending for the current reducer; that read's own completion retries retirement after it publishes. The browser fixture's receipts-cancellation check also handles a verification that cannot complete (page closed or navigated) by keeping the original failure instead of rejecting unhandled. Test: a queued delivery repair superseded by the round's settlement read keeps the reducer until the trailing read publishes the completed tool; removing the retirement guard fails it. --- .../stores/opencode-data-settlement.test.ts | 41 +++++++++++++++++++ packages/ui/src/stores/opencode-data.ts | 5 ++- .../browser/inbox-delivery-order.test.ts | 9 ++-- 3 files changed, 51 insertions(+), 4 deletions(-) diff --git a/packages/ui/src/stores/opencode-data-settlement.test.ts b/packages/ui/src/stores/opencode-data-settlement.test.ts index 4640b3b0b1..207ec88592 100644 --- a/packages/ui/src/stores/opencode-data-settlement.test.ts +++ b/packages/ui/src/stores/opencode-data-settlement.test.ts @@ -299,6 +299,47 @@ test("a delivery crossing an HTTP-ahead settlement read reconciles through its o } finally { f.cleanup() } }) +test("a settlement read superseding a delivery repair keeps the reducer until it publishes", async () => { + const instanceId = "native-delivery-superseded-repair" + const f = fixture(instanceId) + const sessionId = "s" + const zero = { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } } + const tool = () => Object.values(messageStoreBus.getOrCreate(instanceId).getMessage("prior")?.parts ?? {}) + .map((part: any) => part.data).find((part: any) => part.type === "tool") as any + try { + f.emit("session.step.started", { sessionID: sessionId, assistantMessageID: "initial", agent: "build", model, started: 1 }) + f.emit("session.inbox.enqueued", { sessionID: sessionId, inboxID: "q", item: { type: "user", payload: { text: "queued follow-up" }, delivery: "queue" } }) + f.emit("session.step.ended", { sessionID: sessionId, assistantMessageID: "initial", finish: "stop", cost: 0, tokens: zero }) + f.emit("session.step.started", { sessionID: sessionId, assistantMessageID: "prior", agent: "build", model, started: 2 }) + f.emit("session.tool.input.started", { sessionID: sessionId, assistantMessageID: "prior", id: "lost", name: "read" }) + f.emit("session.tool.called", { sessionID: sessionId, assistantMessageID: "prior", id: "lost", input: {} }) + // The tool finished natively, but its terminal event never arrived. + f.emit("session.step.ended", { sessionID: sessionId, assistantMessageID: "prior", finish: "stop", cost: 0, tokens: zero }) + f.emit("session.inbox.delivered", { sessionID: sessionId, inboxID: "q" }) + assert.equal(f.reads.length, 1, "the relocating delivery started repair read A") + f.emit("session.step.started", { sessionID: sessionId, assistantMessageID: "reply", agent: "build", model, started: 3 }) + f.emit("session.step.ended", { sessionID: sessionId, assistantMessageID: "reply", finish: "stop", cost: 0, tokens: zero }) + // The settlement invalidates beneath A: its trailing read B owns publication. + f.emit("session.execution.succeeded", { sessionID: sessionId }) + assert.equal(tool()?.state?.status, "running") + const page = [ + { id: "initial", type: "assistant", agent: "build", model, time: { created: 1, completed: 2 }, content: [] }, + { id: "prior", type: "assistant", agent: "build", model, time: { created: 2, completed: 3 }, content: [{ + type: "tool", id: "lost", name: "read", time: { created: 2, ran: 3, completed: 4 }, + state: { status: "completed", input: {}, content: [{ type: "text", text: "native result" }], metadata: {} }, + }] }, + { id: "q", type: "user", text: "queued follow-up", time: { created: 3 } }, + { id: "reply", type: "assistant", agent: "build", model, time: { created: 4, completed: 5 }, content: [] }, + ] + f.reads[0].resolve({ data: [...page].reverse(), cursor: {} }) + await flush(); await flush() + assert.equal(f.reads.length, 2, "the superseding read B started") + f.reads[1].resolve({ data: [...page].reverse(), cursor: {} }) + await flush(); await flush() + assert.equal(tool()?.state?.status, "completed", "B publishes before the settled reducer retires") + } finally { f.cleanup() } +}) + test("a delivery repair completing over a history window leaves that window's membership alone", async () => { const instanceId = "native-delivery-history-window" const f = fixture(instanceId) diff --git a/packages/ui/src/stores/opencode-data.ts b/packages/ui/src/stores/opencode-data.ts index 26bd747b5d..60fb6b1510 100644 --- a/packages/ui/src/stores/opencode-data.ts +++ b/packages/ui/src/stores/opencode-data.ts @@ -1012,9 +1012,12 @@ function retireDrainedTranscript(instanceId: string, sessionId: string, transcri || transcript.retryTimer || transcript.queue.length) return // Work that outlives the settlement still needs this reducer: prompts parked in // its inbox (e.g. after an interruption) are listed from it, unsettled rows - // settle only in it, and an outstanding delivery repair publishes through it. + // settle only in it, and an outstanding delivery repair or shared + // reconciliation read publishes through it (a trailing read that superseded + // a repair's read owns its publication, and its own completion retries this). const data = transcript.entry.data if (transcript.deliveryRepairPending > 0 || transcript.deliveryRepairOwed + || (transcript.settlementReadPending && transcript.settlementReadEntry === transcript.entry) || data.session.pending.list(sessionId).length || data.session.message.list(sessionId).some(isUnsettledAtSettlement)) return // The reducer's final coalesced page — e.g. a tool that settled after the // execution did — publishes here, before normal retirement destroys the diff --git a/packages/ui/tests/browser/inbox-delivery-order.test.ts b/packages/ui/tests/browser/inbox-delivery-order.test.ts index 56c7a5deb1..e630251770 100644 --- a/packages/ui/tests/browser/inbox-delivery-order.test.ts +++ b/packages/ui/tests/browser/inbox-delivery-order.test.ts @@ -51,9 +51,12 @@ async function open(run: (page: Page) => Promise) { errors.push(failure) return } - receiptsChecks.push(page.evaluate(id => (window as any).fixtureReceiptsReadCancelled(id), id).then(cancelled => { - if (!cancelled) errors.push(failure) - })) + // A verification that cannot complete (page closed or navigated) keeps the + // original failure instead of rejecting unhandled. + receiptsChecks.push(page.evaluate(id => (window as any).fixtureReceiptsReadCancelled(id), id).then( + cancelled => { if (!cancelled) errors.push(failure) }, + () => { errors.push(failure) }, + )) }) await page.route("**/api/**", route => { if (new URL(route.request().url()).pathname.endsWith("/permission-receipts")) {