diff --git a/dev-docs/TRANSCRIPT.md b/dev-docs/TRANSCRIPT.md index 324a4a46af..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. 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 45093b9e47..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,89 @@ 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) + 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-settlement.test.ts b/packages/ui/src/stores/opencode-data-settlement.test.ts index 6b40c76912..207ec88592 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" @@ -230,3 +230,170 @@ 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") + + // 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() } +}) + +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) + 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.test.ts b/packages/ui/src/stores/opencode-data.test.ts index c780935f36..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,26 +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") - assert.deepEqual(messageStoreBus.getOrCreate(instanceId).getSessionMessageIds(sessionId), ["other", "queued"]) + 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 9d7f06373d..60fb6b1510 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") @@ -81,11 +82,20 @@ 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. */ 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 +337,8 @@ function ensureTranscript(instanceId: string, sessionId: string, directory: stri settlementReadPending: false, settlementReadEpoch: 0, queue: [], + deliveryRepairPending: 0, + deliveryRepairOwed: false, } transcriptEntries.set(key, transcript) return transcript @@ -341,11 +353,48 @@ 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) } +/** 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 false + const rows = entry.data.session.message.list(sessionId) + const index = rows.findIndex(row => row.id === inboxID) + return index >= 0 && index !== rows.length - 1 +} + +/** 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 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) + void completeSettlementRead(instanceId, sessionId, transcript, { publishGated: true }) + ?.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 { return fullDataRevisions.get(messageRevisionKey(instanceId, sessionId)) ?? 0 } @@ -424,6 +473,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, }) } @@ -435,6 +485,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 @@ -443,6 +494,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, @@ -589,12 +645,14 @@ async function drainTranscriptQueue( break } transcript.queue.shift() + 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) { @@ -794,6 +852,7 @@ export function applyOpenCodeDataEvent( return transcript.entry.data } } + 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 @@ -801,6 +860,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)) { @@ -949,10 +1011,14 @@ 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 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 (data.session.pending.list(sessionId).length || data.session.message.list(sessionId).some(isUnsettledAtSettlement)) return + 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 // entry; resets, eviction and destructive teardown cancel instead. @@ -996,8 +1062,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 @@ -1009,10 +1082,10 @@ 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 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 @@ -1021,14 +1094,25 @@ function completeSettlementRead(instanceId: string, sessionId: string, transcrip 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. 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) }) + transcript.settlementReadChain = chain + return chain } /** 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..f41ef01274 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}` } @@ -92,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) @@ -102,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/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/fixtures/session.tsx b/packages/ui/tests/browser/fixtures/session.tsx index c30ad86f95..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")!) @@ -97,6 +126,33 @@ 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 }) + }, + /** 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 new file mode 100644 index 0000000000..e630251770 --- /dev/null +++ b/packages/ui/tests/browser/inbox-delivery-order.test.ts @@ -0,0 +1,155 @@ +import assert from "node:assert/strict" +import { after, before, test } from "node:test" +import { chromium, type Browser, type Page } from "playwright" +import { borrowFixture } from "./fixture-borrow" +import { armFixtureNavigationBudget } from "./fixture-navigation-budget" +import { fixtureEventStream } from "./fixture-event-stream" +import { runWithDiagnosticCleanup } from "./fixture-diagnostic-boundary" + +// 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 () => { + 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 () => { 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" }) + 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("response", response => { if (response.status() >= 400) errors.push(`http ${response.status()}: ${response.url()}`) }) + // 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 id = request.headers()["x-codenomad-fixture-receipts-read"] + if (id && !receiptsIdentities.has(id)) receiptsIdentities.set(id, request) + }) + page.on("requestfailed", request => { + 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 + } + // 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")) { + 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 () => { + await page.goto(url) + await page.waitForFunction(() => Boolean((window as any).fixture)) + await run(page) + await Promise.all(receiptsChecks) + 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), + }) +} + +/** 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 ?? "")) +} + +/** 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) + 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 renders above the reply the engine starts for it", async () => { + await open(async page => { + const marker = "Prompt from the other terminal" + 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 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 assertOrder(page, [marker, reply]) + }) +}) + +test("a steer burst delivered while parked keeps the native page order", async () => { + await open(async page => { + 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 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 assertOrder(page, [earlier, marker]) + }) +})