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([issue-906]): stream reasoning-model thinking live in the LLM playground

Adam Eivy98c7ff10c3c4
diff --git a/client/src/pages/LocalLlmPlayground.jsx b/client/src/pages/LocalLlmPlayground.jsx
index 4b4e2427eb..f6211664df 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, ChevronDown, Clock, Copy, Gauge, MessageSquare, Play, RefreshCw, Send, TriangleAlert, X } from 'lucide-react';
+import { ArrowLeft, ArrowRightLeft, Brain, 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';
@@ -173,8 +173,12 @@ function ResultPanel({ result }) {
}
// Live panel shown while a chat run streams tokens. Replaced by a final
-// ResultPanel (with timings) once the run settles.
+// ResultPanel (with timings) once the run settles. Reasoning (a reasoning
+// model's chain-of-thought) streams on its own channel and renders in a
+// distinct "Thinking" block above the answer, so the answer text stays clean.
function StreamingPanel({ stream }) {
+ const hasReasoning = Boolean(stream.reasoning);
+ const hasText = Boolean(stream.text);
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">
@@ -184,12 +188,23 @@ function StreamingPanel({ stream }) {
</div>
<span className="flex items-center gap-2 text-xs px-2 py-1 rounded bg-port-accent/15 text-port-accent">
<BrailleSpinner />
- Streaming
+ {hasText ? 'Streaming' : hasReasoning ? 'Thinking' : 'Streaming'}
</span>
</div>
- {stream.text
+ {hasReasoning && (
+ <div className="rounded-lg border border-port-border bg-port-card/40 p-2 space-y-1">
+ <div className="flex items-center gap-1.5 text-xs text-gray-500">
+ <Brain size={12} className="text-gray-600" />
+ Thinking
+ </div>
+ <div className="max-h-48 overflow-auto text-xs text-gray-400 whitespace-pre-wrap break-words">
+ {stream.reasoning}
+ </div>
+ </div>
+ )}
+ {hasText
? <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>}
+ : !hasReasoning && <div className="text-sm text-gray-500">Waiting for the first token…</div>}
</section>
);
}
@@ -222,10 +237,13 @@ export default function LocalLlmPlayground() {
// 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
+ // re-parses the whole accumulated output). Accumulate into refs and flush to
// state on a ~80ms timer so the live panel updates smoothly without an
- // O(n²) re-parse storm on long outputs.
+ // O(n²) re-parse storm on long outputs. Content and reasoning stream on
+ // separate channels so a reasoning model's chain-of-thought renders live in
+ // its own block instead of polluting the answer text.
const streamBufRef = useRef('');
+ const reasoningBufRef = useRef('');
const flushTimerRef = useRef(null);
useEffect(() => () => {
mountedRef.current = false;
@@ -237,7 +255,8 @@ export default function LocalLlmPlayground() {
flushTimerRef.current = null;
if (!mountedRef.current) return;
const text = streamBufRef.current;
- setStreamingChat((prev) => (prev ? { ...prev, text } : prev));
+ const reasoning = reasoningBufRef.current;
+ setStreamingChat((prev) => (prev ? { ...prev, text, reasoning } : prev));
};
const cancelRun = () => runControllerRef.current?.abort();
@@ -323,14 +342,16 @@ export default function LocalLlmPlayground() {
setBusy(true);
const target = primaryTarget;
streamBufRef.current = '';
- setStreamingChat({ backend: target.backend, modelId: target.modelId, text: '' });
+ reasoningBufRef.current = '';
+ setStreamingChat({ backend: target.backend, modelId: target.modelId, text: '', reasoning: '' });
streamLocalLlmTest(
{ ...target, prompt: prompt.trim(), ...options() },
{
signal: controller.signal,
- onToken: (delta) => {
+ onToken: (delta, kind) => {
if (!mountedRef.current || !delta) return;
- streamBufRef.current += delta;
+ if (kind === 'reasoning') reasoningBufRef.current += delta;
+ else streamBufRef.current += delta;
if (!flushTimerRef.current) flushTimerRef.current = setTimeout(flushStream, 80);
},
},
diff --git a/client/src/pages/LocalLlmPlayground.test.jsx b/client/src/pages/LocalLlmPlayground.test.jsx
index b130a1db35..0aae2f25a3 100644
--- a/client/src/pages/LocalLlmPlayground.test.jsx
+++ b/client/src/pages/LocalLlmPlayground.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, waitFor } from '@testing-library/react';
+import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
vi.mock('../services/api', () => ({
@@ -15,7 +15,7 @@ vi.mock('../components/ui/Toast', () => ({
}));
import LocalLlmPlayground from './LocalLlmPlayground';
-import { getLocalLlmCatalog, getLocalLlmStatus } from '../services/api';
+import { getLocalLlmCatalog, getLocalLlmStatus, streamLocalLlmTest } from '../services/api';
const renderPlayground = () => render(
<MemoryRouter initialEntries={['/local-llm/playground?backend=ollama&model=command-r-plus%3A104b']}>
@@ -69,4 +69,34 @@ describe('LocalLlmPlayground', () => {
expect(screen.getByText('Tool use')).toBeTruthy();
expect(screen.getByText('Multilingual')).toBeTruthy();
});
+
+ it('renders a live "Thinking" block for streamed reasoning, separate from the answer', async () => {
+ // Drive reasoning tokens then a content token through the streaming callback,
+ // mirroring a reasoning model (deepseek-r1, qwq) that emits its chain-of-thought
+ // first. The reasoning must render in its own block; the answer text stays clean.
+ // Hold the run open (gate) so the live streaming panel stays mounted while we
+ // assert — once the promise resolves, the panel is replaced by the result.
+ let releaseRun;
+ const runGate = new Promise((resolve) => { releaseRun = resolve; });
+ streamLocalLlmTest.mockImplementation(async (_payload, { onToken }) => {
+ onToken('reasoning step one ', 'reasoning');
+ onToken('reasoning step two', 'reasoning');
+ onToken('Final answer.', 'content');
+ await runGate;
+ return { backend: 'ollama', modelId: 'command-r-plus:104b', text: 'Final answer.', runId: 'run-x', timings: {} };
+ });
+
+ renderPlayground();
+ await waitFor(() => expect(screen.getAllByText('command-r-plus:104b').length).toBeGreaterThan(0));
+
+ fireEvent.click(screen.getByText('Run chat'));
+
+ // The reasoning block label and its streamed text appear (flushed on the 80ms timer).
+ await waitFor(() => expect(screen.getByText('Thinking')).toBeTruthy());
+ await waitFor(() => expect(screen.getByText(/reasoning step one reasoning step two/)).toBeTruthy());
+ // The streaming answer renders the content channel only — reasoning isn't mixed in.
+ await waitFor(() => expect(screen.getByText('Final answer.')).toBeTruthy());
+
+ releaseRun();
+ });
});
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index 0214bdfa5c..f9a2f8fbd7 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -66,8 +66,10 @@ 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
+// NDJSON response body so `onToken(delta, kind)` fires per chunk for live
+// rendering — kind is 'content' or 'reasoning' so the caller can render a
+// reasoning model's chain-of-thought on its own channel. 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).
@@ -98,7 +100,7 @@ export async function streamLocalLlmTest(payload, { signal, onToken } = {}) {
if (!trimmed) return;
let frame;
try { frame = JSON.parse(trimmed); } catch { return; }
- if (frame.type === 'token') onToken?.(frame.delta || '');
+ if (frame.type === 'token') onToken?.(frame.delta || '', frame.kind || 'content');
else if (frame.type === 'result') result = frame.result;
};
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index ff4ba570a2..533ec2fa3a 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -234,7 +234,8 @@ router.post('/test', asyncHandler(async (req, 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
+// can render live. Frames: `{ type: 'token', delta, kind }` per chunk (kind is
+// 'content' or 'reasoning' so the client can render thinking separately), 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
@@ -273,7 +274,7 @@ router.post('/test/stream', asyncHandler(async (req, res) => {
const result = await runLocalLlmTest({
...body,
signal: abortSignalFromResponse(res),
- onToken: (delta) => (delta ? write({ type: 'token', delta }) : undefined),
+ onToken: (delta, kind = 'content') => (delta ? write({ type: 'token', delta, kind }) : undefined),
}).catch((err) => ({
backend: body.backend,
modelId: body.modelId,
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index 11410d0359..b0b9eb2c5a 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -90,12 +90,32 @@ describe('local LLM playground routes', () => {
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: 'token', delta: 'Hel', kind: 'content' },
+ { type: 'token', delta: 'lo', kind: 'content' },
{ type: 'result', result: { backend: 'ollama', modelId: 'llama3.2', text: 'Hello', runId: 'run-1' } },
]);
});
+ it('tags reasoning tokens with kind:reasoning so the client can render them separately', async () => {
+ runLocalLlmTest.mockImplementation(async ({ onToken }) => {
+ onToken('thinking…', 'reasoning');
+ onToken('Answer.', 'content');
+ return { backend: 'ollama', modelId: 'deepseek-r1', text: 'Answer.', runId: 'run-2' };
+ });
+
+ const res = await request(makeApp())
+ .post('/api/local-llm/test/stream')
+ .send({ backend: 'ollama', modelId: 'deepseek-r1', prompt: 'Think then answer' });
+
+ expect(res.status).toBe(200);
+ const frames = res.text.trim().split('\n').map((l) => JSON.parse(l));
+ expect(frames).toEqual([
+ { type: 'token', delta: 'thinking…', kind: 'reasoning' },
+ { type: 'token', delta: 'Answer.', kind: 'content' },
+ { type: 'result', result: { backend: 'ollama', modelId: 'deepseek-r1', text: 'Answer.', runId: 'run-2' } },
+ ]);
+ });
+
it('emits exactly one terminal result frame (no extra 500) when the run resolves an in-stream error', async () => {
// A timed-out/aborted run resolves an { error, text } result rather than
// throwing — the route must surface it as the single terminal frame.
diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.js
index 431e66199f..bef738497c 100644
--- a/server/services/localLlmPlayground.js
+++ b/server/services/localLlmPlayground.js
@@ -133,7 +133,7 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, system
throw new Error(`Provider returned a non-JSON response (${response.status})`);
}
const text = data.choices?.[0]?.message?.content || '';
- if (text) await onChunk(text);
+ if (text) await onChunk(text, 'content');
return text;
}
@@ -148,9 +148,17 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, system
if (!delta) return;
if (delta.content) {
output += delta.content;
- await onChunk(delta.content);
+ await onChunk(delta.content, 'content');
+ }
+ // Stream reasoning live too, on its own channel, so a reasoning-only model
+ // (deepseek-r1, qwq, …) renders its chain-of-thought as it arrives instead
+ // of sitting on "Waiting for the first token…" until the whole run lands.
+ // Kept distinct from content so the live panel can label it and so the
+ // final content-only `text` doesn't inherit reasoning prose.
+ if (delta.reasoning) {
+ reasoning += delta.reasoning;
+ await onChunk(delta.reasoning, 'reasoning');
}
- if (delta.reasoning) reasoning += delta.reasoning;
};
// Always release the reader (and tear down the socket) on every exit path —
@@ -175,9 +183,10 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, system
await reader.cancel().catch(() => {});
}
- const resolved = resolvePartialOutput({ output, reasoning });
- if (resolved && resolved !== output) await onChunk(resolved);
- return resolved;
+ // Both channels already streamed live via onChunk, so there's no end-of-stream
+ // re-emit here — re-pushing `resolved` would double the reasoning-only output
+ // the client just received. We only resolve the final text for the result record.
+ return resolvePartialOutput({ output, reasoning });
}
export async function runLocalLlmTest({
@@ -189,9 +198,11 @@ 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.
+ // Optional per-token callback `onToken(delta, kind)` where kind is 'content'
+ // or 'reasoning'. When provided (streaming route), each delta is forwarded as
+ // it arrives so the client can render live output (reasoning on its own
+ // channel). The returned result is unchanged, so non-streaming callers ignore
+ // this entirely.
onToken,
}) {
const provider = await resolveLocalProvider(backend);
@@ -230,12 +241,16 @@ export async function runLocalLlmTest({
temperature,
maxTokens,
signal,
- onChunk: (chunk) => {
+ onChunk: (chunk, kind = 'content') => {
+ // First token of EITHER channel marks TTFT: for a reasoning model the
+ // first thing it emits is reasoning, so timing it from that chunk is the
+ // honest time-to-first-token (previously reasoning-only runs reported a
+ // null TTFT because reasoning never reached this callback).
if (!firstChunkAt && chunk) firstChunkAt = Date.now();
// Await the consumer so socket backpressure from the streaming route
// propagates back up to the upstream read loop (pauses reading until the
// client drains). Non-streaming callers pass no onToken, so this no-ops.
- if (chunk) return onToken?.(chunk);
+ if (chunk) return onToken?.(chunk, kind);
return undefined;
},
}).finally(() => clearTimeout(timeoutHandle));
@@ -257,8 +272,8 @@ export async function runLocalLlmTest({
// A timeout/abort mid-stream still has tokens worth keeping — surface what the
// model already streamed (attached to the error by streamChatCompletion) instead
// of discarding it. Persist it on the failed run record too so /runs replay shows it.
- // (TTFT is best-effort here: a reasoning-only partial leaves firstChunkAt unset,
- // since reasoning deltas don't mark first-chunk timing during the stream.)
+ // (TTFT is recorded even for a reasoning-only partial now, since reasoning deltas
+ // mark first-chunk timing too.)
const partialText = typeof err?.partialOutput === 'string' ? err.partialOutput : '';
if (runId) {
await finalizeRunRecord({
diff --git a/server/services/localLlmPlayground.test.js b/server/services/localLlmPlayground.test.js
index 4d14f691f0..2c12fb1a20 100644
--- a/server/services/localLlmPlayground.test.js
+++ b/server/services/localLlmPlayground.test.js
@@ -172,13 +172,63 @@ describe('runLocalLlmTest timeout/abort contract', () => {
const result = await runLocalLlmTest({
backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000,
- onToken: (delta) => tokens.push(delta),
+ onToken: (delta, kind) => tokens.push([delta, kind]),
});
- expect(tokens).toEqual(['Hel', 'lo']);
+ expect(tokens).toEqual([['Hel', 'content'], ['lo', 'content']]);
expect(result.text).toBe('Hello');
});
+ it('forwards reasoning deltas live on the reasoning channel, content on the content channel', async () => {
+ stubStream(makeReader([
+ sse({ reasoning: 'let me ' }),
+ sse({ reasoning: 'think…' }),
+ sse({ content: 'Answer.' }),
+ ], { abort: false }));
+ const tokens = [];
+
+ const result = await runLocalLlmTest({
+ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000,
+ onToken: (delta, kind) => tokens.push([delta, kind]),
+ });
+
+ expect(tokens).toEqual([
+ ['let me ', 'reasoning'],
+ ['think…', 'reasoning'],
+ ['Answer.', 'content'],
+ ]);
+ // The final text is content-only — reasoning streamed live but doesn't pollute the answer.
+ expect(result.text).toBe('Answer.');
+ });
+
+ it('does NOT re-emit a reasoning-only stream at the end (no double output)', async () => {
+ stubStream(makeReader([sse({ reasoning: 'thinking ' }), sse({ reasoning: 'aloud' })], { abort: false }));
+ const tokens = [];
+
+ const result = await runLocalLlmTest({
+ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000,
+ onToken: (delta, kind) => tokens.push([delta, kind]),
+ });
+
+ // Exactly two reasoning tokens — the old end-of-stream onChunk(resolved) re-emit
+ // would have appended the whole joined reasoning a third time.
+ expect(tokens).toEqual([['thinking ', 'reasoning'], ['aloud', 'reasoning']]);
+ // The reasoning-only run still resolves its text from reasoning for the record.
+ expect(result.text).toBe('thinking aloud');
+ });
+
+ it('records TTFT for a reasoning-only run (reasoning marks first-chunk timing)', async () => {
+ stubStream(makeReader([sse({ reasoning: 'hmm' })], { abort: false }));
+
+ const result = await runLocalLlmTest({
+ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000,
+ onToken: () => {},
+ });
+
+ expect(result.timings.ttftMs).not.toBeNull();
+ expect(result.timings.ttftMs).toBeGreaterThanOrEqual(0);
+ });
+
it('awaits onToken before reading the next upstream chunk (honours backpressure)', async () => {
const reader = makeReader([sse({ content: 'a' }), sse({ content: 'b' })], { abort: false });
stubStream(reader);