Files
archived-orca/src/main/startup/hydrate-shell-path.test.ts
T
Neil 4218d5068e fix(cli): seed nvm's default version, not the newest install (#16420)
* fix(cli): seed nvm's default version, not the newest install

#16314 stopped the login-shell probe inheriting the seeded PATH, but left the
seed itself picking the newest installed nvm version. That ordering decides
which node a CLI runs under whenever the probe does not land — a timeout, or a
login shell whose rc never initializes nvm — and newest is precisely the wrong
guess: it is usually the version the user just added and has installed nothing
into. That is the root cause reported in #10932.

Resolve `alias/default` instead, mirroring nvm: follow the alias chain
(`default` -> `lts/*` -> `lts/krypton` -> a version), resolve a partial version
like `24` to the highest matching install, and treat `system`/`node`/`stable`
as no preference. The chain is bounded and cycle-guarded because nvm's own
resolver tracks seen aliases and hand-edited files can point at each other.

Ordering is a preference, not a restriction: the remaining versions stay behind
the default, so a CLI installed outside it is still reachable.

Measured on a real machine with nvm default=24 and a bare v26.7.0 installed:
the old resolver seeds v26.7.0/bin (no CLIs), the new one seeds v24.18.0/bin
(every CLI). Tests were written first and verified to fail on the three bug
cases against main before the fix existed.

Also raise the probe budget from 5s to 10s. The old value was never measured
against a real profile: a bash -ilc loading nvm, rvm, conda and gcloud takes
~1s idle but 6-7s on a loaded machine, so a cold start under load silently
fell back to the seed. Startup does not block on the probe, and the one
awaited consumer is agent detection, which is better served by a probe that
finishes late than one that gives up early.

* fix(cli): reject non-version alias tokens instead of matching v0.x

Review finding, and a real bug I introduced. parseVersionSegment coerces
every unparseable segment to 0, so an unresolvable default alias — `garbage`,
`iojs`, `lts/nonexistent`, any hand-named alias — became [0] and prefix-matched
a `v0.12.x` install, or any stray non-version directory. Orca would then seed a
decade-old node as the preferred runtime. Real nvm answers N/A for all of them.

The `wanted.length === 0` bail could never have caught this: ''.split('.') is
[''], never empty. Replaced with a shape check that still admits legitimate
numeric prefixes — verified against nvm itself, which resolves `24` to
v24.18.0 and `0` to an installed v0.x while answering N/A for the rest.

Also corrects two comments that no longer described the code: the seed is no
longer "newest install", and the probe budget note claimed startup never blocks
on hydration, which is false on packaged Windows where it gates terminal
services and git. The traversal-guard comment claimed a containment join()
already normalizes away; the real guarantee is that matchNvmVersion can only
return an entry of the versions directory.

* fix(cli): match nvm's version-token grammar, not just its first character

Round-2 review finding, and the same bug one layer down. The previous guard
anchored only the first character, but parseInt stops at the first non-digit,
so `0x18`, `00` and `0abc` still parsed to [0] and prefix-matched a v0.12.x
install — the decade-old-node seed the earlier fix was supposed to close.

Reachable: `nvm alias default 0x18` warns that the version does not exist and
writes the alias anyway, then resolves it to N/A.

Use nvm's actual grammar, leading zeros included — nvm calls `00` and `024`
N/A while parseInt reads them as 0 and 24. Verified by executing 17 tokens
against a five-version fixture: every one now agrees with nvm, including the
legitimate prefixes `0`, `0.12`, `24` and `v24.18.0`.

Also drops a dead disjunct (the hop bound already caps the loop, so seen.size
can never exceed it) and corrects the log comment in index.ts, which still
told the reader a failed probe leaves the newest install in front. It leaves
the default version in front now, which is usually survivable but still not
what the shell would have resolved.

