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

address review (self): harden Local LLM playground (nav, scroll, clipboard, SSE)

[._.]/ Adam Eivyf44479369360
diff --git a/PLAN.md b/PLAN.md
index 698b0e7865..eaee54167d 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -180,6 +180,12 @@ Surfaced while building the sync-hygiene feature. Consciously scoped out of v1.
- [ ] [migration-043-line-ending-precedent] **Migration 043 (story-builder prompts) is first-shipment-only — no OLD_SHIPPED_MD5 hashing.** Correct today (the prompts haven't shipped to anyone). But the precedent matters: when a future migration AMENDS these prompts, follow migration 003's pattern — normalize line endings before hashing, and ship both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5`. Add a one-line reminder comment to the migration. (local-review SS-3, 2026-05-27).
- [ ] [style-probe-image-uses-draft-not-saved] **`<StyleProbeImage>` in Universe Builder renders against the in-memory draft but persists the resulting filename to the SERVER's saved record.** A probe image semantically built from in-progress styleNotes/influences gets pinned to a saved universe whose actual style fields are still on the prior values; once the user discards the draft, the styleImageRefs persists on a record that never had those style notes. Either gate `canRender` on `!draftDirty`, or warn when the draft has uncommitted style changes. (local-review C-5, 2026-05-27).
+### Local LLM Playground — deferred follow-ups (2026-05-31)
+
+- [ ] [llm-playground-preserve-partial-output] **A timed-out / aborted playground run discards everything the model already streamed.** `streamChatCompletion` (`server/services/localLlmPlayground.js`) accumulates `output` locally; on an `AbortError` it throws, the `runLocalLlmTest` catch returns `text: ''`, and `ResultPanel` (`client/src/pages/LocalLlmPlayground.jsx`) shows only the error (the `result.error ? <error> : <pre>{result.text}</pre>` branch hides text whenever error is set). Surface the partial stream: thread the accumulated text out of the throw (or accumulate it in `runLocalLlmTest`'s `onChunk`) and render it alongside the timeout error. Deferred — needs a UI change to show partial-text-plus-error, not just a server tweak. (local-review SS, 2026-05-31).
+- [ ] [llm-playground-cancel-in-flight] **No way to cancel an in-flight playground run (up to a 10-minute timeout).** The Run button only locks via `busy`; there's no client `AbortController` / Cancel affordance. Add a Cancel button wired to a client-side `AbortController` passed into `testLocalLlmModel`/`compareLocalLlmModels` (the request options already spread through `apiCore`); aborting the client fetch also closes the server reader early. Deferred as a UX feature, not a bug. (local-review CT, 2026-05-31).
+- [ ] [llm-playground-shared-target-key] **The `${backend}\n${modelId}` compare-target key is hand-inlined ~5×.** It appears in `LocalLlmTab.jsx` (compareTargetKeys, toggleCompareTarget, the delete-prune, the checkbox `checked`) and is re-implemented as `targetKey()` in `LocalLlmPlayground.jsx`. Extract a single `localLlmTargetKey({backend, modelId})` helper both files import, so the URL round-trip can't desync on a delimiter change. Deferred only because a new `client/src/lib` module triggers the barrel + README maintenance rule; fold it in next time either file is touched. (local-review SQ, 2026-05-31).
+
## Deferred
- [ ] [runs-route-fallback-model-tests] **Add a route-level test harness for `POST /api/runs` fallback-model execution.** `server/lib/aiToolkit/routes/runs.js` now derives `runModel` from `runData.usedFallback`/`fallbackModel` so an API/TUI/CLI fallback runs the fallback's model rather than leaking the primary's request model. There is currently no route-test harness anywhere in the repo (no supertest, no httpMocks), so this path is only covered transitively via the `createRun`/`getFallbackProvider` unit tests. Stand up a minimal route harness (fake `runnerService` with spied `createRun`/`executeApiRun`/`executeCliRun`/`executeTuiRun`) and assert: (a) non-fallback runs pass the request `model` unchanged for all three types; (b) a fallback swap with a configured `fallbackModel` runs that model on API (3rd arg), TUI (cloned `defaultModel`), and CLI (cloned `defaultModel`); (c) a fallback swap with no pin runs the fallback provider's own `defaultModel`, never the primary's model id. Skipped here to avoid building a route harness from scratch inside a bugfix PR.
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index d3065165f6..34a3a35bc4 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -1034,6 +1034,7 @@ export default function Layout() {
location.pathname.startsWith('/meatspace') ||
location.pathname.startsWith('/media') ||
location.pathname.startsWith('/messages') ||
+ location.pathname.startsWith('/local-llm/') ||
location.pathname.startsWith('/pipeline/issues/') ||
location.pathname.startsWith('/pipeline/series/') ||
location.pathname.startsWith('/post') ||
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index 100953d890..f0ca01202b 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -394,7 +394,15 @@ export function LocalLlmTab() {
clearConfirm: false
}
);
- const remove = (modelId) => runAction(`delete-${modelId}`, () => deleteLocalLlmModel(selected, modelId), `${modelId} deleted`);
+ const remove = (modelId) => runAction(`delete-${modelId}`, () => deleteLocalLlmModel(selected, modelId), `${modelId} deleted`)
+ .then((result) => {
+ // Drop the just-deleted model from any pending comparison (runAction
+ // resolves undefined on failure, so only prune on a real success) — else
+ // openCompare ships a dead modelId the playground would error on.
+ if (!result) return;
+ const key = `${selected}\n${modelId}`;
+ setCompareTargets((prev) => prev.filter((t) => `${t.backend}\n${t.modelId}` !== key));
+ });
const toggleCompareTarget = (backend, modelId) => {
const key = `${backend}\n${modelId}`;
setCompareTargets((prev) => {
diff --git a/client/src/pages/LocalLlmPlayground.jsx b/client/src/pages/LocalLlmPlayground.jsx
index c76fba5222..8e8da9c42d 100644
--- a/client/src/pages/LocalLlmPlayground.jsx
+++ b/client/src/pages/LocalLlmPlayground.jsx
@@ -1,8 +1,9 @@
-import { useCallback, useEffect, useMemo, useState } from 'react';
+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 BrailleSpinner from '../components/BrailleSpinner';
import toast from '../components/ui/Toast';
+import { copyToClipboard } from '../lib/clipboard';
import { compareLocalLlmModels, getLocalLlmStatus, testLocalLlmModel } from '../services/api';
const BACKEND_LABEL = { ollama: 'Ollama', lmstudio: 'LM Studio' };
@@ -23,6 +24,15 @@ function targetKey(target) {
return `${target.backend}\n${target.modelId}`;
}
+// Number inputs hold raw strings; an emptied field is '' and `Number('')` is 0,
+// which would silently send temperature 0 or fail maxTokens' min(1) server-side.
+// Fall back to the field's default when the value isn't a finite, non-empty number.
+function numOr(value, fallback) {
+ if (value === '' || value == null) return fallback;
+ const n = Number(value);
+ return Number.isFinite(n) ? n : fallback;
+}
+
function parseTargetsParam(searchParams) {
const rawTargets = searchParams.get('targets');
if (rawTargets) {
@@ -88,7 +98,7 @@ function ResultPanel({ result }) {
)}
{result.text && (
<button
- onClick={() => navigator.clipboard?.writeText(result.text).then(() => toast.success('Copied output')).catch(() => toast.error('Copy failed'))}
+ onClick={() => copyToClipboard(result.text, 'Copied output')}
className="text-xs text-gray-400 hover:text-white flex items-center gap-1"
>
<Copy size={12} />
@@ -117,6 +127,9 @@ export default function LocalLlmPlayground() {
const [chatResults, setChatResults] = useState([]);
const [compareResult, setCompareResult] = useState(null);
+ const mountedRef = useRef(true);
+ useEffect(() => () => { mountedRef.current = false; }, []);
+
const loadStatus = useCallback(() => {
setLoadingStatus(true);
setModelLoadError('');
@@ -162,9 +175,9 @@ export default function LocalLlmPlayground() {
const options = () => ({
systemPrompt,
- temperature: Number(temperature),
- maxTokens: Number(maxTokens),
- timeoutMs: Number(timeoutMs),
+ temperature: numOr(temperature, 0.3),
+ maxTokens: numOr(maxTokens, 1000),
+ timeoutMs: numOr(timeoutMs, 300000),
});
const runChat = () => {
@@ -173,11 +186,12 @@ export default function LocalLlmPlayground() {
const target = primaryTarget;
testLocalLlmModel({ ...target, prompt: prompt.trim(), ...options() }, { silent: true })
.then((result) => {
+ if (!mountedRef.current) return;
setChatResults((prev) => [result, ...prev]);
if (result.error) toast.error(result.error);
})
- .catch((err) => toast.error(err?.message || 'Model test failed'))
- .finally(() => setBusy(false));
+ .catch((err) => { if (mountedRef.current) toast.error(err?.message || 'Model test failed'); })
+ .finally(() => { if (mountedRef.current) setBusy(false); });
};
const runCompare = () => {
@@ -191,11 +205,12 @@ export default function LocalLlmPlayground() {
options: options(),
}, { silent: true })
.then((result) => {
+ if (!mountedRef.current) return;
setCompareResult(result);
if ((result.results || []).some((r) => r.error)) toast.error('Some model runs failed');
})
- .catch((err) => toast.error(err?.message || 'Comparison failed'))
- .finally(() => setBusy(false));
+ .catch((err) => { if (mountedRef.current) toast.error(err?.message || 'Comparison failed'); })
+ .finally(() => { if (mountedRef.current) setBusy(false); });
};
return (
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 62988a8680..656080e3e2 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -137,6 +137,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.settings.embeddings', path: '/settings/embeddings', label: 'Embeddings', section: 'Settings', aliases: ['settings-embeddings', 'embeddings', 'embedding'], keywords: ['vector', 'pgvector', 'semantic search', 'nomic', 'ollama', 'lm studio'] },
{ id: 'nav.settings.general', path: '/settings/general', label: 'General', section: 'Settings', aliases: ['settings', 'settings-general', 'general'] },
{ id: 'nav.settings.local-llm', path: '/settings/local-llm', label: 'Local LLMs', section: 'Settings', aliases: ['local-llm', 'local-llms', 'ollama', 'lm-studio', 'lmstudio'], keywords: ['ollama', 'lm studio', 'local model', 'local llm', 'gguf', 'pull model', 'install model', 'migrate', 'switch backend'] },
+ { id: 'nav.settings.local-llm-playground', path: '/local-llm/playground', label: 'Local LLM Playground', section: 'Settings', aliases: ['llm-playground', 'playground', 'model-playground', 'compare-models'], keywords: ['ollama', 'lm studio', 'compare', 'benchmark', 'chat', 'test model', 'ttft', 'tokens per second', 'local llm'] },
{ id: 'nav.settings.mortalloom', path: '/settings/mortalloom', label: 'MortalLoom', section: 'Settings', aliases: ['settings-mortalloom', 'mortalloom'] },
{ id: 'nav.settings.sharing', path: '/settings/sharing', label: 'Sharing', section: 'Settings', aliases: ['settings-sharing', 'sharing-settings'], keywords: ['display name', 'bio', 'attribution', 'identity', 'source'] },
{ id: 'nav.settings.telegram', path: '/settings/telegram', label: 'Telegram', section: 'Settings', aliases: ['settings-telegram', 'telegram'] },
diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.js
index e2bc8fef0d..398b49ce42 100644
--- a/server/services/localLlmPlayground.js
+++ b/server/services/localLlmPlayground.js
@@ -7,28 +7,54 @@ import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManage
const PROVIDER_BY_BACKEND = { ollama: 'ollama', lmstudio: 'lmstudio' };
-function buildPrompt({ systemPrompt, prompt }) {
+// Human-readable record of what was asked, stored on the run for /runs replay.
+// This is NOT the wire format — the API receives the structured `buildMessages`
+// array; the synthetic "System instructions:/User prompt:" framing here exists
+// only so the run viewer shows one readable blob.
+export function buildPrompt({ systemPrompt, prompt }) {
const system = String(systemPrompt || '').trim();
if (!system) return prompt;
return `System instructions:\n${system}\n\nUser prompt:\n${prompt}`;
}
-function summarizeTimings({ startedAt, firstChunkAt, endedAt, text }) {
+export function summarizeTimings({ startedAt, firstChunkAt, endedAt, text }) {
const totalMs = endedAt - startedAt;
const ttftMs = firstChunkAt ? firstChunkAt - startedAt : null;
const chars = text.length;
- const charsPerSecond = totalMs > 0 ? chars / (totalMs / 1000) : chars;
+ // A sub-millisecond total makes a rate meaningless — report n/a (null)
+ // rather than `chars`, which would surface the char COUNT as a chars/sec rate.
+ const charsPerSecond = totalMs > 0 ? Number((chars / (totalMs / 1000)).toFixed(2)) : null;
return {
startedAt: new Date(startedAt).toISOString(),
endedAt: new Date(endedAt).toISOString(),
ttftMs,
totalMs,
chars,
- charsPerSecond: Number(charsPerSecond.toFixed(2)),
+ charsPerSecond,
};
}
-function buildMessages({ systemPrompt, prompt }) {
+// Parse one OpenAI-style SSE `data:` line into its content/reasoning delta.
+// Returns null for non-data lines, the [DONE]/✅ sentinels, or a malformed
+// frame: a single bad frame must SKIP, not abort the stream — one non-JSON
+// keep-alive would otherwise throw out of the read loop and discard every
+// token already received.
+export function extractStreamDelta(rawLine) {
+ const line = rawLine.trim();
+ if (!line.startsWith('data: ')) return null;
+ const data = line.slice(6).trim();
+ if (!data || data === '[DONE]' || data === '✅') return null;
+ let parsed;
+ try {
+ parsed = JSON.parse(data);
+ } catch {
+ return null;
+ }
+ const delta = parsed?.choices?.[0]?.delta;
+ return { content: delta?.content || '', reasoning: delta?.reasoning || '' };
+}
+
+export function buildMessages({ systemPrompt, prompt }) {
const system = String(systemPrompt || '').trim();
return [
...(system ? [{ role: 'system', content: system }] : []),
@@ -98,29 +124,30 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, system
let reasoning = '';
const consumeLine = (rawLine) => {
- const line = rawLine.trim();
- if (!line.startsWith('data: ')) return;
- const data = line.slice(6).trim();
- if (!data || data === '[DONE]' || data === '✅') return;
- const parsed = JSON.parse(data);
- const delta = parsed?.choices?.[0]?.delta;
- const text = delta?.content || '';
- if (text) {
- output += text;
- onChunk(text);
+ const delta = extractStreamDelta(rawLine);
+ if (!delta) return;
+ if (delta.content) {
+ output += delta.content;
+ onChunk(delta.content);
}
- if (delta?.reasoning) reasoning += delta.reasoning;
+ if (delta.reasoning) reasoning += delta.reasoning;
};
- while (true) {
- 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) consumeLine(line);
+ // Always release the reader (and tear down the socket) on every exit path —
+ // a normal finish, an abort via the timeout signal, or a throw mid-stream.
+ try {
+ while (true) {
+ 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) consumeLine(line);
+ }
+ if (buffer.trim()) consumeLine(buffer);
+ } finally {
+ await reader.cancel().catch(() => {});
}
- if (buffer.trim()) consumeLine(buffer);
if (!output.trim() && reasoning.trim()) {
output = reasoning;
diff --git a/server/services/localLlmPlayground.test.js b/server/services/localLlmPlayground.test.js
new file mode 100644
index 0000000000..288bfc34e4
--- /dev/null
+++ b/server/services/localLlmPlayground.test.js
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest';
+import { buildPrompt, buildMessages, summarizeTimings, extractStreamDelta } from './localLlmPlayground.js';
+
+describe('buildPrompt', () => {
+ it('returns the bare prompt when no system instructions', () => {
+ expect(buildPrompt({ systemPrompt: '', prompt: 'hi' })).toBe('hi');
+ expect(buildPrompt({ systemPrompt: ' ', prompt: 'hi' })).toBe('hi');
+ });
+
+ it('prefixes a labeled system block when present (display format, not wire)', () => {
+ expect(buildPrompt({ systemPrompt: 'Be terse', prompt: 'hi' }))
+ .toBe('System instructions:\nBe terse\n\nUser prompt:\nhi');
+ });
+});
+
+describe('buildMessages', () => {
+ it('omits the system message when blank', () => {
+ expect(buildMessages({ systemPrompt: ' ', prompt: 'hi' })).toEqual([
+ { role: 'user', content: 'hi' },
+ ]);
+ });
+
+ it('includes a system message when present', () => {
+ expect(buildMessages({ systemPrompt: 'Be terse', prompt: 'hi' })).toEqual([
+ { role: 'system', content: 'Be terse' },
+ { role: 'user', content: 'hi' },
+ ]);
+ });
+});
+
+describe('summarizeTimings', () => {
+ it('computes ttft, total, and rate', () => {
+ const t = summarizeTimings({ startedAt: 1000, firstChunkAt: 1200, endedAt: 3000, text: 'abcdefghij' });
+ expect(t.ttftMs).toBe(200);
+ expect(t.totalMs).toBe(2000);
+ expect(t.chars).toBe(10);
+ expect(t.charsPerSecond).toBe(5); // 10 chars / 2s
+ });
+
+ it('reports null ttft when no chunk ever arrived', () => {
+ const t = summarizeTimings({ startedAt: 1000, firstChunkAt: null, endedAt: 2000, text: '' });
+ expect(t.ttftMs).toBeNull();
+ });
+
+ it('reports null rate (not a char count) for a zero-duration run', () => {
+ const t = summarizeTimings({ startedAt: 1000, firstChunkAt: 1000, endedAt: 1000, text: 'hello' });
+ expect(t.totalMs).toBe(0);
+ expect(t.charsPerSecond).toBeNull();
+ });
+});
+
+describe('extractStreamDelta', () => {
+ it('parses an OpenAI-style content delta', () => {
+ const line = 'data: {"choices":[{"delta":{"content":"Hi"}}]}';
+ expect(extractStreamDelta(line)).toEqual({ content: 'Hi', reasoning: '' });
+ });
+
+ it('parses a reasoning delta', () => {
+ const line = 'data: {"choices":[{"delta":{"reasoning":"thinking"}}]}';
+ expect(extractStreamDelta(line)).toEqual({ content: '', reasoning: 'thinking' });
+ });
+
+ it('skips non-data lines and the [DONE]/✅ sentinels', () => {
+ expect(extractStreamDelta(': keep-alive')).toBeNull();
+ expect(extractStreamDelta('data: [DONE]')).toBeNull();
+ expect(extractStreamDelta('data: ✅')).toBeNull();
+ expect(extractStreamDelta('')).toBeNull();
+ });
+
+ it('skips a malformed frame instead of throwing (one bad frame must not abort the stream)', () => {
+ expect(extractStreamDelta('data: {not json')).toBeNull();
+ });
+
+ it('tolerates a frame with no delta', () => {
+ expect(extractStreamDelta('data: {"choices":[{}]}')).toEqual({ content: '', reasoning: '' });
+ });
+});