Skip to content
158 changes: 158 additions & 0 deletions docs/design/2026-07-16-webshell-transcript-batched-dispatch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
# Web Shell: Batched Transcript Dispatch on SSE Resume

## Problem

When a Web Shell session has accumulated a large transcript and the browser tab
is switched away for a while, then switched back, the page can freeze for
several minutes or the tab crashes (OOM / "page unresponsive"). The trigger is
the SSE stream draining a burst of buffered events all at once on tab return.

The freeze is not specific to many simultaneous sessions: the sidebar and
Session Overview only poll (no per-session SSE/store), and the split view caps
live panes at `MAX_SPLIT_PANES = 6`. The dominant case is a **single large
session** whose transcript is large and whose buffered stream replays in one
tight loop on return.

## Root Cause (verified against code)

The transcript store applies every dispatch with a cost linear in the number of
retained blocks `B`:

- `store.dispatch` → `reduceDaemonTranscriptEvents`
(`packages/sdk-typescript/src/daemon/ui/store.ts:54`) copies the whole blocks
array once per dispatch via `takeBlocksOwnership`
(`packages/sdk-typescript/src/daemon/ui/transcript.ts:1252`,
`state.blocks = [...state.blocks]`) and then unconditionally
`Object.freeze(result.blocks)` (`transcript.ts:139`) — both `O(B)`.

The live SSE consumer dispatches **once per daemon event**
(`packages/webui/src/daemon/session/DaemonSessionProvider.tsx:1142`, inside the
`for await` loop at `:1040`). While the tab is hidden the browser buffers SSE
bytes; on return the loop drains the backlog event-by-event. Total cost is
`O(E × B)` — effectively quadratic — for `E` buffered events over `B` blocks.
With `DEFAULT_MAX_BLOCKS = 200_000`
(`DaemonSessionProvider.tsx:184`) this is the multi-minute main-thread block,
and the per-dispatch array allocations create the GC pressure that crashes the
tab.

Each dispatch also re-runs the full O(n) message normalization
(`hooks/useMessages.ts` → `MessageList.tsx`), so per-event dispatch multiplies
render cost too.

The daemon already bounds the **server-side** replay window to 4 MiB
(`docs/design/2026-07-07-bounded-replay-snapshot-window.md`); the unbounded
growth here is the **client-side** retained transcript over a long live session.

## Goals

- Make an SSE resume burst cost `O(B)` once instead of `O(E × B)`, without
changing transcript semantics or event ordering.
- Preserve all per-event control logic in the live loop (prompt settling,
passive observer, `replay_complete`, `state_resync_required`,
`prompt.cancelled`).
- Bound peak client memory and steady-state normalization cost for very large
transcripts.
- Remove a wasteful `O(B)` production-only freeze without losing the dev-time
safety net it provides.

## Non-Goals

- No change to the daemon-side replay window or wire shape.
- No persistent / structural-sharing data structure for blocks (a flat array
stays; this is a larger rewrite, out of scope).
- No change to virtualization, message normalization shape, or rendering rules.

## Design

### Fix A — Batch the live transcript dispatch (core fix)

In `DaemonSessionProvider`'s `for await` loop, transcript-mutating UI events are
accumulated into a pending buffer and flushed in a **single** `store.dispatch`
on a macrotask boundary, instead of one dispatch per event.

Why macrotask, not microtask: the loop is `for await` over an async generator,
so a burst of already-buffered events drains back-to-back via microtasks. A
`queueMicrotask` flush would run between every event (no coalescing). A
macrotask flush (`requestAnimationFrame` where available, `setTimeout(0)`
fallback for Node/tests) only runs once the generator blocks on a genuinely new
network event — so a whole burst collapses into one dispatch, while steady
streaming stays at roughly one dispatch per frame.

Batcher API (local to the `run()` scope):

