Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): add deep Node worker failure diagnostics
fmfsaisai45f288860a5f
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.tsindex 5c93f7bd4a..cddac90f4e 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts@@ -67,6 +67,40 @@ class FakeNodeProcess extends EventEmitter {}}+class DiagnosticFakeNodeProcess extends FakeNodeProcess {+ startupState: {+ messageCount: number;+ readySeen: boolean;+ adapterReady: boolean;+ } = { messageCount: 0, readySeen: false, adapterReady: false };++ readStartupState() {+ return this.startupState;+ }+}++class ThrowingDiagnosticKilledProcess extends DiagnosticFakeNodeProcess {+ constructor(+ onMessage?: (message: Record<string, unknown>) => void,+ emitSpawn = true,+ ) {+ super(onMessage, emitSpawn);+ Object.defineProperty(this, 'killed', {+ configurable: true,+ get: () => {+ throw new Error('adapter killed state unavailable');+ },+ set: () => undefined,+ });+ }+}++class ThrowingDiagnosticStateProcess extends FakeNodeProcess {+ readStartupState(): never {+ throw new Error('diagnostic state unavailable');+ }+}+class FakeUtilityProcess extends EventEmitter {stdout = new PassThrough();stderr = new PassThrough();@@ -291,6 +325,11 @@ describe('nodeRuntimeBroker · Electron utilityProcess 适配', () => {child.emit('message', { type: 'ready' });expect(spawned).toHaveBeenCalledTimes(1);expect(stages.map(({ stage }) => stage)).toEqual(['utility-process-spawned']);+ expect(worker.readStartupState?.()).toEqual({+ messageCount: 1,+ readySeen: true,+ adapterReady: true,+ });// 2026-07-23 起普通 worker 就绪后保留一条消息听筒——它只承载引导层的// 子进程控制帧(childSpawn),形状由 broker 严格把关;非控制帧仍然没有// 任何消费面(下面的 stdin 断言即证明正式通信面仍是 stdio)。@@ -644,7 +683,7 @@ describe('nodeRuntimeBroker · 进程生命周期', () => {it('native spawn 已观测但 ready 未观测时只记录两级 observed metadata', async () => {vi.useFakeTimers();const ghost = fakeGhost();- const child = new FakeNodeProcess(undefined, false);+ const child = new DiagnosticFakeNodeProcess(undefined, false);const warn = vi.fn();const broker = new GhostNodeRuntimeBroker({getGhost: () => ghost,@@ -660,12 +699,15 @@ describe('nodeRuntimeBroker · 进程生命周期', () => {stage: 'utility-process-spawned',pid: 1234,});+ child.startupState = { messageCount: 2, readySeen: false, adapterReady: false };await vi.advanceTimersByTimeAsync(10_000);await expect(pending).resolves.toEqual({ok: false,errorCode: 'PROCESS_START_FAILED',message: 'Node 工作进程启动超时',});+ child.startupState = { messageCount: 99, readySeen: true, adapterReady: true };+ child.emit('message', { type: 'ready' });expect(warn).toHaveBeenCalledWith('ghost node start attempt failed', {ghostId: 'node-ghost',entry: 'node/worker.cjs',@@ -677,6 +719,10 @@ describe('nodeRuntimeBroker · 进程生命周期', () => {pid: 1234,error: 'startup-timeout',observedTimeoutClass: 'native-observed-ready-not-observed',+ messageCount: 2,+ readySeen: false,+ adapterReady: false,+ adapterKilledAtDeadline: false,});expect(JSON.stringify(warn.mock.calls)).not.toContain('/fake/node-ghost');expect(JSON.stringify(warn.mock.calls)).not.toContain('echo');@@ -909,7 +955,7 @@ describe('nodeRuntimeBroker · 进程生命周期', () => {it('native spawn 未观测时不给出 UtilityProcess 未创建的因果结论', async () => {vi.useFakeTimers();const ghost = fakeGhost();- const child = new FakeNodeProcess(undefined, false);+ const child = new DiagnosticFakeNodeProcess(undefined, false);const warn = vi.fn();const broker = new GhostNodeRuntimeBroker({getGhost: () => ghost,@@ -917,7 +963,10 @@ describe('nodeRuntimeBroker · 进程生命周期', () => {log: { info: vi.fn(), warn },});- const pending = broker.handleRequest('node-ghost', rpcRequest());+ const pending = broker.handleRequest(+ 'node-ghost',+ rpcRequest('timeout', { forbiddenUserContent: 'timeout-request-sentinel' }),+ );await vi.advanceTimersByTimeAsync(10_000);await expect(pending).resolves.toEqual({ok: false,@@ -930,8 +979,32 @@ describe('nodeRuntimeBroker · 进程生命周期', () => {error: 'startup-timeout',observedTimeoutClass: 'native-not-observed',observedStagesAtDeadline: [],+ messageCount: 0,+ readySeen: false,+ adapterReady: false,+ adapterKilledAtDeadline: false,}),);+ const warningMeta = warn.mock.calls[0]?.[1] as Record<string, unknown>;+ expect(Object.keys(warningMeta).sort()).toEqual(+ [+ 'adapterReady',+ 'appRunId',+ 'attempt',+ 'attemptId',+ 'entry',+ 'error',+ 'ghostId',+ 'messageCount',+ 'observedStagesAtDeadline',+ 'observedTimeoutClass',+ 'outcome',+ 'pid',+ 'adapterKilledAtDeadline',+ 'readySeen',+ ].sort(),+ );+ expect(JSON.stringify(warn.mock.calls)).not.toContain('timeout-request-sentinel');const attemptWarnings = warn.mock.calls.filter(([message]) => message === 'ghost node start attempt failed',);@@ -964,6 +1037,69 @@ describe('nodeRuntimeBroker · 进程生命周期', () => {expect(child.killed).toBe(true);});+ it('启动事实 getter 抛错时只降级未知,不影响超时收口', async () => {+ vi.useFakeTimers();+ const ghost = fakeGhost();+ const child = new ThrowingDiagnosticStateProcess(undefined, false);+ const warn = vi.fn();+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => ghost,+ spawnProcess: () => child as unknown as NodeWorkerProcess,+ appRunId: TEST_APP_RUN_ID,+ createAttemptId: () => TEST_ATTEMPT_ID,+ log: { info: vi.fn(), warn },+ });++ const pending = broker.handleRequest('node-ghost', rpcRequest());+ await vi.advanceTimersByTimeAsync(10_000);+ await expect(pending).resolves.toEqual({+ ok: false,+ errorCode: 'PROCESS_START_FAILED',+ message: 'Node 工作进程启动超时',+ });+ expect(warn).toHaveBeenCalledWith(+ 'ghost node start attempt failed',+ expect.objectContaining({+ messageCount: 'unknown',+ readySeen: 'unknown',+ adapterReady: 'unknown',+ adapterKilledAtDeadline: false,+ }),+ );+ expect(child.killed).toBe(true);+ });++ it('adapter killed getter 抛错时只记录 unknown,不影响超时收口', async () => {+ vi.useFakeTimers();+ const ghost = fakeGhost();+ const child = new ThrowingDiagnosticKilledProcess(undefined, false);+ const warn = vi.fn();+ const broker = new GhostNodeRuntimeBroker({+ getGhost: () => ghost,+ spawnProcess: () => child as unknown as NodeWorkerProcess,+ appRunId: TEST_APP_RUN_ID,+ createAttemptId: () => TEST_ATTEMPT_ID,+ log: { info: vi.fn(), warn },+ });++ const pending = broker.handleRequest('node-ghost', rpcRequest());+ await vi.advanceTimersByTimeAsync(10_000);+ await expect(pending).resolves.toEqual({+ ok: false,+ errorCode: 'PROCESS_START_FAILED',+ message: 'Node 工作进程启动超时',+ });+ expect(warn).toHaveBeenCalledWith(+ 'ghost node start attempt failed',+ expect.objectContaining({+ messageCount: 0,+ readySeen: false,+ adapterReady: false,+ adapterKilledAtDeadline: 'unknown',+ }),+ );+ });+it('每次 attempt 只读一次粗粒度上下文,getter 异常安全降级', async () => {const ghost = fakeGhost();const child = makeAutoReplyProcess();@@ -1140,6 +1276,13 @@ describe('nodeRuntimeBroker · 启动瞬时失败重试(2026-07-24)', () => {outcome: 'failed',}),);+ const failedMeta = warn.mock.calls.find(+ ([message]) => message === 'ghost node start attempt failed',+ )?.[1] as Record<string, unknown> | undefined;+ expect(failedMeta).not.toHaveProperty('messageCount');+ expect(failedMeta).not.toHaveProperty('readySeen');+ expect(failedMeta).not.toHaveProperty('adapterReady');+ expect(failedMeta).not.toHaveProperty('adapterKilledAtDeadline');const failedAttemptWarnings = warn.mock.calls.filter(([message]) => message === 'ghost node start attempt failed',);diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.tsindex 14a6ae0fcb..e6783b0ce6 100644--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts@@ -103,6 +103,8 @@ export interface NodeWorkerProcess {* 观测的 utility-process-spawned。*/onStartupObservation?(listener: (observation: NodeWorkerStartupObservation) => void): void;+ /** Diagnostic-only adapter facts; absent on test/custom process implementations. */+ readStartupState?(): NodeWorkerStartupState;/** 订阅 worker 引导层就绪后经 parentPort 上行的控制帧(代启子进程用;可选)。 */onControl?(listener: (message: unknown) => void): void;/** 给 worker 引导层下行一条控制帧(代启结果/子进程输出等;可选)。 */@@ -116,6 +118,13 @@ export interface NodeWorkerStartupObservation {pid?: number;}+/** Main-only facts sampled at a failed startup deadline; never gate readiness. */+export interface NodeWorkerStartupState {+ messageCount: number;+ readySeen: boolean;+ adapterReady: boolean;+}+type NodeWorkerObservedTimeoutClass = 'native-not-observed' | 'native-observed-ready-not-observed';export type NodeRuntimeObservedMainWindowState =@@ -196,6 +205,26 @@ function readDiagnosticPid(child: NodeWorkerProcess): number | undefined {}}+function readDiagnosticStartupState(+ child: NodeWorkerProcess,+): NodeWorkerStartupState | undefined {+ try {+ return child.readStartupState?.();+ } catch {+ return undefined;+ }+}++/** Best-effort state exposed by Electron's UtilityProcess adapter, not OS polling. */+/** Adapter fact only; false means the adapter has not marked it killed, not OS liveness. */+function readDiagnosticAdapterKilled(child: NodeWorkerProcess): boolean | 'unknown' {+ try {+ return typeof child.killed === 'boolean' ? child.killed : 'unknown';+ } catch {+ return 'unknown';+ }+}+interface PendingRpc {resolve(value: unknown): void;reject(error: Error): void;@@ -309,6 +338,10 @@ interface StartAttemptDiagnostic {observedMainWindowState: NodeRuntimeObservedMainWindowState;observedScreenState: NodeRuntimeObservedScreenState;observedStages: Set<NodeWorkerStartupStage>;+ messageCount?: number | 'unknown';+ readySeen?: boolean | 'unknown';+ adapterReady?: boolean | 'unknown';+ adapterKilledAtDeadline?: boolean | 'unknown';pid?: number;observedTimeoutClass?: NodeWorkerObservedTimeoutClass;observedStagesAtDeadline?: NodeWorkerStartupStage[];@@ -441,6 +474,8 @@ export function createUtilityNodeWorkerProcess(let destroyed = false;let killed = false;let ready = false;+ let messageCount = 0;+ let readySeen = false;const readNativePid = (): number | undefined => {try {const value = child.pid;@@ -471,6 +506,7 @@ export function createUtilityNodeWorkerProcess(}};const onMessage = (message: unknown) => {+ messageCount += 1;if (!ready &&message &&@@ -479,6 +515,7 @@ export function createUtilityNodeWorkerProcess((message as Record<string, unknown>).type === 'ready') {ready = true;+ readySeen = true;events.emit('spawn');// 子进程原样模式:就绪后一律不再收消息——它没有任何上行控制资格。if (isChild) child.removeListener('message', onMessage);@@ -526,6 +563,9 @@ export function createUtilityNodeWorkerProcess(},stdout,stderr,+ readStartupState(): NodeWorkerStartupState {+ return { messageCount, readySeen, adapterReady: ready };+ },onStartupObservation(listener: (observation: NodeWorkerStartupObservation) => void): void {if (nativeSpawnObservation) {try {@@ -1463,7 +1503,17 @@ export class GhostNodeRuntimeBroker {if (cancelled) {debugDiagnostic(this.deps.log, 'ghost node startup settlement', settlement);} else {- warnDiagnostic(this.deps.log, 'ghost node start attempt failed', settlement);+ warnDiagnostic(this.deps.log, 'ghost node start attempt failed', {+ ...settlement,+ ...(attemptDiagnostic.observedTimeoutClass+ ? {+ messageCount: attemptDiagnostic.messageCount,+ readySeen: attemptDiagnostic.readySeen,+ adapterReady: attemptDiagnostic.adapterReady,+ adapterKilledAtDeadline: attemptDiagnostic.adapterKilledAtDeadline,+ }+ : {}),+ });}if (!retryable) break;}@@ -1641,6 +1691,21 @@ export class GhostNodeRuntimeBroker {attemptDiagnostic.observedStagesAtDeadline = STARTUP_STAGE_ORDER.filter((stage) =>entry.startupStages.has(stage),);+ attemptDiagnostic.messageCount = 'unknown';+ attemptDiagnostic.readySeen = 'unknown';+ attemptDiagnostic.adapterReady = 'unknown';+ const state = readDiagnosticStartupState(entry.child);+ if (state) {+ attemptDiagnostic.messageCount =+ Number.isSafeInteger(state.messageCount) && state.messageCount >= 0+ ? state.messageCount+ : 'unknown';+ attemptDiagnostic.readySeen =+ typeof state.readySeen === 'boolean' ? state.readySeen : 'unknown';+ attemptDiagnostic.adapterReady =+ typeof state.adapterReady === 'boolean' ? state.adapterReady : 'unknown';+ }+ attemptDiagnostic.adapterKilledAtDeadline = readDiagnosticAdapterKilled(entry.child);reject(new WorkerStartError('Node 工作进程启动超时', false));}),DEFAULT_START_TIMEOUT_MS,diff --git a/docs/handoffs/issue-3330-root-cause.md b/docs/handoffs/issue-3330-root-cause.mdnew file mode 100644index 0000000000..3201568005--- /dev/null+++ b/docs/handoffs/issue-3330-root-cause.md@@ -0,0 +1,54 @@+# #3330 Node worker startup root-cause handoff++## Scope and current branch++- Investigation branch: `codex/issue-3330-diagnostic-deep`.+- Worktree: `E:\work\git-repos\cindy\.cindy-worktrees\issue-3330-diagnostic-deep`.+- Baseline at 2026-09-07: `origin/main` = `63e90722e0de9e7b1db732274bdd9870337177d2`.+- This worktree is diagnostic-only and must not include the independent exit-ledger branch.++## Field evidence and current inference++The 2026-09-03 production evidence for `xd-sites` showed two attempts in one app run. Each+observed `utility-process-spawned` with a distinct PID, but neither observed `parent-port-ready`+before the 10-second timeout; both were then killed. The user-visible result was+`PROCESS_START_FAILED` with `Node 工作进程启动超时`. Network requests around the failure succeeded,+so plugin network behavior is not the default explanation.++`nodeRuntimeWorkerProcess.ts` posts its `ready` parentPort message before requiring the plugin+entry. Therefore the two existing main-side stages prove native process creation and broker+observation of the ready message, but a missing ready stage does not distinguish worker bootstrap+execution from MessagePort delivery or host-side adapter settlement. No production fix is proven.++Prior isolated v0.1.72 packaged experiments with two local real ghost fixtures, idle/restart,+hidden windows, local child-process/IPC activity, and TEMP old/new process handoff all ended+`NOT REPRODUCED`; they did not cover authenticated vendor agent/provider activity, signed updater+handoff, EDR timing, or the exact user machine state.++## Current diagnostic patch++Only `nodeRuntimeBroker.ts` and its focused test are modified for the deep diagnostic patch.+The adapter keeps in-memory `messageCount`, `readySeen`, and `adapterReady` facts. At the existing+startup timeout callback, the broker samples those facts and the adapter's best-effort `killed`+state once, storing `adapterKilledAtDeadline`; all are emitted only in the existing failed-start+warn. `adapterKilledAtDeadline: false` means only that the adapter had not marked the child+killed at the deadline; it is not confirmation that the OS PID was alive. The PID remains the+existing supplemental failure field.+The deadline stage array is copied at timeout and cannot be changed by later events. Missing or+throwing custom diagnostic getters degrade to `unknown`; logger failures remain fail-open.++The returned error, timer, retry, kill, exit, stderr activity, ready ordering, and process error+semantics are unchanged. No stderr marker/filter, extra timer, drain, polling, wait, ledger,+restart, recovery, upload allowlist, logger schema, UI, request/result/path/stderr/raw-error data,+or credentials are added.++## Validation++- Focused broker + packaging tests: 80 passed.+- Desktop typecheck: passed.+- `sourceAllowlist.test.ts`: 73 passed.+- `pnpm test:unit:related`: passed (`test:runner`: 497 passed, 8 skipped; `apps/desktop` related unit passed, 110.8s).+- `git diff --check`: passed.++Remaining work is independent tester/reviewer review and any packaged smoke explicitly arranged by+the Lead. Do not call this patch a fix without an old-versus-new A/B reproduction.