Skip to content

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

fix: stop flagging the local model servers as a memory problem

Adam Eivy63a8d490dc27
diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsx
index e2a9e8f41e..5c8896e483 100644
--- a/client/src/components/cos/tabs/ConfigTab.jsx
+++ b/client/src/components/cos/tabs/ConfigTab.jsx
@@ -457,7 +457,7 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle })
inputValue={formData.maxProcessMemoryMb}
onChange={v => setFormData(f => ({ ...f, maxProcessMemoryMb: v }))}
suffix="MB"
- tooltip="Memory threshold for health alerts - processes exceeding this will be flagged"
+ tooltip="Memory threshold for health alerts - processes exceeding this will be flagged. The local model servers (llama-server, MTPLX) are exempt: their memory is the model they loaded"
/>
<ConfigRow
label="Auto Start"
diff --git a/server/lib/README.md b/server/lib/README.md
index 829a70019f..7021e3230c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -142,7 +142,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `providerTranscriptUsage.js` | Parsers for the real per-message token counts the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Both de-duplicate a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, and Codex's `total_token_usage` is cumulative and repeated. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. |
| `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring model ids under the namespace the provider's marker selects: a local runtime (`ollama` / `mtplx` / `llama` / `vllm` / `sglang`, bare ids) or a hosted gateway from `providerGateways.js` (`vendor/model` ids kept whole). Fixes --model rejection. Also attaches the key for a key-bearing namespace, and pins `small_model` to the run model for a gateway so OpenCode's own side calls (titles, summarization) can't land on its built-in default — a billed model the operator never chose. |
| `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX / vLLM: label, binary, canonical base URL read from `opencodeConfig.js` rather than re-typed, manage/docs links, model-download hint), `localBackendForProvider` + `localEndpointPort` + `isLocalInstanceHost` (moved here from `services/localModelHealing.js`, which re-exports them, so the healing path and the readiness checklist classify a provider identically — loopback/bind-all only, so a LAN/Tailscale peer on port 11434 is NOT claimed as a local daemon), `localRuntimeKind(provider)` (the `*Backed` markers first, then that classifier; `orcarouter` excluded as a remote API), `localRuntimeForProvider(provider)` → the row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` override the backend managers read, then the canonical default — and `null` when that resolved endpoint fails `isLocalInstanceEndpoint` (an API provider on another machine has no local daemon to check, whatever its name says) — plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. Optional `setupStateDetail` overrides `providerReadiness`'s per-state prose for a runtime whose local setup is not a model cache (vLLM's is a compose project). |
-| `managedDaemon.js` | Shared mechanism for the local daemons PortOS runs as optional PM2 processes (`services/llamaServerManager.js` → `portos-llama-server`, `services/mtplxServerManager.js` → `portos-mtplx`). `createDaemonLogBuffer({maxLines?})` is the bounded timestamped ring buffer of what PortOS logged around a launch, plus `withPm2Logs(output)` → that buffer followed by anything `pm2 logs` has which it doesn't already hold, deduped and re-capped (PM2's lines are a VIEW, never folded into the buffer — PM2 owns them and re-reads them every status call). `pm2ArgValue(args, flag)` reads one value back out of a PM2 process's recorded argv so a manager can recover a still-online daemon's launch config after a PortOS restart; `null` means the flag was absent, which a relaunch must leave off rather than defaulting. Deliberately mechanism only — what a launch line means and when a daemon may start is exactly what differs between the two. |
+| `managedDaemon.js` | Shared mechanism for the local daemons PortOS runs as optional PM2 processes (`services/llamaServerManager.js` → `portos-llama-server`, `services/mtplxServerManager.js` → `portos-mtplx`). 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. 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.js
index ab55c1dd71..cc48892590 100644
--- a/server/lib/managedDaemon.js
+++ b/server/lib/managedDaemon.js
@@ -20,6 +20,34 @@
* with two special cases. This is the shared *mechanism* only.
*/
+/**
+ * The PM2 process names of the two local model servers PortOS manages.
+ *
+ * Declared here rather than in each manager so the health monitor can recognize
+ * them without importing a manager (and its whole PM2/model-probe dependency
+ * chain); `llamaServerManager.js` and `mtplxServerManager.js` re-export these as
+ * `LLAMA_APP` / `MTPLX_APP`.
+ */
+export const LLAMA_APP = 'portos-llama-server';
+export const MTPLX_APP = 'portos-mtplx';
+const MODEL_SERVER_APPS = [LLAMA_APP, MTPLX_APP];
+
+/**
+ * Whether a PM2 process is one of those model servers.
+ *
+ * A model server's resident size IS the checkpoint it loaded — llama.cpp and
+ * MTPLX hold multi-GB weights for as long as they are up, by design. Measuring
+ * them against a generic per-process memory cap produces a warning the user can
+ * never clear (a 24GB llama-server against a 2GB cap is a correctly-running
+ * server, not a leak), so callers policing per-process memory skip them. Genuine
+ * host-wide pressure is still reported — `services/proactiveAlerts.js` alerts on
+ * total used-vs-installed memory, which is where a too-large model actually
+ * shows up.
+ *
+ * @param {string} [name] PM2 process name
+ */
+export const isModelServerProcess = (name) => MODEL_SERVER_APPS.includes(name);
+
/** Same cap both managers used, and what the launcher cards render. */
const DEFAULT_MAX_LINES = 100;
diff --git a/server/services/cosHealthMonitor.js b/server/services/cosHealthMonitor.js
index 6ef55663b0..2d1d883073 100644
--- a/server/services/cosHealthMonitor.js
+++ b/server/services/cosHealthMonitor.js
@@ -9,6 +9,7 @@
import { execPm2 } from './pm2.js';
import { safeJSONParse } from '../lib/fileUtils.js';
import { getMemoryStats } from '../lib/memoryStats.js';
+import { isModelServerProcess } from '../lib/managedDaemon.js';
import { loadState, saveState, withStateLock, isDaemonRunning } from './cosState.js';
import { cosEvents, emitLog } from './cosEvents.js';
import { annotateExpectedExit } from './apps.js';
@@ -117,8 +118,14 @@ export async function runHealthCheck() {
}
}
- // Check memory usage per process
+ // Check memory usage per process. The local model servers are exempt: their
+ // resident size is the checkpoint they loaded, so a healthy llama-server or
+ // MTPLX sits tens of GB over any generic cap from the moment it starts, and
+ // the warning it raises can never be cleared. Host-wide pressure — where an
+ // oversized model actually matters — is reported by proactiveAlerts.js.
+ // Releasing that memory while nothing is using it is issue #4863.
const highMemoryProcesses = pm2Processes.filter(p => {
+ if (isModelServerProcess(p?.name)) return false;
const memMb = (p.monit?.memory || 0) / (1024 * 1024);
return memMb > state.config.maxProcessMemoryMb;
});
diff --git a/server/services/cosHealthMonitor.test.js b/server/services/cosHealthMonitor.test.js
index 02d6c8bd77..de8afa3f78 100644
--- a/server/services/cosHealthMonitor.test.js
+++ b/server/services/cosHealthMonitor.test.js
@@ -205,6 +205,31 @@ describe('cosHealthMonitor.runHealthCheck', () => {
expect(issues.some(i => i.category === 'memory' && /High memory usage/.test(i.message))).toBe(true);
});
+ // A model server's RSS is the checkpoint it loaded, so it clears any generic
+ // cap the moment it comes up — flagging it produced a warning the user could
+ // never clear, on every install that runs a local model.
+ describe('model servers are exempt from the per-process memory cap', () => {
+ const overLimitBytes = 24 * 1024 * 1024 * 1024;
+
+ it.each(['portos-llama-server', 'portos-mtplx'])('does not flag %s', async (name) => {
+ mock.pm2Stdout = JSON.stringify([{ name, pm2_env: { status: 'online' }, monit: { memory: overLimitBytes } }]);
+ const { issues } = await runHealthCheck();
+ expect(issues.filter(i => i.category === 'memory')).toEqual([]);
+ });
+
+ it('still flags a non-model-server process alongside an exempt one', async () => {
+ mock.pm2Stdout = JSON.stringify([
+ { name: 'portos-llama-server', pm2_env: { status: 'online' }, monit: { memory: overLimitBytes } },
+ { name: 'hog', pm2_env: { status: 'online' }, monit: { memory: overLimitBytes } }
+ ]);
+ const { issues } = await runHealthCheck();
+ const memoryIssues = issues.filter(i => i.category === 'memory');
+ expect(memoryIssues).toHaveLength(1);
+ expect(memoryIssues[0].message).toContain('hog');
+ expect(memoryIssues[0].message).not.toContain('portos-llama-server');
+ });
+ });
+
it('persists the latest snapshot to state and emits health:check', async () => {
mock.pm2Stdout = '[]';
const { metrics } = await runHealthCheck();
diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.js
index 32ad53a642..73c6837993 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 } from '../lib/managedDaemon.js';
+import { createDaemonLogBuffer, pm2ArgValue, LLAMA_APP } from '../lib/managedDaemon.js';
import { resolveSpecModelPath } from './specDecodeModels.js';
import { parseSpecTypes, isDraftSpecType } from '../lib/specDecodePresets.js';
import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
@@ -21,7 +21,7 @@ import { tuningSpecsFor } from '../lib/localModelTuning.js';
import { ServerError } from '../lib/errorHandler.js';
import { execPm2, getAppStatusStrict, clearJlistCache, getSavedProcessNames } from './pm2.js';
-export const LLAMA_APP = 'portos-llama-server';
+export { LLAMA_APP };
const PROBE_TIMEOUT_MS = 1500;
const STARTUP_WAIT_TIMEOUT_MS = 4000;
diff --git a/server/services/mtplxServerManager.js b/server/services/mtplxServerManager.js
index 7f455750e7..51554e03cd 100644
--- a/server/services/mtplxServerManager.js
+++ b/server/services/mtplxServerManager.js
@@ -29,13 +29,13 @@ import { launchArgs, normalizeTuning, tuningSpecsFor } from '../lib/localModelTu
import { LOCAL_RUNTIMES, localEndpointPort } from '../lib/localProviderRuntime.js';
import { listMtplxCachedModels, pickMtplxCachedModel } from '../lib/mtplxModels.js';
import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
-import { createDaemonLogBuffer, pm2ArgValue } from '../lib/managedDaemon.js';
+import { createDaemonLogBuffer, pm2ArgValue, MTPLX_APP } from '../lib/managedDaemon.js';
import { isAppleSilicon, isPortInUse } from '../lib/platform.js';
import { findCommandOnPath } from '../lib/processEnv.js';
import { runStreamingCommand } from '../lib/streamingSpawn.js';
import { execPm2, getAppStatusStrict, clearJlistCache, getSavedProcessNames } from './pm2.js';
-export const MTPLX_APP = 'portos-mtplx';
+export { MTPLX_APP };
const PROBE_TIMEOUT_MS = 1500;
/**