From dc18ba9cda76da1358a41c5142a13246b71a56d7 Mon Sep 17 00:00:00 2001 From: Wooseong Kim <2222333+innocarpe@users.noreply.github.com> Date: Fri, 24 Jul 2026 16:27:40 +0900 Subject: [PATCH] fix(win): taskkill agent PTY descendant trees on stop (#10100) * fix(win): taskkill agent PTY descendant trees on stop Windows agent teardown previously degraded to shell-only kill because descendant snapshot is POSIX-only. Orphaned claude/codex/MCP children kept worktree cwd handles open and blocked worktree remove. Use taskkill /T /F on the PTY root in killWithDescendantSweep (daemon + local agent shutdown) so the ConPTY tree is cleared before teardown. Fixes #10004 * fix(win): bound taskkill with timeout and windowsHide Prevent a wedged taskkill from delaying killRoot, and hide the console flash during agent PTY tree teardown (CodeRabbit on #10100). --- src/main/providers/local-pty-provider.test.ts | 86 +++++++++++-------- src/main/providers/local-pty-provider.ts | 26 +++--- src/main/pty-descendant-termination.test.ts | 49 +++++++++++ src/main/pty-descendant-termination.ts | 39 +++++++-- src/main/windows-process-tree-kill.test.ts | 55 ++++++++++++ src/main/windows-process-tree-kill.ts | 35 ++++++++ 6 files changed, 235 insertions(+), 55 deletions(-) create mode 100644 src/main/windows-process-tree-kill.test.ts create mode 100644 src/main/windows-process-tree-kill.ts diff --git a/src/main/providers/local-pty-provider.test.ts b/src/main/providers/local-pty-provider.test.ts index 0ef13db58..00767a29d 100644 --- a/src/main/providers/local-pty-provider.test.ts +++ b/src/main/providers/local-pty-provider.test.ts @@ -13,8 +13,7 @@ const { prepareMacosTccLoginShellMock, resolveAgentForegroundProcessMock, readWindowsConptyProcessIdsMock, - captureDescendantSnapshotMock, - terminateDescendantSnapshotMock + killWithDescendantSweepMock } = vi.hoisted(() => ({ existsSyncMock: vi.fn(), statSyncMock: vi.fn(), @@ -25,8 +24,7 @@ const { prepareMacosTccLoginShellMock: vi.fn(), resolveAgentForegroundProcessMock: vi.fn(), readWindowsConptyProcessIdsMock: vi.fn(), - captureDescendantSnapshotMock: vi.fn(), - terminateDescendantSnapshotMock: vi.fn() + killWithDescendantSweepMock: vi.fn() })) vi.mock('fs', () => ({ @@ -55,8 +53,7 @@ vi.mock('./macos-tcc-login-shell', async (importOriginal) => ({ })) vi.mock('../pty-descendant-termination', () => ({ - captureDescendantSnapshot: captureDescendantSnapshotMock, - terminateDescendantSnapshot: terminateDescendantSnapshotMock + killWithDescendantSweep: killWithDescendantSweepMock })) // Resolve PowerShell family names to deterministic absolute paths (the fs mock @@ -150,9 +147,13 @@ describe('LocalPtyProvider', () => { accessSyncMock.mockReturnValue(undefined) mkdirSyncMock.mockReset() writeFileSyncMock.mockReset() - captureDescendantSnapshotMock.mockReset() - captureDescendantSnapshotMock.mockResolvedValue(null) - terminateDescendantSnapshotMock.mockReset() + killWithDescendantSweepMock.mockReset() + // Default: no-op sweep that still runs killRoot (matches empty-snapshot degrade). + killWithDescendantSweepMock.mockImplementation( + async (_rootPid: number, killRoot: () => void, _deps?: { ownsRoot?: () => boolean }) => { + killRoot() + } + ) prepareMacosTccLoginShellMock.mockReset() prepareMacosTccLoginShellMock.mockResolvedValue(undefined) resolveAgentForegroundProcessMock.mockReset() @@ -1425,11 +1426,15 @@ describe('LocalPtyProvider', () => { }) it('waits for an in-flight agent shutdown before reusing the same session id', async () => { - let resolveSnapshot!: (value: null) => void - captureDescendantSnapshotMock.mockReturnValue( - new Promise((resolve) => { - resolveSnapshot = resolve - }) + let releaseSweep!: () => void + killWithDescendantSweepMock.mockImplementation( + (_rootPid: number, killRoot: () => void) => + new Promise((resolve) => { + releaseSweep = () => { + killRoot() + resolve() + } + }) ) const spawnArgs = { cols: 80, @@ -1445,18 +1450,22 @@ describe('LocalPtyProvider', () => { await Promise.resolve() expect(spawnMock).toHaveBeenCalledTimes(spawnCallsBefore + 1) - resolveSnapshot(null) + releaseSweep() await shutdown await respawn expect(spawnMock).toHaveBeenCalledTimes(spawnCallsBefore + 2) }) - it('coalesces duplicate shutdown while descendant capture is pending', async () => { - let resolveSnapshot!: (value: null) => void - captureDescendantSnapshotMock.mockReturnValue( - new Promise((resolve) => { - resolveSnapshot = resolve - }) + it('coalesces duplicate shutdown while descendant sweep is pending', async () => { + let releaseSweep!: () => void + killWithDescendantSweepMock.mockImplementation( + (_rootPid: number, killRoot: () => void) => + new Promise((resolve) => { + releaseSweep = () => { + killRoot() + resolve() + } + }) ) const { id } = await provider.spawn({ cols: 80, @@ -1466,22 +1475,27 @@ describe('LocalPtyProvider', () => { const first = provider.shutdown(id, { immediate: true }) const second = provider.shutdown(id, { immediate: true }) - expect(captureDescendantSnapshotMock).toHaveBeenCalledOnce() - resolveSnapshot(null) + expect(killWithDescendantSweepMock).toHaveBeenCalledOnce() + releaseSweep() await Promise.all([first, second]) - expect(captureDescendantSnapshotMock).toHaveBeenCalledOnce() + expect(killWithDescendantSweepMock).toHaveBeenCalledOnce() }) - it('does not signal a captured tree after the tracked root exits naturally', async () => { - let resolveSnapshot!: (value: { - rootPgid: number - descendants: [] - capturedAtMs: number - }) => void - captureDescendantSnapshotMock.mockReturnValue( - new Promise((resolve) => { - resolveSnapshot = resolve - }) + it('does not terminate descendants after the tracked root exits mid-sweep', async () => { + const terminateDescendants = vi.fn() + let releaseSweep!: () => void + killWithDescendantSweepMock.mockImplementation( + (_rootPid: number, killRoot: () => void, deps?: { ownsRoot?: () => boolean }) => + new Promise((resolve) => { + releaseSweep = () => { + // Production killWithDescendantSweep only signals descendants while ownsRoot. + if (deps?.ownsRoot?.() ?? true) { + terminateDescendants() + } + killRoot() + resolve() + } + }) ) const { id } = await provider.spawn({ cols: 80, @@ -1491,10 +1505,10 @@ describe('LocalPtyProvider', () => { const shutdown = provider.shutdown(id, { immediate: true }) exitCb?.({ exitCode: 0 }) - resolveSnapshot({ rootPgid: mockProc.pid, descendants: [], capturedAtMs: Date.now() }) + releaseSweep() await shutdown - expect(terminateDescendantSnapshotMock).not.toHaveBeenCalled() + expect(terminateDescendants).not.toHaveBeenCalled() }) }) diff --git a/src/main/providers/local-pty-provider.ts b/src/main/providers/local-pty-provider.ts index 1eef45e63..8f0a10e7b 100644 --- a/src/main/providers/local-pty-provider.ts +++ b/src/main/providers/local-pty-provider.ts @@ -55,10 +55,7 @@ import { resolveAgentForegroundProcessWithAvailability } from './agent-foregroun import { resolveStableForegroundProcess } from './stable-foreground-process' import { getAgentForegroundContextPaths } from './agent-foreground-context-paths' import { recognizeAgentProcessFromCommandLine } from '../../shared/agent-process-recognition' -import { - captureDescendantSnapshot, - terminateDescendantSnapshot -} from '../pty-descendant-termination' +import { killWithDescendantSweep } from '../pty-descendant-termination' import { readWindowsConptyProcessIds } from './windows-conpty-process-membership' import { canConfirmAgentFromConsolePresence } from './windows-console-foreground' import { forceKillPosixPtyProcessGroups } from '../pty/posix-pty-process-groups' @@ -1115,20 +1112,25 @@ export class LocalPtyProvider implements IPtyProvider { operation: PtyShutdownOperation ): Promise { const physicalExit = ptyPhysicalExits.get(id) - // Why: snapshot before signaling — once the shell dies, descendants reparent to pid 1 and a ppid walk can't find them. - const descendants = ptyAgentSessionIds.has(id) - ? await captureDescendantSnapshot(proc.pid) - : null - // Why: a natural exit can race the snapshot — never signal descendants or the root PID after this PTY loses ownership. - if (ptyProcesses.get(id) === proc) { - if (descendants) { - terminateDescendantSnapshot(descendants) + const signalRoot = (): void => { + // Why: natural exit can race the sweep — never signal after this PTY loses ownership. + if (ptyProcesses.get(id) !== proc) { + return } // Cancel startup delivery now, but keep the exit listener and ownership maps until node-pty reports physical exit. runPtyCleanup(id) operation.rootSignalled = true this.requestTrackedPtyShutdown(id, proc, operation.immediate) } + if (ptyAgentSessionIds.has(id)) { + // Why: POSIX needs a pre-kill descendant snapshot; Windows uses taskkill /T so + // agent/MCP orphans cannot hold the worktree cwd after shell stop (#10004). + await killWithDescendantSweep(proc.pid, signalRoot, { + ownsRoot: () => ptyProcesses.get(id) === proc + }) + } else { + signalRoot() + } await waitForPtyPhysicalExit(id, physicalExit) } diff --git a/src/main/pty-descendant-termination.test.ts b/src/main/pty-descendant-termination.test.ts index 593693491..3955e0329 100644 --- a/src/main/pty-descendant-termination.test.ts +++ b/src/main/pty-descendant-termination.test.ts @@ -393,6 +393,55 @@ describe('killWithDescendantSweep', () => { expect(sendSignal).not.toHaveBeenCalled() }) + it('on Windows taskkills the process tree before killRoot (#10004)', async () => { + const events: string[] = [] + const killWindowsTree = vi.fn(async () => { + events.push('tree-kill') + }) + const killRoot = vi.fn(() => events.push('root-kill')) + const sendSignal = vi.fn() + const readTable = vi.fn() + await killWithDescendantSweep(4242, killRoot, { + platform: 'win32', + killWindowsTree, + sendSignal, + readTable + }) + expect(killWindowsTree).toHaveBeenCalledWith(4242) + expect(killRoot).toHaveBeenCalledOnce() + expect(sendSignal).not.toHaveBeenCalled() + expect(readTable).not.toHaveBeenCalled() + expect(events).toEqual(['tree-kill', 'root-kill']) + }) + + it('on Windows still kills the root when ownership is lost mid-sweep', async () => { + const killWindowsTree = vi.fn(async () => { + throw new Error('should not run') + }) + const killRoot = vi.fn() + await killWithDescendantSweep(4242, killRoot, { + platform: 'win32', + killWindowsTree, + ownsRoot: () => false + }) + expect(killWindowsTree).not.toHaveBeenCalled() + expect(killRoot).toHaveBeenCalledOnce() + }) + + it('on Windows still kills the root when taskkill fails', async () => { + const killWindowsTree = vi.fn(async () => { + throw new Error('taskkill failed') + }) + const killRoot = vi.fn() + await expect( + killWithDescendantSweep(99, killRoot, { + platform: 'win32', + killWindowsTree + }) + ).resolves.toBeUndefined() + expect(killRoot).toHaveBeenCalledOnce() + }) + it('does not signal a captured tree after the caller loses root ownership', async () => { const sendSignal = vi.fn() const killRoot = vi.fn() diff --git a/src/main/pty-descendant-termination.ts b/src/main/pty-descendant-termination.ts index 3683df753..6bd162553 100644 --- a/src/main/pty-descendant-termination.ts +++ b/src/main/pty-descendant-termination.ts @@ -1,4 +1,5 @@ import { execFile } from 'node:child_process' +import { terminateWindowsProcessTree, type WindowsTreeKiller } from './windows-process-tree-kill' export const DESCENDANT_KILL_GRACE_MS = 2_000 export const DESCENDANT_SNAPSHOT_TIMEOUT_MS = 1_000 @@ -198,8 +199,8 @@ type SnapshotDeps = { * Snapshots a PTY root's live descendant tree. Must run BEFORE the root is * signalled: once the root dies, surviving descendants reparent to pid 1 and * can no longer be found by a ppid walk. Resolves null (never rejects) on - * Windows, ps failure, or timeout — callers then degrade to today's - * shell-only kill. + * Windows, ps failure, or timeout — callers then degrade to shell-only kill + * on POSIX, or Windows `taskkill /T` via killWithDescendantSweep. */ export async function captureDescendantSnapshot( rootPid: number, @@ -220,17 +221,41 @@ export async function captureDescendantSnapshot( return collectDescendantRows(rootPid, capture.rows, capture.capturedAtMs) } +type KillSweepDeps = SnapshotDeps & + TerminateDeps & { + ownsRoot?: () => boolean + /** Injectable Windows tree killer (defaults to taskkill /T /F). */ + killWindowsTree?: WindowsTreeKiller + } + /** - * Standard agent-session kill sequencing: snapshot the descendant tree, - * signal its members, then run the caller's root kill. Callers must not signal - * the root before this runs — a dead root's descendants reparent to pid 1 and - * become unfindable. Snapshot failure degrades to killRoot alone. + * Standard agent-session kill sequencing. + * - POSIX: snapshot the descendant tree, signal members, then killRoot. + * - Windows: taskkill /T /F walks the ConPTY tree (shell → agent → MCP) so + * worktree teardown is not blocked by orphans holding the cwd handle. + * Callers must not signal the root before this runs on POSIX — a dead root's + * descendants reparent to pid 1 and become unfindable. Snapshot failure + * degrades to killRoot alone on POSIX. */ export async function killWithDescendantSweep( rootPid: number, killRoot: () => void, - deps: SnapshotDeps & TerminateDeps & { ownsRoot?: () => boolean } = {} + deps: KillSweepDeps = {} ): Promise { + const platform = deps.platform ?? process.platform + if (platform === 'win32') { + try { + if ((deps.ownsRoot?.() ?? true) && Number.isInteger(rootPid) && rootPid > 0) { + const killTree = deps.killWindowsTree ?? terminateWindowsProcessTree + // Why: taskkill may race an already-exited tree; never block killRoot on that. + await killTree(rootPid).catch(() => {}) + } + } finally { + killRoot() + } + return + } + const snapshot = await captureDescendantSnapshot(rootPid, deps) try { // Signal the captured descendants while their parent links still exist; diff --git a/src/main/windows-process-tree-kill.test.ts b/src/main/windows-process-tree-kill.test.ts new file mode 100644 index 000000000..0e6cbb739 --- /dev/null +++ b/src/main/windows-process-tree-kill.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it, vi } from 'vitest' +import { + terminateWindowsProcessTree, + WINDOWS_PROCESS_TREE_KILL_TIMEOUT_MS +} from './windows-process-tree-kill' + +describe('terminateWindowsProcessTree', () => { + it('invokes taskkill /T /F with timeout and windowsHide', async () => { + const execFileImpl = vi.fn( + ( + _cmd: string, + _args: readonly string[], + _options: { timeout?: number; windowsHide?: boolean }, + callback: (error: Error | null) => void + ) => { + callback(null) + } + ) + await terminateWindowsProcessTree(1234, { + execFileImpl: execFileImpl as never + }) + expect(execFileImpl).toHaveBeenCalledWith( + 'taskkill', + ['/pid', '1234', '/T', '/F'], + { + timeout: WINDOWS_PROCESS_TREE_KILL_TIMEOUT_MS, + windowsHide: true + }, + expect.any(Function) + ) + }) + + it('resolves even when taskkill reports failure (already dead)', async () => { + const execFileImpl = vi.fn( + ( + _cmd: string, + _args: readonly string[], + _options: { timeout?: number; windowsHide?: boolean }, + callback: (error: Error | null) => void + ) => { + callback(new Error('not found')) + } + ) + await expect( + terminateWindowsProcessTree(55, { execFileImpl: execFileImpl as never }) + ).resolves.toBeUndefined() + }) + + it('skips taskkill for invalid pids', async () => { + const execFileImpl = vi.fn() + await terminateWindowsProcessTree(0, { execFileImpl: execFileImpl as never }) + await terminateWindowsProcessTree(-1, { execFileImpl: execFileImpl as never }) + expect(execFileImpl).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/windows-process-tree-kill.ts b/src/main/windows-process-tree-kill.ts new file mode 100644 index 000000000..44085692d --- /dev/null +++ b/src/main/windows-process-tree-kill.ts @@ -0,0 +1,35 @@ +import { execFile } from 'node:child_process' + +export type WindowsTreeKiller = (rootPid: number) => Promise + +/** Bound hung taskkill so killRoot still runs in killWithDescendantSweep. */ +export const WINDOWS_PROCESS_TREE_KILL_TIMEOUT_MS = 5_000 + +/** + * Force-kill a Windows process and every descendant (`taskkill /T /F`). + * Best-effort: missing/already-dead roots still resolve so callers can finish + * their own handle cleanup via killRoot. + */ +export function terminateWindowsProcessTree( + rootPid: number, + deps: { execFileImpl?: typeof execFile } = {} +): Promise { + if (!Number.isInteger(rootPid) || rootPid <= 0) { + return Promise.resolve() + } + const run = deps.execFileImpl ?? execFile + return new Promise((resolve) => { + run( + 'taskkill', + ['/pid', String(rootPid), '/T', '/F'], + { + // Why: a wedged taskkill must not block killRoot forever (#10004 review). + timeout: WINDOWS_PROCESS_TREE_KILL_TIMEOUT_MS, + windowsHide: true + }, + () => { + resolve() + } + ) + }) +}