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

Add a one-click "Install & start" button to the local-runtime checklist

Adam Eivy56b3187191ab
diff --git a/client/src/components/install/RuntimeInstallModal.jsx b/client/src/components/install/RuntimeInstallModal.jsx
index 5d124dd65b..0416fda498 100644
--- a/client/src/components/install/RuntimeInstallModal.jsx
+++ b/client/src/components/install/RuntimeInstallModal.jsx
@@ -18,6 +18,11 @@ export default function RuntimeInstallModal({
open,
runtime,
label,
+ // Heading + completion prose. Defaults read as an install because that is
+ // what every original caller does; a caller whose action is "start this
+ // daemon" passes its own so the modal doesn't claim an install that isn't
+ // happening.
+ title,
onClose,
onComplete,
installUrlBase = '/api/video-gen/setup/runtime-install',
@@ -73,7 +78,7 @@ export default function RuntimeInstallModal({
: error ? <AlertCircle size={18} className="text-port-error" />
: <Download size={18} className="text-port-accent" />}
<h2 id="runtime-install-title" className="text-sm font-semibold text-white">
- Installing {label || runtime}
+ {title || `Installing ${label || runtime}`}
</h2>
</div>
<button
diff --git a/client/src/components/providers/ProviderCard.jsx b/client/src/components/providers/ProviderCard.jsx
index ba71d393e4..0d9f6c8576 100644
--- a/client/src/components/providers/ProviderCard.jsx
+++ b/client/src/components/providers/ProviderCard.jsx
@@ -87,6 +87,7 @@ export default function ProviderCard({
onDelete,
onRecover,
onInstallRuntime,
+ onAutoSetupRuntime,
}) {
const style = CARD_STATE_STYLES[cardState.state];
return (
@@ -164,7 +165,11 @@ export default function ProviderCard({
provider points at installed, up, and serving the model it names.
Distinct from the card STATE above — that one is about the toggle
and the credentials, this one probes the daemon. */}
- <ProviderReadiness className="mt-2" readiness={daemonReadiness} />
+ <ProviderReadiness
+ className="mt-2"
+ readiness={daemonReadiness}
+ onAutoSetup={(setup) => onAutoSetupRuntime?.({ ...setup, providerId: provider.id })}
+ />
{provider.enabled && status?.available === false && (
<div className="mt-2 text-xs rounded border border-port-error/40 bg-port-error/10 px-3 py-2 text-port-error space-y-1">
diff --git a/client/src/components/providers/ProviderReadiness.jsx b/client/src/components/providers/ProviderReadiness.jsx
index 76ce8f5ea2..c23d65c8a4 100644
--- a/client/src/components/providers/ProviderReadiness.jsx
+++ b/client/src/components/providers/ProviderReadiness.jsx
@@ -10,13 +10,19 @@
* transcript.
*
* `readiness` is one entry of the map from `GET /api/providers/readiness`
- * (`{ kind, label, endpoint, ready, checks, manageUrl, docsUrl }`). Renders
- * nothing without one, so providers with no local dependency — and cards drawn
- * before the fetch resolves — show no checklist at all.
+ * (`{ kind, label, endpoint, ready, checks, manageUrl, docsUrl, setup }`).
+ * Renders nothing without one, so providers with no local dependency — and
+ * cards drawn before the fetch resolves — show no checklist at all.
+ *
+ * `setup` is the one-click fix: when PortOS can install and/or start this
+ * daemon itself (`services/localRuntimeSetup.js`), the banner leads with that
+ * button instead of a setup-doc link. The docs link stays as a secondary
+ * affordance — it is the right answer for the checks a button cannot fix (which
+ * model to download) and for a host the setup does not support.
*/
import { Link } from 'react-router';
-import { CheckCircle2, HelpCircle, Wrench, XCircle } from 'lucide-react';
+import { CheckCircle2, HelpCircle, Wand2, Wrench, XCircle } from 'lucide-react';
import Banner from '../ui/Banner';
import Pill from '../ui/Pill';
@@ -49,9 +55,9 @@ function CodeText({ text }) {
);
}
-export default function ProviderReadiness({ readiness, className = '' }) {
+export default function ProviderReadiness({ readiness, onAutoSetup, className = '' }) {
if (!readiness || !Array.isArray(readiness.checks) || readiness.checks.length === 0) return null;
- const { label, endpoint, ready, checks, manageUrl, docsUrl } = readiness;
+ const { label, endpoint, ready, checks, manageUrl, docsUrl, setup } = readiness;
if (ready) {
return (
@@ -89,6 +95,17 @@ export default function ProviderReadiness({ readiness, className = '' }) {
})}
</ul>
<div className="flex flex-wrap items-center gap-3 pt-1.5">
+ {setup?.action && onAutoSetup && (
+ <button
+ type="button"
+ onClick={() => onAutoSetup(setup)}
+ className="inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 transition-colors font-medium"
+ title={`PortOS runs this on ${endpoint} for you — no terminal needed.`}
+ >
+ <Wand2 size={12} />
+ {setup.actionLabel}
+ </button>
+ )}
{manageUrl && (
<Link to={manageUrl} className={LINK_CLASS}>Open Local LLM settings</Link>
)}
diff --git a/client/src/components/providers/ProviderReadiness.test.jsx b/client/src/components/providers/ProviderReadiness.test.jsx
index a8f7451e2e..8c115006ef 100644
--- a/client/src/components/providers/ProviderReadiness.test.jsx
+++ b/client/src/components/providers/ProviderReadiness.test.jsx
@@ -1,5 +1,5 @@
-import { describe, it, expect } from 'vitest';
-import { render, screen } from '@testing-library/react';
+import { describe, it, expect, vi } from 'vitest';
+import { fireEvent, render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router';
import ProviderReadiness from './ProviderReadiness';
@@ -12,6 +12,7 @@ const readiness = (overrides = {}) => ({
manageUrl: '/settings/local-llm',
docsUrl: 'https://example.com/llama-docs',
ready: false,
+ setup: null,
checks: [
{ id: 'runtime', label: 'llama.cpp installed', ok: true, detail: '`llama-server` is on PortOS\'s PATH.', fixHint: null },
{ id: 'server', label: 'llama.cpp server responding', ok: false, detail: 'Nothing answered at http://127.0.0.1:8080/v1 (connection refused).', fixHint: 'Start llama.cpp — it serves GGUF weights you download yourself.' },
@@ -63,6 +64,37 @@ describe('ProviderReadiness', () => {
expect(screen.getByText('MTPLX setup docs')).toBeTruthy();
});
+ it('offers the one-click setup instead of leaving a docs link as the only way forward', () => {
+ const onAutoSetup = vi.fn();
+ const setup = { runtime: 'mtplx', label: 'MTPLX', action: 'install-start', actionLabel: 'Install & start MTPLX', blockedReason: null };
+ renderWithRouter(
+ <ProviderReadiness readiness={readiness({ label: 'MTPLX', manageUrl: null, setup })} onAutoSetup={onAutoSetup} />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: /Install & start MTPLX/ }));
+ expect(onAutoSetup).toHaveBeenCalledWith(setup);
+ // The docs stay reachable — they answer the checks a button cannot fix.
+ expect(screen.getByText('MTPLX setup docs')).toBeTruthy();
+ });
+
+ it('shows no setup button when the host cannot run the runtime', () => {
+ renderWithRouter(
+ <ProviderReadiness
+ readiness={readiness({ setup: { runtime: 'mtplx', label: 'MTPLX', action: null, actionLabel: null, blockedReason: 'MTPLX runs only on macOS with Apple Silicon.' } })}
+ onAutoSetup={vi.fn()}
+ />,
+ );
+ expect(screen.queryByRole('button')).toBeNull();
+ });
+
+ it('shows no setup button when the card has no handler wired', () => {
+ // The banner is also rendered read-only in places with nothing to click.
+ renderWithRouter(
+ <ProviderReadiness readiness={readiness({ setup: { runtime: 'llama', label: 'llama.cpp', action: 'install', actionLabel: 'Install llama.cpp', blockedReason: null } })} />,
+ );
+ expect(screen.queryByRole('button')).toBeNull();
+ });
+
it('renders backtick-quoted spans as code rather than literal backticks', () => {
const { container } = renderWithRouter(<ProviderReadiness readiness={readiness()} />);
expect(container.textContent).not.toContain('`');
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 376e4e77fa..4b6b9e738a 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -95,6 +95,12 @@ export default function AIProviders() {
const [readiness, setReadiness] = useState({});
// The runtime whose install modal is open (`null` = closed).
const [installingRuntime, setInstallingRuntime] = useState(null);
+ // The local-daemon setup the user asked PortOS to run for them, from a
+ // readiness checklist's action button: `{ runtime, label, actionLabel,
+ // providerId }`. Separate from `installingRuntime` (a CLI binary) because it
+ // streams from a different endpoint and is keyed by the PROVIDER whose
+ // endpoint the daemon must come up on.
+ const [settingUpRuntime, setSettingUpRuntime] = useState(null);
// Ollama / LM Studio install state (and the model lists the editor's pickers
// fold in) — fetched once here rather than inside ProviderForm so opening the
// editor doesn't re-request it.
@@ -330,6 +336,13 @@ export default function AIProviders() {
loadRuntimes();
};
+ // A daemon was just installed/started. Only the readiness checklist changed —
+ // re-poll it so the card's banner collapses to the "ready" pill on its own.
+ const handleRuntimeSetupComplete = () => {
+ toast.success(`${settingUpRuntime?.label || 'Local runtime'} is set up`);
+ loadReadiness();
+ };
+
// The install widget's data for one card: a CLI provider's binary comes from
// the server's runtime table; an API provider fronted by a local app takes the
// local-LLM status, which counts an installed app with no CLI shim on PATH.
@@ -667,6 +680,7 @@ export default function AIProviders() {
onDelete={handleDelete}
onRecover={handleRecover}
onInstallRuntime={setInstallingRuntime}
+ onAutoSetupRuntime={setSettingUpRuntime}
/>
))}
</CollapsibleSection>
@@ -720,6 +734,23 @@ export default function AIProviders() {
flushMs={250}
description={`Installing ${installingRuntime?.label} from ${installingRuntime?.method === 'script' ? "the vendor's official install script" : 'its global npm package'}.`}
/>
+ {/* The readiness checklist's one-click fix. Same streaming modal as the
+ CLI installer, pointed at the local-daemon setup endpoint — which
+ re-derives the runtime and its endpoint from the provider record, so
+ `provider` is the only thing that travels. */}
+ <RuntimeInstallModal
+ open={Boolean(settingUpRuntime)}
+ runtime={settingUpRuntime?.runtime}
+ label={settingUpRuntime?.label}
+ title={settingUpRuntime?.actionLabel}
+ params={settingUpRuntime ? { provider: settingUpRuntime.providerId } : undefined}
+ onClose={() => setSettingUpRuntime(null)}
+ onComplete={handleRuntimeSetupComplete}
+ installUrlBase="/api/providers/readiness/setup"
+ streamMethod="POST"
+ flushMs={250}
+ description={`${settingUpRuntime?.actionLabel || 'Setting up'} — this can take several minutes on a first install.`}
+ />
</div>
</div>
);
diff --git a/docs/API.md b/docs/API.md
index 95aab3f830..2d3918a44f 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -67,7 +67,8 @@ PortOS is designed for personal/developer use on trusted networks. It implements
| PUT | `/providers/active` | Set active provider |
| GET | `/providers/runtimes` | Per-runtime install status (`claude`, `codex`, `opencode`, `grok`, `kimi`, `agy`, `cursor-agent`): is the binary runnable here, and can PortOS install it? Booleans and labels only — never resolved filesystem paths. 60s TTL cache. Ollama / LM Studio are absent on purpose — Settings → Local LLM owns their install. |
| POST | `/providers/runtimes/install?runtime=<id>` | Install one runtime from the installer's fixed table, streaming installer output as SSE. Rejects any id not in the table. |
-| GET | `/providers/readiness` | Requirements checklist per provider backed by a LOCAL daemon (llama.cpp / Ollama / LM Studio / MTPLX), keyed by provider id: is the daemon installed, is it answering at the endpoint THIS provider points at, and is it serving the provider's default model. Providers with no local dependency are absent from the map. Complements `/providers/runtimes` (which answers "can PortOS run this CLI?"). Booleans, labels, and the provider's own endpoint only — never a resolved binary path. Skips disabled providers; 15s endpoint-probe cache (one probe per distinct endpoint), 60s binary-PATH cache, both dropped by the llama-server start/stop/install routes. |
+| GET | `/providers/readiness` | Requirements checklist per provider backed by a LOCAL daemon (llama.cpp / Ollama / LM Studio / MTPLX), keyed by provider id: is the daemon installed, is it answering at the endpoint THIS provider points at, and is it serving the provider's default model. Each entry also carries `setup` — what the one-click fix below can do about the unmet checks (`null` when nothing is auto-fixable here). Providers with no local dependency are absent from the map. Complements `/providers/runtimes` (which answers "can PortOS run this CLI?"). Booleans, labels, and the provider's own endpoint only — never a resolved binary path. Skips disabled providers; 15s endpoint-probe cache (one probe per distinct endpoint), 60s binary-PATH cache, both dropped by the llama-server start/stop/install routes. |
+| POST | `/providers/readiness/setup?provider=<id>` | Install and/or start the LOCAL DAEMON that provider points at (llama.cpp / Ollama / LM Studio / MTPLX), streaming progress as SSE — the "do it for me" half of `/providers/readiness`, so an unmet requirement is fixed from the card instead of from a vendor setup doc. The request names a PROVIDER only: the runtime kind and endpoint are re-derived server-side from the stored record, so no query value reaches a spawn argument (an optional `runtime=` is cross-checked and 409s on a mismatch). Every command comes from a fixed per-runtime table. Never downloads model weights, never starts llama-server (it needs a checkpoint you choose), and never runs MTPLX's privileged fan-control helper. Single-flight. |
| GET | `/providers/opencode/installation` | **Legacy alias**, kept so a stale client bundle still renders: `{ installed, npmAvailable }` for the `opencode` runtime. New code uses `/providers/runtimes`. |
| POST | `/providers/opencode/install` | **Legacy alias** for `/providers/runtimes/install?runtime=opencode`. |
diff --git a/docs/features/mtplx.md b/docs/features/mtplx.md
index ca058e8aaf..0bd5bd5af2 100644
--- a/docs/features/mtplx.md
+++ b/docs/features/mtplx.md
@@ -27,20 +27,40 @@ valid CoS coding-agent runner.
## Setup
-1. Install and validate MTPLX independently using its upstream documentation.
- PortOS does not download model weights, launch its installer, enable optional
- thermal-management helpers, or start a daemon.
-2. Start an MTPLX server for your verified Qwen MTP model on its documented
- loopback OpenAI-compatible endpoint, `http://127.0.0.1:8000/v1`.
-3. On **AI Providers**, enable the matching preset. Use **Refresh Models** only
- after the server is running; PortOS then reads `/v1/models` on demand.
+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
+ 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`
+ 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
- **OpenCode MTPLX** CLI/TUI preset for a CoS coding task. The seed model alias
- is `mtplx`; refresh it if your running server publishes a different alias.
+ **OpenCode MTPLX** CLI/TUI preset for a CoS coding task.
+
+Prefer to run it yourself? Install MTPLX per its upstream documentation and
+start a server on the loopback OpenAI-compatible endpoint the preset points at,
+`http://127.0.0.1:8000/v1`. The checklist notices and collapses to a ready pill.
+
+### What the button does and does not do
+
+- It installs the MTPLX package and starts its **API server only**. Upstream's
+ 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 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.
All presets are disabled by default. Merely updating PortOS does not make a
-network request, invoke a model, tune speculative decoding, or alter the active
-provider. MTPLX tuning remains an explicit operator action outside PortOS.
+network request, invoke a model, tune speculative decoding, alter the active
+provider, or install anything — the setup above runs only from that explicit
+click. MTPLX tuning remains an explicit operator action outside PortOS.
## Operational notes
@@ -51,5 +71,7 @@ provider. MTPLX tuning remains an explicit operator action outside PortOS.
if you intentionally change it, treat the server and model weights as a
separate trusted runtime.
- The source audit that motivated this integration found privileged optional
- thermal-helper and installer paths upstream. The PortOS integration is
- protocol-only so those paths never run as part of PortOS setup or boot.
+ thermal-helper and installer paths upstream. Nothing here runs at PortOS
+ setup or boot, and the one-click setup uses only the published package
+ install plus `mtplx serve`, so those privileged paths never run as part of
+ PortOS at all.
diff --git a/server/lib/README.md b/server/lib/README.md
index 0f84d364fa..f8272d15b3 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -381,6 +381,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?})` — 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. `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/index.js b/server/lib/index.js
index 036de806e7..d5bf2f4fbe 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -357,6 +357,7 @@ export * from './singleFlight.js';
export * from './staleWhileRevalidate.js';
export * from './staticImportGraph.js';
export * from './streamBackpressure.js';
+export * from './streamingSpawn.js';
export * from './sseUtils.js';
export * from './repoIntakeActions.js';
export * from './tombstones.js';
diff --git a/server/lib/localProviderRuntime.js b/server/lib/localProviderRuntime.js
index 489f2691b3..0af4f6e849 100644
--- a/server/lib/localProviderRuntime.js
+++ b/server/lib/localProviderRuntime.js
@@ -156,13 +156,14 @@ export const LOCAL_RUNTIMES = Object.freeze({
mtplx: Object.freeze({
id: 'mtplx',
label: 'MTPLX',
- // PortOS ships no installer for MTPLX — it is a user-run process — so the
- // readiness report offers docs instead of an install action.
- command: null,
+ command: 'mtplx',
defaultBaseUrl: opencodeLocalBaseUrl('mtplx'),
+ // No Local LLM tab entry — MTPLX has no model catalog inside PortOS. The
+ // one-click setup on the readiness checklist
+ // (`services/localRuntimeSetup.js`) is what installs and starts it.
manageUrl: null,
docsUrl: 'https://github.com/atomantic/PortOS/blob/main/docs/features/mtplx.md',
- modelsHint: 'Start the MTPLX server yourself; PortOS does not manage that process.',
+ modelsHint: 'Point the server at the Qwen MTP checkpoint you want; PortOS does not download weights.',
}),
});
diff --git a/server/lib/streamingSpawn.js b/server/lib/streamingSpawn.js
new file mode 100644
index 0000000000..af8d7c40f8
--- /dev/null
+++ b/server/lib/streamingSpawn.js
@@ -0,0 +1,100 @@
+/**
+ * Run one command to completion, streaming its stdout/stderr LINES to a hook.
+ *
+ * The install/setup flows (`services/localLlm.js`'s package-manager installs,
+ * `services/localRuntimeSetup.js`'s one-click daemon setup) all need the same
+ * thing: spawn a package manager, forward every line it prints to an SSE frame,
+ * and end up with an actionable `{ success, error }` — where a non-zero exit
+ * carries the TAIL of what the tool actually said, because `brew upgrade ollama`
+ * exiting 1 with stderr "Error: ollama not installed" must surface that string
+ * rather than "exited with code 1".
+ *
+ * Deliberately never rejects: every failure (spawn error, non-zero exit,
+ * timeout) resolves as `{ success: false, error }`. These run outside the
+ * Express request lifecycle — from a child-process callback there is no
+ * `next(err)` to bubble to — so the caller gets a value to report, and the
+ * `onLine` hook is itself guarded for the same reason.
+ *
+ * `bufferedSpawn.js` is the sibling for the other shape: run a command and get
+ * its whole output at the end. Use this one when live output IS the progress.
+ */
+
+import { spawn } from './childProcess.js';
+import { safeChildProcessEnv, safeChildProcessOptions } from './processEnv.js';
+
+/** Char budget for the recent-output tail attached to a failure message. */
+const TAIL_BUDGET = 1024;
+
+/**
+ * @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}} [options]
+ * `timeoutMs: 0` (default) means no timeout.
+ * @returns {Promise<{success: boolean, error?: string}>}
+ */
+export function runStreamingCommand(cmd, args, onLine, { timeoutMs = 0, cwd, env, spawnImpl = spawn } = {}) {
+ return new Promise((resolve) => {
+ const child = spawnImpl(cmd, args, safeChildProcessOptions({
+ env: env ? safeChildProcessEnv(env) : process.env,
+ ...(cwd ? { cwd } : {}),
+ shell: false,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ }));
+
+ let buffer = '';
+ 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;
+ }
+ };
+
+ const safeLine = (line) => {
+ if (!line) return;
+ rememberLine(line);
+ if (typeof onLine !== 'function') return;
+ try { onLine(line); } catch (err) { console.error(`⚠️ streaming output hook failed: ${err.message}`); }
+ };
+
+ const finish = (result) => {
+ if (settled) return;
+ settled = true;
+ if (timer) clearTimeout(timer);
+ resolve(result);
+ };
+
+ const timer = timeoutMs > 0
+ ? setTimeout(() => {
+ child.kill('SIGKILL');
+ finish({ success: false, error: `timed out after ${Math.round(timeoutMs / 1000)}s` });
+ }, timeoutMs)
+ : null;
+
+ const onData = (chunk) => {
+ buffer += chunk.toString();
+ let nl;
+ while ((nl = buffer.indexOf('\n')) !== -1) {
+ safeLine(buffer.slice(0, nl).trim());
+ buffer = buffer.slice(nl + 1);
+ }
+ };
+
+ child.stdout?.on('data', onData);
+ child.stderr?.on('data', onData);
+ child.on('error', (err) => finish({ success: false, error: err.message }));
+ // 'close' rather than 'exit': 'exit' can fire with stdio still buffered,
+ // which would drop the very lines the failure message needs.
+ child.on('close', (code) => {
+ safeLine(buffer.trim());
+ if (code === 0) return finish({ success: true });
+ const detail = tail.join(' — ').trim();
+ finish({ success: false, error: detail ? `exit ${code}: ${detail}` : `exited with code ${code}` });
+ });
+ });
+}
diff --git a/server/lib/streamingSpawn.test.js b/server/lib/streamingSpawn.test.js
new file mode 100644
index 0000000000..3efc6e5b27
--- /dev/null
+++ b/server/lib/streamingSpawn.test.js
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest';
+import { runStreamingCommand } from './streamingSpawn.js';
+
+const NODE = process.execPath;
+
+describe('runStreamingCommand', () => {
+ it('streams stdout and stderr lines in order and resolves success on exit 0', async () => {
+ const lines = [];
+ const result = await runStreamingCommand(
+ NODE,
+ ['-e', 'console.log("one"); console.error("two"); console.log("three")'],
+ (line) => lines.push(line),
+ );
+
+ expect(result).toEqual({ success: true });
+ expect(lines).toContain('one');
+ expect(lines).toContain('two');
+ expect(lines).toContain('three');
+ });
+
+ it('carries the tail of the output into a non-zero exit, not just the code', async () => {
+ // The whole reason for the tail: `brew upgrade ollama` exits 1 saying
+ // "Error: ollama not installed", and "exited with code 1" is not a fix.
+ const result = await runStreamingCommand(
+ NODE,
+ ['-e', 'console.error("Error: ollama not installed"); process.exit(1)'],
+ );
+
+ expect(result.success).toBe(false);
+ expect(result.error).toMatch(/exit 1: .*ollama not installed/);
+ });
+
+ it('resolves rather than rejecting when the binary does not exist', async () => {
+ // Callers run outside the Express request lifecycle — a rejection here
+ // would surface as an unhandled rejection, not as a 500.
+ const result = await runStreamingCommand('portos-no-such-binary-xyz', ['--version']);
+ expect(result.success).toBe(false);
+ expect(result.error).toBeTruthy();
+ });
+
+ it('kills a command that outruns its timeout', async () => {
+ const result = await runStreamingCommand(
+ NODE,
+ ['-e', 'setTimeout(() => {}, 10000)'],
+ undefined,
+ { timeoutMs: 150 },
+ );
+ expect(result).toEqual({ success: false, error: 'timed out after 0s' });
+ });
+
+ it('survives a throwing output hook instead of taking the process down', async () => {
+ const result = await runStreamingCommand(
+ NODE,
+ ['-e', 'console.log("boom")'],
+ () => { throw new Error('hook exploded'); },
+ );
+ expect(result).toEqual({ success: true });
+ });
+});
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 830c484916..abedc1416d 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -15,7 +15,9 @@ import {
spawnRuntimeInstaller,
stopRuntimeInstaller,
} from '../services/providerRuntimeInstaller.js';
-import { getProviderReadinessMap } from '../services/providerReadiness.js';
+import { getProviderReadinessMap, resetProviderReadinessCache } from '../services/providerReadiness.js';
+import { runLocalRuntimeSetup } from '../services/localRuntimeSetup.js';
+import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';
/**
* The CoS Agent Runner's exec allowlist, published read-only so the AI
@@ -40,6 +42,12 @@ const RUNNER_ALLOWED_COMMANDS = [...ALLOWED_COMMANDS].sort();
// in the route so a client disconnect can terminate it.
let runtimeInstallInFlight = null;
+// Same re-entrancy guard for the local-daemon setup lane. Separate from the CLI
+// one because they install different things, but each is single-flight: two
+// concurrent `brew install`s (or two copies of one daemon racing for a port) is
+// never what a double-click meant.
+let runtimeSetupInFlight = false;
+
/**
* Sanitize a provider object for client responses.
* Strips apiKey (replaces with hasApiKey boolean) and redacts secretEnvVars values.
@@ -292,6 +300,89 @@ export function createPortOSProviderRoutes(aiToolkit) {
});
};
+ /**
+ * Install and/or start the LOCAL DAEMON one provider points at, streaming
+ * progress as SSE. This is the "do it for me" half of `/readiness`: the
+ * checklist says llama.cpp / Ollama / LM Studio / MTPLX is missing or down,
+ * and this fixes it without sending the user to a vendor setup doc.
+ *
+ * The request names a PROVIDER id, never an endpoint, port, or command. The
+ * runtime kind and the endpoint are both re-derived server-side from the
+ * stored provider record, so nothing from the query reaches a spawn argument
+ * — the `runtime` param is only cross-checked against what the record
+ * resolves to, so a stale page cannot set up a different daemon than the card
+ * it was clicked on.
+ */
+ router.post('/readiness/setup', asyncHandler(async (req, res) => {
+ const providerId = String(req.query.provider || '');
+ const data = await providerService.getAllProviders();
+ // RAW record on purpose — a sanitized copy redacts the secret env values a
+ // custom base URL can live in, which would resolve the wrong endpoint.
+ const provider = data.providers.find((row) => row.id === providerId);
+ if (!provider) {
+ throw new ServerError('Unknown provider', { status: 404, code: 'UNKNOWN_PROVIDER', context: { provider: providerId } });
+ }
+ const runtime = localRuntimeForProvider(provider);
+ if (!runtime) {
+ throw new ServerError('This provider does not depend on a local runtime PortOS can set up.', { status: 400, code: 'NO_LOCAL_RUNTIME' });
+ }
+ const requested = req.query.runtime ? String(req.query.runtime) : runtime.kind;
+ if (requested !== runtime.kind) {
+ throw new ServerError('This provider no longer uses that runtime — reload the page and try again.', { status: 409, code: 'RUNTIME_MISMATCH' });
+ }
+
+ const { send, safeEnd } = openSseStream(res);
+ const installLog = createInstallLogger({ installer: runtime.label, target: runtime.endpoint });
+ let clientGone = false;
+ let holdsLock = false;
+ onClientDisconnect(req, res, () => {
+ clientGone = true;
+ installLog.cancel();
+ if (holdsLock) runtimeSetupInFlight = false;
+ safeEnd();
+ });
+
+ if (runtimeSetupInFlight) {
+ send({ type: 'error', message: 'Another local-runtime setup is already running. Wait for it to finish.' });
+ return safeEnd();
+ }
+ runtimeSetupInFlight = true;
+ holdsLock = true;
+ if (clientGone) {
+ runtimeSetupInFlight = false;
+ return safeEnd();
+ }
+
+ send({ type: 'stage', stage: 'setup', message: `Setting up ${runtime.label} for ${runtime.endpoint}.` });
+ installLog.start();
+ const emit = (message) => {
+ const event = { type: 'log', message };
+ installLog.onEvent(event);
+ send(event);
+ };
+
+ // `runLocalRuntimeSetup` resolves for every expected failure; the `.catch`
+ // covers the unexpected throw. Either way the headers are already flushed,
+ // so the outcome has to be a terminal SSE frame rather than a 500 body.
+ const result = await runLocalRuntimeSetup(runtime.kind, {
+ endpoint: runtime.endpoint,
+ emit,
+ isCancelled: () => clientGone,
+ }).catch((err) => ({ success: false, error: err.message }));
+
+ if (holdsLock) { runtimeSetupInFlight = false; holdsLock = false; }
+ // A daemon just came up (or a binary just landed) — the readiness caches
+ // remember it being down, and the page polls them within seconds.
+ resetProviderReadinessCache();
+ if (clientGone) return safeEnd();
+ const terminal = result.success
+ ? { type: 'complete', message: result.message || `${runtime.label} is ready.` }
+ : { type: 'error', message: result.error || `${runtime.label} setup failed.` };
+ installLog.onEvent(terminal);
+ send(terminal);
+ safeEnd();
+ }));
+
// `runtime` rides in the query string because the shared RuntimeInstallModal
// already appends it there for every BYO-runtime installer.
router.post('/runtimes/install', asyncHandler(async (req, res) => {
diff --git a/server/routes/providers.readiness.test.js b/server/routes/providers.readiness.test.js
index 80356b6f7e..a41c0a8c8e 100644
--- a/server/routes/providers.readiness.test.js
+++ b/server/routes/providers.readiness.test.js
@@ -3,8 +3,13 @@ import express, { Router } from 'express';
import { errorMiddleware } from '../lib/errorHandler.js';
import { request } from '../lib/testHelper.js';
-const readinessService = vi.hoisted(() => ({ getProviderReadinessMap: vi.fn() }));
+const readinessService = vi.hoisted(() => ({
+ getProviderReadinessMap: vi.fn(),
+ resetProviderReadinessCache: vi.fn(),
+}));
vi.mock('../services/providerReadiness.js', () => readinessService);
+const setupService = vi.hoisted(() => ({ runLocalRuntimeSetup: vi.fn() }));
+vi.mock('../services/localRuntimeSetup.js', () => setupService);
import { createPortOSProviderRoutes } from './providers.js';
// A provider whose real base URL lives in an env var the user marked secret —
@@ -55,3 +60,65 @@ describe('GET /api/providers/readiness', () => {
expect(providers[0].envVars.ANTHROPIC_AUTH_TOKEN).not.toBe('***');
});
});
+
+/** The SSE frames a streamed response carries, in order. */
+const frames = (text) => text
+ .split(/\r?\n\r?\n/)
+ .map((frame) => frame.split(/\r?\n/).find((line) => line.startsWith('data:')))
+ .filter(Boolean)
+ .map((line) => JSON.parse(line.slice('data:'.length).trim()));
+
+describe('POST /api/providers/readiness/setup', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ readinessService.getProviderReadinessMap.mockResolvedValue({});
+ setupService.runLocalRuntimeSetup.mockResolvedValue({ success: true, message: 'Ollama is running.' });
+ });
+
+ it('resolves the runtime and endpoint from the stored provider, never from the query', async () => {
+ const response = await request(app([CLAUDE_OLLAMA]))
+ .post('/api/providers/readiness/setup?provider=claude-ollama&runtime=ollama');
+
+ expect(response.status).toBe(200);
+ const [kind, ctx] = setupService.runLocalRuntimeSetup.mock.calls[0];
+ expect(kind).toBe('ollama');
+ // The base URL comes from the RAW provider record — a query string cannot
+ // point the setup at a different port.
+ expect(ctx.endpoint).toBe('http://localhost:11500/v1');
+ expect(frames(response.text).at(-1)).toEqual({ type: 'complete', message: 'Ollama is running.' });
+ });
+
+ it('drops the probe caches so the next poll sees the daemon that just came up', async () => {
+ await request(app([CLAUDE_OLLAMA])).post('/api/providers/readiness/setup?provider=claude-ollama');
+ expect(readinessService.resetProviderReadinessCache).toHaveBeenCalled();
+ });
+
+ it('reports a failed setup as a terminal error frame, not a 500', async () => {
+ setupService.runLocalRuntimeSetup.mockResolvedValueOnce({ success: false, error: 'brew exploded' });
+
+ const response = await request(app([CLAUDE_OLLAMA])).post('/api/providers/readiness/setup?provider=claude-ollama');
+
+ expect(response.status).toBe(200);
+ expect(frames(response.text).at(-1)).toEqual({ type: 'error', message: 'brew exploded' });
+ });
+
+ it('rejects a stale page whose card named a different runtime', async () => {
+ const response = await request(app([CLAUDE_OLLAMA]))
+ .post('/api/providers/readiness/setup?provider=claude-ollama&runtime=mtplx');
+
+ expect(response.status).toBe(409);
+ expect(setupService.runLocalRuntimeSetup).not.toHaveBeenCalled();
+ });
+
+ it('404s an unknown provider before opening a stream', async () => {
+ const response = await request(app([CLAUDE_OLLAMA])).post('/api/providers/readiness/setup?provider=nope');
+ expect(response.status).toBe(404);
+ expect(setupService.runLocalRuntimeSetup).not.toHaveBeenCalled();
+ });
+
+ it('400s a provider with no local daemon to set up', async () => {
+ const response = await request(app([{ id: 'claude', command: 'claude', type: 'cli' }]))
+ .post('/api/providers/readiness/setup?provider=claude');
+ expect(response.status).toBe(400);
+ });
+});
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index bfaf5c2164..22cee67db3 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -20,7 +20,7 @@
* multimodal). See `server/lib/localLlmDisk.js` for the disk logic.
*/
-import { execFile, spawn } from '../lib/childProcess.js';import { promisify } from 'util'
+import { execFile } from '../lib/childProcess.js';import { promisify } from 'util'
import { readFileSync, createWriteStream } from 'fs'
import { rm } from 'fs/promises'
import { join } from 'path'
@@ -37,6 +37,7 @@ import { recommendEditorialModel, isVisionModel, isVisionCapableCliProvider, isT
// no import cycle: the store deliberately does not import this module.
import { getMeasuredFits } from './localModelAssessmentStore.js'
import { commandExists } from '../lib/commandExists.js'
+import { runStreamingCommand } from '../lib/streamingSpawn.js'
import * as ollamaManager from './ollamaManager.js'
import * as lmStudioManager from './lmStudioManager.js'
import { getProviderById, getAllProviders, updateProvider, refreshProviderModelsBatch, isOllamaBackedProvider } from './providers.js'
@@ -216,67 +217,9 @@ async function brewPackageInstalled(backend) {
const manager = (backend) => (backend === 'ollama' ? ollamaManager : lmStudioManager)
-/**
- * Spawn a command and stream its stdout/stderr lines to `onLine`, resolving
- * `{ success }` on exit. Used for package-manager installs where live output is
- * the only progress signal. Never rejects (errors resolve as `{ success:false }`)
- * and guards the `onLine` hook — this runs outside the request lifecycle.
- *
- * The error path includes a tail of the streamed output (last ~1KB of recent
- * lines) so callers get an actionable message — `brew upgrade ollama` exiting
- * non-zero with stderr "Error: ollama not installed" must surface that string,
- * not just "exited with code 1".
- */
-function runStreaming(cmd, args, onLine, timeoutMs = 0) {
- return new Promise((resolve) => {
- const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] })
- let buffer = ''
- let settled = false
- const tail = [] // recent non-empty lines, capped by char budget for the error message
- let tailChars = 0
- const TAIL_BUDGET = 1024
- const rememberLine = (line) => {
- if (!line) return
- tail.push(line)
- tailChars += line.length + 1
- while (tailChars > TAIL_BUDGET && tail.length > 1) {
- tailChars -= tail.shift().length + 1
- }
- }
- const safeLine = (line) => {
- if (!line) return
- rememberLine(line)
- if (typeof onLine !== 'function') return
- try { onLine(line) } catch (err) { console.error(`⚠️ install progress hook failed: ${err.message}`) }
- }
- const finish = (result) => {
- if (settled) return
- settled = true
- if (timer) clearTimeout(timer)
- resolve(result)
- }
- const timer = timeoutMs > 0
- ? setTimeout(() => { child.kill('SIGKILL'); finish({ success: false, error: `timed out after ${Math.round(timeoutMs / 1000)}s` }) }, timeoutMs)
- : null
- const onData = (chunk) => {
- buffer += chunk.toString()
- let nl
- while ((nl = buffer.indexOf('\n')) !== -1) {
- safeLine(buffer.slice(0, nl).trim())
- buffer = buffer.slice(nl + 1)
- }
- }
- child.stdout.on('data', onData)
- child.stderr.on('data', onData)
- child.on('error', (err) => finish({ success: false, error: err.message }))
- child.on('close', (code) => {
- safeLine(buffer.trim())
- if (code === 0) return finish({ success: true })
- const detail = tail.join(' — ').trim()
- finish({ success: false, error: detail ? `exit ${code}: ${detail}` : `exited with code ${code}` })
- })
- })
-}
+// `runStreaming` moved to lib/streamingSpawn.js — the one-click local-runtime
+// setup flow needs the same line-streamed spawn (see localRuntimeSetup.js).
+const runStreaming = (cmd, args, onLine, timeoutMs = 0) => runStreamingCommand(cmd, args, onLine, { timeoutMs })
/**
* Install a backend's app/binary via the platform package manager (Homebrew on
diff --git a/server/services/localRuntimeSetup.js b/server/services/localRuntimeSetup.js
new file mode 100644
index 0000000000..0dccf8917b
--- /dev/null
+++ b/server/services/localRuntimeSetup.js
@@ -0,0 +1,336 @@
+/**
+ * One-click "make this local runtime work" for the provider readiness checklist.
+ *
+ * `providerReadiness.js` answers WHAT is missing (the daemon isn't installed,
+ * isn't running, isn't serving the right model). Until this module existed, the
+ * answer to "so fix it" was a link — to the Local LLM settings tab for the two
+ * backends PortOS manages, and to the vendor's README for MTPLX, which is a
+ * dead end inside PortOS: the user leaves the app, reads a setup doc, runs two
+ * commands in a terminal, comes back and reloads. This module makes the
+ * checklist actionable in place: install the daemon, start it, and confirm the
+ * endpoint answers — from the button next to the failing check.
+ *
+ * Every command here comes from the fixed table below. A request names a
+ * runtime *kind* (`mtplx` / `llama` / `ollama` / `lmstudio`) and nothing else —
+ * no package, URL, port, or argument from the request ever reaches a shell
+ * word, which keeps this as narrow as `providerRuntimeInstaller.js`'s CLI
+ * install surface while removing the docs dead end.
+ *
+ * Two deliberate limits, because guessing here would be worse than a link:
+ *
+ * - **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.
+ * - **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
+ * helper stays an explicit operator action outside PortOS, exactly as
+ * `docs/features/mtplx.md` promised before this button existed.
+ */
+
+import { IS_WIN32 } from '../lib/bufferedSpawn.js';
+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 { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
+import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
+import { runStreamingCommand } from '../lib/streamingSpawn.js';
+import { installLlamaServer } from './llamaServerManager.js';
+import { controlOllamaServer, installBackend } from './localLlm.js';
+import { isAppInstalled as isLmStudioAppInstalled } from './lmStudioManager.js';
+
+/** Package-manager installs routinely run for minutes (a cask is a download). */
+const INSTALL_TIMEOUT_MS = 20 * 60 * 1000;
+
+/** A short command that only asks a running daemon to do something. */
+const CONTROL_TIMEOUT_MS = 60 * 1000;
+
+/**
+ * How long to wait for a just-started daemon to answer `/v1/models`. MTPLX
+ * loads a multi-gigabyte MLX checkpoint before it binds, so this is sized for a
+ * cold model load rather than for a socket coming up.
+ */
+const START_TIMEOUT_MS = 3 * 60 * 1000;
+const START_POLL_MS = 1_500;
+
+/**
+ * Bound on the `GET /v1/models` reachability probes. Loopback answers (or
+ * refuses) in single-digit milliseconds; the wider bound is for the FINAL
+ * confirmation, where a daemon that just finished loading a model can be slow
+ * to answer its first request and reporting it as down would be wrong.
+ */
+const PROBE_TIMEOUT_MS = 2_000;
+const CONFIRM_TIMEOUT_MS = 5_000;
+
+/** What each `action` is called on the button and in the log. */
+const ACTION_LABELS = {
+ install: (label) => `Install ${label}`,
+ start: (label) => `Start ${label}`,
+ 'install-start': (label) => `Install & start ${label}`,
+};
+
+/**
+ * Spawn a long-lived local daemon and wait until its OpenAI-compatible endpoint
+ * answers. Detached (own process group) so PortOS restarting does not take the
+ * daemon down with it, and `unref`'d so a running daemon never holds the PortOS
+ * process open. Output is streamed only during the startup window — a daemon's
+ * steady-state request log is not install progress.
+ */
+async function startDaemon({ command, args, endpoint, emit, isCancelled = () => false, timeoutMs = START_TIMEOUT_MS }) {
+ const binary = findCommandOnPath(command);
+ if (!binary) return { success: false, error: `\`${command}\` was not found on PortOS's PATH after the install. Restart PortOS so it picks up the new bin directory, then try again.` };
+
+ emit(`Starting: ${command} ${args.join(' ')}`);
+ const child = spawn(binary, args, safeChildProcessOptions({
+ env: safeChildProcessEnv(),
+ shell: false,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ detached: !IS_WIN32,
+ }));
+
+ let exited = null;
+ const onData = (chunk) => {
+ for (const line of chunk.toString().split(/\r?\n/)) {
+ const text = line.trim();
+ if (text) emit(text);
+ }
+ };
+ child.stdout?.on('data', onData);
+ child.stderr?.on('data', onData);
+ /**
+ * Stop forwarding, but keep DRAINING: a daemon whose stdout pipe fills up
+ * blocks on its next write, and `resume()` on a listener-less stream discards
+ * what it reads. Dropping the listener also releases `emit`'s closure over the
+ * SSE response, which would otherwise be retained for the daemon's lifetime.
+ */
+ const stopStreaming = () => {
+ for (const stream of [child.stdout, child.stderr]) {
+ stream?.off('data', onData);
+ stream?.resume();
+ }
+ child.unref();
+ };
+ // 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.
+ child.on('error', (err) => { exited = `failed to start: ${err.message}`; });
+ child.on('exit', (code, signal) => {
+ if (exited === null) exited = `exited early (${signal || `code ${code}`})`;
+ });
+
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ await sleep(START_POLL_MS);
+ // The daemon is deliberately left running when the user closes the modal —
+ // it is the thing they asked for, and killing it would undo the setup. Only
+ // the WAIT stops.
+ if (isCancelled()) {
+ stopStreaming();
+ return { success: false, error: 'Cancelled while waiting for the server to come up.' };
+ }
+ const probe = await probeOpenAiModels(endpoint, { timeoutMs: PROBE_TIMEOUT_MS });
+ if (probe.reachable) {
+ stopStreaming();
+ return { success: true, models: probe.models };
+ }
+ if (exited) {
+ stopStreaming();
+ return { success: false, error: `${command} ${exited}.` };
+ }
+ }
+
+ stopStreaming();
+ return { success: false, error: `${endpoint} still did not answer after ${Math.round(timeoutMs / 1000)}s. The daemon may still be loading a model — reload this page shortly.` };
+}
+
+/**
+ * One row per local runtime PortOS can set up on its own.
+ *
+ * `platforms` is the HARD gate (an empty/absent list means every platform).
+ * `install` and `start` are async steps taking `({ emit, endpoint, isCancelled })`
+ * and returning `{ success, error?, note? }`; `start: null` means PortOS cannot
+ * start this runtime unattended and the checklist keeps its existing link.
+ */
+const SETUP_ROWS = Object.freeze({
+ mtplx: Object.freeze({
+ platforms: ['darwin'],
+ unsupportedReason: 'MTPLX runs only on macOS with Apple Silicon.',
+ async install({ emit }) {
+ // Upstream's recommended path is its Homebrew tap; pip is the documented
+ // fallback for a host without Homebrew. Both install the same `mtplx`
+ // binary, and neither runs the optional privileged fan-control helper.
+ if (await commandExists('brew', ['--version'])) {
+ emit('Installing MTPLX via Homebrew (youssofal/mtplx/mtplx)…');
+ return runStreamingCommand('brew', ['install', 'youssofal/mtplx/mtplx'], emit, { timeoutMs: INSTALL_TIMEOUT_MS });
+ }
+ if (await commandExists('python3', ['--version'])) {
+ emit('Homebrew was not found — installing MTPLX with pip instead…');
+ return runStreamingCommand('python3', ['-m', 'pip', 'install', '--upgrade', 'mtplx'], emit, { timeoutMs: INSTALL_TIMEOUT_MS });
+ }
+ return { success: false, error: 'Neither Homebrew nor python3 is available. Install Homebrew from https://brew.sh, then try again.' };
+ },
+ start({ emit, endpoint, isCancelled }) {
+ // `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 });
+ },
+ }),
+
+ ollama: Object.freeze({
+ async install({ emit }) {
+ // `installBackend` already registers the Homebrew service / runs the
+ // vendor script on Linux and starts the daemon afterwards, so it covers
+ // both steps for this runtime.
+ const result = await installBackend('ollama', (p) => emit(p.message));
+ return result.success ? { success: true, note: result.note } : result;
+ },
+ async start({ emit }) {
+ emit('Starting the Ollama server…');
+ const result = await controlOllamaServer('start');
+ return result?.success ? { success: true } : { success: false, error: result?.error || 'Ollama did not start.' };
+ },
+ }),
+
+ lmstudio: Object.freeze({
+ async install({ emit }) {
+ const result = await installBackend('lmstudio', (p) => emit(p.message));
+ return result.success ? { success: true, note: result.note } : result;
+ },
+ async start({ emit }) {
+ // `lms` is LM Studio's own CLI shim, installed by `lms bootstrap` from the
+ // app. Without it there is no headless way to start the server, and
+ // pretending otherwise would report a success the user cannot see.
+ if (!findCommandOnPath('lms')) {
+ return { success: false, error: 'LM Studio\'s `lms` CLI is not on PortOS\'s PATH. Open LM Studio once and run `lms bootstrap`, or start its local server from the app\'s Developer tab.' };
+ }
+ emit('Starting the LM Studio local server…');
+ return runStreamingCommand('lms', ['server', 'start'], emit, { timeoutMs: CONTROL_TIMEOUT_MS });
+ },
+ }),
+
+ llama: Object.freeze({
+ async install({ emit }) {
+ const result = await installLlamaServer({ onProgress: (p) => emit(p.message) })
+ .catch((err) => ({ success: false, error: err.message }));
+ return result.success
+ ? { success: true, note: 'Choose a GGUF model on Settings → Local LLM to start llama-server — PortOS does not pick weights for you.' }
+ : result;
+ },
+ // llama-server takes a required model path, and the weights are a separate
+ // multi-gigabyte download. Starting it unattended would mean guessing which
+ // checkpoint the user meant, so the Local LLM tab keeps that step.
+ start: null,
+ }),
+});
+
+/** True when this host can run the runtime's setup at all. */
+function platformSupported(row) {
+ return !row.platforms || row.platforms.includes(process.platform);
+}
+
+/**
+ * What (if anything) a "set this up for me" button should offer for one
+ * runtime, given what its readiness checks found. Pure — the client renders it
+ * straight from the readiness payload, so it must not probe anything.
+ *
+ * Returns `null` when there is nothing to offer: an unknown runtime, a platform
+ * that cannot run it, a runtime already installed and running (the remaining
+ * unmet check is the model, which PortOS will not choose), or a runtime PortOS
+ * can install but not start when the install is already done.
+ *
+ * @param {string} kind - `mtplx` | `llama` | `ollama` | `lmstudio`
+ * @param {{installed: boolean, running: boolean}} state
+ */
+export function describeRuntimeSetup(kind, { installed, running }) {
+ const row = SETUP_ROWS[kind];
+ const runtime = LOCAL_RUNTIMES[kind];
+ if (!row || !runtime) return null;
+
+ const needsInstall = !installed;
+ const needsStart = !running && Boolean(row.start);
+ if (!needsInstall && !needsStart) return null;
+
+ if (!platformSupported(row)) {
+ return { runtime: kind, label: runtime.label, action: null, actionLabel: null, blockedReason: row.unsupportedReason };
+ }
+
+ const action = needsInstall && needsStart ? 'install-start' : needsInstall ? 'install' : 'start';
+ return {
+ runtime: kind,
+ label: runtime.label,
+ action,
+ actionLabel: ACTION_LABELS[action](runtime.label),
+ blockedReason: null,
+ };
+}
+
+/**
+ * Install and/or start one local runtime, reporting progress line by line.
+ *
+ * Re-probes the endpoint first: the user may have started the daemon in a
+ * terminal since the page last polled, and re-running an install over a working
+ * setup is the one outcome a "fix it" button must not produce.
+ *
+ * Never throws — the caller is an SSE route whose headers are already flushed,
+ * so a failure has to come back as a value it can turn into a terminal frame.
+ *
+ * @param {string} kind
+ * @param {{endpoint: string, emit: (line: string) => void, isCancelled?: () => boolean}} ctx
+ * `isCancelled` is checked between steps so a closed modal does not go on to
+ * start a daemon nobody is watching for.
+ * @returns {Promise<{success: boolean, error?: string, message?: string}>}
+ */
+export async function runLocalRuntimeSetup(kind, { endpoint, emit = () => {}, isCancelled = () => false }) {
+ 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)}\`.` };
+ if (!platformSupported(row)) return { success: false, error: row.unsupportedReason };
+
+ const target = endpoint || runtime.defaultBaseUrl;
+ const probe = await probeOpenAiModels(target, { timeoutMs: PROBE_TIMEOUT_MS });
+ if (probe.reachable) {
+ return { success: true, message: `${runtime.label} is already running at ${target} — nothing to do.` };
+ }
+
+ // 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());
+
+ if (!installed) {
+ const result = await row.install({ emit, endpoint: target, isCancelled });
+ if (!result.success) return { success: false, error: `${runtime.label} install failed: ${result.error}` };
+ emit(`${runtime.label} is installed.`);
+ if (result.note) emit(result.note);
+ } else {
+ emit(`${runtime.label} is already installed — starting it.`);
+ }
+
+ if (!row.start) {
+ return { success: true, message: `${runtime.label} is installed. Pick a model on Settings → Local LLM to start it.` };
+ }
+ if (isCancelled()) return { success: false, error: 'Cancelled after the install — nothing was started.' };
+
+ // The install step may have started it (Ollama's Homebrew service does), so
+ // re-probe rather than launching a second copy onto the same port.
+ const afterInstall = await probeOpenAiModels(target, { timeoutMs: PROBE_TIMEOUT_MS });
+ if (!afterInstall.reachable) {
+ const started = await row.start({ emit, endpoint: target, isCancelled });
+ if (!started.success) return { success: false, error: `${runtime.label} did not start: ${started.error}` };
+ }
+
+ const final = await probeOpenAiModels(target, { timeoutMs: CONFIRM_TIMEOUT_MS });
+ if (!final.reachable) {
+ return { success: false, error: `${runtime.label} was set up, but ${target} still does not answer${final.error ? ` (${final.error})` : ''}.` };
+ }
+ const served = Array.isArray(final.models) && final.models.length > 0
+ ? ` It is serving ${final.models.slice(0, 3).join(', ')}${final.models.length > 3 ? ` +${final.models.length - 3} more` : ''}.`
+ : '';
+ return { success: true, message: `${runtime.label} is running at ${target}.${served}` };
+}
+
+/** The runtime kinds this module can set up — used by route validation and tests. */
+export const SETUP_RUNTIME_KINDS = Object.freeze(Object.keys(SETUP_ROWS));
diff --git a/server/services/localRuntimeSetup.test.js b/server/services/localRuntimeSetup.test.js
new file mode 100644
index 0000000000..8602ff11ee
--- /dev/null
+++ b/server/services/localRuntimeSetup.test.js
@@ -0,0 +1,259 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { pinPlatform } from '../lib/testHelper.js';
+
+const probe = vi.hoisted(() => ({ probeOpenAiModels: vi.fn() }));
+vi.mock('../lib/openAiModelsProbe.js', () => probe);
+
+const pathLookup = vi.hoisted(() => ({
+ findCommandOnPath: vi.fn(() => null),
+ safeChildProcessEnv: (extra = {}) => ({ ...extra }),
+ safeChildProcessOptions: (opts = {}) => opts,
+}));
+vi.mock('../lib/processEnv.js', () => pathLookup);
+
+const streaming = vi.hoisted(() => ({ runStreamingCommand: vi.fn(async () => ({ success: true })) }));
+vi.mock('../lib/streamingSpawn.js', () => streaming);
+
+const commands = vi.hoisted(() => ({ commandExists: vi.fn(async () => true) }));
+vi.mock('../lib/commandExists.js', () => commands);
+
+// The three managers this module delegates to for the runtimes PortOS already
+// knew how to install. Mocked so the suite never touches Homebrew or a daemon.
+const llama = vi.hoisted(() => ({ installLlamaServer: vi.fn(async () => ({ success: true })) }));
+vi.mock('./llamaServerManager.js', () => llama);
+const localLlm = vi.hoisted(() => ({
+ installBackend: vi.fn(async () => ({ success: true })),
+ controlOllamaServer: vi.fn(async () => ({ success: true })),
+}));
+vi.mock('./localLlm.js', () => localLlm);
+vi.mock('./lmStudioManager.js', () => ({ isAppInstalled: () => false }));
+const child = vi.hoisted(() => ({ spawn: vi.fn() }));
+vi.mock('../lib/childProcess.js', () => child);
+vi.mock('../lib/fileUtils.js', () => ({ sleep: async () => {} }));
+
+import { describeRuntimeSetup, runLocalRuntimeSetup, 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. */
+const fakeChild = () => {
+ const stream = () => ({ on: vi.fn(), off: vi.fn(), resume: vi.fn() });
+ const handlers = {};
+ return {
+ stdout: stream(),
+ stderr: stream(),
+ on: vi.fn((event, fn) => { handlers[event] = fn; }),
+ unref: vi.fn(),
+ emitEvent: (event, ...args) => handlers[event]?.(...args),
+ };
+};
+const reachable = (models = ['mtplx']) => ({ reachable: true, models, error: null });
+
+afterEach(() => {
+ vi.clearAllMocks();
+ pathLookup.findCommandOnPath.mockReturnValue(null);
+ commands.commandExists.mockResolvedValue(true);
+ streaming.runStreamingCommand.mockResolvedValue({ success: true });
+});
+
+describe('describeRuntimeSetup', () => {
+ it('covers every runtime the readiness checklist can report', () => {
+ expect([...SETUP_RUNTIME_KINDS].sort()).toEqual(['llama', 'lmstudio', 'mtplx', 'ollama']);
+ });
+
+ it('offers install AND start when nothing is there yet', () => {
+ const restore = pinPlatform('darwin');
+ expect(describeRuntimeSetup('mtplx', { installed: false, running: false })).toEqual({
+ runtime: 'mtplx',
+ label: 'MTPLX',
+ action: 'install-start',
+ actionLabel: 'Install & start MTPLX',
+ blockedReason: null,
+ });
+ restore();
+ });
+
+ it('offers only a start once the runtime is installed', () => {
+ const restore = pinPlatform('darwin');
+ expect(describeRuntimeSetup('mtplx', { installed: true, running: false })).toMatchObject({
+ action: 'start',
+ actionLabel: 'Start MTPLX',
+ });
+ restore();
+ });
+
+ it('offers nothing once the daemon is installed and up — the model is the user\'s choice', () => {
+ const restore = pinPlatform('darwin');
+ // A running daemon serving the wrong alias is the remaining unmet check,
+ // and PortOS will not pick (or download) a checkpoint for the user.
+ expect(describeRuntimeSetup('mtplx', { installed: true, running: true })).toBeNull();
+ restore();
+ });
+
+ it('names the reason instead of a button on an unsupported host', () => {
+ const restore = pinPlatform('linux');
+ expect(describeRuntimeSetup('mtplx', { installed: false, running: false })).toMatchObject({
+ action: null,
+ blockedReason: expect.stringMatching(/only on macOS/),
+ });
+ restore();
+ });
+
+ it('stops at the install for llama.cpp, which cannot start without weights', () => {
+ // `start: null` — llama-server takes a required model path, so an installed
+ // but stopped llama.cpp gets no button at all.
+ expect(describeRuntimeSetup('llama', { installed: false, running: false })).toMatchObject({ action: 'install' });
+ expect(describeRuntimeSetup('llama', { installed: true, running: false })).toBeNull();
+ });
+
+ it('returns null for a runtime it has no row for', () => {
+ expect(describeRuntimeSetup('orcarouter', { installed: false, running: false })).toBeNull();
+ expect(describeRuntimeSetup(undefined, { installed: false, running: false })).toBeNull();
+ });
+});
+
+describe('runLocalRuntimeSetup', () => {
+ it('does nothing when the endpoint already answers', async () => {
+ probe.probeOpenAiModels.mockResolvedValueOnce(reachable());
+
+ const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });
+
+ expect(result).toMatchObject({ success: true, message: expect.stringMatching(/already running/) });
+ expect(streaming.runStreamingCommand).not.toHaveBeenCalled();
+ });
+
+ it('installs MTPLX from its Homebrew tap — never the privileged fan-control helper', async () => {
+ probe.probeOpenAiModels.mockResolvedValue(unreachable);
+ const restore = pinPlatform('darwin');
+
+ await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });
+ restore();
+
+ const [cmd, args] = streaming.runStreamingCommand.mock.calls[0];
+ expect(cmd).toBe('brew');
+ expect(args).toEqual(['install', 'youssofal/mtplx/mtplx']);
+ expect(streaming.runStreamingCommand.mock.calls.flatMap(([, a]) => a)).not.toContain('max');
+ });
+
+ it('falls back to pip when Homebrew is absent', async () => {
+ probe.probeOpenAiModels.mockResolvedValue(unreachable);
+ commands.commandExists.mockImplementation(async (cmd) => cmd !== 'brew');
+ const restore = pinPlatform('darwin');
+
+ await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });
+ restore();
+
+ expect(streaming.runStreamingCommand.mock.calls[0][0]).toBe('python3');
+ });
+
+ it('stops at the install failure rather than starting a daemon that is not there', async () => {
+ probe.probeOpenAiModels.mockResolvedValue(unreachable);
+ streaming.runStreamingCommand.mockResolvedValue({ success: false, error: 'exit 1: no such formula' });
+ const restore = pinPlatform('darwin');
+
+ const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });
+ restore();
+
+ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/no such formula/) });
+ });
+
+ it('refuses a host that cannot run the runtime at all', async () => {
+ const restore = pinPlatform('win32');
+ const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8000/v1' });
+ restore();
+ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/only on macOS/) });
+ });
+
+ it('skips the start step when the install already brought the daemon up', async () => {
+ // Ollama's Homebrew service starts on install. Launching a second copy onto
+ // the same port is the failure this re-probe exists to prevent.
+ probe.probeOpenAiModels
+ .mockResolvedValueOnce(unreachable) // pre-flight
+ .mockResolvedValueOnce(reachable([])) // after install
+ .mockResolvedValueOnce(reachable(['qwen3']));
+
+ const result = await runLocalRuntimeSetup('ollama', { endpoint: 'http://localhost:11434/v1' });
+
+ expect(localLlm.installBackend).toHaveBeenCalledWith('ollama', expect.any(Function));
+ expect(localLlm.controlOllamaServer).not.toHaveBeenCalled();
+ expect(result).toMatchObject({ success: true, message: expect.stringContaining('qwen3') });
+ });
+
+ it('starts an installed-but-stopped Ollama', async () => {
+ pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/ollama');
+ probe.probeOpenAiModels
+ .mockResolvedValueOnce(unreachable)
+ .mockResolvedValueOnce(unreachable)
+ .mockResolvedValueOnce(reachable(['qwen3']));
+
+ const result = await runLocalRuntimeSetup('ollama', { endpoint: 'http://localhost:11434/v1' });
+
+ expect(localLlm.installBackend).not.toHaveBeenCalled();
+ expect(localLlm.controlOllamaServer).toHaveBeenCalledWith('start');
+ expect(result.success).toBe(true);
+ });
+
+ it('reports the install as done for llama.cpp and hands the model choice back', async () => {
+ probe.probeOpenAiModels.mockResolvedValue(unreachable);
+
+ const result = await runLocalRuntimeSetup('llama', { endpoint: 'http://127.0.0.1:8080/v1' });
+
+ expect(llama.installLlamaServer).toHaveBeenCalled();
+ expect(result).toMatchObject({ success: true, message: expect.stringMatching(/Local LLM/) });
+ });
+
+ it('stops after the install when the modal was closed', async () => {
+ probe.probeOpenAiModels.mockResolvedValue(unreachable);
+ const restore = pinPlatform('darwin');
+
+ const result = await runLocalRuntimeSetup('mtplx', {
+ endpoint: 'http://127.0.0.1:8000/v1',
+ isCancelled: () => true,
+ });
+ restore();
+
+ expect(result).toMatchObject({ success: false, error: expect.stringMatching(/Cancelled/) });
+ });
+
+ it('starts `mtplx serve` on the port the PROVIDER points at, not a hard-coded 8000', async () => {
+ const daemon = fakeChild();
+ child.spawn.mockReturnValue(daemon);
+ // Not installed at the pre-flight check; on PATH once the install lands.
+ pathLookup.findCommandOnPath.mockReturnValueOnce(null).mockReturnValue('/opt/homebrew/bin/mtplx');
+ probe.probeOpenAiModels
+ .mockResolvedValueOnce(unreachable) // pre-flight
+ .mockResolvedValueOnce(unreachable) // after install
+ .mockResolvedValueOnce(reachable(['mtplx'])) // first poll after spawn
+ .mockResolvedValueOnce(reachable(['mtplx'])); // final confirmation
+ const restore = pinPlatform('darwin');
+
+ const result = await runLocalRuntimeSetup('mtplx', { endpoint: 'http://127.0.0.1:8010/v1' });
+ restore();
+
+ const [binary, args] = child.spawn.mock.calls[0];
+ expect(binary).toBe('/opt/homebrew/bin/mtplx');
+ expect(args).toEqual(['serve', '--port', '8010']);
+ expect(daemon.unref).toHaveBeenCalled();
+ expect(result).toMatchObject({ success: true, message: expect.stringContaining('http://127.0.0.1:8010/v1') });
+ });
+
+ it('reports a daemon that died on startup instead of waiting out the timeout', async () => {
+ const daemon = fakeChild();
+ child.spawn.mockReturnValue(daemon);
+ pathLookup.findCommandOnPath.mockReturnValue('/opt/homebrew/bin/mtplx');
+ probe.probeOpenAiModels.mockImplementation(async () => {
+ 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).toMatchObject({ success: false, error: expect.stringMatching(/exited early \(code 1\)/) });
+ });
+
+ 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/) });
+ });
+});
diff --git a/server/services/providerReadiness.js b/server/services/providerReadiness.js
index 3a1cc5f8fe..dc3d00fb63 100644
--- a/server/services/providerReadiness.js
+++ b/server/services/providerReadiness.js
@@ -37,6 +37,7 @@ import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';
import { isConfiguredDefaultModel } from '../lib/providerModels.js';
import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
import { findCommandOnPath } from '../lib/processEnv.js';
+import { describeRuntimeSetup } from './localRuntimeSetup.js';
import { isAppInstalled as isLmStudioAppInstalled } from './lmStudioManager.js';
/**
@@ -124,21 +125,39 @@ function servedModelId(provider, kind) {
return trimmed.startsWith(`${kind}/`) ? trimmed.slice(kind.length + 1) : trimmed;
}
+/**
+ * The fix hint for a check the one-click setup button already covers.
+ *
+ * `setup.actionLabel` names a button rendered right below the checklist, so the
+ * hint points AT it rather than repeating a terminal recipe — and a runtime this
+ * host cannot set up at all says why instead of sending the user to a doc that
+ * would not help them either.
+ *
+ * `null` means "no button covers this", and the caller falls back to its own
+ * prose. `covers` is the action the check needs: an install-only button does
+ * nothing for a `server` check.
+ */
+function setupHint(setup, covers) {
+ if (!setup) return null;
+ if (setup.blockedReason) return setup.blockedReason;
+ return setup.action?.includes(covers) ? `Use “${setup.actionLabel}” below — PortOS does this for you.` : null;
+}
+
/** The `runtime` check — is the daemon's software here at all? */
-function runtimeCheck(runtime, { onPath, appInstalled, installed, reachable }) {
+function runtimeCheck(runtime, { onPath, appInstalled, installed, reachable, setup }) {
const detail = onPath ? `\`${runtime.command}\` is on PortOS's PATH.`
: appInstalled ? `${runtime.label} is installed as an app.`
: reachable ? `Something is already serving ${runtime.endpoint}.`
- : runtime.command ? `\`${runtime.command}\` was not found on PortOS's PATH.`
- : `PortOS does not install ${runtime.label} — start it yourself.`;
+ : `\`${runtime.command}\` was not found on PortOS's PATH.`;
const fixHint = installed ? null
- : runtime.manageUrl ? `Install ${runtime.label} from Settings → Local LLM.`
- : `Follow the ${runtime.label} setup docs, then reload this page.`;
+ : setupHint(setup, 'install')
+ || (runtime.manageUrl ? `Install ${runtime.label} from Settings → Local LLM.`
+ : `Follow the ${runtime.label} setup docs, then reload this page.`);
return { id: 'runtime', label: `${runtime.label} installed`, ok: installed, detail, fixHint };
}
/** The `server` check — is it running where THIS provider points? */
-function serverCheck(runtime, { installed, result }) {
+function serverCheck(runtime, { installed, result, setup }) {
if (result.reachable) {
return {
id: 'server',
@@ -149,14 +168,15 @@ function serverCheck(runtime, { installed, result }) {
};
}
const start = `Start ${runtime.label}${runtime.manageUrl ? ' from Settings → Local LLM' : ''}.`;
+ const fallback = installed
+ ? `${start} ${runtime.modelsHint}`
+ : `Install ${runtime.label} first, then start it. ${runtime.modelsHint}`;
return {
id: 'server',
label: `${runtime.label} server responding`,
ok: false,
detail: `Nothing answered at ${runtime.endpoint}${result.error ? ` (${result.error})` : ''}.`,
- fixHint: installed
- ? `${start} ${runtime.modelsHint}`
- : `Install ${runtime.label} first, then start it. ${runtime.modelsHint}`,
+ fixHint: setupHint(setup, 'start') || fallback,
};
}
@@ -221,9 +241,13 @@ export async function getProviderReadiness(provider, deps = {}) {
const appInstalled = runtime.kind === 'lmstudio' && (deps.isAppInstalled || isLmStudioAppInstalled)();
const installed = onPath || appInstalled || result.reachable;
+ // Resolved BEFORE the checks so each unmet one can point at the button that
+ // fixes it rather than at a setup doc.
+ const setup = describeRuntimeSetup(runtime.kind, { installed, running: result.reachable });
+
const checks = [
- runtimeCheck(runtime, { onPath, appInstalled, installed, reachable: result.reachable }),
- serverCheck(runtime, { installed, result }),
+ runtimeCheck(runtime, { onPath, appInstalled, installed, reachable: result.reachable, setup }),
+ serverCheck(runtime, { installed, result, setup }),
];
const wanted = servedModelId(provider, runtime.kind);
// `probeEndpoint` returns `models: null` on every unreachable path, so this
@@ -240,6 +264,11 @@ export async function getProviderReadiness(provider, deps = {}) {
// a pass, so the card never claims a provider is good to go on unknowns.
ready: checks.every((check) => check.ok === true),
checks,
+ // What a one-click "set this up for me" button can do about the unmet
+ // checks, or `null` when nothing here is auto-fixable (see
+ // `localRuntimeSetup.js`). Carried on the readiness payload so the card
+ // offers the ACTION next to the failing check instead of a setup-doc link.
+ setup,
};
}
diff --git a/server/services/providerReadiness.test.js b/server/services/providerReadiness.test.js
index 74d2a67f80..7bf2fa1e37 100644
--- a/server/services/providerReadiness.test.js
+++ b/server/services/providerReadiness.test.js
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeEach } from 'vitest';
+import { pinPlatform } from '../lib/testHelper.js';
import { getProviderReadiness, getProviderReadinessMap, resetProviderReadinessCache } from './providerReadiness.js';
const llamaProvider = (overrides = {}) => ({
@@ -180,14 +181,34 @@ describe('getProviderReadiness', () => {
expect(checkById(readiness, 'server').fixHint).toMatch(/Start LM Studio/);
});
- it('offers docs rather than an install for a runtime PortOS does not manage', async () => {
+ it('offers a one-click install+start for MTPLX instead of a setup-doc dead end', async () => {
+ // The whole point of the setup button: MTPLX has no Local LLM tab entry,
+ // so before it existed the only answer here was "go read the vendor docs".
+ const restore = pinPlatform('darwin');
const readiness = await getProviderReadiness(
{ id: 'opencode-mtplx', command: 'opencode', mtplxBacked: true, defaultModel: 'mtplx' },
{ findCommand: () => null, probe: unreachable() },
);
+ restore();
expect(readiness.manageUrl).toBeNull();
+ // The docs link stays as a secondary affordance for the model choice.
expect(readiness.docsUrl).toBeTruthy();
- expect(checkById(readiness, 'runtime').fixHint).toMatch(/setup docs/);
+ expect(readiness.setup).toMatchObject({ runtime: 'mtplx', action: 'install-start', blockedReason: null });
+ expect(checkById(readiness, 'runtime').fixHint).toMatch(/Install & start MTPLX/);
+ expect(checkById(readiness, 'server').fixHint).toMatch(/Install & start MTPLX/);
+ });
+
+ it('falls back to the setup docs on a host that cannot run the runtime', async () => {
+ const restore = pinPlatform('linux');
+ const readiness = await getProviderReadiness(
+ { id: 'opencode-mtplx', command: 'opencode', mtplxBacked: true, defaultModel: 'mtplx' },
+ { findCommand: () => null, probe: unreachable() },
+ );
+ restore();
+ // No button — and the checklist says WHY rather than sending the user to a
+ // doc that would not help them either.
+ expect(readiness.setup.action).toBeNull();
+ expect(checkById(readiness, 'runtime').fixHint).toMatch(/only on macOS/);
});
});