Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

chore(desktop): add Node worker startup diagnostics (#3551)

fmfsaisaie13f11c49be5
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 2531074fd4..fbd003d73a 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -913,6 +913,7 @@ import {
refreshGhostLocalization,
registerGhostIpc,
runStableOwnerPostCommitTask,
+ setGhostNodeRuntimeStartAttemptContextReader,
setGhostsChangedObserver,
suspendAllGhosts,
waitForGhostMutations,
@@ -3742,6 +3743,29 @@ const createWindow = () => {
// 装饰动画闸门的兜底信号。主窗在 running turn 期间会关掉 backgroundThrottling,
// 那之后 Renderer 的 visibilityState 就不再反映真实可见性,细节见模块头注释。
+ setGhostNodeRuntimeStartAttemptContextReader(() => {
+ let observedMainWindowState:
+ 'absent' | 'hidden' | 'minimized' | 'visible-unfocused' | 'focused' | 'unknown' = 'unknown';
+ try {
+ if (mainWindow.isDestroyed()) observedMainWindowState = 'absent';
+ else if (mainWindow.isMinimized()) observedMainWindowState = 'minimized';
+ else if (!mainWindow.isVisible()) observedMainWindowState = 'hidden';
+ else if (mainWindow.isFocused()) observedMainWindowState = 'focused';
+ else observedMainWindowState = 'visible-unfocused';
+ } catch {
+ observedMainWindowState = 'unknown';
+ }
+ let observedScreenState: 'active' | 'idle' | 'locked' | 'unknown' = 'unknown';
+ try {
+ const state = powerMonitor.getSystemIdleState(60);
+ if (state === 'active' || state === 'idle' || state === 'locked') {
+ observedScreenState = state;
+ }
+ } catch {
+ observedScreenState = 'unknown';
+ }
+ return { observedMainWindowState, observedScreenState };
+ });
installWindowHiddenBroadcast(mainWindow);
// Keyboard hello when the window comes back from hide / minimize / Dock.
attachWorkLouderCodexWindowReveal(mainWindow);
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts
index a92ae310e4..5c93f7bd4a 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimeBroker.test.ts
@@ -10,16 +10,21 @@ import type { InstalledGhost } from '../../../shared/ghost';
import {
createUtilityNodeWorkerProcess,
GhostNodeRuntimeBroker,
+ type NodeWorkerStartupObservation,
type NodeWorkerProcess,
} from '../nodeRuntimeBroker';
+const TEST_APP_RUN_ID = 'a'.repeat(16);
+const TEST_ATTEMPT_ID = 'b'.repeat(16);
+
class FakeNodeProcess extends EventEmitter {
stdin = new PassThrough();
stdout = new PassThrough();
stderr = new PassThrough();
- pid = 1234;
+ pid: number | undefined = 1234;
killed = false;
received: Array<Record<string, unknown>> = [];
+ startupObservationListeners = new Set<(observation: NodeWorkerStartupObservation) => void>();
private inputBuffer = '';
constructor(
@@ -47,6 +52,14 @@ class FakeNodeProcess extends EventEmitter {
this.stdout.write(`${JSON.stringify(message)}\n`);
}
+ onStartupObservation(listener: (observation: NodeWorkerStartupObservation) => void): void {
+ this.startupObservationListeners.add(listener);
+ }
+
+ emitStartupObservation(observation: NodeWorkerStartupObservation): void {
+ this.startupObservationListeners.forEach((listener) => listener(observation));
+ }
+
kill(signal?: NodeJS.Signals): boolean {
this.killed = true;
queueMicrotask(() => this.emit('exit', null, signal ?? 'SIGTERM'));
@@ -95,9 +108,14 @@ describe('nodeRuntimeBroker owner boundary races', () => {
const ghost = fakeGhost();
const child = new FakeNodeProcess(undefined, false);
const spawnProcess = vi.fn(() => child as unknown as NodeWorkerProcess);
+ const debug = vi.fn();
+ const warn = vi.fn();
const broker = new GhostNodeRuntimeBroker({
getGhost: () => ghost,
spawnProcess,
+ appRunId: TEST_APP_RUN_ID,
+ createAttemptId: () => TEST_ATTEMPT_ID,
+ log: { debug, info: vi.fn(), warn },
ownerScope: {
capture: () => generation,
isCurrent: (scope) => scope === generation,
@@ -114,6 +132,16 @@ describe('nodeRuntimeBroker owner boundary races', () => {
await expect(pending).resolves.toMatchObject({ ok: false, errorCode: 'PERMISSION_DENIED' });
expect(child.killed).toBe(true);
expect(invalidated).toHaveBeenCalledWith('node-ghost');
+ expect(debug).toHaveBeenCalledWith(
+ 'ghost node startup settlement',
+ expect.objectContaining({
+ appRunId: TEST_APP_RUN_ID,
+ attemptId: TEST_ATTEMPT_ID,
+ outcome: 'cancelled',
+ observedStagesAtSettle: ['parent-port-ready'],
+ }),
+ );
+ expect(warn).not.toHaveBeenCalled();
});
it('owner boundary change before a response discards the response and stops the worker', async () => {
@@ -182,7 +210,7 @@ describe('nodeRuntimeBroker owner boundary races', () => {
});
});
-function makeAutoReplyProcess(methods?: string[]) {
+function makeAutoReplyProcess(methods?: string[], emitSpawn = true) {
const process = new FakeNodeProcess((message) => {
if (typeof message.method === 'string') methods?.push(message.method);
if (message.id !== undefined && typeof message.method === 'string') {
@@ -194,7 +222,7 @@ function makeAutoReplyProcess(methods?: string[]) {
}),
);
}
- });
+ }, emitSpawn);
return process;
}
@@ -250,10 +278,19 @@ describe('nodeRuntimeBroker · Electron utilityProcess 适配', () => {
expect(forkOptions.env.GH_CONFIG_DIR).toBe('D:\\gh-config');
expect(forkOptions.env.XDG_CONFIG_HOME).toBe('D:\\xdg-config');
+ expect(worker.stderr).toBe(child.stderr);
+ expect(child.stderr.listenerCount('error')).toBe(0);
+ const stages: NodeWorkerStartupObservation[] = [];
+ worker.onStartupObservation?.(() => {
+ throw new Error('diagnostic listener failed');
+ });
+ worker.onStartupObservation?.((stage) => stages.push(stage));
+
const spawned = vi.fn();
worker.once('spawn', spawned);
child.emit('message', { type: 'ready' });
expect(spawned).toHaveBeenCalledTimes(1);
+ expect(stages.map(({ stage }) => stage)).toEqual(['utility-process-spawned']);
// 2026-07-23 起普通 worker 就绪后保留一条消息听筒——它只承载引导层的
// 子进程控制帧(childSpawn),形状由 broker 严格把关;非控制帧仍然没有
// 任何消费面(下面的 stdin 断言即证明正式通信面仍是 stdio)。
@@ -264,9 +301,53 @@ describe('nodeRuntimeBroker · Electron utilityProcess 适配', () => {
type: 'stdin',
chunk: '{"jsonrpc":"2.0"}\n',
});
+ const processError = vi.fn();
+ worker.on('error', processError);
+ child.emit('error', 'crashed', 'service');
+ expect(processError).toHaveBeenCalledOnce();
+ expect(processError.mock.calls[0][0]).toEqual(
+ new Error('Node utilityProcess crashed at service'),
+ );
expect(worker.kill('SIGTERM')).toBe(true);
expect(child.kill).toHaveBeenCalledTimes(1);
});
+
+ it('native observation 只在正整数 PID 回放或真实 spawn 时发布一次', () => {
+ const child = new FakeUtilityProcess();
+ child.pid = undefined;
+ const worker = createUtilityNodeWorkerProcess(
+ '/plugins/demo/node/worker.cjs',
+ '/plugins/demo',
+ 'demo',
+ vi.fn(() => child) as never,
+ );
+ const stages: NodeWorkerStartupObservation[] = [];
+ worker.onStartupObservation?.((stage) => stages.push(stage));
+
+ expect(stages).toEqual([]);
+ child.emit('spawn');
+ child.pid = 4321;
+ child.emit('spawn');
+ child.emit('message', { type: 'ready' });
+ expect(stages).toEqual([{ stage: 'utility-process-spawned' }]);
+ });
+
+ it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])(
+ '非法初始 PID %s 不会伪造 native spawn observation',
+ (pid) => {
+ const child = new FakeUtilityProcess();
+ child.pid = pid;
+ const worker = createUtilityNodeWorkerProcess(
+ '/plugins/demo/node/worker.cjs',
+ '/plugins/demo',
+ 'demo',
+ vi.fn(() => child) as never,
+ );
+ const stages: NodeWorkerStartupObservation[] = [];
+ worker.onStartupObservation?.((stage) => stages.push(stage));
+ expect(stages).toEqual([]);
+ },
+ );
});
describe('nodeRuntimeBroker · 进程生命周期', () => {
@@ -446,25 +527,556 @@ describe('nodeRuntimeBroker · 进程生命周期', () => {
broker.destroyAll();
});
- it('工作进程一直不就绪时 10 秒后失败并强制关闭', async () => {
+ it('两级启动观测按 main 接收顺序记录,elapsedMs 是 main observation latency', async () => {
+ const ghost = fakeGhost();
+ const child = makeAutoReplyProcess(undefined, false);
+ let readyTimerCleared = false;
+ const debug = vi.fn((message: string, meta?: Record<string, unknown>) => {
+ if (message === 'ghost node startup stage' && meta?.stage === 'parent-port-ready') {
+ // 同步慢 logger 开始前,settle(resolve) 已经清掉 10s timer。
+ expect(readyTimerCleared).toBe(true);
+ for (let index = 0; index < 10_000; index += 1) Math.sqrt(index);
+ }
+ });
+ const info = vi.fn();
+ let observedAt = 1_000;
+ const broker = new GhostNodeRuntimeBroker({
+ getGhost: () => ghost,
+ spawnProcess: () => child as unknown as NodeWorkerProcess,
+ appRunId: TEST_APP_RUN_ID,
+ createAttemptId: () => TEST_ATTEMPT_ID,
+ getStartAttemptContext: () => ({
+ observedMainWindowState: 'focused',
+ observedScreenState: 'active',
+ }),
+ log: { debug, info, warn: vi.fn() },
+ diagnosticNow: () => observedAt,
+ clearTimer: (timer) => {
+ readyTimerCleared = true;
+ clearTimeout(timer);
+ },
+ });
+
+ const pending = broker.handleRequest(
+ 'node-ghost',
+ rpcRequest('stage-order', { forbiddenUserContent: 'sentinel-request-params' }),
+ );
+ await Promise.resolve();
+ observedAt = 1_007;
+ child.emitStartupObservation({
+ stage: 'utility-process-spawned',
+ pid: 1234,
+ });
+ observedAt = 1_013;
+ child.emit('spawn');
+ await expect(pending).resolves.toMatchObject({
+ ok: true,
+ result: { method: 'stage-order' },
+ });
+
+ const stages = debug.mock.calls
+ .filter(([message]) => message === 'ghost node startup stage')
+ .map(([, meta]) => meta as Record<string, unknown>);
+ expect(stages.map(({ stage }) => stage)).toEqual([
+ 'utility-process-spawned',
+ 'parent-port-ready',
+ ]);
+ expect(stages.map(({ elapsedMs }) => elapsedMs)).toEqual([7, 13]);
+ for (const meta of stages) {
+ expect(Object.keys(meta).sort()).toEqual(
+ ['appRunId', 'attemptId', 'elapsedMs', 'entry', 'ghostId', 'pid', 'stage'].sort(),
+ );
+ expect(meta).toMatchObject({
+ ghostId: 'node-ghost',
+ entry: 'node/worker.cjs',
+ appRunId: TEST_APP_RUN_ID,
+ attemptId: TEST_ATTEMPT_ID,
+ pid: 1234,
+ });
+ }
+ expect(JSON.stringify(stages)).not.toContain('/fake/node-ghost');
+ expect(JSON.stringify(stages)).not.toContain('stage-order');
+ expect(JSON.stringify(debug.mock.calls)).not.toContain('sentinel-request-params');
+ expect(debug).toHaveBeenCalledWith('ghost node startup settlement', {
+ ghostId: 'node-ghost',
+ entry: 'node/worker.cjs',
+ attempt: 1,
+ appRunId: TEST_APP_RUN_ID,
+ attemptId: TEST_ATTEMPT_ID,
+ outcome: 'ready',
+ observedStagesAtSettle: ['utility-process-spawned', 'parent-port-ready'],
+ pid: 1234,
+ });
+ expect(info).not.toHaveBeenCalled();
+ broker.destroyAll();
+ });
+
+ it('乱序或迟到的纯观测不会改写既有 ready settlement', async () => {
+ const ghost = fakeGhost();
+ const child = makeAutoReplyProcess(undefined, false);
+ const debug = vi.fn();
+ const broker = new GhostNodeRuntimeBroker({
+ getGhost: () => ghost,
+ spawnProcess: () => child as unknown as NodeWorkerProcess,
+ appRunId: TEST_APP_RUN_ID,
+ createAttemptId: () => TEST_ATTEMPT_ID,
+ log: { debug, info: vi.fn(), warn: vi.fn() },
+ });
+
+ const pending = broker.handleRequest('node-ghost', rpcRequest('out-of-order'));
+ await Promise.resolve();
+ child.emitStartupObservation({ stage: 'parent-port-ready', pid: 1234 });
+ child.emit('spawn');
+ await expect(pending).resolves.toMatchObject({ ok: true });
+ child.emitStartupObservation({ stage: 'utility-process-spawned', pid: 1234 });
+
+ const settlements = debug.mock.calls.filter(
+ ([message]) => message === 'ghost node startup settlement',
+ );
+ expect(settlements).toHaveLength(1);
+ expect(settlements[0][1]).toMatchObject({
+ outcome: 'ready',
+ observedStagesAtSettle: ['parent-port-ready'],
+ });
+ broker.destroyAll();
+ });
+
+ it('native spawn 已观测但 ready 未观测时只记录两级 observed metadata', async () => {
vi.useFakeTimers();
const ghost = fakeGhost();
const child = new FakeNodeProcess(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 Promise.resolve();
+ child.emitStartupObservation({
+ stage: 'utility-process-spawned',
+ pid: 1234,
+ });
await vi.advanceTimersByTimeAsync(10_000);
- await expect(pending).resolves.toMatchObject({
+ await expect(pending).resolves.toEqual({
ok: false,
errorCode: 'PROCESS_START_FAILED',
- message: expect.stringContaining('启动超时'),
+ message: 'Node 工作进程启动超时',
});
+ expect(warn).toHaveBeenCalledWith('ghost node start attempt failed', {
+ ghostId: 'node-ghost',
+ entry: 'node/worker.cjs',
+ attempt: 1,
+ appRunId: TEST_APP_RUN_ID,
+ attemptId: TEST_ATTEMPT_ID,
+ outcome: 'failed',
+ observedStagesAtDeadline: ['utility-process-spawned'],
+ pid: 1234,
+ error: 'startup-timeout',
+ observedTimeoutClass: 'native-observed-ready-not-observed',
+ });
+ expect(JSON.stringify(warn.mock.calls)).not.toContain('/fake/node-ghost');
+ expect(JSON.stringify(warn.mock.calls)).not.toContain('echo');
expect(child.killed).toBe(true);
expect(broker.stateOf('node-ghost')).toBe('off');
});
+
+ it('空闲回收只在 debug 记录既有 signal/exit 顺序和固定字段', async () => {
+ vi.useFakeTimers();
+ const ghost = fakeGhost();
+ const child = makeAutoReplyProcess();
+ const originalKill = child.kill.bind(child);
+ vi.spyOn(child, 'kill').mockImplementation((signal) => {
+ child.pid = undefined;
+ return originalKill(signal);
+ });
+ const setTimeoutSpy = vi.spyOn(globalThis, 'setTimeout');
+ const statuses: Array<Record<string, unknown>> = [];
+ const debug = vi.fn((message: string, meta?: Record<string, unknown>) => {
+ if (message !== 'ghost node process lifecycle') return;
+ if (meta?.stage === 'sigterm-requested') {
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ expect(setTimeoutSpy.mock.calls.some(([, delay]) => delay === 2_000)).toBe(true);
+ expect(statuses.some(({ state }) => state === 'stopped')).toBe(true);
+ for (let index = 0; index < 10_000; index += 1) Math.sqrt(index);
+ }
+ if (meta?.stage === 'idle-stop') {
+ expect(child.kill).toHaveBeenCalledWith('SIGTERM');
+ }
+ });
+ const info = vi.fn();
+ 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,
+ sendToGhost: (_ghostId, payload) => statuses.push(payload as Record<string, unknown>),
+ log: { debug, info, warn },
+ });
+
+ const pending = broker.handleRequest('node-ghost', rpcRequest());
+ await vi.runAllTicks();
+ await expect(pending).resolves.toMatchObject({ ok: true });
+ await vi.advanceTimersByTimeAsync(120_000);
+ await vi.runAllTicks();
+
+ const lifecycle = debug.mock.calls
+ .filter(([message]) => message === 'ghost node process lifecycle')
+ .map(([, meta]) => meta as Record<string, unknown>);
+ expect(lifecycle.map(({ stage }) => stage)).toEqual(['sigterm-requested', 'idle-stop', 'exit']);
+ expect(lifecycle[0]).toEqual({
+ ghostId: 'node-ghost',
+ entry: 'node/worker.cjs',
+ appRunId: TEST_APP_RUN_ID,
+ attemptId: TEST_ATTEMPT_ID,
+ pid: 1234,
+ stage: 'sigterm-requested',
+ killReturned: true,
+ });
+ expect(lifecycle[1]).toEqual({
+ ghostId: 'node-ghost',
+ entry: 'node/worker.cjs',
+ appRunId: TEST_APP_RUN_ID,
+ attemptId: TEST_ATTEMPT_ID,
+ pid: 1234,
+ stage: 'idle-stop',
+ });
+ expect(lifecycle[2]).toEqual({
+ ghostId: 'node-ghost',
+ entry: 'node/worker.cjs',
+ appRunId: TEST_APP_RUN_ID,
+ attemptId: TEST_ATTEMPT_ID,
+ pid: 1234,
+ stage: 'exit',
+ code: null,
+ signal: 'SIGTERM',
+ stoppingElapsedMs: 0,
+ });
+ expect(info).not.toHaveBeenCalled();
+ expect(warn).not.toHaveBeenCalled();
+ });
+
+ it('既有强杀定时器触发时只追加 SIGKILL 返回值诊断', async () => {
+ vi.useFakeTimers();
+ const ghost = fakeGhost();
+ const child = makeAutoReplyProcess();
+ const kill = vi.spyOn(child, 'kill').mockReturnValue(true);
+ const debug = vi.fn((message: string, meta?: Record<string, unknown>) => {
+ if (message === 'ghost node process lifecycle' && meta?.stage === 'sigkill-requested') {
+ expect(kill).toHaveBeenNthCalledWith(2, 'SIGKILL');
+ }
+ });
+ const broker = new GhostNodeRuntimeBroker({
+ getGhost: () => ghost,
+ spawnProcess: () => child as unknown as NodeWorkerProcess,
+ appRunId: TEST_APP_RUN_ID,
+ createAttemptId: () => TEST_ATTEMPT_ID,
+ log: { debug, info: vi.fn(), warn: vi.fn() },
+ });
+ const pending = broker.handleRequest('node-ghost', rpcRequest());
+ await vi.runAllTicks();
+ await expect(pending).resolves.toMatchObject({ ok: true });
+
+ broker.stop('node-ghost');
+ await vi.advanceTimersByTimeAsync(2_500);
+
+ expect(kill).toHaveBeenNthCalledWith(1, 'SIGTERM');
+ expect(kill).toHaveBeenNthCalledWith(2, 'SIGKILL');
+ expect(debug).toHaveBeenCalledWith('ghost node process lifecycle', {
+ ghostId: 'node-ghost',
+ entry: 'node/worker.cjs',
+ appRunId: TEST_APP_RUN_ID,
+ attemptId: TEST_ATTEMPT_ID,
+ pid: 1234,
+ stage: 'sigkill-requested',
+ killReturned: true,
+ });
+ });
+
+ it('真实 exit debug 只在 worker 状态与 pending 退出收口之后运行', async () => {
+ vi.useFakeTimers();
+ const ghost = fakeGhost();
+ const child = new FakeNodeProcess();
+ const statuses: Array<Record<string, unknown>> = [];
+ let broker!: GhostNodeRuntimeBroker;
+ const debug = vi.fn((message: string, meta?: Record<string, unknown>) => {
+ if (message === 'ghost node process lifecycle' && meta?.stage === 'exit') {
+ expect(broker.stateOf('node-ghost')).toBe('off');
+ expect(statuses.some(({ state }) => state === 'crashed')).toBe(true);
+ }
+ });
+ broker = new GhostNodeRuntimeBroker({
+ getGhost: () => ghost,
+ spawnProcess: () => child as unknown as NodeWorkerProcess,
+ appRunId: TEST_APP_RUN_ID,
+ createAttemptId: () => TEST_ATTEMPT_ID,
+ sendToGhost: (_ghostId, payload) => statuses.push(payload as Record<string, unknown>),
+ log: { debug, info: vi.fn(), warn: vi.fn() },
+ });
+
+ const pending = broker.handleRequest('node-ghost', rpcRequest('will-exit'));
+ await vi.waitFor(() => expect(child.received).toHaveLength(1));
+ child.emit('exit', 1, null);
+ child.stderr.end();
+ await vi.runAllTicks();
+
+ await expect(pending).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'PROCESS_EXITED',
+ });
+ expect(debug).toHaveBeenCalledWith(
+ 'ghost node process lifecycle',
+ expect.objectContaining({ stage: 'exit', code: 1, signal: null }),
+ );
+ });
+
+ it('进程 error 后只在真实 exit 到达并完成既有清理后记录 exit', async () => {
+ vi.useFakeTimers();
+ const ghost = fakeGhost({ lifecycle: 'resident' });
+ const child = new FakeNodeProcess();
+ const kill = vi.spyOn(child, 'kill').mockImplementation(() => {
+ child.killed = true;
+ return true;
+ });
+ const statuses: Array<Record<string, unknown>> = [];
+ let requestSettled = false;
+ let broker!: GhostNodeRuntimeBroker;
+ const debug = vi.fn((message: string, meta?: Record<string, unknown>) => {
+ if (message === 'ghost node process lifecycle' && meta?.stage === 'exit') {
+ expect(requestSettled).toBe(true);
+ expect(broker.stateOf('node-ghost')).toBe('off');
+ expect(statuses.some(({ state }) => state === 'crashed')).toBe(true);
+ expect(vi.getTimerCount()).toBe(0);
+ }
+ });
+ broker = new GhostNodeRuntimeBroker({
+ getGhost: () => ghost,
+ spawnProcess: () => child as unknown as NodeWorkerProcess,
+ appRunId: TEST_APP_RUN_ID,
+ createAttemptId: () => TEST_ATTEMPT_ID,
+ sendToGhost: (_ghostId, payload) => statuses.push(payload as Record<string, unknown>),
+ log: { debug, info: vi.fn(), warn: vi.fn() },
+ });
+
+ const pending = broker.handleRequest('node-ghost', rpcRequest('error-then-exit'));
+ await vi.waitFor(() => expect(child.received).toHaveLength(1));
+
+ child.emit('error', new Error('utility process channel broke'));
+ expect(kill).toHaveBeenCalledWith('SIGTERM');
+ expect(
+ debug.mock.calls.filter(
+ ([message, meta]) => message === 'ghost node process lifecycle' && meta?.stage === 'exit',
+ ),
+ ).toHaveLength(0);
+
+ child.stderr.end();
+ await expect(pending).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'PROCESS_EXITED',
+ });
+ requestSettled = true;
+ expect(broker.stateOf('node-ghost')).toBe('off');
+ expect(statuses.some(({ state }) => state === 'crashed')).toBe(true);
+ expect(vi.getTimerCount()).toBe(1);
+
+ child.emit('exit', 7, 'SIGTERM');
+
+ const exitLogs = debug.mock.calls.filter(
+ ([message, meta]) => message === 'ghost node process lifecycle' && meta?.stage === 'exit',
+ );
+ expect(exitLogs).toEqual([
+ [
+ 'ghost node process lifecycle',
+ {
+ ghostId: 'node-ghost',
+ entry: 'node/worker.cjs',
+ appRunId: TEST_APP_RUN_ID,
+ attemptId: TEST_ATTEMPT_ID,
+ pid: 1234,
+ stage: 'exit',
+ code: 7,
+ signal: 'SIGTERM',
+ },
+ ],
+ ]);
+ expect(exitLogs[0]?.[1]).not.toHaveProperty('stoppingElapsedMs');
+ });
+
+ it('native spawn 未观测时不给出 UtilityProcess 未创建的因果结论', async () => {
+ vi.useFakeTimers();
+ const ghost = fakeGhost();
+ const child = new FakeNodeProcess(undefined, false);
+ const warn = vi.fn();
+ const broker = new GhostNodeRuntimeBroker({
+ getGhost: () => ghost,
+ spawnProcess: () => child as unknown as NodeWorkerProcess,
+ 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({
+ error: 'startup-timeout',
+ observedTimeoutClass: 'native-not-observed',
+ observedStagesAtDeadline: [],
+ }),
+ );
+ const attemptWarnings = warn.mock.calls.filter(
+ ([message]) => message === 'ghost node start attempt failed',
+ );
+ expect(JSON.stringify(attemptWarnings)).not.toMatch(/EPERM|nodeRuntimeWorkerProcess|C:\\app/);
+ expect(child.killed).toBe(true);
+ });
+
+ it('启动失败 settlement warn 抛错仍返回 HEAD 固定错误并走原 kill 路径', async () => {
+ vi.useFakeTimers();
+ const ghost = fakeGhost();
+ const child = new FakeNodeProcess(undefined, false);
+ const broker = new GhostNodeRuntimeBroker({
+ getGhost: () => ghost,
+ spawnProcess: () => child as unknown as NodeWorkerProcess,
+ log: {
+ info: vi.fn(),
+ warn: () => {
+ throw new Error('diagnostic warn failed');
+ },
+ },
+ });
+
+ 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(child.killed).toBe(true);
+ });
+
+ it('每次 attempt 只读一次粗粒度上下文,getter 异常安全降级', async () => {
+ const ghost = fakeGhost();
+ const child = makeAutoReplyProcess();
+ const debug = vi.fn();
+ const getStartAttemptContext = vi.fn(() => ({
+ observedMainWindowState: 'focused' as const,
+ observedScreenState: 'locked' as const,
+ }));
+ const broker = new GhostNodeRuntimeBroker({
+ getGhost: () => ghost,
+ spawnProcess: () => child as unknown as NodeWorkerProcess,
+ appRunId: TEST_APP_RUN_ID,
+ createAttemptId: () => TEST_ATTEMPT_ID,
+ getStartAttemptContext,
+ log: { debug, info: vi.fn(), warn: vi.fn() },
+ });
+
+ await expect(broker.handleRequest('node-ghost', rpcRequest())).resolves.toMatchObject({
+ ok: true,
+ });
+ const attemptContext = debug.mock.calls.find(
+ ([message]) => message === 'ghost node startup attempt',
+ )?.[1] as Record<string, unknown>;
+ expect(getStartAttemptContext).toHaveBeenCalledOnce();
+ expect(attemptContext).toEqual({
+ ghostId: 'node-ghost',
+ entry: 'node/worker.cjs',
+ attempt: 1,
+ appRunId: TEST_APP_RUN_ID,
+ attemptId: TEST_ATTEMPT_ID,
+ stage: 'begin',
+ observedMainWindowState: 'focused',
+ observedScreenState: 'locked',
+ });
+ broker.destroyAll();
+
+ const fallbackChild = makeAutoReplyProcess();
+ const fallbackDebug = vi.fn();
+ const fallbackBroker = new GhostNodeRuntimeBroker({
+ getGhost: () => ghost,
+ spawnProcess: () => fallbackChild as unknown as NodeWorkerProcess,
+ appRunId: TEST_APP_RUN_ID,
+ createAttemptId: () => TEST_ATTEMPT_ID,
+ getStartAttemptContext: () => {
+ throw new Error('diagnostic getter failed');
+ },
+ log: { debug: fallbackDebug, info: vi.fn(), warn: vi.fn() },
+ });
+ await expect(fallbackBroker.handleRequest('node-ghost', rpcRequest())).resolves.toMatchObject({
+ ok: true,
+ });
+ expect(fallbackDebug).toHaveBeenCalledWith(
+ 'ghost node startup attempt',
+ expect.objectContaining({
+ observedMainWindowState: 'unknown',
+ observedScreenState: 'unknown',
+ }),
+ );
+ fallbackBroker.destroyAll();
+ });
+
+ it('新增 diagnostic logger 抛错时不影响 ready 与请求成功', async () => {
+ const ghost = fakeGhost();
+ const child = makeAutoReplyProcess();
+ child.onStartupObservation = () => {
+ throw new Error('diagnostic subscription failed');
+ };
+ const broker = new GhostNodeRuntimeBroker({
+ getGhost: () => ghost,
+ spawnProcess: () => child as unknown as NodeWorkerProcess,
+ appRunId: TEST_APP_RUN_ID,
+ createAttemptId: () => TEST_ATTEMPT_ID,
+ log: {
+ debug: () => {
+ throw new Error('diagnostic logger failed');
+ },
+ info: vi.fn(),
+ warn: vi.fn(),
+ },
+ });
+
+ await expect(
+ broker.handleRequest('node-ghost', rpcRequest('logger-fail-open')),
+ ).resolves.toMatchObject({ ok: true });
+ broker.destroyAll();
+ });
+
+ it('main 注入的 appRunId 跨 broker 稳定且 attemptId 每次唯一', async () => {
+ const ghost = fakeGhost();
+ const starts: Array<Record<string, unknown>> = [];
+ for (let index = 0; index < 2; index += 1) {
+ const debug = vi.fn((message: string, meta?: Record<string, unknown>) => {
+ if (message === 'ghost node startup attempt' && meta) starts.push(meta);
+ });
+ const broker = new GhostNodeRuntimeBroker({
+ getGhost: () => ghost,
+ spawnProcess: () => makeAutoReplyProcess() as unknown as NodeWorkerProcess,
+ appRunId: TEST_APP_RUN_ID,
+ log: { debug, info: vi.fn(), warn: vi.fn() },
+ });
+ await expect(broker.handleRequest('node-ghost', rpcRequest())).resolves.toMatchObject({
+ ok: true,
+ });
+ broker.destroyAll();
+ }
+
+ expect(starts).toHaveLength(2);
+ expect(starts[0].appRunId).toBe(starts[1].appRunId);
+ expect(starts[0].appRunId).toBe(TEST_APP_RUN_ID);
+ expect(starts[0].attemptId).toMatch(/^[0-9a-f]{16,64}$/);
+ expect(starts[1].attemptId).toMatch(/^[0-9a-f]{16,64}$/);
+ expect(starts[0].attemptId).not.toBe(starts[1].attemptId);
+ });
});
describe('nodeRuntimeBroker · 启动瞬时失败重试(2026-07-24)', () => {
@@ -485,9 +1097,20 @@ describe('nodeRuntimeBroker · 启动瞬时失败重试(2026-07-24)', () => {
const ghost = fakeGhost();
const pushes: Array<Record<string, unknown>> = [];
let spawnCount = 0;
+ const attemptIds = ['1'.repeat(16), '2'.repeat(16)];
+ const getStartAttemptContext = vi.fn(() => ({
+ observedMainWindowState: 'hidden' as const,
+ observedScreenState: 'idle' as const,
+ }));
+ const debug = vi.fn();
+ const warn = vi.fn();
const broker = new GhostNodeRuntimeBroker({
getGhost: () => ghost,
sendToGhost: (_id, payload) => pushes.push(payload as unknown as Record<string, unknown>),
+ appRunId: TEST_APP_RUN_ID,
+ createAttemptId: () => attemptIds.shift()!,
+ getStartAttemptContext,
+ log: { debug, info: vi.fn(), warn },
spawnProcess: () => {
spawnCount += 1;
const child = spawnCount === 1 ? epermFailingProcess() : makeAutoReplyProcess();
@@ -501,8 +1124,36 @@ describe('nodeRuntimeBroker · 启动瞬时失败重试(2026-07-24)', () => {
await expect(first).resolves.toMatchObject({ ok: true, result: { method: 'first' } });
await expect(second).resolves.toMatchObject({ ok: true, result: { method: 'second' } });
expect(spawnCount).toBe(2);
+ expect(getStartAttemptContext).toHaveBeenCalledTimes(2);
const states = pushes.filter((p) => p.name === 'node-status').map((p) => p.state);
expect(states).toEqual(['starting', 'running']);
+ expect(
+ debug.mock.calls
+ .filter(([message]) => message === 'ghost node startup attempt')
+ .map(([, meta]) => (meta as { attemptId: string }).attemptId),
+ ).toEqual(['1'.repeat(16), '2'.repeat(16)]);
+ expect(warn).toHaveBeenCalledWith(
+ 'ghost node start attempt failed',
+ expect.objectContaining({
+ appRunId: TEST_APP_RUN_ID,
+ attemptId: '1'.repeat(16),
+ outcome: 'failed',
+ }),
+ );
+ const failedAttemptWarnings = warn.mock.calls.filter(
+ ([message]) => message === 'ghost node start attempt failed',
+ );
+ expect(JSON.stringify(failedAttemptWarnings)).not.toMatch(
+ /EPERM|nodeRuntimeWorkerProcess|C:\\app/,
+ );
+ expect(debug).toHaveBeenCalledWith(
+ 'ghost node startup settlement',
+ expect.objectContaining({
+ appRunId: TEST_APP_RUN_ID,
+ attemptId: '2'.repeat(16),
+ outcome: 'ready',
+ }),
+ );
broker.destroyAll();
});
@@ -1271,6 +1922,46 @@ describe('nodeRuntimeBroker · 长任务续命(maxTotalMs,2026-07-23)', () => {
broker.destroyAll();
});
+ it('raw stderr 的“_”在 t=800ms 同 tick 到达 broker 并保持 HEAD 续命', async () => {
+ vi.useFakeTimers();
+ const ghost = fakeGhost();
+ const utilityChild = new FakeUtilityProcess();
+ const worker = createUtilityNodeWorkerProcess(
+ '/fake/node-ghost/node/worker.cjs',
+ '/fake/node-ghost',
+ 'node-ghost',
+ vi.fn(() => utilityChild) as never,
+ );
+ const broker = new GhostNodeRuntimeBroker({
+ getGhost: () => ghost,
+ spawnProcess: () => worker,
+ });
+ const pending = broker.handleRequest('node-ghost', {
+ ...rpcRequest('build/run'),
+ timeoutMs: 1_000,
+ maxTotalMs: 10_000,
+ });
+ utilityChild.emit('message', { type: 'ready' });
+ await vi.runAllTicks();
+ expect(worker.stderr).toBe(utilityChild.stderr);
+ expect(utilityChild.stderr.listenerCount('error')).toBe(0);
+
+ await vi.advanceTimersByTimeAsync(800);
+ utilityChild.stderr.write('_');
+ await vi.advanceTimersByTimeAsync(800);
+ const stdinFrame = utilityChild.postMessage.mock.calls
+ .map(([message]) => message as { type?: string; chunk?: string })
+ .find(({ type }) => type === 'stdin');
+ const request = JSON.parse(String(stdinFrame?.chunk).trim()) as { id: string };
+ utilityChild.stdout.write(
+ `${JSON.stringify({ jsonrpc: '2.0', id: request.id, result: { built: true } })}\n`,
+ );
+ await vi.runAllTicks();
+
+ await expect(pending).resolves.toMatchObject({ ok: true, result: { built: true } });
+ broker.destroyAll();
+ });
+
it('续命后彻底沉默超过 timeoutMs 仍判死;一直有动静也过不了 maxTotalMs 天花板', async () => {
vi.useFakeTimers();
const ghost = fakeGhost();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts
index b07b40eb90..8e515c0d03 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/nodeRuntimePackaging.test.ts
@@ -76,6 +76,40 @@ describe('Node runtime packaging contract', () => {
expect(broker).not.toContain("ELECTRON_RUN_AS_NODE: '1'");
});
+ it('启动上下文只做每次 attempt 粗粒度快照,不注册窗口/电源时间线', () => {
+ const bootstrap = fs.readFileSync(
+ path.join(desktopRoot, 'src/main/bootstrap-electron.ts'),
+ 'utf8',
+ );
+ const start = bootstrap.indexOf('setGhostNodeRuntimeStartAttemptContextReader(() => {');
+ const end = bootstrap.indexOf('installWindowHiddenBroadcast(mainWindow);', start);
+ expect(start).toBeGreaterThan(0);
+ expect(end).toBeGreaterThan(start);
+ const contextReader = bootstrap.slice(start, end);
+ for (const state of [
+ 'absent',
+ 'hidden',
+ 'minimized',
+ 'visible-unfocused',
+ 'focused',
+ 'unknown',
+ ]) {
+ expect(contextReader).toContain(`'${state}'`);
+ }
+ expect(contextReader).toContain('powerMonitor.getSystemIdleState(60)');
+ expect(contextReader).toContain('observedScreenState');
+ expect(contextReader).not.toMatch(
+ /\.on\(|getSystemIdleTime|systemIdleSec|msSinceVisibility|title|URL|bounds|windowHidden/,
+ );
+ });
+
+ it('appRunId 在 cindy-brain main singleton 边界生成一次并注入每代 broker', () => {
+ const brain = fs.readFileSync(path.join(desktopRoot, 'src/main/cindy-brain/index.ts'), 'utf8');
+ expect(brain).toContain('const nodeRuntimeAppRunId = (() => {');
+ expect(brain).toContain("randomUUID().replaceAll('-', '')");
+ expect(brain).toContain('appRunId: nodeRuntimeAppRunId');
+ });
+
it('代启子进程(childSpawn)仍走同一 utilityProcess 通道,worker 侧只暴露窄接口', () => {
const worker = fs.readFileSync(
path.join(desktopRoot, 'src/main/cindy-brain/nodeRuntimeWorkerProcess.ts'),
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index c439ff0dfc..1535f66179 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -7,6 +7,7 @@ import {
shell,
type WebContents,
} from 'electron';
+import { randomUUID } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { isDeepStrictEqual } from 'node:util';
@@ -237,7 +238,10 @@ import {
import { GhostAgentSlot, type GhostAgentTurnRunner } from './agentSlot.js';
import { GhostErrandSlot, type GhostErrandRunner } from './errandSlot.js';
import { readGhostErrandConfig, writeGhostErrandConfig } from './errandPrefsStore.js';
-import { GhostNodeRuntimeBroker } from './nodeRuntimeBroker.js';
+import {
+ GhostNodeRuntimeBroker,
+ type NodeRuntimeStartAttemptContext,
+} from './nodeRuntimeBroker.js';
import { GhostPickSlot } from './pickSlot.js';
import { recordGhostPickedDir } from './pickGrantsStore.js';
import { GhostPreviewSlot } from './previewSlot.js';
@@ -1677,6 +1681,21 @@ export function getInstalledGhostName(id: string): string | null {
}
let nodeRuntimeBrokerSingleton: GhostNodeRuntimeBroker | null = null;
+let nodeRuntimeStartAttemptContextReader: (() => NodeRuntimeStartAttemptContext) | null = null;
+const nodeRuntimeAppRunId = (() => {
+ try {
+ return randomUUID().replaceAll('-', '');
+ } catch {
+ return 'unknown';
+ }
+})();
+
+/** Desktop bootstrap 注入主窗/系统的粗粒度只读快照;不注册额外全局监听。 */
+export function setGhostNodeRuntimeStartAttemptContextReader(
+ reader: (() => NodeRuntimeStartAttemptContext) | null,
+): void {
+ nodeRuntimeStartAttemptContextReader = reader;
+}
/**
* `GhostNodeRuntimeBroker.destroyAll()` is a terminal host-exit operation. An
@@ -1701,6 +1720,12 @@ export function getGhostNodeRuntimeBroker(): GhostNodeRuntimeBroker {
sendToGhost: (ghostId, payload) => {
sendToGhostLogic(ghostId, payload);
},
+ getStartAttemptContext: () =>
+ nodeRuntimeStartAttemptContextReader?.() ?? {
+ observedMainWindowState: 'unknown',
+ observedScreenState: 'unknown',
+ },
+ appRunId: nodeRuntimeAppRunId,
log,
});
}
diff --git a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts
index ee734ad7ff..14a6ae0fcb 100644
--- a/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts
+++ b/apps/desktop/src/main/cindy-brain/nodeRuntimeBroker.ts
@@ -98,12 +98,36 @@ export interface NodeWorkerProcess {
once(event: 'error', listener: (error: Error) => void): this;
once(event: 'exit', listener: (code: number | null, signal: string | null) => void): this;
kill(signal?: NodeJS.Signals): boolean;
+ /**
+ * 诊断-only 的 main 侧观测;不得用于放行业务请求。晚订阅只安全回放已
+ * 观测的 utility-process-spawned。
+ */
+ onStartupObservation?(listener: (observation: NodeWorkerStartupObservation) => void): void;
/** 订阅 worker 引导层就绪后经 parentPort 上行的控制帧(代启子进程用;可选)。 */
onControl?(listener: (message: unknown) => void): void;
/** 给 worker 引导层下行一条控制帧(代启结果/子进程输出等;可选)。 */
sendControl?(message: unknown): boolean;
}
+export type NodeWorkerStartupStage = 'utility-process-spawned' | 'parent-port-ready';
+
+export interface NodeWorkerStartupObservation {
+ stage: NodeWorkerStartupStage;
+ pid?: number;
+}
+
+type NodeWorkerObservedTimeoutClass = 'native-not-observed' | 'native-observed-ready-not-observed';
+
+export type NodeRuntimeObservedMainWindowState =
+ 'absent' | 'hidden' | 'minimized' | 'visible-unfocused' | 'focused' | 'unknown';
+
+export type NodeRuntimeObservedScreenState = 'active' | 'idle' | 'locked' | 'unknown';
+
+export interface NodeRuntimeStartAttemptContext {
+ observedMainWindowState: NodeRuntimeObservedMainWindowState;
+ observedScreenState: NodeRuntimeObservedScreenState;
+}
+
export interface GhostNodeRuntimeBrokerDeps {
getGhost(id: string): InstalledGhost | null;
ownerScope?: GhostOwnerScope;
@@ -122,14 +146,56 @@ export interface GhostNodeRuntimeBrokerDeps {
) => NodeWorkerProcess;
sendToGhost?: (ghostId: string, payload: GhostPipeEventPush) => void;
now?: () => number;
+ /** 测试注入;生产诊断时钟与业务计时分离。 */
+ diagnosticNow?: () => number;
setTimer?: (callback: () => void, delayMs: number) => NodeJS.Timeout;
clearTimer?: (timer: NodeJS.Timeout) => void;
+ /** 每次启动尝试恰好读取一次的粗粒度宿主快照;异常不得影响 fork。 */
+ getStartAttemptContext?: () => NodeRuntimeStartAttemptContext;
+ /** 生产由 main 单例注入;测试可显式注入。 */
+ appRunId?: string;
+ /** 测试注入;生产每次 startWorkerOnce 生成随机 128-bit 标识。 */
+ createAttemptId?: () => string;
log?: {
+ debug?(message: string, meta?: Record<string, unknown>): void;
info(message: string, meta?: Record<string, unknown>): void;
warn(message: string, meta?: Record<string, unknown>): void;
};
}
+function debugDiagnostic(
+ log: GhostNodeRuntimeBrokerDeps['log'],
+ message: string,
+ meta: Record<string, unknown>,
+): void {
+ try {
+ log?.debug?.(message, meta);
+ } catch {
+ // 诊断输出永不影响进程生命周期。
+ }
+}
+
+function warnDiagnostic(
+ log: GhostNodeRuntimeBrokerDeps['log'],
+ message: string,
+ meta: Record<string, unknown>,
+): void {
+ try {
+ log?.warn(message, meta);
+ } catch {
+ // 诊断输出永不影响进程生命周期。
+ }
+}
+
+function readDiagnosticPid(child: NodeWorkerProcess): number | undefined {
+ try {
+ const pid = child.pid;
+ return typeof pid === 'number' && Number.isInteger(pid) && pid > 0 ? pid : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
interface PendingRpc {
resolve(value: unknown): void;
reject(error: Error): void;
@@ -168,6 +234,14 @@ interface WorkerEntry {
child: NodeWorkerProcess;
/** 就绪握手完成前为 true:此阶段的退出由 ensureWorker 统一报告(可能重试),handleExit 不发 crashed。 */
startupPhase: boolean;
+ /** 诊断-only 启动阶段;不参与 ready 放行。 */
+ startupStages: Set<NodeWorkerStartupStage>;
+ /** 诊断相关性;不参与任何生命周期判定。 */
+ appRunId: string;
+ attemptId: string;
+ diagnosticPid?: number;
+ /** 主动停止开始时间,仅供既有 exit 回调计算观测延迟。 */
+ stoppingStartedAt?: number;
/** 启动期 stderr 头部截存,失败时提取一行诊断拼进错误消息(如杀软拦截的 EPERM)。 */
startupStderr: string;
/** stderr 尾部按段带时间戳截存,退出时只取回看窗口内的段拼接诊断。 */
@@ -190,7 +264,15 @@ interface WorkerEntry {
/** 曾发给本 worker 的凭证明文(退出诊断脱敏用;settleExit 后立即清空)。 */
exposedSecretValues: Set<string>;
/** exit 后 stderr drain 用:非 null 表示进程已退出、正在等待管道排空。 */
- exitDrain: { code: number | null; signal: string | null; error: Error | null; timer: NodeJS.Timeout; exitedAt: number; gen: number } | null;
+ exitDrain: {
+ code: number | null;
+ signal: string | null;
+ error: Error | null;
+ timer: NodeJS.Timeout;
+ exitedAt: number;
+ exitObservedAt: number;
+ gen: number;
+ } | null;
}
class NodeRpcError extends Error {
@@ -213,11 +295,38 @@ class WorkerStartError extends Error {
readonly retryable: boolean,
readonly silent = false,
readonly ownerBoundary = false,
+ readonly diagnostic?: {
+ error: string;
+ },
) {
super(message);
}
}
+interface StartAttemptDiagnostic {
+ appRunId: string;
+ attemptId: string;
+ observedMainWindowState: NodeRuntimeObservedMainWindowState;
+ observedScreenState: NodeRuntimeObservedScreenState;
+ observedStages: Set<NodeWorkerStartupStage>;
+ pid?: number;
+ observedTimeoutClass?: NodeWorkerObservedTimeoutClass;
+ observedStagesAtDeadline?: NodeWorkerStartupStage[];
+}
+
+function randomDiagnosticId(): string | null {
+ try {
+ return randomUUID().replaceAll('-', '');
+ } catch {
+ return null;
+ }
+}
+
+const STARTUP_STAGE_ORDER: readonly NodeWorkerStartupStage[] = [
+ 'utility-process-spawned',
+ 'parent-port-ready',
+];
+
/**
* 从 stderr 里挑最有诊断价值的一行(优先含 error 的行),截短拼进失败消息。
* preferLast: true 时从末尾向前搜索(退出诊断,最后的 error 行更可能是死因);
@@ -325,9 +434,42 @@ export function createUtilityNodeWorkerProcess(
const events = new EventEmitter();
const controlListeners = new Set<(message: unknown) => void>();
+ const startupObservationListeners = new Set<
+ (observation: NodeWorkerStartupObservation) => void
+ >();
+ let nativeSpawnObservation: NodeWorkerStartupObservation | null = null;
let destroyed = false;
let killed = false;
let ready = false;
+ const readNativePid = (): number | undefined => {
+ try {
+ const value = child.pid;
+ return typeof value === 'number' && Number.isInteger(value) && value > 0
+ ? value
+ : undefined;
+ } catch {
+ return undefined;
+ }
+ };
+ const publishNativeSpawnObservation = (pid = readNativePid()): void => {
+ try {
+ if (nativeSpawnObservation) return;
+ const observation: NodeWorkerStartupObservation = {
+ stage: 'utility-process-spawned',
+ ...(pid !== undefined ? { pid } : {}),
+ };
+ nativeSpawnObservation = observation;
+ for (const listener of startupObservationListeners) {
+ try {
+ listener(observation);
+ } catch {
+ // 诊断 observer 不能中断原有 ready/spawn 传播。
+ }
+ }
+ } catch {
+ // 整条 native-spawn diagnostic 发布链 fail-open。
+ }
+ };
const onMessage = (message: unknown) => {
if (
!ready &&
@@ -348,6 +490,17 @@ export function createUtilityNodeWorkerProcess(
controlListeners.forEach((listener) => listener(message));
}
};
+ try {
+ child.on('spawn', () => publishNativeSpawnObservation());
+ } catch {
+ // native spawn observer 安装失败不得影响 adapter 构造。
+ }
+ try {
+ const initialPid = readNativePid();
+ if (initialPid !== undefined) publishNativeSpawnObservation(initialPid);
+ } catch {
+ // PID 只用于诊断;getter 异常不得影响 adapter 构造。
+ }
child.on('message', onMessage);
child.on('exit', (code) => {
destroyed = true;
@@ -373,6 +526,16 @@ export function createUtilityNodeWorkerProcess(
},
stdout,
stderr,
+ onStartupObservation(listener: (observation: NodeWorkerStartupObservation) => void): void {
+ if (nativeSpawnObservation) {
+ try {
+ listener(nativeSpawnObservation);
+ } catch {
+ // native spawn 可能早于 broker 订阅;安全回放仍须 fail-open。
+ }
+ }
+ startupObservationListeners.add(listener);
+ },
onControl(listener: (message: unknown) => void): void {
controlListeners.add(listener);
},
@@ -448,8 +611,74 @@ export class GhostNodeRuntimeBroker {
* 安全相对路径的字符集都不含 ":",拼接无歧义)。
*/
private readonly workers = new Map<string, WorkerEntry>();
+ private readonly appRunId: string;
+
+ constructor(private readonly deps: GhostNodeRuntimeBrokerDeps) {
+ this.appRunId = /^[0-9a-f]{16,64}$/.test(deps.appRunId ?? '') ? deps.appRunId! : 'unknown';
+ }
+
+ private createStartAttemptDiagnostic(): StartAttemptDiagnostic {
+ const mainWindowStates: readonly NodeRuntimeObservedMainWindowState[] = [
+ 'absent',
+ 'hidden',
+ 'minimized',
+ 'visible-unfocused',
+ 'focused',
+ 'unknown',
+ ];
+ const screenStates: readonly NodeRuntimeObservedScreenState[] = [
+ 'active',
+ 'idle',
+ 'locked',
+ 'unknown',
+ ];
+ let observedMainWindowState: NodeRuntimeObservedMainWindowState = 'unknown';
+ let observedScreenState: NodeRuntimeObservedScreenState = 'unknown';
+ try {
+ const observed = this.deps.getStartAttemptContext?.();
+ if (observed && mainWindowStates.includes(observed.observedMainWindowState)) {
+ observedMainWindowState = observed.observedMainWindowState;
+ }
+ if (observed && screenStates.includes(observed.observedScreenState)) {
+ observedScreenState = observed.observedScreenState;
+ }
+ } catch {
+ // 诊断快照或其只读字段失败不能影响 fork。
+ }
+ let attemptId: string | undefined;
+ try {
+ const candidate = this.deps.createAttemptId?.();
+ if (candidate && /^[0-9a-f]{16,64}$/.test(candidate)) attemptId = candidate;
+ } catch {
+ // 测试注入异常同样不得影响启动。
+ }
+ return {
+ appRunId: this.appRunId,
+ attemptId: attemptId ?? randomDiagnosticId() ?? 'unknown',
+ observedMainWindowState,
+ observedScreenState,
+ observedStages: new Set(),
+ };
+ }
- constructor(private readonly deps: GhostNodeRuntimeBrokerDeps) {}
+ private startupSettlementMeta(
+ attempt: StartAttemptDiagnostic,
+ outcome: 'ready' | 'failed' | 'cancelled',
+ ): Record<string, unknown> {
+ return {
+ appRunId: attempt.appRunId,
+ attemptId: attempt.attemptId,
+ outcome,
+ ...(attempt.observedStagesAtDeadline
+ ? { observedStagesAtDeadline: attempt.observedStagesAtDeadline }
+ : {
+ observedStagesAtSettle: STARTUP_STAGE_ORDER.filter((stage) =>
+ attempt.observedStages.has(stage),
+ ),
+ }),
+ ...(attempt.pid !== undefined ? { pid: attempt.pid } : {}),
+ };
+ }
private static keyOf(ghostId: string, entryRel: string): string {
return `${ghostId}::${entryRel}`;
@@ -1062,14 +1291,35 @@ export class GhostNodeRuntimeBroker {
}
entry.pending.clear();
entry.exposedSecretValues.clear();
+ // PID 是启动期已经捕获的只读 fact;停止关键路径前不再调用诊断 getter/logger。
+ const stopPid = entry.diagnosticPid;
+ let sigtermKillReturned = false;
try {
- entry.child.kill('SIGTERM');
+ sigtermKillReturned = entry.child.kill('SIGTERM');
entry.hardKillTimer = this.setTimer(() => {
entry.hardKillTimer = null;
try {
- entry.child.kill('SIGKILL');
+ const killReturned = entry.child.kill('SIGKILL');
+ debugDiagnostic(this.deps.log, 'ghost node process lifecycle', {
+ ghostId: entry.ghost.manifest.id,
+ entry: entry.entryRel,
+ appRunId: entry.appRunId,
+ attemptId: entry.attemptId,
+ ...(entry.diagnosticPid !== undefined ? { pid: entry.diagnosticPid } : {}),
+ stage: 'sigkill-requested',
+ killReturned,
+ });
} catch {
// already gone
+ debugDiagnostic(this.deps.log, 'ghost node process lifecycle', {
+ ghostId: entry.ghost.manifest.id,
+ entry: entry.entryRel,
+ appRunId: entry.appRunId,
+ attemptId: entry.attemptId,
+ ...(entry.diagnosticPid !== undefined ? { pid: entry.diagnosticPid } : {}),
+ stage: 'sigkill-requested',
+ killReturned: false,
+ });
}
}, PROCESS_STOP_GRACE_MS);
entry.hardKillTimer.unref?.();
@@ -1077,6 +1327,17 @@ export class GhostNodeRuntimeBroker {
// 已退出即视为停止成功。
}
this.sendStatus(entry.ghost, 'stopped', undefined, entry.entryRel);
+ // 诊断计时从 HEAD 停止动作全部完成后开始;不得推迟 signal/grace timer/status。
+ if (entry.stoppingStartedAt === undefined) entry.stoppingStartedAt = Date.now();
+ debugDiagnostic(this.deps.log, 'ghost node process lifecycle', {
+ ghostId: entry.ghost.manifest.id,
+ entry: entry.entryRel,
+ appRunId: entry.appRunId,
+ attemptId: entry.attemptId,
+ ...(stopPid !== undefined ? { pid: stopPid } : {}),
+ stage: 'sigterm-requested',
+ killReturned: sigtermKillReturned,
+ });
}
/** Cindy 退出时收掉全部随包 Node 进程。 */
@@ -1156,17 +1417,54 @@ export class GhostNodeRuntimeBroker {
if (!declaredEntries.includes(entryRel)) throw lastError;
current = fresh;
}
+ const attemptDiagnostic = this.createStartAttemptDiagnostic();
+ debugDiagnostic(this.deps.log, 'ghost node startup attempt', {
+ ghostId: ghost.manifest.id,
+ entry: entryRel,
+ attempt,
+ appRunId: attemptDiagnostic.appRunId,
+ attemptId: attemptDiagnostic.attemptId,
+ stage: 'begin',
+ observedMainWindowState: attemptDiagnostic.observedMainWindowState,
+ observedScreenState: attemptDiagnostic.observedScreenState,
+ });
try {
- return await this.startWorkerOnce(current, entryRel, key, ownerScopeSnapshot);
+ const entry = await this.startWorkerOnce(
+ current,
+ entryRel,
+ key,
+ ownerScopeSnapshot,
+ attemptDiagnostic,
+ );
+ debugDiagnostic(this.deps.log, 'ghost node startup settlement', {
+ ghostId: ghost.manifest.id,
+ entry: entryRel,
+ attempt,
+ ...this.startupSettlementMeta(attemptDiagnostic, 'ready'),
+ });
+ return entry;
} 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', {
+ const diagnostic = error instanceof WorkerStartError ? error.diagnostic : undefined;
+ const cancelled = error instanceof WorkerStartError && error.silent;
+ const settlement = {
ghostId: ghost.manifest.id,
entry: entryRel,
attempt,
- message: lastError.message,
- });
+ ...this.startupSettlementMeta(attemptDiagnostic, cancelled ? 'cancelled' : 'failed'),
+ error:
+ diagnostic?.error ??
+ (attemptDiagnostic.observedTimeoutClass ? 'startup-timeout' : 'worker-start-failed'),
+ ...(attemptDiagnostic.observedTimeoutClass
+ ? { observedTimeoutClass: attemptDiagnostic.observedTimeoutClass }
+ : {}),
+ };
+ if (cancelled) {
+ debugDiagnostic(this.deps.log, 'ghost node startup settlement', settlement);
+ } else {
+ warnDiagnostic(this.deps.log, 'ghost node start attempt failed', settlement);
+ }
if (!retryable) break;
}
}
@@ -1181,6 +1479,7 @@ export class GhostNodeRuntimeBroker {
entryRel: string,
key: string,
ownerScopeSnapshot: unknown,
+ attemptDiagnostic: StartAttemptDiagnostic,
): Promise<WorkerEntry> {
this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);
const node = ghost.manifest.node;
@@ -1190,19 +1489,32 @@ export class GhostNodeRuntimeBroker {
if (entryPath === root || !entryPath.startsWith(`${root}${path.sep}`)) {
throw new WorkerStartError('node 入口越出插件安装目录', false);
}
+ const forkStartedAt = this.diagnosticNow();
let child: NodeWorkerProcess;
try {
child = (this.deps.spawnProcess ?? defaultSpawnProcess)(entryPath, root, ghost.manifest.id);
} catch (error) {
- throw new WorkerStartError(error instanceof Error ? error.message : String(error), true);
+ throw new WorkerStartError(
+ error instanceof Error ? error.message : String(error),
+ true,
+ false,
+ false,
+ { error: 'utility-process-fork-threw' },
+ );
}
this.trackLiveProcess(ghost.manifest.id, child);
+ const readChildDiagnosticPid = (): number | undefined => readDiagnosticPid(child);
+ attemptDiagnostic.pid = readChildDiagnosticPid();
const entry: WorkerEntry = {
ghost,
ownerScopeSnapshot,
entryRel,
child,
startupPhase: true,
+ startupStages: attemptDiagnostic.observedStages,
+ appRunId: attemptDiagnostic.appRunId,
+ attemptId: attemptDiagnostic.attemptId,
+ diagnosticPid: attemptDiagnostic.pid,
startupStderr: '',
stderrSegments: [],
stderrTotalChars: 0,
@@ -1219,6 +1531,48 @@ export class GhostNodeRuntimeBroker {
exposedSecretValues: new Set(),
exitDrain: null,
};
+ const recordStartupObservation = (observation: NodeWorkerStartupObservation): void => {
+ if (
+ observation.stage !== 'utility-process-spawned' &&
+ observation.stage !== 'parent-port-ready'
+ ) {
+ return;
+ }
+ if (entry.startupStages.has(observation.stage)) return;
+ entry.startupStages.add(observation.stage);
+ const observedPid =
+ typeof observation.pid === 'number' &&
+ Number.isInteger(observation.pid) &&
+ observation.pid > 0
+ ? observation.pid
+ : readChildDiagnosticPid();
+ if (observedPid !== undefined) {
+ attemptDiagnostic.pid = observedPid;
+ entry.diagnosticPid = observedPid;
+ }
+ const observedAt = this.diagnosticNow();
+ debugDiagnostic(this.deps.log, 'ghost node startup stage', {
+ ghostId: ghost.manifest.id,
+ entry: entryRel,
+ appRunId: attemptDiagnostic.appRunId,
+ attemptId: attemptDiagnostic.attemptId,
+ ...(observedPid !== undefined ? { pid: observedPid } : {}),
+ stage: observation.stage,
+ // main 从 fork 调用开始到观测该阶段的延迟;不是 worker 源侧阶段耗时。
+ ...(forkStartedAt !== undefined && observedAt !== undefined
+ ? { elapsedMs: observedAt - forkStartedAt }
+ : {}),
+ });
+ };
+ try {
+ child.onStartupObservation?.((observation) => {
+ if (observation.stage === 'utility-process-spawned') {
+ recordStartupObservation(observation);
+ }
+ });
+ } catch {
+ // 诊断订阅失败不能改变 ready / retry 语义。
+ }
this.workers.set(key, entry);
if (this.destroyed || this.stoppedGhosts.has(ghost.manifest.id)) {
this.workers.delete(key);
@@ -1276,13 +1630,39 @@ export class GhostNodeRuntimeBroker {
outcome();
};
startTimer = this.setTimer(
- () => settle(() => reject(new WorkerStartError('Node 工作进程启动超时', false))),
+ () =>
+ settle(() => {
+ const observedTimeoutClass: NodeWorkerObservedTimeoutClass = entry.startupStages.has(
+ 'utility-process-spawned',
+ )
+ ? 'native-observed-ready-not-observed'
+ : 'native-not-observed';
+ attemptDiagnostic.observedTimeoutClass = observedTimeoutClass;
+ attemptDiagnostic.observedStagesAtDeadline = STARTUP_STAGE_ORDER.filter((stage) =>
+ entry.startupStages.has(stage),
+ );
+ reject(new WorkerStartError('Node 工作进程启动超时', false));
+ }),
DEFAULT_START_TIMEOUT_MS,
);
startTimer.unref?.();
- child.once('spawn', () => settle(resolve));
+ child.once('spawn', () => {
+ // HEAD 的 ready 结算必须先完成;PID/getter/clock/logger 都只能在其后旁路。
+ settle(resolve);
+ const pid = readChildDiagnosticPid();
+ recordStartupObservation({
+ stage: 'parent-port-ready',
+ ...(pid !== undefined ? { pid } : {}),
+ });
+ });
child.once('error', (error) =>
- settle(() => reject(new WorkerStartError(error.message, true))),
+ settle(() =>
+ reject(
+ new WorkerStartError(error.message, true, false, false, {
+ error: 'utility-process-error',
+ }),
+ ),
+ ),
);
child.once('exit', (code, signal) => {
// stderr 管道字节可能晚于 exit 事件到达:给在途 chunk 一个极短的
@@ -1298,6 +1678,8 @@ export class GhostNodeRuntimeBroker {
`Node 工作进程启动前退出(code=${code}, signal=${signal ?? 'none'})${hint ? `:${hint}` : ''}`,
true,
false,
+ false,
+ { error: 'utility-process-exited-before-ready' },
),
);
}
@@ -1313,16 +1695,12 @@ export class GhostNodeRuntimeBroker {
} catch {
// no-op
}
+ const failedPid = readChildDiagnosticPid();
+ if (failedPid !== undefined) attemptDiagnostic.pid = failedPid;
throw error;
}
entry.startupPhase = false;
this.assertOwnerScopeUsable(ghost.manifest.id, ownerScopeSnapshot);
- this.deps.log?.info('ghost node process started', {
- ghostId: ghost.manifest.id,
- entry: entryRel,
- pid: child.pid,
- protocol: node.protocol,
- });
this.sendStatus(ghost, 'running', undefined, entryRel);
this.scheduleIdleStop(entry);
return entry;
@@ -1606,6 +1984,9 @@ export class GhostNodeRuntimeBroker {
this.clearTimer(entry.hardKillTimer);
entry.hardKillTimer = null;
}
+ // stopWorker 或先到的 error 已完成业务收口;真实 exit 日志只能在其后。
+ // error 路径没有 stopping baseline,但仍须记录随后到达的真实进程退出。
+ if (!error) this.debugProcessExit(entry, code, signal, Date.now());
return;
}
if (error && !entry.stopping && !entry.hardKillTimer) {
@@ -1643,7 +2024,15 @@ export class GhostNodeRuntimeBroker {
const settle = () => this.settleExit(entry, code, signal, error);
const timer = this.setTimer(settle, 500);
timer.unref?.();
- entry.exitDrain = { code, signal, error, timer, exitedAt: this.now(), gen };
+ entry.exitDrain = {
+ code,
+ signal,
+ error,
+ timer,
+ exitedAt: this.now(),
+ exitObservedAt: Date.now(),
+ gen,
+ };
entry.child.stderr.once?.('end', settle);
}
@@ -1654,7 +2043,7 @@ export class GhostNodeRuntimeBroker {
error: Error | null,
): void {
if (!entry.exitDrain) return;
- const { exitedAt, gen } = entry.exitDrain;
+ const { exitedAt, exitObservedAt, gen } = entry.exitDrain;
this.clearTimer(entry.exitDrain.timer);
entry.exitDrain = null;
// flush stderrDecoder 残留字节(多字节字符被切在最后一个 chunk 边界时)
@@ -1686,6 +2075,31 @@ export class GhostNodeRuntimeBroker {
this.sendStatus(entry.ghost, 'crashed', detail, entry.entryRel);
}
}
+ // pending reject、状态广播与所有 HEAD exit 收口完成后才允许诊断 logger 运行。
+ if (!error) this.debugProcessExit(entry, code, signal, exitObservedAt);
+ }
+
+ private debugProcessExit(
+ entry: WorkerEntry,
+ code: number | null,
+ signal: string | null,
+ exitObservedAt: number,
+ ): void {
+ const pid = entry.diagnosticPid;
+ debugDiagnostic(this.deps.log, 'ghost node process lifecycle', {
+ ghostId: entry.ghost.manifest.id,
+ entry: entry.entryRel,
+ appRunId: entry.appRunId,
+ attemptId: entry.attemptId,
+ ...(pid !== undefined ? { pid } : {}),
+ stage: 'exit',
+ code,
+ signal,
+ // 基线在 signal/grace/status 完成后建立;elapsed 不包含诊断 logger 自身耗时。
+ ...(entry.stoppingStartedAt !== undefined
+ ? { stoppingElapsedMs: exitObservedAt - entry.stoppingStartedAt }
+ : {}),
+ });
}
/**
@@ -1726,7 +2140,19 @@ export class GhostNodeRuntimeBroker {
(entry.ghost.manifest.node?.idleTimeoutSeconds ?? DEFAULT_IDLE_TIMEOUT_MS / 1_000) * 1_000;
// 空闲只收本入口的进程,不牵连同插件其它入口。
entry.idleTimer = this.setTimer(() => {
- if (this.workers.get(key) === entry) this.stopWorker(key, entry);
+ if (this.workers.get(key) === entry) {
+ const pid = entry.diagnosticPid;
+ // 先执行 HEAD 的 stopWorker;idle reason 日志不能推迟 SIGTERM/grace timer。
+ this.stopWorker(key, entry);
+ debugDiagnostic(this.deps.log, 'ghost node process lifecycle', {
+ ghostId: entry.ghost.manifest.id,
+ entry: entry.entryRel,
+ appRunId: entry.appRunId,
+ attemptId: entry.attemptId,
+ ...(pid !== undefined ? { pid } : {}),
+ stage: 'idle-stop',
+ });
+ }
}, timeoutMs);
entry.idleTimer.unref?.();
}
@@ -1759,6 +2185,14 @@ export class GhostNodeRuntimeBroker {
return this.deps.now?.() ?? Date.now();
}
+ private diagnosticNow(): number | undefined {
+ try {
+ return this.deps.diagnosticNow?.() ?? Date.now();
+ } catch {
+ return undefined;
+ }
+ }
+
private setTimer(callback: () => void, delayMs: number): NodeJS.Timeout {
if (this.deps.setTimer) return this.deps.setTimer(callback, delayMs);
return setTimeout(callback, delayMs) as NodeJS.Timeout;
diff --git a/apps/desktop/src/main/log-upload/__tests__/sourceAllowlist.test.ts b/apps/desktop/src/main/log-upload/__tests__/sourceAllowlist.test.ts
index 3b7b43632b..850b93b748 100644
--- a/apps/desktop/src/main/log-upload/__tests__/sourceAllowlist.test.ts
+++ b/apps/desktop/src/main/log-upload/__tests__/sourceAllowlist.test.ts
@@ -49,6 +49,7 @@ describe('拒绝:会打用户内容的来源', () => {
['session-search', '搜索关键词'],
['chat-history-search', '搜索关键词'],
['maker-ipc', 'agent 编排,带提示词'],
+ ['brain', '插件运行时诊断与第三方标识'],
['brain-runtime', '插件运行时,带用户内容'],
['skillhub:publishService', '用户内容'],
['secrets:builtin-api-key', '凭证相关'],