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
reshape the AI Providers page into Presets, Harnesses and Services views (#7567)
[._.]/ Adam Eivy8ccb42bf43aa
diff --git a/client/src/App.jsx b/client/src/App.jsxindex 73fc227797..5d892039bc 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -1,6 +1,6 @@import { Suspense, useEffect } from 'react';import { isPublicGuestRoute } from './lib/publicGuestRoutes';-import { Routes, Route, Navigate, useLocation } from 'react-router';+import { Routes, Route, Navigate, useLocation, useParams } from 'react-router';import Layout from './components/Layout';import { getSettings, updateSettings, getSelfInstance, PORTOS_APP_ID } from './services/api';import BrailleSpinner from './components/BrailleSpinner';@@ -192,6 +192,19 @@ function PrefixRedirect({ from, to }) {return <Navigate to={`${to}${rest}${search}${hash}`} state={state} replace />;}+// The retired /ai/harnesses/:harnessId/connections[/:connectionId] drawer+// (#6369 → #7567): a connection id names a service, so a deep link into one+// lands on that service; the bare harness-scoped list lands on the harness.+function HarnessConnectionsRedirect() {+ const { harnessId, connectionId } = useParams();+ const { search, hash } = useLocation();+ const target = connectionId+ ? `/ai/services/${encodeURIComponent(connectionId)}`+ : `/ai/harnesses/${encodeURIComponent(harnessId)}`;+ return <Navigate to={`${target}${search}${hash}`} replace />;+}++const AI_CONNECTIONS_PREFIX = /^\/ai\/connections/;const VIDEO_PROJECT_PREFIX = /^\/video/;const MEDIA_CREATIVE_DIRECTOR_PREFIX = /^\/media\/creative-director/;const MEDIA_SPRITES_PREFIX = /^\/media\/sprites/;@@ -288,25 +301,37 @@ export default function App() {<Route path="devtools/processes" element={<ProcessesPage />} /><Route path="devtools/agents" element={<AgentsPage />} /><Route path="eidoverse" element={<Eidoverse />} />- <Route path="ai" element={<AIProviders />} />- {/* Provider overlays are deep-linkable over the same page: /ai/new- creates, /ai/fleet walks through a remote GPU host, and- /ai/edit/:providerId edits. The id sits under its own `edit`- segment rather than directly under /ai so the create route can't- be shadowed by a real provider: ids are slugified from the display- name, so a provider named "New" gets the id `new` and /ai/new- would otherwise match the static create route instead. */}- <Route path="ai/new" element={<AIProviders />} />- <Route path="ai/fleet" element={<AIProviders />} />+ {/* AI Providers is three views over one page (#7567): Presets (the+ stored records — the index /ai lands on), Harnesses and Services.+ Every overlay is deep-linkable over the same page: /ai/presets/new+ creates, /ai/presets/:presetId edits, /ai/services/new adds a+ service, /ai/services/:serviceSlug opens one, /ai/harnesses/:harnessId+ opens one harness card, and /ai/fleet walks through a remote GPU+ host. A preset id is slugified from its display name, so a preset+ named "New" gets the id `new` and is shadowed by the static create+ route under /ai/presets — the legacy /ai/edit/:providerId alias is+ kept as a WORKING route (not a redirect) so that one record stays+ reachable; the page's own edit links use it for that id only. */}+ <Route path="ai" element={<RedirectWithSearch to="/ai/presets" />} />+ <Route path="ai/presets" element={<AIProviders />} />+ <Route path="ai/presets/new" element={<AIProviders />} />+ <Route path="ai/presets/:presetId" element={<AIProviders />} />+ <Route path="ai/new" element={<RedirectWithSearch to="/ai/presets/new" />} /><Route path="ai/edit/:providerId" element={<AIProviders />} />- {/* Backend connection management (#6369). The selected connection is- a route param, not local state, so a shared link reopens the same- row — and the harness-scoped form is what a "Harnesses → Claude →- Connections" walk deep-links to. */}- <Route path="ai/connections" element={<AIProviders />} />- <Route path="ai/connections/:connectionId" element={<AIProviders />} />- <Route path="ai/harnesses/:harnessId/connections" element={<AIProviders />} />- <Route path="ai/harnesses/:harnessId/connections/:connectionId" element={<AIProviders />} />+ <Route path="ai/fleet" element={<AIProviders />} />+ <Route path="ai/harnesses" element={<AIProviders />} />+ <Route path="ai/harnesses/:harnessId" element={<AIProviders />} />+ <Route path="ai/services" element={<AIProviders />} />+ <Route path="ai/services/new" element={<AIProviders />} />+ <Route path="ai/services/:serviceSlug" element={<AIProviders />} />+ {/* The Backend Connections drawer (#6369) is retired: a connection IS+ a service instance, addressed by the same UUID or slug, so its+ deep links land on the Services view. The harness-scoped forms+ land on that harness's card. */}+ <Route path="ai/connections" element={<PrefixRedirect from={AI_CONNECTIONS_PREFIX} to="/ai/services" />} />+ <Route path="ai/connections/:connectionId" element={<PrefixRedirect from={AI_CONNECTIONS_PREFIX} to="/ai/services" />} />+ <Route path="ai/harnesses/:harnessId/connections" element={<HarnessConnectionsRedirect />} />+ <Route path="ai/harnesses/:harnessId/connections/:connectionId" element={<HarnessConnectionsRedirect />} /><Route path="prompts" element={<PromptManager />} /><Route path="cos" element={<Navigate to="/cos/tasks" replace />} /><Route path="cos/mind/tools" element={<Navigate to="/cos/mind?panel=tools" replace />} />diff --git a/client/src/App.modelRoutes.test.jsx b/client/src/App.modelRoutes.test.jsxindex c7a20f7210..a01f9c40ae 100644--- a/client/src/App.modelRoutes.test.jsx+++ b/client/src/App.modelRoutes.test.jsx@@ -30,3 +30,27 @@ it('still serves the LLMs sub-views that stayed behind', async () => {render(<MemoryRouter initialEntries={['/models/llms/abuse']}><App /></MemoryRouter>);expect(await screen.findByTestId('models-location')).toHaveTextContent('/models/llms/abuse');});++// The AI Providers page became three views (#7567): /ai is the Presets view,+// and the retired Backend Connections deep links land on the Services view+// with their record id carried across — a UUID or slug names the same row.+vi.mock('./pages/AIProviders', () => ({ default: () => { const location = useLocation(); return <pre data-testid="ai-location">{location.pathname}{location.search}</pre>; } }));++it.each([+ ['/ai', '/ai/presets'],+ ['/ai?fleetStep=client', '/ai/presets?fleetStep=client'],+ ['/ai/new', '/ai/presets/new'],+ ['/ai/connections', '/ai/services'],+ ['/ai/connections/abc-123', '/ai/services/abc-123'],+ ['/ai/harnesses/claude/connections', '/ai/harnesses/claude'],+ ['/ai/harnesses/claude/connections/abc-123', '/ai/services/abc-123'],+])('redirects the retired %s to %s', async (from, to) => {+ render(<MemoryRouter initialEntries={[from]}><App /></MemoryRouter>);+ expect(await screen.findByTestId('ai-location')).toHaveTextContent(to);+});++// A preset whose id collides with the create route keeps the legacy editor alias.+it('still serves /ai/edit/:providerId as a working route rather than a redirect', async () => {+ render(<MemoryRouter initialEntries={['/ai/edit/new']}><App /></MemoryRouter>);+ expect(await screen.findByTestId('ai-location')).toHaveTextContent('/ai/edit/new');+});diff --git a/client/src/components/Layout.test.jsx b/client/src/components/Layout.test.jsxindex a446b4ca76..df525b3666 100644--- a/client/src/components/Layout.test.jsx+++ b/client/src/components/Layout.test.jsx@@ -145,7 +145,7 @@ describe('Layout — manifest-derived sidebar structure', () => {'/settings/backup', '/settings/credentials', '/settings/database', '/settings/features','/settings/security', '/settings/sharing','/settings/telegram', '/settings/voice', '/settings/mortalloom',- '/openclaw', '/prompts', '/ai'+ '/openclaw', '/prompts', '/ai/presets', '/ai/harnesses', '/ai/services'];for (const p of settingsPaths) {expect(NAV_PRESENTATION[p], `missing NAV_PRESENTATION for settings path ${p}`).toBeDefined();@@ -551,7 +551,7 @@ describe('Layout — isFullWidthRoute classification', () => {['/story-builder', false], ['/story-builder/s1/step', true],// AI Providers: the index AND its editor sub-routes (a drawer over the same// page) are full-width, but a sibling path sharing the `/ai` prefix is not.- ['/ai', true], ['/ai/new', true], ['/ai/edit/codex', true], ['/airlock', false],+ ['/ai', true], ['/ai/presets', true], ['/ai/presets/codex', true], ['/ai/harnesses', true], ['/ai/services/ollama', true], ['/ai/edit/codex', true], ['/airlock', false],['/pipeline', false], ['/pipeline/series/s1', true],['/local-llm', false], ['/local-llm/m', true],// Music owns the same full-bleed title/tab/body shell as Media Gen, butdiff --git a/client/src/components/providers/ProviderCompatibilityMatrix.jsx b/client/src/components/providers/ProviderCompatibilityMatrix.jsxnew file mode 100644index 0000000000..7f1280566d--- /dev/null+++ b/client/src/components/providers/ProviderCompatibilityMatrix.jsx@@ -0,0 +1,130 @@+import { useMemo } from 'react';+import { Grid3x3 } from 'lucide-react';+import CollapsibleSection from '../ui/CollapsibleSection';++/**+ * The compatibility matrix (#7567): harness rows × service columns, each cell+ * the server's own verdict on that pair. Rendered from `GET /api/providers/catalog`+ * — `compatibility[harnessId]` is `isCompatible` evaluated server-side, and+ * the two `enabled` flags plus the service's `readiness` are its rows — so the+ * browser recomputes nothing: a cell can only disagree with what compose+ * offers by the catalog being stale, never by a second predicate.+ *+ * Three cell states:+ * - **offered** — compatible, both sides on, service ready: a click opens+ * the compose flow on that pair ("New preset", prefilled).+ * - **blocked** — compatible, but a side is switched off or the service+ * still needs a credential / endpoint. The reason is the cell's title and+ * accessible name; nothing to click, the fix is on the other two views.+ * - **incompatible** — the harness cannot reach that service at all.+ */++const READINESS_REASON = {+ 'needs-credential': 'needs a credential',+ 'needs-endpoint': 'needs an endpoint',+ disabled: 'is switched off',+ 'unknown-definition': 'has no definition',+};++/** The pure verdict per cell, exported so the page test can pin it without rendering. */+export function matrixCellState(harness, service, compatibility) {+ if (!(compatibility?.[harness.id] || []).includes(service.slug)) return { state: 'incompatible', reason: null };+ if (harness.enabled === false) return { state: 'blocked', reason: `${harness.label} is switched off` };+ if (service.enabled === false) return { state: 'blocked', reason: `${service.label} is switched off` };+ if (service.readiness && service.readiness !== 'ready') {+ return { state: 'blocked', reason: `${service.label} ${READINESS_REASON[service.readiness] || service.readiness}` };+ }+ return { state: 'offered', reason: null };+}++const CELL_CLASS = {+ offered: 'bg-port-success/20 text-port-success hover:bg-port-success/30 cursor-pointer',+ blocked: 'bg-port-warning/15 text-port-warning',+ incompatible: 'text-gray-600',+};+const CELL_GLYPH = { offered: '●', blocked: '◐', incompatible: '—' };++/**+ * @param {object} props+ * @param {object[]} props.harnesses - catalog rows (`id`, `label`, `modes`, `enabled`).+ * @param {object[]} props.services - catalog rows (`slug`, `label`, `enabled`, `readiness`).+ * @param {Record<string,string[]>} props.compatibility - harness id → compatible service slugs.+ * @param {boolean} props.loading+ * @param {function} props.onCompose - `({ harnessId, method, serviceSlug }) => void` for an offered cell.+ */+export default function ProviderCompatibilityMatrix({ harnesses = [], services = [], compatibility = {}, loading = false, onCompose }) {+ const offered = useMemo(() => harnesses.reduce((count, harness) => count+ + services.filter((service) => matrixCellState(harness, service, compatibility).state === 'offered').length, 0), [harnesses, services, compatibility]);++ return (+ <CollapsibleSection+ id="compatibility-matrix"+ icon={Grid3x3}+ label="Compatibility matrix"+ summary={loading ? 'Loading…' : `${offered} combination${offered === 1 ? '' : 's'} offered`}+ defaultOpen={false}+ size="md"+ className="bg-port-card border border-port-border rounded-xl px-4 py-2"+ bodyClassName="pb-2"+ >+ {services.length === 0 ? (+ <p className="text-xs text-gray-500">No services yet — add one on the Services view and every compatible harness lights up here.</p>+ ) : (+ <div className="overflow-x-auto">+ <table className="text-xs border-separate border-spacing-0 min-w-full" aria-label="Harness and service compatibility">+ <thead>+ <tr>+ <th scope="col" className="sticky left-0 bg-port-card text-left text-gray-500 font-normal pr-3 py-1">Harness</th>+ {services.map((service) => (+ <th key={service.slug} scope="col" className="text-gray-400 font-medium px-2 py-1 whitespace-nowrap">+ <span title={service.slug}>{service.label}</span>+ </th>+ ))}+ </tr>+ </thead>+ <tbody>+ {harnesses.map((harness) => (+ <tr key={harness.id}>+ <th scope="row" className="sticky left-0 bg-port-card text-left text-gray-300 font-medium pr-3 py-1 whitespace-nowrap">+ {harness.label}{harness.enabled === false ? <span className="text-gray-600"> (off)</span> : null}+ </th>+ {services.map((service) => {+ const { state, reason } = matrixCellState(harness, service, compatibility);+ const name = state === 'offered'+ ? `New preset: ${harness.label} on ${service.label}`+ : state === 'blocked' ? `${harness.label} on ${service.label}: ${reason}` : `${harness.label} cannot reach ${service.label}`;+ return (+ <td key={service.slug} className="px-1 py-0.5 text-center">+ {state === 'offered' ? (+ <button+ type="button"+ title={name}+ aria-label={name}+ onClick={() => onCompose({ harnessId: harness.id, method: harness.modes?.[0] || '', serviceSlug: service.slug })}+ className={`inline-flex h-7 w-7 items-center justify-center rounded ${CELL_CLASS.offered}`}+ >+ {CELL_GLYPH.offered}+ </button>+ ) : (+ <span+ role="img"+ title={name}+ aria-label={name}+ className={`inline-flex h-7 w-7 items-center justify-center rounded ${CELL_CLASS[state]}`}+ >+ {CELL_GLYPH[state]}+ </span>+ )}+ </td>+ );+ })}+ </tr>+ ))}+ </tbody>+ </table>+ <p className="mt-2 text-[11px] text-gray-500">● offered — click for a new preset · ◐ compatible but blocked (hover for why) · — not reachable</p>+ </div>+ )}+ </CollapsibleSection>+ );+}diff --git a/client/src/components/providers/ProviderComposePopover.jsx b/client/src/components/providers/ProviderComposePopover.jsxindex 7d9cc9e5be..62feb2644c 100644--- a/client/src/components/providers/ProviderComposePopover.jsx+++ b/client/src/components/providers/ProviderComposePopover.jsx@@ -25,6 +25,13 @@* harnesses offered) to this caller's mode policy, e.g. `['tui']` for* `ShellProviderLauncher`. Omit for no restriction.* @param {string} [props.title] - Panel heading (default: "Compose a custom combination").+ * @param {{harnessId?: string, method?: string, serviceSlug?: string}} [props.initial] -+ * Pre-select these steps on open — the compatibility matrix on the AI+ * Providers page (#7567) opens the flow on the pair the user clicked. Each+ * later step stays open for the user to narrow.+ * @param {boolean} [props.useOnce] - Offer the "Use once" button (default+ * true). The AI Providers page has no selection to hand a composite to, so+ * it offers only "Save as preset".*/import { useEffect, useId, useMemo, useState } from 'react';import Modal from '../ui/Modal.jsx';@@ -51,6 +58,8 @@ export default function ProviderComposePopover({onPresetSaved,allowedMethods,title = 'Compose a custom combination',+ initial = null,+ useOnce = true,}) {const catalog = useProviderCatalog(open);const [harnessId, setHarnessId] = useState('');@@ -66,15 +75,15 @@ export default function ProviderComposePopover({// previous "Use once" choice never lingers into the next open.useEffect(() => {if (!open) return;- setHarnessId('');- setMethod('');- setServiceSlug('');+ setHarnessId(initial?.harnessId || '');+ setMethod(initial?.method || '');+ setServiceSlug(initial?.serviceSlug || '');setModel('');setEffort('');setBootstrapSlug('');setPresetName('');setShowPresetField(false);- }, [open]);+ }, [open, initial]);const harnesses = useMemo(() => (catalog.harnesses || []).filter((harness) => harness.enabled@@ -271,14 +280,16 @@ export default function ProviderComposePopover({)}<div className="flex flex-col sm:flex-row gap-2 mt-1">- <button- type="button"- className="flex-1 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:bg-port-border disabled:opacity-50"- disabled={!canCompose}- onClick={() => { onCompose(compositeId, { model, effort }); onClose(); }}- >- Use once- </button>+ {useOnce && (+ <button+ type="button"+ className="flex-1 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:bg-port-border disabled:opacity-50"+ disabled={!canCompose}+ onClick={() => { onCompose(compositeId, { model, effort }); onClose(); }}+ >+ Use once+ </button>+ )}{!showPresetField ? (<buttontype="button"diff --git a/client/src/components/providers/ProviderConnectionForm.jsx b/client/src/components/providers/ProviderConnectionForm.jsxdeleted file mode 100644index 3b98ee8231..0000000000--- a/client/src/components/providers/ProviderConnectionForm.jsx+++ /dev/null@@ -1,120 +0,0 @@-import { Plus } from 'lucide-react';-import { transportProtocolOptions } from '../../lib/providerManagement';--/**- * Add a backend (#6369) — mock flow 3 in the design record: a new endpoint with- * its own credentials, created as its own identity even when its models match a- * backend already configured. Nothing is contacted when it saves.- *- * ONE transport, which is the server's rule too: a provider record names one- * endpoint, so a backend declaring two could never be the backend its own- * routes describe.- *- * The kind and protocol options come from the graph response- * (`creatableConnectionKinds`, `creatableHarnesses`) rather than a table- * mirrored into the browser — which backends a minted route can honestly- * describe is a server decision.- */-export default function ProviderConnectionForm({ graph, draft, onChange, onSubmit, open, onToggle, busy }) {- const field = (key) => (event) => onChange({ ...draft, [key]: event.target.value });-- return (- <div className="rounded-lg border border-dashed border-port-border p-3">- <button- type="button"- onClick={onToggle}- aria-expanded={open}- className="flex items-center gap-1 text-sm font-medium"- >- <Plus size={14} aria-hidden="true" /> Add a backend- </button>-- {open && (- <div className="mt-3 space-y-3">- <div className="grid gap-3 sm:grid-cols-2">- <label className="block text-sm" htmlFor="new-backend-label">- <span className="mb-1 block text-port-muted">Backend name</span>- <input- id="new-backend-label"- className="w-full rounded border border-port-border bg-port-bg px-2 py-1"- value={draft.label}- onChange={field('label')}- />- </label>- <label className="block text-sm" htmlFor="new-backend-kind">- <span className="mb-1 block text-port-muted">Backend</span>- <select- id="new-backend-kind"- className="w-full rounded border border-port-border bg-port-bg px-2 py-1"- value={draft.kind}- onChange={field('kind')}- >- {(graph?.creatableConnectionKinds || []).map((kind) => (- <option key={kind.id} value={kind.id}>{kind.label}</option>- ))}- </select>- </label>- <label className="block text-sm" htmlFor="new-backend-protocol">- <span className="mb-1 block text-port-muted">Wire protocol</span>- <select- id="new-backend-protocol"- className="w-full rounded border border-port-border bg-port-bg px-2 py-1"- value={draft.protocol}- onChange={field('protocol')}- >- {transportProtocolOptions(graph).map((option) => (- <option key={option.protocol} value={option.protocol}>- {option.protocol} — {option.drivers.join(', ')}- </option>- ))}- </select>- </label>- <label className="block text-sm" htmlFor="new-backend-url">- <span className="mb-1 block text-port-muted">Base URL</span>- <input- id="new-backend-url"- className="w-full rounded border border-port-border bg-port-bg px-2 py-1"- value={draft.baseUrl}- onChange={field('baseUrl')}- placeholder="http://127.0.0.1:11434"- />- </label>- <label className="block text-sm" htmlFor="new-backend-credential-key">- <span className="mb-1 block text-port-muted">Credential name (optional)</span>- <input- id="new-backend-credential-key"- className="w-full rounded border border-port-border bg-port-bg px-2 py-1"- value={draft.credentialKey}- onChange={field('credentialKey')}- placeholder="apiKey"- />- </label>- <label className="block text-sm" htmlFor="new-backend-credential">- <span className="mb-1 block text-port-muted">Credential value (optional)</span>- <input- id="new-backend-credential"- type="password"- autoComplete="off"- className="w-full rounded border border-port-border bg-port-bg px-2 py-1"- value={draft.credential}- onChange={field('credential')}- />- </label>- </div>- <p className="text-xs text-port-muted">- Claude Code speaks <code>anthropic</code> and needs an <code>ANTHROPIC_AUTH_TOKEN</code> credential —- any non-empty value works for a local daemon that ignores it. Nothing is contacted when you save this.- </p>- <button- type="button"- disabled={busy || !draft.label.trim() || !draft.baseUrl.trim()}- onClick={onSubmit}- className="rounded bg-port-accent px-3 py-1 text-sm text-white disabled:opacity-50"- >- Add backend- </button>- </div>- )}- </div>- );-}diff --git a/client/src/components/providers/ProviderConnections.jsx b/client/src/components/providers/ProviderConnections.jsxdeleted file mode 100644index 7547386767..0000000000--- a/client/src/components/providers/ProviderConnections.jsx+++ /dev/null@@ -1,662 +0,0 @@-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { Link2, Link2Off, RefreshCw, Trash2 } from 'lucide-react';-import toast from '../ui/Toast';-import Drawer from '../Drawer';-import Banner from '../ui/Banner';-import EmptyState from '../EmptyState';-import ProviderConnectionForm from './ProviderConnectionForm';-import ProviderHarnessForm from './ProviderHarnessForm';-import ProviderRouteRow from './ProviderRouteRow';-import InlineConfirmRow from '../ui/InlineConfirmRow';-import useConfirmDelete from '../../hooks/useConfirmDelete';-import * as api from '../../services/api';-import { harnessLabel } from '../../utils/providerHarnesses';-import {- bindingModelOffer,- catalogSummary,- findConnectionGroup,- groupGraphByConnection,- staleSelectedModels,-} from '../../lib/providerManagement';--/**- * Backend connection management (#6369) — the deep-linked surface over the- * durable provider graph.- *- * The thing this screen exists to make possible: **edit one backend once**. A- * Claude CLI route, a Claude TUI route and an OpenCode route pointed at the- * same Ollama daemon share ONE connection row here, so its endpoint, its key- * and its model catalog are typed, refreshed and narrowed in one place instead- * of three that drift. Each route below then carries the settings that are its- * own — args, timeout, effort, model pins — so the whole backend is configured- * here rather than on a connection plus three separate route editors.- *- * Three rules the UI is built around, all of them server-enforced too:- *- * - **Identity is never inferred.** Two connections are the same only when- * the server says they share an id. Linking is an explicit, previewed act.- * - **Nothing here grants execution.** Narrowing a catalog, renaming a- * binding, editing an endpoint and tuning one mode's overrides change no- * route's enabled state and no mode's consent. Those stay on the route- * editor, one click away.- * - **A saved value is never hidden.** A pin the catalog no longer offers is- * shown as stale, not dropped.- *- * The selected connection lives in the URL (`/ai/connections/:connectionId`,- * or `/ai/harnesses/:harnessId/connections/:connectionId`) so the open row is- * shareable, bookmarkable and reachable from ⌘K and voice.- */--/**- * A blank "add a backend" form. `openai` is the default protocol because it is- * the one every OpenAI-compatible daemon, gateway and direct API route speaks;- * Claude Code is the exception, and the field says so.- */-const EMPTY_BACKEND_DRAFT = Object.freeze({- label: '', kind: 'ollama', protocol: 'openai', baseUrl: '', credentialKey: '', credential: '',-});--/** What a backend is CALLED on screen — its label, or its id until one is typed. */-const connectionName = (connection) => connection.label || connection.id;--/** How each catalog state reads at a glance — the four are deliberately distinct. */-const CATALOG_TONE_CLASS = {- error: 'text-port-error',- ok: 'text-port-success',- warn: 'text-port-warning',- muted: 'text-port-muted',-};--/** A transports map edited as flat text, back to the wire shape. */-const transportsFromDraft = (draft) => Object.fromEntries(- Object.entries(draft)- .filter(([, baseUrl]) => baseUrl.trim().length > 0)- .map(([protocol, baseUrl]) => [protocol, { baseUrl: baseUrl.trim() }]),-);--const draftFromTransports = (transports) => Object.fromEntries(- Object.entries(transports || {}).map(([protocol, value]) => [protocol, value?.baseUrl || '']),-);--export default function ProviderConnections({- open,- connectionId = null,- harnessId = null,- onClose,- onSelectConnection,- onGraphChanged,-}) {- const [graph, setGraph] = useState(null);- const [unsupported, setUnsupported] = useState(false);- const [loading, setLoading] = useState(true);- const [loadError, setLoadError] = useState(null);- const [busy, setBusy] = useState(false);-- // Edit drafts live here rather than in uncontrolled inputs so a reload of the- // graph (after a refresh or a link) cannot silently discard a half-typed edit- // without the code saying so.- const [labelDraft, setLabelDraft] = useState('');- const [transportDraft, setTransportDraft] = useState({});- const [credentialDraft, setCredentialDraft] = useState('');- const [linkTarget, setLinkTarget] = useState({});- const [linkPreview, setLinkPreview] = useState(null);-- // Creating a backend, and adding a harness to one (#6369). Both drafts live- // here for the same reason the edit drafts above do: a graph reload after any- // write must not silently discard a half-typed create.- const [addingBackend, setAddingBackend] = useState(false);- const [backendDraft, setBackendDraft] = useState(EMPTY_BACKEND_DRAFT);- const [harnessDraft, setHarnessDraft] = useState({});- // Deleting a backend throws away its stored key as well as the row, and the- // button sits beside Save/Refresh — so it asks first. This component owns N- // backend rows, so the armed one is id-keyed rather than a boolean.- const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();-- const loadGraph = useCallback(async () => {- setLoading(true);- const next = await api.getProviderManagementGraph({ silent: true }).catch((err) => ({ err }));- setLoading(false);- if (next?.err) {- // Only an explicit "no such API" downgrades the view. A 500 or an offline- // server stays an error, or a working install would quietly lose its- // management screen the first time a request failed.- if (api.isManagementUnsupported(next.err)) {- setUnsupported(true);- setGraph(null);- return;- }- setLoadError(next.err.message || 'Could not load the connection graph.');- return;- }- setUnsupported(false);- setLoadError(null);- setGraph(next);- }, []);-- useEffect(() => { if (open) loadGraph(); }, [open, loadGraph]);-- const groups = useMemo(() => groupGraphByConnection(graph), [graph]);- const selected = useMemo(- () => (connectionId ? findConnectionGroup(groups, connectionId) : null),- [groups, connectionId],- );-- // Re-seed the drafts when the selection or its revision moves — and ONLY- // then, so a poll that changed nothing cannot wipe a half-typed edit.- //- // `id` + `revision` is a complete key, not a shortcut: the server bumps the- // revision on every write to a connection row, so the label and transports- // below cannot change without it changing too.- // Read through a ref inside the effect: the connection OBJECT is a new- // identity on every poll, so depending on it would re-seed (and wipe) the- // drafts every few seconds. The ref carries the current values; the two- // primitives decide when to apply them.- const selectedId = selected?.connection.id ?? null;- const selectedRevision = selected?.connection.revision ?? null;- const connectionRef = useRef(null);- connectionRef.current = selected?.connection ?? null;- useEffect(() => {- const connection = connectionRef.current;- if (!connection) return;- setLabelDraft(connection.label || '');- setTransportDraft(draftFromTransports(connection.transports));- setCredentialDraft('');- setLinkPreview(null);- }, [selectedId, selectedRevision]);-- // A deep link naming a connection this install does not have should say so- // and fall back, not render an empty panel forever.- useEffect(() => {- if (loading || !graph || !connectionId || selected) return;- toast.error(`No connection with id "${connectionId}"`);- onSelectConnection(null);- }, [loading, graph, connectionId, selected, onSelectConnection]);-- const run = useCallback(async (label, work) => {- setBusy(true);- const result = await work().catch((err) => ({ err }));- setBusy(false);- if (result?.err) {- toast.error(result.err.message || `${label} failed.`);- return null;- }- await loadGraph();- onGraphChanged?.();- return result;- }, [loadGraph, onGraphChanged]);-- /**- * Add a backend. One transport only, which is the server's rule too: a- * provider record names one endpoint, so a backend declaring two could never- * be the backend its own routes describe.- */- const createBackend = useCallback(async () => {- const draft = backendDraft;- const credentialKey = draft.credentialKey.trim() || 'apiKey';- const created = await run('Adding the backend', () => api.createProviderConnection({- kind: draft.kind,- label: draft.label.trim(),- transports: { [draft.protocol]: { baseUrl: draft.baseUrl.trim() } },- ...(draft.credential.trim() ? { credentials: { [credentialKey]: draft.credential.trim() } } : {}),- }, { silent: true }));- if (!created) return;- setBackendDraft(EMPTY_BACKEND_DRAFT);- setAddingBackend(false);- // Open what was just made: the next step is adding a harness to it, and- // that control lives inside the panel.- onSelectConnection(created.connection.id);- toast.success('Backend added. Nothing was contacted — add a harness to give it a route.');- }, [backendDraft, run, onSelectConnection]);-- /**- * Add a harness to a backend, minting one route per checked mode.- *- * Every minted route arrives disabled: this creates the configuration, it- * does not grant it permission to run.- */- const addHarness = useCallback(async (connection, draft) => {- const created = await run('Adding the harness', () => api.createProviderBinding({- connectionId: connection.id,- harnessId: draft.harnessId ?? null,- modes: draft.modes,- }, { silent: true }));- if (!created) return;- setHarnessDraft(({ [connection.id]: _cleared, ...rest }) => rest);- toast.success(`Added ${created.routeIds.join(', ')} — disabled, so nothing runs until you enable it.`);- }, [run]);-- const saveConnection = useCallback(async () => {- if (!selected) return;- const credentials = credentialDraft.trim().length > 0- ? { apiKey: credentialDraft.trim() }- : undefined;- const saved = await run('Saving the connection', () => api.updateProviderConnection(- selected.connection.id,- {- expectedRevision: selected.connection.revision,- label: labelDraft,- transports: transportsFromDraft(transportDraft),- ...(credentials ? { credentials } : {}),- },- { silent: true },- ));- if (saved) toast.success(`Saved — ${saved.affectedRouteIds.length} route(s) updated to match.`);- }, [selected, labelDraft, transportDraft, credentialDraft, run]);-- const clearCredential = useCallback(async () => {- if (!selected) return;- const saved = await run('Clearing the credential', () => api.updateProviderConnection(- selected.connection.id,- { expectedRevision: selected.connection.revision, credentials: { apiKey: null } },- { silent: true },- ));- if (saved) toast.success('Credential cleared on this backend and every route using it.');- }, [selected, run]);-- const refreshModels = useCallback(async () => {- if (!selected) return;- const result = await run('Refreshing models', () =>- api.refreshProviderConnectionModels(selected.connection.id, { silent: true }));- if (!result) return;- if (result.catalog.state === 'failed') {- toast.error(result.catalog.error || 'The model refresh failed — the previous catalog was kept.');- return;- }- toast.success(`${result.catalog.models.length} model(s) shared across ${selected.bindings.length} harness binding(s).`);- }, [selected, run]);-- const saveBindingModels = useCallback(async (binding, selectedModels) => {- // `[]` on the wire means "offer the whole shared catalog", so clearing the- // last checkbox would silently re-select everything — the opposite of the- // click. Refuse it and say why; removing a harness is a route action, not a- // model menu one.- if (selectedModels.length === 0) {- toast.error('Keep at least one model — an empty selection means the whole shared catalog.');- return;- }- const saved = await run('Saving the model selection', () => api.updateProviderBinding(- binding.id,- { expectedRevision: binding.revision, selectedModels },- { silent: true },- ));- if (saved) toast.success('Model selection saved. Existing pins were left as they were.');- }, [run]);-- const previewLink = useCallback(async (binding, targetConnectionId) => {- if (!targetConnectionId) return;- const target = findConnectionGroup(groups, targetConnectionId);- const preview = await api.previewProviderBindingLink(- binding.id,- { targetConnectionId, expectedRevisions: { binding: binding.revision } },- { silent: true },- ).catch((err) => ({ err }));- if (preview?.err) {- toast.error(preview.err.message || 'Could not preview that link.');- return;- }- setLinkPreview({- ...preview,- bindingId: binding.id,- targetConnectionId,- targetLabel: target?.connection.label || targetConnectionId,- });- }, [groups]);-- const applyLink = useCallback(async () => {- if (!linkPreview) return;- const applied = await run('Linking', () => api.linkProviderBinding(- linkPreview.bindingId,- { targetConnectionId: linkPreview.revisions ? linkPreview.targetConnectionId ?? undefined : undefined, expectedRevisions: linkPreview.revisions },- { silent: true },- ));- if (applied) {- setLinkPreview(null);- toast.success(`Linked — ${applied.affectedRouteIds.length} route(s) now use that backend.`);- }- }, [linkPreview, run]);-- const unlink = useCallback(async (binding) => {- const done = await run('Unlinking', () => api.unlinkProviderBinding(- binding.id,- { expectedRevisions: { binding: binding.revision } },- { silent: true },- ));- if (done) toast.success('This harness now has its own copy. Route ids and pins are unchanged.');- }, [run]);-- const removeConnection = useCallback(async (connection) => {- const done = await run('Deleting the connection', () =>- api.deleteProviderConnection(connection.id, { silent: true }));- if (done) {- toast.success('Connection deleted.');- onSelectConnection(null);- }- }, [run, onSelectConnection]);-- const makeDefault = useCallback(async (providerId) => {- const done = await run('Setting the system default', () => api.setActiveProvider(providerId));- if (done) toast.success(`${providerId} is now the system default route.`);- }, [run]);-- // Route-scoped, so the reload afterwards is the same one every other write- // here does: this mode's siblings are untouched and no other harness moves.- const saveRouteSettings = useCallback(async (route, settings) => {- const saved = await run('Saving the overrides', () => api.updateProviderRouteSettings(- route.providerId,- { expectedRevision: route.settingsRevision, settings },- { silent: true },- ));- if (saved) toast.success(`${route.providerId}: ${Object.keys(settings).length} setting(s) saved for this mode only.`);- }, [run]);-- // A hand-authored alias for what THIS harness must be sent for a backend- // model. Resolves to the saved row so the form can clear only on a save that- // landed, and `null` for a key is the removal — nothing else drops one.- const saveRouteAliases = useCallback(async (route, aliases) => {- const saved = await run('Saving the model alias', () => api.updateProviderRouteModelAliases(- route.providerId,- { expectedRevision: route.modelAliasRevision, aliases },- { silent: true },- ));- if (saved) {- const removed = Object.values(aliases).filter((value) => value === null).length;- toast.success(removed > 0- ? 'Alias removed. What the last refresh observed is unchanged.'- : 'Alias saved — it wins over what a refresh finds, and survives the next one.');- }- return saved;- }, [run]);-- return (- <Drawer- open={open}- onClose={onClose}- size="lg"- title="Backend connections"- subtitle={harnessId ? `Scoped to ${harnessLabel(harnessId)}` : 'One backend, shared by every harness pointed at it'}- closeLabel="Close connection management"- >- {unsupported && (- <Banner tone="info">- This PortOS server does not expose connection management. Provider routes are still fully- editable from the provider list behind this panel.- </Banner>- )}- {loadError && <Banner tone="error">{loadError}</Banner>}-- {!unsupported && !loadError && (- <div className="space-y-4">- {loading && <p className="text-sm text-port-muted">Loading connections…</p>}-- <ProviderConnectionForm- graph={graph}- draft={backendDraft}- onChange={setBackendDraft}- onSubmit={createBackend}- open={addingBackend}- onToggle={() => setAddingBackend((isOpen) => !isOpen)}- busy={busy}- />-- {!loading && groups.length === 0 && (- <EmptyState- title="No managed connections yet"- message="Connections are imported from your existing provider routes the first time the graph runs — or add one above and give it a harness."- />- )}-- {groups- .filter((group) => !harnessId- || group.bindings.some((entry) => entry.binding.harnessId === harnessId))- .map((group) => {- const isOpen = group.connection.id === connectionId;- const confirmingDelete = isConfirming(group.connection.id);- const summary = catalogSummary(group.connection.catalog);- return (- <section key={group.connection.id} className="rounded-lg border border-port-border bg-port-card">- <button- type="button"- onClick={() => onSelectConnection(isOpen ? null : group.connection.id)}- aria-expanded={isOpen}- className="flex w-full flex-col gap-1 p-3 text-left sm:flex-row sm:items-center sm:justify-between"- >- <span className="min-w-0">- <span className="block truncate font-medium">{connectionName(group.connection)}</span>- <span className="block text-xs text-port-muted">- {group.connection.kind}- {' · '}- {Object.entries(group.connection.transports)- .map(([protocol, value]) => `${protocol} ${value.baseUrl}`)- .join(' · ') || 'no endpoint declared'}- {group.connection.hasCredentials ? ' · key set' : ''}- </span>- </span>- <span className={`shrink-0 text-xs ${CATALOG_TONE_CLASS[summary.tone]}`}>- {summary.text}- </span>- </button>-- {isOpen && (- <div className="space-y-4 border-t border-port-border p-3">- {summary.detail && <Banner tone="error">{summary.detail}</Banner>}-- <div className="grid gap-3 sm:grid-cols-2">- <label className="block text-sm" htmlFor={`conn-label-${group.connection.id}`}>- <span className="mb-1 block text-port-muted">Name</span>- <input- id={`conn-label-${group.connection.id}`}- className="w-full rounded border border-port-border bg-port-bg px-2 py-1"- value={labelDraft}- onChange={(e) => setLabelDraft(e.target.value)}- />- </label>- <label className="block text-sm" htmlFor={`conn-key-${group.connection.id}`}>- <span className="mb-1 block text-port-muted">- API key {group.connection.hasCredentials ? '(set — leave blank to keep)' : '(none)'}- </span>- <input- id={`conn-key-${group.connection.id}`}- type="password"- autoComplete="off"- className="w-full rounded border border-port-border bg-port-bg px-2 py-1"- value={credentialDraft}- onChange={(e) => setCredentialDraft(e.target.value)}- placeholder={group.connection.hasCredentials ? 'Unchanged' : 'Not set'}- />- </label>- {Object.entries(transportDraft).map(([protocol, baseUrl]) => (- <label key={protocol} className="block text-sm" htmlFor={`conn-${group.connection.id}-${protocol}`}>- <span className="mb-1 block text-port-muted">{protocol} endpoint</span>- <input- id={`conn-${group.connection.id}-${protocol}`}- className="w-full rounded border border-port-border bg-port-bg px-2 py-1"- value={baseUrl}- onChange={(e) => setTransportDraft((prev) => ({ ...prev, [protocol]: e.target.value }))}- />- </label>- ))}- </div>-- <div className="flex flex-wrap gap-2">- <button type="button" disabled={busy} onClick={saveConnection}- className="rounded bg-port-accent px-3 py-1 text-sm text-white disabled:opacity-50">- Save backend- </button>- <button type="button" disabled={busy} onClick={refreshModels}- className="flex items-center gap-1 rounded border border-port-border px-3 py-1 text-sm disabled:opacity-50">- <RefreshCw size={14} aria-hidden="true" /> Refresh models- </button>- {group.connection.hasCredentials && (- <button type="button" disabled={busy} onClick={clearCredential}- className="rounded border border-port-border px-3 py-1 text-sm disabled:opacity-50">- Clear key- </button>- )}- {group.bindings.length === 0 && !confirmingDelete && (- <button type="button" disabled={busy} onClick={() => requestDelete(group.connection.id)}- className="flex items-center gap-1 rounded border border-port-error px-3 py-1 text-sm text-port-error disabled:opacity-50">- <Trash2 size={14} aria-hidden="true" /> Delete- </button>- )}- </div>-- {confirmingDelete && (- <InlineConfirmRow- question={`Delete the ${connectionName(group.connection)} backend? Its endpoint, catalog and saved key go with it.`}- confirmText="Delete backend"- autoFocus- aria-label={`Confirm deleting the ${connectionName(group.connection)} backend`}- onConfirm={() => confirmDelete(() => removeConnection(group.connection))}- onCancel={cancelDelete}- />- )}-- <ProviderHarnessForm- graph={graph}- connection={group.connection}- draft={harnessDraft[group.connection.id]}- onChange={(next) => setHarnessDraft((prev) => ({ ...prev, [group.connection.id]: next }))}- onSubmit={(input) => addHarness(group.connection, input)}- busy={busy}- />-- {group.bindings.map(({ binding, label, routes }) => {- const offer = bindingModelOffer(group.connection, binding);- const stale = staleSelectedModels(group.connection, binding);- const chosen = offer.filter((entry) => entry.selected).map((entry) => entry.model);- return (- <div key={binding.id} className="rounded border border-port-border p-3">- <div className="mb-2 flex flex-wrap items-center justify-between gap-2">- <h4 className="font-medium">{label}</h4>- <span className="text-xs text-port-muted">- {binding.variantKey !== 'default' ? `${binding.variantKey} · ` : ''}- {routes.length} route{routes.length === 1 ? '' : 's'}- </span>- </div>-- {binding.blocked && (- <Banner tone="warning">- This binding has an unresolved projection and cannot be changed until it settles.- </Banner>- )}-- <ul className="mb-3 space-y-2">- {routes.map((route) => (- <ProviderRouteRow- key={route.providerId}- route={route}- isSystemDefault={graph?.activeProvider === route.providerId}- busy={busy}- blocked={binding.blocked}- onMakeDefault={makeDefault}- onSaveSettings={saveRouteSettings}- onSaveAliases={saveRouteAliases}- />- ))}- </ul>-- {offer.length > 0 && (- <fieldset className="mb-2">- <legend className="mb-1 text-xs text-port-muted">- Models this harness offers (from the shared catalog)- </legend>- <div className="flex flex-wrap gap-2">- {offer.map((entry) => (- <label key={entry.model} className="flex items-center gap-1 text-sm"- htmlFor={`model-${binding.id}-${entry.model}`}>- <input- id={`model-${binding.id}-${entry.model}`}- type="checkbox"- checked={entry.selected}- disabled={busy || binding.blocked}- onChange={(e) => saveBindingModels(- binding,- e.target.checked- ? [...chosen, entry.model]- : chosen.filter((model) => model !== entry.model),- )}- />- {entry.model}- </label>- ))}- </div>- </fieldset>- )}-- {stale.length > 0 && (- <p className="mb-2 text-xs text-port-warning">- Still selected but not in the current catalog: {stale.join(', ')} — kept as-is.- </p>- )}-- <div className="flex flex-wrap items-center gap-2">- <label className="sr-only" htmlFor={`link-${binding.id}`}>Move this harness to another backend</label>- <select- id={`link-${binding.id}`}- className="rounded border border-port-border bg-port-bg px-2 py-1 text-sm"- value={linkTarget[binding.id] || ''}- disabled={busy || binding.blocked}- onChange={(e) => setLinkTarget((prev) => ({ ...prev, [binding.id]: e.target.value }))}- >- <option value="">Move to another backend…</option>- {groups- .filter((candidate) => candidate.connection.id !== group.connection.id)- .map((candidate) => (- <option key={candidate.connection.id} value={candidate.connection.id}>- {connectionName(candidate.connection)}- </option>- ))}- </select>- <button type="button" disabled={busy || binding.blocked || !linkTarget[binding.id]}- onClick={() => previewLink(binding, linkTarget[binding.id])}- className="flex items-center gap-1 rounded border border-port-border px-3 py-1 text-sm disabled:opacity-50">- <Link2 size={14} aria-hidden="true" /> Preview- </button>- {group.bindings.length > 1 && (- <button type="button" disabled={busy || binding.blocked} onClick={() => unlink(binding)}- className="flex items-center gap-1 rounded border border-port-border px-3 py-1 text-sm disabled:opacity-50">- <Link2Off size={14} aria-hidden="true" /> Give it its own copy- </button>- )}- </div>-- {linkPreview?.bindingId === binding.id && (- <div className="mt-2 rounded border border-port-accent p-2 text-sm">- <p className="mb-1">- Moving <strong>{label}</strong> to <strong>{linkPreview.targetLabel}</strong> changes- the backend for {linkPreview.affectedRouteIds.length} route(s):- {' '}{linkPreview.affectedRouteIds.join(', ')}.- </p>- {linkPreview.differences.length > 0 && (- <p className="mb-1 text-port-warning">- The two backends differ in: {linkPreview.differences.join(', ')}.- </p>- )}- <p className="mb-2 text-xs text-port-muted">- Route ids, model pins, fallbacks and the system default are unchanged.- </p>- <div className="flex gap-2">- <button type="button" disabled={busy} onClick={applyLink}- className="rounded bg-port-accent px-3 py-1 text-sm text-white disabled:opacity-50">- Apply link- </button>- <button type="button" onClick={() => setLinkPreview(null)}- className="rounded border border-port-border px-3 py-1 text-sm">- Cancel- </button>- </div>- </div>- )}- </div>- );- })}- </div>- )}- </section>- );- })}- </div>- )}- </Drawer>- );-}diff --git a/client/src/components/providers/ProviderConnections.test.jsx b/client/src/components/providers/ProviderConnections.test.jsxdeleted file mode 100644index 46825cf663..0000000000--- a/client/src/components/providers/ProviderConnections.test.jsx+++ /dev/null@@ -1,510 +0,0 @@-/**- * The connection-management surface, rendered (#6369).- *- * What only a rendered test can prove: that the screen a human actually uses- * carries the promises the server enforces — one backend edit reported as- * reaching every harness on it, a narrowed catalog that sends the SUBSET rather- * than a toggle, a pin the catalog no longer offers shown instead of dropped,- * a failed refresh that keeps the old models, and an older server answering- * "no such API" degrading to a message instead of an error state.- *- * Fixtures are synthetic. Nothing here is read out of a running install.- */-import { describe, expect, it, vi, beforeEach } from 'vitest';-import { render, screen, fireEvent, waitFor } from '@testing-library/react';-import { MemoryRouter } from 'react-router';--const api = vi.hoisted(() => ({- getProviderManagementGraph: vi.fn(),- updateProviderConnection: vi.fn(),- updateProviderBinding: vi.fn(),- refreshProviderConnectionModels: vi.fn(),- previewProviderBindingLink: vi.fn(),- linkProviderBinding: vi.fn(),- unlinkProviderBinding: vi.fn(),- deleteProviderConnection: vi.fn(),- createProviderConnection: vi.fn(),- createProviderBinding: vi.fn(),- updateProviderRouteSettings: vi.fn(),- updateProviderRouteModelAliases: vi.fn(),- setActiveProvider: vi.fn(),- isManagementUnsupported: (error) => error?.status === 404 || error?.code === 'PROVIDER_GRAPH_UNAVAILABLE',-}));-vi.mock('../../services/api', () => api);--const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));-vi.mock('../ui/Toast', () => ({ default: toast }));--const ProviderConnections = (await import('./ProviderConnections')).default;--const CONNECTION = '11111111-1111-4111-8111-111111111111';-const OTHER = '22222222-2222-4222-8222-222222222222';-const CLAUDE_BINDING = '33333333-3333-4333-8333-333333333333';--const graphFixture = () => ({- schemaVersion: 1,- activeProvider: 'claude-ollama',- // The static create surface the server publishes, so the browser never has to- // mirror which harnesses carry a command recipe.- creatableHarnesses: [- { id: 'claude', label: 'Claude Code', modes: ['cli', 'tui'], protocol: 'anthropic', credentialKey: 'ANTHROPIC_AUTH_TOKEN', credentialRequired: true },- { id: 'opencode', label: 'OpenCode', modes: ['cli', 'tui'], protocol: 'openai', credentialKey: 'apiKey', credentialRequired: false },- ],- creatableConnectionKinds: [{ id: 'ollama', label: 'Ollama' }, { id: 'api', label: 'Direct API' }],- connections: [- {- id: CONNECTION,- revision: 3,- kind: 'ollama',- label: 'Example local daemon',- transports: { anthropic: { baseUrl: 'http://127.0.0.1:11434' } },- hasCredentials: true,- catalog: { state: 'known', models: ['example-model', 'other-model'] },- },- {- id: OTHER,- revision: 1,- kind: 'ollama',- label: 'Remote daemon',- transports: { anthropic: { baseUrl: 'https://ollama.example.com' } },- hasCredentials: false,- catalog: { state: 'unknown', models: [] },- },- ],- bindings: [{- id: CLAUDE_BINDING, revision: 4, connectionId: CONNECTION, harnessId: 'claude',- variantKey: 'default', label: '', enabled: true,- // `retired-model` is gone from the catalog above — a stale pin, on purpose.- selectedModels: ['example-model', 'retired-model'],- blocked: false,- }],- routes: [- // `settings` is what the server published as route-owned for this MODE, and- // `settingsRevision` the fingerprint a save must echo. The TUI route also- // carries the server-resolved command line that enables the Shell hand-off.- {- providerId: 'claude-ollama', bindingId: CLAUDE_BINDING, mode: 'cli', modelMap: {}, projectionPending: false,- settings: {- args: ['--verbose'], timeout: 60000, effort: 'high', defaultModel: 'example-model',- lightModel: null, mediumModel: null, heavyModel: null, ultraModel: null,- },- settingsRevision: 'cli-fingerprint',- effortLevels: ['low', 'medium', 'high'],- modelAliasOverrides: {},- modelAliasRevision: 'cli-aliases',- staleModelAliases: [],- },- {- providerId: 'claude-ollama-tui', bindingId: CLAUDE_BINDING, mode: 'tui', modelMap: {}, projectionPending: false,- settings: {- args: [], timeout: 60000, effort: null, defaultModel: 'example-model',- lightModel: null, mediumModel: null, heavyModel: null, ultraModel: null,- },- settingsRevision: 'tui-fingerprint',- effortLevels: ['low', 'medium', 'high'],- modelAliasOverrides: {},- modelAliasRevision: 'tui-aliases',- staleModelAliases: [],- tuiCommandLine: 'claude --dangerously-skip-permissions',- },- ],-});--const renderPanel = (props = {}) => render(- <MemoryRouter>- <ProviderConnections- open- connectionId={CONNECTION}- onClose={() => {}}- onSelectConnection={() => {}}- {...props}- />- </MemoryRouter>,-);--beforeEach(() => {- vi.clearAllMocks();- api.getProviderManagementGraph.mockResolvedValue(graphFixture());-});--describe('backend connection management', () => {- it('shows one backend with the harness routes that share it, and never a secret', async () => {- renderPanel();-- expect(await screen.findByText('Example local daemon')).toBeInTheDocument();- // The harness label comes from the mirrored registry, not a raw id.- expect(screen.getByRole('heading', { name: 'Claude Code' })).toBeInTheDocument();- // Both executable routes on that one backend are listed and deep-linkable.- expect(screen.getByRole('link', { name: 'claude-ollama' })).toHaveAttribute('href', '/ai/edit/claude-ollama');- expect(screen.getByRole('link', { name: 'claude-ollama-tui' })).toBeInTheDocument();- // Presence only. The field is a placeholder, never a value to leak or resend.- expect(screen.getByLabelText(/API key/)).toHaveValue('');- });-- it('sends the connection revision it was showing, so a moved row is refused', async () => {- api.updateProviderConnection.mockResolvedValue({ affectedRouteIds: ['claude-ollama', 'claude-ollama-tui'] });- renderPanel();-- // Wait for the SEEDED value, not just for the field to exist. The panel- // re-seeds its drafts from the loaded connection in an effect keyed on- // id + revision; typing before that effect has run lets it overwrite the- // edit, and the save then sends the original label. Green on a fast- // machine, red on a loaded CI runner.- const name = await screen.findByLabelText('Name');- await waitFor(() => expect(name).toHaveValue('Example local daemon'));- fireEvent.change(name, { target: { value: 'Renamed daemon' } });- fireEvent.click(screen.getByRole('button', { name: 'Save backend' }));-- await waitFor(() => expect(api.updateProviderConnection).toHaveBeenCalled());- const [id, body] = api.updateProviderConnection.mock.calls[0];- expect(id).toBe(CONNECTION);- expect(body.expectedRevision).toBe(3);- expect(body.label).toBe('Renamed daemon');- // Omitted, not sent blank — the browser never had the secret to resend.- expect(body).not.toHaveProperty('credentials');- });-- it('reports how many routes a single backend edit moved', async () => {- api.updateProviderConnection.mockResolvedValue({ affectedRouteIds: ['claude-ollama', 'claude-ollama-tui'] });- renderPanel();-- fireEvent.click(await screen.findByRole('button', { name: 'Save backend' }));-- await waitFor(() => expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('2 route(s)')));- });-- it('saves a narrowed catalog as the resulting SUBSET, not a toggle', async () => {- api.updateProviderBinding.mockResolvedValue({ selectedModels: ['example-model'] });- renderPanel();-- // `other-model` is in the catalog but not selected; checking it adds it.- fireEvent.click(await screen.findByLabelText('other-model'));-- await waitFor(() => expect(api.updateProviderBinding).toHaveBeenCalled());- const [bindingId, body] = api.updateProviderBinding.mock.calls[0];- expect(bindingId).toBe(CLAUDE_BINDING);- expect(body.expectedRevision).toBe(4);- expect(body.selectedModels).toEqual(['example-model', 'other-model']);- });-- it('shows a pin the catalog no longer offers instead of dropping it', async () => {- renderPanel();- expect(await screen.findByText(/Still selected but not in the current catalog: retired-model/))- .toBeInTheDocument();- });-- it('keeps the previous models visible when a refresh fails', async () => {- api.refreshProviderConnectionModels.mockResolvedValue({- catalog: { state: 'failed', models: ['example-model', 'other-model'], error: 'connect ECONNREFUSED' },- });- api.getProviderManagementGraph.mockResolvedValue({- ...graphFixture(),- connections: graphFixture().connections.map((connection) => (connection.id === CONNECTION- ? { ...connection, catalog: { state: 'failed', models: ['example-model', 'other-model'], error: 'connect ECONNREFUSED' } }- : connection)),- });- renderPanel();-- fireEvent.click(await screen.findByRole('button', { name: /Refresh models/ }));-- await waitFor(() => expect(toast.error).toHaveBeenCalledWith('connect ECONNREFUSED'));- // Not "0 models" — the distinction the catalog state exists to preserve.- expect(await screen.findByText(/showing 2 previously known models/)).toBeInTheDocument();- });-- it('previews a link before applying it, and applies with the reviewed revisions', async () => {- api.previewProviderBindingLink.mockResolvedValue({- revisions: { binding: 4, sourceConnection: 3, targetConnection: 1 },- affectedRouteIds: ['claude-ollama', 'claude-ollama-tui'],- differences: ['credentials'],- unionModels: ['example-model'],- });- api.linkProviderBinding.mockResolvedValue({ affectedRouteIds: ['claude-ollama', 'claude-ollama-tui'] });- renderPanel();-- fireEvent.change(await screen.findByLabelText('Move this harness to another backend'), { target: { value: OTHER } });- fireEvent.click(screen.getByRole('button', { name: /Preview/ }));-- expect(await screen.findByText(/differ in: credentials/)).toBeInTheDocument();- // Nothing is written by looking.- expect(api.linkProviderBinding).not.toHaveBeenCalled();-- fireEvent.click(screen.getByRole('button', { name: 'Apply link' }));- await waitFor(() => expect(api.linkProviderBinding).toHaveBeenCalled());- expect(api.linkProviderBinding.mock.calls[0][1]).toEqual({- targetConnectionId: OTHER,- expectedRevisions: { binding: 4, sourceConnection: 3, targetConnection: 1 },- });- });-- it('degrades to a message on a server without the management API', async () => {- api.getProviderManagementGraph.mockRejectedValue(Object.assign(new Error('Not Found'), { status: 404 }));- renderPanel();-- expect(await screen.findByText(/does not expose connection management/)).toBeInTheDocument();- });-- it('keeps a real failure a real failure', async () => {- api.getProviderManagementGraph.mockRejectedValue(- Object.assign(new Error('Database is on fire'), { status: 500 }),- );- renderPanel();-- expect(await screen.findByText('Database is on fire')).toBeInTheDocument();- expect(screen.queryByText(/does not expose connection management/)).not.toBeInTheDocument();- });-});--describe('the empty-selection inversion', () => {- it('refuses to clear the last model, because `[]` means the whole catalog', async () => {- renderPanel();-- // `example-model` is the only CATALOG entry currently selected (the other- // selection, `retired-model`, is stale and not offered), so unchecking it- // would send `[]` — read by every consumer as "offer everything".- fireEvent.click(await screen.findByLabelText('example-model'));-- await waitFor(() => expect(toast.error).toHaveBeenCalledWith(expect.stringContaining('at least one model')));- expect(api.updateProviderBinding).not.toHaveBeenCalled();- });-});--describe('a route row', () => {- const openOverrides = async (name) => {- renderPanel();- const rows = await screen.findAllByRole('button', { name: /Overrides & aliases/ });- fireEvent.click(rows[name === 'claude-ollama' ? 0 : 1]);- };-- it('hands a TUI route to the Shell page and shows what it will run', async () => {- renderPanel();-- const launch = await screen.findByRole('link', { name: /Launch in Shell/ });- // The provider id alone: the env the launch needs is secret and is- // re-resolved server-side when the PTY spawns.- expect(launch).toHaveAttribute('href', '/shell?provider=claude-ollama-tui');- expect(launch).toHaveAttribute('title', expect.stringContaining('claude --dangerously-skip-permissions'));- // Exactly one — the CLI route on the same harness is not launchable by hand.- expect(screen.getAllByRole('link', { name: /Launch in Shell/ })).toHaveLength(1);- });-- it('sends only the fields that changed, with the fingerprint it was showing', async () => {- api.updateProviderRouteSettings.mockResolvedValue({ providerId: 'claude-ollama' });- await openOverrides('claude-ollama');-- fireEvent.change(screen.getByLabelText(/Launch arguments/), { target: { value: '--verbose\n--debug' } });- fireEvent.click(screen.getByRole('button', { name: 'Save overrides' }));-- await waitFor(() => expect(api.updateProviderRouteSettings).toHaveBeenCalled());- const [providerId, body] = api.updateProviderRouteSettings.mock.calls[0];- expect(providerId).toBe('claude-ollama');- expect(body.expectedRevision).toBe('cli-fingerprint');- // The timeout, effort and pins the human never touched are absent, so a- // save cannot rewrite a value the route editor changed a moment ago.- expect(body.settings).toEqual({ args: ['--verbose', '--debug'] });- });-- it('reads a cleared pin as unset rather than as an empty string', async () => {- api.updateProviderRouteSettings.mockResolvedValue({ providerId: 'claude-ollama' });- await openOverrides('claude-ollama');-- fireEvent.change(screen.getByLabelText('Default model'), { target: { value: '' } });- fireEvent.click(screen.getByRole('button', { name: 'Save overrides' }));-- await waitFor(() => expect(api.updateProviderRouteSettings).toHaveBeenCalled());- expect(api.updateProviderRouteSettings.mock.calls[0][1].settings).toEqual({ defaultModel: null });- });-- it('cannot save until something differs, and reverts back to the saved values', async () => {- await openOverrides('claude-ollama');-- const save = screen.getByRole('button', { name: 'Save overrides' });- expect(save).toBeDisabled();-- fireEvent.change(screen.getByLabelText('Heavy tier model'), { target: { value: 'other-model' } });- expect(save).toBeEnabled();-- fireEvent.click(screen.getByRole('button', { name: 'Revert' }));- expect(screen.getByLabelText('Heavy tier model')).toHaveValue('');- expect(screen.getByRole('button', { name: 'Save overrides' })).toBeDisabled();- expect(api.updateProviderRouteSettings).not.toHaveBeenCalled();- });-- it('offers only the effort levels this harness accepts', async () => {- await openOverrides('claude-ollama');-- const options = [...screen.getByLabelText('Reasoning effort').options].map((option) => option.value);- // The blank first option is "harness default", not a level.- expect(options).toEqual(['', 'low', 'medium', 'high']);- });-});--describe('an override the harness no longer offers', () => {- it('stays selected instead of reading as a clear the moment the panel opens', async () => {- const graph = graphFixture();- // The stored level is real and saved; this build's ladder for the harness- // simply no longer lists it — the same shape as a model pin outside the- // catalog, and it must not be silently offered up for deletion.- graph.routes[0].settings.effort = 'ultra';- api.getProviderManagementGraph.mockResolvedValue(graph);- renderPanel();-- const rows = await screen.findAllByRole('button', { name: /Overrides & aliases/ });- fireEvent.click(rows[0]);-- expect(screen.getByLabelText('Reasoning effort')).toHaveValue('ultra');- expect(screen.getByRole('button', { name: 'Save overrides' })).toBeDisabled();- });-});--describe('hand-authored model aliases', () => {- const openRoute = async (index = 0) => {- renderPanel();- const rows = await screen.findAllByRole('button', { name: /Overrides & aliases/ });- fireEvent.click(rows[index]);- };-- it('sends the pair a human typed with the fingerprint the panel was showing', async () => {- api.updateProviderRouteModelAliases.mockResolvedValue({ providerId: 'claude-ollama' });- await openRoute();-- fireEvent.change(screen.getByLabelText('Backend model name'), { target: { value: 'example-model' } });- fireEvent.change(screen.getByLabelText('What this harness is sent'),- { target: { value: 'namespace/example-model' } });- fireEvent.click(screen.getByRole('button', { name: 'Add alias' }));-- await waitFor(() => expect(api.updateProviderRouteModelAliases).toHaveBeenCalled());- const [providerId, body] = api.updateProviderRouteModelAliases.mock.calls[0];- expect(providerId).toBe('claude-ollama');- expect(body.expectedRevision).toBe('cli-aliases');- expect(body.aliases).toEqual({ 'example-model': 'namespace/example-model' });- });-- it('marks which aliases a human wrote, and offers to remove only those', async () => {- const graph = graphFixture();- graph.routes[0].modelMap = { 'example-model': 'example-model', 'hand-written': 'other-model' };- graph.routes[0].modelAliasOverrides = { 'hand-written': 'other-model' };- api.getProviderManagementGraph.mockResolvedValue(graph);- api.updateProviderRouteModelAliases.mockResolvedValue({ providerId: 'claude-ollama' });- await openRoute();-- // The observed alias has no Remove button — nothing a refresh wrote is the- // human's to delete here.- expect(screen.getAllByRole('button', { name: /Remove the manual alias/ })).toHaveLength(1);-- fireEvent.click(screen.getByRole('button', { name: 'Remove the manual alias for hand-written' }));-- await waitFor(() => expect(api.updateProviderRouteModelAliases).toHaveBeenCalled());- // `null` is the removal, and it names ONLY that key: the aliases the human- // did not touch are not restated and cannot be lost in the round trip.- expect(api.updateProviderRouteModelAliases.mock.calls[0][1].aliases).toEqual({ 'hand-written': null });- });-- it('shows an alias the route no longer lists instead of dropping it', async () => {- const graph = graphFixture();- graph.routes[0].modelMap = { 'hand-written': 'model-the-backend-dropped' };- graph.routes[0].modelAliasOverrides = { 'hand-written': 'model-the-backend-dropped' };- graph.routes[0].staleModelAliases = ['hand-written'];- api.getProviderManagementGraph.mockResolvedValue(graph);- await openRoute();-- expect(screen.getByText('model-the-backend-dropped')).toBeInTheDocument();- expect(screen.getByText(/no longer lists that spelling/)).toBeInTheDocument();- });-- it('keeps the typed pair when the save is refused, so it can be re-submitted', async () => {- api.updateProviderRouteModelAliases.mockRejectedValue(- Object.assign(new Error('The aliases moved'), { status: 409 }),- );- await openRoute();-- fireEvent.change(screen.getByLabelText('Backend model name'), { target: { value: 'example-model' } });- fireEvent.change(screen.getByLabelText('What this harness is sent'), { target: { value: 'ns/example-model' } });- fireEvent.click(screen.getByRole('button', { name: 'Add alias' }));-- await waitFor(() => expect(toast.error).toHaveBeenCalled());- expect(screen.getByLabelText('Backend model name')).toHaveValue('example-model');- });-});--describe('adding a backend and a harness (#6369)', () => {- it('sends exactly one transport and no probe, then opens what it made', async () => {- const onSelectConnection = vi.fn();- api.createProviderConnection.mockResolvedValue({ connection: { id: OTHER, label: 'Remote example' } });- renderPanel({ onSelectConnection });-- fireEvent.click(await screen.findByRole('button', { name: /add a backend/i }));- fireEvent.change(screen.getByLabelText('Backend name'), { target: { value: 'Remote example' } });- fireEvent.change(screen.getByLabelText('Base URL'), { target: { value: 'https://ollama.example.com/v1' } });- fireEvent.change(screen.getByLabelText('Backend'), { target: { value: 'api' } });- fireEvent.click(screen.getByRole('button', { name: 'Add backend' }));-- await waitFor(() => expect(api.createProviderConnection).toHaveBeenCalled());- const [body] = api.createProviderConnection.mock.calls[0];- expect(body).toMatchObject({- kind: 'api',- label: 'Remote example',- transports: { openai: { baseUrl: 'https://ollama.example.com/v1' } },- });- // No credential typed, so none is sent — an empty string would be stored as- // a real (and broken) secret.- expect(body).not.toHaveProperty('credentials');- expect(Object.keys(body.transports)).toHaveLength(1);- expect(api.refreshProviderConnectionModels).not.toHaveBeenCalled();- // The next step is adding a harness, and that control lives in the panel.- await waitFor(() => expect(onSelectConnection).toHaveBeenCalledWith(OTHER));- });-- it('offers only harnesses that speak the backend it is on', async () => {- renderPanel();- const select = await screen.findByLabelText('Program');- // The fixture backend declares the anthropic transport; OpenCode speaks- // openai and is not offered, because an option whose only outcome is a 409- // is not an option.- expect([...select.options].map((option) => option.textContent)).toEqual(['Claude Code']);- });-- it('creates a disabled binding for the checked modes only', async () => {- api.createProviderBinding.mockResolvedValue({ routeIds: ['claude-ollama-2'], enabled: false });- renderPanel();-- fireEvent.click(await screen.findByLabelText('tui'));- fireEvent.click(screen.getByRole('button', { name: /^Add$/ }));-- await waitFor(() => expect(api.createProviderBinding).toHaveBeenCalled());- expect(api.createProviderBinding.mock.calls[0][0]).toEqual({- connectionId: CONNECTION, harnessId: 'claude', modes: ['cli'],- });- expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('disabled'));- });-- it('refuses to add a harness that needs a credential the backend has not got', async () => {- api.getProviderManagementGraph.mockResolvedValue({- ...graphFixture(),- connections: graphFixture().connections.map((connection) => ({ ...connection, hasCredentials: false })),- });- renderPanel();-- expect(await screen.findByText(/ANTHROPIC_AUTH_TOKEN/)).toBeInTheDocument();- expect(screen.getByRole('button', { name: /^Add$/ })).toBeDisabled();- expect(api.createProviderBinding).not.toHaveBeenCalled();- });-});--describe('deleting a backend', () => {- it('asks before it throws the backend and its stored key away', async () => {- api.deleteProviderConnection.mockResolvedValue({ deleted: true });- renderPanel({ connectionId: OTHER });-- fireEvent.click(await screen.findByRole('button', { name: /Delete/ }));- expect(api.deleteProviderConnection).not.toHaveBeenCalled();- expect(screen.getByText(/Delete the Remote daemon backend\?/)).toBeInTheDocument();-- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));- expect(api.deleteProviderConnection).not.toHaveBeenCalled();-- fireEvent.click(screen.getByRole('button', { name: /Delete/ }));- fireEvent.click(screen.getByRole('button', { name: 'Delete backend' }));- await waitFor(() => expect(api.deleteProviderConnection).toHaveBeenCalledWith(OTHER, { silent: true }));- });-});diff --git a/client/src/components/providers/ProviderCredentialBootstraps.jsx b/client/src/components/providers/ProviderCredentialBootstraps.jsxnew file mode 100644index 0000000000..84a3f75405--- /dev/null+++ b/client/src/components/providers/ProviderCredentialBootstraps.jsx@@ -0,0 +1,285 @@+import { useEffect, useMemo, useState } from 'react';+import { KeyRound, Pencil, Plus, Trash2 } from 'lucide-react';+import toast from '../ui/Toast';+import Banner from '../ui/Banner';+import CollapsibleSection from '../ui/CollapsibleSection';+import InlineConfirmRow from '../ui/InlineConfirmRow';+import { FormField } from '../ui/FormField';+import useConfirmDelete from '../../hooks/useConfirmDelete';+import * as api from '../../services/api';+import { invalidateProviderCatalog } from '../../hooks/useProviderCatalog';+import { formatCount } from '../../utils/formatters';++/**+ * Credential-bootstrap apps (#7564 → #7567): the launch wrappers a composite+ * id's `+<slug>` suffix names — `<command> <args…> <harness-name> [<separator>]+ * <harness args>`. One table in settings, edited whole: every save is the full+ * map back to `PUT /api/providers/bootstraps`, and the compose popover shows+ * its bootstrap select on the next open because the catalog is invalidated.+ *+ * Collapsed and empty-state-only until one exists: most installs never need a+ * wrapper, and a wall of fields for a feature nobody asked for is noise under+ * the harness cards.+ */++const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;+const INPUT_CLASS = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden';++const EMPTY_DRAFT = Object.freeze({+ slug: '', label: '', command: '', args: '', argsSeparator: '', setupCommand: '', harnessNames: {},+});++/** A stored app as the form edits it: argv as one space-separated line. */+const draftFromApp = (slug, app) => ({+ slug,+ label: app.label || '',+ command: app.command || '',+ args: Array.isArray(app.args) ? app.args.join(' ') : '',+ argsSeparator: app.argsSeparator || '',+ setupCommand: app.setupCommand || '',+ harnessNames: { ...(app.harnessNames || {}) },+});++/** The form back to the wire shape. Blank optional fields are omitted, not sent empty. */+function appFromDraft(draft) {+ const args = draft.args.split(/\s+/).map((part) => part.trim()).filter(Boolean);+ const harnessNames = Object.fromEntries(Object.entries(draft.harnessNames)+ .map(([id, name]) => [id, String(name || '').trim()])+ .filter(([, name]) => name.length > 0));+ return {+ label: draft.label.trim(),+ command: draft.command.trim(),+ ...(args.length > 0 ? { args } : {}),+ ...(draft.argsSeparator.trim() ? { argsSeparator: draft.argsSeparator.trim() } : {}),+ ...(draft.setupCommand.trim() ? { setupCommand: draft.setupCommand.trim() } : {}),+ ...(Object.keys(harnessNames).length > 0 ? { harnessNames } : {}),+ };+}++function BootstrapForm({ draft, editing, harnesses, busy, onChange, onSubmit, onCancel }) {+ const set = (key) => (e) => onChange({ ...draft, [key]: e.target.value });+ const setHarnessName = (id) => (e) => onChange({ ...draft, harnessNames: { ...draft.harnessNames, [id]: e.target.value } });+ return (+ <form+ onSubmit={(e) => { e.preventDefault(); onSubmit(); }}+ className="bg-port-bg/60 border border-port-border rounded-lg p-3 space-y-3"+ aria-label={editing ? `Edit bootstrap ${draft.slug}` : 'Add bootstrap'}+ >+ <div className="grid gap-3 grid-cols-[repeat(auto-fit,minmax(min(100%,14rem),1fr))]">+ <FormField label="Slug *" hint="Lowercase letters, digits, dashes — the `+<slug>` a composite id carries" compact>+ <input id="bootstrap-slug" type="text" value={draft.slug} onChange={set('slug')} disabled={editing} required pattern="[a-z0-9][a-z0-9-]*" className={INPUT_CLASS} placeholder="corp-auth" />+ </FormField>+ <FormField label="Label *" compact>+ <input id="bootstrap-label" type="text" value={draft.label} onChange={set('label')} required className={INPUT_CLASS} placeholder="Corp auth wrapper" />+ </FormField>+ <FormField label="Command *" hint="The wrapper binary" compact>+ <input id="bootstrap-command" type="text" value={draft.command} onChange={set('command')} required className={INPUT_CLASS} placeholder="corp-auth" />+ </FormField>+ <FormField label="Arguments" hint="Space-separated, before the harness name" compact>+ <input id="bootstrap-args" type="text" value={draft.args} onChange={set('args')} className={INPUT_CLASS} placeholder="run" />+ </FormField>+ <FormField label="Args separator" hint="Inserted between the harness name and its own args, e.g. --" compact>+ <input id="bootstrap-separator" type="text" value={draft.argsSeparator} onChange={set('argsSeparator')} className={INPUT_CLASS} placeholder="--" />+ </FormField>+ <FormField label="Setup command" hint="Advisory text shown to you — PortOS never runs it" compact>+ <input id="bootstrap-setup" type="text" value={draft.setupCommand} onChange={set('setupCommand')} className={INPUT_CLASS} placeholder="corp-auth login" />+ </FormField>+ </div>+ <fieldset>+ <legend className="text-xs text-gray-400 mb-1">Harness names the wrapper knows (only where they differ from the binary)</legend>+ <div className="grid gap-2 grid-cols-[repeat(auto-fit,minmax(min(100%,12rem),1fr))]">+ {harnesses.filter((harness) => harness.id !== 'direct').map((harness) => (+ <label key={harness.id} htmlFor={`bootstrap-harness-${harness.id}`} className="text-xs text-gray-400">+ <span className="block mb-0.5">{harness.label}</span>+ <input+ id={`bootstrap-harness-${harness.id}`}+ type="text"+ value={draft.harnessNames[harness.id] || ''}+ onChange={setHarnessName(harness.id)}+ className={INPUT_CLASS}+ placeholder={harness.id === 'claude' ? 'claude-code' : harness.id}+ />+ </label>+ ))}+ </div>+ </fieldset>+ <p className="text-xs text-gray-500 font-mono">+ {draft.command || '<command>'} {draft.args} {'<harness>'} {draft.argsSeparator} {'<harness args>'}+ </p>+ <div className="flex flex-wrap gap-2">+ <button type="submit" disabled={busy} className="px-3 py-1.5 text-sm rounded-lg bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50">+ {busy ? 'Saving…' : editing ? 'Save bootstrap' : 'Add bootstrap'}+ </button>+ <button type="button" onClick={onCancel} className="px-3 py-1.5 text-sm rounded-lg border border-port-border text-gray-300 hover:text-white">+ Cancel+ </button>+ </div>+ </form>+ );+}++/**+ * @param {object} props+ * @param {object[]} props.harnesses - catalog harness rows, for the per-harness name map.+ * @param {object[]} props.presets - catalog presets, for the "used by" count.+ */+export default function ProviderCredentialBootstraps({ harnesses = [], presets = [] }) {+ // `null` = not fetched yet (or the fetch failed): render the empty hint, never+ // an "add" that would overwrite a table we could not read.+ const [apps, setApps] = useState(null);+ const [draft, setDraft] = useState(null); // null = form closed; { ...EMPTY_DRAFT, editing }+ const [busy, setBusy] = useState(false);+ // Controlled rather than `defaultOpen`: the table arrives after mount, and an+ // uncontrolled section would have already decided to stay collapsed.+ const [open, setOpen] = useState(false);+ const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();++ useEffect(() => {+ let active = true;+ api.getProviderBootstraps({ silent: true })+ .then((data) => {+ if (!active) return;+ const table = data?.bootstraps && typeof data.bootstraps === 'object' ? data.bootstraps : {};+ setApps(table);+ setOpen(Object.keys(table).length > 0);+ })+ .catch(() => { if (active) setApps(null); });+ return () => { active = false; };+ }, []);++ const usedBy = useMemo(() => {+ const counts = {};+ for (const preset of presets) {+ if (preset.credentialBootstrapId) counts[preset.credentialBootstrapId] = (counts[preset.credentialBootstrapId] || 0) + 1;+ }+ return counts;+ }, [presets]);++ const entries = Object.entries(apps || {});++ const save = async (next, successMessage) => {+ setBusy(true);+ const result = await api.saveProviderBootstraps(next, { silent: true }).catch((err) => ({ error: err?.message }));+ setBusy(false);+ if (!result || result.error || !result.bootstraps) {+ toast.error(result?.error || 'Could not save the credential bootstraps');+ return false;+ }+ setApps(result.bootstraps);+ invalidateProviderCatalog();+ toast.success(successMessage);+ return true;+ };++ const submit = async () => {+ if (!draft) return;+ const slug = draft.slug.trim();+ if (!SLUG_RE.test(slug)) {+ toast.error('A bootstrap slug is lowercase letters, digits and dashes, starting with a letter or digit');+ return;+ }+ if (!draft.editing && apps && Object.hasOwn(apps, slug)) {+ toast.error(`A bootstrap is already addressed as "${slug}"`);+ return;+ }+ const ok = await save({ ...(apps || {}), [slug]: appFromDraft(draft) }, `Bootstrap "${slug}" saved — compose shows it on the next open`);+ if (ok) setDraft(null);+ };++ const remove = async (slug) => {+ const { [slug]: _removed, ...rest } = apps || {};+ await save(rest, `Bootstrap "${slug}" removed`);+ };++ return (+ <CollapsibleSection+ id="credential-bootstraps"+ icon={KeyRound}+ label="Credential bootstraps"+ summary={entries.length === 0 ? 'None configured' : `${formatCount(entries.length)} configured`}+ open={open}+ onOpenChange={setOpen}+ size="md"+ className="bg-port-card border border-port-border rounded-xl px-4 py-2"+ bodyClassName="space-y-3 pb-2"+ >+ <p className="text-xs text-gray-400">+ A launch wrapper that mints a harness's credential at spawn. Any CLI/TUI combination can run through one+ by adding <code className="font-mono">+<slug></code> to its composite id, or by picking it in the compose flow.+ </p>+ {apps === null && <Banner tone="warning" size="sm">Could not read the configured bootstraps.</Banner>}+ {entries.length > 0 && (+ <ul className="space-y-2">+ {entries.map(([slug, app]) => (+ <li key={slug} className="bg-port-bg/60 border border-port-border rounded-lg p-3 space-y-2">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <div className="min-w-0">+ <span className="text-sm font-medium text-white">{app.label}</span>+ <code className="ml-2 text-xs font-mono text-gray-500">+{slug}</code>+ <p className="text-xs text-gray-400 font-mono break-all">+ {app.command} {(app.args || []).join(' ')} {'<harness>'} {app.argsSeparator || ''}+ </p>+ {app.setupCommand && <p className="text-xs text-gray-500">Setup: <code className="font-mono">{app.setupCommand}</code></p>}+ <p className="text-xs text-gray-500">+ Used by {formatCount(usedBy[slug] || 0, { fallback: '0' })} preset{(usedBy[slug] || 0) === 1 ? '' : 's'}+ {app.harnessNames && Object.keys(app.harnessNames).length > 0+ ? ` · names: ${Object.entries(app.harnessNames).map(([id, name]) => `${id}→${name}`).join(', ')}`+ : ''}+ </p>+ </div>+ <div className="flex gap-2 shrink-0">+ <button+ type="button"+ onClick={() => setDraft({ ...draftFromApp(slug, app), editing: true })}+ className="inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded border border-port-border text-gray-300 hover:text-white"+ >+ <Pencil className="w-3 h-3" aria-hidden="true" /> Edit+ </button>+ {!isConfirming(slug) && (+ <button+ type="button"+ onClick={() => requestDelete(slug)}+ className="inline-flex items-center gap-1 px-2.5 py-1 text-xs rounded border border-port-error/50 text-port-error hover:bg-port-error/10"+ >+ <Trash2 className="w-3 h-3" aria-hidden="true" /> Remove+ </button>+ )}+ </div>+ </div>+ {isConfirming(slug) && (+ <InlineConfirmRow+ question={`Remove the "${app.label}" bootstrap? Presets that name +${slug} will refuse to run until it is re-added.`}+ confirmText="Remove bootstrap"+ autoFocus+ aria-label={`Confirm removing the ${app.label} bootstrap`}+ onConfirm={() => confirmDelete(() => remove(slug))}+ onCancel={cancelDelete}+ />+ )}+ </li>+ ))}+ </ul>+ )}+ {draft ? (+ <BootstrapForm+ draft={draft}+ editing={Boolean(draft.editing)}+ harnesses={harnesses}+ busy={busy}+ onChange={setDraft}+ onSubmit={submit}+ onCancel={() => setDraft(null)}+ />+ ) : (+ <button+ type="button"+ disabled={apps === null}+ onClick={() => setDraft({ ...EMPTY_DRAFT, editing: false })}+ className="inline-flex items-center gap-1 px-3 py-1.5 text-sm rounded-lg border border-port-border text-gray-300 hover:text-white disabled:opacity-50"+ >+ <Plus className="w-4 h-4" aria-hidden="true" /> Add bootstrap+ </button>+ )}+ </CollapsibleSection>+ );+}diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsxindex ac4a3c2cb7..abc3abbe8a 100644--- a/client/src/components/providers/ProviderForm.jsx+++ b/client/src/components/providers/ProviderForm.jsx@@ -1,5 +1,6 @@import { hardwareUnavailableReason } from '../../utils/systemCapabilities';import { useMemo, useState } from 'react';+import { Link } from 'react-router';import { AlertTriangle, Braces, Cpu, Link2, Plug, SlidersHorizontal } from 'lucide-react';import toast from '../ui/Toast';import * as api from '../../services/api';@@ -527,8 +528,11 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose{isDerived && (<Banner tone="info" icon={Link2}><p>- Derived from service <code className="font-mono">{provider.serviceId}</code> via{' '}- <code className="font-mono">{provider.harnessId}</code> ({provider.method}). The command, endpoint,+ Derived from service{' '}+ <Link to={`/ai/services/${encodeURIComponent(provider.serviceId)}`} className="font-mono text-port-accent hover:underline">+ {provider.serviceId}+ </Link>{' '}+ via <code className="font-mono">{provider.harnessId}</code> ({provider.method}). The command, endpoint,credential, backend environment and model catalog come from that service and are refreshed on everysave — edit them on the service, not here. Name, arguments, timeouts, model pins, effort andgeneration settings are this preset's own.@@ -561,6 +565,13 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose/></FormField>+ {/* Connection-owned fields (type, command, endpoint, key, inline+ bootstrap) are the SERVICE's on a derived preset (#7565): the+ server re-materializes them on every save and refuses an edit+ that would move one, so the form shows none of them (#7567).+ The values stay in `formData` untouched, which is what keeps+ the per-tab validation satisfied. */}+ {!isDerived && (<FormField label="Type *"><selectvalue={formData.type}@@ -572,9 +583,11 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose<option value="api">API</option></select></FormField>+ )}{(formData.type === 'cli' || formData.type === 'tui') && (<>+ {!isDerived && (<FormField label="Command *"><inputtype="text"@@ -601,6 +614,7 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose</Banner>)}</FormField>+ )}<FormField label="Arguments (space-separated)"><input@@ -658,6 +672,8 @@ export default function ProviderForm({ provider, daemonReadiness = null, onCloseinvocation above, exactly as typing `<bootstrap> run <harness>...` would. Setup Command is shown for the user to runthemselves; PortOS never executes it. */}+ {!isDerived && (+ <><p className="text-sm text-gray-400 -mb-1">Credential Bootstrap (optional)</p><FormField label="Setup Command" compact><input@@ -727,6 +743,8 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClosere-parents the harness out of that group, or traps signals without passing them on, can leaveit running after PortOS has finished the run.</p>+ </>+ )}{/* The CLI/TUI backends that can authenticate: the vLLM composestack is started with VLLM_API_KEY, so without this field@@ -737,7 +755,7 @@ export default function ProviderForm({ provider, daemonReadiness = null, onCloseset when the operator ran `--api-key`), so the two cannotshare one placeholder without telling half the operators topaste a secret that does not exist. */}- {capabilityProvider?.vllmBacked && (+ {!isDerived && capabilityProvider?.vllmBacked && (<FormField label="API Key"><inputtype="password"@@ -753,7 +771,7 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose</FormField>)}- {capabilityProvider?.sglangBacked && (+ {!isDerived && capabilityProvider?.sglangBacked && (<FormField label="API Key (optional)"><inputtype="password"@@ -811,6 +829,8 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose{formData.type === 'api' && (<>+ {!isDerived && (+ <><FormField label="Endpoint *"><inputtype="url"@@ -841,6 +861,8 @@ export default function ProviderForm({ provider, daemonReadiness = null, onCloseone; local backends (Ollama, LM Studio) don't.</p></FormField>+ </>+ )}<FormField label="Custom endpoint"><label htmlFor="allowCustomEndpoint" className="flex items-start gap-2 cursor-pointer">diff --git a/client/src/components/providers/ProviderForm.test.jsx b/client/src/components/providers/ProviderForm.test.jsxindex 2ab66a3bd9..a40a5f1247 100644--- a/client/src/components/providers/ProviderForm.test.jsx+++ b/client/src/components/providers/ProviderForm.test.jsx@@ -341,10 +341,29 @@ describe('ProviderForm model access', () => {describe('preset structure', () => {const legacy = { id: 'claude-local', name: 'Claude', type: 'cli', command: 'claude', presetKind: 'legacy', presetDerivable: true };- it('explains a derived preset and offers no conversion', () => {+ it('explains a derived preset, links its service, hides the connection-owned fields and offers no conversion', () => {renderForm({ provider: { ...legacy, presetKind: 'derived', presetDerivable: false, harnessId: 'claude', method: 'cli', serviceId: 'ollama' } });expect(screen.getByText(/Derived from service/)).toBeInTheDocument();+ expect(screen.getByRole('link', { name: 'ollama' })).toHaveAttribute('href', '/ai/services/ollama');expect(screen.queryByRole('button', { name: /Convert to derived preset/ })).not.toBeInTheDocument();+ // The service owns type, command and the inline bootstrap (#7567); the+ // preset keeps its name and arguments.+ expect(screen.queryByLabelText('Type *')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('Command *')).not.toBeInTheDocument();+ expect(screen.queryByText('Credential Bootstrap (optional)')).not.toBeInTheDocument();+ expect(screen.getByLabelText('Name *')).toHaveValue('Claude');+ expect(screen.getByLabelText('Arguments (space-separated)')).toBeInTheDocument();+ });++ it('hides the endpoint and key of a derived API preset, keeping them on a legacy one', () => {+ const apiRecord = { id: 'nvidia', name: 'NVIDIA', type: 'api', endpoint: 'https://integrate.api.nvidia.com/v1', presetKind: 'legacy', presetDerivable: false };+ const { unmount } = renderForm({ provider: apiRecord });+ expect(screen.getByLabelText('Endpoint *')).toHaveValue('https://integrate.api.nvidia.com/v1');+ expect(screen.getByLabelText('API Key')).toBeInTheDocument();+ unmount();+ renderForm({ provider: { ...apiRecord, presetKind: 'derived', harnessId: 'direct', method: 'api', serviceId: 'nvidia-nim' } });+ expect(screen.queryByLabelText('Endpoint *')).not.toBeInTheDocument();+ expect(screen.queryByLabelText('API Key')).not.toBeInTheDocument();});it('converts a derivable legacy preset through the API and hands back to the page', async () => {diff --git a/client/src/components/providers/ProviderHarnessForm.jsx b/client/src/components/providers/ProviderHarnessForm.jsxdeleted file mode 100644index ea50ad35ce..0000000000--- a/client/src/components/providers/ProviderHarnessForm.jsx+++ /dev/null@@ -1,99 +0,0 @@-import { Plus } from 'lucide-react';-import { connectionProtocol, harnessOptionsFor } from '../../lib/providerManagement';--/**- * Add a harness to a backend (#6369) — mock flow 2: the same daemon, driven by- * a second program, as an independent binding with its own executable routes.- *- * Two rules the control is built around:- *- * - **Only harnesses that speak this backend are offered.** The server- * refuses one that does not, and an option whose only outcome is a 409 is- * not an option. A program that needs a credential the backend has not got- * is shown and disabled WITH the reason, rather than hidden.- * - **Nothing created here is enabled.** New routes arrive disabled with no- * model pins; granting execution stays an explicit edit on the route- * editor. The copy says so, because the button does not.- */-export default function ProviderHarnessForm({ graph, connection, draft, onChange, onSubmit, busy }) {- const options = harnessOptionsFor(graph, connection);- if (options.length === 0) {- return (- <p className="text-xs text-port-muted">- No harness PortOS can point at a {connectionProtocol(connection) || 'transport-less'} backend.- </p>- );- }-- const current = draft || { harnessId: options[0].harnessId, modes: options[0].modes };- const chosen = options.find((option) => option.harnessId === current.harnessId) || options[0];-- return (- <div className="rounded border border-dashed border-port-border p-3">- <h4 className="mb-2 text-sm font-medium">Add a harness</h4>- <div className="flex flex-wrap items-end gap-3">- <label className="block text-sm" htmlFor={`add-harness-${connection.id}`}>- <span className="mb-1 block text-port-muted">Program</span>- <select- id={`add-harness-${connection.id}`}- className="rounded border border-port-border bg-port-bg px-2 py-1"- value={chosen.harnessId ?? ''}- disabled={busy}- onChange={(event) => {- const next = options.find((option) => (option.harnessId ?? '') === event.target.value);- onChange({ harnessId: next?.harnessId ?? null, modes: next?.modes ?? [] });- }}- >- {options.map((option) => (- <option key={option.harnessId ?? 'api'} value={option.harnessId ?? ''}>{option.label}</option>- ))}- </select>- </label>-- <fieldset>- <legend className="mb-1 text-xs text-port-muted">Modes</legend>- <div className="flex flex-wrap gap-2">- {chosen.modes.map((mode) => (- <label key={mode} className="flex items-center gap-1 text-sm" htmlFor={`add-mode-${connection.id}-${mode}`}>- <input- id={`add-mode-${connection.id}-${mode}`}- type="checkbox"- checked={current.modes.includes(mode)}- disabled={busy}- onChange={(event) => onChange({- harnessId: chosen.harnessId,- // Kept in the harness's own mode order, so a route set always- // reads cli-then-tui however it was clicked.- modes: chosen.modes.filter((entry) => (entry === mode- ? event.target.checked- : current.modes.includes(entry))),- })}- />- {mode}- </label>- ))}- </div>- </fieldset>-- <button- type="button"- disabled={busy || current.modes.length === 0 || Boolean(chosen.needsCredential)}- onClick={() => onSubmit({ harnessId: chosen.harnessId, modes: current.modes })}- className="flex items-center gap-1 rounded bg-port-accent px-3 py-1 text-sm text-white disabled:opacity-50"- >- <Plus size={14} aria-hidden="true" /> Add- </button>- </div>-- {chosen.needsCredential && (- <p className="mt-2 text-xs text-port-warning">- {chosen.label} will not start without a <code>{chosen.needsCredential}</code>.- Set one on this backend above first.- </p>- )}- <p className="mt-2 text-xs text-port-muted">- New routes arrive disabled with no model pins. Enable one on its route editor when you want it to run.- </p>- </div>- );-}diff --git a/client/src/components/providers/ProviderHarnessesTab.jsx b/client/src/components/providers/ProviderHarnessesTab.jsxnew file mode 100644index 0000000000..b6f920d1ba--- /dev/null+++ b/client/src/components/providers/ProviderHarnessesTab.jsx@@ -0,0 +1,226 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import { Link, useNavigate } from 'react-router';+import { CheckCircle2, Download, ExternalLink, Gauge, PowerOff, TerminalSquare } from 'lucide-react';+import toast from '../ui/Toast';+import Pill from '../ui/Pill';+import Banner from '../ui/Banner';+import * as api from '../../services/api';+import useProviderCatalog, { invalidateProviderCatalog } from '../../hooks/useProviderCatalog';+import { formatCount } from '../../utils/formatters';+import ProviderCredentialBootstraps from './ProviderCredentialBootstraps';++/**+ * AI Providers → Harnesses (#7567, epic #7561): one card per registry harness+ * — the program that drives a model — with the switch that decides whether+ * compose offers it, what the machine knows about its binary, the methods it+ * runs, and how many switched-on services it can be pointed at. `direct`+ * (PortOS's own HTTP runner) is always on and says so.+ *+ * Read from the shared composition catalog (`useProviderCatalog`), so a toggle+ * here is one write plus one cache invalidation, and every open picker's+ * compose flow reflects it without a reload. Install/update/remove of the+ * binary itself stays on Models → Harnesses; this card offers the install a+ * missing binary needs and links there for the rest.+ */++/** How the enablement verdict reads under the switch. */+const SOURCE_COPY = {+ always: 'Always on — PortOS runs this itself',+ setting: 'Set by you',+ detected: 'Following the binary: on while it is installed',+ default: 'On by default until the binary is probed',+};++const METHOD_LABEL = { cli: 'CLI', tui: 'TUI', api: 'API' };++/** Every harness whose vendor bills a subscription quota the Quota Burn page tracks. */+const QUOTA_TRACKED = new Set(['claude', 'codex', 'grok', 'antigravity']);++/** How a ChatGPT / Codex sign-in state reads on the harness card. */+const CODEX_STATUS_COPY = {+ ready: 'ChatGPT subscription signed in',+ 'signed-out': 'ChatGPT subscription signed out',+ 'login-pending': 'ChatGPT sign-in in progress',+ 'quota-exhausted': 'ChatGPT usage limit reached',+ 'runtime-missing': 'Codex CLI not installed',+};++function HarnessCard({+ harness, runtime, compatibleCount, presetCount, selected, busy,+ codexAccount, onToggle, onInstallRuntime,+}) {+ const ref = useRef(null);+ useEffect(() => {+ if (selected) ref.current?.scrollIntoView?.({ block: 'nearest' });+ }, [selected]);+ const isDirect = harness.id === 'direct';+ const switchId = `harness-enabled-${harness.id}`;+ const codexStatus = harness.id === 'codex' && codexAccount ? codexAccount.status : null;++ return (+ <article+ ref={ref}+ aria-labelledby={`harness-${harness.id}-title`}+ className={`bg-port-card border rounded-xl p-4 space-y-3 ${selected ? 'border-port-accent ring-1 ring-port-accent/40' : 'border-port-border'}`}+ >+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div className="min-w-0">+ <h3 id={`harness-${harness.id}-title`} className="text-base font-semibold text-white flex items-center gap-2">+ <TerminalSquare className="w-4 h-4 text-port-accent shrink-0" aria-hidden="true" />+ <Link to={`/ai/harnesses/${encodeURIComponent(harness.id)}`} className="hover:underline">{harness.label}</Link>+ <code className="text-xs font-mono text-gray-500">{harness.id}</code>+ </h3>+ <p className="mt-1 text-xs text-gray-500">{SOURCE_COPY[harness.source] || ''}</p>+ </div>+ {isDirect ? (+ <Pill tone="success" size="xs" icon={CheckCircle2}>Always on</Pill>+ ) : (+ <label htmlFor={switchId} className="flex items-center gap-2 text-sm text-gray-300 cursor-pointer">+ <input+ id={switchId}+ type="checkbox"+ role="switch"+ aria-checked={harness.enabled}+ checked={harness.enabled}+ disabled={busy}+ onChange={(e) => onToggle(harness, e.target.checked)}+ className="h-4 w-4 accent-port-accent"+ />+ {harness.enabled ? 'Enabled' : 'Disabled'}+ </label>+ )}+ </div>++ <div className="flex flex-wrap items-center gap-2 text-xs">+ {harness.modes.map((mode) => (+ <Pill key={mode} tone="muted" size="xs" mono>{METHOD_LABEL[mode] || mode}</Pill>+ ))}+ <span className="text-gray-400">+ {formatCount(compatibleCount, { fallback: '0' })} compatible service{compatibleCount === 1 ? '' : 's'}+ </span>+ <span className="text-gray-500">·</span>+ <span className="text-gray-400">+ {formatCount(presetCount, { fallback: '0' })} preset{presetCount === 1 ? '' : 's'}+ </span>+ </div>++ {!isDirect && (+ <div className="flex flex-wrap items-center gap-2 text-xs">+ {harness.detected === true && (+ <Pill tone="success" size="xs" icon={CheckCircle2}>+ Installed{harness.version ? ` · ${harness.version}` : ''}+ </Pill>+ )}+ {harness.detected === false && <Pill tone="warning" size="xs" icon={PowerOff}>Binary not found</Pill>}+ {harness.detected === null && <Pill tone="muted" size="xs">Binary not probed yet</Pill>}+ {harness.detected === false && runtime?.installable && (+ <button+ type="button"+ onClick={() => onInstallRuntime(runtime)}+ className="inline-flex items-center gap-1 px-2.5 py-1 rounded bg-port-accent/20 text-port-accent hover:bg-port-accent/30 transition-colors"+ >+ <Download className="w-3.5 h-3.5" aria-hidden="true" /> Install {runtime.label}+ </button>+ )}+ {harness.detected === false && runtime && !runtime.installable && runtime.blockedReason && (+ <span className="text-gray-500">{runtime.blockedReason}</span>+ )}+ <Link to="/models/harnesses" className="text-port-accent hover:underline inline-flex items-center gap-1">+ Versions & updates <ExternalLink className="w-3 h-3" aria-hidden="true" />+ </Link>+ {QUOTA_TRACKED.has(harness.id) && (+ <Link to="/devtools/quota-burn" className="text-port-accent hover:underline inline-flex items-center gap-1">+ <Gauge className="w-3 h-3" aria-hidden="true" /> Quota+ </Link>+ )}+ </div>+ )}++ {codexStatus && (+ <p className="text-xs text-gray-400">+ {CODEX_STATUS_COPY[codexStatus] || `ChatGPT subscription: ${codexStatus}`}+ {codexAccount.planType ? ` (${codexAccount.planType})` : ''}+ {' — '}+ <Link to="/ai/presets" className="text-port-accent hover:underline">sign in from the Codex preset card</Link>+ </p>+ )}+ </article>+ );+}++/**+ * @param {object} props+ * @param {string|null} props.selectedHarnessId - from `/ai/harnesses/:harnessId`; highlighted and scrolled to.+ * @param {object} props.runtimes - the `GET /providers/runtimes` map (by binary id).+ * @param {function} props.onInstallRuntime - opens the page's install modal for one runtime row.+ * @param {object} [props.codexAccount] - the ChatGPT account readiness the page already polls.+ */+export default function ProviderHarnessesTab({ selectedHarnessId = null, runtimes = {}, onInstallRuntime, codexAccount }) {+ const navigate = useNavigate();+ const catalog = useProviderCatalog(true);+ const [pending, setPending] = useState({});++ // A runtime row is keyed by binary; the harness names it by vendor.+ const runtimeByHarness = useMemo(() => Object.fromEntries(+ Object.values(runtimes).filter((row) => row?.vendor).map((row) => [row.vendor, row]),+ ), [runtimes]);++ const presetCountByHarness = useMemo(() => {+ const counts = {};+ for (const preset of catalog.presets || []) {+ const id = preset.harnessId || (preset.type === 'api' ? 'direct' : null);+ if (id) counts[id] = (counts[id] || 0) + 1;+ }+ return counts;+ }, [catalog.presets]);++ const known = catalog.harnesses.some((harness) => harness.id === selectedHarnessId);+ useEffect(() => {+ if (catalog.loading || !selectedHarnessId || known) return;+ toast.error(`No harness with id "${selectedHarnessId}"`);+ navigate('/ai/harnesses', { replace: true });+ }, [catalog.loading, selectedHarnessId, known, navigate]);++ const handleToggle = async (harness, enabled) => {+ setPending((prev) => ({ ...prev, [harness.id]: true }));+ const result = await api.setProviderHarnessEnabled(harness.id, enabled, { silent: true }).catch(() => null);+ setPending((prev) => ({ ...prev, [harness.id]: false }));+ if (!result) {+ toast.error(`Could not ${enabled ? 'enable' : 'disable'} ${harness.label}`);+ return;+ }+ // The verdict is server-computed; every mounted picker re-reads it.+ invalidateProviderCatalog();+ toast.success(`${harness.label} ${enabled ? 'enabled' : 'disabled'} — compose offers it ${enabled ? 'now' : 'no longer'}`);+ };++ if (catalog.loading && catalog.harnesses.length === 0) {+ return <p className="text-sm text-gray-400">Loading harnesses…</p>;+ }++ return (+ <div className="space-y-6">+ <Banner tone="info" size="sm">+ A harness is the program that drives a model. Switch one off and no picker composes a run on it;+ presets that already name it stay stored but stop being offered.+ </Banner>+ <div className="grid gap-4 grid-cols-[repeat(auto-fill,minmax(min(100%,20rem),1fr))]">+ {catalog.harnesses.map((harness) => (+ <HarnessCard+ key={harness.id}+ harness={harness}+ runtime={runtimeByHarness[harness.id] || null}+ compatibleCount={catalog.compatiblePairs(harness.id).length}+ presetCount={presetCountByHarness[harness.id] || 0}+ selected={harness.id === selectedHarnessId}+ busy={Boolean(pending[harness.id])}+ codexAccount={codexAccount}+ onToggle={handleToggle}+ onInstallRuntime={onInstallRuntime}+ />+ ))}+ </div>+ <ProviderCredentialBootstraps harnesses={catalog.harnesses} presets={catalog.presets} />+ </div>+ );+}diff --git a/client/src/components/providers/ProviderHarnessesTab.test.jsx b/client/src/components/providers/ProviderHarnessesTab.test.jsxnew file mode 100644index 0000000000..a8b491f1a7--- /dev/null+++ b/client/src/components/providers/ProviderHarnessesTab.test.jsx@@ -0,0 +1,192 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { MemoryRouter, Route, Routes, useLocation } from 'react-router';+import { __resetProviderCatalogCache } from '../../hooks/useProviderCatalog';++/**+ * AI Providers → Harnesses (#7567). What only this boundary pins: a toggle is+ * one write to the enablement endpoint AND a catalog re-read (so every open+ * picker's compose flow follows), the direct harness offers no switch, a+ * missing binary offers the install its runtime row allows, and the bootstrap+ * table is saved whole with the new app folded in.+ */++const api = vi.hoisted(() => ({+ getProviderCatalog: vi.fn(),+ createProviderPreset: vi.fn(),+ setProviderHarnessEnabled: vi.fn(),+ getProviderBootstraps: vi.fn(),+ saveProviderBootstraps: vi.fn(),+}));+vi.mock('../../services/api', () => api);++const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }));+vi.mock('../ui/Toast', () => ({ default: toast }));++import ProviderHarnessesTab from './ProviderHarnessesTab';++const CATALOG = {+ harnesses: [+ { id: 'claude', label: 'Claude Code', modes: ['cli', 'tui'], enabled: true, source: 'detected', detected: true, version: '2.1.0' },+ { id: 'pi', label: 'Pi', modes: ['cli', 'tui'], enabled: false, source: 'setting', detected: false, version: null },+ { id: 'direct', label: 'Direct API', modes: ['api'], enabled: true, source: 'always', detected: true, version: null },+ ],+ services: [+ { slug: 'nvidia-nim', label: 'NVIDIA NIM', plan: 'free', enabled: true, readiness: 'ready', catalog: { models: [] } },+ { slug: 'ollama', label: 'Ollama', plan: 'local', enabled: true, readiness: 'ready', catalog: { models: [] } },+ ],+ bootstraps: [],+ compatibility: { claude: ['ollama'], pi: ['nvidia-nim', 'ollama'], direct: ['nvidia-nim', 'ollama'] },+ effortLevels: {},+ effortLevelsByModel: {},+ presets: [+ { id: 'claude-code', name: 'Claude Code', harnessId: 'claude', credentialBootstrapId: 'corp-auth' },+ { id: 'nvidia', name: 'NVIDIA', type: 'api' },+ ],+};++const RUNTIMES = {+ pi: { id: 'pi', label: 'Pi Coding Agent CLI', vendor: 'pi', installed: false, installable: true, blockedReason: null },+ claude: { id: 'claude', label: 'Claude Code CLI', vendor: 'claude', installed: true, installable: true, blockedReason: null },+};++const LocationProbe = () => <pre data-testid="location">{useLocation().pathname}</pre>;++// The page derives `selectedHarnessId` from the route param; here it is a+// prop, so the tab is mounted on both routes with whatever the case passes.+const renderTab = (path = '/ai/harnesses', props = {}) => {+ const tab = (+ <>+ <ProviderHarnessesTab runtimes={RUNTIMES} selectedHarnessId={props.selectedHarnessId ?? null} onInstallRuntime={props.onInstallRuntime || vi.fn()} />+ <LocationProbe />+ </>+ );+ return render(+ <MemoryRouter initialEntries={[path]}>+ <Routes>+ <Route path="/ai/harnesses" element={tab} />+ <Route path="/ai/harnesses/:harnessId" element={tab} />+ </Routes>+ </MemoryRouter>,+ );+};++beforeEach(() => {+ vi.clearAllMocks();+ __resetProviderCatalogCache();+ api.getProviderCatalog.mockResolvedValue(CATALOG);+ api.getProviderBootstraps.mockResolvedValue({ bootstraps: {} });+});++describe('ProviderHarnessesTab', () => {+ it('renders one card per harness with its methods, compatible-service count and preset count', async () => {+ renderTab();+ expect(await screen.findByRole('heading', { name: /Claude Code/ })).toBeInTheDocument();+ const claude = screen.getByRole('article', { name: /Claude Code/ });+ expect(claude).toHaveTextContent('1 compatible service');+ expect(claude).toHaveTextContent('1 preset');+ expect(claude).toHaveTextContent('Installed · 2.1.0');+ const pi = screen.getByRole('article', { name: /^Pi/ });+ expect(pi).toHaveTextContent('2 compatible services');+ expect(pi).toHaveTextContent('Binary not found');+ // Direct API presets count under the direct harness even without a harnessId stamp.+ expect(screen.getByRole('article', { name: /Direct API/ })).toHaveTextContent('1 preset');+ });++ it('offers no switch on the direct harness — it is always on', async () => {+ renderTab();+ await screen.findByRole('heading', { name: /Direct API/ });+ expect(screen.getByRole('article', { name: /Direct API/ })).toHaveTextContent('Always on');+ // Two switches: Claude Code and Pi. None for Direct API.+ expect(screen.getAllByRole('switch')).toHaveLength(2);+ });++ it('toggling a harness writes its enablement and re-reads the catalog for every picker', async () => {+ api.setProviderHarnessEnabled.mockResolvedValue({ harness: { id: 'pi', enabled: true, source: 'setting' } });+ const enabled = { ...CATALOG, harnesses: CATALOG.harnesses.map((h) => (h.id === 'pi' ? { ...h, enabled: true } : h)) };+ renderTab();+ const pi = await screen.findByRole('article', { name: /^Pi/ });+ const toggle = pi.querySelector('input[role="switch"]');+ expect(toggle.checked).toBe(false);++ api.getProviderCatalog.mockResolvedValue(enabled);+ fireEvent.click(toggle);++ await waitFor(() => expect(api.setProviderHarnessEnabled).toHaveBeenCalledWith('pi', true, { silent: true }));+ // Second catalog fetch = the invalidation reached the shared hook.+ await waitFor(() => expect(api.getProviderCatalog).toHaveBeenCalledTimes(2));+ await waitFor(() => expect(pi.querySelector('input[role="switch"]').checked).toBe(true));+ expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/Pi enabled/));+ });++ it('keeps the switch where it was when the write fails', async () => {+ api.setProviderHarnessEnabled.mockRejectedValue(new Error('boom'));+ renderTab();+ const pi = await screen.findByRole('article', { name: /^Pi/ });+ fireEvent.click(pi.querySelector('input[role="switch"]'));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/Could not enable Pi/)));+ expect(api.getProviderCatalog).toHaveBeenCalledTimes(1);+ expect(pi.querySelector('input[role="switch"]').checked).toBe(false);+ });++ it('offers the install for a missing binary whose runtime row allows it', async () => {+ const onInstallRuntime = vi.fn();+ renderTab('/ai/harnesses', { onInstallRuntime });+ fireEvent.click(await screen.findByRole('button', { name: 'Install Pi Coding Agent CLI' }));+ expect(onInstallRuntime).toHaveBeenCalledWith(RUNTIMES.pi);+ // An installed harness offers no install.+ expect(screen.queryByRole('button', { name: /Install Claude/ })).not.toBeInTheDocument();+ });++ it('bounces a deep link to an unknown harness back to the list', async () => {+ renderTab('/ai/harnesses/nope', { selectedHarnessId: 'nope' });+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('No harness with id "nope"'));+ expect(screen.getByTestId('location')).toHaveTextContent('/ai/harnesses');+ });+});++describe('credential bootstraps section', () => {+ it('stays collapsed and empty-state-only until one exists', async () => {+ renderTab();+ const header = await screen.findByRole('button', { name: /Credential bootstraps/ });+ expect(header).toHaveAttribute('aria-expanded', 'false');+ expect(header).toHaveTextContent('None configured');+ });++ it('saves the whole table with the new app folded in, then re-reads the catalog', async () => {+ api.getProviderBootstraps.mockResolvedValue({+ bootstraps: { 'corp-auth': { label: 'Corp auth', command: 'corp-auth', args: ['run'], harnessNames: { claude: 'claude-code' } } },+ });+ api.saveProviderBootstraps.mockImplementation(async (bootstraps) => ({ bootstraps }));+ renderTab();+ const header = await screen.findByRole('button', { name: /Credential bootstraps/ });+ expect(header).toHaveAttribute('aria-expanded', 'true');+ expect(screen.getByText('Corp auth').closest('li')).toHaveTextContent('Used by 1 preset');++ fireEvent.click(screen.getByRole('button', { name: 'Add bootstrap' }));+ fireEvent.change(screen.getByLabelText(/Slug/), { target: { value: 'vault' } });+ fireEvent.change(screen.getByLabelText(/Label/), { target: { value: 'Vault wrapper' } });+ fireEvent.change(screen.getByLabelText(/Command/), { target: { value: 'vault-exec' } });+ fireEvent.change(screen.getByLabelText(/Arguments/), { target: { value: 'run --' } });+ fireEvent.click(screen.getByRole('button', { name: 'Add bootstrap' }));++ await waitFor(() => expect(api.saveProviderBootstraps).toHaveBeenCalledWith({+ 'corp-auth': { label: 'Corp auth', command: 'corp-auth', args: ['run'], harnessNames: { claude: 'claude-code' } },+ vault: { label: 'Vault wrapper', command: 'vault-exec', args: ['run', '--'] },+ }, { silent: true }));+ await waitFor(() => expect(api.getProviderCatalog).toHaveBeenCalledTimes(2));+ expect(screen.getByText('Vault wrapper')).toBeInTheDocument();+ });++ it('refuses a slug the composite grammar cannot carry', async () => {+ renderTab();+ fireEvent.click(await screen.findByRole('button', { name: /Credential bootstraps/ }));+ fireEvent.click(screen.getByRole('button', { name: 'Add bootstrap' }));+ fireEvent.change(screen.getByLabelText(/Slug/), { target: { value: 'Bad Slug' } });+ fireEvent.change(screen.getByLabelText(/Label/), { target: { value: 'x' } });+ fireEvent.change(screen.getByLabelText(/Command/), { target: { value: 'x' } });+ fireEvent.submit(screen.getByRole('form', { name: 'Add bootstrap' }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/slug is lowercase/)));+ expect(api.saveProviderBootstraps).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/providers/ProviderPageTabs.jsx b/client/src/components/providers/ProviderPageTabs.jsxnew file mode 100644index 0000000000..84cf7444f5--- /dev/null+++ b/client/src/components/providers/ProviderPageTabs.jsx@@ -0,0 +1,31 @@+import RouteTabsHeader from '../ui/RouteTabsHeader';++/**+ * The AI Providers page's three views (#7567, epic #7561), each its own URL so+ * a card is linkable and reachable from ⌘K and voice:+ *+ * - **Presets** — the stored records the `{ providerId, model, effort }`+ * pickers name, grouped by harness, plus the compatibility matrix.+ * - **Harnesses** — the programs that drive a model and whether each is+ * switched on, plus the credential-bootstrap apps a composite can spawn through.+ * - **Services** — instances of a service definition: plan, credential, catalog.+ *+ * Exported so the page test can enumerate the views without a second list.+ */+export const PROVIDER_PAGE_TABS = Object.freeze([+ { id: 'presets', label: 'Presets', to: '/ai/presets' },+ { id: 'harnesses', label: 'Harnesses', to: '/ai/harnesses' },+ { id: 'services', label: 'Services', to: '/ai/services' },+]);++/** Which view a pathname under `/ai` opens. The index and every overlay off it are presets. */+export const providerPageTabForPath = (pathname) => {+ const bare = String(pathname || '').replace(/\/+$/, '');+ if (/^\/ai\/harnesses(\/|$)/.test(bare)) return 'harnesses';+ if (/^\/ai\/services(\/|$)/.test(bare)) return 'services';+ return 'presets';+};++export default function ProviderPageTabs({ activeTab }) {+ return <RouteTabsHeader tabs={PROVIDER_PAGE_TABS} activeTab={activeTab} ariaLabel="AI provider views" />;+}diff --git a/client/src/components/providers/ProviderRouteModelAliases.jsx b/client/src/components/providers/ProviderRouteModelAliases.jsxdeleted file mode 100644index 3660316bc4..0000000000--- a/client/src/components/providers/ProviderRouteModelAliases.jsx+++ /dev/null@@ -1,113 +0,0 @@-import { useState } from 'react';-import { Trash2 } from 'lucide-react';-import { routeModelAliasRows } from '../../lib/providerManagement';--/**- * Hand-authored model aliases for one route (#6369).- *- * A route's alias map answers "what does THIS harness have to be sent for a- * given canonical backend model". A refresh fills it only with the pairs it can- * verify — an OpenCode route needs `<namespace>/<model>`, so a bare string- * stored on it round-trips to nothing and never reaches the shared catalog,- * which means no harness model menu can offer it. This is where a human- * supplies the pair by hand.- *- * The merge rule the copy below states, and the server enforces:- *- * - A manual alias WINS over the one a refresh observed for the same model,- * and survives every later refresh, because the two are stored apart.- * - Removing one is an explicit act. Nothing else deletes it — an alias- * naming a spelling the route no longer lists is marked stale and kept,- * the same way a model pin outside the catalog stays visible.- *- * Presentation only: the list is whatever the server published, so a build that- * has never seen a given alias still renders it.- */-export default function ProviderRouteModelAliases({ route, busy, blocked, onSaveAliases }) {- const [canonical, setCanonical] = useState('');- const [executable, setExecutable] = useState('');-- const rows = routeModelAliasRows(route);- const id = (suffix) => `route-${route.providerId}-alias-${suffix}`;- const ready = canonical.trim() !== '' && executable.trim() !== '';-- const add = async () => {- const saved = await onSaveAliases(route, { [canonical.trim()]: executable.trim() });- // Clear only on a save that landed, so a 409 leaves the typed pair in place- // to re-submit rather than making the human retype it.- if (saved) {- setCanonical('');- setExecutable('');- }- };-- return (- <div className="space-y-2 border-t border-port-border pt-2">- <p className="text-xs text-port-muted">- Model aliases — what this harness is sent for each backend model. A manual alias wins over- the one a refresh found and survives the next refresh; only you remove it.- </p>-- {rows.length > 0 && (- <ul className="space-y-1 text-xs">- {rows.map((row) => (- <li key={row.canonical} className="flex flex-wrap items-center gap-2">- <span className="font-mono">{row.canonical}</span>- <span aria-hidden="true">→</span>- <span className="font-mono">{row.executable}</span>- {row.manual && <span className="rounded bg-port-bg px-1.5 py-0.5 text-port-muted">manual</span>}- {row.stale && (- <span className="text-port-warning">- this route no longer lists that spelling — kept as-is- </span>- )}- {row.manual && (- <button- type="button"- disabled={busy || blocked}- onClick={() => onSaveAliases(route, { [row.canonical]: null })}- aria-label={`Remove the manual alias for ${row.canonical}`}- className="flex items-center gap-1 text-port-muted hover:text-port-error disabled:opacity-50"- >- <Trash2 size={12} aria-hidden="true" /> Remove- </button>- )}- </li>- ))}- </ul>- )}-- <div className="grid gap-2 sm:grid-cols-2">- <label className="block text-sm" htmlFor={id('canonical')}>- <span className="mb-1 block text-xs text-port-muted">Backend model name</span>- <input- id={id('canonical')}- className="w-full rounded border border-port-border bg-port-bg px-2 py-1 font-mono text-xs"- placeholder="example-model"- value={canonical}- onChange={(e) => setCanonical(e.target.value)}- />- </label>- <label className="block text-sm" htmlFor={id('executable')}>- <span className="mb-1 block text-xs text-port-muted">What this harness is sent</span>- <input- id={id('executable')}- className="w-full rounded border border-port-border bg-port-bg px-2 py-1 font-mono text-xs"- placeholder="namespace/example-model"- value={executable}- onChange={(e) => setExecutable(e.target.value)}- />- </label>- </div>-- <button- type="button"- disabled={busy || blocked || !ready}- onClick={add}- className="rounded border border-port-border px-3 py-1 text-sm disabled:opacity-50"- >- Add alias- </button>- </div>- );-}diff --git a/client/src/components/providers/ProviderRouteRow.jsx b/client/src/components/providers/ProviderRouteRow.jsxdeleted file mode 100644index 6534196d5c..0000000000--- a/client/src/components/providers/ProviderRouteRow.jsx+++ /dev/null@@ -1,204 +0,0 @@-import { useEffect, useMemo, useRef, useState } from 'react';-import { Link } from 'react-router';-import { Star, Terminal } from 'lucide-react';-import ProviderRouteModelAliases from './ProviderRouteModelAliases';-import EffortSelect from '../cos/EffortSelect.jsx';-import { routeOverrideDraft, routeOverridePatch } from '../../lib/providerManagement';--/**- * One executable route inside the connection panel (#6369).- *- * The row a human acts on: it names the mode and the executable provider id,- * offers that id as the system default, hands a TUI off to the Shell page, and- * — behind a disclosure — edits the overrides that belong to THIS mode alone.- *- * Why the overrides live here rather than only on `/ai/edit/:providerId`: a- * backend is configured as a whole. Having typed an endpoint once on the- * connection above, retyping three sets of args in three separate editors is- * exactly the round trip the graph exists to remove.- *- * Three boundaries this row does NOT cross:- *- * - **No execution consent.** There is no enable toggle and no transport- * opt-in. Turning a route on stays an explicit act on the route editor.- * - **No connection state.** The fields are whatever the server published as- * route-owned; an endpoint or a key can never be retyped here and escape- * the projection that keeps the other harnesses on the backend in step.- * - **Nothing launches itself.** "Launch in Shell" is a link the human- * clicks, and the launch re-resolves the command AND the provider's secret- * env server-side; the command line here is display only.- *- * The disclosure is presentation state, not a selection: the connection in the- * URL still names what is open, and every route's editor is one click from a- * shared link.- */--/**- * Reading order and labels. The route's OWN key set decides what renders — a- * setting this build has no label for is still shown, under its raw key, rather- * than silently dropped from a newer server's payload.- */-const FIELD_LABELS = {- args: 'Launch arguments (one per line)',- timeout: 'Timeout (ms)',- effort: 'Reasoning effort',- defaultModel: 'Default model',- lightModel: 'Light tier model',- mediumModel: 'Medium tier model',- heavyModel: 'Heavy tier model',- ultraModel: 'Ultra tier model',-};--/** Published keys, labelled ones first and in reading order. */-const orderedFields = (settings) => {- const published = Object.keys(settings || {});- const known = Object.keys(FIELD_LABELS).filter((key) => published.includes(key));- return [...known, ...published.filter((key) => !Object.hasOwn(FIELD_LABELS, key))];-};--const INPUT_CLASS = 'w-full rounded border border-port-border bg-port-bg px-2 py-1';--export default function ProviderRouteRow({- route,- isSystemDefault,- busy,- blocked,- onMakeDefault,- onSaveSettings,- onSaveAliases,-}) {- const [open, setOpen] = useState(false);- const [draft, setDraft] = useState(() => routeOverrideDraft(route.settings));-- // Re-seed only when the SAVED values move. `settingsRevision` is a- // fingerprint of those values, so a poll that changed nothing leaves a- // half-typed override alone — and an edit made in the route editor does- // replace it, which is the honest outcome given the save would 409 anyway.- //- // The settings object is read through a ref for the same reason the panel- // reads its connection through one: it is a new identity on every reload, so- // depending on it directly would wipe the draft on a poll that changed- // nothing. The two primitives decide WHEN; the ref carries WHAT.- const settingsRef = useRef(route.settings);- settingsRef.current = route.settings;- useEffect(() => {- setDraft(routeOverrideDraft(settingsRef.current));- }, [route.providerId, route.settingsRevision]);-- const patch = useMemo(() => routeOverridePatch(route.settings, draft), [route.settings, draft]);- const dirty = Object.keys(patch).length > 0;- const fields = useMemo(() => orderedFields(route.settings), [route.settings]);-- const set = (key, value) => setDraft((prev) => ({ ...prev, [key]: value }));- const fieldId = (key) => `route-${route.providerId}-${key}`;-- return (- <li className="rounded border border-port-border p-2">- <div className="flex flex-wrap items-center gap-2 text-sm">- <span className="rounded bg-port-bg px-1.5 py-0.5 text-xs uppercase">{route.mode}</span>- <Link to={`/ai/edit/${route.providerId}`} className="text-port-accent hover:underline">- {route.providerId}- </Link>- {isSystemDefault ? (- <span className="flex items-center gap-1 text-xs text-port-success">- <Star size={12} aria-hidden="true" /> system default- </span>- ) : (- <button type="button" disabled={busy} onClick={() => onMakeDefault(route.providerId)}- className="text-xs text-port-muted hover:underline disabled:opacity-50">- Use as system default- </button>- )}- {/* TUI only, and only once the server resolved a real command line. The- link carries the provider id alone — the env it needs is secret and- is re-resolved when the PTY spawns. */}- {route.tuiCommandLine && (- <Link- to={`/shell?provider=${encodeURIComponent(route.providerId)}`}- title={`Launch TUI in Shell: ${route.tuiCommandLine}`}- className="flex items-center gap-1 rounded bg-port-accent/20 px-2 py-0.5 text-xs text-port-accent hover:bg-port-accent/30"- >- <Terminal size={12} aria-hidden="true" /> Launch in Shell- </Link>- )}- <button type="button" onClick={() => setOpen((prev) => !prev)} aria-expanded={open}- className="ml-auto text-xs text-port-muted hover:underline">- {open ? 'Hide' : `Overrides & aliases${dirty ? ' •' : ''}`}- </button>- </div>-- {open && (- <div className="mt-2 space-y-2 border-t border-port-border pt-2">- {/* A route whose mode publishes no overridable setting still has- aliases to correct, so the disclosure opens either way. */}- {fields.length > 0 && (- <>- <div className="grid gap-2 sm:grid-cols-2">- {fields.map((key) => (- <label key={key} className="block text-sm" htmlFor={fieldId(key)}>- <span className="mb-1 block text-xs text-port-muted">{FIELD_LABELS[key] || key}</span>- {key === 'args' ? (- <textarea- id={fieldId(key)}- rows={3}- className={`${INPUT_CLASS} font-mono text-xs`}- value={draft[key] ?? ''}- onChange={(e) => set(key, e.target.value)}- />- ) : key === 'effort' ? (- // The route publishes its own ladder (`effortLevels`), which- // the shared select reads off the record; a stored level the- // ladder no longer lists stays selectable and says what it- // runs as, the same way a model pin outside the catalog does.- // A harness with no ladder keeps a DISABLED control so "this- // program takes no effort flag" is visible, not read as "unset".- <EffortSelect- id={fieldId(key)}- className={INPUT_CLASS}- provider={route}- value={draft[key] ?? ''}- onChange={(value) => set(key, value)}- emptyLadderLabel="This harness takes no effort setting"- />- ) : (- <input- id={fieldId(key)}- type={key === 'timeout' ? 'number' : 'text'}- className={INPUT_CLASS}- placeholder={key === 'timeout' ? 'Provider default' : 'Unpinned'}- value={draft[key] ?? ''}- onChange={(e) => set(key, e.target.value)}- />- )}- </label>- ))}- </div>- <p className="text-xs text-port-muted">- These apply to this mode only — the other modes on this harness keep their own. Enabling- a route and clearing a timeout stay on its editor.- </p>- <div className="flex flex-wrap gap-2">- <button type="button" disabled={busy || blocked || !dirty}- onClick={() => onSaveSettings(route, patch)}- className="rounded bg-port-accent px-3 py-1 text-sm text-white disabled:opacity-50">- Save overrides- </button>- <button type="button" disabled={!dirty}- onClick={() => setDraft(routeOverrideDraft(route.settings))}- className="rounded border border-port-border px-3 py-1 text-sm disabled:opacity-50">- Revert- </button>- </div>- </>- )}- <ProviderRouteModelAliases- route={route}- busy={busy}- blocked={blocked}- onSaveAliases={onSaveAliases}- />- </div>- )}- </li>- );-}diff --git a/client/src/components/providers/ProviderServiceForm.jsx b/client/src/components/providers/ProviderServiceForm.jsxnew file mode 100644index 0000000000..b7aa8e56c1--- /dev/null+++ b/client/src/components/providers/ProviderServiceForm.jsx@@ -0,0 +1,222 @@+import { useEffect, useMemo, useState } from 'react';+import { ExternalLink } from 'lucide-react';+import toast from '../ui/Toast';+import Drawer from '../Drawer';+import Banner from '../ui/Banner';+import { FormField } from '../ui/FormField';+import * as api from '../../services/api';++/**+ * "Add service" (#7567): definition → plan → credential / endpoint, in that+ * order, each step narrowing the next. A service INSTANCE is a definition the+ * user declared a plan for and gave a credential or an endpoint; nothing is+ * probed on create, and the catalog starts `unknown` until the card's explicit+ * Refresh — the same contract as `POST /api/providers/services`.+ *+ * Family decides which step applies:+ * - `subscription` — auth lives in the harness; neither a key nor an endpoint.+ * - `api-key` — a key (stored here, read from the environment, or minted by+ * a bootstrap wrapper at spawn) plus the transport's default endpoint,+ * overridable for a self-hosted gateway.+ * - `local` / `fleet` — an endpoint, required, because a daemon's port is+ * decided per install and the definition declares none.+ */++const FAMILY_ORDER = ['api-key', 'local', 'subscription', 'fleet'];+const FAMILY_LABEL = {+ 'api-key': 'Hosted APIs (key)',+ local: 'Local runtimes',+ subscription: 'Subscriptions (sign in through the harness)',+ fleet: 'Fleet hosts',+};+const PLAN_LABEL = { free: 'Free tier', paid: 'Paid / metered', subscription: 'Subscription', local: 'Local (no billing)' };+const INPUT_CLASS = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden';++const EMPTY_DRAFT = Object.freeze({ definitionId: '', plan: '', label: '', slug: '', transports: {}, apiKey: '', credentialVia: 'stored' });++/** The transports a definition declares, as text the form edits, pre-filled from its defaults. */+const transportsDraftFor = (definition) => Object.fromEntries(+ Object.entries(definition?.transports || {}).map(([protocol, transport]) => [protocol, transport.defaultBaseUrl || '']),+);++export default function ProviderServiceForm({ onClose, onCreated }) {+ const [definitions, setDefinitions] = useState(null); // null = not fetched yet+ const [draft, setDraft] = useState(EMPTY_DRAFT);+ const [busy, setBusy] = useState(false);++ useEffect(() => {+ let active = true;+ api.getProviderServiceDefinitions({ silent: true })+ .then((data) => { if (active) setDefinitions(Array.isArray(data?.definitions) ? data.definitions : []); })+ .catch(() => { if (active) setDefinitions([]); });+ return () => { active = false; };+ }, []);++ const grouped = useMemo(() => FAMILY_ORDER+ .map((family) => ({ family, rows: (definitions || []).filter((row) => row.family === family) }))+ .filter((group) => group.rows.length > 0), [definitions]);+ const definition = (definitions || []).find((row) => row.id === draft.definitionId) || null;++ const pickDefinition = (definitionId) => {+ const next = (definitions || []).find((row) => row.id === definitionId) || null;+ setDraft({+ ...EMPTY_DRAFT,+ definitionId,+ plan: next?.plans?.[0] || '',+ transports: transportsDraftFor(next),+ });+ };++ const needsKey = definition?.family === 'api-key' && definition.envVars.length > 0;+ const declaredTransports = Object.entries(draft.transports);+ const endpointRequired = definition && definition.family !== 'subscription'+ && declaredTransports.length > 0 && declaredTransports.every(([, baseUrl]) => !baseUrl.trim());++ const submit = async (e) => {+ e.preventDefault();+ if (!definition) return;+ if (endpointRequired) {+ toast.error('This service declares no default endpoint — enter the one this install reaches it at');+ return;+ }+ const transports = Object.fromEntries(declaredTransports+ .filter(([, baseUrl]) => baseUrl.trim())+ .map(([protocol, baseUrl]) => [protocol, { baseUrl: baseUrl.trim() }]));+ const body = {+ definitionId: definition.id,+ plan: draft.plan || undefined,+ ...(draft.label.trim() ? { label: draft.label.trim() } : {}),+ ...(draft.slug.trim() ? { slug: draft.slug.trim() } : {}),+ ...(Object.keys(transports).length > 0 ? { transports } : {}),+ ...(needsKey ? { credentialVia: draft.credentialVia } : {}),+ ...(needsKey && draft.credentialVia === 'stored' && draft.apiKey.trim() ? { credentials: { apiKey: draft.apiKey.trim() } } : {}),+ };+ setBusy(true);+ const result = await api.createProviderService(body, { silent: true }).catch((err) => ({ error: err?.message || 'Could not add the service' }));+ setBusy(false);+ if (!result?.service) {+ toast.error(result?.error || 'Could not add the service');+ return;+ }+ toast.success(`${result.service.label} added — nothing was contacted; refresh its catalog when ready`);+ onCreated(result.service);+ };++ return (+ <Drawer open onClose={onClose} title="Add service" size="md" closeLabel="Close add service" closeOnBackdrop={false}>+ <form onSubmit={submit} className="space-y-4">+ {definitions !== null && definitions.length === 0 && (+ <Banner tone="error" size="sm">Could not load the service definitions from this server.</Banner>+ )}+ <FormField label="Service *" hint="The backend a harness can be pointed at">+ <select+ id="service-definition"+ value={draft.definitionId}+ onChange={(e) => pickDefinition(e.target.value)}+ required+ className={INPUT_CLASS}+ >+ <option value="">{definitions === null ? 'Loading…' : 'Choose a service'}</option>+ {grouped.map((group) => (+ <optgroup key={group.family} label={FAMILY_LABEL[group.family]}>+ {group.rows.map((row) => <option key={row.id} value={row.id}>{row.label}</option>)}+ </optgroup>+ ))}+ </select>+ </FormField>++ {definition && (+ <>+ <FormField label="Plan *" hint="What you are entitled to on it — decides which models the catalog keeps and how cost is attributed">+ <select id="service-plan" value={draft.plan} onChange={(e) => setDraft((prev) => ({ ...prev, plan: e.target.value }))} className={INPUT_CLASS}>+ {definition.plans.map((plan) => <option key={plan} value={plan}>{PLAN_LABEL[plan] || plan}</option>)}+ </select>+ </FormField>++ {definition.family === 'subscription' && (+ <Banner tone="info" size="sm">+ Sign-in lives inside the {definition.harnessOnly || 'harness'} program. PortOS holds no key for it.+ </Banner>+ )}++ {needsKey && (+ <fieldset className="space-y-2">+ <legend className="text-sm text-gray-400">Credential</legend>+ <div className="flex flex-wrap gap-3 text-sm text-gray-300">+ {[['stored', 'Store a key here'], ['env', `Read ${definition.envVars[0]} from the environment`], ['bootstrap', 'A bootstrap wrapper supplies it at spawn']].map(([via, label]) => (+ <label key={via} htmlFor={`service-via-${via}`} className="flex items-center gap-1.5 cursor-pointer">+ <input+ id={`service-via-${via}`}+ type="radio"+ name="service-credential-via"+ value={via}+ checked={draft.credentialVia === via}+ onChange={() => setDraft((prev) => ({ ...prev, credentialVia: via }))}+ className="accent-port-accent"+ />+ {label}+ </label>+ ))}+ </div>+ {draft.credentialVia === 'stored' && (+ <FormField label="API key" compact>+ <input+ id="service-api-key"+ type="password"+ autoComplete="off"+ value={draft.apiKey}+ onChange={(e) => setDraft((prev) => ({ ...prev, apiKey: e.target.value }))}+ className={INPUT_CLASS}+ placeholder="Paste the key, or leave blank to add it later"+ />+ </FormField>+ )}+ {definition.keyUrl && (+ <a href={definition.keyUrl} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline">+ Get a key <ExternalLink className="w-3 h-3" aria-hidden="true" />+ </a>+ )}+ </fieldset>+ )}++ {declaredTransports.map(([protocol, baseUrl]) => (+ <FormField+ key={protocol}+ label={`${protocol} endpoint${definition.family === 'api-key' ? '' : ' *'}`}+ hint={definition.family === 'api-key' ? 'The vendor default — change it only for a self-hosted gateway' : 'Where this install reaches the daemon'}+ >+ <input+ id={`service-endpoint-${protocol}`}+ type="url"+ value={baseUrl}+ required={definition.family !== 'api-key'}+ onChange={(e) => setDraft((prev) => ({ ...prev, transports: { ...prev.transports, [protocol]: e.target.value } }))}+ className={INPUT_CLASS}+ placeholder="http://localhost:11434/v1"+ />+ </FormField>+ ))}++ <div className="grid gap-3 sm:grid-cols-2">+ <FormField label="Label" hint={`Defaults to "${definition.label}"`} compact>+ <input id="service-label" type="text" value={draft.label} onChange={(e) => setDraft((prev) => ({ ...prev, label: e.target.value }))} className={INPUT_CLASS} />+ </FormField>+ <FormField label="Slug" hint={`The address a composite id names; defaults to "${definition.id}"`} compact>+ <input id="service-slug" type="text" value={draft.slug} pattern="[a-z0-9][a-z0-9-]*" onChange={(e) => setDraft((prev) => ({ ...prev, slug: e.target.value }))} className={INPUT_CLASS} placeholder={definition.id} />+ </FormField>+ </div>+ </>+ )}++ <div className="flex flex-wrap gap-2 pt-2">+ <button type="submit" disabled={busy || !definition} className="px-4 py-2 text-sm rounded-lg bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50">+ {busy ? 'Adding…' : 'Add service'}+ </button>+ <button type="button" onClick={onClose} className="px-4 py-2 text-sm rounded-lg border border-port-border text-gray-300 hover:text-white">+ Cancel+ </button>+ </div>+ </form>+ </Drawer>+ );+}diff --git a/client/src/components/providers/ProviderServicesTab.jsx b/client/src/components/providers/ProviderServicesTab.jsxnew file mode 100644index 0000000000..df83db907d--- /dev/null+++ b/client/src/components/providers/ProviderServicesTab.jsx@@ -0,0 +1,409 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { Link, useNavigate } from 'react-router';+import { ExternalLink, Plug, RefreshCw, Trash2 } from 'lucide-react';+import toast from '../ui/Toast';+import Banner from '../ui/Banner';+import Pill from '../ui/Pill';+import EmptyState from '../EmptyState';+import InlineConfirmRow from '../ui/InlineConfirmRow';+import { FormField } from '../ui/FormField';+import * as api from '../../services/api';+import { invalidateProviderCatalog } from '../../hooks/useProviderCatalog';+import { catalogSummary } from '../../lib/providerManagement';+import { formatCount } from '../../utils/formatters';+import ProviderReadiness from './ProviderReadiness';+import ProviderServiceForm from './ProviderServiceForm';+import { presetEditPath } from '../../utils/providerHarnesses';++/**+ * AI Providers → Services (#7567, epic #7561): one card per service INSTANCE —+ * a definition the user declared a plan for, holding a credential and the+ * catalog it last listed. This is the surface the Backend Connections drawer+ * (#6369) used to be: a connection IS a service instance, so its endpoint, key+ * and catalog are still edited once here and reach every preset derived from+ * it. What it no longer offers is binding link/unlink and per-route rows —+ * under the composed model a preset names its service outright+ * (`serviceId`), and a preset's own settings live on the preset editor.+ *+ * Nothing on this view contacts a provider on mount or on toggle. The one+ * outbound call is the explicit **Refresh** on a card, which lists the+ * instance's models through its definition's strategy.+ */++const PLAN_TONE = { free: 'success', paid: 'warning', subscription: 'accent', local: 'muted' };+const READINESS_COPY = {+ ready: { tone: 'success', text: 'Ready' },+ disabled: { tone: 'muted', text: 'Switched off' },+ 'needs-endpoint': { tone: 'warning', text: 'Needs an endpoint' },+ 'needs-credential': { tone: 'warning', text: 'Needs a credential' },+ 'unknown-definition': { tone: 'muted', text: 'No definition' },+};+const CREDENTIAL_SOURCE_COPY = {+ settings: 'Key stored on this service',+ env: 'Key read from the environment',+ 'env-file': 'Key read from the install .env',+ cli: 'Signed in through the harness',+ config: 'Supplied by a bootstrap wrapper at spawn',+ none: 'No key',+};+const CATALOG_TONE_CLASS = { error: 'text-port-error', ok: 'text-port-success', warn: 'text-port-warning', muted: 'text-gray-500' };+const INPUT_CLASS = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden';++const serviceName = (service) => service.label || service.slug || service.id;+const serviceRef = (service) => service.slug || service.id;++const draftFrom = (service) => ({+ label: service.label || '',+ transports: Object.fromEntries(Object.entries(service.transports || {}).map(([protocol, value]) => [protocol, value?.baseUrl || ''])),+ apiKey: '',+});++function ServiceCard({+ service, open, busy, presets, readiness, readinessActions, onSelect, onToggle, onRefresh, onSave, onClearKey, onDelete,+}) {+ const ref = useRef(null);+ useEffect(() => {+ if (open) ref.current?.scrollIntoView?.({ block: 'nearest' });+ }, [open]);+ // Re-seeded only when the row's revision moves, so a poll that changed+ // nothing cannot wipe a half-typed edit.+ const [draft, setDraft] = useState(() => draftFrom(service));+ useEffect(() => { setDraft(draftFrom(service)); }, [service.id, service.revision]); // eslint-disable-line react-hooks/exhaustive-deps+ const [confirmingDelete, setConfirmingDelete] = useState(false);++ const summary = catalogSummary(service.catalog);+ const readinessCopy = READINESS_COPY[service.readiness] || READINESS_COPY['unknown-definition'];+ const switchId = `service-enabled-${service.id}`;+ const slug = serviceRef(service);+ const definition = service.definition;++ return (+ <article+ ref={ref}+ aria-labelledby={`service-${service.id}-title`}+ className={`bg-port-card border rounded-xl ${open ? 'border-port-accent ring-1 ring-port-accent/40' : 'border-port-border'}`}+ >+ <div className="flex flex-col gap-2 p-4 sm:flex-row sm:items-start sm:justify-between">+ <button+ type="button"+ onClick={() => onSelect(open ? null : slug)}+ aria-expanded={open}+ className="min-w-0 flex-1 text-left"+ >+ <h3 id={`service-${service.id}-title`} className="text-base font-semibold text-white flex flex-wrap items-center gap-2">+ <Plug className="w-4 h-4 text-port-accent shrink-0" aria-hidden="true" />+ <span className="truncate">{serviceName(service)}</span>+ <code className="text-xs font-mono text-gray-500">{slug}</code>+ </h3>+ <p className="mt-1 text-xs text-gray-400 flex flex-wrap items-center gap-2">+ <span>{definition?.label || service.kind}</span>+ <Pill tone={PLAN_TONE[service.plan] || 'muted'} size="xs">{service.plan}</Pill>+ <Pill tone={readinessCopy.tone} size="xs">{readinessCopy.text}</Pill>+ <span className={CATALOG_TONE_CLASS[summary.tone]}>{summary.text}</span>+ </p>+ </button>+ <label htmlFor={switchId} className="flex items-center gap-2 text-sm text-gray-300 cursor-pointer shrink-0">+ <input+ id={switchId}+ type="checkbox"+ role="switch"+ aria-checked={service.enabled}+ checked={service.enabled}+ disabled={busy}+ onChange={(e) => onToggle(service, e.target.checked)}+ className="h-4 w-4 accent-port-accent"+ />+ {service.enabled ? 'Enabled' : 'Disabled'}+ </label>+ </div>++ {open && (+ <div className="space-y-4 border-t border-port-border p-4">+ {summary.detail && <Banner tone="error" size="sm">{summary.detail}</Banner>}++ <div className="text-xs text-gray-400 flex flex-wrap items-center gap-2">+ <span>{CREDENTIAL_SOURCE_COPY[service.credentialSource] || service.credentialSource}</span>+ {definition?.keyUrl && service.credentialSource === 'none' && (+ <a href={definition.keyUrl} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-1 text-port-accent hover:underline">+ Get a key <ExternalLink className="w-3 h-3" aria-hidden="true" />+ </a>+ )}+ {definition?.envVars?.length > 0 && service.credentialSource !== 'settings' && (+ <span className="text-gray-500">env: <code className="font-mono">{definition.envVars.join(', ')}</code></span>+ )}+ </div>++ <div className="grid gap-3 grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))]">+ <FormField label="Name" compact>+ <input id={`service-label-${service.id}`} type="text" value={draft.label} onChange={(e) => setDraft((prev) => ({ ...prev, label: e.target.value }))} className={INPUT_CLASS} />+ </FormField>+ {Object.entries(draft.transports).map(([protocol, baseUrl]) => (+ <FormField key={protocol} label={`${protocol} endpoint`} compact>+ <input+ id={`service-${service.id}-${protocol}`}+ type="text"+ value={baseUrl}+ onChange={(e) => setDraft((prev) => ({ ...prev, transports: { ...prev.transports, [protocol]: e.target.value } }))}+ className={INPUT_CLASS}+ />+ </FormField>+ ))}+ {service.credentialVia === 'stored' && (+ <FormField label={`API key ${service.hasCredentials ? '(set — leave blank to keep)' : '(none)'}`} compact>+ <input+ id={`service-key-${service.id}`}+ type="password"+ autoComplete="off"+ value={draft.apiKey}+ onChange={(e) => setDraft((prev) => ({ ...prev, apiKey: e.target.value }))}+ placeholder={service.hasCredentials ? 'Unchanged' : 'Not set'}+ className={INPUT_CLASS}+ />+ </FormField>+ )}+ </div>++ <div className="flex flex-wrap gap-2">+ <button type="button" disabled={busy} onClick={() => onSave(service, draft)} className="px-3 py-1.5 text-sm rounded-lg bg-port-accent text-white hover:bg-port-accent/80 disabled:opacity-50">+ Save service+ </button>+ {definition && (+ <button type="button" disabled={busy} onClick={() => onRefresh(service)} className="inline-flex items-center gap-1 px-3 py-1.5 text-sm rounded-lg border border-port-border text-gray-200 hover:text-white disabled:opacity-50">+ <RefreshCw className={`w-3.5 h-3.5 ${busy ? 'animate-spin' : ''}`} aria-hidden="true" /> Refresh catalog+ </button>+ )}+ {service.hasCredentials && (+ <button type="button" disabled={busy} onClick={() => onClearKey(service)} className="px-3 py-1.5 text-sm rounded-lg border border-port-border text-gray-200 hover:text-white disabled:opacity-50">+ Clear key+ </button>+ )}+ {presets.length === 0 && !confirmingDelete && (+ <button type="button" disabled={busy} onClick={() => setConfirmingDelete(true)} className="inline-flex items-center gap-1 px-3 py-1.5 text-sm rounded-lg border border-port-error/50 text-port-error hover:bg-port-error/10 disabled:opacity-50">+ <Trash2 className="w-3.5 h-3.5" aria-hidden="true" /> Delete+ </button>+ )}+ </div>+ {confirmingDelete && (+ <InlineConfirmRow+ question={`Delete the ${serviceName(service)} service? Its endpoint, catalog and saved key go with it.`}+ confirmText="Delete service"+ autoFocus+ aria-label={`Confirm deleting the ${serviceName(service)} service`}+ onConfirm={() => { setConfirmingDelete(false); onDelete(service); }}+ onCancel={() => setConfirmingDelete(false)}+ />+ )}++ {readiness && (+ <ProviderReadiness+ readiness={readiness}+ onAutoSetup={readinessActions.onAutoSetup}+ onUseServedModel={readinessActions.onUseServedModel}+ onServeWantedModel={readinessActions.onServeWantedModel}+ serving={readinessActions.serving}+ optional={!service.enabled}+ />+ )}++ {service.catalog?.models?.length > 0 && (+ <p className="text-xs text-gray-400">+ Catalog: {service.catalog.models.slice(0, 6).map((model) => (typeof model === 'string' ? model : model?.id)).join(', ')}+ {service.catalog.models.length > 6 ? ` +${formatCount(service.catalog.models.length - 6)}` : ''}+ </p>+ )}++ <div>+ <h4 className="text-xs uppercase tracking-wide text-gray-500 mb-1">+ Presets on this service ({formatCount(presets.length, { fallback: '0' })})+ </h4>+ {presets.length === 0 ? (+ <p className="text-xs text-gray-500">+ None yet — compose one from any picker, or from the compatibility matrix on the{' '}+ <Link to="/ai/presets" className="text-port-accent hover:underline">Presets view</Link>.+ </p>+ ) : (+ <ul className="flex flex-wrap gap-2">+ {presets.map((preset) => (+ <li key={preset.id}>+ <Link to={presetEditPath(preset.id)} className="text-xs px-2 py-1 rounded bg-port-bg border border-port-border text-gray-200 hover:border-port-accent">+ {preset.name}+ </Link>+ </li>+ ))}+ </ul>+ )}+ </div>+ </div>+ )}+ </article>+ );+}++/**+ * @param {object} props+ * @param {string|null} props.selectedServiceSlug - from `/ai/services/:serviceSlug` (slug or UUID); opened and scrolled to.+ * @param {boolean} props.creating - `/ai/services/new`: the add drawer is open.+ * @param {object[]} props.presets - the page's provider list, for "presets on this service" and the readiness subject.+ * @param {object} props.readiness - the page's local-daemon readiness map, keyed by preset id.+ * @param {object} props.readinessActions - `{ onAutoSetup, onUseServedModel, onServeWantedModel, servingModel }` from the page.+ * @param {function} props.onChanged - a service write may re-materialize derived presets; the page reloads them.+ */+export default function ProviderServicesTab({+ selectedServiceSlug = null, creating = false, presets = [], readiness = {}, readinessActions = {}, onChanged,+}) {+ const navigate = useNavigate();+ const [services, setServices] = useState(null); // null = not loaded+ const [loadError, setLoadError] = useState(null);+ const [busy, setBusy] = useState({});++ const load = useCallback(async () => {+ const data = await api.getProviderServices({ silent: true }).catch((err) => ({ err }));+ if (data?.err) {+ setLoadError(data.err.message || 'Could not load the services.');+ return;+ }+ setLoadError(null);+ setServices(Array.isArray(data?.services) ? data.services : []);+ }, []);++ useEffect(() => { load(); }, [load]);++ const presetsByService = useMemo(() => {+ const map = {};+ for (const preset of presets) {+ if (!preset.serviceId) continue;+ (map[preset.serviceId] ||= []).push(preset);+ }+ return map;+ }, [presets]);++ const selected = useMemo(() => (services || []).find((service) => service.slug === selectedServiceSlug || service.id === selectedServiceSlug) || null, [services, selectedServiceSlug]);+ useEffect(() => {+ if (services === null || !selectedServiceSlug || selected) return;+ toast.error(`No service with id "${selectedServiceSlug}"`);+ navigate('/ai/services', { replace: true });+ }, [services, selectedServiceSlug, selected, navigate]);++ const select = useCallback((slug) => navigate(slug ? `/ai/services/${encodeURIComponent(slug)}` : '/ai/services', { replace: true }), [navigate]);++ /** One write, then the row the server returns replaces ours and every picker re-reads the catalog. */+ const write = async (service, label, work, { reloadPresets = false } = {}) => {+ const key = service.id;+ setBusy((prev) => ({ ...prev, [key]: true }));+ const result = await work().catch((err) => ({ err }));+ setBusy((prev) => ({ ...prev, [key]: false }));+ if (result?.err) {+ toast.error(result.err.message || `${label} failed.`);+ return null;+ }+ if (result?.service) setServices((current) => (current || []).map((row) => (row.id === result.service.id ? result.service : row)));+ invalidateProviderCatalog();+ if (reloadPresets) onChanged?.();+ return result;+ };++ const handleToggle = async (service, enabled) => {+ const result = await write(service, enabled ? 'Enabling' : 'Disabling', () => api.updateProviderService(+ serviceRef(service), { expectedRevision: service.revision, enabled }, { silent: true },+ ));+ if (result) toast.success(`${serviceName(service)} ${enabled ? 'enabled' : 'disabled'}`);+ };++ const handleRefresh = async (service) => {+ const result = await write(service, 'Refreshing the catalog', () => api.refreshProviderServiceCatalog(serviceRef(service), { silent: true }), { reloadPresets: true });+ if (!result?.service) return;+ const { catalog } = result.service;+ if (catalog.state === 'failed') toast.error(catalog.error || 'The catalog refresh failed — the previous catalog was kept.');+ else toast.success(`${formatCount(catalog.models.length)} model${catalog.models.length === 1 ? '' : 's'} listed for ${serviceName(service)}`);+ };++ const handleSave = async (service, draft) => {+ const transports = Object.fromEntries(Object.entries(draft.transports)+ .filter(([, baseUrl]) => baseUrl.trim())+ .map(([protocol, baseUrl]) => [protocol, { baseUrl: baseUrl.trim() }]));+ const result = await write(service, 'Saving the service', () => api.updateProviderService(serviceRef(service), {+ expectedRevision: service.revision,+ label: draft.label,+ ...(Object.keys(transports).length > 0 ? { transports } : {}),+ ...(draft.apiKey.trim() ? { credentials: { apiKey: draft.apiKey.trim() } } : {}),+ }, { silent: true }), { reloadPresets: true });+ if (result) toast.success(`${serviceName(result.service)} saved — every preset derived from it follows`);+ };++ const handleClearKey = async (service) => {+ const result = await write(service, 'Clearing the key', () => api.updateProviderService(+ serviceRef(service), { expectedRevision: service.revision, credentials: { apiKey: null } }, { silent: true },+ ), { reloadPresets: true });+ if (result) toast.success('Key cleared on this service and every preset derived from it.');+ };++ const handleDelete = async (service) => {+ const result = await write(service, 'Deleting the service', () => api.deleteProviderService(serviceRef(service), { silent: true }));+ if (!result) return;+ setServices((current) => (current || []).filter((row) => row.id !== service.id));+ toast.success(`${serviceName(service)} deleted`);+ select(null);+ };++ const handleCreated = (service) => {+ setServices((current) => [...(current || []), service]);+ invalidateProviderCatalog();+ navigate(`/ai/services/${encodeURIComponent(serviceRef(service))}`, { replace: true });+ };++ return (+ <div className="space-y-4">+ {loadError && (+ <Banner tone="error" size="md" title="Failed to load services" actions={(+ <button type="button" onClick={load} className="px-3 py-1.5 rounded-lg text-xs bg-port-error/20 hover:bg-port-error/30 text-port-error font-medium">Retry</button>+ )}>+ {loadError}+ </Banner>+ )}+ {services === null && !loadError && <p className="text-sm text-gray-400">Loading services…</p>}+ {services?.length === 0 && (+ <EmptyState+ title="No services yet"+ message="A service is a backend a harness can be pointed at — a hosted API you hold a key for, a local runtime, or a subscription the harness signs into. Add one, then any enabled harness can compose a run on it."+ actionLabel="Add service"+ onAction={() => navigate('/ai/services/new')}+ />+ )}+ {services?.length > 0 && (+ <div className="grid gap-4">+ {services.map((service) => {+ const servicePresets = presetsByService[service.slug] || [];+ // Local-daemon readiness is computed per PRESET; the first derived+ // preset on this instance stands for the daemon they all share.+ const subject = servicePresets.find((preset) => readiness[preset.id]) || null;+ return (+ <ServiceCard+ key={service.id}+ service={service}+ open={selected?.id === service.id}+ busy={Boolean(busy[service.id])}+ presets={servicePresets}+ readiness={subject ? readiness[subject.id] : null}+ readinessActions={{+ onAutoSetup: subject ? (setup) => readinessActions.onAutoSetup?.({ ...setup, providerId: subject.id }) : undefined,+ onUseServedModel: subject ? (modelId) => readinessActions.onUseServedModel?.(subject, modelId) : undefined,+ onServeWantedModel: subject ? () => readinessActions.onServeWantedModel?.(subject) : undefined,+ serving: subject ? Boolean(readinessActions.servingModel?.[subject.id]) : false,+ }}+ onSelect={select}+ onToggle={handleToggle}+ onRefresh={handleRefresh}+ onSave={handleSave}+ onClearKey={handleClearKey}+ onDelete={handleDelete}+ />+ );+ })}+ </div>+ )}+ {creating && (+ <ProviderServiceForm onClose={() => navigate('/ai/services')} onCreated={handleCreated} />+ )}+ </div>+ );+}diff --git a/client/src/components/providers/ProviderServicesTab.test.jsx b/client/src/components/providers/ProviderServicesTab.test.jsxnew file mode 100644index 0000000000..ac968557e5--- /dev/null+++ b/client/src/components/providers/ProviderServicesTab.test.jsx@@ -0,0 +1,227 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';+import { MemoryRouter, Route, Routes, useLocation, useParams } from 'react-router';+import useProviderCatalog, { __resetProviderCatalogCache } from '../../hooks/useProviderCatalog';++/**+ * AI Providers → Services (#7567). What only this boundary pins: the list+ * contacts no provider on mount (catalog refresh is the one explicit outbound+ * action), a toggle and an edit go through the revision-gated PATCH and+ * re-read the composition catalog, the add drawer walks definition → plan →+ * credential/endpoint and lands on the new card, and a service with presets+ * on it offers no delete.+ */++const api = vi.hoisted(() => ({+ getProviderCatalog: vi.fn(),+ createProviderPreset: vi.fn(),+ getProviderServices: vi.fn(),+ getProviderServiceDefinitions: vi.fn(),+ createProviderService: vi.fn(),+ updateProviderService: vi.fn(),+ deleteProviderService: vi.fn(),+ refreshProviderServiceCatalog: vi.fn(),+}));+vi.mock('../../services/api', () => api);++const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }));+vi.mock('../ui/Toast', () => ({ default: toast }));++import ProviderServicesTab from './ProviderServicesTab';++const nvidia = {+ id: 'uuid-nvidia', revision: 3, kind: 'gateway:nvidia-nim', label: 'NVIDIA NIM', slug: 'nvidia-nim', definitionId: 'nvidia-nim',+ plan: 'free', enabled: true, credentialVia: 'stored', hasCredentials: false, credentialSource: 'none', bindingCount: 0,+ readiness: 'needs-credential',+ transports: { openai: { baseUrl: 'https://integrate.api.nvidia.com/v1' } },+ catalog: { state: 'unknown', models: [] },+ definition: { id: 'nvidia-nim', label: 'NVIDIA NIM', family: 'api-key', plans: ['free', 'paid'], catalogStrategy: 'probe', harnessOnly: null, keyUrl: 'https://build.nvidia.com', envVars: ['NVIDIA_API_KEY'] },+};+const ollama = {+ id: 'uuid-ollama', revision: 1, kind: 'ollama', label: 'Ollama', slug: 'ollama', definitionId: 'ollama',+ plan: 'local', enabled: true, credentialVia: 'stored', hasCredentials: false, credentialSource: 'none', bindingCount: 2,+ readiness: 'ready',+ transports: { openai: { baseUrl: 'http://localhost:11434/v1' } },+ catalog: { state: 'known', models: ['qwen3:8b', 'llama3:8b'] },+ definition: { id: 'ollama', label: 'Ollama', family: 'local', plans: ['local'], catalogStrategy: 'daemon', harnessOnly: null, keyUrl: null, envVars: [] },+};++const PRESETS = [+ { id: 'claude-ollama', name: 'Claude Ollama', serviceId: 'ollama' },+ { id: 'opencode-ollama', name: 'OpenCode Ollama', serviceId: 'ollama' },+];++const Probe = () => <pre data-testid="location">{useLocation().pathname}</pre>;+// A stand-in for any open picker: mounted beside the tab, it must re-read the+// composition catalog after a service write without being told.+const PickerProbe = () => { useProviderCatalog(); return null; };++function Host({ presets = PRESETS, onChanged = vi.fn() }) {+ const { serviceSlug } = useParams();+ const { pathname } = useLocation();+ return (+ <>+ <ProviderServicesTab+ selectedServiceSlug={serviceSlug || null}+ creating={pathname.endsWith('/new')}+ presets={presets}+ readiness={{}}+ readinessActions={{}}+ onChanged={onChanged}+ />+ <Probe />+ <PickerProbe />+ </>+ );+}++const renderTab = (path = '/ai/services', props = {}) => render(+ <MemoryRouter initialEntries={[path]}>+ <Routes>+ <Route path="/ai/services" element={<Host {...props} />} />+ <Route path="/ai/services/new" element={<Host {...props} />} />+ <Route path="/ai/services/:serviceSlug" element={<Host {...props} />} />+ </Routes>+ </MemoryRouter>,+);++beforeEach(() => {+ vi.clearAllMocks();+ __resetProviderCatalogCache();+ api.getProviderCatalog.mockResolvedValue({ harnesses: [], services: [], bootstraps: [], compatibility: {}, effortLevels: {}, effortLevelsByModel: {}, presets: [] });+ api.getProviderServices.mockResolvedValue({ services: [nvidia, ollama] });+});++describe('ProviderServicesTab', () => {+ it('lists every instance with plan, readiness and catalog state, and contacts no provider on mount', async () => {+ renderTab();+ const card = await screen.findByRole('article', { name: /NVIDIA NIM/ });+ expect(card).toHaveTextContent('free');+ expect(card).toHaveTextContent('Needs a credential');+ expect(card).toHaveTextContent('Not refreshed yet');+ expect(screen.getByRole('article', { name: /Ollama/ })).toHaveTextContent('2 models');+ expect(api.refreshProviderServiceCatalog).not.toHaveBeenCalled();+ });++ it('opens the card the URL names, links a key source, and lists the presets on it', async () => {+ renderTab('/ai/services/ollama');+ const card = await screen.findByRole('article', { name: /Ollama/ });+ expect(within(card).getByRole('button', { name: /Ollama/ })).toHaveAttribute('aria-expanded', 'true');+ expect(within(card).getByRole('link', { name: 'Claude Ollama' })).toHaveAttribute('href', '/ai/presets/claude-ollama');+ // Presets still name this service, so it cannot be deleted.+ expect(within(card).queryByRole('button', { name: /Delete/ })).not.toBeInTheDocument();+ // The keyed vendor with no key offers where to get one.+ fireEvent.click(within(screen.getByRole('article', { name: /NVIDIA NIM/ })).getByRole('button', { name: /NVIDIA NIM/ }));+ expect(await screen.findByRole('link', { name: /Get a key/ })).toHaveAttribute('href', 'https://build.nvidia.com');+ });++ it('refreshes a catalog only on the explicit click, re-derives presets and re-reads the composition catalog', async () => {+ const onChanged = vi.fn();+ api.refreshProviderServiceCatalog.mockResolvedValue({ service: { ...ollama, revision: 2, catalog: { state: 'known', models: ['qwen3:8b', 'llama3:8b', 'phi4'] } } });+ renderTab('/ai/services/ollama', { onChanged });+ fireEvent.click(await screen.findByRole('button', { name: /Refresh catalog/ }));+ await waitFor(() => expect(api.refreshProviderServiceCatalog).toHaveBeenCalledWith('ollama', { silent: true }));+ expect(await screen.findByText(/3 models/)).toBeInTheDocument();+ expect(onChanged).toHaveBeenCalled();+ // The picker probe re-read the catalog: one fetch on mount, one after the write.+ await waitFor(() => expect(api.getProviderCatalog).toHaveBeenCalledTimes(2));+ });++ it('keeps the previous catalog and says so when a refresh fails', async () => {+ api.refreshProviderServiceCatalog.mockResolvedValue({ service: { ...ollama, catalog: { state: 'failed', models: ollama.catalog.models, error: 'daemon not running' } } });+ renderTab('/ai/services/ollama');+ fireEvent.click(await screen.findByRole('button', { name: /Refresh catalog/ }));+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('daemon not running'));+ expect(screen.getByRole('article', { name: /Ollama/ })).toHaveTextContent('Last refresh failed — showing 2 previously known models');+ });++ it('toggles an instance through the revision-gated PATCH', async () => {+ api.updateProviderService.mockResolvedValue({ service: { ...nvidia, revision: 4, enabled: false, readiness: 'disabled' } });+ renderTab();+ const card = await screen.findByRole('article', { name: /NVIDIA NIM/ });+ fireEvent.click(within(card).getByRole('switch'));+ await waitFor(() => expect(api.updateProviderService).toHaveBeenCalledWith('nvidia-nim', { expectedRevision: 3, enabled: false }, { silent: true }));+ await waitFor(() => expect(card).toHaveTextContent('Switched off'));+ });++ it('saves label, endpoint and a new key together, never echoing a stored key', async () => {+ api.updateProviderService.mockResolvedValue({ service: { ...nvidia, revision: 4, label: 'NVIDIA (free)', hasCredentials: true, credentialSource: 'settings', readiness: 'ready' } });+ renderTab('/ai/services/nvidia-nim');+ const card = await screen.findByRole('article', { name: /NVIDIA NIM/ });+ fireEvent.change(within(card).getByLabelText('Name'), { target: { value: 'NVIDIA (free)' } });+ fireEvent.change(within(card).getByLabelText(/API key/), { target: { value: 'nvapi-example' } });+ fireEvent.click(within(card).getByRole('button', { name: 'Save service' }));+ await waitFor(() => expect(api.updateProviderService).toHaveBeenCalledWith('nvidia-nim', {+ expectedRevision: 3,+ label: 'NVIDIA (free)',+ transports: { openai: { baseUrl: 'https://integrate.api.nvidia.com/v1' } },+ credentials: { apiKey: 'nvapi-example' },+ }, { silent: true }));+ expect(await screen.findByText('Key stored on this service')).toBeInTheDocument();+ });++ it('deletes an unused instance and returns to the list', async () => {+ api.deleteProviderService.mockResolvedValue({ deleted: true });+ renderTab('/ai/services/nvidia-nim');+ const card = await screen.findByRole('article', { name: /NVIDIA NIM/ });+ fireEvent.click(within(card).getByRole('button', { name: /Delete/ }));+ fireEvent.click(within(card).getByRole('button', { name: 'Delete service' }));+ await waitFor(() => expect(api.deleteProviderService).toHaveBeenCalledWith('nvidia-nim', { silent: true }));+ await waitFor(() => expect(screen.queryByRole('article', { name: /NVIDIA NIM/ })).not.toBeInTheDocument());+ expect(screen.getByTestId('location')).toHaveTextContent('/ai/services');+ });++ it('bounces a deep link to an unknown service back to the list', async () => {+ renderTab('/ai/services/nope');+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('No service with id "nope"'));+ expect(screen.getByTestId('location')).toHaveTextContent('/ai/services');+ });+});++describe('add service drawer', () => {+ const definitions = [+ { id: 'nvidia-nim', label: 'NVIDIA NIM', family: 'api-key', plans: ['free', 'paid'], catalogStrategy: 'probe', harnessOnly: null, keyUrl: 'https://build.nvidia.com', envVars: ['NVIDIA_API_KEY'], transports: { openai: { defaultBaseUrl: 'https://integrate.api.nvidia.com/v1' } } },+ { id: 'lmstudio', label: 'LM Studio', family: 'local', plans: ['local'], catalogStrategy: 'daemon', harnessOnly: null, keyUrl: null, envVars: [], transports: { openai: { defaultBaseUrl: null } } },+ { id: 'claude-subscription', label: 'Claude subscription', family: 'subscription', plans: ['subscription'], catalogStrategy: 'harness', harnessOnly: 'claude', keyUrl: null, envVars: [], transports: {} },+ ];++ beforeEach(() => {+ api.getProviderServiceDefinitions.mockResolvedValue({ definitions });+ });++ it('walks definition → plan → credential and lands on the new card', async () => {+ api.createProviderService.mockResolvedValue({ service: { ...nvidia, id: 'uuid-2', slug: 'nvidia-nim-paid', label: 'NVIDIA paid', plan: 'paid', hasCredentials: true, credentialSource: 'settings', readiness: 'ready' } });+ renderTab('/ai/services/new');+ const dialog = await screen.findByRole('dialog');+ fireEvent.change(within(dialog).getByLabelText(/Service \*/), { target: { value: 'nvidia-nim' } });+ fireEvent.change(within(dialog).getByLabelText(/Plan \*/), { target: { value: 'paid' } });+ fireEvent.change(within(dialog).getByLabelText('API key'), { target: { value: 'nvapi-example' } });+ fireEvent.change(within(dialog).getByLabelText('Label'), { target: { value: 'NVIDIA paid' } });+ fireEvent.change(within(dialog).getByLabelText('Slug'), { target: { value: 'nvidia-nim-paid' } });+ fireEvent.click(within(dialog).getByRole('button', { name: 'Add service' }));+ await waitFor(() => expect(api.createProviderService).toHaveBeenCalledWith({+ definitionId: 'nvidia-nim',+ plan: 'paid',+ label: 'NVIDIA paid',+ slug: 'nvidia-nim-paid',+ transports: { openai: { baseUrl: 'https://integrate.api.nvidia.com/v1' } },+ credentialVia: 'stored',+ credentials: { apiKey: 'nvapi-example' },+ }, { silent: true }));+ await waitFor(() => expect(screen.getByTestId('location')).toHaveTextContent('/ai/services/nvidia-nim-paid'));+ expect(await screen.findByRole('article', { name: /NVIDIA paid/ })).toBeInTheDocument();+ expect(api.refreshProviderServiceCatalog).not.toHaveBeenCalled();+ });++ it('demands an endpoint for a local runtime that declares no default, and none for a subscription', async () => {+ renderTab('/ai/services/new');+ const dialog = await screen.findByRole('dialog');+ fireEvent.change(within(dialog).getByLabelText(/Service \*/), { target: { value: 'lmstudio' } });+ expect(within(dialog).getByLabelText(/openai endpoint \*/)).toBeRequired();+ expect(within(dialog).queryByLabelText('API key')).not.toBeInTheDocument();++ fireEvent.change(within(dialog).getByLabelText(/Service \*/), { target: { value: 'claude-subscription' } });+ expect(within(dialog).queryByLabelText(/endpoint/)).not.toBeInTheDocument();+ expect(within(dialog).getByText(/Sign-in lives inside the claude program/)).toBeInTheDocument();+ });+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex e4b390bd32..685d5918a5 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -179,7 +179,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useGoalDetail` | All state + handlers backing the GoalDetailPanel (edit form, todos, milestones, plan/phases, check-ins, progress log, activity/calendar links). Loads activities + subcalendars on mount. | GoalDetailPanel composition shell; not intended for reuse outside the goals panel. || `usePostSession` | MeatSpace POST drill-run state, refresh snapshots, scoring, and idempotent test/training saves. | POST launcher and drill runners. || `useRecordMerge` | Duplicate Universe/Series merge flow: open → dry-run preview → resolve field conflicts → execute, with an `onMerged` refresh callback. Drives `<MergeModal>`. | Surfacing the merge-duplicates UI anywhere (Sharing → Duplicates, Universes page). Don't re-implement the preview/execute dance. |-| `useProviderCatalog` | The composition catalog behind the preset-first `ProviderModelSelector` and `ProviderComposePopover` (#7566): one module-shared fetch of `GET /api/providers/catalog` (harnesses + enablement, service instances, bootstrap apps, per-harness/per-model effort ladders, compatibility map, sanitized presets), plus `compatiblePairs(harnessId)`, `methodsFor(harnessId)`, `modelsFor(serviceSlug)`, `effortLevelsFor(harnessId, model)`, `resolveRef(id)` (a preset record, or a synthesized display record for a composite id — no server round trip, so a saved value renders instantly), and `savePreset(input)` (`POST /providers/presets`, "Save as preset"). Gate the fetch with the popover's `open` so a picker that never composes pays nothing. | `ProviderComposePopover`; any picker that needs to resolve/display a composite id or list harnesses/services/effort ladders without a fresh `/providers/composites/:id` round trip. |+| `useProviderCatalog` | The composition catalog behind the preset-first `ProviderModelSelector` and `ProviderComposePopover` (#7566): one module-shared fetch of `GET /api/providers/catalog` (harnesses + enablement, service instances, bootstrap apps, per-harness/per-model effort ladders, compatibility map, sanitized presets), plus `compatiblePairs(harnessId)`, `methodsFor(harnessId)`, `modelsFor(serviceSlug)`, `effortLevelsFor(harnessId, model)`, `resolveRef(id)` (a preset record, or a synthesized display record for a composite id — no server round trip, so a saved value renders instantly), and `savePreset(input)` (`POST /providers/presets`, "Save as preset"). Gate the fetch with the popover's `open` so a picker that never composes pays nothing. `invalidateProviderCatalog()` drops the shared cache and makes every mounted hook re-read — the AI Providers page calls it after a harness toggle, a service write or a bootstrap save (#7567), so an open picker's compose flow reflects the change without a reload. | `ProviderComposePopover`; any picker that needs to resolve/display a composite id or list harnesses/services/effort ladders without a fresh `/providers/composites/:id` round trip. || `useProviderModels` | AI providers + two-step provider→model selection. | Any UI that picks a provider + model. || `useReviewerModelOptions` | Selectable model ids and concrete provider defaults per model-taking reviewer for `ReviewerPicker`'s Model column — local-LLM ids from `/api/local-llm/status`, codex/claude/antigravity tiers from `/api/providers` (claude's list also spans installed Ollama ids for an Ollama-backed CLI; agy's list collapses to base ids since the row has its own Effort cell). Returns `{ optionsByReviewer, defaultModels, freeText, unavailable, loaded, reviewers }`. | Every surface that renders `ReviewerPicker` (Code Review Defaults, TaskAddForm, ScheduleTab, SlashDoRunDrawer) — the picker never fetches; pass this as its `modelOptions`. || `useLocalImageModels` | This install's local image-model catalog plus the model a blank pin resolves to (`settings.imageGen.local.modelId` → the shipped default), `enabled`-gated so nothing is probed until a local render is in play. `models` is `null` until fetched, `[]` when genuinely empty. | Any local image-model picker — the Settings Local default, and the per-record pin row on decks/universes/series/sprites/music video. |diff --git a/client/src/hooks/useProviderCatalog.js b/client/src/hooks/useProviderCatalog.jsindex 128e62a926..f898f372a1 100644--- a/client/src/hooks/useProviderCatalog.js+++ b/client/src/hooks/useProviderCatalog.js@@ -13,6 +13,12 @@ import { parseProviderRef } from '../utils/providerRef.js';*/let inFlight = null;+// Mounted hooks, notified when the shared cache is dropped so they re-read.+// The AI Providers page (#7567) toggles a harness, edits a service or saves a+// bootstrap app and every open picker's compose flow must reflect it without a+// reload — one invalidation reaches all of them.+const subscribers = new Set();+const EMPTY_CATALOG = Object.freeze({harnesses: [], services: [], bootstraps: [], compatibility: {}, effortLevels: {}, effortLevelsByModel: {}, presets: [],});@@ -32,6 +38,16 @@ export function __resetProviderCatalogCache() {inFlight = null;}+/**+ * Drop the shared catalog and make every mounted `useProviderCatalog` re-read+ * it. Call after a write that changes what compose offers: a harness+ * enablement toggle, a service create/edit/delete/refresh, a bootstrap save.+ */+export function invalidateProviderCatalog() {+ inFlight = null;+ for (const notify of subscribers) notify();+}+/*** The composition catalog behind the preset-first `ProviderModelSelector` and* `ProviderComposePopover` (#7566): one fetch of `GET /api/providers/catalog`@@ -95,6 +111,15 @@ export default function useProviderCatalog(enabled = true) {return () => { canceled = true; };}, [enabled, state.loaded]);+ // An invalidation flips `loaded` off; the fetch effect above then re-reads.+ // The stale catalog stays rendered until the new one lands — a picker never+ // blanks mid-toggle.+ useEffect(() => {+ const notify = () => setState((current) => ({ ...current, loaded: false }));+ subscribers.add(notify);+ return () => { subscribers.delete(notify); };+ }, []);+const catalog = state.catalog || EMPTY_CATALOG;const compatiblePairs = useCallback((harnessId) => {diff --git a/client/src/hooks/useProviderCatalog.test.js b/client/src/hooks/useProviderCatalog.test.jsindex 2f393e639c..6c24c7a4df 100644--- a/client/src/hooks/useProviderCatalog.test.js+++ b/client/src/hooks/useProviderCatalog.test.js@@ -148,3 +148,30 @@ describe('useProviderCatalog', () => {expect(second.result.current.harnesses).toHaveLength(2);});});++describe('invalidateProviderCatalog', () => {+ // The AI Providers page toggles a harness or writes a service and every open+ // picker's compose flow must reflect it without a reload (#7567): one+ // invalidation re-reads the catalog in every mounted hook, keeping the+ // stale rows rendered until the new ones land.+ it('re-reads the catalog in every mounted hook and keeps the stale rows until it lands', async () => {+ const { invalidateProviderCatalog } = await import('./useProviderCatalog.js');+ const { result: a } = renderHook(() => useProviderCatalog());+ const { result: b } = renderHook(() => useProviderCatalog());+ await waitFor(() => expect(a.current.loading).toBe(false));+ await waitFor(() => expect(b.current.loading).toBe(false));++ const next = { ...CATALOG, harnesses: CATALOG.harnesses.map((h) => ({ ...h, enabled: true })) };+ let release;+ api.getProviderCatalog.mockImplementationOnce(() => new Promise((resolve) => { release = () => resolve(next); }));+ act(() => { invalidateProviderCatalog(); });+ // In flight: the old rows are still what renders, not an empty catalog.+ expect(a.current.harnesses.find((h) => h.id === 'claude').enabled).toBe(false);+ expect(api.getProviderCatalog).toHaveBeenCalledTimes(2);+ await act(async () => { release(); });+ await waitFor(() => expect(a.current.harnesses.find((h) => h.id === 'claude').enabled).toBe(true));+ await waitFor(() => expect(b.current.harnesses.find((h) => h.id === 'claude').enabled).toBe(true));+ // One shared fetch served both hooks, as on the first read.+ expect(api.getProviderCatalog).toHaveBeenCalledTimes(2);+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 6a2629dfc3..3c7d8e5641 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -167,7 +167,7 @@ grep -i "what you want to do" client/src/lib/README.md| `mediaCollectionList.js` | Search / sort ordering for the Media Collections grid (#3283) and the `CollectionPickerShell` dropdown (#3312): `applyCollectionView(collections, { query, sort })` filters via `mediaSearch.js`'s AND-token matcher over name+description and orders synthetic "Unsorted" → non-empty-or-user-created → auto-generated empties, then by `COLLECTION_SORTS` (`updated` / `name` / `count`, `normalizeCollectionSort` coerces an unknown/URL value); keys are derived once per record, not per comparison. "Hide empty" is deliberately NOT a parameter — the page owns that one predicate (`collectionItemCount(c) > 0`) because it also needs the pre-filter count. `isAutoCollection(c)` recognizes a machine-created collection from ANY of four independent markers (`AUTO_NAME_PREFIXES`, `Auto-created…`/`Auto-generated…` description, `uc-`/`sc-` id, universe/series link) so a record predating a given marker still classifies; `splitCollectionName(name)` lifts the shared `Creative Director: ` / `Writers Room: ` / `Universe: ` / `Series: ` prefix into a badge label so the distinguishing tail survives truncation, and name sorting uses that stripped title. **Adding a server-side auto-creator means adding its prefix here** or its collections silently rank as user-created. Pure — no React. || `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. || `ports.js` | `PORTS` + `DEFAULT_PEER_PORT`, re-exported from the pure leaf `server/lib/ports.js` (which `ports.test.js` pins against `ecosystem.config.cjs`, the source of truth — see docs/PORTS.md). Use these instead of re-hardcoding a port literal in a form default, a copy-paste help string, or a cross-machine URL. |-| `providerManagement.js` | Joins the `GET /api/providers/management` graph into one row per connection (`groupGraphByConnection`, `findConnectionGroup`), and reads a binding's shared-model state honestly: `bindingModelOffer` (empty `selectedModels` = the whole catalog, not none), `staleSelectedModels` (pins the catalog no longer offers — reported, never repaired), `catalogSummary` (keeps `unknown` / `known`-and-empty / `failed` distinct). `routeOverrideDraft` / `routeOverridePatch` are the mode-override form pair: they walk whatever settings the server published for a route rather than naming fields, send only CHANGED keys, read a blank text field as `null` (unpinned) and a blank timeout as no change. `routeModelAliasRows` renders a route’s canonical→executable aliases with the hand-authored ones marked, and a manual alias naming a spelling the route no longer lists flagged stale rather than dropped. `connectionProtocols` / `connectionProtocol` / `transportProtocolOptions` / `harnessOptionsFor` drive the create controls from what the SERVER published (`creatableHarnesses`, `creatableConnectionKinds`) rather than a mirrored table — offering every harness that speaks one of a backend’s DECLARED transports (a cross-protocol row offers both), and naming the credential one still needs. |+| `providerManagement.js` | `catalogSummary` reads a service instance's catalog state honestly for the AI Providers → Services cards (#7567): keeps `unknown` (never asked) / `known`-and-empty / `failed` (models retained, reason attached) distinct rather than collapsing any two into "0 models". || `morsePractice.js` | Pure deterministic adaptive Morse sampler — `selectMorsePrompt` combines bounded weak-character/confusion weighting with a non-zero exploration floor and only emits material valid for the active Koch pool; `canAdvanceMorseLevel` guards level advancement on sample count, accuracy, and effective speed. || `moodBoardItemSrc.js` | `moodBoardItemSrc(item)` resolves a mood-board item to a display image/poster src (`imageUrl` → served `image:<file>` bytes → derived video thumbnail → null); `moodBoardItemVideoSrc(item)` resolves a `type:'video'` item's playback URL; `moodBoardItemAnalysisSource(item)` resolves an item to a prompt-from-media source (null when not a local gallery asset). Shared by MoodBoardDetail + MoodBoardReferenceStrip. || `rapidReaderPosition.js` | Cursor-to-word mapping plus privacy-preserving Rapid Reader progress persistence keyed by a text fingerprint; stores position/settings without storing pasted source text. |diff --git a/client/src/lib/navPresentation.js b/client/src/lib/navPresentation.jsindex 2caf969bd2..3a775f7999 100644--- a/client/src/lib/navPresentation.js+++ b/client/src/lib/navPresentation.js@@ -98,6 +98,8 @@ import {Drama,UserRound,Video,+ Plug,+ TerminalSquare,} from 'lucide-react';// NAV_COMMANDS owns every structural field shared with the sidebar. This map@@ -250,7 +252,9 @@ export const NAV_PRESENTATION = {'/openclaw': { icon: MessagesSquare },'/settings/orchestration': { icon: Cpu },'/prompts': { icon: FileText },- '/ai': { icon: Bot },+ '/ai/presets': { icon: Bot },+ '/ai/harnesses': { icon: TerminalSquare },+ '/ai/services': { icon: Plug },'/settings/security': { icon: Lock },'/settings/sharing': { icon: Share2 },'/settings/telegram': { icon: MessageSquare },diff --git a/client/src/lib/providerManagement.js b/client/src/lib/providerManagement.jsindex 1c4c21f818..baae4f925b 100644--- a/client/src/lib/providerManagement.js+++ b/client/src/lib/providerManagement.js@@ -1,100 +1,13 @@/**- * Reading the provider connection graph (#6369).+ * Reading the provider connection graph honestly (#6369 → #7567).*- * `GET /api/providers/management` returns three flat lists — connections,- * harness bindings and executable routes. Every management screen needs the- * same joined shape and the same three questions answered about it, so the- * joining lives here rather than inside a component:- *- * - which harnesses share this backend, and through which executable routes;- * - which routes a shared-model choice would affect;- * - which saved model pins the current subset no longer covers.- *- * Pure and side-effect-free. The graph is already sanitized server-side (a- * connection reports `hasCredentials`, never a secret), so nothing here has to- * redact — but nothing here may start inventing identity either: two- * connections are the same only when the server says they share an id.- */--import { harnessLabel } from '../utils/providerHarnesses.js';--/** Route modes in the order a human reads them: run it, watch it, call it. */-export const ROUTE_MODE_ORDER = Object.freeze(['cli', 'tui', 'api']);--const byModeOrder = (a, b) => ROUTE_MODE_ORDER.indexOf(a.mode) - ROUTE_MODE_ORDER.indexOf(b.mode);--/**- * The graph joined into one row per connection.- *- * A connection with no bindings is KEPT, not filtered away: reconciliation- * deliberately preserves an emptied connection for explicit cleanup, so hiding- * it here would make the only row a user can act on invisible. Same for a- * binding whose routes have all been deleted.- *- * @param {{connections?:object[], bindings?:object[], routes?:object[]}} graph- * @returns {{connection:object, bindings:{binding:object, label:string, routes:object[]}[], routes:object[]}[]}- */-export function groupGraphByConnection(graph) {- const bindings = Array.isArray(graph?.bindings) ? graph.bindings : [];- const routes = Array.isArray(graph?.routes) ? graph.routes : [];- const routesByBinding = new Map();- for (const route of routes) {- const list = routesByBinding.get(route.bindingId) || [];- list.push(route);- routesByBinding.set(route.bindingId, list);- }-- return (Array.isArray(graph?.connections) ? graph.connections : []).map((connection) => {- const attached = bindings- .filter((binding) => binding.connectionId === connection.id)- .map((binding) => ({- binding,- label: binding.label || harnessLabel(binding.harnessId),- routes: [...(routesByBinding.get(binding.id) || [])].sort(byModeOrder),- }));- return {- connection,- bindings: attached,- routes: attached.flatMap((entry) => entry.routes),- };- });-}--/** One connection's joined row, or `null` — never a partial match on a label. */-export const findConnectionGroup = (groups, connectionId) =>- groups.find((group) => group.connection.id === connectionId) || null;--/**- * The models a binding offers, and where each one came from.- *- * An EMPTY `selectedModels` means "the whole shared catalog", not "nothing":- * an imported binding has never been narrowed, and reading that as an empty- * offer would blank every model menu on the install the moment the graph turned- * on. Narrowing to nothing is expressed by the UI refusing to save it, not by a- * value that also means "untouched".- *- * @returns {{model:string, selected:boolean}[]} catalog order, never reordered by state- */-export function bindingModelOffer(connection, binding) {- const catalog = Array.isArray(connection?.catalog?.models) ? connection.catalog.models : [];- const chosen = Array.isArray(binding?.selectedModels) ? binding.selectedModels : [];- const narrowed = chosen.length > 0;- return catalog.map((model) => ({ model, selected: !narrowed || chosen.includes(model) }));-}--/**- * Models a binding still names that the shared catalog no longer offers.- *- * Reported rather than repaired. A pin outside the catalog is the single most- * common thing a refresh produces — the backend dropped a model — and silently- * dropping it from the binding is how a saved selection disappears without- * anyone deciding to remove it.+ * What is left of the Backend Connections drawer's helpers after the AI+ * Providers page absorbed that drawer into its Services view: a connection is+ * a service instance, and the one reading both surfaces share is how its+ * catalog state is described. Everything about bindings, route overrides and+ * model aliases went with the drawer — a preset names its service outright+ * (`serviceId`), and a preset's own settings live on the preset editor.*/-export function staleSelectedModels(connection, binding) {- const catalog = new Set(Array.isArray(connection?.catalog?.models) ? connection.catalog.models : []);- return (Array.isArray(binding?.selectedModels) ? binding.selectedModels : [])- .filter((model) => !catalog.has(model));-}/*** How to describe a connection's catalog, keeping the three states distinct.@@ -126,161 +39,3 @@ export function catalogSummary(catalog) {}return { tone: 'muted', text: 'Not refreshed yet', detail: null };}--// --- route mode overrides (#6369) ---------------------------------------------//-// A route's `settings` are the fields that belong to ONE execution mode: its-// args, its timeout, its effort and its model pins. The server decides which-// keys a mode publishes, so these two helpers never name a field — they walk-// whatever the route was given, and a mode that gains or loses a setting needs-// no client change.--/** The draft an override form edits: every published setting as text. */-export const routeOverrideDraft = (settings) => Object.fromEntries(- Object.entries(settings || {}).map(([key, value]) => [- key,- key === 'args' ? (Array.isArray(value) ? value : []).join('\n') : (value == null ? '' : String(value)),- ]),-);--/**- * The CHANGED keys between a route's saved settings and its draft.- *- * Only differences travel, so a save cannot rewrite a field the human never- * touched — which matters here because these values are also edited from the- * route editor and by model refresh.- *- * Two normalizations, both deliberate:- *- * - a blank text field is `null` (unpinned), never `''`. The server reads an- * empty pin as unset too, so treating them as different values would make- * every form dirty on open.- * - a blank `timeout` is NO CHANGE rather than a clear. The executable- * record's schema has no null timeout, so clearing one is the route- * editor's job; silently sending `null` here would break its next save.- */-export function routeOverridePatch(settings, draft) {- const patch = {};- for (const [key, current] of Object.entries(settings || {})) {- const typed = draft?.[key] ?? '';- if (key === 'args') {- const next = String(typed).split('\n').map((line) => line.trim()).filter(Boolean);- const before = Array.isArray(current) ? current : [];- if (next.length !== before.length || next.some((arg, index) => arg !== before[index])) patch.args = next;- continue;- }- if (key === 'timeout') {- const next = Number(String(typed).trim());- if (String(typed).trim() !== '' && Number.isInteger(next) && next !== current) patch.timeout = next;- continue;- }- const next = String(typed).trim() === '' ? null : String(typed).trim();- if (next !== (current ?? null)) patch[key] = next;- }- return patch;-}--// --- route model aliases (#6369) ----------------------------------------------//-// A route's `modelMap` says what THIS harness has to be sent for a given-// canonical backend model. A refresh can only record the aliases it verifies,-// so a spelling the harness adapter cannot reproduce is missing from it — and-// the shared catalog, and therefore every model menu. The panel lets a human-// supply the pair, which the server stores apart from what it observed so the-// correction outlives the next refresh.--/**- * One row per alias the route resolves through, ready to render.- *- * Sorted by canonical name so the list does not reshuffle when an entry moves- * between observed and manual. `manual` is what the user wrote (and may remove);- * `stale` is a manual alias naming a spelling the route no longer lists — shown,- * never dropped, exactly like a model pin outside the catalog.- *- * @returns {{canonical:string, executable:string, manual:boolean, stale:boolean}[]}- */-export function routeModelAliasRows(route) {- const effective = route?.modelMap && typeof route.modelMap === 'object' ? route.modelMap : {};- const overrides = route?.modelAliasOverrides && typeof route.modelAliasOverrides === 'object'- ? route.modelAliasOverrides- : {};- const stale = new Set(Array.isArray(route?.staleModelAliases) ? route.staleModelAliases : []);- return Object.entries(effective)- .map(([canonical, executable]) => ({- canonical,- executable,- manual: Object.hasOwn(overrides, canonical),- stale: stale.has(canonical),- }))- .sort((a, b) => a.canonical.localeCompare(b.canonical));-}--// --- creating a backend and a harness on it (#6369) ---------------------------//-// The two questions the create controls ask of a graph response. Both are-// answered from what the SERVER published (`creatableHarnesses`,-// `creatableConnectionKinds`), never from a table mirrored into the browser:-// which harnesses carry a command recipe, and which backend kinds a minted-// route can honestly describe, are server decisions.--/**- * Every transport protocol a connection declares.- *- * More than one is normal on a backend a human linked across protocols — one- * Ollama daemon reached by Claude on its Anthropic port and by Codex on `/v1`- * is ONE backend, and the server accepts a harness for any protocol the row- * declares (#6460).- */-export const connectionProtocols = (connection) => Object.keys(connection?.transports || {});--/** The FIRST transport protocol a connection declares, or `null` — for copy that names one. */-export const connectionProtocol = (connection) => connectionProtocols(connection)[0] || null;--/**- * Transport protocols a new backend may declare, each with the programs that- * speak it, so the form can say what the choice is FOR.- *- * @returns {{protocol:string, drivers:string[]}[]}- */-export function transportProtocolOptions(graph) {- const harnesses = Array.isArray(graph?.creatableHarnesses) ? graph.creatableHarnesses : [];- const byProtocol = new Map();- for (const harness of harnesses) {- byProtocol.set(harness.protocol, [...(byProtocol.get(harness.protocol) || []), harness.label]);- }- // A direct API route has no harness and speaks the OpenAI-compatible wire, so- // that protocol is offerable even on a build shipping no OpenAI harness.- byProtocol.set('openai', [...(byProtocol.get('openai') || []), 'Direct API']);- return [...byProtocol.entries()]- .map(([protocol, drivers]) => ({ protocol, drivers }))- .sort((a, b) => a.protocol.localeCompare(b.protocol));-}--/**- * The harnesses that can be added to THIS backend, plus the direct API option.- *- * Filtered by the protocols the backend DECLARES rather than offered and then- * refused: the server rejects a harness that speaks none of them, and an option- * whose only outcome is a 409 is not an option. A row declaring two protocols- * offers the harnesses for both — that is the whole point of a cross-protocol- * link, and the server mints a route for either one (#6460).- *- * `needsCredential` is why an otherwise-valid choice will still be refused, so- * the row can say so before the click rather than after it.- *- * @returns {{harnessId:string|null, label:string, modes:string[], needsCredential:string|null}[]}- */-export function harnessOptionsFor(graph, connection) {- const protocols = connectionProtocols(connection);- const harnesses = (Array.isArray(graph?.creatableHarnesses) ? graph.creatableHarnesses : [])- .filter((harness) => protocols.includes(harness.protocol))- .map((harness) => ({- harnessId: harness.id,- label: harness.label,- modes: harness.modes,- needsCredential: harness.credentialRequired && !connection?.hasCredentials ? harness.credentialKey : null,- }));- return protocols.includes('openai')- ? [...harnesses, { harnessId: null, label: 'Direct API', modes: ['api'], needsCredential: null }]- : harnesses;-}diff --git a/client/src/lib/providerManagement.test.js b/client/src/lib/providerManagement.test.jsindex d59efbb050..d60064dc92 100644--- a/client/src/lib/providerManagement.test.js+++ b/client/src/lib/providerManagement.test.js@@ -1,56 +1,5 @@-/**- * The two sentinel rules in the connection-graph reader that a rendered test- * cannot pin cheaply, and whose failure is silent rather than loud:- *- * - an EMPTY `selectedModels` means "the whole shared catalog", not "none".- * Reading it as none blanks every model menu on the install the moment the- * graph turns on, with no error anywhere.- * - `unknown` / `known`-and-empty / `failed` are three different answers.- * Collapsing any two into "0 models" is exactly what the catalog state- * field exists to prevent.- *- * The joining itself is exercised through the rendered management panel- * (`components/providers/ProviderConnections.test.jsx`).- */import { describe, expect, it } from 'vitest';-import {- bindingModelOffer,- catalogSummary,- groupGraphByConnection,- harnessOptionsFor,- staleSelectedModels,-} from './providerManagement.js';--const connection = (models, state = 'known') => ({- id: 'conn-1', catalog: { state, models },-});--describe('bindingModelOffer', () => {- it('offers the whole catalog when a binding has never been narrowed', () => {- expect(bindingModelOffer(connection(['a', 'b']), { selectedModels: [] }))- .toEqual([{ model: 'a', selected: true }, { model: 'b', selected: true }]);- });-- it('offers only the chosen subset once one exists', () => {- expect(bindingModelOffer(connection(['a', 'b']), { selectedModels: ['b'] }))- .toEqual([{ model: 'a', selected: false }, { model: 'b', selected: true }]);- });-- it('keeps catalog order rather than floating the selected ones', () => {- expect(bindingModelOffer(connection(['a', 'b', 'c']), { selectedModels: ['c'] }).map((e) => e.model))- .toEqual(['a', 'b', 'c']);- });-});--describe('staleSelectedModels', () => {- it('reports a selection the catalog no longer carries', () => {- expect(staleSelectedModels(connection(['a']), { selectedModels: ['a', 'gone'] })).toEqual(['gone']);- });-- it('reports nothing for a never-narrowed binding', () => {- expect(staleSelectedModels(connection(['a']), { selectedModels: [] })).toEqual([]);- });-});+import { catalogSummary } from './providerManagement.js';describe('catalogSummary', () => {it('keeps never-asked distinct from asked-and-empty', () => {@@ -64,56 +13,3 @@ describe('catalogSummary', () => {expect(summary.detail).toBe('timed out');});});--describe('groupGraphByConnection', () => {- it('keeps a connection with no bindings, so it stays cleanable', () => {- const groups = groupGraphByConnection({ connections: [connection(['a'])], bindings: [], routes: [] });- expect(groups).toHaveLength(1);- expect(groups[0].bindings).toEqual([]);- });-- it('orders a binding’s routes cli → tui → api however the server listed them', () => {- const groups = groupGraphByConnection({- connections: [connection(['a'])],- bindings: [{ id: 'b1', connectionId: 'conn-1', harnessId: 'claude', label: '' }],- routes: [- { providerId: 'p-api', bindingId: 'b1', mode: 'api' },- { providerId: 'p-tui', bindingId: 'b1', mode: 'tui' },- { providerId: 'p-cli', bindingId: 'b1', mode: 'cli' },- ],- });- expect(groups[0].bindings[0].routes.map((route) => route.mode)).toEqual(['cli', 'tui', 'api']);- // An unlabeled binding falls back to its harness's display name.- expect(groups[0].bindings[0].label).toBe('Claude Code');- });-});--describe('harnessOptionsFor', () => {- const GRAPH = {- creatableHarnesses: [- { id: 'claude', label: 'Claude Code', protocol: 'anthropic', modes: ['cli', 'tui'], credentialRequired: true, credentialKey: 'ANTHROPIC_AUTH_TOKEN' },- { id: 'codex', label: 'Codex CLI', protocol: 'openai', modes: ['cli'], credentialRequired: false, credentialKey: null },- ],- };-- it('offers the harnesses for EVERY protocol a cross-protocol backend declares', () => {- // One daemon reached on two ports is one backend, and the server mints a- // route for either protocol (#6460) — hiding one here would make the- // second harness link-only in a UI that can already create it.- const options = harnessOptionsFor(GRAPH, {- hasCredentials: true,- transports: { anthropic: { baseUrl: 'http://127.0.0.1:11434' }, openai: { baseUrl: 'http://127.0.0.1:11434/v1' } },- });- expect(options.map((option) => option.label)).toEqual(['Claude Code', 'Codex CLI', 'Direct API']);- });-- it('still hides a harness no declared transport speaks', () => {- const options = harnessOptionsFor(GRAPH, { transports: { openai: { baseUrl: 'http://127.0.0.1:11434/v1' } } });- expect(options.map((option) => option.label)).toEqual(['Codex CLI', 'Direct API']);- });-- it('names the credential a keyless backend still needs rather than hiding the choice', () => {- const [claude] = harnessOptionsFor(GRAPH, { transports: { anthropic: { baseUrl: 'http://127.0.0.1:11434' } } });- expect(claude).toMatchObject({ harnessId: 'claude', needsCredential: 'ANTHROPIC_AUTH_TOKEN' });- });-});diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex 068b85cbf7..c79ee78138 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -1,11 +1,13 @@import { useState, useEffect, useCallback, useMemo } from 'react';import { Link, useLocation, useNavigate, useParams } from 'react-router';-import { Bot, Cpu, Gauge, Link2, Network, Package } from 'lucide-react';+import { Bot, Cpu, Gauge, Network, Package, Wand2 } from 'lucide-react';import toast from '../components/ui/Toast';import * as api from '../services/api';import socket from '../services/socket';import ProviderModelSelector from '../components/ProviderModelSelector';import { filterSelectableModels, isProviderHardwareCompatible, mergeModelLists, localBackendForProvider, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isCodexSubscriptionProvider, isLocalEndpoint, isLocalInstanceProvider, providerRuntimeKey, providerCardState, PROVIDER_CARD_STATE } from '../utils/providers';+import { groupProvidersByHarness, presetEditPath } from '../utils/providerHarnesses';+import useProviderCatalog from '../hooks/useProviderCatalog';import { copyToClipboard } from '../lib/clipboard';import { formatCount } from '../utils/formatters';import { isHttpsUrl } from '../utils/urlNormalize';@@ -24,61 +26,42 @@ import CollapsibleSection from '../components/ui/CollapsibleSection';import FleetProviderSetup from '../components/providers/FleetProviderSetup';import FleetHostSetup from '../components/providers/FleetHostSetup';import LocalPersistentMindSetupCard from '../components/settings/LocalPersistentMindSetupCard.jsx';-import ProviderConnections from '../components/providers/ProviderConnections';import RetiredModelPinsPanel from '../components/providers/RetiredModelPinsPanel';+import ProviderPageTabs, { providerPageTabForPath } from '../components/providers/ProviderPageTabs';+import ProviderHarnessesTab from '../components/providers/ProviderHarnessesTab';+import ProviderServicesTab from '../components/providers/ProviderServicesTab';+import ProviderCompatibilityMatrix from '../components/providers/ProviderCompatibilityMatrix';+import ProviderComposePopover from '../components/providers/ProviderComposePopover';// The two local apps an API provider can front. Their installer lives on the// Models → LLMs page (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' };-// The buckets the cards are grouped into, in the order they render.-// "Needs setup" sits second because it is the page's only outstanding-task list,-// and it is short: it holds ONLY providers the user switched ON that still can't-// run. A switched-off one files under "Disabled" whatever it is missing — see-// the precedence note on `providerCardState`.+// Presets are grouped by HARNESS (#7567) — the program that drives them — and+// within a group ordered by readiness: what can run first, what the user+// switched on but cannot run yet second, what is switched off last. The+// readiness is still on every card as its color and badge; it just no longer+// decides which section a card lands in.//-// The last bucket is the machine's own veto: a provider the server has marked-// hardware-`unavailable` can never run here no matter what the user toggles, so-// it is pulled out of the three readiness buckets and parked in a section that-// stays COLLAPSED. Deleting it outright is not an option — the record is shared-// across a user's federated machines, and one that is unavailable here may be-// the workhorse on another — so it stays editable/deletable one click away-// instead of adding noise to the three sections that describe real choices.-export const PROVIDER_SECTIONS = [- {- key: 'enabled',- title: 'Enabled',- hint: 'Switched on and available to run',- dot: 'bg-port-success',- states: [PROVIDER_CARD_STATE.READY, PROVIDER_CARD_STATE.BENCHED],- },- {- key: 'blocked',- title: 'Needs setup',- hint: 'Switched on but missing a CLI or an API key — these cannot run yet',- dot: 'bg-port-warning',- states: [PROVIDER_CARD_STATE.BLOCKED, PROVIDER_CARD_STATE.UNKNOWN],- },- {- key: 'disabled',- title: 'Disabled',- hint: 'Switched off — optional, nothing to do unless you want one',- dot: 'bg-gray-500',- states: [PROVIDER_CARD_STATE.DISABLED],- },- {- key: 'incompatible',- title: 'Unavailable on this machine',- hint: 'This hardware cannot run them — kept for your other machines',- dot: 'bg-port-error',- // Matched by hardware, not by card state: `states` stays empty so the- // readiness filter never claims one of these cards back.- states: [],- hardwareIncompatible: true,- defaultOpen: false,- },-];+// A hardware-`unavailable` preset is pulled out of the groups altogether and+// parked in a section that stays COLLAPSED. Deleting it outright is not an+// option — the record is shared across a user's federated machines, and one+// that is unavailable here may be the workhorse on another — so it stays+// editable/deletable one click away instead of adding noise to the groups.+export const PRESET_STATE_ORDER = Object.freeze([+ PROVIDER_CARD_STATE.READY,+ PROVIDER_CARD_STATE.BENCHED,+ PROVIDER_CARD_STATE.BLOCKED,+ PROVIDER_CARD_STATE.UNKNOWN,+ PROVIDER_CARD_STATE.DISABLED,+]);++const UNAVAILABLE_SECTION = Object.freeze({+ key: 'incompatible',+ title: 'Unavailable on this machine',+ hint: 'This hardware cannot run them — kept for your other machines',+});export default function AIProviders() {const [providers, setProviders] = useState([]);@@ -206,24 +189,26 @@ export default function AIProviders() {// create route shadow its editor.const navigate = useNavigate();const location = useLocation();- const { providerId: editingProviderId, connectionId, harnessId } = useParams();- const creatingProvider = location.pathname.replace(/\/+$/, '').endsWith('/ai/new');- const fleetSetupOpen = location.pathname.replace(/\/+$/, '').endsWith('/ai/fleet');- const closeForm = useCallback(() => navigate('/ai'), [navigate]);- const openForm = useCallback((target) => navigate(target ? `/ai/edit/${target.id}` : '/ai/new'), [navigate]);-- // Backend connection management (#6369). Open state and the selected- // connection are both route segments, so `/ai/connections/<id>` and the- // harness-scoped `/ai/harnesses/<harness>/connections/<id>` are shareable and- // reachable from ⌘K and voice — same rule as the provider editor above.- const connectionsOpen = /\/ai(?:\/harnesses\/[^/]+)?\/connections(?:\/|$)/.test(- `${location.pathname.replace(/\/+$/, '')}`,- );- const connectionsBase = harnessId ? `/ai/harnesses/${harnessId}/connections` : '/ai/connections';- const selectConnection = useCallback(- (id) => navigate(id ? `${connectionsBase}/${id}` : connectionsBase, { replace: true }),- [navigate, connectionsBase],- );+ // `presetId` is the canonical editor route; `providerId` is the legacy+ // /ai/edit/:providerId alias App.jsx keeps for a preset whose id collides+ // with the create route (see `presetEditPath`).+ const { presetId, providerId, harnessId, serviceSlug } = useParams();+ const editingProviderId = presetId ?? providerId;+ const barePath = location.pathname.replace(/\/+$/, '');+ // The three views (#7567) are route prefixes, so the open one is the URL's.+ const activeTab = providerPageTabForPath(barePath);+ const creatingProvider = barePath.endsWith('/ai/presets/new');+ const creatingService = barePath.endsWith('/ai/services/new');+ const fleetSetupOpen = barePath.endsWith('/ai/fleet');+ const closeForm = useCallback(() => navigate('/ai/presets'), [navigate]);+ const openForm = useCallback((target) => navigate(target ? presetEditPath(target.id) : '/ai/presets/new'), [navigate]);++ // The compatibility matrix and the "Compose custom…" action open the shared+ // compose flow (#7566) on this page with "Save as preset" as its only exit:+ // there is no selection here to hand a one-off composite to. `null` =+ // closed; an object (possibly empty) = open, prefilled with those steps.+ const [composeInitial, setComposeInitial] = useState(null);+ const compositionCatalog = useProviderCatalog(activeTab === 'presets');useEffect(() => {loadData();@@ -676,7 +661,7 @@ export default function AIProviders() {// 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, cardStateByProviderId, providersBySection } = useMemo(() => {+ const { providersById, runtimeByProviderId, cardStateByProviderId, presetGroups, unavailablePresets } = 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((provider) => [provider.id, providerCardState(provider, {@@ -692,14 +677,15 @@ export default function AIProviders() {return typeof referenced.hasApiKey === 'boolean' ? referenced.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)];- };+ // Within a group: the default provider first (so "which one runs by+ // default" stays a one-glance answer), then by readiness, then input order.+ const rank = (p) => PRESET_STATE_ORDER.indexOf(readinessById[p.id].state);+ const ordered = (list) => list+ .map((p, index) => ({ p, index }))+ .sort((a, b) => (b.p.id === activeProviderId) - (a.p.id === activeProviderId) || rank(a.p) - rank(b.p) || a.index - b.index)+ .map(({ p }) => p);// The hardware veto is decided first: what this machine cannot run never- // reaches the readiness buckets, so a card lands in exactly one section.+ // reaches the harness groups, so a card lands in exactly one section.const cards = providers.filter(provider => {const modes = provider.executionModes || [{ id: provider.id }];const representative = modes.find(mode => mode.id === activeProviderId) || modes[0];@@ -711,12 +697,8 @@ export default function AIProviders() {providersById: byId,runtimeByProviderId: runtimeById,cardStateByProviderId: readinessById,- providersBySection: Object.fromEntries(PROVIDER_SECTIONS.map(section => [- section.key,- defaultFirst(section.hardwareIncompatible- ? unrunnable- : runnable.filter(p => section.states.includes(readinessById[p.id].state))),- ])),+ presetGroups: groupProvidersByHarness(runnable).map((group) => ({ ...group, providers: ordered(group.providers) })),+ unavailablePresets: ordered(unrunnable),};}, [providers, statuses, activeProviderId, runtimeForProvider, codexAccount]);@@ -734,7 +716,7 @@ export default function AIProviders() {useEffect(() => {if (loading || loadError || !editingProviderId || editingProvider) return;toast.error(`No provider with id "${editingProviderId}"`);- navigate('/ai', { replace: true });+ navigate('/ai/presets', { replace: true });}, [loading, loadError, editingProviderId, editingProvider, navigate]);const selectedRunProvider = providers.find(p => p.id === activeProviderId);@@ -757,11 +739,11 @@ export default function AIProviders() {// stays one row tall on a 360px viewport and the first provider card is// reachable without scrolling (issue #5653).const secondaryActions = [+ // A named combination of enabled parts, saved without hand-typing a record.+ { id: 'compose-custom', label: 'Compose custom preset…', icon: Wand2, onSelect: () => setComposeInitial({}) },{ id: 'orchestration-profiles', label: 'Orchestration profiles', icon: Cpu, to: '/settings/orchestration' },{ id: 'compare-models', label: 'Compare local models', icon: Gauge, to: '/models/performance' },{ id: 'fleet-setup', label: 'Fleet setup', icon: Network, to: '/ai/fleet' },- // One backend, edited once, for every harness pointed at it (#6369).- { id: 'backend-connections', label: 'Backend connections', icon: Link2, to: '/ai/connections' },{id: 'load-samples',label: loadingSamples ? 'Loading samples…' : 'Load Samples',@@ -771,32 +753,73 @@ export default function AIProviders() {},];+ // The header's actions belong to the open view: the presets view runs and+ // adds presets, the services view adds services, the harnesses view has+ // nothing to create (its rows are the registry).+ const headerActions = activeTab === 'presets' ? (+ <>+ <button+ onClick={() => setShowRunPanel(!showRunPanel)}+ className="inline-flex min-h-[40px] items-center rounded-lg bg-port-accent px-3 py-1.5 text-sm text-white transition-colors hover:bg-port-accent/80"+ >+ {showRunPanel ? 'Hide Runner' : 'Run Prompt'}+ </button>+ <button+ onClick={() => openForm(null)}+ className="inline-flex min-h-[40px] items-center rounded-lg bg-port-border px-3 py-1.5 text-sm text-white transition-colors hover:bg-port-border/80"+ >+ Add Preset+ </button>+ <OverflowMenu label="More provider actions" items={secondaryActions} />+ </>+ ) : activeTab === 'services' ? (+ <button+ onClick={() => navigate('/ai/services/new')}+ className="inline-flex min-h-[40px] items-center rounded-lg bg-port-accent px-3 py-1.5 text-sm text-white transition-colors hover:bg-port-accent/80"+ >+ Add Service+ </button>+ ) : null;+return (<div className="flex flex-col h-full">- <PageHeader- icon={Bot}- title="AI Providers"- actions={(- <>- <button- onClick={() => setShowRunPanel(!showRunPanel)}- className="inline-flex min-h-[40px] items-center rounded-lg bg-port-accent px-3 py-1.5 text-sm text-white transition-colors hover:bg-port-accent/80"- >- {showRunPanel ? 'Hide Runner' : 'Run Prompt'}- </button>- <button- onClick={() => openForm(null)}- className="inline-flex min-h-[40px] items-center rounded-lg bg-port-border px-3 py-1.5 text-sm text-white transition-colors hover:bg-port-border/80"- >- Add Provider- </button>- <OverflowMenu label="More provider actions" items={secondaryActions} />- </>- )}- />+ <PageHeader icon={Bot} title="AI Providers" actions={headerActions} /><ModelsTabsHeader activeTab="providers" />+ <div className="px-4 pt-3">+ <ProviderPageTabs activeTab={activeTab} />+ </div>++ {activeTab === 'harnesses' && (+ <div className="flex-1 overflow-auto p-4">+ <ProviderHarnessesTab+ selectedHarnessId={harnessId || null}+ runtimes={runtimes}+ onInstallRuntime={setInstallingRuntime}+ codexAccount={codexAccount}+ />+ </div>+ )}+ {activeTab === 'services' && (+ <div className="flex-1 overflow-auto p-4">+ <ProviderServicesTab+ selectedServiceSlug={serviceSlug || null}+ creating={creatingService}+ presets={providers}+ readiness={readiness}+ readinessActions={{+ onAutoSetup: setSettingUpRuntime,+ onUseServedModel: handleUseServedModel,+ onServeWantedModel: handleServeWantedModel,+ servingModel,+ }}+ onChanged={loadData}+ />+ </div>+ )}++ {activeTab === 'presets' && (<div className="flex-1 overflow-auto p-4 space-y-6">{/* A retirement only becomes observable when a catalog refresh lands, so@@ -1038,7 +1061,18 @@ export default function AIProviders() {</div>)}- {/* Provider List, grouped by readiness (see PROVIDER_SECTIONS) */}+ {/* Every harness × service pair the server would offer, and a click into+ the compose flow on it. Derived from the same catalog every picker+ reads, so it can never disagree with what compose lists. */}+ <ProviderCompatibilityMatrix+ harnesses={compositionCatalog.harnesses}+ services={compositionCatalog.services}+ compatibility={compositionCatalog.compatibility}+ loading={compositionCatalog.loading}+ onCompose={setComposeInitial}+ />++ {/* Preset list, grouped by harness (see PRESET_STATE_ORDER) */}<div className="grid gap-6">{loadError ? (<Banner@@ -1059,22 +1093,39 @@ export default function AIProviders() {</Banner>) : (<>- {PROVIDER_SECTIONS.map(section => {- const sectionProviders = providersBySection[section.key];+ {[+ ...presetGroups.map((group) => ({+ key: group.harnessId,+ title: group.label,+ link: group.harnessId === 'other' ? null : `/ai/harnesses/${encodeURIComponent(group.harnessId)}`,+ providers: group.providers,+ defaultOpen: true,+ })),+ { ...UNAVAILABLE_SECTION, link: null, providers: unavailablePresets, defaultOpen: false },+ ].map(section => {+ const sectionProviders = section.providers;if (sectionProviders.length === 0) return null;+ const ready = sectionProviders.filter((p) => cardStateByProviderId[p.id].state === PROVIDER_CARD_STATE.READY || cardStateByProviderId[p.id].state === PROVIDER_CARD_STATE.BENCHED).length;return (<CollapsibleSectionkey={section.key}size="lg"- defaultOpen={section.defaultOpen !== false}+ defaultOpen={section.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={`w-2 h-2 rounded-full shrink-0 ${section.key === UNAVAILABLE_SECTION.key ? 'bg-port-error' : ready > 0 ? 'bg-port-success' : 'bg-gray-500'}`} 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 className="text-xs text-gray-500">+ {section.hint || `${formatCount(ready, { fallback: '0' })} of ${formatCount(sectionProviders.length)} can run`}+ </span>+ {section.link && (+ <Link to={section.link} onClick={(e) => e.stopPropagation()} className="text-xs text-port-accent hover:underline">+ harness →+ </Link>+ )}</span>)}>@@ -1127,9 +1178,9 @@ export default function AIProviders() {{providers.length === 0 && (<EmptyState- title="No providers configured"- message="Configure at least one API provider to enable autonomous CoS, voice, and AI-assisted features across PortOS."- actionLabel="Add Provider"+ title="No presets configured"+ message="A preset is a named harness × service combination. Add a service, then compose a preset on it — or add a legacy record by hand — to enable autonomous CoS, voice, and AI-assisted features across PortOS."+ actionLabel="Add Preset"onAction={() => openForm(null)}/>)}@@ -1171,16 +1222,19 @@ export default function AIProviders() {flushMs={250}description={`Installing ${installingRuntime?.label} from ${installingRuntime?.method === 'script' ? "the vendor's official install script" : 'its global npm package'}.`}/>- {connectionsOpen && (- <ProviderConnections- open- connectionId={connectionId || null}- harnessId={harnessId || null}- onClose={closeForm}- onSelectConnection={selectConnection}- onGraphChanged={loadData}- />- )}+ <ProviderComposePopover+ open={composeInitial !== null}+ initial={composeInitial}+ useOnce={false}+ title="Compose a new preset"+ onClose={() => setComposeInitial(null)}+ onCompose={() => {}}+ onPresetSaved={(preset) => {+ toast.success(`${preset.name} saved as a preset`);+ loadData();+ navigate(presetEditPath(preset.id));+ }}+ />{fleetSetupOpen && (<FleetProviderSetuppeers={fleetPeers}@@ -1211,6 +1265,7 @@ export default function AIProviders() {: `${settingUpRuntime?.actionLabel || 'Setting up'} — this can take several minutes on a first install.`}/></div>+ )}</div>);}diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsxindex e31c834369..1dcba2bc12 100644--- a/client/src/pages/AIProviders.test.jsx+++ b/client/src/pages/AIProviders.test.jsx@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';import { MemoryRouter, Route, Routes } from 'react-router';const api = vi.hoisted(() => ({@@ -29,6 +29,15 @@ const api = vi.hoisted(() => ({getOrchestrationProfiles: vi.fn().mockResolvedValue({ profiles: [] }),createRun: vi.fn().mockResolvedValue({ runId: 'run-1' }),stopRun: vi.fn().mockResolvedValue({}),+ // The compatibility matrix reads the composition catalog (#7567). Empty by+ // default so the preset list renders exactly as before; the matrix has its+ // own cases below.+ getProviderCatalog: vi.fn().mockResolvedValue({+ harnesses: [], services: [], bootstraps: [], compatibility: {}, effortLevels: {}, effortLevelsByModel: {}, presets: [],+ }),+ createProviderPreset: vi.fn(),+ // The Services view lists instances; empty by default.+ getProviderServices: vi.fn().mockResolvedValue({ services: [] }),}));const localModels = vi.hoisted(() => ({ value: { ctxById: {}, installed: { ollama: null, lmstudio: null } } }));@@ -70,20 +79,29 @@ vi.mock('../components/install/RuntimeInstallModal', () => ({: null,}));-import AIProviders, { PROVIDER_SECTIONS } from './AIProviders';+import AIProviders, { PRESET_STATE_ORDER } from './AIProviders';+import { __resetProviderCatalogCache } from '../hooks/useProviderCatalog';import { CARD_STATE_STYLES } from '../components/providers/ProviderCard';import { PROVIDER_CARD_STATE } from '../utils/providers';-// The editor is route-driven (/ai/new · /ai/edit/:providerId over the same-// page), so the tests mount the real route table rather than a bare page —-// clicking Edit navigates, and a deep link can be rendered directly.-const renderPage = (initialPath = '/ai') => render(+// The editor is route-driven (/ai/presets/new · /ai/presets/:presetId over+// the same page, plus the legacy /ai/edit/:providerId alias), so the tests+// mount the real route table rather than a bare page — clicking Edit+// navigates, and a deep link can be rendered directly. The three views are+// route prefixes of the same page (#7567).+const renderPage = (initialPath = '/ai/presets') => render(<MemoryRouter initialEntries={[initialPath]}><Routes>- <Route path="/ai" element={<AIProviders />} />- <Route path="/ai/new" element={<AIProviders />} />- <Route path="/ai/fleet" element={<AIProviders />} />+ <Route path="/ai/presets" element={<AIProviders />} />+ <Route path="/ai/presets/new" element={<AIProviders />} />+ <Route path="/ai/presets/:presetId" element={<AIProviders />} /><Route path="/ai/edit/:providerId" element={<AIProviders />} />+ <Route path="/ai/fleet" element={<AIProviders />} />+ <Route path="/ai/harnesses" element={<AIProviders />} />+ <Route path="/ai/harnesses/:harnessId" element={<AIProviders />} />+ <Route path="/ai/services" element={<AIProviders />} />+ <Route path="/ai/services/new" element={<AIProviders />} />+ <Route path="/ai/services/:serviceSlug" element={<AIProviders />} /></Routes></MemoryRouter>);@@ -315,7 +333,7 @@ describe('AIProviders page load error handling', () => {renderPage();expect(await screen.findByText('OpenAI')).toBeInTheDocument();- expect(screen.queryByText('No providers configured')).not.toBeInTheDocument();+ expect(screen.queryByText('No presets configured')).not.toBeInTheDocument();expect(screen.queryByText('Failed to load AI providers')).not.toBeInTheDocument();// Demoted to the overflow menu, but still a real anchor so it can be@@ -380,10 +398,10 @@ describe('AIProviders page load error handling', () => {renderPage();- expect(await screen.findByText('No providers configured')).toBeInTheDocument();+ expect(await screen.findByText('No presets 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();+ // With nothing to group, no harness section renders either.+ expect(screen.queryByRole('button', { name: new RegExp('^Claude Code') })).not.toBeInTheDocument();});it('renders Banner with Retry button when api.getProviders rejects and does not show EmptyState', async () => {@@ -393,7 +411,7 @@ describe('AIProviders page load error handling', () => {expect(await screen.findByText('Failed to load AI providers')).toBeInTheDocument();expect(screen.getByRole('button', { name: 'Retry' })).toBeInTheDocument();- expect(screen.queryByText('No providers configured')).not.toBeInTheDocument();+ expect(screen.queryByText('No presets configured')).not.toBeInTheDocument();});it('re-fetches when Retry button is clicked and displays providers upon success', async () => {@@ -413,7 +431,7 @@ describe('AIProviders page load error handling', () => {expect(await screen.findByText('Claude')).toBeInTheDocument();expect(screen.queryByText('Failed to load AI providers')).not.toBeInTheDocument();- expect(screen.queryByText('No providers configured')).not.toBeInTheDocument();+ expect(screen.queryByText('No presets configured')).not.toBeInTheDocument();expect(api.getProviders).toHaveBeenCalledTimes(2);});});@@ -1076,7 +1094,7 @@ describe('Codex subscription text read-risk gate', () => {});it('requires the read-risk acknowledgement before enabling generic text calls', async () => {- renderPage('/ai/edit/codex');+ renderPage('/ai/presets/codex');const acknowledgement = await screen.findByLabelText(/Codex may read local files/i);const enable = screen.getByLabelText(/serve generic text calls/i);@@ -1111,7 +1129,7 @@ describe('Codex subscription text read-risk gate', () => {}],activeProvider: 'codex',});- renderPage('/ai/edit/codex');+ renderPage('/ai/presets/codex');const acknowledgement = await screen.findByLabelText(/Codex may read local files/i);const enable = screen.getByLabelText(/serve generic text calls/i);@@ -1143,14 +1161,14 @@ describe('provider editor deep links', () => {});it('opens the editor for the provider named in the URL', async () => {- renderPage('/ai/edit/codex');+ renderPage('/ai/presets/codex');expect(await screen.findByRole('heading', { name: 'Edit Provider' })).toBeInTheDocument();expect(screen.getByDisplayValue('Codex')).toBeInTheDocument();});it('opens the create form on /ai/new', async () => {- renderPage('/ai/new');+ renderPage('/ai/presets/new');expect(await screen.findByRole('heading', { name: 'Add Provider' })).toBeInTheDocument();expect(screen.getByRole('button', { name: 'Create' })).toBeInTheDocument();@@ -1159,7 +1177,7 @@ describe('provider editor deep links', () => {// A deleted/hand-edited id must bounce back to the list rather than leaving a// blank editor open over it.it('sends an unknown provider id back to the list', async () => {- renderPage('/ai/edit/does-not-exist');+ renderPage('/ai/presets/does-not-exist');await waitFor(() => expect(toast.error).toHaveBeenCalledWith('No provider with id "does-not-exist"'));expect(screen.queryByRole('heading', { name: 'Edit Provider' })).toBeNull();@@ -1168,14 +1186,14 @@ describe('provider editor deep links', () => {// The id comes off the URL, so a prototype key must not resolve to// Object.prototype and open the editor on it.it('does not open the editor for a prototype-chain id', async () => {- renderPage('/ai/edit/__proto__');+ renderPage('/ai/presets/__proto__');await waitFor(() => expect(toast.error).toHaveBeenCalledWith('No provider with id "__proto__"'));expect(screen.queryByRole('heading', { name: 'Edit Provider' })).toBeNull();});it('honors the ?providerTab deep link', async () => {- renderPage('/ai/edit/codex?providerTab=models');+ renderPage('/ai/presets/codex?providerTab=models');expect(await screen.findByLabelText('Default Model')).toBeInTheDocument();expect(screen.getByRole('tab', { name: 'Models' })).toHaveAttribute('aria-selected', 'true');@@ -1184,7 +1202,7 @@ describe('provider editor deep links', () => {// Only the active tab renders, so the browser can't run its own required-field// check for a Save triggered from another tab.it('sends the user back to the field a cross-tab Save left empty', async () => {- renderPage('/ai/edit/codex');+ renderPage('/ai/presets/codex');fireEvent.change(await screen.findByDisplayValue('Codex'), { target: { value: ' ' } });await openEditorTab('Models');@@ -1221,7 +1239,7 @@ describe('provider editor deep links', () => {activeProvider: 'codex',});- renderPage('/ai/edit/codex?providerTab=models');+ renderPage('/ai/presets/codex?providerTab=models');await screen.findByLabelText('Default Model');fireEvent.click(screen.getByRole('button', { name: 'Save' }));@@ -1232,7 +1250,7 @@ describe('provider editor deep links', () => {});it('closes back to the list', async () => {- renderPage('/ai/edit/codex');+ renderPage('/ai/presets/codex');fireEvent.click(await screen.findByRole('button', { name: 'Cancel' }));@@ -1405,7 +1423,7 @@ describe('OpenCode OrcaRouter key hint', () => {});});-describe('readiness grouping', () => {+describe('harness grouping', () => {beforeEach(() => {vi.clearAllMocks();api.getApps.mockResolvedValue([]);@@ -1414,7 +1432,7 @@ describe('readiness grouping', () => {localModels.value = { ctxById: {}, installed: { ollama: null, lmstudio: null } };});- it('sorts each provider into the section its readiness implies', async () => {+ it('groups presets by harness and orders each group by readiness', async () => {api.getProviders.mockResolvedValue({providers: [{ id: 'ready', name: 'Ready CLI', type: 'cli', command: 'claude', enabled: true },@@ -1426,25 +1444,29 @@ describe('readiness grouping', () => {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();+ // Two Claude Code records share one group whatever their readiness; the+ // API record lands under the Direct API harness.+ const claude = await screen.findByRole('button', { name: new RegExp('^Claude Code') });+ expect(claude).toHaveTextContent('2');+ expect(claude).toHaveTextContent('1 of 2 can run');+ expect(screen.getByRole('button', { name: new RegExp('^Direct API') })).toHaveTextContent('0 of 1 can run');+ // Readiness is still on every card as its badge …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();- // "Needs setup" is the only outstanding-task bucket, so it reads before the- // long optional catalog rather than being buried under it. Sections render- // in `PROVIDER_SECTIONS` order, so the array is what pins it.- expect(PROVIDER_SECTIONS.findIndex((s) => s.key === 'blocked'))- .toBeLessThan(PROVIDER_SECTIONS.findIndex((s) => s.key === 'disabled'));+ // … and decides the order within the group: what can run reads first.+ const ready = screen.getByText('Ready CLI');+ const off = screen.getByText('Switched Off');+ expect(ready.compareDocumentPosition(off) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();+ expect(PRESET_STATE_ORDER.indexOf(PROVIDER_CARD_STATE.BLOCKED))+ .toBeLessThan(PRESET_STATE_ORDER.indexOf(PROVIDER_CARD_STATE.DISABLED));});- // "Needs setup" is the outstanding-task list, so only providers the user has- // switched ON belong in it. A switched-off one is optional — it files under- // Disabled and merely notes what enabling it would take.- it('files a switched-off provider with a missing CLI under Disabled, noting the setup', async () => {+ // A switched-off provider is optional — its badge says so and merely notes+ // what enabling it would take, rather than reading as an outstanding task.+ it('badges a switched-off provider with a missing CLI as Disabled, noting the setup', async () => {api.getProviders.mockResolvedValue({providers: [{ id: 'opencode-ollama', name: 'OpenCode Ollama', type: 'cli', command: 'opencode', enabled: false }],activeProvider: null,@@ -1453,7 +1475,7 @@ describe('readiness grouping', () => {renderPage();- expect(await screen.findByRole('button', { name: new RegExp('^Disabled') })).toBeInTheDocument();+ expect(await screen.findByRole('button', { name: new RegExp('^OpenCode') })).toBeInTheDocument();expect(screen.getByText('DISABLED')).toBeInTheDocument();expect(screen.getByText('SETUP TO ENABLE')).toBeInTheDocument();// The missing CLI is still named — that IS the note about enabling it — but@@ -1461,12 +1483,12 @@ describe('readiness grouping', () => {const runtimePill = screen.getByText('OpenCode CLI not installed');expect(runtimePill).toBeInTheDocument();expect(runtimePill.className).not.toMatch(/port-warning/);- expect(screen.queryByRole('button', { name: new RegExp('^Needs setup') })).not.toBeInTheDocument();+ expect(screen.queryByText('NEEDS SETUP')).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 () => {+ it('badges an OrcaRouter wrapper whose sibling was deleted as Needs setup', async () => {api.getProviders.mockResolvedValue({providers: [{id: 'opencode-orcarouter',@@ -1482,7 +1504,6 @@ describe('readiness grouping', () => {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 () => {@@ -1497,12 +1518,12 @@ describe('readiness grouping', () => {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();+ // A benched provider still counts as runnable — nothing is missing on it.+ expect(screen.getByRole('button', { name: new RegExp('^Claude Code') })).toHaveTextContent('1 of 1 can run');+ expect(screen.queryByText('NEEDS SETUP')).not.toBeInTheDocument();});- it('badges a Codex provider whose ChatGPT quota is exhausted as Benched under Enabled', async () => {+ it('badges a Codex provider whose ChatGPT quota is exhausted as Benched, still runnable', async () => {api.getCodexAccount.mockResolvedValue({readiness: {status: 'quota-exhausted',@@ -1524,8 +1545,8 @@ describe('readiness grouping', () => {renderPage();expect(await screen.findByText('BENCHED · usage-limit')).toBeInTheDocument();- expect(screen.getByRole('button', { name: new RegExp('^Enabled') })).toBeInTheDocument();- expect(screen.queryByRole('button', { name: new RegExp('^Needs setup') })).not.toBeInTheDocument();+ expect(screen.getByRole('button', { name: new RegExp('^Codex') })).toHaveTextContent('1 of 1 can run');+ expect(screen.queryByText('NEEDS SETUP')).not.toBeInTheDocument();});it('folds a section away when its header is clicked', async () => {@@ -1536,7 +1557,7 @@ describe('readiness grouping', () => {renderPage();- const header = await screen.findByRole('button', { name: /Disabled/ });+ const header = await screen.findByRole('button', { name: /^Claude Code/ });expect(screen.getByText('Switched Off')).toBeInTheDocument();fireEvent.click(header);@@ -1561,7 +1582,7 @@ describe('hardware-incompatible providers', () => {// A provider this machine cannot run is not a choice the user can act on, so// it must not sit among the enabled cards adding a HARDWARE MISMATCH badge to// a section that otherwise lists live providers.- it('parks an unrunnable provider in a collapsed section instead of Enabled', async () => {+ it('parks an unrunnable provider in a collapsed section instead of its harness group', async () => {api.getProviders.mockResolvedValue({providers: [{ id: 'ok', name: 'Runs Here', type: 'cli', command: 'claude', enabled: true },@@ -1579,9 +1600,11 @@ describe('hardware-incompatible providers', () => {renderPage();- const enabled = await screen.findByRole('button', { name: new RegExp('^Enabled') });- expect(enabled).toHaveTextContent('1');+ const claude = await screen.findByRole('button', { name: new RegExp('^Claude Code') });+ expect(claude).toHaveTextContent('1');expect(screen.getByText('Runs Here')).toBeInTheDocument();+ // The unrunnable API record does not surface as a Direct API group.+ expect(screen.queryByRole('button', { name: new RegExp('^Direct API') })).not.toBeInTheDocument();// Collapsed by default: neither the card nor its badge is on screen.const parked = screen.getByRole('button', { name: /Unavailable on this machine/ });@@ -1657,13 +1680,14 @@ describe('hardware-incompatible providers', () => {});// 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 CARD_STATE_STYLES row and the card throws on `style.border`.+// fails quietly: no PRESET_STATE_ORDER rank sorts those cards to the front of+// every group (indexOf = -1), 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', () => {+ it('gives every readiness state a card style and exactly one rank', () => {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);+ expect(PRESET_STATE_ORDER.filter((rank) => rank === state)).toHaveLength(1);}});});@@ -1995,3 +2019,96 @@ describe('AIProviders model refresh', () => {expect(await screen.findByRole('button', { name: 'Enable' })).toBeInTheDocument();});});++// The compatibility matrix (#7567) is rendered from the composition catalog+// every picker reads, so a cell can only disagree with what compose offers+// by the catalog being stale — never by a second predicate in the browser.+describe('compatibility matrix', () => {+ const catalog = {+ harnesses: [+ { id: 'claude', label: 'Claude Code', modes: ['cli', 'tui'], enabled: true, detected: true },+ { id: 'pi', label: 'Pi', modes: ['cli', 'tui'], enabled: false, detected: false },+ { id: 'direct', label: 'Direct API', modes: ['api'], enabled: true, detected: true },+ ],+ services: [+ { slug: 'ollama', label: 'Ollama', plan: 'local', enabled: true, readiness: 'ready', catalog: { models: ['qwen3:8b'] } },+ { slug: 'nvidia-nim', label: 'NVIDIA NIM', plan: 'free', enabled: true, readiness: 'needs-credential', catalog: { models: [] } },+ ],+ bootstraps: [],+ compatibility: { claude: ['ollama'], pi: ['ollama', 'nvidia-nim'], direct: ['ollama', 'nvidia-nim'] },+ effortLevels: { claude: ['low', 'medium', 'high'], pi: [], direct: [] },+ effortLevelsByModel: {},+ presets: [],+ };++ beforeEach(() => {+ vi.clearAllMocks();+ __resetProviderCatalogCache();+ api.getApps.mockResolvedValue([]);+ api.getProviderStatuses.mockResolvedValue({ providers: {} });+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });+ api.getProviders.mockResolvedValue({ providers: [], activeProvider: null });+ api.getProviderCatalog.mockResolvedValue(catalog);+ });++ it('renders the server verdict per cell: offered, blocked with its reason, or unreachable', async () => {+ renderPage();+ const header = await screen.findByRole('button', { name: /Compatibility matrix/ });+ await waitFor(() => expect(header).toHaveTextContent('2 combinations offered'));+ fireEvent.click(header);+ // Claude × Ollama: compatible, both on, ready → a click target.+ expect(screen.getByRole('button', { name: 'New preset: Claude Code on Ollama' })).toBeInTheDocument();+ // Claude × NVIDIA: not in the compatibility map → unreachable, not blocked.+ expect(screen.getByRole('img', { name: 'Claude Code cannot reach NVIDIA NIM' })).toBeInTheDocument();+ // Pi is switched off → blocked with that reason, even on a ready service.+ expect(screen.getByRole('img', { name: 'Pi on Ollama: Pi is switched off' })).toBeInTheDocument();+ // Direct × NVIDIA: compatible and on, but the service still needs a key.+ expect(screen.getByRole('img', { name: 'Direct API on NVIDIA NIM: NVIDIA NIM needs a credential' })).toBeInTheDocument();+ });++ it('opens the compose flow on the clicked pair with only "Save as preset" as its exit, then lands on the new preset', async () => {+ api.createProviderPreset.mockResolvedValue({ id: 'claude-cli-ollama', name: 'Claude Code · Ollama' });+ renderPage();+ fireEvent.click(await screen.findByRole('button', { name: /Compatibility matrix/ }));+ fireEvent.click(screen.getByRole('button', { name: 'New preset: Claude Code on Ollama' }));++ const dialog = await screen.findByRole('dialog', { name: 'Compose a new preset' });+ expect(within(dialog).getByLabelText('Harness')).toHaveValue('claude');+ expect(within(dialog).getByLabelText('Method')).toHaveValue('cli');+ expect(within(dialog).getByLabelText('Service')).toHaveValue('ollama');+ expect(within(dialog).queryByRole('button', { name: 'Use once' })).not.toBeInTheDocument();++ fireEvent.click(within(dialog).getByRole('button', { name: 'Save as preset…' }));+ fireEvent.click(within(dialog).getByRole('button', { name: 'Confirm save' }));+ await waitFor(() => expect(api.createProviderPreset).toHaveBeenCalledWith(expect.objectContaining({ compositeId: 'claude.cli@ollama' })));+ // The page reloads its presets and opens the editor on the one just saved.+ await waitFor(() => expect(api.getProviders).toHaveBeenCalledTimes(2));+ expect(toast.success).toHaveBeenCalledWith('Claude Code · Ollama saved as a preset');+ });+});++describe('page views', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ __resetProviderCatalogCache();+ api.getApps.mockResolvedValue([]);+ api.getProviderStatuses.mockResolvedValue({ providers: {} });+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });+ api.getProviders.mockResolvedValue({ providers: [], activeProvider: null });+ });++ it('offers the three views as routed tabs and swaps the header action per view', async () => {+ renderPage('/ai/services');+ expect(await screen.findByRole('button', { name: 'Add Service' })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Run Prompt' })).not.toBeInTheDocument();+ const tabs = screen.getByRole('tablist', { name: 'AI provider views' });+ expect(within(tabs).getAllByRole('tab').map((tab) => tab.textContent)).toEqual(['Presets', 'Harnesses', 'Services']);+ fireEvent.click(within(tabs).getByRole('tab', { name: 'Presets' }));+ expect(await screen.findByRole('button', { name: 'Run Prompt' })).toBeInTheDocument();+ // The header action plus the empty state's own — both create a preset.+ expect(screen.getAllByRole('button', { name: 'Add Preset' }).length).toBeGreaterThan(0);+ expect(screen.queryByRole('button', { name: 'Add Service' })).not.toBeInTheDocument();+ });+});diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 0b5749c13d..1ce8e24909 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -53,7 +53,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiPorts.js` | Port scan/detect wrappers (no current UI callers; module kept for the catalog). || `apiHarnesses.js` | Coding-agent harness (CLI/TUI) inventory for Models → Harnesses: installed vs latest version, the providers riding on each, and the model-catalog refresh. Install/update/remove is an SSE stream driven by `RuntimeInstallModal`, not a call here. || `apiModelComparison.js` | Sourced model comparison catalog, provider discovery and validated observation import. |-| `apiProviders.js` | AI provider configuration, plus provider-runtime (CLI) install readiness for the per-card Install buttons, and the Codex / ChatGPT-subscription account calls (`getCodexAccount`, `startCodexLogin`, `cancelCodexLogin`, `codexLogout`) — sign-in STATE only, never a token. Also the connection-graph management calls, including `createProviderConnection` / `createProviderBinding`, which add a backend and mint its (disabled) executable routes. `getProviderCatalog` (`GET /providers/catalog`, #7566) is the composition surface `useProviderCatalog` fetches; `createProviderPreset` (`POST /providers/presets`) is the compose popover's "Save as preset". |+| `apiProviders.js` | AI provider configuration, plus provider-runtime (CLI) install readiness for the per-card Install buttons, and the Codex / ChatGPT-subscription account calls (`getCodexAccount`, `startCodexLogin`, `cancelCodexLogin`, `codexLogout`) — sign-in STATE only, never a token. `getProviderCatalog` (`GET /providers/catalog`, #7566) is the composition surface `useProviderCatalog` fetches; `createProviderPreset` (`POST /providers/presets`) is the compose popover's "Save as preset". The AI Providers page's three axes (#7567): `setProviderHarnessEnabled` (per-harness enablement; the read rides `getProviderCatalog`), `getProviderBootstraps` / `saveProviderBootstraps` (credential-bootstrap apps), and the service-instance calls (`getProviderServiceDefinitions`, `getProviderServices`, `createProviderService`, `updateProviderService`, `deleteProviderService`, `refreshProviderServiceCatalog`) — every response credential-free, and only the explicit catalog refresh contacts a provider. || `apiPrompts.js` | Prompt Manager: stage templates, variables, and job-skill templates (providers list reuses `apiProviders.getProviders`). || `apiReferenceRepos.js` | Per-app reference-repo registry. || `apiReview.js` | Review hub. |diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.jsindex 72839836f6..7288fa33f3 100644--- a/client/src/services/apiProviders.js+++ b/client/src/services/apiProviders.js@@ -52,6 +52,55 @@ export const createProviderPreset = (body, options) => request('/providers/prese...options,});export const testProvider = (id) => request(`/providers/${id}/test`, { method: 'POST' });++// --- the composed axes the AI Providers page manages (#7567, epic #7561) -----+// Harness enablement (the read rides the composition catalog above), services+// (instances of a definition: plan + credential + catalog), and+// credential-bootstrap apps. Every response+// is credential-free: a service reports `hasCredentials` / `credentialSource`,+// never a value. Nothing here contacts a provider except the explicit catalog+// refresh — listing, creating and toggling are local reads and writes.++/** The user's word on one harness. `direct` cannot be switched off; the server refuses it. */+export const setProviderHarnessEnabled = (harnessId, enabled, options) => request(+ `/providers/harnesses/${encodeURIComponent(harnessId)}`,+ { method: 'PUT', body: JSON.stringify({ enabled }), ...options },+);++/** The credential-bootstrap table, keyed by slug — command lines included, for the editor. */+export const getProviderBootstraps = (options) => request('/providers/bootstraps', options);+/** Replace the whole table. Saving never spawns anything. */+export const saveProviderBootstraps = (bootstraps, options) => request('/providers/bootstraps', {+ method: 'PUT', body: JSON.stringify({ bootstraps }), ...options,+});++/** Every `SERVICE_DEFINITIONS` row an "Add service" flow may instantiate. */+export const getProviderServiceDefinitions = (options) => request('/providers/service-definitions', options);+/** Every service instance, sanitized. */+export const getProviderServices = (options) => request('/providers/services', options);+/** Create an instance from a definition. Nothing is probed; the catalog starts `unknown`. */+export const createProviderService = (body, options) => request('/providers/services', {+ method: 'POST', body: JSON.stringify(body), ...options,+});+/**+ * Edit one instance: label, endpoints, credential, plan, enabled. `expectedRevision`+ * is required; a 409 means the row moved. Omit a credential key to preserve it,+ * send `null` to clear it — never send back the redacted placeholder.+ */+export const updateProviderService = (slug, body, options) => request(+ `/providers/services/${encodeURIComponent(slug)}`,+ { method: 'PATCH', body: JSON.stringify(body), ...options },+);+/** Delete an instance no preset uses. Refused with a 409 while one still does. */+export const deleteProviderService = (slug, options) => request(+ `/providers/services/${encodeURIComponent(slug)}`,+ { method: 'DELETE', ...options },+);+/** List the instance's models through its definition's strategy — an explicit discovery request. */+export const refreshProviderServiceCatalog = (slug, options) => request(+ `/providers/services/${encodeURIComponent(slug)}/refresh-catalog`,+ { method: 'POST', ...options },+);export const refreshProviderModels = (id, options) => request(`/providers/${id}/refresh-models`, { method: 'POST', ...options });// Stored model pins naming a model their provider no longer lists (#7315).// Derived on read, so it reflects a pin cleared a moment ago without a refresh.@@ -131,120 +180,3 @@ export const getFleetLlmHost = (options) => request('/providers/fleet-host', optexport const revealFleetLlmHostKey = (options) => request('/providers/fleet-host/key', { method: 'POST', ...options });export const getFleetPeerHosts = (options) => request('/providers/fleet-peer-hosts', options);export const revealFleetPeerHostKey = (peerId, options) => request(`/providers/fleet-peer-hosts/${encodeURIComponent(peerId)}/key`, { method: 'POST', ...options });--// --- provider connection graph management (#6369) -----------------------------// The MANAGEMENT surface, separate from the flat `/providers` execution list-// above. Every response here is credential-free: a connection reports whether-// it `hasCredentials`, never the secret, and no projection snapshot is exposed.--/**- * Whether a failed management call means "this server has no management API"- * rather than "the call failed".- *- * Only two answers count, and both are the server saying so explicitly: a 404- * (an older build with no such route) and the graph's own- * `PROVIDER_GRAPH_UNAVAILABLE` 503. A timeout, a 500 or an offline server is- * NOT an unsupported server — treating it as one would quietly downgrade a- * working install to the legacy view and hide a real outage.- */-export const isManagementUnsupported = (error) =>- error?.status === 404 || error?.code === 'PROVIDER_GRAPH_UNAVAILABLE';--/** The durable graph: connections, harness bindings and executable routes. */-export const getProviderManagementGraph = (options) => request('/providers/management', options);--/**- * Create a new backend. Nothing is probed and no route is minted — a- * connection with no binding is a legitimate row you then attach a harness to.- */-export const createProviderConnection = (body, options) => request('/providers/connections', {- method: 'POST', body: JSON.stringify(body), ...options,-});--/**- * Add a harness to an existing backend, minting one executable route per- * requested mode from that harness's command recipe.- *- * Every minted route arrives DISABLED with no model pins: creating a route is a- * management act, and granting it execution stays a separate, explicit edit on- * the route editor.- */-export const createProviderBinding = (body, options) => request('/providers/bindings', {- method: 'POST', body: JSON.stringify(body), ...options,-});--/** What linking this binding onto another connection would change. Read-only. */-export const previewProviderBindingLink = (bindingId, body, options) => request(- `/providers/bindings/${encodeURIComponent(bindingId)}/link/preview`,- { method: 'POST', body: JSON.stringify(body), ...options },-);--/** Apply a reviewed link. Every revision named in `body` is re-checked server-side. */-export const linkProviderBinding = (bindingId, body, options) => request(- `/providers/bindings/${encodeURIComponent(bindingId)}/link`,- { method: 'POST', body: JSON.stringify(body), ...options },-);--/** Give this binding its own copy of the connection it shares. Route ids are kept. */-export const unlinkProviderBinding = (bindingId, body, options) => request(- `/providers/bindings/${encodeURIComponent(bindingId)}/unlink`,- { method: 'POST', body: JSON.stringify(body ?? {}), ...options },-);--/**- * Edit one shared backend. `expectedRevision` is required; a 409- * `PROVIDER_GRAPH_STALE_REVISION` means the row moved and the edit must be- * re-made against a fresh read. Omit a credential key to preserve it, send- * `null` to clear it — never send back the redacted placeholder.- */-export const updateProviderConnection = (connectionId, body, options) => request(- `/providers/connections/${encodeURIComponent(connectionId)}`,- { method: 'PATCH', body: JSON.stringify(body), ...options },-);--/** Probe the shared model catalog once for every harness on this connection. */-export const refreshProviderConnectionModels = (connectionId, options) => request(- `/providers/connections/${encodeURIComponent(connectionId)}/refresh-models`,- { method: 'POST', ...options },-);--/** Edit a binding's label and the subset of the shared catalog it offers. */-export const updateProviderBinding = (bindingId, body, options) => request(- `/providers/bindings/${encodeURIComponent(bindingId)}`,- { method: 'PATCH', body: JSON.stringify(body), ...options },-);--/** Delete a connection no binding uses. Refused with a 409 while one still does. */-export const deleteProviderConnection = (connectionId, options) => request(- `/providers/connections/${encodeURIComponent(connectionId)}`,- { method: 'DELETE', ...options },-);--/**- * Edit ONE route's mode overrides — args, timeout, effort, model pins.- *- * `expectedRevision` is the route's `settingsRevision` from the management- * graph, a fingerprint of the values on disk: a 409 means somebody (or the- * route editor in another tab) changed them and the edit must be re-made- * against a fresh read. Connection-owned values and the `enabled` flag are not- * reachable here — those stay on the connection and the route editor.- */-export const updateProviderRouteSettings = (providerId, body, options) => request(- `/providers/routes/${encodeURIComponent(providerId)}`,- { method: 'PATCH', body: JSON.stringify(body), ...options },-);--/**- * Edit ONE route's hand-authored canonical→executable model aliases.- *- * The correction surface for a `modelMap` a refresh could only fill with the- * aliases it could verify. `null` for a key removes that override and is the- * only thing that does — a refresh rewrites what it observed in a separate- * column, so a correction survives it. `expectedRevision` is the route's- * `modelAliasRevision` from the management graph; a 409 means the aliases moved- * and the edit must be re-made against a fresh read.- */-export const updateProviderRouteModelAliases = (providerId, body, options) => request(- `/providers/routes/${encodeURIComponent(providerId)}/model-aliases`,- { method: 'PATCH', body: JSON.stringify(body), ...options },-);diff --git a/client/src/test/timeouts.test.js b/client/src/test/timeouts.test.jsindex f5f2587d94..360dbae561 100644--- a/client/src/test/timeouts.test.js+++ b/client/src/test/timeouts.test.js@@ -23,7 +23,7 @@ const TIMEOUT_KEY = /(?:^|,)\s*timeout:\s*([\d_]+)\s*(?:,|$)/;* Every option `waitFor` / `findBy*` accept. An object whose keys are all in* here is an async bound; one carrying anything else is fixture data that* happens to hold a `timeout` field (`src/utils/providers.test.js` has- * `{ id, timeout }`, `ProviderConnections.test.jsx` has `{ args, timeout, … }`).+ * `{ id, timeout }`).*/const WAIT_FOR_OPTIONS = new Set(['timeout', 'interval', 'onTimeout', 'container', 'mutationObserverOptions',diff --git a/client/src/utils/providerHarnesses.js b/client/src/utils/providerHarnesses.jsindex 91bb9b6914..2ffce144fd 100644--- a/client/src/utils/providerHarnesses.js+++ b/client/src/utils/providerHarnesses.js@@ -29,6 +29,17 @@ export const harnessLabel = (harnessId) => {return harnessById(harnessId)?.label || harnessId;};+/**+ * Where a preset is edited (#7567): `/ai/presets/:presetId`. Preset ids are+ * slugified from the display name, so a preset named "New" gets the id `new`+ * and would be shadowed by the static `/ai/presets/new` create route — that+ * one record keeps the legacy `/ai/edit/:providerId` alias, which App.jsx+ * serves as a working route for exactly this reason.+ */+export const presetEditPath = (presetId) => (+ presetId === 'new' ? '/ai/edit/new' : `/ai/presets/${encodeURIComponent(presetId)}`+);+/** The group a preset with no recognizable harness lands in. */export const OTHER_HARNESS_GROUP = 'other';diff --git a/docs/AI_PROVIDERS.md b/docs/AI_PROVIDERS.mdnew file mode 100644index 0000000000..14b466279f--- /dev/null+++ b/docs/AI_PROVIDERS.md@@ -0,0 +1,51 @@+# AI Providers — harnesses, services, presets++**Models → Providers** (`/ai`) is where PortOS decides how an AI run is composed. A run is five independent choices, and the page is three views over them (epic #7561, page reshape #7567):++```+Harness × Method × Service × Model × Effort+```++| Axis | What it is | Where it lives |+|---|---|---|+| **Harness** | The program that drives a model: Claude Code, OpenCode, Codex, Antigravity, Cursor, Grok, Kimi, Pi, … and `direct` — PortOS's own HTTP runner. | `PROVIDER_HARNESSES` (`server/lib/providerHarnesses.js`); per-install enablement in `settings.harnesses` |+| **Method** | How the harness is driven: `cli` (headless), `tui` (a PTY the agent runner attaches to), or `api` (the `direct` harness's only method). | Declared per harness (`modes`) |+| **Service** | The backend a harness is pointed at — a hosted API you hold a key for, a local runtime daemon, a subscription the harness signs into, or a fleet peer's gateway. An **instance** is a definition plus the **plan** you declared (`free` / `paid` / `subscription` / `local`), a credential, and the model catalog it last listed. | Definitions in `server/lib/serviceDefinitions.js`; instances are `ai_connections` rows (`docs/STORAGE.md`) |+| **Model** | One entry of the service's catalog, narrowed by its plan. | The instance's `catalog` |+| **Effort** | The reasoning budget, on the harness's ladder (and per model where a model narrows it). | `effortLevels` / `effortLevelsByModel` in the catalog |++Any **compatible** combination of enabled parts is runnable without a stored record: `pi.tui@nvidia-nim-free`, `direct.api@ollama`, `claude.cli@anthropic+corp-auth`. The grammar, the resolver, and which surfaces accept a composite id are in [PROVIDER_COMPOSITION.md](./PROVIDER_COMPOSITION.md). A **preset** is a *named* combination — the stored `data/providers.json` record every `{ providerId, model, effort }` picker has always selected — and every picker stays one dropdown of presets with a "Custom…" step that opens the compose flow.++## The three views++### Presets (`/ai/presets`)++The stored records, **grouped by harness** and ordered within a group by readiness (what can run first, what you switched on but cannot run yet second, what is switched off last). Readiness is still on every card as its color and badge; it no longer decides which section a card lands in. A record this machine's hardware cannot run is parked in a collapsed *Unavailable on this machine* section — kept, because the file is shared with your other machines.++- **Compatibility matrix** — harness rows × service columns, each cell the server's verdict on that pair (`GET /api/providers/catalog`, nothing recomputed in the browser): **offered** (click for a prefilled "New preset"), **blocked** with its reason (a side switched off, a missing key or endpoint), or **unreachable**.+- **Compose custom preset…** (overflow menu) — the same compose flow every picker offers, with "Save as preset" as its only exit.+- **Add Preset** — a hand-written legacy record, for a backend no definition describes.+- The preset editor (`/ai/presets/:presetId`; `/ai/edit/:providerId` is a kept alias) shows a **derived** preset's connection-owned fields — type, command, endpoint, key, inline bootstrap — as *Derived from service …* with a link to the service, because the server re-materializes them from that service on every save and refuses an edit that would move one. Name, arguments, timeouts, model pins, effort and generation settings stay the preset's own. A **legacy** preset is fully hand-editable, as before, and offers *Convert to derived preset* when re-deriving it would change nothing about how it runs.+- **Tiers** (Light / Medium / Heavy / Ultra, [MODEL_TIERS.md](./MODEL_TIERS.md)) are pins on a preset, so a `model: "heavy"` selection resolves on whichever preset the task names.++### Harnesses (`/ai/harnesses`)++One card per registry harness: the **enable switch** (the user's word; a harness with no word follows whether its binary is detected on PATH; `direct` is always on), the detected version, the methods it runs, how many switched-on services it can reach, and the install a missing binary needs. Updates, removal and the harness's own model listing stay on Models → Harnesses. A toggle here is one write plus a catalog invalidation, so an open picker's compose flow reflects it without a reload.++**Credential bootstraps** sits under the cards, collapsed until one exists: the launch wrappers a composite's `+<slug>` suffix names (`<command> <args…> <harness-name> [<separator>] <harness args>`), with the per-harness name map a wrapper may use (`claude` → `claude-code`). Saving never spawns anything; the wrapper runs only when a composite naming it executes.++### Services (`/ai/services`)++One card per instance: definition, plan badge, readiness (*Ready*, *Needs a credential*, *Needs an endpoint*, *Switched off*), where its credential comes from (stored here, the environment, the install `.env`, the harness's own sign-in, or a bootstrap wrapper) with a *Get a key* link for a keyed vendor still waiting on one, its endpoints, and its catalog state. **Refresh catalog** is the one action on this page that contacts a provider, and it is never run on mount, on toggle, or on display (root `AGENTS.md`, AI Provider Usage Policy) — it lists the instance's models through its definition's strategy (probe the endpoint, ask the daemon, ask the program that signs in, or the declared list) and filters them to the plan, then re-derives every preset on the instance.++**Add Service** walks definition → plan → credential / endpoint. A subscription needs neither (the harness signs in); a hosted API takes a key you store, a conventional environment variable, or a bootstrap wrapper; a local runtime needs the endpoint this install reaches it at. A service still named by a preset cannot be deleted.++This view is what the Backend Connections drawer (#6369) used to be — a connection *is* a service instance, addressed by the same UUID or slug, so `/ai/connections/:id` redirects here. What it no longer offers is binding link/unlink and per-route rows: a preset names its service outright (`serviceId`), and a preset's own settings live on its editor.++## Reaching the views++Every view and every open card is a URL — `/ai/harnesses/:harnessId`, `/ai/services/:serviceSlug`, `/ai/presets/:presetId` — reachable from ⌘K and voice ("AI presets", "AI harnesses", "AI services"; `server/lib/navManifest.js`). `/ai`, `/ai/new`, `/ai/connections[/:id]` and `/ai/harnesses/:id/connections[/:id]` redirect to their current homes.++## What federates++Nothing on this page. Harness enablement, bootstrap apps, service instances (endpoints, credentials, catalogs) and presets are machine-local: an `ai_connections` row carries this host's execution environment and credential material (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)), and `settings.harnesses` / `settings.credentialBootstraps` describe binaries on this host. A CoS task's `metadata.provider` crosses to a peer verbatim; a peer with no preset or service under that id reports it unresolved rather than substituting another.diff --git a/docs/API.md b/docs/API.mdindex f9d24a29b3..e4d95e4d48 100644--- a/docs/API.md+++ b/docs/API.md@@ -124,6 +124,7 @@ legacy list for local Apps/Dashboard views.| POST | `/providers/:id/modes/tui` | Give an EXISTING CLI provider the TUI half of its harness, minted from the record already on disk — the other end of the dual-mode create above, for an install that already has a lone `claude` or `opencode` CLI record. A new endpoint rather than a flag on `PUT /providers/:id`, because `modes` is create-only: a PATCH against one record cannot mean "make me two". No request body: the command, endpoint, credentials and env come from `:id` (retyping them is both friction and a fresh chance for a grouped field to differ and leave two unrelated routes), and the argv defaults from the harness recipe’s proven interactive line, or stays empty for a binary PortOS has no row for. Answers the created record; `GET /providers` flags eligible records with `canAddTuiMode` so a card only ever offers what this accepts. Refuses a non-CLI record, a record storing no command, and a known harness declaring no TUI mode (400); a taken `<id>-tui` answers 409 and writes nothing — the CLI id is already fixed, so something else is standing there. || POST | `/providers/:id/test` | Test provider connectivity || PUT | `/providers/active` | Set active provider |+| GET | `/providers/service-definitions` | Every `SERVICE_DEFINITIONS` row an "Add service" flow may instantiate (#7567): id, label, family, plans, catalog strategy, transports with their default base URLs, and where a key is obtained (`keyUrl`, conventional `envVars`). Code-only data — no instance, no credential. The instance surface is `/providers/services*` (`docs/PROVIDER_COMPOSITION.md`). || GET | `/providers/runtimes` | Per-runtime install status (`claude`, `codex`, `opencode`, `kilo`, `openchamber`, `grok`, `kimi`, `agy`, `cursor-agent`): is the binary runnable here, and can PortOS install it? Booleans and labels only — never resolved filesystem paths. 60s TTL cache. Ollama / LM Studio are absent on purpose — Models → LLMs owns their install. || POST | `/providers/runtimes/install?runtime=<id>` | Install one runtime from the installer's fixed table, streaming installer output as SSE. Rejects any id not in the table. || GET | `/providers/readiness` | Requirements checklist per provider backed by a LOCAL daemon (llama.cpp / Ollama / LM Studio / MTPLX), keyed by provider id: is the daemon installed, is it answering at the endpoint THIS provider points at, and is it serving the provider's default model. Each entry also carries `setup` — what the one-click fix below can do about the unmet checks (`null` when nothing is auto-fixable here). Each entry also carries `contextWindows` — what the daemon is SERVING right now, keyed by every spelling the provider could dispatch under, or `null` when it is down or silent about them; the provider card budgets its meter with it so the number matches what the pre-dispatch gate enforces, and it is never written back to the stored provider record. Providers with no local dependency are absent from the map. Complements `/providers/runtimes` (which answers "can PortOS run this CLI?"). Booleans, labels, and the provider's own endpoint only — never a resolved binary path. Skips disabled providers; 15s endpoint-probe cache (one probe per distinct endpoint), 60s binary-PATH cache, both dropped by the llama-server start/stop/install routes. |diff --git a/docs/MODEL_ACCESS.md b/docs/MODEL_ACCESS.mdindex ac2abe0a5d..56ce057691 100644--- a/docs/MODEL_ACCESS.md+++ b/docs/MODEL_ACCESS.md@@ -21,7 +21,7 @@ PortOS cannot detect it. It is declared instead, per provider, in| `deny` | Everything except models matching the pattern list. |Once set, the scope applies to **every model picker in PortOS** — provider cards,-the Settings > AI assignment page, the Backend Connections model menus, CoS agent+the Settings > AI assignment page, the AI Providers → Services catalog summaries, CoS agentand task pickers, pipeline stage pickers, reviewer model selection — and to the**model comparison chart**, whose default pills and coverage list are built fromthe models your providers can dispatch.diff --git a/docs/MODEL_TIERS.md b/docs/MODEL_TIERS.mdindex 389713f601..399ac3a5b5 100644--- a/docs/MODEL_TIERS.md+++ b/docs/MODEL_TIERS.md@@ -1,10 +1,13 @@# AI provider model tiers-Tiers are active routing configuration, not display-only labels. Each provider maps+Tiers are active routing configuration, not display-only labels. Each **preset**+(a stored provider record — see [AI_PROVIDERS.md](./AI_PROVIDERS.md)) mapsLight (mechanical work), Medium (routine work), Heavy (complex work), and Ultra-(exceptional frontier reasoning) to its own model. Configure them in Models →-Providers. Astra and Fable are examples of Ultra choices; use a model supported-by the selected provider and account.+(exceptional frontier reasoning) to its own model. Tiers live on presets, not on+harnesses or services: configure them in Models → Providers → Presets, on the+preset's editor, and a tier name resolves on whichever preset a task names. Astra+and Fable are examples of Ultra choices; use a model supported by the selected+preset's service and plan.CoS selects Light/Heavy from task heuristics and can learn tier preferences fromoutcomes. Explicit thinking levels have their own routing precedence. Promptdiff --git a/docs/PROVIDER_COMPOSITION.md b/docs/PROVIDER_COMPOSITION.mdindex d6245d7b2a..eb7ff19768 100644--- a/docs/PROVIDER_COMPOSITION.md+++ b/docs/PROVIDER_COMPOSITION.md@@ -55,7 +55,7 @@ Fallback selection admits a composite only where a stored candidate would be adm| `GET /api/providers/composites/:id` | One composite's verdict and sanitized record || `GET /api/providers/readiness?providerId=<composite>` | Readiness for one composition |-`GET /api/providers` stays presets-only, so existing consumers are unaffected until the UI slices of the epic (#7561) land; each record now also carries its preset structure (see **Presets**).+`GET /api/providers` stays presets-only, so existing consumers are unaffected; each record now also carries its preset structure (see **Presets**). The management surface over these axes is the AI Providers page — [AI_PROVIDERS.md](./AI_PROVIDERS.md) (#7567). `GET /api/providers/service-definitions` lists every definition an instance can be created from, with its plans, transports (and default base URLs) and where a key is obtained.## Presetsdiff --git a/docs/README.md b/docs/README.mdindex b814ab6362..a0aff24dbb 100644--- a/docs/README.md+++ b/docs/README.md@@ -21,6 +21,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo| [INSTANCE_FEATURES.md](./INSTANCE_FEATURES.md) | Optional per-install features — registry, client-side nav gating, feature groups, reconcile-at-toggle || [PM2.md](./PM2.md) | Recommended PM2 ecosystem patterns for sub-projects || [QUOTA-BURN.md](./QUOTA-BURN.md) | Quota-burn automation — spending subscription-backed CLI quota before expiry |+| [AI_PROVIDERS.md](./AI_PROVIDERS.md) | The AI Providers page: a run composed from Harness × Method × Service × Model × Effort, its Presets / Harnesses / Services views, compatibility matrix, derived vs legacy presets, and what federates (nothing) || [PROVIDER_COMPOSITION.md](./PROVIDER_COMPOSITION.md) | Composite provider ids (`harness.method@service[+bootstrap]`): the grammar, per-harness enablement, bootstrap apps, how every run path resolves one, and the preset-only surfaces || [MODEL_ACCESS.md](./MODEL_ACCESS.md) | Scoping a provider to the models your plan entitles you to — free tiers, allow/deny globs, gateway inheritance || [MODEL-COMPARISON.md](./MODEL-COMPARISON.md) | Sourced provider/model/effort comparisons, cost estimates and CoS research refresh |diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex df01a95f7e..67effa932b 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -44,7 +44,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- `games` — Game studio workspaces (#3177): one row per managed-app asset plan, with the full reusable sprite/music binding set, current compiled-manifest pointer, compile history, and user-requested AI feedback history in `data` JSONB; `app_id`/`name`/`updated_at` are mirrored for list and relationship queries. The record is **machine-local** because managed-app registration, sprite atlases, and music-library bytes are machine-local; there is no peer-sync cursor or tombstone, and deletes are hard deletes. Compiled manifests are immutable, SHA-256-addressed artifacts under `data/games/{id}/manifests/`; their pointers and hashes live in the DB record. Adapter: `server/services/games/db.js`, selected pg-vs-collectionStore by `server/services/games/store.js` (collectionStore is test/unsupported file escape hatch only).- `fableloom_stories` — FableLoom branching narratives: one row per loom (a branching-narrative story), with episodes, scene-node graphs, and intent transitions in `data` JSONB; `name`/`universe_id`/`series_id`/`updated_at` are mirrored for list and relationship queries (both refs are soft — no FK). `db-primary` because looms relate to universes and series and the index queries by recency. Federates through the opt-in per-record `fableLoom` category: whole-record LWW merges carry soft-delete tombstones, conflict-journal recovery, and hashed manifests for scene images/videos; there is no snapshot cursor or `sync_sequence`. Adapter: `server/services/fableLoom/db.js`, selected pg-vs-collectionStore by `server/services/fableLoom/store.js` (collectionStore is the test/unsupported file escape hatch only). Feature doc: [FableLoom](./features/fableloom.md).- `threejs_models` — generated procedural 3D-model workspaces: one row per model with gallery-image lineage, provider/model attribution, generation/refinement status, and the validated declarative scene spec in `data` JSONB. The referenced image bytes remain under `data/images/`; deterministic Three.js source is derived from the stored spec rather than persisted as a second mutable artifact. The table is local-only in this first slice, with soft-delete columns retained so federation can be added without a record-shape migration.-- `ai_connections` / `ai_harness_bindings` / `ai_route_bindings` — the AI provider connection graph (#6367, design record [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md)): the backend a harness talks to, each harness configuration bound to it, and the executable route each one projects. `db-primary` because it is a real graph — a connection has many bindings, a binding has one route per mode, and the uniqueness rules (`UNIQUE(binding_id, mode)`, `UNIQUE(connection_id, harness_id, variant_key)` plus a partial index for null-harness API bindings) are integrity constraints a set of JSON files cannot hold. `data/providers.json` REMAINS the execution contract and stays fully materialized: every connection-owned value is projected back into it, so a downgraded release runs unchanged with these tables simply idle. **Intentionally machine-local — never federated**: rows carry endpoints, credential material and this host's execution environment (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)). No `sync_sequence`, no tombstones, no `PORTOS_SCHEMA_VERSIONS` entry, no `dataSync` category; deletes are hard deletes and are refused while a binding still references the row. `ai_route_bindings.projected` / `.pending` are the projection snapshots that make an interrupted file write recoverable — as private as the credentials, and covered by the Postgres dump like every other db-primary table. Adapters: `server/services/providerGraphStore.js` (rows) and `server/services/providerGraph.js` (import, reconciliation, link/unlink), over the pure `server/lib/providerGraphRecords.js`. Since #7563 an `ai_connections` row is also one SERVICE INSTANCE of a `server/lib/serviceDefinitions.js` entry: additive `slug` (unique, the address a composite provider id will carry), `definition_id`, `plan` (`free` / `paid` / `subscription` / `local`), `enabled` and `credential_via` (`stored` / `env` / `cli-login` / `bootstrap` — only `stored` holds a secret), with `catalog` gaining optional per-model `capabilities` and `refreshedAt`. The columns are backfilled from `kind` by the boot reconcile pass (`planServiceColumnBackfill` in `server/lib/providerServiceInstances.js`) — derived from the install's own rows, never seeded, idempotent — and managed through `server/services/providerServices.js` (`/api/providers/services*`), which refreshes a catalog through the definition's listing strategy without needing an executable route. Since #7565 a `data/providers.json` record may name the instance it is DERIVED from (`harnessId` / `method` / `serviceId`, plus `catalogNarrowing` and `credentialBootstrapId`): its connection-owned values are re-materialized from that row on every save and on every service edit, while the file stays the fully materialized execution contract — an older release runs the record unchanged and its schema strips the keys it never saw. The stamping of existing records rides the same boot reconcile pass (`planPresetBackfill` in `server/lib/providerPresets.js`), additive and idempotent; see `docs/PROVIDER_COMPOSITION.md` § Presets.+- `ai_connections` / `ai_harness_bindings` / `ai_route_bindings` — AI **services** (instances a harness is pointed at) and the graph the **presets** derived from them are projected through (#6367 → #7561; user guide [AI_PROVIDERS.md](./AI_PROVIDERS.md), design record [provider connections and harnesses](./plans/2026-09-06-provider-connections-and-harnesses.md)): the backend a harness talks to, each harness configuration bound to it, and the executable route each one projects. `db-primary` because it is a real graph — a connection has many bindings, a binding has one route per mode, and the uniqueness rules (`UNIQUE(binding_id, mode)`, `UNIQUE(connection_id, harness_id, variant_key)` plus a partial index for null-harness API bindings) are integrity constraints a set of JSON files cannot hold. `data/providers.json` REMAINS the execution contract and stays fully materialized: every connection-owned value is projected back into it, so a downgraded release runs unchanged with these tables simply idle. **Intentionally machine-local — never federated**: rows carry endpoints, credential material and this host's execution environment (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md)). No `sync_sequence`, no tombstones, no `PORTOS_SCHEMA_VERSIONS` entry, no `dataSync` category; deletes are hard deletes and are refused while a binding still references the row. `ai_route_bindings.projected` / `.pending` are the projection snapshots that make an interrupted file write recoverable — as private as the credentials, and covered by the Postgres dump like every other db-primary table. Adapters: `server/services/providerGraphStore.js` (rows) and `server/services/providerGraph.js` (import, reconciliation, link/unlink), over the pure `server/lib/providerGraphRecords.js`. Since #7563 an `ai_connections` row is also one SERVICE INSTANCE of a `server/lib/serviceDefinitions.js` entry: additive `slug` (unique, the address a composite provider id will carry), `definition_id`, `plan` (`free` / `paid` / `subscription` / `local`), `enabled` and `credential_via` (`stored` / `env` / `cli-login` / `bootstrap` — only `stored` holds a secret), with `catalog` gaining optional per-model `capabilities` and `refreshedAt`. The columns are backfilled from `kind` by the boot reconcile pass (`planServiceColumnBackfill` in `server/lib/providerServiceInstances.js`) — derived from the install's own rows, never seeded, idempotent — and managed through `server/services/providerServices.js` (`/api/providers/services*`), which refreshes a catalog through the definition's listing strategy without needing an executable route. Since #7565 a `data/providers.json` record may name the instance it is DERIVED from (`harnessId` / `method` / `serviceId`, plus `catalogNarrowing` and `credentialBootstrapId`): its connection-owned values are re-materialized from that row on every save and on every service edit, while the file stays the fully materialized execution contract — an older release runs the record unchanged and its schema strips the keys it never saw. The stamping of existing records rides the same boot reconcile pass (`planPresetBackfill` in `server/lib/providerPresets.js`), additive and idempotent; see `docs/PROVIDER_COMPOSITION.md` § Presets.- `privacy_subjects` / `privacy_vault_records` / `privacy_consents` / `privacy_orgs` / `privacy_org_holdings` / `privacy_change_events` / `privacy_brokers` / `privacy_broker_cases` — the Privacy Center (epic #2138): the household subjects the suite works on behalf of (`self` plus consenting partners/children/parents — every other table carries a `subject_id` FK defaulted to the seeded `self` row, #3658), the encrypted PII vault, the trusted-organization registry with per-field holdings, the change-of-address inventory, and the data-broker opt-out ledger. Relational by nature (org ↔ holdings ↔ vault records ↔ change events ↔ broker cases), which is why they are `db-primary`. Vault *values* are AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`, key from `PRIVACY_VAULT_KEY`) — the DB holds bytes of ciphertext, never plaintext PII, and plaintext never appears in logs (`server/lib/vaultCrypto.js`). **Intentionally machine-local — never federated**, and this is a product *guarantee*, not a deferred feature (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), #2148). NO `sync_sequence`, NO peer-sync record kind, NO `dataSync` category, NO `PORTOS_SCHEMA_VERSIONS` entry, and no `deleted`/`deleted_at` tombstones — deletes are hard deletes, mirroring `tribe`. The reasoning is the same class as the Tribe graph but stronger: the peer-sync **pull** path (`GET /api/peer-sync/record`) carries no peer identity, `masked_value` is plaintext by design so even ciphertext-only sync would leak a PII fingerprint, and a shared `PRIVACY_VAULT_KEY` would widen the at-rest blast radius to every peer's `.env`. A second machine gets the vault by restoring a backup and copying the key by hand — a deliberate act, not continuous replication. Enforced by `server/services/sharing/privacyNeverFederates.test.js`. Adapters: `server/services/privacySubjects.js`, `privacyVault.js`, `privacyOrgs.js`, `privacyChanges.js`, `privacyBrokers.js`, `privacyOptOut.js`.**Postgres-First target.** Pipeline series/issues, Story Builder sessions, and searchable media metadata are still `db-primary` targets — they currently live in `data/` JSON but carry relationships and status that belong in the DB. The schema for the Create domains is designed in [`docs/plans/2026-06-07-create-relational-schema-design.md`](./plans/2026-06-07-create-relational-schema-design.md) (#999), with implementation tracked as #1014–#1018. (Creative Director project/scene/run state moved to Postgres in Phase 3 / #997; catalog user-defined types moved in Phase 4 lead-in / #1001; **universes moved in Phase 3 Create slice 1 / #1014** — see the `universes` entry above. Pipeline series/issues #1015, Story Builder #1016, Writers Room #1017, and the catalog ref resolver #1018 are the remaining slices.)diff --git a/docs/features/claude-ollama.md b/docs/features/claude-ollama.mdindex 91f2855ccc..52595e3379 100644--- a/docs/features/claude-ollama.md+++ b/docs/features/claude-ollama.md@@ -10,6 +10,15 @@ variants:(`claude --dangerously-skip-permissions`), the interactive harness CoS agentsdrive in TUI mode.+> **Since #7561 this is a preset example.** Claude Ollama is what the composed model+> calls `claude.cli@ollama` / `claude.tui@ollama`: the Claude Code **harness**+> pointed at the Ollama **service** instance. The shipped records below are+> **presets** of that pair, derived from the Ollama service where the boot+> backfill can prove it, so editing the service's endpoint reaches both. Any+> other enabled harness × service pair is composed the same way — see+> [AI_PROVIDERS.md](../AI_PROVIDERS.md). The rest of this page still describes+> how the pair works and how to set it up.+## Why a special provider?PortOS has two provider classes:diff --git a/docs/plans/2026-09-06-provider-connections-and-harnesses.md b/docs/plans/2026-09-06-provider-connections-and-harnesses.mdindex a8060fed2f..44bf8af4b6 100644--- a/docs/plans/2026-09-06-provider-connections-and-harnesses.md+++ b/docs/plans/2026-09-06-provider-connections-and-harnesses.md@@ -2,6 +2,15 @@Status: proposed implementation decision for #6359; this PR changes documentation only.+> **Superseded by epic #7561** (Harness × Method × Service × Model × Effort). The+> durable graph this record introduced stays the persistence layer, but records+> are no longer authoritative over it: a run is composed from enabled parts, an+> `ai_connections` row is a **service instance** with its own plan and catalog,+> a stored record is a **preset** derived from one, and the Backend Connections+> drawer became the Services view of the AI Providers page (#7567). Current+> contract: [PROVIDER_COMPOSITION.md](../PROVIDER_COMPOSITION.md) and+> [AI_PROVIDERS.md](../AI_PROVIDERS.md).+## Decision and scopeIntroduce durable, machine-local connection and harness-binding IDs for management,diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex 169bf20b53..5267077e93 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -89,8 +89,15 @@ const RAW_NAV_COMMANDS = [{ id: 'nav.writers-room', path: '/writers-room', label: 'Writers Room', section: 'Create', aliases: ['writers-room', 'writersroom', 'writer', 'write', 'studio', 'novel'], keywords: ['prose', 'screenplay', 'story', 'draft', 'manuscript', 'literary', 'novel', 'short story'] },{ id: 'nav.writers-room.guide', path: '/writers-room/guide', label: 'Writers Room Guide', section: 'Create', aliases: ['writers-room-guide', 'writing-guide', 'writing-rules', 'word-count', 'length-targets'], keywords: ['microfiction', 'flash fiction', 'short story', 'novelette', 'novella', 'novel length', 'word count', 'character count', 'book length', 'craft', 'writing advice', 'emotional roadmap', 'documentation', 'help'] },{ id: 'nav.settings.prompts', path: '/prompts', label: 'Prompts', section: 'Settings', tabId: 'prompts', aliases: ['prompts'] },- { id: 'nav.settings.providers', path: '/ai', label: 'Providers', section: 'Models', tabId: 'providers', aliases: ['providers', 'ai-providers'] },- { id: 'nav.settings.connections', path: '/ai/connections', label: 'Backend Connections', section: 'Models', aliases: ['connections', 'backend-connections', 'provider-connections', 'harness-connections'], keywords: ['endpoint', 'shared backend', 'link', 'unlink', 'model catalog', 'ollama', 'api key'] },+ // The AI Providers page is three views over the composed model (#7567, epic+ // #7561): Presets (the stored records, the page's index), Harnesses (the+ // programs and their enablement, plus credential-bootstrap apps) and Services+ // (instances of a service definition: plan, credential, catalog). Each is its+ // own URL so a card can be linked and reached from ⌘K and voice; the retired+ // Backend Connections drawer (#6369) redirects onto Services.+ { id: 'nav.settings.providers', path: '/ai/presets', label: 'Providers', section: 'Models', tabId: 'providers', previousPaths: ['/ai'], aliases: ['providers', 'ai-providers', 'presets', 'ai-presets', 'provider-presets'], keywords: ['preset', 'harness', 'service', 'model', 'effort', 'compose', 'compatibility matrix', 'default provider'] },+ { id: 'nav.ai.harnesses', path: '/ai/harnesses', label: 'AI Harnesses', section: 'Models', aliases: ['ai-harnesses', 'provider-harnesses', 'harness-enablement', 'credential-bootstraps', 'bootstraps'], keywords: ['enable harness', 'disable harness', 'claude code', 'codex', 'opencode', 'pi', 'direct api', 'cli', 'tui', 'bootstrap', 'launch wrapper', 'sign in', 'quota'] },+ { id: 'nav.ai.services', path: '/ai/services', label: 'AI Services', section: 'Models', previousPaths: ['/ai/connections', '/ai/connections/:connectionId'], aliases: ['ai-services', 'services', 'provider-services', 'backends', 'connections', 'backend-connections', 'provider-connections', 'harness-connections'], keywords: ['endpoint', 'api key', 'plan', 'free', 'paid', 'subscription', 'model catalog', 'refresh catalog', 'ollama', 'nvidia', 'openrouter', 'add service'] },{ id: 'nav.settings.fleet-llm', path: '/ai/fleet', label: 'Fleet LLM Setup', section: 'Settings', aliases: ['fleet-llm', 'gpu-host', 'remote-ai-provider'], keywords: ['3090', 'tailscale', 'vllm', 'qwen', 'coding model', 'dedicated host'] },{ id: 'nav.brain.inbox', path: '/brain/inbox', label: 'Inbox', section: 'Brain', tabGroup: 'brain', tabId: 'inbox', aliases: ['brain', 'brain-inbox', 'inbox'] },diff --git a/server/lib/navManifest.test.js b/server/lib/navManifest.test.jsindex b90d9d96d9..1f1abd6deb 100644--- a/server/lib/navManifest.test.js+++ b/server/lib/navManifest.test.js@@ -157,16 +157,16 @@ describe('nav contract — generated section child navigation', () => {it('keeps moved Providers and Usage destinations in the Models child nav', () => {expect(getSectionNavTabs('Models').filter((tab) => ['providers', 'usage'].includes(tab.id))).toEqual([- { id: 'providers', label: 'Providers', to: '/ai' },+ { id: 'providers', label: 'Providers', to: '/ai/presets' },{ id: 'usage', label: 'Usage', to: '/devtools/usage' },]);expect(getSectionNavTabs('Settings').some((tab) => tab.id === 'providers')).toBe(false);});it.each([- ['/ai', 'Models'],- ['/ai/edit/example-provider', 'Models'],- ['/ai/fleet', 'Models'],+ ['/ai/presets', 'Models'],+ ['/ai/presets/example-provider', 'Models'],+ ['/ai/presets/new', 'Models'],['/devtools/usage', 'Models'],['/models/llms/abuse', 'Models'],['/models/llms-runtimes', 'Models'],@@ -560,7 +560,8 @@ const SOCKET_JS = path.join(REPO_ROOT, 'client/src/services/socket.js');// not from ⌘K / voice / the sidebar.const NAV_COVERAGE_OPT_OUT = new Map([['/*', 'catch-all 404 page — reached only by an unmatched URL, never a destination'],- ['/ai/new', 'create-provider drawer, reached via the "Add Provider" button on /ai'],+ ['/ai/presets/new', 'create-preset drawer, reached via the "Add preset" button on /ai/presets'],+ ['/ai/services/new', 'add-service drawer, reached via the "Add service" button on /ai/services'],['/apps/create', 'create-app form, reached via the "New App" button on /apps'],['/creative-commission/new', 'create-commission drawer, reached via the "New Commission" button on /creative-commission'],['/feature-agents/create', 'create-agent form, reached via the "New Agent" button'],@@ -761,6 +762,11 @@ describe('nav coverage — every navigable App.jsx route has a manifest entry',// The dataset workbench was its own deep-linkable path, and a bookmark into// one dataset breaks just as silently as the index.'/media/training/:datasetId',+ // #7567 — /ai became /ai/presets and the Backend Connections drawer+ // became the Services view; a stored pin or bookmark on either must land.+ '/ai',+ '/ai/connections',+ '/ai/connections/:connectionId',// The rest of the moves App.jsx already redirected but nothing declared.// A pinned sidebar row is a STORED route path, so an undeclared move made// the pin stop resolving and vanish on the next update — the client readsdiff --git a/server/lib/providerServiceInstances.js b/server/lib/providerServiceInstances.jsindex cd628bb4fa..32a313bd17 100644--- a/server/lib/providerServiceInstances.js+++ b/server/lib/providerServiceInstances.js@@ -244,8 +244,37 @@ const definitionDtoSchema = z.object({plans: z.array(z.enum(SERVICE_PLANS)).min(1),catalogStrategy: z.enum(CATALOG_STRATEGIES),harnessOnly: z.string().nullable(),+ // Where a key is obtained and which variables it is conventionally held+ // under — what a Services card's "get a key" link and env hint read (#7567).+ keyUrl: z.string().nullable(),+ envVars: z.array(z.string()),}).strict();+/**+ * The definition half of the service DTO, and each row of+ * `GET /api/providers/service-definitions` — what an "Add service" flow+ * chooses from. Code-only data (no instance, no credential): the transports a+ * definition speaks with their default base URLs, so a form can pre-fill an+ * endpoint or demand one where the definition declares none.+ */+export const presentServiceDefinition = (definition) => ({+ id: definition.id,+ label: definition.label,+ family: definition.family,+ plans: [...definition.plans],+ catalogStrategy: definition.catalog.strategy,+ harnessOnly: definition.harnessOnly ?? null,+ keyUrl: definition.credential.keyUrl ?? null,+ envVars: [...definition.credential.envVars],+});++/** `presentServiceDefinition` plus the transport defaults an instance form pre-fills. */+export const presentServiceDefinitionForCreate = (definition) => ({+ ...presentServiceDefinition(definition),+ transports: Object.fromEntries(Object.entries(definition.transports)+ .map(([protocol, transport]) => [protocol, { defaultBaseUrl: transport.defaultBaseUrl ?? null }])),+});+/*** One instance as `GET /api/providers/services` publishes it: the connection* DTO (so a column is mapped in exactly one place and `credentials` never@@ -283,14 +312,7 @@ export function toServiceDto(connection, { bindingCount = 0, credentialSource =const resolved = definition === undefined ? (base.definitionId ? serviceDefinitionById(base.definitionId) : null) : definition;return serviceDtoSchema.parse({...base,- definition: resolved ? {- id: resolved.id,- label: resolved.label,- family: resolved.family,- plans: [...resolved.plans],- catalogStrategy: resolved.catalog.strategy,- harnessOnly: resolved.harnessOnly ?? null,- } : null,+ definition: resolved ? presentServiceDefinition(resolved) : null,credentialSource,bindingCount,readiness: serviceReadiness(base, resolved, credentialSource),diff --git a/server/routes/providers.js b/server/routes/providers.jsindex d688af42d3..8c21dde960 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -22,6 +22,8 @@ import {refreshServiceCatalog,updateService,} from '../services/providerServices.js';+import { presentServiceDefinitionForCreate } from '../lib/providerServiceInstances.js';+import { SERVICE_DEFINITIONS } from '../lib/serviceDefinitions.js';import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { testVision, runVisionTestSuite, checkVisionHealth } from '../services/visionTest.js';@@ -511,6 +513,17 @@ export function createPortOSProviderRoutes(aiToolkit) {res.set('Cache-Control', 'no-store').json(await listServices());}));+ /**+ * Every `SERVICE_DEFINITIONS` row an "Add service" flow may instantiate+ * (#7567): family, plans, transports with default base URLs, and where a key+ * is obtained. Code-only data — no instance, no credential — so it is+ * cacheable for the process lifetime. Declared above `/services/:slug` by+ * name rather than position: its own segment can never be read as a slug.+ */+ router.get('/service-definitions', (_req, res) => {+ res.json({ definitions: SERVICE_DEFINITIONS.map(presentServiceDefinitionForCreate) });+ });+// Create an instance from a definition. Nothing is probed and no route is// minted; the catalog starts `unknown` until the explicit refresh below.router.post('/services', asyncHandler(async (req, res) => {diff --git a/server/services/providerRuntimeInstaller.js b/server/services/providerRuntimeInstaller.jsindex a8477fe78d..48cfd599f3 100644--- a/server/services/providerRuntimeInstaller.js+++ b/server/services/providerRuntimeInstaller.js@@ -271,6 +271,9 @@ async function probeRuntimeStatus(runtime, findCommand, probeCommand) {id: runtime.id,label: runtime.label,command: runtime.command,+ // The harness this binary drives (`PROVIDER_HARNESSES` id), so a harness+ // card can find its runtime without a client-side copy of the vendor table.+ vendor: runtime.vendor,installed,// `null` = the banner did not parse (or the probe answered a bare boolean),// NOT "0.0.0". Every version comparison bails on it rather than reporting adiff --git a/server/services/providerRuntimeInstaller.test.js b/server/services/providerRuntimeInstaller.test.jsindex 3638ccabca..9160c420b7 100644--- a/server/services/providerRuntimeInstaller.test.js+++ b/server/services/providerRuntimeInstaller.test.js@@ -42,6 +42,7 @@ describe('provider runtime installer', () => {id: 'opencode',label: 'OpenCode CLI',command: 'opencode',+ vendor: 'opencode',installed: true,version: '1.18.27',method: 'npm',