mirror of
https://github.com/wu736139669/hapi.git
synced 2026-12-05 07:07:04 +00:00
merge: hapi upstream main 2026-10-19 (34 commits past v0.30.7)
Bring in the post-0.30.7 upstream work while keeping local team, macaron, requirement, DSH and deployment features: - runner/hub: cross-platform orphan reap on archive and tracking loss, machine-spawn preallocated stubs, keepalive-only sessions reconcile to idle - hub: prepared-statement cache, stale/canceled permission request handling - cli: Codex compaction announcements, dynamic Kimi models, MCP bridge reap - web: session toolbar icon shedding, mark-all-read, unread/active sections, Russian locale, external-link preference, 48px search chrome - ios/android: locale and font-size updates Conflict resolution keeps local-only behavior (agent team spawns, macaron skins, collapsible sidebar, workspace markdown images) layered on the new upstream toolbar and session lifecycle plumbing. Test infrastructure: skip the Docker-only pwsh integration test quickly when Docker is unavailable, and exclude the Bun-only usageScan test from vitest. via [HAPI](https://hapi.run) Co-Authored-By: HAPI <noreply@hapi.run> Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
+563
-44
@@ -10,7 +10,7 @@ vi.mock('cross-spawn', () => ({
|
||||
}
|
||||
}))
|
||||
|
||||
import { getHapiRunnerProcessIdentity } from './process'
|
||||
import { getHapiRunnerProcessIdentity, killProcess } from './process'
|
||||
|
||||
const originalPlatformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')
|
||||
|
||||
@@ -50,6 +50,11 @@ describe('getHapiRunnerProcessIdentity on Windows', () => {
|
||||
beforeEach(() => {
|
||||
setPlatform('win32')
|
||||
spawnSyncMock.mockReset()
|
||||
// Prefer signal-0 probe in these identity tests: tasklist falls through.
|
||||
spawnSyncMock.mockImplementation((cmd: string, ...rest: unknown[]) => {
|
||||
if (cmd === 'tasklist') return unavailable('tasklist')
|
||||
return completed('')
|
||||
})
|
||||
vi.spyOn(process, 'kill').mockReturnValue(true)
|
||||
})
|
||||
|
||||
@@ -64,77 +69,85 @@ describe('getHapiRunnerProcessIdentity on Windows', () => {
|
||||
})
|
||||
|
||||
it('reports a foreign process when CIM identifies it', () => {
|
||||
spawnSyncMock.mockReturnValueOnce(completed('C:\\Windows\\System32\\conhost.exe'))
|
||||
spawnSyncMock.mockImplementation((cmd: string, args?: string[]) => {
|
||||
if (cmd === 'tasklist') return unavailable('tasklist')
|
||||
if (cmd === 'powershell') return completed('C:\\Windows\\System32\\conhost.exe')
|
||||
return completed('')
|
||||
})
|
||||
|
||||
expect(getHapiRunnerProcessIdentity(8328)).toBe('foreign')
|
||||
expect(spawnSyncMock).toHaveBeenCalledTimes(1)
|
||||
expect(spawnSyncMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'powershell',
|
||||
[
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-Command',
|
||||
'(Get-CimInstance Win32_Process -Filter "ProcessId = 8328").CommandLine'
|
||||
],
|
||||
{ stdio: 'pipe', windowsHide: true }
|
||||
)
|
||||
expect(spawnSyncMock.mock.calls.some((call) => call[0] === 'powershell')).toBe(true)
|
||||
})
|
||||
|
||||
it('reports the runner when CIM identifies it', () => {
|
||||
spawnSyncMock.mockReturnValueOnce(completed('hapi-local.exe runner start-sync'))
|
||||
spawnSyncMock.mockImplementation((cmd: string) => {
|
||||
if (cmd === 'tasklist') return unavailable('tasklist')
|
||||
if (cmd === 'powershell') return completed('hapi-local.exe runner start-sync')
|
||||
return completed('')
|
||||
})
|
||||
|
||||
expect(getHapiRunnerProcessIdentity(9124)).toBe('runner')
|
||||
})
|
||||
|
||||
it('falls back to WMIC when PowerShell is unavailable', () => {
|
||||
spawnSyncMock
|
||||
.mockReturnValueOnce(unavailable('powershell'))
|
||||
.mockReturnValueOnce(completed('hapi-local.exe runner start-sync'))
|
||||
spawnSyncMock.mockImplementation((cmd: string) => {
|
||||
if (cmd === 'tasklist') return unavailable('tasklist')
|
||||
if (cmd === 'powershell') return unavailable('powershell')
|
||||
if (cmd === 'wmic') return completed('hapi-local.exe runner start-sync')
|
||||
return completed('')
|
||||
})
|
||||
|
||||
expect(getHapiRunnerProcessIdentity(9124)).toBe('runner')
|
||||
expect(spawnSyncMock).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'wmic',
|
||||
['process', 'where', 'ProcessId=9124', 'get', 'CommandLine'],
|
||||
{ stdio: 'pipe', windowsHide: true }
|
||||
)
|
||||
expect(spawnSyncMock.mock.calls.some((call) => call[0] === 'wmic')).toBe(true)
|
||||
})
|
||||
|
||||
it('falls back to WMIC when CIM reports no command line', () => {
|
||||
spawnSyncMock
|
||||
.mockReturnValueOnce(completed(''))
|
||||
.mockReturnValueOnce(completed('CommandLine\r\nhapi-local.exe runner start-sync\r\n'))
|
||||
let powershellCalls = 0
|
||||
spawnSyncMock.mockImplementation((cmd: string) => {
|
||||
if (cmd === 'tasklist') return unavailable('tasklist')
|
||||
if (cmd === 'powershell') {
|
||||
powershellCalls += 1
|
||||
return completed('')
|
||||
}
|
||||
if (cmd === 'wmic') return completed('CommandLine\r\nhapi-local.exe runner start-sync\r\n')
|
||||
return completed('')
|
||||
})
|
||||
|
||||
expect(getHapiRunnerProcessIdentity(9124)).toBe('runner')
|
||||
expect(spawnSyncMock).toHaveBeenCalledTimes(2)
|
||||
expect(spawnSyncMock.mock.calls.some((call) => call[0] === 'wmic')).toBe(true)
|
||||
})
|
||||
|
||||
it('reports unknown when WMIC prints only the column header', () => {
|
||||
spawnSyncMock
|
||||
.mockReturnValueOnce(completed(''))
|
||||
.mockReturnValueOnce(completed('CommandLine\r\n\r\n'))
|
||||
spawnSyncMock.mockImplementation((cmd: string) => {
|
||||
if (cmd === 'tasklist') return unavailable('tasklist')
|
||||
if (cmd === 'powershell') return completed('')
|
||||
if (cmd === 'wmic') return completed('CommandLine\r\n\r\n')
|
||||
return completed('')
|
||||
})
|
||||
|
||||
expect(getHapiRunnerProcessIdentity(8328)).toBe('unknown')
|
||||
expect(spawnSyncMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('falls back to WMIC when PowerShell exits non-zero', () => {
|
||||
spawnSyncMock
|
||||
.mockReturnValueOnce(completed('', 1))
|
||||
.mockReturnValueOnce(completed('hapi-local.exe runner start-sync'))
|
||||
spawnSyncMock.mockImplementation((cmd: string) => {
|
||||
if (cmd === 'tasklist') return unavailable('tasklist')
|
||||
if (cmd === 'powershell') return completed('', 1)
|
||||
if (cmd === 'wmic') return completed('hapi-local.exe runner start-sync')
|
||||
return completed('')
|
||||
})
|
||||
|
||||
expect(getHapiRunnerProcessIdentity(9124)).toBe('runner')
|
||||
expect(spawnSyncMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('reports unknown when no probe reports a command line', () => {
|
||||
spawnSyncMock
|
||||
.mockReturnValueOnce(completed(''))
|
||||
.mockReturnValueOnce(unavailable('wmic'))
|
||||
spawnSyncMock.mockImplementation((cmd: string) => {
|
||||
if (cmd === 'tasklist') return unavailable('tasklist')
|
||||
if (cmd === 'powershell') return completed('')
|
||||
if (cmd === 'wmic') return unavailable('wmic')
|
||||
return completed('')
|
||||
})
|
||||
|
||||
expect(getHapiRunnerProcessIdentity(8328)).toBe('unknown')
|
||||
expect(spawnSyncMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('reports dead when the pid exits while the probes run', () => {
|
||||
@@ -143,9 +156,10 @@ describe('getHapiRunnerProcessIdentity on Windows', () => {
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error('ESRCH')
|
||||
})
|
||||
spawnSyncMock
|
||||
.mockReturnValueOnce(unavailable('powershell'))
|
||||
.mockReturnValueOnce(unavailable('wmic'))
|
||||
spawnSyncMock.mockImplementation((cmd: string) => {
|
||||
if (cmd === 'tasklist') return unavailable('tasklist')
|
||||
return unavailable(cmd)
|
||||
})
|
||||
|
||||
expect(getHapiRunnerProcessIdentity(8328)).toBe('dead')
|
||||
})
|
||||
@@ -154,9 +168,514 @@ describe('getHapiRunnerProcessIdentity on Windows', () => {
|
||||
vi.spyOn(process, 'kill').mockImplementation(() => {
|
||||
throw new Error('ESRCH')
|
||||
})
|
||||
spawnSyncMock.mockImplementation((cmd: string) => {
|
||||
if (cmd === 'tasklist') return unavailable('tasklist')
|
||||
return completed('')
|
||||
})
|
||||
|
||||
expect(getHapiRunnerProcessIdentity(8328)).toBe('dead')
|
||||
expect(spawnSyncMock).not.toHaveBeenCalled()
|
||||
expect(spawnSyncMock.mock.calls.every((call) => call[0] === 'tasklist')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('killProcess on Windows (orphanReap / stopSession)', () => {
|
||||
beforeAll(() => {
|
||||
if (!originalPlatformDescriptor?.configurable) {
|
||||
throw new Error('process.platform is not configurable in this runtime')
|
||||
}
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
setPlatform('win32')
|
||||
spawnSyncMock.mockReset()
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
if (originalPlatformDescriptor) {
|
||||
Object.defineProperty(process, 'platform', originalPlatformDescriptor)
|
||||
}
|
||||
})
|
||||
|
||||
it('escalates soft taskkill to /F when the process stays alive (mirrors SIGTERM→SIGKILL)', async () => {
|
||||
// Soft taskkill on win32 console trees often fails with
|
||||
// "can only be terminated forcefully" — orphanReap must escalate.
|
||||
let alive = true
|
||||
// Match @types/node process.kill(pid, signal?: string | number): true
|
||||
vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => {
|
||||
if (signal === 0 || signal === undefined) {
|
||||
if (!alive) {
|
||||
const err = new Error('ESRCH') as NodeJS.ErrnoException
|
||||
err.code = 'ESRCH'
|
||||
throw err
|
||||
}
|
||||
return true
|
||||
}
|
||||
return true
|
||||
})
|
||||
spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => {
|
||||
if (cmd === 'tasklist') {
|
||||
if (!alive) {
|
||||
return completed('INFO: No tasks are running which match the specified criteria.')
|
||||
}
|
||||
return completed(`hapi.exe 5544 Console 1 5,000 K`)
|
||||
}
|
||||
if (cmd !== 'taskkill') {
|
||||
return completed('')
|
||||
}
|
||||
if (args.includes('/F')) {
|
||||
alive = false
|
||||
return completed('', 0)
|
||||
}
|
||||
// Soft refuse — process still alive (real Windows console-tree behavior)
|
||||
return {
|
||||
status: 1,
|
||||
stdout: Buffer.from(''),
|
||||
stderr: Buffer.from('ERROR: This process can only be terminated forcefully (with /F option).')
|
||||
}
|
||||
})
|
||||
|
||||
const done = killProcess(5544, false)
|
||||
// Soft fails → immediate /F; then brief death-poll timers
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
await expect(done).resolves.toBe(true)
|
||||
|
||||
const taskkills = spawnSyncMock.mock.calls.filter((call) => call[0] === 'taskkill')
|
||||
expect(taskkills.length).toBeGreaterThanOrEqual(2)
|
||||
expect(taskkills[0]![1]).toEqual(['/T', '/PID', '5544'])
|
||||
expect(taskkills.some((call) => (call[1] as string[]).includes('/F'))).toBe(true)
|
||||
})
|
||||
|
||||
it('waits for grace when soft taskkill succeeds before escalating to /F', async () => {
|
||||
// Soft status=0 but PID still draining archive flush — do not /F immediately.
|
||||
let alive = true
|
||||
let softCalls = 0
|
||||
vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => {
|
||||
if (signal === 0 || signal === undefined) {
|
||||
if (!alive) {
|
||||
const err = new Error('ESRCH') as NodeJS.ErrnoException
|
||||
err.code = 'ESRCH'
|
||||
throw err
|
||||
}
|
||||
return true
|
||||
}
|
||||
return true
|
||||
})
|
||||
spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => {
|
||||
if (cmd === 'tasklist') {
|
||||
if (!alive) {
|
||||
return completed('INFO: No tasks are running which match the specified criteria.')
|
||||
}
|
||||
return completed(`hapi.exe 7788 Console 1 5,000 K`)
|
||||
}
|
||||
if (cmd === 'taskkill' && args.includes('/F')) {
|
||||
alive = false
|
||||
return completed('', 0)
|
||||
}
|
||||
if (cmd === 'taskkill') {
|
||||
softCalls += 1
|
||||
// Succeeds, but process remains alive until grace elapses
|
||||
return completed('', 0)
|
||||
}
|
||||
return completed('')
|
||||
})
|
||||
|
||||
const done = killProcess(7788, false)
|
||||
// During grace, process exits without needing /F
|
||||
await vi.advanceTimersByTimeAsync(100)
|
||||
alive = false
|
||||
await vi.advanceTimersByTimeAsync(2_500)
|
||||
await expect(done).resolves.toBe(true)
|
||||
|
||||
expect(softCalls).toBeGreaterThanOrEqual(1)
|
||||
const forceKills = spawnSyncMock.mock.calls.filter(
|
||||
(call) => call[0] === 'taskkill' && (call[1] as string[]).includes('/F')
|
||||
)
|
||||
expect(forceKills).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('uses forced taskkill immediately when force=true', async () => {
|
||||
let alive = true
|
||||
vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => {
|
||||
if (signal === 0 || signal === undefined) {
|
||||
if (!alive) {
|
||||
const err = new Error('ESRCH') as NodeJS.ErrnoException
|
||||
err.code = 'ESRCH'
|
||||
throw err
|
||||
}
|
||||
return true
|
||||
}
|
||||
return true
|
||||
})
|
||||
spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => {
|
||||
if (cmd === 'tasklist') {
|
||||
if (!alive) {
|
||||
return completed('INFO: No tasks are running which match the specified criteria.')
|
||||
}
|
||||
return completed(`hapi.exe 9901 Console 1 5,000 K`)
|
||||
}
|
||||
if (cmd === 'taskkill' && args.includes('/F')) {
|
||||
alive = false
|
||||
return completed('', 0)
|
||||
}
|
||||
return completed('', 1)
|
||||
})
|
||||
|
||||
const done = killProcess(9901, true)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
await expect(done).resolves.toBe(true)
|
||||
|
||||
const taskkills = spawnSyncMock.mock.calls.filter((call) => call[0] === 'taskkill')
|
||||
expect(taskkills).toHaveLength(1)
|
||||
expect(taskkills[0]![1]).toEqual(['/F', '/T', '/PID', '9901'])
|
||||
})
|
||||
|
||||
it('killProcessTreeByPid signals surviving descendants after taskkill /T misses them', async () => {
|
||||
// #1911 bot Major: taskkill /T exit 0 is "signalled", not "tree gone".
|
||||
// When the root dies but a grandchild survives (broken intermediate link),
|
||||
// individually signal survivors from the pre-kill snapshot — but only when
|
||||
// the process-generation marker still matches (PID reuse guard).
|
||||
const { killProcessTreeByPid } = await import('./process')
|
||||
const alive = new Set([100, 200]) // 100=root, 200=descendant
|
||||
const markers = new Map([[100, 'gen-100'], [200, 'gen-200']])
|
||||
const taskkillPids: number[] = []
|
||||
vi.spyOn(process, 'kill').mockImplementation((pid: number, signal?: string | number) => {
|
||||
if (signal === 0 || signal === undefined) {
|
||||
if (!alive.has(pid)) {
|
||||
const err = new Error('ESRCH') as NodeJS.ErrnoException
|
||||
err.code = 'ESRCH'
|
||||
throw err
|
||||
}
|
||||
return true
|
||||
}
|
||||
return true
|
||||
})
|
||||
spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => {
|
||||
if (cmd === 'powershell') {
|
||||
const script = String(args[args.length - 1] ?? '')
|
||||
if (script.includes('ParentProcessId')) {
|
||||
return completed('OK:200,100')
|
||||
}
|
||||
// getProcessStartMarker CIM probe
|
||||
const filterMatch = /ProcessId = (\d+)/.exec(script)
|
||||
if (filterMatch) {
|
||||
const pid = Number(filterMatch[1])
|
||||
if (!alive.has(pid)) return completed('')
|
||||
return completed(markers.get(pid) ?? '')
|
||||
}
|
||||
return completed('')
|
||||
}
|
||||
if (cmd === 'tasklist') {
|
||||
const filter = args.find((a) => a.startsWith('PID eq '))
|
||||
const pid = filter ? Number(filter.replace('PID eq ', '')) : NaN
|
||||
if (!alive.has(pid)) {
|
||||
return completed('INFO: No tasks are running which match the specified criteria.')
|
||||
}
|
||||
return completed(`proc.exe ${pid} Console 1 1,000 K`)
|
||||
}
|
||||
if (cmd === 'taskkill') {
|
||||
const idx = args.indexOf('/PID')
|
||||
const pid = Number(args[idx + 1])
|
||||
taskkillPids.push(pid)
|
||||
alive.delete(pid)
|
||||
return completed('', 0)
|
||||
}
|
||||
return completed('')
|
||||
})
|
||||
|
||||
const done = killProcessTreeByPid(100, true)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
await expect(done).resolves.toBe(true)
|
||||
expect(taskkillPids).toContain(100)
|
||||
expect(taskkillPids).toContain(200)
|
||||
expect(alive.size).toBe(0)
|
||||
})
|
||||
|
||||
it('killProcessTreeByPid does not kill a surviving PID that was reused', async () => {
|
||||
const { killProcessTreeByPid } = await import('./process')
|
||||
const alive = new Set([100, 200])
|
||||
// After root kill, PID 200 is recycled with a new generation marker.
|
||||
let rootGone = false
|
||||
const taskkillPids: number[] = []
|
||||
vi.spyOn(process, 'kill').mockImplementation((pid: number, signal?: string | number) => {
|
||||
if (signal === 0 || signal === undefined) {
|
||||
if (!alive.has(pid)) {
|
||||
const err = new Error('ESRCH') as NodeJS.ErrnoException
|
||||
err.code = 'ESRCH'
|
||||
throw err
|
||||
}
|
||||
return true
|
||||
}
|
||||
return true
|
||||
})
|
||||
spawnSyncMock.mockImplementation((cmd: string, args: string[] = []) => {
|
||||
if (cmd === 'powershell') {
|
||||
const script = String(args[args.length - 1] ?? '')
|
||||
if (script.includes('ParentProcessId')) {
|
||||
return completed('OK:200,100')
|
||||
}
|
||||
const filterMatch = /ProcessId = (\d+)/.exec(script)
|
||||
if (filterMatch) {
|
||||
const pid = Number(filterMatch[1])
|
||||
if (!alive.has(pid)) return completed('')
|
||||
if (pid === 200 && rootGone) return completed('gen-200-reused')
|
||||
return completed(pid === 100 ? 'gen-100' : 'gen-200')
|
||||
}
|
||||
return completed('')
|
||||
}
|
||||
if (cmd === 'tasklist') {
|
||||
const filter = args.find((a) => a.startsWith('PID eq '))
|
||||
const pid = filter ? Number(filter.replace('PID eq ', '')) : NaN
|
||||
if (!alive.has(pid)) {
|
||||
return completed('INFO: No tasks are running which match the specified criteria.')
|
||||
}
|
||||
return completed(`proc.exe ${pid} Console 1 1,000 K`)
|
||||
}
|
||||
if (cmd === 'taskkill') {
|
||||
const idx = args.indexOf('/PID')
|
||||
const pid = Number(args[idx + 1])
|
||||
taskkillPids.push(pid)
|
||||
if (pid === 100) {
|
||||
alive.delete(100)
|
||||
rootGone = true
|
||||
} else {
|
||||
alive.delete(pid)
|
||||
}
|
||||
return completed('', 0)
|
||||
}
|
||||
return completed('')
|
||||
})
|
||||
|
||||
const done = killProcessTreeByPid(100, true)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
// Root signalled; reused descendant left alone → tree verify fails closed.
|
||||
await expect(done).resolves.toBe(false)
|
||||
expect(taskkillPids).toEqual([100])
|
||||
expect(alive.has(200)).toBe(true)
|
||||
})
|
||||
|
||||
it('windowsProcessTreeCimCommand is newline-separated (WinPS-parseable)', async () => {
|
||||
// #1911 bot Major: `.join(' ')` yields `$seen=@{} $bfs=@()` — parse error.
|
||||
// Assert generated command text, not mocked stdout (mocks never parse PS).
|
||||
const { windowsProcessTreeCimCommand } = await import('./process')
|
||||
const cmd = windowsProcessTreeCimCommand(4242)
|
||||
expect(cmd).toContain('$root=4242')
|
||||
expect(cmd).toContain('ParentProcessId=$p')
|
||||
// Statements must be on separate lines — spaces between `$x=@{}` tokens fail.
|
||||
expect(cmd).toContain('\n$seen=@{}')
|
||||
expect(cmd).toContain('\n$bfs=@()')
|
||||
expect(cmd).toContain('\n$queue=@($root)')
|
||||
expect(cmd).toContain('\nwhile($queue.Count -gt 0){')
|
||||
// Space-join regression: adjacent statement tokens on one line (not newline).
|
||||
expect(cmd).not.toMatch(/\$seen=@\{\}[ ]+\$bfs=@\(\)/)
|
||||
expect(cmd).not.toMatch(/\$bfs=@\(\)[ ]+\$queue=@/)
|
||||
// Do not terminate `while(...){` with `;` (also invalid).
|
||||
expect(cmd).not.toMatch(/while\(\$queue\.Count -gt 0\)\{\s*;/)
|
||||
// #1911 B1: never SilentlyContinue — CIM failure must not look like childless root.
|
||||
expect(cmd).toContain("$ErrorActionPreference='Stop'")
|
||||
expect(cmd).toContain('trap { exit 1 }')
|
||||
expect(cmd).not.toContain('SilentlyContinue')
|
||||
expect(cmd).toContain('Write-Output ("OK:" + ($bfs -join ","))')
|
||||
})
|
||||
|
||||
it('parseWindowsProcessTreeStdout requires OK: sentinel (B1 root-only is scan_failed)', async () => {
|
||||
const { parseWindowsProcessTreeStdout } = await import('./process')
|
||||
// Overseer measured: CIM failure with SilentlyContinue prints "1234" exit 0 —
|
||||
// byte-identical to healthy childless. Without OK: that must be scan_failed.
|
||||
expect(parseWindowsProcessTreeStdout('1234', 1234)).toBe('scan_failed')
|
||||
expect(parseWindowsProcessTreeStdout('4000,3000,2000,1234', 1234)).toBe('scan_failed')
|
||||
expect(parseWindowsProcessTreeStdout('', 1234)).toBe('scan_failed')
|
||||
expect(parseWindowsProcessTreeStdout('OK:', 1234)).toBe('scan_failed')
|
||||
expect(parseWindowsProcessTreeStdout('OK:1234', 1234)).toEqual([1234])
|
||||
expect(parseWindowsProcessTreeStdout('OK:4000,3000,2000,1234', 1234)).toEqual([
|
||||
4000, 3000, 2000, 1234,
|
||||
])
|
||||
expect(parseWindowsProcessTreeStdout('OK:200,100', 100)).toEqual([200, 100])
|
||||
expect(parseWindowsProcessTreeStdout('OK:200,100', 999)).toBe('scan_failed')
|
||||
})
|
||||
|
||||
it('killProcessTreeByPid treats bare root stdout (B1 fail-open shape) as scan_failed', async () => {
|
||||
const { killProcessTreeByPid } = await import('./process')
|
||||
let alive = true
|
||||
vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => {
|
||||
if (signal === 0 || signal === undefined) {
|
||||
if (!alive) {
|
||||
const err = new Error('ESRCH') as NodeJS.ErrnoException
|
||||
err.code = 'ESRCH'
|
||||
throw err
|
||||
}
|
||||
return true
|
||||
}
|
||||
return true
|
||||
})
|
||||
spawnSyncMock.mockImplementation((cmd: string) => {
|
||||
// Status 0 + root-only — the measured CIM-failure shape under SilentlyContinue.
|
||||
if (cmd === 'powershell') return completed('1234')
|
||||
if (cmd === 'tasklist') {
|
||||
if (!alive) {
|
||||
return completed('INFO: No tasks are running which match the specified criteria.')
|
||||
}
|
||||
return completed(`proc.exe 1234 Console 1 1,000 K`)
|
||||
}
|
||||
if (cmd === 'taskkill') {
|
||||
alive = false
|
||||
return completed('', 0)
|
||||
}
|
||||
return completed('')
|
||||
})
|
||||
const done = killProcessTreeByPid(1234, true)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
await expect(done).resolves.toBe(false)
|
||||
expect(spawnSyncMock.mock.calls.some((c) => c[0] === 'taskkill')).toBe(true)
|
||||
})
|
||||
|
||||
it('killProcessTreeByPid signals root but returns false when Windows tree scan fails', async () => {
|
||||
const { killProcessTreeByPid } = await import('./process')
|
||||
let alive = true
|
||||
vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => {
|
||||
if (signal === 0 || signal === undefined) {
|
||||
if (!alive) {
|
||||
const err = new Error('ESRCH') as NodeJS.ErrnoException
|
||||
err.code = 'ESRCH'
|
||||
throw err
|
||||
}
|
||||
return true
|
||||
}
|
||||
return true
|
||||
})
|
||||
spawnSyncMock.mockImplementation((cmd: string) => {
|
||||
if (cmd === 'powershell') {
|
||||
return { status: 1, stdout: Buffer.from(''), stderr: Buffer.from('parse error') }
|
||||
}
|
||||
if (cmd === 'tasklist') {
|
||||
if (!alive) {
|
||||
return completed('INFO: No tasks are running which match the specified criteria.')
|
||||
}
|
||||
return completed(`proc.exe 100 Console 1 1,000 K`)
|
||||
}
|
||||
if (cmd === 'taskkill') {
|
||||
alive = false
|
||||
return completed('', 0)
|
||||
}
|
||||
return completed('')
|
||||
})
|
||||
const done = killProcessTreeByPid(100, true)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
await expect(done).resolves.toBe(false)
|
||||
// Partial kill: root signalled, but never claim stopped without tree verify.
|
||||
expect(spawnSyncMock.mock.calls.some((c) => c[0] === 'taskkill')).toBe(true)
|
||||
})
|
||||
|
||||
it('killProcessTreeByPid signals root but returns false when Windows tree scan returns empty stdout', async () => {
|
||||
const { killProcessTreeByPid } = await import('./process')
|
||||
let alive = true
|
||||
vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => {
|
||||
if (signal === 0 || signal === undefined) {
|
||||
if (!alive) {
|
||||
const err = new Error('ESRCH') as NodeJS.ErrnoException
|
||||
err.code = 'ESRCH'
|
||||
throw err
|
||||
}
|
||||
return true
|
||||
}
|
||||
return true
|
||||
})
|
||||
spawnSyncMock.mockImplementation((cmd: string) => {
|
||||
if (cmd === 'powershell') return completed('') // status 0, empty — scan_failed
|
||||
if (cmd === 'tasklist') {
|
||||
if (!alive) {
|
||||
return completed('INFO: No tasks are running which match the specified criteria.')
|
||||
}
|
||||
return completed(`proc.exe 100 Console 1 1,000 K`)
|
||||
}
|
||||
if (cmd === 'taskkill') {
|
||||
alive = false
|
||||
return completed('', 0)
|
||||
}
|
||||
return completed('')
|
||||
})
|
||||
const done = killProcessTreeByPid(100, true)
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
await expect(done).resolves.toBe(false)
|
||||
expect(spawnSyncMock.mock.calls.some((c) => c[0] === 'taskkill')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('killProcessTreeByPid on POSIX (pgrep tree scan)', () => {
|
||||
beforeEach(() => {
|
||||
setPlatform('linux')
|
||||
spawnSyncMock.mockReset()
|
||||
vi.spyOn(process, 'kill').mockReturnValue(true)
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
if (originalPlatformDescriptor) {
|
||||
Object.defineProperty(process, 'platform', originalPlatformDescriptor)
|
||||
}
|
||||
})
|
||||
|
||||
it('returns false when pgrep is missing (signal root, never claim stopped)', async () => {
|
||||
const { killProcessTreeByPid } = await import('./process')
|
||||
let dead = false
|
||||
vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => {
|
||||
if (signal === 0 || signal === undefined) {
|
||||
if (dead) {
|
||||
const err = new Error('ESRCH') as NodeJS.ErrnoException
|
||||
err.code = 'ESRCH'
|
||||
throw err
|
||||
}
|
||||
return true
|
||||
}
|
||||
dead = true
|
||||
return true
|
||||
})
|
||||
spawnSyncMock.mockImplementation((cmd: string) => {
|
||||
if (cmd === 'pgrep') return unavailable('pgrep')
|
||||
return completed('')
|
||||
})
|
||||
const done = killProcessTreeByPid(4242, true)
|
||||
await vi.advanceTimersByTimeAsync(3000)
|
||||
await expect(done).resolves.toBe(false)
|
||||
// Root still signalled — partial kill > zero kill on hosts without pgrep.
|
||||
expect(process.kill).toHaveBeenCalledWith(4242, 'SIGKILL')
|
||||
})
|
||||
|
||||
it('returns false when pgrep is signalled (status null — partial tree)', async () => {
|
||||
const { killProcessTreeByPid } = await import('./process')
|
||||
let dead = false
|
||||
vi.spyOn(process, 'kill').mockImplementation((_pid: number, signal?: string | number) => {
|
||||
if (signal === 0 || signal === undefined) {
|
||||
if (dead) {
|
||||
const err = new Error('ESRCH') as NodeJS.ErrnoException
|
||||
err.code = 'ESRCH'
|
||||
throw err
|
||||
}
|
||||
return true
|
||||
}
|
||||
dead = true
|
||||
return true
|
||||
})
|
||||
spawnSyncMock.mockImplementation((cmd: string) => {
|
||||
if (cmd === 'pgrep') {
|
||||
return { status: null, stdout: '999\n', stderr: '', error: null }
|
||||
}
|
||||
return completed('')
|
||||
})
|
||||
const done = killProcessTreeByPid(4242, true)
|
||||
await vi.advanceTimersByTimeAsync(3000)
|
||||
await expect(done).resolves.toBe(false)
|
||||
expect(process.kill).toHaveBeenCalledWith(4242, 'SIGKILL')
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
+245
-41
@@ -3,11 +3,33 @@ import spawn from 'cross-spawn';
|
||||
|
||||
export const isWindows = (): boolean => process.platform === 'win32';
|
||||
|
||||
/** Bound hung WMI/tasklist/ps so a wedged spawn cannot darken the runner (#1911 Overseer B3). */
|
||||
const SPAWN_SYNC_TIMEOUT_MS = 10_000;
|
||||
|
||||
export function isProcessAlive(pid: number): boolean {
|
||||
if (!Number.isFinite(pid) || pid <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Windows: prefer tasklist. Bun/Node `process.kill(pid, 0)` is unreliable as a
|
||||
// liveness probe on win32 and can disagree with the console tree taskkill sees.
|
||||
if (isWindows()) {
|
||||
try {
|
||||
const result = spawn.sync(
|
||||
'tasklist',
|
||||
['/FI', `PID eq ${pid}`, '/NH'],
|
||||
{ stdio: 'pipe', windowsHide: true, encoding: 'utf8', timeout: SPAWN_SYNC_TIMEOUT_MS }
|
||||
);
|
||||
if (!result.error && result.status === 0) {
|
||||
const out = (result.stdout?.toString() ?? '').trim();
|
||||
if (!out || /no tasks/i.test(out)) return false;
|
||||
return new RegExp(`(^|\\D)${pid}(\\D|$)`).test(out);
|
||||
}
|
||||
} catch {
|
||||
// fall through to signal-0 probe
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
@@ -16,28 +38,59 @@ export function isProcessAlive(pid: number): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared Win32 generation marker: CIM CreationDate as UTC round-trip ISO.
|
||||
* Must match orphan list + recheck — ConvertTo-Json of a raw DateTime emits
|
||||
* `/Date(...)/` on Windows PowerShell 5.1 (#1911 bot Major).
|
||||
*/
|
||||
export const WINDOWS_CIM_CREATION_DATE_MARKER_EXPR =
|
||||
"$_.CreationDate.ToUniversalTime().ToString('o')";
|
||||
|
||||
/** PowerShell -Command body for the argv orphan process list (CIM + JSON). */
|
||||
export function windowsProcessListCimCommand(): string {
|
||||
// Fail closed: non-terminating CIM errors must not yield empty stdout with
|
||||
// exit 0 (that was misread as "no orphans" → false archive-ok). #1911 B2.
|
||||
// Note: Stop on the whole enumeration means one transient per-instance WMI
|
||||
// error aborts the scan → still_alive until it clears (availability trap,
|
||||
// fail-closed; #1911 Overseer non-blocker).
|
||||
return [
|
||||
"$ErrorActionPreference='Stop'",
|
||||
'trap { exit 1 }',
|
||||
'Get-CimInstance Win32_Process | Select-Object ProcessId,Name,CommandLine,'
|
||||
+ `@{N='CreationDate';E={if ($_.CreationDate) { ${WINDOWS_CIM_CREATION_DATE_MARKER_EXPR} } else { $null }}}`
|
||||
+ ' | ConvertTo-Json -Compress',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
/** PowerShell -Command body for a single-PID start-marker probe. */
|
||||
export function windowsProcessMarkerCimCommand(pid: number): string {
|
||||
const expr = WINDOWS_CIM_CREATION_DATE_MARKER_EXPR.replace(/\$_/g, '$p');
|
||||
return (
|
||||
`$p = Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}"; `
|
||||
+ `if ($p -and $p.CreationDate) { ${expr} }`
|
||||
);
|
||||
}
|
||||
|
||||
/** Stable marker for one OS PID generation; null means the platform probe failed. */
|
||||
export function getProcessStartMarker(pid: number): string | null {
|
||||
if (!isProcessAlive(pid)) return null;
|
||||
if (isWindows()) {
|
||||
// Same UTC ISO 'o' string as orphanReap listWindowsProcessesWithCommandLine.
|
||||
// Do not print raw DateTime or use WMIC DMTF (format mismatch skips reap).
|
||||
const powershell = spawn.sync('powershell', [
|
||||
'-NoProfile', '-NonInteractive', '-Command',
|
||||
`(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").CreationDate`
|
||||
], { stdio: 'pipe', windowsHide: true });
|
||||
windowsProcessMarkerCimCommand(pid),
|
||||
], { stdio: 'pipe', windowsHide: true, timeout: SPAWN_SYNC_TIMEOUT_MS });
|
||||
if (!powershell.error && powershell.status === 0) {
|
||||
const marker = powershell.stdout?.toString().trim();
|
||||
if (marker) return marker;
|
||||
}
|
||||
const result = spawn.sync('wmic', [
|
||||
'process', 'where', `ProcessId=${pid}`, 'get', 'CreationDate', '/value'
|
||||
], { stdio: 'pipe', windowsHide: true });
|
||||
if (result.error || result.status !== 0) return null;
|
||||
const match = (result.stdout?.toString() ?? '').match(/CreationDate=([^\r\n]+)/);
|
||||
return match?.[1]?.trim() || null;
|
||||
return null;
|
||||
}
|
||||
const result = spawn.sync('ps', ['-p', String(pid), '-o', 'lstart='], {
|
||||
stdio: 'pipe',
|
||||
env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' }
|
||||
env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
|
||||
timeout: SPAWN_SYNC_TIMEOUT_MS,
|
||||
});
|
||||
if (result.error || result.status !== 0) return null;
|
||||
return result.stdout?.toString().trim() || null;
|
||||
@@ -56,7 +109,7 @@ function getWindowsProcessCommandLine(pid: number): string | null {
|
||||
'-NonInteractive',
|
||||
'-Command',
|
||||
`(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").CommandLine`
|
||||
], { stdio: 'pipe', windowsHide: true });
|
||||
], { stdio: 'pipe', windowsHide: true, timeout: SPAWN_SYNC_TIMEOUT_MS });
|
||||
if (!powershell.error && powershell.status === 0) {
|
||||
const commandLine = powershell.stdout?.toString() ?? '';
|
||||
if (commandLine.trim()) return commandLine;
|
||||
@@ -64,7 +117,7 @@ function getWindowsProcessCommandLine(pid: number): string | null {
|
||||
|
||||
const wmic = spawn.sync('wmic', [
|
||||
'process', 'where', `ProcessId=${pid}`, 'get', 'CommandLine'
|
||||
], { stdio: 'pipe', windowsHide: true });
|
||||
], { stdio: 'pipe', windowsHide: true, timeout: SPAWN_SYNC_TIMEOUT_MS });
|
||||
if (!wmic.error && wmic.status === 0) {
|
||||
const commandLine = readWmicCommandLine(wmic.stdout?.toString() ?? '');
|
||||
if (commandLine) return commandLine;
|
||||
@@ -106,7 +159,10 @@ export function getHapiRunnerProcessIdentity(pid: number): RunnerProcessIdentity
|
||||
}
|
||||
|
||||
function getPosixProcessCommandLine(pid: number): string | null {
|
||||
const result = spawn.sync('ps', ['-p', String(pid), '-o', 'command='], { stdio: 'pipe' });
|
||||
const result = spawn.sync('ps', ['-p', String(pid), '-o', 'command='], {
|
||||
stdio: 'pipe',
|
||||
timeout: SPAWN_SYNC_TIMEOUT_MS,
|
||||
});
|
||||
if (result.error || result.status !== 0) return null;
|
||||
const commandLine = result.stdout?.toString() ?? '';
|
||||
return commandLine.trim() ? commandLine : null;
|
||||
@@ -124,7 +180,8 @@ function killProcessWindows(pid: number, force: boolean): boolean {
|
||||
try {
|
||||
const result = spawn.sync('taskkill', args, {
|
||||
stdio: 'pipe',
|
||||
windowsHide: true
|
||||
windowsHide: true,
|
||||
timeout: SPAWN_SYNC_TIMEOUT_MS,
|
||||
});
|
||||
if (result.error) {
|
||||
return false;
|
||||
@@ -143,18 +200,110 @@ function killProcessWindows(pid: number, force: boolean): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect a win32 process tree (children first, root last) via CIM ParentProcessId.
|
||||
* Used to verify taskkill /T actually cleared descendants — exit 0 is "signalled",
|
||||
* not "gone" (#1911 B2).
|
||||
*
|
||||
* Returns `'scan_failed'` when PowerShell errors or returns nothing usable —
|
||||
* callers must fail closed (never fall back to root-only verify).
|
||||
*
|
||||
* Success is a positive sentinel (`OK:<pids>`), not "exit 0 + somehow looks like
|
||||
* PIDs". With `-ErrorAction SilentlyContinue`, a CIM failure exited 0 printing
|
||||
* only the root — byte-identical to a healthy childless tree (#1911 B1).
|
||||
*/
|
||||
export function windowsProcessTreeCimCommand(pid: number): string {
|
||||
// Newlines between statements — `.join(' ')` is a parse error on WinPS
|
||||
// (`$seen=@{} $bfs=@()`). Do not join with `;` either: `while(...){;` is invalid.
|
||||
return [
|
||||
"$ErrorActionPreference='Stop'",
|
||||
'trap { exit 1 }',
|
||||
`$root=${pid}`,
|
||||
'$seen=@{}',
|
||||
'$bfs=@()',
|
||||
'$queue=@($root)',
|
||||
'while($queue.Count -gt 0){',
|
||||
' $p=$queue[0]; if($queue.Count -eq 1){$queue=@()}else{$queue=$queue[1..($queue.Count-1)]}',
|
||||
' if($seen.ContainsKey($p)){continue}',
|
||||
' $seen[$p]=$true',
|
||||
' $bfs+=$p',
|
||||
' Get-CimInstance Win32_Process -Filter "ParentProcessId=$p" |',
|
||||
' ForEach-Object { $queue+=,[int]$_.ProcessId }',
|
||||
'}',
|
||||
// children-first: reverse BFS so root is last; OK: marks clean completion
|
||||
'if($bfs.Count -gt 0){ [array]::Reverse($bfs); Write-Output ("OK:" + ($bfs -join ",")) }',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
/** Parse tree-scan stdout. Requires the `OK:` success sentinel (#1911 B1). */
|
||||
export function parseWindowsProcessTreeStdout(
|
||||
raw: string,
|
||||
rootPid: number
|
||||
): number[] | 'scan_failed' {
|
||||
const text = raw.trim()
|
||||
if (!text.startsWith('OK:')) return 'scan_failed'
|
||||
const body = text.slice('OK:'.length).trim()
|
||||
if (!body) return 'scan_failed'
|
||||
const pids = body.split(',').map((s) => Number(s.trim())).filter((p) => Number.isFinite(p) && p > 0)
|
||||
if (pids.length === 0 || !pids.includes(rootPid)) return 'scan_failed'
|
||||
return pids
|
||||
}
|
||||
|
||||
export function collectWindowsProcessTree(pid: number): number[] | 'scan_failed' {
|
||||
const n = typeof pid === 'number' ? pid : Number(pid)
|
||||
if (!Number.isFinite(n) || n <= 0) return 'scan_failed'
|
||||
|
||||
const result = spawn.sync(
|
||||
'powershell',
|
||||
[
|
||||
'-NoProfile',
|
||||
'-NonInteractive',
|
||||
'-Command',
|
||||
windowsProcessTreeCimCommand(n),
|
||||
],
|
||||
{ encoding: 'utf8', windowsHide: true, maxBuffer: 16 * 1024 * 1024, timeout: SPAWN_SYNC_TIMEOUT_MS }
|
||||
)
|
||||
if (result.error || result.status !== 0) {
|
||||
return 'scan_failed'
|
||||
}
|
||||
return parseWindowsProcessTreeStdout((result.stdout ?? '').toString(), n)
|
||||
}
|
||||
|
||||
async function signalAndWaitWindowsRoot(pid: number, force: boolean): Promise<void> {
|
||||
if (force) {
|
||||
killProcessWindows(pid, true);
|
||||
await waitForProcessToDie(pid, true);
|
||||
return;
|
||||
}
|
||||
const softOk = killProcessWindows(pid, false);
|
||||
if (!softOk && isProcessAlive(pid)) {
|
||||
killProcessWindows(pid, true);
|
||||
await waitForProcessToDie(pid, true);
|
||||
return;
|
||||
}
|
||||
await waitForProcessToDie(pid, false);
|
||||
}
|
||||
|
||||
export async function killProcess(pid: number, force: boolean = false): Promise<boolean> {
|
||||
if (!Number.isFinite(pid) || pid <= 0) {
|
||||
const n = typeof pid === 'number' ? pid : Number(pid)
|
||||
if (!Number.isFinite(n) || n <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isWindows()) {
|
||||
return killProcessWindows(pid, force);
|
||||
// Soft taskkill (/T without /F) is routinely refused on win32 console trees
|
||||
// ("can only be terminated forcefully"). Mirror POSIX SIGTERM→SIGKILL:
|
||||
// escalate immediately only when soft kill is *refused*; when soft succeeds
|
||||
// but the PID is still draining, honor the grace wait before /F so archive
|
||||
// flush can finish.
|
||||
// Root-only verify — callers that need full-tree proof use killProcessTreeByPid.
|
||||
await signalAndWaitWindowsRoot(n, force);
|
||||
return !isProcessAlive(n);
|
||||
}
|
||||
|
||||
try {
|
||||
process.kill(pid, force ? 'SIGKILL' : 'SIGTERM');
|
||||
await waitForProcessToDie(pid, force);
|
||||
process.kill(n, force ? 'SIGKILL' : 'SIGTERM');
|
||||
await waitForProcessToDie(n, force);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
@@ -163,21 +312,34 @@ export async function killProcess(pid: number, force: boolean = false): Promise<
|
||||
|
||||
/**
|
||||
* Recursively collects all descendant PIDs of a process (depth-first).
|
||||
* Returns PIDs in child-first order (leaves first, root last).
|
||||
* Returns PIDs in child-first order (leaves first, root last), or
|
||||
* `'scan_failed'` when pgrep could not be run (so callers fail closed
|
||||
* instead of verifying root-only — #1911 Opus / Overseer).
|
||||
*/
|
||||
function collectProcessTree(pid: number): number[] {
|
||||
function collectProcessTree(pid: number): number[] | 'scan_failed' {
|
||||
const pids: number[] = [];
|
||||
|
||||
try {
|
||||
const result = spawn.sync('pgrep', ['-P', pid.toString()], { encoding: 'utf8' });
|
||||
if (result.stdout) {
|
||||
const childPids = result.stdout.trim().split('\n').filter(Boolean).map(Number);
|
||||
for (const childPid of childPids) {
|
||||
pids.push(...collectProcessTree(childPid));
|
||||
}
|
||||
const result = spawn.sync('pgrep', ['-P', pid.toString()], {
|
||||
encoding: 'utf8',
|
||||
timeout: SPAWN_SYNC_TIMEOUT_MS,
|
||||
});
|
||||
// spawn.sync returns {error} rather than throwing when the binary is missing.
|
||||
if (result.error) {
|
||||
return 'scan_failed';
|
||||
}
|
||||
// pgrep: 0 = matches, 1 = no children. null = signalled / aborted → partial
|
||||
// stdout is not a trustworthy tree (#1911 Overseer POSIX B1 twin).
|
||||
if (result.status !== 0 && result.status !== 1) {
|
||||
return 'scan_failed';
|
||||
}
|
||||
if (result.stdout) {
|
||||
const childPids = result.stdout.trim().split('\n').filter(Boolean).map(Number);
|
||||
for (const childPid of childPids) {
|
||||
if (!Number.isFinite(childPid) || childPid <= 0) continue;
|
||||
const nested = collectProcessTree(childPid);
|
||||
if (nested === 'scan_failed') return 'scan_failed';
|
||||
pids.push(...nested);
|
||||
}
|
||||
} catch {
|
||||
// pgrep may not be available
|
||||
}
|
||||
|
||||
pids.push(pid);
|
||||
@@ -192,6 +354,18 @@ function collectProcessTree(pid: number): number[] {
|
||||
async function killProcessTree(pid: number, force: boolean): Promise<boolean> {
|
||||
// Collect all PIDs first (sync) - returns in child-first order
|
||||
const pids = collectProcessTree(pid);
|
||||
if (pids === 'scan_failed') {
|
||||
// Signal the known root anyway (partial kill > zero kill), but never claim
|
||||
// stopped without a full-tree verify (#1911 Opus Major / debian-slim no pgrep).
|
||||
const signal = force ? 'SIGKILL' : 'SIGTERM';
|
||||
try {
|
||||
process.kill(pid, signal);
|
||||
} catch {
|
||||
// already gone
|
||||
}
|
||||
await waitForProcessToDie(pid, force);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Signal all processes synchronously (children first, then root)
|
||||
const signal = force ? 'SIGKILL' : 'SIGTERM';
|
||||
@@ -213,17 +387,48 @@ async function killProcessTree(pid: number, force: boolean): Promise<boolean> {
|
||||
|
||||
/** Kill a PID and all descendants, verifying the complete tree is gone. */
|
||||
export async function killProcessTreeByPid(pid: number, force: boolean = false): Promise<boolean> {
|
||||
if (!Number.isFinite(pid) || pid <= 0) return false;
|
||||
if (isWindows()) return killProcess(pid, force);
|
||||
return killProcessTree(pid, force);
|
||||
const n = typeof pid === 'number' ? pid : Number(pid)
|
||||
if (!Number.isFinite(n) || n <= 0) return false;
|
||||
if (isWindows()) {
|
||||
// taskkill /T exit 0 means "signalled", not "every descendant is dead".
|
||||
// Collect the tree + generation markers first, signal the root with /T,
|
||||
// then individually signal any surviving pre-kill PIDs whose generation
|
||||
// still matches (PID reuse must not be killed) (#1911 bot Major).
|
||||
const treePids = collectWindowsProcessTree(n);
|
||||
if (treePids === 'scan_failed') {
|
||||
// Still signal the (known) root — scan failure must not mean zero kill —
|
||||
// but never claim stopped without a full-tree verify (#1911 Opus Major).
|
||||
await signalAndWaitWindowsRoot(n, force);
|
||||
return false;
|
||||
}
|
||||
const markers = new Map<number, string | null>();
|
||||
for (const candidate of treePids) {
|
||||
markers.set(candidate, getProcessStartMarker(candidate));
|
||||
}
|
||||
await signalAndWaitWindowsRoot(n, force);
|
||||
for (const survivor of treePids) {
|
||||
if (survivor === n) continue;
|
||||
if (!isProcessAlive(survivor)) continue;
|
||||
const expected = markers.get(survivor);
|
||||
const current = getProcessStartMarker(survivor);
|
||||
// Unverifiable or reused PID — leave alone; final every() fails closed.
|
||||
if (!expected || !current || current !== expected) continue;
|
||||
await signalAndWaitWindowsRoot(survivor, true);
|
||||
}
|
||||
return treePids.every((candidate) => !isProcessAlive(candidate));
|
||||
}
|
||||
return killProcessTree(n, force);
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for a process to die, escalating to SIGKILL if SIGTERM doesn't work.
|
||||
* Waits for a process to die, escalating if the graceful signal didn't work.
|
||||
* POSIX: SIGTERM → SIGKILL. Windows: taskkill /T → taskkill /F /T.
|
||||
*/
|
||||
async function waitForProcessToDie(pid: number, force: boolean): Promise<void> {
|
||||
const maxWait = 2000;
|
||||
const pollInterval = 20;
|
||||
// Windows isProcessAlive shells out to tasklist; keep the poll coarse so a
|
||||
// stop cannot burn the runner event loop for seconds (#1911 Overseer).
|
||||
const pollInterval = isWindows() ? 100 : 20;
|
||||
let waited = 0;
|
||||
|
||||
while (isProcessAlive(pid) && waited < maxWait) {
|
||||
@@ -231,10 +436,14 @@ async function waitForProcessToDie(pid: number, force: boolean): Promise<void> {
|
||||
waited += pollInterval;
|
||||
}
|
||||
|
||||
// If SIGTERM didn't work and we haven't tried SIGKILL yet, escalate
|
||||
// Graceful kill didn't finish — escalate (same structure on both platforms).
|
||||
if (!force && isProcessAlive(pid)) {
|
||||
try {
|
||||
process.kill(pid, 'SIGKILL');
|
||||
if (isWindows()) {
|
||||
killProcessWindows(pid, true);
|
||||
} else {
|
||||
process.kill(pid, 'SIGKILL');
|
||||
}
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
@@ -255,11 +464,6 @@ export async function killProcessByChildProcess(
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isWindows()) {
|
||||
// Windows taskkill /T already kills the entire process tree
|
||||
return killProcess(pid, force);
|
||||
}
|
||||
|
||||
// Kill entire process tree on Unix to prevent orphan processes
|
||||
// Both platforms: tree-kill + full-tree verify (win32 must not trust root-only).
|
||||
return killProcessTreeByPid(pid, force);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* Executes the generated Windows tree-scan PowerShell under Docker pwsh.
|
||||
* Mocks agree with themselves; this is the structural antidote to #1911 B1
|
||||
* (CIM failure looking like a healthy childless root).
|
||||
*
|
||||
* Locally: skips when docker/image missing.
|
||||
* In CI (`CI=true`): fails hard — silent skip is fake coverage (#1911 Overseer).
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { windowsProcessListCimCommand, windowsProcessTreeCimCommand } from './process'
|
||||
|
||||
const POWERSHELL_IMAGE = 'mcr.microsoft.com/powershell:latest'
|
||||
|
||||
function dockerPwshAvailable(): boolean {
|
||||
try {
|
||||
execFileSync('docker', ['image', 'inspect', POWERSHELL_IMAGE], {
|
||||
stdio: 'ignore',
|
||||
// A stopped Docker daemon can hang `docker image inspect` until
|
||||
// the socket timeout. Local runs must skip, not block the suite.
|
||||
timeout: 5_000,
|
||||
})
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function ensureDockerPwsh(): void {
|
||||
if (dockerPwshAvailable()) return
|
||||
if (process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true') {
|
||||
throw new Error(
|
||||
`CI requires ${POWERSHELL_IMAGE} for windowsProcessTree.pwsh.test.ts — `
|
||||
+ 'pull it in the workflow before bun run test (silent skip is not coverage)'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function runPwsh(script: string): { status: number; stdout: string; stderr: string } {
|
||||
try {
|
||||
const stdout = execFileSync(
|
||||
'docker',
|
||||
['run', '--rm', POWERSHELL_IMAGE, 'pwsh', '-NoProfile', '-Command', script],
|
||||
{ encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 }
|
||||
)
|
||||
return { status: 0, stdout: stdout.toString(), stderr: '' }
|
||||
} catch (error) {
|
||||
const err = error as { status?: number; stdout?: string; stderr?: string }
|
||||
return {
|
||||
status: typeof err.status === 'number' ? err.status : 1,
|
||||
stdout: err.stdout?.toString() ?? '',
|
||||
stderr: err.stderr?.toString() ?? '',
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ensureDockerPwsh()
|
||||
const describePwsh = dockerPwshAvailable() ? describe : describe.skip
|
||||
|
||||
describePwsh('windowsProcessTreeCimCommand under real pwsh (#1911 B1)', () => {
|
||||
it('fails closed when Get-CimInstance is missing (Linux container)', () => {
|
||||
// Measured pre-fix: SilentlyContinue printed root-only with exit 0.
|
||||
const result = runPwsh(windowsProcessTreeCimCommand(1234))
|
||||
expect(result.status).not.toBe(0)
|
||||
expect(result.stdout.trim()).not.toMatch(/^OK:/)
|
||||
expect(result.stdout.trim()).not.toBe('1234')
|
||||
})
|
||||
|
||||
it('emits OK: children-first tree when Get-CimInstance is mocked healthy', () => {
|
||||
const mock = `
|
||||
function Get-CimInstance {
|
||||
param($ClassName, $Filter)
|
||||
$ppid = [int](($Filter -split "=")[1])
|
||||
if ($ppid -eq 1234) {
|
||||
[pscustomobject]@{ ProcessId = 2000 }
|
||||
[pscustomobject]@{ ProcessId = 3000 }
|
||||
} elseif ($ppid -eq 2000) {
|
||||
[pscustomobject]@{ ProcessId = 4000 }
|
||||
}
|
||||
}
|
||||
${windowsProcessTreeCimCommand(1234)}
|
||||
`
|
||||
const result = runPwsh(mock)
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout.trim()).toBe('OK:4000,3000,2000,1234')
|
||||
})
|
||||
|
||||
it('emits OK:root alone when the mocked tree has no children', () => {
|
||||
const mock = `
|
||||
function Get-CimInstance { param($ClassName, $Filter) }
|
||||
${windowsProcessTreeCimCommand(1234)}
|
||||
`
|
||||
const result = runPwsh(mock)
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout.trim()).toBe('OK:1234')
|
||||
})
|
||||
|
||||
it('list command fails closed when Get-CimInstance is missing', () => {
|
||||
const result = runPwsh(windowsProcessListCimCommand())
|
||||
expect(result.status).not.toBe(0)
|
||||
expect(result.stdout.trim()).toBe('')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user