- `enqueue(events)` — push transcript events, schedule a flush if none pending.
- `flushSync()` — cancel the scheduled flush and dispatch the buffer now.
- `dispatchNow(events)` — `flushSync()` then dispatch a control event, so
control events keep correct order relative to buffered transcript events.
- `clearPending()` — drop the buffer (used before `store.reset()` where pending
events are stale).

Flush points:

- Replace the per-event `store.dispatch(eventsToDispatch)` with
`enqueue(eventsToDispatch)`.
- `flushSync()` before turn-terminal handling
(`turn_complete` / `turn_error`) so `settleActivePromptFromTurnEvent`'s
`assistant.done` is ordered after the turn's transcript content.
- Route observer `assistant.done`, `replay_complete` `assistant.done`, and
`prompt.cancelled` `assistant.done` through `dispatchNow`.
- `clearPending()` before `store.reset()` (resync / epoch reload).
- `flushSync()` on loop exit and provider unmount so no buffered events are lost.

Known minor semantic: `shouldGuardAssistant` reads `store.getSnapshot()`
pre-dispatch and may lag the pending buffer by a few events within a burst. This
only affects whether rare `debug` events are filtered while observing another
client's turn; it does not affect ordering or correctness of rendered content.

### Fix B2 — Dev-only block freeze

`Object.freeze(result.blocks)` (`transcript.ts:139`) exists to catch consumers
mutating a COW-shared blocks array in place. That is a dev/CI safety net; in
production it is pure `O(B)` overhead on every dispatch. Guard it behind a
dev-mode check so production skips it while dev/CI keeps the protection. The
reducer's own mutation discipline (`takeBlocksOwnership`) does not depend on the
freeze.

### Fix B1 — Bound the web-shell client `maxBlocks`

Introduce a documented, tunable constant for the web-shell transcript window and
pass it from the main provider (`WorkspaceSessionProvider`) and split panes
(`SplitView`). The SDK default (`200_000`) stays unchanged for other consumers.
This bounds peak memory and the per-flush normalization constant while still
retaining a very large history (proposed `50_000`; trivially tunable). The
daemon remains the authoritative full-transcript source.

## Audit Notes

Round 1: A microtask flush was rejected — `for await` drains buffered events
via microtasks, so a microtask flush fires between every event and never
coalesces. A macrotask flush is required.

Round 2: Deferring all dispatch would break control logic that reads the store
after dispatch (`replay_complete` → `awaitingResync`, turn-terminal
`assistant.done`). The batcher flushes synchronously before every control
interaction, preserving order.

Round 3: `store.reset()` must clear the pending buffer, not flush it — pending
events belong to the epoch being discarded.

Round 4: Lowering `maxBlocks` alone does not fix the asymptotics (`O(E × B)`
remains, just with smaller `B`); it is a memory/normalization ceiling, not the
core fix. Fix A is required.

Round 5: The freeze is intentionally kept in dev so an in-place mutation
regression still throws during development and CI.

## Verification Plan

- Unit-test the batcher: a burst of many events yields one (or few)
`store.dispatch` calls and a correct, fully-ordered transcript; control
events (`turn_complete`, `replay_complete`, `prompt.cancelled`,
`state_resync_required`) stay correctly ordered relative to buffered content;
unmount flushes the buffer.
- Unit-test that `reduceDaemonTranscriptEvents` does not freeze `blocks` in
production mode and still freezes in dev.
- Regression: existing `DaemonSessionProvider` and transcript reducer tests stay
green.
- Final: `npm run build`, `npm run typecheck`, `npm run lint`, and targeted
vitest runs for the changed files.
12 changes: 11 additions & 1 deletion packages/sdk-typescript/src/daemon/ui/transcript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,14 @@ export function appendLocalUserTranscriptMessage(
return trimTranscriptState(next);
}

