Skip to content

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

add a TUI sibling to an existing CLI provider from its card (#7501)

[._.]/ Adam Eivy6f507ab1b9cf
diff --git a/client/src/components/providers/ProviderCard.jsx b/client/src/components/providers/ProviderCard.jsx
index 056feda1ae..a35eeaa1a9 100644
--- a/client/src/components/providers/ProviderCard.jsx
+++ b/client/src/components/providers/ProviderCard.jsx
@@ -108,6 +108,8 @@ export default function ProviderCard({
onSetActive,
onEdit,
onDelete,
+ onAddTuiMode,
+ addingTuiMode = false,
onRecover,
onInstallRuntime,
onAutoSetupRuntime,
@@ -348,6 +350,29 @@ export default function ProviderCard({
Edit
</button>}
+ {/* A lone CLI record is half a harness: the same program usually also
+ runs interactively, and configuring that half used to mean adding
+ the provider a second time from /ai/new and retyping the command,
+ endpoint, credentials and env — which only pairs the two records
+ if every one of those matches exactly. The server mints the
+ sibling from the record already on disk instead.
+
+ `canAddTuiMode` is the SERVER's verdict (the provider list
+ decorates it), not a re-derivation here: it also answers whether
+ this harness has an interactive mode at all and whether the
+ sibling id is free, neither of which the card can see. */}
+ {!unified && provider.canAddTuiMode && (
+ <button
+ onClick={() => onAddTuiMode(provider)}
+ disabled={addingTuiMode}
+ title={`Add the interactive (TUI) mode of ${displayName}, using its existing command and connection`}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded transition-colors disabled:opacity-50"
+ >
+ <Terminal size={14} />
+ {addingTuiMode ? 'Adding…' : 'Add interactive mode'}
+ </button>
+ )}
+
{!confirmingDelete && (
<button
onClick={() => setConfirmingDelete(true)}
diff --git a/client/src/components/providers/ProviderCard.test.jsx b/client/src/components/providers/ProviderCard.test.jsx
index 8e16d0d819..247c456250 100644
--- a/client/src/components/providers/ProviderCard.test.jsx
+++ b/client/src/components/providers/ProviderCard.test.jsx
@@ -320,3 +320,51 @@ describe('ProviderCard delete confirmation', () => {
expect(screen.getByText(/Both its CLI and TUI modes are removed/)).toBeTruthy();
});
});
+
+describe('ProviderCard "Add interactive mode"', () => {
+ const cliRecord = (overrides = {}) => wrapper({
+ id: 'opencode-cli', name: 'OpenCode CLI', type: 'cli', canAddTuiMode: true, ...overrides,
+ });
+
+ it('offers the action on an unpaired CLI record and hands the whole provider to the page', () => {
+ // The record already carries the command, endpoint, credentials and env the
+ // sibling needs — the click is the whole interaction, not a pre-filled form.
+ const onAddTuiMode = vi.fn();
+ const provider = cliRecord();
+ renderCard(provider, null, { onAddTuiMode });
+ fireEvent.click(screen.getByRole('button', { name: /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.
+ const cli = cliRecord();
+ const tui = wrapper({ id: 'opencode-tui', name: 'OpenCode TUI' });
+ renderCard(
+ { ...cli, executionModes: [{ id: 'opencode-cli' }, { id: 'opencode-tui' }] },
+ 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();
+
+ renderCard(wrapper({ id: 'openai', name: 'OpenAI', type: 'api' }));
+ expectNoAction();
+ });
+
+ it('shows the in-flight state rather than letting a second click mint twice', () => {
+ const onAddTuiMode = vi.fn();
+ renderCard(cliRecord(), null, { onAddTuiMode, addingTuiMode: true });
+ const button = screen.getByRole('button', { name: /Adding/ });
+ expect(button.disabled).toBe(true);
+ fireEvent.click(button);
+ expect(onAddTuiMode).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/providers/ProviderForm.jsx b/client/src/components/providers/ProviderForm.jsx
index f6e0ed26bc..317a188f0e 100644
--- a/client/src/components/providers/ProviderForm.jsx
+++ b/client/src/components/providers/ProviderForm.jsx
@@ -109,7 +109,10 @@ export default function ProviderForm({ provider, daemonReadiness = null, onClose
// back out of every payload.
//
// Editing never offers it: pairing describes two records being created
- // together, which a save against one existing record cannot mean.
+ // together, which a save against one existing record cannot mean. An existing
+ // CLI record gains its TUI sibling from the card's "Add interactive mode"
+ // instead (`POST /api/providers/:id/modes/tui`), which mints it from what is
+ // already stored rather than from a re-submitted form.
const canPairModes = !provider && formData.type === 'cli';
const [alsoTui, setAlsoTui] = useState(false);
const [tuiArgs, setTuiArgs] = useState('');
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index 5ca8a12b65..0b2eba4475 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -85,6 +85,7 @@ export default function AIProviders() {
const [runnerAllowedCommands, setRunnerAllowedCommands] = useState(null);
const [statuses, setStatuses] = useState({}); // runtime availability by providerId (separate from the `enabled` toggle)
const [recovering, setRecovering] = useState({});
+ const [addingTuiMode, setAddingTuiMode] = useState({}); // in-flight "Add interactive mode" by providerId
const [activeProviderId, setActiveProviderId] = useState(null);
const [loading, setLoading] = useState(true);
const [loadError, setLoadError] = useState(false);
@@ -367,6 +368,22 @@ export default function AIProviders() {
loadData();
};
+ // Complete a lone CLI provider into a CLI / TUI pair. A full `loadData()`
+ // rather than an in-place patch: the two records become ONE card, and the
+ // grouping (`executionModes`) is computed server-side — there is no correct
+ // way to splice a new mode into the list from here.
+ const handleAddTuiMode = async (provider) => {
+ setAddingTuiMode(prev => ({ ...prev, [provider.id]: true }));
+ const created = await api.addProviderTuiMode(provider.id, { silent: true }).catch(() => null);
+ setAddingTuiMode(prev => ({ ...prev, [provider.id]: false }));
+ if (!created) {
+ toast.error(`Could not add an interactive mode for ${provider.name}`);
+ return;
+ }
+ toast.success(`${created.name} added — edit it to change its arguments`);
+ loadData();
+ };
+
const handleToggleEnabled = async (provider) => {
await api.updateProvider(provider.id, {
enabled: !provider.enabled,
@@ -1068,6 +1085,8 @@ export default function AIProviders() {
onSetActive={handleSetActive}
onEdit={openForm}
onDelete={handleDelete}
+ onAddTuiMode={handleAddTuiMode}
+ addingTuiMode={Boolean(addingTuiMode[provider.id])}
onRecover={handleRecover}
onInstallRuntime={setInstallingRuntime}
onAutoSetupRuntime={setSettingUpRuntime}
diff --git a/client/src/services/apiProviders.js b/client/src/services/apiProviders.js
index 607b0be13e..2a3cbe8c90 100644
--- a/client/src/services/apiProviders.js
+++ b/client/src/services/apiProviders.js
@@ -19,6 +19,14 @@ export const updateProvider = (id, data, options = {}) => request(`/providers/${
...options,
});
export const deleteProvider = (id) => request(`/providers/${id}`, { method: 'DELETE' });
+// Mint the TUI half of an existing CLI provider's harness. No body: the sibling
+// is built from the stored record plus the harness recipe's interactive argv,
+// so the connection details never get retyped (and never get retyped WRONG,
+// which would leave two unrelated routes instead of one CLI / TUI card).
+export const addProviderTuiMode = (id, options = {}) => request(`/providers/${id}/modes/tui`, {
+ method: 'POST',
+ ...options,
+});
export const getSampleProviders = () => request('/providers/samples');
export const testProvider = (id) => request(`/providers/${id}/test`, { method: 'POST' });
export const refreshProviderModels = (id, options) => request(`/providers/${id}/refresh-models`, { method: 'POST', ...options });
diff --git a/docs/API.md b/docs/API.md
index d7a19df58a..03d286abc0 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -121,6 +121,7 @@ legacy list for local Apps/Dashboard views.
| POST | `/providers` | Add new provider. A body carrying `modes` (`{ cli: {…}, tui: {…} }`) instead creates BOTH execution modes of one harness in one write — a program that runs headlessly and interactively is one program on one backend, but a record stores one `type`, so configuring both otherwise means adding the same command twice and hoping the two records satisfy the pairing rule. The pair is minted as `<id>` / `<id>-tui` with every grouped field (command, endpoint, credentials, env) shared, and answers `{ providers: [cli, tui] }`; a single-mode create still answers the bare provider object. A mode declares only `args` / `headlessArgs` / `tuiPromptDelayMs` for itself, and `cli: {}` is normal — the body's own fields already describe the CLI record, so the key is there to declare the pair. A per-mode MAP rather than the mode-name ARRAY `POST /providers/bindings` takes, because a binding mints argv from the harness's shipped recipe while a provider added here has none and the user types each mode's arguments. Create-only: `PUT /providers/:id` drops the key. |
| PUT | `/providers/:id` | Update provider |
| DELETE | `/providers/:id` | Delete provider |
+| POST | `/providers/:id/modes/tui` | Give an EXISTING CLI provider the TUI half of its harness, minted from the record already on disk — the other end of the dual-mode create above, for an install that already has a lone `claude` or `opencode` CLI record. A new endpoint rather than a flag on `PUT /providers/:id`, because `modes` is create-only: a PATCH against one record cannot mean "make me two". No request body: the command, endpoint, credentials and env come from `:id` (retyping them is both friction and a fresh chance for a grouped field to differ and leave two unrelated routes), and the argv defaults from the harness recipe’s proven interactive line, or stays empty for a binary PortOS has no row for. Answers the created record; `GET /providers` flags eligible records with `canAddTuiMode` so a card only ever offers what this accepts. Refuses a non-CLI record, a record storing no command, and a known harness declaring no TUI mode (400); a taken `<id>-tui` answers 409 and writes nothing — the CLI id is already fixed, so something else is standing there. |
| POST | `/providers/:id/test` | Test provider connectivity |
| PUT | `/providers/active` | Set active provider |
| GET | `/providers/runtimes` | Per-runtime install status (`claude`, `codex`, `opencode`, `kilo`, `openchamber`, `grok`, `kimi`, `agy`, `cursor-agent`): is the binary runnable here, and can PortOS install it? Booleans and labels only — never resolved filesystem paths. 60s TTL cache. Ollama / LM Studio are absent on purpose — Models → LLMs owns their install. |
diff --git a/server/lib/README.md b/server/lib/README.md
index f4590345a0..d10c0a62f4 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -233,6 +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. |
| `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.js
index 9e0a8e71b3..df4cac036a 100644
--- a/server/lib/aiToolkit/internal/providerModes.js
+++ b/server/lib/aiToolkit/internal/providerModes.js
@@ -16,6 +16,26 @@ const MODE_KEY_DEFAULTS = { endpoint: '', apiKey: '', envVars: {}, credentialBoo
*/
export 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.
+ *
+ * `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".
+ *
+ * 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 function providerModeGroups(providers) {
const byId = new Map(providers.map(provider => [provider.id, provider]));
const paired = new Set();
@@ -129,9 +149,19 @@ export const modeSiblingName = (name, mode) => (mode === 'tui' ? `${name} TUI` :
* 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` and the mode's own
+ * 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.
+ *
* @param {{modes?:Record<string,object>, id?:string, name:string}} providerData
* @returns {object[]|null} one create payload per mode, CLI first
*/
@@ -141,9 +171,10 @@ export function expandModePair(providerData) {
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) => ({
- ...shared,
+ ...(mode === 'tui' ? tuiShared : shared),
...modes[mode],
id: modeSiblingId(stem, mode),
name: modeSiblingName(shared.name, mode),
diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.js
index 2a61db9d66..de94a3ed2a 100644
--- a/server/lib/aiToolkit/providers.js
+++ b/server/lib/aiToolkit/providers.js
@@ -824,6 +824,39 @@ export function createProviderService(config = {}) {
return created;
},
+ /**
+ * Complete an existing CLI record's harness by minting its TUI sibling.
+ *
+ * The sibling is built from the STORED record, never from a re-submitted
+ * form: retyping the command, endpoint, credentials and env is exactly the
+ * friction a dual-mode create removed for a provider being added, and a
+ * second hand-entry is also a second chance for a grouped field to differ
+ * 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.
+ *
+ * @param {string} id - the CLI record to derive from
+ * @param {object} [tuiOverrides] - mode-specific fields, typically `args`
+ * @returns {Promise<object|null>} the created TUI record, or `null` when `id` names no record
+ */
+ async createProviderTuiMode(id, tuiOverrides = {}) {
+ const data = await loadProviders();
+ const stored = data.providers[id];
+ 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);
+ storeProviderRecords(data, [created]);
+ await saveProviders(data);
+ return created;
+ },
+
async updateProvider(id, updates) {
const data = await loadProviders();
diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.js
index 5cebf906f8..9afb0c8fe0 100644
--- a/server/lib/aiToolkit/providers.test.js
+++ b/server/lib/aiToolkit/providers.test.js
@@ -71,6 +71,62 @@ describe('Provider Service', () => {
expect((await providerService.getProviderById('example-agent')).enabled).toBe(true);
});
+ it('completes an existing CLI record into a pair the toolkit groups, without re-entering its connection', async () => {
+ // The whole point of minting from the STORED record: an install that
+ // already has a lone CLI provider gets the sibling for free, and the two
+ // records satisfy the pairing rule by construction rather than because the
+ // user retyped the endpoint, key and env identically.
+ await writeFile(join(TEST_DATA_DIR, 'providers.json'), JSON.stringify({ activeProvider: 'example', providers: {
+ example: {
+ 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,
+ },
+ } }));
+
+ const tui = await providerService.createProviderTuiMode('example', { args: ['--interactive'] });
+ expect(tui.id).toBe('example-tui');
+ expect(tui.name).toBe('Example Agent TUI');
+ expect(tui.args).toEqual(['--interactive']);
+ // Every grouped field came across unchanged — that is what makes it groupable.
+ expect(tui).toMatchObject({
+ command: 'example',
+ endpoint: 'https://backend.example.com',
+ apiKey: 'sk-test',
+ 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".
+ 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.
+ await providerService.updateProvider('example-tui', { enabled: false });
+ expect((await providerService.getProviderById('example')).enabled).toBe(false);
+ });
+
+ it('refuses to derive a TUI mode from a record that is not a CLI, or from an id that does not exist', async () => {
+ await providerService.createProvider({ name: 'Example TUI', id: 'example-tui', type: 'tui', command: 'example' });
+ // The CLI id is the stem, so minting it from the TUI half is a rename.
+ await expect(providerService.createProviderTuiMode('example-tui')).rejects.toThrow(/Only a CLI provider/);
+ expect(await providerService.createProviderTuiMode('missing')).toBeNull();
+ });
+
+ it('refuses rather than suffixing when the sibling id is already taken', async () => {
+ // `mintRouteIds` suffixes a whole set on collision because it owns both
+ // halves; here the CLI id is fixed, so a taken sibling id means something
+ // else is standing there — and a `example-tui-2` would group with nothing.
+ await providerService.createProvider({ name: 'Example Agent', id: 'example', type: 'cli', command: 'example' });
+ await providerService.createProvider({ name: 'Unrelated', id: 'example-tui', type: 'tui', command: 'other' });
+ await expect(providerService.createProviderTuiMode('example')).rejects.toThrow(/already exists/);
+ expect((await providerService.getProviderById('example-tui')).command).toBe('other');
+ });
+
it('lands no half-made pair when the second record collides with an existing id', async () => {
await providerService.createProvider({ name: 'Example Agent TUI', id: 'example-agent-tui', type: 'tui', command: 'example' });
await expect(providerService.createProviderModes({
diff --git a/server/lib/aiToolkit/validation.test.js b/server/lib/aiToolkit/validation.test.js
index 954d6cbf34..1930a0ea93 100644
--- a/server/lib/aiToolkit/validation.test.js
+++ b/server/lib/aiToolkit/validation.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
import { sanitizeScreenshotRefs, providerCreateSchema, providerSchema, providerActiveSchema, PROVIDER_MODE_OVERRIDE_KEYS, validate } from './validation.js';
-import { MODE_GROUPED_KEYS } from './internal/providerModes.js';
+import { CLI_ONLY_KEYS, MODE_GROUPED_KEYS } from './internal/providerModes.js';
describe('sanitizeScreenshotRefs — POST /api/runs screenshot hardening (#1870)', () => {
it('keeps an in-dir image basename unchanged', () => {
@@ -271,6 +271,11 @@ describe('providerCreateSchema — declaring both execution modes of one harness
// two unrelated routes instead of one harness, with nothing to report it.
expect(PROVIDER_MODE_OVERRIDE_KEYS.filter(key => MODE_GROUPED_KEYS.includes(key))).toEqual([]);
expect(PROVIDER_MODE_OVERRIDE_KEYS).not.toContain('command');
+ // Same invariant from the other side: `expandModePair` DROPS these from the
+ // TUI half, so listing a grouped key here would split the pair just as
+ // surely as overriding one would.
+ expect(CLI_ONLY_KEYS.filter(key => MODE_GROUPED_KEYS.includes(key))).toEqual([]);
+ expect(CLI_ONLY_KEYS).not.toContain('command');
});
it('holds each mode to the same field rules as a single-mode create', () => {
diff --git a/server/lib/index.js b/server/lib/index.js
index 4abf27ad4f..89f7a1e248 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -483,6 +483,7 @@ export * from './providerConnections.js';
export * from './providerGraphPreview.js';
export * from './providerGraphRecords.js';
export * from './providerModelAliases.js';
+export * from './providerModePairing.js';
export * from './providerRouteRecipes.js';
export * from './providerRouteSettings.js';
export * from './personaTraitBlend.js';
diff --git a/server/lib/providerModePairing.js b/server/lib/providerModePairing.js
new file mode 100644
index 0000000000..eb29026eff
--- /dev/null
+++ b/server/lib/providerModePairing.js
@@ -0,0 +1,70 @@
+/**
+ * May this provider record gain the OTHER execution mode of its harness?
+ *
+ * One rule, read by two callers that must never disagree: the provider list
+ * decorates each record with `canAddTuiMode` so the card offers the action, and
+ * `POST /api/providers/:id/modes/tui` refuses on the same verdict. Gating the
+ * button on one expression and the endpoint on another is how a card comes to
+ * advertise an action the server rejects.
+ *
+ * Lives here rather than in `aiToolkit/` because the verdict consults the
+ * harness registry, and that directory stays self-contained (see its AGENTS.md).
+ */
+
+import { harnessForProvider, harnessRecipe, harnessSupportsMode } from './providerHarnesses.js';
+import { modeSiblingId } 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
+ * 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.
+ *
+ * @param {object|null|undefined} provider - the record to derive from
+ * @param {object[]} providers - every stored provider, for the id-collision check
+ * @returns {{ok:true, args:string[]}|{ok:false, status:number, code:string, message:string}}
+ */
+export function tuiModeAddition(provider, providers = []) {
+ const refuse = (status, code, message) => ({ ok: false, status, code, message });
+
+ if (provider?.type !== 'cli') {
+ // The CLI id is the stem, so minting it FROM a TUI record would be a
+ // rename of the record that already exists, not an addition beside it.
+ return refuse(400, 'TUI_MODE_UNSUPPORTED', 'Only a CLI provider can gain an interactive mode.');
+ }
+ if (typeof provider.command !== 'string' || provider.command.trim() === '') {
+ return refuse(400, 'TUI_MODE_UNSUPPORTED', 'This provider stores no command to launch interactively.');
+ }
+
+ // An UNKNOWN harness (a custom binary PortOS has no row for) is allowed
+ // through with no default argv — the user knows their own program. A KNOWN
+ // harness that declares no TUI mode is a different answer: the registry says
+ // this program has no interactive mode, so minting one would store a lie.
+ const harness = harnessForProvider(provider);
+ if (harness && !harnessSupportsMode(harness.id, 'tui')) {
+ return refuse(400, 'TUI_MODE_UNSUPPORTED', `${harness.label} has no 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.`);
+ }
+
+ 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.
+ *
+ * Taken from the harness recipe, which already carries the proven interactive
+ * line for the programs PortOS ships a row for. An unknown harness gets an
+ * empty list rather than a guess — the user edits it like any other provider.
+ */
+function tuiSiblingArgs(harness) {
+ return [...(harnessRecipe(harness?.id)?.modes?.tui?.args || [])];
+}
diff --git a/server/lib/providerModePairing.test.js b/server/lib/providerModePairing.test.js
new file mode 100644
index 0000000000..90f2da3dc0
--- /dev/null
+++ b/server/lib/providerModePairing.test.js
@@ -0,0 +1,54 @@
+import { describe, it, expect } from 'vitest';
+import { canAddTuiMode, 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.
+
+const CLAUDE_CLI = { id: 'claude-code', name: 'Claude Code', type: 'cli', command: 'claude' };
+
+describe('tuiModeAddition', () => {
+ 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');
+ expect(tuiModeAddition(CLAUDE_CLI, [CLAUDE_CLI]).args).toEqual(['--dangerously-skip-permissions']);
+ });
+
+ it('lets an UNKNOWN harness through with empty argv rather than a guess', () => {
+ 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.js
index 44a66abbaf..188e97b0f3 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -1,4 +1,5 @@
import { providerModeGroups } from '../lib/aiToolkit/internal/providerModes.js';
+import { canAddTuiMode, tuiModeAddition } from '../lib/providerModePairing.js';
import { buildProviderGraphPreview, toManagementPreviewDto } from '../lib/providerGraphPreview.js';
import {
createBinding,
@@ -270,6 +271,12 @@ export function createPortOSProviderRoutes(aiToolkit) {
providers: data.providers.map((provider) => ({
...presentProvider(provider, capabilities),
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),
prerequisitesMet: prerequisites[provider.id]?.met ?? true,
missingPrerequisites: prerequisites[provider.id]?.missing ?? [],
// NON-blocking notices — today only 'this install's own ~/.codex/config.toml
@@ -930,6 +937,35 @@ export function createPortOSProviderRoutes(aiToolkit) {
res.json(presentProvider(provider, await detectSystemCapabilities()));
}));
+ /**
+ * POST /:id/modes/tui — give an existing CLI record the TUI half of its
+ * harness, minted from the record already on disk.
+ *
+ * A NEW endpoint rather than a flag on `PUT /:id`, because `modes` is
+ * deliberately create-only: a PATCH against one record cannot mean "make me
+ * two". `:id` names the record the sibling is DERIVED from, and the sibling
+ * is built from what is stored — the user does not retype the command,
+ * endpoint, credentials and env that `providerModeGroups` then has to find
+ * identical on both halves.
+ *
+ * There is no request body: every field either comes from the stored record
+ * or from the harness recipe. The new record is editable like any other
+ * afterwards.
+ */
+ router.post('/:id/modes/tui', asyncHandler(async (req, res) => {
+ const { providers } = await providerService.getAllProviders();
+ const stored = providers.find(provider => provider.id === req.params.id);
+ if (!stored) throw new ServerError('Provider not found', { status: 404 });
+
+ // The same verdict the list decorated this record with, so a card can only
+ // ever offer an action this endpoint accepts.
+ const verdict = tuiModeAddition(stored, providers);
+ if (!verdict.ok) throw new ServerError(verdict.message, { status: verdict.status, code: verdict.code });
+
+ const created = await providerService.createProviderTuiMode(stored.id, { args: verdict.args });
+ res.status(201).json(presentProvider(created, await detectSystemCapabilities()));
+ }));
+
// POST / — intercept to (a) validate the body against providerCreateSchema so
// invalid fields like `timeout: "abc"` or non-object `envVars` don't
// persist and later break runner behavior, and (b) sanitize the created
diff --git a/server/routes/providers.tuiMode.test.js b/server/routes/providers.tuiMode.test.js
new file mode 100644
index 0000000000..98911da7b9
--- /dev/null
+++ b/server/routes/providers.tuiMode.test.js
@@ -0,0 +1,88 @@
+import { describe, it, expect, vi } from 'vitest';
+import express from 'express';
+import { Router } from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { createPortOSProviderRoutes } from './providers.js';
+
+// An install that already has a lone `claude` or `opencode` CLI record used to
+// have to add the provider a SECOND time from /ai/new — retyping the command,
+// endpoint, credentials and env, and hoping the two records happened to satisfy
+// the pairing rule. `POST /:id/modes/tui` mints the sibling from what is stored.
+//
+// The card offers that action from `canAddTuiMode`, which this same route module
+// decorates the LIST with, so both halves are pinned here: a button that appears
+// where the endpoint refuses (or hides where it would accept) is the failure.
+
+const CLAUDE_CLI = { id: 'claude-code', name: 'Claude Code', type: 'cli', command: 'claude', envVars: {} };
+const CLAUDE_TUI = { id: 'claude-code-tui', name: 'Claude Code TUI', type: 'tui', command: 'claude', envVars: {} };
+const OPENCHAMBER_CLI = { id: 'openchamber', name: 'OpenChamber', type: 'cli', command: 'openchamber', envVars: {} };
+const API_PROVIDER = { id: 'openai', name: 'OpenAI', type: 'api', endpoint: 'https://api.example.com', envVars: {} };
+
+function appWith(providerService) {
+ const toolkit = { services: { providers: providerService }, routes: { providers: Router() } };
+ const app = express();
+ app.use(express.json());
+ app.use('/api/providers', createPortOSProviderRoutes(toolkit));
+ app.use(errorMiddleware);
+ return app;
+}
+
+const listing = (providers) => ({
+ getAllProviders: vi.fn().mockResolvedValue({ activeProvider: providers[0]?.id ?? null, providers }),
+});
+
+describe('POST /api/providers/:id/modes/tui', () => {
+ it('mints the sibling from the stored record, defaulting its argv from the harness recipe', async () => {
+ const createProviderTuiMode = vi.fn().mockResolvedValue({
+ ...CLAUDE_TUI, args: ['--dangerously-skip-permissions'],
+ });
+ const app = appWith({ ...listing([CLAUDE_CLI, API_PROVIDER]), createProviderTuiMode });
+
+ const res = await request(app).post('/api/providers/claude-code/modes/tui');
+ expect(res.status).toBe(201);
+ expect(res.body.id).toBe('claude-code-tui');
+ // No request body is read: the endpoint names the record to derive from and
+ // supplies the recipe's proven interactive argv itself.
+ expect(createProviderTuiMode).toHaveBeenCalledWith('claude-code', { args: ['--dangerously-skip-permissions'] });
+ });
+
+ it('answers 409 and writes NOTHING when the sibling id is already taken', async () => {
+ const createProviderTuiMode = vi.fn();
+ const app = appWith({ ...listing([CLAUDE_CLI, CLAUDE_TUI]), createProviderTuiMode });
+
+ const res = await request(app).post('/api/providers/claude-code/modes/tui');
+ expect(res.status).toBe(409);
+ expect(createProviderTuiMode).not.toHaveBeenCalled();
+ });
+
+ it('refuses a TUI record, an api record, a CLI-only harness, and an unknown id', async () => {
+ const createProviderTuiMode = vi.fn();
+ const app = appWith({
+ ...listing([CLAUDE_TUI, API_PROVIDER, OPENCHAMBER_CLI]),
+ createProviderTuiMode,
+ });
+
+ // The CLI id is the stem, so minting it FROM the TUI half is a rename.
+ expect((await request(app).post('/api/providers/claude-code-tui/modes/tui')).status).toBe(400);
+ expect((await request(app).post('/api/providers/openai/modes/tui')).status).toBe(400);
+ // OpenChamber's registry row declares no TUI mode — a minted one is a lie.
+ expect((await request(app).post('/api/providers/openchamber/modes/tui')).status).toBe(400);
+ expect((await request(app).post('/api/providers/nope/modes/tui')).status).toBe(404);
+ expect(createProviderTuiMode).not.toHaveBeenCalled();
+ });
+
+ 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
+ // neither does an api record or a CLI-only harness.
+ const app = appWith(listing([CLAUDE_CLI, CLAUDE_TUI, OPENCHAMBER_CLI, API_PROVIDER, {
+ id: 'my-agent', name: 'My Agent', type: 'cli', command: '/opt/bin/my-agent', envVars: {},
+ }]));
+
+ const res = await request(app).get('/api/providers');
+ expect(res.status).toBe(200);
+ const flagged = res.body.providers.filter(p => p.canAddTuiMode).map(p => p.id);
+ expect(flagged).toEqual(['my-agent']);
+ });
+});