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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(windows): execute resolved CLI shims safely
Fabricio Casali34e4826d3dd6
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0c8ce81e7..34df00d72 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -71,4 +71,4 @@ jobs:run: npm run host:build- name: Windows-relevant tests- run: npx vitest run src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/session-host/ src/core/session-host-client.test.ts src/core/session-host-launch-ledger.test.ts src/core/agent-launch.test.ts src/core/pty-session-host.test.ts src/main/bootstrap-windows.test.ts src/main/media-protocol.test.ts src/main/remote-atomic-write.test.ts src/main/ssh-fs.test.ts src/main/remote-ssh/ssh-project.test.ts src/renderer/terminal/file-links.test.ts src/renderer/terminal/file-links.windows.test.ts src/renderer/terminal/file-link-dialect.test.ts src/renderer/terminal/host-platform.test.ts+ run: npx vitest run src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/core/exec-path.test.ts src/core/claude-cli.test.ts src/core/codex-identity-caps.test.ts src/core/grok-cli.test.ts src/core/commit-message.test.ts src/core/context-link.windows.test.ts src/core/git-service.windows.test.ts src/core/usage/codex-usage.windows.test.ts src/session-host/ src/core/session-host-client.test.ts src/core/session-host-launch-ledger.test.ts src/core/agent-launch.test.ts src/core/pty-session-host.test.ts src/main/bootstrap-windows.test.ts src/main/media-protocol.test.ts src/main/remote-atomic-write.test.ts src/main/ssh-fs.test.ts src/main/remote-ssh/ssh-project.test.ts src/renderer/terminal/file-links.test.ts src/renderer/terminal/file-links.windows.test.ts src/renderer/terminal/file-link-dialect.test.ts src/renderer/terminal/host-platform.test.tsdiff --git a/CLAUDE.md b/CLAUDE.mdindex 8e2e3feee..ec2ee7285 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -57,6 +57,16 @@ means — and what you may assume when writing a feature — is three tiers, notfails on any such read that does not. `*.bat`/`*.cmd`/`*.ps1` are the deliberate exception andkeep CRLF: cmd.exe is not reliably tolerant of LF, and those are the files a Windows contributorruns before anything else works.+- **PATH resolution and direct execution are separate on Windows.** `findInPathString` correctly+ follows `PATHEXT`, which means an npm-installed CLI may resolve to `<name>.cmd`; Node's+ `execFile`/`spawn` still cannot execute that path directly (`spawn EINVAL`). App-owned+ subprocesses must pass their resolved executable and argv through `directExecutableInvocation`+ (`src/core/exec-path.ts`), which maps an npm `.cmd` to its equivalent sibling `.ps1` and invokes+ it with PowerShell `-File`. The argv remains structured all the way through — never replace this+ with `shell:true`, because commit prompts and other user-controlled arguments would then be+ reinterpreted as shell syntax. A `.bat` has no npm sibling contract and fails closed. This helper+ is for subprocess calls; interactive terminal agent launches keep using `agent-launch.ts`'s+ separately tested shell plan.## Commandsdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex a6878fd22..d411791be 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -178,6 +178,14 @@ lane unaffected.sees the pane app's own bytes — see CLAUDE.md's "We have our own VT emulator" for the one placethat reasoning is inverted.+- **Finding a Windows executable is not the same as being able to spawn it.** A PATH lookup may+ correctly resolve an npm CLI to `<name>.cmd`, but Node's `execFile`/`spawn` cannot execute that+ shim directly. For short-lived app-owned subprocesses, pass the resolved path and argv through+ `directExecutableInvocation` (`src/core/exec-path.ts`): it uses npm's sibling `.ps1` shim via+ PowerShell `-File`, preserving the argv boundary. Do not fix this with `shell: true`; prompts and+ other user-controlled arguments would become shell syntax. A `.bat` file has no equivalent safe+ entry point and must fail explicitly.+- **Normalize BOTH sides of a path comparison, through one function.** A marker normalized whereit is built and matched raw where it is used is a no-op on the machine you wrote it on and asilent defect on Windows. That is issue #558: the managed-hook marker was folded to `/` whilediff --git a/src/core/claude-cli.test.ts b/src/core/claude-cli.test.tsindex 81ec3dbf0..b0ca949d3 100644--- a/src/core/claude-cli.test.ts+++ b/src/core/claude-cli.test.ts@@ -1,5 +1,8 @@-import { describe, it, expect } from 'vitest'-import { claudeCliCapsFrom, UNKNOWN_CLAUDE_CLI_CAPS } from './claude-cli'+import { afterEach, beforeEach, describe, it, expect } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { claudeCliCapsFrom, probeClaudeCliAt, UNKNOWN_CLAUDE_CLI_CAPS } from './claude-cli'describe('claudeCliCapsFrom', () => {it('reads a real `claude --version` line', () => {@@ -88,3 +91,34 @@ Options:expect(c.autoPermissionMode).toBe(false)})})++describe.skipIf(process.platform !== 'win32')('probeClaudeCliAt — Windows npm shim', () => {+ let dir: string++ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-claude-shim-'))+ })+ afterEach(() => {+ fs.rmSync(dir, { recursive: true, force: true })+ })++ it('probes a .cmd CLI through its sibling .ps1 entry point', async () => {+ const cmd = path.join(dir, 'claude.cmd')+ fs.writeFileSync(cmd, '@echo off\r\nexit /b 91\r\n')+ fs.writeFileSync(+ path.join(dir, 'claude.ps1'),+ [+ "if ($args[0] -eq '--version') { Write-Output '2.1.226 (Claude Code)'; exit 0 }",+ "if ($args[0] -eq '--help') { Write-Output ' --session-id <uuid>'; exit 0 }",+ 'exit 92'+ ].join('\r\n')+ )++ expect(await probeClaudeCliAt(cmd)).toEqual({+ version: '2.1.226 (Claude Code)',+ autoPermissionMode: true,+ fullscreenTui: true,+ sessionIdFlag: true+ })+ })+})diff --git a/src/core/claude-cli.ts b/src/core/claude-cli.tsindex a5ba82193..b58073c6d 100644--- a/src/core/claude-cli.ts+++ b/src/core/claude-cli.ts@@ -10,6 +10,7 @@ import { promisify } from 'util'import { supportsAutoPermissionMode, supportsFullscreenTui } from '../shared/agents/config'import { IPC } from '../shared/ipc'import { UNKNOWN_CLAUDE_CLI_CAPS, type ClaudeCliCaps } from '../shared/types'+import { directExecutableInvocation } from './exec-path'import { findInLoginPath } from './pty-manager'import { platform } from './platform'@@ -42,21 +43,24 @@ export function claudeCliCapsFrom(}}-let cached: Promise<ClaudeCliCaps> | null = null--async function probe(): Promise<ClaudeCliCaps> {+export async function probeClaudeCliAt(bin: string): Promise<ClaudeCliCaps> {try {- // GUI apps don't inherit the shell PATH — resolve through the login shell like every other- // CLI lookup in the app (pty-manager, commit-message).- const bin = await findInLoginPath('claude')- if (!bin) return UNKNOWN_CLAUDE_CLI_CAPS- const { stdout } = await execFileP(bin, ['--version'], { timeout: PROBE_TIMEOUT_MS })+ const versionInvocation = directExecutableInvocation(bin, ['--version'])+ if (!versionInvocation) return UNKNOWN_CLAUDE_CLI_CAPS+ const { stdout } = await execFileP(versionInvocation.executable, versionInvocation.args, {+ timeout: PROBE_TIMEOUT_MS+ })// `--help` is a second spawn, paid once per process (this whole probe is memoized). Its// failure must not cost us the version answer, so it degrades on its own: no help text just// means no minted session ids.- const help = await execFileP(bin, ['--help'], { timeout: PROBE_TIMEOUT_MS })- .then((r) => r.stdout)- .catch(() => null)+ const helpInvocation = directExecutableInvocation(bin, ['--help'])+ const help = helpInvocation+ ? await execFileP(helpInvocation.executable, helpInvocation.args, {+ timeout: PROBE_TIMEOUT_MS+ })+ .then((r) => r.stdout)+ .catch(() => null)+ : nullreturn claudeCliCapsFrom(stdout, help)} catch {// Missing CLI, timeout, non-zero exit — all mean "unknown", which means "omit the flag".@@ -64,6 +68,16 @@ async function probe(): Promise<ClaudeCliCaps> {}}+let cached: Promise<ClaudeCliCaps> | null = null++async function probe(): Promise<ClaudeCliCaps> {+ // GUI apps don't inherit the shell PATH — resolve through the login shell like every other+ // CLI lookup in the app (pty-manager, commit-message).+ const bin = await findInLoginPath('claude')+ if (!bin) return UNKNOWN_CLAUDE_CLI_CAPS+ return probeClaudeCliAt(bin)+}+/*** The local Claude CLI's capabilities. Memoized for the process lifetime: `claude --version`* spawns a login shell + node, and the answer only changes when the user upgrades the CLI (which adiff --git a/src/core/codex-identity-caps.test.ts b/src/core/codex-identity-caps.test.tsindex df01bab2f..bc910e08d 100644--- a/src/core/codex-identity-caps.test.ts+++ b/src/core/codex-identity-caps.test.ts@@ -8,6 +8,7 @@ import {codexIdentityCaps,codexManagedRuntimeInstalled,codexManagedRuntimePath,+ probeCodexRemoteFlagAt,refreshCodexIdentityCaps,resetCodexIdentityCapsForTests} from './codex-identity-caps'@@ -164,18 +165,22 @@ describe('codexManagedRuntimeInstalled', () => {)})- it('answers yes only for an executable runtime at that path', () => {- // An npm install has ~/.codex (auth, config, sessions) and no `packages/` at all — which is- // exactly the shape measured on the machine this fix was written on.- expect(codexManagedRuntimeInstalled(dir)).toBe(false)- const runtime = codexManagedRuntimePath(dir)- fs.mkdirSync(path.dirname(runtime), { recursive: true })- fs.writeFileSync(runtime, '#!/bin/sh\nexit 0\n', { mode: 0o644 })- // Present but not executable is not a runtime the daemon can exec, so it is still no.- expect(codexManagedRuntimeInstalled(dir)).toBe(false)- fs.chmodSync(runtime, 0o755)- expect(codexManagedRuntimeInstalled(dir)).toBe(true)- })+ it.skipIf(process.platform === 'win32')(+ 'answers yes only for an executable runtime at that path',+ () => {+ // An npm install has ~/.codex (auth, config, sessions) and no `packages/` at all — which is+ // exactly the shape measured on the machine this fix was written on.+ // Windows ignores the executable bit, so `X_OK` cannot distinguish the two fixture modes.+ expect(codexManagedRuntimeInstalled(dir)).toBe(false)+ const runtime = codexManagedRuntimePath(dir)+ fs.mkdirSync(path.dirname(runtime), { recursive: true })+ fs.writeFileSync(runtime, '#!/bin/sh\nexit 0\n', { mode: 0o644 })+ // Present but not executable is not a runtime the daemon can exec, so it is still no.+ expect(codexManagedRuntimeInstalled(dir)).toBe(false)+ fs.chmodSync(runtime, 0o755)+ expect(codexManagedRuntimeInstalled(dir)).toBe(true)+ }+ )})describe('codexCliSupportsRemote', () => {@@ -193,3 +198,20 @@ describe('codexCliSupportsRemote', () => {expect(codexCliSupportsRemote('no flags here', ' --remote <URL>')).toBe(true)})})++describe.skipIf(process.platform !== 'win32')('probeCodexRemoteFlagAt — Windows npm shim', () => {+ it('uses the sibling PowerShell shim for both help probes', async () => {+ const cmd = path.join(dir, 'codex.cmd')+ fs.writeFileSync(cmd, '@echo off\r\nexit /b 91\r\n')+ fs.writeFileSync(+ path.join(dir, 'codex.ps1'),+ [+ "if ($args.Count -eq 1 -and $args[0] -eq '--help') { Write-Output 'no flag'; exit 0 }",+ "if ($args[0] -eq 'resume' -and $args[1] -eq '--help') { Write-Output ' --remote <URL>'; exit 0 }",+ 'exit 92'+ ].join('\r\n')+ )++ await expect(probeCodexRemoteFlagAt(cmd)).resolves.toBe(true)+ })+})diff --git a/src/core/codex-identity-caps.ts b/src/core/codex-identity-caps.tsindex 26116c811..429d7805a 100644--- a/src/core/codex-identity-caps.ts+++ b/src/core/codex-identity-caps.ts@@ -46,6 +46,7 @@ import { accessSync, constants } from 'fs'import path from 'path'import { promisify } from 'util'import { IPC } from '../shared/ipc'+import { directExecutableInvocation } from './exec-path'import { platform } from './platform'import { type CodexIdentityCaps } from '../shared/types'import { installCodexLauncher, codexThreadIdentityAvailable } from './codex-identity-proxy'@@ -115,21 +116,27 @@ export function codexCliSupportsRemote(...helpOutputs: Array<string | null | undreturn helpOutputs.some((h) => /(^|\s)--remote(\s|=|$)/m.test(h ?? ''))}-async function probeRemoteFlag(): Promise<boolean> {+export async function probeCodexRemoteFlagAt(bin: string): Promise<boolean> {try {- // GUI apps don't inherit the shell PATH — resolve through the login shell like every other- // CLI lookup in the app (pty-manager, claude-cli, commit-message).- const bin = await findInLoginPath('codex')- if (!bin) return false- const help = await execFileP(bin, ['--help'], { timeout: PROBE_TIMEOUT_MS })- .then((r) => r.stdout)- .catch(() => null)+ const helpInvocation = directExecutableInvocation(bin, ['--help'])+ const help = helpInvocation+ ? await execFileP(helpInvocation.executable, helpInvocation.args, {+ timeout: PROBE_TIMEOUT_MS+ })+ .then((r) => r.stdout)+ .catch(() => null)+ : nullif (codexCliSupportsRemote(help)) return true// Some CLIs list a global flag only under the subcommand that takes it. One extra spawn, paid// once per app run and only when the top-level help did not already answer yes.- const resumeHelp = await execFileP(bin, ['resume', '--help'], { timeout: PROBE_TIMEOUT_MS })- .then((r) => r.stdout)- .catch(() => null)+ const resumeInvocation = directExecutableInvocation(bin, ['resume', '--help'])+ const resumeHelp = resumeInvocation+ ? await execFileP(resumeInvocation.executable, resumeInvocation.args, {+ timeout: PROBE_TIMEOUT_MS+ })+ .then((r) => r.stdout)+ .catch(() => null)+ : nullreturn codexCliSupportsRemote(resumeHelp)} catch {// Missing CLI, timeout, non-zero exit — all mean "unknown", which means "no shared identity".@@ -137,6 +144,13 @@ async function probeRemoteFlag(): Promise<boolean> {}}+async function probeRemoteFlag(): Promise<boolean> {+ // GUI apps don't inherit the shell PATH — resolve through the login shell like every other+ // CLI lookup in the app (pty-manager, claude-cli, commit-message).+ const bin = await findInLoginPath('codex')+ return bin ? probeCodexRemoteFlagAt(bin) : false+}+let latest: CodexIdentityCaps | null = nulllet ready: Promise<CodexIdentityCaps> | null = nulllet announce: ((c: CodexIdentityCaps) => void) | null = nulldiff --git a/src/core/commit-message.test.ts b/src/core/commit-message.test.tsindex 25776b0f6..c712741f5 100644--- a/src/core/commit-message.test.ts+++ b/src/core/commit-message.test.ts@@ -135,3 +135,43 @@ describe('resolveBinary', () => {expect(resolveBinary('nt-definitely-not-installed')).toBeNull()})})++describe.skipIf(process.platform !== 'win32')('runAgent — Windows npm shim', () => {+ let dir: string++ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-commit-shim-'))+ })+ afterEach(() => {+ fs.rmSync(dir, { recursive: true, force: true })+ })++ it('keeps a hostile prompt as one argument without invoking cmd.exe', async () => {+ const cmd = path.join(dir, 'fake agent.cmd')+ const touched = path.join(dir, 'should-not-exist.txt')+ fs.writeFileSync(cmd, '@echo off\r\nexit /b 91\r\n')+ fs.writeFileSync(+ path.join(dir, 'fake agent.ps1'),+ [+ '$bytes = [Text.Encoding]::UTF8.GetBytes($args[0])',+ '[Console]::Out.Write([Convert]::ToBase64String($bytes))'+ ].join('\r\n')+ )+ const prompt = `message & echo pwned > "${touched}"`++ vi.resetModules()+ vi.doUnmock('child_process')+ const { runAgent } = await import('./commit-message')+ const result = await runAgent(prompt, dir, {+ commitAgent: 'custom',+ commitAgentCommand: `"${cmd}" "{prompt}"`,+ commitExtraPrompt: ''+ } as never)++ expect(result).toEqual({+ ok: true,+ message: Buffer.from(prompt, 'utf8').toString('base64')+ })+ expect(fs.existsSync(touched)).toBe(false)+ })+})diff --git a/src/core/commit-message.ts b/src/core/commit-message.tsindex 7d929b79d..ae1448d56 100644--- a/src/core/commit-message.ts+++ b/src/core/commit-message.ts@@ -4,7 +4,7 @@ import os from 'os'import path from 'path'import { promisify } from 'util'import type { GitResult, Settings } from '../shared/types'-import { findInPathString, shellPathNow } from './exec-path'+import { directExecutableInvocation, findInPathString, shellPathNow } from './exec-path'import { resolveGitRemote, runRemoteGit } from './remote-ssh/remote-git'const run = promisify(execFile)@@ -179,7 +179,13 @@ function spawnAgent(stdin: string | null): Promise<{ code: number; stdout: string; stderr: string }> {return new Promise((resolve) => {- const child = spawn(bin, args, {+ const invocation = directExecutableInvocation(bin, args)+ if (!invocation) {+ resolve({ code: 1, stdout: '', stderr: `Cannot safely execute Windows script: ${bin}` })+ return+ }++ const child = spawn(invocation.executable, invocation.args, {cwd,env: process.env,stdio: ['pipe', 'pipe', 'pipe'],diff --git a/src/core/context-link.ts b/src/core/context-link.tsindex 61af8b40c..8104815dc 100644--- a/src/core/context-link.ts+++ b/src/core/context-link.ts@@ -21,6 +21,7 @@ import { platform } from './platform'import { IPC } from '../shared/ipc'import type { ContextLinkMap } from '../shared/types'import { type PtyManager } from './pty-manager'+import { directExecutableInvocation, findInLoginPath } from './exec-path'import { TMUX_SOCKET } from './tmux-naming'import {buildContextShimScript,@@ -202,18 +203,17 @@ async function fetchTranscript(node: LinkDocEntry): Promise<string | null> {}}-async function fetchOpencodeExport(node: LinkDocEntry): Promise<string | null> {- if (!node.sessionId) return null- if (deps.isRemoteNode?.(node.id)) {- return deps.runRemoteCommand- ? await deps.runRemoteCommand(node.id, `opencode export ${shellQuote(node.sessionId)}`)- : null- }+export async function opencodeExportAt(bin: string, sessionId: string): Promise<string | null> {+ const invocation = directExecutableInvocation(bin, ['export', sessionId])+ if (!invocation) return nulltry {const { execFile } = await import('node:child_process')return await new Promise<string | null>((resolve) => {- execFile('opencode', ['export', node.sessionId ?? ''], { encoding: 'utf-8' }, (err, stdout) =>- resolve(err ? null : stdout)+ execFile(+ invocation.executable,+ invocation.args,+ { encoding: 'utf-8' },+ (err, stdout) => resolve(err ? null : stdout))})} catch {@@ -221,6 +221,17 @@ async function fetchOpencodeExport(node: LinkDocEntry): Promise<string | null> {}}+async function fetchOpencodeExport(node: LinkDocEntry): Promise<string | null> {+ if (!node.sessionId) return null+ if (deps.isRemoteNode?.(node.id)) {+ return deps.runRemoteCommand+ ? await deps.runRemoteCommand(node.id, `opencode export ${shellQuote(node.sessionId)}`)+ : null+ }+ const bin = await findInLoginPath('opencode')+ return bin ? opencodeExportAt(bin, node.sessionId) : null+}+/** Single-quote for a POSIX shell. The session id reaches a remote command line, and it is* ultimately provider-supplied data — never interpolate it raw. */function shellQuote(s: string): string {diff --git a/src/core/context-link.windows.test.ts b/src/core/context-link.windows.test.tsnew file mode 100644index 000000000..df86db0e4--- /dev/null+++ b/src/core/context-link.windows.test.ts@@ -0,0 +1,30 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { opencodeExportAt } from './context-link'++describe.skipIf(process.platform !== 'win32')('opencodeExportAt - Windows npm shim', () => {+ let dir: string++ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-opencode-shim-'))+ })++ afterEach(() => {+ fs.rmSync(dir, { recursive: true, force: true })+ })++ it('runs the sibling PowerShell shim without interpreting the session id', async () => {+ const cmd = path.join(dir, 'opencode.cmd')+ fs.writeFileSync(cmd, '@exit /b 99\r\n')+ fs.writeFileSync(+ path.join(dir, 'opencode.ps1'),+ '[Console]::Out.Write(($args | ConvertTo-Json -Compress))\n'+ )++ const sessionId = 'session & untouched'+ const output = await opencodeExportAt(cmd, sessionId)+ expect(JSON.parse(output ?? 'null')).toEqual(['export', sessionId])+ })+})diff --git a/src/core/exec-path.test.ts b/src/core/exec-path.test.tsindex 88350d58e..42b240fd1 100644--- a/src/core/exec-path.test.ts+++ b/src/core/exec-path.test.ts@@ -2,7 +2,12 @@ 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'+import {+ directExecutableInvocation,+ executableCandidates,+ findInPathString,+ unquotePathEntry+} from './exec-path'describe('executableCandidates', () => {it('leaves a bare name alone off win32 — POSIX has no PATHEXT', () => {@@ -61,6 +66,65 @@ describe('unquotePathEntry', () => {})})+describe('directExecutableInvocation', () => {+ const systemRoot = 'C:\\Windows'+ const powershell = `${systemRoot}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`++ it('leaves native and non-Windows executables unchanged', () => {+ expect(+ directExecutableInvocation('C:\\Tools\\agent.exe', ['--version'], {+ platform: 'win32',+ systemRoot,+ exists: () => false+ })+ ).toEqual({ executable: 'C:\\Tools\\agent.exe', args: ['--version'] })+ expect(+ directExecutableInvocation('/usr/bin/agent.cmd', ['--version'], { platform: 'linux' })+ ).toEqual({ executable: '/usr/bin/agent.cmd', args: ['--version'] })+ })++ it('runs a Windows npm cmd shim through its sibling PowerShell shim', () => {+ const existing = new Set([powershell.toLowerCase(), 'c:\\tools\\agent.ps1'])+ expect(+ directExecutableInvocation('C:\\Tools\\agent.CMD', ['--flag', 'value & untouched'], {+ platform: 'win32',+ systemRoot,+ exists: (candidate) => existing.has(candidate.toLowerCase())+ })+ ).toEqual({+ executable: powershell,+ args: [+ '-NoLogo',+ '-NoProfile',+ '-NonInteractive',+ '-ExecutionPolicy',+ 'Bypass',+ '-File',+ 'C:\\Tools\\agent.ps1',+ '--flag',+ 'value & untouched'+ ]+ })+ })++ it('fails closed when a Windows script has no safe direct entry point', () => {+ expect(+ directExecutableInvocation('C:\\Tools\\agent.cmd', [], {+ platform: 'win32',+ systemRoot,+ exists: (candidate) => candidate.toLowerCase() === powershell.toLowerCase()+ })+ ).toBeNull()+ expect(+ directExecutableInvocation('C:\\Tools\\agent.bat', [], {+ platform: 'win32',+ systemRoot,+ exists: () => true+ })+ ).toBeNull()+ })+})+// 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.diff --git a/src/core/exec-path.ts b/src/core/exec-path.tsindex 4aa8fc362..d5b0b7f09 100644--- a/src/core/exec-path.ts+++ b/src/core/exec-path.ts@@ -107,6 +107,12 @@ export function shellPathNow(): string | null | undefined {return cachedShellPath}+/** Resolve an executable against the user's real login-shell PATH, returning its absolute path. */+export async function findInLoginPath(bin: string): Promise<string | null> {+ const shellPath = (await resolveShellPath()) ?? process.env.PATH ?? ''+ return findInPathString(bin, shellPath)+}+/** What Windows itself falls back to when PATHEXT is unset or empty. */const DEFAULT_PATHEXT = '.COM;.EXE;.BAT;.CMD'@@ -183,6 +189,63 @@ export function findInPathString(bin: string, pathStr: string | null | undefinedreturn null}+export interface DirectExecutableInvocation {+ executable: string+ args: string[]+}++interface DirectExecutableInvocationOptions {+ platform?: NodeJS.Platform+ systemRoot?: string+ exists?: (candidate: string) => boolean+}++/**+ * Builds an argv-safe invocation for a resolved executable. Node cannot execute Windows npm+ * `.cmd` shims directly, and using a shell would reinterpret user-controlled arguments. npm+ * installs an equivalent sibling `.ps1` shim, so run that through PowerShell's `-File` boundary.+ */+export function directExecutableInvocation(+ executable: string,+ args: string[],+ options: DirectExecutableInvocationOptions = {}+): DirectExecutableInvocation | null {+ const platform = options.platform ?? os.platform()+ if (platform !== 'win32') return { executable, args }++ const ext = path.win32.extname(executable).toLowerCase()+ if (ext === '.bat') return null+ if (ext !== '.cmd' && ext !== '.ps1') return { executable, args }++ const script = ext === '.ps1' ? executable : `${executable.slice(0, -ext.length)}.ps1`+ const systemRoot = options.systemRoot ?? process.env.SystemRoot+ if (!systemRoot) return null++ const powershell = path.win32.join(+ systemRoot,+ 'System32',+ 'WindowsPowerShell',+ 'v1.0',+ 'powershell.exe'+ )+ const exists = options.exists ?? fs.existsSync+ if (!exists(powershell) || !exists(script)) return null++ return {+ executable: powershell,+ args: [+ '-NoLogo',+ '-NoProfile',+ '-NonInteractive',+ '-ExecutionPolicy',+ 'Bypass',+ '-File',+ script,+ ...args+ ]+ }+}+/*** Resolve `bin` against the cached login-shell PATH (falling back to the inherited PATH while* the probe is in flight), then against the caller's well-known locations. Never spawns.diff --git a/src/core/git-service.ts b/src/core/git-service.tsindex cc0d65f9e..ff1e85be3 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 { directExecutableInvocation } from './exec-path'import { ghPath } from './gh-path'import { gitEnv } from './git-env'import {@@ -29,6 +30,11 @@ const run = promisify(execFile)// (issue #583) — live in git-env.ts, which github/credentials.ts imports as well.const GIT_ENV: NodeJS.ProcessEnv = gitEnv()+function ghInvocation(args: string[]): ReturnType<typeof directExecutableInvocation> {+ const gh = ghPath()+ return gh ? directExecutableInvocation(gh, args) : null+}+// Single-flight registry for the one clone the app runs at a time. Module-scoped so a// macOS window re-creation can't orphan it.type ActiveClone = {@@ -45,15 +51,15 @@ let ghAuthedCache: { value: boolean; at: number } | null = nulllet ghAuthedInFlight: Promise<boolean> | null = nullasync function ghAuthed(): Promise<boolean> {- const gh = ghPath()- if (!gh) return false+ const invocation = ghInvocation(['auth', 'status'])+ if (!invocation) return falseconst now = Date.now()if (ghAuthedCache && now - ghAuthedCache.at < GH_AUTH_TTL_MS) return ghAuthedCache.valueif (ghAuthedInFlight) return ghAuthedInFlightghAuthedInFlight = (async () => {let value = falsetry {- await run(gh, ['auth', 'status'], { env: GIT_ENV, maxBuffer: 1024 * 1024 })+ await run(invocation.executable, invocation.args, { env: GIT_ENV, maxBuffer: 1024 * 1024 })value = true} catch {value = false@@ -73,8 +79,7 @@ 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 {- const gh = ghPath()- if (!gh) return false+ if (!ghInvocation([])) return falseconst fresh = !!ghAuthedCache && Date.now() - ghAuthedCache.at < GH_AUTH_TTL_MSif (!fresh) void ghAuthed().catch(() => {})return ghAuthedCache?.value ?? false@@ -343,7 +348,7 @@ export class GitService {hasRemote: false,hasOrigin: false,hasUpstream: false,- ghAvailable: !!ghPath(),+ ghAvailable: !!ghInvocation([]),ghAuthed: false,staged: [],changes: []@@ -444,7 +449,7 @@ export class GitService {hasRemote,hasOrigin,hasUpstream,- ghAvailable: !!ghPath(),+ ghAvailable: !!ghInvocation([]),ghAuthed: gh,staged,changes@@ -781,14 +786,21 @@ export class GitService {}async publish(cwd: string, name: string, isPrivate: boolean): Promise<GitResult> {- 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.if (!repo || repo.startsWith('-') || !/^[A-Za-z0-9._/-]+$/.test(repo)) {return { ok: false, message: 'Invalid repository name.' }}+ const invocation = ghInvocation([+ 'repo',+ 'create',+ repo,+ isPrivate ? '--private' : '--public',+ '--source=.',+ '--push'+ ])+ if (!invocation) return { ok: false, message: 'GitHub CLI (gh) not found.' }// Prefer gh's own login; otherwise reuse the user's existing git HTTPS token// (the one that already lets them push) so publishing doesn't demand a separate// `gh auth login`. If neither is available, signal the UI to start a login.@@ -801,11 +813,7 @@ export class GitService {env.GH_TOKEN = token}try {- await run(- gh,- ['repo', 'create', repo, isPrivate ? '--private' : '--public', '--source=.', '--push'],- { cwd, env, maxBuffer: 10 * 1024 * 1024 }- )+ await run(invocation.executable, invocation.args, { cwd, env, maxBuffer: 10 * 1024 * 1024 })return { ok: true, message: 'Published to GitHub.' }} catch (e) {const err = e as { stderr?: string; message?: string }diff --git a/src/core/git-service.windows.test.ts b/src/core/git-service.windows.test.tsnew file mode 100644index 000000000..1086d99c7--- /dev/null+++ b/src/core/git-service.windows.test.ts@@ -0,0 +1,68 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'++describe.skipIf(process.platform !== 'win32')('GitService - Windows npm gh shim', () => {+ let dir: string+ let originalPath: string | undefined+ let originalPathext: string | undefined+ let originalCapture: string | undefined++ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-gh-shim-'))+ originalPath = process.env.PATH+ originalPathext = process.env.PATHEXT+ originalCapture = process.env.NT_GH_CAPTURE+ })++ afterEach(() => {+ if (originalPath === undefined) delete process.env.PATH+ else process.env.PATH = originalPath+ if (originalPathext === undefined) delete process.env.PATHEXT+ else process.env.PATHEXT = originalPathext+ if (originalCapture === undefined) delete process.env.NT_GH_CAPTURE+ else process.env.NT_GH_CAPTURE = originalCapture+ fs.rmSync(dir, { recursive: true, force: true })+ vi.resetModules()+ })++ it('publishes through the PowerShell sibling with the original Windows PATH', async () => {+ const capture = path.join(dir, 'gh-call.json')+ fs.writeFileSync(path.join(dir, 'gh.cmd'), '@exit /b 99\r\n')+ fs.writeFileSync(+ path.join(dir, 'gh.ps1'),+ [+ "if ($args[0] -eq 'repo') {",+ " [IO.File]::WriteAllText($env:NT_GH_CAPTURE, (@{ args = @($args); path = $env:PATH } | ConvertTo-Json -Compress))",+ '}',+ 'exit 0'+ ].join('\r\n')+ )+ const expectedPath = `${dir};${originalPath ?? ''}`+ process.env.PATH = expectedPath+ process.env.PATHEXT = '.EXE;.CMD'+ process.env.NT_GH_CAPTURE = capture++ vi.resetModules()+ const { GitService } = await import('./git-service')+ await expect(new GitService().publish(dir, 'owner/repo', true)).resolves.toEqual({+ ok: true,+ message: 'Published to GitHub.'+ })++ const recorded = JSON.parse(fs.readFileSync(capture, 'utf8')) as {+ args: string[]+ path: string+ }+ expect(recorded.args).toEqual([+ 'repo',+ 'create',+ 'owner/repo',+ '--private',+ '--source=.',+ '--push'+ ])+ expect(recorded.path).toBe(expectedPath)+ })+})diff --git a/src/core/grok-cli.test.ts b/src/core/grok-cli.test.tsindex 330a02d33..66357fa68 100644--- a/src/core/grok-cli.test.ts+++ b/src/core/grok-cli.test.ts@@ -1,5 +1,8 @@import { describe, it, expect } from 'vitest'-import { grokCapsFromRunner, grokCliCapsFrom, UNKNOWN_GROK_CLI_CAPS } from './grok-cli'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { grokCapsFromRunner, grokCliCapsFrom, probeGrokCliAt, UNKNOWN_GROK_CLI_CAPS } from './grok-cli'// Verbatim from `grok --help` on 1.0.13 (2026-09-02). The two lines matter for opposite reasons:// the first DEFINES the flag, the second only MENTIONS it inside another option's prose.@@ -90,3 +93,22 @@ describe('grokCapsFromRunner — both subcommands are actually asked', () => {expect(await grokCapsFromRunner(async () => null)).toEqual(UNKNOWN_GROK_CLI_CAPS)})})++describe.skipIf(process.platform !== 'win32')('probeGrokCliAt — Windows npm shim', () => {+ it('probes through the sibling PowerShell shim', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-grok-shim-'))+ try {+ const cmd = path.join(dir, 'grok.cmd')+ fs.writeFileSync(cmd, '@echo off\r\nexit /b 91\r\n')+ fs.writeFileSync(+ path.join(dir, 'grok.ps1'),+ "if ($args[0] -eq '--help') { Write-Output ' --session-id <uuid>'; exit 0 }\r\nexit 92\r\n"+ )++ // `models` exits 92 in the fake shim: the help answer survives, the model list is empty.+ await expect(probeGrokCliAt(cmd)).resolves.toEqual({ sessionIdFlag: true, models: [] })+ } finally {+ fs.rmSync(dir, { recursive: true, force: true })+ }+ })+})diff --git a/src/core/grok-cli.ts b/src/core/grok-cli.tsindex 213eb0985..7fe22fe1e 100644--- a/src/core/grok-cli.ts+++ b/src/core/grok-cli.ts@@ -11,6 +11,7 @@import { execFile } from 'child_process'import { promisify } from 'util'import { IPC } from '../shared/ipc'+import { directExecutableInvocation } from './exec-path'import { findInLoginPath } from './pty-manager'import { platform } from './platform'import { grokModelsFrom } from '../shared/agents/model-gateway'@@ -40,8 +41,6 @@ export function grokCliCapsFrom(}}-let cached: Promise<GrokCliCaps> | null = null-/*** The two spawns, separated from HOW they are spawned so the composition is testable.*@@ -61,17 +60,31 @@ export async function grokCapsFromRunner(return grokCliCapsFrom(help, models)}+/** Probe the grok binary at `bin`, which may be a Windows npm shim the platform cannot spawn+ * directly — `directExecutableInvocation` decides how it is run, once, for both subcommands. */+export function probeGrokCliAt(bin: string): Promise<GrokCliCaps> {+ return grokCapsFromRunner(async (args) => {+ try {+ const invocation = directExecutableInvocation(bin, args)+ if (!invocation) return null+ const { stdout } = await execFileP(invocation.executable, invocation.args, {+ timeout: PROBE_TIMEOUT_MS+ })+ return stdout+ } catch {+ // Missing CLI, timeout, non-zero exit — all mean "unknown", which means "omit the flag".+ return null+ }+ })+}++let cached: Promise<GrokCliCaps> | null = null+async function probe(): Promise<GrokCliCaps> {// GUI apps don't inherit the shell PATH — resolve through the login shell like every other CLI// lookup in the app.const bin = await findInLoginPath('grok').catch(() => null)- if (!bin) return UNKNOWN_GROK_CLI_CAPS- return grokCapsFromRunner((args) =>- execFileP(bin, args, { timeout: PROBE_TIMEOUT_MS })- .then((r) => r.stdout)- // Missing CLI, timeout, non-zero exit — all mean "unknown", which means "omit the flag".- .catch(() => null)- )+ return bin ? probeGrokCliAt(bin) : UNKNOWN_GROK_CLI_CAPS}/** The local grok CLI's capabilities. Memoized for the process lifetime. Never rejects. */diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex a131c67e5..62fe64a85 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -506,15 +506,8 @@ function resolveLocaleLang(): string | null {return /utf-?8/i.test(cur) ? null : 'en_US.UTF-8'}-/**- * Resolve an executable against the user's real login-shell PATH (reusing the cached probe),- * returning its absolute path or null. GUI apps inherit only a minimal PATH, so a bare- * `execFile('claude', …)` would fail even when the tool is installed.- */-export async function findInLoginPath(bin: string): Promise<string | null> {- const shellPath = (await resolveShellPath()) ?? process.env.PATH ?? ''- return findInPathString(bin, shellPath)-}+// Kept as a compatibility export: executable resolution now lives with the other PATH helpers.+export { findInLoginPath } from './exec-path'/** A UI client: an Electron webContents id or a ServerPlatform uiId. */type ClientId = numberdiff --git a/src/core/usage/codex-usage.test.ts b/src/core/usage/codex-usage.test.tsindex a423519dc..a7cb1fb03 100644--- a/src/core/usage/codex-usage.test.ts+++ b/src/core/usage/codex-usage.test.ts@@ -13,7 +13,8 @@ import path from 'path'// The app-server tier spawns the real `codex` binary; force it to decline instantly so the// identity-stamping tests below are hermetic (they exercise the backend + unavailable paths only).-vi.mock('child_process', () => ({+vi.mock('child_process', async (importOriginal) => ({+ ...(await importOriginal<typeof import('child_process')>()),spawn: () => {throw new Error('app-server disabled in test')}diff --git a/src/core/usage/codex-usage.ts b/src/core/usage/codex-usage.tsindex cf97ccb3d..60ea508a7 100644--- a/src/core/usage/codex-usage.ts+++ b/src/core/usage/codex-usage.ts@@ -16,6 +16,7 @@ import path from 'path'import { spawn } from 'child_process'import type { ProviderUsage, UsageLimit } from '../../shared/types'import { parseResetTimestamp } from './claude-usage-map'+import { directExecutableInvocation, findInLoginPath } from '../exec-path'const BACKEND_USAGE_URL = 'https://chatgpt.com/backend-api/wham/usage'const FETCH_TIMEOUT_MS = 8000@@ -150,11 +151,22 @@ async function fetchViaBackend(home: string): Promise<ProviderUsage | null> {* when the backend tier declined. Sandboxed read-only/untrusted — this must never be a way for* a quota refresh to touch the user's files.*/-async function fetchViaAppServer(home: string): Promise<ProviderUsage | null> {+export async function fetchCodexUsageViaAppServerAt(+ bin: string,+ home: string+): Promise<ProviderUsage | null> {+ const invocation = directExecutableInvocation(bin, [+ '-s',+ 'read-only',+ '-a',+ 'untrusted',+ 'app-server'+ ])+ if (!invocation) return nullreturn new Promise<ProviderUsage | null>((resolve) => {let child: ReturnType<typeof spawn>try {- child = spawn('codex', ['-s', 'read-only', '-a', 'untrusted', 'app-server'], {+ child = spawn(invocation.executable, invocation.args, {env: { ...process.env, CODEX_HOME: home },stdio: ['pipe', 'pipe', 'ignore']})@@ -225,6 +237,11 @@ async function fetchViaAppServer(home: string): Promise<ProviderUsage | null> {})}+async function fetchViaAppServer(home: string): Promise<ProviderUsage | null> {+ const bin = await findInLoginPath('codex')+ return bin ? fetchCodexUsageViaAppServerAt(bin, home) : null+}+/*** Codex usage, backend first and app-server second.*diff --git a/src/core/usage/codex-usage.windows.test.ts b/src/core/usage/codex-usage.windows.test.tsnew file mode 100644index 000000000..88b58f6de--- /dev/null+++ b/src/core/usage/codex-usage.windows.test.ts@@ -0,0 +1,43 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { fetchCodexUsageViaAppServerAt } from './codex-usage'++describe.skipIf(process.platform !== 'win32')(+ 'fetchCodexUsageViaAppServerAt - Windows npm shim',+ () => {+ let dir: string++ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-codex-usage-shim-'))+ })++ afterEach(() => {+ fs.rmSync(dir, { recursive: true, force: true })+ })++ it('completes the JSON-RPC fallback through the sibling PowerShell shim', async () => {+ const cmd = path.join(dir, 'codex.cmd')+ fs.writeFileSync(cmd, '@exit /b 99\r\n')+ fs.writeFileSync(+ path.join(dir, 'codex.ps1'),+ [+ 'while (($line = [Console]::In.ReadLine()) -ne $null) {',+ " if ($line -match '\"id\":1') {",+ " [Console]::Out.WriteLine('{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{}}')",+ " } elseif ($line -match '\"id\":2') {",+ " [Console]::Out.WriteLine('{\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{\"rateLimits\":{\"primary\":{\"usedPercent\":42,\"limitWindowSeconds\":18000}}}}')",+ ' }',+ '}'+ ].join('\n')+ )++ const usage = await fetchCodexUsageViaAppServerAt(cmd, dir)+ expect(usage?.status).toBe('ok')+ expect(usage?.limits).toMatchObject([+ { kind: 'session', usedPercent: 42, windowMinutes: 300 }+ ])+ })+ }+)diff --git a/src/main/codex-accounts-e2e.test.ts b/src/main/codex-accounts-e2e.test.tsindex 1c1b03273..3f53ee9ef 100644--- a/src/main/codex-accounts-e2e.test.ts+++ b/src/main/codex-accounts-e2e.test.ts@@ -232,8 +232,8 @@ describe('S6 acceptance gate — the merged machine-scoped-Codex-account chain cexpect(existsSync(rollout)).toBe(true)// ---- LEG E: per-account usage attribution — never mixed, never fabricated --------------------- // Neutralise PATH so the app-server tier's `spawn('codex')` fails fast with ENOENT instead of- // finding a real binary; no auth.json ⇒ the backend tier declines without a network call.+ // Neutralise PATH so the app-server tier cannot resolve a real Codex binary;+ // no auth.json means the backend tier declines without a network call.const prevPath = process.env.PATHprocess.env.PATH = ''try {diff --git a/src/main/codex-accounts.ts b/src/main/codex-accounts.tsindex aa462cee4..1764db126 100644--- a/src/main/codex-accounts.ts+++ b/src/main/codex-accounts.ts@@ -32,6 +32,7 @@ import {type CodexRolloutExposurePlan} from '../core/codex-accounts-core'import { readCodexAccountAt, readCodexThreadAt } from '../core/codex-session-name'+import { directExecutableInvocation } from '../core/exec-path'import { ensureCodexRelayRoot } from './codex-relay-daemon'import { platform } from '../core/platform'import { findInLoginPath } from '../core/pty-manager'@@ -109,7 +110,9 @@ export async function ensureCodexAccountDaemon(accountId?: string): Promise<voidasync () => {const codex = await findInLoginPath('codex')if (!codex) throw new Error('Codex CLI unavailable')- await execFileP(codex, ['app-server', 'daemon', 'start'], {+ const invocation = directExecutableInvocation(codex, ['app-server', 'daemon', 'start'])+ if (!invocation) throw new Error('Codex CLI has no safe Windows entry point')+ await execFileP(invocation.executable, invocation.args, {cwd: os.homedir(),env: { ...process.env, ...codexSessionEnv(platform().userDataDir, accountId) },timeout: 15_000,@@ -267,7 +270,9 @@ export function initCodexAccounts(getSshManager?: () => SshProjectManager | undetry {const codex = await findInLoginPath('codex')if (codex) {- await execFileP(codex, ['app-server', 'daemon', 'stop'], {+ const invocation = directExecutableInvocation(codex, ['app-server', 'daemon', 'stop'])+ if (!invocation) throw new Error('Codex CLI has no safe Windows entry point')+ await execFileP(invocation.executable, invocation.args, {cwd: os.homedir(),env: { ...process.env, CODEX_HOME: localCodexAccountHome(id) },timeout: 10_000,