Files
orca/src/main/wsl.ts
T
Neil 4bc20cb842 fix(wsl): name an explicit Windows cwd for wsl.exe spawns (#17834)
* fix(wsl): name an explicit Windows cwd for wsl.exe spawns

Removing the worktree Orca was launched from broke every wsl.exe spawn for
the rest of the session. The WSL command builders passed `cwd: undefined`
meaning "the directory is inside the command" -- but CreateProcessW reads
NULL as "inherit the parent's", and the parent's was a \\wsl.localhost path
Linux had just deleted.

Fixes #16463

* fix(wsl): name the spawn directory at the six remaining wsl.exe sites

The first commit fixed the WSL command builders. Six spawn sites were left
inheriting the process cwd, which is the same deletable `\\wsl.localhost`
worktree: `wsl-availability` (both probes), the WSL filesystem watcher, the
agent-hook relay launch, the UNC delete, and the local worktree filesystem.

`wsl-availability` is the one that matters most, and it turns the bug into a
latching false negative. `isRetryableWslProbeFailure` returns false for ENOENT,
so a spawn that failed only because the inherited cwd was gone is cached as
"WSL is not installed" on the 10-minute definitive TTL with exponential
backoff up to 30 minutes. Git keeps working and Orca reports WSL unavailable --
worse than the bug being fixed.

ENOENT stays non-retryable. It is answer-shaped for the reason it is meant to
be -- wsl.exe is not on PATH -- and naming the directory is what removes the
one cause that was not. Making it retryable would instead re-probe every
non-WSL Windows machine on the short window, and would leave the false ENOENT
in place for the other five sites, which have no cache to correct.

Three of these are also on the `runWslProcess` W3 migration allowlist; this is
the interim until they move, and matches what #17837 does inside the runner.
2026-09-02 01:39:48 -07:00

407 lines
14 KiB
TypeScript

import { execFile, execFileSync } from 'node:child_process'
import { parseWslUncPath, toWindowsWslPath } from '../shared/wsl-paths'
import { filterUserWslDistros, parseWslDistros } from './wsl-distro-list-output'
import { wslDistroListRetryDelayMs } from './wsl-distro-retry'
import {
_resetWslAvailabilityCacheForTests,
_setWslAvailabilityCacheForTests,
dropStaleWslAvailabilityFailure
} from './wsl-availability'
import { resolveWslInteropSpawnCwd } from './wsl-interop-spawn-directory'
import {
_resetRunningWslDistroCacheForTests,
resolveRunningWslDistros
} from './wsl-running-distro-cache'
import {
getWslDirectoryProbeArgs,
parseWslDirectoryProbeOutput
} from './wsl-directory-probe-command'
// Why re-exported rather than defined here: the relay bundle needs the path
// conversion without this module's distro-probing subprocess graph.
export { toLinuxPath, toWindowsWslPath } from '../shared/wsl-paths'
export {
getCachedWslAvailability,
hasCachedWslAvailability,
isWslAvailable,
isWslAvailableAsync
} from './wsl-availability'
export type WslPathInfo = {
distro: string
linuxPath: string
}
/**
* Detect if a Windows path is a WSL UNC path and extract the distro name
* and equivalent Linux path.
*
* Why: Windows exposes WSL filesystems as UNC paths under \\wsl.localhost\<Distro>\...
* (modern) or \\wsl$\<Distro>\... (legacy). When a repo lives on a WSL filesystem,
* native Windows git.exe is either absent or painfully slow — all process spawning
* must be routed through `wsl.exe -d <distro>` with Linux-native paths instead.
*/
export function parseWslPath(windowsPath: string): WslPathInfo | null {
if (process.platform !== 'win32') {
return null
}
return parseWslUncPath(windowsPath)
}
export function isWslPath(path: string): boolean {
return parseWslPath(path) !== null
}
/**
* Check whether a WSL UNC working directory exists by testing it inside the
* distro itself, returning null when the answer can't be determined.
*
* Why: Win32 fs.statSync against the WSL 9P filesystem (\\wsl.localhost\...)
* is unreliable for repos that live on the WSL side — it can report ENOENT for
* directories that exist, which made opening a WSL worktree fail with
* "Working directory ... does not exist". The guest marker probe asks the
* distro directly, which is the authoritative answer. Returns null (rather
* than false) when wsl.exe is unavailable or errors so callers can fall back to
* the fs check instead of falsely rejecting a valid directory.
*/
export function wslUncDirectoryExists(uncPath: string): boolean | null {
if (process.platform !== 'win32') {
return null
}
const info = parseWslUncPath(uncPath)
if (!info) {
return null
}
try {
const stdout = execFileSync('wsl.exe', getWslDirectoryProbeArgs(info), {
stdio: ['pipe', 'pipe', 'pipe'],
timeout: 5000,
encoding: 'utf8',
cwd: resolveWslInteropSpawnCwd()
})
return parseWslDirectoryProbeOutput(stdout)
} catch {
return null
}
}
export function wslUncDirectoryExistsAsync(uncPath: string): Promise<boolean | null> {
if (process.platform !== 'win32') {
return Promise.resolve(null)
}
const info = parseWslUncPath(uncPath)
if (!info) {
return Promise.resolve(null)
}
return new Promise((resolve) => {
const probeOpts = { timeout: 5000, cwd: resolveWslInteropSpawnCwd() }
execFile('wsl.exe', getWslDirectoryProbeArgs(info), probeOpts, (_error, stdout) => {
// Why: wsl.exe uses numeric exits for both guest results and host failures; only the guest marker is authoritative.
resolve(parseWslDirectoryProbeOutput(stdout))
})
})
}
// ─── WSL home directory resolution ──────────────────────────────────
const wslHomeCache = new Map<string, string>()
const wslHomeProbeCache = new Map<string, Promise<string | null>>()
let wslDistroCache: string[] | null = null
let wslDistroListInFlight: Promise<string[]> | null = null
// Why: a wsl.exe failure must stay retryable (a transient error would
// otherwise hide every distro until restart), but repeated failures cannot
// re-spawn a blocking wsl.exe on every caller; brief negative caching bounds
// the spawn rate on machines where WSL is absent or persistently broken.
// Empty and failed probes back off from 15 seconds to a five-minute cap.
let wslDistroListRetryAfterMs = 0
let wslDistroListEmptyStreak = 0
let wslDistroProbeSequence = 0
let wslDistroCacheSequence = 0
function armWslDistroListRetry(): void {
const now = Date.now()
// Concurrent completions belong to the retry window already armed by the first result.
if (now < wslDistroListRetryAfterMs) {
return
}
wslDistroListEmptyStreak += 1
wslDistroListRetryAfterMs = now + wslDistroListRetryDelayMs(wslDistroListEmptyStreak)
}
// Why: `wsl --install` reports zero distros while one is still provisioning, so an
// empty answer is transient and must stay retryable — caching it for the process
// lifetime is what made WSL vanish from the picker after setup. It is still cached
// for reads, so a missing distro stays visible to `isKnownMissingDistro`.
function cacheWslDistroList(rawDistros: string[], probeSequence: number): string[] {
const userDistros = filterUserWslDistros(rawDistros)
// An older positive result must not replace the newer lifetime-stable list.
if (
probeSequence < wslDistroCacheSequence &&
(userDistros.length === 0 || (wslDistroCache?.length ?? 0) > 0)
) {
return wslDistroCache ?? []
}
// Why: probes overlap and can resolve out of order — a slow pre-registration wsl.exe
// can land after a fast one that already found the distro. A late empty answer must
// not erase that list, or provisioning reverts to "no distros" and backs off again.
if (userDistros.length === 0 && wslDistroCache !== null && wslDistroCache.length > 0) {
return wslDistroCache
}
if (userDistros.length > 0) {
dropStaleWslAvailabilityFailure()
}
wslDistroCacheSequence = probeSequence
wslDistroCache = userDistros
if (wslDistroCache.length === 0) {
armWslDistroListRetry()
}
return wslDistroCache
}
/** A non-empty list is stable; an empty one re-probes once the retry window elapses. */
function shouldReuseCachedWslDistros(): boolean {
return (
wslDistroCache !== null && (wslDistroCache.length > 0 || Date.now() < wslDistroListRetryAfterMs)
)
}
export function listWslDistros(): string[] {
if (shouldReuseCachedWslDistros()) {
return wslDistroCache ?? []
}
if (process.platform !== 'win32') {
wslDistroCache = []
return wslDistroCache
}
if (Date.now() < wslDistroListRetryAfterMs) {
return wslDistroCache ?? []
}
try {
const probeSequence = ++wslDistroProbeSequence
const output = execFileSync('wsl.exe', ['--list', '--quiet'], {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
timeout: 5000,
cwd: resolveWslInteropSpawnCwd()
})
return cacheWslDistroList(parseWslDistros(output), probeSequence)
} catch {
armWslDistroListRetry()
return wslDistroCache ?? []
}
}
export async function listWslDistrosAsync(): Promise<string[]> {
// A non-empty list is lifetime-stable, so never wait on a probe that cannot improve it.
if (wslDistroCache !== null && wslDistroCache.length > 0) {
return wslDistroCache
}
// Why ahead of the negative cache: a synchronous caller can land an empty result and arm
// the retry window mid-probe, and handing this caller that [] would strand it even though
// the pending probe is about to see the distro that just finished provisioning.
if (wslDistroListInFlight) {
return wslDistroListInFlight
}
if (shouldReuseCachedWslDistros()) {
return wslDistroCache ?? []
}
if (process.platform !== 'win32') {
wslDistroCache = []
return wslDistroCache
}
if (Date.now() < wslDistroListRetryAfterMs) {
return wslDistroCache ?? []
}
// Capability reads, CLI reconciliation and hook startup all ask before the first result
// lands; one host-wide answer must cost one wsl.exe spawn. `catch` sits ahead of the
// stored promise, so joiners get the same fail-safe [] a per-caller catch returned.
const probeSequence = ++wslDistroProbeSequence
const probe = execFileUtf8('wsl.exe', ['--list', '--quiet'])
.then((output) => cacheWslDistroList(parseWslDistros(output), probeSequence))
.catch(() => {
armWslDistroListRetry()
return wslDistroCache ?? []
})
.finally(() => {
// Only the probe that owns the slot may clear it; a test reset can install a newer one.
if (wslDistroListInFlight === probe) {
wslDistroListInFlight = null
}
})
wslDistroListInFlight = probe
return probe
}
/** Running user distros only — see `resolveRunningWslDistros` for the fallback/backoff and
* single-flight contract shared by every caller. */
export async function listRunningWslDistrosAsync(): Promise<string[]> {
if (process.platform !== 'win32') {
return []
}
return resolveRunningWslDistros(() =>
execFileUtf8('wsl.exe', ['--list', '--running', '--quiet'], {
...process.env,
WSL_UTF8: '1'
}).then((output) => filterUserWslDistros(parseWslDistros(output)))
)
}
export function hasCachedWslDistros(): boolean {
return wslDistroCache !== null
}
// Why: report the last observed answer even once it is stale. An empty list is a real
// probe result, so it must keep driving the `wsl-distro-missing` repair prompt; going
// null instead fails open and silently spawns `wsl.exe -d <distro>` for a distro Orca
// last saw was absent. Staleness self-corrects — `listWslDistros` re-probes after the
// retry window and a distro installed since clears the prompt on its own.
export function getCachedWslDistros(): string[] | null {
return wslDistroCache
}
export function getDefaultWslDistro(): string | null {
return listWslDistros()[0] ?? null
}
/**
* Get the home directory for a WSL distro, returned as a Windows UNC path.
* Result is cached per distro for the process lifetime.
*
* Why: worktrees for WSL repos are created under ~/orca/workspaces inside
* the WSL filesystem, mirroring the Windows workspace layout. We need the
* WSL user's $HOME to compute that path.
*/
export function getWslHome(distro: string): string | null {
if (wslHomeCache.has(distro)) {
return wslHomeCache.get(distro)!
}
try {
const home = execFileSync('wsl.exe', ['-d', distro, '--exec', 'bash', '-c', 'echo $HOME'], {
encoding: 'utf-8',
stdio: ['pipe', 'pipe', 'pipe'],
timeout: 5000,
cwd: resolveWslInteropSpawnCwd()
}).trim()
if (!home || !home.startsWith('/')) {
return null
}
const uncPath = toWindowsWslPath(home, distro)
wslHomeCache.set(distro, uncPath)
return uncPath
} catch {
return null
}
}
/** Pure cache lookup — never probes. Lets callers that memoize a derived value avoid caching one
* built from the unresolved fallback, since only the success path is cached above. */
export function hasCachedWslHome(distro: string): boolean {
return wslHomeCache.has(distro)
}
export async function getWslHomeAsync(distro: string): Promise<string | null> {
if (wslHomeCache.has(distro)) {
return wslHomeCache.get(distro)!
}
const inflight = wslHomeProbeCache.get(distro)
if (inflight) {
return inflight
}
const probe = execFileUtf8('wsl.exe', ['-d', distro, '--exec', 'bash', '-c', 'echo $HOME'])
.then((output) => {
const home = output.trim()
if (!home || !home.startsWith('/')) {
return null
}
const uncPath = toWindowsWslPath(home, distro)
wslHomeCache.set(distro, uncPath)
return uncPath
})
.catch(() => null)
.finally(() => {
if (wslHomeProbeCache.get(distro) === probe) {
wslHomeProbeCache.delete(distro)
}
})
wslHomeProbeCache.set(distro, probe)
return probe
}
/** UNC home roots for distros that are running at discovery time. */
export async function listRunningWslHomeDirsAsync(): Promise<string[]> {
const homes = await Promise.all(
(await listRunningWslDistrosAsync()).map((distro) => getWslHomeAsync(distro))
)
return homes.filter((home): home is string => Boolean(home))
}
// Both test entry points retire the pending probe with the cache it would write into;
// leaving it armed would let a retired probe answer the next test.
function resetWslDistroListState(): void {
wslDistroCache = null
wslDistroListInFlight = null
wslDistroListRetryAfterMs = 0
wslDistroListEmptyStreak = 0
wslDistroProbeSequence = 0
wslDistroCacheSequence = 0
}
export function _resetWslCachesForTests(): void {
wslHomeCache.clear()
wslHomeProbeCache.clear()
resetWslDistroListState()
_resetRunningWslDistroCacheForTests()
_resetWslAvailabilityCacheForTests()
}
// Why: seeded state expires like real state — an `available: false` seed is re-probed
// once its window lapses, and a `distros` seed is filtered and arms the retry window.
// Tests that advance timers past either window must mock child_process.
export function _setWslCachesForTests(args: {
available?: boolean | null
distros?: string[] | null
availabilityRetryable?: boolean
}): void {
_setWslAvailabilityCacheForTests(args.available, args.availabilityRetryable ?? false)
// Why: seed through the real cache path so an empty seed arms the retry window
// too — otherwise a seeded [] lets the next call spawn a real 5s wsl.exe.
resetWslDistroListState()
if (args.distros) {
cacheWslDistroList(args.distros, ++wslDistroProbeSequence)
}
}
function execFileUtf8(command: string, args: string[], env?: NodeJS.ProcessEnv): Promise<string> {
return new Promise((resolve, reject) => {
execFile(
command,
args,
{
encoding: 'utf-8',
env,
timeout: 5000,
windowsHide: true,
cwd: resolveWslInteropSpawnCwd()
},
(error, stdout) => {
if (error) {
reject(error)
return
}
resolve(stdout)
}
)
})
}