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

track downloaded models in a manifest so Models > Status stops rescanning disk

[._.]/ Adam Eivy1ce71bdc540d
diff --git a/client/src/components/models/ModelStatusTab.jsx b/client/src/components/models/ModelStatusTab.jsx
index 2d83670789..3fdec8ecb2 100644
--- a/client/src/components/models/ModelStatusTab.jsx
+++ b/client/src/components/models/ModelStatusTab.jsx
@@ -1,4 +1,6 @@
+import { useEffect, useState } from 'react';
import ModelsPanel from './ModelsPanel.jsx';
+import { getTrackedModelInventory } from '../../services/api';
import { useSystemResourceReport } from '../../hooks/useSystemResourceReport.js';
/**
@@ -11,18 +13,42 @@ import { useSystemResourceReport } from '../../hooks/useSystemResourceReport.js'
* already rendered residency above the inventory, so folding them is a matter of
* hosting that panel here and feeding it the shared scan (#4728).
*
- * The scan is deliberately NOT run on mount: it walks the Hugging Face cache,
- * `data/loras/`, Ollama and LM Studio, which is slow and pointless for a user who
- * came here to unload a model. `ModelsPanel` shows its own "Run model inventory"
- * prompt until the user asks.
+ * The scan is still deliberately NOT run on mount: it walks the Hugging Face
+ * cache, `data/loras/`, Ollama and LM Studio, which is slow and pointless for a
+ * user who came here to unload a model. What arrives instead is the MANIFEST —
+ * the record the server keeps as models are installed and deleted — so the
+ * inventory is on screen immediately and the scan becomes the explicit "Refresh"
+ * that reconciles it with the disk.
+ *
+ * The manifest only fills an EMPTY slot (`previous ?? tracked`). Today the panel
+ * cannot start a scan before the record lands — the Refresh button is behind
+ * `initializing` — but the rule is what makes this safe if that ever changes: a
+ * scan read the disk itself, and must never be replaced by the cheaper record.
*/
export default function ModelStatusTab() {
- const { report, loading, runReport, cleanup } = useSystemResourceReport();
+ const { report, setReport, loading, runReport, cleanup } = useSystemResourceReport();
+ const [trackedLoaded, setTrackedLoaded] = useState(false);
+
+ useEffect(() => {
+ let active = true;
+ getTrackedModelInventory({ silent: true }).catch(() => null).then((tracked) => {
+ if (!active) return;
+ setTrackedLoaded(true);
+ // `reconciledAt: null` means no scan has ever verified this install, so an
+ // empty list is "we have not looked" rather than "nothing installed" —
+ // leave the panel on its run-the-inventory prompt.
+ if (tracked?.reconciledAt || tracked?.models?.downloaded?.length) {
+ setReport((previous) => previous ?? tracked);
+ }
+ });
+ return () => { active = false; };
+ }, [setReport]);
return (
<ModelsPanel
report={report}
loading={loading}
+ initializing={!trackedLoaded}
onRunReport={runReport}
cleanup={cleanup}
/>
diff --git a/client/src/components/models/ModelStatusTab.test.jsx b/client/src/components/models/ModelStatusTab.test.jsx
index 917ce706a6..e06f187d06 100644
--- a/client/src/components/models/ModelStatusTab.test.jsx
+++ b/client/src/components/models/ModelStatusTab.test.jsx
@@ -7,14 +7,22 @@
* tolerable if it does NOT scan on mount: the scan walks the Hugging Face cache,
* `data/loras/`, Ollama and LM Studio, which is slow and wasted on a user who
* came to unload a model.
+ *
+ * What the page shows INSTEAD of that scan is the manifest the server maintains
+ * as models are installed and removed. These tests pin the three things that
+ * makes load-bearing: the manifest renders without a scan, an unreconciled
+ * install still offers the one-time scan rather than claiming an empty machine,
+ * and an explicit scan still replaces what the record said.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
const runSystemResourceReport = vi.fn();
+const getTrackedModelInventory = vi.fn();
vi.mock('../../services/api', () => ({
runSystemResourceReport: (...a) => runSystemResourceReport(...a),
+ getTrackedModelInventory: (...a) => getTrackedModelInventory(...a),
purgeDataCategory: vi.fn(),
deleteCachedModel: vi.fn(),
deleteLora: vi.fn(),
@@ -27,11 +35,12 @@ import ModelStatusTab from './ModelStatusTab';
const REPORT = {
generatedAt: '2026-08-21T00:00:00.000Z',
+ inventorySource: 'scan',
cleanupCandidates: [],
sourceErrors: [],
models: {
downloaded: [{
- id: 'huggingface:example-model',
+ id: 'hf:models--example--model',
name: 'example-model',
backend: 'huggingface',
sizeBytes: 2048,
@@ -42,24 +51,98 @@ const REPORT = {
},
};
+const MANIFEST = {
+ inventorySource: 'manifest',
+ generatedAt: '2026-08-20T00:00:00.000Z',
+ reconciledAt: '2026-08-20T00:00:00.000Z',
+ cleanupCandidates: [],
+ sourceErrors: [],
+ models: {
+ downloaded: [{
+ id: 'lora:tracked-example.safetensors',
+ name: 'tracked-example',
+ backend: 'lora',
+ sizeBytes: 512,
+ loaded: false,
+ installedAt: '2026-08-19T00:00:00.000Z',
+ source: 'install',
+ }],
+ loaded: [],
+ totals: { all: 512 },
+ },
+};
+
+const EMPTY_MANIFEST = {
+ inventorySource: 'manifest',
+ generatedAt: null,
+ reconciledAt: null,
+ cleanupCandidates: [],
+ sourceErrors: [],
+ models: { downloaded: [], loaded: [], totals: { all: null } },
+};
+
const renderTab = () => render(<MemoryRouter><ModelStatusTab /></MemoryRouter>);
describe('ModelStatusTab', () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(() => {
+ vi.clearAllMocks();
+ getTrackedModelInventory.mockResolvedValue(EMPTY_MANIFEST);
+ });
- it('shows residency without scanning disk on mount', () => {
+ it('shows residency and the tracked inventory without scanning disk on mount', async () => {
+ getTrackedModelInventory.mockResolvedValue(MANIFEST);
renderTab();
+
expect(screen.getByText('residency panel')).toBeInTheDocument();
+ expect(await screen.findByText('tracked-example')).toBeInTheDocument();
+ expect(runSystemResourceReport).not.toHaveBeenCalled();
+ expect(screen.getByText(/tracked, last verified/i)).toBeInTheDocument();
+ // A row PortOS installed itself reports when the weights actually landed.
+ expect(screen.getByText(/installed .* ago/i)).toBeInTheDocument();
+ });
+
+ it('says "tracked since" for a row a scan adopted rather than claiming an install date', async () => {
+ getTrackedModelInventory.mockResolvedValue({
+ ...MANIFEST,
+ models: {
+ ...MANIFEST.models,
+ downloaded: [{ ...MANIFEST.models.downloaded[0], source: 'scan' }],
+ },
+ });
+ renderTab();
+
+ // The weights may be years old; all PortOS knows is when it first looked.
+ expect(await screen.findByText(/tracked since .* ago/i)).toBeInTheDocument();
+ expect(screen.queryByText(/installed .* ago/i)).not.toBeInTheDocument();
+ });
+
+ it('offers the one-time scan when nothing has ever been reconciled', async () => {
+ renderTab();
+ expect(await screen.findByRole('button', { name: /run model inventory/i })).toBeInTheDocument();
expect(runSystemResourceReport).not.toHaveBeenCalled();
- expect(screen.getByRole('button', { name: /run model inventory/i })).toBeInTheDocument();
});
it('renders the downloaded-model inventory once the user asks for it', async () => {
runSystemResourceReport.mockResolvedValue(REPORT);
renderTab();
- fireEvent.click(screen.getByRole('button', { name: /run model inventory/i }));
+ fireEvent.click(await screen.findByRole('button', { name: /run model inventory/i }));
await waitFor(() => expect(runSystemResourceReport).toHaveBeenCalledWith({ silent: true }));
expect(await screen.findByText('example-model')).toBeInTheDocument();
expect(screen.getByText(/downloaded model inventory/i)).toBeInTheDocument();
});
+
+ it('replaces the tracked list with a fresh scan when the user rescans', async () => {
+ getTrackedModelInventory.mockResolvedValue(MANIFEST);
+ runSystemResourceReport.mockResolvedValue(REPORT);
+ renderTab();
+
+ expect(await screen.findByText('tracked-example')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: /rescan disk/i }));
+
+ expect(await screen.findByText('example-model')).toBeInTheDocument();
+ // The rescan is what drops a model deleted outside PortOS — a row that
+ // survived it would still offer a delete button for weights that are gone.
+ expect(screen.queryByText('tracked-example')).not.toBeInTheDocument();
+ expect(screen.getByText(/scanned just now/i)).toBeInTheDocument();
+ });
});
diff --git a/client/src/components/models/ModelsPanel.jsx b/client/src/components/models/ModelsPanel.jsx
index 1d20415bae..d9fe8308c3 100644
--- a/client/src/components/models/ModelsPanel.jsx
+++ b/client/src/components/models/ModelsPanel.jsx
@@ -5,7 +5,7 @@ import DuplicateModelWeights from './DuplicateModelWeights.jsx';
import MemoryManagement from '../settings/MemoryManagement.jsx';
import Banner from '../ui/Banner.jsx';
import CleanupControl from '../system-resources/CleanupControl.jsx';
-import { formatBytes } from '../../utils/formatters.js';
+import { formatBytes, timeAgo } from '../../utils/formatters.js';
const BACKEND_LABEL = {
huggingface: 'Hugging Face',
@@ -14,6 +14,22 @@ const BACKEND_LABEL = {
lmstudio: 'LM Studio',
};
+/**
+ * When these weights arrived, phrased honestly about how PortOS knows.
+ *
+ * A row PortOS installed itself carries the real moment it landed. A row a scan
+ * ADOPTED — weights pulled by another tool, or by an install predating the
+ * manifest — only knows when PortOS first looked at the disk, so it must not
+ * claim a year-old model was installed this afternoon. `source` is what
+ * distinguishes them; a scan-built row carries neither field and says nothing.
+ */
+const provenanceLabel = (model) => {
+ if (!model.installedAt) return null;
+ return model.source === 'scan'
+ ? `tracked since ${timeAgo(model.installedAt)}`
+ : `installed ${timeAgo(model.installedAt)}`;
+};
+
const normalizeLmStudioRepo = (value) => String(value || '')
.split('/').pop()
.trim()
@@ -26,7 +42,9 @@ function InventoryEmpty({ loading, onRun }) {
<section className="rounded-2xl border border-dashed border-port-accent/40 bg-port-accent/5 px-5 py-7 text-center">
<Download className="mx-auto mb-3 text-port-accent" size={25} />
<h3 className="font-semibold text-white">Inventory downloaded models</h3>
- <p className="mx-auto mt-2 max-w-xl text-sm text-gray-400">Scan Hugging Face, LoRA, Ollama, and LM Studio storage to see what is installed.</p>
+ <p className="mx-auto mt-2 max-w-xl text-sm text-gray-400">
+ Nothing has been tracked yet. Scan Hugging Face, LoRA, Ollama, and LM Studio storage once — after that PortOS keeps the list current as you install and remove models.
+ </p>
<button
type="button"
onClick={onRun}
@@ -40,7 +58,19 @@ function InventoryEmpty({ loading, onRun }) {
);
}
-export default function ModelsPanel({ report, loading, onRunReport, cleanup }) {
+/**
+ * Residency above, the downloaded-model inventory below.
+ *
+ * `report` is either a live disk scan or the manifest-backed record of it
+ * (`inventorySource`), which the server shapes identically on purpose — the rows,
+ * their cleanup candidates and their delete actions are built by the same server
+ * helpers either way, so this component never needs to know which it is holding
+ * beyond the one provenance line it prints. `initializing` covers the brief read
+ * of that record: without it the run-the-inventory prompt flashes on every visit
+ * to an install that has one.
+ */
+export default function ModelsPanel({ report, loading, initializing = false, onRunReport, cleanup }) {
+ const fromManifest = report?.inventorySource === 'manifest';
const [residency, setResidency] = useState(null);
const candidates = new Map((report?.cleanupCandidates || []).map((item) => [item.id, item]));
const loaded = useMemo(() => ({
@@ -64,7 +94,11 @@ export default function ModelsPanel({ report, loading, onRunReport, cleanup }) {
<DuplicateModelWeights key={report?.generatedAt} duplicates={report?.modelDuplicates} locked={loading || cleanup.locked} onRefresh={onRunReport} />
- {!report ? <InventoryEmpty loading={loading} onRun={onRunReport} /> : (
+ {!report ? (initializing ? (
+ <section className="rounded-2xl border border-port-border bg-port-card px-5 py-7 text-center text-sm text-gray-500" role="status">
+ Loading tracked model inventory…
+ </section>
+ ) : <InventoryEmpty loading={loading} onRun={onRunReport} />) : (
<section className="rounded-2xl border border-port-border bg-port-card p-4 sm:p-5">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
@@ -74,6 +108,9 @@ export default function ModelsPanel({ report, loading, onRunReport, cleanup }) {
</div>
<p className="mt-1 text-xs text-gray-500">
{report.models.downloaded.length} item{report.models.downloaded.length === 1 ? '' : 's'} · {Number.isFinite(report.models.totals.all) ? formatBytes(report.models.totals.all) : 'size unavailable'}
+ {fromManifest
+ ? ` · tracked, last verified ${timeAgo(report.reconciledAt)}`
+ : ' · scanned just now'}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
@@ -83,9 +120,10 @@ export default function ModelsPanel({ report, loading, onRunReport, cleanup }) {
type="button"
onClick={onRunReport}
disabled={loading || cleanup.locked}
+ title="Rescan the model stores on disk and reconcile the tracked list — picks up models installed or deleted outside PortOS"
className="inline-flex min-h-[36px] items-center gap-1.5 rounded-lg border border-port-border px-3 py-2 text-xs text-gray-300 hover:bg-port-border/40 disabled:opacity-50"
>
- <RefreshCw size={13} className={loading ? 'animate-spin' : ''} /> Refresh
+ <RefreshCw size={13} className={loading ? 'animate-spin' : ''} /> {loading ? 'Rescanning…' : 'Rescan disk'}
</button>
</div>
</div>
@@ -142,7 +180,9 @@ export default function ModelsPanel({ report, loading, onRunReport, cleanup }) {
{effectiveLoaded && <span className="rounded bg-purple-500/10 px-1.5 py-0.5 text-[10px] uppercase text-purple-300">loaded</span>}
{residencyUnknown && <span className="rounded bg-port-warning/10 px-1.5 py-0.5 text-[10px] uppercase text-port-warning">status unknown</span>}
</div>
- {model.detail && <p className="mt-0.5 truncate text-xs text-gray-500">{model.detail}</p>}
+ <p className="mt-0.5 truncate text-xs text-gray-500">
+ {[model.detail, provenanceLabel(model)].filter(Boolean).join(' · ')}
+ </p>
</div>
<div className="text-sm font-semibold tabular-nums text-white">
{Number.isFinite(model.sizeBytes) ? `${model.sizeIsEstimate ? '≈' : ''}${formatBytes(model.sizeBytes)}` : 'Size unavailable'}
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index 8d51923256..9aa68d4c93 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -18,6 +18,10 @@ export const runSystemResourceReport = (options = {}) => request('/system-resour
method: 'POST',
...options,
});
+// The tracked downloaded-model inventory, read from the manifest PortOS keeps at
+// install/uninstall time. A GET because it runs no scan — that is what makes it
+// safe to call on page load, unlike `runSystemResourceReport`.
+export const getTrackedModelInventory = (options = {}) => request('/system-resources/models/manifest', options);
export const triageSystemResources = (payload, options = {}) => request('/system-resources/triage', {
method: 'POST',
body: JSON.stringify(payload),
diff --git a/docs/API.md b/docs/API.md
index e4d95e4d48..8fca81a21b 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -659,7 +659,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/avatar` | Avatar rendering/config |
| `/api/system` | System health metrics |
| `/api/system/capabilities` | Local hardware capabilities for model/provider selection |
-| `/api/system-resources` | System storage report and AI-assisted cleanup triage |
+| `/api/system-resources` | System storage report, the tracked downloaded-model manifest, and AI-assisted cleanup triage |
| `/api/remote-desktop`, `/remote-desktop` | PortDeck remote desktop session broker and viewer |
| `/api/capabilities` | Feature capability flags |
| `/api/agent-context` | Opt-in, loopback-only MCP context plus separately granted semantic PortOS actions |
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 67effa932b..4481e3d5d6 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -125,6 +125,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- Browser CDP profile / downloads — `data/browser-profile/`, `data/browser-downloads/` — cache, non-overridable backup excludes.
- Brain parity audit results — `data/brain_parity_reports.json` (`server/services/brainParity.js`, #4519). The last record-level brain-parity report per peer, keyed by peer `instanceId` (the same key `data/instances_sync_cursors.json` uses). `ephemeral-file` because it is a point-in-time *observation* about two installs, fully regenerable by re-running the audit, and stale the moment either side syncs — the durable state it describes lives in the brain stores. **Intentionally machine-local — never federated**: it is this install's view of a peer, and each peer computes its own. No sync cursor, no tombstone, no migration (an absent file reads as "nothing audited yet"). Per-type record lists are capped at 25 ids with a `truncated` flag so a badly diverged install can't grow the file without bound.
- CoS event ledgers — ordinary diagnostics use `data/cos/run-events.jsonl` + `run-events.1.jsonl`; persistent-mind trajectory uses the separate `mind-events.jsonl` + `mind-events.1.jsonl` pair (`server/services/agentRunEventLog.js`, #4540, #5082). Both are append-only, machine-local `ephemeral-file` replay aids with no federation cursor, tombstone, or `PORTOS_SCHEMA_VERSIONS` entry. The durable ordinary run record remains `data/runs/{id}/metadata.json`; mind rollups remain in their own bounded cache. Ordinary generations rotate at 5000 events and additionally expire after 30 days. Mind generations rotate at 10000 events without an age cutoff so a stopped mind keeps its unsummarized window, while high-volume mind chatter cannot evict ordinary run diagnostics. Migration 301 moves existing `mind.*` lines out of the shared files and stamps predecessor sequence provenance used to distinguish a legitimate timestamp jump from lost retained events. Payloads are redacted at append time, and both bounded pairs are backed up with the rest of `data/cos/`.
+- Downloaded-model manifest — `data/model-manifest.json` (`server/services/modelManifest.js`). One row per set of model weights on this machine — Hugging Face cache directories, LoRA adapters, Ollama tags, LM Studio model folders, each stamped with when it arrived and whether PortOS installed it or a scan adopted it. It exists so Models → Status can render the downloaded-model inventory on arrival instead of walking every model store on every visit; the scan it replaces still runs on demand and RECONCILES the file (adopting weights installed outside PortOS, dropping ones deleted outside it). `ephemeral-file`: fully re-derivable by that scan, with no queries, relationships, or sync cursor. **Intentionally machine-local — never federated**, and a non-overridable backup exclude for the same reason: it describes THIS machine's disks, so a restored copy would claim gigabytes of weights the target does not have and offer delete buttons for them. No migration and no `data.reference/` seed — an absent file reads as "nothing tracked yet", which is what the page's one-time scan prompt is for.
- Remote-API metadata cache — `data/cache/huggingface-repos.json` (`server/services/huggingFaceRepoCache.js`). Hugging Face per-repo records (file sizes, native context window) backing the local-LLM catalog's quant pickers. `ephemeral-file` rather than `db-primary` because it is a pure projection of someone else's API with no queries, no relationships, and no sync cursor — and because it is *machine-local by construction*: it exists to spare THIS install's cold-start requests, so federating it would be pure noise. Long TTL (7 days) since published GGUF file sizes are immutable, but bounded because a repo can gain a new quant. Non-overridable backup exclude — regenerable on demand, and stale by restore time anyway. Purgeable from Data Manager (`cache` category).
- Rapid Reader's Accelerando source cache — `data/cache/accelerando.html` (`server/services/rapidReader.js`). The official author-hosted HTML edition is fetched only when the user asks to load it, then retained locally for repeat and offline reads. `ephemeral-file` rather than `db-primary`: it is a machine-local copy of a separately licensed remote work, has no PortOS records or queries, and can be re-downloaded or purged without data loss. It is not bundled, federated, or backed up; Data Manager purges it with the `cache` category.
- Peer AI-usage digests — `data/peer-usage.json` (`server/services/peerUsage.js`). One aggregate usage digest per FEDERATED instance, keyed by origin `instanceId` and replaced whole under an LWW `capturedAt` stamp. `ephemeral-file`: it is entirely derived, replicated state whose authority is each peer's own `data/usage.json`, so a corrupt or missing file self-heals on the next 60s sync cycle. It is deliberately NOT merged into local `usage.json` — summing peer counters into our own file would double-count on the very next round trip and corrupt this machine's history irreversibly. Federated by the default-ON `usage` snapshot category: no per-record sequence cursor (a digest is replaced whole under an LWW `capturedAt`), but it DOES carry tombstones (`server/lib/tombstones.js`, keyed on `instanceId`) — removing a peer must retire its digest everywhere, since our own snapshot forwards every digest we hold and a surviving peer would otherwise hand a deleted row straight back. Capped at 64 instances (oldest `capturedAt` evicted), and each arriving digest is rebuilt to the known wire shape rather than stored as it came. Backed up with the rest of `data/` — harmless either way, since a restore is re-converged on the next cycle. See ADR [AI usage metrics federate on by default](./decisions/2026-09-01-federated-usage-metrics.md).
diff --git a/server/lib/README.md b/server/lib/README.md
index 6e44754451..3afa54c76e 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -196,6 +196,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `promptFencing.js` | Fencing for untrusted text spliced into an LLM prompt. `fenceBlock(label, text, maxChars)` truncates, collapses every run of 3+ backticks to `'''` so the content cannot terminate its own fence, and wraps the result as a labeled ```` ```text ```` block; `neutralizeFences` / `clampText` are the two halves on their own. `UNTRUSTED_CONTENT_NOTICE` is the standing "fenced content is data, not instructions" line a prompt places above its fenced sections — the fence stops delimiter escape, that line is what makes an in-band directive inert. `UNTRUSTED_PULL_REQUEST_NOTICE` is its counterpart for a prompt that sends an agent to READ a pull request off the forge (nothing is fenced because nothing is embedded) — shared by `services/prRemediationFollowUp.js` and `services/prDoReviewTask.js`. Used by `services/aiDetect.js`, whose prompt splices a scanned repository's package.json/config/README into a prompt that yields an executed `startCommands`. |
| `mediaModelBuckets.js` | Names and resolves the video registry's two model buckets (#4142). The split is by RUNTIME FAMILY — `mlx` (Apple MLX runtimes) vs `cuda` (plain torch+CUDA, which runs on Windows *and* Linux) — not by operating system, which is why `activeVideoBucket()` keys on `process.platform === 'darwin'` instead of on "is this Windows". `readVideoBucket` / `readVideoDefault` / `matchesVideoBucket` resolve the canonical key first and fall back to the pre-#4142 `macos` / `windows` / `defaultMacos` / `defaultWindows` spellings, so any registry written by an older install still loads untouched; `canonicalizeVideoBuckets` performs the one-time rename (migration 270 and the load-time twin in `mediaModels.js`). Kept separate from `mediaModels.js` so `scripts/migrations/` can share the alias resolution without importing the registry loader, which seeds `data/` as a side effect. |
| `mediaModels.js` | Single source of truth for image/video model metadata. Entry fields are documented in the module docblock — note `repoFiles[]`, which narrows a model's own repo to an explicit file list for an aggregate repo that holds far more than the runner loads (MiniMax H3 CUDA). |
+| `modelInventory.js` | Identity AND durable shape of a downloaded-model inventory row. `modelInventoryId(backend, key)` mints the `hf:` / `lora:` / `ollama:` / `lmstudio:` id and `parseModelInventoryId` splits it back on the FIRST colon (an Ollama tag like `qwen3:8b` carries one of its own). `hfInventoryRow` / `loraInventoryRow` / `localModelInventoryRow` build the row a backend contributes, and `presentInventoryRow` re-derives the live fields (residency, inventory-verified) that a STORED row can never answer. Shared by the scan that mints rows from disk (`services/systemResources.js`) and the manifest that records them at the install chokepoints (`services/modelManifest.js`) — a drifted copy of a row's risk, manage path or delete action is a delete button pointed at the wrong place. Pure and dependency-free, so the install services reach the builders without pulling the scan's module graph. |
| `videoFailure.js` | `normalizeVideoFailure` classifies and scrubs local video causes; `createVideoDiagnosticTail` retains bounded stdout/stderr diagnostics without grouping bare exit codes. |
| `maintenanceSequence.js` | The maintenance ladder shared by both runners: `MAINTENANCE_TASK_ORDER` / `MAINTENANCE_ORDER_GUIDANCE`, the interleaved `MAINTENANCE_SEQUENCE_TYPES` (a perpetual `claim-issue` drain between every pair of audits), `maintenanceStepParams` (audits file issues, documentation does the work), and `buildMaintenanceSteps` (fix mode runs audits directly with one final drain; issue filing can omit claim jobs) which emits quota-burn-shaped run-once steps so `quotaBurnInvoke.js` can run a step from the Schedule tab's manual run or a Quota Burn family plan alike. Pure. |
| `meetingUrl.js` | Selects the one cacheable join URL (`selectMeetingUrl`) out of a raw Google Calendar event — first http(s) `video` entry point, else `hangoutLink` — and owns the shared `MEETING_URL_MAX` bound. Three-state: `undefined` = the producer never described conferencing, `null` = described with none usable. |
diff --git a/server/lib/hfCache.js b/server/lib/hfCache.js
index 6af6b9c2d5..56fdbe01c8 100644
--- a/server/lib/hfCache.js
+++ b/server/lib/hfCache.js
@@ -42,7 +42,12 @@ export const getHfCacheRoot = () => {
// HF's on-disk naming: `org/name` -> `models--org--name`. Forward slashes
// inside the name (rare) are also `--` separated. Strip trailing slash so
// a registry-edit user pasting `org/name/` doesn't miss a real cache hit.
-const repoToDirName = (repoId) => `models--${repoId.replace(/\/$/, '').replace(/\//g, '--')}`;
+//
+// Exported because the directory name is also the IDENTITY of a downloaded model
+// everywhere outside this file: the inventory row id, the manifest key, and the
+// delete route's path parameter. A second copy of this rule that forgot the
+// trailing-slash strip would mint a key that never matches the cache listing.
+export const repoToDirName = (repoId) => `models--${repoId.replace(/\/$/, '').replace(/\//g, '--')}`;
const WEIGHT_EXTENSIONS = ['.safetensors', '.ckpt', '.bin', '.pt', '.msgpack', '.gguf'];
const isWeightFile = (name) => WEIGHT_EXTENSIONS.some((ext) => name.endsWith(ext));
diff --git a/server/lib/index.js b/server/lib/index.js
index f5c605aa6e..39792548f0 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -192,6 +192,7 @@ export * from './installLogger.js';
export * from './kimi.js';
export * from './mediaModelBuckets.js';
export * from './mediaModels.js';
+export * from './modelInventory.js';
export * from './meetingUrl.js';
export * from './minimaxH3Memory.js';
export * from './videoContinuity.js';
diff --git a/server/lib/modelInventory.js b/server/lib/modelInventory.js
new file mode 100644
index 0000000000..8846f55436
--- /dev/null
+++ b/server/lib/modelInventory.js
@@ -0,0 +1,157 @@
+/**
+ * The identity and durable shape of a downloaded-model inventory row.
+ *
+ * A row is addressed as `<prefix>:<key>`, where the key is the backend's OWN
+ * identifier for the weights — a Hugging Face cache directory (`models--org--repo`),
+ * a LoRA filename, an Ollama tag, an LM Studio model id. That pairing is what lets
+ * a scan row, a persisted manifest entry, and a delete action refer to the same
+ * thing: the id is stable across a rescan because the backend key is, and the
+ * delete action can be reconstructed from the two halves.
+ *
+ * Both halves of the scheme carry a separator that also appears inside the
+ * payload — an Ollama tag is `qwen3:8b`, an LM Studio id is `org/repo` — so the
+ * split and the join are written once, here, rather than as templates at each
+ * site.
+ *
+ * **Why the row BUILDERS live here too.** The same four row shapes are produced
+ * from two directions: `services/systemResources.js` mints them from a disk scan,
+ * and `services/modelManifest.js` records them from the install chokepoints, which
+ * never run a scan. A second copy of a row's `risk`, `managePath`, `action` or
+ * cleanup sentence is not a cosmetic duplication — the manifest row is rendered by
+ * the same component and armed by the same `modelCleanupCandidates`, so a drifted
+ * copy is a delete button pointed at the wrong place, or a one-click delete on
+ * weights the scan would have refused to arm.
+ *
+ * Pure and dependency-free, so the install services can reach the builders without
+ * pulling the scan's module graph (Ollama, LM Studio, the HF cache, the data
+ * manager) into their own.
+ */
+
+/** Backends whose downloaded weights PortOS inventories. */
+export const MODEL_INVENTORY_BACKENDS = ['huggingface', 'lora', 'ollama', 'lmstudio'];
+
+// The on-the-wire prefix per backend. `huggingface` shortens to `hf` for the same
+// reason the cache directories do — it is the longest of the four and appears in
+// every row id.
+const BACKEND_PREFIX = {
+ huggingface: 'hf',
+ lora: 'lora',
+ ollama: 'ollama',
+ lmstudio: 'lmstudio',
+};
+
+const PREFIX_BACKEND = new Map(Object.entries(BACKEND_PREFIX).map(([backend, prefix]) => [prefix, backend]));
+
+/**
+ * The inventory id for a model, or null when the backend or key is not usable.
+ *
+ * Returning null rather than throwing is deliberate: the callers are recording a
+ * side effect of an install that already succeeded, and a manifest entry is worth
+ * less than the install it describes.
+ *
+ * @param {string} backend One of MODEL_INVENTORY_BACKENDS
+ * @param {string} key The backend's own identifier for the weights
+ * @returns {string|null}
+ */
+export function modelInventoryId(backend, key) {
+ const prefix = BACKEND_PREFIX[backend];
+ const trimmed = typeof key === 'string' ? key.trim() : '';
+ if (!prefix || !trimmed) return null;
+ return `${prefix}:${trimmed}`;
+}
+
+/**
+ * Split an inventory id back into `{ backend, key }`, or null when it is not one.
+ *
+ * Splits on the FIRST colon only — an Ollama tag (`qwen3:8b`) contains colons of
+ * its own, so a greedy split would truncate the key the delete action needs.
+ *
+ * @param {string} id
+ * @returns {{ backend: string, key: string }|null}
+ */
+export function parseModelInventoryId(id) {
+ if (typeof id !== 'string') return null;
+ const separator = id.indexOf(':');
+ if (separator <= 0) return null;
+ const backend = PREFIX_BACKEND.get(id.slice(0, separator));
+ const key = id.slice(separator + 1);
+ return backend && key ? { backend, key } : null;
+}
+
+/**
+ * A downloaded Hugging Face repo, addressed by its cache directory name.
+ *
+ * `dirName` rather than the repo string, because that is what the scan reads off
+ * disk and what `DELETE /image-video/models/hf/:dirName` takes. Callers holding a
+ * repo id convert with `repoToDirName` (`lib/hfCache.js`), which owns the Hub's
+ * layout rule.
+ */
+export const hfInventoryRow = ({ dirName, name, detail, sizeBytes, sizeIsEstimate = false }) => ({
+ id: modelInventoryId('huggingface', dirName),
+ backend: 'huggingface',
+ name: name || dirName,
+ detail: detail || null,
+ sizeBytes,
+ sizeIsEstimate,
+ managePath: '/models/media',
+ action: { type: 'hf-model', dirName },
+});
+
+/** A LoRA adapter in `data/loras/`. High risk: it may be the only copy in existence. */
+export const loraInventoryRow = ({ filename, name, sizeBytes }) => ({
+ id: modelInventoryId('lora', filename),
+ backend: 'lora',
+ name: name || filename,
+ detail: 'LoRA adapter',
+ sizeBytes,
+ sizeIsEstimate: false,
+ risk: 'high',
+ cleanupReason: 'A trained or imported LoRA adapter may be the only copy and can take hours to reproduce.',
+ managePath: '/models/loras',
+ action: { type: 'lora', filename },
+});
+
+/**
+ * An Ollama tag or an LM Studio model folder.
+ *
+ * Ollama sizes are upper-bound estimates because tags share underlying layers, so
+ * deleting one reclaims less than its displayed size — the inventory renders that
+ * with a `≈`. Deleting an LM Studio entry takes the whole repo folder with it,
+ * which is why that one carries a cleanup warning and Ollama does not.
+ *
+ * `action` is nullable: a backend that is not available cannot be asked to delete.
+ */
+export const localModelInventoryRow = ({ backend, modelId, name, detail, sizeBytes, deletable = true }) => ({
+ id: modelInventoryId(backend, modelId),
+ backend,
+ name: name || modelId,
+ detail: detail || null,
+ sizeBytes,
+ sizeIsEstimate: backend === 'ollama',
+ cleanupReason: backend === 'lmstudio'
+ ? 'Deleting this entry removes the whole LM Studio model folder, including every downloaded quantization in it.'
+ : null,
+ managePath: '/models/llms',
+ action: deletable ? { type: 'local-model', backend, modelId } : null,
+});
+
+/**
+ * Apply the LIVE facts to a stored row on read.
+ *
+ * Residency, and whether the on-disk folder could be verified, are answers only a
+ * running backend can give — a manifest read knows the weights were on disk, never
+ * whether they are resident right now. Local backends therefore present as
+ * "residency unknown", which the Status panel overrides the moment its residency
+ * probe reports, and which keeps a one-click delete off a row nobody has verified
+ * is unloaded. Deriving it here rather than storing it means changing the rule
+ * fixes every existing row, not just newly written ones.
+ *
+ * @param {Object} entry A stored manifest entry
+ * @returns {Object} The entry as the inventory renders it
+ */
+export const presentInventoryRow = (entry) => ({
+ ...entry,
+ loaded: false,
+ residencyUnknown: entry.backend === 'ollama' || entry.backend === 'lmstudio',
+ inventoryUnknown: false,
+});
diff --git a/server/lib/modelInventory.test.js b/server/lib/modelInventory.test.js
new file mode 100644
index 0000000000..515f81f868
--- /dev/null
+++ b/server/lib/modelInventory.test.js
@@ -0,0 +1,103 @@
+/**
+ * The id scheme's real input matrix.
+ *
+ * Both halves of it carry a separator that also appears inside the payload: an
+ * Ollama tag is `qwen3:8b` and an LM Studio id is `org/repo`, so a greedy split
+ * or a blind `replace` truncates the very identifier the delete action needs.
+ * The round trip is the contract — a manifest entry that cannot be parsed back
+ * into `{ backend, key }` is an inventory row nothing can act on.
+ */
+import { describe, expect, it } from 'vitest';
+import {
+ hfInventoryRow,
+ localModelInventoryRow,
+ loraInventoryRow,
+ modelInventoryId,
+ parseModelInventoryId,
+ presentInventoryRow,
+} from './modelInventory.js';
+
+describe('modelInventoryId round trip', () => {
+ it.each([
+ ['huggingface', 'models--black-forest-labs--FLUX.1-dev', 'hf:models--black-forest-labs--FLUX.1-dev'],
+ ['lora', 'lora-example-v1.safetensors', 'lora:lora-example-v1.safetensors'],
+ // The two that a naive split gets wrong.
+ ['ollama', 'qwen3:8b', 'ollama:qwen3:8b'],
+ ['lmstudio', 'org/example-model-GGUF@Q4_K_M', 'lmstudio:org/example-model-GGUF@Q4_K_M'],
+ ])('%s/%s survives both directions', (backend, key, id) => {
+ expect(modelInventoryId(backend, key)).toBe(id);
+ expect(parseModelInventoryId(id)).toEqual({ backend, key });
+ });
+
+ it('refuses an id it cannot mint or read rather than inventing one', () => {
+ expect(modelInventoryId('unknown', 'x')).toBeNull();
+ expect(modelInventoryId('ollama', ' ')).toBeNull();
+ expect(modelInventoryId('ollama', undefined)).toBeNull();
+ expect(parseModelInventoryId('no-separator')).toBeNull();
+ expect(parseModelInventoryId(':leading')).toBeNull();
+ expect(parseModelInventoryId('ollama:')).toBeNull();
+ expect(parseModelInventoryId('unknownprefix:key')).toBeNull();
+ });
+});
+
+describe('row builders', () => {
+ // The scan and the install chokepoints both call these. The fields asserted here
+ // are the ones a drifted second copy would get wrong in a way the user feels: a
+ // delete action pointed at the wrong identifier, or a destructive row that lost
+ // the warning that makes it destructive.
+ it('gives a LoRA the high-risk treatment and a delete keyed by filename', () => {
+ const row = loraInventoryRow({ filename: 'lora-example-v1.safetensors', name: 'Example', sizeBytes: 512 });
+ expect(row).toMatchObject({
+ id: 'lora:lora-example-v1.safetensors',
+ backend: 'lora',
+ risk: 'high',
+ managePath: '/models/loras',
+ action: { type: 'lora', filename: 'lora-example-v1.safetensors' },
+ });
+ });
+
+ it('keys a Hugging Face row by its CACHE DIRECTORY, which is what the delete route takes', () => {
+ const row = hfInventoryRow({ dirName: 'models--org--repo', name: 'org/repo', sizeBytes: 700 });
+ expect(row).toMatchObject({
+ id: 'hf:models--org--repo',
+ action: { type: 'hf-model', dirName: 'models--org--repo' },
+ sizeIsEstimate: false,
+ });
+ });
+
+ it('marks Ollama sizes as estimates and warns only where a delete takes more than asked', () => {
+ // Ollama tags share layers, so the per-tag size is an upper bound.
+ expect(localModelInventoryRow({ backend: 'ollama', modelId: 'qwen3:8b' })).toMatchObject({
+ id: 'ollama:qwen3:8b',
+ sizeIsEstimate: true,
+ cleanupReason: null,
+ action: { type: 'local-model', backend: 'ollama', modelId: 'qwen3:8b' },
+ });
+ // Deleting an LM Studio entry removes every quantization in the folder.
+ expect(localModelInventoryRow({ backend: 'lmstudio', modelId: 'org/repo' })).toMatchObject({
+ sizeIsEstimate: false,
+ cleanupReason: expect.stringContaining('whole LM Studio model folder'),
+ });
+ });
+
+ it('offers no delete action for a backend that is not available to perform one', () => {
+ expect(localModelInventoryRow({ backend: 'ollama', modelId: 'qwen3:8b', deletable: false }).action).toBeNull();
+ });
+});
+
+describe('presentInventoryRow', () => {
+ // Residency is the fact a STORED row can never carry. Deriving it on read is what
+ // keeps a one-click delete off a local model nobody has verified is unloaded.
+ it('presents a local model as residency-unknown and a file-backed one as known', () => {
+ expect(presentInventoryRow({ id: 'ollama:qwen3:8b', backend: 'ollama' }))
+ .toMatchObject({ loaded: false, residencyUnknown: true, inventoryUnknown: false });
+ expect(presentInventoryRow({ id: 'lmstudio:org/repo', backend: 'lmstudio' }).residencyUnknown).toBe(true);
+ expect(presentInventoryRow({ id: 'hf:models--org--repo', backend: 'huggingface' }).residencyUnknown).toBe(false);
+ expect(presentInventoryRow({ id: 'lora:a.safetensors', backend: 'lora' }).residencyUnknown).toBe(false);
+ });
+
+ it('never lets a stored value override a live one', () => {
+ const stale = { id: 'ollama:qwen3:8b', backend: 'ollama', loaded: true, residencyUnknown: false };
+ expect(presentInventoryRow(stale)).toMatchObject({ loaded: false, residencyUnknown: true });
+ });
+});
diff --git a/server/routes/imageVideoModels.js b/server/routes/imageVideoModels.js
index dd5c23a6b8..10eaec3a96 100644
--- a/server/routes/imageVideoModels.js
+++ b/server/routes/imageVideoModels.js
@@ -27,6 +27,7 @@ import { emptyToUndefined, validateRequest } from '../lib/validation.js';
import { ADDABLE_IMAGE_RUNNERS, ADDABLE_VIDEO_RUNTIMES, searchHuggingfaceModels } from '../lib/huggingfaceModel.js';
import { addModelFromHuggingface } from '../services/mediaModelInstall.js';
import { getMediaModelStorage } from '../services/mediaModelStorage.js';
+import { recordModelUninstall } from '../services/modelManifest.js';
import { detectSystemCapabilities, withHardwareCompatibility } from '../lib/systemCapabilities.js';
const router = Router();
@@ -175,6 +176,7 @@ router.delete('/hf/:dirName', asyncHandler(async (req, res) => {
if (!existsSync(fullPath)) throw new ServerError('Model not found', { status: 404, code: 'NOT_FOUND' });
console.log(`🗑️ Deleting HF model cache: ${dirName}`);
await rmGuarded(fullPath, { recursive: true, force: true });
+ await recordModelUninstall({ backend: 'huggingface', key: dirName });
res.json({ ok: true });
}));
@@ -187,6 +189,9 @@ router.delete('/lora/:filename', asyncHandler(async (req, res) => {
if (!existsSync(filePath)) throw new ServerError('LoRA not found', { status: 404, code: 'NOT_FOUND' });
console.log(`🗑️ Deleting LoRA: ${filename}`);
await rmGuarded(filePath, { force: true });
+ // This route removes the weight file directly rather than going through
+ // `loras.deleteLora`, so it clears the manifest entry itself.
+ await recordModelUninstall({ backend: 'lora', key: filename });
res.json({ ok: true });
}));
diff --git a/server/routes/systemResources.js b/server/routes/systemResources.js
index bc62b64d02..c90cd35795 100644
--- a/server/routes/systemResources.js
+++ b/server/routes/systemResources.js
@@ -12,7 +12,7 @@ import { validateRequest } from '../lib/validation.js';
import { EFFORT_LEVELS } from '../lib/providerModels.js';
import { onClientDisconnect } from '../lib/sseDownload.js';
import { stopRun } from '../services/runner.js';
-import { getSystemResourceReport, triageSystemResources } from '../services/systemResources.js';
+import { getSystemResourceReport, getTrackedModelInventory, triageSystemResources } from '../services/systemResources.js';
import { rectifyModelDuplicates } from '../services/modelDeduplication.js';
const router = Router();
@@ -42,6 +42,14 @@ export const systemResourceTriageSchema = z.object({
.refine((value) => value === undefined || EFFORT_LEVELS.includes(value), 'Unsupported effort level'),
}).strict();
+// GET, unlike everything else here, because it performs NO scan: it reads the
+// model manifest PortOS maintains at install/uninstall time. That is the whole
+// point — Models → Status can show the downloaded-model inventory on arrival,
+// and a scan (POST /report) becomes the explicit "re-check the disk" action.
+router.get('/models/manifest', asyncHandler(async (_req, res) => {
+ res.json(await getTrackedModelInventory());
+}));
+
router.post('/report', asyncHandler(async (req, res) => {
validateRequest(emptyBodySchema, req.body || {});
res.json(await getSystemResourceReport({ force: true }));
diff --git a/server/routes/systemResources.test.js b/server/routes/systemResources.test.js
index 167069ed8d..6edcb5c477 100644
--- a/server/routes/systemResources.test.js
+++ b/server/routes/systemResources.test.js
@@ -10,6 +10,7 @@ const lifecycle = vi.hoisted(() => ({ onDisconnect: null, stopRun: vi.fn(async (
vi.mock('../services/systemResources.js', () => ({
getSystemResourceReport: vi.fn(),
+ getTrackedModelInventory: vi.fn(),
triageSystemResources: vi.fn(),
}));
vi.mock('../lib/sseDownload.js', () => ({
@@ -43,6 +44,21 @@ describe('system resources routes', () => {
expect(resources.getSystemResourceReport).toHaveBeenCalledWith({ force: true });
});
+ // The manifest read is the one route here that runs no scan — that is what lets
+ // Models → Status call it on arrival. A regression that routed it through the
+ // report instead would put a multi-store disk walk on every page load.
+ it('serves the tracked model inventory without touching the scan', async () => {
+ resources.getTrackedModelInventory.mockResolvedValue({
+ inventorySource: 'manifest',
+ reconciledAt: '2026-08-16T00:00:00.000Z',
+ models: { downloaded: [], loaded: [], totals: {} },
+ });
+ const response = await request(makeApp()).get('/api/system-resources/models/manifest');
+ expect(response.status).toBe(200);
+ expect(response.body).toMatchObject({ inventorySource: 'manifest' });
+ expect(resources.getSystemResourceReport).not.toHaveBeenCalled();
+ });
+
it('rejects report input instead of accepting filesystem hints', async () => {
const response = await request(makeApp()).post('/api/system-resources/report').send({ path: '/example' });
expect(response.status).toBe(400);
diff --git a/server/services/backup.js b/server/services/backup.js
index 8eb70fe25a..07c6b6c625 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -157,6 +157,11 @@ export const DEFAULT_EXCLUDES = [
{ path: '/cos/reference-repos/', reason: 'Reference upstream repos used by agents — re-cloneable', overridable: true },
{ path: '/browser-downloads/', reason: 'Browser downloads cache — large, re-downloadable', overridable: true },
{ path: '/cache/', reason: 'Remote-API metadata and licensed reading caches — regenerable on demand, and stale on restore anyway', overridable: false },
+ // Anchored with a leading `/`, like every entry here. The manifest describes
+ // which model weights are on THIS machine's disks; restoring it onto another
+ // would claim gigabytes of models that machine does not have, and offer delete
+ // buttons for them. It is fully re-derivable by a rescan from Models → Status.
+ { path: '/model-manifest.json', reason: 'Tracked downloaded-model inventory — machine-local and re-derivable by rescanning the model stores; a restored copy would describe another machine\'s disks', overridable: false },
// Sprite animation-run raw intermediates: 30–96 ffmpeg-extracted PNGs per
// run, byte-for-byte regenerable from the archived source video by the
// deterministic postprocess (walkPostprocess.js). The source video, packaged
diff --git a/server/services/hfDownloadStream.js b/server/services/hfDownloadStream.js
index 272253ca53..27572dc64c 100644
--- a/server/services/hfDownloadStream.js
+++ b/server/services/hfDownloadStream.js
@@ -11,9 +11,11 @@
// SSE plumbing it builds on (`openSseStream`, `onClientDisconnect`) stays in
// `lib/sseDownload.js` (issue #4901).
-import { findCachedRepoFile, inspectModelCache } from '../lib/hfCache.js';
+import { findCachedRepoFile, inspectModelCache, repoToDirName } from '../lib/hfCache.js';
+import { hfInventoryRow } from '../lib/modelInventory.js';
import { openSseStream, onClientDisconnect } from '../lib/sseDownload.js';
import { downloadHfRepo } from './hfDownload.js';
+import { recordModelInstall } from './modelManifest.js';
const inFlight = new Map(); // repo -> { promise, kill }
@@ -190,6 +192,22 @@ export async function startHfDownloadStream({ req, res, repo, revision = null, r
result = await handle.promise;
if (result?.ok) {
console.log(`✅ HuggingFace download complete: ${r} (${result.sizeBytes || 0} bytes)`);
+ // Every HF weight pull in PortOS lands here — image gen, video gen and
+ // music all drive this one stream — so this is the single place the model
+ // manifest learns a Hub repo is now on disk. A single-file pull reports
+ // only the bytes IT moved, which is a floor rather than the directory's
+ // size, hence the estimate flag; the next reconcile replaces it with the
+ // measured total.
+ await recordModelInstall({
+ ...hfInventoryRow({
+ dirName: repoToDirName(r),
+ name: r,
+ detail: r,
+ sizeBytes: result.sizeBytes,
+ sizeIsEstimate: singleFile,
+ }),
+ source: 'download',
+ });
} else if (result?.errorKind !== 'cancelled') {
console.error(`❌ HuggingFace download failed: ${r} — ${result?.errorMessage || 'unknown error'}`);
}
diff --git a/server/services/hfDownloadStream.test.js b/server/services/hfDownloadStream.test.js
index 2132954a25..13ff6a02bd 100644
--- a/server/services/hfDownloadStream.test.js
+++ b/server/services/hfDownloadStream.test.js
@@ -6,7 +6,8 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// never pull the deleted shard back. Mock the IO-bound cache inspect + HF fetch
// so the pure stream-control logic is exercised in isolation.
-vi.mock('../lib/hfCache.js', () => ({
+vi.mock('../lib/hfCache.js', async (importOriginal) => ({
+ ...(await importOriginal()),
inspectModelCache: vi.fn(async () => ({ cached: true, sizeBytes: 100, snapshotPath: '/snap' })),
findCachedRepoFile: vi.fn(async () => null),
}));
@@ -17,9 +18,17 @@ vi.mock('./hfDownload.js', () => ({
downloadHfRepo: vi.fn(() => ({ promise: Promise.resolve({ ok: true, sizeBytes: 100 }), kill: vi.fn() })),
}));
+// The manifest write is the same class of IO collaborator as the two above: this
+// suite exercises stream control, and a real write would land in the developer's
+// own `data/`. Doubled so the recording can be ASSERTED instead of merely allowed.
+vi.mock('./modelManifest.js', () => ({
+ recordModelInstall: vi.fn(async () => null),
+}));
+
import { startHfDownloadStream } from './hfDownloadStream.js';
import { inspectModelCache } from '../lib/hfCache.js';
import { downloadHfRepo } from './hfDownload.js';
+import { recordModelInstall } from './modelManifest.js';
// Minimal req/res doubles. Disconnect detection lives on `res` (see
// onClientDisconnect), so `res.on` records handlers and `disconnect()` fires
@@ -138,6 +147,31 @@ describe('startHfDownloadStream server-side logging', () => {
expect(lines.some((l) => l.includes('org/flux-fresh: model-00001-of-00002.safetensors (1/2)'))).toBe(true);
expect(lines.some((l) => l.includes('download complete: org/flux-fresh (4096 bytes)'))).toBe(true);
expect(errorSpy).not.toHaveBeenCalled();
+ // Every HF weight pull in PortOS comes through here, so this is the one place
+ // the model manifest learns a repo landed — keyed by the cache directory the
+ // scan and the delete route both address it by, not by the repo string.
+ expect(recordModelInstall).toHaveBeenCalledWith(expect.objectContaining({
+ backend: 'huggingface',
+ id: 'hf:models--org--flux-fresh',
+ sizeBytes: 4096,
+ action: { type: 'hf-model', dirName: 'models--org--flux-fresh' },
+ }));
+ });
+
+ it('does not record a repo that was already cached, or one whose download failed', async () => {
+ inspectModelCache.mockResolvedValue({ cached: true, sizeBytes: 100 });
+ const cachedRun = makeLoggingReqRes();
+ await startHfDownloadStream({ req: cachedRun.req, res: cachedRun.res, repo: 'org/already-here' });
+ expect(recordModelInstall).not.toHaveBeenCalled();
+
+ inspectModelCache.mockResolvedValue({ cached: false });
+ downloadHfRepo.mockImplementation(() => ({
+ promise: Promise.resolve({ ok: false, errorKind: 'gated_repo', errorMessage: 'gated' }),
+ kill: vi.fn(),
+ }));
+ const failedRun = makeLoggingReqRes();
+ await startHfDownloadStream({ req: failedRun.req, res: failedRun.res, repo: 'org/gated' });
+ expect(recordModelInstall).not.toHaveBeenCalled();
});
it('does not log every byte-progress tick', async () => {
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index 72d0ff10dd..7ac5bd2954 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -51,6 +51,8 @@ import { commandExists } from '../lib/commandExists.js'
import { runStreamingCommand } from '../lib/streamingSpawn.js'
import * as ollamaManager from './ollamaManager.js'
import * as lmStudioManager from './lmStudioManager.js'
+import { localModelInventoryRow } from '../lib/modelInventory.js'
+import { recordModelInstall, recordModelUninstall } from './modelManifest.js'
import { getProviderById, getAllProviders, updateProvider, refreshProviderModelsBatch, isOllamaBackedProvider } from './providers.js'
import { getSettings } from './settings.js'
@@ -1022,7 +1024,7 @@ export async function previewInstallModel(backend, modelId) {
}
}
-export async function installModel(backend, modelId, onProgress, { force = false } = {}) {
+async function performInstallModel(backend, modelId, onProgress, { force = false } = {}) {
if (!isBackend(backend)) return { success: false, error: `Unknown backend: ${backend}` }
// Resolve-not-throw: every other failure this function can hit (unknown
// backend, OLLAMA_OUTDATED, ...) resolves `{ success: false, error }` —
@@ -1072,7 +1074,7 @@ export async function installModel(backend, modelId, onProgress, { force = false
/**
* Delete an installed model from a backend.
*/
-export async function deleteModel(backend, modelId) {
+async function performDeleteModel(backend, modelId) {
if (!isBackend(backend)) return { success: false, error: `Unknown backend: ${backend}` }
if (backend === 'ollama') {
const loaded = await ollamaManager.getLoadedModels()
@@ -1098,6 +1100,54 @@ export async function deleteModel(backend, modelId) {
return lmStudioManager.deleteModel(modelId)
}
+// Both backends' installs and deletes have several success and failure exits
+// each (preflight refusal, a forced evict that failed, the `lms` CLI vs the REST
+// fallback, a residency check that could not be verified). Recording the manifest
+// at every one of those is how a later exit gets added without one — so the two
+// public entry points wrap a single internal function and record once, off its
+// one contractual `{ success }` result.
+//
+// A `pending` LM Studio install is deliberately NOT recorded: the REST fallback
+// only QUEUES the download, so the weights are not on disk yet and the next
+// reconcile is what adopts them.
+/**
+ * Install a model into a backend, recording it in the model manifest on success.
+ *
+ * @param {string} backend
+ * @param {string} modelId
+ * @param {Function} [onProgress]
+ * @param {Object} [options]
+ * @param {boolean} [options.force] Re-download even when the weights are present
+ * @returns {Promise<Object>} `{ success, ... }` — never throws (see performInstallModel)
+ */
+export async function installModel(backend, modelId, onProgress, options = {}) {
+ const result = await performInstallModel(backend, modelId, onProgress, options)
+ if (result?.success && !result.pending) {
+ // The row comes from the shared builder the SCAN uses, so a tracked model and
+ // a scanned one carry the same size semantics, cleanup warning and delete
+ // action. Size is left unset: neither backend reports the installed bytes, and
+ // the next reconcile measures it off disk.
+ await recordModelInstall({
+ ...localModelInventoryRow({ backend, modelId }),
+ source: 'download',
+ })
+ }
+ return result
+}
+
+/**
+ * Delete an installed model from a backend, clearing it from the model manifest.
+ *
+ * @param {string} backend
+ * @param {string} modelId
+ * @returns {Promise<Object>} `{ success, ... }`
+ */
+export async function deleteModel(backend, modelId) {
+ const result = await performDeleteModel(backend, modelId)
+ if (result?.success) await recordModelUninstall({ backend, key: modelId })
+ return result
+}
+
// ---- switch / migrate --------------------------------------------------------
/**
@@ -1141,6 +1191,13 @@ async function tryLocalImport(to, model, targetId, resolved, mode, onProgress) {
// `linked` reflects what actually happened on disk — link mode falls back to a
// copy across filesystems, so report the real outcome, not the requested mode.
onProgress({ event: 'start', message: `${r.linked ? 'Linked' : 'Copied'} ${r.modelId} onto ${to} (no download)` })
+ // A migration's fast path never goes through `installModel` — it moves the GGUF
+ // itself — so it records its own arrival, or the target backend's newest models
+ // would be the ones the manifest does not know about.
+ await recordModelInstall({
+ ...localModelInventoryRow({ backend: to, modelId: r.modelId }),
+ source: 'import',
+ })
return { source: model.id, target: r.modelId, status: 'imported', linked: !!r.linked, reason: null }
}
diff --git a/server/services/localLlm.test.js b/server/services/localLlm.test.js
index cd59c3c84b..a00d916238 100644
--- a/server/services/localLlm.test.js
+++ b/server/services/localLlm.test.js
@@ -58,6 +58,14 @@ vi.mock('../lib/fileUtils.js', async () => {
};
});
+// The model manifest is an IO collaborator of install/delete, not part of the
+// dispatch this file tests — and the fileUtils mock above deliberately omits the
+// JSON readers it needs. Doubled so the recording can be asserted directly.
+vi.mock('./modelManifest.js', () => ({
+ recordModelInstall: vi.fn(async () => null),
+ recordModelUninstall: vi.fn(async () => false),
+}));
+
// The macOS .app upgrade renames / removes / stats REAL absolute paths under
// /Applications. Model only those in memory — everything else (the temp dir the
// download actually writes to) keeps the real implementation — so no test can
@@ -365,6 +373,39 @@ describe('localLlm', () => {
await svc.deleteModel('ollama', 'llama3.2');
expect(mocks.ollama.deleteModel).toHaveBeenCalledWith('llama3.2');
});
+ // The manifest is what Models → Status renders without a disk scan, so a
+ // delete that leaves the row behind offers a delete button for weights that
+ // are gone, and an install that never records one hides the model entirely
+ // until someone rescans. Both directions asserted here because install and
+ // delete each have several exits and the recording sits on only one path.
+ it('records an Ollama install and clears it again on delete', async () => {
+ const { recordModelInstall, recordModelUninstall } = await import('./modelManifest.js');
+
+ await svc.installModel('ollama', 'llama3.2');
+ expect(recordModelInstall).toHaveBeenCalledWith(expect.objectContaining({
+ id: 'ollama:llama3.2',
+ backend: 'ollama',
+ action: { type: 'local-model', backend: 'ollama', modelId: 'llama3.2' },
+ // Ollama tags share layers, so a per-tag size is an upper bound.
+ sizeIsEstimate: true,
+ }));
+
+ await svc.deleteModel('ollama', 'llama3.2');
+ expect(recordModelUninstall).toHaveBeenCalledWith({ backend: 'ollama', key: 'llama3.2' });
+ });
+ it('does not record a refused delete or a merely-queued LM Studio download', async () => {
+ const { recordModelInstall, recordModelUninstall } = await import('./modelManifest.js');
+
+ mocks.ollama.getLoadedModels.mockResolvedValueOnce([{ id: 'llama3.2', name: 'llama3.2' }]);
+ await svc.deleteModel('ollama', 'llama3.2');
+ expect(recordModelUninstall).not.toHaveBeenCalled();
+
+ // The REST fallback only QUEUES the download (`pending`), so the weights are
+ // not on disk yet — recording here would claim an install that may never land.
+ const queued = await svc.installModel('lmstudio', 'unsloth/Qwen3.8-27B-GGUF');
+ expect(queued).toMatchObject({ success: true, pending: true });
+ expect(recordModelInstall).not.toHaveBeenCalled();
+ });
it('refuses to delete a model whose live residency check says loaded', async () => {
mocks.ollama.getLoadedModels.mockResolvedValueOnce([{ id: 'llama3.2', name: 'llama3.2' }]);
diff --git a/server/services/loras.js b/server/services/loras.js
index 0ce404428c..a8bf3f88c2 100644
--- a/server/services/loras.js
+++ b/server/services/loras.js
@@ -35,6 +35,8 @@ import { isPlainObject } from '../lib/objects.js';
import { readCachedLoraEffectReport } from '../lib/loraEffect.js';
import { createKeyedFileWriteQueue } from '../lib/fileWriteQueue.js';
import { createSingleFlight } from '../lib/singleFlight.js';
+import { loraInventoryRow } from '../lib/modelInventory.js';
+import { recordModelInstall, recordModelUninstall } from './modelManifest.js';
import {
applyDownloadToken,
baseModelToRunner,
@@ -355,6 +357,7 @@ export const deleteLora = async (filename) => {
}
invalidateLoraMetadataCache(filename);
});
+ await recordModelUninstall({ backend: 'lora', key: filename });
console.log(`🗑️ Deleted LoRA: ${filename}`);
return { ok: true, filename };
};
@@ -375,12 +378,27 @@ export const deleteLora = async (filename) => {
const queueSidecarWrite = createKeyedFileWriteQueue();
// Replace a sidecar wholesale (the install paths), serialized against patches.
+//
+// This is also where the model manifest learns about a new adapter: all three
+// installers (Civitai, Hugging Face, and a finished training run) finish by
+// writing the sidecar wholesale, and none of them shares another step. Recording
+// here rather than in each installer is what keeps a fourth one from arriving
+// untracked — and a re-install over an existing filename keeps its original
+// `installedAt`, so it does not read as newly downloaded.
export const writeLoraSidecar = (filename, sidecar) => queueSidecarWrite(filename, async () => {
- if (!existsSync(join(PATHS.loras, filename))) {
+ const loraPath = join(PATHS.loras, filename);
+ if (!existsSync(loraPath)) {
throw new ServerError(`LoRA not found: ${filename}`, { status: 404, code: 'NOT_FOUND' });
}
await atomicWrite(sidecarPath(filename), JSON.stringify(sidecar, null, 2) + '\n');
invalidateLoraMetadataCache(filename);
+ await recordModelInstall(loraInventoryRow({
+ filename,
+ name: sidecar?.name || filename.replace(/^lora-/, '').replace(/\.safetensors$/, ''),
+ // Measured, not claimed: the Civitai sidecar carries the API's `sizeKB` and the
+ // HF one carries nothing, so the file itself is the only uniform source.
+ sizeBytes: await stat(loraPath).then((info) => info.size, () => null),
+ }));
});
export const patchLoraSidecar = async (filename, patch) => {
diff --git a/server/services/loras.test.js b/server/services/loras.test.js
index ae0833604d..2c93e6a9a2 100644
--- a/server/services/loras.test.js
+++ b/server/services/loras.test.js
@@ -58,7 +58,10 @@ beforeEach(async () => {
const actual = await vi.importActual('../lib/fileUtils.js');
return {
...actual,
- PATHS: { ...actual.PATHS, loras: tmpLoras },
+ // `data` as well as `loras`: a finished install records itself in the model
+ // manifest (`data/model-manifest.json`), and the test-isolation guard
+ // refuses that write while the data root still points at the real install.
+ PATHS: { ...actual.PATHS, data: tmpRoot, loras: tmpLoras },
atomicWrite: (...args) => atomicWriteHook
? atomicWriteHook(actual.atomicWrite, ...args)
: actual.atomicWrite(...args),
@@ -520,12 +523,19 @@ describe('patchLoraSidecar', () => {
const firstPatch = lorasService.patchLoraSidecar('delete-race.safetensors', { name: 'Before delete' });
await writeStarted;
const deletion = lorasService.deleteLora('delete-race.safetensors');
- const latePatch = lorasService.patchLoraSidecar('delete-race.safetensors', { name: 'After delete' });
+ // Capture the rejection AT CREATION, not after the awaits below: this patch is
+ // queued behind the deletion and rejects as soon as that lands, which is
+ // before an `await deletion` on the line after it has returned. Attaching the
+ // handler later leaves a window where the rejection is genuinely unhandled,
+ // and Node reports it as such — a false failure about the delete path rather
+ // than about anything this test asserts.
+ const latePatch = lorasService.patchLoraSidecar('delete-race.safetensors', { name: 'After delete' })
+ .catch((error) => error);
releaseWrite();
await firstPatch;
await deletion;
- const err = await latePatch.catch((error) => error);
+ const err = await latePatch;
expect(err.status).toBe(404);
expect(err.code).toBe('NOT_FOUND');
expect(existsSync(filePath)).toBe(false);
diff --git a/server/services/modelManifest.js b/server/services/modelManifest.js
new file mode 100644
index 0000000000..4accd03527
--- /dev/null
+++ b/server/services/modelManifest.js
@@ -0,0 +1,279 @@
+/**
+ * The persisted record of which model weights this machine has on disk.
+ *
+ * The downloaded-model inventory used to exist only for as long as a page was
+ * open: Models → Status ran a multi-store disk scan (the Hugging Face cache,
+ * `data/loras/`, Ollama's blob store, LM Studio's model tree) and threw the
+ * result away on navigation, so the answer to "what have I downloaded?" cost a
+ * fresh walk over tens of gigabytes every single time. PortOS already knows the
+ * answer, though — it is the side that performs the installs and the deletes.
+ * This manifest is that knowledge written down, so the page can render instantly
+ * from `data/model-manifest.json` and a scan becomes a RECONCILIATION the user
+ * asks for rather than the only way to see anything.
+ *
+ * Two write paths, and they are deliberately different:
+ *
+ * - **Recording.** `recordModelInstall` / `recordModelUninstall` are called from
+ * the install and delete chokepoints (one per backend — see the comment at
+ * each call site). They are best-effort and never fail their caller: a
+ * manifest entry is worth strictly less than the install it describes.
+ * - **Reconciliation.** `reconcileModelManifest` folds a real scan back in,
+ * adopting weights that arrived outside PortOS and dropping entries whose
+ * files are gone. Every full system-resource report reconciles as a side
+ * effect, so the Refresh button and the Dev Tools storage report both heal the
+ * manifest without a second code path.
+ *
+ * **Reconciliation prunes only backends the scan could actually see.** An Ollama
+ * server that is down, or a backend the user disabled in settings, reports zero
+ * models — pruning on that would erase a correct manifest and silently tell the
+ * user their weights are gone. Untrusted backends are left exactly as they were.
+ *
+ * Storage class: `ephemeral-file` (docs/STORAGE.md). It is machine-local and
+ * fully re-derivable by scanning, which is also why it is excluded from backup:
+ * restoring one machine's model inventory onto another describes weights that
+ * machine does not have.
+ */
+
+import { join } from 'path';
+import { createCachedStore, PATHS } from '../lib/fileUtils.js';
+import {
+ MODEL_INVENTORY_BACKENDS,
+ modelInventoryId,
+ presentInventoryRow,
+} from '../lib/modelInventory.js';
+
+const MODEL_MANIFEST_SCHEMA_VERSION = 1;
+
+const EMPTY_MANIFEST = { schemaVersion: MODEL_MANIFEST_SCHEMA_VERSION, reconciledAt: null, models: {} };
+
+/**
+ * The shared single-JSON-document store: one write tail, a short read cache, and
+ * — the part that matters here — a STRICT load.
+ *
+ * `mutate` is load → modify → persist, so a present-but-unreadable manifest must
+ * reject rather than read as "no models installed": the very next write would
+ * otherwise stamp that emptiness over the record. An ABSENT file still yields the
+ * default, which is the pre-first-install state and the state of every install
+ * upgrading into this feature.
+ *
+ * The single tail matters because the writers genuinely overlap — a reconcile
+ * walks four backends while a queued LM Studio download finishes and records
+ * itself — and this module is the only writer of the file.
+ *
+ * Built on FIRST USE rather than at module load. The install chokepoints import
+ * this module, so it is reached transitively by a long tail of suites that mock
+ * `fileUtils.js` partially — and constructing the store in module scope turns a
+ * missing mock export into an import-time crash in a file that has nothing to do
+ * with models. Lazily, the same suites simply never touch it.
+ */
+let store = null;
+const manifestStore = () => (store ??= createCachedStore(
+ join(PATHS.data, 'model-manifest.json'),
+ EMPTY_MANIFEST,
+ { context: 'model manifest' },
+));
+
+/** Test seam, mirroring `resetSystemResourceReportCache` on the surface this feeds. */
+export const resetModelManifestCache = () => store?.invalidateCache();
+
+// Read-time shape repair. The file survives downgrades and hand edits, so a
+// missing or wrong-typed member reads as its empty form rather than throwing.
+const normalize = (raw) => ({
+ reconciledAt: typeof raw?.reconciledAt === 'string' ? raw.reconciledAt : null,
+ models: raw?.models && typeof raw.models === 'object' && !Array.isArray(raw.models) ? raw.models : {},
+});
+
+/**
+ * Serialized read-modify-write over the normalized manifest.
+ *
+ * `fn` returns `{ document, value }`, where a null `document` leaves the file
+ * untouched and `value` is what the caller wanted to learn from the write — the
+ * counts a reconcile produced, or whether an entry was really there to remove.
+ * The value rides out of the mutation rather than being decoded from the persisted
+ * document, which cannot distinguish "wrote nothing because nothing changed" from
+ * "wrote nothing because the write failed".
+ *
+ * Every mutator is best-effort: a failed write logs and yields `fallback` rather
+ * than failing the install or delete that triggered it.
+ */
+const mutateManifest = async (label, fn, fallback) => {
+ let value = fallback;
+ return manifestStore().mutate(async (raw) => {
+ const outcome = await fn(normalize(raw));
+ value = outcome.value;
+ return outcome.document === null
+ ? raw
+ : { schemaVersion: MODEL_MANIFEST_SCHEMA_VERSION, ...outcome.document };
+ }).then(() => value, (err) => {
+ console.error(`❌ ${label}: ${err.message}`);
+ return fallback;
+ });
+};
+
+/**
+ * The stored shape of one inventory row: the durable facts only.
+ *
+ * Residency, and whether the on-disk folder could be verified, are LIVE facts a
+ * stored row can never answer — `presentInventoryRow` re-derives them on read, so
+ * changing that rule fixes every existing row instead of only newly written ones.
+ * `key` is not stored either: it is the second half of `id` by construction.
+ *
+ * `installedAt` + `source` are the pair the page renders. `source` matters because
+ * a row adopted by the first reconcile has an `installedAt` of "when we first
+ * looked", not when the weights actually landed — the UI says "tracked since"
+ * for those and "installed" for the ones PortOS performed itself.
+ */
+function storedEntry(row, { installedAt, source }) {
+ const entry = { id: row.id, backend: row.backend, installedAt, source };
+ for (const field of ['name', 'detail', 'sizeBytes', 'risk', 'cleanupReason', 'managePath', 'action']) {
+ if (row[field] != null) entry[field] = row[field];
+ }
+ if (row.sizeIsEstimate) entry.sizeIsEstimate = true;
+ return entry;
+}
+
+/**
+ * The manifest as the API and the Status page consume it: rows sorted largest
+ * first, matching the scan's own ordering so the two views do not reshuffle.
+ *
+ * @returns {Promise<{ reconciledAt: string|null, models: Array<Object> }>}
+ */
+export async function getModelManifest() {
+ const manifest = normalize(await manifestStore().load());
+ const models = Object.values(manifest.models)
+ .filter((entry) => entry && typeof entry === 'object' && typeof entry.id === 'string')
+ .map(presentInventoryRow)
+ .sort((a, b) => (b.sizeBytes || 0) - (a.sizeBytes || 0));
+ return { reconciledAt: manifest.reconciledAt, models };
+}
+
+/**
+ * Record that weights are now on disk.
+ *
+ * Idempotent on re-install: the original `installedAt` and `source` survive a
+ * re-download, so a repair pass over a corrupt shard does not make a year-old
+ * model look newly installed.
+ *
+ * @param {Object} row An inventory row from `lib/modelInventory.js`'s builders
+ * @param {string} [row.source] How PortOS learned about it ('install' by default)
+ * @returns {Promise<boolean>} Whether the manifest now holds the entry
+ */
+export function recordModelInstall({ source = 'install', ...row }) {
+ if (!row.id) return Promise.resolve(false);
+ return mutateManifest(`Could not record model install ${row.id}`, (manifest) => {
+ const previous = manifest.models[row.id];
+ return {
+ document: {
+ ...manifest,
+ models: {
+ ...manifest.models,
+ [row.id]: storedEntry(row, {
+ installedAt: previous?.installedAt || new Date().toISOString(),
+ source: previous?.source || source,
+ }),
+ },
+ },
+ value: true,
+ };
+ }, false);
+}
+
+/**
+ * Record that weights are gone from disk.
+ *
+ * @param {Object} input
+ * @param {string} input.backend
+ * @param {string} input.key The backend's own identifier for the weights
+ * @returns {Promise<boolean>} Whether an entry was actually removed
+ */
+export function recordModelUninstall({ backend, key }) {
+ const id = modelInventoryId(backend, key);
+ if (!id) return Promise.resolve(false);
+ return mutateManifest(`Could not record model uninstall ${id}`, (manifest) => {
+ if (!manifest.models[id]) return { document: null, value: false };
+ const { [id]: _removed, ...models } = manifest.models;
+ return { document: { ...manifest, models }, value: true };
+ }, false);
+}
+
+/**
+ * Which backends a scan actually observed, and may therefore be pruned against.
+ *
+ * A disabled or unreachable backend contributes zero rows, which is
+ * indistinguishable from "you have no models there" — and acting on that reading
+ * would delete a correct manifest. The scan's own `sourceErrors` / `disabledSources`
+ * are the honest signal, so the mapping from those ids to backends lives here next
+ * to the pruning that depends on it. A *residency* probe failure is deliberately
+ * not disqualifying: it says nothing about what is on disk.
+ *
+ * @param {Object} [options]
+ * @param {Array<string>} [options.sourceErrors]
+ * @param {Array<string>} [options.disabledSources]
+ * @returns {Set<string>}
+ */
+export function trustedInventoryBackends({ sourceErrors = [], disabledSources = [] } = {}) {
+ const failed = new Set(sourceErrors);
+ const disabled = new Set(disabledSources);
+ const trusted = new Set(MODEL_INVENTORY_BACKENDS);
+ if (failed.has('huggingface')) trusted.delete('huggingface');
+ if (failed.has('loras')) trusted.delete('lora');
+ for (const backend of ['ollama', 'lmstudio']) {
+ if (disabled.has(backend) || failed.has(`${backend}-backend`) || failed.has(`${backend}-inventory`)) {
+ trusted.delete(backend);
+ }
+ }
+ return trusted;
+}
+
+/**
+ * Fold a real disk scan back into the manifest.
+ *
+ * Adopts rows PortOS never saw installed (weights pulled by another tool, or by a
+ * PortOS old enough to predate this manifest) and drops rows whose files are gone
+ * (deleted outside the app). Both directions are scoped to the backends the scan
+ * could see — see `trustedInventoryBackends`.
+ *
+ * @param {Array<Object>} downloadedModels Rows from the system-resource scan
+ * @param {Object} [options]
+ * @param {Array<string>} [options.sourceErrors]
+ * @param {Array<string>} [options.disabledSources]
+ * @returns {Promise<{ reconciledAt: string, added: number, removed: number, trusted: Array<string> }|null>}
+ */
+export function reconcileModelManifest(downloadedModels, { sourceErrors = [], disabledSources = [] } = {}) {
+ const trusted = trustedInventoryBackends({ sourceErrors, disabledSources });
+ return mutateManifest('Could not reconcile model manifest', (manifest) => {
+ const now = new Date().toISOString();
+ // A row the backend listed but whose on-disk folder could not be verified is
+ // not evidence of anything: it must neither be adopted as a tracked install
+ // nor counted as absent when pruning.
+ const scanned = new Map((downloadedModels || [])
+ .filter((row) => trusted.has(row.backend) && !row.inventoryUnknown)
+ .map((row) => [row.id, row]));
+
+ const models = {};
+ let removed = 0;
+ for (const [id, entry] of Object.entries(manifest.models)) {
+ if (trusted.has(entry.backend) && !scanned.has(id)) removed += 1;
+ else models[id] = entry;
+ }
+ let added = 0;
+ for (const [id, row] of scanned) {
+ const previous = models[id];
+ if (!previous) added += 1;
+ // A row PortOS installed itself keeps its real install date and provenance;
+ // one the scan found first is dated "when we first looked", which is what
+ // `source: 'scan'` tells the page so it does not claim a year-old model was
+ // installed this afternoon.
+ models[id] = storedEntry(row, {
+ installedAt: previous?.installedAt || now,
+ source: previous?.source || 'scan',
+ });
+ }
+
+ if (added || removed) console.log(`📓 Model manifest reconciled: +${added} / -${removed} (${[...trusted].join(', ') || 'no trusted backends'})`);
+ return {
+ document: { reconciledAt: now, models },
+ value: { reconciledAt: now, added, removed, trusted: [...trusted] },
+ };
+ }, null);
+}
diff --git a/server/services/modelManifest.test.js b/server/services/modelManifest.test.js
new file mode 100644
index 0000000000..b42cfd0495
--- /dev/null
+++ b/server/services/modelManifest.test.js
@@ -0,0 +1,171 @@
+/**
+ * The model manifest's durability contract.
+ *
+ * These are the behaviors a scan can no longer supply once the Status page reads
+ * a persisted record instead of walking the disk on every visit: that an
+ * uninstall actually clears the row, that a re-install does not reset an install
+ * date, that a reconcile adopts weights PortOS never installed and drops ones
+ * that vanished — and, the one that costs real data if it regresses, that a
+ * backend the scan could NOT see is never pruned against.
+ */
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { rmSync, writeFileSync } from 'fs';
+import { join } from 'path';
+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';
+import { hfInventoryRow, loraInventoryRow, localModelInventoryRow } from '../lib/modelInventory.js';
+
+const { TEMP_ROOT } = await vi.hoisted(async () => {
+ const { mkdtempSync } = await import('fs');
+ const { tmpdir } = await import('os');
+ const { join: joinPath } = await import('path');
+ return { TEMP_ROOT: mkdtempSync(joinPath(tmpdir(), 'portos-model-manifest-')) };
+});
+
+vi.mock('../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../lib/fileUtils.js');
+ return makePathsProxy(actual, { dataRoot: TEMP_ROOT });
+});
+
+const {
+ getModelManifest,
+ recordModelInstall,
+ recordModelUninstall,
+ reconcileModelManifest,
+ resetModelManifestCache,
+ trustedInventoryBackends,
+} = await import('./modelManifest.js');
+
+const MANIFEST_PATH = join(TEMP_ROOT, 'model-manifest.json');
+
+const hfRow = (overrides = {}) => ({
+ ...hfInventoryRow({ dirName: 'models--example--repo', name: 'Example (Image)', detail: 'example/repo', sizeBytes: 4096 }),
+ loaded: false,
+ ...overrides,
+});
+
+beforeEach(() => {
+ rmSync(MANIFEST_PATH, { force: true });
+ // The store caches reads; deleting the file behind it would otherwise leave the
+ // previous test's manifest live for the TTL.
+ resetModelManifestCache();
+});
+afterAll(() => rmSync(TEMP_ROOT, { recursive: true, force: true }));
+
+describe('install and uninstall records', () => {
+ it('tracks a model across install, re-install, and uninstall', async () => {
+ const row = loraInventoryRow({ filename: 'lora-example-v1.safetensors', name: 'Example LoRA', sizeBytes: 100 });
+ expect(await recordModelInstall(row)).toBe(true);
+
+ const first = await getModelManifest();
+ expect(first.models).toHaveLength(1);
+ expect(first.models[0]).toMatchObject({
+ id: 'lora:lora-example-v1.safetensors',
+ backend: 'lora',
+ name: 'Example LoRA',
+ sizeBytes: 100,
+ source: 'install',
+ });
+ // Never reconciled, so the page must not read this as a verified inventory.
+ expect(first.reconciledAt).toBeNull();
+
+ // A re-download of the same filename keeps the original install date and
+ // provenance, but does refresh the measured size.
+ await recordModelInstall({ ...row, sizeBytes: 250, source: 'download' });
+ const reinstalled = await getModelManifest();
+ expect(reinstalled.models[0].installedAt).toBe(first.models[0].installedAt);
+ expect(reinstalled.models[0].source).toBe('install');
+ expect(reinstalled.models[0].sizeBytes).toBe(250);
+
+ expect(await recordModelUninstall({ backend: 'lora', key: 'lora-example-v1.safetensors' })).toBe(true);
+ expect((await getModelManifest()).models).toEqual([]);
+ // A second delete of the same row is not a removal — the caller learns that
+ // nothing was there, rather than a success it can report.
+ expect(await recordModelUninstall({ backend: 'lora', key: 'lora-example-v1.safetensors' })).toBe(false);
+ });
+
+ it('stores only durable facts, leaving residency to the read projection', async () => {
+ await recordModelInstall(localModelInventoryRow({ backend: 'ollama', modelId: 'qwen3:8b' }));
+ const [entry] = (await getModelManifest()).models;
+ expect(entry.id).toBe('ollama:qwen3:8b');
+ expect(entry.residencyUnknown).toBe(true);
+ expect(entry.loaded).toBe(false);
+ // `key` is the second half of `id`; storing it too would be a second source of
+ // truth for one string.
+ expect(entry).not.toHaveProperty('key');
+ expect(JSON.parse(String(require('fs').readFileSync(MANIFEST_PATH))).models['ollama:qwen3:8b'])
+ .not.toHaveProperty('residencyUnknown');
+ });
+
+ it('refuses to record a model it cannot identify', async () => {
+ expect(await recordModelInstall(localModelInventoryRow({ backend: 'ollama', modelId: ' ' }))).toBe(false);
+ expect(await recordModelUninstall({ backend: 'unknown-backend', key: 'x' })).toBe(false);
+ expect((await getModelManifest()).models).toEqual([]);
+ });
+
+ it('leaves an unreadable manifest alone rather than replacing it with an empty one', async () => {
+ writeFileSync(MANIFEST_PATH, '{"models": {"hf:models--a--b": ');
+ await expect(getModelManifest()).rejects.toThrow(/unreadable/i);
+ // A best-effort record must not paper over it either: a successful write here
+ // would persist an empty manifest over the bytes, destroying the record.
+ expect(await recordModelInstall(loraInventoryRow({ filename: 'x.safetensors' }))).toBe(false);
+ expect(await reconcileModelManifest([hfRow()], {})).toBeNull();
+ });
+});
+
+describe('reconciliation against a scan', () => {
+ it('adopts models it never installed and drops ones that are gone', async () => {
+ await recordModelInstall(loraInventoryRow({ filename: 'stale.safetensors', name: 'Stale' }));
+ expect(await reconcileModelManifest([hfRow()], {})).toMatchObject({ added: 1, removed: 1 });
+
+ const manifest = await getModelManifest();
+ expect(manifest.models.map((model) => model.id)).toEqual(['hf:models--example--repo']);
+ // `scan` rather than `install`: this row's installedAt is when PortOS first
+ // LOOKED, not when the weights landed, and the page says so.
+ expect(manifest.models[0].source).toBe('scan');
+ expect(manifest.models[0].action).toEqual({ type: 'hf-model', dirName: 'models--example--repo' });
+ expect(manifest.reconciledAt).toEqual(expect.any(String));
+ });
+
+ it('keeps a tracked install date and provenance across a reconcile that re-sees it', async () => {
+ await recordModelInstall({ ...hfRow(), source: 'download' });
+ const installedAt = (await getModelManifest()).models[0].installedAt;
+
+ await reconcileModelManifest([hfRow({ sizeBytes: 9999 })], {});
+ const [entry] = (await getModelManifest()).models;
+ expect(entry).toMatchObject({ installedAt, source: 'download', sizeBytes: 9999 });
+ });
+
+ it('never prunes a backend the scan could not see', async () => {
+ await recordModelInstall(localModelInventoryRow({ backend: 'ollama', modelId: 'qwen3:8b' }));
+ await recordModelInstall(localModelInventoryRow({ backend: 'lmstudio', modelId: 'example/model' }));
+ await recordModelInstall(loraInventoryRow({ filename: 'kept.safetensors', name: 'Kept' }));
+
+ // Ollama disabled in settings, LM Studio unreachable, the LoRA store failed to
+ // read — a scan that reports nothing for any of them is not evidence of
+ // deletion, and pruning on it would erase three correct rows.
+ const result = await reconcileModelManifest([], {
+ sourceErrors: ['lmstudio-backend', 'loras'],
+ disabledSources: ['ollama'],
+ });
+ expect(result).toMatchObject({ added: 0, removed: 0, trusted: ['huggingface'] });
+ expect((await getModelManifest()).models).toHaveLength(3);
+ });
+
+ it('ignores a row whose on-disk folder the scan could not verify', async () => {
+ await reconcileModelManifest([hfRow({ inventoryUnknown: true })], {});
+ expect((await getModelManifest()).models).toEqual([]);
+ });
+
+ it('maps every scan source error to the backend it actually invalidates', () => {
+ expect([...trustedInventoryBackends({})]).toEqual(['huggingface', 'lora', 'ollama', 'lmstudio']);
+ expect([...trustedInventoryBackends({ sourceErrors: ['huggingface'] })]).not.toContain('huggingface');
+ expect([...trustedInventoryBackends({ sourceErrors: ['loras'] })]).not.toContain('lora');
+ expect([...trustedInventoryBackends({ sourceErrors: ['ollama-inventory'] })]).not.toContain('ollama');
+ expect([...trustedInventoryBackends({ sourceErrors: ['lmstudio-backend'] })]).not.toContain('lmstudio');
+ expect([...trustedInventoryBackends({ disabledSources: ['lmstudio'] })]).not.toContain('lmstudio');
+ // A residency probe failure says nothing about what is ON DISK, so it must
+ // not stop a reconcile — the inventory read is a separate source.
+ expect([...trustedInventoryBackends({ sourceErrors: ['ollama-residency', 'lmstudio-residency'] })])
+ .toEqual(['huggingface', 'lora', 'ollama', 'lmstudio']);
+ });
+});
diff --git a/server/services/mtplxModelManager.js b/server/services/mtplxModelManager.js
index 706517b6bd..b4c071758e 100644
--- a/server/services/mtplxModelManager.js
+++ b/server/services/mtplxModelManager.js
@@ -25,8 +25,10 @@ import { bufferedSpawn, spawnFailureDetail } from '../lib/bufferedSpawn.js';
import { ServerError } from '../lib/errorHandler.js';
import { assessDownloadPreflight, assertDownloadFits } from '../lib/downloadPreflight.js';
import { safeJSONParse } from '../lib/fileUtils.js';
-import { getHfCacheRoot } from '../lib/hfCache.js';
+import { getHfCacheRoot, repoToDirName } from '../lib/hfCache.js';
+import { hfInventoryRow } from '../lib/modelInventory.js';
import { listMtplxCachedModels } from '../lib/mtplxModels.js';
+import { recordModelInstall, recordModelUninstall } from './modelManifest.js';
import { findCommandOnPath } from '../lib/processEnv.js';
import { fetchRepoPublishedDates } from './huggingFaceMetadata.js';
import { runStreamingCommand } from '../lib/streamingSpawn.js';
@@ -243,6 +245,19 @@ export async function pullMtplxModel({ model = null, onProgress = () => {} } = {
const cache = await listMtplxCachedModels();
const cached = (cache.models || []).map((m) => m?.repo_id).filter(Boolean);
console.log(`✅ MTPLX pull complete for ${label} (${cached.length} checkpoint(s) cached)`);
+ // MTPLX pulls through huggingface_hub into the standard hub cache (see
+ // `mtplxCachePath`), so what lands here is an ordinary `models--org--name`
+ // directory that Models → Status inventories. Recording it HERE rather than at
+ // the callers covers both entry points — the model-pull route and the
+ // readiness checklist's default-checkpoint fetch — with one seam. A named pull
+ // records itself; the default pull has no repo to name, so the cache listing is
+ // the only thing that knows what arrived.
+ for (const repoId of repo ? [repo] : cached) {
+ await recordModelInstall({
+ ...hfInventoryRow({ dirName: repoToDirName(repoId), name: repoId, detail: repoId, sizeBytes: null }),
+ source: 'download',
+ });
+ }
onProgress({ event: 'complete', model: repo, message: `${label} downloaded` });
return { success: true, model: repo, cachedModels: cached };
}
@@ -279,6 +294,7 @@ export async function removeMtplxModel(model) {
);
}
+ await recordModelUninstall({ backend: 'huggingface', key: repoToDirName(repo) });
console.log(`🗑️ MTPLX checkpoint removed: ${repo}`);
return {
success: true,
diff --git a/server/services/mtplxModelManager.test.js b/server/services/mtplxModelManager.test.js
index d631a67419..7b8b958caf 100644
--- a/server/services/mtplxModelManager.test.js
+++ b/server/services/mtplxModelManager.test.js
@@ -13,6 +13,7 @@ import * as streamingSpawn from '../lib/streamingSpawn.js';
import * as hfMetadata from './huggingFaceMetadata.js';
import * as huggingfaceLora from '../lib/huggingfaceLora.js';
import * as hfToken from './hfToken.js';
+import * as modelManifest from './modelManifest.js';
const BINARY = '/opt/homebrew/bin/mtplx';
@@ -29,6 +30,10 @@ describe('mtplxModelManager', () => {
vi.spyOn(huggingfaceLora, 'fetchHuggingfaceModel').mockResolvedValue({ usedStorage: 0 });
vi.spyOn(console, 'log').mockImplementation(() => {});
vi.spyOn(console, 'error').mockImplementation(() => {});
+ // The manifest write is real file IO against the install's data root; doubled
+ // so it can be asserted rather than reaching disk.
+ vi.spyOn(modelManifest, 'recordModelInstall').mockResolvedValue(true);
+ vi.spyOn(modelManifest, 'recordModelUninstall').mockResolvedValue(true);
});
describe('isMtplxRepoId', () => {
@@ -227,4 +232,55 @@ describe('mtplxModelManager', () => {
await expect(removeMtplxModel('Example/Qwen-MTP')).rejects.toThrow(/error: model not cached/);
});
});
+ // MTPLX pulls through huggingface_hub into the standard HF hub cache, so a
+ // checkpoint it fetches shows up in the Models → Status inventory like any other
+ // `models--org--name` directory. Recording lives in this manager because BOTH
+ // entry points reach it — the model-pull route and the readiness checklist's
+ // default-checkpoint fetch — and neither would have recorded on its own.
+ describe('model manifest', () => {
+ it('records a named pull under its HF cache directory', async () => {
+ vi.spyOn(streamingSpawn, 'runStreamingCommand').mockResolvedValue({ success: true });
+
+ await pullMtplxModel({ model: 'Example/Qwen-MTP' });
+
+ expect(modelManifest.recordModelInstall).toHaveBeenCalledWith(expect.objectContaining({
+ id: 'hf:models--Example--Qwen-MTP',
+ backend: 'huggingface',
+ action: { type: 'hf-model', dirName: 'models--Example--Qwen-MTP' },
+ source: 'download',
+ }));
+ });
+
+ it('records what actually landed when the default checkpoint was pulled by no name', async () => {
+ vi.spyOn(streamingSpawn, 'runStreamingCommand').mockResolvedValue({ success: true });
+ mtplxModels.listMtplxCachedModels.mockResolvedValue({
+ models: [{ repo_id: 'Example/Default-MTP' }], error: null,
+ });
+
+ await pullMtplxModel({});
+
+ expect(modelManifest.recordModelInstall).toHaveBeenCalledWith(expect.objectContaining({
+ id: 'hf:models--Example--Default-MTP',
+ }));
+ });
+
+ it('records nothing when the pull failed', async () => {
+ vi.spyOn(streamingSpawn, 'runStreamingCommand').mockResolvedValue({ success: false, error: 'network' });
+
+ await pullMtplxModel({ model: 'Example/Qwen-MTP' });
+
+ expect(modelManifest.recordModelInstall).not.toHaveBeenCalled();
+ });
+
+ it('clears the entry when a checkpoint is removed', async () => {
+ vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockResolvedValue(spawnOk(JSON.stringify({ removed: true, size_bytes_removed: 10 })));
+
+ await removeMtplxModel('Example/Qwen-MTP');
+
+ expect(modelManifest.recordModelUninstall).toHaveBeenCalledWith({
+ backend: 'huggingface',
+ key: 'models--Example--Qwen-MTP',
+ });
+ });
+ });
});
diff --git a/server/services/systemResources.js b/server/services/systemResources.js
index ed85cb0197..7039cb97b0 100644
--- a/server/services/systemResources.js
+++ b/server/services/systemResources.js
@@ -25,6 +25,13 @@ import * as lmStudioManager from './lmStudioManager.js';
import { getQueueCapacity } from './mediaJobQueue/index.js';
import * as cos from './cos.js';
import { getSettings } from './settings.js';
+import {
+ hfInventoryRow,
+ localModelInventoryRow,
+ loraInventoryRow,
+ modelInventoryId,
+} from '../lib/modelInventory.js';
+import { getModelManifest, reconcileModelManifest } from './modelManifest.js';
export const REPORT_CACHE_TTL_MS = 30_000;
@@ -99,7 +106,18 @@ function dataCleanupCandidates(categories) {
});
}
-function modelCleanupCandidates(downloaded) {
+/**
+ * The cleanup candidate for each downloaded-model row.
+ *
+ * Exported because the manifest-backed inventory (`getTrackedModelInventory`)
+ * has to describe its rows exactly as a scan would — the Status page renders both
+ * through one component, and a second copy of this risk/`manualOnly` logic is how
+ * a delete button ends up armed on a tracked row the scan would have refused.
+ *
+ * @param {Array<Object>} downloaded Downloaded-model inventory rows
+ * @returns {Array<Object>}
+ */
+export function modelCleanupCandidates(downloaded) {
return downloaded.map((model) => ({
id: model.id,
label: model.name,
@@ -178,29 +196,23 @@ function downloadedModelInventory({
normalizeLmStudioRepo(model.id),
]).filter(Boolean));
+ // The durable half of every row comes from the shared builders in
+ // `lib/modelInventory.js`, which the install chokepoints call too — so a row's
+ // risk, manage path, delete action and cleanup sentence cannot drift between the
+ // scan and the manifest. Only the LIVE half (residency, whether the on-disk
+ // folder could be verified) is added here, because only a scan can know it.
const huggingFace = (hf?.models || []).map((model) => ({
- id: `hf:${model.id}`,
- backend: 'huggingface',
- name: model.label || model.repo,
- detail: model.repo,
- sizeBytes: model.size,
- sizeIsEstimate: false,
+ ...hfInventoryRow({
+ dirName: model.id,
+ name: model.label || model.repo,
+ detail: model.repo,
+ sizeBytes: model.size,
+ }),
loaded: false,
- managePath: '/models/media',
- action: { type: 'hf-model', dirName: model.id },
}));
const loras = (loraStorage?.loras || []).map((model) => ({
- id: `lora:${model.filename}`,
- backend: 'lora',
- name: model.name,
- detail: 'LoRA adapter',
- sizeBytes: model.size,
- sizeIsEstimate: false,
- risk: 'high',
- cleanupReason: 'A trained or imported LoRA adapter may be the only copy and can take hours to reproduce.',
+ ...loraInventoryRow({ filename: model.filename, name: model.name, sizeBytes: model.size }),
loaded: false,
- managePath: '/models/loras',
- action: { type: 'lora', filename: model.filename },
}));
const ollamaApi = new Map((ollamaStatus?.models || []).map((model) => [model.id, model]));
const ollamaDiskModels = Array.isArray(ollamaStored) ? ollamaStored : [];
@@ -212,21 +224,18 @@ function downloadedModelInventory({
const ollama = ollamaRows.map((stored) => {
const model = ollamaApi.get(stored.id) || stored;
return {
- id: `ollama:${stored.id}`,
- backend: 'ollama',
- name: model.name || stored.name || stored.id,
- detail: [model.params, model.quantization, model.family].filter(Boolean).join(' · '),
- sizeBytes: finiteOrNull(stored.size ?? model.size),
- // Ollama layers can be shared between tags, so the per-model size is an
- // upper-bound estimate rather than guaranteed reclaimed bytes.
- sizeIsEstimate: true,
+ ...localModelInventoryRow({
+ backend: 'ollama',
+ modelId: stored.id,
+ name: model.name || stored.name || stored.id,
+ detail: [model.params, model.quantization, model.family].filter(Boolean).join(' · '),
+ sizeBytes: finiteOrNull(stored.size ?? model.size),
+ // A backend that is not running cannot be asked to delete anything.
+ deletable: Boolean(ollamaStatus?.available),
+ }),
loaded: !ollamaResidencyError && ollamaLoadedIds.has(stored.id),
residencyUnknown: Boolean(ollamaResidencyError),
inventoryUnknown: !Array.isArray(ollamaStored) || Boolean(stored.inventoryUnknown),
- managePath: '/models/llms',
- action: ollamaStatus?.available
- ? { type: 'local-model', backend: 'ollama', modelId: stored.id }
- : null,
};
});
@@ -261,21 +270,22 @@ function downloadedModelInventory({
|| group?.models.some((model) => model.state === 'loaded')
);
return {
- id: `lmstudio:${stored.id}`,
- backend: 'lmstudio',
- name: stored.name || stored.id,
- detail: [
- quantizations.length ? `${quantizations.length} quantization${quantizations.length === 1 ? '' : 's'}: ${quantizations.join(', ')}` : null,
- 'removes the whole model folder',
- ].filter(Boolean).join(' · '),
- sizeBytes: finiteOrNull(stored.size),
+ ...localModelInventoryRow({
+ backend: 'lmstudio',
+ modelId: stored.id,
+ name: stored.name || stored.id,
+ detail: [
+ quantizations.length ? `${quantizations.length} quantization${quantizations.length === 1 ? '' : 's'}: ${quantizations.join(', ')}` : null,
+ 'removes the whole model folder',
+ ].filter(Boolean).join(' · '),
+ sizeBytes: finiteOrNull(stored.size),
+ }),
+ // A row the API reported but the disk listing did not is sized from the
+ // API's own number, which is a claim rather than a measurement.
sizeIsEstimate: Boolean(stored.inventoryUnknown),
loaded,
residencyUnknown: Boolean(lmStudioResidencyError),
inventoryUnknown: !Array.isArray(lmStudioStored) || Boolean(stored.inventoryUnknown),
- cleanupReason: 'Deleting this entry removes the whole LM Studio model folder, including every downloaded quantization in it.',
- managePath: '/models/llms',
- action: { type: 'local-model', backend: 'lmstudio', modelId: stored.id },
};
});
return [...huggingFace, ...loras, ...ollama, ...lmstudio]
@@ -285,14 +295,14 @@ function downloadedModelInventory({
function loadedModelInventory({ ollamaLoaded, lmStudioLoaded }) {
return [
...(ollamaLoaded || []).map((model) => ({
- id: `ollama:${model.id}`,
+ id: modelInventoryId('ollama', model.id),
backend: 'ollama',
name: model.name || model.id,
memoryBytes: finiteOrNull(model.sizeVram ?? model.size),
expiresAt: model.expiresAt || null,
})),
...(lmStudioLoaded || []).map((model) => ({
- id: `lmstudio:${model.id}`,
+ id: modelInventoryId('lmstudio', model.id),
backend: 'lmstudio',
name: model.id,
memoryBytes: null,
@@ -504,8 +514,17 @@ export async function buildSystemResourceReport() {
? agentQueue.pendingUser + agentQueue.pendingSystem
: 0;
+ // Every full scan heals the persisted manifest, so Models → Status has a fresh
+ // answer to fall back on next time without walking the model stores again, and
+ // weights installed or deleted outside PortOS get picked up. Scoped to the
+ // backends this scan could actually see — `reconcileModelManifest` will not
+ // prune against a disabled or unreachable one.
+ const manifest = await reconcileModelManifest(downloadedModels, { sourceErrors, disabledSources });
+
return {
generatedAt: new Date().toISOString(),
+ inventorySource: 'scan',
+ manifestReconciledAt: manifest?.reconciledAt || null,
filesystem,
summary: {
knownFootprintBytes: sumKnownBytes(storageAreas.map((area) => area.sizeBytes)),
@@ -577,6 +596,52 @@ export function getSystemResourceReport({ force = false } = {}) {
return reportInFlight;
}
+/**
+ * The downloaded-model inventory as the manifest already knows it — no disk scan.
+ *
+ * This is what Models → Status loads on arrival. It is shaped as a PARTIAL system
+ * resource report rather than a bespoke payload so the page renders it through the
+ * same component that renders a live scan: the two differ in `inventorySource` and
+ * in the fields a scan alone can supply (residency, duplicates, per-store totals
+ * for stores whose rows the manifest may not cover).
+ *
+ * `reconciledAt: null` means no scan has ever reconciled this install — the page
+ * shows its "run the inventory" prompt rather than claiming an empty machine.
+ *
+ * @returns {Promise<Object>} Partial report: `{ inventorySource: 'manifest', … }`
+ */
+export async function getTrackedModelInventory() {
+ const manifest = await getModelManifest();
+ const downloaded = manifest.models;
+ // `sumKnownBytes` already answers null for a list with no finite sizes, which
+ // covers a backend with no tracked rows at all.
+ const backendTotal = (backend) => sumKnownBytes(
+ downloaded.filter((model) => model.backend === backend).map((model) => model.sizeBytes),
+ );
+ return {
+ inventorySource: 'manifest',
+ generatedAt: manifest.reconciledAt,
+ reconciledAt: manifest.reconciledAt,
+ models: {
+ downloaded,
+ loaded: [],
+ totals: {
+ huggingface: backendTotal('huggingface'),
+ loras: backendTotal('lora'),
+ ollama: backendTotal('ollama'),
+ lmstudio: backendTotal('lmstudio'),
+ all: sumKnownBytes(downloaded.map((model) => model.sizeBytes)),
+ },
+ },
+ cleanupCandidates: modelCleanupCandidates(downloaded),
+ // A duplicate-weight scan is exactly the expensive walk this endpoint exists to
+ // avoid, so the panel renders nothing for it until the user asks for a refresh.
+ modelDuplicates: null,
+ sourceErrors: [],
+ disabledSources: [],
+ };
+}
+
export function buildSystemResourceTriagePrompt(report) {
const candidates = report.cleanupCandidates.slice(0, 50).map((candidate, index) => ({
// Deliberately opaque. A model id or LoRA filename can contain a personal
diff --git a/server/services/systemResources.test.js b/server/services/systemResources.test.js
index 4c44d92cf1..9db955fee9 100644
--- a/server/services/systemResources.test.js
+++ b/server/services/systemResources.test.js
@@ -93,6 +93,13 @@ vi.mock('./cos.js', () => ({
vi.mock('./settings.js', () => ({
getSettings: vi.fn(async () => ({})),
}));
+// The manifest is the report's persistence side effect, and its real writer needs
+// JSON helpers the fileUtils mock above deliberately omits. Doubled so the
+// reconcile call can be asserted rather than swallowed by its best-effort catch.
+vi.mock('./modelManifest.js', () => ({
+ getModelManifest: vi.fn(async () => ({ reconciledAt: null, models: [] })),
+ reconcileModelManifest: vi.fn(async () => ({ reconciledAt: '2026-08-16T00:00:00.000Z', added: 0, removed: 0, trusted: [] })),
+}));
const promptRunner = await import('./promptRunner.js');
const fsPromises = await import('fs/promises');
@@ -104,10 +111,12 @@ const ollamaManager = await import('./ollamaManager.js');
const lmStudioManager = await import('./lmStudioManager.js');
const cos = await import('./cos.js');
const settings = await import('./settings.js');
+const modelManifest = await import('./modelManifest.js');
const {
buildCleanupCandidates,
buildSystemResourceReport,
buildSystemResourceTriagePrompt,
+ getTrackedModelInventory,
resetSystemResourceReportCache,
triageSystemResources,
} = await import('./systemResources.js');
@@ -318,3 +327,75 @@ describe('system resource reporting', () => {
expect(result.triage.recommendations[0].candidateId).toBe('data:cache');
});
});
+
+/**
+ * The manifest side of the report: a scan heals the persisted inventory, and the
+ * persisted inventory is what the Status page renders when no scan has run.
+ */
+describe('tracked model inventory', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetSystemResourceReportCache();
+ modelManifest.reconcileModelManifest.mockResolvedValue({
+ reconciledAt: '2026-08-16T00:00:00.000Z', added: 0, removed: 0, trusted: [],
+ });
+ });
+
+ it('reconciles the manifest from every scan, carrying the scan\'s own trust signals', async () => {
+ settings.getSettings.mockResolvedValue({ localLlm: { lmstudio: { disabled: true } } });
+ const report = await buildSystemResourceReport();
+
+ const [rows, trust] = modelManifest.reconcileModelManifest.mock.calls[0];
+ expect(rows).toBe(report.models.downloaded);
+ // Without these the reconcile would prune a disabled or unreachable backend's
+ // rows against a scan that could never have listed them.
+ expect(trust.disabledSources).toContain('lmstudio');
+ expect(trust.sourceErrors).toEqual(report.sourceErrors);
+ expect(report).toMatchObject({ inventorySource: 'scan', manifestReconciledAt: '2026-08-16T00:00:00.000Z' });
+ });
+
+ it('still returns a report when the manifest could not be written', async () => {
+ modelManifest.reconcileModelManifest.mockResolvedValue(null);
+ const report = await buildSystemResourceReport();
+ expect(report.manifestReconciledAt).toBeNull();
+ expect(report.models.downloaded.length).toBeGreaterThan(0);
+ });
+
+ it('serves the manifest as a scan-shaped report, with the same cleanup candidates', async () => {
+ modelManifest.getModelManifest.mockResolvedValue({
+ reconciledAt: '2026-08-16T00:00:00.000Z',
+ models: [
+ {
+ id: 'hf:models--example--public', backend: 'huggingface', key: 'models--example--public',
+ name: 'example/public', sizeBytes: 700, loaded: false, residencyUnknown: false, inventoryUnknown: false,
+ managePath: '/models/media', action: { type: 'hf-model', dirName: 'models--example--public' },
+ },
+ {
+ id: 'ollama:example:latest', backend: 'ollama', key: 'example:latest', name: 'Example',
+ sizeBytes: 100, loaded: false, residencyUnknown: true, inventoryUnknown: false,
+ managePath: '/models/llms', action: { type: 'local-model', backend: 'ollama', modelId: 'example:latest' },
+ },
+ ],
+ });
+
+ const inventory = await getTrackedModelInventory();
+ expect(inventory).toMatchObject({ inventorySource: 'manifest', reconciledAt: '2026-08-16T00:00:00.000Z' });
+ expect(inventory.models.totals).toMatchObject({ huggingface: 700, ollama: 100, lmstudio: null, all: 800 });
+ // No scan means no residency probe, so the local row must stay un-armed: a
+ // one-click delete offered off the record alone could remove loaded weights.
+ const [hf, ollama] = inventory.cleanupCandidates;
+ expect(hf).toMatchObject({ id: 'hf:models--example--public', manualOnly: false, action: { type: 'hf-model', dirName: 'models--example--public' } });
+ expect(ollama).toMatchObject({ id: 'ollama:example:latest', manualOnly: true, action: null });
+ // And the duplicate-weight scan — the most expensive walk of them all — is
+ // never run for a manifest read.
+ expect(inventory.modelDuplicates).toBeNull();
+ });
+
+ it('reports a never-reconciled install as unverified rather than empty', async () => {
+ modelManifest.getModelManifest.mockResolvedValue({ reconciledAt: null, models: [] });
+ const inventory = await getTrackedModelInventory();
+ expect(inventory.reconciledAt).toBeNull();
+ expect(inventory.models.downloaded).toEqual([]);
+ expect(inventory.models.totals.all).toBeNull();
+ });
+});