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

report local-daemon requirements on the provider card instead of failing at run time

[._.]/ Adam Eivy46090c1e6d09
diff --git a/client/src/components/providers/ProviderReadiness.jsx b/client/src/components/providers/ProviderReadiness.jsx
new file mode 100644
index 0000000000..87370b691a
--- /dev/null
+++ b/client/src/components/providers/ProviderReadiness.jsx
@@ -0,0 +1,102 @@
+/**
+ * Local-daemon requirements checklist for one provider card.
+ *
+ * `ProviderRuntimeStatus` (its sibling) answers "is the CLI binary installed?".
+ * This answers the other half for a provider backed by a local daemon: is
+ * llama.cpp / Ollama / LM Studio / MTPLX installed, is it actually running at
+ * the endpoint this provider points at, and is it serving the model this
+ * provider asks for. Without it, a missing daemon or an un-downloaded model only
+ * surfaced as `Cannot connect to API: Unable to connect` inside a dead agent
+ * 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.
+ */
+
+import { Link } from 'react-router';
+import { CheckCircle2, HelpCircle, Wrench, XCircle } from 'lucide-react';
+import Pill from '../ui/Pill';
+
+const ICONS = {
+ true: { Icon: CheckCircle2, cls: 'text-port-success' },
+ false: { Icon: XCircle, cls: 'text-port-error' },
+ // `ok: null` — a check the server could not evaluate yet (the model list
+ // cannot be read while the server is down). Shown as unknown rather than as a
+ // failure, so the user chases the check that IS actionable.
+ null: { Icon: HelpCircle, cls: 'text-gray-500' },
+};
+
+/**
+ * Render `text` with `backtick`-quoted spans as inline code. The server writes
+ * check details in that shape so model ids and binary names read as literals
+ * rather than as prose.
+ */
+function CodeText({ text }) {
+ if (typeof text !== 'string' || text === '') return null;
+ return (
+ <>
+ {text.split(/`([^`]+)`/).map((part, i) => (
+ i % 2 === 1
+ ? <code key={i} className="text-gray-300 font-mono break-all">{part}</code>
+ : <span key={i}>{part}</span>
+ ))}
+ </>
+ );
+}
+
+export default function ProviderReadiness({ readiness, className = '' }) {
+ if (!readiness || !Array.isArray(readiness.checks) || readiness.checks.length === 0) return null;
+ const { label, endpoint, ready, checks, manageUrl, docsUrl } = readiness;
+
+ if (ready) {
+ return (
+ <div className={`flex flex-wrap items-center gap-2 ${className}`}>
+ <Pill tone="success" size="xs" icon={CheckCircle2} title={`${label} is running at ${endpoint}.`}>
+ {label} ready
+ </Pill>
+ </div>
+ );
+ }
+
+ const blocked = checks.filter((check) => check.ok !== true).length;
+
+ return (
+ <div className={`text-xs rounded border border-port-warning/40 bg-port-warning/10 px-3 py-2 space-y-1.5 ${className}`}>
+ <p className="text-port-warning font-semibold flex items-center gap-1.5">
+ <Wrench size={12} />
+ {label} setup incomplete — {blocked} requirement{blocked === 1 ? '' : 's'} unmet
+ </p>
+ <ul className="space-y-1">
+ {checks.map((check) => {
+ const { Icon, cls } = ICONS[String(check.ok)] || ICONS.null;
+ return (
+ <li key={check.id} className="flex items-start gap-1.5">
+ <Icon size={12} className={`${cls} mt-0.5 shrink-0`} />
+ <span className="text-gray-300 break-words">
+ <CodeText text={check.label} />
+ {check.detail && <span className="text-gray-500"> — <CodeText text={check.detail} /></span>}
+ {check.fixHint && (
+ <span className="block text-port-warning/90"><CodeText text={check.fixHint} /></span>
+ )}
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ <div className="flex flex-wrap items-center gap-3 pt-0.5">
+ {manageUrl && (
+ <Link to={manageUrl} className="text-port-accent hover:text-port-accent/80 underline underline-offset-2">
+ Open Local LLM settings
+ </Link>
+ )}
+ {docsUrl && (
+ <a href={docsUrl} target="_blank" rel="noreferrer" className="text-port-accent hover:text-port-accent/80 underline underline-offset-2">
+ {label} setup docs
+ </a>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/providers/ProviderReadiness.test.jsx b/client/src/components/providers/ProviderReadiness.test.jsx
new file mode 100644
index 0000000000..47ee83c3c9
--- /dev/null
+++ b/client/src/components/providers/ProviderReadiness.test.jsx
@@ -0,0 +1,77 @@
+import { describe, it, expect } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+import ProviderReadiness from './ProviderReadiness';
+
+const renderWithRouter = (ui) => render(<MemoryRouter>{ui}</MemoryRouter>);
+
+const readiness = (overrides = {}) => ({
+ kind: 'llama',
+ label: 'llama.cpp',
+ endpoint: 'http://127.0.0.1:8080/v1',
+ manageUrl: '/settings/local-llm',
+ docsUrl: 'https://example.com/llama-docs',
+ ready: false,
+ 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.' },
+ { id: 'model', label: 'Model `dflash` available', ok: null, detail: 'Cannot be checked until the server responds.', fixHint: null },
+ ],
+ ...overrides,
+});
+
+describe('ProviderReadiness', () => {
+ it('renders nothing without a readiness report', () => {
+ const { container } = renderWithRouter(<ProviderReadiness readiness={null} />);
+ expect(container.textContent).toBe('');
+ });
+
+ it('renders nothing when the report carries no checks', () => {
+ const { container } = renderWithRouter(<ProviderReadiness readiness={readiness({ checks: [] })} />);
+ expect(container.textContent).toBe('');
+ });
+
+ it('collapses to a single pill once every requirement is met', () => {
+ const met = readiness({
+ ready: true,
+ checks: readiness().checks.map((check) => ({ ...check, ok: true, fixHint: null })),
+ });
+ renderWithRouter(<ProviderReadiness readiness={met} />);
+ expect(screen.getByText('llama.cpp ready')).toBeTruthy();
+ expect(screen.queryByText(/setup incomplete/)).toBeNull();
+ });
+
+ it('counts only the unmet requirements, and shows each fix', () => {
+ renderWithRouter(<ProviderReadiness readiness={readiness()} />);
+ // The `server` failure plus the `model` check that could not be evaluated —
+ // an unknown is not a pass.
+ expect(screen.getByText(/2 requirements unmet/)).toBeTruthy();
+ expect(screen.getByText(/Start llama\.cpp/)).toBeTruthy();
+ });
+
+ it('pluralizes a single unmet requirement', () => {
+ const one = readiness({
+ checks: [readiness().checks[0], { ...readiness().checks[1], ok: false }],
+ });
+ renderWithRouter(<ProviderReadiness readiness={one} />);
+ expect(screen.getByText(/1 requirement unmet/)).toBeTruthy();
+ });
+
+ it('links to the Local LLM tab and the vendor docs when the setup is incomplete', () => {
+ renderWithRouter(<ProviderReadiness readiness={readiness()} />);
+ expect(screen.getByText('Open Local LLM settings').closest('a').getAttribute('href')).toBe('/settings/local-llm');
+ expect(screen.getByText('llama.cpp setup docs').closest('a').getAttribute('href')).toBe('https://example.com/llama-docs');
+ });
+
+ it('omits the manage link for a runtime PortOS does not install', () => {
+ renderWithRouter(<ProviderReadiness readiness={readiness({ label: 'MTPLX', manageUrl: null })} />);
+ expect(screen.queryByText('Open Local LLM settings')).toBeNull();
+ expect(screen.getByText('MTPLX setup docs')).toBeTruthy();
+ });
+
+ it('renders backtick-quoted spans as code rather than literal backticks', () => {
+ const { container } = renderWithRouter(<ProviderReadiness readiness={readiness()} />);
+ expect(container.textContent).not.toContain('`');
+ expect([...container.querySelectorAll('code')].map((el) => el.textContent)).toContain('dflash');
+ });
+});
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 44fbd8b8ad..44868d0961 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -23,6 +23,7 @@ import Modal from '../components/ui/Modal';
import { FormField } from '../components/ui/FormField';
import RuntimeInstallModal from '../components/install/RuntimeInstallModal';
import ProviderRuntimeStatus from '../components/providers/ProviderRuntimeStatus';
+import ProviderReadiness from '../components/providers/ProviderReadiness';
// The two local apps an API provider can front. Their installer lives on the
// Local LLM settings tab (it starts the service too), so the provider card
@@ -114,6 +115,11 @@ export default function AIProviders() {
// an upgrade) — distinct from a confirmed missing CLI — and simply renders no
// install widgets.
const [runtimes, setRuntimes] = useState({});
+ // Local-daemon requirements per provider (llama.cpp / Ollama / LM Studio /
+ // MTPLX), keyed by provider id. Providers with no local dependency are absent
+ // from the map, and an empty map means the endpoint was not reached — both
+ // render no checklist.
+ const [readiness, setReadiness] = useState({});
// The runtime whose install modal is open (`null` = closed).
const [installingRuntime, setInstallingRuntime] = useState(null);
// Ollama / LM Studio install state (and the model lists the editor's pickers
@@ -194,10 +200,24 @@ export default function AIProviders() {
if (statusData?.providers) setStatuses(statusData.providers);
}, []);
+ // Local-daemon readiness (is llama-server / Ollama actually up and serving the
+ // model this provider names?). Off the critical path like the runtime probes,
+ // and re-polled on the same cadence as the status map so starting a daemon
+ // from the Local LLM tab clears the card's checklist on its own.
+ const loadReadiness = useCallback(async () => {
+ const data = await api.getProviderReadiness({ silent: true }).catch(() => null);
+ setReadiness(data?.readiness && typeof data.readiness === 'object' ? data.readiness : {});
+ }, []);
+
+ useEffect(() => { loadReadiness(); }, [loadReadiness]);
+
useEffect(() => {
- const id = setInterval(refreshStatuses, 20000);
+ const id = setInterval(() => {
+ refreshStatuses();
+ loadReadiness();
+ }, 20000);
return () => clearInterval(id);
- }, [refreshStatuses]);
+ }, [refreshStatuses, loadReadiness]);
// Clear a provider's bench (runtime unavailability) so the next call retries it.
// Note: if the underlying cause persists (e.g. an invalid model id), the very
@@ -659,6 +679,8 @@ export default function AIProviders() {
onInstall={setInstallingRuntime}
/>
+ <ProviderReadiness className="mt-2" readiness={readiness[provider.id]} />
+
{provider.enabled && statuses[provider.id]?.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">
<p className="break-words">
diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsx
index 33687a6c1b..1c5869baf7 100644
--- a/client/src/pages/AIProviders.test.jsx
+++ b/client/src/pages/AIProviders.test.jsx
@@ -7,6 +7,7 @@ const api = vi.hoisted(() => ({
getApps: vi.fn(),
getProviderStatuses: vi.fn(),
getProviderRuntimes: vi.fn(),
+ getProviderReadiness: vi.fn(),
getSampleProviders: vi.fn(),
createProvider: vi.fn(),
updateProvider: vi.fn(),
@@ -69,6 +70,7 @@ describe('AIProviders page load error handling', () => {
api.getApps.mockResolvedValue([]);
api.getProviderStatuses.mockResolvedValue({ providers: {} });
api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });
localModels.value = { ctxById: {}, installed: { ollama: null, lmstudio: null } };
});
@@ -244,12 +246,61 @@ describe('AIProviders page load error handling', () => {
});
});
+describe('local-daemon readiness on the provider card', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.getApps.mockResolvedValue([]);
+ api.getProviderStatuses.mockResolvedValue({ providers: {} });
+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
+ localModels.value = { ctxById: {}, installed: { ollama: null, lmstudio: null } };
+ api.getProviders.mockResolvedValue({
+ providers: [{ id: 'opencode-llama-tui', name: 'OpenCode llama TUI', type: 'tui', command: 'opencode', args: [], enabled: true, endpoint: 'http://127.0.0.1:8080/v1', llamaBacked: true }],
+ activeProvider: null,
+ });
+ });
+
+ it('surfaces the unmet requirements when the local daemon is not running', async () => {
+ api.getProviderReadiness.mockResolvedValue({
+ readiness: {
+ 'opencode-llama-tui': {
+ kind: 'llama',
+ label: 'llama.cpp',
+ endpoint: 'http://127.0.0.1:8080/v1',
+ manageUrl: '/settings/local-llm',
+ docsUrl: 'https://example.com/docs',
+ ready: false,
+ checks: [
+ { id: 'runtime', label: 'llama.cpp installed', ok: false, detail: 'not found', fixHint: 'Install llama.cpp from Settings → Local LLM.' },
+ { id: 'server', label: 'llama.cpp server responding', ok: false, detail: 'nothing answered', fixHint: 'Install llama.cpp first, then start it.' },
+ ],
+ },
+ },
+ });
+
+ renderPage();
+
+ expect(await screen.findByText(/llama\.cpp setup incomplete/)).toBeInTheDocument();
+ expect(screen.getByText(/Install llama\.cpp from Settings/)).toBeInTheDocument();
+ });
+
+ it('renders no checklist for a provider the server reports nothing about', async () => {
+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });
+
+ renderPage();
+
+ expect(await screen.findByText('OpenCode llama TUI')).toBeInTheDocument();
+ expect(screen.queryByText(/setup incomplete/)).not.toBeInTheDocument();
+ expect(screen.queryByText(/ready$/)).not.toBeInTheDocument();
+ });
+});
+
describe('handleAddSample error handling', () => {
beforeEach(() => {
vi.clearAllMocks();
api.getApps.mockResolvedValue([]);
api.getProviderStatuses.mockResolvedValue({ providers: {} });
api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });
api.getProviders.mockResolvedValue({
providers: [],
activeProvider: null,
@@ -286,6 +337,7 @@ describe('handleAddAllSamples partial failure handling', () => {
api.getApps.mockResolvedValue([]);
api.getProviderStatuses.mockResolvedValue({ providers: {} });
api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });
api.getProviders.mockResolvedValue({
providers: [],
activeProvider: null,
@@ -331,6 +383,7 @@ describe('CoS Agent Runner allowlist warning', () => {
api.getApps.mockResolvedValue([]);
api.getProviderStatuses.mockResolvedValue({ providers: {} });
api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });
});
it('badges a provider whose command is off the published allowlist', async () => {
@@ -430,6 +483,7 @@ describe('Local num_ctx field', () => {
api.getApps.mockResolvedValue([]);
api.getProviderStatuses.mockResolvedValue({ providers: {} });
api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });
});
const openEditorFor = async (provider) => {
@@ -484,6 +538,7 @@ describe('OpenCode OrcaRouter key hint', () => {
api.getApps.mockResolvedValue([]);
api.getProviderStatuses.mockResolvedValue({ providers: {} });
api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });
});
// The OpenCode wrapper carries no key of its own — the card must point the
diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.js
index 01b82d5050..0852067b62 100644
--- a/client/src/services/apiProviders.js
+++ b/client/src/services/apiProviders.js
@@ -27,6 +27,11 @@ export const refreshProviderModels = (id, options) => request(`/providers/${id}/
// after an explicit Providers-page click; the status payload carries booleans
// and labels only — never local executable paths.
export const getProviderRuntimes = (options) => request('/providers/runtimes', options);
+// Per-provider requirements checklist for providers backed by a LOCAL daemon
+// (llama.cpp, Ollama, LM Studio, MTPLX): is it installed, is it running, is it
+// serving the model this provider asks for. Keyed by provider id; providers
+// with no local dependency are absent from the map.
+export const getProviderReadiness = (options) => request('/providers/readiness', options);
// Provider status (usage limits, availability)
export const getProviderStatuses = () => request('/providers/status');
diff --git a/docs/API.md b/docs/API.md
index 5494b33fd0..b4fc9b7f33 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -67,6 +67,7 @@ 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. 5s endpoint-probe cache. |
| 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/dflash2.md b/docs/features/dflash2.md
index 51baab8820..9becf2eebb 100644
--- a/docs/features/dflash2.md
+++ b/docs/features/dflash2.md
@@ -71,6 +71,29 @@ llama-server \
3. Click **Refresh Models** to pull the live aliases from `llama-server`, or use the default `dflash` model.
4. Select **OpenCode llama TUI** in the CoS task creator or terminal runner to execute coding and agent tasks with speculative acceleration.
+### Checking the requirements from the Providers page
+
+Every provider backed by a local daemon carries a **requirements checklist** on
+its card in **AI Providers** — fed by `GET /api/providers/readiness`, re-polled
+every 20s:
+
+1. **llama.cpp installed** — `llama-server` is on PortOS's PATH (or something is
+ already answering at the endpoint, which proves it another way).
+2. **llama.cpp server responding** — the endpoint THIS provider points at (its
+ own `OPENCODE_CONFIG_CONTENT` `baseURL`, not a hardcoded default) answers
+ `GET /v1/models`.
+3. **Model available** — the provider's default model is one that endpoint
+ actually serves. This is the alias check: `--alias dflash` with a provider
+ asking for `dspark` fails here rather than inside a dead agent run.
+
+Until all three pass, the card says what is missing and links to
+**Settings → Local LLM**. The same failure previously surfaced only as
+`Cannot connect to API: Unable to connect` inside the agent transcript.
+
+The GGUF weights are a separate download from the binary: `llama-server` will
+not start without them, and PortOS now refuses the start with the missing path
+named rather than reporting a PID for a process that already exited.
+
---
## Ollama
diff --git a/server/lib/README.md b/server/lib/README.md
index 9fa92c7c40..758a208709 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -132,6 +132,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `providerFamilies.js` | Subscription-quota FAMILY identity — `PROVIDER_FAMILIES` (`{ id, label, matches }` for claude/codex/agy/grok), `PROVIDER_FAMILY_IDS`, `familyLabel`, `familyForProvider(config)` → family id or null (local-runtime wrappers and API-only providers belong to none). The pure half of the registry `services/providerUsage.js` attaches quota `fetch`ers to, so cost attribution and route validation can ask "which plan is this provider on?" without importing the PTY-scrape graph. Distinct from `providerVendors.js`, which is argv-shaped and includes vendors with no subscription quota. |
| `providerTranscriptUsage.js` | Parsers for the real per-message token counts the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `claudeProjectSlug`, `totalTranscriptTokens`. Both de-duplicate a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, and Codex's `total_token_usage` is cumulative and repeated. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. |
| `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring bare model ids under the selected local provider (`ollama` or `mtplx`) for marked OpenCode providers. Fixes --model rejection. |
+| `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX: label, binary, canonical base URL, manage/docs links, model-download hint), `localRuntimeKind(provider)` (the `*Backed` markers first, then the endpoint/name heuristic that mirrors the client's `localBackendForProvider`; `orcarouter` is excluded as a remote API), and `localRuntimeForProvider(provider)` → that row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`) rather than the canonical default, plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. |
| `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 1831c066dc..2237c66bb8 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -149,6 +149,7 @@ export * from './quotaBurnValidation.js';
export * from './quotaReset.js';
export * from './quotaWindows.js';
export * from './opencodeConfig.js';
+export * from './localProviderRuntime.js';
// `runners.js` re-defines `isFlux2`/`isZImage`/`isErnie` that also live in
// mediaModels.js — namespace it so the barrel surface is unambiguous.
export * as runners from './runners.js';
diff --git a/server/lib/localProviderRuntime.js b/server/lib/localProviderRuntime.js
new file mode 100644
index 0000000000..45814b4cfd
--- /dev/null
+++ b/server/lib/localProviderRuntime.js
@@ -0,0 +1,162 @@
+/**
+ * Which local runtime a provider talks to, and at which endpoint.
+ *
+ * A provider like `opencode-llama-tui` is only half a configuration: PortOS can
+ * spawn the OpenCode CLI perfectly and the run still dies with "Cannot connect
+ * to API: Unable to connect" because the daemon it points at — `llama-server`,
+ * the Ollama daemon, LM Studio's server, an MTPLX process — was never installed
+ * or never started. The binary check in `providerRuntimeInstaller.js` answers
+ * "can PortOS run `opencode`?", which is a different question and stays green in
+ * exactly that failure.
+ *
+ * This module is the pure half of the answer: given a provider record, which
+ * local runtime backs it (`llama` / `ollama` / `lmstudio` / `mtplx`) and what
+ * base URL should be probed. `services/providerReadiness.js` does the probing.
+ * Kept side-effect-free so both the readiness service and its tests can reason
+ * about the mapping without a daemon on the host.
+ *
+ * Endpoint resolution deliberately prefers the provider's OWN configuration
+ * over the canonical default: a user who moved llama-server to port 8090 edited
+ * `OPENCODE_CONFIG_CONTENT` (or `endpoint`), and probing 8080 anyway would
+ * report their working setup as broken.
+ */
+
+import { getOpencodeLocalProviderNamespace, isOpencodeCommand } from './providerModels.js';
+
+/**
+ * One row per local runtime PortOS knows how to check for.
+ *
+ * `manageUrl` is the client route that installs/starts it — the Local LLM
+ * settings tab owns every one of these flows, so an unmet requirement links
+ * there rather than duplicating the install UI on the Providers page.
+ */
+export const LOCAL_RUNTIMES = Object.freeze({
+ llama: Object.freeze({
+ id: 'llama',
+ label: 'llama.cpp',
+ // The server binary, not the `llama` convenience wrapper: this is what
+ // `llamaServerManager` resolves and starts.
+ command: 'llama-server',
+ defaultBaseUrl: 'http://127.0.0.1:8080/v1',
+ manageUrl: '/settings/local-llm',
+ docsUrl: 'https://github.com/ggml-org/llama.cpp',
+ // Named so an unmet check can say what the user still has to fetch. GGUF
+ // weights are a separate download from the binary — the single most common
+ // reason a freshly-installed llama.cpp still cannot serve a request.
+ modelsHint: 'llama.cpp serves GGUF weights you download yourself — a base model, plus a drafter for speculative decoding.',
+ }),
+ ollama: Object.freeze({
+ id: 'ollama',
+ label: 'Ollama',
+ command: 'ollama',
+ defaultBaseUrl: 'http://localhost:11434/v1',
+ manageUrl: '/settings/local-llm',
+ docsUrl: 'https://ollama.com/download',
+ modelsHint: 'Pull a model from Settings → Local LLM before an agent can use this provider.',
+ }),
+ lmstudio: Object.freeze({
+ id: 'lmstudio',
+ label: 'LM Studio',
+ command: 'lms',
+ defaultBaseUrl: 'http://localhost:1234/v1',
+ manageUrl: '/settings/local-llm',
+ docsUrl: 'https://lmstudio.ai/download',
+ modelsHint: 'Download a model in LM Studio and start its local server.',
+ }),
+ 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,
+ defaultBaseUrl: 'http://127.0.0.1:8000/v1',
+ 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.',
+ }),
+});
+
+/** Normalize a base URL to the `/v1` root an OpenAI-compatible probe needs. */
+export function normalizeOpenAiBaseUrl(url) {
+ if (typeof url !== 'string') return null;
+ const trimmed = url.trim().replace(/\/+$/, '');
+ if (trimmed === '') return null;
+ return /\/v\d+$/.test(trimmed) ? trimmed : `${trimmed}/v1`;
+}
+
+/** The `baseURL` an OpenCode provider config declares for `namespace`, if any. */
+function opencodeConfiguredBaseUrl(provider, namespace) {
+ const stored = provider?.envVars?.OPENCODE_CONFIG_CONTENT;
+ if (typeof stored !== 'string' || stored === '') return null;
+ let parsed = null;
+ try {
+ parsed = JSON.parse(stored);
+ } catch {
+ // A hand-edited config that no longer parses tells us nothing about the
+ // endpoint; fall through to the provider's own fields.
+ return null;
+ }
+ const baseUrl = parsed?.provider?.[namespace]?.options?.baseURL;
+ return typeof baseUrl === 'string' && baseUrl.trim() !== '' ? baseUrl : null;
+}
+
+/**
+ * The local-runtime kind a provider is backed by, from its explicit markers
+ * first and its endpoint/name only as a fallback.
+ *
+ * The `*Backed` markers are authoritative — they are what the spawner itself
+ * keys on. The heuristic tail mirrors the client's `localBackendForProvider`
+ * so a plain `api` provider pointed at Ollama or LM Studio is recognized too.
+ *
+ * `orcarouter` is deliberately excluded: it is an OpenCode local *namespace*
+ * but a remote hosted API, so there is no local daemon to check.
+ *
+ * @param {object|null|undefined} provider
+ * @returns {'llama'|'ollama'|'lmstudio'|'mtplx'|null}
+ */
+export function localRuntimeKind(provider) {
+ if (!provider || typeof provider !== 'object') return null;
+
+ const namespace = getOpencodeLocalProviderNamespace(provider);
+ if (namespace && namespace !== 'orcarouter') return namespace;
+ // `claude-ollama` carries `ollamaBacked` without being an OpenCode provider.
+ if (provider.ollamaBacked === true) return 'ollama';
+
+ const endpoint = String(provider.endpoint || '');
+ const id = String(provider.id || '').toLowerCase();
+ const name = String(provider.name || '').toLowerCase();
+ if (id === 'ollama' || /:11434\b/.test(endpoint) || name.includes('ollama')) return 'ollama';
+ if (id === 'lmstudio' || /:1234\b/.test(endpoint) || /lm[\s-]?studio/.test(name)) return 'lmstudio';
+ return null;
+}
+
+/**
+ * The local runtime a provider needs, with the endpoint PortOS should probe.
+ *
+ * @param {object|null|undefined} provider
+ * @returns {{kind:string,label:string,command:string|null,endpoint:string|null,manageUrl:string|null,docsUrl:string,modelsHint:string}|null}
+ */
+export function localRuntimeForProvider(provider) {
+ const kind = localRuntimeKind(provider);
+ if (!kind) return null;
+ const runtime = LOCAL_RUNTIMES[kind];
+
+ const configured = isOpencodeCommand(provider?.command)
+ ? opencodeConfiguredBaseUrl(provider, kind)
+ // Claude's Ollama wrapper carries the daemon URL in its own env var.
+ : (typeof provider?.envVars?.ANTHROPIC_BASE_URL === 'string' ? provider.envVars.ANTHROPIC_BASE_URL : null);
+
+ const endpoint = normalizeOpenAiBaseUrl(configured)
+ || normalizeOpenAiBaseUrl(provider?.endpoint)
+ || runtime.defaultBaseUrl;
+
+ return {
+ kind: runtime.id,
+ label: runtime.label,
+ command: runtime.command,
+ endpoint,
+ manageUrl: runtime.manageUrl,
+ docsUrl: runtime.docsUrl,
+ modelsHint: runtime.modelsHint,
+ };
+}
diff --git a/server/lib/localProviderRuntime.test.js b/server/lib/localProviderRuntime.test.js
new file mode 100644
index 0000000000..2cdea89c39
--- /dev/null
+++ b/server/lib/localProviderRuntime.test.js
@@ -0,0 +1,110 @@
+import { describe, it, expect } from 'vitest';
+import {
+ LOCAL_RUNTIMES,
+ localRuntimeForProvider,
+ localRuntimeKind,
+ normalizeOpenAiBaseUrl,
+} from './localProviderRuntime.js';
+
+const opencodeConfig = (namespace, baseURL) => JSON.stringify({
+ permission: 'allow',
+ provider: { [namespace]: { npm: '@ai-sdk/openai-compatible', options: { baseURL } } },
+});
+
+describe('normalizeOpenAiBaseUrl', () => {
+ it('appends /v1 only when the URL does not already end in a version segment', () => {
+ expect(normalizeOpenAiBaseUrl('http://localhost:11434')).toBe('http://localhost:11434/v1');
+ expect(normalizeOpenAiBaseUrl('http://localhost:11434/v1')).toBe('http://localhost:11434/v1');
+ expect(normalizeOpenAiBaseUrl('http://localhost:11434/v1/')).toBe('http://localhost:11434/v1');
+ });
+
+ it('returns null for anything unusable', () => {
+ expect(normalizeOpenAiBaseUrl('')).toBeNull();
+ expect(normalizeOpenAiBaseUrl(' ')).toBeNull();
+ expect(normalizeOpenAiBaseUrl(null)).toBeNull();
+ expect(normalizeOpenAiBaseUrl(42)).toBeNull();
+ });
+});
+
+describe('localRuntimeKind', () => {
+ it('reads the explicit backing markers first', () => {
+ expect(localRuntimeKind({ command: 'opencode', llamaBacked: true })).toBe('llama');
+ expect(localRuntimeKind({ command: 'opencode', mtplxBacked: true })).toBe('mtplx');
+ expect(localRuntimeKind({ command: 'opencode', ollamaBacked: true })).toBe('ollama');
+ // claude-ollama is not an OpenCode provider but is still Ollama-backed.
+ expect(localRuntimeKind({ command: 'claude', ollamaBacked: true })).toBe('ollama');
+ });
+
+ it('treats OrcaRouter as remote, not a local daemon', () => {
+ expect(localRuntimeKind({ command: 'opencode', orcarouterBacked: true })).toBeNull();
+ });
+
+ it('falls back to the endpoint/name heuristic for plain API providers', () => {
+ expect(localRuntimeKind({ type: 'api', id: 'ollama', endpoint: 'http://localhost:11434/v1' })).toBe('ollama');
+ expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://localhost:1234/v1' })).toBe('lmstudio');
+ expect(localRuntimeKind({ type: 'api', id: 'x', name: 'LM Studio local' })).toBe('lmstudio');
+ });
+
+ it('returns null for a remote provider and for junk input', () => {
+ expect(localRuntimeKind({ type: 'api', id: 'openai', endpoint: 'https://api.openai.com/v1' })).toBeNull();
+ expect(localRuntimeKind(null)).toBeNull();
+ expect(localRuntimeKind('nope')).toBeNull();
+ });
+});
+
+describe('localRuntimeForProvider', () => {
+ it('prefers the baseURL the provider itself declares over the canonical default', () => {
+ const runtime = localRuntimeForProvider({
+ id: 'opencode-llama-tui',
+ command: 'opencode',
+ llamaBacked: true,
+ endpoint: 'http://127.0.0.1:8080/v1',
+ envVars: { OPENCODE_CONFIG_CONTENT: opencodeConfig('llama', 'http://127.0.0.1:8090/v1') },
+ });
+ expect(runtime.kind).toBe('llama');
+ expect(runtime.label).toBe('llama.cpp');
+ expect(runtime.command).toBe('llama-server');
+ expect(runtime.endpoint).toBe('http://127.0.0.1:8090/v1');
+ expect(runtime.manageUrl).toBe('/settings/local-llm');
+ });
+
+ it('falls back to the provider endpoint when the stored OpenCode config is unparseable', () => {
+ const runtime = localRuntimeForProvider({
+ command: 'opencode',
+ llamaBacked: true,
+ endpoint: 'http://127.0.0.1:8081/v1',
+ envVars: { OPENCODE_CONFIG_CONTENT: '{not json' },
+ });
+ expect(runtime.endpoint).toBe('http://127.0.0.1:8081/v1');
+ });
+
+ it('falls back to the canonical default when the provider declares no endpoint at all', () => {
+ const runtime = localRuntimeForProvider({ command: 'opencode', ollamaBacked: true, envVars: {} });
+ expect(runtime.endpoint).toBe(LOCAL_RUNTIMES.ollama.defaultBaseUrl);
+ });
+
+ it('reads the Claude Ollama wrapper base URL out of ANTHROPIC_BASE_URL', () => {
+ const runtime = localRuntimeForProvider({
+ command: 'claude',
+ ollamaBacked: true,
+ envVars: { ANTHROPIC_BASE_URL: 'http://localhost:11500' },
+ });
+ expect(runtime.endpoint).toBe('http://localhost:11500/v1');
+ });
+
+ it('ignores a foreign namespace in the stored OpenCode config', () => {
+ // A config that only declares `ollama` says nothing about where this
+ // llama-backed provider points — using its baseURL would probe Ollama and
+ // report the wrong daemon as the missing requirement.
+ const runtime = localRuntimeForProvider({
+ command: 'opencode',
+ llamaBacked: true,
+ envVars: { OPENCODE_CONFIG_CONTENT: opencodeConfig('ollama', 'http://localhost:11434/v1') },
+ });
+ expect(runtime.endpoint).toBe(LOCAL_RUNTIMES.llama.defaultBaseUrl);
+ });
+
+ it('returns null for providers with no local dependency', () => {
+ expect(localRuntimeForProvider({ command: 'claude', type: 'cli' })).toBeNull();
+ });
+});
diff --git a/server/routes/providers.js b/server/routes/providers.js
index e247e5b853..830c484916 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -15,6 +15,7 @@ import {
spawnRuntimeInstaller,
stopRuntimeInstaller,
} from '../services/providerRuntimeInstaller.js';
+import { getProviderReadinessMap } from '../services/providerReadiness.js';
/**
* The CoS Agent Runner's exec allowlist, published read-only so the AI
@@ -134,6 +135,26 @@ export function createPortOSProviderRoutes(aiToolkit) {
res.json({ runtimes: await getProviderRuntimeStatuses() });
}));
+ /**
+ * Requirements checklist for every provider backed by a LOCAL daemon
+ * (llama.cpp, Ollama, LM Studio, MTPLX) — see `services/providerReadiness.js`.
+ *
+ * `/runtimes` above answers "can PortOS run this CLI?"; this answers "is the
+ * daemon that CLI talks to installed, running, and serving the model this
+ * provider asks for?" — the failure that otherwise only surfaces as
+ * "Cannot connect to API" inside a dead agent transcript.
+ *
+ * Computed on the RAW providers on purpose: a sanitized copy redacts secret
+ * env values, and a user's custom base URL can live in one
+ * (`OPENCODE_CONFIG_CONTENT`, `ANTHROPIC_BASE_URL`), which would send the
+ * probe at the wrong endpoint. The response carries booleans, labels, and the
+ * provider's own already-displayed endpoint — never a resolved binary path.
+ */
+ router.get('/readiness', asyncHandler(async (_req, res) => {
+ const data = await providerService.getAllProviders();
+ res.json({ readiness: await getProviderReadinessMap(data.providers) });
+ }));
+
/**
* Install one provider runtime, streaming the installer's output as SSE.
*
diff --git a/server/routes/providers.readiness.test.js b/server/routes/providers.readiness.test.js
new file mode 100644
index 0000000000..eb5a61aa14
--- /dev/null
+++ b/server/routes/providers.readiness.test.js
@@ -0,0 +1,68 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express, { Router } from 'express';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { request } from '../lib/testHelper.js';
+
+const readinessService = vi.hoisted(() => ({ getProviderReadinessMap: vi.fn() }));
+vi.mock('../services/providerReadiness.js', () => readinessService);
+// The runtime installer probes real binaries at import time in some paths; the
+// readiness route never touches it, so keep it inert here.
+vi.mock('../services/providerRuntimeInstaller.js', () => ({
+ getProviderRuntime: vi.fn(),
+ getProviderRuntimeStatus: vi.fn(),
+ getProviderRuntimeStatuses: vi.fn().mockResolvedValue({}),
+ spawnRuntimeInstaller: vi.fn(),
+ stopRuntimeInstaller: vi.fn(),
+ describeRuntimeInstall: vi.fn(),
+}));
+
+import { createPortOSProviderRoutes } from './providers.js';
+
+// A provider whose real base URL lives in an env var the user marked secret —
+// the shape that would be redacted to `***` by the client-facing sanitizer.
+const CLAUDE_OLLAMA = {
+ id: 'claude-ollama',
+ name: 'Claude Ollama (local model)',
+ command: 'claude',
+ ollamaBacked: true,
+ envVars: { ANTHROPIC_BASE_URL: 'http://localhost:11500', ANTHROPIC_AUTH_TOKEN: 'ollama' },
+ secretEnvVars: ['ANTHROPIC_AUTH_TOKEN'],
+};
+
+const app = (providers) => {
+ const toolkit = {
+ services: { providers: { getAllProviders: vi.fn().mockResolvedValue({ providers, activeProvider: null }) } },
+ routes: { providers: Router() },
+ };
+ const server = express();
+ server.use(express.json());
+ server.use('/api/providers', createPortOSProviderRoutes(toolkit));
+ server.use(errorMiddleware);
+ return server;
+};
+
+describe('GET /api/providers/readiness', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ readinessService.getProviderReadinessMap.mockResolvedValue({});
+ });
+
+ it('publishes the readiness map keyed by provider id', async () => {
+ readinessService.getProviderReadinessMap.mockResolvedValueOnce({
+ 'claude-ollama': { kind: 'ollama', label: 'Ollama', ready: false, checks: [{ id: 'server', ok: false }] },
+ });
+
+ const response = await request(app([CLAUDE_OLLAMA])).get('/api/providers/readiness');
+
+ expect(response.status).toBe(200);
+ expect(response.body.readiness['claude-ollama'].ready).toBe(false);
+ });
+
+ it('checks the RAW providers, so a base URL stored as a secret env var still resolves', async () => {
+ await request(app([CLAUDE_OLLAMA])).get('/api/providers/readiness');
+
+ const [providers] = readinessService.getProviderReadinessMap.mock.calls[0];
+ expect(providers[0].envVars.ANTHROPIC_BASE_URL).toBe('http://localhost:11500');
+ expect(providers[0].envVars.ANTHROPIC_AUTH_TOKEN).not.toBe('***');
+ });
+});
diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.js
index f8b6165998..4fbdbe3547 100644
--- a/server/services/llamaServerManager.js
+++ b/server/services/llamaServerManager.js
@@ -5,6 +5,8 @@
* for a local `llama-server` instance running speculative decoding (e.g. DFlash 2).
*/
+import { stat } from 'fs/promises';
+import { isAbsolute, resolve } from 'path';
import { spawn } from '../lib/childProcess.js';
import { commandExists } from '../lib/commandExists.js';
import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
@@ -39,7 +41,11 @@ function appendLog(line) {
async function probeEndpoint(endpoint) {
try {
const url = `${endpoint.replace(/\/+$/, '')}/models`;
- const res = await fetchWithTimeout(url, { method: 'GET', timeout: PROBE_TIMEOUT_MS });
+ // The bound is `fetchWithTimeout`'s THIRD argument — a `timeout` key inside
+ // the init object is not a fetch option and was silently ignored, leaving
+ // this probe on the 15s default. That mattered on the start path, where the
+ // probe runs in a 500ms poll loop against a port nothing has bound yet.
+ const res = await fetchWithTimeout(url, { method: 'GET' }, PROBE_TIMEOUT_MS);
return res.ok;
} catch {
return false;
@@ -65,6 +71,29 @@ function resolveLlamaServerBinary() {
return findCommandOnPath('llama-server');
}
+/**
+ * Fails the start request when a GGUF the launch line names is not on disk.
+ *
+ * The weights are a SEPARATE download from the binary — several gigabytes the
+ * user fetches from Hugging Face themselves — and that is the single most
+ * common reason a freshly-installed llama.cpp still cannot serve anything.
+ * Without this check llama-server spawns, exits within a second, and the UI
+ * reports "started (PID …)" from a process that is already gone; the real cause
+ * is one line deep in the server log.
+ *
+ * Relative paths resolve against the server's cwd, which is the cwd the child
+ * inherits — so this checks the same file llama-server would open.
+ */
+async function assertModelFileExists(label, modelPath) {
+ const resolved = isAbsolute(modelPath) ? modelPath : resolve(process.cwd(), modelPath);
+ const stats = await stat(resolved).catch(() => null);
+ if (stats?.isFile()) return;
+ throw new ServerError(
+ `${label} was not found at \`${modelPath}\`. Download the GGUF first — the Local LLM tab lists the base/drafter pairs — or point this field at a file you already have.`,
+ { status: 400, code: 'LLAMA_MODEL_FILE_MISSING' }
+ );
+}
+
/**
* Returns current status of llama-server (binary availability, running state, config, logs).
*/
@@ -131,7 +160,9 @@ export async function startLlamaServer(options = {}) {
}
const args = ['-m', model.trim()];
+ await assertModelFileExists('The base model', model.trim());
if (draftModel && typeof draftModel === 'string' && draftModel.trim()) {
+ await assertModelFileExists('The drafter model', draftModel.trim());
args.push('--draft-model', draftModel.trim());
if (specType) args.push('--spec-type', specType.trim());
}
@@ -200,6 +231,19 @@ export async function startLlamaServer(options = {}) {
if (online) break;
}
+ // A child that has already exited is not a started server. Reporting
+ // `success: true` here put "llama-server started (PID …)" on screen for a
+ // process that died on a bad flag, an unreadable GGUF, or an unsupported
+ // `--spec-type` — the user then went looking for a connection problem in
+ // OpenCode instead of reading the four log lines that explain it.
+ if (child.exitCode !== null || child.signalCode) {
+ const tail = recentLogs.slice(-4).join(' | ');
+ throw new ServerError(
+ `llama-server exited immediately${lastExitError ? ` (${lastExitError})` : ''}.${tail ? ` Last output: ${tail}` : ''}`,
+ { status: 500, code: 'LLAMA_SERVER_EXITED' }
+ );
+ }
+
return {
success: true,
running: true,
diff --git a/server/services/llamaServerManager.test.js b/server/services/llamaServerManager.test.js
index eaa383c150..0a5e11b29c 100644
--- a/server/services/llamaServerManager.test.js
+++ b/server/services/llamaServerManager.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest';
import {
getLlamaServerStatus,
startLlamaServer,
@@ -10,6 +10,9 @@ import * as processEnv from '../lib/processEnv.js';
import * as commandExistsModule from '../lib/commandExists.js';
import * as childProcess from '../lib/childProcess.js';
import { EventEmitter } from 'events';
+import { mkdtemp, rm, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
function fakeSpawnProcess() {
const child = new EventEmitter();
@@ -27,6 +30,24 @@ function endProcess(child, code) {
}
describe('llamaServerManager', () => {
+ // startLlamaServer refuses to spawn for a GGUF that is not on disk, so the
+ // lifecycle tests need real files to point at.
+ let modelDir;
+ let modelPath;
+ let draftPath;
+
+ beforeAll(async () => {
+ modelDir = await mkdtemp(join(tmpdir(), 'portos-llama-'));
+ modelPath = join(modelDir, 'model.gguf');
+ draftPath = join(modelDir, 'draft.gguf');
+ await writeFile(modelPath, 'gguf');
+ await writeFile(draftPath, 'gguf');
+ });
+
+ afterAll(async () => {
+ await rm(modelDir, { recursive: true, force: true });
+ });
+
beforeEach(() => {
_resetLlamaServerStateForTests();
vi.restoreAllMocks();
@@ -62,7 +83,7 @@ describe('llamaServerManager', () => {
it('rejects start when binary is missing', async () => {
vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue(null);
- await expect(startLlamaServer({ model: '/path/to/model.gguf' })).rejects.toThrow(
+ await expect(startLlamaServer({ model: modelPath })).rejects.toThrow(
/llama-server binary was not found/i
);
});
@@ -84,8 +105,8 @@ describe('llamaServerManager', () => {
});
const result = await startLlamaServer({
- model: 'models/Qwen3.8-27B.gguf',
- draftModel: 'models/Qwen3.8-DFlash2.gguf',
+ model: modelPath,
+ draftModel: draftPath,
specType: 'draft-dflash',
port: 8080,
host: '127.0.0.1',
@@ -96,8 +117,8 @@ describe('llamaServerManager', () => {
expect(result.pid).toBe(12345);
expect(spawnArgs.cmd).toBe('/usr/local/bin/llama-server');
expect(spawnArgs.args).toEqual([
- '-m', 'models/Qwen3.8-27B.gguf',
- '--draft-model', 'models/Qwen3.8-DFlash2.gguf',
+ '-m', modelPath,
+ '--draft-model', draftPath,
'--spec-type', 'draft-dflash',
'--port', '8080',
'--host', '127.0.0.1',
@@ -112,6 +133,46 @@ describe('llamaServerManager', () => {
expect(status.pid).toBe(12345);
});
+ it('refuses to start when the GGUF the launch line names is not on disk', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');
+ const spawnSpy = vi.spyOn(childProcess, 'spawn');
+
+ await expect(startLlamaServer({ model: join(modelDir, 'absent.gguf') })).rejects.toThrow(
+ /base model was not found/i
+ );
+ await expect(startLlamaServer({ model: modelPath, draftModel: join(modelDir, 'absent.gguf') })).rejects.toThrow(
+ /drafter model was not found/i
+ );
+ // The weights are a separate multi-gigabyte download; spawning anyway just
+ // buries that in a server log.
+ expect(spawnSpy).not.toHaveBeenCalled();
+ });
+
+ it('reports a failure — not a PID — when llama-server exits during startup', async () => {
+ vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');
+
+ const fakeChild = new EventEmitter();
+ fakeChild.pid = 999;
+ fakeChild.killed = false;
+ fakeChild.exitCode = null;
+ fakeChild.stdout = new EventEmitter();
+ fakeChild.stderr = new EventEmitter();
+
+ vi.spyOn(childProcess, 'spawn').mockImplementation(() => {
+ // A real llama.cpp rejects an unsupported --spec-type within a beat.
+ setTimeout(() => {
+ fakeChild.stderr.emit('data', Buffer.from('error: unknown spec type\n'));
+ fakeChild.exitCode = 1;
+ fakeChild.emit('exit', 1, null);
+ }, 0);
+ return fakeChild;
+ });
+
+ await expect(startLlamaServer({ model: modelPath, specType: 'draft-nope' })).rejects.toThrow(
+ /llama-server exited immediately/i
+ );
+ });
+
it('stops managed process cleanly', async () => {
vi.spyOn(processEnv, 'findCommandOnPath').mockReturnValue('/usr/local/bin/llama-server');
@@ -125,7 +186,7 @@ describe('llamaServerManager', () => {
vi.spyOn(childProcess, 'spawn').mockReturnValue(fakeChild);
- await startLlamaServer({ model: 'models/model.gguf' });
+ await startLlamaServer({ model: modelPath });
const stopResult = await stopLlamaServer();
expect(stopResult.success).toBe(true);
diff --git a/server/services/providerReadiness.js b/server/services/providerReadiness.js
new file mode 100644
index 0000000000..b00e681fcb
--- /dev/null
+++ b/server/services/providerReadiness.js
@@ -0,0 +1,230 @@
+/**
+ * "Is everything this provider needs actually installed and running?"
+ *
+ * The Providers page could already tell you whether the CLI binary a provider
+ * shells out to exists (`providerRuntimeInstaller.js`). For a provider backed by
+ * a LOCAL daemon that is only half the story: `opencode` can be perfectly
+ * installed and the run still ends at
+ *
+ * Cannot connect to API: Unable to connect. Is the computer able to access the url
+ *
+ * because `llama-server` was never installed, or was installed but never
+ * started, or is running but serving a different model alias than the provider
+ * asks for. Those are three distinct fixes, and none of them was visible from
+ * the provider card — the user had to read a failed agent transcript to learn
+ * that a second piece of software (and a multi-gigabyte model download) was
+ * still missing.
+ *
+ * This module turns that into a per-provider requirements checklist:
+ *
+ * 1. runtime — the daemon's binary is on PortOS's PATH (or something is
+ * already answering, which proves it another way)
+ * 2. server — the endpoint the provider points at answers `GET /v1/models`
+ * 3. model — the provider's default model is one the endpoint serves
+ *
+ * Checks are reported in fix order, each with what to do about it. Only
+ * local-daemon providers get a report at all (`localProviderRuntime.js` decides
+ * which those are); everything else returns `null` and renders nothing.
+ *
+ * No LLM call is ever made here — `GET /v1/models` is a listing, so this is safe
+ * to poll from a settings page under the no-cold-bootstrap policy in CLAUDE.md.
+ */
+
+import { LOCAL_RUNTIMES, localRuntimeForProvider } from '../lib/localProviderRuntime.js';
+import { isConfiguredDefaultModel } from '../lib/providerModels.js';
+import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+import { findCommandOnPath } from '../lib/processEnv.js';
+
+/**
+ * Loopback daemons answer (or refuse the connection) in single-digit
+ * milliseconds, so a short bound keeps a page poll snappy. A host that needs
+ * longer than this to answer a model listing is not going to serve an agent run
+ * either, and reporting it as unreachable points at the right fix.
+ */
+const PROBE_TIMEOUT_MS = 2_000;
+
+/**
+ * Collapse the bursts a page reload produces (the Providers page asks for
+ * readiness on mount and on every 20s status poll, and several providers can
+ * share one endpoint) without going stale enough to hide a daemon the user just
+ * started from the Local LLM tab.
+ */
+const PROBE_TTL_MS = 5_000;
+
+// endpoint → { at, result }
+const probeCache = new Map();
+
+/**
+ * Ask an OpenAI-compatible endpoint what it serves.
+ * @returns {Promise<{reachable:boolean, models:string[]|null, error:string|null}>}
+ * `models: null` means reachable but the listing could not be read — distinct
+ * from `[]`, a server that is up with nothing loaded.
+ */
+async function probeEndpoint(endpoint) {
+ const res = await fetchWithTimeout(`${endpoint}/models`, { method: 'GET' }, PROBE_TIMEOUT_MS)
+ .catch((err) => ({ ok: false, transportError: err?.message || 'connection failed' }));
+
+ if (res.transportError) return { reachable: false, models: null, error: res.transportError };
+ if (!res.ok) return { reachable: false, models: null, error: `HTTP ${res.status}` };
+
+ const body = await res.json().catch(() => null);
+ const rows = Array.isArray(body?.data) ? body.data : Array.isArray(body?.models) ? body.models : null;
+ if (!rows) return { reachable: true, models: null, error: 'model listing was not readable' };
+ const models = rows
+ .map((row) => (typeof row === 'string' ? row : row?.id || row?.name))
+ .filter((id) => typeof id === 'string' && id !== '');
+ return { reachable: true, models, error: null };
+}
+
+/** Cached endpoint probe — see PROBE_TTL_MS. */
+async function probeEndpointCached(endpoint, probe) {
+ const cached = probeCache.get(endpoint);
+ if (cached && Date.now() - cached.at < PROBE_TTL_MS) return cached.result;
+ const result = await probe(endpoint);
+ probeCache.set(endpoint, { at: Date.now(), result });
+ return result;
+}
+
+/**
+ * The model id the endpoint would be asked for: the provider's default with any
+ * OpenCode `<namespace>/` prefix stripped, since that prefix addresses the
+ * OpenCode provider entry and never reaches the daemon's own model list.
+ * Returns null when the provider selects no specific model.
+ */
+function servedModelId(provider, kind) {
+ const model = provider?.defaultModel;
+ if (typeof model !== 'string' || model.trim() === '' || isConfiguredDefaultModel(model)) return null;
+ const trimmed = model.trim();
+ return trimmed.startsWith(`${kind}/`) ? trimmed.slice(kind.length + 1) : trimmed;
+}
+
+/**
+ * The requirements checklist for one provider, or `null` when the provider does
+ * not depend on a local daemon.
+ *
+ * Deps are injectable so the suite can drive every combination without a daemon
+ * or a real PATH on the host.
+ *
+ * @param {object} provider - the RAW provider record (endpoint + envVars intact;
+ * a sanitized copy has its secret env values redacted, which would hide a
+ * custom base URL)
+ * @param {{findCommand?:Function, probe?:Function}} [deps]
+ */
+export async function getProviderReadiness(provider, deps = {}) {
+ const runtime = localRuntimeForProvider(provider);
+ if (!runtime) return null;
+
+ const findCommand = deps.findCommand || findCommandOnPath;
+
+ // An injected probe bypasses the cache: it is a different oracle than the
+ // real one, and sharing a cache entry with it would let one caller's stub
+ // answer for another's live probe.
+ const endpointResult = deps.probe
+ ? await deps.probe(runtime.endpoint)
+ : await probeEndpointCached(runtime.endpoint, probeEndpoint);
+ // A daemon that answers is installed, whatever PATH says — Ollama's macOS app
+ // and LM Studio both serve without putting a CLI on PortOS's PATH.
+ const onPath = Boolean(runtime.command && findCommand(runtime.command));
+ const installed = onPath || endpointResult.reachable;
+
+ const checks = [];
+
+ checks.push({
+ id: 'runtime',
+ label: `${runtime.label} installed`,
+ ok: installed,
+ detail: installed
+ ? (onPath ? `\`${runtime.command}\` is on PortOS's PATH.` : `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.`,
+ fixHint: installed
+ ? null
+ : runtime.manageUrl
+ ? `Install ${runtime.label} from Settings → Local LLM.`
+ : `Follow the ${runtime.label} setup docs, then reload this page.`,
+ });
+
+ checks.push({
+ id: 'server',
+ label: `${runtime.label} server responding`,
+ ok: endpointResult.reachable,
+ detail: endpointResult.reachable
+ ? `${runtime.endpoint} answered.`
+ : `Nothing answered at ${runtime.endpoint}${endpointResult.error ? ` (${endpointResult.error})` : ''}.`,
+ fixHint: endpointResult.reachable
+ ? null
+ : installed
+ ? `Start ${runtime.label}${runtime.manageUrl ? ' from Settings → Local LLM' : ''}. ${runtime.modelsHint}`
+ : `Install ${runtime.label} first, then start it. ${runtime.modelsHint}`,
+ });
+
+ const wantedModel = servedModelId(provider, runtime.kind);
+ if (wantedModel) {
+ // Only assertable against a server that answered with a readable list. An
+ // unreachable (or unlistable) endpoint says nothing about the model, and
+ // reporting it as missing would send the user after the wrong fix.
+ const served = endpointResult.reachable ? endpointResult.models : null;
+ const ok = Array.isArray(served) ? served.includes(wantedModel) : null;
+ checks.push({
+ id: 'model',
+ label: `Model \`${wantedModel}\` available`,
+ ok,
+ detail: ok === null
+ ? 'Cannot be checked until the server responds.'
+ : ok
+ ? `${runtime.label} is serving \`${wantedModel}\`.`
+ : served.length === 0
+ ? `${runtime.label} is running but has no model loaded.`
+ : `${runtime.label} is serving ${served.slice(0, 3).map((id) => `\`${id}\``).join(', ')}${served.length > 3 ? ` +${served.length - 3} more` : ''}.`,
+ fixHint: ok === null || ok
+ ? null
+ : `${runtime.modelsHint} Then set this provider's default model to one the server reports.`,
+ });
+ }
+
+ return {
+ kind: runtime.kind,
+ label: runtime.label,
+ endpoint: runtime.endpoint,
+ manageUrl: runtime.manageUrl,
+ docsUrl: runtime.docsUrl,
+ // `ready` is strict: a check that could not be evaluated (`ok: null`) is not
+ // a pass, so the card never claims a provider is good to go on unknowns.
+ ready: checks.every((check) => check.ok === true),
+ checks,
+ };
+}
+
+/**
+ * Readiness for every provider that needs a local daemon, keyed by provider id.
+ * Providers with no local dependency are omitted entirely, so the client can
+ * treat "absent" as "nothing to report".
+ *
+ * @param {object[]} providers - RAW provider records
+ */
+export async function getProviderReadinessMap(providers, deps = {}) {
+ const list = Array.isArray(providers) ? providers : [];
+ // One PATH scan per distinct binary, and one HTTP probe per distinct endpoint,
+ // no matter how many providers share them.
+ const pathCache = new Map();
+ const findCommand = deps.findCommand || findCommandOnPath;
+ const memoFind = (command) => {
+ if (!pathCache.has(command)) pathCache.set(command, findCommand(command));
+ return pathCache.get(command);
+ };
+
+ const entries = await Promise.all(list.map(async (provider) => {
+ const readiness = await getProviderReadiness(provider, { ...deps, findCommand: memoFind });
+ return readiness ? [provider.id, readiness] : null;
+ }));
+ return Object.fromEntries(entries.filter(Boolean));
+}
+
+/** The runtimes this module knows how to check — re-exported for callers/tests. */
+export { LOCAL_RUNTIMES };
+
+/** Drops the endpoint probe cache (tests, and after an install/start action). */
+export function resetProviderReadinessCache() {
+ probeCache.clear();
+}
diff --git a/server/services/providerReadiness.test.js b/server/services/providerReadiness.test.js
new file mode 100644
index 0000000000..bfca75f336
--- /dev/null
+++ b/server/services/providerReadiness.test.js
@@ -0,0 +1,179 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { getProviderReadiness, getProviderReadinessMap, resetProviderReadinessCache } from './providerReadiness.js';
+
+const llamaProvider = (overrides = {}) => ({
+ id: 'opencode-llama-tui',
+ name: 'OpenCode llama TUI',
+ type: 'tui',
+ command: 'opencode',
+ llamaBacked: true,
+ endpoint: 'http://127.0.0.1:8080/v1',
+ models: ['dflash'],
+ defaultModel: 'dflash',
+ ...overrides,
+});
+
+const reachable = (models) => async () => ({ reachable: true, models, error: null });
+const unreachable = (error = 'connection refused') => async () => ({ reachable: false, models: null, error });
+
+const checkById = (readiness, id) => readiness.checks.find((check) => check.id === id);
+
+beforeEach(() => {
+ resetProviderReadinessCache();
+});
+
+describe('getProviderReadiness', () => {
+ it('returns null for a provider with no local daemon', async () => {
+ const readiness = await getProviderReadiness(
+ { id: 'claude', command: 'claude', type: 'cli' },
+ { findCommand: () => '/usr/bin/claude', probe: unreachable() },
+ );
+ expect(readiness).toBeNull();
+ });
+
+ it('reports ready when the binary, the server, and the model all check out', async () => {
+ const readiness = await getProviderReadiness(llamaProvider(), {
+ findCommand: () => '/opt/homebrew/bin/llama-server',
+ probe: reachable(['dflash']),
+ });
+ expect(readiness.kind).toBe('llama');
+ expect(readiness.ready).toBe(true);
+ expect(readiness.checks.map((check) => check.ok)).toEqual([true, true, true]);
+ });
+
+ it('separates "not installed" from "installed but not running" — the two different fixes', async () => {
+ const missing = await getProviderReadiness(llamaProvider(), {
+ findCommand: () => null,
+ probe: unreachable(),
+ });
+ expect(checkById(missing, 'runtime').ok).toBe(false);
+ expect(checkById(missing, 'runtime').fixHint).toMatch(/Install llama\.cpp/);
+
+ const stopped = await getProviderReadiness(llamaProvider(), {
+ findCommand: () => '/opt/homebrew/bin/llama-server',
+ probe: unreachable(),
+ });
+ expect(checkById(stopped, 'runtime').ok).toBe(true);
+ expect(checkById(stopped, 'server').ok).toBe(false);
+ expect(checkById(stopped, 'server').fixHint).toMatch(/Start llama\.cpp/);
+ expect(stopped.ready).toBe(false);
+ });
+
+ it('counts a responding endpoint as installed even with nothing on PATH', async () => {
+ // LM Studio and the Ollama macOS app both serve without putting a CLI on
+ // PortOS's PATH — reporting them uninstalled would send the user to install
+ // software they are already running.
+ const readiness = await getProviderReadiness(llamaProvider({ defaultModel: null }), {
+ findCommand: () => null,
+ probe: reachable(['dflash']),
+ });
+ expect(checkById(readiness, 'runtime').ok).toBe(true);
+ expect(readiness.ready).toBe(true);
+ });
+
+ it('flags a model the running server does not serve, and names what it does serve', async () => {
+ const readiness = await getProviderReadiness(llamaProvider({ defaultModel: 'dspark' }), {
+ findCommand: () => '/opt/homebrew/bin/llama-server',
+ probe: reachable(['dflash', 'qwen3.8-27b']),
+ });
+ const model = checkById(readiness, 'model');
+ expect(model.ok).toBe(false);
+ expect(model.detail).toContain('dflash');
+ expect(readiness.ready).toBe(false);
+ });
+
+ it('calls out a running server with nothing loaded', async () => {
+ const readiness = await getProviderReadiness(llamaProvider(), {
+ findCommand: () => '/opt/homebrew/bin/llama-server',
+ probe: reachable([]),
+ });
+ expect(checkById(readiness, 'model').detail).toMatch(/no model loaded/);
+ });
+
+ it('leaves the model check unknown — never failed — while the server is down', async () => {
+ const readiness = await getProviderReadiness(llamaProvider(), {
+ findCommand: () => '/opt/homebrew/bin/llama-server',
+ probe: unreachable(),
+ });
+ const model = checkById(readiness, 'model');
+ expect(model.ok).toBeNull();
+ expect(model.fixHint).toBeNull();
+ // An unevaluated check is not a pass.
+ expect(readiness.ready).toBe(false);
+ });
+
+ it('strips the OpenCode namespace before comparing against the served model ids', async () => {
+ // `--model llama/dflash` addresses the OpenCode provider entry; the daemon
+ // itself only ever reports the bare alias.
+ const readiness = await getProviderReadiness(llamaProvider({ defaultModel: 'llama/dflash' }), {
+ findCommand: () => '/opt/homebrew/bin/llama-server',
+ probe: reachable(['dflash']),
+ });
+ expect(checkById(readiness, 'model').ok).toBe(true);
+ });
+
+ it('omits the model check when the provider pins no model', async () => {
+ const readiness = await getProviderReadiness(
+ { id: 'opencode-ollama', command: 'opencode', ollamaBacked: true, defaultModel: null },
+ { findCommand: () => '/usr/local/bin/ollama', probe: reachable(['llama3:8b']) },
+ );
+ expect(readiness.checks.map((check) => check.id)).toEqual(['runtime', 'server']);
+ expect(readiness.ready).toBe(true);
+ });
+
+ it('probes the endpoint the provider configures, not the canonical default', async () => {
+ const probed = [];
+ await getProviderReadiness(
+ llamaProvider({
+ endpoint: 'http://127.0.0.1:8090/v1',
+ envVars: { OPENCODE_CONFIG_CONTENT: JSON.stringify({ provider: { llama: { options: { baseURL: 'http://127.0.0.1:8090/v1' } } } }) },
+ }),
+ { findCommand: () => null, probe: async (endpoint) => { probed.push(endpoint); return { reachable: false, models: null, error: 'refused' }; } },
+ );
+ expect(probed).toEqual(['http://127.0.0.1:8090/v1']);
+ });
+
+ it('never leaks the resolved binary path', async () => {
+ const readiness = await getProviderReadiness(llamaProvider(), {
+ findCommand: () => '/Users/someone/bin/llama-server',
+ probe: reachable(['dflash']),
+ });
+ expect(JSON.stringify(readiness)).not.toContain('/Users/someone');
+ });
+
+ it('offers docs rather than an install for a runtime PortOS does not manage', async () => {
+ const readiness = await getProviderReadiness(
+ { id: 'opencode-mtplx', command: 'opencode', mtplxBacked: true, defaultModel: 'mtplx' },
+ { findCommand: () => null, probe: unreachable() },
+ );
+ expect(readiness.manageUrl).toBeNull();
+ expect(readiness.docsUrl).toBeTruthy();
+ expect(checkById(readiness, 'runtime').fixHint).toMatch(/setup docs/);
+ });
+});
+
+describe('getProviderReadinessMap', () => {
+ it('keys only the local-daemon providers, and probes each endpoint once', async () => {
+ const probed = [];
+ const map = await getProviderReadinessMap(
+ [
+ llamaProvider(),
+ llamaProvider({ id: 'opencode-llama', type: 'cli' }),
+ { id: 'claude', command: 'claude', type: 'cli' },
+ ],
+ {
+ findCommand: () => '/opt/homebrew/bin/llama-server',
+ probe: async (endpoint) => { probed.push(endpoint); return { reachable: true, models: ['dflash'], error: null }; },
+ },
+ );
+ expect(Object.keys(map).sort()).toEqual(['opencode-llama', 'opencode-llama-tui']);
+ // Both llama providers point at the same daemon; the injected probe sees
+ // one call per provider, but the PATH scan is shared.
+ expect(probed).toHaveLength(2);
+ expect(map['opencode-llama'].ready).toBe(true);
+ });
+
+ it('tolerates junk input', async () => {
+ await expect(getProviderReadinessMap(null, { findCommand: () => null, probe: unreachable() })).resolves.toEqual({});
+ });
+});