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

add an overnight "measure all models" sweep and report throughput in tokens/s

[._.]/ Adam Eivyfba01d4b0866
diff --git a/client/src/components/settings/AssessmentSweepPanel.jsx b/client/src/components/settings/AssessmentSweepPanel.jsx
new file mode 100644
index 0000000000..d8cc6c8eac
--- /dev/null
+++ b/client/src/components/settings/AssessmentSweepPanel.jsx
@@ -0,0 +1,339 @@
+/**
+ * "Measure every model" — the overnight sweep control.
+ *
+ * Measuring one model takes minutes, so measuring all of them is something you
+ * start at the end of the day. Two consequences shape this component:
+ *
+ * 1. **The run does not belong to this tab.** The server owns the queue; this
+ * polls its status and listens for socket frames. Closing the browser, or
+ * reloading, must not stop or lose an overnight run — so there is no abort
+ * controller here and no in-flight request to hold open.
+ * 2. **Consent names real numbers.** The AI Provider Usage Policy (root
+ * CLAUDE.md) requires that a batch of provider calls be preceded by a gate
+ * that says exactly what will run. The counts come from the server's own
+ * target selector, not from a client-side estimate, so the number shown is
+ * the number that executes.
+ */
+
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { PlayCircle, Square, AlertTriangle, CheckCircle2 } from 'lucide-react';
+import Modal from '../ui/Modal';
+import ProgressBar from '../ui/ProgressBar';
+import BrailleSpinner from '../BrailleSpinner';
+import toast from '../ui/Toast';
+import socket from '../../services/socket';
+import useMounted from '../../hooks/useMounted';
+import { useAsyncAction } from '../../hooks/useAsyncAction';
+import { useAutoRefetch } from '../../hooks/useAutoRefetch';
+import { formatContextTokens, throughputLabel, timeAgo } from '../../utils/formatters';
+import {
+ getLocalLlmAssessmentSweep, startLocalLlmAssessmentSweep, cancelLocalLlmAssessmentSweep,
+} from '../../services/api';
+
+const SCOPES = [
+ { id: 'unmeasured', label: 'Only models never measured', blurb: 'Leaves existing readings alone.' },
+ { id: 'stale', label: 'Only stale readings', blurb: 'Re-runs measurements taken on a different machine state, reusing each one\'s tuning.' },
+ { id: 'all', label: 'Everything installed', blurb: 'Every unmeasured model, plus a fresh reading for every configuration already recorded.' },
+];
+
+// How often to re-read the queue while it runs. Socket frames drive the live
+// message; this is the reload-safe backstop that also catches the transition to
+// finished when the last frame is missed.
+const POLL_MS = 5000;
+
+const isRunning = (status) => status?.status === 'running';
+
+function SweepConsentModal({ scope, onScopeChange, counts, contextTokens, onCancel, onConfirm, starting }) {
+ const count = counts?.[scope] ?? 0;
+ const generations = count * Math.max(1, contextTokens.length);
+ return (
+ <Modal open onClose={onCancel} size="sm" ariaLabel="Measure every local model">
+ <div className="bg-port-card border border-port-border rounded-lg p-5 space-y-4">
+ <div className="flex items-center gap-2">
+ <PlayCircle size={18} className="text-port-accent" />
+ <h3 className="text-white font-medium">Measure every model?</h3>
+ </div>
+
+ <fieldset className="space-y-2">
+ <legend className="text-xs text-gray-400 mb-1">What to measure</legend>
+ {SCOPES.map((option) => {
+ const optionCount = counts?.[option.id] ?? 0;
+ const fieldId = `sweep-scope-${option.id}`;
+ return (
+ <div key={option.id} className="flex items-start gap-2">
+ <input
+ id={fieldId}
+ type="radio"
+ name="sweep-scope"
+ checked={scope === option.id}
+ disabled={starting || optionCount === 0}
+ onChange={() => onScopeChange(option.id)}
+ className="mt-1 accent-port-accent"
+ />
+ <label htmlFor={fieldId} className={`min-w-0 ${optionCount === 0 ? 'opacity-50' : ''}`}>
+ <span className="text-xs text-gray-200">{option.label}</span>
+ <span className="text-xs text-gray-500 ml-1.5">
+ ({optionCount} model{optionCount === 1 ? '' : 's'})
+ </span>
+ <p className="text-[10px] text-gray-500 leading-snug">{option.blurb}</p>
+ </label>
+ </div>
+ );
+ })}
+ </fieldset>
+
+ <p className="text-sm text-gray-400">
+ PortOS will run <span className="text-gray-200">{count}</span> measurement{count === 1 ? '' : 's'} —{' '}
+ <span className="text-gray-200">{generations}</span> short generation{generations === 1 ? '' : 's'} in
+ total, one at each of {contextTokens.map(formatContextTokens).join(', ')} tokens of context per model.
+ </p>
+ <p className="text-xs text-gray-500">
+ They run one at a time (two models at once would measure the contention, not the models), which makes
+ this a job for overnight — expect several minutes per model. It keeps running with this tab closed,
+ and you can stop it at any point; everything measured up to then is kept.
+ </p>
+
+ <div className="flex gap-3 pt-1">
+ <button
+ onClick={onCancel}
+ disabled={starting}
+ 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={starting || count === 0}
+ 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"
+ >
+ {starting ? <><BrailleSpinner /> Starting…</> : <>Start sweep</>}
+ </button>
+ </div>
+ </div>
+ </Modal>
+ );
+}
+
+/** One finished measurement from the queue. */
+function SweepResultRow({ result }) {
+ const failed = Boolean(result.error) || result.verdict === 'does-not-fit' || result.verdict === 'incompatible';
+ return (
+ <div className="flex items-center gap-2 text-[11px] flex-wrap">
+ {failed
+ ? <AlertTriangle size={11} className="text-port-warning shrink-0" />
+ : <CheckCircle2 size={11} className="text-emerald-400 shrink-0" />}
+ <span className="text-gray-300 font-mono break-all min-w-0">{result.modelId}</span>
+ {/* The tokens/s figure is the headline of a sweep, so it leads where the
+ runtime reported one; chars/s is the fallback, never both. */}
+ <span className="text-gray-500">
+ {result.error || [result.verdict, throughputLabel(result)].filter(Boolean).join(' — ')}
+ </span>
+ </div>
+ );
+}
+
+/**
+ * @param {object} props
+ * @param {Record<string, number>} props.counts per-scope target counts from the report
+ * @param {number[]} props.contextTokens context sizes each measurement samples
+ * @param {() => void} props.onSweepFinished refresh the report once the queue ends
+ * @param {(running: boolean) => void} [props.onRunningChange] lets the parent
+ * disable its own per-model Measure buttons while the queue holds the provider
+ * @param {boolean} props.disabled a single-model run is already occupying the provider
+ */
+export default function AssessmentSweepPanel({ counts, contextTokens = [], onSweepFinished, onRunningChange, disabled }) {
+ const [status, setStatus] = useState(null);
+ const [showConsent, setShowConsent] = useState(false);
+ const [scope, setScope] = useState('unmeasured');
+ // The live socket message for the model in flight. Reset whenever the model
+ // changes so a stale line never sits under a different model's name.
+ const [message, setMessage] = useState('');
+ const mountedRef = useMounted();
+
+ const refresh = useCallback(async () => {
+ const next = await getLocalLlmAssessmentSweep({ silent: true }).catch(() => null);
+ if (!next || !mountedRef.current) return null;
+ setStatus(next);
+ return next;
+ }, [mountedRef]);
+
+ // A sweep that started in another tab (or before a reload) has to show up here
+ // — the queue is server state, not this component's.
+ useEffect(() => { refresh(); }, [refresh]);
+
+ const running = isRunning(status);
+ // `onSweepFinished` is a fresh closure on every parent render, so keeping it in
+ // a ref stops the poll callback from re-registering on each one.
+ const finishedRef = useRef(onSweepFinished);
+ finishedRef.current = onSweepFinished;
+
+ // `onSweepFinished` re-reads the whole assessment report, which probes every
+ // runtime — expensive enough that firing it twice for one finish (a poll tick
+ // racing the terminal socket frame) is worth latching out.
+ const finishNotifiedRef = useRef(false);
+ const notifyFinished = useCallback(() => {
+ if (finishNotifiedRef.current) return;
+ finishNotifiedRef.current = true;
+ finishedRef.current?.();
+ }, []);
+
+ // A single-model run started mid-sweep would contend with the model the queue
+ // is measuring, and BOTH readings would describe that contention. Tell the
+ // parent so its per-model buttons go quiet for the duration.
+ useEffect(() => { onRunningChange?.(running); }, [running, onRunningChange]);
+
+ // Poll only while something is running, and only while the tab is visible —
+ // `useAutoRefetch` gives both, which matters for a queue deliberately left
+ // running in a background tab all night.
+ useAutoRefetch(async () => {
+ const next = await refresh();
+ // The report is only worth re-reading once the queue is done — mid-sweep it
+ // would re-rank on partial evidence every five seconds.
+ if (next && !isRunning(next)) notifyFinished();
+ }, POLL_MS, { enabled: running, immediate: false, pollOnly: true });
+
+ // Per-sample frames from the model in flight, on the same channel the
+ // single-model run and model pulls use — hence the scope filter, or a
+ // background model download would drive this line.
+ useEffect(() => {
+ const handleProgress = (frame) => {
+ if (!mountedRef.current) return;
+ if (frame?.scope !== 'assessment' && frame?.scope !== 'assessment-sweep') return;
+ if (frame.event === 'complete' && frame.scope === 'assessment-sweep') {
+ // Terminal frame for the QUEUE (not for one model): pull the final
+ // snapshot and let the parent re-read the now-complete report.
+ setMessage('');
+ refresh().then(notifyFinished);
+ return;
+ }
+ if (frame.message) setMessage(frame.message);
+ // The counter moves when a model starts — and the frame already carries the
+ // new numbers, so take them from it rather than paying a round-trip per
+ // model for data we were just handed.
+ if (frame.event === 'model-start') {
+ setStatus((prev) => (prev ? {
+ ...prev,
+ completed: frame.completed ?? prev.completed,
+ total: frame.total ?? prev.total,
+ current: { backend: frame.backend, modelId: frame.modelId },
+ } : prev));
+ }
+ };
+ socket.on('localLlm:progress', handleProgress);
+ return () => socket.off('localLlm:progress', handleProgress);
+ }, [mountedRef, refresh, notifyFinished]);
+
+ const [start, starting] = useAsyncAction(async () => {
+ finishNotifiedRef.current = false;
+ const next = await startLocalLlmAssessmentSweep({ scope });
+ setStatus(next);
+ setShowConsent(false);
+ toast.success(`Sweep started — ${next.total} model${next.total === 1 ? '' : 's'} queued`);
+ return next;
+ }, { errorMessage: 'Could not start the sweep' });
+
+ const [stop, stopping] = useAsyncAction(async () => {
+ setStatus(await cancelLocalLlmAssessmentSweep());
+ // Whatever it measured before stopping is real evidence, so the report has
+ // to catch up rather than waiting for the next mount.
+ notifyFinished();
+ return true;
+ }, { errorMessage: 'Could not stop the sweep' });
+
+ const openConsent = () => {
+ // Default to the scope that has something to do, so the common case is one
+ // click: never-measured first, then stale, then everything.
+ const firstUseful = SCOPES.find((s) => (counts?.[s.id] ?? 0) > 0)?.id || 'unmeasured';
+ setScope(firstUseful);
+ setShowConsent(true);
+ };
+
+ const totalTargets = counts?.all ?? 0;
+ const finished = status && !running && status.status !== 'idle';
+
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center gap-2 flex-wrap">
+ {running ? (
+ <button
+ onClick={stop}
+ disabled={stopping}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg border border-port-border text-gray-200 hover:border-port-error hover:text-port-error transition-colors disabled:opacity-50"
+ >
+ <Square size={12} /> Stop sweep
+ </button>
+ ) : (
+ <button
+ onClick={openConsent}
+ disabled={disabled || totalTargets === 0}
+ title={totalTargets === 0 ? 'No models are listable to measure right now' : 'Measure every installed model, one after another'}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-accent hover:bg-port-accent/80 text-port-on-accent font-medium transition-colors disabled:opacity-50"
+ >
+ <PlayCircle size={13} /> Measure all models
+ </button>
+ )}
+ {running && (
+ <span className="text-[11px] text-gray-400 flex items-center gap-1.5" aria-live="polite">
+ <BrailleSpinner />
+ {status.completed}/{status.total} measured
+ {status.current && <span className="text-gray-500 font-mono break-all">· {status.current.modelId}</span>}
+ </span>
+ )}
+ {finished && (
+ <span className="text-[11px] text-gray-500">
+ Last sweep {status.status} — {status.completed}/{status.total} measured {timeAgo(status.finishedAt, '')}
+ </span>
+ )}
+ </div>
+
+ {running && (
+ <div className="border border-port-border rounded-lg p-3 space-y-1.5">
+ {status.total > 0 && (
+ <ProgressBar
+ percent={(status.completed / status.total) * 100}
+ track="border"
+ label={`Sweep progress: ${status.completed} of ${status.total} models measured`}
+ />
+ )}
+ {message && <p className="text-[11px] text-gray-400 break-words" aria-live="polite">{message}</p>}
+ <p className="text-[10px] text-gray-600">
+ Running on the server — you can close this tab and read the results in the morning.
+ </p>
+ </div>
+ )}
+
+ {/* Results stay on screen after the queue ends: the whole point of an
+ overnight run is reading what it found the next day. */}
+ {status?.results?.length > 0 && (
+ <details className="border border-port-border rounded-lg" open={running}>
+ <summary className="px-3 py-2 text-xs text-gray-300 cursor-pointer hover:text-white">
+ Sweep results ({status.results.length})
+ </summary>
+ <div className="px-3 pb-3 space-y-1">
+ {status.results.map((result) => (
+ <SweepResultRow key={`${result.backend}:${result.modelId}:${result.finishedAt}`} result={result} />
+ ))}
+ </div>
+ </details>
+ )}
+
+ {status?.error && (
+ <p className="text-xs text-port-warning flex items-center gap-1.5" role="alert">
+ <AlertTriangle size={12} /> The sweep stopped early: {status.error}
+ </p>
+ )}
+
+ {showConsent && (
+ <SweepConsentModal
+ scope={scope}
+ onScopeChange={setScope}
+ counts={counts}
+ contextTokens={contextTokens}
+ starting={starting}
+ onCancel={() => setShowConsent(false)}
+ onConfirm={start}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/settings/AssessmentSweepPanel.test.jsx b/client/src/components/settings/AssessmentSweepPanel.test.jsx
new file mode 100644
index 0000000000..58149d43c4
--- /dev/null
+++ b/client/src/components/settings/AssessmentSweepPanel.test.jsx
@@ -0,0 +1,174 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+vi.mock('../../services/api', () => ({
+ getLocalLlmAssessmentSweep: vi.fn(),
+ startLocalLlmAssessmentSweep: vi.fn(),
+ cancelLocalLlmAssessmentSweep: vi.fn(),
+}));
+
+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } }));
+
+vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn() } }));
+
+import {
+ getLocalLlmAssessmentSweep, startLocalLlmAssessmentSweep, cancelLocalLlmAssessmentSweep,
+} from '../../services/api';
+import socket from '../../services/socket';
+import AssessmentSweepPanel from './AssessmentSweepPanel.jsx';
+
+const idle = { status: 'idle', scope: null, total: 0, completed: 0, current: null, results: [], startedAt: null, finishedAt: null };
+
+const counts = { unmeasured: 2, stale: 1, all: 4 };
+
+const renderPanel = (props = {}) => render(
+ <AssessmentSweepPanel counts={counts} contextTokens={[512, 4096, 16384]} onSweepFinished={vi.fn()} {...props} />
+);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getLocalLlmAssessmentSweep.mockResolvedValue(idle);
+});
+
+describe('AssessmentSweepPanel', () => {
+ // The AI Provider Usage Policy gate: a batch of provider calls has to be
+ // preceded by a statement of exactly what will run.
+ it('names the model and generation count before anything is queued', async () => {
+ const user = userEvent.setup();
+ renderPanel();
+
+ await user.click(await screen.findByRole('button', { name: 'Measure all models' }));
+ expect(startLocalLlmAssessmentSweep).not.toHaveBeenCalled();
+ expect(screen.getByText(/Measure every model\?/)).toBeInTheDocument();
+ // 2 unmeasured models × 3 context lengths = 6 generations, spelled out.
+ expect(screen.getByText(/short generations in total/)).toBeInTheDocument();
+ expect(screen.getByText('6')).toBeInTheDocument();
+ expect(screen.getByText(/512, 4K, 16K tokens of context/)).toBeInTheDocument();
+ });
+
+ it('starts the scope the user picked', async () => {
+ const user = userEvent.setup();
+ startLocalLlmAssessmentSweep.mockResolvedValue({ ...idle, status: 'running', total: 4 });
+ renderPanel();
+
+ await user.click(await screen.findByRole('button', { name: 'Measure all models' }));
+ await user.click(screen.getByLabelText(/Everything installed/));
+ await user.click(screen.getByRole('button', { name: /start sweep/i }));
+
+ await waitFor(() => expect(startLocalLlmAssessmentSweep).toHaveBeenCalledWith({ scope: 'all' }));
+ });
+
+ it('defaults to the first scope that has something to do', async () => {
+ const user = userEvent.setup();
+ startLocalLlmAssessmentSweep.mockResolvedValue({ ...idle, status: 'running', total: 1 });
+ renderPanel({ counts: { unmeasured: 0, stale: 3, all: 3 } });
+
+ await user.click(await screen.findByRole('button', { name: 'Measure all models' }));
+ await user.click(screen.getByRole('button', { name: /start sweep/i }));
+ await waitFor(() => expect(startLocalLlmAssessmentSweep).toHaveBeenCalledWith({ scope: 'stale' }));
+ });
+
+ it('does not queue anything when the ask is cancelled', async () => {
+ const user = userEvent.setup();
+ renderPanel();
+
+ await user.click(await screen.findByRole('button', { name: 'Measure all models' }));
+ await user.click(screen.getByRole('button', { name: /^cancel$/i }));
+ expect(startLocalLlmAssessmentSweep).not.toHaveBeenCalled();
+ await waitFor(() => expect(screen.queryByText(/Measure every model\?/)).not.toBeInTheDocument());
+ });
+
+ // The queue is server state. A sweep started in another tab, or before a
+ // reload, has to show up here — otherwise the page offers to start a second one.
+ it('picks up a sweep that was already running when it mounted', async () => {
+ getLocalLlmAssessmentSweep.mockResolvedValue({
+ ...idle, status: 'running', total: 5, completed: 2,
+ current: { backend: 'ollama', modelId: 'example-model:14b' },
+ });
+ renderPanel();
+
+ expect(await screen.findByText(/2\/5 measured/)).toBeInTheDocument();
+ expect(screen.getByText(/example-model:14b/)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /stop sweep/i })).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: 'Measure all models' })).not.toBeInTheDocument();
+ });
+
+ it('says the run outlives the tab, because that is the whole point of it', async () => {
+ getLocalLlmAssessmentSweep.mockResolvedValue({ ...idle, status: 'running', total: 3, completed: 0 });
+ renderPanel();
+ expect(await screen.findByText(/close this tab/i)).toBeInTheDocument();
+ });
+
+ it('stops the queue and lets the parent re-read what it measured', async () => {
+ const user = userEvent.setup();
+ const onSweepFinished = vi.fn();
+ getLocalLlmAssessmentSweep.mockResolvedValue({ ...idle, status: 'running', total: 5, completed: 2 });
+ cancelLocalLlmAssessmentSweep.mockResolvedValue({ ...idle, status: 'cancelled', total: 5, completed: 2 });
+ renderPanel({ onSweepFinished });
+
+ await user.click(await screen.findByRole('button', { name: /stop sweep/i }));
+ await waitFor(() => expect(cancelLocalLlmAssessmentSweep).toHaveBeenCalled());
+ // Two measurements are real evidence even though the run was abandoned.
+ await waitFor(() => expect(onSweepFinished).toHaveBeenCalled());
+ });
+
+ // Results are what you read the next morning — they must survive the queue
+ // ending rather than disappearing with the progress bar.
+ it('keeps the finished results on screen after the sweep ends', async () => {
+ getLocalLlmAssessmentSweep.mockResolvedValue({
+ ...idle,
+ status: 'complete',
+ total: 2,
+ completed: 2,
+ finishedAt: '2026-01-01T00:00:00.000Z',
+ results: [
+ { backend: 'ollama', modelId: 'fast-model', verdict: 'fits', error: null, meanTokensPerSecond: 61, finishedAt: '2026-01-01T00:00:00.000Z' },
+ { backend: 'ollama', modelId: 'big-model', verdict: 'does-not-fit', error: null, meanTokensPerSecond: null, meanCharsPerSecond: null, finishedAt: '2026-01-01T00:01:00.000Z' },
+ ],
+ });
+ renderPanel();
+
+ expect(await screen.findByText(/Sweep results \(2\)/)).toBeInTheDocument();
+ expect(screen.getByText('fast-model')).toBeInTheDocument();
+ expect(screen.getByText(/fits — 61 tok\/s/)).toBeInTheDocument();
+ expect(screen.getByText('does-not-fit')).toBeInTheDocument();
+ });
+
+ it('falls back to chars/s for a runtime that reported no token counts', async () => {
+ getLocalLlmAssessmentSweep.mockResolvedValue({
+ ...idle,
+ status: 'complete',
+ total: 1,
+ completed: 1,
+ results: [{ backend: 'llama', modelId: 'quiet-model', verdict: 'fits', error: null, meanTokensPerSecond: null, meanCharsPerSecond: 240, finishedAt: '2026-01-01T00:00:00.000Z' }],
+ });
+ renderPanel();
+ expect(await screen.findByText(/fits — 240 chars\/s/)).toBeInTheDocument();
+ });
+
+ it('subscribes to the shared progress event and filters out unrelated frames', async () => {
+ getLocalLlmAssessmentSweep.mockResolvedValue({ ...idle, status: 'running', total: 2, completed: 0 });
+ renderPanel();
+ await screen.findByText(/0\/2 measured/);
+
+ const handler = socket.on.mock.calls.find(([event]) => event === 'localLlm:progress')[1];
+ // A model PULL streams on the same event, in the shape the install route
+ // actually emits (`{ event, message }`, no scope) — it must not drive this line.
+ await act(async () => handler({ event: 'progress', message: 'pulling manifest' }));
+ expect(screen.queryByText('pulling manifest')).not.toBeInTheDocument();
+
+ await act(async () => handler({ scope: 'assessment', message: 'example-model: sample 2/3 at 4,096 tokens…' }));
+ expect(await screen.findByText(/sample 2\/3/)).toBeInTheDocument();
+ });
+
+ it('offers nothing to press when no runtime lists a model to measure', async () => {
+ renderPanel({ counts: { unmeasured: 0, stale: 0, all: 0 } });
+ expect(await screen.findByRole('button', { name: 'Measure all models' })).toBeDisabled();
+ });
+
+ it('is disabled while a single-model run already holds the provider', async () => {
+ renderPanel({ disabled: true });
+ expect(await screen.findByRole('button', { name: 'Measure all models' })).toBeDisabled();
+ });
+});
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index 3fb22ee87a..02bde07e91 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -585,6 +585,13 @@ export function LocalLlmTab() {
useEffect(() => {
const handleProgress = (data) => {
+ // `localLlm:progress` is a shared channel. Measurement frames (`assessment`,
+ // `assessment-sweep`) belong to the Performance tab and say nothing about
+ // what is installed here — and an overnight sweep emits a `complete` frame
+ // per model, so answering them would reload the status AND re-query the
+ // Hugging Face catalog once per measured model, all night. This tab owns
+ // the unscoped install/migrate/upgrade frames only.
+ if (data?.scope === 'assessment' || data?.scope === 'assessment-sweep') return;
clearTimeout(progressTimer.current);
setProgressMsg(data.message || '');
if (data.event === 'complete') {
diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsx
index 9218f349a4..68c020044a 100644
--- a/client/src/components/settings/LocalLlmTab.test.jsx
+++ b/client/src/components/settings/LocalLlmTab.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
vi.mock('../../services/api', () => ({
@@ -29,6 +29,7 @@ vi.mock('../ui/Toast', () => ({
}));
import { getLocalLlmStatus, getLocalLlmCatalog, patchSettingsSlice, installLocalLlmModel } from '../../services/api';
+import socket from '../../services/socket';
import { LocalLlmTab } from './LocalLlmTab';
// A realistically long HF model id — the shape that got ellipsised to
@@ -732,4 +733,32 @@ describe('LocalLlmTab llama-server management', () => {
expect(stopLlamaServer).toHaveBeenCalled();
});
});
-});
+
+ // `localLlm:progress` is shared with the measurement paths, and an overnight
+ // sweep emits a `complete` frame PER MODEL. Answering those here would reload
+ // the status and re-query the Hugging Face catalog once per measured model,
+ // all night, and paint sweep text into the install banner.
+ describe('shared progress channel', () => {
+ const fireFrame = async (frame) => {
+ const handler = socket.on.mock.calls.find(([event]) => event === 'localLlm:progress')?.[1];
+ await act(async () => handler(frame));
+ };
+
+ it('ignores assessment and sweep frames on the shared progress event', async () => {
+ await renderTab();
+ const catalogCalls = getLocalLlmCatalog.mock.calls.length;
+
+ await fireFrame({ scope: 'assessment', event: 'complete', message: 'example-model: fits' });
+ await fireFrame({ scope: 'assessment-sweep', event: 'complete', message: 'Sweep complete: 30/30 measured' });
+
+ expect(getLocalLlmCatalog.mock.calls.length).toBe(catalogCalls);
+ expect(screen.queryByText(/Sweep complete/)).not.toBeInTheDocument();
+ });
+
+ it('still answers the install frames this tab owns', async () => {
+ await renderTab();
+ await fireFrame({ event: 'progress', message: 'pulling manifest' });
+ expect(await screen.findByText(/pulling manifest/)).toBeInTheDocument();
+ });
+ });
+});
\ No newline at end of file
diff --git a/client/src/components/settings/LocalModelAssessments.jsx b/client/src/components/settings/LocalModelAssessments.jsx
index dae8b5fc33..91c91c69e6 100644
--- a/client/src/components/settings/LocalModelAssessments.jsx
+++ b/client/src/components/settings/LocalModelAssessments.jsx
@@ -11,10 +11,15 @@
* 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.
+ * backend, the model, and how many generations are about to happen. The
+ * batch run (`AssessmentSweepPanel`) is held to exactly the same gate.
* 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.
+ *
+ * Throughput is reported in tokens/s wherever the runtime reported token counts,
+ * with chars/s as the universal fallback — `ModelThroughputReport` is the full
+ * per-context table. PortOS never derives one unit from the other.
*/
import { useCallback, useEffect, useRef, useState } from 'react';
@@ -25,7 +30,9 @@ import BrailleSpinner from '../BrailleSpinner';
import toast from '../ui/Toast';
import { useAsyncAction } from '../../hooks/useAsyncAction';
import useMounted from '../../hooks/useMounted';
-import { formatContextLength, formatDurationMs } from '../../utils/formatters';
+import AssessmentSweepPanel from './AssessmentSweepPanel';
+import ModelThroughputReport from './ModelThroughputReport';
+import { formatContextTokens, formatDurationMs, throughputLabel } from '../../utils/formatters';
import {
getLocalLlmAssessments, runLocalLlmAssessment, deleteLocalLlmAssessment,
} from '../../services/api';
@@ -61,10 +68,6 @@ const VERDICT_META = {
const AXIS_LABEL = { capability: 'Capability', speed: 'Speed', fidelity: 'Context stability', memory: 'Memory headroom' };
-// The shared formatter, minus its standalone-badge suffix — the prose around
-// every call site here already says "tokens of context".
-const formatContext = (tokens) => formatContextLength(tokens, { suffix: '' });
-
const backendLabel = (report, id) =>
report?.runtimes?.find((r) => r.id === id)?.label || BACKEND_LABEL[id] || id;
@@ -195,7 +198,7 @@ function AssessmentConsentModal({
PortOS will run <span className="text-gray-200 font-mono break-all">{target.modelId}</span> on{' '}
<span className="text-gray-200">{runtimeLabel}</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.
+ {contextTokens.map(formatContextTokens).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
@@ -337,7 +340,18 @@ function RankedRow({ entry, runtimeLabel, onRemeasure, onDelete, busy }) {
<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>
+ {/* Tokens/s where the runtime reported token counts — the figure people
+ compare local models on — with chars/s underneath as the universal
+ one. A runtime that reports no usage shows chars/s alone rather than
+ a tokens/s figure divided out of it. */}
+ <div className="text-gray-200">
+ {throughputLabel(perf) || <span className="text-gray-600 italic">not measured</span>}
+ {Number.isFinite(perf.meanTokensPerSecond) && (
+ <span className="text-gray-600 ml-1.5 text-[10px]">
+ <Measured value={perf.meanCharsPerSecond} suffix=" chars/s" />
+ </span>
+ )}
+ </div>
</div>
<div>
<div className="text-gray-500">First token</div>
@@ -351,7 +365,7 @@ function RankedRow({ entry, runtimeLabel, onRemeasure, onDelete, busy }) {
<div className="text-gray-500">Max context</div>
<div className="text-gray-200">
{Number.isFinite(perf.maxWorkingContextTokens)
- ? `${formatContext(perf.maxWorkingContextTokens)} tokens`
+ ? `${formatContextTokens(perf.maxWorkingContextTokens)} tokens`
: <span className="text-gray-600 italic">not measured</span>}
</div>
</div>
@@ -476,6 +490,9 @@ export function LocalModelAssessments() {
// Per-sample progress for the run in flight. `null` = no frame yet, which is
// rendered as "no progress bar" rather than as 0 of N.
const [progress, setProgress] = useState(null);
+ // Whether the server-side sweep is working. Owned here rather than in the
+ // sweep panel because it gates this panel's per-model buttons too.
+ const [sweepRunning, setSweepRunning] = useState(false);
const load = useCallback(async (nextIntent) => {
setLoading(true);
@@ -612,7 +629,21 @@ export function LocalModelAssessments() {
setPendingTarget(entry);
};
- const busy = running || removing;
+ // A sweep holds the provider for hours. A single-model run started on top of
+ // it would measure the contention between the two, so every per-model action
+ // goes quiet while the queue is working.
+ // O(1) label lookup with a stable identity: the throughput table calls it once
+ // per row, and a fresh closure each render would forbid ever memoizing that
+ // table. The report's roster is authoritative; BACKEND_LABEL is the fallback.
+ const runtimeLabelFor = useCallback(
+ (id) => report?.runtimes?.find((r) => r.id === id)?.label || BACKEND_LABEL[id] || id,
+ [report?.runtimes],
+ );
+
+ // The sweep is excluded from the panel's OWN disable: pressing Stop has to stay
+ // available while the queue is what is busy.
+ const localBusy = running || removing;
+ const busy = localBusy || sweepRunning;
const activeIntent = INTENTS.find((i) => i.id === intent);
return (
@@ -637,13 +668,26 @@ export function LocalModelAssessments() {
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 — across every local runtime PortOS can reach
- (Ollama, LM Studio, llama.cpp, MTPLX, vLLM). Measure a model under more than one launch tuning to
- see which configuration this machine actually prefers. Results stay on this machine — they
- describe this hardware, so they are never synced to a peer.
+ (Ollama, LM Studio, llama.cpp, MTPLX, vLLM). Throughput is reported in tokens per second wherever
+ the runtime reports token counts. Measure a model under more than one launch tuning to
+ see which configuration this machine actually prefers, or start a sweep to measure everything at
+ once. Results stay on this machine — they describe this hardware, so they are never synced to a peer.
</p>
<RuntimeRoster runtimes={report?.runtimes} />
+ {/* The batch run. Kept above the ranking because it is what you come here
+ to press at the end of the day; the results below are what you read the
+ next morning. Disabled while a single-model run holds the provider —
+ two measurements at once would measure the contention. */}
+ <AssessmentSweepPanel
+ counts={report?.sweepScopes}
+ contextTokens={report?.defaultContextTokens || []}
+ disabled={localBusy}
+ onRunningChange={setSweepRunning}
+ onSweepFinished={() => load(intent)}
+ />
+
<div className="flex items-center gap-2 flex-wrap">
<label htmlFor="assessment-intent" className="text-xs text-gray-400">Rank for</label>
<select
@@ -714,9 +758,14 @@ export function LocalModelAssessments() {
</div>
)}
+ <ModelThroughputReport
+ report={report.throughputReport}
+ runtimeLabelFor={runtimeLabelFor}
+ />
+
<TuningComparison
rows={report.tuningComparison}
- runtimeLabelFor={(id) => backendLabel(report, id)}
+ runtimeLabelFor={runtimeLabelFor}
/>
{report.unassessed?.length > 0 && (
diff --git a/client/src/components/settings/LocalModelAssessments.test.jsx b/client/src/components/settings/LocalModelAssessments.test.jsx
index 412d539e6d..518564dbaf 100644
--- a/client/src/components/settings/LocalModelAssessments.test.jsx
+++ b/client/src/components/settings/LocalModelAssessments.test.jsx
@@ -6,6 +6,11 @@ vi.mock('../../services/api', () => ({
getLocalLlmAssessments: vi.fn(),
runLocalLlmAssessment: vi.fn(),
deleteLocalLlmAssessment: vi.fn(),
+ // The sweep panel is a child of this one and polls the queue on mount. Its own
+ // behavior has a dedicated suite; here it just has to be idle and quiet.
+ getLocalLlmAssessmentSweep: vi.fn(async () => ({ status: 'idle', total: 0, completed: 0, results: [] })),
+ startLocalLlmAssessmentSweep: vi.fn(),
+ cancelLocalLlmAssessmentSweep: vi.fn(),
}));
vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } }));
@@ -16,7 +21,10 @@ vi.mock('../../services/socket', () => ({
default: { on: vi.fn(), off: vi.fn() },
}));
-import { getLocalLlmAssessments, runLocalLlmAssessment, deleteLocalLlmAssessment } from '../../services/api';
+import {
+ getLocalLlmAssessments, runLocalLlmAssessment, deleteLocalLlmAssessment,
+ getLocalLlmAssessmentSweep, cancelLocalLlmAssessmentSweep,
+} from '../../services/api';
import toast from '../ui/Toast';
import socket from '../../services/socket';
import LocalModelAssessments from './LocalModelAssessments.jsx';
@@ -34,6 +42,8 @@ const report = (overrides = {}) => ({
runtimes: RUNTIMES,
tuningComparison: [],
uninstalled: [],
+ throughputReport: { rows: [], contexts: [], modelsWithTokenRates: 0 },
+ sweepScopes: { unmeasured: 0, stale: 0, all: 0 },
...overrides,
});
@@ -51,6 +61,11 @@ const RUNTIMES = [
{ id: 'mtplx', label: 'MTPLX', managed: false, modelCount: null, error: 'not reachable at http://127.0.0.1:8000/v1 (ECONNREFUSED)', tuningSpecs: [] },
];
+// The sweep queue is server state the panel reads on mount. Every suite here
+// starts from "nothing running" — a test that wants a live queue says so.
+const idleSweep = () =>
+ getLocalLlmAssessmentSweep.mockResolvedValue({ status: 'idle', total: 0, completed: 0, current: null, results: [] });
+
const rankedEntry = (overrides = {}) => ({
backend: 'ollama',
modelId: 'example-model:7b',
@@ -77,6 +92,7 @@ const rankedEntry = (overrides = {}) => ({
describe('LocalModelAssessments', () => {
beforeEach(() => {
vi.clearAllMocks();
+ idleSweep();
getLocalLlmAssessments.mockResolvedValue(report());
});
@@ -123,7 +139,7 @@ describe('LocalModelAssessments', () => {
runLocalLlmAssessment.mockResolvedValue({ verdict: 'fits' });
render(<LocalModelAssessments />);
- await user.click(await screen.findByRole('button', { name: /measure/i }));
+ await user.click(await screen.findByRole('button', { name: 'Measure' }));
// 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();
@@ -144,7 +160,7 @@ describe('LocalModelAssessments', () => {
}));
render(<LocalModelAssessments />);
- await user.click(await screen.findByRole('button', { name: /measure/i }));
+ await user.click(await screen.findByRole('button', { name: 'Measure' }));
await user.click(screen.getByRole('button', { name: /cancel/i }));
expect(runLocalLlmAssessment).not.toHaveBeenCalled();
await waitFor(() => expect(screen.queryByText(/Measure this model\?/)).not.toBeInTheDocument());
@@ -159,6 +175,44 @@ describe('LocalModelAssessments', () => {
expect(screen.getByText(/not a mark against them/)).toBeInTheDocument();
});
+ // Two measurements at once measure the contention between them, not the
+ // models — so the queue holding the provider has to quiet the per-model buttons.
+ it('disables the per-model Measure button while the sweep holds the provider', async () => {
+ getLocalLlmAssessments.mockResolvedValue(report({
+ unassessed: [{ backend: 'ollama', modelId: 'example-model:7b', params: '7B' }],
+ }));
+ getLocalLlmAssessmentSweep.mockResolvedValue({ status: 'running', total: 4, completed: 1, current: null, results: [] });
+ render(<LocalModelAssessments />);
+
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Measure' })).toBeDisabled());
+ });
+
+ it('re-reads the ranking once the sweep finishes, so the morning view is current', async () => {
+ const user = userEvent.setup();
+ getLocalLlmAssessmentSweep.mockResolvedValue({ status: 'running', total: 2, completed: 1, current: null, results: [] });
+ cancelLocalLlmAssessmentSweep.mockResolvedValue({ status: 'cancelled', total: 2, completed: 1, current: null, results: [] });
+ render(<LocalModelAssessments />);
+
+ await user.click(await screen.findByRole('button', { name: /stop sweep/i }));
+ // Once for the mount, once because the queue's evidence just changed.
+ await waitFor(() => expect(getLocalLlmAssessments).toHaveBeenCalledTimes(2));
+ });
+
+ it('renders throughput in tokens/s when the runtime reported token counts', async () => {
+ getLocalLlmAssessments.mockResolvedValue(report({
+ ranked: [rankedEntry({ performance: { ...rankedEntry().performance, meanTokensPerSecond: 58.5, tokensEstimated: false } })],
+ }));
+ render(<LocalModelAssessments />);
+ expect(await screen.findByText(/58.5 tok\/s/)).toBeInTheDocument();
+ });
+
+ it('shows chars/s alone for a runtime that reported no token counts', async () => {
+ getLocalLlmAssessments.mockResolvedValue(report({ ranked: [rankedEntry()] }));
+ render(<LocalModelAssessments />);
+ expect(await screen.findByText('120 chars/s')).toBeInTheDocument();
+ expect(screen.queryByText(/tok\/s/)).not.toBeInTheDocument();
+ });
+
it('refetches for the selected intent', async () => {
const user = userEvent.setup();
render(<LocalModelAssessments />);
@@ -197,7 +251,7 @@ describe('LocalModelAssessments', () => {
});
render(<LocalModelAssessments />);
- await user.click(await screen.findByRole('button', { name: /measure/i }));
+ await user.click(await screen.findByRole('button', { name: 'Measure' }));
await user.click(screen.getByRole('button', { name: /run assessment/i }));
await waitFor(() => expect(screen.getByRole('button', { name: /stop/i })).toBeInTheDocument());
@@ -220,7 +274,7 @@ describe('LocalModelAssessments', () => {
});
const { unmount } = render(<LocalModelAssessments />);
- await user.click(await screen.findByRole('button', { name: /measure/i }));
+ await user.click(await screen.findByRole('button', { name: 'Measure' }));
await user.click(screen.getByRole('button', { name: /run assessment/i }));
await waitFor(() => expect(capturedSignal).toBeDefined());
@@ -302,7 +356,7 @@ describe('LocalModelAssessments', () => {
// Never resolves during the test — the run stays in flight so progress renders.
runLocalLlmAssessment.mockImplementation(() => new Promise(() => {}));
render(<LocalModelAssessments />);
- await user.click(await screen.findByRole('button', { name: /measure/i }));
+ await user.click(await screen.findByRole('button', { name: 'Measure' }));
await user.click(await screen.findByRole('button', { name: /run assessment/i }));
return user;
};
@@ -350,6 +404,7 @@ describe('LocalModelAssessments', () => {
describe('LocalModelAssessments — runtimes', () => {
beforeEach(() => {
vi.clearAllMocks();
+ idleSweep();
getLocalLlmAssessments.mockResolvedValue(report());
});
@@ -383,6 +438,7 @@ describe('LocalModelAssessments — runtimes', () => {
describe('LocalModelAssessments — tuning', () => {
beforeEach(() => {
vi.clearAllMocks();
+ idleSweep();
getLocalLlmAssessments.mockResolvedValue(report({
unassessed: [{ backend: 'llama', modelId: 'dflash', params: null }],
}));
@@ -392,7 +448,7 @@ describe('LocalModelAssessments — tuning', () => {
runLocalLlmAssessment.mockResolvedValue({ verdict: 'fits', tuningApplied: true });
const user = userEvent.setup();
render(<LocalModelAssessments />);
- await user.click(await screen.findByRole('button', { name: /Measure/ }));
+ await user.click(await screen.findByRole('button', { name: 'Measure' }));
await user.click(await screen.findByRole('button', { name: /Tuning/ }));
await user.type(screen.getByLabelText('Micro-batch size'), '512');
await user.click(screen.getByRole('button', { name: 'Run assessment' }));
@@ -408,7 +464,7 @@ describe('LocalModelAssessments — tuning', () => {
runLocalLlmAssessment.mockResolvedValue({ verdict: 'fits', tuningApplied: true });
const user = userEvent.setup();
render(<LocalModelAssessments />);
- await user.click(await screen.findByRole('button', { name: /Measure/ }));
+ await user.click(await screen.findByRole('button', { name: 'Measure' }));
await user.click(await screen.findByRole('button', { name: /Tuning/ }));
await user.click(screen.getByRole('button', { name: 'Run assessment' }));
await waitFor(() => expect(runLocalLlmAssessment).toHaveBeenCalledWith(
@@ -420,7 +476,7 @@ describe('LocalModelAssessments — tuning', () => {
it('says what PortOS can and cannot set for each knob', async () => {
const user = userEvent.setup();
render(<LocalModelAssessments />);
- await user.click(await screen.findByRole('button', { name: /Measure/ }));
+ await user.click(await screen.findByRole('button', { name: 'Measure' }));
await user.click(await screen.findByRole('button', { name: /Tuning/ }));
expect(screen.getAllByText(/puts this on the launch line/).length).toBe(2);
});
@@ -431,7 +487,7 @@ describe('LocalModelAssessments — tuning', () => {
});
const user = userEvent.setup();
render(<LocalModelAssessments />);
- await user.click(await screen.findByRole('button', { name: /Measure/ }));
+ await user.click(await screen.findByRole('button', { name: 'Measure' }));
await user.click(screen.getByRole('button', { name: 'Run assessment' }));
await waitFor(() => expect(toast.warning).toHaveBeenCalledWith(expect.stringMatching(/tuning not applied/)));
expect(toast.success).not.toHaveBeenCalled();
@@ -439,7 +495,7 @@ describe('LocalModelAssessments — tuning', () => {
});
describe('LocalModelAssessments — tuning comparison', () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(() => { vi.clearAllMocks(); idleSweep(); });
it('shows each tuning against the winner once a model has two', async () => {
getLocalLlmAssessments.mockResolvedValue(report({
@@ -488,6 +544,7 @@ describe('LocalModelAssessments — one row per tuning', () => {
beforeEach(() => {
vi.clearAllMocks();
+ idleSweep();
getLocalLlmAssessments.mockResolvedValue(report({
ranked: [rankedEntry({ backend: 'llama', modelId: 'dflash', tuningKey: '' }), tunedEntry()],
assessments: [{ backend: 'llama', modelId: 'dflash', tuningKey: '' }, { backend: 'llama', modelId: 'dflash', tuningKey: 'ubatchSize=512' }],
diff --git a/client/src/components/settings/ModelThroughputReport.jsx b/client/src/components/settings/ModelThroughputReport.jsx
new file mode 100644
index 0000000000..4721fd750f
--- /dev/null
+++ b/client/src/components/settings/ModelThroughputReport.jsx
@@ -0,0 +1,178 @@
+/**
+ * Tokens-per-second report.
+ *
+ * The ranked list above it answers "which model should I use?". This answers
+ * "how fast is each one, and where does it fall off?" — one row per measured
+ * model+tuning, with the per-context readings side by side, which is what you
+ * actually read the morning after an overnight sweep.
+ *
+ * ## Two things this must never do
+ *
+ * 1. **Never derive tokens from characters.** PortOS has no tokenizer. Every
+ * figure here comes from the daemon's own usage block, or (labelled `~`) from
+ * counting streamed frames. A blank cell means NOT MEASURED — never zero, and
+ * never chars/s wearing a tok/s label.
+ * 2. **Never hide a model because its runtime is quiet.** A runtime that reports
+ * no token counts still gets a row, with its chars/s figure and an explicit
+ * "no token counts" note. Dropping it would make the table look complete.
+ */
+
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { Timer, Copy, Check } from 'lucide-react';
+import { copyToClipboard } from '../../lib/clipboard';
+import { formatContextTokens, formatDurationMs } from '../../utils/formatters';
+
+// One rate, as text. `null` is not measured and renders as an em dash — never a
+// zero; `estimated` marks a frame-counted figure with a `~` so it is never
+// mistaken for one the daemon's own tokenizer produced. Shared by the table and
+// the markdown serializer so a formatting change lands in both.
+const rateText = (value, estimated) =>
+ (Number.isFinite(value) ? `${estimated ? '~' : ''}${value.toFixed(1)}` : '—');
+
+const Rate = ({ value, estimated, suffix = '' }) => (
+ Number.isFinite(value)
+ ? <span className="text-gray-200 whitespace-nowrap">{rateText(value, estimated)}{suffix}</span>
+ : <span className="text-gray-600">{rateText(value, estimated)}</span>
+);
+
+// A row's samples keyed by context, for the per-context columns.
+const pointsByContext = (row) => new Map((row.points || []).map((p) => [p.contextTokens, p]));
+
+/** The report as a markdown table — what a copy of this is actually useful as. */
+export function toMarkdown(report) {
+ const contexts = report?.contexts || [];
+ const header = ['Model', 'Runtime', 'Tuning', 'tok/s', 'Prefill tok/s', 'TTFT', ...contexts.map((c) => `${formatContextTokens(c)} tok/s`)];
+ const lines = [
+ `| ${header.join(' | ')} |`,
+ `| ${header.map(() => '---').join(' | ')} |`,
+ ];
+ for (const row of report?.rows || []) {
+ const byContext = pointsByContext(row);
+ lines.push(`| ${[
+ row.modelId,
+ row.backend,
+ row.tuningLabel || 'backend defaults',
+ rateText(row.meanTokensPerSecond, row.tokensEstimated),
+ rateText(row.meanPromptTokensPerSecond, row.tokensEstimated),
+ Number.isFinite(row.meanTtftMs) ? formatDurationMs(row.meanTtftMs) : '—',
+ ...contexts.map((c) => rateText(byContext.get(c)?.tokensPerSecond, row.tokensEstimated)),
+ ].join(' | ')} |`);
+ }
+ return lines.join('\n');
+}
+
+export default function ModelThroughputReport({ report, runtimeLabelFor }) {
+ const [copied, setCopied] = useState(false);
+ const copiedTimerRef = useRef(null);
+ useEffect(() => () => clearTimeout(copiedTimerRef.current), []);
+ const contexts = report?.contexts || [];
+ const rows = report?.rows || [];
+ // Indexed once per report rather than per render: the `copied` toggle alone
+ // would otherwise rebuild one Map per row for nothing.
+ const indexed = useMemo(() => rows.map((row) => ({ row, byContext: pointsByContext(row) })), [rows]);
+
+ if (!rows.length) return null;
+
+ const copy = async () => {
+ // Serialized on the click, not on every report change — nothing else needs
+ // the markdown, and a sweep re-reports after every model it finishes.
+ // The button owns its own "Copied" state, so the success toast would be a
+ // second confirmation of the same thing (client/src/lib/clipboard.js).
+ const ok = await copyToClipboard(toMarkdown(report), null);
+ if (!ok) return;
+ setCopied(true);
+ clearTimeout(copiedTimerRef.current);
+ copiedTimerRef.current = setTimeout(() => setCopied(false), 2000);
+ };
+
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <h3 className="text-xs font-medium text-gray-400 flex items-center gap-1.5">
+ <Timer size={12} /> Tokens per second
+ </h3>
+ <button
+ onClick={copy}
+ 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"
+ aria-label="Copy the throughput report as a markdown table"
+ >
+ {copied ? <><Check size={11} /> Copied</> : <><Copy size={11} /> Copy table</>}
+ </button>
+ </div>
+ <p className="text-[11px] text-gray-500">
+ Generation speed after the first token — the same figure llama.cpp and Ollama report. Prefill speed
+ (how fast the prompt was read) and time to first token are beside it, so a model that decodes fast
+ but chews slowly through long context is visible as such.
+ {report.modelsWithTokenRates < rows.length && (
+ <> A <span className="text-gray-400">—</span> means the runtime reported no token counts for that
+ reading; its chars/s figure is in the ranked list above.</>
+ )}
+ </p>
+
+ {/* Wide by nature — one column per sampled context. Scrolls inside its own
+ box so the page body never scrolls sideways on a phone. */}
+ <div className="overflow-x-auto border border-port-border rounded-lg">
+ <table className="w-full text-[11px] min-w-[560px]">
+ <thead>
+ <tr className="text-gray-500 border-b border-port-border">
+ <th scope="col" className="text-left font-medium px-2 py-1.5">Model</th>
+ <th scope="col" className="text-right font-medium px-2 py-1.5 whitespace-nowrap">tok/s</th>
+ <th scope="col" className="text-right font-medium px-2 py-1.5 whitespace-nowrap">Prefill</th>
+ <th scope="col" className="text-right font-medium px-2 py-1.5 whitespace-nowrap">TTFT</th>
+ {contexts.map((context) => (
+ <th key={context} scope="col" className="text-right font-medium px-2 py-1.5 whitespace-nowrap">
+ {formatContextTokens(context)}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {indexed.map(({ row, byContext }) => (
+ <tr key={`${row.backend}:${row.modelId}@${row.tuningKey}`} className="border-b border-port-border/50 last:border-0">
+ <td className="px-2 py-1.5 min-w-0">
+ <div className="text-gray-200 font-mono break-all">{row.modelId}</div>
+ <div className="text-[10px] text-gray-500">
+ {runtimeLabelFor?.(row.backend) || row.backend}
+ <span className="mx-1">·</span>
+ {row.tuningLabel || 'backend defaults'}
+ {row.staleness?.stale && <span className="ml-1 text-port-warning">stale</span>}
+ {/* The numbers are real but describe a configuration nobody
+ asked for — say so here too, not only in the ranked list. */}
+ {row.tuningApplied === false && <span className="ml-1 text-port-warning">tuning not applied</span>}
+ </div>
+ </td>
+ <td className="px-2 py-1.5 text-right"><Rate value={row.meanTokensPerSecond} estimated={row.tokensEstimated} /></td>
+ <td className="px-2 py-1.5 text-right"><Rate value={row.meanPromptTokensPerSecond} estimated={row.tokensEstimated} /></td>
+ <td className="px-2 py-1.5 text-right text-gray-200 whitespace-nowrap">
+ {Number.isFinite(row.meanTtftMs) ? formatDurationMs(row.meanTtftMs) : <span className="text-gray-600">—</span>}
+ </td>
+ {contexts.map((context) => {
+ const point = byContext.get(context);
+ return (
+ <td
+ key={context}
+ className="px-2 py-1.5 text-right"
+ // A context that FAILED is different from one that was
+ // never sampled — the title says which, and why.
+ title={point && !point.ok ? (point.error || 'failed') : undefined}
+ >
+ {point && !point.ok
+ ? <span className="text-port-warning">failed</span>
+ : <Rate value={point?.tokensPerSecond} estimated={row.tokensEstimated} />}
+ </td>
+ );
+ })}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ {rows.some((r) => r.tokensEstimated) && (
+ <p className="text-[10px] text-gray-600">
+ <span className="text-gray-400">~</span> counted from streamed frames — that runtime reported no
+ usage block, so the token count is an approximation, not its tokenizer&apos;s.
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/settings/ModelThroughputReport.test.jsx b/client/src/components/settings/ModelThroughputReport.test.jsx
new file mode 100644
index 0000000000..f4ca5db9d3
--- /dev/null
+++ b/client/src/components/settings/ModelThroughputReport.test.jsx
@@ -0,0 +1,123 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+vi.mock('../../lib/clipboard', () => ({ copyToClipboard: vi.fn(async () => true) }));
+
+import { copyToClipboard } from '../../lib/clipboard';
+import ModelThroughputReport, { toMarkdown } from './ModelThroughputReport.jsx';
+
+const point = (contextTokens, tokensPerSecond, extra = {}) => ({
+ contextTokens, ok: true, tokensPerSecond, promptTokensPerSecond: 900, charsPerSecond: 200,
+ ttftMs: 300, completionTokens: 96, error: null, ...extra,
+});
+
+const row = (modelId, overrides = {}) => ({
+ backend: 'ollama',
+ modelId,
+ tuningKey: '',
+ tuningLabel: null,
+ tuningApplied: null,
+ tuningNotApplied: null,
+ verdict: 'fits',
+ assessedAt: '2026-01-01T00:00:00.000Z',
+ staleness: null,
+ meanTokensPerSecond: 50,
+ peakTokensPerSecond: 60,
+ meanPromptTokensPerSecond: 900,
+ meanCharsPerSecond: 200,
+ meanTtftMs: 300,
+ tokensEstimated: false,
+ points: [point(512, 60), point(4096, 40)],
+ ...overrides,
+});
+
+const report = (rows, contexts = [512, 4096]) => ({
+ rows, contexts, modelsWithTokenRates: rows.filter((r) => r.meanTokensPerSecond !== null).length,
+});
+
+beforeEach(() => vi.clearAllMocks());
+
+describe('ModelThroughputReport', () => {
+ it('renders a column per sampled context and the per-context rates', () => {
+ render(<ModelThroughputReport report={report([row('example-model:7b')])} />);
+ expect(screen.getByRole('columnheader', { name: '512' })).toBeInTheDocument();
+ expect(screen.getByRole('columnheader', { name: '4K' })).toBeInTheDocument();
+ expect(screen.getByText('60.0')).toBeInTheDocument();
+ expect(screen.getByText('40.0')).toBeInTheDocument();
+ });
+
+ // The sentinel contract, in the UI: a runtime that reported no token counts
+ // must render as blank, never as 0 and never as its chars/s figure relabelled.
+ it('renders an unmeasured rate as a dash, not a zero', () => {
+ const quiet = row('quiet-model', {
+ meanTokensPerSecond: null, peakTokensPerSecond: null, meanPromptTokensPerSecond: null,
+ tokensEstimated: null,
+ points: [point(512, null), point(4096, null)],
+ });
+ render(<ModelThroughputReport report={report([quiet])} />);
+ expect(screen.queryByText('0.0')).not.toBeInTheDocument();
+ expect(screen.getAllByText('—').length).toBeGreaterThanOrEqual(4);
+ });
+
+ it('marks a frame-counted figure with a ~ and explains it', () => {
+ render(<ModelThroughputReport report={report([row('estimated-model', { tokensEstimated: true })])} />);
+ expect(screen.getByText('~50.0')).toBeInTheDocument();
+ expect(screen.getByText(/counted from streamed frames/)).toBeInTheDocument();
+ });
+
+ it('omits the estimate footnote when every figure came from a tokenizer', () => {
+ render(<ModelThroughputReport report={report([row('example-model:7b')])} />);
+ expect(screen.queryByText(/counted from streamed frames/)).not.toBeInTheDocument();
+ });
+
+ // A context that failed is a different fact from one that was never sampled.
+ it('says "failed" for a context the model could not run', () => {
+ const partial = row('big-model', {
+ points: [point(512, 30), point(4096, null, { ok: false, error: 'out of memory' })],
+ });
+ render(<ModelThroughputReport report={report([partial])} />);
+ expect(screen.getByText('failed')).toBeInTheDocument();
+ });
+
+ it('flags a reading whose tuning never reached the daemon', () => {
+ const unapplied = row('tuned-model', {
+ tuningLabel: '8k context', tuningApplied: false, tuningNotApplied: 'llama-server is not running',
+ });
+ render(<ModelThroughputReport report={report([unapplied])} />);
+ expect(screen.getByText('tuning not applied')).toBeInTheDocument();
+ });
+
+ it('renders nothing at all when no model has been measured', () => {
+ const { container } = render(<ModelThroughputReport report={report([])} />);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('copies the table as markdown without a second success toast', async () => {
+ const user = userEvent.setup();
+ render(<ModelThroughputReport report={report([row('example-model:7b')])} />);
+
+ await user.click(screen.getByRole('button', { name: /copy the throughput report/i }));
+ expect(copyToClipboard).toHaveBeenCalledWith(expect.stringContaining('example-model:7b'), null);
+ expect(await screen.findByText('Copied')).toBeInTheDocument();
+ });
+});
+
+describe('toMarkdown', () => {
+ it('emits one row per measurement with a column per context', () => {
+ const md = toMarkdown(report([row('example-model:7b')]));
+ const lines = md.split('\n');
+ expect(lines[0]).toBe('| Model | Runtime | Tuning | tok/s | Prefill tok/s | TTFT | 512 tok/s | 4K tok/s |');
+ expect(lines[2]).toContain('| example-model:7b | ollama | backend defaults | 50.0 |');
+ expect(lines[2]).toContain('| 60.0 | 40.0 |');
+ });
+
+ it('writes a dash for an unmeasured cell rather than a zero', () => {
+ const quiet = row('quiet-model', {
+ meanTokensPerSecond: null, meanPromptTokensPerSecond: null, meanTtftMs: null,
+ points: [point(512, null)],
+ });
+ const md = toMarkdown(report([quiet]));
+ expect(md).toContain('| quiet-model | ollama | backend defaults | — | — | — |');
+ });
+});
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 379e618971..2e57644e88 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, playground test/compare, and measured per-model assessments (run + persisted results + intent ranking). |
+| `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 + the server-side "measure everything" sweep). |
| `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 bfe145b8f7..5d0fa64204 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -194,6 +194,27 @@ export const getLocalLlmAssessments = (intent = 'balanced', options) =>
export const runLocalLlmAssessment = (payload, options) =>
request('/local-llm/assessments/run', { method: 'POST', body: JSON.stringify(payload), ...options });
+// === The overnight sweep =====================================================
+// Measure every model the scope covers, in one server-side queue. Unlike
+// `runLocalLlmAssessment` this returns as soon as the queue is built — the run
+// itself keeps going with the tab closed, which is the whole point of starting
+// one at the end of the day. Same consent rule: it only fires from a click that
+// was shown the model and generation count first.
+
+// Queue status: what is running, what has finished, what it measured. Module
+// state on the server, so it is safe to poll and a reload picks a sweep back up.
+export const getLocalLlmAssessmentSweep = (options) =>
+ request('/local-llm/assessments/sweep', options);
+
+// `scope` is 'unmeasured' | 'stale' | 'all'. 409s when a sweep is already
+// running or the scope covers nothing.
+export const startLocalLlmAssessmentSweep = (payload, options) =>
+ request('/local-llm/assessments/sweep', { method: 'POST', body: JSON.stringify(payload), ...options });
+
+// Stop the queue and the model in flight. Everything already measured stays.
+export const cancelLocalLlmAssessmentSweep = (options) =>
+ request('/local-llm/assessments/sweep/cancel', { method: 'POST', ...options });
+
// Drop a stale measurement — after a RAM upgrade or a backend update the
// recorded evidence describes a machine that no longer exists.
//
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 41076d1b41..a239993b99 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -22,7 +22,7 @@ grep -i "what you want to do" client/src/utils/README.md
| Module | Purpose |
|---|---|
-| `formatters` | Date/time/duration/byte/word formatters (`clamp`, `formatBytes`, `formatDownloadGb` (decimal-GB model download size, "~29 GB"), `formatCompactCount`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `parseTimeoutMs`, `formatCooldown`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price) — `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. **Never write `new Date(x).toLocaleDateString()` inline** — pick the helper for the shape you want: `formatDateNumeric` ("3/5/2026", compact cells), `formatDateShort` ("Mar 5, 2026"), `formatDate` ("March 5, 2026"), `formatDateFull` ("Saturday, March 5, 2026"), `formatWeekdayDate` ("Monday, Mar 5", `{ weekday, year }`), `formatMonthDay` ("Mar 5"), `formatMonthYear` ("March 2026"), `formatWeekdayShort` ("Mon"), `formatWeekdayTime` ("Mon, 7:00 AM"), `formatTimeOfDay` ("1:30 PM"), `formatTimeOfDaySeconds` ("1:30:45 PM", log/queue rows), `formatClockTime` ("02:30:45 PM"; `{ seconds, hour12, timeZone }`), `formatDateTime`. All of them anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date". |
+| `formatters` | Date/time/duration/byte/word formatters (`clamp`, `formatBytes`, `formatDownloadGb` (decimal-GB model download size, "~29 GB"), `formatCompactCount`, `timeAgo`, `formatTimecode`, `formatDurationMs`, `formatDateShort`, `formatContextTokens` (suffix-less context length, "4K"), `throughputLabel` (a measured model's speed as one label — tok/s where the runtime reported token counts, `~` prefixed when frame-counted, else chars/s; never both), `parseTimeoutMs`, `formatCooldown`, `recommendedRamGb`, `nameFromImageFilename`, `formatUsd` — one USD renderer (`signed` puts the minus outside the `$`; `trimWhole` drops `.00` on a typed round price) — `formatWeight` / `formatPercent` — round unit-converted floats (`170.35000000000002` → `170.4 lbs`) so raw binary precision never reaches a tile — `middleTruncate` — clip a long string from the MIDDLE so its distinguishing tail survives, where CSS `line-clamp`/`text-overflow` always eats the end — …) plus timeout-input bounds and `getAppName`. Do not re-define formatters inside components. **Never write `new Date(x).toLocaleDateString()` inline** — pick the helper for the shape you want: `formatDateNumeric` ("3/5/2026", compact cells), `formatDateShort` ("Mar 5, 2026"), `formatDate` ("March 5, 2026"), `formatDateFull` ("Saturday, March 5, 2026"), `formatWeekdayDate` ("Monday, Mar 5", `{ weekday, year }`), `formatMonthDay` ("Mar 5"), `formatMonthYear` ("March 2026"), `formatWeekdayShort` ("Mon"), `formatWeekdayTime` ("Mon, 7:00 AM"), `formatTimeOfDay` ("1:30 PM"), `formatTimeOfDaySeconds` ("1:30:45 PM", log/queue rows), `formatClockTime` ("02:30:45 PM"; `{ seconds, hour12, timeZone }`), `formatDateTime`. All of them anchor a bare `YYYY-MM-DD` at LOCAL midnight (a naive `new Date('2026-03-05')` is UTC midnight and renders as the previous day west of Greenwich) and take a fallback instead of rendering the literal "Invalid Date". |
| `cronHelpers` | Cron preset list, `isCronExpression` detection, `describeCron` human-readable rendering, and `JOB_INTERVAL_OPTIONS` — the interval-mode cadences for autonomous jobs, mirroring the server's `INTERVAL_OPTIONS`. Import it rather than re-declaring the list in a scheduling component. |
| `markdownText` | `markdownToPlainText(md)` — flatten markdown source to one plain-text string for a clamped preview: strips heading/list/blockquote/fence markers, unwraps emphasis, inline code and links, images → `[alt]`, collapses blank-line runs. Use whenever a card previews arbitrary agent-authored markdown — `line-clamp-N` does not clamp a subtree of block elements, and foreign `##` headings would otherwise join the page's heading outline. Underscore emphasis is word-boundary gated and `__…__` needs interior whitespace, so stack frames and user-agent strings (`10_15_7`, `__init__`) are never silently rewritten. `dropsMarkupWhenFlattened(md)` — did the flatten lose actual markup, as opposed to only normalizing whitespace? Gates a "Show more" disclosure so a short-but-lossy body stays reachable without putting a toggle on every body that merely lost a trailing newline. |
| `timeWindow` | Time-of-day window math (`isInTimeWindow`, `timeStringToMinutes`) and morning-layout auto-switch helpers (`pickActiveLayoutId`, `recordManualLayoutPick`). |
diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.js
index ceb39330d7..636133eb8c 100644
--- a/client/src/utils/formatters.js
+++ b/client/src/utils/formatters.js
@@ -402,6 +402,40 @@ export function formatContextLength(tokens, { suffix = ' ctx' } = {}) {
return `${n}${suffix}`;
}
+/**
+ * Context length with NO unit suffix — `4096` → `"4K"` — for prose that
+ * already says "tokens of context" around it.
+ *
+ * Three surfaces in the Models section had each declared this same one-line
+ * alias privately; it lives here, beside `formatContextLength`, so a change to
+ * the K/M thresholds reaches all of them.
+ */
+export function formatContextTokens(tokens) {
+ return formatContextLength(tokens, { suffix: '' });
+}
+
+/**
+ * How fast a measured model generated, as one label: `"58.5 tok/s"`,
+ * `"~58.5 tok/s"` for a frame-counted estimate, or `"240 chars/s"` when the
+ * runtime reported no token counts at all. `null` when neither was measured.
+ *
+ * Tokens/s leads because it is the figure people compare local models on, and
+ * the two are never shown together — one row carrying both units reads as a
+ * contradiction. The `~` is not decoration: PortOS has no tokenizer, so a count
+ * derived from counting streamed frames must never be presented as one the
+ * daemon's tokenizer produced.
+ *
+ * @param {{meanTokensPerSecond?: number|null, meanCharsPerSecond?: number|null, tokensEstimated?: boolean|null}} perf
+ */
+export function throughputLabel(perf) {
+ const tokens = perf?.meanTokensPerSecond;
+ if (typeof tokens === 'number' && Number.isFinite(tokens)) {
+ return `${perf?.tokensEstimated ? '~' : ''}${tokens} tok/s`;
+ }
+ const chars = perf?.meanCharsPerSecond;
+ return typeof chars === 'number' && Number.isFinite(chars) ? `${chars} chars/s` : null;
+}
+
/**
* Count whitespace-separated words in a string. Mirrors the canonical
* server-side `countWords` in `server/lib/textUtils.js` (the client cannot
diff --git a/server/lib/README.md b/server/lib/README.md
index 03343a4b28..797bc45a90 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -139,7 +139,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `mtplxModels.js` | `listMtplxCachedModels({command?})` → `{models, error}` from `mtplx models --json` (a local directory listing — no network, no model load) and `pickMtplxCachedModel(models)` → the repo id to hand `mtplx serve --model`. `models: null` means the cache could not be READ (no binary, command failed, unparseable) and is deliberately distinct from `[]` (read, and empty), because `services/localRuntimeSetup.js` starts MTPLX on its own default in the first case and refuses with the `mtplx pull` command in the second. Exists because `mtplx serve` defaults `--model` to one hard-coded checkpoint and exits 1 before binding when that repo is not cached — even on a host holding a different MTP model that serves fine. Picks only entries MTPLX itself calls complete (`validation.ok !== false`, so a half-finished pull is not served), preferring one with a recorded `mtplx_runtime.json` exactness contract. |
| `vllmQwenProject.js` | `resolveVllmProjectDir()` / `inspectVllmQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the operator-cloned syv-ai/qwen38-27b-rtx3090 compose project, plus `vllmStartBlockedReason(project)` → the prose refusal (or `null`). Directory reads only — never runs docker or touches a registry. `hasWeights` is tri-state: `true` found / `false` caches read and empty / `null` no cache readable (a docker-volume cache is invisible from a native-Win32 PortOS), and `services/localRuntimeSetup.js` refuses to `docker compose up` on anything but `true` so the start button can never kick off the ~20 GB prepare. Overrides: `VLLM_QWEN_PROJECT_DIR`, `VLLM_QWEN_WEIGHTS_DIR`. |
| `openAiModelsProbe.js` | `probeOpenAiModels(baseUrl, { timeoutMs, apiKey })` → `{ reachable, models, error }` — the one `GET {base}/models` probe for the local OpenAI-compatible daemons, shared by `services/providerReadiness.js` and `services/llamaServerManager.js`. Distinguishes unreachable from reachable-but-unlistable (`models: null`) from up-with-nothing-loaded (`[]`), names the real transport failure via `describeFetchError` (undici reports every one as a bare `fetch failed`), and cancels an unread body on a non-OK response. `apiKey` attaches a Bearer header for a key-gated daemon (vLLM's compose stack), and a 401/403 answers `reachable: true` with `error: 'authentication required'` — a server that refused the request is definitively running, and calling it unreachable would send the user to start it again. Consolidated after the two copies drifted — one passed its timeout as a `timeout` key inside the fetch init object, where it is not an option, silently running a 500ms poll loop on the 15s default. |
-| `openAiChatStream.js` | `streamOpenAiChat({ endpoint, apiKey, model, messages, temperature, maxTokens, extraBody, signal, onChunk })` → the streamed text — one streaming `POST {base}/chat/completions` against any local OpenAI-compatible daemon, plus `buildMessages`, `extractStreamDelta` (skips a malformed SSE frame instead of aborting the stream) and `resolvePartialOutput` (content, else reasoning, else `''`). Sibling of `openAiModelsProbe.js`. Shared by `services/localLlmPlayground.js` (provider-backed runs with a `/runs` record) and its `runEndpointLlmTest` (a bare loopback daemon PortOS holds no provider record for, which is how `services/localModelAssessments.js` measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with `.partialOutput` carrying what already streamed. |
+| `openAiChatStream.js` | `streamOpenAiChat({ endpoint, apiKey, model, messages, temperature, maxTokens, extraBody, signal, onChunk, onStats })` → the streamed text — one streaming `POST {base}/chat/completions` against any local OpenAI-compatible daemon, plus `buildMessages`, `parseStreamFrame` (content/reasoning delta + the terminal `usage` block; skips a malformed SSE frame instead of aborting the stream), `normalizeUsage` (snake/camel/Ollama token-count keys → `{completionTokens, promptTokens}`, `null` = not reported). Registering `onStats` is what asks for token counts; a daemon that rejects `stream_options` is retried once without it and remembered per endpoint and `resolvePartialOutput` (content, else reasoning, else `''`). Sibling of `openAiModelsProbe.js`. Shared by `services/localLlmPlayground.js` (provider-backed runs with a `/runs` record) and its `runEndpointLlmTest` (a bare loopback daemon PortOS holds no provider record for, which is how `services/localModelAssessments.js` measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with `.partialOutput` carrying what already streamed. |
| `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |
@@ -313,7 +313,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `specDecodePresets.js` | Curated llama-server speculative-decoding presets (target + drafter GGUF paths, `--spec-type`, and the Hugging Face repo/quant each file comes from) plus `findSpecDecodePreset` / `specDecodeSource` / `hfSearchUrl`. Also owns the `--spec-type` vocabulary: `SPEC_TYPE_SUGGESTIONS` (published to the launcher card), `parseSpecTypes` (the flag is a comma-separated list) and `isDraftSpecType` (the `draft-` prefix is what needs a drafter GGUF — every `ngram-*` type runs without one). Server-owned so the launcher card can offer a Download button per file. Pure. |
| `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, { measured })` ranks installed models for editorial review/editing, dropping any a fresh measurement proved cannot run here. 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, `explainAssessment`, `compareEnvironments`/`describeStaleness` (is a stored reading still valid for THIS machine?), and `measuredFitVerdict`/`reconcileFit` (fold a measurement into the catalog's size-estimate fit badge, keeping the disagreement). Pure. `null` strictly means NOT MEASURED — never 0, never "failed". |
+| `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 AND tokens-per-second, prefill rate, TTFT, max working context, cross-context degradation), `scoreAssessment` + `scoreForIntent` + `rankByIntent` for the balanced/smartest/fastest/lightweight pickers, `explainAssessment`, `compareEnvironments`/`describeStaleness` (is a stored reading still valid for THIS machine?), `buildThroughputReport` (every measurement as one tokens/s table, fastest first, per-context readings intact), `selectSweepTargets`/`summarizeSweepScopes`/`SWEEP_SCOPES` (which measurements a "measure everything" run covers, and how many), and `measuredFitVerdict`/`reconcileFit` (fold a measurement into the catalog's size-estimate fit badge, keeping the disagreement). Pure. `null` strictly means NOT MEASURED — never 0, never "failed". |
| `localModelTuning.js` | Launch/runtime tuning knobs for the measurable local runtimes: `TUNING_SPECS` (per runtime — llama.cpp's `-b`/`-ub`/`-t`/`--flash-attn`/`--cache-type-k|v`/`--draft-max`, Ollama's `num_ctx`, plus the record-only knobs for LM Studio / MTPLX / vLLM), each declaring `applies: 'launch' \| 'request' \| 'record'` so the UI can never claim PortOS set something it cannot. `normalizeTuning` (coerce + clamp + drop unknown keys), `tuningSignature` (stable identity — `''` for backend defaults, so pre-tuning store keys keep resolving), `describeTuning`, `launchTuning`, `requestBody` (request knobs under their wire names), and `compareTunings` (which tuning won per model, with a `deltaPercent` against the winner). Pure. |
| `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. |
diff --git a/server/lib/localModelAssessment.js b/server/lib/localModelAssessment.js
index ec0777396f..27f685b34d 100644
--- a/server/lib/localModelAssessment.js
+++ b/server/lib/localModelAssessment.js
@@ -144,18 +144,32 @@ function meanOf(samples, field) {
* @param {Array<object>} samples
*/
export function summarizePerformance(samples) {
- const measured = okSamples(samples)
+ const ok = okSamples(samples);
+ const measured = ok
.filter((s) => isMeasured(s.charsPerSecond) && s.charsPerSecond > 0 && isMeasured(s.contextTokens));
const fastest = measured.length ? Math.max(...measured.map((s) => s.charsPerSecond)) : null;
const atLongest = measured.length
? measured.reduce((longest, s) => (s.contextTokens > longest.contextTokens ? s : longest)).charsPerSecond
: null;
+ const tokenRates = ok.map((s) => s.tokensPerSecond).filter(isMeasured);
return {
samplesRun: Array.isArray(samples) ? samples.length : 0,
- samplesOk: okSamples(samples).length,
+ samplesOk: ok.length,
meanCharsPerSecond: meanOf(samples, 'charsPerSecond'),
meanTtftMs: meanOf(samples, 'ttftMs'),
peakCharsPerSecond: fastest,
+ // Token-denominated throughput, present only when the daemon reported token
+ // counts. `null` here means the runtime told us nothing — a reader must show
+ // "not measured", not fall back to chars/s under a tokens/s label.
+ meanTokensPerSecond: meanOf(samples, 'tokensPerSecond'),
+ peakTokensPerSecond: tokenRates.length ? Math.max(...tokenRates) : null,
+ meanPromptTokensPerSecond: meanOf(samples, 'promptTokensPerSecond'),
+ // `true` when ANY contributing sample counted streamed frames instead of
+ // reading the daemon's own count. One estimated sample makes the mean an
+ // estimate, so this is deliberately pessimistic. `null` = no token evidence.
+ tokensEstimated: tokenRates.length
+ ? ok.some((s) => isMeasured(s.tokensPerSecond) && s.tokensEstimated === true)
+ : null,
maxWorkingContextTokens: maxWorkingContextTokens(samples),
// Clamped: the longest context can measure marginally ABOVE the peak of the
// others only through noise, and a >1 "degradation" is meaningless.
@@ -164,13 +178,109 @@ export function summarizePerformance(samples) {
};
}
-// 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.
+/**
+ * Flatten every measurement into one tokens-per-second table, fastest first.
+ *
+ * This is the "how fast is each model, really" view: one row per measured
+ * model+tuning, carrying the per-context readings so falloff as the prompt grows
+ * is visible rather than averaged away. It is a REPORT, not a ranking — no
+ * scoring, no intent, no exclusions — so a model that only ran at 512 tokens
+ * still appears, with one column filled and the rest honestly blank.
+ *
+ * Rows whose runtime reported no token counts are still included (with `null`
+ * rates) rather than dropped: "this runtime does not report tokens" is the
+ * answer to why a model is missing from a tokens/s table, and silently omitting
+ * it would make the table look complete when it isn't.
+ *
+ * @param {Array<object>} assessments stored assessment records
+ * @returns {{ rows: Array<object>, contexts: number[], modelsWithTokenRates: number }}
+ */
+export function buildThroughputReport(assessments) {
+ const list = Array.isArray(assessments) ? assessments : [];
+ // Every rate on a row is null-or-measured; nothing is defaulted to 0.
+ const num = (value) => (isMeasured(value) ? value : null);
+ const contexts = new Set();
+ const rows = [];
+
+ for (const assessment of list) {
+ const samples = Array.isArray(assessment?.samples) ? assessment.samples : [];
+ const perf = assessment?.performance || {};
+ const points = [];
+ for (const sample of samples) {
+ if (!isMeasured(sample?.contextTokens)) continue;
+ contexts.add(sample.contextTokens);
+ points.push({
+ contextTokens: sample.contextTokens,
+ ok: sample?.ok === true,
+ // A failed sample carries its error so the cell can say WHY it is blank
+ // instead of just being blank.
+ tokensPerSecond: num(sample.tokensPerSecond),
+ promptTokensPerSecond: num(sample.promptTokensPerSecond),
+ charsPerSecond: num(sample.charsPerSecond),
+ ttftMs: num(sample.ttftMs),
+ completionTokens: num(sample.completionTokens),
+ error: sample?.error || null,
+ });
+ }
+ rows.push({
+ backend: assessment?.backend || null,
+ modelId: assessment?.modelId || null,
+ tuningKey: assessment?.tuningKey || '',
+ tuningLabel: assessment?.tuningLabel || null,
+ // A reading taken under a tuning that never reached the daemon describes
+ // some OTHER configuration. It stays in the table (the numbers are real)
+ // but has to carry the caveat, or the row credits the wrong config.
+ tuningApplied: assessment?.tuningApplied ?? null,
+ tuningNotApplied: assessment?.tuningNotApplied || null,
+ verdict: assessment?.verdict || 'unknown',
+ assessedAt: assessment?.assessedAt || null,
+ staleness: assessment?.staleness || null,
+ meanTokensPerSecond: num(perf.meanTokensPerSecond),
+ peakTokensPerSecond: num(perf.peakTokensPerSecond),
+ meanPromptTokensPerSecond: num(perf.meanPromptTokensPerSecond),
+ meanCharsPerSecond: num(perf.meanCharsPerSecond),
+ meanTtftMs: num(perf.meanTtftMs),
+ tokensEstimated: typeof perf.tokensEstimated === 'boolean' ? perf.tokensEstimated : null,
+ points: points.sort((a, b) => a.contextTokens - b.contextTokens),
+ });
+ }
+
+ // Fastest first, but a row with NO token rate sorts last rather than as zero —
+ // unmeasured is not slow. Ties fall back to model id so the order is stable.
+ rows.sort((a, b) => {
+ const left = a.meanTokensPerSecond;
+ const right = b.meanTokensPerSecond;
+ if (left === null && right === null) return String(a.modelId).localeCompare(String(b.modelId));
+ if (left === null) return 1;
+ if (right === null) return -1;
+ return right - left || String(a.modelId).localeCompare(String(b.modelId));
+ });
+
+ return {
+ rows,
+ contexts: [...contexts].sort((a, b) => a - b),
+ // How many rows actually carry a tokens/s figure, so the UI can explain an
+ // empty table ("no local runtime here reports token counts") instead of
+ // rendering a blank grid.
+ modelsWithTokenRates: rows.filter((r) => r.meanTokensPerSecond !== null).length,
+ };
+}
+
+// Speed normalization anchor, in CHARACTERS per second.
+//
+// Chars/s, not tokens/s, and deliberately so. PortOS now RECORDS tokens/s when
+// the daemon reports token counts (`summarizeTimings`), and reports it — but it
+// cannot SCORE on it: a runtime that reports no usage block would score `null`
+// on speed and drop out of the ranking entirely, and records written before
+// token counts existed carry none. Chars/s is the one figure every runtime and
+// every stored record has, so the ranking stays comparable across both.
+// Still no tokenizer in the repo: nothing here ever derives a token count from
+// a character count.
+//
+// 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
@@ -272,7 +382,14 @@ const INTENT_LABEL = {
export function explainAssessment(assessment, intent) {
const perf = assessment?.performance || {};
const parts = [];
- if (isMeasured(perf.meanCharsPerSecond)) parts.push(`${perf.meanCharsPerSecond} chars/s measured`);
+ // Tokens/s leads when the runtime reported token counts — it is the figure
+ // people actually compare local models on. Chars/s is the fallback, never both:
+ // two throughput numbers in one sentence read as a contradiction.
+ if (isMeasured(perf.meanTokensPerSecond)) {
+ parts.push(`${perf.meanTokensPerSecond} tok/s${perf.tokensEstimated ? ' (estimated)' : ''} measured`);
+ } else 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`);
}
@@ -385,6 +502,85 @@ export function rankByIntent(assessments, intent = 'balanced') {
return { intent: resolvedIntent, ranked, excluded };
}
+// ---- batch measurement ------------------------------------------------------
+
+/** What a "measure everything" run can cover. */
+export const SWEEP_SCOPES = ['unmeasured', 'stale', 'all'];
+
+const targetKey = (t) => `${t.backend}:${t.modelId}@${t.tuningKey || ''}`;
+
+/**
+ * Expand a sweep scope into the exact list of measurements to run.
+ *
+ * Pure and deterministic so the consent modal can be told the real count before
+ * anything runs, and so the sweep and the count can never disagree about what
+ * "all" means — they call this same function.
+ *
+ * A re-measure reuses the tuning that produced the existing record, matching
+ * what the single-model Measure-again button does: "run it again" has to
+ * reproduce the same configuration, or the sweep would quietly replace every
+ * tuned reading with a backend-defaults one.
+ *
+ * @param {object} options
+ * @param {Array<object>} options.assessments stored records, already filtered to
+ * models that are STILL INSTALLED — a sweep must not queue a model the runtime
+ * can no longer load.
+ * @param {Array<{backend:string, modelId:string}>} options.unassessed models with
+ * no evidence at all
+ * @param {'unmeasured'|'stale'|'all'} options.scope
+ * @returns {Array<{backend:string, modelId:string, tuning:object, tuningKey:string, tuningLabel:string|null, reason:string}>}
+ */
+export function selectSweepTargets({ assessments = [], unassessed = [], scope = 'unmeasured' } = {}) {
+ const resolved = SWEEP_SCOPES.includes(scope) ? scope : 'unmeasured';
+ const stored = Array.isArray(assessments) ? assessments : [];
+ const fresh = Array.isArray(unassessed) ? unassessed : [];
+ const targets = [];
+ const seen = new Set();
+
+ const add = (target) => {
+ const key = targetKey(target);
+ if (!target.backend || !target.modelId || seen.has(key)) return;
+ seen.add(key);
+ targets.push(target);
+ };
+
+ // Never-measured models come first in every scope that includes them: they are
+ // the ones with no answer at all, so if an overnight run is cut short they are
+ // the measurements worth having got.
+ if (resolved === 'unmeasured' || resolved === 'all') {
+ for (const model of fresh) {
+ add({ backend: model?.backend, modelId: model?.modelId, tuning: {}, tuningKey: '', tuningLabel: null, reason: 'never measured' });
+ }
+ }
+
+ if (resolved === 'stale' || resolved === 'all') {
+ for (const assessment of stored) {
+ if (resolved === 'stale' && !assessment?.staleness?.stale) continue;
+ add({
+ backend: assessment?.backend,
+ modelId: assessment?.modelId,
+ tuning: assessment?.tuning && typeof assessment.tuning === 'object' ? assessment.tuning : {},
+ tuningKey: assessment?.tuningKey || '',
+ tuningLabel: assessment?.tuningLabel || null,
+ reason: assessment?.staleness?.stale ? 'measured on a different machine state' : 're-measure',
+ });
+ }
+ }
+
+ return targets;
+}
+
+/**
+ * How many measurements each scope would run, for the consent gate.
+ * Derived from `selectSweepTargets` so a displayed count is always the count
+ * that would actually execute.
+ */
+export function summarizeSweepScopes({ assessments, unassessed } = {}) {
+ return Object.fromEntries(
+ SWEEP_SCOPES.map((scope) => [scope, selectSweepTargets({ assessments, unassessed, scope }).length])
+ );
+}
+
// ---- staleness ---------------------------------------------------------------
/**
diff --git a/server/lib/localModelAssessment.test.js b/server/lib/localModelAssessment.test.js
index 7d5fd97658..6d141057a8 100644
--- a/server/lib/localModelAssessment.test.js
+++ b/server/lib/localModelAssessment.test.js
@@ -11,6 +11,9 @@ import {
scoreAssessment,
scoreForIntent,
summarizePerformance,
+ buildThroughputReport,
+ selectSweepTargets,
+ summarizeSweepScopes,
compareEnvironments,
describeStaleness,
measuredFitVerdict,
@@ -536,3 +539,170 @@ describe('rankByIntent staleness', () => {
expect(ranked[0].modelId).toBe('unannotated:14b');
});
});
+
+// ---- tokens per second -------------------------------------------------------
+
+const tokenSample = (contextTokens, tokensPerSecond, { estimated = false, promptRate = null } = {}) => ({
+ ...okSample(contextTokens, 200),
+ tokensPerSecond,
+ promptTokensPerSecond: promptRate,
+ completionTokens: 96,
+ tokensEstimated: estimated,
+});
+
+describe('summarizePerformance — token throughput', () => {
+ it('averages the measured tokens/s alongside chars/s', () => {
+ const perf = summarizePerformance([tokenSample(512, 40), tokenSample(4096, 20)]);
+ expect(perf.meanTokensPerSecond).toBe(30);
+ expect(perf.peakTokensPerSecond).toBe(40);
+ expect(perf.tokensEstimated).toBe(false);
+ });
+
+ // A runtime that reports no usage block must not have a tokens/s figure
+ // invented from its character count.
+ it('reports null token rates when no sample carried one', () => {
+ const perf = summarizePerformance([okSample(512, 200), okSample(4096, 100)]);
+ expect(perf.meanTokensPerSecond).toBeNull();
+ expect(perf.peakTokensPerSecond).toBeNull();
+ expect(perf.tokensEstimated).toBeNull();
+ expect(perf.meanCharsPerSecond).toBe(150);
+ });
+
+ it('marks the mean as estimated when ANY contributing sample was frame-counted', () => {
+ const perf = summarizePerformance([tokenSample(512, 40), tokenSample(4096, 20, { estimated: true })]);
+ expect(perf.tokensEstimated).toBe(true);
+ });
+});
+
+describe('explainAssessment — throughput clause', () => {
+ it('leads with tokens/s when it was measured', () => {
+ const text = explainAssessment({ performance: summarizePerformance([tokenSample(512, 40)]) }, 'fastest');
+ expect(text).toContain('40 tok/s');
+ expect(text).not.toContain('chars/s');
+ });
+
+ it('falls back to chars/s, and never reports both', () => {
+ const text = explainAssessment({ performance: summarizePerformance([okSample(512, 200)]) }, 'fastest');
+ expect(text).toContain('200 chars/s');
+ expect(text).not.toContain('tok/s');
+ });
+});
+
+describe('buildThroughputReport', () => {
+ const record = (modelId, rates) => ({
+ backend: 'ollama',
+ modelId,
+ tuningKey: '',
+ verdict: 'fits',
+ samples: rates.map(([context, rate]) => tokenSample(context, rate)),
+ performance: summarizePerformance(rates.map(([context, rate]) => tokenSample(context, rate))),
+ });
+
+ it('sorts fastest first and collects every sampled context as a column', () => {
+ const report = buildThroughputReport([
+ record('slow-model', [[512, 10], [4096, 8]]),
+ record('fast-model', [[512, 60], [4096, 40]]),
+ ]);
+ expect(report.rows.map((r) => r.modelId)).toEqual(['fast-model', 'slow-model']);
+ expect(report.contexts).toEqual([512, 4096]);
+ expect(report.rows[0].points.map((p) => p.tokensPerSecond)).toEqual([60, 40]);
+ expect(report.modelsWithTokenRates).toBe(2);
+ });
+
+ // Unmeasured is not slow. A runtime that reports no token counts still gets a
+ // row — dropping it would make the table look complete when it isn't.
+ it('keeps a row with no token rate, and sorts it last rather than as zero', () => {
+ const quiet = {
+ backend: 'llama',
+ modelId: 'quiet-model',
+ verdict: 'fits',
+ samples: [okSample(512, 300)],
+ performance: summarizePerformance([okSample(512, 300)]),
+ };
+ const report = buildThroughputReport([quiet, record('fast-model', [[512, 5]])]);
+ expect(report.rows.map((r) => r.modelId)).toEqual(['fast-model', 'quiet-model']);
+ expect(report.rows[1].meanTokensPerSecond).toBeNull();
+ expect(report.rows[1].meanCharsPerSecond).toBe(300);
+ expect(report.modelsWithTokenRates).toBe(1);
+ });
+
+ it('carries a failed sample as failed rather than dropping the context', () => {
+ const report = buildThroughputReport([{
+ backend: 'ollama',
+ modelId: 'big-model',
+ verdict: 'fits',
+ samples: [tokenSample(512, 12), failSample(16384, 'out of memory')],
+ performance: summarizePerformance([tokenSample(512, 12), failSample(16384, 'out of memory')]),
+ }]);
+ expect(report.contexts).toEqual([512, 16384]);
+ const failed = report.rows[0].points.find((p) => p.contextTokens === 16384);
+ expect(failed.ok).toBe(false);
+ expect(failed.tokensPerSecond).toBeNull();
+ expect(failed.error).toBe('out of memory');
+ });
+
+ it('returns an empty report for no assessments rather than throwing', () => {
+ expect(buildThroughputReport(null)).toEqual({ rows: [], contexts: [], modelsWithTokenRates: 0 });
+ });
+});
+
+// ---- sweep target selection --------------------------------------------------
+
+describe('selectSweepTargets', () => {
+ const stale = {
+ backend: 'ollama', modelId: 'stale-model', tuningKey: 'ctx=8192', tuningLabel: '8k context',
+ tuning: { numCtx: 8192 }, staleness: { stale: true },
+ };
+ const fresh = {
+ backend: 'ollama', modelId: 'fresh-model', tuningKey: '', tuningLabel: null,
+ tuning: {}, staleness: { stale: false },
+ };
+ const unassessed = [{ backend: 'lmstudio', modelId: 'new-model' }];
+
+ it('queues only never-measured models for the unmeasured scope', () => {
+ const targets = selectSweepTargets({ assessments: [stale, fresh], unassessed, scope: 'unmeasured' });
+ expect(targets.map((t) => t.modelId)).toEqual(['new-model']);
+ });
+
+ it('queues only stale readings for the stale scope', () => {
+ const targets = selectSweepTargets({ assessments: [stale, fresh], unassessed, scope: 'stale' });
+ expect(targets.map((t) => t.modelId)).toEqual(['stale-model']);
+ });
+
+ // A re-measure has to reproduce the configuration that produced the record, or
+ // the sweep quietly replaces every tuned reading with a defaults one.
+ it('re-uses each record\'s tuning so a re-measure reproduces its configuration', () => {
+ const [target] = selectSweepTargets({ assessments: [stale], unassessed: [], scope: 'stale' });
+ expect(target.tuning).toEqual({ numCtx: 8192 });
+ expect(target.tuningKey).toBe('ctx=8192');
+ });
+
+ it('covers unmeasured models FIRST in the all scope, so a cut-short run got the unknowns', () => {
+ const targets = selectSweepTargets({ assessments: [stale, fresh], unassessed, scope: 'all' });
+ expect(targets.map((t) => t.modelId)).toEqual(['new-model', 'stale-model', 'fresh-model']);
+ });
+
+ it('never queues the same model+tuning twice', () => {
+ const targets = selectSweepTargets({
+ assessments: [fresh, fresh],
+ unassessed: [{ backend: 'ollama', modelId: 'fresh-model' }],
+ scope: 'all',
+ });
+ expect(targets).toHaveLength(1);
+ });
+
+ it('falls back to the unmeasured scope for an unrecognized scope', () => {
+ const targets = selectSweepTargets({ assessments: [stale], unassessed, scope: 'everything-please' });
+ expect(targets.map((t) => t.modelId)).toEqual(['new-model']);
+ });
+});
+
+describe('summarizeSweepScopes', () => {
+ it('counts exactly what each scope would run', () => {
+ const counts = summarizeSweepScopes({
+ assessments: [{ backend: 'ollama', modelId: 'a', staleness: { stale: true } }],
+ unassessed: [{ backend: 'ollama', modelId: 'b' }, { backend: 'ollama', modelId: 'c' }],
+ });
+ expect(counts).toEqual({ unmeasured: 2, stale: 1, all: 3 });
+ });
+});
diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.js
index e6e945f2d4..358939bb1c 100644
--- a/server/lib/mediaValidation.js
+++ b/server/lib/mediaValidation.js
@@ -11,6 +11,7 @@
import { z } from 'zod';
import { PORTS } from './ports.js';
import { ASSESSABLE_RUNTIMES } from './localProviderRuntime.js';
+import { SWEEP_SCOPES } from './localModelAssessment.js';
// OpenWorld snapshot pipeline (issue #877): how often to capture a city-state
// frame and how many to retain. Validated as a settings slice on PUT /api/settings;
@@ -239,6 +240,14 @@ export const localLlmAssessmentRunSchema = z.object({
contextTokens: z.array(z.coerce.number().int().min(64).max(131072)).min(1).max(5).optional(),
tuning: localLlmTuningSchema,
});
+// "Measure everything" — one request, one server-side queue, hours of provider
+// work. The scope decides WHICH models (see `selectSweepTargets`); the target
+// list itself is derived server-side rather than sent, so a client can't ask for
+// an arbitrary batch of models.
+export const localLlmAssessmentSweepSchema = z.object({
+ scope: z.enum(SWEEP_SCOPES).optional().default('unmeasured'),
+ 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'),
});
diff --git a/server/lib/openAiChatStream.js b/server/lib/openAiChatStream.js
index 2a310622e6..f2226ee07d 100644
--- a/server/lib/openAiChatStream.js
+++ b/server/lib/openAiChatStream.js
@@ -22,13 +22,19 @@
import { readResponseJson } from './readResponseJson.js';
/**
- * Parse one OpenAI-style SSE `data:` line into its content/reasoning delta.
+ * Parse one OpenAI-style SSE `data:` line into its content/reasoning delta and,
+ * when the daemon sent one, its `usage` block.
+ *
* Returns null for non-data lines, the `[DONE]`/`✅` sentinels, or a malformed
* frame: a single bad frame must SKIP, not abort the stream — one non-JSON
* keep-alive would otherwise throw out of the read loop and discard every
* token already received.
+ *
+ * `usage` rides on a terminal frame that carries an EMPTY `choices` array (that
+ * is how `stream_options.include_usage` reports it), so a frame can legitimately
+ * carry a usage block and no delta at all.
*/
-export function extractStreamDelta(rawLine) {
+export function parseStreamFrame(rawLine) {
const line = rawLine.trim();
if (!line.startsWith('data: ')) return null;
const data = line.slice(6).trim();
@@ -40,7 +46,49 @@ export function extractStreamDelta(rawLine) {
return null;
}
const delta = parsed?.choices?.[0]?.delta;
- return { content: delta?.content || '', reasoning: delta?.reasoning || '' };
+ return {
+ content: delta?.content || '',
+ reasoning: delta?.reasoning || '',
+ // `null` = this frame reported no usage, which is every frame but the last.
+ usage: parsed?.usage && typeof parsed.usage === 'object' ? parsed.usage : null,
+ };
+}
+
+// Endpoints that answered 4xx to `stream_options`. A sweep runs hundreds of
+// samples against the same daemon, and re-discovering its incompatibility on
+// every one would double the prefill cost of each — including a 16k-token
+// context. Absent from the set = never rejected (which covers "never tried"),
+// the same "validate, don't infer" shape the local-LLM model caches use.
+const usageUnsupportedEndpoints = new Set();
+
+/** Test seam: forget which endpoints rejected `stream_options`. */
+export function __resetUsageSupport() {
+ usageUnsupportedEndpoints.clear();
+}
+
+/**
+ * Normalize a provider `usage` block into the token counts PortOS records.
+ *
+ * Every OpenAI-compatible local daemon reports snake_case (`completion_tokens`),
+ * but Ollama's native passthrough and a few forks use camelCase — accept both
+ * rather than silently recording "no tokens" for half the runtimes.
+ *
+ * `null` on either field means NOT REPORTED. It never means zero: a zero-token
+ * completion is a real (failed) measurement, and collapsing the two would let a
+ * daemon that reports nothing masquerade as one that generated nothing.
+ */
+export function normalizeUsage(usage) {
+ const pick = (...keys) => {
+ for (const key of keys) {
+ const value = usage?.[key];
+ if (typeof value === 'number' && Number.isFinite(value) && value >= 0) return value;
+ }
+ return null;
+ };
+ return {
+ completionTokens: pick('completion_tokens', 'completionTokens', 'eval_count'),
+ promptTokens: pick('prompt_tokens', 'promptTokens', 'prompt_eval_count'),
+ };
}
/**
@@ -80,6 +128,13 @@ export function buildMessages({ systemPrompt, prompt }) {
* @param {AbortSignal} [options.signal]
* @param {(chunk: string, kind: 'content'|'reasoning') => any} [options.onChunk]
* awaited, so a consumer's backpressure reaches the upstream read loop.
+ * @param {(stats: object) => void} [options.onStats] registering one is what
+ * asks the daemon for a terminal usage frame (`stream_options.include_usage`);
+ * a daemon that rejects the key is retried once without it and remembered, so
+ * no caller has to know which runtimes support it. Called exactly once, before
+ * this resolves or throws, with `{ completionTokens, promptTokens, estimated }`.
+ * Token counts are `null` when the daemon reported none AND nothing streamed
+ * to estimate from — never 0, which would read as "generated nothing".
* @returns {Promise<string>} the streamed text. Throws on transport/HTTP
* failure; an abort mid-stream throws with `.partialOutput` carrying whatever
* had already streamed.
@@ -94,11 +149,16 @@ export async function streamOpenAiChat({
extraBody = {},
signal,
onChunk,
+ onStats,
}) {
const headers = { 'Content-Type': 'application/json' };
if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
+ const url = `${String(endpoint || '').replace(/\/+$/, '')}/chat/completions`;
+ // Ask for usage whenever anyone is listening — unless this endpoint already
+ // told us it does not understand the key.
+ const includeUsage = typeof onStats === 'function' && !usageUnsupportedEndpoints.has(url);
- const response = await fetch(`${String(endpoint || '').replace(/\/+$/, '')}/chat/completions`, {
+ const post = (withUsage) => fetch(url, {
method: 'POST',
headers,
signal,
@@ -108,15 +168,42 @@ export async function streamOpenAiChat({
stream: true,
temperature,
max_tokens: maxTokens,
+ ...(withUsage ? { stream_options: { include_usage: true } } : {}),
...extraBody,
}),
}).catch((err) => ({ ok: false, status: 0, error: err.message }));
+ let response = await post(includeUsage);
+ // `stream_options` is standard OpenAI, but a stricter daemon (or an older
+ // build) can reject an unknown body key outright. Token counts are a
+ // nice-to-have; the generation is not — so drop the ask and retry once rather
+ // than failing a run over a metric. Narrowed to the two codes that actually
+ // mean "I did not like this body": a 401 (key-gated vLLM), a 404, a 5xx, or a
+ // transport error all say nothing about `stream_options`, and retrying them
+ // would double every real failure.
+ if (!response.ok && includeUsage && (response.status === 400 || response.status === 422) && !signal?.aborted) {
+ console.log(`⚠️ Local LLM: ${model} rejected stream_options (${response.status}) — retrying without usage reporting`);
+ usageUnsupportedEndpoints.add(url);
+ // Drain the rejected response so its socket is released before the retry.
+ await response.body?.cancel?.().catch(() => {});
+ response = await post(false);
+ }
+
if (!response.ok) {
const body = response.text ? await response.text().catch(() => '') : response.error || '';
throw new Error(`Provider returned ${response.status || 0}: ${body || response.error || response.statusText || 'request failed'}`);
}
+ // A stats listener must fire on EVERY exit path, including the abort/throw one
+ // — a timed-out run still measured real tokens up to the cut, and dropping
+ // them would report "not measured" for a sample that was in fact measured.
+ // Guarded because a broken listener must not take down a live generation.
+ const emitStats = (stats) => {
+ if (typeof onStats !== 'function') return;
+ try { onStats(stats); }
+ catch (err) { console.error(`❌ Local LLM: usage listener failed: ${err.message}`); }
+ };
+
if (!response.body?.getReader) {
// A non-streaming 200 (some daemons ignore `stream: true`). Read it whole
// rather than reporting an empty generation, which a caller would persist as
@@ -125,6 +212,10 @@ export async function streamOpenAiChat({
const data = await readResponseJson(response, { fallback: null, emptyValue: null });
if (!data) throw new Error(`Provider returned a non-JSON response (${response.status})`);
const text = data.choices?.[0]?.message?.content || '';
+ // A whole-body response reports usage the same way a non-streamed call does.
+ // There is no per-chunk fallback here — nothing streamed — so an absent usage
+ // block stays `null` rather than being estimated from a count we never made.
+ emitStats({ ...normalizeUsage(data.usage), estimated: false });
if (text) await onChunk?.(text, 'content');
return text;
}
@@ -134,10 +225,25 @@ export async function streamOpenAiChat({
let buffer = '';
let output = '';
let reasoning = '';
+ // Token counts as the daemon reported them, plus the streamed-frame fallback.
+ // A frame carrying content is one decode step on every local runtime PortOS
+ // talks to, so counting frames approximates the completion length closely —
+ // but it is an ESTIMATE and is labelled as one, never merged into the reported
+ // figure. `null` until a usage frame arrives keeps "reported none" distinct
+ // from "reported zero".
+ //
+ // CONTENT frames only, deliberately: the text this returns is content-only
+ // (`resolvePartialOutput` prefers it), so counting reasoning frames too would
+ // report a tokens/s figure covering more output than the chars/s figure beside
+ // it — the two would disagree systematically on every reasoning model.
+ let usage = null;
+ let contentFrames = 0;
const consumeLine = async (rawLine) => {
- const delta = extractStreamDelta(rawLine);
+ const delta = parseStreamFrame(rawLine);
if (!delta) return;
+ if (delta.usage) usage = delta.usage;
+ if (delta.content) contentFrames += 1;
if (delta.content) {
output += delta.content;
await onChunk?.(delta.content, 'content');
@@ -170,6 +276,13 @@ export async function streamOpenAiChat({
err.partialOutput = resolvePartialOutput({ output, reasoning });
throw err;
} finally {
+ const reported = normalizeUsage(usage);
+ emitStats(reported.completionTokens !== null
+ ? { ...reported, estimated: false }
+ // No usage block: fall back to the streamed-frame count, which is the only
+ // token-shaped evidence we have. `null` when nothing streamed at all —
+ // reporting 0 would file a transport failure as a zero-token generation.
+ : { completionTokens: contentFrames > 0 ? contentFrames : null, promptTokens: reported.promptTokens, estimated: contentFrames > 0 });
await reader.cancel().catch(() => {});
}
diff --git a/server/lib/openAiChatStream.test.js b/server/lib/openAiChatStream.test.js
index 1e61ba7f36..f4b03b4051 100644
--- a/server/lib/openAiChatStream.test.js
+++ b/server/lib/openAiChatStream.test.js
@@ -10,7 +10,7 @@
*/
import { describe, it, expect } from 'vitest';
-import { buildMessages, extractStreamDelta, resolvePartialOutput } from './openAiChatStream.js';
+import { buildMessages, normalizeUsage, parseStreamFrame, resolvePartialOutput } from './openAiChatStream.js';
describe('buildMessages', () => {
it('omits the system message when blank', () => {
@@ -27,30 +27,30 @@ describe('buildMessages', () => {
});
});
-describe('extractStreamDelta', () => {
+describe('parseStreamFrame — deltas', () => {
it('parses an OpenAI-style content delta', () => {
const line = 'data: {"choices":[{"delta":{"content":"Hi"}}]}';
- expect(extractStreamDelta(line)).toEqual({ content: 'Hi', reasoning: '' });
+ expect(parseStreamFrame(line)).toEqual({ content: 'Hi', reasoning: '', usage: null });
});
it('parses a reasoning delta', () => {
const line = 'data: {"choices":[{"delta":{"reasoning":"thinking"}}]}';
- expect(extractStreamDelta(line)).toEqual({ content: '', reasoning: 'thinking' });
+ expect(parseStreamFrame(line)).toEqual({ content: '', reasoning: 'thinking', usage: null });
});
it('skips non-data lines and the [DONE]/✅ sentinels', () => {
- expect(extractStreamDelta(': keep-alive')).toBeNull();
- expect(extractStreamDelta('data: [DONE]')).toBeNull();
- expect(extractStreamDelta('data: ✅')).toBeNull();
- expect(extractStreamDelta('')).toBeNull();
+ expect(parseStreamFrame(': keep-alive')).toBeNull();
+ expect(parseStreamFrame('data: [DONE]')).toBeNull();
+ expect(parseStreamFrame('data: ✅')).toBeNull();
+ expect(parseStreamFrame('')).toBeNull();
});
it('skips a malformed frame instead of throwing (one bad frame must not abort the stream)', () => {
- expect(extractStreamDelta('data: {not json')).toBeNull();
+ expect(parseStreamFrame('data: {not json')).toBeNull();
});
it('tolerates a frame with no delta', () => {
- expect(extractStreamDelta('data: {"choices":[{}]}')).toEqual({ content: '', reasoning: '' });
+ expect(parseStreamFrame('data: {"choices":[{}]}')).toEqual({ content: '', reasoning: '', usage: null });
});
});
@@ -68,3 +68,44 @@ describe('resolvePartialOutput', () => {
expect(resolvePartialOutput({})).toBe('');
});
});
+
+describe('parseStreamFrame', () => {
+ it('carries the usage block off the terminal frame (which has no choices)', () => {
+ const line = 'data: {"choices":[],"usage":{"completion_tokens":42,"prompt_tokens":900}}';
+ expect(parseStreamFrame(line)).toEqual({
+ content: '', reasoning: '', usage: { completion_tokens: 42, prompt_tokens: 900 },
+ });
+ });
+
+ it('reports usage null on an ordinary delta frame', () => {
+ const line = 'data: {"choices":[{"delta":{"content":"Hi"}}]}';
+ expect(parseStreamFrame(line)).toEqual({ content: 'Hi', reasoning: '', usage: null });
+ });
+});
+
+describe('normalizeUsage', () => {
+ it('reads the OpenAI snake_case keys', () => {
+ expect(normalizeUsage({ completion_tokens: 12, prompt_tokens: 500 }))
+ .toEqual({ completionTokens: 12, promptTokens: 500 });
+ });
+
+ it('accepts camelCase and Ollama eval counts', () => {
+ expect(normalizeUsage({ completionTokens: 7, promptTokens: 8 }))
+ .toEqual({ completionTokens: 7, promptTokens: 8 });
+ expect(normalizeUsage({ eval_count: 30, prompt_eval_count: 1200 }))
+ .toEqual({ completionTokens: 30, promptTokens: 1200 });
+ });
+
+ // The sentinel contract: an absent count must stay distinguishable from a
+ // reported zero, or a daemon that reports nothing looks like one that
+ // generated nothing.
+ it('reports null for an absent count and keeps a reported zero', () => {
+ expect(normalizeUsage(null)).toEqual({ completionTokens: null, promptTokens: null });
+ expect(normalizeUsage({ completion_tokens: 0 }).completionTokens).toBe(0);
+ });
+
+ it('ignores non-numeric and negative values rather than recording them', () => {
+ expect(normalizeUsage({ completion_tokens: 'lots', prompt_tokens: -3 }))
+ .toEqual({ completionTokens: null, promptTokens: null });
+ });
+});
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index 59ed36ee74..d4a25456fe 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -26,6 +26,7 @@ import {
localLlmAssessmentRunSchema,
localLlmAssessmentIntentSchema,
localLlmAssessmentDeleteSchema,
+ localLlmAssessmentSweepSchema,
localLlmLlamaServerStartSchema,
localLlmSpecModelDownloadSchema
} from '../lib/validation.js'
@@ -44,6 +45,7 @@ import {
import { getSettings } from '../services/settings.js'
import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js'
import { getAssessmentReport, runAssessment, deleteAssessment } from '../services/localModelAssessments.js'
+import { startSweep, getSweepStatus, cancelSweep } from '../services/localModelAssessmentSweep.js'
import { listUserModels } from '../services/audioModels.js'
import { ENGINES } from '../services/pipeline/musicGen.js'
import { abortSignalFromResponse } from '../lib/requestAbort.js'
@@ -456,6 +458,37 @@ router.post('/assessments/run', asyncHandler(async (req, res) => {
res.json(await runAssessment({ backend, modelId, contextTokens, tuning, signal: abortSignalFromResponse(res), onProgress }))
}))
+// POST /api/local-llm/assessments/sweep — measure EVERY model the scope covers.
+// User-triggered only, same as the single-model run: the UI names the model and
+// generation count before this fires.
+//
+// Unlike /run this returns immediately and the queue keeps going server-side —
+// a full sweep is hours of work started at the end of the day, so it must not
+// depend on the browser tab staying open. Progress rides the same
+// `localLlm:progress` socket event under `scope: 'assessment-sweep'`, and the
+// GET below is the reload-safe source of truth.
+router.post('/assessments/sweep', asyncHandler(async (req, res) => {
+ const { scope, contextTokens } = validateRequest(localLlmAssessmentSweepSchema, req.body)
+ const io = req.app.get('io')
+ const status = await startSweep({ scope, contextTokens, onProgress: (frame) => io?.emit('localLlm:progress', frame) })
+ // A refused start (one already running, or nothing to measure) is a 409, not a
+ // silent no-op that would leave the page waiting for progress that never comes.
+ if (status.rejected) throw new ServerError(status.rejected, { status: 409, context: { scope } })
+ res.json(status)
+}))
+
+// GET /api/local-llm/assessments/sweep — queue status. Module state only, zero
+// LLM calls, so the page can poll it and a reload can pick a running sweep back up.
+router.get('/assessments/sweep', asyncHandler(async (_req, res) => {
+ res.json(getSweepStatus())
+}))
+
+// POST /api/local-llm/assessments/sweep/cancel — stop the queue and the model in
+// flight. Everything already measured stays on disk.
+router.post('/assessments/sweep/cancel', asyncHandler(async (_req, res) => {
+ res.json(cancelSweep())
+}))
+
// 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.
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index 7ebb04b731..07db8d7d8f 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -7,6 +7,7 @@ import { listModels, listVisionModels, listToolUseModels, installModel } from '.
import { enrichCatalogWithVariants, applyMeasuredFit } from '../services/huggingFaceCatalog.js';
import { getMeasuredFits } from '../services/localModelAssessmentStore.js';
import { runAssessment } from '../services/localModelAssessments.js';
+import { startSweep, getSweepStatus, cancelSweep } from '../services/localModelAssessmentSweep.js';
import { getLoadedModels, unloadModel } from '../services/ollamaManager.js';
import { getLoadedModels as getLoadedLmStudioModels, getLastLoadedModelsError as getLmStudioResidencyError } from '../services/lmStudioManager.js';
import { getSettings } from '../services/settings.js';
@@ -71,6 +72,12 @@ vi.mock('../services/localModelAssessments.js', () => ({
deleteAssessment: vi.fn(async () => ({ deleted: true })),
}));
+vi.mock('../services/localModelAssessmentSweep.js', () => ({
+ startSweep: vi.fn(async () => ({ status: 'running', total: 3, completed: 0 })),
+ getSweepStatus: vi.fn(() => ({ status: 'idle', total: 0, completed: 0, results: [] })),
+ cancelSweep: vi.fn(() => ({ status: 'cancelled', total: 3, completed: 1, results: [] })),
+}));
+
vi.mock('../services/llamaServerManager.js', () => ({
getLlamaServerStatus: vi.fn(async () => ({ installed: true, running: false })),
startLlamaServer: vi.fn(async () => ({ success: true, pid: 123 })),
@@ -505,6 +512,69 @@ describe('measured assessments wiring', () => {
scope: 'assessment', backend: 'ollama', modelId: 'example-model:14b', event: 'start', sampleIndex: 1, sampleCount: 3,
});
});
+
+ // The sweep is the overnight path: it must return as soon as the queue exists,
+ // because the run outlives the request that started it.
+ it('POST /assessments/sweep starts a queue and returns its snapshot', async () => {
+ const res = await request(makeApp())
+ .post('/api/local-llm/assessments/sweep')
+ .send({ scope: 'all' });
+
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ status: 'running', total: 3 });
+ expect(startSweep).toHaveBeenCalledWith(expect.objectContaining({ scope: 'all' }));
+ });
+
+ it('POST /assessments/sweep defaults to the unmeasured scope', async () => {
+ const res = await request(makeApp()).post('/api/local-llm/assessments/sweep').send({});
+ expect(res.status).toBe(200);
+ expect(startSweep).toHaveBeenCalledWith(expect.objectContaining({ scope: 'unmeasured' }));
+ });
+
+ it('POST /assessments/sweep rejects an unknown scope rather than silently narrowing it', async () => {
+ const res = await request(makeApp())
+ .post('/api/local-llm/assessments/sweep')
+ .send({ scope: 'everything-please' });
+
+ expect(res.status).toBe(400);
+ expect(startSweep).not.toHaveBeenCalled();
+ });
+
+ // A refused start has to be visible: a 200 with no queue behind it would leave
+ // the page waiting on progress that never comes.
+ it('POST /assessments/sweep 409s when the service refuses to start', async () => {
+ startSweep.mockResolvedValueOnce({ status: 'running', rejected: 'a sweep is already running' });
+ const res = await request(makeApp()).post('/api/local-llm/assessments/sweep').send({ scope: 'all' });
+ expect(res.status).toBe(409);
+ });
+
+ it('forwards sweep progress to the shared localLlm:progress socket event', async () => {
+ startSweep.mockImplementation(async ({ onProgress }) => {
+ onProgress({ scope: 'assessment-sweep', event: 'start', total: 2, completed: 0 });
+ return { status: 'running', total: 2, completed: 0 };
+ });
+ const app = makeApp();
+ await request(app).post('/api/local-llm/assessments/sweep').send({ scope: 'unmeasured' });
+
+ expect(app.get('io').emit).toHaveBeenCalledWith('localLlm:progress', {
+ scope: 'assessment-sweep', event: 'start', total: 2, completed: 0,
+ });
+ });
+
+ it('GET /assessments/sweep reports the queue without touching a provider', async () => {
+ const res = await request(makeApp()).get('/api/local-llm/assessments/sweep');
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ status: 'idle' });
+ expect(getSweepStatus).toHaveBeenCalled();
+ expect(startSweep).not.toHaveBeenCalled();
+ });
+
+ it('POST /assessments/sweep/cancel stops the queue', async () => {
+ const res = await request(makeApp()).post('/api/local-llm/assessments/sweep/cancel');
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ status: 'cancelled', completed: 1 });
+ expect(cancelSweep).toHaveBeenCalled();
+ });
});
describe('llama-server routes', () => {
diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.js
index f1f98565e8..40e66594b3 100644
--- a/server/services/localLlmPlayground.js
+++ b/server/services/localLlmPlayground.js
@@ -22,13 +22,41 @@ export function buildPrompt({ systemPrompt, prompt }) {
return `System instructions:\n${system}\n\nUser prompt:\n${prompt}`;
}
-export function summarizeTimings({ startedAt, firstChunkAt, endedAt, text }) {
+/**
+ * Collapse one generation's clock readings (and, when the daemon reported them,
+ * its token counts) into the numbers PortOS records.
+ *
+ * ## Why tokens/s is decode-only
+ *
+ * `tokensPerSecond` divides the completion tokens by the time spent GENERATING
+ * them — wall clock minus time-to-first-token — because that is what "tokens per
+ * second" means everywhere else in the local-LLM world (llama.cpp's `eval time`,
+ * Ollama's `eval_count / eval_duration`). Including prefill would make the same
+ * model look several times slower at 16k context than at 512 for a reason that
+ * has nothing to do with its decode speed, and TTFT is already reported beside
+ * it. Prefill gets its own honest number, `promptTokensPerSecond`.
+ *
+ * @param {{ completionTokens: number|null, promptTokens: number|null, estimated: boolean }} [usage]
+ * token counts from `streamOpenAiChat`'s `onStats`. Absent entirely for a
+ * caller that does not track usage, which records `null` — not zero.
+ */
+export function summarizeTimings({ startedAt, firstChunkAt, endedAt, text, usage }) {
const totalMs = endedAt - startedAt;
const ttftMs = firstChunkAt ? firstChunkAt - startedAt : null;
const chars = text.length;
// A sub-millisecond total makes a rate meaningless — report n/a (null)
// rather than `chars`, which would surface the char COUNT as a chars/sec rate.
const charsPerSecond = totalMs > 0 ? Number((chars / (totalMs / 1000)).toFixed(2)) : null;
+
+ const completionTokens = Number.isFinite(usage?.completionTokens) ? usage.completionTokens : null;
+ const promptTokens = Number.isFinite(usage?.promptTokens) ? usage.promptTokens : null;
+ // Decode window: everything after the first token arrived. Falls back to the
+ // full wall clock when TTFT was never observed (a non-streamed response), which
+ // understates the rate rather than inventing a prefill split that wasn't seen.
+ const decodeMs = Number.isFinite(ttftMs) ? totalMs - ttftMs : totalMs;
+ const rate = (tokens, ms) =>
+ (Number.isFinite(tokens) && tokens > 0 && ms > 0 ? Number((tokens / (ms / 1000)).toFixed(2)) : null);
+
return {
startedAt: new Date(startedAt).toISOString(),
endedAt: new Date(endedAt).toISOString(),
@@ -36,6 +64,20 @@ export function summarizeTimings({ startedAt, firstChunkAt, endedAt, text }) {
totalMs,
chars,
charsPerSecond,
+ // `null` throughout = the daemon reported no usage and nothing streamed to
+ // count. Never 0, which a reader would take for a measured standstill.
+ completionTokens,
+ promptTokens,
+ tokensPerSecond: rate(completionTokens, decodeMs),
+ // Prompt processing (prefill) speed: how fast the daemon chewed through the
+ // context before the first token. Needs BOTH a prompt-token count and a
+ // measured TTFT, so it is null on a non-streamed response.
+ promptTokensPerSecond: Number.isFinite(ttftMs) ? rate(promptTokens, ttftMs) : null,
+ // Whether the token count came from the daemon's own tokenizer (`false`) or
+ // from counting streamed frames (`true`). `null` = no token count at all.
+ // A consumer must label an estimate as one — PortOS has no tokenizer, and
+ // presenting a frame count as a measurement is the thing this flag prevents.
+ tokensEstimated: completionTokens === null ? null : Boolean(usage?.estimated),
};
}
@@ -57,7 +99,7 @@ async function resolveLocalProvider(backend) {
return provider;
}
-async function streamChatCompletion({ provider, backend, modelId, prompt, systemPrompt, temperature, maxTokens, extraBody = {}, signal, onChunk }) {
+async function streamChatCompletion({ provider, backend, modelId, prompt, systemPrompt, temperature, maxTokens, extraBody = {}, signal, onChunk, onStats }) {
if (backend === 'ollama') {
const ready = await ensureOllamaProviderReady(provider).catch((err) => ({ success: false, error: err.message }));
if (!ready.success) {
@@ -85,6 +127,9 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, system
extraBody: { ...(Number(provider.numCtx) > 0 ? { num_ctx: Number(provider.numCtx) } : {}), ...extraBody },
signal,
onChunk,
+ // Registering `onStats` is what asks the daemon for token counts; a runtime
+ // that does not support the ask is handled inside `streamOpenAiChat`.
+ onStats,
});
}
@@ -112,6 +157,11 @@ export async function runLocalLlmTest({
const startedAt = Date.now();
let firstChunkAt = null;
let runId = null;
+ // Filled by the stream's terminal usage frame (or the frame-count fallback).
+ // Stays null until then so a run that died before any frame records "no token
+ // count" rather than a fabricated zero.
+ let usage = null;
+ const onStats = (stats) => { usage = stats; };
try {
const run = await createRun({
@@ -144,6 +194,7 @@ export async function runLocalLlmTest({
maxTokens,
extraBody,
signal,
+ onStats,
onChunk: (chunk, kind = 'content') => {
// First token of EITHER channel marks TTFT: for a reasoning model the
// first thing it emits is reasoning, so timing it from that chunk is the
@@ -166,7 +217,7 @@ export async function runLocalLlmTest({
providerId: provider.id,
runId,
text,
- timings: summarizeTimings({ startedAt, firstChunkAt, endedAt, text }),
+ timings: summarizeTimings({ startedAt, firstChunkAt, endedAt, text, usage }),
options: { temperature, maxTokens, timeoutMs },
};
} catch (err) {
@@ -195,7 +246,7 @@ export async function runLocalLlmTest({
runId,
error,
text: partialText,
- timings: summarizeTimings({ startedAt, firstChunkAt, endedAt, text: partialText }),
+ timings: summarizeTimings({ startedAt, firstChunkAt, endedAt, text: partialText, usage }),
options: { temperature, maxTokens, timeoutMs },
};
}
@@ -233,6 +284,7 @@ export async function runEndpointLlmTest({
}) {
const startedAt = Date.now();
let firstChunkAt = null;
+ let usage = null;
const timeoutController = new AbortController();
const timeoutHandle = setTimeout(() => timeoutController.abort(), timeoutMs);
const signal = anyAbortSignal([clientSignal, timeoutController.signal]);
@@ -247,6 +299,7 @@ export async function runEndpointLlmTest({
maxTokens,
extraBody,
signal,
+ onStats: (stats) => { usage = stats; },
onChunk: (chunk, kind = 'content') => {
if (!firstChunkAt && chunk) firstChunkAt = Date.now();
if (chunk) return onToken?.(chunk, kind);
@@ -258,7 +311,7 @@ export async function runEndpointLlmTest({
modelId,
endpoint,
text,
- timings: summarizeTimings({ startedAt, firstChunkAt, endedAt: Date.now(), text }),
+ timings: summarizeTimings({ startedAt, firstChunkAt, endedAt: Date.now(), text, usage }),
options: { temperature, maxTokens, timeoutMs },
};
} catch (err) {
@@ -271,7 +324,7 @@ export async function runEndpointLlmTest({
endpoint,
error,
text: partialText,
- timings: summarizeTimings({ startedAt, firstChunkAt, endedAt: Date.now(), text: partialText }),
+ timings: summarizeTimings({ startedAt, firstChunkAt, endedAt: Date.now(), text: partialText, usage }),
options: { temperature, maxTokens, timeoutMs },
};
}
diff --git a/server/services/localLlmPlayground.test.js b/server/services/localLlmPlayground.test.js
index b62f1e070d..895789a7a0 100644
--- a/server/services/localLlmPlayground.test.js
+++ b/server/services/localLlmPlayground.test.js
@@ -7,6 +7,7 @@ vi.mock('./providerStatus.js', () => ({ markProviderAvailable: vi.fn(() => Promi
vi.mock('./ollamaManager.js', () => ({ ensureProviderReady: vi.fn(() => Promise.resolve({ success: true })) }));
import { buildPrompt, summarizeTimings, runLocalLlmTest } from './localLlmPlayground.js';
+import { __resetUsageSupport } from '../lib/openAiChatStream.js';
import { createRun, finalizeRunRecord } from './runner.js';
import { getProviderById } from './providers.js';
@@ -41,6 +42,44 @@ describe('summarizeTimings', () => {
expect(t.totalMs).toBe(0);
expect(t.charsPerSecond).toBeNull();
});
+
+ // tokens/s is DECODE throughput — completion tokens over the time after the
+ // first token — matching what llama.cpp and Ollama report. Dividing by the
+ // full wall clock would make the same model look slower purely because its
+ // prompt was longer, which is what TTFT and the prefill rate are for.
+ it('measures tokens/s over the decode window, not the whole wall clock', () => {
+ const t = summarizeTimings({
+ startedAt: 0, firstChunkAt: 1000, endedAt: 3000, text: 'abc',
+ usage: { completionTokens: 100, promptTokens: 4000, estimated: false },
+ });
+ expect(t.completionTokens).toBe(100);
+ expect(t.tokensPerSecond).toBe(50); // 100 tokens / 2s of decode, not / 3s
+ expect(t.promptTokensPerSecond).toBe(4000); // 4000 prompt tokens / 1s of prefill
+ expect(t.tokensEstimated).toBe(false);
+ });
+
+ it('marks a frame-counted token figure as an estimate', () => {
+ const t = summarizeTimings({
+ startedAt: 0, firstChunkAt: 500, endedAt: 1500, text: 'abc',
+ usage: { completionTokens: 20, promptTokens: null, estimated: true },
+ });
+ expect(t.tokensEstimated).toBe(true);
+ expect(t.tokensPerSecond).toBe(20);
+ // No prompt count reported → no prefill rate invented from the char count.
+ expect(t.promptTokensPerSecond).toBeNull();
+ });
+
+ // The sentinel rule: a caller that tracks no usage records "not measured",
+ // never a tokens/s figure derived from characters.
+ it('reports null token fields when the daemon reported no usage', () => {
+ const t = summarizeTimings({ startedAt: 0, firstChunkAt: 100, endedAt: 1100, text: 'abcdefgh' });
+ expect(t.completionTokens).toBeNull();
+ expect(t.promptTokens).toBeNull();
+ expect(t.tokensPerSecond).toBeNull();
+ expect(t.tokensEstimated).toBeNull();
+ // ...while the chars/s figure it CAN measure is unaffected.
+ expect(t.charsPerSecond).toBe(7.27); // 8 chars / 1.1s wall clock
+ });
});
// Build a fake stream reader: yields each SSE line as a chunk, then either
@@ -243,3 +282,98 @@ describe('runLocalLlmTest timeout/abort contract', () => {
expect(capturedSignal.aborted).toBe(true);
});
});
+
+describe('token counting through the stream', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ __resetUsageSupport();
+ getProviderById.mockResolvedValue({ id: 'lmstudio', type: 'api', endpoint: 'http://localhost:1234/v1' });
+ createRun.mockResolvedValue({ runId: 'run-1', provider: { id: 'lmstudio' } });
+ finalizeRunRecord.mockResolvedValue(undefined);
+ });
+
+ afterEach(() => { delete global.fetch; __resetUsageSupport(); });
+
+ const stubStream = (reader) => {
+ global.fetch = vi.fn().mockResolvedValue({ ok: true, status: 200, body: { getReader: () => reader } });
+ return global.fetch;
+ };
+
+ const usageFrame = (usage) => `data: ${JSON.stringify({ choices: [], usage })}\n`;
+
+ it('asks for usage and records the count the daemon reported', async () => {
+ const fetchMock = stubStream(makeReader([
+ sse({ content: 'Hi' }),
+ usageFrame({ completion_tokens: 40, prompt_tokens: 900 }),
+ ]));
+
+ const result = await runLocalLlmTest({ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000 });
+
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body).stream_options).toEqual({ include_usage: true });
+ expect(result.timings.completionTokens).toBe(40);
+ expect(result.timings.promptTokens).toBe(900);
+ expect(result.timings.tokensEstimated).toBe(false);
+ });
+
+ // No usage block: the streamed CONTENT frames are the only token-shaped
+ // evidence there is, and the figure must be labelled as the estimate it is.
+ it('falls back to counting content frames, marked as an estimate', async () => {
+ stubStream(makeReader([sse({ content: 'a' }), sse({ content: 'b' }), sse({ content: 'c' })]));
+
+ const result = await runLocalLlmTest({ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000 });
+
+ expect(result.timings.completionTokens).toBe(3);
+ expect(result.timings.tokensEstimated).toBe(true);
+ });
+
+ // The text this reports chars/s from is content-only, so counting reasoning
+ // frames too would make the two throughput numbers describe different outputs.
+ it('does not count reasoning frames toward the estimate', async () => {
+ stubStream(makeReader([
+ sse({ reasoning: 'thinking' }),
+ sse({ reasoning: 'harder' }),
+ sse({ content: 'Answer.' }),
+ ]));
+
+ const result = await runLocalLlmTest({ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000 });
+ expect(result.timings.completionTokens).toBe(1);
+ });
+
+ it('reports no token count at all when nothing streamed', async () => {
+ stubStream(makeReader([]));
+ const result = await runLocalLlmTest({ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000 });
+ // Never 0 — that would read as a measured standstill.
+ expect(result.timings.completionTokens).toBeNull();
+ expect(result.timings.tokensEstimated).toBeNull();
+ });
+
+ it('retries without stream_options when the daemon rejects it, and remembers', async () => {
+ const reject = { ok: false, status: 400, text: async () => 'unknown field stream_options' };
+ const stream = { ok: true, status: 200, body: { getReader: () => makeReader([sse({ content: 'Hi' })]) } };
+ global.fetch = vi.fn()
+ .mockResolvedValueOnce(reject)
+ .mockResolvedValue(stream);
+
+ const first = await runLocalLlmTest({ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000 });
+ expect(first.text).toBe('Hi');
+ expect(JSON.parse(global.fetch.mock.calls[1][1].body).stream_options).toBeUndefined();
+
+ // The SECOND run must not re-discover the same incompatibility: a sweep runs
+ // hundreds of samples against one daemon, and each rediscovery costs a whole
+ // extra prefill.
+ global.fetch.mockClear();
+ global.fetch.mockResolvedValue({ ok: true, status: 200, body: { getReader: () => makeReader([sse({ content: 'Hi' })]) } });
+ await runLocalLlmTest({ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000 });
+ expect(global.fetch).toHaveBeenCalledTimes(1);
+ expect(JSON.parse(global.fetch.mock.calls[0][1].body).stream_options).toBeUndefined();
+ });
+
+ // A 401 says nothing about the body. Retrying it would double every real
+ // auth failure against a key-gated vLLM.
+ it('does not retry an auth failure as though it were a body rejection', async () => {
+ global.fetch = vi.fn().mockResolvedValue({ ok: false, status: 401, text: async () => 'unauthorized' });
+ const result = await runLocalLlmTest({ backend: 'lmstudio', modelId: 'm1', prompt: 'hi', timeoutMs: 5000 });
+ expect(result.error).toContain('401');
+ expect(global.fetch).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/server/services/localModelAssessmentSweep.js b/server/services/localModelAssessmentSweep.js
new file mode 100644
index 0000000000..e3a074761c
--- /dev/null
+++ b/server/services/localModelAssessmentSweep.js
@@ -0,0 +1,258 @@
+/**
+ * Measure every local model in one pass — the overnight sweep.
+ *
+ * Measuring one model takes minutes; measuring a machine's worth of them takes
+ * hours. That is a job you start at the end of the day and read in the morning,
+ * which rules out the shape the single-model path uses (one blocking POST held
+ * open by the browser tab). This module runs the queue SERVER-SIDE: the request
+ * that starts it returns immediately, the loop keeps going with nobody watching,
+ * and the page reads its progress from a status endpoint plus the existing
+ * `localLlm:progress` socket event.
+ *
+ * ## AI Provider Usage Policy (root CLAUDE.md) — read before editing
+ *
+ * A sweep calls a provider once per model, so it is STRICTLY user-triggered, the
+ * same as the single-model run:
+ *
+ * - `startSweep()` is reachable only from `POST /api/local-llm/assessments/sweep`,
+ * behind a consent gate that names the exact model count and generation count.
+ * - `getSweepStatus()` reads module state only. Zero LLM calls, safe to poll.
+ *
+ * The prohibition the single-model service states — "no scheduler, no boot hook,
+ * no background sweep" — is about work the user did not ask for. This IS the ask:
+ * a button they pressed, having been told what it will run. What must never
+ * appear is a cron entry, a boot hook, or an auto-start that fires this without a
+ * click. Do not add one.
+ *
+ * `lib/sseUtils.js#createSseRunner` owns a similar lifecycle (runId, abort,
+ * cancel, active-guard) but is SSE-transport-bound and keeps no cumulative record
+ * of what a run has produced so far — which is the one thing a page reloaded at
+ * 3am needs. Hence a small queue of its own rather than a transport it would have
+ * to work around.
+ *
+ * ## Restart behavior
+ *
+ * The queue lives in module memory, so a server restart mid-sweep ends it. That
+ * is deliberate rather than unfinished: every COMPLETED measurement is already
+ * durable (`runAssessment` persists as it goes), so a restart costs the model in
+ * flight and nothing else, and re-running the sweep afterwards picks up exactly
+ * what is still unmeasured. Persisting the queue would buy a resumable pointer
+ * into a job that is cheap to restart and must never auto-resume on boot.
+ */
+
+import { selectSweepTargets, SWEEP_SCOPES } from '../lib/localModelAssessment.js';
+import { getAssessmentReport, runAssessment } from './localModelAssessments.js';
+
+// One sweep at a time. This is a re-entrancy guard, not a concurrency control:
+// PortOS serves one user, and the thing being prevented is a second click (or a
+// second tab) queuing the same models against a machine that can only run one
+// model at a time anyway.
+let sweep = null;
+
+// A sweep is sequential BY DESIGN. Two models measured at once contend for the
+// same memory and the same GPU, and every number either one produces would
+// describe that contention rather than the model — which is the one thing this
+// whole feature exists to measure accurately.
+
+// How long one model waits for the machine-wide accelerator claim before giving
+// up on its turn. An interactive Measure click refuses immediately; a queue
+// running unattended should ride out a short image render rather than throwing
+// away a model's slot over it — but not wait all night behind a LoRA training
+// run, which would leave the sweep looking hung with nothing to show.
+const CLAIM_WAIT_MS = 10 * 60 * 1000;
+
+const nowIso = () => new Date().toISOString();
+
+/** Public snapshot. Never leaks the AbortController or the emit hook. */
+function snapshot() {
+ if (!sweep) {
+ // `status: 'idle'` with a null run is the honest "nothing has been started",
+ // distinct from a finished sweep whose results are still worth showing.
+ return { status: 'idle', scope: null, startedAt: null, finishedAt: null, total: 0, completed: 0, current: null, results: [], cancelRequested: false };
+ }
+ return {
+ status: sweep.status,
+ scope: sweep.scope,
+ startedAt: sweep.startedAt,
+ finishedAt: sweep.finishedAt,
+ total: sweep.total,
+ completed: sweep.results.length,
+ // Which model is being measured right now — `null` between models and once
+ // the sweep ends.
+ current: sweep.current,
+ results: sweep.results,
+ cancelRequested: sweep.cancelRequested,
+ error: sweep.error || null,
+ };
+}
+
+export function getSweepStatus() {
+ return snapshot();
+}
+
+/**
+ * Ask the running sweep to stop.
+ *
+ * Aborts the model in flight (which `runAssessment` treats as a cancel and does
+ * NOT record) and drops the rest of the queue. Everything already measured stays
+ * on disk — an interrupted overnight run is still worth what it finished.
+ */
+export function cancelSweep() {
+ if (!sweep || sweep.status !== 'running') return snapshot();
+ sweep.cancelRequested = true;
+ sweep.controller.abort();
+ // Flip the status here rather than waiting for the loop's `finally`: the
+ // caller is an HTTP handler returning this snapshot NOW, and reporting
+ // `running` to a client that just stopped it would leave a Stop button on
+ // screen for a queue that is already winding down. The `finally` re-affirms
+ // `cancelled` (it reads the same flag), so the two cannot disagree.
+ sweep.status = 'cancelled';
+ console.log(`🛑 Local LLM: assessment sweep cancelled after ${sweep.results.length}/${sweep.total}`);
+ return snapshot();
+}
+
+/** Test seam: forget any sweep state between suites. */
+export function __resetSweep() {
+ sweep?.controller?.abort();
+ sweep = null;
+}
+
+// The sweep loop runs OUTSIDE the request lifecycle — there is no `next(err)` to
+// bubble to, so an uncaught throw here would take the process down (root
+// CLAUDE.md). Every model is individually caught, and the loop itself is wrapped.
+//
+// It mutates the `run` it was handed, NOT the module-level `sweep`: a cancelled
+// queue is replaceable the moment it is cancelled, and a loop still winding down
+// its last model must not write its results into the sweep that succeeded it.
+async function runSweepLoop(run, targets, contextTokens, emit) {
+ for (const target of targets) {
+ if (run.cancelRequested) break;
+ run.current = { backend: target.backend, modelId: target.modelId, tuningLabel: target.tuningLabel, startedAt: nowIso() };
+ emit({
+ scope: 'assessment-sweep',
+ event: 'model-start',
+ backend: target.backend,
+ modelId: target.modelId,
+ completed: run.results.length,
+ total: run.total,
+ message: `Sweep ${run.results.length + 1}/${run.total}: measuring ${target.modelId}…`,
+ });
+
+ // One model failing is a RESULT, not a reason to abandon the queue — the
+ // whole point of an overnight run is that it gets through the list.
+ const result = await runAssessment({
+ backend: target.backend,
+ modelId: target.modelId,
+ contextTokens,
+ tuning: target.tuning,
+ signal: run.controller.signal,
+ onProgress: emit,
+ claimTimeoutMs: CLAIM_WAIT_MS,
+ }).catch((err) => ({ error: err?.message || 'assessment failed' }));
+
+ run.current = null;
+ // A cancelled run recorded nothing, so it is not a result — recording it as
+ // one would make a stopped sweep look like it measured what it abandoned.
+ if (result?.cancelled) break;
+ run.results.push({
+ backend: target.backend,
+ modelId: target.modelId,
+ tuningLabel: target.tuningLabel,
+ finishedAt: nowIso(),
+ // `null` verdict + an error means the run threw before producing evidence.
+ verdict: result?.error ? null : (result?.verdict || 'unknown'),
+ error: result?.error || null,
+ meanTokensPerSecond: Number.isFinite(result?.performance?.meanTokensPerSecond) ? result.performance.meanTokensPerSecond : null,
+ meanCharsPerSecond: Number.isFinite(result?.performance?.meanCharsPerSecond) ? result.performance.meanCharsPerSecond : null,
+ // Travels WITH the rate it qualifies. Dropping it here would render a
+ // frame-counted estimate as a tokenizer measurement in the results list.
+ tokensEstimated: typeof result?.performance?.tokensEstimated === 'boolean' ? result.performance.tokensEstimated : null,
+ });
+ }
+}
+
+/**
+ * Start measuring every model the scope covers. **Calls a provider, once per
+ * model** — see the policy note at the top.
+ *
+ * Returns as soon as the queue is built: the loop runs detached so the HTTP
+ * request that started it can return, and so closing the browser does not stop
+ * an overnight run.
+ *
+ * @param {object} options
+ * @param {'unmeasured'|'stale'|'all'} [options.scope]
+ * @param {number[]} [options.contextTokens] passed through to each measurement
+ * @param {(frame: object) => void} [options.onProgress] forwarded to the socket
+ * @returns {Promise<object>} the initial snapshot, or `{ rejected }` when a
+ * sweep is already running or the scope covers nothing
+ */
+export async function startSweep({ scope = 'unmeasured', contextTokens, onProgress } = {}) {
+ if (sweep?.status === 'running') return { ...snapshot(), rejected: 'a sweep is already running' };
+ const resolvedScope = SWEEP_SCOPES.includes(scope) ? scope : 'unmeasured';
+
+ // Read the report ONCE, here, rather than per model: it lists installed models
+ // across every runtime and annotates staleness, which is exactly the input the
+ // target selection needs. It is disk-plus-listing only — no LLM call.
+ const report = await getAssessmentReport({ intent: 'balanced' });
+ const uninstalledKeys = new Set(report.uninstalled.map((u) => `${u.backend}:${u.modelId}`));
+ const targets = selectSweepTargets({
+ // Records for models that are no longer installed cannot be re-measured, so
+ // they never enter the queue.
+ assessments: report.assessments.filter((a) => !uninstalledKeys.has(`${a?.backend}:${a?.modelId}`)),
+ unassessed: report.unassessed,
+ scope: resolvedScope,
+ });
+
+ if (!targets.length) return { ...snapshot(), rejected: 'nothing to measure for that scope' };
+
+ const emit = (frame) => {
+ if (typeof onProgress !== 'function') return;
+ // A broken listener (a closed socket) must never abort a job the user is
+ // paying hours of compute for.
+ try { onProgress(frame); }
+ catch (err) { console.error(`❌ Local LLM: sweep progress listener failed: ${err.message}`); }
+ };
+
+ const run = {
+ status: 'running',
+ scope: resolvedScope,
+ startedAt: nowIso(),
+ finishedAt: null,
+ total: targets.length,
+ current: null,
+ results: [],
+ cancelRequested: false,
+ error: null,
+ controller: new AbortController(),
+ };
+ sweep = run;
+
+ console.log(`📏 Local LLM: assessment sweep started — ${targets.length} measurement${targets.length === 1 ? '' : 's'} (${resolvedScope})`);
+ emit({ scope: 'assessment-sweep', event: 'start', total: targets.length, completed: 0, message: `Measuring ${targets.length} model${targets.length === 1 ? '' : 's'}…` });
+
+ // Detached on purpose: the caller is an HTTP handler that must return now.
+ runSweepLoop(run, targets, contextTokens, emit)
+ .catch((err) => {
+ run.error = err?.message || 'sweep failed';
+ console.error(`❌ Local LLM: assessment sweep failed: ${run.error}`);
+ })
+ .finally(() => {
+ run.status = run.cancelRequested ? 'cancelled' : (run.error ? 'failed' : 'complete');
+ run.finishedAt = nowIso();
+ run.current = null;
+ console.log(`📏 Local LLM: assessment sweep ${run.status} — ${run.results.length}/${run.total} measured`);
+ // A queue the user already replaced has nothing to report — emitting its
+ // terminal frame would tell the page the CURRENT sweep just finished.
+ if (sweep !== run) return;
+ emit({
+ scope: 'assessment-sweep',
+ event: 'complete',
+ status: run.status,
+ completed: run.results.length,
+ total: run.total,
+ message: `Sweep ${run.status}: ${run.results.length}/${run.total} measured`,
+ });
+ });
+
+ return snapshot();
+}
diff --git a/server/services/localModelAssessmentSweep.test.js b/server/services/localModelAssessmentSweep.test.js
new file mode 100644
index 0000000000..c9ee8aae20
--- /dev/null
+++ b/server/services/localModelAssessmentSweep.test.js
@@ -0,0 +1,208 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// The sweep's only two collaborators: the report (what to measure) and the
+// single-model runner (measure it). Both are mocked so the queue's own behavior
+// — order, cancellation, failure isolation — is what's under test.
+vi.mock('./localModelAssessments.js', () => ({
+ getAssessmentReport: vi.fn(),
+ runAssessment: vi.fn(),
+}));
+
+import { getAssessmentReport, runAssessment } from './localModelAssessments.js';
+import { startSweep, getSweepStatus, cancelSweep, __resetSweep } from './localModelAssessmentSweep.js';
+
+// Let the detached loop run to completion. The sweep deliberately does NOT
+// return a promise for its own queue (the HTTP handler must return immediately),
+// so a test has to drain the microtask queue instead.
+const settle = async () => { for (let i = 0; i < 50; i += 1) await Promise.resolve(); };
+
+const report = ({ unassessed = [], assessments = [], uninstalled = [] } = {}) => ({
+ unassessed, assessments, uninstalled,
+});
+
+const measured = (verdict = 'fits', meanTokensPerSecond = 42) => ({
+ verdict, performance: { meanTokensPerSecond, meanCharsPerSecond: 170 },
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ __resetSweep();
+});
+afterEach(() => __resetSweep());
+
+describe('startSweep', () => {
+ it('measures every unmeasured model in order and records what each produced', async () => {
+ getAssessmentReport.mockResolvedValue(report({
+ unassessed: [{ backend: 'ollama', modelId: 'a' }, { backend: 'ollama', modelId: 'b' }],
+ }));
+ runAssessment.mockResolvedValue(measured());
+
+ const started = await startSweep({ scope: 'unmeasured' });
+ expect(started.status).toBe('running');
+ expect(started.total).toBe(2);
+
+ await settle();
+ const status = getSweepStatus();
+ expect(status.status).toBe('complete');
+ expect(status.results.map((r) => r.modelId)).toEqual(['a', 'b']);
+ expect(status.results[0].meanTokensPerSecond).toBe(42);
+ // Sequential by design — two models at once would measure the contention.
+ expect(runAssessment).toHaveBeenCalledTimes(2);
+ });
+
+ it('passes each target\'s recorded tuning through, so a re-measure reproduces it', async () => {
+ getAssessmentReport.mockResolvedValue(report({
+ assessments: [{
+ backend: 'llama', modelId: 'tuned', tuningKey: 'ctx=8192', tuningLabel: '8k',
+ tuning: { contextSize: 8192 }, staleness: { stale: true },
+ }],
+ }));
+ runAssessment.mockResolvedValue(measured());
+
+ await startSweep({ scope: 'stale' });
+ await settle();
+ expect(runAssessment).toHaveBeenCalledWith(expect.objectContaining({
+ backend: 'llama', modelId: 'tuned', tuning: { contextSize: 8192 },
+ }));
+ });
+
+ // The point of an overnight run is that it gets through the list. One model
+ // that throws must not abandon the rest of the queue.
+ it('records a failed model as a result and keeps going', async () => {
+ getAssessmentReport.mockResolvedValue(report({
+ unassessed: [{ backend: 'ollama', modelId: 'broken' }, { backend: 'ollama', modelId: 'fine' }],
+ }));
+ runAssessment
+ .mockRejectedValueOnce(new Error('backend refused the model'))
+ .mockResolvedValueOnce(measured());
+
+ await startSweep({ scope: 'unmeasured' });
+ await settle();
+ const status = getSweepStatus();
+ expect(status.status).toBe('complete');
+ expect(status.results[0]).toMatchObject({ modelId: 'broken', error: 'backend refused the model', verdict: null });
+ expect(status.results[1]).toMatchObject({ modelId: 'fine', verdict: 'fits' });
+ });
+
+ it('never queues a model that is no longer installed', async () => {
+ getAssessmentReport.mockResolvedValue(report({
+ assessments: [
+ { backend: 'ollama', modelId: 'gone', tuningKey: '', tuning: {}, staleness: { stale: true } },
+ { backend: 'ollama', modelId: 'here', tuningKey: '', tuning: {}, staleness: { stale: true } },
+ ],
+ uninstalled: [{ backend: 'ollama', modelId: 'gone' }],
+ }));
+ runAssessment.mockResolvedValue(measured());
+
+ const started = await startSweep({ scope: 'stale' });
+ expect(started.total).toBe(1);
+ await settle();
+ expect(runAssessment).toHaveBeenCalledWith(expect.objectContaining({ modelId: 'here' }));
+ });
+
+ // A refused start has to SAY so — a silent no-op would leave the page waiting
+ // for progress that never arrives.
+ it('refuses a second sweep while one is running', async () => {
+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'a' }] }));
+ // Never resolves: the first sweep stays in flight for the duration.
+ runAssessment.mockImplementation(() => new Promise(() => {}));
+
+ await startSweep({ scope: 'unmeasured' });
+ const second = await startSweep({ scope: 'unmeasured' });
+ expect(second.rejected).toBe('a sweep is already running');
+ });
+
+ it('refuses a scope that covers nothing', async () => {
+ getAssessmentReport.mockResolvedValue(report());
+ const result = await startSweep({ scope: 'all' });
+ expect(result.rejected).toBe('nothing to measure for that scope');
+ expect(runAssessment).not.toHaveBeenCalled();
+ });
+
+ it('emits start and per-model progress frames under the sweep scope', async () => {
+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'a' }] }));
+ runAssessment.mockResolvedValue(measured());
+ const frames = [];
+
+ await startSweep({ scope: 'unmeasured', onProgress: (f) => frames.push(f) });
+ await settle();
+ expect(frames.map((f) => f.event)).toEqual(['start', 'model-start', 'complete']);
+ expect(frames.every((f) => f.scope === 'assessment-sweep')).toBe(true);
+ });
+
+ it('survives a progress listener that throws', async () => {
+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'a' }] }));
+ runAssessment.mockResolvedValue(measured());
+
+ await startSweep({ scope: 'unmeasured', onProgress: () => { throw new Error('socket closed'); } });
+ await settle();
+ expect(getSweepStatus().status).toBe('complete');
+ });
+});
+
+describe('cancelSweep', () => {
+ it('stops the queue and keeps what was already measured', async () => {
+ getAssessmentReport.mockResolvedValue(report({
+ unassessed: [{ backend: 'ollama', modelId: 'a' }, { backend: 'ollama', modelId: 'b' }],
+ }));
+ // First model lands; the second reports itself cancelled, as runAssessment
+ // does when it sees the abort signal.
+ runAssessment
+ .mockResolvedValueOnce(measured())
+ .mockResolvedValueOnce({ cancelled: true });
+
+ await startSweep({ scope: 'unmeasured' });
+ await Promise.resolve();
+ cancelSweep();
+ await settle();
+
+ const status = getSweepStatus();
+ expect(status.status).toBe('cancelled');
+ // The abandoned model is NOT a result — recording it would make a stopped
+ // sweep look like it measured what it gave up on.
+ expect(status.results.map((r) => r.modelId)).toEqual(['a']);
+ });
+
+ it('is a no-op when nothing is running', () => {
+ expect(cancelSweep().status).toBe('idle');
+ });
+
+ // Cancelling frees the slot immediately, so a replacement sweep can start
+ // while the abandoned one is still unwinding its last model. That loop must
+ // not write its results (or its terminal frame) into the new queue.
+ it('does not let an abandoned queue write into the sweep that replaced it', async () => {
+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'slow' }] }));
+ let releaseFirst;
+ runAssessment.mockImplementationOnce(() => new Promise((resolve) => { releaseFirst = resolve; }));
+
+ await startSweep({ scope: 'unmeasured' });
+ cancelSweep();
+
+ // A fresh queue takes over before the abandoned model resolves.
+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'second' }] }));
+ runAssessment.mockResolvedValue(measured());
+ const frames = [];
+ await startSweep({ scope: 'unmeasured', onProgress: (f) => frames.push(f) });
+
+ releaseFirst(measured('fits', 9));
+ await settle();
+
+ const status = getSweepStatus();
+ expect(status.results.map((r) => r.modelId)).toEqual(['second']);
+ // Exactly one terminal frame, and it belongs to the queue still standing.
+ expect(frames.filter((f) => f.event === 'complete')).toHaveLength(1);
+ });
+});
+
+describe('getSweepStatus', () => {
+ it('reports idle before anything has been started', () => {
+ expect(getSweepStatus()).toMatchObject({ status: 'idle', total: 0, completed: 0, current: null, results: [] });
+ });
+
+ it('never exposes the abort controller', async () => {
+ getAssessmentReport.mockResolvedValue(report({ unassessed: [{ backend: 'ollama', modelId: 'a' }] }));
+ runAssessment.mockImplementation(() => new Promise(() => {}));
+ await startSweep({ scope: 'unmeasured' });
+ expect(getSweepStatus().controller).toBeUndefined();
+ });
+});
diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.js
index 1ba31a6e09..6ba4e89675 100644
--- a/server/services/localModelAssessments.js
+++ b/server/services/localModelAssessments.js
@@ -27,9 +27,13 @@
* 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.
+ * There is NO scheduler and NO boot hook. Do not add one: a fresh install must be
+ * silent on the LLM front until the user asks.
+ *
+ * `localModelAssessmentSweep.js` measures every installed model in one pass, and
+ * is not an exception to that — it runs only from a button press behind a consent
+ * gate that names the model and generation count, which is the user asking. What
+ * stays forbidden is anything that starts it WITHOUT that press.
*
* ## Where the pieces live
*
@@ -42,10 +46,12 @@
import {
ASSESSMENT_INTENTS,
+ buildThroughputReport,
classifyFitVerdict,
classifySampleFailure,
rankByIntent,
summarizePerformance,
+ summarizeSweepScopes,
} from '../lib/localModelAssessment.js';
import {
assessmentKey,
@@ -73,6 +79,8 @@ import {
tuningSignature,
tuningSpecsFor,
} from '../lib/localModelTuning.js';
+import { claimHeavyLocalJob } from '../lib/heavyJobClaim.js';
+import { ServerError } from '../lib/errorHandler.js';
import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
import { getAllProviders } from './providers.js';
import { runEndpointLlmTest, runLocalLlmTest } from './localLlmPlayground.js';
@@ -227,14 +235,26 @@ export async function listRuntimeModels(runtime) {
export function toSample(contextTokens, result) {
const timings = result?.timings || {};
const ok = !result?.error && typeof result?.text === 'string' && result.text.trim().length > 0;
+ const measured = (value) => (ok && Number.isFinite(value) ? value : null);
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,
+ charsPerSecond: measured(timings.charsPerSecond),
+ ttftMs: measured(timings.ttftMs),
totalMs: Number.isFinite(timings.totalMs) ? timings.totalMs : null,
chars: Number.isFinite(timings.chars) ? timings.chars : null,
+ // Token-denominated throughput, when the daemon reported token counts (see
+ // `summarizeTimings`). `null` = the daemon reported none — NOT zero, and not
+ // a chars/s figure divided by a guessed chars-per-token ratio, which would
+ // dress arithmetic up as a measurement.
+ completionTokens: measured(timings.completionTokens),
+ promptTokens: measured(timings.promptTokens),
+ tokensPerSecond: measured(timings.tokensPerSecond),
+ promptTokensPerSecond: measured(timings.promptTokensPerSecond),
+ // `true` = the count came from counting streamed frames rather than the
+ // daemon's tokenizer, and every figure derived from it must be labelled.
+ tokensEstimated: ok && typeof timings.tokensEstimated === 'boolean' ? timings.tokensEstimated : null,
error: result?.error || (ok ? null : 'model produced no output'),
};
}
@@ -282,6 +302,10 @@ function describeVerdict(verdict, samples) {
* rest are recorded so two readings of one model stay comparable. The tuning
* is part of the record's identity, so a second tuning of the same model is a
* NEW record rather than an overwrite.
+ * @param {number} [options.claimTimeoutMs] how long to WAIT for the machine-wide
+ * accelerator claim before giving up. 0 (the default) refuses immediately,
+ * which is right for an interactive click; the sweep waits, so one image
+ * render slipping in between two models does not kill an overnight queue.
* @param {AbortSignal} [options.signal] client disconnect
* @param {(frame: object) => void} [options.onProgress] per-sample progress.
* A run is minutes long on a large model, so the caller (the route) forwards
@@ -290,7 +314,7 @@ function describeVerdict(verdict, samples) {
* THIS run apart from an unrelated model install streaming on the same event.
* @returns {Promise<object>} the persisted assessment record
*/
-export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_CONTEXT_TOKENS, tuning, signal, onProgress } = {}) {
+export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_CONTEXT_TOKENS, tuning, signal, onProgress, claimTimeoutMs = 0 } = {}) {
const contexts = [...new Set(contextTokens)].filter((n) => Number.isFinite(n) && n > 0).sort((a, b) => a - b);
// The listener runs outside the request lifecycle's error path in some callers
// (a socket emit can throw on a closed io), and a broken progress consumer must
@@ -300,6 +324,28 @@ export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_
try { onProgress({ scope: 'assessment', backend, modelId, ...frame }); }
catch (err) { console.error(`❌ Local LLM: assessment progress listener failed: ${err.message}`); }
};
+ // A measurement is only valid if it had the machine to itself. This is the
+ // SAME machine-wide claim local image/video/3D rendering and LoRA training
+ // take (`lib/heavyJobClaim.js`), for a stronger reason than theirs: a
+ // contending job does not merely slow this run down, it silently changes the
+ // number being recorded. It also makes the "one at a time" rule real for every
+ // caller — a second browser tab, ⌘K, or curl — rather than resting on a
+ // disabled button. Refusing is far better than recording a corrupt reading.
+ const claim = await claimHeavyLocalJob({ kind: 'local-model assessment', id: `${backend}/${modelId}`, timeoutMs: claimTimeoutMs });
+ if (!claim.ok) {
+ throw new ServerError(claim.message, { status: 409, code: 'HEAVY_LOCAL_JOB_BUSY', context: { holder: claim.holder } });
+ }
+ try {
+ return await measureModel({ backend, modelId, contexts, tuning, signal, emit });
+ } finally {
+ await claim.release();
+ }
+}
+
+// The measurement itself, with the accelerator already claimed by the caller
+// above. Split out so the claim's release is one `finally` around one call
+// rather than wrapped around a 100-line body.
+async function measureModel({ backend, modelId, contexts, tuning, signal, emit }) {
const normalizedTuning = normalizeTuning(backend, tuning);
const tuningKey = tuningSignature(normalizedTuning);
const tuningLabel = describeTuning(backend, normalizedTuning);
@@ -548,6 +594,16 @@ export async function getAssessmentReport({ intent = 'balanced' } = {}) {
runtimes,
// Which tuning won, per model, for models measured under two or more.
tuningComparison: compareTunings(scorable),
+ // Every measurement as a tokens-per-second table, fastest first, with the
+ // per-context readings intact. Unlike `ranked` this is not a recommendation
+ // — it is the raw speed answer, which is what you read the morning after a
+ // sweep. Built from still-installed records only: a table row for a model
+ // that can no longer run is noise.
+ throughputReport: buildThroughputReport(stillInstalled),
+ // How many measurements each sweep scope would run right now, so the
+ // "Measure all" consent gate can name a real number rather than an estimate.
+ // Derived from the same selector the sweep uses, so the two cannot disagree.
+ sweepScopes: summarizeSweepScopes({ assessments: stillInstalled, unassessed }),
// Runtimes whose model list could not be trusted — distinct from "listed,
// and legitimately empty".
listErrors,
diff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.js
index 7ab570a446..b1de8152ad 100644
--- a/server/services/localModelAssessments.test.js
+++ b/server/services/localModelAssessments.test.js
@@ -67,6 +67,9 @@ const svc = await import('./localModelAssessments.js');
// The durable store is a separate module (no path to a provider); the read-only
// projections the catalog badge consumes live there.
const store = await import('./localModelAssessmentStore.js');
+// Dynamic, like the two above: a static import hoists ABOVE the fileUtils mock,
+// and this module resolves its claim path from `PATHS.data` at load time.
+const { claimHeavyLocalJob } = await import('../lib/heavyJobClaim.js');
const STORE = join(tempRoot, 'local-llm', 'assessments.json');
@@ -193,6 +196,45 @@ describe('loadAssessments / getAssessmentReport (read path)', () => {
});
});
+describe('runAssessment — machine-wide accelerator claim', () => {
+ // A measurement is only valid if it had the machine to itself, so this is
+ // enforced in the SERVICE, not by a disabled button: a second tab, ⌘K, or curl
+ // has to hit the same wall. Refusing beats recording a corrupt reading.
+ it('refuses when another heavy local job already holds the machine', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun());
+ const held = await claimHeavyLocalJob({ kind: 'LoRA training', id: 'run-1' });
+ expect(held.ok).toBe(true);
+ try {
+ await expect(svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] }))
+ .rejects.toMatchObject({ code: 'HEAVY_LOCAL_JOB_BUSY' });
+ // Nothing was measured, so nothing was recorded.
+ expect(runLocalLlmTest).not.toHaveBeenCalled();
+ } finally {
+ await held.release();
+ }
+ });
+
+ it('releases the claim afterwards, so the next measurement can run', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun());
+ await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });
+ const after = await claimHeavyLocalJob({ kind: 'probe', id: 'after' });
+ expect(after.ok).toBe(true);
+ await after.release();
+ });
+
+ it('releases the claim even when the run throws', async () => {
+ // A relaunch failure escapes before any sample runs; a leaked claim would
+ // wedge every local render on the machine until the process exited.
+ relaunchLlamaServerWithTuning.mockRejectedValueOnce(new Error('boom'));
+ getLlamaServerEndpoint.mockResolvedValue(null);
+ await svc.runAssessment({ backend: 'llama', modelId: 'dflash', contextTokens: [512], tuning: { ubatchSize: 512 } })
+ .catch(() => null);
+ const after = await claimHeavyLocalJob({ kind: 'probe', id: 'after-throw' });
+ expect(after.ok).toBe(true);
+ await after.release();
+ });
+});
+
describe('runAssessment', () => {
it('samples every context in ascending order and persists the result', async () => {
runLocalLlmTest.mockResolvedValue(okRun());