Files
orca/src/main/ipc/pty-spawn-cwd-fallback.test.ts
T
Neil 9367169888 refactor(tests): split every oversized test file off the max-lines suppression list (#14728)
* refactor(tests): split oversized test files off the max-lines suppression list

Every `*.test.ts`/`*.spec.ts` that carried an `eslint/oxlint-disable max-lines`
directive is now split into focused, behavior-scoped suites that fit the 800-line
test budget, with shared setup extracted into co-located `*-test-harness.ts` /
`*-test-fixtures.ts` modules (300-line budget). 83 files became ~930; the largest
output is 797 effective lines. `orca-runtime.test.ts` is intentionally untouched.

Test bodies were moved by scripted line-range slicing rather than retyped, so
assertions are byte-identical. The only permitted body edits were mechanical
rebinding where a shared value moved into a harness (e.g. `tmpHome` ->
`homes.tmpHome`).

Registries that enumerate test files were updated in lockstep:
- config/max-lines-baseline.txt: pruned 341 -> 258 entries (all 83 removed).
- config/reliability-gates.jsonc: 33 gates repointed at the split files, with
  assertionRefs split per file where a gate's coverage now spans several.
- .github/workflows/pr.yml: the real-zsh lane now lists the 4 split files that
  actually exercise zsh, so they keep running in the dedicated shell lane.

Also renamed agent-hooks `server-test-fixtures.ts` to `server.test-fixtures.ts`
so the global-fetch call-site audit keeps skipping it, and added `.js` extensions
to the CLI suites' dynamic harness imports (node16 resolution) to unbreak
`build:cli`.

Verification: full suite 52,449 passing vs 52,448 at baseline with zero
assertions lost; `pnpm lint`, `pnpm typecheck`, and `pnpm build:cli` all exit 0;
the terminal-pane e2e spec runs 31/31 headless.

* refactor(tests): split hook-idle arbitration suite that oxfmt pushed over budget

The pre-commit oxfmt pass reflowed pty-connection-hook-idle-arbitration.test.ts
to 811 effective lines, 11 over the test budget. Split the hook-completion side
effect and replacement-agent veto cases into their own suite; both files now sit
well under the cap and the 15 tests are unchanged.

* test: port upstream test changes into the split files after rebase

Rebasing onto main surfaced 27 tests that main had added to files this branch
deleted, plus edits to tests that had already moved. Taking the deletion side of
those modify/delete conflicts would have dropped that coverage silently, so each
upstream change is ported into the split file that now owns the behavior — for
example main's six orchestration mailbox tests land across orchestration-runs,
-send, and -check.

Also repoints `orchestration.notification-mailbox-consistency`, a gate main added
after this branch's gate remap, at those same three split files, and re-prunes
the max-lines baseline against main's (257 entries).

Verified: all 27 upstream test titles present; full suite 52,761 passing with the
only diff vs baseline being 12 tests main itself removed and 3 that moved from
skipped to passing; lint and typecheck exit 0.

* fix(test): flush pending continuations before tearing down terminal test globals

CI shard 5/16 failed on both Node 24 and 26 with `ReferenceError: window is not
defined` from pty-connection.ts, surfacing through
pty-connection-daemon-snapshot-replay.test.ts.

The reattach/settle chains `await` a real promise and then touch `window.api`.
Under fake timers those continuations cannot run, so they only become schedulable
once restoreTerminalTestGlobals() switches back to real timers — which previously
happened immediately before `delete globalThis.window`, so a late continuation
threw and failed the whole file. Flush async ticks in that window instead.

This is latent in the source rather than new: the pre-split 25k-line file kept
running other tests after these, which gave the chains time to settle before
teardown. Splitting the file moved teardown directly behind them.

* fix(test): keep an inert window after terminal test teardown instead of deleting it

The async-tick flush was not enough: the reattach/settle chain can resolve after
teardown regardless of how long we drain, so CI shard 5/16 still failed with
`ReferenceError: window is not defined` from pty-connection.ts.

A real renderer never loses `window`, so deleting it was the artificial part.
Swap in an inert proxy whose properties resolve to callables and whose calls
resolve to undefined, making a late `window.api.pty.*` call a harmless no-op.
The next test replaces it wholesale via installTerminalTestGlobals(), and no test
asserts that `window` is absent.
2026-08-15 00:54:20 -07:00

367 lines
14 KiB
TypeScript

import { describe, expect, it, vi } from 'vitest'
import { statSyncMock, spawnMock, wslUncDirectoryExistsAsyncMock } from './pty-ipc-mock-registry'
import { setupPtyIpcSuite } from './pty-ipc-test-harness'
import { FLOATING_TERMINAL_WORKTREE_ID } from '../../shared/constants'
import { _setWslCachesForTests } from '../wsl'
import { acquireWatcherRemovalGate } from './watcher-removal-gate'
import { registerPtyHandlers, registerSshPtyProvider } from './pty'
vi.mock('electron', () => import('./pty-ipc-mock-registry').then((m) => m.electronModuleMock()))
vi.mock('fs', () => import('./pty-ipc-mock-registry').then((m) => m.fsModuleMock()))
vi.mock('node-pty', () => import('./pty-ipc-mock-registry').then((m) => m.nodePtyModuleMock()))
vi.mock('node:child_process', async (importOriginal) =>
(await import('./pty-ipc-mock-registry')).childProcessModuleMock(await importOriginal())
)
vi.mock('../opencode/hook-service', () =>
import('./pty-ipc-mock-registry').then((m) => m.openCodeHookServiceModuleMock())
)
vi.mock('../mimo/hook-service', () =>
import('./pty-ipc-mock-registry').then((m) => m.mimoHookServiceModuleMock())
)
vi.mock('../agent-hooks/server', () =>
import('./pty-ipc-mock-registry').then((m) => m.agentHookServerModuleMock())
)
vi.mock('../pi/titlebar-extension-service', () =>
import('./pty-ipc-mock-registry').then((m) => m.piTitlebarExtensionModuleMock())
)
vi.mock('../pwsh', () => import('./pty-ipc-mock-registry').then((m) => m.pwshModuleMock()))
vi.mock('../wsl', async (importOriginal) =>
(await import('./pty-ipc-mock-registry')).wslModuleMock(await importOriginal())
)
vi.mock('../telemetry/client', () =>
import('./pty-ipc-mock-registry').then((m) => m.telemetryClientModuleMock())
)
vi.mock('../telemetry/classify-error', () =>
import('./pty-ipc-mock-registry').then((m) => m.classifyErrorModuleMock())
)
vi.mock('../cli/linux-terminal-orca-cli-shim', () =>
import('./pty-ipc-mock-registry').then((m) => m.linuxCliShimModuleMock())
)
vi.mock('../memory/pty-registry', () =>
import('./pty-ipc-mock-registry').then((m) => m.ptyRegistryModuleMock())
)
vi.mock('../agent-hooks/migration-unsupported-pty-state', () =>
import('./pty-ipc-mock-registry').then((m) => m.migrationUnsupportedPtyModuleMock())
)
vi.mock('../codex/codex-pane-account-registry', () =>
import('./pty-ipc-mock-registry').then((m) => m.codexPaneAccountRegistryModuleMock())
)
vi.mock('../codex/codex-state-db-backfill-recovery', () =>
import('./pty-ipc-mock-registry').then((m) => m.codexBackfillRecoveryModuleMock())
)
describe('registerPtyHandlers', () => {
const { handlers, mainWindow, installDaemonTestProvider } = setupPtyIpcSuite()
it('passes floating terminal cwds through to the spawned shell', async () => {
// Why: the floating sentinel has no worktree root; its cwd is validated against trusted-directory grants before reaching pty:spawn.
registerPtyHandlers(mainWindow as never)
await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/tmp/floating-notes',
worktreeId: FLOATING_TERMINAL_WORKTREE_ID
})
const [, , options] = spawnMock.mock.calls.at(-1) as [string, string[], { cwd: string }]
expect(options.cwd).toBe('/tmp/floating-notes')
})
it('rejects a renderer spawn while destructive worktree removal holds the gate', async () => {
const removal = acquireWatcherRemovalGate('/repo/app')
await removal.ready
registerPtyHandlers(mainWindow as never)
try {
await expect(
handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
worktreeId: 'repo-1::/repo/app'
})
).rejects.toMatchObject({ code: 'terminal_removal_in_progress' })
expect(spawnMock).not.toHaveBeenCalled()
} finally {
removal.release()
}
})
it('rejects a sibling-worktree terminal cwd inside a worktree being removed', async () => {
const removal = acquireWatcherRemovalGate('/repo/app')
await removal.ready
registerPtyHandlers(mainWindow as never)
try {
await expect(
handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/repo/app/nested',
worktreeId: 'repo-1::/repo/sibling'
})
).rejects.toMatchObject({ code: 'terminal_removal_in_progress' })
expect(spawnMock).not.toHaveBeenCalled()
} finally {
removal.release()
}
const siblingRemoval = acquireWatcherRemovalGate('/repo/sibling')
await siblingRemoval.ready
siblingRemoval.release()
})
it('rejects a runtime sibling-worktree cwd inside a removing worktree', async () => {
const runtime = {
setPtyController: vi.fn(),
registerPty: vi.fn(),
onPtySpawned: vi.fn(),
onPtyExit: vi.fn(),
onPtyData: vi.fn()
}
registerPtyHandlers(mainWindow as never, runtime as never)
const controller = runtime.setPtyController.mock.calls[0]?.[0] as {
spawn(args: {
cols: number
rows: number
cwd?: string
worktreeId?: string
env?: Record<string, string>
}): Promise<{ id: string }>
}
const removal = acquireWatcherRemovalGate('/repo/app')
await removal.ready
try {
await expect(
controller.spawn({
cols: 80,
rows: 24,
cwd: '/repo/app/nested',
worktreeId: 'repo-1::/repo/sibling',
env: {}
})
).rejects.toMatchObject({ code: 'terminal_removal_in_progress' })
expect(spawnMock).not.toHaveBeenCalled()
} finally {
removal.release()
}
})
it('falls back to the worktree root when a saved local cwd no longer exists', async () => {
registerPtyHandlers(mainWindow as never)
// Why: issue #7239 reproduced in a Japanese-named worktree; the fallback must return the selected worktree path verbatim.
const worktreePath = '/Users/motoki/orca/workspaces/nakamuramotoki/Fableと議論'
const missingCwd = `${worktreePath}/deleted-folder`
statSyncMock.mockImplementation((target: string) => {
if (target === missingCwd) {
throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
}
return { isDirectory: () => true, mode: 0o755 }
})
const result = (await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: missingCwd,
cwdFallback: 'worktree',
worktreeId: `repo-1::${worktreePath}`
})) as { startupCwdFallback?: { kind: string; cwd: string } }
const [, , options] = spawnMock.mock.calls.at(-1) as [string, string[], { cwd: string }]
expect(options.cwd).toBe(worktreePath)
expect(result.startupCwdFallback).toEqual({ kind: 'worktree', cwd: worktreePath })
})
it.each(['/home/alice/repo', '/a', '/c'])(
'keeps an existing POSIX startup cwd for the selected WSL runtime (%s)',
async (startupCwd) => {
const originalPlatform = process.platform
const providerSpawn = vi.fn().mockResolvedValue({ id: 'pty-wsl-cwd' })
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
wslUncDirectoryExistsAsyncMock.mockResolvedValue(true)
statSyncMock.mockImplementation((target: string) => {
if (target === startupCwd) {
throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
}
return { isDirectory: () => true, mode: 0o755 }
})
try {
installDaemonTestProvider({ spawn: providerSpawn })
registerPtyHandlers(mainWindow as never)
await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: startupCwd,
cwdFallback: 'worktree',
worktreeId: 'repo-1::C:\\Users\\alice\\repo',
projectRuntime: {
status: 'resolved',
runtime: {
kind: 'wsl',
hostPlatform: 'wsl',
projectId: 'repo-1',
distro: 'Ubuntu-24.04',
reason: 'project-override',
cacheKey: 'repo-1:wsl'
}
}
})
const expectedValidationCwd = `\\\\wsl.localhost\\Ubuntu-24.04${startupCwd.replaceAll('/', '\\')}`
expect(statSyncMock).not.toHaveBeenCalledWith(startupCwd)
expect(wslUncDirectoryExistsAsyncMock).toHaveBeenCalledTimes(1)
expect(wslUncDirectoryExistsAsyncMock).toHaveBeenCalledWith(expectedValidationCwd)
expect(providerSpawn).toHaveBeenCalledWith(
expect.objectContaining({
cwd: startupCwd,
shellOverride: 'wsl.exe'
})
)
expect(providerSpawn).toHaveBeenCalledWith(
expect.not.objectContaining({ prevalidatedCwd: expect.anything() })
)
} finally {
Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform })
}
}
)
it('falls back when the selected WSL runtime reports a POSIX cwd missing', async () => {
const originalPlatform = process.platform
const providerSpawn = vi.fn().mockResolvedValue({ id: 'pty-wsl-missing-cwd' })
const worktreePath = 'C:/Users/alice/repo'
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
wslUncDirectoryExistsAsyncMock.mockResolvedValue(false)
try {
installDaemonTestProvider({ spawn: providerSpawn })
registerPtyHandlers(mainWindow as never)
const result = (await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/a',
cwdFallback: 'worktree',
worktreeId: `repo-1::${worktreePath}`,
projectRuntime: {
status: 'resolved',
runtime: {
kind: 'wsl',
hostPlatform: 'wsl',
projectId: 'repo-1',
distro: 'Ubuntu-24.04',
reason: 'project-override',
cacheKey: 'repo-1:wsl'
}
}
})) as { startupCwdFallback?: { kind: string; cwd: string } }
expect(wslUncDirectoryExistsAsyncMock).toHaveBeenCalledTimes(1)
expect(providerSpawn).toHaveBeenCalledWith(expect.objectContaining({ cwd: worktreePath }))
expect(providerSpawn).toHaveBeenCalledWith(
expect.not.objectContaining({ prevalidatedCwd: expect.anything() })
)
expect(result.startupCwdFallback).toEqual({ kind: 'worktree', cwd: worktreePath })
} finally {
Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform })
}
})
it('does not probe or forward local WSL cwd evidence for SSH fallback spawns', async () => {
const sshSpawn = vi.fn(async () => ({ id: 'ssh-wsl-looking-cwd' }))
registerSshPtyProvider('ssh-1', {
spawn: sshSpawn,
write: vi.fn(),
resize: vi.fn(),
shutdown: vi.fn(),
sendSignal: vi.fn(),
getCwd: vi.fn(),
getInitialCwd: vi.fn(),
clearBuffer: vi.fn(),
acknowledgeDataEvent: vi.fn(),
hasChildProcesses: vi.fn(),
getForegroundProcess: vi.fn(),
serialize: vi.fn(),
revive: vi.fn(),
onData: vi.fn(() => () => {}),
onReplay: vi.fn(() => () => {}),
onExit: vi.fn(() => () => {}),
listProcesses: vi.fn(async () => []),
attach: vi.fn(),
getDefaultShell: vi.fn(),
getProfiles: vi.fn()
} as never)
registerPtyHandlers(mainWindow as never)
await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/a',
cwdFallback: 'worktree',
connectionId: 'ssh-1',
worktreeId: 'repo-1::C:\\Users\\alice\\repo',
shellOverride: 'wsl.exe',
projectRuntime: {
status: 'resolved',
runtime: {
kind: 'wsl',
hostPlatform: 'wsl',
projectId: 'repo-1',
distro: 'Ubuntu-24.04',
reason: 'project-override',
cacheKey: 'repo-1:wsl'
}
}
})
expect(wslUncDirectoryExistsAsyncMock).not.toHaveBeenCalled()
expect(sshSpawn).toHaveBeenCalledWith(expect.objectContaining({ cwd: '/a' }))
expect(sshSpawn).toHaveBeenCalledWith(
expect.not.objectContaining({ prevalidatedCwd: expect.anything() })
)
})
it('preserves a POSIX WSL cwd when the distro probe is inconclusive', async () => {
const originalPlatform = process.platform
const providerSpawn = vi.fn().mockResolvedValue({ id: 'pty-wsl-inconclusive-cwd' })
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
wslUncDirectoryExistsAsyncMock.mockResolvedValue(null)
try {
installDaemonTestProvider({ spawn: providerSpawn })
registerPtyHandlers(mainWindow as never)
const result = (await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/a',
cwdFallback: 'worktree',
worktreeId: 'repo-1::C:/Users/alice/repo',
shellOverride: 'wsl.exe'
})) as { startupCwdFallback?: unknown }
expect(providerSpawn).toHaveBeenCalledWith(expect.objectContaining({ cwd: '/a' }))
expect(result.startupCwdFallback).toBeUndefined()
} finally {
Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform })
}
})
it('preserves a POSIX cwd when WSL owns it but no distro can be resolved', async () => {
const originalPlatform = process.platform
const providerSpawn = vi.fn().mockResolvedValue({ id: 'pty-wsl-no-distro-cwd' })
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
_setWslCachesForTests({ available: true, distros: [] })
try {
installDaemonTestProvider({ spawn: providerSpawn })
registerPtyHandlers(mainWindow as never)
const result = (await handlers.get('pty:spawn')!(null, {
cols: 80,
rows: 24,
cwd: '/c',
cwdFallback: 'worktree',
worktreeId: 'repo-1::C:/Users/alice/repo',
shellOverride: 'wsl.exe'
})) as { startupCwdFallback?: unknown }
expect(statSyncMock).not.toHaveBeenCalledWith('/c')
expect(wslUncDirectoryExistsAsyncMock).not.toHaveBeenCalled()
expect(providerSpawn).toHaveBeenCalledWith(expect.objectContaining({ cwd: '/c' }))
expect(result.startupCwdFallback).toBeUndefined()
} finally {
Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform })
}
})
})