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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
Merge remote-tracking branch 'origin/main' into cos/task-mt0tu72h/agent-9ed5de84
[._.]/ Adam Eivyd29b2c1fc9f0
diff --cc client/src/components/providers/ProviderCard.jsxindex bb263e49a1,0000000000..3733817db3mode 100644,000000..100644--- a/client/src/components/providers/ProviderCard.jsx+++ b/client/src/components/providers/ProviderCard.jsx@@@ -1,339 -1,0 +1,347 @@@+/**+ * 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.++ * started grouping cards by their card state.+ *- * The card renders no derivation of its own: `readiness`, `runtime` and++ * The card renders no derivation of its own: `cardState`, `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,++ PROVIDER_CARD_STATE,+ effectiveModelContextWindow,+ isApiProvider,+ isGrokBuildCli,+ isLocalEndpoint,+ isOrcaRouterBackedProvider,+ isProcessProvider,+ isRunnerAllowedCommand,+ isTuiProvider,+ providerTypeClass,+ supportsModelRefresh,+} from '../../utils/providers';+import { formatContextLength } from '../../utils/formatters';+import ProviderRuntimeStatus from './ProviderRuntimeStatus';++import ProviderReadiness from './ProviderReadiness';+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++// Card presentation per card 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]: {++export const CARD_STATE_STYLES = {++ [PROVIDER_CARD_STATE.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]: {++ [PROVIDER_CARD_STATE.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]: {++ [PROVIDER_CARD_STATE.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]: {++ [PROVIDER_CARD_STATE.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,++ cardState,++ daemonReadiness,+ runtime,+ status,+ isDefault,+ providersById,+ runnerAllowedCommands,+ testResult,+ refreshing,+ recovering,+ onTest,+ onRefreshModels,+ onToggleEnabled,+ onSetActive,+ onEdit,+ onDelete,+ onRecover,+ onInstallRuntime,+}) {- const style = READINESS_STYLES[readiness.state];++ const style = CARD_STATE_STYLES[cardState.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++ {/* One badge for the card's state — the same one 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(' · ')++ title={cardState.state === PROVIDER_CARD_STATE.BLOCKED++ ? cardState.missing.map(m => m.label).join(' · ')+ : (status?.message || style.hint)}+ >+ {style.label}- {readiness.state === PROVIDER_READINESS.BENCHED && status?.reason++ {cardState.state === PROVIDER_CARD_STATE.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 && (++ {cardState.state === PROVIDER_CARD_STATE.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}+ />+++ {/* The other half of "can this actually run": is the local daemon this++ provider points at installed, up, and serving the model it names.++ Distinct from the card STATE above — that one is about the toggle++ and the credentials, this one probes the daemon. */}++ <ProviderReadiness className="mt-2" readiness={daemonReadiness} />+++ {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 --cc client/src/pages/AIProviders.jsxindex a9d0065102,3f1f7e3390..5054f2f957--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@@ -4,8 -4,9 +4,9 @@@ import { AlertTriangle } from 'lucide-rimport 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, isGrokBuildCli, isLocalEndpoint, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, isOrcaRouterBackedProvider, providerRuntimeKey, providerReadiness, PROVIDER_READINESS } 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 { filterSelectableModels, filterGenerationModels, isEmbeddingModel, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isGrokBuildCli, isLocalEndpoint, effectiveModelContextWindow, isRunnerAllowedCommand, effortLevelsForProvider, isOllamaBackedProvider, isOrcaRouterBackedProvider, providerRuntimeKey, providerCardState, PROVIDER_CARD_STATE } from '../utils/providers';import useLocalModels from '../hooks/useLocalModels';+ import { useAutoRefetch } from '../hooks/useAutoRefetch';import BrailleSpinner from '../components/BrailleSpinner';import EmptyState from '../components/EmptyState';import Banner from '../components/ui/Banner';@@@ -31,32 -31,61 +32,32 @@@ import CollapsibleSection from '../comp// 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],++ states: [PROVIDER_CARD_STATE.READY, PROVIDER_CARD_STATE.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],++ states: [PROVIDER_CARD_STATE.BLOCKED],+ },+ {+ key: 'disabled',+ title: 'Disabled',+ hint: 'Fully configured, but switched off',+ dot: 'bg-gray-500',- states: [PROVIDER_READINESS.DISABLED],++ states: [PROVIDER_CARD_STATE.DISABLED],+ },+];export default function AIProviders() {const [providers, setProviders] = useState([]);@@@ -317,48 -361,19 +333,53 @@@// 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;+ // The readiness checklist covers this same backend in more detail, and knows+ // the difference between "not installed" and "installed but not started".+ // Rendering both put a green "LM Studio installed" pill directly above+ // "Install LM Studio" — so wherever the checklist has an answer, it wins.+ if (readiness[provider.id]?.kind === backend) return null;const installed = localModels.installed?.[backend];// `null` = status not fetched — never offer an install from an unknown state.if (typeof installed !== 'boolean') return null;return { id: backend, label: LOCAL_APP_LABELS[backend], installed, installable: false, manageUrl: '/settings/local-llm' };- }, [runtimes, localModels.installed]);- };++ }, [runtimes, localModels.installed, readiness]);++ // 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 { providersById, runtimeByProviderId, cardStateByProviderId, 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, {++ const readinessById = Object.fromEntries(providers.map(p => [p.id, providerCardState(p, {+ runtime: runtimeById[p.id],+ status: statuses[p.id],+ // `providers` is the authoritative list, so a sibling that is absent from+ // it was deleted — the wrapper has no key to inherit, which is `false`,+ // not "unknown". (Nothing here runs before the list loads.)+ orcaRouterKeySet: Boolean(byId.orcarouter?.hasApiKey),+ })]));+ // 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,++ cardStateByProviderId: 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);@@@ -598,51 -613,254 +619,52 @@@</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]}++ cardState={cardStateByProviderId[provider.id]}++ daemonReadiness={readiness[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}/>-- <ProviderReadiness className="mt-2" readiness={readiness[provider.id]} />-- {provider.enabled && statuses[provider.id]?.available === false && (- <div className="mt-2 text-xs rounded border border-port-error/40 bg-port-error/10 px-3 py-2 text-port-error space-y-1">- <p className="break-words">- <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 && (<EmptyStatediff --cc client/src/pages/AIProviders.test.jsxindex 6362e2a5aa,1c5869baf7..1f44d35261--- a/client/src/pages/AIProviders.test.jsx+++ b/client/src/pages/AIProviders.test.jsx@@@ -43,9 -44,7 +44,9 @@@ vi.mock('../components/install/RuntimeI: null,}));-import AIProviders from './AIProviders';+import AIProviders, { PROVIDER_SECTIONS } from './AIProviders';- import { READINESS_STYLES } from '../components/providers/ProviderCard';- import { PROVIDER_READINESS } from '../utils/providers';++import { CARD_STATE_STYLES } from '../components/providers/ProviderCard';++import { PROVIDER_CARD_STATE } from '../utils/providers';const renderPage = () => render(<MemoryRouter>@@@ -583,121 -634,3 +638,121 @@@ 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();+ });++ // The provider list is authoritative: no sibling means the wrapper has no key+ // to inherit at spawn time, which is a missing prerequisite, not "unknown".+ it('files an OrcaRouter wrapper whose sibling was deleted under Needs setup', async () => {+ api.getProviders.mockResolvedValue({+ providers: [{+ id: 'opencode-orcarouter',+ name: 'OpenCode OrcaRouter',+ type: 'cli',+ command: 'opencode',+ enabled: true,+ orcarouterBacked: true,+ }],+ activeProvider: null,+ });++ renderPage();++ expect(await screen.findByText('NEEDS SETUP')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: new RegExp('^Needs setup') })).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++// Both tables are keyed off PROVIDER_CARD_STATE, 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`.++// no CARD_STATE_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();++ for (const state of Object.values(PROVIDER_CARD_STATE)) {++ expect(CARD_STATE_STYLES[state]).toBeDefined();+ expect(PROVIDER_SECTIONS.filter(section => section.states.includes(state))).toHaveLength(1);+ }+ });+});diff --cc client/src/utils/README.mdindex b0fe4a0452,d720454467..fbbc4c6d20--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@@ -41,7 -41,7 +41,7 @@@ grep -i "what you want to do" client/sr| `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`. `isPrivateNetworkEndpoint(endpoint)` — loopback, RFC1918/tailnet address, or a `.local`/`.ts.net`/single-label host, i.e. somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key. 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. |-| `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`. `isPrivateNetworkEndpoint(endpoint)` — loopback, RFC1918/tailnet address, or a `.local`/`.ts.net`/single-label host, i.e. somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key. And `providerCardState(provider, { runtime, status, orcaRouterKeySet })` + `PROVIDER_CARD_STATE` — 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 — distinct from `ProviderReadiness`/`GET /api/providers/readiness`, which probes the local daemon behind a provider. 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 / resiliencediff --cc client/src/utils/providers.jsindex 67f17d57ed,b5c48d6d3b..4132a0a351--- a/client/src/utils/providers.js+++ b/client/src/utils/providers.js@@@ -910,82 -882,6 +918,88 @@@ export const isGrokBuildCli = (providerreturn 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({++export const PROVIDER_CARD_STATE = 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.++ * Which prerequisites a provider is missing, and the card 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.++ *++ * NOT the same thing as `ProviderReadiness` /++ * `GET /api/providers/readiness`, which probes whether the local DAEMON a++ * provider points at (llama.cpp, Ollama, LM Studio, MTPLX) is up and serving++ * the right model. This decides the card's bucket from its toggle, its++ * credentials and the server's bench status; the two render side by side.+ *- * PRESENTATION readiness, not an exec gate: the server routes on++ * PRESENTATION state, 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. `false` covers BOTH "sibling has no key" and+ * "sibling was deleted" — the server injects the key only+ * when that provider exists and holds one, so either way+ * the wrapper cannot authenticate. `null` is for a caller+ * that genuinely cannot tell (no provider list yet) and,+ * like `runtime`, is never 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 } = {}) => {++export const providerCardState = (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 — but only an endpoint outside+ // the private network actually needs one. The server attaches `Authorization`+ // only when a key is stored, so a keyless call to loopback, a LAN box, or a+ // tailnet peer running LM Studio / Ollama works exactly as configured.+ if (isApiProvider(provider) && provider?.hasApiKey !== true && !isPrivateNetworkEndpoint(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 };++ if (missing.length > 0) return { state: PROVIDER_CARD_STATE.BLOCKED, missing };++ if (!provider?.enabled) return { state: PROVIDER_CARD_STATE.DISABLED, missing };++ if (status?.available === false) return { state: PROVIDER_CARD_STATE.BENCHED, missing };++ return { state: PROVIDER_CARD_STATE.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 todiff --cc client/src/utils/providers.test.jsindex 326e423528,6b00287346..200f6ac1c7--- a/client/src/utils/providers.test.js+++ b/client/src/utils/providers.test.js@@@ -33,9 -33,6 +33,9 @@@ importisApiProvider,isProcessProvider,providerRuntimeKey,- providerReadiness,++ providerCardState,+ isPrivateNetworkEndpoint,- PROVIDER_READINESS,++ PROVIDER_CARD_STATE,isOllamaBackedProvider,isOrcaRouterBackedProvider,isGrokBuildCli,@@@ -1179,125 -1176,4 +1179,125 @@@ describe('providerRuntimeKey', () =>});});- describe('providerReadiness', () => {++describe('providerCardState', () => {+ 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: [] });++ expect(providerCardState(cli(), { runtime: { label: 'OpenCode CLI', installed: true } }))++ .toEqual({ state: PROVIDER_CARD_STATE.READY, missing: [] });++ expect(providerCardState(cloudApi({ hasApiKey: true })))++ .toEqual({ state: PROVIDER_CARD_STATE.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);++ expect(providerCardState(cli(), { runtime: null }).state).toBe(PROVIDER_CARD_STATE.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);++ const readiness = providerCardState(cli(), { runtime: { label: 'OpenCode CLI', installed: false } });++ expect(readiness.state).toBe(PROVIDER_CARD_STATE.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);++ const readiness = providerCardState(cloudApi({ hasApiKey: false }));++ expect(readiness.state).toBe(PROVIDER_CARD_STATE.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);++ expect(providerCardState({ id: 'ollama', type: 'api', endpoint: 'http://localhost:11434/v1', enabled: true }).state)++ .toBe(PROVIDER_CARD_STATE.READY);+ });++ // A LAN box or a tailnet peer running LM Studio / Ollama serves keylessly, and+ // PortOS is a tailnet-first product — flagging those as unconfigured would be+ // a false alarm on a supported deployment.+ it.each([+ ['http://192.168.1.50:1234/v1'],+ ['http://10.0.0.4:11434/v1'],+ ['http://100.101.102.103:11434/v1'],+ ['http://desk-machine.ts.net:1234/v1'],+ ['http://nas:11434/v1'],+ ])('does not demand a key from the private-network endpoint %s', (endpoint) => {- expect(providerReadiness({ id: 'lan', type: 'api', endpoint, enabled: true }).state)- .toBe(PROVIDER_READINESS.READY);++ expect(providerCardState({ id: 'lan', type: 'api', endpoint, enabled: true }).state)++ .toBe(PROVIDER_CARD_STATE.READY);+ });++ it('still demands a key from a public endpoint', () => {- expect(providerReadiness({ id: 'cloud', type: 'api', endpoint: 'https://api.example.com/v1', enabled: true }).state)- .toBe(PROVIDER_READINESS.BLOCKED);++ expect(providerCardState({ id: 'cloud', type: 'api', endpoint: 'https://api.example.com/v1', enabled: true }).state)++ .toBe(PROVIDER_CARD_STATE.BLOCKED);+ });++ 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)++ expect(providerCardState(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);++ expect(providerCardState(wrapper, { orcaRouterKeySet: null }).state).toBe(PROVIDER_CARD_STATE.READY);++ expect(providerCardState(wrapper, { orcaRouterKeySet: true }).state).toBe(PROVIDER_CARD_STATE.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);++ const readiness = providerCardState(cli(), { status: { available: false, reason: 'usage-limit' } });++ expect(readiness.state).toBe(PROVIDER_CARD_STATE.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);++ expect(providerCardState(cli({ enabled: false }), { runtime: { label: 'OpenCode CLI', installed: true } }).state)++ .toBe(PROVIDER_CARD_STATE.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);++ expect(providerCardState(cli({ enabled: false }), { runtime: { label: 'OpenCode CLI', installed: false } }).state)++ .toBe(PROVIDER_CARD_STATE.BLOCKED);+ });++ it('collects every missing prerequisite at once', () => {- const readiness = providerReadiness(++ const readiness = providerCardState(+ { 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']);+ });+});++describe('isPrivateNetworkEndpoint', () => {+ it.each([+ 'http://localhost:11434/v1',+ 'http://127.0.0.1:1234',+ '192.168.1.5:1234/v1',+ 'http://172.16.4.4:11434',+ 'http://172.31.255.1:11434',+ 'http://100.64.0.1:11434',+ 'http://host.local:1234',+ 'http://box.internal/v1',+ 'http://ollama',+ ])('treats %s as inside the private network', (endpoint) => {+ expect(isPrivateNetworkEndpoint(endpoint)).toBe(true);+ });++ it.each([+ 'https://api.example.com/v1',+ 'https://example.com:8443/v1',+ // 172.32 is outside RFC1918 (which stops at 172.31), and 100.128 is above+ // the Tailscale CGNAT range — both are public space.+ 'http://172.32.0.1:11434',+ 'http://100.128.0.1:11434',+ 'http://9.9.9.9/v1',+ '',+ null,+ ])('treats %s as public', (endpoint) => {+ expect(isPrivateNetworkEndpoint(endpoint)).toBe(false);+ });+});+// @vitest-environment node