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
Launch Windows shell sessions in PowerShell, not cmd.exe
[._.]/ Adam Eivy4a35ca220734
diff --git a/.env.example b/.env.exampleindex 5090904524..03ab6cf2da 100644--- a/.env.example+++ b/.env.example@@ -109,9 +109,20 @@ PGPASSWORD=portos# CivitAI API key for LoRA / model downloads from civitai.com# CIVITAI_API_KEY=your_civitai_api_key_here-# Absolute path to the bash binary used when spawning shell sessions (auto-detected if unset)+# Absolute path to the bash binary used to run PortOS's bundled *.sh scripts+# (e.g. scripts/db.sh). Auto-detected if unset; on Windows it prefers Git Bash,+# because a bare `bash` often resolves to WSL, which can't see drive paths.# 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:.+# Windows: PORTOS_SHELL=C:\Program Files\Git\bin\bash.exe+# PORTOS_SHELL=/bin/fish+# Extra directory roots exposed in the workspace file browser, on top of the# defaults (home, /tmp, /Users, /Volumes, /mnt, /media, /opt — on Windows: home,# the temp dir, and any lettered non-system drive). Separated by the platformdiff --git a/server/lib/README.md b/server/lib/README.mdindex 0f84d364fa..1b55e3b44f 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -197,6 +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. || `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`. |@@ -371,6 +372,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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?)` — build a `cd` line for the shell a PTY session is ACTUALLY running (`cmd.exe` → `cd /d "…"`, PowerShell → `Set-Location -LiteralPath '…'`, everything else → POSIX `cd '…'` via `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`. |+| `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). || `slashdoCatalog.js` | The single catalog of which bundled slashdo workflows PortOS offers as a one-click agent run — `SLASHDO_WORKFLOWS` (`{command, label, description, icon, templateName, templatePrompt?, settings, appTypes, configurable?}`), `getSlashdoWorkflow()` (the allowlist gate for `POST /api/cos/tasks/slashdo`), `SLASHDO_COMMAND_NAMES`, `slashdoWorkflowsForApp(isSwiftApp)`, `SLASHDO_APP_TYPES`, and the two run-shape postures `WORKFLOW_OWNS_ITS_OWN_GIT` (commit-shaped) / `WORKFLOW_REPORTS_NO_CODE` (report-shaped — carries `worktreeChangesExpected: false` so a filed-issue/printed-report run retains its non-code deliverable posture). Backs the Agent Operations buttons, the CoS quick templates (`taskTemplates.js`), and the route allowlist, replacing two catalogs that had drifted. Mirrored in `client/src/lib/slashdoCatalog.js` (button styling only), pinned by `slashdoCatalog.test.js`. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 036de806e7..9dbc984823 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -210,6 +210,7 @@ export * from './gitOutputParsers.js';export * from './gitRemote.js';export * from './githubRepoUrl.js';export * from './goalFeatureMap.js';+export * from './interactiveShellResolver.js';export * from './killWithEscalation.js';export * from './openFolder.js';export * from './processEnv.js';@@ -348,6 +349,7 @@ export * from './objects.js';export * from './openapiSpec.js';export * from './prDisposition.js';export * from './shellCd.js';+export * from './shellExit.js';export * from './shellQuote.js';export * from './sidecarProcess.js';export * from './slashdoCatalog.js';diff --git a/server/lib/interactiveShellResolver.js b/server/lib/interactiveShellResolver.jsnew file mode 100644index 0000000000..f441ba64e3--- /dev/null+++ b/server/lib/interactiveShellResolver.js@@ -0,0 +1,129 @@+/**+ * Pick the shell binary a PTY session (the Shell page, agent TUI shells) runs.+ *+ * THE PROBLEM (Windows). The default used to be `COMSPEC`, i.e. `cmd.exe`, and+ * `cmd.exe` cannot get you onto another drive by any command a user would+ * reasonably type:+ *+ * cd I: → PRINTS `I:\` and stays put. `cd` without `/d`+ * reports the working dir *of* that drive rather+ * than switching to it — silent, no error.+ * I:\ / I:/ → "is not recognized as an internal or external+ * command" (a bare drive letter is a command, not+ * a `cd`; only `I:` alone works, and even that+ * only changes the drive, not the directory).+ * cd 'I:\path\to\repo' → "The filename, directory name, or volume label+ * syntax is incorrect" — cmd has no single-quote+ * quoting, so the quotes become part of the path.+ *+ * Only `cd /d "I:\path"` works, which is why `buildCdCommand` (lib/shellCd.js)+ * emits that form for the "cd to app" picker. But that fixes only the commands+ * PortOS sends — anything the user types by hand still fails, and a Windows+ * install whose repos live on a second drive is then stuck on `C:`.+ *+ * PowerShell has none of these problems: `cd I:`, `cd I:\path`, `cd 'I:\path'`+ * and `Set-Location` all cross drives, and it accepts both quote styles. So on+ * Windows we prefer PowerShell and keep `cmd.exe` only as a last resort.+ *+ * 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+ * 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.+ *+ * 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';++/**+ * `%ProgramFiles%\PowerShell\<major>\pwsh.exe` for every installed major+ * version, newest first. Enumerated rather than hard-coding `7` so a future+ * 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) {+ const roots = [env.ProgramFiles, env['ProgramFiles(x86)']].filter(Boolean);+ const found = [];+ for (const root of roots) {+ const base = join(root, 'PowerShell');+ let entries;+ // readdirSync throws when PowerShell 7+ was never installed — the common+ // case on a stock Windows box, not an error worth surfacing.+ try {+ entries = readdir(base);+ } catch {+ continue;+ }+ // Numeric sort, not lexical: '10' must outrank '7'.+ const majors = entries+ .filter(name => /^\d+$/.test(name))+ .sort((a, b) => Number(b) - Number(a));+ for (const major of majors) found.push(join(base, major, 'pwsh.exe'));+ }+ 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'));+ }+ // 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;+}++/**+ * Resolve the shell without consulting (or populating) the memo. Exported for+ * tests, which need to drive the Windows branch from a POSIX host.+ *+ * @param {object} [deps]+ * @param {string} [deps.platform] - `process.platform` value+ * @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+ * @returns {string} shell binary path (or bare name, on POSIX)+ */+export function resolveInteractiveShellWith({+ platform = process.platform,+ env = process.env,+ exists = existsSync,+ readdir = readdirSync,+} = {}) {+ // 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 (platform !== 'win32') return env.SHELL || '/bin/zsh';++ const found = windowsShellCandidates(env, readdir).find(exists);+ if (found) return found;+ return env.COMSPEC || 'cmd.exe';+}++let cached;++/**+ * Resolve the interactive shell. Memoized after the first call — the answer is+ * a property of the machine, and every new PTY session would otherwise re-probe+ * the filesystem. Which binary a session actually got is logged by+ * `createShellSession`, per session.+ *+ * @returns {string} shell binary path (or bare name, on POSIX)+ */+export function resolveInteractiveShell() {+ if (cached === undefined) cached = resolveInteractiveShellWith();+ return cached;+}diff --git a/server/lib/interactiveShellResolver.test.js b/server/lib/interactiveShellResolver.test.jsnew file mode 100644index 0000000000..78bbbfcf0d--- /dev/null+++ b/server/lib/interactiveShellResolver.test.js@@ -0,0 +1,108 @@+import { describe, it, expect } from 'vitest';+import { resolveInteractiveShellWith } from './interactiveShellResolver.js';++// Windows env fixture. `exists` is driven per-test so the whole preference+// chain is reachable from a POSIX host.+const WIN_ENV = {+ ProgramFiles: 'C:\\Program Files',+ 'ProgramFiles(x86)': 'C:\\Program Files (x86)',+ LOCALAPPDATA: 'C:\\Users\\example\\AppData\\Local',+ SystemRoot: 'C:\\Windows',+ COMSPEC: 'C:\\Windows\\system32\\cmd.exe',+};+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.+const win = (opts = {}) => resolveInteractiveShellWith({+ platform: 'win32', env: WIN_ENV, readdir: () => ['7'], ...opts,+});++describe('resolveInteractiveShellWith on Windows', () => {+ it('prefers PowerShell 7+ over Windows PowerShell and cmd.exe', () => {+ // The whole point: cmd.exe cannot reach another drive by anything a user+ // would type — `cd I:` prints that drive's cwd and stays put.+ expect(win({ exists: onlyExists('C:\\Program Files\\PowerShell\\7\\pwsh.exe', PS5) }))+ .toBe('C:\\Program Files\\PowerShell\\7\\pwsh.exe');+ });++ it('picks the newest installed pwsh major, comparing numerically not as strings', () => {+ // '10' must beat '7'; a lexical sort would pick '7'.+ expect(win({+ readdir: (dir) => (dir === 'C:\\Program Files\\PowerShell' ? ['7', '10', 'preview'] : []),+ exists: (p) => p.startsWith('C:\\Program Files\\PowerShell\\'),+ })).toBe('C:\\Program Files\\PowerShell\\10\\pwsh.exe');+ });++ it('survives a machine with no PowerShell install directory to list', () => {+ // readdirSync throws on a stock box that never installed PowerShell 7+.+ expect(win({+ readdir: () => { throw new Error('ENOENT'); },+ exists: onlyExists(PS5),+ })).toBe(PS5);+ });++ it('falls back to Windows PowerShell 5.1 when pwsh is absent', () => {+ // 5.1 ships with every supported Windows and crosses drives too — it is+ // the realistic floor, not cmd.exe.+ 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('uses COMSPEC only when no PowerShell exists at all', () => {+ expect(win({ exists: () => false })).toBe('C:\\Windows\\system32\\cmd.exe');+ });++ it('defaults to cmd.exe when COMSPEC is unset and no PowerShell exists', () => {+ expect(resolveInteractiveShellWith({ platform: 'win32', env: {}, exists: () => false }))+ .toBe('cmd.exe');+ });+});++describe('resolveInteractiveShellWith PORTOS_SHELL override', () => {+ it('wins over the Windows preference chain when the path exists', () => {+ const bash = 'C:\\Program Files\\Git\\bin\\bash.exe';+ expect(win({ env: { ...WIN_ENV, PORTOS_SHELL: bash }, exists: onlyExists(bash, PS5) })).toBe(bash);+ });++ it('is ignored when it names a path that does not exist', () => {+ // A stale `.env` entry must not strand every session on a shell that+ // cannot spawn.+ expect(win({+ env: { ...WIN_ENV, PORTOS_SHELL: 'D:\\gone\\nushell.exe' },+ exists: onlyExists(PS5),+ })).toBe(PS5);+ });++ it('passes a bare command name through unchecked, since PATH resolves it', () => {+ expect(resolveInteractiveShellWith({+ platform: 'darwin',+ env: { PORTOS_SHELL: 'fish', SHELL: '/bin/bash' },+ exists: () => false,+ })).toBe('fish');+ });++ it('ignores a blank/whitespace override', () => {+ expect(resolveInteractiveShellWith({+ platform: 'linux',+ env: { PORTOS_SHELL: ' ', SHELL: '/bin/bash' },+ exists: () => false,+ })).toBe('/bin/bash');+ });+});++describe('resolveInteractiveShellWith on POSIX', () => {+ it('uses SHELL, and zsh when it is unset — unchanged behavior', () => {+ expect(resolveInteractiveShellWith({ platform: 'darwin', env: { SHELL: '/bin/bash' } })).toBe('/bin/bash');+ expect(resolveInteractiveShellWith({ platform: 'linux', env: {} })).toBe('/bin/zsh');+ });++ it('never reaches the Windows candidates even when they exist', () => {+ expect(resolveInteractiveShellWith({ platform: 'linux', env: WIN_ENV, exists: () => true }))+ .toBe('/bin/zsh');+ });+});diff --git a/server/lib/shellExit.js b/server/lib/shellExit.jsnew file mode 100644index 0000000000..537f20a551--- /dev/null+++ b/server/lib/shellExit.js@@ -0,0 +1,41 @@+/**+ * Build "run this command, then close the shell with its exit status" for the+ * shell a PTY session is actually running.+ *+ * An agent TUI session exists only to host one CLI (`claude`, `codex`, …). The+ * shell must die when that CLI does, carrying its status out — otherwise the+ * shell returns to its prompt, the PTY stays open, and the spawner can't see+ * completion until the wall-clock backstop fires.+ *+ * The POSIX form `cmd; exit $?` was applied to every platform, and it is not+ * merely unsupported elsewhere — it is wrong in an actively misleading way:+ *+ * • PowerShell — `$?` is a BOOLEAN (did the last command succeed), not a+ * status. `exit $?` coerces it, so a CLI that exited 0 leaves the shell+ * with 1 and one that failed leaves 0. Exactly inverted. `$LASTEXITCODE`+ * is the actual status, pre-seeded to 1 so a command that never ran (typo,+ * not on PATH) still exits non-zero instead of leaving it unset → 0.+ * • cmd.exe — `;` is an argument separator, not a command separator, so the+ * CLI is handed `;`, `exit` and `$?` as extra arguments and usually dies on+ * them. `&` chains unconditionally, and a bare `exit` carries ERRORLEVEL.+ *+ * Verified against node-pty on Windows 11 for pwsh 7, Windows PowerShell 5.1+ * and cmd.exe: exit 7 → 7, exit 0 → 0, command-not-found → non-zero.+ *+ * Renders the LINE only; the Enter byte that submits it is `SUBMIT_KEY` in+ * `tuiHandshake.js`.+ */+import { detectShellFlavor } from './shellCd.js';++/**+ * @param {string} commandLine - the command to run, already quoted for `shell`+ * @param {string} [shell] - the session's shell binary; see detectShellFlavor+ * @returns {string} a single command line, no trailing terminator+ */+export function buildRunThenExitCommand(commandLine, shell) {+ switch (detectShellFlavor(shell)) {+ case 'cmd': return `${commandLine} & exit`;+ case 'powershell': return `$LASTEXITCODE = 1; ${commandLine}; exit $LASTEXITCODE`;+ default: return `${commandLine}; exit $?`;+ }+}diff --git a/server/lib/shellExit.test.js b/server/lib/shellExit.test.jsnew file mode 100644index 0000000000..03add650d1--- /dev/null+++ b/server/lib/shellExit.test.js@@ -0,0 +1,40 @@+import { describe, it, expect } from 'vitest';+import { buildRunThenExitCommand } from './shellExit.js';++describe('buildRunThenExitCommand', () => {+ it('uses $LASTEXITCODE on PowerShell, because $? there is a boolean', () => {+ // `exit $?` under PowerShell coerces the boolean: a CLI that exited 0+ // leaves the shell with 1 and one that failed leaves 0 — exactly inverted,+ // which would record every successful agent run as a failure.+ expect(buildRunThenExitCommand('claude --model opus', 'pwsh.exe'))+ .toBe('$LASTEXITCODE = 1; claude --model opus; exit $LASTEXITCODE');+ expect(buildRunThenExitCommand('codex', 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe'))+ .toBe('$LASTEXITCODE = 1; codex; exit $LASTEXITCODE');+ });++ it('pre-seeds $LASTEXITCODE so a command that never runs still exits non-zero', () => {+ // A typo'd / missing CLI leaves $LASTEXITCODE unset, and `exit $null` is 0.+ expect(buildRunThenExitCommand('nope', 'pwsh.exe')).toMatch(/^\$LASTEXITCODE = 1;/);+ });++ it('chains with & on cmd.exe, where ; is an argument separator', () => {+ // `claude foo; exit $?` hands cmd's CLI three extra arguments (`;`, `exit`,+ // `$?`) instead of chaining. A bare `exit` carries ERRORLEVEL out.+ expect(buildRunThenExitCommand('claude --model opus', 'C:\\WINDOWS\\system32\\cmd.exe'))+ .toBe('claude --model opus & exit');+ });++ it('keeps the POSIX form for POSIX shells, including git-bash on Windows', () => {+ expect(buildRunThenExitCommand('claude', '/bin/zsh')).toBe('claude; exit $?');+ expect(buildRunThenExitCommand('claude', 'C:\\Program Files\\Git\\bin\\bash.exe'))+ .toBe('claude; exit $?');+ });++ 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.+ expect(buildRunThenExitCommand('claude', undefined)).toBe(+ process.platform === 'win32' ? 'claude & exit' : 'claude; exit $?',+ );+ });+});diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex bcc6c1731a..6a9677c955 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -28,6 +28,7 @@ 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';@@ -138,8 +139,15 @@ export async function createAgentTuiSession({// 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.- const initialCommand = `${tuiConfig.commandLine}; exit $?`;+ //+ // 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);const sessionId = shellService.createShellSession(null, {+ shell,cwd,kind: 'agent-tui',agentId,diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 44708eaf93..572621bb88 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -12,6 +12,9 @@ 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', () => ({@@ -652,7 +655,24 @@ describe('spawnTuiAgent runtime', () => {expect(shellService.createShellSession).toHaveBeenCalledWith(null,- expect.objectContaining({ initialCommand: 'codex; exit $?' }),+ 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',+ }),);});diff --git a/server/services/shell.js b/server/services/shell.jsindex e0e31eba4b..6c04b34301 100644--- a/server/services/shell.js+++ b/server/services/shell.js@@ -4,6 +4,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';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';// Store active shell sessions (persist across socket reconnects)const shellSessions = new Map();@@ -117,13 +118,16 @@ export function buildSafeEnv(env = process.env, platform = process.platform) {}/**- * Get the default shell for the current OS+ * 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)*/-function getDefaultShell() {- if (process.platform === 'win32') {- return process.env.COMSPEC || 'cmd.exe';- }- return process.env.SHELL || '/bin/zsh';+export function getDefaultShell() {+ return resolveInteractiveShell();}/**@@ -264,10 +268,10 @@ export function createShellSession(socket, options = {}) {// 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 cmd.exe shell `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 platform-aware- // probe.+ // 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.let sent = false;let sub = null;let exitSub = null;diff --git a/server/services/shell.test.js b/server/services/shell.test.jsindex 8635ae5863..1958dd16c6 100644--- a/server/services/shell.test.js+++ b/server/services/shell.test.js@@ -1,4 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { buildCdCommand } from '../lib/shellCd.js';let ptyInstances = [];let spawnImpl;@@ -389,6 +390,18 @@ describe('changeSessionDirectory', () => {it('returns false for a missing session', () => {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.+ 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`);+ });});describe('submitToSession', () => {