Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix([llm-playground-cancel-in-flight]): key cancel signal off response close, stop round-robin on abort

[._.]/ Adam Eivy6ddb87c4962c
diff --git a/server/lib/README.md b/server/lib/README.md
index d6edf0b767..a43d49365d 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -123,7 +123,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `httpClient.js` | Fetch-based HTTP client factory (axios.create replacement). |
| `fetchWithTimeout.js` | `fetch` wrapper with AbortController timeout. |
-| `requestAbort.js` | `abortSignalFromRequest(req)` — AbortSignal that fires when an Express client disconnects, so a streaming handler can tear down its upstream read on cancel. |
+| `requestAbort.js` | `abortSignalFromResponse(res)` — AbortSignal that fires only when an Express client disconnects *before the response finishes*, so a streaming handler can tear down its upstream read on cancel (keyed off `res` close + `writableEnded`, not `req`). |
| `readResponseJson.js` | Read a `Response` body as JSON, tolerating a non-JSON/HTML error page (no `Unexpected token <` crash). Object callers need no opts; pass `{ fallback, emptyValue }` for arrays or to surface the raw error text. |
| `peerHttpClient.js` | Federation HTTP/Socket.IO client (TLS validation off — Tailnet is the trust boundary). |
| `peerSelfHost.js` | Tailscale-issued hostname this PortOS sends in federation. |
diff --git a/server/lib/requestAbort.js b/server/lib/requestAbort.js
index 3cf8eaccb8..5ca8d52079 100644
--- a/server/lib/requestAbort.js
+++ b/server/lib/requestAbort.js
@@ -1,19 +1,25 @@
-// Derive an AbortSignal from an Express request that fires when the client
-// disconnects (browser fetch aborted, tab closed, network drop). Long-running
-// route handlers that proxy a streamed upstream call (e.g. the Local LLM
-// playground streaming a model's tokens) can forward this signal so the upstream
-// reader tears down the moment the user hits Cancel instead of running on to a
-// multi-minute timeout with no one left to receive the response.
+// Derive an AbortSignal from an Express response that fires only when the client
+// disconnects *before the response is finished* — i.e. a genuine cancel (browser
+// fetch aborted, tab closed, network drop) rather than the normal end of a
+// request. Long-running route handlers that proxy a streamed upstream call (e.g.
+// the Local LLM playground streaming a model's tokens) can forward this signal so
+// the upstream reader tears down the moment the user hits Cancel instead of
+// running on to a multi-minute timeout with no one left to receive the response.
//
-// `req.on('close')` fires once the connection is gone; the listener only calls
-// `controller.abort()`, which can't throw — safe to attach outside the request
-// lifecycle without a try/catch.
-export function abortSignalFromRequest(req) {
+// We key off `res`'s `close` event, NOT `req`'s: `req` (the IncomingMessage) can
+// emit `close` once the request body is fully consumed — which, after body
+// parsing, is before the handler even runs — so a `req`-based signal would abort
+// every normal request immediately. `res` `close` fires when the response is done
+// OR the connection drops; we only treat it as a cancel when the response had not
+// finished writing (`writableEnded` false), which is the disconnect case.
+//
+// The listener only calls `controller.abort()`, which can't throw — safe to attach
+// outside the request lifecycle without a try/catch.
+export function abortSignalFromResponse(res) {
const controller = new AbortController();
- if (req?.destroyed || req?.aborted) {
- controller.abort();
- return controller.signal;
- }
- req?.once?.('close', () => controller.abort());
+ if (res?.writableEnded || res?.destroyed) return controller.signal;
+ res?.once?.('close', () => {
+ if (!res.writableEnded) controller.abort();
+ });
return controller.signal;
}
diff --git a/server/lib/requestAbort.test.js b/server/lib/requestAbort.test.js
new file mode 100644
index 0000000000..3aa8c8a842
--- /dev/null
+++ b/server/lib/requestAbort.test.js
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+import { EventEmitter } from 'node:events';
+import { abortSignalFromResponse } from './requestAbort.js';
+
+// Minimal stand-in for an Express response: an EventEmitter carrying the
+// `writableEnded` flag the helper keys off.
+function fakeRes({ writableEnded = false, destroyed = false } = {}) {
+ const res = new EventEmitter();
+ res.writableEnded = writableEnded;
+ res.destroyed = destroyed;
+ return res;
+}
+
+describe('abortSignalFromResponse', () => {
+ it('does NOT abort when the response closes after finishing normally', () => {
+ const res = fakeRes();
+ const signal = abortSignalFromResponse(res);
+ res.writableEnded = true; // response fully written…
+ res.emit('close'); // …then the connection closes normally
+ expect(signal.aborted).toBe(false);
+ });
+
+ it('aborts when the client disconnects before the response finishes', () => {
+ const res = fakeRes();
+ const signal = abortSignalFromResponse(res);
+ res.emit('close'); // connection dropped mid-response, writableEnded still false
+ expect(signal.aborted).toBe(true);
+ });
+
+ it('returns an un-aborted signal when the response is already finished', () => {
+ const signal = abortSignalFromResponse(fakeRes({ writableEnded: true }));
+ expect(signal.aborted).toBe(false);
+ });
+
+ it('tolerates a missing response object', () => {
+ expect(abortSignalFromResponse(undefined).aborted).toBe(false);
+ });
+});
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index a591f6e2e6..ec5f520e93 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -29,7 +29,7 @@ import {
getStatus, listModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer
} from '../services/localLlm.js'
import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js'
-import { abortSignalFromRequest } from '../lib/requestAbort.js'
+import { abortSignalFromResponse } from '../lib/requestAbort.js'
import { getLoadedModels as getLoadedOllamaModels, unloadModel as unloadOllamaModel } from '../services/ollamaManager.js'
const router = Router()
@@ -228,7 +228,7 @@ router.post('/unload', asyncHandler(async (req, res) => {
// quality without leaving the Local LLM workflow.
router.post('/test', asyncHandler(async (req, res) => {
const body = validateRequest(localLlmTestSchema, req.body)
- res.json(await runLocalLlmTest({ ...body, signal: abortSignalFromRequest(req) }))
+ res.json(await runLocalLlmTest({ ...body, signal: abortSignalFromResponse(res) }))
}))
// POST /api/local-llm/compare — run one prompt through multiple local models.
@@ -236,7 +236,7 @@ router.post('/test', asyncHandler(async (req, res) => {
// measures contention when several loaded local models run at once.
router.post('/compare', asyncHandler(async (req, res) => {
const body = validateRequest(localLlmCompareSchema, req.body)
- res.json(await compareLocalLlmModels({ ...body, signal: abortSignalFromRequest(req) }))
+ res.json(await compareLocalLlmModels({ ...body, signal: abortSignalFromResponse(res) }))
}))
export default router
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index 3af51fca57..b7ed300c26 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -70,7 +70,7 @@ describe('local LLM playground routes', () => {
temperature: 0.3,
maxTokens: 1000,
timeoutMs: 300000,
- // Derived from req — lets a client disconnect tear down the upstream stream.
+ // Derived from res — lets a client disconnect tear down the upstream stream.
signal: expect.any(AbortSignal),
});
});
diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.js
index 6b73e1c0d0..095c9be226 100644
--- a/server/services/localLlmPlayground.js
+++ b/server/services/localLlmPlayground.js
@@ -288,6 +288,10 @@ export async function compareLocalLlmModels({ targets, prompt, mode = 'round-rob
}
for (const target of targets) {
+ // `runLocalLlmTest` swallows aborts into a result object rather than throwing,
+ // so without this guard a cancel mid-sequence would still kick off every
+ // remaining model. Stop the round-robin once the client has hung up.
+ if (signal?.aborted) break;
results.push(await runOne(target));
}
return { mode: 'round-robin', prompt, results };