Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(cindy-brain): 插件 Node worker 启动瞬时 EPERM 有界重试与 stderr 诊断透出 (#334)
Lizi6869ca7a898b
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.tsindex 4a2a68341d..5cc0ec50c3 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts@@ -263,6 +263,211 @@ describe('nodeRuntimeBroker · 进程生命周期', () => {});});+describe('nodeRuntimeBroker · 启动瞬时失败重试(2026-07-24)', () => {+ /** 就绪前即崩的假进程:Windows 杀软扫描刚写入的引导产物时的真实形态。 */+ function epermFailingProcess(): FakeNodeProcess {+ const failing = new FakeNodeProcess(undefined, false);+ queueMicrotask(() => {+ failing.stderr.write(+ "node:fs:560\nError: EPERM: operation not permitted, open 'C:\\app\\.vite\\build\\nodeRuntimeWorkerProcess.js'\n",+ );+ failing.emit('exit', 1, null);+ });+ return failing;+ }++ it('就绪前退出自动重试,第二次成功;并发请求共享同一次启动,不发假 crashed', async () => {+ vi.useFakeTimers();+ const ghost = fakeGhost();+ const pushes: Array<Record<string, unknown>> = [];+ let spawnCount = 0;+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => ghost,+ sendToGhost: (_id, payload) => pushes.push(payload as unknown as Record<string, unknown>),+ spawnProcess: () => {+ spawnCount += 1;+ const child = spawnCount === 1 ? epermFailingProcess() : makeAutoReplyProcess();+ return child as unknown as NodeWorkerProcess;+ },+ });++ const first = broker.handleRequest('node-ghost', rpcRequest('first'));+ const second = broker.handleRequest('node-ghost', rpcRequest('second'));+ await vi.advanceTimersByTimeAsync(2_000);+ await expect(first).resolves.toMatchObject({ ok: true, result: { method: 'first' } });+ await expect(second).resolves.toMatchObject({ ok: true, result: { method: 'second' } });+ expect(spawnCount).toBe(2);+ const states = pushes.filter((p) => p.name === 'node-status').map((p) => p.state);+ expect(states).toEqual(['starting', 'running']);+ broker.destroyAll();+ });++ it('连续失败耗尽重试:失败消息与 crashed 状态都带 stderr 诊断行,crashed 只发一次', async () => {+ vi.useFakeTimers();+ const ghost = fakeGhost();+ const pushes: Array<Record<string, unknown>> = [];+ let spawnCount = 0;+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => ghost,+ sendToGhost: (_id, payload) => pushes.push(payload as unknown as Record<string, unknown>),+ spawnProcess: () => {+ spawnCount += 1;+ return epermFailingProcess() as unknown as NodeWorkerProcess;+ },+ });++ const pending = broker.handleRequest('node-ghost', rpcRequest());+ await vi.advanceTimersByTimeAsync(5_000);+ const result = await pending;+ expect(result).toMatchObject({ ok: false, errorCode: 'PROCESS_START_FAILED' });+ expect((result as { message?: string }).message).toContain('启动前退出');+ expect((result as { message?: string }).message).toContain('EPERM');+ expect(spawnCount).toBe(3);+ const states = pushes.filter((p) => p.name === 'node-status').map((p) => p.state);+ expect(states).toEqual(['starting', 'crashed']);+ const crashed = pushes.find((p) => p.state === 'crashed') as { message?: string };+ expect(crashed.message).toContain('EPERM');+ expect(broker.stateOf('node-ghost')).toBe('off');+ });++ it('重试退避期间插件被停用:不再拉新进程', async () => {+ vi.useFakeTimers();+ const ghost = fakeGhost();+ let enabled = true;+ let spawnCount = 0;+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => (enabled ? ghost : null),+ spawnProcess: () => {+ spawnCount += 1;+ return epermFailingProcess() as unknown as NodeWorkerProcess;+ },+ });++ const pending = broker.handleRequest('node-ghost', rpcRequest());+ await vi.advanceTimersByTimeAsync(50); // 第一次尝试已失败,退避中+ enabled = false;+ await vi.advanceTimersByTimeAsync(5_000);+ await expect(pending).resolves.toMatchObject({ ok: false, errorCode: 'PROCESS_START_FAILED' });+ expect(spawnCount).toBe(1);+ });++ it('destroyAll 后到达的请求不拉新进程(首次尝试即短路)', async () => {+ const ghost = fakeGhost();+ const spawnProcess = vi.fn();+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => ghost,+ spawnProcess,+ });++ broker.destroyAll();+ const result = await broker.handleRequest('node-ghost', rpcRequest());+ expect(result).toMatchObject({ ok: false, errorCode: 'PROCESS_START_FAILED' });+ expect(spawnProcess).not.toHaveBeenCalled();+ });++ it('stop(ghostId) 取消在途重试:退避中不再拉新进程', async () => {+ vi.useFakeTimers();+ const ghost = fakeGhost();+ let spawnCount = 0;+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => ghost,+ spawnProcess: () => {+ spawnCount += 1;+ return epermFailingProcess() as unknown as NodeWorkerProcess;+ },+ });++ const pending = broker.handleRequest('node-ghost', rpcRequest());+ await vi.advanceTimersByTimeAsync(50);+ broker.stop('node-ghost');+ await vi.advanceTimersByTimeAsync(5_000);+ await expect(pending).resolves.toMatchObject({ ok: false, errorCode: 'PROCESS_START_FAILED' });+ expect(spawnCount).toBe(1);+ });++ it('stop 期间上层禁用阻拦请求;重新启用后 resident 由 startResident 恢复', async () => {+ const ghost = fakeGhost({ lifecycle: 'resident' });+ let enabled = true;+ let spawnCount = 0;+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => (enabled ? ghost : null),+ spawnProcess: () => {+ spawnCount += 1;+ return makeAutoReplyProcess() as unknown as NodeWorkerProcess;+ },+ });++ broker.stop('node-ghost');+ enabled = false;+ const blocked = await broker.handleRequest('node-ghost', rpcRequest());+ expect(blocked).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });+ expect(spawnCount).toBe(0);++ enabled = true;+ await broker.startResident(ghost);+ expect(spawnCount).toBe(1);+ const ok = await broker.handleRequest('node-ghost', rpcRequest());+ expect(ok).toMatchObject({ ok: true });+ broker.destroyAll();+ });++ it('按需插件 stop 后:上层重新启用时 handleRequest 自动恢复', async () => {+ const ghost = fakeGhost();+ let enabled = true;+ let spawnCount = 0;+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => (enabled ? ghost : null),+ spawnProcess: () => {+ spawnCount += 1;+ return makeAutoReplyProcess() as unknown as NodeWorkerProcess;+ },+ });++ broker.stop('node-ghost');+ enabled = false;+ const blocked = await broker.handleRequest('node-ghost', rpcRequest());+ expect(blocked).toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });+ expect(spawnCount).toBe(0);++ enabled = true;+ const ok = await broker.handleRequest('node-ghost', rpcRequest());+ expect(ok).toMatchObject({ ok: true });+ expect(spawnCount).toBe(1);+ broker.destroyAll();+ });++ it('诊断行不泄露绝对路径', async () => {+ vi.useFakeTimers();+ const ghost = fakeGhost();+ const pushes: Array<Record<string, unknown>> = [];+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => ghost,+ sendToGhost: (_id, payload) => pushes.push(payload as unknown as Record<string, unknown>),+ spawnProcess: () => {+ const failing = new FakeNodeProcess(undefined, false);+ queueMicrotask(() => {+ failing.stderr.write(+ "Error: EPERM: operation not permitted, open 'C:\\Users\\dev\\AppData\\Local\\cindy\\.vite\\build\\nodeRuntimeWorkerProcess.js'\n",+ );+ failing.emit('exit', 1, null);+ });+ return failing as unknown as NodeWorkerProcess;+ },+ });++ const pending = broker.handleRequest('node-ghost', rpcRequest());+ await vi.advanceTimersByTimeAsync(5_000);+ const result = await pending;+ expect((result as { message?: string }).message).toContain('EPERM');+ expect((result as { message?: string }).message).not.toContain('C:\\Users');+ expect((result as { message?: string }).message).not.toContain('AppData');+ const crashed = pushes.find((p) => p.state === 'crashed') as { message?: string };+ expect(crashed.message).toContain('EPERM');+ expect(crashed.message).not.toContain('C:\\Users');+ broker.destroyAll();+ });+});+describe('nodeRuntimeBroker · 权限与协议', () => {it('没声明 node 槽时拒绝且不启动进程', async () => {const ghost = fakeGhost();diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.tsindex 28f7e8e972..139c11ae3f 100644--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts@@ -41,6 +41,17 @@ import {const DEFAULT_IDLE_TIMEOUT_MS = 2 * 60_000;const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;const DEFAULT_START_TIMEOUT_MS = 10_000;+/**+ * 启动失败重试(2026-07-24):Windows 上杀软实时扫描刚写入的 .vite 产物 /+ * 刚更新的 app.asar 时,子进程读引导入口会瞬时 ACCESS_DENIED(表现为+ * "EPERM: operation not permitted, open …nodeRuntimeWorkerProcess.js" 后+ * 立即退出)。这类失败几百毫秒内自愈,给"fork 抛错 / 就绪前退出"留有界+ * 重试;启动超时不重试——进程活着只是没就绪,重跑只会成倍拉长等待。+ */+const WORKER_START_ATTEMPTS = 3;+const WORKER_START_RETRY_DELAYS_MS = [250, 750] as const;+/** 启动期 stderr 只留头部这么多字符,够提取一行诊断,不给日志灌洪。 */+const STARTUP_STDERR_CAP = 4_096;const MAX_REQUEST_TIMEOUT_MS = 120_000;const MAX_PENDING_REQUESTS = 32;const MAX_REQUEST_BYTES = 256 * 1024;@@ -126,6 +137,10 @@ interface WorkerEntry {/** 本进程对应的入口(相对路径;主入口 = manifest.node.entry)。 */entryRel: string;child: NodeWorkerProcess;+ /** 就绪握手完成前为 true:此阶段的退出由 ensureWorker 统一报告(可能重试),handleExit 不发 crashed。 */+ startupPhase: boolean;+ /** 启动期 stderr 头部截存,失败时提取一行诊断拼进错误消息(如杀软拦截的 EPERM)。 */+ startupStderr: string;/** stdout 的 UTF-8 字节可能把一个汉字切在两个 chunk 之间,必须流式解码。 */stdoutDecoder: StringDecoder;stdoutBuffer: string;@@ -149,6 +164,39 @@ class NodeRpcError extends Error {}}+/**+ * 工作进程启动失败:retryable 决定 ensureWorker 是否值得再试一次;+ * silent = 状态已由别处如实播报(如 stop 时的 'stopped'),不再补发 'crashed'。+ */+class WorkerStartError extends Error {+ constructor(+ message: string,+ readonly retryable: boolean,+ readonly silent = false,+ ) {+ super(message);+ }+}++/** 从启动期 stderr 里挑最有诊断价值的一行(优先含 error 的行),截短拼进失败消息。 */+function startupStderrHint(text: string): string | null {+ const lines = text+ .split(/\r?\n/)+ .map((line) => line.trim())+ .filter(Boolean);+ if (lines.length === 0) return null;+ const line = lines.find((candidate) => /error/i.test(candidate)) ?? lines[0];+ return sanitizePathsInHint(line.slice(0, 240));+}++function sanitizePathsInHint(hint: string): string {+ const basename = (p: string) => p.split(/[/\\]/).pop() ?? p;+ return hint+ .replace(/(['"])((?:[A-Z]:[/\\]|\/)[^'"]+)\1/g, (_, q, p) => `${q}${basename(p)}${q}`)+ .replace(/[A-Z]:[/\\][^\s'")\]]*/g, basename)+ .replace(/\/(?:[^\s/'")\]]+\/)+[^\s'")\]]*/g, basename);+}+type UtilityFork = typeof utilityProcess.fork;/**@@ -344,8 +392,10 @@ export class GhostNodeRuntimeBroker {return 'off';}- /** resident 档在插件启用/启动时调用;按需档保持零进程。常驻只覆盖主入口。 */+ /** resident 档在插件启用/启动时调用;按需档保持零进程。常驻只覆盖主入口。+ * 同时也是 stop() 的对称点:上层完成更新/重启后调用此方法,清除停止标记。 */async startResident(ghost: InstalledGhost): Promise<void> {+ this.stoppedGhosts.delete(ghost.manifest.id);if (!ghost.enabled || ghost.manifest.node?.lifecycle !== 'resident') return;const entry = await this.ensureWorker(ghost, ghost.manifest.node.entry);if (ghost.manifest.node.protocol === 'mcp-stdio') await this.ensureMcpInitialized(entry);@@ -357,6 +407,9 @@ export class GhostNodeRuntimeBroker {if (!ghost?.enabled || !ghost.manifest.slots.includes('node') || !ghost.manifest.node) {return errorResult('PERMISSION_DENIED', '插件未申请本地 Node 权限,或当前未启用');}+ // getGhost 确认插件当前已启用——这是按需插件的"后更新/重启边界",+ // 清除 stop() 留下的停止标记,使按需进程可以恢复启动。+ this.stoppedGhosts.delete(ghostId);if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {return errorResult('INVALID_REQUEST', 'node-request 载荷必须是对象');}@@ -741,6 +794,7 @@ export class GhostNodeRuntimeBroker {/** 停用、更新或卸载一个插件时立即停止其名下**全部** Node 进程。 */stop(ghostId: string): void {+ this.stoppedGhosts.add(ghostId);for (const [key, entry] of [...this.workers]) {if (entry.ghost.manifest.id === ghostId) this.stopWorker(key, entry);}@@ -776,33 +830,103 @@ export class GhostNodeRuntimeBroker {/** Cindy 退出时收掉全部随包 Node 进程。 */destroyAll(): void {+ this.destroyed = true;for (const [key, entry] of [...this.workers]) this.stopWorker(key, entry);}+ /** 同 key 在途启动去重:重试退避窗口内的并发请求共享同一次启动,不双开进程。 */+ private readonly startingWorkers = new Map<string, Promise<WorkerEntry>>();++ /** stop(ghostId) 置入:在途重试检测到后立即中止,不继续拉新进程。 */+ private readonly stoppedGhosts = new Set<string>();++ /** destroyAll(主机退出)后置真:退避中的重试不得再拉新进程。 */+ private destroyed = false;+private async ensureWorker(ghost: InstalledGhost, entryRel: string): Promise<WorkerEntry> {const key = GhostNodeRuntimeBroker.keyOf(ghost.manifest.id, entryRel);+ const inflight = this.startingWorkers.get(key);+ if (inflight) return inflight;const existing = this.workers.get(key);if (existing) return existing;- const node = ghost.manifest.node;- if (!node) throw new Error('ghost.json 缺少 node 工作进程详单');+ const starting = this.startWorkerWithRetry(ghost, entryRel, key);+ this.startingWorkers.set(key, starting);+ try {+ return await starting;+ } finally {+ this.startingWorkers.delete(key);+ }+ }+ private async startWorkerWithRetry(+ ghost: InstalledGhost,+ entryRel: string,+ key: string,+ ): Promise<WorkerEntry> {+ if (this.destroyed || this.stoppedGhosts.has(ghost.manifest.id)) {+ throw new WorkerStartError('Node 工作进程启动已取消', false, true);+ }+ this.sendStatus(ghost, 'starting', undefined, entryRel);+ let current = ghost;+ let lastError = new Error('Node 工作进程启动失败');+ for (let attempt = 1; attempt <= WORKER_START_ATTEMPTS; attempt++) {+ if (attempt > 1) {+ await this.delay(WORKER_START_RETRY_DELAYS_MS[attempt - 2] ?? 750);+ // 退避期间插件可能被停用/卸载/更新/停止,主机也可能正在退出:+ // 现查现用;已停用/已收摊/已停止就不再拉进程,也不补发状态事件。+ if (this.destroyed || this.stoppedGhosts.has(ghost.manifest.id)) throw lastError;+ const fresh = this.deps.getGhost(ghost.manifest.id);+ if (!fresh?.enabled) throw lastError;+ // 跨更新边界时重验入口:新 manifest 可能已不再申报该 entry。+ if (!fresh.manifest.node) throw lastError;+ const declaredEntries = [fresh.manifest.node.entry, ...(fresh.manifest.node.entries ?? [])];+ if (!declaredEntries.includes(entryRel)) throw lastError;+ current = fresh;+ }+ try {+ return await this.startWorkerOnce(current, entryRel, key);+ } catch (error) {+ lastError = error instanceof Error ? error : new Error(String(error));+ const retryable = error instanceof WorkerStartError ? error.retryable : true;+ this.deps.log?.warn('ghost node start attempt failed', {+ ghostId: ghost.manifest.id,+ entry: entryRel,+ attempt,+ message: lastError.message,+ });+ if (!retryable) break;+ }+ }+ if (!(lastError instanceof WorkerStartError) || !lastError.silent) {+ this.sendStatus(current, 'crashed', lastError.message, entryRel);+ }+ throw lastError;+ }++ private async startWorkerOnce(+ ghost: InstalledGhost,+ entryRel: string,+ key: string,+ ): Promise<WorkerEntry> {+ const node = ghost.manifest.node;+ if (!node) throw new WorkerStartError('ghost.json 缺少 node 工作进程详单', false);const entryPath = path.resolve(ghost.dir, ...entryRel.split('/'));const root = path.resolve(ghost.dir);if (entryPath === root || !entryPath.startsWith(`${root}${path.sep}`)) {- throw new Error('node 入口越出插件安装目录');+ throw new WorkerStartError('node 入口越出插件安装目录', false);}- this.sendStatus(ghost, 'starting', undefined, entryRel);let child: NodeWorkerProcess;try {child = (this.deps.spawnProcess ?? defaultSpawnProcess)(entryPath, root, ghost.manifest.id);} catch (error) {- this.sendStatus(ghost, 'crashed', error instanceof Error ? error.message : String(error), entryRel);- throw error;+ throw new WorkerStartError(error instanceof Error ? error.message : String(error), true);}const entry: WorkerEntry = {ghost,entryRel,child,+ startupPhase: true,+ startupStderr: '',stdoutDecoder: new StringDecoder('utf8'),stdoutBuffer: '',nextId: 1,@@ -814,10 +938,18 @@ export class GhostNodeRuntimeBroker {stopping: false,};this.workers.set(key, entry);+ if (this.destroyed || this.stoppedGhosts.has(ghost.manifest.id)) {+ this.workers.delete(key);+ try { child.kill('SIGKILL'); } catch { /* already gone */ }+ throw new WorkerStartError('Node 工作进程启动已取消', false, true);+ }// 代启子进程的控制帧入口(childSpawn):帧形状严格把关,资格在 handle 里查。child.onControl?.((message) => this.handleWorkerControl(entry, message));child.stdout.on('data', (chunk) => this.handleStdout(entry, chunk));child.stderr.on('data', (chunk) => {+ if (entry.startupPhase && entry.startupStderr.length < STARTUP_STDERR_CAP) {+ entry.startupStderr = (entry.startupStderr + String(chunk)).slice(0, STARTUP_STDERR_CAP);+ }const text = String(chunk).trim().slice(0, 4_096);if (text) this.deps.log?.warn('ghost node stderr', { ghostId: ghost.manifest.id, text });// stderr 是手册钦定的日志口——构建刷日志就是活着的证据,给续命请求重置沉默窗口。@@ -837,16 +969,34 @@ export class GhostNodeRuntimeBroker {outcome();};startTimer = this.setTimer(- () => settle(() => reject(new Error('Node 工作进程启动超时'))),+ () => settle(() => reject(new WorkerStartError('Node 工作进程启动超时', false))),DEFAULT_START_TIMEOUT_MS,);startTimer.unref?.();child.once('spawn', () => settle(resolve));- child.once('error', (error) => settle(() => reject(error)));+ child.once('error', (error) =>+ settle(() => reject(new WorkerStartError(error.message, true))),+ );child.once('exit', (code, signal) => {- settle(() =>- reject(new Error(`Node 工作进程启动前退出(code=${code}, signal=${signal ?? 'none'})`)),- );+ // stderr 管道字节可能晚于 exit 事件到达:给在途 chunk 一个极短的+ // 落地窗口,诊断行(如杀软拦截的 EPERM)才截得到。+ const drainTimer = this.setTimer(() => {+ settle(() => {+ if (entry.stopping) {+ reject(new WorkerStartError('Node 工作进程启动已取消', false, true));+ } else {+ const hint = startupStderrHint(entry.startupStderr);+ reject(+ new WorkerStartError(+ `Node 工作进程启动前退出(code=${code}, signal=${signal ?? 'none'})${hint ? `:${hint}` : ''}`,+ true,+ false,+ ),+ );+ }+ });+ }, 10);+ drainTimer.unref?.();});});} catch (error) {@@ -858,6 +1008,7 @@ export class GhostNodeRuntimeBroker {}throw error;}+ entry.startupPhase = false;this.deps.log?.info('ghost node process started', {ghostId: ghost.manifest.id,entry: entryRel,@@ -869,6 +1020,13 @@ export class GhostNodeRuntimeBroker {return entry;}+ private delay(ms: number): Promise<void> {+ return new Promise((resolve) => {+ const timer = this.setTimer(resolve, ms);+ timer.unref?.();+ });+ }+private async ensureMcpInitialized(entry: WorkerEntry): Promise<void> {if (!entry.mcpInitPromise) {entry.mcpInitPromise = this.sendRpc(@@ -1098,7 +1256,9 @@ export class GhostNodeRuntimeBroker {pending.reject(new NodeRpcError('exit', `Node 工作进程已退出(${detail})`));}entry.pending.clear();- if (!entry.stopping) {+ // 启动期退出不在这里报 crashed:ensureWorker 统一收口(可能还要重试,+ // 重试成功时插件不该看到一次假 crash)。+ if (!entry.stopping && !entry.startupPhase) {this.deps.log?.warn('ghost node process exited', { ghostId, entry: entry.entryRel, detail });this.sendStatus(entry.ghost, 'crashed', detail, entry.entryRel);}