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
refactor: share managed daemon lifecycle watcher (#4887)
[._.]/ Adam Eivyb56a9b1705b3
diff --git a/server/lib/README.md b/server/lib/README.mdindex e3d7306935..e11fd5258e 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -143,7 +143,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`). Owns their PM2 process names — `LLAMA_APP`, `MTPLX_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 the two names. `isModelServerProcess` is why per-process memory policing skips them: their RSS is the checkpoint they loaded, so they clear any generic cap the moment they come up. `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. |+| `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`). Owns their PM2 process names — `LLAMA_APP`, `MTPLX_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 the two 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, 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/managedDaemon.js b/server/lib/managedDaemon.jsindex 2eab6d8747..9f89b8b14e 100644--- a/server/lib/managedDaemon.js+++ b/server/lib/managedDaemon.js@@ -114,6 +114,98 @@ export function pm2ArgValue(args, flag) {return idx !== -1 && idx + 1 < list.length ? list[idx + 1] : null;}+/**+ * Shared watcher for a local daemon PortOS owns through PM2.+ *+ * Managers supply their daemon-specific launch-line parser and endpoint probe;+ * the watcher owns the common PM2 adoption, status skeleton, bounded logs, and+ * stop-then-relaunch port-release wait. State remains in the manager through+ * `getConfig` / `setConfig`, so install and tuning paths can keep their domain+ * rules without reaching into this mechanism.+ *+ * Dependency callbacks are explicit both to keep this module side-effect free+ * and to preserve the managers' existing test seams around PM2 and networking.+ */+export function createDaemonWatcher({+ appName,+ defaultHost = '127.0.0.1',+ defaultPort,+ endpointFor,+ parseConfigFromArgs,+ probe,+ isPortInUse,+ sleep,+ getConfig,+ setConfig,+ getLastExitError,+ getAppStatus,+ getSavedProcessNames,+ execPm2,+ getPortReleaseTimeoutMs,+ preserveConfigOnReadFailure = false,+ maxLogLines,+}) {+ const logs = createDaemonLogBuffer({ maxLines: maxLogLines });++ const recoverConfig = (pm2Status) => {+ const current = getConfig();+ if (current || pm2Status?.status !== 'online' || !pm2Status.args) return current;+ const recovered = parseConfigFromArgs(pm2Status.args);+ setConfig(recovered);+ return recovered;+ };++ const readLaunch = async () => {+ const pm2Status = await getAppStatus(appName);+ if (pm2Status === null) return { managed: false, config: null, readFailed: true };+ if (pm2Status.status !== 'online') return { managed: false, config: null, readFailed: false };+ return { managed: true, config: recoverConfig(pm2Status), readFailed: false };+ };++ const endpoint = () => endpointFor(getConfig());++ const getStatusBase = async ({ installed }) => {+ const [pm2Status, savedApps] = await Promise.all([getAppStatus(appName), getSavedProcessNames()]);+ const isReadFailed = pm2Status === null;+ const isManagedActive = pm2Status?.status === 'online';+ const config = recoverConfig(pm2Status);+ const resolvedEndpoint = endpointFor(config);+ const reachable = await probe(resolvedEndpoint);+ const pm2Logs = pm2Status && pm2Status.status !== 'not_found'+ ? await execPm2(['logs', appName, '--nostream', '--lines', String(logs.maxLines)]).catch(() => null)+ : null;++ return {+ installed,+ running: isManagedActive || reachable,+ managed: isReadFailed ? null : isManagedActive,+ pid: isManagedActive ? (pm2Status.pid || null) : null,+ host: config?.host || defaultHost,+ port: config?.port ?? defaultPort,+ endpoint: resolvedEndpoint,+ config: isManagedActive || (isReadFailed && preserveConfigOnReadFailure) ? config : null,+ runAtStartup: savedApps === null ? null : savedApps.includes(appName),+ recentLogs: logs.withPm2Logs(`${pm2Logs?.stdout || ''}\n${pm2Logs?.stderr || ''}`),+ lastExitError: isReadFailed ? 'Failed to read PM2 status' : getLastExitError(),+ };+ };++ const waitForPortRelease = async (port) => {+ const deadline = Date.now() + getPortReleaseTimeoutMs();+ while (Date.now() < deadline && await isPortInUse(port)) await sleep(200);+ };++ return {+ appendLog: logs.append,+ endpoint,+ getStatusBase,+ readLaunch,+ resetLogs: logs.reset,+ snapshotLogs: logs.snapshot,+ waitForPortRelease,+ };+}+// =============================================================================// IDLE REAPER// =============================================================================diff --git a/server/lib/managedDaemon.test.js b/server/lib/managedDaemon.test.jsnew file mode 100644index 0000000000..8e10aeeed3--- /dev/null+++ b/server/lib/managedDaemon.test.js@@ -0,0 +1,78 @@+import { describe, expect, it, vi } from 'vitest';+import { createDaemonWatcher } from './managedDaemon.js';++const makeWatcher = (overrides = {}) => {+ let config = overrides.config ?? null;+ const getAppStatus = vi.fn(async () => Object.hasOwn(overrides, 'pm2Status')+ ? overrides.pm2Status+ : { status: 'online', pid: 42, args: ['--port', '9001'] });+ const execPm2 = vi.fn(async () => ({ stdout: 'pm2 output', stderr: '' }));+ const isPortInUse = vi.fn(async () => false);+ const probe = vi.fn(async () => overrides.reachable ?? false);+ const watcher = createDaemonWatcher({+ appName: 'example-daemon',+ defaultPort: 9000,+ endpointFor: (value) => `http://127.0.0.1:${value?.port ?? 9000}/v1`,+ parseConfigFromArgs: (args) => ({ port: Number(args[args.indexOf('--port') + 1]) }),+ probe,+ isPortInUse,+ sleep: vi.fn(async () => {}),+ getConfig: () => config,+ setConfig: (value) => { config = value; },+ getLastExitError: () => null,+ getAppStatus,+ getSavedProcessNames: vi.fn(async () => ['example-daemon']),+ execPm2,+ getPortReleaseTimeoutMs: () => 5_000,+ ...overrides.options,+ });+ return { watcher, getAppStatus, execPm2, isPortInUse, probe, getConfig: () => config };+};++describe('createDaemonWatcher', () => {+ it('re-adopts a live PM2 launch line and builds the shared status fields', async () => {+ const { watcher, execPm2, probe, getConfig } = makeWatcher();++ const status = await watcher.getStatusBase({ installed: true });++ expect(getConfig()).toEqual({ port: 9001 });+ expect(status).toMatchObject({+ installed: true,+ running: true,+ managed: true,+ pid: 42,+ port: 9001,+ endpoint: 'http://127.0.0.1:9001/v1',+ config: { port: 9001 },+ runAtStartup: true,+ recentLogs: ['pm2 output'],+ lastExitError: null,+ });+ expect(probe).toHaveBeenCalledWith('http://127.0.0.1:9001/v1');+ expect(execPm2).toHaveBeenCalledWith(['logs', 'example-daemon', '--nostream', '--lines', '100']);+ });++ it('keeps an unreadable PM2 distinct from a confirmed missing process', async () => {+ const { watcher } = makeWatcher({+ config: { port: 9002 },+ pm2Status: null,+ options: { preserveConfigOnReadFailure: true },+ });++ await expect(watcher.getStatusBase({ installed: true })).resolves.toMatchObject({+ managed: null,+ config: { port: 9002 },+ lastExitError: 'Failed to read PM2 status',+ });+ });++ it('waits until a stopped daemon releases its port', async () => {+ const { watcher, isPortInUse } = makeWatcher();+ isPortInUse.mockResolvedValueOnce(true).mockResolvedValueOnce(false);++ await watcher.waitForPortRelease(9001);++ expect(isPortInUse).toHaveBeenCalledTimes(2);+ expect(isPortInUse).toHaveBeenCalledWith(9001);+ });+});diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.jsindex 8522516424..6ec8a1782f 100644--- a/server/services/llamaServerManager.js+++ b/server/services/llamaServerManager.js@@ -11,7 +11,7 @@ import { spawn } from '../lib/childProcess.js';import { commandExists } from '../lib/commandExists.js';import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';import { expandHome, sleep } from '../lib/fileUtils.js';-import { createDaemonLogBuffer, pm2ArgValue, LLAMA_APP } from '../lib/managedDaemon.js';+import { createDaemonWatcher, pm2ArgValue, LLAMA_APP } from '../lib/managedDaemon.js';import { execFile } from '../lib/childProcess.js';import { resolveSpecModelPath } from './specDecodeModels.js';import { parseSpecTypes, isDraftSpecType } from '../lib/specDecodePresets.js';@@ -77,8 +77,6 @@ let currentConfig = null;// cannot tell a PortOS tuning apart from the same flags typed by the user.let preTuningConfig = null;let lastExitError = null;-const logs = createDaemonLogBuffer();-const appendLog = logs.append;/*** Probes whether an OpenAI-compatible endpoint responds at the given host/port.@@ -234,6 +232,25 @@ function parseConfigFromArgs(args) {const endpointFor = (config) =>`http://${config?.host || '127.0.0.1'}:${config?.port ?? PORTS.LLAMA_SERVER}/v1`;+const daemon = createDaemonWatcher({+ appName: LLAMA_APP,+ defaultPort: PORTS.LLAMA_SERVER,+ endpointFor,+ parseConfigFromArgs,+ probe: probeEndpoint,+ isPortInUse: (...args) => isPortInUse(...args),+ sleep,+ getConfig: () => currentConfig,+ setConfig: (config) => { currentConfig = config; },+ getLastExitError: () => lastExitError,+ getAppStatus: (...args) => getAppStatusStrict(...args),+ getSavedProcessNames: (...args) => getSavedProcessNames(...args),+ execPm2: (...args) => execPm2(...args),+ getPortReleaseTimeoutMs: () => PORT_RELEASE_TIMEOUT_MS,+ preserveConfigOnReadFailure: true,+});+const appendLog = daemon.appendLog;+/*** Just the base URL llama-server is serving on — no endpoint probe, no PM2 log* fetch.@@ -252,7 +269,7 @@ export async function getLlamaServerEndpoint() {// Reconstructs `currentConfig` from PM2's args as a side effect when PortOS// restarted under a still-running daemon — see `readLlamaServerLaunch`.if (!currentConfig) await readLlamaServerLaunch();- return endpointFor(currentConfig);+ return daemon.endpoint();}/**@@ -262,48 +279,12 @@ export async function getLlamaServerStatus() {const binaryPath = resolveLlamaServerBinary();const installed = Boolean(binaryPath);- const [pm2Status, savedApps] = await Promise.all([getAppStatusStrict(LLAMA_APP), getSavedProcessNames()]);- const isReadFailed = pm2Status === null;- const isManagedActive = Boolean(pm2Status && pm2Status.status === 'online');-- if (!currentConfig && isManagedActive && pm2Status?.args) {- currentConfig = parseConfigFromArgs(pm2Status.args);- }-- const host = currentConfig?.host || '127.0.0.1';- const port = currentConfig?.port ?? PORTS.LLAMA_SERVER;- const endpoint = endpointFor(currentConfig);-- const reachable = await probeEndpoint(endpoint);-- const pm2Logs = isManagedActive || (pm2Status && pm2Status.status !== 'not_found')- ? await execPm2(['logs', LLAMA_APP, '--nostream', '--lines', String(logs.maxLines)]).catch(() => null)- : null;-return {- installed,- running: isManagedActive || reachable,- managed: isReadFailed ? null : isManagedActive,- pid: isManagedActive ? (pm2Status?.pid || null) : null,- host,- port,- endpoint,- // NOT nulled on a failed read. `currentConfig` is the launch line PortOS- // itself last started this daemon on, and a subprocess hiccup reading PM2 is- // no evidence it stopped serving it. Nulling it here collapsed `managed:- // null` ("could not tell") straight back into `managed: false` ("somebody- // else's daemon") for every caller guarding on `!managed || !config?.model`- // — defeating, one line later, the entire point of the null sentinel.- config: isManagedActive || isReadFailed ? currentConfig : null,- // Is this PM2 app in the saved dump `pm2 resurrect` replays at boot?- // `null` = the dump could not be read, which is not the same as "no".- runAtStartup: savedApps === null ? null : savedApps.includes(LLAMA_APP),+ ...await daemon.getStatusBase({ installed }),// 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,};}@@ -464,7 +445,7 @@ export async function startLlamaServer(options = {}) {if (effectiveIdleMinutes > 0) args.push(SLEEP_IDLE_FLAG, String(effectiveIdleMinutes * 60));lastExitError = null;- logs.reset();+ daemon.resetLogs();if (requestedIdleMinutes > 0 && effectiveIdleMinutes === 0) {appendLog(`This llama-server build has no ${SLEEP_IDLE_FLAG} — the model stays resident while idle`);}@@ -541,7 +522,7 @@ export async function startLlamaServer(options = {}) {const exitLogs = await execPm2(['logs', LLAMA_APP, '--nostream', '--lines', '15']).catch(() => null);const lines = (exitLogs?.stderr || exitLogs?.stdout || '').trim().split('\n').map((l) => l.trimEnd()).filter(Boolean);for (const line of lines) appendLog(line);- const tail = (lines.length ? lines : logs.snapshot()).slice(-4).join(' | ');+ const tail = (lines.length ? lines : daemon.snapshotLogs()).slice(-4).join(' | ');lastExitError = `PM2 status: ${currentProc.status}`;@@ -611,10 +592,7 @@ export async function stopLlamaServer() {* loses a race with itself and reports "port already in use" for the server it* just stopped.*/-async function waitForPortRelease(port) {- const deadline = Date.now() + PORT_RELEASE_TIMEOUT_MS;- while (Date.now() < deadline && await isPortInUse(port)) await sleep(200);-}+const waitForPortRelease = daemon.waitForPortRelease;/*** Block until the endpoint answers, or the readiness budget elapses.@@ -702,11 +680,7 @@ async function relaunchWithConfig(next, previous) {* @returns {Promise<{managed: boolean, config: object|null, readFailed: boolean}>}*/export async function readLlamaServerLaunch() {- const pm2Status = await getAppStatusStrict(LLAMA_APP);- if (pm2Status === null) return { managed: false, config: null, readFailed: true };- if (pm2Status.status !== 'online') return { managed: false, config: null, readFailed: false };- if (!currentConfig && pm2Status.args) currentConfig = parseConfigFromArgs(pm2Status.args);- return { managed: true, config: currentConfig, readFailed: false };+ return daemon.readLaunch();}/**@@ -1171,7 +1145,7 @@ export function _resetLlamaServerStateForTests({ relaunchReadyTimeout, pm2ReadResleepIdleMinutesOverride = sleepIdleMinutes;currentConfig = null;preTuningConfig = null;- logs.reset();+ daemon.resetLogs();lastExitError = null;// Restored to the production budget unless a suite asks for a shorter one.relaunchReadyTimeoutMs = Number.isFinite(relaunchReadyTimeout) ? relaunchReadyTimeout : 120000;diff --git a/server/services/mtplxServerManager.js b/server/services/mtplxServerManager.jsindex ff87cba9b8..69cc835b02 100644--- a/server/services/mtplxServerManager.js+++ b/server/services/mtplxServerManager.js@@ -29,7 +29,7 @@ import { launchArgs, normalizeTuning, tuningSpecsFor } from '../lib/localModelTuimport { 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, idleWindowMs, markDaemonUsed, registerIdleDaemon, MTPLX_APP } from '../lib/managedDaemon.js';+import { createDaemonWatcher, pm2ArgValue, idleWindowMs, markDaemonUsed, registerIdleDaemon, MTPLX_APP } 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@@ -113,8 +113,6 @@ const MTPLX_NO_MODEL_ERROR = 'MTPLX has no model weights cached, so its server elet currentConfig = null;let lastExitError = null;-const logs = createDaemonLogBuffer();-const appendLog = logs.append;const probeEndpoint = async (endpoint) =>(await probeOpenAiModels(endpoint, { timeoutMs: PROBE_TIMEOUT_MS })).reachable;@@ -122,6 +120,25 @@ const probeEndpoint = async (endpoint) =>const endpointFor = (config) =>`http://${DEFAULT_HOST}:${config?.port ?? DEFAULT_PORT}/v1`;+const daemon = createDaemonWatcher({+ appName: MTPLX_APP,+ defaultHost: DEFAULT_HOST,+ defaultPort: DEFAULT_PORT,+ endpointFor,+ parseConfigFromArgs,+ probe: probeEndpoint,+ isPortInUse: (...args) => isPortInUse(...args),+ sleep,+ getConfig: () => currentConfig,+ setConfig: (config) => { currentConfig = config; },+ getLastExitError: () => lastExitError,+ getAppStatus: (...args) => getAppStatusStrict(...args),+ getSavedProcessNames: (...args) => getSavedProcessNames(...args),+ execPm2: (...args) => execPm2(...args),+ getPortReleaseTimeoutMs: () => portReleaseTimeoutMs,+});+const appendLog = daemon.appendLog;+/*** Reconstructs the launch config from PM2 process args when PortOS restarted* while the PM2 process stayed online — same recovery `llamaServerManager` does,@@ -186,11 +203,7 @@ const withinDeclaredRange = (spec, raw) => {return Number.isFinite(num) && num >= (spec.min ?? -Infinity) && num <= (spec.max ?? Infinity);};-/** Block until the port is free, or the release budget elapses. */-async function waitForPortRelease(port) {- const deadline = Date.now() + portReleaseTimeoutMs;- while (Date.now() < deadline && await isPortInUse(port)) await sleep(200);-}+const waitForPortRelease = daemon.waitForPortRelease;/*** Block until the relaunched server answers, or until it is proven dead.@@ -243,10 +256,9 @@ const resolveMtplxBinary = () => findCommandOnPath('mtplx');/** Just the base URL MTPLX is serving on — no endpoint probe, no PM2 log fetch. */export async function getMtplxServerEndpoint() {if (!currentConfig) {- const pm2Status = await getAppStatusStrict(MTPLX_APP);- if (pm2Status?.status === 'online' && pm2Status.args) currentConfig = parseConfigFromArgs(pm2Status.args);+ await daemon.readLaunch();}- return endpointFor(currentConfig);+ return daemon.endpoint();}/**@@ -267,34 +279,16 @@ export async function getMtplxServerStatus() {// be a false negative.const supported = installed || isAppleSilicon();- const [pm2Status, savedApps] = await Promise.all([getAppStatusStrict(MTPLX_APP), getSavedProcessNames()]);- const isReadFailed = pm2Status === null;- const isManagedActive = Boolean(pm2Status && pm2Status.status === 'online');-- if (!currentConfig && isManagedActive && pm2Status?.args) currentConfig = parseConfigFromArgs(pm2Status.args);-- const endpoint = endpointFor(currentConfig);- const reachable = await probeEndpoint(endpoint);+ const base = await daemon.getStatusBase({ installed });// `models: null` means the cache could NOT be read — deliberately not the same// as `[]` (read, and empty). Only the latter blocks a start.const cache = installed ? await listMtplxCachedModels() : { models: null, error: null };- const pm2Logs = pm2Status && pm2Status.status !== 'not_found'- ? await execPm2(['logs', MTPLX_APP, '--nostream', '--lines', String(logs.maxLines)]).catch(() => null)- : null;-return {- installed,+ ...base,supported,unsupportedReason: supported ? null : MTPLX_UNSUPPORTED_REASON,- running: isManagedActive || reachable,- managed: isReadFailed ? null : isManagedActive,- pid: isManagedActive ? (pm2Status?.pid || null) : null,- host: DEFAULT_HOST,- port: currentConfig?.port ?? DEFAULT_PORT,- endpoint,- config: isManagedActive ? currentConfig : null,// The tuning flags the running daemon was LAUNCHED with, rendered by the// catalog that owns the transport rather than re-derived in the UI. A// measured assessment relaunches this daemon and leaves its flags on, so a@@ -302,10 +296,7 @@ export async function getMtplxServerStatus() {// "running" while it serves with, say, MTP decoding switched off. Empty for// an untuned server, and for one PortOS does not manage — it cannot read// another process's launch line.- tuningFlags: isManagedActive ? launchArgs('mtplx', currentConfig?.tuning) : [],- // 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),+ tuningFlags: base.managed === true ? launchArgs('mtplx', currentConfig?.tuning) : [],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.@@ -325,8 +316,6 @@ export async function getMtplxServerStatus() {valid: m.validation?.ok !== false,})),cacheError: cache.error,- recentLogs: logs.withPm2Logs(`${pm2Logs?.stdout || ''}\n${pm2Logs?.stderr || ''}`),- lastExitError: isReadFailed ? 'Failed to read PM2 status' : lastExitError,};}@@ -434,7 +423,7 @@ export async function startMtplxServer(options = {}) {);}- logs.reset();+ daemon.resetLogs();lastExitError = null;const resolved = await resolveStartModel(requestedModel, emit);@@ -482,7 +471,7 @@ export async function startMtplxServer(options = {}) {const pm2Logs = await execPm2(['logs', MTPLX_APP, '--nostream', '--lines', '15']).catch(() => null);const lines = `${pm2Logs?.stderr || pm2Logs?.stdout || ''}`.split('\n').map((l) => l.trimEnd()).filter(Boolean);for (const line of lines) appendLog(line);- const tail = (lines.length ? lines : logs.snapshot()).slice(-4).join(' | ');+ const tail = (lines.length ? lines : daemon.snapshotLogs()).slice(-4).join(' | ');lastExitError = `PM2 status: ${currentProc.status}`;await execPm2(['delete', MTPLX_APP]).catch(() => {});@@ -712,7 +701,7 @@ async function restorePrevious(previous, failure) {export function _resetMtplxServerStateForTests({ startupWait, startupPoll, portRelease, relaunchReadyTimeout, idleMinutes = 0 } = {}) {idleMinutesOverride = idleMinutes;currentConfig = null;- logs.reset();+ daemon.resetLogs();lastExitError = null;// Restored to the production budget unless a suite asks for a shorter one.startupWaitMs = Number.isFinite(startupWait) ? startupWait : 8_000;