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

simplify the AI Providers views after the cleanup review (#7567)

[._.]/ Adam Eivy73b7f8c38ded
diff --git a/client/src/components/providers/ProviderCompatibilityMatrix.jsx b/client/src/components/providers/ProviderCompatibilityMatrix.jsx
index 7f1280566d..2413641782 100644
--- a/client/src/components/providers/ProviderCompatibilityMatrix.jsx
+++ b/client/src/components/providers/ProviderCompatibilityMatrix.jsx
@@ -1,14 +1,17 @@
import { useMemo } from 'react';
import { Grid3x3 } from 'lucide-react';
import CollapsibleSection from '../ui/CollapsibleSection';
+import { serviceReadinessCopy } from '../../lib/providerManagement';
+import { pluralize } from '../../lib/textUtils';
/**
- * The compatibility matrix (#7567): harness rows × service columns, each cell
- * the server's own verdict on that pair. Rendered from `GET /api/providers/catalog`
- * — `compatibility[harnessId]` is `isCompatible` evaluated server-side, and
- * the two `enabled` flags plus the service's `readiness` are its rows — so the
- * browser recomputes nothing: a cell can only disagree with what compose
- * offers by the catalog being stale, never by a second predicate.
+ * The compatibility matrix (#7567): harness rows × service columns. Rendered
+ * from `GET /api/providers/catalog`: whether a pair is REACHABLE is
+ * `compatibility[harnessId]`, the server's own `isCompatible`, never
+ * re-derived here; whether a reachable pair is OFFERED reads the same three
+ * server fields the compose popover reads (`harness.enabled`,
+ * `service.enabled`, `service.readiness`), so a cell can only disagree with
+ * compose by the catalog being stale.
*
* Three cell states:
* - **offered** — compatible, both sides on, service ready: a click opens
@@ -19,20 +22,13 @@ import CollapsibleSection from '../ui/CollapsibleSection';
* - **incompatible** — the harness cannot reach that service at all.
*/
-const READINESS_REASON = {
- 'needs-credential': 'needs a credential',
- 'needs-endpoint': 'needs an endpoint',
- disabled: 'is switched off',
- 'unknown-definition': 'has no definition',
-};
-
/** The pure verdict per cell, exported so the page test can pin it without rendering. */
export function matrixCellState(harness, service, compatibility) {
if (!(compatibility?.[harness.id] || []).includes(service.slug)) return { state: 'incompatible', reason: null };
if (harness.enabled === false) return { state: 'blocked', reason: `${harness.label} is switched off` };
if (service.enabled === false) return { state: 'blocked', reason: `${service.label} is switched off` };
if (service.readiness && service.readiness !== 'ready') {
- return { state: 'blocked', reason: `${service.label} ${READINESS_REASON[service.readiness] || service.readiness}` };
+ return { state: 'blocked', reason: `${service.label} ${serviceReadinessCopy(service.readiness).reason}` };
}
return { state: 'offered', reason: null };
}
@@ -53,15 +49,20 @@ const CELL_GLYPH = { offered: '●', blocked: '◐', incompatible: '—' };
* @param {function} props.onCompose - `({ harnessId, method, serviceSlug }) => void` for an offered cell.
*/
export default function ProviderCompatibilityMatrix({ harnesses = [], services = [], compatibility = {}, loading = false, onCompose }) {
- const offered = useMemo(() => harnesses.reduce((count, harness) => count
- + services.filter((service) => matrixCellState(harness, service, compatibility).state === 'offered').length, 0), [harnesses, services, compatibility]);
+ // One pass over the product per catalog: the rows render from it and the
+ // summary counts it, on a page that re-renders on a 20s poll.
+ const rows = useMemo(() => harnesses.map((harness) => ({
+ harness,
+ cells: services.map((service) => ({ service, ...matrixCellState(harness, service, compatibility) })),
+ })), [harnesses, services, compatibility]);
+ const offered = useMemo(() => rows.reduce((count, row) => count + row.cells.filter((cell) => cell.state === 'offered').length, 0), [rows]);
return (
<CollapsibleSection
id="compatibility-matrix"
icon={Grid3x3}
label="Compatibility matrix"
- summary={loading ? 'Loading…' : `${offered} combination${offered === 1 ? '' : 's'} offered`}
+ summary={loading ? 'Loading…' : `${pluralize(offered, 'combination')} offered`}
defaultOpen={false}
size="md"
className="bg-port-card border border-port-border rounded-xl px-4 py-2"
@@ -83,13 +84,12 @@ export default function ProviderCompatibilityMatrix({ harnesses = [], services =
</tr>
</thead>
<tbody>
- {harnesses.map((harness) => (
+ {rows.map(({ harness, cells }) => (
<tr key={harness.id}>
<th scope="row" className="sticky left-0 bg-port-card text-left text-gray-300 font-medium pr-3 py-1 whitespace-nowrap">
{harness.label}{harness.enabled === false ? <span className="text-gray-600"> (off)</span> : null}
</th>
- {services.map((service) => {
- const { state, reason } = matrixCellState(harness, service, compatibility);
+ {cells.map(({ service, state, reason }) => {
const name = state === 'offered'
? `New preset: ${harness.label} on ${service.label}`
: state === 'blocked' ? `${harness.label} on ${service.label}: ${reason}` : `${harness.label} cannot reach ${service.label}`;
diff --git a/client/src/components/providers/ProviderComposePopover.jsx b/client/src/components/providers/ProviderComposePopover.jsx
index 62feb2644c..2e7bac7792 100644
--- a/client/src/components/providers/ProviderComposePopover.jsx
+++ b/client/src/components/providers/ProviderComposePopover.jsx
@@ -15,9 +15,10 @@
* @param {object} props
* @param {boolean} props.open
* @param {function} props.onClose
- * @param {function} props.onCompose - `(compositeId, { model, effort }) => void`.
+ * @param {function} [props.onCompose] - `(compositeId, { model, effort }) => void`.
* Called for "Use once" — the caller stores the composite id in its existing
* `{ providerId, model, effort }` field; nothing is persisted server-side.
+ * Omit it with `useOnce={false}`.
* @param {function} [props.onPresetSaved] - `(presetRecord) => void`. Called
* after "Save as preset" succeeds, so the caller can select the new preset
* id in place of the composite.
@@ -39,18 +40,10 @@ import { FormField } from '../ui/FormField.jsx';
import EffortSelect from '../cos/EffortSelect.jsx';
import useProviderCatalog from '../../hooks/useProviderCatalog.js';
import { useAsyncAction } from '../../hooks/useAsyncAction.js';
+import { serviceReadinessCopy } from '../../lib/providerManagement.js';
const SELECT_CLASS = 'w-full px-3 py-1.5 min-h-[36px] bg-port-bg border border-port-border rounded-lg text-white text-sm';
-/** The readiness line under the service select: harness detection + service credential/daemon state. */
-const READINESS_LABEL = {
- ready: 'ready to run',
- 'needs-credential': 'needs a credential',
- 'needs-endpoint': 'needs an endpoint',
- disabled: 'switched off',
- 'unknown-definition': 'unknown service definition',
-};
-
export default function ProviderComposePopover({
open,
onClose,
@@ -214,7 +207,7 @@ export default function ProviderComposePopover({
{selectedService && (
<p className="text-xs text-gray-500 mt-1">
{selectedHarness?.detected === false ? `${selectedHarness.label} not detected on this machine — ` : ''}
- {READINESS_LABEL[selectedService.readiness] || selectedService.readiness}
+ {serviceReadinessCopy(selectedService.readiness).reason}
</p>
)}
</FormField>
@@ -285,7 +278,7 @@ export default function ProviderComposePopover({
type="button"
className="flex-1 px-3 py-1.5 rounded-lg bg-port-bg border border-port-border text-white text-sm hover:bg-port-border disabled:opacity-50"
disabled={!canCompose}
- onClick={() => { onCompose(compositeId, { model, effort }); onClose(); }}
+ onClick={() => { onCompose?.(compositeId, { model, effort }); onClose(); }}
>
Use once
</button>
diff --git a/client/src/components/providers/ProviderCredentialBootstraps.jsx b/client/src/components/providers/ProviderCredentialBootstraps.jsx
index 84a3f75405..8e02c7f8e2 100644
--- a/client/src/components/providers/ProviderCredentialBootstraps.jsx
+++ b/client/src/components/providers/ProviderCredentialBootstraps.jsx
@@ -5,10 +5,13 @@ import Banner from '../ui/Banner';
import CollapsibleSection from '../ui/CollapsibleSection';
import InlineConfirmRow from '../ui/InlineConfirmRow';
import { FormField } from '../ui/FormField';
+import { INPUT_CLASS } from '../apps/constants';
import useConfirmDelete from '../../hooks/useConfirmDelete';
import * as api from '../../services/api';
import { invalidateProviderCatalog } from '../../hooks/useProviderCatalog';
+import { pluralize } from '../../lib/textUtils';
import { formatCount } from '../../utils/formatters';
+import { SERVICE_SLUG_RE } from '../../../../server/lib/serviceDefinitions.js';
/**
* Credential-bootstrap apps (#7564 → #7567): the launch wrappers a composite
@@ -22,8 +25,8 @@ import { formatCount } from '../../utils/formatters';
* the harness cards.
*/
-const SLUG_RE = /^[a-z0-9][a-z0-9-]*$/;
-const INPUT_CLASS = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden';
+// The same rule the server validates the table with (`credentialBootstrapsSettingsSchema`).
+const SLUG_PATTERN = SERVICE_SLUG_RE.source.slice(1, -1);
const EMPTY_DRAFT = Object.freeze({
slug: '', label: '', command: '', args: '', argsSeparator: '', setupCommand: '', harnessNames: {},
@@ -67,7 +70,7 @@ function BootstrapForm({ draft, editing, harnesses, busy, onChange, onSubmit, on
>
<div className="grid gap-3 grid-cols-[repeat(auto-fit,minmax(min(100%,14rem),1fr))]">
<FormField label="Slug *" hint="Lowercase letters, digits, dashes — the `+<slug>` a composite id carries" compact>
- <input id="bootstrap-slug" type="text" value={draft.slug} onChange={set('slug')} disabled={editing} required pattern="[a-z0-9][a-z0-9-]*" className={INPUT_CLASS} placeholder="corp-auth" />
+ <input id="bootstrap-slug" type="text" value={draft.slug} onChange={set('slug')} disabled={editing} required pattern={SLUG_PATTERN} className={INPUT_CLASS} placeholder="corp-auth" />
</FormField>
<FormField label="Label *" compact>
<input id="bootstrap-label" type="text" value={draft.label} onChange={set('label')} required className={INPUT_CLASS} placeholder="Corp auth wrapper" />
@@ -88,7 +91,7 @@ function BootstrapForm({ draft, editing, harnesses, busy, onChange, onSubmit, on
<fieldset>
<legend className="text-xs text-gray-400 mb-1">Harness names the wrapper knows (only where they differ from the binary)</legend>
<div className="grid gap-2 grid-cols-[repeat(auto-fit,minmax(min(100%,12rem),1fr))]">
- {harnesses.filter((harness) => harness.id !== 'direct').map((harness) => (
+ {harnesses.filter((harness) => harness.source !== 'always').map((harness) => (
<label key={harness.id} htmlFor={`bootstrap-harness-${harness.id}`} className="text-xs text-gray-400">
<span className="block mb-0.5">{harness.label}</span>
<input
@@ -174,7 +177,7 @@ export default function ProviderCredentialBootstraps({ harnesses = [], presets =
const submit = async () => {
if (!draft) return;
const slug = draft.slug.trim();
- if (!SLUG_RE.test(slug)) {
+ if (!SERVICE_SLUG_RE.test(slug)) {
toast.error('A bootstrap slug is lowercase letters, digits and dashes, starting with a letter or digit');
return;
}
@@ -221,7 +224,7 @@ export default function ProviderCredentialBootstraps({ harnesses = [], presets =
</p>
{app.setupCommand && <p className="text-xs text-gray-500">Setup: <code className="font-mono">{app.setupCommand}</code></p>}
<p className="text-xs text-gray-500">
- Used by {formatCount(usedBy[slug] || 0, { fallback: '0' })} preset{(usedBy[slug] || 0) === 1 ? '' : 's'}
+ Used by {pluralize(usedBy[slug] || 0, 'preset')}
{app.harnessNames && Object.keys(app.harnessNames).length > 0
? ` · names: ${Object.entries(app.harnessNames).map(([id, name]) => `${id}→${name}`).join(', ')}`
: ''}
diff --git a/client/src/components/providers/ProviderHarnessesTab.jsx b/client/src/components/providers/ProviderHarnessesTab.jsx
index b6f920d1ba..b94d612aca 100644
--- a/client/src/components/providers/ProviderHarnessesTab.jsx
+++ b/client/src/components/providers/ProviderHarnessesTab.jsx
@@ -4,9 +4,12 @@ import { CheckCircle2, Download, ExternalLink, Gauge, PowerOff, TerminalSquare }
import toast from '../ui/Toast';
import Pill from '../ui/Pill';
import Banner from '../ui/Banner';
+import ToggleSwitch from '../ToggleSwitch';
import * as api from '../../services/api';
import useProviderCatalog, { invalidateProviderCatalog } from '../../hooks/useProviderCatalog';
-import { formatCount } from '../../utils/formatters';
+import { pluralize } from '../../lib/textUtils';
+import { serviceReadinessCopy } from '../../lib/providerManagement';
+import { providerHarnessId } from '../../utils/providerHarnesses';
import ProviderCredentialBootstraps from './ProviderCredentialBootstraps';
/**
@@ -36,26 +39,16 @@ const METHOD_LABEL = { cli: 'CLI', tui: 'TUI', api: 'API' };
/** Every harness whose vendor bills a subscription quota the Quota Burn page tracks. */
const QUOTA_TRACKED = new Set(['claude', 'codex', 'grok', 'antigravity']);
-/** How a ChatGPT / Codex sign-in state reads on the harness card. */
-const CODEX_STATUS_COPY = {
- ready: 'ChatGPT subscription signed in',
- 'signed-out': 'ChatGPT subscription signed out',
- 'login-pending': 'ChatGPT sign-in in progress',
- 'quota-exhausted': 'ChatGPT usage limit reached',
- 'runtime-missing': 'Codex CLI not installed',
-};
-
function HarnessCard({
- harness, runtime, compatibleCount, presetCount, selected, busy,
- codexAccount, onToggle, onInstallRuntime,
+ harness, runtime, compatibleCount, presetCount, subscription, selected, busy, onToggle, onInstallRuntime,
}) {
const ref = useRef(null);
useEffect(() => {
if (selected) ref.current?.scrollIntoView?.({ block: 'nearest' });
}, [selected]);
- const isDirect = harness.id === 'direct';
- const switchId = `harness-enabled-${harness.id}`;
- const codexStatus = harness.id === 'codex' && codexAccount ? codexAccount.status : null;
+ // `always` is the catalog's word for a harness with nothing to switch off or
+ // install — PortOS's own runner — so no id is special-cased here.
+ const alwaysOn = harness.source === 'always';
return (
<article
@@ -72,22 +65,19 @@ function HarnessCard({
</h3>
<p className="mt-1 text-xs text-gray-500">{SOURCE_COPY[harness.source] || ''}</p>
</div>
- {isDirect ? (
+ {alwaysOn ? (
<Pill tone="success" size="xs" icon={CheckCircle2}>Always on</Pill>
) : (
- <label htmlFor={switchId} className="flex items-center gap-2 text-sm text-gray-300 cursor-pointer">
- <input
- id={switchId}
- type="checkbox"
- role="switch"
- aria-checked={harness.enabled}
- checked={harness.enabled}
+ <span className="flex items-center gap-2 text-sm text-gray-300">
+ <ToggleSwitch
+ size="sm"
+ enabled={harness.enabled}
disabled={busy}
- onChange={(e) => onToggle(harness, e.target.checked)}
- className="h-4 w-4 accent-port-accent"
+ ariaLabel={`${harness.enabled ? 'Disable' : 'Enable'} ${harness.label}`}
+ onChange={() => onToggle(harness, !harness.enabled)}
/>
{harness.enabled ? 'Enabled' : 'Disabled'}
- </label>
+ </span>
)}
</div>
@@ -95,16 +85,12 @@ function HarnessCard({
{harness.modes.map((mode) => (
<Pill key={mode} tone="muted" size="xs" mono>{METHOD_LABEL[mode] || mode}</Pill>
))}
- <span className="text-gray-400">
- {formatCount(compatibleCount, { fallback: '0' })} compatible service{compatibleCount === 1 ? '' : 's'}
- </span>
+ <span className="text-gray-400">{pluralize(compatibleCount, 'compatible service')}</span>
<span className="text-gray-500">·</span>
- <span className="text-gray-400">
- {formatCount(presetCount, { fallback: '0' })} preset{presetCount === 1 ? '' : 's'}
- </span>
+ <span className="text-gray-400">{pluralize(presetCount, 'preset')}</span>
</div>
- {!isDirect && (
+ {!alwaysOn && (
<div className="flex flex-wrap items-center gap-2 text-xs">
{harness.detected === true && (
<Pill tone="success" size="xs" icon={CheckCircle2}>
@@ -136,12 +122,17 @@ function HarnessCard({
</div>
)}
- {codexStatus && (
+ {/* The subscription service only this program can reach: its sign-in
+ lives inside the harness, so the card says how that service stands
+ and where to manage it. Vendor-agnostic — any definition declaring
+ `harnessOnly` for this harness lands here. */}
+ {subscription && (
<p className="text-xs text-gray-400">
- {CODEX_STATUS_COPY[codexStatus] || `ChatGPT subscription: ${codexStatus}`}
- {codexAccount.planType ? ` (${codexAccount.planType})` : ''}
- {' — '}
- <Link to="/ai/presets" className="text-port-accent hover:underline">sign in from the Codex preset card</Link>
+ Subscription:{' '}
+ <Link to={`/ai/services/${encodeURIComponent(subscription.slug)}`} className="text-port-accent hover:underline">
+ {subscription.label}
+ </Link>
+ {' — '}{serviceReadinessCopy(subscription.readiness).reason}
</p>
)}
</article>
@@ -153,9 +144,8 @@ function HarnessCard({
* @param {string|null} props.selectedHarnessId - from `/ai/harnesses/:harnessId`; highlighted and scrolled to.
* @param {object} props.runtimes - the `GET /providers/runtimes` map (by binary id).
* @param {function} props.onInstallRuntime - opens the page's install modal for one runtime row.
- * @param {object} [props.codexAccount] - the ChatGPT account readiness the page already polls.
*/
-export default function ProviderHarnessesTab({ selectedHarnessId = null, runtimes = {}, onInstallRuntime, codexAccount }) {
+export default function ProviderHarnessesTab({ selectedHarnessId = null, runtimes = {}, onInstallRuntime }) {
const navigate = useNavigate();
const catalog = useProviderCatalog(true);
const [pending, setPending] = useState({});
@@ -165,14 +155,19 @@ export default function ProviderHarnessesTab({ selectedHarnessId = null, runtime
Object.values(runtimes).filter((row) => row?.vendor).map((row) => [row.vendor, row]),
), [runtimes]);
+ // The same classification the Presets view groups by, so the two counts agree
+ // on a legacy record the backfill has not stamped.
const presetCountByHarness = useMemo(() => {
const counts = {};
for (const preset of catalog.presets || []) {
- const id = preset.harnessId || (preset.type === 'api' ? 'direct' : null);
+ const id = providerHarnessId(preset);
if (id) counts[id] = (counts[id] || 0) + 1;
}
return counts;
}, [catalog.presets]);
+ const subscriptionByHarness = useMemo(() => Object.fromEntries(
+ (catalog.services || []).filter((service) => service.definition?.harnessOnly).map((service) => [service.definition.harnessOnly, service]),
+ ), [catalog.services]);
const known = catalog.harnesses.some((harness) => harness.id === selectedHarnessId);
useEffect(() => {
@@ -212,9 +207,9 @@ export default function ProviderHarnessesTab({ selectedHarnessId = null, runtime
runtime={runtimeByHarness[harness.id] || null}
compatibleCount={catalog.compatiblePairs(harness.id).length}
presetCount={presetCountByHarness[harness.id] || 0}
+ subscription={subscriptionByHarness[harness.id] || null}
selected={harness.id === selectedHarnessId}
busy={Boolean(pending[harness.id])}
- codexAccount={codexAccount}
onToggle={handleToggle}
onInstallRuntime={onInstallRuntime}
/>
diff --git a/client/src/components/providers/ProviderHarnessesTab.test.jsx b/client/src/components/providers/ProviderHarnessesTab.test.jsx
index a8b491f1a7..e569c3f060 100644
--- a/client/src/components/providers/ProviderHarnessesTab.test.jsx
+++ b/client/src/components/providers/ProviderHarnessesTab.test.jsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
-import { render, screen, fireEvent, waitFor } from '@testing-library/react';
+import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';
import { MemoryRouter, Route, Routes, useLocation } from 'react-router';
import { __resetProviderCatalogCache } from '../../hooks/useProviderCatalog';
@@ -34,9 +34,10 @@ const CATALOG = {
services: [
{ slug: 'nvidia-nim', label: 'NVIDIA NIM', plan: 'free', enabled: true, readiness: 'ready', catalog: { models: [] } },
{ slug: 'ollama', label: 'Ollama', plan: 'local', enabled: true, readiness: 'ready', catalog: { models: [] } },
+ { slug: 'claude-subscription', label: 'Claude subscription', plan: 'subscription', enabled: true, readiness: 'ready', catalog: { models: [] }, definition: { id: 'claude-subscription', family: 'subscription', harnessOnly: 'claude' } },
],
bootstraps: [],
- compatibility: { claude: ['ollama'], pi: ['nvidia-nim', 'ollama'], direct: ['nvidia-nim', 'ollama'] },
+ compatibility: { claude: ['ollama', 'claude-subscription'], pi: ['nvidia-nim', 'ollama'], direct: ['nvidia-nim', 'ollama'] },
effortLevels: {},
effortLevelsByModel: {},
presets: [
@@ -83,9 +84,12 @@ describe('ProviderHarnessesTab', () => {
renderTab();
expect(await screen.findByRole('heading', { name: /Claude Code/ })).toBeInTheDocument();
const claude = screen.getByRole('article', { name: /Claude Code/ });
- expect(claude).toHaveTextContent('1 compatible service');
+ expect(claude).toHaveTextContent('2 compatible services');
expect(claude).toHaveTextContent('1 preset');
expect(claude).toHaveTextContent('Installed · 2.1.0');
+ // The subscription only this program reaches is named with its state and linked.
+ expect(within(claude).getByRole('link', { name: 'Claude subscription' })).toHaveAttribute('href', '/ai/services/claude-subscription');
+ expect(claude).toHaveTextContent('ready to run');
const pi = screen.getByRole('article', { name: /^Pi/ });
expect(pi).toHaveTextContent('2 compatible services');
expect(pi).toHaveTextContent('Binary not found');
@@ -106,8 +110,8 @@ describe('ProviderHarnessesTab', () => {
const enabled = { ...CATALOG, harnesses: CATALOG.harnesses.map((h) => (h.id === 'pi' ? { ...h, enabled: true } : h)) };
renderTab();
const pi = await screen.findByRole('article', { name: /^Pi/ });
- const toggle = pi.querySelector('input[role="switch"]');
- expect(toggle.checked).toBe(false);
+ const toggle = within(pi).getByRole('switch');
+ expect(toggle).toHaveAttribute('aria-checked', 'false');
api.getProviderCatalog.mockResolvedValue(enabled);
fireEvent.click(toggle);
@@ -115,7 +119,7 @@ describe('ProviderHarnessesTab', () => {
await waitFor(() => expect(api.setProviderHarnessEnabled).toHaveBeenCalledWith('pi', true, { silent: true }));
// Second catalog fetch = the invalidation reached the shared hook.
await waitFor(() => expect(api.getProviderCatalog).toHaveBeenCalledTimes(2));
- await waitFor(() => expect(pi.querySelector('input[role="switch"]').checked).toBe(true));
+ await waitFor(() => expect(within(pi).getByRole('switch')).toHaveAttribute('aria-checked', 'true'));
expect(toast.success).toHaveBeenCalledWith(expect.stringMatching(/Pi enabled/));
});
@@ -123,10 +127,10 @@ describe('ProviderHarnessesTab', () => {
api.setProviderHarnessEnabled.mockRejectedValue(new Error('boom'));
renderTab();
const pi = await screen.findByRole('article', { name: /^Pi/ });
- fireEvent.click(pi.querySelector('input[role="switch"]'));
+ fireEvent.click(within(pi).getByRole('switch'));
await waitFor(() => expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/Could not enable Pi/)));
expect(api.getProviderCatalog).toHaveBeenCalledTimes(1);
- expect(pi.querySelector('input[role="switch"]').checked).toBe(false);
+ expect(within(pi).getByRole('switch')).toHaveAttribute('aria-checked', 'false');
});
it('offers the install for a missing binary whose runtime row allows it', async () => {
@@ -160,7 +164,8 @@ describe('credential bootstraps section', () => {
api.saveProviderBootstraps.mockImplementation(async (bootstraps) => ({ bootstraps }));
renderTab();
const header = await screen.findByRole('button', { name: /Credential bootstraps/ });
- expect(header).toHaveAttribute('aria-expanded', 'true');
+ // The table arrives after mount; the section opens once it holds a row.
+ await waitFor(() => expect(header).toHaveAttribute('aria-expanded', 'true'));
expect(screen.getByText('Corp auth').closest('li')).toHaveTextContent('Used by 1 preset');
fireEvent.click(screen.getByRole('button', { name: 'Add bootstrap' }));
diff --git a/client/src/components/providers/ProviderPageTabs.jsx b/client/src/components/providers/ProviderPageTabs.jsx
index 84cf7444f5..ac6b924608 100644
--- a/client/src/components/providers/ProviderPageTabs.jsx
+++ b/client/src/components/providers/ProviderPageTabs.jsx
@@ -18,12 +18,10 @@ export const PROVIDER_PAGE_TABS = Object.freeze([
{ id: 'services', label: 'Services', to: '/ai/services' },
]);
-/** Which view a pathname under `/ai` opens. The index and every overlay off it are presets. */
+/** Which view a pathname under `/ai` opens: the tab whose route prefixes it, else presets (the index and every overlay off it). */
export const providerPageTabForPath = (pathname) => {
const bare = String(pathname || '').replace(/\/+$/, '');
- if (/^\/ai\/harnesses(\/|$)/.test(bare)) return 'harnesses';
- if (/^\/ai\/services(\/|$)/.test(bare)) return 'services';
- return 'presets';
+ return PROVIDER_PAGE_TABS.find((tab) => bare === tab.to || bare.startsWith(`${tab.to}/`))?.id ?? 'presets';
};
export default function ProviderPageTabs({ activeTab }) {
diff --git a/client/src/components/providers/ProviderServiceForm.jsx b/client/src/components/providers/ProviderServiceForm.jsx
index b7aa8e56c1..6ec02829c5 100644
--- a/client/src/components/providers/ProviderServiceForm.jsx
+++ b/client/src/components/providers/ProviderServiceForm.jsx
@@ -4,7 +4,10 @@ import toast from '../ui/Toast';
import Drawer from '../Drawer';
import Banner from '../ui/Banner';
import { FormField } from '../ui/FormField';
+import { INPUT_CLASS } from '../apps/constants';
import * as api from '../../services/api';
+import { SERVICE_SLUG_RE } from '../../../../server/lib/serviceDefinitions.js';
+import { transportsFromDraft } from '../../lib/providerManagement';
/**
* "Add service" (#7567): definition → plan → credential / endpoint, in that
@@ -30,7 +33,8 @@ const FAMILY_LABEL = {
fleet: 'Fleet hosts',
};
const PLAN_LABEL = { free: 'Free tier', paid: 'Paid / metered', subscription: 'Subscription', local: 'Local (no billing)' };
-const INPUT_CLASS = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden';
+// The static `/ai/services/new` route would shadow a card addressed by this slug.
+const RESERVED_SLUGS = new Set(['new']);
const EMPTY_DRAFT = Object.freeze({ definitionId: '', plan: '', label: '', slug: '', transports: {}, apiKey: '', credentialVia: 'stored' });
@@ -43,6 +47,7 @@ export default function ProviderServiceForm({ onClose, onCreated }) {
const [definitions, setDefinitions] = useState(null); // null = not fetched yet
const [draft, setDraft] = useState(EMPTY_DRAFT);
const [busy, setBusy] = useState(false);
+ const set = (key) => (e) => setDraft((prev) => ({ ...prev, [key]: e.target.value }));
useEffect(() => {
let active = true;
@@ -79,9 +84,11 @@ export default function ProviderServiceForm({ onClose, onCreated }) {
toast.error('This service declares no default endpoint — enter the one this install reaches it at');
return;
}
- const transports = Object.fromEntries(declaredTransports
- .filter(([, baseUrl]) => baseUrl.trim())
- .map(([protocol, baseUrl]) => [protocol, { baseUrl: baseUrl.trim() }]));
+ if (RESERVED_SLUGS.has(draft.slug.trim())) {
+ toast.error(`"${draft.slug.trim()}" is reserved by the page's own routes — pick another slug`);
+ return;
+ }
+ const transports = transportsFromDraft(draft.transports);
const body = {
definitionId: definition.id,
plan: draft.plan || undefined,
@@ -128,7 +135,7 @@ export default function ProviderServiceForm({ onClose, onCreated }) {
{definition && (
<>
<FormField label="Plan *" hint="What you are entitled to on it — decides which models the catalog keeps and how cost is attributed">
- <select id="service-plan" value={draft.plan} onChange={(e) => setDraft((prev) => ({ ...prev, plan: e.target.value }))} className={INPUT_CLASS}>
+ <select id="service-plan" value={draft.plan} onChange={set('plan')} className={INPUT_CLASS}>
{definition.plans.map((plan) => <option key={plan} value={plan}>{PLAN_LABEL[plan] || plan}</option>)}
</select>
</FormField>
@@ -165,7 +172,7 @@ export default function ProviderServiceForm({ onClose, onCreated }) {
type="password"
autoComplete="off"
value={draft.apiKey}
- onChange={(e) => setDraft((prev) => ({ ...prev, apiKey: e.target.value }))}
+ onChange={set('apiKey')}
className={INPUT_CLASS}
placeholder="Paste the key, or leave blank to add it later"
/>
@@ -199,10 +206,10 @@ export default function ProviderServiceForm({ onClose, onCreated }) {
<div className="grid gap-3 sm:grid-cols-2">
<FormField label="Label" hint={`Defaults to "${definition.label}"`} compact>
- <input id="service-label" type="text" value={draft.label} onChange={(e) => setDraft((prev) => ({ ...prev, label: e.target.value }))} className={INPUT_CLASS} />
+ <input id="service-label" type="text" value={draft.label} onChange={set('label')} className={INPUT_CLASS} />
</FormField>
<FormField label="Slug" hint={`The address a composite id names; defaults to "${definition.id}"`} compact>
- <input id="service-slug" type="text" value={draft.slug} pattern="[a-z0-9][a-z0-9-]*" onChange={(e) => setDraft((prev) => ({ ...prev, slug: e.target.value }))} className={INPUT_CLASS} placeholder={definition.id} />
+ <input id="service-slug" type="text" value={draft.slug} pattern={SERVICE_SLUG_RE.source.slice(1, -1)} onChange={set('slug')} className={INPUT_CLASS} placeholder={definition.id} />
</FormField>
</div>
</>
diff --git a/client/src/components/providers/ProviderServicesTab.jsx b/client/src/components/providers/ProviderServicesTab.jsx
index df83db907d..1894f58658 100644
--- a/client/src/components/providers/ProviderServicesTab.jsx
+++ b/client/src/components/providers/ProviderServicesTab.jsx
@@ -7,9 +7,12 @@ import Pill from '../ui/Pill';
import EmptyState from '../EmptyState';
import InlineConfirmRow from '../ui/InlineConfirmRow';
import { FormField } from '../ui/FormField';
+import ToggleSwitch from '../ToggleSwitch';
+import { INPUT_CLASS } from '../apps/constants';
import * as api from '../../services/api';
import { invalidateProviderCatalog } from '../../hooks/useProviderCatalog';
-import { catalogSummary } from '../../lib/providerManagement';
+import { catalogSummary, draftFromTransports, serviceReadinessCopy, transportsFromDraft } from '../../lib/providerManagement';
+import { pluralize } from '../../lib/textUtils';
import { formatCount } from '../../utils/formatters';
import ProviderReadiness from './ProviderReadiness';
import ProviderServiceForm from './ProviderServiceForm';
@@ -31,13 +34,6 @@ import { presetEditPath } from '../../utils/providerHarnesses';
*/
const PLAN_TONE = { free: 'success', paid: 'warning', subscription: 'accent', local: 'muted' };
-const READINESS_COPY = {
- ready: { tone: 'success', text: 'Ready' },
- disabled: { tone: 'muted', text: 'Switched off' },
- 'needs-endpoint': { tone: 'warning', text: 'Needs an endpoint' },
- 'needs-credential': { tone: 'warning', text: 'Needs a credential' },
- 'unknown-definition': { tone: 'muted', text: 'No definition' },
-};
const CREDENTIAL_SOURCE_COPY = {
settings: 'Key stored on this service',
env: 'Key read from the environment',
@@ -47,19 +43,15 @@ const CREDENTIAL_SOURCE_COPY = {
none: 'No key',
};
const CATALOG_TONE_CLASS = { error: 'text-port-error', ok: 'text-port-success', warn: 'text-port-warning', muted: 'text-gray-500' };
-const INPUT_CLASS = 'w-full px-3 py-2 bg-port-bg border border-port-border rounded-lg text-white text-sm focus:border-port-accent focus:outline-hidden';
const serviceName = (service) => service.label || service.slug || service.id;
const serviceRef = (service) => service.slug || service.id;
-const draftFrom = (service) => ({
- label: service.label || '',
- transports: Object.fromEntries(Object.entries(service.transports || {}).map(([protocol, value]) => [protocol, value?.baseUrl || ''])),
- apiKey: '',
-});
+const draftFrom = (service) => ({ label: service.label || '', transports: draftFromTransports(service.transports), apiKey: '' });
function ServiceCard({
- service, open, busy, presets, readiness, readinessActions, onSelect, onToggle, onRefresh, onSave, onClearKey, onDelete,
+ service, open, busy, presets, subject, readiness, servingModel, onAutoSetup, onUseServedModel, onServeWantedModel,
+ onSelect, onToggle, onRefresh, onSave, onClearKey, onDelete,
}) {
const ref = useRef(null);
useEffect(() => {
@@ -70,10 +62,11 @@ function ServiceCard({
const [draft, setDraft] = useState(() => draftFrom(service));
useEffect(() => { setDraft(draftFrom(service)); }, [service.id, service.revision]); // eslint-disable-line react-hooks/exhaustive-deps
const [confirmingDelete, setConfirmingDelete] = useState(false);
+ const set = (key) => (e) => setDraft((prev) => ({ ...prev, [key]: e.target.value }));
+ const setTransport = (protocol) => (e) => setDraft((prev) => ({ ...prev, transports: { ...prev.transports, [protocol]: e.target.value } }));
const summary = catalogSummary(service.catalog);
- const readinessCopy = READINESS_COPY[service.readiness] || READINESS_COPY['unknown-definition'];
- const switchId = `service-enabled-${service.id}`;
+ const readinessCopy = serviceReadinessCopy(service.readiness);
const slug = serviceRef(service);
const definition = service.definition;
@@ -98,23 +91,20 @@ function ServiceCard({
<p className="mt-1 text-xs text-gray-400 flex flex-wrap items-center gap-2">
<span>{definition?.label || service.kind}</span>
<Pill tone={PLAN_TONE[service.plan] || 'muted'} size="xs">{service.plan}</Pill>
- <Pill tone={readinessCopy.tone} size="xs">{readinessCopy.text}</Pill>
+ <Pill tone={readinessCopy.tone} size="xs">{readinessCopy.label}</Pill>
<span className={CATALOG_TONE_CLASS[summary.tone]}>{summary.text}</span>
</p>
</button>
- <label htmlFor={switchId} className="flex items-center gap-2 text-sm text-gray-300 cursor-pointer shrink-0">
- <input
- id={switchId}
- type="checkbox"
- role="switch"
- aria-checked={service.enabled}
- checked={service.enabled}
+ <span className="flex items-center gap-2 text-sm text-gray-300 shrink-0">
+ <ToggleSwitch
+ size="sm"
+ enabled={service.enabled}
disabled={busy}
- onChange={(e) => onToggle(service, e.target.checked)}
- className="h-4 w-4 accent-port-accent"
+ ariaLabel={`${service.enabled ? 'Disable' : 'Enable'} ${serviceName(service)}`}
+ onChange={() => onToggle(service, !service.enabled)}
/>
{service.enabled ? 'Enabled' : 'Disabled'}
- </label>
+ </span>
</div>
{open && (
@@ -135,7 +125,7 @@ function ServiceCard({
<div className="grid gap-3 grid-cols-[repeat(auto-fit,minmax(min(100%,16rem),1fr))]">
<FormField label="Name" compact>
- <input id={`service-label-${service.id}`} type="text" value={draft.label} onChange={(e) => setDraft((prev) => ({ ...prev, label: e.target.value }))} className={INPUT_CLASS} />
+ <input id={`service-label-${service.id}`} type="text" value={draft.label} onChange={set('label')} className={INPUT_CLASS} />
</FormField>
{Object.entries(draft.transports).map(([protocol, baseUrl]) => (
<FormField key={protocol} label={`${protocol} endpoint`} compact>
@@ -143,7 +133,7 @@ function ServiceCard({
id={`service-${service.id}-${protocol}`}
type="text"
value={baseUrl}
- onChange={(e) => setDraft((prev) => ({ ...prev, transports: { ...prev.transports, [protocol]: e.target.value } }))}
+ onChange={setTransport(protocol)}
className={INPUT_CLASS}
/>
</FormField>
@@ -155,7 +145,7 @@ function ServiceCard({
type="password"
autoComplete="off"
value={draft.apiKey}
- onChange={(e) => setDraft((prev) => ({ ...prev, apiKey: e.target.value }))}
+ onChange={set('apiKey')}
placeholder={service.hasCredentials ? 'Unchanged' : 'Not set'}
className={INPUT_CLASS}
/>
@@ -194,13 +184,16 @@ function ServiceCard({
/>
)}
- {readiness && (
+ {/* Local-daemon readiness is computed per PRESET; `subject` is the
+ first derived preset on this instance, standing for the daemon
+ they all share. Same wiring as the preset card. */}
+ {subject && readiness && (
<ProviderReadiness
readiness={readiness}
- onAutoSetup={readinessActions.onAutoSetup}
- onUseServedModel={readinessActions.onUseServedModel}
- onServeWantedModel={readinessActions.onServeWantedModel}
- serving={readinessActions.serving}
+ onAutoSetup={(setup) => onAutoSetup?.({ ...setup, providerId: subject.id })}
+ onUseServedModel={(modelId) => onUseServedModel?.(subject, modelId)}
+ onServeWantedModel={onServeWantedModel ? () => onServeWantedModel(subject) : undefined}
+ serving={Boolean(servingModel?.[subject.id])}
optional={!service.enabled}
/>
)}
@@ -214,7 +207,7 @@ function ServiceCard({
<div>
<h4 className="text-xs uppercase tracking-wide text-gray-500 mb-1">
- Presets on this service ({formatCount(presets.length, { fallback: '0' })})
+ Presets on this service ({formatCount(presets.length)})
</h4>
{presets.length === 0 ? (
<p className="text-xs text-gray-500">
@@ -245,11 +238,15 @@ function ServiceCard({
* @param {boolean} props.creating - `/ai/services/new`: the add drawer is open.
* @param {object[]} props.presets - the page's provider list, for "presets on this service" and the readiness subject.
* @param {object} props.readiness - the page's local-daemon readiness map, keyed by preset id.
- * @param {object} props.readinessActions - `{ onAutoSetup, onUseServedModel, onServeWantedModel, servingModel }` from the page.
+ * @param {function} [props.onAutoSetup] - the page's readiness handlers, as the preset card takes them.
+ * @param {function} [props.onUseServedModel]
+ * @param {function} [props.onServeWantedModel]
+ * @param {object} [props.servingModel] - preset id → relaunch in flight.
* @param {function} props.onChanged - a service write may re-materialize derived presets; the page reloads them.
*/
export default function ProviderServicesTab({
- selectedServiceSlug = null, creating = false, presets = [], readiness = {}, readinessActions = {}, onChanged,
+ selectedServiceSlug = null, creating = false, presets = [], readiness = {},
+ onAutoSetup, onUseServedModel, onServeWantedModel, servingModel = {}, onChanged,
}) {
const navigate = useNavigate();
const [services, setServices] = useState(null); // null = not loaded
@@ -314,13 +311,11 @@ export default function ProviderServicesTab({
if (!result?.service) return;
const { catalog } = result.service;
if (catalog.state === 'failed') toast.error(catalog.error || 'The catalog refresh failed — the previous catalog was kept.');
- else toast.success(`${formatCount(catalog.models.length)} model${catalog.models.length === 1 ? '' : 's'} listed for ${serviceName(service)}`);
+ else toast.success(`${pluralize(catalog.models.length, 'model')} listed for ${serviceName(service)}`);
};
const handleSave = async (service, draft) => {
- const transports = Object.fromEntries(Object.entries(draft.transports)
- .filter(([, baseUrl]) => baseUrl.trim())
- .map(([protocol, baseUrl]) => [protocol, { baseUrl: baseUrl.trim() }]));
+ const transports = transportsFromDraft(draft.transports);
const result = await write(service, 'Saving the service', () => api.updateProviderService(serviceRef(service), {
expectedRevision: service.revision,
label: draft.label,
@@ -373,8 +368,6 @@ export default function ProviderServicesTab({
<div className="grid gap-4">
{services.map((service) => {
const servicePresets = presetsByService[service.slug] || [];
- // Local-daemon readiness is computed per PRESET; the first derived
- // preset on this instance stands for the daemon they all share.
const subject = servicePresets.find((preset) => readiness[preset.id]) || null;
return (
<ServiceCard
@@ -383,13 +376,12 @@ export default function ProviderServicesTab({
open={selected?.id === service.id}
busy={Boolean(busy[service.id])}
presets={servicePresets}
+ subject={subject}
readiness={subject ? readiness[subject.id] : null}
- readinessActions={{
- onAutoSetup: subject ? (setup) => readinessActions.onAutoSetup?.({ ...setup, providerId: subject.id }) : undefined,
- onUseServedModel: subject ? (modelId) => readinessActions.onUseServedModel?.(subject, modelId) : undefined,
- onServeWantedModel: subject ? () => readinessActions.onServeWantedModel?.(subject) : undefined,
- serving: subject ? Boolean(readinessActions.servingModel?.[subject.id]) : false,
- }}
+ servingModel={servingModel}
+ onAutoSetup={onAutoSetup}
+ onUseServedModel={onUseServedModel}
+ onServeWantedModel={onServeWantedModel}
onSelect={select}
onToggle={handleToggle}
onRefresh={handleRefresh}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 3c7d8e5641..f617dd6565 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -167,7 +167,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `mediaCollectionList.js` | Search / sort ordering for the Media Collections grid (#3283) and the `CollectionPickerShell` dropdown (#3312): `applyCollectionView(collections, { query, sort })` filters via `mediaSearch.js`'s AND-token matcher over name+description and orders synthetic "Unsorted" → non-empty-or-user-created → auto-generated empties, then by `COLLECTION_SORTS` (`updated` / `name` / `count`, `normalizeCollectionSort` coerces an unknown/URL value); keys are derived once per record, not per comparison. "Hide empty" is deliberately NOT a parameter — the page owns that one predicate (`collectionItemCount(c) > 0`) because it also needs the pre-filter count. `isAutoCollection(c)` recognizes a machine-created collection from ANY of four independent markers (`AUTO_NAME_PREFIXES`, `Auto-created…`/`Auto-generated…` description, `uc-`/`sc-` id, universe/series link) so a record predating a given marker still classifies; `splitCollectionName(name)` lifts the shared `Creative Director: ` / `Writers Room: ` / `Universe: ` / `Series: ` prefix into a badge label so the distinguishing tail survives truncation, and name sorting uses that stripped title. **Adding a server-side auto-creator means adding its prefix here** or its collections silently rank as user-created. Pure — no React. |
| `mediaSearch.js` | `buildMediaHaystack`, `tokenizeQuery`, `matchHaystack`, `filterByQuery` — client-side AND-token search over normalized media items (prompt/model/seed/LoRA/universe tags). Shared by MediaHistory + the Image Gen gallery picker. |
| `ports.js` | `PORTS` + `DEFAULT_PEER_PORT`, re-exported from the pure leaf `server/lib/ports.js` (which `ports.test.js` pins against `ecosystem.config.cjs`, the source of truth — see docs/PORTS.md). Use these instead of re-hardcoding a port literal in a form default, a copy-paste help string, or a cross-machine URL. |
-| `providerManagement.js` | `catalogSummary` reads a service instance's catalog state honestly for the AI Providers → Services cards (#7567): keeps `unknown` (never asked) / `known`-and-empty / `failed` (models retained, reason attached) distinct rather than collapsing any two into "0 models". |
+| `providerManagement.js` | What every AI Providers surface shares about a service instance (#7567): `catalogSummary` reads its catalog state honestly (keeps `unknown` / `known`-and-empty / `failed`-with-retained-models distinct), `serviceReadinessCopy` / `SERVICE_READINESS_COPY` give one phrasing per `readiness` value (badge tone + label, and the predicate the compose popover and compatibility matrix append to the service's name), and `draftFromTransports` / `transportsFromDraft` round-trip its `transports` map through a text form, dropping a blank endpoint rather than sending an empty one. |
| `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/providerManagement.js b/client/src/lib/providerManagement.js
index baae4f925b..5187137984 100644
--- a/client/src/lib/providerManagement.js
+++ b/client/src/lib/providerManagement.js
@@ -3,8 +3,8 @@
*
* What is left of the Backend Connections drawer's helpers after the AI
* Providers page absorbed that drawer into its Services view: a connection is
- * a service instance, and the one reading both surfaces share is how its
- * catalog state is described. Everything about bindings, route overrides and
+ * a service instance, and what every surface shares is how its catalog state
+ * and readiness are described and how its transports round-trip a form. Everything about bindings, route overrides and
* model aliases went with the drawer — a preset names its service outright
* (`serviceId`), and a preset's own settings live on the preset editor.
*/
@@ -39,3 +39,32 @@ export function catalogSummary(catalog) {
}
return { tone: 'muted', text: 'Not refreshed yet', detail: null };
}
+
+/**
+ * One phrasing per service `readiness` value (`server/lib/providerServiceInstances.js`),
+ * for every surface that names it: the Services card badge (`tone` + `label`),
+ * the compose popover's readiness line and the compatibility matrix's blocked
+ * reason (`reason`, a predicate that follows the service's name). A value this
+ * build does not know reads as itself rather than as "no definition".
+ */
+export const SERVICE_READINESS_COPY = Object.freeze({
+ ready: { tone: 'success', label: 'Ready', reason: 'ready to run' },
+ 'needs-credential': { tone: 'warning', label: 'Needs a credential', reason: 'needs a credential' },
+ 'needs-endpoint': { tone: 'warning', label: 'Needs an endpoint', reason: 'needs an endpoint' },
+ disabled: { tone: 'muted', label: 'Switched off', reason: 'is switched off' },
+ 'unknown-definition': { tone: 'muted', label: 'No definition', reason: 'has no definition' },
+});
+
+export const serviceReadinessCopy = (readiness) => SERVICE_READINESS_COPY[readiness]
+ || { tone: 'muted', label: readiness || 'Unknown', reason: readiness ? `is ${readiness}` : 'has an unknown readiness' };
+
+/** A service's `transports` map as flat text a form edits, and back to the wire shape (blank = not declared). */
+export const draftFromTransports = (transports) => Object.fromEntries(
+ Object.entries(transports || {}).map(([protocol, value]) => [protocol, value?.baseUrl || '']),
+);
+
+export const transportsFromDraft = (draft) => Object.fromEntries(
+ Object.entries(draft || {})
+ .filter(([, baseUrl]) => String(baseUrl).trim().length > 0)
+ .map(([protocol, baseUrl]) => [protocol, { baseUrl: String(baseUrl).trim() }]),
+);
diff --git a/client/src/lib/providerManagement.test.js b/client/src/lib/providerManagement.test.js
index d60064dc92..3b90b9e36c 100644
--- a/client/src/lib/providerManagement.test.js
+++ b/client/src/lib/providerManagement.test.js
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { catalogSummary } from './providerManagement.js';
+import { catalogSummary, draftFromTransports, serviceReadinessCopy, transportsFromDraft } from './providerManagement.js';
describe('catalogSummary', () => {
it('keeps never-asked distinct from asked-and-empty', () => {
@@ -13,3 +13,18 @@ describe('catalogSummary', () => {
expect(summary.detail).toBe('timed out');
});
});
+
+describe('serviceReadinessCopy', () => {
+ it('names a readiness this build does not know rather than calling it "no definition"', () => {
+ expect(serviceReadinessCopy('needs-credential').label).toBe('Needs a credential');
+ expect(serviceReadinessCopy('quota-exhausted')).toEqual({ tone: 'muted', label: 'quota-exhausted', reason: 'is quota-exhausted' });
+ });
+});
+
+describe('transport drafts', () => {
+ it('round-trips the wire shape and drops a blank endpoint rather than sending an empty one', () => {
+ const wire = { openai: { baseUrl: 'http://localhost:11434/v1' }, anthropic: { baseUrl: 'http://localhost:11434' } };
+ expect(transportsFromDraft(draftFromTransports(wire))).toEqual(wire);
+ expect(transportsFromDraft({ openai: ' ', anthropic: ' http://h/ ' })).toEqual({ anthropic: { baseUrl: 'http://h/' } });
+ });
+});
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index c79ee78138..a4c53288f5 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -6,7 +6,7 @@ import * as api from '../services/api';
import socket from '../services/socket';
import ProviderModelSelector from '../components/ProviderModelSelector';
import { filterSelectableModels, isProviderHardwareCompatible, mergeModelLists, localBackendForProvider, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isCodexSubscriptionProvider, isLocalEndpoint, isLocalInstanceProvider, providerRuntimeKey, providerCardState, PROVIDER_CARD_STATE } from '../utils/providers';
-import { groupProvidersByHarness, presetEditPath } from '../utils/providerHarnesses';
+import { OTHER_HARNESS_GROUP, groupProvidersByHarness, presetEditPath } from '../utils/providerHarnesses';
import useProviderCatalog from '../hooks/useProviderCatalog';
import { copyToClipboard } from '../lib/clipboard';
import { formatCount } from '../utils/formatters';
@@ -57,10 +57,16 @@ export const PRESET_STATE_ORDER = Object.freeze([
PROVIDER_CARD_STATE.DISABLED,
]);
+/** The two states a card can run in: what a section's "N of M can run" counts. */
+const RUNNABLE_STATES = new Set([PROVIDER_CARD_STATE.READY, PROVIDER_CARD_STATE.BENCHED]);
+
const UNAVAILABLE_SECTION = Object.freeze({
key: 'incompatible',
title: 'Unavailable on this machine',
hint: 'This hardware cannot run them — kept for your other machines',
+ dot: 'bg-port-error',
+ link: null,
+ defaultOpen: false,
});
export default function AIProviders() {
@@ -195,7 +201,6 @@ export default function AIProviders() {
const { presetId, providerId, harnessId, serviceSlug } = useParams();
const editingProviderId = presetId ?? providerId;
const barePath = location.pathname.replace(/\/+$/, '');
- // The three views (#7567) are route prefixes, so the open one is the URL's.
const activeTab = providerPageTabForPath(barePath);
const creatingProvider = barePath.endsWith('/ai/presets/new');
const creatingService = barePath.endsWith('/ai/services/new');
@@ -321,7 +326,8 @@ export default function AIProviders() {
loadReadiness(),
hasCodexSubscriptionProvider ? loadCodexAccount() : Promise.resolve(),
]), [refreshStatuses, loadReadiness, hasCodexSubscriptionProvider, loadCodexAccount]);
- useAutoRefetch(pollCards, 20000, { pollOnly: true });
+ // The Harnesses view renders none of what the poll refreshes, so it pauses there.
+ useAutoRefetch(pollCards, 20000, { pollOnly: true, enabled: activeTab !== 'harnesses' });
// Clear a provider's bench (runtime unavailability) so the next call retries it.
// Note: if the underlying cause persists (e.g. an invalid model id), the very
@@ -661,7 +667,7 @@ export default function AIProviders() {
// section), and the id lookup the cards use for fallback/sibling references.
// Memoized because this page re-renders on the 20s status poll and on every
// keystroke in the ad-hoc runner's prompt box.
- const { providersById, runtimeByProviderId, cardStateByProviderId, presetGroups, unavailablePresets } = useMemo(() => {
+ const { providersById, runtimeByProviderId, cardStateByProviderId, presetSections } = useMemo(() => {
const byId = Object.fromEntries(providers.map(p => [p.id, p]));
const runtimeById = Object.fromEntries(providers.map(p => [p.id, runtimeForProvider(p)]));
const readinessById = Object.fromEntries(providers.map((provider) => [provider.id, providerCardState(provider, {
@@ -693,12 +699,27 @@ export default function AIProviders() {
});
const runnable = cards.filter(isProviderHardwareCompatible);
const unrunnable = cards.filter(p => !isProviderHardwareCompatible(p));
+ // One section per harness group, then the parked hardware-unavailable
+ // records; `ready` is what the header's "N of M can run" reports.
+ const section = (base, list) => {
+ const sectionProviders = ordered(list);
+ return { ...base, providers: sectionProviders, ready: sectionProviders.filter((p) => RUNNABLE_STATES.has(readinessById[p.id].state)).length };
+ };
+ const sections = [
+ ...groupProvidersByHarness(runnable).map((group) => section({
+ key: group.harnessId,
+ title: group.label,
+ hint: null,
+ link: group.harnessId === OTHER_HARNESS_GROUP ? null : `/ai/harnesses/${encodeURIComponent(group.harnessId)}`,
+ defaultOpen: true,
+ }, group.providers)),
+ section(UNAVAILABLE_SECTION, unrunnable),
+ ].filter((entry) => entry.providers.length > 0);
return {
providersById: byId,
runtimeByProviderId: runtimeById,
cardStateByProviderId: readinessById,
- presetGroups: groupProvidersByHarness(runnable).map((group) => ({ ...group, providers: ordered(group.providers) })),
- unavailablePresets: ordered(unrunnable),
+ presetSections: sections.map((entry) => ({ ...entry, dot: entry.dot || (entry.ready > 0 ? 'bg-port-success' : 'bg-gray-500') })),
};
}, [providers, statuses, activeProviderId, runtimeForProvider, codexAccount]);
@@ -790,37 +811,31 @@ export default function AIProviders() {
<ProviderPageTabs activeTab={activeTab} />
</div>
+ <div className={`flex-1 overflow-auto p-4 ${activeTab === 'presets' ? 'space-y-6' : ''}`}>
{activeTab === 'harnesses' && (
- <div className="flex-1 overflow-auto p-4">
- <ProviderHarnessesTab
- selectedHarnessId={harnessId || null}
- runtimes={runtimes}
- onInstallRuntime={setInstallingRuntime}
- codexAccount={codexAccount}
- />
- </div>
+ <ProviderHarnessesTab
+ selectedHarnessId={harnessId || null}
+ runtimes={runtimes}
+ onInstallRuntime={setInstallingRuntime}
+ />
)}
{activeTab === 'services' && (
- <div className="flex-1 overflow-auto p-4">
- <ProviderServicesTab
- selectedServiceSlug={serviceSlug || null}
- creating={creatingService}
- presets={providers}
- readiness={readiness}
- readinessActions={{
- onAutoSetup: setSettingUpRuntime,
- onUseServedModel: handleUseServedModel,
- onServeWantedModel: handleServeWantedModel,
- servingModel,
- }}
- onChanged={loadData}
- />
- </div>
+ <ProviderServicesTab
+ selectedServiceSlug={serviceSlug || null}
+ creating={creatingService}
+ presets={providers}
+ readiness={readiness}
+ onAutoSetup={setSettingUpRuntime}
+ onUseServedModel={handleUseServedModel}
+ onServeWantedModel={handleServeWantedModel}
+ servingModel={servingModel}
+ onChanged={loadData}
+ />
)}
{activeTab === 'presets' && (
- <div className="flex-1 overflow-auto p-4 space-y-6">
+ <>
{/* A retirement only becomes observable when a catalog refresh lands, so
the panel re-reads on every refresh — see RetiredModelPinsPanel. */}
@@ -1093,19 +1108,8 @@ export default function AIProviders() {
</Banner>
) : (
<>
- {[
- ...presetGroups.map((group) => ({
- key: group.harnessId,
- title: group.label,
- link: group.harnessId === 'other' ? null : `/ai/harnesses/${encodeURIComponent(group.harnessId)}`,
- providers: group.providers,
- defaultOpen: true,
- })),
- { ...UNAVAILABLE_SECTION, link: null, providers: unavailablePresets, defaultOpen: false },
- ].map(section => {
+ {presetSections.map(section => {
const sectionProviders = section.providers;
- if (sectionProviders.length === 0) return null;
- const ready = sectionProviders.filter((p) => cardStateByProviderId[p.id].state === PROVIDER_CARD_STATE.READY || cardStateByProviderId[p.id].state === PROVIDER_CARD_STATE.BENCHED).length;
return (
<CollapsibleSection
key={section.key}
@@ -1115,11 +1119,11 @@ export default function AIProviders() {
bodyClassName="grid gap-4 pt-3"
label={(
<span className="flex flex-wrap items-center gap-2">
- <span className={`w-2 h-2 rounded-full shrink-0 ${section.key === UNAVAILABLE_SECTION.key ? 'bg-port-error' : ready > 0 ? 'bg-port-success' : 'bg-gray-500'}`} aria-hidden="true" />
+ <span className={`w-2 h-2 rounded-full shrink-0 ${section.dot}`} aria-hidden="true" />
<span className="text-sm font-semibold uppercase tracking-wide text-white">{section.title}</span>
<span className="text-xs px-1.5 py-0.5 rounded bg-port-bg text-gray-400">{sectionProviders.length}</span>
<span className="text-xs text-gray-500">
- {section.hint || `${formatCount(ready, { fallback: '0' })} of ${formatCount(sectionProviders.length)} can run`}
+ {section.hint || `${formatCount(section.ready)} of ${formatCount(sectionProviders.length)} can run`}
</span>
{section.link && (
<Link to={section.link} onClick={(e) => e.stopPropagation()} className="text-xs text-port-accent hover:underline">
@@ -1228,7 +1232,6 @@ export default function AIProviders() {
useOnce={false}
title="Compose a new preset"
onClose={() => setComposeInitial(null)}
- onCompose={() => {}}
onPresetSaved={(preset) => {
toast.success(`${preset.name} saved as a preset`);
loadData();
@@ -1264,8 +1267,9 @@ export default function AIProviders() {
? `${settingUpRuntime.actionLabel} — model weights are a multi-gigabyte download, so this can run for a long time.`
: `${settingUpRuntime?.actionLabel || 'Setting up'} — this can take several minutes on a first install.`}
/>
- </div>
+ </>
)}
+ </div>
</div>
);
}
diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.js
index 7288fa33f3..5fcdde672e 100644
--- a/client/src/services/apiProviders.js
+++ b/client/src/services/apiProviders.js
@@ -56,10 +56,10 @@ export const testProvider = (id) => request(`/providers/${id}/test`, { method: '
// --- the composed axes the AI Providers page manages (#7567, epic #7561) -----
// Harness enablement (the read rides the composition catalog above), services
// (instances of a definition: plan + credential + catalog), and
-// credential-bootstrap apps. Every response
-// is credential-free: a service reports `hasCredentials` / `credentialSource`,
-// never a value. Nothing here contacts a provider except the explicit catalog
-// refresh — listing, creating and toggling are local reads and writes.
+// credential-bootstrap apps. Every response is credential-free: a service
+// reports `hasCredentials` / `credentialSource`, never a value. Nothing here
+// contacts a provider except the explicit catalog refresh — listing, creating
+// and toggling are local reads and writes.
/** The user's word on one harness. `direct` cannot be switched off; the server refuses it. */
export const setProviderHarnessEnabled = (harnessId, enabled, options) => request(
diff --git a/client/src/utils/README.md b/client/src/utils/README.md
index 6340968241..f40a916aca 100644
--- a/client/src/utils/README.md
+++ b/client/src/utils/README.md
@@ -57,7 +57,7 @@ is where each shared table is re-exported from its `server/lib` leaf.
| `providerTypes` | What KIND of provider a record is: `PROVIDER_TYPES` (re-exported from `server/lib/aiToolkit/constants.js`) with `isCliProvider` / `isTuiProvider` / `isApiProvider` / `isProcessProvider` and `isClaudeHarnessProvider` (re-exported from `server/lib/providerTypes.js`, with legacy alias `isClaudeCommandProvider`), `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`). Everything with a server twin is re-exported from the pure leaves `server/lib/providerTypes.js`, `server/lib/providerModels.js`, `server/lib/aiToolkit/constants.js` and `server/lib/aiToolkit/internal/ollamaBacked.js`, never copied — `isGrokBuildCli` moved there in #7339 so the shared reviewer→provider matcher table keys on the same predicate the browser does. |
| `providerGateways` | `PROVIDER_GATEWAYS` / `gatewayById` / `gatewayForProvider` / `isGatewayBackedProvider` — the hosted OpenAI-compatible gateways (`orcarouter`, `openrouter`, `nvidia-nim`) 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. Rows with a stable vendor key page also carry `keyUrl`, rendered as the card's "get a key" link while the key is missing. All four are re-exported from the pure leaf `server/lib/providerGateways.js`. |
| `providerRef` | `parseProviderRef(id)` / `isCompositeProviderId(id)` / `isPresetProviderId(id)` / `formatCompositeId(parts)` / `PRESET_ID_RE` / `COMPOSITE_ID_RE` — the shared preset-vs-composite grammar (#7566): distinguishes a preset id from a `<harness>.<method>@<service-slug>[+<bootstrap-slug>]` composite so `useProviderCatalog`'s `resolveRef` and `ProviderComposePopover` recognize the same strings the server does. Re-exported from the pure leaf `server/lib/providerRef.js`, never copied. |
-| `providerHarnesses` | `harnessLabel(harnessId)` — the display name for an agent program 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. Read through `harnessById` from the pure leaf `server/lib/providerHarnesses.js`, so a harness added to the registry is named here without a second edit. Also `providerHarnessId(provider)` (a derived preset's own `harnessId`, else the server's `harnessForProvider` classification) and `groupProvidersByHarness(providers)` — the `{ harnessId, label, providers }` buckets in registry order (Direct API after the agent harnesses, an `Other` bucket last) that the preset-first `ProviderModelSelector` renders as `<optgroup>`s (#7566). |
+| `providerHarnesses` | `harnessLabel(harnessId)` — the display name for an agent program PortOS drives (Claude Code, OpenCode, Codex, …), used wherever a harness is named (the preset-first pickers, the composition catalog hook), where `null` means Direct API and an unknown id renders verbatim rather than disappearing. Read through `harnessById` from the pure leaf `server/lib/providerHarnesses.js`, so a harness added to the registry is named here without a second edit. Also `providerHarnessId(provider)` (a derived preset's own `harnessId`, else the server's `harnessForProvider` classification) and `groupProvidersByHarness(providers)` — the `{ harnessId, label, providers }` buckets in registry order (Direct API after the agent harnesses, an `Other` bucket last) that the preset-first `ProviderModelSelector` renders as `<optgroup>`s (#7566) and the AI Providers page renders as its preset sections (#7567). `presetEditPath(presetId)` — the preset editor URL (`/ai/presets/:id`), falling back to the kept `/ai/edit/:id` alias for the one id (`new`) the static create route shadows. |
| `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). The sentinels, effort ladders and the Antigravity split are re-exported from the pure leaf `server/lib/providerModels.js`; `effortLevelsForProvider` / `resolveCliEffort` delegate to the server's and add the ladder a sanitized provider inventory publishes, clamped through the server's `clampEffortToLadder`. The generation-control tables still mirror `server/lib/opencodeConfig.js`. |
| `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 picker rule (`callerModeList`, `providerModeSelectionPolicy` — whose `modes` also bound the selector's compose flow) and `COMPOSE_OPTION_VALUE`, the "Custom combination…" action sentinel outside both provider-id grammars (#7566), over `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 — read off `CALLER_MODE_POLICIES` in that pure leaf, so it cannot drift). |
diff --git a/docs/AI_PROVIDERS.md b/docs/AI_PROVIDERS.md
index 14b466279f..73f2db7f0d 100644
--- a/docs/AI_PROVIDERS.md
+++ b/docs/AI_PROVIDERS.md
@@ -30,7 +30,7 @@ The stored records, **grouped by harness** and ordered within a group by readine
### Harnesses (`/ai/harnesses`)
-One card per registry harness: the **enable switch** (the user's word; a harness with no word follows whether its binary is detected on PATH; `direct` is always on), the detected version, the methods it runs, how many switched-on services it can reach, and the install a missing binary needs. Updates, removal and the harness's own model listing stay on Models → Harnesses. A toggle here is one write plus a catalog invalidation, so an open picker's compose flow reflects it without a reload.
+One card per registry harness: the **enable switch** (the user's word; a harness with no word follows whether its binary is detected on PATH; `direct` is always on), the detected version, the methods it runs, how many switched-on services it can reach, the install a missing binary needs, and — for a program that signs into its own vendor — the subscription service only it can reach, with that service's readiness and a link to it. Sign-in itself (the ChatGPT device flow, for instance) stays on the preset card. Updates, removal and the harness's own model listing stay on Models → Harnesses. A toggle here is one write plus a catalog invalidation, so an open picker's compose flow reflects it without a reload.
**Credential bootstraps** sits under the cards, collapsed until one exists: the launch wrappers a composite's `+<slug>` suffix names (`<command> <args…> <harness-name> [<separator>] <harness args>`), with the per-harness name map a wrapper may use (`claude` → `claude-code`). Saving never spawns anything; the wrapper runs only when a composite naming it executes.
diff --git a/server/lib/providerServiceInstances.js b/server/lib/providerServiceInstances.js
index 32a313bd17..3a10598403 100644
--- a/server/lib/providerServiceInstances.js
+++ b/server/lib/providerServiceInstances.js
@@ -248,14 +248,16 @@ const definitionDtoSchema = z.object({
// under — what a Services card's "get a key" link and env hint read (#7567).
keyUrl: z.string().nullable(),
envVars: z.array(z.string()),
+ // The transports a definition speaks with their default base URLs, so an
+ // "Add service" form can pre-fill an endpoint or demand one where the
+ // definition declares none.
+ transports: z.record(z.string(), z.object({ defaultBaseUrl: z.string().nullable() }).strict()),
}).strict();
/**
- * The definition half of the service DTO, and each row of
- * `GET /api/providers/service-definitions` — what an "Add service" flow
- * chooses from. Code-only data (no instance, no credential): the transports a
- * definition speaks with their default base URLs, so a form can pre-fill an
- * endpoint or demand one where the definition declares none.
+ * One definition as the wire publishes it — the `definition` half of the
+ * service DTO and each row of `GET /api/providers/service-definitions`.
+ * Code-only data: no instance, no credential.
*/
export const presentServiceDefinition = (definition) => ({
id: definition.id,
@@ -266,11 +268,6 @@ export const presentServiceDefinition = (definition) => ({
harnessOnly: definition.harnessOnly ?? null,
keyUrl: definition.credential.keyUrl ?? null,
envVars: [...definition.credential.envVars],
-});
-
-/** `presentServiceDefinition` plus the transport defaults an instance form pre-fills. */
-export const presentServiceDefinitionForCreate = (definition) => ({
- ...presentServiceDefinition(definition),
transports: Object.fromEntries(Object.entries(definition.transports)
.map(([protocol, transport]) => [protocol, { defaultBaseUrl: transport.defaultBaseUrl ?? null }])),
});
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 8c21dde960..d708d08407 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -22,7 +22,7 @@ import {
refreshServiceCatalog,
updateService,
} from '../services/providerServices.js';
-import { presentServiceDefinitionForCreate } from '../lib/providerServiceInstances.js';
+import { presentServiceDefinition } from '../lib/providerServiceInstances.js';
import { SERVICE_DEFINITIONS } from '../lib/serviceDefinitions.js';
import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
@@ -521,7 +521,7 @@ export function createPortOSProviderRoutes(aiToolkit) {
* name rather than position: its own segment can never be read as a slug.
*/
router.get('/service-definitions', (_req, res) => {
- res.json({ definitions: SERVICE_DEFINITIONS.map(presentServiceDefinitionForCreate) });
+ res.json({ definitions: SERVICE_DEFINITIONS.map(presentServiceDefinition) });
});
// Create an instance from a definition. Nothing is probed and no route is