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
feat: audit local LLM performance and TUI harnesses (#4837)
[._.]/ Adam Eivyb5f0179a37da
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex a6622c7a4b..e25bf794a8 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -73,12 +73,13 @@ const CATEGORY_LABELS = {reasoning: 'Reasoning & analysis',vision: 'Image Analysis',chat: 'Chat & voice',+ writing: 'Fiction & writing',audio: 'Audio & Music',embedding: 'Text Embeddings',lightweight: 'Small & Fast',multilingual: 'Multilingual'};-const CATEGORY_ORDER = ['general', 'coding', 'reasoning', 'vision', 'chat', 'lightweight', 'multilingual', 'embedding', 'audio'];+const CATEGORY_ORDER = ['general', 'coding', 'writing', 'reasoning', 'vision', 'chat', 'lightweight', 'multilingual', 'embedding', 'audio'];const categoryLabel = (id) => CATEGORY_LABELS[id] || id;const primaryCategoryFor = (model) => model?.category || 'general';const recommendationCategoriesFor = (model) => {diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsxindex e0293991c2..fd64c3e1f6 100644--- a/client/src/components/settings/LocalLlmTab.test.jsx+++ b/client/src/components/settings/LocalLlmTab.test.jsx@@ -301,8 +301,8 @@ describe('LocalLlmTab recommendations', () => {category: 'general',recommendedFor: ['general', 'coding', 'reasoning', 'vision', 'multilingual'],featured: {- label: 'Best overall',- description: 'Flagship local pick for general work, coding and agents, reasoning, and image analysis.',+ label: 'Best Qwen3.8 path',+ description: 'For Qwen3.8 CoS tasks, use MTPLX + OpenCode MTPLX TUI; use native MLX when isolated decoder throughput or vision is the priority.',},params: '27B',size: '16.5 GB',@@ -315,7 +315,7 @@ describe('LocalLlmTab recommendations', () => {await renderTab();- expect(await screen.findByText('Best overall')).toBeTruthy();+ expect(await screen.findByText('Best Qwen3.8 path')).toBeTruthy();expect(screen.getAllByText('General purpose').length).toBeGreaterThan(0);fireEvent.click(screen.getByRole('button', { name: 'Coding & agents (1)' }));@@ -883,4 +883,4 @@ describe('LocalLlmTab llama-server management', () => {expect(await screen.findByText(/pulling manifest/)).toBeInTheDocument();});});-});\ No newline at end of file+});diff --git a/client/src/components/settings/LocalModelAssessments.jsx b/client/src/components/settings/LocalModelAssessments.jsxindex 2ead2ebc42..71e2cf851a 100644--- a/client/src/components/settings/LocalModelAssessments.jsx+++ b/client/src/components/settings/LocalModelAssessments.jsx@@ -57,9 +57,11 @@ const BACKEND_LABEL = {};const OPENCODE_AGENT_TARGETS = [- { backend: 'llama', label: 'OpenCode llama TUI', modelId: 'qwen3.8-27b-dflash2' },+ { backend: 'llama', label: 'OpenCode llama TUI (Qwen3.8-27B → dflash)', modelId: 'dflash' },{ backend: 'mtplx', label: 'OpenCode MTPLX TUI', modelId: 'mtplx-qwen38-27b-optimized-speed' },{ backend: 'ollama', label: 'OpenCode Ollama TUI', modelId: 'qwen3.8:27b-mlx' },+ { backend: 'ollama-coder', label: 'OpenCode Ollama TUI (Qwen3-Coder 30B)', modelId: 'qwen3-coder:30b' },+ { backend: 'claude-ollama', label: 'Claude Ollama TUI', modelId: 'qwen3.8:27b-mlx' },];const VERDICT_META = {@@ -600,33 +602,28 @@ function OpenCodeAgentBenchmarkPanel({ results, running, onRun }) {const completed = OPENCODE_AGENT_TARGETS.map((target) => ({ target, result: results?.[target.backend] })).filter(({ result }) => result?.completed);- const comparableTokens = completed.length > 0- && completed.every(({ result }) => Number.isFinite(result.taskTokensPerSecond));- const metricKey = comparableTokens ? 'taskTokensPerSecond' : 'taskCharsPerSecond';- const metricLabel = comparableTokens ? 'tok/s' : 'chars/s';const leader = [...completed]- .filter(({ result }) => Number.isFinite(result[metricKey]))- .sort((a, b) => b.result[metricKey] - a.result[metricKey])[0];+ .filter(({ result }) => Number.isFinite(result.elapsedMs))+ .sort((a, b) => a.result.elapsedMs - b.result.elapsedMs)[0];return (<div className="border border-port-border rounded-lg p-3 space-y-2"><div className="flex items-center gap-1.5 text-xs text-gray-300"><Terminal size={12} className="text-port-accent" />- <h3 className="font-medium">OpenCode agent-task check</h3>+ <h3 className="font-medium">Local TUI agent-task check</h3></div><p className="text-[11px] text-gray-500">- Runs one disposable task through each configured OpenCode local preset. The agent must create and- read a sentinel file in a temporary workspace, so this measures tool-loop completion rather than raw- decoder speed. Terminal paste/render overhead is intentionally excluded; compare the direct report- above for engine throughput.+ Runs one disposable task through each configured local TUI preset using the actual PTY-backed harness.+ The agent must create and read a sentinel file in a temporary workspace, so this measures harness+ completion including startup and terminal paste overhead. Compare the direct report above for engine+ throughput.</p>{leader && (<div className="text-[11px] text-port-accent border border-port-accent/30 rounded px-2 py-1">- Current task leader: <span className="font-medium">{leader.target.label}</span> — {leader.result[metricKey]} {metricLabel}- {comparableTokens ? ' (exact OpenCode output counts)' : ' (chars/s fallback until every check reports tokens)'}+ Current task leader: <span className="font-medium">{leader.target.label}</span> — {formatDurationMs(leader.result.elapsedMs)} fastest completion</div>)}- <div className="grid gap-1.5 sm:grid-cols-3">+ <div className="grid gap-1.5 sm:grid-cols-2 xl:grid-cols-5">{OPENCODE_AGENT_TARGETS.map((target) => {const result = results?.[target.backend];return (@@ -640,8 +637,12 @@ function OpenCodeAgentBenchmarkPanel({ results, running, onRun }) {)}{result?.completed && (<div className="text-[10px] text-gray-400 space-y-0.5">- <div>{Number.isFinite(result.taskTokensPerSecond) ? `${result.taskTokensPerSecond} tok/s · ` : ''}{Number.isFinite(result.taskCharsPerSecond) ? `${result.taskCharsPerSecond} chars/s` : 'chars/s n/a'}</div>- <div>{result.toolCalls} tool call{result.toolCalls === 1 ? '' : 's'} · {formatDurationMs(result.elapsedMs)}</div>+ <div>+ {result.toolCalls === null || result.toolCalls === undefined+ ? 'PTY-backed TUI'+ : `${result.toolCalls} tool call${result.toolCalls === 1 ? '' : 's'}`}+ {' · '}{formatDurationMs(result.elapsedMs)}+ </div></div>)}<buttondiff --git a/client/src/components/settings/LocalModelAssessments.test.jsx b/client/src/components/settings/LocalModelAssessments.test.jsxindex bab6cc1fda..f3350edc29 100644--- a/client/src/components/settings/LocalModelAssessments.test.jsx+++ b/client/src/components/settings/LocalModelAssessments.test.jsx@@ -142,20 +142,20 @@ describe('LocalModelAssessments', () => {expect(runLocalLlmAssessment).not.toHaveBeenCalled();});- it('runs an explicit OpenCode task check and renders its task-level rates', async () => {+ it('runs an explicit local TUI task check and ranks by completion time', async () => {runOpenCodeAgentBenchmark.mockResolvedValue({- backend: 'llama', modelId: 'qwen3.8-27b-dflash2', completed: true,- taskTokensPerSecond: 27.5, taskCharsPerSecond: 110, toolCalls: 2, elapsedMs: 4000,+ backend: 'llama', modelId: 'dflash', completed: true,+ taskTokensPerSecond: null, taskCharsPerSecond: null, toolCalls: null, elapsedMs: 4000,});const user = userEvent.setup();renderPanel();await user.click(screen.getAllByRole('button', { name: 'Run task check' })[0]);await waitFor(() => expect(runOpenCodeAgentBenchmark).toHaveBeenCalledWith({- backend: 'llama', modelId: 'qwen3.8-27b-dflash2',+ backend: 'llama', modelId: 'dflash',}));expect(await screen.findByText('sentinel complete')).toBeInTheDocument();- expect(screen.getAllByText(/27\.5 tok\/s/)).toHaveLength(2);- expect(screen.getByText(/exact OpenCode output counts/)).toBeInTheDocument();+ expect(screen.getByText(/4s fastest completion/)).toBeInTheDocument();+ expect(screen.getByText(/PTY-backed TUI/)).toBeInTheDocument();});it('renders measured numbers for a ranked model', async () => {diff --git a/client/src/components/settings/ModelCapabilityTests.jsx b/client/src/components/settings/ModelCapabilityTests.jsxindex b99d07fca3..8d7f6a9fed 100644--- a/client/src/components/settings/ModelCapabilityTests.jsx+++ b/client/src/components/settings/ModelCapabilityTests.jsx@@ -26,7 +26,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { Link } from 'react-router';import {- FlaskConical, Play, RefreshCw, Trash2, Check, X, AlertTriangle, Terminal, Eye, BookOpen, Wrench,+ FlaskConical, Play, RefreshCw, Trash2, Check, X, AlertTriangle, Terminal, Eye, BookOpen, Wrench, Search, Trophy,} from 'lucide-react';import socket from '../../services/socket';import Drawer from '../Drawer';@@ -45,6 +45,7 @@ const TEST_META = {'sandbox-repair': { Icon: Wrench, cls: 'text-blue-400', border: 'border-blue-400/35' },'image-analysis': { Icon: Eye, cls: 'text-amber-400', border: 'border-amber-400/35' },'story-outline': { Icon: BookOpen, cls: 'text-port-accent-2', border: 'border-port-accent-2/35' },+ 'fiction-scene': { Icon: BookOpen, cls: 'text-pink-400', border: 'border-pink-400/35' },};const testMeta = (id) => TEST_META[id] || { Icon: FlaskConical, cls: 'text-gray-400', border: 'border-port-border' };@@ -79,6 +80,69 @@ const pairFor = (report, backend, modelId, testId) => {return { model, test, slot };};+const TASK_FILTERS = [+ { id: 'all', label: 'All tests' },+ { id: 'coding', label: 'Coding', testIds: ['sandbox-repair'] },+ { id: 'vision', label: 'Vision', testIds: ['image-analysis'] },+ // Older servers shipped only the outline proxy. Prefer the prose check when+ // present, but keep the filter useful during a rolling upgrade.+ { id: 'writing', label: 'Writing', testIds: ['fiction-scene', 'story-outline'] },+];++const verdictRank = { passed: 2, partial: 1, failed: 0 };++const taskScore = (taskId, result) => {+ if (!result?.verdict || !Number.isFinite(verdictRank[result.verdict])) return null;+ const detail = result.detail || {};+ if (taskId === 'vision' && Number.isFinite(detail.requiredTotal) && detail.requiredTotal > 0) {+ const required = detail.requiredHit / detail.requiredTotal;+ const bonus = Number.isFinite(detail.bonusTotal) && detail.bonusTotal > 0+ ? detail.bonusHit / detail.bonusTotal+ : 0;+ return required * 0.8 + bonus * 0.2;+ }+ if (taskId === 'writing' && Number.isFinite(detail.requiredTotal) && detail.requiredTotal > 0) {+ const anchors = detail.requiredHit / detail.requiredTotal;+ const beats = Number.isFinite(detail.total) && detail.total > 0 && Number.isFinite(detail.found)+ ? detail.found / detail.total+ : 0;+ const craft = Number.isFinite(detail.wordCount)+ ? Object.values(detail.craft || {}).filter(Boolean).length / Math.max(1, Object.keys(detail.craft || {}).length)+ : 0;+ return detail.total ? beats : anchors * 0.7 + craft * 0.3;+ }+ return verdictRank[result.verdict] / 2;+};++const taskTest = (tests, task) => (task?.testIds || [])+ .map((id) => tests.find((test) => test.id === id))+ .find(Boolean) || null;++// A structural pass is the primary evidence. When several models tie, prefer+// an explicit specialization in the installed model id before falling back to+// a stable name sort; this keeps a coding-specialist or fiction-tuned model+// from losing to an unrelated model merely because its name sorts later.+const specializationScore = (taskId, model) => {+ const id = String(model?.modelId || '').toLowerCase();+ if (taskId === 'coding') return /coder|code/.test(id) ? 2 : 0;+ if (taskId === 'writing') return /fable|fiction|writer|story/.test(id) ? 2 : 0;+ return 0;+};++const bestForTask = (models, tests, task) => {+ if (!task || task.id === 'all') return null;+ const candidates = (models || []).flatMap((model) => {+ const test = taskTest(tests, task);+ const slot = test && model.tests?.find((entry) => entry.testId === test.id);+ const score = taskScore(task.id, slot?.result);+ return score === null ? [] : [{ model, test, slot, score }];+ });+ return candidates.sort((a, b) => b.score - a.score+ || (verdictRank[b.slot.result.verdict] - verdictRank[a.slot.result.verdict])+ || (specializationScore(task.id, b.model) - specializationScore(task.id, a.model))+ || String(a.model.modelId).localeCompare(String(b.model.modelId)))[0] || null;+};+// ---- small shared bits ------------------------------------------------------function VerdictChip({ verdict, children, title }) {@@ -213,6 +277,50 @@ function BeatScore({ detail }) {);}+/** Structural checks for the fiction scene, kept distinct from prose quality. */+function FictionScore({ detail }) {+ const row = (entry, required) => (+ <div key={entry.id} className="flex items-center gap-2 py-1.5 border-b border-port-border/50 last:border-b-0">+ {entry.hit+ ? <Check size={13} className="text-emerald-400 shrink-0" aria-label="found" />+ : <X size={13} className={`${required ? 'text-port-error' : 'text-gray-600'} shrink-0`} aria-label="not found" />}+ <span className={`text-xs ${entry.hit ? 'text-gray-300' : 'text-gray-500'}`}>{entry.label}</span>+ <span className="ml-auto text-[10px] text-gray-600 font-mono">{entry.any.join(' | ')}</span>+ </div>+ );+ const craftChecks = Object.entries(detail.craft || {});+ const craftPassed = craftChecks.filter(([, passed]) => passed).length;++ return (+ <div className="space-y-3">+ <dl className="grid grid-cols-3 gap-2 text-xs">+ <div><dt className="text-gray-500">Words</dt><dd className="text-gray-200">{detail.wordCount ?? '—'}</dd></div>+ <div><dt className="text-gray-500">Paragraphs</dt><dd className="text-gray-200">{detail.paragraphCount ?? '—'}</dd></div>+ <div><dt className="text-gray-500">Dialogue</dt><dd className="text-gray-200">{detail.hasDialogue ? 'yes' : 'no'}</dd></div>+ </dl>+ <div>+ <div className="flex items-baseline justify-between gap-2 mb-1">+ <h4 className="text-xs font-medium text-gray-400">Scene anchors</h4>+ <span className="text-[11px] text-gray-500">{detail.requiredHit} of {detail.requiredTotal} — all needed to pass</span>+ </div>+ {(detail.required || []).map((entry) => row(entry, true))}+ </div>+ <div>+ <div className="flex items-baseline justify-between gap-2 mb-1">+ <h4 className="text-xs font-medium text-gray-400">Scene signals</h4>+ <span className="text-[11px] text-gray-500">{detail.bonusHit} of {detail.bonusTotal}</span>+ </div>+ {(detail.bonus || []).map((entry) => row(entry, false))}+ </div>+ <p className="text-[11px] text-gray-500">Minimum craft checks: {craftPassed} of {craftChecks.length}</p>+ <p className="text-[11px] text-gray-500 leading-snug">+ This is a structural screen for a saved scene, not a literary-quality score. Read the scene above+ before choosing a writing model.+ </p>+ </div>+ );+}+/** On-disk checks for the sandbox test. */function SandboxChecks({ detail }) {return (@@ -250,6 +358,7 @@ function SandboxChecks({ detail }) {const SCORE_VIEWS = {'image-analysis': KeywordScore,'story-outline': BeatScore,+ 'fiction-scene': FictionScore,'sandbox-repair': SandboxChecks,};@@ -455,6 +564,51 @@ function CapabilityTestDrawer({);}+function CapabilityRecommendations({ report, onOpen }) {+ const tests = report?.tests || [];+ const models = report?.models || [];+ const tasks = TASK_FILTERS.filter((task) => task.id !== 'all');+ return (+ <div className="border border-port-accent/30 rounded-lg p-3 space-y-2">+ <div className="flex items-center gap-1.5 text-xs text-gray-300">+ <Trophy size={12} className="text-port-accent" />+ <h4 className="font-medium">Evidence-based task picks</h4>+ <span className="text-[10px] text-gray-500">recorded checks only</span>+ </div>+ <p className="text-[11px] text-gray-500 leading-snug">+ These leaders are task-specific, not a generic model rank. Unmeasured models are left out; the+ writing result is a structural screen, so open the saved scene before choosing a voice. Tied+ structural results favor an explicitly task-specialized model name.+ </p>+ <div className="grid gap-2 sm:grid-cols-3">+ {tasks.map((task) => {+ const winner = bestForTask(models, tests, task);+ return (+ <div key={task.id} className="border border-port-border/70 rounded p-2 space-y-1.5">+ <div className="text-[11px] text-gray-300">Best {task.label.toLowerCase()} evidence</div>+ {winner ? (+ <>+ <div className="text-[11px] text-white font-mono break-all">{winner.model.modelId}</div>+ <div className="text-[10px] text-gray-500">{winner.model.runtimeLabel} · {winner.slot.result.summary}</div>+ <button+ type="button"+ onClick={() => onOpen(winner.model.backend, winner.model.modelId, winner.test.id)}+ className="text-[10px] text-port-accent hover:underline"+ >+ Read the result+ </button>+ </>+ ) : (+ <span className="text-[10px] text-gray-600 italic">Run the {task.label.toLowerCase()} check to rank it.</span>+ )}+ </div>+ );+ })}+ </div>+ </div>+ );+}+// ---- the panel --------------------------------------------------------------export default function ModelCapabilityTests({ report, loading, onReload, disabled = false }) {@@ -473,6 +627,8 @@ export default function ModelCapabilityTests({ report, loading, onReload, disabl// would turn one click into a batch of provider calls the gate never counted —// so "run everything applicable" is a queue here, not a wider endpoint.const [queue, setQueue] = useState(null);+ const [modelQuery, setModelQuery] = useState('');+ const [taskFilter, setTaskFilter] = useState('all');const mountedRef = useMounted();// Which pairing is in flight. A ref, not state: the socket handler subscribes@@ -621,6 +777,26 @@ export default function ModelCapabilityTests({ report, loading, onReload, disablconst tests = report?.tests || [];const models = report?.models || [];const busy = disabled || running;+ const selectedTask = TASK_FILTERS.find((task) => task.id === taskFilter) || TASK_FILTERS[0];+ const visibleTests = selectedTask.id === 'all'+ ? tests+ : tests.filter((test) => selectedTask.testIds.includes(test.id));+ const visibleModels = useMemo(() => {+ const query = modelQuery.trim().toLowerCase();+ return models.filter((model) => {+ const matchesQuery = !query || [model.modelId, model.runtimeLabel, ...(model.capabilities || [])]+ .some((value) => String(value).toLowerCase().includes(query));+ const matchesTask = selectedTask.id === 'all'+ || visibleTests.some((test) => model.tests?.some((slot) => slot.testId === test.id));+ return matchesQuery && matchesTask;+ });+ }, [models, modelQuery, selectedTask, visibleTests]);++ const openRecommended = useCallback((b, m, t) => {+ setLiveLines([]);+ setProgress('');+ updateParams({ capBackend: b, capModel: m, capTest: t });+ }, [updateParams]);return (<div className="border border-port-border rounded-lg p-3 space-y-3">@@ -680,6 +856,8 @@ export default function ModelCapabilityTests({ report, loading, onReload, disabl</div>)}+ <CapabilityRecommendations report={report} onOpen={openRecommended} />+{/* A runtime PortOS could not reach. Every line carries the fix: for theruntimes PortOS can start, a link to the page that starts them; for theones it cannot (vLLM and SGLang are containers the user runs), the@@ -718,19 +896,47 @@ export default function ModelCapabilityTests({ report, loading, onReload, disablNo local models are installed, so there is nothing to test yet.</p>) : (- <div className="border border-port-border rounded overflow-x-auto">+ <>+ <div className="flex items-center gap-2 flex-wrap">+ <label htmlFor="capability-model-search" className="sr-only">Search models</label>+ <div className="relative min-w-[14rem] flex-1">+ <Search size={13} className="absolute left-2 top-1/2 -translate-y-1/2 text-gray-500" />+ <input+ id="capability-model-search"+ type="search"+ value={modelQuery}+ onChange={(event) => setModelQuery(event.target.value)}+ placeholder="Search model, runtime, or capability"+ className="w-full bg-port-bg border border-port-border rounded pl-7 pr-2 py-1.5 text-xs text-white placeholder:text-gray-600"+ />+ </div>+ <label htmlFor="capability-task-filter" className="text-[11px] text-gray-500">Show</label>+ <select+ id="capability-task-filter"+ value={taskFilter}+ onChange={(event) => setTaskFilter(event.target.value)}+ className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-xs text-white"+ >+ {TASK_FILTERS.map((task) => <option key={task.id} value={task.id}>{task.label}</option>)}+ </select>+ <span className="text-[10px] text-gray-600">{visibleModels.length} of {models.length} models</span>+ </div>+ {visibleModels.length === 0 ? (+ <p className="text-xs text-gray-500">No models match this filter.</p>+ ) : (+ <div className="border border-port-border rounded overflow-x-auto"><table className="w-full min-w-[42rem] text-left"><thead><tr className="bg-port-bg/60 border-b border-port-border"><th scope="col" className="px-3 py-2 text-[11px] font-normal text-gray-500">Model</th>- {tests.map((t) => (+ {visibleTests.map((t) => (<th key={t.id} scope="col" className="px-3 py-2 text-[11px] font-normal text-gray-500">{t.label}</th>))}<th scope="col" className="px-3 py-2 text-[11px] font-normal text-gray-500 text-right">Run</th></tr></thead><tbody>- {models.map((m) => (+ {visibleModels.map((m) => (<tr key={modelKey(m.backend, m.modelId)} className="border-b border-port-border/60 last:border-b-0"><td className="px-3 py-2 align-top"><div className="flex items-center gap-2 flex-wrap">@@ -746,7 +952,7 @@ export default function ModelCapabilityTests({ report, loading, onReload, disabl<CapabilityBadges capabilities={m.capabilities} /></div></td>- {tests.map((t) => (+ {visibleTests.map((t) => (<td key={t.id} className="px-3 py-2 align-top"><TestCellslot={m.tests.find((s) => s.testId === t.id)}@@ -762,7 +968,9 @@ export default function ModelCapabilityTests({ report, loading, onReload, disabl))}</tbody></table>- </div>+ </div>+ )}+ </>)}{open && (diff --git a/client/src/components/settings/ModelCapabilityTests.test.jsx b/client/src/components/settings/ModelCapabilityTests.test.jsxindex fa156f2c72..faab0be864 100644--- a/client/src/components/settings/ModelCapabilityTests.test.jsx+++ b/client/src/components/settings/ModelCapabilityTests.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { act, render, screen, waitFor } from '@testing-library/react';+import { act, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter } from 'react-router';@@ -24,6 +24,7 @@ const TESTS = [{ id: 'image-analysis', label: 'Image analysis', capabilities: ['vision'], prefers: [], blurb: 'Describe a fixture image.', driver: 'chat', kind: 'vision' },{ id: 'story-outline', label: 'Story outline', capabilities: ['chat'], prefers: ['reasoning'], blurb: 'Outline a hero journey.', driver: 'chat', kind: 'text' },];+const FICTION_TEST = { id: 'fiction-scene', label: 'Fiction scene', capabilities: ['chat'], prefers: [], blurb: 'Write a constrained opening scene.', driver: 'chat', kind: 'text' };const slot = (testId, over = {}) => ({ testId, state: 'applicable', missing: [], reason: null, result: null, ...over });@@ -59,6 +60,14 @@ const renderPanel = (props = {}) => render(</MemoryRouter>,);+const fictionReport = (result) => report({+ tests: [...TESTS, FICTION_TEST],+ testIds: [...TESTS.map((t) => t.id), FICTION_TEST.id],+ prompts: { ...report().prompts, 'fiction-scene': 'Write a constrained opening scene.' },+ models: [model({ tests: [...TESTS.map((t) => slot(t.id)), slot('fiction-scene', { result })] })],+ counts: { models: 1, applicable: 4, passed: 0, failed: 0 },+});+/*** Replay a server progress frame through the handler the panel registered.* Wrapped in `act` because a socket frame drives a state update from outside@@ -133,6 +142,21 @@ describe('the matrix', () => {renderPanel({ report: report({ models: [], counts: { models: 0, applicable: 0, passed: 0, failed: 0 } }) });expect(screen.getByText(/no local models are installed/i)).toBeInTheDocument();});++ it('uses an explicit task specialization to break a tied evidence score', () => {+ const passingSandbox = { verdict: 'passed', summary: 'fixed in 5 tool calls' };+ renderPanel({+ report: report({+ models: [+ model({ modelId: 'generic-model:30b', tests: [slot('sandbox-repair', { result: passingSandbox }), slot('image-analysis'), slot('story-outline')] }),+ model({ modelId: 'qwen3-coder:30b', tests: [slot('sandbox-repair', { result: passingSandbox }), slot('image-analysis'), slot('story-outline')] }),+ ],+ }),+ });++ const card = screen.getByText('Best coding evidence').parentElement;+ expect(within(card).getByText('qwen3-coder:30b')).toBeInTheDocument();+ });});describe('the run gate', () => {@@ -303,6 +327,30 @@ describe('a recorded result', () => {expect(await screen.findByRole('alert')).toHaveTextContent('Timed out after 300000ms');expect(await screen.findByText('A bicycle and a bench at night.')).toBeInTheDocument();});++ it('shows the fiction scene structure checks and warns that they are not literary quality', async () => {+ const user = userEvent.setup();+ const result = {+ verdict: 'partial',+ summary: '4 of 5 story anchors, 2 of 3 scene signals, 3 of 3 minimum craft checks, 446 words',+ detail: {+ requiredHit: 4,+ requiredTotal: 5,+ wordCount: 446,+ paragraphCount: 8,+ hasDialogue: true,+ required: [{ id: 'marsh', label: 'Tidal-marsh setting', any: ['marsh'], hit: true }],+ bonus: [{ id: 'dialogue', label: 'Spoken line', any: ['said'], hit: true }],+ craft: { minimumWords: true, paragraphs: true, dialogue: true },+ },+ };+ renderPanel({ report: fictionReport(result) });+ await user.click(screen.getByRole('button', { name: /4 of 5 story anchors/i }));+ await user.click(await screen.findByRole('tab', { name: /checks/i }));++ expect(screen.getByText('446')).toBeInTheDocument();+ expect(screen.getByText(/not a literary-quality score/i)).toBeInTheDocument();+ });});describe('running everything that applies to one model', () => {diff --git a/client/src/components/settings/ModelThroughputReport.jsx b/client/src/components/settings/ModelThroughputReport.jsxindex 03b5e82f1c..477903746c 100644--- a/client/src/components/settings/ModelThroughputReport.jsx+++ b/client/src/components/settings/ModelThroughputReport.jsx@@ -36,13 +36,20 @@ const Rate = ({ value, estimated, suffix = '' }) => (: <span className="text-gray-600">{rateText(value, estimated)}</span>);+const timingLabel = (source) => ({+ runtime: 'runtime timing',+ 'stream-window': 'observed stream window',+ 'wall-clock': 'end-to-end wall clock',+ mixed: 'mixed timing basis',+}[source] || 'timing basis unavailable');+// A row's samples keyed by context, for the per-context columns.const pointsByContext = (row) => new Map((row.points || []).map((p) => [p.contextTokens, p]));/** The report as a markdown table — what a copy of this is actually useful as. */export function toMarkdown(report) {const contexts = report?.contexts || [];- const header = ['Model', 'Runtime', 'Tuning', 'tok/s', 'chars/s', 'Prefill tok/s', 'TTFT', ...contexts.map((c) => `${formatContextTokens(c)} tok/s`)];+ const header = ['Model', 'Runtime', 'Tuning', 'Rate basis', 'tok/s', 'chars/s', 'Prefill tok/s', 'TTFT', ...contexts.map((c) => `${formatContextTokens(c)} tok/s`)];const lines = [`| ${header.join(' | ')} |`,`| ${header.map(() => '---').join(' | ')} |`,@@ -53,6 +60,7 @@ export function toMarkdown(report) {row.modelId,row.backend,row.tuningLabel || 'backend defaults',+ timingLabel(row.timingSource),rateText(row.meanTokensPerSecond, row.tokensEstimated),rateText(row.meanCharsPerSecond, false),rateText(row.meanPromptTokensPerSecond, row.tokensEstimated),@@ -110,6 +118,9 @@ export default function ModelThroughputReport({ report, runtimeLabelFor }) {<> A <span className="text-gray-400">—</span> means the runtime reported no token counts for thatreading; its chars/s figure is in the ranked list above.</>)}+ {rows.some((row) => row.timingSource === 'wall-clock') && (+ <> Some local endpoints expose exact token counts but no decode duration; those rates use end-to-end wall clock and are marked below.</>+ )}</p>{/* Wide by nature — one column per sampled context. Scrolls inside its own@@ -119,6 +130,7 @@ export default function ModelThroughputReport({ report, runtimeLabelFor }) {<thead><tr className="text-gray-500 border-b border-port-border"><th scope="col" className="text-left font-medium px-2 py-1.5">Model</th>+ <th scope="col" className="text-right font-medium px-2 py-1.5 whitespace-nowrap">Rate basis</th><th scope="col" className="text-right font-medium px-2 py-1.5 whitespace-nowrap">tok/s</th><th scope="col" className="text-right font-medium px-2 py-1.5 whitespace-nowrap">chars/s</th><th scope="col" className="text-right font-medium px-2 py-1.5 whitespace-nowrap">Prefill</th>@@ -139,12 +151,17 @@ export default function ModelThroughputReport({ report, runtimeLabelFor }) {{runtimeLabelFor?.(row.backend) || row.backend}<span className="mx-1">·</span>{row.tuningLabel || 'backend defaults'}+ <span className="mx-1">·</span>+ <span className={row.timingSource === 'wall-clock' ? 'text-port-warning' : ''} title="How the runtime timing was obtained">+ {timingLabel(row.timingSource)}+ </span>{row.staleness?.stale && <span className="ml-1 text-port-warning">stale</span>}{/* The numbers are real but describe a configuration nobodyasked for — say so here too, not only in the ranked list. */}{tuningNoticeChip(row) && <span className="ml-1 text-port-warning">{tuningNoticeChip(row)}</span>}</div></td>+ <td className="px-2 py-1.5 text-right text-gray-500 whitespace-nowrap">{timingLabel(row.timingSource)}</td><td className="px-2 py-1.5 text-right"><Rate value={row.meanTokensPerSecond} estimated={row.tokensEstimated} /></td><td className="px-2 py-1.5 text-right"><Rate value={row.meanCharsPerSecond} estimated={false} /></td><td className="px-2 py-1.5 text-right"><Rate value={row.meanPromptTokensPerSecond} estimated={row.tokensEstimated} /></td>diff --git a/client/src/components/settings/ModelThroughputReport.test.jsx b/client/src/components/settings/ModelThroughputReport.test.jsxindex c94be79b2c..f4da97a4ef 100644--- a/client/src/components/settings/ModelThroughputReport.test.jsx+++ b/client/src/components/settings/ModelThroughputReport.test.jsx@@ -119,8 +119,8 @@ describe('toMarkdown', () => {it('emits one row per measurement with a column per context', () => {const md = toMarkdown(report([row('example-model:7b')]));const lines = md.split('\n');- expect(lines[0]).toBe('| Model | Runtime | Tuning | tok/s | chars/s | Prefill tok/s | TTFT | 512 tok/s | 4K tok/s |');- expect(lines[2]).toContain('| example-model:7b | ollama | backend defaults | 50.0 |');+ expect(lines[0]).toBe('| Model | Runtime | Tuning | Rate basis | tok/s | chars/s | Prefill tok/s | TTFT | 512 tok/s | 4K tok/s |');+ expect(lines[2]).toContain('| example-model:7b | ollama | backend defaults | timing basis unavailable | 50.0 |');expect(lines[2]).toContain('| 60.0 | 40.0 |');});@@ -130,6 +130,6 @@ describe('toMarkdown', () => {points: [point(512, null)],});const md = toMarkdown(report([quiet]));- expect(md).toContain('| quiet-model | ollama | backend defaults | — | 200.0 | — | — |');+ expect(md).toContain('| quiet-model | ollama | backend defaults | timing basis unavailable | — | 200.0 | — | — |');});});diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex edd1173ea4..23a374845a 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -1,6 +1,6 @@import { useState, useEffect, useCallback, useMemo } from 'react';import { Link, useLocation, useNavigate, useParams } from 'react-router';-import { AlertTriangle } from 'lucide-react';+import { AlertTriangle, Gauge } from 'lucide-react';import toast from '../components/ui/Toast';import * as api from '../services/api';import socket from '../services/socket';@@ -538,6 +538,12 @@ export default function AIProviders() {<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4"><h1 className="text-2xl font-bold text-white">AI Providers</h1><div className="flex flex-wrap gap-2">+ <Link+ to="/models/performance"+ className="inline-flex items-center gap-1.5 px-4 py-2 bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors text-sm sm:text-base"+ >+ <Gauge size={15} /> Compare local models+ </Link><buttononClick={() => setShowRunPanel(!showRunPanel)}className="px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-white rounded-lg transition-colors text-sm sm:text-base"diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsxindex 94defe8444..38ed97d90b 100644--- a/client/src/pages/AIProviders.test.jsx+++ b/client/src/pages/AIProviders.test.jsx@@ -215,6 +215,7 @@ describe('AIProviders page load error handling', () => {renderPage();expect(await screen.findByText('OpenAI')).toBeInTheDocument();+ expect(screen.getByRole('link', { name: /Compare local models/ })).toHaveAttribute('href', '/models/performance');expect(screen.queryByText('No providers configured')).not.toBeInTheDocument();expect(screen.queryByText('Failed to load AI providers')).not.toBeInTheDocument();});diff --git a/data.reference/providers.json b/data.reference/providers.jsonindex c106513f8a..ed909b6dc9 100644--- a/data.reference/providers.json+++ b/data.reference/providers.json@@ -201,8 +201,8 @@"command": "opencode","args": ["run"],"endpoint": "http://127.0.0.1:8000/v1",- "models": ["mtplx"],- "defaultModel": "mtplx",+ "models": ["mtplx-qwen38-27b-optimized-speed"],+ "defaultModel": "mtplx-qwen38-27b-optimized-speed","mtplxBacked": true,"timeout": 600000,"enabled": false,@@ -219,8 +219,8 @@"command": "opencode","args": [],"endpoint": "http://127.0.0.1:8000/v1",- "models": ["mtplx"],- "defaultModel": "mtplx",+ "models": ["mtplx-qwen38-27b-optimized-speed"],+ "defaultModel": "mtplx-qwen38-27b-optimized-speed","mtplxBacked": true,"timeout": 600000,"enabled": false,@@ -484,8 +484,8 @@"type": "api","endpoint": "http://127.0.0.1:8000/v1","apiKey": "",- "models": ["mtplx"],- "defaultModel": "mtplx",+ "models": ["mtplx-qwen38-27b-optimized-speed"],+ "defaultModel": "mtplx-qwen38-27b-optimized-speed","timeout": 300000,"enabled": false,"envVars": {}diff --git a/docs/README.md b/docs/README.mdindex ed9cdfd0be..401810e81c 100644--- a/docs/README.md+++ b/docs/README.md@@ -48,7 +48,7 @@ Comms & voice: [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([- **[plans/](./plans/README.md)** — dated design plans (`YYYY-MM-DD-<slug>.md`), archived on approval before implementation. Historical records, not living docs.- **decisions/** — ADRs (`YYYY-MM-DD-<slug>.md`), e.g. the [Postgres-as-primary-datastore decision](./decisions/2026-06-07-postgres-as-primary-datastore.md) and what may cross the federation layer ([privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), [federated visual prompts](./decisions/2026-08-20-federated-visual-prompts.md), [conditioning crosses to an allowlisted peer](./decisions/2026-08-22-federated-media-input-assets.md)).-- **research/** — dated investigation and incident write-ups (e.g. the [mflux GPU-watchdog panic](./research/2026-06-13-mflux-training-watchdog-panic.md)).+- **research/** — dated investigation and incident write-ups (e.g. the [mflux GPU-watchdog panic](./research/2026-06-13-mflux-training-watchdog-panic.md) and the [local LLM performance audit](./research/2026-08-22-local-llm-performance-audit.md)).- **superpowers/** — plan/spec pairs from superpowers-driven builds: `specs/<date>-<slug>-design.md` (design) + `plans/<date>-<slug>.md` (implementation plan).## Otherdiff --git a/docs/features/sglang-qwen38.md b/docs/features/sglang-qwen38.mdindex 7579d0553c..d577c86a6c 100644--- a/docs/features/sglang-qwen38.md+++ b/docs/features/sglang-qwen38.md@@ -11,7 +11,7 @@ the OpenAI and the Anthropic wire protocols, so either harness can drive it.the weights.** It holds the whole GPU, so local image/video generation cannot runwhile it is up — see [GPU exclusivity](#gpu-exclusivity) below.-Investigation record: [2026-08-21 SGLang Qwen3.8-27B](../research/2026-08-21-sglang-qwen38-27b.md).+Investigation record: [2026-08-21 SGLang Qwen3.8-27B](../research/2026-08-21-sglang-qwen38-27b.md). The latest local-model comparison is recorded in the [2026-08-22 performance audit](../research/2026-08-22-local-llm-performance-audit.md); it found this Apple Silicon install cannot run the recipe. The seed presets stay disabled by default; a live TUI card may be enabled for an explicit future test, but the readiness checklist keeps it blocked until a supported NVIDIA endpoint is reachable.## Which carddiff --git a/docs/research/2026-08-22-local-llm-performance-audit.md b/docs/research/2026-08-22-local-llm-performance-audit.mdnew file mode 100644index 0000000000..116d848f50--- /dev/null+++ b/docs/research/2026-08-22-local-llm-performance-audit.md@@ -0,0 +1,140 @@+# Local LLM performance audit — Qwen3.8, coding, vision, writing, and TUI harnesses++Date: 2026-08-22++This is the point-in-time record of the local-model evaluation that drives the+recommendations in **Models → LLMs**, **Models → Performance**, and **AI+Providers**. It is intentionally scoped to model behavior and runtime choices;+it contains no machine identity, private network names, credentials, or user+content.++## Executive decision++| Use case | Model | Runtime and harness | Decision |+| --- | --- | --- | --- |+| CoS coding | `qwen3-coder:30b` | Ollama + OpenCode Ollama TUI | Primary local coding path |+| Qwen3.8-27B CoS tasks | Qwen3.8-27B MTPLX checkpoint | MTPLX + OpenCode MTPLX TUI | Primary Qwen3.8 path |+| Image analysis | `qwen3.8:27b-mlx` or the MTPLX Qwen3.8 checkpoint | Ollama/OpenCode TUI or MTPLX/OpenCode TUI | Both passed the full image rubric |+| Fiction writing | Qwen3.6 Fable Fusion Q8 | Ollama for drafting; use a separate coding TUI | Best fiction-specialist candidate |++The coding recommendation is **Qwen3-Coder 30B through Ollama + OpenCode+Ollama TUI**. The direct runtime measurement was 66.14 tokens/second, the+disk-verifiable coding repair passed in six tool calls, and the actual PTY task+completed in 16.6 seconds.++The required Qwen3.8 recommendation is **MTPLX + OpenCode MTPLX TUI**. It+completed the same PTY task in 51.0 seconds and passed the coding, image, and+fiction structural checks. Native MLX Qwen3.8 produced the higher isolated+decoder rate (44.76 versus MTPLX's 38.92 tokens/second) but took 89.0 seconds+for the end-to-end agent task, so it is the direct-throughput and vision+fallback rather than the primary CoS TUI path.++The measurements are not interchangeable: decoder rates measure generation;+PTY times include process startup, prompt handling, tool calls, file I/O, and+verification. The UI labels the timing basis instead of presenting a blended+or synthetic rate.++## Measured harness comparison++| Harness target | PTY task | Direct decoder result | Result |+| --- | ---: | ---: | --- |+| OpenCode Ollama TUI + `qwen3-coder:30b` | 16.6s | 66.14 tok/s | Completed; best coding path |+| OpenCode MTPLX TUI + Qwen3.8-27B | 51.0s | 38.92 tok/s | Completed; best Qwen3.8 TUI path |+| OpenCode Ollama TUI + `qwen3.8:27b-mlx` | 89.0s | 44.76 tok/s | Completed; best direct Qwen3.8 fallback |+| OpenCode llama TUI + served `dflash` | 230.3s | 20.92 tok/s | Completed, but too slow for the primary path |+| Claude Ollama TUI + `qwen3.8:27b-mlx` | 314.2s | — | Completed, but not competitive locally |++The fastest raw decoder in the broader sweep was `gpt-oss:20b` at 97.88+tokens/second, followed by `qwen3.6:35b` at 86.71. Neither displaced+Qwen3-Coder for coding because the recommendation is based on task completion+and coding specialization, not tokens/second alone.++## Capability findings++The capability suite covers four distinct claims:++- **Sandbox repair:** a structured OpenCode agent loop must modify only the+ target module, preserve fixtures, and pass the verification command.+- **Image analysis:** a fixed fixture prompt is scored on required and bonus+ visual facts. Ollama image messages are converted to Ollama's native image+ payload before dispatch.+- **Story outline:** twelve structural beats are checked in order.+- **Fiction scene:** premise anchors, scene signals, minimum length,+ paragraphing, and dialogue are checked separately. This is a structural+ screen, not an aesthetic literary score; the saved prose still needs human+ review.++The strongest image results were Qwen3.8 MLX and MTPLX: 4/4 required facts and+3/3 bonus facts. Qwen3.8 Q4 and the Fable checkpoint were useful but partial;+Qwen3.8 Q8, Gemma 4, and llama/DFlash did not provide a reliable vision path+in this install. The DFlash failure was an explicit missing multimodal+projection file, not a silent quality judgment.++The Fable checkpoint passed all fiction anchors and craft checks. Several+general models also produced structurally complete scenes. The catalog labels+Fable as the fiction candidate but deliberately does not claim that a lexical+rubric proves voice, originality, or sentence quality.++## SGLang status and bring-up requirement++SGLang was **not a failed model result**. The configured local endpoint on port+18021 was unreachable because this install has no Docker runtime and no NVIDIA+GPU probe, while the shipped SGLang Qwen3.8 recipe requires an NVIDIA Hopper or+Blackwell host. The feature guide explicitly routes Apple Silicon to MTPLX or+llama.cpp instead. See [SGLang Qwen3.8-27B](../features/sglang-qwen38.md).++There is also an upstream image-pin decision still waiting for that hardware:+the repository recipe is pinned to `lmsysorg/sglang:qwen38-27b`, while the+current [SGLang Qwen3.8-27B cookbook](https://docs.sglang.io/cookbook/autoregressive/Qwen/Qwen3.8-27B)+documents `lmsysorg/sglang:dev-qwen38-27b-dflash2`. The pin was not changed+without a supported host on which to validate the parser flags and end-to-end+TUI behavior.++To produce a fair SGLang comparison, provide a supported NVIDIA host with:++1. Docker and the NVIDIA Container Toolkit.+2. The generated compose project from the SGLang feature guide.+3. The matching Qwen3.8-27B checkpoint, such as the documented FP8 H200 cell.+4. A reachable OpenAI-compatible `/v1/models` endpoint and a PortOS provider+ endpoint that is not incorrectly pointing at loopback on another machine.++Only then should the SGLang OpenCode TUI and Claude SGLang TUI be treated as+ready and measured. The source presets are disabled by default; this live+instance keeps its TUI cards visible for an explicit future test, while the+readiness checklist correctly marks them blocked until the endpoint answers.+SGLang supports speculative decoding, but there is no basis for calling it+faster than MTPLX until it runs on compatible hardware. Upstream references:+[SGLang speculative decoding](https://github.com/sgl-project/sglang/blob/main/docs_new/docs/advanced_features/speculative_decoding.mdx),+[MTPLX](https://github.com/youssofal/MTPLX).++## Catalog and provider consequences++- `qwen3-coder:30b` is a curated coding/agent entry and is marked **Best+ coding agent**.+- Qwen3.8 remains a curated general, coding, reasoning, and vision model, with+ the card explaining that MTPLX + OpenCode MTPLX TUI is the preferred Qwen3.8+ agent route and native MLX is the direct-decoder fallback.+- Qwen3.6 Fable Fusion is a curated **Fiction & writing** entry with an+ explicit structural-evidence caveat.+- The live instance defaults Ollama and OpenCode Ollama TUI to+ `qwen3-coder:30b`, and OpenCode MTPLX TUI to+ `mtplx-qwen38-27b-optimized-speed`.+- SGLang provider presets are disabled by default in the catalog. The live+ TUI cards are visible for future testing, but readiness blocks them until a+ supported endpoint exists; they are not presented as locally validated+ recommendations.++## Verification record++- Full server suite: 33,222 passing tests, 19 skipped.+- Full client suite: 9,468 passing tests.+- Focused capability, stream-transport, TUI benchmark, catalog, and UI tests+ passed after the audit changes.+- Production client build passed; the existing large-chunk warning remains a+ performance-budget warning, not a build failure.+- Live browser smoke checks confirmed the performance filters, evidence-based+ recommendation cards, actual TUI target cards, and AI Providers link.++Re-run this record after a hardware change, a runtime upgrade, or a supported+SGLang endpoint becomes reachable. Stored measurements are evidence for this+machine state, not universal model benchmarks.diff --git a/scripts/migrations/292-mtplx-served-model.js b/scripts/migrations/292-mtplx-served-model.jsnew file mode 100644index 0000000000..d12773e2ba--- /dev/null+++ b/scripts/migrations/292-mtplx-served-model.js@@ -0,0 +1,43 @@+/**+ * Align the shipped MTPLX provider presets with the model id emitted by the+ * managed MTPLX server.+ *+ * MTPLX serves one checkpoint under its generated model id. The old provider+ * seed used the friendly alias `mtplx`, which made readiness report a mismatch+ * and caused OpenCode to request a model the endpoint did not advertise. Only+ * the untouched sentinel configuration is migrated; a user who selected a+ * different checkpoint or model list keeps that choice.+ */++import { readProvidersDoc, writeJsonAtomic } from './_lib.js';++const OLD_MODEL = 'mtplx';+const NEW_MODEL = 'mtplx-qwen38-27b-optimized-speed';+const PROVIDER_IDS = ['mtplx', 'opencode-mtplx', 'opencode-mtplx-tui'];++const isUntouchedSentinel = (provider) =>+ Array.isArray(provider?.models)+ && provider.models.length === 1+ && provider.models[0] === OLD_MODEL+ && provider.defaultModel === OLD_MODEL;++export default {+ async up({ rootDir }) {+ const doc = await readProvidersDoc({ rootDir });+ if (!doc.ok) return { ok: false, reason: doc.reason, updated: 0 };++ let updated = 0;+ for (const id of PROVIDER_IDS) {+ const provider = doc.providers[id];+ if (!isUntouchedSentinel(provider)) continue;+ provider.models = [NEW_MODEL];+ provider.defaultModel = NEW_MODEL;+ updated += 1;+ }++ if (!updated) return { ok: true, reason: 'already-current-or-custom', updated: 0 };+ await writeJsonAtomic(doc.path, doc.config);+ console.log(`📝 ${doc.path}: aligned ${updated} MTPLX provider model preset${updated === 1 ? '' : 's'} with the served model`);+ return { ok: true, reason: 'updated', updated };+ },+};diff --git a/scripts/migrations/292-mtplx-served-model.test.js b/scripts/migrations/292-mtplx-served-model.test.jsnew file mode 100644index 0000000000..cd4bc96d2b--- /dev/null+++ b/scripts/migrations/292-mtplx-served-model.test.js@@ -0,0 +1,56 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './292-mtplx-served-model.js';++const NEW_MODEL = 'mtplx-qwen38-27b-optimized-speed';+const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));++describe('migration 292 — MTPLX served model', () => {+ let rootDir;+ let providersPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-292-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ providersPath = join(rootDir, 'data/providers.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('updates untouched API and TUI sentinels together', async () => {+ writeJson(providersPath, {+ providers: {+ mtplx: { models: ['mtplx'], defaultModel: 'mtplx' },+ 'opencode-mtplx': { models: ['mtplx'], defaultModel: 'mtplx' },+ 'opencode-mtplx-tui': { models: ['mtplx'], defaultModel: 'mtplx' },+ },+ });++ const result = await migration.up({ rootDir });+ const providers = readJson(providersPath).providers;++ expect(result.updated).toBe(3);+ expect(providers.mtplx).toMatchObject({ models: [NEW_MODEL], defaultModel: NEW_MODEL });+ expect(providers['opencode-mtplx-tui']).toMatchObject({ models: [NEW_MODEL], defaultModel: NEW_MODEL });+ });++ it('preserves a customized checkpoint selection', async () => {+ writeJson(providersPath, {+ providers: {+ mtplx: { models: ['custom-checkpoint'], defaultModel: 'custom-checkpoint' },+ 'opencode-mtplx-tui': { models: ['mtplx', 'custom-checkpoint'], defaultModel: 'custom-checkpoint' },+ },+ });++ const result = await migration.up({ rootDir });+ expect(result.updated).toBe(0);+ expect(readJson(providersPath).providers).toEqual(expect.objectContaining({+ mtplx: { models: ['custom-checkpoint'], defaultModel: 'custom-checkpoint' },+ 'opencode-mtplx-tui': { models: ['mtplx', 'custom-checkpoint'], defaultModel: 'custom-checkpoint' },+ }));+ });+});diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.jsonindex 294d336984..041f238429 100644--- a/server/lib/aiToolkit/defaults/providers.sample.json+++ b/server/lib/aiToolkit/defaults/providers.sample.json@@ -121,8 +121,8 @@"command": "opencode","args": ["run"],"endpoint": "http://127.0.0.1:8000/v1",- "models": ["mtplx"],- "defaultModel": "mtplx",+ "models": ["mtplx-qwen38-27b-optimized-speed"],+ "defaultModel": "mtplx-qwen38-27b-optimized-speed","mtplxBacked": true,"timeout": 600000,"enabled": false,@@ -139,8 +139,8 @@"command": "opencode","args": [],"endpoint": "http://127.0.0.1:8000/v1",- "models": ["mtplx"],- "defaultModel": "mtplx",+ "models": ["mtplx-qwen38-27b-optimized-speed"],+ "defaultModel": "mtplx-qwen38-27b-optimized-speed","mtplxBacked": true,"timeout": 600000,"enabled": false,@@ -527,8 +527,8 @@"type": "api","endpoint": "http://127.0.0.1:8000/v1","apiKey": "",- "models": ["mtplx"],- "defaultModel": "mtplx",+ "models": ["mtplx-qwen38-27b-optimized-speed"],+ "defaultModel": "mtplx-qwen38-27b-optimized-speed","timeout": 300000,"enabled": false,"envVars": {},diff --git a/server/lib/localLlmCatalog.js b/server/lib/localLlmCatalog.jsindex 9368c75924..0441ed7e1e 100644--- a/server/lib/localLlmCatalog.js+++ b/server/lib/localLlmCatalog.js@@ -24,6 +24,7 @@ export const LOCAL_LLM_CATEGORIES = [{ id: 'reasoning', label: 'Reasoning & analysis' },{ id: 'vision', label: 'Image Analysis' },{ id: 'chat', label: 'Chat & voice' },+ { id: 'writing', label: 'Fiction & writing' },// Audio/music GENERATION models (ACE-Step, MusicGen, AudioLDM2, Stable Audio,// Magenta…). These are NOT GGUF chat models and don't run on Ollama/LM Studio// — the Hugging Face search relaxes its GGUF filter for this category and the@@ -290,7 +291,7 @@ export const LOCAL_LLM_CATALOG = [recommendedFor: ['general', 'coding', 'reasoning', 'vision', 'multilingual'],featured: {label: 'Fast on Apple Silicon',- description: 'Recommended native-MLX Qwen3.8 install on Apple Silicon.'+ description: 'Full image-analysis score in the local audit and the faster direct Qwen3.8 decoder fallback; MTPLX completed the end-to-end TUI task sooner.'},params: '27B',size: '15.0 GB',@@ -335,8 +336,8 @@ export const LOCAL_LLM_CATALOG = [category: 'general',recommendedFor: ['general', 'coding', 'reasoning', 'vision', 'multilingual'],featured: {- label: 'Best overall',- description: 'Flagship local pick for general work, coding and agents, reasoning, and image analysis.'+ label: 'Best Qwen3.8 path',+ description: 'For Qwen3.8 CoS tasks, use MTPLX + OpenCode MTPLX TUI; use native MLX when isolated decoder throughput or vision is the priority.'},params: '27B',size: '16.5 GB',@@ -448,6 +449,24 @@ export const LOCAL_LLM_CATALOG = [lmstudio: 'lmstudio-community/Qwen3.5-122B-A10B-GGUF'},// ── Coding / agentic tier ──+ {+ key: 'qwen3-coder-30b',+ name: 'Qwen3-Coder 30B',+ category: 'coding',+ recommendedFor: ['coding', 'general'],+ featured: {+ label: 'Best coding agent',+ description: 'Measured local CoS pick: Ollama + OpenCode TUI. Confirm the local performance record before changing the default on another machine.'+ },+ params: '30B / 3.3B active',+ size: '19 GB',+ family: 'qwen',+ description: 'Qwen\'s agentic coding model for repository work, tool calling, and multi-step software-engineering tasks. The audit made this the primary coding/TUI recommendation on the current Apple Silicon profile.',+ capabilities: ['chat', 'code', 'tools'],+ context: 262144,+ repository: 'Qwen/Qwen3-Coder-30B-A3B-Instruct',+ ollama: 'qwen3-coder:30b'+ },{key: 'ornith-9b',name: 'Ornith 1.0 9B',@@ -529,6 +548,25 @@ export const LOCAL_LLM_CATALOG = [ollama: 'qwen3.6:35b',lmstudio: 'unsloth/Qwen3.6-35B-A3B-GGUF'},+ // ── Fiction / writing tier ──+ {+ key: 'qwen3.6-fable-fusion',+ name: 'Qwen3.6 Fable Fusion 27B',+ category: 'writing',+ recommendedFor: ['writing', 'general'],+ featured: {+ label: 'Best fiction candidate',+ description: 'Best fiction-specialist result in the local audit. The screen is structural, not an aesthetic judgment—read the saved prose.'+ },+ params: '27B',+ size: '31 GB',+ family: 'qwen',+ description: 'A Qwen3.6 Fable Fusion checkpoint for fiction drafting and narrative voice experiments. Keep a general or coding model selected for agentic repository work.',+ capabilities: ['chat', 'reasoning'],+ context: 262144,+ repository: 'DavidAU/Qwen3.6-27B-Fable-Fusion-711-Uncensored-Heretic-NM-DAU-NEO-MAX-MTP-GGUF',+ ollama: 'hf.co/DavidAU/Qwen3.6-27B-Fable-Fusion-711-Uncensored-Heretic-NM-DAU-NEO-MAX-MTP-GGUF:Q8_0'+ },// ── Vision / image analysis tier ──{key: 'minicpm-v4.6',diff --git a/server/lib/localLlmCatalog.test.js b/server/lib/localLlmCatalog.test.jsindex 019ef3294d..c4940ee41d 100644--- a/server/lib/localLlmCatalog.test.js+++ b/server/lib/localLlmCatalog.test.js@@ -128,7 +128,7 @@ describe('localLlmCatalog', () => {const qwen = getCatalog('ollama').find((m) => m.key === 'qwen3.8-27b');expect(qwen).toMatchObject({category: 'general',- featured: { label: 'Best overall' },+ featured: { label: 'Best Qwen3.8 path' },id: 'hf.co/unsloth/Qwen3.8-27B-GGUF:UD-Q4_K_M',size: '16.5 GB',repository: 'unsloth/Qwen3.8-27B-GGUF',@@ -138,6 +138,19 @@ describe('localLlmCatalog', () => {expect(qwen.capabilities).toEqual(expect.arrayContaining(['code', 'tools', 'vision']));});+ it('surfaces the measured coding and fiction recommendations in the Ollama catalog', () => {+ expect(getCatalog('ollama').find((m) => m.key === 'qwen3-coder-30b')).toMatchObject({+ id: 'qwen3-coder:30b',+ category: 'coding',+ featured: { label: 'Best coding agent' },+ capabilities: ['chat', 'code', 'tools'],+ });+ expect(getCatalog('ollama').find((m) => m.key === 'qwen3.6-fable-fusion')).toMatchObject({+ category: 'writing',+ featured: { label: 'Best fiction candidate' },+ });+ });+it('still treats an older Unsloth Q4_K_M install as the same Qwen3.8 catalog entry', () => {const qwen = getCatalog('ollama', ['hf.co/unsloth/Qwen3.8-27B-GGUF:Q4_K_M']).find((m) => m.key === 'qwen3.8-27b');diff --git a/server/lib/localModelAssessment.js b/server/lib/localModelAssessment.jsindex d63afc7125..7e8fd51c1a 100644--- a/server/lib/localModelAssessment.js+++ b/server/lib/localModelAssessment.js@@ -164,6 +164,10 @@ export function summarizePerformance(samples) {meanTokensPerSecond: meanOf(samples, 'tokensPerSecond'),peakTokensPerSecond: tokenRates.length ? Math.max(...tokenRates) : null,meanPromptTokensPerSecond: meanOf(samples, 'promptTokensPerSecond'),+ timingSource: (() => {+ const sources = [...new Set(ok.map((s) => s.timingSource).filter(Boolean))];+ return sources.length === 1 ? sources[0] : (sources.length ? 'mixed' : null);+ })(),// `true` when ANY contributing sample counted streamed frames instead of// reading the daemon's own count. One estimated sample makes the mean an// estimate, so this is deliberately pessimistic. `null` = no token evidence.@@ -219,6 +223,7 @@ export function buildThroughputReport(assessments) {charsPerSecond: num(sample.charsPerSecond),ttftMs: num(sample.ttftMs),completionTokens: num(sample.completionTokens),+ timingSource: sample.timingSource || null,error: sample?.error || null,});}@@ -240,6 +245,7 @@ export function buildThroughputReport(assessments) {meanPromptTokensPerSecond: num(perf.meanPromptTokensPerSecond),meanCharsPerSecond: num(perf.meanCharsPerSecond),meanTtftMs: num(perf.meanTtftMs),+ timingSource: perf.timingSource || null,tokensEstimated: typeof perf.tokensEstimated === 'boolean' ? perf.tokensEstimated : null,points: points.sort((a, b) => a.contextTokens - b.contextTokens),});diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.jsindex 82fe7a204f..152b5e257d 100644--- a/server/lib/mediaValidation.js+++ b/server/lib/mediaValidation.js@@ -306,11 +306,11 @@ export const localLlmAssessmentSweepSchema = z.object({export const localLlmAssessmentIntentSchema = z.object({intent: z.enum(['balanced', 'smartest', 'fastest', 'lightweight']).optional().default('balanced'),});-// One explicit OpenCode task through each of the three Qwen runtime presets.-// The service still restricts the model id to the named target for that backend-// so this endpoint cannot become an arbitrary CLI launcher.+// One explicit local-TUI task through each configured Qwen runtime preset. The+// service still restricts the model id and provider to the named target for that+// backend, so this endpoint cannot become an arbitrary CLI launcher.export const localLlmAgentBenchmarkSchema = z.object({- backend: z.enum(['ollama', 'mtplx', 'llama']),+ backend: z.enum(['ollama', 'ollama-coder', 'mtplx', 'llama', 'claude-ollama']),modelId: localLlmModelIdSchema,timeoutMs: z.coerce.number().int().min(10000).max(600000).optional().default(600000),});diff --git a/server/lib/modelCapabilityTests.js b/server/lib/modelCapabilityTests.jsindex 67d5083eff..12dd0086f6 100644--- a/server/lib/modelCapabilityTests.js+++ b/server/lib/modelCapabilityTests.js@@ -42,6 +42,12 @@ export const CAPABILITY_TEST_PROMPTS = Object.freeze({'',"Outline this as a hero's journey in twelve beats. Give each beat its standard name as a heading, followed by one short paragraph.",].join('\n'),+ 'fiction-scene': [+ 'Premise: a tidal-marsh oyster farmer finds that the water killing her beds is coming from the sea wall she campaigned to build.',+ '',+ 'Write a 350–500 word opening scene in close third person.',+ 'Keep the prose concrete and sensory. Include one spoken line of dialogue, the oyster farmer taking a consequential action, and a final turn that makes the sea wall the source of the dying water.',+ ].join('\n'),});/**@@ -96,6 +102,15 @@ export const CAPABILITY_TESTS = Object.freeze([blurb: "Outline a hero's-journey story from one premise. Scored on how many of the twelve beats are present and in order.",driver: 'chat',}),+ Object.freeze({+ id: 'fiction-scene',+ label: 'Fiction scene',+ kind: 'text',+ capabilities: Object.freeze(['chat']),+ prefers: Object.freeze(['reasoning']),+ blurb: 'Write a short opening scene from a fixed premise. Scored on required story facts plus minimum scene craft signals; read the saved prose for quality.',+ driver: 'chat',+ }),]);export const CAPABILITY_TEST_IDS = Object.freeze(CAPABILITY_TESTS.map((t) => t.id));@@ -161,6 +176,28 @@ export const VISION_FIXTURE_KEYWORDS = Object.freeze({]),});+/**+ * The fiction fixture's content anchors. This is deliberately a modest+ * structural rubric, not a claim that keywords can judge literary quality.+ * The complete scene is retained so a human can read the prose after the+ * deterministic checks have separated a coherent attempt from a refusal or a+ * generic paragraph.+ */+export const FICTION_SCENE_KEYWORDS = Object.freeze({+ required: Object.freeze([+ Object.freeze({ id: 'tidal-marsh', label: 'Tidal-marsh setting', any: Object.freeze(['tidal marsh', 'marsh', 'estuary']) }),+ Object.freeze({ id: 'oyster-farmer', label: 'Oyster farmer', any: Object.freeze(['oyster farmer', 'oyster grower']) }),+ Object.freeze({ id: 'dying-beds', label: 'Dying oyster beds', any: Object.freeze(['dying', 'dead', 'die', 'killing', 'rot']) }),+ Object.freeze({ id: 'sea-wall', label: 'Sea wall', any: Object.freeze(['sea wall', 'seawall']) }),+ Object.freeze({ id: 'water', label: 'Water as the immediate problem', any: Object.freeze(['water', 'brine', 'tide', 'salt']) }),+ ]),+ bonus: Object.freeze([+ Object.freeze({ id: 'sensory-detail', label: 'Concrete sensory detail', any: Object.freeze(['mud', 'silt', 'stench', 'stink', 'cold', 'wind', 'grit', 'slick']) }),+ Object.freeze({ id: 'spoken-line', label: 'Spoken line', any: Object.freeze(['said', 'asked', 'whispered', 'shouted', 'murmured']) }),+ Object.freeze({ id: 'consequence', label: 'Consequential action', any: Object.freeze(['cut', 'climb', 'break', 'open', 'pull', 'wade', 'run', 'turn']) }),+ ]),+});+// A phrase is matched on word boundaries so "bike" does not fire on "bikeshed"// and "3" does not fire inside "1024x3". Multi-word phrases tolerate any run of// whitespace, because a wrapped transcript can break "lamp post" across lines.@@ -296,6 +333,46 @@ export function scoreStoryBeats(text, beats = HEROS_JOURNEY_BEATS) {};}+/**+ * Score a short fiction scene without pretending that a lexical rubric is an+ * aesthetic judge. Required anchors establish that the model followed the+ * premise; length, paragraphing, and dialogue establish that it attempted a+ * scene rather than returning notes. The prose itself remains the evidence a+ * human should use for voice, originality, and sentence quality.+ *+ * @returns {{verdict:string, summary:string, required:Array, bonus:Array,+ * requiredHit:number, requiredTotal:number, bonusHit:number, bonusTotal:number,+ * wordCount:number, paragraphCount:number, hasDialogue:boolean}}+ */+export function scoreFictionScene(text, spec = FICTION_SCENE_KEYWORDS) {+ const keyword = scoreKeywords(text, spec);+ const source = String(text || '').trim();+ const words = source ? source.split(/\s+/u).filter(Boolean) : [];+ const paragraphs = source ? source.split(/\n\s*\n/u).map((p) => p.trim()).filter(Boolean) : [];+ const hasDialogue = /["“][^"”\n]{2,}["”]/u.test(source)+ || /\b(?:said|asked|whispered|shouted|murmured)\s*:\s*\S/iu.test(source)+ || /(?:^|\n)\s*—\s*\S(?:.*\S)?$/mu.test(source);+ const craft = {+ minimumWords: words.length >= 350 && words.length <= 500,+ paragraphs: paragraphs.length >= 3,+ dialogue: hasDialogue,+ };+ const craftHit = Object.values(craft).filter(Boolean).length;+ const requiredComplete = keyword.requiredHit === keyword.requiredTotal;+ const verdict = requiredComplete && craftHit === Object.keys(craft).length+ ? 'passed'+ : (keyword.requiredHit >= Math.ceil(keyword.requiredTotal * 0.6) && craftHit >= 1 ? 'partial' : 'failed');+ return {+ ...keyword,+ verdict,+ wordCount: words.length,+ paragraphCount: paragraphs.length,+ hasDialogue,+ craft,+ summary: `${keyword.requiredHit} of ${keyword.requiredTotal} story anchors, ${keyword.bonusHit} of ${keyword.bonusTotal} scene signals, ${craftHit} of ${Object.keys(craft).length} minimum craft checks, ${words.length} words`,+ };+}+// ---- sandbox-repair scoring -------------------------------------------------/**@@ -340,4 +417,3 @@ export function rollUpVerdict(verdicts) {if (list.includes('partial')) return 'partial';return 'passed';}-diff --git a/server/lib/modelCapabilityTests.test.js b/server/lib/modelCapabilityTests.test.jsindex f3b3fc0296..9e8d3b7647 100644--- a/server/lib/modelCapabilityTests.test.js+++ b/server/lib/modelCapabilityTests.test.js@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import {CAPABILITY_TESTS,+ FICTION_SCENE_KEYWORDS,HEROS_JOURNEY_BEATS,VISION_FIXTURE_KEYWORDS,applicabilityFor,@@ -9,6 +10,7 @@ import {getCapabilityTest,rollUpVerdict,scoreKeywords,+ scoreFictionScene,scoreSandboxRepair,scoreStoryBeats,} from './modelCapabilityTests.js';@@ -124,6 +126,40 @@ describe('scoreStoryBeats', () => {});});+describe('scoreFictionScene', () => {+ const scene = [+ 'At dawn the tidal marsh breathed mud and salt around Mara, the oyster farmer, while the dying beds clicked below the water. The flats should have been silver with shells, but a skin of black scum gathered between the stakes and turned the tide opaque. Gulls wheeled above the racks, their cries thin in the fog. Mara had spent twenty years learning the marsh by touch: the safe firmness of a bed, the soft collapse of silt, the sweet iron smell that warned of a dead pocket. This water carried a harsher sting that coated her tongue and made the oysters clamp shut. She lifted one from its cage and found its shell warm, its living edge withdrawn.',+ 'She waded toward the sea wall, heard the wind in its cracks, and pulled a rusted gate open. The wall had been her victory once, a straight grey promise against the storms. Now its stones sweated warm water that smelled of pennies and rot, and the current pressed inland instead of out. Behind her, the pumps coughed in the work shed, trying to draw clean water through a pipe that had begun to tremble. The oldest bedhands had warned her about that vibration, but she had signed the inspection anyway, trusting a survey stamped by the county more than the unease in her palms.',+ '“Stay back,” she said, though nobody stood beside her. Her boots sank past the ankles. She cut the rope on the inspection ladder, climbed through the reeds, and reached for the valve she had signed off on herself. The metal shuddered under her palm. A memory came back with the pressure: the wall being poured, her younger hands smoothing concrete while the mayor called it a promise. She had told the cameras that the marsh would finally be safe. Now every turn of the wheel felt like opening the door on that lie.',+ 'Black water poured through the breach. The sea wall was feeding the beds their death. Mara watched the current carry a pale oyster shell into the channel, then took the wrench from her belt and began to undo the gate before the next tide arrived. The first bolt resisted, then cracked loose hard enough to numb her fingers. Somewhere behind the wall, a hidden sluice groaned and answered. She braced one shoulder against the wheel, tasted salt and metal, and kept turning while the tide climbed over the dying beds.',+ ].join('\n\n');++ it('passes a scene that follows the premise and the craft gate', () => {+ const scored = scoreFictionScene(scene, FICTION_SCENE_KEYWORDS);+ expect(scored.verdict).toBe('passed');+ expect(scored.requiredHit).toBe(scored.requiredTotal);+ expect(scored.hasDialogue).toBe(true);+ expect(scored.paragraphCount).toBe(4);+ expect(scored.summary).toContain('3 of 3 scene signals');+ expect(scored.summary).toContain('3 of 3 minimum craft checks');+ });++ it('keeps a content attempt partial when the scene craft is incomplete', () => {+ const scored = scoreFictionScene('The oyster farmer saw the tidal marsh, the sea wall, and water. The beds were dying. “Not again,” she said.', FICTION_SCENE_KEYWORDS);+ expect(scored.verdict).toBe('partial');+ expect(scored.wordCount).toBeLessThan(350);+ });++ it('does not count speech-attribution prose as dialogue', () => {+ const scored = scoreFictionScene('The oyster farmer said the tidal marsh was changing, and the sea wall held back the dying water.', FICTION_SCENE_KEYWORDS);+ expect(scored.hasDialogue).toBe(false);+ });++ it('fails generic prose that does not follow the fixed premise', () => {+ expect(scoreFictionScene('A person walked through a city and watched the rain.', FICTION_SCENE_KEYWORDS).verdict).toBe('failed');+ });+});+describe('scoreSandboxRepair', () => {it('passes only when the test command actually exits 0', () => {expect(scoreSandboxRepair({ moduleChanged: true, fixturesIntact: true, testsPass: true, toolCalls: 3 }).verdict).toBe('passed');@@ -158,4 +194,3 @@ describe('rollUpVerdict', () => {expect(rollUpVerdict([undefined, null])).toBeNull();});});-diff --git a/server/lib/openAiChatStream.js b/server/lib/openAiChatStream.jsindex 52c497cc56..0a6cc94858 100644--- a/server/lib/openAiChatStream.js+++ b/server/lib/openAiChatStream.js@@ -46,12 +46,23 @@ export function parseStreamFrame(rawLine) {return null;}const delta = parsed?.choices?.[0]?.delta;- return {+ const frame = {content: delta?.content || '',- reasoning: delta?.reasoning || '',+ // llama.cpp/MTPLX commonly name the hidden channel `reasoning_content`;+ // normalize it beside the OpenAI `reasoning` spelling so a reasoning-only+ // answer is not reduced to a stray newline and scored as a one-character+ // generation.+ reasoning: delta?.reasoning || delta?.reasoning_content || delta?.thinking || '',// `null` = this frame reported no usage, which is every frame but the last.usage: parsed?.usage && typeof parsed.usage === 'object' ? parsed.usage : null,};+ // llama.cpp puts its authoritative prompt/decode timings on the terminal+ // chunk rather than inside OpenAI's usage object. MTPLX carries a richer+ // sibling stats block. Keep both optional so ordinary OpenAI frames retain+ // the small stable shape callers already consume.+ if (parsed?.timings && typeof parsed.timings === 'object') frame.timings = parsed.timings;+ if (parsed?.mtplx_stats && typeof parsed.mtplx_stats === 'object') frame.mtplxStats = parsed.mtplx_stats;+ return frame;}// Endpoints that answered 4xx to `stream_options`. A sweep runs hundreds of@@ -91,6 +102,34 @@ export function normalizeUsage(usage) {};}+/**+ * Normalize runtime-specific timing blocks into milliseconds and counts.+ *+ * The OpenAI-compatible surface does not standardize decode timing: llama.cpp+ * uses `predicted_ms`, while MTPLX reports seconds in `mtplx_stats`. Without+ * this translation the generic clock fallback subtracts TTFT from a one-frame+ * response and can report absurd rates such as tens of thousands of tokens/s.+ * Missing fields stay absent so the caller can preserve the null sentinel.+ */+export function normalizeRuntimeTiming(timings, mtplxStats) {+ const t = timings && typeof timings === 'object' ? timings : {};+ const s = mtplxStats && typeof mtplxStats === 'object' ? mtplxStats : {};+ const firstFinite = (...values) => values.find((value) => Number.isFinite(value) && value >= 0);+ const result = {};+ const promptTokens = firstFinite(t.prompt_n, t.prompt_tokens, s.prompt_tokens);+ const completionTokens = firstFinite(t.predicted_n, t.completion_tokens, s.completion_tokens, s.generated_tokens);+ const promptMs = firstFinite(t.prompt_ms, t.prompt_eval_ms,+ Number.isFinite(s.prompt_eval_time_s) ? s.prompt_eval_time_s * 1000 : null);+ const completionMs = firstFinite(t.predicted_ms, t.completion_ms,+ Number.isFinite(s.decode_elapsed_s) ? s.decode_elapsed_s * 1000 : null,+ Number.isFinite(s.elapsed_s) ? s.elapsed_s * 1000 : null);+ if (promptTokens !== undefined) result.promptTokens = promptTokens;+ if (completionTokens !== undefined) result.completionTokens = completionTokens;+ if (promptMs !== undefined) result.promptMs = promptMs;+ if (completionMs !== undefined) result.completionMs = completionMs;+ return result;+}+/*** Parse one native Ollama `/api/chat` NDJSON frame.*@@ -209,7 +248,7 @@ export async function streamOpenAiChat({signal,body: JSON.stringify({model,- messages: toOllamaMessages(messages),+ messages,stream: true,temperature,max_tokens: maxTokens,@@ -226,16 +265,30 @@ export async function streamOpenAiChat({// mean "I did not like this body": a 401 (key-gated vLLM), a 404, a 5xx, or a// transport error all say nothing about `stream_options`, and retrying them// would double every real failure.- if (!response.ok && includeUsage && (response.status === 400 || response.status === 422) && !signal?.aborted) {- console.log(`⚠️ Local LLM: ${model} rejected stream_options (${response.status}) — retrying without usage reporting`);- usageUnsupportedEndpoints.add(url);- // Drain the rejected response so its socket is released before the retry.- await response.body?.cancel?.().catch(() => {});- response = await post(false);+ let responseErrorBody = '';+ const mayRejectUsage = !response.ok+ && includeUsage+ && (response.status === 400 || response.status === 422)+ && !signal?.aborted;+ if (mayRejectUsage) {+ // A bad model or request can also be a 400/422. Inspect the body before+ // caching endpoint capability, otherwise one unrelated failure disables+ // exact usage collection for every later sample on this daemon.+ responseErrorBody = typeof response.clone === 'function'+ ? await response.clone().text().catch(() => '')+ : (response.text ? await response.text().catch(() => '') : response.error || '');+ if (/stream_options|include_usage/i.test(responseErrorBody)) {+ console.log(`⚠️ Local LLM: ${model} rejected stream_options (${response.status}) — retrying without usage reporting`);+ usageUnsupportedEndpoints.add(url);+ // Drain the rejected response so its socket is released before the retry.+ await response.body?.cancel?.().catch(() => {});+ responseErrorBody = '';+ response = await post(false);+ }}if (!response.ok) {- const body = response.text ? await response.text().catch(() => '') : response.error || '';+ const body = responseErrorBody || (response.text ? await response.text().catch(() => '') : response.error || '');throw new Error(`Provider returned ${response.status || 0}: ${body || response.error || response.statusText || 'request failed'}`);}@@ -283,11 +336,15 @@ export async function streamOpenAiChat({// it — the two would disagree systematically on every reasoning model.let usage = null;let contentFrames = 0;+ let runtimeTimings = null;+ let mtplxStats = null;const consumeLine = async (rawLine) => {const delta = parseStreamFrame(rawLine);if (!delta) return;if (delta.usage) usage = delta.usage;+ if (delta.timings) runtimeTimings = delta.timings;+ if (delta.mtplxStats) mtplxStats = delta.mtplxStats;if (delta.content) contentFrames += 1;if (delta.content) {output += delta.content;@@ -322,12 +379,19 @@ export async function streamOpenAiChat({throw err;} finally {const reported = normalizeUsage(usage);+ const runtime = normalizeRuntimeTiming(runtimeTimings, mtplxStats);emitStats(reported.completionTokens !== null- ? { ...reported, estimated: false }+ ? { ...reported, ...runtime, estimated: false }// No usage block: fall back to the streamed-frame count, which is the only// token-shaped evidence we have. `null` when nothing streamed at all —// reporting 0 would file a transport failure as a zero-token generation.- : { completionTokens: contentFrames > 0 ? contentFrames : null, promptTokens: reported.promptTokens, estimated: contentFrames > 0 });+ : {+ completionTokens: runtime.completionTokens ?? (contentFrames > 0 ? contentFrames : null),+ promptTokens: runtime.promptTokens ?? reported.promptTokens,+ ...(runtime.promptMs !== undefined ? { promptMs: runtime.promptMs } : {}),+ ...(runtime.completionMs !== undefined ? { completionMs: runtime.completionMs } : {}),+ estimated: runtime.completionTokens === undefined && contentFrames > 0,+ });await reader.cancel().catch(() => {});}@@ -400,7 +464,7 @@ export async function streamOllamaChat({signal,body: JSON.stringify({model,- messages,+ messages: toOllamaMessages(messages),stream: true,...(Object.keys(options).length ? { options } : {}),...(typeof think === 'boolean' ? { think } : {}),diff --git a/server/lib/openAiChatStream.test.js b/server/lib/openAiChatStream.test.jsindex 3b27022a29..d44fbe896d 100644--- a/server/lib/openAiChatStream.test.js+++ b/server/lib/openAiChatStream.test.js@@ -13,10 +13,12 @@ import { describe, it, expect, vi } from 'vitest';import {buildMessages,normalizeUsage,+ normalizeRuntimeTiming,parseOllamaStreamFrame,parseStreamFrame,resolvePartialOutput,streamOllamaChat,+ toOllamaMessages,} from './openAiChatStream.js';describe('buildMessages', () => {@@ -34,6 +36,22 @@ describe('buildMessages', () => {});});+describe('toOllamaMessages', () => {+ it('converts OpenAI image parts to Ollama text plus bare base64 images', () => {+ expect(toOllamaMessages([{+ role: 'user',+ content: [+ { type: 'image_url', image_url: { url: 'data:image/png;base64,abc123' } },+ { type: 'text', text: 'Describe this.' },+ ],+ }])).toEqual([{+ role: 'user',+ content: 'Describe this.',+ images: ['abc123'],+ }]);+ });+});+describe('parseStreamFrame — deltas', () => {it('parses an OpenAI-style content delta', () => {const line = 'data: {"choices":[{"delta":{"content":"Hi"}}]}';@@ -45,6 +63,11 @@ describe('parseStreamFrame — deltas', () => {expect(parseStreamFrame(line)).toEqual({ content: '', reasoning: 'thinking', usage: null });});+ it('normalizes llama.cpp reasoning_content deltas', () => {+ const line = 'data: {"choices":[{"delta":{"reasoning_content":"thinking"}}]}';+ expect(parseStreamFrame(line)).toEqual({ content: '', reasoning: 'thinking', usage: null });+ });+it('skips non-data lines and the [DONE]/✅ sentinels', () => {expect(parseStreamFrame(': keep-alive')).toBeNull();expect(parseStreamFrame('data: [DONE]')).toBeNull();@@ -59,6 +82,14 @@ describe('parseStreamFrame — deltas', () => {it('tolerates a frame with no delta', () => {expect(parseStreamFrame('data: {"choices":[{}]}')).toEqual({ content: '', reasoning: '', usage: null });});++ it('preserves llama.cpp timing blocks from the terminal frame', () => {+ expect(parseStreamFrame('data: {"choices":[],"timings":{"prompt_n":20,"predicted_n":10,"prompt_ms":100,"predicted_ms":250}}'))+ .toMatchObject({+ content: '', reasoning: '', usage: null,+ timings: { prompt_n: 20, predicted_n: 10, prompt_ms: 100, predicted_ms: 250 },+ });+ });});describe('resolvePartialOutput', () => {@@ -117,6 +148,18 @@ describe('normalizeUsage', () => {});});+describe('normalizeRuntimeTiming', () => {+ it('converts llama.cpp millisecond timings', () => {+ expect(normalizeRuntimeTiming({ prompt_n: 20, predicted_n: 10, prompt_ms: 100, predicted_ms: 250 }))+ .toEqual({ promptTokens: 20, completionTokens: 10, promptMs: 100, completionMs: 250 });+ });++ it('converts MTPLX seconds without falling back to TTFT subtraction', () => {+ expect(normalizeRuntimeTiming(null, { prompt_tokens: 20, generated_tokens: 10, prompt_eval_time_s: 0.1, decode_elapsed_s: 0.25 }))+ .toEqual({ promptTokens: 20, completionTokens: 10, promptMs: 100, completionMs: 250 });+ });+});+describe('parseOllamaStreamFrame', () => {it('reads native content and thinking deltas', () => {expect(parseOllamaStreamFrame(JSON.stringify({ message: { content: 'answer', thinking: 'hmm' } })))diff --git a/server/lib/tuiPromptRunner.js b/server/lib/tuiPromptRunner.jsindex 716f8c8217..5e081c15ae 100644--- a/server/lib/tuiPromptRunner.js+++ b/server/lib/tuiPromptRunner.js@@ -139,9 +139,11 @@ const PTY_ROWS = 50;* @param {string} [options.label] — human label for the live Shell view (the* run `source`, e.g. `'pipeline-manuscript-completeness'`). Surfaced in the* Shell page's session tab; falls back to `command · model` when absent.+ * @param {boolean} [options.guard=false] — prepend the PM2 guard shim for an+ * autonomous task that must not be able to kill the shared PortOS daemon.* @returns {Promise<void>}*/-export async function executeTuiRun({ runId, provider, prompt, workspacePath, onData, onComplete, timeout, idleMs, label }) {+export async function executeTuiRun({ runId, provider, prompt, workspacePath, onData, onComplete, timeout, idleMs, label, guard = false }) {if (!provider || typeof provider !== 'object') {throw new Error('executeTuiRun: provider is required');}@@ -219,6 +221,7 @@ ${prompt}`;const childEnv = buildCliChildEnv({provider,cwd: workingDir,+ guard,extra: { TERM: 'xterm-256color', COLORTERM: 'truecolor' },});diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 039b016be7..26464aa97e 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -495,7 +495,7 @@ router.post('/assessments/run', asyncHandler(async (req, res) => {}))// POST /api/local-llm/assessments/agent-benchmark — run one explicit,-// disposable OpenCode task through a configured local TUI provider. This is+// disposable local-TUI task through a configured local provider. This is// deliberately separate from `/run`: it measures task-loop completion, not just// decoder speed, and never runs from a read/poll/bootstrap path.router.post('/assessments/agent-benchmark', asyncHandler(async (req, res) => {@@ -556,10 +556,11 @@ router.post('/assessments/delete', asyncHandler(async (req, res) => {// === Capability tests ========================================================// The assessments above answer "how fast is this model here". These answer the// question speed cannot: can it do what its badges claim? One test per-// capability — tool use (repair a module in a sandbox, driven through a real-// OpenCode TUI), vision (describe a fixture image, scored on required and bonus-// keywords), and chat/reasoning (a twelve-beat story outline, scored on beat-// coverage). Every run keeps the model's full output.+// capability — tool use (repair a module in a sandbox, driven through the+// configured OpenCode task driver), vision (describe a fixture image, scored on+// required and bonus keywords), and chat/reasoning (a twelve-beat story outline+// plus a fiction scene, scored on structural signals). Every run keeps the+// model's full output.//// Same read/run split as the assessments, and for the same reason: GET touches// disk only; POST /run is the ONLY path that reaches a model, and it fires fromdiff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.jsindex be2371c7f3..ace891ab6f 100644--- a/server/routes/localLlm.test.js+++ b/server/routes/localLlm.test.js@@ -534,7 +534,7 @@ describe('measured assessments wiring', () => {});});- it('rejects an agent benchmark backend outside the three local targets', async () => {+ it('rejects an agent benchmark backend outside the configured local targets', async () => {const res = await request(makeApp()).post('/api/local-llm/assessments/agent-benchmark').send({ backend: 'vllm', modelId: 'qwen3.8-27b-dflash2' });diff --git a/server/services/huggingFaceCatalog.js b/server/services/huggingFaceCatalog.jsindex 111d649b17..63e540fa15 100644--- a/server/services/huggingFaceCatalog.js+++ b/server/services/huggingFaceCatalog.js@@ -47,6 +47,7 @@ const CATEGORY_SEARCH = {chat: 'instruct gguf',reasoning: 'reasoning gguf',coding: 'coder gguf',+ writing: 'fiction gguf',vision: 'vision gguf',// Audio is NOT a GGUF category — the search relaxes the GGUF filter for it// (see `searchHuggingFaceModels`) and these terms surface generation models.diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.jsindex c5b420c5fa..2ee1129167 100644--- a/server/services/localLlmPlayground.js+++ b/server/services/localLlmPlayground.js@@ -39,8 +39,9 @@ export function buildPrompt({ systemPrompt, prompt }) {* @param {{ completionTokens: number|null, promptTokens: number|null, estimated: boolean }} [usage]* token counts from `streamOpenAiChat`'s `onStats`. Absent entirely for a* caller that does not track usage, which records `null` — not zero.+ * @param {number|null} [streamChunks] number of non-empty streamed chunks*/-export function summarizeTimings({ startedAt, firstChunkAt, endedAt, text, usage }) {+export function summarizeTimings({ startedAt, firstChunkAt, endedAt, text, usage, streamChunks = null }) {const totalMs = endedAt - startedAt;const ttftMs = firstChunkAt ? firstChunkAt - startedAt : null;const chars = text.length;@@ -59,7 +60,10 @@ export function summarizeTimings({ startedAt, firstChunkAt, endedAt, text, usageconst reportedPromptMs = Number.isFinite(usage?.promptMs) && usage.promptMs > 0? usage.promptMs: null;- const decodeMs = reportedDecodeMs ?? (Number.isFinite(ttftMs) ? totalMs - ttftMs : totalMs);+ const observedDecodeMs = (streamChunks === null || streamChunks > 1) && Number.isFinite(ttftMs)+ ? totalMs - ttftMs+ : totalMs;+ const decodeMs = reportedDecodeMs ?? observedDecodeMs;const rate = (tokens, ms) =>(Number.isFinite(tokens) && tokens > 0 && ms > 0 ? Number((tokens / (ms / 1000)).toFixed(2)) : null);@@ -85,6 +89,13 @@ export function summarizeTimings({ startedAt, firstChunkAt, endedAt, text, usage// the report auditable and avoids forcing readers to reverse the rates.decodeMs: reportedDecodeMs,promptMs: reportedPromptMs,+ // Runtime timings are authoritative. When they are absent, a response+ // delivered in multiple chunks has an observable decode window; a single+ // chunk does not, so its token rate uses end-to-end wall time rather than+ // subtracting TTFT from a near-zero remainder.+ timingSource: reportedDecodeMs+ ? 'runtime'+ : (streamChunks !== null && streamChunks <= 1 ? 'wall-clock' : 'stream-window'),// Whether the token count came from the daemon's own tokenizer (`false`) or// from counting streamed frames (`true`). `null` = no token count at all.// A consumer must label an estimate as one — PortOS has no tokenizer, and@@ -185,6 +196,7 @@ export async function runLocalLlmTest({// Stays null until then so a run that died before any frame records "no token// count" rather than a fabricated zero.let usage = null;+ let streamChunks = 0;const onStats = (stats) => { usage = stats; };try {@@ -227,6 +239,7 @@ export async function runLocalLlmTest({// 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();+ if (chunk) streamChunks += 1;// 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.@@ -243,7 +256,7 @@ export async function runLocalLlmTest({providerId: provider.id,runId,text,- timings: summarizeTimings({ startedAt, firstChunkAt, endedAt, text, usage }),+ timings: summarizeTimings({ startedAt, firstChunkAt, endedAt, text, usage, streamChunks }),options: { temperature, maxTokens, timeoutMs, nativeOllamaUsage },};} catch (err) {@@ -272,7 +285,7 @@ export async function runLocalLlmTest({runId,error,text: partialText,- timings: summarizeTimings({ startedAt, firstChunkAt, endedAt, text: partialText, usage }),+ timings: summarizeTimings({ startedAt, firstChunkAt, endedAt, text: partialText, usage, streamChunks }),options: { temperature, maxTokens, timeoutMs, nativeOllamaUsage },};}@@ -313,6 +326,7 @@ export async function runEndpointLlmTest({const startedAt = Date.now();let firstChunkAt = null;let usage = null;+ let streamChunks = 0;const timeoutController = new AbortController();const timeoutHandle = setTimeout(() => timeoutController.abort(), timeoutMs);const signal = anyAbortSignal([clientSignal, timeoutController.signal]);@@ -330,6 +344,7 @@ export async function runEndpointLlmTest({onStats: (stats) => { usage = stats; },onChunk: (chunk, kind = 'content') => {if (!firstChunkAt && chunk) firstChunkAt = Date.now();+ if (chunk) streamChunks += 1;if (chunk) return onToken?.(chunk, kind);return undefined;},@@ -339,7 +354,7 @@ export async function runEndpointLlmTest({modelId,endpoint,text,- timings: summarizeTimings({ startedAt, firstChunkAt, endedAt: Date.now(), text, usage }),+ timings: summarizeTimings({ startedAt, firstChunkAt, endedAt: Date.now(), text, usage, streamChunks }),options: { temperature, maxTokens, timeoutMs },};} catch (err) {@@ -352,7 +367,7 @@ export async function runEndpointLlmTest({endpoint,error,text: partialText,- timings: summarizeTimings({ startedAt, firstChunkAt, endedAt: Date.now(), text: partialText, usage }),+ timings: summarizeTimings({ startedAt, firstChunkAt, endedAt: Date.now(), text: partialText, usage, streamChunks }),options: { temperature, maxTokens, timeoutMs },};}diff --git a/server/services/localLlmPlayground.test.js b/server/services/localLlmPlayground.test.jsindex 8d3d5f1ece..abc11d18ad 100644--- a/server/services/localLlmPlayground.test.js+++ b/server/services/localLlmPlayground.test.js@@ -58,6 +58,15 @@ describe('summarizeTimings', () => {expect(t.tokensEstimated).toBe(false);});+ it('uses wall clock for a one-chunk response when no runtime decode duration exists', () => {+ const t = summarizeTimings({+ startedAt: 0, firstChunkAt: 1000, endedAt: 3000, text: 'abc', streamChunks: 1,+ usage: { completionTokens: 100, promptTokens: 4000, estimated: false },+ });+ expect(t.tokensPerSecond).toBe(33.33);+ expect(t.timingSource).toBe('wall-clock');+ });+it('prefers native decode and prefill durations when the runtime reports them', () => {const t = summarizeTimings({startedAt: 0, firstChunkAt: 1000, endedAt: 3000, text: 'abc',@@ -381,6 +390,15 @@ describe('token counting through the stream', () => {expect(JSON.parse(global.fetch.mock.calls[0][1].body).stream_options).toBeUndefined();});+ it('does not cache an unrelated 400 as stream_options incompatibility', async () => {+ global.fetch = vi.fn().mockResolvedValue({ ok: false, status: 400, text: async () => 'invalid model name' });++ const result = await runLocalLlmTest({ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000 });++ expect(result.error).toContain('invalid model name');+ expect(global.fetch).toHaveBeenCalledTimes(1);+ });+// A 401 says nothing about the body. Retrying it would double every real// auth failure against a key-gated vLLM.it('does not retry an auth failure as though it were a body rejection', async () => {diff --git a/server/services/localModelAgentBenchmark.js b/server/services/localModelAgentBenchmark.jsindex 7f94e04880..7281a88f83 100644--- a/server/services/localModelAgentBenchmark.js+++ b/server/services/localModelAgentBenchmark.js@@ -1,68 +1,92 @@/**- * User-triggered OpenCode agent-task checks for the local Qwen runtimes.+ * User-triggered local-TUI agent-task checks for the local Qwen runtimes.** The ordinary assessment measures one direct generation at several context* lengths. That is the right instrument for decoder throughput, but it cannot* answer whether a CoS task actually completes through the OpenCode tool loop.* This service runs one bounded, disposable task through the configured- * OpenCode TUI provider preset, then reports task-level chars/s and any output- * token counts OpenCode exposes in its JSON event stream.+ * local TUI provider preset, then reports task completion and terminal-+ * inclusive elapsed time. Direct decoder speed remains the responsibility of+ * the measured assessment beside this check.*- * It deliberately uses `opencode run --format json` rather than a PTY. The- * provider config, model namespace, local endpoint, permissions, and tool loop- * are the same; terminal paste/render latency is not included. The UI labels- * that distinction so a task result is never mistaken for raw decode speed.+ * The target is deliberately the real PTY-backed TUI path used by PortOS CoS+ * tasks. A separate headless OpenCode JSON stream is useful for parser tests and+ * lower-level diagnostics, but it is not a substitute for the primary harness+ * users asked to select.*/import { mkdtemp, readFile, rm } from 'fs/promises';import { tmpdir } from 'os';import { join } from 'path';import { ServerError } from '../lib/errorHandler.js';-import { bufferedSpawn, prepareCliSpawn } from '../lib/bufferedSpawn.js';-import { buildCliChildEnv } from '../lib/cliChildEnv.js';-import { isOpencodeCommand, prefixOpencodeModel } from '../lib/providerModels.js';+import { isClaudeCommand, isOpencodeCommand } from '../lib/providerModels.js';// The stream parser is shared with the capability test suite: two independent// parsers of the same OpenCode envelope is how the two end up reporting// different tool-call counts for the same run.import { summarizeOpenCodeEvents } from '../lib/opencodeStream.js';import { getProviderById } from './providers.js';+import { executeTuiRun } from '../lib/tuiPromptRunner.js';+import { getRunsPath } from './runner.js';-export const OPENCODE_AGENT_BENCHMARK_TARGETS = Object.freeze({+export const LOCAL_TUI_AGENT_BENCHMARK_TARGETS = Object.freeze({llama: Object.freeze({providerId: 'opencode-llama-tui',- label: 'OpenCode llama TUI',- modelId: 'qwen3.8-27b-dflash2',- aliases: Object.freeze(['dflash']),+ label: 'OpenCode llama TUI (Qwen3.8-27B served as dflash)',+ command: 'opencode',+ modelId: 'dflash',+ aliases: Object.freeze(['qwen3.8-27b-dflash2']),}),mtplx: Object.freeze({providerId: 'opencode-mtplx-tui',label: 'OpenCode MTPLX TUI',+ command: 'opencode',modelId: 'mtplx-qwen38-27b-optimized-speed',aliases: Object.freeze([]),}),ollama: Object.freeze({providerId: 'opencode-ollama-tui',label: 'OpenCode Ollama TUI',+ command: 'opencode',+ modelId: 'qwen3.8:27b-mlx',+ aliases: Object.freeze([]),+ }),+ 'ollama-coder': Object.freeze({+ providerId: 'opencode-ollama-tui',+ label: 'OpenCode Ollama TUI (Qwen3-Coder 30B)',+ command: 'opencode',+ modelId: 'qwen3-coder:30b',+ aliases: Object.freeze([]),+ }),+ 'claude-ollama': Object.freeze({+ providerId: 'claude-ollama-tui',+ label: 'Claude Ollama TUI',+ command: 'claude',modelId: 'qwen3.8:27b-mlx',aliases: Object.freeze([]),}),});-export const OPENCODE_AGENT_BENCHMARK_PROMPT = [+export const OPENCODE_AGENT_BENCHMARK_TARGETS = LOCAL_TUI_AGENT_BENCHMARK_TARGETS;++export const buildOpenCodeAgentBenchmarkPrompt = (benchmarkFilePath = 'PORTOS_AGENT_BENCHMARK.txt') => ['This is a disposable PortOS runtime benchmark. You must exercise the terminal tool loop.',- 'In the current scratch workspace, create a file named PORTOS_AGENT_BENCHMARK.txt',+ `In the current scratch workspace, create a file named PORTOS_AGENT_BENCHMARK.txt at exactly this path: ${benchmarkFilePath}`,'whose entire contents are exactly PORTOS_AGENT_BENCHMARK_OK (with no extra newline if your tool permits).','Read that file back with a terminal tool, verify the exact sentinel, and then reply with exactly','PORTOS_AGENT_BENCHMARK_OK. Do not create or modify any other file.',].join(' ');+// Kept as a stable export for callers/tests that only need the prompt shape;+// live runs use the builder with their disposable scratch path below.+export const OPENCODE_AGENT_BENCHMARK_PROMPT = buildOpenCodeAgentBenchmarkPrompt();+const DEFAULT_TIMEOUT_MS = 10 * 60 * 1000;const targetFor = (backend, modelId) => {- const target = OPENCODE_AGENT_BENCHMARK_TARGETS[backend];+ const target = LOCAL_TUI_AGENT_BENCHMARK_TARGETS[backend];if (!target || (modelId !== target.modelId && !target.aliases.includes(modelId))) {throw new ServerError(- `OpenCode agent benchmark supports only the configured ${backend || 'local'} Qwen target`,+ `Local TUI agent benchmark supports only the configured ${backend || 'local'} Qwen target`,{ status: 400, code: 'LOCAL_AGENT_BENCHMARK_TARGET_INVALID' },);}@@ -77,15 +101,18 @@ const validateProvider = (provider, target) => {if (!provider) {throw new ServerError(`Provider "${target.providerId}" is not configured`, { status: 503, code: 'LOCAL_AGENT_BENCHMARK_PROVIDER_MISSING' });}- if (provider.type !== 'tui' || !isOpencodeCommand(provider.command)) {+ const commandMatches = target.command === 'claude'+ ? isClaudeCommand(provider.command)+ : isOpencodeCommand(provider.command);+ if (provider.type !== 'tui' || !commandMatches) {throw new ServerError(`Provider "${target.providerId}" is not an OpenCode TUI provider`, { status: 503, code: 'LOCAL_AGENT_BENCHMARK_PROVIDER_INVALID' });}};/**- * Run one explicit OpenCode task benchmark.+ * Run one explicit local-TUI PTY task benchmark.*- * @param {{backend:'llama'|'mtplx'|'ollama', modelId:string, timeoutMs?:number}} options+ * @param {{backend:'llama'|'mtplx'|'ollama'|'ollama-coder'|'claude-ollama', modelId:string, timeoutMs?:number}} options*/export async function runOpenCodeAgentBenchmark({ backend, modelId, timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {const target = targetFor(backend, modelId);@@ -93,54 +120,55 @@ export async function runOpenCodeAgentBenchmark({ backend, modelId, timeoutMs =validateProvider(provider, target);const scratchDir = await mkdtemp(join(tmpdir(), 'portos-opencode-agent-benchmark-'));+ const runId = `portos-opencode-agent-benchmark-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;const startedAt = Date.now();+ const benchmarkFilePath = join(scratchDir, 'PORTOS_AGENT_BENCHMARK.txt');try {- // Reuse the same model-prefix and dynamic OpenCode config path as the real- // TUI spawner. The benchmark cannot accidentally route a bare model to a- // cloud provider or fail because the per-run model was not declared.- const qualifiedModel = prefixOpencodeModel(provider, modelId);- const command = provider.command;- const baseArgs = Array.isArray(provider.args) ? provider.args : [];- const args = ['run', '--format', 'json', '--auto', '--dir', scratchDir, ...baseArgs, '--model', qualifiedModel, OPENCODE_AGENT_BENCHMARK_PROMPT];- const env = buildCliChildEnv({ provider, model: modelId, cwd: scratchDir, guard: true });- const spawnTarget = prepareCliSpawn(command, args, env);- const result = await bufferedSpawn(spawnTarget.command, spawnTarget.args, {- cwd: scratchDir,- env,- timeoutMs,+ // The one-shot TUI runner owns PTY startup, prompt paste, trust dialogs,+ // response-file completion, cancellation and run-record cleanup semantics.+ // Clone only the model pin: the provider's endpoint, env and permissions+ // stay exactly as the user configured them.+ const completion = await new Promise((resolve) => {+ executeTuiRun({+ runId,+ provider: { ...provider, defaultModel: modelId },+ prompt: buildOpenCodeAgentBenchmarkPrompt(benchmarkFilePath),+ workspacePath: scratchDir,+ timeout: timeoutMs,+ label: `local-model-benchmark:${backend}`,+ guard: true,+ onComplete: resolve,+ }).catch((err) => resolve({ success: false, exitCode: 1, error: err?.message || 'OpenCode TUI failed' }));});- const evidence = summarizeOpenCodeEvents(result.stdout);- const sentinel = await readFile(join(scratchDir, 'PORTOS_AGENT_BENCHMARK.txt'), 'utf8')+ const sentinel = await readFile(benchmarkFilePath, 'utf8').then((value) => value.trim()).catch(() => '');const elapsedMs = Math.max(0, Date.now() - startedAt);- const completed = result.success && sentinel === 'PORTOS_AGENT_BENCHMARK_OK';- const taskCharsPerSecond = elapsedMs > 0 && evidence.assistantChars > 0- ? Number((evidence.assistantChars / (elapsedMs / 1000)).toFixed(2))- : null;- const taskTokensPerSecond = elapsedMs > 0 && Number.isFinite(evidence.outputTokens) && evidence.outputTokens > 0- ? Number((evidence.outputTokens / (elapsedMs / 1000)).toFixed(2))- : null;+ const completed = completion.success === true && sentinel === 'PORTOS_AGENT_BENCHMARK_OK';return {backend,modelId,providerId: target.providerId,providerLabel: target.label,+ measurementMode: 'pty-tui',completed,elapsedMs,- assistantChars: evidence.assistantChars,- outputTokens: evidence.outputTokens,- toolCalls: evidence.toolCalls,- taskCharsPerSecond,- taskTokensPerSecond,- exitCode: result.code,- timedOut: result.timedOut,+ // The response file contains the fixed sentinel for this check, not the+ // model's full terminal transcript. Reporting its 25 characters as a+ // throughput rate would rank terminal overhead, not inference.+ assistantChars: null,+ outputTokens: null,+ toolCalls: null,+ taskCharsPerSecond: null,+ taskTokensPerSecond: null,+ exitCode: completion.exitCode ?? null,+ timedOut: completion.exitCode === 124,error: completed? null- : (result.timedOut+ : (completion.exitCode === 124? `OpenCode task timed out after ${Math.round(timeoutMs / 1000)}s`- : (result.success ? 'OpenCode finished without the benchmark sentinel' : `OpenCode exited with code ${result.code ?? 'unknown'}`)),+ : (completion.success ? `${target.label} finished without the benchmark sentinel` : (completion.error || `${target.label} exited with code ${completion.exitCode ?? 'unknown'}`))),// Deliberately no stdout/stderr or scratch path in the API response: a// local model may echo environment details, and the page needs rates, not// a transcript that could contain user data.@@ -149,5 +177,8 @@ export async function runOpenCodeAgentBenchmark({ backend, modelId, timeoutMs =await rm(scratchDir, { recursive: true, force: true }).catch((err) => {console.error(`⚠️ Local LLM: could not remove the OpenCode benchmark scratch directory — ${err.message}`);});+ await rm(join(getRunsPath(), runId), { recursive: true, force: true }).catch((err) => {+ console.error(`⚠️ Local LLM: could not remove the OpenCode TUI benchmark run record — ${err.message}`);+ });}}diff --git a/server/services/localModelAgentBenchmark.test.js b/server/services/localModelAgentBenchmark.test.jsindex 0f80ac9f2e..41b93cccd0 100644--- a/server/services/localModelAgentBenchmark.test.js+++ b/server/services/localModelAgentBenchmark.test.js@@ -1,22 +1,17 @@import { describe, expect, it, vi, beforeEach } from 'vitest';-import { writeFile } from 'fs/promises';-+import { join } from 'path';vi.mock('./providers.js', () => ({ getProviderById: vi.fn() }));-vi.mock('../lib/bufferedSpawn.js', () => ({- bufferedSpawn: vi.fn(),- prepareCliSpawn: vi.fn((command, args) => ({ command, args })),-}));-vi.mock('../lib/cliChildEnv.js', () => ({ buildCliChildEnv: vi.fn(() => ({ PATH: '/example/bin' })) }));+vi.mock('../lib/tuiPromptRunner.js', () => ({ executeTuiRun: vi.fn() }));+vi.mock('./runner.js', () => ({ getRunsPath: vi.fn(() => '/tmp/portos-benchmark-runs') }));vi.mock('../lib/providerModels.js', () => ({isOpencodeCommand: vi.fn(() => true),- prefixOpencodeModel: vi.fn((_provider, model) => `llama/${model}`),+ isClaudeCommand: vi.fn((command) => command === 'claude'),}));import { getProviderById } from './providers.js';-import { bufferedSpawn } from '../lib/bufferedSpawn.js';-import { buildCliChildEnv } from '../lib/cliChildEnv.js';+import { executeTuiRun } from '../lib/tuiPromptRunner.js';import {- OPENCODE_AGENT_BENCHMARK_PROMPT,+ buildOpenCodeAgentBenchmarkPrompt,runOpenCodeAgentBenchmark,summarizeOpenCodeEvents,} from './localModelAgentBenchmark.js';@@ -48,42 +43,76 @@ describe('runOpenCodeAgentBenchmark', () => {args: [],llamaBacked: true,});- bufferedSpawn.mockImplementation(async (_command, args) => {- const dir = args[args.indexOf('--dir') + 1];- await writeFile(`${dir}/PORTOS_AGENT_BENCHMARK.txt`, 'PORTOS_AGENT_BENCHMARK_OK');- return {- success: true,- code: 0,- signal: null,- stdout: [- JSON.stringify({ type: 'tool_use', part: { type: 'tool' } }),- JSON.stringify({ type: 'text', text: 'PORTOS_AGENT_BENCHMARK_OK' }),- JSON.stringify({ type: 'step_finish', part: { tokens: { output: 9 } } }),- ].join('\n'),- stderr: '',- timedOut: false,- };+ executeTuiRun.mockImplementation(async ({ workspacePath, onComplete }) => {+ const { writeFile } = await import('fs/promises');+ await writeFile(`${workspacePath}/PORTOS_AGENT_BENCHMARK.txt`, 'PORTOS_AGENT_BENCHMARK_OK');+ onComplete({ success: true, exitCode: 0, text: 'PORTOS_AGENT_BENCHMARK_OK', duration: 25 });});});- it('runs the named target in a scratch workspace and returns task rates', async () => {- const result = await runOpenCodeAgentBenchmark({ backend: 'llama', modelId: 'qwen3.8-27b-dflash2' });+ it('runs the named target in a scratch workspace and returns PTY completion timing', async () => {+ const result = await runOpenCodeAgentBenchmark({ backend: 'llama', modelId: 'dflash' });expect(result).toMatchObject({backend: 'llama',- modelId: 'qwen3.8-27b-dflash2',+ modelId: 'dflash',providerId: 'opencode-llama-tui',completed: true,- toolCalls: 1,- outputTokens: 9,+ toolCalls: null,+ outputTokens: null,+ measurementMode: 'pty-tui',error: null,});- expect(result.taskCharsPerSecond).toBeGreaterThan(0);- expect(result.taskTokensPerSecond).toBeGreaterThan(0);- expect(buildCliChildEnv).toHaveBeenCalledWith(expect.objectContaining({ model: 'qwen3.8-27b-dflash2', guard: true }));- expect(bufferedSpawn).toHaveBeenCalledWith('opencode', expect.arrayContaining([- 'run', '--format', 'json', '--auto', '--model', 'llama/qwen3.8-27b-dflash2', OPENCODE_AGENT_BENCHMARK_PROMPT,- ]), expect.objectContaining({ timeoutMs: 600000, env: { PATH: '/example/bin' } }));+ expect(result.taskCharsPerSecond).toBeNull();+ expect(result.taskTokensPerSecond).toBeNull();+ const invocation = executeTuiRun.mock.calls[0][0];+ expect(invocation).toEqual(expect.objectContaining({+ provider: expect.objectContaining({ defaultModel: 'dflash' }),+ prompt: buildOpenCodeAgentBenchmarkPrompt(join(invocation.workspacePath, 'PORTOS_AGENT_BENCHMARK.txt')),+ timeout: 600000,+ workspacePath: expect.any(String),+ guard: true,+ }));+ });++ it('accepts the Claude Ollama TUI as a separate local harness target', async () => {+ getProviderById.mockResolvedValue({+ id: 'claude-ollama-tui',+ type: 'tui',+ command: 'claude',+ args: [],+ ollamaBacked: true,+ });++ const result = await runOpenCodeAgentBenchmark({ backend: 'claude-ollama', modelId: 'qwen3.8:27b-mlx' });++ expect(result).toMatchObject({+ backend: 'claude-ollama',+ modelId: 'qwen3.8:27b-mlx',+ providerId: 'claude-ollama-tui',+ completed: true,+ measurementMode: 'pty-tui',+ });+ });++ it('accepts the installed Qwen3-Coder Ollama target', async () => {+ getProviderById.mockResolvedValue({+ id: 'opencode-ollama-tui',+ type: 'tui',+ command: 'opencode',+ args: [],+ ollamaBacked: true,+ });++ const result = await runOpenCodeAgentBenchmark({ backend: 'ollama-coder', modelId: 'qwen3-coder:30b' });++ expect(result).toMatchObject({+ backend: 'ollama-coder',+ modelId: 'qwen3-coder:30b',+ providerId: 'opencode-ollama-tui',+ completed: true,+ measurementMode: 'pty-tui',+ });});it('rejects a model outside the three explicit benchmark targets', async () => {diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.jsindex 72a127b296..a33dd62bc0 100644--- a/server/services/localModelAssessments.js+++ b/server/services/localModelAssessments.js@@ -316,6 +316,7 @@ export function toSample(contextTokens, result) {promptTokensPerSecond: measured(timings.promptTokensPerSecond),decodeMs: measured(timings.decodeMs),promptMs: measured(timings.promptMs),+ timingSource: ok && typeof timings.timingSource === 'string' ? timings.timingSource : null,// `true` = the count came from counting streamed frames rather than the// daemon's tokenizer, and every figure derived from it must be labelled.tokensEstimated: ok && typeof timings.tokensEstimated === 'boolean' ? timings.tokensEstimated : null,diff --git a/server/services/modelCapabilityTests.js b/server/services/modelCapabilityTests.jsindex 87ffb81337..ef4f67c247 100644--- a/server/services/modelCapabilityTests.js+++ b/server/services/modelCapabilityTests.js@@ -3,17 +3,20 @@** The assessments panel next door answers "how fast is this model here". This* one answers the question speed cannot: **can it actually do what its badges- * claim?** Three tests, each bound to the capability badges the install catalog+ * claim?** Four tests, each bound to the capability badges the install catalog* already shows, each keeping the model's full output:** - `sandbox-repair` (`tools`) — a broken module and its failing test are- * copied into a throwaway sandbox and a real OpenCode TUI agent is pointed- * at it. The model has to read the files, write a fix to disk, and make the- * test pass. The transcript streams to the page while it works.+ * copied into a throwaway sandbox and the configured OpenCode task driver is+ * pointed at it. The model has to read the files, write a fix to disk, and+ * make the test pass. Its structured transcript streams to the page while it+ * works; the PTY-backed TUI path is measured separately by the harness check.* - `image-analysis` (`vision`) — a fixture image with known contents goes in;* the description is scored against required and bonus keywords.* - `story-outline` (`chat`) — one hero's-journey outline from a fixed* premise, scored on beat coverage and ordering.+ * - `fiction-scene` (`chat`) — a short opening scene from the same premise,+ * scored on story anchors and basic scene craft before a human reads it.** ## Rules this file exists to honour*@@ -52,9 +55,9 @@ import {} from '../lib/localProviderRuntime.js';import {CAPABILITY_TESTS, CAPABILITY_TEST_IDS, CAPABILITY_TEST_PROMPTS, SANDBOX_TASK_PROMPT,- VISION_FIXTURE_KEYWORDS, HEROS_JOURNEY_BEATS,+ VISION_FIXTURE_KEYWORDS, FICTION_SCENE_KEYWORDS, HEROS_JOURNEY_BEATS,applicableTests, getCapabilityTest,- scoreKeywords, scoreStoryBeats, scoreSandboxRepair, rollUpVerdict,+ scoreKeywords, scoreFictionScene, scoreStoryBeats, scoreSandboxRepair, rollUpVerdict,} from '../lib/modelCapabilityTests.js';import { listRuntimeModels, runtimeEndpoint, runtimeApiKey } from './localModelAssessments.js';import { runLocalLlmTest, runEndpointLlmTest } from './localLlmPlayground.js';@@ -209,10 +212,10 @@ async function generate({ backend, modelId, prompt, images, maxTokens, signal })});}-// ---- the three tests --------------------------------------------------------+// ---- the generative tests ---------------------------------------------------/**- * The two generative tests, which differ only in what they send and how the+ * The generative tests, which differ only in what they send and how the* answer is scored. Everything else — the empty-output contract, keeping the* text whichever way the run ended — is identical, and was worth having in one* place rather than twice.@@ -233,6 +236,12 @@ const CHAT_TESTS = {images: async () => undefined,score: (text) => scoreStoryBeats(text, HEROS_JOURNEY_BEATS),},+ 'fiction-scene': {+ maxTokens: 1400,+ message: (modelId) => `Asking ${modelId} for a short fiction scene…`,+ images: async () => undefined,+ score: (text) => scoreFictionScene(text, FICTION_SCENE_KEYWORDS),+ },};async function runChatTest({ backend, modelId, testId, signal, emit }) {@@ -291,95 +300,102 @@ async function runSandboxRepair({ backend, modelId, signal, emit, runId, provideconst sandboxRoot = join(PATHS.data, 'model-tests', 'sandboxes');const sandbox = join(sandboxRoot, runId);- await ensureDir(sandbox);- await cp(SANDBOX_FIXTURE, sandbox, { recursive: true });- emit({ event: 'progress', message: `Sandbox ready — ${Object.keys(SANDBOX_FILES).length} files copied.` });-- const fixtureHashes = await sandboxFixtureHashes();-- let transcript = '';- let toolCalls = 0;- const startedAt = Date.now();-- emit({ event: 'progress', message: `Starting the ${driver.provider.name || 'OpenCode'} agent on ${modelId}…` });- const agent = await runOpencodeTask({- provider: driver.provider,- modelId,- cwd: sandbox,- prompt: SANDBOX_TASK_PROMPT,- timeoutMs: AGENT_TIMEOUT_MS,- // One parse feeds both the stored transcript and the live view, so the two- // can never disagree about what the agent did.- onEvent: (event) => {- const rendered = formatAgentEvent(event);- if (!rendered) return;- if (rendered.toolCall) toolCalls += 1;- transcript += `${rendered.line}\n`;- // Watching the loop work is the point of driving a TUI here rather than an- // in-process tool loop.- emit({ event: 'output', line: rendered.line });- },- });-- // ---- verification: disk only, never the transcript ----- emit({ event: 'progress', message: 'Agent finished — checking the sandbox on disk…' });-- const hashOf = (name) => sha256File(join(sandbox, name)).catch(() => null);- const [moduleHash, testHash, dataHash] = await Promise.all([- hashOf(SANDBOX_FILES.module), hashOf(SANDBOX_FILES.test), hashOf(SANDBOX_FILES.data),- ]);-- // PortOS runs the test itself rather than believing the agent's own run: the- // exit code of a command we issued is the only evidence that survives a model- // reporting a success it did not achieve.- const verify = await bufferedSpawn(SANDBOX_VERIFY_COMMAND[0], SANDBOX_VERIFY_COMMAND.slice(1), {- cwd: sandbox,- // PWD pinned at the call site (#3193). `node` resolves the test path from- // cwd rather than PWD, so this is belt-and-braces today — but the command is- // the kind of thing that grows a package runner later, and an inherited PWD- // pointing at the PortOS checkout is exactly how one ends up verifying the- // wrong directory.- env: withSpawnCwdEnv(process.env, sandbox),- timeoutMs: VERIFY_TIMEOUT_MS,- });+ const run = async () => {+ await ensureDir(sandbox);+ await cp(SANDBOX_FIXTURE, sandbox, { recursive: true });+ emit({ event: 'progress', message: `Sandbox ready — ${Object.keys(SANDBOX_FILES).length} files copied.` });++ const fixtureHashes = await sandboxFixtureHashes();++ let transcript = '';+ let toolCalls = 0;+ const startedAt = Date.now();++ emit({ event: 'progress', message: `Starting the ${driver.provider.name || 'OpenCode'} agent on ${modelId}…` });+ const agent = await runOpencodeTask({+ provider: driver.provider,+ modelId,+ cwd: sandbox,+ prompt: SANDBOX_TASK_PROMPT,+ timeoutMs: AGENT_TIMEOUT_MS,+ signal,+ // One parse feeds both the stored transcript and the live view, so the two+ // can never disagree about what the agent did.+ onEvent: (event) => {+ const rendered = formatAgentEvent(event);+ if (!rendered) return;+ if (rendered.toolCall) toolCalls += 1;+ transcript += `${rendered.line}\n`;+ // Watching the structured tool loop work is the point of streaming this+ // driver rather than hiding it behind an in-process helper.+ emit({ event: 'output', line: rendered.line });+ },+ });- const detail = scoreSandboxRepair({- // A deleted module reads as "never wrote a fix", not as a change.- moduleChanged: Boolean(moduleHash) && moduleHash !== fixtureHashes.module,- fixturesIntact: testHash === fixtureHashes.test && dataHash === fixtureHashes.data,- testsPass: verify.success,- toolCalls,- });+ // ---- verification: disk only, never the transcript ----+ emit({ event: 'progress', message: 'Agent finished — checking the sandbox on disk…' });++ const hashOf = (name) => sha256File(join(sandbox, name)).catch(() => null);+ const [moduleHash, testHash, dataHash] = await Promise.all([+ hashOf(SANDBOX_FILES.module), hashOf(SANDBOX_FILES.test), hashOf(SANDBOX_FILES.data),+ ]);++ // PortOS runs the test itself rather than believing the agent's own run: the+ // exit code of a command we issued is the only evidence that survives a model+ // reporting a success it did not achieve.+ const verify = await bufferedSpawn(SANDBOX_VERIFY_COMMAND[0], SANDBOX_VERIFY_COMMAND.slice(1), {+ cwd: sandbox,+ // PWD pinned at the call site (#3193). `node` resolves the test path from+ // cwd rather than PWD, so this is belt-and-braces today — but this is the+ // kind of command that grows a package runner later, and an inherited PWD+ // pointing at the PortOS checkout is exactly how one ends up verifying the+ // wrong directory.+ env: withSpawnCwdEnv(process.env, sandbox),+ timeoutMs: VERIFY_TIMEOUT_MS,+ });- await pruneSandboxes(sandboxRoot);+ const detail = scoreSandboxRepair({+ // A deleted module reads as "never wrote a fix", not as a change.+ moduleChanged: Boolean(moduleHash) && moduleHash !== fixtureHashes.module,+ fixturesIntact: testHash === fixtureHashes.test && dataHash === fixtureHashes.data,+ testsPass: verify.success,+ toolCalls,+ });- return {- verdict: detail.verdict,- summary: detail.summary,- // The test's "output" is what PortOS's own verification run printed — the- // thing that decided the verdict — with the agent's narration beside it.- output: verify.stdout || verify.stderr || '',- transcript,- detail: {- ...detail,- driver: driver.provider.id,- driverLabel: driver.provider.name || driver.provider.id,- verifyCommand: SANDBOX_VERIFY_COMMAND.join(' '),- verifyExitCode: verify.code,- sandboxPath: sandbox,- elapsedMs: Math.max(0, Date.now() - startedAt),- },- // Recorded even when the verdict already stands on its own: "never wrote a- // fix" and "never wrote a fix because the CLI was missing" need different- // responses from the user.- error: agent.error,- timings: null,+ return {+ verdict: detail.verdict,+ summary: detail.summary,+ // The test's "output" is what PortOS's own verification run printed — the+ // thing that decided the verdict — with the agent's narration beside it.+ output: verify.stdout || verify.stderr || '',+ transcript,+ detail: {+ ...detail,+ driver: driver.provider.id,+ driverLabel: driver.provider.name || driver.provider.id,+ verifyCommand: SANDBOX_VERIFY_COMMAND.join(' '),+ verifyExitCode: verify.code,+ sandboxPath: sandbox,+ elapsedMs: Math.max(0, Date.now() - startedAt),+ },+ // Recorded even when the verdict already stands on its own: "never wrote a+ // fix" and "never wrote a fix because the CLI was missing" need different+ // responses from the user.+ error: agent.error,+ timings: null,+ };};+ try {+ return await run();+ } finally {+ await pruneSandboxes(sandboxRoot);+ }}const RUNNERS = {'image-analysis': runChatTest,'story-outline': runChatTest,+ 'fiction-scene': runChatTest,'sandbox-repair': runSandboxRepair,};@@ -422,11 +438,11 @@ export async function runCapabilityTest({ backend, modelId, testId, signal, onPr}console.log(`🧪 Capability tests: ${test.id} on ${backend}/${modelId} (run ${runId})`);- emit({ event: 'start', message: `${test.label}: starting on ${modelId}…`, runId });const startedAt = Date.now();let outcome;try {+ emit({ event: 'start', message: `${test.label}: starting on ${modelId}…`, runId });// The claim wait is bounded but can be long, and it does not observe the// abort signal. A cancel that landed while we waited must not turn into a// run now that the machine is free.diff --git a/server/services/modelCapabilityTests.test.js b/server/services/modelCapabilityTests.test.jsindex e83bb4bbdd..855e0e1597 100644--- a/server/services/modelCapabilityTests.test.js+++ b/server/services/modelCapabilityTests.test.js@@ -211,6 +211,24 @@ describe('runCapabilityTest — story outline', () => {});});+describe('runCapabilityTest — fiction scene', () => {+ it('keeps the scene and returns the structural craft score', async () => {+ runLocalLlmTest.mockResolvedValue({+ text: [+ 'The tidal marsh smelled of mud as the oyster farmer watched the dying beds.',+ 'She waded to the sea wall and pulled the gate open.',+ '“No,” she said, as black water spilled through the breach.',+ ].join('\n\n'),+ timings: null,+ });+ const record = await runCapabilityTest({ backend: 'ollama', modelId: 'writer', testId: 'fiction-scene' });+ expect(record.output).toContain('oyster farmer');+ expect(record.detail.wordCount).toBeGreaterThan(0);+ expect(record.detail.hasDialogue).toBe(true);+ expect(record.verdict).toBe('partial');+ });+});+describe('runCapabilityTest — sandbox repair', () => {beforeEach(() => {getAllProviders.mockResolvedValue({ activeProvider: null, providers: [OPENCODE_LLAMA] });@@ -349,6 +367,24 @@ describe('the machine-wide heavy-job claim', () => {await expect(runCapabilityTest({ backend: 'lmstudio', modelId: 'vlm', testId: 'image-analysis' })).rejects.toThrow();expect(release).toHaveBeenCalled();});++ it('releases the claim when the progress consumer disconnects before the runner starts', async () => {+ const release = vi.fn(async () => {});+ claimHeavyLocalJob.mockResolvedValue({ ok: true, holder: null, release });+ let firstFrame = true;+ const onProgress = vi.fn(() => {+ if (firstFrame) {+ firstFrame = false;+ throw new Error('progress consumer disconnected');+ }+ });++ await expect(runCapabilityTest({+ backend: 'lmstudio', modelId: 'vlm', testId: 'image-analysis', onProgress,+ })).rejects.toThrow(/progress consumer disconnected/);+ expect(release).toHaveBeenCalledOnce();+ expect(runLocalLlmTest).not.toHaveBeenCalled();+ });});describe('what the report ships', () => {diff --git a/server/services/opencodeTask.js b/server/services/opencodeTask.jsindex db5acce13c..2d6fb0230d 100644--- a/server/services/opencodeTask.js+++ b/server/services/opencodeTask.js@@ -1,5 +1,6 @@/**- * Run one bounded task through an OpenCode TUI provider — the shared driver.+ * Run one bounded task through an OpenCode provider preset — the shared+ * structured task driver.** Two features need this: the runtime agent-task benchmark* (`localModelAgentBenchmark.js`) and the sandbox-repair capability test@@ -25,7 +26,7 @@ import { parseAgentLine } from '../lib/opencodeStream.js';import { listProviders } from './providers.js';/**- * The configured OpenCode TUI provider that drives a given local runtime.+ * The configured OpenCode TUI provider preset that drives a given local runtime.** Matched on the provider's own `*Backed` marker rather than a hardcoded id* list, so renaming or adding a preset keeps working. LM Studio has no OpenCode@@ -45,7 +46,10 @@ export async function resolveOpencodeTuiProvider(runtime, providers) {}/**- * Drive one disposable OpenCode task to completion.+ * Drive one disposable OpenCode task to completion through its JSON task+ * interface. The PTY-backed TUI path is measured by the separate local harness+ * benchmark; keeping this driver structured makes disk-verifiable capability+ * scoring and live tool-event rendering deterministic.** @param {object} options* @param {object} options.provider a TUI provider record (validated here)@@ -55,12 +59,13 @@ export async function resolveOpencodeTuiProvider(runtime, providers) {* @param {string} options.cwd the directory the agent works in* @param {string} options.prompt* @param {number} options.timeoutMs+ * @param {AbortSignal} [options.signal] caller disconnect/cancel signal* @param {(event: object) => void} [options.onEvent] called with each parsed* stream frame as it arrives, for a caller rendering live progress* @returns {Promise<{success: boolean, error: string|null, events: object[]}>}* never rejects for an in-run failure — the caller gets a value to score.*/-export async function runOpencodeTask({ provider, modelId, cwd, prompt, timeoutMs, onEvent }) {+export async function runOpencodeTask({ provider, modelId, cwd, prompt, timeoutMs, signal, onEvent }) {if (!provider) {throw new ServerError('No OpenCode TUI provider was given', { status: 503, code: 'OPENCODE_TASK_PROVIDER_MISSING' });}@@ -86,7 +91,7 @@ export async function runOpencodeTask({ provider, modelId, cwd, prompt, timeoutM// Hook failures are already caught by runStreamingCommand — this runs// outside the request lifecycle, where a throw would take the process down.onEvent?.(event);- }, { cwd, env, timeoutMs });+ }, { cwd, env, timeoutMs, isCancelled: () => signal?.aborted === true });return { success: result.success, error: result.error || null, events };}diff --git a/server/services/opencodeTask.test.js b/server/services/opencodeTask.test.jsindex cd0c5580ae..5e3bc62a40 100644--- a/server/services/opencodeTask.test.js+++ b/server/services/opencodeTask.test.js@@ -104,6 +104,20 @@ describe('runOpencodeTask', () => {expect(result.success).toBe(true);});+ it('passes a caller cancellation signal to the streaming runner', async () => {+ runStreamingCommand.mockResolvedValue({ success: true });+ const controller = new AbortController();+ await runOpencodeTask({+ provider: OPENCODE_OLLAMA_TUI, modelId: 'm', cwd: '/tmp/s', prompt: 'p', timeoutMs: 1000,+ signal: controller.signal,+ });++ const options = runStreamingCommand.mock.calls[0][3];+ expect(options.isCancelled()).toBe(false);+ controller.abort();+ expect(options.isCancelled()).toBe(true);+ });+it('refuses a provider that is not an OpenCode TUI', async () => {await expect(runOpencodeTask({ provider: CLAUDE_OLLAMA_TUI, modelId: 'm', cwd: '/tmp/s', prompt: 'p', timeoutMs: 1 })).rejects.toThrow(/not an OpenCode TUI provider/);