From da93f0d85293adaff80802b312dae88ee95962c1 Mon Sep 17 00:00:00 2001 From: Jinwoo Hong <73622457+Jinwoo-H@users.noreply.github.com> Date: Thu, 21 May 2026 17:29:46 -0400 Subject: [PATCH] Fix WSL Codex terminal environment (#2558) --- src/main/cli/wsl-cli-installer.test.ts | 19 ++++++ src/main/cli/wsl-cli-installer.ts | 20 +++++-- src/main/daemon/pty-subprocess.test.ts | 60 +++++++++++++++++++ src/main/daemon/pty-subprocess.ts | 9 +++ src/main/providers/local-pty-provider.test.ts | 40 +++++++++++++ src/main/providers/local-pty-provider.ts | 10 ++++ src/main/pty/codex-home-wsl-env.test.ts | 17 ++++++ src/main/pty/codex-home-wsl-env.ts | 7 +++ .../src/components/settings/AccountsPane.tsx | 18 +++++- 9 files changed, 193 insertions(+), 7 deletions(-) create mode 100644 src/main/pty/codex-home-wsl-env.test.ts create mode 100644 src/main/pty/codex-home-wsl-env.ts diff --git a/src/main/cli/wsl-cli-installer.test.ts b/src/main/cli/wsl-cli-installer.test.ts index 71104d787..ef51b67df 100644 --- a/src/main/cli/wsl-cli-installer.test.ts +++ b/src/main/cli/wsl-cli-installer.test.ts @@ -177,6 +177,25 @@ describe('WslCliInstaller', () => { expect(bridge).toContain('exit 1') }) + it('wraps WSL bash scripts as a single encoded command line', () => { + const command = [ + 'set -euo pipefail', + `cat > "$command_tmp" <<'ORCA_WSL_CLI'`, + '#!/usr/bin/env bash', + 'exec powershell.exe "$@"', + 'ORCA_WSL_CLI' + ].join('\n') + const wrapped = _internals.buildEncodedWslBashCommand(command) + const encoded = wrapped.match( + /^set -o pipefail; printf %s '([^']+)' \| base64 -d \| bash$/ + )?.[1] + + expect(wrapped).not.toContain('\n') + expect(wrapped).toContain('set -o pipefail;') + expect(encoded).toBeTruthy() + expect(Buffer.from(encoded as string, 'base64').toString('utf8')).toBe(command) + }) + it('refuses to remove an old managed launcher when the bridge path is user-owned', async () => { const oldLauncher = _internals.buildWslLauncher( 'C:\\Old\\orca.cmd', diff --git a/src/main/cli/wsl-cli-installer.ts b/src/main/cli/wsl-cli-installer.ts index 7f90ace74..257ea5db3 100644 --- a/src/main/cli/wsl-cli-installer.ts +++ b/src/main/cli/wsl-cli-installer.ts @@ -339,14 +339,26 @@ export class WslCliInstaller { } async function runWslCommand(distro: string, command: string): Promise { - const { stdout } = (await execFileAsync('wsl.exe', ['-d', distro, '--', 'bash', '-lc', command], { - encoding: 'utf8', - timeout: 5000 - })) as { stdout: string } + const { stdout } = (await execFileAsync( + 'wsl.exe', + ['-d', distro, '--', 'bash', '-lc', buildEncodedWslBashCommand(command)], + { + encoding: 'utf8', + timeout: 10000 + } + )) as { stdout: string } return stdout } +function buildEncodedWslBashCommand(command: string): string { + // Why: raw multiline heredocs can be flattened while crossing wsl.exe's + // Windows command-line boundary. Send one shell-safe line and decode inside WSL. + const encoded = Buffer.from(command, 'utf8').toString('base64') + return `set -o pipefail; printf %s ${quoteShell(encoded)} | base64 -d | bash` +} + export const _internals = { + buildEncodedWslBashCommand, buildWslBridgeScript, buildWslLauncher } diff --git a/src/main/daemon/pty-subprocess.test.ts b/src/main/daemon/pty-subprocess.test.ts index fdf182803..97d760397 100644 --- a/src/main/daemon/pty-subprocess.test.ts +++ b/src/main/daemon/pty-subprocess.test.ts @@ -786,6 +786,66 @@ describe('createPtySubprocess', () => { ) }) + it('does not pass a Windows Codex home into daemon WSL terminals', () => { + const proc = mockPtyProcess() + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + + Object.defineProperty(process, 'platform', { value: 'win32' }) + + try { + createPtySubprocess({ + sessionId: 'test', + cols: 80, + rows: 24, + cwd: '\\\\wsl.localhost\\Ubuntu\\home\\jin\\repo', + env: { CODEX_HOME: 'C:\\Users\\jin\\.codex' } + }) + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + + expect(spawnMock).toHaveBeenCalledWith( + 'wsl.exe', + ['-d', 'Ubuntu', '--', 'bash', '-c', "cd '/home/jin/repo' && exec bash -l"], + expect.objectContaining({ + env: expect.not.objectContaining({ CODEX_HOME: expect.anything() }) + }) + ) + }) + + it('preserves an explicit Linux Codex home in daemon WSL terminals', () => { + const proc = mockPtyProcess() + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + + Object.defineProperty(process, 'platform', { value: 'win32' }) + + try { + createPtySubprocess({ + sessionId: 'test', + cols: 80, + rows: 24, + cwd: '\\\\wsl.localhost\\Ubuntu\\home\\jin\\repo', + env: { CODEX_HOME: '/home/jin/.codex-alt' } + }) + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + + expect(spawnMock).toHaveBeenCalledWith( + 'wsl.exe', + ['-d', 'Ubuntu', '--', 'bash', '-c', "cd '/home/jin/repo' && exec bash -l"], + expect.objectContaining({ + env: expect.objectContaining({ CODEX_HOME: '/home/jin/.codex-alt' }) + }) + ) + }) + it('keeps daemon WSL split panes in their distro when cwd is already POSIX', () => { const proc = mockPtyProcess() spawnMock.mockReturnValue(proc) diff --git a/src/main/daemon/pty-subprocess.ts b/src/main/daemon/pty-subprocess.ts index 78aeac726..4060b7580 100644 --- a/src/main/daemon/pty-subprocess.ts +++ b/src/main/daemon/pty-subprocess.ts @@ -19,6 +19,7 @@ import { import { resolveWindowsShellLaunchArgs } from '../providers/windows-shell-args' import { resolveEffectiveWindowsPowerShell } from '../providers/windows-powershell' import { isPwshAvailable } from '../pwsh' +import { isHostCodexHomeForWsl } from '../pty/codex-home-wsl-env' import { removeInheritedNoColor } from '../pty/terminal-color-env' import { parseWslPath } from '../wsl' import { getWslContextFromSessionId } from './wsl-session-context' @@ -237,6 +238,14 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl shellArgs = resolved.shellArgs spawnCwd = resolved.effectiveCwd validationCwd = resolved.validationCwd + if ( + pathWin32.basename(shellPath).toLowerCase() === 'wsl.exe' && + isHostCodexHomeForWsl(env.CODEX_HOME) + ) { + // Why: Orca's selected Codex runtime home is host-local. WSL Codex must + // use its Linux-side ~/.codex instead of inheriting a Windows path. + delete env.CODEX_HOME + } } else { // Why: any Orca-injected overlay env that user rc files can clobber // needs the wrapper so the post-rc restore line runs. diff --git a/src/main/providers/local-pty-provider.test.ts b/src/main/providers/local-pty-provider.test.ts index 1ae1979dc..e06841f40 100644 --- a/src/main/providers/local-pty-provider.test.ts +++ b/src/main/providers/local-pty-provider.test.ts @@ -159,6 +159,46 @@ describe('LocalPtyProvider', () => { expect(spawnCall[2].env.CUSTOM_VAR).toBe('custom-value') }) + it('does not pass a Windows Codex home into WSL terminals', async () => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + provider.configure({ + buildSpawnEnv: (_id, env) => { + env.CODEX_HOME = 'C:\\Users\\jin\\.codex' + return env + } + }) + + await provider.spawn({ + cols: 80, + rows: 24, + cwd: '\\\\wsl.localhost\\Ubuntu\\home\\jin\\repo' + }) + + const spawnCall = spawnMock.mock.calls.at(-1)! + expect(spawnCall[0]).toBe('wsl.exe') + expect(spawnCall[2].env.CODEX_HOME).toBeUndefined() + }) + + it('preserves an explicit Linux Codex home for WSL terminals', async () => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + provider.configure({ + buildSpawnEnv: (_id, env) => { + env.CODEX_HOME = '/home/jin/.codex-alt' + return env + } + }) + + await provider.spawn({ + cols: 80, + rows: 24, + cwd: '\\\\wsl.localhost\\Ubuntu\\home\\jin\\repo' + }) + + const spawnCall = spawnMock.mock.calls.at(-1)! + expect(spawnCall[0]).toBe('wsl.exe') + expect(spawnCall[2].env.CODEX_HOME).toBe('/home/jin/.codex-alt') + }) + it('does not inherit parent Orca pane identity when caller omits pane env', async () => { const saved = { ORCA_PANE_KEY: process.env.ORCA_PANE_KEY, diff --git a/src/main/providers/local-pty-provider.ts b/src/main/providers/local-pty-provider.ts index 202bcefeb..3b0b38fe6 100644 --- a/src/main/providers/local-pty-provider.ts +++ b/src/main/providers/local-pty-provider.ts @@ -31,6 +31,7 @@ import { STARTUP_COMMAND_READY_MAX_WAIT_MS } from './local-pty-shell-ready' import { removeInheritedNoColor } from '../pty/terminal-color-env' +import { isHostCodexHomeForWsl } from '../pty/codex-home-wsl-env' const PANE_IDENTITY_ENV_KEYS = ['ORCA_PANE_KEY', 'ORCA_TAB_ID', 'ORCA_WORKTREE_ID'] as const @@ -281,6 +282,15 @@ export class LocalPtyProvider implements IPtyProvider { } const finalEnv = this.opts.buildSpawnEnv ? this.opts.buildSpawnEnv(id, spawnEnv) : spawnEnv + if ( + process.platform === 'win32' && + pathWin32.basename(shellPath).toLowerCase() === 'wsl.exe' && + isHostCodexHomeForWsl(finalEnv.CODEX_HOME) + ) { + // Why: Orca's selected Codex runtime home is host-local. WSL Codex must + // use its Linux-side ~/.codex instead of inheriting a Windows path. + delete finalEnv.CODEX_HOME + } if (!wslInfo && process.platform !== 'win32') { // Why: any Orca-injected overlay env that user rc files can clobber // needs the wrapper so the post-rc restore line runs. diff --git a/src/main/pty/codex-home-wsl-env.test.ts b/src/main/pty/codex-home-wsl-env.test.ts new file mode 100644 index 000000000..c98958cbd --- /dev/null +++ b/src/main/pty/codex-home-wsl-env.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' +import { isHostCodexHomeForWsl } from './codex-home-wsl-env' + +describe('isHostCodexHomeForWsl', () => { + it('matches Windows paths that WSL Codex cannot use as CODEX_HOME', () => { + expect(isHostCodexHomeForWsl('C:\\Users\\jin\\.codex')).toBe(true) + expect(isHostCodexHomeForWsl('C:/Users/jin/.codex')).toBe(true) + expect(isHostCodexHomeForWsl('C:')).toBe(true) + expect(isHostCodexHomeForWsl('\\\\server\\share\\.codex')).toBe(true) + }) + + it('does not match Linux paths or empty values', () => { + expect(isHostCodexHomeForWsl('/home/jin/.codex')).toBe(false) + expect(isHostCodexHomeForWsl('')).toBe(false) + expect(isHostCodexHomeForWsl(undefined)).toBe(false) + }) +}) diff --git a/src/main/pty/codex-home-wsl-env.ts b/src/main/pty/codex-home-wsl-env.ts new file mode 100644 index 000000000..13efe2ad8 --- /dev/null +++ b/src/main/pty/codex-home-wsl-env.ts @@ -0,0 +1,7 @@ +export function isHostCodexHomeForWsl(value: string | undefined): boolean { + const trimmed = value?.trim() + if (!trimmed) { + return false + } + return /^[A-Za-z]:(?:[\\/]|$)/.test(trimmed) || trimmed.startsWith('\\\\') +} diff --git a/src/renderer/src/components/settings/AccountsPane.tsx b/src/renderer/src/components/settings/AccountsPane.tsx index 9da2052a6..768e7ef68 100644 --- a/src/renderer/src/components/settings/AccountsPane.tsx +++ b/src/renderer/src/components/settings/AccountsPane.tsx @@ -28,6 +28,7 @@ import { import { SearchableSetting } from './SearchableSetting' import { matchesSettingsSearch } from './settings-search' import { markLiveCodexSessionsForRestart } from '@/lib/codex-session-restart' +import { getLocalPreflightContext } from '@/lib/local-preflight-context' import { Dialog, DialogContent, @@ -111,6 +112,8 @@ function getClaudeAccountErrorDescription(error: unknown): string { export function AccountsPane({ settings, updateSettings }: AccountsPaneProps): React.JSX.Element { const searchQuery = useAppStore((s) => s.settingsSearchQuery) const fetchSettings = useAppStore((s) => s.fetchSettings) + const localPreflightContext = useAppStore(getLocalPreflightContext) + const activeWslDistro = localPreflightContext?.wslDistro?.trim() || null const [codexAccounts, setCodexAccounts] = useState({ accounts: [], @@ -422,6 +425,12 @@ export function AccountsPane({ settings, updateSettings }: AccountsPaneProps): R Optional. Orca can use your normal Codex login; add accounts only if you want quick switching in Orca.

+ {activeWslDistro ? ( +

+ WSL terminals use the Codex login inside {activeWslDistro}. Managed Codex account + switching applies to host terminals. +

+ ) : null}

Each account keeps its own local sign-in context in Orca. Account auth stays on this device. @@ -451,7 +460,9 @@ export function AccountsPane({ settings, updateSettings }: AccountsPaneProps): R

- Add a Codex account to use it in Orca. + {activeWslDistro + ? `Use codex login in ${activeWslDistro} to change the WSL Codex account.` + : 'Add a Codex account to use it in Orca.'}