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
address review (codex): launch TUI providers with their provider env
Adam Eivy51ec4f297d5f
diff --git a/client/src/components/providers/ProviderCard.jsx b/client/src/components/providers/ProviderCard.jsxindex a6f8b67121..ba4da9e6c4 100644--- a/client/src/components/providers/ProviderCard.jsx+++ b/client/src/components/providers/ProviderCard.jsx@@ -301,16 +301,18 @@ export default function ProviderCard({<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. */}+ they get a one-click hand-off to the Shell page. The link carries+ only the provider ID: the server resolves both the command line+ and the provider's `envVars` (its backend and auth) when it spawns+ the PTY, so an Ollama-backed or Bedrock provider reaches the+ backend it is configured for instead of the vendor cloud. Sending+ the command itself would leave that env behind — and those values+ are secret, so they can't ride a URL anyway. `tuiCommandLine` is+ the display half of the same resolution: it shows what will run,+ and an older server that omits it simply renders no button. */}{isTuiProvider(provider) && provider.tuiCommandLine && (<Link- to={`/shell?cmd=${encodeURIComponent(provider.tuiCommandLine)}`}+ to={`/shell?provider=${encodeURIComponent(provider.id)}`}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}`}>diff --git a/client/src/hooks/useShellSession.js b/client/src/hooks/useShellSession.jsindex bfc07a77f3..33c1ac8362 100644--- a/client/src/hooks/useShellSession.js+++ b/client/src/hooks/useShellSession.js@@ -149,8 +149,13 @@ export function useShellSession({ isFullscreen } = {}) {const cwd = searchParams.get('cwd');const cmd = searchParams.get('cmd');const session = searchParams.get('session');- if (cwd || cmd || session) {- initialOptsRef.current = { cwd, cmd, session };+ // `provider` is the AI Providers page's "Launch in Shell" hand-off. It sends+ // an ID rather than a command line because the server has to pair the+ // command with the provider's own env (its backend/auth live in secret+ // `envVars` the client never sees) — see socket.js's shell:start handler.+ const provider = searchParams.get('provider');+ if (cwd || cmd || session || provider) {+ initialOptsRef.current = { cwd, cmd, session, provider };setSearchParams({}, { replace: true });} else {initialOptsRef.current = {};@@ -444,6 +449,7 @@ export function useShellSession({ isFullscreen } = {}) {const startOpts = {};if (opts.cwd) startOpts.cwd = opts.cwd;if (opts.cmd) startOpts.initialCommand = opts.cmd;+ if (opts.provider) startOpts.providerId = opts.provider;initialOptsRef.current = {};socket.emit('shell:start', Object.keys(startOpts).length > 0 ? startOpts : undefined);}, [socket, setPendingAttach]);@@ -588,7 +594,7 @@ export function useShellSession({ isFullscreen } = {}) {if (opts.session && sessionList.some(s => s.sessionId === opts.session)) {attachToSession(opts.session);initialOptsRef.current = {};- } else if (opts.cwd || opts.cmd) {+ } else if (opts.cwd || opts.cmd || opts.provider) {startSession();} else if (urlSid && sessionList.some(s => s.sessionId === urlSid)) {// URL points at a live session — attach to that one (deep-link intentdiff --git a/client/src/hooks/useShellSession.test.jsx b/client/src/hooks/useShellSession.test.jsxindex c71f8b2991..07e90e3017 100644--- a/client/src/hooks/useShellSession.test.jsx+++ b/client/src/hooks/useShellSession.test.jsx@@ -334,7 +334,7 @@ describe('useShellSession', () => {// "open claude here" buttons. If this hook stopped consuming the param the// buttons would silently drop the user at a bare prompt with no error, so pin// that the query param reaches the server as `shell:start { initialCommand }`.- describe('?cmd= / ?cwd= deep link', () => {+ describe('?cmd= / ?cwd= / ?provider= deep links', () => {const at = (entry) => ({ children }) => (<MemoryRouter initialEntries={[entry]}>{children}</MemoryRouter>);@@ -352,5 +352,22 @@ describe('useShellSession', () => {expect(lastEmit('shell:start')).toEqual(['shell:start', { cwd: '/tmp/app', initialCommand: 'claude' }]);expect(lastEmit('shell:attach')).toBeUndefined();});+ // The AI Providers card links by provider ID so the SERVER can pair the+ // command with that provider's env (its backend/auth live in secret+ // envVars). If the hook dropped the param, the shell would open at a bare+ // prompt and the button would look broken with no error anywhere.+ it('forwards ?provider= to the server as shell:start { providerId }', () => {+ renderHook(() => useShellSession({}), { wrapper: at('/shell?provider=claude-ollama-tui') });+ fire('shell:sessions', []);+ expect(lastEmit('shell:start')).toEqual(['shell:start', { providerId: 'claude-ollama-tui' }]);+ });++ it('sends no command of its own for a provider launch — the server owns it', () => {+ renderHook(() => useShellSession({}), { wrapper: at('/shell?provider=codex') });+ fire('shell:sessions', [session('already-running')]);+ const [, opts] = lastEmit('shell:start');+ expect(opts.initialCommand).toBeUndefined();+ expect(lastEmit('shell:attach')).toBeUndefined();+ });});});diff --git a/client/src/pages/AIProviders.test.jsx b/client/src/pages/AIProviders.test.jsxindex 99eebb78a1..0cc4a286ee 100644--- a/client/src/pages/AIProviders.test.jsx+++ b/client/src/pages/AIProviders.test.jsx@@ -816,11 +816,12 @@ 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.+ // The card hands the user a one-click way to drive a TUI provider by hand.+ // The link carries only the provider ID — the server pairs the command with+ // the provider's env (its backend/auth) when it spawns the PTY, and those+ // values are secret, so the command line itself must NOT be what's sent.+ // `tuiCommandLine` is the display half: it decides whether the button renders+ // at all (an older server omits it) and shows what will run.const baseMocks = () => {vi.clearAllMocks();api.getApps.mockResolvedValue([]);@@ -848,10 +849,12 @@ describe('Launch in Shell button on TUI provider cards', () => {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')}`- );+ // By ID, never by command — sending the line would leave the provider's env+ // behind and launch it against the wrong backend.+ expect(link).toHaveAttribute('href', '/shell?provider=codex');+ expect(link.getAttribute('href')).not.toContain('cmd=');+ // The resolved line is still surfaced, so the user can see what will run.+ expect(link).toHaveAttribute('title', expect.stringContaining('--model gpt-5'));});it('renders no button for a CLI provider, or when the server sent no command line', async () => {diff --git a/server/lib/README.md b/server/lib/README.mdindex 2f29b05ca2..3bac7c5291 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -111,6 +111,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `providerCooldown.js` | Provider bench policy — `resolveProviderBench(analysis)` → `null` (don't bench) / a `usage-limit` marker / an `unavailable` marker with the per-category cooldown from `COOLDOWN_MS_BY_CATEGORY`. Declines to bench request/response-specific categories (`isRequestSpecificCategory` / `isSchemaTypeCategory`) so one bad model id or off-shape response can't take a healthy provider offline. Shared by `promptRunner.js` (prompt cascade) and `services/agentFinalization.js` (finished CoS agent run) so both bench a category for the same window. Pure. || `providerPrerequisites.js` | Can a provider run on this host AT ALL — `providerPrerequisites(provider, { runtime, orcaRouterKeySet })` → `{ met, missing: [{ code, label }] }` (CLI binary on PATH, API key stored for a public endpoint, the sibling key an OrcaRouter wrapper inherits), plus `providerRuntimeKey` (`null` for an API provider, for a command carrying an explicit path, and for a provider with its own `PATH` in `envVars` — the runtime table only answers "does the BARE binary resolve on PortOS's PATH?", which is not those providers' question), `isPrivateNetworkEndpoint` (mirror of the client copy: loopback/RFC1918/tailnet CGNAT + ULA/`.ts.net`/single-label hosts need no key) and `describeMissingPrerequisites`. `runtime: null` = NOT PROBED and never counts as missing. Feeds BOTH `GET /api/providers` and the fallback chain in `aiToolkit/providerStatus.js` (via `services/providerPrerequisites.js`), so a `NEEDS SETUP` card and the router read one computation (#4611). `ROUTING_BLOCKING_CODES`/`blocksRouting(missing)` narrow what ROUTING may act on to the missing binary — a credential finding stays presentation-only until #4612 teaches this module about env-var credentials, since a provider can authenticate through one. Pure. || `tuiPromptRunner.js` | One-shot TUI prompt runner (PTY-driven). |+| `tuiShellLaunch.js` | `buildTuiShellLaunch(provider)` → `{ commandLine, env }` for launching a TUI provider by hand in a Shell session (the AI Providers card's "Launch in Shell" button). Resolves the command via `tuiHandshake.js#buildTuiInvocation` (so the vendor posture flags and `--model`/`--effort` injection match a real TUI spawn) and the env via `cliChildEnv.js#composeProviderEnv`. **The env is why this is server-side and the deep link carries only a provider ID**: a TUI provider's backend lives in `envVars` (`ANTHROPIC_BASE_URL` for an Ollama-backed or Bedrock `claude`, `OPENCODE_CONFIG_CONTENT` for an OpenCode wrapper), so a shell handed only the command line would run the right binary against the vendor cloud instead of the local daemon the user configured — and those values are secret, so they can't ride a URL. Returns null for a non-TUI provider. Must be given a RAW provider, never a client-sanitized one (redacted `'***'` env reads truthy). || `tuiHandshake.js` | Shared TUI invocation + paste-handshake constants. Also owns `SUBMIT_KEY` — the single Enter byte every PTY writer sends, whether it's submitting a pasted TUI prompt or a command PortOS injected into a shell session. It is CR, never LF: a POSIX pty's ICRNL hides the difference, but cmd.exe under Windows ConPTY accepts only CR and leaves an LF-terminated line typed-but-unexecuted at the prompt. || `tuiUsageScrape.js` | `scrapeTuiUsage({ command, slashCommand, … })` + `USAGE_SANDBOX_DIR` — drive an agy/grok TUI in a sandbox PTY, send a slash command, return the ANSI-stripped screen (for quota panels `--print` can't reach). || `stageRunner.js` | Shared staged-LLM runner. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 204bb90c4d..88a6703ca1 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -161,6 +161,7 @@ export * as stageRunner from './stageRunner.js';export * from './stagePinPolicy.js';export * from './tuiHandshake.js';export * from './tuiPromptRunner.js';+export * from './tuiShellLaunch.js';export * from './tuiUsageScrape.js';// === File & I/O ===diff --git a/server/lib/tuiShellLaunch.js b/server/lib/tuiShellLaunch.jsnew file mode 100644index 0000000000..1195fbcb0a--- /dev/null+++ b/server/lib/tuiShellLaunch.js@@ -0,0 +1,40 @@+/**+ * Resolve everything a TUI provider needs to be launched by hand in a Shell+ * session: the exact command line to type, and the environment the PTY must+ * carry for that command to reach the backend the provider is configured for.+ *+ * The environment half is the reason this is a server-side resolution rather+ * than a `?cmd=<line>` query string. A TUI provider's backend and auth live in+ * `provider.envVars` — `ANTHROPIC_BASE_URL` for an Ollama-backed or Bedrock+ * `claude`, `OPENCODE_CONFIG_CONTENT` for an OpenCode wrapper — so a shell that+ * runs the command line WITHOUT that env silently talks to the vendor cloud+ * instead of the local daemon the user picked. Those values are also secret+ * (the client payload redacts them to `***`), so they can never ride a URL.+ *+ * The command half reuses `buildTuiInvocation`, the same builder the TUI prompt+ * runner uses, so the vendor posture flags and the `--model`/`--effort`+ * injection match what the provider really launches with.+ */++import { PROVIDER_TYPES } from './aiToolkit/constants.js';+import { buildTuiInvocation } from './tuiHandshake.js';+import { formatShellCommandLine } from './shellCd.js';+import { resolveInteractiveShell } from './interactiveShellResolver.js';+import { composeProviderEnv } from './cliChildEnv.js';++/**+ * @param {object|null|undefined} provider - a RAW provider record (unredacted+ * `envVars` — never a client-sanitized one, whose secrets are `'***'`)+ * @returns {{commandLine: string, env: object}|null} null when the provider is+ * not a TUI or resolves no launch command, so callers can treat "not+ * launchable" as one case rather than checking two conditions apiece.+ */+export function buildTuiShellLaunch(provider) {+ if (provider?.type !== PROVIDER_TYPES.TUI) return null;+ const { command, args } = buildTuiInvocation(provider, provider.defaultModel);+ if (!command) return null;+ return {+ commandLine: formatShellCommandLine(command, args, resolveInteractiveShell()),+ env: composeProviderEnv({ provider, model: provider.defaultModel }),+ };+}diff --git a/server/lib/tuiShellLaunch.test.js b/server/lib/tuiShellLaunch.test.jsnew file mode 100644index 0000000000..347a1dd122--- /dev/null+++ b/server/lib/tuiShellLaunch.test.js@@ -0,0 +1,45 @@+import { describe, it, expect } from 'vitest';+import { buildTuiShellLaunch } from './tuiShellLaunch.js';++// The env half is the whole reason this resolution is server-side: a TUI+// provider's backend lives in `envVars`, so a Shell session handed only the+// command line runs the right binary against the WRONG backend — silently+// billing the vendor cloud for a provider the user pointed at a local daemon.++const OLLAMA_CLAUDE_TUI = {+ id: 'claude-ollama-tui',+ name: 'Claude Ollama TUI',+ type: 'tui',+ command: 'claude',+ args: [],+ ollamaBacked: true,+ defaultModel: 'qwen3:32b',+ envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:11434', ANTHROPIC_AUTH_TOKEN: 'local' },+};++describe('buildTuiShellLaunch', () => {+ it('pairs the command line with the provider env that points it at its backend', () => {+ const launch = buildTuiShellLaunch(OLLAMA_CLAUDE_TUI);+ expect(launch.commandLine).toContain('claude');+ expect(launch.commandLine).toContain('qwen3:32b');+ expect(launch.env.ANTHROPIC_BASE_URL).toBe('http://127.0.0.1:11434');+ expect(launch.env.ANTHROPIC_AUTH_TOKEN).toBe('local');+ });++ it('returns null for a non-TUI provider, so callers have one not-launchable case', () => {+ expect(buildTuiShellLaunch({ ...OLLAMA_CLAUDE_TUI, type: 'cli' })).toBeNull();+ expect(buildTuiShellLaunch({ ...OLLAMA_CLAUDE_TUI, type: 'api' })).toBeNull();+ expect(buildTuiShellLaunch(null)).toBeNull();+ expect(buildTuiShellLaunch(undefined)).toBeNull();+ });++ it('falls back to the id-inferred command when the provider stores none', () => {+ const launch = buildTuiShellLaunch({ id: 'codex', type: 'tui', command: '', args: [] });+ expect(launch.commandLine.startsWith('codex')).toBe(true);+ });++ it('applies the vendor posture flag a naive command+args join would drop', () => {+ const launch = buildTuiShellLaunch({ id: 'codex', type: 'tui', command: 'codex', args: [] });+ expect(launch.commandLine).toContain('--dangerously-bypass-approvals-and-sandbox');+ });+});diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 637db20027..6999ce4033 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -19,10 +19,7 @@ import { getProviderReadinessMap, resetProviderReadinessCache } from '../serviceimport { 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';+import { buildTuiShellLaunch } from '../lib/tuiShellLaunch.js';/*** The CoS Agent Runner's exec allowlist, published read-only so the AI@@ -78,28 +75,21 @@ const sanitizeProvider = (provider) => {};/**- * 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.+ * Decorate a TUI provider with the command line the Shell page will run for it,+ * so the card can render a "Launch in Shell" button and show what it will type.+ *+ * DISPLAY ONLY — the launch itself goes through `shell:start { providerId }`,+ * which re-resolves this server-side and pairs it with the provider's env (see+ * `lib/tuiShellLaunch.js`). Publishing the line does not publish the env: those+ * values are secret and stay on the server.** 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()) };+ const launch = buildTuiShellLaunch(provider);+ return launch ? { ...provider, tuiCommandLine: launch.commandLine } : provider;};/**@@ -107,17 +97,21 @@ const withTuiLaunchCommand = (provider) => {* plus the derived `canRefreshModels` flag the AI Providers page reads to* decide whether to offer a "Refresh Models" button (#3620).*- * Order matters. `canRefreshModels` is computed on the RAW provider, before- * sanitization: the ollama row of the fetcher table keys partly on- * `envVars.ANTHROPIC_BASE_URL`, which `sanitizeProvider` redacts to `'***'`- * when the user marked it secret — deriving after would silently drop the- * Refresh button for a Claude-Ollama provider.+ * Order matters, and BOTH derivations run on the RAW provider, before+ * sanitization. `canRefreshModels`: the ollama row of the fetcher table keys+ * partly on `envVars.ANTHROPIC_BASE_URL`, which `sanitizeProvider` redacts to+ * `'***'` when the user marked it secret — deriving after would silently drop+ * the Refresh button for a Claude-Ollama provider. `tuiCommandLine`: the same+ * trap one layer down, since `buildTuiInvocation` consults `envVars` for the+ * Bedrock model mapping (`CLAUDE_CODE_USE_BEDROCK`) — a redacted `'***'` reads+ * truthy, so a card whose provider has that var marked secret and switched OFF+ * would advertise a Bedrock-mapped model the real launch never uses.** These PortOS routes SHADOW the toolkit's own (which decorate the same way);* 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) => withTuiLaunchCommand(sanitizeProvider(withRefreshCapability(provider)));+const presentProvider = (provider) => sanitizeProvider(withTuiLaunchCommand(withRefreshCapability(provider)));/*** Create PortOS-specific provider routesdiff --git a/server/routes/providers.tuiLaunch.test.js b/server/routes/providers.tuiLaunch.test.jsindex 27042532b6..33386622e2 100644--- a/server/routes/providers.tuiLaunch.test.js+++ b/server/routes/providers.tuiLaunch.test.js@@ -5,11 +5,13 @@ 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(' ')`.+// The AI Providers page's "Launch in Shell" button renders from+// `tuiCommandLine` and deep-links to `/shell?provider=<id>` (the launch itself+// re-resolves server-side so the provider's env rides along — see+// lib/tuiShellLaunch.js). This suite pins the DISPLAY half: the line is derived+// from `buildTuiInvocation` — the SAME builder the TUI spawn paths use — so it+// carries the vendor posture flags and the model injection rather than a naive+// `command + args.join(' ')`, and it is derived BEFORE redaction.const CODEX_TUI = {id: 'codex',@@ -72,4 +74,46 @@ describe('tuiCommandLine decoration', () => {expect(res.status).toBe(200);expect(res.body.tuiCommandLine.startsWith('codex ')).toBe(true);});++ it('derives the line BEFORE redaction, so a secret Bedrock marker is read at its real value', async () => {+ // `buildTuiInvocation` consults envVars for the Bedrock model mapping.+ // `sanitizeProvider` rewrites a secret var to '***', which reads TRUTHY —+ // so deriving after redaction would advertise a Bedrock-mapped model for a+ // provider that has the marker explicitly switched OFF, and the real launch+ // (which reads the raw provider) would run something else.+ const app = appWith({+ getProviderById: vi.fn().mockResolvedValue({+ ...CODEX_TUI,+ id: 'claude-tui',+ command: 'claude',+ defaultModel: 'claude-opus-4-8',+ envVars: { CLAUDE_CODE_USE_BEDROCK: '0' },+ secretEnvVars: ['CLAUDE_CODE_USE_BEDROCK'],+ }),+ });++ const res = await request(app).get('/api/providers/claude-tui');+ expect(res.status).toBe(200);+ expect(res.body.envVars.CLAUDE_CODE_USE_BEDROCK).toBe('***');+ expect(res.body.tuiCommandLine).toContain('claude-opus-4-8');+ expect(res.body.tuiCommandLine).not.toContain('anthropic.claude-opus-4-8');+ });++ it('never publishes the provider env alongside the command line', async () => {+ // The env is the half that must NOT cross the wire — those values are+ // secret, which is why the deep link carries an ID instead of a command.+ const app = appWith({+ getProviderById: vi.fn().mockResolvedValue({+ ...CODEX_TUI,+ envVars: { OPENAI_API_KEY: 'sk-not-a-real-key' },+ secretEnvVars: ['OPENAI_API_KEY'],+ }),+ });++ const res = await request(app).get('/api/providers/codex');+ expect(res.status).toBe(200);+ expect(res.body.tuiLaunchEnv).toBeUndefined();+ expect(res.body.tuiCommandLine).not.toContain('sk-not-a-real-key');+ expect(res.body.envVars.OPENAI_API_KEY).toBe('***');+ });});diff --git a/server/services/socket.js b/server/services/socket.jsindex a3ce087088..a294bd6c1e 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -29,6 +29,8 @@ import { audioGenEvents } from './audioGen/events.js';import { aiStatusEvents } from './aiStatusEvents.js';import { wireProactiveTriggers } from './voice/proactiveTriggers.js';import * as shellService from './shell.js';+import { getProviderById } from './providers.js';+import { buildTuiShellLaunch } from '../lib/tuiShellLaunch.js';import {validateSocketData,detectStartSchema,@@ -634,18 +636,50 @@ export function initSocket(io) {}});- // Shell session handlers- socket.on('shell:start', (options) => {- const cwd = options?.cwd || undefined;- const initialCommand = options?.initialCommand || undefined;- const sessionId = shellService.createShellSession(socket, { cwd });- if (sessionId) {- socket.emit('shell:started', { sessionId });- if (initialCommand) {- setTimeout(() => shellService.submitToSession(sessionId, initialCommand), 200);+ // Shell session handlers.+ //+ // `providerId` is the AI Providers page's "Launch in Shell" path. The client+ // sends only the ID and the SERVER resolves both the command line and the+ // provider's env — a TUI provider's backend lives in `envVars`+ // (ANTHROPIC_BASE_URL for an Ollama-backed or Bedrock claude,+ // OPENCODE_CONFIG_CONTENT for an OpenCode wrapper), so a session started+ // from a bare `initialCommand` would run the right binary against the WRONG+ // backend — silently billing the vendor cloud for a provider the user+ // pointed at a local daemon. Those values are secret besides, so they must+ // never round-trip through the client. Resolving server-side also means the+ // client can't choose the command: the ID only selects among the user's own+ // stored providers.+ socket.on('shell:start', async (options) => {+ try {+ const cwd = options?.cwd || undefined;+ const providerId = typeof options?.providerId === 'string' ? options.providerId : null;+ let initialCommand = options?.initialCommand || undefined;+ let env;+ if (providerId) {+ const provider = await getProviderById(providerId).catch(() => null);+ const launch = buildTuiShellLaunch(provider);+ if (!launch) {+ socket.emit('shell:error', { error: `Provider '${providerId}' is not a launchable TUI provider` });+ return;+ }+ // Server-resolved wins outright — never fall back to a client-supplied+ // command for a provider launch.+ initialCommand = launch.commandLine;+ env = launch.env;}- } else {- socket.emit('shell:error', { error: 'Failed to create shell session' });+ const sessionId = shellService.createShellSession(socket, { cwd, env });+ if (sessionId) {+ socket.emit('shell:started', { sessionId });+ if (initialCommand) {+ setTimeout(() => shellService.submitToSession(sessionId, initialCommand), 200);+ }+ } else {+ socket.emit('shell:error', { error: 'Failed to create shell session' });+ }+ } catch (err) {+ const message = err?.message ?? String(err);+ console.error(`❌ Socket handler error [shell:start]: ${message}`);+ socket.emit('shell:error', { error: message });}});diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex 2feb4b68df..f6eeb84807 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -33,6 +33,7 @@ vi.mock('./loops.js', () => ({ loopEvents: { on: vi.fn() } }));vi.mock('./imageGenEvents.js', () => ({ imageGenEvents: { on: vi.fn() } }));vi.mock('./shell.js', () => ({createShellSession: vi.fn(),+ submitToSession: vi.fn(),attachSession: vi.fn(),subscribeSessionList: vi.fn(),listAllSessions: vi.fn(() => []),@@ -44,6 +45,9 @@ vi.mock('./shell.js', () => ({unsubscribeSessionList: vi.fn(),detachSocketSessions: vi.fn(() => 0)}));+// The shell:start provider-launch path resolves a stored provider. Mock the+// service (not lib/tuiShellLaunch.js) so the REAL command+env resolution runs.+vi.mock('./providers.js', () => ({ getProviderById: vi.fn() }));vi.mock('../lib/socketValidation.js', () => ({validateSocketData: vi.fn((schema, data) => data),detectStartSchema: {},@@ -72,6 +76,7 @@ import { mediaJobEvents } from './mediaJobQueue/index.js';import { audioGenEvents } from './audioGen/events.js';import { detachSocketSessions } from './shell.js';import * as shellService from './shell.js';+import { getProviderById } from './providers.js';import { updateApp as runAppUpdate } from './appUpdater.js';import { analyzeApp, standardizeRefusalFor } from './pm2Standardizer.js';@@ -785,4 +790,88 @@ describe('socket.js — initSocket', () => {await flush();});});+ // ===========================================================================+ // shell:start — the AI Providers "Launch in Shell" path+ //+ // The client sends only a provider ID. The server resolves the command AND+ // the provider's env, because a TUI provider's backend lives in `envVars`:+ // a session started from a bare command line runs the right binary against+ // the vendor cloud instead of the local daemon the user configured. Those+ // values are secret besides, so they can never round-trip through the client.+ // ===========================================================================+ describe('shell:start provider launch', () => {+ const OLLAMA_TUI = {+ id: 'claude-ollama-tui',+ name: 'Claude Ollama TUI',+ type: 'tui',+ command: 'claude',+ args: [],+ ollamaBacked: true,+ defaultModel: 'qwen3:32b',+ envVars: { ANTHROPIC_BASE_URL: 'http://127.0.0.1:11434' },+ };++ const start = async (payload) => {+ const socket = makeSocket('shell-launch');+ createdSockets.push(socket);+ io.connect(socket);+ await socket.handlers['shell:start'](payload);+ return socket;+ };++ beforeEach(() => {+ vi.mocked(shellService.createShellSession).mockClear().mockReturnValue('sess-1');+ vi.mocked(shellService.submitToSession).mockClear();+ vi.mocked(getProviderById).mockReset();+ });++ it('spawns the PTY with the provider env and types the resolved command', async () => {+ vi.mocked(getProviderById).mockResolvedValue(OLLAMA_TUI);++ const socket = await start({ providerId: 'claude-ollama-tui' });++ expect(socket.emitted).toContainEqual(['shell:started', { sessionId: 'sess-1' }]);+ const [, opts] = vi.mocked(shellService.createShellSession).mock.calls.at(-1);+ expect(opts.env.ANTHROPIC_BASE_URL).toBe('http://127.0.0.1:11434');+ });++ it('ignores a client-supplied command for a provider launch — the server owns it', async () => {+ vi.mocked(getProviderById).mockResolvedValue(OLLAMA_TUI);++ await start({ providerId: 'claude-ollama-tui', initialCommand: 'rm -rf /' });++ // The submit is deferred behind a timer; drain it before asserting.+ await vi.waitFor(() => expect(shellService.submitToSession).toHaveBeenCalled());+ const [, typed] = vi.mocked(shellService.submitToSession).mock.calls.at(-1);+ expect(typed).not.toContain('rm -rf');+ expect(typed).toContain('claude');+ });++ it('refuses a provider that is not a launchable TUI rather than opening a bare shell', async () => {+ vi.mocked(getProviderById).mockResolvedValue({ ...OLLAMA_TUI, type: 'api' });++ const socket = await start({ providerId: 'claude-ollama-tui' });++ expect(socket.emitted.some(([ev]) => ev === 'shell:error')).toBe(true);+ expect(shellService.createShellSession).not.toHaveBeenCalled();+ });++ it('refuses an unknown provider id', async () => {+ vi.mocked(getProviderById).mockResolvedValue(null);++ const socket = await start({ providerId: 'nope' });++ expect(socket.emitted.some(([ev]) => ev === 'shell:error')).toBe(true);+ expect(shellService.createShellSession).not.toHaveBeenCalled();+ });++ it('still supports a plain cwd/command start with no provider', async () => {+ await start({ cwd: '/tmp/app', initialCommand: 'claude' });++ expect(getProviderById).not.toHaveBeenCalled();+ const [, opts] = vi.mocked(shellService.createShellSession).mock.calls.at(-1);+ expect(opts.cwd).toBe('/tmp/app');+ expect(opts.env).toBeUndefined();+ });+ });});