merge: hapi upstream v0.34.1

Merge release tag v0.34.1 into the local deployment fork. Preserve local
features (Agent Team, Studio, session shares, skins, DSH Web runtime,
attachment cache, deploy tooling) while adopting upstream session-list,
composer, steering, model-catalog, native-client, and migration changes.

Regenerate the local chat_attachments migration as v31→v32 behind the
upstream v28-v31 ladder; keep DSH on the Web runtime instead of the ACP
transport added upstream.

Co-Authored-By: Claude Code <noreply@anthropic.com>
Co-Authored-By: HAPI <noreply@hapi.run>
This commit is contained in:
2026-11-05 00:51:11 +08:00
co-authored by Claude Code HAPI
1245 changed files with 120973 additions and 12391 deletions
+13 -5
View File
@@ -609,10 +609,18 @@ describe('MessageQueue2', () => {
expect(queue.beginReservationDispatch(reservation!)).toBe(true);
expect(queue.markReservationIndeterminate(reservation!)).toBe(true);
expect(queue.size()).toBe(0);
expect(queue.takeByLocalId('b')).toBe(reservation);
expect(queue.beginReservationDispatch(reservation!)).toBe(true);
expect(queue.restoreReservation(reservation!)).toBe(true);
expect(queue.takeByLocalId('b')).toBe(reservation);
const retry = queue.takeByLocalId('b');
expect(retry).not.toBeNull();
expect(retry).not.toBe(reservation);
expect(queue.beginReservationDispatch(retry!)).toBe(true);
expect(queue.commitReservation(reservation!)).toBe(false);
expect(queue.markReservationIndeterminate(reservation!)).toBe(false);
expect(queue.cancelByLocalId('b')).toBe('in-flight');
expect(queue.restoreReservation(retry!)).toBe(true);
const nextRetry = queue.takeByLocalId('b');
expect(nextRetry).not.toBeNull();
expect(nextRetry).not.toBe(retry);
expect(queue.commitReservation(retry!)).toBe(false);
});
it('allows a positive reconciliation after a queue reset', () => {
@@ -692,4 +700,4 @@ describe('MessageQueue2', () => {
expect(batch3?.message).toBe('after-isolated');
expect(batch3?.mode.type).toBe('B');
});
});
});
+56 -11
View File
@@ -8,8 +8,17 @@ export interface QueueItem<T> {
isolate?: boolean; // If true, this message must be processed alone
/** Stable FIFO key used when an async reservation is restored later. */
enqueueOrder?: number;
/**
* True when HAPI enqueued this item as an internal control message
* (e.g. Cursor Auto-review toggle slash), not a user-authored turn.
*/
internal?: boolean;
}
export type QueueItemOptions = {
internal?: boolean;
};
export type QueueReservation<T> = {
item: QueueItem<T>;
index: number;
@@ -137,7 +146,7 @@ export class MessageQueue2<T> {
* Use this when a slash command must run alone but earlier prompts must
* still be delivered in order.
*/
pushIsolated(message: string, mode: T, localId?: string): void {
pushIsolated(message: string, mode: T, localId?: string, options?: QueueItemOptions): void {
if (this.closed) {
throw new Error('Cannot push to closed queue');
}
@@ -151,6 +160,7 @@ export class MessageQueue2<T> {
modeHash,
localId,
isolate: true,
internal: options?.internal,
enqueueOrder: this.nextEnqueueOrder++
};
Object.defineProperty(item, 'enqueueOrder', { value: item.enqueueOrder, enumerable: false, writable: true });
@@ -261,7 +271,7 @@ export class MessageQueue2<T> {
* that failed transiently and must retry without batching against sibling
* prompts).
*/
unshiftIsolated(message: string, mode: T, localId?: string): void {
unshiftIsolated(message: string, mode: T, localId?: string, options?: QueueItemOptions): void {
if (this.closed) {
throw new Error('Cannot unshift to closed queue');
}
@@ -275,6 +285,7 @@ export class MessageQueue2<T> {
modeHash,
localId,
isolate: true,
internal: options?.internal,
enqueueOrder: this.previousEnqueueOrder--
};
Object.defineProperty(item, 'enqueueOrder', { value: item.enqueueOrder, enumerable: false, writable: true });
@@ -346,13 +357,16 @@ export class MessageQueue2<T> {
if (!localId) return null;
// An indeterminate steer is deliberately held outside the normal queue.
// A later explicit Steer retries that same reservation; automatic queue
// drains never see it.
// A later explicit Steer owns a fresh attempt, so an abandoned
// request's late callbacks cannot mutate its replacement.
const existing = this.reservations.get(localId);
if (existing) {
if (existing.state !== 'indeterminate') return null;
existing.state = 'reserved';
return existing;
const retry: QueueReservation<T> = { ...existing, state: 'reserved', cancelReason: undefined };
existing.state = 'cancelled';
existing.cancelReason = 'explicit';
this.reservations.set(localId, retry);
return retry;
}
const idx = this.queue.findIndex(item => item.localId === localId);
@@ -517,6 +531,37 @@ export class MessageQueue2<T> {
.filter((id): id is string => typeof id === 'string');
}
/** True if any pending (not yet dequeued) message matches the predicate. */
hasMessageMatching(predicate: (message: string) => boolean): boolean {
return this.queue.some((item) => predicate(item.message));
}
/**
* Drop pending items matching the predicate (e.g. reconcile an internal
* slash that a fresh spawn already satisfies). Does not hub-ack.
*/
removeItemsMatching(predicate: (item: QueueItem<T>) => boolean): number {
const kept: QueueItem<T>[] = [];
let removed = 0;
for (const item of this.queue) {
if (!predicate(item)) {
kept.push(item);
continue;
}
removed += 1;
if (item.localId) {
const reservation = this.reservations.get(item.localId);
if (reservation) {
reservation.cancelReason = 'explicit';
reservation.state = 'cancelled';
this.reservations.delete(item.localId);
}
}
}
this.queue = kept;
return removed;
}
/**
* Close the queue - no more messages can be pushed
*/
@@ -551,7 +596,7 @@ export class MessageQueue2<T> {
* Wait for messages and return all messages with the same mode as a single string
* Returns { message: string, mode: T } or null if aborted/closed
*/
async waitForMessagesAndGetAsString(abortSignal?: AbortSignal): Promise<{ message: string, mode: T, isolate: boolean, hash: string, items: Array<{ message: string, localId?: string }> } | null> {
async waitForMessagesAndGetAsString(abortSignal?: AbortSignal): Promise<{ message: string, mode: T, isolate: boolean, hash: string, items: Array<{ message: string, localId?: string, internal?: boolean }> } | null> {
// If we have messages, return them immediately
if (this.queue.length > 0) {
return this.collectBatch();
@@ -575,7 +620,7 @@ export class MessageQueue2<T> {
/**
* Collect a batch of messages with the same mode, respecting isolation requirements
*/
private collectBatch(): { message: string, mode: T, hash: string, isolate: boolean, items: Array<{ message: string, localId?: string }> } | null {
private collectBatch(): { message: string, mode: T, hash: string, isolate: boolean, items: Array<{ message: string, localId?: string, internal?: boolean }> } | null {
if (this.queue.length === 0) {
return null;
}
@@ -587,7 +632,7 @@ export class MessageQueue2<T> {
// `message` string below so callers that need to requeue individual
// messages (e.g. restoring a failed batch with each item's own
// localId intact) don't have to re-split an already-joined string.
const items: Array<{ message: string, localId?: string }> = [];
const items: Array<{ message: string, localId?: string, internal?: boolean }> = [];
let mode = firstItem.mode;
let isolate = firstItem.isolate ?? false;
const targetModeHash = firstItem.modeHash;
@@ -596,7 +641,7 @@ export class MessageQueue2<T> {
if (firstItem.isolate) {
const item = this.queue.shift()!;
sameModeMessages.push(item.message);
items.push({ message: item.message, localId: item.localId });
items.push({ message: item.message, localId: item.localId, internal: item.internal });
if (item.localId) consumedLocalIds.push(item.localId);
logger.debug(`[MessageQueue2] Collected isolated message with mode hash: ${targetModeHash}`);
} else {
@@ -606,7 +651,7 @@ export class MessageQueue2<T> {
!this.queue[0].isolate) {
const item = this.queue.shift()!;
sameModeMessages.push(item.message);
items.push({ message: item.message, localId: item.localId });
items.push({ message: item.message, localId: item.localId, internal: item.internal });
if (item.localId) consumedLocalIds.push(item.localId);
}
logger.debug(`[MessageQueue2] Collected batch of ${sameModeMessages.length} messages with mode hash: ${targetModeHash}`);
+93 -231
View File
@@ -41,6 +41,53 @@ function unavailable(command: string) {
}
describe('getHapiRunnerProcessIdentity on Windows', () => {
it.each(['', '[]', '{}', '{broken', JSON.stringify([{ ProcessId: 100, CreationDate: 'generation' }]),
JSON.stringify([{ ProcessId: process.pid }, { ProcessId: process.pid }]),
JSON.stringify([{ ProcessId: process.pid }, { ProcessId: 1.5 }]),
JSON.stringify([{ ProcessId: process.pid }, { ProcessId: -1 }])])(
'rejects an unverifiable complete process-generation snapshot: %s', async (stdout) => {
const { readWindowsProcessStartMarkers } = await import('./process')
spawnSyncMock.mockReturnValue(completed(stdout))
expect(readWindowsProcessStartMarkers()).toBeNull()
}
)
it('keeps present processes with unknown creation times distinct from absent processes', async () => {
const { readWindowsProcessStartMarkers } = await import('./process')
spawnSyncMock.mockReturnValue(completed(JSON.stringify([
{ ProcessId: process.pid, CreationDate: 'scanner-generation' },
{ ProcessId: 100, CreationDate: null }
])))
const snapshot = readWindowsProcessStartMarkers()!
expect(snapshot.has(100)).toBe(true)
expect(snapshot.get(100)).toBeNull()
expect(snapshot.has(200)).toBe(false)
})
it('does not use stdout as a complete snapshot after a failed OS query', async () => {
const { readWindowsProcessStartMarkers } = await import('./process')
const stdout = JSON.stringify([{ ProcessId: process.pid, CreationDate: 'scanner-generation' }])
spawnSyncMock.mockReturnValue(completed(stdout, 1))
expect(readWindowsProcessStartMarkers()).toBeNull()
spawnSyncMock.mockReturnValue({ ...completed(stdout), error: new Error('query failed') })
expect(readWindowsProcessStartMarkers()).toBeNull()
})
it('reads the generation directly from CIM without a redundant tasklist probe', async () => {
const { getProcessStartMarker } = await import('./process')
spawnSyncMock.mockImplementation((command: string) => command === 'powershell'
? completed('generation-100') : completed('hapi.exe 100 Console'))
expect(getProcessStartMarker(100)).toBe('generation-100')
expect(spawnSyncMock.mock.calls.filter(call => call[0] === 'tasklist')).toHaveLength(0)
})
it('keeps a missing CIM generation unknown and rejects invalid PIDs without probing', async () => {
const { getProcessStartMarker } = await import('./process')
spawnSyncMock.mockReturnValue(completed(''))
expect(getProcessStartMarker(100)).toBeNull()
spawnSyncMock.mockClear()
for (const pid of [0, -1, 1.5, NaN, Infinity]) expect(getProcessStartMarker(pid)).toBeNull()
expect(spawnSyncMock).not.toHaveBeenCalled()
})
beforeAll(() => {
if (!originalPlatformDescriptor?.configurable) {
throw new Error('process.platform is not configurable in this runtime')
@@ -179,6 +226,50 @@ describe('getHapiRunnerProcessIdentity on Windows', () => {
})
describe('killProcess on Windows (orphanReap / stopSession)', () => {
it('includes slow liveness probes in the graceful shutdown deadline', async () => {
let graceStarted: number | undefined
let alive = true
let forcedAt: number | undefined
spawnSyncMock.mockImplementation((command: string, args: string[] = []) => {
if (command === 'tasklist') {
// A synchronous OS query consumes real time even though it is
// not part of the timer used to yield between observations.
vi.setSystemTime(Date.now() + 400)
return completed(alive ? 'hapi.exe 7788 Console' : 'INFO: No tasks')
}
if (command === 'taskkill' && args.includes('/F')) {
forcedAt = Date.now()
alive = false
} else if (command === 'taskkill') {
graceStarted = Date.now()
}
return completed('')
})
const stopped = killProcess(7788)
await vi.runAllTimersAsync()
await expect(stopped).resolves.toBe(true)
expect(forcedAt).toBeDefined()
expect(graceStarted).toBeDefined()
// The two-second wait plus the final observation and taskkill's own
// liveness recheck, each taking 400ms in this scenario.
expect(forcedAt! - graceStarted!).toBeLessThanOrEqual(2_800)
})
it('bounds slow probes after forced shutdown without treating a live process as stopped', async () => {
const started = Date.now()
spawnSyncMock.mockImplementation((command: string) => {
if (command === 'tasklist') {
vi.setSystemTime(Date.now() + 400)
return completed('hapi.exe 7788 Console')
}
return completed('')
})
const stopped = killProcess(7788, true)
await vi.runAllTimersAsync()
await expect(stopped).resolves.toBe(false)
expect(Date.now() - started).toBeLessThanOrEqual(3_200)
})
beforeAll(() => {
if (!originalPlatformDescriptor?.configurable) {
throw new Error('process.platform is not configurable in this runtime')
@@ -335,137 +426,13 @@ describe('killProcess on Windows (orphanReap / stopSession)', () => {
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')
expect(cmd).toContain('$root=[long]4242')
expect(cmd).toContain('ParentProcessId')
// Statements must be on separate lines — spaces between `$x=@{}` tokens fail.
expect(cmd).toContain('\n$seen=@{}')
expect(cmd).toContain('\n$bfs=@()')
@@ -499,111 +466,6 @@ describe('killProcess on Windows (orphanReap / stopSession)', () => {
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)', () => {
+96 -41
View File
@@ -1,5 +1,7 @@
import type { ChildProcess } from 'node:child_process';
import spawn from 'cross-spawn';
import { readFileSync } from 'node:fs';
import { stopWindowsProcessTree, type WindowsStopReport } from './windowsProcessStop';
export const isWindows = (): boolean => process.platform === 'win32';
@@ -71,10 +73,40 @@ export function windowsProcessMarkerCimCommand(pid: number): string {
);
}
/** Linux boot and thread identity are independent of a potentially reused PID. */
export function normalizeBootId(value: unknown): string | null {
return typeof value === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value.trim())
? value.trim().toLowerCase()
: null;
}
export function getSystemBootId(): string | null {
if (process.platform !== 'linux') return null;
try {
return normalizeBootId(readFileSync('/proc/sys/kernel/random/boot_id', 'utf8'));
} catch {
return null;
}
}
export function getProcessThreadGroupId(pid: number): number | null {
if (process.platform !== 'linux' || !Number.isSafeInteger(pid) || pid <= 0) return null;
try {
const status = readFileSync(`/proc/${pid}/status`, 'utf8');
const match = /^Tgid:[ \t]+([0-9]+)[ \t]*$/m.exec(status);
const tgid = match ? Number(match[1]) : 0;
return Number.isSafeInteger(tgid) && tgid > 0 ? tgid : null;
} catch {
return null;
}
}
/** 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 (!Number.isInteger(pid) || pid <= 0) return null;
if (isWindows()) {
// CIM already answers whether this PID has a readable generation. A
// preceding tasklist adds a process launch without strengthening identity.
// 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', [
@@ -87,6 +119,7 @@ export function getProcessStartMarker(pid: number): string | null {
}
return null;
}
if (!isProcessAlive(pid)) return null;
const result = spawn.sync('ps', ['-p', String(pid), '-o', 'lstart='], {
stdio: 'pipe',
env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
@@ -96,6 +129,38 @@ export function getProcessStartMarker(pid: number): string | null {
return result.stdout?.toString().trim() || null;
}
/** A fresh complete listing. Null means unavailable, never proof of absence. */
export function readWindowsProcessStartMarkers(): ReadonlyMap<number, string | null> | null {
if (!isWindows()) return null;
try {
const command = [
"$ErrorActionPreference='Stop'",
'trap { exit 1 }',
'Get-CimInstance Win32_Process | Select-Object ProcessId,'
+ `@{N='CreationDate';E={if ($_.CreationDate) { ${WINDOWS_CIM_CREATION_DATE_MARKER_EXPR} } else { $null }}}`
+ ' | ConvertTo-Json -Compress',
].join('\n');
const result = spawn.sync('powershell', ['-NoProfile', '-NonInteractive', '-Command', command], {
encoding: 'utf8', windowsHide: true, timeout: SPAWN_SYNC_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024
});
if (result.error || result.status !== 0) return null;
const parsed: unknown = JSON.parse(result.stdout?.toString() ?? '');
const rows = Array.isArray(parsed) ? parsed : [parsed];
const markers = new Map<number, string | null>();
for (const value of rows) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const row = value as Record<string, unknown>;
if (typeof row.ProcessId !== 'number' || !Number.isInteger(row.ProcessId)
|| row.ProcessId < 0 || markers.has(row.ProcessId)) return null;
markers.set(row.ProcessId, typeof row.CreationDate === 'string' && row.CreationDate.length > 0
? row.CreationDate : null);
}
// This caller remains alive for the whole query. Missing it makes the
// listing unverifiable; do not infer that any other PID has exited.
return markers.has(process.pid) ? markers : null;
} catch { return null; }
}
// ponytail: ps -p is cheap and avoids PID-reuse false positives after OS upgrades/reboots
function isRunnerCommand(commandLine: string): boolean {
return /(?:^|\s)runner(?:\s|$)/.test(commandLine) && /(?:^|\s)start-sync(?:\s|$)/.test(commandLine);
@@ -218,7 +283,17 @@ export function windowsProcessTreeCimCommand(pid: number): string {
return [
"$ErrorActionPreference='Stop'",
'trap { exit 1 }',
`$root=${pid}`,
`$root=[long]${pid}`,
// One complete enumeration keeps cost independent of tree depth. Build
// parent links from the same observation, rather than querying each parent.
'$processes=@(Get-CimInstance Win32_Process)',
'if($processes.Count -eq 0 -or -not ($processes | Where-Object ProcessId -eq $PID)){ throw "Incomplete process snapshot" }',
'$children=@{}',
'foreach($process in $processes){',
' $parent=[long]$process.ParentProcessId',
' if(-not $children.ContainsKey($parent)){ $children[$parent]=[System.Collections.Generic.List[long]]::new() }',
' $children[$parent].Add([long]$process.ProcessId)',
'}',
'$seen=@{}',
'$bfs=@()',
'$queue=@($root)',
@@ -227,8 +302,7 @@ export function windowsProcessTreeCimCommand(pid: number): string {
' if($seen.ContainsKey($p)){continue}',
' $seen[$p]=$true',
' $bfs+=$p',
' Get-CimInstance Win32_Process -Filter "ParentProcessId=$p" |',
' ForEach-Object { $queue+=,[int]$_.ProcessId }',
' if($children.ContainsKey($p)){ foreach($child in $children[$p]){ $queue+=,$child } }',
'}',
// 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 ",")) }',
@@ -386,36 +460,11 @@ 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> {
export async function killProcessTreeByPid(pid: number, force: boolean = false, report?: (result: WindowsStopReport) => void): Promise<boolean> {
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 stopWindowsProcessTree(n, force, report);
}
return killProcessTree(n, force);
}
@@ -429,11 +478,15 @@ async function waitForProcessToDie(pid: number, force: boolean): Promise<void> {
// 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;
let deadline = Date.now() + maxWait;
while (isProcessAlive(pid) && waited < maxWait) {
await new Promise(r => setTimeout(r, pollInterval));
waited += pollInterval;
// OS probes are synchronous on Windows. Count their time against the
// grace period too, otherwise twenty slow tasklist calls can turn two
// seconds of graceful shutdown into a much longer archive request.
while (Date.now() < deadline && isProcessAlive(pid)) {
const remaining = deadline - Date.now();
if (remaining <= 0) break;
await new Promise(r => setTimeout(r, Math.min(pollInterval, remaining)));
}
// Graceful kill didn't finish — escalate (same structure on both platforms).
@@ -447,17 +500,19 @@ async function waitForProcessToDie(pid: number, force: boolean): Promise<void> {
} catch {
return;
}
waited = 0;
while (isProcessAlive(pid) && waited < 1000) {
await new Promise(r => setTimeout(r, pollInterval));
waited += pollInterval;
deadline = Date.now() + 1000;
while (Date.now() < deadline && isProcessAlive(pid)) {
const remaining = deadline - Date.now();
if (remaining <= 0) break;
await new Promise(r => setTimeout(r, Math.min(pollInterval, remaining)));
}
}
}
export async function killProcessByChildProcess(
child: ChildProcess,
force: boolean = false
force: boolean = false,
report?: (result: WindowsStopReport) => void
): Promise<boolean> {
const pid = child.pid;
if (!pid) {
@@ -465,5 +520,5 @@ export async function killProcessByChildProcess(
}
// Both platforms: tree-kill + full-tree verify (win32 must not trust root-only).
return killProcessTreeByPid(pid, force);
return killProcessTreeByPid(pid, force, report);
}
+68
View File
@@ -0,0 +1,68 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { readFileSync } from 'node:fs'
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs')>()
return { ...actual, readFileSync: vi.fn(actual.readFileSync) }
})
import { getSystemBootId, getProcessThreadGroupId, normalizeBootId } from './process'
const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!
const bootId = 'e7c92900-5693-4ba0-b40c-9dfc57512edb'
const read = vi.mocked(readFileSync)
function platform(value: string) {
Object.defineProperty(process, 'platform', { configurable: true, value })
}
afterEach(() => {
Object.defineProperty(process, 'platform', originalPlatform)
read.mockReset()
})
describe('Linux recovered process identity', () => {
it('reads and normalizes boot identity', () => {
platform('linux')
read.mockReturnValue(`${bootId.toUpperCase()}\n`)
expect(getSystemBootId()).toBe(bootId)
expect(read).toHaveBeenCalledWith('/proc/sys/kernel/random/boot_id', 'utf8')
})
it.each([undefined, null, '', 'invalid', 17])('rejects malformed boot identity %s', value => {
expect(normalizeBootId(value)).toBeNull()
})
it('reads the exact thread group field', () => {
platform('linux')
read.mockReturnValue('Name:\tgdbus\nTgid:\t2067\nPid:\t2109\n')
expect(getProcessThreadGroupId(2109)).toBe(2067)
expect(read).toHaveBeenCalledWith('/proc/2109/status', 'utf8')
})
it.each(['Tgid: 0', 'Tgid: -1', 'Tgid: 12junk', 'NotTgid: 12', 'Tgid: 9007199254740992'])('does not invent evidence from %s', value => {
platform('linux')
read.mockReturnValue(value)
expect(getProcessThreadGroupId(2109)).toBeNull()
})
it('keeps unavailable procfs evidence unknown', () => {
platform('linux')
read.mockImplementation(() => { throw new Error('EACCES') })
expect(getSystemBootId()).toBeNull()
expect(getProcessThreadGroupId(2109)).toBeNull()
})
it.each(['win32', 'darwin'])('does not probe procfs on %s', value => {
platform(value)
expect(getSystemBootId()).toBeNull()
expect(getProcessThreadGroupId(2109)).toBeNull()
expect(read).not.toHaveBeenCalled()
})
it.each([0, -1, NaN, 1.5, Infinity])('does not probe invalid pid %s', value => {
platform('linux')
expect(getProcessThreadGroupId(value)).toBeNull()
expect(read).not.toHaveBeenCalled()
})
})
+59 -3
View File
@@ -29,24 +29,58 @@ const dummyOptions = {
describe('spawnWithTerminalGuard', () => {
let stdinPauseSpy: ReturnType<typeof vi.spyOn>;
let stdinResumeSpy: ReturnType<typeof vi.spyOn>;
let stdinDestroySpy: ReturnType<typeof vi.spyOn>;
let destroyedDescriptor: PropertyDescriptor | undefined;
let isTTYDescriptor: PropertyDescriptor | undefined;
const setStdinDestroyed = (value: boolean) => {
Object.defineProperty(process.stdin, 'destroyed', {
configurable: true,
get: () => value
});
};
const setStdinIsTTY = (value: boolean | undefined) => {
Object.defineProperty(process.stdin, 'isTTY', {
configurable: true,
get: () => value
});
};
beforeEach(() => {
vi.clearAllMocks();
stdinPauseSpy = vi.spyOn(process.stdin, 'pause').mockImplementation(() => process.stdin);
stdinResumeSpy = vi.spyOn(process.stdin, 'resume').mockImplementation(() => process.stdin);
stdinDestroySpy = vi.spyOn(process.stdin, 'destroy').mockImplementation(() => process.stdin);
destroyedDescriptor = Object.getOwnPropertyDescriptor(process.stdin, 'destroyed');
isTTYDescriptor = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
setStdinDestroyed(false);
setStdinIsTTY(true);
});
afterEach(() => {
stdinPauseSpy.mockRestore();
stdinResumeSpy.mockRestore();
stdinDestroySpy.mockRestore();
if (destroyedDescriptor) {
Object.defineProperty(process.stdin, 'destroyed', destroyedDescriptor);
} else {
delete (process.stdin as unknown as { destroyed?: unknown }).destroyed;
}
if (isTTYDescriptor) {
Object.defineProperty(process.stdin, 'isTTY', isTTYDescriptor);
} else {
delete (process.stdin as unknown as { isTTY?: unknown }).isTTY;
}
});
it('pauses stdin before spawn and resumes after success', async () => {
it('releases (pauses and destroys) stdin before spawn and resumes after success', async () => {
mockSpawnWithAbort.mockResolvedValue();
await spawnWithTerminalGuard(dummyOptions);
expect(stdinPauseSpy).toHaveBeenCalledOnce();
expect(stdinDestroySpy).toHaveBeenCalledOnce();
expect(stdinResumeSpy).toHaveBeenCalledOnce();
expect(mockRestoreTerminalState).toHaveBeenCalledOnce();
});
@@ -68,6 +102,17 @@ describe('spawnWithTerminalGuard', () => {
expect(mockRestoreTerminalState).toHaveBeenCalledOnce();
});
it('does not resume stdin when the stream was destroyed', async () => {
mockSpawnWithAbort.mockImplementation(async () => {
setStdinDestroyed(true);
});
await spawnWithTerminalGuard(dummyOptions);
expect(stdinResumeSpy).not.toHaveBeenCalled();
expect(mockRestoreTerminalState).toHaveBeenCalledOnce();
});
it('propagates the original error from spawnWithAbort', async () => {
const error = new Error('process exited with code 1');
mockSpawnWithAbort.mockRejectedValue(error);
@@ -75,12 +120,23 @@ describe('spawnWithTerminalGuard', () => {
await expect(spawnWithTerminalGuard(dummyOptions)).rejects.toThrow(error);
});
it('calls pause before spawn, and resume after spawn', async () => {
it('preserves piped stdin: pauses without destroying, then resumes', async () => {
setStdinIsTTY(undefined);
mockSpawnWithAbort.mockResolvedValue();
await spawnWithTerminalGuard(dummyOptions);
expect(stdinPauseSpy.mock.invocationCallOrder[0])
expect(stdinPauseSpy).toHaveBeenCalledOnce();
expect(stdinDestroySpy).not.toHaveBeenCalled();
expect(stdinResumeSpy).toHaveBeenCalledOnce();
});
it('releases stdin before spawn, and resumes after spawn', async () => {
mockSpawnWithAbort.mockResolvedValue();
await spawnWithTerminalGuard(dummyOptions);
expect(stdinDestroySpy.mock.invocationCallOrder[0])
.toBeLessThan(mockSpawnWithAbort.mock.invocationCallOrder[0]);
expect(mockSpawnWithAbort.mock.invocationCallOrder[0])
.toBeLessThan(stdinResumeSpy.mock.invocationCallOrder[0]);
+9 -4
View File
@@ -1,16 +1,21 @@
import { restoreTerminalState } from '@/ui/terminalState';
import { releaseStdinForChild } from '@/utils/stdinLifecycle';
import { spawnWithAbort, type SpawnWithAbortOptions } from '@/utils/spawnWithAbort';
/**
* Guards the terminal around a spawnWithAbort call: pauses stdin before spawn,
* then resumes stdin and restores terminal escape state in finally.
* Guards the terminal around a spawnWithAbort call: releases stdin before
* spawn (pause() alone is not enough — Bun keeps a pending read on fd 0 that
* starves the child; see stdinLifecycle), then resumes stdin and restores
* terminal escape state in finally.
*/
export async function spawnWithTerminalGuard(options: SpawnWithAbortOptions): Promise<void> {
process.stdin.pause();
releaseStdinForChild();
try {
await spawnWithAbort(options);
} finally {
process.stdin.resume();
if (!process.stdin.destroyed) {
process.stdin.resume();
}
restoreTerminalState();
}
}
+60
View File
@@ -0,0 +1,60 @@
import tty from 'node:tty';
import { logger } from '@/ui/logger';
// Why this module exists:
// Bun's tty.ReadStream keeps an in-flight read on fd 0 even after pause()
// (https://github.com/oven-sh/bun/issues/29126). When a session switches from
// remote mode back to local mode, the agent TUI is spawned with
// stdio:'inherit' and races that stale read for console input — and loses.
// The TUI renders but no keystroke ever reaches it.
// The only reliable way to stop the read under Bun is to destroy the stdin
// stream outright; remote mode re-creates it via ensureLiveStdin() when it
// starts up again.
/**
* Stop consuming stdin so a child spawned with stdio:'inherit' gets all
* console input. Destroys the stream because pause() alone leaves a pending
* read under Bun.
*/
export function releaseStdinForChild(): void {
try {
process.stdin.pause();
} catch {
}
// Destroying is only needed for a TTY (Bun's stale pending read). For
// piped stdin, destroy() would close fd 0 and starve a child spawned
// with stdio:'inherit'; pause() is sufficient there.
if (process.stdin.destroyed || !process.stdin.isTTY) {
return;
}
try {
process.stdin.destroy();
} catch (error) {
logger.debug('[stdinLifecycle] Failed to destroy stdin', error);
}
}
/**
* Re-create process.stdin from fd 0 after releaseStdinForChild() destroyed
* it. No-op when stdin is still alive or fd 0 is not a terminal (remote mode
* without a TTY never reads stdin).
*/
export function ensureLiveStdin(): void {
if (!process.stdin.destroyed) {
return;
}
if (!tty.isatty(0)) {
return;
}
try {
const fresh = new tty.ReadStream(0);
Object.defineProperty(process, 'stdin', {
value: fresh,
writable: true,
configurable: true
});
logger.debug('[stdinLifecycle] Re-created process.stdin from fd 0');
} catch (error) {
logger.debug('[stdinLifecycle] Failed to re-create stdin', error);
}
}
@@ -0,0 +1,42 @@
import { execFileSync } from 'node:child_process'
import { describe, expect, it } from 'vitest'
import { readWindowsProcessTable, WINDOWS_PROCESS_TABLE_COMMAND, windowsProcessTableCommand } from './windowsProcessStop'
describe.skipIf(process.platform !== 'win32')('Windows native process snapshot', () => {
it('runs the generated command under Windows PowerShell with matching generation markers', async () => {
const table = await readWindowsProcessTable(15_000, [process.pid], true)
expect(table).not.toBeNull()
expect(table!.get(process.pid)?.marker).toMatch(/^\d{4}-\d\d-\d\dT/)
expect(table!.get(process.pid)?.parentPid).toBeGreaterThanOrEqual(0)
expect(table!.get(process.pid)?.name).toBeTruthy()
const direct = await readWindowsProcessTable(15_000, [process.pid])
expect(direct?.get(process.pid)?.marker).toBe(table!.get(process.pid)?.marker)
}, 40_000)
it('uses invariant generation markers under a non-Gregorian current culture', () => {
const culture = "[System.Threading.Thread]::CurrentThread.CurrentCulture = [System.Globalization.CultureInfo]::GetCultureInfo('th-TH')\n"
const marker = (command: string): string => {
const output = execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', culture + command], {
windowsHide: true, timeout: 15_000, stdio: 'pipe', encoding: 'utf8',
})
return JSON.parse(output).processes[0].CreationDate
}
const direct = marker(windowsProcessTableCommand([process.pid]))
const cim = marker(windowsProcessTableCommand([process.pid], true))
expect(direct).toBe(cim)
}, 40_000)
it('represents a missing process as a complete empty filtered snapshot', async () => {
const table = await readWindowsProcessTable(15_000, [2147483647])
expect(table).not.toBeNull()
expect(table!.size).toBe(0)
}, 20_000)
it('exits unsuccessfully when CIM fails instead of emitting a partial success table', () => {
const script = "function Get-CimInstance { throw 'simulated CIM failure' }\n" + WINDOWS_PROCESS_TABLE_COMMAND
expect(() => execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], {
windowsHide: true, timeout: 15_000, stdio: 'pipe',
})).toThrow()
}, 20_000)
})
+213
View File
@@ -0,0 +1,213 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { execFileMock, syncMock } = vi.hoisted(() => ({ execFileMock: vi.fn(), syncMock: vi.fn() }))
vi.mock('node:child_process', () => ({ execFile: execFileMock }))
vi.mock('cross-spawn', () => ({ default: { sync: syncMock } }))
import { killProcessTreeByPid } from './process'
import { readWindowsProcessTable, windowsGenerationMayBeAlive } from './windowsProcessStop'
const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!
type Row = { ProcessId: number; ParentProcessId: number; CreationDate: string | null }
const row = (pid: number, parent = 0, marker: string | null = `gen-${pid}`): Row => ({
ProcessId: pid, ParentProcessId: parent, CreationDate: marker
})
describe('Windows asynchronous tree stop', () => {
let rows: Row[]
let kills: Array<{ pid: number; force: boolean; tree: boolean }>
let onKill: (pid: number, force: boolean) => void
let rejectSoft: boolean
beforeEach(() => {
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
rows = [row(0, 0, null), row(100), row(200, 100)]
kills = []
rejectSoft = false
onKill = pid => { rows = rows.filter(p => p.ProcessId !== pid) }
syncMock.mockReset().mockReturnValue({ status: 1, error: new Error('No synchronous probes permitted') })
execFileMock.mockReset().mockImplementation((file, args, _options, callback) => {
queueMicrotask(() => {
if (file === 'powershell') {
callback(null, JSON.stringify({ complete: true, processes: rows }), '')
} else {
const pid = Number(args[args.indexOf('/PID') + 1])
kills.push({ pid, force: args.includes('/F'), tree: args.includes('/T') })
onKill(pid, args.includes('/F'))
callback(rejectSoft && !args.includes('/F') ? new Error('Soft termination refused') : null, '', '')
}
})
return { kill: vi.fn() }
})
})
afterEach(() => {
Object.defineProperty(process, 'platform', originalPlatform)
vi.useRealTimers()
vi.restoreAllMocks()
})
it('confirms all descendants without blocking the runner with per-PID shell probes', async () => {
await expect(killProcessTreeByPid(100, true)).resolves.toBe(true)
expect(kills.map(k => k.pid)).toEqual([100, 200])
expect(syncMock).not.toHaveBeenCalled()
})
it('does not terminate a PID reused after the original descendant exits', async () => {
onKill = pid => {
rows = rows.filter(p => p.ProcessId !== pid)
if (pid === 100) rows = [row(0, 0, null), row(200, 0, 'new-generation')]
}
await expect(killProcessTreeByPid(100, true)).resolves.toBe(true)
expect(kills.map(k => k.pid)).toEqual([100])
})
it.each(['refused', 'grace-expired'])('force-stops new descendants tree-wide when soft termination is %s', async reason => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] })
rejectSoft = reason === 'refused'
onKill = (pid, force) => {
if (!force) { rows.push(row(300, 100)); return }
if (pid === 100 && kills.at(-1)?.tree) rows = [row(0, 0, null)]
else rows = rows.filter(p => p.ProcessId !== pid)
}
const operation = killProcessTreeByPid(100, false)
await vi.advanceTimersByTimeAsync(3_000)
await expect(operation).resolves.toBe(true)
expect(kills).toContainEqual({ pid: 100, force: true, tree: true })
expect(rows.some(p => p.ProcessId === 300)).toBe(false)
})
it('does not confirm cleanup if a newly discovered descendant survives forced tree termination', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] })
rejectSoft = true
onKill = (pid, force) => {
if (!force) { rows.push(row(300, 100)); return }
if (pid !== 300) rows = rows.filter(p => p.ProcessId !== pid)
}
const operation = killProcessTreeByPid(100, false)
await vi.advanceTimersByTimeAsync(46_000)
await expect(operation).resolves.toBe(false)
expect(rows.some(p => p.ProcessId === 300)).toBe(true)
})
it('does not force a replacement root or its new children after soft termination', async () => {
rejectSoft = true
onKill = (pid, force) => {
if (!force) {
rows = [row(0, 0, null), row(100, 0, 'replacement-root'), row(200, 100), row(300, 100)]
return
}
rows = rows.filter(p => p.ProcessId !== pid)
}
await expect(killProcessTreeByPid(100, false)).resolves.toBe(true)
expect(kills.filter(k => k.force).map(k => k.pid)).toEqual([200])
expect(rows.map(p => p.ProcessId)).toContain(300)
})
it.each([false, true])('terminates late descendants behind an exited intermediate process (force=%s)', async force => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] })
rows = [row(0, 0, null), row(100), row(200, 100), row(300, 200)]
onKill = (pid) => {
if (pid === 100) { rows = [row(0, 0, null), row(300, 200), row(400, 300)]; return }
if (pid === 300 && kills.at(-1)?.tree) rows = [row(0, 0, null)]
else rows = rows.filter(p => p.ProcessId !== pid)
}
const operation = killProcessTreeByPid(100, force)
await vi.advanceTimersByTimeAsync(3_000)
await expect(operation).resolves.toBe(true)
expect(kills).toContainEqual({ pid: 300, force: true, tree: true })
expect(rows.some(p => p.ProcessId === 400)).toBe(false)
})
it('does not confirm a disconnected survivor subtree while its new child remains alive', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] })
rows = [row(0, 0, null), row(100), row(200, 100), row(300, 200)]
onKill = pid => {
if (pid === 100) { rows = [row(0, 0, null), row(300, 200), row(400, 300)]; return }
if (pid !== 400) rows = rows.filter(p => p.ProcessId !== pid)
}
const operation = killProcessTreeByPid(100, true)
await vi.advanceTimersByTimeAsync(46_000)
await expect(operation).resolves.toBe(false)
expect(rows.some(p => p.ProcessId === 400)).toBe(true)
})
it('attempts root tree termination through a direct probe when CIM is unavailable', async () => {
execFileMock.mockImplementation((file, args, _options, callback) => {
queueMicrotask(() => {
if (file === 'powershell') {
const script = String(args.at(-1))
if (script.includes('Get-CimInstance')) callback(new Error('CIM failed'), '', '')
else callback(null, JSON.stringify({ complete: true, processes: [row(100)] }), '')
} else {
const pid = Number(args[args.indexOf('/PID') + 1])
kills.push({ pid, force: args.includes('/F'), tree: args.includes('/T') })
callback(null, '', '')
}
})
return { kill: vi.fn() }
})
await expect(killProcessTreeByPid(100, true)).resolves.toBe(false)
expect(kills).toContainEqual({ pid: 100, force: true, tree: true })
})
it('never treats a failed snapshot as proof of exit', async () => {
execFileMock.mockImplementation((_file, _args, _options, callback) => {
queueMicrotask(() => callback(new Error('CIM failed'), '', ''))
return { kill: vi.fn() }
})
await expect(killProcessTreeByPid(100, true)).resolves.toBe(false)
expect(kills).toEqual([])
})
it.each(['', '[]', '{"complete":true,"processes":[]}', '{"complete":false,"processes":[]}',
'{"complete":true,"processes":[{"ProcessId":100}]}'])('rejects incomplete or malformed snapshot %s', async output => {
execFileMock.mockImplementation((_file, _args, _options, callback) => {
queueMicrotask(() => callback(null, output, ''))
return { kill: vi.fn() }
})
expect(await readWindowsProcessTable()).toBeNull()
})
it('keeps ownership on failed or missing markers and recognizes only positive exit evidence', async () => {
const table = await readWindowsProcessTable()
expect(windowsGenerationMayBeAlive(null, 100, 'gen-100')).toBe(true)
expect(windowsGenerationMayBeAlive(table, 100, 'gen-100')).toBe(true)
expect(windowsGenerationMayBeAlive(table, 100, 'old-generation')).toBe(false)
expect(windowsGenerationMayBeAlive(table, 999, 'gen-999')).toBe(false)
})
it('does not signal a root whose PID was reused between snapshots', async () => {
let scans = 0
const implementation = execFileMock.getMockImplementation()!
execFileMock.mockImplementation((file, ...args) => {
if (file === 'powershell' && ++scans === 2) rows = [row(0, 0, null), row(100, 0, 'new-root')]
return implementation(file, ...args)
})
await expect(killProcessTreeByPid(100, true)).resolves.toBe(true)
expect(kills).toEqual([])
})
it('keeps the Runner event loop responsive while OS probes are pending', async () => {
const callbacks: Array<() => void> = []
execFileMock.mockImplementation((_file, _args, _options, callback) => {
callbacks.push(() => callback(new Error('probe unavailable'), '', ''))
return { kill: vi.fn() }
})
const operation = killProcessTreeByPid(100, true)
await new Promise(resolve => setTimeout(resolve, 0))
expect(callbacks).toHaveLength(1)
callbacks[0]()
await new Promise(resolve => setTimeout(resolve, 0))
expect(callbacks).toHaveLength(2)
callbacks[1]()
await expect(operation).resolves.toBe(false)
})
it('bounds an unkillable tree by elapsed time including OS queries', async () => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] })
onKill = () => {}
const operation = killProcessTreeByPid(100, true)
await vi.advanceTimersByTimeAsync(46_000)
await expect(operation).resolves.toBe(false)
expect(kills.every(k => k.force)).toBe(true)
expect(syncMock).not.toHaveBeenCalled()
})
})
+238
View File
@@ -0,0 +1,238 @@
import { execFile } from 'node:child_process'
export type WindowsProcessEntry = { parentPid: number; marker: string | null; name: string; commandLine: string }
export type WindowsProcessTable = Map<number, WindowsProcessEntry>
// One complete CIM snapshot supplies ancestry AND generation markers. Launching
// PowerShell/tasklist for each member made a small tree take over a minute.
export function windowsProcessTableCommand(pids?: number[], includeCommandLine = false): string {
if (pids?.length && !includeCommandLine) {
// Verification needs only PID + generation, not another WMI table.
// CIM truncates Windows FILETIME to microseconds; keep its existing
// marker format so both sources identify the same process generation.
return [
"$ErrorActionPreference='Stop'", 'trap { exit 1 }', '$rows=@(',
`foreach($processId in @(${pids.join(',')})){`,
' $p=$null',
' try { $p=[System.Diagnostics.Process]::GetProcessById($processId) }',
' catch [System.ArgumentException] { continue }',
' try {',
' try { $marker=$p.StartTime.ToUniversalTime().ToString("yyyy-MM-dd\'T\'HH:mm:ss.ffffff\'0Z\'", [System.Globalization.CultureInfo]::InvariantCulture) }',
' catch { if($p.HasExited){continue}; throw }',
' [pscustomobject]@{ProcessId=$processId;ParentProcessId=0;CreationDate=$marker}',
' } finally { if($p){$p.Dispose()} }',
'}', ')', '@{complete=$true;processes=$rows} | ConvertTo-Json -Depth 4 -Compress',
].join('\n')
}
const properties = `ProcessId,ParentProcessId,CreationDate${includeCommandLine ? ',Name,CommandLine' : ''}`
const filter = pids?.length ? ` -Filter "${pids.map(pid => `ProcessId = ${pid}`).join(' OR ')}"` : ''
return [
"$ErrorActionPreference='Stop'",
'trap { exit 1 }',
`$rows=@(Get-CimInstance Win32_Process -Property ${properties}${filter} | Select-Object ProcessId,ParentProcessId,Name,CommandLine,`,
" @{N='CreationDate';E={if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { $null }}})",
'@{complete=$true;processes=$rows} | ConvertTo-Json -Depth 4 -Compress',
].join('\n')
}
export const WINDOWS_PROCESS_TABLE_COMMAND = windowsProcessTableCommand()
function execute(file: string, args: string[], timeout: number): Promise<string | null> {
if (timeout <= 0) return Promise.resolve(null)
return new Promise(resolve => {
execFile(file, args, {
encoding: 'utf8', windowsHide: true, timeout: Math.ceil(timeout),
killSignal: 'SIGKILL', maxBuffer: 16 * 1024 * 1024,
}, (error, stdout) => resolve(error ? null : stdout))
})
}
export async function readWindowsProcessTable(timeout = 15_000, pids?: number[], includeCommandLine = false): Promise<WindowsProcessTable | null> {
if (pids?.some(pid => !Number.isInteger(pid) || pid < 0)) return null
const output = await execute('powershell', ['-NoProfile', '-NonInteractive', '-Command', windowsProcessTableCommand(pids, includeCommandLine)], timeout)
if (output === null) return null
try {
const parsed = JSON.parse(output)
if (parsed?.complete !== true || !Array.isArray(parsed.processes) || (!pids?.length && !parsed.processes.length)) return null
const table: WindowsProcessTable = new Map()
for (const entry of parsed.processes) {
if (!entry || !Number.isInteger(entry.ProcessId) || entry.ProcessId < 0
|| !Number.isInteger(entry.ParentProcessId) || entry.ParentProcessId < 0
|| (entry.CreationDate !== null && typeof entry.CreationDate !== 'string')
|| table.has(entry.ProcessId)) return null
table.set(entry.ProcessId, { parentPid: entry.ParentProcessId, marker: entry.CreationDate || null,
name: typeof entry.Name === 'string' ? entry.Name : '',
commandLine: typeof entry.CommandLine === 'string' ? entry.CommandLine : '',
})
}
return table
} catch { return null }
}
/** A failed probe conservatively keeps ownership; it must never authorize a kill. */
export function windowsGenerationMayBeAlive(table: WindowsProcessTable | null, pid: number, marker?: string): boolean {
if (table === null) return true
const entry = table.get(pid)
return Boolean(entry && (!entry.marker || !marker || entry.marker === marker))
}
export type WindowsStopReport = { confirmed: boolean; phase: string; elapsedMs: number; snapshots: number }
export async function stopWindowsProcessTree(rootPid: number, force: boolean, report?: (result: WindowsStopReport) => void): Promise<boolean> {
// Includes command startup, queries, signalling and verification, independent
// of tree size. Each async child is killed when its remaining budget expires.
const started = performance.now()
const deadline = started + 45_000
let phase = 'initial-snapshot', snapshots = 1
const finish = (confirmed: boolean) => {
report?.({ confirmed, phase, elapsedMs: Math.round(performance.now() - started), snapshots })
return confirmed
}
const remaining = () => Math.max(0, deadline - performance.now())
const signal = async (pid: number, hard: boolean, tree: boolean) => {
phase = 'signal'
return execute('taskkill', [
...(hard ? ['/F'] : []), ...(tree ? ['/T'] : []), '/PID', String(pid),
], Math.min(5_000, remaining()))
}
const initial = await readWindowsProcessTable(Math.min(15_000, remaining()))
if (!initial) {
// A transient CIM failure must not leave the cancellation path with no
// termination attempt. A direct process probe still supplies a
// generation-safe witness for the known root; descendants remain
// unverified, so the result stays unconfirmed.
phase = 'root-fallback-probe'; snapshots++
const rootProbe = await readWindowsProcessTable(Math.min(5_000, remaining()), [rootPid])
if (rootProbe?.get(rootPid)) await signal(rootPid, force, true)
return finish(false)
}
const members = new Map<number, string | null>()
const queue = [rootPid]
while (queue.length) {
const pid = queue.shift()!
if (members.has(pid)) continue
members.set(pid, initial.get(pid)?.marker ?? null)
for (const [child, entry] of initial) if (child !== pid && entry.parentPid === pid) queue.push(child)
}
const unresolved = new Map(members)
const snapshot = () => {
phase = 'verification-snapshot'; snapshots++
return readWindowsProcessTable(Math.min(10_000, remaining()), [...unresolved.keys()])
}
const refresh = (table: WindowsProcessTable) => {
for (const [pid, marker] of unresolved) {
const current = table.get(pid)
// A different known generation proves the ORIGINAL process exited.
// Once resolved, PID reuse cannot reintroduce it into this tree.
if (!current || (marker && current.marker && marker !== current.marker)) unresolved.delete(pid)
}
}
refresh(initial)
if (!unresolved.size) return finish(true)
// Recheck the root's generation immediately before tree-wide signalling.
let current = await snapshot()
if (!current) return finish(false)
refresh(current)
const rootMarker = members.get(rootPid)
if (unresolved.has(rootPid) && rootMarker && current.get(rootPid)?.marker === rootMarker) {
const softAccepted = await signal(rootPid, force, true)
if (!force && softAccepted !== null) {
const graceDeadline = Math.min(deadline, performance.now() + 2_000)
while (unresolved.size && performance.now() < graceDeadline) {
current = await snapshot()
if (!current) return finish(false)
refresh(current)
if (unresolved.size && performance.now() < graceDeadline) {
await new Promise(resolve => setTimeout(resolve, Math.min(100, graceDeadline - performance.now())))
}
}
}
}
if (!force && remaining()) {
// A console tree can grow while soft termination is refused or drains.
// Capture those descendants before escalation, rather than killing only
// the original PIDs and mistaking their exit for complete cleanup.
phase = 'escalation-snapshot'; snapshots++
const expanded = await readWindowsProcessTable(Math.min(15_000, remaining()))
if (!expanded) return finish(false)
refresh(expanded)
const root = expanded.get(rootPid)
if (!root || (rootMarker && root.marker === rootMarker)) {
const pending = [rootPid], seen = new Set<number>()
while (pending.length) {
const pid = pending.shift()!
if (seen.has(pid)) continue
seen.add(pid)
const entry = expanded.get(pid)
if (entry && !members.has(pid)) {
members.set(pid, entry.marker)
unresolved.set(pid, entry.marker)
}
for (const [child, candidate] of expanded) if (child !== pid && candidate.parentPid === pid) pending.push(child)
}
}
// Never tree-kill a replacement root. Recheck once more after the full
// snapshot so a slow CIM scan cannot authorize signalling a reused PID.
if (unresolved.has(rootPid) && rootMarker && root?.marker === rootMarker) {
current = await snapshot()
if (!current) return finish(false)
refresh(current)
if (unresolved.has(rootPid) && current.get(rootPid)?.marker === rootMarker) {
await signal(rootPid, true, true)
}
}
}
// A missing intermediate process disconnects a survivor from the root's
// taskkill /T traversal. Expand each surviving generation's OWN subtree,
// including new children, before forcing that subtree and verifying it.
const pendingSignals = [...unresolved.keys()].reverse()
const scheduled = new Set(pendingSignals)
for (let index = 0; index < pendingSignals.length; index++) {
const pid = pendingSignals[index]
if (!unresolved.size) return finish(true)
if (!remaining()) return finish(false)
current = await snapshot()
if (!current) return finish(false)
refresh(current)
if (!unresolved.size) return finish(true)
const expected = unresolved.get(pid)
if (!expected || current.get(pid)?.marker !== expected) continue
phase = 'survivor-subtree-snapshot'; snapshots++
const subtree = await readWindowsProcessTable(Math.min(15_000, remaining()))
if (!subtree) return finish(false)
refresh(subtree)
if (!unresolved.has(pid) || subtree.get(pid)?.marker !== expected) continue
const descendants = [pid], seen = new Set<number>()
while (descendants.length) {
const child = descendants.shift()!
if (seen.has(child)) continue
seen.add(child)
const entry = subtree.get(child)
if (!entry) continue
const captured = members.get(child)
if (captured && entry.marker && captured !== entry.marker) continue
if (!members.has(child)) {
members.set(child, entry.marker)
unresolved.set(child, entry.marker)
}
for (const [next, candidate] of subtree) if (next !== child && candidate.parentPid === child) descendants.push(next)
}
current = await snapshot()
if (!current) return finish(false)
refresh(current)
if (unresolved.has(pid) && current.get(pid)?.marker === expected) await signal(pid, true, true)
for (const child of unresolved.keys()) {
if (!scheduled.has(child)) { scheduled.add(child); pendingSignals.push(child) }
}
}
while (remaining()) {
current = await snapshot()
if (!current) return finish(false)
refresh(current)
if (!unresolved.size) return finish(true)
await new Promise(resolve => setTimeout(resolve, Math.min(100, remaining())))
}
return finish(false)
}
+11 -8
View File
@@ -70,13 +70,12 @@ describePwsh('windowsProcessTreeCimCommand under real pwsh (#1911 B1)', () => {
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 }
}
# A healthy full enumeration includes parent links and the scanner itself.
[pscustomobject]@{ ProcessId = 1234; ParentProcessId = 0 }
[pscustomobject]@{ ProcessId = 2000; ParentProcessId = 1234 }
[pscustomobject]@{ ProcessId = 3000; ParentProcessId = 1234 }
[pscustomobject]@{ ProcessId = 4000; ParentProcessId = 2000 }
[pscustomobject]@{ ProcessId = $PID; ParentProcessId = 0 }
}
${windowsProcessTreeCimCommand(1234)}
`
@@ -87,7 +86,11 @@ ${windowsProcessTreeCimCommand(1234)}
it('emits OK:root alone when the mocked tree has no children', () => {
const mock = `
function Get-CimInstance { param($ClassName, $Filter) }
function Get-CimInstance {
param($ClassName, $Filter)
[pscustomobject]@{ ProcessId = 1234; ParentProcessId = 0 }
[pscustomobject]@{ ProcessId = $PID; ParentProcessId = 0 }
}
${windowsProcessTreeCimCommand(1234)}
`
const result = runPwsh(mock)
@@ -0,0 +1,61 @@
import { describe, expect, it } from 'vitest'
import { execFileSync } from 'node:child_process'
import { windowsProcessTreeCimCommand } from './process'
// Execute the actual generated WinPS query against an in-memory CIM fixture.
// No process is signalled by this test.
describe.skipIf(process.platform !== 'win32')('Windows process-tree query', () => {
it('uses one CIM enumeration across the Windows PID range and terminates on parent cycles', () => {
const setup = `
$script:calls=0
$script:rows=@(
[pscustomobject]@{ProcessId=100;ParentProcessId=300},
[pscustomobject]@{ProcessId=200;ParentProcessId=100},
[pscustomobject]@{ProcessId=300;ParentProcessId=200},
[pscustomobject]@{ProcessId=[uint32]3000000000;ParentProcessId=200},
[pscustomobject]@{ProcessId=400;ParentProcessId=[uint32]4000000000},
[pscustomobject]@{ProcessId=$PID;ParentProcessId=0}
)
function Get-CimInstance {
param([string]$ClassName,[string]$Filter)
$script:calls++
if($Filter){
$parent=[int]($Filter -replace 'ParentProcessId=','')
return $script:rows|Where-Object ParentProcessId -eq $parent
}
return $script:rows
}
`
const output = execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command',
setup + windowsProcessTreeCimCommand(100) + '\n"COUNT:$script:calls"'],
{ encoding: 'utf8', windowsHide: true, timeout: 10_000 })
expect(output).toContain('OK:3000000000,300,200,100')
expect(output).toContain('COUNT:1')
})
it('never emits a success sentinel when CIM enumeration fails', () => {
const script = "function Get-CimInstance { throw 'fixture CIM failure' }\n" + windowsProcessTreeCimCommand(100)
let failure: { status?: number; stdout?: string } | undefined
try {
execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script],
{ encoding: 'utf8', windowsHide: true, timeout: 10_000, stdio: 'pipe' })
} catch (error) { failure = error as typeof failure }
expect(failure).toBeDefined()
expect(failure?.status).not.toBe(0)
expect(failure?.stdout ?? '').not.toContain('OK:')
})
it.each(['@()', '@([pscustomobject]@{ProcessId=100;ParentProcessId=0})'])(
'rejects an empty or partial enumeration without success: %s', (rows) => {
const script = `function Get-CimInstance { ${rows} }\n` + windowsProcessTreeCimCommand(100)
let failure: { status?: number; stdout?: string } | undefined
try {
execFileSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script],
{ encoding: 'utf8', windowsHide: true, timeout: 10_000, stdio: 'pipe' })
} catch (error) { failure = error as typeof failure }
expect(failure).toBeDefined()
expect(failure?.status).not.toBe(0)
expect(failure?.stdout ?? '').not.toContain('OK:')
}
)
})