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

feat([llm-playground-cancel-in-flight]): add Cancel button to stop an in-flight playground run

[._.]/ Adam Eivy0cc5a6aeef43
diff --git a/client/src/pages/LocalLlmPlayground.jsx b/client/src/pages/LocalLlmPlayground.jsx
index d36dcde8b2..c490f2d9cf 100644
--- a/client/src/pages/LocalLlmPlayground.jsx
+++ b/client/src/pages/LocalLlmPlayground.jsx
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Link, useSearchParams } from 'react-router-dom';
-import { ArrowLeft, ArrowRightLeft, Check, Clock, Copy, Gauge, MessageSquare, Play, RefreshCw, Send, TriangleAlert } from 'lucide-react';
+import { ArrowLeft, ArrowRightLeft, Check, Clock, Copy, Gauge, MessageSquare, Play, RefreshCw, Send, TriangleAlert, X } from 'lucide-react';
import BrailleSpinner from '../components/BrailleSpinner';
import toast from '../components/ui/Toast';
import { copyToClipboard } from '../lib/clipboard';
@@ -135,7 +135,16 @@ export default function LocalLlmPlayground() {
const [compareResult, setCompareResult] = useState(null);
const mountedRef = useRef(true);
- useEffect(() => () => { mountedRef.current = false; }, []);
+ // Holds the AbortController for the in-flight run so the Cancel button can
+ // abort the client fetch (which closes the server-side stream early). Cleared
+ // in each run's .finally(). Abort the live request on unmount too.
+ const runControllerRef = useRef(null);
+ useEffect(() => () => {
+ mountedRef.current = false;
+ runControllerRef.current?.abort();
+ }, []);
+
+ const cancelRun = () => runControllerRef.current?.abort();
const loadStatus = useCallback(() => {
setLoadingStatus(true);
@@ -189,20 +198,29 @@ export default function LocalLlmPlayground() {
const runChat = () => {
if (!canRunChat) return;
+ const controller = new AbortController();
+ runControllerRef.current = controller;
setBusy(true);
const target = primaryTarget;
- testLocalLlmModel({ ...target, prompt: prompt.trim(), ...options() }, { silent: true })
+ testLocalLlmModel({ ...target, prompt: prompt.trim(), ...options() }, { silent: true, signal: controller.signal })
.then((result) => {
if (!mountedRef.current) return;
setChatResults((prev) => [result, ...prev]);
if (result.error) toast.error(result.error);
})
- .catch((err) => { if (mountedRef.current) toast.error(err?.message || 'Model test failed'); })
- .finally(() => { if (mountedRef.current) setBusy(false); });
+ // A user-initiated cancel rejects the fetch with AbortError — don't surface
+ // it as a failure; the request was stopped on purpose.
+ .catch((err) => { if (mountedRef.current && !controller.signal.aborted) toast.error(err?.message || 'Model test failed'); })
+ .finally(() => {
+ if (runControllerRef.current === controller) runControllerRef.current = null;
+ if (mountedRef.current) setBusy(false);
+ });
};
const runCompare = () => {
if (!canCompare) return;
+ const controller = new AbortController();
+ runControllerRef.current = controller;
setBusy(true);
setCompareResult(null);
compareLocalLlmModels({
@@ -210,14 +228,17 @@ export default function LocalLlmPlayground() {
prompt: prompt.trim(),
targets: selectedTargets,
options: options(),
- }, { silent: true })
+ }, { silent: true, signal: controller.signal })
.then((result) => {
if (!mountedRef.current) return;
setCompareResult(result);
if ((result.results || []).some((r) => r.error)) toast.error('Some model runs failed');
})
- .catch((err) => { if (mountedRef.current) toast.error(err?.message || 'Comparison failed'); })
- .finally(() => { if (mountedRef.current) setBusy(false); });
+ .catch((err) => { if (mountedRef.current && !controller.signal.aborted) toast.error(err?.message || 'Comparison failed'); })
+ .finally(() => {
+ if (runControllerRef.current === controller) runControllerRef.current = null;
+ if (mountedRef.current) setBusy(false);
+ });
};
return (
@@ -344,14 +365,24 @@ export default function LocalLlmPlayground() {
</select>
</>
)}
- <button
- onClick={activeMode === 'chat' ? runChat : runCompare}
- disabled={busy || (activeMode === 'chat' ? !canRunChat : !canCompare)}
- className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent text-sm font-medium rounded-lg disabled:opacity-50"
- >
- {busy ? <BrailleSpinner /> : activeMode === 'chat' ? <Send size={15} /> : <Play size={15} />}
- {activeMode === 'chat' ? 'Run chat' : 'Run comparison'}
- </button>
+ {busy ? (
+ <button
+ onClick={cancelRun}
+ className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-port-error/15 hover:bg-port-error/25 text-port-error text-sm font-medium rounded-lg"
+ >
+ <X size={15} />
+ Cancel
+ </button>
+ ) : (
+ <button
+ onClick={activeMode === 'chat' ? runChat : runCompare}
+ disabled={activeMode === 'chat' ? !canRunChat : !canCompare}
+ className="w-full flex items-center justify-center gap-2 px-3 py-2 bg-port-accent/20 hover:bg-port-accent/30 text-port-accent text-sm font-medium rounded-lg disabled:opacity-50"
+ >
+ {activeMode === 'chat' ? <Send size={15} /> : <Play size={15} />}
+ {activeMode === 'chat' ? 'Run chat' : 'Run comparison'}
+ </button>
+ )}
</div>
</div>
</section>
diff --git a/server/lib/README.md b/server/lib/README.md
index c0a6cf2f06..d6edf0b767 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -123,6 +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. |
| `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/index.js b/server/lib/index.js
index 733ff5278a..e407e55c78 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -107,6 +107,7 @@ export * from './pythonSetup.js';
// === Networking ===
export * from './fetchWithTimeout.js';
+export * from './requestAbort.js';
export * from './httpClient.js';
export * from './httpsState.js';
export * from './networkExposure.js';
diff --git a/server/lib/requestAbort.js b/server/lib/requestAbort.js
new file mode 100644
index 0000000000..3cf8eaccb8
--- /dev/null
+++ b/server/lib/requestAbort.js
@@ -0,0 +1,19 @@
+// 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.
+//
+// `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) {
+ const controller = new AbortController();
+ if (req?.destroyed || req?.aborted) {
+ controller.abort();
+ return controller.signal;
+ }
+ req?.once?.('close', () => controller.abort());
+ return controller.signal;
+}
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index fdd7e4791e..a591f6e2e6 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -29,6 +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 { getLoadedModels as getLoadedOllamaModels, unloadModel as unloadOllamaModel } from '../services/ollamaManager.js'
const router = Router()
@@ -227,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))
+ res.json(await runLocalLlmTest({ ...body, signal: abortSignalFromRequest(req) }))
}))
// POST /api/local-llm/compare — run one prompt through multiple local models.
@@ -235,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))
+ res.json(await compareLocalLlmModels({ ...body, signal: abortSignalFromRequest(req) }))
}))
export default router
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index 818455c1f1..3af51fca57 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -70,6 +70,8 @@ describe('local LLM playground routes', () => {
temperature: 0.3,
maxTokens: 1000,
timeoutMs: 300000,
+ // Derived from req — lets a client disconnect tear down the upstream stream.
+ signal: expect.any(AbortSignal),
});
});
@@ -102,6 +104,7 @@ describe('local LLM playground routes', () => {
maxTokens: 64,
timeoutMs: 300000,
},
+ signal: expect.any(AbortSignal),
});
});
diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.js
index d93336903f..510a75f61d 100644
--- a/server/services/localLlmPlayground.js
+++ b/server/services/localLlmPlayground.js
@@ -187,6 +187,7 @@ export async function runLocalLlmTest({
temperature = 0.3,
maxTokens = 1000,
timeoutMs = 300000,
+ signal: clientSignal,
}) {
const provider = await resolveLocalProvider(backend);
const fullPrompt = buildPrompt({ systemPrompt, prompt });
@@ -207,7 +208,16 @@ export async function runLocalLlmTest({
throw new Error(`Local LLM playground refused fallback provider for ${provider.id}`);
}
+ // The timeout aborts the upstream read; a client disconnect (the user hit
+ // Cancel, closing the browser fetch) aborts `clientSignal`, which we forward
+ // onto the same controller so the upstream reader tears down early instead of
+ // running on to the full timeout with no one listening.
const controller = new AbortController();
+ const onClientAbort = () => controller.abort();
+ if (clientSignal) {
+ if (clientSignal.aborted) controller.abort();
+ else clientSignal.addEventListener('abort', onClientAbort, { once: true });
+ }
const timeoutHandle = setTimeout(() => controller.abort(), timeoutMs);
const text = await streamChatCompletion({
provider,
@@ -221,7 +231,10 @@ export async function runLocalLlmTest({
onChunk: (chunk) => {
if (!firstChunkAt && chunk) firstChunkAt = Date.now();
},
- }).finally(() => clearTimeout(timeoutHandle));
+ }).finally(() => {
+ clearTimeout(timeoutHandle);
+ clientSignal?.removeEventListener('abort', onClientAbort);
+ });
const endedAt = Date.now();
await finalizeRunRecord({ runId, output: text, exitCode: 0, success: true, startTime: startedAt });
@@ -266,8 +279,8 @@ export async function runLocalLlmTest({
}
}
-export async function compareLocalLlmModels({ targets, prompt, mode = 'round-robin', options = {} }) {
- const runOne = (target) => runLocalLlmTest({ ...options, ...target, prompt });
+export async function compareLocalLlmModels({ targets, prompt, mode = 'round-robin', options = {}, signal }) {
+ const runOne = (target) => runLocalLlmTest({ ...options, ...target, prompt, signal });
const results = [];
if (mode === 'parallel') {
diff --git a/server/services/localLlmPlayground.test.js b/server/services/localLlmPlayground.test.js
index 6d20fed1ac..84f4690e79 100644
--- a/server/services/localLlmPlayground.test.js
+++ b/server/services/localLlmPlayground.test.js
@@ -165,4 +165,38 @@ describe('runLocalLlmTest timeout/abort contract', () => {
expect(result.text).toBe('Done.');
expect(finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({ output: 'Done.', success: true, exitCode: 0 }));
});
+
+ it('forwards a client cancel onto the upstream fetch so the reader tears down early', async () => {
+ let capturedSignal = null;
+ global.fetch = vi.fn().mockImplementation((_url, init) => {
+ capturedSignal = init.signal;
+ return Promise.resolve({ ok: true, status: 200, body: { getReader: () => makeReader([sse({ content: 'partial' })], { abort: true }) } });
+ });
+
+ // A client that hung up before the run even started is the worst case — the
+ // upstream signal must already be aborted, not run on to the 5s timeout.
+ const clientController = new AbortController();
+ clientController.abort();
+
+ const result = await runLocalLlmTest({ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000, signal: clientController.signal });
+
+ expect(capturedSignal.aborted).toBe(true);
+ // The cancel surfaces as the same partial-output-on-abort contract.
+ expect(result.text).toBe('partial');
+ });
+
+ it('aborts the upstream fetch when the client signal fires mid-run', async () => {
+ let capturedSignal = null;
+ global.fetch = vi.fn().mockImplementation((_url, init) => {
+ capturedSignal = init.signal;
+ return Promise.resolve({ ok: true, status: 200, body: { getReader: () => makeReader([sse({ content: 'partial' })], { abort: true }) } });
+ });
+
+ const clientController = new AbortController();
+ const promise = runLocalLlmTest({ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000, signal: clientController.signal });
+ clientController.abort();
+ await promise;
+
+ expect(capturedSignal.aborted).toBe(true);
+ });
});