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(core): resolve executables through PATHEXT on Windows, and stop hardcoding gh's path

Erik Zwep0c3268d36abb
diff --git a/src/core/exec-path.test.ts b/src/core/exec-path.test.ts
new file mode 100644
index 000000000..5d679408c
--- /dev/null
+++ b/src/core/exec-path.test.ts
@@ -0,0 +1,132 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { executableCandidates, findInPathString, unquotePathEntry } from './exec-path'
+
+describe('executableCandidates', () => {
+ it('leaves a bare name alone off win32 — POSIX has no PATHEXT', () => {
+ expect(executableCandidates('gh', 'darwin', undefined)).toEqual(['gh'])
+ expect(executableCandidates('gh', 'linux', '.EXE')).toEqual(['gh'])
+ })
+
+ it('appends PATHEXT on win32, bare name first', () => {
+ // The regression this closes: `gh` on Windows is `gh.exe`, so a bare-name-only walk found
+ // nothing and every caller fell through to its POSIX fallbacks.
+ expect(executableCandidates('gh', 'win32', '.COM;.EXE;.CMD')).toEqual([
+ 'gh',
+ 'gh.COM',
+ 'gh.EXE',
+ 'gh.CMD'
+ ])
+ })
+
+ it('falls back to the stock PATHEXT when the variable is missing or empty', () => {
+ expect(executableCandidates('ssh', 'win32', undefined)).toEqual([
+ 'ssh',
+ 'ssh.COM',
+ 'ssh.EXE',
+ 'ssh.BAT',
+ 'ssh.CMD'
+ ])
+ expect(executableCandidates('ssh', 'win32', '')).toEqual(
+ executableCandidates('ssh', 'win32', undefined)
+ )
+ })
+
+ it('tolerates whitespace and empty entries in PATHEXT', () => {
+ expect(executableCandidates('gh', 'win32', ' .EXE ; ; .CMD ')).toEqual([
+ 'gh',
+ 'gh.EXE',
+ 'gh.CMD'
+ ])
+ })
+
+ it('does not double up on a name that already carries an extension', () => {
+ expect(executableCandidates('gh.exe', 'win32', '.COM;.EXE')).toEqual(['gh.exe'])
+ // Case-insensitively: Windows does not care, and neither should the guard.
+ expect(executableCandidates('claude.CMD', 'win32', '.EXE;.cmd')).toEqual(['claude.CMD'])
+ })
+})
+
+describe('unquotePathEntry', () => {
+ it('strips the quotes Windows tolerates around a PATH entry', () => {
+ expect(unquotePathEntry('"C:\Program Files\GitHub CLI"')).toBe('C:\Program Files\GitHub CLI')
+ })
+
+ it('leaves an unquoted entry and a lone quote untouched', () => {
+ expect(unquotePathEntry('/usr/bin')).toBe('/usr/bin')
+ expect(unquotePathEntry('"C:\half')).toBe('"C:\half')
+ })
+})
+
+// End-to-end over the real filesystem: the unit tests above prove the NAME mapping, these prove the
+// walk actually resolves those names — the half that was broken. Split by platform because the
+// mapping they exercise only exists on one of them.
+describe('findInPathString (real filesystem)', () => {
+ let dir: string
+
+ beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-exec-path-'))
+ })
+ afterEach(() => {
+ fs.rmSync(dir, { recursive: true, force: true })
+ })
+
+ /** POSIX needs the exec bit for X_OK; on Windows the mode is ignored and F_OK is what we ask. */
+ const writeBin = (name: string): string => {
+ const p = path.join(dir, name)
+ fs.writeFileSync(p, '', { mode: 0o755 })
+ return p
+ }
+
+ /** A win32 hit carries PATHEXT's casing (`.EXE`), not the file's own — the same path, since
+ * Windows is case-insensitive. Compare the way the platform does. */
+ const expectPath = (got: string | null, want: string): void => {
+ expect(process.platform === 'win32' ? got?.toLowerCase() : got).toBe(
+ process.platform === 'win32' ? want.toLowerCase() : want
+ )
+ }
+
+ it('finds an executable that is on the PATH, and answers null for one that is not', () => {
+ const bin = process.platform === 'win32' ? 'nt-probe.exe' : 'nt-probe'
+ writeBin(bin)
+ expectPath(findInPathString(process.platform === 'win32' ? 'nt-probe' : bin, dir), path.join(dir, bin))
+ expect(findInPathString('nt-absent', dir)).toBeNull()
+ })
+
+ it('skips empty entries and searches later ones', () => {
+ const bin = process.platform === 'win32' ? 'nt-probe.exe' : 'nt-probe'
+ writeBin(bin)
+ const pathStr = ['', path.join(dir, 'nope'), dir].join(path.delimiter)
+ expectPath(findInPathString(process.platform === 'win32' ? 'nt-probe' : bin, pathStr), path.join(dir, bin))
+ })
+
+ it('tolerates a quoted PATH entry', () => {
+ const bin = process.platform === 'win32' ? 'nt-probe.exe' : 'nt-probe'
+ writeBin(bin)
+ expectPath(
+ findInPathString(process.platform === 'win32' ? 'nt-probe' : bin, `"${dir}"`),
+ path.join(dir, bin)
+ )
+ })
+
+ // The regression itself: a bare name must reach `<name>.exe` / `<name>.cmd` on disk. `gh` really
+ // is `gh.exe` and an npm shim really is `<name>.cmd`, and resolving neither is what left Windows
+ // with no gh, no ssh and a claude probe that never ran.
+ describe.skipIf(process.platform !== 'win32')('win32 PATHEXT', () => {
+ it('resolves a bare name to its .exe and .cmd on disk', () => {
+ writeBin('nt-exe-only.exe')
+ writeBin('nt-cmd-only.cmd')
+ expectPath(findInPathString('nt-exe-only', dir), path.join(dir, 'nt-exe-only.exe'))
+ expectPath(findInPathString('nt-cmd-only', dir), path.join(dir, 'nt-cmd-only.cmd'))
+ })
+
+ it('prefers an extensionless file when one exists, and still finds a name given in full', () => {
+ writeBin('nt-both')
+ writeBin('nt-both.exe')
+ expectPath(findInPathString('nt-both', dir), path.join(dir, 'nt-both'))
+ expectPath(findInPathString('nt-both.exe', dir), path.join(dir, 'nt-both.exe'))
+ })
+ })
+})
diff --git a/src/core/exec-path.ts b/src/core/exec-path.ts
index 841cf0006..c1f2e8c12 100644
--- a/src/core/exec-path.ts
+++ b/src/core/exec-path.ts
@@ -67,17 +67,73 @@ export function shellPathNow(): string | null | undefined {
return cachedShellPath
}
-/** Walk a PATH string for an executable — sync but SUBPROCESS-FREE (one accessSync per entry),
+/** What Windows itself falls back to when PATHEXT is unset or empty. */
+const DEFAULT_PATHEXT = '.COM;.EXE;.BAT;.CMD'
+
+/**
+ * The names a bare `bin` can have ON DISK, in the order Windows itself tries them.
+ *
+ * Windows resolves a bare command against PATHEXT — `gh` on disk is `gh.exe`, `claude` is
+ * `claude.exe`, an npm shim is `<name>.cmd`. Without this a PATH walk finds nothing at all there:
+ * `path.join(dir, 'gh')` names a file that does not exist, and every caller then falls through to
+ * its POSIX fallback list (`/usr/bin/...`), which does not exist either. The result was a silent
+ * `null` for every lookup on Windows — and, downstream, no `gh`, no `ssh`, and a claude
+ * capability probe that never ran.
+ *
+ * The bare name stays FIRST so an extensionless executable still wins where one exists, and a
+ * `bin` that already carries a PATHEXT suffix is returned untouched rather than growing a second
+ * one (`gh.exe.EXE`).
+ *
+ * The extension is appended with PATHEXT's OWN casing, which is conventionally upper case — so a
+ * hit on `gh.exe` comes back as `...\gh.EXE`. That is the same file (Windows paths are
+ * case-insensitive) and every consumer here spawns it rather than comparing it, so the alternative
+ * — a readdir per directory to recover the on-disk spelling — buys nothing and would put I/O on a
+ * function whose whole point is to stay cheap on the main thread.
+ *
+ * `platform` and `pathext` are parameters, not reads of the ambient process, so the mapping is
+ * unit-testable from any OS — the same shape as `tmuxInstall(platform, hasCommand)` next door.
+ */
+export function executableCandidates(
+ bin: string,
+ platform: NodeJS.Platform | string,
+ pathext: string | undefined
+): string[] {
+ if (platform !== 'win32') return [bin]
+ const exts = (pathext || DEFAULT_PATHEXT)
+ .split(';')
+ .map((e) => e.trim())
+ .filter(Boolean)
+ const lower = bin.toLowerCase()
+ if (exts.some((e) => lower.endsWith(e.toLowerCase()))) return [bin]
+ return [bin, ...exts.map((e) => bin + e)]
+}
+
+/** Strip the quotes Windows tolerates around a PATH entry ("C:\Program Files\..."). `where.exe`
+ * strips them before resolving; a quote left in place turns a real directory into a miss. */
+export function unquotePathEntry(entry: string): string {
+ return entry.replace(/^"(.*)"$/, '$1')
+}
+
+/** `X_OK` is meaningless on Windows — Node documents it as degrading to `F_OK` — so the extension
+ * list above, not the executable bit, is what makes a hit real there. Asking for X_OK anyway is
+ * harmless but says something untrue about the check; F_OK says what we actually test. */
+const ACCESS_MODE = os.platform() === 'win32' ? fs.constants.F_OK : fs.constants.X_OK
+
+/** Walk a PATH string for an executable — sync but SUBPROCESS-FREE (one accessSync per candidate),
* so it is safe on the main thread. Returns the first accessible match, or null. */
export function findInPathString(bin: string, pathStr: string | null | undefined): string | null {
- for (const dir of (pathStr ?? '').split(path.delimiter)) {
+ const names = executableCandidates(bin, os.platform(), process.env.PATHEXT)
+ for (const raw of (pathStr ?? '').split(path.delimiter)) {
+ const dir = unquotePathEntry(raw)
if (!dir) continue
- const candidate = path.join(dir, bin)
- try {
- fs.accessSync(candidate, fs.constants.X_OK)
- return candidate
- } catch {
- // not here — keep looking
+ for (const name of names) {
+ const candidate = path.join(dir, name)
+ try {
+ fs.accessSync(candidate, ACCESS_MODE)
+ return candidate
+ } catch {
+ // not here — keep looking
+ }
}
}
return null
@@ -92,7 +148,7 @@ export function findExecutableSync(bin: string, fallbacks: string[] = []): strin
if (hit) return hit
for (const c of fallbacks) {
try {
- fs.accessSync(c, fs.constants.X_OK)
+ fs.accessSync(c, ACCESS_MODE)
return c
} catch {
// keep trying
diff --git a/src/core/git-service.ts b/src/core/git-service.ts
index bd69f2458..1e0d103e7 100644
--- a/src/core/git-service.ts
+++ b/src/core/git-service.ts
@@ -11,6 +11,7 @@ import type { WorktreeListResult } from '../shared/worktree'
import type { GitHistoryOptions, GitHistoryResult } from '../shared/git-history'
import { resolveGitRemote, runRemoteGit } from './remote-ssh/remote-git'
import { platform } from './platform'
+import { findExecutableSync } from './exec-path'
import {
isValidCloneUrl,
expandCloneUrl,
@@ -21,19 +22,33 @@ import {
const run = promisify(execFile)
-function findBin(names: string[]): string | null {
- for (const c of names) {
- try {
- if (fs.existsSync(c)) return c
- } catch {
- // ignore
- }
- }
- return null
+/**
+ * Absolute path to the GitHub CLI, or null when it isn't installed.
+ *
+ * Was a module-level const over three hardcoded POSIX paths, which never consulted PATH at all.
+ * That answered null for EVERY Windows install — `gh` there is `gh.exe`, usually under
+ * `C:\Program Files\GitHub CLI\` — so `ghAvailable` was permanently false and every GitHub
+ * action reported "GitHub CLI (gh) not found." on a machine where gh was installed and authed.
+ *
+ * Now it goes through the shared resolver (login-shell PATH first, then the well-known locations),
+ * and it is MEMOIZED-ON-HIT rather than computed at import: a miss is re-probed, so a gh installed
+ * while the app is running is picked up, and the async login-shell PATH probe that lands after
+ * module load is no longer raced.
+ */
+let cachedGh: string | null | undefined
+function ghPath(): string | null {
+ if (cachedGh) return cachedGh
+ const found = findExecutableSync('gh', [
+ '/opt/homebrew/bin/gh',
+ '/usr/local/bin/gh',
+ '/usr/bin/gh'
+ ])
+ // Only a HIT is cached. Caching a miss here would freeze the answer for the process lifetime,
+ // which is what the old module-level const effectively did.
+ if (found) cachedGh = found
+ return found
}
-const GH_PATH = findBin(['/opt/homebrew/bin/gh', '/usr/local/bin/gh', '/usr/bin/gh'])
-
// GUI apps on macOS don't inherit the shell PATH, so a git credential helper installed by
// Homebrew (e.g. `gh auth git-credential`, or osxkeychain shims) wouldn't be found by our
// `git` subprocess — making push/pull fail even when the user is authed. Prepend the common
@@ -61,14 +76,15 @@ let ghAuthedCache: { value: boolean; at: number } | null = null
let ghAuthedInFlight: Promise<boolean> | null = null
async function ghAuthed(): Promise<boolean> {
- if (!GH_PATH) return false
+ const gh = ghPath()
+ if (!gh) return false
const now = Date.now()
if (ghAuthedCache && now - ghAuthedCache.at < GH_AUTH_TTL_MS) return ghAuthedCache.value
if (ghAuthedInFlight) return ghAuthedInFlight
ghAuthedInFlight = (async () => {
let value = false
try {
- await run(GH_PATH, ['auth', 'status'], { env: GIT_ENV, maxBuffer: 1024 * 1024 })
+ await run(gh, ['auth', 'status'], { env: GIT_ENV, maxBuffer: 1024 * 1024 })
value = true
} catch {
value = false
@@ -88,7 +104,8 @@ async function ghAuthed(): Promise<boolean> {
* call ever (no cache at all) reports `false` while the probe runs; that flips one refresh later.
*/
function ghAuthedSwr(): boolean {
- if (!GH_PATH) return false
+ const gh = ghPath()
+ if (!gh) return false
const fresh = !!ghAuthedCache && Date.now() - ghAuthedCache.at < GH_AUTH_TTL_MS
if (!fresh) void ghAuthed().catch(() => {})
return ghAuthedCache?.value ?? false
@@ -357,7 +374,7 @@ export class GitService {
hasRemote: false,
hasOrigin: false,
hasUpstream: false,
- ghAvailable: !!GH_PATH,
+ ghAvailable: !!ghPath(),
ghAuthed: false,
staged: [],
changes: []
@@ -458,7 +475,7 @@ export class GitService {
hasRemote,
hasOrigin,
hasUpstream,
- ghAvailable: !!GH_PATH,
+ ghAvailable: !!ghPath(),
ghAuthed: gh,
staged,
changes
@@ -795,7 +812,8 @@ export class GitService {
}
async publish(cwd: string, name: string, isPrivate: boolean): Promise<GitResult> {
- if (!GH_PATH) return { ok: false, message: 'GitHub CLI (gh) not found.' }
+ const gh = ghPath()
+ if (!gh) return { ok: false, message: 'GitHub CLI (gh) not found.' }
const repo = (name || '').trim()
// GitHub repo names (optionally `owner/repo`) are limited to these chars and
// must not start with `-`, so gh can't read the value as an option flag.
@@ -815,7 +833,7 @@ export class GitService {
}
try {
await run(
- GH_PATH,
+ gh,
['repo', 'create', repo, isPrivate ? '--private' : '--public', '--source=.', '--push'],
{ cwd, env, maxBuffer: 10 * 1024 * 1024 }
)