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(desktop): stop the agent turn when the renderer cancels a stream
Elian Dorand3155471632b
diff --git a/apps/desktop/src/protocol.spec.ts b/apps/desktop/src/protocol.spec.tsindex f8b4589849..5c6bae1dbe 100644--- a/apps/desktop/src/protocol.spec.ts+++ b/apps/desktop/src/protocol.spec.ts@@ -522,6 +522,66 @@ describe("trilium-app protocol dispatcher", () => {await tail; // let the handler's post-abort writes run});+ it("survives the renderer cancelling the body stream mid-write, and tells the handler", async () => {+ const app = express();+ let releaseTail: (() => void) | undefined;+ const tail = new Promise<void>((r) => { releaseTail = r; });+ let writeError: unknown;+ let closed = false;++ app.get("/sse", async (_req, res) => {+ res.setHeader("Content-Type", "text/event-stream");+ res.flushHeaders();+ // The disconnect signal llm_chat.ts uses to abort the agent turn.+ res.on("close", () => { closed = true; });+ res.write("a\n");+ await tail;+ try {+ res.write("b\n");+ res.end();+ } catch (err) {+ writeError = err;+ }+ });++ // No AbortController: Electron's net layer cancels the response body+ // when the renderer aborts, and that can land before the fetch signal.+ const response = await dispatch(app, new Request("trilium-app://app/sse"));+ const reader = response.body?.getReader();+ if (!reader) throw new Error("expected a streaming body");+ expect(new TextDecoder().decode((await reader.read()).value)).toBe("a\n");++ await reader.cancel();+ expect(closed).toBe(true);++ releaseTail?.();+ await tail;+ expect(writeError).toBeUndefined();+ });++ it("signals 'close' once when the fetch abort tears the stream down", async () => {+ const app = express();+ let closeCount = 0;+ app.get("/sse", (_req, res) => {+ res.setHeader("Content-Type", "text/event-stream");+ res.flushHeaders();+ res.on("close", () => { closeCount++; });+ res.write("a\n");+ });++ const ac = new AbortController();+ const response = await dispatch(app, new Request("trilium-app://app/sse", { signal: ac.signal }));+ const reader = response.body?.getReader();+ if (!reader) throw new Error("expected a streaming body");+ await reader.read();++ ac.abort();+ await expect(reader.read()).rejects.toThrow();+ // The reader's own cancel path must not raise a second disconnect.+ await reader.cancel().catch(() => {});+ expect(closeCount).toBe(1);+ });+it("serialises object and primitive response payloads to bytes", async () => {// Express always stringifies objects/primitives before they reach the// mock's buffer, so force the buffered branch to read a raw object /diff --git a/apps/desktop/src/protocol.ts b/apps/desktop/src/protocol.tsindex e0aeddbeab..1ff76789cf 100644--- a/apps/desktop/src/protocol.ts+++ b/apps/desktop/src/protocol.ts@@ -300,6 +300,15 @@ function installStreamingBridge(// export to disk — would let the whole payload pile up in memory.const HIGH_WATER_MARK = 1024 * 1024; // 1 MiB+ // Handlers watch `res` for the client going away — llm_chat.ts aborts the+ // agent turn on it — and nothing else emits it on this mock response.+ let disconnected = false;+ function signalDisconnect() {+ if (disconnected) return;+ disconnected = true;+ res.emit("close");+ }+function resumeProducerIfReady() {if (producerPaused && controller && controller.desiredSize !== null && controller.desiredSize > 0) {producerPaused = false;@@ -314,7 +323,11 @@ function installStreamingBridge(start(c) { controller = c; },// The consumer pulled (queue has capacity again) → release a producer// that paused on backpressure.- pull() { resumeProducerIfReady(); }+ pull() { resumeProducerIfReady(); },+ // The renderer stopped reading — it aborted the fetch or its window+ // went away. `controller` is already closed, so drop it before the+ // handler's next write() and let the handler unwind through 'close'.+ cancel() { controller = null; signalDisconnect(); }}, new ByteLengthQueuingStrategy({ highWaterMark: HIGH_WATER_MARK }));try {onCommit(new Response(body, {@@ -329,7 +342,9 @@ function installStreamingBridge(function enqueue(chunk: unknown) {const buf = toUint8Array(chunk);- if (buf && controller) controller.enqueue(buf);+ if (!buf || !controller) return;+ /* v8 ignore next -- defensive: enqueue() only throws if the stream was torn down without cancel() firing */+ try { controller.enqueue(buf); } catch { controller = null; }}function closeStream() {@@ -383,7 +398,9 @@ function installStreamingBridge(// Renderer cancelled the fetch (e.g. user hit stop, tab navigated).abortSignal?.addEventListener("abort", () => {- if (streaming) errorStream(new Error("Renderer cancelled request"));+ if (!streaming) return;+ errorStream(new Error("Renderer cancelled request"));+ signalDisconnect();});return {