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

collapse the duplicated local-daemon probes and classifiers behind one lib each

[._.]/ Adam Eivy5e91ca893ac5
diff --git a/client/src/components/providers/ProviderReadiness.jsx b/client/src/components/providers/ProviderReadiness.jsx
index 87370b691a..76ce8f5ea2 100644
--- a/client/src/components/providers/ProviderReadiness.jsx
+++ b/client/src/components/providers/ProviderReadiness.jsx
@@ -17,6 +17,7 @@
import { Link } from 'react-router';
import { CheckCircle2, HelpCircle, Wrench, XCircle } from 'lucide-react';
+import Banner from '../ui/Banner';
import Pill from '../ui/Pill';
const ICONS = {
@@ -28,6 +29,8 @@ const ICONS = {
null: { Icon: HelpCircle, cls: 'text-gray-500' },
};
+const LINK_CLASS = 'text-port-accent hover:text-port-accent/80 underline underline-offset-2';
+
/**
* 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
@@ -52,23 +55,23 @@ export default function ProviderReadiness({ readiness, className = '' }) {
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>
+ <Pill tone="success" size="xs" icon={CheckCircle2} className={className} title={`${label} is running at ${endpoint}.`}>
+ {label} ready
+ </Pill>
);
}
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">
+ <Banner
+ tone="warning"
+ size="sm"
+ icon={Wrench}
+ className={className}
+ title={`${label} setup incomplete — ${blocked} requirement${blocked === 1 ? '' : 's'} unmet`}
+ >
+ <ul className="space-y-1 mt-1">
{checks.map((check) => {
const { Icon, cls } = ICONS[String(check.ok)] || ICONS.null;
return (
@@ -85,18 +88,14 @@ export default function ProviderReadiness({ readiness, className = '' }) {
);
})}
</ul>
- <div className="flex flex-wrap items-center gap-3 pt-0.5">
+ <div className="flex flex-wrap items-center gap-3 pt-1.5">
{manageUrl && (
- <Link to={manageUrl} className="text-port-accent hover:text-port-accent/80 underline underline-offset-2">
- Open Local LLM settings
- </Link>
+ <Link to={manageUrl} className={LINK_CLASS}>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>
+ <a href={docsUrl} target="_blank" rel="noreferrer" className={LINK_CLASS}>{label} setup docs</a>
)}
</div>
- </div>
+ </Banner>
);
}
diff --git a/client/src/components/providers/ProviderReadiness.test.jsx b/client/src/components/providers/ProviderReadiness.test.jsx
index 47ee83c3c9..a8f7451e2e 100644
--- a/client/src/components/providers/ProviderReadiness.test.jsx
+++ b/client/src/components/providers/ProviderReadiness.test.jsx
@@ -21,13 +21,11 @@ const readiness = (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: [] })} />);
+ it.each([
+ ['no report yet (the card paints before the fetch lands)', null],
+ ['a report with no checks', readiness({ checks: [] })],
+ ])('renders nothing for %s', (_label, value) => {
+ const { container } = renderWithRouter(<ProviderReadiness readiness={value} />);
expect(container.textContent).toBe('');
});
@@ -47,13 +45,9 @@ describe('ProviderReadiness', () => {
// 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} />);
+ // …and reads correctly when only one is outstanding.
+ renderWithRouter(<ProviderReadiness readiness={readiness({ checks: readiness().checks.slice(0, 2) })} />);
expect(screen.getByText(/1 requirement unmet/)).toBeTruthy();
});
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 44868d0961..3f1f7e3390 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -6,6 +6,7 @@ import * as api from '../services/api';
import socket from '../services/socket';
import { filterSelectableModels, filterGenerationModels, isEmbeddingModel, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, supportsModelRefresh, isGrokBuildCli, isLocalEndpoint, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, isOrcaRouterBackedProvider, providerRuntimeKey } from '../utils/providers';
import useLocalModels from '../hooks/useLocalModels';
+import { useAutoRefetch } from '../hooks/useAutoRefetch';
import BrailleSpinner from '../components/BrailleSpinner';
import EmptyState from '../components/EmptyState';
import Banner from '../components/ui/Banner';
@@ -209,15 +210,11 @@ export default function AIProviders() {
setReadiness(data?.readiness && typeof data.readiness === 'object' ? data.readiness : {});
}, []);
- useEffect(() => { loadReadiness(); }, [loadReadiness]);
-
- useEffect(() => {
- const id = setInterval(() => {
- refreshStatuses();
- loadReadiness();
- }, 20000);
- return () => clearInterval(id);
- }, [refreshStatuses, loadReadiness]);
+ // `useAutoRefetch` rather than a raw interval so both polls pause while the
+ // tab is hidden — a readiness tick costs one HTTP probe per distinct local
+ // endpoint, which a backgrounded settings tab should not keep spending.
+ const pollCards = useCallback(() => Promise.all([refreshStatuses(), loadReadiness()]), [refreshStatuses, loadReadiness]);
+ useAutoRefetch(pollCards, 20000, { pollOnly: true });
// 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
@@ -367,6 +364,11 @@ export default function AIProviders() {
const runtimeForProvider = (provider) => {
const backend = isApiProvider(provider) ? localBackendForProvider(provider) : null;
if (!backend) return runtimes[providerRuntimeKey(provider)] || null;
+ // The readiness checklist covers this same backend in more detail, and knows
+ // the difference between "not installed" and "installed but not started".
+ // Rendering both put a green "LM Studio installed" pill directly above
+ // "Install LM Studio" — so wherever the checklist has an answer, it wins.
+ if (readiness[provider.id]?.kind === backend) return null;
const installed = localModels.installed?.[backend];
// `null` = status not fetched — never offer an install from an unknown state.
if (typeof installed !== 'boolean') return null;
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index d6e3d8a637..842fa56a27 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -658,6 +658,12 @@ export const visionLocalModelFilter = (id, provider, visionIdsByProvider = null)
* @param {{id?:string,endpoint?:string,name?:string}} provider
* @returns {'ollama'|'lmstudio'|null}
*/
+// Client mirror of `localBackendForProvider` in server/lib/localProviderRuntime.js
+// — keep in lockstep. The SERVER copy is authoritative and stricter: it parses
+// the endpoint as a URL and requires a loopback/bind-all host, so a peer
+// machine's daemon on the same port is not claimed as local. This one only
+// labels UI, so it stays a cheap regex; if it ever gates an action, take the
+// server's rules with it.
export const localBackendForProvider = (provider) => {
if (!provider) return null;
const id = String(provider.id || '').toLowerCase();
diff --git a/docs/API.md b/docs/API.md
index b4fc9b7f33..7ab5034629 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -67,7 +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/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/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/server/lib/README.md b/server/lib/README.md
index 758a208709..e5aee685e4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -132,7 +132,8 @@ 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`. |
+| `localProviderRuntime.js` | Which LOCAL daemon a provider talks to, and where — `LOCAL_RUNTIMES` (llama.cpp / Ollama / LM Studio / MTPLX: label, binary, canonical base URL read from `opencodeConfig.js` rather than re-typed, manage/docs links, model-download hint), `localBackendForProvider` + `localEndpointPort` + `isLocalInstanceHost` (moved here from `services/localModelHealing.js`, which re-exports them, so the healing path and the readiness checklist classify a provider identically — loopback/bind-all only, so a LAN/Tailscale peer on port 11434 is NOT claimed as a local daemon), `localRuntimeKind(provider)` (the `*Backed` markers first, then that classifier; `orcarouter` excluded as a remote API), `localRuntimeForProvider(provider)` → the row with the endpoint the provider ITSELF configures (`OPENCODE_CONFIG_CONTENT`'s `baseURL`, `ANTHROPIC_BASE_URL`, or `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` override the backend managers read, then the canonical default — plus `normalizeOpenAiBaseUrl`. Pure; the probing half is `services/providerReadiness.js`. |
+| `openAiModelsProbe.js` | `probeOpenAiModels(baseUrl, { timeoutMs })` → `{ reachable, models, error }` — the one `GET {base}/models` probe for the local OpenAI-compatible daemons, shared by `services/providerReadiness.js` and `services/llamaServerManager.js`. Distinguishes unreachable from reachable-but-unlistable (`models: null`) from up-with-nothing-loaded (`[]`), names the real transport failure via `describeFetchError` (undici reports every one as a bare `fetch failed`), and cancels an unread body on a non-OK response. Consolidated after the two copies drifted — one passed its timeout as a `timeout` key inside the fetch init object, where it is not an option, silently running a 500ms poll loop on the 15s default. |
| `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `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 2237c66bb8..10781f2f10 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -150,6 +150,7 @@ export * from './quotaReset.js';
export * from './quotaWindows.js';
export * from './opencodeConfig.js';
export * from './localProviderRuntime.js';
+export * from './openAiModelsProbe.js';
// `runners.js` re-defines `isFlux2`/`isZImage`/`isErnie` that also live in
// mediaModels.js — namespace it so the barrel surface is unambiguous.
export * as runners from './runners.js';
diff --git a/server/lib/localProviderRuntime.js b/server/lib/localProviderRuntime.js
index 45814b4cfd..259a18d020 100644
--- a/server/lib/localProviderRuntime.js
+++ b/server/lib/localProviderRuntime.js
@@ -15,17 +15,84 @@
* Kept side-effect-free so both the readiness service and its tests can reason
* about the mapping without a daemon on the host.
*
+ * `localBackendForProvider` (and the loopback-host rules under it) lived in
+ * `services/localModelHealing.js` until this module existed; it moved here so
+ * the healing path and the readiness path classify a provider identically, and
+ * `localModelHealing.js` re-exports it for its existing callers.
+ *
* Endpoint resolution deliberately prefers the provider's OWN configuration
- * over the canonical default: a user who moved llama-server to port 8090 edited
+ * over any 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';
+import { opencodeLocalBaseUrl } from './opencodeConfig.js';
+
+// Default OpenAI-compatible ports for the two local backends PortOS manages. An
+// endpoint-only provider (no id/name) pointed at one of these on the local
+// instance maps to that backend.
+const BACKEND_DEFAULT_PORT = { 11434: 'ollama', 1234: 'lmstudio' };
+
+/**
+ * True when a hostname names the SAME local instance the backend manager runs
+ * on — any loopback (`127.0.0.0/8`, `::1`), `localhost`, or the unspecified /
+ * bind-all address (`0.0.0.0`, `::`, which a manager bound to all interfaces
+ * reports while a provider reaches it as localhost). These all canonicalize to
+ * one token so spelling differences don't block healing. Deliberately NOT
+ * link-local / LAN / Tailscale hosts — a peer on another box is a DIFFERENT
+ * instance whose installed models we must not heal against, and whose daemon
+ * PortOS must not offer to install here.
+ */
+export function isLocalInstanceHost(hostname) {
+ const h = String(hostname || '').toLowerCase().replace(/^\[|\]$/g, ''); // strip IPv6 brackets
+ return h === 'localhost' || h === '0.0.0.0' || h === '::' || h === '::1' ||
+ /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
+}
+
+/**
+ * The port of a provider endpoint when it points at THIS machine's local
+ * instance (any loopback / bind-all host spelling); null otherwise — so a
+ * LAN/Tailscale peer on the same port is NOT mistaken for a local backend.
+ */
+export function localEndpointPort(endpoint) {
+ const cleaned = String(endpoint || '').replace(/\/v1\/?$/, '').replace(/\/+$/, '');
+ try {
+ const u = new URL(cleaned);
+ if (!isLocalInstanceHost(u.hostname)) return null;
+ return u.port || (u.protocol === 'https:' ? '443' : '80');
+ } catch { return null; }
+}
+
+// MIRROR of `isOllamaProvider` in services/ollamaManager.js — keep in lockstep.
+// Inlined so this module stays free of the manager's module graph.
+const isOllamaShape = (provider) =>
+ provider?.id === 'ollama' ||
+ /ollama/i.test(provider?.name || '') ||
+ /(^|[/:])(?:localhost|127\.0\.0\.1|\[::1\]):11434\b/i.test(String(provider?.endpoint || ''));
+
+/**
+ * Which local backend (if any) a provider maps to. Matches by id/name first
+ * (`ollama` / `lmstudio`), then by an endpoint pointing at the backend's default
+ * port on THIS machine's local instance.
+ * @returns {'ollama'|'lmstudio'|null}
+ */
+export function localBackendForProvider(provider) {
+ if (isOllamaShape(provider)) return 'ollama';
+ if (provider?.id === 'lmstudio' || /lm[\s-]?studio/i.test(provider?.name || '')) return 'lmstudio';
+ const port = localEndpointPort(provider?.endpoint);
+ return port ? (BACKEND_DEFAULT_PORT[port] || null) : null;
+}
/**
* One row per local runtime PortOS knows how to check for.
*
+ * `defaultBaseUrl` is read from `opencodeConfig.js`'s provider table rather than
+ * re-typed: that table is what a spawned OpenCode actually talks to when the
+ * provider stores no config of its own, so a second copy here would eventually
+ * probe a port nothing is on and call a working setup broken. LM Studio has no
+ * row there (nothing spawns OpenCode against it), so it carries its own.
+ *
* `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.
@@ -37,7 +104,7 @@ export const LOCAL_RUNTIMES = Object.freeze({
// 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',
+ defaultBaseUrl: opencodeLocalBaseUrl('llama'),
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
@@ -49,7 +116,7 @@ export const LOCAL_RUNTIMES = Object.freeze({
id: 'ollama',
label: 'Ollama',
command: 'ollama',
- defaultBaseUrl: 'http://localhost:11434/v1',
+ defaultBaseUrl: opencodeLocalBaseUrl('ollama'),
manageUrl: '/settings/local-llm',
docsUrl: 'https://ollama.com/download',
modelsHint: 'Pull a model from Settings → Local LLM before an agent can use this provider.',
@@ -69,21 +136,39 @@ export const LOCAL_RUNTIMES = Object.freeze({
// 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',
+ defaultBaseUrl: opencodeLocalBaseUrl('mtplx'),
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. */
+/**
+ * Normalize a base URL to the `/v1` root an OpenAI-compatible probe needs.
+ * A scheme is added when missing, because `OLLAMA_HOST` is conventionally a
+ * bare `host:port` (mirroring `ollamaManager`'s own normalization).
+ */
export function normalizeOpenAiBaseUrl(url) {
if (typeof url !== 'string') return null;
- const trimmed = url.trim().replace(/\/+$/, '');
+ let trimmed = url.trim().replace(/\/+$/, '');
if (trimmed === '') return null;
+ if (!/^https?:\/\//i.test(trimmed)) trimmed = `http://${trimmed}`;
return /\/v\d+$/.test(trimmed) ? trimmed : `${trimmed}/v1`;
}
+/**
+ * The base URL the rest of PortOS talks to this backend on, when the provider
+ * itself names none. The backend managers resolve their own base URL from these
+ * env vars (`ollamaManager.js`, `lmStudioManager.js`); reading them here keeps a
+ * relocated daemon from showing up as "not responding — install it" on the card
+ * while every other PortOS feature reaches it fine.
+ */
+function envBaseUrl(kind) {
+ if (kind === 'ollama') return process.env.OLLAMA_URL || process.env.OLLAMA_HOST || null;
+ if (kind === 'lmstudio') return process.env.LM_STUDIO_URL || null;
+ return null;
+}
+
/** The `baseURL` an OpenCode provider config declares for `namespace`, if any. */
function opencodeConfiguredBaseUrl(provider, namespace) {
const stored = provider?.envVars?.OPENCODE_CONFIG_CONTENT;
@@ -105,29 +190,19 @@ function opencodeConfiguredBaseUrl(provider, namespace) {
* 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.
+ * keys on. `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;
-
+ // Marker-based, NOT command-based: this also resolves `claude-ollama`, which
+ // carries `ollamaBacked` without being an OpenCode provider.
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;
+ return localBackendForProvider(provider);
}
/**
@@ -148,15 +223,9 @@ export function localRuntimeForProvider(provider) {
const endpoint = normalizeOpenAiBaseUrl(configured)
|| normalizeOpenAiBaseUrl(provider?.endpoint)
+ || normalizeOpenAiBaseUrl(envBaseUrl(kind))
|| runtime.defaultBaseUrl;
- return {
- kind: runtime.id,
- label: runtime.label,
- command: runtime.command,
- endpoint,
- manageUrl: runtime.manageUrl,
- docsUrl: runtime.docsUrl,
- modelsHint: runtime.modelsHint,
- };
+ const { id, ...row } = runtime;
+ return { ...row, kind: id, endpoint };
}
diff --git a/server/lib/localProviderRuntime.test.js b/server/lib/localProviderRuntime.test.js
index 2cdea89c39..2d703fd247 100644
--- a/server/lib/localProviderRuntime.test.js
+++ b/server/lib/localProviderRuntime.test.js
@@ -1,10 +1,16 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi, afterEach } from 'vitest';
import {
LOCAL_RUNTIMES,
+ localBackendForProvider,
localRuntimeForProvider,
localRuntimeKind,
normalizeOpenAiBaseUrl,
} from './localProviderRuntime.js';
+import { opencodeLocalBaseUrl } from './opencodeConfig.js';
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+});
const opencodeConfig = (namespace, baseURL) => JSON.stringify({
permission: 'allow',
@@ -45,6 +51,17 @@ describe('localRuntimeKind', () => {
expect(localRuntimeKind({ type: 'api', id: 'x', name: 'LM Studio local' })).toBe('lmstudio');
});
+ it('does NOT claim a peer machine daemon as a local runtime', () => {
+ // A provider pointed at another box on the LAN/tailnet used to match on the
+ // bare port, so the card offered to install Ollama HERE for a daemon that
+ // lives — and may simply be switched off — over there.
+ expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://192.0.2.10:11434/v1' })).toBeNull();
+ expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://192.0.2.10:1234/v1' })).toBeNull();
+ // Every loopback / bind-all spelling still resolves.
+ expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://0.0.0.0:1234' })).toBe('lmstudio');
+ expect(localRuntimeKind({ type: 'api', id: 'x', endpoint: 'http://[::1]:1234/v1' })).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();
@@ -107,4 +124,51 @@ describe('localRuntimeForProvider', () => {
it('returns null for providers with no local dependency', () => {
expect(localRuntimeForProvider({ command: 'claude', type: 'cli' })).toBeNull();
});
+
+ it('takes the canonical default from the OpenCode provider table, not a second copy', () => {
+ // These are the base URLs a spawned OpenCode actually talks to; probing a
+ // hand-typed duplicate would eventually check a port nothing is on.
+ expect(LOCAL_RUNTIMES.llama.defaultBaseUrl).toBe(opencodeLocalBaseUrl('llama'));
+ expect(LOCAL_RUNTIMES.ollama.defaultBaseUrl).toBe(opencodeLocalBaseUrl('ollama'));
+ expect(LOCAL_RUNTIMES.mtplx.defaultBaseUrl).toBe(opencodeLocalBaseUrl('mtplx'));
+ });
+
+ it('honors the env override the backend managers themselves read', () => {
+ // A user who relocated Ollama via OLLAMA_HOST reaches it fine everywhere
+ // else in PortOS; the card must not answer "not responding — install it".
+ vi.stubEnv('OLLAMA_HOST', 'localhost:11500');
+ const runtime = localRuntimeForProvider({ command: 'opencode', ollamaBacked: true, envVars: {} });
+ // Bare `host:port` is Ollama's own convention — the scheme is added here.
+ expect(runtime.endpoint).toBe('http://localhost:11500/v1');
+ });
+
+ it('lets the provider config win over the env override', () => {
+ vi.stubEnv('OLLAMA_HOST', 'localhost:11500');
+ const runtime = localRuntimeForProvider({
+ command: 'opencode',
+ ollamaBacked: true,
+ envVars: { OPENCODE_CONFIG_CONTENT: opencodeConfig('ollama', 'http://localhost:11600/v1') },
+ });
+ expect(runtime.endpoint).toBe('http://localhost:11600/v1');
+ });
+});
+
+describe('localBackendForProvider', () => {
+ // Moved here from services/localModelHealing.js, which now re-exports it —
+ // these cases pin the behavior its healing path depends on.
+ it('matches by id, name, and local endpoint port', () => {
+ expect(localBackendForProvider({ id: 'ollama' })).toBe('ollama');
+ expect(localBackendForProvider({ name: 'My Ollama' })).toBe('ollama');
+ expect(localBackendForProvider({ endpoint: 'http://localhost:11434/v1' })).toBe('ollama');
+ expect(localBackendForProvider({ id: 'lmstudio' })).toBe('lmstudio');
+ expect(localBackendForProvider({ name: 'lm-studio' })).toBe('lmstudio');
+ expect(localBackendForProvider({ endpoint: 'http://127.0.0.1:1234/v1' })).toBe('lmstudio');
+ });
+
+ it('declines a remote host, an unknown port, and junk', () => {
+ expect(localBackendForProvider({ endpoint: 'http://192.0.2.10:11434/v1' })).toBeNull();
+ expect(localBackendForProvider({ endpoint: 'http://localhost:9999' })).toBeNull();
+ expect(localBackendForProvider({ id: 'anthropic', endpoint: 'https://api.anthropic.com/v1' })).toBeNull();
+ expect(localBackendForProvider(null)).toBeNull();
+ });
});
diff --git a/server/lib/openAiModelsProbe.js b/server/lib/openAiModelsProbe.js
new file mode 100644
index 0000000000..10f25639ba
--- /dev/null
+++ b/server/lib/openAiModelsProbe.js
@@ -0,0 +1,70 @@
+/**
+ * One `GET {base}/models` reachability+listing probe for the local
+ * OpenAI-compatible daemons (llama.cpp, Ollama, LM Studio, MTPLX).
+ *
+ * This existed three times in `server/` before it existed once here, and the
+ * copies had already drifted: `llamaServerManager`'s passed its timeout as a
+ * `timeout` key INSIDE the fetch init object, where it is not an option, so
+ * that probe silently ran on the 15s default inside a 500ms startup poll loop.
+ * A single implementation makes the timeout, the URL normalization, and the
+ * "reachable but unlistable" distinction one decision instead of N.
+ *
+ * Answers three states a caller must be able to tell apart:
+ * - `reachable: false` — nothing is serving here (with `error` naming why)
+ * - `reachable: true, models: null`— it answered, but the listing was unreadable
+ * - `reachable: true, models: []` — it is up and genuinely serving nothing
+ */
+
+import { fetchWithTimeout } from './fetchWithTimeout.js';
+import { describeFetchError } from './fetchErrorChain.js';
+import { readResponseJson } from './readResponseJson.js';
+
+/**
+ * The one-token reason a probe failed, for a UI that has a line to spend on it.
+ * `describeFetchError` returns the whole cause chain (`fetch failed: ECONNREFUSED:
+ * connect ECONNREFUSED 127.0.0.1:8080`); the code alone is what tells the user
+ * "nothing is listening" from "the host is wedged", and the two timeout
+ * spellings mean the same thing to them.
+ */
+function shortFailureReason(err) {
+ // `describeFetchError` walks `.code`/`.message` only, and an abort carries its
+ // identity in `.name` (`AbortError`) — which is exactly the timeout case.
+ const chain = `${err?.name || ''}: ${describeFetchError(err)}`;
+ if (/AbortError|TimeoutError|ETIMEDOUT|UND_ERR_(?:CONNECT_)?TIMEOUT/.test(chain)) return 'timed out';
+ const code = chain.match(/\b(E[A-Z]{3,}|UND_ERR_[A-Z_]+)\b/);
+ return code ? code[1] : chain.slice(0, 120);
+}
+
+/**
+ * @param {string} baseUrl - an OpenAI-compatible base (…/v1); trailing slashes tolerated
+ * @param {{timeoutMs?: number}} [opts]
+ * @returns {Promise<{reachable:boolean, models:string[]|null, error:string|null}>}
+ */
+export async function probeOpenAiModels(baseUrl, { timeoutMs = 2_000 } = {}) {
+ const url = `${String(baseUrl || '').replace(/\/+$/, '')}/models`;
+ const res = await fetchWithTimeout(url, { method: 'GET' }, timeoutMs)
+ // undici reports every network failure as a bare `TypeError: fetch failed`;
+ // the real reason (ECONNREFUSED vs. ETIMEDOUT — "nothing is listening" vs.
+ // "the host is wedged", two different fixes for the user) lives in the
+ // cause chain.
+ .catch((err) => ({ transportError: shortFailureReason(err) }));
+
+ if (res.transportError) return { reachable: false, models: null, error: res.transportError };
+ if (!res.ok) {
+ // Undici holds the socket until an unread body is consumed; an endpoint
+ // answering 404 on every poll would otherwise leak one each time.
+ await res.body?.cancel().catch(() => {});
+ return { reachable: false, models: null, error: `HTTP ${res.status}` };
+ }
+
+ const body = await readResponseJson(res, { fallback: null, emptyValue: 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' };
+ return {
+ reachable: true,
+ models: rows
+ .map((row) => (typeof row === 'string' ? row : row?.id || row?.name))
+ .filter((id) => typeof id === 'string' && id !== ''),
+ error: null,
+ };
+}
diff --git a/server/lib/openAiModelsProbe.test.js b/server/lib/openAiModelsProbe.test.js
new file mode 100644
index 0000000000..24f02db984
--- /dev/null
+++ b/server/lib/openAiModelsProbe.test.js
@@ -0,0 +1,78 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import * as fetchWithTimeoutModule from './fetchWithTimeout.js';
+import { probeOpenAiModels } from './openAiModelsProbe.js';
+
+const jsonResponse = (body) => ({ ok: true, status: 200, text: async () => JSON.stringify(body) });
+
+const mockFetch = (impl) => vi.spyOn(fetchWithTimeoutModule, 'fetchWithTimeout').mockImplementation(impl);
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('probeOpenAiModels', () => {
+ it('asks {base}/models with the caller bound, tolerating a trailing slash', async () => {
+ const fetchMock = mockFetch(async () => jsonResponse({ data: [] }));
+
+ await probeOpenAiModels('http://127.0.0.1:8080/v1/', { timeoutMs: 1234 });
+
+ // The bound is fetchWithTimeout's THIRD argument — passing it inside the
+ // init object (the bug this module consolidated away) silently kept the 15s
+ // default.
+ expect(fetchMock).toHaveBeenCalledWith('http://127.0.0.1:8080/v1/models', { method: 'GET' }, 1234);
+ });
+
+ it('reads both the OpenAI `data` shape and a bare `models` array', async () => {
+ mockFetch(async () => jsonResponse({ data: [{ id: 'dflash' }, { name: 'qwen' }, 'bare-string', { id: '' }] }));
+ await expect(probeOpenAiModels('http://x/v1')).resolves.toMatchObject({
+ reachable: true,
+ models: ['dflash', 'qwen', 'bare-string'],
+ error: null,
+ });
+
+ mockFetch(async () => jsonResponse({ models: ['a'] }));
+ await expect(probeOpenAiModels('http://x/v1')).resolves.toMatchObject({ reachable: true, models: ['a'] });
+ });
+
+ it('tells a server with nothing loaded from one whose listing is unreadable', async () => {
+ mockFetch(async () => jsonResponse({ data: [] }));
+ // Up and serving nothing — an actionable "load a model", not a connection problem.
+ await expect(probeOpenAiModels('http://x/v1')).resolves.toMatchObject({ reachable: true, models: [] });
+
+ mockFetch(async () => ({ ok: true, status: 200, text: async () => 'not json at all' }));
+ const unreadable = await probeOpenAiModels('http://x/v1');
+ expect(unreadable).toMatchObject({ reachable: true, models: null });
+ expect(unreadable.error).toMatch(/not readable/i);
+ });
+
+ it('names the real transport failure instead of undici bare "fetch failed"', async () => {
+ const err = new TypeError('fetch failed');
+ err.cause = Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:8080'), { code: 'ECONNREFUSED' });
+ mockFetch(async () => { throw err; });
+
+ await expect(probeOpenAiModels('http://127.0.0.1:8080/v1')).resolves.toEqual({
+ reachable: false,
+ models: null,
+ error: 'ECONNREFUSED',
+ });
+ });
+
+ it('collapses the timeout spellings to one phrase', async () => {
+ mockFetch(async () => { throw Object.assign(new Error('The operation was aborted'), { name: 'AbortError' }); });
+ await expect(probeOpenAiModels('http://x/v1')).resolves.toMatchObject({ reachable: false, error: 'timed out' });
+ });
+
+ it('reports a non-OK response as unreachable and releases its body', async () => {
+ const cancel = vi.fn().mockResolvedValue(undefined);
+ mockFetch(async () => ({ ok: false, status: 404, body: { cancel } }));
+
+ await expect(probeOpenAiModels('http://x/v1')).resolves.toEqual({
+ reachable: false,
+ models: null,
+ error: 'HTTP 404',
+ });
+ // Undici holds the socket until an unread body is consumed; this path runs
+ // on a poll loop.
+ expect(cancel).toHaveBeenCalled();
+ });
+});
diff --git a/server/lib/opencodeConfig.js b/server/lib/opencodeConfig.js
index 7ef07c059e..2c967c6a07 100644
--- a/server/lib/opencodeConfig.js
+++ b/server/lib/opencodeConfig.js
@@ -48,6 +48,17 @@ const OPENCODE_LOCAL_BASE_PROVIDERS = {
},
};
+/**
+ * The canonical base URL PortOS declares for one local OpenCode provider entry
+ * — what a spawned OpenCode talks to when the provider stores no config of its
+ * own. Read by `lib/localProviderRuntime.js` so the readiness probe and the
+ * spawn agree on the endpoint instead of keeping two copies of these ports.
+ * @param {'ollama'|'mtplx'|'llama'|'orcarouter'} providerKey
+ * @returns {string|null}
+ */
+export const opencodeLocalBaseUrl = (providerKey) =>
+ OPENCODE_LOCAL_BASE_PROVIDERS[providerKey]?.options?.baseURL || null;
+
const localProviderBase = (providerKey) => {
if (!Object.hasOwn(OPENCODE_LOCAL_BASE_PROVIDERS, providerKey)) {
throw new Error(`Unsupported OpenCode local provider '${providerKey}'`);
diff --git a/server/routes/localLlm.js b/server/routes/localLlm.js
index f6d58542cb..1fe3440fc9 100644
--- a/server/routes/localLlm.js
+++ b/server/routes/localLlm.js
@@ -29,6 +29,7 @@ import {
localLlmLlamaServerStartSchema
} from '../lib/validation.js'
import { getLlamaServerStatus, startLlamaServer, stopLlamaServer, installLlamaServer } from '../services/llamaServerManager.js'
+import { resetProviderReadinessCache } from '../services/providerReadiness.js'
import { getCatalog, searchCatalog, isBackend } from '../lib/localLlmCatalog.js'
import { isAppleSilicon } from '../lib/platform.js'
import { searchHuggingFaceModels, enrichCatalogWithVariants, applyMeasuredFit } from '../services/huggingFaceCatalog.js'
@@ -468,22 +469,33 @@ router.get('/llama-server/status', asyncHandler(async (_req, res) => {
res.json(await getLlamaServerStatus())
}))
+// Each of the three actions below changes exactly what the provider-readiness
+// probes remember — is the binary there, is something answering — so each drops
+// those caches. Without it the Providers page keeps reporting "llama.cpp setup
+// incomplete" for up to a cache TTL after the user fixed it right here.
+
// POST /api/local-llm/llama-server/start — launch llama-server
router.post('/llama-server/start', asyncHandler(async (req, res) => {
const options = validateRequest(localLlmLlamaServerStartSchema, req.body)
- res.json(await startLlamaServer(options))
+ const result = await startLlamaServer(options)
+ resetProviderReadinessCache()
+ res.json(result)
}))
// POST /api/local-llm/llama-server/stop — stop managed llama-server
router.post('/llama-server/stop', asyncHandler(async (_req, res) => {
- res.json(await stopLlamaServer())
+ const result = await stopLlamaServer()
+ resetProviderReadinessCache()
+ res.json(result)
}))
// POST /api/local-llm/llama-server/install — install llama.cpp via Homebrew
router.post('/llama-server/install', asyncHandler(async (req, res) => {
const io = req.app.get('io')
const onProgress = (data) => io?.emit('localLlm:progress', data)
- res.json(await installLlamaServer({ onProgress }))
+ const result = await installLlamaServer({ onProgress })
+ resetProviderReadinessCache()
+ res.json(result)
}))
export default router
diff --git a/server/routes/providers.readiness.test.js b/server/routes/providers.readiness.test.js
index eb5a61aa14..80356b6f7e 100644
--- a/server/routes/providers.readiness.test.js
+++ b/server/routes/providers.readiness.test.js
@@ -5,17 +5,6 @@ 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 —
diff --git a/server/services/llamaServerManager.js b/server/services/llamaServerManager.js
index 4fbdbe3547..2d67b742fa 100644
--- a/server/services/llamaServerManager.js
+++ b/server/services/llamaServerManager.js
@@ -6,13 +6,13 @@
*/
import { stat } from 'fs/promises';
-import { isAbsolute, resolve } from 'path';
+import { resolve } from 'path';
import { spawn } from '../lib/childProcess.js';
import { commandExists } from '../lib/commandExists.js';
import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
import { killProcessTree } from '../lib/bufferedSpawn.js';
-import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
-import { sleep } from '../lib/fileUtils.js';
+import { expandHome, sleep } from '../lib/fileUtils.js';
+import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
import { ServerError } from '../lib/errorHandler.js';
const IS_WIN = process.platform === 'win32';
@@ -37,20 +37,13 @@ function appendLog(line) {
/**
* Probes whether an OpenAI-compatible endpoint responds at the given host/port.
+ * Shares one implementation with the readiness checklist — the timeout bug this
+ * used to carry (a `timeout` key inside the fetch init object, which is not a
+ * fetch option, leaving a 500ms poll loop on the 15s default) came from having
+ * two copies of the same probe.
*/
-async function probeEndpoint(endpoint) {
- try {
- const url = `${endpoint.replace(/\/+$/, '')}/models`;
- // 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;
- }
-}
+const probeEndpoint = async (endpoint) =>
+ (await probeOpenAiModels(endpoint, { timeoutMs: PROBE_TIMEOUT_MS })).reachable;
/**
* Resolves the `llama-server` executable on the child-process PATH.
@@ -82,11 +75,12 @@ function resolveLlamaServerBinary() {
* 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.
+ * inherits, and `~` is expanded here AND in the argv below — `spawn` does no
+ * shell expansion, so a tilde path must be expanded once for both or the check
+ * and the launch disagree about which file they mean.
*/
async function assertModelFileExists(label, modelPath) {
- const resolved = isAbsolute(modelPath) ? modelPath : resolve(process.cwd(), modelPath);
- const stats = await stat(resolved).catch(() => null);
+ const stats = await stat(resolve(expandHome(modelPath))).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.`,
@@ -159,11 +153,18 @@ export async function startLlamaServer(options = {}) {
throw new ServerError(`Port ${port} is already in use by an active server at ${endpoint}`, { status: 409 });
}
- const args = ['-m', model.trim()];
+ // Validate the weights before building the launch line, and hand `spawn` the
+ // EXPANDED paths: it performs no shell expansion, so a `~/models/…` argv entry
+ // would reach llama.cpp as a literal directory named `~`.
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());
+ const draftPath = typeof draftModel === 'string' && draftModel.trim()
+ ? draftModel.trim()
+ : null;
+ if (draftPath) await assertModelFileExists('The drafter model', draftPath);
+
+ const args = ['-m', expandHome(model.trim())];
+ if (draftPath) {
+ args.push('--draft-model', expandHome(draftPath));
if (specType) args.push('--spec-type', specType.trim());
}
if (port) args.push('--port', String(port));
diff --git a/server/services/localModelHealing.js b/server/services/localModelHealing.js
index b05359b149..fb6a6013e2 100644
--- a/server/services/localModelHealing.js
+++ b/server/services/localModelHealing.js
@@ -20,12 +20,12 @@ import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifica
import * as ollamaManager from './ollamaManager.js';
import * as lmStudioManager from './lmStudioManager.js';
import { recommendEditorialModel, isEmbeddingModel } from '../lib/localModelHeuristics.js';
+// Moved to server/lib so the readiness checklist classifies a provider exactly
+// as the healing path does; re-exported below for this module's callers.
+import { isLocalInstanceHost, localBackendForProvider } from '../lib/localProviderRuntime.js';
import { getMeasuredFits } from './localModelAssessmentStore.js';
-// Default OpenAI-compatible ports for the two local backends. An endpoint-only
-// provider (no id/name) pointed at one of these on the local instance maps to
-// that backend.
-const BACKEND_DEFAULT_PORT = { '11434': 'ollama', '1234': 'lmstudio' };
+export { localBackendForProvider };
// A backend "model not found" — Ollama answers 404 `model "x" not found, try
// pulling it first`; LM Studio answers `model "x" not found`/`unknown model`.
@@ -35,32 +35,6 @@ const BACKEND_DEFAULT_PORT = { '11434': 'ollama', '1234': 'lmstudio' };
const MODEL_NOT_FOUND_RE = /model\s*['"]?[\w./:-]*['"]?\s*(?:not found|does not exist|is not (?:found|installed|available))|not found, try pulling|unknown model|no such model/i;
const NO_MODELS_LOADED_RE = /no models loaded/i;
-/**
- * Which local backend (if any) a provider maps to. Matches by id/name first
- * (`ollama` / `lmstudio`), then by an endpoint pointing at the backend's default
- * port on THIS machine's local instance — using the same local-host logic as
- * the endpoint guard, so every loopback / bind-all spelling resolves.
- * @returns {'ollama'|'lmstudio'|null}
- */
-export function localBackendForProvider(provider) {
- if (ollamaManager.isOllamaProvider(provider)) return 'ollama';
- if (provider?.id === 'lmstudio' || /lm[\s-]?studio/i.test(provider?.name || '')) return 'lmstudio';
- const port = localEndpointPort(provider?.endpoint);
- return port ? (BACKEND_DEFAULT_PORT[port] || null) : null;
-}
-
-// The port of a provider endpoint when it points at THIS machine's local
-// instance (any loopback / bind-all host spelling); null otherwise — so a
-// LAN/Tailscale peer on the same port is NOT mistaken for a local backend.
-function localEndpointPort(endpoint) {
- const cleaned = String(endpoint || '').replace(/\/v1\/?$/, '').replace(/\/+$/, '');
- try {
- const u = new URL(cleaned);
- if (!isLocalInstanceHost(u.hostname)) return null;
- return u.port || (u.protocol === 'https:' ? '443' : '80');
- } catch { return null; }
-}
-
/**
* True when an error string is a backend "configured model isn't installed"
* failure (vs. "no models loaded", which is a separate recovery).
@@ -128,19 +102,6 @@ function managerOrigin(backend) {
return normalizeOrigin(base);
}
-// True when a hostname names the SAME local instance the backend manager runs
-// on — any loopback (`127.0.0.0/8`, `::1`), `localhost`, or the unspecified /
-// bind-all address (`0.0.0.0`, `::`, which a manager bound to all interfaces
-// reports while a provider reaches it as localhost). These all canonicalize to
-// one token so spelling differences don't block healing. Deliberately NOT
-// link-local / LAN / Tailscale hosts — a peer on another box is a DIFFERENT
-// instance whose installed models we must not heal against.
-function isLocalInstanceHost(hostname) {
- const h = hostname.toLowerCase().replace(/^\[|\]$/g, ''); // strip IPv6 brackets
- return h === 'localhost' || h === '0.0.0.0' || h === '::' || h === '::1' ||
- /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h);
-}
-
function normalizeOrigin(url) {
const cleaned = String(url || '').replace(/\/v1\/?$/, '').replace(/\/+$/, '');
try {
diff --git a/server/services/providerReadiness.js b/server/services/providerReadiness.js
index b00e681fcb..274bbf492d 100644
--- a/server/services/providerReadiness.js
+++ b/server/services/providerReadiness.js
@@ -30,10 +30,11 @@
* to poll from a settings page under the no-cold-bootstrap policy in CLAUDE.md.
*/
-import { LOCAL_RUNTIMES, localRuntimeForProvider } from '../lib/localProviderRuntime.js';
+import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';
import { isConfiguredDefaultModel } from '../lib/providerModels.js';
-import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+import { probeOpenAiModels } from '../lib/openAiModelsProbe.js';
import { findCommandOnPath } from '../lib/processEnv.js';
+import { isAppInstalled as isLmStudioAppInstalled } from './lmStudioManager.js';
/**
* Loopback daemons answer (or refuse the connection) in single-digit
@@ -44,45 +45,67 @@ import { findCommandOnPath } from '../lib/processEnv.js';
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.
+ * Sized just under the Providers page's 20s poll so consecutive polls each get
+ * a fresh answer (a daemon the user just started must show up on the next tick,
+ * not two ticks later) while a reload landing on top of a poll still reuses it.
+ * Within ONE request the promise cache below is what collapses providers that
+ * share an endpoint.
*/
-const PROBE_TTL_MS = 5_000;
+const PROBE_TTL_MS = 15_000;
-// endpoint → { at, result }
+/**
+ * Same 60s TTL and reasoning as `providerRuntimeInstaller.js`'s status cache:
+ * availability changes only when someone installs or removes a binary, and
+ * `findCommandOnPath` is a SYNCHRONOUS PATH walk (a stat per directory), so an
+ * uncached miss blocks the event loop on every 20s poll from every open tab.
+ */
+const BINARY_TTL_MS = 60_000;
+
+// endpoint → { at, promise } — the PROMISE, not the settled value, so N
+// providers sharing one endpoint in the same batch share one socket instead of
+// all missing a not-yet-written cache entry at once.
const probeCache = new Map();
+// command → { at, path }
+const binaryCache = new Map();
/**
- * Ask an OpenAI-compatible endpoint what it serves.
+ * Ask an OpenAI-compatible endpoint what it serves. `llamaServerManager` runs the
+ * same probe against the same daemons, so the request shape lives in one lib.
* @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 };
-}
+const probeEndpoint = (endpoint) => probeOpenAiModels(endpoint, { timeoutMs: PROBE_TIMEOUT_MS });
-/** Cached endpoint probe — see PROBE_TTL_MS. */
-async function probeEndpointCached(endpoint, probe) {
+/** TTL-cached endpoint probe, shared across requests — see PROBE_TTL_MS. */
+function probeEndpointCached(endpoint) {
+ const now = Date.now();
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;
+ if (cached && now - cached.at < PROBE_TTL_MS) return cached.promise;
+ // Sweep while we are here: entries are keyed by endpoint, and an edited or
+ // deleted provider would otherwise leave its old endpoint behind forever.
+ for (const [key, entry] of probeCache) {
+ if (now - entry.at >= PROBE_TTL_MS) probeCache.delete(key);
+ }
+ // Written BEFORE the await so concurrent callers join this probe. A rejected
+ // probe would poison the entry for its TTL, so drop it on failure —
+ // `probeEndpoint` resolves for every expected failure, making this the
+ // unexpected-throw path only.
+ const promise = probeEndpoint(endpoint).catch((err) => {
+ probeCache.delete(endpoint);
+ throw err;
+ });
+ probeCache.set(endpoint, { at: now, promise });
+ return promise;
+}
+
+/** TTL-cached PATH lookup for the handful of daemon binaries — see BINARY_TTL_MS. */
+function findCommandCached(command) {
+ const cached = binaryCache.get(command);
+ if (cached && Date.now() - cached.at < BINARY_TTL_MS) return cached.path;
+ const path = findCommandOnPath(command);
+ binaryCache.set(command, { at: Date.now(), path });
+ return path;
}
/**
@@ -98,6 +121,71 @@ function servedModelId(provider, kind) {
return trimmed.startsWith(`${kind}/`) ? trimmed.slice(kind.length + 1) : trimmed;
}
+/** The `runtime` check — is the daemon's software here at all? */
+function runtimeCheck(runtime, { onPath, appInstalled, installed, reachable }) {
+ 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.`;
+ const fixHint = installed ? null
+ : 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 }) {
+ if (result.reachable) {
+ return {
+ id: 'server',
+ label: `${runtime.label} server responding`,
+ ok: true,
+ detail: `${runtime.endpoint} answered.`,
+ fixHint: null,
+ };
+ }
+ const start = `Start ${runtime.label}${runtime.manageUrl ? ' from Settings → Local LLM' : ''}.`;
+ 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}`,
+ };
+}
+
+/**
+ * The `model` check — does the running daemon serve what this provider asks
+ * for? This is the alias mismatch: `llama-server --alias dflash` against a
+ * provider pinned to `dspark` fails HERE rather than inside a dead agent run.
+ *
+ * `served` is null when the endpoint never answered (or answered unreadably),
+ * which says nothing about the model — reported as unknown, never as missing,
+ * so the user chases the check that IS actionable.
+ */
+function modelCheck(runtime, wanted, served) {
+ const label = `Model \`${wanted}\` available`;
+ if (!Array.isArray(served)) {
+ return { id: 'model', label, ok: null, detail: 'Cannot be checked until the server responds.', fixHint: null };
+ }
+ if (served.includes(wanted)) {
+ return { id: 'model', label, ok: true, detail: `${runtime.label} is serving \`${wanted}\`.`, fixHint: null };
+ }
+ const detail = 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` : ''}.`;
+ return {
+ id: 'model',
+ label,
+ ok: false,
+ detail,
+ fixHint: `${runtime.modelsHint} Then set this provider's default model to one the server reports.`,
+ };
+}
+
/**
* The requirements checklist for one provider, or `null` when the provider does
* not depend on a local daemon.
@@ -114,74 +202,30 @@ export async function getProviderReadiness(provider, deps = {}) {
const runtime = localRuntimeForProvider(provider);
if (!runtime) return null;
- const findCommand = deps.findCommand || findCommandOnPath;
+ const findCommand = deps.findCommand || findCommandCached;
+ const probe = deps.probe || probeEndpointCached;
- // 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);
+ const result = await probe(runtime.endpoint);
// 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}`,
- });
+ // LM Studio ships as a macOS app bundle whose `lms` shim the user opts into
+ // separately, so PATH alone says "not installed" for a perfectly installed
+ // copy. The Local LLM tab already counts the bundle (`localLlm.getStatus`);
+ // without the same signal here the card would render "LM Studio installed"
+ // and "install LM Studio" two lines apart, and send the user after the wrong
+ // fix — the real one is "start its server".
+ const appInstalled = runtime.kind === 'lmstudio' && (deps.isAppInstalled || isLmStudioAppInstalled)();
+ const installed = onPath || appInstalled || result.reachable;
- 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.`,
- });
- }
+ const checks = [
+ runtimeCheck(runtime, { onPath, appInstalled, installed, reachable: result.reachable }),
+ serverCheck(runtime, { installed, result }),
+ ];
+ const wanted = servedModelId(provider, runtime.kind);
+ // `probeEndpoint` returns `models: null` on every unreachable path, so this
+ // needs no second reachability test.
+ if (wanted) checks.push(modelCheck(runtime, wanted, result.models));
return {
kind: runtime.kind,
@@ -197,34 +241,47 @@ export async function getProviderReadiness(provider, deps = {}) {
}
/**
- * 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".
+ * Readiness for every ENABLED 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".
+ *
+ * Disabled providers are skipped: a stock install ships most of the local
+ * presets disabled, and probing daemons for providers the user switched off
+ * spends most of every poll on cards that would show the checklist for a
+ * provider they cannot run anyway.
*
* @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 list = (Array.isArray(providers) ? providers : []).filter((provider) => provider?.enabled !== false);
+ // One PATH scan per distinct binary and one probe per distinct endpoint for
+ // the whole batch — including when the caller injects its own probe, which
+ // would otherwise bypass the module-level caches that normally collapse them.
+ const findCommand = memoize(deps.findCommand || findCommandCached);
+ const probe = memoize(deps.probe || probeEndpointCached);
const entries = await Promise.all(list.map(async (provider) => {
- const readiness = await getProviderReadiness(provider, { ...deps, findCommand: memoFind });
+ const readiness = await getProviderReadiness(provider, { findCommand, probe });
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 };
+/** Per-batch single-argument memo (the returned promise is shared, not awaited). */
+function memoize(fn) {
+ const seen = new Map();
+ return (arg) => {
+ if (!seen.has(arg)) seen.set(arg, fn(arg));
+ return seen.get(arg);
+ };
+}
-/** Drops the endpoint probe cache (tests, and after an install/start action). */
+/**
+ * Drops the probe caches so the next read reflects a daemon that was just
+ * started, stopped, or installed — called by the llama-server lifecycle routes,
+ * which change exactly what these caches remember.
+ */
export function resetProviderReadinessCache() {
probeCache.clear();
+ binaryCache.clear();
}
diff --git a/server/services/providerReadiness.test.js b/server/services/providerReadiness.test.js
index bfca75f336..a9856fbd8c 100644
--- a/server/services/providerReadiness.test.js
+++ b/server/services/providerReadiness.test.js
@@ -141,6 +141,19 @@ describe('getProviderReadiness', () => {
expect(JSON.stringify(readiness)).not.toContain('/Users/someone');
});
+ it('counts an LM Studio app bundle as installed, so the card asks for a START not an install', async () => {
+ // The Local LLM tab already treats the macOS app bundle as installed. When
+ // this disagreed, one card rendered 'LM Studio installed' and 'Install LM
+ // Studio' two lines apart — and the install was the wrong fix.
+ const readiness = await getProviderReadiness(
+ { id: 'lmstudio', name: 'LM Studio', type: 'api', endpoint: 'http://localhost:1234/v1' },
+ { findCommand: () => null, isAppInstalled: () => true, probe: unreachable() },
+ );
+ expect(checkById(readiness, 'runtime').ok).toBe(true);
+ expect(checkById(readiness, 'server').ok).toBe(false);
+ expect(checkById(readiness, 'server').fixHint).toMatch(/Start LM Studio/);
+ });
+
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' },
@@ -167,12 +180,23 @@ describe('getProviderReadinessMap', () => {
},
);
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);
+ // Both llama providers point at the same daemon: one probe for the batch,
+ // not one per provider. A stock install ships several providers per
+ // endpoint, and this runs on a 20s poll.
+ expect(probed).toEqual(['http://127.0.0.1:8080/v1']);
expect(map['opencode-llama'].ready).toBe(true);
});
+ it('skips disabled providers rather than probing daemons for cards nobody can run', async () => {
+ const probed = [];
+ const map = await getProviderReadinessMap(
+ [llamaProvider({ enabled: false }), llamaProvider({ id: 'on', endpoint: 'http://127.0.0.1:9/v1', enabled: true })],
+ { findCommand: () => null, probe: async (endpoint) => { probed.push(endpoint); return { reachable: false, models: null, error: 'refused' }; } },
+ );
+ expect(Object.keys(map)).toEqual(['on']);
+ expect(probed).toEqual(['http://127.0.0.1:9/v1']);
+ });
+
it('tolerates junk input', async () => {
await expect(getProviderReadinessMap(null, { findCommand: () => null, probe: unreachable() })).resolves.toEqual({});
});