Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: manage a shared provider backend from one screen instead of once per harness (#6369)

[._.]/ Adam Eivye6c8301269ba
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 3184e3136d..6a1ce4adbc 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -293,6 +293,14 @@ export default function App() {
<Route path="ai/new" element={<AIProviders />} />
<Route path="ai/fleet" element={<AIProviders />} />
<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="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/components/providers/ProviderConnections.jsx b/client/src/components/providers/ProviderConnections.jsx
new file mode 100644
index 0000000000..c9bd8c2721
--- /dev/null
+++ b/client/src/components/providers/ProviderConnections.jsx
@@ -0,0 +1,522 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { Link } from 'react-router';
+import { Link2, Link2Off, RefreshCw, Star, Trash2 } from 'lucide-react';
+import toast from '../ui/Toast';
+import Drawer from '../Drawer';
+import Banner from '../ui/Banner';
+import EmptyState from '../EmptyState';
+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.
+ *
+ * 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 and editing an endpoint 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 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);
+
+ 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]);
+
+ 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) => {
+ 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]);
+
+ 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>}
+
+ {!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. Configure a provider and it will appear here."
+ />
+ )}
+
+ {groups
+ .filter((group) => !harnessId
+ || group.bindings.some((entry) => entry.binding.harnessId === harnessId))
+ .map((group) => {
+ const isOpen = group.connection.id === connectionId;
+ 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">{group.connection.label || group.connection.id}</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 ${summary.tone === 'error' ? 'text-port-error' : summary.tone === 'ok' ? 'text-port-success' : 'text-port-muted'}`}>
+ {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 && (
+ <button type="button" disabled={busy} onClick={() => removeConnection(group.connection)}
+ 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>
+
+ {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-1">
+ {routes.map((route) => (
+ <li key={route.providerId} 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>
+ {graph?.activeProvider === route.providerId ? (
+ <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={() => makeDefault(route.providerId)}
+ className="text-xs text-port-muted hover:underline disabled:opacity-50">
+ Use as system default
+ </button>
+ )}
+ </li>
+ ))}
+ </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}>
+ {candidate.connection.label || candidate.connection.id}
+ </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.jsx
new file mode 100644
index 0000000000..6a11452e32
--- /dev/null
+++ b/client/src/components/providers/ProviderConnections.test.jsx
@@ -0,0 +1,212 @@
+/**
+ * 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(),
+ 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',
+ 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: [
+ { providerId: 'claude-ollama', bindingId: CLAUDE_BINDING, mode: 'cli', modelMap: {}, projectionPending: false },
+ { providerId: 'claude-ollama-tui', bindingId: CLAUDE_BINDING, mode: 'tui', modelMap: {}, projectionPending: false },
+ ],
+});
+
+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.getByText('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();
+
+ fireEvent.change(await screen.findByLabelText('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();
+ });
+});
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 2290aa23c0..53097f1897 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -156,6 +156,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). |
| `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/index.js b/client/src/lib/index.js
index da8dfc6ea1..782550d8b2 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -122,6 +122,7 @@ export * from './mediaSearch.js';
export * from './morsePractice.js';
export * from './moodBoardItemSrc.js';
export * from './ports.js';
+export * from './providerManagement.js';
export * from './rapidReaderPosition.js';
export * from './registerServiceWorker.js';
export * from './safeStorage.js';
diff --git a/client/src/lib/providerManagement.js b/client/src/lib/providerManagement.js
new file mode 100644
index 0000000000..ef9f107e24
--- /dev/null
+++ b/client/src/lib/providerManagement.js
@@ -0,0 +1,128 @@
+/**
+ * Reading the provider connection graph (#6369).
+ *
+ * `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.
+ */
+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.
+ *
+ * `known` with zero models is a real answer from a backend with no models
+ * installed; `unknown` is "never asked"; `failed` keeps the models it already
+ * had. Collapsing any two of those into "0 models" is the exact bug the catalog
+ * state field exists to prevent.
+ */
+export function catalogSummary(catalog) {
+ const models = Array.isArray(catalog?.models) ? catalog.models : [];
+ if (catalog?.state === 'failed') {
+ return {
+ tone: 'error',
+ text: models.length > 0
+ ? `Last refresh failed — showing ${models.length} previously known model${models.length === 1 ? '' : 's'}`
+ : 'Last refresh failed — no models known yet',
+ detail: catalog.error || null,
+ };
+ }
+ if (catalog?.state === 'known') {
+ return {
+ tone: models.length > 0 ? 'ok' : 'warn',
+ text: models.length > 0
+ ? `${models.length} model${models.length === 1 ? '' : 's'}`
+ : 'No models installed on this backend',
+ detail: null,
+ };
+ }
+ return { tone: 'muted', text: 'Not refreshed yet', detail: null };
+}
diff --git a/client/src/lib/providerManagement.test.js b/client/src/lib/providerManagement.test.js
new file mode 100644
index 0000000000..e9e3ff6c70
--- /dev/null
+++ b/client/src/lib/providerManagement.test.js
@@ -0,0 +1,83 @@
+/**
+ * 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, 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([]);
+ });
+});
+
+describe('catalogSummary', () => {
+ it('keeps never-asked distinct from asked-and-empty', () => {
+ expect(catalogSummary({ state: 'unknown', models: [] }).text).toBe('Not refreshed yet');
+ expect(catalogSummary({ state: 'known', models: [] }).text).toBe('No models installed on this backend');
+ });
+
+ it('reports a failed refresh as retained models, never as an empty backend', () => {
+ const summary = catalogSummary({ state: 'failed', models: ['a'], error: 'timed out' });
+ expect(summary.text).toContain('1 previously known model');
+ 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');
+ });
+});
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 3060c3f937..d0d69222b9 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback, useMemo } from 'react';
import { Link, useLocation, useNavigate, useParams } from 'react-router';
-import { Bot, Cpu, Gauge, Network, Package } from 'lucide-react';
+import { Bot, Cpu, Gauge, Link2, Network, Package } from 'lucide-react';
import toast from '../components/ui/Toast';
import * as api from '../services/api';
import socket from '../services/socket';
@@ -21,6 +21,7 @@ import ProviderForm from '../components/providers/ProviderForm';
import CollapsibleSection from '../components/ui/CollapsibleSection';
import FleetProviderSetup from '../components/providers/FleetProviderSetup';
import FleetHostSetup from '../components/providers/FleetHostSetup';
+import ProviderConnections from '../components/providers/ProviderConnections';
// 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
@@ -196,12 +197,25 @@ export default function AIProviders() {
// create route shadow its editor.
const navigate = useNavigate();
const location = useLocation();
- const { providerId: editingProviderId } = useParams();
+ 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],
+ );
+
useEffect(() => {
loadData();
}, []);
@@ -691,6 +705,8 @@ export default function AIProviders() {
{ 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',
@@ -1079,6 +1095,16 @@ 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}
+ />
+ )}
{fleetSetupOpen && (
<FleetProviderSetup
peers={fleetPeers}
diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.js
index 819d8d7541..fb56e8b8ca 100644
--- a/client/src/services/apiProviders.js
+++ b/client/src/services/apiProviders.js
@@ -89,3 +89,71 @@ export const getFleetLlmHost = (options) => request('/providers/fleet-host', opt
export 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);
+
+/** 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 },
+);
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index ebcce4c4ed..359362ca08 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -56,6 +56,7 @@ is where the server parity tests pin each browser mirror.
| `providers` | Compatibility facade re-exporting every helper from the nine modules below, so existing `../utils/providers` imports keep working. New code imports the declaring module. |
| `providerTypes` | What KIND of provider a record is: `PROVIDER_TYPES` (mirror of `server/lib/aiToolkit/constants.js`) with `isCliProvider` / `isTuiProvider` / `isApiProvider` / `isProcessProvider`, `isLaunchableTuiProvider` (a TUI provider carrying the server-resolved `tuiCommandLine`, i.e. one a human can start at a shell prompt — shared by the Providers card's "Launch in Shell" button and the Shell page's launch menu so the two can't disagree), `enabledApiProviderFilter`, `enabledProcessProviderFilter` (the coding/CLI-TUI-only counterpart, for a manual Claim/Replan/Resolve/Review "Run with" picker), `providerTypeClass`; the vendor-harness predicates keyed on the shipped ids plus `commandBasename` so a path-configured or renamed binary still qualifies (`isCodexProvider`, `isCodexSubscriptionProvider` — subscription readiness is keyed on the `codex` command, never an editable id — `isAntigravityProvider`, `isCursorProvider`, `isKimiProvider`, `isGrokProvider`, `isGrokBuildCli`, `isClaudeCommandProvider`, `isOpencodeLocalProvider`); and the structural backend markers a wrapper carries (`localRuntimeNamespace`, `isOllamaBackedProvider`). Mirror of the same predicates in `server/lib/providerModels.js`. |
| `providerGateways` | `PROVIDER_GATEWAYS` / `gatewayForProvider` / `isGatewayBackedProvider` — the hosted OpenAI-compatible gateways (`orcarouter`, `openrouter`) an OpenCode CLI/TUI wrapper can front-end, inheriting its API key at spawn time from the sibling API provider whose id equals the gateway id. Reads the generic `gatewayBacked` marker and, forever, the legacy per-gateway boolean. MIRROR of `server/lib/providerGateways.js`, which the browser cannot import; `server/lib/providerGateways.parity.test.js` reads this file as text and fails when the copies drift. |
+| `providerHarnesses` | `PROVIDER_HARNESS_LABELS` / `harnessLabel(harnessId)` — display names for the agent programs PortOS drives (Claude Code, OpenCode, Codex, …), used by the connection-management UI, where `null` means Direct API and an unknown id renders verbatim rather than disappearing. MIRROR of `PROVIDER_HARNESSES` in `server/lib/providerHarnesses.js`, which the browser cannot import; `server/lib/providerHarnesses.parity.test.js` reads this file as text and fails when the copies drift. |
| `providerEndpoints` | WHERE a provider's endpoint points. `isLocalEndpoint` (loopback), `isPrivateNetworkEndpoint` (RFC1918 / tailnet address, or a `.local` / `.ts.net` / single-label host — somewhere an unauthenticated OpenAI-compatible server is a normal setup rather than a missing API key), `isLocalInstanceProvider` (talks to a daemon on THIS machine; mirror of `server/lib/localProviderRuntime.js#isLocalInstanceEndpoint` — gate anything that explains a provider by inspecting the host PortOS runs on), `isFleetProvider` / `isFleetHostConfigured` (another machine inside the private network), and `localBackendForProvider` (`'ollama'` / `'lmstudio'` / `null` by id, endpoint or name — it matches by NAME, so pair it with `isLocalInstanceProvider` before claiming this machine's install state). |
| `providerModels` | Which MODEL and EFFORT a run resolves to, and what a picker may list. The configured-default sentinels (`CODEX_CONFIGURED_DEFAULT` …, `isConfiguredDefaultModel`, `configuredDefaultIn` — so a picker can render an option matching a sentinel-valued tier instead of a blank select) and `filterSelectableModels`; the per-CLI effort ladders, `effortLevelsForProvider`, `resolveCliEffort` (what a stored effort actually runs as, so the picker can name a clamped level), `effortSurvivingModel` and `seedModelEffort`; the Antigravity base-model ↔ effort-suffix split (`splitAntigravityModel`, `antigravityBaseModels`, `antigravityModelEffortLevels`, `withStaleAntigravityPin`); the account-aware option list (`providerModelList`, `resolveProviderModelOptions`, `effortAwareModelOptions`, `MODEL_SOURCE` — the one place a Codex-subscription account catalog enters a picker); `effectiveModelFor`; `mergeModelLists` / `mergeProviderUpdate`; and `generationControlsFor` (which temperature / top-p / thinking controls a provider forwards at all). Mirror of `server/lib/providerModels.js` (and `server/lib/opencodeConfig.js` for the controls); `server/lib/providerModels.mirror.test.js` reads this file as text and fails when a mirrored declaration drifts. |
| `providerSelection` | Which providers and models a picker may OFFER on this install: `isProviderHardwareCompatible` / `isProviderModelHardwareCompatible` / `filterHardwareCompatibleProviderModels` (server-annotated, fail-open), `selectableProviders` (the single rule `ProviderModelSelector` renders from), `filterRunnableProviders` (agent jobs need a CLI/TUI harness), the fail-closed tool-free local policy (`TOOL_FREE_LOCAL_PROVIDER_IDS`, `TOOL_FREE_LOCAL_TEXT_CAPABILITIES`, `isToolFreeLocalProvider`, `isToolFreeLocalModel`, `toolFreeLocalSelectionPolicy`) used by security-sensitive pickers, and the pr-reviewer postures (`PUBLIC_REVIEW_NO_TOOL_POSTURE` / `PUBLIC_REVIEW_ACTIONS_POSTURE`, `supportsPublicReviewPosture`, `enforcesPublicReviewPosture`, `publicReviewSelectionPolicy` — mirror of `server/lib/agentExecutionProfiles.js`: a pipeline stage names a POSTURE, the server publishes each provider's `publicReviewPostures` and `publicReviewEnforcedPostures` on `GET /api/providers`, and the picker offers exactly the providers this install can run the stage on, so no vendor is named on either side). Also the caller EXECUTION-MODE mirror (`CALLER_MODE_POLICY_MODES`, `callerModeList`, `providerModeSelectionPolicy`) of `server/lib/callerModePolicy.js` — the server enforces the policy on the pin, on `activeProvider` inheritance and on every fallback candidate; this only lets a picker SHOW the rule, keeping an ineligible saved value visible-but-disabled instead of hidden or silently replaced (parity: `providerModePolicy.parity.test.js`). |
diff --git a/client/src/utils/index.js b/client/src/utils/index.js
index 0c6fe2eead..67697be001 100644
--- a/client/src/utils/index.js
+++ b/client/src/utils/index.js
@@ -38,6 +38,7 @@ export * from './providerAssignments.js';
export * from './providerContextWindows.js';
export * from './providerEndpoints.js';
export * from './providerGateways.js';
+export * from './providerHarnesses.js';
export * from './providerModels.js';
export * from './providerReadiness.js';
export * from './providerSelection.js';
diff --git a/client/src/utils/providerHarnesses.js b/client/src/utils/providerHarnesses.js
new file mode 100644
index 0000000000..2f6fc138d8
--- /dev/null
+++ b/client/src/utils/providerHarnesses.js
@@ -0,0 +1,40 @@
+/**
+ * The agent programs PortOS drives, as the browser needs to name them.
+ *
+ * Browser MIRROR of `PROVIDER_HARNESSES` in `server/lib/providerHarnesses.js`
+ * — the browser cannot import server code, so the id→label table is duplicated
+ * and `server/lib/providerHarnesses.parity.test.js` reads this file as TEXT to
+ * pin the two together.
+ *
+ * Only `id → label` is mirrored, and deliberately so. The server registry's
+ * other columns are all decided server-side and arrive on the wire already
+ * resolved: `matches` classifies a provider RECORD (the browser is handed a
+ * `harnessId`), `modes` is already reflected by the routes a binding actually
+ * owns, and `protocol` is a transport decision no picker makes. Mirroring them
+ * would create three more things to drift for no rendered difference.
+ */
+
+/** id → display label. MIRROR of the server registry; keep in lockstep. */
+export const PROVIDER_HARNESS_LABELS = Object.freeze({
+ claude: 'Claude Code',
+ opencode: 'OpenCode',
+ codex: 'Codex',
+ antigravity: 'Antigravity',
+ cursor: 'Cursor Agent',
+ grok: 'Grok',
+ kimi: 'Kimi Code',
+ pi: 'Pi',
+});
+
+/**
+ * What to call a binding's harness.
+ *
+ * `null` is the DIRECT API case and has a name of its own — it is a real
+ * binding with a real route, not a missing value. An id this build does not
+ * know is shown verbatim rather than hidden: an unmapped harness stays a
+ * visible legacy route, which is exactly what the graph promises.
+ */
+export const harnessLabel = (harnessId) => {
+ if (harnessId === null || harnessId === undefined) return 'Direct API';
+ return PROVIDER_HARNESS_LABELS[harnessId] || harnessId;
+};
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index b9ea0643ca..d522e9117b 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -13880,6 +13880,14 @@
"server/routes/providers.js"
]
},
+ {
+ "method": "PATCH",
+ "path": "/api/providers/bindings/:id",
+ "mountPath": "/api/providers",
+ "sources": [
+ "server/routes/providers.js"
+ ]
+ },
{
"method": "POST",
"path": "/api/providers/bindings/:id/link",
@@ -13984,6 +13992,22 @@
"server/routes/providers.js"
]
},
+ {
+ "method": "PATCH",
+ "path": "/api/providers/connections/:id",
+ "mountPath": "/api/providers",
+ "sources": [
+ "server/routes/providers.js"
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/providers/connections/:id/refresh-models",
+ "mountPath": "/api/providers",
+ "sources": [
+ "server/routes/providers.js"
+ ]
+ },
{
"method": "GET",
"path": "/api/providers/fleet-host",
@@ -17900,8 +17924,8 @@
],
"stats": {
"mounts": 150,
- "operations": 2217,
- "declarations": 2225,
+ "operations": 2220,
+ "declarations": 2228,
"sourceFiles": 233
}
}
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 5a2238b3fe..95524bef55 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -87,6 +87,7 @@ const RAW_NAV_COMMANDS = [
{ 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'] },
{ 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/providerGraphPreview.js b/server/lib/providerGraphPreview.js
index 04e062d35e..dd7632b0bf 100644
--- a/server/lib/providerGraphPreview.js
+++ b/server/lib/providerGraphPreview.js
@@ -218,7 +218,7 @@ export function routeModeEligibility(provider, { allowedModes = ROUTE_MODES } =
* can never claim one canonical name: `modelMap` is keyed by canonical, so a
* literal duplicate collapses and nothing else can collide.
*/
-function resolveRouteModels(provider) {
+export function resolveRouteModels(provider) {
const stored = Array.isArray(provider?.models) ? provider.models : [];
const modelMap = {};
const unresolvedModels = [];
diff --git a/server/lib/providerGraphRecords.js b/server/lib/providerGraphRecords.js
index 0744ee913e..5b5746be40 100644
--- a/server/lib/providerGraphRecords.js
+++ b/server/lib/providerGraphRecords.js
@@ -1,7 +1,7 @@
import { randomUUID } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import { z } from 'zod';
-import { providerConnectionProfile } from './providerConnections.js';
+import { REDACTED_CREDENTIAL, providerConnectionProfile } from './providerConnections.js';
import {
PROVIDER_GRAPH_SCHEMA_VERSION,
buildProviderGraphPreview,
@@ -46,6 +46,10 @@ import { PROVIDER_HARNESS_IDS, ROUTE_MODES, providerRouteMode } from './provider
const catalogSchema = z.object({
state: z.enum(['unknown', 'known', 'failed']),
models: z.array(z.string()),
+ // Why the last refresh failed, already stripped of credential material
+ // (#6369). Optional so rows written before the field existed still parse, and
+ // nullable so a later SUCCESS can clear it without deleting the key.
+ error: z.string().nullable().optional(),
}).strict();
const connectionDtoSchema = z.object({
@@ -367,3 +371,86 @@ export const reconciliationIsNoop = (plan) =>
&& plan.snapshots.length === 0
&& plan.imports.routes.length === 0
&& plan.regroups.every((regroup) => regroup.connectionAction === 'unchanged' && regroup.bindingId);
+
+// --- explicit management edits (#6369) ---------------------------------------
+
+/**
+ * Merge a credential patch into a connection's stored credentials.
+ *
+ * Three distinct inputs, three distinct outcomes — the sentinel-vs-empty rule
+ * from AGENTS.md, applied to secrets, where conflating them silently destroys
+ * one:
+ *
+ * - key ABSENT → preserve the stored secret (the client never had it)
+ * - value `null`→ an explicit clear
+ * - a string → set it
+ *
+ * A client can only have learned `REDACTED_CREDENTIAL` by reading a sanitized
+ * response, so echoing it back is never an intentional value. It is reported as
+ * `rejected` rather than written, because storing `'***'` as the real secret
+ * would break execution in a way no later edit could distinguish from a typo.
+ *
+ * @param {Record<string,string>} current
+ * @param {Record<string,string|null>|undefined} patch
+ * @returns {{credentials: Record<string,string>, rejected: string[]}}
+ */
+export function mergeConnectionCredentials(current, patch) {
+ const credentials = { ...(current || {}) };
+ const rejected = [];
+ for (const [name, value] of Object.entries(patch || {})) {
+ if (value === null) {
+ delete credentials[name];
+ continue;
+ }
+ if (value === REDACTED_CREDENTIAL) {
+ rejected.push(name);
+ continue;
+ }
+ credentials[name] = value;
+ }
+ return { credentials, rejected };
+}
+
+/** Bound on a persisted refresh error, so one runaway provider message cannot bloat a row. */
+const CATALOG_ERROR_MAX = 300;
+
+/**
+ * A refresh failure reduced to something safe to persist and show.
+ *
+ * Provider errors routinely echo the request that produced them, so the
+ * connection's OWN credential values are replaced before anything is stored —
+ * an exact match on known secrets, not a guess at what a secret looks like.
+ *
+ * @param {unknown} error
+ * @param {Record<string,string>} credentials - the connection's raw secrets
+ * @returns {string}
+ */
+export function sanitizeCatalogError(error, credentials = {}) {
+ const raw = (error && typeof error === 'object' && 'message' in error ? String(error.message) : String(error || ''))
+ || 'The model refresh failed';
+ const redacted = Object.values(credentials)
+ .filter((secret) => typeof secret === 'string' && secret.length > 0)
+ .reduce((text, secret) => text.split(secret).join(REDACTED_CREDENTIAL), raw);
+ return redacted.length > CATALOG_ERROR_MAX ? `${redacted.slice(0, CATALOG_ERROR_MAX)}…` : redacted;
+}
+
+/**
+ * The catalog a refresh should leave behind.
+ *
+ * The rule that matters is the one this whole feature exists to protect: a
+ * FAILED probe keeps the models it already knew. Only a successful probe writes
+ * a model list, and a successful probe returning nothing writes `known` with an
+ * empty list — a real answer from a backend whose last model was deleted, not
+ * the same state as "never asked".
+ *
+ * @param {{state:string, models:string[]}} current - the stored catalog
+ * @param {{refreshed: boolean, models?: string[], error?: string|null}} outcome
+ * @returns {{state:'unknown'|'known'|'failed', models:string[], error:string|null}}
+ */
+export function nextConnectionCatalog(current, outcome) {
+ const models = Array.isArray(current?.models) ? current.models : [];
+ if (!outcome?.refreshed) {
+ return { state: 'failed', models, error: outcome?.error ?? 'The model refresh failed' };
+ }
+ return { state: 'known', models: [...new Set(outcome.models || [])], error: null };
+}
diff --git a/server/lib/providerHarnesses.parity.test.js b/server/lib/providerHarnesses.parity.test.js
new file mode 100644
index 0000000000..9518942470
--- /dev/null
+++ b/server/lib/providerHarnesses.parity.test.js
@@ -0,0 +1,82 @@
+/**
+ * The harness registry lives in two places by architecture: the browser cannot
+ * import server code, so `client/src/utils/providerHarnesses.js` carries its own
+ * id→label table. This suite pins the two together, so a harness added to the
+ * server registry can never render as a bare id in the connection management UI
+ * — and a harness REMOVED from the server can never linger as a label the
+ * browser still offers.
+ *
+ * The client copy is read with `readFileSync` and parsed out of the source,
+ * never imported, so the client's dependency tree stays out of the server CI
+ * job (`server/vitest.config.js` globs this directory).
+ */
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { resolve, dirname } from 'path';
+import { fileURLToPath } from 'url';
+import { PROVIDER_HARNESSES } from './providerHarnesses.js';
+import { stripCommentsAndNormalize } from './mirrorParity.js';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const CLIENT_PATH = resolve(__dirname, '../../client/src/utils/providerHarnesses.js');
+
+// The whole normalized declaration, ANCHORED: a scan for `key: 'value'` pairs
+// anywhere in the file would keep reading row literals out of a table that had
+// been wrapped in a transform and report a registry that no longer exists as
+// intact. Anchoring makes an unrecognized shape fail closed instead.
+const TABLE_RE = /^(?:export\s+)?const\s+PROVIDER_HARNESS_LABELS\s*=\s*Object\.freeze\(\s*\{(.*)\}\s*\)\s*;$/;
+// One `id: 'Label'` entry at the head of the remaining body, plus its separator.
+// Escapes are rejected outright — no harness label has one, and decoding them by
+// inspection is how a parser starts guessing.
+const NEXT_ENTRY_RE = /^(\w+)\s*:\s*'([^'\\]*)'\s*(?:,\s*)?/;
+
+/** The client's mirrored table as a plain object, or null when it isn't a static one. */
+function parseClientLabels(source) {
+ const declaration = stripCommentsAndNormalize(source)
+ .split(';')
+ .map((statement) => `${statement.trim()};`)
+ .find((statement) => TABLE_RE.test(statement));
+ if (!declaration) return null;
+
+ const labels = {};
+ let rest = TABLE_RE.exec(declaration)[1].trim();
+ while (rest.length > 0) {
+ const match = NEXT_ENTRY_RE.exec(rest);
+ if (!match) return null;
+ labels[match[1]] = match[2];
+ rest = rest.slice(match[0].length);
+ }
+ return labels;
+}
+
+describe('provider harness registry parity', () => {
+ const clientLabels = parseClientLabels(readFileSync(CLIENT_PATH, 'utf8'));
+
+ it('parses the browser mirror as a static table', () => {
+ expect(clientLabels).not.toBeNull();
+ });
+
+ it('mirrors every server harness id and label, and adds none', () => {
+ expect(clientLabels).toEqual(
+ Object.fromEntries(PROVIDER_HARNESSES.map((harness) => [harness.id, harness.label])),
+ );
+ });
+
+ // A guard that cannot fail is not a guard. These pin the parser itself:
+ // real drift has to be DETECTED, and an unparseable table has to fail closed
+ // rather than silently compare an empty registry against an empty one.
+ it('detects a drifted label', () => {
+ const drifted = parseClientLabels(
+ readFileSync(CLIENT_PATH, 'utf8').replace("claude: 'Claude Code'", "claude: 'Claude'"),
+ );
+ expect(drifted).not.toEqual(
+ Object.fromEntries(PROVIDER_HARNESSES.map((harness) => [harness.id, harness.label])),
+ );
+ });
+
+ it('fails closed on a table it cannot read statically', () => {
+ expect(parseClientLabels(
+ "export const PROVIDER_HARNESS_LABELS = Object.freeze({ ...someOtherTable });",
+ )).toBeNull();
+ });
+});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index f0a05f0717..590a5a0d30 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -581,6 +581,35 @@ export const providerBindingUnlinkSchema = z.object({
}).strict().optional().default({}),
}).strict();
+// PATCH /api/providers/connections/:id (#6369).
+//
+// `expectedRevision` is REQUIRED, unlike the link schemas where a preview may
+// omit it: this endpoint always writes, and a shared backend edit that lands on
+// a row the human never saw is exactly the silent overwrite the graph exists to
+// prevent.
+//
+// Credentials are three-valued on purpose — absent preserves, `null` clears, a
+// string sets — so a client that never received the secret (the DTO carries
+// only `hasCredentials`) can edit a label without wiping the key.
+export const providerConnectionUpdateSchema = z.object({
+ expectedRevision: z.number().int().positive(),
+ label: z.string().trim().max(200).optional(),
+ transports: z.record(
+ z.string().trim().min(1).max(64),
+ z.object({ baseUrl: z.string().trim().min(1).max(2048) }).strict(),
+ ).optional(),
+ credentials: z.record(z.string().trim().min(1).max(128), z.string().max(4096).nullable()).optional(),
+}).strict();
+
+// PATCH /api/providers/bindings/:id (#6369). Management state only: no
+// `enabled`, because route enablement is an executable-record field that
+// PATCH /api/providers/:id owns and a binding toggle must never grant it.
+export const providerBindingUpdateSchema = z.object({
+ expectedRevision: z.number().int().positive(),
+ label: z.string().trim().max(200).optional(),
+ selectedModels: z.array(z.string().trim().min(1).max(512)).max(1000).optional(),
+}).strict();
+
// POST /api/providers/:id/vision-suite.
export const providerVisionSuiteSchema = z.object({
model: z.preprocess(emptyToUndefined, z.string().trim().min(1).max(256).optional()),
diff --git a/server/routes/providers.connectionManagement.test.js b/server/routes/providers.connectionManagement.test.js
new file mode 100644
index 0000000000..666b284513
--- /dev/null
+++ b/server/routes/providers.connectionManagement.test.js
@@ -0,0 +1,429 @@
+/**
+ * Shared-backend management, end to end (#6369): real Express route → real Zod
+ * schema → the real `providerGraph` service → a doubled store and toolkit.
+ *
+ * Only the two persistence edges are doubled, because everything worth pinning
+ * here happens between them:
+ *
+ * - one edit to a shared backend reaches EVERY harness on it, in one
+ * projection, without renaming a route or moving a pin;
+ * - a stale revision is refused BEFORE anything is written;
+ * - a failed catalog refresh keeps the models the connection already knew,
+ * while a successful empty one is recorded as a real empty answer;
+ * - narrowing a binding's model subset touches no executable record at all;
+ * - no response ever carries a credential or a projection snapshot.
+ *
+ * Fixtures are synthetic. Nothing here is read out of a running install.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import express, { Router } from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const store = {
+ readGraph: vi.fn(),
+ applyReconciliation: vi.fn().mockResolvedValue(undefined),
+ commitPendingProjection: vi.fn().mockResolvedValue(undefined),
+ acknowledgeProjection: vi.fn().mockResolvedValue(undefined),
+ relinkBinding: vi.fn().mockResolvedValue(undefined),
+ deleteConnection: vi.fn(),
+ detachBindingToConnection: vi.fn().mockResolvedValue(undefined),
+ saveConnectionSettings: vi.fn().mockResolvedValue(2),
+ saveBindingSettings: vi.fn().mockResolvedValue(2),
+ saveRouteModelMap: vi.fn().mockResolvedValue(undefined),
+};
+vi.mock('../services/providerGraphStore.js', () => store);
+
+const providerService = {
+ getAllProviders: vi.fn(),
+ applyProviderPatches: vi.fn(),
+ refreshProviderModelsBatch: vi.fn(),
+};
+// Partial: the routes module pulls the whole toolkit-state surface in through
+// `services/providers.js`, so only `requireToolkit` is doubled.
+vi.mock('../lib/aiToolkitState.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ requireToolkit: () => ({ services: { providers: providerService } }),
+}));
+
+const graph = await import('../services/providerGraph.js');
+const { createPortOSProviderRoutes } = await import('./providers.js');
+
+const CONNECTION = '11111111-1111-4111-8111-111111111111';
+const OTHER_CONNECTION = '22222222-2222-4222-8222-222222222222';
+const CLAUDE_BINDING = '33333333-3333-4333-8333-333333333333';
+const CODEX_BINDING = '44444444-4444-4444-8444-444444444444';
+
+// One daemon, two protocol ports — the shape a local Ollama actually presents,
+// and the reason a connection carries a transports MAP rather than one URL.
+const DAEMON = 'http://127.0.0.1:11434';
+const DAEMON_OPENAI = 'http://127.0.0.1:11434/v1';
+const TOKEN = 'example-shared-token';
+const OPENAI_KEY = 'example-openai-key';
+
+// Two harnesses, three executable routes, ONE backend — the configuration this
+// whole feature exists to stop a human from typing three times.
+const CLAUDE_CLI = {
+ id: 'claude-ollama',
+ name: 'Claude',
+ type: 'cli',
+ command: 'claude',
+ ollamaBacked: true,
+ enabled: true,
+ models: ['example-model'],
+ defaultModel: 'example-model',
+ envVars: { ANTHROPIC_BASE_URL: DAEMON, ANTHROPIC_AUTH_TOKEN: TOKEN },
+ secretEnvVars: ['ANTHROPIC_AUTH_TOKEN'],
+};
+const CLAUDE_TUI = { ...CLAUDE_CLI, id: 'claude-ollama-tui', type: 'tui', enabled: false };
+const CODEX_CLI = {
+ id: 'codex-ollama',
+ name: 'Codex',
+ type: 'cli',
+ command: 'codex',
+ ollamaBacked: true,
+ enabled: true,
+ models: ['example-model'],
+ // The same daemon, reached through its OpenAI-compatible port — a SECOND
+ // harness on ONE connection, which is what makes a shared edit meaningful.
+ envVars: { OPENAI_BASE_URL: DAEMON_OPENAI, OPENAI_API_KEY: OPENAI_KEY },
+ secretEnvVars: ['OPENAI_API_KEY'],
+};
+
+const ownedSnapshot = () => ({
+ fields: {},
+ envVars: { ANTHROPIC_BASE_URL: DAEMON, ANTHROPIC_AUTH_TOKEN: TOKEN },
+ hasEnvVars: true,
+});
+const codexOwnedSnapshot = () => ({
+ fields: {},
+ envVars: { OPENAI_BASE_URL: DAEMON_OPENAI, OPENAI_API_KEY: OPENAI_KEY },
+ hasEnvVars: true,
+});
+
+const route = (providerId, bindingId, mode, projected = ownedSnapshot()) => ({
+ providerId,
+ bindingId,
+ mode,
+ modelMap: { 'example-model': 'example-model' },
+ projected,
+ pending: null,
+ pendingRevision: null,
+});
+
+const graphFixture = () => ({
+ connections: [
+ {
+ id: CONNECTION,
+ revision: 3,
+ kind: 'ollama',
+ label: 'Example local daemon',
+ transports: { anthropic: { baseUrl: DAEMON }, openai: { baseUrl: DAEMON_OPENAI } },
+ credentials: { ANTHROPIC_AUTH_TOKEN: TOKEN, OPENAI_API_KEY: OPENAI_KEY },
+ catalog: { state: 'known', models: ['example-model', 'retired-model'] },
+ },
+ {
+ id: OTHER_CONNECTION,
+ revision: 1,
+ kind: 'ollama',
+ label: 'Remote daemon',
+ transports: { anthropic: { baseUrl: 'https://ollama.example.com' } },
+ credentials: {},
+ catalog: { state: 'unknown', models: [] },
+ },
+ ],
+ bindings: [
+ {
+ id: CLAUDE_BINDING, revision: 4, connectionId: CONNECTION, harnessId: 'claude',
+ variantKey: 'default', label: 'Claude', enabled: true, selectedModels: ['example-model'],
+ },
+ {
+ id: CODEX_BINDING, revision: 2, connectionId: CONNECTION, harnessId: 'codex',
+ variantKey: 'default', label: 'Codex', enabled: false, selectedModels: [],
+ },
+ ],
+ routes: [
+ route('claude-ollama', CLAUDE_BINDING, 'cli'),
+ route('claude-ollama-tui', CLAUDE_BINDING, 'tui'),
+ route('codex-ollama', CODEX_BINDING, 'cli', codexOwnedSnapshot()),
+ ],
+});
+
+function app() {
+ const toolkit = { services: { providers: providerService }, routes: { providers: Router() } };
+ const server = express();
+ server.use(express.json());
+ server.use('/api/providers', createPortOSProviderRoutes(toolkit));
+ server.use(errorMiddleware);
+ return server;
+}
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ graph.resetProviderGraphState();
+ store.readGraph.mockResolvedValue(graphFixture());
+ store.saveConnectionSettings.mockResolvedValue(4);
+ store.saveBindingSettings.mockResolvedValue(5);
+ providerService.getAllProviders.mockResolvedValue({
+ activeProvider: 'claude-ollama',
+ providers: [structuredClone(CLAUDE_CLI), structuredClone(CLAUDE_TUI), structuredClone(CODEX_CLI)],
+ });
+ providerService.applyProviderPatches.mockImplementation(async (patches) => Object.keys(patches));
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ await graph.initProviderGraph();
+ vi.clearAllMocks();
+ store.readGraph.mockResolvedValue(graphFixture());
+ store.saveConnectionSettings.mockResolvedValue(4);
+ store.saveBindingSettings.mockResolvedValue(5);
+ providerService.applyProviderPatches.mockImplementation(async (patches) => Object.keys(patches));
+});
+
+afterEach(() => vi.restoreAllMocks());
+
+describe('PATCH /api/providers/connections/:id', () => {
+ it('moves every harness on the backend with one edit, keeping route ids', async () => {
+ const res = await request(app())
+ .patch(`/api/providers/connections/${CONNECTION}`)
+ .send({
+ expectedRevision: 3,
+ label: 'Renamed daemon',
+ // The daemon moved port. Both protocol ports move with it, because
+ // they are one backend, not two.
+ transports: {
+ anthropic: { baseUrl: 'http://127.0.0.1:22222' },
+ openai: { baseUrl: 'http://127.0.0.1:22222/v1' },
+ },
+ });
+
+ expect(res.status).toBe(200);
+ // All three executable routes — both Claude modes AND OpenCode — follow the
+ // one edit. That is the whole promise of a shared connection.
+ expect(res.body.affectedRouteIds.sort())
+ .toEqual(['claude-ollama', 'claude-ollama-tui', 'codex-ollama']);
+
+ const [patches] = providerService.applyProviderPatches.mock.calls.at(-1);
+ // Each harness follows the edit through ITS OWN protocol's env var — the
+ // projection is per-transport, not one URL smeared over every route.
+ expect(patches['claude-ollama'].envVars.ANTHROPIC_BASE_URL).toBe('http://127.0.0.1:22222');
+ expect(patches['claude-ollama-tui'].envVars.ANTHROPIC_BASE_URL).toBe('http://127.0.0.1:22222');
+ expect(patches['codex-ollama'].envVars.OPENAI_BASE_URL).toBe('http://127.0.0.1:22222/v1');
+ // A route's OWN settings are never in the patch: an endpoint edit is not a
+ // licence to rewrite a pin, a mode or an enabled flag.
+ expect(patches['claude-ollama']).not.toHaveProperty('defaultModel');
+ expect(patches['claude-ollama']).not.toHaveProperty('enabled');
+ });
+
+ it('stages the projection before writing the file and acknowledges only after', async () => {
+ const order = [];
+ store.commitPendingProjection.mockImplementation(async () => { order.push('stage'); });
+ providerService.applyProviderPatches.mockImplementation(async (patches) => {
+ order.push('write');
+ return Object.keys(patches);
+ });
+ store.acknowledgeProjection.mockImplementation(async () => { order.push('ack'); });
+
+ await request(app()).patch(`/api/providers/connections/${CONNECTION}`)
+ .send({ expectedRevision: 3, label: 'Renamed daemon' });
+
+ expect(order).toEqual(['stage', 'write', 'ack']);
+ });
+
+ it('refuses a stale revision without writing anything', async () => {
+ const res = await request(app())
+ .patch(`/api/providers/connections/${CONNECTION}`)
+ .send({ expectedRevision: 2, label: 'Renamed from a screen that had moved on' });
+
+ expect(res.status).toBe(409);
+ expect(res.body.code).toBe('PROVIDER_GRAPH_STALE_REVISION');
+ expect(store.saveConnectionSettings).not.toHaveBeenCalled();
+ expect(providerService.applyProviderPatches).not.toHaveBeenCalled();
+ });
+
+ it('preserves an omitted credential and clears an explicitly null one', async () => {
+ await request(app()).patch(`/api/providers/connections/${CONNECTION}`)
+ .send({ expectedRevision: 3, label: 'Renamed daemon' });
+ expect(store.saveConnectionSettings.mock.calls[0][0].credentials)
+ .toEqual({ ANTHROPIC_AUTH_TOKEN: TOKEN, OPENAI_API_KEY: OPENAI_KEY });
+
+ // An explicit null clears exactly the one named key — the other harness's
+ // secret on the same backend is not collateral.
+ store.saveConnectionSettings.mockClear();
+ await request(app()).patch(`/api/providers/connections/${CONNECTION}`)
+ .send({ expectedRevision: 3, credentials: { ANTHROPIC_AUTH_TOKEN: null } });
+ expect(store.saveConnectionSettings.mock.calls[0][0].credentials)
+ .toEqual({ OPENAI_API_KEY: OPENAI_KEY });
+ });
+
+ it('refuses a credential echoed back as the redaction placeholder', async () => {
+ const res = await request(app()).patch(`/api/providers/connections/${CONNECTION}`)
+ .send({ expectedRevision: 3, credentials: { ANTHROPIC_AUTH_TOKEN: '***' } });
+
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('PROVIDER_GRAPH_REDACTED_CREDENTIAL');
+ expect(store.saveConnectionSettings).not.toHaveBeenCalled();
+ });
+
+ it('refuses while a route on the backend is mid-projection', async () => {
+ const fixture = graphFixture();
+ fixture.routes[0].pending = ownedSnapshot();
+ store.readGraph.mockResolvedValue(fixture);
+
+ const res = await request(app()).patch(`/api/providers/connections/${CONNECTION}`)
+ .send({ expectedRevision: 3, label: 'Renamed daemon' });
+
+ expect(res.status).toBe(409);
+ expect(res.body.code).toBe('PROVIDER_GRAPH_BINDING_BLOCKED');
+ expect(store.saveConnectionSettings).not.toHaveBeenCalled();
+ });
+
+ it('rejects an unknown field rather than persisting it', async () => {
+ const res = await request(app()).patch(`/api/providers/connections/${CONNECTION}`)
+ .send({ expectedRevision: 3, kind: 'lmstudio' });
+
+ expect(res.status).toBe(400);
+ expect(store.saveConnectionSettings).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST /api/providers/connections/:id/refresh-models', () => {
+ it('probes the shared backend once for every harness on it', async () => {
+ providerService.refreshProviderModelsBatch.mockResolvedValue([
+ { ids: ['claude-ollama', 'claude-ollama-tui', 'codex-ollama'], leadId: 'claude-ollama', status: 'updated' },
+ ]);
+
+ const res = await request(app()).post(`/api/providers/connections/${CONNECTION}/refresh-models`);
+
+ expect(res.status).toBe(200);
+ expect(providerService.refreshProviderModelsBatch).toHaveBeenCalledTimes(1);
+ expect(providerService.refreshProviderModelsBatch.mock.calls[0][0].sort())
+ .toEqual(['claude-ollama', 'claude-ollama-tui', 'codex-ollama']);
+ expect(res.body.catalog.state).toBe('known');
+ expect(res.body.catalog.models).toEqual(['example-model']);
+ });
+
+ it('keeps the models it already knew when the probe fails', async () => {
+ providerService.refreshProviderModelsBatch.mockResolvedValue([
+ { ids: ['claude-ollama'], leadId: 'claude-ollama', status: 'failed', error: new Error('connect ECONNREFUSED') },
+ ]);
+
+ const res = await request(app()).post(`/api/providers/connections/${CONNECTION}/refresh-models`);
+
+ expect(res.status).toBe(200);
+ expect(res.body.catalog.state).toBe('failed');
+ // The catalog it had, not an empty backend — the failure mode this endpoint
+ // exists to avoid.
+ expect(res.body.catalog.models).toEqual(['example-model', 'retired-model']);
+ expect(res.body.catalog.error).toContain('ECONNREFUSED');
+ });
+
+ it('strips the connection secret out of a failure message before storing it', async () => {
+ providerService.refreshProviderModelsBatch.mockResolvedValue([
+ {
+ ids: ['claude-ollama'], leadId: 'claude-ollama', status: 'failed',
+ error: new Error(`401 from ${DAEMON} using Authorization: Bearer ${TOKEN}`),
+ },
+ ]);
+
+ const res = await request(app()).post(`/api/providers/connections/${CONNECTION}/refresh-models`);
+
+ expect(res.body.catalog.error).not.toContain(TOKEN);
+ expect(res.body.catalog.error).toContain('***');
+ });
+
+ it('records a successful empty answer as known-and-empty, not as never-asked', async () => {
+ providerService.getAllProviders.mockResolvedValue({
+ activeProvider: 'claude-ollama',
+ providers: [
+ { ...structuredClone(CLAUDE_CLI), models: [] },
+ { ...structuredClone(CLAUDE_TUI), models: [] },
+ { ...structuredClone(CODEX_CLI), models: [] },
+ ],
+ });
+ providerService.refreshProviderModelsBatch.mockResolvedValue([
+ { ids: ['claude-ollama'], leadId: 'claude-ollama', status: 'updated' },
+ ]);
+
+ const res = await request(app()).post(`/api/providers/connections/${CONNECTION}/refresh-models`);
+
+ expect(res.body.catalog).toMatchObject({ state: 'known', models: [] });
+ });
+
+ it('never repicks a pin or the system default', async () => {
+ providerService.refreshProviderModelsBatch.mockResolvedValue([
+ { ids: ['claude-ollama'], leadId: 'claude-ollama', status: 'updated' },
+ ]);
+
+ await request(app()).post(`/api/providers/connections/${CONNECTION}/refresh-models`);
+
+ // A refresh writes the catalog and the alias maps; it does not go near the
+ // executable records' own model pins.
+ expect(providerService.applyProviderPatches).not.toHaveBeenCalled();
+ });
+
+ it('refuses a connection with no executable route to probe', async () => {
+ const res = await request(app()).post(`/api/providers/connections/${OTHER_CONNECTION}/refresh-models`);
+
+ expect(res.status).toBe(409);
+ expect(res.body.code).toBe('PROVIDER_GRAPH_CONNECTION_UNROUTED');
+ expect(providerService.refreshProviderModelsBatch).not.toHaveBeenCalled();
+ });
+});
+
+describe('PATCH /api/providers/bindings/:id', () => {
+ it('narrows one harness to a subset without touching any executable record', async () => {
+ const res = await request(app())
+ .patch(`/api/providers/bindings/${CLAUDE_BINDING}`)
+ .send({ expectedRevision: 4, selectedModels: ['example-model'] });
+
+ expect(res.status).toBe(200);
+ expect(res.body.selectedModels).toEqual(['example-model']);
+ // Management state only: no projection, so no route's enabled flag, consent
+ // or model pin can move as a side effect of a menu choice.
+ expect(providerService.applyProviderPatches).not.toHaveBeenCalled();
+ expect(store.commitPendingProjection).not.toHaveBeenCalled();
+ });
+
+ it('refuses a stale revision without writing', async () => {
+ const res = await request(app())
+ .patch(`/api/providers/bindings/${CLAUDE_BINDING}`)
+ .send({ expectedRevision: 3, selectedModels: [] });
+
+ expect(res.status).toBe(409);
+ expect(res.body.code).toBe('PROVIDER_GRAPH_STALE_REVISION');
+ expect(store.saveBindingSettings).not.toHaveBeenCalled();
+ });
+
+ it('rejects an `enabled` field, so a menu edit can never grant execution', async () => {
+ const res = await request(app())
+ .patch(`/api/providers/bindings/${CLAUDE_BINDING}`)
+ .send({ expectedRevision: 4, enabled: true });
+
+ expect(res.status).toBe(400);
+ expect(store.saveBindingSettings).not.toHaveBeenCalled();
+ });
+
+ it('404s an unknown binding rather than creating one', async () => {
+ const res = await request(app())
+ .patch('/api/providers/bindings/55555555-5555-4555-8555-555555555555')
+ .send({ expectedRevision: 1, label: 'Invented' });
+
+ expect(res.status).toBe(404);
+ expect(store.saveBindingSettings).not.toHaveBeenCalled();
+ });
+});
+
+describe('the management graph a browser actually receives', () => {
+ it('reports credential PRESENCE and never a secret or a projection snapshot', async () => {
+ const res = await request(app()).get('/api/providers/management');
+ const body = JSON.stringify(res.body);
+
+ expect(res.status).toBe(200);
+ expect(res.body.connections[0].hasCredentials).toBe(true);
+ expect(body).not.toContain(TOKEN);
+ expect(res.body.connections[0]).not.toHaveProperty('credentials');
+ expect(res.body.routes[0]).not.toHaveProperty('projected');
+ expect(res.body.routes[0]).not.toHaveProperty('pending');
+ });
+});
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 3f9b42653f..8c54b7d7bb 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -4,8 +4,11 @@ import {
getManagementGraph,
linkBinding,
previewBindingLink,
+ refreshConnectionCatalog,
removeConnection,
unlinkBinding,
+ updateBindingSettings,
+ updateConnectionSettings,
} from '../services/providerGraph.js';
import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
@@ -23,6 +26,8 @@ import {
providerVisionSuiteSchema,
providerBindingLinkSchema,
providerBindingUnlinkSchema,
+ providerBindingUpdateSchema,
+ providerConnectionUpdateSchema,
} from '../lib/validation.js';
import {
getProviderRuntimeStatus,
@@ -345,6 +350,41 @@ export function createPortOSProviderRoutes(aiToolkit) {
res.json(await removeConnection(req.params.id));
}));
+ /**
+ * Edit one SHARED backend (#6369) — its label, transports and credentials —
+ * and materialize the result into every executable route on it.
+ *
+ * This is the edit the graph exists for: an endpoint or key changed once
+ * rather than retyped per harness. `expectedRevision` is required and
+ * re-checked inside the serialized pass, so an edit made against a row that
+ * has since moved is a 409 instead of a silent overwrite.
+ */
+ router.patch('/connections/:id', asyncHandler(async (req, res) => {
+ const input = validateRequest(providerConnectionUpdateSchema, req.body ?? {});
+ res.json(await updateConnectionSettings({ connectionId: req.params.id, ...input }));
+ }));
+
+ /**
+ * Refresh a connection's SHARED model catalog once for every harness on it.
+ *
+ * An explicit discovery request and nothing more: it lists models, it never
+ * generates, and a failed probe keeps the catalog the connection already had
+ * rather than reporting an empty backend.
+ */
+ router.post('/connections/:id/refresh-models', asyncHandler(async (req, res) => {
+ res.json(await refreshConnectionCatalog(req.params.id));
+ }));
+
+ /**
+ * Edit one harness binding's management state: its label and the subset of
+ * the shared catalog it offers. Never its routes' enablement or consent —
+ * those stay on `PATCH /api/providers/:id`, where granting them is explicit.
+ */
+ router.patch('/bindings/:id', asyncHandler(async (req, res) => {
+ const input = validateRequest(providerBindingUpdateSchema, req.body ?? {});
+ res.json(await updateBindingSettings({ bindingId: req.params.id, ...input }));
+ }));
+
router.get('/samples', asyncHandler(async (req, res) => {
const providers = await providerService.getSampleProviders();
const capabilities = await detectSystemCapabilities();
diff --git a/server/services/providerGraph.js b/server/services/providerGraph.js
index 4c20ace0f1..a3d209e4db 100644
--- a/server/services/providerGraph.js
+++ b/server/services/providerGraph.js
@@ -3,10 +3,14 @@ import { ServerError } from '../lib/errorHandler.js';
import { compareBackendEndpoints, withConnectionOwnedFields } from '../lib/providerConnections.js';
import {
connectionOwnedSnapshot,
+ mergeConnectionCredentials,
+ nextConnectionCatalog,
planGraphReconciliation,
reconciliationIsNoop,
+ sanitizeCatalogError,
toManagementGraphDto,
} from '../lib/providerGraphRecords.js';
+import { resolveRouteModels } from '../lib/providerGraphPreview.js';
import { requireToolkit } from '../lib/aiToolkitState.js';
import {
acknowledgeProjection,
@@ -16,6 +20,9 @@ import {
detachBindingToConnection,
readGraph,
relinkBinding,
+ saveBindingSettings,
+ saveConnectionSettings,
+ saveRouteModelMap,
} from './providerGraphStore.js';
/**
@@ -373,3 +380,168 @@ function ownedFromConnection(provider, connection) {
}
return { fields, envVars, hasEnvVars: owned.hasEnvVars };
}
+
+// --- explicit management edits (#6369) ---------------------------------------
+//
+// The three edits a human makes to a SHARED backend, as opposed to the link and
+// unlink above which change which backend a harness reaches:
+//
+// 1. edit the connection once and have every attached route follow it,
+// 2. refresh its model catalog once for every harness on it,
+// 3. choose the subset of that catalog a harness offers.
+//
+// All three are revision-checked against exactly what the human was looking at,
+// all three run on the same serialization queue as reconciliation, and none of
+// them contacts an AI provider except (3)'s explicitly requested model list.
+
+/** Locate a row the caller named, or 404. Never a partial match on a label. */
+function requireRow(rows, id, what, code) {
+ const row = rows.find((candidate) => candidate.id === id);
+ if (!row) throw new ServerError(`${what} not found`, { status: 404, code });
+ return row;
+}
+
+/**
+ * Refuse a mutation while any of these routes is mid-projection.
+ *
+ * That state is precisely where the graph and `providers.json` disagree, so an
+ * edit decided against it would be decided against unknown values. Same guard
+ * `resolveLink` applies, applied to the connection's whole route set.
+ */
+function requireSettledRoutes(routes) {
+ if (routes.some((route) => route.pending)) {
+ throw new ServerError('This connection has an unresolved projection and cannot be changed yet',
+ { status: 409, code: 'PROVIDER_GRAPH_BINDING_BLOCKED' });
+ }
+}
+
+/** Every binding on a connection, and the executable routes those bindings own. */
+function connectionFanout(graph, connectionId) {
+ const bindings = graph.bindings.filter((binding) => binding.connectionId === connectionId);
+ const bindingIds = new Set(bindings.map((binding) => binding.id));
+ return { bindings, routes: graph.routes.filter((route) => bindingIds.has(route.bindingId)) };
+}
+
+/**
+ * Edit one shared backend: its label, its transports, its credentials.
+ *
+ * This is the whole point of the graph — the endpoint and secret a human
+ * changes here are materialized into EVERY route on the connection in one
+ * projection, instead of being retyped per harness and drifting. Route ids,
+ * mode settings, pins, `activeProvider` and fallback references are untouched.
+ *
+ * A stale `expectedRevision` is a 409, not a last-writer merge: the human was
+ * editing values they had read, and a moved row means they were not.
+ */
+export function updateConnectionSettings({ connectionId, expectedRevision, label, transports, credentials }) {
+ return serialize(async () => {
+ requireGraph();
+ const graph = await readGraph();
+ const connection = requireRow(graph.connections, connectionId, 'Connection', 'CONNECTION_NOT_FOUND');
+ if (connection.revision !== expectedRevision) throw stale('The connection');
+ const { routes } = connectionFanout(graph, connection.id);
+ requireSettledRoutes(routes);
+
+ const merged = mergeConnectionCredentials(connection.credentials, credentials);
+ if (merged.rejected.length > 0) {
+ throw new ServerError(
+ `Send the real value or null for ${merged.rejected.join(', ')} — a redacted placeholder is not a credential`,
+ { status: 400, code: 'PROVIDER_GRAPH_REDACTED_CREDENTIAL' });
+ }
+
+ const next = {
+ ...connection,
+ label: label ?? connection.label,
+ transports: transports ?? connection.transports,
+ credentials: merged.credentials,
+ };
+ const revision = await saveConnectionSettings(next);
+ const applied = await projectRoutes(routes.map((route) => route.providerId), next);
+ console.log(`🔗 Updated connection ${connection.id} (${applied.length} routes projected)`);
+ return { connectionId: connection.id, revision, affectedRouteIds: applied };
+ });
+}
+
+/**
+ * Choose which of the shared catalog a harness offers, and rename the binding.
+ *
+ * Management state only — nothing here is projected into an executable record,
+ * so choosing a subset can never enable a route, grant a mode's execution
+ * consent, or repoint a saved selection. A pin outside the new subset stays
+ * exactly where it was and simply reads as stale, which is what keeps a
+ * narrowed catalog from silently repicking somebody's model.
+ */
+export function updateBindingSettings({ bindingId, expectedRevision, label, selectedModels }) {
+ return serialize(async () => {
+ requireGraph();
+ const graph = await readGraph();
+ const binding = requireRow(graph.bindings, bindingId, 'Binding', 'BINDING_NOT_FOUND');
+ if (binding.revision !== expectedRevision) throw stale('The binding');
+ requireSettledRoutes(graph.routes.filter((route) => route.bindingId === binding.id));
+
+ const revision = await saveBindingSettings({
+ id: binding.id,
+ label: label ?? binding.label,
+ selectedModels: selectedModels ?? binding.selectedModels,
+ });
+ return {
+ bindingId: binding.id,
+ revision,
+ label: label ?? binding.label,
+ selectedModels: selectedModels ?? binding.selectedModels,
+ };
+ });
+}
+
+/**
+ * Refresh the shared model catalog — ONE probe per backend, not one per route.
+ *
+ * `refreshProviderModelsBatch` groups the connection's routes by daemon and
+ * probe shape, so a connection carrying Claude CLI, Claude TUI and OpenCode
+ * routes is asked once and written once. It never throws for a per-route
+ * failure, which is what lets a partial answer stay a partial answer.
+ *
+ * The failure rule is the one this endpoint exists for: **a failed probe keeps
+ * the models the connection already knew**, with a sanitized reason attached.
+ * A successful probe that returns nothing writes `known` with an empty list —
+ * a backend whose last model was deleted is a real answer, not "never asked".
+ * No pin, default or `activeProvider` is repicked either way.
+ */
+export function refreshConnectionCatalog(connectionId) {
+ return serialize(async () => {
+ requireGraph();
+ const graph = await readGraph();
+ const connection = requireRow(graph.connections, connectionId, 'Connection', 'CONNECTION_NOT_FOUND');
+ const { routes } = connectionFanout(graph, connection.id);
+ if (routes.length === 0) {
+ throw new ServerError('This connection has no executable route to probe',
+ { status: 409, code: 'PROVIDER_GRAPH_CONNECTION_UNROUTED' });
+ }
+
+ const groups = await providerService().refreshProviderModelsBatch(routes.map((route) => route.providerId));
+ const failures = groups.filter((group) => group.status === 'failed');
+ const refreshed = groups.some((group) => group.status === 'updated');
+
+ // Canonical names come from the records as they are AFTER the write, so the
+ // catalog and each route's alias map describe the same observation.
+ const { providers } = await providerService().getAllProviders();
+ const byId = new Map(providers.map((provider) => [provider.id, provider]));
+ const models = [];
+ for (const route of routes) {
+ const provider = byId.get(route.providerId);
+ if (!provider) continue;
+ const { modelMap } = resolveRouteModels(provider);
+ await saveRouteModelMap(route.providerId, modelMap);
+ models.push(...Object.keys(modelMap));
+ }
+
+ const catalog = nextConnectionCatalog(connection.catalog, refreshed
+ ? { refreshed: true, models }
+ : { refreshed: false, error: sanitizeCatalogError(failures[0]?.error, connection.credentials) });
+ await saveConnectionSettings({ ...connection, catalog });
+
+ console.log(`🔗 Refreshed connection ${connection.id} catalog: ${catalog.state}, `
+ + `${catalog.models.length} models across ${groups.length} probe groups (${failures.length} failed)`);
+ return { connectionId: connection.id, catalog, probedGroups: groups.length, failedGroups: failures.length };
+ });
+}
diff --git a/server/services/providerGraphStore.js b/server/services/providerGraphStore.js
index 2376217588..bb303f95c2 100644
--- a/server/services/providerGraphStore.js
+++ b/server/services/providerGraphStore.js
@@ -247,3 +247,56 @@ export async function deleteConnection(connectionId) {
await query('DELETE FROM ai_connections WHERE id = $1', [connectionId]);
return { deleted: true };
}
+
+// --- explicit management mutations (#6369) -----------------------------------
+// Every function below is revision-checked and serialized by `providerGraph.js`
+// BEFORE it is called. They write a whole row rather than a computed SET list:
+// the caller already read the row it is replacing, so a partial-column update
+// would only add a second place for the merge rules to live.
+
+/**
+ * Write a connection's user-editable settings and bump its revision.
+ *
+ * `catalog` is written here too because a refresh is a connection-level edit,
+ * not a per-route one — see `refreshConnectionCatalog`.
+ *
+ * @returns {Promise<number|null>} the new revision, or `null` if the row is gone
+ */
+export async function saveConnectionSettings({ id, label, transports, credentials, catalog }) {
+ const { rows } = await query(
+ `UPDATE ai_connections
+ SET label = $2, transports = $3, credentials = $4, catalog = $5,
+ revision = revision + 1, updated_at = NOW()
+ WHERE id = $1
+ RETURNING revision`,
+ [id, label ?? '', JSON.stringify(transports || {}), JSON.stringify(credentials || {}),
+ JSON.stringify(catalog || { state: 'unknown', models: [] })],
+ );
+ return rows[0]?.revision ?? null;
+}
+
+/**
+ * Write a binding's management settings and bump its revision.
+ *
+ * Deliberately NOT `enabled`: route enablement is an executable-record field
+ * that `PATCH /api/providers/:id` owns, and projecting a binding-level toggle
+ * into it would turn a management edit into an execution consent grant.
+ *
+ * @returns {Promise<number|null>} the new revision, or `null` if the row is gone
+ */
+export async function saveBindingSettings({ id, label, selectedModels }) {
+ const { rows } = await query(
+ `UPDATE ai_harness_bindings
+ SET label = $2, selected_models = $3, revision = revision + 1, updated_at = NOW()
+ WHERE id = $1
+ RETURNING revision`,
+ [id, label ?? '', JSON.stringify(selectedModels || [])],
+ );
+ return rows[0]?.revision ?? null;
+}
+
+/** Record the canonical→executable model aliases a refresh observed on a route. */
+export async function saveRouteModelMap(providerId, modelMap) {
+ await query('UPDATE ai_route_bindings SET model_map = $2, updated_at = NOW() WHERE provider_id = $1',
+ [providerId, JSON.stringify(modelMap || {})]);
+}