Skip to content

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

feat(local-llm): let a measured assessment overrule the size-estimate fit badge, stream its progress, and flag a stale reading (#4539)

[._.]/ Adam Eivyd7154956706f
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsx
index 593078ab30..18f6a338ed 100644
--- a/client/src/components/settings/LocalLlmTab.jsx
+++ b/client/src/components/settings/LocalLlmTab.jsx
@@ -74,8 +74,31 @@ const FIT_META = {
comfortable: { label: 'fits comfortably', cls: 'text-port-success' },
tight: { label: 'tight fit', cls: 'text-port-warning' },
'too-large': { label: 'exceeds RAM', cls: 'text-port-error' },
+ // Only ever produced by a MEASUREMENT — the size estimate cannot know that a
+ // backend refuses a model outright, and no amount of free RAM changes it.
+ incompatible: { label: 'backend refused it', cls: 'text-port-error' },
};
+// The fit badge is a size ESTIMATE (weights + ~20% overhead vs. usable memory)
+// until the model has actually been run here, at which point the measurement
+// replaces it. The tooltip has to say which one the reader is looking at —
+// "fits comfortably" from arithmetic and "fits comfortably" from a real run are
+// very different claims — and it names the disagreement when there is one,
+// because that is the most useful thing the measurement can say.
+function fitTitle(source, entry) {
+ if (source !== 'measured') {
+ const stale = entry?.measuredFit && entry?.stale
+ ? ` A previous measurement (${FIT_META[entry.measuredFit]?.label || entry.measuredFit}) was taken on a different machine state, so the estimate stands.`
+ : '';
+ return `Estimated fit on this machine — model weights + ~20% overhead vs. usable memory.${stale}`;
+ }
+ const measuredAt = entry?.assessedAt ? ` on ${new Date(entry.assessedAt).toLocaleDateString()}` : '';
+ const disagree = entry?.disagrees
+ ? ` The size estimate said "${FIT_META[entry.estimatedFit]?.label || entry.estimatedFit}".`
+ : '';
+ return `Measured on this machine${measuredAt} — PortOS ran this model rather than estimating from its file size.${disagree}`;
+}
+
// Model format badge — GGUF (llama.cpp, cross-backend) vs. MLX (Apple's native
// format, LM Studio on Apple Silicon only). Shown so the user knows what they're
// installing when both formats appear in the same result list.
@@ -923,8 +946,14 @@ export function LocalLlmTab() {
const chosenUnsupported = chosenVariant?.unsupportedReason ?? null;
const size = chosenVariant?.size || m.size;
const sizeBytes = chosenVariant?.sizeBytes ?? m.sizeBytes;
- const fit = chosenVariant?.fit;
+ // Curated entries fetched without `?variants=1` carry no
+ // variant list at all — the server puts a measured fit on the
+ // model itself there, so fall back to it rather than dropping
+ // the only evidence that exists.
+ const fitEntry = chosenVariant || m;
+ const fit = fitEntry?.fit;
const fitMeta = fit ? FIT_META[fit] : null;
+ const fitMeasured = fitEntry?.fitSource === 'measured';
const ram = recommendedRamGb(sizeBytes, size);
const ctxLabel = formatContextLength(m.contextLength);
const createdMs = new Date(m.createdAt).getTime();
@@ -978,11 +1007,15 @@ export function LocalLlmTab() {
>
{variants.map((v) => (
<option key={v.installId} value={v.installId}>
- {v.quant}{v.size ? ` · ${v.size}` : ''}{v.installed ? ' · installed' : ''}{v.recommended ? ' · recommended' : ''}{v.fit === 'too-large' ? ' · exceeds RAM' : ''}{v.unsupported === 'sharded' ? ' · sharded (not on Ollama)' : ''}
+ {v.quant}{v.size ? ` · ${v.size}` : ''}{v.installed ? ' · installed' : ''}{v.recommended ? ' · recommended' : ''}{v.fit === 'too-large' ? ' · exceeds RAM' : ''}{v.fit === 'incompatible' ? ' · backend refused it' : ''}{v.fitSource === 'measured' ? ' · measured' : ''}{v.unsupported === 'sharded' ? ' · sharded (not on Ollama)' : ''}
</option>
))}
</select>
- {fitMeta && <span className={`text-[11px] ${fitMeta.cls}`} title="Fit on this machine — model weights + ~20% overhead vs. usable memory">{fitMeta.label}</span>}
+ {fitMeta && (
+ <span className={`text-[11px] ${fitMeta.cls}`} title={fitTitle(fitEntry?.fitSource, fitEntry)}>
+ {fitMeta.label}{fitMeasured ? ' (measured)' : ''}
+ </span>
+ )}
</div>
)}
<div className="flex items-center gap-1.5 flex-wrap text-[11px] text-gray-600 mt-1">
@@ -991,7 +1024,9 @@ export function LocalLlmTab() {
{/* Single-variant cards (e.g. MLX) have no quant picker, so
surface the RAM-fit hint here instead of in the picker row. */}
{fitMeta && !hasVariantPicker && (
- <span className={fitMeta.cls} title="Fit on this machine — model weights + ~20% overhead vs. usable memory">{fitMeta.label}</span>
+ <span className={fitMeta.cls} title={fitTitle(fitEntry?.fitSource, fitEntry)}>
+ {fitMeta.label}{fitMeasured ? ' (measured)' : ''}
+ </span>
)}
{ctxLabel && (
<span title="Native context window (max tokens)">{ctxLabel}</span>
diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsx
index ff189b02a2..c01eead609 100644
--- a/client/src/components/settings/LocalLlmTab.test.jsx
+++ b/client/src/components/settings/LocalLlmTab.test.jsx
@@ -209,3 +209,56 @@ describe('LocalLlmTab runtime context window', () => {
expect(screen.queryByTitle(/Loaded models are running at/)).toBeNull();
});
});
+
+describe('LocalLlmTab measured fit badge', () => {
+ const catalogEntry = (overrides = {}) => ({
+ key: 'example-14b',
+ id: 'example-model:14b',
+ name: 'Example 14B',
+ params: '14B',
+ description: 'An example instruct model.',
+ category: 'general',
+ size: '9 GB',
+ sizeBytes: 9_000_000_000,
+ source: 'catalog',
+ ...overrides,
+ });
+
+ it('marks a measured verdict as measured and keeps the estimate it overruled in the tooltip', async () => {
+ getLocalLlmCatalog.mockResolvedValue({
+ models: [catalogEntry({
+ fit: 'too-large',
+ fitSource: 'measured',
+ estimatedFit: 'comfortable',
+ measuredFit: 'too-large',
+ disagrees: true,
+ assessedAt: '2026-01-02T00:00:00.000Z',
+ })],
+ });
+ await renderTab();
+
+ const badge = await screen.findByText(/exceeds RAM \(measured\)/);
+ expect(badge).toBeInTheDocument();
+ expect(badge.getAttribute('title')).toMatch(/Measured on this machine/);
+ // The disagreement is the point — the reader must see what the estimate claimed.
+ expect(badge.getAttribute('title')).toMatch(/fits comfortably/);
+ });
+
+ it('labels an unmeasured verdict as the estimate it is', async () => {
+ getLocalLlmCatalog.mockResolvedValue({ models: [catalogEntry({ fit: 'comfortable', fitSource: 'estimated', estimatedFit: 'comfortable', measuredFit: null })] });
+ await renderTab();
+
+ const badge = await screen.findByText('fits comfortably');
+ expect(badge.getAttribute('title')).toMatch(/Estimated fit/);
+ expect(badge.textContent).not.toMatch(/measured/);
+ });
+
+ it('renders the measurement-only verdict the size estimate can never produce', async () => {
+ // No amount of free RAM fixes a backend refusing a model, so `incompatible`
+ // only ever comes from a real run.
+ getLocalLlmCatalog.mockResolvedValue({ models: [catalogEntry({ fit: 'incompatible', fitSource: 'measured', estimatedFit: 'comfortable', measuredFit: 'incompatible', disagrees: true })] });
+ await renderTab();
+
+ expect(await screen.findByText(/backend refused it \(measured\)/)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/settings/LocalModelAssessments.jsx b/client/src/components/settings/LocalModelAssessments.jsx
index 02faea1a32..09be1c8089 100644
--- a/client/src/components/settings/LocalModelAssessments.jsx
+++ b/client/src/components/settings/LocalModelAssessments.jsx
@@ -18,11 +18,13 @@
*/
import { useCallback, useEffect, useRef, useState } from 'react';
-import { Gauge, RefreshCw, Trash2, Play, AlertTriangle } from 'lucide-react';
+import { Gauge, RefreshCw, Trash2, Play, AlertTriangle, History } from 'lucide-react';
+import socket from '../../services/socket';
import Modal from '../ui/Modal';
import BrailleSpinner from '../BrailleSpinner';
import toast from '../ui/Toast';
import { useAsyncAction } from '../../hooks/useAsyncAction';
+import useMounted from '../../hooks/useMounted';
import { formatDurationMs } from '../../utils/formatters';
import {
getLocalLlmAssessments, runLocalLlmAssessment, deleteLocalLlmAssessment,
@@ -55,6 +57,21 @@ const Measured = ({ value, suffix = '', digits = 0 }) =>
? <>{value.toFixed(digits)}{suffix}</>
: <span className="text-gray-600 italic">not measured</span>);
+// A measurement only describes the machine it was taken on. When the recorded
+// environment no longer matches the live one — a RAM upgrade, a backend update —
+// the reading is silently misleading, and nothing else on this page would say so.
+function StalePill({ staleness }) {
+ if (!staleness?.stale) return null;
+ return (
+ <span
+ className="inline-flex items-center gap-1 px-1.5 py-0.5 text-[10px] font-medium rounded border text-port-warning border-port-warning/50"
+ title={staleness.description || 'Measured on a different machine state.'}
+ >
+ <History size={9} /> stale
+ </span>
+ );
+}
+
function VerdictPill({ verdict }) {
const meta = VERDICT_META[verdict] || VERDICT_META.unknown;
return (
@@ -65,7 +82,7 @@ function VerdictPill({ verdict }) {
// Consent gate. PortOS never calls a provider the user didn't knowingly ask for,
// so this names the exact backend, model, and generation count before the first
// request goes out — the same contract as the POST drill cache's fill modal.
-function AssessmentConsentModal({ target, contextTokens, onCancel, onConfirm, running }) {
+function AssessmentConsentModal({ target, contextTokens, onCancel, onConfirm, running, progress }) {
if (!target) return null;
return (
<Modal open onClose={onCancel} size="sm" ariaLabel="Run local model assessment" closeOnBackdrop={!running}>
@@ -84,6 +101,22 @@ function AssessmentConsentModal({ target, contextTokens, onCancel, onConfirm, ru
Nothing else on this page calls a model. This can take several minutes on a large model, and it
loads the model into memory. The result stays on this machine and is never synced to a peer.
</p>
+ {/* Live per-sample progress off the `localLlm:progress` socket event, so a
+ multi-minute run reports which sample it is on instead of a bare spinner.
+ Absent until the first frame arrives — never a fake 0%. */}
+ {running && progress && (
+ <div className="space-y-1" aria-live="polite">
+ {Number.isFinite(progress.sampleCount) && progress.sampleCount > 0 && (
+ <div className="h-1 rounded bg-port-border overflow-hidden">
+ <div
+ className="h-full bg-port-accent transition-all"
+ style={{ width: `${Math.round((Math.min(progress.sampleIndex ?? 0, progress.sampleCount) / progress.sampleCount) * 100)}%` }}
+ />
+ </div>
+ )}
+ <p className="text-[11px] text-gray-400 break-words">{progress.message}</p>
+ </div>
+ )}
<div className="flex gap-3 pt-1">
{/* Stays enabled while the run is in flight — it aborts the request
rather than merely closing the modal, so the user is never stuck
@@ -117,8 +150,14 @@ function RankedRow({ entry, onRemeasure, onDelete, busy }) {
<span className="text-sm text-white font-mono break-all">{entry.modelId}</span>
<span className="text-[10px] text-gray-500">{BACKEND_LABEL[entry.backend] || entry.backend}</span>
<VerdictPill verdict={entry.verdict} />
+ <StalePill staleness={entry.staleness} />
</div>
<p className="text-xs text-gray-400 mt-1">{entry.explanation}</p>
+ {entry.staleness?.stale && (
+ <p className="text-[11px] text-port-warning mt-0.5">
+ {entry.staleness.description} Measure again to refresh it.
+ </p>
+ )}
{/* The score renormalizes over MEASURED axes, so a model with partial
evidence can outrank a fully-measured one. Say so rather than
presenting the rank as though it rested on the same footing. */}
@@ -209,6 +248,9 @@ export function LocalModelAssessments() {
const [report, setReport] = useState(null);
const [loading, setLoading] = useState(true);
const [pendingTarget, setPendingTarget] = useState(null);
+ // 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);
const load = useCallback(async (nextIntent) => {
setLoading(true);
@@ -221,6 +263,38 @@ export function LocalModelAssessments() {
useEffect(() => { load(intent); }, [load, intent]);
+ // Which model this panel is currently measuring. A ref, not state: the socket
+ // handler subscribes once and must read the CURRENT target, not the one
+ // captured when it was registered.
+ const activeTargetRef = useRef(null);
+ // Re-arms on every mount, so StrictMode's dev mount→cleanup→mount cycle does
+ // not leave the panel permanently deaf to progress frames.
+ const mountedRef = useMounted();
+
+ // A run is one blocking POST, so without this the UI shows a spinner for
+ // minutes. The server streams per-sample frames over the same
+ // `localLlm:progress` event model pulls and migrations use — hence the strict
+ // filtering below, or a background model download would drive this bar.
+ useEffect(() => {
+ const handleProgress = (frame) => {
+ if (!mountedRef.current) return;
+ if (frame?.scope !== 'assessment') return;
+ const target = activeTargetRef.current;
+ // Frames for a model this panel is not measuring (another tab measuring
+ // something else, a run the user already cancelled) are dropped rather
+ // than rendered — a stale message is worse than none.
+ if (!target || frame.backend !== target.backend || frame.modelId !== target.modelId) return;
+ if (frame.event === 'complete') { setProgress(null); return; }
+ setProgress({
+ message: frame.message || '',
+ sampleIndex: Number.isFinite(frame.sampleIndex) ? frame.sampleIndex : null,
+ sampleCount: Number.isFinite(frame.sampleCount) ? frame.sampleCount : null,
+ });
+ };
+ socket.on('localLlm:progress', handleProgress);
+ return () => socket.off('localLlm:progress', handleProgress);
+ }, []);
+
// A run occupies the local provider for minutes. Without an abort, leaving
// the page (or changing your mind) leaves it running with nobody listening —
// the server drops the assessment on an aborted signal rather than recording a
@@ -250,7 +324,11 @@ export function LocalModelAssessments() {
const confirmRun = async () => {
const target = pendingTarget;
+ activeTargetRef.current = target;
+ setProgress(null);
const result = await runAssessment(target);
+ activeTargetRef.current = null;
+ setProgress(null);
setPendingTarget(null);
// An aborted run recorded nothing on either side, so there is no verdict
// to report — marked `cancelled` by the abort catch above, or by the server
@@ -274,6 +352,10 @@ export function LocalModelAssessments() {
const cancelRun = () => {
runControllerRef.current?.abort();
+ // Stop accepting frames for the abandoned run BEFORE the modal closes, or a
+ // late frame would repopulate a progress bar with nothing behind it.
+ activeTargetRef.current = null;
+ setProgress(null);
setPendingTarget(null);
};
@@ -403,6 +485,7 @@ export function LocalModelAssessments() {
target={pendingTarget}
contextTokens={report?.defaultContextTokens || []}
running={running}
+ progress={progress}
onCancel={cancelRun}
onConfirm={confirmRun}
/>
diff --git a/client/src/components/settings/LocalModelAssessments.test.jsx b/client/src/components/settings/LocalModelAssessments.test.jsx
index ee594f2dc6..784823ee2c 100644
--- a/client/src/components/settings/LocalModelAssessments.test.jsx
+++ b/client/src/components/settings/LocalModelAssessments.test.jsx
@@ -1,5 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { render, screen, waitFor } from '@testing-library/react';
+import { act, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
vi.mock('../../services/api', () => ({
@@ -10,8 +10,15 @@ vi.mock('../../services/api', () => ({
vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));
+// Per-sample run progress arrives on the shared `localLlm:progress` socket
+// event; the tests below replay frames through the registered handler.
+vi.mock('../../services/socket', () => ({
+ default: { on: vi.fn(), off: vi.fn() },
+}));
+
import { getLocalLlmAssessments, runLocalLlmAssessment, deleteLocalLlmAssessment } from '../../services/api';
import toast from '../ui/Toast';
+import socket from '../../services/socket';
import LocalModelAssessments from './LocalModelAssessments.jsx';
const report = (overrides = {}) => ({
@@ -219,4 +226,102 @@ describe('LocalModelAssessments', () => {
render(<LocalModelAssessments />);
expect(await screen.findByText(/Could not list installed models for LM Studio/)).toBeInTheDocument();
});
+
+ describe('stale measurements', () => {
+ it('flags a reading taken on a different machine state and says what changed', async () => {
+ getLocalLlmAssessments.mockResolvedValue(report({
+ ranked: [rankedEntry({
+ staleness: {
+ comparable: true,
+ stale: true,
+ changes: [{ field: 'totalMemoryGb', label: 'installed memory', from: 32, to: 64 }],
+ description: 'Measured on a different machine state — installed memory 32 → 64.',
+ },
+ })],
+ }));
+ render(<LocalModelAssessments />);
+
+ expect(await screen.findByText('stale')).toBeInTheDocument();
+ expect(screen.getByText(/installed memory 32 → 64/)).toBeInTheDocument();
+ expect(screen.getByText(/Measure again to refresh it/)).toBeInTheDocument();
+ });
+
+ it('says nothing when the reading still matches this machine', async () => {
+ getLocalLlmAssessments.mockResolvedValue(report({
+ ranked: [rankedEntry({ staleness: { comparable: true, stale: false, changes: [], description: null } })],
+ }));
+ render(<LocalModelAssessments />);
+
+ await screen.findByText('example-model:7b');
+ expect(screen.queryByText('stale')).not.toBeInTheDocument();
+ });
+
+ it('does not claim freshness for a record nothing could be compared against', async () => {
+ // `comparable: false` is UNKNOWN, not current — it must not render a
+ // stale warning either way.
+ getLocalLlmAssessments.mockResolvedValue(report({
+ ranked: [rankedEntry({ staleness: { comparable: false, stale: false, changes: [], description: null } })],
+ }));
+ render(<LocalModelAssessments />);
+
+ await screen.findByText('example-model:7b');
+ expect(screen.queryByText('stale')).not.toBeInTheDocument();
+ });
+ });
+
+ describe('run progress', () => {
+ const emitProgress = (frame) => {
+ // Replay whatever handler the component registered on the shared event.
+ for (const [event, handler] of socket.on.mock.calls) {
+ if (event === 'localLlm:progress') act(() => handler(frame));
+ }
+ };
+
+ const startRun = async () => {
+ const user = userEvent.setup();
+ getLocalLlmAssessments.mockResolvedValue(report({
+ unassessed: [{ backend: 'ollama', modelId: 'example-model:7b', params: '7B' }],
+ }));
+ // 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: /run assessment/i }));
+ return user;
+ };
+
+ it('renders per-sample progress from the shared localLlm:progress event', async () => {
+ await startRun();
+ emitProgress({
+ scope: 'assessment', backend: 'ollama', modelId: 'example-model:7b',
+ event: 'start', sampleIndex: 1, sampleCount: 3, message: 'example-model:7b: sample 2/3 at 4,096 tokens of context…',
+ });
+ expect(await screen.findByText(/sample 2\/3 at 4,096 tokens/)).toBeInTheDocument();
+ });
+
+ it('ignores frames from an unrelated model pull on the same channel', async () => {
+ await startRun();
+ emitProgress({ event: 'start', message: 'other-model:70b: pulling 42%' });
+ emitProgress({
+ scope: 'assessment', backend: 'ollama', modelId: 'some-other-model:3b',
+ event: 'start', sampleIndex: 1, sampleCount: 3, message: 'some-other-model:3b: sample 2/3',
+ });
+ await waitFor(() => expect(screen.queryByText(/pulling 42%/)).not.toBeInTheDocument());
+ expect(screen.queryByText(/some-other-model/)).not.toBeInTheDocument();
+ // …and the panel is still live: its OWN frame renders right after.
+ emitProgress({
+ scope: 'assessment', backend: 'ollama', modelId: 'example-model:7b',
+ event: 'start', sampleIndex: 0, sampleCount: 3, message: 'example-model:7b: sample 1/3',
+ });
+ expect(await screen.findByText(/sample 1\/3/)).toBeInTheDocument();
+ });
+
+ it('unsubscribes on unmount so a late frame cannot update a dead panel', async () => {
+ getLocalLlmAssessments.mockResolvedValue(report());
+ const { unmount } = render(<LocalModelAssessments />);
+ await screen.findByText(/Nothing measured yet/);
+ unmount();
+ expect(socket.off).toHaveBeenCalledWith('localLlm:progress', expect.any(Function));
+ });
+ });
});
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index fd7a005343..1edde360ee 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -60,7 +60,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.
- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + ordered job list. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and the plan's `agent-prompt` jobs name managed apps that only exist on this machine. No sync cursor, no tombstone. Its four companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight), and `data/cos/quota-burn-denials.json` (per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL — deleting it only risks one dispatch into a still-exhausted window). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).
- YouTube brain ingests — `data/brain/youtube/{videoId}.md` (transcript), `{videoId}.mp3` (optional audio), plus `data/brain/youtube/index.json` (the ingest index) and `data/brain/youtube-ingest-settings.json`. The transcript IS an external file: it is mirrored into the user's Obsidian vault, edited there, and syncs through iCloud — the same boundary that keeps the Daily Log file-backed. The index is **intentionally machine-local — never federated**: every field in it is a local filesystem path, an Obsidian vault id, or a local video-history id, so a peer's copy would be meaningless and would poison brain reconcile exactly the way the daily log's `journal-obsidian-locations.json` sidecar would. The durable, federated record of "I consumed and kept this" is the brain `links` entry (`db-primary` via the brain store) plus a `media.watch` row in `human_activity_events`. No sync cursor, no tombstone. Adapter: `server/services/youtubeIngest.js`.
-- Local-model assessments — `data/local-llm/assessments.json` (#4539). Measured evidence for one installed local model per (backend, model): the fit verdict (`fits`/`does-not-fit`/`incompatible`/`unknown`), per-context throughput/TTFT samples, resident footprint, and the coarse hardware environment the measurement was taken in. `file-primary` — a flat, capped, single-JSON projection with no cross-record queries and no relationships; the newest measurement replaces the old one per model rather than accumulating history. **Intentionally machine-local — never federated**: an assessment is a claim about THIS box, so a peer inheriting a 128 GB machine's its verdict for its 8 GB laptop would be actively wrong. No sync cursor, no tombstone, no `PORTOS_SCHEMA_VERSIONS` entry. Backed up (a run costs the user minutes of local compute), and the environment record deliberately carries no hostname/username/path. Adapter: `server/services/localModelAssessments.js`; scoring in `server/lib/localModelAssessment.js`.
+- Local-model assessments — `data/local-llm/assessments.json` (#4539). Measured evidence for one installed local model per (backend, model): the fit verdict (`fits`/`does-not-fit`/`incompatible`/`unknown`), per-context throughput/TTFT samples, resident footprint, and the coarse hardware environment the measurement was taken in. `file-primary` — a flat, capped, single-JSON projection with no cross-record queries and no relationships; the newest measurement replaces the old one per model rather than accumulating history. **Intentionally machine-local — never federated**: an assessment is a claim about THIS box, so a peer inheriting a 128 GB machine's its verdict for its 8 GB laptop would be actively wrong. No sync cursor, no tombstone, no `PORTOS_SCHEMA_VERSIONS` entry. Backed up (a run costs the user minutes of local compute), and the environment record deliberately carries no hostname/username/path. Adapter: `server/services/localModelAssessmentStore.js` (durable store + environment capture; no path to a provider, so read-only consumers like the catalog fit badge can import it); the run lives in `server/services/localModelAssessments.js` and the scoring in `server/lib/localModelAssessment.js`. Each record's environment is re-compared against the live machine on read, so a reading taken before a RAM upgrade or backend update is flagged stale rather than silently trusted.
- LoRA training datasets — `data/lora-datasets/{id}/index.json` + `images/*.png` (collectionStore). The record is inseparable from the image bytes it organizes, has no cross-record queries beyond a small characterId scan, and is **machine-local** like `data/loras/` itself (training artifacts tied to this machine's GPU output — never federates, no sync cursor/tombstone). Backed up in full: uploads and hand-edited captions are not re-creatable. Training RUN records are `db-primary` (`lora_training_runs`); run artifacts (checkpoints/samples) live under `data/training-runs/{runId}/` with checkpoints/cache excluded from backup.
---
diff --git a/server/lib/README.md b/server/lib/README.md
index 4eb05c68e0..3c4d2e61f9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -294,8 +294,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `localLlmCatalog.js` | Curated cross-backend (Ollama↔LM Studio) local-LLM catalog + install-id mapping for the migrate flow. Pure. |
| `localLlmDisk.js` | Pure on-disk reasoning for the migrate "copy GGUF locally instead of re-downloading" fast-path (Ollama manifest/blob parsing, LM Studio path layout, MLX/projector/shard detection) plus the Hugging Face registry addressing used to finish an abandoned Ollama pull. |
| `ollamaContext.js` | Ollama runtime context-window reasoning. `resolveOllamaContextLength(provider, env)` → the window PortOS should hold the daemon at (`provider.numCtx`, then `OLLAMA_CONTEXT_LENGTH`, then `null` = leave Ollama's VRAM-based auto-pick alone); `withOllamaContextEnv(env, n)` builds the `ollama serve` child env; `parseOllamaContextOverflow(text)` recognizes the `exceed_context_size_error` rejection and pulls `{ promptTokens, contextLength }` out of either the JSON body or the human message; `describeOllamaContextOverflow` / `describeOllamaContextTooSmall` render the actionable one-liners; `isSameOllamaDaemon(providerBase, managedBase)` compares host+port so a provider pointed at a *remote* Ollama never triggers a local-daemon reload; `OLLAMA_AGENT_MIN_CONTEXT` is the window below which an agent harness is warned. Pure — the daemon side lives in `services/ollamaManager.js` (`ensureContextWindow`), the pre-spawn enforcement in `services/ollamaAgentContext.js`. |
-| `localModelHeuristics.js` | Capability heuristics for untyped local (Ollama/LM Studio) models. `isEmbeddingModel`/`isGenerationModel` (so a generation/fallback run never picks an embedding model like `nomic-embed-text`); `isVisionModel(model)` (string id or model card — prefers explicit `type:'vlm'`/`capabilities:['vision']` metadata, falls back to id regex; used by the LoRA captioner); `recommendEditorialModel(models)` ranks installed models for editorial review/editing. Pure. Mirror `isEmbeddingModel`/`isVisionModel` in `client/src/utils/providers.js`. |
-| `localModelAssessment.js` | Scoring for MEASURED local-model assessments (recorded by `services/localModelAssessments.js`): `classifyFitVerdict` (`fits`/`does-not-fit`/`incompatible`/`unknown`), `summarizePerformance` (mean/peak chars-per-second, TTFT, max working context, cross-context degradation), `scoreAssessment` + `scoreForIntent` + `rankByIntent` for the balanced/smartest/fastest/lightweight pickers, and `explainAssessment`. Pure. `null` strictly means NOT MEASURED — never 0, never "failed". |
+| `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". |
| `loraDataset.js` | Pure helpers for character LoRA training datasets (`data/lora-datasets/`): `sanitizeLoraDataset` (collectionStore sanitizer), `deriveTriggerWord` (name → single-token slug with collision suffix), `prefixCaption` (idempotent trigger-word prefixing), `buildVariationMatrix` (deterministic view/pose/expression/outfit tuples for batch generation), `computeDatasetReadiness` (trainable gate: ≥`MIN_TRAINING_IMAGES` ready+captioned images, plus an advisory `recommended`/`quality` tier via `datasetQualityTier` nudging toward `RECOMMENDED_TRAINING_IMAGES`), `analyzeCaptionInvariants` (flags identity fragments repeated across ≥`INVARIANT_SHARE_THRESHOLD` of captions — those bind to the caption phrases instead of the trigger token, issue #1320) + `stripSharedFragments` (rewrite one caption with those fragments removed, trigger preserved). Prompt building + I/O live in `services/loraDatasetGenerate.js` / `services/loraDatasets.js`. |
| `issueLength.js` | Per-issue size targets fed into text stages. |
| `musicDuration.js` | Lyric-aware MiniMax Music 3 duration analysis and ending-cushioned auto-duration recommendation; mirrors `client/src/lib/musicDuration.js`. |
diff --git a/server/lib/localModelAssessment.js b/server/lib/localModelAssessment.js
index 902de05557..dbaf15d429 100644
--- a/server/lib/localModelAssessment.js
+++ b/server/lib/localModelAssessment.js
@@ -338,6 +338,11 @@ export function rankByIntent(assessments, intent = 'balanced') {
residentGb: Number.isFinite(assessment?.residentGb) ? assessment.residentGb : null,
params: assessment?.params ?? null,
assessedAt: assessment?.assessedAt || null,
+ // Travels with the entry so the UI can mark a reading taken before a RAM
+ // upgrade / backend update WITHOUT re-deriving the comparison client-side.
+ // `null` = the caller did not annotate staleness, which is not the same as
+ // "compared and current".
+ staleness: assessment?.staleness || null,
explanation: explainAssessment(assessment, resolvedIntent),
});
}
@@ -347,3 +352,139 @@ export function rankByIntent(assessments, intent = 'balanced') {
ranked.sort((a, b) => (b.score - a.score) || (b.coverage - a.coverage) || String(a.modelId).localeCompare(String(b.modelId)));
return { intent: resolvedIntent, ranked, excluded };
}
+
+// ---- staleness ---------------------------------------------------------------
+
+/**
+ * Machine facts a measurement is only valid FOR. These are the durable ones: a
+ * RAM upgrade, a CPU swap, an OS/arch move, or a backend update all invalidate a
+ * recorded reading, and none of them announce themselves to the user.
+ *
+ * Transient state is deliberately NOT here. `availableMemoryGb` swings by
+ * gigabytes minute to minute on any working machine, so comparing it would flag
+ * essentially every assessment as stale and the badge would mean nothing.
+ */
+const ENVIRONMENT_FIELDS = [
+ { field: 'platform', label: 'operating system' },
+ { field: 'arch', label: 'CPU architecture' },
+ { field: 'cpuCount', label: 'CPU count' },
+ { field: 'totalMemoryGb', label: 'installed memory', unit: ' GB', toleranceGb: 0.5 },
+ { field: 'backendVersion', label: 'backend version' },
+];
+
+// Absent on EITHER side is not-comparable, never a change: an older record
+// predates a captured field (`backendVersion` landed after the first
+// assessments), and LM Studio reports no version at all. Reading either as
+// "changed" would mark every legacy record stale on sight.
+const present = (v) => v !== null && v !== undefined && v !== '';
+
+/**
+ * Compare a recorded assessment environment against the live one.
+ *
+ * @param {object|null} recorded environment stored with the assessment
+ * @param {object|null} live environment captured now
+ * @returns {{ comparable: boolean, stale: boolean, changes: Array<{field:string,label:string,from:*,to:*}> }}
+ * `comparable: false` means no field could be compared — that is UNKNOWN, not
+ * fresh, and callers must not render it as a clean bill of health.
+ */
+export function compareEnvironments(recorded, live) {
+ const changes = [];
+ let compared = 0;
+ for (const { field, label, toleranceGb } of ENVIRONMENT_FIELDS) {
+ const from = recorded?.[field];
+ const to = live?.[field];
+ if (!present(from) || !present(to)) continue;
+ compared += 1;
+ const changed = typeof toleranceGb === 'number' && typeof from === 'number' && typeof to === 'number'
+ ? Math.abs(from - to) > toleranceGb
+ : from !== to;
+ if (changed) changes.push({ field, label, from, to });
+ }
+ return { comparable: compared > 0, stale: changes.length > 0, changes };
+}
+
+/**
+ * One human sentence naming what changed since the measurement, or `null` when
+ * nothing did (or nothing could be compared).
+ */
+export function describeStaleness(staleness) {
+ const changes = staleness?.changes;
+ if (!Array.isArray(changes) || changes.length === 0) return null;
+ const parts = changes.map(({ label, from, to }) => `${label} ${from} → ${to}`);
+ return `Measured on a different machine state — ${parts.join('; ')}.`;
+}
+
+// ---- folding measured evidence into the estimated fit badge ------------------
+
+// The catalog's estimate calls a model "tight" once its projected resident size
+// passes 60% of the usable budget (`huggingFaceCatalog.js#classifyFit`). The
+// measured verdict uses the SAME threshold against the measured footprint so the
+// two vocabularies stay comparable — a badge that flips from `comfortable` to
+// `tight` must mean the same thing whichever source produced it.
+const TIGHT_FRACTION = 0.6;
+
+/**
+ * Translate a stored assessment into the catalog's fit vocabulary.
+ *
+ * `null` means the measurement says nothing about fit (`unknown` verdict, or no
+ * assessment at all) — it must NOT collapse into `'unknown'`, which is a real
+ * badge value the estimate also produces.
+ *
+ * @param {object|null} assessment
+ * @returns {'comfortable'|'tight'|'too-large'|'incompatible'|null}
+ */
+export function measuredFitVerdict(assessment) {
+ switch (assessment?.verdict) {
+ case 'fits': {
+ const resident = assessment?.residentGb;
+ const budget = assessment?.environment?.memoryBudgetGb;
+ // Footprint unknown (LM Studio reports none) — it RAN, so `comfortable`
+ // is the honest read; we just can't say how close to the edge it was.
+ if (!Number.isFinite(resident) || !Number.isFinite(budget) || budget <= 0) return 'comfortable';
+ return resident > budget * TIGHT_FRACTION ? 'tight' : 'comfortable';
+ }
+ case 'does-not-fit': return 'too-large';
+ case 'incompatible': return 'incompatible';
+ default: return null;
+ }
+}
+
+/**
+ * Reconcile the size ESTIMATE with the MEASUREMENT for one model.
+ *
+ * Rules, in order:
+ * 1. No usable measurement → the estimate stands, unchanged.
+ * 2. A STALE measurement never overrides the estimate. It describes a machine
+ * that no longer exists (RAM changed, backend updated), so trusting it over
+ * a fresh estimate would be worse than the estimate alone — but it is still
+ * reported, because "we measured this before your upgrade" is information.
+ * 3. Otherwise the measurement wins. It ran the model; the estimate multiplied
+ * a file size by 1.2.
+ *
+ * `disagrees` is the point of the whole exercise: it marks the models where
+ * running the thing contradicted the arithmetic, which is the most useful thing
+ * this data can say.
+ *
+ * @param {string|null} estimatedFit the catalog's `classifyFit` result
+ * @param {object|null} measurement compact record from the assessments store:
+ * `{ fit, verdict, assessedAt, stale, staleReason }`
+ */
+export function reconcileFit(estimatedFit, measurement) {
+ const estimated = estimatedFit || null;
+ const measuredFit = measurement?.fit || null;
+ const base = {
+ fit: estimated,
+ fitSource: 'estimated',
+ estimatedFit: estimated,
+ measuredFit,
+ verdict: measurement?.verdict || null,
+ assessedAt: measurement?.assessedAt || null,
+ // `disagrees` is only meaningful when BOTH sides have an opinion; an
+ // unmeasured or unestimated model disagrees with nothing.
+ disagrees: Boolean(measuredFit && estimated && estimated !== 'unknown' && measuredFit !== estimated),
+ stale: Boolean(measurement?.stale),
+ staleReason: measurement?.staleReason || null,
+ };
+ if (!measuredFit || measurement?.stale) return base;
+ return { ...base, fit: measuredFit, fitSource: 'measured' };
+}
diff --git a/server/lib/localModelAssessment.test.js b/server/lib/localModelAssessment.test.js
index 52b3e1584f..edc70fcd9c 100644
--- a/server/lib/localModelAssessment.test.js
+++ b/server/lib/localModelAssessment.test.js
@@ -11,6 +11,10 @@ import {
scoreAssessment,
scoreForIntent,
summarizePerformance,
+ compareEnvironments,
+ describeStaleness,
+ measuredFitVerdict,
+ reconcileFit,
} from './localModelAssessment.js';
const okSample = (contextTokens, charsPerSecond, ttftMs = 300) => ({
@@ -301,3 +305,121 @@ describe('rankByIntent', () => {
expect(rankByIntent([], 'nonsense').intent).toBe('balanced');
});
});
+
+describe('compareEnvironments', () => {
+ const recorded = { platform: 'darwin', arch: 'arm64', cpuCount: 12, totalMemoryGb: 64, backendVersion: '1.2.3' };
+
+ it('reports current when every comparable field matches', () => {
+ expect(compareEnvironments(recorded, { ...recorded })).toEqual({ comparable: true, stale: false, changes: [] });
+ });
+
+ it('flags a RAM change — the case the badge exists for', () => {
+ const result = compareEnvironments(recorded, { ...recorded, totalMemoryGb: 128 });
+ expect(result.stale).toBe(true);
+ expect(result.changes).toEqual([{ field: 'totalMemoryGb', label: 'installed memory', from: 64, to: 128 }]);
+ expect(describeStaleness(result)).toContain('installed memory 64 → 128');
+ });
+
+ it('flags a backend update', () => {
+ const result = compareEnvironments(recorded, { ...recorded, backendVersion: '1.3.0' });
+ expect(result.stale).toBe(true);
+ expect(result.changes[0].field).toBe('backendVersion');
+ });
+
+ it('ignores sub-tolerance memory reporting jitter', () => {
+ expect(compareEnvironments(recorded, { ...recorded, totalMemoryGb: 64.3 }).stale).toBe(false);
+ });
+
+ it('never treats a field absent on either side as a change', () => {
+ // Records written before `backendVersion` was captured, and LM Studio (which
+ // exposes no version at all), must not read as "the backend changed".
+ const legacy = { platform: 'darwin', arch: 'arm64', cpuCount: 12, totalMemoryGb: 64 };
+ const result = compareEnvironments(legacy, { ...legacy, backendVersion: '1.3.0' });
+ expect(result.stale).toBe(false);
+ expect(result.comparable).toBe(true);
+ });
+
+ it('reports not-comparable rather than fresh when there is nothing to compare', () => {
+ // `comparable: false` is UNKNOWN. A caller must not render it as a clean bill
+ // of health — that is the absent-vs-empty sentinel rule.
+ expect(compareEnvironments(null, null)).toEqual({ comparable: false, stale: false, changes: [] });
+ expect(describeStaleness({ comparable: false, stale: false, changes: [] })).toBeNull();
+ });
+
+ it('does not compare transient available memory, which swings constantly', () => {
+ const result = compareEnvironments(
+ { ...recorded, availableMemoryGb: 40, memoryBudgetGb: 40 },
+ { ...recorded, availableMemoryGb: 3, memoryBudgetGb: 3 },
+ );
+ expect(result.stale).toBe(false);
+ });
+});
+
+describe('measuredFitVerdict', () => {
+ it('reads a comfortable fit when the footprint is well under the budget', () => {
+ expect(measuredFitVerdict({
+ verdict: 'fits', residentGb: 8, environment: { memoryBudgetGb: 40 },
+ })).toBe('comfortable');
+ });
+
+ it('reads tight past the same 60% threshold the estimate uses', () => {
+ expect(measuredFitVerdict({
+ verdict: 'fits', residentGb: 30, environment: { memoryBudgetGb: 40 },
+ })).toBe('tight');
+ });
+
+ it('says comfortable when it ran but the footprint is unmeasured (LM Studio)', () => {
+ expect(measuredFitVerdict({ verdict: 'fits', residentGb: null, environment: {} })).toBe('comfortable');
+ });
+
+ it('maps the failure verdicts onto the badge vocabulary', () => {
+ expect(measuredFitVerdict({ verdict: 'does-not-fit' })).toBe('too-large');
+ expect(measuredFitVerdict({ verdict: 'incompatible' })).toBe('incompatible');
+ });
+
+ it('says nothing at all for an unknown verdict or a missing assessment', () => {
+ // null ≠ 'unknown': 'unknown' is a badge the ESTIMATE also produces, so
+ // collapsing them would make an unmeasured model look measured.
+ expect(measuredFitVerdict({ verdict: 'unknown' })).toBeNull();
+ expect(measuredFitVerdict(null)).toBeNull();
+ });
+});
+
+describe('reconcileFit', () => {
+ const measurement = { fit: 'too-large', verdict: 'does-not-fit', assessedAt: '2026-01-02T00:00:00.000Z', stale: false };
+
+ it('leaves the estimate alone when nothing was measured', () => {
+ const result = reconcileFit('comfortable', null);
+ expect(result).toMatchObject({ fit: 'comfortable', fitSource: 'estimated', measuredFit: null, disagrees: false });
+ });
+
+ it('prefers the measurement and records the disagreement', () => {
+ const result = reconcileFit('comfortable', measurement);
+ expect(result).toMatchObject({
+ fit: 'too-large',
+ fitSource: 'measured',
+ estimatedFit: 'comfortable',
+ measuredFit: 'too-large',
+ disagrees: true,
+ verdict: 'does-not-fit',
+ });
+ });
+
+ it('does not flag a disagreement when both sides agree', () => {
+ expect(reconcileFit('too-large', measurement).disagrees).toBe(false);
+ });
+
+ it('keeps the estimate when the measurement is stale, but still reports it', () => {
+ const result = reconcileFit('comfortable', { ...measurement, stale: true, staleReason: 'RAM changed' });
+ expect(result.fit).toBe('comfortable');
+ expect(result.fitSource).toBe('estimated');
+ expect(result.measuredFit).toBe('too-large');
+ expect(result.stale).toBe(true);
+ expect(result.staleReason).toBe('RAM changed');
+ });
+
+ it('does not claim a disagreement against an unknown estimate', () => {
+ expect(reconcileFit('unknown', measurement).disagrees).toBe(false);
+ expect(reconcileFit(null, measurement)).toMatchObject({ fit: 'too-large', fitSource: 'measured', disagrees: false });
+ });
+});
diff --git a/server/lib/localModelHeuristics.js b/server/lib/localModelHeuristics.js
index 2aa923a6a1..24cfe8d058 100644
--- a/server/lib/localModelHeuristics.js
+++ b/server/lib/localModelHeuristics.js
@@ -228,29 +228,71 @@ function familyScore(id) {
return 1.0 - (idx / EDITORIAL_FAMILY_RANK.length) * 0.5; // [1.0 .. 0.5], best-first
}
+// How much a fresh, successful measurement is worth against the family/size
+// guess. Big enough that a model PROVEN to run here beats an equally-plausible
+// guess, small enough that it can't drag a poor editorial family (a coder model,
+// a 1B toy) past a strong one just for having been benchmarked.
+const MEASURED_FITS_BONUS = 0.12;
+
/**
* Recommend the best installed model for editorial feedback / line editing.
*
+ * The family/size heuristic is a guess from a model's name. When a MEASUREMENT
+ * exists for a model (`services/localModelAssessmentStore.js#getMeasuredFits`)
+ * it overrules the guess in the two places evidence is decisive:
+ *
+ * - a model measured `does-not-fit` / `incompatible` is dropped outright — the
+ * name says it would be a great editor, the machine says it cannot run it;
+ * - a model measured `fits` gets a bonus, so proven beats plausible.
+ *
+ * A STALE measurement (taken before a RAM upgrade or a backend update) does
+ * neither: it describes a machine that no longer exists, so the guess stands.
+ * An UNMEASURED model is untouched — unknown is not a mark against it.
+ *
* @param {Array<string|{id?:string,name?:string,params?:string,family?:string}>} models
- * @returns {{ id: string, reason: string }|null} null when nothing is suitable
+ * @param {{ measured?: Record<string, {verdict?:string, stale?:boolean}> }} [options]
+ * `measured` is keyed by model id; a missing key means "never measured".
+ * @returns {{ id: string, reason: string, evidence: 'measured'|'estimated',
+ * ruledOutByMeasurement: string[] }|null} null when nothing is suitable
*/
-export function recommendEditorialModel(models) {
- const candidates = (models || [])
+export function recommendEditorialModel(models, { measured = {} } = {}) {
+ const editorial = (models || [])
.map((m) => (typeof m === 'string' ? { id: m } : m))
.filter((m) => m?.id && !NON_EDITORIAL_RE.test(m.id));
+
+ // Trusted only when fresh — a stale reading is not evidence about this machine.
+ const trustedVerdict = (id) => {
+ const record = measured?.[id];
+ return record && !record.stale ? record.verdict : null;
+ };
+ const ruledOutByMeasurement = editorial
+ .filter((m) => ['does-not-fit', 'incompatible'].includes(trustedVerdict(m.id)))
+ .map((m) => m.id);
+ const ruledOut = new Set(ruledOutByMeasurement);
+
+ const candidates = editorial.filter((m) => !ruledOut.has(m.id));
if (!candidates.length) return null;
let best = null;
for (const m of candidates) {
const paramsB = parseParamsB(m);
- const score = familyScore(m.id) * 0.6 + sizeScore(paramsB) * 0.4;
- if (!best || score > best.score) best = { id: m.id, score, paramsB };
+ const fits = trustedVerdict(m.id) === 'fits';
+ const score = familyScore(m.id) * 0.6 + sizeScore(paramsB) * 0.4 + (fits ? MEASURED_FITS_BONUS : 0);
+ if (!best || score > best.score) best = { id: m.id, score, paramsB, fits };
}
if (!best) return null;
const sizeLabel = best.paramsB ? `${best.paramsB}B params` : 'size unknown';
+ const measuredNote = best.fits ? ' Measured on this machine: it runs here.' : '';
+ const ruledOutNote = ruledOutByMeasurement.length
+ ? ` ${ruledOutByMeasurement.length} otherwise-preferred model${ruledOutByMeasurement.length === 1 ? '' : 's'} ruled out by measurement (${ruledOutByMeasurement.join(', ')}).`
+ : '';
return {
id: best.id,
- reason: `Best installed fit for editorial review/editing (${sizeLabel}) — tight instruction-following and clean, constrained output for generating fixes.`,
+ reason: `Best installed fit for editorial review/editing (${sizeLabel}) — tight instruction-following and clean, constrained output for generating fixes.${measuredNote}${ruledOutNote}`,
+ // Says which kind of answer this is, so a caller never presents a guess with
+ // the confidence of a measurement.
+ evidence: best.fits ? 'measured' : 'estimated',
+ ruledOutByMeasurement,
};
}
diff --git a/server/lib/localModelHeuristics.test.js b/server/lib/localModelHeuristics.test.js
index c6570a9c3b..184bd1c5c4 100644
--- a/server/lib/localModelHeuristics.test.js
+++ b/server/lib/localModelHeuristics.test.js
@@ -251,5 +251,69 @@ describe('localModelHeuristics', () => {
expect(recommendEditorialModel(['nomic-embed-text:latest', 'mxbai-embed-large'])).toBeNull();
expect(recommendEditorialModel(null)).toBeNull();
});
+
+ describe('with measured evidence', () => {
+ const models = [
+ { id: 'qwen3.6:35b', params: '35B' },
+ { id: 'gemma4:9b', params: '9B' },
+ ];
+
+ it('drops a model measured not to run here, however good its name looks', () => {
+ const rec = recommendEditorialModel(models, {
+ measured: { 'qwen3.6:35b': { verdict: 'does-not-fit', stale: false } },
+ });
+ expect(rec?.id).toBe('gemma4:9b');
+ expect(rec.ruledOutByMeasurement).toEqual(['qwen3.6:35b']);
+ expect(rec.reason).toMatch(/ruled out by measurement/i);
+ });
+
+ it('drops a model the backend refused outright', () => {
+ const rec = recommendEditorialModel(models, {
+ measured: { 'qwen3.6:35b': { verdict: 'incompatible', stale: false } },
+ });
+ expect(rec?.id).toBe('gemma4:9b');
+ });
+
+ it('ignores a STALE measurement — it describes a machine that no longer exists', () => {
+ const rec = recommendEditorialModel(models, {
+ measured: { 'qwen3.6:35b': { verdict: 'does-not-fit', stale: true } },
+ });
+ expect(rec?.id).toBe('qwen3.6:35b');
+ expect(rec.evidence).toBe('estimated');
+ });
+
+ it('lets a proven model beat a merely-plausible one of similar standing', () => {
+ const close = [
+ { id: 'qwen3.6:14b', params: '14B' },
+ { id: 'llama3.3:14b', params: '14B' },
+ ];
+ // Without evidence the family ranking picks Qwen.
+ expect(recommendEditorialModel(close)?.id).toBe('qwen3.6:14b');
+ // A fresh "fits" on the runner-up is enough to flip it.
+ const rec = recommendEditorialModel(close, {
+ measured: { 'llama3.3:14b': { verdict: 'fits', stale: false } },
+ });
+ expect(rec?.id).toBe('llama3.3:14b');
+ expect(rec.evidence).toBe('measured');
+ expect(rec.reason).toMatch(/it runs here/i);
+ });
+
+ it('leaves an unmeasured model untouched — unknown is not a mark against it', () => {
+ const rec = recommendEditorialModel(models, { measured: {} });
+ expect(rec?.id).toBe('qwen3.6:35b');
+ expect(rec.evidence).toBe('estimated');
+ expect(rec.ruledOutByMeasurement).toEqual([]);
+ });
+
+ it('returns null when measurement rules out everything installed', () => {
+ const rec = recommendEditorialModel(models, {
+ measured: {
+ 'qwen3.6:35b': { verdict: 'does-not-fit', stale: false },
+ 'gemma4:9b': { verdict: 'incompatible', stale: false },
+ },
+ });
+ expect(rec).toBeNull();
+ });
+ });
});
});
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index 03faaf940f..2695b7729e 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -29,7 +29,8 @@ import {
} from '../lib/validation.js'
import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'
import { isAppleSilicon } from '../lib/platform.js'
-import { searchHuggingFaceModels, enrichCatalogWithVariants } from '../services/huggingFaceCatalog.js'
+import { searchHuggingFaceModels, enrichCatalogWithVariants, applyMeasuredFit } from '../services/huggingFaceCatalog.js'
+import { getMeasuredFits } from '../services/localModelAssessmentStore.js'
import {
getStatus, listModels, listVisionModels, listToolUseModels, installModel, deleteModel, switchBackend, migrateBackend, installBackend, upgradeBackend, controlOllamaServer,
describeInstallProgress
@@ -117,6 +118,10 @@ router.get('/catalog', asyncHandler(async (req, res) => {
if (variants === '1' || variants === 'true') {
await enrichCatalogWithVariants(models, { backend, systemMemoryBytes, installedIds: installedForVariants })
}
+ // Measured evidence overrules the size estimate wherever a model has actually
+ // been run here. Disk-only read — a catalog listing must never trigger a
+ // measurement (AI Provider Usage Policy).
+ applyMeasuredFit(models, { backend, measured: await getMeasuredFits(backend).catch(() => ({})) })
res.json({ backend, models, systemMemoryGb: Math.round(systemMemoryBytes / 1024 ** 3) })
}))
@@ -150,6 +155,7 @@ router.get('/huggingface-search', asyncHandler(async (req, res) => {
// the route boundary so the service stays deterministic.
const appleSilicon = isAppleSilicon()
const models = await searchHuggingFaceModels({ backend, query: q, category, limit, installedIds: installed, installedAudioRepos, systemMemoryBytes, appleSilicon })
+ applyMeasuredFit(models, { backend, measured: await getMeasuredFits(backend).catch(() => ({})) })
res.json({ backend, source: 'huggingface', models, systemMemoryGb: Math.round(systemMemoryBytes / 1024 ** 3), appleSilicon })
}))
@@ -435,7 +441,13 @@ router.get('/assessments', asyncHandler(async (req, res) => {
// client's abort signal is threaded through to stop mid-run on disconnect.
router.post('/assessments/run', asyncHandler(async (req, res) => {
const { backend, modelId, contextTokens } = validateRequest(localLlmAssessmentRunSchema, req.body)
- res.json(await runAssessment({ backend, modelId, contextTokens, signal: abortSignalFromResponse(res) }))
+ const io = req.app.get('io')
+ // Same `localLlm:progress` channel the pull/migrate paths use, so one banner
+ // renders every long local-LLM operation. The extra fields (`scope`, `backend`,
+ // `modelId`, `sampleIndex`/`sampleCount`) let a listener tell an assessment
+ // frame from a model pull streaming on the same event.
+ const onProgress = (frame) => io?.emit('localLlm:progress', frame)
+ res.json(await runAssessment({ backend, modelId, contextTokens, signal: abortSignalFromResponse(res), onProgress }))
}))
// POST /api/local-llm/assessments/delete — drop one stale measurement (e.g. after
diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.js
index c51ea35b14..e447a2dacb 100644
--- a/server/routes/localLlm.test.js
+++ b/server/routes/localLlm.test.js
@@ -4,7 +4,9 @@ import { request } from '../lib/testHelper.js';
import localLlmRoutes from './localLlm.js';
import { runLocalLlmTest, compareLocalLlmModels } from '../services/localLlmPlayground.js';
import { listModels, listVisionModels, listToolUseModels } from '../services/localLlm.js';
-import { enrichCatalogWithVariants } from '../services/huggingFaceCatalog.js';
+import { enrichCatalogWithVariants, applyMeasuredFit } from '../services/huggingFaceCatalog.js';
+import { getMeasuredFits } from '../services/localModelAssessmentStore.js';
+import { runAssessment } from '../services/localModelAssessments.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';
@@ -53,6 +55,19 @@ vi.mock('../services/lmStudioManager.js', () => ({
vi.mock('../services/huggingFaceCatalog.js', () => ({
searchHuggingFaceModels: vi.fn(async () => []),
enrichCatalogWithVariants: vi.fn(async (catalog) => catalog),
+ applyMeasuredFit: vi.fn((models) => models),
+}));
+
+// Measured assessments are folded into the catalog fit badge. Disk-only in
+// production; mocked here so a catalog listing test never touches the store.
+vi.mock('../services/localModelAssessmentStore.js', () => ({
+ getMeasuredFits: vi.fn(async () => ({})),
+}));
+
+vi.mock('../services/localModelAssessments.js', () => ({
+ getAssessmentReport: vi.fn(async () => ({ ranked: [], excluded: [] })),
+ runAssessment: vi.fn(async () => ({ verdict: 'fits' })),
+ deleteAssessment: vi.fn(async () => ({ deleted: true })),
}));
// /loaded reads getSettings() to honor a user's intentionally-disabled backends,
@@ -407,3 +422,45 @@ describe('local LLM capability routes', () => {
expect(tools.body.models.map((m) => m.id)).toEqual(['phi4-mini:latest']);
});
});
+
+describe('measured assessments wiring', () => {
+ beforeEach(() => { vi.clearAllMocks(); });
+
+ it('folds measured evidence into the catalog fit badge', async () => {
+ getMeasuredFits.mockResolvedValue({ 'example-model:14b': { fit: 'too-large', verdict: 'does-not-fit', stale: false } });
+ const res = await request(makeApp()).get('/api/local-llm/catalog?backend=ollama');
+
+ expect(res.status).toBe(200);
+ expect(getMeasuredFits).toHaveBeenCalledWith('ollama');
+ // The overlay runs against the SAME backend the listing was built for —
+ // an LM Studio measurement must never decorate an Ollama card.
+ expect(applyMeasuredFit).toHaveBeenCalledWith(res.body.models, {
+ backend: 'ollama',
+ measured: { 'example-model:14b': { fit: 'too-large', verdict: 'does-not-fit', stale: false } },
+ });
+ });
+
+ it('still serves the catalog when the assessments store cannot be read', async () => {
+ // A broken measurement file must not take the install picker down with it.
+ getMeasuredFits.mockRejectedValue(new Error('disk on fire'));
+ const res = await request(makeApp()).get('/api/local-llm/catalog?backend=ollama');
+ expect(res.status).toBe(200);
+ expect(applyMeasuredFit).toHaveBeenCalledWith(expect.anything(), { backend: 'ollama', measured: {} });
+ });
+
+ it('forwards assessment progress to the shared localLlm:progress socket event', async () => {
+ runAssessment.mockImplementation(async ({ onProgress }) => {
+ onProgress({ scope: 'assessment', backend: 'ollama', modelId: 'example-model:14b', event: 'start', sampleIndex: 1, sampleCount: 3 });
+ return { verdict: 'fits' };
+ });
+ const app = makeApp();
+ const res = await request(app)
+ .post('/api/local-llm/assessments/run')
+ .send({ backend: 'ollama', modelId: 'example-model:14b' });
+
+ expect(res.status).toBe(200);
+ expect(app.get('io').emit).toHaveBeenCalledWith('localLlm:progress', {
+ scope: 'assessment', backend: 'ollama', modelId: 'example-model:14b', event: 'start', sampleIndex: 1, sampleCount: 3,
+ });
+ });
+});
diff --git a/server/services/huggingFaceCatalog.js b/server/services/huggingFaceCatalog.js
index a576540eef..379e1de673 100644
--- a/server/services/huggingFaceCatalog.js
+++ b/server/services/huggingFaceCatalog.js
@@ -8,6 +8,7 @@ import { readCachedRepoModel, writeCachedRepoModel } from './huggingFaceRepoCach
import { LOCAL_LLM_CATEGORIES, isBackend } from '../lib/localLlmCatalog.js'
import { ENGINES } from './pipeline/musicGen.js'
import { fetchOllamaRegistryVariants } from './ollamaRegistryCatalog.js'
+import { reconcileFit } from '../lib/localModelAssessment.js'
const HF_API_BASE = 'https://huggingface.co/api/models'
const HF_TIMEOUT_MS = 12_000
@@ -512,7 +513,7 @@ function lmStudioParts(id) {
// the repo name, e.g. `mlx-community/Foo-4bit`), so it must still match an installed
// `mlx-community/Foo-4bit@4bit`. GGUF variants always carry a quant, so this never
// loosens per-quant GGUF matching; it only adds the missing repo-level case.
-function installIdInstalled(backend, installId, repository, installedIds) {
+function installIdInstalled(backend, installId, installedIds) {
if (backend === 'ollama') {
const target = normalizeOllamaInstalled(installId)
return installedIds.some((id) => normalizeOllamaInstalled(id) === target)
@@ -525,7 +526,7 @@ function installIdInstalled(backend, installId, repository, installedIds) {
}
function isInstalled(backend, result, installedIds) {
- return installIdInstalled(backend, result.id, result.repository, installedIds)
+ return installIdInstalled(backend, result.id, installedIds)
}
// ---- MLX (Apple Silicon) ----------------------------------------------------
@@ -612,7 +613,7 @@ function toMlxResult(model, requestedCategory, installedIds) {
score: scoreModel(model, category, null),
installable: true
}
- result.installed = installIdInstalled('lmstudio', repoId, repoId, installedIds)
+ result.installed = installIdInstalled('lmstudio', repoId, installedIds)
return result
}
@@ -898,7 +899,7 @@ function applyGgufVariants(result, model, { backend, usableBytes, installedIds,
if (variants.length === 0) return false
// Per-quant installed state — Ollama tracks each quant separately, so the card
// must gate Install on the *selected* variant, not one repo-wide flag.
- for (const v of variants) v.installed = installIdInstalled(backend, v.installId, result.repository, installedIds)
+ for (const v of variants) v.installed = installIdInstalled(backend, v.installId, installedIds)
applyChosenVariant(result, variants, { usableBytes, rewriteInstallId })
return true
}
@@ -922,7 +923,7 @@ function applyMlxVariant(result, model, { backend, usableBytes, installedIds })
sizeBytes: Number.isFinite(result.sizeBytes) ? result.sizeBytes : null,
size: formatBytes(result.sizeBytes) || result.size || (quant ? quant.toUpperCase() : 'MLX'),
fit: classifyFit(result.sizeBytes, usableBytes),
- installed: installIdInstalled(backend, result.id, result.repository, installedIds),
+ installed: installIdInstalled(backend, result.id, installedIds),
recommended: true
}
result.format = 'mlx'
@@ -1128,7 +1129,7 @@ async function applyOllamaRegistryVariants(entry, { usableBytes, installedIds })
.sort((a, b) => (b.sizeBytes || 0) - (a.sizeBytes || 0))
// Per-quant installed state — Ollama tracks each `<name>:<tag>` build separately,
// so the card gates Install on the selected variant (matches applyGgufVariants).
- for (const v of variants) v.installed = installIdInstalled('ollama', v.installId, entry.repository, installedIds)
+ for (const v of variants) v.installed = installIdInstalled('ollama', v.installId, installedIds)
// The discovered quant variants use exact `<name>:<tag>` ids that never include the
// default `:latest` alias, so an already-installed default build matches none of them.
// The card gates Install on the SELECTED variant's `installed` (LocalLlmTab uses
@@ -1229,3 +1230,51 @@ export async function enrichCatalogWithVariants(catalog, { backend, systemMemory
}
return catalog
}
+
+/**
+ * Fold MEASURED evidence into the estimated fit badge.
+ *
+ * `classifyFit` above answers from file size alone: weight bytes × 1.2 against a
+ * usable-memory budget. It never runs the model, so it cannot see a build that
+ * loads and then thrashes, nor one the backend refuses outright. Once an
+ * assessment exists for a model (`services/localModelAssessmentStore.js`) the
+ * measurement is the better answer, and where the two DISAGREE is the most
+ * useful thing this data can say — so both are kept on the variant.
+ *
+ * Matching reuses `installIdInstalled`, the exact normalization that decides the
+ * `installed` flag (Ollama's `hf.co/<repo>:<quant>` casing/`:latest`, LM Studio's
+ * quant-aware `<repo>@<quant>`). A separate matcher here would eventually drift
+ * and mark a variant "installed" while showing someone else's measurement.
+ *
+ * Mutates in place (the catalog builders already do) and returns `models`.
+ *
+ * @param {Array<object>} models catalog/search results
+ * @param {{ backend: string, measured?: Record<string, object> }} options
+ * `measured` comes from `getMeasuredFits(backend)`; `{}` means nothing has been
+ * measured, which leaves every estimate exactly as it was.
+ */
+export function applyMeasuredFit(models, { backend, measured } = {}) {
+ const list = Array.isArray(models) ? models : []
+ const measuredIds = measured ? Object.keys(measured) : []
+ if (!measuredIds.length) return list
+ // One id at a time so the backend-specific normalization decides the match.
+ const measurementFor = (installId) => {
+ if (!installId) return null
+ const hit = measuredIds.find((id) => installIdInstalled(backend, installId, [id]))
+ return hit ? measured[hit] : null
+ }
+ for (const model of list) {
+ // Audio/music entries install into the shared audio registry, not a local
+ // LLM backend, so a chat-model measurement can never describe them.
+ if (model?.category === 'audio') continue
+ const variants = Array.isArray(model?.variants) ? model.variants : []
+ for (const variant of variants) {
+ Object.assign(variant, reconcileFit(variant.fit, measurementFor(variant.installId)))
+ }
+ // Entries with no variant list (curated results without `?variants=1`) carry
+ // no estimated fit at all — a measurement is then the ONLY thing that can
+ // say anything, so surface it rather than leaving the card blank.
+ if (!variants.length) Object.assign(model, reconcileFit(model?.fit ?? null, measurementFor(model?.id)))
+ }
+ return list
+}
diff --git a/server/services/huggingFaceCatalog.test.js b/server/services/huggingFaceCatalog.test.js
index ef96ed527e..85d26938db 100644
--- a/server/services/huggingFaceCatalog.test.js
+++ b/server/services/huggingFaceCatalog.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
-import { searchHuggingFaceModels, enrichCatalogWithVariants } from './huggingFaceCatalog.js'
+import { searchHuggingFaceModels, enrichCatalogWithVariants, applyMeasuredFit } from './huggingFaceCatalog.js'
import { __resetOllamaRegistryCache } from './ollamaRegistryCatalog.js'
// The disk cache resolves its file from the REAL PATHS.data, and fetchRepoModel
@@ -1249,3 +1249,84 @@ describe('huggingFaceCatalog', () => {
})
})
})
+
+describe('applyMeasuredFit', () => {
+ // Ollama's HF install ids and the assessment's recorded model id are the same
+ // string modulo case and a `:latest` tag, so matching must go through the same
+ // normalization that decides `installed`.
+ const ollamaModel = () => ({
+ id: 'hf.co/example-org/Example-14B-GGUF:Q4_K_M',
+ variants: [
+ { quant: 'Q4_K_M', installId: 'hf.co/example-org/Example-14B-GGUF:Q4_K_M', fit: 'comfortable' },
+ { quant: 'Q8_0', installId: 'hf.co/example-org/Example-14B-GGUF:Q8_0', fit: 'tight' }
+ ]
+ })
+
+ it('replaces the estimate with the measurement and keeps the disagreement', () => {
+ const models = [ollamaModel()]
+ applyMeasuredFit(models, {
+ backend: 'ollama',
+ measured: {
+ 'hf.co/example-org/example-14b-gguf:Q4_K_M': {
+ fit: 'too-large', verdict: 'does-not-fit', assessedAt: '2026-01-02T00:00:00.000Z', stale: false
+ }
+ }
+ })
+ expect(models[0].variants[0]).toMatchObject({
+ fit: 'too-large', fitSource: 'measured', estimatedFit: 'comfortable', disagrees: true
+ })
+ // The unmeasured sibling quant keeps its estimate untouched.
+ expect(models[0].variants[1]).toMatchObject({ fit: 'tight', fitSource: 'estimated', measuredFit: null })
+ })
+
+ it('leaves every estimate alone when nothing has been measured', () => {
+ const models = [ollamaModel()]
+ applyMeasuredFit(models, { backend: 'ollama', measured: {} })
+ expect(models[0].variants.map((v) => v.fit)).toEqual(['comfortable', 'tight'])
+ expect(models[0].variants[0].fitSource).toBeUndefined()
+ })
+
+ it('keeps the estimate when the measurement is stale, but still reports it', () => {
+ const models = [ollamaModel()]
+ applyMeasuredFit(models, {
+ backend: 'ollama',
+ measured: {
+ 'hf.co/example-org/Example-14B-GGUF:Q4_K_M': { fit: 'too-large', verdict: 'does-not-fit', stale: true, staleReason: 'installed memory 32 → 64' }
+ }
+ })
+ expect(models[0].variants[0]).toMatchObject({ fit: 'comfortable', fitSource: 'estimated', measuredFit: 'too-large', stale: true })
+ })
+
+ it('matches LM Studio ids quant-aware, the same way `installed` does', () => {
+ const models = [{
+ id: 'example-org/Example-14B-GGUF',
+ variants: [{ quant: 'Q4_K_M', installId: 'example-org/Example-14B-GGUF@Q4_K_M', fit: 'comfortable' }]
+ }]
+ applyMeasuredFit(models, {
+ backend: 'lmstudio',
+ measured: { 'example-org/Example-14B-GGUF': { fit: 'tight', verdict: 'fits', stale: false } }
+ })
+ expect(models[0].variants[0]).toMatchObject({ fit: 'tight', fitSource: 'measured' })
+ })
+
+ it('annotates a variant-less entry, where the measurement is the only evidence there is', () => {
+ const models = [{ id: 'example-model:14b' }]
+ applyMeasuredFit(models, {
+ backend: 'ollama',
+ measured: { 'example-model:14b': { fit: 'comfortable', verdict: 'fits', stale: false } }
+ })
+ expect(models[0]).toMatchObject({ fit: 'comfortable', fitSource: 'measured', estimatedFit: null, disagrees: false })
+ })
+
+ it('never applies a chat-model measurement to an audio entry', () => {
+ // Audio/music models install into the shared audio registry, not a local LLM
+ // backend — a same-named chat measurement could not describe them.
+ const models = [{ id: 'example-model:14b', category: 'audio', fit: 'comfortable' }]
+ applyMeasuredFit(models, {
+ backend: 'ollama',
+ measured: { 'example-model:14b': { fit: 'too-large', verdict: 'does-not-fit', stale: false } }
+ })
+ expect(models[0].fit).toBe('comfortable')
+ expect(models[0].fitSource).toBeUndefined()
+ })
+})
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index 93a9b3536c..bfaf5c2164 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -32,6 +32,10 @@ import { compareSemver } from '../lib/versionUtils.js'
import { isBackend, mapModelToBackend, getOllamaImportSpec } from '../lib/localLlmCatalog.js'
import { sanitizeOllamaName } from '../lib/localLlmDisk.js'
import { recommendEditorialModel, isVisionModel, isVisionCapableCliProvider, isToolUseModel } from '../lib/localModelHeuristics.js'
+// Disk-only read of the measured assessments (`localModelAssessmentStore.js` has no
+// path to a provider, so this cannot turn a status poll into an LLM call), and
+// no import cycle: the store deliberately does not import this module.
+import { getMeasuredFits } from './localModelAssessmentStore.js'
import { commandExists } from '../lib/commandExists.js'
import * as ollamaManager from './ollamaManager.js'
import * as lmStudioManager from './lmStudioManager.js'
@@ -688,7 +692,7 @@ export async function listModels(backend, forceRefresh = false) {
* Combined status for both backends plus the active marker.
*/
export async function getStatus() {
- const [ollamaStatus, ollamaCli, lmStudioStatus, lmsCli, lmStudioModels, latestOllamaVersion, settings] = await Promise.all([
+ const [ollamaStatus, ollamaCli, lmStudioStatus, lmsCli, lmStudioModels, latestOllamaVersion, settings, measuredOllama, measuredLmStudio] = await Promise.all([
ollamaManager.getStatus(true),
commandExists('ollama', ['--version']),
lmStudioManager.getStatus(),
@@ -697,11 +701,16 @@ export async function getStatus() {
listModels('lmstudio', true).catch(() => []),
// Cached (6h) — never blocks the steady-state UI on a GitHub round-trip.
getLatestOllamaVersion().catch(() => null),
- getSettings()
+ getSettings(),
+ // Measured evidence, so the editorial pick can prefer a model that PROVABLY
+ // runs here over one whose name merely looks right. Disk-only; a status poll
+ // must never trigger a measurement.
+ getMeasuredFits('ollama').catch(() => ({})),
+ getMeasuredFits('lmstudio').catch(() => ({}))
])
const ollamaModels = normalizeModels('ollama', ollamaStatus.models)
- const lmStudioRecommendation = recommendEditorialModel(lmStudioModels)
+ const lmStudioRecommendation = recommendEditorialModel(lmStudioModels, { measured: measuredLmStudio })
// An update is "available" only when we know BOTH the installed version (Ollama
// must be running for /api/version to answer) and the latest, and latest is
// newer. canUpgrade (canAutoUpgrade) gates the in-app updater to the platforms
@@ -724,7 +733,7 @@ export async function getStatus() {
models: ollamaModels,
// Best installed model for editorial review/editing, surfaced so the
// manuscript editor can suggest it (and warn against the embedding model).
- recommendations: { editorial: recommendEditorialModel(ollamaModels) },
+ recommendations: { editorial: recommendEditorialModel(ollamaModels, { measured: measuredOllama }) },
canControl: ollamaCli || ollamaStatus.available,
service: ollamaStatus.service,
canAutoInstall: canAutoInstall('ollama'),
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index c7c46ed24c..23c3663949 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -10,6 +10,14 @@ import { pinPlatform } from '../lib/testHelper.js';
// service captures ENV_PATH = join(PATHS.root, '.env') at import time, so each
// test sets `state.root` to a fresh temp dir and re-imports under resetModules.
const state = vi.hoisted(() => ({ root: '' }));
+// Measured assessments feed the editorial recommendation (a model measured NOT
+// to run here must never be recommended). The store is disk-only, so it is
+// mocked here to a controllable map rather than re-rooting a data dir; keyed by
+// model id, exactly as `getMeasuredFits` returns it.
+const measured = vi.hoisted(() => ({ ollama: {}, lmstudio: {} }));
+vi.mock('./localModelAssessmentStore.js', () => ({
+ getMeasuredFits: async (backend) => measured[backend] || {},
+}));
vi.mock('../lib/fileUtils.js', async () => {
const fsMod = await import('fs');
return {
@@ -802,4 +810,30 @@ describe('localLlm', () => {
expect(s.ollama.updateAvailable).toBe(false);
});
});
+
+ describe('getStatus editorial recommendation with measured evidence', () => {
+ const installed = [
+ { id: 'qwen3.6:35b', name: 'qwen3.6:35b', params: '35B' },
+ { id: 'gemma4:9b', name: 'gemma4:9b', params: '9B' },
+ ];
+ beforeEach(() => {
+ measured.ollama = {};
+ measured.lmstudio = {};
+ mocks.ollama.getStatus.mockResolvedValue({ available: true, baseUrl: 'x', version: '0.5.7', modelCount: 2, models: installed });
+ });
+ afterEach(() => { measured.ollama = {}; measured.lmstudio = {}; });
+
+ it('recommends the heuristic pick when nothing has been measured', async () => {
+ const s = await svc.getStatus();
+ expect(s.ollama.recommendations.editorial.id).toBe('qwen3.6:35b');
+ expect(s.ollama.recommendations.editorial.evidence).toBe('estimated');
+ });
+
+ it('refuses to recommend a model measured NOT to run on this machine', async () => {
+ measured.ollama = { 'qwen3.6:35b': { verdict: 'does-not-fit', stale: false } };
+ const s = await svc.getStatus();
+ expect(s.ollama.recommendations.editorial.id).toBe('gemma4:9b');
+ expect(s.ollama.recommendations.editorial.ruledOutByMeasurement).toEqual(['qwen3.6:35b']);
+ });
+ });
});
diff --git a/server/services/localModelAssessmentStore.js b/server/services/localModelAssessmentStore.js
new file mode 100644
index 0000000000..e09a2307b3
--- /dev/null
+++ b/server/services/localModelAssessmentStore.js
@@ -0,0 +1,245 @@
+/**
+ * Measured local-model assessments — the durable store and the environment the
+ * measurements are only valid for.
+ *
+ * Split out of `localModelAssessments.js` so the READ side has no path to a
+ * provider. Two reasons that matters:
+ *
+ * 1. **AI Provider Usage Policy** (root CLAUDE.md). Everything here touches
+ * disk (plus, on the run path, one cheap version probe). Nothing in this
+ * file can reach an LLM, so importing it from a status/catalog read is safe
+ * by construction rather than by review.
+ * 2. **No import cycle.** `localModelAssessments.js` imports `localLlm.js`
+ * (for the installed-model list), so `localLlm.js` could not import the
+ * store back from there. It imports this module instead.
+ *
+ * ## Storage (docs/STORAGE.md)
+ *
+ * `file-primary`, **intentionally machine-local — never federated.** An
+ * assessment is a statement about THIS machine's hardware; a peer's copy would
+ * be actively misleading (a peer's 8 GB laptop must not inherit a 128 GB box's
+ * "fits" verdict). No sync cursor, no tombstone, no schema-version entry.
+ *
+ * ## Privacy
+ *
+ * The recorded environment is deliberately coarse — platform, arch, CPU count,
+ * total/available memory, backend version. It never captures a hostname, a
+ * username, a path, or any other machine identity, because assessments are
+ * user-visible and end up in bug reports.
+ */
+
+import { join } from 'path';
+import { rename } from 'fs/promises';
+import os from 'os';
+import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';
+import { getAvailableMemoryGb } from '../lib/localMemory.js';
+import { compareEnvironments, describeStaleness, measuredFitVerdict } from '../lib/localModelAssessment.js';
+import { getVersion as getOllamaVersion } from './ollamaManager.js';
+
+// Resolved lazily, not at import time: `PATHS.data` is patched by suites that
+// re-root the data dir, and a module-level `join()` would capture (or crash on)
+// whatever the value happened to be the moment this module was first imported.
+const assessmentsDir = () => join(PATHS.data, 'local-llm');
+const assessmentsFile = () => join(assessmentsDir(), 'assessments.json');
+
+// Storage-layout version for the on-disk file. Bump only when the persisted
+// shape changes in a way a reader must branch on.
+const STORE_SCHEMA_VERSION = 1;
+
+const GB = 2 ** 30;
+
+// ---- environment ------------------------------------------------------------
+
+/**
+ * The machine facts that are free to read: no subprocess, no network. Used on
+ * every READ path (catalog badges, status) to decide whether a stored
+ * measurement still describes this machine.
+ */
+export function captureDurableEnvironment() {
+ return {
+ platform: os.platform(),
+ arch: os.arch(),
+ cpuCount: os.cpus()?.length ?? null,
+ totalMemoryGb: Number((os.totalmem() / GB).toFixed(1)),
+ };
+}
+
+/**
+ * Coarse description of the machine a measurement was taken on. Deliberately
+ * carries NO machine identity (see the privacy note at the top of this file).
+ *
+ * Costs a `vm_stat` subprocess (macOS) and, for Ollama, one loopback HTTP GET —
+ * so this is the RUN-path capture. Read paths use `captureDurableEnvironment()`
+ * plus, where they can afford it, `captureLiveEnvironments()`.
+ *
+ * @param {{ backend?: string }} [options]
+ */
+export async function captureEnvironment({ backend } = {}) {
+ const totalGb = os.totalmem() / GB;
+ // `null` (not `0`) when the probe fails — an unknown budget must not read as
+ // "no memory available", which would make every model look like it fits
+ // nothing.
+ const availableGb = await getAvailableMemoryGb().catch(() => null);
+ return {
+ ...captureDurableEnvironment(),
+ totalMemoryGb: Number(totalGb.toFixed(1)),
+ availableMemoryGb: Number.isFinite(availableGb) ? Number(availableGb.toFixed(1)) : null,
+ // The budget the fit verdict is scored against: never more than what is
+ // actually free right now, never more than the box has.
+ memoryBudgetGb: Number.isFinite(availableGb)
+ ? Number(Math.min(totalGb, availableGb).toFixed(1))
+ : null,
+ // `null` = not recorded, which is the honest answer for LM Studio (it
+ // exposes no version endpoint) and for a stopped Ollama. It must never
+ // default to a string, or a later comparison would read a fabricated
+ // "unchanged".
+ backendVersion: backend === 'ollama' ? await getOllamaVersion().catch(() => null) : null,
+ };
+}
+
+/**
+ * Live environment for a STALENESS comparison, including the backend version.
+ * Costs one loopback GET for Ollama, so it belongs on paths that already talk to
+ * the backend (the assessments report) — not on the catalog badge path.
+ *
+ * @param {{ backends?: string[] }} [options]
+ * @returns {Promise<Record<string, object>>} keyed by backend
+ */
+export async function captureLiveEnvironments({ backends = ['ollama', 'lmstudio'] } = {}) {
+ const durable = captureDurableEnvironment();
+ const entries = await Promise.all(backends.map(async (backend) => [
+ backend,
+ { ...durable, backendVersion: backend === 'ollama' ? await getOllamaVersion().catch(() => null) : null },
+ ]));
+ return Object.fromEntries(entries);
+}
+
+// ---- store ------------------------------------------------------------------
+
+export const assessmentKey = (backend, modelId) => `${backend}:${modelId}`;
+
+// Move an unparseable store aside so a fresh one can be written without losing
+// whatever the old file held. Best-effort: if the rename fails there is nothing
+// further to preserve, and refusing the write outright would leave assessments
+// permanently unusable.
+async function quarantineStore(reason) {
+ const parked = `${assessmentsFile()}.corrupt-${Date.now()}`;
+ const moved = await rename(assessmentsFile(), parked).then(() => true).catch(() => false);
+ console.error(`❌ Local LLM: ${reason} — ${moved ? `parked the old file as ${parked.split('/').pop()}` : 'could not park the old file'}`);
+}
+
+export async function loadStore() {
+ const raw = await tryReadFile(assessmentsFile());
+ // Never read = an empty store, not an error: the file simply doesn't exist
+ // until the first assessment runs.
+ if (raw == null) return { schemaVersion: STORE_SCHEMA_VERSION, assessments: [], readError: null };
+ const parsed = safeJSONParse(raw, null);
+ if (!parsed || !Array.isArray(parsed.assessments)) {
+ // Present but unparseable is NOT an empty store — say so rather than
+ // silently reporting "nothing assessed" and letting a re-run overwrite it.
+ return { schemaVersion: STORE_SCHEMA_VERSION, assessments: [], readError: 'assessments file is unreadable or malformed' };
+ }
+ return { schemaVersion: parsed.schemaVersion ?? STORE_SCHEMA_VERSION, assessments: parsed.assessments, readError: null };
+}
+
+/**
+ * Read the persisted assessments. Disk only — never calls a provider, so this is
+ * safe from boot, a poll, or any read path.
+ *
+ * @returns {Promise<Array<object>>} `[]` means "no assessments recorded", which
+ * is a real, measured-empty answer — distinct from a read failure, which is
+ * surfaced by `loadStore().readError`.
+ */
+export async function loadAssessments() {
+ return (await loadStore()).assessments;
+}
+
+export async function saveAssessment(assessment) {
+ const { assessments, readError } = await loadStore();
+ // An unreadable store reports zero assessments, and writing on top of that
+ // would replace every prior measurement with this one record — a read failure
+ // silently destroying data the user spent minutes of compute on. Quarantine
+ // the unreadable file instead: nothing is lost, and the feature keeps working
+ // rather than wedging on a file the user has no way to repair from the UI.
+ if (readError) await quarantineStore(readError);
+ const key = assessmentKey(assessment.backend, assessment.modelId);
+ // One record per (backend, model): the newest measurement supersedes the old
+ // one. History is not kept — a stale reading from a different memory state is
+ // worse than no reading, and the run is cheap to repeat.
+ const next = assessments.filter((a) => assessmentKey(a?.backend, a?.modelId) !== key);
+ next.push(assessment);
+ await ensureDir(assessmentsDir());
+ await atomicWrite(assessmentsFile(), { schemaVersion: STORE_SCHEMA_VERSION, assessments: next });
+ return assessment;
+}
+
+/**
+ * Drop one recorded assessment. Returns whether a record was actually removed,
+ * so the caller can 404 rather than reporting a phantom success.
+ */
+export async function deleteAssessment(backend, modelId) {
+ const { assessments, readError } = await loadStore();
+ // Same hazard as saveAssessment: rewriting from an empty in-memory list would
+ // wipe the file. A delete against an unreadable store has nothing to remove.
+ if (readError) return { deleted: false };
+ const key = assessmentKey(backend, modelId);
+ const next = assessments.filter((a) => assessmentKey(a?.backend, a?.modelId) !== key);
+ if (next.length === assessments.length) return { deleted: false };
+ await ensureDir(assessmentsDir());
+ await atomicWrite(assessmentsFile(), { schemaVersion: STORE_SCHEMA_VERSION, assessments: next });
+ console.log(`🧹 Local LLM: dropped assessment for ${backend}/${modelId}`);
+ return { deleted: true };
+}
+
+// ---- measured evidence for the ESTIMATE-driven surfaces ---------------------
+
+/**
+ * Annotate one assessment with how well its recorded environment still matches
+ * the machine as it is now.
+ *
+ * @param {object} assessment
+ * @param {object|null} liveEnvironment
+ */
+export function withStaleness(assessment, liveEnvironment) {
+ const staleness = compareEnvironments(assessment?.environment, liveEnvironment);
+ return {
+ ...assessment,
+ staleness: { ...staleness, description: describeStaleness(staleness) },
+ };
+}
+
+/**
+ * Compact measured-fit records the catalog badge and the editorial
+ * recommendation fold in, keyed by model id for one backend.
+ *
+ * Disk only, and the staleness check uses the FREE durable environment (no
+ * subprocess, no HTTP) because this runs on the catalog path, which is hit on
+ * every debounced keystroke. A backend-version change therefore doesn't register
+ * here — it does on the assessments report, which can afford the probe.
+ *
+ * @param {string} backend
+ * @returns {Promise<Record<string, {fit:string|null, verdict:string, assessedAt:string|null, stale:boolean, staleReason:string|null, meanCharsPerSecond:number|null, residentGb:number|null}>>}
+ */
+export async function getMeasuredFits(backend) {
+ const { assessments } = await loadStore();
+ const live = captureDurableEnvironment();
+ const out = {};
+ for (const assessment of assessments) {
+ if (assessment?.backend !== backend || !assessment?.modelId) continue;
+ const staleness = compareEnvironments(assessment.environment, live);
+ out[assessment.modelId] = {
+ fit: measuredFitVerdict(assessment),
+ verdict: assessment.verdict || 'unknown',
+ assessedAt: assessment.assessedAt || null,
+ stale: staleness.stale,
+ staleReason: describeStaleness(staleness),
+ // `null` = never measured on both of these; a consumer rendering them must
+ // say "not measured" rather than showing a zero.
+ meanCharsPerSecond: Number.isFinite(assessment.performance?.meanCharsPerSecond)
+ ? assessment.performance.meanCharsPerSecond
+ : null,
+ residentGb: Number.isFinite(assessment.residentGb) ? assessment.residentGb : null,
+ };
+ }
+ return out;
+}
diff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.js
index f673dac369..1b8162d17d 100644
--- a/server/services/localModelAssessments.js
+++ b/server/services/localModelAssessments.js
@@ -31,26 +31,15 @@
* background sweep. Do not add one: a fresh install must be silent on the LLM
* front until the user asks.
*
- * ## Privacy
+ * ## Where the pieces live
*
- * The recorded environment is deliberately coarse — platform, arch, CPU count,
- * total/available memory, backend name. It never captures a hostname, a
- * username, a path, or any other machine identity, because assessments are
- * user-visible and end up in bug reports.
- *
- * ## Storage (docs/STORAGE.md)
- *
- * `file-primary`, **intentionally machine-local — never federated.** An
- * assessment is a statement about THIS machine's hardware; a peer's copy would
- * be actively misleading (a peer's 8 GB laptop must not inherit a 128 GB box's
- * "fits" verdict). No sync cursor, no tombstone, no schema-version entry.
+ * The durable store, the environment capture, and the privacy/storage contract
+ * moved to `localModelAssessmentStore.js` — that module has no path to a
+ * provider, so read-only consumers (the catalog fit badge, `localLlm.getStatus`)
+ * can import it without importing this one, and without an import cycle through
+ * `localLlm.js`.
*/
-import { join } from 'path';
-import { rename } from 'fs/promises';
-import os from 'os';
-import { PATHS, atomicWrite, ensureDir, tryReadFile, safeJSONParse } from '../lib/fileUtils.js';
-import { getAvailableMemoryGb } from '../lib/localMemory.js';
import {
ASSESSMENT_INTENTS,
classifyFitVerdict,
@@ -58,6 +47,16 @@ import {
rankByIntent,
summarizePerformance,
} from '../lib/localModelAssessment.js';
+import {
+ assessmentKey,
+ captureEnvironment,
+ captureLiveEnvironments,
+ deleteAssessment,
+ loadAssessments,
+ loadStore,
+ saveAssessment,
+ withStaleness,
+} from './localModelAssessmentStore.js';
import { runLocalLlmTest } from './localLlmPlayground.js';
import { listModels } from './localLlm.js';
import {
@@ -66,12 +65,9 @@ import {
} from './ollamaManager.js';
import { getLastListError as getLmStudioListError } from './lmStudioManager.js';
-const ASSESSMENTS_DIR = join(PATHS.data, 'local-llm');
-const ASSESSMENTS_FILE = join(ASSESSMENTS_DIR, 'assessments.json');
-
-// Storage-layout version for the on-disk file. Bump only when the persisted
-// shape changes in a way a reader must branch on.
-const STORE_SCHEMA_VERSION = 1;
+// Re-exported so the store split stays an implementation detail for callers that
+// only ever wanted "the assessments feature".
+export { captureEnvironment, deleteAssessment, loadAssessments };
const GB = 2 ** 30;
@@ -122,107 +118,6 @@ export function buildSamplePrompt(contextTokens) {
return `${filler}\nIgnoring every reference item above, what is 2 + 2? Answer with the number only.`;
}
-/**
- * Coarse description of the machine the measurement was taken on. Deliberately
- * carries NO machine identity (see the privacy note at the top of this file).
- */
-export async function captureEnvironment() {
- const totalGb = os.totalmem() / GB;
- // `null` (not `0`) when the probe fails — an unknown budget must not read as
- // "no memory available", which would make every model look like it fits
- // nothing.
- const availableGb = await getAvailableMemoryGb().catch(() => null);
- return {
- platform: os.platform(),
- arch: os.arch(),
- cpuCount: os.cpus()?.length ?? null,
- totalMemoryGb: Number(totalGb.toFixed(1)),
- availableMemoryGb: Number.isFinite(availableGb) ? Number(availableGb.toFixed(1)) : null,
- // The budget the fit verdict is scored against: never more than what is
- // actually free right now, never more than the box has.
- memoryBudgetGb: Number.isFinite(availableGb)
- ? Number(Math.min(totalGb, availableGb).toFixed(1))
- : null,
- };
-}
-
-// ---- store ------------------------------------------------------------------
-
-/**
- * Read the persisted assessments. Disk only — never calls a provider, so this is
- * safe from boot, a poll, or any read path.
- *
- * @returns {Promise<Array<object>>} `[]` means "no assessments recorded", which
- * is a real, measured-empty answer — distinct from a read failure, which is
- * surfaced by `loadStore().readError`.
- */
-export async function loadAssessments() {
- return (await loadStore()).assessments;
-}
-
-// Move an unparseable store aside so a fresh one can be written without losing
-// whatever the old file held. Best-effort: if the rename fails there is nothing
-// further to preserve, and refusing the write outright would leave assessments
-// permanently unusable.
-async function quarantineStore(reason) {
- const parked = `${ASSESSMENTS_FILE}.corrupt-${Date.now()}`;
- const moved = await rename(ASSESSMENTS_FILE, parked).then(() => true).catch(() => false);
- console.error(`❌ Local LLM: ${reason} — ${moved ? `parked the old file as ${parked.split('/').pop()}` : 'could not park the old file'}`);
-}
-
-async function loadStore() {
- const raw = await tryReadFile(ASSESSMENTS_FILE);
- // Never read = an empty store, not an error: the file simply doesn't exist
- // until the first assessment runs.
- if (raw == null) return { schemaVersion: STORE_SCHEMA_VERSION, assessments: [], readError: null };
- const parsed = safeJSONParse(raw, null);
- if (!parsed || !Array.isArray(parsed.assessments)) {
- // Present but unparseable is NOT an empty store — say so rather than
- // silently reporting "nothing assessed" and letting a re-run overwrite it.
- return { schemaVersion: STORE_SCHEMA_VERSION, assessments: [], readError: 'assessments file is unreadable or malformed' };
- }
- return { schemaVersion: parsed.schemaVersion ?? STORE_SCHEMA_VERSION, assessments: parsed.assessments, readError: null };
-}
-
-const assessmentKey = (backend, modelId) => `${backend}:${modelId}`;
-
-async function saveAssessment(assessment) {
- const { assessments, readError } = await loadStore();
- // An unreadable store reports zero assessments, and writing on top of that
- // would replace every prior measurement with this one record — a read failure
- // silently destroying data the user spent minutes of compute on. Quarantine
- // the unreadable file instead: nothing is lost, and the feature keeps working
- // rather than wedging on a file the user has no way to repair from the UI.
- if (readError) await quarantineStore(readError);
- const key = assessmentKey(assessment.backend, assessment.modelId);
- // One record per (backend, model): the newest measurement supersedes the old
- // one. History is not kept — a stale reading from a different memory state is
- // worse than no reading, and the run is cheap to repeat.
- const next = assessments.filter((a) => assessmentKey(a?.backend, a?.modelId) !== key);
- next.push(assessment);
- await ensureDir(ASSESSMENTS_DIR);
- await atomicWrite(ASSESSMENTS_FILE, { schemaVersion: STORE_SCHEMA_VERSION, assessments: next });
- return assessment;
-}
-
-/**
- * Drop one recorded assessment. Returns whether a record was actually removed,
- * so the caller can 404 rather than reporting a phantom success.
- */
-export async function deleteAssessment(backend, modelId) {
- const { assessments, readError } = await loadStore();
- // Same hazard as saveAssessment: rewriting from an empty in-memory list would
- // wipe the file. A delete against an unreadable store has nothing to remove.
- if (readError) return { deleted: false };
- const key = assessmentKey(backend, modelId);
- const next = assessments.filter((a) => assessmentKey(a?.backend, a?.modelId) !== key);
- if (next.length === assessments.length) return { deleted: false };
- await ensureDir(ASSESSMENTS_DIR);
- await atomicWrite(ASSESSMENTS_FILE, { schemaVersion: STORE_SCHEMA_VERSION, assessments: next });
- console.log(`🧹 Local LLM: dropped assessment for ${backend}/${modelId}`);
- return { deleted: true };
-}
-
// ---- measurement ------------------------------------------------------------
/**
@@ -287,19 +182,45 @@ function describeVerdict(verdict, samples) {
* @param {string} options.modelId
* @param {number[]} [options.contextTokens] nominal context sizes to sample
* @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
+ * these to the `localLlm:progress` socket event the pull/migrate paths already
+ * use. Frames carry `backend` + `modelId` so a listener can tell a frame from
+ * 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, signal } = {}) {
+export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_CONTEXT_TOKENS, signal, onProgress } = {}) {
const contexts = [...new Set(contextTokens)].filter((n) => Number.isFinite(n) && n > 0).sort((a, b) => a - b);
- const environment = await captureEnvironment();
+ // 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
+ // never abort a measurement the user is paying minutes for.
+ const emit = (frame) => {
+ if (typeof onProgress !== 'function') return;
+ try { onProgress({ scope: 'assessment', backend, modelId, ...frame }); }
+ catch (err) { console.error(`❌ Local LLM: assessment progress listener failed: ${err.message}`); }
+ };
+ const environment = await captureEnvironment({ backend });
const installed = await listModels(backend).catch(() => []);
const card = installed.find((m) => m?.id === modelId) || null;
console.log(`📏 Local LLM: assessing ${backend}/${modelId} across ${contexts.length} context sizes`);
+ emit({
+ event: 'start',
+ sampleIndex: 0,
+ sampleCount: contexts.length,
+ message: `Measuring ${modelId} — ${contexts.length} generation${contexts.length === 1 ? '' : 's'}…`,
+ });
const samples = [];
for (const context of contexts) {
if (signal?.aborted) break;
+ emit({
+ event: 'start',
+ sampleIndex: samples.length,
+ sampleCount: contexts.length,
+ contextTokens: context,
+ message: `${modelId}: sample ${samples.length + 1}/${contexts.length} at ${context.toLocaleString('en-US')} tokens of context…`,
+ });
// runLocalLlmTest resolves (never throws) for in-stream failures, but can
// still throw before the stream opens — an unconfigured provider. Catch that
// into the same result shape so one bad backend records a failed sample
@@ -317,6 +238,19 @@ export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_
const sample = toSample(context, result);
samples.push(sample);
+ // Report what the sample actually measured, not just that it finished — a
+ // multi-minute run should show throughput accumulating rather than a bar
+ // that only moves between contexts.
+ emit({
+ event: 'start',
+ sampleIndex: samples.length,
+ sampleCount: contexts.length,
+ contextTokens: context,
+ sample,
+ message: sample.ok
+ ? `${modelId}: ${context.toLocaleString('en-US')} tokens → ${sample.charsPerSecond ?? '?'} chars/s`
+ : `${modelId}: ${context.toLocaleString('en-US')} tokens → failed (${sample.error})`,
+ });
if (!sample.ok && classifySampleFailure(sample)) break;
}
@@ -344,10 +278,18 @@ export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_
// leave the store untouched.
if (signal?.aborted) {
console.log(`📏 Local LLM: ${backend}/${modelId} assessment cancelled — not recorded`);
+ // A terminal frame either way, or a listener's banner sits on the last
+ // sample forever. `cancelled` is NOT `error` — nothing failed.
+ emit({ event: 'complete', cancelled: true, message: `${modelId}: assessment cancelled — nothing recorded` });
return { ...assessment, cancelled: true };
}
console.log(`📏 Local LLM: ${backend}/${modelId} → ${verdict} (${assessment.performance.samplesOk}/${samples.length} samples ok)`);
+ emit({
+ event: 'complete',
+ verdict,
+ message: `${modelId}: ${verdict} (${assessment.performance.samplesOk}/${samples.length} samples ok)`,
+ });
return saveAssessment(assessment);
}
@@ -361,9 +303,18 @@ export async function runAssessment({ backend, modelId, contextTokens = DEFAULT_
* @param {{ intent?: string }} [options]
*/
export async function getAssessmentReport({ intent = 'balanced' } = {}) {
- const { assessments, readError } = await loadStore();
+ const { assessments: stored, readError } = await loadStore();
const resolvedIntent = ASSESSMENT_INTENTS.includes(intent) ? intent : 'balanced';
+ // Every stored record is compared against the machine as it is NOW. A reading
+ // taken before a RAM upgrade or a backend update describes hardware that no
+ // longer exists, and nothing else on this page would ever say so — the user
+ // would have to remember. This path can afford the backend-version probe (it
+ // already lists models from both backends); the catalog badge path cannot, and
+ // uses the free durable-fields comparison instead.
+ const liveEnvironments = await captureLiveEnvironments();
+ const assessments = stored.map((a) => withStaleness(a, liveEnvironments[a?.backend] || null));
+
// Both managers cache an EMPTY list on a failed read rather than throwing, so
// `[]` alone cannot distinguish "this backend has no models" from "the list
// could not be read" — and presenting the second as the first would silently
@@ -423,5 +374,9 @@ export async function getAssessmentReport({ intent = 'balanced' } = {}) {
readError,
ranked,
excluded,
+ // The machine as it is now, so the panel can name the difference rather than
+ // just flagging "stale". Keyed by backend because the backend version is
+ // part of what makes a reading stale.
+ liveEnvironments,
};
}
diff --git a/server/services/localModelAssessments.test.js b/server/services/localModelAssessments.test.js
index 2ab1fa2a53..23f95ecdcb 100644
--- a/server/services/localModelAssessments.test.js
+++ b/server/services/localModelAssessments.test.js
@@ -7,7 +7,7 @@
*/
import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';
-import { rmSync, existsSync, mkdirSync, writeFileSync, readdirSync } from 'fs';
+import { rmSync, existsSync, mkdirSync, writeFileSync, readFileSync, readdirSync } from 'fs';
import { join } from 'path';
import { createTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
@@ -24,9 +24,13 @@ vi.mock('./localLlm.js', () => ({ listModels: (...args) => listModels(...args) }
const getLoadedModels = vi.fn();
const getOllamaListError = vi.fn();
+const ollamaVersion = vi.fn(async () => '0.0.0-test');
vi.mock('./ollamaManager.js', () => ({
getLoadedModels: (...args) => getLoadedModels(...args),
getLastInstalledModelsError: () => getOllamaListError(),
+ // Recorded with each assessment so a backend UPDATE can later be detected as
+ // staleness — see localModelAssessmentStore.captureEnvironment.
+ getVersion: (...args) => ollamaVersion(...args),
}));
const getLmStudioListError = vi.fn();
@@ -36,6 +40,9 @@ vi.mock('./lmStudioManager.js', () => ({ getLastListError: () => getLmStudioList
vi.mock('../lib/localMemory.js', () => ({ getAvailableMemoryGb: async () => 64 }));
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');
const STORE = join(tempRoot, 'local-llm', 'assessments.json');
@@ -364,3 +371,109 @@ describe('deleteAssessment', () => {
expect(await svc.deleteAssessment('ollama', 'example-model:404')).toEqual({ deleted: false });
});
});
+
+describe('progress streaming', () => {
+ it('reports each sample as it lands, then one terminal complete frame', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun());
+ const frames = [];
+ await svc.runAssessment({
+ backend: 'ollama',
+ modelId: 'example-model:7b',
+ contextTokens: [512, 4096],
+ onProgress: (frame) => frames.push(frame),
+ });
+
+ // Every frame carries enough to be correlated on a channel shared with
+ // model pulls and migrations.
+ expect(frames.every((f) => f.scope === 'assessment' && f.backend === 'ollama' && f.modelId === 'example-model:7b')).toBe(true);
+ expect(frames.filter((f) => f.event === 'complete')).toHaveLength(1);
+ expect(frames.at(-1)).toMatchObject({ event: 'complete', verdict: 'fits' });
+ // Per-sample: one "about to run" and one "here is what it measured" each.
+ const withContext = frames.filter((f) => f.contextTokens);
+ expect(withContext.map((f) => f.contextTokens)).toEqual([512, 512, 4096, 4096]);
+ expect(withContext.every((f) => f.sampleCount === 2)).toBe(true);
+ });
+
+ it('emits a terminal frame for a cancelled run so a listener never hangs', async () => {
+ const controller = new AbortController();
+ runLocalLlmTest.mockImplementation(async () => { controller.abort(); return okRun(); });
+ const frames = [];
+ await svc.runAssessment({
+ backend: 'ollama',
+ modelId: 'example-model:7b',
+ contextTokens: [512],
+ signal: controller.signal,
+ onProgress: (frame) => frames.push(frame),
+ });
+ expect(frames.at(-1)).toMatchObject({ event: 'complete', cancelled: true });
+ });
+
+ it('does not let a broken progress listener abort the measurement', async () => {
+ // The listener runs outside the request error path; a throw there must not
+ // cost the user the minutes of compute already spent.
+ runLocalLlmTest.mockResolvedValue(okRun());
+ const result = await svc.runAssessment({
+ backend: 'ollama',
+ modelId: 'example-model:7b',
+ contextTokens: [512],
+ onProgress: () => { throw new Error('listener exploded'); },
+ });
+ expect(result.verdict).toBe('fits');
+ });
+});
+
+describe('staleness', () => {
+ it('flags a stored reading taken on a different machine state', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun());
+ await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });
+
+ // Rewrite the recorded environment as if the box had half the RAM then.
+ const store = JSON.parse(readFileSync(STORE, 'utf8'));
+ store.assessments[0].environment.totalMemoryGb = 1;
+ writeFileSync(STORE, JSON.stringify(store));
+
+ const report = await svc.getAssessmentReport({});
+ expect(report.assessments[0].staleness.stale).toBe(true);
+ expect(report.assessments[0].staleness.description).toMatch(/installed memory/i);
+ // And it travels with the ranked entry, so the panel doesn't recompute it.
+ expect(report.ranked[0].staleness.stale).toBe(true);
+ });
+
+ it('does not flag a reading taken on the machine as it is now', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun());
+ await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });
+ const report = await svc.getAssessmentReport({});
+ expect(report.assessments[0].staleness.stale).toBe(false);
+ expect(report.liveEnvironments.ollama.platform).toBe(process.platform);
+ });
+});
+
+describe('getMeasuredFits', () => {
+ it('projects a stored assessment into the catalog fit vocabulary', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun());
+ await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });
+
+ const fits = await store.getMeasuredFits('ollama');
+ expect(fits['example-model:7b']).toMatchObject({
+ fit: 'comfortable', verdict: 'fits', stale: false, meanCharsPerSecond: 120, residentGb: 5,
+ });
+ // Scoped to the backend — an Ollama measurement says nothing about LM Studio.
+ expect(await store.getMeasuredFits('lmstudio')).toEqual({});
+ });
+
+ it('returns an empty map when nothing has been measured', async () => {
+ expect(await store.getMeasuredFits('ollama')).toEqual({});
+ });
+
+ it('marks a reading from a different machine state stale rather than hiding it', async () => {
+ runLocalLlmTest.mockResolvedValue(okRun());
+ await svc.runAssessment({ backend: 'ollama', modelId: 'example-model:7b', contextTokens: [512] });
+ const raw = JSON.parse(readFileSync(STORE, 'utf8'));
+ raw.assessments[0].environment.cpuCount = 1;
+ writeFileSync(STORE, JSON.stringify(raw));
+
+ const fits = await store.getMeasuredFits('ollama');
+ expect(fits['example-model:7b'].stale).toBe(true);
+ expect(fits['example-model:7b'].staleReason).toMatch(/CPU count/i);
+ });
+});
diff --git a/server/services/localModelHealing.js b/server/services/localModelHealing.js
index 71da341e3e..08418accd0 100644
--- a/server/services/localModelHealing.js
+++ b/server/services/localModelHealing.js
@@ -20,6 +20,7 @@ import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifica
import * as ollamaManager from './ollamaManager.js';
import * as lmStudioManager from './lmStudioManager.js';
import { recommendEditorialModel, isEmbeddingModel } from '../lib/localModelHeuristics.js';
+import { getMeasuredFits } from './localModelAssessmentStore.js';
// Default OpenAI-compatible ports for the two local backends. An endpoint-only
// provider (no id/name) pointed at one of these on the local instance maps to
@@ -72,13 +73,14 @@ export function isModelNotFoundError(text) {
/**
* Pick the best installed model to fall back to. Prefers the editorial
- * recommender (family + size ranking, already drops embeddings/media weights);
+ * recommender (family + size ranking, already drops embeddings/media weights,
+ * and — given `measured` — refuses a model measured as not running here);
* if it finds nothing usable, takes the first non-embedding model, then any —
* embeddings can't serve a chat completion, so never auto-pick one.
* @returns {string|null}
*/
-export function chooseFallbackModel(models) {
- const recommended = recommendEditorialModel(models);
+export function chooseFallbackModel(models, { measured = {} } = {}) {
+ const recommended = recommendEditorialModel(models, { measured });
if (recommended?.id) return recommended.id;
const usable = (models || []).find((m) => m?.id && !isEmbeddingModel(m.id));
return usable?.id || (models || [])[0]?.id || null;
@@ -188,7 +190,12 @@ export async function healMissingLocalModel({ provider, requestedModel }) {
const installedIds = installed.map((m) => m.id);
if (requestedModel && installedIds.includes(requestedModel)) return null; // present after all
- const fallback = chooseFallbackModel(installed);
+ // Self-healing onto a model that was MEASURED not to run on this machine just
+ // swaps one broken run for another, so feed the recorded evidence in. Disk
+ // only, and a read failure degrades to the name-based guess rather than
+ // blocking the heal.
+ const measured = await getMeasuredFits(backend).catch(() => ({}));
+ const fallback = chooseFallbackModel(installed, { measured });
if (!fallback || fallback === requestedModel) return null;
// Persist the repoint so future runs use the real model. Track success: a
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index 6ede1b3b8d..db196bb17f 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -726,7 +726,13 @@ async function getInstalledModels(forceRefresh = false) {
return installedModels
}
-async function getVersion() {
+/**
+ * Ollama's reported version, or `null` when it isn't answering. Exported so the
+ * assessment store can record WHICH backend build a measurement was taken
+ * against — a backend update is one of the things that makes a stored reading
+ * stale, and there is no other way to notice it after the fact.
+ */
+export async function getVersion() {
const data = await ollamaRequest('/api/version', { timeout: AVAILABILITY_PROBE_TIMEOUT_MS }).catch(() => null)
return data?.version || null
}