Today I learned
Why does my ReadableStream hang when pull() doesn't enqueue anything?
A ReadableStream that re-emits another stream (SSE from an LLM API, say) froze halfway: the reader waited forever, no error. The cause: when pull() resolves without calling controller.enqueue(), the stream does not call pull() again. Only an enqueue or a new read() while pull() is running schedules the next call, so a chunk of events you skip leaves the reader hanging.
Keep reading inside pull() until you have enqueued something, closed or errored:
new ReadableStream<Uint8Array>({
async pull(controller) {
while (true) {
const { done, value } = await upstream.read()
if (done) return controller.close()
const text = extractText(value) // may be '' for bookkeeping events
if (text) {
controller.enqueue(encoder.encode(text))
return // hand back now so deltas flush as they arrive
}
// nothing enqueued: loop, don't return
}
},
cancel: reason => upstream.cancel(reason),
})
Hit this while streaming OpenAI Responses events into a plain-text stream for a rewrite tool: events like response.created carry no text, and a pull that returned on them stalled the page. The same loop is also the place to controller.error() on a response.incomplete event, so a cut-off answer rejects the reader instead of looking finished.