Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
manage MTPLX model weights from the UI instead of a terminal
Adam Eivy1f56ea331ec8
diff --git a/PRD.md b/PRD.mdindex 499a666628..1ab0933245 100644--- a/PRD.md+++ b/PRD.md@@ -56,6 +56,7 @@ Reused verbatim (condensed to objective statements) from [GOALS.md](./GOALS.md)'| FR-2 | The system MUST manage PM2-backed app lifecycle actions (start/stop/restart/update/build/status/logs). | Must | Each lifecycle action returns success/failure state and streams logs for the target app within its running duration. || FR-3 | The system MUST detect port conflicts against the canonical `PORTS` registry before allocation. | Must | Requesting a port already claimed by another app returns a conflict, not a silent overwrite. || FR-4 | The system SHOULD expose configurable system-health thresholds. | Should | `PUT /api/system/health/thresholds` persists new thresholds and subsequent `GET /api/system/health` checks use them. |+| FR-59 | The system MUST provide in-app UI for the full lifecycle of every local runtime it supports and every model that runtime needs — install/uninstall the runtime, search a catalog, download a model, and remove a downloaded model — with progress surfaced live. A user MUST never be told to run a shell command to complete one of these steps. | Must | For each supported local runtime (Ollama, LM Studio, llama.cpp, MTPLX), the UI offers install, start/stop, model search, model download with byte progress, and model removal; no user-facing empty/blocked state names a terminal command as its remedy. |### AI Agent Orchestration (CoS)@@ -190,6 +191,7 @@ Reused verbatim (condensed to objective statements) from [GOALS.md](./GOALS.md)'| NFR-13 | Compatibility | PostgreSQL (with pgvector) MUST be treated as a mandatory dependency for every install and federated peer — the file-backed memory mode MUST remain a test-only escape hatch, never a supported deployment fallback. || NFR-14 | Compatibility | The system MUST run correctly across independently-upgrading installs and forks — no feature may assume all peers are on the same code version. || NFR-15 | Cost | The system MUST be operable primarily on flat-rate AI provider subscriptions rather than requiring metered per-token billing for normal (non-power-user) operation, consistent with the project's stated cost philosophy. |+| NFR-16 | Usability | Any operation PortOS is capable of performing on the user's behalf MUST be reachable from the UI. When a state blocks a workflow (a missing binary, an empty model cache, an unprovisioned dependency), the message MUST name the in-app control that resolves it — never a command for the user to type. |---@@ -205,6 +207,7 @@ Reused verbatim (condensed to objective statements) from [GOALS.md](./GOALS.md)'| NR-6 | The system MUST NOT add CORS restrictions, request-level rate limiting, or cross-actor concurrency defenses (mutex/atomic-write races) as protection against competing human actors within one install. | The trust model is one human per install on a private Tailnet — these defenses solve a problem PortOS doesn't have and add maintenance surface. || NR-7 | The system MUST NOT treat leakage of a free, non-monetary third-party API key (e.g. CivitAI) to an unintended host as a security finding requiring host-allowlisting or key-stripping. | Won't-fix precedent (#2200): worst case is quota abuse against a free service, borne by that service — no monetary loss or meaningful security consequence. Does not extend to paid/quota-billed providers or money-bearing/destructive-action keys, which retain full hardening requirements. || NR-8 | The system MUST NOT send an AI-drafted outbound message (email, social post) without explicit user review-and-approve, regardless of how confident the draft is. | Full digital autonomy (Goal 8) extends to task execution, not to irreversible outward-facing communication acting under the user's identity without a human gate. |+| NR-9 | The system MUST NOT instruct the user to run a shell/terminal command in order to complete a workflow PortOS can perform itself — including installing or removing a runtime, and searching for, downloading, or deleting a model. Blocked-state copy points at the in-app control, not at a command line. | PortOS is the control surface for the machine; sending the user to a terminal for one step of an otherwise-managed lifecycle is a dead end that breaks remote/mobile use (Anywhere Access) and leaves the app's own state stale. **Carve-out:** genuinely privileged one-time host setup PortOS deliberately refuses to perform (`pm2 startup`, `sudo` fan-control helpers, `gcloud auth login`) may be named as an operator step — the refusal must be deliberate and documented, not a gap in the UI. |---diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 96aa75d94b..d890207cff 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -12,6 +12,7 @@ import {deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService,installAudioModel, patchSettingsSlice, getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer,downloadSpecDecodeModel, controlLmStudioService, getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx,+ searchMtplxModels, pullMtplxModel, removeMtplxModel,saveRuntimeStartupList} from '../../services/api';import socket from '../../services/socket';@@ -357,6 +358,10 @@ export function LocalLlmTab() {const [llamaStatus, setLlamaStatus] = useState(null);const [mtplxStatus, setMtplxStatus] = useState(null);+ // Live byte progress for an in-flight `mtplx pull`, driven by the socket. One+ // at a time on purpose: a checkpoint is tens of gigabytes, so two concurrent+ // pulls just make both slower.+ const [mtplxDownload, setMtplxDownload] = useState(null);const [llamaLoading, setLlamaLoading] = useState(false);// Anchor for the unified server card's "Configure" action — llama-server needs// a model path, so its Start lives in the launcher rather than in that row.@@ -515,6 +520,31 @@ export function LocalLlmTab() {socket.on('llamaServer:download', handleDownloadProgress);return () => socket.off('llamaServer:download', handleDownloadProgress);}, [loadLlamaStatus]);++ // MTPLX checkpoint download progress. A pull can run for hours, so the socket+ // — not the still-open HTTP request — is what the UI trusts: a terminal frame+ // clears the bar AND re-reads the cache, so the list is right even if the+ // request itself never comes back.+ useEffect(() => {+ const handleMtplxDownload = (frame) => {+ if (!frame) return;+ if (frame.event === 'complete' || frame.event === 'error' || frame.event === 'cancelled') {+ setMtplxDownload(null);+ loadMtplxStatus();+ return;+ }+ setMtplxDownload((prev) => ({+ model: frame.model || prev?.model || null,+ // A frame without byte counters (`resolving`, `verifying`) must not+ // reset a bar that already has them — keep the last known numbers.+ received: Number.isFinite(frame.received) ? frame.received : (prev?.received ?? 0),+ total: Number.isFinite(frame.total) ? frame.total : (prev?.total ?? 0),+ message: frame.message || prev?.message || null,+ }));+ };+ socket.on('mtplx:download', handleMtplxDownload);+ return () => socket.off('mtplx:download', handleMtplxDownload);+ }, [loadMtplxStatus]);// Debounce so typing in the search box doesn't fire a request per keystroke.//// `activeCategory` is a trigger for the Hugging Face source ONLY — the live@@ -650,6 +680,29 @@ export function LocalLlmTab() {() => stopMtplxServer(),(r) => r?.message || 'MTPLX stopped').then(loadMtplxStatus);+ // Checkpoint management. The pull resolves only when the weights are on disk;+ // byte progress arrives on `mtplx:download` (subscribed below), so the button+ // spinner is not the only sign of life during a multi-gigabyte transfer.+ // Stable identity: the checkpoint panel keys its initial load on this, and the+ // status poll re-renders this component every few seconds.+ const mtplxSearch = useCallback((params) => searchMtplxModels(params, { silent: true })+ .catch((err) => ({ models: [], error: err?.message || 'Search failed' })), []);+ const mtplxPull = (model) => runAction(+ model ? `mtplx-pull-${model}` : 'mtplx-pull',+ () => pullMtplxModel(model),+ (r) => (r?.success ? `${r.model || 'Default checkpoint'} downloaded` : null),+ ).then((r) => {+ setMtplxDownload(null);+ // A pull that exits non-zero resolves rather than throwing, so its reason+ // has to be surfaced here — `runAction`'s success toast can't tell.+ if (r && r.success === false) toast.error(`Download failed: ${r.error}`);+ return loadMtplxStatus();+ });+ const mtplxRemove = (model) => runAction(+ `mtplx-remove-${model}`,+ () => removeMtplxModel(model),+ (r) => `${r?.model || model} removed${r?.bytesFreed ? ` — ${formatBytes(r.bytesFreed)} freed` : ''}`,+ ).then(loadMtplxStatus);const saveRuntimeStartup = () => runAction('runtime-save-startup',() => saveRuntimeStartupList(),@@ -1135,6 +1188,10 @@ export function LocalLlmTab() {onStart={runtimeStartMtplx}onStop={runtimeStopMtplx}onInstall={runtimeInstallMtplx}+ onSearchModels={mtplxSearch}+ onPullModel={mtplxPull}+ onRemoveModel={mtplxRemove}+ download={mtplxDownload}/></div>diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsxindex 6a42760a15..f5f217d012 100644--- a/client/src/components/settings/LocalLlmTab.test.jsx+++ b/client/src/components/settings/LocalLlmTab.test.jsx@@ -18,6 +18,10 @@ vi.mock('../../services/api', () => ({startMtplxServer: vi.fn(),stopMtplxServer: vi.fn(),installMtplx: vi.fn(),+ // The MTPLX card's checkpoint panel loads upstream's default listing on mount.+ searchMtplxModels: vi.fn().mockResolvedValue({ models: [], error: null }),+ pullMtplxModel: vi.fn(),+ removeMtplxModel: vi.fn(),saveRuntimeStartupList: vi.fn(),installAudioModel: vi.fn(),patchSettingsSlice: vi.fn(),@@ -49,6 +53,11 @@ const renderTab = async () => {</MemoryRouter>,);await waitFor(() => expect(screen.getByText(/Installed on Ollama/)).toBeTruthy());+ // The MTPLX checkpoint panel only mounts once the MTPLX status resolves, and+ // it then fetches its default listing — two chained awaits, so flush twice so+ // both state updates land inside act().+ await act(async () => {});+ await act(async () => {});};beforeEach(() => {diff --git a/client/src/components/settings/MtplxCheckpoints.jsx b/client/src/components/settings/MtplxCheckpoints.jsxnew file mode 100644index 0000000000..29971453bc--- /dev/null+++ b/client/src/components/settings/MtplxCheckpoints.jsx@@ -0,0 +1,251 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { Download, HardDrive, RefreshCw, Search, Trash2, CheckCircle2, AlertTriangle } from 'lucide-react';+import BrailleSpinner from '../BrailleSpinner';+import ConfirmButtonPair from '../ui/ConfirmButtonPair';+import { useConfirmDelete } from '../../hooks/useConfirmDelete';+import { formatBytes } from '../../utils/formatters';++/**+ * MTPLX checkpoint manager — search, download, and remove MTP model weights.+ *+ * This replaces the card's old answer to an empty cache, which was to print+ * `mtplx pull` and tell the user to go run it in a terminal. PortOS installs the+ * runtime, starts it, stops it, logs it, and persists it across a reboot; making+ * the one step in the middle a shell command the user has to leave the app for+ * was the odd one out (PRD NR-9).+ *+ * A download is still never implicit: it moves tens of gigabytes and only runs+ * from a button pressed here that names what it will fetch.+ *+ * The search source is `mtplx forge discover`, upstream's index of MTPLX-branded+ * checkpoints — deliberately not a raw Hugging Face search, which would mostly+ * offer models that download for an hour and then fail MTPLX's file check.+ */++const btn = 'flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium rounded-lg transition-colors disabled:opacity-50';+const accentBtn = `${btn} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`;+const neutralBtn = `${btn} bg-port-border hover:bg-port-border/70 text-white`;+const dangerBtn = `${btn} bg-port-error/10 hover:bg-port-error/20 text-port-error`;++/** A pull frame carries bytes only once the transfer starts — show what we have. */+function ProgressBar({ download }) {+ const { received = 0, total = 0, message } = download;+ const pct = total > 0 ? Math.min(100, Math.round((received / total) * 100)) : null;+ return (+ <div className="space-y-1">+ <div className="h-1.5 bg-port-border rounded overflow-hidden">+ <div+ className={`h-full bg-port-accent transition-all ${pct === null ? 'animate-pulse w-1/3' : ''}`}+ style={pct === null ? undefined : { width: `${pct}%` }}+ />+ </div>+ <p className="text-[11px] text-gray-500">+ {pct === null+ ? (message || 'Downloading…')+ : `${formatBytes(received)} of ${formatBytes(total)} (${pct}%)`}+ </p>+ </div>+ );+}++export default function MtplxCheckpoints({+ cached,+ cacheError,+ download,+ busy,+ actionInProgress,+ onSearch,+ onPull,+ onRemove,+}) {+ const [query, setQuery] = useState('');+ const [results, setResults] = useState(null);+ const [searchError, setSearchError] = useState(null);+ const [searching, setSearching] = useState(false);+ // Shared single-at-a-time arm/confirm state — arming a second row disarms the+ // first, and nothing reaches `window.confirm`.+ const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();++ const cachedRepos = new Set(cached.map((row) => row.repo));++ const runSearch = useCallback((text) => {+ setSearching(true);+ setSearchError(null);+ return onSearch({ query: text })+ .then((res) => {+ // `error` is MTPLX's own reason (offline, rate-limited) — surface it+ // rather than rendering an empty list that reads as "nothing exists".+ setSearchError(res?.error || null);+ setResults(res?.models || []);+ })+ .finally(() => setSearching(false));+ }, [onSearch]);++ // Load upstream's default listing once, so an empty cache lands on something+ // to click instead of an empty box with a search field. One HTTP call to+ // Hugging Face — no weights, no model load.+ //+ // Guarded by a ref rather than by `runSearch`'s identity: the parent re-renders+ // on every status poll, and a dep-driven effect would re-hit Hugging Face on+ // each one.+ const didInitialSearch = useRef(false);+ useEffect(() => {+ if (didInitialSearch.current) return;+ didInitialSearch.current = true;+ runSearch('');+ }, [runSearch]);++ const pulling = Boolean(download);++ return (+ <div className="space-y-4">+ <div className="space-y-2">+ <div className="flex items-center justify-between gap-2">+ <h3 className="text-xs font-medium text-gray-300 flex items-center gap-1.5">+ <HardDrive size={12} className="text-port-accent" />+ Cached checkpoints+ </h3>+ {cached.length > 0 && (+ <span className="text-[11px] text-gray-500">+ {formatBytes(cached.reduce((sum, row) => sum + (row.sizeBytes || 0), 0))} on disk+ </span>+ )}+ </div>++ {cacheError ? (+ <p className="text-xs text-gray-500">Couldn't read MTPLX's model cache ({cacheError}).</p>+ ) : cached.length === 0 ? (+ <div className="bg-port-warning/10 border border-port-warning/30 rounded-lg p-3 space-y-2">+ <p className="text-xs text-port-warning">+ MTPLX has no checkpoints yet, so its server exits before it binds a port. Download one below — MTPLX's own verified default is the safe pick.+ </p>+ <button onClick={() => onPull(null)} disabled={busy || pulling} className={accentBtn}>+ {actionInProgress === 'mtplx-pull' ? <BrailleSpinner /> : <Download size={13} />}+ Download default checkpoint+ </button>+ </div>+ ) : (+ <ul className="space-y-1.5">+ {cached.map((row) => (+ <li key={row.repo} className="flex flex-col sm:flex-row sm:items-center gap-2 bg-port-bg border border-port-border rounded-lg px-3 py-2">+ <div className="min-w-0 flex-1">+ <p className="text-xs text-white truncate">{row.repo}</p>+ <p className="text-[11px] text-gray-500 flex items-center gap-1.5 flex-wrap">+ {row.sizeBytes ? <span>{formatBytes(row.sizeBytes)}</span> : null}+ {row.valid === false ? (+ <span className="text-port-warning flex items-center gap-1">+ <AlertTriangle size={10} /> incomplete — remove and download again+ </span>+ ) : row.hasRuntimeContract ? (+ <span className="text-port-success flex items-center gap-1">+ <CheckCircle2 size={10} /> verified MTP contract+ </span>+ ) : null}+ </p>+ </div>+ {isConfirming(row.repo) ? (+ <ConfirmButtonPair+ className="shrink-0"+ prompt="Delete these weights?"+ confirmIcon={Trash2}+ busy={actionInProgress === `mtplx-remove-${row.repo}`}+ busyText="Deleting"+ onConfirm={() => confirmDelete(() => onRemove(row.repo))}+ onCancel={cancelDelete}+ ariaLabel={`Confirm removing ${row.repo}`}+ />+ ) : (+ <button+ onClick={() => requestDelete(row.repo)}+ disabled={busy}+ className={`${dangerBtn} shrink-0`}+ title={`Delete ${row.repo} from MTPLX's cache`}+ >+ <Trash2 size={12} />+ Remove+ </button>+ )}+ </li>+ ))}+ </ul>+ )}+ </div>++ {download && (+ <div className="bg-port-bg border border-port-border rounded-lg p-3 space-y-2">+ <p className="text-xs text-gray-300 truncate">+ Downloading <code className="text-port-accent">{download.model || 'MTPLX default checkpoint'}</code>+ </p>+ <ProgressBar download={download} />+ <p className="text-[11px] text-gray-500">This runs in the background — leaving this page won't cancel it.</p>+ </div>+ )}++ <div className="space-y-2">+ <h3 className="text-xs font-medium text-gray-300 flex items-center gap-1.5">+ <Search size={12} className="text-port-accent" />+ Find a checkpoint+ </h3>+ <form+ className="flex items-center gap-2"+ onSubmit={(e) => { e.preventDefault(); runSearch(query); }}+ >+ <label htmlFor="mtplx-model-search" className="sr-only">Search MTPLX checkpoints</label>+ <input+ id="mtplx-model-search"+ type="search"+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ placeholder="Search MTPLX-branded models on Hugging Face…"+ className="flex-1 min-w-0 bg-port-card border border-port-border rounded px-2 py-1.5 text-xs text-white"+ />+ <button type="submit" disabled={searching} className={neutralBtn}>+ {searching ? <BrailleSpinner /> : <RefreshCw size={12} />}+ Search+ </button>+ </form>++ {searchError && <p className="text-xs text-port-warning">{searchError}</p>}++ {results !== null && results.length === 0 && !searchError && (+ <p className="text-xs text-gray-500">No MTPLX-branded checkpoints matched that search.</p>+ )}++ {results !== null && results.length > 0 && (+ <ul className="space-y-1.5 max-h-72 overflow-y-auto">+ {results.map((row) => {+ const installed = cachedRepos.has(row.repo);+ return (+ <li key={row.repo} className="flex flex-col sm:flex-row sm:items-center gap-2 bg-port-bg border border-port-border rounded-lg px-3 py-2">+ <div className="min-w-0 flex-1">+ <p className="text-xs text-white truncate">{row.name}</p>+ <p className="text-[11px] text-gray-500 truncate">+ {row.repo}+ {Number.isFinite(row.downloads) ? ` · ${row.downloads.toLocaleString()} downloads` : ''}+ {row.license ? ` · ${row.license}` : ''}+ </p>+ </div>+ {installed ? (+ <span className="text-[11px] text-port-success shrink-0 flex items-center gap-1">+ <CheckCircle2 size={11} /> Cached+ </span>+ ) : (+ <button+ onClick={() => onPull(row.repo)}+ disabled={busy || pulling}+ className={`${accentBtn} shrink-0`}+ title={`Download ${row.repo} into MTPLX's cache — a multi-gigabyte transfer`}+ >+ {actionInProgress === `mtplx-pull-${row.repo}` ? <BrailleSpinner /> : <Download size={12} />}+ Download+ </button>+ )}+ </li>+ );+ })}+ </ul>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/components/settings/MtplxServerCard.jsx b/client/src/components/settings/MtplxServerCard.jsxindex 2ab7b19329..21d12798a0 100644--- a/client/src/components/settings/MtplxServerCard.jsx+++ b/client/src/components/settings/MtplxServerCard.jsx@@ -2,16 +2,18 @@ import { useState } from 'react';import { Link } from 'react-router';import { Gauge, RefreshCw, ExternalLink, Play, Square, Download, Terminal } from 'lucide-react';import BrailleSpinner from '../BrailleSpinner';+import MtplxCheckpoints from './MtplxCheckpoints.jsx';/*** MTPLX launcher — the same shape as the llama.cpp launcher below it, because* MTPLX is managed the same way: a PM2 process (`portos-mtplx`) PortOS starts,* stops, logs, and can persist across a reboot.*- * What it deliberately does NOT do is fetch weights. `mtplx pull` is a- * multi-gigabyte download and stays the user's decision, so this card serves a- * checkpoint already in MTPLX's cache and names the command that fills an empty- * one. See `docs/features/mtplx.md`.+ * Weights are managed here too, in `MtplxCheckpoints` below: search, download,+ * remove. A download is never implicit — it moves tens of gigabytes and only+ * runs from a button that says so — but it IS in the app, because sending the+ * user to a terminal for the one step in the middle of a managed lifecycle is a+ * dead end (PRD NR-9). See `docs/features/mtplx.md`.*/const btnClass = 'flex items-center gap-1.5 px-2.5 py-1.5 text-xs font-medium rounded-lg transition-colors disabled:opacity-50';@@ -25,6 +27,10 @@ export default function MtplxServerCard({onStart,onStop,onInstall,+ onSearchModels,+ onPullModel,+ onRemoveModel,+ download,}) {// '' = let PortOS pick from the cache (which is also what the readiness// checklist's one-click setup does).@@ -33,6 +39,9 @@ export default function MtplxServerCard({const [showLogs, setShowLogs] = useState(false);const cached = status?.cachedModels || [];+ // Rows carry size/verification for the manage-checkpoints list; older status+ // payloads (a peer or a tab open across an upgrade) carry only the ids.+ const cachedRows = status?.cachedModelRows || cached.map((repo) => ({ repo }));const emptyCache = Boolean(status?.installed) && cached.length === 0 && !status?.cacheError;const external = status?.running && status?.managed === false;@@ -60,7 +69,7 @@ export default function MtplxServerCard({</div><p className="text-xs text-gray-400 leading-relaxed">- MTPLX runs Qwen checkpoints with native multi-token-prediction decoding on Apple Silicon and serves them over an OpenAI-compatible loopback API. PortOS manages it as a PM2 process, exactly like <code className="text-gray-300">llama-server</code> — start it here, then pick an <strong className="text-white">MTPLX</strong> preset in AI Providers. PortOS never downloads MTPLX weights: <code className="text-gray-300">mtplx pull <hf-repo-id></code> in a terminal fills its cache, and this card serves what is already in it.+ MTPLX runs Qwen checkpoints with native multi-token-prediction decoding on Apple Silicon and serves them over an OpenAI-compatible loopback API. PortOS manages it as a PM2 process, exactly like <code className="text-gray-300">llama-server</code> — start it here, then pick an <strong className="text-white">MTPLX</strong> preset in AI Providers. Search for and download MTP checkpoints below — PortOS never fetches weights on its own, but every download, removal, and launch happens here.</p>{!status ? (@@ -102,7 +111,7 @@ export default function MtplxServerCard({<div className="bg-port-bg border border-port-border rounded-lg p-3 space-y-3">{emptyCache ? (<p className="text-xs text-port-warning">- MTPLX's model cache is empty, so its server exits before it binds a port. Run <code className="text-gray-300">mtplx pull</code> in a terminal for its default checkpoint (or <code className="text-gray-300">mtplx pull <hf-repo-id></code> for another MTP model), then refresh.+ MTPLX's model cache is empty, so its server exits before it binds a port. Download a checkpoint below, then start it.</p>) : (<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">@@ -139,7 +148,7 @@ export default function MtplxServerCard({onClick={() => onStart({ ...(model ? { model } : {}), ...(port ? { port: Number(port) } : {}) })}disabled={busy || emptyCache}className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`}- title={emptyCache ? 'Pull an MTP checkpoint first — PortOS never downloads MTPLX weights' : 'Start `mtplx serve` under PM2'}+ title={emptyCache ? 'Download an MTP checkpoint below first — a start never fetches weights' : 'Start `mtplx serve` under PM2'}>{actionInProgress === 'runtime-start-mtplx' ? <BrailleSpinner /> : <Play size={13} />}Start MTPLX@@ -147,6 +156,19 @@ export default function MtplxServerCard({</div>)}+ {status?.installed && status?.supported !== false && (+ <MtplxCheckpoints+ cached={cachedRows}+ cacheError={status?.cacheError || null}+ download={download}+ busy={busy}+ actionInProgress={actionInProgress}+ onSearch={onSearchModels}+ onPull={onPullModel}+ onRemove={onRemoveModel}+ />+ )}+{status?.recentLogs?.length > 0 && (<div className="space-y-1"><buttondiff --git a/client/src/components/settings/MtplxServerCard.test.jsx b/client/src/components/settings/MtplxServerCard.test.jsxindex f25ab9e6d5..2acbad8b65 100644--- a/client/src/components/settings/MtplxServerCard.test.jsx+++ b/client/src/components/settings/MtplxServerCard.test.jsx@@ -1,21 +1,33 @@import { describe, it, expect, vi } from 'vitest';-import { fireEvent, render, screen } from '@testing-library/react';+import { act, fireEvent, render, screen } from '@testing-library/react';import { MemoryRouter } from 'react-router';import MtplxServerCard from './MtplxServerCard.jsx';-const renderCard = (status, props = {}) => {- const handlers = { onRefresh: vi.fn(), onStart: vi.fn(), onStop: vi.fn(), onInstall: vi.fn() };+const renderCard = async (status, props = {}) => {+ const handlers = {+ onRefresh: vi.fn(),+ onStart: vi.fn(),+ onStop: vi.fn(),+ onInstall: vi.fn(),+ // The checkpoint manager loads upstream's default listing on mount.+ onSearchModels: vi.fn().mockResolvedValue({ models: [], error: null }),+ onPullModel: vi.fn(),+ onRemoveModel: vi.fn(),+ };render(<MemoryRouter><MtplxServerCard status={status} loading={false} busy={false} actionInProgress={null} {...handlers} {...props} /></MemoryRouter>,);+ // The checkpoint manager fetches its default listing on mount — settle it so+ // its state update lands inside act().+ await act(async () => {});return handlers;};describe('MtplxServerCard', () => {- it('starts on the cached checkpoint and port the user picked', () => {- const handlers = renderCard({+ it('starts on the cached checkpoint and port the user picked', async () => {+ const handlers = await renderCard({installed: true,running: false,supported: true,@@ -30,42 +42,96 @@ describe('MtplxServerCard', () => {expect(handlers.onStart).toHaveBeenCalledWith({ model: 'Example/Other-MTP', port: 8010 });});- it('omits an untouched field so PortOS picks the cache default and the shipped port', () => {- const handlers = renderCard({ installed: true, running: false, supported: true, cachedModels: ['Example/Qwen-MTP'] });+ it('omits an untouched field so PortOS picks the cache default and the shipped port', async () => {+ const handlers = await renderCard({ installed: true, running: false, supported: true, cachedModels: ['Example/Qwen-MTP'] });fireEvent.click(screen.getByRole('button', { name: /Start MTPLX/ }));expect(handlers.onStart).toHaveBeenCalledWith({});});- it('names the pull command instead of offering a start that cannot bind', () => {- // PortOS never downloads MTPLX weights, and `mtplx serve` exits before it- // binds a port on an empty cache.- renderCard({ installed: true, running: false, supported: true, cachedModels: [], cacheError: null });+ it('offers an in-app download instead of a start that cannot bind', async () => {+ // No start downloads weights, and `mtplx serve` exits before it binds a port+ // on an empty cache — so the card offers the download itself rather than+ // naming a terminal command (PRD NR-9).+ const handlers = await renderCard({ installed: true, running: false, supported: true, cachedModels: [], cacheError: null });expect(screen.getByText(/model cache is empty/)).toBeInTheDocument();expect(screen.getByRole('button', { name: /Start MTPLX/ })).toBeDisabled();+ expect(screen.queryByText(/in a terminal/i)).toBeNull();++ fireEvent.click(screen.getByRole('button', { name: /Download default checkpoint/ }));+ // `null` = MTPLX's own verified default, the checkpoint the readiness+ // checklist pulls — not a repo id the card invented.+ expect(handlers.onPullModel).toHaveBeenCalledWith(null);+ expect(handlers.onSearchModels).toHaveBeenCalled();+ });++ it('downloads a searched checkpoint and removes a cached one', async () => {+ const handlers = await renderCard(+ {+ installed: true,+ running: false,+ supported: true,+ cachedModels: ['Example/Cached-MTP'],+ cachedModelRows: [{ repo: 'Example/Cached-MTP', sizeBytes: 1024, hasRuntimeContract: true, valid: true }],+ },+ {+ onSearchModels: vi.fn().mockResolvedValue({+ models: [{ repo: 'Example/New-MTP', name: 'New MTP', owner: 'Example', downloads: 12, license: 'apache-2.0' }],+ error: null,+ }),+ },+ );++ fireEvent.click(await screen.findByRole('button', { name: /^Download$/ }));+ expect(handlers.onPullModel).toHaveBeenCalledWith('Example/New-MTP');++ // Removal is confirm-then-delete inline — no window.confirm.+ fireEvent.click(screen.getByRole('button', { name: /^Remove$/ }));+ fireEvent.click(screen.getByRole('button', { name: /^Delete$/ }));+ expect(handlers.onRemoveModel).toHaveBeenCalledWith('Example/Cached-MTP');+ });++ it('marks an already-cached search hit instead of offering to download it again', async () => {+ await renderCard(+ {+ installed: true,+ running: false,+ supported: true,+ cachedModels: ['Example/Cached-MTP'],+ cachedModelRows: [{ repo: 'Example/Cached-MTP', sizeBytes: 1024, valid: true }],+ },+ {+ onSearchModels: vi.fn().mockResolvedValue({+ models: [{ repo: 'Example/Cached-MTP', name: 'Cached MTP', owner: 'Example' }],+ error: null,+ }),+ },+ );+ expect(await screen.findByText('Cached')).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /^Download$/ })).toBeNull();});- it('still offers a start when the cache could not be READ — unreadable is not empty', () => {- const handlers = renderCard({ installed: true, running: false, supported: true, cachedModels: [], cacheError: '`mtplx models` timed out' });+ it('still offers a start when the cache could not be READ — unreadable is not empty', async () => {+ const handlers = await renderCard({ installed: true, running: false, supported: true, cachedModels: [], cacheError: '`mtplx models` timed out' });const start = screen.getByRole('button', { name: /Start MTPLX/ });expect(start).not.toBeDisabled();fireEvent.click(start);expect(handlers.onStart).toHaveBeenCalled();});- it('will not offer to stop a server started outside PortOS', () => {- renderCard({ installed: true, running: true, managed: false, supported: true, endpoint: 'http://127.0.0.1:8000/v1' });+ it('will not offer to stop a server started outside PortOS', async () => {+ await renderCard({ installed: true, running: true, managed: false, supported: true, endpoint: 'http://127.0.0.1:8000/v1' });expect(screen.getByText(/Started outside PortOS/)).toBeInTheDocument();expect(screen.queryByRole('button', { name: /Stop MTPLX/ })).toBeNull();});- it('offers the install when the binary is missing', () => {- const handlers = renderCard({ installed: false, running: false, supported: true });+ it('offers the install when the binary is missing', async () => {+ const handlers = await renderCard({ installed: false, running: false, supported: true });fireEvent.click(screen.getByRole('button', { name: /Install MTPLX/ }));expect(handlers.onInstall).toHaveBeenCalled();});- it('says why, and offers nothing, on a host that cannot run MLX', () => {- renderCard({ installed: false, running: false, supported: false, unsupportedReason: 'MTPLX runs only on macOS with Apple Silicon.' });+ it('says why, and offers nothing, on a host that cannot run MLX', async () => {+ await renderCard({ installed: false, running: false, supported: false, unsupportedReason: 'MTPLX runs only on macOS with Apple Silicon.' });expect(screen.getByText('MTPLX runs only on macOS with Apple Silicon.')).toBeInTheDocument();expect(screen.queryByRole('button', { name: /Install MTPLX/ })).toBeNull();});diff --git a/client/src/components/settings/RuntimeServersCard.jsx b/client/src/components/settings/RuntimeServersCard.jsxindex a7d5432727..dcd2e56c5b 100644--- a/client/src/components/settings/RuntimeServersCard.jsx+++ b/client/src/components/settings/RuntimeServersCard.jsx@@ -236,11 +236,12 @@ export default function RuntimeServersCard({onInstall: onInstallMtplx,onStart: onStartMtplx,onStop: onStopMtplx,- // MTPLX weights are a multi-gigabyte pull PortOS never runs. An installed- // MTPLX with an empty cache exits before it binds, so say so here rather- // than offering a Start that cannot work.+ // MTPLX weights are a multi-gigabyte download no Start button runs on its+ // own. An installed MTPLX with an empty cache exits before it binds, so+ // point at the card that downloads one rather than offering a Start that+ // cannot work.startBlockedReason: mtplxStatus?.installed && mtplxStatus?.cachedModels?.length === 0 && !mtplxStatus?.cacheError- ? 'Run `mtplx pull` in a terminal first — PortOS never downloads MTPLX weights'+ ? 'No checkpoint yet — use Configure to download one': null,detail: mtplxStatus?.cachedModels?.length? `${mtplxStatus.cachedModels.length} checkpoint${mtplxStatus.cachedModels.length === 1 ? '' : 's'} cached`diff --git a/client/src/components/settings/RuntimeServersCard.test.jsx b/client/src/components/settings/RuntimeServersCard.test.jsxindex d768c2f549..7bbd11ec10 100644--- a/client/src/components/settings/RuntimeServersCard.test.jsx+++ b/client/src/components/settings/RuntimeServersCard.test.jsx@@ -106,15 +106,17 @@ describe('RuntimeServersCard', () => {expect(handlers.onInstallBackend).toHaveBeenCalledWith('ollama');});- it('blocks the MTPLX Start with the pull command when its cache is empty', () => {- // PortOS never downloads MTPLX weights, and `mtplx serve` exits before it- // binds on an empty cache — so offering Start would only produce a failure.+ it('blocks the MTPLX Start and points at the in-app download when its cache is empty', () => {+ // No Start button downloads weights, and `mtplx serve` exits before it binds+ // on an empty cache — so offering Start would only produce a failure. The+ // fix is the Configure card below, never a terminal command (PRD NR-9).renderCard({mtplxStatus: { installed: true, running: false, supported: true, cachedModels: [], cacheError: null },});const mtplx = row('MTPLX');expect(within(mtplx).queryByRole('button', { name: /^Start/ })).toBeNull();- expect(within(mtplx).getByText(/mtplx pull/)).toBeInTheDocument();+ expect(within(mtplx).getByText(/use Configure to download one/)).toBeInTheDocument();+ expect(within(mtplx).queryByText(/terminal/i)).toBeNull();});it('reports a runtime this host cannot run without offering to install it', () => {diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 2e57644e88..dc8c50157a 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -45,7 +45,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiCommands.js` | CLI command dispatch. || `apiDashboard.js` | Dashboard state. || `apiDatabase.js` | Database introspection. |-| `apiLocalLlm.js` | Local LLM backends (Ollama / LM Studio): status (incl. installed models), catalog, model install/delete, backend install (Homebrew/script), switch/migrate, playground test/compare, and measured per-model assessments (run + persisted results + intent ranking + the server-side "measure everything" sweep). |+| `apiLocalLlm.js` | Local LLM backends (Ollama / LM Studio): status (incl. installed models), catalog, model install/delete, backend install (Homebrew/script), switch/migrate, playground test/compare, and measured per-model assessments (run + persisted results + intent ranking + the server-side "measure everything" sweep). Also the PM2-managed runtime servers (llama.cpp, MTPLX) and MTPLX's checkpoint catalog — `searchMtplxModels` / `pullMtplxModel` / `removeMtplxModel`, so weights are managed in-app rather than from a terminal. || `apiGit.js` | Git operations. || `apiGithub.js` | GitHub repo metadata. || `apiHistory.js` | Historical logs / runs. |diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex de4597f249..eaae796767 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -72,6 +72,25 @@ export const stopMtplxServer = () =>export const installMtplx = () =>request('/local-llm/mtplx/install', { method: 'POST' });+// MTPLX model catalog — search, download, and remove MTP checkpoints in-app.+// `mtplx forge discover` is upstream's index of MTPLX-branded models, which is+// exactly the set `mtplx serve` can run; an empty query returns its default list.+export const searchMtplxModels = (params = {}, options) => {+ const query = new URLSearchParams(+ Object.entries(params).filter(([, v]) => v !== undefined && v !== null && v !== '')+ ).toString();+ return request(`/local-llm/mtplx/models/search${query ? `?${query}` : ''}`, options);+};++// Omitting `model` fetches MTPLX's own verified default checkpoint. Byte+// progress arrives on the `mtplx:download` socket event, not in this response —+// a multi-GB transfer resolves only when the weights are on disk.+export const pullMtplxModel = (model = null) =>+ request('/local-llm/mtplx/models/pull', { method: 'POST', body: JSON.stringify(model ? { model } : {}) });++export const removeMtplxModel = (model) =>+ request('/local-llm/mtplx/models/remove', { method: 'POST', body: JSON.stringify({ model }) });+// `pm2 save` — snapshot the running PM2 process list into the dump a boot-time// `pm2 resurrect` replays, so the local runtime servers come back after a// reboot. The privileged `pm2 startup` half stays a one-time operator command.diff --git a/docs/API.md b/docs/API.mdindex dcd45608a6..8b4271f3ec 100644--- a/docs/API.md+++ b/docs/API.md@@ -529,7 +529,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom| `/api/messages` | Messages (email) integration || `/api/digital-twin/social-accounts`, `/identity`, `/autobiography` | Digital-twin sub-domains || `/api/meatspace` | MeatSpace (health, POST, genome) |-| `/api/lmstudio`, `/api/local-llm` | Local LLM backends and the local runtime servers PortOS can start/stop (Ollama, LM Studio, `llama-server`, MTPLX — the last two as PM2 processes; `POST /api/local-llm/save-startup` is `pm2 save`) |+| `/api/lmstudio`, `/api/local-llm` | Local LLM backends and the local runtime servers PortOS can start/stop (Ollama, LM Studio, `llama-server`, MTPLX — the last two as PM2 processes; `POST /api/local-llm/save-startup` is `pm2 save`), plus MTPLX's checkpoint catalog — `GET /api/local-llm/mtplx/models/search`, `POST .../models/pull` (byte progress on the `mtplx:download` socket event), `POST .../models/remove` || `/api/code-review` | Code review runs || `/api/voice`, `/api/voice/public` | Voice assistant || `/api/api-docs` | OpenAPI 3.1 spec |diff --git a/docs/features/mtplx.md b/docs/features/mtplx.mdindex 6afb520874..31b90da4bd 100644--- a/docs/features/mtplx.md+++ b/docs/features/mtplx.md@@ -55,11 +55,16 @@ you are already on.1. Install MTPLX from **Local Runtime Servers**. PortOS installs the packagefrom upstream's Homebrew tap (`brew install youssofal/mtplx/mtplx`), fallingback to `python3 -m pip install mtplx` on a host without Homebrew.-2. **Pull a checkpoint** — `mtplx pull` fetches MTPLX's default verified model,- `mtplx pull <hf-repo-id>` any other MTP model. This page never downloads- weights, and `mtplx serve` exits before it binds a port on an empty cache, so- the card refuses to start until something is cached. (The AI Providers- checklist below *can* run that download for you — see step 3 there.)+2. **Download a checkpoint** from the MTPLX card's **Cached checkpoints** /+ **Find a checkpoint** panel. Search runs `mtplx forge discover` — upstream's+ index of MTPLX-branded MTP models, which is exactly the set `mtplx serve` can+ run — and **Download** on a result runs `mtplx pull <repo>` with live byte+ progress. With an empty cache the panel leads with **Download default+ checkpoint**, MTPLX's own verified model. **Remove** on a cached row runs+ `mtplx remove` and reports the disk freed. Nothing here downloads on its own:+ `mtplx serve` exits before it binds a port on an empty cache, and the card+ refuses to start until something is cached — but the fix is a button, not a+ terminal.3. **Start MTPLX** from the MTPLX card, choosing a cached checkpoint and the portyour provider points at. PortOS runs `mtplx serve` under PM2. A cold MLXcheckpoint takes a while to load: the request comes back as soon as the@@ -80,8 +85,8 @@ you are already on.default model & start MTPLX**. That runs `mtplx pull` (MTPLX's own defaultverified checkpoint, a multi-gigabyte download) and then starts the server,with the download's progress streaming into the same modal. To use a- different MTP checkpoint instead, run `mtplx pull <hf-repo-id>` in a- terminal and click **Start MTPLX**.+ different MTP checkpoint instead, search for and download it on the MTPLX+ card in Models → LLMs, then click **Start MTPLX**.Then, either way:@@ -109,17 +114,25 @@ not offer to stop a process it did not start.particular repo was never pulled, even on a machine holding a different MTPmodel. A running server serving a different alias than the provider names isreported by the checklist's model check and left for you to resolve.-- The **Download the default model & start MTPLX** button on the AI Providers- checklist is the one action anywhere in PortOS that fetches MTPLX weights (the- Models → LLMs card never does), and it appears only when that same cache listing- proves there is nothing servable — an empty cache, or one holding only a- half-finished `mtplx pull`. It runs `mtplx pull` with no repo id, so it can- only ever fetch MTPLX's own default verified checkpoint; nothing from the- page picks what is downloaded. It exists because the checklist otherwise- offered a **Start MTPLX** that could only fail, and named the missing weights- solely inside that failure — the one blocking fact was reachable only by- clicking the button it made impossible.-- Closing the modal **cancels the download**. PortOS allows one local-runtime+- **Two surfaces fetch weights, and both are buttons the user presses by name.**+ The AI Providers checklist's **Download the default model & start MTPLX**+ appears only when the cache listing proves there is nothing servable — an+ empty cache, or one holding only a half-finished pull — and runs `mtplx pull`+ with no repo id, so it can only ever fetch MTPLX's own default verified+ checkpoint; nothing on that page picks what is downloaded. The Models → LLMs+ card's checkpoint panel is the full-control counterpart: search, download a+ named repo id, remove one. Neither is ever reached implicitly by an Install or+ a Start.+- **The card never tells you to open a terminal.** It used to: an empty cache+ printed `mtplx pull` and left the user to go run it. PortOS installs the+ runtime, starts it, stops it, logs it, and persists it across a reboot — the+ one step in the middle being a shell command was the odd one out, and the PRD+ now forbids it outright (NR-9).+- A download started from the **LLMs card** keeps running if you navigate away —+ it is a server-side `mtplx pull` with progress on a socket, not work owned by+ the page. Only the AI Providers checklist's modal cancels on close, for the+ reason below.+- Closing the checklist modal **cancels the download**. PortOS allows one local-runtimesetup at a time, and a weights pull can run for hours, so leaving it runningafter you dismissed it would also refuse every other runtime's setup buttonfor the rest of it. A cancelled pull leaves a partial download in the cache,diff --git a/server/lib/README.md b/server/lib/README.mdindex 3ad51d12ef..4e289e12fa 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -210,7 +210,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `interactiveShellResolver.js` | `resolveInteractiveShell()` — picks the shell binary a PTY session runs (Shell page, agent TUI shells). On Windows the old `COMSPEC` default meant `cmd.exe`, where no command a user would type reaches another drive: `cd I:` silently PRINTS that drive's cwd and stays put, a bare `I:\` is "not recognized as a command", and `cd 'I:\path'` is a syntax error (no single-quote quoting) — so a Windows install with its repos on a second drive was stuck on `C:`. Resolves PORTOS_SHELL → newest `pwsh.exe` under `%ProgramFiles%\PowerShell\<major>` (majors enumerated and sorted numerically, so a future 8 needs no code change) → any `pwsh.exe` on PATH via `findCommandOnPath` (scoop/choco/Store shim) → `powershell.exe` 5.1 (ships with Windows) → `cmd.exe` last. PowerShell crosses drives with every form. Unchanged on POSIX (`SHELL` → zsh). `resolveInteractiveShellWith({platform, env, exists, readdir, findOnPath})` is the un-memoized injectable form for tests. || `openFolder.js` | `openFolderInSystemExplorer(localPath)` — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child `error` handler prevents spawn failures from crashing the process. || `childProcess.js` | Drop-in `child_process` replacement that defaults every spawn to `windowsHide: true` — `spawn` / `spawnSync` / `fork` / `exec` / `execSync` / `execFile` / `execFileSync`, plus a `ChildProcess` re-export. **Server runtime code must import from here, never from `child_process` directly** (enforced by `childProcess.guards.test.js`): a console-less PM2 fork spawning a console child without `CREATE_NO_WINDOW` makes Windows hand the new console to Windows Terminal, which flashes a focus-stealing window. `exec`/`execFile` carry `util.promisify.custom` so `promisify(execFile)` still resolves to `{ stdout, stderr }`. An explicit `windowsHide: false` is respected. Background: `docs/WINDOWS_CONSOLE.md`. |-| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. `killProcessTree(child, signal, { processGroup })` takes the POSIX group down too when the child was spawned `detached` (Windows always tree-kills). Used by `appBuilder.js`, `appUpdater.js`, the CoS agent spawners, and `setupScriptRunner.js`. |+| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES`, `spawnFailureDetail(result, fallback)` (the most useful sentence from a failed result — prefers the spawn error, then a stderr line, then a stdout line that isn't bare JSON punctuation, because a `--json` CLI prints its payload to stdout even when it exits non-zero) — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. `killProcessTree(child, signal, { processGroup })` takes the POSIX group down too when the child was spawned `detached` (Windows always tree-kills). Used by `appBuilder.js`, `appUpdater.js`, the CoS agent spawners, and `setupScriptRunner.js`. || `setupScriptRunner.js` | `spawnSetupScript(envVars)` / `stopSetupScript(child)` / `SETUP_IMAGE_VIDEO_SCRIPT` — the one way to run `scripts/setup-image-video.sh` (shared by the Video Gen BYOV runtimes, the music engines and the MuScriptor venv). Runs it under `resolveBashBinary()` with a `toBashPath` script path, and on Windows presets the `PYTHON_BIN` the script would otherwise default to `python3` for. Cancel via `stopSetupScript`, which tree-kills so uv / pip / git die with bash. || `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000, env, cwd })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`; `env`/`cwd` let a caller check the exact child process configuration. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. || `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `usesCreativeDirectorScratchCwd(task)` / `creativeDirectorScratchCwd(agentId)` / `removeCreativeDirectorScratchCwd(agentId)` / `resolveAgentCliCwd({ workspacePath, fallbackRoot, task, agentId })` — Creative Director no-worktree tasks get a per-agent scratch cwd under `os.tmpdir()/portos-cd-cwd/<id>` (outside the PortOS git tree) instead of the PortOS root, so native CLI CLAUDE.md discovery cannot walk up into the repo (#4650). `removeCreativeDirectorScratchCwd` is the matching finalize cleanup. `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.diff --git a/server/lib/bufferedSpawn.js b/server/lib/bufferedSpawn.jsindex 2b703c0d6c..9d79ec1175 100644--- a/server/lib/bufferedSpawn.js+++ b/server/lib/bufferedSpawn.js@@ -355,3 +355,26 @@ export async function bufferedSpawnOrThrow(cmd, args, options = {}) {}return { stdout: result.stdout, stderr: result.stderr };}++/**+ * The most useful sentence from a FAILED `bufferedSpawn` result.+ *+ * Callers of a `--json` CLI need this rather than a bare exit code, and the+ * naive "last line of stderr, else stdout" walk gets it wrong for exactly those+ * tools: they print their payload to stdout even when they exit non-zero, so the+ * last stdout line is a closing `}` or `]`. Prefers the spawn error, then a+ * stderr line, then a stdout line that isn't just JSON punctuation.+ *+ * @param {{error?: Error, stderr?: string, stdout?: string}} result - a `bufferedSpawn` result+ * @param {string} fallback - used when the command failed without saying anything+ * @returns {string}+ */+export function spawnFailureDetail(result, fallback) {+ if (result?.error?.message) return result.error.message;+ const lastLine = (text) => String(text || '').trim().split(/\r?\n/).filter(Boolean).pop();+ const stderrTail = lastLine(result?.stderr);+ if (stderrTail) return stderrTail;+ const stdoutTail = lastLine(result?.stdout);+ if (stdoutTail && !/^[}\]]+,?$/.test(stdoutTail)) return stdoutTail;+ return fallback;+}diff --git a/server/lib/bufferedSpawn.test.js b/server/lib/bufferedSpawn.test.jsindex e65927b0de..21e242365f 100644--- a/server/lib/bufferedSpawn.test.js+++ b/server/lib/bufferedSpawn.test.js@@ -28,6 +28,7 @@ const {IS_WIN32,WIN_CMD_SHIMS,MAX_OUTPUT_BYTES,+ spawnFailureDetail,} = await import('./bufferedSpawn.js');/**@@ -492,3 +493,31 @@ describe('bufferedSpawnOrThrow — throwing adapter', () => {await assertion;});});++describe('spawnFailureDetail', () => {+ const fallback = 'mtplx exited with code 1';++ it('prefers the spawn error, which is the only stream a failed spawn writes to', () => {+ expect(spawnFailureDetail({ error: new Error('EACCES'), stderr: 'noise' }, fallback)).toBe('EACCES');+ });++ it('falls back to the last stderr line', () => {+ expect(spawnFailureDetail({ stderr: 'warning: slow\nerror: not cached\n' }, fallback)).toBe('error: not cached');+ });++ it('ignores a stdout tail that is only JSON punctuation', () => {+ // A `--json` CLI prints its payload to stdout even when it exits non-zero,+ // so the naive last-stdout-line walk surfaces a bare closing brace.+ expect(spawnFailureDetail({ stdout: '{\n "removed": false\n}' }, fallback)).toBe(fallback);+ expect(spawnFailureDetail({ stdout: '{\n "removed": false\n},' }, fallback)).toBe(fallback);+ });++ it('still uses a meaningful stdout line when stderr is empty', () => {+ expect(spawnFailureDetail({ stderr: '', stdout: 'error: pull failed' }, fallback)).toBe('error: pull failed');+ });++ it('returns the fallback when the command failed without saying anything', () => {+ expect(spawnFailureDetail({}, fallback)).toBe(fallback);+ expect(spawnFailureDetail(null, fallback)).toBe(fallback);+ });+});diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.jsindex 845f20c714..cebf644d72 100644--- a/server/lib/mediaValidation.js+++ b/server/lib/mediaValidation.js@@ -180,6 +180,25 @@ export const localLlmMtplxStartSchema = z.object({'model must be a Hugging Face repo id',).optional().nullable(),});+// MTPLX model catalog. `mtplx forge discover` is upstream's own index of+// MTPLX-branded MTP checkpoints; an empty query means its default listing.+export const localLlmMtplxSearchSchema = z.object({+ query: z.string().trim().max(200).optional().default(''),+ limit: z.coerce.number().int().min(1).max(100).optional().default(24),+ offset: z.coerce.number().int().min(0).max(10000).optional().default(0),+});+// A checkpoint download. `model` omitted means MTPLX's own verified default —+// the same one the provider-readiness checklist pulls — so the two surfaces+// cannot fetch different weights. A named model must be a Hugging Face repo id.+const mtplxRepoIdSchema = z.string().trim().min(1).max(200).regex(+ /^[A-Za-z0-9][A-Za-z0-9._-]*\/[A-Za-z0-9][A-Za-z0-9._-]*$/,+ 'model must be a Hugging Face repo id (owner/name)',+);+export const localLlmMtplxPullSchema = z.object({+ model: mtplxRepoIdSchema.optional().nullable(),+});+// Removal always names a checkpoint — there is no "remove whatever is cached".+export const localLlmMtplxRemoveSchema = z.object({ model: mtplxRepoIdSchema });export const localLlmLlamaServerStartSchema = z.object({model: z.string().trim().min(1).max(500),draftModel: z.string().trim().max(500).optional().nullable(),diff --git a/server/lib/mtplxModels.js b/server/lib/mtplxModels.jsindex 49e1d77f5a..aa1a5b42ba 100644--- a/server/lib/mtplxModels.js+++ b/server/lib/mtplxModels.js@@ -21,7 +21,7 @@* action), exactly as `docs/features/mtplx.md` promises.*/-import { bufferedSpawn } from './bufferedSpawn.js';+import { bufferedSpawn, spawnFailureDetail } from './bufferedSpawn.js';import { safeJSONParse } from './fileUtils.js';import { findCommandOnPath } from './processEnv.js';@@ -51,8 +51,7 @@ export async function listMtplxCachedModels({ command = 'mtplx' } = {}) {// A spawn failure (EACCES, ENOENT on a dangling symlink) reports nothing on// either stream — its reason lives on `error`, and dropping it would leave// the user with a bare exit code for a fixable permissions problem.- const detail = result.error?.message || String(result.stderr || result.stdout || '').trim().split(/\r?\n/).pop();- return { models: null, error: detail || `\`${command} models\` exited with code ${result.code}` };+ return { models: null, error: spawnFailureDetail(result, `\`${command} models\` exited with code ${result.code}`) };}// Parse from the first brace: MTPLX writes the JSON alone today, but a bannerdiff --git a/server/lib/mtplxModels.test.js b/server/lib/mtplxModels.test.jsindex c1b3aa05e9..89c12368c0 100644--- a/server/lib/mtplxModels.test.js+++ b/server/lib/mtplxModels.test.js@@ -1,7 +1,9 @@import { afterEach, describe, expect, it, vi } from 'vitest';const spawned = vi.hoisted(() => ({ bufferedSpawn: vi.fn() }));-vi.mock('./bufferedSpawn.js', () => spawned);+// Partial mock: only the spawn is faked — `spawnFailureDetail` is the real pure+// helper, so the failure sentence this asserts on is the shipped one.+vi.mock('./bufferedSpawn.js', async (importOriginal) => ({ ...(await importOriginal()), ...spawned }));const pathLookup = vi.hoisted(() => ({ findCommandOnPath: vi.fn(() => '/opt/homebrew/bin/mtplx') }));vi.mock('./processEnv.js', () => pathLookup);diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 3e496a1906..0387e9fc07 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -30,10 +30,14 @@ import {localLlmLlamaServerStartSchema,localLlmLmStudioServiceSchema,localLlmMtplxStartSchema,+ localLlmMtplxSearchSchema,+ localLlmMtplxPullSchema,+ localLlmMtplxRemoveSchema,localLlmSpecModelDownloadSchema} from '../lib/validation.js'import { getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer } from '../services/llamaServerManager.js'import { getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx } from '../services/mtplxServerManager.js'+import { searchMtplxCatalog, pullMtplxModel, removeMtplxModel } from '../services/mtplxModelManager.js'import { saveProcessList } from '../services/pm2.js'import { getSpecDecodePresetStatus, downloadSpecDecodeModel } from '../services/specDecodeModels.js'import { SPEC_TYPE_SUGGESTIONS } from '../lib/specDecodePresets.js'@@ -629,6 +633,40 @@ router.post('/mtplx/install', asyncHandler(async (req, res) => {res.json(result)}))+// --- MTPLX model catalog ----------------------------------------------------+// Search / download / remove MTP checkpoints without leaving PortOS. Before+// these existed the card told the user to run `mtplx pull` in a terminal, which+// is a dead end inside an app that manages the runtime everywhere else.++// GET /api/local-llm/mtplx/models/search — MTPLX-branded checkpoints on+// Hugging Face (`mtplx forge discover`). Network call; no download.+router.get('/mtplx/models/search', asyncHandler(async (req, res) => {+ const params = validateRequest(localLlmMtplxSearchSchema, req.query)+ res.json(await searchMtplxCatalog(params))+}))++// POST /api/local-llm/mtplx/models/pull — download one checkpoint into MTPLX's+// cache. Byte progress streams over `mtplx:download`; the card renders it as a+// bar on the row that started it. Omitting `model` fetches MTPLX's own verified+// default, the same checkpoint the provider-readiness checklist pulls.+router.post('/mtplx/models/pull', asyncHandler(async (req, res) => {+ const { model } = validateRequest(localLlmMtplxPullSchema, req.body)+ const io = req.app.get('io')+ const result = await pullMtplxModel({ model, onProgress: (frame) => io?.emit('mtplx:download', frame) })+ // A cache that just went from empty to servable is exactly what the readiness+ // probes remember as "MTPLX setup incomplete".+ if (result.success) resetProviderReadinessCache()+ res.json(result)+}))++// POST /api/local-llm/mtplx/models/remove — delete one checkpoint from the cache+router.post('/mtplx/models/remove', asyncHandler(async (req, res) => {+ const { model } = validateRequest(localLlmMtplxRemoveSchema, req.body)+ const result = await removeMtplxModel(model)+ resetProviderReadinessCache()+ res.json(result)+}))+// POST /api/local-llm/save-startup — `pm2 save`, so the PM2-managed local// runtime servers currently running (llama-server, MTPLX, PortOS itself) are in// the dump a boot-time `pm2 resurrect` replays. The privileged half — `pm2diff --git a/server/services/localRuntimeSetup.js b/server/services/localRuntimeSetup.jsindex 81abfe014e..b75094112b 100644--- a/server/services/localRuntimeSetup.js+++ b/server/services/localRuntimeSetup.js@@ -90,14 +90,14 @@ const CONFIRM_TIMEOUT_MS = 5_000;/*** Why an installed MTPLX still cannot be started. Weights stay the user's* decision (`docs/features/mtplx.md`), so a plain Start never fetches them —- * it names the button that does, plus the terminal command for a checkpoint- * other than MTPLX's own default.+ * it names the button that does, plus the in-app card that searches for and+ * downloads a checkpoint other than MTPLX's own default.*/-const MTPLX_NO_MODEL_ERROR = 'no model weights are cached, so its server exits before it binds a port. Close this window — the checklist now offers “Download the default model & start MTPLX”, which fetches MTPLX\'s own verified checkpoint (a multi-gigabyte download) and then starts the server. To use a different MTP checkpoint instead, run `mtplx pull <hf-repo-id>` in a terminal, then click Start MTPLX again.';+const MTPLX_NO_MODEL_ERROR = 'no model weights are cached, so its server exits before it binds a port. Close this window — the checklist now offers “Download the default model & start MTPLX”, which fetches MTPLX\'s own verified checkpoint (a multi-gigabyte download) and then starts the server. To use a different MTP checkpoint instead, search for one on the MTPLX card in Models → LLMs, download it there, then click Start MTPLX again.';/** The same dead end, reached from a cache holding only interrupted pulls. */const mtplxPartialCacheError = (count) =>- `its cache holds ${count} model${count === 1 ? '' : 's'}, but none passed its own file check — an interrupted \`mtplx pull\` leaves a partial download behind. Use “Download the default model & start MTPLX” on the checklist to re-fetch it, or run \`mtplx pull <hf-repo-id>\` in a terminal for another checkpoint.`;+ `its cache holds ${count} model${count === 1 ? '' : 's'}, but none passed its own file check — an interrupted download leaves a partial pack behind. Use “Download the default model & start MTPLX” on the checklist to re-fetch it, or pick another checkpoint on the MTPLX card in Models → LLMs.`;/** What each `action` is called on the button and in the log. */const ACTION_LABELS = {diff --git a/server/services/localRuntimeSetup.test.js b/server/services/localRuntimeSetup.test.jsindex 792df7b27a..265c3f2372 100644--- a/server/services/localRuntimeSetup.test.js+++ b/server/services/localRuntimeSetup.test.js@@ -304,16 +304,16 @@ describe('runLocalRuntimeSetup', () => {});it('surfaces the manager\'s refusal instead of a bare failure', async () => {- // e.g. an empty MTPLX cache, which names the `mtplx pull` that fixes it.+ // e.g. an empty MTPLX cache, which names the download button that fixes it.pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');probe.probeOpenAiModels.mockResolvedValue(unreachable);- mtplx.startMtplxServer.mockRejectedValue(new Error('MTPLX has no model weights cached — run `mtplx pull`'));+ mtplx.startMtplxServer.mockRejectedValue(new Error('MTPLX has no model weights cached — use "Download default checkpoint"'));const restore = pinPlatform('darwin');const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });restore();- expect(result).toMatchObject({ success: false, error: expect.stringContaining('mtplx pull') });+ expect(result).toMatchObject({ success: false, error: expect.stringContaining('Download default checkpoint') });});it('downloads the default checkpoint and then starts, but ONLY for `pull-start`', async () => {@@ -344,7 +344,7 @@ describe('runLocalRuntimeSetup', () => {it('never downloads weights behind an explicit plain start', async () => {// A multi-gigabyte download is a decision; only the action that says so may- // spend it. A `start` reaches `mtplx pull` in PROSE and nowhere else.+ // spend it. A `start` names the download BUTTON in prose and spends nothing.mtplxCache.listMtplxCachedModels.mockResolvedValue(cachedModels([]));pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');probe.probeOpenAiModels.mockResolvedValue(unreachable);@@ -355,7 +355,9 @@ describe('runLocalRuntimeSetup', () => {expect(streaming.runStreamingCommand).not.toHaveBeenCalled();expect(mtplx.startMtplxServer).not.toHaveBeenCalled();- expect(result).toMatchObject({ success: false, error: expect.stringContaining('mtplx pull') });+ expect(result).toMatchObject({ success: false, error: expect.stringContaining('Download the default model') });+ // Never a terminal command as the remedy (PRD NR-9).+ expect(result.error).not.toMatch(/terminal/);});it('resolves an ABSENT action to whatever the checklist is currently offering', async () => {diff --git a/server/services/mtplxModelManager.js b/server/services/mtplxModelManager.jsnew file mode 100644index 0000000000..8d8dfaca7a--- /dev/null+++ b/server/services/mtplxModelManager.js@@ -0,0 +1,238 @@+/**+ * MTPLX model catalog — search, download, and remove MTP checkpoints from the UI.+ *+ * `mtplxServerManager.js` owns the *process* (install / start / stop / logs).+ * This module owns the *weights*, which used to be the one part of MTPLX PortOS+ * refused to touch: an empty cache produced a card that told the user to go run+ * `mtplx pull` in a terminal and come back. That is a dead end inside the app —+ * PortOS manages the runtime everywhere else, so it manages the models too.+ *+ * Every operation is a fixed `mtplx` subcommand with `shell: false`; the only+ * request-supplied values that ever reach an argv slot are a repo id (shape-+ * checked before it is passed) and a search string, each as its own element, so+ * no input can become a shell word.+ *+ * - `searchMtplxCatalog` → `mtplx forge discover --json` (Hugging Face search)+ * - `pullMtplxModel` → `mtplx pull <repo> --progress-json` (NDJSON progress)+ * - `removeMtplxModel` → `mtplx remove <repo> --json`+ *+ * A download still is NOT something any other action does silently: it moves+ * tens of gigabytes and only ever runs from a button the user pressed that says+ * so. What changed is that the button now exists.+ */++import { bufferedSpawn, spawnFailureDetail } from '../lib/bufferedSpawn.js';+import { ServerError } from '../lib/errorHandler.js';+import { safeJSONParse } from '../lib/fileUtils.js';+import { listMtplxCachedModels } from '../lib/mtplxModels.js';+import { findCommandOnPath } from '../lib/processEnv.js';+import { runStreamingCommand } from '../lib/streamingSpawn.js';++/** A Hugging Face search is one API call — short, and worth failing fast. */+const SEARCH_TIMEOUT_MS = 30_000;+/** Removing a directory tree is local I/O, but a large pack takes a moment. */+const REMOVE_TIMEOUT_MS = 60_000;+/**+ * A model pull moves tens of gigabytes. Sized for a slow domestic line rather+ * than a fast one — a bound that kills a download at 90% is worse than no bound+ * at all. Mirrors `services/localRuntimeSetup.js`'s own weights budget.+ */+const PULL_TIMEOUT_MS = 6 * 60 * 60 * 1000;++/**+ * `owner/name`, the only shape `mtplx pull` and `mtplx remove` are given.+ *+ * Both accept a bare URL too, but PortOS deliberately does not: the search+ * results it renders carry repo ids, and refusing everything else keeps a+ * hand-typed value from becoming a path or a flag (a leading `-` would be read+ * as an option by argparse).+ */+const REPO_ID_RE = /^[A-Za-z0-9][\w.-]*\/[\w.-]+$/;++export const isMtplxRepoId = (value) => typeof value === 'string' && REPO_ID_RE.test(value);++/** Resolve `mtplx`, or say why the operation cannot run at all. */+function requireBinary() {+ const binary = findCommandOnPath('mtplx');+ if (!binary) {+ throw new ServerError(+ 'The `mtplx` binary was not found on PATH. Install MTPLX from the Local Runtime Servers card first.',+ { status: 400, code: 'MTPLX_NOT_INSTALLED' }+ );+ }+ return binary;+}++function requireRepoId(model) {+ if (!isMtplxRepoId(model)) {+ throw new ServerError(+ `"${model}" is not a Hugging Face repo id. Expected owner/name — pick a model from the search results.`,+ { status: 400, code: 'MTPLX_INVALID_REPO_ID' }+ );+ }+ return model;+}++/**+ * Search Hugging Face for MTPLX-branded MTP checkpoints.+ *+ * `mtplx forge discover` is upstream's own index of models carrying the MTPLX+ * runtime contract, which is exactly the set `mtplx serve` can run — a raw Hub+ * search would mostly return checkpoints that download for an hour and then+ * fail their file check.+ *+ * @param {{query?: string, limit?: number, offset?: number}} [options]+ * @returns {Promise<{models: object[], error: string|null}>}+ */+export async function searchMtplxCatalog({ query = '', limit = 24, offset = 0 } = {}) {+ const binary = requireBinary();+ const args = ['forge', 'discover', '--json', '--limit', String(limit), '--offset', String(offset)];+ // An empty query means "MTPLX's own default listing" — passing `--query ''`+ // would search for the empty string instead of falling through to it.+ if (query.trim()) args.push('--query', query.trim());++ const result = await bufferedSpawn(binary, args, { timeoutMs: SEARCH_TIMEOUT_MS, shell: false });+ if (result.timedOut) return { models: [], error: '`mtplx forge discover` timed out' };+ if (!result.success) {+ return { models: [], error: spawnFailureDetail(result, `\`mtplx forge discover\` exited with code ${result.code}`) };+ }++ // Parse from the first bracket: upstream writes the array alone today, but a+ // banner line ahead of it must not read as "nothing was found".+ const text = String(result.stdout || '');+ const start = text.indexOf('[');+ const parsed = start === -1 ? null : safeJSONParse(text.slice(start), null, { allowArray: true });+ if (!Array.isArray(parsed)) return { models: [], error: '`mtplx forge discover --json` did not return a model list' };++ return {+ models: parsed+ .filter((row) => typeof row?.repo === 'string' && row.repo)+ .map((row) => ({+ repo: row.repo,+ name: row.branded_name || row.repo.split('/').pop(),+ owner: row.owner || row.repo.split('/')[0],+ downloads: Number.isFinite(row.downloads) ? row.downloads : null,+ license: row.license || null,+ })),+ error: null,+ };+}++/**+ * One NDJSON line from `mtplx pull --progress-json`, normalised to the frame+ * shape the client renders.+ *+ * Upstream emits `resolving` / `start` / `resume` / `progress` / `verifying` /+ * `complete` / `result` / `failed` / `cancelled`. Only the byte counters and a+ * message are load-bearing here; anything unrecognised still surfaces as a log+ * line rather than being dropped, because a download that goes quiet for an+ * hour is indistinguishable from one that hung.+ */+export function parseMtplxPullFrame(line, model) {+ const trimmed = String(line || '').trim();+ if (!trimmed) return null;+ const parsed = trimmed.startsWith('{') ? safeJSONParse(trimmed, null, { allowArray: false }) : null;+ if (!parsed) return { event: 'progress', model, message: trimmed };++ const received = Number(parsed.size_bytes);+ const total = Number(parsed.total_bytes);+ return {+ event: parsed.event === 'failed' ? 'error' : parsed.event || 'progress',+ model: parsed.repo_id || model,+ received: Number.isFinite(received) ? received : null,+ total: Number.isFinite(total) && total > 0 ? total : null,+ message: parsed.message || parsed.detail || null,+ };+}++/**+ * Download one MTP checkpoint into MTPLX's cache.+ *+ * `model` omitted means MTPLX's own verified default — the same checkpoint the+ * provider-readiness checklist's "Download the default model & start MTPLX"+ * fetches, so the two surfaces cannot pull different weights.+ *+ * Never throws for a failed download: this runs behind a request that has+ * already streamed progress, so the outcome is a value (`{ success, error }`)+ * the route reports rather than a rejection mid-stream.+ *+ * @param {{model?: string|null, onProgress?: (frame: object) => void, isCancelled?: () => boolean}} [options]+ */+export async function pullMtplxModel({ model = null, onProgress = () => {}, isCancelled } = {}) {+ const binary = requireBinary();+ const repo = model ? requireRepoId(model) : null;+ const label = repo || 'MTPLX\'s default verified checkpoint';++ onProgress({ event: 'start', model: repo, message: `Downloading ${label}. This is a multi-gigabyte download and can take a while.` });+ console.log(`⬇️ MTPLX pull started for ${label}`);++ const args = ['pull', ...(repo ? [repo] : []), '--progress-json'];+ const result = await runStreamingCommand(+ binary,+ args,+ (line) => {+ const frame = parseMtplxPullFrame(line, repo);+ // `complete`/`result` are upstream's own terminal frames — the caller's+ // own completion frame below is the one the client acts on, so don't let+ // an early one tear the progress bar down before the process exits.+ if (frame && frame.event !== 'complete' && frame.event !== 'result') onProgress(frame);+ },+ { timeoutMs: PULL_TIMEOUT_MS, isCancelled }+ );++ if (!result.success) {+ console.error(`❌ MTPLX pull failed for ${label}: ${result.error}`);+ onProgress({ event: 'error', model: repo, message: result.error });+ return { success: false, model: repo, error: result.error };+ }++ // Report what actually landed rather than what was asked for: an interrupted+ // pull can exit 0 with an incomplete pack, and the cache listing is the only+ // honest answer to "can this be served now".+ 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)`);+ onProgress({ event: 'complete', model: repo, message: `${label} downloaded` });+ return { success: true, model: repo, cachedModels: cached };+}++/**+ * Delete one checkpoint from MTPLX's cache.+ *+ * `mtplx remove` owns the deletion rather than PortOS unlinking a directory it+ * inferred: the cache layout (safe-name directories, sidecars, a shared blob+ * store) is upstream's, and a path PortOS assembled itself would be a data-loss+ * bug the first time that layout changed.+ */+export async function removeMtplxModel(model) {+ const binary = requireBinary();+ const repo = requireRepoId(model);++ const result = await bufferedSpawn(binary, ['remove', repo, '--json'], { timeoutMs: REMOVE_TIMEOUT_MS, shell: false });+ if (result.timedOut) throw new ServerError(`\`mtplx remove ${repo}\` timed out`, { status: 504 });++ // `mtplx remove --json` writes its payload to stdout even when it exits 1+ // (nothing to remove), so parse before deciding this failed — the JSON says+ // WHY, and the exit code alone would surface as a bare `}`.+ const text = String(result.stdout || '');+ const start = text.indexOf('{');+ const parsed = start === -1 ? null : safeJSONParse(text.slice(start), null, { allowArray: false });++ if (!result.success) {+ if (parsed?.removed === false) {+ throw new ServerError(`${repo} is not in MTPLX's cache — nothing to remove.`, { status: 404, code: 'MTPLX_MODEL_NOT_CACHED' });+ }+ throw new ServerError(+ `Failed to remove ${repo}: ${spawnFailureDetail(result, `mtplx exited with code ${result.code}`)}`,+ { status: 500 }+ );+ }++ console.log(`🗑️ MTPLX checkpoint removed: ${repo}`);+ return {+ success: true,+ model: repo,+ removed: parsed?.removed !== false,+ bytesFreed: Number.isFinite(Number(parsed?.size_bytes_removed)) ? Number(parsed.size_bytes_removed) : null,+ };+}diff --git a/server/services/mtplxModelManager.test.js b/server/services/mtplxModelManager.test.jsnew file mode 100644index 0000000000..b3bb5734ce--- /dev/null+++ b/server/services/mtplxModelManager.test.js@@ -0,0 +1,204 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import {+ isMtplxRepoId,+ parseMtplxPullFrame,+ pullMtplxModel,+ removeMtplxModel,+ searchMtplxCatalog,+} from './mtplxModelManager.js';+import * as bufferedSpawnModule from '../lib/bufferedSpawn.js';+import * as mtplxModels from '../lib/mtplxModels.js';+import * as processEnv from '../lib/processEnv.js';+import * as streamingSpawn from '../lib/streamingSpawn.js';++const BINARY = '/opt/homebrew/bin/mtplx';++const spawnOk = (stdout) => ({ success: true, code: 0, stdout, stderr: '', timedOut: false });++describe('mtplxModelManager', () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ vi.spyOn(mtplxModels, 'listMtplxCachedModels').mockResolvedValue({ models: [], error: null });+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });++ describe('isMtplxRepoId', () => {+ it('accepts owner/name and rejects anything that could become a flag or a path', () => {+ expect(isMtplxRepoId('Example/Qwen-MTP')).toBe(true);+ // A leading dash would be read as an option by MTPLX's own argparse, and a+ // bare name / URL is not something the search results ever produce.+ expect(isMtplxRepoId('-rf')).toBe(false);+ expect(isMtplxRepoId('Qwen-MTP')).toBe(false);+ expect(isMtplxRepoId('https://huggingface.co/Example/Qwen-MTP')).toBe(false);+ expect(isMtplxRepoId('../../etc/passwd')).toBe(false);+ });+ });++ describe('searchMtplxCatalog', () => {+ it('maps discover cards and omits --query when nothing was typed', async () => {+ const spawn = vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockResolvedValue(spawnOk(JSON.stringify([+ { repo: 'Example/Qwen-MTP', branded_name: 'Qwen MTP', owner: 'Example', downloads: 42, license: 'apache-2.0' },+ { branded_name: 'No repo id — dropped' },+ ])));++ const result = await searchMtplxCatalog({});++ expect(result).toEqual({+ models: [{ repo: 'Example/Qwen-MTP', name: 'Qwen MTP', owner: 'Example', downloads: 42, license: 'apache-2.0' }],+ error: null,+ });+ // An empty `--query ''` would search for the empty string instead of+ // falling through to upstream's default listing.+ expect(spawn.mock.calls[0][1]).not.toContain('--query');+ });++ it('passes a typed query through as its own argv element', async () => {+ const spawn = vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockResolvedValue(spawnOk('[]'));+ await searchMtplxCatalog({ query: 'qwen coder', limit: 5 });+ const args = spawn.mock.calls[0][1];+ expect(args[args.indexOf('--query') + 1]).toBe('qwen coder');+ expect(args[args.indexOf('--limit') + 1]).toBe('5');+ expect(spawn.mock.calls[0][2]).toMatchObject({ shell: false });+ });++ it('reports MTPLX\'s own reason rather than an empty list that reads as "none exist"', async () => {+ vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockResolvedValue({+ success: false, code: 1, stdout: '', stderr: 'error: huggingface.co unreachable', timedOut: false,+ });+ expect(await searchMtplxCatalog({})).toEqual({ models: [], error: 'error: huggingface.co unreachable' });+ });++ it('refuses before spawning when MTPLX is not installed', async () => {+ processEnv.findCommandOnPath.mockReturnValue(null);+ await expect(searchMtplxCatalog({})).rejects.toThrow(/not found on PATH/);+ });+ });++ describe('parseMtplxPullFrame', () => {+ it('normalises a structured progress event', () => {+ expect(parseMtplxPullFrame(+ JSON.stringify({ event: 'progress', repo_id: 'Example/Qwen-MTP', size_bytes: 10, total_bytes: 100, message: 'Downloading model files' }),+ 'Example/Qwen-MTP',+ )).toEqual({ event: 'progress', model: 'Example/Qwen-MTP', received: 10, total: 100, message: 'Downloading model files' });+ });++ it('maps `failed` onto the error event the client clears the bar on', () => {+ expect(parseMtplxPullFrame(JSON.stringify({ event: 'failed', message: 'pull failed' }), 'Example/A'))+ .toMatchObject({ event: 'error', message: 'pull failed' });+ });++ it('keeps an unparseable line as a message instead of dropping it', () => {+ // A download that goes quiet for an hour is indistinguishable from one+ // that hung, so a banner line still surfaces.+ expect(parseMtplxPullFrame('Bootstrapping with pip...', 'Example/A'))+ .toEqual({ event: 'progress', model: 'Example/A', message: 'Bootstrapping with pip...' });+ expect(parseMtplxPullFrame(' ', 'Example/A')).toBeNull();+ });++ it('reports a missing total as null so the bar stays indeterminate, not 0%', () => {+ expect(parseMtplxPullFrame(JSON.stringify({ event: 'start', size_bytes: 0, total_bytes: 0 }), 'Example/A'))+ .toMatchObject({ received: 0, total: null });+ });+ });++ describe('pullMtplxModel', () => {+ it('pulls MTPLX\'s own default when no model is named', async () => {+ const run = vi.spyOn(streamingSpawn, 'runStreamingCommand').mockResolvedValue({ success: true });+ const frames = [];++ const result = await pullMtplxModel({ onProgress: (f) => frames.push(f) });++ expect(run.mock.calls[0][1]).toEqual(['pull', '--progress-json']);+ expect(result).toMatchObject({ success: true, model: null });+ expect(frames.at(-1)).toMatchObject({ event: 'complete' });+ });++ it('names the requested repo id on the command line', async () => {+ const run = vi.spyOn(streamingSpawn, 'runStreamingCommand').mockResolvedValue({ success: true });+ await pullMtplxModel({ model: 'Example/Qwen-MTP' });+ expect(run.mock.calls[0][1]).toEqual(['pull', 'Example/Qwen-MTP', '--progress-json']);+ });++ it('rejects a model that is not a repo id before it reaches argv', async () => {+ const run = vi.spyOn(streamingSpawn, 'runStreamingCommand').mockResolvedValue({ success: true });+ await expect(pullMtplxModel({ model: '--cache-dir=/etc' })).rejects.toThrow(/Hugging Face repo id/);+ expect(run).not.toHaveBeenCalled();+ });++ it('resolves (never throws) with the downloader\'s reason on failure', async () => {+ vi.spyOn(streamingSpawn, 'runStreamingCommand').mockResolvedValue({ success: false, error: 'disk full' });+ const frames = [];+ const result = await pullMtplxModel({ model: 'Example/Qwen-MTP', onProgress: (f) => frames.push(f) });+ expect(result).toEqual({ success: false, model: 'Example/Qwen-MTP', error: 'disk full' });+ expect(frames.at(-1)).toMatchObject({ event: 'error', message: 'disk full' });+ });++ it('forwards progress lines but swallows upstream\'s own terminal frames', async () => {+ vi.spyOn(streamingSpawn, 'runStreamingCommand').mockImplementation(async (_cmd, _args, onLine) => {+ onLine(JSON.stringify({ event: 'progress', size_bytes: 5, total_bytes: 10 }));+ // Upstream emits its own `complete`/`result` before the process exits —+ // letting those through would tear the bar down early.+ onLine(JSON.stringify({ event: 'complete', size_bytes: 10, total_bytes: 10 }));+ return { success: true };+ });+ const frames = [];+ await pullMtplxModel({ model: 'Example/Qwen-MTP', onProgress: (f) => frames.push(f) });+ expect(frames.filter((f) => f.event === 'complete')).toHaveLength(1);+ expect(frames.some((f) => f.event === 'progress' && f.received === 5)).toBe(true);+ });++ it('reports what actually landed in the cache, not what was asked for', async () => {+ vi.spyOn(streamingSpawn, 'runStreamingCommand').mockResolvedValue({ success: true });+ mtplxModels.listMtplxCachedModels.mockResolvedValue({+ models: [{ repo_id: 'Example/Qwen-MTP' }], error: null,+ });+ const result = await pullMtplxModel({ model: 'Example/Qwen-MTP' });+ expect(result.cachedModels).toEqual(['Example/Qwen-MTP']);+ });+ });++ describe('removeMtplxModel', () => {+ it('delegates deletion to `mtplx remove` and reports the freed bytes', async () => {+ const spawn = vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockResolvedValue(+ spawnOk(JSON.stringify({ repo_id: 'Example/Qwen-MTP', removed: true, size_bytes_removed: 2048 })),+ );++ const result = await removeMtplxModel('Example/Qwen-MTP');++ // Never an unlink of a path PortOS assembled itself — the cache layout is+ // upstream's, and guessing it would be a data-loss bug on the first change.+ expect(spawn.mock.calls[0][1]).toEqual(['remove', 'Example/Qwen-MTP', '--json']);+ expect(result).toEqual({ success: true, model: 'Example/Qwen-MTP', removed: true, bytesFreed: 2048 });+ });++ it('refuses anything that is not a repo id', async () => {+ const spawn = vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockResolvedValue(spawnOk('{}'));+ await expect(removeMtplxModel('--cache-dir')).rejects.toThrow(/Hugging Face repo id/);+ expect(spawn).not.toHaveBeenCalled();+ });++ it('reports "not cached" from the JSON payload, not the bare `}` on stdout', async () => {+ // `mtplx remove --json` prints its payload to stdout even on exit 1, so a+ // last-stdout-line heuristic would surface a closing brace as the reason.+ vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockResolvedValue({+ success: false,+ code: 1,+ stdout: JSON.stringify({ repo_id: 'Example/Qwen-MTP', removed: false }, null, 2),+ stderr: '',+ timedOut: false,+ });+ const err = await removeMtplxModel('Example/Qwen-MTP').catch((e) => e);+ expect(err.status).toBe(404);+ expect(err.message).toMatch(/not in MTPLX's cache/);+ });++ it('surfaces MTPLX\'s stderr when the removal fails', async () => {+ vi.spyOn(bufferedSpawnModule, 'bufferedSpawn').mockResolvedValue({+ success: false, code: 1, stdout: '', stderr: 'error: model not cached', timedOut: false,+ });+ await expect(removeMtplxModel('Example/Qwen-MTP')).rejects.toThrow(/error: model not cached/);+ });+ });+});diff --git a/server/services/mtplxServerManager.js b/server/services/mtplxServerManager.jsindex ad34425c55..85188b3266 100644--- a/server/services/mtplxServerManager.js+++ b/server/services/mtplxServerManager.js@@ -12,10 +12,11 @@* re-adopt a server it started earlier instead of losing track of a detached* pid. A detached child gets none of that.*- * Two limits carried over from `docs/features/mtplx.md`, unchanged:- * - **Weights are never downloaded.** `mtplx serve` is started on a checkpoint- * ALREADY in MTPLX's cache; an empty cache is reported with the `mtplx pull`- * command that fixes it.+ * Two limits carried over from `docs/features/mtplx.md`:+ * - **A start never downloads weights.** `mtplx serve` is started on a+ * checkpoint ALREADY in MTPLX's cache; an empty cache is reported rather+ * than silently filled. Fetching one is its own explicit, user-pressed+ * action in `mtplxModelManager.js` — in the UI, never in a terminal.* - **MTPLX's privileged paths are never touched.** Upstream's optional* `mtplx max --install` fan-control helper stays an explicit operator action* outside PortOS.@@ -62,15 +63,16 @@ const INSTALL_TIMEOUT_MS = 20 * 60 * 1000;const DEFAULT_HOST = '127.0.0.1';const DEFAULT_PORT = Number(localEndpointPort(LOCAL_RUNTIMES.mtplx.defaultBaseUrl)) || 8000;-/**- * Why an installed MTPLX still cannot be started. Weights are a multi-gigabyte- * download and stay the user's decision, so this names the one command that- * fixes it instead of running it.- *//** MTPLX is an Apple-Silicon MLX runtime — nothing to install anywhere else. */export const MTPLX_UNSUPPORTED_REASON = 'MTPLX runs only on macOS with Apple Silicon.';-const MTPLX_NO_MODEL_ERROR = 'MTPLX has no model weights cached, so its server exits before it binds a port. Run `mtplx pull` in a terminal to fetch its default checkpoint (or `mtplx pull <hf-repo-id>` for another MTP model) — a multi-gigabyte download PortOS will not start for you — then start MTPLX again.';+/**+ * Why an installed MTPLX still cannot be started. Weights are a multi-gigabyte+ * download and stay the user's decision — so a start never fetches them+ * silently, and this names the in-app control that does instead of a terminal+ * command (`services/mtplxModelManager.js`).+ */+const MTPLX_NO_MODEL_ERROR = 'MTPLX has no model weights cached, so its server exits before it binds a port. Use "Download default checkpoint" on the MTPLX card (or search for another MTP model there) to fetch one — a multi-gigabyte download PortOS will not start without you asking — then start MTPLX again.';let currentConfig = null;let lastExitError = null;@@ -163,6 +165,19 @@ export async function getMtplxServerStatus() {// `null` = the dump could not be read, which is not the same as "no".runAtStartup: savedApps === null ? null : savedApps.includes(MTPLX_APP),cachedModels: (cache.models || []).map((m) => m?.repo_id).filter(Boolean),+ // The same cache, with what the manage-checkpoints UI needs to let a user+ // free the disk: how big each pack is, and whether it is actually servable+ // (an interrupted pull leaves a directory that lists but cannot load).+ cachedModelRows: (cache.models || [])+ .filter((m) => m?.repo_id)+ .map((m) => ({+ repo: m.repo_id,+ sizeBytes: Number.isFinite(Number(m.size_bytes)) ? Number(m.size_bytes) : null,+ hasRuntimeContract: m.has_runtime_contract === true,+ // `validation.ok` absent means an older `mtplx models` that did not+ // report one — treat that as usable rather than flagging every row.+ valid: m.validation?.ok !== false,+ })),cacheError: cache.error,recentLogs: logs.withPm2Logs(`${pm2Logs?.stdout || ''}\n${pm2Logs?.stderr || ''}`),lastExitError: isReadFailed ? 'Failed to read PM2 status' : lastExitError,@@ -216,7 +231,7 @@ async function resolveStartModel(requested, emit) {const model = pickMtplxCachedModel(cache.models);if (!model) {const count = cache.models.length;- return { error: `MTPLX's cache holds ${count} model${count === 1 ? '' : 's'}, but none passed its own file check — an interrupted \`mtplx pull\` leaves a partial download behind. Re-run \`mtplx pull <hf-repo-id>\` in a terminal, then try again.` };+ return { error: `MTPLX's cache holds ${count} model${count === 1 ? '' : 's'}, but none passed its own file check — an interrupted download leaves a partial pack behind. Remove it on the MTPLX card and download the checkpoint again, then try again.` };}return { model };}diff --git a/server/services/mtplxServerManager.test.js b/server/services/mtplxServerManager.test.jsindex d12ff78fcd..d50ed6576d 100644--- a/server/services/mtplxServerManager.test.js+++ b/server/services/mtplxServerManager.test.js@@ -141,9 +141,13 @@ describe('mtplxServerManager', () => {expect(launch[launch.indexOf('--port') + 1]).toBe('8010');});- it('refuses with the `mtplx pull` fix when the cache was read and is empty', async () => {+ it('refuses with the in-app download as the fix when the cache was read and is empty', async () => {vi.spyOn(mtplxModels, 'listMtplxCachedModels').mockResolvedValue({ models: [], error: null });- await expect(startMtplxServer()).rejects.toThrow(/mtplx pull/);+ // The fix a user is pointed at is a button in PortOS, never a terminal+ // command they have to leave the app to run (PRD NR-9).+ const err = await startMtplxServer().catch((e) => e);+ expect(err.message).toMatch(/Download default checkpoint/);+ expect(err.message).not.toMatch(/terminal/);expect(execPm2Calls.some((args) => args[0] === 'start')).toBe(false);});