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

move the CLI install call to action onto each AI provider card

[._.]/ Adam Eivy1b4011731e09
diff --git a/client/src/components/providers/ProviderRuntimeStatus.jsx b/client/src/components/providers/ProviderRuntimeStatus.jsx
new file mode 100644
index 0000000000..e7e5ea9e87
--- /dev/null
+++ b/client/src/components/providers/ProviderRuntimeStatus.jsx
@@ -0,0 +1,72 @@
+/**
+ * Per-provider runtime install status + call to action.
+ *
+ * A CLI/TUI provider is dead weight until its binary is on PortOS's PATH, and
+ * an API provider fronted by a local app (LM Studio, Ollama) is dead until that
+ * app is installed. This is the small badge-sized widget every provider card
+ * renders for its runtime — replacing the full-width OpenCode-only install bar
+ * that used to sit at the top of the page, so the affordance lives next to the
+ * provider it belongs to and every installable runtime gets the same treatment.
+ *
+ * `runtime` is `{ id, label, installed, installable, blockedReason, docsUrl,
+ * manageUrl }` — an entry of the `runtimes` map from
+ * `GET /api/providers/runtimes` for a CLI provider, or the local-app shape the
+ * page derives from the local-LLM status. Renders nothing without one, so a
+ * command PortOS has no installer for (and a card drawn before the fetch
+ * resolves) shows no install UI at all.
+ *
+ * `manageUrl` means "PortOS installs this from another screen" — the Local LLM
+ * tab owns Ollama/LM Studio, service start-up included — so that case links
+ * there rather than duplicating the flow.
+ */
+
+import { Link } from 'react-router';
+import { CheckCircle2, Download, ExternalLink } from 'lucide-react';
+import Pill from '../ui/Pill';
+
+const ACTION_CLASS = 'inline-flex items-center gap-1 px-2 py-1 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 transition-colors';
+
+export default function ProviderRuntimeStatus({ runtime, onInstall, className = '' }) {
+ if (!runtime) return null;
+ const { label, command, installed, installable, blockedReason, docsUrl, manageUrl } = runtime;
+
+ if (installed) {
+ return (
+ <div className={`flex flex-wrap items-center gap-2 ${className}`}>
+ <Pill tone="success" size="xs" icon={CheckCircle2} title={command ? `PortOS can run \`${command}\`.` : undefined}>
+ {label} installed
+ </Pill>
+ </div>
+ );
+ }
+
+ return (
+ <div className={`flex flex-wrap items-center gap-2 text-xs ${className}`}>
+ <Pill tone="warning" size="xs">{label} not installed</Pill>
+ {installable ? (
+ <button
+ type="button"
+ onClick={() => onInstall?.(runtime)}
+ className={ACTION_CLASS}
+ title={`Install ${label} on this host`}
+ >
+ <Download size={12} />
+ Install {label}
+ </button>
+ ) : manageUrl ? (
+ <Link to={manageUrl} className={ACTION_CLASS} title={`Install ${label} from Settings → Local LLM`}>
+ <Download size={12} />
+ Install {label}
+ </Link>
+ ) : docsUrl && (
+ // PortOS can't run this install here — the vendor's own instructions are
+ // the only way forward, so offer them rather than a dead button.
+ <a href={docsUrl} target="_blank" rel="noreferrer" className={ACTION_CLASS}>
+ Install instructions
+ <ExternalLink size={11} />
+ </a>
+ )}
+ {!installable && blockedReason && <span className="text-gray-400">{blockedReason}</span>}
+ </div>
+ );
+}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index f7e84b6578..b1316ca1b5 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -169,7 +169,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useRecordMerge` | Duplicate Universe/Series merge flow: open → dry-run preview → resolve field conflicts → execute, with an `onMerged` refresh callback. Drives `<MergeModal>`. | Surfacing the merge-duplicates UI anywhere (Sharing → Duplicates, Universes page). Don't re-implement the preview/execute dance. |
| `useProviderModels` | AI providers + two-step provider→model selection. | Any UI that picks a provider + model. |
| `useReviewerModelOptions` | Selectable model ids per model-taking reviewer for `ReviewerPicker`'s Model column — local-LLM ids from `/api/local-llm/status`, codex/claude/antigravity tiers from `/api/providers` (claude's list also spans installed Ollama ids for an Ollama-backed CLI; agy's collapses to base ids since the row has its own Effort cell). Returns `{ optionsByReviewer, freeText, unavailable, loaded, reviewers }`. | Every surface that renders `ReviewerPicker` (Code Review Defaults, TaskAddForm, ScheduleTab, SlashDoRunDrawer) — the picker never fetches; pass this as its `modelOptions`. |
-| `useLocalModels` | Live installed Ollama/LM Studio model ids per backend + the server's editorial recommendation. | Model pickers that must show currently-installed local models (not just a provider's stale stored `models`). Fold in via `mergeModelLists` + `localBackendForProvider`. |
+| `useLocalModels` | Live installed Ollama/LM Studio model ids per backend + the server's editorial recommendation, plus `installed` per backend (`null` until fetched) — the app-level verdict that counts a macOS bundle with no CLI shim. | Model pickers that must show currently-installed local models (not just a provider's stale stored `models`). Fold in via `mergeModelLists` + `localBackendForProvider`. |
| `useVisionModelIds` | `{ idsByProvider, loaded }` — vision-capable model ids the server reports (Ollama `/api/show` + LM Studio `type:'vlm'`), keyed by the provider id that serves them (`{ ollama: Set, lmstudio: Set }`), `null` until fetched; `loaded` flips once the fetch settles. Drops `backend:'cli'` rows (a blanket per-provider claim, not a per-model fact) and never vouches for a provider the server didn't enumerate. | Any VISION model picker — pass `idsByProvider` to `visionLocalModelFilter` / `assignmentModelOptions` so a new multimodal family (`gemma4`) isn't hidden by the stale client id regex, and so an installed VLM shows even when the provider's stored `models` snapshot is stale; gate any "none installed" messaging on `loaded` and on the provider being a local backend. |
| `useToolUseModelIds` | `{ idsByProvider, loaded }` — TOOL-USE (function-calling) capable model ids the server reports (Ollama `/api/show` `tools` capability + LM Studio catalog capabilities) via `/api/local-llm/tool-use-models`, keyed by the provider id that serves them (`{ ollama: Set, lmstudio: Set }`), `null` until fetched; `loaded` flips once the fetch settles. One module-shared fetch across every mounted caller, retried on a later mount if it failed. | Any AGENT model picker — pass `idsByProvider` to `localToolUseHint` / `withToolUseOptionLabel` so a tool-capable family the client id regex predates (`phi4-mini`) isn't mislabelled "⚠ no known tool use", and gate the annotation on `loaded` so the warning isn't asserted mid-fetch. |
| `useTheme` | Dark/light theme + paired-theme switching. | Theme picker. |
diff --git a/client/src/hooks/useLocalModels.js b/client/src/hooks/useLocalModels.js
index daf3040450..d43f20b1cf 100644
--- a/client/src/hooks/useLocalModels.js
+++ b/client/src/hooks/useLocalModels.js
@@ -16,12 +16,20 @@ import { getLocalLlmStatus } from '../services/apiLocalLlm';
* `ctxById` maps each installed model id to its native context window (tokens)
* so pickers can show a "(32K ctx)" parenthetical without a second fetch.
*
- * @returns {{ ollama: string[], lmstudio: string[], recommendations: { ollama: object|null, lmstudio: object|null }, ctxById: Record<string, number>, loading: boolean }}
+ * `installed` is the server's per-backend "is the app here at all" verdict —
+ * which counts a macOS LM Studio bundle with no `lms` shim and a running server
+ * with no CLI, so callers must NOT re-derive it from a bare binary probe. It
+ * stays `null` until the fetch resolves (and after a failed one), so a caller
+ * can tell "not fetched" from a confirmed `false` and never offers an install
+ * for an app it simply hasn't heard about yet.
+ *
+ * @returns {{ ollama: string[], lmstudio: string[], installed: { ollama: boolean|null, lmstudio: boolean|null }, recommendations: { ollama: object|null, lmstudio: object|null }, ctxById: Record<string, number>, loading: boolean }}
*/
export default function useLocalModels() {
const [state, setState] = useState({
ollama: [],
lmstudio: [],
+ installed: { ollama: null, lmstudio: null },
recommendations: { ollama: null, lmstudio: null },
ctxById: {},
loading: true,
@@ -39,9 +47,13 @@ export default function useLocalModels() {
const id = m.id || m.name;
if (id && Number(m.contextLength) > 0) ctxById[id] = m.contextLength;
}
+ const installedFlag = (backend) => (
+ typeof status?.[backend]?.installed === 'boolean' ? status[backend].installed : null
+ );
setState({
ollama: ids(status?.ollama?.models),
lmstudio: ids(status?.lmstudio?.models),
+ installed: { ollama: installedFlag('ollama'), lmstudio: installedFlag('lmstudio') },
recommendations: {
ollama: status?.ollama?.recommendations?.editorial || null,
lmstudio: status?.lmstudio?.recommendations?.editorial || null,
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 27b8b43ba3..44fbd8b8ad 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -4,7 +4,7 @@ import { AlertTriangle } from 'lucide-react';
import toast from '../components/ui/Toast';
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 } from '../utils/providers';
+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 BrailleSpinner from '../components/BrailleSpinner';
import EmptyState from '../components/EmptyState';
@@ -22,6 +22,12 @@ import EffortSelect from '../components/cos/EffortSelect';
import Modal from '../components/ui/Modal';
import { FormField } from '../components/ui/FormField';
import RuntimeInstallModal from '../components/install/RuntimeInstallModal';
+import ProviderRuntimeStatus from '../components/providers/ProviderRuntimeStatus';
+
+// 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
+// links there instead of offering an install of its own.
+const LOCAL_APP_LABELS = { ollama: 'Ollama', lmstudio: 'LM Studio' };
// One phrasing for "this command isn't on the CoS Agent Runner's allowlist",
// shared by the provider-card badge tooltip and the editor's inline banner.
@@ -103,15 +109,32 @@ export default function AIProviders() {
const [sampleProviders, setSampleProviders] = useState([]);
const [loadingSamples, setLoadingSamples] = useState(false);
const [addingSample, setAddingSample] = useState({});
- // `null` means the availability endpoint was not reached (for example, an
- // older server during an upgrade), distinct from a confirmed missing CLI.
- const [opencodeInstallStatus, setOpenCodeInstallStatus] = useState(null);
- const [showOpenCodeInstaller, setShowOpenCodeInstaller] = useState(false);
+ // CLI availability per provider card, keyed by `providerRuntimeKey`. An empty
+ // map means the endpoint was not reached (for example, an older server during
+ // an upgrade) — distinct from a confirmed missing CLI — and simply renders no
+ // install widgets.
+ const [runtimes, setRuntimes] = 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
+ // fold in) — fetched once here rather than inside ProviderForm so opening the
+ // editor doesn't re-request it.
+ const localModels = useLocalModels();
useEffect(() => {
loadData();
}, []);
+ // Probing the CLIs costs a `--version` child process each, so this stays OFF
+ // the critical path: the page paints from the provider list and the install
+ // badges appear when the probes land.
+ const loadRuntimes = useCallback(async () => {
+ const data = await api.getProviderRuntimes({ silent: true }).catch(() => null);
+ setRuntimes(data?.runtimes && typeof data.runtimes === 'object' ? data.runtimes : {});
+ }, []);
+
+ useEffect(() => { loadRuntimes(); }, [loadRuntimes]);
+
useEffect(() => {
if (!activeRun) return;
@@ -136,14 +159,13 @@ export default function AIProviders() {
setLoading(true);
setLoadError(false);
let providersFailed = false;
- const [providersData, appsData, statusData, opencodeData] = await Promise.all([
+ const [providersData, appsData, statusData] = await Promise.all([
api.getProviders().catch(() => {
providersFailed = true;
return null;
}),
api.getApps().catch(() => []),
api.getProviderStatuses().catch(() => ({ providers: {} })),
- api.getOpenCodeInstallStatus({ silent: true }).catch(() => null),
]);
if (providersFailed || !providersData) {
setLoadError(true);
@@ -161,9 +183,6 @@ export default function AIProviders() {
}
setApps(appsData);
setStatuses(statusData.providers || {});
- setOpenCodeInstallStatus(opencodeData && typeof opencodeData.installed === 'boolean'
- ? opencodeData
- : null);
setLoading(false);
};
@@ -316,9 +335,22 @@ export default function AIProviders() {
}
};
- const handleOpenCodeInstallComplete = () => {
- toast.success('OpenCode CLI installed and ready to test');
- loadData();
+ const handleRuntimeInstallComplete = () => {
+ toast.success(`${installingRuntime?.label || 'Runtime'} installed and ready to test`);
+ // Only the CLI's availability changed — the provider records did not.
+ loadRuntimes();
+ };
+
+ // The install widget's data for one card: a CLI provider's binary comes from
+ // the server's runtime table; an API provider fronted by a local app takes the
+ // local-LLM status, which counts an installed app with no CLI shim on PATH.
+ const runtimeForProvider = (provider) => {
+ const backend = isApiProvider(provider) ? localBackendForProvider(provider) : null;
+ if (!backend) return runtimes[providerRuntimeKey(provider)] || null;
+ const installed = localModels.installed?.[backend];
+ // `null` = status not fetched — never offer an install from an unknown state.
+ if (typeof installed !== 'boolean') return null;
+ return { id: backend, label: LOCAL_APP_LABELS[backend], installed, installable: false, manageUrl: '/settings/local-llm' };
};
const selectedRunProvider = providers.find(p => p.id === activeProviderId);
@@ -371,39 +403,6 @@ export default function AIProviders() {
</div>
</div>
- {opencodeInstallStatus && (
- <div className={`rounded-xl border p-4 flex flex-col sm:flex-row sm:items-center justify-between gap-4 ${
- opencodeInstallStatus.installed
- ? 'border-port-success/40 bg-port-success/5'
- : 'border-port-warning/40 bg-port-warning/5'
- }`}>
- <div className="min-w-0">
- <h2 className="text-base font-semibold text-white">OpenCode CLI</h2>
- {opencodeInstallStatus.installed ? (
- <p className="mt-1 text-sm text-port-success">Available on PortOS&apos;s PATH. OpenCode CLI and TUI providers can run.</p>
- ) : (
- <>
- <p className="mt-1 text-sm text-gray-300">Required by OpenCode CLI and TUI providers. Install it here before sending an OpenCode agent task.</p>
- {!opencodeInstallStatus.npmAvailable && (
- <p className="mt-1 text-xs text-port-warning">npm is not available on PortOS&apos;s PATH, so this host cannot install OpenCode from the page.</p>
- )}
- </>
- )}
- </div>
- {!opencodeInstallStatus.installed && (
- <button
- type="button"
- onClick={() => setShowOpenCodeInstaller(true)}
- disabled={!opencodeInstallStatus.npmAvailable}
- className="min-h-[44px] shrink-0 px-4 py-2 rounded-lg text-sm font-medium bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50 disabled:cursor-not-allowed"
- title={opencodeInstallStatus.npmAvailable ? 'Install OpenCode CLI with npm' : 'npm is required to install OpenCode from this page'}
- >
- Install OpenCode
- </button>
- )}
- </div>
- )}
-
{/* Sample Providers Panel */}
{showSamples && (
<div className="bg-port-card border border-port-border rounded-xl p-4 space-y-4">
@@ -654,6 +653,12 @@ export default function AIProviders() {
)}
</div>
+ <ProviderRuntimeStatus
+ className="mt-2"
+ runtime={runtimeForProvider(provider)}
+ onInstall={setInstallingRuntime}
+ />
+
{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">
@@ -859,6 +864,7 @@ export default function AIProviders() {
key={editingProvider?.id || 'new'}
provider={editingProvider}
allProviders={providers}
+ localModels={localModels}
runnerAllowedCommands={runnerAllowedCommands}
onEditProvider={(providerToEdit) => {
setEditingProvider(providerToEdit);
@@ -869,22 +875,22 @@ export default function AIProviders() {
/>
)}
<RuntimeInstallModal
- open={showOpenCodeInstaller}
- runtime="opencode"
- label="OpenCode CLI"
- onClose={() => setShowOpenCodeInstaller(false)}
- onComplete={handleOpenCodeInstallComplete}
- installUrlBase="/api/providers/opencode/install"
+ open={Boolean(installingRuntime)}
+ runtime={installingRuntime?.id}
+ label={installingRuntime?.label}
+ onClose={() => setInstallingRuntime(null)}
+ onComplete={handleRuntimeInstallComplete}
+ installUrlBase="/api/providers/runtimes/install"
streamMethod="POST"
flushMs={250}
- description="Installing the OpenCode CLI with npm. This downloads the current OpenCode package."
+ description={`Installing ${installingRuntime?.label} from ${installingRuntime?.method === 'script' ? "the vendor's official install script" : 'its global npm package'}.`}
/>
</div>
</div>
);
}
-function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders = [], runnerAllowedCommands = null }) {
+function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders = [], localModels = { ollama: [], lmstudio: [], ctxById: {} }, runnerAllowedCommands = null }) {
const [formData, setFormData] = useState({
name: provider?.name || '',
type: provider?.type || 'cli',
@@ -920,7 +926,7 @@ function ProviderForm({ provider, onClose, onSave, onEditProvider, allProviders
// Live installed Ollama/LM Studio models, folded into the model pickers so a
// local provider shows what's actually installed — not just the stale `models`
// list stored on the provider record (the "Command R+ / Gemma missing" bug).
- const localModels = useLocalModels();
+ // Passed down from the page, which already holds this status for the cards.
const liveModelsFor = (p) => {
const backend = localBackendForProvider(p);
return backend ? localModels[backend] : [];
diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsx
index 357ce3864c..33687a6c1b 100644
--- a/client/src/pages/AIProviders.test.jsx
+++ b/client/src/pages/AIProviders.test.jsx
@@ -6,12 +6,14 @@ const api = vi.hoisted(() => ({
getProviders: vi.fn(),
getApps: vi.fn(),
getProviderStatuses: vi.fn(),
- getOpenCodeInstallStatus: vi.fn(),
+ getProviderRuntimes: vi.fn(),
getSampleProviders: vi.fn(),
createProvider: vi.fn(),
updateProvider: vi.fn(),
}));
+const localModels = vi.hoisted(() => ({ value: { ctxById: {}, installed: { ollama: null, lmstudio: null } } }));
+
const toast = vi.hoisted(() => ({
success: vi.fn(),
error: vi.fn(),
@@ -30,13 +32,15 @@ vi.mock('../services/socket', () => ({
},
}));
vi.mock('../hooks/useLocalModels', () => ({
- default: () => ({ ctxById: {} }),
+ default: () => localModels.value,
}));
vi.mock('../components/settings/SettingsTabsHeader', () => ({
default: () => <div data-testid="settings-tabs-header" />,
}));
vi.mock('../components/install/RuntimeInstallModal', () => ({
- default: ({ open, streamMethod, flushMs }) => open ? <div data-testid="opencode-install-modal" data-stream-method={streamMethod} data-flush-ms={flushMs} /> : null,
+ default: ({ open, runtime, streamMethod, flushMs }) => open
+ ? <div data-testid="runtime-install-modal" data-runtime={runtime} data-stream-method={streamMethod} data-flush-ms={flushMs} />
+ : null,
}));
import AIProviders from './AIProviders';
@@ -47,46 +51,138 @@ const renderPage = () => render(
</MemoryRouter>
);
+// One entry of the `runtimes` map from GET /api/providers/runtimes.
+const missingRuntime = {
+ id: 'opencode',
+ label: 'OpenCode CLI',
+ command: 'opencode',
+ installed: false,
+ method: 'npm',
+ installable: true,
+ blockedReason: null,
+ docsUrl: 'https://opencode.ai/docs',
+};
+
describe('AIProviders page load error handling', () => {
beforeEach(() => {
vi.clearAllMocks();
api.getApps.mockResolvedValue([]);
api.getProviderStatuses.mockResolvedValue({ providers: {} });
- api.getOpenCodeInstallStatus.mockResolvedValue({ installed: false, npmAvailable: true });
+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
+ localModels.value = { ctxById: {}, installed: { ollama: null, lmstudio: null } };
});
- it('offers an in-page OpenCode install when the CLI is missing', async () => {
- api.getProviders.mockResolvedValue({ providers: [], activeProvider: null });
+ it('offers an install button on the card of a provider whose CLI is missing', async () => {
+ api.getProviders.mockResolvedValue({
+ providers: [{ id: 'opencode-ollama', name: 'OpenCode Ollama', type: 'cli', command: 'opencode', args: ['run'], enabled: true }],
+ activeProvider: null,
+ });
+ api.getProviderRuntimes.mockResolvedValue({ runtimes: { opencode: missingRuntime } });
renderPage();
- expect(await screen.findByText('OpenCode CLI')).toBeInTheDocument();
- const install = screen.getByRole('button', { name: 'Install OpenCode' });
+ const install = await screen.findByRole('button', { name: /Install OpenCode CLI/ });
expect(install).toBeEnabled();
fireEvent.click(install);
- const modal = screen.getByTestId('opencode-install-modal');
+ const modal = screen.getByTestId('runtime-install-modal');
+ expect(modal).toHaveAttribute('data-runtime', 'opencode');
expect(modal).toHaveAttribute('data-stream-method', 'POST');
expect(modal).toHaveAttribute('data-flush-ms', '250');
});
- it('reports OpenCode as ready instead of offering another install', async () => {
- api.getProviders.mockResolvedValue({ providers: [], activeProvider: null });
- api.getOpenCodeInstallStatus.mockResolvedValue({ installed: true, npmAvailable: true });
+ // An absolute path in `command` is a legitimate config — the widget must
+ // still find its runtime rather than silently dropping the install button.
+ it('matches a runtime through a path-qualified command', async () => {
+ api.getProviders.mockResolvedValue({
+ providers: [{ id: 'codex-pinned', name: 'Codex (pinned)', type: 'cli', command: '/opt/bin/codex', args: [], enabled: true }],
+ activeProvider: null,
+ });
+ api.getProviderRuntimes.mockResolvedValue({
+ runtimes: { codex: { ...missingRuntime, id: 'codex', label: 'Codex CLI', command: 'codex' } },
+ });
renderPage();
- expect(await screen.findByText(/Available on PortOS's PATH/)).toBeInTheDocument();
- expect(screen.queryByRole('button', { name: 'Install OpenCode' })).not.toBeInTheDocument();
+ expect(await screen.findByRole('button', { name: /Install Codex CLI/ })).toBeEnabled();
});
- it('explains why the install action is unavailable without npm', async () => {
- api.getProviders.mockResolvedValue({ providers: [], activeProvider: null });
- api.getOpenCodeInstallStatus.mockResolvedValue({ installed: false, npmAvailable: false });
+ it('reports an installed runtime instead of offering another install', async () => {
+ api.getProviders.mockResolvedValue({
+ providers: [{ id: 'opencode-ollama', name: 'OpenCode Ollama', type: 'cli', command: 'opencode', args: ['run'], enabled: true }],
+ activeProvider: null,
+ });
+ api.getProviderRuntimes.mockResolvedValue({ runtimes: { opencode: { ...missingRuntime, installed: true } } });
+
+ renderPage();
+
+ expect(await screen.findByText(/installed/)).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /Install OpenCode CLI/ })).not.toBeInTheDocument();
+ });
+
+ it('explains why the install action is unavailable and links the vendor instructions', async () => {
+ api.getProviders.mockResolvedValue({
+ providers: [{ id: 'opencode-ollama', name: 'OpenCode Ollama', type: 'cli', command: 'opencode', args: ['run'], enabled: true }],
+ activeProvider: null,
+ });
+ api.getProviderRuntimes.mockResolvedValue({
+ runtimes: {
+ opencode: {
+ ...missingRuntime,
+ installable: false,
+ blockedReason: "npm is not available on PortOS's PATH, so this host cannot install OpenCode CLI from this page.",
+ },
+ },
+ });
renderPage();
expect(await screen.findByText(/npm is not available on PortOS's PATH/)).toBeInTheDocument();
- expect(screen.getByRole('button', { name: 'Install OpenCode' })).toBeDisabled();
+ // No dead Install button — the vendor's own instructions are the way out.
+ expect(screen.queryByRole('button', { name: /Install OpenCode CLI/ })).not.toBeInTheDocument();
+ expect(screen.getByRole('link', { name: /Install instructions/ })).toHaveAttribute('href', 'https://opencode.ai/docs');
+ });
+
+ // Ollama / LM Studio keep their real installer on the Local LLM tab, so the
+ // provider card links there instead of streaming an install of its own — and
+ // reads their state from the local-LLM status, which counts an installed app
+ // with no CLI shim on PATH.
+ it('links a locally-managed app to its own settings tab', async () => {
+ api.getProviders.mockResolvedValue({
+ providers: [{ id: 'lmstudio', name: 'LM Studio', type: 'api', endpoint: 'http://localhost:1234/v1', enabled: true }],
+ activeProvider: null,
+ });
+ localModels.value = { ctxById: {}, installed: { ollama: null, lmstudio: false } };
+
+ renderPage();
+
+ expect(await screen.findByRole('link', { name: /Install LM Studio/ })).toHaveAttribute('href', '/settings/local-llm');
+ });
+
+ // `null` means the local-LLM status has not answered yet — offering an
+ // install from that state would flash a wrong CTA on every page load.
+ it('offers nothing for a local app whose status has not been fetched', async () => {
+ api.getProviders.mockResolvedValue({
+ providers: [{ id: 'lmstudio', name: 'LM Studio', type: 'api', endpoint: 'http://localhost:1234/v1', enabled: true }],
+ activeProvider: null,
+ });
+
+ renderPage();
+
+ expect(await screen.findByText('LM Studio')).toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: /Install LM Studio/ })).not.toBeInTheDocument();
+ });
+
+ it('shows no install widget for a command PortOS has no installer for', async () => {
+ api.getProviders.mockResolvedValue({
+ providers: [{ id: 'custom', name: 'Custom CLI', type: 'cli', command: 'my-agent', args: [], enabled: true }],
+ activeProvider: null,
+ });
+ api.getProviderRuntimes.mockResolvedValue({ runtimes: { opencode: missingRuntime } });
+
+ renderPage();
+
+ expect(await screen.findByText('Custom CLI')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: /^Install/ })).not.toBeInTheDocument();
});
it('renders provider list when api.getProviders succeeds with data', async () => {
@@ -153,7 +249,7 @@ describe('handleAddSample error handling', () => {
vi.clearAllMocks();
api.getApps.mockResolvedValue([]);
api.getProviderStatuses.mockResolvedValue({ providers: {} });
- api.getOpenCodeInstallStatus.mockResolvedValue({ installed: false, npmAvailable: true });
+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
api.getProviders.mockResolvedValue({
providers: [],
activeProvider: null,
@@ -189,7 +285,7 @@ describe('handleAddAllSamples partial failure handling', () => {
vi.clearAllMocks();
api.getApps.mockResolvedValue([]);
api.getProviderStatuses.mockResolvedValue({ providers: {} });
- api.getOpenCodeInstallStatus.mockResolvedValue({ installed: false, npmAvailable: true });
+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
api.getProviders.mockResolvedValue({
providers: [],
activeProvider: null,
@@ -234,7 +330,7 @@ describe('CoS Agent Runner allowlist warning', () => {
vi.clearAllMocks();
api.getApps.mockResolvedValue([]);
api.getProviderStatuses.mockResolvedValue({ providers: {} });
- api.getOpenCodeInstallStatus.mockResolvedValue({ installed: false, npmAvailable: true });
+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
});
it('badges a provider whose command is off the published allowlist', async () => {
@@ -333,7 +429,7 @@ describe('Local num_ctx field', () => {
vi.clearAllMocks();
api.getApps.mockResolvedValue([]);
api.getProviderStatuses.mockResolvedValue({ providers: {} });
- api.getOpenCodeInstallStatus.mockResolvedValue({ installed: false, npmAvailable: true });
+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
});
const openEditorFor = async (provider) => {
@@ -387,7 +483,7 @@ describe('OpenCode OrcaRouter key hint', () => {
vi.clearAllMocks();
api.getApps.mockResolvedValue([]);
api.getProviderStatuses.mockResolvedValue({ providers: {} });
- api.getOpenCodeInstallStatus.mockResolvedValue({ installed: true, npmAvailable: true });
+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
});
// The OpenCode wrapper carries no key of its own — the card must point the
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 9fcc139509..19a25fb343 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -51,7 +51,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiHistory.js` | Historical logs / runs. |
| `apiLogs.js` | PM2 system logs: fetch a process's recent log tail (process list comes from `apiCommands.getProcessesList`). |
| `apiPorts.js` | Port forwarding / allocation. |
-| `apiProviders.js` | AI provider configuration and safe OpenCode CLI installation readiness. |
+| `apiProviders.js` | AI provider configuration, plus provider-runtime (CLI) install readiness for the per-card Install buttons. |
| `apiPrompts.js` | Prompt Manager: stage templates, variables, and job-skill templates (providers list reuses `apiProviders.getProviders`). |
| `apiReferenceRepos.js` | Per-app reference-repo registry. |
| `apiReview.js` | Review hub. |
diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.js
index 24c352d481..01b82d5050 100644
--- a/client/src/services/apiProviders.js
+++ b/client/src/services/apiProviders.js
@@ -22,9 +22,11 @@ export const deleteProvider = (id) => request(`/providers/${id}`, { method: 'DEL
export const getSampleProviders = () => request('/providers/samples');
export const testProvider = (id) => request(`/providers/${id}/test`, { method: 'POST' });
export const refreshProviderModels = (id, options) => request(`/providers/${id}/refresh-models`, { method: 'POST', ...options });
-// OpenCode is installed only after an explicit Providers-page click. The
-// status endpoint carries booleans only — never local executable paths.
-export const getOpenCodeInstallStatus = (options) => request('/providers/opencode/installation', options);
+// Which provider runtimes (claude, codex, opencode, …) are runnable on this
+// host, and which of them PortOS can install for you. Installs happen only
+// 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);
// Provider status (usage limits, availability)
export const getProviderStatuses = () => request('/providers/status');
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 549f6e97c4..d720454467 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -41,7 +41,7 @@ grep -i "what you want to do" client/src/utils/README.md
| `urlNormalize` | `isUrl` detection, `normalizeUrl` (optional git/`requireDot` modes), `isHttpUrl` (explicit http(s) only — safe-href check), and `tiktokVideoId` / `tiktokEmbedSrc` (host-anchored TikTok video-id extraction + its Embed Player URL, so a reference embeds without loading TikTok's embed.js). |
| `platform` | `isMac` detection and `modKey` (⌘/Ctrl) for keyboard-shortcut display. |
| `navWorkingSet` | Recent/pinned nav persistence (`recordVisit`, `togglePin`, `isPinned`) plus `resolveRecentNavEntries` for mapping stored deep links back to their longest matching nav-manifest entry. |
-| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `isAntigravityProvider`, `isOrcaRouterBackedProvider` (the OpenCode wrapper that inherits its API key from the sibling `orcarouter` API provider at spawn time), `filterSelectableModels`, `resolveCliEffort` (mirror — what a stored effort actually runs as, so the picker can name a clamped level), `configuredDefaultIn` — the sentinel a provider's catalog carries, so a picker can render an option matching a sentinel-valued tier instead of a blank select — `getProviderTimeout`, `resolveEffectiveProvider` — the provider a record actually runs on (its pin, else the active provider) plus whether it fell back, so a "Default" option can name what it resolves to — `resolveSeriesRunLlm` (mirror of server `seriesLlmOverride.js`: which provider/model a Pipeline **series** run resolves to — per-run override → `series.llm` → active provider) and `providerModelLabel` (the one "Provider / model" phrasing), configured-default sentinels, and the claude/codex/agy thinking-effort levels — `effortLevelsForProvider`, mirror of server `providerModels.js`). Also `isRunnerAllowedCommand(command, allowedCommands)` — would the CoS Agent Runner (`/spawn`, `/spawn-tui`) accept this command? Mirrors only the *normalization* in `server/cos-runner/allowedCommands.js` (the list itself arrives as `runnerAllowedCommands` on `GET /api/providers`, because the allowlist is an exec boundary and stays hand-curated server-side); returns `null` for "list not fetched / field blank" so a failed fetch never renders a warning. Pinned by `server/cos-runner/allowedCommands.parity.test.js`. |
+| `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `isAntigravityProvider`, `isOrcaRouterBackedProvider` (the OpenCode wrapper that inherits its API key from the sibling `orcarouter` API provider at spawn time), `filterSelectableModels`, `resolveCliEffort` (mirror — what a stored effort actually runs as, so the picker can name a clamped level), `configuredDefaultIn` — the sentinel a provider's catalog carries, so a picker can render an option matching a sentinel-valued tier instead of a blank select — `getProviderTimeout`, `resolveEffectiveProvider` — the provider a record actually runs on (its pin, else the active provider) plus whether it fell back, so a "Default" option can name what it resolves to — `resolveSeriesRunLlm` (mirror of server `seriesLlmOverride.js`: which provider/model a Pipeline **series** run resolves to — per-run override → `series.llm` → active provider) and `providerModelLabel` (the one "Provider / model" phrasing), configured-default sentinels, and the claude/codex/agy thinking-effort levels — `effortLevelsForProvider`, mirror of server `providerModels.js`). Also `isRunnerAllowedCommand(command, allowedCommands)` — would the CoS Agent Runner (`/spawn`, `/spawn-tui`) accept this command? Mirrors only the *normalization* in `server/cos-runner/allowedCommands.js` (the list itself arrives as `runnerAllowedCommands` on `GET /api/providers`, because the allowlist is an exec boundary and stays hand-curated server-side); returns `null` for "list not fetched / field blank" so a failed fetch never renders a warning. Pinned by `server/cos-runner/allowedCommands.parity.test.js`. And `providerRuntimeKey(provider)` — the key a provider's runtime is published under by `GET /api/providers/runtimes`, so a card can show its CLI install status (bare binary name for a cli/tui provider, provider id for an API provider fronted by a local app); the runtime table itself stays server-side. |
| `layeredIntelligenceReasons` | Canonical gloss for the Layered Intelligence loop's run-outcome reason tokens, shared by the on-demand toast and the durable "Last run" line (`formatLiReason`, `liReasonTone`, `LI_NEUTRAL_REASONS`). |
## Module loading / resilience
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index ef243e290c..d6e3d8a637 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -804,6 +804,27 @@ export const isRunnerAllowedCommand = (command, allowedCommands) => {
return allowedCommands.includes(runnerCommandBaseName(command));
};
+/**
+ * The key a CLI/TUI provider's runtime is published under in the `runtimes` map
+ * from `GET /api/providers/runtimes` — the binary it spawns, basename-normalized
+ * so a provider pinned to an absolute path still matches.
+ *
+ * Deliberately NOT a client-side copy of the runtime table: the server owns
+ * which runtimes exist and how they install, and a key with no entry in the
+ * fetched map simply renders no install widget. That's the right default for a
+ * custom command PortOS has no installer for.
+ *
+ * API providers have no runtime here — the two fronted by a local app resolve
+ * through `localBackendForProvider` (which also matches a renamed provider by
+ * its endpoint) and get their install state from the local-LLM status.
+ */
+export const providerRuntimeKey = (provider) => {
+ if (!isProcessProvider(provider)) return null;
+ const command = provider?.command;
+ if (typeof command !== 'string' || command.trim() === '') return null;
+ return runnerCommandBaseName(command.trim());
+};
+
/**
* Whether `provider` is served by an Ollama daemon rather than its nominal
* cloud/CLI backend: the built-in `ollama` API provider itself (id match), an
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 64f47cdd3b..6b00287346 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -32,6 +32,7 @@ import {
isCliProvider,
isApiProvider,
isProcessProvider,
+ providerRuntimeKey,
isOllamaBackedProvider,
isOrcaRouterBackedProvider,
isGrokBuildCli,
@@ -1149,4 +1150,30 @@ describe('AI Assignments option helpers', () => {
});
});
});
+
+describe('providerRuntimeKey', () => {
+ // The key is what a provider card looks its runtime up by in the server's
+ // `runtimes` map, so a path-qualified or Windows command must normalize to
+ // the same bare binary name the server publishes.
+ it('normalizes a process provider command to its bare binary name', () => {
+ expect(providerRuntimeKey({ type: 'cli', command: 'codex' })).toBe('codex');
+ expect(providerRuntimeKey({ type: 'tui', command: '/opt/homebrew/bin/opencode' })).toBe('opencode');
+ expect(providerRuntimeKey({ type: 'cli', command: 'C:\\tools\\claude.exe' })).toBe('claude');
+ expect(providerRuntimeKey({ type: 'cli', command: ' agy ' })).toBe('agy');
+ });
+
+ // API providers have no CLI runtime — the two fronted by a local app resolve
+ // through localBackendForProvider instead, so this must not claim a key for
+ // every cloud provider id.
+ it('has no runtime key for an API provider', () => {
+ expect(providerRuntimeKey({ type: 'api', id: 'lmstudio', endpoint: 'http://localhost:1234/v1' })).toBeNull();
+ expect(providerRuntimeKey({ type: 'api', id: 'cerebras' })).toBeNull();
+ });
+
+ it('returns null when there is nothing to look up', () => {
+ expect(providerRuntimeKey(null)).toBeNull();
+ expect(providerRuntimeKey({ type: 'cli', command: ' ' })).toBeNull();
+ });
+});
+
// @vitest-environment node
diff --git a/docs/API.md b/docs/API.md
index 5bbec9f6f5..5494b33fd0 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -65,6 +65,10 @@ PortOS is designed for personal/developer use on trusted networks. It implements
| DELETE | `/providers/:id` | Delete provider |
| POST | `/providers/:id/test` | Test provider connectivity |
| 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/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`. |
### AI Runs
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 243f53e835..4d29b44029 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -8,11 +8,13 @@ import { createLineReader } from '../lib/streamLines.js';
import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';
import { createInstallLogger } from '../lib/installLogger.js';
import {
- getOpenCodeInstallStatus,
- OPENCODE_NPM_PACKAGE,
- spawnOpenCodeInstaller,
- stopOpenCodeInstaller,
-} from '../services/opencodeInstaller.js';
+ describeRuntimeInstall,
+ getProviderRuntime,
+ getProviderRuntimeStatus,
+ getProviderRuntimeStatuses,
+ spawnRuntimeInstaller,
+ stopRuntimeInstaller,
+} from '../services/providerRuntimeInstaller.js';
/**
* The CoS Agent Runner's exec allowlist, published read-only so the AI
@@ -31,10 +33,11 @@ import {
*/
const RUNNER_ALLOWED_COMMANDS = [...ALLOWED_COMMANDS].sort();
-// One npm global install may write the same package prefix at a time. This is
-// a lightweight re-entrancy guard for a double-click or a second browser tab;
-// its child stays in the route so a client disconnect can terminate it.
-let opencodeInstallInFlight = null;
+// One global CLI install at a time — npm's global prefix and the vendor
+// install scripts all write the same bin directory. This is a lightweight
+// re-entrancy guard for a double-click or a second browser tab; its child stays
+// in the route so a client disconnect can terminate it.
+let runtimeInstallInFlight = null;
/**
* Sanitize a provider object for client responses.
@@ -121,24 +124,39 @@ export function createPortOSProviderRoutes(aiToolkit) {
res.json({ providers: providers.map(presentProvider) });
}));
- // OpenCode is a local coding CLI, not an LLM service PortOS can silently
- // bootstrap. These endpoints only expose availability and service an
- // explicit click from the Providers page. They intentionally return no
- // resolved filesystem paths, which could disclose the host account name.
- router.get('/opencode/installation', asyncHandler(async (_req, res) => {
- res.json(await getOpenCodeInstallStatus());
+ // A CLI/TUI provider is only usable if its runtime binary is on PortOS's
+ // PATH. These are local coding tools, not LLM services PortOS may silently
+ // bootstrap, so this endpoint only reports availability and the companion
+ // install endpoint services an explicit click from the Providers page. Both
+ // intentionally return no resolved filesystem paths, which could disclose the
+ // host account name.
+ router.get('/runtimes', asyncHandler(async (_req, res) => {
+ res.json({ runtimes: await getProviderRuntimeStatuses() });
}));
- // Installing a global CLI mutates host state, so this stays a POST even
- // though the response is SSE-encoded. The client reads it with fetch rather
- // than EventSource: EventSource would auto-reconnect after a dropped stream
- // and could launch another non-idempotent npm install.
- //
- // The fixed command is npm install --global --ignore-scripts=false
- // opencode-ai@latest; no request input reaches a shell or package argument.
- router.post('/opencode/install', asyncHandler(async (req, res) => {
+ /**
+ * Install one provider runtime, streaming the installer's output as SSE.
+ *
+ * Installing a global CLI mutates host state, so this stays a POST even
+ * though the response is SSE-encoded. The client reads it with fetch rather
+ * than EventSource: EventSource would auto-reconnect after a dropped stream
+ * and could launch another non-idempotent install.
+ *
+ * The request names a runtime *id* only. The command, package, and URL all
+ * come from the installer's fixed table, so no request input ever reaches a
+ * shell word.
+ */
+ const streamRuntimeInstall = async (req, res, runtimeId) => {
+ // Table lookup only (no I/O), so an unknown id is a plain 400 instead of a
+ // stream that only says "no" once the modal is up. The real probe waits
+ // until the disconnect handler is registered below.
+ const row = getProviderRuntime(runtimeId);
+ if (!row) {
+ throw new ServerError('Unknown provider runtime', { status: 400, code: 'UNKNOWN_RUNTIME', context: { runtime: String(runtimeId || '') } });
+ }
+
const { send, safeEnd } = openSseStream(res);
- const installLog = createInstallLogger({ installer: 'OpenCode CLI', target: 'npm global prefix' });
+ const installLog = createInstallLogger({ installer: row.label, target: `${row.command} on PortOS's PATH` });
const emit = (event) => { installLog.onEvent(event); send(event); };
let child = null;
let finished = false;
@@ -151,50 +169,54 @@ export function createPortOSProviderRoutes(aiToolkit) {
clientGone = true;
installLog.cancel();
if (finished) return;
- if (child) stopOpenCodeInstaller(child);
- if (reservation && opencodeInstallInFlight === reservation) opencodeInstallInFlight = null;
+ if (child) stopRuntimeInstaller(child);
+ if (reservation && runtimeInstallInFlight === reservation) runtimeInstallInFlight = null;
safeEnd();
});
- const status = await getOpenCodeInstallStatus();
+ // Un-cached: the user may have just installed this CLI in a terminal, and a
+ // stale "not installed" would run a redundant install.
+ const runtime = await getProviderRuntimeStatus(row.id, { fresh: true });
if (clientGone) return safeEnd();
- if (status.installed) {
- send({ type: 'log', message: 'OpenCode is already available to PortOS.' });
+ if (runtime.installed) {
+ send({ type: 'log', message: `${runtime.label} is already available to PortOS.` });
send({ type: 'complete', message: 'Already installed — nothing to do.' });
return safeEnd();
}
- if (!status.npmAvailable) {
- send({ type: 'error', message: 'npm is not available on PortOS\'s PATH, so OpenCode cannot be installed from this page.' });
+ if (!runtime.installable) {
+ send({ type: 'error', message: runtime.blockedReason || `PortOS cannot install ${runtime.label} on this host.` });
return safeEnd();
}
- if (opencodeInstallInFlight) {
- send({ type: 'error', message: 'Another OpenCode install is already running. Wait for it to finish or restart PortOS.' });
+ if (runtimeInstallInFlight) {
+ send({ type: 'error', message: 'Another runtime install is already running. Wait for it to finish or restart PortOS.' });
return safeEnd();
}
// Reserve synchronously before spawning so two requests that finish their
- // status probe together cannot launch competing global npm installs.
+ // status probe together cannot launch competing installs into the same bin
+ // directory.
reservation = {};
- opencodeInstallInFlight = reservation;
+ runtimeInstallInFlight = reservation;
if (clientGone) {
- opencodeInstallInFlight = null;
+ runtimeInstallInFlight = null;
return safeEnd();
}
- send({ type: 'stage', stage: 'install', message: 'Installing OpenCode CLI with npm.' });
- emit({ type: 'log', message: `Running npm install --global ${OPENCODE_NPM_PACKAGE}.` });
+ send({ type: 'stage', stage: 'install', message: `Installing ${runtime.label}.` });
+ emit({ type: 'log', message: `Running ${describeRuntimeInstall(runtime.id)}.` });
installLog.start();
- child = spawnOpenCodeInstaller();
- opencodeInstallInFlight = child;
+ child = spawnRuntimeInstaller(runtime.id);
+ runtimeInstallInFlight = child;
const onLine = (line) => {
const text = line.trimEnd();
if (text) emit({ type: 'log', message: text });
};
- // `--no-progress` suppresses npm's usual redraws. Keep the default
- // newline-only reader as a defensive second layer: a lifecycle child that
- // still writes bare carriage returns cannot turn every redraw into a
- // browser log frame and a full modal re-render.
+ // npm runs with `--no-progress`, which suppresses its usual redraws. Keep
+ // the default newline-only reader as a defensive second layer: a lifecycle
+ // child (or a vendor install script's own progress bar) that still writes
+ // bare carriage returns cannot turn every redraw into a browser log frame
+ // and a full modal re-render.
const stdoutReader = createLineReader(onLine);
const stderrReader = createLineReader(onLine);
child.stdout.on('data', stdoutReader.push);
@@ -202,12 +224,12 @@ export function createPortOSProviderRoutes(aiToolkit) {
child.on('error', (err) => {
if (finished) return;
finished = true;
- if (opencodeInstallInFlight === child) opencodeInstallInFlight = null;
- emit({ type: 'error', message: `OpenCode installer failed to start: ${err.message}` });
+ if (runtimeInstallInFlight === child) runtimeInstallInFlight = null;
+ emit({ type: 'error', message: `${runtime.label} installer failed to start: ${err.message}` });
safeEnd();
});
- // The post-install PATH check is deliberately stronger than npm's exit
- // code. A successful global write whose bin directory is absent from PM2's
+ // The post-install PATH check is deliberately stronger than the installer's
+ // exit code. A successful write whose bin directory is absent from PM2's
// PATH would otherwise recreate the same opaque agent-start failure.
child.on('close', async (code) => {
if (finished) return;
@@ -215,23 +237,43 @@ export function createPortOSProviderRoutes(aiToolkit) {
stdoutReader.flush();
stderrReader.flush();
finished = true;
- if (opencodeInstallInFlight === child) opencodeInstallInFlight = null;
- const installed = code === 0 && (await getOpenCodeInstallStatus()).installed;
+ if (runtimeInstallInFlight === child) runtimeInstallInFlight = null;
+ // `fresh` is load-bearing: the pre-install probe cached "not installed"
+ // seconds ago, and re-reading it would fail a CLI that now works.
+ const installed = code === 0 && (await getProviderRuntimeStatus(runtime.id, { fresh: true })).installed;
if (installed) {
- emit({ type: 'complete', message: 'OpenCode is installed and available to PortOS.' });
+ emit({ type: 'complete', message: `${runtime.label} is installed and available to PortOS.` });
} else if (code === 0) {
- emit({ type: 'error', message: 'npm completed, but OpenCode is not runnable by PortOS. Restart PortOS or reinstall OpenCode so its postinstall script can complete, then try again.' });
+ emit({ type: 'error', message: `The installer finished, but PortOS still cannot run \`${runtime.command}\`. Its bin directory may be missing from PortOS's PATH — restart PortOS, then try again.` });
} else {
- emit({ type: 'error', message: `OpenCode installer exited with code ${code}.` });
+ emit({ type: 'error', message: `${runtime.label} installer exited with code ${code}.` });
}
safeEnd();
} catch (err) {
// Child-process completion runs outside Express's request lifecycle.
- console.error(`❌ OpenCode install completion check failed: ${err.message}`);
- emit({ type: 'error', message: `OpenCode install completion check failed: ${err.message}` });
+ console.error(`❌ ${runtime.label} install completion check failed: ${err.message}`);
+ emit({ type: 'error', message: `${runtime.label} install completion check failed: ${err.message}` });
safeEnd();
}
});
+ };
+
+ // `runtime` rides in the query string because the shared RuntimeInstallModal
+ // already appends it there for every BYO-runtime installer.
+ router.post('/runtimes/install', asyncHandler(async (req, res) => {
+ await streamRuntimeInstall(req, res, req.query.runtime);
+ }));
+
+ // Back-compat for a client build that predates the generalized routes (a
+ // deployed `client/dist` can lag the server across an upgrade). Both mirror
+ // the old OpenCode-only response shape exactly.
+ router.get('/opencode/installation', asyncHandler(async (_req, res) => {
+ const status = await getProviderRuntimeStatus('opencode');
+ res.json({ installed: status.installed, npmAvailable: status.installable });
+ }));
+
+ router.post('/opencode/install', asyncHandler(async (req, res) => {
+ await streamRuntimeInstall(req, res, 'opencode');
}));
// Provider status routes MUST be defined before toolkit routes,
diff --git a/server/routes/providers.opencodeInstall.test.js b/server/routes/providers.opencodeInstall.test.js
deleted file mode 100644
index 0fba5ea28f..0000000000
--- a/server/routes/providers.opencodeInstall.test.js
+++ /dev/null
@@ -1,100 +0,0 @@
-import { EventEmitter } from 'node:events';
-import { PassThrough } from 'node:stream';
-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 installer = vi.hoisted(() => ({
- getOpenCodeInstallStatus: vi.fn(),
- spawnOpenCodeInstaller: vi.fn(),
- stopOpenCodeInstaller: vi.fn(),
- OPENCODE_NPM_PACKAGE: 'opencode-ai@latest',
-}));
-
-vi.mock('../services/opencodeInstaller.js', () => installer);
-
-import { createPortOSProviderRoutes } from './providers.js';
-
-const app = () => {
- const toolkit = { services: { providers: {} }, routes: { providers: Router() } };
- const server = express();
- server.use(express.json());
- server.use('/api/providers', createPortOSProviderRoutes(toolkit));
- server.use(errorMiddleware);
- return server;
-};
-
-const makeChild = () => {
- const child = new EventEmitter();
- child.pid = 123;
- child.killed = false;
- child.stdout = new PassThrough();
- child.stderr = new PassThrough();
- child.kill = vi.fn();
- return child;
-};
-
-describe('OpenCode Providers installer routes', () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it('returns only install readiness booleans', async () => {
- installer.getOpenCodeInstallStatus.mockResolvedValueOnce({ installed: false, npmAvailable: true });
-
- const response = await request(app()).get('/api/providers/opencode/installation');
-
- expect(response.status).toBe(200);
- expect(response.body).toEqual({ installed: false, npmAvailable: true });
- });
-
- it('streams a verified completion after the fixed installer exits', async () => {
- const child = makeChild();
- installer.getOpenCodeInstallStatus
- .mockResolvedValueOnce({ installed: false, npmAvailable: true })
- .mockResolvedValueOnce({ installed: true, npmAvailable: true });
- installer.spawnOpenCodeInstaller.mockReturnValueOnce(child);
-
- const responsePromise = request(app()).post('/api/providers/opencode/install').then((response) => response);
- await vi.waitFor(() => expect(installer.spawnOpenCodeInstaller).toHaveBeenCalledOnce());
- child.stdout.end('added OpenCode\n');
- child.stderr.end();
- child.emit('close', 0);
- const response = await responsePromise;
-
- expect(response.status).toBe(200);
- expect(response.headers['content-type']).toContain('text/event-stream');
- expect(response.text).toContain('Running npm install --global opencode-ai@latest.');
- expect(response.text).toContain('added OpenCode');
- expect(response.text).toContain('OpenCode is installed and available to PortOS.');
- });
-
- it('reports an unusable CLI after npm exits successfully', async () => {
- const child = makeChild();
- installer.getOpenCodeInstallStatus
- .mockResolvedValueOnce({ installed: false, npmAvailable: true })
- .mockResolvedValueOnce({ installed: false, npmAvailable: true });
- installer.spawnOpenCodeInstaller.mockReturnValueOnce(child);
-
- const responsePromise = request(app()).post('/api/providers/opencode/install').then((response) => response);
- await vi.waitFor(() => expect(installer.spawnOpenCodeInstaller).toHaveBeenCalledOnce());
- child.stdout.end();
- child.stderr.end();
- child.emit('close', 0);
- const response = await responsePromise;
-
- expect(response.status).toBe(200);
- expect(response.text).toContain('OpenCode is not runnable by PortOS');
- });
-
- it('fails the stream without spawning when npm is absent', async () => {
- installer.getOpenCodeInstallStatus.mockResolvedValueOnce({ installed: false, npmAvailable: false });
-
- const response = await request(app()).post('/api/providers/opencode/install');
-
- expect(response.status).toBe(200);
- expect(response.text).toContain('npm is not available');
- expect(installer.spawnOpenCodeInstaller).not.toHaveBeenCalled();
- });
-});
diff --git a/server/routes/providers.runtimeInstall.test.js b/server/routes/providers.runtimeInstall.test.js
new file mode 100644
index 0000000000..3188b521bb
--- /dev/null
+++ b/server/routes/providers.runtimeInstall.test.js
@@ -0,0 +1,158 @@
+import { EventEmitter } from 'node:events';
+import { PassThrough } from 'node:stream';
+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 RUNTIMES = {
+ opencode: { id: 'opencode', label: 'OpenCode CLI', command: 'opencode', install: { kind: 'npm', package: 'opencode-ai@latest' } },
+ codex: { id: 'codex', label: 'Codex CLI', command: 'codex', install: { kind: 'npm', package: '@openai/codex@latest' } },
+};
+
+const statusOf = (id, overrides) => ({ ...RUNTIMES[id], installed: false, method: 'npm', installable: true, blockedReason: null, ...overrides });
+
+const installer = vi.hoisted(() => ({
+ getProviderRuntime: vi.fn(),
+ getProviderRuntimeStatus: vi.fn(),
+ getProviderRuntimeStatuses: vi.fn(),
+ spawnRuntimeInstaller: vi.fn(),
+ stopRuntimeInstaller: vi.fn(),
+ describeRuntimeInstall: vi.fn(),
+}));
+
+vi.mock('../services/providerRuntimeInstaller.js', () => installer);
+
+import { createPortOSProviderRoutes } from './providers.js';
+
+const app = () => {
+ const toolkit = { services: { providers: {} }, routes: { providers: Router() } };
+ const server = express();
+ server.use(express.json());
+ server.use('/api/providers', createPortOSProviderRoutes(toolkit));
+ server.use(errorMiddleware);
+ return server;
+};
+
+const makeChild = () => {
+ const child = new EventEmitter();
+ child.pid = 123;
+ child.killed = false;
+ child.stdout = new PassThrough();
+ child.stderr = new PassThrough();
+ child.kill = vi.fn();
+ return child;
+};
+
+describe('Provider runtime installer routes', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ installer.getProviderRuntime.mockImplementation((id) => RUNTIMES[id] || null);
+ installer.describeRuntimeInstall.mockImplementation((id) => `npm install --global ${RUNTIMES[id]?.install?.package}`);
+ });
+
+ it('publishes every runtime status in one payload', async () => {
+ installer.getProviderRuntimeStatuses.mockResolvedValueOnce({ codex: statusOf('codex', { installed: true }) });
+
+ const response = await request(app()).get('/api/providers/runtimes');
+
+ expect(response.status).toBe(200);
+ expect(response.body.runtimes.codex.installed).toBe(true);
+ });
+
+ it('streams a verified completion after the fixed installer exits', async () => {
+ const child = makeChild();
+ installer.getProviderRuntimeStatus
+ .mockResolvedValueOnce(statusOf('codex'))
+ .mockResolvedValueOnce(statusOf('codex', { installed: true }));
+ installer.spawnRuntimeInstaller.mockReturnValueOnce(child);
+
+ const responsePromise = request(app()).post('/api/providers/runtimes/install?runtime=codex').then((response) => response);
+ await vi.waitFor(() => expect(installer.spawnRuntimeInstaller).toHaveBeenCalledWith('codex'));
+ child.stdout.end('added Codex\n');
+ child.stderr.end();
+ child.emit('close', 0);
+ const response = await responsePromise;
+
+ expect(response.status).toBe(200);
+ expect(response.headers['content-type']).toContain('text/event-stream');
+ expect(response.text).toContain('Running npm install --global @openai/codex@latest.');
+ expect(response.text).toContain('added Codex');
+ expect(response.text).toContain('Codex CLI is installed and available to PortOS.');
+ // Both probes bypass the TTL cache: a stale "installed" would skip a needed
+ // install, and a stale "missing" would fail a CLI that now works.
+ for (const call of installer.getProviderRuntimeStatus.mock.calls) {
+ expect(call[1]).toEqual(expect.objectContaining({ fresh: true }));
+ }
+ });
+
+ it('reports an unusable CLI after the installer exits successfully', async () => {
+ const child = makeChild();
+ installer.getProviderRuntimeStatus
+ .mockResolvedValueOnce(statusOf('codex'))
+ .mockResolvedValueOnce(statusOf('codex'));
+ installer.spawnRuntimeInstaller.mockReturnValueOnce(child);
+
+ const responsePromise = request(app()).post('/api/providers/runtimes/install?runtime=codex').then((response) => response);
+ await vi.waitFor(() => expect(installer.spawnRuntimeInstaller).toHaveBeenCalledOnce());
+ child.stdout.end();
+ child.stderr.end();
+ child.emit('close', 0);
+ const response = await responsePromise;
+
+ expect(response.status).toBe(200);
+ expect(response.text).toContain('PortOS still cannot run');
+ });
+
+ it('fails the stream without spawning when the host cannot install', async () => {
+ installer.getProviderRuntimeStatus.mockResolvedValueOnce(statusOf('codex', {
+ installable: false,
+ blockedReason: "npm is not available on PortOS's PATH, so this host cannot install Codex CLI from this page.",
+ }));
+
+ const response = await request(app()).post('/api/providers/runtimes/install?runtime=codex');
+
+ expect(response.status).toBe(200);
+ expect(response.text).toContain('npm is not available');
+ expect(installer.spawnRuntimeInstaller).not.toHaveBeenCalled();
+ });
+
+ // The runtime is a request value, so an unknown id must be rejected before a
+ // child is spawned — the installer table is the only source of commands.
+ it('rejects an unknown runtime without probing or spawning', async () => {
+ const response = await request(app()).post('/api/providers/runtimes/install?runtime=rm-rf');
+
+ expect(response.status).toBe(400);
+ expect(installer.getProviderRuntimeStatus).not.toHaveBeenCalled();
+ expect(installer.spawnRuntimeInstaller).not.toHaveBeenCalled();
+ });
+
+ // A deployed client/dist can lag the server across an upgrade, so the
+ // OpenCode-only endpoints keep answering in their original shape.
+ it('keeps the legacy OpenCode status endpoint answering', async () => {
+ installer.getProviderRuntimeStatus.mockResolvedValueOnce(statusOf('opencode'));
+
+ const response = await request(app()).get('/api/providers/opencode/installation');
+
+ expect(response.status).toBe(200);
+ expect(response.body).toEqual({ installed: false, npmAvailable: true });
+ });
+
+ it('routes the legacy OpenCode install POST through the shared installer', async () => {
+ const child = makeChild();
+ installer.getProviderRuntimeStatus
+ .mockResolvedValueOnce(statusOf('opencode'))
+ .mockResolvedValueOnce(statusOf('opencode', { installed: true }));
+ installer.spawnRuntimeInstaller.mockReturnValueOnce(child);
+
+ const responsePromise = request(app()).post('/api/providers/opencode/install').then((response) => response);
+ await vi.waitFor(() => expect(installer.spawnRuntimeInstaller).toHaveBeenCalledWith('opencode'));
+ child.stdout.end();
+ child.stderr.end();
+ child.emit('close', 0);
+ const response = await responsePromise;
+
+ expect(response.status).toBe(200);
+ expect(response.text).toContain('OpenCode CLI is installed and available to PortOS.');
+ });
+});
diff --git a/server/services/opencodeInstaller.js b/server/services/opencodeInstaller.js
deleted file mode 100644
index 17360a8756..0000000000
--- a/server/services/opencodeInstaller.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * OpenCode CLI availability and installation.
- *
- * The Providers page owns the user gesture; this module deliberately exposes
- * only one fixed npm invocation, never a user-supplied package or command.
- * That keeps the install surface as narrow as the agent runner's command
- * allowlist while letting a missing OpenCode provider become self-service.
- */
-
-import { spawn } from '../lib/childProcess.js';
-import { killProcessTree, prepareCliSpawn } from '../lib/bufferedSpawn.js';
-import { commandExists } from '../lib/commandExists.js';
-import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
-
-const IS_WIN = process.platform === 'win32';
-
-export const OPENCODE_COMMAND = 'opencode';
-export const OPENCODE_NPM_PACKAGE = 'opencode-ai@latest';
-export const OPENCODE_NPM_INSTALL_ARGS = Object.freeze([
- 'install',
- '--global',
- // PortOS pins ignore-scripts=true in its project .npmrc. OpenCode's package
- // needs its postinstall to install the runnable CLI, so opt in explicitly for
- // this fixed, user-triggered package install rather than weakening the repo
- // default for every dependency.
- '--ignore-scripts=false',
- // npm's carriage-return progress renderer can emit hundreds of repaint
- // frames per second. The installer streams stdout to the browser, so keep
- // the useful package messages without turning the modal into a re-render
- // storm.
- '--no-progress',
- OPENCODE_NPM_PACKAGE,
-]);
-
-/**
- * Report only runnable availability, never the discovered absolute paths.
- * Paths can contain the machine account name and are not useful to the browser;
- * the boolean is the exact question the Providers page needs to answer.
- */
-export async function getOpenCodeInstallStatus({ findCommand = findCommandOnPath, probeCommand = commandExists } = {}) {
- const [opencode, npm] = await Promise.all([
- findCommand(OPENCODE_COMMAND),
- findCommand('npm'),
- ]);
- // `where opencode` can select npm's extensionless POSIX shim before the
- // working `.cmd` wrapper on Windows. The filesystem resolver gives us the
- // real executable; prepareCliSpawn then probes that same safe launch shape.
- const versionProbe = opencode ? prepareCliSpawn(opencode, ['--version']) : null;
- return {
- installed: Boolean(versionProbe) && Boolean(await probeCommand(versionProbe.command, versionProbe.args)),
- npmAvailable: Boolean(npm),
- };
-}
-
-/**
- * Start the one supported OpenCode install command with no shell interpolation.
- * `prepareCliSpawn` handles npm's Windows .cmd shim without falling back to
- * unsafe `shell: true`, and the returned child stays owned by the SSE route.
- */
-export function spawnOpenCodeInstaller({ spawnImpl = spawn } = {}) {
- const env = safeChildProcessEnv();
- const { command, args } = prepareCliSpawn('npm', OPENCODE_NPM_INSTALL_ARGS, env);
- return spawnImpl(command, args, safeChildProcessOptions({
- env,
- shell: false,
- stdio: ['ignore', 'pipe', 'pipe'],
- // npm can run package lifecycle children. Give the POSIX install its own
- // group so closing the modal stops that entire install, not just npm.
- detached: !IS_WIN,
- }));
-}
-
-/** Terminate the npm child and descendants when the installer modal closes. */
-export function stopOpenCodeInstaller(child) {
- if (!child?.pid || child.killed) return;
- killProcessTree(child, 'SIGTERM', { processGroup: !IS_WIN });
-}
diff --git a/server/services/opencodeInstaller.test.js b/server/services/opencodeInstaller.test.js
deleted file mode 100644
index 28e721b256..0000000000
--- a/server/services/opencodeInstaller.test.js
+++ /dev/null
@@ -1,60 +0,0 @@
-import { describe, expect, it, vi } from 'vitest';
-import {
- getOpenCodeInstallStatus,
- OPENCODE_NPM_INSTALL_ARGS,
- spawnOpenCodeInstaller,
-} from './opencodeInstaller.js';
-
-describe('OpenCode installer', () => {
- it('reports runnable availability as booleans without returning local paths', async () => {
- const findCommand = vi.fn(async (command) => command === 'opencode' ? '/example/opencode' : null);
- const probeCommand = vi.fn(async () => true);
-
- await expect(getOpenCodeInstallStatus({ findCommand, probeCommand })).resolves.toEqual({
- installed: true,
- npmAvailable: false,
- });
- expect(findCommand).toHaveBeenCalledWith('opencode');
- expect(findCommand).toHaveBeenCalledWith('npm');
- expect(probeCommand).toHaveBeenCalledWith('/example/opencode', ['--version']);
- });
-
- it('reports a PATH-resolved but broken OpenCode CLI as unavailable', async () => {
- const findCommand = vi.fn(async (command) => command === 'opencode' ? '/example/opencode' : '/example/npm');
- const probeCommand = vi.fn(async () => false);
-
- await expect(getOpenCodeInstallStatus({ findCommand, probeCommand })).resolves.toEqual({
- installed: false,
- npmAvailable: true,
- });
- expect(probeCommand).toHaveBeenCalledWith('/example/opencode', ['--version']);
- });
-
- it('spawns only the fixed npm global package install without a shell', () => {
- const spawnImpl = vi.fn(() => ({ pid: 123 }));
-
- spawnOpenCodeInstaller({ spawnImpl });
-
- const [command, args, options] = spawnImpl.mock.calls[0];
- if (process.platform === 'win32') {
- // Windows must launch npm's .cmd shim through cmd.exe because Node
- // rejects direct .cmd spawns when shell:false.
- expect(command).toBe('cmd.exe');
- expect(args).toEqual([
- '/c',
- expect.stringMatching(/npm\.cmd$/i),
- ...OPENCODE_NPM_INSTALL_ARGS,
- ]);
- } else {
- expect(command).toBe('npm');
- expect(args).toEqual(OPENCODE_NPM_INSTALL_ARGS);
- }
- expect(options).toEqual(expect.objectContaining({
- shell: false,
- stdio: ['ignore', 'pipe', 'pipe'],
- detached: process.platform !== 'win32',
- }));
- expect(OPENCODE_NPM_INSTALL_ARGS).toContain('--no-progress');
- expect(OPENCODE_NPM_INSTALL_ARGS).toContain('--ignore-scripts=false');
- });
-});
diff --git a/server/services/providerRuntimeInstaller.js b/server/services/providerRuntimeInstaller.js
new file mode 100644
index 0000000000..0012e1e374
--- /dev/null
+++ b/server/services/providerRuntimeInstaller.js
@@ -0,0 +1,297 @@
+/**
+ * Provider runtime (CLI) availability and installation.
+ *
+ * A CLI/TUI provider is only as usable as the binary it shells out to, so the
+ * AI Providers page asks this module "is `codex` runnable, and can PortOS
+ * install it for you?" per provider card. Generalized from the OpenCode-only
+ * installer (#4143 follow-up) so every provider whose runtime PortOS can
+ * install gets the same small status + Install affordance instead of one
+ * hard-coded banner for OpenCode.
+ *
+ * The Providers page owns the user gesture; this module exposes only a fixed
+ * per-runtime invocation from the table below, never a user-supplied package,
+ * URL, or command. A request names a runtime *id* — anything not in the table
+ * is rejected before a child is spawned — which keeps the install surface as
+ * narrow as the agent runner's command allowlist while letting a missing CLI
+ * become self-service.
+ *
+ * The binary each row installs comes from `PROVIDER_VENDORS` rather than a
+ * second hand-typed list of CLI names (#3618's rule — one vendor row, not N
+ * copies); `providerRuntimeInstaller.test.js` fails if a vendor ever lands
+ * there without an install row here.
+ *
+ * Install kinds:
+ * - `npm` — one fixed `npm install --global <package>`.
+ * - `script` — the vendor's own published POSIX install script, piped to bash
+ * (the same shape `localLlm.js` uses for Ollama on Linux). This
+ * *is* remote code by design: it's the install path these two
+ * vendors publish, and no request value reaches the command. Not
+ * offered on Windows, where they ship a separate PowerShell
+ * script PortOS deliberately does not run for the user.
+ *
+ * Ollama and LM Studio are deliberately absent: the Local LLM settings tab owns
+ * their install (it also starts the service afterwards, and knows that a macOS
+ * app bundle with no `lms` shim still counts as installed). The Providers page
+ * links there for those two instead of re-probing them here.
+ */
+
+import { spawn } from '../lib/childProcess.js';
+import { killProcessTree, prepareCliSpawn } from '../lib/bufferedSpawn.js';
+import { commandExists } from '../lib/commandExists.js';
+import { findCommandOnPath, safeChildProcessEnv, safeChildProcessOptions } from '../lib/processEnv.js';
+import { PROVIDER_VENDORS } from '../lib/providerVendors.js';
+
+const IS_WIN = process.platform === 'win32';
+
+/**
+ * Flags shared by every global npm runtime install.
+ *
+ * PortOS pins ignore-scripts=true in its project .npmrc, and these installs run
+ * from the PortOS working directory. Every one of these CLIs ships its runnable
+ * binary from a postinstall script, so opt in explicitly for these fixed,
+ * user-triggered package installs — which is what the same command in the
+ * user's own shell would do — rather than weakening the repo default for every
+ * dependency.
+ *
+ * npm's carriage-return progress renderer can emit hundreds of repaint frames
+ * per second, and the installer streams stdout to the browser — `--no-progress`
+ * keeps the useful package messages without turning the modal into a re-render
+ * storm.
+ */
+export const NPM_GLOBAL_INSTALL_FLAGS = Object.freeze([
+ 'install',
+ '--global',
+ '--ignore-scripts=false',
+ '--no-progress',
+]);
+
+/** The host tool each install kind shells out through. */
+const INSTALL_TOOL = Object.freeze({ npm: 'npm', script: 'curl' });
+
+/**
+ * How long a probed status stays good. Availability changes only when someone
+ * installs, upgrades, or removes a CLI, and probing is expensive: each runtime
+ * costs a PATH scan plus a `--version` child process, and the bundled-JS CLIs
+ * take seconds to answer. The AI Providers page reloads its whole payload after
+ * every provider mutation (enable, save, delete, add-sample), so without this a
+ * single toggle re-spawns every CLI on the host. Same shape and reasoning as
+ * `getReviewerCliInstalled()`'s cache in `codeReview.js`.
+ */
+const STATUS_TTL_MS = 60_000;
+
+/**
+ * Matches `codeReview.js`'s `REVIEWER_CLI_PROBE_TIMEOUT_MS` for these same
+ * binaries: `commandExists`'s 5s default is sized for lightweight tools like
+ * `brew --version` and previously clocked the heavier agentic CLIs as falsely
+ * uninstalled under a cold start — which here would offer an install for a CLI
+ * that is already there.
+ */
+const PROBE_TIMEOUT_MS = 15_000;
+
+/** One row per installable provider runtime, keyed by its vendor row. */
+const RUNTIME_ROWS = [
+ {
+ vendor: 'claude',
+ label: 'Claude Code CLI',
+ install: { kind: 'npm', package: '@anthropic-ai/claude-code@latest' },
+ docsUrl: 'https://docs.claude.com/en/docs/claude-code/setup',
+ },
+ {
+ vendor: 'codex',
+ label: 'Codex CLI',
+ install: { kind: 'npm', package: '@openai/codex@latest' },
+ docsUrl: 'https://developers.openai.com/codex/cli',
+ },
+ {
+ vendor: 'opencode',
+ label: 'OpenCode CLI',
+ install: { kind: 'npm', package: 'opencode-ai@latest' },
+ docsUrl: 'https://opencode.ai/docs',
+ },
+ {
+ vendor: 'grok',
+ label: 'Grok Build CLI',
+ install: { kind: 'npm', package: '@xai-official/grok@latest' },
+ docsUrl: 'https://x.ai/cli',
+ },
+ {
+ vendor: 'kimi',
+ label: 'Kimi Code CLI',
+ install: { kind: 'npm', package: '@kimi-code/cli@latest' },
+ docsUrl: 'https://moonshotai.github.io/kimi-cli/',
+ },
+ {
+ vendor: 'antigravity',
+ label: 'Antigravity CLI',
+ // Antigravity ships a single compiled binary, not an npm package.
+ install: { kind: 'script', url: 'https://antigravity.google/cli/install.sh' },
+ docsUrl: 'https://antigravity.google/docs/cli/install',
+ },
+ {
+ vendor: 'cursor',
+ label: 'Cursor Agent CLI',
+ install: { kind: 'script', url: 'https://cursor.com/install' },
+ docsUrl: 'https://cursor.com/docs/cli/installation',
+ },
+];
+
+const vendorCommand = (vendorId) => {
+ const command = PROVIDER_VENDORS.find((vendor) => vendor.id === vendorId)?.inferredCommand;
+ // A renamed vendor row must fail loudly at boot, not silently drop a card's
+ // install button.
+ if (!command) throw new Error(`providerRuntimeInstaller: no PROVIDER_VENDORS row for "${vendorId}"`);
+ return command;
+};
+
+/**
+ * The runtime table the routes serve. `id` IS the binary name, so a provider
+ * card looks its runtime up straight from its `command` with no second mapping.
+ */
+export const PROVIDER_RUNTIMES = Object.freeze(RUNTIME_ROWS.map((row) => Object.freeze({
+ ...row,
+ id: vendorCommand(row.vendor),
+ command: vendorCommand(row.vendor),
+})));
+
+const RUNTIMES_BY_ID = new Map(PROVIDER_RUNTIMES.map((runtime) => [runtime.id, runtime]));
+
+// id → { at, status }
+const statusCache = new Map();
+
+/** The runtime row for an id, or `null` for anything not in the table. */
+export function getProviderRuntime(id) {
+ return (typeof id === 'string' && RUNTIMES_BY_ID.get(id)) || null;
+}
+
+async function probeRuntimeStatus(runtime, findCommand, probeCommand) {
+ const kind = runtime.install.kind;
+ const tool = INSTALL_TOOL[kind];
+
+ const [resolved, toolPath] = await Promise.all([findCommand(runtime.command), findCommand(tool)]);
+
+ // `where <cmd>` can select npm's extensionless POSIX shim before the working
+ // `.cmd` wrapper on Windows. The filesystem resolver gives us the real
+ // executable; prepareCliSpawn then probes that same safe launch shape.
+ const versionProbe = resolved ? prepareCliSpawn(resolved, ['--version']) : null;
+ const installed = Boolean(versionProbe)
+ && Boolean(await probeCommand(versionProbe.command, versionProbe.args, { timeoutMs: PROBE_TIMEOUT_MS }));
+
+ // Windows-only gap: the script-installed vendors publish a PowerShell
+ // installer there, which PortOS deliberately does not run for the user.
+ const windowsScriptOnly = kind === 'script' && IS_WIN;
+ const installable = Boolean(toolPath) && !windowsScriptOnly;
+ const blockedReason = installable ? null
+ : windowsScriptOnly
+ ? `${runtime.label} installs from a PowerShell script on Windows. Follow the vendor instructions, then reload this page.`
+ : `${tool} is not available on PortOS's PATH, so this host cannot install ${runtime.label} from this page.`;
+
+ return {
+ id: runtime.id,
+ label: runtime.label,
+ command: runtime.command,
+ installed,
+ method: kind,
+ installable,
+ blockedReason,
+ docsUrl: runtime.docsUrl,
+ };
+}
+
+/**
+ * Report only runnable availability, never the discovered absolute paths.
+ * Paths can contain the machine account name and are not useful to the browser;
+ * the booleans are the exact questions the Providers page needs answered.
+ *
+ * `installable` is "can PortOS run this install right now" — false when the
+ * required tool is missing (npm, curl) or the platform has no supported script
+ * — and `blockedReason` says why, so the card can explain a disabled button
+ * instead of failing at click time.
+ *
+ * Pass `fresh: true` to bypass the TTL cache. The install route must, on both
+ * sides of the install: a cached "installed" would skip an install the user
+ * still needs, and a cached pre-install probe would fail the post-install
+ * verification of a CLI that is now perfectly runnable.
+ */
+export async function getProviderRuntimeStatus(id, { findCommand, probeCommand, fresh = false } = {}) {
+ const runtime = getProviderRuntime(id);
+ if (!runtime) return null;
+ const cached = statusCache.get(id);
+ if (!fresh && cached && Date.now() - cached.at < STATUS_TTL_MS) return cached.status;
+ const status = await probeRuntimeStatus(runtime, findCommand || findCommandOnPath, probeCommand || commandExists);
+ statusCache.set(id, { at: Date.now(), status });
+ return status;
+}
+
+/** Every runtime's status, keyed by id — one round trip for the Providers page. */
+export async function getProviderRuntimeStatuses(deps = {}) {
+ // One PATH scan per distinct binary for the whole batch: five rows resolve
+ // `npm` and two resolve `curl`, and the resolver hits the filesystem.
+ const findCommand = memoizePerBatch(deps.findCommand || findCommandOnPath);
+ const statuses = await Promise.all(
+ PROVIDER_RUNTIMES.map((runtime) => getProviderRuntimeStatus(runtime.id, { ...deps, findCommand })),
+ );
+ return Object.fromEntries(statuses.map((status) => [status.id, status]));
+}
+
+function memoizePerBatch(findCommand) {
+ const seen = new Map();
+ return (command) => {
+ if (!seen.has(command)) seen.set(command, findCommand(command));
+ return seen.get(command);
+ };
+}
+
+/** Test-only: drop cached statuses so the next read re-probes. */
+export function __resetRuntimeStatusCache() {
+ statusCache.clear();
+}
+
+/**
+ * The one supported install invocation for a runtime, as an argv pair. Built
+ * entirely from the table above — no request value reaches a shell word.
+ */
+export function buildRuntimeInstallCommand(id) {
+ const runtime = getProviderRuntime(id);
+ if (!runtime) return null;
+ if (runtime.install.kind === 'npm') {
+ return { command: 'npm', args: [...NPM_GLOBAL_INSTALL_FLAGS, runtime.install.package] };
+ }
+ // `-fsSL` keeps curl quiet on success and non-zero on an HTTP error, so a 404
+ // page can't be piped into bash as a script. POSIX only — a Windows
+ // enablement would need `resolveBashBinary()` (`server/lib/bashResolver.js`),
+ // since a bare `bash` there resolves to WSL.
+ return { command: 'bash', args: ['-c', `curl -fsSL ${runtime.install.url} | bash`] };
+}
+
+/** A human-readable one-liner for the install log ("Running npm install …"). */
+export function describeRuntimeInstall(id) {
+ const invocation = buildRuntimeInstallCommand(id);
+ return invocation ? `${invocation.command} ${invocation.args.join(' ')}` : null;
+}
+
+/**
+ * Start a runtime's fixed install command with no request input in its argv.
+ * `prepareCliSpawn` handles npm's Windows .cmd shim without falling back to
+ * unsafe `shell: true`, and the returned child stays owned by the SSE route.
+ */
+export function spawnRuntimeInstaller(id, { spawnImpl = spawn } = {}) {
+ const invocation = buildRuntimeInstallCommand(id);
+ if (!invocation) return null;
+ const env = safeChildProcessEnv();
+ const { command, args } = prepareCliSpawn(invocation.command, invocation.args, env);
+ return spawnImpl(command, args, safeChildProcessOptions({
+ env,
+ shell: false,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ // npm and vendor install scripts both run lifecycle children. Give the
+ // POSIX install its own group so closing the modal stops that entire
+ // install, not just the parent.
+ detached: !IS_WIN,
+ }));
+}
+
+/** Terminate the installer child and descendants when the installer modal closes. */
+export function stopRuntimeInstaller(child) {
+ if (!child?.pid || child.killed) return;
+ killProcessTree(child, 'SIGTERM', { processGroup: !IS_WIN });
+}
diff --git a/server/services/providerRuntimeInstaller.test.js b/server/services/providerRuntimeInstaller.test.js
new file mode 100644
index 0000000000..93223499d9
--- /dev/null
+++ b/server/services/providerRuntimeInstaller.test.js
@@ -0,0 +1,167 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { PROVIDER_VENDORS } from '../lib/providerVendors.js';
+import {
+ buildRuntimeInstallCommand,
+ getProviderRuntime,
+ getProviderRuntimeStatus,
+ getProviderRuntimeStatuses,
+ NPM_GLOBAL_INSTALL_FLAGS,
+ PROVIDER_RUNTIMES,
+ spawnRuntimeInstaller,
+ __resetRuntimeStatusCache,
+} from './providerRuntimeInstaller.js';
+
+const IS_WIN = process.platform === 'win32';
+
+describe('provider runtime installer', () => {
+ beforeEach(() => {
+ __resetRuntimeStatusCache();
+ });
+
+ it('reports runnable availability as booleans without returning local paths', async () => {
+ const findCommand = vi.fn(async (command) => command === 'opencode' ? '/example/opencode' : '/example/npm');
+ const probeCommand = vi.fn(async () => true);
+
+ const status = await getProviderRuntimeStatus('opencode', { findCommand, probeCommand });
+
+ expect(status).toEqual({
+ id: 'opencode',
+ label: 'OpenCode CLI',
+ command: 'opencode',
+ installed: true,
+ method: 'npm',
+ installable: true,
+ blockedReason: null,
+ docsUrl: expect.stringContaining('http'),
+ });
+ expect(findCommand).toHaveBeenCalledWith('opencode');
+ expect(findCommand).toHaveBeenCalledWith('npm');
+ // The resolved executable path can carry the host account name.
+ expect(JSON.stringify(status)).not.toContain('/example/');
+ });
+
+ // A cold agentic CLI can take seconds to answer; commandExists's 5s default
+ // clocked these as uninstalled, which here would offer a redundant install.
+ it('probes with the longer agentic-CLI timeout', async () => {
+ const probeCommand = vi.fn(async () => false);
+ await getProviderRuntimeStatus('codex', { findCommand: async () => '/example/codex', probeCommand });
+
+ expect(probeCommand).toHaveBeenCalledWith('/example/codex', ['--version'], { timeoutMs: 15_000 });
+ });
+
+ it('reports a PATH-resolved but broken CLI as unavailable', async () => {
+ const status = await getProviderRuntimeStatus('codex', {
+ findCommand: async () => '/example/codex',
+ probeCommand: async () => false,
+ });
+
+ expect(status.installed).toBe(false);
+ expect(status.installable).toBe(true);
+ });
+
+ it('blocks an npm-backed install with a reason when npm is missing', async () => {
+ const status = await getProviderRuntimeStatus('claude', {
+ findCommand: async (command) => command === 'npm' ? null : '/example/claude',
+ probeCommand: async () => true,
+ });
+
+ expect(status.installable).toBe(false);
+ expect(status.blockedReason).toContain('npm is not available');
+ });
+
+ it('gates a script-backed install on curl and the platform', async () => {
+ const probeCommand = vi.fn(async () => false);
+ const withCurl = await getProviderRuntimeStatus('cursor-agent', { findCommand: async () => '/example/curl', probeCommand });
+ const withoutCurl = await getProviderRuntimeStatus('cursor-agent', { fresh: true, findCommand: async () => null, probeCommand });
+
+ expect(withCurl.method).toBe('script');
+ expect(withCurl.installable).toBe(!IS_WIN);
+ expect(withoutCurl.installable).toBe(false);
+ expect(withoutCurl.blockedReason).toBeTruthy();
+ });
+
+ it('returns nothing for a runtime that is not in the table', async () => {
+ expect(getProviderRuntime('rm-rf')).toBeNull();
+ expect(getProviderRuntime(undefined)).toBeNull();
+ expect(buildRuntimeInstallCommand('rm-rf')).toBeNull();
+ expect(spawnRuntimeInstaller('rm-rf', { spawnImpl: () => { throw new Error('must not spawn'); } })).toBeNull();
+ await expect(getProviderRuntimeStatus('rm-rf', { findCommand: async () => null, probeCommand: async () => false })).resolves.toBeNull();
+ });
+
+ it('answers every runtime in one keyed map, resolving each install tool once', async () => {
+ const findCommand = vi.fn(async () => null);
+ const statuses = await getProviderRuntimeStatuses({ findCommand, probeCommand: async () => false });
+
+ expect(Object.keys(statuses).sort()).toEqual(PROVIDER_RUNTIMES.map((runtime) => runtime.id).sort());
+ expect(statuses.agy.installed).toBe(false);
+ // Five rows install through npm and two through curl — one PATH scan each.
+ expect(findCommand.mock.calls.filter(([command]) => command === 'npm')).toHaveLength(1);
+ expect(findCommand.mock.calls.filter(([command]) => command === 'curl')).toHaveLength(1);
+ });
+
+ // The AI Providers page re-reads this after every provider mutation, and each
+ // miss costs a child process per runtime.
+ it('serves repeat reads from the TTL cache and re-probes on demand', async () => {
+ const findCommand = async () => '/example/bin';
+ const missing = vi.fn(async () => false);
+ const present = vi.fn(async () => true);
+
+ const first = await getProviderRuntimeStatus('codex', { findCommand, probeCommand: missing });
+ const second = await getProviderRuntimeStatus('codex', { findCommand, probeCommand: present });
+ expect(second).toBe(first);
+ expect(present).not.toHaveBeenCalled();
+
+ // `fresh` must bypass it — the install route verifies a just-installed CLI
+ // against a cache entry it primed itself seconds earlier.
+ const third = await getProviderRuntimeStatus('codex', { fresh: true, findCommand, probeCommand: present });
+ expect(third.installed).toBe(true);
+ expect(await getProviderRuntimeStatus('codex', { findCommand, probeCommand: missing })).toBe(third);
+ });
+
+ // The install surface is exactly the table: no request value ever reaches a
+ // package name, a URL, or a shell word.
+ it('builds only fixed invocations from the runtime table', () => {
+ expect(buildRuntimeInstallCommand('grok')).toEqual({
+ command: 'npm',
+ args: [...NPM_GLOBAL_INSTALL_FLAGS, '@xai-official/grok@latest'],
+ });
+ expect(buildRuntimeInstallCommand('agy')).toEqual({
+ command: 'bash',
+ args: ['-c', 'curl -fsSL https://antigravity.google/cli/install.sh | bash'],
+ });
+ });
+
+ it('spawns the global npm package install without a shell', () => {
+ const spawnImpl = vi.fn(() => ({ pid: 123 }));
+
+ spawnRuntimeInstaller('opencode', { spawnImpl });
+
+ const [command, args, options] = spawnImpl.mock.calls[0];
+ if (IS_WIN) {
+ // Windows must launch npm's .cmd shim through cmd.exe because Node
+ // rejects direct .cmd spawns when shell:false.
+ expect(command).toBe('cmd.exe');
+ expect(args.slice(0, 2)).toEqual(['/c', expect.stringMatching(/npm\.cmd$/i)]);
+ } else {
+ expect(command).toBe('npm');
+ }
+ expect(options).toEqual(expect.objectContaining({
+ shell: false,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ detached: !IS_WIN,
+ }));
+ });
+
+ // #3618's rule: a vendor is one row. A new coding-agent CLI must not land in
+ // the runner allowlist and argv builders while silently having no way to be
+ // installed from the Providers page.
+ it('offers an install for every live CLI vendor', () => {
+ const installable = new Set(PROVIDER_RUNTIMES.map((runtime) => runtime.command));
+ for (const vendor of PROVIDER_VENDORS) {
+ // The legacy gemini-cli row is deliberately incomplete — Gemini CLI was
+ // migrated to Antigravity and ships no installable binary of its own.
+ if (vendor.id === 'gemini-legacy') continue;
+ expect(installable).toContain(vendor.inferredCommand);
+ }
+ });
+});