diff --git a/AGENTS.md b/AGENTS.md index dfc78bbcb..aeb5effa4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1141,6 +1141,36 @@ end to end: dropped or reordered. Merged frames keep the latest frame's sequence and emit time and carry `web.first`, their first piece's sequence. Deltas of different blocks never merge past each other: that would break the sequence order. +- Tool snapshots (`event-stream-hub.ts`, session channel): omp sends the whole + accumulated output on every `tool_execution_update`, so the newest snapshot per + `toolCallId` is held **outside** the ordered message queue and written at most + once per `TOOL_UPDATE_FRAME_MIN_INTERVAL_MS` of that tool. A tool frame needs + no position among the deltas: the browser fences it by `max(lifecycleSequence, + toolsSnapshotSequence, toolSequences.get(tool))` and never by + `messageSequence` (`hooks/useAgentSession-sync.ts`). Three consequences, all + required: a message delta neither waits for a held snapshot nor releases one + (otherwise a bash tool printing during a streaming turn got one snapshot per + delta, i.e. no cap at all); a tool that has never been written has no window, + so its first snapshot is never delayed behind another tool's hold; and the + ordering guarantee is per domain, not globally by `web.sequence`. Message + deltas stay ordered and lossless among themselves, each tool's own frames stay + monotonic, and a boundary frame follows the frames emitted before it. Across + domains an older sequence may arrive later: another tool's newly written + snapshot can carry a lower sequence than a held one, and message@3 can precede + tool@2. That is safe because the consumer keeps separate floors; it is not a + replay or reordering defect. Where several held snapshots become releasable + together they are written in their own emission order. + The "at most once per second" holds only between consecutive + `tool_execution_update` frames of the same tool. Every other session frame — + the same or another tool's `tool_execution_start`/`end`, `btw_delta`, + `message_end`, … — is a boundary that merges every held snapshot into the + queue ahead of itself in emission order; the forced drain then writes the whole + queue regardless of backpressure, so the boundary never overtakes the output it + ends. A burst of boundary frames therefore releases snapshots at the + pre-throttle rate, bounded by how many boundary frames arrive; no snapshot is + dropped or reordered. The throttle is not an unconditional one-per-second cap. + A written snapshot is stamped with its write time, not the emit time: the + deliberate hold must not appear as network latency in Connection diagnostics. - Browser (`lib/message-update-coalescer.ts`): applies each delta on arrival and dispatches the whole message at display rate, so `useAgentSession` only ever sees whole messages. A delta with no base is held and triggers a catch-up; the diff --git a/CHANGELOG.md b/CHANGELOG.md index 548e9ad55..e476df9e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -184,6 +184,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f - **Recovered prompts and attachment-backed drafts preserve their input mode.** Prompts remain model input even when their text starts with `!` or `!!`, including after navigation, session identity moves, rejection, and page reload. Drafts keep this provenance even when memory-only attachment payloads disappear on reload. Clearing the recovered content, including removing its final image from an otherwise empty composer, starts fresh input so a new shell command works normally. Empty recovery results never change newer input. - **History prefills and unfinished uploads keep prompt intent.** History Edit, edit-and-resend Fork, and refused interrupt/reply prefills remain model input when their omitted attachments once prevented shell execution. Existing user drafts keep their own intent. Draft snapshots capture every live attachment before filtering unfinished upload payloads, so uploading or failed file chips cannot turn a prompt into a shell command after navigation or reload. - **Side questions look different before you send.** Typing `/btw` tints the composer and shows **Send**, even during a run and when the usual submit action is Queue or Steer. Side questions are sent immediately, never queued. +- **Live tool output no longer floods a slow connection.** omp sends a tool's whole accumulated output with every progress report, so a chatty command forwarded megabytes many times a second to every open tab. ompweb now holds the newest snapshot of each running tool and sends at most one per second per tool, writing the final output immediately when the tool ends. The hold lives outside the message queue, so streaming text neither waits for a held snapshot nor releases one, and a tool that has not been written yet is never delayed behind another tool's hold. Concurrent tools keep their own snapshot, so a slow one never hides another's progress. The cap applies between progress reports of one tool: any other frame — another tool's start or end, a finished message, a side-question delta — flushes held output first, so an event burst can release snapshots as often as it arrives, but never drops or reorders them. Sequence domains stay separate: message deltas remain ordered and lossless among themselves and each tool's frames stay monotonic, while an older tool snapshot may arrive after newer message text. The delay is not reported as connection latency. - **Finished background tool calls no longer show up as running.** A `bash` or `task` call that omp moved to the background kept reporting progress after it returned, and ompweb counted each report as a running tool. Opening the chat mid-run then listed those long-finished calls as empty running rows below the transcript until the next event, and an open chat could briefly show a finished call as running again. Calls that returned before an ompweb server restart can still show this once. - **Background Sync retains permanent rejection states.** A rejected held message, including one from a changed installation scope, is saved as **Not sent** rather than left as **Sending**. It is not rebound to new credentials, and a late refusal cannot recreate an entry another sender already accepted. - **Pending messages protect newer drafts and delivery intent.** A delayed storage acknowledgement does not clear newer input, even if an edit restores identical text. Same-time submissions keep durable enqueue order; duplicate browser IDs and unrelated successful HTTP responses cannot overwrite or acknowledge a held message. Delete confirmations distinguish removing tracking from cancelling work omp may already have received. diff --git a/hooks/useAgentSession-sync.test.mjs b/hooks/useAgentSession-sync.test.mjs index f967b1ca9..2ba06e6eb 100644 --- a/hooks/useAgentSession-sync.test.mjs +++ b/hooks/useAgentSession-sync.test.mjs @@ -149,6 +149,37 @@ test("a snapshot no field takes still completes deltas that arrived without thei assert.equal(pipe.shown.at(-1), "abcd"); }); +test("a tool snapshot older than a newer message delta is accepted, not stale", () => { + // Tool frames are fenced per tool and by the lifecycle/tool-snapshot floors, + // never by messageSequence: the catch-up sequence domains are separate. A + // mutation that adds messageSequence to the tool floor rejects tool@2 here. + const catchUp = createSessionCatchUp({ sessionId: () => "s1", scope: () => "run", history() {}, subscribe: () => false, live() {} }); + catchUp.observe({ type: "connected", web: { streamId: "s", sequence: 0 } }); + assert.equal( + catchUp.observe({ + type: "message_update", messageId: "m1", message: { role: "assistant" }, + assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "x" }, web: { streamId: "s", sequence: 3 }, + }), + null, + "the message delta at 3 is applied", + ); + assert.equal( + catchUp.observe({ type: "tool_execution_update", toolCallId: "t1", web: { streamId: "s", sequence: 2 } }), + null, + "tool@2 is accepted after message-delta@3: tool and message floors are separate", + ); + assert.equal( + catchUp.observe({ type: "tool_execution_update", toolCallId: "t1", web: { streamId: "s", sequence: 1 } }), + "stale", + "per-tool monotonicity still rejects an older snapshot of the same tool", + ); + assert.equal( + catchUp.observe({ type: "tool_execution_update", toolCallId: "t2", web: { streamId: "s", sequence: 1 } }), + null, + "another tool has its own floor", + ); +}); + // Base-less deltas through the coalescer into catch-up, reads failing at once, on a clock the test moves (performance.now and timers). function missingBasePipeline(t) { t.mock.timers.enable({ apis: ["setTimeout"] }); diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index b574c9f28..3609ba29f 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -865,6 +865,94 @@ test("a sink connection writes name/at/data, coalesces while backpressured and f } }); +test("a boundary frame written to a peer that pulls synchronously is not written twice", async () => { + // An SSE consumer that is ready when the frame is handed over pulls inside + // `write`, which re-enters the drain while the frame is still in flight. A + // boundary frame (`tool_execution_end`, `message_end`) must reach the peer once. + const writes = []; + let connection; + let resuming = false; + const sink = { + heartbeatMs: 60_000, + write(name, at, data) { + writes.push({ name, data: JSON.parse(data) }); + // One pull per write, like a reader that is ready for each enqueue: do not + // recurse through the writes this pull itself causes. + if (!resuming) { + resuming = true; + try { connection?.resume(); } finally { resuming = false; } + } + return true; + }, + backpressured: () => false, + heartbeat: () => true, + close() {}, + }; + const session = emitterSession(); + const release = withSession("sync-pull-sess", session); + connection = new EventStreamConnection(undefined, sink); + try { + assert.deepEqual(await connection.subscribe("s1", { kind: "session", sessionId: "sync-pull-sess" }), { ok: true }); + writes.length = 0; + session.emit({ type: "tool_execution_start", toolCallId: "t1", toolName: "bash", args: { command: "make" } }); + session.emit({ type: "tool_execution_end", toolCallId: "t1", toolName: "bash", result: { content: [] }, isError: false }); + assert.deepEqual(writes.map(({ name, data }) => [name, data.type, data.toolCallId ?? null]), [ + ["s1", "tool_execution_start", "t1"], + ["s1", "tool_execution_end", "t1"], + ]); + } finally { + connection.close(); + release(); + } +}); + +test("two held snapshots released in one drain are written once and in emit order when the peer pulls", async (t) => { + // The timer drain releases both open windows in one pass. A sink write that + // re-enters resume() drains the second one first; iterating the stale entry + // list would then write that frame again. The release loop must stop at the + // live map's current value. + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const writes = []; + let connection; + let resuming = false; + const sink = { + heartbeatMs: 60_000, + write(name, at, data) { + writes.push({ name, data: JSON.parse(data) }); + if (!resuming) { + resuming = true; + try { connection?.resume(); } finally { resuming = false; } + } + return true; + }, + backpressured: () => false, + heartbeat: () => true, + close() {}, + }; + const session = emitterSession(); + const release = withSession("sync-pull-release", session); + connection = new EventStreamConnection(undefined, sink); + try { + assert.deepEqual(await connection.subscribe("s1", { kind: "session", sessionId: "sync-pull-release" }), { ok: true }); + writes.length = 0; + // Prime both windows, then let both next snapshots wait for the same timer. + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "t1-v1" }); + session.emit({ type: "tool_execution_update", toolCallId: "t2", output: "t2-v1" }); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "t1-v2" }); + session.emit({ type: "tool_execution_update", toolCallId: "t2", output: "t2-v2" }); + assert.deepEqual(writes.map(({ data }) => data.output), ["t1-v1", "t2-v1"], "both later snapshots are held"); + t.mock.timers.tick(1000); + assert.deepEqual( + writes.map(({ data }) => data.output), + ["t1-v1", "t2-v1", "t1-v2", "t2-v2"], + "one drain releases both held snapshots exactly once, in emit order", + ); + } finally { + connection.close(); + release(); + } +}); + test("a sink that refuses a write closes the connection", async () => { let closed = 0; const sink = { heartbeatMs: 1000, write: () => false, backpressured: () => false, heartbeat: () => true, close() { closed += 1; } }; @@ -947,6 +1035,243 @@ test("while the peer is behind, a whole message replaces the queued updates of t } }); +test("tool snapshots are throttled to one per second and boundary frames flush the latest first", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const { session, writes, done } = await sinkSubscription("tool-throttle"); + try { + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "a" }); + assert.deepEqual(writes.map(({ data }) => data.output), ["a"], "the first snapshot is written at once"); + + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "ab" }); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "abc" }); + assert.equal(writes.length, 1, "snapshots inside the window are held, newest wins"); + + t.mock.timers.tick(999); + assert.equal(writes.length, 1); + t.mock.timers.tick(1); + assert.deepEqual(writes.map(({ data }) => data.output), ["a", "abc"], "the window releases only the newest snapshot"); + + // A boundary frame right after a held snapshot flushes that snapshot first. + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "abcd" }); + session.emit({ type: "tool_execution_end", toolCallId: "t1", output: "abcd" }); + assert.deepEqual( + writes.slice(2).map(({ data }) => data.type), + ["tool_execution_update", "tool_execution_end"], + "the held snapshot precedes the end frame", + ); + assert.equal(writes[2].data.output, "abcd"); + } finally { + done(); + } +}); + +test("a tool snapshot is stamped with its write time, not the time it was held", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const { session, writes, done } = await sinkSubscription("tool-stamp"); + try { + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "first" }); + assert.equal(writes[0].at, 1_000_000); + t.mock.timers.tick(400); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "held" }); + t.mock.timers.tick(600); + assert.equal(writes.length, 2, "the window released the held snapshot"); + assert.equal(writes[1].at, 1_001_000, "the stamp is the write time, so the deliberate hold is not reported as latency"); + } finally { + done(); + } +}); + +test("concurrent tools hold their newest snapshot independently and never supersede each other", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const { session, writes, done } = await sinkSubscription("tool-concurrent"); + try { + // The maintainer's probe: t1-v1, t1-v2 and t2-v1 inside one window. + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "t1-v1" }); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "t1-v2" }); + session.emit({ type: "tool_execution_update", toolCallId: "t2", output: "t2-v1" }); + assert.deepEqual( + writes.map(({ data }) => data.output), + ["t1-v1", "t2-v1"], + "t2's first snapshot is not delayed by t1's window: it has no window of its own yet", + ); + + t.mock.timers.tick(1_000); + assert.deepEqual( + writes.map(({ data }) => data.output), + ["t1-v1", "t2-v1", "t1-v2"], + "the held newest snapshot of t1 releases when its window opens", + ); + + // A later window: t1 is slow, t2 is fast. t2 must keep flowing. + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "t1-v3" }); + session.emit({ type: "tool_execution_update", toolCallId: "t2", output: "t2-v2" }); + t.mock.timers.tick(1_000); + session.emit({ type: "tool_execution_update", toolCallId: "t2", output: "t2-v3" }); + t.mock.timers.tick(1_000); + assert.deepEqual( + writes.map(({ data }) => data.output), + ["t1-v1", "t2-v1", "t1-v2", "t2-v2", "t1-v3", "t2-v3"], + "a slow tool's window never holds back another tool's snapshots", + ); + } finally { + done(); + } +}); + +/** A tool snapshot carrying the stream metadata the browser uses as a cursor. */ +const toolFrame = (toolCallId, sequence, output) => ({ + type: "tool_execution_update", toolCallId, output, web: { streamId: "s", sequence }, +}); + +test("a superseding tool snapshot is held outside the message queue, so the cursor never goes backwards", async () => { + const { sink, session, connection, writes, done } = await sinkSubscription("tool-supersede-cross"); + try { + // The maintainer's probe: t1@1, t2@2, newer t1@3, all while the peer is behind. + sink.behind = true; + session.emit(toolFrame("t1", 1, "t1-v1")); + session.emit(toolFrame("t2", 2, "t2-v1")); + session.emit(toolFrame("t1", 3, "t1-v3")); + assert.deepEqual(writes, [], "nothing is written while the peer is behind"); + sink.behind = false; + connection.resume(); + assert.deepEqual( + writes.map(({ data }) => data.web.sequence), + [2, 3], + "t2's first snapshot and t1's newest are written in sequence order", + ); + assert.deepEqual(writes.map(({ data }) => data.output), ["t2-v1", "t1-v3"]); + } finally { + done(); + } +}); + +test("a superseding tool snapshot never overtakes a message delta emitted before it", async () => { + const { sink, session, connection, writes, done } = await sinkSubscription("tool-supersede-delta"); + try { + sink.behind = true; + session.emit(toolFrame("t1", 1, "t1-v1")); + session.emit(deltaFrame(2, "text_delta", 0, { delta: "D2" })); + session.emit(toolFrame("t1", 3, "t1-v3")); + assert.deepEqual(writes, []); + sink.behind = false; + connection.resume(); + assert.deepEqual( + writes.map(({ data }) => data.web.sequence), + [2, 3], + "the delta emitted before the replacement keeps its place ahead of it", + ); + assert.deepEqual( + writes.map(({ data }) => [data.type, data.assistantMessageEvent?.delta ?? data.output]), + [["message_update", "D2"], ["tool_execution_update", "t1-v3"]], + ); + } finally { + done(); + } +}); + +test("a held tool snapshot is not lost when a boundary frame ends its tool", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const { session, writes, done } = await sinkSubscription("tool-end-order"); + try { + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "a" }); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "ab" }); + session.emit({ type: "tool_execution_update", toolCallId: "t2", output: "b" }); + session.emit({ type: "tool_execution_end", toolCallId: "t1", output: "ab" }); + assert.deepEqual( + writes.map(({ data }) => [data.type, data.output]), + [["tool_execution_update", "a"], ["tool_execution_update", "b"], ["tool_execution_update", "ab"], ["tool_execution_end", "ab"]], + "the held snapshot of t1 precedes the end frame that ends it", + ); + } finally { + done(); + } +}); + +test("message deltas are never throttled while a tool snapshot is held", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const { session, writes, done } = await sinkSubscription("tool-delta-order"); + try { + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "first" }); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "held" }); + assert.equal(writes.length, 1); + + session.emit(deltaFrame(1, "text_delta", 0, { delta: "hi" })); + assert.deepEqual( + writes.slice(1).map(({ data }) => data.type), + ["message_update"], + "a delta is written at once and never releases the held snapshot", + ); + assert.equal(writes[1].data.assistantMessageEvent.delta, "hi"); + assert.equal(writes.length, 2, "the held snapshot is still waiting for its window"); + } finally { + done(); + } +}); + +test("a queued message delta is written before a held tool snapshot (emission order)", { timeout: 5000 }, async () => { + const { sink, session, connection, writes, done } = await sinkSubscription("tool-delta-behind"); + try { + sink.behind = true; + session.emit(deltaFrame(1, "text_delta", 0, { delta: "first" })); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "second" }); + assert.deepEqual(writes, []); + sink.behind = false; + connection.resume(); + assert.deepEqual( + writes.map(({ data }) => [data.type, data.assistantMessageEvent?.delta ?? data.output]), + [["message_update", "first"], ["tool_execution_update", "second"]], + "the older queued delta must precede the held tool snapshot", + ); + } finally { + done(); + } +}); + +test("a backpressured delta, tool snapshot and end frame reach the wire in emission order", { timeout: 5000 }, async () => { + const { sink, session, connection, writes, done } = await sinkSubscription("tool-delta-backpressure"); + try { + // The maintainer's probe: D1, T, END emitted while the sink is behind. + sink.behind = true; + session.emit(deltaFrame(1, "text_delta", 0, { delta: "D1" })); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "T" }); + session.emit({ type: "tool_execution_end", toolCallId: "t1", output: "T" }); + assert.deepEqual( + writes.map(({ data }) => [data.type, data.assistantMessageEvent?.delta ?? data.output]), + [["message_update", "D1"], ["tool_execution_update", "T"], ["tool_execution_end", "T"]], + "the drain preserves emission order; the tool update never jumps ahead of the older delta", + ); + sink.behind = false; + connection.resume(); + assert.equal(writes.length, 3, "nothing is written twice"); + } finally { + done(); + } +}); + +test("a heartbeat never writes a held tool snapshot around queued message deltas", { timeout: 5000 }, async (t) => { + t.mock.timers.enable({ apis: ["setInterval", "Date"], now: 1_000_000 }); + const { sink, session, connection, writes, done } = await sinkSubscription("tool-heartbeat-order"); + try { + sink.behind = true; + session.emit(deltaFrame(1, "text_delta", 0, { delta: "D1" })); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "T" }); + assert.deepEqual(writes, [], "both wait while the peer is behind"); + // The heartbeat force-flushes; it must not write the held snapshot ahead of + // the older delta that the sink cannot take yet. + t.mock.timers.tick(60_000); + assert.deepEqual(writes, [], "the heartbeat writes nothing while the peer is behind"); + sink.behind = false; + connection.resume(); + assert.deepEqual( + writes.map(({ data }) => [data.type, data.assistantMessageEvent?.delta ?? data.output]), + [["message_update", "D1"], ["tool_execution_update", "T"]], + "the delta precedes the tool snapshot emitted after it", + ); + } finally { + done(); + } +}); + test("outbox snapshots wait through backpressured heartbeats and resumes, keeping the latest settled ids", async (t) => { t.mock.timers.enable({ apis: ["setInterval", "Date"], now: 1_000_000 }); const { sink, session, connection, writes, done } = await sinkSubscription("outbox-heartbeat"); @@ -1110,3 +1435,52 @@ test("the connection's keep-alive timer fires at the requested interval, never e await reader.cancel(); } }); + +test("the per-tool cap holds while message deltas stream: a delta neither waits for nor releases a held snapshot", { timeout: 5000 }, async (t) => { + // The regression the earlier design could not see: `release` mode ignored the + // throttle window, so every delta flushed the held snapshot. A bash tool that + // prints while the model streams text (the normal case) got one snapshot per + // delta, i.e. no cap at all. + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const { session, writes, done } = await sinkSubscription("tool-cap-under-deltas"); + try { + for (let i = 0; i < 10; i += 1) { + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: `v${i}` }); + session.emit(deltaFrame(i + 1, "text_delta", 0, { delta: `d${i}` })); + t.mock.timers.tick(100); + } + const snapshots = writes.filter(({ data }) => data.type === "tool_execution_update"); + const deltas = writes.filter(({ data }) => data.type === "message_update"); + assert.equal(deltas.length, 10, "every delta is written at once: they are not throttled"); + assert.ok( + snapshots.length <= 2, + `at most one snapshot per second despite 10 deltas (got ${snapshots.length})`, + ); + assert.deepEqual(snapshots.map(({ data }) => data.output), ["v0", "v9"], "the newest snapshot is the one that survives"); + } finally { + done(); + } +}); + +test("one tool's closed window never delays another tool's first snapshot", { timeout: 5000 }, async (t) => { + // The other half of the same contract: the hold lives outside the ordered + // message queue, so a tool that has never been written has no window to wait + // for and must not sit behind an older tool's held snapshot. + t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 1_000_000 }); + const { session, writes, done } = await sinkSubscription("tool-no-cross-delay"); + try { + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "t1-v1" }); + session.emit({ type: "tool_execution_update", toolCallId: "t1", output: "t1-v2" }); + t.mock.timers.tick(400); + session.emit({ type: "tool_execution_update", toolCallId: "t2", output: "t2-v1" }); + assert.deepEqual( + writes.map(({ data }) => data.output), + ["t1-v1", "t2-v1"], + "t2's first snapshot is written at once, 400 ms after t1's held one", + ); + t.mock.timers.tick(600); + assert.deepEqual(writes.map(({ data }) => data.output), ["t1-v1", "t2-v1", "t1-v2"]); + } finally { + done(); + } +}); diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index 0d02ece8f..f15091391 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -47,14 +47,57 @@ export type SubscribeResult = const SUBSCRIBED: SubscribeResult = { ok: true }; +/** + * The floor between two `tool_execution_update` snapshots of one tool in one + * session subscription. omp sends the accumulated tool output on every update, + * so a bash run printing megabytes would otherwise forward the whole buffer + * many times per second. Each frame is a self-contained snapshot of one + * `toolCallId`, so holding the newest one per tool is lossless and concurrent + * tools never supersede each other; a boundary frame (`tool_execution_end`, + * `message_end`, …) always flushes them first, in emission order, so the final + * output is never delayed. Message deltas are not throttled: they are + * incremental since the delta protocol, and — because a held snapshot is not in + * the message queue — they neither wait for one nor release one. + */ +export const TOOL_UPDATE_FRAME_MIN_INTERVAL_MS = 1_000; + class Subscription { active = true; detach: (() => void) | null = null; - // Session backpressure queue: message updates merge and consecutive outbox - // snapshots replace each other. Other frames flush it first to preserve order. - pendingUpdates: QueuedUpdate[] = []; - - constructor(readonly id: string, readonly coalescesMessageUpdates: boolean) {} + // Message and outbox updates plus boundary frames, in emission order: message + // updates merge and consecutive outbox snapshots replace each other. Tool + // snapshots are held OUTSIDE this queue (see `heldToolUpdates`), so a held + // snapshot can neither delay a queued frame nor be released by one. + pendingUpdates: QueuedFrame[] = []; + /** + * The newest snapshot of each tool, keyed by `toolCallId`, held until its + * window opens. It needs no position among the message frames: the browser + * fences a tool frame by the tool and lifecycle sequences, never by the + * message sequence (`hooks/useAgentSession-sync.ts`). `seq` is the emission + * counter of the frame it holds, so a boundary flush can merge it back into + * the queue in the order it was emitted. + */ + heldToolUpdates = new Map(); + /** When the last snapshot of each tool was written (absent = never written). */ + lastToolUpdateAt = new Map(); + /** Monotonic emission counter: orders held snapshots against queued frames. */ + emitCount = 0; + /** The one timer that releases held frames once their window elapsed. */ + drainTimer: NodeJS.Timeout | undefined = undefined; + /** Deadline of `drainTimer`; a newer frame may pull it forward. */ + drainAt = 0; + + constructor(readonly id: string, readonly throttlesAgentUpdates: boolean) {} + + /** Drop held frames and their timer (unsubscribe, end, close). */ + clearUpdates(): void { + this.pendingUpdates = []; + this.heldToolUpdates.clear(); + this.lastToolUpdateAt.clear(); + clearTimeout(this.drainTimer); + this.drainTimer = undefined; + this.drainAt = 0; + } } /** What a channel opener may do with its subscription. */ @@ -241,7 +284,7 @@ export class EventStreamConnection { private release(subscription: Subscription): void { subscription.active = false; - subscription.pendingUpdates = []; + subscription.clearUpdates(); const detach = subscription.detach; subscription.detach = null; runDetach(detach); @@ -278,47 +321,190 @@ export class EventStreamConnection { return this.write(subscription.id, text, at); } - private flush(subscription: Subscription, force = false): boolean { - if (!force && this.sink.backpressured()) return true; - const queued = subscription.pendingUpdates; + /** The peer drained: deliver queued frames now rather than waiting for the next event or heartbeat. */ + resume(): void { + this.flushAll(); + } + + private flushAll(): boolean { + for (const subscription of this.subscriptions.values()) { + if (!this.drainAndReschedule(subscription)) return false; + } + return !this.closed; + } + + /** + * Write the message/outbox queue in emission order, then release every held + * tool snapshot whose window has opened. A held snapshot never blocks a + * queued frame and a queued frame never releases a held snapshot: the two are + * independent, which is what makes the throttle hold under a streaming turn + * (deltas arrive constantly) and keeps one tool's window from delaying + * another tool's snapshot. + * + * `force` (a boundary frame is waiting) writes the queued frames without + * regard to backpressure, because the frame that follows must not be delayed; + * a boundary flush merges the held snapshots into the queue first, in + * emission order, so the end frame never overtakes the output it ends. The + * heartbeat retries through the non-force path, so it never overrides + * backpressure; a snapshot released by its own window is written only while + * the sink has capacity. + * + * A tool snapshot is stamped with the time it is actually written, not the + * time it was emitted: the deliberate hold must not read as network latency. + */ + private drain(subscription: Subscription, force = false): boolean { + // A stamp whose window elapsed is useless: a later snapshot is writable at once. + for (const [toolCallId, at] of subscription.lastToolUpdateAt) { + if (Date.now() - at >= TOOL_UPDATE_FRAME_MIN_INTERVAL_MS) subscription.lastToolUpdateAt.delete(toolCallId); + } + // Detach the queue before writing: `writeFrame` can release the peer + // synchronously (a stream pull calls `resume()`, which drains every + // subscription), and that re-entrant drain must see an empty queue rather + // than write the frames this loop still holds a second time. + const queue = subscription.pendingUpdates; subscription.pendingUpdates = []; - for (let i = 0; i < queued.length; i++) { - if (!force && this.sink.backpressured()) { - subscription.pendingUpdates = queued.slice(i); - return true; - } - const { data, at } = queued[i]; - if (!this.writeFrame(subscription, data, at)) return false; + let written = 0; + while (written < queue.length) { + if (!force && this.sink.backpressured()) break; + const frame = queue[written]; + written += 1; + if (!this.writeFrame(subscription, frame.data, frame.tool ? Date.now() : frame.at)) return !this.closed; + } + // Frames appended while writing stay behind the ones still to write. + if (written < queue.length) subscription.pendingUpdates = queue.slice(written).concat(subscription.pendingUpdates); + if (this.sink.backpressured()) return !this.closed; + // Release what the windows allow. Ordering is required per tool, not across + // tools: two independent tools may be written in either order, so the emit + // order here is deterministic, not a consumer dependency. + const releasable = [...subscription.heldToolUpdates.entries()] + .filter(([toolCallId]) => Date.now() >= (subscription.lastToolUpdateAt.get(toolCallId) ?? 0) + TOOL_UPDATE_FRAME_MIN_INTERVAL_MS) + .sort(([, a], [, b]) => a.seq - b.seq); + for (const [toolCallId, held] of releasable) { + // A sink whose write re-enters `drain()` may already have released and + // written this entry from the live map: stop at the current value, never + // write a stale iteration snapshot a second time. + if (subscription.heldToolUpdates.get(toolCallId) !== held) continue; + subscription.heldToolUpdates.delete(toolCallId); + const stamp = Date.now(); + subscription.lastToolUpdateAt.set(toolCallId, stamp); + if (!this.writeFrame(subscription, held.data, stamp)) return !this.closed; + } + return !this.closed; + } + + /** Drain what is ready, then arm the one timer for the next held snapshot. */ + private drainAndReschedule(subscription: Subscription, force = false): boolean { + if (!this.drain(subscription, force)) return false; + if (!subscription.active || this.closed) return !this.closed; + if (subscription.heldToolUpdates.size === 0) { + clearTimeout(subscription.drainTimer); + subscription.drainTimer = undefined; + subscription.drainAt = 0; + return true; } + // The sink's owner calls `resume()` once it has capacity again, and the + // heartbeat retries: a timer here would only spin while the peer is behind. + if (this.sink.backpressured()) return true; + let earliest = Infinity; + for (const toolCallId of subscription.heldToolUpdates.keys()) { + const at = subscription.lastToolUpdateAt.get(toolCallId) ?? 0; + earliest = Math.min(earliest, at + TOOL_UPDATE_FRAME_MIN_INTERVAL_MS); + } + this.scheduleDrain(subscription, Math.max(earliest - Date.now(), 1)); return true; } - /** The peer drained: deliver coalesced updates now rather than waiting for the next event or heartbeat. */ - resume(): void { - this.flushAll(); + /** + * Arm the timer that releases held frames. A newer frame only pulls the + * deadline forward, never pushes it back. + */ + private scheduleDrain(subscription: Subscription, delayMs: number): void { + if (!subscription.active || this.closed) return; + const deadline = Date.now() + delayMs; + if (subscription.drainTimer !== undefined && subscription.drainAt <= deadline) return; + clearTimeout(subscription.drainTimer); + subscription.drainAt = deadline; + subscription.drainTimer = setTimeout(() => { + subscription.drainTimer = undefined; + subscription.drainAt = 0; + if (!subscription.active || this.closed) return; + this.drainAndReschedule(subscription); + }, delayMs); + // A throttle window must not keep the process alive. + subscription.drainTimer.unref?.(); } - private flushAll(): boolean { - for (const subscription of this.subscriptions.values()) this.flush(subscription); - return !this.closed; + /** + * Move every held snapshot into the message queue, in the order it was + * emitted. Used when a boundary frame arrives: it must not overtake output + * that was emitted before it, and the queue is the one place a drain writes + * in order. + */ + private releaseHeldToolUpdates(subscription: Subscription): void { + if (subscription.heldToolUpdates.size === 0) return; + const held = [...subscription.heldToolUpdates.entries()].sort(([, a], [, b]) => a.seq - b.seq); + subscription.heldToolUpdates.clear(); + for (const [toolCallId, update] of held) { + // `tool: true` makes the drain stamp the write time, not this release time. + subscription.pendingUpdates.push({ data: update.data, at: Date.now(), tool: true }); + subscription.lastToolUpdateAt.set(toolCallId, Date.now()); + } } private deliver(subscription: Subscription, data: unknown): void { if (!subscription.active || this.closed) return; - if ( - subscription.coalescesMessageUpdates - && isRecord(data) - && (data.type === "outbox_update" || (data.type === "message_update" && this.sink.backpressured())) - ) { - queueUpdate(subscription.pendingUpdates, data, Date.now()); - if (data.type === "outbox_update") this.flush(subscription); + // Other channels never queue: their frames are neither throttled nor merged. + if (!subscription.throttlesAgentUpdates) { + this.writeFrame(subscription, data); return; } - if (this.flush(subscription, true)) this.writeFrame(subscription, data); + if (isRecord(data)) { + if (data.type === "tool_execution_update" && typeof data.toolCallId === "string" && data.toolCallId) { + // Held outside the message queue: the browser fences a tool frame by + // its tool/lifecycle sequences, never by `messageSequence`, so it needs + // no position among the deltas. The newest snapshot per tool wins. + subscription.heldToolUpdates.set(data.toolCallId, { data, seq: ++subscription.emitCount }); + this.drainAndReschedule(subscription); + return; + } + if (data.type === "outbox_update" || data.type === "message_update") { + // Nothing waits: the frame goes out at once, and it never releases a + // held tool snapshot (that would defeat the throttle). + if (subscription.pendingUpdates.length === 0 && subscription.heldToolUpdates.size === 0 && !this.sink.backpressured()) { + this.writeFrame(subscription, data); + return; + } + queueUpdate(subscription.pendingUpdates, data, Date.now()); + this.drainAndReschedule(subscription); + return; + } + } + // Every other frame is a boundary (`tool_execution_end`, `message_end`, …): + // everything emitted before it must reach the client first, in order. The + // held snapshots were emitted before it too, so they join the queue ahead + // of it — in their own emission order — and the forced drain writes all of + // it without regard to backpressure. + this.releaseHeldToolUpdates(subscription); + subscription.pendingUpdates.push({ data, at: Date.now() }); + this.drainAndReschedule(subscription, true); } } -type QueuedUpdate = { data: Record; at: number }; +/** + * One queued frame. `at` is the emit time, so the stamp keeps measuring + * server-to-peer delay — except for a tool snapshot released by a boundary + * frame, which is stamped when it is written (`tool`): the deliberate hold must + * not read as network latency in Connection diagnostics. + */ +type QueuedFrame = { data: unknown; at: number; tool?: boolean }; + +/** + * The newest snapshot of one tool, held until its window opens. Each frame + * carries the tool's whole accumulated output, so a newer snapshot supersedes + * the held one losslessly. `seq` orders it against the other held snapshots + * when a boundary frame flushes them all. + */ +type HeldToolUpdate = { data: Record; seq: number }; /** * Merge a `message_update` into a backpressure queue without losing anything: @@ -330,10 +516,11 @@ type QueuedUpdate = { data: Record; at: number }; * joining a delta to an earlier entry would put it before frames it follows * and break the sequence fence the browser relies on. */ -function queueUpdate(queue: QueuedUpdate[], data: Record, at: number): void { +function queueUpdate(queue: QueuedFrame[], data: Record, at: number): void { + const last = queue.at(-1); + const lastData = last && isRecord(last.data) ? last.data : null; if (data.type === "outbox_update") { - const last = queue.at(-1); - if (last?.data.type === "outbox_update") { + if (last && lastData?.type === "outbox_update") { last.data = data; last.at = at; } else { @@ -343,14 +530,15 @@ function queueUpdate(queue: QueuedUpdate[], data: Record, at: n } if (!isDeltaUpdate(data)) { for (let i = queue.length - 1; i >= 0; i--) { - if (queue[i].data.type === "outbox_update") break; - if (queue[i].data.messageId === data.messageId) queue.splice(i, 1); + const frame = queue[i]; + if (!isRecord(frame.data)) continue; + if (frame.data.type === "outbox_update") break; + if (frame.data.messageId === data.messageId) queue.splice(i, 1); } queue.push({ data, at }); return; } - const last = queue.at(-1); - const merged = last && isDeltaUpdate(last.data) ? mergeDeltaUpdates(last.data, data) : null; + const merged = lastData && isDeltaUpdate(lastData) ? mergeDeltaUpdates(lastData, data) : null; if (last && merged) { last.data = merged; last.at = at;