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
refuse a TUI mode for a harness already paired under a `-cli` id
[._.]/ Adam Eivy380886ecfa32
diff --git a/client/src/components/providers/ProviderCard.test.jsx b/client/src/components/providers/ProviderCard.test.jsxindex 247c456250..14ab3b1887 100644--- a/client/src/components/providers/ProviderCard.test.jsx+++ b/client/src/components/providers/ProviderCard.test.jsx@@ -336,12 +336,13 @@ describe('ProviderCard "Add interactive mode"', () => {expect(onAddTuiMode).toHaveBeenCalledWith(provider);});- it('offers nothing on an already-unified card, a TUI record, or an api record', () => {- const expectNoAction = () => expect(screen.queryByRole('button', { name: /Add interactive mode/ })).toBeNull();-- // Unified: the pair exists, so there is nothing to add. Flagged `true` on- // purpose — the server would never say so, and this pins that a card- // rendering a stale list still refuses rather than offering a second TUI.+ it('offers nothing on an already-unified card, whatever the server flagged', () => {+ // Flagged `true` on purpose: the card's own `!unified` guard is what this+ // pins, so a stale list still refuses rather than offering a second TUI+ // mode beside the one already on the card. (Which RECORDS qualify — a TUI+ // record, an api record, a CLI-only harness — is the server's rule, pinned+ // where it lives in routes/providers.tuiMode.test.js; the card reads only+ // the flag and never looks at `type`.)const cli = cliRecord();const tui = wrapper({ id: 'opencode-tui', name: 'OpenCode TUI' });renderCard(@@ -349,14 +350,12 @@ describe('ProviderCard "Add interactive mode"', () => {null,{ providersById: { 'opencode-cli': cli, 'opencode-tui': tui } },);- expectNoAction();-- // A TUI record: the CLI id is the stem, so minting it here is a rename.- renderCard(wrapper());- expectNoAction();+ expect(screen.queryByRole('button', { name: /Add interactive mode/ })).toBeNull();+ });- renderCard(wrapper({ id: 'openai', name: 'OpenAI', type: 'api' }));- expectNoAction();+ it('offers nothing when the server did not flag the record', () => {+ renderCard(cliRecord({ canAddTuiMode: false }));+ expect(screen.queryByRole('button', { name: /Add interactive mode/ })).toBeNull();});it('shows the in-flight state rather than letting a second click mint twice', () => {diff --git a/server/lib/README.md b/server/lib/README.mdindex d10c0a62f4..60cb2189fb 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -233,7 +233,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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; `routeBelongsOnConnection` answers whether a stored connection still CONTAINS the backend one route describes (the create-time and reconcile-time test, looser than `sameConnectionIdentity`); 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. |-| `providerModePairing.js` | May an existing record gain the OTHER execution mode of its harness (#7501) — `tuiModeAddition(provider, providers)` is the ONE verdict behind both the `canAddTuiMode` flag the provider list decorates each record with (so the card offers "Add interactive mode") and the refusal `POST /api/providers/:id/modes/tui` answers with, so a card can never advertise an action the server rejects. Refuses a non-CLI record (the CLI id is the stem, so minting it from a TUI record would be a rename), a record storing no command, and a KNOWN harness declaring no TUI mode; an UNKNOWN harness passes with empty argv rather than a guess, while a known one starts from its recipe’s proven interactive line. A taken `<stem>-tui` id answers 409 rather than being suffixed around — the CLI half is already fixed, so something else is standing there. Pure: no I/O. |+| `providerModePairing.js` | May an existing record gain the OTHER execution mode of its harness (#7501) — `tuiModeAddition(provider, providers, executionModes?)` is the ONE verdict behind both the `canAddTuiMode` flag `GET /providers` decorates each record with (so the card offers "Add interactive mode") and the refusal `POST /providers/:id/modes/tui` answers with, so a card can never advertise an action the server rejects. Refuses a non-CLI record (the CLI id is the stem, so minting it from a TUI record would be a rename), a record storing no command, and a KNOWN harness declaring no TUI mode; an UNKNOWN harness passes with empty argv rather than a guess, while a known one starts from its recipe’s proven interactive line. Asks whether the harness already HAS its interactive mode (the record’s `providerModeGroups` group — the shipped `grok-cli`/`grok-tui` pair leaves `grok-cli-tui` unclaimed, so an id-only check would mint a third record beside it), and separately 409s on a taken `<id>-tui` rather than suffixing around it. Pure: no I/O. || `providerRouteRecipes.js` | Minting a FRESH executable route from a connection and a harness command recipe (#6369) — the reverse of `providerConnections.js`, which reads an existing record. `buildRouteRecord({harnessId, mode, providerId, name, connection})` materializes a connection's endpoint, credentials and backend marker into a DISABLED `data/providers.json` record through `PROVIDER_HARNESSES[].recipe`; `mintRouteIds` allocates readable ids keeping the `<stem>` / `<stem>-tui` pairing `providerModeGroups` recognizes; `bindingBlocker` is the pre-write refusal (no recipe, unsupported mode, a transport the backend does not declare, a credential the program requires); `CREATABLE_CONNECTION_KINDS` / `connectionKindLabel` / `connectionKindMarkers` bound the backends a route can honestly describe (`slotstream` and `vendor` deliberately excluded); `bindingProtocol` names the wire a binding needs. Pure: no I/O, no spawn, 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/`), `parseKimiWireLog`/`parseKimiSessionIndex` (`~/.kimi-code/sessions/.../agents/<id>/wire.jsonl`, indexed by `~/.kimi-code/session_index.jsonl`), `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. Kimi's `usage.record` lines are already discrete per-call deltas (no cumulative-snapshot trap), but split across one `wire.jsonl` per agent — a subagent's spend is never in its parent's file. 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`. |diff --git a/server/lib/aiToolkit/internal/providerModes.js b/server/lib/aiToolkit/internal/providerModes.jsindex df4cac036a..c580cc1ecf 100644--- a/server/lib/aiToolkit/internal/providerModes.js+++ b/server/lib/aiToolkit/internal/providerModes.js@@ -17,24 +17,24 @@ const MODE_KEY_DEFAULTS = { endpoint: '', apiKey: '', envVars: {}, credentialBooexport const MODE_GROUPED_KEYS = Object.freeze(['endpoint', 'apiKey', 'envVars', 'credentialBootstrap']);/**- * Fields that describe the CLI mode's own transport and must NOT ride along to- * the TUI sibling {@link expandModePair} mints beside it.+ * Fields belonging to the CLI mode ALONE, which must not ride the shared body+ * to the TUI sibling {@link expandModePair} mints beside it.*- * `headlessArgs` is the non-interactive argv, meaningless to a PTY launch.- * `textTransport` and its two consents describe the Codex app-server path the- * CLI record speaks; copied onto the sibling they make a SECOND record answer- * `isCodexTextTransportEnabled`, so a text call could be routed to a record- * whose whole contract is "a human drives this in a terminal".+ * `headlessArgs` is the non-interactive argv — a flag list handed to a program+ * being driven without a terminal, meaningless to a PTY launch, and already+ * declared mode-specific by `PROVIDER_MODE_OVERRIDE_KEYS`.+ *+ * Deliberately NOT here: `textTransport` and its consents. A record ADVERTISING+ * the Codex app-server transport is not a record permitted to use it — the two+ * explicit consents are, and they are never fanned out (see+ * `sharedModeUpdates`). The shipped Codex pair declares the transport on BOTH+ * modes, so dropping it would make a hand-minted pair differ from the seeded+ * one for the same program.** Every key here must stay clear of {@link MODE_GROUPED_KEYS} — dropping one of* those would mint a pair `providerModeGroups` then refuses to group.*/-export const CLI_ONLY_KEYS = Object.freeze([- 'headlessArgs',- 'textTransport',- 'textTransportEnabled',- 'textTransportReadRiskAcknowledged',-]);+export const CLI_ONLY_KEYS = Object.freeze(['headlessArgs']);export function providerModeGroups(providers) {const byId = new Map(providers.map(provider => [provider.id, provider]));@@ -140,6 +140,37 @@ export function unifyProviderModes(data) {export const modeSiblingId = (stem, mode) => (mode === 'tui' ? `${stem}-tui` : stem);export const modeSiblingName = (name, mode) => (mode === 'tui' ? `${name} TUI` : name);+/**+ * ONE mode's create payload, derived from the body both modes share.+ *+ * The single writer of the pair convention: every {@link MODE_GROUPED_KEYS}+ * field (and `command`) comes from the shared body, and only `id`, `name`,+ * `type`, the {@link CLI_ONLY_KEYS} the TUI half must not inherit, and this+ * mode's own declared overrides differ. Mint a sibling any other way and+ * `providerModeGroups` stops seeing one harness.+ *+ * The shared body is the CLI mode's, so the drop is one-sided — and a value+ * declared explicitly in `overrides` still wins, because it lands after.+ *+ * @param {{id?:string, name:string}} shared - the body both modes are built from+ * @param {'cli'|'tui'} mode+ * @param {object} [overrides] - this mode's own fields (argv, prompt delay)+ */+export function modeSiblingPayload(shared, mode, overrides = {}) {+ const stem = shared.id || String(shared.name).toLowerCase().replace(/[^a-z0-9]/g, '-');+ const inherited = mode === 'tui'+ ? Object.fromEntries(Object.entries(shared).filter(([key]) => !CLI_ONLY_KEYS.includes(key)))+ : shared;++ return {+ ...inherited,+ ...overrides,+ id: modeSiblingId(stem, mode),+ name: modeSiblingName(shared.name, mode),+ type: mode,+ };+}+/*** Split one dual-mode create body into its per-mode create payloads, or `null`* when the body declares no `modes`.@@ -148,19 +179,7 @@ export const modeSiblingName = (name, mode) => (mode === 'tui' ? `${name} TUI` :* backend, but a record stores exactly one `type` — so configuring both used to* mean adding the same command twice and hoping the two records happened to* satisfy the pairing rule above. This mints them in that shape by- * construction: every {@link MODE_GROUPED_KEYS} field (and `command`) comes- * from the shared body, and only `id`, `name`, `type`, the- * {@link CLI_ONLY_KEYS} the TUI half must not inherit, and the mode's own- * declared overrides differ.- *- * The shared body is the CLI mode's, so the drop is one-sided: a value declared- * explicitly under `modes.tui` still wins, because the per-mode overrides land- * after it.- *- * Also the minter for a TUI sibling added to an EXISTING CLI record — pass that- * record as the body with `modes: { cli: {}, tui: overrides }` and take the- * second payload. The id/name convention then has exactly one writer whether a- * pair is born together or completed later.+ * construction, through {@link modeSiblingPayload}.** @param {{modes?:Record<string,object>, id?:string, name:string}} providerData* @returns {object[]|null} one create payload per mode, CLI first@@ -170,14 +189,5 @@ export function expandModePair(providerData) {if (!modes || typeof modes !== 'object') return null;const { modes: _modes, ...shared } = providerData;- const stem = shared.id || String(shared.name).toLowerCase().replace(/[^a-z0-9]/g, '-');- const tuiShared = Object.fromEntries(Object.entries(shared).filter(([key]) => !CLI_ONLY_KEYS.includes(key)));-- return ['cli', 'tui'].map((mode) => ({- ...(mode === 'tui' ? tuiShared : shared),- ...modes[mode],- id: modeSiblingId(stem, mode),- name: modeSiblingName(shared.name, mode),- type: mode,- }));+ return ['cli', 'tui'].map((mode) => modeSiblingPayload(shared, mode, modes[mode]));}diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex de94a3ed2a..b51c68ac58 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -1,5 +1,5 @@import { composeBootstrapSpawn } from './internal/credentialBootstrap.js';-import { expandModePair, providerModeGroups, sharedModeUpdates, unifyProviderModes } from './internal/providerModes.js';+import { expandModePair, modeSiblingPayload, providerModeGroups, sharedModeUpdates, unifyProviderModes } from './internal/providerModes.js';import { readFile, rename } from 'fs/promises';import { existsSync } from 'fs';import { join, dirname, delimiter, isAbsolute } from 'path';@@ -834,11 +834,12 @@ export function createProviderService(config = {}) {* and leave two unrelated routes. Everything but the mode's own argv comes* across unchanged, which is what makes the result groupable.*- * Routed through {@link expandModePair} so the `<stem>` / `<stem>-tui` id- * and name convention has ONE writer whether a pair is born together or- * completed later. The CLI id is already fixed, so a taken sibling id is- * not a collision to suffix around — it is something else already standing- * there, and this throws rather than guessing.+ * Routed through {@link modeSiblingPayload} — the same writer a dual-mode+ * create goes through — so the `<stem>` / `<stem>-tui` id and name+ * convention has ONE spelling whether a pair is born together or completed+ * later. The CLI id is already fixed, so a taken sibling id is not a+ * collision to suffix around — it is something else already standing there,+ * and this throws rather than guessing.** @param {string} id - the CLI record to derive from* @param {object} [tuiOverrides] - mode-specific fields, typically `args`@@ -850,8 +851,7 @@ export function createProviderService(config = {}) {if (!stored) return null;if (stored.type !== 'cli') throw new Error('Only a CLI provider can gain a TUI mode');- const [, tuiData] = expandModePair({ ...stored, modes: { cli: {}, tui: tuiOverrides } });- const created = buildProviderRecord(data.providers, tuiData);+ const created = buildProviderRecord(data.providers, modeSiblingPayload(stored, 'tui', tuiOverrides));storeProviderRecords(data, [created]);await saveProviders(data);return created;diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.jsindex 9afb0c8fe0..8965b50e72 100644--- a/server/lib/aiToolkit/providers.test.js+++ b/server/lib/aiToolkit/providers.test.js@@ -81,7 +81,6 @@ describe('Provider Service', () => {id: 'example', name: 'Example Agent', type: 'cli', command: 'example', enabled: true,args: ['--print'], headlessArgs: ['--quiet'], models: ['a'], defaultModel: 'a',endpoint: 'https://backend.example.com', apiKey: 'sk-test', envVars: { EXAMPLE_HOME: '/opt/example' },- textTransport: 'codex-app-server', textTransportEnabled: true,},} }));@@ -97,12 +96,10 @@ describe('Provider Service', () => {envVars: { EXAMPLE_HOME: '/opt/example' },enabled: true,});- // CLI-only transport fields did NOT: a second record advertising the Codex- // app-server transport would let a text call be routed to a record whose- // whole contract is "a human drives this in a terminal".+ // The CLI's non-interactive argv did NOT — it is a flag list for a program+ // being driven without a terminal, and inheriting it would hand those flags+ // to a PTY launch.expect(tui.headlessArgs).toEqual([]);- expect(tui).not.toHaveProperty('textTransport');- expect(tui).not.toHaveProperty('textTransportEnabled');// The grouping CONSEQUENCE, not just "two records exist": disabling one// mode disables the harness, which only happens for a real pair.diff --git a/server/lib/providerModePairing.js b/server/lib/providerModePairing.jsindex eb29026eff..0f8cc5d062 100644--- a/server/lib/providerModePairing.js+++ b/server/lib/providerModePairing.js@@ -12,21 +12,24 @@*/import { harnessForProvider, harnessRecipe, harnessSupportsMode } from './providerHarnesses.js';-import { modeSiblingId } from './aiToolkit/internal/providerModes.js';+import { modeSiblingId, providerModeGroups } from './aiToolkit/internal/providerModes.js';/*** Whether a TUI sibling can be minted for `provider`, and with which argv.*- * A refusal carries the HTTP status the endpoint answers with, because the two+ * A refusal carries the HTTP status the endpoint answers with, because the* refusals mean different things to a caller: a record that can never have a- * TUI mode is a bad request, while a sibling id that is already taken is a- * conflict with something standing in that slot.+ * TUI mode is a bad request, while a harness that already HAS one — or a+ * sibling id something else is standing in — is a conflict.** @param {object|null|undefined} provider - the record to derive from- * @param {object[]} providers - every stored provider, for the id-collision check+ * @param {object[]} providers - every stored provider, for the pairing and id checks+ * @param {{id:string,type:string}[]|null} [executionModes] - this record's mode+ * group when the caller already computed it (the provider list does, per+ * record); derived here otherwise* @returns {{ok:true, args:string[]}|{ok:false, status:number, code:string, message:string}}*/-export function tuiModeAddition(provider, providers = []) {+export function tuiModeAddition(provider, providers = [], executionModes = null) {const refuse = (status, code, message) => ({ ok: false, status, code, message });if (provider?.type !== 'cli') {@@ -47,6 +50,18 @@ export function tuiModeAddition(provider, providers = []) {return refuse(400, 'TUI_MODE_UNSUPPORTED', `${harness.label} has no interactive mode.`);}+ // Ask whether this harness ALREADY has its interactive mode, not merely+ // whether `<id>-tui` is free — `providerModeGroups` also pairs `<stem>-cli`+ // with `<stem>-tui`, so the shipped `grok-cli` is already half of a pair+ // while `grok-cli-tui` sits unclaimed. Checking only the id would flag it and+ // then mint a pointless third record beside the pair that already exists.+ const modes = executionModes+ || providerModeGroups(providers).find(group => group.some(mode => mode.id === provider.id))+ || [];+ if (modes.some(mode => mode.type === 'tui')) {+ return refuse(409, 'TUI_MODE_EXISTS', `${provider.name || provider.id} already has an interactive mode.`);+ }+const siblingId = modeSiblingId(provider.id, 'tui');if (providers.some(entry => entry?.id === siblingId)) {return refuse(409, 'TUI_MODE_EXISTS', `A provider with the ID “${siblingId}” already exists.`);@@ -55,9 +70,6 @@ export function tuiModeAddition(provider, providers = []) {return { ok: true, args: tuiSiblingArgs(harness) };}-/** Convenience for the list decoration — the verdict as the one boolean a card needs. */-export const canAddTuiMode = (provider, providers = []) => tuiModeAddition(provider, providers).ok;-/*** The argv a freshly minted TUI sibling starts with.*diff --git a/server/lib/providerModePairing.test.js b/server/lib/providerModePairing.test.jsindex 90f2da3dc0..12a0339e2c 100644--- a/server/lib/providerModePairing.test.js+++ b/server/lib/providerModePairing.test.js@@ -1,23 +1,23 @@import { describe, it, expect } from 'vitest';-import { canAddTuiMode, tuiModeAddition } from './providerModePairing.js';+import { tuiModeAddition } from './providerModePairing.js';-// One verdict feeds both the card's button and the endpoint's refusal, so what-// matters here is that each refusal keeps its OWN answer: an unsupported record-// and a taken sibling id are different failures to a caller, and a known-// harness and an unknown one differ in what argv the sibling starts with.+// The refusal matrix and its status codes are asserted through the endpoint+// that answers them (`routes/providers.tuiMode.test.js`), which runs this same+// function. What only a unit test can pin cheaply is where the sibling's ARGV+// comes from — a detail no HTTP response shape makes visible.const CLAUDE_CLI = { id: 'claude-code', name: 'Claude Code', type: 'cli', command: 'claude' };-describe('tuiModeAddition', () => {+describe('tuiModeAddition argv defaults', () => {it('starts a known harness at its recipe’s proven interactive argv', () => {// Not a guess and not empty: `--dangerously-skip-permissions` is what the// Claude row declares for its TUI mode, and a sibling minted without it// stops at a permission prompt the moment the Shell page launches it.expect(tuiModeAddition(CLAUDE_CLI, [CLAUDE_CLI])).toEqual({ ok: true, args: ['--dangerously-skip-permissions'] });- // A fresh array each call — a caller storing it must not be able to mutate- // the frozen recipe row every later mint reads.- const first = tuiModeAddition(CLAUDE_CLI, [CLAUDE_CLI]);- first.args.push('--tampered');+ });++ it('hands back a fresh array, not the frozen recipe row every later mint reads', () => {+ tuiModeAddition(CLAUDE_CLI, [CLAUDE_CLI]).args.push('--tampered');expect(tuiModeAddition(CLAUDE_CLI, [CLAUDE_CLI]).args).toEqual(['--dangerously-skip-permissions']);});@@ -25,30 +25,4 @@ describe('tuiModeAddition', () => {const custom = { id: 'my-agent', name: 'My Agent', type: 'cli', command: '/opt/bin/my-agent' };expect(tuiModeAddition(custom, [custom])).toEqual({ ok: true, args: [] });});-- it('refuses a KNOWN harness that declares no interactive mode', () => {- // OpenChamber is CLI-only in the registry. Minting a TUI record for it- // would store a mode the program does not have.- const openchamber = { id: 'openchamber', name: 'OpenChamber', type: 'cli', command: 'openchamber' };- expect(tuiModeAddition(openchamber, [openchamber])).toMatchObject({ ok: false, status: 400 });- });-- it('refuses a TUI record and an api record', () => {- // The CLI id is the stem, so minting it FROM the TUI half would rename the- // record that already exists instead of adding one beside it.- expect(canAddTuiMode({ id: 'claude-code-tui', name: 'Claude Code TUI', type: 'tui', command: 'claude' }, [])).toBe(false);- expect(canAddTuiMode({ id: 'openai', name: 'OpenAI', type: 'api', endpoint: 'https://api.example.com' }, [])).toBe(false);- expect(canAddTuiMode({ ...CLAUDE_CLI, command: ' ' }, [])).toBe(false);- });-- it('answers 409 — not a suffixed id — when the sibling id is already taken', () => {- // `mintRouteIds` suffixes a whole SET on collision because it owns both- // halves. Here the CLI id is fixed, so `claude-code-tui` existing means- // something else is standing in that slot; silently minting- // `claude-code-tui-2` would produce a record nothing ever groups.- const taken = { id: 'claude-code-tui', name: 'Something Else', type: 'tui', command: 'other' };- const verdict = tuiModeAddition(CLAUDE_CLI, [CLAUDE_CLI, taken]);- expect(verdict).toMatchObject({ ok: false, status: 409 });- expect(verdict.message).toContain('claude-code-tui');- });});diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 188e97b0f3..6e97476a76 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -1,5 +1,5 @@import { providerModeGroups } from '../lib/aiToolkit/internal/providerModes.js';-import { canAddTuiMode, tuiModeAddition } from '../lib/providerModePairing.js';+import { tuiModeAddition } from '../lib/providerModePairing.js';import { buildProviderGraphPreview, toManagementPreviewDto } from '../lib/providerGraphPreview.js';import {createBinding,@@ -273,10 +273,12 @@ export function createPortOSProviderRoutes(aiToolkit) {executionModes: modeGroups.get(provider.id),// Whether this record can be COMPLETED into a CLI/TUI pair. Derived// here rather than on the record alone because the verdict reads the- // whole list (the sibling id must be free), and decided server-side for- // the same reason `prerequisitesMet` is: the card offering the action- // and the endpoint performing it must not re-derive the rule apart.- canAddTuiMode: canAddTuiMode(provider, data.providers),+ // whole list — this record's mode GROUP (a `<stem>-cli` record is+ // already paired while its `<id>-tui` sits unclaimed) and the sibling+ // id — and decided server-side for the same reason `prerequisitesMet`+ // is: the card offering the action and the endpoint performing it must+ // not re-derive the rule apart.+ canAddTuiMode: tuiModeAddition(provider, data.providers, modeGroups.get(provider.id)).ok,prerequisitesMet: prerequisites[provider.id]?.met ?? true,missingPrerequisites: prerequisites[provider.id]?.missing ?? [],// NON-blocking notices — today only 'this install's own ~/.codex/config.tomldiff --git a/server/routes/providers.tuiMode.test.js b/server/routes/providers.tuiMode.test.jsindex 98911da7b9..193ce57b13 100644--- a/server/routes/providers.tuiMode.test.js+++ b/server/routes/providers.tuiMode.test.js@@ -47,9 +47,15 @@ describe('POST /api/providers/:id/modes/tui', () => {expect(createProviderTuiMode).toHaveBeenCalledWith('claude-code', { args: ['--dangerously-skip-permissions'] });});- it('answers 409 and writes NOTHING when the sibling id is already taken', async () => {+ it('answers 409 and writes NOTHING when the sibling id is taken by something unrelated', async () => {+ // Distinct from the already-paired refusal below: this record runs a+ // DIFFERENT command, so it does not group with `claude-code` — it is simply+ // squatting the id. `mintRouteIds` suffixes a whole set on collision+ // because it owns both halves; here the CLI id is fixed, so a+ // `claude-code-tui-2` would be a record nothing ever groups.+ const squatter = { ...CLAUDE_TUI, name: 'Something Else', command: 'other' };const createProviderTuiMode = vi.fn();- const app = appWith({ ...listing([CLAUDE_CLI, CLAUDE_TUI]), createProviderTuiMode });+ const app = appWith({ ...listing([CLAUDE_CLI, squatter]), createProviderTuiMode });const res = await request(app).post('/api/providers/claude-code/modes/tui');expect(res.status).toBe(409);@@ -72,6 +78,23 @@ describe('POST /api/providers/:id/modes/tui', () => {expect(createProviderTuiMode).not.toHaveBeenCalled();});+ it('refuses a harness that already HAS its interactive mode under a `-cli` id', async () => {+ // The shipped Grok pair is `grok-cli` / `grok-tui`, which `providerModeGroups`+ // groups — but `modeSiblingId('grok-cli')` is `grok-cli-tui`, an id nothing+ // holds. Judging eligibility on the free id alone flags half of an existing+ // pair and mints a pointless third record beside it.+ const grokCli = { id: 'grok-cli', name: 'Grok CLI', type: 'cli', command: 'grok', envVars: {} };+ const grokTui = { id: 'grok-tui', name: 'Grok TUI', type: 'tui', command: 'grok', envVars: {} };+ const createProviderTuiMode = vi.fn();+ const app = appWith({ ...listing([grokCli, grokTui]), createProviderTuiMode });++ expect((await request(app).post('/api/providers/grok-cli/modes/tui')).status).toBe(409);+ expect(createProviderTuiMode).not.toHaveBeenCalled();++ const list = await request(app).get('/api/providers');+ expect(list.body.providers.find(p => p.id === 'grok-cli').canAddTuiMode).toBe(false);+ });+it('GET / flags exactly the records this endpoint would accept', async () => {// The card's gate. An unpaired CLI qualifies; a record whose sibling already// exists does not (neither half of a pair, nor the pair's TUI record), and