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

Local LLM Playground: live streaming, HTML preview, mobile layout

Adam Eivy003d36741cb9
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7ba9d2afcd..8e577e2a95 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,7 @@
- **[issue-730] Turn cross-machine resume on per session, right in the Story Builder** — each Story Builder session now has a "Cross-machine resume" toggle in its header, so you can opt a single session into syncing across your machines without leaving the wizard. Once it's on, a Reconcile button appears that adopts this machine's current universe/series records as the session's new staleness baseline — and it lights up only when those records have actually drifted from what the session last synced, so you know when reconciling will change something. Sessions stay private to one machine by default.
- **[issue-730] Story Builder sessions can sync across your machines** — a Story Builder session you mark for cross-machine resume now travels to your sync peers, so you can pick up the same wizard (its step locks, progress, and provider choice) on another machine. Sessions stay private to one machine by default; only the ones you explicitly opt in are shared, via a new "Story Builder" sync category you enable per peer on the Instances page. Local-only sessions are never pushed.
+- **Local LLM Playground: live streaming, HTML preview, and mobile layout** — chat runs now stream the model's output token-by-token as it generates instead of waiting for the whole reply, so you see progress immediately. Code blocks render in their own panels, and any HTML/SVG block gets a Code / Preview toggle that runs the markup in a sandboxed iframe right inline — handy for "generate a web page" prompts you want to actually see. The page is now phone-friendly too: the model list collapses behind a tap on small screens so the prompt and controls stay above the fold.
- **[issue-735] AudioLDM2 long-form music backend** — the pipeline audio stage can now generate background music with a second local engine, AudioLDM2, alongside MusicGen. Pick the engine in the Generate panel: MusicGen for short clips (up to 30s) or AudioLDM2 for longer pieces (up to two minutes), each with its own model choices. Both run entirely on your machine with no API key; install AudioLDM2's runtime with `INSTALL_AUDIOLDM2=1 bash scripts/setup-image-video.sh` and the panel shows an install hint until it's ready.
- **Shell arrow-key hot buttons** — the Shell page's quick-command toolbar now has touch-friendly Up / Down / Left / Right / Enter buttons that send the matching key to the terminal. Handy on phones and tablets where the on-screen keyboard hides the arrow keys, for scrolling command history, and for driving TUI apps without a hardware keyboard.
- **[issue-827] Clinician export for blood and lifestyle data** — MeatSpace gains an Export tab that builds a one-page, doctor-ready summary of your blood panels and lifestyle. Each blood test is laid out as a clean table with reference ranges and out-of-range markers flagged, and your lifestyle factors (sex, smoking, exercise, sleep, diet, stress, BMI, and any chronic conditions) are summarized above them. Print it or save it as a PDF straight from the browser, or copy the whole thing as markdown to paste into a message or note. Genome and longevity context are intentionally left out of this view.
diff --git a/client/src/components/localLlm/PlaygroundOutput.jsx b/client/src/components/localLlm/PlaygroundOutput.jsx
new file mode 100644
index 0000000000..bba853761b
--- /dev/null
+++ b/client/src/components/localLlm/PlaygroundOutput.jsx
@@ -0,0 +1,135 @@
+import { useMemo, useState } from 'react';
+import { Check, Code2, Copy, Eye } from 'lucide-react';
+import MarkdownOutput from '../cos/MarkdownOutput';
+import { copyToClipboard } from '../../lib/clipboard';
+
+// Languages whose fenced blocks can be rendered as a live preview. `htm`/`xml`/
+// `svg` round out the common ways a model labels markup it expects to render.
+const HTML_LANGS = new Set(['html', 'htm', 'xml', 'svg']);
+// Content sniff for the common case where a model emits a bare ``` fence (or no
+// fence at all) but the body is obviously a renderable document/fragment.
+const HTML_SNIFF = /<!doctype html|<html[\s>]|<body[\s>]|<svg[\s>]|<head[\s>]|<div[\s>]|<p[\s>]/i;
+
+function isHtmlLike(lang, code) {
+ if (HTML_LANGS.has(lang)) return true;
+ if (lang && lang !== 'markup') return false; // an explicit non-HTML language wins
+ return HTML_SNIFF.test(code);
+}
+
+// Split raw model output into ordered segments of fenced code blocks and the
+// plain text (markdown) between them. A fence opens on a line starting with ```
+// and closes on the next such line; an UNclosed fence (still streaming) consumes
+// the rest as code so live output renders sensibly until the closing fence lands.
+export function parseSegments(text) {
+ const lines = (text || '').split('\n');
+ const segments = [];
+ let textRun = [];
+ const flushText = () => {
+ // Drop whitespace-only runs (e.g. the blank line between two code fences) —
+ // they'd render as an empty markdown block and only add vertical noise.
+ if (textRun.length && textRun.join('\n').trim()) {
+ segments.push({ type: 'text', content: textRun.join('\n') });
+ }
+ textRun = [];
+ };
+
+ let i = 0;
+ while (i < lines.length) {
+ const line = lines[i];
+ if (line.startsWith('```')) {
+ flushText();
+ const lang = line.slice(3).trim().toLowerCase().split(/\s+/)[0] || '';
+ let end = i + 1;
+ while (end < lines.length && !lines[end].startsWith('```')) end++;
+ const code = lines.slice(i + 1, end).join('\n');
+ segments.push({ type: 'code', lang, code, closed: end < lines.length });
+ i = end + 1; // skip the closing fence (or run off the end if unterminated)
+ continue;
+ }
+ textRun.push(line);
+ i++;
+ }
+ flushText();
+ return segments;
+}
+
+function CopyButton({ value, label = 'Copied' }) {
+ const [copied, setCopied] = useState(false);
+ return (
+ <button
+ onClick={() => { copyToClipboard(value, label); setCopied(true); setTimeout(() => setCopied(false), 1200); }}
+ className="flex items-center gap-1 text-[11px] text-gray-400 hover:text-white"
+ title="Copy code"
+ >
+ {copied ? <Check size={12} className="text-port-success" /> : <Copy size={12} />}
+ {copied ? 'Copied' : 'Copy'}
+ </button>
+ );
+}
+
+function CodeBlock({ lang, code, closed }) {
+ const htmlPreviewable = useMemo(() => isHtmlLike(lang, code), [lang, code]);
+ // 'code' | 'preview' — only meaningful when htmlPreviewable. Default to code so
+ // the user opts in to running model-generated markup.
+ const [view, setView] = useState('code');
+ const showPreview = htmlPreviewable && view === 'preview';
+
+ return (
+ <div className="my-2 border border-port-border rounded-lg overflow-hidden bg-port-bg">
+ <div className="flex items-center justify-between gap-2 px-2 py-1 border-b border-port-border bg-port-card/60">
+ <span className="text-[11px] font-mono text-gray-500 truncate">
+ {lang || 'code'}{!closed && <span className="text-port-warning"> · streaming…</span>}
+ </span>
+ <div className="flex items-center gap-3 shrink-0">
+ {htmlPreviewable && (
+ <div className="flex items-center rounded-md border border-port-border overflow-hidden">
+ <button
+ onClick={() => setView('code')}
+ className={`flex items-center gap-1 px-2 py-0.5 text-[11px] ${view === 'code' ? 'bg-port-accent/20 text-port-accent' : 'text-gray-400 hover:text-white'}`}
+ >
+ <Code2 size={11} /> Code
+ </button>
+ <button
+ onClick={() => setView('preview')}
+ className={`flex items-center gap-1 px-2 py-0.5 text-[11px] ${view === 'preview' ? 'bg-port-accent/20 text-port-accent' : 'text-gray-400 hover:text-white'}`}
+ >
+ <Eye size={11} /> Preview
+ </button>
+ </div>
+ )}
+ <CopyButton value={code} label="Copied code" />
+ </div>
+ </div>
+ {showPreview ? (
+ // Sandbox WITHOUT allow-same-origin so the model's markup/scripts can run
+ // (allow-scripts) but can't reach this page's DOM, cookies, or storage.
+ <iframe
+ title="HTML preview"
+ sandbox="allow-scripts allow-forms allow-modals allow-popups"
+ srcDoc={code}
+ className="w-full h-72 md:h-96 bg-white"
+ />
+ ) : (
+ <pre className="overflow-x-auto p-2 text-xs font-mono text-port-accent whitespace-pre-wrap break-words">
+ {code}
+ </pre>
+ )}
+ </div>
+ );
+}
+
+// Renders model output: markdown for prose, with each fenced code block in its
+// own panel. HTML-like blocks get a Code/Preview toggle that runs the markup in
+// a sandboxed iframe — so "generate an HTML page" output is viewable inline.
+export default function PlaygroundOutput({ text }) {
+ const segments = useMemo(() => parseSegments(text), [text]);
+ return (
+ <div className="text-sm text-gray-200 leading-relaxed min-w-0">
+ {segments.map((seg, idx) => (
+ seg.type === 'code'
+ ? <CodeBlock key={idx} lang={seg.lang} code={seg.code} closed={seg.closed} />
+ : <MarkdownOutput key={idx} content={seg.content} />
+ ))}
+ </div>
+ );
+}
diff --git a/client/src/components/localLlm/PlaygroundOutput.test.jsx b/client/src/components/localLlm/PlaygroundOutput.test.jsx
new file mode 100644
index 0000000000..668e6a7e6b
--- /dev/null
+++ b/client/src/components/localLlm/PlaygroundOutput.test.jsx
@@ -0,0 +1,59 @@
+import { describe, it, expect } from 'vitest';
+import { render, fireEvent } from '@testing-library/react';
+import PlaygroundOutput, { parseSegments } from './PlaygroundOutput';
+
+describe('parseSegments', () => {
+ it('splits prose and fenced code into ordered segments with the language captured', () => {
+ const segments = parseSegments('Here you go:\n```html\n<h1>Hi</h1>\n```\nDone.');
+ expect(segments.map((s) => s.type)).toEqual(['text', 'code', 'text']);
+ expect(segments[1]).toMatchObject({ lang: 'html', code: '<h1>Hi</h1>', closed: true });
+ expect(segments[0].content).toBe('Here you go:');
+ expect(segments[2].content).toBe('Done.');
+ });
+
+ it('marks an unterminated fence (still streaming) as not closed and consumes the rest as code', () => {
+ const segments = parseSegments('```js\nconst a = 1;\nconst b = 2;');
+ expect(segments).toHaveLength(1);
+ expect(segments[0]).toMatchObject({ type: 'code', lang: 'js', closed: false });
+ expect(segments[0].code).toBe('const a = 1;\nconst b = 2;');
+ });
+
+ it('returns a single text segment when there is no code', () => {
+ const segments = parseSegments('just plain text');
+ expect(segments).toEqual([{ type: 'text', content: 'just plain text' }]);
+ });
+
+ it('handles empty input', () => {
+ expect(parseSegments('')).toEqual([]);
+ expect(parseSegments(null)).toEqual([]);
+ });
+});
+
+describe('PlaygroundOutput rendering', () => {
+ it('renders an HTML code block with a Preview toggle and a sandboxed iframe', () => {
+ const { container, getByText, queryByTitle } = render(
+ <PlaygroundOutput text={'```html\n<p>hello</p>\n```'} />,
+ );
+ // Preview toggle present for html-like blocks
+ const preview = getByText('Preview');
+ expect(preview).toBeTruthy();
+ // Defaults to code view — no iframe until toggled
+ expect(queryByTitle('HTML preview')).toBeNull();
+ fireEvent.click(preview);
+ const iframe = container.querySelector('iframe[title="HTML preview"]');
+ expect(iframe).toBeTruthy();
+ expect(iframe.getAttribute('sandbox')).toContain('allow-scripts');
+ expect(iframe.getAttribute('sandbox')).not.toContain('allow-same-origin');
+ expect(iframe.getAttribute('srcdoc')).toBe('<p>hello</p>');
+ });
+
+ it('does NOT offer a Preview toggle for a non-HTML language', () => {
+ const { queryByText } = render(<PlaygroundOutput text={'```python\nprint(1)\n```'} />);
+ expect(queryByText('Preview')).toBeNull();
+ });
+
+ it('offers Preview for a bare fence whose body sniffs as HTML', () => {
+ const { getByText } = render(<PlaygroundOutput text={'```\n<!doctype html><html></html>\n```'} />);
+ expect(getByText('Preview')).toBeTruthy();
+ });
+});
diff --git a/client/src/pages/LocalLlmPlayground.jsx b/client/src/pages/LocalLlmPlayground.jsx
index a58bc66065..5b95970e00 100644
--- a/client/src/pages/LocalLlmPlayground.jsx
+++ b/client/src/pages/LocalLlmPlayground.jsx
@@ -1,12 +1,13 @@
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, X } from 'lucide-react';
+import { ArrowLeft, ArrowRightLeft, Check, ChevronDown, Clock, Copy, Gauge, MessageSquare, Play, RefreshCw, Send, TriangleAlert, X } from 'lucide-react';
import BrailleSpinner from '../components/BrailleSpinner';
+import PlaygroundOutput from '../components/localLlm/PlaygroundOutput';
import toast from '../components/ui/Toast';
import { copyToClipboard } from '../lib/clipboard';
import { localLlmTargetKey } from '../lib/localLlmTargetKey';
import { formatBytes } from '../utils/formatters';
-import { compareLocalLlmModels, getLocalLlmCatalog, getLocalLlmStatus, testLocalLlmModel } from '../services/api';
+import { compareLocalLlmModels, getLocalLlmCatalog, getLocalLlmStatus, streamLocalLlmTest } from '../services/api';
const BACKEND_LABEL = { ollama: 'Ollama', lmstudio: 'LM Studio' };
const DEFAULT_PROMPT = 'Write a short, vivid paragraph about a lighthouse computer waking up at dawn.';
@@ -145,7 +146,9 @@ function ResultPanel({ result }) {
{result.text && (
<div className="space-y-1">
{hasPartial && <div className="text-xs text-port-warning">Partial output before the run stopped</div>}
- <pre className="text-sm text-gray-200 whitespace-pre-wrap break-words font-sans leading-relaxed max-h-72 overflow-auto">{result.text}</pre>
+ <div className="max-h-[28rem] overflow-auto">
+ <PlaygroundOutput text={result.text} />
+ </div>
</div>
)}
@@ -169,6 +172,28 @@ function ResultPanel({ result }) {
);
}
+// Live panel shown while a chat run streams tokens. Replaced by a final
+// ResultPanel (with timings) once the run settles.
+function StreamingPanel({ stream }) {
+ return (
+ <section className="border border-port-accent/40 rounded-lg bg-port-bg p-3 space-y-3">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <div className="text-sm text-white truncate">{stream.modelId}</div>
+ <div className="text-xs text-gray-500">{BACKEND_LABEL[stream.backend] || stream.backend}</div>
+ </div>
+ <span className="flex items-center gap-2 text-xs px-2 py-1 rounded bg-port-accent/15 text-port-accent">
+ <BrailleSpinner />
+ Streaming
+ </span>
+ </div>
+ {stream.text
+ ? <div className="max-h-[28rem] overflow-auto"><PlaygroundOutput text={stream.text} /></div>
+ : <div className="text-sm text-gray-500">Waiting for the first token…</div>}
+ </section>
+ );
+}
+
export default function LocalLlmPlayground() {
const [searchParams] = useSearchParams();
const [status, setStatus] = useState(null);
@@ -185,18 +210,36 @@ export default function LocalLlmPlayground() {
const [timeoutMs, setTimeoutMs] = useState(300000);
const [busy, setBusy] = useState(false);
const [chatResults, setChatResults] = useState([]);
+ const [streamingChat, setStreamingChat] = useState(null);
const [compareResult, setCompareResult] = useState(null);
+ // Models sidebar is always shown on xl+; on smaller screens it collapses so
+ // the prompt/controls stay above the fold. Open by default on first load.
+ const [modelsOpen, setModelsOpen] = useState(true);
const mountedRef = useRef(true);
// 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);
+ // Streaming tokens arrive faster than is worth re-rendering for (each render
+ // re-parses the whole accumulated output). Accumulate into a ref and flush to
+ // state on a ~80ms timer so the live panel updates smoothly without an
+ // O(n²) re-parse storm on long outputs.
+ const streamBufRef = useRef('');
+ const flushTimerRef = useRef(null);
useEffect(() => () => {
mountedRef.current = false;
runControllerRef.current?.abort();
+ if (flushTimerRef.current) clearTimeout(flushTimerRef.current);
}, []);
+ const flushStream = () => {
+ flushTimerRef.current = null;
+ if (!mountedRef.current) return;
+ const text = streamBufRef.current;
+ setStreamingChat((prev) => (prev ? { ...prev, text } : prev));
+ };
+
const cancelRun = () => runControllerRef.current?.abort();
const loadStatus = useCallback(() => {
@@ -279,9 +322,21 @@ export default function LocalLlmPlayground() {
runControllerRef.current = controller;
setBusy(true);
const target = primaryTarget;
- testLocalLlmModel({ ...target, prompt: prompt.trim(), ...options() }, { silent: true, signal: controller.signal })
+ streamBufRef.current = '';
+ setStreamingChat({ backend: target.backend, modelId: target.modelId, text: '' });
+ streamLocalLlmTest(
+ { ...target, prompt: prompt.trim(), ...options() },
+ {
+ signal: controller.signal,
+ onToken: (delta) => {
+ if (!mountedRef.current || !delta) return;
+ streamBufRef.current += delta;
+ if (!flushTimerRef.current) flushTimerRef.current = setTimeout(flushStream, 80);
+ },
+ },
+ )
.then((result) => {
- if (!mountedRef.current) return;
+ if (!mountedRef.current || !result) return;
setChatResults((prev) => [result, ...prev]);
if (result.error) toast.error(result.error);
})
@@ -290,7 +345,12 @@ export default function LocalLlmPlayground() {
.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);
+ // Drop any pending flush — the final result replaces the live panel.
+ if (flushTimerRef.current) { clearTimeout(flushTimerRef.current); flushTimerRef.current = null; }
+ if (mountedRef.current) {
+ setBusy(false);
+ setStreamingChat(null);
+ }
});
};
@@ -326,8 +386,8 @@ export default function LocalLlmPlayground() {
<ArrowLeft size={16} />
</Link>
<div className="min-w-0">
- <h1 className="text-2xl font-bold text-white">Local LLM Playground</h1>
- <p className="text-sm text-gray-500 truncate">{selectedTargets.length} model{selectedTargets.length === 1 ? '' : 's'} selected</p>
+ <h1 className="text-lg md:text-2xl font-bold text-white truncate">Local LLM Playground</h1>
+ <p className="text-xs md:text-sm text-gray-500 truncate">{selectedTargets.length} model{selectedTargets.length === 1 ? '' : 's'} selected</p>
</div>
</div>
<button onClick={loadStatus} disabled={loadingStatus} className="p-2 text-gray-400 hover:text-white transition-colors" title="Refresh models" aria-label="Refresh models">
@@ -338,10 +398,22 @@ export default function LocalLlmPlayground() {
<div className="flex-1 overflow-auto p-4 space-y-4">
<div className="grid grid-cols-1 xl:grid-cols-[320px_1fr] gap-4">
<aside className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">
- <div className="flex items-center justify-between">
- <h2 className="text-sm font-medium text-gray-300">Models</h2>
- {loadingStatus && <BrailleSpinner />}
- </div>
+ <button
+ type="button"
+ onClick={() => setModelsOpen((v) => !v)}
+ className="w-full flex items-center justify-between gap-2 xl:cursor-default"
+ aria-expanded={modelsOpen}
+ >
+ <span className="flex items-center gap-2">
+ <h2 className="text-sm font-medium text-gray-300">Models</h2>
+ <span className="text-xs text-gray-500 xl:hidden">({selectedTargets.length} selected)</span>
+ </span>
+ <span className="flex items-center gap-2">
+ {loadingStatus && <BrailleSpinner />}
+ <ChevronDown size={16} className={`text-gray-500 xl:hidden transition-transform ${modelsOpen ? '' : '-rotate-90'}`} />
+ </span>
+ </button>
+ <div className={`${modelsOpen ? 'block' : 'hidden'} xl:block space-y-4`}>
{installedTargets.length === 0 && !loadingStatus ? (
<p className={`text-sm ${modelLoadError ? 'text-port-warning' : 'text-gray-500'}`}>
{modelLoadError || 'No installed local models found.'}
@@ -400,6 +472,7 @@ export default function LocalLlmPlayground() {
})}
</div>
)}
+ </div>
</aside>
<main className="space-y-4">
@@ -489,7 +562,8 @@ export default function LocalLlmPlayground() {
{activeMode === 'chat' ? (
<section className="space-y-3">
- {chatResults.length === 0 ? (
+ {streamingChat && <StreamingPanel stream={streamingChat} />}
+ {chatResults.length === 0 && !streamingChat ? (
<div className="bg-port-card border border-port-border rounded-lg p-5 text-sm text-gray-500 flex items-center gap-2">
<TriangleAlert size={16} className="text-gray-600" />
Pick a model, enter a prompt, and run a chat test.
diff --git a/client/src/pages/LocalLlmPlayground.test.jsx b/client/src/pages/LocalLlmPlayground.test.jsx
index 7d2a9f073f..b130a1db35 100644
--- a/client/src/pages/LocalLlmPlayground.test.jsx
+++ b/client/src/pages/LocalLlmPlayground.test.jsx
@@ -6,6 +6,7 @@ vi.mock('../services/api', () => ({
getLocalLlmStatus: vi.fn(),
getLocalLlmCatalog: vi.fn(),
testLocalLlmModel: vi.fn(),
+ streamLocalLlmTest: vi.fn(),
compareLocalLlmModels: vi.fn(),
}));
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index c034f56046..ac239a6a99 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -1,4 +1,4 @@
-import { request } from './apiCore.js';
+import { request, API_BASE } from './apiCore.js';
// Local LLM backends (Ollama / LM Studio) — status, model management, migrate.
// Installed models per backend come back inside getLocalLlmStatus().
@@ -64,3 +64,56 @@ export const testLocalLlmModel = (payload, options) =>
export const compareLocalLlmModels = (payload, options) =>
request('/local-llm/compare', { method: 'POST', body: JSON.stringify(payload), ...options });
+
+// Streaming variant of testLocalLlmModel. POSTs the same payload but reads the
+// NDJSON response body so `onToken(delta)` fires per content chunk for live
+// rendering. Resolves with the terminal result object (same shape as
+// testLocalLlmModel, including `error`/`text` for a timed-out partial). The
+// caller passes `signal` to cancel — aborting rejects the read with AbortError,
+// which the caller should swallow when `signal.aborted` (intentional cancel).
+// Can't use the EventSource-based useSseProgress hook here: that's GET-only and
+// this request carries a prompt body.
+export async function streamLocalLlmTest(payload, { signal, onToken } = {}) {
+ const response = await fetch(`${API_BASE}/local-llm/test/stream`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ signal,
+ });
+ if (!response.ok || !response.body?.getReader) {
+ const err = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
+ throw new Error(err.error || `HTTP ${response.status}`);
+ }
+
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+ let result = null;
+
+ const consume = (line) => {
+ const trimmed = line.trim();
+ if (!trimmed) return;
+ let frame;
+ try { frame = JSON.parse(trimmed); } catch { return; }
+ if (frame.type === 'token') onToken?.(frame.delta || '');
+ else if (frame.type === 'result') result = frame.result;
+ };
+
+ // Always release the reader on every exit — a clean finish, a thrown
+ // AbortError on cancel, or a mid-stream throw — so a non-abort error doesn't
+ // leave the stream dangling (mirrors apiAsk.js / apiOpenClaw.js).
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split('\n');
+ buffer = lines.pop() || '';
+ for (const line of lines) consume(line);
+ }
+ if (buffer.trim()) consume(buffer);
+ } finally {
+ await reader.cancel().catch(() => {});
+ }
+ return result;
+}
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index 73610fb9fd..8e454130aa 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -231,6 +231,49 @@ router.post('/test', asyncHandler(async (req, res) => {
res.json(await runLocalLlmTest({ ...body, signal: abortSignalFromResponse(res) }))
}))
+// POST /api/local-llm/test/stream — same as /test, but streams the model's
+// output token-by-token as newline-delimited JSON (NDJSON) so the playground
+// can render live. Frames: `{ type: 'token', delta }` per content chunk, then a
+// terminal `{ type: 'result', result }` carrying the same object /test returns
+// (text, timings, runId, and any error). `runLocalLlmTest` resolves rather than
+// throws — including on timeout/abort — so the result frame always lands while
+// the socket is alive, and no JSON error body is attempted after headers flush.
+router.post('/test/stream', asyncHandler(async (req, res) => {
+ const body = validateRequest(localLlmTestSchema, req.body)
+ res.set({
+ 'Content-Type': 'application/x-ndjson; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ Connection: 'keep-alive',
+ 'X-Accel-Buffering': 'no',
+ })
+ res.flushHeaders?.()
+
+ // Once headers are flushed the response is "in stream mode" — never throw past
+ // here. A write after the client disconnected can throw ERR_STREAM_WRITE_AFTER_END;
+ // treat any failure as a dead socket and drop the frame.
+ const write = (frame) => {
+ if (res.writableEnded || res.destroyed) return
+ try { res.write(`${JSON.stringify(frame)}\n`) } catch { /* client gone */ }
+ }
+
+ // `runLocalLlmTest` resolves for in-stream failures, but can still THROW before
+ // the stream opens (unconfigured/invalid provider). Headers are already flushed,
+ // so a throw past here can't bubble to asyncHandler's JSON error path without
+ // ERR_HTTP_HEADERS_SENT — convert it to a terminal result frame the client toasts.
+ const result = await runLocalLlmTest({
+ ...body,
+ signal: abortSignalFromResponse(res),
+ onToken: (delta) => { if (delta) write({ type: 'token', delta }) },
+ }).catch((err) => ({
+ backend: body.backend,
+ modelId: body.modelId,
+ error: err?.message || 'Local LLM test failed',
+ text: '',
+ }))
+ write({ type: 'result', result })
+ res.end()
+}))
+
// POST /api/local-llm/compare — run one prompt through multiple local models.
// `round-robin` measures each model in isolation; `parallel` intentionally
// measures contention when several loaded local models run at once.
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index 8fc00ee6f3..20c50ee704 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -75,6 +75,40 @@ describe('local LLM playground routes', () => {
});
});
+ it('streams tokens then a terminal result frame as NDJSON', async () => {
+ runLocalLlmTest.mockImplementation(async ({ onToken }) => {
+ onToken('Hel');
+ onToken('lo');
+ return { backend: 'ollama', modelId: 'llama3.2', text: 'Hello', runId: 'run-1' };
+ });
+
+ const res = await request(makeApp())
+ .post('/api/local-llm/test/stream')
+ .send({ backend: 'ollama', modelId: 'llama3.2', prompt: 'Say hello' });
+
+ expect(res.status).toBe(200);
+ expect(res.headers['content-type']).toMatch(/application\/x-ndjson/);
+ const frames = res.text.trim().split('\n').map((l) => JSON.parse(l));
+ expect(frames).toEqual([
+ { type: 'token', delta: 'Hel' },
+ { type: 'token', delta: 'lo' },
+ { type: 'result', result: { backend: 'ollama', modelId: 'llama3.2', text: 'Hello', runId: 'run-1' } },
+ ]);
+ });
+
+ it('converts a pre-stream provider throw into a terminal error result frame (no 500 after headers)', async () => {
+ runLocalLlmTest.mockRejectedValue(new Error('Local provider "ollama" is not configured'));
+
+ const res = await request(makeApp())
+ .post('/api/local-llm/test/stream')
+ .send({ backend: 'ollama', modelId: 'llama3.2', prompt: 'Say hello' });
+
+ expect(res.status).toBe(200); // headers flushed before the throw — never a JSON 500
+ const frames = res.text.trim().split('\n').map((l) => JSON.parse(l));
+ expect(frames).toHaveLength(1);
+ expect(frames[0]).toMatchObject({ type: 'result', result: { error: 'Local provider "ollama" is not configured', text: '' } });
+ });
+
it('compares models in the requested execution mode', async () => {
compareLocalLlmModels.mockResolvedValue({
mode: 'parallel',
diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.js
index 72036ede00..a1b7998521 100644
--- a/server/services/localLlmPlayground.js
+++ b/server/services/localLlmPlayground.js
@@ -189,6 +189,10 @@ export async function runLocalLlmTest({
maxTokens = 1000,
timeoutMs = 300000,
signal: clientSignal,
+ // Optional per-token callback. When provided (streaming route), each content
+ // delta is forwarded as it arrives so the client can render live output. The
+ // returned result is unchanged, so non-streaming callers ignore this entirely.
+ onToken,
}) {
const provider = await resolveLocalProvider(backend);
const fullPrompt = buildPrompt({ systemPrompt, prompt });
@@ -228,6 +232,7 @@ export async function runLocalLlmTest({
signal,
onChunk: (chunk) => {
if (!firstChunkAt && chunk) firstChunkAt = Date.now();
+ if (chunk) onToken?.(chunk);
},
}).finally(() => clearTimeout(timeoutHandle));
diff --git a/server/services/localLlmPlayground.test.js b/server/services/localLlmPlayground.test.js
index 84f4690e79..0a5b28a78f 100644
--- a/server/services/localLlmPlayground.test.js
+++ b/server/services/localLlmPlayground.test.js
@@ -166,6 +166,19 @@ describe('runLocalLlmTest timeout/abort contract', () => {
expect(finalizeRunRecord).toHaveBeenCalledWith(expect.objectContaining({ output: 'Done.', success: true, exitCode: 0 }));
});
+ it('forwards each content delta to onToken as it streams (streaming route)', async () => {
+ stubStream(makeReader([sse({ content: 'Hel' }), sse({ content: 'lo' })], { abort: false }));
+ const tokens = [];
+
+ const result = await runLocalLlmTest({
+ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000,
+ onToken: (delta) => tokens.push(delta),
+ });
+
+ expect(tokens).toEqual(['Hel', 'lo']);
+ expect(result.text).toBe('Hello');
+ });
+
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) => {