From d995ce3bbdd4cbe4301b99be44b5b29b80a74f44 Mon Sep 17 00:00:00 2001 From: Felix Weinberger Date: Thu, 27 Nov 2025 21:57:17 +0000 Subject: [PATCH] Fix ReadableStream controller double-close crash Guard against calling controller.close() when the stream has already been closed by an external cancellation. This can happen when the SDK cancels the stream before the underlying Node stream emits its 'end' event. - Add `closed` flag to track controller state - Guard all controller operations with closed check - Add `cancel()` callback to handle external cancellation - Properly destroy the Node stream on cancellation --- server/src/index.ts | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/server/src/index.ts b/server/src/index.ts index 88954ebc5..687e8f74e 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -241,18 +241,31 @@ const authMiddleware = ( * This is necessary for the EventSource polyfill which expects web streams */ const createWebReadableStream = (nodeStream: any): ReadableStream => { + let closed = false; return new ReadableStream({ start(controller) { nodeStream.on("data", (chunk: any) => { - controller.enqueue(chunk); + if (!closed) { + controller.enqueue(chunk); + } }); nodeStream.on("end", () => { - controller.close(); + if (!closed) { + closed = true; + controller.close(); + } }); nodeStream.on("error", (err: any) => { - controller.error(err); + if (!closed) { + closed = true; + controller.error(err); + } }); }, + cancel() { + closed = true; + nodeStream.destroy(); + }, }); };