Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: measure local models instead of guessing whether they fit (#4539)

[._.]/ Adam Eivy4e7ea009e19c
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index 44a43bc1bb..593078ab30 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -14,6 +14,7 @@ import {
} from '../../services/api';
import socket from '../../services/socket';
import MemoryManagement from './MemoryManagement.jsx';
+import LocalModelAssessments from './LocalModelAssessments.jsx';
const BACKENDS = [
{ id: 'ollama', label: 'Ollama', icon: Cpu },
@@ -646,6 +647,7 @@ export function LocalLlmTab() {
return (
<div className="space-y-4">
<MemoryManagement />
+ <LocalModelAssessments />
{/* Backends — status + switch/migrate */}
<div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4">
<div className="flex items-center justify-between">
diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsx
index fda2490853..ff189b02a2 100644
--- a/client/src/components/settings/LocalLlmTab.test.jsx
+++ b/client/src/components/settings/LocalLlmTab.test.jsx
@@ -21,6 +21,9 @@ vi.mock('../../services/socket', () => ({
}));
// The memory panel owns its own 5s poll + voice/TTS endpoints — irrelevant here.
vi.mock('./MemoryManagement.jsx', () => ({ default: () => <div data-testid="memory-management" /> }));
+// Same for the assessments panel — it fetches its own report on mount and is
+// covered by LocalModelAssessments.test.jsx.
+vi.mock('./LocalModelAssessments.jsx', () => ({ default: () => <div data-testid="local-model-assessments" /> }));
vi.mock('../ui/Toast', () => ({
default: Object.assign(vi.fn(), { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }),
}));
diff --git a/client/src/components/settings/LocalModelAssessments.jsx b/client/src/components/settings/LocalModelAssessments.jsx
new file mode 100644
index 0000000000..48b07060d7
--- /dev/null
+++ b/client/src/components/settings/LocalModelAssessments.jsx
@@ -0,0 +1,388 @@
+/**
+ * Measured local-model assessments.
+ *
+ * The catalog's fit badge is a size estimate that never runs the model. This
+ * panel shows what a model ACTUALLY did on this machine — throughput, TTFT, the
+ * largest context it managed, and how much of its peak speed survived to that
+ * context — and ranks the assessed models for one of four intents.
+ *
+ * ## Two rules this panel exists to honour
+ *
+ * 1. **No cold-bootstrap LLM calls** (root CLAUDE.md). Reading assessments hits
+ * disk only, so it loads with the tab. Running one calls a provider, so it
+ * fires only from an explicit click AND a consent modal that names the
+ * backend, the model, and how many generations are about to happen.
+ * 2. **Unknown is not bad.** A model with no evidence is listed under "Not yet
+ * measured" with a Measure button — never ranked last, never shown as a poor
+ * choice. Same for an axis that wasn't measured: it is omitted, not zeroed.
+ */
+
+import { useCallback, useEffect, useState } from 'react';
+import { Gauge, RefreshCw, Trash2, Play, AlertTriangle } from 'lucide-react';
+import Modal from '../ui/Modal';
+import BrailleSpinner from '../BrailleSpinner';
+import toast from '../ui/Toast';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import { formatDurationMs } from '../../utils/formatters';
+import {
+ getLocalLlmAssessments, runLocalLlmAssessment, deleteLocalLlmAssessment,
+} from '../../services/api';
+
+const INTENTS = [
+ { id: 'balanced', label: 'Balanced', blurb: 'Even weight on capability, speed, context stability, and memory headroom.' },
+ { id: 'smartest', label: 'Smartest', blurb: 'Favors the largest model that actually ran here.' },
+ { id: 'fastest', label: 'Fastest', blurb: 'Favors measured throughput above all else.' },
+ { id: 'lightweight', label: 'Lightweight', blurb: 'Favors the smallest resident footprint — room left for other work.' },
+];
+
+const BACKEND_LABEL = { ollama: 'Ollama', lmstudio: 'LM Studio' };
+
+const VERDICT_META = {
+ fits: { label: 'Fits', cls: 'text-emerald-400 border-emerald-400/50' },
+ 'does-not-fit': { label: 'Does not fit', cls: 'text-port-warning border-port-warning/50' },
+ incompatible: { label: 'Incompatible', cls: 'text-port-error border-port-error/50' },
+ unknown: { label: 'Unknown', cls: 'text-gray-400 border-gray-500/50' },
+};
+
+const AXIS_LABEL = { capability: 'Capability', speed: 'Speed', fidelity: 'Context stability', memory: 'Memory headroom' };
+
+const formatContext = (tokens) => (tokens >= 1024 ? `${Math.round(tokens / 1024)}k` : String(tokens));
+
+// `null` is NOT MEASURED and must render as such — never as 0, and never as a
+// dash the reader could mistake for "measured, none".
+const Measured = ({ value, suffix = '', digits = 0 }) =>
+ (typeof value === 'number' && Number.isFinite(value)
+ ? <>{value.toFixed(digits)}{suffix}</>
+ : <span className="text-gray-600 italic">not measured</span>);
+
+function VerdictPill({ verdict }) {
+ const meta = VERDICT_META[verdict] || VERDICT_META.unknown;
+ return (
+ <span className={`px-1.5 py-0.5 text-[10px] font-medium rounded border ${meta.cls}`}>{meta.label}</span>
+ );
+}
+
+// Consent gate. PortOS never calls a provider the user didn't knowingly ask for,
+// so this names the exact backend, model, and generation count before the first
+// request goes out — the same contract as the POST drill cache's fill modal.
+function AssessmentConsentModal({ target, contextTokens, onCancel, onConfirm, running }) {
+ if (!target) return null;
+ return (
+ <Modal open onClose={onCancel} size="sm" ariaLabel="Run local model assessment" closeOnBackdrop={!running}>
+ <div className="bg-port-card border border-port-border rounded-lg p-5 space-y-4">
+ <div className="flex items-center gap-2">
+ <Gauge size={18} className="text-port-accent" />
+ <h3 className="text-white font-medium">Measure this model?</h3>
+ </div>
+ <p className="text-sm text-gray-400">
+ PortOS will run <span className="text-gray-200 font-mono break-all">{target.modelId}</span> on{' '}
+ <span className="text-gray-200">{BACKEND_LABEL[target.backend] || target.backend}</span>{' '}
+ {contextTokens.length} time{contextTokens.length === 1 ? '' : 's'} — one short generation at each of{' '}
+ {contextTokens.map(formatContext).join(', ')} tokens of context — and record what it measured.
+ </p>
+ <p className="text-xs text-gray-500">
+ Nothing else on this page calls a model. This can take several minutes on a large model, and it
+ loads the model into memory. The result stays on this machine and is never synced to a peer.
+ </p>
+ <div className="flex gap-3 pt-1">
+ <button
+ onClick={onCancel}
+ disabled={running}
+ className="flex-1 px-4 py-2 bg-port-card border border-port-border hover:border-port-accent text-white text-sm font-medium rounded-lg transition-colors disabled:opacity-50"
+ >
+ Cancel
+ </button>
+ <button
+ onClick={onConfirm}
+ disabled={running}
+ className="flex-1 px-4 py-2 bg-port-accent hover:bg-port-accent/80 text-port-on-accent text-sm font-medium rounded-lg transition-colors disabled:opacity-50 flex items-center justify-center gap-2"
+ >
+ {running ? <><BrailleSpinner /> Measuring…</> : <>Run assessment</>}
+ </button>
+ </div>
+ </div>
+ </Modal>
+ );
+}
+
+function RankedRow({ entry, onRemeasure, onDelete, busy }) {
+ const perf = entry.performance || {};
+ return (
+ <div className="border border-port-border rounded-lg p-3 space-y-2">
+ <div className="flex items-start justify-between gap-2 flex-wrap">
+ <div className="min-w-0">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-sm text-white font-mono break-all">{entry.modelId}</span>
+ <span className="text-[10px] text-gray-500">{BACKEND_LABEL[entry.backend] || entry.backend}</span>
+ <VerdictPill verdict={entry.verdict} />
+ </div>
+ <p className="text-xs text-gray-400 mt-1">{entry.explanation}</p>
+ {/* The score renormalizes over MEASURED axes, so a model with partial
+ evidence can outrank a fully-measured one. Say so rather than
+ presenting the rank as though it rested on the same footing. */}
+ {Number.isFinite(entry.coverage) && entry.coverage < 1 && (
+ <p className="text-[11px] text-gray-500 mt-0.5">
+ Ranked on {Math.round(entry.coverage * 100)}% of this intent&apos;s criteria — the rest went unmeasured.
+ </p>
+ )}
+ </div>
+ <div className="flex items-center gap-1 shrink-0">
+ <button
+ onClick={() => onRemeasure(entry)}
+ disabled={busy}
+ title="Measure again"
+ aria-label={`Measure ${entry.modelId} again`}
+ className="p-1.5 text-gray-400 hover:text-white transition-colors disabled:opacity-50"
+ >
+ <RefreshCw size={13} />
+ </button>
+ <button
+ onClick={() => onDelete(entry)}
+ disabled={busy}
+ title="Discard this measurement"
+ aria-label={`Discard the measurement for ${entry.modelId}`}
+ className="p-1.5 text-gray-400 hover:text-port-error transition-colors disabled:opacity-50"
+ >
+ <Trash2 size={13} />
+ </button>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 text-xs">
+ <div>
+ <div className="text-gray-500">Throughput</div>
+ <div className="text-gray-200"><Measured value={perf.meanCharsPerSecond} suffix=" chars/s" /></div>
+ </div>
+ <div>
+ <div className="text-gray-500">First token</div>
+ <div className="text-gray-200">
+ {Number.isFinite(perf.meanTtftMs)
+ ? formatDurationMs(perf.meanTtftMs)
+ : <span className="text-gray-600 italic">not measured</span>}
+ </div>
+ </div>
+ <div>
+ <div className="text-gray-500">Max context</div>
+ <div className="text-gray-200">
+ {Number.isFinite(perf.maxWorkingContextTokens)
+ ? `${formatContext(perf.maxWorkingContextTokens)} tokens`
+ : <span className="text-gray-600 italic">not measured</span>}
+ </div>
+ </div>
+ <div>
+ <div className="text-gray-500">Resident</div>
+ <div className="text-gray-200"><Measured value={entry.residentGb} suffix=" GB" digits={1} /></div>
+ </div>
+ </div>
+
+ {/* Per-axis bars, so the ranking is explainable rather than a bare score.
+ An unmeasured axis renders as text, never as an empty bar the reader
+ would read as "scored zero". */}
+ <div className="flex flex-wrap gap-x-4 gap-y-1 text-[11px] pt-1">
+ {Object.entries(AXIS_LABEL).map(([axis, label]) => {
+ const value = entry.scores?.[axis];
+ return (
+ <span key={axis} className="flex items-center gap-1.5">
+ <span className="text-gray-500">{label}</span>
+ {Number.isFinite(value) ? (
+ <span className="inline-flex items-center gap-1">
+ <span className="inline-block w-10 h-1.5 rounded bg-port-border overflow-hidden align-middle">
+ <span className="block h-full bg-port-accent" style={{ width: `${Math.round(value * 100)}%` }} />
+ </span>
+ <span className="text-gray-300">{Math.round(value * 100)}</span>
+ </span>
+ ) : (
+ <span className="text-gray-600 italic">n/a</span>
+ )}
+ </span>
+ );
+ })}
+ </div>
+ </div>
+ );
+}
+
+export function LocalModelAssessments() {
+ const [intent, setIntent] = useState('balanced');
+ const [report, setReport] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [pendingTarget, setPendingTarget] = useState(null);
+
+ const load = useCallback(async (nextIntent) => {
+ setLoading(true);
+ // The panel owns its own empty/error rendering, so silence the default toast
+ // (client/src/CLAUDE.md: custom catch ⇒ silent).
+ const data = await getLocalLlmAssessments(nextIntent, { silent: true }).catch(() => null);
+ setReport(data);
+ setLoading(false);
+ }, []);
+
+ useEffect(() => { load(intent); }, [load, intent]);
+
+ const [runAssessment, running] = useAsyncAction(async (target) => {
+ const result = await runLocalLlmAssessment(
+ { backend: target.backend, modelId: target.modelId },
+ { silent: true },
+ );
+ // Reactive update rather than a refetch of the whole report — except the
+ // ranking itself is server-derived, so pull the fresh ranking once the run
+ // lands. Keeping the local swap would mean re-implementing the scoring here.
+ await load(intent);
+ return result;
+ }, { errorMessage: 'Assessment failed' });
+
+ const confirmRun = async () => {
+ const target = pendingTarget;
+ const result = await runAssessment(target);
+ setPendingTarget(null);
+ if (result) {
+ const verdict = VERDICT_META[result.verdict]?.label || result.verdict;
+ toast.success(`${target.modelId}: ${verdict}`);
+ }
+ };
+
+ const [removeAssessment, removing] = useAsyncAction(async (entry) => {
+ await deleteLocalLlmAssessment(entry.backend, entry.modelId, { silent: true });
+ setReport((prev) => (prev ? {
+ ...prev,
+ ranked: prev.ranked.filter((r) => !(r.backend === entry.backend && r.modelId === entry.modelId)),
+ assessments: prev.assessments.filter((a) => !(a.backend === entry.backend && a.modelId === entry.modelId)),
+ unassessed: [...prev.unassessed, { backend: entry.backend, modelId: entry.modelId, params: null }],
+ } : prev));
+ return true;
+ }, { errorMessage: 'Could not discard that measurement' });
+
+ const busy = running || removing;
+ const activeIntent = INTENTS.find((i) => i.id === intent);
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <div className="flex items-center gap-2">
+ <Gauge size={16} className="text-port-accent" />
+ <h2 className="text-sm font-medium text-gray-300">Measured Model Assessments</h2>
+ </div>
+ <button
+ onClick={() => load(intent)}
+ disabled={loading}
+ className="p-1.5 text-gray-400 hover:text-white transition-colors"
+ title="Refresh"
+ aria-label="Refresh model assessments"
+ >
+ <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />
+ </button>
+ </div>
+
+ <p className="text-xs text-gray-500">
+ The install catalog estimates fit from a model&apos;s file size. This measures it: one short
+ generation at each of several context lengths, recording throughput, time to first token, and how
+ far throughput falls off as context grows. Results stay on this machine — they describe this
+ hardware, so they are never synced to a peer.
+ </p>
+
+ <div className="flex items-center gap-2 flex-wrap">
+ <label htmlFor="assessment-intent" className="text-xs text-gray-400">Rank for</label>
+ <select
+ id="assessment-intent"
+ value={intent}
+ onChange={(e) => setIntent(e.target.value)}
+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white"
+ >
+ {INTENTS.map((i) => <option key={i.id} value={i.id}>{i.label}</option>)}
+ </select>
+ <span className="text-xs text-gray-500">{activeIntent?.blurb}</span>
+ </div>
+
+ {loading && !report ? (
+ <BrailleSpinner text="Loading assessments" />
+ ) : !report ? (
+ <p className="text-xs text-gray-500">Could not load assessments. Use Refresh to try again.</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 assessment will start a fresh record.
+ </p>
+ )}
+ {report.listErrors?.length > 0 && (
+ <p className="text-xs text-port-warning flex items-center gap-1.5" role="alert">
+ <AlertTriangle size={12} />
+ Could not list installed models for {report.listErrors.map((b) => BACKEND_LABEL[b] || b).join(' and ')} —
+ models there may be missing from this list.
+ </p>
+ )}
+
+ {report.ranked.length > 0 ? (
+ <div className="space-y-2">
+ {report.ranked.map((entry) => (
+ <RankedRow
+ key={`${entry.backend}:${entry.modelId}`}
+ entry={entry}
+ busy={busy}
+ onRemeasure={setPendingTarget}
+ onDelete={removeAssessment}
+ />
+ ))}
+ </div>
+ ) : (
+ <p className="text-xs text-gray-500">
+ Nothing measured yet. Pick a model below and run an assessment to see how it actually
+ performs here.
+ </p>
+ )}
+
+ {report.excluded?.length > 0 && (
+ <div className="space-y-1">
+ <h3 className="text-xs font-medium text-gray-400">Measured, but not recommended</h3>
+ {report.excluded.map((entry) => (
+ <div key={`${entry.backend}:${entry.modelId}`} className="flex items-center gap-2 text-xs flex-wrap">
+ <span className="text-gray-300 font-mono break-all">{entry.modelId}</span>
+ <VerdictPill verdict={entry.verdict} />
+ {entry.reason && <span className="text-gray-500">{entry.reason}</span>}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {report.unassessed?.length > 0 && (
+ <div className="space-y-1">
+ <h3 className="text-xs font-medium text-gray-400">
+ Not yet measured ({report.unassessed.length})
+ </h3>
+ <p className="text-[11px] text-gray-500">
+ No evidence recorded — that is not a mark against them, just an unanswered question.
+ </p>
+ <div className="space-y-1 pt-1">
+ {report.unassessed.map((entry) => (
+ <div key={`${entry.backend}:${entry.modelId}`} className="flex items-center justify-between gap-2 text-xs">
+ <span className="text-gray-300 font-mono break-all min-w-0">
+ {entry.modelId}
+ <span className="text-gray-600 ml-2">{BACKEND_LABEL[entry.backend] || entry.backend}</span>
+ </span>
+ <button
+ onClick={() => setPendingTarget(entry)}
+ disabled={busy}
+ className="flex items-center gap-1 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 shrink-0"
+ >
+ <Play size={11} /> Measure
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+ </>
+ )}
+
+ <AssessmentConsentModal
+ target={pendingTarget}
+ contextTokens={report?.defaultContextTokens || []}
+ running={running}
+ onCancel={() => (running ? null : setPendingTarget(null))}
+ onConfirm={confirmRun}
+ />
+ </div>
+ );
+}
+
+export default LocalModelAssessments;
diff --git a/client/src/components/settings/LocalModelAssessments.test.jsx b/client/src/components/settings/LocalModelAssessments.test.jsx
new file mode 100644
index 0000000000..57b87ef333
--- /dev/null
+++ b/client/src/components/settings/LocalModelAssessments.test.jsx
@@ -0,0 +1,169 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+vi.mock('../../services/api', () => ({
+ getLocalLlmAssessments: vi.fn(),
+ runLocalLlmAssessment: vi.fn(),
+ deleteLocalLlmAssessment: vi.fn(),
+}));
+
+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+
+import { getLocalLlmAssessments, runLocalLlmAssessment, deleteLocalLlmAssessment } from '../../services/api';
+import LocalModelAssessments from './LocalModelAssessments.jsx';
+
+const report = (overrides = {}) => ({
+ intent: 'balanced',
+ intents: ['balanced', 'smartest', 'fastest', 'lightweight'],
+ defaultContextTokens: [512, 4096, 16384],
+ assessments: [],
+ unassessed: [],
+ listErrors: [],
+ readError: null,
+ ranked: [],
+ excluded: [],
+ ...overrides,
+});
+
+const rankedEntry = (overrides = {}) => ({
+ backend: 'ollama',
+ modelId: 'example-model:7b',
+ verdict: 'fits',
+ score: 0.7,
+ coverage: 1,
+ scores: { capability: 0.5, speed: 0.6, fidelity: 0.9, memory: 0.8 },
+ performance: {
+ meanCharsPerSecond: 120,
+ meanTtftMs: 250,
+ maxWorkingContextTokens: 4096,
+ peakCharsPerSecond: 140,
+ contextDegradation: 0.85,
+ samplesRun: 3,
+ samplesOk: 3,
+ },
+ assessedAt: '2026-01-01T00:00:00.000Z',
+ explanation: '120 chars/s measured, ran at up to 4,096 tokens of context.',
+ ...overrides,
+});
+
+describe('LocalModelAssessments', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getLocalLlmAssessments.mockResolvedValue(report());
+ });
+
+ it('loads persisted results on mount without triggering any model run', async () => {
+ render(<LocalModelAssessments />);
+ await waitFor(() => expect(getLocalLlmAssessments).toHaveBeenCalled());
+ // The AI Provider Usage Policy boundary: mounting the panel must never
+ // reach a provider.
+ expect(runLocalLlmAssessment).not.toHaveBeenCalled();
+ });
+
+ it('renders measured numbers for a ranked model', async () => {
+ getLocalLlmAssessments.mockResolvedValue(report({ ranked: [rankedEntry()] }));
+ render(<LocalModelAssessments />);
+ expect(await screen.findByText('example-model:7b')).toBeInTheDocument();
+ expect(screen.getByText('120 chars/s')).toBeInTheDocument();
+ expect(screen.getByText('4k tokens')).toBeInTheDocument();
+ expect(screen.getByText('Fits')).toBeInTheDocument();
+ });
+
+ it('says "not measured" rather than showing a zero for an unmeasured field', async () => {
+ getLocalLlmAssessments.mockResolvedValue(report({
+ ranked: [rankedEntry({
+ residentGb: null,
+ performance: { ...rankedEntry().performance, meanCharsPerSecond: null, meanTtftMs: null },
+ scores: { capability: 0.5, speed: null, fidelity: null, memory: null },
+ })],
+ }));
+ render(<LocalModelAssessments />);
+ await screen.findByText('example-model:7b');
+ expect(screen.getAllByText('not measured').length).toBeGreaterThanOrEqual(3);
+ // An unmeasured axis renders as n/a, never as an empty bar that reads as 0.
+ expect(screen.getAllByText('n/a')).toHaveLength(3);
+ });
+
+ it('requires explicit consent naming the model and run count before running', async () => {
+ const user = userEvent.setup();
+ getLocalLlmAssessments.mockResolvedValue(report({
+ unassessed: [{ backend: 'ollama', modelId: 'example-model:7b', params: '7B' }],
+ }));
+ runLocalLlmAssessment.mockResolvedValue({ verdict: 'fits' });
+ render(<LocalModelAssessments />);
+
+ await user.click(await screen.findByRole('button', { name: /measure/i }));
+ // Nothing has been sent yet — the click opens the ask, it does not run.
+ expect(runLocalLlmAssessment).not.toHaveBeenCalled();
+ expect(screen.getByText(/Measure this model\?/)).toBeInTheDocument();
+ expect(screen.getByText(/3 times/)).toBeInTheDocument();
+ expect(screen.getByText(/512, 4k, 16k tokens of context/)).toBeInTheDocument();
+
+ await user.click(screen.getByRole('button', { name: /run assessment/i }));
+ await waitFor(() => expect(runLocalLlmAssessment).toHaveBeenCalledWith(
+ { backend: 'ollama', modelId: 'example-model:7b' },
+ { silent: true },
+ ));
+ });
+
+ it('does not run when the consent modal is cancelled', async () => {
+ const user = userEvent.setup();
+ getLocalLlmAssessments.mockResolvedValue(report({
+ unassessed: [{ backend: 'ollama', modelId: 'example-model:7b', params: '7B' }],
+ }));
+ render(<LocalModelAssessments />);
+
+ await user.click(await screen.findByRole('button', { name: /measure/i }));
+ await user.click(screen.getByRole('button', { name: /cancel/i }));
+ expect(runLocalLlmAssessment).not.toHaveBeenCalled();
+ await waitFor(() => expect(screen.queryByText(/Measure this model\?/)).not.toBeInTheDocument());
+ });
+
+ it('presents unmeasured models as an open question, not as a poor choice', async () => {
+ getLocalLlmAssessments.mockResolvedValue(report({
+ unassessed: [{ backend: 'lmstudio', modelId: 'example-model:14b', params: '14B' }],
+ }));
+ render(<LocalModelAssessments />);
+ expect(await screen.findByText(/Not yet measured \(1\)/)).toBeInTheDocument();
+ expect(screen.getByText(/not a mark against them/)).toBeInTheDocument();
+ });
+
+ it('refetches for the selected intent', async () => {
+ const user = userEvent.setup();
+ render(<LocalModelAssessments />);
+ await waitFor(() => expect(getLocalLlmAssessments).toHaveBeenCalledWith('balanced', { silent: true }));
+ await user.selectOptions(screen.getByLabelText('Rank for'), 'fastest');
+ await waitFor(() => expect(getLocalLlmAssessments).toHaveBeenCalledWith('fastest', { silent: true }));
+ });
+
+ it('drops a discarded measurement from local state and returns it to the unmeasured list', async () => {
+ const user = userEvent.setup();
+ getLocalLlmAssessments.mockResolvedValue(report({
+ ranked: [rankedEntry()],
+ assessments: [{ backend: 'ollama', modelId: 'example-model:7b' }],
+ }));
+ deleteLocalLlmAssessment.mockResolvedValue({ success: true });
+ render(<LocalModelAssessments />);
+
+ await user.click(await screen.findByRole('button', { name: /discard the measurement/i }));
+ await waitFor(() => expect(screen.getByText(/Not yet measured \(1\)/)).toBeInTheDocument());
+ expect(deleteLocalLlmAssessment).toHaveBeenCalledWith('ollama', 'example-model:7b', { silent: true });
+ });
+
+ it('explains a model that ran but was excluded from the ranking', async () => {
+ getLocalLlmAssessments.mockResolvedValue(report({
+ excluded: [{ backend: 'ollama', modelId: 'example-model:70b', verdict: 'does-not-fit', reason: 'out of memory' }],
+ }));
+ render(<LocalModelAssessments />);
+ expect(await screen.findByText('example-model:70b')).toBeInTheDocument();
+ expect(screen.getByText('Does not fit')).toBeInTheDocument();
+ expect(screen.getByText('out of memory')).toBeInTheDocument();
+ });
+
+ it('warns when a backend model list could not be read instead of implying it is empty', async () => {
+ getLocalLlmAssessments.mockResolvedValue(report({ listErrors: ['lmstudio'] }));
+ render(<LocalModelAssessments />);
+ expect(await screen.findByText(/Could not list installed models for LM Studio/)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 13bd36912e..5ab86e7549 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -45,7 +45,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiCommands.js` | CLI command dispatch. |
| `apiDashboard.js` | Dashboard state. |
| `apiDatabase.js` | Database introspection. |
-| `apiLocalLlm.js` | Local LLM backends (Ollama / LM Studio): status (incl. installed models), catalog, model install/delete, backend install (Homebrew/script), switch/migrate. |
+| `apiLocalLlm.js` | Local LLM backends (Ollama / LM Studio): status (incl. installed models), catalog, model install/delete, backend install (Homebrew/script), switch/migrate, playground test/compare, and measured per-model assessments (run + persisted results + intent ranking). |
| `apiGit.js` | Git operations. |
| `apiGithub.js` | GitHub repo metadata. |
| `apiHistory.js` | Historical logs / runs. |
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index 4c699a16f7..0b26c60fea 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -147,3 +147,24 @@ export async function streamLocalLlmTest(payload, { signal, onToken } = {}) {
if (!result && !signal?.aborted) throw new Error('Stream ended before a result was received');
return result;
}
+
+// === Measured local-model assessments ========================================
+// The catalog fit badge is a size estimate; these run the model and record what
+// it actually did. GET is disk-only and safe to call on mount; the run endpoint
+// calls a provider and must only fire from a deliberate user action (root
+// CLAUDE.md, "AI Provider Usage Policy").
+
+// Persisted assessments + the intent-ranked recommendation + which installed
+// models have no evidence yet. Zero LLM calls, so it's safe to load with the tab.
+export const getLocalLlmAssessments = (intent = 'balanced', options) =>
+ request(`/local-llm/assessments?intent=${encodeURIComponent(intent)}`, options);
+
+// Measure ONE model. Minutes-long by nature (one bounded generation per context
+// size), so callers pass a `signal` to abort when the user navigates away.
+export const runLocalLlmAssessment = (payload, options) =>
+ request('/local-llm/assessments/run', { method: 'POST', body: JSON.stringify(payload), ...options });
+
+// Drop a stale measurement — after a RAM upgrade or a backend update the
+// recorded evidence describes a machine that no longer exists.
+export const deleteLocalLlmAssessment = (backend, modelId, options) =>
+ request('/local-llm/assessments/delete', { method: 'POST', body: JSON.stringify({ backend, modelId }), ...options });
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 8093d81dec..432df42e96 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -60,6 +60,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.
- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + ordered job list. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and the plan's `agent-prompt` jobs name managed apps that only exist on this machine. No sync cursor, no tombstone. Its four companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight), and `data/cos/quota-burn-denials.json` (per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL — deleting it only risks one dispatch into a still-exhausted window). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).
- YouTube brain ingests — `data/brain/youtube/{videoId}.md` (transcript), `{videoId}.mp3` (optional audio), plus `data/brain/youtube/index.json` (the ingest index) and `data/brain/youtube-ingest-settings.json`. The transcript IS an external file: it is mirrored into the user's Obsidian vault, edited there, and syncs through iCloud — the same boundary that keeps the Daily Log file-backed. The index is **intentionally machine-local — never federated**: every field in it is a local filesystem path, an Obsidian vault id, or a local video-history id, so a peer's copy would be meaningless and would poison brain reconcile exactly the way the daily log's `journal-obsidian-locations.json` sidecar would. The durable, federated record of "I consumed and kept this" is the brain `links` entry (`db-primary` via the brain store) plus a `media.watch` row in `human_activity_events`. No sync cursor, no tombstone. Adapter: `server/services/youtubeIngest.js`.
+- Local-model assessments — `data/local-llm/assessments.json` (#4539). Measured evidence for one installed local model per (backend, model): the fit verdict (`fits`/`does-not-fit`/`incompatible`/`unknown`), per-context throughput/TTFT samples, resident footprint, and the coarse hardware environment the measurement was taken in. `file-primary` — a flat, capped, single-JSON projection with no cross-record queries and no relationships; the newest measurement replaces the old one per model rather than accumulating history. **Intentionally machine-local — never federated**: an assessment is a claim about THIS box, so a peer inheriting a 128 GB machine's its verdict for its 8 GB laptop would be actively wrong. No sync cursor, no tombstone, no `PORTOS_SCHEMA_VERSIONS` entry. Backed up (a run costs the user minutes of local compute), and the environment record deliberately carries no hostname/username/path. Adapter: `server/services/localModelAssessments.js`; scoring in `server/lib/localModelAssessment.js`.
- LoRA training datasets — `data/lora-datasets/{id}/index.json` + `images/*.png` (collectionStore). The record is inseparable from the image bytes it organizes, has no cross-record queries beyond a small characterId scan, and is **machine-local** like `data/loras/` itself (training artifacts tied to this machine's GPU output — never federates, no sync cursor/tombstone). Backed up in full: uploads and hand-edited captions are not re-creatable. Training RUN records are `db-primary` (`lora_training_runs`); run artifacts (checkpoints/samples) live under `data/training-runs/{runId}/` with checkpoints/cache excluded from backup.
---
diff --git a/server/lib/README.md b/server/lib/README.md
index fbfb8e450b..12df2c42ca 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -292,6 +292,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection) plus the Hugging Face registry addressing used to finish an abandoned Ollama pull. |
| `ollamaContext.js` | Ollama runtime context-window reasoning. `resolveOllamaContextLength(provider, env)` → the window PortOS should hold the daemon at (`provider.numCtx`, then `OLLAMA_CONTEXT_LENGTH`, then `null` = leave Ollama's VRAM-based auto-pick alone); `withOllamaContextEnv(env, n)` builds the `ollama serve` child env; `parseOllamaContextOverflow(text)` recognizes the `exceed_context_size_error` rejection and pulls `{ promptTokens, contextLength }` out of either the JSON body or the human message; `describeOllamaContextOverflow` / `describeOllamaContextTooSmall` render the actionable one-liners; `isSameOllamaDaemon(providerBase, managedBase)` compares host+port so a provider pointed at a *remote* Ollama never triggers a local-daemon reload; `OLLAMA_AGENT_MIN_CONTEXT` is the window below which an agent harness is warned. Pure — the daemon side lives in `services/ollamaManager.js` (`ensureContextWindow`), the pre-spawn enforcement in `services/ollamaAgentContext.js`. |
| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. |
+| `localModelAssessment.js` | Scoring for MEASURED local-model assessments (recorded by `services/localModelAssessments.js`): `classifyFitVerdict` (`fits`/`does-not-fit`/`incompatible`/`unknown`), `summarizePerformance` (mean/peak chars-per-second, TTFT, max working context, cross-context degradation), `scoreAssessment` + `scoreForIntent` + `rankByIntent` for the balanced/smartest/fastest/lightweight pickers, and `explainAssessment`. Pure. `null` strictly means NOT MEASURED — never 0, never "failed". |
| `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |
| `issueLength.js` | Per-issue size targets fed into text stages. |
| `musicDuration.js` | Lyric-aware MiniMax Music 3 duration analysis and ending-cushioned auto-duration recommendation; mirrors `client/src/lib/musicDuration.js`. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 93d7aa8c6a..28e467199c 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -270,6 +270,7 @@ export * from './huggingfaceModel.js';
export * from './localLlmCatalog.js';
export * from './localLlmDisk.js';
export * from './localModelHeuristics.js';
+export * from './localModelAssessment.js';
export * from './ollamaContext.js';
export * from './loraDataset.js';
export * from './issueLength.js';
diff --git a/server/lib/localModelAssessment.js b/server/lib/localModelAssessment.js
new file mode 100644
index 0000000000..3a4be9e15b
--- /dev/null
+++ b/server/lib/localModelAssessment.js
@@ -0,0 +1,329 @@
+/**
+ * Local-model assessment scoring — pure, dependency-free.
+ *
+ * PortOS already guesses whether a local model fits from catalog metadata alone
+ * (weight bytes × a fixed overhead multiplier, in `huggingFaceCatalog.js`). That
+ * guess never touches the machine: it can't tell a model that loads and streams
+ * fast from one that loads, thrashes, and crawls, and it says
+ * nothing at all about how a model behaves as the prompt gets long.
+ *
+ * This module turns *measured* evidence — one bounded generation per context
+ * length, recorded by `services/localModelAssessments.js` — into an explainable
+ * verdict and an intent-specific ranking.
+ *
+ * ## The sentinel contract (read before touching anything here)
+ *
+ * `null` means NOT MEASURED. It never means zero, never means failed, and never
+ * collapses into a fallback. `[]` / `0` mean measured-and-empty. Concretely:
+ *
+ * - `sample.charsPerSecond === null` → the sample never produced timings
+ * - `sample.ok === false` → the sample RAN and FAILED (has `error`)
+ * - `verdict === 'unknown'` → nothing usable was measured
+ * - `scores.speed === null` → speed was never observed; a ranking
+ * must not treat that as "slow"
+ *
+ * Anything that conflates those makes an unassessed model look worse than a
+ * measured-bad one, which is the exact failure this feature exists to remove.
+ */
+
+/**
+ * Fit verdicts. Deliberately four values, not a boolean:
+ * - `fits` — at least one context length generated successfully
+ * - `does-not-fit` — every attempted context length failed for a resource
+ * reason (OOM / load failure / timeout)
+ * - `incompatible` — the backend refused the model outright (wrong format,
+ * unsupported architecture) — retrying with less context
+ * or more RAM will not help
+ * - `unknown` — nothing was measured
+ */
+export const FIT_VERDICTS = ['fits', 'does-not-fit', 'incompatible', 'unknown'];
+
+/** Ranking intents, mirroring how people actually pick a local model. */
+export const ASSESSMENT_INTENTS = ['balanced', 'smartest', 'fastest', 'lightweight'];
+
+// Error text that means "this model can never run here", as opposed to "this
+// model ran out of room at this context length". Matched case-insensitively
+// against the sample error. Kept narrow on purpose: a false `incompatible`
+// permanently hides a model that a smaller context would have run.
+const INCOMPATIBLE_RE =
+ /unsupported|unknown model architecture|unrecognized|not supported|invalid model file|no such file|unsupported model format|does not support/i;
+
+// Error text that means "resource exhaustion at this size" — the model itself is
+// fine, this machine could not hold it as configured.
+const RESOURCE_RE =
+ /out of memory|oom|cannot allocate|insufficient memory|not enough memory|resource exhausted|model requires more system memory|timed out|context (?:length|window) exceed/i;
+
+/**
+ * Classify one recorded sample's failure. Returns `null` for a sample that
+ * succeeded or that carries no error text (unknown cause — never guessed at).
+ *
+ * @param {{ ok?: boolean, error?: string }} sample
+ * @returns {'incompatible'|'resource'|null}
+ */
+export function classifySampleFailure(sample) {
+ if (!sample || sample.ok !== false) return null;
+ const error = typeof sample.error === 'string' ? sample.error : '';
+ if (!error) return null;
+ if (INCOMPATIBLE_RE.test(error)) return 'incompatible';
+ if (RESOURCE_RE.test(error)) return 'resource';
+ return null;
+}
+
+const isMeasured = (value) => typeof value === 'number' && Number.isFinite(value);
+
+/** Samples that actually produced output. */
+const okSamples = (samples) => (Array.isArray(samples) ? samples : []).filter((s) => s?.ok === true);
+
+/**
+ * Derive the fit verdict from the recorded samples.
+ *
+ * One success anywhere is enough for `fits` — a model that runs at 4k but dies
+ * at 32k still fits this machine, and `maxWorkingContextTokens` (below) is what
+ * carries the nuance. `incompatible` wins over `does-not-fit` because it is the
+ * actionable one: no amount of freed memory changes it.
+ *
+ * @param {Array<{ ok?: boolean, error?: string }>} samples
+ * @returns {'fits'|'does-not-fit'|'incompatible'|'unknown'}
+ */
+export function classifyFitVerdict(samples) {
+ const list = Array.isArray(samples) ? samples : [];
+ if (list.length === 0) return 'unknown';
+ if (list.some((s) => s?.ok === true)) return 'fits';
+ const failures = list.map(classifySampleFailure);
+ if (failures.some((f) => f === 'incompatible')) return 'incompatible';
+ if (failures.some((f) => f === 'resource')) return 'does-not-fit';
+ // Ran, failed, and we can't say why (network blip, backend restart). That is
+ // NOT evidence the model doesn't fit — leave it unknown so a re-run decides.
+ return 'unknown';
+}
+
+/**
+ * Largest context length that produced a successful generation.
+ * `null` when nothing succeeded — distinct from `0`, which never occurs here.
+ *
+ * @param {Array<{ ok?: boolean, contextTokens?: number }>} samples
+ * @returns {number|null}
+ */
+export function maxWorkingContextTokens(samples) {
+ const working = okSamples(samples)
+ .map((s) => s.contextTokens)
+ .filter(isMeasured);
+ return working.length ? Math.max(...working) : null;
+}
+
+/**
+ * Mean of a numeric field across successful samples, or `null` when the field
+ * was never measured. Rounded to two decimals so persisted records stay stable.
+ */
+function meanOf(samples, field) {
+ const values = okSamples(samples).map((s) => s[field]).filter(isMeasured);
+ if (!values.length) return null;
+ const mean = values.reduce((sum, v) => sum + v, 0) / values.length;
+ return Number(mean.toFixed(2));
+}
+
+/**
+ * Collapse the per-context samples into one performance summary.
+ *
+ * `contextDegradation` is the ratio of the slowest measured throughput to the
+ * fastest (0..1]; 1 means throughput held flat across every context length,
+ * 0.25 means the longest context ran at a quarter of the shortest. `null` when
+ * fewer than two context lengths produced throughput — a single sample cannot
+ * describe a trend, and reporting `1` there would fake perfect scaling.
+ *
+ * @param {Array<object>} samples
+ */
+export function summarizePerformance(samples) {
+ const throughputs = okSamples(samples).map((s) => s.charsPerSecond).filter((v) => isMeasured(v) && v > 0);
+ const fastest = throughputs.length ? Math.max(...throughputs) : null;
+ const slowest = throughputs.length ? Math.min(...throughputs) : null;
+ return {
+ samplesRun: Array.isArray(samples) ? samples.length : 0,
+ samplesOk: okSamples(samples).length,
+ meanCharsPerSecond: meanOf(samples, 'charsPerSecond'),
+ meanTtftMs: meanOf(samples, 'ttftMs'),
+ peakCharsPerSecond: fastest,
+ maxWorkingContextTokens: maxWorkingContextTokens(samples),
+ contextDegradation:
+ throughputs.length >= 2 && fastest > 0 ? Number((slowest / fastest).toFixed(3)) : null,
+ };
+}
+
+// Speed normalization anchor, in CHARACTERS per second — the unit PortOS
+// actually measures (`localLlmPlayground.summarizeTimings`). There is no
+// tokenizer anywhere in the repo, so reporting a tokens/sec figure would be an
+// invented number dressed as a measurement. 240 chars/s (~60 tok/s at the
+// conventional ~4 chars/token) is a comfortable interactive rate on consumer
+// hardware; at or above it the axis scores 1, below it the score is linear so a
+// crawling model reads as clearly worse rather than both bottoming out.
+const SPEED_CEILING_CHARS_PER_SECOND = 240;
+
+// Parameter-count anchor for the capability score. Local models above ~70B are
+// rare on consumer hardware and already score at the top of the curve.
+const PARAMS_CEILING_B = 70;
+
+const clamp01 = (v) => Math.min(1, Math.max(0, v));
+
+/**
+ * Parse a parameter count in billions out of a params string or model id
+ * (`"32B"`, `"qwen3:14b"`). `null` when the id carries no size marker — never
+ * defaulted, so an unsized model doesn't masquerade as a small one.
+ *
+ * @param {{ params?: string, modelId?: string }} model
+ * @returns {number|null}
+ */
+export function parseParamsBillions({ params, modelId } = {}) {
+ const match = `${params || ''} ${modelId || ''}`.match(/(\d+(?:\.\d+)?)\s*[bB]\b/);
+ return match ? Number(match[1]) : null;
+}
+
+/**
+ * Score one assessment on the four axes the ranking uses. Every axis is `null`
+ * when its evidence is missing — callers must handle that rather than
+ * substituting 0.
+ *
+ * - `capability` — parameter count, the only capability proxy available offline
+ * - `speed` — measured mean throughput against the interactive anchor
+ * - `fidelity` — how well throughput held up as context grew (needs ≥2 samples)
+ * - `memory` — measured headroom left after the model's resident footprint
+ *
+ * @param {object} assessment
+ * @returns {{capability:number|null, speed:number|null, fidelity:number|null, memory:number|null}}
+ */
+export function scoreAssessment(assessment) {
+ const perf = assessment?.performance || {};
+ const paramsB = parseParamsBillions({ params: assessment?.params, modelId: assessment?.modelId });
+ const residentGb = assessment?.residentGb;
+ const budgetGb = assessment?.environment?.memoryBudgetGb;
+
+ const memory =
+ isMeasured(residentGb) && isMeasured(budgetGb) && budgetGb > 0
+ ? clamp01(1 - residentGb / budgetGb)
+ : null;
+
+ return {
+ capability: paramsB == null ? null : clamp01(Math.log10(1 + paramsB) / Math.log10(1 + PARAMS_CEILING_B)),
+ speed: isMeasured(perf.meanCharsPerSecond) ? clamp01(perf.meanCharsPerSecond / SPEED_CEILING_CHARS_PER_SECOND) : null,
+ fidelity: isMeasured(perf.contextDegradation) ? clamp01(perf.contextDegradation) : null,
+ memory,
+ };
+}
+
+// Per-intent axis weights. Weights of axes with no measurement are dropped and
+// the rest renormalized, so a partly-measured model is scored on what IS known
+// instead of being penalized for the gap. `coverage` reports how much of the
+// intended weight was actually backed by evidence, and the caller surfaces it.
+const INTENT_WEIGHTS = {
+ balanced: { capability: 0.3, speed: 0.3, fidelity: 0.2, memory: 0.2 },
+ smartest: { capability: 0.6, speed: 0.1, fidelity: 0.2, memory: 0.1 },
+ fastest: { capability: 0.1, speed: 0.6, fidelity: 0.2, memory: 0.1 },
+ lightweight: { capability: 0.1, speed: 0.25, fidelity: 0.15, memory: 0.5 },
+};
+
+/**
+ * Weighted score for one intent.
+ *
+ * @param {object} scores from `scoreAssessment`
+ * @param {string} intent one of ASSESSMENT_INTENTS
+ * @returns {{ score: number|null, coverage: number }} `score` is null when NO
+ * axis was measured — an unassessed model must not be rankable as "0".
+ */
+export function scoreForIntent(scores, intent) {
+ const weights = INTENT_WEIGHTS[intent] || INTENT_WEIGHTS.balanced;
+ let weighted = 0;
+ let used = 0;
+ for (const [axis, weight] of Object.entries(weights)) {
+ const value = scores?.[axis];
+ if (!isMeasured(value)) continue;
+ weighted += value * weight;
+ used += weight;
+ }
+ if (used === 0) return { score: null, coverage: 0 };
+ return { score: Number((weighted / used).toFixed(4)), coverage: Number(used.toFixed(2)) };
+}
+
+const INTENT_LABEL = {
+ balanced: 'balanced',
+ smartest: 'strongest',
+ fastest: 'fastest',
+ lightweight: 'lightest',
+};
+
+/**
+ * One-sentence, evidence-only explanation for a ranked candidate. Every clause
+ * names a measured number; unmeasured axes are simply omitted rather than
+ * described with a guess.
+ */
+export function explainAssessment(assessment, intent) {
+ const perf = assessment?.performance || {};
+ const parts = [];
+ if (isMeasured(perf.meanCharsPerSecond)) parts.push(`${perf.meanCharsPerSecond} chars/s measured`);
+ if (isMeasured(perf.maxWorkingContextTokens)) {
+ parts.push(`ran at up to ${perf.maxWorkingContextTokens.toLocaleString('en-US')} tokens of context`);
+ }
+ if (isMeasured(perf.contextDegradation)) {
+ parts.push(`held ${Math.round(perf.contextDegradation * 100)}% of peak throughput at its longest context`);
+ }
+ if (isMeasured(assessment?.residentGb)) parts.push(`${assessment.residentGb} GB resident`);
+ if (!parts.length) return `No measurements recorded yet — run an assessment to rank it for ${INTENT_LABEL[intent] || intent} use.`;
+ return `${parts.join(', ')}.`;
+}
+
+/**
+ * Rank assessed models for one intent.
+ *
+ * Only `fits` candidates are ranked — a model that did not run is not a
+ * recommendation, however good its metadata looks. Everything else is returned
+ * under `excluded` with its verdict so the UI can explain the absence instead
+ * of silently dropping it.
+ *
+ * @param {Array<object>} assessments
+ * @param {string} intent
+ * @returns {{ intent: string, ranked: Array<object>, excluded: Array<object> }}
+ */
+export function rankByIntent(assessments, intent = 'balanced') {
+ const resolvedIntent = ASSESSMENT_INTENTS.includes(intent) ? intent : 'balanced';
+ const list = Array.isArray(assessments) ? assessments : [];
+
+ const ranked = [];
+ const excluded = [];
+ for (const assessment of list) {
+ const verdict = assessment?.verdict || 'unknown';
+ if (verdict !== 'fits') {
+ excluded.push({
+ backend: assessment?.backend || null,
+ modelId: assessment?.modelId || null,
+ verdict,
+ reason: assessment?.verdictReason || null,
+ });
+ continue;
+ }
+ const scores = scoreAssessment(assessment);
+ const { score, coverage } = scoreForIntent(scores, resolvedIntent);
+ if (score == null) {
+ excluded.push({
+ backend: assessment?.backend || null,
+ modelId: assessment?.modelId || null,
+ verdict,
+ reason: 'ran, but no axis of this intent was measured',
+ });
+ continue;
+ }
+ ranked.push({
+ backend: assessment?.backend || null,
+ modelId: assessment?.modelId || null,
+ verdict,
+ score,
+ coverage,
+ scores,
+ performance: assessment?.performance || null,
+ assessedAt: assessment?.assessedAt || null,
+ explanation: explainAssessment(assessment, resolvedIntent),
+ });
+ }
+
+ // Higher score first; ties broken by evidence coverage so a fully-measured
+ // model outranks one scored on a single axis, then by model id for stability.
+ ranked.sort((a, b) => (b.score - a.score) || (b.coverage - a.coverage) || String(a.modelId).localeCompare(String(b.modelId)));
+ return { intent: resolvedIntent, ranked, excluded };
+}
diff --git a/server/lib/localModelAssessment.test.js b/server/lib/localModelAssessment.test.js
new file mode 100644
index 0000000000..421eec3446
--- /dev/null
+++ b/server/lib/localModelAssessment.test.js
@@ -0,0 +1,277 @@
+import { describe, it, expect } from 'vitest';
+import {
+ ASSESSMENT_INTENTS,
+ FIT_VERDICTS,
+ classifyFitVerdict,
+ classifySampleFailure,
+ explainAssessment,
+ maxWorkingContextTokens,
+ parseParamsBillions,
+ rankByIntent,
+ scoreAssessment,
+ scoreForIntent,
+ summarizePerformance,
+} from './localModelAssessment.js';
+
+const okSample = (contextTokens, charsPerSecond, ttftMs = 300) => ({
+ contextTokens, ok: true, charsPerSecond, ttftMs, totalMs: 1000, chars: 40, error: null,
+});
+const failSample = (contextTokens, error) => ({
+ contextTokens, ok: false, charsPerSecond: null, ttftMs: null, totalMs: null, chars: null, error,
+});
+
+describe('classifySampleFailure', () => {
+ it('returns null for a sample that succeeded', () => {
+ expect(classifySampleFailure(okSample(512, 100))).toBeNull();
+ });
+
+ it('distinguishes an architecture refusal from resource exhaustion', () => {
+ expect(classifySampleFailure(failSample(512, 'unknown model architecture: mamba2'))).toBe('incompatible');
+ expect(classifySampleFailure(failSample(512, 'model requires more system memory (42.0 GiB) than is available'))).toBe('resource');
+ });
+
+ it('treats a timeout as resource exhaustion, not incompatibility', () => {
+ expect(classifySampleFailure(failSample(16384, 'Timed out after 120000ms'))).toBe('resource');
+ });
+
+ it('refuses to guess when the failure carries no error text', () => {
+ // A failed sample with no message is NOT evidence of anything — guessing
+ // here would produce a permanent `does-not-fit` from a transient blip.
+ expect(classifySampleFailure({ ok: false })).toBeNull();
+ expect(classifySampleFailure({ ok: false, error: 'connection reset by peer' })).toBeNull();
+ });
+});
+
+describe('classifyFitVerdict', () => {
+ it('is unknown with no samples — never "does not fit"', () => {
+ expect(classifyFitVerdict([])).toBe('unknown');
+ expect(classifyFitVerdict(undefined)).toBe('unknown');
+ });
+
+ it('fits when any context length succeeded, even if a larger one failed', () => {
+ const samples = [okSample(512, 120), okSample(4096, 60), failSample(16384, 'out of memory')];
+ expect(classifyFitVerdict(samples)).toBe('fits');
+ });
+
+ it('reports incompatible ahead of does-not-fit — it is the actionable one', () => {
+ const samples = [failSample(512, 'cannot allocate memory'), failSample(4096, 'unsupported model format')];
+ expect(classifyFitVerdict(samples)).toBe('incompatible');
+ });
+
+ it('reports does-not-fit only when a failure is identifiably about resources', () => {
+ expect(classifyFitVerdict([failSample(512, 'not enough memory to load model')])).toBe('does-not-fit');
+ });
+
+ it('stays unknown when every run failed for an unattributable reason', () => {
+ // A network blip is not evidence about hardware fit. Collapsing it into
+ // does-not-fit would permanently mislabel a perfectly good model.
+ expect(classifyFitVerdict([failSample(512, 'socket hang up')])).toBe('unknown');
+ });
+
+ it('only ever emits documented verdicts', () => {
+ const cases = [[], [okSample(1, 1)], [failSample(1, 'oom')], [failSample(1, 'unsupported')], [failSample(1, '?')]];
+ for (const samples of cases) expect(FIT_VERDICTS).toContain(classifyFitVerdict(samples));
+ });
+});
+
+describe('maxWorkingContextTokens', () => {
+ it('reports the largest SUCCESSFUL context, ignoring failures at larger sizes', () => {
+ expect(maxWorkingContextTokens([okSample(512, 100), okSample(4096, 50), failSample(16384, 'oom')])).toBe(4096);
+ });
+
+ it('is null — not 0 — when nothing succeeded', () => {
+ expect(maxWorkingContextTokens([failSample(512, 'oom')])).toBeNull();
+ });
+});
+
+describe('summarizePerformance', () => {
+ it('averages only successful samples and reports the degradation trend', () => {
+ const perf = summarizePerformance([okSample(512, 200, 100), okSample(4096, 100, 400), failSample(16384, 'oom')]);
+ expect(perf.samplesRun).toBe(3);
+ expect(perf.samplesOk).toBe(2);
+ expect(perf.meanCharsPerSecond).toBe(150);
+ expect(perf.meanTtftMs).toBe(250);
+ expect(perf.peakCharsPerSecond).toBe(200);
+ expect(perf.contextDegradation).toBe(0.5);
+ });
+
+ it('does not fake a degradation trend from a single sample', () => {
+ // Reporting 1 here would claim "throughput held flat across contexts" on
+ // the strength of one data point.
+ expect(summarizePerformance([okSample(512, 200)]).contextDegradation).toBeNull();
+ });
+
+ it('reports nulls, not zeros, when nothing was measured', () => {
+ const perf = summarizePerformance([failSample(512, 'oom')]);
+ expect(perf.meanCharsPerSecond).toBeNull();
+ expect(perf.meanTtftMs).toBeNull();
+ expect(perf.peakCharsPerSecond).toBeNull();
+ expect(perf.maxWorkingContextTokens).toBeNull();
+ expect(perf.samplesOk).toBe(0);
+ });
+});
+
+describe('parseParamsBillions', () => {
+ it('reads a size from the params field or the model id', () => {
+ expect(parseParamsBillions({ params: '32B' })).toBe(32);
+ expect(parseParamsBillions({ modelId: 'example-model:14b' })).toBe(14);
+ expect(parseParamsBillions({ modelId: 'example-model:1.5b' })).toBe(1.5);
+ });
+
+ it('is null when no size marker exists — never defaulted to a small model', () => {
+ expect(parseParamsBillions({ modelId: 'example-model:latest' })).toBeNull();
+ expect(parseParamsBillions({})).toBeNull();
+ });
+});
+
+describe('scoreAssessment', () => {
+ const base = {
+ modelId: 'example-model:14b',
+ performance: { meanCharsPerSecond: 120, contextDegradation: 0.8 },
+ residentGb: 10,
+ environment: { memoryBudgetGb: 40 },
+ };
+
+ it('scores every axis that has evidence', () => {
+ const scores = scoreAssessment(base);
+ expect(scores.capability).toBeGreaterThan(0);
+ expect(scores.speed).toBeCloseTo(0.5, 5);
+ expect(scores.fidelity).toBeCloseTo(0.8, 5);
+ expect(scores.memory).toBeCloseTo(0.75, 5);
+ });
+
+ it('caps speed at the interactive anchor rather than rewarding runaway numbers', () => {
+ expect(scoreAssessment({ ...base, performance: { meanCharsPerSecond: 5000 } }).speed).toBe(1);
+ });
+
+ it('leaves an unmeasured axis null instead of scoring it 0', () => {
+ const scores = scoreAssessment({ modelId: 'example-model:latest', performance: {}, environment: {} });
+ expect(scores.capability).toBeNull();
+ expect(scores.speed).toBeNull();
+ expect(scores.fidelity).toBeNull();
+ expect(scores.memory).toBeNull();
+ });
+
+ it('leaves memory null when the budget probe failed, rather than assuming no headroom', () => {
+ expect(scoreAssessment({ ...base, environment: { memoryBudgetGb: null } }).memory).toBeNull();
+ });
+});
+
+describe('scoreForIntent', () => {
+ const full = { capability: 0.5, speed: 0.5, fidelity: 0.5, memory: 0.5 };
+
+ it('produces the same score for uniform axes under every intent', () => {
+ for (const intent of ASSESSMENT_INTENTS) {
+ expect(scoreForIntent(full, intent).score).toBeCloseTo(0.5, 5);
+ }
+ });
+
+ it('weights the intent it is asked for', () => {
+ const fast = { capability: 0, speed: 1, fidelity: 0, memory: 0 };
+ expect(scoreForIntent(fast, 'fastest').score).toBeGreaterThan(scoreForIntent(fast, 'smartest').score);
+ });
+
+ it('renormalizes over measured axes instead of penalizing missing evidence', () => {
+ // Speed-only evidence at 1.0 should score 1.0 — not 0.3 (its balanced
+ // weight), which would make a partly-measured model look mediocre.
+ const partial = { capability: null, speed: 1, fidelity: null, memory: null };
+ const result = scoreForIntent(partial, 'balanced');
+ expect(result.score).toBe(1);
+ expect(result.coverage).toBe(0.3);
+ });
+
+ it('is null — not 0 — when no axis was measured', () => {
+ expect(scoreForIntent({ capability: null, speed: null, fidelity: null, memory: null }, 'balanced'))
+ .toEqual({ score: null, coverage: 0 });
+ });
+
+ it('falls back to balanced weights for an unrecognized intent', () => {
+ expect(scoreForIntent(full, 'nonsense').score).toBeCloseTo(0.5, 5);
+ });
+});
+
+describe('explainAssessment', () => {
+ it('names only measured numbers', () => {
+ const text = explainAssessment({
+ performance: { meanCharsPerSecond: 120, maxWorkingContextTokens: 4096, contextDegradation: 0.8 },
+ residentGb: 10,
+ }, 'balanced');
+ expect(text).toContain('120 chars/s measured');
+ expect(text).toContain('4,096 tokens');
+ expect(text).toContain('80% of peak');
+ expect(text).toContain('10 GB resident');
+ });
+
+ it('omits an unmeasured axis rather than describing it', () => {
+ const text = explainAssessment({ performance: { meanCharsPerSecond: 120 }, residentGb: null }, 'fastest');
+ expect(text).toBe('120 chars/s measured.');
+ });
+
+ it('says so plainly when nothing was measured', () => {
+ expect(explainAssessment({ performance: {} }, 'smartest')).toMatch(/No measurements recorded/);
+ });
+});
+
+describe('rankByIntent', () => {
+ const assessment = (modelId, verdict, performance, extra = {}) => ({
+ backend: 'ollama',
+ modelId,
+ verdict,
+ performance,
+ environment: { memoryBudgetGb: 40 },
+ ...extra,
+ });
+
+ it('ranks a faster model first for "fastest" and a bigger one first for "smartest"', () => {
+ const models = [
+ assessment('example-small:7b', 'fits', { meanCharsPerSecond: 240, contextDegradation: 1 }, { residentGb: 5 }),
+ assessment('example-large:70b', 'fits', { meanCharsPerSecond: 30, contextDegradation: 1 }, { residentGb: 38 }),
+ ];
+ expect(rankByIntent(models, 'fastest').ranked[0].modelId).toBe('example-small:7b');
+ expect(rankByIntent(models, 'smartest').ranked[0].modelId).toBe('example-large:70b');
+ });
+
+ it('favors the lightest resident footprint for "lightweight"', () => {
+ const models = [
+ assessment('example-large:70b', 'fits', { meanCharsPerSecond: 60, contextDegradation: 1 }, { residentGb: 38 }),
+ assessment('example-small:7b', 'fits', { meanCharsPerSecond: 60, contextDegradation: 1 }, { residentGb: 5 }),
+ ];
+ expect(rankByIntent(models, 'lightweight').ranked[0].modelId).toBe('example-small:7b');
+ });
+
+ it('never ranks a model that did not run, and explains why it was left out', () => {
+ const models = [
+ assessment('example-model:70b', 'does-not-fit', { meanCharsPerSecond: null }, { verdictReason: 'out of memory' }),
+ assessment('example-model:7b', 'fits', { meanCharsPerSecond: 120, contextDegradation: 1 }, { residentGb: 5 }),
+ ];
+ const { ranked, excluded } = rankByIntent(models, 'balanced');
+ expect(ranked.map((r) => r.modelId)).toEqual(['example-model:7b']);
+ expect(excluded).toEqual([
+ { backend: 'ollama', modelId: 'example-model:70b', verdict: 'does-not-fit', reason: 'out of memory' },
+ ]);
+ });
+
+ it('excludes a "fits" model whose intent axes were never measured, rather than ranking it last', () => {
+ // Scoring it 0 would put a working-but-unmeasured model below a measured-bad
+ // one, which is the exact confusion this feature removes.
+ const models = [assessment('example-model:latest', 'fits', {})];
+ const { ranked, excluded } = rankByIntent(models, 'balanced');
+ expect(ranked).toEqual([]);
+ expect(excluded[0].reason).toMatch(/no axis of this intent was measured/);
+ });
+
+ it('breaks a score tie on evidence coverage, so a fully-measured model wins', () => {
+ const measured = assessment('example-b:7b', 'fits', { meanCharsPerSecond: 120, contextDegradation: 1 }, { residentGb: 20 });
+ const partial = assessment('example-a:7b', 'fits', { meanCharsPerSecond: 120 });
+ const { ranked } = rankByIntent([partial, measured], 'balanced');
+ expect(ranked[0].coverage).toBeGreaterThan(ranked[1].coverage);
+ });
+
+ it('is empty and safe on no input', () => {
+ expect(rankByIntent(undefined, 'balanced')).toEqual({ intent: 'balanced', ranked: [], excluded: [] });
+ });
+
+ it('falls back to the balanced intent for an unknown one', () => {
+ expect(rankByIntent([], 'nonsense').intent).toBe('balanced');
+ });
+});
diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.js
index 3dd0ff31a3..bb746a8821 100644
--- a/server/lib/mediaValidation.js
+++ b/server/lib/mediaValidation.js
@@ -175,6 +175,20 @@ export const localLlmTestSchema = localLlmPlaygroundOptionsSchema.extend({
modelId: localLlmModelIdSchema,
prompt: z.string().trim().min(1).max(50000),
});
+// Measured local-model assessment (server/services/localModelAssessments.js). One
+// request runs ONE model across up to 5 nominal context sizes; the cap keeps a
+// single user click from turning into an unbounded, minutes-long provider job.
+// 131072 is the largest context any shipped local model advertises.
+export const localLlmAssessmentRunSchema = z.object({
+ backend: localLlmBackendSchema,
+ modelId: localLlmModelIdSchema,
+ contextTokens: z.array(z.coerce.number().int().min(64).max(131072)).min(1).max(5).optional(),
+});
+export const localLlmAssessmentIntentSchema = z.object({
+ intent: z.enum(['balanced', 'smartest', 'fastest', 'lightweight']).optional().default('balanced'),
+});
+export const localLlmAssessmentDeleteSchema = localLlmInstallSchema;
+
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/routes/localLlm.js b/server/routes/localLlm.js
index e0b7b9d56f..03faaf940f 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -22,7 +22,10 @@ import {
localLlmOllamaServiceSchema,
localLlmHuggingFaceSearchSchema,
localLlmTestSchema,
- localLlmCompareSchema
+ localLlmCompareSchema,
+ localLlmAssessmentRunSchema,
+ localLlmAssessmentIntentSchema,
+ localLlmAssessmentDeleteSchema
} from '../lib/validation.js'
import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'
import { isAppleSilicon } from '../lib/platform.js'
@@ -33,6 +36,7 @@ import {
} from '../services/localLlm.js'
import { getSettings } from '../services/settings.js'
import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js'
+import { getAssessmentReport, runAssessment, deleteAssessment } from '../services/localModelAssessments.js'
import { listUserModels } from '../services/audioModels.js'
import { ENGINES } from '../services/pipeline/musicGen.js'
import { abortSignalFromResponse } from '../lib/requestAbort.js'
@@ -407,4 +411,41 @@ router.post('/compare', asyncHandler(async (req, res) => {
res.json(await compareLocalLlmModels({ ...body, signal: abortSignalFromResponse(res) }))
}))
+// === Measured local-model assessments ========================================
+// PortOS's catalog fit badge is a size estimate that never runs the model. These
+// endpoints back the measured alternative: run a model at several context sizes
+// and rank installed models on the evidence.
+//
+// The read/run split is the AI Provider Usage Policy boundary (root CLAUDE.md):
+// GET touches disk only and is safe to poll; POST /run is the ONLY path that
+// reaches a provider, and it fires solely from a deliberate user action whose
+// UI names the backend, model, and run count first. Do not add a boot hook, a
+// scheduler, or an "assess everything" sweep here.
+
+// GET /api/local-llm/assessments?intent=balanced — persisted results, the
+// intent-ranked recommendation, and which installed models have no evidence yet.
+// Zero LLM calls.
+router.get('/assessments', asyncHandler(async (req, res) => {
+ const { intent } = validateRequest(localLlmAssessmentIntentSchema, req.query)
+ res.json(await getAssessmentReport({ intent }))
+}))
+
+// POST /api/local-llm/assessments/run — measure ONE model. User-triggered only.
+// Long-running by nature (one bounded generation per context size), so the
+// client's abort signal is threaded through to stop mid-run on disconnect.
+router.post('/assessments/run', asyncHandler(async (req, res) => {
+ const { backend, modelId, contextTokens } = validateRequest(localLlmAssessmentRunSchema, req.body)
+ res.json(await runAssessment({ backend, modelId, contextTokens, signal: abortSignalFromResponse(res) }))
+}))
+
+// POST /api/local-llm/assessments/delete — drop one stale measurement (e.g. after
+// a RAM upgrade or a backend update makes the recorded evidence misleading).
+// 404s when nothing was removed rather than reporting a phantom success.
+router.post('/assessments/delete', asyncHandler(async (req, res) => {
+ const { backend, modelId } = validateRequest(localLlmAssessmentDeleteSchema, req.body)
+ const result = await deleteAssessment(backend, modelId)
+ if (!result.deleted) throw new ServerError('No assessment recorded for that model', { status: 404, context: { backend, modelId } })
+ res.json({ success: true, backend, modelId })
+}))
+
export default router
diff --git a/server/services/dataManager.js b/server/services/dataManager.js
index 77fd8f6fb4..8c05d31e36 100644
--- a/server/services/dataManager.js
+++ b/server/services/dataManager.js
@@ -74,6 +74,10 @@ export const CATEGORIES = {
'jira-reports': { label: 'Jira Reports', description: 'Generated Jira reports — regenerable from Jira', archivable: true, deletable: true, purgeScope: 'category' },
'loops': { label: 'Loops', description: 'Output history from scheduled loop runs', archivable: true, deletable: false },
'lora-datasets': { label: 'LoRA Datasets', description: 'Training images and captions for LoRA runs — uploaded source material, not regenerable', archivable: false, deletable: false },
+ // Measured local-model assessments. Deletable: every record is reproducible by
+ // re-running the assessment, and a stale one (taken before a RAM upgrade or a
+ // backend update) actively misleads the picker.
+ 'local-llm': { label: 'Local Model Assessments', description: 'Measured fit and performance results for installed local models — re-runnable, and stale after a hardware or backend change', archivable: true, deletable: true, purgeScope: 'category' },
'loras': { label: 'LoRAs', description: 'Trained LoRA adapters — excluded from backups and not regenerable without hours of GPU retraining', archivable: false, deletable: false },
'meatspace': { label: 'MeatSpace', description: 'Body metrics, blood tests, eyes', archivable: true, deletable: false },
'media-collections': { label: 'Media Collections', description: 'Media collection records', archivable: true, deletable: false },
diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.js
new file mode 100644
index 0000000000..174e700bfd
--- /dev/null
+++ b/server/services/localModelAssessments.js
@@ -0,0 +1,367 @@
+/**
+ * Measured local-model assessments — the run + durable store.
+ *
+ * PortOS's existing "does it fit" answer is a size estimate: weight bytes × 1.2
+ * against total RAM minus a reserve (`huggingFaceCatalog.js#classifyFit`). It
+ * never runs the model, so it cannot distinguish a model that loads and streams
+ * comfortably from one that loads, thrashes, and crawls — and it says nothing
+ * about how either behaves once the prompt is long.
+ *
+ * This service closes that gap by actually running the model: one bounded
+ * generation per context length, through the SAME provider seam the Local LLM
+ * playground uses (`localLlmPlayground.runLocalLlmTest`), recording throughput,
+ * time-to-first-token, resident footprint, and the environment the measurement
+ * was taken in. `lib/localModelAssessment.js` turns that evidence into a verdict
+ * and an intent-specific ranking.
+ *
+ * ## AI Provider Usage Policy (root CLAUDE.md) — read before editing
+ *
+ * Assessments call an LLM, so they are STRICTLY user-triggered. This module
+ * mirrors the `initDrillCache` / `requestCacheFill` split from
+ * `meatspacePostDrillCache.js`:
+ *
+ * - `loadAssessments()` / `getAssessmentReport()` read ONLY what is already on
+ * disk. Zero LLM calls. Safe from boot, from a poll, from anywhere.
+ * - `runAssessment()` is the only function that touches a provider, and it is
+ * reachable only from `POST /api/local-llm/assessments/run` — a deliberate
+ * user action whose UI names the backend, the model, and the number of runs
+ * before it fires.
+ *
+ * There is NO scheduler, NO boot hook, and NO "assess everything installed"
+ * background sweep. Do not add one: a fresh install must be silent on the LLM
+ * front until the user asks.
+ *
+ * ## Privacy
+ *
+ * The recorded environment is deliberately coarse — platform, arch, CPU count,
+ * total/available memory, backend name. It never captures a hostname, a
+ * username, a path, or any other machine identity, because assessments are
+ * user-visible and end up in bug reports.
+ *
+ * ## Storage (docs/STORAGE.md)
+ *
+ * `file-primary`, **intentionally machine-local — never federated.** An
+ * assessment is a statement about THIS machine's hardware; a peer's copy would
+ * be actively misleading (a peer's 8 GB laptop must not inherit a 128 GB box's
+ * "fits" verdict). No sync cursor, no tombstone, no schema-version entry.
+ */
+
+import { join } from 'path';
+import os from 'os';
+import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';
+import { getAvailableMemoryGb } from '../lib/localMemory.js';
+import {
+ ASSESSMENT_INTENTS,
+ classifyFitVerdict,
+ classifySampleFailure,
+ rankByIntent,
+ summarizePerformance,
+} from '../lib/localModelAssessment.js';
+import { runLocalLlmTest } from './localLlmPlayground.js';
+import { listModels } from './localLlm.js';
+import { getLoadedModels as getLoadedOllamaModels } from './ollamaManager.js';
+
+const ASSESSMENTS_DIR = join(PATHS.data, 'local-llm');
+const ASSESSMENTS_FILE = join(ASSESSMENTS_DIR, 'assessments.json');
+
+// Storage-layout version for the on-disk file. Bump only when the persisted
+// shape changes in a way a reader must branch on.
+const STORE_SCHEMA_VERSION = 1;
+
+const GB = 2 ** 30;
+
+// Nominal context sizes to sample, in approximate tokens. Three points is the
+// minimum that shows a TREND rather than a single data point, and the top of
+// the range is where a local model typically starts paging. Users can override
+// per run; the route caps the list so one request can't turn into a 20-run job.
+export const DEFAULT_CONTEXT_TOKENS = [512, 4096, 16384];
+
+// Conventional English chars-per-token ratio, used ONLY to size the filler
+// prompt for a requested nominal context. PortOS has no tokenizer, so nothing
+// downstream reports a token *measurement* — see the throughput unit note in
+// lib/localModelAssessment.js.
+const CHARS_PER_TOKEN = 4;
+
+// Each sample generates a short answer: the point is measuring prefill + decode
+// at a given context, not producing text. Small and fixed so throughput is
+// comparable across models and across context lengths.
+const SAMPLE_MAX_TOKENS = 96;
+
+// Per-sample ceiling. A model that cannot answer a trivial question within two
+// minutes at this context has, for assessment purposes, failed at it — the
+// timeout is recorded as a resource failure and the run moves on to the next
+// context rather than hanging the request.
+const SAMPLE_TIMEOUT_MS = 120000;
+
+const SAMPLE_SYSTEM_PROMPT =
+ 'You are being benchmarked. Answer the final question in one short sentence. Do not summarize the reference text.';
+
+// Deterministic filler, generated rather than stored, so a long context costs no
+// repository bytes. Distinct numbered lines (not one repeated line) keep a
+// backend's prefix cache from making a long prompt look artificially cheap.
+function buildFillerPrompt(contextTokens) {
+ const targetChars = Math.max(0, Math.round(contextTokens * CHARS_PER_TOKEN));
+ const lines = [];
+ let length = 0;
+ for (let n = 1; length < targetChars; n += 1) {
+ const line = `Reference item ${n}: a placeholder record used only to occupy context during measurement.\n`;
+ lines.push(line);
+ length += line.length;
+ }
+ return lines.join('');
+}
+
+/** The prompt for one sample: filler to fill the context, then a trivial question. */
+export function buildSamplePrompt(contextTokens) {
+ const filler = buildFillerPrompt(contextTokens);
+ return `${filler}\nIgnoring every reference item above, what is 2 + 2? Answer with the number only.`;
+}
+
+/**
+ * Coarse description of the machine the measurement was taken on. Deliberately
+ * carries NO machine identity (see the privacy note at the top of this file).
+ */
+export async function captureEnvironment() {
+ const totalGb = os.totalmem() / GB;
+ // `null` (not `0`) when the probe fails — an unknown budget must not read as
+ // "no memory available", which would make every model look like it fits
+ // nothing.
+ const availableGb = await getAvailableMemoryGb().catch(() => null);
+ return {
+ platform: os.platform(),
+ arch: os.arch(),
+ cpuCount: os.cpus()?.length ?? null,
+ totalMemoryGb: Number(totalGb.toFixed(1)),
+ availableMemoryGb: Number.isFinite(availableGb) ? Number(availableGb.toFixed(1)) : null,
+ // The budget the fit verdict is scored against: never more than what is
+ // actually free right now, never more than the box has.
+ memoryBudgetGb: Number.isFinite(availableGb)
+ ? Number(Math.min(totalGb, availableGb).toFixed(1))
+ : null,
+ };
+}
+
+// ---- store ------------------------------------------------------------------
+
+/**
+ * Read the persisted assessments. Disk only — never calls a provider, so this is
+ * safe from boot, a poll, or any read path.
+ *
+ * @returns {Promise<Array<object>>} `[]` means "no assessments recorded", which
+ * is a real, measured-empty answer — distinct from a read failure, which is
+ * surfaced by `loadStore().readError`.
+ */
+export async function loadAssessments() {
+ return (await loadStore()).assessments;
+}
+
+async function loadStore() {
+ const raw = await tryReadFile(ASSESSMENTS_FILE);
+ // Never read = an empty store, not an error: the file simply doesn't exist
+ // until the first assessment runs.
+ if (raw == null) return { schemaVersion: STORE_SCHEMA_VERSION, assessments: [], readError: null };
+ const parsed = safeJSONParse(raw, null);
+ if (!parsed || !Array.isArray(parsed.assessments)) {
+ // Present but unparseable is NOT an empty store — say so rather than
+ // silently reporting "nothing assessed" and letting a re-run overwrite it.
+ return { schemaVersion: STORE_SCHEMA_VERSION, assessments: [], readError: 'assessments file is unreadable or malformed' };
+ }
+ return { schemaVersion: parsed.schemaVersion ?? STORE_SCHEMA_VERSION, assessments: parsed.assessments, readError: null };
+}
+
+const assessmentKey = (backend, modelId) => `${backend}:${modelId}`;
+
+async function saveAssessment(assessment) {
+ const { assessments } = await loadStore();
+ const key = assessmentKey(assessment.backend, assessment.modelId);
+ // One record per (backend, model): the newest measurement supersedes the old
+ // one. History is not kept — a stale reading from a different memory state is
+ // worse than no reading, and the run is cheap to repeat.
+ const next = assessments.filter((a) => assessmentKey(a?.backend, a?.modelId) !== key);
+ next.push(assessment);
+ await ensureDir(ASSESSMENTS_DIR);
+ await atomicWrite(ASSESSMENTS_FILE, { schemaVersion: STORE_SCHEMA_VERSION, assessments: next });
+ return assessment;
+}
+
+/**
+ * Drop one recorded assessment. Returns whether a record was actually removed,
+ * so the caller can 404 rather than reporting a phantom success.
+ */
+export async function deleteAssessment(backend, modelId) {
+ const { assessments } = await loadStore();
+ const key = assessmentKey(backend, modelId);
+ const next = assessments.filter((a) => assessmentKey(a?.backend, a?.modelId) !== key);
+ if (next.length === assessments.length) return { deleted: false };
+ await ensureDir(ASSESSMENTS_DIR);
+ await atomicWrite(ASSESSMENTS_FILE, { schemaVersion: STORE_SCHEMA_VERSION, assessments: next });
+ console.log(`🧹 Local LLM: dropped assessment for ${backend}/${modelId}`);
+ return { deleted: true };
+}
+
+// ---- measurement ------------------------------------------------------------
+
+/**
+ * Turn one `runLocalLlmTest` result into a recorded sample.
+ *
+ * The distinction that matters: a run that produced no text is a FAILURE even
+ * when `runLocalLlmTest` resolved without an `error` (it resolves rather than
+ * throws on timeout). Recording it as a success with `charsPerSecond: 0` would
+ * feed a fabricated zero into the speed average.
+ */
+export function toSample(contextTokens, result) {
+ const timings = result?.timings || {};
+ const ok = !result?.error && typeof result?.text === 'string' && result.text.trim().length > 0;
+ return {
+ contextTokens,
+ ok,
+ // Every timing is null-or-measured; nothing is defaulted to 0.
+ charsPerSecond: ok && Number.isFinite(timings.charsPerSecond) ? timings.charsPerSecond : null,
+ ttftMs: ok && Number.isFinite(timings.ttftMs) ? timings.ttftMs : null,
+ totalMs: Number.isFinite(timings.totalMs) ? timings.totalMs : null,
+ chars: Number.isFinite(timings.chars) ? timings.chars : null,
+ error: result?.error || (ok ? null : 'model produced no output'),
+ };
+}
+
+/** Resident bytes for a model, from Ollama's `/api/ps`. `null` when unknown. */
+async function residentGbFor(backend, modelId) {
+ // Only Ollama reports a resident size (`/api/ps` → `size`). LM Studio's
+ // loaded-model listing carries no footprint, so the honest answer there is
+ // `null` — not a size copied from the weight file, which would silently
+ // re-introduce the estimate this feature exists to replace.
+ if (backend !== 'ollama') return null;
+ const loaded = await getLoadedOllamaModels().catch(() => []);
+ const match = loaded.find((m) => m?.id === modelId || m?.name === modelId);
+ const bytes = match?.size;
+ return Number.isFinite(bytes) && bytes > 0 ? Number((bytes / GB).toFixed(2)) : null;
+}
+
+// Human-readable reason behind a non-`fits` verdict, or `null` for `fits`.
+// Quotes the backend's own error where there is one — a verbatim OOM message is
+// far more actionable than a paraphrase.
+function describeVerdict(verdict, samples) {
+ if (verdict === 'fits') return null;
+ const backendError = samples.find((s) => s?.error)?.error || null;
+ if (verdict === 'unknown') return backendError || 'no sample produced a usable measurement';
+ if (verdict === 'incompatible') return backendError || 'the backend refused this model';
+ return backendError || 'every context length tested exhausted this machine';
+}
+
+/**
+ * Run one model's assessment. **The only LLM-calling entry point in this
+ * module** — see the AI Provider Usage Policy note at the top.
+ *
+ * Samples run sequentially, smallest context first, so a model that dies at the
+ * largest size has already recorded its working sizes. A resource failure stops
+ * the remaining (larger) contexts: they cannot succeed once a smaller one has
+ * exhausted memory, and running them would only burn minutes. An `incompatible`
+ * failure stops immediately for the same reason.
+ *
+ * @param {object} options
+ * @param {'ollama'|'lmstudio'} options.backend
+ * @param {string} options.modelId
+ * @param {number[]} [options.contextTokens] nominal context sizes to sample
+ * @param {AbortSignal} [options.signal] client disconnect
+ * @returns {Promise<object>} the persisted assessment record
+ */
+export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_CONTEXT_TOKENS, signal } = {}) {
+ const contexts = [...new Set(contextTokens)].filter((n) => Number.isFinite(n) && n > 0).sort((a, b) => a - b);
+ const environment = await captureEnvironment();
+ const installed = await listModels(backend).catch(() => []);
+ const card = installed.find((m) => m?.id === modelId) || null;
+
+ console.log(`📏 Local LLM: assessing ${backend}/${modelId} across ${contexts.length} context sizes`);
+
+ const samples = [];
+ for (const context of contexts) {
+ if (signal?.aborted) break;
+ // runLocalLlmTest resolves (never throws) for in-stream failures, but can
+ // still throw before the stream opens — an unconfigured provider. Catch that
+ // into the same result shape so one bad backend records a failed sample
+ // instead of aborting the whole assessment with no evidence at all.
+ const result = await runLocalLlmTest({
+ backend,
+ modelId,
+ prompt: buildSamplePrompt(context),
+ systemPrompt: SAMPLE_SYSTEM_PROMPT,
+ temperature: 0,
+ maxTokens: SAMPLE_MAX_TOKENS,
+ timeoutMs: SAMPLE_TIMEOUT_MS,
+ signal,
+ }).catch((err) => ({ backend, modelId, text: '', error: err?.message || 'assessment run failed' }));
+
+ const sample = toSample(context, result);
+ samples.push(sample);
+ if (!sample.ok && classifySampleFailure(sample)) break;
+ }
+
+ const verdict = classifyFitVerdict(samples);
+ const assessment = {
+ backend,
+ modelId,
+ params: card?.params ?? null,
+ // `null` = never measured; the LM Studio path legitimately reports null.
+ residentGb: verdict === 'fits' ? await residentGbFor(backend, modelId) : null,
+ assessedAt: new Date().toISOString(),
+ environment,
+ verdict,
+ verdictReason: describeVerdict(verdict, samples),
+ samples,
+ performance: summarizePerformance(samples),
+ };
+
+ console.log(`📏 Local LLM: ${backend}/${modelId} → ${verdict} (${assessment.performance.samplesOk}/${samples.length} samples ok)`);
+ return saveAssessment(assessment);
+}
+
+/**
+ * Everything the UI needs to explain local-model choice, read from disk only.
+ *
+ * `assessed` / `unassessed` split installed models by whether evidence exists —
+ * an unassessed model is NOT ranked and NOT presented as a poor choice; it is
+ * presented as unknown, with a button to measure it.
+ *
+ * @param {{ intent?: string }} [options]
+ */
+export async function getAssessmentReport({ intent = 'balanced' } = {}) {
+ const { assessments, readError } = await loadStore();
+ const resolvedIntent = ASSESSMENT_INTENTS.includes(intent) ? intent : 'balanced';
+
+ const installedByBackend = Object.fromEntries(
+ await Promise.all(
+ ['ollama', 'lmstudio'].map(async (backend) => [backend, await listModels(backend).catch(() => null)])
+ )
+ );
+
+ const { ranked, excluded } = rankByIntent(assessments, resolvedIntent);
+
+ const assessedKeys = new Set(assessments.map((a) => assessmentKey(a?.backend, a?.modelId)));
+ const unassessed = [];
+ for (const [backend, models] of Object.entries(installedByBackend)) {
+ // `null` = the backend's model list could not be read. Reporting it as `[]`
+ // would claim "this backend has nothing to assess", which is a different
+ // (and wrong) statement — skip it instead.
+ if (!Array.isArray(models)) continue;
+ for (const model of models) {
+ if (model?.id && !assessedKeys.has(assessmentKey(backend, model.id))) {
+ unassessed.push({ backend, modelId: model.id, params: model.params ?? null });
+ }
+ }
+ }
+
+ return {
+ intent: resolvedIntent,
+ intents: ASSESSMENT_INTENTS,
+ defaultContextTokens: DEFAULT_CONTEXT_TOKENS,
+ assessments,
+ unassessed,
+ // Which backends could not be listed at all — distinct from "listed, empty".
+ listErrors: Object.entries(installedByBackend)
+ .filter(([, models]) => !Array.isArray(models))
+ .map(([backend]) => backend),
+ readError,
+ ranked,
+ excluded,
+ };
+}
diff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.js
new file mode 100644
index 0000000000..5152bac63f
--- /dev/null
+++ b/server/services/localModelAssessments.test.js
@@ -0,0 +1,255 @@
+/**
+ * Assessment run + store behavior, driven against a real on-disk store with
+ * `PATHS.data` re-rooted at a temp dir. The provider seam (`runLocalLlmTest`)
+ * is the only thing stubbed — that is the boundary where a real LLM call would
+ * otherwise happen, and stubbing it is what lets these tests assert the "never
+ * call a provider from a read path" contract.
+ */
+
+import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
+import { rmSync, existsSync } from 'fs';
+import { join } from 'path';
+import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
+
+const tempRoot = createTempDataRoot('portos-local-assessment-');
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) =>
+ makePathsProxy(await importOriginal(), { dataRoot: tempRoot }));
+
+const runLocalLlmTest = vi.fn();
+vi.mock('./localLlmPlayground.js', () => ({ runLocalLlmTest: (...args) => runLocalLlmTest(...args) }));
+
+const listModels = vi.fn();
+vi.mock('./localLlm.js', () => ({ listModels: (...args) => listModels(...args) }));
+
+const getLoadedModels = vi.fn();
+vi.mock('./ollamaManager.js', () => ({ getLoadedModels: (...args) => getLoadedModels(...args) }));
+
+// A fixed, generous memory budget so the memory axis is deterministic.
+vi.mock('../lib/localMemory.js', () => ({ getAvailableMemoryGb: async () => 64 }));
+
+const svc = await import('./localModelAssessments.js');
+
+const STORE = join(tempRoot, 'local-llm', 'assessments.json');
+
+const okRun = (chars = 40, charsPerSecond = 120, ttftMs = 250) => ({
+ text: 'The answer is 4.',
+ timings: { charsPerSecond, ttftMs, totalMs: 800, chars },
+});
+
+afterAll(() => rmSync(tempRoot, { recursive: true, force: true }));
+
+beforeEach(() => {
+ rmSync(join(tempRoot, 'local-llm'), { recursive: true, force: true });
+ runLocalLlmTest.mockReset();
+ listModels.mockReset().mockResolvedValue([{ id: 'example-model:7b', params: '7B' }]);
+ getLoadedModels.mockReset().mockResolvedValue([{ id: 'example-model:7b', name: 'example-model:7b', size: 5 * 2 ** 30 }]);
+});
+
+describe('buildSamplePrompt', () => {
+ it('scales the filler to the requested nominal context', () => {
+ const small = svc.buildSamplePrompt(512);
+ const large = svc.buildSamplePrompt(4096);
+ expect(large.length).toBeGreaterThan(small.length * 4);
+ });
+
+ it('always ends with the question, so a model that ignores the filler still answers', () => {
+ expect(svc.buildSamplePrompt(512).trimEnd()).toMatch(/what is 2 \+ 2\?/i);
+ });
+
+ it('uses distinct filler lines so a prefix cache cannot fake a cheap long prompt', () => {
+ const prompt = svc.buildSamplePrompt(1024);
+ expect(prompt).toContain('Reference item 1:');
+ expect(prompt).toContain('Reference item 2:');
+ });
+});
+
+describe('toSample', () => {
+ it('records timings from a successful run', () => {
+ expect(svc.toSample(512, okRun())).toMatchObject({
+ contextTokens: 512, ok: true, charsPerSecond: 120, ttftMs: 250, error: null,
+ });
+ });
+
+ it('treats an empty-text run as a FAILURE, not a zero-throughput success', () => {
+ // runLocalLlmTest resolves rather than throwing on timeout, so an
+ // error-free empty result is the shape a timed-out run actually takes.
+ // Recording it as ok would feed a fabricated 0 into the speed average.
+ const sample = svc.toSample(512, { text: '', timings: { totalMs: 120000 } });
+ expect(sample.ok).toBe(false);
+ expect(sample.charsPerSecond).toBeNull();
+ expect(sample.error).toBe('model produced no output');
+ });
+
+ it('keeps the backend error verbatim', () => {
+ expect(svc.toSample(512, { text: '', error: 'model requires more system memory' }).error)
+ .toBe('model requires more system memory');
+ });
+});
+
+describe('captureEnvironment', () => {
+ it('records hardware shape without any machine identity', async () => {
+ const env = await svc.captureEnvironment();
+ expect(env).toHaveProperty('platform');
+ expect(env).toHaveProperty('arch');
+ expect(env.totalMemoryGb).toBeGreaterThan(0);
+ expect(env.memoryBudgetGb).toBeGreaterThan(0);
+ // Privacy: assessments end up in bug reports, so the record must never
+ // carry a hostname, username, or path.
+ const keys = Object.keys(env);
+ expect(keys).not.toContain('hostname');
+ expect(keys).not.toContain('username');
+ for (const value of Object.values(env)) {
+ if (typeof value === 'string') expect(value).not.toContain('/');
+ }
+ });
+});
+
+describe('loadAssessments / getAssessmentReport (read path)', () => {
+ it('never calls a provider', async () => {
+ await svc.loadAssessments();
+ await svc.getAssessmentReport();
+ // The AI Provider Usage Policy boundary: a read must be safe from boot,
+ // from a poll, from anywhere.
+ expect(runLocalLlmTest).not.toHaveBeenCalled();
+ });
+
+ it('reports an empty store as empty, with no read error', async () => {
+ expect(await svc.loadAssessments()).toEqual([]);
+ expect((await svc.getAssessmentReport()).readError).toBeNull();
+ });
+
+ it('lists installed-but-unmeasured models without ranking or penalizing them', async () => {
+ const report = await svc.getAssessmentReport();
+ expect(report.ranked).toEqual([]);
+ expect(report.unassessed).toContainEqual({ backend: 'ollama', modelId: 'example-model:7b', params: '7B' });
+ });
+
+ it('flags a backend whose model list could not be read, rather than reporting it empty', async () => {
+ listModels.mockImplementation(async (backend) => {
+ if (backend === 'lmstudio') throw new Error('LM Studio unreachable');
+ return [{ id: 'example-model:7b', params: '7B' }];
+ });
+ const report = await svc.getAssessmentReport();
+ expect(report.listErrors).toEqual(['lmstudio']);
+ });
+
+ it('falls back to the balanced intent for an unrecognized one', async () => {
+ expect((await svc.getAssessmentReport({ intent: 'nonsense' })).intent).toBe('balanced');
+ });
+});
+
+describe('runAssessment', () => {
+ it('samples every context in ascending order and persists the result', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun());
+ const result = await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [4096, 512] });
+
+ expect(runLocalLlmTest.mock.calls.map((c) => c[0].prompt.length))
+ .toEqual([...runLocalLlmTest.mock.calls.map((c) => c[0].prompt.length)].sort((a, b) => a - b));
+ expect(result.verdict).toBe('fits');
+ expect(result.samples.map((s) => s.contextTokens)).toEqual([512, 4096]);
+ expect(existsSync(STORE)).toBe(true);
+ expect((await svc.loadAssessments())[0].modelId).toBe('example-model:7b');
+ });
+
+ it('stops after a resource failure instead of burning minutes on larger contexts', async () => {
+ runLocalLlmTest
+ .mockResolvedValueOnce(okRun())
+ .mockResolvedValueOnce({ text: '', error: 'model requires more system memory' })
+ .mockResolvedValue(okRun());
+
+ const result = await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512, 4096, 16384] });
+ expect(runLocalLlmTest).toHaveBeenCalledTimes(2);
+ // A smaller context worked, so the model DOES fit — the largest working
+ // context is what carries the nuance.
+ expect(result.verdict).toBe('fits');
+ expect(result.performance.maxWorkingContextTokens).toBe(512);
+ });
+
+ it('records does-not-fit when every context exhausted memory', async () => {
+ runLocalLlmTest.mockResolvedValue({ text: '', error: 'out of memory' });
+ const result = await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512, 4096] });
+ expect(result.verdict).toBe('does-not-fit');
+ expect(result.verdictReason).toBe('out of memory');
+ expect(result.residentGb).toBeNull();
+ });
+
+ it('turns a pre-stream throw into a recorded sample rather than losing the whole run', async () => {
+ // runLocalLlmTest throws (not resolves) when the provider is unconfigured.
+ // Letting that escape would abort the assessment with zero evidence.
+ runLocalLlmTest.mockRejectedValue(new Error('Local provider "ollama" is not configured'));
+ const result = await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });
+ expect(result.samples).toHaveLength(1);
+ expect(result.samples[0].error).toMatch(/not configured/);
+ // Not attributable to hardware — must not become a permanent does-not-fit.
+ expect(result.verdict).toBe('unknown');
+ });
+
+ it('records resident size for Ollama and null for LM Studio, which does not report one', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun());
+ const ollama = await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });
+ expect(ollama.residentGb).toBe(5);
+
+ const lmstudio = await svc.runAssessment({ backend: 'lmstudio', modelId: 'example-model:7b', contextTokens: [512] });
+ // Copying the weight-file size here would silently re-introduce the estimate
+ // this feature exists to replace.
+ expect(lmstudio.residentGb).toBeNull();
+ });
+
+ it('replaces the previous measurement for the same model rather than accumulating', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun(40, 100));
+ await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });
+ runLocalLlmTest.mockResolvedValue(okRun(40, 200));
+ await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });
+
+ const stored = await svc.loadAssessments();
+ expect(stored).toHaveLength(1);
+ expect(stored[0].performance.meanCharsPerSecond).toBe(200);
+ });
+
+ it('keeps separate records per backend for the same model id', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun());
+ await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });
+ await svc.runAssessment({ backend: 'lmstudio', modelId: 'example-model:7b', contextTokens: [512] });
+ expect(await svc.loadAssessments()).toHaveLength(2);
+ });
+
+ it('de-duplicates and sorts the requested context list', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun());
+ const result = await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [4096, 512, 4096] });
+ expect(result.samples.map((s) => s.contextTokens)).toEqual([512, 4096]);
+ });
+
+ it('honors an already-aborted signal without calling the provider', async () => {
+ const controller = new AbortController();
+ controller.abort();
+ const result = await svc.runAssessment({
+ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512], signal: controller.signal,
+ });
+ expect(runLocalLlmTest).not.toHaveBeenCalled();
+ expect(result.verdict).toBe('unknown');
+ });
+
+ it('feeds the ranking once evidence exists', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun());
+ await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512, 4096] });
+ const report = await svc.getAssessmentReport({ intent: 'fastest' });
+ expect(report.ranked.map((r) => r.modelId)).toEqual(['example-model:7b']);
+ // The stub lists the same model under both backends, so only the ollama
+ // copy leaves the unassessed list — assessments are per (backend, model).
+ expect(report.unassessed).toEqual([{ backend: 'lmstudio', modelId: 'example-model:7b', params: '7B' }]);
+ });
+});
+
+describe('deleteAssessment', () => {
+ it('removes a record and reports that it did', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun());
+ await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });
+ expect(await svc.deleteAssessment('ollama', 'example-model:7b')).toEqual({ deleted: true });
+ expect(await svc.loadAssessments()).toEqual([]);
+ });
+
+ it('reports a miss rather than a phantom success', async () => {
+ expect(await svc.deleteAssessment('ollama', 'example-model:404')).toEqual({ deleted: false });
+ });
+});