// Freeze retained blocks at the dispatch boundary to catch consumers that
// mutate a COW-shared blocks array in place (see reduceDaemonTranscriptEvents).
// This is a dev/CI safety net; in production it is pure O(blocks) overhead on
// every dispatch and the reducer's own mutation discipline (takeBlocksOwnership)
// does not depend on it, so skip it there. Bundlers statically replace
// `process.env.NODE_ENV`, so this folds to `false` in production builds.
const FREEZE_TRANSCRIPT_BLOCKS = process.env.NODE_ENV !== 'production';

export function reduceDaemonTranscriptEvents(
state: DaemonTranscriptState,
events: readonly DaemonUiEvent[],
Expand All @@ -136,7 +144,9 @@ export function reduceDaemonTranscriptEvents(
// poisoning future snapshots. Internal reducer mutation goes through
// `takeBlocksOwnership` which copies BEFORE mutating, so the frozen
// shared reference is never touched in-place by the next dispatch.
Object.freeze(result.blocks);
if (FREEZE_TRANSCRIPT_BLOCKS) {
Object.freeze(result.blocks);
}
return result;
}

Expand Down
2 changes: 2 additions & 0 deletions packages/web-shell/client/components/SplitView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import type {
import {
SESSION_LIST_PAGE_SIZE,
SESSION_ORGANIZATION_FEATURE,
WEB_SHELL_MAX_TRANSCRIPT_BLOCKS,
} from '../constants/sessions';
import { useOtherWorkspaceSessions } from '../hooks/useOtherWorkspaceSessions';
import { useScopedSessions } from '../hooks/useScopedSessions';
Expand Down Expand Up @@ -478,6 +479,7 @@ export function SplitView({
// collide on one client identity.
clientId={`split-pane:${instanceId}:${sessionId}`}
suppressOwnUserEcho
maxBlocks={WEB_SHELL_MAX_TRANSCRIPT_BLOCKS}
>
<ChatPane
title={titleById.get(sessionId)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
import type { DaemonWorkspaceCapability } from '@qwen-code/sdk/daemon';
import { App, type WebShellProps } from '../App';
import { getTranslator, normalizeLanguage } from '../i18n';
import { WEB_SHELL_MAX_TRANSCRIPT_BLOCKS } from '../constants/sessions';
import { Spinner } from './ui/spinner';
import { WorkspaceUnavailableState } from './WorkspaceUnavailableState';

Expand Down Expand Up @@ -226,6 +227,7 @@ export function WorkspaceSessionProvider({
workspaceCwd={targetWorkspace?.cwd}
clientId={clientId}
suppressOwnUserEcho
maxBlocks={WEB_SHELL_MAX_TRANSCRIPT_BLOCKS}
>
<App
{...webShellProps}
Expand Down
14 changes: 14 additions & 0 deletions packages/web-shell/client/constants/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,17 @@
export const SESSION_LIST_PAGE_SIZE = 1000;
export const SESSION_ORGANIZATION_FEATURE = 'session_organization';
export const WEB_SHELL_SESSION_SOURCE_TYPE = 'default';

/**
* Upper bound on transcript blocks retained in memory per Web Shell session
* (the main chat and each split pane). The daemon stays the authoritative
* full-transcript source; this only caps the client's in-memory window.
*
* The SDK default (200_000) is far beyond what the virtualized message list
* renders, and it inflates both the per-dispatch reducer cost (a full
* block-array copy) and the full-list message normalization. On a large
* transcript that turns a burst of buffered SSE events — e.g. the stream
* catching up when the tab returns from being hidden — into a multi-minute
* main-thread block. Bounding the window keeps very long sessions responsive.
*/
export const WEB_SHELL_MAX_TRANSCRIPT_BLOCKS = 50_000;
79 changes: 79 additions & 0 deletions packages/webui/src/daemon/session/DaemonSessionProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2429,6 +2429,7 @@ describe('DaemonSessionProvider', () => {
await flushPromises();
assistantChunk.resolve();
await flushPromises();
await flushTranscriptDispatch();
});
expect(blocks).toMatchObject([
{ kind: 'user', text: 'cancel me' },
Expand Down Expand Up @@ -2532,6 +2533,7 @@ describe('DaemonSessionProvider', () => {
await flushPromises();
assistantChunk.resolve();
await flushPromises();
await flushTranscriptDispatch();
});
expect(blocks).toMatchObject([
{ kind: 'user', text: 'fail later' },
Expand All @@ -2558,6 +2560,68 @@ describe('DaemonSessionProvider', () => {
]);
});

it('coalesces a burst of streamed chunks into one complete ordered transcript', async () => {
// A burst of buffered SSE events — e.g. the stream catching up after the
// tab was hidden — must drain into a complete, correctly-ordered
// transcript even though transcript dispatch is batched onto a macrotask.
// Regression guard for the batched-dispatch path losing or reordering
// events.
const CHUNK_COUNT = 100;
const burstDrained = createDeferred<void>();
const session = createMockSession({
events: async function* burstEvents(opts: { signal?: AbortSignal } = {}) {
for (let i = 0; i < CHUNK_COUNT; i += 1) {
yield {
id: i + 1,
v: 1,
type: 'session_update',
data: {
update: {
sessionUpdate: 'agent_message_chunk',
content: { type: 'text', text: `chunk-${i} ` },
},
},
};
}
burstDrained.resolve();
// Stay alive so the consumer loop does not end (which would flush
// synchronously) — exercise the batched macrotask flush instead.
await new Promise<void>((resolve) => {
if (opts.signal?.aborted) {
resolve();
return;
}
opts.signal?.addEventListener('abort', () => resolve(), {
once: true,
});
});
},
});
sdkMocks.sessions.push(session);
let blocks: readonly DaemonTranscriptBlock[] = [];
function Harness() {
blocks = useDaemonTranscriptBlocks();
return null;
}

await renderWithProvider(<Harness />, { autoConnect: true });
await act(async () => {
await burstDrained.promise;
await flushPromises();
await flushTranscriptDispatch();
});

const assistant = blocks.find((block) => block.kind === 'assistant');
const text = (assistant as { text?: string } | undefined)?.text ?? '';
// No chunk lost, and all in order.
let lastIndex = -1;
for (let i = 0; i < CHUNK_COUNT; i += 1) {
const idx = text.indexOf(`chunk-${i} `);
expect(idx).toBeGreaterThan(lastIndex);
lastIndex = idx;
}
});

it('does not insert abort errors from shell commands into the transcript', async () => {
const session = createMockSession({
events: createIdleEvents(),
Expand Down Expand Up @@ -4508,6 +4572,10 @@ describe('DaemonSessionProvider', () => {
await renderWithProvider(<Harness />, { autoConnect: true });
await act(async () => {
await flushPromises();
// Batched transcript dispatch rides a setTimeout; under fake timers
// advance it so the passive assistant chunk lands before asserting.
await vi.advanceTimersByTimeAsync(0);
await flushPromises();
});
expect(blocks).toMatchObject([
{ kind: 'assistant', text: 'passive', streaming: true },
Expand Down Expand Up @@ -7472,6 +7540,7 @@ describe('DaemonSessionProvider', () => {
await act(async () => {
await reattachDelivered.promise;
await flushPromises();
await flushTranscriptDispatch();
});
expect(blocks).not.toEqual(
expect.arrayContaining([
Expand Down Expand Up @@ -8446,6 +8515,16 @@ async function flushPromises(): Promise<void> {
await Promise.resolve();
}

// Transcript dispatch is batched onto a macrotask (setTimeout 0) so a burst of
// SSE events coalesces into one reducer pass. Stay-alive mock generators never
// end the consumer loop (which would flush synchronously), so tests that assert
// transcript state mid-stream drain the batched dispatch here.
async function flushTranscriptDispatch(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 0));
await Promise.resolve();
await Promise.resolve();
}

async function wait(ms: number): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, ms));
}
Expand Down
Loading
Loading