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

address review (codex): cancel the pull, honor a legacy click, refuse it elsewhere

Adam Eivy0b372e64f5b1
diff --git a/docs/features/mtplx.md b/docs/features/mtplx.md
index 01c0ca5aac..3b8b29cee4 100644
--- a/docs/features/mtplx.md
+++ b/docs/features/mtplx.md
@@ -75,6 +75,11 @@ start a server on the loopback OpenAI-compatible endpoint the preset points at,
offered a **Start MTPLX** that could only fail, and named the missing weights
solely inside that failure — the one blocking fact was reachable only by
clicking the button it made impossible.
+- Closing the modal **cancels the download**. PortOS allows one local-runtime
+ setup at a time, and a weights pull can run for hours, so leaving it running
+ after you dismissed it would also refuse every other runtime's setup button
+ for the rest of it. A cancelled pull leaves a partial download in the cache,
+ which the checklist reports as such and offers to re-fetch.
- 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 1c9bc30b81..40bb07b399 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -402,7 +402,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `staticImportGraph.js` | Static ES-module import scanning for structural test guards. `staticImportSpecifiers(file)` → every specifier a file statically imports (verbatim, source order); `staticImportClosure(entry)` → `{files, packages}` for the whole reachable graph; `specifierMatchesPackage(spec, pkg)` matches a package or any subpath. Static imports only — `await import()` is deferred and can't create a load-time cycle or drag a native dep into an init graph. Shared by `agentImportCycles.test.js` (acyclicity) and `sprites/animationTracks.test.js` (the request-validation graph reaches no sharp/ffmpeg). |
| `sseUtils.js` | Per-job SSE stream helpers (imageGen + others) plus `createSseRunner` — the shared batch-runner lifecycle (runs map, terminal-frame replay, cancel, fire-and-forget coordinator) used by the pipeline completeness/analysis/checks runners. |
| `streamBackpressure.js` | `awaitWritableDrain(res)` — park a streaming-response producer on the socket's next `drain` (or `close`) when `res.write()` returned false, so SSE/NDJSON writes stay bounded for a slow reader. Shared by `routes/ask.js` (SSE) and `routes/localLlm.js` (NDJSON). |
-| `streamingSpawn.js` | `runStreamingCommand(cmd, args, onLine, {timeoutMs?, cwd?, env?, splitRe?})` — run one command to completion and forward its stdout/stderr LINES to a hook, resolving `{ success, error? }`. Never rejects (spawn error, non-zero exit, and timeout all resolve as `success: false`) because every caller is an install/setup flow running outside the Express request lifecycle, and the `onLine` hook is guarded for the same reason. A failure carries the last ~1KB of streamed output, so `brew upgrade ollama` exiting 1 with "Error: ollama not installed" surfaces that string instead of "exited with code 1". Shared by `services/localLlm.js`'s package-manager installs and `services/localRuntimeSetup.js`'s one-click daemon setup. `splitRe` is forwarded to the line readers — pass `/[\r\n]+/` for a downloader whose progress bar redraws one line with a bare `\r`, or the stream goes silent for the whole download. `bufferedSpawn.js` is the sibling for run-and-collect; use this one when live output IS the progress. |
+| `streamingSpawn.js` | `runStreamingCommand(cmd, args, onLine, {timeoutMs?, cwd?, env?, splitRe?})` — run one command to completion and forward its stdout/stderr LINES to a hook, resolving `{ success, error? }`. Never rejects (spawn error, non-zero exit, and timeout all resolve as `success: false`) because every caller is an install/setup flow running outside the Express request lifecycle, and the `onLine` hook is guarded for the same reason. A failure carries the last ~1KB of streamed output, so `brew upgrade ollama` exiting 1 with "Error: ollama not installed" surfaces that string instead of "exited with code 1". Shared by `services/localLlm.js`'s package-manager installs and `services/localRuntimeSetup.js`'s one-click daemon setup. `splitRe` is forwarded to the line readers — pass `/[\r\n]+/` for a downloader whose progress bar redraws one line with a bare `\r`, or the stream goes silent for the whole download. `isCancelled` is polled once a second and SIGKILLs the child when it turns true (resolving `{success:false, error:'cancelled'}`) — required for a command that can run for hours while the caller holds a lock until it settles; a throwing predicate is logged and read as "not cancelled" rather than crashing the process from a timer callback. `bufferedSpawn.js` is the sibling for run-and-collect; use this one when live output IS the progress. |
| `repoIntakeActions.js` | `REPO_INTAKE_KEYS` + `normalizeRepoIntake(input)` — the opt-in post-clone agent actions a Brain capture can request for a GitHub repo URL (`malwareScan` → `/do:scan`, `learn` → a `repo-study` review). Pure half of `services/repoIntake.js` (which pulls the CoS task graph), so the link write path and the Zod schemas can import it freely. Normalizes to null when nothing was ticked, so "no intake" is never persisted onto a link. |
| `tombstones.js` | Generic timestamped tombstones (`{ <keyField>, deletedAt }`) that let an otherwise add-only peer merge represent a DELETE, so a record removed on one machine is not resurrected by a peer that still has it (#3530). `normalizeTombstones` / `recordTombstone` / `clearTombstone` / `tombstoneTimestamp` maintain the list; `mergeTombstones` unions it in both directions (newest deletion per key wins) so a delete propagates rather than only defending locally; `isTombstoned(list, key, createdAt)` suppresses a record unless its own creation stamp is strictly NEWER than the deletion; `pruneTombstones(list, records)` drops tombstones a re-created record has superseded (otherwise a stale peer copy keeps reaping it); `supersedingTimestamp(deletedAt)` stamps a re-create that lands in the same millisecond (or behind a skewed peer clock). Comparison goes through `lwwTimestamp.js`, so polarity matches every other sync merge. Key on a field that means the same thing on every machine — locally-minted ids usually do not. `DEFAULT_TOMBSTONE_LIMIT` (200) caps growth. |
| `uploadLimits.js` | Single source of truth for upload size caps — `JSON_BODY_LIMIT`/`JSON_BODY_LIMIT_BYTES` (the express.json limit applied in `index.js`), `MAX_BASE64_UPLOAD_BYTES` derived from it (base64 ×4/3, so a bigger per-route cap is unreachable), `MAX_SCREENSHOT_BYTES`. Mirrored client-side as `JSON_UPLOAD_MAX_FILE_SIZE`. |
diff --git a/server/lib/streamingSpawn.js b/server/lib/streamingSpawn.js
index 3b8e36a927..d3b84f4748 100644
--- a/server/lib/streamingSpawn.js
+++ b/server/lib/streamingSpawn.js
@@ -23,18 +23,26 @@ import { spawn } from './childProcess.js';
import { safeChildProcessEnv, safeChildProcessOptions } from './processEnv.js';
import { createLineReader, createOutputTail } from './streamLines.js';
+/**
+ * How often `isCancelled` is asked. A second is well under human perception for
+ * "I closed it and it stopped", and a check this cheap costs nothing against a
+ * command whose whole point is that it runs for minutes or hours.
+ */
+const CANCEL_POLL_MS = 1_000;
+
/**
* @param {string} cmd
* @param {string[]} args
* @param {(line: string) => void} [onLine] - called once per non-empty line
- * @param {{timeoutMs?: number, cwd?: string, env?: object, spawnImpl?: Function, splitRe?: RegExp}} [options]
+ * @param {{timeoutMs?: number, cwd?: string, env?: object, spawnImpl?: Function, splitRe?: RegExp, isCancelled?: () => boolean}} [options]
* `timeoutMs: 0` (default) means no timeout. `splitRe` is forwarded to the
* line readers — pass `/[\r\n]+/` for a tool whose progress bar redraws the
* same line with a bare `\r`, so each redraw surfaces instead of the stream
- * going silent for the length of a multi-gigabyte download.
+ * going silent for the length of a multi-gigabyte download. `isCancelled` is
+ * polled while the command runs; see CANCEL_POLL_MS.
* @returns {Promise<{success: boolean, error?: string}>}
*/
-export function runStreamingCommand(cmd, args, onLine, { timeoutMs = 0, cwd, env, spawnImpl = spawn, splitRe } = {}) {
+export function runStreamingCommand(cmd, args, onLine, { timeoutMs = 0, cwd, env, spawnImpl = spawn, splitRe, isCancelled } = {}) {
return new Promise((resolve) => {
const child = spawnImpl(cmd, args, safeChildProcessOptions({
env: env ? safeChildProcessEnv(env) : process.env,
@@ -58,6 +66,7 @@ export function runStreamingCommand(cmd, args, onLine, { timeoutMs = 0, cwd, env
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
+ if (cancelTimer) clearInterval(cancelTimer);
resolve(result);
};
@@ -68,6 +77,25 @@ export function runStreamingCommand(cmd, args, onLine, { timeoutMs = 0, cwd, env
}, timeoutMs)
: null;
+ // A command that runs for hours (a model-weights download) outlives the
+ // request that asked for it, and a caller holding a lock until this settles
+ // holds it for the whole run. Polling is what lets a closed stream actually
+ // STOP the child — `timeoutMs` alone only bounds the worst case.
+ //
+ // The callback runs outside the Express request lifecycle, so a throwing
+ // `isCancelled` would take the process down with no `next(err)` to bubble to
+ // (see the try/catch exception in CLAUDE.md). A predicate that cannot be
+ // asked is treated as "not cancelled" — the timeout still bounds the run.
+ const cancelTimer = typeof isCancelled === 'function'
+ ? setInterval(() => {
+ let cancelled = false;
+ try { cancelled = isCancelled(); } catch (err) { console.error(`⚠️ cancellation check failed for ${cmd}: ${err.message}`); }
+ if (!cancelled) return;
+ child.kill('SIGKILL');
+ finish({ success: false, error: 'cancelled' });
+ }, CANCEL_POLL_MS)
+ : null;
+
// ONE reader per stream — never a shared buffer. Chunks arrive on arbitrary
// byte boundaries, so a single carry shared by stdout and stderr splices a
// half-written stdout line onto the next stderr chunk: `npm install` writing
diff --git a/server/lib/streamingSpawn.test.js b/server/lib/streamingSpawn.test.js
index 4b73d9c9a6..5480fb109c 100644
--- a/server/lib/streamingSpawn.test.js
+++ b/server/lib/streamingSpawn.test.js
@@ -38,6 +38,35 @@ describe('runStreamingCommand', () => {
expect(result.error).toBeTruthy();
});
+ it('kills a command the caller cancels, without waiting for its timeout', async () => {
+ // A weights download runs for hours and the caller holds a lock until this
+ // settles, so a closed stream has to actually STOP the child — a timeout
+ // bounds the worst case, it does not answer a cancel.
+ let cancelled = false;
+ setTimeout(() => { cancelled = true; }, 50);
+ const result = await runStreamingCommand(
+ NODE,
+ ['-e', 'setTimeout(() => {}, 600000)'],
+ undefined,
+ { timeoutMs: 600_000, isCancelled: () => cancelled },
+ );
+
+ expect(result).toEqual({ success: false, error: 'cancelled' });
+ }, 20_000);
+
+ it('treats a throwing cancellation check as "not cancelled" rather than crashing', async () => {
+ // The poll fires outside the Express request lifecycle: an uncaught throw
+ // there takes the process down, with no `next(err)` to bubble to.
+ const result = await runStreamingCommand(
+ NODE,
+ ['-e', 'console.log("done")'],
+ undefined,
+ { isCancelled: () => { throw new Error('gone'); } },
+ );
+
+ expect(result).toEqual({ success: true });
+ });
+
it('kills a command that outruns its timeout', async () => {
const result = await runStreamingCommand(
NODE,
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 5e7b6b05dd..cfe9189a04 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -381,10 +381,12 @@ export function createPortOSProviderRoutes(aiToolkit) {
}
// Which of the fixed steps the checklist's button named. Matched against the
// closed set rather than passed through, so the only thing an unexpected
- // value can do is 400 — it never reaches a command. `install-start` is the
- // default because that is the shape every pre-`action` client sends.
- const action = req.query.action ? String(req.query.action) : 'install-start';
- if (!SETUP_ACTIONS.includes(action)) {
+ // value can do is 400 — it never reaches a command. Absent stays `null`
+ // rather than becoming a default here: a client built before this parameter
+ // existed still renders THIS server's button label, so the service resolves
+ // what the checklist is currently offering instead of assuming a start.
+ const action = req.query.action ? String(req.query.action) : null;
+ if (action !== null && !SETUP_ACTIONS.includes(action)) {
throw new ServerError('Unknown setup action.', { status: 400, code: 'UNKNOWN_SETUP_ACTION', context: { action } });
}
diff --git a/server/routes/providers.readiness.test.js b/server/routes/providers.readiness.test.js
index a6836b1d59..c66aaf12c3 100644
--- a/server/routes/providers.readiness.test.js
+++ b/server/routes/providers.readiness.test.js
@@ -91,15 +91,18 @@ describe('POST /api/providers/readiness/setup', () => {
expect(frames(response.text).at(-1)).toEqual({ type: 'complete', message: 'Ollama is running.' });
});
- it('forwards the action the checklist button named, defaulting to install-start', async () => {
+ it('forwards the action the checklist button named, and null when it names none', async () => {
// `pull-start` is the only action that downloads model weights, so it has
- // to survive the trip from the button to the service — and every older
- // client, which sends no action at all, must keep its old behavior.
+ // to survive the trip from the button to the service.
await request(app([CLAUDE_OLLAMA])).post('/api/providers/readiness/setup?provider=claude-ollama&action=pull-start');
expect(setupService.runLocalRuntimeSetup.mock.calls[0][1]).toMatchObject({ action: 'pull-start' });
+ // An absent action stays absent rather than becoming a default HERE: a
+ // client built before this parameter still renders this server's button
+ // label, so the service resolves what the checklist is offering. Defaulting
+ // to a start in the route would hide that from it.
await request(app([CLAUDE_OLLAMA])).post('/api/providers/readiness/setup?provider=claude-ollama');
- expect(setupService.runLocalRuntimeSetup.mock.calls[1][1]).toMatchObject({ action: 'install-start' });
+ expect(setupService.runLocalRuntimeSetup.mock.calls[1][1]).toMatchObject({ action: null });
});
it('rejects an action outside the fixed set rather than passing it through', async () => {
diff --git a/server/services/localRuntimeSetup.js b/server/services/localRuntimeSetup.js
index 54f77cd825..7471e88f67 100644
--- a/server/services/localRuntimeSetup.js
+++ b/server/services/localRuntimeSetup.js
@@ -250,18 +250,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.' };
},
+ /**
+ * What MTPLX's own cache holds, WITHOUT starting it — `mtplx models --json`
+ * is a local directory listing. Sits next to the `pull` step it gates so
+ * the two cannot drift, and `providerReadiness.js` reads it through
+ * `readRuntimeWeights` to put the same fact on the checklist.
+ */
+ async weights() {
+ return describeMtplxCache(await listMtplxCachedModels()).state;
+ },
/**
* Fetch MTPLX's OWN default verified checkpoint — no repo id from the
* request, so this cannot be pointed at an arbitrary download. Runs only
* for the `pull-start` action, which the user clicks by its full name.
*/
- async pull({ emit }) {
+ async pull({ emit, isCancelled }) {
const binary = findCommandOnPath('mtplx');
if (!binary) return { success: false, error: '`mtplx` was not found on PortOS\'s PATH. Restart PortOS so it picks up the new bin directory, then try again.' };
emit('Downloading MTPLX\'s default verified checkpoint. This is a multi-gigabyte download and can take a long while — leave this window open to watch it.');
// `mtplx pull` redraws one progress line with a bare `\r`; splitting on
// newlines alone would leave the stream silent for the whole download.
- return runStreamingCommand(binary, ['pull'], emit, { timeoutMs: WEIGHTS_TIMEOUT_MS, splitRe: PROGRESS_SPLIT_RE });
+ // `isCancelled` is load-bearing here, not decoration: this is the one
+ // step that can run for HOURS, and the route holds its single-setup lock
+ // until this promise settles. Without it, closing the modal leaves the
+ // download running and every other runtime's setup button refused for the
+ // rest of it.
+ return runStreamingCommand(binary, ['pull'], emit, { timeoutMs: WEIGHTS_TIMEOUT_MS, splitRe: PROGRESS_SPLIT_RE, isCancelled });
},
async start({ emit, endpoint, isCancelled }) {
// `mtplx serve` defaults `--model` to ONE hard-coded checkpoint and exits
@@ -372,6 +386,25 @@ const SETUP_ROWS = Object.freeze({
}),
});
+/**
+ * What a runtime's own model cache holds, without starting it. `'unknown'` for
+ * every runtime with no cache PortOS can read offline — never `'empty'`, which
+ * would claim a fact PortOS does not have.
+ *
+ * Exported so `providerReadiness.js` reports the checklist from the SAME fact
+ * `describeRuntimeSetup` picks a button from; a second copy of the reader table
+ * over there is how the two would drift into disagreeing about one cache.
+ *
+ * @returns {Promise<'unknown'|'empty'|'partial'|'ready'>}
+ */
+export async function readRuntimeWeights(kind) {
+ const read = SETUP_ROWS[kind]?.weights;
+ return read ? read() : 'unknown';
+}
+
+/** The cache states that make a start impossible. */
+export const weightsBlockStart = (weights) => weights === 'empty' || weights === 'partial';
+
/** True when this host can run the runtime's setup at all. */
function platformSupported(row) {
return !row.platforms || row.platforms.includes(process.platform);
@@ -414,7 +447,7 @@ export function describeRuntimeSetup(kind, { installed, running, weights = 'unkn
// Only offered once the binary is here: the cache cannot be read without it,
// so an uninstalled runtime's `weights` says nothing and `install-start`
// stays the honest first step.
- const needsWeights = Boolean(row.pull) && !needsInstall && needsStart && (weights === 'empty' || weights === 'partial');
+ const needsWeights = Boolean(row.pull) && !needsInstall && needsStart && weightsBlockStart(weights);
const action = needsWeights ? 'pull-start'
: needsInstall && needsStart ? 'install-start'
: needsInstall ? 'install' : 'start';
@@ -442,10 +475,12 @@ export function describeRuntimeSetup(kind, { installed, running, weights = 'unkn
* `isCancelled` is checked between steps so a closed modal does not go on to
* start a daemon nobody is watching for. `action` is the one the checklist's
* button named; only `pull-start` adds a step (the model download), and it is
- * opt-in precisely so no other action can spend gigabytes of bandwidth.
+ * opt-in precisely so no other action can spend gigabytes of bandwidth. Omit
+ * it (`null`) and this resolves the action the checklist would offer right
+ * now — see the resolution comment below.
* @returns {Promise<{success: boolean, error?: string, message?: string}>}
*/
-export async function runLocalRuntimeSetup(kind, { endpoint, emit = () => {}, isCancelled = () => false, action = 'install-start' }) {
+export async function runLocalRuntimeSetup(kind, { endpoint, emit = () => {}, isCancelled = () => false, action = null }) {
const row = SETUP_ROWS[kind];
const runtime = LOCAL_RUNTIMES[kind];
if (!row || !runtime) return { success: false, error: `PortOS has no automatic setup for \`${String(kind)}\`.` };
@@ -462,11 +497,32 @@ export async function runLocalRuntimeSetup(kind, { endpoint, emit = () => {}, is
}
if (!platformSupported(row)) return { success: false, error: row.unsupportedReason };
+ // Refuse a step this runtime does not have BEFORE anything is installed. A
+ // `pull-start` aimed at Ollama would otherwise run Ollama's install on its way
+ // to being refused, and llama.cpp (`start: null`) would return the
+ // install-succeeded message without ever refusing at all.
+ if (action === 'pull-start' && !row.pull) {
+ return { success: false, error: `PortOS cannot download model weights for ${runtime.label}.` };
+ }
+
// Same two signals `providerReadiness.js` uses: the binary on PATH, plus LM
// Studio's macOS app bundle, which serves without ever putting `lms` there.
const installed = Boolean(runtime.command && findCommandOnPath(runtime.command)) ||
(kind === 'lmstudio' && isLmStudioAppInstalled());
+ // A request that names NO action came from a client built before `pull-start`
+ // existed — a stale `client/dist` (`pm2 restart` does not rebuild it) or a tab
+ // open across an upgrade. That client still renders THIS server's
+ // `setup.actionLabel`, so the user clicked a button reading “Download the
+ // default model & start MTPLX”; defaulting to a plain start would answer that
+ // click with the very "no model weights are cached" dead end this action
+ // exists to remove. Resolve what the checklist is offering instead, which is
+ // by construction the label they clicked.
+ // `installed &&` mirrors `describeRuntimeSetup`'s own gate: the cache cannot
+ // be read without the binary, so an uninstalled runtime never resolves to a
+ // download — and never spends a cache read to learn that.
+ const resolved = action || (row.pull && installed && weightsBlockStart(await row.weights()) ? 'pull-start' : 'install-start');
+
if (!installed) {
const result = await row.install({ emit, endpoint: target, isCancelled });
if (!result.success) return { success: false, error: `${runtime.label} install failed: ${result.error}` };
@@ -485,9 +541,8 @@ export async function runLocalRuntimeSetup(kind, { endpoint, emit = () => {}, is
// clicked a button that says so. `describeRuntimeSetup` offers it exactly
// when the cache is provably unusable, which is the state where a plain
// Start would exit before binding a port.
- if (action === 'pull-start') {
- if (!row.pull) return { success: false, error: `PortOS cannot download model weights for ${runtime.label}.` };
- const pulled = await row.pull({ emit });
+ if (resolved === 'pull-start') {
+ const pulled = await row.pull({ emit, isCancelled });
if (!pulled.success) return { success: false, error: `${runtime.label} model download failed: ${pulled.error}` };
emit(`${runtime.label}'s default checkpoint is cached.`);
if (isCancelled()) return { success: false, error: 'Cancelled after the download — the weights are cached, but nothing was started.' };
diff --git a/server/services/localRuntimeSetup.test.js b/server/services/localRuntimeSetup.test.js
index a48160a8a8..2054eebc47 100644
--- a/server/services/localRuntimeSetup.test.js
+++ b/server/services/localRuntimeSetup.test.js
@@ -45,7 +45,7 @@ const vllmProject = vi.hoisted(() => ({
}));
vi.mock('../lib/vllmQwenProject.js', () => vllmProject);
-import { describeRuntimeSetup, runLocalRuntimeSetup, SETUP_ACTIONS, SETUP_RUNTIME_KINDS } from './localRuntimeSetup.js';
+import { describeRuntimeSetup, readRuntimeWeights, runLocalRuntimeSetup, SETUP_ACTIONS, SETUP_RUNTIME_KINDS } from './localRuntimeSetup.js';
const unreachable = { reachable: false, models: null, error: 'ECONNREFUSED' };
/** A spawned daemon whose stdio never emits, driven entirely by the poll loop. */
@@ -394,19 +394,109 @@ describe('runLocalRuntimeSetup', () => {
expect(result.success).toBe(true);
});
- it('never downloads weights behind a plain start', async () => {
- // A multi-gigabyte download is a decision; only the button that says so
- // may spend it. Both of the refusals below reach `mtplx pull` in PROSE.
+ it('never downloads weights behind an explicit plain start', async () => {
+ // A multi-gigabyte download is a decision; only the action that says so may
+ // spend it. A `start` reaches `mtplx pull` in PROSE and nowhere else.
mtplxCache.listMtplxCachedModels.mockResolvedValue(cachedModels([]));
pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');
probe.probeOpenAiModels.mockResolvedValue(unreachable);
const restore = pinPlatform('darwin');
- await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1', action: 'start' });
+ const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1', action: 'start' });
+ restore();
+
+ expect(streaming.runStreamingCommand).not.toHaveBeenCalled();
+ expect(result).toMatchObject({ success: false, error: expect.stringContaining('mtplx pull') });
+ });
+
+ it('resolves an ABSENT action to whatever the checklist is currently offering', async () => {
+ // A client built before `pull-start` existed sends no action — but it still
+ // renders THIS server's button label, so on an empty cache the user clicked
+ // “Download the default model & start MTPLX”. Defaulting to a start would
+ // answer that click with the exact no-weights dead end the action removes.
+ const daemon = fakeChild();
+ child.spawn.mockReturnValue(daemon);
+ pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');
+ mtplxCache.listMtplxCachedModels
+ .mockResolvedValueOnce(cachedModels([]))
+ .mockResolvedValueOnce(cachedModels([{ repo_id: 'Example/Fresh', validation: { ok: true } }]));
+ 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(streaming.runStreamingCommand.mock.calls[0][1]).toEqual(['pull']);
+ expect(result.success).toBe(true);
+ });
+
+ it('resolves an ABSENT action to a plain start when the cache can serve', async () => {
+ 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');
+
await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });
restore();
expect(streaming.runStreamingCommand).not.toHaveBeenCalled();
+ expect(child.spawn.mock.calls[0][1]).toContain('serve');
+ });
+
+ it('refuses `pull-start` for a runtime with no pull step BEFORE installing anything', async () => {
+ // Reached after the route validated only membership in the global action
+ // list. Refusing late would run Ollama's install on the way to the refusal,
+ // and llama.cpp (`start: null`) would return its install-succeeded message
+ // without ever refusing at all.
+ pathLookup.findCommandOnPath.mockReturnValue(null);
+ probe.probeOpenAiModels.mockResolvedValue(unreachable);
+
+ for (const kind of ['ollama', 'llama']) {
+ const result = await runLocalRuntimeSetup(kind, { endpoint: 'http://127.0.0.1:11434/v1', action: 'pull-start' });
+ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/cannot download model weights/) });
+ }
+ expect(localLlm.installBackend).not.toHaveBeenCalled();
+ expect(llama.installLlamaServer).not.toHaveBeenCalled();
+ });
+
+ it('hands the download a cancellation hook — the setup lock is held until it settles', async () => {
+ // The route holds its single-setup lock until this promise resolves, and a
+ // weights pull can run for hours. Without a hook the child ignores a closed
+ // modal, so the download keeps going AND every other runtime's setup button
+ // is refused for the rest of it.
+ pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');
+ child.spawn.mockReturnValue(fakeChild());
+ // Let the daemon come up, so this case ends at a settled setup rather than
+ // spinning the start poll until its three-minute deadline.
+ probe.probeOpenAiModels
+ .mockResolvedValueOnce(unreachable)
+ .mockResolvedValueOnce(unreachable)
+ .mockResolvedValueOnce(reachable(['mtplx']))
+ .mockResolvedValueOnce(reachable(['mtplx']));
+ const isCancelled = () => false;
+ const restore = pinPlatform('darwin');
+
+ await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1', action: 'pull-start', isCancelled });
+ restore();
+
+ expect(streaming.runStreamingCommand.mock.calls[0][3]).toMatchObject({ isCancelled });
+ });
+
+ it('reads no model cache for a runtime that has none', async () => {
+ // `readRuntimeWeights` is what keeps the readiness poll from spending a
+ // subprocess per non-MTPLX runtime.
+ await expect(readRuntimeWeights('ollama')).resolves.toBe('unknown');
+ await expect(readRuntimeWeights('nonsense')).resolves.toBe('unknown');
+ expect(mtplxCache.listMtplxCachedModels).not.toHaveBeenCalled();
});
it('stops at a failed download rather than starting a server that cannot serve', async () => {
diff --git a/server/services/providerReadiness.js b/server/services/providerReadiness.js
index d03ef23c83..e387c6e6e1 100644
--- a/server/services/providerReadiness.js
+++ b/server/services/providerReadiness.js
@@ -35,10 +35,9 @@
import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';
import { isConfiguredDefaultModel } from '../lib/providerModels.js';
-import { describeMtplxCache, listMtplxCachedModels } from '../lib/mtplxModels.js';
import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
import { findCommandOnPath } from '../lib/processEnv.js';
-import { describeRuntimeSetup } from './localRuntimeSetup.js';
+import { describeRuntimeSetup, readRuntimeWeights, weightsBlockStart } from './localRuntimeSetup.js';
import { isAppInstalled as isLmStudioAppInstalled } from './lmStudioManager.js';
/**
@@ -74,18 +73,6 @@ const BINARY_TTL_MS = 60_000;
*/
const WEIGHTS_TTL_MS = 60_000;
-/**
- * How to read a runtime's model cache WITHOUT starting it, for the runtimes
- * where that is possible. Ollama and LM Studio need their daemon up to list
- * anything (and the Models → LLMs page owns their downloads anyway);
- * llama.cpp's weights are a GGUF path the user picks; the vLLM stack's weights
- * ship inside an operator-prepared compose project. MTPLX alone answers
- * `mtplx models --json` offline.
- */
-const WEIGHT_CACHE_READERS = Object.freeze({
- mtplx: async () => describeMtplxCache(await listMtplxCachedModels()).state,
-});
-
// endpoint + key → { at, promise } — the PROMISE, not the settled value, so N
// providers sharing one endpoint in the same batch share one socket instead of
// all missing a not-yet-written cache entry at once. The key is part of the
@@ -144,9 +131,9 @@ ${apiKey}`;
* say so up front and offer the download instead of the start.
*
* A cache that could not be read reports `'unknown'` — never `'empty'`, which
- * would claim a fact PortOS does not have. Only called for a kind in
- * `WEIGHT_CACHE_READERS`; everything else answers `'unknown'` at the call site
- * without spending a subprocess.
+ * would claim a fact PortOS does not have, and so does a runtime with no cache
+ * PortOS can read offline (`readRuntimeWeights` answers those without spending
+ * a subprocess).
*
* TTL-cached — see WEIGHTS_TTL_MS.
*
@@ -159,7 +146,7 @@ function readWeightsStateCached(kind) {
// Cached BEFORE the await so concurrent providers on one runtime share the
// subprocess; dropped on an unexpected throw so a transient failure cannot
// poison the entry for its whole TTL (same shape as the probe cache above).
- const promise = WEIGHT_CACHE_READERS[kind]().catch((err) => {
+ const promise = readRuntimeWeights(kind).catch((err) => {
weightsCache.delete(kind);
throw err;
});
@@ -220,9 +207,6 @@ function weightsDetail(runtime, weights) {
return null;
}
-/** True for the cache states that make a start impossible. */
-const blocksStart = (weights) => weights === 'empty' || weights === 'partial';
-
/** The `runtime` check — is the daemon's software here at all? */
function runtimeCheck(runtime, { onPath, appInstalled, installed, reachable, setup }) {
const detail = onPath ? `\`${runtime.command}\` is on PortOS's PATH.`
@@ -254,7 +238,7 @@ function serverCheck(runtime, { installed, result, setup, weights = 'unknown' })
// Name the blocker in the SAME line that says nothing answered. Otherwise the
// checklist reads "installed ✓ / not responding — just press Start", and
// Start is the thing that cannot work until the weights land.
- const blocked = blocksStart(weights) ? weightsDetail(runtime, weights) : null;
+ const blocked = weightsBlockStart(weights) ? weightsDetail(runtime, weights) : null;
return {
id: 'server',
label: `${runtime.label} server responding`,
@@ -284,7 +268,7 @@ function modelCheck(runtime, wanted, served, probeError = null, { weights = 'unk
: weightsDetail(runtime, weights) || 'Cannot be checked until the server responds.';
// An unservable cache is the ONE unknown here that has a fix: the download
// that makes a start possible at all.
- const fixHint = blocksStart(weights) ? setupHint(setup, 'pull') : null;
+ const fixHint = weightsBlockStart(weights) ? setupHint(setup, 'pull') : null;
return { id: 'model', label, ok: null, detail, fixHint };
}
if (served.includes(wanted)) {
@@ -347,7 +331,7 @@ export async function getProviderReadiness(provider, deps = {}) {
// What the runtime's own model cache holds. Only worth asking when the daemon
// is installed and NOT answering: a running server's `/v1/models` is the
// better answer, and an uninstalled runtime has no cache to read.
- const weights = installed && !result.reachable && WEIGHT_CACHE_READERS[runtime.kind]
+ const weights = installed && !result.reachable
? await (deps.readWeights || readWeightsStateCached)(runtime.kind)
: 'unknown';
diff --git a/server/services/providerReadiness.test.js b/server/services/providerReadiness.test.js
index 4dc8c64b19..e0eb66d1c2 100644
--- a/server/services/providerReadiness.test.js
+++ b/server/services/providerReadiness.test.js
@@ -254,11 +254,12 @@ describe('getProviderReadiness', () => {
expect(checkById(readiness, 'model').detail).toMatch(/Weights are cached locally/);
});
- it('never reads a model cache it has no reason to — or cannot', async () => {
+ it('never reads a model cache it has no reason to', async () => {
// A running daemon answers `/v1/models`, which is a better source than its
// cache; an uninstalled one has no cache to read at all. Spawning `mtplx
// models` (a directory walk) on either would burn a subprocess per 20s poll
- // for nothing.
+ // for nothing. (A runtime with no readable cache is filtered one level
+ // down, by `readRuntimeWeights` — see its test in localRuntimeSetup.)
const restore = pinPlatform('darwin');
const reads = [];
const readWeights = async (kind) => { reads.push(kind); return 'empty'; };
@@ -270,8 +271,6 @@ describe('getProviderReadiness', () => {
{ id: 'opencode-mtplx', command: 'opencode', mtplxBacked: true, defaultModel: 'mtplx' },
{ findCommand: () => null, probe: unreachable(), readWeights },
);
- // ...and a runtime with no cache PortOS can read never asks either.
- await getProviderReadiness(llamaProvider(), { findCommand: () => '/opt/homebrew/bin/llama-server', probe: unreachable(), readWeights });
restore();
expect(reads).toEqual([]);
});