Fix WSL Codex terminal environment (#2558)

This commit is contained in:
Jinwoo Hong
2026-05-21 17:29:46 -04:00
committed by GitHub
parent 77daf71386
commit da93f0d852
9 changed files with 193 additions and 7 deletions
+19
View File
@@ -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',
+16 -4
View File
@@ -339,14 +339,26 @@ export class WslCliInstaller {
}
async function runWslCommand(distro: string, command: string): Promise<string> {
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
}
+60
View File
@@ -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)
+9
View File
@@ -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.
@@ -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,
+10
View File
@@ -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.
+17
View File
@@ -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)
})
})
+7
View File
@@ -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('\\\\')
}
@@ -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<CodexRateLimitAccountsState>({
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.
</p>
{activeWslDistro ? (
<p className="text-xs text-muted-foreground">
WSL terminals use the Codex login inside {activeWslDistro}. Managed Codex account
switching applies to host terminals.
</p>
) : null}
<p className="text-xs text-muted-foreground">
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
<div className="space-y-0.5">
<Label>Accounts</Label>
<p className="text-xs text-muted-foreground">
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.'}
</p>
</div>
<Button
@@ -474,8 +485,9 @@ export function AccountsPane({ settings, updateSettings }: AccountsPaneProps): R
{codexAccounts.accounts.length === 0 ? (
<div className="rounded-md border border-dashed border-border/70 px-3 py-4 text-xs text-muted-foreground">
No managed Codex accounts yet. Orca will use your system default Codex login until you
add one here.
{activeWslDistro
? `No managed host Codex accounts yet. WSL terminals will use the Codex login in ${activeWslDistro}.`
: 'No managed Codex accounts yet. Orca will use your system default Codex login until you add one here.'}
</div>
) : (
<div className="space-y-2">