// A tab multiplexes its live follows over one WebSocket. Older daemons fall // back to SSE; each transport resumes after the last fully handled batch. import type { components } from './api.gen'; type Schema = components['schemas']; type SessionEvent = | Extract< Schema['SessionEvent'], { type: Exclude } > | Pick; export type CollectionEvent = Schema['CollectionBatch']['events'][number]; type Snapshot = Partial< Pick< Schema['ResetBatch']['snapshot'], | 'status' | 'usage' | 'history' | 'active_output' | 'current_progress' | 'shell_commands' | 'side_question' > >; // A reset supplies the starting snapshot for any following events. export type SessionBatch = Pick< Schema['SessionBatch'], 'generation' | 'cursor' > & ( | { kind: 'reset'; snapshot: Snapshot; events: SessionEvent[] } | { kind: 'replay'; events: SessionEvent[] } ); const RETRY = { first: 500, most: 5000 }; type FollowState = { key?: string; background: boolean; onState: (connected: boolean) => void; delay: number; retry?: ReturnType; fallback?: () => void; }; type Subscription = | { kind: 'session'; sessionId: string; onBatch: (batch: SessionBatch) => void; after: Record; } | { kind: 'list'; onEvents: (events: CollectionEvent[]) => void }; type Follow = FollowState & Subscription; function record(value: unknown): value is Record { return !!value && typeof value === 'object' && !Array.isArray(value); } function counter(value: unknown): value is number { return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0; } function strings(value: unknown): value is string[] { return ( Array.isArray(value) && value.every((item) => typeof item === 'string') ); } function optional(value: unknown, valid: (value: unknown) => boolean) { return value == null || valid(value); } function string(value: unknown): value is string { return typeof value === 'string'; } function number(value: unknown) { return typeof value === 'number' && Number.isFinite(value); } function compaction(value: unknown) { return ( record(value) && string(value.strategy) && string(value.stage) && counter(value.completed) && optional(value.total, counter) && optional(value.active, counter) && string(value.started_at) ); } function status(value: unknown) { return ( record(value) && optional(value.phase, string) && optional(value.run_id, string) && optional(value.interrupt_requested, boolean) && optional( value.blocking_reason, (reason) => record(reason) && string(reason.code) && string(reason.detail), ) && optional(value.compaction, compaction) ); } function progress(value: unknown) { return ( record(value) && typeof value.call_id === 'string' && (value.tool_call_id == null || typeof value.tool_call_id === 'string') && typeof value.name === 'string' && (value.title == null || typeof value.title === 'string') && (value.preview == null || (record(value.preview) && typeof value.preview.text === 'string')) ); } function usage(value: unknown) { if (!record(value)) return false; const counters = [ value.prompt_tokens, value.cached_prompt_tokens, value.cache_write_tokens, value.completion_tokens, value.total_tokens, value.context_window_tokens, value.cache_ttl_seconds, value.cache_miss_tokens, value.cache_drift_tokens, ]; return ( counters.every((item) => optional(item, counter)) && optional(value.model, string) && optional(value.observed_at, string) && optional(value.elapsed_ms, number) && optional(value.tokens_per_second, number) && optional( value.spent, (cost) => record(cost) && number(cost.usd) && string(cost.basis), ) && optional(value.size, record) && Array.isArray(value.cache_fade) && value.cache_fade.every( (step) => record(step) && string(step.at) && optional(step.cached_tokens, counter), ) ); } function snapshotOf(value: unknown): Snapshot { // Older SSE peers omitted snapshot sections that had no state to restore. if (value == null) return {}; if ( !record(value) || !optional(value.status, status) || !optional(value.usage, usage) || !optional( value.history, (history) => record(history) && optional(history.high_water, counter), ) || !optional( value.active_output, (outputs) => Array.isArray(outputs) && outputs.every( (output) => record(output) && string(output.kind) && string(output.message_id) && optional(output.text, string), ), ) || !optional( value.current_progress, (items) => Array.isArray(items) && items.every(progress), ) || !optional(value.shell_commands, Array.isArray) ) throw new Error('invalid stream snapshot'); return value as Snapshot; } function activity(value: unknown) { return ( record(value) && optional(value.observed_at, string) && optional( value.lines, (lines) => Array.isArray(lines) && lines.every( (line) => record(line) && string(line.kind) && string(line.text), ), ) && optional( value.latest_answer, (answer) => record(answer) && string(answer.message_id), ) && optional( value.latest_input, (input) => record(input) && string(input.input_id) && string(input.source), ) && optional( value.current_request, (request) => record(request) && string(request.input_id) && string(request.text), ) && optional(value.latest_progress, string) ); } type Payload = Record; type PayloadCheck = (data: Payload) => boolean; function boolean(value: unknown) { return typeof value === 'boolean'; } function delta(data: Payload) { return string(data.message_id) && string(data.text); } const sessionPayloads = { status, usage, text: delta, thinking: delta, error: (data) => optional(data.run_id, string) && string(data.message), invalidate: (data) => string(data.kind) && string(data.url), // The consumers already validate the receipt and the exchange. shell_command: (data) => 'shell_command' in data, side_question: (data) => 'side_question' in data, tool_progress: (data) => optional(data.progress, progress), tool: (data) => optional(data.progress_call_id, string), committed: (data) => optional(data.high_water, counter) && optional(data.replaces_all_live, boolean) && optional(data.replaces_live_ids, strings), note: (data) => string(data.entry_id) && string(data.origin) && string(data.text), // The transcript uses a message as a signal to reread durable history. message: (data) => record(data.entry), } satisfies Partial>; const collectionPayloads: Record = { ready: () => true, overflow: () => true, reset: (data) => optional(data.reason, string), activity: (data) => string(data.session_id) && optional(data.status, status) && optional(data.activity, activity), mail: (data) => string(data.mail_id) && string(data.receiver_session_id) && optional(data.sender_session_id, string) && boolean(data.notifies), invalidate: (data) => optional(data.urls, strings) && optional(data.session_ids, strings) && optional(data.scope_dirty, boolean), }; // Check what consumers read. A future event type may advance the cursor // even when this browser has no consumer for its payload. function decodeEvents( values: unknown[], checks: Record, sequenced = false, ): Event[] { const events: Event[] = []; for (const value of values) { if (!record(value) || !string(value.type)) throw new Error('invalid stream event'); const { type, data } = value; if (sequenced && (type === 'reset' || type === 'failure')) throw new Error('misplaced session batch event'); if (!Object.hasOwn(checks, type)) continue; if ( !record(data) || !checks[type](data) || (sequenced && !counter(value.sequence)) ) throw new Error(`invalid stream event: ${type}`); events.push(value as Event); } return events; } function sessionBatchOf( value: Record, events: unknown[], ): SessionBatch { const { generation, cursor } = value; if (typeof generation !== 'string' || !generation || !counter(cursor)) throw new Error('invalid session batch cursor'); const first: unknown = events[0]; if (record(first) && first.type === 'reset') { if ( !optional( first.data, (data) => record(data) && optional(data.reason, string), ) ) throw new Error('invalid stream reset'); return { kind: 'reset', generation, cursor, snapshot: snapshotOf(value.snapshot), events: decodeEvents( events.slice(1), sessionPayloads, true, ), }; } if (value.snapshot !== undefined) throw new Error('snapshot without reset'); return { kind: 'replay', generation, cursor, events: decodeEvents(events, sessionPayloads, true), }; } let nextKey = 0; let socket: WebSocket | null = null; let socketDelay = RETRY.first; let reconnect: ReturnType | undefined; let websocketUnavailable = false; const follows = new Set(); const attachments = new Map(); function forgetAttachment(follow: Follow) { if (follow.key) attachments.delete(follow.key); follow.key = undefined; } function disconnected(follow: Follow) { clearTimeout(follow.retry); follow.retry = undefined; forgetAttachment(follow); follow.onState(false); } function closeSocket() { clearTimeout(reconnect); reconnect = undefined; const previous = socket; socket = null; previous?.close(); for (const follow of follows.values()) disconnected(follow); } function active(follow: Follow) { return !document.hidden || follow.background; } function hasActive() { return [...follows.values()].some(active); } document.addEventListener('visibilitychange', () => { if (!hasActive()) closeSocket(); else { for (const follow of follows.values()) { if (!active(follow) && follow.key) { if (socket?.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ key: follow.key, type: 'stop' })); disconnected(follow); } } ensureSocket(); for (const follow of follows.values()) if (active(follow)) sendFollow(follow); } }); function startFallback(follow: Follow) { if (follow.fallback) return; follow.fallback = sseSubscribe(follow); } function ensureSocket() { if (!hasActive()) return; if (websocketUnavailable) { for (const follow of follows.values()) if (active(follow)) startFallback(follow); return; } if (socket) return; clearTimeout(reconnect); reconnect = undefined; const scheme = location.protocol === 'https:' ? 'wss:' : 'ws:'; const ws = new WebSocket(`${scheme}//${location.host}/api/events`); socket = ws; let opened = false; let lastMessage = Date.now(); let heartbeat: ReturnType | undefined; const timeout = setTimeout(() => ws.close(), 5000); ws.onopen = () => { clearTimeout(timeout); if (socket !== ws || !hasActive()) { ws.close(); return; } opened = true; socketDelay = RETRY.first; heartbeat = setInterval(() => { if (Date.now() - lastMessage > 45000) ws.close(); else if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'ping' })); }, 15000); for (const follow of follows.values()) sendFollow(follow); }; ws.onmessage = (event) => { if (socket !== ws) return; lastMessage = Date.now(); try { receive(String(event.data)); } catch { ws.close(); } }; ws.onerror = () => ws.close(); ws.onclose = () => { clearTimeout(timeout); clearInterval(heartbeat); if (socket !== ws) return; socket = null; for (const follow of follows.values()) disconnected(follow); if (!opened) { websocketUnavailable = true; ensureSocket(); } else if (hasActive()) { const wait = socketDelay; socketDelay = Math.min(RETRY.most, socketDelay * 2); reconnect = setTimeout(ensureSocket, wait); } }; } function sendFollow(follow: Follow) { if ( !active(follow) || follow.key || !socket || socket.readyState !== WebSocket.OPEN ) return; clearTimeout(follow.retry); follow.retry = undefined; const key = `tab-${++nextKey}`; const value = follow.kind === 'list' ? { key, type: 'sessions', scope: 'all' } : { key, type: 'session', session_id: follow.sessionId, tail: 0, ...follow.after, }; socket.send(JSON.stringify(value)); follow.key = key; attachments.set(key, follow); } function consume(follow: Follow, value: unknown) { if (!follows.has(follow) || !active(follow)) return false; if (!record(value) || !Array.isArray(value.events)) throw new Error('invalid stream batch'); const first: unknown = value.events[0]; if (record(first) && first.type === 'failure') return false; if (follow.kind === 'session') { const batch = sessionBatchOf(value, value.events); follow.onBatch(batch); follow.after = { after_generation: batch.generation, after_seq: String(batch.cursor), }; } else { follow.onEvents( decodeEvents(value.events, collectionPayloads), ); } follow.delay = RETRY.first; if (follows.has(follow)) follow.onState(true); return true; } function receive(raw: string) { let value: unknown; try { value = JSON.parse(raw); } catch { return; } if (!record(value) || typeof value.key !== 'string') return; const follow = attachments.get(value.key); if (!follow) return; if ('batch' in value) { consume(follow, value.batch); } else if (value.end || value.failure) { disconnected(follow); if (!active(follow)) return; const wait = follow.delay; follow.delay = Math.min(RETRY.most, follow.delay * 2); follow.retry = setTimeout(() => { follow.retry = undefined; if (!follows.has(follow) || !active(follow)) return; ensureSocket(); sendFollow(follow); }, wait); } } function subscribe( subscription: Subscription, onState: (connected: boolean) => void, background = false, ): () => void { const follow: Follow = { ...subscription, background, onState, delay: RETRY.first, }; follows.add(follow); ensureSocket(); // onopen handles pending follows; an already-open socket needs this one now. sendFollow(follow); return () => { follows.delete(follow); const key = follow.key; forgetAttachment(follow); clearTimeout(follow.retry); follow.fallback?.(); if (key && socket?.readyState === WebSocket.OPEN) { socket.send(JSON.stringify({ key, type: 'stop' })); } if (!hasActive()) closeSocket(); }; } export function follow( sessionId: string, onBatch: (batch: SessionBatch) => void, onState: (connected: boolean) => void, ): () => void { return subscribe({ kind: 'session', sessionId, onBatch, after: {} }, onState); } export function followSessions( onEvents: (events: CollectionEvent[]) => void, onState: (connected: boolean) => void, background = false, ): () => void { return subscribe({ kind: 'list', onEvents }, onState, background); } /** * Streams a tab holds at once. A browser keeps at most six connections to * the daemon, shared by every tab, and a stream holds one for as long as it * runs; past this many, a stream waits for one to end, and what it would * have carried is polled meanwhile (a chat reads its history every few * seconds while it is not streaming). Half are left for ordinary reads. */ const MOST_STREAMS = 3; let streams = 0; const queued: (() => void)[] = []; /** Waits for a stream's turn to connect; false when it was stopped first. */ function take(signal: AbortSignal): Promise { if (streams < MOST_STREAMS) { streams += 1; return Promise.resolve(true); } return new Promise((resolve) => { const turn = () => { signal.removeEventListener('abort', stop); resolve(true); }; const stop = () => { queued.splice(queued.indexOf(turn), 1); resolve(false); }; queued.push(turn); signal.addEventListener('abort', stop, { once: true }); }); } /** Hands a stream's connection to the next one waiting. */ function release() { const next = queued.shift(); if (next) next(); else streams -= 1; } /** Reads a follow over SSE until stopped, resuming after each handled batch. */ function sseSubscribe(follow: Follow): () => void { const controller = new AbortController(); const path = follow.kind === 'list' ? '/sessions?scope=all' : `/sessions/${follow.sessionId}/events?tail=0`; const [base, given] = path.split('?'); let delay = RETRY.first; const run = async () => { while (!controller.signal.aborted) { if (!active(follow)) { await shown(controller.signal); continue; } const pause = new AbortController(); const signal = AbortSignal.any([controller.signal, pause.signal]); const hide = () => { if (!active(follow)) pause.abort(); }; document.addEventListener('visibilitychange', hide); let acquired = false; try { acquired = await take(signal); if (!acquired || signal.aborted) continue; const query = new URLSearchParams(given); if (follow.kind === 'session') { for (const [key, value] of Object.entries(follow.after)) query.set(key, value); } const response = await fetch(`/api${base}?${query}`, { headers: { accept: 'text/event-stream' }, signal, }); if (signal.aborted) continue; if (!response.ok || !response.body) throw new Error(`stream answered ${response.status}`); for await (const data of frames(response.body)) { if (signal.aborted || !consume(follow, JSON.parse(data))) break; delay = RETRY.first; } } catch { // A failed connection or batch is retried from the last consumed cursor. } finally { document.removeEventListener('visibilitychange', hide); pause.abort(); if (acquired) release(); } if (controller.signal.aborted) return; follow.onState(false); if (!active(follow)) continue; await new Promise((resolve) => setTimeout(resolve, delay)); delay = Math.min(RETRY.most, delay * 2); } }; run(); return () => controller.abort(); } /** Resolves once the tab shows, or the stream is stopped. */ function shown(signal: AbortSignal): Promise { return new Promise((resolve) => { const done = () => { if (document.hidden && !signal.aborted) return; document.removeEventListener('visibilitychange', done); signal.removeEventListener('abort', done); resolve(); }; document.addEventListener('visibilitychange', done); signal.addEventListener('abort', done, { once: true }); }); } /** The data of each server-sent event in a body: lines after `data:`, joined, up to a blank line. */ async function* frames( body: ReadableStream, ): AsyncGenerator { const reader = body.getReader(); const decoder = new TextDecoder(); let pending = ''; let data: string[] = []; for (;;) { const { value, done } = await reader.read(); if (done) return; pending += decoder.decode(value, { stream: true }); let end: number; while ((end = pending.indexOf('\n')) >= 0) { const line = pending.slice(0, end).replace(/\r$/, ''); pending = pending.slice(end + 1); if (line === '') { if (data.length) yield data.join('\n'); data = []; } else if (line.startsWith('data:')) data.push(line.slice(line.startsWith('data: ') ? 6 : 5)); } } }