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: correct a route's model aliases by hand, so a refresh cannot delete them (#6369)

[._.]/ Adam Eivy00ccfbd09e4f
diff --git a/client/src/components/providers/ProviderConnections.jsx b/client/src/components/providers/ProviderConnections.jsx
index 1e224e85d9..6a06880757 100644
--- a/client/src/components/providers/ProviderConnections.jsx
+++ b/client/src/components/providers/ProviderConnections.jsx
@@ -282,6 +282,24 @@ export default function ProviderConnections({
if (saved) toast.success(`${route.providerId}: ${Object.keys(settings).length} setting(s) saved for this mode only.`);
}, [run]);
+ // A hand-authored alias for what THIS harness must be sent for a backend
+ // model. Resolves to the saved row so the form can clear only on a save that
+ // landed, and `null` for a key is the removal — nothing else drops one.
+ const saveRouteAliases = useCallback(async (route, aliases) => {
+ const saved = await run('Saving the model alias', () => api.updateProviderRouteModelAliases(
+ route.providerId,
+ { expectedRevision: route.modelAliasRevision, aliases },
+ { silent: true },
+ ));
+ if (saved) {
+ const removed = Object.values(aliases).filter((value) => value === null).length;
+ toast.success(removed > 0
+ ? 'Alias removed. What the last refresh observed is unchanged.'
+ : 'Alias saved — it wins over what a refresh finds, and survives the next one.');
+ }
+ return saved;
+ }, [run]);
+
return (
<Drawer
open={open}
@@ -434,6 +452,7 @@ export default function ProviderConnections({
blocked={binding.blocked}
onMakeDefault={makeDefault}
onSaveSettings={saveRouteSettings}
+ onSaveAliases={saveRouteAliases}
/>
))}
</ul>
diff --git a/client/src/components/providers/ProviderConnections.test.jsx b/client/src/components/providers/ProviderConnections.test.jsx
index eabcf4afe4..886f50fed3 100644
--- a/client/src/components/providers/ProviderConnections.test.jsx
+++ b/client/src/components/providers/ProviderConnections.test.jsx
@@ -24,6 +24,7 @@ const api = vi.hoisted(() => ({
unlinkProviderBinding: vi.fn(),
deleteProviderConnection: vi.fn(),
updateProviderRouteSettings: vi.fn(),
+ updateProviderRouteModelAliases: vi.fn(),
setActiveProvider: vi.fn(),
isManagementUnsupported: (error) => error?.status === 404 || error?.code === 'PROVIDER_GRAPH_UNAVAILABLE',
}));
@@ -80,6 +81,9 @@ const graphFixture = () => ({
},
settingsRevision: 'cli-fingerprint',
effortLevels: ['low', 'medium', 'high'],
+ modelAliasOverrides: {},
+ modelAliasRevision: 'cli-aliases',
+ staleModelAliases: [],
},
{
providerId: 'claude-ollama-tui', bindingId: CLAUDE_BINDING, mode: 'tui', modelMap: {}, projectionPending: false,
@@ -89,6 +93,9 @@ const graphFixture = () => ({
},
settingsRevision: 'tui-fingerprint',
effortLevels: ['low', 'medium', 'high'],
+ modelAliasOverrides: {},
+ modelAliasRevision: 'tui-aliases',
+ staleModelAliases: [],
tuiCommandLine: 'claude --dangerously-skip-permissions',
},
],
@@ -249,7 +256,7 @@ describe('the empty-selection inversion', () => {
describe('a route row', () => {
const openOverrides = async (name) => {
renderPanel();
- const rows = await screen.findAllByRole('button', { name: /Overrides/ });
+ const rows = await screen.findAllByRole('button', { name: /Overrides & aliases/ });
fireEvent.click(rows[name === 'claude-ollama' ? 0 : 1]);
};
@@ -326,10 +333,80 @@ describe('an override the harness no longer offers', () => {
api.getProviderManagementGraph.mockResolvedValue(graph);
renderPanel();
- const rows = await screen.findAllByRole('button', { name: /Overrides/ });
+ const rows = await screen.findAllByRole('button', { name: /Overrides & aliases/ });
fireEvent.click(rows[0]);
expect(screen.getByLabelText('Reasoning effort')).toHaveValue('ultra');
expect(screen.getByRole('button', { name: 'Save overrides' })).toBeDisabled();
});
});
+
+describe('hand-authored model aliases', () => {
+ const openRoute = async (index = 0) => {
+ renderPanel();
+ const rows = await screen.findAllByRole('button', { name: /Overrides & aliases/ });
+ fireEvent.click(rows[index]);
+ };
+
+ it('sends the pair a human typed with the fingerprint the panel was showing', async () => {
+ api.updateProviderRouteModelAliases.mockResolvedValue({ providerId: 'claude-ollama' });
+ await openRoute();
+
+ fireEvent.change(screen.getByLabelText('Backend model name'), { target: { value: 'example-model' } });
+ fireEvent.change(screen.getByLabelText('What this harness is sent'),
+ { target: { value: 'namespace/example-model' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Add alias' }));
+
+ await waitFor(() => expect(api.updateProviderRouteModelAliases).toHaveBeenCalled());
+ const [providerId, body] = api.updateProviderRouteModelAliases.mock.calls[0];
+ expect(providerId).toBe('claude-ollama');
+ expect(body.expectedRevision).toBe('cli-aliases');
+ expect(body.aliases).toEqual({ 'example-model': 'namespace/example-model' });
+ });
+
+ it('marks which aliases a human wrote, and offers to remove only those', async () => {
+ const graph = graphFixture();
+ graph.routes[0].modelMap = { 'example-model': 'example-model', 'hand-written': 'other-model' };
+ graph.routes[0].modelAliasOverrides = { 'hand-written': 'other-model' };
+ api.getProviderManagementGraph.mockResolvedValue(graph);
+ api.updateProviderRouteModelAliases.mockResolvedValue({ providerId: 'claude-ollama' });
+ await openRoute();
+
+ // The observed alias has no Remove button — nothing a refresh wrote is the
+ // human's to delete here.
+ expect(screen.getAllByRole('button', { name: /Remove the manual alias/ })).toHaveLength(1);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Remove the manual alias for hand-written' }));
+
+ await waitFor(() => expect(api.updateProviderRouteModelAliases).toHaveBeenCalled());
+ // `null` is the removal, and it names ONLY that key: the aliases the human
+ // did not touch are not restated and cannot be lost in the round trip.
+ expect(api.updateProviderRouteModelAliases.mock.calls[0][1].aliases).toEqual({ 'hand-written': null });
+ });
+
+ it('shows an alias the route no longer lists instead of dropping it', async () => {
+ const graph = graphFixture();
+ graph.routes[0].modelMap = { 'hand-written': 'model-the-backend-dropped' };
+ graph.routes[0].modelAliasOverrides = { 'hand-written': 'model-the-backend-dropped' };
+ graph.routes[0].staleModelAliases = ['hand-written'];
+ api.getProviderManagementGraph.mockResolvedValue(graph);
+ await openRoute();
+
+ expect(screen.getByText('model-the-backend-dropped')).toBeInTheDocument();
+ expect(screen.getByText(/no longer lists that spelling/)).toBeInTheDocument();
+ });
+
+ it('keeps the typed pair when the save is refused, so it can be re-submitted', async () => {
+ api.updateProviderRouteModelAliases.mockRejectedValue(
+ Object.assign(new Error('The aliases moved'), { status: 409 }),
+ );
+ await openRoute();
+
+ fireEvent.change(screen.getByLabelText('Backend model name'), { target: { value: 'example-model' } });
+ fireEvent.change(screen.getByLabelText('What this harness is sent'), { target: { value: 'ns/example-model' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Add alias' }));
+
+ await waitFor(() => expect(toast.error).toHaveBeenCalled());
+ expect(screen.getByLabelText('Backend model name')).toHaveValue('example-model');
+ });
+});
diff --git a/client/src/components/providers/ProviderRouteModelAliases.jsx b/client/src/components/providers/ProviderRouteModelAliases.jsx
new file mode 100644
index 0000000000..3660316bc4
--- /dev/null
+++ b/client/src/components/providers/ProviderRouteModelAliases.jsx
@@ -0,0 +1,113 @@
+import { useState } from 'react';
+import { Trash2 } from 'lucide-react';
+import { routeModelAliasRows } from '../../lib/providerManagement';
+
+/**
+ * Hand-authored model aliases for one route (#6369).
+ *
+ * A route's alias map answers "what does THIS harness have to be sent for a
+ * given canonical backend model". A refresh fills it only with the pairs it can
+ * verify — an OpenCode route needs `<namespace>/<model>`, so a bare string
+ * stored on it round-trips to nothing and never reaches the shared catalog,
+ * which means no harness model menu can offer it. This is where a human
+ * supplies the pair by hand.
+ *
+ * The merge rule the copy below states, and the server enforces:
+ *
+ * - A manual alias WINS over the one a refresh observed for the same model,
+ * and survives every later refresh, because the two are stored apart.
+ * - Removing one is an explicit act. Nothing else deletes it — an alias
+ * naming a spelling the route no longer lists is marked stale and kept,
+ * the same way a model pin outside the catalog stays visible.
+ *
+ * Presentation only: the list is whatever the server published, so a build that
+ * has never seen a given alias still renders it.
+ */
+export default function ProviderRouteModelAliases({ route, busy, blocked, onSaveAliases }) {
+ const [canonical, setCanonical] = useState('');
+ const [executable, setExecutable] = useState('');
+
+ const rows = routeModelAliasRows(route);
+ const id = (suffix) => `route-${route.providerId}-alias-${suffix}`;
+ const ready = canonical.trim() !== '' && executable.trim() !== '';
+
+ const add = async () => {
+ const saved = await onSaveAliases(route, { [canonical.trim()]: executable.trim() });
+ // Clear only on a save that landed, so a 409 leaves the typed pair in place
+ // to re-submit rather than making the human retype it.
+ if (saved) {
+ setCanonical('');
+ setExecutable('');
+ }
+ };
+
+ return (
+ <div className="space-y-2 border-t border-port-border pt-2">
+ <p className="text-xs text-port-muted">
+ Model aliases — what this harness is sent for each backend model. A manual alias wins over
+ the one a refresh found and survives the next refresh; only you remove it.
+ </p>
+
+ {rows.length > 0 && (
+ <ul className="space-y-1 text-xs">
+ {rows.map((row) => (
+ <li key={row.canonical} className="flex flex-wrap items-center gap-2">
+ <span className="font-mono">{row.canonical}</span>
+ <span aria-hidden="true">→</span>
+ <span className="font-mono">{row.executable}</span>
+ {row.manual && <span className="rounded bg-port-bg px-1.5 py-0.5 text-port-muted">manual</span>}
+ {row.stale && (
+ <span className="text-port-warning">
+ this route no longer lists that spelling — kept as-is
+ </span>
+ )}
+ {row.manual && (
+ <button
+ type="button"
+ disabled={busy || blocked}
+ onClick={() => onSaveAliases(route, { [row.canonical]: null })}
+ aria-label={`Remove the manual alias for ${row.canonical}`}
+ className="flex items-center gap-1 text-port-muted hover:text-port-error disabled:opacity-50"
+ >
+ <Trash2 size={12} aria-hidden="true" /> Remove
+ </button>
+ )}
+ </li>
+ ))}
+ </ul>
+ )}
+
+ <div className="grid gap-2 sm:grid-cols-2">
+ <label className="block text-sm" htmlFor={id('canonical')}>
+ <span className="mb-1 block text-xs text-port-muted">Backend model name</span>
+ <input
+ id={id('canonical')}
+ className="w-full rounded border border-port-border bg-port-bg px-2 py-1 font-mono text-xs"
+ placeholder="example-model"
+ value={canonical}
+ onChange={(e) => setCanonical(e.target.value)}
+ />
+ </label>
+ <label className="block text-sm" htmlFor={id('executable')}>
+ <span className="mb-1 block text-xs text-port-muted">What this harness is sent</span>
+ <input
+ id={id('executable')}
+ className="w-full rounded border border-port-border bg-port-bg px-2 py-1 font-mono text-xs"
+ placeholder="namespace/example-model"
+ value={executable}
+ onChange={(e) => setExecutable(e.target.value)}
+ />
+ </label>
+ </div>
+
+ <button
+ type="button"
+ disabled={busy || blocked || !ready}
+ onClick={add}
+ className="rounded border border-port-border px-3 py-1 text-sm disabled:opacity-50"
+ >
+ Add alias
+ </button>
+ </div>
+ );
+}
diff --git a/client/src/components/providers/ProviderRouteRow.jsx b/client/src/components/providers/ProviderRouteRow.jsx
index 717dfb75b5..aab4b5046c 100644
--- a/client/src/components/providers/ProviderRouteRow.jsx
+++ b/client/src/components/providers/ProviderRouteRow.jsx
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { Link } from 'react-router';
import { Star, Terminal } from 'lucide-react';
+import ProviderRouteModelAliases from './ProviderRouteModelAliases';
import { routeOverrideDraft, routeOverridePatch } from '../../lib/providerManagement';
/**
@@ -63,6 +64,7 @@ export default function ProviderRouteRow({
blocked,
onMakeDefault,
onSaveSettings,
+ onSaveAliases,
}) {
const [open, setOpen] = useState(false);
const [draft, setDraft] = useState(() => routeOverrideDraft(route.settings));
@@ -125,16 +127,18 @@ export default function ProviderRouteRow({
<Terminal size={12} aria-hidden="true" /> Launch in Shell
</Link>
)}
- {fields.length > 0 && (
- <button type="button" onClick={() => setOpen((prev) => !prev)} aria-expanded={open}
- className="ml-auto text-xs text-port-muted hover:underline">
- {open ? 'Hide overrides' : `Overrides${dirty ? ' •' : ''}`}
- </button>
- )}
+ <button type="button" onClick={() => setOpen((prev) => !prev)} aria-expanded={open}
+ className="ml-auto text-xs text-port-muted hover:underline">
+ {open ? 'Hide' : `Overrides & aliases${dirty ? ' •' : ''}`}
+ </button>
</div>
- {open && fields.length > 0 && (
+ {open && (
<div className="mt-2 space-y-2 border-t border-port-border pt-2">
+ {/* A route whose mode publishes no overridable setting still has
+ aliases to correct, so the disclosure opens either way. */}
+ {fields.length > 0 && (
+ <>
<div className="grid gap-2 sm:grid-cols-2">
{fields.map((key) => (
<label key={key} className="block text-sm" htmlFor={fieldId(key)}>
@@ -192,6 +196,14 @@ export default function ProviderRouteRow({
Revert
</button>
</div>
+ </>
+ )}
+ <ProviderRouteModelAliases
+ route={route}
+ busy={busy}
+ blocked={blocked}
+ onSaveAliases={onSaveAliases}
+ />
</div>
)}
</li>
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 84148bd6b6..6c61513ac9 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -156,7 +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). `routeOverrideDraft` / `routeOverridePatch` are the mode-override form pair: they walk whatever settings the server published for a route rather than naming fields, send only CHANGED keys, read a blank text field as `null` (unpinned) and a blank timeout as no change. |
+| `providerManagement.js` | Joins the `GET /api/providers/management` graph into one row per connection (`groupGraphByConnection`, `findConnectionGroup`), and reads a binding's shared-model state honestly: `bindingModelOffer` (empty `selectedModels` = the whole catalog, not none), `staleSelectedModels` (pins the catalog no longer offers — reported, never repaired), `catalogSummary` (keeps `unknown` / `known`-and-empty / `failed` distinct). `routeOverrideDraft` / `routeOverridePatch` are the mode-override form pair: they walk whatever settings the server published for a route rather than naming fields, send only CHANGED keys, read a blank text field as `null` (unpinned) and a blank timeout as no change. `routeModelAliasRows` renders a route’s canonical→executable aliases with the hand-authored ones marked, and a manual alias naming a spelling the route no longer lists flagged stale rather than dropped. |
| `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 875f9e8642..0e2fb08fbc 100644
--- a/client/src/lib/providerManagement.js
+++ b/client/src/lib/providerManagement.js
@@ -179,3 +179,38 @@ export function routeOverridePatch(settings, draft) {
}
return patch;
}
+
+// --- route model aliases (#6369) ---------------------------------------------
+//
+// A route's `modelMap` says what THIS harness has to be sent for a given
+// canonical backend model. A refresh can only record the aliases it verifies,
+// so a spelling the harness adapter cannot reproduce is missing from it — and
+// the shared catalog, and therefore every model menu. The panel lets a human
+// supply the pair, which the server stores apart from what it observed so the
+// correction outlives the next refresh.
+
+/**
+ * One row per alias the route resolves through, ready to render.
+ *
+ * Sorted by canonical name so the list does not reshuffle when an entry moves
+ * between observed and manual. `manual` is what the user wrote (and may remove);
+ * `stale` is a manual alias naming a spelling the route no longer lists — shown,
+ * never dropped, exactly like a model pin outside the catalog.
+ *
+ * @returns {{canonical:string, executable:string, manual:boolean, stale:boolean}[]}
+ */
+export function routeModelAliasRows(route) {
+ const effective = route?.modelMap && typeof route.modelMap === 'object' ? route.modelMap : {};
+ const overrides = route?.modelAliasOverrides && typeof route.modelAliasOverrides === 'object'
+ ? route.modelAliasOverrides
+ : {};
+ const stale = new Set(Array.isArray(route?.staleModelAliases) ? route.staleModelAliases : []);
+ return Object.entries(effective)
+ .map(([canonical, executable]) => ({
+ canonical,
+ executable,
+ manual: Object.hasOwn(overrides, canonical),
+ stale: stale.has(canonical),
+ }))
+ .sort((a, b) => a.canonical.localeCompare(b.canonical));
+}
diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.js
index 38f86ed993..a906e71461 100644
--- a/client/src/services/apiProviders.js
+++ b/client/src/services/apiProviders.js
@@ -171,3 +171,18 @@ export const updateProviderRouteSettings = (providerId, body, options) => reques
`/providers/routes/${encodeURIComponent(providerId)}`,
{ method: 'PATCH', body: JSON.stringify(body), ...options },
);
+
+/**
+ * Edit ONE route's hand-authored canonical→executable model aliases.
+ *
+ * The correction surface for a `modelMap` a refresh could only fill with the
+ * aliases it could verify. `null` for a key removes that override and is the
+ * only thing that does — a refresh rewrites what it observed in a separate
+ * column, so a correction survives it. `expectedRevision` is the route's
+ * `modelAliasRevision` from the management graph; a 409 means the aliases moved
+ * and the edit must be re-made against a fresh read.
+ */
+export const updateProviderRouteModelAliases = (providerId, body, options) => request(
+ `/providers/routes/${encodeURIComponent(providerId)}/model-aliases`,
+ { method: 'PATCH', body: JSON.stringify(body), ...options },
+);
diff --git a/server/lib/README.md b/server/lib/README.md
index fc8986ba2a..e439504fe2 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -196,6 +196,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `providerConnections.js` | Provider CONNECTION identity for the connection graph (#6366) — `providerConnectionProfile(provider)` reads one record as the backend it describes (`kind`, `protocol`, `transports`, RAW server-only `credentials`, the `owned` field/env split, and `reasons` from `CONNECTION_ISOLATION_REASONS` when the config is dynamic, external, unparsable or endpoint-less). `sameConnectionIdentity` compares real credential values and refuses once any is the `REDACTED_CREDENTIAL` sentinel, so a sanitized record can never merge two connections; `compareBackendEndpoints` is the looser same-daemon test that only ever produces a link SUGGESTION, applying the recognized OpenAI-compatible `/v1` conversion (never DNS resolution, loopback/remote equivalence or arbitrary path trimming). `withoutConnectionOwnedFields` / `withConnectionOwnedFields` are the lossless split/materialize pair that keeps a downgraded install runnable from `data/providers.json` alone. Pure: no I/O. |
| `providerGraphPreview.js` | READ-ONLY import preview for the provider connection graph (#6366) — `buildProviderGraphPreview({providers, activeProvider})` projects the records an install already runs into proposed connections, harness bindings and executable routes, grouping ONLY the proven same-harness CLI/TUI siblings from `providerModeGroups` and surfacing a cross-harness daemon match as a `suggestedLinks` entry requiring an explicit link. `toManagementPreviewDto` sanitizes and validates the version-1 DTOs (`managementPreviewSchema`, `PROVIDER_GRAPH_SCHEMA_VERSION`) that `GET /api/providers/management/preview` returns; `projectPreviewToProviders` re-materializes every original record (pins, secrets, consent flags and unknown custom fields included) as the import-fidelity and downgrade proof; `providerGraphUniquenessViolations` checks the UNIQUE constraints #6367 will enforce; `routeModeEligibility` is the pure declarative half of mode eligibility (harness support + enabled + caller-allowed mode + text-transport consent), with the prerequisite/fallback policy left to #6368. Persists nothing and makes no generation call or runtime launch. |
| `providerGraphRecords.js` | The DURABLE half of the provider connection graph (#6367) — the pure record layer over `ai_connections` / `ai_harness_bindings` / `ai_route_bindings`. `graphFromPreview` / `importGraphFromProviders` mint UUID-keyed rows from a #6366 preview while every executable `providerId` stays untouched; `toManagementGraphDto` (`managementGraphSchema`) sanitizes them for `GET /api/providers/management` (credential PRESENCE only, no projection snapshots); `connectionOwnedSnapshot` / `applyProjections` materialize connection-owned values back into providers.json so a downgraded install still runs; and `planGraphReconciliation` / `reconciliationIsNoop` are the reconciliation contract shared by boot, legacy provider writes and downgrade-edit-reupgrade — acknowledging a landed projection, retrying an interrupted one, REFUSING a third externally changed value, dropping deleted records without resurrecting them, and detaching or splitting a binding whose backend moved. Pure: no DB handle, no file I/O, no provider call. |
+| `providerModelAliases.js` | HAND-AUTHORED canonical→executable model aliases for one provider route (#6369) — the correction surface for a `modelMap` a refresh could only fill with what it could VERIFY. Observed aliases (`ai_route_bindings.model_map`) and user overrides (`model_alias_overrides`) are stored apart and merged on READ by `effectiveModelAliases` (`{ ...observed, ...overrides }`), which is what lets a hand-authored alias outlast the next refresh; `applyModelAliasPatch` is the three-valued edit (absent preserves, a string sets, `null` is the only thing that removes); `staleModelAliases` reports — never repairs — an override naming a spelling the record no longer lists, and makes no claim at all about a route listing no models; `connectionCatalogModels` is the union an alias write re-derives the shared catalog from, so a correction actually reaches the model menus; `modelAliasRevision` is the stale-edit fingerprint, reusing `routeSettingsRevision` because `ai_route_bindings` has no revision column. Pure: no I/O. |
| `providerRouteSettings.js` | The MODE-OVERRIDE half of a provider route (#6369) — the route-owned fields a human tunes per execution mode (`args`, `timeout`, `effort` and the `defaultModel`/`lightModel`/`mediumModel`/`heavyModel`/`ultraModel` pins), mirroring what the toolkit's `sharedModeUpdates` already declares mode-specific. `ROUTE_SETTING_FIELDS` / `ROUTE_SETTING_KEYS` / `routeSettingKeys(mode)` name the set (`args` reaches cli/tui only); `routeSettingsFor(provider)` reads it off a record with absent and cleared collapsing to `null`; `routeSettingsSchema` is the wire shape `GET /api/providers/management` publishes; `unsupportedRouteSettings` rejects a key the route's mode does not accept; and `routeSettingsRevision` is the stale-edit fingerprint — a hash of the values as they are in providers.json rather than a graph row revision, so an edit made through `/ai/edit/:providerId` is caught too. Connection-owned values and execution consent (`enabled`) are deliberately absent. Pure: no I/O.
| `providerTranscriptUsage.js` | Parsers for the session files the coding CLIs write to disk (0 tokens to read) — `parseClaudeTranscript` (`~/.claude/projects/<cwd-slug>/*.jsonl`), `parseCodexRollout` (`~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`), `parseGrokTurns`/`parseGrokChatHistory`/`decodeGrokSessionDir` (`~/.grok/sessions/<encodeURIComponent(cwd)>/<id>/`), `parseAgyTranscript`/`parseAgyHistory` (`~/.gemini/antigravity-cli/`), `claudeProjectSlug`, `totalTranscriptTokens`. Each de-duplicates a format hazard that otherwise inflates counts badly: Claude repeats one response across several lines sharing a `message.id`, Codex's `total_token_usage` is cumulative and repeated, grok's `turn_completed.usage` has shipped in both per-prompt and cumulative shapes (detected and delta'd, never summed raw) while its `_meta.totalTokens` is context occupancy and never billed. Antigravity writes no token fields at all, so its parser returns chars for the caller to estimate from. Each parser returns per-model buckets (`byModel`) plus the message keys it counted (`countedKeys`), and accepts an `exclude` set — that is what stops two overlapping PortOS runs from both billing the same messages. Tolerant of truncated (mid-write) files; consumed by `services/usageReconciler.js`. |
| `opencodeCatalogCache.js` | Primes the on-disk catalog `opencode models` prints from — `primeOpencodeCatalogCache()` fetches OpenCode's `api.json` with Node's fetch and atomically writes `$XDG_CACHE_HOME/opencode/models.json` (`~/.cache` when unset). OpenCode refreshes that file from a forked task whose failures it swallows (`opencode models --refresh` still prints `Models cache refreshed`) and its HTTP client has no Happy Eyeballs, so a host advertising an unreachable IPv6 default route freezes the catalog indefinitely while other machines on the same account list newer models. Refuses to fetch or write when `OPENCODE_MODELS_PATH` / a custom `OPENCODE_MODELS_URL` / `OPENCODE_DISABLE_MODELS_FETCH` means PortOS cannot be sure which file OpenCode reads, when the file is under five minutes old, or when the body did not parse as a catalog — a stale list beats an empty picker. Never throws; the caller probes either way. |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 71f3f97d6b..b52b484f95 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -14120,6 +14120,14 @@
"server/routes/providers.js"
]
},
+ {
+ "method": "PATCH",
+ "path": "/api/providers/routes/:providerId/model-aliases",
+ "mountPath": "/api/providers",
+ "sources": [
+ "server/routes/providers.js"
+ ]
+ },
{
"method": "GET",
"path": "/api/providers/runtimes",
@@ -17940,8 +17948,8 @@
],
"stats": {
"mounts": 150,
- "operations": 2222,
- "declarations": 2230,
+ "operations": 2223,
+ "declarations": 2231,
"sourceFiles": 233
}
}
diff --git a/server/lib/db/schema/aiGraph.js b/server/lib/db/schema/aiGraph.js
index c22b7351c3..cedb39c12a 100644
--- a/server/lib/db/schema/aiGraph.js
+++ b/server/lib/db/schema/aiGraph.js
@@ -82,6 +82,11 @@ export const aiGraphDdl = [
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW()
)`,
+ // Hand-authored canonical→executable aliases, kept apart from `model_map`
+ // on purpose (#6369): a refresh rewrites what it OBSERVED, and merging the
+ // two into one column would make the next refresh silently delete the
+ // correction a human typed. Read as `{ ...model_map, ...overrides }`.
+ `ALTER TABLE ai_route_bindings ADD COLUMN IF NOT EXISTS model_alias_overrides JSONB NOT NULL DEFAULT '{}'::jsonb`,
`CREATE UNIQUE INDEX IF NOT EXISTS uq_ai_route_bindings_binding_mode
ON ai_route_bindings (binding_id, mode)`,
`CREATE INDEX IF NOT EXISTS idx_ai_route_bindings_binding
diff --git a/server/lib/index.js b/server/lib/index.js
index bcc3adf14b..8b9d857100 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -419,6 +419,7 @@ export * from './providerHarnesses.js';
export * from './providerConnections.js';
export * from './providerGraphPreview.js';
export * from './providerGraphRecords.js';
+export * from './providerModelAliases.js';
export * from './providerRouteSettings.js';
export * from './personaTraitBlend.js';
export * from './pipelineIssueOrder.js';
diff --git a/server/lib/providerGraphRecords.js b/server/lib/providerGraphRecords.js
index f90af3c9ac..e73668d4e8 100644
--- a/server/lib/providerGraphRecords.js
+++ b/server/lib/providerGraphRecords.js
@@ -7,6 +7,12 @@ import {
buildProviderGraphPreview,
} from './providerGraphPreview.js';
import { PROVIDER_HARNESS_IDS, ROUTE_MODES, providerRouteMode } from './providerHarnesses.js';
+import {
+ effectiveModelAliases,
+ modelAliasRevision,
+ sanitizeModelAliases,
+ staleModelAliases,
+} from './providerModelAliases.js';
import { routeSettingsRevision, routeSettingsSchema } from './providerRouteSettings.js';
// `PROVIDER_GRAPH_SCHEMA_VERSION` is deliberately NOT re-exported: it is one
@@ -81,7 +87,18 @@ const routeDtoSchema = z.object({
providerId: z.string().min(1),
bindingId: z.string().min(1),
mode: z.enum(ROUTE_MODES),
+ // The EFFECTIVE alias map: what the last refresh observed, with the user's
+ // hand-authored overrides laid over the top (#6369).
modelMap: z.record(z.string(), z.string()),
+ // The override half on its own, so the panel can say which aliases a human
+ // wrote and offer to remove them, plus the fingerprint an edit must send
+ // back. `ai_route_bindings` has no revision column, so the stale check is a
+ // hash of these values — the same technique the mode overrides use.
+ modelAliasOverrides: z.record(z.string(), z.string()),
+ modelAliasRevision: z.string().min(1),
+ // Overrides naming a spelling the record no longer lists. Reported, never
+ // repaired: a saved alias is only ever removed by the person who wrote it.
+ staleModelAliases: z.array(z.string()),
// Presence only — the snapshots themselves can carry secrets.
projectionPending: z.boolean(),
// This mode's own overrides, and the fingerprint a write must send back
@@ -124,6 +141,11 @@ export const managementGraphSchema = z.object({
* row whose record is mid-removal — publishes an empty override set rather than
* an absent field, so the client never has to branch on presence.
*
+ * A route entry also carries `storedModels` — the record's own model list — used
+ * only to decide which hand-authored aliases have gone stale. It is read here
+ * rather than from the graph row because `providers.json` is what a run
+ * actually executes, so the file is the honest thing to check an alias against.
+ *
* @param {{routeSettings?: Map<string, object>}} input
*/
export function toManagementGraphDto({ connections, bindings, routes, activeProvider = null, routeSettings = new Map() }) {
@@ -143,13 +165,19 @@ export function toManagementGraphDto({ connections, bindings, routes, activeProv
bindings: bindings.map(({ id, revision, connectionId, harnessId, variantKey, label, enabled, selectedModels }) => ({
id, revision, connectionId, harnessId, variantKey, label, enabled, selectedModels, blocked: blocked.has(id),
})),
- routes: routes.map(({ providerId, bindingId, mode, modelMap, pending }) => {
- const { settings = {}, effortLevels = null, tuiCommandLine = null } = routeSettings.get(providerId) || {};
+ routes: routes.map(({ providerId, bindingId, mode, modelMap, modelAliasOverrides, pending }) => {
+ const {
+ settings = {}, effortLevels = null, tuiCommandLine = null, storedModels = null,
+ } = routeSettings.get(providerId) || {};
+ const overrides = sanitizeModelAliases(modelAliasOverrides);
return {
providerId,
bindingId,
mode,
- modelMap,
+ modelMap: effectiveModelAliases(modelMap, overrides),
+ modelAliasOverrides: overrides,
+ modelAliasRevision: modelAliasRevision(overrides),
+ staleModelAliases: staleModelAliases(overrides, storedModels),
projectionPending: Boolean(pending),
settings,
settingsRevision: routeSettingsRevision(settings),
diff --git a/server/lib/providerModelAliases.js b/server/lib/providerModelAliases.js
new file mode 100644
index 0000000000..7abb0499ca
--- /dev/null
+++ b/server/lib/providerModelAliases.js
@@ -0,0 +1,139 @@
+import { routeSettingsRevision } from './providerRouteSettings.js';
+
+/**
+ * Hand-authored model aliases for one provider route (#6369).
+ *
+ * A route's `modelMap` answers one question: what does THIS harness have to be
+ * sent for a given canonical backend model. `resolveRouteModels` derives it by
+ * round-tripping every stored model string through the harness's own adapter,
+ * and a string no candidate reproduces is reported rather than rewritten — an
+ * OpenCode route carrying a bare `example-model` where the harness needs
+ * `<namespace>/example-model` resolves to nothing at all. Nothing then puts
+ * that model into the shared catalog, so no harness model menu can offer it.
+ *
+ * This module is the correction: the user names the pair by hand, and it wins.
+ *
+ * **The merge rule.** Observed and overridden aliases are stored separately and
+ * merged on read, never merged on write:
+ *
+ * - `model_map` is what the last refresh OBSERVED, rewritten wholesale by
+ * each refresh. A model the backend dropped leaves it, as it should.
+ * - `model_alias_overrides` is what the USER wrote. No refresh reads or
+ * writes it; only an explicit edit adds or removes an entry.
+ * - The effective map is `{ ...observed, ...overrides }`, so an override wins
+ * a key collision and survives every subsequent refresh.
+ *
+ * An override for a model the route no longer lists is kept and reported
+ * stale — the same rule the model pins and a binding's narrowed subset already
+ * follow, because silently dropping a saved value is how a human's choice
+ * disappears with nobody deciding to remove it.
+ *
+ * Pure: no I/O, no clock, no provider call.
+ */
+
+/** Bounds shared by the row sanitizer and the request schema. */
+export const MODEL_ALIAS_LIMITS = Object.freeze({ maxEntries: 200, maxLength: 512 });
+
+const isUsable = (value) => typeof value === 'string' && value.trim() !== '';
+
+/**
+ * A stored alias map with unusable entries dropped.
+ *
+ * A row is read defensively because these maps outlive the build that wrote
+ * them: a column hand-edited in psql, or restored from a backup taken by an
+ * older release, must not be able to put a `null` executable into a DTO the
+ * schema then refuses to publish.
+ */
+export const sanitizeModelAliases = (aliases) => Object.fromEntries(
+ Object.entries(aliases && typeof aliases === 'object' ? aliases : {})
+ .filter(([canonical, executable]) => isUsable(canonical) && isUsable(executable))
+ .map(([canonical, executable]) => [canonical.trim(), executable.trim()]),
+);
+
+/**
+ * The alias map a route actually resolves through: observed, with the user's
+ * overrides laid over the top.
+ *
+ * Order is the whole contract — spreading overrides last is what makes a
+ * hand-authored alias outlast the next refresh.
+ */
+export const effectiveModelAliases = (observed, overrides) => ({
+ ...sanitizeModelAliases(observed),
+ ...sanitizeModelAliases(overrides),
+});
+
+/**
+ * Apply one edit to a route's overrides.
+ *
+ * `null` DELETES a key; a string sets it. Absent keys are preserved, so a panel
+ * that read three aliases and changed one sends one. That three-valued shape is
+ * the same one connection credentials use, for the same reason: the caller must
+ * be able to change one entry without restating the rest.
+ *
+ * @returns {{aliases: Record<string,string>, removed: string[]}}
+ */
+export function applyModelAliasPatch(current, patch) {
+ const aliases = sanitizeModelAliases(current);
+ const removed = [];
+ for (const [rawCanonical, value] of Object.entries(patch || {})) {
+ const canonical = String(rawCanonical).trim();
+ if (canonical === '') continue;
+ if (value === null) {
+ if (Object.hasOwn(aliases, canonical)) removed.push(canonical);
+ delete aliases[canonical];
+ continue;
+ }
+ aliases[canonical] = String(value).trim();
+ }
+ return { aliases, removed };
+}
+
+/**
+ * Overrides whose executable spelling this route no longer lists.
+ *
+ * An alias claims "this route spells canonical X as Y". It goes stale when Y
+ * leaves the record's model list — the backend dropped it — not when X leaves
+ * the catalog, because X reaching the catalog is precisely what the alias is
+ * for.
+ *
+ * A route listing NO models makes no staleness claim. `[]` on a provider record
+ * cannot distinguish "never fetched" from "fetched and legitimately empty" (the
+ * same reason a record's catalog reads `unknown` rather than `known: []`), and
+ * reporting every alias as stale on a never-refreshed install would be a
+ * warning about nothing.
+ *
+ * @param {Record<string,string>} overrides
+ * @param {string[]|null|undefined} storedModels - the record's `models`
+ * @returns {string[]} canonical names, in the order the overrides were stored
+ */
+export function staleModelAliases(overrides, storedModels) {
+ const stored = Array.isArray(storedModels) ? storedModels.filter(isUsable) : [];
+ if (stored.length === 0) return [];
+ return Object.entries(sanitizeModelAliases(overrides))
+ .filter(([, executable]) => !stored.includes(executable))
+ .map(([canonical]) => canonical);
+}
+
+/**
+ * Stale-edit fingerprint of one route's overrides.
+ *
+ * `ai_route_bindings` carries no revision column, so this reuses the hash
+ * `routeSettingsRevision` already computes over a sorted entry list — the same
+ * technique the mode overrides use, and for the same reason: a fingerprint of
+ * the values catches every writer, where a row counter would only notice the
+ * ones that go through the graph.
+ */
+export const modelAliasRevision = (overrides) => routeSettingsRevision(sanitizeModelAliases(overrides));
+
+/**
+ * The canonical model names a connection's routes resolve, across all of them.
+ *
+ * The shared catalog is exactly this union, which is why an alias write
+ * recomputes it: an override that adds a canonical name has not corrected
+ * anything until the model menus can offer it. Derived from the maps already
+ * stored — it probes nothing.
+ *
+ * @param {{modelMap?: object, modelAliasOverrides?: object}[]} routes
+ */
+export const connectionCatalogModels = (routes) => [...new Set((routes || [])
+ .flatMap((route) => Object.keys(effectiveModelAliases(route?.modelMap, route?.modelAliasOverrides))))];
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 78230bfe98..6ff88a22f4 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -13,6 +13,7 @@ import {
} from './sharedSchemas.js';
import { PR_COMPLETION_VALUES } from './prDisposition.js';
import { EFFORT_LEVELS } from './providerModels.js';
+import { MODEL_ALIAS_LIMITS } from './providerModelAliases.js';
import { MAX_TIMEOUT as AI_RUN_TIMEOUT_MAX_MS, MIN_TIMEOUT as AI_RUN_TIMEOUT_MIN_MS } from './aiToolkit/constants.js';
import {
FEDERATED_MEDIA_ASSET_MAX_COUNT,
@@ -643,6 +644,29 @@ export const providerRouteSettingsUpdateSchema = z.object({
}),
}).strict();
+// PATCH /api/providers/routes/:providerId/model-aliases (#6369) — ONE route's
+// HAND-AUTHORED canonical→executable model aliases.
+//
+// Three-valued like the connection credentials above, and for the same reason:
+// a panel that read three aliases and changed one must be able to send one. An
+// absent key is preserved, a string sets, and `null` DELETES — the only way an
+// override is ever removed, because a refresh must never delete a correction.
+//
+// The keys are model names, so the record is not enumerable and each key is
+// length-checked. `expectedRevision` is a FINGERPRINT of the current override
+// map (`ai_route_bindings` has no revision column), and an empty patch is
+// refused rather than written: it would rewrite a row to say nothing.
+export const providerRouteModelAliasSchema = z.object({
+ expectedRevision: z.string().trim().min(1).max(64),
+ aliases: z.record(
+ z.string().trim().min(1).max(MODEL_ALIAS_LIMITS.maxLength),
+ z.string().trim().min(1).max(MODEL_ALIAS_LIMITS.maxLength).nullable(),
+ ).refine((value) => Object.keys(value).length > 0, { message: 'Name at least one alias to change' })
+ .refine((value) => Object.keys(value).length <= MODEL_ALIAS_LIMITS.maxEntries, {
+ message: `At most ${MODEL_ALIAS_LIMITS.maxEntries} aliases at a time`,
+ }),
+}).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
index 75c4c97ccb..5801b9edaa 100644
--- a/server/routes/providers.connectionManagement.test.js
+++ b/server/routes/providers.connectionManagement.test.js
@@ -20,6 +20,7 @@ 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';
+import { modelAliasRevision } from '../lib/providerModelAliases.js';
const store = {
readGraph: vi.fn(),
@@ -32,6 +33,7 @@ const store = {
saveConnectionSettings: vi.fn().mockResolvedValue(2),
saveBindingSettings: vi.fn().mockResolvedValue(2),
saveRouteModelMap: vi.fn().mockResolvedValue(undefined),
+ saveRouteModelAliases: vi.fn().mockResolvedValue(undefined),
};
vi.mock('../services/providerGraphStore.js', () => store);
@@ -603,3 +605,171 @@ describe('what a route row can act on', () => {
expect(byId['codex-ollama'].effortLevels).toContain('minimal');
});
});
+
+describe('PATCH /api/providers/routes/:providerId/model-aliases', () => {
+ /** The graph as a browser reads it, which is where the fingerprint comes from. */
+ const routeFromGraph = async (providerId) => {
+ const res = await request(app()).get('/api/providers/management');
+ return res.body.routes.find((route) => route.providerId === providerId);
+ };
+
+ it('makes an alias the harness adapter could not derive, and puts it in the shared catalog', async () => {
+ // OpenCode needs `<namespace>/<model>`, so a bare string on that route
+ // round-trips to nothing and reaches no catalog. This is the repair.
+ const before = await routeFromGraph('codex-ollama');
+ expect(before.modelMap).not.toHaveProperty('namespaced-model');
+
+ const res = await request(app())
+ .patch('/api/providers/routes/codex-ollama/model-aliases')
+ .send({
+ expectedRevision: before.modelAliasRevision,
+ aliases: { 'namespaced-model': 'example-model' },
+ });
+
+ expect(res.status).toBe(200);
+ expect(store.saveRouteModelAliases).toHaveBeenCalledWith('codex-ollama',
+ { 'namespaced-model': 'example-model' });
+ // The effective map is the merge, so the observed alias is still there.
+ expect(res.body.modelMap).toEqual({
+ 'example-model': 'example-model',
+ 'namespaced-model': 'example-model',
+ });
+ // A correction no model menu offers has corrected nothing, so the shared
+ // catalog is re-derived from the stored maps — without probing anything.
+ const [{ catalog }] = store.saveConnectionSettings.mock.calls.at(-1);
+ expect(catalog.models).toContain('namespaced-model');
+ expect(providerService.refreshProviderModelsBatch).not.toHaveBeenCalled();
+ // Aliases are graph state: no executable record is rewritten by one.
+ expect(providerService.applyProviderPatches).not.toHaveBeenCalled();
+ });
+
+ it('wins over the alias a refresh observed for the same model', async () => {
+ const route = await routeFromGraph('claude-ollama');
+
+ const res = await request(app())
+ .patch('/api/providers/routes/claude-ollama/model-aliases')
+ .send({
+ expectedRevision: route.modelAliasRevision,
+ aliases: { 'example-model': 'example-model:8b' },
+ });
+
+ expect(res.status).toBe(200);
+ expect(res.body.modelMap['example-model']).toBe('example-model:8b');
+ });
+
+ it('survives the next catalog refresh, which rewrites only what it observed', async () => {
+ const withOverride = graphFixture();
+ withOverride.routes[0].modelAliasOverrides = { 'hand-written': 'example-model' };
+ store.readGraph.mockResolvedValue(withOverride);
+ 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);
+ // The observed column is rewritten wholesale...
+ expect(store.saveRouteModelMap).toHaveBeenCalledWith('claude-ollama', { 'example-model': 'example-model' });
+ // ...the override column is not touched at all...
+ expect(store.saveRouteModelAliases).not.toHaveBeenCalled();
+ // ...and the hand-written alias is still in the refreshed shared catalog.
+ expect(res.body.catalog.models).toContain('hand-written');
+ });
+
+ it('removes an override only on an explicit null', async () => {
+ const withOverride = graphFixture();
+ withOverride.routes[0].modelAliasOverrides = { 'hand-written': 'example-model', kept: 'example-model' };
+ store.readGraph.mockResolvedValue(withOverride);
+ const route = await routeFromGraph('claude-ollama');
+
+ const res = await request(app())
+ .patch('/api/providers/routes/claude-ollama/model-aliases')
+ .send({ expectedRevision: route.modelAliasRevision, aliases: { 'hand-written': null } });
+
+ expect(res.status).toBe(200);
+ // The alias not named in the patch is preserved, not restated by the caller.
+ expect(res.body.modelAliasOverrides).toEqual({ kept: 'example-model' });
+ });
+
+ it('keeps an alias whose spelling the record no longer lists, and reports it stale', async () => {
+ const withOverride = graphFixture();
+ withOverride.routes[0].modelAliasOverrides = { 'hand-written': 'model-the-backend-dropped' };
+ store.readGraph.mockResolvedValue(withOverride);
+
+ const route = await routeFromGraph('claude-ollama');
+
+ expect(route.modelAliasOverrides).toEqual({ 'hand-written': 'model-the-backend-dropped' });
+ expect(route.staleModelAliases).toEqual(['hand-written']);
+ // Reported, never repaired: it is still in the effective map a run resolves
+ // through, exactly like a model pin outside the catalog.
+ expect(route.modelMap['hand-written']).toBe('model-the-backend-dropped');
+ });
+
+ it('makes no staleness claim about a route that lists no models at all', async () => {
+ const withOverride = graphFixture();
+ withOverride.routes[0].modelAliasOverrides = { 'hand-written': 'example-model' };
+ store.readGraph.mockResolvedValue(withOverride);
+ // `[]` on a record cannot tell "never fetched" from "fetched and empty", so
+ // calling every alias stale here would be a warning about nothing.
+ providerService.getAllProviders.mockResolvedValue({
+ activeProvider: 'claude-ollama',
+ providers: [{ ...structuredClone(CLAUDE_CLI), models: [] },
+ structuredClone(CLAUDE_TUI), structuredClone(CODEX_CLI)],
+ });
+
+ const route = await routeFromGraph('claude-ollama');
+
+ expect(route.staleModelAliases).toEqual([]);
+ });
+
+ it('refuses an edit made against aliases that have since moved', async () => {
+ const res = await request(app())
+ .patch('/api/providers/routes/claude-ollama/model-aliases')
+ .send({ expectedRevision: 'a-fingerprint-from-a-screen-that-moved-on', aliases: { a: 'b' } });
+
+ expect(res.status).toBe(409);
+ expect(res.body.code).toBe('PROVIDER_GRAPH_STALE_REVISION');
+ expect(store.saveRouteModelAliases).not.toHaveBeenCalled();
+ expect(store.saveConnectionSettings).not.toHaveBeenCalled();
+ });
+
+ it('404s a provider id the graph does not route, and refuses an empty patch', async () => {
+ const route = await routeFromGraph('claude-ollama');
+
+ const missing = await request(app())
+ .patch('/api/providers/routes/not-a-route/model-aliases')
+ .send({ expectedRevision: route.modelAliasRevision, aliases: { a: 'b' } });
+ expect(missing.status).toBe(404);
+
+ const empty = await request(app())
+ .patch('/api/providers/routes/claude-ollama/model-aliases')
+ .send({ expectedRevision: route.modelAliasRevision, aliases: {} });
+ expect(empty.status).toBe(400);
+ expect(store.saveRouteModelAliases).not.toHaveBeenCalled();
+ });
+
+ it('refuses while the route is mid-projection', async () => {
+ const fixture = graphFixture();
+ fixture.routes[0].pending = ownedSnapshot();
+ store.readGraph.mockResolvedValue(fixture);
+
+ const res = await request(app())
+ .patch('/api/providers/routes/claude-ollama/model-aliases')
+ .send({ expectedRevision: modelAliasRevision({}), aliases: { a: 'b' } });
+
+ expect(res.status).toBe(409);
+ expect(res.body.code).toBe('PROVIDER_GRAPH_BINDING_BLOCKED');
+ expect(store.saveRouteModelAliases).not.toHaveBeenCalled();
+ });
+
+ it('drops a hand-edited row entry that could not be published, rather than failing the graph', async () => {
+ const fixture = graphFixture();
+ // A column edited in psql, or restored from an older release's backup.
+ fixture.routes[0].modelAliasOverrides = { good: 'example-model', broken: null, '': 'x' };
+ store.readGraph.mockResolvedValue(fixture);
+
+ const route = await routeFromGraph('claude-ollama');
+
+ expect(route.modelAliasOverrides).toEqual({ good: 'example-model' });
+ });
+});
diff --git a/server/routes/providers.js b/server/routes/providers.js
index 69762ab4c6..526ca33dc1 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -9,6 +9,7 @@ import {
unlinkBinding,
updateBindingSettings,
updateConnectionSettings,
+ updateRouteModelAliases,
updateRouteSettings,
} from '../services/providerGraph.js';
import { Router } from 'express';
@@ -29,6 +30,7 @@ import {
providerBindingUnlinkSchema,
providerBindingUpdateSchema,
providerConnectionUpdateSchema,
+ providerRouteModelAliasSchema,
providerRouteSettingsUpdateSchema,
} from '../lib/validation.js';
import {
@@ -405,6 +407,25 @@ export function createPortOSProviderRoutes(aiToolkit) {
res.json(await updateRouteSettings({ providerId: req.params.providerId, ...input }));
}));
+ /**
+ * Correct ONE route's canonical→executable model aliases by hand (#6369).
+ *
+ * A refresh records only the aliases it can VERIFY — a stored model string
+ * round-trips through the harness's own adapter or it stays an unresolved
+ * alias rather than being rewritten — so a spelling the adapter cannot
+ * reproduce reaches no shared catalog and no model menu. This is where a
+ * human supplies it.
+ *
+ * `null` for a key removes that override and is the ONLY thing that does: a
+ * refresh rewrites what it observed in a separate column, so a correction
+ * survives it and an alias for a model the route no longer lists is kept and
+ * reported stale rather than dropped.
+ */
+ router.patch('/routes/:providerId/model-aliases', asyncHandler(async (req, res) => {
+ const input = validateRequest(providerRouteModelAliasSchema, req.body ?? {});
+ res.json(await updateRouteModelAliases({ providerId: req.params.providerId, ...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 bd1eaf3cef..7c76048238 100644
--- a/server/services/providerGraph.js
+++ b/server/services/providerGraph.js
@@ -11,6 +11,12 @@ import {
toManagementGraphDto,
} from '../lib/providerGraphRecords.js';
import { resolveRouteModels } from '../lib/providerGraphPreview.js';
+import {
+ applyModelAliasPatch,
+ connectionCatalogModels,
+ effectiveModelAliases,
+ modelAliasRevision,
+} from '../lib/providerModelAliases.js';
import { effortLevelsForProvider } from '../lib/providerModels.js';
import {
routeSettingsFor,
@@ -29,6 +35,7 @@ import {
relinkBinding,
saveBindingSettings,
saveConnectionSettings,
+ saveRouteModelAliases,
saveRouteModelMap,
} from './providerGraphStore.js';
@@ -186,6 +193,9 @@ function describeRoute(provider) {
settings,
effortLevels: effortLevelsForProvider(provider, settings.defaultModel ?? null),
tuiCommandLine: buildTuiShellLaunch(provider)?.commandLine ?? null,
+ // The record's own model strings, so the DTO can say which hand-authored
+ // aliases name a spelling this route no longer carries (#6369).
+ storedModels: Array.isArray(provider?.models) ? provider.models : null,
};
}
@@ -574,14 +584,19 @@ export function refreshConnectionCatalog(connectionId) {
// 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 = [];
+ const refreshedRoutes = [];
for (const route of routes) {
const provider = byId.get(route.providerId);
if (!provider) continue;
const { modelMap } = resolveRouteModels(provider);
+ // Only the OBSERVED half is written back. The user's overrides stay in
+ // their own column, which is what lets a hand-authored alias outlast this
+ // refresh — but they still count towards the shared catalog below,
+ // because a correction that no model menu offers has corrected nothing.
await saveRouteModelMap(route.providerId, modelMap);
- models.push(...Object.keys(modelMap));
+ refreshedRoutes.push({ ...route, modelMap });
}
+ const models = connectionCatalogModels(refreshedRoutes);
// A failure is reported whether or not another group succeeded: a partial
// answer is still a harness that cannot reach this backend.
@@ -673,3 +688,70 @@ export function updateRouteSettings({ providerId, expectedRevision, settings })
return { providerId, settings: next, settingsRevision: routeSettingsRevision(next) };
});
}
+
+/**
+ * Edit ONE route's hand-authored model aliases (#6369).
+ *
+ * The correction surface for `modelMap`. A refresh only ever records the
+ * aliases it could VERIFY — a stored model string round-trips through the
+ * harness's own adapter or it is reported unresolved rather than rewritten — so
+ * a bare `example-model` on an OpenCode route that needs its `<namespace>/`
+ * prefix resolves to nothing, reaches no catalog, and can be offered by no
+ * model menu. Naming the pair by hand is the repair.
+ *
+ * The merge rule, which is the whole design decision behind this endpoint:
+ *
+ * - Observed aliases and user overrides live in SEPARATE columns. A refresh
+ * rewrites the observed one wholesale and never touches the other, so an
+ * override survives every refresh and is removed only by the person who
+ * wrote it (`null` for its key).
+ * - The effective map is `{ ...observed, ...overrides }` — an override wins.
+ * - An override naming a spelling the record no longer lists is KEPT and
+ * reported stale, the same way a model pin outside the catalog is.
+ *
+ * The connection's catalog is re-derived here from the maps already stored,
+ * because an alias that no model menu offers has fixed nothing. That is a pure
+ * recompute: no backend is probed, `state` and `error` are preserved, and a
+ * failed catalog keeps reading as failed.
+ *
+ * Stale-checked with a fingerprint of the overrides rather than a row revision,
+ * for the reason `routeSettingsRevision` documents: `ai_route_bindings` has no
+ * revision column, and a hash of the values catches every writer.
+ */
+export function updateRouteModelAliases({ providerId, expectedRevision, aliases }) {
+ return serialize(async () => {
+ requireGraph();
+ const graph = await readGraph();
+ const route = graph.routes.find((candidate) => candidate.providerId === providerId);
+ if (!route) throw new ServerError('Route not found', { status: 404, code: 'ROUTE_NOT_FOUND' });
+ requireSettledRoutes([route]);
+
+ if (modelAliasRevision(route.modelAliasOverrides) !== expectedRevision) {
+ throw stale("This route's model aliases");
+ }
+
+ const { aliases: overrides, removed } = applyModelAliasPatch(route.modelAliasOverrides, aliases);
+ await saveRouteModelAliases(providerId, overrides);
+
+ // Re-derive the shared catalog from every route on this backend, reading
+ // the row we just wrote rather than the stale one the graph read.
+ const bindingConnectionId = graph.bindings.find((binding) => binding.id === route.bindingId)?.connectionId;
+ const connection = graph.connections.find((candidate) => candidate.id === bindingConnectionId);
+ if (connection) {
+ const { routes } = connectionFanout(graph, connection.id);
+ const models = connectionCatalogModels(routes.map((entry) => (entry.providerId === providerId
+ ? { ...entry, modelAliasOverrides: overrides }
+ : entry)));
+ await saveConnectionSettings({ ...connection, catalog: { ...connection.catalog, models } });
+ }
+
+ console.log(`🔗 Updated route ${providerId} model aliases: `
+ + `${Object.keys(overrides).length} kept, ${removed.length} removed`);
+ return {
+ providerId,
+ modelMap: effectiveModelAliases(route.modelMap, overrides),
+ modelAliasOverrides: overrides,
+ modelAliasRevision: modelAliasRevision(overrides),
+ };
+ });
+}
diff --git a/server/services/providerGraphStore.db.test.js b/server/services/providerGraphStore.db.test.js
index 44399b28c0..376aec1bee 100644
--- a/server/services/providerGraphStore.db.test.js
+++ b/server/services/providerGraphStore.db.test.js
@@ -109,6 +109,21 @@ describe.skipIf(!runDb)('ai_* connection graph store', () => {
expect(read.routes[0].projected).toEqual(route(bind.id, 'x').projected);
});
+ it('keeps a hand-authored alias when an unrelated repair re-upserts the route', async () => {
+ const conn = connection();
+ const bind = binding(conn.id);
+ await store.writeGraph({ connections: [conn], bindings: [bind], routes: [route(bind.id, 'claude-ollama')] });
+ await store.saveRouteModelAliases('claude-ollama', { 'hand-written': 'example-model' });
+
+ // An import, a reconciliation re-import and a binding split all carry no
+ // overrides. If the conflict update took them from EXCLUDED, this would
+ // silently delete a correction the user typed (#6369).
+ await store.writeGraph({ connections: [], bindings: [], routes: [route(bind.id, 'claude-ollama')] });
+
+ const read = await store.readGraph();
+ expect(read.routes[0].modelAliasOverrides).toEqual({ 'hand-written': 'example-model' });
+ });
+
it('refuses two routes on one binding in the same mode', async () => {
const conn = connection();
const bind = binding(conn.id);
diff --git a/server/services/providerGraphStore.js b/server/services/providerGraphStore.js
index bb303f95c2..8b80e441e2 100644
--- a/server/services/providerGraphStore.js
+++ b/server/services/providerGraphStore.js
@@ -48,6 +48,7 @@ const routeRow = (row) => ({
bindingId: row.binding_id,
mode: row.mode,
modelMap: row.model_map || {},
+ modelAliasOverrides: row.model_alias_overrides || {},
projected: row.projected || {},
pending: row.pending ?? null,
pendingRevision: row.pending_revision ?? null,
@@ -94,15 +95,21 @@ const upsertBinding = (client, binding) => client.query(
JSON.stringify(binding.selectedModels || [])],
);
+// `model_alias_overrides` is set on INSERT and deliberately absent from the
+// conflict update: an import, a reconciliation re-import and a binding split
+// all carry no overrides, so updating the column from EXCLUDED would delete a
+// human's hand-authored aliases as a side effect of an unrelated repair. Only
+// `saveRouteModelAliases` writes it.
const upsertRoute = (client, route) => client.query(
`INSERT INTO ai_route_bindings
- (provider_id, binding_id, mode, model_map, projected, pending, pending_revision, updated_at)
- VALUES ($1, $2, $3, $4, $5, $6, $7, NOW())
+ (provider_id, binding_id, mode, model_map, model_alias_overrides, projected, pending, pending_revision, updated_at)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, NOW())
ON CONFLICT (provider_id) DO UPDATE SET
binding_id = EXCLUDED.binding_id, mode = EXCLUDED.mode, model_map = EXCLUDED.model_map,
projected = EXCLUDED.projected, pending = EXCLUDED.pending,
pending_revision = EXCLUDED.pending_revision, updated_at = NOW()`,
[route.providerId, route.bindingId, route.mode, JSON.stringify(route.modelMap || {}),
+ JSON.stringify(route.modelAliasOverrides || {}),
JSON.stringify(route.projected || {}),
route.pending == null ? null : JSON.stringify(route.pending),
route.pendingRevision ?? null],
@@ -300,3 +307,18 @@ 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 || {})]);
}
+
+/**
+ * Write one route's hand-authored alias overrides. Revision-checked and
+ * serialized by the caller, like every other mutation in this block.
+ *
+ * Separate from {@link saveRouteModelMap} on purpose: that column records what
+ * a refresh OBSERVED and is rewritten by the next one, so keeping the two apart
+ * is what lets a correction survive a refresh (#6369).
+ */
+export async function saveRouteModelAliases(providerId, overrides) {
+ await query(
+ 'UPDATE ai_route_bindings SET model_alias_overrides = $2, updated_at = NOW() WHERE provider_id = $1',
+ [providerId, JSON.stringify(overrides || {})],
+ );
+}