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
feat(issue-4863): release model-server memory when nothing is using it
Adam Eivy453de9227c7f
diff --git a/client/src/components/settings/LocalLlmTab.jsx b/client/src/components/settings/LocalLlmTab.jsxindex e25bf794a8..10ae6d561e 100644--- a/client/src/components/settings/LocalLlmTab.jsx+++ b/client/src/components/settings/LocalLlmTab.jsx@@ -11,7 +11,7 @@ import {getLocalLlmStatus, getLocalLlmCatalog, getLocalLlmHuggingFaceSearch, installLocalLlmModel,deleteLocalLlmModel, switchLocalLlmBackend, migrateLocalLlmBackend, installLocalLlmBackend, upgradeLocalLlmBackend, controlOllamaService,installAudioModel, patchSettingsSlice, getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer,- downloadSpecDecodeModel, controlLmStudioService, getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx,+ downloadSpecDecodeModel, controlLmStudioService, getMtplxServerStatus, stopMtplxServer, installMtplx,searchMtplxModels, pullMtplxModel, removeMtplxModel,saveRuntimeStartupList} from '../../services/api';@@ -634,15 +634,24 @@ export function LocalLlmTab() {() => 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')+ // MTPLX has no Start action: the first PortOS request routed to it starts it.+ // What the card saves is the launch line that on-demand start will replay.+ const saveMtplxLaunch = (launch) => runAction(+ 'runtime-save-mtplx-launch',+ () => patchSettingsSlice('localLlm.mtplx', { launch }),+ 'Saved — MTPLX will start on these options when a request needs it').then(loadMtplxStatus);++ // The idle window is a plain settings write for both daemons; only what+ // happens when it elapses differs (llama.cpp unloads in place on its next+ // start, MTPLX is stopped and lazily restarted).+ const saveIdleWindow = (runtime, minutes) => runAction(+ `runtime-idle-${runtime}`,+ () => patchSettingsSlice(`localLlm.${runtime}`, { idleMinutes: minutes }),+ minutes === 0+ ? `${runtime === 'llama' ? 'llama.cpp' : 'MTPLX'} will stay loaded while idle`+ : `${runtime === 'llama' ? 'llama.cpp' : 'MTPLX'} releases its model after ${minutes} idle minute${minutes === 1 ? '' : 's'}`+ ).then(runtime === 'llama' ? loadLlamaStatus : loadMtplxStatus);const runtimeStopMtplx = () => runAction('runtime-stop-mtplx',() => stopMtplxServer(),@@ -1045,9 +1054,9 @@ export function LocalLlmTab() {onConfigureLlama={() => scrollTo(llamaSectionRef)}onConfigureMtplx={() => scrollTo(mtplxSectionRef)}onInstallMtplx={runtimeInstallMtplx}- onStartMtplx={runtimeStartMtplx}onStopMtplx={runtimeStopMtplx}onSaveStartup={saveRuntimeStartup}+ onSaveIdleWindow={saveIdleWindow}/>{/* Backends — model catalog, default marker, cross-backend import */}@@ -1162,7 +1171,7 @@ export function LocalLlmTab() {busy={busy}actionInProgress={actionInProgress}onRefresh={loadMtplxStatus}- onStart={runtimeStartMtplx}+ onSaveLaunch={saveMtplxLaunch}onStop={runtimeStopMtplx}onInstall={runtimeInstallMtplx}onSearchModels={mtplxSearch}diff --git a/client/src/components/settings/LocalLlmTab.test.jsx b/client/src/components/settings/LocalLlmTab.test.jsxindex fd64c3e1f6..93e1163e68 100644--- a/client/src/components/settings/LocalLlmTab.test.jsx+++ b/client/src/components/settings/LocalLlmTab.test.jsx@@ -118,19 +118,34 @@ describe('LocalLlmTab runtime servers', () => {}});- it('starts MTPLX from that surface', async () => {- const { getMtplxServerStatus, startMtplxServer } = await import('../../services/api');+ // MTPLX starts on demand — the first request routed to it brings it up — so+ // this surface offers Install and Configure, never Start.+ it('offers no MTPLX Start on that surface', async () => {+ const { getMtplxServerStatus } = 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());+ expect(within(mtplxRow).queryByRole('button', { name: /^Start/ })).toBeNull();+ expect(within(mtplxRow).getByText(/Starts on demand/)).toBeInTheDocument();+ });++ it('saves an idle window through the settings slice for that runtime', async () => {+ const { getLlamaServerStatus, patchSettingsSlice } = await import('../../services/api');+ getLlamaServerStatus.mockResolvedValue({ installed: true, running: true, idleMinutes: 0, config: {} });++ await renderTab();+ const card = screen.getByRole('heading', { name: 'Local Runtime Servers' }).closest('div.bg-port-card');+ const llamaRow = within(card).getByText('llama.cpp').closest('div.flex.flex-col');+ const field = within(llamaRow).getByLabelText('Idle release');+ fireEvent.change(field, { target: { value: '30' } });+ fireEvent.blur(field);++ await waitFor(() => expect(patchSettingsSlice).toHaveBeenCalledWith('localLlm.llama', { idleMinutes: 30 }));});it('reports a failed checkpoint download as one error, not an empty success', async () => {diff --git a/client/src/components/settings/MtplxServerCard.jsx b/client/src/components/settings/MtplxServerCard.jsxindex 617e037332..0ff03c2f54 100644--- a/client/src/components/settings/MtplxServerCard.jsx+++ b/client/src/components/settings/MtplxServerCard.jsx@@ -1,6 +1,6 @@import { useState } from 'react';import { Link } from 'react-router';-import { Gauge, RefreshCw, ExternalLink, Play, Square, Download, Terminal } from 'lucide-react';+import { Gauge, RefreshCw, ExternalLink, Save, Square, Download, Terminal } from 'lucide-react';import BrailleSpinner from '../BrailleSpinner';import MtplxCheckpoints from './MtplxCheckpoints.jsx';@@ -24,7 +24,7 @@ export default function MtplxServerCard({busy,actionInProgress,onRefresh,- onStart,+ onSaveLaunch,onStop,onInstall,onSearchModels,@@ -122,7 +122,7 @@ export default function MtplxServerCard({<div className="bg-port-bg border border-port-border rounded-lg p-3 space-y-3">{emptyCache ? (<p className="text-xs text-port-warning">- MTPLX's model cache is empty, so its server exits before it binds a port. Download a checkpoint below, then start it.+ MTPLX's model cache is empty, so its server exits before it binds a port. Download a checkpoint below — the first request that needs MTPLX will start it on one.</p>) : (<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">@@ -153,16 +153,22 @@ export default function MtplxServerCard({</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>+ <p className="text-xs text-gray-500">Couldn't read MTPLX's model cache ({status.cacheError}) — an on-demand start will fall through to MTPLX's own default checkpoint.</p>)}+ <p className="text-[11px] text-gray-500">+ MTPLX starts on demand — the first PortOS request routed to it brings it up on these+ options, and its idle window (set under Local Runtime Servers) stops it again to release+ the checkpoint. There is no Start button because a manually-started server would only pin+ those gigabytes ahead of a request that may never come.+ </p><button- onClick={() => onStart({ ...(model ? { model } : {}), ...(port ? { port: Number(port) } : {}) })}+ onClick={() => onSaveLaunch({ model: model || null, ...(port ? { port: Number(port) } : {}) })}disabled={busy || emptyCache}className={`${btnClass} bg-port-accent/20 hover:bg-port-accent/30 text-port-accent`}- title={emptyCache ? 'Download an MTP checkpoint below first — a start never fetches weights' : 'Start `mtplx serve` under PM2'}+ title={emptyCache ? 'Download an MTP checkpoint below first — a start never fetches weights' : 'Remember these options for the next on-demand start'}>- {actionInProgress === 'runtime-start-mtplx' ? <BrailleSpinner /> : <Play size={13} />}- Start MTPLX+ {actionInProgress === 'runtime-save-mtplx-launch' ? <BrailleSpinner /> : <Save size={13} />}+ Save configuration</button></div>)}diff --git a/client/src/components/settings/MtplxServerCard.test.jsx b/client/src/components/settings/MtplxServerCard.test.jsxindex 929c708eb3..290e8d78c2 100644--- a/client/src/components/settings/MtplxServerCard.test.jsx+++ b/client/src/components/settings/MtplxServerCard.test.jsx@@ -6,7 +6,7 @@ import MtplxServerCard from './MtplxServerCard.jsx';const renderCard = async (status, props = {}) => {const handlers = {onRefresh: vi.fn(),- onStart: vi.fn(),+ onSaveLaunch: vi.fn(),onStop: vi.fn(),onInstall: vi.fn(),// The checkpoint manager loads upstream's default listing on mount.@@ -26,7 +26,10 @@ const renderCard = async (status, props = {}) => {};describe('MtplxServerCard', () => {- it('starts on the cached checkpoint and port the user picked', async () => {+ // MTPLX has no Start button: the first PortOS request routed to it starts it.+ // What this card saves is the launch line that on-demand start replays, so the+ // user's checkpoint choice survives a stop/start cycle they never see.+ it('saves the cached checkpoint and port the user picked', async () => {const handlers = await renderCard({installed: true,running: false,@@ -37,24 +40,27 @@ describe('MtplxServerCard', () => {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/ }));+ fireEvent.click(screen.getByRole('button', { name: /Save configuration/ }));- expect(handlers.onStart).toHaveBeenCalledWith({ model: 'Example/Other-MTP', port: 8010 });+ expect(handlers.onSaveLaunch).toHaveBeenCalledWith({ model: 'Example/Other-MTP', port: 8010 });});- it('omits an untouched field so PortOS picks the cache default and the shipped port', async () => {+ // An untouched port stays off the saved config so a lazy start falls through+ // to the shipped default; an untouched checkpoint is saved as an explicit+ // `null`, which is what CLEARS a previously-saved pick back to "Auto".+ it('omits an untouched port and clears an untouched checkpoint', async () => {const handlers = await renderCard({ installed: true, running: false, supported: true, cachedModels: ['Example/Qwen-MTP'] });- fireEvent.click(screen.getByRole('button', { name: /Start MTPLX/ }));- expect(handlers.onStart).toHaveBeenCalledWith({});+ fireEvent.click(screen.getByRole('button', { name: /Save configuration/ }));+ expect(handlers.onSaveLaunch).toHaveBeenCalledWith({ model: null });});- it('offers an in-app download instead of a start that cannot bind', async () => {+ it('offers an in-app download instead of a config that cannot bind', async () => {// No start downloads weights, and `mtplx serve` exits before it binds a port// on an empty cache — so the card offers the download itself rather than// naming a terminal command (PRD NR-9).const handlers = await renderCard({ installed: true, running: false, supported: true, cachedModels: [], cacheError: null });expect(screen.getByText(/model cache is empty/)).toBeInTheDocument();- expect(screen.getByRole('button', { name: /Start MTPLX/ })).toBeDisabled();+ expect(screen.getByRole('button', { name: /Save configuration/ })).toBeDisabled();expect(screen.queryByText(/in a terminal/i)).toBeNull();fireEvent.click(screen.getByRole('button', { name: /Download default checkpoint/ }));@@ -131,12 +137,18 @@ describe('MtplxServerCard', () => {expect(screen.queryByRole('button', { name: /^Download$/ })).toBeNull();});- it('still offers a start when the cache could not be READ — unreadable is not empty', async () => {+ it('still lets the config be saved when the cache could not be READ — unreadable is not empty', async () => {const handlers = await renderCard({ installed: true, running: false, supported: true, cachedModels: [], cacheError: '`mtplx models` timed out' });- const start = screen.getByRole('button', { name: /Start MTPLX/ });- expect(start).not.toBeDisabled();- fireEvent.click(start);- expect(handlers.onStart).toHaveBeenCalled();+ const save = screen.getByRole('button', { name: /Save configuration/ });+ expect(save).not.toBeDisabled();+ fireEvent.click(save);+ expect(handlers.onSaveLaunch).toHaveBeenCalled();+ });++ it('says MTPLX starts on demand, so the missing Start button reads as intent', async () => {+ await renderCard({ installed: true, running: false, supported: true, cachedModels: ['Example/Qwen-MTP'] });+ expect(screen.getByText(/starts on demand/i)).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: /^Start/ })).toBeNull();});it('will not offer to stop a server started outside PortOS', async () => {diff --git a/client/src/components/settings/RuntimeServersCard.jsx b/client/src/components/settings/RuntimeServersCard.jsxindex dcd2e56c5b..c0cad71868 100644--- a/client/src/components/settings/RuntimeServersCard.jsx+++ b/client/src/components/settings/RuntimeServersCard.jsx@@ -1,3 +1,4 @@+import { useEffect, useState } from 'react';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';@@ -88,6 +89,62 @@ function pm2Row({ id, label, icon, status, platformReason, onStart, onStop, onIn};}+/**+ * The per-daemon "release the model when nothing is using it" window.+ *+ * The two daemons honour this the same way from the user's side and in two very+ * different ways underneath, which is why the copy is per-row rather than shared:+ * llama.cpp unloads the checkpoint IN PLACE (`--sleep-idle-seconds`) and reloads+ * it on the next request without the process ever going away, while MTPLX — which+ * cannot unload anything but its retrieval models — is stopped outright and+ * started again by the next request that needs it.+ *+ * `0` means never release, which is what every install did before this setting+ * existed and is still the default.+ *+ * Committed on blur/Enter rather than per keystroke: each save is a settings+ * PATCH, and a three-digit window would otherwise write three times.+ */+function IdleWindowField({ id, value, onSave, busy, note }) {+ const [draft, setDraft] = useState(String(value ?? 0));+ // Re-sync when the saved value changes underneath (a refresh, another tab) —+ // but never while the field is being edited, which would fight the typist.+ useEffect(() => { setDraft(String(value ?? 0)); }, [value]);++ const commit = () => {+ const next = Number(draft);+ if (!Number.isFinite(next) || next < 0) { setDraft(String(value ?? 0)); return; }+ const clamped = Math.min(1440, Math.floor(next));+ setDraft(String(clamped));+ if (clamped !== (value ?? 0)) onSave(clamped);+ };++ const fieldId = `idle-window-${id}`;+ return (+ <div className="flex items-center gap-1.5">+ <label htmlFor={fieldId} className="text-xs text-gray-500 whitespace-nowrap">+ Idle release+ </label>+ <input+ id={fieldId}+ type="number"+ min="0"+ max="1440"+ value={draft}+ disabled={busy}+ onChange={(e) => setDraft(e.target.value)}+ onBlur={commit}+ onKeyDown={(e) => { if (e.key === 'Enter') e.currentTarget.blur(); }}+ className="w-16 px-1.5 py-1 text-xs bg-port-bg border border-port-border rounded text-white disabled:opacity-50"+ title={note}+ />+ <span className="text-xs text-gray-500 whitespace-nowrap" title={note}>+ min {Number(draft) === 0 ? '(never)' : ''}+ </span>+ </div>+ );+}+/*** Every action is invoked as `row.onX()`, never bound straight to `onClick` —* React would hand the handler its SyntheticEvent as the first argument, and a@@ -189,10 +246,14 @@ export default function RuntimeServersCard({onConfigureLlama,onConfigureMtplx,onInstallMtplx,- onStartMtplx,onStopMtplx,onSaveStartup,+ onSaveIdleWindow,}) {+ // Read off each daemon's own status payload — the same place `runAtStartup`+ // and Ollama's `disabled` come from — so there is no second settings fetch on+ // this tab to keep in sync.+ const idleWindows = { llama: llamaStatus?.idleMinutes ?? 0, mtplx: mtplxStatus?.idleMinutes ?? 0 };const ollamaService = status?.ollama?.service;const ollamaRunsAtStartup = Boolean(ollamaService?.runAtStartup);@@ -234,14 +295,17 @@ export default function RuntimeServersCard({status: mtplxStatus,platformReason: mtplxStatus?.supported === false ? 'macOS with Apple Silicon only' : null,onInstall: onInstallMtplx,- onStart: onStartMtplx,+ // No Start button by design. MTPLX is lazily started by the first PortOS+ // request routed to it and stopped again once its idle window elapses, so+ // a manual Start would only pin 20GB ahead of a request that may never+ // come. Install and Configure (download a checkpoint, set the launch+ // options) are the two things that still need a human.+ onStart: null,onStop: onStopMtplx,- // MTPLX weights are a multi-gigabyte download no Start button runs on its- // own. An installed MTPLX with an empty cache exits before it binds, so- // point at the card that downloads one rather than offering a Start that- // cannot work.- startBlockedReason: mtplxStatus?.installed && mtplxStatus?.cachedModels?.length === 0 && !mtplxStatus?.cacheError- ? 'No checkpoint yet — use Configure to download one'+ startBlockedReason: mtplxStatus?.installed && !mtplxStatus?.running+ ? (mtplxStatus?.cachedModels?.length === 0 && !mtplxStatus?.cacheError+ ? 'No checkpoint yet — use Configure to download one'+ : 'Starts on demand'): null,detail: mtplxStatus?.cachedModels?.length? `${mtplxStatus.cachedModels.length} checkpoint${mtplxStatus.cachedModels.length === 1 ? '' : 's'} cached`@@ -283,6 +347,17 @@ export default function RuntimeServersCard({{ollamaRunsAtStartup ? 'Disable at login' : 'Run at login'}</button>)}+ {(row.id === 'llama' || row.id === 'mtplx') && row.state !== 'unsupported' && row.state !== 'missing' && (+ <IdleWindowField+ id={row.id}+ value={idleWindows[row.id] ?? 0}+ busy={busy}+ onSave={(minutes) => onSaveIdleWindow?.(row.id, minutes)}+ note={row.id === 'llama'+ ? 'Minutes of PortOS inactivity after which llama.cpp unloads the model in place and reloads it on the next request. 0 = keep it resident. Applies from the next start.'+ : 'Minutes of PortOS inactivity after which MTPLX is stopped. The next PortOS request starts it again on the same checkpoint. 0 = keep it running.'}+ />+ )}{(row.id === 'llama' || row.id === 'mtplx') && row.state !== 'unsupported' && (<buttononClick={row.id === 'llama' ? onConfigureLlama : onConfigureMtplx}@@ -297,13 +372,17 @@ export default function RuntimeServersCard({))}</div>+ <p className="text-xs text-gray-500">+ <span className="text-gray-400">Idle release</span> puts a model down when nothing has used it for that many minutes — llama.cpp unloads it in place and reloads it on the next request; MTPLX is stopped and restarted on demand. <span className="text-gray-400">Only PortOS traffic counts.</span> A client hitting these ports directly is invisible to the timer and cannot lazily start a stopped server, so set <code className="text-gray-400">0</code> for a daemon you drive from outside PortOS.+ </p>+<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.+ 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. <span className="text-gray-400">MTPLX is deliberately left out of that snapshot</span>: it starts on demand when a request needs it, so resurrecting it at boot would only pin its checkpoint on an idle machine. 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.jsxindex 7bbd11ec10..f5590a5993 100644--- a/client/src/components/settings/RuntimeServersCard.test.jsx+++ b/client/src/components/settings/RuntimeServersCard.test.jsx@@ -18,7 +18,7 @@ const renderCard = (props = {}) => {onConfigureLlama: vi.fn(),onConfigureMtplx: vi.fn(),onInstallMtplx: vi.fn(),- onStartMtplx: vi.fn(),+ onSaveIdleWindow: vi.fn(),onStopMtplx: vi.fn(),onSaveStartup: vi.fn(),};@@ -83,33 +83,46 @@ describe('RuntimeServersCard', () => {expect(handlers.onConfigureLlama).toHaveBeenCalled();});- it('starts MTPLX in place once a checkpoint is cached', () => {- const handlers = renderCard({+ // MTPLX cannot unload its checkpoint in place, so PortOS stops the process+ // when it goes idle and the next request starts it again. A manual Start would+ // only pin 20GB ahead of a request that may never come.+ it('offers no MTPLX Start — it starts on demand', () => {+ 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();+ const mtplx = row('MTPLX');+ expect(within(mtplx).queryByRole('button', { name: /^Start/ })).toBeNull();+ expect(within(mtplx).getByText(/Starts on demand/)).toBeInTheDocument();+ });++ // llama.cpp keeps its Stop: it is started explicitly from the launcher, and+ // its idle release keeps the process up rather than removing it.+ it('still offers Stop for a running MTPLX', () => {+ const handlers = renderCard({+ mtplxStatus: { installed: true, running: true, managed: true, supported: true, cachedModels: ['Example/Qwen-MTP'] },+ });+ fireEvent.click(within(row('MTPLX')).getByRole('button', { name: /^Stop/ }));+ expect(handlers.onStopMtplx).toHaveBeenCalled();});it('invokes a row action with NO arguments — never React\'s click event', () => {- // MTPLX's start handler takes a launch config and the client JSON.stringify's- // it into the request body. Binding it straight to `onClick` handed it the- // SyntheticEvent instead, which throws on its circular DOM refs.+ // A handler bound straight to `onClick` is handed React's SyntheticEvent as+ // its first argument, which throws on its circular DOM refs the moment a+ // handler tries to serialize it into a request body.const handlers = renderCard({- mtplxStatus: { installed: true, running: false, supported: true, cachedModels: ['Example/Qwen-MTP'] },+ mtplxStatus: { installed: true, running: true, managed: true, supported: true, cachedModels: ['Example/Qwen-MTP'] },});- const mtplx = row('MTPLX');- fireEvent.click(within(mtplx).getByRole('button', { name: /^Start/ }));- expect(handlers.onStartMtplx).toHaveBeenCalledWith();+ fireEvent.click(within(row('MTPLX')).getByRole('button', { name: /^Stop/ }));+ expect(handlers.onStopMtplx).toHaveBeenCalledWith();fireEvent.click(within(row('Ollama')).getByRole('button', { name: /Install/ }));expect(handlers.onInstallBackend).toHaveBeenCalledWith('ollama');});- it('blocks the MTPLX Start and points at the in-app download when its cache is empty', () => {- // No Start button downloads weights, and `mtplx serve` exits before it binds- // on an empty cache — so offering Start would only produce a failure. The- // fix is the Configure card below, never a terminal command (PRD NR-9).+ it('points at the in-app download when the MTPLX cache is empty', () => {+ // Nothing downloads weights on its own, and `mtplx serve` exits before it+ // binds on an empty cache — so the row names the in-app fix (the Configure+ // card below) rather than a terminal command (PRD NR-9).renderCard({mtplxStatus: { installed: true, running: false, supported: true, cachedModels: [], cacheError: null },});@@ -152,4 +165,83 @@ describe('RuntimeServersCard', () => {expect(within(ollama).queryByRole('button', { name: /Install/ })).toBeNull();expect(within(ollama).getByRole('link', { name: /Download/ })).toHaveAttribute('href', 'https://ollama.com/download');});++ // ===========================================================================+ // IDLE RELEASE+ // ===========================================================================+ describe('idle release window', () => {+ const idleField = (label) => within(row(label)).getByLabelText('Idle release');++ it('shows the saved window for each managed daemon', () => {+ renderCard({+ llamaStatus: { installed: true, running: true, idleMinutes: 30 },+ mtplxStatus: { installed: true, running: true, supported: true, idleMinutes: 15 },+ });+ expect(idleField('llama.cpp')).toHaveValue(30);+ expect(idleField('MTPLX')).toHaveValue(15);+ });++ it('saves the window on blur, per runtime', () => {+ const handlers = renderCard({ llamaStatus: { installed: true, running: true, idleMinutes: 0 } });+ const field = idleField('llama.cpp');+ fireEvent.change(field, { target: { value: '45' } });+ fireEvent.blur(field);+ expect(handlers.onSaveIdleWindow).toHaveBeenCalledWith('llama', 45);+ });++ // 0 is a real choice, not a cleared field — it reproduces the always-on+ // behaviour every install had before this setting existed.+ it('saves an explicit 0 and labels it "never"', () => {+ const handlers = renderCard({ llamaStatus: { installed: true, running: true, idleMinutes: 30 } });+ const field = idleField('llama.cpp');+ fireEvent.change(field, { target: { value: '0' } });+ fireEvent.blur(field);+ expect(handlers.onSaveIdleWindow).toHaveBeenCalledWith('llama', 0);+ expect(within(row('llama.cpp')).getByText(/never/)).toBeInTheDocument();+ });++ it('does not re-save a value that did not change', () => {+ const handlers = renderCard({ llamaStatus: { installed: true, running: true, idleMinutes: 30 } });+ fireEvent.blur(idleField('llama.cpp'));+ expect(handlers.onSaveIdleWindow).not.toHaveBeenCalled();+ });++ it('reverts a nonsensical value instead of saving it', () => {+ const handlers = renderCard({ llamaStatus: { installed: true, running: true, idleMinutes: 30 } });+ const field = idleField('llama.cpp');+ fireEvent.change(field, { target: { value: '-5' } });+ fireEvent.blur(field);+ expect(handlers.onSaveIdleWindow).not.toHaveBeenCalled();+ expect(field).toHaveValue(30);+ });++ // A window longer than a day is indistinguishable from "never" and is far+ // likelier a units mix-up (seconds typed into a minutes field).+ it('clamps a window longer than a day', () => {+ const handlers = renderCard({ llamaStatus: { installed: true, running: true, idleMinutes: 0 } });+ const field = idleField('llama.cpp');+ fireEvent.change(field, { target: { value: '99999' } });+ fireEvent.blur(field);+ expect(handlers.onSaveIdleWindow).toHaveBeenCalledWith('llama', 1440);+ });++ it('offers no window for a runtime that is not installed', () => {+ renderCard({ llamaStatus: { installed: false, running: false } });+ expect(within(row('llama.cpp')).queryByLabelText('Idle release')).toBeNull();+ });++ // Ollama and LM Studio own their own lifecycles — PortOS has no process to+ // stop and no flag to pass, so offering the control would be a lie.+ it('offers no window for the runtimes PortOS does not manage as PM2 processes', () => {+ renderCard({});+ expect(within(row('Ollama')).queryByLabelText('Idle release')).toBeNull();+ expect(within(row('LM Studio')).queryByLabelText('Idle release')).toBeNull();+ });++ it('warns that only PortOS traffic counts', () => {+ renderCard({});+ expect(screen.getByText(/Only PortOS traffic counts/)).toBeInTheDocument();+ });+ });+});diff --git a/docs/features/mtplx.md b/docs/features/mtplx.mdindex d2f862de38..37a2746339 100644--- a/docs/features/mtplx.md+++ b/docs/features/mtplx.md@@ -31,10 +31,13 @@ valid CoS coding-agent runner.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+ and MTPLX, with an **Idle release** window per PM2-managed server and a**Save PM2 list for reboot** action (see [Startup at boot](#startup-at-boot)).+ MTPLX's row offers **Install**, **Configure** and **Stop** but deliberately no+ **Start** — see [Idle release and lazy start](#idle-release-and-lazy-start).- The **MTPLX** card below it picks *which* cached checkpoint and *which* port to- serve on, and shows the server's recent log lines.+ serve on, **saves that as the launch line an on-demand start replays**, 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,@@ -65,11 +68,12 @@ you are already on.`mtplx serve` exits before it binds a port on an empty cache, and the cardrefuses to start until something is cached — but the fix is a button, not aterminal.-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.+3. **Save configuration** on the MTPLX card, choosing a cached checkpoint and the+ port your provider points at. There is no Start button: the first PortOS+ request routed to MTPLX runs `mtplx serve` under PM2 on exactly those options+ and waits for it to answer. A cold MLX checkpoint takes a while to load, so+ that first request pays the load; the card's status shows the server once the+ endpoint answers.**From AI Providers** (one click, MTPLX's own default checkpoint):@@ -86,7 +90,7 @@ you are already on.verified checkpoint, a multi-gigabyte download) and then starts the server,with the download's progress streaming into the same modal. To use adifferent MTP checkpoint instead, search for and download it on the MTPLX- card in Models → LLMs, then click **Start MTPLX**.+ card in Models → LLMs, then **Save configuration** there.Then, either way:@@ -179,17 +183,51 @@ Two things worth knowing:`mtplx tune` — upstream's own depth auto-tuner, which writes a saved winner intoMTPLX's config — stays an explicit operator action outside PortOS.+## Idle release and lazy start++MTPLX holds its whole MLX checkpoint resident for as long as the process is up —+20GB is ordinary — and it has no way to put that down in place. Its+`--retrieval-idle-timeout` unloads *retrieval* models (embedding/rerank) only,+never the main checkpoint, and `mtplx settings set` covers live tunables like+depth, not residency. So the only lever is the process itself.++**Idle release.** Set a window in minutes on the MTPLX row under Local Runtime+Servers. When no PortOS request has been routed to MTPLX for that long, PortOS+stops `portos-mtplx` and the memory comes back. `0` (the default) means never —+exactly the behaviour every install had before this existed.++**Lazy start.** Because it can be stopped automatically, MTPLX has no Start+button: the next PortOS request routed to it starts it and waits for readiness.+It comes back on the launch line it last ran with, or — after a PortOS restart —+on the options saved from the MTPLX card.++**Only PortOS traffic counts.** A client hitting the MTPLX port directly is+invisible to the idle timer and cannot lazily start a stopped server. If you+drive MTPLX from outside PortOS, set the window to `0`.++**llama.cpp works differently.** `llama-server` carries its own+`--sleep-idle-seconds`, which unloads the checkpoint *in place* and reloads it on+the next request without the process going away, so PortOS passes that flag+rather than stopping it. Its Idle release field sets that flag, and it applies+from the next start (a launch flag, not a live setting). A llama.cpp build too+old to advertise the flag keeps starting normally — PortOS probes `--help` and+leaves it off, saying so in the server's log lines.+## 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:+`portos-llama-server` comes back after a reboot the same way every other PortOS+process does — through PM2's saved dump. **`portos-mtplx` deliberately does+not**: it starts on demand, so resurrecting it at boot would pin its checkpoint+on a machine nobody has asked anything of yet. **Save PM2 list for reboot**+filters it out of the dump after `pm2 save` writes it; the running process is+left alone, it just isn't in the list a reboot replays.1. Run `pm2 startup` **once** in a terminal and follow the privileged command itprints. PortOS deliberately never runs this: it writes a launchd/systemd unitand 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.+ Models → LLMs (a `pm2 save`, minus `portos-mtplx`). Each runtime the dump+ holds then shows a **starts at boot** pill — MTPLX never will.Ollama and LM Studio are not PM2 processes — they manage their ownlaunch-at-login (Ollama through its service manager, via the **Run at login**diff --git a/server/lib/README.md b/server/lib/README.mdindex 829a70019f..a6e44bf988 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -142,7 +142,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 model ids under the namespace the provider's marker selects: a local runtime (`ollama` / `mtplx` / `llama` / `vllm` / `sglang`, bare ids) or a hosted gateway from `providerGateways.js` (`vendor/model` ids kept whole). Fixes --model rejection. Also attaches the key for a key-bearing namespace, and pins `small_model` to the run model for a gateway so OpenCode's own side calls (titles, summarization) can't land on its built-in default — a billed model the operator never chose. || `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`. Optional `setupStateDetail` overrides `providerReadiness`'s per-state prose for a runtime whose local setup is not a model cache (vLLM's is a compose project). |-| `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. |+| `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. Also the shared **idle reaper**, for a daemon that cannot release its weights any other way: `registerIdleDaemon({name, getIdleMs, stop})` (seeds `lastUsedAt` to NOW, so a hand-started daemon gets a full window), `markDaemonUsed(name)` — call on real traffic, NEVER on a status poll — `daemonLastUsedAt(name)`, `idleWindowMs(minutes)` (minutes → ms; `0` = never, `null` = not configured, kept distinct), `reapIdleDaemons(now?)` → the names stopped, and `startIdleReaper({intervalMs?})` / `stopIdleReaper()` (ONE interval for all registrants, `unref`'d, idempotent). `mtplxServerManager` is the only registrant: llama.cpp releases its checkpoint in place via `--sleep-idle-seconds` and must NOT be stopped for it. 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`), and `vllmProjectSetupState(project)` → `ready`/`empty`/`unknown` for the readiness checklist. 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`. || `qwenAgentParsers.js` | The tool-call / reasoning parser flags a local runtime MUST carry to serve a Qwen3-family model to a coding agent — one table PortOS owns instead of three docs. `QWEN_AGENT_PARSERS` maps runtime → `{toolCallParser, reasoningParser, enableAutoToolChoice}` (vLLM `qwen3_xml` + `--enable-auto-tool-choice`, SGLang `qwen3_coder` + `--reasoning-parser qwen3`, llama both `null` — a positive "no such flag today", not a placeholder). `parserFlagsFor(runtime)` returns the argv fragment (always an array, so no caller type-checks) and `vllmExtraArgs()` its string form for the compose project's `.env` `EXTRA_ARGS`; an unknown runtime THROWS, because the failure it prevents is silent — a parser-less server answers fluently and returns tool markup as ordinary text with `tool_calls: null`, so the agent never touches a file. Spellings are empirical (`docs/research/2026-08-21-qwen38-rtx3090-vllm.md`, `…-sglang-qwen38-27b.md`); never auto-detect one from the chat template — that is how `hermes` got picked. Pure. |diff --git a/server/lib/aiProvider.js b/server/lib/aiProvider.jsindex 47a8e69be9..d44ab7cbba 100644--- a/server/lib/aiProvider.js+++ b/server/lib/aiProvider.js@@ -6,6 +6,7 @@import { getAllProviders } from '../services/providers.js';import { startAIOp } from '../services/aiStatusEvents.js';import { ensureProviderReady as ensureOllamaProviderReady, isOllamaProvider } from '../services/ollamaManager.js';+import { ensureMtplxProviderReady, isMtplxProvider } from '../services/mtplxServerManager.js';// localModelHealing is lazy-imported at its (rare, error-recovery) call site// below — a static import here pulls its notifications/providers deps (which// eagerly import fileUtils `PATHS`) into every aiProvider consumer's module@@ -276,6 +277,19 @@ export async function callProviderAISimple(provider, model, prompt, options = {}}}+ // The idle reaper may have stopped MTPLX to release its checkpoint. This is+ // the lazy half of that bargain — and the only place the idle clock is+ // refreshed, so a run that takes an hour still counts as use throughout.+ if (isMtplxProvider(provider)) {+ statusOp.update('provider:starting', 'Starting MTPLX if needed…', { providerId: provider.id });+ const ready = await ensureMtplxProviderReady(provider).catch((err) => ({ success: false, error: err.message }));+ if (!ready.success) {+ const error = `MTPLX is not running and PortOS could not start it: ${ready.error || 'unknown error'}`;+ statusOp.error(error);+ return { error };+ }+ }+const first = await postChatCompletion(provider, model, body, opts);if (!first.error) {statusOp.complete(`${doneLabel} done (${elapsedSec()}s)`, throughput(first.tokens));diff --git a/server/lib/managedDaemon.idle.test.js b/server/lib/managedDaemon.idle.test.jsnew file mode 100644index 0000000000..cba896399a--- /dev/null+++ b/server/lib/managedDaemon.idle.test.js@@ -0,0 +1,190 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ idleWindowMs,+ registerIdleDaemon,+ markDaemonUsed,+ daemonLastUsedAt,+ reapIdleDaemons,+ startIdleReaper,+ stopIdleReaper,+ _resetIdleDaemonsForTests,+} from './managedDaemon.js';++const MINUTE = 60_000;++describe('managedDaemon idle reaper', () => {+ beforeEach(() => {+ _resetIdleDaemonsForTests();+ vi.spyOn(console, 'log').mockImplementation(() => {});+ vi.spyOn(console, 'error').mockImplementation(() => {});+ });+ afterEach(() => {+ _resetIdleDaemonsForTests();+ vi.restoreAllMocks();+ });++ describe('idleWindowMs', () => {+ it('converts minutes to milliseconds', () => {+ expect(idleWindowMs(30)).toBe(30 * MINUTE);+ });++ // 0 is a real choice ("never stop"), not the absence of one — collapsing it+ // into null would make a stored 0 indistinguishable from an unset field.+ it('keeps 0 as 0 rather than folding it into null', () => {+ expect(idleWindowMs(0)).toBe(0);+ expect(idleWindowMs(null)).toBeNull();+ expect(idleWindowMs('not a number')).toBeNull();+ expect(idleWindowMs(-5)).toBeNull();+ });+ });++ it('stops a daemon whose idle window has elapsed', async () => {+ const stop = vi.fn().mockResolvedValue(undefined);+ registerIdleDaemon({ name: 'daemon-a', getIdleMs: () => 30 * MINUTE, stop });++ // 31 minutes after the last use.+ const stopped = await reapIdleDaemons(Date.now() + 31 * MINUTE);++ expect(stop).toHaveBeenCalledTimes(1);+ expect(stopped).toEqual(['daemon-a']);+ });++ it('leaves a daemon used inside the window alone', async () => {+ const stop = vi.fn().mockResolvedValue(undefined);+ registerIdleDaemon({ name: 'daemon-a', getIdleMs: () => 30 * MINUTE, stop });++ const stopped = await reapIdleDaemons(Date.now() + 29 * MINUTE);++ expect(stop).not.toHaveBeenCalled();+ expect(stopped).toEqual([]);+ });++ it('never stops a daemon whose window is 0', async () => {+ const stop = vi.fn().mockResolvedValue(undefined);+ registerIdleDaemon({ name: 'daemon-a', getIdleMs: () => 0, stop });++ // A year of idleness is still not enough when the user said "never".+ const stopped = await reapIdleDaemons(Date.now() + 525_600 * MINUTE);++ expect(stop).not.toHaveBeenCalled();+ expect(stopped).toEqual([]);+ });++ it('never stops a daemon with no configured window', async () => {+ const stop = vi.fn().mockResolvedValue(undefined);+ registerIdleDaemon({ name: 'daemon-a', getIdleMs: () => null, stop });++ expect(await reapIdleDaemons(Date.now() + 10_000 * MINUTE)).toEqual([]);+ expect(stop).not.toHaveBeenCalled();+ });++ // The acceptance criterion that makes the feature safe to leave on: a server+ // the user started thirty seconds ago must not be reaped because its+ // registration carried no use history.+ it('gives a freshly registered daemon a full window before it is eligible', async () => {+ const stop = vi.fn().mockResolvedValue(undefined);+ const now = Date.now();+ registerIdleDaemon({ name: 'daemon-a', getIdleMs: () => 30 * MINUTE, stop });++ expect(await reapIdleDaemons(now + 29 * MINUTE)).toEqual([]);+ expect(await reapIdleDaemons(now + 31 * MINUTE)).toEqual(['daemon-a']);+ });++ it('refreshes the clock on use', async () => {+ const stop = vi.fn().mockResolvedValue(undefined);+ registerIdleDaemon({ name: 'daemon-a', getIdleMs: () => 30 * MINUTE, stop });++ const before = daemonLastUsedAt('daemon-a');+ await new Promise((r) => setTimeout(r, 2));+ markDaemonUsed('daemon-a');++ expect(daemonLastUsedAt('daemon-a')).toBeGreaterThan(before);+ });++ it('ignores a mark for an unregistered daemon rather than throwing', () => {+ expect(() => markDaemonUsed('never-registered')).not.toThrow();+ expect(daemonLastUsedAt('never-registered')).toBeNull();+ });++ // A re-registration (a manager module reloaded under test, or re-imported)+ // must not reset a clock that is already ticking.+ it('preserves lastUsedAt across a re-registration', async () => {+ registerIdleDaemon({ name: 'daemon-a', getIdleMs: () => 30 * MINUTE, stop: vi.fn() });+ const first = daemonLastUsedAt('daemon-a');++ const stop = vi.fn().mockResolvedValue(undefined);+ registerIdleDaemon({ name: 'daemon-a', getIdleMs: () => 30 * MINUTE, stop });++ expect(daemonLastUsedAt('daemon-a')).toBe(first);+ });++ // A stop that fails leaves the daemon UP. Resetting its clock anyway would+ // retry every single beat forever; leaving the clock stale lets the next+ // sweep try again without pretending the stop worked.+ it('reports a failed stop and does not count it as stopped', async () => {+ const stop = vi.fn().mockRejectedValue(new Error('pm2 unreachable'));+ registerIdleDaemon({ name: 'daemon-a', getIdleMs: () => 30 * MINUTE, stop });++ const stopped = await reapIdleDaemons(Date.now() + 31 * MINUTE);++ expect(stopped).toEqual([]);+ expect(console.error).toHaveBeenCalledWith(expect.stringContaining('pm2 unreachable'));+ });++ it('keeps sweeping the other daemons after one throws', async () => {+ const failing = vi.fn().mockRejectedValue(new Error('boom'));+ const healthy = vi.fn().mockResolvedValue(undefined);+ registerIdleDaemon({ name: 'daemon-a', getIdleMs: () => 30 * MINUTE, stop: failing });+ registerIdleDaemon({ name: 'daemon-b', getIdleMs: () => 30 * MINUTE, stop: healthy });++ expect(await reapIdleDaemons(Date.now() + 31 * MINUTE)).toEqual(['daemon-b']);+ expect(healthy).toHaveBeenCalledTimes(1);+ });++ // The window is resolved per sweep so a settings change lands on the next+ // beat rather than at the next server restart.+ it('re-reads the window on every sweep', async () => {+ const stop = vi.fn().mockResolvedValue(undefined);+ let windowMs = 0;+ registerIdleDaemon({ name: 'daemon-a', getIdleMs: () => windowMs, stop });++ const now = Date.now();+ expect(await reapIdleDaemons(now + 60 * MINUTE)).toEqual([]);++ windowMs = 30 * MINUTE;+ expect(await reapIdleDaemons(now + 60 * MINUTE)).toEqual(['daemon-a']);+ });++ it('treats a window lookup that throws as "never stop"', async () => {+ const stop = vi.fn().mockResolvedValue(undefined);+ registerIdleDaemon({+ name: 'daemon-a',+ getIdleMs: () => Promise.reject(new Error('settings unreadable')),+ stop,+ });++ expect(await reapIdleDaemons(Date.now() + 10_000 * MINUTE)).toEqual([]);+ expect(stop).not.toHaveBeenCalled();+ });++ describe('startIdleReaper', () => {+ afterEach(() => stopIdleReaper());++ it('arms exactly one timer no matter how many times it is called', () => {+ const spy = vi.spyOn(global, 'setInterval');+ startIdleReaper({ intervalMs: 60_000 });+ startIdleReaper({ intervalMs: 60_000 });+ expect(spy).toHaveBeenCalledTimes(1);+ });++ it('stops sweeping once disarmed', async () => {+ const stop = vi.fn().mockResolvedValue(undefined);+ // Window 0 so a stray sweep can't stop it — this asserts the timer, not the policy.+ registerIdleDaemon({ name: 'daemon-a', getIdleMs: () => 0, stop });+ startIdleReaper({ intervalMs: 5 });+ stopIdleReaper();+ await new Promise((r) => setTimeout(r, 25));+ expect(stop).not.toHaveBeenCalled();+ });+ });+});diff --git a/server/lib/managedDaemon.js b/server/lib/managedDaemon.jsindex ab55c1dd71..04856b4023 100644--- a/server/lib/managedDaemon.js+++ b/server/lib/managedDaemon.js@@ -85,3 +85,171 @@ export function pm2ArgValue(args, flag) {const idx = list.indexOf(flag);return idx !== -1 && idx + 1 < list.length ? list[idx + 1] : null;}++// =============================================================================+// IDLE REAPER+// =============================================================================++/**+ * Shared "stop this daemon when nothing has used it for a while" mechanism.+ *+ * ONLY for a daemon that cannot release its weights any other way. `llama-server`+ * deliberately does NOT register here: it carries its own `--sleep-idle-seconds`,+ * which unloads the model in place and reloads it on the next request without the+ * process ever going away (see `llamaServerManager.js`). Stopping that process to+ * reclaim the same memory would trade a cheap internal reload for a full PM2+ * cold start, and lose the launch line with it. MTPLX has no such flag — its+ * `--retrieval-idle-timeout` unloads retrieval models only, never the main+ * checkpoint — so stopping the process is the only way to get its 20GB back, and+ * it is the one registrant.+ *+ * One `setInterval` for every registrant, not one per daemon: the beat is a+ * coarse poll against a timestamp, so N timers would buy nothing but N chances+ * to leak one.+ */++/** How often the reaper checks. Coarse on purpose — the windows are minutes. */+const IDLE_REAP_INTERVAL_MS = 60_000;++/** name → `{ getIdleMs, stop, lastUsedAt }`. */+const idleDaemons = new Map();+let reaperTimer = null;++/**+ * A user-supplied idle window in minutes, as milliseconds.+ *+ * `0` means "never stop" and is returned as `0`, NOT as null — it is a real+ * choice (today's always-on behaviour) and must survive a round-trip through+ * settings distinguishably from "no value stored". Anything unparseable or+ * negative is `null` = not configured, which the reaper also treats as never.+ *+ * @param {unknown} minutes+ * @returns {number|null}+ */+export function idleWindowMs(minutes) {+ // `Number(null)` and `Number('')` are both 0, which would make "nothing+ // stored" indistinguishable from the user explicitly choosing "never stop".+ // They mean the same thing to the reaper, but not to a caller reporting what+ // is configured — so absent stays null.+ if (minutes === null || minutes === undefined || minutes === '') return null;+ const n = Number(minutes);+ if (!Number.isFinite(n) || n < 0) return null;+ return Math.floor(n) * 60_000;+}++/**+ * Register a daemon the reaper may stop.+ *+ * `lastUsedAt` is seeded to NOW rather than to null, so a daemon that was just+ * started by hand — or one PortOS re-adopted after its own restart — gets a+ * full idle window before it is eligible. Seeding null and treating it as+ * "infinitely idle" would reap a server the user started seconds ago.+ *+ * Re-registering the same name refreshes the hooks and leaves `lastUsedAt`+ * alone, so a manager reloaded under test doesn't reset a live clock.+ *+ * @param {{name: string, getIdleMs: () => Promise<number|null>|number|null, stop: () => Promise<unknown>}} daemon+ * `getIdleMs` resolves the CURRENT configured window on every sweep (so a+ * settings change takes effect without a restart); `null`/`0` = never stop.+ */+export function registerIdleDaemon({ name, getIdleMs, stop }) {+ const existing = idleDaemons.get(name);+ idleDaemons.set(name, {+ getIdleMs,+ stop,+ lastUsedAt: existing?.lastUsedAt ?? Date.now(),+ });+}++/**+ * Record that something just used `name` — the signal the whole mechanism runs+ * on. Call it on real traffic (an inference request, a lazy start), never on a+ * status poll: a status card that refreshes every few seconds would otherwise+ * hold a 24GB checkpoint resident forever while nobody used it.+ *+ * A no-op for an unregistered name, so a call site doesn't have to know whether+ * this install registered that daemon.+ *+ * @param {string} name+ */+export function markDaemonUsed(name) {+ const entry = idleDaemons.get(name);+ if (entry) entry.lastUsedAt = Date.now();+}++/** The recorded last-use timestamp for `name`, or `null`. Exposed for status cards. */+export function daemonLastUsedAt(name) {+ return idleDaemons.get(name)?.lastUsedAt ?? null;+}++/**+ * One sweep: stop every registered daemon whose window has elapsed.+ *+ * Exported so a test can drive it directly instead of waiting on the timer, and+ * so a caller can force a sweep after a settings change.+ *+ * @param {number} [now]+ * @returns {Promise<string[]>} the names actually stopped+ */+export async function reapIdleDaemons(now = Date.now()) {+ const stopped = [];+ for (const [name, entry] of idleDaemons) {+ // Resolved per sweep, so lowering the window in Settings applies to the very+ // next beat rather than to the next server restart.+ const windowMs = await Promise.resolve(entry.getIdleMs()).catch(() => null);+ if (!windowMs || windowMs <= 0) continue;+ if (now - entry.lastUsedAt < windowMs) continue;++ const idleMin = Math.round((now - entry.lastUsedAt) / 60_000);+ console.log(`💤 Stopping ${name} — idle ${idleMin}m (window ${Math.round(windowMs / 60_000)}m)`);+ // `stop` reaches PM2 over a subprocess. A failure here must not kill the+ // interval that every other daemon's reaping depends on.+ const failed = await Promise.resolve(entry.stop()).then(() => null, (err) => err);+ if (failed) {+ console.error(`❌ Idle stop of ${name} failed: ${failed.message}`);+ continue;+ }+ // Only on success: a failed stop that left the daemon up would otherwise+ // retry every beat forever with the clock reset each time.+ entry.lastUsedAt = now;+ stopped.push(name);+ }+ return stopped;+}++/**+ * Arm the single reaper timer. Idempotent — a second call is a no-op rather than+ * a second interval.+ *+ * Boot-safe by construction: it arms a timer and reads timestamps. It makes no+ * AI provider call, which is what lets `server/index.js` start it unconditionally+ * under AGENTS.md's "No cold-bootstrap LLM calls" rule.+ *+ * @param {{intervalMs?: number}} [options]+ */+export function startIdleReaper({ intervalMs = IDLE_REAP_INTERVAL_MS } = {}) {+ if (reaperTimer) return;+ reaperTimer = setInterval(() => {+ // Outside the Express request lifecycle: an unhandled rejection here would+ // take the process down, so the sweep's own failures are swallowed after+ // logging (each daemon's stop failure is already reported individually).+ reapIdleDaemons().catch((err) => console.error(`❌ Idle reaper sweep failed: ${err.message}`));+ }, intervalMs);+ // Never hold the event loop open for this — a shutdown must not wait a minute+ // for a poll that has nothing to do.+ reaperTimer.unref?.();+ console.log(`💤 Idle reaper armed (checking every ${Math.round(intervalMs / 1000)}s)`);+}++/** Disarm the reaper. For shutdown and for test isolation. */+export function stopIdleReaper() {+ if (!reaperTimer) return;+ clearInterval(reaperTimer);+ reaperTimer = null;+}++/** Test seam: drop every registration and disarm the timer. */+export function _resetIdleDaemonsForTests() {+ stopIdleReaper();+ idleDaemons.clear();+}diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 998284e05a..c96b686f74 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1388,6 +1388,23 @@ export const settingsEmbeddingsSchema = z.object({export const localLlmSettingsSchema = z.object({ollama: z.object({ disabled: z.boolean().optional() }).strict().optional(),lmstudio: z.object({ disabled: z.boolean().optional() }).strict().optional(),+ // Idle windows for the two PM2-managed model servers, in minutes. `0` = never+ // release the model, which is what every install did before this setting+ // existed and stays the default. Capped at a day: a longer window is+ // indistinguishable from "never" and is far likelier a units mix-up.+ llama: z.object({ idleMinutes: z.number().int().min(0).max(1440).optional() }).strict().optional(),+ mtplx: z.object({+ idleMinutes: z.number().int().min(0).max(1440).optional(),+ // The launch line a lazy start replays. MTPLX has no Start button any more —+ // the first request that needs it brings it up — so the checkpoint and port+ // the user chose have to outlive the process, or an on-demand start would+ // fall back to "first verified checkpoint in the cache" and quietly serve+ // something they didn't pick.+ launch: z.object({+ model: z.string().trim().max(300).nullable().optional(),+ port: z.number().int().min(1).max(65535).optional(),+ }).strict().optional(),+ }).strict().optional(),}).strict();// =============================================================================diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex 96c299b2aa..36ceefff02 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -40,7 +40,7 @@ import {localLlmSpecModelDownloadSchema} from '../lib/validation.js'import { getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer } from '../services/llamaServerManager.js'-import { getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx } from '../services/mtplxServerManager.js'+import { MTPLX_APP, getMtplxServerStatus, startMtplxServer, stopMtplxServer, installMtplx } from '../services/mtplxServerManager.js'import { searchMtplxCatalog, pullMtplxModel, removeMtplxModel } from '../services/mtplxModelManager.js'import { saveProcessList } from '../services/pm2.js'import { getSpecDecodePresetStatus, downloadSpecDecodeModel } from '../services/specDecodeModels.js'@@ -753,12 +753,18 @@ router.post('/mtplx/models/remove', asyncHandler(async (req, res) => {}))// 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+// runtime servers currently running (llama-server, 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.+//+// MTPLX is deliberately EXCLUDED. It is started on demand by the first request+// that needs it and stopped again when idle, so resurrecting it at boot would+// pin its multi-gigabyte checkpoint on a machine nobody has asked anything of+// yet — the exact waste the idle stop exists to end. The running process is+// left alone; only the boot list drops it.router.post('/save-startup', asyncHandler(async (_req, res) => {- res.json(await saveProcessList())+ res.json(await saveProcessList(null, { exclude: [MTPLX_APP] }))}))export default routerdiff --git a/server/services/bootstrap.js b/server/services/bootstrap.jsindex 44f2ad3261..ebbe653de5 100644--- a/server/services/bootstrap.js+++ b/server/services/bootstrap.js@@ -31,6 +31,7 @@ import { setupProcessErrorHandlers, asyncHandler, ServerError, errorEvents } froimport { ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';import { createAIToolkit } from '../lib/aiToolkit/index.js';import { verifyCollectionVersions } from '../lib/collectionStore.js';+import { startIdleReaper, stopIdleReaper } from '../lib/managedDaemon.js';import { conflictJournalStore } from '../lib/conflictJournal.js';import { markHostShuttingDown, writeHostShutdownMarker } from '../lib/hostShutdown.js';import { setUserCatalogTypes } from '../lib/catalogTypes.js';@@ -333,6 +334,11 @@ const startBackgroundServices = ({ spawnerReady }) => {// cold-bootstrap provider call.recoverInterruptedThreejsModels().catch(err => console.error(`❌ Three.js model recovery failed: ${err.message}`));recoverInterruptedImageTo3dModels().catch(err => console.error(`❌ Image-to-3D model recovery failed: ${err.message}`));+ // Arm the managed-model-server idle reaper. Timer only — it reads timestamps+ // and may stop a PM2 process, and makes no AI provider call, so it is safe+ // under AGENTS.md's "No cold-bootstrap LLM calls". Off in practice until the+ // user sets an idle window (0 = never, the default).+ startIdleReaper();// Initialize brain scheduler for daily digests and weekly reviewsstartBrainScheduler();// Initialize activity-digest scheduler — OFF by default; drafts daily-log@@ -816,6 +822,10 @@ export const registerShutdownHandlers = ({ io, httpServer, localHttpServer }) =>// microseconds from now — and its exit handler must already know the PTY// died because PortOS is going down, not because the agent finished (#3202).markHostShuttingDown();+ // Disarm the idle reaper before anything awaits: a sweep that fires mid+ // -shutdown would `pm2 stop` a model server the user never asked to lose,+ // and PortOS is about to stop being the thing that could restart it.+ stopIdleReaper();// Diagnostic context for the shutdown trigger. ppid tells us whether the// signal came from PM2 (parent is the PM2 god process), a TTY (parent is// the user's shell), or some external orchestrator. pm_* env vars are setdiff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.jsindex 32ad53a642..72cbec1a55 100644--- a/server/services/llamaServerManager.js+++ b/server/services/llamaServerManager.js@@ -12,6 +12,7 @@ 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 { execFile } from '../lib/childProcess.js';import { resolveSpecModelPath } from './specDecodeModels.js';import { parseSpecTypes, isDraftSpecType } from '../lib/specDecodePresets.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';@@ -20,11 +21,27 @@ import { PORTS } from '../lib/ports.js';import { tuningSpecsFor } from '../lib/localModelTuning.js';import { ServerError } from '../lib/errorHandler.js';import { execPm2, getAppStatusStrict, clearJlistCache, getSavedProcessNames } from './pm2.js';+// `settings.js` is lazy-imported at its call sites below, never statically: it+// eagerly resolves `fileUtils.PATHS` at module load, which drags PATHS into the+// module graph of every consumer of this manager and breaks the many suites that+// partial-mock fileUtils without it. Same reason `lib/aiProvider.js` defers+// `localModelHealing`.+export const LLAMA_APP = 'portos-llama-server';const PROBE_TIMEOUT_MS = 1500;const STARTUP_WAIT_TIMEOUT_MS = 4000;+// `llama-server --help` is a fast local exec; this only bounds a wedged binary.+const HELP_PROBE_TIMEOUT_MS = 5000;+// llama.cpp's own in-place idle unload. See `supportsSleepIdle`.+const SLEEP_IDLE_FLAG = '--sleep-idle-seconds';+// binary path -> does it understand SLEEP_IDLE_FLAG. Keyed by path so a user who+// swaps in a newer build at a different location is re-probed rather than+// inheriting the old answer.+const sleepIdleSupport = new Map();+// See `configuredSleepIdleMinutes`. Only `_resetLlamaServerStateForTests` writes it.+let sleepIdleMinutesOverride = null;// How long a relaunch waits for the kernel to release the old listener.const PORT_RELEASE_TIMEOUT_MS = 5000;// How long a relaunch waits for the new process to answer. `startLlamaServer`@@ -83,6 +100,61 @@ function resolveLlamaServerBinary() {return findCommandOnPath('llama-server');}+/**+ * Does the installed `llama-server` understand `--sleep-idle-seconds`?+ *+ * That flag is how llama.cpp releases a checkpoint WITHOUT the process going+ * away: after N idle seconds the server unloads the model and reloads it on the+ * next request, keeping its PM2 entry, its port, and its launch line. Stopping+ * the process instead would reclaim the same memory at the cost of a full cold+ * start — which is why PortOS reaps MTPLX (it has no such flag) but not this.+ *+ * Probed rather than assumed because PortOS is distributed software: the flag+ * landed in a recent llama.cpp, and every install upgrades on its own schedule.+ * An older binary REJECTS an unknown flag and exits before it binds, so emitting+ * it blind would break the start outright for anyone who hasn't upgraded.+ *+ * Cached per binary path — `--help` is a subprocess, and a start already pays+ * for several. A probe that cannot run at all answers `false`: leaving the flag+ * off costs the idle release, while guessing `true` costs the daemon.+ *+ * @param {string} binaryPath+ * @returns {Promise<boolean>}+ */+async function supportsSleepIdle(binaryPath) {+ if (sleepIdleSupport.has(binaryPath)) return sleepIdleSupport.get(binaryPath);+ const help = await new Promise((resolve) => {+ execFile(binaryPath, ['--help'], { timeout: HELP_PROBE_TIMEOUT_MS, ...safeChildProcessOptions() },+ (err, stdout, stderr) => resolve(`${stdout || ''}${stderr || ''}`));+ }).catch(() => '');+ const supported = help.includes(SLEEP_IDLE_FLAG);+ sleepIdleSupport.set(binaryPath, supported);+ if (!supported) {+ console.log(`🦙 llama-server at ${binaryPath} has no ${SLEEP_IDLE_FLAG} — idle unload unavailable on this build`);+ }+ return supported;+}++/**+ * The configured idle window for llama-server, in minutes.+ *+ * `0` is a real choice ("keep the model resident", the behaviour every install+ * had before this setting existed) and is the default, so an upgrade changes+ * nothing until the user asks for it. An unreadable settings file degrades to+ * the same `0` rather than to a window nobody chose.+ *+ * @returns {Promise<number>}+ */+async function configuredSleepIdleMinutes() {+ // Test seam. Suites here assert EXACT launch lines, so reading the developer's+ // real `data/settings.json` would make them pass or fail on whether that+ // developer happens to use this feature. `null` (production) reads settings.+ if (sleepIdleMinutesOverride !== null) return sleepIdleMinutesOverride;+ const settings = await import('./settings.js').then((m) => m.getSettings()).catch(() => null);+ const raw = Number(settings?.localLlm?.llama?.idleMinutes);+ return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 0;+}+/*** Fails the start request when a GGUF the launch line names is not on disk.*/@@ -145,6 +217,12 @@ function parseConfigFromArgs(args) {// Current llama.cpp calls this `--spec-draft-n-max`; retain the older// spelling on read so a pre-upgrade PortOS launch line can still be captured// and restored without inventing a new value.+ // Stored in MINUTES here, on the launch line in SECONDS — the flag's own+ // unit. Absent means the daemon is running without idle unload, which is 0+ // ("keep it resident"), not "unknown".+ sleepIdleMinutes: getArg(SLEEP_IDLE_FLAG) !== null+ ? Math.round(Number(getArg(SLEEP_IDLE_FLAG)) / 60)+ : 0,draftMax: getArg('--spec-draft-n-max') !== null? Number(getArg('--spec-draft-n-max')): (getArg('--draft-max') !== null ? Number(getArg('--draft-max')) : null),@@ -220,6 +298,10 @@ export async function getLlamaServerStatus() {// 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),+ // The SAVED window, which is what the settings field edits. What the running+ // process actually got is `config.sleepIdleMinutes` — they differ until the+ // next start, because this is a launch flag.+ idleMinutes: await configuredSleepIdleMinutes(),recentLogs: logs.withPm2Logs(`${pm2Logs?.stdout || ''}\n${pm2Logs?.stderr || ''}`),lastExitError: isReadFailed ? 'Failed to read PM2 status' : lastExitError,};@@ -286,6 +368,11 @@ export async function startLlamaServer(options = {}) {cacheTypeK = null,cacheTypeV = null,draftMax = null,+ // Minutes of idleness after which llama.cpp unloads the checkpoint in place.+ // `undefined` = not supplied, so fall through to the saved setting; an+ // explicit number (including 0) is the caller's own choice and wins, which+ // is what lets a relaunch replay exactly the line it captured.+ sleepIdleMinutes = undefined,} = options;if (!model || typeof model !== 'string') {@@ -361,8 +448,26 @@ export async function startLlamaServer(options = {}) {if (Number.isFinite(draftMax) && draftPath) args.push('--spec-draft-n-max', String(draftMax));if (alias) args.push('--alias', alias);+ // llama.cpp's in-place idle unload. Resolved AFTER the rest of the line so a+ // relaunch that carried an explicit value replays it verbatim, and only then+ // falls back to the saved setting.+ const requestedIdleMinutes = Number.isFinite(sleepIdleMinutes)+ ? Math.max(0, Math.floor(sleepIdleMinutes))+ : await configuredSleepIdleMinutes();+ // A build without the flag gets the line it would have got before this+ // feature existed — never a rejected launch. `effectiveIdleMinutes` is what+ // actually reached the process, so the status card reports the truth rather+ // than the request.+ const effectiveIdleMinutes = requestedIdleMinutes > 0 && await supportsSleepIdle(binaryPath)+ ? requestedIdleMinutes+ : 0;+ if (effectiveIdleMinutes > 0) args.push(SLEEP_IDLE_FLAG, String(effectiveIdleMinutes * 60));+lastExitError = null;logs.reset();+ if (requestedIdleMinutes > 0 && effectiveIdleMinutes === 0) {+ appendLog(`This llama-server build has no ${SLEEP_IDLE_FLAG} — the model stays resident while idle`);+ }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)`);@@ -399,6 +504,7 @@ export async function startLlamaServer(options = {}) {cacheTypeK,cacheTypeV,draftMax,+ sleepIdleMinutes: effectiveIdleMinutes,};// Delete stale PM2 entry so our own previous instance doesn't count as a collision@@ -1059,7 +1165,10 @@ export async function installLlamaServer({ onProgress = () => {} } = {}) {/*** Clears in-memory test state (used by test suites).*/-export function _resetLlamaServerStateForTests({ relaunchReadyTimeout, pm2ReadRetryDelay } = {}) {+export function _resetLlamaServerStateForTests({ relaunchReadyTimeout, pm2ReadRetryDelay, sleepIdleMinutes = 0 } = {}) {+ sleepIdleSupport.clear();+ // Pinned rather than read from disk — see `configuredSleepIdleMinutes`.+ sleepIdleMinutesOverride = sleepIdleMinutes;currentConfig = null;preTuningConfig = null;logs.reset();diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.jsindex 09a9d63f75..8d972f805f 100644--- a/server/services/llamaServerManager.test.js+++ b/server/services/llamaServerManager.test.js@@ -1065,4 +1065,106 @@ describe('llamaServerManager', () => {// not by accident, so this one test buys the room rather than the suite.}, 30000);});++ // ===========================================================================+ // IDLE UNLOAD (--sleep-idle-seconds)+ // ===========================================================================+ //+ // llama.cpp releases a checkpoint IN PLACE and reloads it on the next request,+ // so PortOS passes a flag rather than stopping the process the way it does for+ // MTPLX. The flag is recent, and an older build rejects an unknown flag and+ // exits before it binds — hence the capability probe these tests pin.+ describe('idle unload', () => {+ /** Pin `llama-server --help` output for the capability probe. */+ const mockHelp = (text) => vi.spyOn(childProcess, 'execFile')+ .mockImplementation((_bin, _args, _opts, cb) => { cb(null, text, ''); return fakeSpawnProcess(); });++ const startArgs = () => (execPm2Calls.find((c) => c[0] === 'start') || []).slice(8);++ it('puts the window on the launch line in SECONDS when the build supports it', async () => {+ mockHelp('--sleep-idle-seconds SECONDS number of seconds of idleness');++ await startLlamaServer({ model: modelPath, draftModel: null, specType: '', port: 8080, sleepIdleMinutes: 30 });++ expect(startArgs()).toContain('--sleep-idle-seconds');+ // 30 minutes on the card, 1800 seconds on the flag — the unit is the+ // flag's, and getting this backwards would idle-unload after 30 seconds.+ expect(startArgs()[startArgs().indexOf('--sleep-idle-seconds') + 1]).toBe('1800');+ });++ it('leaves the flag off entirely when the window is 0', async () => {+ mockHelp('--sleep-idle-seconds SECONDS number of seconds of idleness');++ await startLlamaServer({ model: modelPath, draftModel: null, specType: '', port: 8080, sleepIdleMinutes: 0 });++ expect(startArgs()).not.toContain('--sleep-idle-seconds');+ });++ // The compatibility guarantee: an install on an older llama.cpp must keep+ // starting. Emitting an unknown flag would make the daemon exit immediately.+ it('omits the flag on a build that does not advertise it, rather than failing the start', async () => {+ mockHelp('--port PORT port to listen on\n--ctx-size N context size');++ const result = await startLlamaServer({ model: modelPath, draftModel: null, specType: '', port: 8080, sleepIdleMinutes: 30 });++ expect(result.success).toBe(true);+ expect(startArgs()).not.toContain('--sleep-idle-seconds');+ // ...and the status reports what actually reached the process, not what was asked for.+ expect(result.config.sleepIdleMinutes).toBe(0);+ });++ it('says so in the logs when the build cannot idle-unload', async () => {+ mockHelp('--port PORT port to listen on');++ await startLlamaServer({ model: modelPath, draftModel: null, specType: '', port: 8080, sleepIdleMinutes: 30 });+ const status = await getLlamaServerStatus();++ expect(status.recentLogs.join('\n')).toContain('--sleep-idle-seconds');+ });++ it('treats a --help probe that fails as "unsupported"', async () => {+ vi.spyOn(childProcess, 'execFile')+ .mockImplementation((_bin, _args, _opts, cb) => { cb(new Error('ENOENT'), '', ''); return fakeSpawnProcess(); });++ const result = await startLlamaServer({ model: modelPath, draftModel: null, specType: '', port: 8080, sleepIdleMinutes: 30 });++ expect(result.success).toBe(true);+ expect(startArgs()).not.toContain('--sleep-idle-seconds');+ });++ it('probes --help once per binary, not once per start', async () => {+ const spy = mockHelp('--sleep-idle-seconds SECONDS');++ await startLlamaServer({ model: modelPath, draftModel: null, specType: '', port: 8080, sleepIdleMinutes: 30 });+ await stopLlamaServer();+ await startLlamaServer({ model: modelPath, draftModel: null, specType: '', port: 8080, sleepIdleMinutes: 30 });++ expect(spy).toHaveBeenCalledTimes(1);+ });++ // A PortOS restart under a still-running daemon recovers the launch line+ // from PM2's argv; the window has to come back with it or the status card+ // would report idle unload as off on a server that has it on.+ it('recovers the window from a running process argv, converting back to minutes', async () => {+ pm2State = {+ name: LLAMA_APP,+ status: 'online',+ pid: 4242,+ args: ['-m', modelPath, '--port', '8080', '--sleep-idle-seconds', '1800'],+ };++ const status = await getLlamaServerStatus();++ expect(status.config.sleepIdleMinutes).toBe(30);+ });++ it('reports 0 for a running process whose argv carries no window', async () => {+ pm2State = { name: LLAMA_APP, status: 'online', pid: 4242, args: ['-m', modelPath, '--port', '8080'] };++ const status = await getLlamaServerStatus();++ expect(status.config.sleepIdleMinutes).toBe(0);+ });+ });+});diff --git a/server/services/mtplxServerManager.js b/server/services/mtplxServerManager.jsindex 7f455750e7..b3417d0763 100644--- a/server/services/mtplxServerManager.js+++ b/server/services/mtplxServerManager.js@@ -26,10 +26,16 @@ import { commandExists } from '../lib/commandExists.js';import { sleep } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';import { launchArgs, normalizeTuning, tuningSpecsFor } from '../lib/localModelTuning.js';-import { LOCAL_RUNTIMES, localEndpointPort } from '../lib/localProviderRuntime.js';+import { LOCAL_RUNTIMES, localEndpointPort, localRuntimeKind, isLocalInstanceEndpoint } 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 { createDaemonLogBuffer, pm2ArgValue, idleWindowMs, markDaemonUsed, registerIdleDaemon } from '../lib/managedDaemon.js';+// `settings.js` is lazy-imported at its call sites below, never statically: it+// eagerly resolves `fileUtils.PATHS` at module load, which drags PATHS into the+// module graph of every consumer of this manager and breaks the many suites that+// partial-mock fileUtils without it. Same reason `lib/aiProvider.js` defers+// `localModelHealing`.+import { isAppleSilicon, isPortInUse } from '../lib/platform.js';import { findCommandOnPath } from '../lib/processEnv.js';import { runStreamingCommand } from '../lib/streamingSpawn.js';@@ -300,6 +306,10 @@ export async function getMtplxServerStatus() {// 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),+ idleMinutes: await configuredIdleMinutes(),+ // What a lazy start will launch on, so the card's fields show the saved+ // choice rather than resetting to "Auto" on every page load.+ launch: await savedLaunchConfig(),cachedModels: (cache.models || []).map((m) => m?.repo_id).filter(Boolean),// The same cache, with what the manage-checkpoints UI needs to let a user// free the disk: how big each pack is, and whether it is actually servable@@ -699,7 +709,8 @@ async function restorePrevious(previous, failure) {}/** Clears in-memory state (used by test suites). */-export function _resetMtplxServerStateForTests({ startupWait, startupPoll, portRelease, relaunchReadyTimeout } = {}) {+export function _resetMtplxServerStateForTests({ startupWait, startupPoll, portRelease, relaunchReadyTimeout, idleMinutes = 0 } = {}) {+ idleMinutesOverride = idleMinutes;currentConfig = null;logs.reset();lastExitError = null;@@ -709,3 +720,163 @@ export function _resetMtplxServerStateForTests({ startupWait, startupPoll, portRportReleaseTimeoutMs = Number.isFinite(portRelease) ? portRelease : 30_000;relaunchReadyTimeoutMs = Number.isFinite(relaunchReadyTimeout) ? relaunchReadyTimeout : 300_000;}++// =============================================================================+// IDLE STOP + LAZY START+// =============================================================================++/**+ * Why MTPLX is stopped on idle while llama-server is not.+ *+ * MTPLX holds its whole MLX checkpoint — 20GB is ordinary — for as long as the+ * process is up, and it has no way to put that down in place: its+ * `--retrieval-idle-timeout` unloads RETRIEVAL models (embedding/rerank) only,+ * never the main checkpoint, and `mtplx settings set` covers live tunables like+ * depth, not residency. Stopping the process is therefore the only lever, and+ * lazy-start is what makes stopping it safe to do automatically.+ *+ * `llamaServerManager` deliberately takes the other path (`--sleep-idle-seconds`),+ * because llama.cpp CAN unload in place — see `supportsSleepIdle` there.+ */++/**+ * The configured idle window for MTPLX, in minutes. `0`/absent = never stop,+ * which is what every install did before this setting existed, so an upgrade+ * changes nothing until the user opts in.+ */+const readSettings = () => import('./settings.js').then((m) => m.getSettings()).catch(() => null);+// See `configuredIdleMinutes`. Only `_resetMtplxServerStateForTests` writes it.+let idleMinutesOverride = null;++async function configuredIdleMinutes() {+ // Test seam, same reason as `llamaServerManager`'s: a suite must not depend on+ // whether this developer has an idle window configured. `null` reads settings.+ if (idleMinutesOverride !== null) return idleMinutesOverride;+ const settings = await readSettings();+ const raw = Number(settings?.localLlm?.mtplx?.idleMinutes);+ return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 0;+}++// Registered at module load so the reaper knows about MTPLX regardless of which+// call path touches this module first. Registration itself starts nothing and+// reads no settings — the window is resolved per sweep, inside `getIdleMs`.+registerIdleDaemon({+ name: MTPLX_APP,+ getIdleMs: async () => idleWindowMs(await configuredIdleMinutes()),+ stop: () => stopMtplxServer(),+});++/**+ * The checkpoint/port the user last saved on the MTPLX card, for a lazy start to+ * replay. Empty when nothing was saved — `startMtplxServer` then resolves a+ * cached checkpoint itself, which is what the old Start button did.+ */+async function savedLaunchConfig() {+ const settings = await readSettings();+ const launch = settings?.localLlm?.mtplx?.launch;+ return {+ model: typeof launch?.model === 'string' && launch.model.trim() ? launch.model.trim() : null,+ port: Number.isFinite(Number(launch?.port)) ? Number(launch.port) : null,+ };+}++/** Record real MTPLX traffic. Never call this from a status poll — see `markDaemonUsed`. */+export const markMtplxUsed = () => markDaemonUsed(MTPLX_APP);++/**+ * Bring MTPLX up if the idle reaper (or the user) stopped it, and mark it used+ * either way.+ *+ * A no-op when it is already online — the overwhelmingly common case, and it+ * must stay cheap enough to sit in front of every request. The one PM2 status+ * read it costs is the same read `getMtplxServerStatus` already does on a poll.+ *+ * The relaunch reuses the config recovered from PM2's argv when PortOS still+ * holds one, so the daemon comes back on exactly the checkpoint, port, and+ * tuning the user last launched it with. `startMtplxServer` resolves a cached+ * checkpoint on its own when there is no such record (a fresh PortOS whose+ * reaper stopped a server it never started), which is the same fallback the+ * Start button used to take.+ *+ * Resolves `{ ready, reason }` rather than throwing: a caller in front of an+ * inference request wants to report "MTPLX could not be started" alongside its+ * own error, not have a lazy start unwind its stack.+ *+ * @returns {Promise<{ready: boolean, reason: string|null}>}+ */+export async function ensureMtplxRunning() {+ markMtplxUsed();++ const pm2Status = await getAppStatusStrict(MTPLX_APP);+ if (pm2Status?.status === 'online') return { ready: true, reason: null };++ // Resolve the launch line BEFORE probing, so the probe below asks about the+ // port this start would actually bind. Precedence: the config recovered from+ // the last live process (it carries the tuning an assessment relaunch applied,+ // which settings never see), then the launch options the user saved on the+ // MTPLX card, then MTPLX's own cache pick. Reversing the first two would let a+ // stale saved port fight a daemon PortOS is already tracking on another one.+ const saved = await savedLaunchConfig();+ const config = {+ port: currentConfig?.port ?? saved.port ?? DEFAULT_PORT,+ model: currentConfig?.model ?? saved.model ?? null,+ tuning: currentConfig?.tuning ?? null,+ };++ // Something else is already serving that port — an MTPLX the user started+ // outside PortOS, or another daemon entirely. Either way this is not ours to+ // start, and probing beats racing `startMtplxServer` into a port conflict.+ // Probing `endpointFor(currentConfig)` instead would ask about the DEFAULT+ // port whenever PortOS restarted while MTPLX was stopped, which is exactly+ // when the saved port is the only record of where it belongs.+ const endpoint = endpointFor(config);+ if (await probeEndpoint(endpoint)) return { ready: true, reason: null };++ console.log(`🚄 MTPLX is stopped — starting it for an incoming request`);+ const started = await startMtplxServer(config).catch((err) => ({ error: err }));++ if (started.error) return { ready: false, reason: started.error.message };+ // `startMtplxServer` returns as soon as it knows the process did not die on+ // the spot; a multi-gigabyte MLX checkpoint routinely outlasts that window, so+ // the caller's request has to wait for the real readiness signal.+ if (started.online) return { ready: true, reason: null };+ return waitForRelaunchedEndpoint(started.endpoint ?? endpoint);+}++/**+ * Is this provider served by the MTPLX daemon PortOS manages?+ *+ * Mirrors `ollamaManager.isOllamaProvider` so `lib/aiProvider.js` gates both+ * local daemons the same way. Only a LOCAL endpoint counts: an MTPLX on a+ * tailnet peer is someone else's process, and neither starting nor idle-stopping+ * it is this install's business.+ */+export function isMtplxProvider(provider) {+ if (!provider || provider.type !== 'api') return false;+ if (!isLocalInstanceEndpoint(provider.endpoint)) return false;+ // `localRuntimeKind`, not `localBackendForProvider` — the latter only ever+ // answers 'ollama'/'lmstudio' (it maps those two catalog ports), so it reports+ // every MTPLX provider as having no local backend at all. The authoritative+ // signal is the `mtplxBacked` marker the spawner itself keys on.+ if (localRuntimeKind(provider) === 'mtplx') return true;+ // ...and an endpoint-only provider aimed at the port THIS daemon is serving.+ // Deliberately compared against the live launch config rather than treating+ // :8000 as "must be MTPLX" — 8000 is a generic port, and claiming any local+ // server on it would lazily start MTPLX for someone else's API.+ const managedPort = currentConfig?.port;+ return Boolean(managedPort) && localEndpointPort(provider.endpoint) === managedPort;+}++/**+ * The `ensureProviderReady` shape `lib/aiProvider.js` expects, for MTPLX.+ *+ * This is the one call site that both refreshes the idle clock and lazily+ * restarts — deliberately on the INFERENCE path rather than in+ * `getMtplxServerEndpoint`, which status polls call every few seconds and which+ * would therefore keep a 20GB checkpoint resident for a UI nobody is watching.+ */+export async function ensureMtplxProviderReady(provider) {+ if (!isMtplxProvider(provider)) return { success: true };+ const { ready, reason } = await ensureMtplxRunning();+ return ready ? { success: true } : { success: false, error: reason };+}diff --git a/server/services/mtplxServerManager.test.js b/server/services/mtplxServerManager.test.jsindex 3f2dd1820d..bc53f00d12 100644--- a/server/services/mtplxServerManager.test.js+++ b/server/services/mtplxServerManager.test.js@@ -6,6 +6,9 @@ import {relaunchMtplxServerWithTuning,installMtplx,_resetMtplxServerStateForTests,+ ensureMtplxRunning,+ ensureMtplxProviderReady,+ isMtplxProvider,MTPLX_APP,} from './mtplxServerManager.js';import * as processEnv from '../lib/processEnv.js';@@ -552,4 +555,148 @@ describe('mtplxServerManager', () => {expect(result.message).toMatch(/not running/i);});});++ // ===========================================================================+ // LAZY START+ // ===========================================================================+ //+ // MTPLX cannot unload its checkpoint in place (its `--retrieval-idle-timeout`+ // covers retrieval models only), so the idle reaper stops the whole process+ // and the next PortOS request has to bring it back. There is no Start button+ // any more — this IS how MTPLX starts.+ describe('ensureMtplxRunning', () => {+ const startCalls = () => execPm2Calls.filter((c) => c[0] === 'start');++ beforeEach(() => {+ // A lazy start that never answers waits out the READINESS budget, not the+ // startup one — five real minutes by default. Shorten it here rather than+ // in the shared setup, which the give-up-path tests below depend on.+ _resetMtplxServerStateForTests({ startupWait: 50, startupPoll: 5, portRelease: 20, relaunchReadyTimeout: 30 });+ });++ it('is a no-op when the daemon is already online', async () => {+ pm2State = { name: MTPLX_APP, status: 'online', pid: 777, args: ['serve', '--port', '8000'] };++ const result = await ensureMtplxRunning();++ expect(result).toEqual({ ready: true, reason: null });+ expect(startCalls()).toHaveLength(0);+ });++ it('starts a stopped daemon and reports ready once it answers', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ // Not answering yet at the guard probe, answering by the readiness poll —+ // the ordinary cold-start shape for a multi-gigabyte MLX checkpoint.+ const probe = vi.spyOn(openAiModelsProbe, 'probeOpenAiModels');+ probe.mockResolvedValueOnce({ reachable: false }) // ensureMtplxRunning's "is someone else serving?" guard+ .mockResolvedValueOnce({ reachable: false }) // startMtplxServer's port-collision guard+ .mockResolvedValue({ reachable: true }); // startup poll++ const result = await ensureMtplxRunning();++ expect(result.ready).toBe(true);+ expect(startCalls()).toHaveLength(1);+ });++ // A server the user started outside PortOS answers on the port but has no+ // PM2 entry. Starting our own would collide, so back off and use it.+ it('does not start anything when something else already serves the port', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: true });++ const result = await ensureMtplxRunning();++ expect(result).toEqual({ ready: true, reason: null });+ expect(startCalls()).toHaveLength(0);+ });++ it('reports the reason rather than throwing when the start fails', async () => {+ // No binary on PATH — `startMtplxServer` throws a ServerError, and a+ // caller sitting in front of an inference request must get a reason back,+ // not an exception through its stack.+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(null);++ const result = await ensureMtplxRunning();++ expect(result.ready).toBe(false);+ expect(result.reason).toMatch(/not found on PATH/);+ });++ it('relaunches on the checkpoint and port the recovered config names', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ // Seed the recovered config the way a PortOS restart under a live daemon+ // would, then stop it — the relaunch must reuse that line, not guess.+ pm2State = { name: MTPLX_APP, status: 'online', pid: 5, args: ['serve', '--port', '8123', '--model', 'Example/Chosen-MTP'] };+ await getMtplxServerStatus();+ pm2State = null;++ await ensureMtplxRunning();++ const args = startCalls()[0].slice(startCalls()[0].indexOf('--') + 1);+ expect(args).toContain('8123');+ expect(args).toContain('Example/Chosen-MTP');+ });++ // The saved port is the ONLY record of where MTPLX belongs once PortOS has+ // restarted with it stopped — probing the default port instead would miss a+ // server already on the saved one and then collide with it on start.+ it('probes the saved port, not the default, when there is no recovered config', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ const settings = await import('./settings.js');+ vi.spyOn(settings, 'getSettings').mockResolvedValue({ localLlm: { mtplx: { launch: { port: 8010 } } } });+ const probe = vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: true });++ const result = await ensureMtplxRunning();++ expect(result.ready).toBe(true);+ expect(probe).toHaveBeenCalledWith('http://127.0.0.1:8010/v1', expect.anything());+ expect(startCalls()).toHaveLength(0);+ });++ it('marks the daemon used, so a request resets the idle clock', async () => {+ pm2State = { name: MTPLX_APP, status: 'online', pid: 777, args: ['serve', '--port', '8000'] };+ const { daemonLastUsedAt } = await import('../lib/managedDaemon.js');++ const before = daemonLastUsedAt(MTPLX_APP);+ await new Promise((r) => setTimeout(r, 2));+ await ensureMtplxRunning();++ expect(daemonLastUsedAt(MTPLX_APP)).toBeGreaterThan(before);+ });+ });++ describe('isMtplxProvider', () => {+ it('matches a local MTPLX endpoint', () => {+ expect(isMtplxProvider({ type: 'api', endpoint: 'http://127.0.0.1:8000/v1', id: 'mtplx', mtplxBacked: true })).toBe(true);+ });++ // An MTPLX on a tailnet peer is someone else's process — PortOS must+ // neither start it nor count its traffic against this install's idle window.+ it('does not match an MTPLX on another machine', () => {+ expect(isMtplxProvider({ type: 'api', endpoint: 'http://100.64.0.5:8000/v1', id: 'mtplx', mtplxBacked: true })).toBe(false);+ });++ it('does not match a CLI provider', () => {+ expect(isMtplxProvider({ type: 'cli', endpoint: 'http://127.0.0.1:8000/v1', id: 'mtplx', mtplxBacked: true })).toBe(false);+ });+ });++ describe('ensureMtplxProviderReady', () => {+ it('passes through a provider that is not MTPLX without touching PM2', async () => {+ const result = await ensureMtplxProviderReady({ type: 'api', endpoint: 'https://api.example.com/v1', id: 'remote' });++ expect(result).toEqual({ success: true });+ expect(execPm2Calls.filter((c) => c[0] === 'start')).toHaveLength(0);+ });++ it('surfaces a failed lazy start as an error the caller can report', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(null);++ const result = await ensureMtplxProviderReady({ type: 'api', endpoint: 'http://127.0.0.1:8000/v1', id: 'mtplx', mtplxBacked: true });++ expect(result.success).toBe(false);+ expect(result.error).toMatch(/not found on PATH/);+ });+ });+});diff --git a/server/services/pm2.js b/server/services/pm2.jsindex 84e1a3feb7..ca8e373a82 100644--- a/server/services/pm2.js+++ b/server/services/pm2.js@@ -5,7 +5,7 @@ import { writeFile, unlink } from 'fs/promises';import { join, dirname } from 'path';import { createRequire } from 'module';import { homedir } from 'os';-import { extractJSONArray, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';+import { atomicWrite, extractJSONArray, safeJSONParse, tryReadFile } from '../lib/fileUtils.js';import { parseCommandArgs } from '../lib/commandSecurity.js';const IS_WIN = process.platform === 'win32';@@ -664,9 +664,51 @@ function spawnPm2StartEcosystem(cwd, ecosystemFile, processNames, pm2Home) {** @param {string|null} [pm2Home=null]*/-export async function saveProcessList(pm2Home = null) {+export async function saveProcessList(pm2Home = null, { exclude = [] } = {}) {await execPm2(['save'], { env: buildEnv(pm2Home) });- return { success: true };+ const dropped = await dropFromSavedList(exclude, pm2Home);+ return { success: true, excluded: dropped };+}++/**+ * Remove app entries from PM2's dump AFTER `pm2 save` wrote it.+ *+ * `pm2 save` is process-list wide with no exclusion flag — it snapshots whatever+ * is running. That is the wrong answer for a daemon PortOS starts on demand:+ * MTPLX is lazily started by the first request that needs it and stopped again+ * when idle, so resurrecting it at boot would put 20GB back on a machine nobody+ * has asked anything of yet — precisely the waste the idle stop exists to end.+ *+ * Rewriting the dump rather than stopping the daemon first keeps the running+ * process untouched: the user's MTPLX stays up for the session, it just isn't in+ * the list a reboot replays.+ *+ * Best-effort by design. An unreadable or non-JSON dump means PM2 owns a format+ * this doesn't understand, and a save that persisted one extra process is a far+ * better outcome than a corrupted dump that resurrects none.+ *+ * @param {string[]} names app names to drop+ * @param {string|null} [pm2Home]+ * @returns {Promise<string[]>} the names actually removed+ */+async function dropFromSavedList(names, pm2Home = null) {+ if (!names?.length) return [];+ const home = pm2Home || process.env.PM2_HOME || join(homedir(), '.pm2');+ const dumpPath = join(home, 'dump.pm2');+ const raw = await tryReadFile(dumpPath);+ if (raw === null) return [];+ const parsed = safeJSONParse(raw, null, { allowArray: true });+ if (!Array.isArray(parsed)) return [];++ const drop = new Set(names);+ const kept = parsed.filter((app) => !drop.has(app?.name));+ const removed = parsed.length - kept.length;+ if (removed === 0) return [];++ await atomicWrite(dumpPath, kept);+ const dropped = parsed.filter((app) => drop.has(app?.name)).map((app) => app.name);+ console.log(`💾 Excluded ${dropped.join(', ')} from the PM2 boot list (started on demand instead)`);+ return dropped;}/**diff --git a/server/services/pm2.savedProcesses.test.js b/server/services/pm2.savedProcesses.test.jsindex 2760bdebcc..7242402943 100644--- a/server/services/pm2.savedProcesses.test.js+++ b/server/services/pm2.savedProcesses.test.js@@ -7,7 +7,8 @@ import { join } from 'path';// 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';+import { getSavedProcessNames, saveProcessList } from './pm2.js';+import * as pm2Module from './pm2.js';/*** `getSavedProcessNames` reads `$PM2_HOME/dump.pm2` — the list a boot-time@@ -53,3 +54,78 @@ describe('getSavedProcessNames', () => {expect(await getSavedProcessNames(home)).toEqual(['portos-mtplx']);});});+++/**+ * `pm2 save` snapshots the whole running process list and has no exclusion flag,+ * so a daemon PortOS starts ON DEMAND has to be filtered out of the dump after+ * the fact. MTPLX is exactly that: the first request that needs it starts it and+ * the idle reaper stops it again, so resurrecting it at boot would pin its+ * multi-gigabyte checkpoint on a machine nobody has asked anything of yet.+ */+describe('saveProcessList exclusions', () => {+ let home;++ beforeEach(async () => {+ home = await mkdtemp(join(tmpdir(), 'portos-pm2-home-'));+ // `pm2 save` itself is the real subprocess; the dump it would have written+ // is seeded per test so the filtering is what's under assertion.+ vi.spyOn(pm2Module, 'execPm2').mockResolvedValue({ stdout: '', stderr: '' });+ });++ afterEach(async () => {+ vi.restoreAllMocks();+ await rm(home, { recursive: true, force: true });+ });++ const seedDump = (names) =>+ writeFile(join(home, 'dump.pm2'), JSON.stringify(names.map((name) => ({ name, script: `/bin/${name}` }))));++ it('drops an excluded app from the dump and leaves the rest', async () => {+ await seedDump(['portos-server', 'portos-llama-server', 'portos-mtplx']);++ const result = await saveProcessList(home, { exclude: ['portos-mtplx'] });++ expect(result.excluded).toEqual(['portos-mtplx']);+ expect(await getSavedProcessNames(home)).toEqual(['portos-server', 'portos-llama-server']);+ });++ // llama.cpp still runs at boot when the user saves — it has no lazy start, and+ // its own idle unload releases the memory without the process going away.+ it('leaves llama-server in the boot list', async () => {+ await seedDump(['portos-llama-server', 'portos-mtplx']);++ await saveProcessList(home, { exclude: ['portos-mtplx'] });++ expect(await getSavedProcessNames(home)).toContain('portos-llama-server');+ });++ it('is a no-op when the excluded app was not running anyway', async () => {+ await seedDump(['portos-server']);++ const result = await saveProcessList(home, { exclude: ['portos-mtplx'] });++ expect(result.excluded).toEqual([]);+ expect(await getSavedProcessNames(home)).toEqual(['portos-server']);+ });++ it('saves everything when nothing is excluded', async () => {+ await seedDump(['portos-server', 'portos-mtplx']);++ const result = await saveProcessList(home);++ expect(result).toEqual({ success: true, excluded: [] });+ expect(await getSavedProcessNames(home)).toEqual(['portos-server', 'portos-mtplx']);+ });++ // A dump PM2 wrote in a shape this doesn't understand must be left ALONE. One+ // extra resurrected process beats a rewritten dump that resurrects none.+ it('leaves an unparseable dump untouched rather than rewriting it', async () => {+ await writeFile(join(home, 'dump.pm2'), 'not json at all');++ const result = await saveProcessList(home, { exclude: ['portos-mtplx'] });++ expect(result.excluded).toEqual([]);+ expect(await getSavedProcessNames(home)).toBeNull();+ });+});