* test(cli): skip the lts/* chain fixture on Windows

Round-3 review finding. makeNvmHome materializes each alias as a real file,
and the chain case uses nvm's actual `lts/*` alias — `*` is a reserved Win32
filename character, so writeFileSync fails with EINVAL. PR CI runs a Windows
allowlist that excludes this file, so the breakage only reaches a Windows
developer running the suite locally.

Skipped rather than renamed: `lts/*` is the alias nvm really ships, and the
assertion pins platform: 'darwin' anyway, so the real name costs no coverage.
Matches the skipIf convention already used across src/shared.

Also reflows a comment line that a previous edit ran to 143 characters;
oxfmt does not reflow comments, so nothing would have caught it.
2026-08-25 03:05:24 -07:00

295 lines
10 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { EventEmitter } from 'node:events'
import { delimiter } from 'node:path'
import type { ChildProcessWithoutNullStreams } from 'node:child_process'
import {
_resetHydrateShellPathCache,
hydrateShellPath,
mergePathSegments,
_setLaunchPathForTests,
type HydrationResult
} from './hydrate-shell-path'
const { spawnMock } = vi.hoisted(() => ({
spawnMock: vi.fn()
}))
vi.mock('child_process', () => ({
spawn: spawnMock
}))
type HydrationSpawner = (shell: string) => Promise<HydrationResult>
function createMockShellProcess(): ChildProcessWithoutNullStreams {
const proc = new EventEmitter() as ChildProcessWithoutNullStreams
Object.assign(proc, {
stdout: new EventEmitter(),
stderr: new EventEmitter(),
stdin: new EventEmitter(),
kill: vi.fn()
})
return proc
}
describe('hydrateShellPath', () => {
const originalPath = process.env.PATH
beforeEach(() => {
_resetHydrateShellPathCache()
spawnMock.mockReset()
})
afterEach(() => {
vi.restoreAllMocks()
if (originalPath === undefined) {
delete process.env.PATH
} else {
process.env.PATH = originalPath
}
})
it('invokes the provided shell with a custom spawner and returns its segments', async () => {
let capturedShell = ''
const result = await hydrateShellPath({
shellOverride: '/bin/zsh',
spawner: async (shell) => {
capturedShell = shell
return {
segments: ['/Users/tester/.opencode/bin', '/Users/tester/.cargo/bin'],
ok: true,
failureReason: 'none'
}
}
})
expect(capturedShell).toBe('/bin/zsh')
expect(result.ok).toBe(true)
expect(result.segments).toEqual(['/Users/tester/.opencode/bin', '/Users/tester/.cargo/bin'])
expect(result.failureReason).toBe('none')
})
it('caches the hydration result so repeated calls do not re-spawn', async () => {
let spawnCount = 0
const spawner: HydrationSpawner = async () => {
spawnCount += 1
return { segments: ['/a'], ok: true, failureReason: 'none' }
}
await hydrateShellPath({ shellOverride: '/bin/zsh', spawner })
await hydrateShellPath({ shellOverride: '/bin/zsh', spawner })
await hydrateShellPath({ shellOverride: '/bin/zsh', spawner })
expect(spawnCount).toBe(1)
})
it('re-spawns when force:true is passed — matches the Refresh button contract', async () => {
let spawnCount = 0
const spawner: HydrationSpawner = async () => {
spawnCount += 1
return { segments: ['/a'], ok: true, failureReason: 'none' }
}
await hydrateShellPath({ shellOverride: '/bin/zsh', spawner })
await hydrateShellPath({ shellOverride: '/bin/zsh', spawner, force: true })
expect(spawnCount).toBe(2)
})
it('continues the probe queue after a rejected hydration', async () => {
const rejectedSpawner = vi.fn<HydrationSpawner>(async () => {
throw new Error('profile failed')
})
const successfulSpawner = vi.fn<HydrationSpawner>(async () => ({
segments: ['/current'],
ok: true,
failureReason: 'none'
}))
await expect(
hydrateShellPath({ shellOverride: '/bin/zsh', spawner: rejectedSpawner, force: true })
).rejects.toThrow('profile failed')
await expect(
hydrateShellPath({ shellOverride: '/bin/bash', spawner: successfulSpawner, force: true })
).resolves.toEqual({ segments: ['/current'], ok: true, failureReason: 'none' })
expect(successfulSpawner).toHaveBeenCalledWith('/bin/bash')
})
it('returns failureReason:no_shell when no shell is available (Windows path)', async () => {
const result = await hydrateShellPath({
shellOverride: null,
spawner: async () => {
throw new Error('spawner must not run when shell is null')
}
})
expect(result).toEqual({ segments: [], ok: false, failureReason: 'no_shell' })
})
// Why: each failure mode tagged independently so dashboards can pick the
// right fix (lengthen timeout vs investigate shell-invocation strategy vs
// surface a UX error). Spawner override stands in for the four resolve
// sites — the actual classification happens inside `spawnShellAndReadPath`,
// covered by the existing real-shell smoke surface.
it('propagates failureReason:timeout from the spawner', async () => {
const result = await hydrateShellPath({
shellOverride: '/bin/zsh',
spawner: async () => ({ segments: [], ok: false, failureReason: 'timeout' })
})
expect(result).toEqual({ segments: [], ok: false, failureReason: 'timeout' })
})
it('propagates failureReason:spawn_error from the spawner', async () => {
const result = await hydrateShellPath({
shellOverride: '/bin/zsh',
spawner: async () => ({ segments: [], ok: false, failureReason: 'spawn_error' })
})
expect(result).toEqual({ segments: [], ok: false, failureReason: 'spawn_error' })
})
it('propagates failureReason:empty_path from the spawner', async () => {
const result = await hydrateShellPath({
shellOverride: '/bin/zsh',
spawner: async () => ({ segments: [], ok: false, failureReason: 'empty_path' })
})
expect(result).toEqual({ segments: [], ok: false, failureReason: 'empty_path' })
})
it('cleans up shell listeners when hydration times out', async () => {
vi.useFakeTimers()
const proc = createMockShellProcess()
spawnMock.mockReturnValue(proc)
try {
const resultPromise = hydrateShellPath({ shellOverride: '/bin/zsh', force: true })
const assertion = expect(resultPromise).resolves.toEqual({
segments: [],
ok: false,
failureReason: 'timeout'
})
await vi.advanceTimersByTimeAsync(10_000)
await assertion
expect(proc.kill).toHaveBeenCalledWith('SIGKILL')
expect(proc.stdout.listenerCount('data')).toBe(0)
expect(proc.listenerCount('error')).toBe(0)
expect(proc.listenerCount('close')).toBe(0)
} finally {
vi.useRealTimers()
}
})
async function captureProbeEnv(shell = '/bin/bash'): Promise<NodeJS.ProcessEnv> {
const proc = createMockShellProcess()
spawnMock.mockReturnValue(proc)
const resultPromise = hydrateShellPath({ shellOverride: shell, force: true })
await vi.waitFor(() => expect(spawnMock).toHaveBeenCalled())
proc.emit('close', 0)
await resultPromise
return spawnMock.mock.calls[0][2].env
}
it('probes with the launch PATH so seeded fallbacks cannot pin nvm', async () => {
process.env.PATH = `/home/u/.nvm/versions/node/v26.7.0/bin${delimiter}/usr/bin`
_setLaunchPathForTests('/usr/bin')
expect((await captureProbeEnv()).PATH).toBe('/usr/bin')
})
it('uses the PATH captured at module load, not a later mutation of process.env', async () => {
// Why: this is the anti-regression guard. patchPackagedProcessPath mutates
// process.env.PATH after this module is evaluated; the probe must not see it.
const seeded = `/seeded/newest-nvm/bin${delimiter}/usr/bin`
process.env.PATH = seeded
expect((await captureProbeEnv()).PATH).not.toBe(seeded)
})
it('sets a probe marker so rc files can take a fast path', async () => {
expect((await captureProbeEnv()).ORCA_SHELL_PATH_PROBE).toBe('1')
})
it('overwrites the captured key in place so Windows never carries both Path and PATH', async () => {
vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
const originalWindowsPath = process.env.Path
delete process.env.PATH
process.env.PATH = 'C:\\Users\\u\\.nvm\\versions\\node\\v22.9.0\\bin;C:\\Windows'
process.env.Path = 'C:\\Users\\u\\.nvm\\versions\\node\\v22.9.0\\bin;C:\\Windows'
_setLaunchPathForTests('C:\\Windows', 'Path')
try {
const env = await captureProbeEnv('C:/Git/bin/bash.exe')
expect(env.Path).toBe('C:\\Windows')
expect(env.PATH).toBeUndefined()
} finally {
if (originalWindowsPath === undefined) {
delete process.env.Path
} else {
process.env.Path = originalWindowsPath
}
}
})
})
describe('mergePathSegments', () => {
const originalPath = process.env.PATH
beforeEach(() => {
_resetHydrateShellPathCache()
})
afterEach(() => {
if (originalPath === undefined) {
delete process.env.PATH
} else {
process.env.PATH = originalPath
}
})
// Why: mergePathSegments joins with the platform PATH delimiter, so the
// expectations must too — hardcoding ':' made this suite fail on Windows
// dev machines even though the code under test was correct.
const joinPath = (...segments: string[]): string => segments.join(delimiter)
it('prepends new segments ahead of existing PATH entries', () => {
process.env.PATH = joinPath('/usr/bin', '/bin')
const added = mergePathSegments(['/Users/tester/.opencode/bin', '/Users/tester/.cargo/bin'])
expect(added).toEqual(['/Users/tester/.opencode/bin', '/Users/tester/.cargo/bin'])
expect(process.env.PATH).toBe(
joinPath('/Users/tester/.opencode/bin', '/Users/tester/.cargo/bin', '/usr/bin', '/bin')
)
})
it('promotes shell segments already on PATH so shell ordering wins', () => {
process.env.PATH = joinPath('/Users/tester/.cargo/bin', '/usr/bin')
const added = mergePathSegments(['/Users/tester/.cargo/bin', '/Users/tester/.opencode/bin'])
expect(added).toEqual(['/Users/tester/.opencode/bin'])
expect(process.env.PATH).toBe(
joinPath('/Users/tester/.cargo/bin', '/Users/tester/.opencode/bin', '/usr/bin')
)
})
it('moves user-local shell paths ahead of packaged Homebrew fallbacks', () => {
process.env.PATH = joinPath('/opt/homebrew/bin', '/Users/tester/.local/bin', '/usr/bin', '/bin')
const added = mergePathSegments(['/Users/tester/.local/bin', '/opt/homebrew/bin'])
expect(added).toEqual([])
expect(process.env.PATH).toBe(
joinPath('/Users/tester/.local/bin', '/opt/homebrew/bin', '/usr/bin', '/bin')
)
})
it('returns [] and leaves PATH untouched when given nothing', () => {
process.env.PATH = joinPath('/usr/bin', '/bin')
expect(mergePathSegments([])).toEqual([])
expect(process.env.PATH).toBe(joinPath('/usr/bin', '/bin'))
})
})