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

group AI provider cards by readiness so a missing CLI or API key is visible at a glance

[._.]/ Adam Eivyaf722a977d62
diff --git a/client/src/components/providers/ProviderCard.jsx b/client/src/components/providers/ProviderCard.jsx
new file mode 100644
index 0000000000..79b4d9025e
--- /dev/null
+++ b/client/src/components/providers/ProviderCard.jsx
@@ -0,0 +1,339 @@
+/**
+ * One AI-provider card on the Settings → AI Providers page.
+ *
+ * Lives here rather than inline on the page because the page also owns the
+ * provider EDITOR, the sample-provider panel and the ad-hoc runner — the card
+ * is ~250 lines of its own and was already three `map`s deep once the page
+ * started grouping cards by readiness.
+ *
+ * The card renders no derivation of its own: `readiness`, `runtime` and
+ * `status` all arrive resolved, so what colors the border, what the badge says,
+ * and which section the page filed the card under can never disagree.
+ */
+
+import {
+ PROVIDER_READINESS,
+ effectiveModelContextWindow,
+ isApiProvider,
+ isGrokBuildCli,
+ isLocalEndpoint,
+ isOrcaRouterBackedProvider,
+ isProcessProvider,
+ isRunnerAllowedCommand,
+ isTuiProvider,
+ providerTypeClass,
+ supportsModelRefresh,
+} from '../../utils/providers';
+import { formatContextLength } from '../../utils/formatters';
+import ProviderRuntimeStatus from './ProviderRuntimeStatus';
+import { GrokUploadWarning, OrcaRouterKeyHint } from './ProviderNotices';
+
+// One phrasing for "this command isn't on the CoS Agent Runner's allowlist".
+// The editor states the same thing in its own inline banner, in prose.
+const RUNNER_NOT_ALLOWED_HINT = 'This command is not on the CoS Agent Runner’s allowlist, so /spawn and /spawn-tui will refuse it. The provider still works everywhere else (direct spawn, chat, pipeline). The allowlist is curated in the PortOS source, not in this form.';
+
+// Card presentation per readiness state. Exactly ONE border-color utility is
+// emitted per card — Tailwind resolves same-specificity color utilities by
+// stylesheet order, not by the order they appear in `className` — so the
+// "default provider" highlight is a ring rather than a competing border color.
+export const READINESS_STYLES = {
+ [PROVIDER_READINESS.READY]: {
+ label: 'READY',
+ border: 'border-port-success/40',
+ badge: 'bg-port-success/20 text-port-success',
+ hint: 'Enabled, and every prerequisite is in place.',
+ },
+ [PROVIDER_READINESS.BENCHED]: {
+ label: 'BENCHED',
+ border: 'border-port-error/50',
+ badge: 'bg-port-error/20 text-port-error',
+ hint: 'Enabled, but benched after a failure — calls route to the fallback.',
+ },
+ [PROVIDER_READINESS.BLOCKED]: {
+ label: 'NEEDS SETUP',
+ border: 'border-port-warning/50',
+ badge: 'bg-port-warning/20 text-port-warning',
+ hint: 'Missing a prerequisite — install the CLI or add the API key to use it.',
+ },
+ [PROVIDER_READINESS.DISABLED]: {
+ label: 'DISABLED',
+ border: 'border-port-border',
+ badge: 'bg-gray-500/20 text-gray-400',
+ // Switched-off cards recede until hovered, so a long list reads as the
+ // handful of providers that are actually live.
+ dim: 'opacity-70 hover:opacity-100 transition-opacity',
+ hint: 'Ready to go, but switched off.',
+ },
+};
+
+export default function ProviderCard({
+ provider,
+ readiness,
+ runtime,
+ status,
+ isDefault,
+ providersById,
+ runnerAllowedCommands,
+ testResult,
+ refreshing,
+ recovering,
+ onTest,
+ onRefreshModels,
+ onToggleEnabled,
+ onSetActive,
+ onEdit,
+ onDelete,
+ onRecover,
+ onInstallRuntime,
+}) {
+ const style = READINESS_STYLES[readiness.state];
+ return (
+ <div
+ className={`bg-port-card border border-l-4 rounded-xl p-4 ${style.border} ${style.dim || ''} ${
+ isDefault ? 'ring-1 ring-port-accent/60' : ''
+ }`}
+ >
+ <div className="flex flex-col lg:flex-row lg:items-start justify-between gap-4">
+ <div className="flex-1 min-w-0">
+ <div className="flex flex-wrap items-center gap-2">
+ <h3 className="text-lg font-semibold text-white">{provider.name}</h3>
+ <span className={`text-xs px-2 py-0.5 rounded ${providerTypeClass(provider.type)}`}>
+ {provider.type.toUpperCase()}
+ </span>
+ {isDefault && (
+ <span className="text-xs px-2 py-0.5 rounded bg-port-accent/20 text-port-accent">
+ DEFAULT
+ </span>
+ )}
+ {provider.llamaBacked && (
+ <span className="text-xs px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30">
+ LLAMA.CPP / DFLASH
+ </span>
+ )}
+ {provider.mtplxBacked && (
+ <span className="text-xs px-2 py-0.5 rounded bg-blue-500/20 text-blue-300 border border-blue-500/30">
+ MTPLX
+ </span>
+ )}
+ {/* One badge for the card's readiness — the same state that
+ colors its border and decides which section it sits in.
+ BENCHED covers what used to render as UNAVAILABLE: an
+ enabled provider sidelined after a failure (usage limit,
+ model-not-found, auth) in favor of its fallback. */}
+ <span
+ className={`text-xs px-2 py-0.5 rounded ${style.badge}`}
+ title={readiness.state === PROVIDER_READINESS.BLOCKED
+ ? readiness.missing.map(m => m.label).join(' · ')
+ : (status?.message || style.hint)}
+ >
+ {style.label}
+ {readiness.state === PROVIDER_READINESS.BENCHED && status?.reason
+ ? ` · ${status.reason}`
+ : ''}
+ </span>
+ {/* A blocked provider's toggle is not what's stopping it, so
+ spell out which way it sits rather than leaving the reader
+ to infer it from the Enable/Disable button. */}
+ {readiness.state === PROVIDER_READINESS.BLOCKED && (
+ <span className="text-xs px-2 py-0.5 rounded bg-gray-500/20 text-gray-400">
+ {provider.enabled ? 'SWITCHED ON' : 'SWITCHED OFF'}
+ </span>
+ )}
+ {/* Off the CoS Agent Runner's exec allowlist: the provider still
+ works for direct spawn, it just can't be launched by /spawn
+ or /spawn-tui. Informational — never a save-time rejection. */}
+ {isProcessProvider(provider) && isRunnerAllowedCommand(provider.command, runnerAllowedCommands) === false && (
+ <span
+ className="text-xs px-2 py-0.5 rounded bg-port-warning/20 text-port-warning"
+ title={RUNNER_NOT_ALLOWED_HINT}
+ >
+ NO AGENT RUNNER
+ </span>
+ )}
+ </div>
+
+ <ProviderRuntimeStatus
+ className="mt-2"
+ runtime={runtime}
+ onInstall={onInstallRuntime}
+ />
+
+ {provider.enabled && status?.available === false && (
+ <div className="mt-2 text-xs rounded border border-port-error/40 bg-port-error/10 px-3 py-2 text-port-error space-y-1">
+ <p className="break-words">
+ <span className="font-semibold">Benched ({status?.reason || 'unknown'})</span>
+ {status?.timeUntilRecovery ? ` — auto-retries in ${status.timeUntilRecovery}` : ''}
+ . Calls route to the fallback until then.
+ </p>
+ {status?.message && (
+ <p className="break-words text-port-error/80">Why: {status.message}</p>
+ )}
+ <button
+ type="button"
+ onClick={() => onRecover(provider.id)}
+ disabled={recovering}
+ className="mt-1 px-2 py-0.5 rounded bg-port-error/20 hover:bg-port-error/30 disabled:opacity-50 text-port-error"
+ >
+ {recovering ? 'Clearing…' : 'Recover now'}
+ </button>
+ </div>
+ )}
+
+ <div className="mt-2 text-sm text-gray-400 space-y-1">
+ {provider.llamaBacked && (
+ <p className="text-xs text-purple-300/90">
+ Local llama.cpp / llama-server harness (endpoint: <code className="text-purple-200">{provider.endpoint}</code>) — supports DFlash 2 speculative drafting.
+ </p>
+ )}
+ {isProcessProvider(provider) && (
+ <p className="break-words">Command: <code className="text-gray-300 break-all">{provider.command} {provider.args?.join(' ')}</code></p>
+ )}
+ {isApiProvider(provider) && (
+ <p className="break-words">Endpoint: <code className="text-gray-300 break-all">{provider.endpoint}</code></p>
+ )}
+ {/* API-type providers auth solely via the stored apiKey (sent as a
+ Bearer header) — surface its state here so "where does the key
+ go?" is answered from the card, not by spelunking the form. */}
+ {isApiProvider(provider) && (
+ provider.hasApiKey ? (
+ <p className="text-xs">API key: <span className="text-port-success">set</span></p>
+ ) : isLocalEndpoint(provider.endpoint) ? (
+ <p className="text-xs">API key: <span className="text-gray-500">none (local endpoint)</span></p>
+ ) : (
+ <p className="text-xs">API key: <span className="text-port-warning">not set — Edit this provider to paste one</span></p>
+ )
+ )}
+ {provider.models?.length > 0 && (
+ <p>Models: {provider.models.slice(0, 3).join(', ')}{provider.models.length > 3 ? ` +${provider.models.length - 3}` : ''}</p>
+ )}
+ {provider.defaultModel && (
+ <p className="break-words">Default: <code className="text-gray-300 break-all">{provider.defaultModel}</code></p>
+ )}
+ {provider.effort && (
+ <p className="break-words">Default effort: <code className="text-gray-300">{provider.effort}</code></p>
+ )}
+ {(() => {
+ const windowLabel = formatContextLength(effectiveModelContextWindow(provider, provider.defaultModel));
+ return windowLabel ? (
+ <p className="text-xs">
+ Context: <span className="text-gray-300">{windowLabel}</span>
+ {provider.contextWindow ? <span className="text-gray-500"> override</span> : null}
+ </p>
+ ) : null;
+ })()}
+ {(provider.lightModel || provider.mediumModel || provider.heavyModel) && (
+ <p className="text-xs">
+ Tiers:
+ {provider.lightModel && <span className="ml-1 text-port-success">{provider.lightModel}</span>}
+ {provider.mediumModel && <span className="ml-1 text-port-warning">{provider.mediumModel}</span>}
+ {provider.heavyModel && <span className="ml-1 text-port-error">{provider.heavyModel}</span>}
+ </p>
+ )}
+ {provider.headlessArgs?.length > 0 && (
+ <p className="text-xs break-words">
+ Headless: <code className="text-gray-300 break-all">{provider.headlessArgs.join(' ')}</code>
+ </p>
+ )}
+ {isTuiProvider(provider) && (
+ <p className="text-xs break-words">
+ TUI: paste delay <span className="text-gray-300">{provider.tuiPromptDelayMs || 2500}ms</span>, completion by sentinel, process exit, or explicit failure
+ </p>
+ )}
+ {provider.fallbackProvider && (
+ <p className="text-xs">
+ Fallback: <span className="text-port-accent">{providersById[provider.fallbackProvider]?.name || provider.fallbackProvider}</span>
+ {provider.fallbackModel && <span className="ml-1 text-gray-300">({provider.fallbackModel})</span>}
+ </p>
+ )}
+ {provider.envVars && Object.keys(provider.envVars).length > 0 && (
+ <div className="text-xs mt-1">
+ <span className="text-gray-400">Env:</span>
+ {Object.entries(provider.envVars).map(([k, v]) => (
+ <div key={k}>
+ <code className="ml-1 text-orange-400">
+ {k}={provider.secretEnvVars?.includes(k) ? '***' : v}
+ </code>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+
+ {isGrokBuildCli(provider) && <GrokUploadWarning className="mt-2" />}
+
+ {isOrcaRouterBackedProvider(provider) && (
+ <OrcaRouterKeyHint
+ sibling={providersById.orcarouter}
+ onEdit={onEdit}
+ className="mt-2"
+ />
+ )}
+
+ {testResult && !testResult.testing && (
+ <div className={`mt-2 text-sm ${testResult.success ? 'text-port-success' : 'text-port-error'}`}>
+ {testResult.success
+ ? `✓ Available${testResult.version ? ` (${testResult.version})` : ''}`
+ : `✗ ${testResult.error}`
+ }
+ </div>
+ )}
+ </div>
+
+ <div className="flex flex-wrap items-center gap-2">
+ <button
+ onClick={() => onTest(provider.id)}
+ disabled={testResult?.testing}
+ className="px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors disabled:opacity-50"
+ >
+ {testResult?.testing ? 'Testing...' : 'Test'}
+ </button>
+
+ {supportsModelRefresh(provider) && (
+ <button
+ onClick={() => onRefreshModels(provider.id)}
+ disabled={refreshing}
+ className="px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
+ title="Refresh available models"
+ >
+ {refreshing ? 'Refreshing...' : 'Refresh Models'}
+ </button>
+ )}
+
+ <button
+ onClick={() => onToggleEnabled(provider)}
+ className={`px-3 py-1.5 text-sm rounded transition-colors ${
+ provider.enabled
+ ? 'bg-port-warning/20 text-port-warning hover:bg-port-warning/30'
+ : 'bg-port-success/20 text-port-success hover:bg-port-success/30'
+ }`}
+ >
+ {provider.enabled ? 'Disable' : 'Enable'}
+ </button>
+
+ {!isDefault && provider.enabled && (
+ <button
+ onClick={() => onSetActive(provider.id)}
+ className="px-3 py-1.5 text-sm bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded transition-colors"
+ >
+ Set Default
+ </button>
+ )}
+
+ <button
+ onClick={() => onEdit(provider)}
+ className="px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors"
+ >
+ Edit
+ </button>
+
+ <button
+ onClick={() => onDelete(provider.id)}
+ className="px-3 py-1.5 text-sm bg-port-error/20 text-port-error hover:bg-port-error/30 rounded transition-colors"
+ >
+ Delete
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/providers/ProviderNotices.jsx b/client/src/components/providers/ProviderNotices.jsx
new file mode 100644
index 0000000000..433bc5c0fb
--- /dev/null
+++ b/client/src/components/providers/ProviderNotices.jsx
@@ -0,0 +1,61 @@
+/**
+ * The two credential/privacy notices a provider surface renders: the Grok Build
+ * CLI's repo-upload disclosure and the OpenCode OrcaRouter wrappers' "the key
+ * lives on the sibling API provider" hint.
+ *
+ * Shared because both the provider CARD and the provider EDITOR show them — the
+ * card so the state is visible at a glance, the editor so the user reads it
+ * before enabling. Keeping one copy is what stops the two from drifting.
+ */
+
+// Privacy disclosure for the Grok Build CLI/TUI: its harness uploads the entire
+// working repo to xAI (GCP) as it works unless the user opts out. Shown both on
+// the provider card and in the create/edit form (before enabling) — see
+// isGrokBuildCli for which providers match.
+export function GrokUploadWarning({ className = '' }) {
+ return (
+ <div className={`text-xs rounded-md border border-port-warning/40 bg-port-warning/10 text-port-warning px-2.5 py-2 leading-relaxed ${className}`}>
+ ⚠️ The Grok harness uploads your <span className="font-semibold">entire working repo</span> to
+ xAI (GCP) as it works. To keep your code local, add the following to{' '}
+ <code className="font-mono">~/.grok/config.toml</code> before enabling this provider:
+ <pre className="mt-1.5 whitespace-pre rounded bg-port-bg/60 px-2 py-1.5 font-mono text-[11px] text-port-warning">{`[harness]
+disable_codebase_upload = true`}</pre>
+ </div>
+ );
+}
+
+// The OpenCode OrcaRouter wrappers (opencode-orcarouter / -tui) keep no key of
+// their own — at spawn time the server copies the key from the sibling
+// `orcarouter` API provider. This answers "where do I put the API key?" from the
+// card/form: it's on the API provider, not here.
+export function OrcaRouterKeyHint({ sibling, className = '', onEdit }) {
+ const hasKey = Boolean(sibling?.hasApiKey);
+ return (
+ <div className={`text-xs rounded-md border border-port-border bg-port-bg/60 px-2.5 py-2 leading-relaxed ${className}`}>
+ <span className="text-gray-300">
+ API key is inherited from the <code className="font-mono">OrcaRouter</code> API provider
+ {" "}at run time — this wrapper has no key field of its own.
+ </span>
+ <p className="mt-1 text-gray-400">
+ You do not need to add an environment variable. PortOS supplies{' '}
+ <code className="font-mono">ORCAROUTER_API_KEY</code> to OpenCode automatically.
+ </p>
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ {hasKey ? (
+ <span className="text-port-success">OrcaRouter key: set</span>
+ ) : (
+ <span className="text-port-warning">OrcaRouter key: not set</span>
+ )}
+ {sibling && onEdit && (
+ <button
+ type="button"
+ onClick={() => onEdit(sibling)}
+ className="text-port-accent hover:text-port-accent/80 underline underline-offset-2"
+ >
+ Edit OrcaRouter API provider
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 44fbd8b8ad..5fe40fecf8 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -1,10 +1,10 @@
-import { useState, useEffect, useCallback } from 'react';
+import { useState, useEffect, useCallback, useMemo } from 'react';
import { Link } from 'react-router';
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, providerRuntimeKey } from '../utils/providers';
+import { filterSelectableModels, filterGenerationModels, isEmbeddingModel, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isGrokBuildCli, isLocalEndpoint, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, isOrcaRouterBackedProvider, providerRuntimeKey, providerReadiness, PROVIDER_READINESS } from '../utils/providers';
import useLocalModels from '../hooks/useLocalModels';
import BrailleSpinner from '../components/BrailleSpinner';
import EmptyState from '../components/EmptyState';
@@ -22,68 +22,41 @@ 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';
+import ProviderCard from '../components/providers/ProviderCard';
+import { GrokUploadWarning, OrcaRouterKeyHint } from '../components/providers/ProviderNotices';
+import CollapsibleSection from '../components/ui/CollapsibleSection';
// 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.
-const RUNNER_NOT_ALLOWED_HINT = 'This command is not on the CoS Agent Runner’s allowlist, so /spawn and /spawn-tui will refuse it. The provider still works everywhere else (direct spawn, chat, pipeline). The allowlist is curated in the PortOS source, not in this form.';
-
-// Privacy disclosure for the Grok Build CLI/TUI: its harness uploads the entire
-// working repo to xAI (GCP) as it works unless the user opts out. Shown both on
-// the provider card and in the create/edit form (before enabling) — see
-// isGrokBuildCli for which providers match.
-function GrokUploadWarning({ className = '' }) {
- return (
- <div className={`text-xs rounded-md border border-port-warning/40 bg-port-warning/10 text-port-warning px-2.5 py-2 leading-relaxed ${className}`}>
- ⚠️ The Grok harness uploads your <span className="font-semibold">entire working repo</span> to
- xAI (GCP) as it works. To keep your code local, add the following to{' '}
- <code className="font-mono">~/.grok/config.toml</code> before enabling this provider:
- <pre className="mt-1.5 whitespace-pre rounded bg-port-bg/60 px-2 py-1.5 font-mono text-[11px] text-port-warning">{`[harness]
-disable_codebase_upload = true`}</pre>
- </div>
- );
-}
-
-// The OpenCode OrcaRouter wrappers (opencode-orcarouter / -tui) keep no key of
-// their own — at spawn time the server copies the key from the sibling
-// `orcarouter` API provider. This answers "where do I put the API key?" from the
-// card/form: it's on the API provider, not here.
-function OrcaRouterKeyHint({ sibling, className = '', onEdit }) {
- const hasKey = Boolean(sibling?.hasApiKey);
- return (
- <div className={`text-xs rounded-md border border-port-border bg-port-bg/60 px-2.5 py-2 leading-relaxed ${className}`}>
- <span className="text-gray-300">
- API key is inherited from the <code className="font-mono">OrcaRouter</code> API provider
- {" "}at run time — this wrapper has no key field of its own.
- </span>
- <p className="mt-1 text-gray-400">
- You do not need to add an environment variable. PortOS supplies{' '}
- <code className="font-mono">ORCAROUTER_API_KEY</code> to OpenCode automatically.
- </p>
- <div className="mt-2 flex flex-wrap items-center gap-2">
- {hasKey ? (
- <span className="text-port-success">OrcaRouter key: set</span>
- ) : (
- <span className="text-port-warning">OrcaRouter key: not set</span>
- )}
- {sibling && onEdit && (
- <button
- type="button"
- onClick={() => onEdit(sibling)}
- className="text-port-accent hover:text-port-accent/80 underline underline-offset-2"
- >
- Edit OrcaRouter API provider
- </button>
- )}
- </div>
- </div>
- );
-}
+// The three buckets the cards are grouped into, in the order they render.
+// "Needs setup" sits between them deliberately: a provider missing its CLI or
+// key can't be turned on at all, so it is neither enabled nor merely disabled.
+export const PROVIDER_SECTIONS = [
+ {
+ key: 'enabled',
+ title: 'Enabled',
+ hint: 'Switched on and available to run',
+ dot: 'bg-port-success',
+ states: [PROVIDER_READINESS.READY, PROVIDER_READINESS.BENCHED],
+ },
+ {
+ key: 'blocked',
+ title: 'Needs setup',
+ hint: 'Missing a CLI or an API key — these cannot run yet',
+ dot: 'bg-port-warning',
+ states: [PROVIDER_READINESS.BLOCKED],
+ },
+ {
+ key: 'disabled',
+ title: 'Disabled',
+ hint: 'Fully configured, but switched off',
+ dot: 'bg-gray-500',
+ states: [PROVIDER_READINESS.DISABLED],
+ },
+];
export default function AIProviders() {
const [providers, setProviders] = useState([]);
@@ -344,14 +317,46 @@ export default function AIProviders() {
// 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 runtimeForProvider = useCallback((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' };
- };
+ }, [runtimes, localModels.installed]);
+
+ // Everything the cards are derived from, in one pass: each provider's runtime,
+ // its readiness (runtime install state + credentials + the runtime bench,
+ // folded into the state that drives the card's color, its badge and its
+ // section), and the id lookup the cards use for fallback/sibling references.
+ // Memoized because this page re-renders on the 20s status poll and on every
+ // keystroke in the ad-hoc runner's prompt box.
+ const { providersById, runtimeByProviderId, readinessByProviderId, providersBySection } = useMemo(() => {
+ const byId = Object.fromEntries(providers.map(p => [p.id, p]));
+ const runtimeById = Object.fromEntries(providers.map(p => [p.id, runtimeForProvider(p)]));
+ const readinessById = Object.fromEntries(providers.map(p => [p.id, providerReadiness(p, {
+ runtime: runtimeById[p.id],
+ status: statuses[p.id],
+ // `null` when the sibling isn't in the list at all — unknown, not missing.
+ orcaRouterKeySet: byId.orcarouter ? Boolean(byId.orcarouter.hasApiKey) : null,
+ })]));
+ // The default provider floats to the top of whichever section it sits in, so
+ // "which one runs by default" stays a one-glance answer after grouping.
+ const defaultFirst = (list) => {
+ const idx = list.findIndex(p => p.id === activeProviderId);
+ return idx <= 0 ? list : [list[idx], ...list.slice(0, idx), ...list.slice(idx + 1)];
+ };
+ return {
+ providersById: byId,
+ runtimeByProviderId: runtimeById,
+ readinessByProviderId: readinessById,
+ providersBySection: Object.fromEntries(PROVIDER_SECTIONS.map(section => [
+ section.key,
+ defaultFirst(providers.filter(p => section.states.includes(readinessById[p.id].state))),
+ ])),
+ };
+ }, [providers, statuses, activeProviderId, runtimeForProvider]);
const selectedRunProvider = providers.find(p => p.id === activeProviderId);
const runProviderIsTui = isTuiProvider(selectedRunProvider);
@@ -570,8 +575,8 @@ export default function AIProviders() {
</div>
)}
- {/* Provider List */}
- <div className="grid gap-4">
+ {/* Provider List, grouped by readiness (see PROVIDER_SECTIONS) */}
+ <div className="grid gap-6">
{loadError ? (
<Banner
tone="error"
@@ -591,252 +596,51 @@ export default function AIProviders() {
</Banner>
) : (
<>
- {(() => {
- const idx = providers.findIndex(p => p.id === activeProviderId);
- if (idx <= 0) return providers;
- return [providers[idx], ...providers.slice(0, idx), ...providers.slice(idx + 1)];
- })().map(provider => (
- <div
- key={provider.id}
- className={`bg-port-card border rounded-xl p-4 ${
- provider.id === activeProviderId ? 'border-port-accent' : 'border-port-border'
- }`}
- >
- <div className="flex flex-col lg:flex-row lg:items-start justify-between gap-4">
- <div className="flex-1 min-w-0">
- <div className="flex flex-wrap items-center gap-2">
- <h3 className="text-lg font-semibold text-white">{provider.name}</h3>
- <span className={`text-xs px-2 py-0.5 rounded ${providerTypeClass(provider.type)}`}>
- {provider.type.toUpperCase()}
- </span>
- {provider.id === activeProviderId && (
- <span className="text-xs px-2 py-0.5 rounded bg-port-accent/20 text-port-accent">
- DEFAULT
- </span>
- )}
- {provider.llamaBacked && (
- <span className="text-xs px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30">
- LLAMA.CPP / DFLASH
- </span>
- )}
- {provider.mtplxBacked && (
- <span className="text-xs px-2 py-0.5 rounded bg-blue-500/20 text-blue-300 border border-blue-500/30">
- MTPLX
- </span>
- )}
- {!provider.enabled && (
- <span className="text-xs px-2 py-0.5 rounded bg-gray-500/20 text-gray-400">
- DISABLED
- </span>
- )}
- {/* Runtime availability is independent of the `enabled` toggle: an
- enabled provider can still be benched after a failure (usage
- limit, model-not-found, auth) and skipped in favor of a fallback. */}
- {provider.enabled && statuses[provider.id]?.available === false && (
- <span
- className="text-xs px-2 py-0.5 rounded bg-port-error/20 text-port-error"
- title={statuses[provider.id]?.message || ''}
- >
- UNAVAILABLE{statuses[provider.id]?.reason ? ` · ${statuses[provider.id].reason}` : ''}
- </span>
- )}
- {/* Off the CoS Agent Runner's exec allowlist: the provider still
- works for direct spawn, it just can't be launched by /spawn
- or /spawn-tui. Informational — never a save-time rejection. */}
- {isProcessProvider(provider) && isRunnerAllowedCommand(provider.command, runnerAllowedCommands) === false && (
- <span
- className="text-xs px-2 py-0.5 rounded bg-port-warning/20 text-port-warning"
- title={RUNNER_NOT_ALLOWED_HINT}
- >
- NO AGENT RUNNER
- </span>
- )}
- </div>
-
- <ProviderRuntimeStatus
- className="mt-2"
- runtime={runtimeForProvider(provider)}
- onInstall={setInstallingRuntime}
+ {PROVIDER_SECTIONS.map(section => {
+ const sectionProviders = providersBySection[section.key];
+ if (sectionProviders.length === 0) return null;
+ return (
+ <CollapsibleSection
+ key={section.key}
+ size="lg"
+ defaultOpen
+ buttonClassName="flex-wrap border-b border-port-border/60 pb-1.5"
+ bodyClassName="grid gap-4 pt-3"
+ label={(
+ <span className="flex flex-wrap items-center gap-2">
+ <span className={`w-2 h-2 rounded-full shrink-0 ${section.dot}`} aria-hidden="true" />
+ <span className="text-sm font-semibold uppercase tracking-wide text-white">{section.title}</span>
+ <span className="text-xs px-1.5 py-0.5 rounded bg-port-bg text-gray-400">{sectionProviders.length}</span>
+ <span className="text-xs text-gray-500">{section.hint}</span>
+ </span>
+ )}
+ >
+ {sectionProviders.map(provider => (
+ <ProviderCard
+ key={provider.id}
+ provider={provider}
+ readiness={readinessByProviderId[provider.id]}
+ runtime={runtimeByProviderId[provider.id]}
+ status={statuses[provider.id]}
+ isDefault={provider.id === activeProviderId}
+ providersById={providersById}
+ runnerAllowedCommands={runnerAllowedCommands}
+ testResult={testResults[provider.id]}
+ refreshing={Boolean(refreshing[provider.id])}
+ recovering={Boolean(recovering[provider.id])}
+ onTest={handleTest}
+ onRefreshModels={handleRefreshModels}
+ onToggleEnabled={handleToggleEnabled}
+ onSetActive={handleSetActive}
+ onEdit={(target) => { setEditingProvider(target); setShowForm(true); }}
+ onDelete={handleDelete}
+ onRecover={handleRecover}
+ onInstallRuntime={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">
- <span className="font-semibold">Benched ({statuses[provider.id]?.reason || 'unknown'})</span>
- {statuses[provider.id]?.timeUntilRecovery ? ` — auto-retries in ${statuses[provider.id].timeUntilRecovery}` : ''}
- . Calls route to the fallback until then.
- </p>
- {statuses[provider.id]?.message && (
- <p className="break-words text-port-error/80">Why: {statuses[provider.id].message}</p>
- )}
- <button
- type="button"
- onClick={() => handleRecover(provider.id)}
- disabled={recovering[provider.id]}
- className="mt-1 px-2 py-0.5 rounded bg-port-error/20 hover:bg-port-error/30 disabled:opacity-50 text-port-error"
- >
- {recovering[provider.id] ? 'Clearing…' : 'Recover now'}
- </button>
- </div>
- )}
-
- <div className="mt-2 text-sm text-gray-400 space-y-1">
- {provider.llamaBacked && (
- <p className="text-xs text-purple-300/90">
- Local llama.cpp / llama-server harness (endpoint: <code className="text-purple-200">{provider.endpoint}</code>) — supports DFlash 2 speculative drafting.
- </p>
- )}
- {isProcessProvider(provider) && (
- <p className="break-words">Command: <code className="text-gray-300 break-all">{provider.command} {provider.args?.join(' ')}</code></p>
- )}
- {isApiProvider(provider) && (
- <p className="break-words">Endpoint: <code className="text-gray-300 break-all">{provider.endpoint}</code></p>
- )}
- {/* API-type providers auth solely via the stored apiKey (sent as a
- Bearer header) — surface its state here so "where does the key
- go?" is answered from the card, not by spelunking the form. */}
- {isApiProvider(provider) && (
- provider.hasApiKey ? (
- <p className="text-xs">API key: <span className="text-port-success">set</span></p>
- ) : isLocalEndpoint(provider.endpoint) ? (
- <p className="text-xs">API key: <span className="text-gray-500">none (local endpoint)</span></p>
- ) : (
- <p className="text-xs">API key: <span className="text-port-warning">not set — Edit this provider to paste one</span></p>
- )
- )}
- {provider.models?.length > 0 && (
- <p>Models: {provider.models.slice(0, 3).join(', ')}{provider.models.length > 3 ? ` +${provider.models.length - 3}` : ''}</p>
- )}
- {provider.defaultModel && (
- <p className="break-words">Default: <code className="text-gray-300 break-all">{provider.defaultModel}</code></p>
- )}
- {provider.effort && (
- <p className="break-words">Default effort: <code className="text-gray-300">{provider.effort}</code></p>
- )}
- {(() => {
- const windowLabel = formatContextLength(effectiveModelContextWindow(provider, provider.defaultModel));
- return windowLabel ? (
- <p className="text-xs">
- Context: <span className="text-gray-300">{windowLabel}</span>
- {provider.contextWindow ? <span className="text-gray-500"> override</span> : null}
- </p>
- ) : null;
- })()}
- {(provider.lightModel || provider.mediumModel || provider.heavyModel) && (
- <p className="text-xs">
- Tiers:
- {provider.lightModel && <span className="ml-1 text-port-success">{provider.lightModel}</span>}
- {provider.mediumModel && <span className="ml-1 text-port-warning">{provider.mediumModel}</span>}
- {provider.heavyModel && <span className="ml-1 text-port-error">{provider.heavyModel}</span>}
- </p>
- )}
- {provider.headlessArgs?.length > 0 && (
- <p className="text-xs break-words">
- Headless: <code className="text-gray-300 break-all">{provider.headlessArgs.join(' ')}</code>
- </p>
- )}
- {isTuiProvider(provider) && (
- <p className="text-xs break-words">
- TUI: paste delay <span className="text-gray-300">{provider.tuiPromptDelayMs || 2500}ms</span>, completion by sentinel, process exit, or explicit failure
- </p>
- )}
- {provider.fallbackProvider && (
- <p className="text-xs">
- Fallback: <span className="text-port-accent">{providers.find(p => p.id === provider.fallbackProvider)?.name || provider.fallbackProvider}</span>
- {provider.fallbackModel && <span className="ml-1 text-gray-300">({provider.fallbackModel})</span>}
- </p>
- )}
- {provider.envVars && Object.keys(provider.envVars).length > 0 && (
- <div className="text-xs mt-1">
- <span className="text-gray-400">Env:</span>
- {Object.entries(provider.envVars).map(([k, v]) => (
- <div key={k}>
- <code className="ml-1 text-orange-400">
- {k}={provider.secretEnvVars?.includes(k) ? '***' : v}
- </code>
- </div>
- ))}
- </div>
- )}
- </div>
-
- {isGrokBuildCli(provider) && <GrokUploadWarning className="mt-2" />}
-
- {isOrcaRouterBackedProvider(provider) && (
- <OrcaRouterKeyHint
- sibling={providers.find(p => p.id === 'orcarouter')}
- onEdit={(sibling) => { setEditingProvider(sibling); setShowForm(true); }}
- className="mt-2"
- />
- )}
-
- {testResults[provider.id] && !testResults[provider.id].testing && (
- <div className={`mt-2 text-sm ${testResults[provider.id].success ? 'text-port-success' : 'text-port-error'}`}>
- {testResults[provider.id].success
- ? `✓ Available${testResults[provider.id].version ? ` (${testResults[provider.id].version})` : ''}`
- : `✗ ${testResults[provider.id].error}`
- }
- </div>
- )}
- </div>
-
- <div className="flex flex-wrap items-center gap-2">
- <button
- onClick={() => handleTest(provider.id)}
- disabled={testResults[provider.id]?.testing}
- className="px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors disabled:opacity-50"
- >
- {testResults[provider.id]?.testing ? 'Testing...' : 'Test'}
- </button>
-
- {supportsModelRefresh(provider) && (
- <button
- onClick={() => handleRefreshModels(provider.id)}
- disabled={refreshing[provider.id]}
- className="px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
- title="Refresh available models"
- >
- {refreshing[provider.id] ? 'Refreshing...' : 'Refresh Models'}
- </button>
- )}
-
- <button
- onClick={() => handleToggleEnabled(provider)}
- className={`px-3 py-1.5 text-sm rounded transition-colors ${
- provider.enabled
- ? 'bg-port-warning/20 text-port-warning hover:bg-port-warning/30'
- : 'bg-port-success/20 text-port-success hover:bg-port-success/30'
- }`}
- >
- {provider.enabled ? 'Disable' : 'Enable'}
- </button>
-
- {provider.id !== activeProviderId && provider.enabled && (
- <button
- onClick={() => handleSetActive(provider.id)}
- className="px-3 py-1.5 text-sm bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded transition-colors"
- >
- Set Default
- </button>
- )}
-
- <button
- onClick={() => { setEditingProvider(provider); setShowForm(true); }}
- className="px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors"
- >
- Edit
- </button>
-
- <button
- onClick={() => handleDelete(provider.id)}
- className="px-3 py-1.5 text-sm bg-port-error/20 text-port-error hover:bg-port-error/30 rounded transition-colors"
- >
- Delete
- </button>
- </div>
- </div>
- </div>
- ))}
+ ))}
+ </CollapsibleSection>
+ );
+ })}
{providers.length === 0 && (
<EmptyState
diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsx
index 33687a6c1b..8aa1a36f28 100644
--- a/client/src/pages/AIProviders.test.jsx
+++ b/client/src/pages/AIProviders.test.jsx
@@ -43,7 +43,9 @@ vi.mock('../components/install/RuntimeInstallModal', () => ({
: null,
}));
-import AIProviders from './AIProviders';
+import AIProviders, { PROVIDER_SECTIONS } from './AIProviders';
+import { READINESS_STYLES } from '../components/providers/ProviderCard';
+import { PROVIDER_READINESS } from '../utils/providers';
const renderPage = () => render(
<MemoryRouter>
@@ -210,6 +212,8 @@ describe('AIProviders page load error handling', () => {
expect(await screen.findByText('No providers configured')).toBeInTheDocument();
expect(screen.queryByText('Failed to load AI providers')).not.toBeInTheDocument();
+ // With nothing to group, no readiness section renders either.
+ expect(screen.queryByRole('button', { name: new RegExp('^Enabled') })).not.toBeInTheDocument();
});
it('renders Banner with Retry button when api.getProviders rejects and does not show EmptyState', async () => {
@@ -579,3 +583,100 @@ describe('OpenCode OrcaRouter key hint', () => {
expect(screen.queryByText(/API key is inherited from/)).not.toBeInTheDocument();
});
});
+
+describe('readiness grouping', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ api.getApps.mockResolvedValue([]);
+ api.getProviderStatuses.mockResolvedValue({ providers: {} });
+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
+ localModels.value = { ctxById: {}, installed: { ollama: null, lmstudio: null } };
+ });
+
+ it('sorts each provider into the section its readiness implies', async () => {
+ api.getProviders.mockResolvedValue({
+ providers: [
+ { id: 'ready', name: 'Ready CLI', type: 'cli', command: 'claude', enabled: true },
+ { id: 'off', name: 'Switched Off', type: 'cli', command: 'claude', enabled: false },
+ { id: 'keyless', name: 'Keyless Cloud', type: 'api', endpoint: 'https://api.example.com/v1', hasApiKey: false, enabled: true },
+ ],
+ activeProvider: 'ready',
+ });
+
+ renderPage();
+
+ expect(await screen.findByRole('button', { name: new RegExp('^Enabled') })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: new RegExp('^Needs setup') })).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: new RegExp('^Disabled') })).toBeInTheDocument();
+ expect(screen.getByText('READY')).toBeInTheDocument();
+ expect(screen.getByText('DISABLED')).toBeInTheDocument();
+ expect(screen.getByText('NEEDS SETUP')).toBeInTheDocument();
+ // The blocker itself stays where its fix is — the card's API-key row.
+ expect(screen.getByText(/not set — Edit this provider to paste one/)).toBeInTheDocument();
+ });
+
+ // A missing CLI is what stops the provider — not the toggle — so it belongs in
+ // "Needs setup" whichever way the switch sits.
+ it('files a switched-off provider with a missing CLI under Needs setup', async () => {
+ api.getProviders.mockResolvedValue({
+ providers: [{ id: 'opencode-ollama', name: 'OpenCode Ollama', type: 'cli', command: 'opencode', enabled: false }],
+ activeProvider: null,
+ });
+ api.getProviderRuntimes.mockResolvedValue({ runtimes: { opencode: missingRuntime } });
+
+ renderPage();
+
+ expect(await screen.findByText('NEEDS SETUP')).toBeInTheDocument();
+ expect(screen.getByText('OpenCode CLI not installed')).toBeInTheDocument();
+ expect(screen.getByText('SWITCHED OFF')).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: new RegExp('^Disabled') })).not.toBeInTheDocument();
+ });
+
+ it('badges an enabled-but-benched provider with its reason', async () => {
+ api.getProviders.mockResolvedValue({
+ providers: [{ id: 'claude', name: 'Claude', type: 'cli', command: 'claude', enabled: true }],
+ activeProvider: 'claude',
+ });
+ api.getProviderStatuses.mockResolvedValue({
+ providers: { claude: { available: false, reason: 'usage-limit', message: 'Usage limit reached' } },
+ });
+
+ renderPage();
+
+ expect(await screen.findByText('BENCHED · usage-limit')).toBeInTheDocument();
+ // Benched providers stay in the Enabled group — nothing is missing on them.
+ expect(screen.getByRole('button', { name: new RegExp('^Enabled') })).toBeInTheDocument();
+ expect(screen.queryByRole('button', { name: new RegExp('^Needs setup') })).not.toBeInTheDocument();
+ });
+
+ it('folds a section away when its header is clicked', async () => {
+ api.getProviders.mockResolvedValue({
+ providers: [{ id: 'off', name: 'Switched Off', type: 'cli', command: 'claude', enabled: false }],
+ activeProvider: null,
+ });
+
+ renderPage();
+
+ const header = await screen.findByRole('button', { name: /Disabled/ });
+ expect(screen.getByText('Switched Off')).toBeInTheDocument();
+
+ fireEvent.click(header);
+ expect(screen.queryByText('Switched Off')).not.toBeInTheDocument();
+ expect(header).toHaveAttribute('aria-expanded', 'false');
+
+ fireEvent.click(header);
+ expect(screen.getByText('Switched Off')).toBeInTheDocument();
+ });
+});
+
+// Both tables are keyed off PROVIDER_READINESS, and a state missing from either
+// fails quietly: no PROVIDER_SECTIONS row and those cards vanish from the page,
+// no READINESS_STYLES row and the card throws on `style.border`.
+describe('readiness table coverage', () => {
+ it('gives every readiness state a card style and exactly one section', () => {
+ for (const state of Object.values(PROVIDER_READINESS)) {
+ expect(READINESS_STYLES[state]).toBeDefined();
+ expect(PROVIDER_SECTIONS.filter(section => section.states.includes(state))).toHaveLength(1);
+ }
+ });
+});
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index d720454467..9ac896b5cb 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`. 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. |
+| `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 `providerReadiness(provider, { runtime, status, orcaRouterKeySet })` + `PROVIDER_READINESS` — is a provider ready to run, benched, blocked on a missing prerequisite (CLI not installed / API key absent), or simply switched off? Presentation-only (the server routes on `enabled && available` alone); `null` inputs mean "not probed", never "missing". Drives the AI Providers page card colors and grouping. 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 d6e3d8a637..db5c4d53f1 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -874,6 +874,76 @@ export const isGrokBuildCli = (provider) => {
return id === 'grok-cli' || id === 'grok-tui' || commandBasename(provider?.command) === 'grok';
};
+/**
+ * The four states a provider card can be in on the AI Providers page, ordered
+ * the way the page groups them: usable now, temporarily benched, missing a
+ * prerequisite, or simply switched off.
+ */
+export const PROVIDER_READINESS = Object.freeze({
+ READY: 'ready',
+ BENCHED: 'benched',
+ BLOCKED: 'blocked',
+ DISABLED: 'disabled',
+});
+
+/**
+ * Which prerequisites a provider is missing, and the readiness state that
+ * follows from them — one place, so a card's border, its badge and the section
+ * the page files it under can never disagree with each other.
+ *
+ * PRESENTATION readiness, not an exec gate: the server routes on
+ * `provider.enabled && isAvailable(id)` alone (`getFallbackProvider` in
+ * server/lib/aiToolkit/providerStatus.js) and discovers a missing binary at
+ * spawn time via ENOENT, so a `blocked` card here is still reachable by the
+ * runner. Publishing the prerequisite check server-side so routing can skip
+ * un-runnable providers is issue #4611; credentials carried in a secret env var
+ * (Bedrock, Ollama auth token) are not covered yet — issue #4612.
+ *
+ * Inputs are passed in rather than read from globals so this stays pure:
+ * runtime — the provider's entry of the `runtimes` map (CLI binary)
+ * or the local-app shape the page derives from the
+ * local-LLM status. `null` = NOT PROBED, which must never
+ * read as "missing" (an older server, or a card drawn
+ * before the probe lands, would otherwise accuse every
+ * perfectly-installed CLI).
+ * status — the runtime-availability entry from
+ * `GET /api/providers/status`; `available === false`
+ * means the provider is benched after a failure.
+ * orcaRouterKeySet — whether the sibling `orcarouter` API provider holds the
+ * key an OpenCode OrcaRouter wrapper inherits at spawn
+ * time. `null` = unknown (sibling not in the list), and
+ * like `runtime` must not be reported as missing.
+ *
+ * `blocked` outranks `disabled`: a provider whose CLI isn't installed can't be
+ * enabled at all, so it belongs in the "needs setup" bucket whichever way its
+ * toggle happens to sit. `benched` only applies to an enabled provider that
+ * otherwise meets its prerequisites.
+ *
+ * @returns {{state: string, missing: {code: string, label: string}[]}}
+ */
+export const providerReadiness = (provider, { runtime = null, status = null, orcaRouterKeySet = null } = {}) => {
+ const missing = [];
+
+ if (runtime && runtime.installed === false) {
+ missing.push({ code: 'runtime', label: `${runtime.label || 'Runtime'} is not installed` });
+ }
+ // API providers auth solely via the stored key. A local endpoint (Ollama, LM
+ // Studio) needs none, so its absence is not a missing prerequisite there.
+ if (isApiProvider(provider) && provider?.hasApiKey !== true && !isLocalEndpoint(provider?.endpoint)) {
+ missing.push({ code: 'apiKey', label: 'API key is not set' });
+ }
+ // The OpenCode OrcaRouter wrappers carry no key of their own — theirs lives
+ // on the sibling API provider, so that's the prerequisite to report.
+ if (isOrcaRouterBackedProvider(provider) && orcaRouterKeySet === false) {
+ missing.push({ code: 'inheritedApiKey', label: 'OrcaRouter API provider has no API key' });
+ }
+
+ if (missing.length > 0) return { state: PROVIDER_READINESS.BLOCKED, missing };
+ if (!provider?.enabled) return { state: PROVIDER_READINESS.DISABLED, missing };
+ if (status?.available === false) return { state: PROVIDER_READINESS.BENCHED, missing };
+ return { state: PROVIDER_READINESS.READY, missing };
+};
+
/**
* Resolve the provider whose timeout is the "fallback" for a stage — the
* stage's pinned provider when set, otherwise the active provider. Used to
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 6b00287346..29d717426e 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -33,6 +33,8 @@ import {
isApiProvider,
isProcessProvider,
providerRuntimeKey,
+ providerReadiness,
+ PROVIDER_READINESS,
isOllamaBackedProvider,
isOrcaRouterBackedProvider,
isGrokBuildCli,
@@ -1176,4 +1178,76 @@ describe('providerRuntimeKey', () => {
});
});
+describe('providerReadiness', () => {
+ const cli = (over = {}) => ({ id: 'p1', type: 'cli', command: 'opencode', enabled: true, ...over });
+ const cloudApi = (over = {}) => ({ id: 'p2', type: 'api', endpoint: 'https://api.example.com/v1', enabled: true, ...over });
+
+ it('reports an enabled provider with every prerequisite met as ready', () => {
+ expect(providerReadiness(cli(), { runtime: { label: 'OpenCode CLI', installed: true } }))
+ .toEqual({ state: PROVIDER_READINESS.READY, missing: [] });
+ expect(providerReadiness(cloudApi({ hasApiKey: true })))
+ .toEqual({ state: PROVIDER_READINESS.READY, missing: [] });
+ });
+
+ // An unprobed runtime (older server, or the card drawn before the probe
+ // lands) must read as "can't tell", never as a missing binary.
+ it('never blocks on an unprobed runtime', () => {
+ expect(providerReadiness(cli(), { runtime: null }).state).toBe(PROVIDER_READINESS.READY);
+ });
+
+ it('blocks a provider whose CLI is not installed, and names it', () => {
+ const readiness = providerReadiness(cli(), { runtime: { label: 'OpenCode CLI', installed: false } });
+ expect(readiness.state).toBe(PROVIDER_READINESS.BLOCKED);
+ expect(readiness.missing).toEqual([{ code: 'runtime', label: 'OpenCode CLI is not installed' }]);
+ });
+
+ it('blocks a cloud API provider with no key', () => {
+ const readiness = providerReadiness(cloudApi({ hasApiKey: false }));
+ expect(readiness.state).toBe(PROVIDER_READINESS.BLOCKED);
+ expect(readiness.missing).toEqual([{ code: 'apiKey', label: 'API key is not set' }]);
+ });
+
+ // Ollama / LM Studio need no key at all — absence there is not a prerequisite.
+ it('does not demand a key from a local endpoint', () => {
+ expect(providerReadiness({ id: 'ollama', type: 'api', endpoint: 'http://localhost:11434/v1', enabled: true }).state)
+ .toBe(PROVIDER_READINESS.READY);
+ });
+
+ it('blocks an OrcaRouter wrapper when the sibling API provider holds no key', () => {
+ const wrapper = cli({ id: 'opencode-orcarouter', orcarouterBacked: true });
+ expect(providerReadiness(wrapper, { orcaRouterKeySet: false }).missing)
+ .toEqual([{ code: 'inheritedApiKey', label: 'OrcaRouter API provider has no API key' }]);
+ // Sibling absent from the list = unknown, which must not accuse the wrapper.
+ expect(providerReadiness(wrapper, { orcaRouterKeySet: null }).state).toBe(PROVIDER_READINESS.READY);
+ expect(providerReadiness(wrapper, { orcaRouterKeySet: true }).state).toBe(PROVIDER_READINESS.READY);
+ });
+
+ it('benches an enabled provider the server marked unavailable', () => {
+ const readiness = providerReadiness(cli(), { status: { available: false, reason: 'usage-limit' } });
+ expect(readiness.state).toBe(PROVIDER_READINESS.BENCHED);
+ // A benched provider is fully configured — nothing to install or paste.
+ expect(readiness.missing).toEqual([]);
+ });
+
+ it('reads a switched-off but fully configured provider as disabled, not blocked', () => {
+ expect(providerReadiness(cli({ enabled: false }), { runtime: { label: 'OpenCode CLI', installed: true } }).state)
+ .toBe(PROVIDER_READINESS.DISABLED);
+ });
+
+ // The toggle is not what's stopping a provider whose CLI is missing, so the
+ // missing prerequisite outranks it — that's the bucket the user must act in.
+ it('keeps a switched-off provider with a missing prerequisite in the blocked bucket', () => {
+ expect(providerReadiness(cli({ enabled: false }), { runtime: { label: 'OpenCode CLI', installed: false } }).state)
+ .toBe(PROVIDER_READINESS.BLOCKED);
+ });
+
+ it('collects every missing prerequisite at once', () => {
+ const readiness = providerReadiness(
+ { id: 'lmstudio-remote', type: 'api', endpoint: 'https://api.example.com/v1', hasApiKey: false, enabled: true },
+ { runtime: { label: 'LM Studio', installed: false } },
+ );
+ expect(readiness.missing.map(m => m.code)).toEqual(['runtime', 'apiKey']);
+ });
+});
+
// @vitest-environment node