diff --git a/packages/core/src/webui/state-stream.ts b/packages/core/src/webui/state-stream.ts index 5f711cde..b51c4896 100644 --- a/packages/core/src/webui/state-stream.ts +++ b/packages/core/src/webui/state-stream.ts @@ -46,30 +46,56 @@ const ALL_RESOURCES: readonly StateResource[] = ['processes', 'qq-list', 'connec export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle { const debounceMs = opts.debounceMs ?? 50; const timers = new Map>(); + // Single-flight per resource: at most one in-flight flush per resource so + // an uneven snapshot latency cannot interleave sends out of order (a slow + // earlier snapshot landing AFTER a later one, leaving the client's last + // observed frame stale). Publishes arriving while a flush is in flight + // mark `pending` and rearm the debounce timer once the flush completes. + const inFlight = new Set(); + const pending = new Set(); let disposed = false; const flush = async (resource: StateResource): Promise => { if (disposed) return; - let data: unknown; + inFlight.add(resource); try { - data = await opts.snapshot(resource); - } catch { - // Per-resource snapshot failure (e.g. listProcesses threw): skip - // this frame so siblings keep flowing. The next publish for the - // same resource gets a fresh attempt. - return; - } - if (disposed) return; - try { - opts.send({ resource, data }); - } catch { - // Downstream consumer (e.g. closed SSE controller) — same isolation - // contract as snapshot failures. + let data: unknown; + try { + data = await opts.snapshot(resource); + } catch { + // Per-resource snapshot failure (e.g. listProcesses threw): skip + // this frame so siblings keep flowing. The next publish for the + // same resource gets a fresh attempt. + return; + } + if (disposed) return; + try { + opts.send({ resource, data }); + } catch { + // Downstream consumer (e.g. closed SSE controller) — same isolation + // contract as snapshot failures. + } + } finally { + inFlight.delete(resource); + // If a publish arrived during the in-flight window, schedule one + // follow-up flush. Re-uses the debounce so a sustained publish + // stream produces at most one frame per (debounceMs + flushLatency), + // not back-to-back frames. + if (!disposed && pending.has(resource)) { + pending.delete(resource); + schedule(resource); + } } }; const schedule = (resource: StateResource): void => { if (disposed) return; + if (inFlight.has(resource)) { + // Defer to the post-flush re-arm; no new timer until the in-flight + // send completes. This is the load-bearing invariant for ordering. + pending.add(resource); + return; + } const existing = timers.get(resource); if (existing) clearTimeout(existing); const t = setTimeout(() => { @@ -85,7 +111,9 @@ export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle async sendAllInitial(): Promise { if (disposed) return; // Fire all three in parallel. Each resource's snapshot is independent - // so a slow listProcesses() doesn't gate qq-list/connections. + // so a slow listProcesses() doesn't gate qq-list/connections. Each + // call goes through the single-flight gate so a concurrent bus + // publish during this initial fan-out coalesces correctly. await Promise.all(ALL_RESOURCES.map((r) => flush(r))); }, dispose(): void { @@ -94,6 +122,7 @@ export function bindStateStream(opts: BindStateStreamOptions): StateStreamHandle unsubscribe(); for (const t of timers.values()) clearTimeout(t); timers.clear(); + pending.clear(); }, }; } diff --git a/packages/core/tests/webui-state-stream.test.ts b/packages/core/tests/webui-state-stream.test.ts index d36db4ed..6c37d9c1 100644 --- a/packages/core/tests/webui-state-stream.test.ts +++ b/packages/core/tests/webui-state-stream.test.ts @@ -155,6 +155,72 @@ describe('bindStateStream', () => { handle.dispose(); }); + it('serialises overlapping flushes for the same resource — the LAST sent frame reflects the LATEST publish (no stale overwrite)', async () => { + const bus = new StateBus(); + const sent: CapturedFrame[] = []; + // Variable-latency snapshot: 1st call sleeps 200ms (slow), 2nd call + // sleeps 10ms (fast). Without single-flight, the second publish would + // race-overlap and send BEFORE the first, leaving the client's last + // observed frame as the older snapshot. + let call = 0; + const versions = ['snap-T0', 'snap-T60']; + const snapshot = vi.fn(async (resource: StateResource): Promise => { + const i = call++; + const sleep = i === 0 ? 200 : 10; + await new Promise((r) => setTimeout(r, sleep)); + return versions[i] ?? `snap-#${i}`; + }); + const handle = bindStateStream({ + bus, snapshot, + send: (f) => sent.push(f), + debounceMs: 50, + }); + + bus.publish('processes'); // schedules timer1 → fires at 50, snapshot A (200ms) + await vi.advanceTimersByTimeAsync(60); + bus.publish('processes'); // arrives WHILE flush A is mid-snapshot + await vi.advanceTimersByTimeAsync(60); // hits 120: timer2 should have fired, flush B observed_after A completes + await vi.advanceTimersByTimeAsync(300); // settle everything + + // Exactly two frames; the LAST one must reflect the most recent snapshot. + expect(sent).toHaveLength(2); + expect(sent[sent.length - 1]).toEqual({ resource: 'processes', data: 'snap-T60' }); + // For single-flight: snapshot is called once per flush (no overlap), + // so the SECOND snapshot read sees the latest state. + expect(call).toBe(2); + + handle.dispose(); + }); + + it('multiple publishes during an in-flight flush coalesce into ONE follow-up flush, not N', async () => { + const bus = new StateBus(); + const sent: CapturedFrame[] = []; + let call = 0; + const snapshot = vi.fn(async (resource: StateResource): Promise => { + call++; + await new Promise((r) => setTimeout(r, 100)); + return `snap-#${call}`; + }); + const handle = bindStateStream({ + bus, snapshot, + send: (f) => sent.push(f), + debounceMs: 50, + }); + + bus.publish('processes'); + await vi.advanceTimersByTimeAsync(55); + // flush A in flight (100ms more). Send 5 publishes during the in-flight window. + for (let i = 0; i < 5; i++) bus.publish('processes'); + await vi.advanceTimersByTimeAsync(200); + await vi.advanceTimersByTimeAsync(200); + + // 1 initial flush + 1 coalesced follow-up = 2 frames, NOT 6. + expect(sent).toHaveLength(2); + expect(call).toBe(2); + + handle.dispose(); + }); + it('send() throw is isolated — the next publish still reaches a healthy send()', async () => { const bus = new StateBus(); const sent: CapturedFrame[] = [];