From ebfe3310ca1d27a26879741c2aee53953b2b5be2 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Fri, 6 Nov 2026 06:26:23 +0100 Subject: [PATCH 01/10] perf(events): hold tool snapshots to one frame per second MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit omp sends the accumulated tool output on every `tool_execution_update`, so a bash run printing megabytes forwarded the whole buffer many times per second to every attached tab. Each frame is a self-contained snapshot, so holding the newest one is lossless: at most one is written per subscription per second, and any other frame (`tool_execution_end`, `message_end`, …) flushes it first so the final output is never delayed. Message deltas are deliberately not throttled: they are incremental since the delta protocol, and holding them would lose text. --- lib/event-stream-hub.test.mjs | 74 +++++++++++++++++++++ lib/event-stream-hub.ts | 119 ++++++++++++++++++++++++++++++++-- 2 files changed, 187 insertions(+), 6 deletions(-) diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index b574c9f28..33ae3146d 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -947,6 +947,80 @@ 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("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), + ["tool_execution_update", "message_update"], + "the held tool snapshot flushes before the delta, so per-subscription order holds", + ); + assert.equal(writes[1].data.output, "held"); + assert.equal(writes[2].data.assistantMessageEvent.delta, "hi"); + } 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("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"); diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index 0d02ece8f..f432631e2 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -39,6 +39,18 @@ export function parseHeartbeatSeconds(value: string | null | undefined): number return seconds; } +/** + * The floor between two `tool_execution_update` snapshots of 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. The frame is a self-contained snapshot: holding the newest + * one is lossless, and a boundary frame (`tool_execution_end`, `message_end`, + * …) always flushes it first, so the final output is never delayed. Message + * deltas are not throttled: they are incremental since the delta protocol. + */ +export const TOOL_UPDATE_FRAME_MIN_INTERVAL_MS = 1_000; +/** Retry step while the socket is backpressured: keep the latest snapshot, never buffer. */ +const TOOL_UPDATE_RETRY_MS = 50; const encoder = new TextEncoder(); export type SubscribeResult = @@ -53,8 +65,27 @@ class Subscription { // 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) {} + // At most one `tool_execution_update` snapshot is held between writes: the + // newest snapshot supersedes every older one (each frame carries the whole + // accumulated output), and any other frame flushes it first. + heldToolUpdate: { data: Record; at: number } | null = null; + /** When the last tool snapshot was written (0 = never). */ + lastToolUpdateAt = 0; + /** The one timer that releases a held tool snapshot once its window elapsed. */ + toolFlushTimer: NodeJS.Timeout | undefined = undefined; + /** Deadline of `toolFlushTimer`; a newer frame may pull it forward. */ + toolFlushAt = 0; + + constructor(readonly id: string, readonly throttlesAgentUpdates: boolean) {} + + /** Drop held frames and their timer (unsubscribe, end, close). */ + clearUpdates(): void { + this.pendingUpdates = []; + this.heldToolUpdate = null; + clearTimeout(this.toolFlushTimer); + this.toolFlushTimer = undefined; + this.toolFlushAt = 0; + } } /** What a channel opener may do with its subscription. */ @@ -200,6 +231,10 @@ export class EventStreamConnection { return this.closed; } + get heartbeatMs(): number { + return this.sink.heartbeatMs; + } + get subscriptionCount(): number { return this.subscriptions.size; } @@ -241,7 +276,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); @@ -299,14 +334,84 @@ export class EventStreamConnection { } private flushAll(): boolean { - for (const subscription of this.subscriptions.values()) this.flush(subscription); + for (const subscription of this.subscriptions.values()) { + if (!this.flushToolUpdate(subscription, true)) return false; + this.flush(subscription); + } return !this.closed; } + /** Write the held tool snapshot when its window elapsed (or `force`), false means the stream is gone. */ + private flushToolUpdate(subscription: Subscription, force = false): boolean { + const held = subscription.heldToolUpdate; + if (!held) return !this.closed; + const now = Date.now(); + if (!force && now < subscription.lastToolUpdateAt + TOOL_UPDATE_FRAME_MIN_INTERVAL_MS) return !this.closed; + // Queued message deltas were emitted before the held snapshot (a tool + // update never queues behind them), so they must go out first. + if (!this.flush(subscription)) return false; + subscription.heldToolUpdate = null; + if (subscription.toolFlushTimer !== undefined) { + clearTimeout(subscription.toolFlushTimer); + subscription.toolFlushTimer = undefined; + subscription.toolFlushAt = 0; + } + subscription.lastToolUpdateAt = now; + return this.writeFrame(subscription, held.data, held.at); + } + + /** + * Arm the timer that releases a held tool snapshot. A newer frame only pulls + * the deadline forward, never pushes it back; while the socket is behind it + * retries shortly and keeps the latest snapshot instead of buffering frames. + */ + private scheduleToolFlush(subscription: Subscription, delayMs: number): void { + if (!subscription.active || this.closed) return; + const deadline = Date.now() + Math.max(0, delayMs); + if (subscription.toolFlushTimer !== undefined && subscription.toolFlushAt <= deadline) return; + clearTimeout(subscription.toolFlushTimer); + subscription.toolFlushAt = deadline; + subscription.toolFlushTimer = setTimeout(() => { + subscription.toolFlushTimer = undefined; + subscription.toolFlushAt = 0; + if (!subscription.active || this.closed) return; + if (this.sink.backpressured()) { + this.scheduleToolFlush(subscription, TOOL_UPDATE_RETRY_MS); + return; + } + if (!this.flushToolUpdate(subscription)) return; + if (subscription.heldToolUpdate) { + const remaining = subscription.lastToolUpdateAt + TOOL_UPDATE_FRAME_MIN_INTERVAL_MS - Date.now(); + this.scheduleToolFlush(subscription, Math.max(remaining, TOOL_UPDATE_RETRY_MS)); + } + }, Math.max(0, delayMs)); + // A throttle window must not keep the process alive. + subscription.toolFlushTimer.unref?.(); + } + + /** Hold the newest tool snapshot, writing it at once when its window is open. */ + private deliverToolUpdate(subscription: Subscription, data: Record): void { + const now = Date.now(); + subscription.heldToolUpdate = { data, at: now }; + const delay = subscription.lastToolUpdateAt + TOOL_UPDATE_FRAME_MIN_INTERVAL_MS - now; + if (delay <= 0 && !this.sink.backpressured()) { + this.flushToolUpdate(subscription, true); + return; + } + this.scheduleToolFlush(subscription, Math.max(delay, TOOL_UPDATE_RETRY_MS)); + } + private deliver(subscription: Subscription, data: unknown): void { if (!subscription.active || this.closed) return; + if (subscription.throttlesAgentUpdates && isRecord(data) && data.type === "tool_execution_update") { + this.deliverToolUpdate(subscription, data); + return; + } + // Every other frame is a boundary (`message_end`, `tool_execution_end`, …): + // the held tool snapshot must reach the client before it, never after. + if (!this.flushToolUpdate(subscription, true)) return; if ( - subscription.coalescesMessageUpdates + subscription.throttlesAgentUpdates && isRecord(data) && (data.type === "outbox_update" || (data.type === "message_update" && this.sink.backpressured())) ) { @@ -411,7 +516,9 @@ function openRunningChannel(handle: SubscriptionHandle): SubscribeResult { // as reachable for toasts and in-page system notifications while this is open. function openNotificationsChannel(clientId: string, handle: SubscriptionHandle): SubscribeResult { handle.open(); - handle.setDetach(attachNotificationClient(clientId, (message) => handle.send({ type: "notification", ...message }))); + handle.setDetach(attachNotificationClient(clientId, (message) => { + handle.send({ type: "notification", kind: message.kind, event: message.event }); + })); return SUBSCRIBED; } From 9ccf5ceab7c45eaadd9b501bb013ab0a17a67908 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 12:27:30 +0100 Subject: [PATCH 02/10] fix(events): hold tool snapshots per tool call and keep one ordered drain The single held slot let one tool's snapshot supersede another's, and flushToolUpdate wrote around the backpressure queue: a boundary frame or a heartbeat could put a held tool update ahead of message deltas emitted before it, and a held snapshot was stamped with its emit time. Each subscription now queues frames in emission order and holds at most one snapshot per toolCallId in place. One drain writes that queue for every path (tool update, delta, outbox snapshot, boundary frame, resume, heartbeat), so nothing overtakes an older frame; a boundary frame and the heartbeat may ignore the throttle window and backpressure, a delta only the window. A written snapshot is stamped with its write time, so the deliberate hold does not read as network latency in Connection diagnostics. Drop the unconsumed heartbeat-option plumbing (parseHeartbeatSeconds, EventStreamConnectionOptions, the SseSink interval parameter and the heartbeatMs getter); nothing called it, and #407 owns that setting. --- AGENTS.md | 12 ++ CHANGELOG.md | 1 + lib/event-stream-hub.test.mjs | 112 ++++++++++++ lib/event-stream-hub.ts | 311 +++++++++++++++++++--------------- 4 files changed, 295 insertions(+), 141 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index dfc78bbcb..1b1affa6b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1141,6 +1141,18 @@ 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 one snapshot per tool + call is held per subscription and written at most once per + `TOOL_UPDATE_FRAME_MIN_INTERVAL_MS`. The hold is per `toolCallId`: concurrent + tools never supersede each other, and one tool's window never delays another + tool's snapshot. The held snapshot keeps its place in the same ordered queue + as the message deltas and outbox snapshots, so a boundary frame + (`tool_execution_end`, `message_end`, …) or a delta emitted after it can never + overtake it, and the heartbeat force-flush drains that one queue rather than + writing around it. 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..183a54b53 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, writing the final output immediately when the tool ends. Concurrent tools keep their own snapshot, so a slow one never hides another's progress, and held output never overtakes the message text around it. 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/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index 33ae3146d..5644455c8 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -980,6 +980,73 @@ test("tool snapshots are throttled to one per second and boundary frames flush t } }); +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 is held, not dropped by t1's window"); + + t.mock.timers.tick(1_000); + assert.deepEqual( + writes.map(({ data }) => data.output), + ["t1-v1", "t1-v2", "t2-v1"], + "each tool releases its own newest snapshot, in emission order", + ); + + // 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", "t1-v2", "t2-v1", "t1-v3", "t2-v2", "t2-v3"], + "a slow tool's window never holds back another tool's snapshots", + ); + } 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", "ab"], ["tool_execution_update", "b"], ["tool_execution_end", "ab"]], + "both held snapshots flush in emission order before the end frame", + ); + } 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"); @@ -1020,6 +1087,51 @@ test("a queued message delta is written before a held tool snapshot (emission or } }); +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 }); diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index f432631e2..110c2eab9 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -26,31 +26,20 @@ import { isRecord } from "./type-guards"; // the browser's shared worker. // Heartbeat keeps the socket alive through reverse proxies that drop silent connections. -// A native client may ask for a longer one per connection (`/api/events?heartbeat=`). const HEARTBEAT_MS = 30_000; -export const MIN_HEARTBEAT_SECONDS = 15; -export const MAX_HEARTBEAT_SECONDS = 110; - -/** `?heartbeat=` in [15, 110]; anything else keeps the 30 s default. */ -export function parseHeartbeatSeconds(value: string | null | undefined): number { - if (typeof value !== "string" || !/^\d{1,4}$/.test(value.trim())) return HEARTBEAT_MS / 1000; - const seconds = Number(value.trim()); - if (seconds < MIN_HEARTBEAT_SECONDS || seconds > MAX_HEARTBEAT_SECONDS) return HEARTBEAT_MS / 1000; - return seconds; -} /** - * The floor between two `tool_execution_update` snapshots of 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. The frame is a self-contained snapshot: holding the newest - * one is lossless, and a boundary frame (`tool_execution_end`, `message_end`, - * …) always flushes it first, so the final output is never delayed. Message - * deltas are not throttled: they are incremental since the delta protocol. + * 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. */ export const TOOL_UPDATE_FRAME_MIN_INTERVAL_MS = 1_000; -/** Retry step while the socket is backpressured: keep the latest snapshot, never buffer. */ -const TOOL_UPDATE_RETRY_MS = 50; const encoder = new TextEncoder(); export type SubscribeResult = @@ -62,29 +51,27 @@ const SUBSCRIBED: SubscribeResult = { ok: true }; 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[] = []; - // At most one `tool_execution_update` snapshot is held between writes: the - // newest snapshot supersedes every older one (each frame carries the whole - // accumulated output), and any other frame flushes it first. - heldToolUpdate: { data: Record; at: number } | null = null; - /** When the last tool snapshot was written (0 = never). */ - lastToolUpdateAt = 0; - /** The one timer that releases a held tool snapshot once its window elapsed. */ - toolFlushTimer: NodeJS.Timeout | undefined = undefined; - /** Deadline of `toolFlushTimer`; a newer frame may pull it forward. */ - toolFlushAt = 0; + // Session backpressure queue, in emission order: message updates merge and + // consecutive outbox snapshots replace each other, a tool snapshot is held + // in place until its own window opens. One writer drains the whole queue, so + // no frame ever overtakes an older one. + pendingUpdates: QueuedFrame[] = []; + /** When the last snapshot of each tool was written (absent = never written). */ + lastToolUpdateAt = new Map(); + /** 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.heldToolUpdate = null; - clearTimeout(this.toolFlushTimer); - this.toolFlushTimer = undefined; - this.toolFlushAt = 0; + this.lastToolUpdateAt.clear(); + clearTimeout(this.drainTimer); + this.drainTimer = undefined; + this.drainAt = 0; } } @@ -128,12 +115,11 @@ export interface FrameSink { } class SseSink implements FrameSink { - readonly heartbeatMs: number; + readonly heartbeatMs = HEARTBEAT_MS; readonly stream: ReadableStream; private controller!: ReadableStreamDefaultController; - constructor(onPull: () => void, onCancel: () => void, heartbeatMs = HEARTBEAT_MS) { - this.heartbeatMs = heartbeatMs; + constructor(onPull: () => void, onCancel: () => void) { this.stream = new ReadableStream({ start: (controller) => { this.controller = controller; }, // A slow consumer resumed reading: deliver coalesced updates now rather @@ -231,10 +217,6 @@ export class EventStreamConnection { return this.closed; } - get heartbeatMs(): number { - return this.sink.heartbeatMs; - } - get subscriptionCount(): number { return this.subscriptions.size; } @@ -313,117 +295,163 @@ 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; - 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; - } - return true; - } - - /** The peer drained: deliver coalesced updates now rather than waiting for the next event or heartbeat. */ + /** 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.flushToolUpdate(subscription, true)) return false; - this.flush(subscription); + if (!this.drainAndReschedule(subscription, "ready")) return false; + } + return !this.closed; + } + + /** + * Write queued frames in emission order, never overtaking one emitted before. + * `ready` stops at the first frame whose throttle window is closed and while + * the peer is behind, leaving the rest queued; `release` ignores the window + * (a delta must not wait for a held snapshot ahead of it) but not + * backpressure; `force` ignores both, because the boundary frame that follows + * must not be delayed. 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, mode: DrainMode): 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); } + const queue = subscription.pendingUpdates; + let written = 0; + while (written < queue.length) { + if (mode !== "force" && this.sink.backpressured()) break; + const frame = queue[written]; + let at: number; + if (frame.kind === "tool") { + if (mode === "ready" && Date.now() < (subscription.lastToolUpdateAt.get(frame.toolCallId) ?? 0) + TOOL_UPDATE_FRAME_MIN_INTERVAL_MS) break; + at = Date.now(); + subscription.lastToolUpdateAt.set(frame.toolCallId, at); + } else { + at = frame.at; + } + written += 1; + if (!this.writeFrame(subscription, frame.data, at)) { + queue.splice(0, written); + return !this.closed; + } + } + queue.splice(0, written); return !this.closed; } - /** Write the held tool snapshot when its window elapsed (or `force`), false means the stream is gone. */ - private flushToolUpdate(subscription: Subscription, force = false): boolean { - const held = subscription.heldToolUpdate; - if (!held) return !this.closed; - const now = Date.now(); - if (!force && now < subscription.lastToolUpdateAt + TOOL_UPDATE_FRAME_MIN_INTERVAL_MS) return !this.closed; - // Queued message deltas were emitted before the held snapshot (a tool - // update never queues behind them), so they must go out first. - if (!this.flush(subscription)) return false; - subscription.heldToolUpdate = null; - if (subscription.toolFlushTimer !== undefined) { - clearTimeout(subscription.toolFlushTimer); - subscription.toolFlushTimer = undefined; - subscription.toolFlushAt = 0; + /** Drain what is ready, then arm the one timer for the next held frame. */ + private drainAndReschedule(subscription: Subscription, mode: DrainMode): boolean { + if (!this.drain(subscription, mode)) return false; + if (!subscription.active || this.closed) return !this.closed; + const head = subscription.pendingUpdates[0]; + if (!head) { + clearTimeout(subscription.drainTimer); + subscription.drainTimer = undefined; + subscription.drainAt = 0; + return true; } - subscription.lastToolUpdateAt = now; - return this.writeFrame(subscription, held.data, held.at); + // 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; + // Only a held tool snapshot can stop a drain short of an empty queue. + if (head.kind !== "tool") return true; + const windowEnds = (subscription.lastToolUpdateAt.get(head.toolCallId) ?? 0) + TOOL_UPDATE_FRAME_MIN_INTERVAL_MS; + this.scheduleDrain(subscription, Math.max(windowEnds - Date.now(), 1)); + return true; } /** - * Arm the timer that releases a held tool snapshot. A newer frame only pulls - * the deadline forward, never pushes it back; while the socket is behind it - * retries shortly and keeps the latest snapshot instead of buffering frames. + * Arm the timer that releases held frames. A newer frame only pulls the + * deadline forward, never pushes it back. */ - private scheduleToolFlush(subscription: Subscription, delayMs: number): void { + private scheduleDrain(subscription: Subscription, delayMs: number): void { if (!subscription.active || this.closed) return; - const deadline = Date.now() + Math.max(0, delayMs); - if (subscription.toolFlushTimer !== undefined && subscription.toolFlushAt <= deadline) return; - clearTimeout(subscription.toolFlushTimer); - subscription.toolFlushAt = deadline; - subscription.toolFlushTimer = setTimeout(() => { - subscription.toolFlushTimer = undefined; - subscription.toolFlushAt = 0; + 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; - if (this.sink.backpressured()) { - this.scheduleToolFlush(subscription, TOOL_UPDATE_RETRY_MS); - return; - } - if (!this.flushToolUpdate(subscription)) return; - if (subscription.heldToolUpdate) { - const remaining = subscription.lastToolUpdateAt + TOOL_UPDATE_FRAME_MIN_INTERVAL_MS - Date.now(); - this.scheduleToolFlush(subscription, Math.max(remaining, TOOL_UPDATE_RETRY_MS)); - } - }, Math.max(0, delayMs)); + this.drainAndReschedule(subscription, "ready"); + }, delayMs); // A throttle window must not keep the process alive. - subscription.toolFlushTimer.unref?.(); - } - - /** Hold the newest tool snapshot, writing it at once when its window is open. */ - private deliverToolUpdate(subscription: Subscription, data: Record): void { - const now = Date.now(); - subscription.heldToolUpdate = { data, at: now }; - const delay = subscription.lastToolUpdateAt + TOOL_UPDATE_FRAME_MIN_INTERVAL_MS - now; - if (delay <= 0 && !this.sink.backpressured()) { - this.flushToolUpdate(subscription, true); - return; - } - this.scheduleToolFlush(subscription, Math.max(delay, TOOL_UPDATE_RETRY_MS)); + subscription.drainTimer.unref?.(); } private deliver(subscription: Subscription, data: unknown): void { if (!subscription.active || this.closed) return; - if (subscription.throttlesAgentUpdates && isRecord(data) && data.type === "tool_execution_update") { - this.deliverToolUpdate(subscription, data); + // Other channels never queue: their frames are neither throttled nor merged. + if (!subscription.throttlesAgentUpdates) { + this.writeFrame(subscription, data); return; } - // Every other frame is a boundary (`message_end`, `tool_execution_end`, …): - // the held tool snapshot must reach the client before it, never after. - if (!this.flushToolUpdate(subscription, true)) return; - if ( - subscription.throttlesAgentUpdates - && 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); - return; + if (isRecord(data)) { + if (data.type === "tool_execution_update" && typeof data.toolCallId === "string" && data.toolCallId) { + queueToolUpdate(subscription.pendingUpdates, data.toolCallId, data); + this.drainAndReschedule(subscription, "ready"); + return; + } + if (data.type === "outbox_update" || data.type === "message_update") { + // Nothing waits: the frame goes out at once. Behind a held snapshot it + // releases that snapshot first, in order, instead of overtaking it. + if (subscription.pendingUpdates.length === 0 && !this.sink.backpressured()) { + this.writeFrame(subscription, data); + return; + } + queueUpdate(subscription.pendingUpdates, data, Date.now()); + this.drainAndReschedule(subscription, "release"); + return; + } } - if (this.flush(subscription, true)) this.writeFrame(subscription, data); + // Every other frame is a boundary (`tool_execution_end`, `message_end`, …): + // everything emitted before it must reach the client first, in order. + subscription.pendingUpdates.push({ kind: "frame", data, at: Date.now() }); + this.drainAndReschedule(subscription, "force"); } } -type QueuedUpdate = { data: Record; at: number }; +/** How much of a subscription's queue a drain may write. */ +type DrainMode = + /** Respect throttle windows and backpressure. */ + | "ready" + /** Ignore throttle windows, still respect backpressure. */ + | "release" + /** Ignore both: a boundary frame must not be delayed or overtaken. */ + | "force"; + +/** + * One queued frame. `at` is the emit time, except for a tool snapshot, which is + * stamped when it is written: holding it deliberately must not show up as + * network latency in Connection diagnostics. + */ +type QueuedFrame = + | { kind: "frame"; data: unknown; at: number } + | { kind: "tool"; toolCallId: string; data: Record }; + +/** + * Hold the newest snapshot of one tool in the queue. Each frame carries the + * tool's whole accumulated output, so a newer snapshot replaces the pending one + * in place: the queue stays bounded to one slot per tool, snapshots of + * concurrent tools never supersede each other, and a newer snapshot never + * overtakes the frames emitted before it. + */ +function queueToolUpdate(queue: QueuedFrame[], toolCallId: string, data: Record): void { + for (const frame of queue) { + if (frame.kind === "tool" && frame.toolCallId === toolCallId) { + frame.data = data; + return; + } + } + queue.push({ kind: "tool", toolCallId, data }); +} /** * Merge a `message_update` into a backpressure queue without losing anything: @@ -435,32 +463,35 @@ 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 { + // Only plain frames merge; a held tool snapshot keeps its place in the order. + const last = queue.at(-1); + const lastData = last?.kind === "frame" && isRecord(last.data) ? last.data : null; if (data.type === "outbox_update") { - const last = queue.at(-1); - if (last?.data.type === "outbox_update") { + if (last?.kind === "frame" && lastData?.type === "outbox_update") { last.data = data; last.at = at; } else { - queue.push({ data, at }); + queue.push({ kind: "frame", data, at }); } return; } 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 (frame.kind !== "frame" || !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 }); + queue.push({ kind: "frame", data, at }); return; } - const last = queue.at(-1); - const merged = last && isDeltaUpdate(last.data) ? mergeDeltaUpdates(last.data, data) : null; - if (last && merged) { + const merged = last && last.kind === "frame" && lastData && isDeltaUpdate(lastData) ? mergeDeltaUpdates(lastData, data) : null; + if (last && last.kind === "frame" && merged) { last.data = merged; last.at = at; } else { - queue.push({ data, at }); + queue.push({ kind: "frame", data, at }); } } @@ -516,9 +547,7 @@ function openRunningChannel(handle: SubscriptionHandle): SubscribeResult { // as reachable for toasts and in-page system notifications while this is open. function openNotificationsChannel(clientId: string, handle: SubscriptionHandle): SubscribeResult { handle.open(); - handle.setDetach(attachNotificationClient(clientId, (message) => { - handle.send({ type: "notification", kind: message.kind, event: message.event }); - })); + handle.setDetach(attachNotificationClient(clientId, (message) => handle.send({ type: "notification", ...message }))); return SUBSCRIBED; } From c36f2d177e8bcdd4aeb46fc544e954100d6a4263 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:17:22 +0100 Subject: [PATCH 03/10] fix(events): supersede a held tool snapshot in the newer frame position A newer snapshot of a tool replaced the pending one in its old slot, so a replacement carrying sequence 3 could be written before a frame carrying sequence 2 that was emitted earlier. web.sequence is the browser's cursor, so the later frame could be discarded as already seen or trigger catch-up. Remove the superseded slot and append the replacement instead, and keep the throttle constant out of the heartbeat block so #407 merges cleanly. --- lib/event-stream-hub.test.mjs | 51 +++++++++++++++++++++++++++++++++++ lib/event-stream-hub.ts | 32 ++++++++++++---------- 2 files changed, 69 insertions(+), 14 deletions(-) diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index 5644455c8..7dcd0ddd3 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -1029,6 +1029,57 @@ test("concurrent tools hold their newest snapshot independently and never supers } }); +/** 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 takes the newer frame position, never the superseded slot", 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], + "the replacement is written in the newer frame's position, so the cursor never goes backwards", + ); + 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"); diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index 110c2eab9..382d2cb3a 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -27,6 +27,13 @@ import { isRecord } from "./type-guards"; // Heartbeat keeps the socket alive through reverse proxies that drop silent connections. const HEARTBEAT_MS = 30_000; +const encoder = new TextEncoder(); + +export type SubscribeResult = + | { ok: true } + | { ok: false; status: number; error: string; code: string }; + +const SUBSCRIBED: SubscribeResult = { ok: true }; /** * The floor between two `tool_execution_update` snapshots of one tool in one @@ -40,13 +47,6 @@ const HEARTBEAT_MS = 30_000; * incremental since the delta protocol. */ export const TOOL_UPDATE_FRAME_MIN_INTERVAL_MS = 1_000; -const encoder = new TextEncoder(); - -export type SubscribeResult = - | { ok: true } - | { ok: false; status: number; error: string; code: string }; - -const SUBSCRIBED: SubscribeResult = { ok: true }; class Subscription { active = true; @@ -438,16 +438,20 @@ type QueuedFrame = /** * Hold the newest snapshot of one tool in the queue. Each frame carries the - * tool's whole accumulated output, so a newer snapshot replaces the pending one - * in place: the queue stays bounded to one slot per tool, snapshots of - * concurrent tools never supersede each other, and a newer snapshot never - * overtakes the frames emitted before it. + * tool's whole accumulated output, so a newer snapshot supersedes the pending + * one: its old slot is removed and the replacement takes the position of the + * newer frame, i.e. the end of the queue. The queue stays bounded to one slot + * per tool and snapshots of concurrent tools never supersede each other, but a + * replacement never keeps an old position either: `web.sequence` is a cursor + * for the browser, so a snapshot carrying sequence 3 must not be written ahead + * of a frame carrying sequence 2 that was emitted before it. */ function queueToolUpdate(queue: QueuedFrame[], toolCallId: string, data: Record): void { - for (const frame of queue) { + for (let i = 0; i < queue.length; i++) { + const frame = queue[i]; if (frame.kind === "tool" && frame.toolCallId === toolCallId) { - frame.data = data; - return; + queue.splice(i, 1); + break; } } queue.push({ kind: "tool", toolCallId, data }); From 6fe87811641f50c329b5257cda6ea290167c5c1a Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:42:47 +0100 Subject: [PATCH 04/10] docs(events): describe the supersede position in the throttle contract --- AGENTS.md | 16 +++++++++------- CHANGELOG.md | 2 +- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 1b1affa6b..8951d70cf 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1146,13 +1146,15 @@ end to end: call is held per subscription and written at most once per `TOOL_UPDATE_FRAME_MIN_INTERVAL_MS`. The hold is per `toolCallId`: concurrent tools never supersede each other, and one tool's window never delays another - tool's snapshot. The held snapshot keeps its place in the same ordered queue - as the message deltas and outbox snapshots, so a boundary frame - (`tool_execution_end`, `message_end`, …) or a delta emitted after it can never - overtake it, and the heartbeat force-flush drains that one queue rather than - writing around it. 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. + tool's snapshot. A superseding snapshot removes the held one and takes the + newer frame's position at the end of the same ordered queue as the message + deltas and outbox snapshots: `web.sequence` is the browser's cursor, so a + replacement carrying a later sequence must never be written ahead of a frame + emitted before it. A boundary frame (`tool_execution_end`, `message_end`, …) + or a delta emitted after it can therefore never be overtaken, and the + heartbeat force-flush drains that one queue rather than writing around it. 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 183a54b53..d6dcaf1b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -184,7 +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, writing the final output immediately when the tool ends. Concurrent tools keep their own snapshot, so a slow one never hides another's progress, and held output never overtakes the message text around it. The delay is not reported as connection latency. +- **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, writing the final output immediately when the tool ends. Concurrent tools keep their own snapshot, so a slow one never hides another's progress, and held output never overtakes the message text around it. A newer snapshot of a tool replaces the held one at the position of that newer frame, so the stream's sequence numbers stay ordered even when several tools and message deltas are queued. 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. From 3bb587f2ad79a95fc84474851bb2ef7073676c18 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:33:00 +0100 Subject: [PATCH 05/10] fix(events): hold tool snapshots outside the ordered queue so the cap holds MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A message delta drained with 'release', which ignored the throttle window: every delta flushed the held snapshot. A bash tool printing while the model streams text (the normal case) therefore got one snapshot per delta — 10 snapshots in 1000 ms — so the advertised one-per-second cap did not exist in the case it was written for. A delta no longer waits for a held snapshot and never releases one. Holding the snapshot in the ordered message queue also made one tool's closed window delay another tool's first snapshot by up to the full interval (t2-v1 arrived 901 ms late). Tool frames are fenced by max(lifecycleSequence, toolsSnapshotSequence, toolSequences.get(tool)) in hooks/useAgentSession-sync.ts and never by messageSequence, so they need no position among the deltas: the newest snapshot per toolCallId is now held outside the queue and enqueued only when its window opens. Held snapshots release in their own emission order, so a replacement carrying a later web.sequence never precedes one carrying an earlier sequence. A boundary frame merges every held snapshot into the queue ahead of itself, in emission order, and the forced drain writes the whole queue regardless of backpressure, so tool_execution_end never overtakes the output it ends. AGENTS.md and the CHANGELOG now state what the code does: the hold is per toolCallId and outside the message queue, deltas neither wait for nor release a snapshot, and a never-written tool is never delayed. Also drops the stray blank lines the previous push left in the test file. --- AGENTS.md | 31 +++--- CHANGELOG.md | 2 +- lib/event-stream-hub.test.mjs | 80 +++++++++++--- lib/event-stream-hub.ts | 197 +++++++++++++++++++--------------- 4 files changed, 195 insertions(+), 115 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 8951d70cf..f9d49506d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1142,19 +1142,24 @@ end to end: 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 one snapshot per tool - call is held per subscription and written at most once per - `TOOL_UPDATE_FRAME_MIN_INTERVAL_MS`. The hold is per `toolCallId`: concurrent - tools never supersede each other, and one tool's window never delays another - tool's snapshot. A superseding snapshot removes the held one and takes the - newer frame's position at the end of the same ordered queue as the message - deltas and outbox snapshots: `web.sequence` is the browser's cursor, so a - replacement carrying a later sequence must never be written ahead of a frame - emitted before it. A boundary frame (`tool_execution_end`, `message_end`, …) - or a delta emitted after it can therefore never be overtaken, and the - heartbeat force-flush drains that one queue rather than writing around it. 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. + 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`. 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`). Two consequences, both + 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), and a tool that has never been written has no + window, so its first snapshot is never delayed behind another tool's hold. + Held snapshots release in their own emission order, so a replacement carrying + a later `web.sequence` never precedes one carrying an earlier sequence. A + boundary frame (`tool_execution_end`, `message_end`, …) merges every held + snapshot into the queue ahead of itself, in emission order, and the forced + drain then writes the whole queue regardless of backpressure, so the end frame + never overtakes the output it ends. 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 d6dcaf1b1..ad030b29e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -184,7 +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, writing the final output immediately when the tool ends. Concurrent tools keep their own snapshot, so a slow one never hides another's progress, and held output never overtakes the message text around it. A newer snapshot of a tool replaces the held one at the position of that newer frame, so the stream's sequence numbers stay ordered even when several tools and message deltas are queued. The delay is not reported as connection latency. +- **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, 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. Held snapshots release in their own emission order, so the stream's sequence numbers stay ordered, and a frame that ends a tool never overtakes the output it ends. 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/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index 7dcd0ddd3..b13f0d280 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -947,9 +947,6 @@ 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"); @@ -1004,13 +1001,17 @@ test("concurrent tools hold their newest snapshot independently and never supers 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 is held, not dropped by t1's window"); + 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", "t1-v2", "t2-v1"], - "each tool releases its own newest snapshot, in emission order", + ["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. @@ -1021,7 +1022,7 @@ test("concurrent tools hold their newest snapshot independently and never supers t.mock.timers.tick(1_000); assert.deepEqual( writes.map(({ data }) => data.output), - ["t1-v1", "t1-v2", "t2-v1", "t1-v3", "t2-v2", "t2-v3"], + ["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 { @@ -1034,7 +1035,7 @@ const toolFrame = (toolCallId, sequence, output) => ({ type: "tool_execution_update", toolCallId, output, web: { streamId: "s", sequence }, }); -test("a superseding tool snapshot takes the newer frame position, never the superseded slot", async () => { +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. @@ -1048,7 +1049,7 @@ test("a superseding tool snapshot takes the newer frame position, never the supe assert.deepEqual( writes.map(({ data }) => data.web.sequence), [2, 3], - "the replacement is written in the newer frame's position, so the cursor never goes backwards", + "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 { @@ -1090,8 +1091,8 @@ test("a held tool snapshot is not lost when a boundary frame ends its tool", { t 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", "ab"], ["tool_execution_update", "b"], ["tool_execution_end", "ab"]], - "both held snapshots flush in emission order before the end frame", + [["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(); @@ -1109,11 +1110,11 @@ test("message deltas are never throttled while a tool snapshot is held", { timeo session.emit(deltaFrame(1, "text_delta", 0, { delta: "hi" })); assert.deepEqual( writes.slice(1).map(({ data }) => data.type), - ["tool_execution_update", "message_update"], - "the held tool snapshot flushes before the delta, so per-subscription order holds", + ["message_update"], + "a delta is written at once and never releases the held snapshot", ); - assert.equal(writes[1].data.output, "held"); - assert.equal(writes[2].data.assistantMessageEvent.delta, "hi"); + assert.equal(writes[1].data.assistantMessageEvent.delta, "hi"); + assert.equal(writes.length, 2, "the held snapshot is still waiting for its window"); } finally { done(); } @@ -1347,3 +1348,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 382d2cb3a..e1e3993ad 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -44,20 +44,32 @@ const SUBSCRIBED: SubscribeResult = { ok: true }; * 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. + * 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, in emission order: message updates merge and - // consecutive outbox snapshots replace each other, a tool snapshot is held - // in place until its own window opens. One writer drains the whole queue, so - // no frame ever overtakes an older one. + // 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. */ @@ -68,6 +80,7 @@ class Subscription { /** 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; @@ -302,22 +315,28 @@ export class EventStreamConnection { private flushAll(): boolean { for (const subscription of this.subscriptions.values()) { - if (!this.drainAndReschedule(subscription, "ready")) return false; + if (!this.drainAndReschedule(subscription)) return false; } return !this.closed; } /** - * Write queued frames in emission order, never overtaking one emitted before. - * `ready` stops at the first frame whose throttle window is closed and while - * the peer is behind, leaving the rest queued; `release` ignores the window - * (a delta must not wait for a held snapshot ahead of it) but not - * backpressure; `force` ignores both, because the boundary frame that follows - * must not be delayed. 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. + * 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, or the heartbeat) writes both 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. + * + * 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, mode: DrainMode): boolean { + 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); @@ -325,32 +344,36 @@ export class EventStreamConnection { const queue = subscription.pendingUpdates; let written = 0; while (written < queue.length) { - if (mode !== "force" && this.sink.backpressured()) break; + if (!force && this.sink.backpressured()) break; const frame = queue[written]; - let at: number; - if (frame.kind === "tool") { - if (mode === "ready" && Date.now() < (subscription.lastToolUpdateAt.get(frame.toolCallId) ?? 0) + TOOL_UPDATE_FRAME_MIN_INTERVAL_MS) break; - at = Date.now(); - subscription.lastToolUpdateAt.set(frame.toolCallId, at); - } else { - at = frame.at; - } written += 1; - if (!this.writeFrame(subscription, frame.data, at)) { + if (!this.writeFrame(subscription, frame.data, frame.tool ? Date.now() : frame.at)) { queue.splice(0, written); return !this.closed; } } queue.splice(0, written); + if (this.sink.backpressured()) return !this.closed; + // Release what the windows allow, in emission order: two tools whose windows + // are both open must not be written in map order, or a snapshot carrying a + // later sequence would precede one carrying an earlier sequence. + 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) { + 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 frame. */ - private drainAndReschedule(subscription: Subscription, mode: DrainMode): boolean { - if (!this.drain(subscription, mode)) return false; + /** 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; - const head = subscription.pendingUpdates[0]; - if (!head) { + if (subscription.heldToolUpdates.size === 0) { clearTimeout(subscription.drainTimer); subscription.drainTimer = undefined; subscription.drainAt = 0; @@ -359,10 +382,12 @@ export class EventStreamConnection { // 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; - // Only a held tool snapshot can stop a drain short of an empty queue. - if (head.kind !== "tool") return true; - const windowEnds = (subscription.lastToolUpdateAt.get(head.toolCallId) ?? 0) + TOOL_UPDATE_FRAME_MIN_INTERVAL_MS; - this.scheduleDrain(subscription, Math.max(windowEnds - Date.now(), 1)); + 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; } @@ -380,12 +405,29 @@ export class EventStreamConnection { subscription.drainTimer = undefined; subscription.drainAt = 0; if (!subscription.active || this.closed) return; - this.drainAndReschedule(subscription, "ready"); + this.drainAndReschedule(subscription); }, delayMs); // A throttle window must not keep the process alive. subscription.drainTimer.unref?.(); } + /** + * 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; // Other channels never queue: their frames are neither throttled nor merged. @@ -395,67 +437,51 @@ export class EventStreamConnection { } if (isRecord(data)) { if (data.type === "tool_execution_update" && typeof data.toolCallId === "string" && data.toolCallId) { - queueToolUpdate(subscription.pendingUpdates, data.toolCallId, data); - this.drainAndReschedule(subscription, "ready"); + // 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. Behind a held snapshot it - // releases that snapshot first, in order, instead of overtaking it. - if (subscription.pendingUpdates.length === 0 && !this.sink.backpressured()) { + // 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, "release"); + 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. - subscription.pendingUpdates.push({ kind: "frame", data, at: Date.now() }); - this.drainAndReschedule(subscription, "force"); + // 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); } } -/** How much of a subscription's queue a drain may write. */ -type DrainMode = - /** Respect throttle windows and backpressure. */ - | "ready" - /** Ignore throttle windows, still respect backpressure. */ - | "release" - /** Ignore both: a boundary frame must not be delayed or overtaken. */ - | "force"; - /** - * One queued frame. `at` is the emit time, except for a tool snapshot, which is - * stamped when it is written: holding it deliberately must not show up as - * network latency in Connection diagnostics. + * 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 = - | { kind: "frame"; data: unknown; at: number } - | { kind: "tool"; toolCallId: string; data: Record }; +type QueuedFrame = { data: unknown; at: number; tool?: boolean }; /** - * Hold the newest snapshot of one tool in the queue. Each frame carries the - * tool's whole accumulated output, so a newer snapshot supersedes the pending - * one: its old slot is removed and the replacement takes the position of the - * newer frame, i.e. the end of the queue. The queue stays bounded to one slot - * per tool and snapshots of concurrent tools never supersede each other, but a - * replacement never keeps an old position either: `web.sequence` is a cursor - * for the browser, so a snapshot carrying sequence 3 must not be written ahead - * of a frame carrying sequence 2 that was emitted before it. + * 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. */ -function queueToolUpdate(queue: QueuedFrame[], toolCallId: string, data: Record): void { - for (let i = 0; i < queue.length; i++) { - const frame = queue[i]; - if (frame.kind === "tool" && frame.toolCallId === toolCallId) { - queue.splice(i, 1); - break; - } - } - queue.push({ kind: "tool", toolCallId, data }); -} +type HeldToolUpdate = { data: Record; seq: number }; /** * Merge a `message_update` into a backpressure queue without losing anything: @@ -468,34 +494,33 @@ function queueToolUpdate(queue: QueuedFrame[], toolCallId: string, data: Record< * and break the sequence fence the browser relies on. */ function queueUpdate(queue: QueuedFrame[], data: Record, at: number): void { - // Only plain frames merge; a held tool snapshot keeps its place in the order. const last = queue.at(-1); - const lastData = last?.kind === "frame" && isRecord(last.data) ? last.data : null; + const lastData = last && isRecord(last.data) ? last.data : null; if (data.type === "outbox_update") { - if (last?.kind === "frame" && lastData?.type === "outbox_update") { + if (last && lastData?.type === "outbox_update") { last.data = data; last.at = at; } else { - queue.push({ kind: "frame", data, at }); + queue.push({ data, at }); } return; } if (!isDeltaUpdate(data)) { for (let i = queue.length - 1; i >= 0; i--) { const frame = queue[i]; - if (frame.kind !== "frame" || !isRecord(frame.data)) continue; + if (!isRecord(frame.data)) continue; if (frame.data.type === "outbox_update") break; if (frame.data.messageId === data.messageId) queue.splice(i, 1); } - queue.push({ kind: "frame", data, at }); + queue.push({ data, at }); return; } - const merged = last && last.kind === "frame" && lastData && isDeltaUpdate(lastData) ? mergeDeltaUpdates(lastData, data) : null; - if (last && last.kind === "frame" && merged) { + const merged = lastData && isDeltaUpdate(lastData) ? mergeDeltaUpdates(lastData, data) : null; + if (last && merged) { last.data = merged; last.at = at; } else { - queue.push({ kind: "frame", data, at }); + queue.push({ data, at }); } } From adf6bdbdeb40789fc2062860495969cbe36bc165 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:21:10 +0100 Subject: [PATCH 06/10] fix(events): keep #407's per-connection heartbeat through the rebase The branch's pre-#407 commit dropped the then-unconsumed heartbeat plumbing. Rebased onto main, that deletion removed a shipped feature: the route parses `/api/events?heartbeat=` and the SSE sink arms that interval. Keep main's parser and sink interval; only the branch's duplicate constructor option stays gone. --- lib/event-stream-hub.ts | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index e1e3993ad..8dfc6458b 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -26,7 +26,19 @@ import { isRecord } from "./type-guards"; // the browser's shared worker. // Heartbeat keeps the socket alive through reverse proxies that drop silent connections. +// A native client may ask for a longer one per connection (`/api/events?heartbeat=`). const HEARTBEAT_MS = 30_000; +export const MIN_HEARTBEAT_SECONDS = 15; +export const MAX_HEARTBEAT_SECONDS = 110; + +/** `?heartbeat=` in [15, 110]; anything else keeps the 30 s default. */ +export function parseHeartbeatSeconds(value: string | null | undefined): number { + if (typeof value !== "string" || !/^\d{1,4}$/.test(value.trim())) return HEARTBEAT_MS / 1000; + const seconds = Number(value.trim()); + if (seconds < MIN_HEARTBEAT_SECONDS || seconds > MAX_HEARTBEAT_SECONDS) return HEARTBEAT_MS / 1000; + return seconds; +} + const encoder = new TextEncoder(); export type SubscribeResult = @@ -128,11 +140,12 @@ export interface FrameSink { } class SseSink implements FrameSink { - readonly heartbeatMs = HEARTBEAT_MS; + readonly heartbeatMs: number; readonly stream: ReadableStream; private controller!: ReadableStreamDefaultController; - constructor(onPull: () => void, onCancel: () => void) { + constructor(onPull: () => void, onCancel: () => void, heartbeatMs = HEARTBEAT_MS) { + this.heartbeatMs = heartbeatMs; this.stream = new ReadableStream({ start: (controller) => { this.controller = controller; }, // A slow consumer resumed reading: deliver coalesced updates now rather From d68d5509820446847a1f93caaa26367b5bc3322d Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:21:16 +0100 Subject: [PATCH 07/10] fix(events): never write a queued frame twice when the peer pulls mid-write drain() kept writing from the live pendingUpdates array and spliced it only after the loop. A frame sink whose write releases the peer synchronously (an SSE pull calls resume(), which drains every subscription) re-entered drain() while the frame was still in the array, so the peer received the same boundary frame twice. The multi-server integration test caught it as three tool_execution_end frames for two prompts: a forced boundary flush re-entered through the peer's pull. The queue is now detached before the loop, as the pre-throttle flush already did, and frames appended during the loop stay behind the un-written remainder. The drain docstring now states that the heartbeat retries on the non-force path, and the release comment no longer claims a cross-tool sequence dependency. A unit test with a sink that calls resume() from write() guards the duplicate. --- lib/event-stream-hub.test.mjs | 41 +++++++++++++++++++++++++++++++++++ lib/event-stream-hub.ts | 29 +++++++++++++++---------- 2 files changed, 58 insertions(+), 12 deletions(-) diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index b13f0d280..32bc87c83 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -865,6 +865,47 @@ 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("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; } }; diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index 8dfc6458b..75e973e35 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -341,10 +341,12 @@ export class EventStreamConnection { * (deltas arrive constantly) and keeps one tool's window from delaying * another tool's snapshot. * - * `force` (a boundary frame is waiting, or the heartbeat) writes both 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. + * `force` (a boundary frame is waiting) writes the queue and the held + * snapshots 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 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. @@ -354,22 +356,25 @@ export class EventStreamConnection { 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 = []; 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)) { - queue.splice(0, written); - return !this.closed; - } + if (!this.writeFrame(subscription, frame.data, frame.tool ? Date.now() : frame.at)) return !this.closed; } - queue.splice(0, written); + // 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, in emission order: two tools whose windows - // are both open must not be written in map order, or a snapshot carrying a - // later sequence would precede one carrying an earlier sequence. + // 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); From c15121fa90ebffe4f25839acdefb3c4666a657a2 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:21:21 +0100 Subject: [PATCH 08/10] docs(events): state the throttle's real sequence domains and boundary exceptions AGENTS and the CHANGELOG claimed globally ordered web.sequence values. The actual contract keeps separate domains: message deltas are ordered and lossless among themselves, each tool's frames stay monotonic, and a boundary frame follows the frames emitted before it; tool@29 may precede tool@26 and message@3 may precede tool@2 because the consumer keeps separate floors. Also document that every non-update session frame (another tool's start/end, btw_delta, message_end, ...) is a boundary that releases held snapshots at the pre-throttle rate: the cap holds between progress reports of one tool, not unconditionally. --- AGENTS.md | 37 ++++++++++++++++++++++++------------- CHANGELOG.md | 2 +- 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f9d49506d..aeb5effa4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1144,22 +1144,33 @@ end to end: - 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`. A tool frame needs no position - among the deltas: the browser fences it by `max(lifecycleSequence, + 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`). Two consequences, both + `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), and a tool that has never been written has no - window, so its first snapshot is never delayed behind another tool's hold. - Held snapshots release in their own emission order, so a replacement carrying - a later `web.sequence` never precedes one carrying an earlier sequence. A - boundary frame (`tool_execution_end`, `message_end`, …) merges every held - snapshot into the queue ahead of itself, in emission order, and the forced - drain then writes the whole queue regardless of backpressure, so the end frame - never overtakes the output it ends. 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. + 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 ad030b29e..e476df9e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -184,7 +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, 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. Held snapshots release in their own emission order, so the stream's sequence numbers stay ordered, and a frame that ends a tool never overtakes the output it ends. The delay is not reported as connection latency. +- **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. From f4d4e0bef9838557f872978dbd6cc1b00b95ffc6 Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:21:26 +0100 Subject: [PATCH 09/10] test(events): accept an older tool snapshot after a newer message delta Drive the real createSessionCatchUp.observe: message-delta@3 is applied, then tool@2 for a tool is accepted because the tool floor is max(lifecycleSequence, toolsSnapshotSequence, toolSequences.get(tool)) and never messageSequence. The same tool's older snapshot stays stale and another tool keeps its own floor. Adding messageSequence to the tool floor makes this test fail, which the current hub/sync/coalescer suites did not catch. --- hooks/useAgentSession-sync.test.mjs | 31 +++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) 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"] }); From 04a5ab4a3302b23f956bdc0acbd5ca53be50752b Mon Sep 17 00:00:00 2001 From: RoyaLemonade <37620553+RoyaLemonade@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:34:01 +0100 Subject: [PATCH 10/10] fix(events): never release a held snapshot twice when a pull re-enters the drain The release loop iterated a stale copy of heldToolUpdates. A sink whose write synchronously calls resume() drained the later held entries first and wrote them; the outer loop then reached the same stale entry, deleted nothing and wrote the frame a second time (two tools with open windows: t2-v2 twice). Stop at the live map's current value before writing each entry. Adds a regression test where one timer drain releases two held snapshots while the sink pulls from write(). Also narrows the drain docstring: force covers the queued frames, not a separately released held snapshot, which still waits for capacity; drops the double blank line the test file carried. --- lib/event-stream-hub.test.mjs | 48 ++++++++++++++++++++++++++++++++++- lib/event-stream-hub.ts | 17 ++++++++----- 2 files changed, 58 insertions(+), 7 deletions(-) diff --git a/lib/event-stream-hub.test.mjs b/lib/event-stream-hub.test.mjs index 32bc87c83..3609ba29f 100644 --- a/lib/event-stream-hub.test.mjs +++ b/lib/event-stream-hub.test.mjs @@ -906,6 +906,53 @@ test("a boundary frame written to a peer that pulls synchronously is not written } }); +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; } }; @@ -1225,7 +1272,6 @@ test("a heartbeat never writes a held tool snapshot around queued message deltas } }); - 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"); diff --git a/lib/event-stream-hub.ts b/lib/event-stream-hub.ts index 75e973e35..f15091391 100644 --- a/lib/event-stream-hub.ts +++ b/lib/event-stream-hub.ts @@ -341,12 +341,13 @@ export class EventStreamConnection { * (deltas arrive constantly) and keeps one tool's window from delaying * another tool's snapshot. * - * `force` (a boundary frame is waiting) writes the queue and the held - * snapshots 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. + * `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. @@ -379,6 +380,10 @@ export class EventStreamConnection { .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);