Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): reap Windows scan subprocesses
DavidShencc6adb760556
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex a897ea3fb4..2293114f45 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -379,6 +379,7 @@ import {import { reapClaudeOrphansSync } from './claude-orphan-reaper';import { startAgentProcessPriorityWatcher } from './agent-process-priority';import { registerProcessMonitorIpc } from './process-monitor/ipc.js';+import { disposeWindowsProcessScanWorkers } from './process-monitor/windowsProcessScanWorkerClient.js';import { initAppBadgeService, clearAllSessionAttention } from './appBadgeService';import { initNotificationService } from './notificationService';import { initWecomGroupNotificationIpc } from './wecomGroupNotification';@@ -8113,6 +8114,7 @@ onQuit('sync',);onQuit('auth-manager', () => authManager.dispose(), 'sync');+onQuit('windows-process-scan-workers', disposeWindowsProcessScanWorkers, 'sync');onQuit('resource-usage-window', () => resourceUsageWindowController.dispose(), 'sync');onQuit('rsb-window', () => rsbWindowController.dispose(), 'sync');onQuit('ghost-panel-windows', () => ghostPanelWindowsController.dispose(), 'sync');diff --git a/apps/desktop/src/main/process-monitor/__tests__/windowsProcessScanWorkerClient.test.ts b/apps/desktop/src/main/process-monitor/__tests__/windowsProcessScanWorkerClient.test.tsindex be07312093..f3f03d6f7e 100644--- a/apps/desktop/src/main/process-monitor/__tests__/windowsProcessScanWorkerClient.test.ts+++ b/apps/desktop/src/main/process-monitor/__tests__/windowsProcessScanWorkerClient.test.ts@@ -1,41 +1,99 @@+import { execFileSync, spawn, type ChildProcess } from 'node:child_process';import { EventEmitter } from 'node:events';-import { describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import {+ disposeWindowsProcessScanWorkers,runWindowsProcessScanWorker,type WindowsProcessScanWorkerHandle,} from '../windowsProcessScanWorkerClient.js';class FakeWorker extends EventEmitter implements WindowsProcessScanWorkerHandle {+ postMessage = vi.fn();+ unref = vi.fn();terminate = vi.fn(async () => 0);}+afterEach(() => {+ disposeWindowsProcessScanWorkers();+});+describe('runWindowsProcessScanWorker', () => {- it('返回 worker 的 PowerShell 输出并回收一次性线程', async () => {+ it('returns PowerShell output and releases the one-shot worker', async () => {const worker = new FakeWorker();- const result = runWindowsProcessScanWorker({ createWorker: () => worker });+ const terminateProcessTree = vi.fn();+ const result = runWindowsProcessScanWorker({+ createWorker: () => worker,+ terminateProcessTree,+ });- worker.emit('message', { ok: true, stdout: '1|0|1024|0||cindy.exe' });+ worker.emit('message', { type: 'started', pid: 1234 });+ worker.emit('message', {+ type: 'result',+ response: { ok: true, stdout: '1|0|1024|0||cindy.exe' },+ });await expect(result).resolves.toBe('1|0|1024|0||cindy.exe');+ expect(terminateProcessTree).not.toHaveBeenCalled();+ expect(worker.unref).toHaveBeenCalledOnce();expect(worker.terminate).toHaveBeenCalledOnce();});- it('worker 内 child_process 的 ENOTCONN 只拒绝本次扫描', async () => {+ it('kills the announced PowerShell process when the worker emits ENOTCONN', async () => {const worker = new FakeWorker();- const result = runWindowsProcessScanWorker({ createWorker: () => worker });+ const terminateProcessTree = vi.fn();+ const result = runWindowsProcessScanWorker({+ createWorker: () => worker,+ terminateProcessTree,+ });const error = Object.assign(new Error('read ENOTCONN'), {code: 'ENOTCONN',syscall: 'read',});+ worker.emit('message', { type: 'started', pid: 4321 });worker.emit('error', error);await expect(result).rejects.toMatchObject({ code: 'ENOTCONN', syscall: 'read' });+ expect(worker.postMessage).toHaveBeenCalledWith({ type: 'cancel' });+ expect(terminateProcessTree).toHaveBeenCalledWith(4321);expect(worker.terminate).toHaveBeenCalledOnce();});- it('worker 未返回消息就退出时失败并回收', async () => {+ it('kills the announced PowerShell process when the worker times out', async () => {+ const worker = new FakeWorker();+ const terminateProcessTree = vi.fn();+ const result = runWindowsProcessScanWorker({+ createWorker: () => worker,+ timeoutMs: 5,+ terminateProcessTree,+ });++ worker.emit('message', { type: 'started', pid: 5678 });++ await expect(result).rejects.toMatchObject({ code: 'ETIMEDOUT' });+ expect(terminateProcessTree).toHaveBeenCalledWith(5678);+ expect(worker.terminate).toHaveBeenCalledOnce();+ });++ it('kills active PowerShell processes during application disposal', async () => {+ const worker = new FakeWorker();+ const terminateProcessTree = vi.fn();+ const result = runWindowsProcessScanWorker({+ createWorker: () => worker,+ terminateProcessTree,+ });++ worker.emit('message', { type: 'started', pid: 6789 });+ disposeWindowsProcessScanWorkers();++ expect(terminateProcessTree).toHaveBeenCalledWith(6789);+ expect(worker.terminate).toHaveBeenCalledOnce();+ worker.emit('exit', 1);+ await expect(result).rejects.toThrow('exited before response (1)');+ });++ it('fails and releases the worker when it exits before responding', async () => {const worker = new FakeWorker();const result = runWindowsProcessScanWorker({ createWorker: () => worker });@@ -44,4 +102,108 @@ describe('runWindowsProcessScanWorker', () => {await expect(result).rejects.toThrow('exited before response (1)');expect(worker.terminate).toHaveBeenCalledOnce();});++ it.runIf(process.platform === 'win32')(+ 'does not leave PowerShell alive after a worker crash',+ async () => {+ const child = spawnSleepingPowerShell();+ const pid = requirePid(child);+ try {+ const worker = new FakeWorker();+ const result = runWindowsProcessScanWorker({ createWorker: () => worker });++ worker.emit('message', { type: 'started', pid });+ expect(isProcessAlive(pid)).toBe(true);+ worker.emit('error', Object.assign(new Error('read ENOTCONN'), { code: 'ENOTCONN' }));++ await expect(result).rejects.toMatchObject({ code: 'ENOTCONN' });+ expect(isProcessAlive(pid)).toBe(false);+ } finally {+ forceKillProcessTree(pid);+ }+ },+ );++ it.runIf(process.platform === 'win32')(+ 'does not leave PowerShell alive after the outer timeout',+ async () => {+ const child = spawnSleepingPowerShell();+ const pid = requirePid(child);+ try {+ const worker = new FakeWorker();+ const result = runWindowsProcessScanWorker({+ createWorker: () => worker,+ timeoutMs: 10,+ });++ worker.emit('message', { type: 'started', pid });+ expect(isProcessAlive(pid)).toBe(true);++ await expect(result).rejects.toMatchObject({ code: 'ETIMEDOUT' });+ expect(isProcessAlive(pid)).toBe(false);+ } finally {+ forceKillProcessTree(pid);+ }+ },+ );++ it.runIf(process.platform === 'win32')(+ 'does not leave PowerShell alive during application disposal',+ async () => {+ const child = spawnSleepingPowerShell();+ const pid = requirePid(child);+ try {+ const worker = new FakeWorker();+ const result = runWindowsProcessScanWorker({ createWorker: () => worker });++ worker.emit('message', { type: 'started', pid });+ expect(isProcessAlive(pid)).toBe(true);+ disposeWindowsProcessScanWorkers();++ expect(isProcessAlive(pid)).toBe(false);+ worker.emit('exit', 1);+ await expect(result).rejects.toThrow('exited before response (1)');+ } finally {+ forceKillProcessTree(pid);+ }+ },+ );});++function spawnSleepingPowerShell(): ChildProcess {+ return spawn(+ 'powershell.exe',+ ['-NoProfile', '-NonInteractive', '-Command', 'Start-Sleep -Seconds 30'],+ {+ windowsHide: true,+ stdio: 'ignore',+ },+ );+}++function requirePid(child: ChildProcess): number {+ if (typeof child.pid !== 'number') throw new Error('PowerShell did not expose a PID');+ return child.pid;+}++function isProcessAlive(pid: number): boolean {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return (error as NodeJS.ErrnoException).code !== 'ESRCH';+ }+}++function forceKillProcessTree(pid: number): void {+ if (!isProcessAlive(pid)) return;+ try {+ execFileSync('taskkill', ['/T', '/F', '/PID', String(pid)], {+ timeout: 2_000,+ windowsHide: true,+ stdio: 'ignore',+ });+ } catch {+ // The assertion reports cleanup failure; this is only a best-effort test teardown.+ }+}diff --git a/apps/desktop/src/main/process-monitor/windowsProcessScanProtocol.ts b/apps/desktop/src/main/process-monitor/windowsProcessScanProtocol.tsindex 45d7779a92..841a625999 100644--- a/apps/desktop/src/main/process-monitor/windowsProcessScanProtocol.ts+++ b/apps/desktop/src/main/process-monitor/windowsProcessScanProtocol.ts@@ -18,6 +18,9 @@ export type WindowsProcessScanWorkerResponse =};};+export type WindowsProcessScanWorkerMessage =+ { type: 'started'; pid: number } | { type: 'result'; response: WindowsProcessScanWorkerResponse };+export function isWindowsProcessScanWorkerResponse(value: unknown,): value is WindowsProcessScanWorkerResponse {@@ -35,3 +38,14 @@ export function isWindowsProcessScanWorkerResponse((response.error.syscall === undefined || typeof response.error.syscall === 'string'));}++export function isWindowsProcessScanWorkerMessage(+ value: unknown,+): value is WindowsProcessScanWorkerMessage {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;+ const message = value as { type?: unknown; pid?: unknown; response?: unknown };+ if (message.type === 'started') {+ return Number.isSafeInteger(message.pid) && Number(message.pid) > 0;+ }+ return message.type === 'result' && isWindowsProcessScanWorkerResponse(message.response);+}diff --git a/apps/desktop/src/main/process-monitor/windowsProcessScanWorker.ts b/apps/desktop/src/main/process-monitor/windowsProcessScanWorker.tsindex afa4a271be..9871caa506 100644--- a/apps/desktop/src/main/process-monitor/windowsProcessScanWorker.ts+++ b/apps/desktop/src/main/process-monitor/windowsProcessScanWorker.ts@@ -1,44 +1,144 @@-import { execFile } from 'node:child_process';+import { spawn, type ChildProcess } from 'node:child_process';// eslint-disable-next-line no-restricted-imports -- child-process pipe failures are isolated from Electron Main.import { parentPort } from 'node:worker_threads';-import { promisify } from 'node:util';import {WINDOWS_PROCESS_SCAN_SCRIPT,+ type WindowsProcessScanWorkerMessage,type WindowsProcessScanWorkerResponse,} from './windowsProcessScanProtocol.js';-const execFileAsync = promisify(execFile);+const CHILD_TIMEOUT_MS = 10_000;+const MAX_STDOUT_BYTES = 8 * 1024 * 1024;+const MAX_STDERR_BYTES = 64 * 1024;++if (!parentPort) throw new Error('Windows process scan must run in a worker thread');const workerPort = parentPort;-if (!workerPort) throw new Error('Windows process scan must run in a worker thread');+runWindowsProcessTable();-void scanWindowsProcessTable().then(- (stdout) =>- workerPort.postMessage({ ok: true, stdout } satisfies WindowsProcessScanWorkerResponse),- (error: unknown) => {- const errno = error as NodeJS.ErrnoException;- workerPort.postMessage({- ok: false,- error: {- message: error instanceof Error ? error.message : String(error),- ...(typeof errno?.code === 'string' ? { code: errno.code } : {}),- ...(typeof errno?.syscall === 'string' ? { syscall: errno.syscall } : {}),+function runWindowsProcessTable(): void {+ let child: ChildProcess;+ try {+ child = spawn(+ 'powershell.exe',+ ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_PROCESS_SCAN_SCRIPT],+ {+ windowsHide: true,+ stdio: ['ignore', 'pipe', 'pipe'],},- } satisfies WindowsProcessScanWorkerResponse);- },-);--async function scanWindowsProcessTable(): Promise<string> {- const { stdout } = await execFileAsync(- 'powershell.exe',- ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_PROCESS_SCAN_SCRIPT],- {- encoding: 'utf8',- timeout: 10_000,- windowsHide: true,- maxBuffer: 8 * 1024 * 1024,+ );+ } catch (error) {+ workerPort.postMessage({+ type: 'result',+ response: workerFailure(error),+ } satisfies WindowsProcessScanWorkerMessage);+ workerPort.close();+ return;+ }++ let stdout = '';+ let stdoutBytes = 0;+ let stderr = '';+ let stderrBytes = 0;+ let pendingFailure: NodeJS.ErrnoException | null = null;+ let finished = false;+ const timeout = setTimeout(() => {+ failChild(workerError('Windows process scan PowerShell timed out', 'ETIMEDOUT'));+ }, CHILD_TIMEOUT_MS);+ timeout.unref?.();++ child.unref();+ child.stdout?.setEncoding('utf8');+ child.stderr?.setEncoding('utf8');++ const pid = child.pid;+ if (typeof pid === 'number' && pid > 0) {+ workerPort.postMessage({ type: 'started', pid } satisfies WindowsProcessScanWorkerMessage);+ }++ child.once('error', failChild);+ child.stdout?.on('error', failChild);+ child.stderr?.on('error', failChild);+ child.stdout?.on('data', (chunk: string) => {+ if (pendingFailure) return;+ stdoutBytes += Buffer.byteLength(chunk);+ if (stdoutBytes > MAX_STDOUT_BYTES) {+ failChild(workerError('Windows process scan stdout exceeded maxBuffer', 'ENOBUFS'));+ return;+ }+ stdout += chunk;+ });+ child.stderr?.on('data', (chunk: string) => {+ if (stderrBytes >= MAX_STDERR_BYTES) return;+ const remaining = MAX_STDERR_BYTES - stderrBytes;+ const slice = Buffer.from(chunk).subarray(0, remaining).toString('utf8');+ stderr += slice;+ stderrBytes += Buffer.byteLength(slice);+ });+ child.once('close', (code, signal) => {+ if (finished) return;+ clearTimeout(timeout);+ if (pendingFailure) {+ postResult(workerFailure(pendingFailure));+ return;+ }+ if (code === 0) {+ postResult({ ok: true, stdout });+ return;+ }+ postResult(+ workerFailure(+ workerError(+ stderr.trim() ||+ `Windows process scan PowerShell exited (${code ?? signal ?? 'unknown'})`,+ 'ECHILD',+ ),+ ),+ );+ });+ workerPort.once('message', (value: unknown) => {+ if ((value as { type?: unknown } | null)?.type === 'cancel') {+ failChild(workerError('Windows process scan cancelled', 'ECANCELED'));+ }+ });++ function failChild(error: unknown): void {+ if (finished || pendingFailure) return;+ pendingFailure = normalizeError(error);+ try {+ child.kill('SIGKILL');+ } catch {+ // Parent owns the announced PID and performs a taskkill fallback.+ }+ }++ function postResult(response: WindowsProcessScanWorkerResponse): void {+ if (finished) return;+ finished = true;+ clearTimeout(timeout);+ workerPort.removeAllListeners('message');+ workerPort.postMessage({ type: 'result', response } satisfies WindowsProcessScanWorkerMessage);+ workerPort.close();+ }+}++function workerFailure(error: unknown): WindowsProcessScanWorkerResponse {+ const errno = normalizeError(error);+ return {+ ok: false,+ error: {+ message: errno.message,+ ...(typeof errno.code === 'string' ? { code: errno.code } : {}),+ ...(typeof errno.syscall === 'string' ? { syscall: errno.syscall } : {}),},- );- return stdout;+ };+}++function normalizeError(error: unknown): NodeJS.ErrnoException {+ return error instanceof Error ? error : new Error(String(error));+}++function workerError(message: string, code: string): NodeJS.ErrnoException {+ return Object.assign(new Error(message), { code });}diff --git a/apps/desktop/src/main/process-monitor/windowsProcessScanWorkerClient.ts b/apps/desktop/src/main/process-monitor/windowsProcessScanWorkerClient.tsindex aa77eda502..627bf9b738 100644--- a/apps/desktop/src/main/process-monitor/windowsProcessScanWorkerClient.ts+++ b/apps/desktop/src/main/process-monitor/windowsProcessScanWorkerClient.ts@@ -1,36 +1,69 @@+import { execFileSync } from 'node:child_process';import path from 'node:path';// eslint-disable-next-line no-restricted-imports -- Windows child-process pipes must be isolated from Electron Main.import { Worker } from 'node:worker_threads';-import { isWindowsProcessScanWorkerResponse } from './windowsProcessScanProtocol.js';+import { isWindowsProcessScanWorkerMessage } from './windowsProcessScanProtocol.js';export const WINDOWS_PROCESS_SCAN_WORKER_TIMEOUT_MS = 12_000;export interface WindowsProcessScanWorkerHandle {- once(event: 'message', listener: (value: unknown) => void): this;+ on(event: 'message', listener: (value: unknown) => void): this;once(event: 'error', listener: (error: Error) => void): this;once(event: 'exit', listener: (code: number) => void): this;+ postMessage(value: unknown): void;+ unref(): void;terminate(): Promise<number>;}interface WindowsProcessScanWorkerOptions {createWorker?: () => WindowsProcessScanWorkerHandle;timeoutMs?: number;+ terminateProcessTree?: (pid: number) => void;}+interface ActiveWindowsProcessScan {+ worker: WindowsProcessScanWorkerHandle;+ childPid: number | null;+ childClosed: boolean;+ cleaning: boolean;+ cleanupPromise: Promise<void> | null;+ terminateProcessTree: (pid: number) => void;+}++const activeWindowsProcessScans = new Set<ActiveWindowsProcessScan>();+export async function runWindowsProcessScanWorker(options: WindowsProcessScanWorkerOptions = {},): Promise<string> {const worker =options.createWorker?.() ?? new Worker(path.join(__dirname, 'windowsProcessScanWorker.js'));+ const scan: ActiveWindowsProcessScan = {+ worker,+ childPid: null,+ childClosed: false,+ cleaning: false,+ cleanupPromise: null,+ terminateProcessTree: options.terminateProcessTree ?? terminateWindowsProcessTree,+ };+ worker.unref();+ activeWindowsProcessScans.add(scan);try {- return await waitForWorker(worker, options.timeoutMs ?? WINDOWS_PROCESS_SCAN_WORKER_TIMEOUT_MS);+ return await waitForWorker(scan, options.timeoutMs ?? WINDOWS_PROCESS_SCAN_WORKER_TIMEOUT_MS);} finally {- await worker.terminate().catch(() => void 0);+ await cleanupWindowsProcessScan(scan);+ activeWindowsProcessScans.delete(scan);}}-function waitForWorker(worker: WindowsProcessScanWorkerHandle, timeoutMs: number): Promise<string> {+export function disposeWindowsProcessScanWorkers(): void {+ for (const scan of activeWindowsProcessScans) {+ void cleanupWindowsProcessScan(scan);+ }+}++function waitForWorker(scan: ActiveWindowsProcessScan, timeoutMs: number): Promise<string> {+ const { worker } = scan;return new Promise((resolve, reject) => {let settled = false;const finish = (operation: () => void): void => {@@ -45,16 +78,34 @@ function waitForWorker(worker: WindowsProcessScanWorkerHandle, timeoutMs: number);timer.unref?.();- worker.once('message', (value) => {- if (!isWindowsProcessScanWorkerResponse(value)) {+ worker.on('message', (value) => {+ if (!isWindowsProcessScanWorkerMessage(value)) {finish(() => reject(new Error('invalid Windows process scan worker response')));return;}- if (value.ok) {- finish(() => resolve(value.stdout));+ if (value.type === 'started') {+ if (scan.childPid !== null && scan.childPid !== value.pid) {+ finish(() => reject(new Error('Windows process scan worker reported multiple PIDs')));+ return;+ }+ if (scan.cleaning) {+ terminatePowerShell(scan, value.pid);+ return;+ }+ scan.childPid = value.pid;return;}- finish(() => reject(workerError(value.error.message, value.error.code, value.error.syscall)));++ scan.childClosed = true;+ scan.childPid = null;+ const { response } = value;+ if (response.ok) {+ const { stdout } = response;+ finish(() => resolve(stdout));+ return;+ }+ const { error } = response;+ finish(() => reject(workerError(error.message, error.code, error.syscall)));});worker.once('error', (error) => finish(() => reject(error)));worker.once('exit', (code) =>@@ -65,6 +116,62 @@ function waitForWorker(worker: WindowsProcessScanWorkerHandle, timeoutMs: number});}+function cleanupWindowsProcessScan(scan: ActiveWindowsProcessScan): Promise<void> {+ if (scan.cleanupPromise) return scan.cleanupPromise;++ scan.cleaning = true;+ if (!scan.childClosed) {+ try {+ scan.worker.postMessage({ type: 'cancel' });+ } catch {+ // A crashed worker can no longer receive cancellation; the PID fallback remains available.+ }+ }+ terminateTrackedPowerShell(scan);++ const termination = scan.worker.terminate().catch(() => void 0);+ scan.cleanupPromise = termination.then(() => {+ // Catch a late "started" message delivered while terminate() was in flight.+ terminateTrackedPowerShell(scan);+ });+ return scan.cleanupPromise;+}++function terminateTrackedPowerShell(scan: ActiveWindowsProcessScan): void {+ const pid = scan.childPid;+ scan.childPid = null;+ if (pid === null) return;+ terminatePowerShell(scan, pid);+}++function terminatePowerShell(scan: ActiveWindowsProcessScan, pid: number): void {+ try {+ scan.terminateProcessTree(pid);+ } catch {+ // Cleanup must not mask the worker's original scan failure.+ }+}++function terminateWindowsProcessTree(pid: number): void {+ if (process.platform === 'win32') {+ try {+ execFileSync('taskkill', ['/T', '/F', '/PID', String(pid)], {+ timeout: 2_000,+ windowsHide: true,+ stdio: 'ignore',+ });+ return;+ } catch {+ // The process may already have exited; retain a direct-kill fallback below.+ }+ }+ try {+ process.kill(pid, 'SIGKILL');+ } catch {+ // The process is already gone or inaccessible.+ }+}+function workerError(message: string, code?: string, syscall?: string): NodeJS.ErrnoException {return Object.assign(new Error(message), {...(code ? { code } : {}),