diff --git a/src/relay/fs-handler-list-files-ignored.test.ts b/src/relay/fs-handler-list-files-ignored.test.ts index 78244e214..fea487a49 100644 --- a/src/relay/fs-handler-list-files-ignored.test.ts +++ b/src/relay/fs-handler-list-files-ignored.test.ts @@ -159,6 +159,43 @@ describe('relay quick open ignored file listing', () => { } }) + it('rg file listing rejects and detaches when a timed-out child does not emit close', async () => { + vi.useFakeTimers() + try { + const primaryProc = createMockProcess() + const ignoredProc = createMockProcess() + let callIndex = 0 + + spawnMock.mockImplementation(() => { + callIndex++ + return callIndex === 1 ? primaryProc : ignoredProc + }) + + const promise = listFilesWithRg('/remote/root') + const outcomePromise = promise.then( + () => 'resolved', + (err: Error) => `rejected:${err.message}` + ) + + await vi.advanceTimersByTimeAsync(25_000) + const outcome = await Promise.race([outcomePromise, Promise.resolve('pending')]) + + expect(outcome).toBe('rejected:rg list timed out') + expect(primaryProc.kill).toHaveBeenCalled() + expect(ignoredProc.kill).toHaveBeenCalled() + expect((primaryProc.stdout as unknown as EventEmitter).listenerCount('data')).toBe(0) + expect((primaryProc.stderr as unknown as EventEmitter).listenerCount('data')).toBe(0) + expect(primaryProc.listenerCount('error')).toBe(0) + expect(primaryProc.listenerCount('close')).toBe(0) + expect((ignoredProc.stdout as unknown as EventEmitter).listenerCount('data')).toBe(0) + expect((ignoredProc.stderr as unknown as EventEmitter).listenerCount('data')).toBe(0) + expect(ignoredProc.listenerCount('error')).toBe(0) + expect(ignoredProc.listenerCount('close')).toBe(0) + } finally { + vi.useRealTimers() + } + }) + it('rg search settles and detaches when a timed-out child does not emit close', async () => { vi.useFakeTimers() try { diff --git a/src/relay/fs-handler-list-files.ts b/src/relay/fs-handler-list-files.ts index 9ccee533b..a28d6a8be 100644 --- a/src/relay/fs-handler-list-files.ts +++ b/src/relay/fs-handler-list-files.ts @@ -32,7 +32,11 @@ export function listFilesWithRg( return new Promise((resolve, reject) => { const files = new Set() let done = false - const children: ChildProcess[] = [] + const children: { + child: ChildProcess + isDone: () => boolean + reject: (error: Error) => void + }[] = [] const { primary, ignoredPass } = buildRgArgsForQuickOpen({ // Why: rg only applies root-relative exclude globs as traversal pruning @@ -75,22 +79,48 @@ export function listFilesWithRg( cwd: rootPath, stdio: ['ignore', 'pipe', 'pipe'] }) - children.push(child) - - const timer = setTimeout(() => { + let timer: ReturnType | null = null + const cleanup = (): void => { + if (timer) { + clearTimeout(timer) + timer = null + } + child.stdout!.off('data', handleStdoutData) + child.stderr!.off('data', handleStderrData) + child.off('error', handleError) + child.off('close', handleClose) + } + const rejectPass = (error: Error): void => { if (passDone) { return } passDone = true + passBuf = '' + cleanup() + passReject(error) + } + const resolvePass = (): void => { + if (passDone) { + return + } + passDone = true + cleanup() + passResolve() + } + children.push({ + child, + isDone: () => passDone, + reject: rejectPass + }) + + timer = setTimeout(() => { // Discard residual buffer on abnormal exit — a truncated byte // sequence could look like a valid path. - passBuf = '' child.kill() - passReject(new Error('rg list timed out')) + rejectPass(new Error('rg list timed out')) }, LIST_FILES_TIMEOUT_MS) - child.stdout!.setEncoding('utf-8') - child.stdout!.on('data', (chunk: string) => { + function handleStdoutData(chunk: string): void { passBuf += chunk let start = 0 let idx = passBuf.indexOf('\n', start) @@ -102,31 +132,22 @@ export function listFilesWithRg( idx = passBuf.indexOf('\n', start) } passBuf = start < passBuf.length ? passBuf.substring(start) : '' - }) - child.stderr!.on('data', () => { + } + function handleStderrData(): void { /* drain to prevent backpressure stalls */ - }) - child.once('error', (err) => { + } + function handleError(err: Error): void { + rejectPass(err) + } + function handleClose(code: number | null, signal: NodeJS.Signals | null): void { if (passDone) { return } - passDone = true - clearTimeout(timer) - passBuf = '' - passReject(err) - }) - child.once('close', (code, signal) => { - if (passDone) { - return - } - passDone = true - clearTimeout(timer) // Why signal != null is a failure: the only way spawn gets a signal // is if the process was killed (timeout, OOM, external SIGKILL). // Trusting its stdout could surface a truncated list as a success. if (signal) { - passBuf = '' - passReject(new Error(`rg killed by ${signal}`)) + rejectPass(new Error(`rg killed by ${signal}`)) return } // Flush residual line only on clean exit. @@ -141,13 +162,19 @@ export function listFilesWithRg( // (bad flag, invalid glob). Only trust exit 2 when rg emitted at // least one parseable path — otherwise treat it as a real failure. if (code === 0 || code === 1) { - passResolve() + resolvePass() } else if (code === 2 && passFileCount > 0) { - passResolve() + resolvePass() } else { - passReject(new Error(`rg exited with code ${code}`)) + rejectPass(new Error(`rg exited with code ${code}`)) } - }) + } + + child.stdout!.setEncoding('utf-8') + child.stdout!.on('data', handleStdoutData) + child.stderr!.on('data', handleStderrData) + child.once('error', handleError) + child.once('close', handleClose) }) const killSurvivors = (): void => { @@ -155,10 +182,14 @@ export function listFilesWithRg( // but the sibling rg keeps running up to LIST_FILES_TIMEOUT_MS. Kill it // so repeated Quick Open opens don't pile up orphan rg processes on the // remote. - for (const child of children) { - if (child.exitCode === null && child.signalCode === null) { - child.kill() + for (const entry of children) { + if (entry.isDone()) { + continue } + if (entry.child.exitCode === null && entry.child.signalCode === null) { + entry.child.kill() + } + entry.reject(new Error('rg list canceled after sibling failure')) } }