Skip to content

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

feat(providers): launch a TUI provider straight into a Shell session

Adam Eivyf9267fb3bc68
diff --git a/client/src/components/providers/ProviderCard.jsx b/client/src/components/providers/ProviderCard.jsx
index 0d9f6c8576..a6f8b67121 100644
--- a/client/src/components/providers/ProviderCard.jsx
+++ b/client/src/components/providers/ProviderCard.jsx
@@ -11,6 +11,8 @@
* and which section the page filed the card under can never disagree.
*/
+import { Link } from 'react-router';
+import { Terminal } from 'lucide-react';
import {
PROVIDER_CARD_STATE,
effectiveModelContextWindow,
@@ -298,6 +300,25 @@ export default function ProviderCard({
</div>
<div className="flex flex-wrap items-center gap-2">
+ {/* TUI providers are the only ones a human can drive interactively, so
+ they get a one-click hand-off to the Shell page. `?cmd=` starts a
+ fresh PTY session and types the line for you. The line is built
+ SERVER-side as `tuiCommandLine` — the argv a TUI provider really
+ launches with is vendor-specific and the quoting depends on the
+ host's shell, so a client-side `command + args.join(' ')` would be
+ a wrong second copy. An older server omits the field, and the
+ button then simply doesn't render. */}
+ {isTuiProvider(provider) && provider.tuiCommandLine && (
+ <Link
+ to={`/shell?cmd=${encodeURIComponent(provider.tuiCommandLine)}`}
+ className="flex items-center gap-1.5 px-3 py-1.5 text-sm bg-port-accent/20 text-port-accent hover:bg-port-accent/30 rounded transition-colors"
+ title={`Launch in Shell: ${provider.tuiCommandLine}`}
+ >
+ <Terminal size={14} />
+ Launch in Shell
+ </Link>
+ )}
+
<button
onClick={() => onTest(provider.id)}
disabled={testResult?.testing}
diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsx
index c57f3b8416..99eebb78a1 100644
--- a/client/src/pages/AIProviders.test.jsx
+++ b/client/src/pages/AIProviders.test.jsx
@@ -814,3 +814,59 @@ describe('readiness table coverage', () => {
}
});
});
+
+describe('Launch in Shell button on TUI provider cards', () => {
+ // The card hands the user a one-click way to drive a TUI provider by hand:
+ // `/shell?cmd=<tuiCommandLine>` starts a fresh PTY and types the exact
+ // invocation the CoS TUI spawner would use. The line is built server-side
+ // (vendor posture flags + model/effort injection + shell quoting), so the
+ // card renders nothing when an older server omits it.
+ const baseMocks = () => {
+ vi.clearAllMocks();
+ api.getApps.mockResolvedValue([]);
+ api.getProviderStatuses.mockResolvedValue({ providers: {} });
+ api.getProviderRuntimes.mockResolvedValue({ runtimes: {} });
+ api.getProviderReadiness.mockResolvedValue({ readiness: {} });
+ localModels.value = { ctxById: {}, installed: { ollama: null, lmstudio: null } };
+ };
+
+ it('links to the Shell page with the server-built command line', async () => {
+ baseMocks();
+ api.getProviders.mockResolvedValue({
+ providers: [{
+ id: 'codex',
+ name: 'Codex TUI',
+ type: 'tui',
+ command: 'codex',
+ args: [],
+ enabled: true,
+ tuiCommandLine: 'codex --dangerously-bypass-approvals-and-sandbox --model gpt-5',
+ }],
+ activeProvider: null,
+ });
+
+ renderPage();
+
+ const link = await screen.findByRole('link', { name: /Launch in Shell/ });
+ expect(link).toHaveAttribute(
+ 'href',
+ `/shell?cmd=${encodeURIComponent('codex --dangerously-bypass-approvals-and-sandbox --model gpt-5')}`
+ );
+ });
+
+ it('renders no button for a CLI provider, or when the server sent no command line', async () => {
+ baseMocks();
+ api.getProviders.mockResolvedValue({
+ providers: [
+ { id: 'claude-code', name: 'Claude Code', type: 'cli', command: 'claude', args: [], enabled: true },
+ { id: 'legacy-tui', name: 'Legacy TUI', type: 'tui', command: 'claude', args: [], enabled: true },
+ ],
+ activeProvider: null,
+ });
+
+ renderPage();
+
+ expect(await screen.findByText('Legacy TUI')).toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: /Launch in Shell/ })).not.toBeInTheDocument();
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 6c47ed877c..2f29b05ca2 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -374,7 +374,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |
| `openapiSpec.js` | `buildOpenApiSpec(settings, { baseUrl, version })` — builds an OpenAPI 3.1 document for the currently-exposed public APIs from `apiRegistry`, reusing route Zod schemas via `z.toJSONSchema`. Exposed+`requireAuth` operations get a `security` requirement; passwordless ones don't. Served by `routes/apiDocs.js`. |
| `prDisposition.js` | `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOwnsPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. |
-| `shellCd.js` | `buildCdCommand(path, shell)` + `detectShellFlavor(shell, platform?)` + `quoteForShell(value, flavor, position?)` — build `cd` and arbitrary command-token lines for the shell a PTY session is ACTUALLY running (`cmd.exe` → Windows-escaped double quotes, PowerShell → doubled single quotes with `&` for a quoted command token, everything else → POSIX `shellQuote`). The Shell page's "cd to app" picker used to hard-code the POSIX form, which on Windows both mis-quoted the path and silently refused to cross drives (a bare `cd` does not switch drive). Flavor comes from the shell binary name, not the platform, so git-bash on Windows still gets POSIX quoting. Renders the LINE only; the Enter byte that submits it is `SUBMIT_KEY` in `tuiHandshake.js`. |
+| `shellCd.js` | `buildCdCommand(path, shell)` + `formatShellCommandLine(command, args, shell)` + `detectShellFlavor(shell, platform?)` + `quoteForShell(value, flavor, position?)` — build `cd` and arbitrary command-token lines for the shell a PTY session is ACTUALLY running (`cmd.exe` → Windows-escaped double quotes, PowerShell → doubled single quotes with `&` for a quoted command token, everything else → POSIX `shellQuote`). The Shell page's "cd to app" picker used to hard-code the POSIX form, which on Windows both mis-quoted the path and silently refused to cross drives (a bare `cd` does not switch drive). Flavor comes from the shell binary name, not the platform, so git-bash on Windows still gets POSIX quoting. `formatShellCommandLine` joins a command + argv into one quoted line and is shared by `agentTuiSpawning.js#buildTuiSpawnConfig` and the AI Providers page's "Launch in Shell" deep link, so a hand-launched TUI provider is quoted exactly the way the CoS runner would quote it. Renders the LINE only; the Enter byte that submits it is `SUBMIT_KEY` in `tuiHandshake.js`. |
| `shellExit.js` | `buildRunThenExitCommand(commandLine, shell)` — "run this CLI, then close the shell with its status", in the dialect the session speaks. An agent TUI shell exists only to host one CLI and must die with it. The POSIX `cmd; exit $?` was applied everywhere and is actively wrong off-POSIX: in PowerShell `$?` is a BOOLEAN, so `exit $?` reports success as 1 and failure as 0 (inverted) — use `$LASTEXITCODE`, pre-seeded to 1 so a command that never ran still exits non-zero; in cmd.exe `;` is an argument separator, so the CLI is handed `;`/`exit`/`$?` as arguments — use `& exit`. Verified against node-pty on Windows 11 for pwsh 7, PowerShell 5.1 and cmd.exe. |
| `shellQuote.js` | `shellQuote(value)` — POSIX single-quote escaping for values interpolated into shell command strings (display command lines, copy-paste blocks in agent prompts). Bare-safe tokens pass through; everything else is single-quoted. Canonical escaper — don't hand-roll. |
| `sidecarProcess.js` | `runSidecarProcess({bin,args,env,signal,onStage,onProcess})` + `parseSidecarResult(stdout)` — the shared Python-sidecar STAGE:/RESULT: wire-protocol runner (spawn, tail-capped stdout/stderr, per-STAGE-line callback, abort/SIGTERM → `canceled`, non-zero exit → stderr-tail reason). Used by `pipeline/musicGen.js` (all music backends) and `audioMidiTranscription.js` (MuScriptor). |
diff --git a/server/lib/shellCd.js b/server/lib/shellCd.js
index 0c6728019a..c0324cc401 100644
--- a/server/lib/shellCd.js
+++ b/server/lib/shellCd.js
@@ -97,3 +97,22 @@ export function buildCdCommand(dirPath, shell) {
default: return `cd ${quoteForShell(path, 'posix')}`;
}
}
+
+/**
+ * Render a command plus its argv as ONE shell command line, quoted for the
+ * dialect that shell speaks. Shared by the CoS TUI spawner
+ * (`agentTuiSpawning.js#buildTuiSpawnConfig`) and the AI Providers page's
+ * "Launch in Shell" deep link, so a provider launched by hand is quoted exactly
+ * the way the agent runner would quote it.
+ *
+ * @param {string} command - the binary (command position — PowerShell needs `&`)
+ * @param {string[]} [args] - argv tokens
+ * @param {string} [shell] - the session's shell binary; see detectShellFlavor
+ * @returns {string} a single command line, no trailing newline
+ */
+export function formatShellCommandLine(command, args = [], shell) {
+ const flavor = detectShellFlavor(shell);
+ return [command, ...args]
+ .map((value, index) => quoteForShell(value, flavor, index === 0 ? 'command' : 'argument'))
+ .join(' ');
+}
diff --git a/server/lib/shellCd.test.js b/server/lib/shellCd.test.js
index 7bf014a560..ce72a2f42b 100644
--- a/server/lib/shellCd.test.js
+++ b/server/lib/shellCd.test.js
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
-import { buildCdCommand, detectShellFlavor, quoteForShell } from './shellCd.js';
+import { buildCdCommand, detectShellFlavor, formatShellCommandLine, quoteForShell } from './shellCd.js';
describe('detectShellFlavor', () => {
it('reads the flavor off the shell binary, ignoring path and case', () => {
@@ -90,3 +90,22 @@ describe('quoteForShell', () => {
.toBe(`"C:${slash}work${slash}${slash}"`);
});
});
+
+describe('formatShellCommandLine', () => {
+ it('quotes the first token in command position and the rest as arguments', () => {
+ expect(formatShellCommandLine('codex', ['--model', 'gpt-5'], '/bin/zsh'))
+ .toBe('codex --model gpt-5');
+ expect(formatShellCommandLine("C:\\Program Files\\claude.cmd", ['--effort', 'max'], 'powershell.exe'))
+ .toBe("& 'C:\\Program Files\\claude.cmd' '--effort' 'max'");
+ });
+
+ it('quotes an argument containing spaces so the shell keeps it as one token', () => {
+ expect(formatShellCommandLine('agy', ['--model', 'gemini 3 pro'], '/bin/zsh'))
+ .toBe("agy --model 'gemini 3 pro'");
+ });
+
+ it('renders a bare command with no arguments', () => {
+ expect(formatShellCommandLine('claude', [], '/bin/zsh')).toBe('claude');
+ expect(formatShellCommandLine('claude', undefined, '/bin/zsh')).toBe('claude');
+ });
+});
diff --git a/server/routes/providers.js b/server/routes/providers.js
index aa675abf96..637db20027 100644
--- a/server/routes/providers.js
+++ b/server/routes/providers.js
@@ -19,6 +19,10 @@ import { getProviderReadinessMap, resetProviderReadinessCache } from '../service
import { getProviderPrerequisiteMap } from '../services/providerPrerequisites.js';
import { runLocalRuntimeSetup } from '../services/localRuntimeSetup.js';
import { localRuntimeForProvider } from '../lib/localProviderRuntime.js';
+import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
+import { buildTuiInvocation } from '../lib/tuiHandshake.js';
+import { formatShellCommandLine } from '../lib/shellCd.js';
+import { resolveInteractiveShell } from '../lib/interactiveShellResolver.js';
/**
* The CoS Agent Runner's exec allowlist, published read-only so the AI
@@ -73,6 +77,31 @@ const sanitizeProvider = (provider) => {
return sanitized;
};
+/**
+ * Decorate a TUI provider with the exact command line the Shell page should
+ * type to launch it by hand (`?cmd=` deep link from the card's "Launch in
+ * Shell" button). Derived here rather than joined client-side because the argv
+ * a TUI provider really launches with is vendor-specific — posture flags
+ * (`applyCommandDefaults`) plus `--model`/`--effort` injection — and the
+ * quoting depends on the shell the PTY will actually run. Reusing
+ * `buildTuiInvocation` (the same builder `tuiPromptRunner.js` uses) keeps this
+ * from drifting into a second, wronger copy of that argv logic. It deliberately
+ * stops short of the agent-only decorations `buildTuiSpawnConfig` layers on —
+ * the lean-Claude `--bare` posture and `--append-system-prompt-file` exist to
+ * strip a HEADLESS run down to an agent contract, and a human opening this
+ * session wants their normal environment.
+ *
+ * Non-TUI providers get no field at all: the button is TUI-only, and an absent
+ * key (rather than an empty string) keeps "not a TUI" distinct from "a TUI
+ * whose command line came back blank".
+ */
+const withTuiLaunchCommand = (provider) => {
+ if (provider?.type !== PROVIDER_TYPES.TUI) return provider;
+ const { command, args } = buildTuiInvocation(provider, provider.defaultModel);
+ if (!command) return provider;
+ return { ...provider, tuiCommandLine: formatShellCommandLine(command, args, resolveInteractiveShell()) };
+};
+
/**
* The shape a provider takes on its way OUT to the client: secrets stripped,
* plus the derived `canRefreshModels` flag the AI Providers page reads to
@@ -88,7 +117,7 @@ const sanitizeProvider = (provider) => {
* the toolkit keeps its copy so it stays correct standalone. Both decorate on
* the way out only — the field is never persisted.
*/
-const presentProvider = (provider) => sanitizeProvider(withRefreshCapability(provider));
+const presentProvider = (provider) => withTuiLaunchCommand(sanitizeProvider(withRefreshCapability(provider)));
/**
* Create PortOS-specific provider routes
diff --git a/server/routes/providers.tuiLaunch.test.js b/server/routes/providers.tuiLaunch.test.js
new file mode 100644
index 0000000000..27042532b6
--- /dev/null
+++ b/server/routes/providers.tuiLaunch.test.js
@@ -0,0 +1,75 @@
+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';
+
+// The AI Providers page's "Launch in Shell" button deep-links to
+// `/shell?cmd=<tuiCommandLine>`. The line is derived server-side from
+// `buildTuiInvocation` — the SAME builder the CoS TUI spawner uses — so a
+// hand-launched provider gets its vendor posture flags and its default
+// model/effort injection rather than a naive `command + args.join(' ')`.
+
+const CODEX_TUI = {
+ id: 'codex',
+ name: 'Codex TUI',
+ type: 'tui',
+ command: 'codex',
+ args: [],
+ defaultModel: 'gpt-5',
+ envVars: {},
+};
+const CLAUDE_CLI = { id: 'claude-code', name: 'Claude Code', type: 'cli', command: 'claude', 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;
+}
+
+describe('tuiCommandLine decoration', () => {
+ it('GET / gives TUI providers a launch command line and everyone else none', async () => {
+ const app = appWith({
+ getAllProviders: vi.fn().mockResolvedValue({
+ activeProvider: 'codex',
+ providers: [CODEX_TUI, CLAUDE_CLI, API_PROVIDER],
+ }),
+ });
+
+ const res = await request(app).get('/api/providers');
+ expect(res.status).toBe(200);
+ const byId = Object.fromEntries(res.body.providers.map((p) => [p.id, p]));
+ expect(byId.codex.tuiCommandLine).toContain('codex');
+ expect(byId.codex.tuiCommandLine).toContain('gpt-5');
+ // The vendor posture flag comes from applyCommandDefaults, not from
+ // provider.args — a naive join would have dropped it.
+ expect(byId.codex.tuiCommandLine).toContain('--dangerously-bypass-approvals-and-sandbox');
+ expect(byId['claude-code'].tuiCommandLine).toBeUndefined();
+ expect(byId.openai.tuiCommandLine).toBeUndefined();
+ });
+
+ it('quotes an argument with spaces so the Shell page types one token', async () => {
+ const app = appWith({
+ getProviderById: vi.fn().mockResolvedValue({ ...CODEX_TUI, args: ['--cd', '/tmp/my apps'] }),
+ });
+
+ const res = await request(app).get('/api/providers/codex');
+ expect(res.status).toBe(200);
+ expect(res.body.tuiCommandLine).toContain("'/tmp/my apps'");
+ });
+
+ it('falls back to the id-inferred command when the provider stores none', async () => {
+ const app = appWith({
+ getProviderById: vi.fn().mockResolvedValue({ ...CODEX_TUI, command: '' }),
+ });
+
+ const res = await request(app).get('/api/providers/codex');
+ expect(res.status).toBe(200);
+ expect(res.body.tuiCommandLine.startsWith('codex ')).toBe(true);
+ });
+});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index edfdbbfe3f..ebedf3d55e 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -29,7 +29,7 @@ import * as git from './git.js';
import { resolveReviewLoopOptions } from './codeReview.js';
import { spawnTuiSessionViaRunner } from './cosRunnerClient.js';
import { resolveInteractiveShell } from '../lib/interactiveShellResolver.js';
-import { detectShellFlavor, quoteForShell } from '../lib/shellCd.js';
+import { formatShellCommandLine } from '../lib/shellCd.js';
import { isClaudeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';
import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
@@ -222,10 +222,7 @@ export function buildTuiSpawnConfig(provider, model, {
if (systemPromptFile && isClaudeCommand(command)) {
args = [...args, '--append-system-prompt-file', systemPromptFile];
}
- const flavor = detectShellFlavor(shell);
- const commandLine = [command, ...args]
- .map((value, index) => quoteForShell(value, flavor, index === 0 ? 'command' : 'argument'))
- .join(' ');
+ const commandLine = formatShellCommandLine(command, args, shell);
return {
command,