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

fix(shell): POSIX fallback to bash/sh when zsh is missing (#6496)

atomanticagent752db055062d
diff --git a/server/lib/README.md b/server/lib/README.md
index b39d0344d3..d576c63f83 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -314,7 +314,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` 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. |
+| `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. On POSIX: PORTOS_SHELL → existing `SHELL` → `/bin/bash` `/usr/bin/bash` `/bin/sh` `/usr/bin/sh` then zsh if present → bare `bash`/`sh` via `findCommandOnPath` → bare `sh` last — never a hard-coded missing `/bin/zsh` (PM2/containers often lack `SHELL` and zsh; node-pty then `execvp`s and the Shell page shows only `execvp(3) failed`). Memoized; `_resetInteractiveShellCache()` for tests. `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`, `guardChildStdin(child)` (attach the no-op `stdin` `'error'` listener BEFORE any `stdin.write`/`stdin.end` — a child that dies before reading stdin makes the pipe emit `EPIPE`, and an unlistened stream `'error'` outside the Express request lifecycle takes the whole server process down; call it at every spawn that writes to a child's stdin) + `deliverChildStdin(child, payload, label)` (its other half: write-then-`end()` with a synchronously-throwing `write` caught, the pipe destroyed so a reading child sees EOF rather than hanging, and the failure logged so an empty-prompt run that exits 0 isn't filed as clean), `spawnFailureDetail(result, fallback)` (the most useful sentence from a failed result — prefers the spawn error, then a stderr line, then a stdout line that isn't bare JSON punctuation, because a `--json` CLI prints its payload to stdout even when it exits non-zero) — shared buffered-spawn machinery with capped stdout/stderr, timeout SIGTERM plus fire-and-forget SIGKILL escalation (`killGraceMs`, default 8s), 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). A killable that is NOT a `ChildProcess` — a node-pty `IPty` TUI session — is killed through its own `.kill()`, with **no signal on Windows**: node-pty throws `Signals not supported on windows.` for any signal argument, so a signalled kill there killed nothing and threw past the caller. 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 ee4e64c39e..73ae4a83a5 100644
--- a/server/lib/interactiveShellResolver.js
+++ b/server/lib/interactiveShellResolver.js
@@ -35,7 +35,24 @@
* profile (slower start) and is stuck on the older engine.
* 5. `COMSPEC` / `cmd.exe` — only if no PowerShell exists at all.
*
- * On POSIX the choice was never broken: PORTOS_SHELL, else `SHELL`, else zsh.
+ * Resolution order (POSIX):
+ * 1. PORTOS_SHELL override — same escape hatch as Windows (absolute path must
+ * exist; bare names pass through for PATH).
+ * 2. `SHELL` when set — absolute path only if it exists; bare name unchecked.
+ * 3. Common absolute candidates that exist on the host, in order:
+ * `/bin/bash`, `/usr/bin/bash`, `/bin/sh`, `/usr/bin/sh`, then zsh if
+ * present (`/bin/zsh`, `/usr/bin/zsh`). Bash/sh first because container and
+ * PM2 hosts often lack zsh; a login-shell `SHELL` already won in step 2 on
+ * macOS where zsh is the default.
+ * 4. Bare `bash` / `sh` via `findCommandOnPath` (same PATH helper as Windows).
+ * 5. Bare `sh` as the absolute last resort — never a hard-coded `/bin/zsh`
+ * that does not exist (node-pty `execvp`s the missing binary and the Shell
+ * page shows only `execvp(3) failed.: No such file or directory`).
+ *
+ * Why step 3–5 matter: under PM2 (and many containers) `process.env.SHELL` is
+ * unset — the daemon never inherited a login shell — and minimal images ship
+ * bash/sh but not zsh. The previous fallback of `/bin/zsh` was therefore a
+ * guaranteed spawn failure on those hosts.
*/
import { existsSync, readdirSync } from 'fs';
@@ -51,6 +68,19 @@ import { findCommandOnPath } from './processEnv.js';
// shellCd.js.
const { join } = win32;
+/**
+ * Absolute POSIX shells probed when neither PORTOS_SHELL nor an existing SHELL
+ * answered. Bash/sh before zsh: containers and daemonized Node often lack zsh.
+ */
+const POSIX_SHELL_CANDIDATES = Object.freeze([
+ '/bin/bash',
+ '/usr/bin/bash',
+ '/bin/sh',
+ '/usr/bin/sh',
+ '/bin/zsh',
+ '/usr/bin/zsh',
+]);
+
/**
* `%ProgramFiles%\PowerShell\<major>\pwsh.exe` for every installed major
* version, newest first. Enumerated rather than hard-coding `7` so a future
@@ -101,6 +131,42 @@ function resolveWindowsShell(env, exists, readdir, findOnPath) {
return env.COMSPEC || 'cmd.exe';
}
+/**
+ * Accept a configured shell path/name the same way PORTOS_SHELL is accepted:
+ * bare names pass through for PATH; absolute/relative paths must exist.
+ * Returns null when the value is blank or a missing path.
+ */
+function acceptConfiguredShell(value, exists) {
+ const trimmed = (value || '').trim();
+ if (!trimmed) return null;
+ if (!/[\\/]/.test(trimmed) || exists(trimmed)) return trimmed;
+ return null;
+}
+
+function resolvePosixShell(env, exists, findOnPath) {
+ // Prefer the user's login shell when the process inherited one that still
+ // exists. A stale SHELL pointing at a removed binary must not strand the
+ // session the way a hard-coded missing zsh used to.
+ const fromEnv = acceptConfiguredShell(env.SHELL, exists);
+ if (fromEnv) return fromEnv;
+
+ const absolute = POSIX_SHELL_CANDIDATES.find(exists);
+ if (absolute) return absolute;
+
+ for (const name of ['bash', 'sh', 'zsh']) {
+ const onPath = findOnPath(name, { env });
+ if (onPath) return onPath;
+ }
+
+ // Bare name last: node-pty will search PATH. Prefer this over inventing an
+ // absolute path that does not exist (the previous `/bin/zsh` default).
+ console.warn(
+ '🐚 No interactive shell binary found on disk or PATH — falling back to bare `sh`. '
+ + 'Install bash/zsh or set PORTOS_SHELL to an existing shell.',
+ );
+ return 'sh';
+}
+
/**
* Resolve the shell without consulting (or populating) the memo. Exported for
* tests, which need to drive the Windows branch from a POSIX host.
@@ -132,7 +198,7 @@ export function resolveInteractiveShellWith({
console.warn(`🐚 PORTOS_SHELL='${override}' does not exist — auto-detecting instead`);
}
- if (platform !== 'win32') return env.SHELL || '/bin/zsh';
+ if (platform !== 'win32') return resolvePosixShell(env, exists, findOnPath);
return resolveWindowsShell(env, exists, readdir, findOnPath);
}
@@ -144,9 +210,25 @@ let cached;
* the filesystem. Which binary a session actually got is logged by
* `createShellSession`, per session.
*
+ * The memo captures whatever the first call resolved under the process env and
+ * filesystem at that moment. Tests that change those must call
+ * `_resetInteractiveShellCache()` (or use `resolveInteractiveShellWith`, which
+ * never touches the memo). After this fix ships, the first resolve on a host
+ * without zsh / without SHELL picks bash/sh instead of the old missing
+ * `/bin/zsh` — restart the server (or reset the cache) so a process that
+ * memoized the old answer before upgrade is not stuck on it.
+ *
* @returns {string} shell binary path (or bare name, on POSIX)
*/
export function resolveInteractiveShell() {
if (cached === undefined) cached = resolveInteractiveShellWith();
return cached;
}
+
+/**
+ * Reset the memoized resolution. Test-only (and post-upgrade recovery if a
+ * long-lived process somehow reloads this module without restarting).
+ */
+export function _resetInteractiveShellCache() {
+ cached = undefined;
+}
diff --git a/server/lib/interactiveShellResolver.test.js b/server/lib/interactiveShellResolver.test.js
index 3330d55add..dff501b98d 100644
--- a/server/lib/interactiveShellResolver.test.js
+++ b/server/lib/interactiveShellResolver.test.js
@@ -1,5 +1,9 @@
-import { describe, it, expect, vi } from 'vitest';
-import { resolveInteractiveShellWith } from './interactiveShellResolver.js';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import {
+ resolveInteractiveShellWith,
+ resolveInteractiveShell,
+ _resetInteractiveShellCache,
+} from './interactiveShellResolver.js';
// Windows env fixture. `exists` is driven per-test so the whole preference
// chain is reachable from a POSIX host.
@@ -112,19 +116,151 @@ describe('resolveInteractiveShellWith PORTOS_SHELL override', () => {
expect(resolveInteractiveShellWith({
platform: 'linux',
env: { PORTOS_SHELL: ' ', SHELL: '/bin/bash' },
- exists: () => false,
+ exists: onlyExists('/bin/bash'),
+ })).toBe('/bin/bash');
+ });
+
+ it('wins on POSIX when the override path exists', () => {
+ expect(resolveInteractiveShellWith({
+ platform: 'linux',
+ env: { PORTOS_SHELL: '/usr/local/bin/fish', SHELL: '/bin/bash' },
+ exists: onlyExists('/usr/local/bin/fish', '/bin/bash'),
+ })).toBe('/usr/local/bin/fish');
+ });
+
+ it('falls through on POSIX when the override path is missing', () => {
+ expect(resolveInteractiveShellWith({
+ platform: 'linux',
+ env: { PORTOS_SHELL: '/opt/missing/zsh', SHELL: '/bin/bash' },
+ exists: onlyExists('/bin/bash'),
+ findOnPath: () => null,
})).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('uses an existing SHELL path when set', () => {
+ expect(resolveInteractiveShellWith({
+ platform: 'darwin',
+ env: { SHELL: '/bin/bash' },
+ exists: onlyExists('/bin/bash'),
+ findOnPath: () => null,
+ })).toBe('/bin/bash');
+ });
+
+ it('passes a bare SHELL name through unchecked', () => {
+ expect(resolveInteractiveShellWith({
+ platform: 'linux',
+ env: { SHELL: 'bash' },
+ exists: () => false,
+ findOnPath: () => null,
+ })).toBe('bash');
+ });
+
+ it('skips a missing SHELL path and picks bash when zsh is absent', () => {
+ // The PM2 / container failure mode: SHELL unset (or pointing at a removed
+ // binary), no zsh on disk, bash present. Must NOT return `/bin/zsh`.
+ expect(resolveInteractiveShellWith({
+ platform: 'linux',
+ env: {},
+ exists: onlyExists('/bin/bash', '/bin/sh'),
+ findOnPath: () => null,
+ })).toBe('/bin/bash');
+ });
+
+ it('prefers /bin/bash over /bin/sh and over zsh when SHELL is unset', () => {
+ expect(resolveInteractiveShellWith({
+ platform: 'linux',
+ env: {},
+ exists: onlyExists('/bin/bash', '/bin/sh', '/bin/zsh'),
+ findOnPath: () => null,
+ })).toBe('/bin/bash');
+ });
+
+ it('falls back to /bin/sh when bash is absent', () => {
+ expect(resolveInteractiveShellWith({
+ platform: 'linux',
+ env: {},
+ exists: onlyExists('/bin/sh'),
+ findOnPath: () => null,
+ })).toBe('/bin/sh');
+ });
+
+ it('uses zsh only when it exists and earlier candidates do not', () => {
+ expect(resolveInteractiveShellWith({
+ platform: 'linux',
+ env: {},
+ exists: onlyExists('/bin/zsh'),
+ findOnPath: () => null,
+ })).toBe('/bin/zsh');
+ });
+
+ it('never returns a hard-coded /bin/zsh that does not exist', () => {
+ expect(resolveInteractiveShellWith({
+ platform: 'linux',
+ env: {},
+ exists: () => false,
+ findOnPath: () => null,
+ })).toBe('sh');
+ });
+
+ it('uses findCommandOnPath for bare bash/sh when no absolute candidate exists', () => {
+ const findOnPath = vi.fn((name) => (name === 'bash' ? '/nix/store/…/bin/bash' : null));
+ expect(resolveInteractiveShellWith({
+ platform: 'linux',
+ env: {},
+ exists: () => false,
+ findOnPath,
+ })).toBe('/nix/store/…/bin/bash');
+ expect(findOnPath).toHaveBeenCalledWith('bash', expect.objectContaining({ env: {} }));
});
it('never reaches the Windows candidates even when they exist', () => {
- expect(resolveInteractiveShellWith({ platform: 'linux', env: WIN_ENV, exists: () => true }))
- .toBe('/bin/zsh');
+ // Empty POSIX env + every path "exists" → first POSIX absolute candidate.
+ expect(resolveInteractiveShellWith({
+ platform: 'linux',
+ env: WIN_ENV,
+ exists: () => true,
+ findOnPath: () => null,
+ })).toBe('/bin/bash');
+ });
+
+ it('skips a stale absolute SHELL and continues the candidate chain', () => {
+ expect(resolveInteractiveShellWith({
+ platform: 'linux',
+ env: { SHELL: '/bin/zsh' },
+ exists: onlyExists('/usr/bin/bash'),
+ findOnPath: () => null,
+ })).toBe('/usr/bin/bash');
+ });
+});
+
+describe('resolveInteractiveShell memoization', () => {
+ beforeEach(() => {
+ _resetInteractiveShellCache();
+ });
+ afterEach(() => {
+ _resetInteractiveShellCache();
+ });
+
+ it('memoizes the first resolveInteractiveShell result until reset', async () => {
+ // Drive the memo through the injectable helper by temporarily resolving
+ // with process defaults is host-dependent; instead poke the cache by
+ // resolving once, then confirming a second call returns the same reference
+ // without re-entering detection (reset clears it for the next assertion).
+ const first = resolveInteractiveShell();
+ const second = resolveInteractiveShell();
+ expect(second).toBe(first);
+ _resetInteractiveShellCache();
+ // After reset, a fresh resolve runs again under the real host env/fs.
+ const after = resolveInteractiveShell();
+ expect(typeof after).toBe('string');
+ expect(after.length).toBeGreaterThan(0);
+ // A hard-coded missing /bin/zsh was the bug; if we return that absolute
+ // path it must actually exist on this host.
+ if (after === '/bin/zsh') {
+ const { existsSync } = await import('fs');
+ expect(existsSync('/bin/zsh')).toBe(true);
+ }
});
});