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

Render the shell-exit wrapper where the shell is known, and fix the dialect fallback

[._.]/ Adam Eivy61fd3eb8a51d
diff --git a/.env.example b/.env.example
index 03ab6cf2da..a37da531b7 100644
--- a/.env.example
+++ b/.env.example
@@ -115,11 +115,9 @@ PGPASSWORD=portos
# PORTOS_BASH=/bin/bash
# Shell binary for interactive PTY sessions (the Shell page, agent TUI shells).
-# Auto-detected if unset: on Windows PowerShell 7 (pwsh.exe) if installed, else
-# Windows PowerShell, else cmd.exe; on macOS/Linux $SHELL, else zsh.
-# cmd.exe is last on purpose — it can't reach another drive by anything you'd
-# type (`cd I:` prints that drive's folder and stays put, `cd 'I:\path'` is a
-# syntax error), which strands an install whose repos live off C:.
+# Auto-detected if unset: on Windows PowerShell 7, else Windows PowerShell, else
+# cmd.exe (last, because it can't reach another drive by anything you'd type —
+# see server/lib/interactiveShellResolver.js); on macOS/Linux $SHELL, else zsh.
# Windows: PORTOS_SHELL=C:\Program Files\Git\bin\bash.exe
# PORTOS_SHELL=/bin/fish
diff --git a/server/lib/README.md b/server/lib/README.md
index 1b55e3b44f..3c69f58f61 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -197,7 +197,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `agentGuard/` | `agentGuardEnv(baseEnv?)` + `AGENT_GUARD_BIN` — env patch that prepends a guarded `pm2` shim (`bin/pm2`) to a spawned AI agent's PATH so a confused `--dangerously-skip-permissions` agent can't `pm2 kill` / `pm2 delete all` the shared daemon (which would down every app, incl. PortOS). Blocked-subcommand list mirrors `validatePm2Command` in `commandSecurity.js`. POSIX-only (no-op on Windows). |
| `bashResolver.js` | `resolveBashBinary()` — resolves the POSIX `bash` for running bundled `*.sh` scripts (e.g. `scripts/db.sh`). On Windows a bare `bash` often resolves (via PM2's PATH) to WSL, which mounts drives at `/mnt/h` and can't see a `H:/...` drive path (exit 127); this prefers Git Bash (PORTOS_BASH override → standard install dirs → derived from `git` on PATH → bare `bash`). No-op (`bash`) on non-Windows. `toBashPath(p)` — the companion path rule: bash reads backslashes as escapes, so a Windows path must reach it with forward slashes. |
-| `interactiveShellResolver.js` | `resolveInteractiveShell()` — picks the shell binary a PTY session runs (Shell page, agent TUI shells). On Windows the old `COMSPEC` default meant `cmd.exe`, where no command a user would type reaches another drive: `cd I:` silently PRINTS that drive's cwd and stays put, a bare `I:\` is "not recognized as a command", and `cd 'I:\path'` is a syntax error (no single-quote quoting) — so a Windows install with its repos on a second drive was stuck on `C:`. Resolves PORTOS_SHELL → newest `pwsh.exe` (PowerShell 7+, version dirs enumerated so a future 8 needs no code change) → `powershell.exe` (5.1, ships with Windows) → `cmd.exe` last. PowerShell crosses drives with every form. Unchanged on POSIX (`SHELL` → zsh). `resolveInteractiveShellWith({platform, env, exists})` is the un-memoized injectable form for tests. |
+| `interactiveShellResolver.js` | `resolveInteractiveShell()` — picks the shell binary a PTY session runs (Shell page, agent TUI shells). On Windows the old `COMSPEC` default meant `cmd.exe`, where no command a user would type reaches another drive: `cd I:` silently PRINTS that drive's cwd and stays put, a bare `I:\` is "not recognized as a command", and `cd 'I:\path'` is a syntax error (no single-quote quoting) — so a Windows install with its repos on a second drive was stuck on `C:`. Resolves PORTOS_SHELL → newest `pwsh.exe` under `%ProgramFiles%\PowerShell\<major>` (majors enumerated and sorted numerically, so a future 8 needs no code change) → any `pwsh.exe` on PATH via `findCommandOnPath` (scoop/choco/Store shim) → `powershell.exe` 5.1 (ships with Windows) → `cmd.exe` last. PowerShell crosses drives with every form. Unchanged on POSIX (`SHELL` → zsh). `resolveInteractiveShellWith({platform, env, exists, readdir, findOnPath})` is the un-memoized injectable form for tests. |
| `openFolder.js` | `openFolderInSystemExplorer(localPath)` — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child `error` handler prevents spawn failures from crashing the process. |
| `childProcess.js` | Drop-in `child_process` replacement that defaults every spawn to `windowsHide: true` — `spawn` / `spawnSync` / `fork` / `exec` / `execSync` / `execFile` / `execFileSync`, plus a `ChildProcess` re-export. **Server runtime code must import from here, never from `child_process` directly** (enforced by `childProcess.guards.test.js`): a console-less PM2 fork spawning a console child without `CREATE_NO_WINDOW` makes Windows hand the new console to Windows Terminal, which flashes a focus-stealing window. `exec`/`execFile` carry `util.promisify.custom` so `promisify(execFile)` still resolves to `{ stdout, stderr }`. An explicit `windowsHide: false` is respected. Background: `docs/WINDOWS_CONSOLE.md`. |
| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. `killProcessTree(child, signal, { processGroup })` takes the POSIX group down too when the child was spawned `detached` (Windows always tree-kills). Used by `appBuilder.js`, `appUpdater.js`, the CoS agent spawners, and `setupScriptRunner.js`. |
diff --git a/server/lib/interactiveShellResolver.js b/server/lib/interactiveShellResolver.js
index f441ba64e3..7f5b533928 100644
--- a/server/lib/interactiveShellResolver.js
+++ b/server/lib/interactiveShellResolver.js
@@ -27,19 +27,20 @@
*
* Resolution order (Windows):
* 1. PORTOS_SHELL override — explicit escape hatch, always wins.
- * 2. PowerShell 7+ (`pwsh.exe`), highest major version installed.
- * 3. Windows PowerShell 5.1 (`powershell.exe`) — ships with Windows, so this
+ * 2. PowerShell 7+ (`pwsh.exe`) at its versioned install dirs, newest major.
+ * 3. Any other `pwsh.exe` on PATH — scoop, chocolatey, a custom prefix, or
+ * the winget/Store launcher shim under `WindowsApps`.
+ * 4. Windows PowerShell 5.1 (`powershell.exe`) — ships with Windows, so this
* is the realistic floor; it crosses drives too, it just loads the user's
* profile (slower start) and is stuck on the older engine.
- * 4. `COMSPEC` / `cmd.exe` — only if no PowerShell exists at all.
+ * 5. `COMSPEC` / `cmd.exe` — only if no PowerShell exists at all.
*
* On POSIX the choice was never broken: PORTOS_SHELL, else `SHELL`, else zsh.
- *
- * Self-contained: no imports out to other PortOS modules.
*/
import { existsSync, readdirSync } from 'fs';
import { join } from 'path';
+import { findCommandOnPath } from './processEnv.js';
/**
* `%ProgramFiles%\PowerShell\<major>\pwsh.exe` for every installed major
@@ -47,7 +48,7 @@ import { join } from 'path';
* PowerShell 8 is picked up without a code change, and so a box with both 7 and
* 8 gets the newer one.
*/
-function pwshVersionDirs(env, readdir) {
+function pwshCandidatePaths(env, readdir) {
const roots = [env.ProgramFiles, env['ProgramFiles(x86)']].filter(Boolean);
const found = [];
for (const root of roots) {
@@ -69,17 +70,26 @@ function pwshVersionDirs(env, readdir) {
return found;
}
-function windowsShellCandidates(env, readdir) {
- const candidates = pwshVersionDirs(env, readdir);
- // winget/Store installs put a `pwsh.exe` launcher here; it is on PATH but the
- // versioned directory above may not exist (or may be a different install).
- if (env.LOCALAPPDATA) {
- candidates.push(join(env.LOCALAPPDATA, 'Microsoft', 'WindowsApps', 'pwsh.exe'));
- }
+// Probed in order and short-circuited, so the PATH scan only runs on a box with
+// no versioned PowerShell 7 install.
+function resolveWindowsShell(env, exists, readdir, findOnPath) {
+ const versioned = pwshCandidatePaths(env, readdir).find(exists);
+ if (versioned) return versioned;
+
+ // Covers every non-standard pwsh install — scoop, chocolatey, a custom
+ // prefix, and the winget/Store launcher shim under WindowsApps — rather than
+ // hard-coding one more directory per packaging tool.
+ const onPath = findOnPath('pwsh.exe', { env });
+ if (onPath) return onPath;
+
// Windows PowerShell 5.1 — present on every supported Windows.
- const systemRoot = env.SystemRoot || env.SYSTEMROOT || 'C:\\Windows';
- candidates.push(join(systemRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'));
- return candidates;
+ const ps5 = join(
+ env.SystemRoot || 'C:\\Windows',
+ 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe',
+ );
+ if (exists(ps5)) return ps5;
+
+ return env.COMSPEC || 'cmd.exe';
}
/**
@@ -91,6 +101,7 @@ function windowsShellCandidates(env, readdir) {
* @param {NodeJS.ProcessEnv} [deps.env] - environment to read
* @param {(path: string) => boolean} [deps.exists] - filesystem probe
* @param {(dir: string) => string[]} [deps.readdir] - directory listing; may throw
+ * @param {(name: string, opts: object) => string|null} [deps.findOnPath] - PATH lookup
* @returns {string} shell binary path (or bare name, on POSIX)
*/
export function resolveInteractiveShellWith({
@@ -98,19 +109,22 @@ export function resolveInteractiveShellWith({
env = process.env,
exists = existsSync,
readdir = readdirSync,
+ findOnPath = findCommandOnPath,
} = {}) {
- // The override wins on every platform, but only if it actually resolves —
- // a stale path in `.env` must not strand every session on a shell that
- // cannot spawn. Bare names (`fish`, `pwsh`) are passed through unchecked and
- // left to PATH, since `exists` can't see them.
+ // The override wins on every platform, but only if it actually resolves — a
+ // stale path in `.env` must not strand every session on a shell that cannot
+ // spawn. Bare names (`fish`, `pwsh`) are passed through unchecked and left to
+ // PATH, since `exists` can't see them.
const override = (env.PORTOS_SHELL || '').trim();
- if (override && (!/[\\/]/.test(override) || exists(override))) return override;
+ if (override) {
+ if (!/[\\/]/.test(override) || exists(override)) return override;
+ // Silently auto-detecting past a typo'd override leaves the user with no
+ // signal at all about why their setting had no effect.
+ console.warn(`🐚 PORTOS_SHELL='${override}' does not exist — auto-detecting instead`);
+ }
if (platform !== 'win32') return env.SHELL || '/bin/zsh';
-
- const found = windowsShellCandidates(env, readdir).find(exists);
- if (found) return found;
- return env.COMSPEC || 'cmd.exe';
+ return resolveWindowsShell(env, exists, readdir, findOnPath);
}
let cached;
diff --git a/server/lib/interactiveShellResolver.test.js b/server/lib/interactiveShellResolver.test.js
index 78bbbfcf0d..f9d044b9ff 100644
--- a/server/lib/interactiveShellResolver.test.js
+++ b/server/lib/interactiveShellResolver.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect } from 'vitest';
+import { describe, it, expect, vi } from 'vitest';
import { resolveInteractiveShellWith } from './interactiveShellResolver.js';
// Windows env fixture. `exists` is driven per-test so the whole preference
@@ -12,10 +12,10 @@ const WIN_ENV = {
};
const PS5 = 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe';
const onlyExists = (...paths) => (p) => paths.includes(p);
-// readdir is stubbed by default so the suite never depends on what the host
-// machine happens to have installed under Program Files.
+// readdir and the PATH lookup are stubbed by default so the suite never depends
+// on what the host machine happens to have installed.
const win = (opts = {}) => resolveInteractiveShellWith({
- platform: 'win32', env: WIN_ENV, readdir: () => ['7'], ...opts,
+ platform: 'win32', env: WIN_ENV, readdir: () => ['7'], findOnPath: () => null, ...opts,
});
describe('resolveInteractiveShellWith on Windows', () => {
@@ -48,9 +48,21 @@ describe('resolveInteractiveShellWith on Windows', () => {
expect(win({ exists: onlyExists(PS5) })).toBe(PS5);
});
- it('falls back to the WindowsApps pwsh launcher when no versioned dir exists', () => {
- const launcher = 'C:\\Users\\example\\AppData\\Local\\Microsoft\\WindowsApps\\pwsh.exe';
- expect(win({ exists: onlyExists(launcher, PS5) })).toBe(launcher);
+ it('finds a pwsh installed anywhere on PATH (scoop, choco, the Store shim)', () => {
+ // Those installs have no %ProgramFiles%\PowerShell\<n> directory, so the
+ // versioned scan misses them entirely.
+ const scoop = 'C:\\Users\\example\\scoop\\shims\\pwsh.exe';
+ expect(win({
+ exists: onlyExists(PS5),
+ findOnPath: (name) => (name === 'pwsh.exe' ? scoop : null),
+ })).toBe(scoop);
+ });
+
+ it('does not scan PATH when a versioned pwsh install already answered', () => {
+ const versioned = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe';
+ const findOnPath = vi.fn(() => 'C:\\other\\pwsh.exe');
+ expect(win({ exists: onlyExists(versioned), findOnPath })).toBe(versioned);
+ expect(findOnPath).not.toHaveBeenCalled();
});
it('uses COMSPEC only when no PowerShell exists at all', () => {
diff --git a/server/lib/shellCd.js b/server/lib/shellCd.js
index 06dad43cb3..9b2fd9775b 100644
--- a/server/lib/shellCd.js
+++ b/server/lib/shellCd.js
@@ -44,8 +44,13 @@ export function detectShellFlavor(shell, platform = process.platform) {
if (bin) return 'posix';
// No shell recorded — an externally-registered session (a CoS agent's TUI run)
// hands us its PTY without one. Fall back to the platform default, which is
- // what getDefaultShell() spawned for it.
- return platform === 'win32' ? 'cmd' : 'posix';
+ // what lib/interactiveShellResolver.js picks: PowerShell on Windows, since
+ // cmd.exe is now only reached on a box with no PowerShell at all. Guessing
+ // 'cmd' here is not a safe default — its syntax is a hard error under
+ // PowerShell (`cd /d` → "positional parameter", `&` → "not allowed"),
+ // whereas the PowerShell forms merely fail to parse in the vanishingly rare
+ // cmd-only case.
+ return platform === 'win32' ? 'powershell' : 'posix';
}
/**
diff --git a/server/lib/shellCd.test.js b/server/lib/shellCd.test.js
index 3eab4cce83..fb04883ef0 100644
--- a/server/lib/shellCd.test.js
+++ b/server/lib/shellCd.test.js
@@ -15,7 +15,9 @@ describe('detectShellFlavor', () => {
});
it('falls back to the platform default when no shell is recorded', () => {
- expect(detectShellFlavor(undefined, 'win32')).toBe('cmd');
+ // PowerShell, not cmd — that is what interactiveShellResolver picks on
+ // Windows, and cmd's syntax is a hard error under PowerShell.
+ expect(detectShellFlavor(undefined, 'win32')).toBe('powershell');
expect(detectShellFlavor('', 'darwin')).toBe('posix');
expect(detectShellFlavor(null, 'linux')).toBe('posix');
});
diff --git a/server/lib/shellExit.test.js b/server/lib/shellExit.test.js
index 03add650d1..cc7b5fd0f5 100644
--- a/server/lib/shellExit.test.js
+++ b/server/lib/shellExit.test.js
@@ -32,9 +32,13 @@ describe('buildRunThenExitCommand', () => {
it('falls back to the platform default when the session records no shell', () => {
// Matches detectShellFlavor's own fallback — an externally-registered PTY
- // hands us no shell binary.
+ // hands us no shell binary. On Windows that default is PowerShell, where
+ // `&` is a *parse error* in 5.1 and backgrounds the command as a job in
+ // pwsh 7, so this must not fall back to the cmd form.
expect(buildRunThenExitCommand('claude', undefined)).toBe(
- process.platform === 'win32' ? 'claude & exit' : 'claude; exit $?',
+ process.platform === 'win32'
+ ? '$LASTEXITCODE = 1; claude; exit $LASTEXITCODE'
+ : 'claude; exit $?',
);
});
});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 6a9677c955..7d2d3ab007 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -28,7 +28,6 @@ import * as git from './git.js';
import { resolveReviewLoopOptions } from './codeReview.js';
import { spawnTuiSessionViaRunner } from './cosRunnerClient.js';
import { shellQuote } from '../lib/shellQuote.js';
-import { buildRunThenExitCommand } from '../lib/shellExit.js';
import { isClaudeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';
import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
@@ -135,25 +134,20 @@ export async function createAgentTuiSession({
return session;
}
- // This shell exists only to host the CoS TUI. Make it follow the TUI's
- // lifetime and preserve the TUI exit status; otherwise the login shell
- // returns to its prompt when the provider exits and the spawner cannot
- // observe completion until the wall-clock backstop fires.
- //
- // The shell is resolved HERE and passed down, rather than left to
- // createShellSession's default, so the run-then-exit line is guaranteed to be
- // written in the dialect of the shell that actually receives it — the POSIX
- // `; exit $?` inverts the status under PowerShell (see lib/shellExit.js).
- const shell = shellService.getDefaultShell();
- const initialCommand = buildRunThenExitCommand(tuiConfig.commandLine, shell);
+ // This shell exists only to host the CoS TUI. `exitWithCommand` makes it
+ // follow the TUI's lifetime and preserve the TUI exit status; otherwise the
+ // login shell returns to its prompt when the provider exits and the spawner
+ // cannot observe completion until the wall-clock backstop fires. The wrapper
+ // is dialect-specific, so shell.js renders it once it knows which shell the
+ // session got (see lib/shellExit.js).
const sessionId = shellService.createShellSession(null, {
- shell,
cwd,
+ initialCommand: tuiConfig.commandLine,
+ exitWithCommand: true,
kind: 'agent-tui',
agentId,
label: `${provider.name} ${agentId}`,
command: tuiConfig.commandLine,
- initialCommand,
// Wait until the shell can actually RUN commands before injecting the CLI
// command — a fixed delay races a heavy interactive shell and the launched
// TUI can fall straight back to a half-loaded prompt (see shell.js
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 572621bb88..b50aec557a 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -12,9 +12,6 @@ vi.mock('./shell.js', () => ({
getSession: vi.fn(),
getSessionProcess: vi.fn(),
registerExternalSession: vi.fn(),
- // The spawner asks for the session's shell so it can render the run-then-exit
- // line in that shell's dialect (lib/shellExit.js).
- getDefaultShell: vi.fn(() => '/bin/zsh'),
}));
vi.mock('./cosRunnerClient.js', () => ({
@@ -653,26 +650,12 @@ describe('spawnTuiAgent runtime', () => {
runSpawn();
await flushMicrotasks();
+ // The raw command plus the flag — the run-then-exit wrapper is rendered by
+ // shell.js, which is the only place that knows the session's shell dialect.
+ // Its rendering is covered by shell.test.js and lib/shellExit.test.js.
expect(shellService.createShellSession).toHaveBeenCalledWith(
null,
- expect.objectContaining({ initialCommand: 'codex; exit $?', shell: '/bin/zsh' }),
- );
- });
-
- it('writes the run-then-exit line in the dialect of the shell it also pins on the session', async () => {
- // The shell is resolved once and passed down, so the line can never be
- // rendered for a different shell than the one that receives it. Under
- // PowerShell the POSIX `exit $?` reports success as 1 (see lib/shellExit.js).
- vi.mocked(shellService.getDefaultShell).mockReturnValueOnce('C:\\Program Files\\PowerShell\\7\\pwsh.exe');
- runSpawn();
- await flushMicrotasks();
-
- expect(shellService.createShellSession).toHaveBeenCalledWith(
- null,
- expect.objectContaining({
- initialCommand: '$LASTEXITCODE = 1; codex; exit $LASTEXITCODE',
- shell: 'C:\\Program Files\\PowerShell\\7\\pwsh.exe',
- }),
+ expect.objectContaining({ initialCommand: 'codex', exitWithCommand: true }),
);
});
diff --git a/server/services/shell.js b/server/services/shell.js
index 6c04b34301..af63e0abc3 100644
--- a/server/services/shell.js
+++ b/server/services/shell.js
@@ -5,6 +5,7 @@ import { withSpawnCwdEnv } from '../lib/spawnCwd.js';
import { scheduleSubmitEnters, SUBMIT_KEY } from '../lib/tuiHandshake.js';
import { buildCdCommand } from '../lib/shellCd.js';
import { resolveInteractiveShell } from '../lib/interactiveShellResolver.js';
+import { buildRunThenExitCommand } from '../lib/shellExit.js';
// Store active shell sessions (persist across socket reconnects)
const shellSessions = new Map();
@@ -119,14 +120,8 @@ export function buildSafeEnv(env = process.env, platform = process.platform) {
/**
* The shell a session runs when the caller doesn't name one.
- *
- * Exported so a caller that must render a command in this shell's dialect
- * (agentTuiSpawning's run-then-exit line) can ask for the same answer the
- * session will get, rather than re-deriving it and drifting.
- *
- * @returns {string} shell binary path (or bare name, on POSIX)
*/
-export function getDefaultShell() {
+function getDefaultShell() {
return resolveInteractiveShell();
}
@@ -241,6 +236,14 @@ export function createShellSession(socket, options = {}) {
releaseExternalViews(socket, sessionId);
broadcastSessionList();
if (options.initialCommand) {
+ // `exitWithCommand` wraps the command so the shell dies with it, carrying its
+ // status out (an agent-TUI shell exists only to host one CLI). Rendered HERE
+ // rather than by the caller because only this function knows which shell the
+ // session actually got, and the wrapper is dialect-specific — see
+ // lib/shellExit.js. Same reason changeSessionDirectory renders its own `cd`.
+ const initialCommand = options.exitWithCommand
+ ? buildRunThenExitCommand(options.initialCommand, shell)
+ : options.initialCommand;
// onInitialCommandSent fires at the exact moment the command is injected,
// regardless of which branch sent it. The agent-TUI spawner uses this to
// start observing claude's input-readiness ONLY after the real command is
@@ -248,7 +251,7 @@ export function createShellSession(socket, options = {}) {
// prematurely satisfy its bracketed-paste gate.
const sendInitial = () => {
options.onInitialCommandSent?.();
- submitToSession(sessionId, options.initialCommand);
+ submitToSession(sessionId, initialCommand);
};
if (options.waitForPromptReady) {
// Inject the command only once the shell can ACTUALLY run commands. A fixed
@@ -266,12 +269,13 @@ export function createShellSession(socket, options = {}) {
// sighting is unambiguous. Instant-prompt keystroke buffering replays the
// probe into the real shell, so this is theme- and shell-agnostic. A
// bounded fallback still injects the command if the probe never round-trips.
- // NOTE: the probe is POSIX (`printf`). The only caller of waitForPromptReady
- // is the agent-TUI path, which is developer-machine (mac/linux) only; on a
- // Windows shell (PowerShell or cmd.exe) `printf` isn't a command, so the
- // probe errors out, the marker never appears, and the command injects on the
- // bounded fallback below (slower, never broken). A Windows port would need a
- // dialect-aware probe — see #4638.
+ // NOTE: the probe is still POSIX-only (`printf`), unlike the `cd` and
+ // run-then-exit lines, which are rendered per dialect. On a Windows shell
+ // (PowerShell or cmd.exe) `printf` isn't a command, so the probe errors
+ // out, the marker never appears, and the command injects on the bounded
+ // fallback below — i.e. every Windows agent-TUI spawn waits the full 8s
+ // and then injects blind, which is exactly what the probe exists to avoid.
+ // Never broken, just slow and unproven. Making it dialect-aware is #4638.
let sent = false;
let sub = null;
let exitSub = null;
diff --git a/server/services/shell.test.js b/server/services/shell.test.js
index 1958dd16c6..9d2985f0e6 100644
--- a/server/services/shell.test.js
+++ b/server/services/shell.test.js
@@ -1,5 +1,4 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { buildCdCommand } from '../lib/shellCd.js';
let ptyInstances = [];
let spawnImpl;
@@ -391,16 +390,57 @@ describe('changeSessionDirectory', () => {
expect(shell.changeSessionDirectory('missing', '/tmp')).toBe(false);
});
- it('records the resolved default shell when the caller names none', () => {
- // The recorded shell is what picks the cd dialect, so a session that spawned
- // from the default must remember which binary that was — not fall through to
- // detectShellFlavor's platform guess. Resolution itself is covered by
- // lib/interactiveShellResolver.test.js.
+ it('records the shell it spawned when the caller names none', () => {
+ // The recorded shell is what picks the cd dialect, so a session started from
+ // the default must remember which binary that was rather than leaving
+ // detectShellFlavor to guess from the platform. Which binary gets resolved is
+ // covered by lib/interactiveShellResolver.test.js.
const id = shell.createShellSession(makeSocket('sock-default'));
const spawnedShell = vi.mocked(defaultSpawn).mock.calls[0][0];
- expect(spawnedShell).toBe(shell.getDefaultShell());
- expect(shell.changeSessionDirectory(id, '/tmp/app')).toBe(true);
- expect(ptyInstances[0].write).toHaveBeenCalledWith(`${buildCdCommand('/tmp/app', spawnedShell)}\r`);
+ expect(spawnedShell).toBeTruthy();
+ expect(shell.getSession(id).shell).toBe(spawnedShell);
+ });
+});
+
+describe('initialCommand + exitWithCommand', () => {
+ it('wraps the command so the shell exits with it, in that shell\'s dialect', () => {
+ // The wrapper is rendered here rather than by the caller because only this
+ // function knows which shell the session got. Under PowerShell the POSIX
+ // `exit $?` would report a successful run as 1 — see lib/shellExit.js.
+ vi.useFakeTimers();
+ shell.createShellSession(makeSocket('sock-pwsh'), {
+ shell: 'C:\\Program Files\\PowerShell\\7\\pwsh.exe',
+ initialCommand: 'codex',
+ exitWithCommand: true,
+ initialCommandDelayMs: 10,
+ });
+ vi.advanceTimersByTime(10);
+ expect(ptyInstances[0].write).toHaveBeenCalledWith(
+ `$LASTEXITCODE = 1; codex; exit $LASTEXITCODE${shell.SUBMIT_KEY}`,
+ );
+
+ shell.createShellSession(makeSocket('sock-zsh'), {
+ shell: '/bin/zsh',
+ initialCommand: 'codex',
+ exitWithCommand: true,
+ initialCommandDelayMs: 10,
+ });
+ vi.advanceTimersByTime(10);
+ expect(ptyInstances[1].write).toHaveBeenCalledWith(`codex; exit $?${shell.SUBMIT_KEY}`);
+ vi.useRealTimers();
+ });
+
+ it('sends the command untouched without the flag, so a user-typed command is never wrapped', () => {
+ // socket.js `shell:start` forwards whatever the user asked to run.
+ vi.useFakeTimers();
+ shell.createShellSession(makeSocket('sock-raw'), {
+ shell: 'C:\\Program Files\\PowerShell\\7\\pwsh.exe',
+ initialCommand: 'npm test',
+ initialCommandDelayMs: 10,
+ });
+ vi.advanceTimersByTime(10);
+ expect(ptyInstances[0].write).toHaveBeenCalledWith(`npm test${shell.SUBMIT_KEY}`);
+ vi.useRealTimers();
});
});