Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/main/codex-accounts/wsl-codex-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,13 @@ export function buildWslCodexLoginArgs(distro: string, linuxHomePath: string): s
}

function buildCodexPathLookup(): string {
return buildPosixCommandPathLookupScript({ kind: 'literal', value: 'codex' })
// Same skip as agent detection: otherwise detection can report the guest
// codex while this resolves the Windows one ahead of it on PATH, and Orca
// launches a different binary than the one it said was installed.
return buildPosixCommandPathLookupScript(
{ kind: 'literal', value: 'codex' },
{ skipWindowsMountDirs: true }
)
}

function buildWslCodexShellArgs(distro: string, command: string): string[] {
Expand Down
7 changes: 6 additions & 1 deletion src/main/ipc/preflight-command-exec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,12 @@ describe('isCommandOnPath', () => {
expect(runPreflightCommandInWslMock).toHaveBeenCalledOnce()
const [, command] = runPreflightCommandInWslMock.mock.calls[0] as [{ distro: string }, string]
expect(command).toContain(
buildPosixCommandPathLookupScript({ kind: 'literal', value: 'codex' })
buildPosixCommandPathLookupScript(
{ kind: 'literal', value: 'codex' },
// The WSL branch skips Windows mounts, so detection and this check
// cannot disagree about the same distro.
{ skipWindowsMountDirs: true }
)
)
expect(command).toContain(
['if [ -n "$resolved" ]; then', `printf '${sentinel}%s\\n' "$resolved"`, 'fi'].join('\n')
Expand Down
8 changes: 7 additions & 1 deletion src/main/ipc/preflight-command-exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,13 @@ export async function isCommandOnPath(
const { stdout } = await execCommandInWsl(
wslTarget,
[
buildPosixCommandPathLookupScript({ kind: 'literal', value: command }),
// Same skip as agent detection: without it this branch answers "yes"
// for a Windows binary reached through interop, so preflight and the
// detector disagree about the same distro.
buildPosixCommandPathLookupScript(
{ kind: 'literal', value: command },
{ skipWindowsMountDirs: true }
),
'if [ -n "$resolved" ]; then',
`printf '${WSL_COMMAND_PATH_SENTINEL}%s\\n' "$resolved"`,
'fi'
Expand Down
94 changes: 93 additions & 1 deletion src/main/ipc/preflight-wsl-agent-detection.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { execFileSync, type ExecFileSyncOptions } from 'node:child_process'
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
Expand Down Expand Up @@ -291,3 +291,95 @@ describe('the PATH walk, run by a real POSIX shell', () => {
}
})
})

describe('the mount table read, counted against a real shell', () => {
const itPosix = process.platform === 'win32' ? it.skip : it

const runWithCountingAwk = async (commands: string[]): Promise<number> => {
const root = mkdtempSync(join(tmpdir(), 'orca-awk-'))
try {
const counter = join(root, 'count')
const bin = join(root, 'bin')
mkdirSync(bin, { recursive: true })
// A stub that records each fork, then answers as awk would on a host
// with no Windows mounts.
writeFileSync(join(bin, 'awk'), `#!/bin/sh\necho x >> ${counter}\nexit 0\n`)
chmodSync(join(bin, 'awk'), 0o755)
writeFileSync(counter, '')

runWslProcessMock.mockResolvedValue({
environmentResolved: true,
code: 0,
stdout: '',
stderr: '',
timedOut: false
})
await detectWslCommandsOnPath({ distro: 'Ubuntu' }, commands)
const script = String(runWslProcessMock.mock.calls.at(-1)?.[0].script)
const options: ExecFileSyncOptions = {
encoding: 'utf8',
env: { PATH: `${bin}:/usr/bin:/bin`, HOME: root }
}
execFileSync('/bin/sh', ['-c', script], options)
return readFileSync(counter, 'utf8').trim().split('\n').filter(Boolean).length
Comment on lines +304 to +324

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Pass the counter path through the environment.

Line 306 inserts counter into shell source without quoting. If TMPDIR contains whitespace, the stub writes to the wrong path and this test reports zero invocations.

Proposed fix
-      writeFileSync(join(bin, 'awk'), `#!/bin/sh\necho x >> ${counter}\nexit 0\n`)
+      writeFileSync(join(bin, 'awk'), '#!/bin/sh\nprintf x >> "$ORCA_AWK_COUNTER"\nexit 0\n')
...
-        env: { PATH: `${bin}:/usr/bin:/bin`, HOME: root }
+        env: { PATH: `${bin}:/usr/bin:/bin`, HOME: root, ORCA_AWK_COUNTER: counter }

As per coding guidelines, commands and scripts must work on macOS, Linux, and Windows.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// A stub that records each fork, then answers as awk would on a host
// with no Windows mounts.
writeFileSync(join(bin, 'awk'), `#!/bin/sh\necho x >> ${counter}\nexit 0\n`)
chmodSync(join(bin, 'awk'), 0o755)
writeFileSync(counter, '')
runWslProcessMock.mockResolvedValue({
environmentResolved: true,
code: 0,
stdout: '',
stderr: '',
timedOut: false
})
await detectWslCommandsOnPath({ distro: 'Ubuntu' }, commands)
const script = String(runWslProcessMock.mock.calls.at(-1)?.[0].script)
const options: ExecFileSyncOptions = {
encoding: 'utf8',
env: { PATH: `${bin}:/usr/bin:/bin`, HOME: root }
}
execFileSync('/bin/sh', ['-c', script], options)
return readFileSync(counter, 'utf8').trim().split('\n').filter(Boolean).length
// A stub that records each fork, then answers as awk would on a host
// with no Windows mounts.
writeFileSync(join(bin, 'awk'), '#!/bin/sh\nprintf x >> "$ORCA_AWK_COUNTER"\nexit 0\n')
chmodSync(join(bin, 'awk'), 0o755)
writeFileSync(counter, '')
runWslProcessMock.mockResolvedValue({
environmentResolved: true,
code: 0,
stdout: '',
stderr: '',
timedOut: false
})
await detectWslCommandsOnPath({ distro: 'Ubuntu' }, commands)
const script = String(runWslProcessMock.mock.calls.at(-1)?.[0].script)
const options: ExecFileSyncOptions = {
encoding: 'utf8',
env: { PATH: `${bin}:/usr/bin:/bin`, HOME: root, ORCA_AWK_COUNTER: counter }
}
execFileSync('/bin/sh', ['-c', script], options)
return readFileSync(counter, 'utf8').trim().split('\n').filter(Boolean).length
🧰 Tools
🪛 ast-grep (0.45.1)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFileSync, type ExecFileSyncOptions } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

Source: Coding guidelines

} finally {
rmSync(root, { recursive: true, force: true })
}
}

itPosix('reads /proc/mounts once, not once per probed command', async () => {
// The prelude is embedded in the lookup script, which the caller wraps in
// `for cmd in <every agent>`. An unconditional assignment forked awk once
// per CLI -- 36 of them inside the distro against a 10s budget.
expect(await runWithCountingAwk(['claude', 'codex', 'gemini', 'opencode'])).toBe(1)
})

itPosix('still reads it once when only one command is probed', async () => {
expect(await runWithCountingAwk(['claude'])).toBe(1)
})

itPosix('applies the memoised mount list to every command, not just the first', async () => {
// Counting forks with a stub that reports NO mounts cannot see the thing
// the hoist trades correctness for: a refactor that empties or clobbers
// the variable inside the walk keeps the fork count at 1 and keeps the
// single-command test green, while every agent after the first stops
// skipping /mnt. A surviving mutant proved that gap.
const root = mkdtempSync(join(tmpdir(), 'orca-memo-'))
try {
const win = join(root, 'winmnt/c/npm')
const guest = join(root, 'home/bin')
for (const [dir, body] of [
[win, 'win'],
[guest, 'guest']
] as const) {
mkdirSync(dir, { recursive: true })
for (const name of ['claude', 'codex']) {
writeFileSync(join(dir, name), `#!/bin/sh\necho ${body}\n`)
chmodSync(join(dir, name), 0o755)
}
}
runWslProcessMock.mockResolvedValue({
environmentResolved: true,
code: 0,
stdout: '',
stderr: '',
timedOut: false
})
await detectWslCommandsOnPath({ distro: 'Ubuntu' }, ['claude', 'codex'])
const script = String(runWslProcessMock.mock.calls.at(-1)?.[0].script).replace(
/_orca_win_mounts=\$\([^)]*\)/,
`_orca_win_mounts=${join(root, 'winmnt')}`
)
const options: ExecFileSyncOptions = {
encoding: 'utf8',
env: { PATH: `${win}:${guest}:/usr/bin:/bin`, HOME: root }
Comment on lines +369 to +375

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Pass the mount path through the environment.

Line 371 inserts join(root, 'winmnt') into shell source without quoting. If TMPDIR contains whitespace or shell-significant characters, the test can fail before it checks command resolution. Store the path in env and reference a quoted variable in the replacement.

Proposed fix
-        `_orca_win_mounts=${join(root, 'winmnt')}`
+        '_orca_win_mounts="$ORCA_TEST_WIN_MOUNT"'
...
-        env: { PATH: `${win}:${guest}:/usr/bin:/bin`, HOME: root }
+        env: {
+          PATH: `${win}:${guest}:/usr/bin:/bin`,
+          HOME: root,
+          ORCA_TEST_WIN_MOUNT: join(root, 'winmnt')
+        }

As per coding guidelines, commands and scripts must work on macOS, Linux, and Windows.

🧰 Tools
🪛 ast-grep (0.45.1)

[warning] Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFileSync, type ExecFileSyncOptions } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

Source: Coding guidelines

}
const out = String(execFileSync('/bin/sh', ['-c', script], options))
// BOTH must resolve behind the mount, not just the first.
expect(out).toContain(`__ORCA_AGENT_PATH__claude\t${join(guest, 'claude')}`)
expect(out).toContain(`__ORCA_AGENT_PATH__codex\t${join(guest, 'codex')}`)
} finally {
rmSync(root, { recursive: true, force: true })
}
})
})
13 changes: 10 additions & 3 deletions src/shared/posix-command-path-lookup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,18 @@ export function buildPosixCommandPathLookupScript(
options: PosixCommandPathLookupOptions = {}
): string {
const commandAssignment = buildCommandAssignment(target)
// `-t drvfs` is what WSL mounts a Windows drive as, wherever the automount
// root is; 9p/virtiofs cover the WSL2 shapes. Read once, outside the loop.
// `drvfs` is what WSL mounts a Windows drive as, wherever the automount root
// is; 9p/virtiofs cover the WSL2 shapes.
//
// `${x+set}` so the table is read once per SHELL, not once per lookup: the
// caller embeds this script inside `for cmd in <every agent>`, so an
// unconditional assignment forked awk once per probed CLI -- 36 of them
// against a 10s budget. The variable outlives the iteration, so the second
// pass finds it set. Deliberately not `[ -n ... ]`: a host with no Windows
// mounts yields the empty string, which must still count as read.
const mountPrelude = options.skipWindowsMountDirs
? [
'_orca_win_mounts=$(awk \'$3 == "drvfs" || $3 == "9p" || $3 == "virtiofs" { print $2 }\' /proc/mounts 2>/dev/null)'
'[ "${_orca_win_mounts+set}" = set ] || _orca_win_mounts=$(awk \'$3 == "drvfs" || $3 == "9p" || $3 == "virtiofs" { print $2 }\' /proc/mounts 2>/dev/null)'
]
: []
const skipMountComponent = options.skipWindowsMountDirs
Expand Down