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
Unify start/stop controls for every local LLM server, and run MTPLX under PM2
Adam Eivy55f569a107a9
diff --git a/README.md b/README.mdindex 2f9bed1712..66c125338a 100644--- a/README.md+++ b/README.md@@ -430,7 +430,7 @@ Full catalog (including design plans, ADRs, and research notes): [docs/README.md- [Claude on Ollama](./docs/features/claude-ollama.md) — Run agent tasks on a local model- [CoS Agent Runner](./docs/features/cos-agent-runner.md) — Isolated agent process architecture- [CoS Enhancement](./docs/features/cos-enhancement.md) — Hybrid search, proactive execution, error recovery-- [MTPLX](./docs/features/mtplx.md) — Multiplexed agent execution and terminal streaming+- [MTPLX](./docs/features/mtplx.md) — Native multi-token-prediction Qwen runtime on Apple Silicon, managed as a PM2 process from Models → LLMs- [Memory System](./docs/features/memory-system.md) — Semantic memory with vector search and importance decay- [Digital Twin](./docs/features/digital-twin.md) — Genome, chronotype, taste, and mortality-aware goals- [Identity System](./docs/features/identity-system.md) — Extended identity modeling (P1-P3)diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex 02bde07e91..268e4c1c11 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -1,6 +1,6 @@import { useState, useEffect, useRef, useCallback, useMemo } from 'react';import { Link, useNavigate } from 'react-router';-import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Square, Power, PowerOff, Eye, Wrench, Brain, Code2, MessageSquare, Boxes, AlertTriangle, FlaskConical, Music, ArrowUpCircle, Zap, ChevronDown, ChevronUp, Terminal } from 'lucide-react';+import { Cpu, Box, ArrowRightLeft, Download, Trash2, RefreshCw, Search, Plus, ExternalLink, Star, Link2, Copy, Play, Power, PowerOff, Eye, Wrench, Brain, Code2, MessageSquare, Boxes, AlertTriangle, FlaskConical, Music, ArrowUpCircle, Zap, ChevronDown, ChevronUp, Terminal } from 'lucide-react';import toast from '../ui/Toast';import ConfirmButtonPair from '../ui/ConfirmButtonPair';import BrailleSpinner from '../BrailleSpinner';@@ -11,10 +11,13 @@ import {getLocalLlmStatus, getLocalLlmCatalog, getLocalLlmHuggingFaceSearch, installLocalLlmModel,deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService,installAudioModel, patchSettingsSlice, getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer,- downloadSpecDecodeModel+ downloadSpecDecodeModel, controlLmStudioService, getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx,+ saveRuntimeStartupList} from '../../services/api';import socket from '../../services/socket';import SpecDecodeWeightRow from './SpecDecodeWeightRow.jsx';+import RuntimeServersCard from './RuntimeServersCard.jsx';+import MtplxServerCard from './MtplxServerCard.jsx';const BACKENDS = [{ id: 'ollama', label: 'Ollama', icon: Cpu },@@ -191,8 +194,6 @@ function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAcconst Icon = backend.icon;const other = backend.id === 'ollama' ? 'lmstudio' : 'ollama';const otherData = status?.[other];- const statusLabel = data?.disabled ? 'Disabled' : data?.available ? 'Running' : data?.installed ? 'Installed (stopped)' : 'Not installed';- const statusColor = data?.disabled ? 'bg-gray-600' : data?.available ? 'bg-port-success' : data?.installed ? 'bg-port-warning' : 'bg-gray-600';const startupService = backend.id === 'ollama' ? data?.service : null;const runsAtStartup = Boolean(startupService?.runAtStartup);// The window resident models were ACTUALLY loaded at — Ollama picks it from@@ -214,16 +215,14 @@ function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAc{isDefault && (<spanclassName="text-xs px-1.5 py-0.5 bg-port-accent/20 text-port-accent rounded"- title="PortOS routes local-LLM runs here by default. This is independent of whether the server is running (see the status dot)."+ title="PortOS routes local-LLM runs here by default. This is independent of whether the server is running — see Local Runtime Servers above.">Default</span>)}- <span className={`w-2 h-2 rounded-full ${statusColor}`} title={statusLabel} /></div></div>- <div className="text-sm text-white">{statusLabel}</div><div className="text-xs text-gray-400">{data?.modelCount ?? 0} model{(data?.modelCount ?? 0) === 1 ? '' : 's'} installed{data?.version && <> · v{data.version}</>}@@ -245,55 +244,8 @@ function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAc)}</div>- {!data?.installed && (- <div className="flex flex-wrap gap-1.5 pt-1 border-t border-port-border/50">- {data?.canAutoInstall ? (- <button- onClick={() => runAction(- `install-backend-${backend.id}`,- () => installLocalLlmBackend(backend.id),- (r) => r?.note ? `Installed ${backend.label} — ${r.note}` : `Installed ${backend.label}`- )}- disabled={busy}- className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`}- title="Install via Homebrew (macOS) / official installer (Linux)"- >- {actionInProgress === `install-backend-${backend.id}` ? <BrailleSpinner /> : <Download size={12} />}- Install {backend.label}- </button>- ) : (- <a- href={data?.downloadUrl}- target="_blank"- rel="noreferrer"- className={`${btnClass} bg-port-border hover:bg-port-border/70 text-white no-underline`}- >- <ExternalLink size={12} />- Get {backend.label}- </a>- )}- </div>- )}-{data?.installed && (<div className="flex flex-wrap gap-1.5 pt-1 border-t border-port-border/50">- {backend.id === 'ollama' && data?.canControl && (- <button- onClick={() => runAction(- `ollama-service-${data.available ? 'stop' : 'start'}`,- () => controlOllamaService(data.available ? 'stop' : 'start'),- data.available ? 'Ollama stopped' : 'Ollama is running'- )}- disabled={busy}- className={`${btnClass} ${data.available ? 'bg-port-warning/20 hover:bg-port-warning/30 text-port-warning' : 'bg-port-accent/20 hover:bg-port-accent/30 text-port-accent'}`}- title={data.available ? 'Stop the local Ollama server' : 'Start the local Ollama server'}- >- {actionInProgress === `ollama-service-${data.available ? 'stop' : 'start'}`- ? <BrailleSpinner />- : data.available ? <Square size={12} /> : <Play size={12} />}- {data.available ? 'Stop' : 'Start'} Ollama- </button>- )}{backend.id === 'ollama' && data?.updateAvailable && (data?.canUpgrade ? (<button@@ -322,23 +274,6 @@ function BackendCard({ backend, status, isDefault, busy, actionInProgress, runAc</a>))}- {backend.id === 'ollama' && startupService?.supported && (- <button- onClick={() => runAction(- `ollama-service-${runsAtStartup ? 'disable' : 'enable'}`,- () => controlOllamaService(runsAtStartup ? 'disable' : 'enable'),- runsAtStartup ? 'Ollama background service disabled' : 'Ollama will run at login'- )}- disabled={busy}- className={`${btnClass} ${runsAtStartup ? 'bg-port-warning/20 hover:bg-port-warning/30 text-port-warning' : 'bg-port-accent/20 hover:bg-port-accent/30 text-port-accent'}`}- title={runsAtStartup ? 'Stop the Homebrew service and remove the launch-at-login registration' : 'Start Ollama with Homebrew services so it runs in the background at login'}- >- {actionInProgress === `ollama-service-${runsAtStartup ? 'disable' : 'enable'}`- ? <BrailleSpinner />- : runsAtStartup ? <PowerOff size={12} /> : <Power size={12} />}- {runsAtStartup ? 'Disable Startup' : 'Run at Startup'}- </button>- )}{!isDefault && (<buttononClick={() => runAction(`switch-${backend.id}`, () => switchLocalLlmBackend(backend.id), `${backend.label} is now the default backend`)}@@ -421,7 +356,12 @@ export function LocalLlmTab() {const selectedInitialized = useRef(false);const [llamaStatus, setLlamaStatus] = useState(null);+ const [mtplxStatus, setMtplxStatus] = 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.+ const llamaSectionRef = useRef(null);+ const mtplxSectionRef = useRef(null);const [llamaPresetId, setLlamaPresetId] = useState(DEFAULT_SPEC_PRESET_ID);const [llamaForm, setLlamaForm] = useState({model: '',@@ -461,10 +401,20 @@ export function LocalLlmTab() {.catch(() => null);}, []);+ const loadMtplxStatus = useCallback(() => (+ getMtplxServerStatus({ silent: true })+ .then((res) => {+ if (res) setMtplxStatus(res);+ return res;+ })+ .catch(() => null)+ ), []);+const loadStatus = useCallback(() => {const requestId = ++statusRequestId.current;setLoading(true);loadLlamaStatus();+ loadMtplxStatus();return getLocalLlmStatus({ silent: true }).then((s) => {if (requestId !== statusRequestId.current) return;@@ -481,7 +431,7 @@ export function LocalLlmTab() {.finally(() => {if (requestId === statusRequestId.current) setLoading(false);});- }, [loadLlamaStatus]);+ }, [loadLlamaStatus, loadMtplxStatus]);// `source` and `category` are required rather than defaulted from state: a// state default would put them in the dep list, so `loadCatalog`'s identity@@ -611,13 +561,18 @@ export function LocalLlmTab() {}, [loadStatus, loadCatalog, selected, query, catalogSource, activeCategory]);const runAction = useCallback((key, fn, successMsg, options = {}) => {- const { onError, clearConfirm = true } = options;+ const { onError, clearConfirm = true, ollamaService = false } = options;if (clearConfirm) setConfirmAction(null);setActionInProgress(key);return fn().then((result) => {if (successMsg) toast.success(typeof successMsg === 'function' ? successMsg(result) : successMsg);- if (typeof result?.running === 'boolean') {+ // Optimistic repaint for the Ollama service controls only. Every runtime+ // start/stop result carries `running` — llama-server's and MTPLX's too —+ // so the CALLER declares this, rather than it being inferred from the+ // response shape; otherwise stopping MTPLX would paint Ollama as stopped+ // until the refetch lands.+ if (ollamaService && typeof result?.running === 'boolean') {setStatus((prev) => prev ? ({...prev,ollama: {@@ -642,6 +597,62 @@ export function LocalLlmTab() {}, [loadStatus, loadCatalog, selected, query, catalogSource, activeCategory]);const busy = actionInProgress != null;++ // === Unified runtime-server controls ======================================+ // Every handler routes through `runAction` so one busy/spinner/refresh path+ // covers all four runtimes. The `runtime-<verb>-<id>` keys are what+ // `RuntimeServersCard` matches to place its spinner.+ const controlOllama = (action) => runAction(+ action === 'enable' || action === 'disable' ? 'runtime-startup-ollama' : `runtime-${action}-ollama`,+ () => controlOllamaService(action),+ { start: 'Ollama is running', stop: 'Ollama stopped', enable: 'Ollama will run at login', disable: 'Ollama background service disabled' }[action],+ { ollamaService: true }+ );+ const controlLmStudio = (action) => runAction(+ `runtime-${action}-lmstudio`,+ () => controlLmStudioService(action),+ action === 'start' ? 'LM Studio server is running' : 'LM Studio server stopped'+ );+ const installRuntimeBackend = (backend) => runAction(+ `runtime-install-${backend}`,+ () => installLocalLlmBackend(backend),+ (r) => r?.note ? `Installed ${labelFor(backend)} — ${r.note}` : `Installed ${labelFor(backend)}`+ );+ const runtimeInstallLlama = () => runAction(+ 'runtime-install-llama',+ () => installLlamaServer(),+ 'llama.cpp installed'+ ).then(loadLlamaStatus);+ const runtimeStopLlama = () => runAction(+ 'runtime-stop-llama',+ () => stopLlamaServer(),+ (r) => r?.message || 'llama-server stopped'+ ).then(loadLlamaStatus);+ const runtimeInstallMtplx = () => runAction(+ 'runtime-install-mtplx',+ () => installMtplx(),+ 'MTPLX installed'+ ).then(loadMtplxStatus);+ const runtimeStartMtplx = (config = {}) => runAction(+ 'runtime-start-mtplx',+ () => startMtplxServer(config),+ // `online: false` is "started, still loading its checkpoint" — not a+ // failure. Saying "running" there would be wrong the moment the user checks.+ (r) => (r?.online+ ? `MTPLX is running at ${r?.endpoint || 'its endpoint'}`+ : 'MTPLX started — it\'s loading its checkpoint, refresh in a moment')+ ).then(loadMtplxStatus);+ const runtimeStopMtplx = () => runAction(+ 'runtime-stop-mtplx',+ () => stopMtplxServer(),+ (r) => r?.message || 'MTPLX stopped'+ ).then(loadMtplxStatus);+ const saveRuntimeStartup = () => runAction(+ 'runtime-save-startup',+ () => saveRuntimeStartupList(),+ 'Saved — the PM2 processes running now will come back after a reboot'+ ).then(() => { loadLlamaStatus(); loadMtplxStatus(); });+ const scrollTo = (ref) => ref.current?.scrollIntoView({ behavior: 'smooth', block: 'start' });const selectedData = status?.[selected];const selectedOllamaStartupAction = selectedData?.service?.supported ? 'enable' : 'start';const selectedOllamaStartupLabel = selectedData?.service?.supported ? 'Run at Startup' : 'Start Ollama';@@ -984,7 +995,29 @@ export function LocalLlmTab() {return (<div className="space-y-4">- {/* Backends — status + switch/migrate */}+ {/* One start/stop/install surface for every local server PortOS can run */}+ <RuntimeServersCard+ status={status}+ llamaStatus={llamaStatus}+ mtplxStatus={mtplxStatus}+ loading={loading}+ busy={busy}+ actionInProgress={actionInProgress}+ onRefresh={loadStatus}+ onControlOllama={controlOllama}+ onControlLmStudio={controlLmStudio}+ onInstallBackend={installRuntimeBackend}+ onInstallLlama={runtimeInstallLlama}+ onStopLlama={runtimeStopLlama}+ onConfigureLlama={() => scrollTo(llamaSectionRef)}+ onConfigureMtplx={() => scrollTo(mtplxSectionRef)}+ onInstallMtplx={runtimeInstallMtplx}+ onStartMtplx={runtimeStartMtplx}+ onStopMtplx={runtimeStopMtplx}+ onSaveStartup={saveRuntimeStartup}+ />++ {/* Backends — model catalog, default marker, cross-backend import */}<div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4"><div className="flex items-center justify-between"><h2 className="text-sm font-medium text-gray-300">Local LLM Backends</h2>@@ -993,7 +1026,7 @@ export function LocalLlmTab() {</button></div><p className="text-xs text-gray-500">- Both backends can be installed and running at the same time — <span className="text-gray-400">Default</span> just sets which one PortOS routes local-LLM runs to. Use <span className="text-gray-400">Import from…</span> to copy or link models between them without re-downloading.+ Ollama and LM Studio are the two backends PortOS keeps a model catalog for — both can be installed and running at once, and <span className="text-gray-400">Default</span> just sets which one PortOS routes local-LLM runs to. Use <span className="text-gray-400">Import from…</span> to copy or link models between them without re-downloading. Start and stop them (and llama.cpp and MTPLX) from <span className="text-gray-400">Local Runtime Servers</span> above.</p><p className="text-xs text-gray-500">For local coding agents, configure the shared <Link to="/ai" className="text-port-accent hover:underline">temperature, top-p and thinking defaults in AI Providers</Link>. Every local OpenAI-compatible backend receives them — Ollama, llama.cpp and MTPLX, whether reached directly or through an OpenCode CLI/TUI wrapper. Every control left blank is simply not sent, so the backend keeps its own default — Ollama agent runs fall back to temperature 0.6.@@ -1088,34 +1121,26 @@ export function LocalLlmTab() {)}</div>+ {/* MTPLX — PM2-managed native-MTP runtime (Apple Silicon) */}+ <div ref={mtplxSectionRef}>+ <MtplxServerCard+ status={mtplxStatus}+ loading={loading}+ busy={busy}+ actionInProgress={actionInProgress}+ onRefresh={loadMtplxStatus}+ onStart={runtimeStartMtplx}+ onStop={runtimeStopMtplx}+ onInstall={runtimeInstallMtplx}+ />+ </div>+{/* Speculative Decoding & Custom Runtimes (DFlash 2 / llama.cpp) */}- <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4">+ <div ref={llamaSectionRef} className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4"><div className="flex items-center justify-between flex-wrap gap-2"><div className="flex items-center gap-2"><Zap size={16} className="text-port-accent" /><h2 className="text-sm font-medium text-gray-300">Speculative Decoding & Custom Runtimes (DFlash 2 / llama.cpp)</h2>- {llamaStatus?.running && llamaStatus?.managed && (- <span className="px-2 py-0.5 text-xs rounded bg-port-success/20 text-port-success flex items-center gap-1.5">- <span className="w-2 h-2 rounded-full bg-port-success animate-pulse" />- Running (PID {llamaStatus.pid})- </span>- )}- {llamaStatus?.running && !llamaStatus?.managed && (- <span className="px-2 py-0.5 text-xs rounded bg-blue-500/20 text-blue-300 flex items-center gap-1.5">- <span className="w-2 h-2 rounded-full bg-blue-400" />- Active on {llamaStatus.endpoint} (External)- </span>- )}- {!llamaStatus?.running && llamaStatus?.installed && (- <span className="px-2 py-0.5 text-xs rounded bg-gray-500/20 text-gray-400">- Stopped- </span>- )}- {!llamaStatus?.installed && (- <span className="px-2 py-0.5 text-xs rounded bg-port-warning/20 text-port-warning" title="Install via Homebrew: brew install llama.cpp or compile with DFlash2 support">- llama-server not found on PATH- </span>- )}</div><div className="flex items-center gap-3"><button@@ -1519,7 +1544,8 @@ export function LocalLlmTab() {onClick={() => runAction(`ollama-service-${selectedOllamaStartupAction}-models`,() => controlOllamaService(selectedOllamaStartupAction),- selectedOllamaStartupAction === 'enable' ? 'Ollama will run at login' : 'Ollama is running'+ selectedOllamaStartupAction === 'enable' ? 'Ollama will run at login' : 'Ollama is running',+ { ollamaService: true })}disabled={busy}className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`}diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsxindex 68c020044a..14973bfd54 100644--- a/client/src/components/settings/LocalLlmTab.test.jsx+++ b/client/src/components/settings/LocalLlmTab.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import { MemoryRouter } from 'react-router';vi.mock('../../services/api', () => ({@@ -13,6 +13,12 @@ vi.mock('../../services/api', () => ({installLocalLlmBackend: vi.fn(),upgradeLocalLlmBackend: vi.fn(),controlOllamaService: vi.fn(),+ controlLmStudioService: vi.fn(),+ getMtplxServerStatus: vi.fn().mockResolvedValue({ installed: false, running: false, supported: true, cachedModels: [] }),+ startMtplxServer: vi.fn(),+ stopMtplxServer: vi.fn(),+ installMtplx: vi.fn(),+ saveRuntimeStartupList: vi.fn(),installAudioModel: vi.fn(),patchSettingsSlice: vi.fn(),getLlamaServerStatus: vi.fn().mockResolvedValue({ installed: false, running: false }),@@ -94,6 +100,41 @@ describe('LocalLlmTab backend disable state', () => {});});+describe('LocalLlmTab runtime servers', () => {+ it('mounts one control surface covering every local runtime, not just the catalog backends', async () => {+ await renderTab();+ const card = screen.getByRole('heading', { name: 'Local Runtime Servers' }).closest('div.bg-port-card');+ for (const label of ['Ollama', 'LM Studio', 'llama.cpp', 'MTPLX']) {+ expect(within(card).getByText(label)).toBeInTheDocument();+ }+ });++ it('starts MTPLX from that surface', async () => {+ const { getMtplxServerStatus, startMtplxServer } = await import('../../services/api');+ getMtplxServerStatus.mockResolvedValue({+ installed: true, running: false, supported: true, cachedModels: ['Example/Qwen-MTP'], endpoint: 'http://127.0.0.1:8000/v1',+ });+ startMtplxServer.mockResolvedValue({ success: true, online: true, endpoint: 'http://127.0.0.1:8000/v1' });++ await renderTab();+ const card = screen.getByRole('heading', { name: 'Local Runtime Servers' }).closest('div.bg-port-card');+ const mtplxRow = within(card).getByText('MTPLX').closest('div.flex.flex-col');+ fireEvent.click(within(mtplxRow).getByRole('button', { name: /^Start/ }));++ await waitFor(() => expect(startMtplxServer).toHaveBeenCalled());+ });++ it('saves the PM2 process list so the managed daemons survive a reboot', async () => {+ const { saveRuntimeStartupList } = await import('../../services/api');+ saveRuntimeStartupList.mockResolvedValue({ success: true });++ await renderTab();+ fireEvent.click(screen.getByRole('button', { name: /Save PM2 list for reboot/ }));++ await waitFor(() => expect(saveRuntimeStartupList).toHaveBeenCalled());+ });+});+describe('LocalLlmTab installed models', () => {it('links to the shared local generation controls', async () => {await renderTab();diff --git a/client/src/components/settings/MtplxServerCard.jsx b/client/src/components/settings/MtplxServerCard.jsxnew file mode 100644index 0000000000..2ab7b19329--- /dev/null+++ b/client/src/components/settings/MtplxServerCard.jsx@@ -0,0 +1,169 @@+import { useState } from 'react';+import { Link } from 'react-router';+import { Gauge, RefreshCw, ExternalLink, Play, Square, Download, Terminal } from 'lucide-react';+import BrailleSpinner from '../BrailleSpinner';++/**+ * 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`.+ */++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';++export default function MtplxServerCard({+ status,+ loading,+ busy,+ actionInProgress,+ onRefresh,+ onStart,+ onStop,+ onInstall,+}) {+ // '' = let PortOS pick from the cache (which is also what the readiness+ // checklist's one-click setup does).+ const [model, setModel] = useState('');+ const [port, setPort] = useState('');+ const [showLogs, setShowLogs] = useState(false);++ const cached = status?.cachedModels || [];+ const emptyCache = Boolean(status?.installed) && cached.length === 0 && !status?.cacheError;+ const external = status?.running && status?.managed === false;++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-4">+ <div className="flex items-center justify-between flex-wrap gap-2">+ <div className="flex items-center gap-2">+ <Gauge size={16} className="text-port-accent" />+ <h2 className="text-sm font-medium text-gray-300">MTPLX (native multi-token prediction)</h2>+ </div>+ <div className="flex items-center gap-3">+ <button+ onClick={onRefresh}+ disabled={loading}+ className="p-1 text-gray-400 hover:text-white transition-colors"+ title="Refresh MTPLX status"+ aria-label="Refresh MTPLX status"+ >+ <RefreshCw size={13} className={loading ? 'animate-spin' : ''} />+ </button>+ <Link to="/ai" className="text-xs text-port-accent hover:underline flex items-center gap-1">+ MTPLX presets in AI Providers <ExternalLink size={11} />+ </Link>+ </div>+ </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.+ </p>++ {!status ? (+ <p className="text-xs text-gray-500">Checking for MTPLX…</p>+ ) : status.supported === false ? (+ <p className="text-xs text-gray-500">{status.unsupportedReason || 'MTPLX runs only on macOS with Apple Silicon.'}</p>+ ) : !status.installed ? (+ <div className="bg-port-warning/10 border border-port-warning/30 rounded-lg p-3 text-xs text-port-warning flex flex-col sm:flex-row sm:items-center justify-between gap-3">+ <div className="space-y-1">+ <p className="font-semibold">`mtplx` was not detected on system PATH.</p>+ <p className="text-gray-300">Installs from upstream's Homebrew tap, or with pip on a host without Homebrew.</p>+ </div>+ <button onClick={onInstall} disabled={busy} className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent shrink-0`}>+ {actionInProgress === 'runtime-install-mtplx' ? <BrailleSpinner /> : <Download size={13} />}+ Install MTPLX+ </button>+ </div>+ ) : status.running ? (+ <div className="bg-port-bg border border-port-success/30 rounded-lg p-3 space-y-3">+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">+ <div className="text-xs text-gray-300 space-y-1">+ <p><span className="text-gray-500">Endpoint:</span> <code className="text-port-success">{status.endpoint}</code></p>+ {status.config?.model && (+ <p><span className="text-gray-500">Model:</span> <code className="text-gray-300">{status.config.model}</code></p>+ )}+ {external && (+ <p className="text-blue-300">Started outside PortOS — stop it where you started it.</p>+ )}+ </div>+ {!external && (+ <button onClick={onStop} disabled={busy} className={`${btnClass} bg-port-warning/20 hover:bg-port-warning/30 text-port-warning shrink-0`}>+ {actionInProgress === 'runtime-stop-mtplx' ? <BrailleSpinner /> : <Square size={13} />}+ Stop MTPLX+ </button>+ )}+ </div>+ </div>+ ) : (+ <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.+ </p>+ ) : (+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">+ <div className="space-y-1">+ <label htmlFor="mtplx-model" className="block text-xs text-gray-400">Checkpoint</label>+ <select+ id="mtplx-model"+ value={model}+ onChange={(e) => setModel(e.target.value)}+ className="w-full bg-port-card border border-port-border rounded px-2 py-1.5 text-xs text-white"+ >+ <option value="">Auto — first verified checkpoint in the cache</option>+ {cached.map((id) => <option key={id} value={id}>{id}</option>)}+ </select>+ </div>+ <div className="space-y-1">+ <label htmlFor="mtplx-port" className="block text-xs text-gray-400">Port</label>+ <input+ id="mtplx-port"+ type="number"+ value={port}+ placeholder={String(status?.port ?? 8000)}+ onChange={(e) => setPort(e.target.value)}+ className="w-full bg-port-card border border-port-border rounded px-2 py-1.5 text-xs text-white"+ />+ <p className="text-[11px] text-gray-500">Must match the endpoint your MTPLX provider points at.</p>+ </div>+ </div>+ )}+ {status?.cacheError && (+ <p className="text-xs text-gray-500">Couldn't read MTPLX's model cache ({status.cacheError}) — starting will fall through to MTPLX's own default checkpoint.</p>+ )}+ <button+ 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'}+ >+ {actionInProgress === 'runtime-start-mtplx' ? <BrailleSpinner /> : <Play size={13} />}+ Start MTPLX+ </button>+ </div>+ )}++ {status?.recentLogs?.length > 0 && (+ <div className="space-y-1">+ <button+ type="button"+ onClick={() => setShowLogs((prev) => !prev)}+ className="text-[11px] text-gray-500 hover:text-gray-300 flex items-center gap-1"+ >+ <Terminal size={11} />+ {showLogs ? 'Hide server logs' : `View server logs (${status.recentLogs.length} lines)`}+ </button>+ {showLogs && (+ <pre className="text-[10px] text-gray-400 bg-port-bg border border-port-border/60 p-2.5 rounded max-h-40 overflow-y-auto font-mono whitespace-pre-wrap">+ {status.recentLogs.join('\n')}+ </pre>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/settings/MtplxServerCard.test.jsx b/client/src/components/settings/MtplxServerCard.test.jsxnew file mode 100644index 0000000000..f25ab9e6d5--- /dev/null+++ b/client/src/components/settings/MtplxServerCard.test.jsx@@ -0,0 +1,72 @@+import { describe, it, expect, vi } from 'vitest';+import { 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() };+ render(+ <MemoryRouter>+ <MtplxServerCard status={status} loading={false} busy={false} actionInProgress={null} {...handlers} {...props} />+ </MemoryRouter>,+ );+ return handlers;+};++describe('MtplxServerCard', () => {+ it('starts on the cached checkpoint and port the user picked', () => {+ const handlers = renderCard({+ installed: true,+ running: false,+ supported: true,+ port: 8000,+ cachedModels: ['Example/Qwen-MTP', 'Example/Other-MTP'],+ });++ fireEvent.change(screen.getByLabelText('Checkpoint'), { target: { value: 'Example/Other-MTP' } });+ fireEvent.change(screen.getByLabelText('Port'), { target: { value: '8010' } });+ fireEvent.click(screen.getByRole('button', { name: /Start MTPLX/ }));++ 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'] });+ 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 });+ expect(screen.getByText(/model cache is empty/)).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /Start MTPLX/ })).toBeDisabled();+ });++ 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' });+ 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' });+ 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 });+ 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.' });+ 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.jsxnew file mode 100644index 0000000000..bab055c92a--- /dev/null+++ b/client/src/components/settings/RuntimeServersCard.jsx@@ -0,0 +1,304 @@+import { Link } from 'react-router';+import { Cpu, Box, Zap, Gauge, Play, Square, Download, Power, PowerOff, RefreshCw, Save, Settings2, ExternalLink } from 'lucide-react';+import BrailleSpinner from '../BrailleSpinner';++/**+ * One control surface for every local LLM server PortOS can run.+ *+ * Ollama, LM Studio, llama.cpp (`llama-server`) and MTPLX each used to be+ * managed somewhere different — two of them inline on this tab, one further down+ * behind the speculative-decoding launcher, and MTPLX only from a provider+ * readiness checklist on another page. They all answer the same three questions+ * ("installed?", "running?", "start it / stop it"), so they get one table that+ * asks them the same way.+ *+ * The runtimes are NOT mutually exclusive: any number of them can be installed+ * and running at once. Which one PortOS routes a given run to is a separate+ * decision — the default backend below, or the provider a task names.+ */++/** Uniform lifecycle state for a row, from each runtime's own status shape. */+const STATE_META = {+ running: { label: 'Running', cls: 'bg-port-success/20 text-port-success', dot: 'bg-port-success animate-pulse' },+ external: { label: 'Running (external)', cls: 'bg-blue-500/20 text-blue-300', dot: 'bg-blue-400' },+ stopped: { label: 'Stopped', cls: 'bg-port-warning/20 text-port-warning', dot: 'bg-port-warning' },+ missing: { label: 'Not installed', cls: 'bg-gray-500/20 text-gray-400', dot: 'bg-gray-500' },+ disabled: { label: 'Disabled', cls: 'bg-gray-500/20 text-gray-400', dot: 'bg-gray-600' },+ unsupported: { label: 'Unavailable on this platform', cls: 'bg-gray-500/20 text-gray-400', dot: 'bg-gray-600' },+};++const btnClass = 'flex items-center gap-1.5 px-2 py-1 text-xs font-medium rounded transition-colors disabled:opacity-50';+const neutralBtn = `${btnClass} bg-port-border hover:bg-port-border/70 text-white`;+const accentBtn = `${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`;++/**+ * Rows for the two backends PortOS installs and catalogs models for.+ *+ * `managed` is deliberately absent: PortOS does not own these processes (Ollama+ * runs as a Homebrew/systemd service, LM Studio's server belongs to its app), so+ * "running" is all that can honestly be reported — there is no external-vs-ours+ * distinction to draw.+ */+function backendRow({ id, label, icon, data, onStart, onStop, onInstall }) {+ const state = data?.disabled ? 'disabled' : data?.available ? 'running' : data?.installed ? 'stopped' : 'missing';+ return {+ id,+ label,+ icon,+ state,+ endpoint: data?.baseUrl || null,+ detail: data?.installed && Number.isFinite(data?.modelCount)+ ? `${data.modelCount} model${data.modelCount === 1 ? '' : 's'} installed`+ : null,+ onInstall: !data?.installed && data?.canAutoInstall ? onInstall : null,+ downloadUrl: !data?.installed && !data?.canAutoInstall ? data?.downloadUrl : null,+ onStart: data?.installed && !data?.available ? onStart : null,+ onStop: data?.available ? onStop : null,+ };+}++/**+ * Rows for the two daemons PortOS runs as PM2 processes.+ *+ * These DO distinguish ours from external: `managed === false` while something+ * answers on the port means a server the user started in a terminal, which+ * PortOS must not offer to stop.+ */+function pm2Row({ id, label, icon, status, platformReason, onStart, onStop, onInstall, startBlockedReason, detail }) {+ const external = status?.running && status?.managed === false;+ const state = platformReason ? 'unsupported'+ : status?.running ? (external ? 'external' : 'running')+ : status?.installed ? 'stopped' : 'missing';+ return {+ id,+ label,+ icon,+ state,+ endpoint: status?.endpoint || null,+ detail: platformReason || detail || null,+ pm2: true,+ runAtStartup: status?.runAtStartup ?? null,+ pid: status?.managed && status?.pid ? status.pid : null,+ // `status` is null until the first poll lands. Offering Install then would+ // put a button on a host that turns out not to support the runtime at all.+ onInstall: status && !platformReason && !status.installed ? onInstall : null,+ onStart: !platformReason && status?.installed && !status?.running && !startBlockedReason ? onStart : null,+ startBlockedReason: status?.installed && !status?.running ? startBlockedReason : null,+ onStop: !external && status?.running ? onStop : null,+ };+}++function ServerRow({ row, busy, actionInProgress, children }) {+ const Icon = row.icon;+ const meta = STATE_META[row.state] || STATE_META.missing;+ return (+ <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 bg-port-bg border border-port-border rounded-lg px-3 py-2">+ <div className="flex items-center gap-2 min-w-0 sm:w-44 shrink-0">+ <Icon size={14} className="text-port-accent shrink-0" />+ <span className="text-sm text-white truncate">{row.label}</span>+ </div>+ <div className="flex items-center gap-2 flex-wrap min-w-0 flex-1">+ <span className={`px-2 py-0.5 text-xs rounded flex items-center gap-1.5 ${meta.cls}`}>+ <span className={`w-2 h-2 rounded-full ${meta.dot}`} />+ {meta.label}{row.pid ? ` (PID ${row.pid})` : ''}+ </span>+ {row.endpoint && (+ <code className="text-xs text-gray-500 truncate max-w-full">{row.endpoint}</code>+ )}+ {row.pm2 && row.runAtStartup && (+ <span className="px-1.5 py-0.5 text-xs rounded border border-port-success/40 text-port-success" title="This PM2 process is in the saved list `pm2 resurrect` replays at boot">+ starts at boot+ </span>+ )}+ {row.detail && <span className="text-xs text-gray-500">{row.detail}</span>}+ </div>+ <div className="flex items-center gap-2 flex-wrap shrink-0">+ {children}+ {row.onInstall && (+ <button+ onClick={row.onInstall}+ disabled={busy}+ className={accentBtn}+ title={`Install ${row.label} on this machine`}+ >+ {actionInProgress === `runtime-install-${row.id}` ? <BrailleSpinner /> : <Download size={12} />}+ Install+ </button>+ )}+ {row.downloadUrl && (+ <a+ href={row.downloadUrl}+ target="_blank"+ rel="noopener noreferrer"+ className={`${neutralBtn} no-underline`}+ title={`PortOS can't install ${row.label} on this platform — download it from the vendor`}+ >+ <ExternalLink size={12} />+ Download+ </a>+ )}+ {row.onStart && (+ <button+ onClick={row.onStart}+ disabled={busy}+ className={neutralBtn}+ title={`Start the local ${row.label} server`}+ >+ {actionInProgress === `runtime-start-${row.id}` ? <BrailleSpinner /> : <Play size={12} />}+ Start+ </button>+ )}+ {row.startBlockedReason && (+ <span className="text-xs text-gray-500 max-w-xs">{row.startBlockedReason}</span>+ )}+ {row.onStop && (+ <button+ onClick={row.onStop}+ disabled={busy}+ className={neutralBtn}+ title={`Stop the local ${row.label} server`}+ >+ {actionInProgress === `runtime-stop-${row.id}` ? <BrailleSpinner /> : <Square size={12} />}+ Stop+ </button>+ )}+ </div>+ </div>+ );+}++export default function RuntimeServersCard({+ status,+ llamaStatus,+ mtplxStatus,+ loading,+ busy,+ actionInProgress,+ onRefresh,+ onControlOllama,+ onControlLmStudio,+ onInstallBackend,+ onInstallLlama,+ onStopLlama,+ onConfigureLlama,+ onConfigureMtplx,+ onInstallMtplx,+ onStartMtplx,+ onStopMtplx,+ onSaveStartup,+}) {+ const ollamaService = status?.ollama?.service;+ const ollamaRunsAtStartup = Boolean(ollamaService?.runAtStartup);++ const rows = [+ backendRow({+ id: 'ollama',+ label: 'Ollama',+ icon: Cpu,+ data: status?.ollama,+ onInstall: () => onInstallBackend('ollama'),+ onStart: () => onControlOllama('start'),+ onStop: () => onControlOllama('stop'),+ }),+ backendRow({+ id: 'lmstudio',+ label: 'LM Studio',+ icon: Box,+ data: status?.lmstudio,+ onInstall: () => onInstallBackend('lmstudio'),+ onStart: () => onControlLmStudio('start'),+ onStop: () => onControlLmStudio('stop'),+ }),+ pm2Row({+ id: 'llama',+ label: 'llama.cpp',+ icon: Zap,+ status: llamaStatus,+ onInstall: onInstallLlama,+ onStop: onStopLlama,+ // llama-server takes a REQUIRED model path, and which GGUF (plus which+ // drafter and spec type) is a real choice — so there is no honest one-click+ // Start here. The launcher below owns it.+ startBlockedReason: 'Pick a model in Speculative Decoding below to start it',+ }),+ pm2Row({+ id: 'mtplx',+ label: 'MTPLX',+ icon: Gauge,+ status: mtplxStatus,+ platformReason: mtplxStatus?.supported === false ? 'macOS with Apple Silicon only' : null,+ 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.+ startBlockedReason: mtplxStatus?.installed && mtplxStatus?.cachedModels?.length === 0 && !mtplxStatus?.cacheError+ ? 'Run `mtplx pull` in a terminal first — PortOS never downloads MTPLX weights'+ : null,+ detail: mtplxStatus?.cachedModels?.length+ ? `${mtplxStatus.cachedModels.length} checkpoint${mtplxStatus.cachedModels.length === 1 ? '' : 's'} cached`+ : null,+ }),+ ];++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6 space-y-3">+ <div className="flex items-center justify-between gap-2">+ <h2 className="text-sm font-medium text-gray-300">Local Runtime Servers</h2>+ <button+ onClick={onRefresh}+ disabled={loading}+ className="p-1.5 text-gray-400 hover:text-white transition-colors"+ title="Refresh runtime server status"+ aria-label="Refresh runtime server status"+ >+ <RefreshCw size={14} className={loading ? 'animate-spin' : ''} />+ </button>+ </div>+ <p className="text-xs text-gray-500">+ Every local server PortOS can run, in one place. They are not mutually exclusive — install and run as many as you like. Which one a run goes to is a separate choice: the <span className="text-gray-400">Default</span> backend below, or the provider a task names in <Link to="/ai" className="text-port-accent hover:underline">AI Providers</Link>.+ </p>++ <div className="space-y-2">+ {rows.map((row) => (+ <ServerRow key={row.id} row={row} busy={busy} actionInProgress={actionInProgress}>+ {row.id === 'ollama' && ollamaService?.supported && (+ <button+ onClick={() => onControlOllama(ollamaRunsAtStartup ? 'disable' : 'enable')}+ disabled={busy}+ className={neutralBtn}+ title={ollamaRunsAtStartup+ ? 'Stop the background service and remove the launch-at-login registration'+ : 'Run Ollama in the background at login via its own service manager'}+ >+ {actionInProgress === `runtime-startup-ollama` ? <BrailleSpinner /> : ollamaRunsAtStartup ? <PowerOff size={12} /> : <Power size={12} />}+ {ollamaRunsAtStartup ? 'Disable at login' : 'Run at login'}+ </button>+ )}+ {(row.id === 'llama' || row.id === 'mtplx') && row.state !== 'unsupported' && (+ <button+ onClick={row.id === 'llama' ? onConfigureLlama : onConfigureMtplx}+ className={neutralBtn}+ title={`Jump to the ${row.label} launcher below`}+ >+ <Settings2 size={12} />+ Configure+ </button>+ )}+ </ServerRow>+ ))}+ </div>++ <div className="flex flex-col sm:flex-row sm:items-center gap-2 pt-1">+ <button onClick={onSaveStartup} disabled={busy} className={accentBtn} title="Run `pm2 save` so the running PM2 processes are in the list a reboot resurrects">+ {actionInProgress === 'runtime-save-startup' ? <BrailleSpinner /> : <Save size={12} />}+ Save PM2 list for reboot+ </button>+ <p className="text-xs text-gray-500">+ llama.cpp and MTPLX run as PM2 processes (<code className="text-gray-400">portos-llama-server</code>, <code className="text-gray-400">portos-mtplx</code>). Saving snapshots what is running now so it comes back after a reboot — this needs <code className="text-gray-400">pm2 startup</code> to have been run once in a terminal, which is a privileged one-time step PortOS deliberately leaves to you. Ollama and LM Studio manage their own launch-at-login.+ </p>+ </div>+ </div>+ );+}diff --git a/client/src/components/settings/RuntimeServersCard.test.jsx b/client/src/components/settings/RuntimeServersCard.test.jsxnew file mode 100644index 0000000000..1da623a788--- /dev/null+++ b/client/src/components/settings/RuntimeServersCard.test.jsx@@ -0,0 +1,138 @@+import { describe, it, expect, vi } from 'vitest';+import { fireEvent, render, screen, within } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import RuntimeServersCard from './RuntimeServersCard.jsx';++// Every row renders the same status/action vocabulary, so a text query alone+// would match the wrong runtime. Scope to the row that names it.+const row = (label) => screen.getByText(label).closest('div.flex.flex-col');++const renderCard = (props = {}) => {+ const handlers = {+ onRefresh: vi.fn(),+ onControlOllama: vi.fn(),+ onControlLmStudio: vi.fn(),+ onInstallBackend: vi.fn(),+ onInstallLlama: vi.fn(),+ onStopLlama: vi.fn(),+ onConfigureLlama: vi.fn(),+ onConfigureMtplx: vi.fn(),+ onInstallMtplx: vi.fn(),+ onStartMtplx: vi.fn(),+ onStopMtplx: vi.fn(),+ onSaveStartup: vi.fn(),+ };+ render(+ <MemoryRouter>+ <RuntimeServersCard+ status={{ ollama: {}, lmstudio: {} }}+ llamaStatus={null}+ mtplxStatus={null}+ loading={false}+ busy={false}+ actionInProgress={null}+ {...handlers}+ {...props}+ />+ </MemoryRouter>,+ );+ return handlers;+};++describe('RuntimeServersCard', () => {+ it('lists every local runtime PortOS can run, not just the two catalog backends', () => {+ renderCard();+ for (const label of ['Ollama', 'LM Studio', 'llama.cpp', 'MTPLX']) {+ expect(screen.getByText(label)).toBeInTheDocument();+ }+ });++ it('offers Start for an installed-but-stopped backend and Stop for a running one', () => {+ const handlers = renderCard({+ status: {+ ollama: { installed: true, available: false, modelCount: 2, baseUrl: 'http://localhost:11434' },+ lmstudio: { installed: true, available: true, modelCount: 1, baseUrl: 'http://localhost:1234' },+ },+ });++ fireEvent.click(within(row('Ollama')).getByRole('button', { name: /Start/ }));+ expect(handlers.onControlOllama).toHaveBeenCalledWith('start');++ fireEvent.click(within(row('LM Studio')).getByRole('button', { name: /Stop/ }));+ expect(handlers.onControlLmStudio).toHaveBeenCalledWith('stop');+ });++ it('will not offer to stop a PM2 runtime PortOS did not start', () => {+ renderCard({+ llamaStatus: { installed: true, running: true, managed: false, endpoint: 'http://127.0.0.1:5568/v1' },+ });+ const llama = row('llama.cpp');+ expect(within(llama).getByText('Running (external)')).toBeInTheDocument();+ expect(within(llama).queryByRole('button', { name: /Stop/ })).toBeNull();+ });++ it('sends llama.cpp to its launcher instead of offering a Start it cannot honour', () => {+ // llama-server takes a REQUIRED model path — a one-click Start here would+ // have to guess which multi-gigabyte GGUF the user meant.+ const handlers = renderCard({ llamaStatus: { installed: true, running: false } });+ const llama = row('llama.cpp');+ expect(within(llama).queryByRole('button', { name: /^Start/ })).toBeNull();+ expect(within(llama).getByText(/Pick a model in Speculative Decoding/)).toBeInTheDocument();++ fireEvent.click(within(llama).getByRole('button', { name: /Configure/ }));+ expect(handlers.onConfigureLlama).toHaveBeenCalled();+ });++ it('starts MTPLX in place once a checkpoint is cached', () => {+ const handlers = renderCard({+ mtplxStatus: { installed: true, running: false, supported: true, cachedModels: ['Example/Qwen-MTP'], endpoint: 'http://127.0.0.1:8000/v1' },+ });+ fireEvent.click(within(row('MTPLX')).getByRole('button', { name: /^Start/ }));+ expect(handlers.onStartMtplx).toHaveBeenCalled();+ });++ 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.+ 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();+ });++ it('reports a runtime this host cannot run without offering to install it', () => {+ renderCard({ mtplxStatus: { installed: false, running: false, supported: false, unsupportedReason: 'MTPLX runs only on macOS with Apple Silicon.' } });+ const mtplx = row('MTPLX');+ expect(within(mtplx).getByText('Unavailable on this platform')).toBeInTheDocument();+ expect(within(mtplx).queryByRole('button', { name: /Install/ })).toBeNull();+ });++ it('flags a PM2 runtime that is in the saved boot list', () => {+ renderCard({+ llamaStatus: { installed: true, running: true, managed: true, pid: 321, runAtStartup: true, endpoint: 'http://127.0.0.1:5568/v1' },+ mtplxStatus: { installed: true, running: true, managed: true, pid: 654, runAtStartup: false, supported: true, endpoint: 'http://127.0.0.1:8000/v1' },+ });+ expect(within(row('llama.cpp')).getByText('starts at boot')).toBeInTheDocument();+ expect(within(row('MTPLX')).queryByText('starts at boot')).toBeNull();+ });++ it('saves the PM2 process list so the running daemons survive a reboot', () => {+ const handlers = renderCard();+ fireEvent.click(screen.getByRole('button', { name: /Save PM2 list for reboot/ }));+ expect(handlers.onSaveStartup).toHaveBeenCalled();+ });++ it('links out to the vendor when PortOS cannot install a backend on this platform', () => {+ renderCard({+ status: {+ ollama: { installed: false, canAutoInstall: false, downloadUrl: 'https://ollama.com/download' },+ lmstudio: {},+ },+ });+ const ollama = row('Ollama');+ expect(within(ollama).queryByRole('button', { name: /Install/ })).toBeNull();+ expect(within(ollama).getByRole('link', { name: /Download/ })).toHaveAttribute('href', 'https://ollama.com/download');+ });+});diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex 5d0fa64204..de4597f249 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -51,6 +51,33 @@ export const upgradeLocalLlmBackend = (backend) =>export const controlOllamaService = (action) =>request('/local-llm/ollama-service', { method: 'POST', body: JSON.stringify({ action }) });+// Start/stop LM Studio's local server through its own `lms` CLI. No+// enable/disable counterpart — launch-at-login belongs to the LM Studio app.+export const controlLmStudioService = (action) =>+ request('/local-llm/lmstudio-service', { method: 'POST', body: JSON.stringify({ action }) });++// MTPLX (native-MTP Qwen on Apple Silicon) — a PM2-managed process, same+// lifecycle shape as llama-server below.+export const getMtplxServerStatus = (options) =>+ request('/local-llm/mtplx/status', options);++// `config` is optional: with none of it PortOS serves the checkpoint already in+// MTPLX's cache on the port the shipped provider presets point at.+export const startMtplxServer = (config = {}) =>+ request('/local-llm/mtplx/start', { method: 'POST', body: JSON.stringify(config) });++export const stopMtplxServer = () =>+ request('/local-llm/mtplx/stop', { method: 'POST' });++export const installMtplx = () =>+ request('/local-llm/mtplx/install', { method: 'POST' });++// `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.+export const saveRuntimeStartupList = () =>+ request('/local-llm/save-startup', { method: 'POST' });+// llama-server (DFlash 2 / Speculative Decoding) process controlsexport const getLlamaServerStatus = (options) =>request('/local-llm/llama-server/status', options);diff --git a/docs/API.md b/docs/API.mdindex 7d83de34cf..dcd45608a6 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 |+| `/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/code-review` | Code review runs || `/api/voice`, `/api/voice/public` | Voice assistant || `/api/api-docs` | OpenAPI 3.1 spec |diff --git a/docs/PORTS.md b/docs/PORTS.mdindex 063531abaa..42f5aea231 100644--- a/docs/PORTS.md+++ b/docs/PORTS.md@@ -34,7 +34,8 @@ Common port labels:| 5559 | portos-autofixer | api | Autofixer daemon API || 5560 | portos-autofixer-ui | ui | Autofixer web UI || 5561 | portos-db (Docker container) | - | Infrastructure dependency: PostgreSQL Docker container provisioned by `scripts/setup-db.js` / Docker Compose (not a PM2 process in `server/services/apps.js`; native mode uses system pg on 5432). |-| 5568 | llama-server | - | Loopback speculative-decoding server managed from Models → LLMs |+| 5568 | portos-llama-server | - | Loopback llama.cpp speculative-decoding server. Optional PM2 process, started/stopped from Models → LLMs. |+| 8000 | portos-mtplx | - | Loopback MTPLX OpenAI-compatible API (upstream's own default, kept so the shipped provider presets match). Optional PM2 process, started/stopped from Models → LLMs. See [features/mtplx.md](./features/mtplx.md). || 18020 | vLLM (Docker) | - | Loopback vLLM Qwen3.8-27B / DFlash 2 container on an RTX 3090 host. Operator-started (`docker compose --profile single up -d`) — PortOS never brings it up on boot. See [features/qwen38-rtx3090.md](./features/qwen38-rtx3090.md). |## How `:5555`, `:5553`, and `:5554` Relate@@ -127,9 +128,10 @@ PortOS automatically detects ports from env vars:| 5562-5569 | Reserved for PortOS extensions (5568 is the managed llama-server default) || 5570-5599 | User applications |-PostgreSQL in native mode listens on the system default `:5432`, outside these ranges. The vLLM-Qwen3.8-27B container listens on `:18020` — upstream's own default, kept as-is so an operator's-unmodified `syv-ai/qwen38-27b-rtx3090` checkout works against PortOS without editing its compose file.+PostgreSQL in native mode listens on the system default `:5432`, outside these ranges. Two third-party+local runtimes also sit outside them, each on its own upstream default so an unmodified install works+against PortOS without editing anything: MTPLX on `:8000` and the vLLM Qwen3.8-27B container on+`:18020` (`syv-ai/qwen38-27b-rtx3090`'s own compose file).## Viewing Port Usagediff --git a/docs/features/mtplx.md b/docs/features/mtplx.mdindex 3b8b29cee4..6afb520874 100644--- a/docs/features/mtplx.md+++ b/docs/features/mtplx.md@@ -25,16 +25,55 @@ The two OpenCode variants give CoS agents a file-writing tool harness. The APIvariant returns text only, like the existing Ollama API provider, so it is not avalid CoS coding-agent runner.+## Where it is managed++**Models → LLMs** is the home for MTPLX's lifecycle, alongside every other local+server PortOS can run:++- **Local Runtime Servers** — one table covering Ollama, LM Studio, llama.cpp+ and MTPLX, with the same Install / Start / Stop controls for each and a+ **Save PM2 list for reboot** action (see [Startup at boot](#startup-at-boot)).+- The **MTPLX** card below it picks *which* cached checkpoint and *which* port to+ serve on, and shows the server's recent log lines.++PortOS runs MTPLX as a **PM2 process named `portos-mtplx`**, exactly like+`portos-llama-server`. So `pm2 list` shows it next to the rest of the install,+`pm2 logs portos-mtplx` has its output, a PortOS restart re-adopts a server it+started earlier rather than losing track of it, and a reboot can bring it back.++The **AI Providers** readiness checklist keeps its one-click **Install & start+MTPLX** button. That button now drives the same manager, so a server started+from the checklist is the same managed process the LLMs page can stop and log.+## Setup-1. On **AI Providers**, enable the matching preset. Its card shows an MTPLX- requirements checklist (installed / server responding / model available).-2. Click **Install & start MTPLX** on that checklist. PortOS installs the- package from upstream's Homebrew tap (`brew install youssofal/mtplx/mtplx`),- falling back to `python3 -m pip install mtplx` on a host without Homebrew,- then runs `mtplx serve --port <the port your provider points at> --model <a- model already in your MTPLX cache>` and waits for `/v1/models` to answer.- Progress streams into the install modal.+Two surfaces set MTPLX up, and they drive the same PM2 process — use whichever+you are already on.++**From Models → LLMs** (full control over the checkpoint and the port):++1. Install MTPLX from **Local Runtime Servers**. PortOS installs the package+ from upstream's Homebrew tap (`brew install youssofal/mtplx/mtplx`), falling+ back 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.)+3. **Start MTPLX** from the MTPLX card, choosing a cached checkpoint and the port+ your provider points at. PortOS runs `mtplx serve` under PM2. A cold MLX+ checkpoint takes a while to load: the request comes back as soon as the+ server survives its first seconds, and the card's status finishes the story+ once the endpoint answers.++**From AI Providers** (one click, MTPLX's own default checkpoint):++1. Enable the matching preset. Its card shows an MTPLX requirements checklist+ (installed / server responding / model available).+2. Click **Install & start MTPLX** on that checklist. PortOS runs the same+ install as above, then `mtplx serve --port <the port your provider points at>+ --model <a model already in your MTPLX cache>`, and waits for `/v1/models` to+ answer. Progress streams into the install modal.3. **If no weights are cached**, the checklist says so on the "serverresponding" and "model available" rows — MTPLX's server exits before itbinds a port with an empty cache — and the button becomes **Download the@@ -43,17 +82,21 @@ valid CoS coding-agent runner.with the download's progress streaming into the same modal. To use adifferent MTP checkpoint instead, run `mtplx pull <hf-repo-id>` in aterminal and click **Start MTPLX**.-4. Use **Refresh Models** once the server is up; PortOS then reads `/v1/models`- on demand. The seed model alias is `mtplx` — refresh it if your running- server publishes a different one.++Then, either way:++4. Use **Refresh Models** on the provider once the server is up; PortOS reads+ `/v1/models` on demand. The seed model alias is `mtplx` — refresh it if your+ running server publishes a different one.5. Choose **MTPLX (local MTP)** for supported non-coding tasks, or choose an**OpenCode MTPLX** CLI/TUI preset for a CoS coding task.Prefer to run it yourself? Install MTPLX per its upstream documentation andstart a server on the loopback OpenAI-compatible endpoint the preset points at,-`http://127.0.0.1:8000/v1`. The checklist notices and collapses to a ready pill.+`http://127.0.0.1:8000/v1`. PortOS reports it as **Running (external)** and does+not offer to stop a process it did not start.-### What the button does and does not do+## What PortOS does and does not do- It installs the MTPLX package and starts its **API server only**. Upstream'soptional `mtplx max --install` fan-control helper — the one privileged path@@ -66,8 +109,9 @@ start a server on the loopback OpenAI-compatible endpoint the preset points at,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 is the one action- here that fetches weights, and it appears only when that same cache listing+- 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 listingproves there is nothing servable — an empty cache, or one holding only ahalf-finished `mtplx pull`. It runs `mtplx pull` with no repo id, so it canonly ever fetch MTPLX's own default verified checkpoint; nothing from the@@ -89,6 +133,22 @@ network request, invoke a model, tune speculative decoding, alter the activeprovider, or install anything — the setup above runs only from that explicitclick. MTPLX tuning remains an explicit operator action outside PortOS.+## Startup at boot++`portos-mtplx` and `portos-llama-server` come back after a reboot the same way+every other PortOS process does — through PM2's saved dump:++1. Run `pm2 startup` **once** in a terminal and follow the privileged command it+ prints. PortOS deliberately never runs this: it writes a launchd/systemd unit+ and is blocked in PortOS's PM2 command guard.+2. With the servers you want running, click **Save PM2 list for reboot** on+ Models → LLMs (a plain `pm2 save`). Each PM2-managed runtime then shows a+ **starts at boot** pill.++Ollama and LM Studio are not PM2 processes — they manage their own+launch-at-login (Ollama through its service manager, via the **Run at login**+control on the same card; LM Studio through its app).+## Operational notes- MTPLX can offer a faster path for an MTP-capable Qwen checkpoint; benchmark itdiff --git a/server/lib/README.md b/server/lib/README.mdindex c6918d62c4..44aac2404a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -74,7 +74,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `storyArc.js` | Canonical Arc + Season + Reader-Map shapes for pipeline arc planning. || `styleGuide.js` | Per-series house style (tense/POV/audience/rating/reading-level/tone/conventions): `sanitizeStyleGuide` + `renderStyleGuide` generation block + enums. || `storyBuilderSteps.js` | Unified Story Builder ordered step definitions + helpers (`STEPS`, `STEP_IDS`, `STEP_STATUSES`, `isValidStepId`, `stepIndex`). |-| `streamLines.js` | `createLineReader(onLine, {splitRe?, maxCarry?})` + `createOutputTail({budget?})` — buffered chunk→line splitter for child-process stdout/stderr. Carries the partial trailing line across `data` chunks and `flush()`es the final unterminated line on `close`; carry clamp guards a newline-less runaway stream. One reader per stream (a shared buffer corrupts marker lines). `splitRe: /[\r\n]+/` handles torch/tqdm bare-`\r` progress redraws. `createOutputTail` is the sibling rolling buffer of recent lines (char-budgeted, decoration-only lines skipped so an ASCII-art banner cannot push the real error out) that turns "exited with code 1" into what the tool actually printed — shared by `streamingSpawn.js` and the daemon starter in `services/localRuntimeSetup.js`. |+| `streamLines.js` | `createLineReader(onLine, {splitRe?, maxCarry?})` + `createOutputTail({budget?})` — buffered chunk→line splitter for child-process stdout/stderr. Carries the partial trailing line across `data` chunks and `flush()`es the final unterminated line on `close`; carry clamp guards a newline-less runaway stream. One reader per stream (a shared buffer corrupts marker lines). `splitRe: /[\r\n]+/` handles torch/tqdm bare-`\r` progress redraws. `createOutputTail` is the sibling rolling buffer of recent lines (char-budgeted, decoration-only lines skipped so an ASCII-art banner cannot push the real error out) that turns "exited with code 1" into what the tool actually printed — used by `streamingSpawn.js`. || `storyBuilderIntegrity.js` | Pure staleness hashing for the Story Builder (`hashUpstream`, `computeStaleSteps`, `computeSyncDrift`). || `canonPrompt.js` | Per-kind field-precedence rules; SHORT/RICH/PREVIEW spec tables; `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` / `descriptorForCanonEntry`. || `scenePrompt.js` | Scene-prompt composer + bible matchers (chars/places/objects in text). |@@ -136,6 +136,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `providerTranscriptUsage.js` | Parsers for the real per-message token counts the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Both de-duplicate a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, and Codex's `total_token_usage` is cumulative and repeated. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. || `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring bare model ids under the selected local provider (`ollama` or `mtplx`) for marked OpenCode providers. Fixes --model rejection. || `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX / vLLM: label, binary, canonical base URL read from `opencodeConfig.js` rather than re-typed, manage/docs links, model-download hint), `localBackendForProvider` + `localEndpointPort` + `isLocalInstanceHost` (moved here from `services/localModelHealing.js`, which re-exports them, so the healing path and the readiness checklist classify a provider identically — loopback/bind-all only, so a LAN/Tailscale peer on port 11434 is NOT claimed as a local daemon), `localRuntimeKind(provider)` (the `*Backed` markers first, then that classifier; `orcarouter` excluded as a remote API), `localRuntimeForProvider(provider)` → the row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` override the backend managers read, then the canonical default — and `null` when that resolved endpoint fails `isLocalInstanceEndpoint` (an API provider on another machine has no local daemon to check, whatever its name says) — plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. |+| `managedDaemon.js` | Shared mechanism for the local daemons PortOS runs as optional PM2 processes (`services/llamaServerManager.js` → `portos-llama-server`, `services/mtplxServerManager.js` → `portos-mtplx`). `createDaemonLogBuffer({maxLines?})` is the bounded timestamped ring buffer of what PortOS logged around a launch, plus `withPm2Logs(output)` → that buffer followed by anything `pm2 logs` has which it doesn't already hold, deduped and re-capped (PM2's lines are a VIEW, never folded into the buffer — PM2 owns them and re-reads them every status call). `pm2ArgValue(args, flag)` reads one value back out of a PM2 process's recorded argv so a manager can recover a still-online daemon's launch config after a PortOS restart; `null` means the flag was absent, which a relaunch must leave off rather than defaulting. Deliberately mechanism only — what a launch line means and when a daemon may start is exactly what differs between the two. || `mtplxModels.js` | `listMtplxCachedModels({command?})` → `{models, error}` from `mtplx models --json` (a local directory listing — no network, no model load) and `pickMtplxCachedModel(models)` → the repo id to hand `mtplx serve --model`. `models: null` means the cache could not be READ (no binary, command failed, unparseable) and is deliberately distinct from `[]` (read, and empty), because `services/localRuntimeSetup.js` starts MTPLX on its own default in the first case and refuses with the `mtplx pull` command in the second. Exists because `mtplx serve` defaults `--model` to one hard-coded checkpoint and exits 1 before binding when that repo is not cached — even on a host holding a different MTP model that serves fine. Picks only entries MTPLX itself calls complete (`validation.ok !== false`, so a half-finished pull is not served), preferring one with a recorded `mtplx_runtime.json` exactness contract. `describeMtplxCache(cache)` → `{state: 'unknown'\|'empty'\|'partial'\|'ready', model, count, error}` folds both into the one value `services/providerReadiness.js` puts on the checklist and `describeRuntimeSetup` picks a button from — so an empty cache is named up front instead of only inside the failure of a Start that could never work. || `vllmQwenProject.js` | `resolveVllmProjectDir()` / `inspectVllmQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the operator-cloned syv-ai/qwen38-27b-rtx3090 compose project, plus `vllmStartBlockedReason(project)` → the prose refusal (or `null`). Directory reads only — never runs docker or touches a registry. `hasWeights` is tri-state: `true` found / `false` caches read and empty / `null` no cache readable (a docker-volume cache is invisible from a native-Win32 PortOS), and `services/localRuntimeSetup.js` refuses to `docker compose up` on anything but `true` so the start button can never kick off the ~20 GB prepare. Overrides: `VLLM_QWEN_PROJECT_DIR`, `VLLM_QWEN_WEIGHTS_DIR`. || `openAiModelsProbe.js` | `probeOpenAiModels(baseUrl, { timeoutMs, apiKey })` → `{ reachable, models, error }` — the one `GET {base}/models` probe for the local OpenAI-compatible daemons, shared by `services/providerReadiness.js` and `services/llamaServerManager.js`. Distinguishes unreachable from reachable-but-unlistable (`models: null`) from up-with-nothing-loaded (`[]`), names the real transport failure via `describeFetchError` (undici reports every one as a bare `fetch failed`), and cancels an unread body on a non-OK response. `apiKey` attaches a Bearer header for a key-gated daemon (vLLM's compose stack), and a 401/403 answers `reachable: true` with `error: 'authentication required'` — a server that refused the request is definitively running, and calling it unreachable would send the user to start it again. Consolidated after the two copies drifted — one passed its timeout as a `timeout` key inside the fetch init object, where it is not an option, silently running a 500ms poll loop on the 15s default. |diff --git a/server/lib/index.js b/server/lib/index.jsindex c28d34db7b..e030cb85cc 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -153,6 +153,7 @@ export * from './quotaWindows.js';export * from './opencodeConfig.js';export * from './localProviderRuntime.js';export * from './mtplxModels.js';+export * from './managedDaemon.js';export * from './vllmQwenProject.js';export * from './openAiModelsProbe.js';export * from './openAiChatStream.js';diff --git a/server/lib/managedDaemon.js b/server/lib/managedDaemon.jsnew file mode 100644index 0000000000..ab55c1dd71--- /dev/null+++ b/server/lib/managedDaemon.js@@ -0,0 +1,87 @@+/**+ * Shared plumbing for a local daemon PortOS runs as an optional PM2 process+ * (`llamaServerManager.js` → `portos-llama-server`, `mtplxServerManager.js` →+ * `portos-mtplx`).+ *+ * Both managers answer the same two questions the same way, and the answers are+ * fiddly enough that two copies drift:+ *+ * - **What did it print?** A launcher card is useless without the daemon's+ * recent output, and the output lives in two places — the lines PortOS+ * itself logged around the launch, and what `pm2 logs` has. They have to be+ * merged without duplicating the overlap and without growing unbounded.+ * - **What was it launched with?** After a PortOS restart the only record of a+ * still-online daemon's configuration is its PM2 argv, so both managers+ * recover the launch flags by reading values back out of that array.+ *+ * Deliberately NOT a "daemon manager" abstraction: what each daemon's launch+ * line means, when it may be started, and what a refusal should say are exactly+ * the parts that differ, and folding them together would produce a base class+ * with two special cases. This is the shared *mechanism* only.+ */++/** Same cap both managers used, and what the launcher cards render. */+const DEFAULT_MAX_LINES = 100;++/**+ * A bounded, timestamped ring buffer of a daemon's recent output.+ *+ * `withPm2Logs` does NOT fold the PM2 output into the buffer: PM2 owns those+ * lines and re-reads them on every status call, so remembering them here would+ * grow a second copy that outlives the process they came from. It returns the+ * merged VIEW a status response renders.+ *+ * @param {{maxLines?: number}} [options]+ */+export function createDaemonLogBuffer({ maxLines = DEFAULT_MAX_LINES } = {}) {+ let lines = [];++ const append = (line) => {+ if (!line) return;+ const text = String(line).trimEnd();+ if (!text) return;+ lines.push(`[${new Date().toISOString()}] ${text}`);+ if (lines.length > maxLines) lines = lines.slice(-maxLines);+ };++ return {+ append,+ maxLines,+ reset: () => { lines = []; },+ snapshot: () => [...lines],+ /**+ * This buffer's lines followed by anything in `pm2Output` it does not+ * already hold, capped to the same budget.+ * @param {string} pm2Output combined stdout + stderr from `pm2 logs`+ * @returns {string[]}+ */+ withPm2Logs(pm2Output) {+ const merged = [...lines];+ const seen = new Set(merged);+ for (const line of String(pm2Output || '').split('\n').map((l) => l.trimEnd()).filter(Boolean)) {+ if (seen.has(line)) continue;+ merged.push(line);+ seen.add(line);+ }+ return merged.length > maxLines ? merged.slice(-maxLines) : merged;+ },+ };+}++/**+ * The value following `flag` in a PM2 process's recorded argv, or `null`.+ *+ * `null` means the flag was NOT on the launch line, which is distinct from a+ * flag whose value happens to be falsy — a caller reconstructing a config must+ * leave an absent flag off a relaunch rather than substituting a default the+ * daemon never saw.+ *+ * @param {string[]|string} args PM2's `args` (an array, or the space-joined string it sometimes reports)+ * @param {string} flag+ * @returns {string|null}+ */+export function pm2ArgValue(args, flag) {+ const list = Array.isArray(args) ? args : String(args || '').split(' ');+ const idx = list.indexOf(flag);+ return idx !== -1 && idx + 1 < list.length ? list[idx + 1] : null;+}diff --git a/server/lib/mediaValidation.js b/server/lib/mediaValidation.jsindex 358939bb1c..1b9d38af60 100644--- a/server/lib/mediaValidation.js+++ b/server/lib/mediaValidation.js@@ -164,6 +164,21 @@ export const localLlmMigrateSchema = z.object({});export const localLlmInstallBackendSchema = z.object({ backend: localLlmBackendSchema });export const localLlmOllamaServiceSchema = z.object({ action: z.enum(['start', 'stop', 'enable', 'disable']) });+// LM Studio's own server has no enable/disable equivalent (the app owns its+// launch-at-login), so this is start/stop only — deliberately NOT reusing the+// Ollama schema, which would accept two actions `lms` cannot perform.+export const localLlmLmStudioServiceSchema = z.object({ action: z.enum(['start', 'stop']) });+// MTPLX launch. Every field is optional: with none of them PortOS serves the+// checkpoint already in MTPLX's cache on the port the shipped provider presets+// point at. `model` is a Hugging Face repo id, which lands in the launch argv.+export const localLlmMtplxStartSchema = z.object({+ port: z.coerce.number().int().min(1).max(65535).optional(),+ host: z.string().trim().max(100).optional(),+ model: z.string().trim().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',+ ).optional().nullable(),+});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/routes/localLlm.js b/server/routes/localLlm.jsindex d4a25456fe..3e496a1906 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -28,9 +28,13 @@ import {localLlmAssessmentDeleteSchema,localLlmAssessmentSweepSchema,localLlmLlamaServerStartSchema,+ localLlmLmStudioServiceSchema,+ localLlmMtplxStartSchema,localLlmSpecModelDownloadSchema} from '../lib/validation.js'import { getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer } from '../services/llamaServerManager.js'+import { getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx } from '../services/mtplxServerManager.js'+import { saveProcessList } from '../services/pm2.js'import { getSpecDecodePresetStatus, downloadSpecDecodeModel } from '../services/specDecodeModels.js'import { SPEC_TYPE_SUGGESTIONS } from '../lib/specDecodePresets.js'import { resetProviderReadinessCache } from '../services/providerReadiness.js'@@ -56,6 +60,7 @@ import {unloadModel as unloadOllamaModel,} from '../services/ollamaManager.js'import {+ controlLmStudioServer,getLastLoadedModelsError as getLmStudioResidencyError,getLoadedModels as getLoadedLmStudioModels,} from '../services/lmStudioManager.js'@@ -214,6 +219,26 @@ router.post('/ollama-service', asyncHandler(async (req, res) => {res.json(result)}))+// POST /api/local-llm/lmstudio-service — start/stop LM Studio's local server+// via its own `lms` CLI. No enable/disable counterpart: launch-at-login belongs+// to the LM Studio app, not to `lms`.+router.post('/lmstudio-service', asyncHandler(async (req, res) => {+ const { action } = validateRequest(localLlmLmStudioServiceSchema, req.body)+ const emit = emitter(req)+ emit('start', action === 'start' ? 'Starting the LM Studio server…' : 'Stopping the LM Studio server…')+ const result = await controlLmStudioServer(action).catch((err) => {+ emit('error', `LM Studio ${action} failed: ${err.message}`)+ throw err+ })+ if (!result.success) {+ emit('error', result.error || `LM Studio ${action} failed`)+ throw new ServerError(result.error || `LM Studio ${action} failed`, { status: 502 })+ }+ resetProviderReadinessCache()+ emit('complete', action === 'start' ? 'LM Studio server is running' : 'LM Studio server stopped')+ res.json(result)+}))+// POST /api/local-llm/install — pull/download a model (streams progress)router.post('/install', asyncHandler(async (req, res) => {const { backend, modelId, force } = validateRequest(localLlmInstallSchema, req.body)@@ -556,4 +581,61 @@ router.post('/llama-server/install', asyncHandler(async (req, res) => {res.json(result)}))+// === MTPLX (native-MTP Qwen on Apple Silicon) ================================+// Managed exactly like llama-server: a PM2 process (`portos-mtplx`) PortOS can+// start, stop, log, and — via /save-startup below — persist across a reboot.+// PortOS never downloads MTPLX weights; `serve` runs on a checkpoint already in+// MTPLX's own cache. See docs/features/mtplx.md.++// GET /api/local-llm/mtplx/status — binary availability, process state, the+// endpoint it serves on, its cached checkpoints, and recent logs. Disk + a+// loopback probe only.+router.get('/mtplx/status', asyncHandler(async (_req, res) => {+ res.json(await getMtplxServerStatus())+}))++// POST /api/local-llm/mtplx/start — launch `mtplx serve` under PM2+router.post('/mtplx/start', asyncHandler(async (req, res) => {+ const options = validateRequest(localLlmMtplxStartSchema, req.body)+ const emit = emitter(req)+ emit('start', 'Starting MTPLX…')+ const result = await startMtplxServer({ ...options, onProgress: (line) => emit('start', line) })+ .catch((err) => {+ emit('error', err.message)+ throw err+ })+ resetProviderReadinessCache()+ emit('complete', `MTPLX is running at ${result.endpoint}`)+ res.json(result)+}))++// POST /api/local-llm/mtplx/stop — stop the managed MTPLX process+router.post('/mtplx/stop', asyncHandler(async (_req, res) => {+ const result = await stopMtplxServer()+ resetProviderReadinessCache()+ res.json(result)+}))++// POST /api/local-llm/mtplx/install — install MTPLX (Homebrew tap, pip fallback)+router.post('/mtplx/install', asyncHandler(async (req, res) => {+ const emit = emitter(req)+ const result = await installMtplx({ onProgress: ({ event, message }) => emit(event, message) })+ .catch((err) => {+ emit('error', `Install failed: ${err.message}`)+ throw err+ })+ resetProviderReadinessCache()+ emit('complete', 'MTPLX installed')+ 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 — `pm2+// startup`, which writes the launchd/systemd unit — is deliberately blocked and+// stays a one-time operator command.+router.post('/save-startup', asyncHandler(async (_req, res) => {+ res.json(await saveProcessList())+}))+export default routerdiff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.jsindex 1d9ab7291e..67b38d4ff3 100644--- a/server/services/llamaServerManager.js+++ b/server/services/llamaServerManager.js@@ -11,17 +11,17 @@ import { spawn } from '../lib/childProcess.js';import { commandExists } from '../lib/commandExists.js';import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';import { expandHome, sleep } from '../lib/fileUtils.js';+import { createDaemonLogBuffer, pm2ArgValue } from '../lib/managedDaemon.js';import { resolveSpecModelPath } from './specDecodeModels.js';import { parseSpecTypes, isDraftSpecType } from '../lib/specDecodePresets.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';import { isPortInUse } from '../lib/platform.js';import { PORTS } from '../lib/ports.js';import { ServerError } from '../lib/errorHandler.js';-import { execPm2, getAppStatusStrict, clearJlistCache } from './pm2.js';+import { execPm2, getAppStatusStrict, clearJlistCache, getSavedProcessNames } from './pm2.js';export const LLAMA_APP = 'portos-llama-server';-const MAX_LOG_LINES = 100;const PROBE_TIMEOUT_MS = 1500;const STARTUP_WAIT_TIMEOUT_MS = 4000;// How long a relaunch waits for the kernel to release the old listener.@@ -34,18 +34,9 @@ const PORT_RELEASE_TIMEOUT_MS = 5000;let relaunchReadyTimeoutMs = 120000;let currentConfig = null;-let recentLogs = [];let lastExitError = null;--function appendLog(line) {- if (!line) return;- const text = String(line).trimEnd();- if (!text) return;- recentLogs.push(`[${new Date().toISOString()}] ${text}`);- if (recentLogs.length > MAX_LOG_LINES) {- recentLogs = recentLogs.slice(-MAX_LOG_LINES);- }-}+const logs = createDaemonLogBuffer();+const appendLog = logs.append;/*** Probes whether an OpenAI-compatible endpoint responds at the given host/port.@@ -86,10 +77,7 @@ async function assertModelFileExists(label, modelPath) {function parseConfigFromArgs(args) {if (!args) return null;const list = Array.isArray(args) ? args : String(args).split(' ');- const getArg = (flag) => {- const idx = list.indexOf(flag);- return idx !== -1 && idx + 1 < list.length ? list[idx + 1] : null;- };+ const getArg = (flag) => pm2ArgValue(list, flag);const model = getArg('-m') || getArg('--model');if (!model) return null;@@ -163,7 +151,7 @@ export async function getLlamaServerStatus() {const binaryPath = resolveLlamaServerBinary();const installed = Boolean(binaryPath);- const pm2Status = await getAppStatusStrict(LLAMA_APP);+ const [pm2Status, savedApps] = await Promise.all([getAppStatusStrict(LLAMA_APP), getSavedProcessNames()]);const isReadFailed = pm2Status === null;const isManagedActive = Boolean(pm2Status && pm2Status.status === 'online');@@ -177,28 +165,9 @@ export async function getLlamaServerStatus() {const reachable = await probeEndpoint(endpoint);- let logs = [...recentLogs];- if (isManagedActive || (pm2Status && pm2Status.status !== 'not_found')) {- try {- const pm2LogsResult = await execPm2(['logs', LLAMA_APP, '--nostream', '--lines', String(MAX_LOG_LINES)]);- const combined = (pm2LogsResult.stdout || '') + '\n' + (pm2LogsResult.stderr || '');- const parsedLines = combined.split('\n').map((l) => l.trimEnd()).filter(Boolean);- if (parsedLines.length > 0) {- const seen = new Set(logs);- for (const line of parsedLines) {- if (!seen.has(line)) {- logs.push(line);- seen.add(line);- }- }- if (logs.length > MAX_LOG_LINES) {- logs = logs.slice(-MAX_LOG_LINES);- }- }- } catch {- // Ignore PM2 log retrieval errors- }- }+ const pm2Logs = isManagedActive || (pm2Status && pm2Status.status !== 'not_found')+ ? await execPm2(['logs', LLAMA_APP, '--nostream', '--lines', String(logs.maxLines)]).catch(() => null)+ : null;return {installed,@@ -209,7 +178,10 @@ export async function getLlamaServerStatus() {port,endpoint,config: isManagedActive ? currentConfig : null,- recentLogs: logs,+ // Is this PM2 app in the saved dump `pm2 resurrect` replays at boot?+ // `null` = the dump could not be read, which is not the same as "no".+ runAtStartup: savedApps === null ? null : savedApps.includes(LLAMA_APP),+ recentLogs: logs.withPm2Logs(`${pm2Logs?.stdout || ''}\n${pm2Logs?.stderr || ''}`),lastExitError: isReadFailed ? 'Failed to read PM2 status' : lastExitError,};}@@ -322,7 +294,7 @@ export async function startLlamaServer(options = {}) {if (alias) args.push('--alias', alias);lastExitError = null;- recentLogs = [];+ logs.reset();if (droppedSpecTypes.length > 0) {appendLog(`Ignoring spec-type ${droppedSpecTypes.join(',')} — no drafter model is set`);console.log(`🦙 llama-server dropping drafter-based spec types ${droppedSpecTypes.join(',')} (no --model-draft configured)`);@@ -386,16 +358,10 @@ export async function startLlamaServer(options = {}) {}if (currentProc && (currentProc.status === 'errored' || currentProc.status === 'stopped' || currentProc.status === 'not_found')) {- let tail = '';- try {- const pm2Logs = await execPm2(['logs', LLAMA_APP, '--nostream', '--lines', '15']);- const combined = (pm2Logs.stderr || pm2Logs.stdout || '').trim();- const lines = combined.split('\n').map((l) => l.trimEnd()).filter(Boolean);- for (const line of lines) appendLog(line);- tail = lines.slice(-4).join(' | ');- } catch {- tail = recentLogs.slice(-4).join(' | ');- }+ const exitLogs = await execPm2(['logs', LLAMA_APP, '--nostream', '--lines', '15']).catch(() => null);+ const lines = (exitLogs?.stderr || exitLogs?.stdout || '').trim().split('\n').map((l) => l.trimEnd()).filter(Boolean);+ for (const line of lines) appendLog(line);+ const tail = (lines.length ? lines : logs.snapshot()).slice(-4).join(' | ');lastExitError = `PM2 status: ${currentProc.status}`;@@ -691,7 +657,7 @@ export async function installLlamaServer({ onProgress = () => {} } = {}) {*/export function _resetLlamaServerStateForTests({ relaunchReadyTimeout } = {}) {currentConfig = null;- recentLogs = [];+ logs.reset();lastExitError = null;// Restored to the production budget unless a suite asks for a shorter one.relaunchReadyTimeoutMs = Number.isFinite(relaunchReadyTimeout) ? relaunchReadyTimeout : 120000;diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.jsindex 3e217e1fe7..12add98fb1 100644--- a/server/services/lmStudioManager.js+++ b/server/services/lmStudioManager.js@@ -15,12 +15,17 @@ import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'import {dirIsMlx, selectPrimaryGguf, selectProjectorGguf, isShardedGguf, lmStudioPublisherRepo} from '../lib/localLlmDisk.js'+import { bufferedSpawn } from '../lib/bufferedSpawn.js'+import { findCommandOnPath } from '../lib/processEnv.js'const AVAILABILITY_CACHE_TTL_MS = 30_000const DEFAULT_REQUEST_TIMEOUT_MS = 30_000// Availability probe is short — if the local server is down we'd rather fail// fast and degrade to "no LM Studio" than block 30s on every cold check.const AVAILABILITY_PROBE_TIMEOUT_MS = 5_000+// `lms server start|stop` only asks the already-installed app to flip its+// listener — it never downloads anything, so a minute is generous.+const LMS_CONTROL_TIMEOUT_MS = 60_000// Default LM Studio configurationconst DEFAULT_CONFIG = {@@ -501,6 +506,41 @@ function isAppInstalled() {return process.platform === 'darwin' && existsSync('/Applications/LM Studio.app')}+/**+ * Start or stop LM Studio's local OpenAI-compatible server via its own `lms` CLI.+ *+ * `lms` is LM Studio's CLI shim, installed by `lms bootstrap` from the app.+ * Without it there is no headless way to drive the server, and pretending+ * otherwise would report a success the user cannot see — so that case is a+ * refusal naming the one command that fixes it.+ *+ * Resolves rather than throws (mirrors `controlOllamaServer`) so the route can+ * turn a refusal into a 502 with the reason intact.+ *+ * @param {'start'|'stop'} action+ */+async function controlServer(action) {+ if (action !== 'start' && action !== 'stop') {+ return { success: false, error: `Unknown LM Studio action: ${action}` }+ }+ const binary = findCommandOnPath('lms')+ if (!binary) {+ return {+ success: false,+ error: "LM Studio's `lms` CLI is not on PortOS's PATH. Open LM Studio once and run `lms bootstrap`, or use the app's Developer tab."+ }+ }+ const result = await bufferedSpawn(binary, ['server', action], { timeoutMs: LMS_CONTROL_TIMEOUT_MS, shell: false })+ resetCache()+ if (result.timedOut) return { success: false, error: `\`lms server ${action}\` timed out` }+ if (!result.success) {+ const detail = result.error?.message || String(result.stderr || result.stdout || '').trim().split(/\r?\n/).pop()+ return { success: false, error: detail || `\`lms server ${action}\` exited with code ${result.code}` }+ }+ console.log(`📦 LM Studio server ${action === 'start' ? 'started' : 'stopped'}`)+ return { success: true }+}+// ---- local-disk introspection / import (migrate fast-path) ------------------const dirExists = (p) => stat(p).then((s) => s.isDirectory()).catch(() => false)@@ -816,6 +856,7 @@ async function importModelFromGguf({ lmstudioId, ggufPath, projectorPath, mode =export {checkLMStudioAvailable,+ controlServer as controlLmStudioServer,getLoadedModels,getLastLoadedModelsError,getAvailableModels,diff --git a/server/services/localLlm.js b/server/services/localLlm.jsindex 59124f989f..2ba6eb6a61 100644--- a/server/services/localLlm.js+++ b/server/services/localLlm.js@@ -1,9 +1,14 @@/*** Local LLM orchestration — unifies the Ollama and LM Studio backends behind* one shape so the UI can list / search / install / delete models, move models- * between backends, and pick the default backend. Both backends can be installed- * and running at the same time; the "default" is just which one PortOS routes- * local runs to.+ * between backends, and pick the default backend. Both can be installed and+ * running at the same time; the "default" is just which one PortOS routes local+ * runs to.+ *+ * These two are the backends PortOS keeps a MODEL CATALOG for. They are not the+ * only local servers it runs: `llamaServerManager.js` and `mtplxServerManager.js`+ * own the two PM2-managed daemons (llama.cpp, MTPLX), and the LLMs page's+ * "Local Runtime Servers" card starts and stops all four through one surface.** The default backend is recorded in `.env` as `LLM_BACKEND` (parallel to* `PGMODE`), so it survives restarts and is readable by the setup script. Thediff --git a/server/services/localModelAssessments.js b/server/services/localModelAssessments.jsindex 627bc494ba..565be9ebf9 100644--- a/server/services/localModelAssessments.js+++ b/server/services/localModelAssessments.js@@ -85,6 +85,7 @@ import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';import { getAllProviders } from './providers.js';import { runEndpointLlmTest, runLocalLlmTest } from './localLlmPlayground.js';import { getLlamaServerEndpoint, relaunchLlamaServerWithTuning } from './llamaServerManager.js';+import { getMtplxServerEndpoint } from './mtplxServerManager.js';import { listModels } from './localLlm.js';import {getLoadedModels as getLoadedOllamaModels,@@ -150,17 +151,19 @@ export function buildSamplePrompt(contextTokens) {/*** Where this runtime's OpenAI-compatible API actually is right now.*- * llama.cpp is the one that moves: PortOS starts it, and a user who picked a- * different port under Advanced options is serving somewhere the default no- * longer names. Ask the manager rather than re-deriving the port here — probing- * the stale default would report a working server as unreachable.+ * The two PM2-managed daemons are the ones that move: PortOS starts llama.cpp+ * and MTPLX, and a user who picked a different port on the LLMs page is serving+ * somewhere the shipped default no longer names. Ask the manager rather than+ * re-deriving the port here — probing the stale default would report a working+ * server as unreachable.*/export async function runtimeEndpoint(runtime) {- if (runtime === 'llama') {- // The endpoint-only accessor, NOT `getLlamaServerStatus` — that one pays for- // a network probe and an `execPm2 logs` subprocess, and this path runs on- // every Performance page load only to learn a port number.- const endpoint = await getLlamaServerEndpoint().catch(() => null);+ // The endpoint-only accessors, NOT the `get*Status` calls — those pay for a+ // network probe and an `execPm2 logs` subprocess, and this path runs on every+ // Performance page load only to learn a port number.+ const resolver = { llama: getLlamaServerEndpoint, mtplx: getMtplxServerEndpoint }[runtime];+ if (resolver) {+ const endpoint = await resolver().catch(() => null);if (endpoint) return endpoint;}return LOCAL_RUNTIMES[runtime]?.defaultBaseUrl || null;diff --git a/server/services/localRuntimeSetup.js b/server/services/localRuntimeSetup.jsindex 7471e88f67..59fee24693 100644--- a/server/services/localRuntimeSetup.js+++ b/server/services/localRuntimeSetup.js@@ -33,31 +33,28 @@* optional `mtplx max --install` fan-control helper behind a sudo prompt.* PortOS installs the package and starts the loopback API server; that* helper stays an explicit operator action outside PortOS, exactly as- * `docs/features/mtplx.md` promised before this button existed.+ * `docs/features/mtplx.md` promised before this button existed. Both of+ * those steps are delegated to `mtplxServerManager.js`, so a server started+ * here is the same PM2 process (`portos-mtplx`) the Models → LLMs page can+ * stop, log, and persist across a reboot — the two surfaces cannot drift+ * onto different install commands or a daemon only one of them can see.* - **The vLLM container is never provisioned.** Its start row brings up an* already-prepared compose project and nothing else: no image pull, no* weight download, no docker/WSL2/NVIDIA-toolkit install. A project that is* not demonstrably prepared is refused with the command that prepares it.*/-import { IS_WIN32 } from '../lib/bufferedSpawn.js';-import { spawn } from '../lib/childProcess.js';-import { commandExists } from '../lib/commandExists.js';-import { sleep } from '../lib/fileUtils.js';import { LOCAL_RUNTIMES, localEndpointPort } from '../lib/localProviderRuntime.js';import { describeMtplxCache, listMtplxCachedModels } from '../lib/mtplxModels.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';import { inspectVllmQwenProject, vllmStartBlockedReason } from '../lib/vllmQwenProject.js';-import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';-import { createLineReader, createOutputTail } from '../lib/streamLines.js';+import { findCommandOnPath } from '../lib/processEnv.js';import { runStreamingCommand } from '../lib/streamingSpawn.js';import { installLlamaServer } from './llamaServerManager.js';+import { installMtplx, startMtplxServer, MTPLX_UNSUPPORTED_REASON } from './mtplxServerManager.js';import { controlOllamaServer, installBackend } from './localLlm.js';import { isAppInstalled as isLmStudioAppInstalled } from './lmStudioManager.js';-/** Package-manager installs routinely run for minutes (a cask is a download). */-const INSTALL_TIMEOUT_MS = 20 * 60 * 1000;-/** A short command that only asks a running daemon to do something. */const CONTROL_TIMEOUT_MS = 60 * 1000;@@ -76,20 +73,10 @@ const WEIGHTS_TIMEOUT_MS = 6 * 60 * 60 * 1000;const PROGRESS_SPLIT_RE = /[\r\n]+/;/**- * How long to wait for a just-started daemon to answer `/v1/models`. MTPLX- * loads a multi-gigabyte MLX checkpoint before it binds, so this is sized for a- * cold model load rather than for a socket coming up.- */-/**- * Parked on a detached daemon's `error` once this module stops watching it. An- * EventEmitter `error` with NO listener throws, which outside the request- * lifecycle takes the PortOS process down — so the watchers are replaced, never- * merely removed. Module-scope, so it closes over nothing.+ * How long a start step waits for a just-started daemon to answer. Sized for a+ * cold multi-gigabyte model load, not for a socket coming up.*/-const IGNORE_ERROR = () => {};-const START_TIMEOUT_MS = 3 * 60 * 1000;-const START_POLL_MS = 1_500;/*** Bound on the `GET /v1/models` reachability probes. Loopback answers (or@@ -125,105 +112,6 @@ const ACTION_LABELS = {/** Every action `runLocalRuntimeSetup` accepts — route validation reads this. */export const SETUP_ACTIONS = Object.freeze(Object.keys(ACTION_LABELS));-/**- * Spawn a long-lived local daemon and wait until its OpenAI-compatible endpoint- * answers. Detached (own process group) so PortOS restarting does not take the- * daemon down with it, and `unref`'d so a running daemon never holds the PortOS- * process open. Output is streamed only during the startup window — a daemon's- * steady-state request log is not install progress.- */-async function startDaemon({ command, args, endpoint, emit, isCancelled = () => false, timeoutMs = START_TIMEOUT_MS }) {- const binary = findCommandOnPath(command);- if (!binary) return { success: false, error: `\`${command}\` was not found on PortOS's PATH after the install. Restart PortOS so it picks up the new bin directory, then try again.` };-- emit(`Starting: ${command} ${args.join(' ')}`);- const child = spawn(binary, args, safeChildProcessOptions({- env: safeChildProcessEnv(),- shell: false,- stdio: ['ignore', 'pipe', 'pipe'],- detached: !IS_WIN32,- }));-- let exited = null;- // Recent output, so a daemon that dies before it binds reports what it- // printed rather than only its exit code.- const tail = createOutputTail();- const onLine = (line) => {- const text = line.trim();- if (!text) return;- tail.remember(text);- emit(text);- };- // One reader per stream: a shared carry buffer splices a half-written stdout- // line onto the next stderr chunk (see `lib/streamLines.js`).- const stdoutReader = createLineReader(onLine);- const stderrReader = createLineReader(onLine);- const onStdout = stdoutReader.push;- const onStderr = stderrReader.push;- child.stdout?.on('data', onStdout);- child.stderr?.on('data', onStderr);- // Outside the request lifecycle: an unhandled 'error' on a child is a process- // crash, and the exit code is what turns "still waiting" into a real reason.- const onError = (err) => { exited = `failed to start: ${err.message}`; };- const onExit = (code, signal) => {- if (exited === null) exited = `exited early (${signal || `code ${code}`})`;- };- child.on('error', onError);- child.on('exit', onExit);- /**- * Detach from the daemon, which outlives this request.- *- * Keep DRAINING: a daemon whose stdout pipe fills up blocks on its next- * write, and `resume()` on a listener-less stream discards what it reads.- *- * Drop EVERY listener, not just `onData`: they share one closure scope, so- * any one of them left attached to a long-lived child pins that scope — and- * `emit` in it — which holds the SSE response open for the daemon's whole- * lifetime. `IGNORE_ERROR` takes the `error` slot back so a later crash- * cannot throw on an emitter with no listener.- */- const stopStreaming = () => {- child.stdout?.off('data', onStdout);- child.stderr?.off('data', onStderr);- for (const stream of [child.stdout, child.stderr]) {- stream?.resume();- }- child.off('error', onError);- child.off('exit', onExit);- child.on('error', IGNORE_ERROR);- child.unref();- };-- const deadline = Date.now() + timeoutMs;- while (Date.now() < deadline) {- await sleep(START_POLL_MS);- // The daemon is deliberately left running when the user closes the modal —- // it is the thing they asked for, and killing it would undo the setup. Only- // the WAIT stops.- if (isCancelled()) {- stopStreaming();- return { success: false, error: 'Cancelled while waiting for the server to come up.' };- }- const probe = await probeOpenAiModels(endpoint, { timeoutMs: PROBE_TIMEOUT_MS });- if (probe.reachable) {- stopStreaming();- return { success: true, models: probe.models };- }- if (exited) {- // Flush FIRST: the reason a daemon dies is often its last line, and a- // child that exited without a trailing newline leaves it in the carry.- stdoutReader.flush();- stderrReader.flush();- stopStreaming();- const detail = tail.text();- return { success: false, error: `${command} ${exited}.${detail ? ` ${detail}` : ''}` };- }- }-- stopStreaming();- return { success: false, error: `${endpoint} still did not answer after ${Math.round(timeoutMs / 1000)}s. The daemon may still be loading a model — reload this page shortly.` };-}-/*** One row per local runtime PortOS can set up on its own.*@@ -235,20 +123,14 @@ async function startDaemon({ command, args, endpoint, emit, isCancelled = () =>const SETUP_ROWS = Object.freeze({mtplx: Object.freeze({platforms: ['darwin'],- unsupportedReason: 'MTPLX runs only on macOS with Apple Silicon.',+ unsupportedReason: MTPLX_UNSUPPORTED_REASON,async install({ emit }) {- // Upstream's recommended path is its Homebrew tap; pip is the documented- // fallback for a host without Homebrew. Both install the same `mtplx`- // binary, and neither runs the optional privileged fan-control helper.- if (await commandExists('brew', ['--version'])) {- emit('Installing MTPLX via Homebrew (youssofal/mtplx/mtplx)…');- return runStreamingCommand('brew', ['install', 'youssofal/mtplx/mtplx'], emit, { timeoutMs: INSTALL_TIMEOUT_MS });- }- if (await commandExists('python3', ['--version'])) {- emit('Homebrew was not found — installing MTPLX with pip instead…');- return runStreamingCommand('python3', ['-m', 'pip', 'install', '--upgrade', 'mtplx'], emit, { timeoutMs: INSTALL_TIMEOUT_MS });- }- return { success: false, error: 'Neither Homebrew nor python3 is available. Install Homebrew from https://brew.sh, then try again.' };+ // Same install `mtplxServerManager` runs from the Models → LLMs card:+ // upstream's Homebrew tap, with pip as the documented fallback for a host+ // without Homebrew. Neither runs the optional privileged fan-control helper.+ const result = await installMtplx({ onProgress: (p) => { if (p?.message) emit(p.message); } })+ .catch((err) => ({ success: false, error: err.message }));+ return result;},/*** What MTPLX's own cache holds, WITHOUT starting it — `mtplx models --json`@@ -281,7 +163,11 @@ const SETUP_ROWS = Object.freeze({// `mtplx serve` defaults `--model` to ONE hard-coded checkpoint and exits// 1 before binding when that repo is not in its cache — even on a machine// holding a different MTP model that would have served fine. Ask the- // cache first and name what is actually there.+ // cache first and name what is actually there. Read HERE rather than+ // leaving it to the manager because the refusals differ by surface: this+ // checklist can offer the `pull-start` download button, and the messages+ // above say so; the Models → LLMs launcher has no such button and names+ // `mtplx pull` instead.const cache = describeMtplxCache(await listMtplxCachedModels());if (cache.state === 'unknown') {// The cache could not be READ — which is not "read, and empty". Fall@@ -294,15 +180,20 @@ const SETUP_ROWS = Object.freeze({if (cache.model) emit(`Serving the cached MTPLX model ${cache.model}.`);// The cache lookup is an awaited subprocess — the modal can close while it// runs, and the caller's cancellation check happened BEFORE it. Without- // this, a cancelled setup still spawns a detached daemon nobody asked to- // keep.+ // this, a cancelled setup still starts a server nobody asked to keep.if (isCancelled()) return { success: false, error: 'Cancelled before the server was started.' };- // `mtplx start` is interactive (it prompts for a model); `serve` is the- // API-only server, which is the half PortOS actually talks to. The daemon- // must bind where the PROVIDER points — a user who moved MTPLX to 8010- // would otherwise get a second server on 8000 that nothing talks to.- const args = ['serve', '--port', localEndpointPort(endpoint) || '8000', ...(cache.model ? ['--model', cache.model] : [])];- return startDaemon({ command: 'mtplx', args, endpoint, emit, isCancelled });+ // Delegated to the PM2-backed manager so a server started from this+ // checklist is the SAME managed process the LLMs page can stop, log, and+ // persist with `pm2 save` — a detached spawn here would be invisible there.+ // The resolved checkpoint rides along so the manager does not walk the+ // cache a second time for one start.+ const port = Number(localEndpointPort(endpoint)) || undefined;+ // This flow's contract is "the endpoint answers when the button finishes",+ // so it buys the full cold-model-load budget rather than the launcher's+ // short beat — MTPLX loads a multi-gigabyte MLX checkpoint before it binds.+ return startMtplxServer({ port, model: cache.model, waitMs: START_TIMEOUT_MS, onProgress: emit })+ .then(() => ({ success: true }))+ .catch((err) => ({ success: false, error: err.message }));},}),diff --git a/server/services/localRuntimeSetup.test.js b/server/services/localRuntimeSetup.test.jsindex 2054eebc47..119b2c0a12 100644--- a/server/services/localRuntimeSetup.test.js+++ b/server/services/localRuntimeSetup.test.js@@ -27,16 +27,23 @@ const localLlm = vi.hoisted(() => ({}));vi.mock('./localLlm.js', () => localLlm);vi.mock('./lmStudioManager.js', () => ({ isAppInstalled: () => false }));-const child = vi.hoisted(() => ({ spawn: vi.fn() }));-vi.mock('../lib/childProcess.js', () => child);-// MTPLX's model cache — the setup asks it what is actually cached before it-// starts a server that would otherwise exit 1 looking for a checkpoint.+// MTPLX's model cache — this module reads it directly (the checklist's refusals+// and its `pull-start` download button are phrased for THIS surface, so the+// reading happens here rather than inside the manager).const mtplxCache = vi.hoisted(() => ({ listMtplxCachedModels: vi.fn() }));// PARTIAL mock: only the subprocess call is faked. `describeMtplxCache` and// `pickMtplxCachedModel` are pure classifiers of that output, and stubbing them// would let a wrong reading of a real cache listing pass here.vi.mock('../lib/mtplxModels.js', async (importOriginal) => ({ ...(await importOriginal()), ...mtplxCache }));-vi.mock('../lib/fileUtils.js', () => ({ sleep: async () => {} }));+// The install and the launch itself are delegated to the PM2-backed manager+// (`portos-mtplx`) — its Homebrew/pip install and `mtplx serve` launch line are+// covered in `mtplxServerManager.test.js`. This suite asserts the delegation.+const mtplx = vi.hoisted(() => ({+ installMtplx: vi.fn(async () => ({ success: true })),+ startMtplxServer: vi.fn(async () => ({ success: true, endpoint: 'http://127.0.0.1:8000/v1' })),+ MTPLX_UNSUPPORTED_REASON: 'MTPLX runs only on macOS with Apple Silicon.',+}));+vi.mock('./mtplxServerManager.js', () => mtplx);// The vLLM compose project on disk. Mocked so the suite never stats a real// checkout, and so each start case can pick its own refusal.const vllmProject = vi.hoisted(() => ({@@ -48,19 +55,6 @@ vi.mock('../lib/vllmQwenProject.js', () => vllmProject);import { describeRuntimeSetup, readRuntimeWeights, runLocalRuntimeSetup, SETUP_ACTIONS, SETUP_RUNTIME_KINDS } from './localRuntimeSetup.js';const unreachable = { reachable: false, models: null, error: 'ECONNREFUSED' };-/** A spawned daemon whose stdio never emits, driven entirely by the poll loop. */-const fakeChild = () => {- const stream = () => ({ on: vi.fn(), off: vi.fn(), resume: vi.fn() });- const handlers = {};- return {- stdout: stream(),- stderr: stream(),- on: vi.fn((event, fn) => { handlers[event] = fn; }),- off: vi.fn(),- unref: vi.fn(),- emitEvent: (event, ...args) => handlers[event]?.(...args),- };-};const reachable = (models = ['mtplx']) => ({ reachable: true, models, error: null });const cachedModels = (models) => ({ models, error: null });@@ -71,12 +65,12 @@ beforeEach(() => {vllmProject.inspectVllmQwenProject.mockResolvedValue(preparedVllmProject);vllmProject.vllmStartBlockedReason.mockReturnValue(null);// Implementations AND return values (not just call records) survive- // `clearAllMocks`. A probe implementation left over from an earlier test drives- // this module's poll loop for its full three-minute timeout, and a leftover- // `spawn` return value hands a stale child to whichever test spawns next.+ // `clearAllMocks`, so a probe implementation left over from an earlier test+ // would drive this module's poll loop for its full timeout.probe.probeOpenAiModels.mockReset();- child.spawn.mockReset();mtplxCache.listMtplxCachedModels.mockResolvedValue(cachedModels([{ repo_id: 'Example/MTP-Model', validation: { ok: true } }]));+ mtplx.installMtplx.mockResolvedValue({ success: true });+ mtplx.startMtplxServer.mockResolvedValue({ success: true, endpoint: 'http://127.0.0.1:8000/v1' });});afterEach(() => {@@ -188,39 +182,30 @@ describe('runLocalRuntimeSetup', () => {expect(streaming.runStreamingCommand).not.toHaveBeenCalled();});- it('installs MTPLX from its Homebrew tap — never the privileged fan-control helper', async () => {- probe.probeOpenAiModels.mockResolvedValue(unreachable);- const restore = pinPlatform('darwin');-- await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });- restore();-- const [cmd, args] = streaming.runStreamingCommand.mock.calls[0];- expect(cmd).toBe('brew');- expect(args).toEqual(['install', 'youssofal/mtplx/mtplx']);- expect(streaming.runStreamingCommand.mock.calls.flatMap(([, a]) => a)).not.toContain('max');- });-- it('falls back to pip when Homebrew is absent', async () => {+ it('delegates the MTPLX install to its PM2-backed manager', async () => {probe.probeOpenAiModels.mockResolvedValue(unreachable);- commands.commandExists.mockImplementation(async (cmd) => cmd !== 'brew');const restore = pinPlatform('darwin');await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });restore();- expect(streaming.runStreamingCommand.mock.calls[0][0]).toBe('python3');+ expect(mtplx.installMtplx).toHaveBeenCalled();+ // Nothing about MTPLX is installed by a command this module composes — which+ // is what keeps upstream's privileged `mtplx max --install` fan-control+ // helper out of every PortOS path.+ expect(streaming.runStreamingCommand).not.toHaveBeenCalled();});it('stops at the install failure rather than starting a daemon that is not there', async () => {probe.probeOpenAiModels.mockResolvedValue(unreachable);- streaming.runStreamingCommand.mockResolvedValue({ success: false, error: 'exit 1: no such formula' });+ mtplx.installMtplx.mockResolvedValue({ success: false, error: 'exit 1: no such formula' });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.stringMatching(/no such formula/) });+ expect(mtplx.startMtplxServer).not.toHaveBeenCalled();});it('refuses a host that cannot run the runtime at all', async () => {@@ -282,96 +267,58 @@ describe('runLocalRuntimeSetup', () => {expect(result).toMatchObject({ success: false, error: expect.stringMatching(/Cancelled/) });});- it('starts `mtplx serve` on the port the PROVIDER points at, not a hard-coded 8000', async () => {- const daemon = fakeChild();- child.spawn.mockReturnValue(daemon);- // Not installed at the pre-flight check; on PATH once the install lands.- pathLookup.findCommandOnPath.mockReturnValueOnce(null).mockReturnValue('/opt/homebrew/bin/mtplx');+ it('starts MTPLX on the port the PROVIDER points at, not a hard-coded 8000', async () => {+ // A user who moved MTPLX to 8010 would otherwise get a second server on+ // 8000 that nothing talks to.+ pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');probe.probeOpenAiModels.mockResolvedValueOnce(unreachable) // pre-flight.mockResolvedValueOnce(unreachable) // after install- .mockResolvedValueOnce(reachable(['mtplx'])) // first poll after spawn.mockResolvedValueOnce(reachable(['mtplx'])); // final confirmation+ mtplx.startMtplxServer.mockResolvedValue({ success: true, endpoint: 'http://127.0.0.1:8010/v1' });const restore = pinPlatform('darwin');const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8010/v1' });restore();- const [binary, args] = child.spawn.mock.calls[0];- expect(binary).toBe('/opt/homebrew/bin/mtplx');- expect(args).toEqual(['serve', '--port', '8010', '--model', 'Example/MTP-Model']);- expect(daemon.unref).toHaveBeenCalled();+ expect(mtplx.startMtplxServer).toHaveBeenCalledWith(expect.objectContaining({ port: 8010 }));expect(result).toMatchObject({ success: true, message: expect.stringContaining('http://127.0.0.1:8010/v1') });});- it('detaches every listener from the daemon it leaves running', async () => {- // The daemon outlives the request. Any listener still attached pins the- // closure scope holding `emit` — and through it the SSE response — for the- // daemon's whole lifetime. The `error` slot is REPLACED rather than left- // empty: an EventEmitter `error` with no listener throws, and outside the- // request lifecycle that takes the process down.- const daemon = fakeChild();- child.spawn.mockReturnValue(daemon);+ it('waits out a cold model load rather than the launcher\'s short beat', async () => {+ // This flow's contract is "the endpoint answers when the button finishes",+ // so it must not inherit the LLMs-page budget that hands back a still-loading+ // server and lets a status poll finish the story.pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');probe.probeOpenAiModels.mockResolvedValueOnce(unreachable).mockResolvedValueOnce(unreachable)- .mockResolvedValueOnce(reachable(['mtplx'])).mockResolvedValueOnce(reachable(['mtplx']));const restore = pinPlatform('darwin');await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });restore();- const detached = daemon.off.mock.calls.map(([event]) => event);- expect(detached).toContain('error');- expect(detached).toContain('exit');- for (const stream of [daemon.stdout, daemon.stderr]) {- expect(stream.off).toHaveBeenCalledWith('data', expect.any(Function));- // …and keep draining, so a full pipe can't block the daemon's next write.- expect(stream.resume).toHaveBeenCalled();- }- // A no-op error listener is parked in place of the one that was removed.- expect(daemon.on.mock.calls.filter(([event]) => event === 'error')).toHaveLength(2);+ const [{ waitMs }] = mtplx.startMtplxServer.mock.calls[0];+ expect(waitMs).toBeGreaterThanOrEqual(60_000);});- it('reports a daemon that died on startup instead of waiting out the timeout', async () => {- const daemon = fakeChild();- child.spawn.mockReturnValue(daemon);- pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');- probe.probeOpenAiModels.mockImplementation(async () => {- daemon.emitEvent('exit', 1, null);- return unreachable;- });- 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.stringMatching(/exited early \(code 1\)/) });- });-- it('refuses to start MTPLX with an EMPTY model cache, naming the pull command', async () => {- // `mtplx serve` defaults to one hard-coded checkpoint and exits 1 before it- // binds when nothing is cached. Spawning it anyway is how "Start MTPLX"- // reported "exited early (code 1)" and left the user with no next step.- mtplxCache.listMtplxCachedModels.mockResolvedValue(cachedModels([]));+ 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.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`'));const restore = pinPlatform('darwin');const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });restore();- expect(child.spawn).not.toHaveBeenCalled();expect(result).toMatchObject({ success: false, error: expect.stringContaining('mtplx pull') });});it('downloads the default checkpoint and then starts, but ONLY for `pull-start`', async () => {// The other half of the fix: the button the checklist now offers actually// fetches the weights, so the user is not sent to a terminal.- const daemon = fakeChild();- child.spawn.mockReturnValue(daemon);pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');// The cache is read by the START step, which runs AFTER the pull — so what// it reports here is what the download just landed.@@ -380,7 +327,6 @@ describe('runLocalRuntimeSetup', () => {probe.probeOpenAiModels.mockResolvedValueOnce(unreachable).mockResolvedValueOnce(unreachable)- .mockResolvedValueOnce(reachable(['mtplx'])).mockResolvedValueOnce(reachable(['mtplx']));const restore = pinPlatform('darwin');@@ -390,7 +336,9 @@ describe('runLocalRuntimeSetup', () => {expect(streaming.runStreamingCommand).toHaveBeenCalledWith('/opt/homebrew/bin/mtplx', ['pull'], expect.any(Function), expect.objectContaining({ splitRe: expect.any(RegExp) }),);- expect(child.spawn.mock.calls[0][1]).toEqual(['serve', '--port', '8000', '--model', 'Example/Fresh']);+ // The checkpoint the pull just landed is handed to the manager, so it does+ // not walk the same cache a second time for one start.+ expect(mtplx.startMtplxServer).toHaveBeenCalledWith(expect.objectContaining({ port: 8000, model: 'Example/Fresh' }));expect(result.success).toBe(true);});@@ -406,6 +354,7 @@ describe('runLocalRuntimeSetup', () => {restore();expect(streaming.runStreamingCommand).not.toHaveBeenCalled();+ expect(mtplx.startMtplxServer).not.toHaveBeenCalled();expect(result).toMatchObject({ success: false, error: expect.stringContaining('mtplx pull') });});@@ -414,8 +363,6 @@ describe('runLocalRuntimeSetup', () => {// renders THIS server's button label, so on an empty cache the user clicked// “Download the default model & start MTPLX”. Defaulting to a start would// answer that click with the exact no-weights dead end the action removes.- const daemon = fakeChild();- child.spawn.mockReturnValue(daemon);pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');mtplxCache.listMtplxCachedModels.mockResolvedValueOnce(cachedModels([]))@@ -423,7 +370,6 @@ describe('runLocalRuntimeSetup', () => {probe.probeOpenAiModels.mockResolvedValueOnce(unreachable).mockResolvedValueOnce(unreachable)- .mockResolvedValueOnce(reachable(['mtplx'])).mockResolvedValueOnce(reachable(['mtplx']));const restore = pinPlatform('darwin');@@ -435,13 +381,10 @@ describe('runLocalRuntimeSetup', () => {});it('resolves an ABSENT action to a plain start when the cache can serve', async () => {- const daemon = fakeChild();- child.spawn.mockReturnValue(daemon);pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');probe.probeOpenAiModels.mockResolvedValueOnce(unreachable).mockResolvedValueOnce(unreachable)- .mockResolvedValueOnce(reachable(['mtplx'])).mockResolvedValueOnce(reachable(['mtplx']));const restore = pinPlatform('darwin');@@ -449,7 +392,7 @@ describe('runLocalRuntimeSetup', () => {restore();expect(streaming.runStreamingCommand).not.toHaveBeenCalled();- expect(child.spawn.mock.calls[0][1]).toContain('serve');+ expect(mtplx.startMtplxServer).toHaveBeenCalled();});it('refuses `pull-start` for a runtime with no pull step BEFORE installing anything', async () => {@@ -474,13 +417,9 @@ describe('runLocalRuntimeSetup', () => {// modal, so the download keeps going AND every other runtime's setup button// is refused for the rest of it.pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');- child.spawn.mockReturnValue(fakeChild());- // Let the daemon come up, so this case ends at a settled setup rather than- // spinning the start poll until its three-minute deadline.probe.probeOpenAiModels.mockResolvedValueOnce(unreachable).mockResolvedValueOnce(unreachable)- .mockResolvedValueOnce(reachable(['mtplx'])).mockResolvedValueOnce(reachable(['mtplx']));const isCancelled = () => false;const restore = pinPlatform('darwin');@@ -508,7 +447,7 @@ describe('runLocalRuntimeSetup', () => {const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1', action: 'pull-start' });restore();- expect(child.spawn).not.toHaveBeenCalled();+ expect(mtplx.startMtplxServer).not.toHaveBeenCalled();expect(result).toMatchObject({ success: false, error: expect.stringContaining('connection reset') });});@@ -522,37 +461,35 @@ describe('runLocalRuntimeSetup', () => {probe.probeOpenAiModels.mockResolvedValue(unreachable);const restore = pinPlatform('darwin');- const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });+ const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1', action: 'start' });restore();- expect(child.spawn).not.toHaveBeenCalled();+ expect(mtplx.startMtplxServer).not.toHaveBeenCalled();expect(result).toMatchObject({ success: false, error: expect.stringMatching(/none passed its own file check/) });});it('starts MTPLX on its own default when the cache cannot be READ', async () => {// Unreadable is not empty: blocking here would refuse a start that works.mtplxCache.listMtplxCachedModels.mockResolvedValue({ models: null, error: '`mtplx models` timed out' });- const daemon = fakeChild();- child.spawn.mockReturnValue(daemon);pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');probe.probeOpenAiModels.mockResolvedValueOnce(unreachable).mockResolvedValueOnce(unreachable)- .mockResolvedValueOnce(reachable(['mtplx'])).mockResolvedValueOnce(reachable(['mtplx']));const restore = pinPlatform('darwin');const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });restore();- expect(child.spawn.mock.calls[0][1]).toEqual(['serve', '--port', '8000']);+ // No checkpoint to name, so the manager falls through to MTPLX's own default.+ expect(mtplx.startMtplxServer).toHaveBeenCalledWith(expect.objectContaining({ model: null }));expect(result.success).toBe(true);});- it('does not spawn a daemon when the modal closed while the cache was being read', async () => {+ it('does not start a server when the modal closed while the cache was being read', async () => {// The cache lookup is an awaited subprocess, and the caller's cancellation- // check ran BEFORE it — without a re-check, a closed modal still leaves a- // detached MTPLX server running.+ // check ran BEFORE it — without a re-check, a closed modal still leaves an+ // MTPLX server running.let cancelled = false;mtplxCache.listMtplxCachedModels.mockImplementation(async () => {cancelled = true; // the user closes the modal while `mtplx models` runs@@ -568,39 +505,10 @@ describe('runLocalRuntimeSetup', () => {});restore();- expect(child.spawn).not.toHaveBeenCalled();+ expect(mtplx.startMtplxServer).not.toHaveBeenCalled();expect(result).toMatchObject({ success: false, error: expect.stringMatching(/Cancelled/) });});- it('reports what a dying daemon printed, skipping its ASCII-art banner', async () => {- const daemon = fakeChild();- child.spawn.mockReturnValue(daemon);- pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');- // The stdout handler is registered as `on('data', …)` — feed it the way the- // real stream would, split across chunks mid-line.- const feed = (chunk) => daemon.stdout.on.mock.calls.find(([event]) => event === 'data')?.[1](chunk);- let printed = false;- probe.probeOpenAiModels.mockImplementation(async () => {- // Only once the daemon has been spawned and its stdout hooked up.- if (daemon.stdout.on.mock.calls.length > 0 && !printed) {- printed = true;- feed('╭──────────╮\n╰──────────╯\nerror: model is not ava');- feed('ilable locally\ndetail: run mtplx pull\n');- daemon.emitEvent('exit', 1, null);- }- return unreachable;- });- const restore = pinPlatform('darwin');-- const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });- restore();-- expect(result.error).toContain('exited early (code 1)');- // Line reassembled across the chunk boundary, box drawing left out of it.- expect(result.error).toContain('error: model is not available locally');- expect(result.error).not.toContain('╭');- });-it('refuses a runtime kind it has no row for', async () => {const result = await runLocalRuntimeSetup('made-up', { endpoint: 'http://127.0.0.1:9/v1' });expect(result).toMatchObject({ success: false, error: expect.stringMatching(/no automatic setup/) });diff --git a/server/services/mtplxServerManager.js b/server/services/mtplxServerManager.jsnew file mode 100644index 0000000000..e88adcadd3--- /dev/null+++ b/server/services/mtplxServerManager.js@@ -0,0 +1,367 @@+/**+ * MTPLX process manager+ *+ * Lifecycle management (status probe, install, start, stop, recent logs) for the+ * local `mtplx serve` OpenAI-compatible API server, managed as an optional PM2+ * process (`portos-mtplx`) — deliberately the same shape as+ * `llamaServerManager.js`.+ *+ * PM2 rather than a bare detached spawn, because that is what makes the daemon+ * *manageable*: `pm2 list` shows it next to the rest of the install, `pm2 logs`+ * has its output, restart-on-boot is a `pm2 save` away, and a PortOS restart can+ * 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.+ * - **MTPLX's privileged paths are never touched.** Upstream's optional+ * `mtplx max --install` fan-control helper stays an explicit operator action+ * outside PortOS.+ */++import { commandExists } from '../lib/commandExists.js';+import { sleep } from '../lib/fileUtils.js';+import { ServerError } from '../lib/errorHandler.js';+import { LOCAL_RUNTIMES, localEndpointPort } from '../lib/localProviderRuntime.js';+import { listMtplxCachedModels, pickMtplxCachedModel } from '../lib/mtplxModels.js';+import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';+import { createDaemonLogBuffer, pm2ArgValue } from '../lib/managedDaemon.js';+import { isAppleSilicon, isPortInUse } from '../lib/platform.js';+import { findCommandOnPath } from '../lib/processEnv.js';+import { runStreamingCommand } from '../lib/streamingSpawn.js';+import { execPm2, getAppStatusStrict, clearJlistCache, getSavedProcessNames } from './pm2.js';++export const MTPLX_APP = 'portos-mtplx';++const PROBE_TIMEOUT_MS = 1500;+/**+ * How long `startMtplxServer` waits before returning.+ *+ * This is NOT how long MTPLX gets to come up — it is how long the HTTP request+ * blocks. MTPLX loads a multi-gigabyte MLX checkpoint before it binds, which+ * routinely outlasts any sane request timeout, so the wait exists only to catch+ * a server that dies immediately (an empty cache, a bad checkpoint). Still+ * loading after this returns `online: false` and the status poll takes over —+ * exactly what `llamaServerManager` does with its own four-second beat.+ *+ * Mutable only through the test seam below, so a suite asserting the+ * still-loading path doesn't have to sit through the real budget.+ */+let startupWaitMs = 8_000;+const STARTUP_POLL_MS = 1500;+/** Package-manager installs routinely run for minutes. */+const INSTALL_TIMEOUT_MS = 20 * 60 * 1000;++/**+ * The default loopback endpoint the shipped MTPLX provider presets point at.+ * Read from the runtime table rather than re-declared, so the launcher and the+ * readiness probe cannot drift onto different ports.+ */+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.';++let currentConfig = null;+let lastExitError = null;+const logs = createDaemonLogBuffer();+const appendLog = logs.append;++const probeEndpoint = async (endpoint) =>+ (await probeOpenAiModels(endpoint, { timeoutMs: PROBE_TIMEOUT_MS })).reachable;++const endpointFor = (config) =>+ `http://${config?.host || DEFAULT_HOST}:${config?.port ?? DEFAULT_PORT}/v1`;++/**+ * Reconstructs the launch config from PM2 process args when PortOS restarted+ * while the PM2 process stayed online — same recovery `llamaServerManager` does,+ * so a restart doesn't report a server it started as "external".+ */+function parseConfigFromArgs(args) {+ if (!args) return null;+ const list = Array.isArray(args) ? args : String(args).split(' ');+ if (!list.includes('serve')) return null;+ const port = pm2ArgValue(list, '--port');+ return {+ host: pm2ArgValue(list, '--host') || DEFAULT_HOST,+ port: port ? Number(port) : DEFAULT_PORT,+ // Absent means MTPLX was started on its OWN default checkpoint — don't+ // invent a repo id the launch line never carried.+ model: pm2ArgValue(list, '--model'),+ };+}++/** Resolve the `mtplx` executable on the child-process PATH. */+const resolveMtplxBinary = () => findCommandOnPath('mtplx');++/** Just the base URL MTPLX is serving on — no endpoint probe, no PM2 log fetch. */+export async function getMtplxServerEndpoint() {+ if (!currentConfig) {+ const pm2Status = await getAppStatusStrict(MTPLX_APP);+ if (pm2Status?.status === 'online' && pm2Status.args) currentConfig = parseConfigFromArgs(pm2Status.args);+ }+ return endpointFor(currentConfig);+}++/**+ * Current MTPLX state: binary availability, process state, endpoint, config,+ * logs, and what is in its model cache.+ *+ * The cache listing is a local directory walk (`mtplx models --json`) — no+ * network, no model load — so it is safe on a status poll, and it is what lets+ * the UI say "installed, but nothing to serve" instead of making the user press+ * Start to find out.+ */+export async function getMtplxServerStatus() {+ const binaryPath = resolveMtplxBinary();+ const installed = Boolean(binaryPath);+ // The platform gate is about what PortOS may INSTALL, never about what is+ // already there: a binary on PATH (or a server answering) is proof enough that+ // this host runs it, and reporting "macOS only" over a working install would+ // be a false negative.+ const supported = installed || isAppleSilicon();++ const [pm2Status, savedApps] = await Promise.all([getAppStatusStrict(MTPLX_APP), getSavedProcessNames()]);+ const isReadFailed = pm2Status === null;+ const isManagedActive = Boolean(pm2Status && pm2Status.status === 'online');++ if (!currentConfig && isManagedActive && pm2Status?.args) currentConfig = parseConfigFromArgs(pm2Status.args);++ const endpoint = endpointFor(currentConfig);+ const reachable = await probeEndpoint(endpoint);++ // `models: null` means the cache could NOT be read — deliberately not the same+ // as `[]` (read, and empty). Only the latter blocks a start.+ const cache = installed ? await listMtplxCachedModels() : { models: null, error: null };++ const pm2Logs = pm2Status && pm2Status.status !== 'not_found'+ ? await execPm2(['logs', MTPLX_APP, '--nostream', '--lines', String(logs.maxLines)]).catch(() => null)+ : null;++ return {+ installed,+ supported,+ unsupportedReason: supported ? null : MTPLX_UNSUPPORTED_REASON,+ running: isManagedActive || reachable,+ managed: isReadFailed ? null : isManagedActive,+ pid: isManagedActive ? (pm2Status?.pid || null) : null,+ host: currentConfig?.host || DEFAULT_HOST,+ port: currentConfig?.port ?? DEFAULT_PORT,+ endpoint,+ config: isManagedActive ? currentConfig : null,+ // Is this PM2 app in the saved dump `pm2 resurrect` replays at boot?+ // `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),+ cacheError: cache.error,+ recentLogs: logs.withPm2Logs(`${pm2Logs?.stdout || ''}\n${pm2Logs?.stderr || ''}`),+ lastExitError: isReadFailed ? 'Failed to read PM2 status' : lastExitError,+ };+}++/**+ * Install MTPLX from upstream's Homebrew tap, falling back to pip on a host+ * without Homebrew. Both install the same `mtplx` binary, and neither runs the+ * optional privileged fan-control helper.+ */+export async function installMtplx({ onProgress = () => {} } = {}) {+ const emit = (message) => onProgress({ event: 'progress', message });+ if (!isAppleSilicon()) {+ throw new ServerError(MTPLX_UNSUPPORTED_REASON, { status: 400, code: 'MTPLX_UNSUPPORTED_PLATFORM' });+ }+ if (await commandExists('brew', ['--version'])) {+ emit('Installing MTPLX via Homebrew (youssofal/mtplx/mtplx)…');+ const result = await runStreamingCommand('brew', ['install', 'youssofal/mtplx/mtplx'], emit, { timeoutMs: INSTALL_TIMEOUT_MS });+ if (!result.success) throw new ServerError(`MTPLX install failed: ${result.error}`, { status: 500 });+ return { success: true, message: 'MTPLX installed' };+ }+ if (await commandExists('python3', ['--version'])) {+ emit('Homebrew was not found — installing MTPLX with pip instead…');+ const result = await runStreamingCommand('python3', ['-m', 'pip', 'install', '--upgrade', 'mtplx'], emit, { timeoutMs: INSTALL_TIMEOUT_MS });+ if (!result.success) throw new ServerError(`MTPLX install failed: ${result.error}`, { status: 500 });+ return { success: true, message: 'MTPLX installed' };+ }+ throw new ServerError('Neither Homebrew nor python3 is available. Install Homebrew from https://brew.sh, then try again.', { status: 400 });+}++/**+ * Resolve which cached checkpoint `mtplx serve` should be started on.+ *+ * `mtplx serve` defaults `--model` to ONE hard-coded repo id and exits 1 before+ * binding when that repo is not cached — even on a machine holding a different+ * MTP model that would have served fine. So ask the cache first and name what is+ * actually there.+ *+ * Returns `{ model }` (possibly `null` = fall through to MTPLX's own default+ * because the cache could not be READ) or `{ error }`.+ */+async function resolveStartModel(requested, emit) {+ if (requested) return { model: requested };+ const cache = await listMtplxCachedModels();+ if (cache.models === null) {+ emit(`Could not read MTPLX's model cache (${cache.error}) — starting with its default model.`);+ return { model: null };+ }+ if (cache.models.length === 0) return { error: MTPLX_NO_MODEL_ERROR };+ 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 { model };+}++/**+ * Start `mtplx serve` under PM2.+ *+ * `waitMs` overrides how long this blocks before handing back `online: false`+ * for a server that is still loading. The LLMs-page launcher takes the short+ * default and lets its status poll finish the story; the provider-readiness+ * checklist passes its own longer budget, because that flow's contract is "the+ * endpoint answers when this returns".+ *+ * @param {{port?: number, host?: string, model?: string, waitMs?: number, onProgress?: (line: string) => void}} options+ */+export async function startMtplxServer(options = {}) {+ const { port = DEFAULT_PORT, host = DEFAULT_HOST, model: requestedModel = null, waitMs, onProgress = () => {} } = options;+ const emit = (line) => { appendLog(line); onProgress(line); };++ const binaryPath = resolveMtplxBinary();+ if (!binaryPath) {+ throw new ServerError(+ 'The `mtplx` binary was not found on PATH. Install it from this card (Homebrew tap, or pip as a fallback), then try again.',+ { status: 400, code: 'MTPLX_NOT_INSTALLED' }+ );+ }++ const pm2Status = await getAppStatusStrict(MTPLX_APP);+ if (pm2Status && pm2Status.status === 'online') {+ throw new ServerError(`MTPLX is already running with PID ${pm2Status.pid}`, { status: 409 });+ }++ const endpoint = `http://${host}:${port}/v1`;+ if (await probeEndpoint(endpoint)) {+ throw new ServerError(`Port ${port} is already in use by an active server at ${endpoint}`, { status: 409 });+ }+ if (await isPortInUse(port)) {+ throw new ServerError(+ `Port ${port} is already in use on ${host}. Point MTPLX at a different port before starting it.`,+ { status: 409, code: 'MTPLX_PORT_IN_USE' }+ );+ }++ logs.reset();+ lastExitError = null;++ const resolved = await resolveStartModel(requestedModel, emit);+ if (resolved.error) throw new ServerError(resolved.error, { status: 400, code: 'MTPLX_NO_CACHED_MODEL' });+ const model = resolved.model;+ if (model) emit(`Serving the cached MTPLX model ${model}.`);++ // `mtplx start` is interactive (it prompts for a model); `serve` is the+ // API-only server, which is the half PortOS talks to. The daemon must bind+ // where the PROVIDER points — a user who moved MTPLX to 8010 would otherwise+ // get a second server on 8000 that nothing talks to.+ const args = ['serve', '--port', String(port), ...(model ? ['--model', model] : [])];+ currentConfig = { host, port, model };+ appendLog(`Starting: mtplx ${args.join(' ')}`);++ // Delete any stale PM2 entry so our own previous instance doesn't count as a collision.+ await execPm2(['delete', MTPLX_APP]).catch(() => {});+ clearJlistCache();++ console.log(`🚄 MTPLX starting on ${host}:${port}${model ? ` (model ${model})` : ' (MTPLX default model)'}`);+ await execPm2([+ 'start', binaryPath,+ '--name', MTPLX_APP,+ '--interpreter', 'none',+ '--no-autorestart',+ '--',+ ...args,+ ]);+ clearJlistCache();++ const deadline = Date.now() + (Number.isFinite(waitMs) ? waitMs : startupWaitMs);+ let online = false;+ let currentProc = null;+ while (Date.now() < deadline) {+ await sleep(STARTUP_POLL_MS);+ clearJlistCache();+ currentProc = await getAppStatusStrict(MTPLX_APP);+ if (currentProc && ['errored', 'stopped', 'not_found'].includes(currentProc.status)) break;+ online = await probeEndpoint(endpoint);+ if (online) break;+ }++ if (currentProc && ['errored', 'stopped', 'not_found'].includes(currentProc.status)) {+ const pm2Logs = await execPm2(['logs', MTPLX_APP, '--nostream', '--lines', '15']).catch(() => null);+ const lines = `${pm2Logs?.stderr || pm2Logs?.stdout || ''}`.split('\n').map((l) => l.trimEnd()).filter(Boolean);+ for (const line of lines) appendLog(line);+ const tail = (lines.length ? lines : logs.snapshot()).slice(-4).join(' | ');++ lastExitError = `PM2 status: ${currentProc.status}`;+ await execPm2(['delete', MTPLX_APP]).catch(() => {});+ clearJlistCache();+ currentConfig = null;+ throw new ServerError(+ `MTPLX exited immediately (${lastExitError}).${tail ? ` Last output: ${tail}` : ''}`,+ { status: 500, code: 'MTPLX_EXITED' }+ );+ }++ const finalProc = await getAppStatusStrict(MTPLX_APP);+ return {+ success: true,+ running: true,+ managed: true,+ pid: finalProc?.pid || null,+ endpoint,+ online,+ config: currentConfig,+ };+}++/** Stop the managed MTPLX process. */+export async function stopMtplxServer() {+ const pm2Status = await getAppStatusStrict(MTPLX_APP);+ const isManaged = Boolean(pm2Status && pm2Status.status === 'online');++ if (!isManaged) {+ const endpoint = endpointFor(currentConfig);+ if (await probeEndpoint(endpoint)) {+ return {+ success: false,+ message: `An external process is listening on ${endpoint}. It was not started by PortOS and cannot be stopped here.`,+ };+ }+ return { success: true, message: 'MTPLX is not running' };+ }++ appendLog(`Stopping ${MTPLX_APP}`);+ await execPm2(['delete', MTPLX_APP]).catch((err) => {+ throw new ServerError(`Failed to stop MTPLX: ${err.message}`, { status: 500 });+ });+ clearJlistCache();+ currentConfig = null;+ return { success: true, message: 'MTPLX stopped' };+}++/** Clears in-memory state (used by test suites). */+export function _resetMtplxServerStateForTests({ startupWait } = {}) {+ currentConfig = null;+ logs.reset();+ lastExitError = null;+ // Restored to the production budget unless a suite asks for a shorter one.+ startupWaitMs = Number.isFinite(startupWait) ? startupWait : 8_000;+}diff --git a/server/services/mtplxServerManager.test.js b/server/services/mtplxServerManager.test.jsnew file mode 100644index 0000000000..7670622cf6--- /dev/null+++ b/server/services/mtplxServerManager.test.js@@ -0,0 +1,240 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ getMtplxServerStatus,+ startMtplxServer,+ stopMtplxServer,+ installMtplx,+ _resetMtplxServerStateForTests,+ MTPLX_APP,+} from './mtplxServerManager.js';+import * as processEnv from '../lib/processEnv.js';+import * as platform from '../lib/platform.js';+import * as openAiModelsProbe from '../lib/openAiModelsProbe.js';+import * as mtplxModels from '../lib/mtplxModels.js';+import * as pm2Module from './pm2.js';+import * as commandExistsModule from '../lib/commandExists.js';+import * as streamingSpawn from '../lib/streamingSpawn.js';++const BINARY = '/opt/homebrew/bin/mtplx';+const cachedModel = (repoId, extra = {}) => ({ repo_id: repoId, validation: { ok: true }, ...extra });++describe('mtplxServerManager', () => {+ let pm2State = null;+ let execPm2Calls = [];++ beforeEach(() => {+ // A start that never answers on its port is the NORMAL path here (the probe+ // is pinned unreachable) — shorten the beat so the suite doesn't sit+ // through the production budget on every lifecycle test.+ _resetMtplxServerStateForTests({ startupWait: 50 });+ vi.restoreAllMocks();+ pm2State = null;+ execPm2Calls = [];++ // The host may genuinely be running MTPLX (or anything else) on :8000 — pin+ // both probes so a developer machine's real listeners can't decide these.+ vi.spyOn(platform, 'isPortInUse').mockResolvedValue(false);+ vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: false });+ vi.spyOn(platform, 'isAppleSilicon').mockReturnValue(true);+ // The dump is a real file on the developer's machine; pin it so the+ // startsAtBoot assertions are about this code, not their PM2 state.+ vi.spyOn(pm2Module, 'getSavedProcessNames').mockResolvedValue([]);+ vi.spyOn(mtplxModels, 'listMtplxCachedModels').mockResolvedValue({ models: [cachedModel('Example/Qwen-MTP')], error: null });++ vi.spyOn(pm2Module, 'execPm2').mockImplementation(async (args) => {+ execPm2Calls.push(args);+ if (args[0] === 'start') {+ const nameIdx = args.indexOf('--name');+ const dashIdx = args.indexOf('--');+ pm2State = {+ name: nameIdx !== -1 ? args[nameIdx + 1] : args[1],+ status: 'online',+ pid: 4242,+ args: dashIdx !== -1 ? args.slice(dashIdx + 1) : [],+ };+ }+ if (args[0] === 'delete') pm2State = null;+ return { stdout: '', stderr: '' };+ });+ vi.spyOn(pm2Module, 'getAppStatusStrict').mockImplementation(async (name) => (+ pm2State && pm2State.name === name ? pm2State : { name, status: 'not_found', pm2_env: null }+ ));+ vi.spyOn(pm2Module, 'clearJlistCache').mockImplementation(() => {});+ });++ afterEach(() => {+ _resetMtplxServerStateForTests();+ vi.restoreAllMocks();+ });++ describe('getMtplxServerStatus', () => {+ it('reports not installed when the binary is not on PATH', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(null);+ const status = await getMtplxServerStatus();+ expect(status.installed).toBe(false);+ expect(status.running).toBe(false);+ expect(status.managed).toBe(false);+ // A missing binary means the cache was never queried, so `cachedModels`+ // must not read as "queried and empty" plus a phantom error.+ expect(status.cacheError).toBeNull();+ });++ it('surfaces the cached checkpoints an installed MTPLX can be started on', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ const status = await getMtplxServerStatus();+ expect(status.installed).toBe(true);+ expect(status.cachedModels).toEqual(['Example/Qwen-MTP']);+ expect(status.endpoint).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/v1$/);+ });++ it('reports the platform gate only when nothing is installed here', async () => {+ vi.spyOn(platform, 'isAppleSilicon').mockReturnValue(false);+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(null);+ expect((await getMtplxServerStatus()).supported).toBe(false);++ // A binary on PATH is proof this host runs it — "macOS only" would be a+ // false report about an install the user can see.+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ const installed = await getMtplxServerStatus();+ expect(installed.supported).toBe(true);+ expect(installed.unsupportedReason).toBeNull();+ });++ it('flags the process as boot-persisted only when the PM2 dump names it', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ expect((await getMtplxServerStatus()).runAtStartup).toBe(false);++ vi.spyOn(pm2Module, 'getSavedProcessNames').mockResolvedValue([MTPLX_APP]);+ expect((await getMtplxServerStatus()).runAtStartup).toBe(true);++ // An unreadable dump is NOT "no" — it has to stay distinguishable so the+ // UI can say "unknown" instead of "won't come back after a reboot".+ vi.spyOn(pm2Module, 'getSavedProcessNames').mockResolvedValue(null);+ expect((await getMtplxServerStatus()).runAtStartup).toBeNull();+ });+ });++ describe('startMtplxServer', () => {+ beforeEach(() => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ });++ it('starts `mtplx serve` under PM2 on a cached checkpoint', async () => {+ const result = await startMtplxServer();+ expect(result.success).toBe(true);+ expect(result.managed).toBe(true);++ const start = execPm2Calls.find((args) => args[0] === 'start');+ expect(start).toContain('--name');+ expect(start[start.indexOf('--name') + 1]).toBe(MTPLX_APP);+ const launch = start.slice(start.indexOf('--') + 1);+ // `serve` (API-only), never `start` — which is interactive and prompts.+ expect(launch[0]).toBe('serve');+ expect(launch).toContain('--model');+ expect(launch[launch.indexOf('--model') + 1]).toBe('Example/Qwen-MTP');+ });++ it('binds the port the caller asked for, so the provider endpoint matches', async () => {+ const result = await startMtplxServer({ port: 8010 });+ expect(result.endpoint).toBe('http://127.0.0.1:8010/v1');+ const launch = execPm2Calls.find((a) => a[0] === 'start');+ expect(launch[launch.indexOf('--port') + 1]).toBe('8010');+ });++ it('refuses with the `mtplx pull` 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/);+ expect(execPm2Calls.some((args) => args[0] === 'start')).toBe(false);+ });++ it('falls through to MTPLX\'s own default when the cache could not be READ', async () => {+ // `models: null` is "could not read", which must not block a start that+ // may well work — unlike `[]`, which means "read, and empty".+ vi.spyOn(mtplxModels, 'listMtplxCachedModels').mockResolvedValue({ models: null, error: 'mtplx models timed out' });+ const result = await startMtplxServer();+ expect(result.success).toBe(true);+ const launch = execPm2Calls.find((a) => a[0] === 'start');+ expect(launch).not.toContain('--model');+ });++ it('reports what a server that died on startup printed', async () => {+ // PM2 leaving `online` is the signal; its log tail is what turns "exited"+ // into something the user can act on.+ vi.spyOn(pm2Module, 'execPm2').mockImplementation(async (args) => {+ execPm2Calls.push(args);+ if (args[0] === 'start') {+ pm2State = { name: MTPLX_APP, status: 'errored', pid: null, args: [] };+ }+ if (args[0] === 'delete') pm2State = null;+ if (args[0] === 'logs') return { stdout: '', stderr: 'error: model is not available locally' };+ return { stdout: '', stderr: '' };+ });+ await expect(startMtplxServer()).rejects.toThrow(/model is not available locally/);+ // The failed entry is cleaned up so the next start isn't a name collision.+ expect(pm2State).toBeNull();+ });++ it('refuses when the binary is not installed', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(null);+ await expect(startMtplxServer()).rejects.toThrow(/not found on PATH/);+ });++ it('refuses rather than launching a second copy onto a bound port', async () => {+ vi.spyOn(platform, 'isPortInUse').mockResolvedValue(true);+ await expect(startMtplxServer()).rejects.toThrow(/already in use/);+ });+ });++ describe('installMtplx', () => {+ beforeEach(() => {+ vi.spyOn(streamingSpawn, 'runStreamingCommand').mockResolvedValue({ success: true });+ });++ it('installs from upstream\'s Homebrew tap, never the privileged fan-control helper', async () => {+ vi.spyOn(commandExistsModule, 'commandExists').mockResolvedValue(true);+ const result = await installMtplx();+ expect(result.success).toBe(true);+ const [cmd, args] = streamingSpawn.runStreamingCommand.mock.calls[0];+ expect(cmd).toBe('brew');+ expect(args).toEqual(['install', 'youssofal/mtplx/mtplx']);+ // `mtplx max --install` is upstream's one privileged path (a sudo fan+ // controller). It stays an explicit operator action outside PortOS.+ expect(streamingSpawn.runStreamingCommand.mock.calls.flatMap(([, a]) => a)).not.toContain('max');+ });++ it('falls back to pip on a host without Homebrew', async () => {+ vi.spyOn(commandExistsModule, 'commandExists').mockImplementation(async (cmd) => cmd !== 'brew');+ await installMtplx();+ expect(streamingSpawn.runStreamingCommand.mock.calls[0][0]).toBe('python3');+ });++ it('refuses on a host that cannot run MLX at all', async () => {+ vi.spyOn(platform, 'isAppleSilicon').mockReturnValue(false);+ await expect(installMtplx()).rejects.toThrow(/macOS with Apple Silicon/);+ expect(streamingSpawn.runStreamingCommand).not.toHaveBeenCalled();+ });+ });++ describe('stopMtplxServer', () => {+ it('deletes the PM2 process it manages', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ await startMtplxServer();+ const result = await stopMtplxServer();+ expect(result.success).toBe(true);+ expect(pm2State).toBeNull();+ });++ it('will not claim to stop a server PortOS did not start', async () => {+ vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: true });+ const result = await stopMtplxServer();+ expect(result.success).toBe(false);+ expect(result.message).toMatch(/external process/i);+ });++ it('is a no-op when nothing is running', async () => {+ const result = await stopMtplxServer();+ expect(result.success).toBe(true);+ expect(result.message).toMatch(/not running/i);+ });+ });+});diff --git a/server/services/pm2.js b/server/services/pm2.jsindex 840aacf81a..cc32994ab0 100644--- a/server/services/pm2.js+++ b/server/services/pm2.js@@ -4,7 +4,8 @@ import { existsSync } from 'fs';import { writeFile, unlink } from 'fs/promises';import { join, dirname } from 'path';import { createRequire } from 'module';-import { extractJSONArray, safeJSONParse } from '../lib/fileUtils.js';+import { homedir } from 'os';+import { extractJSONArray, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';import { parseCommandArgs } from '../lib/commandSecurity.js';const IS_WIN = process.platform === 'win32';@@ -647,6 +648,48 @@ function spawnPm2StartEcosystem(cwd, ecosystemFile, processNames, pm2Home) {});}+/**+ * Persist the CURRENT PM2 process list to PM2's dump file (`pm2 save`).+ *+ * This is the half of "start at boot" PortOS can own. `pm2 startup` writes a+ * system init/launchd unit and is deliberately blocked (see+ * `PM2_BLOCKED_SUBCOMMANDS` in `lib/commandSecurity.js`) — it is a one-time,+ * privileged, machine-level decision the operator makes in a terminal. `pm2+ * save` only rewrites `$PM2_HOME/dump.pm2`, which that unit resurrects, so once+ * the operator has run `pm2 startup` once, saving here is what makes a+ * newly-started daemon (llama-server, MTPLX) come back after a reboot.+ *+ * The dump is process-list wide by design: it snapshots everything currently+ * running, which is exactly what a resurrect needs.+ *+ * @param {string|null} [pm2Home=null]+ */+export async function saveProcessList(pm2Home = null) {+ await execPm2(['save'], { env: buildEnv(pm2Home) });+ return { success: true };+}++/**+ * The app names in PM2's saved dump — i.e. what `pm2 resurrect` (and therefore+ * a boot-time `pm2 startup` unit) would bring back.+ *+ * Returns `null` when the dump could not be READ (absent, unreadable, not JSON)+ * — deliberately NOT the same value as `[]` ("read, and it saves nothing"), so a+ * caller can say "unknown" instead of reporting a daemon as not-persisted when+ * PortOS simply could not tell.+ *+ * @param {string|null} [pm2Home=null]+ * @returns {Promise<string[]|null>}+ */+export async function getSavedProcessNames(pm2Home = null) {+ const home = pm2Home || process.env.PM2_HOME || join(homedir(), '.pm2');+ const raw = await tryReadFile(join(home, 'dump.pm2'));+ if (raw === null) return null;+ const parsed = safeJSONParse(raw, null, { allowArray: true });+ if (!Array.isArray(parsed)) return null;+ return parsed.map((app) => app?.name).filter((name) => typeof name === 'string');+}+/*** Start app(s) using ecosystem.config.cjs/js file* This properly uses all env vars, scripts, args defined in the configdiff --git a/server/services/pm2.savedProcesses.test.js b/server/services/pm2.savedProcesses.test.jsnew file mode 100644index 0000000000..2760bdebcc--- /dev/null+++ b/server/services/pm2.savedProcesses.test.js@@ -0,0 +1,55 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { mkdtemp, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';++// pm2.js imports the `pm2` package at module load (no daemon connection until a+// call is made). Mocked to keep the import side-effect-free in CI.+vi.mock('pm2', () => ({ default: { connect: vi.fn(), list: vi.fn(), disconnect: vi.fn() } }));++import { getSavedProcessNames } from './pm2.js';++/**+ * `getSavedProcessNames` reads `$PM2_HOME/dump.pm2` — the list a boot-time+ * `pm2 resurrect` replays. The LLMs page shows it as "starts at boot" per+ * PM2-managed local runtime server, so absent-vs-empty has to stay legible: an+ * unreadable dump is "unknown", never "this daemon won't come back".+ */+describe('getSavedProcessNames', () => {+ let home;++ beforeEach(async () => {+ home = await mkdtemp(join(tmpdir(), 'portos-pm2-home-'));+ });++ afterEach(async () => {+ await rm(home, { recursive: true, force: true });+ });++ it('lists the app names in the saved dump', async () => {+ await writeFile(join(home, 'dump.pm2'), JSON.stringify([+ { name: 'portos-server' },+ { name: 'portos-llama-server' },+ { name: 'portos-mtplx' },+ ]));+ expect(await getSavedProcessNames(home)).toEqual(['portos-server', 'portos-llama-server', 'portos-mtplx']);+ });++ it('reports an EMPTY saved list as [] — read fine, saves nothing', async () => {+ await writeFile(join(home, 'dump.pm2'), '[]');+ expect(await getSavedProcessNames(home)).toEqual([]);+ });++ it('returns null when the dump is absent or unreadable', async () => {+ // Never `pm2 save`d on this machine.+ expect(await getSavedProcessNames(home)).toBeNull();+ // Truncated / not the array PM2 writes.+ await writeFile(join(home, 'dump.pm2'), '{"not":"an array"');+ expect(await getSavedProcessNames(home)).toBeNull();+ });++ it('skips entries with no usable name rather than emitting undefined', async () => {+ await writeFile(join(home, 'dump.pm2'), JSON.stringify([{ name: 'portos-mtplx' }, {}, { name: 42 }]));+ expect(await getSavedProcessNames(home)).toEqual(['portos-mtplx']);+ });+});