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
test model capabilities on the Performance page, not just their speed
[._.]/ Adam Eivy1f99870818f7
diff --git a/client/src/components/models/CapabilityBadges.jsx b/client/src/components/models/CapabilityBadges.jsxnew file mode 100644index 0000000000..4ecf35f8db--- /dev/null+++ b/client/src/components/models/CapabilityBadges.jsx@@ -0,0 +1,67 @@+import { MessageSquare, Code2, Brain, Eye, Boxes, Wrench, Music } from 'lucide-react';++/**+ * The capability icon row, shared by every surface that shows what a model can do.+ *+ * It started life inside the install tab and is now also the gate the+ * Performance page's capability tests key off — so it lives here rather than+ * being copied. Two surfaces rendering the same claim with different icons (or,+ * worse, a different vocabulary) is how a model ends up looking tool-capable on+ * one page and not on another.+ *+ * `cls` is the icon color; the bordered chip uses the same hue at low opacity —+ * the LM Studio style, icons rather than text, because a model with five badges+ * would otherwise wrap a card into three lines.+ */+export const CAPABILITY_META = {+ chat: { Icon: MessageSquare, label: 'Chat', cls: 'text-gray-400 border-gray-500/50' },+ code: { Icon: Code2, label: 'Code', cls: 'text-sky-400 border-sky-400/50' },+ reasoning: { Icon: Brain, label: 'Reasoning', cls: 'text-emerald-400 border-emerald-400/50' },+ vision: { Icon: Eye, label: 'Vision', cls: 'text-amber-400 border-amber-400/50' },+ embeddings: { Icon: Boxes, label: 'Embeddings', cls: 'text-violet-400 border-violet-400/50' },+ tools: { Icon: Wrench, label: 'Tool use', cls: 'text-blue-400 border-blue-400/50' },+ audio: { Icon: Music, label: 'Audio generation', cls: 'text-pink-400 border-pink-400/50' },+};++/**+ * A model's capability badges.+ *+ * `capabilities` is `null` when NOTHING authoritative reported a badge set — a+ * bare llama.cpp endpoint lists model ids and nothing else. That is rendered as+ * an explicit "not reported" chip rather than as an empty row, because an empty+ * row reads as "this model can do nothing", which is a different and untrue+ * claim. `[]` (a runtime that answered and named none) legitimately renders+ * nothing.+ */+export default function CapabilityBadges({ capabilities, unknownLabel = 'capabilities not reported' }) {+ if (!Array.isArray(capabilities)) {+ return (+ <span+ className="px-1.5 py-0.5 text-[10px] rounded border border-dashed border-port-border text-gray-500"+ title="This runtime lists model ids only, so PortOS cannot say what this model claims."+ >+ {unknownLabel}+ </span>+ );+ }++ return capabilities.map((capability) => {+ const meta = CAPABILITY_META[capability];+ // An unmapped capability still shows — the server's vocabulary can grow+ // ahead of this map, and silently dropping one would hide a real claim.+ if (!meta) {+ return <span key={capability} className="px-1.5 py-0.5 bg-port-border/60 rounded">{capability}</span>;+ }+ const Icon = meta.Icon;+ return (+ <span+ key={capability}+ title={meta.label}+ aria-label={meta.label}+ className={`inline-flex items-center justify-center w-5 h-5 rounded border ${meta.cls}`}+ >+ <Icon size={12} />+ </span>+ );+ });+}diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex bb73ce9fbb..4011945f62 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -1,6 +1,6 @@import { useState, useEffect, useRef, useCallback, useMemo } from 'react';import { Link, useNavigate } from 'react-router';-import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Power, PowerOff, Eye, Wrench, Brain, Code2, MessageSquare, Boxes, AlertTriangle, FlaskConical, Music, ArrowUpCircle, Zap, ChevronDown, ChevronUp, Terminal } from 'lucide-react';+import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Power, PowerOff, AlertTriangle, FlaskConical, ArrowUpCircle, Zap, ChevronDown, ChevronUp, Terminal } from 'lucide-react';import toast from '../ui/Toast';import ConfirmButtonPair from '../ui/ConfirmButtonPair';import BrailleSpinner from '../BrailleSpinner';@@ -16,6 +16,7 @@ import {saveRuntimeStartupList} from '../../services/api';import socket from '../../services/socket';+import CapabilityBadges from '../models/CapabilityBadges.jsx';import SpecDecodeWeightRow from './SpecDecodeWeightRow.jsx';import RuntimeServersCard from './RuntimeServersCard.jsx';import MtplxServerCard from './MtplxServerCard.jsx';@@ -86,18 +87,6 @@ const recommendationCategoriesFor = (model) => {};const isRecommendedForCategory = (model, category) => recommendationCategoriesFor(model).includes(category);-// Render model capabilities as colored icons (LM Studio style) instead of text.-// `cls` is the icon color; the bordered chip uses the same hue at low opacity.-const CAPABILITY_META = {- chat: { Icon: MessageSquare, label: 'Chat', cls: 'text-gray-400 border-gray-500/50' },- code: { Icon: Code2, label: 'Code', cls: 'text-sky-400 border-sky-400/50' },- reasoning: { Icon: Brain, label: 'Reasoning', cls: 'text-emerald-400 border-emerald-400/50' },- vision: { Icon: Eye, label: 'Vision', cls: 'text-amber-400 border-amber-400/50' },- embeddings: { Icon: Boxes, label: 'Embeddings', cls: 'text-violet-400 border-violet-400/50' },- tools: { Icon: Wrench, label: 'Tool use', cls: 'text-blue-400 border-blue-400/50' },- audio: { Icon: Music, label: 'Audio generation', cls: 'text-pink-400 border-pink-400/50' },-};-// A model suited to AGENT / CoS tasks (coding agents, the Creative Director// treatment/plan agents) needs BOTH native tool calling AND enough coding /// instruction-following muscle to drive a multi-step loop. A chat-only@@ -168,28 +157,6 @@ function summarizeMigrate(r) {return `${labelFor(r.from)} → ${labelFor(r.to)}: ${parts.join(', ') || 'nothing to move'}`;}-// Shared capability-icon row for both catalog/search-result cards and the-// installed-models list, so the two surfaces render the same badges the same way.-function CapabilityBadges({ capabilities }) {- return (capabilities || []).map((capability) => {- const meta = CAPABILITY_META[capability];- if (!meta) {- return <span key={capability} className="px-1.5 py-0.5 bg-port-border/60 rounded">{capability}</span>;- }- const Icon = meta.Icon;- return (- <span- key={capability}- title={meta.label}- aria-label={meta.label}- className={`inline-flex items-center justify-center w-5 h-5 rounded border ${meta.cls}`}- >- <Icon size={12} />- </span>- );- });-}-function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAction, setConfirmAction }) {const data = status?.[backend.id];const Icon = backend.icon;diff --git a/client/src/components/settings/LocalModelAssessments.jsx b/client/src/components/settings/LocalModelAssessments.jsxindex 1251aa633a..434a62094d 100644--- a/client/src/components/settings/LocalModelAssessments.jsx+++ b/client/src/components/settings/LocalModelAssessments.jsx@@ -32,11 +32,14 @@ import { useAsyncAction } from '../../hooks/useAsyncAction';import useMounted from '../../hooks/useMounted';import useUrlParams from '../../hooks/useUrlParams';import AssessmentSweepPanel from './AssessmentSweepPanel';+import ModelCapabilityTests, { TestCell } from './ModelCapabilityTests.jsx';+import CapabilityBadges from '../models/CapabilityBadges.jsx';import ModelThroughputReport from './ModelThroughputReport';import { formatContextTokens, formatDurationMs, throughputLabel } from '../../utils/formatters';import { tuningNoticeChip } from '../../lib/assessmentTuningNotice';import {getLocalLlmAssessments, runLocalLlmAssessment, runOpenCodeAgentBenchmark, deleteLocalLlmAssessment,+ getModelCapabilityTests,} from '../../services/api';const INTENTS = [@@ -333,7 +336,37 @@ function AssessmentDrawer({);}-function RankedRow({ entry, runtimeLabel, onRemeasure, onDelete, onSweepTunings, sweepVariants, busy }) {+/**+ * What this model has PROVED, beside what it is fast at.+ *+ * Only tests that apply are shown. An unclaimed capability is left out entirely+ * rather than rendered as a grey "n/a" on every row — the matrix in the suite+ * panel above is where the full grid lives; here it would be columns of nothing+ * on the models that matter most.+ *+ * The chips themselves are the matrix's own `TestCell`, so the two surfaces on+ * one page cannot drift into rendering the same verdict differently.+ */+function CapabilityStrip({ capability, backend, modelId, tests, onOpen }) {+ if (!capability) return null;+ const runnable = (capability.tests || []).filter((t) => t.state === 'applicable' || t.state === 'unknown');+ if (!runnable.length) return null;+ const labelFor = (testId) => tests?.find((t) => t.id === testId)?.label || testId;++ return (+ <div className="border-t border-port-border/70 pt-2 flex items-center gap-2 flex-wrap">+ <span className="text-[11px] text-gray-500">Capability tests</span>+ {runnable.map((slot) => (+ <span key={slot.testId} className="flex items-center gap-1.5">+ <span className="text-[11px] text-gray-400">{labelFor(slot.testId)}</span>+ <TestCell slot={slot} onOpen={() => onOpen(backend, modelId, slot.testId)} />+ </span>+ ))}+ </div>+ );+}++function RankedRow({ entry, runtimeLabel, onRemeasure, onDelete, onSweepTunings, sweepVariants, busy, capability, capabilityTests, onOpenCapabilityTest }) {const perf = entry.performance || {};return (<div className="border border-port-border rounded-lg p-3 space-y-2">@@ -350,6 +383,10 @@ function RankedRow({ entry, runtimeLabel, onRemeasure, onDelete, onSweepTunings,<span className="px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400">{entry.tuningLabel || 'backend defaults'}</span>+ {/* What the model CLAIMS, from the same badge component the install+ catalog renders — the claim is what decides which tests below+ apply, so the two must never disagree. */}+ {capability && <CapabilityBadges capabilities={capability.capabilities} />}</div>{/* No `tuningApplied === false` caveat here on purpose: a reading whoseconfiguration never reached the daemon is never RANKED. The server@@ -467,6 +504,14 @@ function RankedRow({ entry, runtimeLabel, onRemeasure, onDelete, onSweepTunings,);})}</div>++ <CapabilityStrip+ capability={capability}+ backend={entry.backend}+ modelId={entry.modelId}+ tests={capabilityTests}+ onOpen={onOpenCapabilityTest}+ /></div>);}@@ -633,6 +678,12 @@ export function LocalModelAssessments() {// sweep panel because it gates this panel's per-model buttons too.const [sweepRunning, setSweepRunning] = useState(false);const [agentBenchmarkResults, setAgentBenchmarkResults] = useState({});+ // Kept beside the assessment report rather than inside the suite panel: the+ // ranked rows show each model's badges and capability verdicts too, so one+ // fetch feeds both surfaces and they can never disagree about what a model+ // claims. Disk-only on the server — safe to load with the tab.+ const [capabilityReport, setCapabilityReport] = useState(null);+ const [capabilityLoading, setCapabilityLoading] = useState(true);const [searchParams, updateParams] = useUrlParams();const measureBackend = searchParams.get('measureBackend') || '';@@ -684,6 +735,30 @@ export function LocalModelAssessments() {useEffect(() => { load(intent); }, [load, intent]);+ const loadCapabilities = useCallback(async () => {+ setCapabilityLoading(true);+ // The panel renders its own empty/error state (client/src/CLAUDE.md: custom+ // catch ⇒ silent).+ const data = await getModelCapabilityTests({ silent: true }).catch(() => null);+ setCapabilityReport(data);+ setCapabilityLoading(false);+ }, []);++ useEffect(() => { loadCapabilities(); }, [loadCapabilities]);++ // One lookup shared by every ranked row, rebuilt only when the report changes —+ // a per-row `find` over every installed model would be quadratic on a box with+ // thirty models installed.+ const capabilityByModel = useMemo(() => new Map(+ (capabilityReport?.models || []).map((m) => [`${m.backend}:${m.modelId}`, m]),+ ), [capabilityReport]);++ // Both this panel and the suite panel drive the same URL params, so a row's+ // chip opens the same drawer the matrix does without either owning the other.+ const openCapabilityTest = useCallback((capBackend, capModel, capTest) => {+ updateParams({ ...CLOSED_GATE_PARAMS, capBackend, capModel, capTest });+ }, [updateParams]);+// The row the URL names, once the report can say which one it is — that record// is what carries the tuning a re-measure starts from. Matched through// `entryKey` so "the same measurement" has one definition, not two.@@ -919,6 +994,16 @@ export function LocalModelAssessments() {to press at the end of the day; the results below are what you read thenext morning. Disabled while a single-model run holds the provider —two measurements at once would measure the contention. */}+ {/* What each model CLAIMS, and what it has proved. Kept above the ranking+ because "can it do the job" is the question you ask before "how fast is+ it" — and because the matrix is what sends you into a run. */}+ <ModelCapabilityTests+ report={capabilityReport}+ loading={capabilityLoading}+ onReload={loadCapabilities}+ disabled={busy}+ />+<AssessmentSweepPanelcounts={report?.sweepScopes}contextTokens={report?.defaultContextTokens || []}@@ -973,6 +1058,9 @@ export function LocalModelAssessments() {onRemeasure={openTarget}onDelete={removeAssessment}onSweepTunings={openSweepTarget}+ capability={capabilityByModel.get(`${entry.backend}:${entry.modelId}`) || null}+ capabilityTests={capabilityReport?.tests}+ onOpenCapabilityTest={openCapabilityTest}/>))}</div>diff --git a/client/src/components/settings/LocalModelAssessments.test.jsx b/client/src/components/settings/LocalModelAssessments.test.jsxindex 92a8d7c0f9..bab6cc1fda 100644--- a/client/src/components/settings/LocalModelAssessments.test.jsx+++ b/client/src/components/settings/LocalModelAssessments.test.jsx@@ -13,6 +13,14 @@ vi.mock('../../services/api', () => ({getLocalLlmAssessmentSweep: vi.fn(async () => ({ status: 'idle', total: 0, completed: 0, results: [] })),startLocalLlmAssessmentSweep: vi.fn(),cancelLocalLlmAssessmentSweep: vi.fn(),+ // The capability suite panel is a child of this one and loads its report on+ // mount. Its own behavior has a dedicated suite; here it just has to be quiet.+ getModelCapabilityTests: vi.fn(async () => ({+ tests: [], testIds: [], prompts: {}, models: [], runtimes: [],+ counts: { models: 0, applicable: 0, passed: 0, failed: 0 }, listErrors: [], readError: null,+ })),+ runModelCapabilityTest: vi.fn(),+ deleteModelCapabilityTest: vi.fn(),}));vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } }));diff --git a/client/src/components/settings/ModelCapabilityTests.jsx b/client/src/components/settings/ModelCapabilityTests.jsxnew file mode 100644index 0000000000..198b52e03c--- /dev/null+++ b/client/src/components/settings/ModelCapabilityTests.jsx@@ -0,0 +1,769 @@+/**+ * Capability tests for the installed local models.+ *+ * The assessments panel this sits inside answers "how fast is this model here".+ * This one answers the question speed cannot: **can it do what its badges+ * claim?** The badges are the gate — a test is offered exactly where the model+ * made a claim worth checking — and every run keeps the model's full output,+ * because reading what came back is the point.+ *+ * ## Three rules the UI has to carry+ *+ * 1. **An unclaimed capability is not a failure.** A model with no `vision`+ * badge shows "not applicable" on the image test, in muted grey, never a red+ * X. A red cell always means "it said it could, and it could not".+ * 2. **No cold-bootstrap LLM calls** (root CLAUDE.md). The report loads with the+ * tab and calls nothing. Running a test goes through a consent gate that+ * names the runtime, the model, the test and the prompt first.+ * 3. **Show the output.** Every result view leads with what the model actually+ * produced; the score sits beside it, never in place of it.+ *+ * The drawer is one component in three states (gate → live → result) rather than+ * three drawers, so starting a run never closes and reopens a panel, and the+ * live transcript is already on screen when the first frame arrives.+ */++import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import {+ FlaskConical, Play, RefreshCw, Trash2, Check, X, AlertTriangle, Terminal, Eye, BookOpen, Wrench,+} from 'lucide-react';+import socket from '../../services/socket';+import Drawer from '../Drawer';+import toast from '../ui/Toast';+import BrailleSpinner from '../BrailleSpinner';+import Pill from '../ui/Pill';+import CapabilityBadges, { CAPABILITY_META } from '../models/CapabilityBadges.jsx';+import useUrlParams from '../../hooks/useUrlParams';+import useMounted from '../../hooks/useMounted';+import { formatDurationMs } from '../../utils/formatters';+import { runModelCapabilityTest, deleteModelCapabilityTest, getModelCapabilityTestResult } from '../../services/api';++// Per-test icon and accent. Keyed off the test id the SERVER ships, so a test+// added there renders with a sensible fallback rather than vanishing.+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' },+};+const testMeta = (id) => TEST_META[id] || { Icon: FlaskConical, cls: 'text-gray-400', border: 'border-port-border' };++// A verdict's colour and word. `null` is NOT a verdict — it means the test has+// not been run, which every caller renders as its own thing rather than folding+// into "failed".+const VERDICT_META = {+ passed: { label: 'passed', cls: 'text-emerald-400 border-emerald-400/40', Icon: Check },+ partial: { label: 'partial', cls: 'text-port-warning border-port-warning/40', Icon: AlertTriangle },+ failed: { label: 'failed', cls: 'text-port-error border-port-error/40', Icon: X },+};++const modelKey = (backend, modelId) => `${backend}:${modelId}`;++/**+ * How many streamed transcript lines the live view keeps.+ *+ * A ten-minute agent run emits thousands, and every one re-renders the drawer+ * and copies the whole array. The view is a scrolling tail anyway, and the FULL+ * transcript is stored server-side and shown on the Transcript tab once the run+ * finishes — so capping the preview loses nothing a reader can see.+ */+const MAX_LIVE_LINES = 400;++const CLOSED_PARAMS = { capBackend: null, capModel: null, capTest: null };++/** Everything the drawer needs about one model+test pairing. */+const pairFor = (report, backend, modelId, testId) => {+ const model = report?.models?.find((m) => m.backend === backend && m.modelId === modelId) || null;+ const test = report?.tests?.find((t) => t.id === testId) || null;+ const slot = model?.tests?.find((t) => t.testId === testId) || null;+ return { model, test, slot };+};++// ---- small shared bits ------------------------------------------------------++function VerdictChip({ verdict, children, title }) {+ const meta = VERDICT_META[verdict];+ if (!meta) return null;+ // `bare` because the tone is per-verdict rather than one of Pill's semantic+ // trio — Pill still owns the shape, size and icon slot.+ return (+ <Pill tone="bare" size="xs" icon={meta.Icon} title={title} className={meta.cls}>+ {children || meta.label}+ </Pill>+ );+}++/**+ * One cell of the matrix — and the only control that opens the drawer.+ *+ * The four states are deliberately visually distinct: a result is coloured, an+ * unclaimed capability is muted italic text with the reason in its tooltip, a+ * blocked test says what PortOS cannot do, and an untested applicable pairing is+ * a button that offers the run.+ */+function TestCell({ slot, onOpen, disabled }) {+ if (!slot) return null;+ if (slot.state === 'not-applicable') {+ return <span className="text-[11px] text-gray-600 italic" title={slot.reason || undefined}>{slot.reason || 'not applicable'}</span>;+ }+ if (slot.state === 'unavailable') {+ return <span className="text-[11px] text-gray-600 italic" title={slot.reason || undefined}>can’t run here</span>;+ }+ const verdict = slot.result?.verdict || null;+ return (+ <button+ type="button"+ onClick={onOpen}+ disabled={disabled}+ className="text-left disabled:opacity-50"+ title={slot.result ? slot.result.summary : 'Not run yet — open to see what this test does'}+ >+ {verdict+ ? <VerdictChip verdict={verdict}>{slot.result.summary}</VerdictChip>+ : (+ <Pill tone="bare" size="xs" icon={Play} className="border-port-border text-gray-400 hover:border-port-accent hover:text-white transition-colors">+ not run+ </Pill>+ )}+ </button>+ );+}++/**+ * Run every test that applies to one model, in one click.+ *+ * Only the runnable ones are queued, and the count says how many that is before+ * the click — so "Run 2 tests" is a promise about how many provider calls are+ * about to happen, the same promise a single test's gate makes.+ */+function RunAllButton({ model, disabled, onRun }) {+ const runnable = (model.tests || []).filter((t) => t.state === 'applicable' || t.state === 'unknown');+ if (!runnable.length) return null;+ return (+ <button+ type="button"+ onClick={() => onRun(model.backend, model.modelId, runnable.map((t) => t.testId))}+ disabled={disabled}+ title={`Run the ${runnable.length} test${runnable.length === 1 ? '' : 's'} that apply to ${model.modelId}, one after another`}+ className="inline-flex items-center gap-1.5 px-2 py-1 text-[11px] rounded border border-port-border text-gray-300 hover:border-port-accent hover:text-white transition-colors disabled:opacity-50 whitespace-nowrap"+ >+ <Play size={10} /> Run {runnable.length}+ </button>+ );+}++// ---- result rendering -------------------------------------------------------++/** Required/bonus keyword scoring for the vision test. */+function KeywordScore({ 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>+ );++ return (+ <div className="space-y-3">+ <div>+ <div className="flex items-baseline justify-between gap-2 mb-1">+ <h4 className="text-xs font-medium text-gray-400">Required</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">Bonus</h4>+ <span className="text-[11px] text-gray-500">{detail.bonusHit} of {detail.bonusTotal} — detail work, never fails a run</span>+ </div>+ {detail.bonus.map((entry) => row(entry, false))}+ </div>+ </div>+ );+}++/** Twelve-beat coverage for the story test. */+function BeatScore({ detail }) {+ return (+ <div>+ <div className="flex items-baseline justify-between gap-2 mb-1">+ <h4 className="text-xs font-medium text-gray-400">Beat coverage</h4>+ <span className="text-[11px] text-gray-500">+ {detail.found} of {detail.total}{detail.found > 1 && !detail.inOrder ? ' — out of order' : ' — in order'}+ </span>+ </div>+ {detail.beats.map((beat, i) => (+ <div key={beat.id} className="flex items-center gap-2 py-1.5 border-b border-port-border/50 last:border-b-0">+ {beat.hit+ ? <Check size={13} className="text-emerald-400 shrink-0" aria-label="present" />+ : <X size={13} className="text-port-error shrink-0" aria-label="missing" />}+ <span className={`text-xs ${beat.hit ? 'text-gray-300' : 'text-gray-500'}`}>{i + 1} · {beat.label}</span>+ {!beat.hit && <span className="ml-auto text-[10px] text-gray-600">missing</span>}+ </div>+ ))}+ <p className="text-[11px] text-gray-500 mt-2 leading-snug">+ Coverage is structure, not quality — it only says the model held a twelve-part shape across a long+ generation. Whether the outline is any good is above.+ </p>+ </div>+ );+}++/** On-disk checks for the sandbox test. */+function SandboxChecks({ detail }) {+ return (+ <div className="space-y-2">+ <p className="text-[11px] text-gray-500 leading-snug">+ Every check reads the sandbox on disk after the agent stopped, never the transcript. A model that+ says it fixed the module scores nothing for saying so.+ </p>+ {(detail.checks || []).map((check) => (+ <div key={check.id} className="flex items-center gap-2 py-1.5 border-b border-port-border/50 last:border-b-0">+ {check.ok+ ? <Check size={13} className="text-emerald-400 shrink-0" aria-label="passed" />+ : <X size={13} className="text-port-error shrink-0" aria-label="failed" />}+ <span className={`text-xs ${check.ok ? 'text-gray-300' : 'text-gray-500'}`}>{check.label}</span>+ </div>+ ))}+ <dl className="grid grid-cols-2 gap-2 text-xs pt-1">+ <div><dt className="text-gray-500">Tool calls</dt><dd className="text-gray-200">{detail.toolCalls ?? 0}</dd></div>+ <div><dt className="text-gray-500">Verify exit code</dt><dd className="text-gray-200">{detail.verifyExitCode ?? '—'}</dd></div>+ <div className="col-span-2">+ <dt className="text-gray-500">Verified with</dt>+ <dd className="text-gray-300 font-mono break-all">{detail.verifyCommand}</dd>+ </div>+ {detail.sandboxPath && (+ <div className="col-span-2">+ <dt className="text-gray-500">Sandbox kept at</dt>+ <dd className="text-gray-400 font-mono break-all text-[11px]">{detail.sandboxPath}</dd>+ </div>+ )}+ </dl>+ </div>+ );+}++const SCORE_VIEWS = {+ 'image-analysis': KeywordScore,+ 'story-outline': BeatScore,+ 'sandbox-repair': SandboxChecks,+};++// ---- the drawer -------------------------------------------------------------++/**+ * Gate → live → result, in one panel.+ *+ * Consent copy names the runtime, the model and the exact prompt before the+ * first call goes out — the same contract the assessment gate honours.+ */+function CapabilityTestDrawer({+ modelId, test, slot, model, prompt, runtimeLabel,+ running, liveLines, progress, onRun, onDelete, onClose, deleting, queue,+}) {+ const [tab, setTab] = useState('output');+ const liveRef = useRef(null);+ const result = slot?.result || null;+ const meta = testMeta(test?.id);++ // Follow the tail while the agent works — a transcript you have to scroll to+ // keep up with is not a live view.+ useEffect(() => {+ if (running && liveRef.current) liveRef.current.scrollTop = liveRef.current.scrollHeight;+ }, [running, liveLines]);++ // A finished run lands on its output rather than leaving the reader on the+ // transcript they were watching.+ useEffect(() => { if (!running && result) setTab('output'); }, [running, result]);++ if (!test) return null;+ const Icon = meta.Icon;+ const showTabs = Boolean(result) || running;+ // `undefined` transcript = still fetching, so the tab is offered rather than+ // hidden and then appearing under the reader a moment later.+ const hasTranscript = result?.transcript === undefined ? Boolean(result) : Boolean(result.transcript || liveLines.length);++ const tabs = showTabs+ ? [+ { id: 'output', label: 'Output' },+ { id: 'score', label: 'Checks' },+ ...(hasTranscript ? [{ id: 'transcript', label: 'Transcript' }] : []),+ ]+ : null;++ const ScoreView = SCORE_VIEWS[test.id];++ return (+ <Drawer+ open+ onClose={onClose}+ size="lg"+ title={test.label}+ subtitle={queue ? `${modelId} · ${runtimeLabel} · test ${queue.index} of ${queue.total}` : `${modelId} · ${runtimeLabel}`}+ tabs={tabs}+ activeTab={showTabs ? tab : undefined}+ onTabChange={setTab}+ // Closing IS stopping while a run is in flight, so both accidental+ // dismissal paths are shut off and the close button says what it will do.+ closeLabel={running ? (queue ? 'Stop the remaining tests' : 'Stop this test') : 'Close'}+ closeOnEsc={!running}+ closeOnBackdrop={!running}+ >+ <div className="space-y-4">+ <div className="flex items-start gap-2">+ <Icon size={16} className={`${meta.cls} shrink-0 mt-0.5`} />+ <div className="min-w-0">+ <p className="text-sm text-gray-300 leading-snug">{test.blurb}</p>+ <div className="flex items-center gap-1.5 mt-1.5 flex-wrap">+ <span className="text-[11px] text-gray-500">needs</span>+ {test.capabilities.map((c) => (+ <span key={c} className="px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400">+ {CAPABILITY_META[c]?.label || c}+ </span>+ ))}+ </div>+ </div>+ </div>++ {slot?.state === 'unknown' && (+ <p className="text-xs text-port-warning flex items-start gap-1.5" role="alert">+ <AlertTriangle size={12} className="mt-0.5 shrink-0" />+ {runtimeLabel} lists model ids only, so PortOS cannot confirm this model claims the capability.+ Running the test is how you find out.+ </p>+ )}++ {/* ---- gate: shown until the first run of this pairing ---- */}+ {!showTabs && (+ <>+ <div className="border border-port-border rounded-lg p-3 space-y-2">+ <h3 className="text-xs font-medium text-gray-400">What PortOS will send</h3>+ <pre className="text-[11px] text-gray-300 whitespace-pre-wrap font-mono leading-relaxed max-h-56 overflow-y-auto">{prompt}</pre>+ </div>+ <p className="text-xs text-gray-500 leading-snug">+ This runs <span className="text-gray-300 font-mono break-all">{modelId}</span> on{' '}+ <span className="text-gray-300">{runtimeLabel}</span> once. It loads the model into memory and+ can hold the runtime for several minutes. The result stays on this machine — it describes this+ hardware and this install, so it is never synced to a peer.+ </p>+ {test.id === 'sandbox-repair' && (+ <p className="text-xs text-gray-500 leading-snug">+ The broken module, its test and the data file are copied into a throwaway sandbox first. The+ model only ever edits the copy, and PortOS runs the test itself afterwards to decide the verdict.+ </p>+ )}+ </>+ )}++ {/* ---- live ---- */}+ {running && (+ <div className="border border-port-accent/30 rounded-lg overflow-hidden">+ <div className="flex items-center gap-2 px-3 py-2 border-b border-port-border">+ <Terminal size={12} className="text-port-accent" />+ <span className="text-xs text-gray-300">{progress || 'Starting…'}</span>+ <BrailleSpinner className="ml-auto" />+ </div>+ {liveLines.length > 0 && (+ <div ref={liveRef} className="bg-port-bg p-3 max-h-72 overflow-y-auto">+ {liveLines.map((line, i) => (+ // Lines are append-only and never reordered, so the index is a+ // stable key here; the model's own text has no id to key on.+ // eslint-disable-next-line react/no-array-index-key+ <div key={i} className="text-[11px] font-mono text-gray-400 whitespace-pre-wrap leading-relaxed">{line}</div>+ ))}+ </div>+ )}+ </div>+ )}++ {/* ---- result ---- */}+ {showTabs && !running && result && (+ <>+ {tab === 'output' && (+ <div className="space-y-2">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <VerdictChip verdict={result.verdict}>{result.summary}</VerdictChip>+ <span className="text-[11px] text-gray-500">+ {formatDurationMs(result.elapsedMs)}+ {result.timings?.tokensPerSecond ? ` · ${result.timings.tokensPerSecond} tok/s` : ''}+ </span>+ </div>+ {result.error && (+ <p className="text-xs text-port-warning flex items-start gap-1.5" role="alert">+ <AlertTriangle size={12} className="mt-0.5 shrink-0" /> {result.error}+ </p>+ )}+ <div className="bg-port-bg border border-port-border rounded-lg p-3">+ {/* `undefined` = the full record has not arrived yet (the report+ carries summaries only); `''` = it arrived and the model+ genuinely said nothing. Collapsing the two would show a+ loading drawer as a silent model. */}+ {result.output === undefined+ ? <BrailleSpinner text="Loading the output" />+ : (result.output.trim()+ ? <pre className="text-sm text-gray-200 whitespace-pre-wrap leading-relaxed font-sans">{result.output}</pre>+ : <p className="text-xs text-gray-500 italic">The model returned no text.</p>)}+ </div>+ </div>+ )}+ {tab === 'score' && (result.detail && ScoreView+ ? <ScoreView detail={result.detail} />+ : <p className="text-xs text-gray-500">Nothing was scored — the run failed before it produced anything.</p>)}+ {tab === 'transcript' && (+ <div className="bg-port-bg border border-port-border rounded-lg p-3 max-h-[28rem] overflow-y-auto">+ {result.transcript === undefined && liveLines.length === 0+ ? <BrailleSpinner text="Loading the transcript" />+ : (+ <pre className="text-[11px] font-mono text-gray-400 whitespace-pre-wrap leading-relaxed">+ {result.transcript?.trim() || liveLines.join('\n') || 'No agent transcript for this test.'}+ </pre>+ )}+ </div>+ )}+ </>+ )}++ <div className="flex items-center gap-2 pt-1 flex-wrap">+ <button+ type="button"+ onClick={onRun}+ disabled={running || deleting}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded bg-port-accent text-port-on-accent hover:opacity-90 transition-opacity disabled:opacity-50"+ >+ <Play size={12} /> {running ? 'Running…' : (result ? 'Run again' : `Run ${test.label.toLowerCase()}`)}+ </button>+ {result && !running && (+ <button+ type="button"+ onClick={onDelete}+ disabled={deleting}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded border border-port-border text-gray-300 hover:border-port-error hover:text-port-error transition-colors disabled:opacity-50"+ >+ <Trash2 size={12} /> Discard this result+ </button>+ )}+ {model?.capabilities === null && (+ <span className="text-[11px] text-gray-500">claim unverified</span>+ )}+ </div>+ </div>+ </Drawer>+ );+}++// ---- the panel --------------------------------------------------------------++export default function ModelCapabilityTests({ report, loading, onReload, disabled = false }) {+ const [searchParams, updateParams] = useUrlParams();+ const backend = searchParams.get('capBackend') || '';+ const modelId = searchParams.get('capModel') || '';+ const testId = searchParams.get('capTest') || '';+ const open = Boolean(backend && modelId && testId);++ const [liveLines, setLiveLines] = useState([]);+ const [progress, setProgress] = useState('');+ const [running, setRunning] = useState(false);+ const [deleting, setDeleting] = useState(false);+ // Position within a multi-test run, or `null` for a single one. The server+ // deliberately takes ONE test per request — a client that could post a list+ // 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 mountedRef = useMounted();++ // Which pairing is in flight. A ref, not state: the socket handler subscribes+ // once and must read the CURRENT target, not the one captured at registration.+ const activeRef = useRef(null);+ // A run occupies the local runtime for minutes. Without an abort, closing the+ // drawer would leave it running with nobody listening.+ const controllerRef = useRef(null);+ useEffect(() => () => controllerRef.current?.abort(), []);++ const openTest = useCallback((b, m, t) => {+ setLiveLines([]);+ setProgress('');+ updateParams({ capBackend: b, capModel: m, capTest: t });+ }, [updateParams]);++ const closeTest = useCallback(() => {+ controllerRef.current?.abort();+ controllerRef.current = null;+ activeRef.current = null;+ setRunning(false);+ setQueue(null);+ setProgress('');+ // `replace` so closing does not leave a Back button that reopens a run the+ // user just stopped.+ updateParams(CLOSED_PARAMS, { replace: true });+ }, [updateParams]);++ useEffect(() => {+ const onFrame = (frame) => {+ if (!mountedRef.current) return;+ if (frame?.scope !== 'capability-test') return;+ const active = activeRef.current;+ // Frames for a pairing this panel is not running (another tab, a run the+ // user already cancelled) are dropped: a stale line is worse than none.+ if (!active || frame.backend !== active.backend || frame.modelId !== active.modelId || frame.testId !== active.testId) return;+ if (frame.event === 'output' && frame.line) {+ setLiveLines((lines) => (lines.length >= MAX_LIVE_LINES+ ? [...lines.slice(1 - MAX_LIVE_LINES), frame.line]+ : [...lines, frame.line]));+ return;+ }+ if (frame.event === 'complete') { setProgress(''); return; }+ if (frame.message) setProgress(frame.message);+ };+ socket.on('localLlm:progress', onFrame);+ return () => socket.off('localLlm:progress', onFrame);+ }, [mountedRef]);++ const { model, test, slot } = useMemo(+ () => pairFor(report, backend, modelId, testId),+ [report, backend, modelId, testId],+ );++ // The report ships a SUMMARY of each result (verdict, score detail) — the+ // model output and the agent transcript are fetched only for the pairing the+ // drawer actually opens, so a page load does not carry every stored+ // transcript. `null` = not fetched yet, which renders as loading rather than+ // as "the model returned nothing".+ const [fullResult, setFullResult] = useState(null);+ useEffect(() => {+ if (!open || !slot?.result) { setFullResult(null); return undefined; }+ let live = true;+ // The drawer renders its own empty state, so the default toast is silenced+ // (client/src/CLAUDE.md: custom catch ⇒ silent).+ getModelCapabilityTestResult(backend, modelId, testId, { silent: true })+ .then((record) => { if (live) setFullResult(record); })+ .catch(() => { if (live) setFullResult(null); });+ return () => { live = false; };+ }, [open, backend, modelId, testId, slot?.result?.ranAt]);++ /**+ * Run one or more tests against one model, in sequence.+ *+ * Sequential rather than parallel because they all contend for the same local+ * runtime: two at once would measure the contention, and the sandbox test+ * holds an agent loop for minutes. Stopping (closing the drawer) ends the+ * whole queue rather than advancing to the next test — the user asked for it+ * to stop.+ */+ const runTests = useCallback(async (runBackend, runModel, testIds) => {+ const list = (testIds || []).filter(Boolean);+ if (!list.length) return;+ let completed = 0;++ for (const [index, id] of list.entries()) {+ setQueue(list.length > 1 ? { total: list.length, index: index + 1 } : null);+ // `replace` after the first, so Back does not walk through every test of a+ // queue the user already watched finish.+ updateParams({ capBackend: runBackend, capModel: runModel, capTest: id }, { replace: index > 0 });++ const controller = new AbortController();+ controllerRef.current = controller;+ activeRef.current = { backend: runBackend, modelId: runModel, testId: id };+ setLiveLines([]);+ setProgress('Starting…');+ setRunning(true);++ // The panel renders its own progress and error state, so the default toast+ // is silenced (client/src/CLAUDE.md: custom catch ⇒ silent).+ const result = await runModelCapabilityTest(+ { backend: runBackend, modelId: runModel, testId: id },+ { signal: controller.signal, silent: true },+ ).catch((err) => {+ // Our own abort rejects with the generic unreachable message — that is+ // the user stopping the run, not a failure worth shouting about.+ if (!controller.signal.aborted) toast.error(err?.message || 'The capability test could not run');+ return null;+ });++ if (!mountedRef.current) return;+ setRunning(false);+ activeRef.current = null;+ controllerRef.current = null;++ // A stop or a failure ends the queue: pressing on would run minutes of+ // work the user just interrupted.+ if (!result || result.cancelled) break;+ completed += 1;+ toast.success(`${result.testId}: ${result.verdict} — ${result.summary}`);+ }++ setQueue(null);+ if (completed) await onReload();+ }, [updateParams, onReload, mountedRef]);++ const removeResult = useCallback(async () => {+ setDeleting(true);+ const ok = await deleteModelCapabilityTest(backend, modelId, testId, { silent: true })+ .then(() => true)+ .catch((err) => { toast.error(err?.message || 'Could not discard that result'); return false; });+ if (!mountedRef.current) return;+ setDeleting(false);+ if (ok) {+ setLiveLines([]);+ await onReload();+ }+ }, [backend, modelId, testId, onReload, mountedRef]);++ // Summary first (it is always present and always current), with the fetched+ // output/transcript layered on when they arrive.+ const mergedSlot = useMemo(() => (slot?.result+ ? { ...slot, result: { ...slot.result, output: fullResult?.output, transcript: fullResult?.transcript } }+ : slot), [slot, fullResult]);++ const tests = report?.tests || [];+ const models = report?.models || [];+ const busy = disabled || running;++ return (+ <div className="border border-port-border rounded-lg p-3 space-y-3">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <div className="flex items-center gap-1.5">+ <FlaskConical size={13} className="text-port-accent-2" />+ <h3 className="text-xs font-medium text-gray-300">Capability test suite</h3>+ </div>+ <div className="flex items-center gap-3">+ <span className="text-[11px] text-gray-500">+ {report+ ? [+ `${report.counts.models} model${report.counts.models === 1 ? '' : 's'}`,+ `${report.counts.applicable} applicable test${report.counts.applicable === 1 ? '' : 's'}`,+ report.counts.passed ? `${report.counts.passed} passed` : null,+ report.counts.failed ? `${report.counts.failed} failed` : null,+ ].filter(Boolean).join(' · ')+ : '—'}+ </span>+ <button+ type="button"+ onClick={onReload}+ disabled={loading}+ title="Refresh capability tests"+ aria-label="Refresh capability tests"+ className="p-1 text-gray-400 hover:text-white transition-colors disabled:opacity-50"+ >+ <RefreshCw size={13} className={loading ? 'animate-spin' : ''} />+ </button>+ </div>+ </div>++ <p className="text-[11px] text-gray-500 leading-relaxed">+ Speed says how fast a model runs here; it cannot say whether the model can do the job. Each test below+ runs only where the model claims the matching capability — a model with no{' '}+ <span className="text-gray-400">vision</span> badge shows <em>not applicable</em> on the image test,+ never a failure. Nothing here calls a model until you press a button that names it, and every run keeps+ the full output.+ </p>++ {tests.length > 0 && (+ <div className="grid gap-2 sm:grid-cols-3">+ {tests.map((t) => {+ const meta = testMeta(t.id);+ const Icon = meta.Icon;+ return (+ <div key={t.id} className={`border ${meta.border} rounded p-2.5 space-y-1.5`}>+ <div className="flex items-center gap-1.5 flex-wrap">+ <Icon size={13} className={meta.cls} />+ <span className="text-xs font-medium text-gray-200">{t.label}</span>+ <span className="text-[10px] text-gray-500">{t.capabilities.join(' · ')}</span>+ </div>+ <p className="text-[11px] text-gray-500 leading-snug">{t.blurb}</p>+ </div>+ );+ })}+ </div>+ )}++ {/* A runtime whose model list could not be read is missing from the matrix+ entirely — without this the table silently under-reports rather than+ saying it could not look. */}+ {report?.listErrors?.length > 0 && (+ <p className="text-xs text-port-warning flex items-start gap-1.5" role="alert">+ <AlertTriangle size={12} className="mt-0.5 shrink-0" />+ Could not list models for {report.listErrors.map((r) => r.label).join(', ')} — models there are missing from this table.+ </p>+ )}++ {report?.readError && (+ <p className="text-xs text-port-warning flex items-center gap-1.5" role="alert">+ <AlertTriangle size={12} /> {report.readError} — the next run will start a fresh record.+ </p>+ )}++ {loading && !report ? (+ <BrailleSpinner text="Loading capability tests" />+ ) : models.length === 0 ? (+ <p className="text-xs text-gray-500">+ No local models are installed, so there is nothing to test yet.+ </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) => (+ <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) => (+ <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">+ <span className="text-xs text-gray-200 font-mono break-all">{m.modelId}</span>+ <span className="text-[10px] text-gray-500">{m.runtimeLabel}</span>+ </div>+ <div className="flex items-center gap-1 mt-1 flex-wrap">+ <CapabilityBadges capabilities={m.capabilities} />+ </div>+ </td>+ {tests.map((t) => (+ <td key={t.id} className="px-3 py-2 align-top">+ <TestCell+ slot={m.tests.find((s) => s.testId === t.id)}+ disabled={busy}+ onOpen={() => openTest(m.backend, m.modelId, t.id)}+ />+ </td>+ ))}+ <td className="px-3 py-2 align-top text-right">+ <RunAllButton model={m} disabled={busy} onRun={runTests} />+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ </div>+ )}++ {open && (+ <CapabilityTestDrawer+ modelId={modelId}+ test={test}+ slot={mergedSlot}+ model={model}+ prompt={report?.prompts?.[testId] || ''}+ runtimeLabel={model?.runtimeLabel || backend}+ running={running}+ liveLines={liveLines}+ progress={progress}+ deleting={deleting}+ queue={queue}+ onRun={() => runTests(backend, modelId, [testId])}+ onDelete={removeResult}+ onClose={closeTest}+ />+ )}+ </div>+ );+}++export { VerdictChip, TestCell };diff --git a/client/src/components/settings/ModelCapabilityTests.test.jsx b/client/src/components/settings/ModelCapabilityTests.test.jsxnew file mode 100644index 0000000000..5fc897fbb9--- /dev/null+++ b/client/src/components/settings/ModelCapabilityTests.test.jsx@@ -0,0 +1,363 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { act, render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { MemoryRouter } from 'react-router';++vi.mock('../../services/api', () => ({+ runModelCapabilityTest: vi.fn(),+ deleteModelCapabilityTest: vi.fn(),+ // The report carries summaries only; the drawer fetches the model output and+ // the agent transcript for the one pairing it opens.+ getModelCapabilityTestResult: vi.fn(async () => ({ output: '', transcript: '' })),+}));+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } }));+// The live agent transcript arrives on the shared `localLlm:progress` socket+// event; these tests replay frames through the registered handler.+vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));++import { runModelCapabilityTest, deleteModelCapabilityTest, getModelCapabilityTestResult } from '../../services/api';+import socket from '../../services/socket';+import ModelCapabilityTests from './ModelCapabilityTests.jsx';++const TESTS = [+ { id: 'sandbox-repair', label: 'Sandbox repair', capabilities: ['tools'], prefers: ['code'], blurb: 'Fix a broken module in a sandbox.', driver: 'tui', kind: 'agent' },+ { 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 slot = (testId, over = {}) => ({ testId, state: 'applicable', missing: [], reason: null, result: null, ...over });++const model = (over = {}) => ({+ backend: 'ollama',+ runtimeLabel: 'Ollama',+ modelId: 'example-model:7b',+ capabilities: ['chat', 'tools', 'vision'],+ tests: TESTS.map((t) => slot(t.id)),+ verdict: null,+ ...over,+});++const report = (over = {}) => ({+ tests: TESTS,+ testIds: TESTS.map((t) => t.id),+ prompts: {+ 'image-analysis': 'Describe everything you can see in this image.',+ 'story-outline': 'Outline this as a hero journey in twelve beats.',+ 'sandbox-repair': 'Fix cart-totals.mjs so the test passes.',+ },+ models: [model()],+ runtimes: [{ id: 'ollama', label: 'Ollama', endpointRuntime: false, error: null, agentDriver: { available: true, reason: null } }],+ counts: { models: 1, applicable: 3, passed: 0, failed: 0 },+ listErrors: [],+ readError: null,+ ...over,+});++const renderPanel = (props = {}) => render(+ <MemoryRouter initialEntries={['/models/performance']}>+ <ModelCapabilityTests report={report()} loading={false} onReload={vi.fn()} {...props} />+ </MemoryRouter>,+);++/**+ * Replay a server progress frame through the handler the panel registered.+ * Wrapped in `act` because a socket frame drives a state update from outside+ * React's event system — the suite treats an unwrapped one as a hard failure.+ */+const emitFrame = async (frame) => {+ const handler = socket.on.mock.calls.find(([event]) => event === 'localLlm:progress')?.[1];+ await act(async () => { handler?.(frame); });+};++beforeEach(() => vi.clearAllMocks());++describe('the matrix', () => {+ it('lists every installed model with the badges it claims', () => {+ renderPanel();+ expect(screen.getByText('example-model:7b')).toBeInTheDocument();+ expect(screen.getByLabelText('Tool use')).toBeInTheDocument();+ expect(screen.getByLabelText('Vision')).toBeInTheDocument();+ });++ it('shows an unclaimed capability as a reason, never as a failure', () => {+ renderPanel({+ report: report({+ models: [model({+ capabilities: ['chat'],+ tests: [+ slot('sandbox-repair', { state: 'not-applicable', missing: ['tools'], reason: 'no tools badge' }),+ slot('image-analysis', { state: 'not-applicable', missing: ['vision'], reason: 'no vision badge' }),+ slot('story-outline'),+ ],+ })],+ }),+ });+ expect(screen.getByText('no tools badge')).toBeInTheDocument();+ expect(screen.getByText('no vision badge')).toBeInTheDocument();+ // A skipped test is not a red verdict and offers no run.+ expect(screen.queryByText('failed')).not.toBeInTheDocument();+ expect(screen.getAllByRole('button', { name: /not run/i })).toHaveLength(1);+ });++ it('says a test cannot run here when PortOS has no driver for the runtime', () => {+ renderPanel({+ report: report({+ models: [model({ tests: [slot('sandbox-repair', { state: 'unavailable', reason: 'no OpenCode TUI provider is configured for LM Studio' }), slot('image-analysis'), slot('story-outline')] })],+ }),+ });+ expect(screen.getByText(/can.t run here/)).toBeInTheDocument();+ });++ it('renders "capabilities not reported" rather than an empty badge row', () => {+ renderPanel({ report: report({ models: [model({ capabilities: null })] }) });+ expect(screen.getByText('capabilities not reported')).toBeInTheDocument();+ });++ it('summarises a recorded result in the cell', () => {+ renderPanel({+ report: report({+ models: [model({+ tests: [+ slot('sandbox-repair', { result: { verdict: 'passed', summary: 'fixed in 3 tool calls' } }),+ slot('image-analysis', { result: { verdict: 'failed', summary: '1 of 4 required' } }),+ slot('story-outline'),+ ],+ })],+ }),+ });+ expect(screen.getByText('fixed in 3 tool calls')).toBeInTheDocument();+ expect(screen.getByText('1 of 4 required')).toBeInTheDocument();+ });++ it('says so plainly when nothing is installed', () => {+ renderPanel({ report: report({ models: [], counts: { models: 0, applicable: 0, passed: 0, failed: 0 } }) });+ expect(screen.getByText(/no local models are installed/i)).toBeInTheDocument();+ });+});++describe('the run gate', () => {+ it('names the exact prompt before anything is sent', async () => {+ const user = userEvent.setup();+ renderPanel();+ await user.click(screen.getAllByRole('button', { name: /not run/i })[1]);++ expect(await screen.findByText('Describe everything you can see in this image.')).toBeInTheDocument();+ // Nothing has been called yet — the gate is the consent step.+ expect(runModelCapabilityTest).not.toHaveBeenCalled();+ });++ it('warns that the claim is unverified on a runtime that reports no capabilities', async () => {+ const user = userEvent.setup();+ renderPanel({+ report: report({+ models: [model({ backend: 'llama', runtimeLabel: 'llama.cpp', capabilities: null, tests: TESTS.map((t) => slot(t.id, { state: 'unknown', reason: 'this runtime reports no capability list' })) })],+ }),+ });+ await user.click(screen.getAllByRole('button', { name: /not run/i })[0]);+ expect(await screen.findByRole('alert')).toHaveTextContent(/lists model ids only/i);+ });++ it('runs only the model and test the gate named', async () => {+ const user = userEvent.setup();+ const onReload = vi.fn();+ runModelCapabilityTest.mockResolvedValue({ verdict: 'passed', summary: '4 of 4 required' });+ renderPanel({ onReload });++ await user.click(screen.getAllByRole('button', { name: /not run/i })[1]);+ await user.click(await screen.findByRole('button', { name: /run image analysis/i }));++ await waitFor(() => expect(runModelCapabilityTest).toHaveBeenCalledTimes(1));+ expect(runModelCapabilityTest.mock.calls[0][0]).toEqual({+ backend: 'ollama', modelId: 'example-model:7b', testId: 'image-analysis',+ });+ await waitFor(() => expect(onReload).toHaveBeenCalled());+ });+});++describe('the live run', () => {+ it('streams agent transcript lines as they arrive', async () => {+ const user = userEvent.setup();+ // Never resolves: the run stays in flight so the live view is what renders.+ runModelCapabilityTest.mockImplementation(() => new Promise(() => {}));+ renderPanel();++ await user.click(screen.getAllByRole('button', { name: /not run/i })[0]);+ await user.click(await screen.findByRole('button', { name: /run sandbox repair/i }));++ const target = { scope: 'capability-test', backend: 'ollama', modelId: 'example-model:7b', testId: 'sandbox-repair' };+ await emitFrame({ ...target, event: 'progress', message: 'Sandbox ready — 3 files copied.' });+ await emitFrame({ ...target, event: 'output', line: '● read cart-totals.mjs' });++ expect(await screen.findByText('Sandbox ready — 3 files copied.')).toBeInTheDocument();+ expect(await screen.findByText('● read cart-totals.mjs')).toBeInTheDocument();+ });++ it('ignores frames for a pairing it is not running', async () => {+ const user = userEvent.setup();+ runModelCapabilityTest.mockImplementation(() => new Promise(() => {}));+ renderPanel();++ await user.click(screen.getAllByRole('button', { name: /not run/i })[0]);+ await user.click(await screen.findByRole('button', { name: /run sandbox repair/i }));++ await emitFrame({ scope: 'capability-test', backend: 'ollama', modelId: 'some-other-model', testId: 'sandbox-repair', event: 'output', line: 'from another run' });+ // A model pull streaming on the same socket event must not render here either.+ await emitFrame({ scope: 'model-pull', backend: 'ollama', modelId: 'example-model:7b', event: 'output', line: 'pulling a layer' });++ expect(screen.queryByText('from another run')).not.toBeInTheDocument();+ expect(screen.queryByText('pulling a layer')).not.toBeInTheDocument();+ });+});++describe('a recorded result', () => {+ const withResult = (result) => report({+ models: [model({ tests: [slot('sandbox-repair'), slot('image-analysis', { result }), slot('story-outline')] })],+ });++ const openResult = async (user) => {+ await user.click(screen.getByRole('button', { name: /2 of 4 required/i }));+ };++ const RESULT = {+ verdict: 'partial',+ summary: '2 of 4 required, 1 of 3 bonus',+ ranAt: '2026-08-22T09:00:00.000Z',+ elapsedMs: 4200,+ error: null,+ timings: null,+ detail: {+ verdict: 'partial',+ requiredHit: 2,+ requiredTotal: 4,+ bonusHit: 1,+ bonusTotal: 3,+ required: [+ { id: 'bicycle', label: 'Bicycle', any: ['bicycle', 'bike'], hit: true },+ { id: 'bench', label: 'Bench', any: ['bench'], hit: true },+ { id: 'lamp', label: 'Street lamp', any: ['lamp'], hit: false },+ { id: 'dog', label: 'Dog', any: ['dog'], hit: false },+ ],+ bonus: [+ { id: 'red-bicycle', label: 'Bicycle is red', any: ['red'], hit: true },+ { id: 'blue-bench', label: 'Bench is blue', any: ['blue'], hit: false },+ { id: 'sign-number', label: 'Reads the number 3', any: ['3'], hit: false },+ ],+ },+ };++ it('leads with what the model actually said, fetched for this pairing alone', async () => {+ const user = userEvent.setup();+ getModelCapabilityTestResult.mockResolvedValue({ output: 'A bicycle and a bench at night.', transcript: '' });+ renderPanel({ report: withResult(RESULT) });+ await openResult(user);++ expect(await screen.findByText('A bicycle and a bench at night.')).toBeInTheDocument();+ expect(getModelCapabilityTestResult).toHaveBeenCalledWith(+ 'ollama', 'example-model:7b', 'image-analysis', { silent: true },+ );+ });++ it('says the model returned nothing only once the record has actually arrived', async () => {+ const user = userEvent.setup();+ getModelCapabilityTestResult.mockResolvedValue({ output: '', transcript: '' });+ renderPanel({ report: withResult(RESULT) });+ await openResult(user);+ // An empty string is a silent model; "not fetched yet" must not render as one.+ expect(await screen.findByText(/returned no text/i)).toBeInTheDocument();+ });++ it('separates required from bonus, and says bonus cannot fail a run', async () => {+ const user = userEvent.setup();+ renderPanel({ report: withResult(RESULT) });+ await openResult(user);+ await user.click(await screen.findByRole('tab', { name: /checks/i }));++ expect(screen.getByText(/2 of 4 — all needed to pass/i)).toBeInTheDocument();+ expect(screen.getByText(/1 of 3 — detail work, never fails a run/i)).toBeInTheDocument();+ // Two required hits plus one bonus hit — a bonus miss is styled as a muted+ // skip, never as the red X a required miss gets.+ expect(screen.getAllByLabelText('found')).toHaveLength(3);+ expect(screen.getAllByLabelText('not found')).toHaveLength(4);+ });++ it('discards a result and refreshes rather than leaving a stale row', async () => {+ const user = userEvent.setup();+ const onReload = vi.fn();+ deleteModelCapabilityTest.mockResolvedValue({ success: true });+ renderPanel({ report: withResult(RESULT), onReload });++ await openResult(user);+ await user.click(await screen.findByRole('button', { name: /discard this result/i }));++ await waitFor(() => expect(deleteModelCapabilityTest).toHaveBeenCalledWith(+ 'ollama', 'example-model:7b', 'image-analysis', { silent: true },+ ));+ await waitFor(() => expect(onReload).toHaveBeenCalled());+ });++ it('shows a mid-run error beside the score instead of replacing it', async () => {+ const user = userEvent.setup();+ getModelCapabilityTestResult.mockResolvedValue({ output: 'A bicycle and a bench at night.', transcript: '' });+ renderPanel({ report: withResult({ ...RESULT, error: 'Timed out after 300000ms' }) });+ await openResult(user);+ expect(await screen.findByRole('alert')).toHaveTextContent('Timed out after 300000ms');+ expect(await screen.findByText('A bicycle and a bench at night.')).toBeInTheDocument();+ });+});++describe('running everything that applies to one model', () => {+ it('offers only the runnable tests, and says how many before the click', () => {+ renderPanel({+ report: report({+ models: [model({+ tests: [+ slot('sandbox-repair', { state: 'not-applicable', reason: 'no tools badge' }),+ slot('image-analysis'),+ slot('story-outline'),+ ],+ })],+ }),+ });+ expect(screen.getByRole('button', { name: /run 2/i })).toBeInTheDocument();+ });++ it('runs them one after another rather than all at once', async () => {+ const user = userEvent.setup();+ const onReload = vi.fn();+ runModelCapabilityTest.mockImplementation(async ({ testId }) => ({ testId, verdict: 'passed', summary: 'ok' }));+ renderPanel({ onReload });++ await user.click(screen.getByRole('button', { name: /run 3/i }));++ await waitFor(() => expect(runModelCapabilityTest).toHaveBeenCalledTimes(3));+ expect(runModelCapabilityTest.mock.calls.map(([payload]) => payload.testId))+ .toEqual(['sandbox-repair', 'image-analysis', 'story-outline']);+ // One refresh at the end, not one per test.+ await waitFor(() => expect(onReload).toHaveBeenCalledTimes(1));+ });++ it('stops the whole queue when a test fails rather than pressing on', async () => {+ const user = userEvent.setup();+ runModelCapabilityTest.mockRejectedValueOnce(new Error('llama.cpp is not reachable'));+ renderPanel();++ await user.click(screen.getByRole('button', { name: /run 3/i }));++ await waitFor(() => expect(runModelCapabilityTest).toHaveBeenCalledTimes(1));+ // Minutes of queued work must not run on after the user has been told the+ // runtime is down.+ expect(runModelCapabilityTest).not.toHaveBeenCalledTimes(2);+ });++ it('hides the control for a model no test applies to', () => {+ renderPanel({+ report: report({+ models: [model({+ capabilities: [],+ tests: TESTS.map((t) => slot(t.id, { state: 'not-applicable', reason: 'no badge' })),+ })],+ }),+ });+ expect(screen.queryByRole('button', { name: /^run \d/i })).not.toBeInTheDocument();+ });+});diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex 43ce96ae7c..3c4326c271 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -279,3 +279,35 @@ export const cancelLocalLlmAssessmentSweep = (options) =>// several, one per launch tuning. `''` is the backend-defaults record.export const deleteLocalLlmAssessment = (backend, modelId, tuningKey = '', options) =>request('/local-llm/assessments/delete', { method: 'POST', body: JSON.stringify({ backend, modelId, tuningKey }), ...options });++// === 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? Same consent rule —+// GET is disk-only and safe on mount; the run endpoint calls a model and must+// only fire from a click that was shown the runtime, model and tests first.+//+// There is deliberately no sweep and no schedule endpoint. A capability run is a+// manual act.++// What each installed model claims, which tests apply to it, and what each one+// proved last time. Zero LLM calls.+export const getModelCapabilityTests = (options) =>+ request('/local-llm/capability-tests', options);++// Run ONE test against ONE model. Minutes-long for the sandbox repair (it drives+// a real agent loop), so callers pass a `signal` to abort on navigate-away, and+// watch `localLlm:progress` frames with `scope: 'capability-test'` for the live+// transcript.+export const runModelCapabilityTest = (payload, options) =>+ request('/local-llm/capability-tests/run', { method: 'POST', body: JSON.stringify(payload), ...options });++// ONE stored result in full — the model's output and, for the sandbox test, the+// agent transcript. The report ships summaries only (those two fields are the+// bulk of a record), so the drawer fills in the rest when it opens a pairing.+export const getModelCapabilityTestResult = (backend, modelId, testId, options) =>+ request(`/local-llm/capability-tests/result?backend=${encodeURIComponent(backend)}&modelId=${encodeURIComponent(modelId)}&testId=${encodeURIComponent(testId)}`, options);++// Drop one recorded result — after re-pulling a model at a different quant, the+// stored verdict describes weights that are no longer installed.+export const deleteModelCapabilityTest = (backend, modelId, testId, options) =>+ request('/local-llm/capability-tests/delete', { method: 'POST', body: JSON.stringify({ backend, modelId, testId }), ...options });diff --git a/server/fixtures/model-tests/sandbox/cart-totals/cart-totals.mjs b/server/fixtures/model-tests/sandbox/cart-totals/cart-totals.mjsnew file mode 100644index 0000000000..811b5d2c54--- /dev/null+++ b/server/fixtures/model-tests/sandbox/cart-totals/cart-totals.mjs@@ -0,0 +1,31 @@+import { readFile } from 'node:fs/promises';++// Tax rate per region. `default` is what an unrecognised region should fall+// back to — several of our marketplaces send regions this table has never heard+// of, and an order must still total.+export const TAX = {+ 'us-ca': 0.0875,+ 'us-ny': 0.08875,+ uk: 0.2,+ default: 0.05,+};++/** Round a currency amount to two decimal places. */+export function round2(value) {+ return Math.round(value * 100) / 100;+}++/** Load the sample orders this module's test runs against. */+export async function loadOrders(path = new URL('./orders.json', import.meta.url)) {+ return JSON.parse(await readFile(path, 'utf8'));+}++/**+ * Total one order: line items, then regional tax, then the discount, rounded to+ * two decimal places.+ */+export function cartTotal({ items, region, discount = 0 }) {+ const sub = items.reduce((acc, item) => acc + item.price * item.qty, 0);+ const rate = TAX[region];+ return (sub - discount) + (sub - discount) * rate;+}diff --git a/server/fixtures/model-tests/sandbox/cart-totals/cart-totals.test.mjs b/server/fixtures/model-tests/sandbox/cart-totals/cart-totals.test.mjsnew file mode 100644index 0000000000..2dddfc3718--- /dev/null+++ b/server/fixtures/model-tests/sandbox/cart-totals/cart-totals.test.mjs@@ -0,0 +1,28 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { cartTotal, loadOrders } from './cart-totals.mjs';++const { orders } = await loadOrders();+const byId = (id) => orders.find((order) => order.id === id);++test('cartTotal sums line items and applies regional tax', () => {+ const order = byId('A-1');+ assert.equal(cartTotal(order), order.expectedTotal);+});++test('cartTotal subtracts the discount AFTER tax', () => {+ const order = byId('A-2');+ assert.equal(cartTotal(order), order.expectedTotal);+});++test('cartTotal falls back to the default rate for an unknown region', () => {+ const order = byId('A-3');+ assert.equal(cartTotal(order), order.expectedTotal);+});++test('cartTotal rounds every total to two decimal places', () => {+ for (const order of orders) {+ const total = cartTotal(order);+ assert.equal(total, Number(total.toFixed(2)), `${order.id} is not rounded to two places`);+ }+});diff --git a/server/fixtures/model-tests/sandbox/cart-totals/orders.json b/server/fixtures/model-tests/sandbox/cart-totals/orders.jsonnew file mode 100644index 0000000000..4d322ef8de--- /dev/null+++ b/server/fixtures/model-tests/sandbox/cart-totals/orders.json@@ -0,0 +1,32 @@+{+ "orders": [+ {+ "id": "A-1",+ "region": "us-ca",+ "discount": 0,+ "items": [+ { "sku": "oyster-knife", "price": 18.5, "qty": 2 },+ { "sku": "cedar-board", "price": 24, "qty": 1 }+ ],+ "expectedTotal": 66.34+ },+ {+ "id": "A-2",+ "region": "uk",+ "discount": 5,+ "items": [+ { "sku": "tide-chart", "price": 12, "qty": 3 }+ ],+ "expectedTotal": 38.2+ },+ {+ "id": "A-3",+ "region": "mars-1",+ "discount": 0,+ "items": [+ { "sku": "salt-cellar", "price": 9.99, "qty": 1 }+ ],+ "expectedTotal": 10.49+ }+ ]+}diff --git a/server/fixtures/model-tests/vision/bicycle-bench.svg b/server/fixtures/model-tests/vision/bicycle-bench.svgnew file mode 100644index 0000000000..2426116b16--- /dev/null+++ b/server/fixtures/model-tests/vision/bicycle-bench.svg@@ -0,0 +1,61 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 420 300" width="1024" height="731">+ <!-- PortOS vision capability fixture. Flat vector on purpose: every element is+ a solid, unambiguous shape so the expected description is knowable, and+ the scorer can be a keyword match rather than a second model.+ Required: bicycle, bench, street lamp, dog. Bonus: red, blue, the number 3.+ No <text> element anywhere — glyph rendering depends on the host's fonts,+ and the digit on the sign has to look the same on every machine. -->+ <rect x="0" y="0" width="420" height="300" fill="#14202b"/>+ <circle cx="70" cy="42" r="1.8" fill="#e8eef5" opacity="0.55"/>+ <circle cx="150" cy="26" r="1.4" fill="#e8eef5" opacity="0.45"/>+ <circle cx="255" cy="52" r="1.6" fill="#e8eef5" opacity="0.5"/>+ <circle cx="392" cy="34" r="1.4" fill="#e8eef5" opacity="0.45"/>++ <circle cx="350" cy="95" r="54" fill="#fbbf24" opacity="0.10"/>+ <circle cx="350" cy="95" r="30" fill="#fbbf24" opacity="0.14"/>++ <rect x="0" y="225" width="420" height="75" fill="#1b2a21"/>+ <rect x="0" y="225" width="420" height="20" fill="#26362e"/>++ <!-- street lamp, lit -->+ <rect x="347" y="95" width="6" height="130" fill="#6b7d74"/>+ <path d="M334 95 L366 95 L359 78 L341 78 Z" fill="#fbbf24"/>+ <rect x="338" y="221" width="24" height="6" rx="2" fill="#6b7d74"/>++ <!-- sign post carrying the number 3 -->+ <rect x="298" y="150" width="5" height="75" fill="#6b7d74"/>+ <rect x="281" y="120" width="39" height="38" rx="5" fill="#22c55e"/>+ <path d="M293.5 130.5 C296 126.5, 307.5 126, 307.5 133 C307.5 137.6, 302.5 139, 300 139 C302.5 139, 309 140, 309 145.5 C309 152.5, 296 152.5, 293 148"+ fill="none" stroke="#0d1a12" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round"/>++ <!-- blue bench -->+ <rect x="155" y="160" width="110" height="7" rx="2" fill="#3b82f6"/>+ <rect x="155" y="172" width="110" height="7" rx="2" fill="#3b82f6"/>+ <rect x="152" y="186" width="116" height="8" rx="2" fill="#60a5fa"/>+ <rect x="160" y="194" width="7" height="31" fill="#2f6fd0"/>+ <rect x="253" y="194" width="7" height="31" fill="#2f6fd0"/>+ <rect x="160" y="158" width="6" height="30" fill="#2f6fd0"/>+ <rect x="254" y="158" width="6" height="30" fill="#2f6fd0"/>++ <!-- dog: floppy ear, snout, four legs and a low tail, so it reads as a dog+ rather than a cat at thumbnail size -->+ <ellipse cx="200" cy="212" rx="17" ry="8.5" fill="#e5e7eb"/>+ <rect x="187" y="217" width="4" height="11" rx="1.6" fill="#e5e7eb"/>+ <rect x="195" y="217" width="4" height="11" rx="1.6" fill="#e5e7eb"/>+ <rect x="205" y="217" width="4" height="11" rx="1.6" fill="#e5e7eb"/>+ <rect x="213" y="217" width="4" height="11" rx="1.6" fill="#e5e7eb"/>+ <circle cx="220" cy="203" r="8.5" fill="#e5e7eb"/>+ <ellipse cx="230" cy="206" rx="6.5" ry="4.2" fill="#e5e7eb"/>+ <circle cx="235" cy="205" r="1.7" fill="#14202b"/>+ <path d="M215 196 C210 194, 208 202, 211 207 C214 208, 215 202, 216 199 Z" fill="#d1d5db"/>+ <path d="M183 209 C176 208, 174 202, 177 198" fill="none" stroke="#e5e7eb" stroke-width="3.6" stroke-linecap="round"/>++ <!-- red bicycle -->+ <circle cx="60" cy="200" r="21" fill="none" stroke="#ef4444" stroke-width="4"/>+ <circle cx="118" cy="200" r="21" fill="none" stroke="#ef4444" stroke-width="4"/>+ <path d="M60 200 L84 166 L118 200 M84 166 L96 200 M60 200 L96 200"+ fill="none" stroke="#ef4444" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>+ <path d="M78 162 L92 162" stroke="#ef4444" stroke-width="4" stroke-linecap="round"/>+ <path d="M118 200 L118 176 L110 171" fill="none" stroke="#ef4444" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>+ <path d="M104 169 L122 165" stroke="#ef4444" stroke-width="4" stroke-linecap="round"/>+</svg>diff --git a/server/lib/README.md b/server/lib/README.mdindex ad89c815f4..dfad1642e1 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -133,6 +133,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision plus an explicit `files` LIST — one repackaged safetensors, or just the shards of an upstream checkpoint that carry parameters the loader actually builds; in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to `[]` — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; `TextEncoderPicker` owns the hide-when-there-is-no-real-choice check), `isStockTextEncoder(id)` makes absence and the `stock` sentinel the same request, `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED` (with the non-throwing `supportsVideoTextEncoder` + `videoTextEncoderUnsupportedError` split out so the request path can reject before staging uploads), and `downloadableVideoTextEncoders()` (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). Both are absent for an UPSTREAM Qwen3-VL-32B checkpoint, which already uses the loader namespace and ships its own norm. A candidate must BE Qwen3-VL-32B (the shim reuses upstream's config/tokenizer/processor) — a different Qwen generation is not a substitute however close its conditioning width looks; see docs/features/video-text-encoders.md. `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. The `ltx25` table (#4320) uses a third mechanic, `configOverrides`, because an LTX-2.5 pack's OWN Gemma 4 tower wins over `--gemma` inside the pinned fork: the substitution is a standalone shim directory whose generated `config.json` is the substitute's own with these keys merged over it (only ever the `model_type` label a unified checkpoint gets wrong — never `text_config`/`quantization`), and a candidate must BE Gemma 4 12B at 48 layers / hidden 3840 / vocab 262144 / `k_eq_v`. `verified` gates a substitute out of BOTH lanes (picker AND download) until it has been A/B-rendered against its runtime's stock conditioner — required on every non-built-in entry and fail-closed on absence, so a new entry is unreachable until someone states a verdict; both ltx25 substitutes are `verified: false` today. `declaredVideoTextEncoders()` is the UNFILTERED table for shape/invariant checks only — never the render or download path, and `videoTextEncoderRuntimes()` enumerates the table's runtime keys so parity/shape tests cover every runtime rather than the one that happened to exist when they were written. || `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, model-flag scan helpers incl. `stripBrokenModelFlags`, `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`, `isCursorProvider`) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `CURSOR_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `hasEffortFlag`, `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`, and deliberately silent for cursor — and `foldCursorEffortIntoModel`, which carries a cursor level inside `--model` as Cursor’s own variant syntax (`gpt-5[effort=max]`) because `cursor-agent` has no `--effort` flag) plus codex startup-arg helpers (`CODEX_EFFORT_KEY`, `CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal) plus `PORTOS_CLI_CONFIG_KEYS` / `isPortosSuppliedConfigKey` — the exhaustive list of `-c <key>=<value>` config keys PortOS injects, read by the `cli-config-invalid` error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file. || `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. |+| `modelCapabilityTests.js` | Catalog + scoring for the CAPABILITY tests on `/models/performance` (run by `services/modelCapabilityTests.js`): `CAPABILITY_TESTS` (sandbox repair / image analysis / story outline, each gated on the capability badges the install catalog already shows), `applicabilityFor` + `applicableTests` (`applicable` / `not-applicable` / `unknown` — an UNCLAIMED capability is never a failure, and `null` capabilities mean the runtime reported none, which is distinct from `[]`), `scoreKeywords` + `VISION_FIXTURE_KEYWORDS` (required vs bonus terms, word-boundary matched with a negation guard so "no dog" doesn't score a dog), `scoreStoryBeats` + `HEROS_JOURNEY_BEATS` (coverage AND ordering, judged only over the beats present), `scoreSandboxRepair` (verdict from observed disk facts — editing the test instead of the module fails outright), `formatAgentEvent` (one agent stream frame → a transcript line), `rollUpVerdict`, and the verbatim `CAPABILITY_TEST_PROMPTS` / `SANDBOX_TASK_PROMPT` the consent gate shows. Pure, so any stored transcript can be re-scored with no provider call. || `modelPricing.js` | Per-model API billing rates for the /devtools/usage cost estimates — `resolveModelRates(providerId, model)` (exact → family regex → provider default → blended fallback, with a `matched` tier; also derives `cacheReadPer1M`/`cacheWritePer1M` from the input rate via per-family multipliers), `isFreeProvider` (ollama/lmstudio/`ollamaBacked`/localhost = free), `estimateCostUsd(tokensIn, tokensOut, rates, cache?)` — `tokensIn` is UNCACHED input; cache tiers are priced separately via the optional 4th arg — and `PRICING_AS_OF`. Informational only (PortOS runs on subscriptions); still excludes batch/long-context tiers. || `usageRange.js` | `resolveUsageRange({ period, from, to })` — pure period→inclusive-YYYY-MM-DD range resolution for the usage cost report (explicit dates win; `all` unbounded; default 7d). || `subscriptionSavings.js` | Subscription-vs-API savings math for the usage page — `resolveSavingsWindow` (clamps an open-ended report range to today / first activity day), `prorateMonthlyCost` (monthly plan price → this window's share, `DAYS_PER_MONTH`, capped by `MAX_MONTHLY_COST`), `savingsPercent` / `costMultiplier` (null, never 0, when the comparison is undefined), `attributeReportCostToFamilies` (groups report rows by their stamped `family`), `roundCents` (the one money rounder), and `buildSubscriptionSavings({ entries, range, unmatchedApiCost })` → per-family rows + totals. Pure. |@@ -147,6 +148,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `vllmQwenProvision.js` | The `.env` half of provisioning that same project: `generateVllmApiKey()`, `isWsl2Engine()` (win32 counts — Docker Desktop's engine IS a WSL2 VM), `vllmEnvDefaults({apiKey, wsl2})` → the load-bearing tool-parser/pin-memory/alloc-conf settings, and `mergeEnvFileContents(existing, defaults)` → `{contents, added, kept, effective}`. **Additive only** — an operator's existing key or tuning is never overwritten, and `effective` reports what the container will actually read. Plus `WSL2_PREPARE_MIN_BYTES` / `WSL2_PREPARE_CONFIG_HINT` for the ceiling `prepare` needs (detected and warned about, never raised). || `sglangQwenProject.js` | `resolveSglangProjectDir()` / `inspectSglangQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the operator's SGLang Qwen3.8-27B project, plus `sglangStartBlockedReason(project)` → the prose refusal (or `null`). Sibling of `vllmQwenProject.js` with the same tri-state `hasWeights` contract (`true` found / `false` caches read and empty / `null` no cache readable) and the same directory-reads-only rule — never docker, never a registry. Differs in that PortOS OWNS this launch line (SGLang publishes an image but no compose project), so the refusals point at the compose file in `docs/features/sglang-qwen38.md` rather than at a `git clone`. Overrides: `SGLANG_QWEN_PROJECT_DIR`, `SGLANG_QWEN_WEIGHTS_DIR`. || `sglangQwenRecipe.js` | The `sglang serve` launch line PortOS owns, per NVIDIA card class. `buildSglangQwenRecipe({hw, contextLength, ssmDtype, spec, radixStrategy, host, port})` → `{image, modelName, modelPath, cell, mambaRatio, stateSlots, flags, env}`, and `sglangComposeYaml(recipe)` renders the `docker-compose.yml` from it (one source of truth; a test pins the doc against it). `mambaFullMemoryRatio(...)` derives `--mamba-full-memory-ratio` from the cookbook formula `(S + D) × state_bytes / (L × kv_bytes_per_token)` — load-bearing, because the cookbook default `0.9` under-sizes the GDN state pool at CoS prompt lengths and silently clamps `max_running_requests`. Both Qwen parsers (`--reasoning-parser qwen3`, `--tool-call-parser qwen3_coder` — NOT vLLM's `qwen3_xml`) are baked into every cell: getting them wrong fails silently, with the model emitting raw markup and the agent never calling a tool. `sglangCellForGpu(gpu)` maps a `cudaCapability.js` compute-cap row to a cell (SM 9.x → `h200`, SM ≥10 → `rtx6000`/`rtx5090` by VRAM, Ampere → `null`, which is a refusal: 24 GB stays on vLLM), and `sglangUnsupportedReason({platform, status, gpus})` is the prose for every no — never collapsing a probe `'unknown'` into "no GPU". Pure: no filesystem, no docker, no network. |+| `opencodeStream.js` | OpenCode's `--format json` event stream — ONE parser, shared by `services/localModelAgentBenchmark.js` (which wants chars/tokens) and `services/modelCapabilityTests.js` (which wants a readable transcript). `eventPart` (accepts the flat `{part}` and nested `{properties.part}` envelopes OpenCode has both used), `isToolEvent` / `eventText`, `parseAgentLine` / `parseAgentEvents` (blank and unparsable lines yield nothing rather than throwing), `formatAgentEvent` (one frame → a transcript line a person can read, with the path or command the tool acted on), and `summarizeOpenCodeEvents` (assistant chars, tool calls, and output tokens — `null`, never 0, when OpenCode reported no usage; tool ARGUMENTS are deliberately not counted as answer text). Pure. The runner that produces the stream is `services/opencodeTask.js`. || `openAiModelsProbe.js` | `probeOpenAiModels(baseUrl, { timeoutMs, apiKey })` → `{ reachable, models, error }` — the one `GET {base}/models` probe for the local OpenAI-compatible daemons, shared by `services/providerReadiness.js` and `services/llamaServerManager.js`. Distinguishes unreachable from reachable-but-unlistable (`models: null`) from up-with-nothing-loaded (`[]`), names the real transport failure via `describeFetchError` (undici reports every one as a bare `fetch failed`), and cancels an unread body on a non-OK response. `apiKey` attaches a Bearer header for a key-gated daemon (vLLM's compose stack), and a 401/403 answers `reachable: true` with `error: 'authentication required'` — a server that refused the request is definitively running, and calling it unreachable would send the user to start it again. Consolidated after the two copies drifted — one passed its timeout as a `timeout` key inside the fetch init object, where it is not an option, silently running a 500ms poll loop on the 15s default. || `openAiChatStream.js` | `streamOpenAiChat({ endpoint, apiKey, model, messages, temperature, maxTokens, extraBody, signal, onChunk, onStats })` → the streamed text — one streaming `POST {base}/chat/completions` against any local OpenAI-compatible daemon; `streamOllamaChat(...)` is the assessment-only native `/api/chat` transport that preserves Ollama's exact eval counts and nanosecond timings. Also exports `buildMessages`, `parseStreamFrame`, `parseOllamaStreamFrame`, `normalizeUsage` (snake/camel/Ollama token-count keys → `{completionTokens, promptTokens}`, `null` = not reported), and `resolvePartialOutput`. Registering `onStats` on the OpenAI path asks for token counts; a daemon that rejects `stream_options` is retried once without it and remembered per endpoint. Sibling of `openAiModelsProbe.js`. Shared by `services/localLlmPlayground.js` (provider-backed runs with a `/runs` record) and its `runEndpointLlmTest` (a bare loopback daemon PortOS holds no provider record for, which is how `services/localModelAssessments.js` measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with `.partialOutput` carrying what already streamed. || `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 973380c0e6..8de3583fb2 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -302,6 +302,8 @@ export * from './specDecodePresets.js';export * from './localModelHeuristics.js';export * from './localModelAssessment.js';export * from './localModelTuning.js';+export * from './modelCapabilityTests.js';+export * from './opencodeStream.js';export * from './ollamaContext.js';export * from './loraDataset.js';export * from './loraTriggers.js';diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.jsindex a8ecca4d2b..82fe7a204f 100644--- a/server/lib/mediaValidation.js+++ b/server/lib/mediaValidation.js@@ -12,6 +12,7 @@ import { z } from 'zod';import { PORTS } from './ports.js';import { ASSESSABLE_RUNTIMES } from './localProviderRuntime.js';import { SWEEP_SCOPES } from './localModelAssessment.js';+import { CAPABILITY_TEST_IDS } from './modelCapabilityTests.js';// OpenWorld snapshot pipeline (issue #877): how often to capture a city-state// frame and how many to retain. Validated as a settings slice on PUT /api/settings;@@ -322,6 +323,25 @@ export const localLlmAssessmentDeleteSchema = z.object({tuningKey: z.string().max(500).optional().default(''),});+// Capability tests (server/services/modelCapabilityTests.js). One request runs+// ONE test against ONE model — deliberately not a batch. A capability run is a+// manual act with a consent gate in front of it, and an endpoint that could+// accept a list of models would turn one click into an unbounded, hours-long+// sequence of provider calls the gate never named.+//+// `testId` is validated against the shipped catalog rather than as free text:+// the id selects which runner executes, so an unknown one must be a 400 at the+// edge, not a lookup miss deep in the service.+export const localLlmCapabilityTestSchema = z.object({+ backend: localLlmRuntimeSchema,+ modelId: localLlmModelIdSchema,+ testId: z.enum(CAPABILITY_TEST_IDS),+});+// Run, read-one and delete all name exactly one model+test pairing, so they+// share a schema rather than three copies that could drift apart.+export const localLlmCapabilityTestRunSchema = localLlmCapabilityTestSchema;+export const localLlmCapabilityTestDeleteSchema = localLlmCapabilityTestSchema;+export const localLlmCompareSchema = z.object({mode: z.enum(['round-robin', 'parallel']).optional().default('round-robin'),prompt: z.string().trim().min(1).max(50000),diff --git a/server/lib/modelCapabilityTests.js b/server/lib/modelCapabilityTests.jsnew file mode 100644index 0000000000..67d5083eff--- /dev/null+++ b/server/lib/modelCapabilityTests.js@@ -0,0 +1,343 @@+/**+ * Capability test catalog and scoring — pure.+ *+ * The Performance page answers "how FAST is this model here". This module backs+ * the other half: "can it actually DO the thing its badges claim". Each test is+ * bound to the capability badges the install catalog already shows+ * (`chat`/`code`/`reasoning`/`vision`/`tools`), so a test runs exactly where the+ * model made a claim worth checking.+ *+ * ## Two rules this file exists to hold+ *+ * 1. **An unclaimed capability is NOT a failure.** A model with no `vision`+ * badge is `not-applicable` on the image test — never `failed`. That is what+ * keeps the results matrix meaningful: a red cell always means "it said it+ * could, and it could not".+ * 2. **Unknown is not empty.** A runtime that reports no capability list at all+ * (a bare llama.cpp endpoint) yields `null`, which resolves to `unknown` —+ * distinct from `[]`, which is a runtime that answered and named none. The+ * UI offers an unknown-capability test rather than hiding or failing it.+ *+ * Scoring lives here rather than in the runner so every verdict is reproducible+ * from a stored transcript with no provider call — re-scoring an old run after+ * a keyword change costs nothing.+ */++import { escapeRegExp } from './textUtils.js';++/** Verdicts every scorer returns. `partial` is real evidence, not a soft fail. */+export const TEST_VERDICTS = Object.freeze(['passed', 'partial', 'failed']);++/**+ * The prompt each generative test sends, verbatim.+ *+ * Exported because the consent gate shows it before the first provider call —+ * a user agreeing to a run should be able to read what is about to be asked.+ * Fixed wording is also what makes two models' results comparable.+ */+export const CAPABILITY_TEST_PROMPTS = Object.freeze({+ 'image-analysis': 'Describe everything you can see in this image, including colours, objects, and any text or numbers.',+ 'story-outline': [+ 'Premise: a tidal-marsh oyster farmer finds that the water killing her beds is coming from the sea wall she campaigned to build.',+ '',+ "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'),+});++/**+ * The task the sandbox agent is given. The sandbox already contains the broken+ * module, its test, and the data file the test reads — the model has to find+ * and read them, not be handed their contents.+ */+export const SANDBOX_TASK_PROMPT = [+ 'This is a disposable PortOS capability check in the current directory.',+ 'The test file cart-totals.test.mjs is failing.',+ 'Read cart-totals.test.mjs, cart-totals.mjs and orders.json, then fix cart-totals.mjs on disk so the test passes.',+ 'Run `node cart-totals.test.mjs` to check your work, and keep going until it exits 0.',+ 'Do not edit cart-totals.test.mjs or orders.json, and do not create files outside this directory.',+].join(' ');++/**+ * One entry per test.+ *+ * `capabilities` is the badge set a model must ALREADY claim for the test to+ * apply — the gate, not a wish list. `prefers` is advisory only: it colours the+ * explanation ("a tool-caller without `code` usually narrates instead of+ * acting") and never decides applicability, because a model that clears the+ * gate deserves to be measured rather than pre-judged.+ */+export const CAPABILITY_TESTS = Object.freeze([+ Object.freeze({+ id: 'sandbox-repair',+ label: 'Sandbox repair',+ kind: 'agent',+ capabilities: Object.freeze(['tools']),+ prefers: Object.freeze(['code']),+ blurb: 'A broken module and its failing test are copied into a throwaway sandbox. The model must read the files, write a fix to disk, and make the test pass.',+ // Watching it work is the point of this one, so the runner drives a real+ // OpenCode TUI rather than an in-process tool loop.+ driver: 'tui',+ }),+ Object.freeze({+ id: 'image-analysis',+ label: 'Image analysis',+ kind: 'vision',+ capabilities: Object.freeze(['vision']),+ prefers: Object.freeze([]),+ blurb: 'A fixture image with known contents goes in; the description comes back. Scored on required and bonus keywords, so the check is deterministic.',+ driver: 'chat',+ }),+ Object.freeze({+ id: 'story-outline',+ label: 'Story outline',+ kind: 'text',+ capabilities: Object.freeze(['chat']),+ prefers: Object.freeze(['reasoning']),+ 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',+ }),+]);++export const CAPABILITY_TEST_IDS = Object.freeze(CAPABILITY_TESTS.map((t) => t.id));++export const getCapabilityTest = (id) => CAPABILITY_TESTS.find((t) => t.id === id) || null;++/**+ * Does this test apply to a model with these badges?+ *+ * @param {object} test one of CAPABILITY_TESTS+ * @param {string[]|null|undefined} capabilities `null`/`undefined` = the runtime+ * reported none at all (unknown); `[]` = it answered and the model claims none.+ * @returns {{ state: 'applicable'|'not-applicable'|'unknown', missing: string[], reason: string|null }}+ */+export function applicabilityFor(test, capabilities) {+ if (!test) return { state: 'not-applicable', missing: [], reason: 'unknown test' };+ if (!Array.isArray(capabilities)) {+ return {+ state: 'unknown',+ missing: [],+ // Naming the runtime's silence rather than the model's: the model may well+ // be capable, and the UI offers the test anyway with this caveat attached.+ reason: 'this runtime reports no capability list, so the claim is unverified',+ };+ }+ const missing = test.capabilities.filter((c) => !capabilities.includes(c));+ if (missing.length) {+ return {+ state: 'not-applicable',+ missing,+ reason: `no ${missing.join(' or ')} badge`,+ };+ }+ return { state: 'applicable', missing: [], reason: null };+}++/** Every test with its applicability for one model. Order follows the catalog. */+export const applicableTests = (capabilities) =>+ CAPABILITY_TESTS.map((test) => ({ test, ...applicabilityFor(test, capabilities) }));++// ---- keyword scoring --------------------------------------------------------++/**+ * The vision fixture's known contents.+ *+ * REQUIRED are the four objects any usable vision model must name; the pass+ * turns on those alone. BONUS is detail work — two colours and a number painted+ * on a sign — which separates "captions the scene" from "reads the frame". A+ * model that gets every required term passes with bonus misses recorded, so the+ * score says what it was good at rather than collapsing to one number.+ */+export const VISION_FIXTURE_KEYWORDS = Object.freeze({+ required: Object.freeze([+ Object.freeze({ id: 'bicycle', label: 'Bicycle', any: Object.freeze(['bicycle', 'bike']) }),+ Object.freeze({ id: 'bench', label: 'Bench', any: Object.freeze(['bench']) }),+ Object.freeze({ id: 'lamp', label: 'Street lamp', any: Object.freeze(['lamp', 'lamppost', 'lamp post', 'streetlight', 'street light']) }),+ Object.freeze({ id: 'dog', label: 'Dog', any: Object.freeze(['dog', 'puppy']) }),+ ]),+ bonus: Object.freeze([+ Object.freeze({ id: 'red-bicycle', label: 'Bicycle is red', any: Object.freeze(['red', 'crimson', 'scarlet']) }),+ Object.freeze({ id: 'blue-bench', label: 'Bench is blue', any: Object.freeze(['blue']) }),+ Object.freeze({ id: 'sign-number', label: 'Reads the number 3 on the sign', any: Object.freeze(['3', 'three']) }),+ ]),+});++// 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.+const phrasePattern = (phrase) =>+ escapeRegExp(String(phrase).trim()).replace(/\\?\s+/g, '\\s+');++const keywordRegExp = (entry) =>+ new RegExp(`(?<![\\p{L}\\p{N}_])(?:${entry.any.map(phrasePattern).join('|')})(?![\\p{L}\\p{N}_])`, 'giu');++// "there is no dog" must not score as a dog. Only the few words immediately+// before the match are considered: a negation further back than that belongs to+// a different clause, and treating it as one here would start losing real hits.+const NEGATED_BEFORE = /\b(?:no|not|without|isn'?t|aren'?t|lacks?|lacking|missing|absent|cannot|can'?t)\b[^.;!?]{0,24}$/i;++const isNegated = (text, matchIndex) => NEGATED_BEFORE.test(text.slice(Math.max(0, matchIndex - 60), matchIndex));++/**+ * Is one keyword entry present in the text, ignoring negated mentions?+ * @returns {{ hit: boolean, matched: string|null }}+ */+export function findKeyword(text, entry) {+ const haystack = String(text || '');+ const re = keywordRegExp(entry);+ for (const match of haystack.matchAll(re)) {+ if (!isNegated(haystack, match.index)) return { hit: true, matched: match[0] };+ }+ return { hit: false, matched: null };+}++/**+ * Score a description against a required/bonus keyword spec.+ *+ * The pass turns on REQUIRED alone. Bonus terms are reported either way — they+ * are what makes two passing models distinguishable — but a bonus miss can+ * never fail a run, or "bonus" would just be a second required tier.+ */+export function scoreKeywords(text, spec = VISION_FIXTURE_KEYWORDS) {+ const score = (entries) => (entries || []).map((entry) => ({+ id: entry.id,+ label: entry.label,+ any: [...entry.any],+ ...findKeyword(text, entry),+ }));++ const required = score(spec.required);+ const bonus = score(spec.bonus);+ const requiredHit = required.filter((r) => r.hit).length;+ const bonusHit = bonus.filter((b) => b.hit).length;+ const verdict = requiredHit === required.length+ ? 'passed'+ : (requiredHit >= Math.ceil(required.length / 2) ? 'partial' : 'failed');++ return {+ verdict,+ required,+ bonus,+ requiredHit,+ requiredTotal: required.length,+ bonusHit,+ bonusTotal: bonus.length,+ summary: `${requiredHit} of ${required.length} required`+ + (bonus.length ? `, ${bonusHit} of ${bonus.length} bonus` : ''),+ };+}++// ---- story-beat scoring -----------------------------------------------------++/**+ * The twelve beats, with the wordings a model actually uses for each.+ *+ * Matching is on the beat NAME, not on the prose: the test asks for named+ * headings, so a missing heading is a missing beat rather than a scoring+ * failure. Alternates cover the common synonyms ("Call to adventure" /+ * "The call"), not every possible paraphrase — a model that renames the+ * structure has not produced the structure that was asked for.+ */+export const HEROS_JOURNEY_BEATS = Object.freeze([+ Object.freeze({ id: 'ordinary-world', label: 'Ordinary world', any: Object.freeze(['ordinary world', 'everyday world', 'status quo', 'the known world']) }),+ Object.freeze({ id: 'call-to-adventure', label: 'Call to adventure', any: Object.freeze(['call to adventure', 'the call', 'inciting incident']) }),+ Object.freeze({ id: 'refusal', label: 'Refusal of the call', any: Object.freeze(['refusal of the call', 'refusal', 'refuses the call']) }),+ Object.freeze({ id: 'mentor', label: 'Meeting the mentor', any: Object.freeze(['meeting the mentor', 'meeting with the mentor', 'the mentor', 'supernatural aid']) }),+ Object.freeze({ id: 'threshold', label: 'Crossing the threshold', any: Object.freeze(['crossing the threshold', 'crossing the first threshold', 'the threshold']) }),+ Object.freeze({ id: 'tests-allies', label: 'Tests, allies, enemies', any: Object.freeze(['tests, allies', 'tests allies', 'allies and enemies', 'the road of trials', 'trials']) }),+ Object.freeze({ id: 'approach', label: 'Approach to the inmost cave', any: Object.freeze(['approach to the inmost cave', 'inmost cave', 'innermost cave', 'the approach']) }),+ Object.freeze({ id: 'ordeal', label: 'The ordeal', any: Object.freeze(['the ordeal', 'ordeal', 'the central crisis']) }),+ Object.freeze({ id: 'reward', label: 'The reward', any: Object.freeze(['the reward', 'reward', 'seizing the sword']) }),+ Object.freeze({ id: 'road-back', label: 'The road back', any: Object.freeze(['the road back', 'road back', 'the return journey']) }),+ Object.freeze({ id: 'resurrection', label: 'Resurrection', any: Object.freeze(['resurrection', 'the final test', 'climax']) }),+ Object.freeze({ id: 'elixir', label: 'Return with the elixir', any: Object.freeze(['return with the elixir', 'the elixir', 'elixir', 'freedom to live']) }),+]);++/**+ * Score an outline for beat coverage and ordering.+ *+ * Coverage is structure, NOT quality — it can only say the model held a+ * twelve-part shape across a long generation. Whether the outline is any good is+ * a reading job, which is why the runner always keeps the full text.+ *+ * @returns {{verdict:string, beats:Array, found:number, total:number, inOrder:boolean, summary:string}}+ */+export function scoreStoryBeats(text, beats = HEROS_JOURNEY_BEATS) {+ const haystack = String(text || '');+ const scored = beats.map((beat) => {+ const re = keywordRegExp(beat);+ const match = re.exec(haystack);+ return {+ id: beat.id,+ label: beat.label,+ hit: Boolean(match),+ // Where the beat first appears, used for the ordering check. `null` for a+ // miss — never -1, which would sort ahead of every real position.+ at: match ? match.index : null,+ };+ });++ const hits = scored.filter((b) => b.hit);+ // Ordering is judged on the beats that ARE present: an outline missing beat 3+ // is not out of order, it is short one beat, and conflating the two would+ // punish the same gap twice.+ const inOrder = hits.every((beat, i) => i === 0 || beat.at > hits[i - 1].at);+ const found = hits.length;+ const verdict = found === beats.length && inOrder+ ? 'passed'+ : (found >= Math.ceil(beats.length * 0.66) ? 'partial' : 'failed');++ return {+ verdict,+ beats: scored,+ found,+ total: beats.length,+ inOrder,+ summary: `${found} of ${beats.length} beats${found > 1 && !inOrder ? ' — out of order' : ''}`,+ };+}++// ---- sandbox-repair scoring -------------------------------------------------++/**+ * Turn the observed facts of a sandbox run into a verdict.+ *+ * Every input is read from DISK after the agent stops — never from what the+ * agent said it did. A model that reports success without touching the file+ * scores nothing.+ *+ * @param {object} facts+ * @param {boolean} facts.moduleChanged the module under repair differs from the fixture+ * @param {boolean} facts.fixturesIntact the test and data files are byte-identical to the fixture+ * @param {boolean} facts.testsPass the sandbox test command exited 0+ * @param {number} facts.toolCalls tool calls observed in the agent stream+ */+export function scoreSandboxRepair({ moduleChanged, fixturesIntact, testsPass, toolCalls = 0 }) {+ const checks = [+ { id: 'module-written', label: 'Wrote a fix to the module on disk', ok: Boolean(moduleChanged) },+ { id: 'fixtures-intact', label: 'Left the test and data files untouched', ok: Boolean(fixturesIntact) },+ { id: 'tests-pass', label: 'The sandbox test command exits 0', ok: Boolean(testsPass) },+ ];+ // Editing the test into submission is the one way to "pass" without fixing+ // anything, so it fails outright rather than scoring partial — a partial there+ // would read as progress toward a solution it is moving away from.+ const verdict = !fixturesIntact+ ? 'failed'+ : (testsPass ? 'passed' : (moduleChanged ? 'partial' : 'failed'));+ const summary = verdict === 'passed'+ ? `fixed in ${toolCalls} tool call${toolCalls === 1 ? '' : 's'}`+ : (!fixturesIntact+ ? 'edited the test or data file instead of the module'+ : (moduleChanged ? 'wrote a fix, but the test still fails' : 'never wrote a fix'));++ return { verdict, checks, summary, toolCalls };+}++/** Roll several test verdicts into the one a model's row shows. */+export function rollUpVerdict(verdicts) {+ const list = (verdicts || []).filter((v) => TEST_VERDICTS.includes(v));+ if (!list.length) return null;+ if (list.includes('failed')) return 'failed';+ if (list.includes('partial')) return 'partial';+ return 'passed';+}+diff --git a/server/lib/modelCapabilityTests.test.js b/server/lib/modelCapabilityTests.test.jsnew file mode 100644index 0000000000..f3b3fc0296--- /dev/null+++ b/server/lib/modelCapabilityTests.test.js@@ -0,0 +1,161 @@+import { describe, expect, it } from 'vitest';+import {+ CAPABILITY_TESTS,+ HEROS_JOURNEY_BEATS,+ VISION_FIXTURE_KEYWORDS,+ applicabilityFor,+ applicableTests,+ findKeyword,+ getCapabilityTest,+ rollUpVerdict,+ scoreKeywords,+ scoreSandboxRepair,+ scoreStoryBeats,+} from './modelCapabilityTests.js';++const visionTest = getCapabilityTest('image-analysis');+const sandboxTest = getCapabilityTest('sandbox-repair');++describe('applicabilityFor', () => {+ it('applies a test only where the model claims the capability', () => {+ expect(applicabilityFor(visionTest, ['chat', 'vision']).state).toBe('applicable');+ });++ it('reports an unclaimed capability as not-applicable, never as a failure', () => {+ const result = applicabilityFor(visionTest, ['chat', 'tools']);+ expect(result.state).toBe('not-applicable');+ expect(result.missing).toEqual(['vision']);+ expect(result.reason).toContain('vision');+ });++ it('separates "the runtime said nothing" from "the model claims nothing"', () => {+ // `null` — a bare endpoint that reports ids only. The claim is unverified,+ // so the test stays on offer rather than being hidden.+ expect(applicabilityFor(visionTest, null).state).toBe('unknown');+ // `[]` — a runtime that answered. That IS an answer: no vision badge.+ expect(applicabilityFor(visionTest, []).state).toBe('not-applicable');+ });++ it('never lets a preferred-but-missing capability block a test', () => {+ // sandbox-repair requires `tools` and merely prefers `code`.+ expect(sandboxTest.prefers).toContain('code');+ expect(applicabilityFor(sandboxTest, ['chat', 'tools']).state).toBe('applicable');+ });++ it('covers every shipped test for one model', () => {+ expect(applicableTests(['chat', 'tools', 'vision']).map((t) => t.state))+ .toEqual(CAPABILITY_TESTS.map(() => 'applicable'));+ });+});++describe('scoreKeywords', () => {+ const answer = 'A red bicycle leans by a blue bench. A dog sits under it, beside a lit street lamp, and the sign reads 3.';++ it('passes when every required term is present and counts the bonus separately', () => {+ const scored = scoreKeywords(answer, VISION_FIXTURE_KEYWORDS);+ expect(scored.verdict).toBe('passed');+ expect(scored.requiredHit).toBe(scored.requiredTotal);+ expect(scored.bonusHit).toBe(scored.bonusTotal);+ });++ it('still passes when only bonus terms are missed — bonus can never fail a run', () => {+ const scored = scoreKeywords('A bicycle, a bench, a dog and a lamp.', VISION_FIXTURE_KEYWORDS);+ expect(scored.verdict).toBe('passed');+ expect(scored.bonusHit).toBe(0);+ expect(scored.summary).toContain('0 of 3 bonus');+ });++ it('fails once most required terms are missing', () => {+ expect(scoreKeywords('Some kind of outdoor scene at night.', VISION_FIXTURE_KEYWORDS).verdict).toBe('failed');+ });++ it('does not credit a negated mention', () => {+ expect(findKeyword('There is no dog in the picture.', { any: ['dog'] }).hit).toBe(false);+ expect(findKeyword('A dog sits there.', { any: ['dog'] }).hit).toBe(true);+ });++ it('matches on word boundaries, so a substring is not a hit', () => {+ expect(findKeyword('A bikeshed stands there.', { any: ['bike'] }).hit).toBe(false);+ expect(findKeyword('rendered at 1024x300', { any: ['3'] }).hit).toBe(false);+ expect(findKeyword('the sign shows a 3', { any: ['3'] }).hit).toBe(true);+ });++ it('tolerates a phrase broken across a wrapped line', () => {+ expect(findKeyword('beside a lamp\n post at the kerb', { any: ['lamp post'] }).hit).toBe(true);+ });+});++describe('scoreStoryBeats', () => {+ const outline = HEROS_JOURNEY_BEATS.map((b, i) => `${i + 1}. ${b.label}\nSomething happens.`).join('\n\n');++ it('passes a complete, in-order outline', () => {+ const scored = scoreStoryBeats(outline);+ expect(scored.verdict).toBe('passed');+ expect(scored.found).toBe(HEROS_JOURNEY_BEATS.length);+ expect(scored.inOrder).toBe(true);+ });++ it('reports a short outline as partial rather than failed', () => {+ const short = HEROS_JOURNEY_BEATS.slice(0, 9).map((b) => b.label).join('\n');+ const scored = scoreStoryBeats(short);+ expect(scored.verdict).toBe('partial');+ expect(scored.found).toBe(9);+ });++ it('judges ordering only over the beats that are present', () => {+ // Beat 3 missing, everything else in sequence: short one beat, not jumbled.+ const gapped = HEROS_JOURNEY_BEATS.filter((b) => b.id !== 'refusal').map((b) => b.label).join('\n');+ expect(scoreStoryBeats(gapped).inOrder).toBe(true);+ });++ it('flags a genuinely reordered outline', () => {+ const reversed = [...HEROS_JOURNEY_BEATS].reverse().map((b) => b.label).join('\n');+ const scored = scoreStoryBeats(reversed);+ expect(scored.inOrder).toBe(false);+ expect(scored.summary).toContain('out of order');+ });++ it('marks each beat found or missing by id', () => {+ const scored = scoreStoryBeats('Ordinary world. Then the ordeal.');+ expect(scored.beats.find((b) => b.id === 'ordinary-world').hit).toBe(true);+ expect(scored.beats.find((b) => b.id === 'elixir').hit).toBe(false);+ // A miss records no position — never -1, which would sort ahead of a real one.+ expect(scored.beats.find((b) => b.id === 'elixir').at).toBeNull();+ });+});++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');+ });++ it('fails a model that edited the test instead of the module, even when tests pass', () => {+ const scored = scoreSandboxRepair({ moduleChanged: true, fixturesIntact: false, testsPass: true, toolCalls: 4 });+ expect(scored.verdict).toBe('failed');+ expect(scored.summary).toContain('edited the test');+ });++ it('records a written-but-still-failing attempt as partial', () => {+ expect(scoreSandboxRepair({ moduleChanged: true, fixturesIntact: true, testsPass: false }).verdict).toBe('partial');+ });++ it('fails a model that never wrote anything', () => {+ const scored = scoreSandboxRepair({ moduleChanged: false, fixturesIntact: true, testsPass: false });+ expect(scored.verdict).toBe('failed');+ expect(scored.summary).toContain('never wrote a fix');+ });+});++describe('rollUpVerdict', () => {+ it('takes the worst verdict recorded', () => {+ expect(rollUpVerdict(['passed', 'partial', 'failed'])).toBe('failed');+ expect(rollUpVerdict(['passed', 'partial'])).toBe('partial');+ expect(rollUpVerdict(['passed', 'passed'])).toBe('passed');+ });++ it('is null when nothing has been run — never "passed" by default', () => {+ expect(rollUpVerdict([])).toBeNull();+ expect(rollUpVerdict([undefined, null])).toBeNull();+ });+});+diff --git a/server/lib/openAiChatStream.js b/server/lib/openAiChatStream.jsindex 35b7a77fc8..52c497cc56 100644--- a/server/lib/openAiChatStream.js+++ b/server/lib/openAiChatStream.js@@ -134,11 +134,26 @@ export function resolvePartialOutput({ output = '', reasoning = '' }) {return '';}-export function buildMessages({ systemPrompt, prompt }) {+export function buildMessages({ systemPrompt, prompt, images }) {const system = String(systemPrompt || '').trim();+ // A vision request is the same chat call with a multi-part user `content`,+ // in the OpenAI wire shape. Empty/absent `images` keeps the plain string form+ // rather than wrapping the prompt in a one-element array — several local+ // daemons accept only the string shape on a text-only call, so the wrapper is+ // not free.+ //+ // NOTE: this builder feeds BOTH transports. Ollama's native `/api/chat`+ // (`streamOllamaChat`) wants `{content: string, images: [bare base64]}`, not+ // `image_url` parts, so `toOllamaMessages` below converts on the way out.+ // Producing a payload one consumer cannot read is how images end up silently+ // dropped with no error.+ const parts = (Array.isArray(images) ? images : []).filter((url) => typeof url === 'string' && url);+ const content = parts.length+ ? [...parts.map((url) => ({ type: 'image_url', image_url: { url } })), { type: 'text', text: prompt }]+ : prompt;return [...(system ? [{ role: 'system', content: system }] : []),- { role: 'user', content: prompt },+ { role: 'user', content },];}@@ -194,7 +209,7 @@ export async function streamOpenAiChat({signal,body: JSON.stringify({model,- messages,+ messages: toOllamaMessages(messages),stream: true,temperature,max_tokens: maxTokens,@@ -332,6 +347,30 @@ export async function streamOpenAiChat({* @returns {Promise<string>} visible content, or reasoning when content is* absent; an interrupted stream throws with `.partialOutput`.*/+/**+ * OpenAI-shaped messages → Ollama's native `/api/chat` shape.+ *+ * The two differ on exactly one thing: an image rides as an `image_url` content+ * PART on the OpenAI wire and as a sibling `images: [bare base64]` array on+ * Ollama's, with the text back in `content`. `buildMessages` produces the+ * OpenAI shape for both transports, so without this the native path posts a+ * content array Ollama does not read and the images vanish with no error.+ *+ * The `data:` wrapper is stripped because Ollama wants raw base64; a text-only+ * message passes through untouched.+ */+export function toOllamaMessages(messages) {+ return (messages || []).map((message) => {+ if (!Array.isArray(message?.content)) return message;+ const text = message.content.filter((part) => part?.type === 'text').map((part) => part.text || '').join('\n');+ const images = message.content+ .filter((part) => part?.type === 'image_url')+ .map((part) => String(part?.image_url?.url || '').replace(/^data:[^;]+;base64,/, ''))+ .filter(Boolean);+ return { ...message, content: text, ...(images.length ? { images } : {}) };+ });+}+export async function streamOllamaChat({endpoint,apiKey,diff --git a/server/lib/opencodeStream.js b/server/lib/opencodeStream.jsnew file mode 100644index 0000000000..ff7703c595--- /dev/null+++ b/server/lib/opencodeStream.js@@ -0,0 +1,121 @@+/**+ * OpenCode's `--format json` event stream — one parser, shared.+ *+ * Two PortOS features drive an OpenCode agent and read its stdout: the runtime+ * agent-task benchmark (`services/localModelAgentBenchmark.js`, which wants+ * chars and token counts) and the capability test suite+ * (`services/modelCapabilityTests.js`, which wants a readable transcript). They+ * aggregate different things, but they are reading the SAME envelope — and that+ * envelope has already changed shape once upstream.+ *+ * So the envelope lives here and the aggregations live with their callers. A+ * second parser is how the two end up reporting different tool-call counts for+ * the same run, and how a future OpenCode change gets fixed in one file and+ * missed in the other.+ *+ * Pure: no I/O, no spawning. `services/opencodeTask.js` is the runner that+ * produces the stream this module reads.+ */++/**+ * OpenCode has used a flat `{type:'text', part:{text}}` envelope and a nested+ * `{type:'message.part.updated', properties:{part:{…}}}` one. Both are accepted;+ * anything else yields no part, and its frame renders as nothing rather than as+ * noise.+ */+export const eventPart = (event) => event?.part || event?.properties?.part || event?.data?.part || null;++/** Part types that mean "the agent called a tool", across envelope versions. */+export const TOOL_PART_TYPES = new Set(['tool', 'tool_use', 'tool-call']);++export const isToolEvent = (event) => TOOL_PART_TYPES.has(eventPart(event)?.type || event?.type)+ || event?.type === 'tool_use';++/** The assistant text a frame carries, or '' when it carries none. */+export function eventText(event) {+ const part = eventPart(event);+ if ((part?.type || event?.type) !== 'text') return '';+ const text = typeof part?.text === 'string' ? part.text : event?.text;+ return typeof text === 'string' ? text : '';+}++/** One stdout line → a parsed frame, or `null` for a blank or unparsable line. */+export function parseAgentLine(line) {+ const trimmed = String(line || '').trim();+ if (!trimmed) return null;+ try { return JSON.parse(trimmed); } catch { return null; }+}++/** Every parsable frame in a whole stdout buffer, in order. */+export function parseAgentEvents(output) {+ return String(output || '').split(/\r?\n/).map(parseAgentLine).filter(Boolean);+}++const firstString = (...values) => values.find((v) => typeof v === 'string' && v.trim()) || '';++/**+ * Render one frame as a transcript line a person can read while the agent works.+ *+ * @returns {{ line: string, toolCall: boolean }|null} `null` for a frame with+ * nothing worth showing — a heartbeat, an ack, an unknown envelope.+ */+export function formatAgentEvent(event) {+ const part = eventPart(event);+ const type = part?.type || event?.type;++ if (isToolEvent(event)) {+ const name = firstString(part?.tool, part?.name, event?.tool, event?.name) || 'tool';+ // The one detail worth showing beside a tool name is what it acted ON — a+ // path or a command. Everything else is argument noise at transcript width.+ const input = part?.input || part?.args || part?.state?.input || event?.input || {};+ const target = firstString(input.filePath, input.path, input.command);+ return { line: `● ${name}${target ? ` ${target}` : ''}`, toolCall: true };+ }++ if (type === 'text') {+ const text = eventText(event).trim();+ return text ? { line: text, toolCall: false } : null;+ }++ if (type === 'error' || event?.error) {+ const message = firstString(event?.error?.message, event?.error, part?.error, event?.message);+ return message ? { line: `✖ ${message}`, toolCall: false } : null;+ }++ return null;+}++/**+ * Task evidence from a whole stream: how much the assistant actually said, how+ * many tools it called, and the token counts OpenCode exposed.+ *+ * Tool ARGUMENTS are deliberately not counted as answer text — a benchmark that+ * counted them would reward a model for verbose tool calls.+ */+export function summarizeOpenCodeEvents(output) {+ let assistantText = '';+ let toolCalls = 0;+ let outputTokens = 0;+ let hasOutputTokens = false;++ for (const event of parseAgentEvents(output)) {+ assistantText += eventText(event);+ if (isToolEvent(event)) toolCalls += 1;++ const part = eventPart(event);+ const candidate = part?.tokens?.output ?? event?.tokens?.output+ ?? event?.usage?.completion_tokens ?? event?.usage?.output_tokens;+ if (typeof candidate === 'number' && Number.isFinite(candidate) && candidate >= 0) {+ outputTokens += candidate;+ hasOutputTokens = true;+ }+ }++ return {+ assistantChars: assistantText.length,+ toolCalls,+ // `null` = OpenCode reported no usage at all — NOT zero, which a reader+ // would take for a measured standstill.+ outputTokens: hasOutputTokens ? outputTokens : null,+ };+}diff --git a/server/lib/opencodeStream.test.js b/server/lib/opencodeStream.test.jsnew file mode 100644index 0000000000..b75c69370e--- /dev/null+++ b/server/lib/opencodeStream.test.js@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest';+import {+ eventText,+ formatAgentEvent,+ isToolEvent,+ parseAgentEvents,+ parseAgentLine,+ summarizeOpenCodeEvents,+} from './opencodeStream.js';++describe('formatAgentEvent', () => {+ it('renders a tool call with the path it acted on', () => {+ expect(formatAgentEvent({ type: 'tool', part: { type: 'tool', tool: 'read', input: { filePath: 'cart-totals.mjs' } } }))+ .toEqual({ line: '● read cart-totals.mjs', toolCall: true });+ });++ it('accepts the nested envelope OpenCode also emits', () => {+ expect(formatAgentEvent({ type: 'message.part.updated', properties: { part: { type: 'text', text: 'Fixing the fallback.' } } }))+ .toEqual({ line: 'Fixing the fallback.', toolCall: false });+ });++ it('drops a frame with nothing a reader would want', () => {+ expect(formatAgentEvent({ type: 'heartbeat' })).toBeNull();+ expect(formatAgentEvent({ type: 'text', part: { type: 'text', text: ' ' } })).toBeNull();+ });+});++describe('parsing the stream', () => {+ const stream = [+ JSON.stringify({ type: 'tool', part: { type: 'tool', tool: 'read', input: { filePath: 'a.mjs' } } }),+ '',+ 'not json at all',+ JSON.stringify({ type: 'text', part: { type: 'text', text: 'Thinking.' } }),+ JSON.stringify({ type: 'tool', part: { type: 'tool', tool: 'bash', input: { command: 'node a.test.mjs' } } }),+ ].join('\n');++ it('skips blank and unparsable lines rather than throwing on them', () => {+ expect(parseAgentLine(' ')).toBeNull();+ expect(parseAgentLine('not json at all')).toBeNull();+ expect(parseAgentEvents(stream)).toHaveLength(3);+ });++ it('renders the frames a reader would want, in order', () => {+ expect(parseAgentEvents(stream).map(formatAgentEvent).filter(Boolean).map((r) => r.line))+ .toEqual(['● read a.mjs', 'Thinking.', '● bash node a.test.mjs']);+ });++ it('reads assistant text without counting tool arguments as answer text', () => {+ expect(eventText({ type: 'text', part: { type: 'text', text: 'hello' } })).toBe('hello');+ expect(eventText({ type: 'tool', part: { type: 'tool', tool: 'bash', input: 'a long command' } })).toBe('');+ });++ it('recognises a tool call across every envelope version', () => {+ expect(isToolEvent({ type: 'tool_use', part: { type: 'tool' } })).toBe(true);+ expect(isToolEvent({ type: 'message.part.updated', properties: { part: { type: 'tool-call' } } })).toBe(true);+ expect(isToolEvent({ type: 'text', part: { type: 'text', text: 'x' } })).toBe(false);+ });++ it('returns an empty summary rather than throwing on no output', () => {+ expect(summarizeOpenCodeEvents('')).toEqual({ assistantChars: 0, toolCalls: 0, outputTokens: null });+ expect(summarizeOpenCodeEvents(undefined)).toEqual({ assistantChars: 0, toolCalls: 0, outputTokens: null });+ });++ it('keeps "no usage reported" distinct from a measured zero', () => {+ expect(summarizeOpenCodeEvents(JSON.stringify({ type: 'text', text: 'done' })).outputTokens).toBeNull();+ expect(summarizeOpenCodeEvents(JSON.stringify({ type: 'step_finish', part: { tokens: { output: 0 } } })).outputTokens).toBe(0);+ });+});diff --git a/server/lib/textUtils.js b/server/lib/textUtils.jsindex 1f80b00049..5a99a50935 100644--- a/server/lib/textUtils.js+++ b/server/lib/textUtils.js@@ -24,3 +24,15 @@ export function countWords(text) {const matches = text.trim().match(/\S+/g);return matches ? matches.length : 0;}++/**+ * Escape a string for literal use inside a RegExp.+ *+ * Exported because this was hand-rolled privately in seven other modules+ * (markedSection, loraTriggers, loraDataset, scenePrompt, assetMounts,+ * editorial/cutApplier, editorial/proseTics) — none of them exported it, so the+ * eighth caller copied it too. This is the one to import.+ */+export function escapeRegExp(value) {+ return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 44124bee5b..039b016be7 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -28,6 +28,9 @@ import {localLlmAgentBenchmarkSchema,localLlmAssessmentDeleteSchema,localLlmAssessmentSweepSchema,+ localLlmCapabilityTestSchema,+ localLlmCapabilityTestRunSchema,+ localLlmCapabilityTestDeleteSchema,localLlmLlamaServerStartSchema,localLlmLmStudioServiceSchema,localLlmMtplxStartSchema,@@ -56,6 +59,8 @@ import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayimport { getAssessmentReport, runAssessment, deleteAssessment } from '../services/localModelAssessments.js'import { startSweep, getSweepStatus, cancelSweep } from '../services/localModelAssessmentSweep.js'import { runOpenCodeAgentBenchmark } from '../services/localModelAgentBenchmark.js'+import { getCapabilityTestReport, getCapabilityTestResult, runCapabilityTest } from '../services/modelCapabilityTests.js'+import { deleteResult as deleteCapabilityTestResult } from '../services/modelCapabilityTestStore.js'import { listUserModels } from '../services/audioModels.js'import { ENGINES } from '../services/pipeline/musicGen.js'import { abortSignalFromResponse } from '../lib/requestAbort.js'@@ -548,6 +553,65 @@ router.post('/assessments/delete', asyncHandler(async (req, res) => {res.json({ success: true, backend, modelId, tuningKey })}))+// === 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.+//+// 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 from+// one deliberate click whose gate names the runtime, model and tests first.+// There is deliberately no sweep and no scheduled entry point here — a+// capability run is a manual act.++// GET /api/local-llm/capability-tests — what each installed model claims, which+// tests apply, and what each one proved last time. Zero LLM calls.+router.get('/capability-tests', asyncHandler(async (_req, res) => {+ res.json(await getCapabilityTestReport())+}))++// POST /api/local-llm/capability-tests/run — run ONE test against ONE model.+// Long-running (a sandbox repair is an agent loop), so the client's abort signal+// is threaded through to stop mid-run on disconnect.+router.post('/capability-tests/run', asyncHandler(async (req, res) => {+ const { backend, modelId, testId } = validateRequest(localLlmCapabilityTestRunSchema, req.body)+ const io = req.app.get('io')+ // Same `localLlm:progress` channel every long local-LLM operation uses. The+ // `scope: 'capability-test'` field plus backend/model/test is what lets a+ // listener tell these frames from a model pull streaming on the same event —+ // and the `output` frames are what render the agent transcript live.+ const onProgress = (frame) => io?.emit('localLlm:progress', frame)+ res.json(await runCapabilityTest({+ backend, modelId, testId, onProgress, signal: abortSignalFromResponse(res),+ }))+}))++// GET /api/local-llm/capability-tests/result — ONE stored result in full,+// including the model's output and the agent transcript.+//+// Split from the report on purpose: those two fields are the bulk of a record+// and are read only when the drawer opens one pairing, so the report ships+// summaries and this fills in the rest. Query params rather than a path because+// a model id is not one — it carries `/` and `:` (`hf.co/org/repo:Q4_K_M`).+router.get('/capability-tests/result', asyncHandler(async (req, res) => {+ const { backend, modelId, testId } = validateRequest(localLlmCapabilityTestSchema, req.query)+ const result = await getCapabilityTestResult(backend, modelId, testId)+ if (!result) throw new ServerError('No capability test result recorded for that model', { status: 404, context: { backend, modelId, testId } })+ res.json(result)+}))++// POST /api/local-llm/capability-tests/delete — drop one recorded result.+// 404s when nothing was removed rather than reporting a phantom success.+router.post('/capability-tests/delete', asyncHandler(async (req, res) => {+ const { backend, modelId, testId } = validateRequest(localLlmCapabilityTestDeleteSchema, req.body)+ const result = await deleteCapabilityTestResult(backend, modelId, testId)+ if (!result.deleted) throw new ServerError('No capability test result recorded for that model', { status: 404, context: { backend, modelId, testId } })+ res.json({ success: true, backend, modelId, testId })+}))+// === llama-server (DFlash 2 / Speculative Decoding) ==========================// GET /api/local-llm/llama-server/status — binary availability, process state,// logs, and the curated target/drafter presets with each GGUF's on-disk state.diff --git a/server/services/backup.js b/server/services/backup.jsindex 5e0112c7d9..ff5d0c4740 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -80,6 +80,10 @@ export const DEFAULT_EXCLUDES = [// model.glb, which IS backed up), and at ~1 GB per render it would otherwise// dominate every snapshot. Overridable, because it is the only copy of the// discarded detail and someone archiving finished work may want it.+ // Anchored, like every entry here. Capability-test sandboxes are throwaway+ // copies of a fixture that ships in the repo — restoring one would restore a+ // half-finished agent edit, which is worse than not having it.+ { path: '/model-tests/sandboxes/', reason: 'Capability-test agent sandboxes — throwaway working copies of a repo fixture, recreated per run', overridable: false },{ path: '/image-to-3d/*/model.obj', reason: 'TRELLIS.2 full-resolution mesh sidecar — ~1 GB per render, regenerable by re-rendering at the same seed. The exported model.glb and keyed source ARE backed up.', overridable: true },// Anchored, like every entry here. Not overridable: these are another// machine's conditioning bytes, staged for one federated render and swept ondiff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex 8ef6dd1dce..e90a0f826e 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -94,6 +94,7 @@ export const CATEGORIES = {'media-sketches': { label: 'Media Sketches', description: 'Saved sketch canvases used as render inputs', archivable: true, deletable: false },'messages': { label: 'Messages', description: 'Email and messaging data', archivable: true, deletable: true, purgeScope: 'category' },'model-personality': { label: 'Model Personality', description: 'Model personality probe results and settings', archivable: true, deletable: false },+ 'model-tests': { label: 'Model Capability Tests', description: 'Throwaway agent sandboxes from the capability test suite — recreated per run, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },'music': { label: 'Music', description: 'Uploaded and generated background tracks', archivable: true, deletable: false },'openclaw': { label: 'OpenClaw', description: 'OpenClaw integration config', archivable: true, deletable: false },'pipeline-comparative-rank': { label: 'Comparative Rank', description: 'Cached comparative issue rankings — re-running them costs LLM calls', archivable: true, deletable: false },diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex 2ba6eb6a61..03b989e82e 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -577,8 +577,20 @@ const OLLAMA_CAPABILITY_BADGES = {thinking: 'reasoning'}-function ollamaBadgeCapabilities(rawCapabilities) {- return (Array.isArray(rawCapabilities) ? rawCapabilities : [])+/**+ * Ollama's reported capabilities → the badge vocabulary.+ *+ * `null` for a NON-ARRAY input, which is what `/api/tags` gives: that listing+ * carries no capability flags at all, so nothing was reported and nothing is+ * known. Returning `[]` there would collapse "not probed" into "claims+ * nothing" — the sentinel mistake root CLAUDE.md forbids — which rendered an+ * empty badge row on the install catalog and made every capability test look+ * inapplicable. `/api/show` is what actually knows; an EMPTY array from it is a+ * real answer and stays `[]`.+ */+export function ollamaBadgeCapabilities(rawCapabilities) {+ if (!Array.isArray(rawCapabilities)) return null+ return rawCapabilities.map((c) => OLLAMA_CAPABILITY_BADGES[String(c).toLowerCase()]).filter(Boolean)}diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.jsindex 046592e7f7..bc1300f811 100644--- a/server/services/localLlm.test.js+++ b/server/services/localLlm.test.js@@ -633,8 +633,12 @@ describe('localLlm', () => {expect(models.find((m) => m.id === 'qwen3.6:35b').capabilities.sort()).toEqual(['chat', 'reasoning', 'tools', 'vision']);expect(models.find((m) => m.id === 'nomic-embed-text').capabilities).toEqual(['embeddings']);- // No reported capabilities → no guessed badges (unlike the vision id heuristic).- expect(models.find((m) => m.id === 'legacy-model').capabilities).toEqual([]);+ // No reported capabilities → `null`, meaning NOT PROBED — /api/tags carries+ // no capability flags at all, so nothing was reported and nothing is known.+ // `[]` would say "this model claims nothing", which is a different and+ // untrue claim: it renders an empty badge row and makes every capability+ // test look inapplicable. Still no guessing (unlike the vision id heuristic).+ expect(models.find((m) => m.id === 'legacy-model').capabilities).toBeNull();});it('derives LM Studio badges from the native `type` field plus the shared tool-use id heuristic', async () => {diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.jsindex 5f3c0e3d39..c5b420c5fa 100644--- a/server/services/localLlmPlayground.js+++ b/server/services/localLlmPlayground.js@@ -111,7 +111,7 @@ async function resolveLocalProvider(backend) {return provider;}-async function streamChatCompletion({ provider, backend, modelId, prompt, systemPrompt, temperature, maxTokens, extraBody = {}, signal, onChunk, onStats, nativeOllamaUsage = false }) {+async function streamChatCompletion({ provider, backend, modelId, prompt, systemPrompt, images, temperature, maxTokens, extraBody = {}, signal, onChunk, onStats, nativeOllamaUsage = false }) {if (backend === 'ollama') {const ready = await ensureOllamaProviderReady(provider).catch((err) => ({ success: false, error: err.message }));if (!ready.success) {@@ -132,7 +132,7 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, systemendpoint: provider.endpoint,apiKey: provider.apiKey,model: modelId,- messages: buildMessages({ systemPrompt, prompt }),+ messages: buildMessages({ systemPrompt, prompt, images }),temperature,maxTokens,// The caller's knobs win over the provider default, so a caller measuring a@@ -154,6 +154,10 @@ export async function runLocalLlmTest({modelId,prompt,systemPrompt = '',+ // Base64 data URLs sent alongside the prompt as `image_url` parts — how the+ // vision capability test asks a model to look at the fixture. Empty for every+ // text-only caller, which keeps the plain string `content` shape.+ images,temperature = 0.3,maxTokens = 1000,timeoutMs = 300000,@@ -210,6 +214,7 @@ export async function runLocalLlmTest({modelId,prompt,systemPrompt,+ images,temperature,maxTokens,extraBody,@@ -296,6 +301,8 @@ export async function runEndpointLlmTest({modelId,prompt,systemPrompt = '',+ // See `runLocalLlmTest` — base64 data URLs for a vision request.+ images,temperature = 0.3,maxTokens = 1000,timeoutMs = 300000,@@ -315,7 +322,7 @@ export async function runEndpointLlmTest({endpoint,apiKey,model: modelId,- messages: buildMessages({ systemPrompt, prompt }),+ messages: buildMessages({ systemPrompt, prompt, images }),temperature,maxTokens,extraBody,diff --git a/server/services/localModelAgentBenchmark.js b/server/services/localModelAgentBenchmark.jsindex 23ea06d68a..7f94e04880 100644--- a/server/services/localModelAgentBenchmark.js+++ b/server/services/localModelAgentBenchmark.js@@ -21,6 +21,10 @@ 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';+// 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';export const OPENCODE_AGENT_BENCHMARK_TARGETS = Object.freeze({@@ -65,48 +69,9 @@ const targetFor = (backend, modelId) => {return target;};-const jsonLines = (output) => String(output || '').split(/\r?\n/).map((line) => {- const trimmed = line.trim();- if (!trimmed) return null;- try { return JSON.parse(trimmed); }- catch { return null; }-}).filter(Boolean);--/**- * Extract task evidence from OpenCode's `--format json` event stream.- * OpenCode has used both `type: 'text', part: { text }` and- * `type: 'message.part.updated', properties: { part: { type: 'text', text } }`- * shapes, so the parser accepts both without counting tool arguments as answer- * text. It is pure and exported for fixture-driven tests.- */-export function summarizeOpenCodeEvents(output) {- let assistantText = '';- let toolCalls = 0;- let outputTokens = 0;- let hasOutputTokens = false;-- for (const event of jsonLines(output)) {- const part = event?.part || event?.properties?.part || event?.data?.part || null;- const partType = part?.type || event?.type;- if (partType === 'text') {- const text = typeof part?.text === 'string' ? part.text : event?.text;- if (typeof text === 'string') assistantText += text;- }- if (partType === 'tool' || partType === 'tool_use' || partType === 'tool-call' || event?.type === 'tool_use') toolCalls += 1;-- const candidate = part?.tokens?.output ?? event?.tokens?.output ?? event?.usage?.completion_tokens ?? event?.usage?.output_tokens;- if (typeof candidate === 'number' && Number.isFinite(candidate) && candidate >= 0) {- outputTokens += candidate;- hasOutputTokens = true;- }- }-- return {- assistantChars: assistantText.length,- toolCalls,- outputTokens: hasOutputTokens ? outputTokens : null,- };-}+// Re-exported so this module's own callers and suite keep one import site while+// the envelope itself lives in `lib/opencodeStream.js`.+export { summarizeOpenCodeEvents };const validateProvider = (provider, target) => {if (!provider) {diff --git a/server/services/modelCapabilityTestStore.js b/server/services/modelCapabilityTestStore.jsnew file mode 100644index 0000000000..75a568cc31--- /dev/null+++ b/server/services/modelCapabilityTestStore.js@@ -0,0 +1,152 @@+/**+ * Capability test results — the durable store.+ *+ * Split from `modelCapabilityTests.js` for the same two reasons the assessment+ * store is split from its runner:+ *+ * 1. **AI Provider Usage Policy** (root CLAUDE.md). Nothing in this file can+ * reach a provider, so a read path that imports it is safe by construction+ * rather than by review.+ * 2. **No import cycle** — the report builder needs stored results, and the+ * runner needs to write them.+ *+ * ## Storage (docs/STORAGE.md)+ *+ * `file-primary`, **machine-local — never federated.** A capability result+ * describes what a model did on THIS machine, through THIS runtime, at the+ * quantization installed here. A peer inheriting "passed" for a model it runs at+ * a different quant would be told something untrue about its own install. No+ * sync cursor, no tombstone, no `schemaVersions.js` entry — the same rule+ * `localModelAssessmentStore.js` follows and for the same reason.+ *+ * ## Privacy+ *+ * A record holds the model's own output and, for the sandbox test, the agent+ * transcript — because seeing the output IS the feature. Both are produced+ * inside a throwaway sandbox from a fixed fixture, so neither carries user data,+ * and neither ever leaves this machine. The recorded environment stays coarse+ * (platform, arch, CPU count, total memory) exactly as assessments do: no+ * hostname, no username, no paths.+ */++import { join } from 'path';+import { rename } from 'fs/promises';+import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';+import { captureDurableEnvironment } from './localModelAssessmentStore.js';++const storeDir = () => join(PATHS.data, 'local-llm');+const storeFile = () => join(storeDir(), 'capability-tests.json');++// Storage-layout version. Bump only when a reader must branch on the shape.+const STORE_SCHEMA_VERSION = 1;++/**+ * Caps on what one record keeps.+ *+ * Generous enough that a real answer is never clipped — a twelve-beat outline+ * runs ~5k characters and a repair transcript ~20k — but bounded, because the+ * whole store is one JSON file rewritten on every save. A runaway model that+ * emits a megabyte must not make the file unreadable for every other result.+ */+export const MAX_OUTPUT_CHARS = 24000;+export const MAX_TRANSCRIPT_CHARS = 80000;++/**+ * Trim to a cap, keeping the end the reader needs.+ *+ * `head` keeps the beginning (a model's answer starts with its answer); `tail`+ * keeps the end (a transcript's verdict is its last lines). Either way the+ * elision is MARKED — silently returning a shortened string would let a+ * truncated outline read as a model that stopped early.+ */+export function clampText(text, limit, keep = 'head') {+ const value = String(text ?? '');+ if (value.length <= limit) return value;+ const dropped = value.length - limit;+ const note = `\n\n…[${dropped.toLocaleString('en-US')} characters trimmed by PortOS]\n\n`;+ return keep === 'tail'+ ? note.trimStart() + value.slice(-limit)+ : value.slice(0, limit) + note.trimEnd();+}++/** Identity of one stored result: one record per model per test. */+export const capabilityResultKey = (backend, modelId, testId) => `${backend}:${modelId}:${testId}`;++export const keyOfResult = (r) => capabilityResultKey(r?.backend, r?.modelId, r?.testId);++async function quarantineStore(reason) {+ const parked = `${storeFile()}.corrupt-${Date.now()}`;+ const moved = await rename(storeFile(), parked).then(() => true).catch(() => false);+ console.error(`❌ Capability tests: ${reason} — ${moved ? `parked the old file as ${parked.split('/').pop()}` : 'could not park the old file'}`);+}++export async function loadStore() {+ const raw = await tryReadFile(storeFile());+ // Never written = an empty store, not an error.+ if (raw == null) return { schemaVersion: STORE_SCHEMA_VERSION, results: [], readError: null };+ const parsed = safeJSONParse(raw, null);+ if (!parsed || !Array.isArray(parsed.results)) {+ // Present but unparseable is NOT "nothing has been tested" — say so, or a+ // re-run would quietly overwrite results the user spent minutes earning.+ return { schemaVersion: STORE_SCHEMA_VERSION, results: [], readError: 'capability test results file is unreadable or malformed' };+ }+ return { schemaVersion: parsed.schemaVersion ?? STORE_SCHEMA_VERSION, results: parsed.results, readError: null };+}++/** Every stored result. Disk only — safe from any read path. */+export async function loadResults() {+ return (await loadStore()).results;+}++/**+ * Persist one result, replacing any previous run of the same model+test.+ *+ * History is deliberately not kept: a capability verdict is a statement about+ * the model as installed now, and an older run under a different quantization+ * or runtime build is misleading rather than informative. Re-running is cheap+ * enough that keeping a trail would cost more than it explains.+ */+export async function saveResult(result) {+ const { results, readError } = await loadStore();+ // Rewriting from an empty in-memory list after a failed read would replace+ // every stored result with this one. Quarantine instead — nothing is lost and+ // the feature keeps working.+ if (readError) await quarantineStore(readError);+ const record = {+ ...result,+ output: clampText(result.output, MAX_OUTPUT_CHARS, 'head'),+ transcript: clampText(result.transcript, MAX_TRANSCRIPT_CHARS, 'tail'),+ environment: result.environment ?? captureDurableEnvironment(),+ };+ const key = keyOfResult(record);+ const next = results.filter((r) => keyOfResult(r) !== key);+ next.push(record);+ await ensureDir(storeDir());+ await atomicWrite(storeFile(), { schemaVersion: STORE_SCHEMA_VERSION, results: next });+ return record;+}++/**+ * Drop one recorded result. Reports whether anything was actually removed so the+ * caller can 404 rather than claiming a phantom success.+ */+export async function deleteResult(backend, modelId, testId) {+ const { results, readError } = await loadStore();+ if (readError) return { deleted: false };+ const key = capabilityResultKey(backend, modelId, testId);+ const next = results.filter((r) => keyOfResult(r) !== key);+ if (next.length === results.length) return { deleted: false };+ await ensureDir(storeDir());+ await atomicWrite(storeFile(), { schemaVersion: STORE_SCHEMA_VERSION, results: next });+ console.log(`🧹 Capability tests: dropped ${testId} result for ${backend}/${modelId}`);+ return { deleted: true };+}++/**+ * Stored results indexed by `backend:modelId:testId`, for the report builder.+ * `{}` is a real answer (nothing tested yet), distinct from `readError`.+ */+export async function indexResults() {+ const { results, readError } = await loadStore();+ return { index: Object.fromEntries(results.map((r) => [keyOfResult(r), r])), readError };+}diff --git a/server/services/modelCapabilityTests.js b/server/services/modelCapabilityTests.jsnew file mode 100644index 0000000000..e3f4f8a513--- /dev/null+++ b/server/services/modelCapabilityTests.js@@ -0,0 +1,579 @@+/**+ * Capability tests for local models — the runner.+ *+ * 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+ * 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.+ * - `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.+ *+ * ## Rules this file exists to honour+ *+ * 1. **No cold-bootstrap LLM calls** (root CLAUDE.md). `getCapabilityTestReport`+ * touches disk (plus, for Ollama, cached loopback capability probes) and+ * calls no provider, so it is safe from a poll or a page load.+ * `runCapabilityTest` is the ONLY path that reaches a model, and it fires+ * solely from a deliberate click whose gate names the runtime, the model and+ * the prompt first. There is deliberately **no scheduler and no sweep** here:+ * a capability run is a manual act.+ * 2. **Verdicts come from disk, never from the transcript.** A model claiming+ * "I fixed it" scores nothing — the sandbox verdict is the fixture hashes+ * plus the exit code of a test run PortOS performs itself, after the agent+ * has stopped.+ * 3. **An unclaimed capability is not a failure.** Applicability is decided in+ * `lib/modelCapabilityTests.js`; a model with no `vision` badge is skipped on+ * the image test rather than scored zero on it.+ * 4. **One heavy local job at a time.** A run holds a runtime for minutes and+ * loads a model into memory, so it takes the same machine-wide claim+ * assessments and sweeps take. Without it a capability run could execute on+ * top of an overnight sweep and corrupt its timings.+ */++import { cp, readdir, readFile, rm, stat } from 'fs/promises';+import { join } from 'path';+import { fileURLToPath } from 'url';+import sharp from 'sharp';+import { ServerError } from '../lib/errorHandler.js';+import { PATHS, ensureDir, sha256File } from '../lib/fileUtils.js';+import { bufferedSpawn } from '../lib/bufferedSpawn.js';+import { withSpawnCwdEnv } from '../lib/spawnCwd.js';+import { claimHeavyLocalJob } from '../lib/heavyJobClaim.js';+import { formatAgentEvent } from '../lib/opencodeStream.js';+import {+ ASSESSABLE_RUNTIMES, LOCAL_RUNTIMES, MANAGED_ASSESSMENT_BACKENDS,+} from '../lib/localProviderRuntime.js';+import {+ CAPABILITY_TESTS, CAPABILITY_TEST_IDS, CAPABILITY_TEST_PROMPTS, SANDBOX_TASK_PROMPT,+ VISION_FIXTURE_KEYWORDS, HEROS_JOURNEY_BEATS,+ applicableTests, getCapabilityTest,+ scoreKeywords, scoreStoryBeats, scoreSandboxRepair, rollUpVerdict,+} from '../lib/modelCapabilityTests.js';+import { listRuntimeModels, runtimeEndpoint, runtimeApiKey } from './localModelAssessments.js';+import { runLocalLlmTest, runEndpointLlmTest } from './localLlmPlayground.js';+import { getAllProviders } from './providers.js';+import { resolveOpencodeTuiProvider, runOpencodeTask } from './opencodeTask.js';+import { ollamaBadgeCapabilities } from './localLlm.js';+import * as ollamaManager from './ollamaManager.js';+import { indexResults, saveResult, capabilityResultKey, loadResults } from './modelCapabilityTestStore.js';++const FIXTURES = fileURLToPath(new URL('../fixtures/model-tests/', import.meta.url));+const VISION_FIXTURE_SVG = join(FIXTURES, 'vision', 'bicycle-bench.svg');+const SANDBOX_FIXTURE = join(FIXTURES, 'sandbox', 'cart-totals');++/** The three files the sandbox test copies, and what each one is FOR. */+export const SANDBOX_FILES = Object.freeze({+ // The only file the model is allowed to change.+ module: 'cart-totals.mjs',+ // Both of these must come back byte-identical: editing the test into+ // submission is the one way to "pass" without fixing anything.+ test: 'cart-totals.test.mjs',+ data: 'orders.json',+});++/** How PortOS itself checks the sandbox, after the agent has stopped. */+export const SANDBOX_VERIFY_COMMAND = Object.freeze(['node', SANDBOX_FILES.test]);++const AGENT_TIMEOUT_MS = 10 * 60 * 1000;+const VERIFY_TIMEOUT_MS = 60 * 1000;+const CHAT_TIMEOUT_MS = 5 * 60 * 1000;++/**+ * Sandboxes are KEPT after a run — reading the diff is half the value of the+ * test — which means something has to bound them, or a directory the user never+ * looks at grows one copy per run forever. The newest few are what anyone+ * actually opens.+ */+const SANDBOX_KEEP = 20;++// Low but not zero: a deterministic answer makes two runs of the same model+// comparable, while 0 makes some local daemons loop on a repeated phrase.+const TEST_TEMPERATURE = 0.2;++const runtimeLabel = (id) => LOCAL_RUNTIMES[id]?.label || id;++// ---- capabilities -----------------------------------------------------------++/**+ * The badge set a model claims, or `null` when nothing authoritative said.+ *+ * The distinction is the whole point: `[]` means a runtime answered and the+ * model claims nothing (every test is `not-applicable`), while `null` means+ * nobody was asked (every test is `unknown` and stays on offer).+ *+ * Ollama's `/api/tags` carries no capability flags, so `listModels` reports+ * `null` there rather than an empty list — `/api/show` is what actually knows,+ * and it is cached per model, so asking it here stays cheap enough for a read+ * path. Every other runtime either answers in its listing (LM Studio) or is a+ * bare endpoint that reports ids and nothing else.+ */+export async function resolveModelCapabilities(runtime, model) {+ const listed = Array.isArray(model?.capabilities) ? model.capabilities : null;+ if (listed?.length) return listed;+ if (runtime === 'ollama' && model?.id) {+ const raw = await ollamaManager.getModelCapabilities(model.id).catch(() => null);+ // A failed probe is unknown, not "claims nothing".+ return ollamaBadgeCapabilities(raw);+ }+ return listed;+}++/**+ * Whether PortOS can DRIVE the agent tests on a runtime, as opposed to whether a+ * model claims the capability. Surfaced separately so the UI can say "PortOS+ * cannot run this here" rather than implying the model is at fault.+ */+async function agentDriverFor(runtime, providers) {+ const provider = await resolveOpencodeTuiProvider(runtime, providers);+ return provider+ ? { available: true, provider, reason: null }+ : { available: false, provider: null, reason: `no OpenCode TUI provider is configured for ${runtimeLabel(runtime)}` };+}++// ---- fixtures ---------------------------------------------------------------++// Rendered once per process. The fixture is a committed SVG rather than a PNG so+// it stays reviewable in a diff, and rasterizing it here means the bytes a model+// sees are produced the same way on every install.+let visionFixtureCache = null;+// The fixture files never change while the process runs, so their hashes — the+// baseline every sandbox verdict is measured against — are read once.+let fixtureHashCache = null;++export async function loadVisionFixture() {+ if (visionFixtureCache) return visionFixtureCache;+ const png = await sharp(VISION_FIXTURE_SVG).png().toBuffer();+ visionFixtureCache = {+ dataUrl: `data:image/png;base64,${png.toString('base64')}`,+ bytes: png.length,+ };+ return visionFixtureCache;+}++async function sandboxFixtureHashes() {+ if (fixtureHashCache) return fixtureHashCache;+ fixtureHashCache = Object.fromEntries(await Promise.all(+ Object.entries(SANDBOX_FILES).map(async ([role, name]) => [role, await sha256File(join(SANDBOX_FIXTURE, name))]),+ ));+ return fixtureHashCache;+}++/** Test seam: drop the cached fixtures so a suite can re-read them. */+export function __resetFixtureCaches() {+ visionFixtureCache = null;+ fixtureHashCache = null;+}++// ---- run plumbing -----------------------------------------------------------++const progressFrame = (backend, modelId, testId, frame) => ({+ scope: 'capability-test',+ backend,+ modelId,+ testId,+ ...frame,+});++/**+ * Ask the right transport for one bounded generation.+ *+ * A managed backend goes through the playground's provider path (and so lands in+ * `/runs`); a bare daemon is talked to directly, because inventing a provider+ * record for something the user started outside PortOS would put a phantom+ * provider in the run history. Same result shape either way.+ */+async function generate({ backend, modelId, prompt, images, maxTokens, signal }) {+ if (MANAGED_ASSESSMENT_BACKENDS.includes(backend)) {+ return runLocalLlmTest({+ backend, modelId, prompt, images, maxTokens, signal,+ temperature: TEST_TEMPERATURE, timeoutMs: CHAT_TIMEOUT_MS,+ });+ }+ const endpoint = await runtimeEndpoint(backend);+ if (!endpoint) {+ throw new ServerError(`No endpoint is configured for ${runtimeLabel(backend)}`, {+ status: 503, code: 'CAPABILITY_TEST_RUNTIME_UNREACHABLE',+ });+ }+ return runEndpointLlmTest({+ runtime: backend, endpoint, apiKey: await runtimeApiKey(backend),+ modelId, prompt, images, maxTokens, signal,+ temperature: TEST_TEMPERATURE, timeoutMs: CHAT_TIMEOUT_MS,+ });+}++// ---- the three tests --------------------------------------------------------++/**+ * The two 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.+ */+const CHAT_TESTS = {+ 'image-analysis': {+ maxTokens: 700,+ message: (modelId) => `Sending the fixture image to ${modelId}…`,+ images: async () => [(await loadVisionFixture()).dataUrl],+ score: (text) => scoreKeywords(text, VISION_FIXTURE_KEYWORDS),+ },+ 'story-outline': {+ // A twelve-beat outline runs close to a thousand tokens; a budget that+ // clipped it would score as missing beats — a scoring bug dressed up as a+ // model failure.+ maxTokens: 2400,+ message: (modelId) => `Asking ${modelId} for a twelve-beat outline…`,+ images: async () => undefined,+ score: (text) => scoreStoryBeats(text, HEROS_JOURNEY_BEATS),+ },+};++async function runChatTest({ backend, modelId, testId, signal, emit }) {+ const spec = CHAT_TESTS[testId];+ const images = await spec.images();+ emit({ event: 'progress', message: spec.message(modelId) });++ const result = await generate({+ backend, modelId, prompt: CAPABILITY_TEST_PROMPTS[testId], images, maxTokens: spec.maxTokens, signal,+ });+ const output = String(result?.text || '');++ // Nothing came back at all: there is no answer to score, so the error IS the+ // result. A run that produced text AND reported an error (a mid-stream+ // timeout) is scored on what it produced, with the error kept beside it.+ if (result?.error && !output.trim()) {+ return { verdict: 'failed', summary: result.error, output, detail: null, error: result.error, timings: result.timings || null };+ }+ const detail = spec.score(output);+ return {+ verdict: detail.verdict,+ summary: detail.summary,+ output,+ detail,+ error: result?.error || null,+ timings: result?.timings || null,+ };+}++/**+ * Delete all but the newest sandboxes. `runId` starts with a base36 timestamp of+ * fixed width, so a plain sort is chronological.+ */+async function pruneSandboxes(root, keep = SANDBOX_KEEP) {+ const entries = await readdir(root, { withFileTypes: true }).catch(() => []);+ const stale = entries.filter((e) => e.isDirectory()).map((e) => e.name).sort().slice(0, -keep);+ for (const name of stale) {+ await rm(join(root, name), { recursive: true, force: true }).catch((err) => {+ console.error(`⚠️ Capability tests: could not prune sandbox ${name} — ${err.message}`);+ });+ }+}++/**+ * Sandbox repair: the one test that watches a model work.+ *+ * The sandbox is a fresh copy of the fixture for every run, so a model that+ * mangles the module cannot affect the next run — and the fixture in the repo is+ * never the thing being edited.+ */+async function runSandboxRepair({ backend, modelId, signal, emit, runId, providers }) {+ const driver = await agentDriverFor(backend, providers);+ if (!driver.available) {+ throw new ServerError(driver.reason, { status: 503, code: 'CAPABILITY_TEST_AGENT_UNAVAILABLE' });+ }++ const 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 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,+ });++ await pruneSandboxes(sandboxRoot);++ 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,+ };+}++const RUNNERS = {+ 'image-analysis': runChatTest,+ 'story-outline': runChatTest,+ 'sandbox-repair': runSandboxRepair,+};++// ---- public run path --------------------------------------------------------++/**+ * Run ONE capability test against ONE model. The only path here that reaches a+ * provider, and only ever from an explicit user action.+ *+ * @param {object} options+ * @param {string} options.backend assessable runtime id+ * @param {string} options.modelId+ * @param {string} options.testId one of CAPABILITY_TEST_IDS+ * @param {AbortSignal} [options.signal] the client's disconnect+ * @param {(frame: object) => void} [options.onProgress]+ * @param {number} [options.claimTimeoutMs] how long to wait for the machine-wide+ * heavy-job claim before reporting it busy+ */+export async function runCapabilityTest({ backend, modelId, testId, signal, onProgress, claimTimeoutMs = 0 } = {}) {+ const test = getCapabilityTest(testId);+ if (!test) {+ throw new ServerError(`Unknown capability test: ${testId}`, { status: 400, code: 'VALIDATION_ERROR' });+ }+ if (!ASSESSABLE_RUNTIMES.includes(backend)) {+ throw new ServerError(`Unsupported runtime: ${backend}`, { status: 400, code: 'VALIDATION_ERROR' });+ }++ const emit = (frame) => onProgress?.(progressFrame(backend, modelId, testId, frame));+ // A short, sortable id: it names the sandbox directory (and so its prune+ // order) and appears in the log line, so it has to read cleanly and be unique+ // per run.+ const runId = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;++ // A run holds the runtime for minutes and loads a model into memory, so it+ // takes the same claim an assessment or a sweep takes. Without it a capability+ // run could execute on top of an overnight sweep and corrupt its timings.+ const claim = await claimHeavyLocalJob({ kind: 'model capability test', id: `${backend}/${modelId}`, timeoutMs: claimTimeoutMs });+ if (!claim.ok) {+ throw new ServerError(claim.message, { status: 409, code: 'HEAVY_LOCAL_JOB_BUSY', context: { holder: claim.holder } });+ }++ 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 {+ // 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.+ if (signal?.aborted) {+ emit({ event: 'complete', cancelled: true, message: `${test.label}: cancelled — nothing recorded` });+ return { backend, modelId, testId: test.id, cancelled: true };+ }+ const providers = test.driver === 'tui' ? await getAllProviders().catch(() => null) : null;+ outcome = await RUNNERS[test.id]({ backend, modelId, testId: test.id, signal, emit, runId, providers });+ } catch (err) {+ // A terminal frame either way, or the page's banner sits on the last+ // progress line forever waiting for a run that already died.+ emit({ event: 'complete', message: `${test.label}: ${err.message}`, verdict: 'failed' });+ throw err;+ } finally {+ await claim.release();+ }++ // A cancelled run recorded as `failed` would be a lie about the model that+ // then needs manually deleting. Report what was gathered; store nothing.+ if (signal?.aborted) {+ console.log(`🧪 Capability tests: ${test.id} on ${backend}/${modelId} cancelled — not recorded`);+ emit({ event: 'complete', cancelled: true, message: `${test.label}: cancelled — nothing recorded` });+ return { ...outcome, backend, modelId, testId: test.id, cancelled: true };+ }++ const record = await saveResult({+ backend,+ modelId,+ testId: test.id,+ runId,+ verdict: outcome.verdict,+ summary: outcome.summary,+ output: outcome.output,+ transcript: outcome.transcript ?? '',+ detail: outcome.detail ?? null,+ error: outcome.error ?? null,+ timings: outcome.timings ?? null,+ elapsedMs: Math.max(0, Date.now() - startedAt),+ ranAt: new Date().toISOString(),+ });++ console.log(`🧪 Capability tests: ${test.id} on ${backend}/${modelId} → ${record.verdict} (${record.summary})`);+ emit({ event: 'complete', verdict: record.verdict, message: `${test.label}: ${record.verdict} — ${record.summary}` });+ return record;+}++// ---- read path --------------------------------------------------------------++/**+ * What the matrix needs about one recorded result — everything EXCEPT the model+ * output and the agent transcript.+ *+ * Those two are the bulk of a record (up to ~100 KB each) and are needed only+ * when the drawer opens one pairing. Shipping every stored transcript on every+ * page load would make the report grow with the square of how much testing the+ * user has done, to render a chip that says "passed".+ */+const summarizeResult = (r) => (r ? {+ backend: r.backend,+ modelId: r.modelId,+ testId: r.testId,+ verdict: r.verdict,+ summary: r.summary,+ ranAt: r.ranAt ?? null,+ elapsedMs: r.elapsedMs ?? null,+ detail: r.detail ?? null,+ error: r.error ?? null,+ timings: r.timings ?? null,+} : null);++/** One stored result in full, for the drawer. `null` when nothing is recorded. */+export async function getCapabilityTestResult(backend, modelId, testId) {+ const results = await loadResults();+ return results.find((r) => r?.backend === backend && r?.modelId === modelId && r?.testId === testId) || null;+}++/**+ * Everything the page needs to show what each installed model claims and what it+ * has proved. Disk plus cached loopback capability probes; zero LLM calls.+ */+export async function getCapabilityTestReport() {+ const providers = await getAllProviders().catch(() => null);+ const [{ index, readError }, listed, drivers] = await Promise.all([+ indexResults(),+ Promise.all(ASSESSABLE_RUNTIMES.map(async (runtime) => [runtime, await listRuntimeModels(runtime)]))+ .then(Object.fromEntries),+ Promise.all(ASSESSABLE_RUNTIMES.map(async (runtime) => [runtime, await agentDriverFor(runtime, providers)]))+ .then(Object.fromEntries),+ ]);++ // Capability resolution costs one cached `/api/show` per un-probed Ollama+ // model. Sequentially that is one round trip per model on the page-load path;+ // they are independent, so they go together.+ const models = (await Promise.all(ASSESSABLE_RUNTIMES.flatMap((runtime) =>+ (listed[runtime].models || []).filter((m) => m?.id).map(async (model) => {+ const capabilities = await resolveModelCapabilities(runtime, model);+ const tests = applicableTests(capabilities).map(({ test, state, missing, reason }) => {+ const stored = index[capabilityResultKey(runtime, model.id, test.id)] || null;+ // The agent driver is a property of the RUNTIME, not of the model, and it+ // can make an otherwise-applicable test unrunnable. Surfaced as its own+ // state so the UI explains "PortOS cannot drive this" rather than+ // implying the model is at fault.+ const blocked = test.driver === 'tui' && state === 'applicable' && !drivers[runtime].available;+ return {+ testId: test.id,+ state: blocked ? 'unavailable' : state,+ missing,+ reason: blocked ? drivers[runtime].reason : reason,+ result: summarizeResult(stored),+ };+ });+ return {+ backend: runtime,+ runtimeLabel: runtimeLabel(runtime),+ // `null` = nothing authoritative reported a badge set. The UI must say+ // "unverified", never render it as an empty badge row.+ capabilities,+ modelId: model.id,+ tests,+ verdict: rollUpVerdict(tests.map((t) => t.result?.verdict).filter(Boolean)),+ };+ })+ ))).filter(Boolean);++ const countTests = (predicate) => models.reduce((acc, m) => acc + m.tests.filter(predicate).length, 0);++ return {+ // Serialized rather than referenced so the client renders one catalog and+ // cannot drift from the gate the server enforces.+ tests: CAPABILITY_TESTS.map((t) => ({ ...t, capabilities: [...t.capabilities], prefers: [...t.prefers] })),+ prompts: { ...CAPABILITY_TEST_PROMPTS, 'sandbox-repair': SANDBOX_TASK_PROMPT },+ models,+ counts: {+ models: models.length,+ applicable: countTests((t) => t.state === 'applicable' || t.state === 'unknown'),+ passed: countTests((t) => t.result?.verdict === 'passed'),+ failed: countTests((t) => t.result?.verdict === 'failed'),+ },+ // Runtimes whose model list could not be trusted — distinct from "listed and+ // legitimately empty". Without this the matrix silently under-reports: a+ // model that failed to list simply is not there.+ listErrors: ASSESSABLE_RUNTIMES+ .filter((id) => listed[id].error)+ .map((id) => ({ id, label: runtimeLabel(id), error: listed[id].error })),+ readError,+ };+}++export { CAPABILITY_TEST_IDS };diff --git a/server/services/modelCapabilityTests.test.js b/server/services/modelCapabilityTests.test.jsnew file mode 100644index 0000000000..04fd793b5e--- /dev/null+++ b/server/services/modelCapabilityTests.test.js@@ -0,0 +1,398 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtemp, readFile, rm, writeFile } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';++const TEST_ROOT = await mkdtemp(join(tmpdir(), 'portos-captests-'));+vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ actual.PATHS.data = TEST_ROOT;+ return actual;+});++vi.mock('./localModelAssessments.js', () => ({+ listRuntimeModels: vi.fn(async () => ({ models: [], error: null })),+ runtimeEndpoint: vi.fn(async () => 'http://127.0.0.1:8080/v1'),+ runtimeApiKey: vi.fn(async () => ''),+}));+vi.mock('./localLlmPlayground.js', () => ({+ runLocalLlmTest: vi.fn(),+ runEndpointLlmTest: vi.fn(),+}));+vi.mock('./providers.js', () => ({ getAllProviders: vi.fn(async () => []) }));+vi.mock('./ollamaManager.js', () => ({ getModelCapabilities: vi.fn(async () => null) }));+vi.mock('./localLlm.js', () => ({ ollamaBadgeCapabilities: (raw) => raw }));+vi.mock('../lib/bufferedSpawn.js', () => ({+ bufferedSpawn: vi.fn(),+ prepareCliSpawn: vi.fn((command, args) => ({ command, args })),+}));+// The agent runs through the streaming lane; `bufferedSpawn` above is only+// PortOS's own verification run. Mocking the spawn rather than `opencodeTask`+// keeps the real provider matching under test.+vi.mock('../lib/streamingSpawn.js', () => ({ runStreamingCommand: vi.fn() }));+// The claim is a real cross-process file lock; the suite is not testing it here.+vi.mock('../lib/heavyJobClaim.js', () => ({+ claimHeavyLocalJob: vi.fn(async () => ({ ok: true, holder: null, release: async () => {} })),+}));+vi.mock('../lib/cliChildEnv.js', () => ({ buildCliChildEnv: vi.fn(() => ({ PATH: '/example/bin' })) }));++const { listRuntimeModels } = await import('./localModelAssessments.js');+const { runLocalLlmTest, runEndpointLlmTest } = await import('./localLlmPlayground.js');+const { getAllProviders } = await import('./providers.js');+const { getModelCapabilities } = await import('./ollamaManager.js');+const { bufferedSpawn } = await import('../lib/bufferedSpawn.js');+const { runStreamingCommand } = await import('../lib/streamingSpawn.js');+const { claimHeavyLocalJob } = await import('../lib/heavyJobClaim.js');+const {+ getCapabilityTestReport, getCapabilityTestResult, runCapabilityTest,+ resolveModelCapabilities, SANDBOX_FILES, __resetFixtureCaches,+} = await import('./modelCapabilityTests.js');+const { loadResults } = await import('./modelCapabilityTestStore.js');++const OPENCODE_LLAMA = {+ id: 'opencode-llama-tui', name: 'OpenCode llama TUI', type: 'tui', command: 'opencode', args: [], llamaBacked: true,+};++// One installed model on one runtime; every other runtime lists nothing.+const installOn = (runtime, models) => {+ listRuntimeModels.mockImplementation(async (id) => (id === runtime ? { models, error: null } : { models: [], error: null }));+};++const testFor = (model, testId) => model.tests.find((t) => t.testId === testId);++const spawnResult = (over = {}) => ({ success: true, code: 0, signal: null, stdout: '', stderr: '', timedOut: false, ...over });++beforeEach(async () => {+ vi.clearAllMocks();+ await rm(join(TEST_ROOT, 'local-llm'), { recursive: true, force: true });+ await rm(join(TEST_ROOT, 'model-tests'), { recursive: true, force: true });+ listRuntimeModels.mockResolvedValue({ models: [], error: null });+ getAllProviders.mockResolvedValue([]);+ claimHeavyLocalJob.mockResolvedValue({ ok: true, holder: null, release: async () => {} });+ __resetFixtureCaches();+});++afterEach(async () => {+ await rm(join(TEST_ROOT, 'model-tests'), { recursive: true, force: true });+});++describe('resolveModelCapabilities', () => {+ it('keeps "the runtime reported nothing" distinct from "the model claims nothing"', async () => {+ // A bare endpoint reports ids only — unknown, so tests stay on offer.+ expect(await resolveModelCapabilities('llama', { id: 'some-model' })).toBeNull();+ // LM Studio always names at least chat, so its list IS an answer.+ expect(await resolveModelCapabilities('lmstudio', { id: 'm', capabilities: ['chat'] })).toEqual(['chat']);+ });++ it('asks Ollama for capabilities its model list does not carry', async () => {+ getModelCapabilities.mockResolvedValue(['completion', 'tools']);+ expect(await resolveModelCapabilities('ollama', { id: 'qwen', capabilities: [] })).toEqual(['completion', 'tools']);+ expect(getModelCapabilities).toHaveBeenCalledWith('qwen');+ });++ it('reports unknown — not "claims nothing" — when the Ollama probe fails', async () => {+ getModelCapabilities.mockRejectedValue(new Error('daemon down'));+ expect(await resolveModelCapabilities('ollama', { id: 'qwen', capabilities: [] })).toBeNull();+ });+});++describe('getCapabilityTestReport', () => {+ it('gates each test on the badges the model claims', async () => {+ installOn('lmstudio', [{ id: 'vision-only', capabilities: ['chat', 'vision'] }]);+ const report = await getCapabilityTestReport();+ const model = report.models.find((m) => m.modelId === 'vision-only');++ expect(testFor(model, 'image-analysis').state).toBe('applicable');+ expect(testFor(model, 'story-outline').state).toBe('applicable');+ // No `tools` badge — skipped, and the reason names what is missing.+ expect(testFor(model, 'sandbox-repair').state).toBe('not-applicable');+ expect(testFor(model, 'sandbox-repair').reason).toContain('tools');+ });++ it('marks a tool-use test unavailable — not failed — when no agent driver is configured', async () => {+ installOn('lmstudio', [{ id: 'tool-caller', capabilities: ['chat', 'tools'] }]);+ // LM Studio has no OpenCode namespace, so nothing can drive the TUI there.+ const report = await getCapabilityTestReport();+ const sandbox = testFor(report.models.find((m) => m.modelId === 'tool-caller'), 'sandbox-repair');+ expect(sandbox.state).toBe('unavailable');+ expect(sandbox.reason).toContain('OpenCode');+ });++ it('offers the tool-use test once a matching TUI provider exists', async () => {+ getAllProviders.mockResolvedValue([OPENCODE_LLAMA]);+ installOn('llama', [{ id: 'qwen-local' }]);+ const report = await getCapabilityTestReport();+ const model = report.models.find((m) => m.modelId === 'qwen-local');+ // Capabilities are unknown on a bare endpoint, so every test is on offer+ // with the claim marked unverified rather than hidden.+ expect(model.capabilities).toBeNull();+ expect(testFor(model, 'sandbox-repair').state).toBe('unknown');+ });++ it('reports no verdict for a model nothing has been run against', async () => {+ installOn('lmstudio', [{ id: 'fresh', capabilities: ['chat'] }]);+ const report = await getCapabilityTestReport();+ expect(report.models.find((m) => m.modelId === 'fresh').verdict).toBeNull();+ expect(report.counts.passed).toBe(0);+ });++ it('calls no provider — the report is a read path', async () => {+ installOn('lmstudio', [{ id: 'anything', capabilities: ['chat', 'vision', 'tools'] }]);+ await getCapabilityTestReport();+ expect(runLocalLlmTest).not.toHaveBeenCalled();+ expect(runEndpointLlmTest).not.toHaveBeenCalled();+ expect(bufferedSpawn).not.toHaveBeenCalled();+ });+});++describe('runCapabilityTest — image analysis', () => {+ it('scores the answer and keeps the model output verbatim', async () => {+ runLocalLlmTest.mockResolvedValue({+ text: 'A red bicycle beside a blue bench, a dog underneath, a lit street lamp and a sign reading 3.',+ timings: { totalMs: 4200 },+ });+ const record = await runCapabilityTest({ backend: 'lmstudio', modelId: 'vlm', testId: 'image-analysis' });++ expect(record.verdict).toBe('passed');+ expect(record.output).toContain('red bicycle');+ expect(record.detail.requiredHit).toBe(record.detail.requiredTotal);+ // The image really was attached, as a data URL rather than a path.+ expect(runLocalLlmTest.mock.calls[0][0].images[0]).toMatch(/^data:image\/png;base64,/);+ });++ it('records a partial answer as partial and still stores what came back', async () => {+ runLocalLlmTest.mockResolvedValue({ text: 'A bicycle and a bench at night.', timings: null });+ const record = await runCapabilityTest({ backend: 'lmstudio', modelId: 'vlm', testId: 'image-analysis' });+ expect(record.verdict).toBe('partial');+ expect(record.output).toBe('A bicycle and a bench at night.');+ });++ it('scores a mid-stream failure on what it produced, keeping the error beside it', async () => {+ runLocalLlmTest.mockResolvedValue({+ text: 'A bicycle, a bench, a dog and a street lamp.',+ error: 'Timed out after 300000ms',+ timings: null,+ });+ const record = await runCapabilityTest({ backend: 'lmstudio', modelId: 'vlm', testId: 'image-analysis' });+ expect(record.verdict).toBe('passed');+ expect(record.error).toContain('Timed out');+ });++ it('routes a bare endpoint runtime straight at its endpoint', async () => {+ runEndpointLlmTest.mockResolvedValue({ text: 'a bicycle, a bench, a dog, a lamp', timings: null });+ await runCapabilityTest({ backend: 'llama', modelId: 'local-vlm', testId: 'image-analysis' });+ expect(runEndpointLlmTest).toHaveBeenCalled();+ expect(runLocalLlmTest).not.toHaveBeenCalled();+ });+});++describe('runCapabilityTest — story outline', () => {+ it('stores the whole outline, not just the score', async () => {+ const outline = ['Ordinary world', 'Call to adventure', 'The ordeal', 'Return with the elixir']+ .map((b) => `## ${b}\nA paragraph about it.`).join('\n\n');+ runLocalLlmTest.mockResolvedValue({ text: outline, timings: null });+ const record = await runCapabilityTest({ backend: 'ollama', modelId: 'writer', testId: 'story-outline' });+ expect(record.output).toBe(outline);+ expect(record.detail.found).toBe(4);+ expect(record.verdict).toBe('failed');+ });+});++describe('runCapabilityTest — sandbox repair', () => {+ beforeEach(() => {+ getAllProviders.mockResolvedValue([OPENCODE_LLAMA]);+ });++ // The agent is simulated by having the spawn mock edit the sandbox the way a+ // model would, so the verdict is produced by the real on-disk checks.+ const withAgent = (edit) => {+ runStreamingCommand.mockImplementation(async (_cmd, _args, onLine, opts) => {+ await edit(opts.cwd, opts);+ for (const line of [+ JSON.stringify({ type: 'tool', part: { type: 'tool', tool: 'read', input: { filePath: 'cart-totals.mjs' } } }),+ JSON.stringify({ type: 'text', part: { type: 'text', text: 'Rewriting cartTotal.' } }),+ JSON.stringify({ type: 'tool', part: { type: 'tool', tool: 'write', input: { filePath: 'cart-totals.mjs' } } }),+ ]) onLine(line);+ return { success: true };+ });+ // PortOS's own verification run really executes the sandbox test, so the+ // exit code the verdict turns on is a real one.+ bufferedSpawn.mockImplementation(async (cmd, args, opts) => {+ const { execFileSync } = await import('child_process');+ try {+ return spawnResult({ stdout: execFileSync(cmd, args, { cwd: opts.cwd, encoding: 'utf8', stdio: 'pipe' }) });+ } catch (err) {+ return spawnResult({ success: false, code: err.status ?? 1, stdout: String(err.stdout || ''), stderr: String(err.stderr || '') });+ }+ });+ };++ const fixedModule = `import { readFile } from 'node:fs/promises';+export const TAX = { 'us-ca': 0.0875, 'us-ny': 0.08875, uk: 0.2, default: 0.05 };+export function round2(value) { return Math.round(value * 100) / 100; }+export async function loadOrders(path = new URL('./orders.json', import.meta.url)) {+ return JSON.parse(await readFile(path, 'utf8'));+}+export function cartTotal({ items, region, discount = 0 }) {+ const sub = items.reduce((acc, item) => acc + item.price * item.qty, 0);+ const rate = TAX[region] ?? TAX.default;+ return round2(sub + sub * rate - discount);+}+`;++ it('passes only when PortOS’s own test run exits 0', async () => {+ withAgent(async (cwd) => writeFile(join(cwd, SANDBOX_FILES.module), fixedModule));+ const record = await runCapabilityTest({ backend: 'llama', modelId: 'coder', testId: 'sandbox-repair' });++ expect(record.verdict).toBe('passed');+ expect(record.detail.verifyExitCode).toBe(0);+ expect(record.detail.toolCalls).toBe(2);+ // Watching it work is the point: the transcript survives the run.+ expect(record.transcript).toContain('● read cart-totals.mjs');+ expect(record.transcript).toContain('Rewriting cartTotal.');+ });++ it('fails a model that only SAYS it fixed the module', async () => {+ // Touches nothing on disk, narrates success.+ withAgent(async () => {});+ const record = await runCapabilityTest({ backend: 'llama', modelId: 'talker', testId: 'sandbox-repair' });+ expect(record.verdict).toBe('failed');+ expect(record.summary).toContain('never wrote a fix');+ });++ it('fails a model that edited the test into passing', async () => {+ withAgent(async (cwd) => {+ await writeFile(join(cwd, SANDBOX_FILES.module), fixedModule);+ await writeFile(join(cwd, SANDBOX_FILES.test), '// deleted every assertion\n');+ });+ const record = await runCapabilityTest({ backend: 'llama', modelId: 'cheater', testId: 'sandbox-repair' });+ expect(record.verdict).toBe('failed');+ expect(record.summary).toContain('edited the test');+ });++ it('records a wrong fix as partial rather than as no attempt', async () => {+ withAgent(async (cwd) => writeFile(join(cwd, SANDBOX_FILES.module), `${fixedModule}\n// still wrong\nexport const BROKEN = true;\n`+ .replace('return round2(sub + sub * rate - discount);', 'return sub;')));+ const record = await runCapabilityTest({ backend: 'llama', modelId: 'trier', testId: 'sandbox-repair' });+ expect(record.verdict).toBe('partial');+ });++ it('refuses when no agent driver can reach the runtime', async () => {+ getAllProviders.mockResolvedValue([]);+ await expect(runCapabilityTest({ backend: 'lmstudio', modelId: 'x', testId: 'sandbox-repair' }))+ .rejects.toThrow(/OpenCode/);+ });++ it('gives the agent a fresh copy of the fixture, never the repo one', async () => {+ let sandboxDir = null;+ withAgent(async (cwd) => { sandboxDir = cwd; await writeFile(join(cwd, SANDBOX_FILES.module), fixedModule); });+ await runCapabilityTest({ backend: 'llama', modelId: 'coder', testId: 'sandbox-repair' });++ expect(sandboxDir.startsWith(join(TEST_ROOT, 'model-tests', 'sandboxes'))).toBe(true);+ // The repo fixture is untouched: still the broken version.+ const repoFixture = await readFile(new URL(`../fixtures/model-tests/sandbox/cart-totals/${SANDBOX_FILES.module}`, import.meta.url), 'utf8');+ expect(repoFixture).not.toContain('?? TAX.default');+ });+});++describe('runCapabilityTest — cancellation', () => {+ it('records nothing when the client disconnects mid-run', async () => {+ runLocalLlmTest.mockResolvedValue({ text: 'a bicycle, a bench, a dog, a lamp', timings: null });+ const controller = new AbortController();+ controller.abort();+ const result = await runCapabilityTest({ backend: 'lmstudio', modelId: 'vlm', testId: 'image-analysis', signal: controller.signal });++ expect(result.cancelled).toBe(true);+ expect(await loadResults()).toEqual([]);+ });+});++describe('runCapabilityTest — input guards', () => {+ it('rejects an unknown test id at the service boundary', async () => {+ await expect(runCapabilityTest({ backend: 'ollama', modelId: 'm', testId: 'nope' })).rejects.toThrow(/Unknown capability test/);+ });++ it('rejects a runtime PortOS cannot assess', async () => {+ await expect(runCapabilityTest({ backend: 'openai', modelId: 'm', testId: 'story-outline' })).rejects.toThrow(/Unsupported runtime/);+ });+});++describe('the machine-wide heavy-job claim', () => {+ it('refuses to run on top of an assessment sweep', async () => {+ claimHeavyLocalJob.mockResolvedValue({+ ok: false, holder: { kind: 'local-model assessment sweep' }, message: 'A local-model assessment sweep is running', release: async () => {},+ });+ await expect(runCapabilityTest({ backend: 'lmstudio', modelId: 'vlm', testId: 'image-analysis' }))+ .rejects.toThrow(/sweep is running/);+ // Nothing reached a provider — the claim is taken before the model is.+ expect(runLocalLlmTest).not.toHaveBeenCalled();+ });++ it('releases the claim even when the run throws', async () => {+ const release = vi.fn(async () => {});+ claimHeavyLocalJob.mockResolvedValue({ ok: true, holder: null, release });+ runLocalLlmTest.mockRejectedValue(new Error('llama.cpp went away'));++ await expect(runCapabilityTest({ backend: 'lmstudio', modelId: 'vlm', testId: 'image-analysis' })).rejects.toThrow();+ expect(release).toHaveBeenCalled();+ });+});++describe('what the report ships', () => {+ beforeEach(async () => {+ runLocalLlmTest.mockResolvedValue({+ text: 'A red bicycle beside a blue bench, a dog underneath, a lit street lamp and a sign reading 3.',+ timings: null,+ });+ installOn('lmstudio', [{ id: 'vlm', capabilities: ['chat', 'vision'] }]);+ await runCapabilityTest({ backend: 'lmstudio', modelId: 'vlm', testId: 'image-analysis' });+ });++ it('summarises each result rather than shipping every stored transcript', async () => {+ const report = await getCapabilityTestReport();+ const slot = testFor(report.models.find((m) => m.modelId === 'vlm'), 'image-analysis');++ expect(slot.result.verdict).toBe('passed');+ // The score detail is what the matrix and the Checks tab render, so it rides+ // along; the model's own text does not — that is a per-pairing fetch.+ expect(slot.result.detail.requiredHit).toBe(4);+ expect(slot.result).not.toHaveProperty('output');+ expect(slot.result).not.toHaveProperty('transcript');+ });++ it('serves the full record for one pairing on demand', async () => {+ const full = await getCapabilityTestResult('lmstudio', 'vlm', 'image-analysis');+ expect(full.output).toContain('red bicycle');+ expect(await getCapabilityTestResult('lmstudio', 'vlm', 'story-outline')).toBeNull();+ });++ it('names a runtime whose model list could not be read', async () => {+ listRuntimeModels.mockImplementation(async (id) => (id === 'ollama'+ ? { models: null, error: 'not reachable at http://127.0.0.1:11434/v1' }+ : { models: [], error: null }));+ const report = await getCapabilityTestReport();+ // Missing models must read as "could not look", not as "none installed".+ expect(report.listErrors).toEqual([{ id: 'ollama', label: 'Ollama', error: 'not reachable at http://127.0.0.1:11434/v1' }]);+ });+});++describe('sandbox housekeeping', () => {+ it('keeps the newest sandboxes and prunes the rest', async () => {+ const { mkdir, readdir } = await import('fs/promises');+ getAllProviders.mockResolvedValue([OPENCODE_LLAMA]);+ const root = join(TEST_ROOT, 'model-tests', 'sandboxes');+ // 25 older runs, named the way runCapabilityTest names them (a base36+ // timestamp of fixed width, so a plain sort is chronological).+ await mkdir(root, { recursive: true });+ for (let i = 0; i < 25; i += 1) await mkdir(join(root, `aaaaaaa${String(i).padStart(2, '0')}-old`), { recursive: true });++ runStreamingCommand.mockResolvedValue({ success: true });+ bufferedSpawn.mockResolvedValue(spawnResult({ success: false, code: 1 }));+ await runCapabilityTest({ backend: 'llama', modelId: 'coder', testId: 'sandbox-repair' });++ const left = await readdir(root);+ expect(left.length).toBe(20);+ // The run that just happened is never the one pruned.+ expect(left.some((name) => !name.endsWith('-old'))).toBe(true);+ });+});diff --git a/server/services/opencodeTask.js b/server/services/opencodeTask.jsnew file mode 100644index 0000000000..7e85779259--- /dev/null+++ b/server/services/opencodeTask.js@@ -0,0 +1,92 @@+/**+ * Run one bounded task through an OpenCode TUI provider — the shared driver.+ *+ * Two features need this: the runtime agent-task benchmark+ * (`localModelAgentBenchmark.js`) and the sandbox-repair capability test+ * (`modelCapabilityTests.js`). Both want the same thing — point a configured+ * local OpenCode preset at a directory, give it a prompt, and read back what its+ * tool loop did — and both previously carried a character-for-character copy of+ * the argv, the env composition and the spawn. That is two places to fix the+ * next time OpenCode changes a flag, which it has done before.+ *+ * Line-streaming rather than run-and-collect: the capability test renders the+ * transcript live while the agent works, and `lib/streamingSpawn.js` is the+ * helper that owns that lane (`bufferedSpawn` is its run-and-collect sibling).+ * Streaming also means there is exactly ONE parse of the stream — the aggregated+ * events and the live view can never disagree about what happened.+ */++import { ServerError } from '../lib/errorHandler.js';+import { runStreamingCommand } from '../lib/streamingSpawn.js';+import { prepareCliSpawn } from '../lib/bufferedSpawn.js';+import { buildCliChildEnv } from '../lib/cliChildEnv.js';+import { isOpencodeCommand, prefixOpencodeModel, getOpencodeLocalProviderNamespace } from '../lib/providerModels.js';+import { parseAgentLine } from '../lib/opencodeStream.js';+import { getAllProviders } from './providers.js';++/**+ * The configured OpenCode TUI provider 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+ * namespace at all, which is why a caller must handle "none configured" as a+ * real answer rather than a failure to look harder.+ *+ * @param {string} runtime a local runtime id (`llama`, `ollama`, `mtplx`, …)+ * @param {Array<object>} [providers] pass the already-loaded list when resolving+ * several runtimes at once — otherwise every call re-scans it.+ */+export async function resolveOpencodeTuiProvider(runtime, providers) {+ const list = providers ?? await getAllProviders().catch(() => null);+ if (!Array.isArray(list)) return null;+ return list.find((p) => p?.type === 'tui'+ && isOpencodeCommand(p.command)+ && getOpencodeLocalProviderNamespace(p) === runtime) || null;+}++/**+ * Drive one disposable OpenCode task to completion.+ *+ * @param {object} options+ * @param {object} options.provider a TUI provider record (validated here)+ * @param {string} options.modelId model as the RUNTIME names it; the OpenCode+ * namespace prefix is applied here so a bare id can never route to a cloud+ * provider by accident+ * @param {string} options.cwd the directory the agent works in+ * @param {string} options.prompt+ * @param {number} options.timeoutMs+ * @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 }) {+ if (!provider) {+ throw new ServerError('No OpenCode TUI provider was given', { status: 503, code: 'OPENCODE_TASK_PROVIDER_MISSING' });+ }+ if (provider.type !== 'tui' || !isOpencodeCommand(provider.command)) {+ throw new ServerError(`Provider "${provider.id}" is not an OpenCode TUI provider`, {+ status: 503, code: 'OPENCODE_TASK_PROVIDER_INVALID',+ });+ }++ const events = [];+ const qualifiedModel = prefixOpencodeModel(provider, modelId);+ const baseArgs = Array.isArray(provider.args) ? provider.args : [];+ const args = ['run', '--format', 'json', '--auto', '--dir', cwd, ...baseArgs, '--model', qualifiedModel, prompt];+ // Pins PWD to `cwd` (#3193) — OpenCode resolves its project root from PWD, so+ // an inherited one would silently run the task in the PortOS checkout.+ const env = buildCliChildEnv({ provider, model: modelId, cwd, guard: true });+ const spawnTarget = prepareCliSpawn(provider.command, args, env);++ const result = await runStreamingCommand(spawnTarget.command, spawnTarget.args, (line) => {+ const event = parseAgentLine(line);+ if (!event) return;+ events.push(event);+ // 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 });++ return { success: result.success, error: result.error || null, events };+}