From 84411b943f3ca8dc8093877be835fbeb187a2755 Mon Sep 17 00:00:00 2001 From: Rai Butera Date: Tue, 9 Jun 2026 00:23:32 +0100 Subject: [PATCH] fix: detect agents via install-dir resolver when which misses on GUI launch (#4880) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: detect agents via install-dir resolver when which misses on GUI launch The Agents settings pane reports every agent as "Not installed" on a cold GUI launch even when the CLIs are installed and runnable from Terminal. detectInstalledAgents resolves each agent with `which`, which only sees process.env.PATH. GUI-launched Electron inherits a stripped PATH from launchd that omits the user's shell-rc dirs (~/.local/bin, ~/Library/pnpm, ~/.asdf/shims, nvm/volta/fnm/mise shims, ...). The synchronous seed in patchPackagedProcessPath plus the async shell-PATH hydration both race the first detection, and the first result is cached for the session, so the pane can latch onto an empty "nothing installed" snapshot until the user relaunches from a terminal or clicks Refresh. Fall back to resolveCliCommand (the same resolver the spawn path uses in src/main/codex-cli/command.ts) when the PATH lookup misses. Detection now has the same reach as launch: if Orca can run it, Orca detects it, independent of PATH-hydration timing. No false positives — an uninstalled agent still resolves to a bare command name rather than an absolute path. Verified on macOS that resolveCliCommand resolves claude (~/.local/bin), codex (~/.asdf/shims), and opencode (~/Library/pnpm) under a stripped PATH. * fix: bulk resolve agent install-dir detection Co-authored-by: Orca * fix: ignore node navigator for linux webgl policy Co-authored-by: Orca --------- Co-authored-by: Jinwoo-H Co-authored-by: Orca --- src/main/codex-cli/command.test.ts | 52 ++++++++++- src/main/codex-cli/command.ts | 86 +++++++++++++------ .../ipc/local-agent-install-dir-detection.ts | 18 ++++ src/main/ipc/preflight.test.ts | 86 ++++++++++++++++++- src/main/ipc/preflight.ts | 14 ++- .../lib/pane-manager/pane-webgl-renderer.ts | 8 +- 6 files changed, 234 insertions(+), 30 deletions(-) create mode 100644 src/main/ipc/local-agent-install-dir-detection.ts diff --git a/src/main/codex-cli/command.test.ts b/src/main/codex-cli/command.test.ts index 70928625d..045048f29 100644 --- a/src/main/codex-cli/command.test.ts +++ b/src/main/codex-cli/command.test.ts @@ -2,7 +2,12 @@ import { chmodSync, mkdtempSync, mkdirSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { delimiter, dirname, join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' -import { getVersionManagerBinPaths, resolveClaudeCommand, resolveCodexCommand } from './command' +import { + getVersionManagerBinPaths, + resolveClaudeCommand, + resolveCliCommands, + resolveCodexCommand +} from './command' function makeExecutable(path: string): void { mkdirSync(dirname(path), { recursive: true }) @@ -224,6 +229,51 @@ describe('resolveClaudeCommand', () => { }) }) +describe('resolveCliCommands', () => { + afterEach(() => { + delete process.env.PATH + delete process.env.Path + }) + + it('resolves a batch from PATH and install directories', () => { + const root = mkdtempSync(join(tmpdir(), 'orca-cli-commands-')) + const pathDir = join(root, 'bin') + const pathClaude = join(pathDir, 'claude') + const nvmCodex = join(root, '.nvm', 'versions', 'node', 'v24.13.0', 'bin', 'codex') + const pnpmOpencode = join(root, 'Library', 'pnpm', 'opencode') + makeExecutable(pathClaude) + makeExecutable(nvmCodex) + makeExecutable(pnpmOpencode) + + const resolved = resolveCliCommands(['claude', 'codex', 'opencode', 'missing'], { + platform: 'darwin', + pathEnv: pathDir, + homePath: root + }) + + expect(resolved.get('claude')).toBe(pathClaude) + expect(resolved.get('codex')).toBe(nvmCodex) + expect(resolved.get('opencode')).toBe(pnpmOpencode) + expect(resolved.get('missing')).toBe('missing') + }) + + it('deduplicates command names in the returned map', () => { + const root = mkdtempSync(join(tmpdir(), 'orca-cli-commands-')) + const pathDir = join(root, 'bin') + const pathClaude = join(pathDir, 'claude') + makeExecutable(pathClaude) + + const resolved = resolveCliCommands(['claude', 'claude'], { + platform: 'linux', + pathEnv: pathDir, + homePath: root + }) + + expect([...resolved.keys()]).toEqual(['claude']) + expect(resolved.get('claude')).toBe(pathClaude) + }) +}) + describe('getVersionManagerBinPaths', () => { it('includes volta, asdf, fnm, mise, pnpm, yarn, and bun directories', () => { const root = mkdtempSync(join(tmpdir(), 'orca-vm-paths-')) diff --git a/src/main/codex-cli/command.ts b/src/main/codex-cli/command.ts index 666cf0106..177b7e0ea 100644 --- a/src/main/codex-cli/command.ts +++ b/src/main/codex-cli/command.ts @@ -85,11 +85,7 @@ function isRunnableCommand(platform: NodeJS.Platform, candidate: string): boolea } } -function getVersionManagerDirectories( - platform: NodeJS.Platform, - homePath: string, - executableNames: string[] -): string[] { +function getBaseVersionManagerDirectories(platform: NodeJS.Platform, homePath: string): string[] { const directories = [ join(homePath, '.volta', 'bin'), join(homePath, '.asdf', 'shims'), @@ -100,25 +96,6 @@ function getVersionManagerDirectories( join(homePath, '.local', 'share', 'mise', 'shims') ] - // Why: GUI-launched Electron apps do not inherit shell init from version - // managers like nvm, so `spawn('codex')` can fail for users who installed - // Codex under a Node-managed bin directory even though Terminal can run it. - // Probe the newest installed nvm version explicitly so rate-limit tracking - // and account login use the same binary the shell would expose. - const nvmVersionsDir = join(homePath, '.nvm', 'versions', 'node') - if (existsSync(nvmVersionsDir)) { - const nvmVersionDirectories = readdirSync(nvmVersionsDir, { withFileTypes: true }) - .filter((entry) => entry.isDirectory()) - .map((entry) => entry.name) - .sort(compareVersionDesc) - .map((entry) => join(nvmVersionsDir, entry, 'bin')) - - const firstNvmMatch = findFirstExecutable(platform, nvmVersionDirectories, executableNames) - if (firstNvmMatch) { - directories.unshift(dirname(firstNvmMatch)) - } - } - if (platform === 'win32') { // Why: Anthropic's native Windows installer places claude.exe here, and // GUI-launched Orca may not inherit the user's PATH entry for it. @@ -146,6 +123,40 @@ function getVersionManagerDirectories( return directories } +function getNvmVersionDirectories(homePath: string): string[] { + const nvmVersionsDir = join(homePath, '.nvm', 'versions', 'node') + if (!existsSync(nvmVersionsDir)) { + return [] + } + + return readdirSync(nvmVersionsDir, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort(compareVersionDesc) + .map((entry) => join(nvmVersionsDir, entry, 'bin')) +} + +function getVersionManagerDirectories( + platform: NodeJS.Platform, + homePath: string, + executableNames: string[] +): string[] { + const directories = getBaseVersionManagerDirectories(platform, homePath) + + // Why: GUI-launched Electron apps do not inherit shell init from nvm, so + // command resolution probes the newest installed Node versions explicitly. + const firstNvmMatch = findFirstExecutable( + platform, + getNvmVersionDirectories(homePath), + executableNames + ) + if (firstNvmMatch) { + directories.unshift(dirname(firstNvmMatch)) + } + + return directories +} + export function resolveCliCommand( commandName: string, options: ResolveCommandOptions = {} @@ -167,6 +178,33 @@ export function resolveCliCommand( return versionManagerCandidate ?? commandName } +export function resolveCliCommands( + commandNames: readonly string[], + options: ResolveCommandOptions = {} +): Map { + const platform = options.platform ?? process.platform + const pathEnv = options.pathEnv ?? process.env.PATH ?? process.env.Path ?? null + const pathDirectories = splitPath(pathEnv) + const homePath = options.homePath ?? homedir() + // Why: agent detection probes many CLIs at once; compute expensive install + // directories, especially nvm versions, once per detection pass. + const installDirectories = [ + ...getNvmVersionDirectories(homePath), + ...getBaseVersionManagerDirectories(platform, homePath) + ] + const resolved = new Map() + + for (const commandName of new Set(commandNames)) { + const executableNames = getExecutableNames(platform, commandName) + const pathCandidate = findFirstExecutable(platform, pathDirectories, executableNames) + const installCandidate = + pathCandidate ?? findFirstExecutable(platform, installDirectories, executableNames) + resolved.set(commandName, installCandidate ?? commandName) + } + + return resolved +} + export function resolveCodexCommand(options: ResolveCommandOptions = {}): string { return resolveCliCommand('codex', options) } diff --git a/src/main/ipc/local-agent-install-dir-detection.ts b/src/main/ipc/local-agent-install-dir-detection.ts new file mode 100644 index 000000000..6539553e0 --- /dev/null +++ b/src/main/ipc/local-agent-install-dir-detection.ts @@ -0,0 +1,18 @@ +import path from 'path' +import { resolveCliCommands } from '../codex-cli/command' + +// Why: local agent detection may run before shell-PATH hydration, but the +// fallback must stay bounded because it runs on the main process. +export function detectCommandsInInstallDirs(commands: readonly string[]): Set { + if (commands.length === 0) { + return new Set() + } + try { + const resolvedCommands = resolveCliCommands(commands) + return new Set( + commands.filter((command) => path.isAbsolute(resolvedCommands.get(command) ?? command)) + ) + } catch { + return new Set() + } +} diff --git a/src/main/ipc/preflight.test.ts b/src/main/ipc/preflight.test.ts index bb28e1bc6..09f57f1ce 100644 --- a/src/main/ipc/preflight.test.ts +++ b/src/main/ipc/preflight.test.ts @@ -11,7 +11,8 @@ const { getActiveMultiplexerMock, getBitbucketAuthStatusMock, getAzureDevOpsAuthStatusMock, - getGiteaAuthStatusMock + getGiteaAuthStatusMock, + resolveCliCommandsMock } = vi.hoisted(() => ({ handleMock: vi.fn(), execFileMock: vi.fn(), @@ -21,7 +22,8 @@ const { getActiveMultiplexerMock: vi.fn(), getBitbucketAuthStatusMock: vi.fn(), getAzureDevOpsAuthStatusMock: vi.fn(), - getGiteaAuthStatusMock: vi.fn() + getGiteaAuthStatusMock: vi.fn(), + resolveCliCommandsMock: vi.fn() })) vi.mock('electron', () => ({ @@ -45,6 +47,10 @@ vi.mock('../startup/hydrate-shell-path', () => ({ mergePathSegments: mergePathSegmentsMock })) +vi.mock('../codex-cli/command', () => ({ + resolveCliCommands: resolveCliCommandsMock +})) + vi.mock('./ssh', () => ({ getActiveMultiplexer: getActiveMultiplexerMock })) @@ -98,6 +104,12 @@ describe('preflight', () => { getBitbucketAuthStatusMock.mockReset() getAzureDevOpsAuthStatusMock.mockReset() getGiteaAuthStatusMock.mockReset() + // Why: existing tests should keep treating `which` as the only source + // unless a case explicitly exercises the install-dir fallback. + resolveCliCommandsMock.mockReset() + resolveCliCommandsMock.mockImplementation( + (commands: string[]) => new Map(commands.map((command) => [command, command])) + ) getBitbucketAuthStatusMock.mockResolvedValue(defaultBitbucketStatus) getAzureDevOpsAuthStatusMock.mockResolvedValue(defaultAzureDevOpsStatus) getGiteaAuthStatusMock.mockResolvedValue(defaultGiteaStatus) @@ -435,6 +447,72 @@ describe('preflight', () => { await expect(detectInstalledAgents()).resolves.toEqual(['claude', 'cursor']) }) + it('detects agents via the install-dir resolver when which fails (stripped GUI PATH)', async () => { + // Why: cold GUI launches can run detection before shell-PATH hydration + // adds user install dirs, so `which` can miss runnable CLIs. + execFileAsyncMock.mockImplementation(async (command) => { + if (command !== 'which') { + throw new Error(`unexpected command ${String(command)}`) + } + throw new Error('not found') + }) + resolveCliCommandsMock.mockImplementation( + (commands: string[]) => + new Map( + commands.map((cmd) => { + if (cmd === 'claude') { + return [cmd, '/Users/test/.local/bin/claude'] + } + if (cmd === 'codex') { + return [cmd, '/Users/test/.asdf/shims/codex'] + } + if (cmd === 'opencode') { + return [cmd, '/Users/test/Library/pnpm/opencode'] + } + return [cmd, cmd] + }) + ) + ) + + await expect(detectInstalledAgents()).resolves.toEqual(['claude', 'codex', 'opencode']) + expect(resolveCliCommandsMock).toHaveBeenCalledTimes(1) + }) + + it('does not double-count an agent already found on PATH via the install-dir resolver', async () => { + // Why: the fallback should not duplicate ids when PATH already finds a CLI. + execFileAsyncMock.mockImplementation(async (command, args) => { + if (command !== 'which') { + throw new Error(`unexpected command ${String(command)}`) + } + if (String(args[0]) === 'claude') { + return { stdout: '/Users/test/.local/bin/claude\n' } + } + throw new Error('not found') + }) + resolveCliCommandsMock.mockImplementation( + (commands: string[]) => new Map(commands.map((cmd) => [cmd, cmd])) + ) + + await expect(detectInstalledAgents()).resolves.toEqual(['claude']) + expect(resolveCliCommandsMock).toHaveBeenCalledTimes(1) + expect(resolveCliCommandsMock).toHaveBeenCalledWith(expect.not.arrayContaining(['claude'])) + }) + + it('treats an agent as not installed when the install-dir resolver throws', async () => { + // Why: transient fs errors in the fallback must not crash detection. + execFileAsyncMock.mockImplementation(async (command) => { + if (command !== 'which') { + throw new Error(`unexpected command ${String(command)}`) + } + throw new Error('not found') + }) + resolveCliCommandsMock.mockImplementation(() => { + throw new Error('EACCES: permission denied') + }) + + await expect(detectInstalledAgents()).resolves.toEqual([]) + }) + it('registers agent detection through the shared launch config commands', async () => { execFileAsyncMock.mockImplementation(async (command, args) => { if (command !== 'which') { @@ -521,6 +599,8 @@ describe('preflight', () => { await expect(detectInstalledAgents({ wslDistro: 'Ubuntu' })).resolves.toEqual(['claude']) expect(execFileAsyncMock).toHaveBeenCalledTimes(1) + // Why: the local fallback must not report host binaries as WSL binaries. + expect(resolveCliCommandsMock).not.toHaveBeenCalled() expect(execFileAsyncMock).toHaveBeenCalledWith( 'wsl.exe', expect.arrayContaining([ @@ -553,6 +633,8 @@ describe('preflight', () => { await expect(detectInstalledAgents({ wslDefault: true })).resolves.toEqual(['codex']) expect(execFileAsyncMock).toHaveBeenCalledTimes(1) + // Why: the local fallback must not leak into WSL detection. + expect(resolveCliCommandsMock).not.toHaveBeenCalled() expect(execFileAsyncMock).toHaveBeenCalledWith( 'wsl.exe', expect.arrayContaining(['--exec', 'bash', '-ic', expect.stringContaining("'codex'")]), diff --git a/src/main/ipc/preflight.ts b/src/main/ipc/preflight.ts index 15068a5f8..74a46bc13 100644 --- a/src/main/ipc/preflight.ts +++ b/src/main/ipc/preflight.ts @@ -11,6 +11,7 @@ import { getGiteaAuthStatus } from '../gitea/client' import { _resetKnownHostsCache } from '../gitlab/gl-utils' import { getActiveMultiplexer } from './ssh' import { detectWslCommandsOnPath, type WslPreflightTarget } from './preflight-wsl-agent-detection' +import { detectCommandsInInstallDirs } from './local-agent-install-dir-detection' const execFileAsync = promisify(execFile) const PREFLIGHT_COMMAND_TIMEOUT_MS = 5000 @@ -191,12 +192,21 @@ export async function detectInstalledAgents(context?: PreflightRuntimeContext): ) } - const checks = await Promise.all( + const pathChecks = await Promise.all( KNOWN_AGENT_COMMANDS.map(async ({ id, cmd }) => ({ id, - installed: await isCommandOnPath(cmd) + cmd, + installedOnPath: await isCommandOnPath(cmd) })) ) + const missedCommands = pathChecks.filter((check) => !check.installedOnPath).map(({ cmd }) => cmd) + // Why: PATH may still be unhydrated on a cold GUI launch; bulk resolution + // computes user install dirs once instead of blocking once per missed CLI. + const installDirCommands = detectCommandsInInstallDirs(missedCommands) + const checks = pathChecks.map(({ id, cmd, installedOnPath }) => ({ + id, + installed: installedOnPath || installDirCommands.has(cmd) + })) return uniqueAgentIds(checks.filter((c) => c.installed).map((c) => c.id)) } diff --git a/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts b/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts index 61e51e5cd..62ca7a9f2 100644 --- a/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts +++ b/src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts @@ -14,7 +14,13 @@ function isLinuxRenderer(): boolean { if (typeof navigator === 'undefined') { return false } - return navigator.platform.includes('Linux') || navigator.userAgent.includes('Linux') + const userAgent = navigator.userAgent + // Why: Node 24 exposes a Linux `navigator.platform` in CI, but this guard is + // only for real renderer user agents where Linux GPU stacks affect xterm. + return ( + userAgent.includes('Linux') || + (navigator.platform.includes('Linux') && !userAgent.startsWith('Node.js/')) + ) } export function shouldUseTerminalWebgl(pane: ManagedPaneInternal): boolean {