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: start MTPLX on a cached checkpoint instead of failing on its default

Adam Eivy0951dc00ae7c
diff --git a/docs/features/mtplx.md b/docs/features/mtplx.md
index 0bd5bd5af2..ee9a7d1d02 100644
--- a/docs/features/mtplx.md
+++ b/docs/features/mtplx.md
@@ -29,15 +29,19 @@ valid CoS coding-agent runner.
1. On **AI Providers**, enable the matching preset. Its card shows an MTPLX
requirements checklist (installed / server responding / model available).
-2. Click **Install & start MTPLX** on that checklist. PortOS installs the
+2. Pull a checkpoint yourself — `mtplx pull` fetches MTPLX's default verified
+ model, `mtplx pull <hf-repo-id>` any other MTP model. PortOS never downloads
+ weights, and `mtplx serve` exits immediately when its cache is empty.
+3. Click **Install & start MTPLX** on that checklist. PortOS installs the
package from upstream's Homebrew tap (`brew install youssofal/mtplx/mtplx`),
falling back to `python3 -m pip install mtplx` on a host without Homebrew,
- then runs `mtplx serve --port <the port your provider points at>` and waits
- for `/v1/models` to answer. Progress streams into the install modal.
-3. Use **Refresh Models** once the server is up; PortOS then reads `/v1/models`
+ then runs `mtplx serve --port <the port your provider points at> --model <a
+ model already in your MTPLX cache>` and waits for `/v1/models` to answer.
+ Progress streams into the install modal.
+4. Use **Refresh Models** once the server is up; PortOS then reads `/v1/models`
on demand. The seed model alias is `mtplx` — refresh it if your running
server publishes a different one.
-4. Choose **MTPLX (local MTP)** for supported non-coding tasks, or choose an
+5. Choose **MTPLX (local MTP)** for supported non-coding tasks, or choose an
**OpenCode MTPLX** CLI/TUI preset for a CoS coding task.
Prefer to run it yourself? Install MTPLX per its upstream documentation and
@@ -50,9 +54,15 @@ start a server on the loopback OpenAI-compatible endpoint the preset points at,
optional `mtplx max --install` fan-control helper — the one privileged path
in that project — is never invoked; it stays an explicit operator action
outside PortOS.
-- It does **not** download model weights or choose a checkpoint. A running
- server serving a different alias than the provider names is reported by the
- checklist's model check and left for you to resolve.
+- It does **not** download model weights. It does read `mtplx models --json` —
+ a local directory listing, no network — and starts the server on a checkpoint
+ already in that cache, because `mtplx serve` otherwise defaults to one
+ hard-coded repo id and exits 1 before binding when that particular repo was
+ never pulled, even on a machine holding a different MTP model. An empty cache
+ (or one holding only a half-finished `mtplx pull`) is reported with the
+ `mtplx pull` command that fixes it, never fetched. A running server serving a
+ different alias than the provider names is reported by the checklist's model
+ check and left for you to resolve.
- It only ever runs for an endpoint on **this** machine. A preset pointed at
another host gets no checklist and no button — that install is whoever runs
it.
diff --git a/server/lib/README.md b/server/lib/README.md
index fcd4f9ab06..ba2ec5faeb 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -74,7 +74,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `storyArc.js` | Canonical Arc + Season + Reader-Map shapes for pipeline arc planning. |
| `styleGuide.js` | Per-series house style (tense/POV/audience/rating/reading-level/tone/conventions): `sanitizeStyleGuide` + `renderStyleGuide` generation block + enums. |
| `storyBuilderSteps.js` | Unified Story Builder ordered step definitions + helpers (`STEPS`, `STEP_IDS`, `STEP_STATUSES`, `isValidStepId`, `stepIndex`). |
-| `streamLines.js` | `createLineReader(onLine, {splitRe?, maxCarry?})` — buffered chunk→line splitter for child-process stdout/stderr. Carries the partial trailing line across `data` chunks and `flush()`es the final unterminated line on `close`; carry clamp guards a newline-less runaway stream. One reader per stream (a shared buffer corrupts marker lines). `splitRe: /[\r\n]+/` handles torch/tqdm bare-`\r` progress redraws. |
+| `streamLines.js` | `createLineReader(onLine, {splitRe?, maxCarry?})` + `createOutputTail({budget?})` — buffered chunk→line splitter for child-process stdout/stderr. Carries the partial trailing line across `data` chunks and `flush()`es the final unterminated line on `close`; carry clamp guards a newline-less runaway stream. One reader per stream (a shared buffer corrupts marker lines). `splitRe: /[\r\n]+/` handles torch/tqdm bare-`\r` progress redraws. `createOutputTail` is the sibling rolling buffer of recent lines (char-budgeted, decoration-only lines skipped so an ASCII-art banner cannot push the real error out) that turns "exited with code 1" into what the tool actually printed — shared by `streamingSpawn.js` and the daemon starter in `services/localRuntimeSetup.js`. |
| `storyBuilderIntegrity.js` | Pure staleness hashing for the Story Builder (`hashUpstream`, `computeStaleSteps`, `computeSyncDrift`). |
| `canonPrompt.js` | Per-kind field-precedence rules; SHORT/RICH/PREVIEW spec tables; `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` / `descriptorForCanonEntry`. |
| `scenePrompt.js` | Scene-prompt composer + bible matchers (chars/places/objects in text). |
@@ -136,6 +136,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `providerTranscriptUsage.js` | Parsers for the real per-message token counts the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Both de-duplicate a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, and Codex's `total_token_usage` is cumulative and repeated. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. |
| `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring bare model ids under the selected local provider (`ollama` or `mtplx`) for marked OpenCode providers. Fixes --model rejection. |
| `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX: 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`. |
+| `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. |
| `openAiModelsProbe.js` | `probeOpenAiModels(baseUrl, { timeoutMs })` → `{ reachable, models, error }` — the one `GET {base}/models` probe for the local OpenAI-compatible daemons, shared by `services/providerReadiness.js` and `services/llamaServerManager.js`. Distinguishes unreachable from reachable-but-unlistable (`models: null`) from up-with-nothing-loaded (`[]`), names the real transport failure via `describeFetchError` (undici reports every one as a bare `fetch failed`), and cancels an unread body on a non-OK response. Consolidated after the two copies drifted — one passed its timeout as a `timeout` key inside the fetch init object, where it is not an option, silently running a 500ms poll loop on the 15s default. |
| `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
diff --git a/server/lib/index.js b/server/lib/index.js
index eb0fd6ab3f..e13ee09b17 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -152,6 +152,7 @@ export * from './quotaReset.js';
export * from './quotaWindows.js';
export * from './opencodeConfig.js';
export * from './localProviderRuntime.js';
+export * from './mtplxModels.js';
export * from './openAiModelsProbe.js';
// `runners.js` re-defines `isFlux2`/`isZImage`/`isErnie` that also live in
// mediaModels.js — namespace it so the barrel surface is unambiguous.
diff --git a/server/lib/mtplxModels.js b/server/lib/mtplxModels.js
new file mode 100644
index 0000000000..466f0605fe
--- /dev/null
+++ b/server/lib/mtplxModels.js
@@ -0,0 +1,85 @@
+/**
+ * What MTPLX has in its own model cache, and which entry PortOS may serve.
+ *
+ * `mtplx serve` takes NO model from its config — the CLI hard-codes its default
+ * checkpoint (`Youssofal/Qwen3.8-27B-…`) as the `--model` default. On a machine
+ * where that exact repo was never pulled the server prints
+ *
+ * error: model is not available locally
+ * detail: … is not cached. Run: mtplx pull …
+ *
+ * and exits 1 before it binds a port — including when the user HAS pulled a
+ * different MTP checkpoint that would have served fine. That is what turned the
+ * readiness checklist's "Start MTPLX" button into "MTPLX did not start: mtplx
+ * exited early (code 1)".
+ *
+ * So PortOS asks first. `mtplx models --json` is a local directory listing (no
+ * network, no model load), and naming a cached repo on the command line is the
+ * difference between a server that comes up and one that cannot. PortOS still
+ * never downloads weights — a multi-gigabyte pull stays the user's decision,
+ * exactly as `docs/features/mtplx.md` promises.
+ */
+
+import { bufferedSpawn } from './bufferedSpawn.js';
+import { safeJSONParse } from './fileUtils.js';
+import { findCommandOnPath } from './processEnv.js';
+
+/** A cache listing walks the model directories to size them; be generous. */
+const CACHE_QUERY_TIMEOUT_MS = 30_000;
+
+/**
+ * The models in MTPLX's local cache.
+ *
+ * `models: null` means PortOS could not read the cache at all (no binary, the
+ * command failed, unparseable output) — deliberately NOT the same value as
+ * `models: []`, which means the cache was read and is empty. The caller starts
+ * MTPLX with its own default in the first case and refuses in the second; a
+ * shared falsy value would make an unreadable cache look like an empty one and
+ * block a start that would have worked.
+ *
+ * @param {{command?: string}} [options]
+ * @returns {Promise<{models: object[]|null, error: string|null}>}
+ */
+export async function listMtplxCachedModels({ command = 'mtplx' } = {}) {
+ const binary = findCommandOnPath(command);
+ if (!binary) return { models: null, error: `\`${command}\` is not on PortOS's PATH` };
+
+ const result = await bufferedSpawn(binary, ['models', '--json'], { timeoutMs: CACHE_QUERY_TIMEOUT_MS, shell: false });
+ if (result.timedOut) return { models: null, error: `\`${command} models\` timed out` };
+ if (!result.success) {
+ const detail = String(result.stderr || result.stdout || '').trim().split(/\r?\n/).pop();
+ return { models: null, error: detail || `\`${command} models\` exited with code ${result.code}` };
+ }
+
+ // Parse from the first brace: MTPLX writes the JSON alone today, but a banner
+ // line ahead of it must not read as "nothing is cached".
+ const text = String(result.stdout || '');
+ const start = text.indexOf('{');
+ const parsed = start === -1 ? null : safeJSONParse(text.slice(start), null, { allowArray: false });
+ if (!Array.isArray(parsed?.models)) {
+ return { models: null, error: `\`${command} models --json\` did not return a model list` };
+ }
+ return { models: parsed.models, error: null };
+}
+
+/**
+ * The cached repo id PortOS should hand `mtplx serve --model`, or null when the
+ * cache holds nothing servable.
+ *
+ * Only entries MTPLX itself calls complete are eligible: `validation.ok` is
+ * false for a directory missing required files or an MTP sidecar, which is what
+ * an interrupted `mtplx pull` leaves behind — starting the server on one of
+ * those trades an honest "nothing is cached" for a load failure minutes later.
+ * Among complete entries, one carrying `mtplx_runtime.json` wins: that is the
+ * recorded exactness contract, and the runtime warns on stats from artifacts
+ * without it.
+ *
+ * @param {object[]|null|undefined} models - rows from `listMtplxCachedModels`
+ * @returns {string|null}
+ */
+export function pickMtplxCachedModel(models) {
+ if (!Array.isArray(models)) return null;
+ const usable = models.filter((row) => typeof row?.repo_id === 'string' && row.repo_id !== '' && row?.validation?.ok !== false);
+ const verified = usable.find((row) => row.has_runtime_contract === true);
+ return (verified || usable[0])?.repo_id ?? null;
+}
diff --git a/server/lib/mtplxModels.test.js b/server/lib/mtplxModels.test.js
new file mode 100644
index 0000000000..4388896b9a
--- /dev/null
+++ b/server/lib/mtplxModels.test.js
@@ -0,0 +1,95 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+const spawned = vi.hoisted(() => ({ bufferedSpawn: vi.fn() }));
+vi.mock('./bufferedSpawn.js', () => spawned);
+
+const pathLookup = vi.hoisted(() => ({ findCommandOnPath: vi.fn(() => '/opt/homebrew/bin/mtplx') }));
+vi.mock('./processEnv.js', () => pathLookup);
+
+import { listMtplxCachedModels, pickMtplxCachedModel } from './mtplxModels.js';
+
+const ok = (stdout) => ({ success: true, code: 0, signal: null, stdout, stderr: '', timedOut: false });
+
+afterEach(() => {
+ vi.clearAllMocks();
+ pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');
+});
+
+describe('listMtplxCachedModels', () => {
+ it('reads the cache listing without touching the network', async () => {
+ spawned.bufferedSpawn.mockResolvedValue(ok(JSON.stringify({
+ cache_dir: '/cache/models',
+ models: [{ repo_id: 'Example/Model-A', validation: { ok: true } }],
+ })));
+
+ const result = await listMtplxCachedModels();
+
+ expect(spawned.bufferedSpawn).toHaveBeenCalledWith('/opt/homebrew/bin/mtplx', ['models', '--json'], expect.objectContaining({ shell: false }));
+ expect(result).toEqual({ models: [{ repo_id: 'Example/Model-A', validation: { ok: true } }], error: null });
+ });
+
+ it('reports an EMPTY cache as [], not as a failure', async () => {
+ // The sentinel that matters: `[]` means "read it, nothing is there" and the
+ // caller must refuse to start; collapsing it into `null` would launch a
+ // server that exits 1 the moment it looks for weights.
+ spawned.bufferedSpawn.mockResolvedValue(ok(JSON.stringify({ cache_dir: '/cache/models', models: [] })));
+
+ expect(await listMtplxCachedModels()).toMatchObject({ models: [], error: null });
+ });
+
+ it('returns null models — never [] — when the cache cannot be read at all', async () => {
+ pathLookup.findCommandOnPath.mockReturnValue(null);
+ expect(await listMtplxCachedModels()).toMatchObject({ models: null, error: expect.stringMatching(/PATH/) });
+ expect(spawned.bufferedSpawn).not.toHaveBeenCalled();
+
+ pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');
+ spawned.bufferedSpawn.mockResolvedValue({ success: false, code: 2, stdout: '', stderr: 'usage: mtplx models\nerror: unknown flag', timedOut: false });
+ expect(await listMtplxCachedModels()).toMatchObject({ models: null, error: 'error: unknown flag' });
+
+ spawned.bufferedSpawn.mockResolvedValue({ success: false, code: -1, stdout: '', stderr: '', timedOut: true });
+ expect(await listMtplxCachedModels()).toMatchObject({ models: null, error: expect.stringMatching(/timed out/) });
+
+ spawned.bufferedSpawn.mockResolvedValue(ok('not json at all'));
+ expect(await listMtplxCachedModels()).toMatchObject({ models: null, error: expect.stringMatching(/did not return a model list/) });
+ });
+
+ it('skips a banner printed ahead of the JSON payload', async () => {
+ spawned.bufferedSpawn.mockResolvedValue(ok(`MTPLX 2.9.0\n${JSON.stringify({ cache_dir: '/c', models: [] })}`));
+ expect(await listMtplxCachedModels()).toMatchObject({ models: [], error: null });
+ });
+
+ it('honours a custom command name', async () => {
+ pathLookup.findCommandOnPath.mockReturnValue(null);
+ await listMtplxCachedModels({ command: 'mtplx-next' });
+ expect(pathLookup.findCommandOnPath).toHaveBeenCalledWith('mtplx-next');
+ });
+});
+
+describe('pickMtplxCachedModel', () => {
+ it('prefers a model carrying the recorded exactness contract', () => {
+ expect(pickMtplxCachedModel([
+ { repo_id: 'Example/Plain', has_runtime_contract: false, validation: { ok: true } },
+ { repo_id: 'Example/Verified', has_runtime_contract: true, validation: { ok: true } },
+ ])).toBe('Example/Verified');
+ });
+
+ it('falls back to any complete model when none carries a contract', () => {
+ expect(pickMtplxCachedModel([{ repo_id: 'Example/Plain', validation: { ok: true } }])).toBe('Example/Plain');
+ });
+
+ it('refuses a half-finished pull — a partial directory would fail on load', () => {
+ expect(pickMtplxCachedModel([
+ { repo_id: 'Example/Partial', has_runtime_contract: true, validation: { ok: false, missing_files: ['mtp sidecar'] } },
+ ])).toBeNull();
+ });
+
+ it('accepts a row from an older CLI that reports no validation block', () => {
+ expect(pickMtplxCachedModel([{ repo_id: 'Example/Old' }])).toBe('Example/Old');
+ });
+
+ it('returns null for an empty, unreadable, or id-less cache', () => {
+ expect(pickMtplxCachedModel([])).toBeNull();
+ expect(pickMtplxCachedModel(null)).toBeNull();
+ expect(pickMtplxCachedModel([{ path: '/cache/broken' }])).toBeNull();
+ });
+});
diff --git a/server/lib/streamLines.js b/server/lib/streamLines.js
index 0e68fda3a9..63d23f128c 100644
--- a/server/lib/streamLines.js
+++ b/server/lib/streamLines.js
@@ -65,3 +65,33 @@ export function createLineReader(onLine, { splitRe = DEFAULT_SPLIT_RE, maxCarry
return { push, flush };
}
+
+/**
+ * A rolling buffer of the most recent output lines, capped by a char budget.
+ *
+ * The tail is what turns "exited with code 1" into the reason the tool printed
+ * — `runStreamingCommand` attaches it to every non-zero exit, and the daemon
+ * starter in `services/localRuntimeSetup.js` needs the same thing for a server
+ * that dies before it binds. Shared so those two cannot drift.
+ *
+ * `remember` ignores decoration-only lines (box drawing, rules, ASCII-art
+ * banners): a CLI that prints a 6-line logo before failing would otherwise
+ * spend the whole budget on it and push the actual error out of the tail.
+ */
+export function createOutputTail({ budget = 1024 } = {}) {
+ const lines = [];
+ let chars = 0;
+
+ const remember = (line) => {
+ const text = String(line ?? '').trim();
+ // Something readable, not `╭─────╮` / `====` / the logo's block glyphs.
+ if (!/[a-z0-9]/i.test(text)) return;
+ lines.push(text);
+ chars += text.length + 1;
+ while (chars > budget && lines.length > 1) {
+ chars -= lines.shift().length + 1;
+ }
+ };
+
+ return { remember, text: () => lines.join(' — ').trim() };
+}
diff --git a/server/lib/streamLines.test.js b/server/lib/streamLines.test.js
index 7a98235834..597e5149b8 100644
--- a/server/lib/streamLines.test.js
+++ b/server/lib/streamLines.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { createLineReader } from './streamLines.js';
+import { createLineReader, createOutputTail } from './streamLines.js';
const collect = (opts) => {
const lines = [];
@@ -117,3 +117,43 @@ describe('createLineReader', () => {
expect(out).toEqual(['e:ERR-full', 'o:OUT-partial']);
});
});
+
+describe('createOutputTail', () => {
+ it('joins the remembered lines into a failure detail', () => {
+ const tail = createOutputTail();
+ tail.remember('error: model is not available locally');
+ tail.remember('detail: run mtplx pull');
+ expect(tail.text()).toBe('error: model is not available locally — detail: run mtplx pull');
+ });
+
+ it('skips decoration-only lines so a banner cannot crowd out the error', () => {
+ // The MTPLX banner is six lines of block glyphs followed by a box rule; on a
+ // 1KB budget that alone can push the actual failure out of the tail.
+ const tail = createOutputTail({ budget: 60 });
+ for (const line of ['███╗ ███╗', '╭─────────╮', '│ │', '╰─────────╯', '====']) tail.remember(line);
+ tail.remember('error: model is not available locally');
+ expect(tail.text()).toBe('error: model is not available locally');
+ });
+
+ it('drops the OLDEST lines once the char budget is spent', () => {
+ const tail = createOutputTail({ budget: 30 });
+ tail.remember('first line of output');
+ tail.remember('second line');
+ tail.remember('third line');
+ expect(tail.text()).toBe('second line — third line');
+ });
+
+ it('keeps the last line even when it alone exceeds the budget', () => {
+ const tail = createOutputTail({ budget: 5 });
+ tail.remember('a much longer final line');
+ expect(tail.text()).toBe('a much longer final line');
+ });
+
+ it('is empty for blank and nullish input', () => {
+ const tail = createOutputTail();
+ tail.remember(' ');
+ tail.remember(null);
+ tail.remember(undefined);
+ expect(tail.text()).toBe('');
+ });
+});
diff --git a/server/lib/streamingSpawn.js b/server/lib/streamingSpawn.js
index 2def8c01fb..adbbd93be8 100644
--- a/server/lib/streamingSpawn.js
+++ b/server/lib/streamingSpawn.js
@@ -21,10 +21,7 @@
import { spawn } from './childProcess.js';
import { safeChildProcessEnv, safeChildProcessOptions } from './processEnv.js';
-import { createLineReader } from './streamLines.js';
-
-/** Char budget for the recent-output tail attached to a failure message. */
-const TAIL_BUDGET = 1024;
+import { createLineReader, createOutputTail } from './streamLines.js';
/**
* @param {string} cmd
@@ -44,20 +41,12 @@ export function runStreamingCommand(cmd, args, onLine, { timeoutMs = 0, cwd, env
}));
let settled = false;
- const tail = []; // recent non-empty lines, capped by char budget for the error message
- let tailChars = 0;
-
- const rememberLine = (line) => {
- tail.push(line);
- tailChars += line.length + 1;
- while (tailChars > TAIL_BUDGET && tail.length > 1) {
- tailChars -= tail.shift().length + 1;
- }
- };
+ // Recent output, kept so a non-zero exit reports what the tool actually said.
+ const tail = createOutputTail();
const safeLine = (line) => {
if (!line) return;
- rememberLine(line);
+ tail.remember(line);
if (typeof onLine !== 'function') return;
try { onLine(line); } catch (err) { console.error(`⚠️ streaming output hook failed: ${err.message}`); }
};
@@ -94,7 +83,7 @@ export function runStreamingCommand(cmd, args, onLine, { timeoutMs = 0, cwd, env
stdoutReader.flush();
stderrReader.flush();
if (code === 0) return finish({ success: true });
- const detail = tail.join(' — ').trim();
+ const detail = tail.text();
finish({ success: false, error: detail ? `exit ${code}: ${detail}` : `exited with code ${code}` });
});
});
diff --git a/server/services/localRuntimeSetup.js b/server/services/localRuntimeSetup.js
index d09e30f726..4bff64fb59 100644
--- a/server/services/localRuntimeSetup.js
+++ b/server/services/localRuntimeSetup.js
@@ -21,7 +21,9 @@
* - **Weights are never downloaded.** llama.cpp cannot be started without a
* GGUF path the user chooses, and no runtime's *model* check is auto-fixed
* — a multi-gigabyte download is a decision, and the Local LLM tab already
- * owns that flow with a picker.
+ * owns that flow with a picker. MTPLX is started on a checkpoint ALREADY in
+ * its cache (`lib/mtplxModels.js`); an empty cache is reported with the
+ * `mtplx pull` command that fixes it, never fetched.
* - **MTPLX's privileged paths are never touched.** Upstream ships an
* optional `mtplx max --install` fan-control helper behind a sudo prompt.
* PortOS installs the package and starts the loopback API server; that
@@ -34,8 +36,10 @@ import { spawn } from '../lib/childProcess.js';
import { commandExists } from '../lib/commandExists.js';
import { sleep } from '../lib/fileUtils.js';
import { LOCAL_RUNTIMES, localEndpointPort } from '../lib/localProviderRuntime.js';
+import { listMtplxCachedModels, pickMtplxCachedModel } from '../lib/mtplxModels.js';
import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
+import { createLineReader, createOutputTail } from '../lib/streamLines.js';
import { runStreamingCommand } from '../lib/streamingSpawn.js';
import { installLlamaServer } from './llamaServerManager.js';
import { controlOllamaServer, installBackend } from './localLlm.js';
@@ -72,6 +76,13 @@ const START_POLL_MS = 1_500;
const PROBE_TIMEOUT_MS = 2_000;
const CONFIRM_TIMEOUT_MS = 5_000;
+/**
+ * Why an installed MTPLX still cannot be started. Weights are a multi-gigabyte
+ * download and stay the user's decision (`docs/features/mtplx.md`), so the
+ * button names the one command that fixes this instead of running it.
+ */
+const MTPLX_NO_MODEL_ERROR = 'no model weights are cached, so its server exits before it binds a port. Run `mtplx pull` in a terminal to fetch its default checkpoint (or `mtplx pull <hf-repo-id>` for another MTP model) — a multi-gigabyte download PortOS will not start for you — then click Start MTPLX again.';
+
/** What each `action` is called on the button and in the log. */
const ACTION_LABELS = {
install: (label) => `Install ${label}`,
@@ -99,14 +110,23 @@ async function startDaemon({ command, args, endpoint, emit, isCancelled = () =>
}));
let exited = null;
- const onData = (chunk) => {
- for (const line of chunk.toString().split(/\r?\n/)) {
- const text = line.trim();
- if (text) emit(text);
- }
+ // Recent output, so a daemon that dies before it binds reports what it
+ // printed rather than only its exit code.
+ const tail = createOutputTail();
+ const onLine = (line) => {
+ const text = line.trim();
+ if (!text) return;
+ tail.remember(text);
+ emit(text);
};
- child.stdout?.on('data', onData);
- child.stderr?.on('data', onData);
+ // One reader per stream: a shared carry buffer splices a half-written stdout
+ // line onto the next stderr chunk (see `lib/streamLines.js`).
+ const stdoutReader = createLineReader(onLine);
+ const stderrReader = createLineReader(onLine);
+ const onStdout = stdoutReader.push;
+ const onStderr = stderrReader.push;
+ child.stdout?.on('data', onStdout);
+ child.stderr?.on('data', onStderr);
// Outside the request lifecycle: an unhandled 'error' on a child is a process
// crash, and the exit code is what turns "still waiting" into a real reason.
const onError = (err) => { exited = `failed to start: ${err.message}`; };
@@ -128,8 +148,9 @@ async function startDaemon({ command, args, endpoint, emit, isCancelled = () =>
* cannot throw on an emitter with no listener.
*/
const stopStreaming = () => {
+ child.stdout?.off('data', onStdout);
+ child.stderr?.off('data', onStderr);
for (const stream of [child.stdout, child.stderr]) {
- stream?.off('data', onData);
stream?.resume();
}
child.off('error', onError);
@@ -154,8 +175,13 @@ async function startDaemon({ command, args, endpoint, emit, isCancelled = () =>
return { success: true, models: probe.models };
}
if (exited) {
+ // Flush FIRST: the reason a daemon dies is often its last line, and a
+ // child that exited without a trailing newline leaves it in the carry.
+ stdoutReader.flush();
+ stderrReader.flush();
stopStreaming();
- return { success: false, error: `${command} ${exited}.` };
+ const detail = tail.text();
+ return { success: false, error: `${command} ${exited}.${detail ? ` ${detail}` : ''}` };
}
}
@@ -189,12 +215,32 @@ const SETUP_ROWS = Object.freeze({
}
return { success: false, error: 'Neither Homebrew nor python3 is available. Install Homebrew from https://brew.sh, then try again.' };
},
- start({ emit, endpoint, isCancelled }) {
+ async start({ emit, endpoint, isCancelled }) {
+ // `mtplx serve` defaults `--model` to ONE hard-coded checkpoint and exits
+ // 1 before binding when that repo is not in its cache — even on a machine
+ // holding a different MTP model that would have served fine. Ask the
+ // cache first and name what is actually there.
+ const cache = await listMtplxCachedModels();
+ if (cache.models === null) {
+ // The cache could not be READ — which is not "read, and empty". Fall
+ // through to MTPLX's own default rather than blocking a start that may
+ // well work.
+ emit(`Could not read MTPLX's model cache (${cache.error}) — starting with its default model.`);
+ } else if (cache.models.length === 0) {
+ return { success: false, error: MTPLX_NO_MODEL_ERROR };
+ }
+ const model = pickMtplxCachedModel(cache.models);
+ if (cache.models && !model) {
+ const count = cache.models.length;
+ return { success: false, error: `its cache holds ${count} model${count === 1 ? '' : 's'}, but none passed its own file check — an interrupted \`mtplx pull\` leaves a partial download behind. Re-run \`mtplx pull <hf-repo-id>\` in a terminal, then try again.` };
+ }
+ if (model) emit(`Serving the cached MTPLX model ${model}.`);
// `mtplx start` is interactive (it prompts for a model); `serve` is the
// API-only server, which is the half PortOS actually talks to. The daemon
// must bind where the PROVIDER points — a user who moved MTPLX to 8010
// would otherwise get a second server on 8000 that nothing talks to.
- return startDaemon({ command: 'mtplx', args: ['serve', '--port', localEndpointPort(endpoint) || '8000'], endpoint, emit, isCancelled });
+ const args = ['serve', '--port', localEndpointPort(endpoint) || '8000', ...(model ? ['--model', model] : [])];
+ return startDaemon({ command: 'mtplx', args, endpoint, emit, isCancelled });
},
}),
diff --git a/server/services/localRuntimeSetup.test.js b/server/services/localRuntimeSetup.test.js
index 630daf2ff8..4f279975ee 100644
--- a/server/services/localRuntimeSetup.test.js
+++ b/server/services/localRuntimeSetup.test.js
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { pinPlatform } from '../lib/testHelper.js';
const probe = vi.hoisted(() => ({ probeOpenAiModels: vi.fn() }));
@@ -29,6 +29,13 @@ vi.mock('./localLlm.js', () => localLlm);
vi.mock('./lmStudioManager.js', () => ({ isAppInstalled: () => false }));
const child = vi.hoisted(() => ({ spawn: vi.fn() }));
vi.mock('../lib/childProcess.js', () => child);
+// MTPLX's model cache — the setup asks it what is actually cached before it
+// starts a server that would otherwise exit 1 looking for a checkpoint.
+const mtplxCache = vi.hoisted(() => ({
+ listMtplxCachedModels: vi.fn(),
+ pickMtplxCachedModel: vi.fn((models) => (Array.isArray(models) && models[0]?.repo_id) || null),
+}));
+vi.mock('../lib/mtplxModels.js', () => mtplxCache);
vi.mock('../lib/fileUtils.js', () => ({ sleep: async () => {} }));
import { describeRuntimeSetup, runLocalRuntimeSetup, SETUP_RUNTIME_KINDS } from './localRuntimeSetup.js';
@@ -49,6 +56,19 @@ const fakeChild = () => {
};
const reachable = (models = ['mtplx']) => ({ reachable: true, models, error: null });
+const cachedModels = (models) => ({ models, error: null });
+
+beforeEach(() => {
+ // Implementations AND return values (not just call records) survive
+ // `clearAllMocks`. A probe implementation left over from an earlier test drives
+ // this module's poll loop for its full three-minute timeout, and a leftover
+ // `spawn` return value hands a stale child to whichever test spawns next.
+ probe.probeOpenAiModels.mockReset();
+ child.spawn.mockReset();
+ mtplxCache.listMtplxCachedModels.mockResolvedValue(cachedModels([{ repo_id: 'Example/MTP-Model', validation: { ok: true } }]));
+ mtplxCache.pickMtplxCachedModel.mockImplementation((models) => (Array.isArray(models) && models[0]?.repo_id) || null);
+});
+
afterEach(() => {
vi.clearAllMocks();
pathLookup.findCommandOnPath.mockReturnValue(null);
@@ -239,7 +259,7 @@ describe('runLocalRuntimeSetup', () => {
const [binary, args] = child.spawn.mock.calls[0];
expect(binary).toBe('/opt/homebrew/bin/mtplx');
- expect(args).toEqual(['serve', '--port', '8010']);
+ expect(args).toEqual(['serve', '--port', '8010', '--model', 'Example/MTP-Model']);
expect(daemon.unref).toHaveBeenCalled();
expect(result).toMatchObject({ success: true, message: expect.stringContaining('http://127.0.0.1:8010/v1') });
});
@@ -291,6 +311,85 @@ describe('runLocalRuntimeSetup', () => {
expect(result).toMatchObject({ success: false, error: expect.stringMatching(/exited early \(code 1\)/) });
});
+ it('refuses to start MTPLX with an EMPTY model cache, naming the pull command', async () => {
+ // `mtplx serve` defaults to one hard-coded checkpoint and exits 1 before it
+ // binds when nothing is cached. Spawning it anyway is how "Start MTPLX"
+ // reported "exited early (code 1)" and left the user with no next step.
+ mtplxCache.listMtplxCachedModels.mockResolvedValue(cachedModels([]));
+ pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');
+ probe.probeOpenAiModels.mockResolvedValue(unreachable);
+ const restore = pinPlatform('darwin');
+
+ const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });
+ restore();
+
+ expect(child.spawn).not.toHaveBeenCalled();
+ expect(result).toMatchObject({ success: false, error: expect.stringContaining('mtplx pull') });
+ });
+
+ it('refuses when every cached MTPLX model is an incomplete download', async () => {
+ mtplxCache.listMtplxCachedModels.mockResolvedValue(cachedModels([{ repo_id: 'Example/Partial', validation: { ok: false } }]));
+ mtplxCache.pickMtplxCachedModel.mockReturnValue(null);
+ pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');
+ probe.probeOpenAiModels.mockResolvedValue(unreachable);
+ const restore = pinPlatform('darwin');
+
+ const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });
+ restore();
+
+ expect(child.spawn).not.toHaveBeenCalled();
+ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/none passed its own file check/) });
+ });
+
+ it('starts MTPLX on its own default when the cache cannot be READ', async () => {
+ // Unreadable is not empty: blocking here would refuse a start that works.
+ mtplxCache.listMtplxCachedModels.mockResolvedValue({ models: null, error: '`mtplx models` timed out' });
+ const daemon = fakeChild();
+ child.spawn.mockReturnValue(daemon);
+ pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');
+ probe.probeOpenAiModels
+ .mockResolvedValueOnce(unreachable)
+ .mockResolvedValueOnce(unreachable)
+ .mockResolvedValueOnce(reachable(['mtplx']))
+ .mockResolvedValueOnce(reachable(['mtplx']));
+ const restore = pinPlatform('darwin');
+
+ const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });
+ restore();
+
+ expect(child.spawn.mock.calls[0][1]).toEqual(['serve', '--port', '8000']);
+ expect(result.success).toBe(true);
+ });
+
+ it('reports what a dying daemon printed, skipping its ASCII-art banner', async () => {
+ const daemon = fakeChild();
+ child.spawn.mockReturnValue(daemon);
+ pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');
+ // The stdout handler is registered as `on('data', …)` — feed it the way the
+ // real stream would, split across chunks mid-line.
+ const feed = (chunk) => daemon.stdout.on.mock.calls.find(([event]) => event === 'data')?.[1](chunk);
+ let printed = false;
+ probe.probeOpenAiModels.mockImplementation(async () => {
+ // Only once the daemon has been spawned and its stdout hooked up.
+ if (daemon.stdout.on.mock.calls.length > 0 && !printed) {
+ printed = true;
+ feed('╭──────────╮\n╰──────────╯\nerror: model is not ava');
+ feed('ilable locally\ndetail: run mtplx pull\n');
+ daemon.emitEvent('exit', 1, null);
+ }
+ return unreachable;
+ });
+ const restore = pinPlatform('darwin');
+
+ const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });
+ restore();
+
+ expect(result.error).toContain('exited early (code 1)');
+ // Line reassembled across the chunk boundary, box drawing left out of it.
+ expect(result.error).toContain('error: model is not available locally');
+ expect(result.error).not.toContain('╭');
+ });
+
it('refuses a runtime kind it has no row for', async () => {
const result = await runLocalRuntimeSetup('made-up', { endpoint: 'http://127.0.0.1:9/v1' });
expect(result).toMatchObject({ success: false, error: expect.stringMatching(/no automatic setup/) });