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
fix: move MTPLX/Slotstream on-demand wake into managedDaemon (#8105)
[._.]/ Adam Eivy8c78ec3c7108
diff --git a/server/lib/README.md b/server/lib/README.mdindex 01bf35f0ac..58cc64a3ff 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -261,7 +261,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `opencodeCatalogCache.js` | Primes the on-disk catalog `opencode models` prints from — `primeOpencodeCatalogCache()` fetches OpenCode's `api.json` with Node's fetch and atomically writes `$XDG_CACHE_HOME/opencode/models.json` (`~/.cache` when unset). OpenCode refreshes that file from a forked task whose failures it swallows (`opencode models --refresh` still prints `Models cache refreshed`) and its HTTP client has no Happy Eyeballs, so a host advertising an unreachable IPv6 default route freezes the catalog indefinitely while other machines on the same account list newer models. Refuses to fetch or write when `OPENCODE_MODELS_PATH` / a custom `OPENCODE_MODELS_URL` / `OPENCODE_DISABLE_MODELS_FETCH` means PortOS cannot be sure which file OpenCode reads, when the file is under five minutes old, or when the body did not parse as a catalog — a stale list beats an empty picker. Never throws; the caller probes either way. || `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. Under a `no-tool` public-review profile it also applies `hardenOpencodeConfigForNoTool` — root `permission: deny`, an emptied tool map on every agent, `tool_call: false` on every declared model, and no MCP/plugins/share/autoupdate — which IS OpenCode's enforced tool-free recipe, since it ships no read-only argv flag (`providerVendors.js` pairs it with `run --agent` + `OPENCODE_PUBLIC_REVIEW_AGENT`). The harden step also copies `agent.build`'s generation settings onto that agent, so the stage's configured thinking effort reaches the model that actually runs. || `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), `localEndpointPort` + `isLocalInstanceHost`, and re-exports of `localBackendForProvider` / `localRuntimeKind` / `modelPinIsOffered` — all three now live in the browser-safe leaf `modelPinMembership.js` (a picker needs the pin rule and must not pull the endpoint graph below to get it), so existing importers here are untouched — `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); `standbyWhenStopped` marks an installed runtime such as llama.cpp whose stopped state is intentional standby rather than incomplete setup. |-| `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`, `services/slotstreamServerManager.js` → `portos-slotstream`). Owns their PM2 process names — `LLAMA_APP`, `MTPLX_APP`, `SLOTSTREAM_APP`, and the `isModelServerProcess(name)` predicate over them — so a caller like the CoS health monitor can recognize a model server without importing a manager; the managers re-export those names. `createDaemonWatcher({...})` supplies the common PM2 launch-line re-adoption, endpoint probe, status skeleton, bounded log view, and port-release wait while managers retain daemon-specific parsing and lifecycle policy. `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, isPinned?, isRunning?, stop})` (seeds `lastUsedAt` to NOW, so a hand-started daemon gets a full window; `isPinned` exempts user-pinned servers), `markDaemonUsed(name)` — call on real traffic, NEVER on a status poll — `daemonLastUsedAt(name)`, `daemonReleaseReason(name)`, `idleWindowMs(minutes)` (minutes → ms; `0` = never, `null` = not configured, kept distinct), `evaluateMemoryPressurePolicy({...})` (pure policy function evaluating current state, pressure reading, and recent history), `reapIdleDaemons(now?, options?)` → the names stopped (stops idle daemons whose window elapsed, and runs a pressure-aware pass releasing the least recently used unpinned daemon under sustained host memory pressure; at most one daemon stopped per tick), and `startIdleReaper({intervalMs?})` / `stopIdleReaper()` (ONE interval for all registrants, `unref`'d, idempotent). `mtplxServerManager` and `slotstreamServerManager` register: 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. |+| `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`, `services/slotstreamServerManager.js` → `portos-slotstream`). Owns their PM2 process names — `LLAMA_APP`, `MTPLX_APP`, `SLOTSTREAM_APP`, and the `isModelServerProcess(name)` predicate over them — so a caller like the CoS health monitor can recognize a model server without importing a manager; the managers re-export those names. `createDaemonWatcher({...})` supplies the common PM2 launch-line re-adoption, endpoint probe, status skeleton, bounded log view, and port-release wait while managers retain daemon-specific parsing and lifecycle policy. `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, isPinned?, isRunning?, stop})` (seeds `lastUsedAt` to NOW, so a hand-started daemon gets a full window; `isPinned` exempts user-pinned servers), `markDaemonUsed(name)` — call on real traffic, NEVER on a status poll — `daemonLastUsedAt(name)`, `daemonReleaseReason(name)`, `idleWindowMs(minutes)` (minutes → ms; `0` = never, `null` = not configured, kept distinct), `evaluateMemoryPressurePolicy({...})` (pure policy function evaluating current state, pressure reading, and recent history), `reapIdleDaemons(now?, options?)` → the names stopped (stops idle daemons whose window elapsed, and runs a pressure-aware pass releasing the least recently used unpinned daemon under sustained host memory pressure; at most one daemon stopped per tick), and `startIdleReaper({intervalMs?})` / `stopIdleReaper()` (ONE interval for all registrants, `unref`'d, idempotent). `mtplxServerManager` and `slotstreamServerManager` register: llama.cpp releases its checkpoint in place via `--sleep-idle-seconds` and must NOT be stopped for it. `createOnDemandDaemon({appName, label, emoji, readSection, endpointFor, probe, start, stop, getStatusStrict, clearStatusCache?, exitTail?, resolveLaunch, getConfig?, sleep, getRelaunchReadyTimeoutMs, getRelaunchPollMs})` is the shared ON-DEMAND WAKE mechanism (#8105) — `ensureRunning()` (mark used → already online? → resolve the launch line via the manager's `resolveLaunch(current, saved)` → probe → start → wait), `registerIdle()` (wraps `registerIdleDaemon` with the idle-minutes/keep-loaded reads, including the legacy `pinned` fallback and their own `set*OverrideForTests` seams), `waitForReady(endpoint)` (the death-detecting readiness poll, with `exitTail` folded in), `servesPort(provider, managedPort)` (the numeric port-match arm — `Number(localEndpointPort(...))`, fixing a `===` string/number mismatch that made the MTPLX arm permanently dead), and `idleMinutes` / `keepLoaded` / `savedLaunch` for a status card's reads. `createPm2ExitTail({appName, execPm2, appendLog, lines?, tailLines?})` is the shared "what did the dead process print" diagnosis both `waitForReady` and a manager's own startup-window failure can share. Both mechanisms only — what a launch line means and when a daemon may start is exactly what differs between the two. || `mtplxModels.js` | `services/localCachedModels.js` owns provider-refresh discovery and gates it on runtime readiness without loading the process manager. `listMtplxCachedModels({command?})` → `{models, error}` from `mtplx models --json` (walks local directories — pulls no weights, loads no model, but see `mtplxRuntime.js`: on an un-warmed Homebrew wrapper the spawn ITSELF is a several-hundred-megabyte runtime download, so poll callers must gate on `describeMtplxRuntime().ready` first) `servableMtplxCachedModels(models)` → the rows MTPLX itself calls complete, and `pickMtplxCachedModel(models)` → the one 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. || `mtplxRuntime.js` | `describeMtplxRuntime(binaryPath, {env?})` → `{ready, wrapper, venvPath}` — is MTPLX's own Python runtime on disk, decided by READING the binary rather than running it. Homebrew's `mtplx` is a shell wrapper that lazily bootstraps a version-keyed Python venv (a multi-hundred-megabyte pip install) on its first invocation, and `brew upgrade` re-arms it, so a status poll or an 8s-judged PM2 start is really a package download. This parses the wrapper's own `VENV=` assignment, honours `$MTPLX_BREW_VENV` the way `${MTPLX_BREW_VENV:-…}` does, and tests `<venv>/bin/mtplx` for executability — the wrapper's own `[ ! -x … ]` guard, so the two cannot disagree. Anything unrecognisable (a pip install, a compiled binary, an unparseable script) reports `ready: true, wrapper: false`, i.e. the status quo — never a block over a parse failure. || `slotstreamCatalog.js` | `SLOTSTREAM_CATALOG` — the curated mixture-of-experts checkpoints worth streaming from SSD (the technique only pays off on MoE: a dense model of the same size would stream every layer for every token). `resolveSlotstreamRepo(idOrRepo)` maps a catalog id or an `owner/name` repo id to a repo (null for anything else), `slotstreamModelDirName(repo)` flattens it to the single-segment cache directory whose NAME is the id a start hands `--model`, and `selectSlotstreamRepoFiles(siblings)` picks the `.safetensors`/config/tokenizer files a checkpoint is made of while dropping mirrored `original/`, GGUF, ONNX, and PyTorch copies of the same weights (which can double a 100 GB+ pull) and any name that is not a plain relative path. |diff --git a/server/lib/managedDaemon.js b/server/lib/managedDaemon.jsindex df84aac946..271d318281 100644--- a/server/lib/managedDaemon.js+++ b/server/lib/managedDaemon.js@@ -1,4 +1,5 @@import { getMemoryStats } from './memoryStats.js';+import { localEndpointPort } from './localEndpoint.js';/*** Shared plumbing for a local daemon PortOS runs as an optional PM2 process@@ -212,6 +213,208 @@ export function createDaemonWatcher({};}+/**+ * The last few lines PM2 has for a dead daemon, folded into the manager's own+ * log buffer and summarized alongside the PM2 status word.+ *+ * Shared because `startMtplxServer`'s relaunch-wait loop and+ * `ensureSlotstreamRunning`'s used to diagnose the identical failure two+ * different ways: MTPLX's wait loop tailed the PM2 log (6a9348344, 7480e0476),+ * Slotstream's reported only `PM2 status: errored`. A launch line that dies+ * mid-load deserves the same diagnosis regardless of which daemon it was.+ *+ * @param {{appName: string, execPm2: (args: string[]) => Promise<{stdout?: string, stderr?: string}>, appendLog: (line: string) => void, lines?: number, tailLines?: number}} options+ * @returns {(status: string) => Promise<string>}+ */+export function createPm2ExitTail({ appName, execPm2, appendLog, lines = 15, tailLines = 4 }) {+ return async (status) => {+ const pm2Logs = await execPm2(['logs', appName, '--nostream', '--lines', String(lines)]).catch(() => null);+ const outputLines = `${pm2Logs?.stderr || pm2Logs?.stdout || ''}`.split('\n').map((l) => l.trimEnd()).filter(Boolean);+ for (const line of outputLines) appendLog(line);+ const tail = outputLines.slice(-tailLines).join(' | ');+ return tail ? `PM2 status: ${status} — ${tail}` : `PM2 status: ${status}`;+ };+}++/**+ * Shared on-demand wake mechanism for a local daemon that stops on idle+ * (`registerIdleDaemon` above) and must come back up lazily for the next+ * request. Extracted from `mtplxServerManager.js` and `slotstreamServerManager.js`,+ * which had drifted into two copies with different bugs (#8105): MTPLX's port+ * arm never matched (a string compared with `===` to a number), and only+ * MTPLX's death-detecting readiness loop carried a PM2 log tail.+ *+ * Mechanism only, same contract as `createDaemonWatcher` above: what a launch+ * line MEANS (which knobs it carries, how a saved one merges with a live one)+ * stays in `resolveLaunch`, which each manager supplies.+ *+ * @param {{+ * appName: string,+ * label: string,+ * emoji: string,+ * readSection: () => Promise<object|null>,+ * endpointFor: (config: object|null) => string,+ * probe: (endpoint: string) => Promise<boolean>,+ * start: (config: object) => Promise<object>,+ * stop: () => Promise<unknown>,+ * getStatusStrict: () => Promise<object|null>,+ * clearStatusCache?: () => void,+ * exitTail?: (status: string) => Promise<string>,+ * resolveLaunch: (current: object|null, saved: {model: string|null, port: number|null, raw: object}) => object,+ * getConfig?: () => object|null,+ * sleep: (ms: number) => Promise<void>,+ * getRelaunchReadyTimeoutMs: () => number,+ * getRelaunchPollMs: () => number,+ * }} options+ */+export function createOnDemandDaemon({+ appName,+ label,+ emoji,+ readSection,+ endpointFor,+ probe,+ start,+ stop,+ getStatusStrict,+ clearStatusCache = () => {},+ exitTail,+ resolveLaunch,+ getConfig = () => null,+ sleep,+ getRelaunchReadyTimeoutMs,+ getRelaunchPollMs,+}) {+ // Test seam, same shape as each manager's own `_set*OverrideForTests`: a+ // suite must not depend on whether this developer has an idle window+ // configured. `null` means "read settings"; both live here now rather than+ // in the manager, since `registerIdle` below is what reads them.+ let idleMinutesOverride = null;+ let keepLoadedOverride = null;++ const configuredIdleMinutes = async () => {+ if (idleMinutesOverride !== null) return idleMinutesOverride;+ const section = await readSection();+ const raw = Number(section?.idleMinutes);+ return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 0;+ };++ const configuredKeepLoaded = async () => {+ if (keepLoadedOverride !== null) return keepLoadedOverride;+ const section = await readSection();+ // Legacy fallback: `pinned` was the setting's name before `keepLoaded`.+ return Boolean(section?.keepLoaded ?? section?.pinned);+ };++ const registerIdle = () => {+ registerIdleDaemon({+ name: appName,+ getIdleMs: async () => idleWindowMs(await configuredIdleMinutes()),+ isPinned: async () => configuredKeepLoaded(),+ isRunning: async () => Boolean((await getStatusStrict())?.status === 'online'),+ stop: () => stop(),+ });+ };++ /** The launch line last saved on the settings card, sanitized. */+ const savedLaunchConfig = async () => {+ const section = await readSection();+ const launch = section?.launch || {};+ return {+ model: typeof launch.model === 'string' && launch.model.trim() ? launch.model.trim() : null,+ port: Number.isFinite(Number(launch.port)) ? Number(launch.port) : null,+ // Whatever else the daemon's own knobs need (MTPLX's `tuning`,+ // Slotstream's `memoryGb`) — shaped and normalized by `resolveLaunch`,+ // never generically here, since only the manager knows that shape.+ raw: launch,+ };+ };++ /**+ * Block until the relaunched daemon answers, or until it is proven dead.+ * MTPLX's `waitForRelaunchedEndpoint`, generalized: poll PM2 alongside the+ * endpoint, because "still loading" and "already died" look identical from+ * the endpoint alone and cost wildly different amounts of time to wait out.+ */+ const waitForReady = async (endpoint) => {+ const deadline = Date.now() + getRelaunchReadyTimeoutMs();+ while (Date.now() < deadline) {+ if (await probe(endpoint)) return { ready: true, reason: null };+ clearStatusCache();+ const proc = await getStatusStrict();+ if (proc && ['errored', 'stopped', 'not_found'].includes(proc.status)) {+ const tail = exitTail ? await exitTail(proc.status) : `PM2 status: ${proc.status}`;+ return { ready: false, reason: `${label} exited while loading (${tail})` };+ }+ await sleep(getRelaunchPollMs());+ }+ return { ready: false, reason: `${label} relaunched but never answered on its port` };+ };++ const markUsed = () => markDaemonUsed(appName);++ /**+ * Bring the daemon up if the idle reaper (or the user) stopped it, and mark+ * it used either way. A no-op when already online — the overwhelmingly+ * common case, and it has to stay cheap enough to sit in front of every+ * request: the one PM2 status read it costs is the same read a status poll+ * already does.+ *+ * Resolves `{ ready, reason }` rather than throwing: a caller in front of an+ * inference request wants to report "could not be started" alongside its own+ * error, not have a lazy start unwind its stack.+ */+ const ensureRunning = async () => {+ markUsed();++ const pm2Status = await getStatusStrict();+ 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. `resolveLaunch` sets the+ // precedence: the config recovered from the last live process, then the+ // launch the user saved, then the daemon's own default.+ const saved = await savedLaunchConfig();+ const config = resolveLaunch(getConfig(), saved);++ // Something else is already serving that port — a daemon the user started+ // outside PortOS, or another process entirely. Either way this is not+ // ours to start, and probing beats racing `start` into a port conflict.+ const endpoint = endpointFor(config);+ if (await probe(endpoint)) return { ready: true, reason: null };++ console.log(`${emoji} ${label} is stopped — starting it for an incoming request`);+ const started = await start(config).catch((err) => ({ error: err }));++ if (started.error) return { ready: false, reason: started.error.message };+ // `start` returns as soon as it knows the process did not die on the+ // spot; a multi-gigabyte 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 waitForReady(started.endpoint ?? endpoint);+ };++ /** Is `provider` served by the port THIS daemon's live launch is bound to? */+ const servesPort = (provider, managedPort) =>+ Boolean(managedPort) && Number(localEndpointPort(provider?.endpoint)) === managedPort;++ return {+ ensureRunning,+ markUsed,+ registerIdle,+ waitForReady,+ servesPort,+ // Card-status reads. Kept on the returned object rather than re-declared+ // in the manager — that is exactly the "no longer define+ // configuredIdleMinutes/configuredKeepLoaded" half of #8105.+ idleMinutes: configuredIdleMinutes,+ keepLoaded: configuredKeepLoaded,+ savedLaunch: savedLaunchConfig,+ setIdleMinutesOverrideForTests: (value) => { idleMinutesOverride = value; },+ setKeepLoadedOverrideForTests: (value) => { keepLoadedOverride = value; },+ };+}+// =============================================================================// IDLE REAPER// =============================================================================diff --git a/server/lib/managedDaemon.test.js b/server/lib/managedDaemon.test.jsindex 8e10aeeed3..cb433af0bf 100644--- a/server/lib/managedDaemon.test.js+++ b/server/lib/managedDaemon.test.js@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest';-import { createDaemonWatcher } from './managedDaemon.js';+import { createDaemonWatcher, createOnDemandDaemon, createPm2ExitTail, reapIdleDaemons, _resetIdleDaemonsForTests } from './managedDaemon.js';const makeWatcher = (overrides = {}) => {let config = overrides.config ?? null;@@ -76,3 +76,157 @@ describe('createDaemonWatcher', () => {expect(isPortInUse).toHaveBeenCalledWith(9001);});});++describe('createPm2ExitTail', () => {+ it('folds the PM2 log tail into the manager log buffer and the returned status string', async () => {+ const appended = [];+ const execPm2 = vi.fn(async () => ({ stdout: '', stderr: 'line one\nline two\n' }));+ const exitTail = createPm2ExitTail({ appName: 'example-daemon', execPm2, appendLog: (l) => appended.push(l) });++ const result = await exitTail('errored');++ expect(execPm2).toHaveBeenCalledWith(['logs', 'example-daemon', '--nostream', '--lines', '15']);+ expect(appended).toEqual(['line one', 'line two']);+ expect(result).toBe('PM2 status: errored — line one | line two');+ });++ it('reports a bare status word when PM2 has nothing to say', async () => {+ const exitTail = createPm2ExitTail({+ appName: 'example-daemon',+ execPm2: vi.fn(async () => ({ stdout: '', stderr: '' })),+ appendLog: () => {},+ });++ expect(await exitTail('stopped')).toBe('PM2 status: stopped');+ });+});++describe('createOnDemandDaemon', () => {+ const makeOnDemand = (overrides = {}) => {+ let config = overrides.config ?? null;+ let section = overrides.section ?? {};+ let status = overrides.status ?? { status: 'not_found' };+ const probe = vi.fn(async () => overrides.reachable ?? false);+ const start = overrides.start ?? vi.fn(async () => ({ online: true, endpoint: 'http://127.0.0.1:9100/v1', config: { port: 9100 } }));+ const stop = vi.fn(async () => {});+ const onDemand = createOnDemandDaemon({+ appName: 'example-on-demand',+ label: 'Example',+ emoji: '🧪',+ readSection: async () => section,+ endpointFor: (c) => `http://127.0.0.1:${c?.port ?? 9000}/v1`,+ probe,+ start,+ stop,+ getStatusStrict: async () => status,+ exitTail: overrides.exitTail ?? (async (s) => `PM2 status: ${s}`),+ resolveLaunch: overrides.resolveLaunch ?? ((current, saved) => ({+ port: current?.port ?? saved.port ?? 9000,+ model: current?.model ?? saved.model ?? null,+ })),+ getConfig: () => config,+ sleep: vi.fn(async () => {}),+ getRelaunchReadyTimeoutMs: () => overrides.relaunchReadyTimeoutMs ?? 50,+ getRelaunchPollMs: () => 0,+ });+ return {+ onDemand,+ probe,+ start,+ stop,+ setStatus: (v) => { status = v; },+ setSection: (v) => { section = v; },+ setConfig: (v) => { config = v; },+ };+ };++ it('resolves the numeric port-match arm, fixing the string/number mismatch that made it permanently dead', () => {+ const { onDemand } = makeOnDemand();+ // `localEndpointPort` returns a STRING; comparing it with `===` against a+ // numeric `managedPort` is what made `isMtplxProvider`'s port arm dead+ // since it was added (#8105) — `servesPort` compares numerically instead.+ expect(onDemand.servesPort({ endpoint: 'http://127.0.0.1:8010/v1' }, 8010)).toBe(true);+ expect(onDemand.servesPort({ endpoint: 'http://127.0.0.1:8011/v1' }, 8010)).toBe(false);+ expect(onDemand.servesPort({ endpoint: 'http://127.0.0.1:8010/v1' }, null)).toBe(false);+ });++ it('resolves the launch line via resolveLaunch(current, saved) before probing, live config wins', async () => {+ const { onDemand, probe, setConfig, setSection } = makeOnDemand({ reachable: true });+ setConfig({ port: 9100, model: 'live' });+ setSection({ launch: { port: 9200, model: 'saved' } });++ const result = await onDemand.ensureRunning();++ expect(result).toEqual({ ready: true, reason: null });+ expect(probe).toHaveBeenCalledWith('http://127.0.0.1:9100/v1');+ });++ it('falls back to the saved launch when nothing is live', async () => {+ const { onDemand, probe, setSection } = makeOnDemand({ reachable: true });+ setSection({ launch: { port: 9200, model: 'saved' } });++ await onDemand.ensureRunning();++ expect(probe).toHaveBeenCalledWith('http://127.0.0.1:9200/v1');+ });++ it('waitForReady reports the shared exit-tail diagnosis when the process dies before answering', async () => {+ const { onDemand, setStatus } = makeOnDemand({+ start: vi.fn(async () => ({ online: false, endpoint: 'http://127.0.0.1:9000/v1' })),+ exitTail: async (status) => `PM2 status: ${status} — metal buffer allocation failed`,+ });+ setStatus({ status: 'errored' });++ const result = await onDemand.ensureRunning();++ expect(result).toEqual({+ ready: false,+ reason: 'Example exited while loading (PM2 status: errored — metal buffer allocation failed)',+ });+ });++ it('registerIdle honors a legacy `pinned` setting the same as `keepLoaded`', async () => {+ _resetIdleDaemonsForTests();+ const { onDemand, stop } = makeOnDemand({+ section: { idleMinutes: 1, pinned: true }, // legacy key, no `keepLoaded`+ status: { status: 'online' },+ });+ onDemand.registerIdle();++ const stopped = await reapIdleDaemons(Date.now() + 10 * 60_000);++ expect(stopped).not.toContain('example-on-demand');+ expect(stop).not.toHaveBeenCalled();+ });++ it('registerIdle stops the daemon once its configured idle window elapses and it is not pinned', async () => {+ _resetIdleDaemonsForTests();+ const { onDemand, stop } = makeOnDemand({+ section: { idleMinutes: 1, keepLoaded: false },+ status: { status: 'online' },+ });+ onDemand.registerIdle();++ const stopped = await reapIdleDaemons(Date.now() + 10 * 60_000);++ expect(stopped).toContain('example-on-demand');+ expect(stop).toHaveBeenCalledTimes(1);+ });++ it('the idle-minutes/keep-loaded test overrides win over the section read', async () => {+ _resetIdleDaemonsForTests();+ const { onDemand, stop } = makeOnDemand({+ // The section says "pinned, no window" — the overrides below must win.+ section: { idleMinutes: 0, keepLoaded: true },+ status: { status: 'online' },+ });+ onDemand.setIdleMinutesOverrideForTests(1);+ onDemand.setKeepLoadedOverrideForTests(false);+ onDemand.registerIdle();++ const stopped = await reapIdleDaemons(Date.now() + 10 * 60_000);++ expect(stopped).toContain('example-on-demand');+ expect(stop).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/services/localDaemonLaunchConfig.js b/server/services/localDaemonLaunchConfig.jsnew file mode 100644index 0000000000..6ce0d52b0f--- /dev/null+++ b/server/services/localDaemonLaunchConfig.js@@ -0,0 +1,38 @@+/**+ * Persist the launch line a local on-demand daemon (MTPLX, Slotstream) just+ * started with, so its next on-demand restart — after the idle reaper stops+ * it — replays the SAME configuration instead of falling back to a resolved+ * default.+ *+ * Generalized from `slotstreamServerManager.js`'s original `persistLaunchConfig`+ * (#8105): both managers now call this on every successful start. It lives+ * beside the managers rather than in `lib/managedDaemon.js` because it reaches+ * `services/settings.js`, and that import stays out of the daemon-mechanism+ * lib's graph (see the header of `managedDaemon.js` — `readSection` is+ * injected there for the same reason).+ */++/**+ * @param {{key: string, label: string, launch: object}} options+ * `key` is the `settings.localLlm.<key>` slice this daemon owns+ * ('mtplx' | 'slotstream'). `launch` REPLACES the whole `launch`+ * sub-object — callers supply every field they want kept, the same+ * "replace, don't merge" contract the daemon's own launch line already+ * has, so a field left out of one start does not linger from the last one.+ */+export async function persistDaemonLaunchConfig({ key, label, launch }) {+ const settings = await import('./settings.js').catch(() => null);+ if (!settings?.updateSettingsWith) return;+ await settings.updateSettingsWith((current) => ({+ ...current,+ localLlm: {+ ...current?.localLlm,+ [key]: {+ ...current?.localLlm?.[key],+ launch,+ },+ },+ })).catch((error) => {+ console.error(`❌ ${label}: could not persist the launch line (${error?.message || 'unknown'}); an idle restart will fall back to defaults`);+ });+}diff --git a/server/services/mtplxServerManager.js b/server/services/mtplxServerManager.jsindex 3e6b0eb0a1..15a1920697 100644--- a/server/services/mtplxServerManager.js+++ b/server/services/mtplxServerManager.js@@ -33,7 +33,8 @@ import { LOCAL_RUNTIMES, localEndpointPort, localRuntimeKind, isLocalInstanceEndimport { listMtplxCachedModels, pickMtplxCachedModel } from '../lib/mtplxModels.js';import { describeMtplxRuntime } from '../lib/mtplxRuntime.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';-import { createDaemonWatcher, pm2ArgValue, idleWindowMs, markDaemonUsed, registerIdleDaemon, MTPLX_APP } from '../lib/managedDaemon.js';+import { createDaemonWatcher, createOnDemandDaemon, createPm2ExitTail, pm2ArgValue, MTPLX_APP } from '../lib/managedDaemon.js';+import { persistDaemonLaunchConfig } from './localDaemonLaunchConfig.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@@ -175,6 +176,10 @@ const probeEndpoint = async (endpoint) =>const endpointFor = (config) =>`http://${DEFAULT_HOST}:${config?.port ?? DEFAULT_PORT}/v1`;+// `settings.js` stays a dynamic import here too — see the note at the top of+// this file on why it is never imported statically.+const readSettings = () => import('./settings.js').then((m) => m.getSettings()).catch(() => null);+const daemon = createDaemonWatcher({appName: MTPLX_APP,defaultHost: DEFAULT_HOST,@@ -194,6 +199,39 @@ const daemon = createDaemonWatcher({});const appendLog = daemon.appendLog;+/**+ * The shared on-demand wake mechanism (#8105) — idle-window/keep-loaded reads,+ * the relaunch readiness poll (with the PM2 exit-log tail), and the numeric+ * port-match arm `isMtplxProvider` layers its `localRuntimeKind` check on top+ * of. What a launch line MEANS stays here, in `resolveLaunch`: the precedence+ * is the live process's recovered config, then the launch line last saved on+ * the MTPLX card (now including `tuning`, so an idle stop no longer forgets+ * an assessment relaunch's tuning), then the daemon's own default.+ */+const onDemand = createOnDemandDaemon({+ appName: MTPLX_APP,+ label: 'MTPLX',+ emoji: '🚄',+ readSection: () => readSettings().then((settings) => settings?.localLlm?.mtplx ?? null),+ endpointFor,+ probe: probeEndpoint,+ start: (config) => startMtplxServer(config),+ stop: () => stopMtplxServer(),+ getStatusStrict: () => getAppStatusStrict(MTPLX_APP),+ clearStatusCache: () => clearJlistCache(),+ exitTail: createPm2ExitTail({ appName: MTPLX_APP, execPm2: (...args) => execPm2(...args), appendLog }),+ resolveLaunch: (current, saved) => ({+ port: current?.port ?? saved.port ?? DEFAULT_PORT,+ model: current?.model ?? saved.model ?? null,+ tuning: current?.tuning ?? normalizeTuning('mtplx', saved.raw?.tuning),+ }),+ getConfig: () => currentConfig,+ sleep,+ getRelaunchReadyTimeoutMs: () => relaunchReadyTimeoutMs,+ getRelaunchPollMs: () => relaunchPollMs,+});+onDemand.registerIdle();+/*** Reconstructs the launch config from PM2 process args when PortOS restarted* while the PM2 process stayed online — same recovery `llamaServerManager` does,@@ -260,50 +298,10 @@ const withinDeclaredRange = (spec, raw) => {const waitForPortRelease = daemon.waitForPortRelease;-/**- * Block until the relaunched server answers, or until it is proven dead.- *- * Polls PM2 alongside the endpoint, because the two failures look identical from- * the endpoint alone and cost wildly different amounts of time. `mtplx serve`- * accepts a `--context-window` far past what the machine can hold, then dies- * partway through loading the checkpoint — well after `startMtplxServer`'s short- * startup window has already returned. Waiting the full readiness budget out on- * a process PM2 has already marked `errored` would leave the install's `mtplx`- * provider down for minutes per bad launch line, and a tuning sweep is EXPECTED- * to produce bad launch lines.- *- * Resolves `{ ready, reason }` — and the two not-ready cases carry DIFFERENT- * reasons, because they send the user to different places. A process PM2 marks- * `errored` printed something on the way out, and that tail is the whole- * diagnosis ("metal buffer allocation failed"); reporting it as "never answered- * on its port" would throw away the one fact that explains the failure.- */-async function waitForRelaunchedEndpoint(endpoint) {- const deadline = Date.now() + relaunchReadyTimeoutMs;- while (Date.now() < deadline) {- if (await probeEndpoint(endpoint)) return { ready: true, reason: null };- clearJlistCache();- const proc = await getAppStatusStrict(MTPLX_APP);- if (proc && ['errored', 'stopped', 'not_found'].includes(proc.status)) {- return { ready: false, reason: `MTPLX exited while loading (${await exitTail(proc.status)})` };- }- await sleep(relaunchPollMs);- }- return { ready: false, reason: 'MTPLX relaunched but never answered on its port' };-}--/**- * The last few lines the dead process printed, appended to its PM2 status —- * the same tail `startMtplxServer` surfaces for a server that dies inside its- * startup window, so a launch line that fails later is diagnosed the same way.- */-async function exitTail(status) {- const pm2Logs = await execPm2(['logs', MTPLX_APP, '--nostream', '--lines', '15']).catch(() => null);- const lines = `${pm2Logs?.stderr || pm2Logs?.stdout || ''}`.split('\n').map((l) => l.trimEnd()).filter(Boolean);- for (const line of lines) appendLog(line);- const tail = lines.slice(-4).join(' | ');- return tail ? `PM2 status: ${status} — ${tail}` : `PM2 status: ${status}`;-}+// `waitForRelaunchedEndpoint` (the death-detecting readiness poll) and its+// `exitTail` PM2 log-tail helper now live in `lib/managedDaemon.js` as+// `onDemand.waitForReady` — shared with `slotstreamServerManager.js`, whose+// copy of the same loop reported only a bare PM2 status word (#8105)./** Resolve the `mtplx` executable on the child-process PATH. */const resolveMtplxBinary = () => findCommandOnPath('mtplx');@@ -365,11 +363,11 @@ export async function getMtplxServerStatus() {// an untuned server, and for one PortOS does not manage — it cannot read// another process's launch line.tuningFlags: base.managed === true ? launchArgs('mtplx', currentConfig?.tuning) : [],- idleMinutes: await configuredIdleMinutes(),- keepLoaded: await configuredKeepLoaded(),+ idleMinutes: await onDemand.idleMinutes(),+ keepLoaded: await onDemand.keepLoaded(),// 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(),+ launch: await onDemand.savedLaunch().then(({ model, port }) => ({ model, port })),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@@ -602,6 +600,16 @@ export async function startMtplxServer(options = {}) {);}+ // Persist the launch line every successful start used — including `tuning` —+ // so the next on-demand restart (after an idle stop) replays exactly this+ // configuration instead of falling back to a resolved default. Additive+ // field: an older install's saved launch simply has no `tuning` key, which+ // `onDemand`'s `resolveLaunch` reads as untuned. Fixes the bug Slotstream's+ // own `persistLaunchConfig` did not have: MTPLX used to forget a tuning+ // applied through an assessment relaunch the moment the idle reaper stopped+ // it (#8105).+ await persistDaemonLaunchConfig({ key: 'mtplx', label: 'MTPLX', launch: { port, model, tuning: normalizedTuning } });+const finalProc = await getAppStatusStrict(MTPLX_APP);return {success: true,@@ -755,7 +763,7 @@ export async function relaunchMtplxServerWithTuning(tuning = {}) {// waits only long enough to catch a server that dies immediately, and a cold// MLX checkpoint takes far longer than that to load. So `online: false` here// is "not ready YET", not "wedged"; give it the real readiness budget first.- const ready = started.online ? { ready: true, reason: null } : await waitForRelaunchedEndpoint(started.endpoint);+ const ready = started.online ? { ready: true, reason: null } : await onDemand.waitForReady(started.endpoint);if (ready.ready) return { applied: true, reason: null, config: started.config };// Treat it exactly like a rejected launch line: put the previous configuration@@ -810,7 +818,7 @@ async function restorePrevious(previous, failure) {}if (!restored) return null;if (restored.online) return restored.config;- const back = await waitForRelaunchedEndpoint(restored.endpoint);+ const back = await onDemand.waitForReady(restored.endpoint);if (back.ready) return restored.config;console.error(`❌ MTPLX: the restored configuration ${back.reason}`);return null;@@ -827,8 +835,8 @@ export function _resetMtplxServerStateForTests({keepLoaded = null,logFiles,} = {}) {- idleMinutesOverride = idleMinutes;- keepLoadedOverride = keepLoaded;+ onDemand.setIdleMinutesOverrideForTests(idleMinutes);+ onDemand.setKeepLoadedOverrideForTests(keepLoaded);mtplxLogFiles = logFiles ? {stdout: logFiles.stdout || DEFAULT_MTPLX_LOG_FILES.stdout,stderr: logFiles.stderr || DEFAULT_MTPLX_LOG_FILES.stderr,@@ -846,7 +854,7 @@ export function _resetMtplxServerStateForTests({// Test hook for pinningexport function _setMtplxKeepLoadedOverrideForTests(val) {- keepLoadedOverride = val;+ onDemand.setKeepLoadedOverrideForTests(val);}// =============================================================================@@ -865,120 +873,24 @@ export function _setMtplxKeepLoadedOverrideForTests(val) {** `llamaServerManager` deliberately takes the other path (`--sleep-idle-seconds`),* because llama.cpp CAN unload in place — see `supportsSleepIdle` there.+ *+ * The idle-minutes/keep-loaded reads, the `registerIdleDaemon` registration,+ * `savedLaunchConfig`, `markMtplxUsed`, and `ensureMtplxRunning` all now live in+ * `onDemand` (`lib/managedDaemon.js`'s `createOnDemandDaemon`) — see #8105.*/-/**- * 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;-let keepLoadedOverride = 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;-}--async function configuredKeepLoaded() {- if (keepLoadedOverride !== null) return keepLoadedOverride;- const settings = await readSettings();- return Boolean(settings?.localLlm?.mtplx?.keepLoaded ?? settings?.localLlm?.mtplx?.pinned);-}--// 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()),- isPinned: async () => configuredKeepLoaded(),- isRunning: async () => Boolean((await getAppStatusStrict(MTPLX_APP))?.status === 'online'),- 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);+export const markMtplxUsed = () => onDemand.markUsed();/*** 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.+ * either way. See `onDemand.ensureRunning` for the shared mechanism; MTPLX's+ * own contribution is the `resolveLaunch` hook wired above, which carries+ * `tuning` alongside `port`/`model`.** @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);-}+export const ensureMtplxRunning = () => onDemand.ensureRunning();/*** Is this provider served by the MTPLX daemon PortOS manages?@@ -1009,8 +921,11 @@ export function isMtplxProvider(provider) {// MANAGED daemon's live port, which only this module tracks, and reading it// from `localProviderRuntime.js` (a side-effect-free module every readiness// check imports) would be a circular import back to this one.- const managedPort = currentConfig?.port;- return Boolean(managedPort) && localEndpointPort(provider.endpoint) === managedPort;+ //+ // `onDemand.servesPort` compares numerically (#8105) — `localEndpointPort`+ // returns a STRING, and comparing that with `===` against the numeric+ // `managedPort` was permanently false, so this arm never matched.+ return onDemand.servesPort(provider, currentConfig?.port);}/**diff --git a/server/services/mtplxServerManager.test.js b/server/services/mtplxServerManager.test.jsindex 66a070b566..9810b41f5e 100644--- a/server/services/mtplxServerManager.test.js+++ b/server/services/mtplxServerManager.test.js@@ -947,6 +947,47 @@ describe('mtplxServerManager', () => {});});+ describe('surviving an idle-reaper stop (#8105)', () => {+ // Bug #2 from the issue: `stopMtplxServer` clears `currentConfig`, and the+ // saved launch line used to hold only `model`/`port` — an assessment's+ // tuning relaunch was silently lost the moment the reaper stopped MTPLX.+ // Slotstream already persisted its own knob (`memoryGb`); MTPLX now does+ // the same for `tuning`, through the same shared `persistDaemonLaunchConfig`.+ it('relaunches with the same tuning it was started with after the idle reaper stops it', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ resetForTest({ idleMinutes: 1, keepLoaded: false });++ // Real `settings.js` writes are refused outside a test's own isolated+ // data root (see `testDataIsolation.js`) — spy the two calls the manager+ // makes onto an in-memory store, the same seam the "probes the saved+ // port" test above uses for reads.+ const settings = await import('./settings.js');+ let store = {};+ vi.spyOn(settings, 'getSettings').mockImplementation(async () => store);+ vi.spyOn(settings, 'updateSettingsWith').mockImplementation(async (mutate) => {+ store = await mutate(store);+ return store;+ });++ await startMtplxServer({ port: 8010, tuning: { depth: 5, kvQuant: 'q4' } });+ execPm2Calls = [];++ const { reapIdleDaemons } = await import('../lib/managedDaemon.js');+ const stopped = await reapIdleDaemons(Date.now() + 10 * 60_000);+ expect(stopped).toContain(MTPLX_APP);+ expect(pm2State).toBeNull();++ await ensureMtplxRunning();++ const start = execPm2Calls.find((args) => args[0] === 'start');+ const relaunchArgs = start.slice(start.indexOf('--') + 1);+ expect(relaunchArgs[relaunchArgs.indexOf('--port') + 1]).toBe('8010');+ expect(relaunchArgs[relaunchArgs.indexOf('--model') + 1]).toBe('Example/Qwen-MTP');+ expect(relaunchArgs[relaunchArgs.indexOf('--depth') + 1]).toBe('5');+ expect(relaunchArgs[relaunchArgs.indexOf('--kv-quant') + 1]).toBe('q4');+ });+ });+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);@@ -965,6 +1006,18 @@ describe('mtplxServerManager', () => {it('matches an MTPLX-backed TUI provider', () => {expect(isMtplxProvider({ type: 'tui', endpoint: 'http://127.0.0.1:8000/v1', id: 'mtplx-tui', mtplxBacked: true })).toBe(true);});++ // Regression for #8105: `localEndpointPort` returns a STRING, and the port+ // arm used to compare it with `===` against the numeric `currentConfig.port`+ // — always false, so an unnamed/unmarked provider pointed at wherever the+ // managed daemon is actually listening was never recognized.+ it('matches a bare endpoint pointed at the port the managed daemon is actually serving', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ await startMtplxServer({ port: 8010 });++ expect(isMtplxProvider({ type: 'api', endpoint: 'http://127.0.0.1:8010/v1' })).toBe(true);+ expect(isMtplxProvider({ type: 'api', endpoint: 'http://127.0.0.1:8011/v1' })).toBe(false);+ });});/**diff --git a/server/services/slotstreamServerManager.js b/server/services/slotstreamServerManager.jsindex aa2f983746..48022c02db 100644--- a/server/services/slotstreamServerManager.js+++ b/server/services/slotstreamServerManager.js@@ -24,12 +24,12 @@ import { sleep } from '../lib/fileUtils.js';import { LOCAL_RUNTIMES, localEndpointPort, localRuntimeKind, isLocalInstanceEndpoint } from '../lib/localProviderRuntime.js';import {createDaemonWatcher,+ createOnDemandDaemon,+ createPm2ExitTail,pm2ArgValue,- idleWindowMs,- markDaemonUsed,- registerIdleDaemon,SLOTSTREAM_APP,} from '../lib/managedDaemon.js';+import { persistDaemonLaunchConfig } from './localDaemonLaunchConfig.js';import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';import { isAppleSilicon, isPortInUse } from '../lib/platform.js';import { PORTS } from '../lib/ports.js';@@ -111,6 +111,39 @@ const daemon = createDaemonWatcher({});const appendLog = daemon.appendLog;+// `settings.js` reached only through a dynamic import — see the note beside+// `mtplxServerManager.js`'s copy of this same pattern.+const readSettings = () => import('./settings.js').then((m) => m.getSettings()).catch(() => null);++/**+ * The shared on-demand wake mechanism (#8105) — see the identical block in+ * `mtplxServerManager.js` for the full contract. `resolveLaunch` here carries+ * `memoryGb` instead of `tuning`.+ */+const onDemand = createOnDemandDaemon({+ appName: SLOTSTREAM_APP,+ label: 'Slotstream',+ emoji: '🌊',+ readSection: () => readSettings().then((settings) => settings?.localLlm?.slotstream ?? null),+ endpointFor,+ probe: probeEndpoint,+ start: (config) => startSlotstreamServer(config),+ stop: () => stopSlotstreamServer(),+ getStatusStrict: () => getAppStatusStrict(SLOTSTREAM_APP),+ clearStatusCache: () => clearJlistCache(),+ exitTail: createPm2ExitTail({ appName: SLOTSTREAM_APP, execPm2: (...args) => execPm2(...args), appendLog }),+ resolveLaunch: (current, saved) => ({+ port: current?.port ?? saved.port ?? DEFAULT_PORT,+ model: current?.model ?? saved.model ?? null,+ memoryGb: current?.memoryGb ?? (Number.isFinite(Number(saved.raw?.memoryGb)) ? Number(saved.raw.memoryGb) : null),+ }),+ getConfig: () => currentConfig,+ sleep,+ getRelaunchReadyTimeoutMs: () => relaunchReadyTimeoutMs,+ getRelaunchPollMs: () => relaunchPollMs,+});+onDemand.registerIdle();+/*** Reconstructs the launch config from PM2 process args when PortOS restarted* while the PM2 process stayed online.@@ -166,8 +199,8 @@ export async function getSlotstreamServerStatus() {...base,supported,unsupportedReason: supported ? null : SLOTSTREAM_UNSUPPORTED_REASON,- idleMinutes: await configuredIdleMinutes(),- keepLoaded: await configuredKeepLoaded(),+ idleMinutes: await onDemand.idleMinutes(),+ keepLoaded: await onDemand.keepLoaded(),launch: saved,memoryPlan,cachedModels: (cache.models || []).map((m) => m?.id).filter(Boolean),@@ -360,7 +393,11 @@ export async function startSlotstreamServer(options = {}) {);}- await persistLaunchConfig({ port, model, memoryGb: plan.auto ? null : plan.targetGb });+ // `memoryGb` stays the user's *override* (null when PortOS sized it), never+ // the resolved target — `--memory-gb` is always on the launch line, so the+ // saved override is the only thing that can tell an auto-sized 85.8 GB from+ // one the user typed apart later.+ await persistDaemonLaunchConfig({ key: 'slotstream', label: 'Slotstream', launch: { port, model, memoryGb: plan.auto ? null : plan.targetGb } });const finalProc = await getAppStatusStrict(SLOTSTREAM_APP);return {@@ -409,8 +446,8 @@ export function _resetSlotstreamServerStateForTests({keepLoaded = null,logFiles,} = {}) {- idleMinutesOverride = idleMinutes;- keepLoadedOverride = keepLoaded;+ onDemand.setIdleMinutesOverrideForTests(idleMinutes);+ onDemand.setKeepLoadedOverrideForTests(keepLoaded);slotstreamLogFiles = logFiles ? {stdout: logFiles.stdout || DEFAULT_SLOTSTREAM_LOG_FILES.stdout,stderr: logFiles.stderr || DEFAULT_SLOTSTREAM_LOG_FILES.stderr,@@ -426,118 +463,43 @@ export function _resetSlotstreamServerStateForTests({// Test hook for pinningexport function _setSlotstreamKeepLoadedOverrideForTests(val) {- keepLoadedOverride = val;-}--const readSettings = () => import('./settings.js').then((m) => m.getSettings()).catch(() => null);-let idleMinutesOverride = null;-let keepLoadedOverride = null;--async function configuredIdleMinutes() {- if (idleMinutesOverride !== null) return idleMinutesOverride;- const settings = await readSettings();- const raw = Number(settings?.localLlm?.slotstream?.idleMinutes);- return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 0;-}--async function configuredKeepLoaded() {- if (keepLoadedOverride !== null) return keepLoadedOverride;- const settings = await readSettings();- return Boolean(settings?.localLlm?.slotstream?.keepLoaded ?? settings?.localLlm?.slotstream?.pinned);+ onDemand.setKeepLoadedOverrideForTests(val);}-registerIdleDaemon({- name: SLOTSTREAM_APP,- getIdleMs: async () => idleWindowMs(await configuredIdleMinutes()),- isPinned: async () => configuredKeepLoaded(),- isRunning: async () => Boolean((await getAppStatusStrict(SLOTSTREAM_APP))?.status === 'online'),- stop: () => stopSlotstreamServer(),-});-+/**+ * The launch line last saved on the Slotstream card, for a lazy start to+ * replay — including the `memoryGb` override, the one field the shared+ * `onDemand.savedLaunch()` (model/port only) does not sanitize on its own.+ */async function savedLaunchConfig() {- const settings = await readSettings();- const launch = settings?.localLlm?.slotstream?.launch;+ const { model, port, raw } = await onDemand.savedLaunch();return {- model: typeof launch?.model === 'string' && launch.model.trim() ? launch.model.trim() : null,- port: Number.isFinite(Number(launch?.port)) ? Number(launch.port) : null,- memoryGb: Number.isFinite(Number(launch?.memoryGb)) ? Number(launch.memoryGb) : null,+ model,+ port,+ memoryGb: Number.isFinite(Number(raw?.memoryGb)) ? Number(raw.memoryGb) : null,};}-/**- * Record the launch a start actually used, so the on-demand restart after an- * idle release replays it.- *- * Without this an explicit memory cap lives only in `currentConfig`, which- * `stopSlotstreamServer` clears — so the reaper would silently trade the cap- * the user chose for an auto-sized target on the next request. `memoryGb` stays- * the user's *override* (null when PortOS sized it), never the resolved target,- * so a later status still knows which of the two it is looking at.- */-async function persistLaunchConfig({ port, model, memoryGb }) {- const settings = await import('./settings.js').catch(() => null);- if (!settings?.updateSettingsWith) return;- await settings.updateSettingsWith((current) => ({- ...current,- localLlm: {- ...current?.localLlm,- slotstream: {- ...current?.localLlm?.slotstream,- launch: { port, model, memoryGb },- },- },- })).catch((error) => {- console.error(`❌ Slotstream: could not persist the launch line (${error?.message || 'unknown'}); an idle restart will re-size from host RAM`);- });-}--export const markSlotstreamUsed = () => markDaemonUsed(SLOTSTREAM_APP);+// `registerIdleDaemon`, the idle-minutes/keep-loaded reads, `markSlotstreamUsed`,+// and `ensureSlotstreamRunning` all now live in `onDemand` (#8105) — see the+// identical block in `mtplxServerManager.js`.+export const markSlotstreamUsed = () => onDemand.markUsed();/**- * Bring Slotstream up if the idle reaper (or the user) stopped it.+ * Bring Slotstream up if the idle reaper (or the user) stopped it. See+ * `onDemand.ensureRunning` for the shared mechanism; Slotstream's own+ * contribution is the `resolveLaunch` hook wired above, which carries+ * `memoryGb` alongside `port`/`model`.** @returns {Promise<{ready: boolean, reason: string|null}>}*/-export async function ensureSlotstreamRunning() {- markSlotstreamUsed();-- const pm2Status = await getAppStatusStrict(SLOTSTREAM_APP);- if (pm2Status?.status === 'online') return { ready: true, reason: null };-- const saved = await savedLaunchConfig();- const config = {- port: currentConfig?.port ?? saved.port ?? DEFAULT_PORT,- model: currentConfig?.model ?? saved.model ?? null,- memoryGb: currentConfig?.memoryGb ?? saved.memoryGb ?? null,- };-- const endpoint = endpointFor(config);- if (await probeEndpoint(endpoint)) return { ready: true, reason: null };-- console.log(`🌊 Slotstream is stopped — starting it for an incoming request`);- const started = await startSlotstreamServer(config).catch((err) => ({ error: err }));- if (started.error) return { ready: false, reason: started.error.message };- if (started.online) return { ready: true, reason: null };-- const deadline = Date.now() + relaunchReadyTimeoutMs;- while (Date.now() < deadline) {- if (await probeEndpoint(started.endpoint ?? endpoint)) return { ready: true, reason: null };- clearJlistCache();- const proc = await getAppStatusStrict(SLOTSTREAM_APP);- if (proc && ['errored', 'stopped', 'not_found'].includes(proc.status)) {- return { ready: false, reason: `Slotstream exited while loading (PM2 status: ${proc.status})` };- }- await sleep(relaunchPollMs);- }- return { ready: false, reason: 'Slotstream relaunched but never answered on its port' };-}+export const ensureSlotstreamRunning = () => onDemand.ensureRunning();export function isSlotstreamProvider(provider) {if (!provider || !['api', 'tui'].includes(provider.type)) return false;if (!isLocalInstanceEndpoint(provider.endpoint)) return false;if (localRuntimeKind(provider) === 'slotstream') return true;- const managedPort = currentConfig?.port;- return Boolean(managedPort) && Number(localEndpointPort(provider.endpoint)) === managedPort;+ return onDemand.servesPort(provider, currentConfig?.port);}/**diff --git a/server/services/slotstreamServerManager.test.js b/server/services/slotstreamServerManager.test.jsindex 249e1f7872..1b2cbaa519 100644--- a/server/services/slotstreamServerManager.test.js+++ b/server/services/slotstreamServerManager.test.js@@ -306,6 +306,35 @@ describe('slotstreamServerManager', () => {expect(result.ready).toBe(false);expect(result.reason).toMatch(/not found/);});++ // Regression for #8105: the death-detecting readiness loop used to be a+ // hand-rolled copy that reported only a bare `PM2 status: errored` — MTPLX's+ // copy of the same loop already tailed the PM2 log, and the two have drifted+ // back together onto `onDemand.waitForReady`'s shared `exitTail`.+ it('reports the PM2 log tail when it dies after startup but before it answers', async () => {+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(BINARY);+ // Skip `startSlotstreamServer`'s own startup-window poll (deadline+ // immediately in the past) so the ONLY readiness loop exercised is the+ // shared one `ensureSlotstreamRunning` waits on afterward.+ resetForTest({ startupWait: 0 });+ vi.spyOn(openAiModelsProbe, 'probeOpenAiModels').mockResolvedValue({ reachable: false });+ // Errored throughout — including the initial guards — so this cannot start+ // a REAL managed process the assertions below have to unwind.+ vi.spyOn(pm2Module, 'getAppStatusStrict').mockImplementation(async (name) => (+ name === SLOTSTREAM_APP ? { name, status: 'errored', pid: null } : { name, status: 'not_found', pm2_env: null }+ ));+ vi.spyOn(pm2Module, 'execPm2').mockImplementation(async (args) => {+ execPm2Calls.push(args);+ if (args[0] === 'logs') return { stdout: '', stderr: 'metal buffer allocation failed' };+ return { stdout: '', stderr: '' };+ });++ const result = await ensureSlotstreamRunning();++ expect(result.ready).toBe(false);+ expect(result.reason).toMatch(/errored/);+ expect(result.reason).toMatch(/metal buffer allocation failed/);+ });});describe('isSlotstreamProvider', () => {