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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Add local LLM playground
[._.]/ Adam Eivy319ef951001a
diff --git a/client/src/App.jsx b/client/src/App.jsxindex 7990555b6d..610f075d9b 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -60,6 +60,7 @@ const DigitalTwin = lazyWithReload(() => import('./pages/DigitalTwin'));const Agents = lazyWithReload(() => import('./pages/Agents'));const Uploads = lazyWithReload(() => import('./pages/Uploads'));const Settings = lazyWithReload(() => import('./pages/Settings'));+const LocalLlmPlayground = lazyWithReload(() => import('./pages/LocalLlmPlayground'));const Shell = lazyWithReload(() => import('./pages/Shell'));const BrowserPage = lazyWithReload(() => import('./pages/Browser'));const Jira = lazyWithReload(() => import('./pages/Jira'));@@ -195,6 +196,7 @@ export default function App() {<Route path="security" element={<Security />} /><Route path="settings" element={<Navigate to="/settings/backup" replace />} /><Route path="settings/:tab" element={<Settings />} />+ <Route path="local-llm/playground" element={<LocalLlmPlayground />} /><Route path="uploads" element={<Uploads />} /><Route path="shell" element={<Shell />} /><Route path="shell/:sessionId" element={<Shell />} />diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 6ee7b02ec5..100953d890 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -1,5 +1,6 @@import { useState, useEffect, useRef, useCallback, useMemo } from 'react';-import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Square, Power, PowerOff, Eye, Wrench, Brain, Code2, MessageSquare, Boxes, AlertTriangle } from 'lucide-react';+import { Link, useNavigate } from 'react-router-dom';+import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Square, Power, PowerOff, Eye, Wrench, Brain, Code2, MessageSquare, Boxes, AlertTriangle, FlaskConical } from 'lucide-react';import toast from '../ui/Toast';import BrailleSpinner from '../BrailleSpinner';import { formatBytes, timeAgo } from '../../utils/formatters';@@ -214,6 +215,7 @@ function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAc}export function LocalLlmTab() {+ const navigate = useNavigate();const [status, setStatus] = useState(null);const [loading, setLoading] = useState(true);const [selected, setSelected] = useState('ollama');@@ -230,6 +232,7 @@ export function LocalLlmTab() {// id of the installed model awaiting a delete confirmation (two-step inline// confirm — deleting weights is an irreversible multi-GB rm -rf / DELETE).const [confirmDeleteId, setConfirmDeleteId] = useState(null);+ const [compareTargets, setCompareTargets] = useState([]);const progressTimer = useRef(null);const statusRequestId = useRef(0);const catalogRequestId = useRef(0);@@ -341,6 +344,7 @@ export function LocalLlmTab() {const selectedOllamaStartupAction = selectedData?.service?.supported ? 'enable' : 'start';const selectedOllamaStartupLabel = selectedData?.service?.supported ? 'Run at Startup' : 'Start Ollama';const installedModels = selectedData?.models || [];+ const compareTargetKeys = useMemo(() => new Set(compareTargets.map((t) => `${t.backend}\n${t.modelId}`)), [compareTargets]);const catalogCategories = useMemo(() => {const counts = new Map();for (const model of catalog) counts.set(model.category || 'chat', (counts.get(model.category || 'chat') || 0) + 1);@@ -391,6 +395,25 @@ export function LocalLlmTab() {});const remove = (modelId) => runAction(`delete-${modelId}`, () => deleteLocalLlmModel(selected, modelId), `${modelId} deleted`);+ const toggleCompareTarget = (backend, modelId) => {+ const key = `${backend}\n${modelId}`;+ setCompareTargets((prev) => {+ if (prev.some((t) => `${t.backend}\n${t.modelId}` === key)) {+ return prev.filter((t) => `${t.backend}\n${t.modelId}` !== key);+ }+ if (prev.length >= 6) {+ toast.error('Compare up to 6 models at once');+ return prev;+ }+ return [...prev, { backend, modelId }];+ });+ };+ const openCompare = () => {+ const params = new URLSearchParams();+ params.set('targets', JSON.stringify(compareTargets));+ params.set('mode', 'compare');+ navigate(`/local-llm/playground?${params.toString()}`);+ };// Upgrade Ollama in place (direct .app download on macOS; brew elsewhere) and// retry the original model install once Ollama is back online. `upgradeFlow`@@ -727,11 +750,35 @@ export function LocalLlmTab() {{/* Installed models */}<div className="space-y-2 pt-2 border-t border-port-border/50">- <h3 className="text-xs font-medium text-gray-400">Installed on {labelFor(selected)} ({installedModels.length})</h3>+ <div className="flex items-center justify-between gap-3 flex-wrap">+ <h3 className="text-xs font-medium text-gray-400">Installed on {labelFor(selected)} ({installedModels.length})</h3>+ {compareTargets.length > 0 && (+ <div className="flex items-center gap-2">+ <span className="text-xs text-gray-500">{compareTargets.length} selected</span>+ <button+ onClick={openCompare}+ disabled={compareTargets.length < 2}+ className="px-2.5 py-1 text-xs bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded disabled:opacity-50 flex items-center gap-1"+ >+ <ArrowRightLeft size={12} />+ Compare selected+ </button>+ </div>+ )}+ </div>{installedModels.length === 0 ? (<p className="text-xs text-gray-500">No models installed yet.</p>) : installedModels.map((m) => (<div key={m.id} className="flex items-center gap-3 bg-port-bg border border-port-border rounded-lg p-3">+ <label className="shrink-0 flex items-center" title={`Include ${m.name || m.id} in a comparison`}>+ <input+ type="checkbox"+ checked={compareTargetKeys.has(`${selected}\n${m.id}`)}+ onChange={() => toggleCompareTarget(selected, m.id)}+ className="h-4 w-4 accent-port-accent"+ aria-label={`Select ${m.name || m.id} for comparison`}+ />+ </label><div className="flex-1 min-w-0"><div className="text-sm text-white truncate">{m.name}</div><div className="text-xs text-gray-500 truncate">@@ -739,6 +786,14 @@ export function LocalLlmTab() {</div></div>{m.size != null && <span className="text-xs text-gray-400 shrink-0">{formatBytes(m.size)}</span>}+ <Link+ to={`/local-llm/playground?backend=${encodeURIComponent(selected)}&model=${encodeURIComponent(m.id)}`}+ className="px-2.5 py-1 text-xs bg-emerald-500/15 hover:bg-emerald-500/25 text-emerald-300 rounded flex items-center gap-1 shrink-0 no-underline"+ title={`Chat with ${m.name || m.id}`}+ >+ <FlaskConical size={12} />+ Chat+ </Link>{confirmDeleteId === m.id ? (<div className="flex items-center gap-1.5 shrink-0"><span className="text-xs text-port-error">Delete?</span>diff --git a/client/src/pages/LocalLlmPlayground.jsx b/client/src/pages/LocalLlmPlayground.jsxnew file mode 100644index 0000000000..c76fba5222--- /dev/null+++ b/client/src/pages/LocalLlmPlayground.jsx@@ -0,0 +1,365 @@+import { useCallback, useEffect, useMemo, 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 { compareLocalLlmModels, getLocalLlmStatus, testLocalLlmModel } 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.';++function formatMs(ms) {+ if (ms == null) return 'n/a';+ if (ms < 1000) return `${Math.round(ms)} ms`;+ return `${(ms / 1000).toFixed(2)} s`;+}++function formatRate(value) {+ if (!Number.isFinite(value)) return 'n/a';+ return `${value.toFixed(value >= 10 ? 1 : 2)} chars/s`;+}++function targetKey(target) {+ return `${target.backend}\n${target.modelId}`;+}++function parseTargetsParam(searchParams) {+ const rawTargets = searchParams.get('targets');+ if (rawTargets) {+ try {+ const parsed = JSON.parse(rawTargets);+ if (Array.isArray(parsed)) {+ return parsed+ .filter((t) => (t.backend === 'ollama' || t.backend === 'lmstudio') && typeof t.modelId === 'string' && t.modelId)+ .slice(0, 6);+ }+ } catch {+ return [];+ }+ }++ const backend = searchParams.get('backend');+ const modelId = searchParams.get('model');+ if ((backend === 'ollama' || backend === 'lmstudio') && modelId) return [{ backend, modelId }];+ return [];+}++function Metric({ icon: Icon, label, value }) {+ return (+ <div className="flex items-center gap-1.5 text-xs text-gray-400">+ <Icon size={13} className="text-gray-500" />+ <span>{label}</span>+ <span className="text-gray-200">{value}</span>+ </div>+ );+}++function ResultPanel({ result }) {+ const ok = !result?.error;+ return (+ <section className={`border rounded-lg bg-port-bg p-3 space-y-3 ${ok ? 'border-port-border' : 'border-port-error/40'}`}>+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="text-sm text-white truncate">{result.modelId}</div>+ <div className="text-xs text-gray-500">{BACKEND_LABEL[result.backend] || result.backend}</div>+ </div>+ <span className={`text-xs px-2 py-1 rounded ${ok ? 'bg-port-success/15 text-port-success' : 'bg-port-error/15 text-port-error'}`}>+ {ok ? 'Done' : 'Failed'}+ </span>+ </div>++ <div className="flex flex-wrap gap-x-4 gap-y-1">+ <Metric icon={Clock} label="TTFT" value={formatMs(result.timings?.ttftMs)} />+ <Metric icon={Gauge} label="Total" value={formatMs(result.timings?.totalMs)} />+ <Metric icon={MessageSquare} label="Speed" value={formatRate(result.timings?.charsPerSecond)} />+ </div>++ {result.error ? (+ <p className="text-sm text-port-error whitespace-pre-wrap">{result.error}</p>+ ) : (+ <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="flex items-center gap-2 flex-wrap">+ {result.runId && (+ <Link to={`/devtools/runs?run=${encodeURIComponent(result.runId)}`} className="text-xs text-port-accent hover:underline">+ Run {result.runId.slice(0, 8)}+ </Link>+ )}+ {result.text && (+ <button+ onClick={() => navigator.clipboard?.writeText(result.text).then(() => toast.success('Copied output')).catch(() => toast.error('Copy failed'))}+ className="text-xs text-gray-400 hover:text-white flex items-center gap-1"+ >+ <Copy size={12} />+ Copy+ </button>+ )}+ </div>+ </section>+ );+}++export default function LocalLlmPlayground() {+ const [searchParams] = useSearchParams();+ const [status, setStatus] = useState(null);+ const [loadingStatus, setLoadingStatus] = useState(true);+ const [modelLoadError, setModelLoadError] = useState('');+ const [selectedTargets, setSelectedTargets] = useState(() => parseTargetsParam(searchParams));+ const [activeMode, setActiveMode] = useState(() => searchParams.get('mode') === 'compare' ? 'compare' : 'chat');+ const [runMode, setRunMode] = useState('round-robin');+ const [prompt, setPrompt] = useState(DEFAULT_PROMPT);+ const [systemPrompt, setSystemPrompt] = useState('');+ const [temperature, setTemperature] = useState(0.3);+ const [maxTokens, setMaxTokens] = useState(1000);+ const [timeoutMs, setTimeoutMs] = useState(300000);+ const [busy, setBusy] = useState(false);+ const [chatResults, setChatResults] = useState([]);+ const [compareResult, setCompareResult] = useState(null);++ const loadStatus = useCallback(() => {+ setLoadingStatus(true);+ setModelLoadError('');+ return getLocalLlmStatus({ silent: true })+ .then(setStatus)+ .catch((err) => setModelLoadError(err?.message || 'Failed to load local models'))+ .finally(() => setLoadingStatus(false));+ }, []);++ useEffect(() => { loadStatus(); }, [loadStatus]);++ const installedTargets = useMemo(() => {+ const models = [];+ for (const backend of ['ollama', 'lmstudio']) {+ for (const model of status?.[backend]?.models || []) {+ models.push({ backend, modelId: model.id, name: model.name || model.id, meta: model });+ }+ }+ return models;+ }, [status]);++ useEffect(() => {+ if (selectedTargets.length > 0 || installedTargets.length === 0) return;+ setSelectedTargets([{ backend: installedTargets[0].backend, modelId: installedTargets[0].modelId }]);+ }, [installedTargets, selectedTargets.length]);++ const selectedKeys = useMemo(() => new Set(selectedTargets.map(targetKey)), [selectedTargets]);+ const primaryTarget = selectedTargets[0] || null;+ const canRunChat = Boolean(primaryTarget && prompt.trim());+ const canCompare = selectedTargets.length > 0 && prompt.trim();++ const toggleTarget = (target) => {+ const key = targetKey(target);+ setSelectedTargets((prev) => {+ if (prev.some((t) => targetKey(t) === key)) return prev.filter((t) => targetKey(t) !== key);+ if (prev.length >= 6) {+ toast.error('Compare up to 6 models at once');+ return prev;+ }+ return [...prev, { backend: target.backend, modelId: target.modelId }];+ });+ };++ const options = () => ({+ systemPrompt,+ temperature: Number(temperature),+ maxTokens: Number(maxTokens),+ timeoutMs: Number(timeoutMs),+ });++ const runChat = () => {+ if (!canRunChat) return;+ setBusy(true);+ const target = primaryTarget;+ testLocalLlmModel({ ...target, prompt: prompt.trim(), ...options() }, { silent: true })+ .then((result) => {+ setChatResults((prev) => [result, ...prev]);+ if (result.error) toast.error(result.error);+ })+ .catch((err) => toast.error(err?.message || 'Model test failed'))+ .finally(() => setBusy(false));+ };++ const runCompare = () => {+ if (!canCompare) return;+ setBusy(true);+ setCompareResult(null);+ compareLocalLlmModels({+ mode: runMode,+ prompt: prompt.trim(),+ targets: selectedTargets,+ options: options(),+ }, { silent: true })+ .then((result) => {+ 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));+ };++ return (+ <div className="flex flex-col h-full">+ <div className="flex items-center justify-between gap-3 p-4 border-b border-port-border">+ <div className="flex items-center gap-3 min-w-0">+ <Link to="/settings/local-llm" className="p-2 rounded-lg bg-port-card border border-port-border text-gray-400 hover:text-white" title="Back to Local LLMs">+ <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>+ </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">+ <RefreshCw size={16} className={loadingStatus ? 'animate-spin' : ''} />+ </button>+ </div>++ <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>+ {installedTargets.length === 0 && !loadingStatus ? (+ <p className={`text-sm ${modelLoadError ? 'text-port-warning' : 'text-gray-500'}`}>+ {modelLoadError || 'No installed local models found.'}+ </p>+ ) : (+ <div className="space-y-3">+ {['ollama', 'lmstudio'].map((backend) => {+ const models = installedTargets.filter((target) => target.backend === backend);+ if (models.length === 0) return null;+ return (+ <div key={backend} className="space-y-2">+ <div className="text-xs text-gray-500">{BACKEND_LABEL[backend]}</div>+ {models.map((target) => {+ const selected = selectedKeys.has(targetKey(target));+ return (+ <button+ key={targetKey(target)}+ onClick={() => toggleTarget(target)}+ className={`w-full min-h-12 flex items-center gap-2 rounded-lg border px-3 py-2 text-left transition-colors ${selected ? 'border-port-accent/60 bg-port-accent/10' : 'border-port-border bg-port-bg hover:border-gray-600'}`}+ >+ <span className={`w-5 h-5 rounded border flex items-center justify-center shrink-0 ${selected ? 'border-port-accent bg-port-accent/20 text-port-accent' : 'border-gray-600 text-transparent'}`}>+ <Check size={13} />+ </span>+ <span className="min-w-0">+ <span className="block text-sm text-white truncate">{target.name}</span>+ <span className="block text-xs text-gray-500 truncate">{target.modelId}</span>+ </span>+ </button>+ );+ })}+ </div>+ );+ })}+ </div>+ )}+ </aside>++ <main className="space-y-4">+ <section className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">+ <div className="flex items-center gap-2 flex-wrap">+ {[+ { id: 'chat', label: 'Chat', icon: MessageSquare },+ { id: 'compare', label: 'Compare', icon: ArrowRightLeft },+ ].map((tab) => {+ const Icon = tab.icon;+ return (+ <button+ key={tab.id}+ onClick={() => setActiveMode(tab.id)}+ className={`px-3 py-1.5 text-sm rounded-lg flex items-center gap-1.5 ${activeMode === tab.id ? 'bg-port-accent/20 text-port-accent' : 'bg-port-bg text-gray-400 hover:text-white'}`}+ >+ <Icon size={14} />+ {tab.label}+ </button>+ );+ })}+ </div>++ <div className="grid grid-cols-1 lg:grid-cols-[1fr_280px] gap-4">+ <div className="space-y-3">+ <label htmlFor="local-llm-system" className="block text-xs text-gray-500">System prompt</label>+ <textarea+ id="local-llm-system"+ value={systemPrompt}+ onChange={(e) => setSystemPrompt(e.target.value)}+ rows={3}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-port-accent resize-y"+ placeholder="Optional"+ />+ <label htmlFor="local-llm-prompt" className="block text-xs text-gray-500">Prompt</label>+ <textarea+ id="local-llm-prompt"+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ rows={7}+ className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white placeholder-gray-600 focus:outline-none focus:border-port-accent resize-y"+ />+ </div>++ <div className="space-y-3">+ <label className="block text-xs text-gray-500" htmlFor="local-llm-temperature">Temperature</label>+ <input id="local-llm-temperature" type="number" min="0" max="2" step="0.1" value={temperature} onChange={(e) => setTemperature(e.target.value)} className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white" />+ <label className="block text-xs text-gray-500" htmlFor="local-llm-max-tokens">Max tokens</label>+ <input id="local-llm-max-tokens" type="number" min="1" max="8192" step="64" value={maxTokens} onChange={(e) => setMaxTokens(e.target.value)} className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white" />+ <label className="block text-xs text-gray-500" htmlFor="local-llm-timeout">Timeout</label>+ <select id="local-llm-timeout" value={timeoutMs} onChange={(e) => setTimeoutMs(Number(e.target.value))} className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white">+ <option value={60000}>1 minute</option>+ <option value={180000}>3 minutes</option>+ <option value={300000}>5 minutes</option>+ <option value={600000}>10 minutes</option>+ </select>+ {activeMode === 'compare' && (+ <>+ <label className="block text-xs text-gray-500" htmlFor="local-llm-mode">Execution</label>+ <select id="local-llm-mode" value={runMode} onChange={(e) => setRunMode(e.target.value)} className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white">+ <option value="round-robin">Round robin</option>+ <option value="parallel">Parallel</option>+ </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>+ </div>+ </div>+ </section>++ {activeMode === 'chat' ? (+ <section className="space-y-3">+ {chatResults.length === 0 ? (+ <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.+ </div>+ ) : chatResults.map((result, idx) => <ResultPanel key={`${result.runId || idx}-${result.modelId}`} result={result} />)}+ </section>+ ) : (+ <section className="space-y-3">+ {compareResult ? (+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">+ {compareResult.results.map((result, idx) => <ResultPanel key={`${result.runId || idx}-${result.modelId}`} result={result} />)}+ </div>+ ) : (+ <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" />+ Select one or more models and run the same prompt through them.+ </div>+ )}+ </section>+ )}+ </main>+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex 3d3d837d38..c034f56046 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -58,3 +58,9 @@ export const unloadOllamaModel = (modelId, options) =>body: JSON.stringify({ backend: 'ollama', modelId }),...options,});++export const testLocalLlmModel = (payload, options) =>+ request('/local-llm/test', { method: 'POST', body: JSON.stringify(payload), ...options });++export const compareLocalLlmModels = (payload, options) =>+ request('/local-llm/compare', { method: 'POST', body: JSON.stringify(payload), ...options });diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 33f7df2c1c..d32bd47984 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1148,6 +1148,26 @@ export const localLlmHuggingFaceSearchSchema = z.object({category: z.string().max(40).optional().default('all'),limit: z.coerce.number().int().min(1).max(30).optional().default(12),});+export const localLlmPlaygroundOptionsSchema = z.object({+ systemPrompt: z.string().max(8000).optional().default(''),+ temperature: z.coerce.number().min(0).max(2).optional().default(0.3),+ maxTokens: z.coerce.number().int().min(1).max(8192).optional().default(1000),+ timeoutMs: z.coerce.number().int().min(1000).max(600000).optional().default(300000),+});+export const localLlmTestSchema = localLlmPlaygroundOptionsSchema.extend({+ backend: localLlmBackendSchema,+ modelId: localLlmModelIdSchema,+ prompt: z.string().trim().min(1).max(50000),+});+export const localLlmCompareSchema = z.object({+ mode: z.enum(['round-robin', 'parallel']).optional().default('round-robin'),+ prompt: z.string().trim().min(1).max(50000),+ targets: z.array(z.object({+ backend: localLlmBackendSchema,+ modelId: localLlmModelIdSchema,+ })).min(1).max(6),+ options: localLlmPlaygroundOptionsSchema.optional().default({}),+});/*** Validate data against a Zod schema, throwing on failure.diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 657a0396e5..fdd7e4791e 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -19,13 +19,16 @@ import {localLlmMigrateSchema,localLlmInstallBackendSchema,localLlmOllamaServiceSchema,- localLlmHuggingFaceSearchSchema+ localLlmHuggingFaceSearchSchema,+ localLlmTestSchema,+ localLlmCompareSchema} from '../lib/validation.js'import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'import { searchHuggingFaceModels } from '../services/huggingFaceCatalog.js'import {getStatus, listModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer} from '../services/localLlm.js'+import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js'import { getLoadedModels as getLoadedOllamaModels, unloadModel as unloadOllamaModel } from '../services/ollamaManager.js'const router = Router()@@ -219,4 +222,20 @@ router.post('/unload', asyncHandler(async (req, res) => {res.json({ success: true, ...result })}))+// POST /api/local-llm/test — run one installed local model with a prompt.+// Returns speed metrics and a run id so the playground can inspect output+// 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))+}))++// 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.+router.post('/compare', asyncHandler(async (req, res) => {+ const body = validateRequest(localLlmCompareSchema, req.body)+ res.json(await compareLocalLlmModels(body))+}))+export default routerdiff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.jsnew file mode 100644index 0000000000..77633c956d--- /dev/null+++ b/server/routes/localLlm.test.js@@ -0,0 +1,113 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import localLlmRoutes from './localLlm.js';+import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js';+import { localLlmCompareSchema, localLlmTestSchema } from '../lib/validation.js';++vi.mock('../services/localLlm.js', () => ({+ getStatus: vi.fn(),+ listModels: vi.fn(async () => []),+ installModel: vi.fn(),+ deleteModel: vi.fn(),+ switchBackend: vi.fn(),+ migrateBackend: vi.fn(),+ installBackend: vi.fn(),+ upgradeBackend: vi.fn(),+ controlOllamaServer: vi.fn(),+}));++vi.mock('../services/localLlmPlayground.js', () => ({+ runLocalLlmTest: vi.fn(),+ compareLocalLlmModels: vi.fn(),+}));++vi.mock('../services/ollamaManager.js', () => ({+ getLoadedModels: vi.fn(async () => []),+ unloadModel: vi.fn(),+}));++function makeApp() {+ const app = express();+ app.use(express.json());+ app.set('io', { emit: vi.fn() });+ app.use('/api/local-llm', localLlmRoutes);+ return app;+}++describe('local LLM playground routes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('runs a single local model test with validated defaults', async () => {+ runLocalLlmTest.mockResolvedValue({+ backend: 'ollama',+ modelId: 'llama3.2',+ text: 'hello',+ runId: 'run-1',+ timings: { totalMs: 25, ttftMs: 10, chars: 5, charsPerSecond: 200 },+ });++ const res = await request(makeApp())+ .post('/api/local-llm/test')+ .send({ backend: 'ollama', modelId: 'llama3.2', prompt: 'Say hello' });++ expect(res.status).toBe(200);+ expect(res.body.text).toBe('hello');+ expect(runLocalLlmTest).toHaveBeenCalledWith({+ backend: 'ollama',+ modelId: 'llama3.2',+ prompt: 'Say hello',+ systemPrompt: '',+ temperature: 0.3,+ maxTokens: 1000,+ timeoutMs: 300000,+ });+ });++ it('compares models in the requested execution mode', async () => {+ compareLocalLlmModels.mockResolvedValue({+ mode: 'parallel',+ results: [+ { backend: 'ollama', modelId: 'a', text: 'A' },+ { backend: 'lmstudio', modelId: 'b', text: 'B' },+ ],+ });++ const targets = [+ { backend: 'ollama', modelId: 'a' },+ { backend: 'lmstudio', modelId: 'b' },+ ];+ const res = await request(makeApp())+ .post('/api/local-llm/compare')+ .send({ mode: 'parallel', targets, prompt: 'Compare this', options: { maxTokens: 64 } });++ expect(res.status).toBe(200);+ expect(res.body.results).toHaveLength(2);+ expect(compareLocalLlmModels).toHaveBeenCalledWith({+ mode: 'parallel',+ targets,+ prompt: 'Compare this',+ options: {+ systemPrompt: '',+ temperature: 0.3,+ maxTokens: 64,+ timeoutMs: 300000,+ },+ });+ });++ it('rejects empty prompts before running a model', () => {+ const parsed = localLlmTestSchema.safeParse({ backend: 'ollama', modelId: 'llama3.2', prompt: ' ' });++ expect(parsed.success).toBe(false);+ });++ it('limits comparisons to six targets', () => {+ const targets = Array.from({ length: 7 }, (_, i) => ({ backend: 'ollama', modelId: `model-${i}` }));+ const parsed = localLlmCompareSchema.safeParse({ targets, prompt: 'too many' });++ expect(parsed.success).toBe(false);+ });+});diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.jsnew file mode 100644index 0000000000..e2bc8fef0d--- /dev/null+++ b/server/services/localLlmPlayground.js@@ -0,0 +1,228 @@+import { ServerError } from '../lib/errorHandler.js';+import { createRun, finalizeRunRecord } from './runner.js';+import { ensureBackendProvider } from './localLlm.js';+import { getProviderById } from './providers.js';+import { markProviderAvailable } from './providerStatus.js';+import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';++const PROVIDER_BY_BACKEND = { ollama: 'ollama', lmstudio: 'lmstudio' };++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 }) {+ const totalMs = endedAt - startedAt;+ const ttftMs = firstChunkAt ? firstChunkAt - startedAt : null;+ const chars = text.length;+ const charsPerSecond = totalMs > 0 ? chars / (totalMs / 1000) : chars;+ return {+ startedAt: new Date(startedAt).toISOString(),+ endedAt: new Date(endedAt).toISOString(),+ ttftMs,+ totalMs,+ chars,+ charsPerSecond: Number(charsPerSecond.toFixed(2)),+ };+}++function buildMessages({ systemPrompt, prompt }) {+ const system = String(systemPrompt || '').trim();+ return [+ ...(system ? [{ role: 'system', content: system }] : []),+ { role: 'user', content: prompt },+ ];+}++async function resolveLocalProvider(backend) {+ const providerId = PROVIDER_BY_BACKEND[backend];+ if (!providerId) {+ throw new ServerError(`Unsupported local LLM backend: ${backend}`, { status: 400, code: 'VALIDATION_ERROR' });+ }++ await ensureBackendProvider(backend);+ const provider = await getProviderById(providerId);+ if (!provider) {+ throw new ServerError(`Local provider "${providerId}" is not configured`, { status: 503, code: 'LOCAL_LLM_PROVIDER_MISSING' });+ }+ if (provider.type !== 'api') {+ throw new ServerError(`Local provider "${providerId}" must be an API provider`, { status: 503, code: 'LOCAL_LLM_PROVIDER_INVALID' });+ }+ await markProviderAvailable(provider.id).catch(() => {});+ return provider;+}++async function streamChatCompletion({ provider, backend, modelId, prompt, systemPrompt, temperature, maxTokens, signal, onChunk }) {+ if (backend === 'ollama') {+ const ready = await ensureOllamaProviderReady(provider).catch((err) => ({ success: false, error: err.message }));+ if (!ready.success) {+ throw new Error(`Ollama is not running and PortOS could not start it: ${ready.error || 'unknown error'}`);+ }+ }++ const headers = { 'Content-Type': 'application/json' };+ if (provider.apiKey) headers.Authorization = `Bearer ${provider.apiKey}`;++ const response = await fetch(`${provider.endpoint}/chat/completions`, {+ method: 'POST',+ headers,+ signal,+ body: JSON.stringify({+ model: modelId,+ messages: buildMessages({ systemPrompt, prompt }),+ stream: true,+ temperature,+ max_tokens: maxTokens,+ ...(Number(provider.numCtx) > 0 ? { num_ctx: Number(provider.numCtx) } : {}),+ }),+ }).catch((err) => ({ ok: false, status: 0, error: err.message }));++ if (!response.ok) {+ const body = response.text ? await response.text().catch(() => '') : response.error || '';+ throw new Error(`Provider returned ${response.status || 0}: ${body || response.error || response.statusText || 'request failed'}`);+ }++ if (!response.body?.getReader) {+ const data = await response.json();+ const text = data.choices?.[0]?.message?.content || '';+ if (text) onChunk(text);+ return text;+ }++ const reader = response.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';+ let output = '';+ 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);+ }+ 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);+ }+ if (buffer.trim()) consumeLine(buffer);++ if (!output.trim() && reasoning.trim()) {+ output = reasoning;+ onChunk(reasoning);+ }+ return output;+}++export async function runLocalLlmTest({+ backend,+ modelId,+ prompt,+ systemPrompt = '',+ temperature = 0.3,+ maxTokens = 1000,+ timeoutMs = 300000,+}) {+ const provider = await resolveLocalProvider(backend);+ const fullPrompt = buildPrompt({ systemPrompt, prompt });+ const startedAt = Date.now();+ let firstChunkAt = null;+ let runId = null;++ try {+ const run = await createRun({+ providerId: provider.id,+ model: modelId,+ prompt: fullPrompt,+ source: 'local-llm-playground',+ timeout: timeoutMs,+ });+ runId = run.runId;+ if (run.usedFallback || run.provider?.id !== provider.id) {+ throw new Error(`Local LLM playground refused fallback provider for ${provider.id}`);+ }++ const controller = new AbortController();+ const timeoutHandle = setTimeout(() => controller.abort(), timeoutMs);+ const text = await streamChatCompletion({+ provider,+ backend,+ modelId,+ prompt,+ systemPrompt,+ temperature,+ maxTokens,+ signal: controller.signal,+ onChunk: (chunk) => {+ if (!firstChunkAt && chunk) firstChunkAt = Date.now();+ },+ }).finally(() => clearTimeout(timeoutHandle));++ const endedAt = Date.now();+ await finalizeRunRecord({ runId, output: text, exitCode: 0, success: true, startTime: startedAt });+ return {+ backend,+ modelId,+ providerId: provider.id,+ runId,+ text,+ timings: summarizeTimings({ startedAt, firstChunkAt, endedAt, text }),+ options: { temperature, maxTokens, timeoutMs },+ };+ } catch (err) {+ const endedAt = Date.now();+ const error = err?.name === 'AbortError' ? `Timed out after ${timeoutMs}ms` : err?.message || 'Local LLM test failed';+ if (runId) {+ await finalizeRunRecord({+ runId,+ output: '',+ exitCode: 1,+ success: false,+ error,+ startTime: startedAt,+ }).catch(() => {});+ }+ return {+ backend,+ modelId,+ providerId: provider.id,+ runId,+ error,+ timings: summarizeTimings({ startedAt, firstChunkAt, endedAt, text: '' }),+ options: { temperature, maxTokens, timeoutMs },+ };+ }+}++export async function compareLocalLlmModels({ targets, prompt, mode = 'round-robin', options = {} }) {+ const runOne = (target) => runLocalLlmTest({ ...options, ...target, prompt });+ const results = [];++ if (mode === 'parallel') {+ return {+ mode,+ prompt,+ results: await Promise.all(targets.map(runOne)),+ };+ }++ for (const target of targets) {+ results.push(await runOne(target));+ }+ return { mode: 'round-robin', prompt, results };+}