Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: edit a route's mode overrides and launch its TUI from the connection panel (#6369)
[._.]/ Adam Eivyc6b0ec518c72
diff --git a/client/src/components/providers/ProviderConnections.jsx b/client/src/components/providers/ProviderConnections.jsxindex 05db8f5388..1e224e85d9 100644--- a/client/src/components/providers/ProviderConnections.jsx+++ b/client/src/components/providers/ProviderConnections.jsx@@ -1,10 +1,10 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { Link } from 'react-router';-import { Link2, Link2Off, RefreshCw, Star, Trash2 } from 'lucide-react';+import { Link2, Link2Off, RefreshCw, Trash2 } from 'lucide-react';import toast from '../ui/Toast';import Drawer from '../Drawer';import Banner from '../ui/Banner';import EmptyState from '../EmptyState';+import ProviderRouteRow from './ProviderRouteRow';import * as api from '../../services/api';import { harnessLabel } from '../../utils/providerHarnesses';import {@@ -23,15 +23,18 @@ import {* Claude CLI route, a Claude TUI route and an OpenCode route pointed at the* same Ollama daemon share ONE connection row here, so its endpoint, its key* and its model catalog are typed, refreshed and narrowed in one place instead- * of three that drift.+ * of three that drift. Each route below then carries the settings that are its+ * own — args, timeout, effort, model pins — so the whole backend is configured+ * here rather than on a connection plus three separate route editors.** Three rules the UI is built around, all of them server-enforced too:** - **Identity is never inferred.** Two connections are the same only when* the server says they share an id. Linking is an explicit, previewed act.* - **Nothing here grants execution.** Narrowing a catalog, renaming a- * binding and editing an endpoint change no route's enabled state and no- * mode's consent. Those stay on the route editor, one click away.+ * binding, editing an endpoint and tuning one mode's overrides change no+ * route's enabled state and no mode's consent. Those stay on the route+ * editor, one click away.* - **A saved value is never hidden.** A pin the catalog no longer offers is* shown as stale, not dropped.*@@ -268,6 +271,17 @@ export default function ProviderConnections({if (done) toast.success(`${providerId} is now the system default route.`);}, [run]);+ // Route-scoped, so the reload afterwards is the same one every other write+ // here does: this mode's siblings are untouched and no other harness moves.+ const saveRouteSettings = useCallback(async (route, settings) => {+ const saved = await run('Saving the overrides', () => api.updateProviderRouteSettings(+ route.providerId,+ { expectedRevision: route.settingsRevision, settings },+ { silent: true },+ ));+ if (saved) toast.success(`${route.providerId}: ${Object.keys(settings).length} setting(s) saved for this mode only.`);+ }, [run]);+return (<Draweropen={open}@@ -410,24 +424,17 @@ export default function ProviderConnections({</Banner>)}- <ul className="mb-3 space-y-1">+ <ul className="mb-3 space-y-2">{routes.map((route) => (- <li key={route.providerId} className="flex flex-wrap items-center gap-2 text-sm">- <span className="rounded bg-port-bg px-1.5 py-0.5 text-xs uppercase">{route.mode}</span>- <Link to={`/ai/edit/${route.providerId}`} className="text-port-accent hover:underline">- {route.providerId}- </Link>- {graph?.activeProvider === route.providerId ? (- <span className="flex items-center gap-1 text-xs text-port-success">- <Star size={12} aria-hidden="true" /> system default- </span>- ) : (- <button type="button" disabled={busy} onClick={() => makeDefault(route.providerId)}- className="text-xs text-port-muted hover:underline disabled:opacity-50">- Use as system default- </button>- )}- </li>+ <ProviderRouteRow+ key={route.providerId}+ route={route}+ isSystemDefault={graph?.activeProvider === route.providerId}+ busy={busy}+ blocked={binding.blocked}+ onMakeDefault={makeDefault}+ onSaveSettings={saveRouteSettings}+ />))}</ul>diff --git a/client/src/components/providers/ProviderConnections.test.jsx b/client/src/components/providers/ProviderConnections.test.jsxindex cf65ef4719..eabcf4afe4 100644--- a/client/src/components/providers/ProviderConnections.test.jsx+++ b/client/src/components/providers/ProviderConnections.test.jsx@@ -23,6 +23,7 @@ const api = vi.hoisted(() => ({linkProviderBinding: vi.fn(),unlinkProviderBinding: vi.fn(),deleteProviderConnection: vi.fn(),+ updateProviderRouteSettings: vi.fn(),setActiveProvider: vi.fn(),isManagementUnsupported: (error) => error?.status === 404 || error?.code === 'PROVIDER_GRAPH_UNAVAILABLE',}));@@ -68,8 +69,28 @@ const graphFixture = () => ({blocked: false,}],routes: [- { providerId: 'claude-ollama', bindingId: CLAUDE_BINDING, mode: 'cli', modelMap: {}, projectionPending: false },- { providerId: 'claude-ollama-tui', bindingId: CLAUDE_BINDING, mode: 'tui', modelMap: {}, projectionPending: false },+ // `settings` is what the server published as route-owned for this MODE, and+ // `settingsRevision` the fingerprint a save must echo. The TUI route also+ // carries the server-resolved command line that enables the Shell hand-off.+ {+ providerId: 'claude-ollama', bindingId: CLAUDE_BINDING, mode: 'cli', modelMap: {}, projectionPending: false,+ settings: {+ args: ['--verbose'], timeout: 60000, effort: 'high', defaultModel: 'example-model',+ lightModel: null, mediumModel: null, heavyModel: null, ultraModel: null,+ },+ settingsRevision: 'cli-fingerprint',+ effortLevels: ['low', 'medium', 'high'],+ },+ {+ providerId: 'claude-ollama-tui', bindingId: CLAUDE_BINDING, mode: 'tui', modelMap: {}, projectionPending: false,+ settings: {+ args: [], timeout: 60000, effort: null, defaultModel: 'example-model',+ lightModel: null, mediumModel: null, heavyModel: null, ultraModel: null,+ },+ settingsRevision: 'tui-fingerprint',+ effortLevels: ['low', 'medium', 'high'],+ tuiCommandLine: 'claude --dangerously-skip-permissions',+ },],});@@ -224,3 +245,91 @@ describe('the empty-selection inversion', () => {expect(api.updateProviderBinding).not.toHaveBeenCalled();});});++describe('a route row', () => {+ const openOverrides = async (name) => {+ renderPanel();+ const rows = await screen.findAllByRole('button', { name: /Overrides/ });+ fireEvent.click(rows[name === 'claude-ollama' ? 0 : 1]);+ };++ it('hands a TUI route to the Shell page and shows what it will run', async () => {+ renderPanel();++ const launch = await screen.findByRole('link', { name: /Launch in Shell/ });+ // The provider id alone: the env the launch needs is secret and is+ // re-resolved server-side when the PTY spawns.+ expect(launch).toHaveAttribute('href', '/shell?provider=claude-ollama-tui');+ expect(launch).toHaveAttribute('title', expect.stringContaining('claude --dangerously-skip-permissions'));+ // Exactly one — the CLI route on the same harness is not launchable by hand.+ expect(screen.getAllByRole('link', { name: /Launch in Shell/ })).toHaveLength(1);+ });++ it('sends only the fields that changed, with the fingerprint it was showing', async () => {+ api.updateProviderRouteSettings.mockResolvedValue({ providerId: 'claude-ollama' });+ await openOverrides('claude-ollama');++ fireEvent.change(screen.getByLabelText(/Launch arguments/), { target: { value: '--verbose\n--debug' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save overrides' }));++ await waitFor(() => expect(api.updateProviderRouteSettings).toHaveBeenCalled());+ const [providerId, body] = api.updateProviderRouteSettings.mock.calls[0];+ expect(providerId).toBe('claude-ollama');+ expect(body.expectedRevision).toBe('cli-fingerprint');+ // The timeout, effort and pins the human never touched are absent, so a+ // save cannot rewrite a value the route editor changed a moment ago.+ expect(body.settings).toEqual({ args: ['--verbose', '--debug'] });+ });++ it('reads a cleared pin as unset rather than as an empty string', async () => {+ api.updateProviderRouteSettings.mockResolvedValue({ providerId: 'claude-ollama' });+ await openOverrides('claude-ollama');++ fireEvent.change(screen.getByLabelText('Default model'), { target: { value: '' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save overrides' }));++ await waitFor(() => expect(api.updateProviderRouteSettings).toHaveBeenCalled());+ expect(api.updateProviderRouteSettings.mock.calls[0][1].settings).toEqual({ defaultModel: null });+ });++ it('cannot save until something differs, and reverts back to the saved values', async () => {+ await openOverrides('claude-ollama');++ const save = screen.getByRole('button', { name: 'Save overrides' });+ expect(save).toBeDisabled();++ fireEvent.change(screen.getByLabelText('Heavy tier model'), { target: { value: 'other-model' } });+ expect(save).toBeEnabled();++ fireEvent.click(screen.getByRole('button', { name: 'Revert' }));+ expect(screen.getByLabelText('Heavy tier model')).toHaveValue('');+ expect(screen.getByRole('button', { name: 'Save overrides' })).toBeDisabled();+ expect(api.updateProviderRouteSettings).not.toHaveBeenCalled();+ });++ it('offers only the effort levels this harness accepts', async () => {+ await openOverrides('claude-ollama');++ const options = [...screen.getByLabelText('Reasoning effort').options].map((option) => option.value);+ // The blank first option is "harness default", not a level.+ expect(options).toEqual(['', 'low', 'medium', 'high']);+ });+});++describe('an override the harness no longer offers', () => {+ it('stays selected instead of reading as a clear the moment the panel opens', async () => {+ const graph = graphFixture();+ // The stored level is real and saved; this build's ladder for the harness+ // simply no longer lists it — the same shape as a model pin outside the+ // catalog, and it must not be silently offered up for deletion.+ graph.routes[0].settings.effort = 'ultra';+ api.getProviderManagementGraph.mockResolvedValue(graph);+ renderPanel();++ const rows = await screen.findAllByRole('button', { name: /Overrides/ });+ fireEvent.click(rows[0]);++ expect(screen.getByLabelText('Reasoning effort')).toHaveValue('ultra');+ expect(screen.getByRole('button', { name: 'Save overrides' })).toBeDisabled();+ });+});diff --git a/client/src/components/providers/ProviderRouteRow.jsx b/client/src/components/providers/ProviderRouteRow.jsxnew file mode 100644index 0000000000..717dfb75b5--- /dev/null+++ b/client/src/components/providers/ProviderRouteRow.jsx@@ -0,0 +1,199 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import { Link } from 'react-router';+import { Star, Terminal } from 'lucide-react';+import { routeOverrideDraft, routeOverridePatch } from '../../lib/providerManagement';++/**+ * One executable route inside the connection panel (#6369).+ *+ * The row a human acts on: it names the mode and the executable provider id,+ * offers that id as the system default, hands a TUI off to the Shell page, and+ * — behind a disclosure — edits the overrides that belong to THIS mode alone.+ *+ * Why the overrides live here rather than only on `/ai/edit/:providerId`: a+ * backend is configured as a whole. Having typed an endpoint once on the+ * connection above, retyping three sets of args in three separate editors is+ * exactly the round trip the graph exists to remove.+ *+ * Three boundaries this row does NOT cross:+ *+ * - **No execution consent.** There is no enable toggle and no transport+ * opt-in. Turning a route on stays an explicit act on the route editor.+ * - **No connection state.** The fields are whatever the server published as+ * route-owned; an endpoint or a key can never be retyped here and escape+ * the projection that keeps the other harnesses on the backend in step.+ * - **Nothing launches itself.** "Launch in Shell" is a link the human+ * clicks, and the launch re-resolves the command AND the provider's secret+ * env server-side; the command line here is display only.+ *+ * The disclosure is presentation state, not a selection: the connection in the+ * URL still names what is open, and every route's editor is one click from a+ * shared link.+ */++/**+ * Reading order and labels. The route's OWN key set decides what renders — a+ * setting this build has no label for is still shown, under its raw key, rather+ * than silently dropped from a newer server's payload.+ */+const FIELD_LABELS = {+ args: 'Launch arguments (one per line)',+ timeout: 'Timeout (ms)',+ effort: 'Reasoning effort',+ defaultModel: 'Default model',+ lightModel: 'Light tier model',+ mediumModel: 'Medium tier model',+ heavyModel: 'Heavy tier model',+ ultraModel: 'Ultra tier model',+};++/** Published keys, labelled ones first and in reading order. */+const orderedFields = (settings) => {+ const published = Object.keys(settings || {});+ const known = Object.keys(FIELD_LABELS).filter((key) => published.includes(key));+ return [...known, ...published.filter((key) => !Object.hasOwn(FIELD_LABELS, key))];+};++const INPUT_CLASS = 'w-full rounded border border-port-border bg-port-bg px-2 py-1';++export default function ProviderRouteRow({+ route,+ isSystemDefault,+ busy,+ blocked,+ onMakeDefault,+ onSaveSettings,+}) {+ const [open, setOpen] = useState(false);+ const [draft, setDraft] = useState(() => routeOverrideDraft(route.settings));++ // Re-seed only when the SAVED values move. `settingsRevision` is a+ // fingerprint of those values, so a poll that changed nothing leaves a+ // half-typed override alone — and an edit made in the route editor does+ // replace it, which is the honest outcome given the save would 409 anyway.+ //+ // The settings object is read through a ref for the same reason the panel+ // reads its connection through one: it is a new identity on every reload, so+ // depending on it directly would wipe the draft on a poll that changed+ // nothing. The two primitives decide WHEN; the ref carries WHAT.+ const settingsRef = useRef(route.settings);+ settingsRef.current = route.settings;+ useEffect(() => {+ setDraft(routeOverrideDraft(settingsRef.current));+ }, [route.providerId, route.settingsRevision]);++ const patch = useMemo(() => routeOverridePatch(route.settings, draft), [route.settings, draft]);+ const dirty = Object.keys(patch).length > 0;+ const fields = useMemo(() => orderedFields(route.settings), [route.settings]);+ const efforts = Array.isArray(route.effortLevels) ? route.effortLevels : [];+ // A stored level the current ladder no longer lists stays selectable, the+ // same way a model pin outside the catalog stays visible. Without it the+ // select would fall back to the blank option, and simply OPENING the panel+ // would read as "the human cleared the effort" and offer to save it.+ const stored = route.settings?.effort;+ const effortOptions = stored && !efforts.includes(stored) ? [...efforts, stored] : efforts;++ const set = (key, value) => setDraft((prev) => ({ ...prev, [key]: value }));+ const fieldId = (key) => `route-${route.providerId}-${key}`;++ return (+ <li className="rounded border border-port-border p-2">+ <div className="flex flex-wrap items-center gap-2 text-sm">+ <span className="rounded bg-port-bg px-1.5 py-0.5 text-xs uppercase">{route.mode}</span>+ <Link to={`/ai/edit/${route.providerId}`} className="text-port-accent hover:underline">+ {route.providerId}+ </Link>+ {isSystemDefault ? (+ <span className="flex items-center gap-1 text-xs text-port-success">+ <Star size={12} aria-hidden="true" /> system default+ </span>+ ) : (+ <button type="button" disabled={busy} onClick={() => onMakeDefault(route.providerId)}+ className="text-xs text-port-muted hover:underline disabled:opacity-50">+ Use as system default+ </button>+ )}+ {/* TUI only, and only once the server resolved a real command line. The+ link carries the provider id alone — the env it needs is secret and+ is re-resolved when the PTY spawns. */}+ {route.tuiCommandLine && (+ <Link+ to={`/shell?provider=${encodeURIComponent(route.providerId)}`}+ title={`Launch TUI in Shell: ${route.tuiCommandLine}`}+ className="flex items-center gap-1 rounded bg-port-accent/20 px-2 py-0.5 text-xs text-port-accent hover:bg-port-accent/30"+ >+ <Terminal size={12} aria-hidden="true" /> Launch in Shell+ </Link>+ )}+ {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>+ )}+ </div>++ {open && fields.length > 0 && (+ <div className="mt-2 space-y-2 border-t border-port-border pt-2">+ <div className="grid gap-2 sm:grid-cols-2">+ {fields.map((key) => (+ <label key={key} className="block text-sm" htmlFor={fieldId(key)}>+ <span className="mb-1 block text-xs text-port-muted">{FIELD_LABELS[key] || key}</span>+ {key === 'args' ? (+ <textarea+ id={fieldId(key)}+ rows={3}+ className={`${INPUT_CLASS} font-mono text-xs`}+ value={draft[key] ?? ''}+ onChange={(e) => set(key, e.target.value)}+ />+ ) : key === 'effort' ? (+ <select+ id={fieldId(key)}+ className={INPUT_CLASS}+ disabled={efforts.length === 0}+ value={draft[key] ?? ''}+ onChange={(e) => set(key, e.target.value)}+ >+ {/* A harness with no effort ladder gets a DISABLED control+ rather than a hidden field, so "this program takes no+ effort flag" is visible instead of reading as "unset". */}+ <option value="">+ {efforts.length === 0 ? 'This harness takes no effort setting' : 'Harness default'}+ </option>+ {effortOptions.map((level) => <option key={level} value={level}>{level}</option>)}+ </select>+ ) : (+ <input+ id={fieldId(key)}+ type={key === 'timeout' ? 'number' : 'text'}+ className={INPUT_CLASS}+ placeholder={key === 'timeout' ? 'Provider default' : 'Unpinned'}+ value={draft[key] ?? ''}+ onChange={(e) => set(key, e.target.value)}+ />+ )}+ </label>+ ))}+ </div>+ <p className="text-xs text-port-muted">+ These apply to this mode only — the other modes on this harness keep their own. Enabling+ a route and clearing a timeout stay on its editor.+ </p>+ <div className="flex flex-wrap gap-2">+ <button type="button" disabled={busy || blocked || !dirty}+ onClick={() => onSaveSettings(route, patch)}+ className="rounded bg-port-accent px-3 py-1 text-sm text-white disabled:opacity-50">+ Save overrides+ </button>+ <button type="button" disabled={!dirty}+ onClick={() => setDraft(routeOverrideDraft(route.settings))}+ className="rounded border border-port-border px-3 py-1 text-sm disabled:opacity-50">+ Revert+ </button>+ </div>+ </div>+ )}+ </li>+ );+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 53097f1897..5e938f0c39 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). |+| `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. || `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.jsindex ef9f107e24..875f9e8642 100644--- a/client/src/lib/providerManagement.js+++ b/client/src/lib/providerManagement.js@@ -126,3 +126,56 @@ export function catalogSummary(catalog) {}return { tone: 'muted', text: 'Not refreshed yet', detail: null };}++// --- route mode overrides (#6369) --------------------------------------------+//+// A route's `settings` are the fields that belong to ONE execution mode: its+// args, its timeout, its effort and its model pins. The server decides which+// keys a mode publishes, so these two helpers never name a field — they walk+// whatever the route was given, and a mode that gains or loses a setting needs+// no client change.++/** The draft an override form edits: every published setting as text. */+export const routeOverrideDraft = (settings) => Object.fromEntries(+ Object.entries(settings || {}).map(([key, value]) => [+ key,+ key === 'args' ? (Array.isArray(value) ? value : []).join('\n') : (value == null ? '' : String(value)),+ ]),+);++/**+ * The CHANGED keys between a route's saved settings and its draft.+ *+ * Only differences travel, so a save cannot rewrite a field the human never+ * touched — which matters here because these values are also edited from the+ * route editor and by model refresh.+ *+ * Two normalizations, both deliberate:+ *+ * - a blank text field is `null` (unpinned), never `''`. The server reads an+ * empty pin as unset too, so treating them as different values would make+ * every form dirty on open.+ * - a blank `timeout` is NO CHANGE rather than a clear. The executable+ * record's schema has no null timeout, so clearing one is the route+ * editor's job; silently sending `null` here would break its next save.+ */+export function routeOverridePatch(settings, draft) {+ const patch = {};+ for (const [key, current] of Object.entries(settings || {})) {+ const typed = draft?.[key] ?? '';+ if (key === 'args') {+ const next = String(typed).split('\n').map((line) => line.trim()).filter(Boolean);+ const before = Array.isArray(current) ? current : [];+ if (next.length !== before.length || next.some((arg, index) => arg !== before[index])) patch.args = next;+ continue;+ }+ if (key === 'timeout') {+ const next = Number(String(typed).trim());+ if (String(typed).trim() !== '' && Number.isInteger(next) && next !== current) patch.timeout = next;+ continue;+ }+ const next = String(typed).trim() === '' ? null : String(typed).trim();+ if (next !== (current ?? null)) patch[key] = next;+ }+ return patch;+}diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.jsindex fb56e8b8ca..38f86ed993 100644--- a/client/src/services/apiProviders.js+++ b/client/src/services/apiProviders.js@@ -157,3 +157,17 @@ export const deleteProviderConnection = (connectionId, options) => request(`/providers/connections/${encodeURIComponent(connectionId)}`,{ method: 'DELETE', ...options },);++/**+ * Edit ONE route's mode overrides — args, timeout, effort, model pins.+ *+ * `expectedRevision` is the route's `settingsRevision` from the management+ * graph, a fingerprint of the values on disk: a 409 means somebody (or the+ * route editor in another tab) changed them and the edit must be re-made+ * against a fresh read. Connection-owned values and the `enabled` flag are not+ * reachable here — those stay on the connection and the route editor.+ */+export const updateProviderRouteSettings = (providerId, body, options) => request(+ `/providers/routes/${encodeURIComponent(providerId)}`,+ { method: 'PATCH', body: JSON.stringify(body), ...options },+);diff --git a/server/lib/README.md b/server/lib/README.mdindex 7fb87e6457..7e189782d2 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. |+| `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. || `opencodeConfig.js` | OpenCode config builder — `buildOpencodeEnvVars(provider, model)` builds dynamic `OPENCODE_CONFIG_CONTENT` declaring model ids under the namespace the provider's marker selects: a local runtime (`ollama` / `mtplx` / `llama` / `vllm` / `sglang`, bare ids) or a hosted gateway from `providerGateways.js` (`vendor/model` ids kept whole). Fixes --model rejection. Also attaches the key for a key-bearing namespace, and pins `small_model` to the run model for a gateway so OpenCode's own side calls (titles, summarization) can't land on its built-in default — a billed model the operator never chose. Under a `no-tool` public-review profile it also applies `hardenOpencodeConfigForNoTool` — root `permission: deny`, an emptied tool map on every agent, `tool_call: false` on every declared model, and no MCP/plugins/share/autoupdate — which IS OpenCode's enforced tool-free recipe, since it ships no read-only argv flag (`providerVendors.js` pairs it with `run --agent` + `OPENCODE_PUBLIC_REVIEW_AGENT`). The harden step also copies `agent.build`'s generation settings onto that agent, so the stage's configured thinking effort reaches the model that actually runs. |diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex a35d30bba0..71f3f97d6b 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -14112,6 +14112,14 @@"server/routes/providers.js"]},+ {+ "method": "PATCH",+ "path": "/api/providers/routes/:providerId",+ "mountPath": "/api/providers",+ "sources": [+ "server/routes/providers.js"+ ]+ },{"method": "GET","path": "/api/providers/runtimes",@@ -17932,8 +17940,8 @@],"stats": {"mounts": 150,- "operations": 2221,- "declarations": 2229,+ "operations": 2222,+ "declarations": 2230,"sourceFiles": 233}}diff --git a/server/lib/index.js b/server/lib/index.jsindex cfa3819f7a..bcc3adf14b 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 './providerRouteSettings.js';export * from './personaTraitBlend.js';export * from './pipelineIssueOrder.js';export * from './postAdaptive.js';diff --git a/server/lib/providerGraphRecords.js b/server/lib/providerGraphRecords.jsindex 451f63597b..f90af3c9ac 100644--- a/server/lib/providerGraphRecords.js+++ b/server/lib/providerGraphRecords.js@@ -7,6 +7,7 @@ import {buildProviderGraphPreview,} from './providerGraphPreview.js';import { PROVIDER_HARNESS_IDS, ROUTE_MODES, providerRouteMode } from './providerHarnesses.js';+import { routeSettingsRevision, routeSettingsSchema } from './providerRouteSettings.js';// `PROVIDER_GRAPH_SCHEMA_VERSION` is deliberately NOT re-exported: it is one// wire version shared with the preview, and two flat `export *` modules in this@@ -83,6 +84,20 @@ const routeDtoSchema = z.object({modelMap: z.record(z.string(), 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+ // (#6369). Route-owned by construction: nothing here is connection state, so+ // editing it moves no other harness.+ settings: routeSettingsSchema,+ settingsRevision: z.string().min(1),+ // The effort ladder this route's harness actually accepts, or `null` for one+ // that takes no effort flag at all. Published rather than re-derived in the+ // browser so a renamed or path-configured binary still offers the right+ // levels — and so "no control" stays distinct from "an empty list".+ effortLevels: z.array(z.string()).nullable(),+ // Display half of the Shell hand-off, present only on a launchable TUI route.+ // The launch itself re-resolves this AND the provider's secret env server-side+ // (`shell:start { providerId }`), so the command line is never the contract.+ tuiCommandLine: z.string().optional(),}).strict();/** The full `GET /api/providers/management` body. */@@ -101,8 +116,17 @@ export const managementGraphSchema = z.object({* browser is told only WHETHER a connection has credentials and whether a* route's projection is settled. Every identity decision was already made* server-side on real values.+ *+ * `routeSettings` carries the per-route mode overrides the service resolved+ * from the live executable records (#6369). It arrives pre-resolved rather than+ * being read here because the TUI command line it also carries needs the host's+ * shell resolution, and this module stays pure. A route with no entry — a graph+ * 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.+ *+ * @param {{routeSettings?: Map<string, object>}} input*/-export function toManagementGraphDto({ connections, bindings, routes, activeProvider = null }) {+export function toManagementGraphDto({ connections, bindings, routes, activeProvider = null, routeSettings = new Map() }) {const blocked = new Set(routes.filter((route) => route.pending).map((route) => route.bindingId));return managementGraphSchema.parse({schemaVersion: PROVIDER_GRAPH_SCHEMA_VERSION,@@ -119,9 +143,22 @@ export function toManagementGraphDto({ connections, bindings, routes, activeProvbindings: 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 }) => ({- providerId, bindingId, mode, modelMap, projectionPending: Boolean(pending),- })),+ routes: routes.map(({ providerId, bindingId, mode, modelMap, pending }) => {+ const { settings = {}, effortLevels = null, tuiCommandLine = null } = routeSettings.get(providerId) || {};+ return {+ providerId,+ bindingId,+ mode,+ modelMap,+ projectionPending: Boolean(pending),+ settings,+ settingsRevision: routeSettingsRevision(settings),+ effortLevels,+ // Omitted rather than nulled: "not a launchable TUI" is the absence of+ // the affordance, not an empty command.+ ...(tuiCommandLine ? { tuiCommandLine } : {}),+ };+ }),});}diff --git a/server/lib/providerRouteSettings.js b/server/lib/providerRouteSettings.jsnew file mode 100644index 0000000000..939e5ed609--- /dev/null+++ b/server/lib/providerRouteSettings.js@@ -0,0 +1,111 @@+import { createHash } from 'node:crypto';+import { z } from 'zod';+import { ROUTE_MODES, providerRouteMode } from './providerHarnesses.js';++/**+ * The MODE-OVERRIDE half of a provider route (#6369).+ *+ * `providerConnections.js` splits a provider record into the values a shared+ * backend owns (endpoint, credentials, transport env vars). This module names+ * what is left that a human actually tunes per execution mode: the arguments+ * that mode launches with, how long it may run, its reasoning effort, and the+ * model each dispatch tier resolves to.+ *+ * The set is not invented here. `sharedModeUpdates` in the vendored toolkit+ * already declares exactly these mode-specific — "Arguments, timeouts, routing+ * consent and model pins remain mode-specific" — which is why a write built+ * from this table must go through `applyProviderPatches` (no sibling fan-out)+ * rather than `updateProvider`: a CLI route's `--effort` is not the TUI+ * route's, and spreading one onto the other would be the opposite of an+ * override. Execution CONSENT (`enabled`, the transport opt-ins) is deliberately+ * absent: granting it stays on `PATCH /api/providers/:id`.+ *+ * Pure: no I/O, no clock, no provider call.+ */++/** Nullable free-text: `null` is "unpinned", never the empty string. */+const nullableText = z.string().nullable();++/**+ * key → { modes, schema, read }.+ *+ * `modes` is honest about reach rather than about what the record schema+ * tolerates: `args` is a spawn concern, so an `api` route neither publishes nor+ * accepts one. `read` normalizes a stored value into the DTO shape, because an+ * absent key and a cleared pin must both read as `null` — a record that never+ * had a `heavyModel` and one whose pin was removed are the same state to a+ * human, and publishing `undefined` for one would make the fingerprint below+ * depend on key presence rather than on value.+ */+export const ROUTE_SETTING_FIELDS = Object.freeze({+ args: Object.freeze({+ modes: Object.freeze(['cli', 'tui']),+ schema: z.array(z.string()),+ read: (value) => (Array.isArray(value) ? value.filter((entry) => typeof entry === 'string') : []),+ }),+ timeout: Object.freeze({+ modes: ROUTE_MODES,+ schema: z.number().int().nullable(),+ read: (value) => (Number.isInteger(value) ? value : null),+ }),+ effort: Object.freeze({+ modes: ROUTE_MODES,+ schema: nullableText,+ read: (value) => (typeof value === 'string' && value !== '' ? value : null),+ }),+ defaultModel: Object.freeze({ modes: ROUTE_MODES, schema: nullableText, read: readPin }),+ lightModel: Object.freeze({ modes: ROUTE_MODES, schema: nullableText, read: readPin }),+ mediumModel: Object.freeze({ modes: ROUTE_MODES, schema: nullableText, read: readPin }),+ heavyModel: Object.freeze({ modes: ROUTE_MODES, schema: nullableText, read: readPin }),+ ultraModel: Object.freeze({ modes: ROUTE_MODES, schema: nullableText, read: readPin }),+});++function readPin(value) {+ return typeof value === 'string' && value !== '' ? value : null;+}++/** Every override key, in the order a route publishes them. */+export const ROUTE_SETTING_KEYS = Object.freeze(Object.keys(ROUTE_SETTING_FIELDS));++/** The keys that reach `mode`. An unknown mode reaches none. */+export const routeSettingKeys = (mode) =>+ ROUTE_SETTING_KEYS.filter((key) => ROUTE_SETTING_FIELDS[key].modes.includes(mode));++/** The DTO shape a route's `settings` takes on the wire. */+export const routeSettingsSchema = z.object(+ Object.fromEntries(ROUTE_SETTING_KEYS.map((key) => [key, ROUTE_SETTING_FIELDS[key].schema.optional()])),+).strict();++/**+ * The override values a provider record currently carries, for its own mode.+ *+ * A record whose `type` names no executable mode yields `{}` rather than a+ * guess: it is not a route, so it has no overrides to publish or accept.+ */+export function routeSettingsFor(provider) {+ const mode = providerRouteMode(provider);+ return Object.fromEntries(routeSettingKeys(mode)+ .map((key) => [key, ROUTE_SETTING_FIELDS[key].read(provider?.[key])]));+}++/**+ * A stale-edit fingerprint of one route's overrides.+ *+ * Deliberately a hash of the VALUES rather than a `revision` column on+ * `ai_route_bindings`. These fields live in `data/providers.json`, which the+ * route editor, a model refresh, a migration and a downgraded release all+ * write without touching the graph — so a row revision would only ever notice+ * a graph write and would sail straight past the edit a human is most likely to+ * collide with. Hashing what is actually on disk catches every writer.+ *+ * Truncated: this is a collision-detection token compared against a value taken+ * seconds earlier by the same install, not a content address.+ */+export const routeSettingsRevision = (settings) => createHash('sha256')+ .update(JSON.stringify(Object.entries(settings || {}).sort(([a], [b]) => a.localeCompare(b))))+ .digest('hex')+ .slice(0, 16);++/** Keys a caller sent that this route's mode does not accept. */+export const unsupportedRouteSettings = (mode, patch) =>+ Object.keys(patch || {}).filter((key) => !routeSettingKeys(mode).includes(key));diff --git a/server/lib/providerRouteSettings.test.js b/server/lib/providerRouteSettings.test.jsnew file mode 100644index 0000000000..93ac52adc3--- /dev/null+++ b/server/lib/providerRouteSettings.test.js@@ -0,0 +1,93 @@+/**+ * The two contracts the route-override boundary tests cannot pin (#6369).+ *+ * Everything about APPLYING an override is covered end to end in+ * `routes/providers.connectionManagement.test.js`. What a request never+ * exercises is the pair of couplings that would fail SILENTLY:+ *+ * - the HTTP schema and the published field table drifting apart, which makes+ * a field either uneditable or unpublished with no error anywhere;+ * - the stale-edit fingerprint depending on something other than the values,+ * which turns every save into a spurious 409 (or, worse, stops catching a+ * real concurrent edit).+ */++import { describe, expect, it } from 'vitest';+import {+ ROUTE_SETTING_KEYS,+ routeSettingKeys,+ routeSettingsFor,+ routeSettingsRevision,+} from './providerRouteSettings.js';+import { providerRouteSettingsUpdateSchema } from './validation.js';++/** One legal value per published key, so the schema can be probed key by key. */+const SAMPLE = {+ args: ['--verbose'],+ timeout: 60000,+ effort: 'high',+ defaultModel: 'example-model',+ lightModel: 'example-model',+ mediumModel: 'example-model',+ heavyModel: 'example-model',+ ultraModel: 'example-model',+};++describe('the accepted keys and the published keys', () => {+ it('lets the HTTP schema through for every field a route publishes', () => {+ // A field added to the table but not to the schema would be published on the+ // graph, rendered as an input, and 400 on save with no other test noticing.+ expect(Object.keys(SAMPLE).sort()).toEqual([...ROUTE_SETTING_KEYS].sort());+ for (const key of ROUTE_SETTING_KEYS) {+ const parsed = providerRouteSettingsUpdateSchema+ .safeParse({ expectedRevision: 'example-fingerprint', settings: { [key]: SAMPLE[key] } });+ expect(parsed.success, key).toBe(true);+ }+ });++ it('refuses a patch that names nothing, rather than rewriting the provider file', () => {+ expect(providerRouteSettingsUpdateSchema+ .safeParse({ expectedRevision: 'example-fingerprint', settings: {} }).success).toBe(false);+ });++ it('keeps spawn arguments off a direct API route', () => {+ expect(routeSettingKeys('cli')).toContain('args');+ expect(routeSettingKeys('api')).not.toContain('args');+ // An unrecognized mode is not a route, so it offers nothing rather than+ // defaulting to the full set.+ expect(routeSettingKeys('process')).toEqual([]);+ });+});++describe('the stale-edit fingerprint', () => {+ const provider = {+ id: 'example-cli',+ type: 'cli',+ command: 'claude',+ args: ['--verbose'],+ timeout: 60000,+ effort: 'high',+ defaultModel: 'example-model',+ };++ it('ignores the order the record happens to store its keys in', () => {+ const shuffled = { command: provider.command, effort: 'high', type: 'cli', args: ['--verbose'], id: provider.id, timeout: 60000, defaultModel: 'example-model' };+ expect(routeSettingsRevision(routeSettingsFor(shuffled)))+ .toBe(routeSettingsRevision(routeSettingsFor(provider)));+ });++ it('changes when any published value changes', () => {+ const before = routeSettingsRevision(routeSettingsFor(provider));+ for (const change of [{ args: [] }, { timeout: 61000 }, { effort: 'low' }, { heavyModel: 'other-model' }]) {+ expect(routeSettingsRevision(routeSettingsFor({ ...provider, ...change }))).not.toBe(before);+ }+ });++ it('reads an absent pin and a cleared pin as the same state', () => {+ // Otherwise a record that never had a `lightModel` and one whose pin was+ // removed would fingerprint differently, and one of them would 409 forever.+ expect(routeSettingsFor(provider).lightModel).toBeNull();+ expect(routeSettingsRevision(routeSettingsFor({ ...provider, lightModel: '' })))+ .toBe(routeSettingsRevision(routeSettingsFor(provider)));+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 590a5a0d30..78230bfe98 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -610,6 +610,39 @@ export const providerBindingUpdateSchema = z.object({selectedModels: z.array(z.string().trim().min(1).max(512)).max(1000).optional(),}).strict();+// PATCH /api/providers/routes/:providerId (#6369) — ONE route's mode overrides.+//+// Deliberately not `providerSchema.partial()`: that would reopen the whole+// executable record, including the connection-owned endpoint/key the graph+// projects and the `enabled` flag that grants execution consent. The accepted+// keys are exactly the route-owned table in `providerRouteSettings.js`;+// `providerRouteSettings.test.js` fails if the two ever drift.+//+// `expectedRevision` is a FINGERPRINT of the values on disk, not a row counter+// — these fields live in providers.json, which the route editor and a model+// refresh also write. An empty patch is refused rather than written: it would+// rewrite the provider file to say nothing.+//+// `timeout` takes no `null`. The executable record's own schema has no null+// timeout, so storing one here would 400 the next save from the route editor;+// clearing a custom timeout stays that editor's job.+const nullableModelPin = z.preprocess(emptyToNull, z.string().trim().max(512).nullable());+export const providerRouteSettingsUpdateSchema = z.object({+ expectedRevision: z.string().trim().min(1).max(64),+ settings: z.object({+ args: z.array(z.string().trim().min(1).max(2048)).max(200).optional(),+ timeout: z.number().int().min(AI_RUN_TIMEOUT_MIN_MS).max(AI_RUN_TIMEOUT_MAX_MS).optional(),+ effort: z.preprocess(emptyToNull, z.enum(EFFORT_LEVELS).nullable()).optional(),+ defaultModel: nullableModelPin.optional(),+ lightModel: nullableModelPin.optional(),+ mediumModel: nullableModelPin.optional(),+ heavyModel: nullableModelPin.optional(),+ ultraModel: nullableModelPin.optional(),+ }).strict().refine((value) => Object.keys(value).length > 0, {+ message: 'Name at least one setting to change',+ }),+}).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.jsindex 0934b8a845..75c4c97ccb 100644--- a/server/routes/providers.connectionManagement.test.js+++ b/server/routes/providers.connectionManagement.test.js@@ -444,3 +444,162 @@ describe('a partially reachable backend', () => {expect(res.body.failedGroups).toBe(1);});});++describe('PATCH /api/providers/routes/:providerId', () => {+ /** The fingerprint the panel would have been holding. Read the way a browser reads it. */+ const routeFromGraph = async (providerId) => {+ const res = await request(app()).get('/api/providers/management');+ return res.body.routes.find((route) => route.providerId === providerId);+ };++ it('changes ONE mode and leaves its sibling mode alone', async () => {+ const cli = await routeFromGraph('claude-ollama');+ providerService.applyProviderPatches.mockClear();++ const res = await request(app())+ .patch('/api/providers/routes/claude-ollama')+ .send({+ expectedRevision: cli.settingsRevision,+ settings: { args: ['--verbose'], effort: 'high', heavyModel: 'example-model' },+ });++ expect(res.status).toBe(200);+ const [patches] = providerService.applyProviderPatches.mock.calls.at(-1);+ // The TUI route on the same harness shares this backend but NOT this+ // mode's arguments — the whole reason the write skips `updateProvider`.+ expect(Object.keys(patches)).toEqual(['claude-ollama']);+ expect(patches['claude-ollama']).toEqual({ args: ['--verbose'], effort: 'high', heavyModel: 'example-model' });+ // Route-owned, so no connection value moved and nothing was projected:+ // the binding must not be detached by an override edit.+ expect(store.saveConnectionSettings).not.toHaveBeenCalled();+ expect(store.commitPendingProjection).not.toHaveBeenCalled();+ });++ it('refuses an edit made against settings that have since moved', async () => {+ const res = await request(app())+ .patch('/api/providers/routes/claude-ollama')+ .send({ expectedRevision: 'from-a-panel-that-had-moved-on', settings: { effort: 'high' } });++ expect(res.status).toBe(409);+ expect(res.body.code).toBe('PROVIDER_GRAPH_STALE_REVISION');+ expect(providerService.applyProviderPatches).not.toHaveBeenCalled();+ });++ it('rejects a connection-owned field and an execution-consent field', async () => {+ const cli = await routeFromGraph('claude-ollama');+ providerService.applyProviderPatches.mockClear();++ for (const settings of [{ endpoint: 'http://127.0.0.1:22222' }, { enabled: true }, { envVars: {} }]) {+ const res = await request(app())+ .patch('/api/providers/routes/claude-ollama')+ .send({ expectedRevision: cli.settingsRevision, settings });+ expect(res.status).toBe(400);+ }+ expect(providerService.applyProviderPatches).not.toHaveBeenCalled();+ });++ it('refuses an effort level this harness does not accept', async () => {+ const cli = await routeFromGraph('claude-ollama');+ providerService.applyProviderPatches.mockClear();++ // `minimal` is a real effort level — for Codex. Claude's ladder starts at+ // `low`, so storing it would be a value the spawn silently drops.+ const res = await request(app())+ .patch('/api/providers/routes/claude-ollama')+ .send({ expectedRevision: cli.settingsRevision, settings: { effort: 'minimal' } });++ expect(res.status).toBe(400);+ expect(res.body.code).toBe('PROVIDER_ROUTE_EFFORT_UNSUPPORTED');+ expect(providerService.applyProviderPatches).not.toHaveBeenCalled();+ });++ it('refuses launch arguments on a direct API route, which spawns nothing', async () => {+ const API_BINDING = '66666666-6666-4666-8666-666666666666';+ const API_PROVIDER = {+ id: 'example-api',+ name: 'Example API',+ type: 'api',+ endpoint: 'https://api.example.com/v1',+ apiKey: 'example-api-key',+ models: ['example-model'],+ enabled: true,+ };+ const fixture = graphFixture();+ fixture.bindings.push({+ id: API_BINDING, revision: 1, connectionId: OTHER_CONNECTION, harnessId: null,+ variantKey: 'default', label: 'Direct API', enabled: true, selectedModels: [],+ });+ fixture.routes.push({+ providerId: 'example-api', bindingId: API_BINDING, mode: 'api',+ modelMap: {}, projected: {}, pending: null, pendingRevision: null,+ });+ store.readGraph.mockResolvedValue(fixture);+ providerService.getAllProviders.mockResolvedValue({+ activeProvider: 'claude-ollama',+ providers: [structuredClone(CLAUDE_CLI), structuredClone(CLAUDE_TUI), structuredClone(CODEX_CLI),+ structuredClone(API_PROVIDER)],+ });++ const apiRoute = await routeFromGraph('example-api');+ // An API route has no spawn, so it never offers the field in the first place.+ expect(apiRoute.settings).not.toHaveProperty('args');+ expect(apiRoute.settings).toHaveProperty('defaultModel');+ providerService.applyProviderPatches.mockClear();++ const res = await request(app())+ .patch('/api/providers/routes/example-api')+ .send({ expectedRevision: apiRoute.settingsRevision, settings: { args: ['--yolo'] } });++ expect(res.status).toBe(400);+ expect(res.body.code).toBe('PROVIDER_ROUTE_SETTING_UNSUPPORTED');+ expect(providerService.applyProviderPatches).not.toHaveBeenCalled();+ });++ it('404s a provider id the graph does not route', async () => {+ const res = await request(app())+ .patch('/api/providers/routes/not-a-route')+ .send({ expectedRevision: 'anything', settings: { effort: 'high' } });++ expect(res.status).toBe(404);+ expect(providerService.applyProviderPatches).not.toHaveBeenCalled();+ });++ it('refuses while the route is mid-projection', async () => {+ const cli = await routeFromGraph('claude-ollama');+ const fixture = graphFixture();+ fixture.routes[0].pending = ownedSnapshot();+ store.readGraph.mockResolvedValue(fixture);+ providerService.applyProviderPatches.mockClear();++ const res = await request(app())+ .patch('/api/providers/routes/claude-ollama')+ .send({ expectedRevision: cli.settingsRevision, settings: { effort: 'high' } });++ expect(res.status).toBe(409);+ expect(res.body.code).toBe('PROVIDER_GRAPH_BINDING_BLOCKED');+ expect(providerService.applyProviderPatches).not.toHaveBeenCalled();+ });+});++describe('what a route row can act on', () => {+ it('offers the Shell hand-off on the TUI route only, and never its env', async () => {+ const res = await request(app()).get('/api/providers/management');+ const byId = Object.fromEntries(res.body.routes.map((route) => [route.providerId, route]));++ expect(byId['claude-ollama-tui'].tuiCommandLine).toContain('claude');+ // A CLI route is not launchable by hand, so it carries no command at all —+ // absent rather than empty, so the button cannot render on a blank string.+ expect(byId['claude-ollama']).not.toHaveProperty('tuiCommandLine');+ expect(JSON.stringify(res.body)).not.toContain(TOKEN);+ });++ it('publishes the effort ladder the harness really accepts', async () => {+ const res = await request(app()).get('/api/providers/management');+ const byId = Object.fromEntries(res.body.routes.map((route) => [route.providerId, route]));++ expect(byId['claude-ollama'].effortLevels).toContain('high');+ // Distinguishable from an empty ladder: `null` is "this harness has no+ // effort control", which the panel renders as a disabled select.+ expect(byId['codex-ollama'].effortLevels).toContain('minimal');+ });+});diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 8c54b7d7bb..69762ab4c6 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -9,6 +9,7 @@ import {unlinkBinding,updateBindingSettings,updateConnectionSettings,+ updateRouteSettings,} from '../services/providerGraph.js';import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';@@ -28,6 +29,7 @@ import {providerBindingUnlinkSchema,providerBindingUpdateSchema,providerConnectionUpdateSchema,+ providerRouteSettingsUpdateSchema,} from '../lib/validation.js';import {getProviderRuntimeStatus,@@ -385,6 +387,24 @@ export function createPortOSProviderRoutes(aiToolkit) {res.json(await updateBindingSettings({ bindingId: req.params.id, ...input }));}));+ /**+ * Edit ONE route's mode overrides (#6369) — args, timeout, effort, model pins.+ *+ * The per-mode counterpart to the shared-backend edit above, so a whole+ * backend is configurable from one screen instead of a connection plus three+ * route editors. Route-owned only: an endpoint, a credential and the `enabled`+ * flag are all unreachable here by construction, and `PATCH+ * /api/providers/:id` remains the place execution consent is granted.+ *+ * `expectedRevision` is the route's `settingsRevision` from+ * `GET /api/providers/management` — a fingerprint of the values on disk, so an+ * edit made in the route editor while this panel was open is a 409 too.+ */+ router.patch('/routes/:providerId', asyncHandler(async (req, res) => {+ const input = validateRequest(providerRouteSettingsUpdateSchema, req.body ?? {});+ res.json(await updateRouteSettings({ 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.jsindex d31f0c877f..bd1eaf3cef 100644--- a/server/services/providerGraph.js+++ b/server/services/providerGraph.js@@ -11,6 +11,13 @@ import {toManagementGraphDto,} from '../lib/providerGraphRecords.js';import { resolveRouteModels } from '../lib/providerGraphPreview.js';+import { effortLevelsForProvider } from '../lib/providerModels.js';+import {+ routeSettingsFor,+ routeSettingsRevision,+ unsupportedRouteSettings,+} from '../lib/providerRouteSettings.js';+import { buildTuiShellLaunch } from '../lib/tuiShellLaunch.js';import { requireToolkit } from '../lib/aiToolkitState.js';import {acknowledgeProjection,@@ -164,11 +171,36 @@ export async function initProviderGraph() {*/export const onProvidersSaved = () => reconcileProviderGraph('legacy-write');+/**+ * What one executable record contributes to its route's DTO: the overrides this+ * mode carries, the effort ladder its harness really accepts, and — for a+ * launchable TUI — the command line the Shell page would show.+ *+ * The command line is DISPLAY ONLY and its env half is dropped here: a launch+ * goes through `shell:start { providerId }`, which re-resolves both server-side,+ * so the provider's secret env never reaches a management payload.+ */+function describeRoute(provider) {+ const settings = routeSettingsFor(provider);+ return {+ settings,+ effortLevels: effortLevelsForProvider(provider, settings.defaultModel ?? null),+ tuiCommandLine: buildTuiShellLaunch(provider)?.commandLine ?? null,+ };+}+/** The sanitized `GET /api/providers/management` body. */export async function getManagementGraph() {requireGraph();const [graph, data] = await Promise.all([readGraph(), providerService().getAllProviders()]);- return toManagementGraphDto({ ...graph, activeProvider: data.activeProvider });+ // Only the records the graph actually routes: an unmapped legacy provider has+ // no row to decorate, and resolving a shell invocation for it would be work+ // this response throws away.+ const byId = new Map(data.providers.map((provider) => [provider.id, provider]));+ const routeSettings = new Map(graph.routes+ .filter((route) => byId.has(route.providerId))+ .map((route) => [route.providerId, describeRoute(byId.get(route.providerId))]));+ return toManagementGraphDto({ ...graph, activeProvider: data.activeProvider, routeSettings });}// --- link / unlink -----------------------------------------------------------@@ -346,14 +378,29 @@ async function projectRoutes(providerIds, connection) {if (projections.length === 0) return [];await commitPendingProjection(projections);- reconciling = true;- const written = await providerService().applyProviderPatches(Object.fromEntries(+ const written = await writeProviderPatches(Object.fromEntries(projections.map(({ providerId, owned }) => [providerId, projectionPatch(byId.get(providerId), owned)]),- )).finally(() => { reconciling = false; });+ ));await acknowledgeProjection(written);return written;}+/**+ * Write `providers.json` from INSIDE a serialized graph pass.+ *+ * The latch is load-bearing, not defensive: the toolkit's post-save hook calls+ * back into `reconcileProviderGraph`, which queues behind the pass currently+ * awaiting this write. Holding `reconciling` makes that call return+ * immediately, so the pass cannot wait on work that is waiting on the pass.+ *+ * @param {Record<string, object>} patches - provider id → partial update+ * @returns {Promise<string[]>} the ids that existed and were written+ */+function writeProviderPatches(patches) {+ reconciling = true;+ return providerService().applyProviderPatches(patches).finally(() => { reconciling = false; });+}+/*** The connection-owned snapshot a route should carry once bound to* `connection`: the record's own owned KEY SET (so the split stays lossless for@@ -550,3 +597,79 @@ export function refreshConnectionCatalog(connectionId) {return { connectionId: connection.id, catalog, probedGroups: groups.length, failedGroups: failures.length };});}++/**+ * Edit ONE route's mode overrides — its args, timeout, effort and model pins.+ *+ * The counterpart to `updateConnectionSettings`: that one changes a value every+ * harness on the backend shares, this one changes a value that belongs to a+ * single execution mode. Both live on this screen so a human stops bouncing+ * between a connection and three route editors to configure one backend.+ *+ * Three rules make it a genuine OVERRIDE rather than a second way to edit a+ * provider:+ *+ * - **No sibling fan-out.** The write goes through `applyProviderPatches`,+ * which names exactly this route. `updateProvider` would spread the edit+ * onto the record's sibling modes, and a CLI route's `--effort` is not the+ * TUI route's.+ * - **No connection-owned field is reachable.** The accepted key set is the+ * route-owned table in `providerRouteSettings.js`, so an endpoint or a+ * credential can never be retyped here and silently escape the projection+ * that keeps every other harness on the backend in step.+ * - **No execution consent.** `enabled` and the transport opt-ins are absent+ * from that table; granting them stays an explicit act on the route editor.+ *+ * The stale check is a fingerprint of the values as they are ON DISK, so an+ * edit made in `/ai/edit/:providerId` while this panel was open is caught too —+ * see `routeSettingsRevision`.+ */+export function updateRouteSettings({ providerId, expectedRevision, settings }) {+ 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]);++ const { providers } = await providerService().getAllProviders();+ const provider = providers.find((candidate) => candidate.id === providerId);+ // A graph row whose record is gone is a reconciliation removal in flight.+ // Reported as the same 404, because there is nothing left to override.+ if (!provider) throw new ServerError('Route not found', { status: 404, code: 'ROUTE_NOT_FOUND' });++ const current = routeSettingsFor(provider);+ if (routeSettingsRevision(current) !== expectedRevision) throw stale("This route's settings");++ const unsupported = unsupportedRouteSettings(route.mode, settings);+ if (unsupported.length > 0) {+ throw new ServerError(`A ${route.mode} route has no ${unsupported.join(', ')} setting`,+ { status: 400, code: 'PROVIDER_ROUTE_SETTING_UNSUPPORTED' });+ }++ // Effort is a harness capability, not free text: a route whose program takes+ // no `--effort` gets no control, and a level outside its ladder would be+ // stored and then silently dropped at spawn time.+ if (settings.effort != null) {+ const levels = effortLevelsForProvider(provider, settings.defaultModel ?? current.defaultModel ?? null);+ if (!levels || !levels.includes(settings.effort)) {+ throw new ServerError(+ levels+ ? `This route accepts effort ${levels.join(', ')}`+ : 'This route\'s harness takes no effort setting',+ { status: 400, code: 'PROVIDER_ROUTE_EFFORT_UNSUPPORTED' });+ }+ }++ const next = { ...current, ...settings };+ const applied = await writeProviderPatches({ [providerId]: settings });+ if (applied.length === 0) throw new ServerError('Route not found', { status: 404, code: 'ROUTE_NOT_FOUND' });++ // No graph row is touched on purpose. These fields are route-owned, so the+ // connection's `projected` snapshot still describes the record accurately+ // and the binding must NOT be detached — the reconcile this write triggers+ // is a documented no-op.+ console.log(`🔗 Updated route ${providerId} overrides: ${Object.keys(settings).join(', ')}`);+ return { providerId, settings: next, settingsRevision: routeSettingsRevision(next) };+ });+}