import { afterEach, describe, expect, test } from 'bun:test' import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import process from 'node:process' import { runCommand } from '../src/run' function isAlive(pid: number): boolean { try { process.kill(pid, 0) return true } catch { return false } } describe('runCommand timeout process-tree settlement (#3207)', () => { const dirs: string[] = [] const spawnedPids: number[] = [] afterEach(() => { for (const pid of spawnedPids.splice(0)) { try { process.kill(pid, 'SIGKILL') } catch {} } while (dirs.length > 0) rmSync(dirs.pop()!, { recursive: true, force: true }) }) test('settles TERM-ignoring shell, child, and grandchild before returning timeout Err', async () => { if (process.platform === 'win32') return const dir = mkdtempSync(join(tmpdir(), 'stacks-3207-')) dirs.push(dir) const pidFile = join(dir, 'pids.txt') const grandchildScript = join(dir, 'grandchild.sh') const childScript = join(dir, 'child.sh') const rootScript = join(dir, 'root.sh') writeFileSync(grandchildScript, `#!/bin/sh trap '' TERM echo "$$" >> ${JSON.stringify(pidFile)} sleep 30 `, { mode: 0o755 }) writeFileSync(childScript, `#!/bin/sh trap '' TERM echo "$$" >> ${JSON.stringify(pidFile)} /bin/sh ${JSON.stringify(grandchildScript)} & sleep 30 `, { mode: 0o755 }) writeFileSync(rootScript, `#!/bin/sh trap '' TERM echo "$$" >> ${JSON.stringify(pidFile)} /bin/sh ${JSON.stringify(childScript)} & sleep 30 `, { mode: 0o755 }) const result = await runCommand(['/bin/sh', rootScript], { cwd: dir, timeoutMs: 450, silent: true, }) expect(result.isErr).toBe(true) expect(result.isErr ? result.error.message : '').toContain('timed out') const recorded = readFileSync(pidFile, 'utf8') .trim() .split('\n') .map(Number) .filter(n => Number.isInteger(n) && n > 0) spawnedPids.push(...recorded) expect(recorded).toHaveLength(3) for (const pid of recorded) expect(isAlive(pid)).toBe(false) }, 15000) })