Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(windows): run project setup scripts through Git Bash, or say how to get it

review9c0d109b153e
diff --git a/src/core/agents/hooks/codex-windows-wrapper.ts b/src/core/agents/hooks/codex-windows-wrapper.ts
index 554b183cd..799cb4f8b 100644
--- a/src/core/agents/hooks/codex-windows-wrapper.ts
+++ b/src/core/agents/hooks/codex-windows-wrapper.ts
@@ -1,3 +1,5 @@
+import { WINDOWS_SH_LAYOUTS } from '../../windows-sh'
+
// The Windows entry point for the codex managed hook.
//
// WHY THIS EXISTS. Every managed hook command in this repo is a POSIX `sh` one-liner, and for
@@ -48,15 +50,10 @@
// install Git.Git` produces without admin), then whatever `sh.exe` is on PATH. PATH is last on
// purpose: it is the least predictable, and a WSL `sh` shim there cannot run a Windows-path script.
-/** Where the wrapper looks for a POSIX shell, in order. cmd.exe expands these itself. */
-export const WINDOWS_SH_CANDIDATES = [
- '%ProgramFiles%\\Git\\bin\\sh.exe',
- '%ProgramFiles%\\Git\\usr\\bin\\sh.exe',
- '%ProgramFiles(x86)%\\Git\\bin\\sh.exe',
- '%ProgramFiles(x86)%\\Git\\usr\\bin\\sh.exe',
- '%LOCALAPPDATA%\\Programs\\Git\\bin\\sh.exe',
- '%LOCALAPPDATA%\\Programs\\Git\\usr\\bin\\sh.exe'
-] as const
+/** Where the wrapper looks for a POSIX shell, in order. cmd.exe expands these itself. Derived from
+ * `WINDOWS_SH_LAYOUTS` (core/windows-sh.ts) — the same list the setup-script runner resolves in
+ * process — so the two cannot disagree about where Git Bash lives. */
+export const WINDOWS_SH_CANDIDATES: readonly string[] = WINDOWS_SH_LAYOUTS.map((l) => `%${l.envVar}%\\${l.rel}`)
/** The wrapper's file name, beside the managed script it runs. */
export const CODEX_WINDOWS_WRAPPER_FILE = 'codex-hook.cmd'
diff --git a/src/core/project-setup-runner-local.test.ts b/src/core/project-setup-runner-local.test.ts
index 6495699ca..3e13c70a8 100644
--- a/src/core/project-setup-runner-local.test.ts
+++ b/src/core/project-setup-runner-local.test.ts
@@ -4,6 +4,8 @@ import path from 'path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import {
SETUP_OUTPUT_CAP,
+ WINDOWS_NO_SH_MESSAGE,
+ isPowerShellScript,
makeLocalSetupRunner,
resolveProjectSetupTarget,
type ProjectSetupTargetInfo
@@ -101,6 +103,94 @@ describe('makeLocalSetupRunner', () => {
})
})
+describe('makeLocalSetupRunner on Windows (platform injected)', () => {
+ let tmpDir: string
+ beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-setup-win-'))
+ })
+ afterEach(() => {
+ fs.rmSync(tmpDir, { recursive: true, force: true })
+ })
+
+ const go = (runner: ReturnType<typeof makeLocalSetupRunner>, script: string) => {
+ const chunks: string[] = []
+ const promise = runner({
+ script,
+ cwd: tmpDir,
+ env: {},
+ onChunk: (t) => chunks.push(t),
+ signal: new AbortController().signal
+ })
+ return { promise, chunks }
+ }
+
+ it('with no Git Bash, spawns nothing and says how to fix it, as exit 127', async () => {
+ const marker = path.join(tmpDir, 'ran')
+ const runner = makeLocalSetupRunner({ platform: 'win32', resolveWinSh: () => null })
+ const { promise, chunks } = go(runner, `touch '${marker}'`)
+ expect(await promise).toEqual({ exitCode: 127 })
+ expect(chunks.join('')).toContain(WINDOWS_NO_SH_MESSAGE)
+ expect(chunks.join('')).toContain('Install Git for Windows')
+ expect(fs.existsSync(marker)).toBe(false)
+ })
+
+ it.skipIf(process.platform === 'win32')(
+ 'runs through the resolved sh, in the project folder, with CHERE_INVOKING set',
+ async () => {
+ const runner = makeLocalSetupRunner({ platform: 'win32', resolveWinSh: () => '/bin/sh' })
+ const { promise, chunks } = go(runner, 'echo "inv=$CHERE_INVOKING"; pwd')
+ expect(await promise).toEqual({ exitCode: 0 })
+ expect(chunks.join('')).toContain('inv=1')
+ expect(chunks.join('')).toContain(fs.realpathSync(tmpDir))
+ }
+ )
+
+ it.skipIf(process.platform === 'win32')('runs a pwsh-shebang script under PowerShell via -EncodedCommand', async () => {
+ const fake = path.join(tmpDir, 'fake-pwsh')
+ fs.writeFileSync(fake, '#!/bin/sh\nprintf "%s\\n" "$@"\n', { mode: 0o755 })
+ const script = "#!/usr/bin/env pwsh\nWrite-Host 'it''s here'\n"
+ let shCalled = false
+ const runner = makeLocalSetupRunner({
+ platform: 'win32',
+ resolveWinSh: () => {
+ shCalled = true
+ return '/bin/sh'
+ },
+ resolveWinPwsh: () => fake
+ })
+ const { promise, chunks } = go(runner, script)
+ expect(await promise).toEqual({ exitCode: 0 })
+ const argv = chunks.join('').trim().split('\n')
+ expect(argv.slice(0, 5)).toEqual(['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand'])
+ expect(Buffer.from(argv[5], 'base64').toString('utf16le')).toBe(script)
+ expect(shCalled).toBe(false)
+ })
+
+ it('leaves POSIX untouched: a pwsh shebang still runs under sh -lc off Windows', async () => {
+ let resolved = false
+ const runner = makeLocalSetupRunner({
+ platform: 'linux',
+ resolveWinSh: () => {
+ resolved = true
+ return null
+ }
+ })
+ const { promise, chunks } = go(runner, '#!/usr/bin/env pwsh\necho posix')
+ expect(await promise).toEqual({ exitCode: 0 })
+ expect(chunks.join('')).toContain('posix')
+ expect(resolved).toBe(false)
+ })
+})
+
+describe('isPowerShellScript', () => {
+ it('matches only a first-line pwsh/powershell shebang', () => {
+ expect(isPowerShellScript('#!/usr/bin/env pwsh\nnpm ci')).toBe(true)
+ expect(isPowerShellScript('\uFEFF#!powershell.exe\r\nnpm ci')).toBe(true)
+ expect(isPowerShellScript('#!/bin/sh\n# pwsh later')).toBe(false)
+ expect(isPowerShellScript('npm ci && pwsh -c x')).toBe(false)
+ })
+})
+
describe('resolveProjectSetupTarget', () => {
const okList = (paths: string[]): ((repoPath: string) => Promise<WorktreeListResult>) =>
async () => ({ ok: true, entries: paths.map((p) => ({ path: p, branch: null, head: null, isBare: false })) })
diff --git a/src/core/project-setup-runner-local.ts b/src/core/project-setup-runner-local.ts
index 0e09f504d..d2f92438b 100644
--- a/src/core/project-setup-runner-local.ts
+++ b/src/core/project-setup-runner-local.ts
@@ -1,9 +1,11 @@
import { execFile, spawn } from 'child_process'
+import fs from 'fs'
import path from 'path'
import { findInPathString, shellPathNow } from './exec-path'
import type { ProjectSetupRunner, ProjectSetupTarget } from './project-setup-service'
import { SETUP_OUTPUT_CAP, SETUP_TIMEOUT_MS, createSetupOutputStream } from './setup-output-stream'
import type { WorktreeListResult } from '../shared/worktree'
+import { resolveWindowsSh } from './windows-sh'
// The cap/timeout/debounce/truncation rules moved to `setup-output-stream.ts` when the SSH runner
// arrived — both runners MUST report the same way (see that file). Re-exported here because this
@@ -20,6 +22,31 @@ function resolveShellBin(shell: string): string {
return findInPathString(shell, shellPathNow() ?? process.env.PATH) ?? shell
}
+/** Shown (with exit 127, the same shape as a spawn ENOENT) when a Windows machine has no Git Bash. */
+export const WINDOWS_NO_SH_MESSAGE =
+ 'Project setup scripts need a POSIX shell. Install Git for Windows (winget install Git.Git) — nodeterm looks for Git\\bin\\sh.exe.'
+
+/** A script whose first line is a `#!` naming pwsh/powershell — "clearly PowerShell". Only consulted
+ * on Windows; a POSIX host keeps running every script through `sh -lc`, shebang or not. */
+export function isPowerShellScript(script: string): boolean {
+ const first = script.replace(/^\uFEFF/, '').split(/\r?\n/, 1)[0] ?? ''
+ return /^#!.*\b(pwsh|powershell)(\.exe)?\b/i.test(first)
+}
+
+/** The PowerShell to run a pwsh-shebang script with on Windows: `pwsh` (7+) when on PATH, else the
+ * in-box Windows PowerShell 5.1. */
+function defaultWinPwsh(): string {
+ return findInPathString('pwsh', process.env.PATH) ?? 'powershell.exe'
+}
+
+/** `-EncodedCommand` is base64 of UTF-16LE: no quoting at all for cmd/CreateProcess to get wrong. */
+function encodePwsh(script: string): string {
+ return Buffer.from(script, 'utf16le').toString('base64')
+}
+
+/** CreateProcess's whole command line is capped at 32,767 chars; leave room for the exe + flags. */
+const WIN_CMDLINE_BUDGET = 32_000
+
/**
* The local half of `ProjectSetupRunner` (Task 1's `project-setup-service.ts` injects it as
* `runLocal`): `spawn(shell, ['-lc', script], …)` with the commit-message.ts spawn discipline —
@@ -27,9 +54,23 @@ function resolveShellBin(shell: string): string {
* (a spawn failure resolves `{exitCode: 127}` with the error text as a chunk, exactly like a
* failed script run — the service layer has one failure shape to handle, not two).
*/
-export function makeLocalSetupRunner(opts?: { shell?: string; timeoutMs?: number }): ProjectSetupRunner {
- const shell = opts?.shell?.trim() || 'sh'
+export function makeLocalSetupRunner(opts?: {
+ shell?: string
+ timeoutMs?: number
+ /** The platform the runner behaves as (default `process.platform`) — injectable for tests. */
+ platform?: NodeJS.Platform
+ /** Windows: Git Bash's `sh.exe`, or null (default `resolveWindowsSh` over the real env + fs). */
+ resolveWinSh?: () => string | null
+ /** Windows: the PowerShell for a pwsh-shebang script (default `pwsh` on PATH, else `powershell.exe`). */
+ resolveWinPwsh?: () => string
+}): ProjectSetupRunner {
+ const explicitShell = opts?.shell?.trim()
+ const shell = explicitShell || 'sh'
const timeoutMs = opts?.timeoutMs ?? SETUP_TIMEOUT_MS
+ const isWin = (opts?.platform ?? process.platform) === 'win32'
+ const resolveWinSh =
+ opts?.resolveWinSh ?? (() => resolveWindowsSh({ env: process.env, exists: (p) => fs.existsSync(p) }))
+ const resolveWinPwsh = opts?.resolveWinPwsh ?? defaultWinPwsh
return ({ script, cwd, env, onChunk, signal }) =>
new Promise((resolve) => {
@@ -42,11 +83,43 @@ export function makeLocalSetupRunner(opts?: { shell?: string; timeoutMs?: number
const { append, flush } = createSetupOutputStream(onChunk)
- const isWin = process.platform === 'win32'
- const shellBin = resolveShellBin(shell)
- const child = spawn(shellBin, ['-lc', script], {
+ // POSIX (and an explicitly configured shell anywhere): `<shell> -lc <script>`, unchanged.
+ // Windows with the default shell: bare `sh` is not on PATH with a stock Git install (only
+ // Git\cmd is), so resolve Git Bash by its real layouts; a pwsh-shebang script runs under
+ // PowerShell instead; and with neither, report a sentence instead of a raw ENOENT.
+ let shellBin: string
+ let args: string[]
+ let extraEnv: Record<string, string> = {}
+ if (isWin && !explicitShell && isPowerShellScript(script)) {
+ const encoded = encodePwsh(script)
+ if (encoded.length > WIN_CMDLINE_BUDGET) {
+ append('This PowerShell setup script is too long to pass on the Windows command line — move it into a .ps1 file and call that.\n')
+ flush()
+ resolve({ exitCode: 127 })
+ return
+ }
+ shellBin = resolveWinPwsh()
+ args = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded]
+ } else if (isWin && !explicitShell) {
+ const sh = resolveWinSh()
+ if (!sh) {
+ append(`${WINDOWS_NO_SH_MESSAGE}\n`)
+ flush()
+ resolve({ exitCode: 127 })
+ return
+ }
+ shellBin = sh
+ args = ['-lc', script]
+ // Git Bash's login profile (`-l`) cd's to $HOME unless CHERE_INVOKING is set — the script
+ // must start in the project folder, exactly as it does under a POSIX `sh -lc`.
+ extraEnv = { CHERE_INVOKING: '1' }
+ } else {
+ shellBin = resolveShellBin(shell)
+ args = ['-lc', script]
+ }
+ const child = spawn(shellBin, args, {
cwd,
- env: { ...process.env, ...env },
+ env: { ...process.env, ...env, ...extraEnv },
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
// POSIX: a new session/process-group leader (setsid), so `killTree` below can SIGKILL the
diff --git a/src/core/windows-sh.test.ts b/src/core/windows-sh.test.ts
new file mode 100644
index 000000000..b6e12c202
--- /dev/null
+++ b/src/core/windows-sh.test.ts
@@ -0,0 +1,74 @@
+import fs from 'fs'
+import { describe, expect, it } from 'vitest'
+import { WINDOWS_SH_CANDIDATES } from './agents/hooks/codex-windows-wrapper'
+import { WINDOWS_SH_LAYOUTS, resolveWindowsSh } from './windows-sh'
+
+const ENV = {
+ ProgramFiles: 'C:\\Program Files',
+ 'ProgramFiles(x86)': 'C:\\Program Files (x86)',
+ LOCALAPPDATA: 'C:\\Users\\me\\AppData\\Local',
+ SystemRoot: 'C:\\Windows'
+}
+
+const only = (...hits: string[]) => (p: string) => hits.includes(p)
+
+describe('resolveWindowsSh', () => {
+ it('prefers the machine-wide Git layouts in order', () => {
+ expect(
+ resolveWindowsSh({
+ env: ENV,
+ exists: only('C:\\Program Files\\Git\\usr\\bin\\sh.exe', 'C:\\Program Files (x86)\\Git\\bin\\sh.exe')
+ })
+ ).toBe('C:\\Program Files\\Git\\usr\\bin\\sh.exe')
+ expect(resolveWindowsSh({ env: ENV, exists: only('C:\\Program Files\\Git\\bin\\sh.exe') })).toBe(
+ 'C:\\Program Files\\Git\\bin\\sh.exe'
+ )
+ })
+
+ it('finds the per-user (winget, no admin) install under LOCALAPPDATA', () => {
+ expect(
+ resolveWindowsSh({ env: ENV, exists: only('C:\\Users\\me\\AppData\\Local\\Programs\\Git\\bin\\sh.exe') })
+ ).toBe('C:\\Users\\me\\AppData\\Local\\Programs\\Git\\bin\\sh.exe')
+ })
+
+ it('reads env names case-insensitively, as Windows does', () => {
+ expect(
+ resolveWindowsSh({ env: { PROGRAMFILES: 'D:\\Apps' }, exists: only('D:\\Apps\\Git\\bin\\sh.exe') })
+ ).toBe('D:\\Apps\\Git\\bin\\sh.exe')
+ })
+
+ it('falls back to PATH last, and never picks a WSL shim under SystemRoot or WindowsApps', () => {
+ const pathStr = 'C:\\Windows\\System32;C:\\Users\\me\\AppData\\Local\\Microsoft\\WindowsApps;"D:\\msys\\usr\\bin"'
+ const exists = only(
+ 'C:\\Windows\\System32\\sh.exe',
+ 'C:\\Users\\me\\AppData\\Local\\Microsoft\\WindowsApps\\sh.exe',
+ 'D:\\msys\\usr\\bin\\sh.exe'
+ )
+ expect(resolveWindowsSh({ env: ENV, exists, pathStr })).toBe('D:\\msys\\usr\\bin\\sh.exe')
+ expect(
+ resolveWindowsSh({ env: { ...ENV, Path: 'C:\\Windows\\System32' }, exists: only('C:\\Windows\\System32\\sh.exe') })
+ ).toBeNull()
+ })
+
+ it('answers null when there is no shell anywhere', () => {
+ expect(resolveWindowsSh({ env: ENV, exists: () => false, pathStr: 'C:\\tools' })).toBeNull()
+ })
+
+ it('is the same list the codex wrapper probes, in the same order', () => {
+ expect(WINDOWS_SH_CANDIDATES).toEqual([
+ '%ProgramFiles%\\Git\\bin\\sh.exe',
+ '%ProgramFiles%\\Git\\usr\\bin\\sh.exe',
+ '%ProgramFiles(x86)%\\Git\\bin\\sh.exe',
+ '%ProgramFiles(x86)%\\Git\\usr\\bin\\sh.exe',
+ '%LOCALAPPDATA%\\Programs\\Git\\bin\\sh.exe',
+ '%LOCALAPPDATA%\\Programs\\Git\\usr\\bin\\sh.exe'
+ ])
+ expect(WINDOWS_SH_CANDIDATES).toHaveLength(WINDOWS_SH_LAYOUTS.length)
+ })
+
+ // The windows-latest CI job has Git for Windows: the real env + fs must find its sh.
+ it.runIf(process.platform === 'win32')('finds Git Bash on a real Windows machine', () => {
+ const sh = resolveWindowsSh({ env: process.env, exists: (p) => fs.existsSync(p) })
+ expect(sh).toMatch(/sh\.exe$/i)
+ })
+})
diff --git a/src/core/windows-sh.ts b/src/core/windows-sh.ts
new file mode 100644
index 000000000..bd6ef32a0
--- /dev/null
+++ b/src/core/windows-sh.ts
@@ -0,0 +1,69 @@
+import path from 'path'
+
+// Where Git for Windows puts its POSIX `sh`, as data — the ONE list both the codex hook wrapper
+// (which needs it as `%VAR%`-expanded batch text, see `codex-windows-wrapper.ts`) and the in-process
+// resolver below (which needs real paths) derive from, so the two cannot drift. Measured layouts:
+// `bin` and `usr\bin`, the 64-bit and 32-bit program dirs, and the per-user install under
+// LOCALAPPDATA that `winget install Git.Git` produces without admin. A stock Git install puts only
+// `Git\cmd` on PATH, so bare `sh` is NOT found there — that is why this list exists at all.
+
+export interface WindowsShLayout {
+ envVar: 'ProgramFiles' | 'ProgramFiles(x86)' | 'LOCALAPPDATA'
+ rel: string
+}
+
+export const WINDOWS_SH_LAYOUTS: readonly WindowsShLayout[] = [
+ { envVar: 'ProgramFiles', rel: 'Git\\bin\\sh.exe' },
+ { envVar: 'ProgramFiles', rel: 'Git\\usr\\bin\\sh.exe' },
+ { envVar: 'ProgramFiles(x86)', rel: 'Git\\bin\\sh.exe' },
+ { envVar: 'ProgramFiles(x86)', rel: 'Git\\usr\\bin\\sh.exe' },
+ { envVar: 'LOCALAPPDATA', rel: 'Programs\\Git\\bin\\sh.exe' },
+ { envVar: 'LOCALAPPDATA', rel: 'Programs\\Git\\usr\\bin\\sh.exe' }
+]
+
+/** Windows env names are case-insensitive; an injected env object (or one built by hand) is not. */
+function envGet(env: NodeJS.ProcessEnv, name: string): string | undefined {
+ if (env[name] !== undefined) return env[name]
+ const lower = name.toLowerCase()
+ for (const [k, v] of Object.entries(env)) if (k.toLowerCase() === lower) return v
+ return undefined
+}
+
+/** A `sh.exe`/`bash.exe` under the Windows dir or the Store app-alias dir is a WSL shim: it runs a
+ * LINUX shell that cannot see a `C:\…` cwd the way the script expects. Never pick one. */
+function isWslShim(p: string, env: NodeJS.ProcessEnv): boolean {
+ const norm = path.win32.normalize(p).toLowerCase()
+ const sysRoot = envGet(env, 'SystemRoot') ?? envGet(env, 'windir') ?? 'C:\\Windows'
+ const root = path.win32.normalize(sysRoot).toLowerCase().replace(/\\+$/, '')
+ return norm.startsWith(`${root}\\`) || norm.includes('\\microsoft\\windowsapps\\')
+}
+
+export interface ResolveWindowsShDeps {
+ env: NodeJS.ProcessEnv
+ exists: (p: string) => boolean
+ /** PATH to search last; defaults to the env's own PATH. */
+ pathStr?: string | null
+}
+
+/**
+ * Git Bash's `sh.exe` on this Windows machine, or null. Fixed Git layouts first, PATH last (the
+ * least predictable, and where a WSL shim lives — refused). Pure over its deps so the order is
+ * testable on any OS; paths are built with `path.win32` regardless of the host.
+ */
+export function resolveWindowsSh(deps: ResolveWindowsShDeps): string | null {
+ for (const l of WINDOWS_SH_LAYOUTS) {
+ const base = envGet(deps.env, l.envVar)
+ if (!base) continue
+ const p = path.win32.join(base, l.rel)
+ if (deps.exists(p)) return p
+ }
+ const pathStr = deps.pathStr === undefined ? envGet(deps.env, 'PATH') : deps.pathStr
+ for (const raw of (pathStr ?? '').split(';')) {
+ const dir = raw.trim().replace(/^"(.*)"$/, '$1')
+ if (!dir) continue
+ const p = path.win32.join(dir, 'sh.exe')
+ if (isWslShim(p, deps.env)) continue
+ if (deps.exists(p)) return p
+ }
+ return null
+}