// Exercise the browser transport with explicitly delivered frames. Daemon E2E // tests cannot hold a stop acknowledgement across a visibility change. import assert from 'node:assert/strict'; import { readFile } from 'node:fs/promises'; import { stripTypeScriptTypes } from 'node:module'; import test from 'node:test'; const source = stripTypeScriptTypes( await readFile(new URL('../src/lib/stream.ts', import.meta.url), 'utf8'), ); const transport = `data:text/javascript;base64,${Buffer.from(source).toString('base64')}`; async function browser(t, name) { const tab = Object.assign(new EventTarget(), { hidden: false }); const sockets = []; class Socket { static OPEN = 1; readyState = 0; sent = []; constructor() { sockets.push(this); } open() { this.readyState = Socket.OPEN; this.onopen(); } send(raw) { this.sent.push(JSON.parse(raw)); } receive(value) { this.onmessage({ data: JSON.stringify(value) }); } close() { this.readyState = 3; this.onclose(); } } globalThis.document = tab; globalThis.location = new URL('http://localhost'); t.mock.property(globalThis, 'WebSocket', Socket); return { tab, sockets, ...(await import(transport + '#' + name)) }; } test('a resumed follow ignores buffered frames from its stopped attachment', async (t) => { const { tab, sockets, follow, followSessions } = await browser(t, 'resume'); const received = []; const states = []; const stopList = followSessions( () => {}, () => {}, true, ); const stopChat = follow( 'chat', (batch) => received.push(batch.cursor), (connected) => states.push(connected), ); t.after(() => { stopChat(); stopList(); }); const [socket] = sockets; socket.open(); const original = socket.sent[1].key; const batch = (key, cursor) => socket.receive({ key, batch: { events: [], generation: 'actor', cursor } }); batch(original, 4); tab.hidden = true; tab.dispatchEvent(new Event('visibilitychange')); assert.deepEqual(socket.sent.at(-1), { key: original, type: 'stop' }); tab.hidden = false; tab.dispatchEvent(new Event('visibilitychange')); const resumed = socket.sent.at(-1); assert.equal(resumed.after_generation, 'actor'); assert.equal(resumed.after_seq, '4'); batch(original, 5); socket.receive({ key: original, end: true }); batch(resumed.key, 6); assert.deepEqual(received, [4, 6]); assert.deepEqual(states, [true, false, true]); }); test('a terminal failure batch leaves the last delivered resume cursor intact', async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const { sockets, follow } = await browser(t, 'failure'); const received = []; const stop = follow( 'chat', (batch) => received.push(batch.cursor), () => {}, ); t.after(stop); const [socket] = sockets; socket.open(); const { key } = socket.sent[0]; socket.receive({ key, batch: { events: [], generation: 'actor', cursor: 4 }, }); socket.receive({ key, batch: { events: [{ type: 'failure', data: { code: 'unavailable' } }], generation: 'actor', cursor: 9, }, }); socket.receive({ key, end: true }); t.mock.timers.tick(500); assert.deepEqual(received, [4]); assert.equal(socket.sent.at(-1).after_seq, '4'); }); test('a queued SSE chat leaves the connection slot free while hidden', async (t) => { const { tab, sockets, follow, followSessions } = await browser(t, 'sse'); const requests = []; t.mock.method(globalThis, 'fetch', (url, { signal }) => { requests.push(url); return new Promise((resolve, reject) => { signal.addEventListener('abort', () => reject(signal.reason), { once: true, }); }); }); const stops = Array.from({ length: 3 }, () => followSessions( () => {}, () => {}, true, ), ); stops.push( follow( 'chat', () => {}, () => {}, ), ); const stopBackground = followSessions( () => {}, () => {}, true, ); t.after(() => { stops.forEach((stop) => stop()); stopBackground(); }); const settle = () => new Promise(setImmediate); sockets[0].close(); // An upgrade failure selects SSE fallback. await settle(); assert.deepEqual(requests, Array(3).fill('/api/sessions?scope=all')); tab.hidden = true; tab.dispatchEvent(new Event('visibilitychange')); stops[0](); await settle(); assert.deepEqual(requests, Array(4).fill('/api/sessions?scope=all')); }); test('a reset supplies a snapshot before its replay, including new event types', async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const { sockets, follow, followSessions } = await browser(t, 'reset'); const received = []; const listed = []; const stopChat = follow( 'chat', (batch) => received.push(batch), () => {}, ); const stopList = followSessions( (events) => listed.push(events), () => {}, ); t.after(() => { stopChat(); stopList(); }); const [socket] = sockets; socket.open(); const [{ key: chat }, { key: list }] = socket.sent; const snapshot = { status: { phase: 'generating' }, usage: { observed_at: null, cache_fade: [] }, history: { high_water: 6 }, active_output: [], current_progress: [], shell_commands: [], }; const text = { type: 'text', sequence: 8, data: { run_id: 'run', message_id: 'reply', text: 'hello' }, }; socket.receive({ key: chat, batch: { generation: 'actor', cursor: 9, snapshot, events: [ { type: 'reset', data: { reason: 'initial' } }, text, { type: 'future_event', sequence: 9, data: null }, ], }, }); const invalidate = { type: 'invalidate', data: { urls: ['/settings'], session_ids: [], scope_dirty: true }, }; socket.receive({ key: list, batch: { events: [invalidate, { type: 'future_event', data: [] }] }, }); assert.deepEqual(received, [ { kind: 'reset', generation: 'actor', cursor: 9, snapshot, events: [text] }, ]); assert.deepEqual(listed, [[invalidate]]); socket.receive({ key: chat, end: true }); t.mock.timers.tick(500); assert.equal(socket.sent.at(-1).after_seq, '9'); }); test('a malformed known event rejects its whole batch before advancing the cursor', async (t) => { t.mock.timers.enable({ apis: ['setTimeout'] }); const { sockets, follow } = await browser(t, 'malformed'); const received = []; const stop = follow( 'chat', (batch) => received.push(batch.cursor), () => {}, ); t.after(stop); const [socket] = sockets; socket.open(); const { key } = socket.sent[0]; socket.receive({ key, batch: { events: [], generation: 'actor', cursor: 4 }, }); socket.receive({ key, batch: { generation: 'actor', cursor: 6, events: [ { type: 'text', sequence: 5, data: { run_id: 'run', message_id: 'reply', text: 'hello' }, }, { type: 'committed', sequence: 6, data: { high_water: 'bad' } }, ], }, }); assert.deepEqual(received, [4]); t.mock.timers.tick(500); sockets[1].open(); assert.equal(sockets[1].sent[0].after_seq, '4'); }); test( 'SSE resets accept omitted snapshot sections and nullable event data', { timeout: 10000 }, async (t) => { const { sockets, follow } = await browser(t, 'older-sse'); const progress = { type: 'tool_progress', sequence: 1, data: { progress: null }, }; const batch = { generation: 'actor', cursor: 1, snapshot: { status: { phase: 'idle' } }, events: [{ type: 'reset', data: { reason: 'initial' } }, progress], }; t.mock.method(globalThis, 'fetch', (_, { signal }) => Promise.resolve( new Response( new ReadableStream({ start(stream) { stream.enqueue( new TextEncoder().encode( 'data: ' + JSON.stringify(batch) + '\n\n', ), ); signal.addEventListener('abort', () => stream.close(), { once: true, }); }, }), ), ), ); const delivered = new Promise((resolve) => { const stop = follow('chat', resolve, () => {}); t.after(stop); sockets[0].close(); }); assert.deepEqual(await delivered, { kind: 'reset', generation: 'actor', cursor: 1, snapshot: batch.snapshot, events: [progress], }); }, );