A lightweight design agent built with libfx. Describe a page and an agent writes it as one HTML file.
TypeScript
Drop journal read failures after the event stream has closed
Pranit788d13830e05
diff --git a/lib/event-stream.ts b/lib/event-stream.tsindex de88b56..b0eca96 100644--- a/lib/event-stream.ts+++ b/lib/event-stream.ts@@ -41,6 +41,11 @@ export function createSessionEventStream(sessionId: string, options: EventStreamreturn new ReadableStream<string>({start(controller) {+ // Every write goes through here, so nothing is written once the stream has+ // stopped: a closed or cancelled controller throws on enqueue.+ const send = (chunk: string) => {+ if (!stopped) controller.enqueue(chunk)+ }const close = () => {if (stopped) returnstopTimers()@@ -55,13 +60,25 @@ export function createSessionEventStream(sessionId: string, options: EventStream}if (item.type === 'turn_start') running = trueif (item.type === 'done' || item.type === 'error') running = false- controller.enqueue(`id: ${item.seq ?? ''}\ndata: ${JSON.stringify(item)}\n\n`)+ send(`id: ${item.seq ?? ''}\ndata: ${JSON.stringify(item)}\n\n`)if (options.closeWhen?.(item)) {close()return true}return false}+ // A failed journal read ends the stream with an error line, unless the stream+ // already ended while the read was pending: the client left, or a terminal+ // item closed it.+ const fail = (error: unknown) => {+ if (stopped) return+ send(`data: ${JSON.stringify({ type: 'error', text: `event journal unavailable: ${String((error as Error)?.message ?? error)}` })}\n\n`)+ close()+ }+ // Every poll starts here, so no poll's failure goes unhandled.+ const pollSoon = () => {+ void poll().catch(fail)+ }const poll = async () => {if (stopped) returnif (polling) {@@ -83,22 +100,16 @@ export function createSessionEventStream(sessionId: string, options: EventStreamdeliver(draft.item)}pollDelayMs = items.length > 0 || draft ? 100 : Math.min(running ? 150 : options.maxIdleMs ?? 1000, Math.ceil(pollDelayMs * 1.5))- } catch (error) {- controller.enqueue(- `data: ${JSON.stringify({ type: 'error', text: `event journal unavailable: ${String((error as Error)?.message ?? error)}` })}\n\n`,- )- close()- return} finally {polling = false}if (stopped) returnif (pollAgain) {pollAgain = false- void poll()+ pollSoon()return}- pollTimer = setTimeout(poll, pollDelayMs)+ pollTimer = setTimeout(pollSoon, pollDelayMs)}// Same-process commits arrive here as they land. The next item in sequence is@@ -110,21 +121,19 @@ export function createSessionEventStream(sessionId: string, options: EventStreamdeliver(item)pollDelayMs = 100} else {- void poll()+ pollSoon()}}localEvents.on(sessionId, onLocal)// A local write wakes the shared reader; bytes always come from the store,// with its generation and offset, just as they do on another instance.onLive = (item) => {- if (!stopped && item.type === 'design_draft') void poll()+ if (!stopped && item.type === 'design_draft') pollSoon()}localEvents.on(`${sessionId}:live`, onLive)- void poll()- heartbeat = setInterval(() => {- if (!stopped) controller.enqueue(': ping\n\n')- }, 15_000)+ pollSoon()+ heartbeat = setInterval(() => send(': ping\n\n'), 15_000)if (options.wake) {options.wake()wakeTimer = setInterval(options.wake, 5_000)diff --git a/tests/event-stream.test.mjs b/tests/event-stream.test.mjsindex cbbf17f..0503d01 100644--- a/tests/event-stream.test.mjs+++ b/tests/event-stream.test.mjs@@ -4,11 +4,11 @@ import { registerHooks } from 'node:module'import test from 'node:test'// The stream's only boundaries are the Redis journal and the draft store.-const fake = globalThis.__fx0EventStream = { localEvents: new EventEmitter(), reads: 0 }+const fake = globalThis.__fx0EventStream = { localEvents: new EventEmitter(), reads: 0, read: null }const dataUrl = (source) => `data:text/javascript,${encodeURIComponent(source)}`const fakes = {'./journal': dataUrl(`export const localEvents = globalThis.__fx0EventStream.localEvents-export const readEvents = async () => { globalThis.__fx0EventStream.reads += 1; return [] }`),+export const readEvents = async () => { const fake = globalThis.__fx0EventStream; fake.reads += 1; return fake.read ? fake.read() : [] }`),'./draft-store': dataUrl('export const readDraft = async () => null'),}registerHooks({ resolve(specifier, context, next) {@@ -31,3 +31,56 @@ test('a stream with a lifetime ends cleanly on its own and stops reading and lisawait new Promise((resolve) => setTimeout(resolve, 400))assert.equal(fake.reads, reads)})++// A journal read the test fails by hand, and the rejections nothing handled.+function pendingRead(t) {+ let fail+ fake.read = () => new Promise((_resolve, reject) => { fail = reject })+ const unhandled = []+ const onUnhandled = (reason) => unhandled.push(reason)+ process.on('unhandledRejection', onUnhandled)+ t.after(() => {+ fake.read = null+ process.off('unhandledRejection', onUnhandled)+ })+ return {+ unhandled,+ async fail() {+ fail(new Error('redis down'))+ await new Promise((resolve) => setTimeout(resolve, 50))+ },+ }+}++test('a read that fails after the client left is dropped, not left unhandled', async (t) => {+ const read = pendingRead(t)+ const reader = createSessionEventStream('chat-left').getReader()+ assert.equal(fake.localEvents.listenerCount('chat-left'), 1)+ await reader.cancel()+ await read.fail()+ assert.deepEqual(read.unhandled, [])+ const reads = fake.reads+ await new Promise((resolve) => setTimeout(resolve, 300))+ assert.equal(fake.reads, reads, 'a stopped stream reads no more')+})++test('a read that fails after a terminal item closed the stream is dropped, not left unhandled', async (t) => {+ const read = pendingRead(t)+ const reader = createSessionEventStream('chat-ended', { closeWhen: (item) => item.type === 'done' }).getReader()+ fake.localEvents.emit('chat-ended', { type: 'done', seq: 1, turnId: 1 })+ const { value } = await reader.read()+ assert.match(value, /"type":"done"/)+ assert.equal((await reader.read()).done, true)+ await read.fail()+ assert.deepEqual(read.unhandled, [])+})++test('a read that fails while the stream is open still ends it with an error line', async (t) => {+ const read = pendingRead(t)+ const reader = createSessionEventStream('chat-open').getReader()+ await read.fail()+ const { value } = await reader.read()+ assert.equal(value, `data: ${JSON.stringify({ type: 'error', text: 'event journal unavailable: redis down' })}\n\n`)+ assert.equal((await reader.read()).done, true)+ assert.deepEqual(read.unhandled, [])+})