Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(electron): server-sent events not working
Elian Dorana4893eca79f9
diff --git a/apps/server/src/routes/electron.spec.ts b/apps/server/src/routes/electron.spec.tsindex c348a474b6..065c29e0ab 100644--- a/apps/server/src/routes/electron.spec.ts+++ b/apps/server/src/routes/electron.spec.ts@@ -82,6 +82,49 @@ describe("electron protocol dispatcher", () => {expect(markedOnHandler).toBe(true);});+ // SSE / streaming endpoints (e.g. LLM chat) commit headers up front with+ // `res.flushHeaders()` and then write chunks over time. The bridge must+ // (a) not crash on flushHeaders — Express rewires `res.__proto__` to the+ // real ServerResponse, whose internal `outputData` was never initialised+ // on the mock — and (b) deliver subsequent `res.write` chunks to the+ // renderer in real time instead of buffering until `res.end`.+ it("streams chunks to the renderer as soon as flushHeaders is called", async () => {+ const app = express();+ let resolveWriteGate: (() => void) | undefined;+ const writeGate = new Promise<void>((r) => { resolveWriteGate = r; });++ app.get("/stream", async (_req, res) => {+ res.setHeader("Content-Type", "text/event-stream");+ res.flushHeaders();+ res.write("first\n");+ // Hold the second chunk until the test confirms the first was+ // already readable from the Response body — proving real-time+ // delivery instead of buffer-then-flush.+ await writeGate;+ res.write("second\n");+ res.end();+ });++ const dispatched = dispatch(app, new Request("trilium-app://app/stream"));+ const response = await dispatched;+ expect(response.status).toBe(200);+ expect(response.headers.get("content-type")).toBe("text/event-stream");++ const reader = response.body!.getReader();+ const decoder = new TextDecoder();+ const first = await reader.read();+ expect(decoder.decode(first.value)).toBe("first\n");++ resolveWriteGate!();+ let rest = "";+ while (true) {+ const { done, value } = await reader.read();+ if (done) break;+ rest += decoder.decode(value);+ }+ expect(rest).toBe("second\n");+ });+it("does NOT tag plain Express requests with the internal-electron marker", () => {// Anything that didn't come through `dispatch()` — i.e. a real HTTP// request to the TCP listener, or an arbitrary attacker-controlleddiff --git a/apps/server/src/routes/electron.ts b/apps/server/src/routes/electron.tsindex 9f40e54c78..beb568449c 100644--- a/apps/server/src/routes/electron.ts+++ b/apps/server/src/routes/electron.ts@@ -62,7 +62,93 @@ export async function dispatch(app: Application, request: Request): Promise<RespeventEmitter: EventEmitter});+ // Streaming bridge. When the handler calls `res.flushHeaders()` — the+ // standard signal for "send headers now, body coming later" used by SSE+ // endpoints like the LLM chat stream — switch into streaming mode:+ // resolve the Fetch `Response` immediately with a `ReadableStream` body,+ // and forward subsequent `res.write(chunk)` calls into the stream+ // controller so the renderer receives chunks in real time instead of+ // waiting for the whole response to buffer.+ //+ // Also fixes a crash: Express rewires `res.__proto__` to `app.response`,+ // which extends Node's real `http.ServerResponse`. Without a shadowing+ // own-property, `res.flushHeaders()` dereferences ServerResponse internals+ // (`outputData`) that were never initialised on the mock object.+ let streamingMode = false;+ let streamController: ReadableStreamDefaultController<Uint8Array> | null = null;+ const origWrite = res.write.bind(res);+ const origEnd = res.end.bind(res);++ function startStreaming() {+ if (streamingMode) return;+ streamingMode = true;+ const streamBody = new ReadableStream<Uint8Array>({+ start(controller) {+ streamController = controller;+ }+ });+ try {+ resolve(new Response(streamBody, {+ status: res.statusCode || 200,+ headers: normalizeResponseHeaders(res.getHeaders())+ }));+ } catch (err) {+ reject(err);+ }+ }++ (res as unknown as { flushHeaders: () => void }).flushHeaders = startStreaming;+ // Express compression / response-time wrappers and some handlers+ // probe for `res.flush()` to force-flush their buffer. In streaming+ // mode the stream controller delivers each enqueue eagerly, so this+ // is a safe no-op; without the shim it would fall through to the+ // ServerResponse prototype and crash the same way `flushHeaders`+ // does.+ (res as unknown as { flush: () => void }).flush = () => {};++ (res as unknown as { write: typeof res.write }).write = function write(+ this: typeof res,+ chunk: unknown,+ ...rest: unknown[]+ ): boolean {+ if (streamingMode) {+ const buf = toUint8Array(chunk);+ if (buf && streamController) {+ streamController.enqueue(buf);+ }+ return true;+ }+ return (origWrite as (...a: unknown[]) => boolean)(chunk, ...rest);+ } as typeof res.write;++ (res as unknown as { end: typeof res.end }).end = function end(+ this: typeof res,+ ...args: unknown[]+ ) {+ if (streamingMode) {+ if (args.length > 0 && args[0] != null && typeof args[0] !== "function") {+ const buf = toUint8Array(args[0]);+ if (buf && streamController) {+ streamController.enqueue(buf);+ }+ }+ if (streamController) {+ try {+ streamController.close();+ } catch {+ // Already closed (e.g. renderer aborted) — fine.+ }+ streamController = null;+ }+ // Keep mock state coherent for `on-finished` & friends, but+ // drop any payload args since we already drained them.+ return (origEnd as (...a: unknown[]) => unknown)();+ }+ return (origEnd as (...a: unknown[]) => unknown)(...args);+ } as typeof res.end;+res.on("end", () => {+ if (streamingMode) return; // streaming path already resolvedconst buf = typeof (res as any)._getBuffer === "function" ? (res as any)._getBuffer() : null;const data = res._getData();const rawPayload = buf && buf.length > 0 ? buf : data;@@ -80,12 +166,36 @@ export async function dispatch(app: Application, request: Request): Promise<Resp}});+ // Renderer cancelled the fetch (e.g. user hit stop, tab navigated).+ // Tear the stream down so the upstream handler stops writing into a+ // closed channel.+ request.signal?.addEventListener("abort", () => {+ if (streamingMode && streamController) {+ try {+ streamController.error(new Error("Renderer cancelled request"));+ } catch {+ // Already closed.+ }+ streamController = null;+ }+ });+try {(app as unknown as (req: object, res: object, next: (err?: unknown) => void) => void)(req,res,(err) => {- if (err) reject(err);+ if (err) {+ if (streamingMode && streamController) {+ try {+ streamController.error(err instanceof Error ? err : new Error(String(err)));+ } catch {+ // Already closed.+ }+ streamController = null;+ }+ reject(err);+ }});} catch (err) {