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。

feat(desktop): 新增资源用量进程面板 (#1936)

DavidShenXDa59db181389c
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 015e54d6af..55d0228aa4 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -315,6 +315,7 @@ import {
} from './voice-input/powerReleaseNotifier';
import { reapClaudeOrphansSync } from './claude-orphan-reaper';
import { startAgentProcessPriorityWatcher } from './agent-process-priority';
+import { registerProcessMonitorIpc } from './process-monitor/ipc.js';
import { initAppBadgeService, clearAllSessionAttention } from './appBadgeService';
import { initNotificationService } from './notificationService';
import { initWecomGroupNotificationIpc } from './wecomGroupNotification';
@@ -1371,6 +1372,11 @@ registerBrowserBackendIpc();
registerAppShortcutIpc();
registerAppearanceSettingsIpc();
+// ── 资源用量面板 IPC ─────────────────────────────────────────────────
+// 订阅驱动采样(面板不开不采样),interval 已 unref 不拖退出;terminate 只认
+// 本产品 spawn 的 agent 根进程。见 main/process-monitor/。
+registerProcessMonitorIpc();
+
// ── 主界面布局树存储 IPC──────────────────────────────────────────────
// renderer 首帧 sendSync 拉布局(规则 7 无跳变)、set/reset 写路径、changed
// 广播。注册时顺带 ensurePersisted:userData 落 layout.v1.json + 损坏自愈。
diff --git a/apps/desktop/src/main/claude-orphan-reaper.ts b/apps/desktop/src/main/claude-orphan-reaper.ts
index dd111955ba..b94dee16ef 100644
--- a/apps/desktop/src/main/claude-orphan-reaper.ts
+++ b/apps/desktop/src/main/claude-orphan-reaper.ts
@@ -258,7 +258,11 @@ function killPosixProcessTree(pid: number, childrenByParent: Map<number, number[
// rest still got the signal. Only treat hard process errors (above) as failure.
}
-function killProcessTree(pid: number, childrenByParent: Map<number, number[]>): boolean {
+/**
+ * 杀掉一棵进程树,best-effort。除本收割器外,process-monitor 的「结束进程」
+ * 也复用这条路径(调用前必须已按 ppid + marker 独立校验归属)。
+ */
+export function killProcessTree(pid: number, childrenByParent: Map<number, number[]>): boolean {
try {
if (process.platform === 'win32') {
killWindowsProcessTree(pid);
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexModelBackfillWiring.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexModelBackfillWiring.test.ts
new file mode 100644
index 0000000000..9822cd140f
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/codexModelBackfillWiring.test.ts
@@ -0,0 +1,17 @@
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const makerHostSource = readFileSync(resolve(__dirname, '..', 'index.ts'), 'utf8').replace(
+ /\s+/g,
+ ' ',
+);
+
+describe('Codex model backfill wiring', () => {
+ it('routes OAuth startup discovery through the isolated control-plane host', () => {
+ expect(makerHostSource).toContain(
+ "refreshLive: () => makerRef.refreshAgentLocalModels('codex', { credentialMode: 'oauth-bearer', }),",
+ );
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 959740cf35..4fe176a3e5 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -181,6 +181,10 @@ import {
resolveCodexSubagentModelFallback,
} from './codex-subagent-config.js';
import { readSubagentModelSettings } from './subagent-model-settings-store.js';
+import {
+ registerAgentProcess,
+ registerCodexProcessRole,
+} from '../process-monitor/codex-process-registry.js';
import { getOutboundPathSnapshotFor } from './outbound-proxy-resolver.js';
import {
createDesktopMakerMemoryManager,
@@ -758,6 +762,8 @@ export function getMaker(): Maker {
beforeKnownFileWrite: captureKnownFileBefore,
noteOpaqueWrite: noteOpaqueTurnChange,
},
+ registerLocalAgentProcess: ({ pid, kind, role }) =>
+ registerAgentProcess(pid, kind, role),
reviewAutoPermissionAction,
// 每个 session 的 cc 子进程 debug 写到 sessions/<id>/cc-debug.raw.log (logger 拼路径
// + mkdir), tailer 再归一化汇入该 session 的 <date>.ndjson。
@@ -1006,6 +1012,8 @@ export function getMaker(): Maker {
runtimeConfig: desktopCodexRuntimeConfig,
binaryPath: codexPath,
logger: desktopMakerLogger,
+ registerLocalCodexAppServerProcess: ({ pid, role }) =>
+ registerCodexProcessRole(pid, role),
// Codex 也接 Cindy MCP providers (跟 claude 共享同一份 provider instances);
// codex 子进程没法消费 in-process JS instance, prepareCodexExtraSpawnConfig
// 起 streamable-HTTP bridge 把 instance 通过 -c 'mcp_servers...=...' 注入。
@@ -1444,6 +1452,8 @@ export function getMaker(): Maker {
beforeKnownFileWrite: captureKnownFileBefore,
noteOpaqueWrite: noteOpaqueTurnChange,
},
+ registerLocalAgentProcess: ({ pid, kind, role }) =>
+ registerAgentProcess(pid, kind, role),
reviewAutoPermissionAction,
capabilityAdditions: {
availableModels: deriveAvailableModels(getDesktopSelectableCatalog(), 'pi'),
@@ -1554,7 +1564,9 @@ export function getMaker(): Maker {
hasCodexLogin: () => desktopCodexAuthAdapter.hasCodexOAuthLogin(),
hasCodexModels: () =>
(getActiveCatalog().providers.find((p) => p.id === 'openai')?.models.codex?.length ?? 0) > 0,
- refreshLive: () => makerRef.refreshAgentLocalModels('codex'),
+ refreshLive: () => makerRef.refreshAgentLocalModels('codex', {
+ credentialMode: 'oauth-bearer',
+ }),
onApplied: () => refreshSelectableModelsAndBroadcast({}),
log: desktopMakerLogger,
});
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index 5464b548ef..6f883485b6 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -187,6 +187,7 @@ function buildDesktopPiRuntimeConfig(): AgentRuntimeConfig {
export interface BuildPiAgentOpts {
logger: AgentDeps['logger'];
turnChangeCapture?: AgentDeps['turnChangeCapture'];
+ registerLocalAgentProcess?: AgentDeps['registerLocalAgentProcess'];
capabilityAdditions?: AgentDeps['capabilityAdditions'];
reviewAutoPermissionAction?: AgentDeps['reviewAutoPermissionAction'];
/** Cindy MCP providers(与 claude/codex 同源工厂产物);经 HTTP bridge 暴露给 pi。 */
@@ -363,6 +364,7 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {
binaryPath,
logger: opts.logger,
turnChangeCapture: opts.turnChangeCapture,
+ registerLocalAgentProcess: opts.registerLocalAgentProcess,
capabilityAdditions: opts.capabilityAdditions,
reviewAutoPermissionAction: opts.reviewAutoPermissionAction,
mcpProviders: opts.mcpProviders,
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
index 2e0b558fff..b7bfe4ceac 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/authStatusUsageHandlers.test.ts
@@ -70,7 +70,9 @@ describe('maker auth IPC handlers', () => {
identity: { email: '[email protected]' },
});
expect(onCodexAuthChange).toHaveBeenCalledOnce();
- expect(refreshAgentLocalModels).toHaveBeenCalledWith('codex');
+ expect(refreshAgentLocalModels).toHaveBeenCalledWith('codex', {
+ credentialMode: 'oauth-bearer',
+ });
expect(onCodexAuthChange).toHaveBeenCalledWith(true, true, expect.any(Function));
expect(broadcast).toHaveBeenNthCalledWith(1, MAKER_PUSH.AUTH_LOGIN_PROGRESS, {
agentKind: 'codex',
diff --git a/apps/desktop/src/main/maker-ipc/authHandlers.ts b/apps/desktop/src/main/maker-ipc/authHandlers.ts
index 6f1212387d..f7e4a2799c 100644
--- a/apps/desktop/src/main/maker-ipc/authHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/authHandlers.ts
@@ -306,7 +306,9 @@ export function registerMakerAuthHandlers(
if (kind === 'codex' && result.authenticated && result.authSource === 'oauth') {
let liveModelsApplied = false;
try {
- liveModelsApplied = await maker.refreshAgentLocalModels('codex');
+ liveModelsApplied = await maker.refreshAgentLocalModels('codex', {
+ credentialMode: 'oauth-bearer',
+ });
} catch (e) {
// 登录本身已成功;实时模型发现失败时由 host 回退磁盘快照,不能把登录判失败。
// 但记异常原因(原先静默吞掉,首登无模型时无从诊断是 app-server 起不来还是
diff --git a/apps/desktop/src/main/process-monitor/__tests__/agent-scan.test.ts b/apps/desktop/src/main/process-monitor/__tests__/agent-scan.test.ts
new file mode 100644
index 0000000000..cfc199b527
--- /dev/null
+++ b/apps/desktop/src/main/process-monitor/__tests__/agent-scan.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, it } from 'vitest';
+
+import { allUserDataDirNames } from '@cindy/maker-shared/brand-identity';
+
+import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion.js';
+import {
+ buildChildrenByParent,
+ buildPiPathMarkers,
+ buildPosixProcessScanEnv,
+ classifyMonitoredAgentCommandLine,
+ collectDescendantPids,
+ parsePosixProcessTable,
+ parseWindowsProcessTable,
+ registerPiUserDataMarkers,
+} from '../agent-scan.js';
+
+describe('buildPosixProcessScanEnv', () => {
+ it('固定英文输出与 UTC,消除 lstart 的 locale / DST 歧义', () => {
+ expect(buildPosixProcessScanEnv({ LANG: 'zh_CN.UTF-8', TZ: 'Asia/Shanghai' })).toEqual({
+ LANG: 'zh_CN.UTF-8',
+ LC_ALL: 'C',
+ TZ: 'UTC0',
+ });
+ });
+});
+
+describe('parsePosixProcessTable', () => {
+ it('解析 pid/ppid/stat/%cpu/rss/lstart/command,容忍空行与非法行', () => {
+ const out = [
+ ' 101 100 S+ 12.5 20480 Wed Aug 6 12:34:56 2026 /usr/bin/node server.js',
+ '',
+ 'garbage line without numbers',
+ ' 102 101 T 0.0 512 Wed Aug 6 12:35:01 2026 bash -c "sleep 1"',
+ ].join('\n');
+ const rows = parsePosixProcessTable(out);
+ expect(rows).toHaveLength(2);
+ expect(rows[0]).toMatchObject({
+ pid: 101,
+ ppid: 100,
+ state: 'S+',
+ cpuPercent: 12.5,
+ memoryKb: 20480,
+ cpuTimeMs: null,
+ startIdentity: 'Wed Aug 6 12:34:56 2026',
+ });
+ expect(rows[0].cmdLineLower).toBe('/usr/bin/node server.js');
+ expect(rows[1].cmdLineLower).toContain('sleep 1');
+ expect(rows[1].state).toBe('T');
+ });
+});
+
+describe('parseWindowsProcessTable', () => {
+ it('解析 pid|ppid|workingSet|cpuTime|creationTicks|cmd,命令行含管道符不截断', () => {
+ const out = [
+ '4321|100|104857600|1500000|638901092960000000|C:\\bin\\claude.exe run | tee log',
+ 'not|a|row',
+ '',
+ ].join('\r\n');
+ const rows = parseWindowsProcessTable(out);
+ expect(rows).toHaveLength(1);
+ expect(rows[0]).toMatchObject({
+ pid: 4321,
+ ppid: 100,
+ state: null,
+ memoryKb: 102400, // 100MB → KB
+ cpuTimeMs: 150, // 1_500_000 * 100ns = 150ms
+ cpuPercent: null,
+ startIdentity: '638901092960000000',
+ });
+ expect(rows[0].cmdLineLower).toBe('c:\\bin\\claude.exe run | tee log');
+ });
+
+ it('有输出但全不可解析时返回空(格式漂移由上层日志暴露)', () => {
+ expect(parseWindowsProcessTable('ProcessId ParentProcessId\n123 456')).toEqual([]);
+ });
+});
+
+describe('classifyMonitoredAgentCommandLine', () => {
+ it('识别 pi 静态品牌 marker,不影响 claude/codex 委托', () => {
+ const piMarkers = buildPiPathMarkers(['cindy']);
+ expect(piMarkers).toContain('appdata\\roaming\\cindy\\pi\\');
+ // 品牌目录名随构建配置变化(如 CindyGlobal / 历史 xdt-maker),测试从真实
+ // 品牌清单派生 probe,不写死品牌名。
+ const brandDir = allUserDataDirNames(CURRENT_CINDY_REGION)[0].toLowerCase();
+ expect(
+ classifyMonitoredAgentCommandLine(
+ `c:\\users\\u\\appdata\\roaming\\${brandDir}\\pi\\1.0\\pi.exe`,
+ ),
+ ).toBe('pi');
+ // 外部安装的同名二进制不带产品 marker → 不认领。
+ expect(classifyMonitoredAgentCommandLine('/usr/local/bin/pi serve')).toBeNull();
+ });
+
+ it('识别 dev/sandbox 的 apps/pi-bin 二进制路径', () => {
+ expect(
+ classifyMonitoredAgentCommandLine(
+ 'd:\\projects\\cindy\\apps\\pi-bin\\win32-x64\\pi.exe --rpc',
+ ),
+ ).toBe('pi');
+ expect(
+ classifyMonitoredAgentCommandLine('/repo/apps/pi-bin/darwin-arm64/pi --rpc'),
+ ).toBe('pi');
+ });
+
+ it('识别运行时 userData 派生的 pi marker(userData 重定向场景)', () => {
+ registerPiUserDataMarkers('/custom/data-home/CindyBrand');
+ expect(
+ classifyMonitoredAgentCommandLine('/custom/data-home/cindybrand/pi/2.0/pi --rpc'),
+ ).toBe('pi');
+ // 空路径显式清空,不能退化成会命中所有 `/pi/` 路径的宽泛 marker。
+ registerPiUserDataMarkers('');
+ expect(classifyMonitoredAgentCommandLine('/opt/pi/2.0/pi --rpc')).toBeNull();
+ });
+});
+
+describe('buildChildrenByParent / collectDescendantPids', () => {
+ it('展开整棵子树且防环', () => {
+ const rows = [
+ { pid: 1, ppid: 0 },
+ { pid: 2, ppid: 1 },
+ { pid: 3, ppid: 2 },
+ { pid: 4, ppid: 9 }, // 无关分支
+ ].map((r) => ({
+ ...r,
+ state: null,
+ cmdLineLower: '',
+ memoryKb: 0,
+ cpuPercent: 0,
+ cpuTimeMs: null,
+ startIdentity: null,
+ }));
+ const map = buildChildrenByParent(rows);
+ // 人为制造环:3 → 1
+ map.set(3, [1]);
+ const pids = collectDescendantPids(1, map);
+ expect([...pids].sort((a, b) => a - b)).toEqual([1, 2, 3]);
+ });
+});
diff --git a/apps/desktop/src/main/process-monitor/__tests__/codex-process-registry.test.ts b/apps/desktop/src/main/process-monitor/__tests__/codex-process-registry.test.ts
new file mode 100644
index 0000000000..6a29b431d3
--- /dev/null
+++ b/apps/desktop/src/main/process-monitor/__tests__/codex-process-registry.test.ts
@@ -0,0 +1,48 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ _resetCodexProcessRegistryForTests,
+ registerAgentProcess,
+ registerCodexProcessRole,
+ resolveAgentProcessRegistration,
+ resolveCodexProcessRole,
+} from '../codex-process-registry.js';
+
+beforeEach(() => {
+ _resetCodexProcessRegistryForTests();
+});
+
+describe('codex process registry', () => {
+ it('登记角色并在 disposer 时清理', () => {
+ const dispose = registerCodexProcessRole(101, 'task-host');
+ expect(resolveCodexProcessRole(101)).toBe('task-host');
+ dispose();
+ dispose();
+ expect(resolveCodexProcessRole(101)).toBeNull();
+ });
+
+ it('PID 复用后旧 disposer 不会删除新登记', () => {
+ const disposeOld = registerCodexProcessRole(101, 'task-host');
+ const disposeNew = registerCodexProcessRole(101, 'control-plane-service');
+ disposeOld();
+ expect(resolveCodexProcessRole(101)).toBe('control-plane-service');
+ disposeNew();
+ expect(resolveCodexProcessRole(101)).toBeNull();
+ });
+
+ it('同一 PID 的每次实际 spawn 都获得不同 generation,旧 disposer 不影响新实例', () => {
+ const disposeOld = registerAgentProcess(202, 'claude', 'task-host');
+ const oldRegistration = resolveAgentProcessRegistration(202);
+ const disposeNew = registerAgentProcess(202, 'claude', 'task-host');
+ const newRegistration = resolveAgentProcessRegistration(202);
+
+ expect(oldRegistration).toMatchObject({ kind: 'claude', role: 'task-host' });
+ expect(newRegistration).toMatchObject({ kind: 'claude', role: 'task-host' });
+ expect(newRegistration?.instanceId).not.toBe(oldRegistration?.instanceId);
+
+ disposeOld();
+ expect(resolveAgentProcessRegistration(202)).toEqual(newRegistration);
+ disposeNew();
+ expect(resolveAgentProcessRegistration(202)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/process-monitor/__tests__/ipc.test.ts b/apps/desktop/src/main/process-monitor/__tests__/ipc.test.ts
new file mode 100644
index 0000000000..30bdca59be
--- /dev/null
+++ b/apps/desktop/src/main/process-monitor/__tests__/ipc.test.ts
@@ -0,0 +1,437 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ ipcHandle: vi.fn(),
+ ipcRemoveHandler: vi.fn(),
+ assertTrustedAppRendererEvent: vi.fn(),
+ isTrustedAppRendererWindow: vi.fn().mockReturnValue(true),
+ fromWebContents: vi.fn().mockReturnValue({}),
+}));
+
+vi.mock('electron', () => ({
+ app: { getPath: () => '/tmp/userData', getAppMetrics: () => [] },
+ ipcMain: { handle: mocks.ipcHandle, removeHandler: mocks.ipcRemoveHandler },
+ webContents: { getAllWebContents: () => [] },
+ BrowserWindow: { fromWebContents: mocks.fromWebContents },
+}));
+
+vi.mock('../../security/trustedAppRenderer.js', () => ({
+ assertTrustedAppRendererEvent: mocks.assertTrustedAppRendererEvent,
+ isTrustedAppRendererWindow: mocks.isTrustedAppRendererWindow,
+}));
+
+vi.mock('../../logger', () => ({
+ createLogger: () => ({ info: vi.fn(), warn: vi.fn() }),
+}));
+
+import {
+ PROCESS_MONITOR_SAMPLE_CHANNEL,
+ PROCESS_MONITOR_SUBSCRIBE_CHANNEL,
+ PROCESS_MONITOR_TERMINATE_CHANNEL,
+ PROCESS_MONITOR_UNSUBSCRIBE_CHANNEL,
+} from '../../../shared/processMonitor.js';
+import { buildChildrenByParent, type OsProcessRow } from '../agent-scan.js';
+import { _resetProcessMonitorIpcForTests, registerProcessMonitorIpc } from '../ipc.js';
+
+const SELF_PID = 4242;
+
+function osRow(partial: Partial<OsProcessRow> & { pid: number; ppid: number }): OsProcessRow {
+ return {
+ state: 'S',
+ cmdLineLower: '',
+ memoryKb: 0,
+ cpuPercent: 0,
+ cpuTimeMs: null,
+ startIdentity: `start:${partial.pid}`,
+ ...partial,
+ };
+}
+
+function terminateRequest(pid: number, processInstanceId = `start:${pid}`) {
+ return { pid, processInstanceId };
+}
+
+function handlerFor(channel: string) {
+ const call = mocks.ipcHandle.mock.calls.find(([ch]) => ch === channel);
+ expect(call, `handler for ${channel}`).toBeDefined();
+ return call![1] as (...args: unknown[]) => unknown;
+}
+
+interface FakeWebContents {
+ isDestroyed(): boolean;
+ send: ReturnType<typeof vi.fn>;
+ once: ReturnType<typeof vi.fn>;
+ removeListener: ReturnType<typeof vi.fn>;
+}
+
+function fakeSender(): FakeWebContents {
+ return {
+ isDestroyed: () => false,
+ send: vi.fn(),
+ once: vi.fn(),
+ removeListener: vi.fn(),
+ };
+}
+
+function register(overrides: Parameters<typeof registerProcessMonitorIpc>[0] = {}) {
+ registerProcessMonitorIpc({
+ sampler: { sample: vi.fn().mockResolvedValue({ capturedAtMs: 1, entries: [] }) },
+ scanOsProcessesSync: vi.fn().mockReturnValue({ rows: [], childrenByParent: new Map() }),
+ classify: () => null,
+ resolveAgentProcessRegistration: (pid) => ({
+ kind: 'claude',
+ role: 'task-host',
+ instanceId: `start:${pid}`,
+ }),
+ killProcessTree: vi.fn().mockReturnValue(true),
+ signalProcess: vi.fn(),
+ platform: 'linux',
+ selfPid: SELF_PID,
+ log: { info: vi.fn(), warn: vi.fn() },
+ ...overrides,
+ });
+}
+
+beforeEach(() => {
+ _resetProcessMonitorIpcForTests();
+ mocks.ipcHandle.mockClear();
+ mocks.assertTrustedAppRendererEvent.mockReset();
+ mocks.isTrustedAppRendererWindow.mockReset().mockReturnValue(true);
+});
+
+describe('process monitor IPC authorization', () => {
+ it('三个 handler 都先过 app-content 高权限断言', async () => {
+ register();
+ const event = { sender: fakeSender() };
+ await handlerFor(PROCESS_MONITOR_SUBSCRIBE_CHANNEL)(event);
+ await handlerFor(PROCESS_MONITOR_UNSUBSCRIBE_CHANNEL)(event);
+ mocks.assertTrustedAppRendererEvent.mockImplementation(() => {
+ throw new Error('[PERMISSION_DENIED] nope');
+ });
+ expect(() => handlerFor(PROCESS_MONITOR_TERMINATE_CHANNEL)(event, terminateRequest(1))).toThrow(
+ 'PERMISSION_DENIED',
+ );
+ expect(mocks.assertTrustedAppRendererEvent).toHaveBeenCalledTimes(3);
+ });
+
+ it('订阅后立即推送一帧;窗口不再可信时不推', async () => {
+ const sample = { capturedAtMs: 7, entries: [] };
+ const sampleNow = vi.fn().mockResolvedValue(sample);
+ register({ sampler: { sample: sampleNow } });
+ const sender = fakeSender();
+ await handlerFor(PROCESS_MONITOR_SUBSCRIBE_CHANNEL)({ sender });
+ await vi.waitFor(() => {
+ expect(sender.send).toHaveBeenCalledWith(PROCESS_MONITOR_SAMPLE_CHANNEL, sample);
+ });
+
+ sender.send.mockClear();
+ mocks.isTrustedAppRendererWindow.mockReturnValue(false);
+ await handlerFor(PROCESS_MONITOR_SUBSCRIBE_CHANNEL)({ sender });
+ // 等一个微任务链走完:采样发生但没有 send。
+ await new Promise((r) => setTimeout(r, 0));
+ expect(sender.send).not.toHaveBeenCalled();
+
+ // 失信 sender 已从订阅集合移除;恢复可信后会重新登记 destroyed 监听。
+ mocks.isTrustedAppRendererWindow.mockReturnValue(true);
+ await handlerFor(PROCESS_MONITOR_SUBSCRIBE_CHANNEL)({ sender });
+ await vi.waitFor(() => expect(sender.once).toHaveBeenCalledTimes(2));
+ expect(sender.removeListener).toHaveBeenCalledTimes(1);
+ });
+
+ it('反复切换面板时清理旧 destroyed 监听器', async () => {
+ register();
+ const sender = fakeSender();
+ const subscribe = handlerFor(PROCESS_MONITOR_SUBSCRIBE_CHANNEL);
+ const unsubscribe = handlerFor(PROCESS_MONITOR_UNSUBSCRIBE_CHANNEL);
+
+ await subscribe({ sender });
+ await unsubscribe({ sender });
+ await subscribe({ sender });
+ await unsubscribe({ sender });
+
+ expect(sender.once).toHaveBeenCalledTimes(2);
+ expect(sender.removeListener).toHaveBeenCalledTimes(2);
+ expect(sender.removeListener).toHaveBeenNthCalledWith(1, 'destroyed', expect.any(Function));
+ expect(sender.removeListener).toHaveBeenNthCalledWith(2, 'destroyed', expect.any(Function));
+ });
+});
+
+describe('terminate ownership validation', () => {
+ const ownedRows = [
+ osRow({ pid: 900, ppid: SELF_PID, cmdLineLower: 'claude-marker main' }),
+ osRow({ pid: 901, ppid: 900, cmdLineLower: 'bash child' }),
+ osRow({ pid: 902, ppid: 901, cmdLineLower: 'node tool child' }),
+ osRow({ pid: 950, ppid: 1, cmdLineLower: 'claude-marker orphan' }),
+ osRow({ pid: 960, ppid: SELF_PID, cmdLineLower: 'not-an-agent' }),
+ ];
+ const classify = (cmd: string) => (cmd.includes('claude-marker') ? ('claude' as const) : null);
+
+ function registerWithRows(
+ killProcessTree = vi.fn().mockReturnValue(true),
+ signalProcess = vi.fn(),
+ ) {
+ let scanCount = 0;
+ register({
+ scanOsProcessesSync: vi.fn(() => {
+ scanCount += 1;
+ const rows =
+ scanCount === 1
+ ? ownedRows
+ : ownedRows.map((candidate) => ({ ...candidate, state: 'T' }));
+ return { rows, childrenByParent: buildChildrenByParent(rows) };
+ }),
+ classify,
+ killProcessTree,
+ signalProcess,
+ });
+ return killProcessTree;
+ }
+
+ it('POSIX 暂停根后逐层冻结并终止多级后代', () => {
+ const signal = vi.fn();
+ const kill = registerWithRows(undefined, signal);
+ const result = handlerFor(PROCESS_MONITOR_TERMINATE_CHANNEL)(
+ { sender: fakeSender() },
+ terminateRequest(900),
+ );
+ expect(result).toEqual({ pid: 900, kind: 'claude' });
+ expect(kill).not.toHaveBeenCalled();
+ expect(signal.mock.calls).toEqual([
+ [900, 'SIGSTOP'],
+ [901, 'SIGSTOP'],
+ [902, 'SIGSTOP'],
+ [902, 'SIGKILL'],
+ [901, 'SIGKILL'],
+ [900, 'SIGKILL'],
+ ]);
+ });
+
+ it('Windows 仍由 taskkill /T 展开树,只扫描和校验一次', () => {
+ const snapshot = {
+ rows: ownedRows,
+ childrenByParent: buildChildrenByParent(ownedRows),
+ };
+ const scan = vi.fn().mockReturnValue(snapshot);
+ const kill = vi.fn().mockReturnValue(true);
+ register({
+ platform: 'win32',
+ scanOsProcessesSync: scan,
+ classify,
+ killProcessTree: kill,
+ });
+
+ expect(
+ handlerFor(PROCESS_MONITOR_TERMINATE_CHANNEL)(
+ { sender: fakeSender() },
+ terminateRequest(900),
+ ),
+ ).toEqual({ pid: 900, kind: 'claude' });
+ expect(scan).toHaveBeenCalledTimes(1);
+ expect(kill).toHaveBeenCalledWith(900, new Map());
+ });
+
+ it.each([
+ [
+ '出生身份改变',
+ osRow({
+ pid: 900,
+ ppid: SELF_PID,
+ cmdLineLower: 'claude-marker main',
+ startIdentity: 'start:new',
+ }),
+ false,
+ ],
+ ['父进程改变', osRow({ pid: 900, ppid: 1, cmdLineLower: 'claude-marker main' }), true],
+ ['marker 消失', osRow({ pid: 900, ppid: SELF_PID, cmdLineLower: 'replacement process' }), true],
+ ])('POSIX 暂停后复核发现根进程%s时拒绝终止', (_description, recheckedRoot, shouldResume) => {
+ const first = { rows: ownedRows, childrenByParent: buildChildrenByParent(ownedRows) };
+ const secondRows = [recheckedRoot, ...ownedRows.filter((row) => row.pid !== 900)];
+ const second = { rows: secondRows, childrenByParent: buildChildrenByParent(secondRows) };
+ const scan = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second);
+ const kill = vi.fn().mockReturnValue(true);
+ const signal = vi.fn();
+ register({ scanOsProcessesSync: scan, classify, killProcessTree: kill, signalProcess: signal });
+
+ expect(() =>
+ handlerFor(PROCESS_MONITOR_TERMINATE_CHANNEL)(
+ { sender: fakeSender() },
+ terminateRequest(900),
+ ),
+ ).toThrow('NOT_FOUND');
+ expect(kill).not.toHaveBeenCalled();
+ expect(signal.mock.calls).toEqual(
+ shouldResume
+ ? [
+ [900, 'SIGSTOP'],
+ [900, 'SIGCONT'],
+ ]
+ : [[900, 'SIGSTOP']],
+ );
+ });
+
+ it('POSIX 暂停后的扫描失败时恢复根进程并返回 INTERNAL', () => {
+ const snapshot = { rows: ownedRows, childrenByParent: buildChildrenByParent(ownedRows) };
+ const scan = vi
+ .fn()
+ .mockReturnValueOnce(snapshot)
+ .mockImplementationOnce(() => {
+ throw new Error('second ps failed');
+ });
+ const kill = vi.fn().mockReturnValue(true);
+ const signal = vi.fn();
+ const log = { info: vi.fn(), warn: vi.fn() };
+ register({
+ scanOsProcessesSync: scan,
+ classify,
+ killProcessTree: kill,
+ signalProcess: signal,
+ log,
+ });
+
+ expect(() =>
+ handlerFor(PROCESS_MONITOR_TERMINATE_CHANNEL)(
+ { sender: fakeSender() },
+ terminateRequest(900),
+ ),
+ ).toThrow('INTERNAL');
+ expect(kill).not.toHaveBeenCalled();
+ expect(signal.mock.calls).toEqual([
+ [900, 'SIGSTOP'],
+ [900, 'SIGCONT'],
+ ]);
+ expect(log.warn).toHaveBeenCalledWith(
+ 'process monitor POSIX tree termination failed',
+ expect.objectContaining({ error: 'second ps failed' }),
+ );
+ });
+
+ it.each([
+ ['ppid 不是本进程(别家实例的 agent)', 950],
+ ['本进程子进程但没有 agent marker', 960],
+ ['进程根本不存在', 12345],
+ ])('拒绝:%s', async (_desc, pid) => {
+ const kill = registerWithRows();
+ expect(() =>
+ handlerFor(PROCESS_MONITOR_TERMINATE_CHANNEL)(
+ { sender: fakeSender() },
+ terminateRequest(pid),
+ ),
+ ).toThrow('NOT_FOUND');
+ expect(kill).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['负数', terminateRequest(-1)],
+ ['非整数', terminateRequest(1.5)],
+ ['字符串 pid', { pid: '900', processInstanceId: 'start:900' }],
+ ['缺少出生身份', { pid: 900 }],
+ ['空出生身份', { pid: 900, processInstanceId: '' }],
+ ['旧版裸 pid', 900],
+ ['自身 pid', terminateRequest(SELF_PID)],
+ ])('拒绝非法参数:%s', async (_desc, raw) => {
+ const kill = registerWithRows();
+ expect(() =>
+ handlerFor(PROCESS_MONITOR_TERMINATE_CHANNEL)({ sender: fakeSender() }, raw),
+ ).toThrow('INVALID_PARAMS');
+ expect(kill).not.toHaveBeenCalled();
+ });
+
+ it('Windows taskkill 失败返回 INTERNAL', async () => {
+ const snapshot = { rows: ownedRows, childrenByParent: buildChildrenByParent(ownedRows) };
+ register({
+ platform: 'win32',
+ scanOsProcessesSync: vi.fn().mockReturnValue(snapshot),
+ classify,
+ killProcessTree: vi.fn().mockReturnValue(false),
+ });
+ expect(() =>
+ handlerFor(PROCESS_MONITOR_TERMINATE_CHANNEL)(
+ { sender: fakeSender() },
+ terminateRequest(900),
+ ),
+ ).toThrow('INTERNAL');
+ });
+
+ it('归属扫描失败时包装为 IPC INTERNAL 且不泄露原始错误', async () => {
+ const kill = vi.fn().mockReturnValue(true);
+ const log = { info: vi.fn(), warn: vi.fn() };
+ register({
+ scanOsProcessesSync: vi.fn().mockImplementation(() => {
+ throw new Error('private powershell details');
+ }),
+ classify,
+ killProcessTree: kill,
+ log,
+ });
+ expect(() =>
+ handlerFor(PROCESS_MONITOR_TERMINATE_CHANNEL)(
+ { sender: fakeSender() },
+ terminateRequest(900),
+ ),
+ ).toThrow('INTERNAL');
+ expect(kill).not.toHaveBeenCalled();
+ expect(log.warn).toHaveBeenCalledWith(
+ 'process monitor ownership scan failed',
+ expect.objectContaining({ error: 'private powershell details' }),
+ );
+ });
+
+ it.each([
+ ['控制面服务', 'control-plane-service' as const],
+ ['角色未知', null],
+ ])('Codex %s 即使归属校验通过也不可终止', async (_description, role) => {
+ const rows = [osRow({ pid: 970, ppid: SELF_PID, cmdLineLower: 'codex-marker service' })];
+ const kill = vi.fn().mockReturnValue(true);
+ register({
+ scanOsProcessesSync: vi.fn().mockReturnValue({
+ rows,
+ childrenByParent: buildChildrenByParent(rows),
+ }),
+ classify: () => 'codex',
+ resolveAgentProcessRegistration: () =>
+ role ? { kind: 'codex', role, instanceId: 'start:970' } : null,
+ killProcessTree: kill,
+ });
+ expect(() =>
+ handlerFor(PROCESS_MONITOR_TERMINATE_CHANNEL)(
+ { sender: fakeSender() },
+ terminateRequest(970),
+ ),
+ ).toThrow('NOT_FOUND');
+ expect(kill).not.toHaveBeenCalled();
+ });
+
+ it('同秒复用 pid 时按 spawn generation 拒绝旧终止授权', async () => {
+ const reusedRows = [
+ osRow({
+ pid: 900,
+ ppid: SELF_PID,
+ cmdLineLower: 'claude-marker replacement',
+ // POSIX lstart 只有秒级;故意与旧进程保持相同,证明它不再承担授权身份。
+ startIdentity: 'same-second-lstart',
+ }),
+ ];
+ const kill = vi.fn().mockReturnValue(true);
+ register({
+ scanOsProcessesSync: vi.fn().mockReturnValue({
+ rows: reusedRows,
+ childrenByParent: buildChildrenByParent(reusedRows),
+ }),
+ classify,
+ resolveAgentProcessRegistration: () => ({
+ kind: 'claude',
+ role: 'task-host',
+ instanceId: 'spawn:new',
+ }),
+ killProcessTree: kill,
+ });
+
+ expect(() =>
+ handlerFor(PROCESS_MONITOR_TERMINATE_CHANNEL)(
+ { sender: fakeSender() },
+ terminateRequest(900, 'spawn:old'),
+ ),
+ ).toThrow('NOT_FOUND');
+ expect(kill).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/process-monitor/__tests__/safe-posix-process-tree.test.ts b/apps/desktop/src/main/process-monitor/__tests__/safe-posix-process-tree.test.ts
new file mode 100644
index 0000000000..627110b756
--- /dev/null
+++ b/apps/desktop/src/main/process-monitor/__tests__/safe-posix-process-tree.test.ts
@@ -0,0 +1,322 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { buildChildrenByParent, type OsProcessRow, type OsProcessSnapshot } from '../agent-scan.js';
+import { terminateSafePosixProcessTree } from '../safe-posix-process-tree.js';
+
+function row(pid: number, ppid: number, state = 'T'): OsProcessRow {
+ return {
+ pid,
+ ppid,
+ state,
+ cmdLineLower: `process-${pid}`,
+ memoryKb: 0,
+ cpuPercent: 0,
+ cpuTimeMs: null,
+ startIdentity: `start:${pid}`,
+ };
+}
+
+function snapshot(rows: OsProcessRow[]): OsProcessSnapshot {
+ return { rows, childrenByParent: buildChildrenByParent(rows) };
+}
+
+function errno(code: string): NodeJS.ErrnoException {
+ return Object.assign(new Error(code), { code });
+}
+
+describe('terminateSafePosixProcessTree', () => {
+ it('逐层确认停止状态,纳入暂停投递期间新出现的孙进程并后代优先终止', () => {
+ const scans = [
+ snapshot([row(100, 10, 'T'), row(101, 100, 'S'), row(200, 1, 'R')]),
+ snapshot([row(100, 10, 'T'), row(101, 100, 'T'), row(102, 101, 'S')]),
+ snapshot([row(100, 10, 'T'), row(101, 100, 'T'), row(102, 101, 'T')]),
+ ];
+ const scan = vi.fn(() => scans.shift()!);
+ const signal = vi.fn();
+
+ expect(
+ terminateSafePosixProcessTree({
+ rootPid: 100,
+ rootStartIdentity: 'start:100',
+ rootStateBeforeStop: 'S',
+ scan,
+ signal,
+ isExpectedRoot: (candidate) => candidate.ppid === 10,
+ }),
+ ).toBe('terminated');
+ expect(signal.mock.calls).toEqual([
+ [100, 'SIGSTOP'],
+ [101, 'SIGSTOP'],
+ [102, 'SIGSTOP'],
+ [102, 'SIGKILL'],
+ [101, 'SIGKILL'],
+ [100, 'SIGKILL'],
+ ]);
+ });
+
+ it('根进程消失或暂停后身份不再匹配时 fail closed', () => {
+ const missingSignal = vi.fn(() => {
+ throw errno('ESRCH');
+ });
+ expect(
+ terminateSafePosixProcessTree({
+ rootPid: 100,
+ rootStartIdentity: 'start:100',
+ rootStateBeforeStop: 'S',
+ scan: vi.fn(),
+ signal: missingSignal,
+ isExpectedRoot: () => true,
+ }),
+ ).toBe('root-not-found');
+
+ const changedSignal = vi.fn();
+ expect(
+ terminateSafePosixProcessTree({
+ rootPid: 100,
+ rootStartIdentity: 'start:100',
+ rootStateBeforeStop: 'S',
+ scan: () => snapshot([row(100, 999, 'T')]),
+ signal: changedSignal,
+ isExpectedRoot: (candidate) => candidate.ppid === 10,
+ }),
+ ).toBe('root-not-found');
+ expect(changedSignal.mock.calls).toEqual([
+ [100, 'SIGSTOP'],
+ [100, 'SIGCONT'],
+ ]);
+ });
+
+ it.each(['S', 'T'])(
+ '根进程原状态为 %s 但 PID 已被新实例复用时不向替代进程发 SIGCONT',
+ (rootStateBeforeStop) => {
+ const replacement = row(100, 10, 'T');
+ replacement.startIdentity = 'start:replacement';
+ const signal = vi.fn();
+
+ expect(
+ terminateSafePosixProcessTree({
+ rootPid: 100,
+ rootStartIdentity: 'start:original',
+ rootStateBeforeStop,
+ scan: () => snapshot([replacement]),
+ signal,
+ isExpectedRoot: (candidate) => candidate.startIdentity === 'start:original',
+ }),
+ ).toBe('root-not-found');
+ expect(signal.mock.calls).toEqual([[100, 'SIGSTOP']]);
+ },
+ );
+
+ it('SIGSTOP 后根或子进程仍在运行时拒绝枚举/终止并恢复已暂停节点', () => {
+ const rootSignal = vi.fn();
+ expect(() =>
+ terminateSafePosixProcessTree({
+ rootPid: 100,
+ rootStartIdentity: 'start:100',
+ rootStateBeforeStop: 'S',
+ scan: () => snapshot([row(100, 10, 'R'), row(101, 100, 'S')]),
+ signal: rootSignal,
+ isExpectedRoot: () => true,
+ }),
+ ).toThrow('process did not enter stopped state: 100');
+ expect(rootSignal.mock.calls).toEqual([
+ [100, 'SIGSTOP'],
+ [100, 'SIGCONT'],
+ ]);
+
+ const childScans = [
+ snapshot([row(100, 10, 'T'), row(101, 100, 'S')]),
+ snapshot([row(100, 10, 'T'), row(101, 100, 'S')]),
+ ];
+ const childSignal = vi.fn();
+ expect(() =>
+ terminateSafePosixProcessTree({
+ rootPid: 100,
+ rootStartIdentity: 'start:100',
+ rootStateBeforeStop: 'S',
+ scan: () => childScans.shift()!,
+ signal: childSignal,
+ isExpectedRoot: () => true,
+ }),
+ ).toThrow('process did not enter stopped state: 101');
+ expect(childSignal.mock.calls).toEqual([
+ [100, 'SIGSTOP'],
+ [101, 'SIGSTOP'],
+ [101, 'SIGCONT'],
+ [100, 'SIGCONT'],
+ ]);
+ });
+
+ it('子进程在暂停前退出且仍有已知后代时失败关闭并恢复根进程', () => {
+ const scan = vi.fn(() => snapshot([row(100, 10, 'T'), row(101, 100, 'S'), row(102, 101, 'S')]));
+ const signal = vi.fn((pid: number, processSignal: NodeJS.Signals) => {
+ if (pid === 101 && processSignal === 'SIGSTOP') throw errno('ESRCH');
+ });
+
+ expect(() =>
+ terminateSafePosixProcessTree({
+ rootPid: 100,
+ rootStartIdentity: 'start:100',
+ rootStateBeforeStop: 'S',
+ scan,
+ signal,
+ isExpectedRoot: () => true,
+ }),
+ ).toThrow('process exited before its descendants could be frozen: 101');
+ expect(signal.mock.calls).toEqual([
+ [100, 'SIGSTOP'],
+ [101, 'SIGSTOP'],
+ [100, 'SIGCONT'],
+ ]);
+ expect(scan).toHaveBeenCalledTimes(1);
+ });
+
+ it('旧快照没有后代时,子进程在暂停前退出仍失败关闭', () => {
+ const scan = vi.fn(() => snapshot([row(100, 10, 'T'), row(101, 100, 'S')]));
+ const signal = vi.fn((pid: number, processSignal: NodeJS.Signals) => {
+ if (pid === 101 && processSignal === 'SIGSTOP') throw errno('ESRCH');
+ });
+
+ expect(() =>
+ terminateSafePosixProcessTree({
+ rootPid: 100,
+ rootStartIdentity: 'start:100',
+ rootStateBeforeStop: 'S',
+ scan,
+ signal,
+ isExpectedRoot: () => true,
+ }),
+ ).toThrow('process exited before its descendants could be frozen: 101');
+ expect(signal.mock.calls).toEqual([
+ [100, 'SIGSTOP'],
+ [101, 'SIGSTOP'],
+ [100, 'SIGCONT'],
+ ]);
+ expect(scan).toHaveBeenCalledTimes(1);
+ });
+
+ it('扫描或 KILL 硬失败时恢复所有已确认暂停的进程', () => {
+ const scanError = new Error('ps failed');
+ const scanSignal = vi.fn();
+ expect(() =>
+ terminateSafePosixProcessTree({
+ rootPid: 100,
+ rootStartIdentity: 'start:100',
+ rootStateBeforeStop: 'S',
+ scan: () => {
+ throw scanError;
+ },
+ signal: scanSignal,
+ isExpectedRoot: () => true,
+ }),
+ ).toThrow(scanError);
+ expect(scanSignal.mock.calls).toEqual([
+ [100, 'SIGSTOP'],
+ [100, 'SIGCONT'],
+ ]);
+
+ const scans = [
+ snapshot([row(100, 10, 'T'), row(101, 100, 'S')]),
+ snapshot([row(100, 10, 'T'), row(101, 100, 'T')]),
+ ];
+ const killSignal = vi.fn((pid: number, processSignal: NodeJS.Signals) => {
+ if (pid === 101 && processSignal === 'SIGKILL') throw new Error('kill denied');
+ });
+ expect(() =>
+ terminateSafePosixProcessTree({
+ rootPid: 100,
+ rootStartIdentity: 'start:100',
+ rootStateBeforeStop: 'S',
+ scan: () => scans.shift()!,
+ signal: killSignal,
+ isExpectedRoot: () => true,
+ }),
+ ).toThrow('kill denied');
+ expect(killSignal.mock.calls).toEqual([
+ [100, 'SIGSTOP'],
+ [101, 'SIGSTOP'],
+ [101, 'SIGKILL'],
+ [101, 'SIGCONT'],
+ [100, 'SIGCONT'],
+ ]);
+ });
+
+ it('失败时只恢复本次暂停的节点,不改变原本已暂停的根或子进程', () => {
+ const scans = [
+ snapshot([row(100, 10, 'T'), row(101, 100, 'T')]),
+ snapshot([row(100, 10, 'T'), row(101, 100, 'T'), row(102, 101, 'S')]),
+ snapshot([row(100, 10, 'T'), row(101, 100, 'T'), row(102, 101, 'R')]),
+ ];
+ const signal = vi.fn();
+
+ expect(() =>
+ terminateSafePosixProcessTree({
+ rootPid: 100,
+ rootStartIdentity: 'start:100',
+ rootStateBeforeStop: 'T',
+ scan: () => scans.shift()!,
+ signal,
+ isExpectedRoot: () => true,
+ }),
+ ).toThrow('process did not enter stopped state: 102');
+ expect(signal.mock.calls).toEqual([
+ [100, 'SIGSTOP'],
+ [101, 'SIGSTOP'],
+ [102, 'SIGSTOP'],
+ [102, 'SIGCONT'],
+ ]);
+ });
+
+ it('SIGCONT 非 ESRCH 失败时以 AggregateError 上报,不能静默留下冻结进程', () => {
+ const signal = vi.fn((_pid: number, processSignal: NodeJS.Signals) => {
+ if (processSignal === 'SIGCONT') throw errno('EPERM');
+ });
+ let thrown: unknown;
+ try {
+ terminateSafePosixProcessTree({
+ rootPid: 100,
+ rootStartIdentity: 'start:100',
+ rootStateBeforeStop: 'S',
+ scan: () => snapshot([row(100, 999, 'T')]),
+ signal,
+ isExpectedRoot: (candidate) => candidate.ppid === 10,
+ });
+ } catch (error) {
+ thrown = error;
+ }
+ expect(thrown).toBeInstanceOf(AggregateError);
+ expect((thrown as AggregateError).errors).toHaveLength(1);
+ expect(signal.mock.calls).toEqual([
+ [100, 'SIGSTOP'],
+ [100, 'SIGCONT'],
+ ]);
+ });
+
+ it('确认快照形成环时不会重复暂停或死循环', () => {
+ const scans = [
+ snapshot([row(100, 102, 'T'), row(101, 100, 'S'), row(102, 101, 'S')]),
+ snapshot([row(100, 102, 'T'), row(101, 100, 'T'), row(102, 101, 'S')]),
+ snapshot([row(100, 102, 'T'), row(101, 100, 'T'), row(102, 101, 'T')]),
+ ];
+ const signal = vi.fn();
+
+ expect(
+ terminateSafePosixProcessTree({
+ rootPid: 100,
+ rootStartIdentity: 'start:100',
+ rootStateBeforeStop: 'S',
+ scan: () => scans.shift()!,
+ signal,
+ isExpectedRoot: () => true,
+ }),
+ ).toBe('terminated');
+ expect(signal.mock.calls).toEqual([
+ [100, 'SIGSTOP'],
+ [101, 'SIGSTOP'],
+ [102, 'SIGSTOP'],
+ [102, 'SIGKILL'],
+ [101, 'SIGKILL'],
+ [100, 'SIGKILL'],
+ ]);
+ });
+});
diff --git a/apps/desktop/src/main/process-monitor/__tests__/sampler.test.ts b/apps/desktop/src/main/process-monitor/__tests__/sampler.test.ts
new file mode 100644
index 0000000000..013800b7ab
--- /dev/null
+++ b/apps/desktop/src/main/process-monitor/__tests__/sampler.test.ts
@@ -0,0 +1,289 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { ProcessMonitorSample } from '../../../shared/processMonitor.js';
+import type { OsProcessRow, OsProcessSnapshot } from '../agent-scan.js';
+import { buildChildrenByParent } from '../agent-scan.js';
+import {
+ createProcessMonitorSampler,
+ type ChromiumProcessMetric,
+ type ProcessMonitorSamplerDeps,
+} from '../sampler.js';
+
+const SELF_PID = 100;
+
+function osRow(partial: Partial<OsProcessRow> & { pid: number; ppid: number }): OsProcessRow {
+ return {
+ state: null,
+ cmdLineLower: '',
+ memoryKb: 0,
+ cpuPercent: 0,
+ cpuTimeMs: null,
+ startIdentity: `start:${partial.pid}`,
+ ...partial,
+ };
+}
+
+function snapshotOf(rows: OsProcessRow[]): OsProcessSnapshot {
+ return { rows, childrenByParent: buildChildrenByParent(rows) };
+}
+
+function metric(partial: Partial<ChromiumProcessMetric> & { pid: number }): ChromiumProcessMetric {
+ return {
+ type: 'Utility',
+ cpu: { percentCPUUsage: 1 },
+ memory: { workingSetSize: 1024 },
+ ...partial,
+ };
+}
+
+interface HarnessOverrides {
+ metrics?: ChromiumProcessMetric[];
+ snapshot?: OsProcessSnapshot;
+ deps?: Partial<ProcessMonitorSamplerDeps>;
+}
+
+function makeHarness(overrides: HarnessOverrides = {}) {
+ const state = {
+ metrics: overrides.metrics ?? [],
+ snapshot: overrides.snapshot ?? snapshotOf([]),
+ nowMs: 10_000,
+ scanCalls: 0,
+ };
+ const log = { warn: vi.fn() };
+ const sampler = createProcessMonitorSampler({
+ getMetrics: () => state.metrics,
+ scanOsProcesses: () => {
+ state.scanCalls += 1;
+ return Promise.resolve(state.snapshot);
+ },
+ describeRendererProcess: () => null,
+ classify: (cmd) => {
+ if (cmd.includes('claude-marker')) return 'claude';
+ if (cmd.includes('codex-marker')) return 'codex';
+ if (cmd.includes('pi-marker')) return 'pi';
+ return null;
+ },
+ resolveAgentProcessRegistration: (pid) => {
+ const row = state.snapshot.rows.find((candidate) => candidate.pid === pid);
+ if (!row) return null;
+ const kind = row.cmdLineLower.includes('claude-marker')
+ ? 'claude'
+ : row.cmdLineLower.includes('codex-marker')
+ ? 'codex'
+ : row.cmdLineLower.includes('pi-marker')
+ ? 'pi'
+ : null;
+ return kind
+ ? { kind, role: 'task-host', instanceId: `start:${pid}` }
+ : null;
+ },
+ selfPid: SELF_PID,
+ log,
+ osScanIntervalMs: 5_000,
+ now: () => state.nowMs,
+ ...overrides.deps,
+ });
+ return { state, sampler, log };
+}
+
+function entryByPid(sample: ProcessMonitorSample, pid: number) {
+ return sample.entries.find((e) => e.pid === pid);
+}
+
+describe('createProcessMonitorSampler', () => {
+ it('Chromium 指标映射 kind 与标签;renderer 走注入的标签查询', async () => {
+ const { sampler } = makeHarness({
+ metrics: [
+ metric({ pid: 100, type: 'Browser' }),
+ metric({ pid: 200, type: 'Tab' }),
+ metric({ pid: 300, type: 'GPU' }),
+ metric({ pid: 400, type: 'Utility', serviceName: 'node-runtime' }),
+ ],
+ deps: { describeRendererProcess: (pid) => (pid === 200 ? '设置' : null) },
+ });
+ const sample = await sampler.sample();
+ expect(entryByPid(sample, 100)).toMatchObject({ kind: 'main', terminable: false });
+ expect(entryByPid(sample, 200)).toMatchObject({ kind: 'renderer', label: '设置' });
+ expect(entryByPid(sample, 300)).toMatchObject({ kind: 'gpu' });
+ expect(entryByPid(sample, 400)).toMatchObject({ kind: 'utility', label: 'node-runtime' });
+ });
+
+ it('agent 根进程按整棵子树聚合 CPU / 内存 / 进程数,外部进程不认领', async () => {
+ const { sampler } = makeHarness({
+ snapshot: snapshotOf([
+ osRow({ pid: 501, ppid: SELF_PID, cmdLineLower: 'x claude-marker y', cpuPercent: 10, memoryKb: 100 }),
+ osRow({ pid: 502, ppid: 501, cmdLineLower: 'bash worker', cpuPercent: 40, memoryKb: 200 }),
+ osRow({ pid: 503, ppid: 502, cmdLineLower: 'node mcp', cpuPercent: 5, memoryKb: 300 }),
+ // ppid 不是本进程:哪怕命中 marker 也不算我们的(另一实例的 agent)。
+ osRow({ pid: 601, ppid: 999, cmdLineLower: 'claude-marker other', cpuPercent: 99, memoryKb: 999 }),
+ ]),
+ });
+ const sample = await sampler.sample();
+ const agent = entryByPid(sample, 501);
+ expect(agent).toMatchObject({
+ kind: 'agent-claude',
+ cpuPercent: 55,
+ memoryKb: 600,
+ processCount: 3,
+ terminable: true,
+ processInstanceId: 'start:501',
+ });
+ expect(entryByPid(sample, 601)).toBeUndefined();
+ });
+
+ it('Codex 任务宿主与控制面服务带角色,控制面不可终止', async () => {
+ const { sampler } = makeHarness({
+ snapshot: snapshotOf([
+ osRow({ pid: 701, ppid: SELF_PID, cmdLineLower: 'codex-marker task' }),
+ osRow({ pid: 702, ppid: SELF_PID, cmdLineLower: 'codex-marker service' }),
+ ]),
+ deps: {
+ resolveAgentProcessRegistration: (pid) => ({
+ kind: 'codex',
+ role: pid === 701 ? 'task-host' : 'control-plane-service',
+ instanceId: `instance:${pid}`,
+ }),
+ },
+ });
+ const sample = await sampler.sample();
+ expect(entryByPid(sample, 701)).toMatchObject({
+ agentRole: 'task-host',
+ terminable: true,
+ });
+ expect(entryByPid(sample, 702)).toMatchObject({
+ agentRole: 'control-plane-service',
+ terminable: false,
+ });
+ });
+
+ it('Codex 角色未知时按不可终止处理', async () => {
+ const { sampler } = makeHarness({
+ snapshot: snapshotOf([
+ osRow({ pid: 703, ppid: SELF_PID, cmdLineLower: 'codex-marker unknown' }),
+ ]),
+ deps: { resolveAgentProcessRegistration: () => null },
+ });
+ expect(entryByPid(await sampler.sample(), 703)).toMatchObject({
+ kind: 'agent-codex',
+ terminable: false,
+ });
+ });
+
+ it('OS 未提供出生身份时即使归属明确也不可终止', async () => {
+ const { sampler } = makeHarness({
+ snapshot: snapshotOf([
+ osRow({
+ pid: 704,
+ ppid: SELF_PID,
+ cmdLineLower: 'claude-marker unknown-start',
+ startIdentity: null,
+ }),
+ ]),
+ });
+ expect(entryByPid(await sampler.sample(), 704)).toMatchObject({
+ kind: 'agent-claude',
+ terminable: false,
+ });
+ expect(entryByPid(await sampler.sample(), 704)?.processInstanceId).toBeUndefined();
+ });
+
+ it('Windows conhost 不计入可见进程数,但资源仍计入整棵树', async () => {
+ const { sampler } = makeHarness({
+ snapshot: snapshotOf([
+ osRow({
+ pid: 801,
+ ppid: SELF_PID,
+ cmdLineLower: 'c:\\cindy\\codex-marker.exe app-server',
+ cpuPercent: 4,
+ memoryKb: 100,
+ }),
+ osRow({
+ pid: 802,
+ ppid: 801,
+ cmdLineLower: '\\??\\c:\\windows\\system32\\conhost.exe 0x4',
+ cpuPercent: 1,
+ memoryKb: 20,
+ }),
+ ]),
+ });
+ const entry = entryByPid(await sampler.sample(), 801);
+ expect(entry).toMatchObject({
+ processCount: 1,
+ cpuPercent: 5,
+ memoryKb: 120,
+ });
+ });
+
+ it('OS 扫描按周期缓存:未过期不重扫,过期后重扫', async () => {
+ const { state, sampler } = makeHarness();
+ await sampler.sample();
+ expect(state.scanCalls).toBe(1);
+ state.nowMs += 2_000; // 未过期
+ await sampler.sample();
+ expect(state.scanCalls).toBe(1);
+ state.nowMs += 5_000; // 过期
+ await sampler.sample();
+ expect(state.scanCalls).toBe(2);
+ });
+
+ it('Windows CPU 差分:首个样本 0,第二个样本按累计时间差算百分比', async () => {
+ const { state, sampler } = makeHarness({
+ snapshot: snapshotOf([
+ osRow({ pid: 700, ppid: SELF_PID, cmdLineLower: 'codex-marker', cpuPercent: null, cpuTimeMs: 1_000, memoryKb: 10 }),
+ ]),
+ });
+ const first = await sampler.sample();
+ expect(entryByPid(first, 700)?.cpuPercent).toBe(0);
+
+ state.nowMs += 5_000;
+ state.snapshot = snapshotOf([
+ osRow({ pid: 700, ppid: SELF_PID, cmdLineLower: 'codex-marker', cpuPercent: null, cpuTimeMs: 2_500, memoryKb: 10 }),
+ ]);
+ const second = await sampler.sample();
+ // Δcpu 1500ms / Δwall 5000ms = 30%
+ expect(entryByPid(second, 700)?.cpuPercent).toBe(30);
+ });
+
+ it('Windows 同一 pid 的出生身份变化时重置 CPU 差分基线', async () => {
+ const { state, sampler } = makeHarness({
+ snapshot: snapshotOf([
+ osRow({
+ pid: 710,
+ ppid: SELF_PID,
+ cmdLineLower: 'claude-marker',
+ cpuPercent: null,
+ cpuTimeMs: 8_000,
+ startIdentity: 'start:old',
+ }),
+ ]),
+ });
+ await sampler.sample();
+
+ state.nowMs += 5_000;
+ state.snapshot = snapshotOf([
+ osRow({
+ pid: 710,
+ ppid: SELF_PID,
+ cmdLineLower: 'claude-marker',
+ cpuPercent: null,
+ cpuTimeMs: 500,
+ startIdentity: 'start:new',
+ }),
+ ]);
+ expect(entryByPid(await sampler.sample(), 710)?.cpuPercent).toBe(0);
+ });
+
+ it('OS 扫描失败降级为无 agent 条目,Chromium 部分照常且失败被记录', async () => {
+ const { sampler, log } = makeHarness({
+ metrics: [metric({ pid: 100, type: 'Browser' })],
+ deps: { scanOsProcesses: () => Promise.reject(new Error('ps blew up')) },
+ });
+ const sample = await sampler.sample();
+ expect(sample.entries).toHaveLength(1);
+ expect(entryByPid(sample, 100)?.kind).toBe('main');
+ expect(log.warn).toHaveBeenCalledWith(
+ 'process monitor os scan failed',
+ expect.objectContaining({ error: 'ps blew up' }),
+ );
+ });
+});
diff --git a/apps/desktop/src/main/process-monitor/agent-scan.ts b/apps/desktop/src/main/process-monitor/agent-scan.ts
new file mode 100644
index 0000000000..8595981cbb
--- /dev/null
+++ b/apps/desktop/src/main/process-monitor/agent-scan.ts
@@ -0,0 +1,278 @@
+/**
+ * process-monitor/agent-scan —— 「资源用量」面板的 OS 级进程枚举。
+ *
+ * 为什么不复用 agent-process-priority 的扫描:那边只要 pid/kind(调优先级),
+ * 这边还要 CPU / 内存与全局 PPID→children 图(树聚合 + 杀树校验),且要认 pi
+ * (优先级 watcher 有意不管 pi,直接改它的 classify 会顺带改变调档行为)。
+ * marker 策略与安全边界与 agent-process-priority / claude-orphan-reaper 完全
+ * 一致:只认「ppid == 本进程 且命令行命中本产品二进制路径 marker」的进程。
+ *
+ * 平台差异:
+ * - POSIX:一次 `ps -Awwo pid,ppid,stat,%cpu,rss,lstart,command`。%cpu 是 ps 的近期均值
+ * (macOS 为衰减平均),rss 单位 KB。
+ * - Windows:一次 Win32_Process 全表。WorkingSetSize 单位字节;CPU 没有现成
+ * 百分比,取 UserModeTime+KernelModeTime(100ns)累计值,由 sampler 用两次
+ * 采样差分算百分比。
+ */
+
+import { execFile, execFileSync } from 'node:child_process';
+import { promisify } from 'node:util';
+
+import { allUserDataDirNames } from '@cindy/maker-shared/brand-identity';
+
+import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
+import { classifyAgentCommandLine } from '../agent-process-priority.js';
+
+const execFileAsync = promisify(execFile);
+
+export type MonitoredAgentKind = 'claude' | 'codex' | 'pi';
+
+export interface OsProcessRow {
+ pid: number;
+ ppid: number;
+ /** POSIX ps stat(如 R/S/T/Z);Windows 为 null。 */
+ state: string | null;
+ /** 小写命令行(仅 main 内部用于 marker 匹配,绝不出 IPC)。 */
+ cmdLineLower: string;
+ memoryKb: number;
+ /** POSIX:ps 报告的 %cpu;Windows 为 null(用 cpuTimeMs 差分)。 */
+ cpuPercent: number | null;
+ /** Windows:UserModeTime+KernelModeTime 累计(ms);POSIX 为 null。 */
+ cpuTimeMs: number | null;
+ /**
+ * OS 进程出生提示;Windows 为 CreationDate ticks,POSIX lstart 仅精确到秒。
+ * 只用于同步扫描内的树冻结复核/CPU 差分,不得作为 renderer 终止授权 token。
+ */
+ startIdentity: string | null;
+}
+
+export interface OsProcessSnapshot {
+ rows: OsProcessRow[];
+ childrenByParent: Map<number, number[]>;
+}
+
+/**
+ * pi 二进制路径 marker(与 claude/codex 的 marker 同构):生产二进制安装在
+ * `<userData>/pi/<version>/`,dev/sandbox 则从仓库 `apps/pi-bin/` 启动。
+ */
+export function buildPiPathMarkers(dirNames: readonly string[]): string[] {
+ return [
+ 'apps\\pi-bin\\',
+ 'apps/pi-bin/',
+ ...dirNames.flatMap((dirName) => {
+ const dir = dirName.toLowerCase();
+ return [
+ `appdata\\roaming\\${dir}\\pi\\`,
+ `appdata/roaming/${dir}/pi/`,
+ `/library/application support/${dir}/pi/`,
+ `/.config/${dir}/pi/`,
+ ];
+ }),
+ ];
+}
+
+const PI_MARKERS = buildPiPathMarkers(allUserDataDirNames(CURRENT_CINDY_REGION));
+
+/**
+ * 运行时 userData 派生的 pi marker(XDG_CONFIG_HOME / --user-data-dir 重定向
+ * 场景,与 agent-process-priority.registerUserDataMarkers 同理)。claude/codex
+ * 的运行时 marker 由那边的注册函数维护,这里只补 pi 自己的。
+ */
+let runtimePiMarkers: string[] = [];
+
+export function registerPiUserDataMarkers(userDataPath: string): void {
+ const lower = userDataPath.trim().toLowerCase();
+ if (!lower) {
+ runtimePiMarkers = [];
+ return;
+ }
+ const variants = new Set([lower.replace(/\\/g, '/'), lower.replace(/\//g, '\\')]);
+ runtimePiMarkers = [...variants].map((v) => {
+ const sep = v.includes('\\') ? '\\' : '/';
+ return `${v}${sep}pi${sep}`;
+ });
+}
+
+/** 命令行(已小写)→ 受监视的 agent 种类;不命中 = 不是我们的 agent 进程。 */
+export function classifyMonitoredAgentCommandLine(
+ cmdLineLower: string,
+): MonitoredAgentKind | null {
+ const base = classifyAgentCommandLine(cmdLineLower);
+ if (base) return base;
+ if (
+ PI_MARKERS.some((m) => cmdLineLower.includes(m)) ||
+ runtimePiMarkers.some((m) => cmdLineLower.includes(m))
+ ) {
+ return 'pi';
+ }
+ return null;
+}
+
+// ps 行:pid ppid stat %cpu rss lstart command(command 可含空格,贪婪吃尾)。
+// LC_ALL=C 把 lstart 固定为 "Mon Aug 6 12:34:56 2026" 一类格式。
+const POSIX_PS_ROW_RE =
+ /^(\d+)\s+(\d+)\s+(\S+)\s+([\d.]+)\s+(\d+)\s+(\S+\s+\S+\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4})\s+(.+)$/;
+
+const POSIX_PS_ARGS = ['-Aww', '-o', 'pid=,ppid=,stat=,%cpu=,rss=,lstart=,command='];
+
+const WINDOWS_PROCESS_SCAN_SCRIPT = [
+ 'Get-CimInstance Win32_Process |',
+ 'ForEach-Object {',
+ ' $cmd = ([string]$_.CommandLine) -replace "`r|`n", " "',
+ ' $created = if ($null -eq $_.CreationDate) { "" } else { $_.CreationDate.ToUniversalTime().Ticks }',
+ ' Write-Output ("{0}|{1}|{2}|{3}|{4}|{5}" -f $_.ProcessId, $_.ParentProcessId, $_.WorkingSetSize, ($_.UserModeTime + $_.KernelModeTime), $created, $cmd)',
+ '}',
+].join('\n');
+
+/** lstart 不携带时区;固定 UTC,避免 DST 回拨时一小时内出现重复出生字符串。 */
+export function buildPosixProcessScanEnv(baseEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
+ return { ...baseEnv, LC_ALL: 'C', TZ: 'UTC0' };
+}
+
+export function parsePosixProcessTable(psOutput: string): OsProcessRow[] {
+ const rows: OsProcessRow[] = [];
+ for (const raw of psOutput.split(/\r?\n/)) {
+ const line = raw.trim();
+ if (!line) continue;
+ const match = line.match(POSIX_PS_ROW_RE);
+ if (!match) continue;
+ const pid = Number.parseInt(match[1], 10);
+ const ppid = Number.parseInt(match[2], 10);
+ const cpuPercent = Number.parseFloat(match[4]);
+ const rssKb = Number.parseInt(match[5], 10);
+ if (!Number.isFinite(pid) || !Number.isFinite(ppid)) continue;
+ rows.push({
+ pid,
+ ppid,
+ state: match[3],
+ cmdLineLower: match[7].toLowerCase(),
+ memoryKb: Number.isFinite(rssKb) ? rssKb : 0,
+ cpuPercent: Number.isFinite(cpuPercent) ? cpuPercent : 0,
+ cpuTimeMs: null,
+ startIdentity: match[6].replace(/\s+/g, ' '),
+ });
+ }
+ return rows;
+}
+
+/** Windows 行:pid|ppid|workingSetBytes|cpuTime100ns|creationTicks|cmdline(cmdline 可含 |)。 */
+export function parseWindowsProcessTable(stdout: string): OsProcessRow[] {
+ const rows: OsProcessRow[] = [];
+ for (const raw of stdout.split(/\r?\n/)) {
+ const line = raw.trim();
+ if (!line) continue;
+ const parts = line.split('|');
+ if (parts.length < 6) continue;
+ const pid = Number.parseInt(parts[0]?.trim() ?? '', 10);
+ const ppid = Number.parseInt(parts[1]?.trim() ?? '', 10);
+ const workingSetBytes = Number.parseInt(parts[2]?.trim() ?? '', 10);
+ const cpuTime100ns = Number.parseInt(parts[3]?.trim() ?? '', 10);
+ if (!Number.isFinite(pid) || !Number.isFinite(ppid)) continue;
+ rows.push({
+ pid,
+ ppid,
+ state: null,
+ cmdLineLower: parts.slice(5).join('|').toLowerCase(),
+ memoryKb: Number.isFinite(workingSetBytes) ? Math.round(workingSetBytes / 1024) : 0,
+ cpuPercent: null,
+ cpuTimeMs: Number.isFinite(cpuTime100ns) ? cpuTime100ns / 10_000 : null,
+ startIdentity: parts[4]?.trim() || null,
+ });
+ }
+ return rows;
+}
+
+export function buildChildrenByParent(rows: readonly OsProcessRow[]): Map<number, number[]> {
+ const childrenByParent = new Map<number, number[]>();
+ for (const row of rows) {
+ const siblings = childrenByParent.get(row.ppid);
+ if (siblings) siblings.push(row.pid);
+ else childrenByParent.set(row.ppid, [row.pid]);
+ }
+ return childrenByParent;
+}
+
+/** 从 childrenByParent 展开一棵子树(含根;防环)。 */
+export function collectDescendantPids(
+ rootPid: number,
+ childrenByParent: Map<number, number[]>,
+): number[] {
+ const out: number[] = [];
+ const seen = new Set<number>();
+ const stack: number[] = [rootPid];
+ while (stack.length > 0) {
+ const cur = stack.pop()!;
+ if (seen.has(cur)) continue;
+ seen.add(cur);
+ out.push(cur);
+ const kids = childrenByParent.get(cur);
+ if (kids) for (const k of kids) stack.push(k);
+ }
+ return out;
+}
+
+async function scanPosix(): Promise<OsProcessSnapshot> {
+ // -ww:macOS ps 默认按显示宽度截断 command,截掉 marker 会静默漏认
+ // (与 agent-process-priority 同一个坑)。
+ const { stdout } = await execFileAsync(
+ 'ps',
+ POSIX_PS_ARGS,
+ {
+ encoding: 'utf8',
+ timeout: 5_000,
+ maxBuffer: 8 * 1024 * 1024,
+ env: buildPosixProcessScanEnv(process.env),
+ },
+ );
+ const rows = parsePosixProcessTable(stdout);
+ return { rows, childrenByParent: buildChildrenByParent(rows) };
+}
+
+async function scanWindows(): Promise<OsProcessSnapshot> {
+ // 全表(无 Name filter):agent 树里的 bash/node 子孙也要计入聚合。
+ // 行尾管道符不可省 —— 否则两条语句独立执行、parse 恒 0 行
+ // (claude-orphan-reaper 2026-07-14 实锤的坑)。
+ const { stdout } = await execFileAsync(
+ 'powershell.exe',
+ ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_PROCESS_SCAN_SCRIPT],
+ { encoding: 'utf8', timeout: 10_000, windowsHide: true, maxBuffer: 8 * 1024 * 1024 },
+ );
+ const rows = parseWindowsProcessTable(stdout);
+ return { rows, childrenByParent: buildChildrenByParent(rows) };
+}
+
+/** 生产扫描入口(sampler / terminate 校验共用)。 */
+export function scanOsProcesses(): Promise<OsProcessSnapshot> {
+ return process.platform === 'win32' ? scanWindows() : scanPosix();
+}
+
+/**
+ * 终止前的同步扫描。调用方必须从本函数返回起到同步 kill 完成前不让出事件循环,
+ * 这样 main 持有的直属子进程不会在校验后被回收并复用根 pid。
+ */
+export function scanOsProcessesSync(): OsProcessSnapshot {
+ let stdout: string;
+ if (process.platform === 'win32') {
+ stdout = execFileSync(
+ 'powershell.exe',
+ ['-NoProfile', '-NonInteractive', '-Command', WINDOWS_PROCESS_SCAN_SCRIPT],
+ {
+ encoding: 'utf8',
+ timeout: 10_000,
+ windowsHide: true,
+ maxBuffer: 8 * 1024 * 1024,
+ },
+ );
+ const rows = parseWindowsProcessTable(stdout);
+ return { rows, childrenByParent: buildChildrenByParent(rows) };
+ }
+
+ stdout = execFileSync('ps', POSIX_PS_ARGS, {
+ encoding: 'utf8',
+ timeout: 5_000,
+ maxBuffer: 8 * 1024 * 1024,
+ env: buildPosixProcessScanEnv(process.env),
+ });
+ const rows = parsePosixProcessTable(stdout);
+ return { rows, childrenByParent: buildChildrenByParent(rows) };
+}
diff --git a/apps/desktop/src/main/process-monitor/codex-process-registry.ts b/apps/desktop/src/main/process-monitor/codex-process-registry.ts
new file mode 100644
index 0000000000..3139aae565
--- /dev/null
+++ b/apps/desktop/src/main/process-monitor/codex-process-registry.ts
@@ -0,0 +1,67 @@
+/**
+ * Codex 本地 app-server 的 PID → 职责注册表。
+ *
+ * 职责来自 maker-core 创建 host 时已经确定的 hostPurpose,不从命令行、proxy
+ * endpoint 或凭据模式反推。注册表只驻留 main 内存;renderer 只收到共享契约里的
+ * 枚举,不会看到内部 host key、URL 或启动参数。
+ */
+
+import { randomUUID } from 'node:crypto';
+
+import type { AgentProcessRole } from '../../shared/processMonitor.js';
+import type { MonitoredAgentKind } from './agent-scan.js';
+
+interface Registration {
+ kind: MonitoredAgentKind;
+ role: AgentProcessRole;
+ instanceId: string;
+ identity: symbol;
+}
+
+const registrations = new Map<number, Registration>();
+
+export interface AgentProcessRegistration {
+ kind: MonitoredAgentKind;
+ role: AgentProcessRole;
+ instanceId: string;
+}
+
+export function registerAgentProcess(
+ pid: number,
+ kind: MonitoredAgentKind,
+ role: AgentProcessRole,
+): () => void {
+ const identity = Symbol(`${kind}-process-${pid}`);
+ registrations.set(pid, { kind, role, instanceId: randomUUID(), identity });
+ let disposed = false;
+ return () => {
+ if (disposed) return;
+ disposed = true;
+ // PID 可能已被复用并重新登记;旧 disposer 不能删掉新进程的职责。
+ if (registrations.get(pid)?.identity === identity) registrations.delete(pid);
+ };
+}
+
+export function registerCodexProcessRole(pid: number, role: AgentProcessRole): () => void {
+ return registerAgentProcess(pid, 'codex', role);
+}
+
+export function resolveAgentProcessRegistration(pid: number): AgentProcessRegistration | null {
+ const registration = registrations.get(pid);
+ if (!registration) return null;
+ return {
+ kind: registration.kind,
+ role: registration.role,
+ instanceId: registration.instanceId,
+ };
+}
+
+export function resolveCodexProcessRole(pid: number): AgentProcessRole | null {
+ const registration = registrations.get(pid);
+ return registration?.kind === 'codex' ? registration.role : null;
+}
+
+/** 仅测试用。 */
+export function _resetCodexProcessRegistryForTests(): void {
+ registrations.clear();
+}
diff --git a/apps/desktop/src/main/process-monitor/ipc.ts b/apps/desktop/src/main/process-monitor/ipc.ts
new file mode 100644
index 0000000000..c2616bd08f
--- /dev/null
+++ b/apps/desktop/src/main/process-monitor/ipc.ts
@@ -0,0 +1,306 @@
+/**
+ * process-monitor/ipc —— 「资源用量」面板的 IPC 面(main 侧)。
+ *
+ * 授权边界:
+ * - 所有 handler 首行 assertTrustedAppRendererEvent —— 进程信息与终止能力只
+ * 对 Cindy 自有顶层 renderer 开放,WebView / Ghost 一律拒绝。
+ * - 出站推送同样设闸:采样快照带页面标题(用户内容),只发给仍然可信的
+ * 订阅窗口(trustedAppRenderer 的出站口径)。
+ * - terminate 不信 renderer 传来的 pid 归属:执行前重新扫描,pid 必须命中
+ * 「ppid == 本进程 且命令行带本产品 marker」的 agent 根进程,否则拒绝 ——
+ * 绝不做任意进程杀手。
+ *
+ * 采样只在有订阅者(面板打开)时进行:subscribe 起 interval(unref,不拖
+ * 退出),订阅清零即停,无需 onQuit 挂钩。
+ */
+
+import { BrowserWindow, app, ipcMain, webContents, type WebContents } from 'electron';
+
+import {
+ PROCESS_MONITOR_SAMPLE_CHANNEL,
+ PROCESS_MONITOR_SUBSCRIBE_CHANNEL,
+ PROCESS_MONITOR_TERMINATE_CHANNEL,
+ PROCESS_MONITOR_UNSUBSCRIBE_CHANNEL,
+ type TerminateAgentProcessResult,
+} from '../../shared/processMonitor.js';
+import { registerUserDataMarkers } from '../agent-process-priority.js';
+import { killProcessTree } from '../claude-orphan-reaper.js';
+import { createLogger } from '../logger';
+import {
+ assertTrustedAppRendererEvent,
+ isTrustedAppRendererWindow,
+} from '../security/trustedAppRenderer.js';
+import {
+ requireNonNegativeInt,
+ requireObject,
+ requireString,
+ throwIpcError,
+} from '../utils/ipcValidate.js';
+import {
+ classifyMonitoredAgentCommandLine,
+ registerPiUserDataMarkers,
+ scanOsProcesses,
+ scanOsProcessesSync,
+ type MonitoredAgentKind,
+ type OsProcessSnapshot,
+} from './agent-scan.js';
+import {
+ resolveAgentProcessRegistration,
+ type AgentProcessRegistration,
+} from './codex-process-registry.js';
+import { terminateSafePosixProcessTree } from './safe-posix-process-tree.js';
+import {
+ createProcessMonitorSampler,
+ type ProcessMonitorSampler,
+} from './sampler.js';
+
+/** 推送周期。2s 对「看资源用量」够实时,采样本身(getAppMetrics)开销可忽略。 */
+export const SAMPLE_INTERVAL_MS = 2_000;
+
+interface IpcLogger {
+ info(message: string, meta?: Record<string, unknown>): void;
+ warn(message: string, meta?: Record<string, unknown>): void;
+}
+
+/** 依赖全部可注入(测试用);生产走缺省实现。 */
+export interface ProcessMonitorIpcOptions {
+ sampler?: ProcessMonitorSampler;
+ /** terminate 校验用的**新鲜**扫描(不走 sampler 缓存)。 */
+ scanOsProcessesSync?: () => OsProcessSnapshot;
+ /** sampler 的异步 OS 扫描。 */
+ scanOsProcesses?: () => Promise<OsProcessSnapshot>;
+ classify?: (cmdLineLower: string) => MonitoredAgentKind | null;
+ resolveAgentProcessRegistration?: (pid: number) => AgentProcessRegistration | null;
+ killProcessTree?: (pid: number, childrenByParent: Map<number, number[]>) => boolean;
+ signalProcess?: (pid: number, signal: NodeJS.Signals) => void;
+ /** 仅用于显式分流 Windows taskkill 与 POSIX 冻结终止;测试可注入。 */
+ platform?: NodeJS.Platform;
+ selfPid?: number;
+ sampleIntervalMs?: number;
+ log?: IpcLogger;
+}
+
+let registered = false;
+
+export function registerProcessMonitorIpc(opts: ProcessMonitorIpcOptions = {}): void {
+ if (registered) return;
+ registered = true;
+
+ const log = opts.log ?? createLogger('process-monitor');
+ const selfPid = opts.selfPid ?? process.pid;
+ const classify = opts.classify ?? classifyMonitoredAgentCommandLine;
+ const resolveAgentRegistration =
+ opts.resolveAgentProcessRegistration ?? resolveAgentProcessRegistration;
+ const sampleScan = opts.scanOsProcesses ?? scanOsProcesses;
+ const ownershipScanSync = opts.scanOsProcessesSync ?? scanOsProcessesSync;
+ const killTree = opts.killProcessTree ?? killProcessTree;
+ const signalProcess =
+ opts.signalProcess ??
+ ((pid: number, signal: NodeJS.Signals) => {
+ process.kill(pid, signal);
+ });
+ const platform = opts.platform ?? process.platform;
+ const sampleIntervalMs = opts.sampleIntervalMs ?? SAMPLE_INTERVAL_MS;
+
+ if (!opts.sampler) {
+ // 运行时 userData 可被重定向(XDG_CONFIG_HOME / --user-data-dir),静态品牌
+ // marker 会整体失配 —— 补一组实际路径派生的 marker,失败降级为静态 marker。
+ try {
+ const userData = app.getPath('userData');
+ registerUserDataMarkers(userData);
+ registerPiUserDataMarkers(userData);
+ } catch (err) {
+ log.warn('userData marker registration failed; static brand markers only', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+
+ const sampler =
+ opts.sampler ??
+ createProcessMonitorSampler({
+ getMetrics: () => app.getAppMetrics(),
+ scanOsProcesses: sampleScan,
+ describeRendererProcess: describeRendererProcessByPid,
+ classify,
+ resolveAgentProcessRegistration: resolveAgentRegistration,
+ selfPid,
+ log,
+ });
+
+ const subscribers = new Set<WebContents>();
+ const destroyListeners = new WeakMap<WebContents, () => void>();
+ let timer: ReturnType<typeof setInterval> | null = null;
+ let sampling = false;
+
+ function dropSubscriber(wc: WebContents): void {
+ subscribers.delete(wc);
+ const destroyListener = destroyListeners.get(wc);
+ if (destroyListener) {
+ wc.removeListener('destroyed', destroyListener);
+ destroyListeners.delete(wc);
+ }
+ if (subscribers.size === 0 && timer) {
+ clearInterval(timer);
+ timer = null;
+ }
+ }
+
+ async function tick(): Promise<void> {
+ if (sampling || subscribers.size === 0) return; // 采样慢于周期时跳过,不排队叠加
+ sampling = true;
+ try {
+ const sample = await sampler.sample();
+ for (const wc of [...subscribers]) {
+ if (wc.isDestroyed()) {
+ dropSubscriber(wc);
+ continue;
+ }
+ // 出站闸:快照含页面标题(用户内容),窗口导航离开 Cindy 页面后不再推。
+ if (!isTrustedAppRendererWindow(BrowserWindow.fromWebContents(wc))) {
+ dropSubscriber(wc);
+ continue;
+ }
+ try {
+ wc.send(PROCESS_MONITOR_SAMPLE_CHANNEL, sample);
+ } catch {
+ // 窗口可能在枚举与 send 之间被销毁。
+ }
+ }
+ } catch (err) {
+ log.warn('process monitor sample failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ } finally {
+ sampling = false;
+ }
+ }
+
+ ipcMain.handle(PROCESS_MONITOR_SUBSCRIBE_CHANNEL, (event) => {
+ assertTrustedAppRendererEvent(event);
+ const wc = event.sender;
+ if (!subscribers.has(wc)) {
+ const destroyListener = () => dropSubscriber(wc);
+ subscribers.add(wc);
+ destroyListeners.set(wc, destroyListener);
+ wc.once('destroyed', destroyListener);
+ }
+ if (!timer) {
+ timer = setInterval(() => {
+ void tick();
+ }, sampleIntervalMs);
+ timer.unref?.();
+ }
+ void tick(); // 面板打开立即出首帧,不等第一个周期
+ });
+
+ ipcMain.handle(PROCESS_MONITOR_UNSUBSCRIBE_CHANNEL, (event) => {
+ assertTrustedAppRendererEvent(event);
+ dropSubscriber(event.sender);
+ });
+
+ ipcMain.handle(PROCESS_MONITOR_TERMINATE_CHANNEL, (event, rawRequest: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const request = requireObject(rawRequest, 'request');
+ const pid = requireNonNegativeInt(request.pid, 'pid');
+ const processInstanceId = requireString(request.processInstanceId, 'processInstanceId');
+ if (pid === selfPid || pid === 0) {
+ throwIpcError('INVALID_PARAMS', 'pid is not a terminable process');
+ }
+ // 归属校验用新鲜扫描:renderer 手里的快照可能已过期(进程退出、pid 复用)。
+ let snapshot: OsProcessSnapshot;
+ try {
+ snapshot = ownershipScanSync();
+ } catch (err) {
+ log.warn('process monitor ownership scan failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ throwIpcError('INTERNAL', 'failed to inspect process ownership');
+ }
+ const row = snapshot.rows.find((r) => r.pid === pid);
+ const kind = row && row.ppid === selfPid ? classify(row.cmdLineLower) : null;
+ const registration = row ? resolveAgentRegistration(row.pid) : null;
+ if (
+ !row ||
+ row.ppid !== selfPid ||
+ !row.startIdentity ||
+ !kind ||
+ registration?.kind !== kind ||
+ registration.role !== 'task-host' ||
+ registration.instanceId !== processInstanceId
+ ) {
+ throwIpcError('NOT_FOUND', 'process is not an agent process owned by this app');
+ }
+ // registry 只收紧动作范围,不扩大授权;新鲜扫描 + PPID + marker 仍是首要边界。
+ // 随机 instanceId 绑定一次真实 spawn,消除 POSIX lstart 秒级碰撞导致的陈旧授权。
+ // 从同步扫描开始到终止完成之间不能 await/让出事件循环。Windows taskkill /T 由
+ // OS 展开当前树;POSIX 先暂停根,再逐层暂停后代。父进程暂停期间无法 reap 已退出
+ // 子进程,因此已枚举的 PID 不会被复用为无关进程。
+ if (platform === 'win32') {
+ if (!killTree(pid, new Map())) {
+ throwIpcError('INTERNAL', 'failed to terminate the agent process tree');
+ }
+ } else {
+ let terminationResult: ReturnType<typeof terminateSafePosixProcessTree>;
+ try {
+ terminationResult = terminateSafePosixProcessTree({
+ rootPid: pid,
+ rootStartIdentity: row.startIdentity,
+ rootStateBeforeStop: row.state,
+ scan: ownershipScanSync,
+ signal: signalProcess,
+ isExpectedRoot: (candidate) =>
+ candidate.ppid === selfPid &&
+ candidate.startIdentity === row.startIdentity &&
+ classify(candidate.cmdLineLower) === kind,
+ });
+ } catch (err) {
+ log.warn('process monitor POSIX tree termination failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ throwIpcError('INTERNAL', 'failed to terminate the agent process tree');
+ }
+ if (terminationResult === 'root-not-found') {
+ throwIpcError('NOT_FOUND', 'process is no longer an agent process owned by this app');
+ }
+ }
+ log.info('agent process tree terminated from resource usage panel', { pid, kind });
+ const result: TerminateAgentProcessResult = { pid, kind };
+ return result;
+ });
+}
+
+/**
+ * pid → renderer 展示标签:遍历现存 webContents 匹配 OS pid,取页面标题,
+ * 兜底 URL host。永不缓存 WebContents(与 TabRegistry 同一原则)。
+ * 同进程多页面(Chromium same-site 合并)取第一个命中的标题。
+ */
+function describeRendererProcessByPid(pid: number): string | null {
+ for (const wc of webContents.getAllWebContents()) {
+ try {
+ if (wc.isDestroyed() || wc.getOSProcessId() !== pid) continue;
+ const title = wc.getTitle();
+ if (title) return title;
+ const url = wc.getURL();
+ if (url) {
+ try {
+ return new URL(url).host || null;
+ } catch {
+ return null;
+ }
+ }
+ return null;
+ } catch {
+ // webContents 可能在枚举中途销毁;跳过继续。
+ }
+ }
+ return null;
+}
+
+/** 仅测试用:允许同一进程内重复注册。 */
+export function _resetProcessMonitorIpcForTests(): void {
+ registered = false;
+ ipcMain.removeHandler(PROCESS_MONITOR_SUBSCRIBE_CHANNEL);
+ ipcMain.removeHandler(PROCESS_MONITOR_UNSUBSCRIBE_CHANNEL);
+ ipcMain.removeHandler(PROCESS_MONITOR_TERMINATE_CHANNEL);
+}
diff --git a/apps/desktop/src/main/process-monitor/safe-posix-process-tree.ts b/apps/desktop/src/main/process-monitor/safe-posix-process-tree.ts
new file mode 100644
index 0000000000..3bae8517cf
--- /dev/null
+++ b/apps/desktop/src/main/process-monitor/safe-posix-process-tree.ts
@@ -0,0 +1,174 @@
+/**
+ * 安全终止 POSIX Agent 进程树。
+ *
+ * 普通 `ps` 快照不能直接拿来逐 PID kill:后代可能在扫描后退出并被父进程
+ * reap,原 PID 随后可被无关进程复用。这里先 SIGSTOP 已验证根进程,再按层
+ * 枚举并暂停直属子进程;每层必须由后续 ps stat 确认 T/Z 后才继续。父进程保持
+ * 暂停时,子进程即使退出也只能保持 zombie,PID 不会被回收复用;因此随后对
+ * 这批已冻结 PID 发 SIGKILL 不会越过归属边界。
+ */
+
+import type { OsProcessRow, OsProcessSnapshot } from './agent-scan.js';
+
+export type SafePosixTreeTerminationResult = 'terminated' | 'root-not-found';
+
+export interface SafePosixTreeTerminationOptions {
+ rootPid: number;
+ /** 终止请求重新扫描时确认的根进程出生身份。 */
+ rootStartIdentity: string;
+ rootStateBeforeStop: string | null;
+ scan(): OsProcessSnapshot;
+ signal(pid: number, signal: NodeJS.Signals): void;
+ isExpectedRoot(row: OsProcessRow): boolean;
+}
+
+function isMissingProcess(error: unknown): boolean {
+ return (error as NodeJS.ErrnoException)?.code === 'ESRCH';
+}
+
+function isPosixStoppedOrZombie(state: string | null): boolean {
+ return state != null && /^[TZ]/.test(state);
+}
+
+function resumeStoppedProcesses(
+ stoppedPids: readonly number[],
+ signal: SafePosixTreeTerminationOptions['signal'],
+): unknown[] {
+ const errors: unknown[] = [];
+ for (let index = stoppedPids.length - 1; index >= 0; index -= 1) {
+ try {
+ signal(stoppedPids[index]!, 'SIGCONT');
+ } catch (error) {
+ if (!isMissingProcess(error)) errors.push(error);
+ }
+ }
+ return errors;
+}
+
+interface FrozenProcessIdentity {
+ pid: number;
+ ppid: number;
+ startIdentity: string;
+ root: boolean;
+}
+
+export function terminateSafePosixProcessTree(
+ opts: SafePosixTreeTerminationOptions,
+): SafePosixTreeTerminationResult {
+ const { rootPid, rootStartIdentity, rootStateBeforeStop, scan, signal, isExpectedRoot } = opts;
+ const stoppedPids: number[] = [];
+ const resumeOnFailurePids: number[] = [];
+ const seen = new Set<number>([rootPid]);
+ let completed = false;
+ let result: SafePosixTreeTerminationResult | undefined;
+ let primaryError: unknown;
+ let failed = false;
+
+ const execute = (): SafePosixTreeTerminationResult => {
+ try {
+ signal(rootPid, 'SIGSTOP');
+ } catch (error) {
+ if (isMissingProcess(error)) return 'root-not-found';
+ throw error;
+ }
+ stoppedPids.push(rootPid);
+ if (!isPosixStoppedOrZombie(rootStateBeforeStop)) resumeOnFailurePids.push(rootPid);
+
+ let frontier: FrozenProcessIdentity[] = [
+ { pid: rootPid, ppid: -1, startIdentity: rootStartIdentity, root: true },
+ ];
+ while (frontier.length > 0) {
+ const snapshot = scan();
+ const rowsByPid = new Map(snapshot.rows.map((row) => [row.pid, row]));
+ const nextFrontier: FrozenProcessIdentity[] = [];
+
+ for (const expected of frontier) {
+ const current = rowsByPid.get(expected.pid);
+ if (expected.root && (!current || !isExpectedRoot(current))) {
+ // 复核时若根 PID 已是另一个出生身份,就不能再对该 PID 发 SIGCONT:
+ // SIGSTOP 可能命中的是随后退出的旧实例,而当前 PID 已属于未授权替代进程。
+ // 从恢复集合移除根 PID,保持失败关闭,避免跨越进程归属边界。
+ if (current && current.startIdentity !== expected.startIdentity) {
+ const recoveryIndex = resumeOnFailurePids.indexOf(rootPid);
+ if (recoveryIndex >= 0) resumeOnFailurePids.splice(recoveryIndex, 1);
+ }
+ return 'root-not-found';
+ }
+ if (
+ !current ||
+ (!expected.root &&
+ (current.ppid !== expected.ppid || current.startIdentity !== expected.startIdentity))
+ ) {
+ throw new Error(`stopped process identity changed before confirmation: ${expected.pid}`);
+ }
+ if (!isPosixStoppedOrZombie(current.state)) {
+ throw new Error(`process did not enter stopped state: ${expected.pid}`);
+ }
+ }
+
+ for (const parent of frontier) {
+ for (const childPid of snapshot.childrenByParent.get(parent.pid) ?? []) {
+ if (seen.has(childPid)) continue;
+ const child = rowsByPid.get(childPid);
+ if (!child || child.ppid !== parent.pid || !child.startIdentity) continue;
+
+ try {
+ signal(childPid, 'SIGSTOP');
+ } catch (error) {
+ if (isMissingProcess(error)) {
+ // 子进程可能在本次快照之后 fork 后代再退出;即使旧快照里没有
+ // 已知后代,也不能证明该分支已清空。父链失效后必须失败关闭,
+ // 由外层恢复已冻结进程,等待用户基于新鲜归属快照重试。
+ throw new Error(`process exited before its descendants could be frozen: ${childPid}`);
+ }
+ throw error;
+ }
+
+ seen.add(childPid);
+ stoppedPids.push(childPid);
+ if (!isPosixStoppedOrZombie(child.state)) resumeOnFailurePids.push(childPid);
+ nextFrontier.push({
+ pid: childPid,
+ ppid: parent.pid,
+ startIdentity: child.startIdentity,
+ root: false,
+ });
+ }
+ }
+
+ frontier = nextFrontier;
+ }
+
+ // 后代优先、根最后。所有目标仍处于 SIGSTOP,父链不会在 kill 过程中主动
+ // reap 子进程,因此不会出现“杀到一半 PID 被复用”的窗口。
+ for (let index = stoppedPids.length - 1; index >= 0; index -= 1) {
+ try {
+ signal(stoppedPids[index]!, 'SIGKILL');
+ } catch (error) {
+ if (!isMissingProcess(error)) throw error;
+ }
+ }
+
+ return 'terminated';
+ };
+
+ try {
+ result = execute();
+ completed = result === 'terminated';
+ } catch (error) {
+ failed = true;
+ primaryError = error;
+ }
+
+ if (!completed) {
+ const recoveryErrors = resumeStoppedProcesses(resumeOnFailurePids, signal);
+ if (recoveryErrors.length > 0) {
+ throw new AggregateError(
+ failed ? [primaryError, ...recoveryErrors] : recoveryErrors,
+ 'failed to recover stopped POSIX processes',
+ );
+ }
+ }
+ if (failed) throw primaryError;
+ return result!;
+}
diff --git a/apps/desktop/src/main/process-monitor/sampler.ts b/apps/desktop/src/main/process-monitor/sampler.ts
new file mode 100644
index 0000000000..d1e279e251
--- /dev/null
+++ b/apps/desktop/src/main/process-monitor/sampler.ts
@@ -0,0 +1,258 @@
+/**
+ * process-monitor/sampler —— 「资源用量」的采样合并逻辑(纯业务,依赖全注入,
+ * 不直接 import electron —— main 侧业务逻辑默认带单测,模式照
+ * rsb-browser-bridge/resource-watchdog.ts)。
+ *
+ * 两个数据源按 pid 合并:
+ * 1. app.getAppMetrics():Electron 自家进程(Browser/Tab/GPU/Utility ——
+ * 插件 Node 服务与 watcher-host 都是 Utility)。
+ * 2. OS 级扫描(agent-scan):claude/codex/pi 的 agent 根进程 + 全局 PPID 图,
+ * 每个根聚合整棵子树的 CPU / 内存(agent 干活的 bash / 测试 / MCP node
+ * 都在子树里,只报根进程会严重低估)。
+ *
+ * OS 扫描比 getAppMetrics 贵得多(Windows 冷启 powershell 1.5s+),用独立的
+ * 慢周期缓存:超龄才重扫,in-flight 共享,快 tick 之间复用上一次快照。
+ * Windows 的 CPU% 没有现成值,由两次快照的累计 CPU 时间差分得出(首个快照
+ * 报 0,第二个 tick 起有值)。
+ */
+
+import type {
+ ProcessMonitorSample,
+ ProcessUsageEntry,
+ ProcessUsageKind,
+} from '../../shared/processMonitor.js';
+import {
+ collectDescendantPids,
+ type MonitoredAgentKind,
+ type OsProcessRow,
+ type OsProcessSnapshot,
+} from './agent-scan.js';
+import type { AgentProcessRegistration } from './codex-process-registry.js';
+
+/** app.getAppMetrics() 返回项的最小子集。memory.workingSetSize 单位是 KB。 */
+export interface ChromiumProcessMetric {
+ pid: number;
+ type: string;
+ serviceName?: string;
+ name?: string;
+ cpu: { percentCPUUsage: number };
+ memory: { workingSetSize: number };
+}
+
+interface SamplerLogger {
+ warn(message: string, meta?: Record<string, unknown>): void;
+}
+
+export interface ProcessMonitorSamplerDeps {
+ /** app.getAppMetrics() —— 每次 sample 调一次,percentCPUUsage 即两次调用间均值。 */
+ getMetrics(): ChromiumProcessMetric[];
+ scanOsProcesses(): Promise<OsProcessSnapshot>;
+ /** pid → renderer 展示标签(webContents 标题);查不到返回 null。 */
+ describeRendererProcess(pid: number): string | null;
+ classify(cmdLineLower: string): MonitoredAgentKind | null;
+ /** 本地根进程的 spawn-generation 登记;未知时返回 null,并按不可终止处理。 */
+ resolveAgentProcessRegistration?(pid: number): AgentProcessRegistration | null;
+ selfPid: number;
+ log: SamplerLogger;
+ /** OS 扫描的最小间隔;快 tick 之间复用缓存。 */
+ osScanIntervalMs?: number;
+ /** 注入时钟(测试用;生产缺省 Date.now)。 */
+ now?: () => number;
+}
+
+/** OS 扫描缓存周期。5s 在「agent 树数据新鲜度」与「powershell 开销」间取平衡。 */
+export const OS_SCAN_INTERVAL_MS = 5_000;
+
+const AGENT_KIND_TO_USAGE_KIND: Record<MonitoredAgentKind, ProcessUsageKind> = {
+ claude: 'agent-claude',
+ codex: 'agent-codex',
+ pi: 'agent-pi',
+};
+
+export interface ProcessMonitorSampler {
+ sample(): Promise<ProcessMonitorSample>;
+}
+
+export function createProcessMonitorSampler(
+ deps: ProcessMonitorSamplerDeps,
+): ProcessMonitorSampler {
+ const osScanIntervalMs = deps.osScanIntervalMs ?? OS_SCAN_INTERVAL_MS;
+ const now = deps.now ?? Date.now;
+
+ let cachedSnapshot: OsProcessSnapshot = { rows: [], childrenByParent: new Map() };
+ let cachedAtMs = Number.NEGATIVE_INFINITY;
+ let scanInFlight: Promise<void> | null = null;
+ /** Windows CPU 差分账本:pid → 上一次**扫描**的累计 CPU 时间与时刻。 */
+ const prevCpuTimes = new Map<
+ number,
+ { cpuTimeMs: number; atMs: number; startIdentity: string | null }
+ >();
+ /**
+ * 扫描刷新时一次算好的 CPU%(仅 Windows 差分路径)。差分必须在扫描粒度做:
+ * 若放在每个快 tick 上,复用缓存快照时会拿扫描周期(5s)的 CPU 增量去除以
+ * tick 周期(2s)的墙钟窗口,百分比被高估 2.5 倍。
+ */
+ const computedCpuPercentByPid = new Map<number, number>();
+
+ function onSnapshotRefreshed(snapshot: OsProcessSnapshot, atMs: number): void {
+ cachedSnapshot = snapshot;
+ cachedAtMs = atMs;
+ const alive = new Set<number>();
+ for (const row of snapshot.rows) {
+ alive.add(row.pid);
+ if (row.cpuTimeMs == null) continue;
+ const prev = prevCpuTimes.get(row.pid);
+ prevCpuTimes.set(row.pid, {
+ cpuTimeMs: row.cpuTimeMs,
+ atMs,
+ startIdentity: row.startIdentity,
+ });
+ const percent =
+ prev &&
+ prev.startIdentity === row.startIdentity &&
+ atMs > prev.atMs &&
+ row.cpuTimeMs > prev.cpuTimeMs
+ ? ((row.cpuTimeMs - prev.cpuTimeMs) / (atMs - prev.atMs)) * 100
+ : 0;
+ computedCpuPercentByPid.set(row.pid, percent);
+ }
+ // 账本剪枝:退出的进程不永久占内存(pid 复用时也不会拿到陈旧差分基线)。
+ for (const pid of [...prevCpuTimes.keys()]) {
+ if (!alive.has(pid)) {
+ prevCpuTimes.delete(pid);
+ computedCpuPercentByPid.delete(pid);
+ }
+ }
+ }
+
+ async function refreshSnapshotIfStale(): Promise<void> {
+ if (now() - cachedAtMs < osScanIntervalMs) return;
+ if (!scanInFlight) {
+ scanInFlight = deps
+ .scanOsProcesses()
+ .then((snapshot) => {
+ onSnapshotRefreshed(snapshot, now());
+ })
+ .catch((err) => {
+ // 扫描失败降级为「本轮无 agent 条目」,Chromium 部分照常。缓存时间戳
+ // 也推进,避免每个快 tick 都重试昂贵的失败扫描。
+ onSnapshotRefreshed({ rows: [], childrenByParent: new Map() }, now());
+ deps.log.warn('process monitor os scan failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ })
+ .finally(() => {
+ scanInFlight = null;
+ });
+ }
+ await scanInFlight;
+ }
+
+ /** 单进程 CPU%:POSIX 直接用 ps 值;Windows 用扫描粒度的差分(首个快照 0)。 */
+ function rowCpuPercent(row: OsProcessRow): number {
+ if (row.cpuPercent != null) return row.cpuPercent;
+ return computedCpuPercentByPid.get(row.pid) ?? 0;
+ }
+
+ /** Windows 控制台宿主只是系统辅助进程,不应被用户误读成另一个 Agent 实例。 */
+ function isOsHelperProcess(row: OsProcessRow): boolean {
+ return /(?:^|[\\/])conhost\.exe(?:\s|$)/i.test(row.cmdLineLower);
+ }
+
+ function collectAgentEntries(): ProcessUsageEntry[] {
+ const { rows, childrenByParent } = cachedSnapshot;
+ const rowByPid = new Map(rows.map((r) => [r.pid, r]));
+ const entries: ProcessUsageEntry[] = [];
+ for (const row of rows) {
+ if (row.ppid !== deps.selfPid) continue;
+ const kind = deps.classify(row.cmdLineLower);
+ if (!kind) continue;
+ const registration = deps.resolveAgentProcessRegistration?.(row.pid) ?? null;
+ const registrationMatchesKind = registration?.kind === kind;
+ const registeredRole = registrationMatchesKind ? registration.role : null;
+ const agentRole = kind === 'codex' ? registeredRole : null;
+ let cpuPercent = 0;
+ let memoryKb = 0;
+ let processCount = 0;
+ for (const pid of collectDescendantPids(row.pid, childrenByParent)) {
+ const member = rowByPid.get(pid);
+ if (!member) continue;
+ cpuPercent += rowCpuPercent(member);
+ memoryKb += member.memoryKb;
+ if (!isOsHelperProcess(member)) processCount += 1;
+ }
+ const terminable =
+ row.startIdentity != null && registrationMatchesKind && registeredRole === 'task-host';
+ entries.push({
+ pid: row.pid,
+ kind: AGENT_KIND_TO_USAGE_KIND[kind],
+ label: null,
+ cpuPercent,
+ memoryKb,
+ processCount,
+ // 终止授权使用每次实际 spawn 的随机 generation,而不是秒级 POSIX lstart。
+ terminable,
+ ...(terminable && registration ? { processInstanceId: registration.instanceId } : {}),
+ ...(agentRole ? { agentRole } : {}),
+ });
+ }
+ return entries;
+ }
+
+ function chromiumKind(type: string): ProcessUsageKind {
+ switch (type) {
+ case 'Browser':
+ return 'main';
+ case 'Tab':
+ return 'renderer';
+ case 'GPU':
+ return 'gpu';
+ default:
+ return 'utility';
+ }
+ }
+
+ function collectChromiumEntries(agentPids: Set<number>): ProcessUsageEntry[] {
+ const entries: ProcessUsageEntry[] = [];
+ for (const metric of deps.getMetrics()) {
+ // 理论上 Chromium 进程不会出现在 agent 子树里;真撞了以 agent 聚合为准,
+ // 避免同一进程被计两遍。
+ if (agentPids.has(metric.pid)) continue;
+ const kind = chromiumKind(metric.type);
+ let label: string | null = null;
+ if (kind === 'renderer') {
+ label = deps.describeRendererProcess(metric.pid);
+ } else if (kind === 'utility') {
+ label = metric.serviceName || metric.name || null;
+ }
+ entries.push({
+ pid: metric.pid,
+ kind,
+ label,
+ cpuPercent: metric.cpu?.percentCPUUsage ?? 0,
+ memoryKb: metric.memory?.workingSetSize ?? 0,
+ processCount: 1,
+ terminable: false,
+ });
+ }
+ return entries;
+ }
+
+ return {
+ async sample(): Promise<ProcessMonitorSample> {
+ await refreshSnapshotIfStale();
+ const atMs = now();
+ const agentEntries = collectAgentEntries();
+ const agentPids = new Set<number>();
+ for (const entry of agentEntries) {
+ for (const pid of collectDescendantPids(entry.pid, cachedSnapshot.childrenByParent)) {
+ agentPids.add(pid);
+ }
+ }
+ return {
+ capturedAtMs: atMs,
+ entries: [...collectChromiumEntries(agentPids), ...agentEntries],
+ };
+ },
+ };
+}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index eaf3970d67..90372940ff 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -37,6 +37,15 @@ import {
type LogUploadSettingsPayload,
} from '../shared/logUpload';
import { SELECTION_CONTEXT_MENU_ADD_TO_CHAT_CHANNEL } from '../shared/selectionContextMenu';
+import {
+ PROCESS_MONITOR_SAMPLE_CHANNEL,
+ PROCESS_MONITOR_SUBSCRIBE_CHANNEL,
+ PROCESS_MONITOR_TERMINATE_CHANNEL,
+ PROCESS_MONITOR_UNSUBSCRIBE_CHANNEL,
+ type ProcessMonitorSample,
+ type TerminateAgentProcessRequest,
+ type TerminateAgentProcessResult,
+} from '../shared/processMonitor';
import { SESSION_ATTENTION_CLEARED_CHANNEL } from '../shared/sessionAttention';
import { VOICE_INPUT_POWER_STATE_CHANNEL } from '../shared/voiceInputPowerIpc';
import {
@@ -420,6 +429,8 @@ const fanOutRsbBrowserCommand = createIpcFanOut('rsb:browser-command');
const fanOutRsbBrowserBridgePin = createIpcFanOut('rsb-browser-bridge:pin');
const fanOutRsbBrowserBridgeUnpin = createIpcFanOut('rsb-browser-bridge:unpin');
const fanOutRsbBrowserBridgeResourceEvent = createIpcFanOut('rsb-browser-bridge:resource-event');
+// 资源用量面板:main 订阅驱动采样推送(面板打开才有流量)。
+const fanOutProcessMonitorSample = createIpcFanOut(PROCESS_MONITOR_SAMPLE_CHANNEL);
// Phase 3: RsbWebviewBackend (open/focus/close) push 给 renderer 让它代调 store。
const fanOutRsbBrowserBridgeTabOpRequest = createIpcFanOut('rsb-browser-bridge:tab-op-request');
// session-git-pr-context: HEAD 分支变化 / session PR 引用变化推送
@@ -4651,6 +4662,20 @@ contextBridge.exposeInMainWorld('electronAPI', {
fanOutRsbBrowserBridgeResourceEvent(cb as IpcCallback),
},
+ // ── 资源用量面板(process-monitor)────────────────────────────────────────
+ /**
+ * 订阅期间 main 才采样(面板关闭零开销);onSample 回调只收业务 payload。
+ * terminate 只对本产品 spawn 的 agent 根进程有效,归属由 main 重新校验。
+ */
+ processMonitor: {
+ subscribe: (): Promise<void> => ipcRenderer.invoke(PROCESS_MONITOR_SUBSCRIBE_CHANNEL),
+ unsubscribe: (): Promise<void> => ipcRenderer.invoke(PROCESS_MONITOR_UNSUBSCRIBE_CHANNEL),
+ terminate: (request: TerminateAgentProcessRequest): Promise<TerminateAgentProcessResult> =>
+ ipcRenderer.invoke(PROCESS_MONITOR_TERMINATE_CHANNEL, request),
+ onSample: (cb: (sample: ProcessMonitorSample) => void) =>
+ fanOutProcessMonitorSample(cb as IpcCallback),
+ },
+
rsbNativePopup: {
claim: (input: RsbNativePopupClaimInput): Promise<RsbNativePopupClaimResult> =>
ipcRenderer.invoke(RSB_NATIVE_POPUP_CLAIM_CHANNEL, input),
diff --git a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
index 81d97f5bef..560859a381 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/AddTabDropdown.tsx
@@ -15,7 +15,7 @@
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
-import { FileDiff, FolderTree, Globe, ListTodo, Terminal } from 'lucide-react';
+import { Activity, FileDiff, FolderTree, Globe, ListTodo, Terminal } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { TabKindId, TabKindMenuMeta } from './types';
@@ -66,6 +66,14 @@ const MENU_ITEMS: TabKindMenuMeta[] = [
enabled: true,
singleton: true,
},
+ {
+ kind: 'resource-usage',
+ labelKey: 'rightSidebar.tabs.kinds.resourceUsage',
+ icon: Activity,
+ order: 18,
+ enabled: true,
+ singleton: true,
+ },
{
kind: 'web-browser',
labelKey: 'rightSidebar.tabs.kinds.browser',
diff --git a/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx b/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx
index 203452d35f..4fcd04491e 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/EmptyState.tsx
@@ -9,7 +9,15 @@
* 插件页独占承载,入口只在 /plugins。
*/
-import { ChevronRight, FileDiff, FolderOpen, Globe, ListTodo, Terminal } from 'lucide-react';
+import {
+ Activity,
+ ChevronRight,
+ FileDiff,
+ FolderOpen,
+ Globe,
+ ListTodo,
+ Terminal,
+} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
@@ -20,6 +28,7 @@ interface EmptyStateProps {
onAddTerminalTab: () => void;
onAddReviewTab: () => void;
onAddBackgroundTasksTab: () => void;
+ onAddResourceUsageTab: () => void;
}
export function EmptyState({
@@ -28,10 +37,11 @@ export function EmptyState({
onAddTerminalTab,
onAddReviewTab,
onAddBackgroundTasksTab,
+ onAddResourceUsageTab,
}: EmptyStateProps) {
const { t } = useTranslation();
return (
- <div className="flex flex-1 flex-col items-start gap-8 px-10 pb-8 pt-16">
+ <div className="flex min-h-0 flex-1 flex-col items-start gap-8 overflow-y-auto px-10 pb-8 pt-16">
<div className="flex w-full flex-col gap-2">
<span className="text-[11px] font-semibold uppercase tracking-[0.08em] text-[var(--text-tertiary)]">
{t('rightSidebar.tabs.empty.eyebrow')}
@@ -67,6 +77,13 @@ export function EmptyState({
sub={t('rightSidebar.tabs.empty.backgroundTasksSub')}
onClick={onAddBackgroundTasksTab}
/>
+ {/* 资源用量 order=18,紧跟 background-tasks=17,顺序与 + 菜单一致。 */}
+ <ActionRow
+ icon={Activity}
+ label={t('rightSidebar.tabs.empty.openResourceUsage')}
+ sub={t('rightSidebar.tabs.kinds.resourceUsage')}
+ onClick={onAddResourceUsageTab}
+ />
<ActionRow
icon={Globe}
label={t('rightSidebar.tabs.empty.openBrowser')}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx
index 38546f2dd1..f2bd31bbb9 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/RightSidebarShell.tsx
@@ -507,6 +507,7 @@ export function RightSidebarShell({
onAddFileTab={() => handleAdd('file-browser')}
onAddReviewTab={() => handleAdd('review')}
onAddBackgroundTasksTab={() => handleAdd('background-tasks')}
+ onAddResourceUsageTab={() => handleAdd('resource-usage')}
onAddBrowserTab={() => handleAdd('web-browser')}
onAddTerminalTab={() => handleAdd('terminal')}
/>
diff --git a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
index a378bbeb40..6330d107f9 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/TabBar.tsx
@@ -20,6 +20,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
+ Activity,
FolderTree,
Globe,
Terminal,
@@ -122,6 +123,7 @@ const KIND_ICON: Record<BuiltinTabKindId, LucideIcon> = {
review: GitPullRequestArrow,
'orca-workers': UsersRound,
'background-tasks': ListTodo,
+ 'resource-usage': Activity,
};
const KIND_LABEL_KEY: Record<BuiltinTabKindId, string> = {
@@ -131,6 +133,7 @@ const KIND_LABEL_KEY: Record<BuiltinTabKindId, string> = {
review: 'rightSidebar.tabs.kinds.review',
'orca-workers': 'rightSidebar.tabs.kinds.collaboration',
'background-tasks': 'rightSidebar.tabs.kinds.backgroundTasks',
+ 'resource-usage': 'rightSidebar.tabs.kinds.resourceUsage',
};
/**
diff --git a/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsx
index 3d3dac43e2..d84b5622bb 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsx
+++ b/apps/desktop/src/renderer/features/right-sidebar/__tests__/EmptyState.test.tsx
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import { cleanup, render, screen } from '@testing-library/react';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
vi.mock('react-i18next', () => ({
@@ -10,12 +10,13 @@ import { EmptyState } from '../EmptyState';
afterEach(() => cleanup());
-function renderEmptyState() {
+function renderEmptyState(onAddResourceUsageTab = vi.fn()) {
return render(
<EmptyState
onAddFileTab={vi.fn()}
onAddReviewTab={vi.fn()}
onAddBackgroundTasksTab={vi.fn()}
+ onAddResourceUsageTab={onAddResourceUsageTab}
onAddBrowserTab={vi.fn()}
onAddTerminalTab={vi.fn()}
/>,
@@ -41,4 +42,11 @@ describe('EmptyState 面板收束(2026-08)', () => {
expect(screen.queryByText('rightSidebar.tabs.empty.pluginGroup')).toBeNull();
expect(screen.queryByText('rightSidebar.tabs.empty.pluginSub')).toBeNull();
});
+
+ it('提供资源用量快捷入口', () => {
+ const onAddResourceUsageTab = vi.fn();
+ renderEmptyState(onAddResourceUsageTab);
+ fireEvent.click(screen.getByText('rightSidebar.tabs.empty.openResourceUsage'));
+ expect(onAddResourceUsageTab).toHaveBeenCalledOnce();
+ });
});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts
index da4294954b..e1280cadd2 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/index.ts
@@ -15,3 +15,4 @@ import './terminal';
import './review';
import './orca-workers';
import './background-tasks';
+import './resource-usage';
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx
new file mode 100644
index 0000000000..dd3c158a2b
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/ResourceUsageBody.tsx
@@ -0,0 +1,441 @@
+/** 「资源用量」:单层紧凑进程表,数据与终止授权均由 main 提供。 */
+
+import { useEffect, useMemo, useState } from 'react';
+import type { TFunction } from 'i18next';
+import { useTranslation } from 'react-i18next';
+import {
+ AppWindow,
+ ArrowDown,
+ ArrowUp,
+ Bot,
+ Cog,
+ Cpu,
+ PanelsTopLeft,
+ ServerOff,
+ type LucideIcon,
+} from 'lucide-react';
+
+import { ConfirmDialog } from '@/components/ui/confirm-dialog';
+import { Spinner } from '@/components/ui/spinner';
+import { toast } from '@/components/ui/toast';
+import type {
+ ProcessMonitorSample,
+ ProcessUsageEntry,
+} from '../../../../../shared/processMonitor';
+import type { TabKindHostContext } from '../../types';
+import type { ResourceUsageState } from './index';
+import {
+ acquireProcessMonitorSubscription,
+ releaseProcessMonitorSubscription,
+} from './subscription';
+import './resource-usage.css';
+
+type SortKey = 'name' | 'cpu' | 'memory' | 'pid';
+type SortDirection = 'asc' | 'desc';
+
+const KIND_ICON: Record<ProcessUsageEntry['kind'], LucideIcon> = {
+ main: AppWindow,
+ renderer: PanelsTopLeft,
+ gpu: Cpu,
+ utility: Cog,
+ 'agent-claude': Bot,
+ 'agent-codex': Bot,
+ 'agent-pi': Bot,
+};
+
+const AGENT_NAME: Record<string, string> = {
+ 'agent-claude': 'Claude Code',
+ 'agent-codex': 'Codex',
+ 'agent-pi': 'Pi',
+};
+
+const UTILITY_LABEL_KEY: Record<string, string> = {
+ 'audio.mojom.AudioService': 'audio',
+ 'network.mojom.NetworkService': 'network',
+ 'storage.mojom.StorageService': 'storage',
+ 'video_capture.mojom.VideoCaptureService': 'videoCapture',
+};
+
+function formatCpu(cpuPercent: number): string {
+ return `${cpuPercent >= 10 ? Math.round(cpuPercent) : cpuPercent.toFixed(1)}%`;
+}
+
+function formatMemory(memoryKb: number): string {
+ if (memoryKb >= 1024 * 1024) return `${(memoryKb / 1024 / 1024).toFixed(1)} GB`;
+ return `${Math.round(memoryKb / 1024)} MB`;
+}
+
+function entryName(entry: ProcessUsageEntry, t: TFunction): string {
+ if (entry.kind === 'agent-codex') {
+ if (entry.agentRole === 'task-host') {
+ return t('rightSidebar.resourceUsage.agentRoles.codexTask');
+ }
+ if (entry.agentRole === 'control-plane-service') {
+ return t('rightSidebar.resourceUsage.agentRoles.codexService');
+ }
+ }
+ if (entry.kind.startsWith('agent-')) return AGENT_NAME[entry.kind] ?? 'Agent';
+ if (entry.kind === 'utility' && entry.label) {
+ const serviceKey = UTILITY_LABEL_KEY[entry.label];
+ if (serviceKey) return t(`rightSidebar.resourceUsage.services.${serviceKey}`);
+ }
+ return entry.label ?? t(`rightSidebar.resourceUsage.kinds.${entry.kind}`);
+}
+
+function entryDetails(entry: ProcessUsageEntry, t: TFunction): string | null {
+ if (entry.kind.startsWith('agent-')) {
+ // 单根进程是常态,不重复陈述“1 个进程”;只有实际出现子进程时才提示
+ // 进程树规模。CPU / 内存始终是完整树汇总,与此展示取舍无关。
+ const processCount = entry.processCount > 1
+ ? t('rightSidebar.resourceUsage.processCount', { count: entry.processCount })
+ : null;
+ if (entry.agentRole === 'task-host') {
+ const role = t('rightSidebar.resourceUsage.agentRoleDetails.task');
+ return processCount ? `${role} · ${processCount}` : role;
+ }
+ if (entry.agentRole === 'control-plane-service') {
+ const role = t('rightSidebar.resourceUsage.agentRoleDetails.service');
+ return processCount ? `${role} · ${processCount}` : role;
+ }
+ return processCount;
+ }
+ return entry.label ? t(`rightSidebar.resourceUsage.kinds.${entry.kind}`) : null;
+}
+
+function compareEntries(
+ a: ProcessUsageEntry,
+ b: ProcessUsageEntry,
+ key: SortKey,
+ direction: SortDirection,
+ t: TFunction,
+): number {
+ let value = 0;
+ if (key === 'name') value = entryName(a, t).localeCompare(entryName(b, t));
+ if (key === 'cpu') value = a.cpuPercent - b.cpuPercent;
+ if (key === 'memory') value = a.memoryKb - b.memoryKb;
+ if (key === 'pid') value = a.pid - b.pid;
+ if (value === 0) value = a.pid - b.pid;
+ return direction === 'asc' ? value : -value;
+}
+
+function SortHeader({
+ column,
+ label,
+ activeKey,
+ direction,
+ className,
+ onSort,
+}: {
+ column: SortKey;
+ label: string;
+ activeKey: SortKey;
+ direction: SortDirection;
+ className?: string;
+ onSort: (key: SortKey) => void;
+}) {
+ const { t } = useTranslation();
+ const active = column === activeKey;
+ const Icon = direction === 'asc' ? ArrowUp : ArrowDown;
+ return (
+ <div
+ role="columnheader"
+ aria-sort={active ? (direction === 'asc' ? 'ascending' : 'descending') : 'none'}
+ className={className}
+ >
+ <button
+ type="button"
+ className="resource-usage-sort-button"
+ aria-label={t('rightSidebar.resourceUsage.sortBy', { column: label })}
+ onClick={() => onSort(column)}
+ >
+ <span>{label}</span>
+ {active ? <Icon aria-hidden size={10} strokeWidth={1.75} /> : null}
+ </button>
+ </div>
+ );
+}
+
+function SectionHeader({ label }: { label: string }) {
+ return <div className="resource-usage-section">{label}</div>;
+}
+
+function EntryRow({
+ entry,
+ selected,
+ onSelect,
+}: {
+ entry: ProcessUsageEntry;
+ selected: boolean;
+ onSelect: (entry: ProcessUsageEntry) => void;
+}) {
+ const { t } = useTranslation();
+ const Icon = KIND_ICON[entry.kind];
+ const name = entryName(entry, t);
+ const details = entryDetails(entry, t);
+ const select = () => onSelect(entry);
+ return (
+ <div
+ role="row"
+ tabIndex={0}
+ aria-selected={selected}
+ className="resource-usage-row resource-usage-grid"
+ data-selected={selected ? 'true' : 'false'}
+ data-kind={entry.kind}
+ data-agent-role={entry.agentRole}
+ onClick={select}
+ onKeyDown={(event) => {
+ if (event.key !== 'Enter' && event.key !== ' ') return;
+ event.preventDefault();
+ select();
+ }}
+ >
+ <div role="cell" className="resource-usage-name-cell">
+ <Icon className="resource-usage-icon" aria-hidden size={14} strokeWidth={1.6} />
+ <div className="resource-usage-name-copy">
+ <div className="resource-usage-name" title={name}>{name}</div>
+ {details ? (
+ <div className="resource-usage-details">
+ <span>{details}</span>
+ <span className="resource-usage-pid-inline"> · PID {entry.pid}</span>
+ </div>
+ ) : (
+ <div className="resource-usage-details resource-usage-pid-only">
+ PID {entry.pid}
+ </div>
+ )}
+ </div>
+ </div>
+ <div role="cell" className="resource-usage-number">{formatCpu(entry.cpuPercent)}</div>
+ <div role="cell" className="resource-usage-number">{formatMemory(entry.memoryKb)}</div>
+ <div role="cell" className="resource-usage-number resource-usage-pid">{entry.pid}</div>
+ </div>
+ );
+}
+
+function LocalResourceUsageBody({
+ active,
+ shellVisible,
+}: {
+ state: ResourceUsageState;
+ active?: boolean;
+ shellVisible?: boolean;
+}) {
+ const { t } = useTranslation();
+ const visible = (active ?? true) && (shellVisible ?? true);
+ const [sample, setSample] = useState<ProcessMonitorSample | null>(null);
+ const [selectedPid, setSelectedPid] = useState<number | null>(null);
+ const [pendingKill, setPendingKill] = useState<ProcessUsageEntry | null>(null);
+ const [killing, setKilling] = useState(false);
+ const [sort, setSort] = useState<{ key: SortKey; direction: SortDirection }>({
+ key: 'cpu',
+ direction: 'desc',
+ });
+
+ useEffect(() => {
+ if (!visible) return;
+ let disposed = false;
+ const offSample = window.electronAPI.processMonitor.onSample((next) => {
+ if (!disposed) setSample(next);
+ });
+ acquireProcessMonitorSubscription();
+ return () => {
+ disposed = true;
+ offSample();
+ releaseProcessMonitorSubscription();
+ };
+ }, [visible]);
+
+ useEffect(() => {
+ if (selectedPid == null || !sample) return;
+ if (!sample.entries.some((entry) => entry.pid === selectedPid)) setSelectedPid(null);
+ }, [sample, selectedPid]);
+
+ const sortedEntries = useMemo(() => {
+ const entries = sample?.entries ?? [];
+ const sorter = (a: ProcessUsageEntry, b: ProcessUsageEntry) =>
+ compareEntries(a, b, sort.key, sort.direction, t);
+ return {
+ agents: entries.filter((entry) => entry.kind.startsWith('agent-')).sort(sorter),
+ app: entries.filter((entry) => !entry.kind.startsWith('agent-')).sort(sorter),
+ };
+ }, [sample, sort, t]);
+
+ const selected = sample?.entries.find((entry) => entry.pid === selectedPid) ?? null;
+ const confirmTarget = pendingKill ? entryName(pendingKill, t) : '';
+
+ const handleSort = (key: SortKey) => {
+ setSort((current) => ({
+ key,
+ direction:
+ current.key === key
+ ? current.direction === 'asc' ? 'desc' : 'asc'
+ : key === 'name' ? 'asc' : 'desc',
+ }));
+ };
+
+ const handleConfirmTerminate = async () => {
+ if (!pendingKill?.processInstanceId || killing) return;
+ setKilling(true);
+ try {
+ await window.electronAPI.processMonitor.terminate({
+ pid: pendingKill.pid,
+ processInstanceId: pendingKill.processInstanceId,
+ });
+ toast.success(t('rightSidebar.resourceUsage.terminated', { name: confirmTarget }));
+ } catch {
+ toast.error(t('rightSidebar.resourceUsage.terminateFailed'));
+ } finally {
+ setKilling(false);
+ setPendingKill(null);
+ }
+ };
+
+ const actionHint = !selected
+ ? t('rightSidebar.resourceUsage.selectHint')
+ : selected.terminable
+ ? `${entryName(selected, t)} · PID ${selected.pid}`
+ : t('rightSidebar.resourceUsage.readOnlyHint');
+
+ return (
+ <div className="resource-usage-root">
+ <div
+ className="resource-usage-table"
+ role="table"
+ aria-label={t('rightSidebar.resourceUsage.tableLabel')}
+ >
+ <div role="row" className="resource-usage-header resource-usage-grid">
+ <SortHeader
+ column="name"
+ label={t('rightSidebar.resourceUsage.columns.process')}
+ activeKey={sort.key}
+ direction={sort.direction}
+ onSort={handleSort}
+ />
+ <SortHeader
+ column="cpu"
+ label={t('rightSidebar.resourceUsage.columns.cpu')}
+ activeKey={sort.key}
+ direction={sort.direction}
+ className="resource-usage-header-number"
+ onSort={handleSort}
+ />
+ <SortHeader
+ column="memory"
+ label={t('rightSidebar.resourceUsage.columns.memory')}
+ activeKey={sort.key}
+ direction={sort.direction}
+ className="resource-usage-header-number"
+ onSort={handleSort}
+ />
+ <SortHeader
+ column="pid"
+ label={t('rightSidebar.resourceUsage.columns.pid')}
+ activeKey={sort.key}
+ direction={sort.direction}
+ className="resource-usage-header-number resource-usage-pid"
+ onSort={handleSort}
+ />
+ </div>
+
+ <div role="rowgroup" className="resource-usage-body">
+ {sample === null ? (
+ <div className="resource-usage-loading">
+ <Spinner size={13} />
+ <span>{t('rightSidebar.resourceUsage.loading')}</span>
+ </div>
+ ) : (
+ <>
+ <SectionHeader label={t('rightSidebar.resourceUsage.sections.agents')} />
+ {sortedEntries.agents.length > 0 ? sortedEntries.agents.map((entry) => (
+ <EntryRow
+ key={entry.pid}
+ entry={entry}
+ selected={selectedPid === entry.pid}
+ onSelect={(next) => setSelectedPid(next.pid)}
+ />
+ )) : (
+ <div className="resource-usage-empty">
+ {t('rightSidebar.resourceUsage.agentsEmpty')}
+ </div>
+ )}
+ {sortedEntries.app.length > 0 ? (
+ <>
+ <SectionHeader label={t('rightSidebar.resourceUsage.sections.app')} />
+ {sortedEntries.app.map((entry) => (
+ <EntryRow
+ key={entry.pid}
+ entry={entry}
+ selected={selectedPid === entry.pid}
+ onSelect={(next) => setSelectedPid(next.pid)}
+ />
+ ))}
+ </>
+ ) : null}
+ </>
+ )}
+ </div>
+ </div>
+
+ <div className="resource-usage-footer">
+ <div className="resource-usage-action-hint" title={actionHint}>{actionHint}</div>
+ <button
+ type="button"
+ className="resource-usage-terminate"
+ disabled={!selected?.terminable}
+ onClick={() => {
+ if (selected?.terminable) setPendingKill(selected);
+ }}
+ >
+ {t('rightSidebar.resourceUsage.terminate')}
+ </button>
+ </div>
+
+ <ConfirmDialog
+ open={pendingKill !== null}
+ onOpenChange={(open) => {
+ if (!open && !killing) setPendingKill(null);
+ }}
+ title={t('rightSidebar.resourceUsage.terminateConfirmTitle', { name: confirmTarget })}
+ description={t('rightSidebar.resourceUsage.terminateConfirmDescription')}
+ confirmText={t('rightSidebar.resourceUsage.terminate')}
+ confirmVariant="destructive"
+ loading={killing}
+ onConfirm={() => void handleConfirmTerminate()}
+ />
+ </div>
+ );
+}
+
+export function ResourceUsageBody({
+ ctx,
+ ...props
+}: {
+ state: ResourceUsageState;
+ ctx: TabKindHostContext;
+ active?: boolean;
+ shellVisible?: boolean;
+}) {
+ const { t } = useTranslation();
+
+ // processMonitor only samples this Desktop instance. device-link tasks run on
+ // another device, while undefined means ownership is still resolving; both
+ // must fail closed instead of briefly exposing this device's processes.
+ const isLocalSession = ctx.remoteHostId === null && ctx.deviceLinkDeviceId === null;
+ if (!isLocalSession) {
+ return (
+ <div className="resource-usage-unavailable">
+ <ServerOff aria-hidden size={18} strokeWidth={1.6} />
+ <div className="resource-usage-unavailable-copy">
+ <div className="resource-usage-unavailable-title">
+ {t('rightSidebar.resourceUsage.remoteUnavailableTitle')}
+ </div>
+ <div className="resource-usage-unavailable-description">
+ {t('rightSidebar.resourceUsage.remoteUnavailableDescription')}
+ </div>
+ </div>
+ </div>
+ );
+ }
+
+ return <LocalResourceUsageBody {...props} />;
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/__tests__/ResourceUsageBody.test.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/__tests__/ResourceUsageBody.test.tsx
new file mode 100644
index 0000000000..a3d375ce86
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/__tests__/ResourceUsageBody.test.tsx
@@ -0,0 +1,183 @@
+// @vitest-environment jsdom
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { TabKindHostContext } from '../../../types';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+
+vi.mock('@/components/ui/confirm-dialog', () => ({
+ ConfirmDialog: () => null,
+}));
+
+vi.mock('@/components/ui/spinner', () => ({
+ Spinner: () => <span data-testid="spinner" />,
+}));
+
+vi.mock('@/components/ui/toast', () => ({
+ toast: { success: vi.fn(), error: vi.fn() },
+}));
+
+import { ResourceUsageBody } from '../ResourceUsageBody';
+
+const subscribe = vi.fn(async () => undefined);
+const unsubscribe = vi.fn(async () => undefined);
+const offSample = vi.fn();
+const onSample = vi.fn(() => offSample);
+
+function makeContext({
+ remoteHostId = null,
+ deviceLinkDeviceId,
+}: {
+ remoteHostId?: string | null;
+ deviceLinkDeviceId: string | null | undefined;
+}): TabKindHostContext {
+ return {
+ tabId: 'resource-usage-tab',
+ sessionId: 'session-1',
+ workdir: remoteHostId || deviceLinkDeviceId ? '/remote/project' : 'C:\\project',
+ remoteHostId,
+ deviceLinkDeviceId,
+ patchState: vi.fn(),
+ onVisibilityChange: vi.fn(),
+ setCloseInterceptor: vi.fn(() => vi.fn()),
+ };
+}
+
+beforeEach(() => {
+ subscribe.mockClear();
+ unsubscribe.mockClear();
+ offSample.mockClear();
+ onSample.mockClear();
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ processMonitor: {
+ onSample,
+ subscribe,
+ unsubscribe,
+ terminate: vi.fn(async () => undefined),
+ },
+ },
+ });
+});
+
+afterEach(() => cleanup());
+
+describe('ResourceUsageBody local-only gate', () => {
+ it('shows a local-only unavailable state without subscribing to local samples', () => {
+ render(
+ <ResourceUsageBody
+ state={{}}
+ ctx={makeContext({ remoteHostId: 'ssh-host-1', deviceLinkDeviceId: null })}
+ active
+ shellVisible
+ />,
+ );
+
+ expect(screen.getByText('rightSidebar.resourceUsage.remoteUnavailableTitle')).toBeTruthy();
+ expect(
+ screen.getByText('rightSidebar.resourceUsage.remoteUnavailableDescription'),
+ ).toBeTruthy();
+ expect(onSample).not.toHaveBeenCalled();
+ expect(subscribe).not.toHaveBeenCalled();
+ });
+
+ it('releases the local subscription when the tab switches to an SSH task', () => {
+ const view = render(
+ <ResourceUsageBody
+ state={{}}
+ ctx={makeContext({ deviceLinkDeviceId: null })}
+ active
+ shellVisible
+ />,
+ );
+
+ expect(onSample).toHaveBeenCalledOnce();
+ expect(subscribe).toHaveBeenCalledOnce();
+
+ view.rerender(
+ <ResourceUsageBody
+ state={{}}
+ ctx={makeContext({ remoteHostId: 'ssh-host-1', deviceLinkDeviceId: null })}
+ active
+ shellVisible
+ />,
+ );
+
+ expect(offSample).toHaveBeenCalledOnce();
+ expect(unsubscribe).toHaveBeenCalledOnce();
+ });
+
+ it.each([
+ ['a device-link session', 'device-1' as string | undefined],
+ ['an unresolved device-link owner', undefined],
+ ])('fails closed for %s without subscribing to local samples', (_label, deviceLinkDeviceId) => {
+ render(
+ <ResourceUsageBody
+ state={{}}
+ ctx={makeContext({ deviceLinkDeviceId })}
+ active
+ shellVisible
+ />,
+ );
+
+ expect(screen.getByText('rightSidebar.resourceUsage.remoteUnavailableTitle')).toBeTruthy();
+ expect(onSample).not.toHaveBeenCalled();
+ expect(subscribe).not.toHaveBeenCalled();
+ });
+
+ it('releases the local subscription when the tab switches to a device-link task', () => {
+ const view = render(
+ <ResourceUsageBody
+ state={{}}
+ ctx={makeContext({ deviceLinkDeviceId: null })}
+ active
+ shellVisible
+ />,
+ );
+
+ expect(onSample).toHaveBeenCalledOnce();
+ expect(subscribe).toHaveBeenCalledOnce();
+
+ view.rerender(
+ <ResourceUsageBody
+ state={{}}
+ ctx={makeContext({ deviceLinkDeviceId: 'device-1' })}
+ active
+ shellVisible
+ />,
+ );
+
+ expect(offSample).toHaveBeenCalledOnce();
+ expect(unsubscribe).toHaveBeenCalledOnce();
+ });
+
+ it('subscribes after an unresolved device-link owner is confirmed local', () => {
+ const view = render(
+ <ResourceUsageBody
+ state={{}}
+ ctx={makeContext({ deviceLinkDeviceId: undefined })}
+ active
+ shellVisible
+ />,
+ );
+
+ expect(onSample).not.toHaveBeenCalled();
+ expect(subscribe).not.toHaveBeenCalled();
+
+ view.rerender(
+ <ResourceUsageBody
+ state={{}}
+ ctx={makeContext({ deviceLinkDeviceId: null })}
+ active
+ shellVisible
+ />,
+ );
+
+ expect(onSample).toHaveBeenCalledOnce();
+ expect(subscribe).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/__tests__/subscription.test.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/__tests__/subscription.test.ts
new file mode 100644
index 0000000000..ee645af5f2
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/__tests__/subscription.test.ts
@@ -0,0 +1,31 @@
+// @vitest-environment jsdom
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+describe('resource usage subscription', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ });
+
+ it('引用计数只触发一次订阅,并处理 invoke rejection', async () => {
+ const subscribe = vi.fn().mockRejectedValue(new Error('window closed'));
+ const unsubscribe = vi.fn().mockRejectedValue(new Error('window closed'));
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: { processMonitor: { subscribe, unsubscribe } },
+ });
+ const { acquireProcessMonitorSubscription, releaseProcessMonitorSubscription } =
+ await import('../subscription');
+
+ acquireProcessMonitorSubscription();
+ acquireProcessMonitorSubscription();
+ await Promise.resolve();
+ expect(subscribe).toHaveBeenCalledOnce();
+
+ releaseProcessMonitorSubscription();
+ expect(unsubscribe).not.toHaveBeenCalled();
+ releaseProcessMonitorSubscription();
+ await Promise.resolve();
+ expect(unsubscribe).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx b/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx
new file mode 100644
index 0000000000..578e60f24c
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/index.tsx
@@ -0,0 +1,47 @@
+/**
+ * resource-usage plugin —— 右栏「资源用量」页签(本机进程 CPU / 内存快照)。
+ *
+ * 约束:
+ * - 每会话单例(singleton),进「+」菜单;数据是全局的(本机进程),不随
+ * session 变化 —— 单例只是避免同一会话开一堆重复面板。SSH 任务不订阅
+ * 本机数据,以明确不可用态避免把控制端进程误认为远端任务进程。
+ * - 无持久化状态(纯实时视图,重启后从头采样即可)。
+ * - 注册:模块顶层 import-side-effect,由 plugins/index.ts 汇总。
+ */
+
+import { Activity } from 'lucide-react';
+import type { TFunction } from 'i18next';
+
+import { registerTabKind } from '../../registry';
+import type { TabKindPlugin } from '../../types';
+import { ResourceUsageBody } from './ResourceUsageBody';
+
+export type ResourceUsageState = Record<never, never>;
+
+function ResourceUsageTabPillTitle({ t }: { state: ResourceUsageState; t: TFunction }) {
+ return <>{t('rightSidebar.tabs.kinds.resourceUsage')}</>;
+}
+
+function ResourceUsageTabPillIcon() {
+ return <Activity size={13} />;
+}
+
+const plugin: TabKindPlugin<ResourceUsageState> = {
+ kind: 'resource-usage',
+ menu: {
+ kind: 'resource-usage',
+ labelKey: 'rightSidebar.tabs.kinds.resourceUsage',
+ icon: Activity,
+ order: 18, // background-tasks=17 与 web-browser=20 之间
+ enabled: true,
+ singleton: true,
+ },
+ TabPillTitle: ResourceUsageTabPillTitle,
+ TabPillIcon: ResourceUsageTabPillIcon,
+ TabBody: ResourceUsageBody,
+ defaultState: () => ({}),
+ serializeState: () => ({}),
+ hydrateState: () => ({}),
+};
+
+registerTabKind(plugin as unknown as TabKindPlugin, import.meta.hot);
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css b/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css
new file mode 100644
index 0000000000..26604bdf9f
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/resource-usage.css
@@ -0,0 +1,280 @@
+.resource-usage-root {
+ container: resource-usage / inline-size;
+ display: grid;
+ grid-template-rows: minmax(0, 1fr) 44px;
+ height: 100%;
+ min-width: 0;
+ overflow: hidden;
+ background: var(--panel-bg);
+ color: var(--text-primary);
+ user-select: none;
+}
+
+.resource-usage-unavailable {
+ display: flex;
+ height: 100%;
+ min-width: 0;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ padding: 24px;
+ background: var(--panel-bg);
+ color: var(--text-tertiary);
+ text-align: left;
+ user-select: none;
+}
+
+.resource-usage-unavailable-copy {
+ max-width: 300px;
+}
+
+.resource-usage-unavailable-title {
+ color: var(--text-primary);
+ font-size: 13px;
+ font-weight: 500;
+ line-height: 18px;
+}
+
+.resource-usage-unavailable-description {
+ margin-top: 3px;
+ color: var(--text-secondary);
+ font-size: 12px;
+ line-height: 18px;
+}
+
+.resource-usage-table {
+ display: grid;
+ min-height: 0;
+ grid-template-rows: 32px minmax(0, 1fr);
+}
+
+.resource-usage-grid {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 52px 72px 56px;
+ column-gap: 8px;
+ align-items: center;
+}
+
+.resource-usage-header {
+ padding: 0 10px;
+ border-bottom: 1px solid var(--border-default);
+ color: var(--text-tertiary);
+ font-size: 11px;
+ font-weight: 500;
+}
+
+.resource-usage-header-number {
+ display: flex;
+ justify-content: flex-end;
+}
+
+.resource-usage-sort-button {
+ display: inline-flex;
+ min-width: 0;
+ align-items: center;
+ gap: 3px;
+ border-radius: 9999px;
+ color: inherit;
+ line-height: 20px;
+ transition: color 120ms ease, background-color 120ms ease;
+}
+
+.resource-usage-header-number .resource-usage-sort-button {
+ justify-content: flex-end;
+}
+
+.resource-usage-sort-button:hover {
+ color: var(--text-primary);
+}
+
+.resource-usage-sort-button:focus-visible,
+.resource-usage-row:focus-visible,
+.resource-usage-terminate:focus-visible {
+ outline: none;
+ box-shadow: 0 0 0 2px var(--focus-ring);
+}
+
+.resource-usage-body {
+ min-height: 0;
+ overflow-y: auto;
+ padding: 4px 6px 8px;
+}
+
+.resource-usage-section {
+ height: 28px;
+ padding: 10px 4px 4px;
+ color: var(--text-tertiary);
+ font-size: 11px;
+ font-weight: 500;
+ line-height: 14px;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+}
+
+.resource-usage-row {
+ min-height: 42px;
+ padding: 4px;
+ border-radius: 8px;
+ cursor: default;
+ transition: background-color 120ms ease;
+}
+
+.resource-usage-row:hover {
+ background: var(--surface-hover);
+}
+
+.resource-usage-row[data-selected='true'] {
+ background: var(--surface-chip);
+}
+
+.resource-usage-name-cell {
+ display: flex;
+ min-width: 0;
+ align-items: center;
+ gap: 7px;
+}
+
+.resource-usage-icon {
+ flex: 0 0 auto;
+}
+
+.resource-usage-row[data-kind^='agent-'] .resource-usage-icon {
+ color: var(--process-agent-task-icon);
+}
+
+.resource-usage-row[data-agent-role='control-plane-service'] .resource-usage-icon {
+ color: var(--process-agent-service-icon);
+}
+
+.resource-usage-row[data-kind='main'] .resource-usage-icon {
+ color: var(--process-main-icon);
+}
+
+.resource-usage-row[data-kind='renderer'] .resource-usage-icon {
+ color: var(--process-renderer-icon);
+}
+
+.resource-usage-row[data-kind='gpu'] .resource-usage-icon {
+ color: var(--process-gpu-icon);
+}
+
+.resource-usage-row[data-kind='utility'] .resource-usage-icon {
+ color: var(--process-utility-icon);
+}
+
+.resource-usage-name-copy {
+ min-width: 0;
+}
+
+.resource-usage-name {
+ overflow: hidden;
+ color: var(--text-primary);
+ font-size: 13px;
+ line-height: 18px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.resource-usage-details {
+ min-height: 14px;
+ overflow: hidden;
+ color: var(--text-tertiary);
+ font-size: 11px;
+ line-height: 14px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.resource-usage-number {
+ overflow: hidden;
+ color: var(--text-secondary);
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ line-height: 18px;
+ text-align: right;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.resource-usage-pid-inline {
+ display: none;
+}
+
+.resource-usage-pid-only {
+ display: none;
+}
+
+.resource-usage-loading,
+.resource-usage-empty {
+ display: flex;
+ min-height: 42px;
+ align-items: center;
+ gap: 7px;
+ padding: 8px 4px;
+ color: var(--text-tertiary);
+ font-size: 12px;
+ line-height: 18px;
+}
+
+.resource-usage-footer {
+ display: flex;
+ min-width: 0;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ padding: 6px 10px;
+ border-top: 1px solid var(--border-default);
+}
+
+.resource-usage-action-hint {
+ min-width: 0;
+ overflow: hidden;
+ color: var(--text-tertiary);
+ font-size: 11px;
+ line-height: 18px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.resource-usage-terminate {
+ display: inline-flex;
+ min-height: 30px;
+ flex: 0 0 auto;
+ align-items: center;
+ justify-content: center;
+ border: 1px solid var(--border-default);
+ border-radius: 9999px;
+ background: var(--surface-elevated);
+ padding: 0 12px;
+ color: var(--text-primary);
+ font-size: 12px;
+ font-weight: 500;
+ transition: color 120ms ease, background-color 120ms ease, border-color 120ms ease;
+}
+
+.resource-usage-terminate:hover:not(:disabled) {
+ background: var(--surface-hover);
+}
+
+.resource-usage-terminate:disabled {
+ cursor: default;
+ opacity: 0.4;
+}
+
+@container resource-usage (max-width: 359px) {
+ .resource-usage-grid {
+ grid-template-columns: minmax(0, 1fr) 48px 68px;
+ }
+
+ .resource-usage-pid {
+ display: none;
+ }
+
+ .resource-usage-pid-inline {
+ display: inline;
+ }
+
+ .resource-usage-pid-only {
+ display: block;
+ }
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts b/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts
new file mode 100644
index 0000000000..4593a5b3d1
--- /dev/null
+++ b/apps/desktop/src/renderer/features/right-sidebar/plugins/resource-usage/subscription.ts
@@ -0,0 +1,24 @@
+/**
+ * 采样订阅的 renderer 侧引用计数。
+ *
+ * main 按 webContents 记订阅(同一窗口只有一份),但同一窗口里可能有多个
+ * resource-usage Body 同时挂载(不同 session 的 tab 各一个实例,Body 常驻不
+ * 卸载)。若每个 Body 直接调 subscribe/unsubscribe,后卸载的会把先到的订阅
+ * 一并掐掉 —— 这里聚合成"本窗口是否还有人要数据"的单一事实。
+ */
+
+let refCount = 0;
+
+export function acquireProcessMonitorSubscription(): void {
+ refCount += 1;
+ if (refCount === 1) {
+ void window.electronAPI.processMonitor.subscribe().catch(() => undefined);
+ }
+}
+
+export function releaseProcessMonitorSubscription(): void {
+ refCount = Math.max(0, refCount - 1);
+ if (refCount === 0) {
+ void window.electronAPI.processMonitor.unsubscribe().catch(() => undefined);
+ }
+}
diff --git a/apps/desktop/src/renderer/features/right-sidebar/types.ts b/apps/desktop/src/renderer/features/right-sidebar/types.ts
index 54a0b9aabf..ad03ebb6d0 100644
--- a/apps/desktop/src/renderer/features/right-sidebar/types.ts
+++ b/apps/desktop/src/renderer/features/right-sidebar/types.ts
@@ -27,7 +27,8 @@ export type BuiltinTabKindId =
| 'terminal'
| 'review'
| 'orca-workers'
- | 'background-tasks';
+ | 'background-tasks'
+ | 'resource-usage';
export type TabKindId = BuiltinTabKindId | `ghost:${string}`;
/** 一个 tab 运行时实例。`state` 由各 plugin 自管理结构 + 序列化,壳子只搬运。 */
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 3fbef85ace..9caae34bc7 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -4371,6 +4371,7 @@
"terminal": "Terminal",
"review": "Review",
"backgroundTasks": "Background tasks",
+ "resourceUsage": "Resource Usage",
"collaboration": "Team",
"unknown": "Unknown tab",
"ghostPanel": "Plugin panel"
@@ -4389,13 +4390,14 @@
"empty": {
"eyebrow": "Right Sidebar",
"title": "Add a panel",
- "desc": "Open a file tree, review, built-in browser, or terminal here to work alongside the chat on the left.",
+ "desc": "Open files, review, resource usage, a built-in browser, or a terminal here to work alongside the chat on the left.",
"openFile": "Open files",
"fileSub": "Files",
"openReview": "Open review",
"reviewSub": "Review",
"openBackgroundTasks": "Open background tasks",
"backgroundTasksSub": "Background tasks",
+ "openResourceUsage": "Open Resource Usage",
"openBrowser": "Open browser",
"browserSub": "Browser",
"openTerminal": "Open terminal",
@@ -4772,6 +4774,53 @@
"progressSummary": "{{done}}/{{total}} agents",
"tokens": "{{value}} tokens",
"noProgress": "No progress details yet"
+ },
+ "resourceUsage": {
+ "sections": {
+ "agents": "Agent Processes",
+ "app": "App Processes"
+ },
+ "columns": {
+ "process": "Process",
+ "cpu": "CPU",
+ "memory": "Memory",
+ "pid": "PID"
+ },
+ "kinds": {
+ "main": "Main process",
+ "renderer": "UI process",
+ "gpu": "GPU process",
+ "utility": "Service process"
+ },
+ "agentRoles": {
+ "codexTask": "Codex Task",
+ "codexService": "Codex Service"
+ },
+ "agentRoleDetails": {
+ "task": "Task runtime",
+ "service": "Accounts and models"
+ },
+ "services": {
+ "audio": "Audio Service",
+ "network": "Network Service",
+ "storage": "Storage Service",
+ "videoCapture": "Video Capture"
+ },
+ "processCount_one": "Process tree: {{count}} process",
+ "processCount_other": "Process tree: {{count}} processes",
+ "agentsEmpty": "No agent processes are running. Start a task and its usage will show up here.",
+ "tableLabel": "Resource Usage by Process",
+ "sortBy": "Sort by {{column}}",
+ "loading": "Reading resource usage…",
+ "remoteUnavailableTitle": "Unavailable for remote sessions",
+ "remoteUnavailableDescription": "This panel only reads processes on this device. It is available only for local sessions running on this device.",
+ "selectHint": "Select a process",
+ "readOnlyHint": "Only Agent processes used for tasks can be stopped",
+ "terminate": "Stop Process",
+ "terminateConfirmTitle": "Stop {{name}} process?",
+ "terminateConfirmDescription": "This force-stops the Agent process. Every task using this process will be interrupted; send another message in an affected task to start an Agent again.",
+ "terminated": "Stopped the {{name}} process",
+ "terminateFailed": "Couldn't stop this process — it may have already exited. The list updates with the next sample."
}
},
"update": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 0f52e84b30..acfe4a7b01 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -4369,6 +4369,7 @@
"terminal": "ターミナル",
"review": "レビュー",
"backgroundTasks": "バックグラウンドタスク",
+ "resourceUsage": "リソース使用量",
"collaboration": "コラボ",
"unknown": "不明なタブ",
"ghostPanel": "プラグインパネル"
@@ -4387,13 +4388,14 @@
"empty": {
"eyebrow": "右サイドバー",
"title": "パネルを開く",
- "desc": "ファイルツリー、レビュー、内蔵ブラウザ、ターミナルを開いて、左側のチャットと並行して作業できます。",
+ "desc": "ファイル、レビュー、リソース使用量、内蔵ブラウザ、ターミナルを開いて、左側のチャットと並行して作業できます。",
"openFile": "ファイルを開く",
"fileSub": "Files",
"openReview": "レビューを開く",
"reviewSub": "Review",
"openBackgroundTasks": "バックグラウンドタスクを開く",
"backgroundTasksSub": "Background tasks",
+ "openResourceUsage": "リソース使用量を開く",
"openBrowser": "ブラウザを開く",
"browserSub": "Browser",
"openTerminal": "ターミナルを開く",
@@ -4770,6 +4772,53 @@
"progressSummary": "{{done}}/{{total}} Agent",
"tokens": "{{value}} tokens",
"noProgress": "進行状況の詳細はまだありません"
+ },
+ "resourceUsage": {
+ "sections": {
+ "agents": "Agent プロセス",
+ "app": "アプリプロセス"
+ },
+ "columns": {
+ "process": "プロセス",
+ "cpu": "CPU",
+ "memory": "メモリ",
+ "pid": "PID"
+ },
+ "kinds": {
+ "main": "メインプロセス",
+ "renderer": "UI プロセス",
+ "gpu": "GPU プロセス",
+ "utility": "サービスプロセス"
+ },
+ "agentRoles": {
+ "codexTask": "Codex タスク",
+ "codexService": "Codex サービス"
+ },
+ "agentRoleDetails": {
+ "task": "タスク実行",
+ "service": "アカウントとモデル"
+ },
+ "services": {
+ "audio": "オーディオサービス",
+ "network": "ネットワークサービス",
+ "storage": "ストレージサービス",
+ "videoCapture": "ビデオキャプチャ"
+ },
+ "processCount_one": "プロセスツリー:{{count}} 個",
+ "processCount_other": "プロセスツリー:{{count}} 個",
+ "agentsEmpty": "実行中の Agent プロセスはありません。タスクを開始するとここに表示されます",
+ "tableLabel": "プロセス別のリソース使用量",
+ "sortBy": "{{column}}で並べ替え",
+ "loading": "リソース使用量を読み込んでいます…",
+ "remoteUnavailableTitle": "リモートセッションでは利用できません",
+ "remoteUnavailableDescription": "このパネルはこのデバイス上のプロセスだけを読み取ります。このデバイスでローカルに実行されるセッションでのみ利用できます。",
+ "selectHint": "プロセスを選択",
+ "readOnlyHint": "終了できるのはタスク用の Agent プロセスだけです",
+ "terminate": "プロセスを終了",
+ "terminateConfirmTitle": "{{name}} プロセスを終了しますか?",
+ "terminateConfirmDescription": "この Agent プロセスを強制終了します。このプロセスを使用しているすべてのタスクが中断されます。影響を受けたタスクでメッセージを送信すると、必要に応じて Agent を再起動できます。",
+ "terminated": "{{name}} プロセスを終了しました",
+ "terminateFailed": "プロセスを終了できませんでした。すでに終了している可能性があります。リストは次回のサンプリングで自動的に更新されます"
}
},
"update": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index a628824af2..51e919ca70 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -4369,6 +4369,7 @@
"terminal": "터미널",
"review": "리뷰",
"backgroundTasks": "백그라운드 작업",
+ "resourceUsage": "리소스 사용량",
"collaboration": "협업",
"unknown": "알 수 없는 탭",
"ghostPanel": "플러그인 패널"
@@ -4387,13 +4388,14 @@
"empty": {
"eyebrow": "오른쪽 사이드바",
"title": "패널 시작하기",
- "desc": "왼쪽 채팅과 나란히 작업할 수 있도록 파일 트리, 리뷰, 내장 브라우저, 터미널을 여기에 여세요.",
+ "desc": "왼쪽 채팅과 나란히 작업할 수 있도록 파일, 리뷰, 리소스 사용량, 내장 브라우저, 터미널을 여기에 여세요.",
"openFile": "파일 열기",
"fileSub": "Files",
"openReview": "리뷰 열기",
"reviewSub": "Review",
"openBackgroundTasks": "백그라운드 작업 열기",
"backgroundTasksSub": "Background tasks",
+ "openResourceUsage": "리소스 사용량 열기",
"openBrowser": "브라우저 열기",
"browserSub": "Browser",
"openTerminal": "터미널 열기",
@@ -4770,6 +4772,53 @@
"progressSummary": "{{done}}/{{total}} Agent",
"tokens": "{{value}} tokens",
"noProgress": "진행 상황 정보가 아직 없습니다"
+ },
+ "resourceUsage": {
+ "sections": {
+ "agents": "Agent 프로세스",
+ "app": "앱 프로세스"
+ },
+ "columns": {
+ "process": "프로세스",
+ "cpu": "CPU",
+ "memory": "메모리",
+ "pid": "PID"
+ },
+ "kinds": {
+ "main": "메인 프로세스",
+ "renderer": "UI 프로세스",
+ "gpu": "GPU 프로세스",
+ "utility": "서비스 프로세스"
+ },
+ "agentRoles": {
+ "codexTask": "Codex 작업",
+ "codexService": "Codex 서비스"
+ },
+ "agentRoleDetails": {
+ "task": "작업 실행",
+ "service": "계정 및 모델"
+ },
+ "services": {
+ "audio": "오디오 서비스",
+ "network": "네트워크 서비스",
+ "storage": "스토리지 서비스",
+ "videoCapture": "비디오 캡처"
+ },
+ "processCount_one": "프로세스 트리: {{count}}개",
+ "processCount_other": "프로세스 트리: {{count}}개",
+ "agentsEmpty": "실행 중인 Agent 프로세스가 없습니다. 작업을 시작하면 여기에 표시됩니다.",
+ "tableLabel": "프로세스별 리소스 사용량",
+ "sortBy": "{{column}} 기준 정렬",
+ "loading": "리소스 사용량을 불러오는 중…",
+ "remoteUnavailableTitle": "원격 세션에서는 사용할 수 없음",
+ "remoteUnavailableDescription": "이 패널은 이 기기의 프로세스만 읽습니다. 이 기기에서 로컬로 실행되는 세션에만 사용할 수 있습니다.",
+ "selectHint": "프로세스 선택",
+ "readOnlyHint": "작업용 Agent 프로세스만 종료할 수 있습니다",
+ "terminate": "프로세스 종료",
+ "terminateConfirmTitle": "{{name}} 프로세스를 종료할까요?",
+ "terminateConfirmDescription": "이 Agent 프로세스를 강제 종료합니다. 이 프로세스를 사용하는 모든 작업이 중단되며, 영향을 받은 작업에서 메시지를 보내면 필요할 때 Agent를 다시 시작할 수 있습니다.",
+ "terminated": "{{name}} 프로세스를 종료했습니다",
+ "terminateFailed": "프로세스를 종료하지 못했습니다. 이미 종료되었을 수 있습니다. 목록은 다음 샘플링 때 자동으로 업데이트됩니다."
}
},
"update": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 3d3645c7b4..ca2dba3dbd 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -4369,6 +4369,7 @@
"terminal": "终端",
"review": "审查",
"backgroundTasks": "后台任务",
+ "resourceUsage": "资源用量",
"collaboration": "协同",
"unknown": "未知标签页",
"ghostPanel": "插件面板"
@@ -4387,13 +4388,14 @@
"empty": {
"eyebrow": "右侧栏",
"title": "开始一个面板",
- "desc": "在右侧打开文件树、审查、内置浏览器或终端,与左侧对话并行工作。",
+ "desc": "在右侧打开文件、审查、资源用量、内置浏览器或终端,与左侧对话并行工作。",
"openFile": "打开文件",
"fileSub": "Files",
"openReview": "打开审查",
"reviewSub": "Review",
"openBackgroundTasks": "打开后台任务",
"backgroundTasksSub": "Background tasks",
+ "openResourceUsage": "打开资源用量",
"openBrowser": "打开浏览器",
"browserSub": "Browser",
"openTerminal": "打开终端",
@@ -4770,6 +4772,53 @@
"progressSummary": "{{done}}/{{total}} Agent",
"tokens": "{{value}} tokens",
"noProgress": "暂无进度详情"
+ },
+ "resourceUsage": {
+ "sections": {
+ "agents": "Agent 进程",
+ "app": "应用进程"
+ },
+ "columns": {
+ "process": "进程",
+ "cpu": "CPU",
+ "memory": "内存",
+ "pid": "PID"
+ },
+ "kinds": {
+ "main": "主进程",
+ "renderer": "界面进程",
+ "gpu": "GPU 进程",
+ "utility": "服务进程"
+ },
+ "agentRoles": {
+ "codexTask": "Codex 任务",
+ "codexService": "Codex 服务"
+ },
+ "agentRoleDetails": {
+ "task": "任务运行",
+ "service": "账户与模型"
+ },
+ "services": {
+ "audio": "音频服务",
+ "network": "网络服务",
+ "storage": "存储服务",
+ "videoCapture": "视频采集"
+ },
+ "processCount_one": "进程树:{{count}} 个进程",
+ "processCount_other": "进程树:{{count}} 个进程",
+ "agentsEmpty": "当前没有运行中的 Agent 进程,启动任务后会在这里展示占用",
+ "tableLabel": "按进程展示的资源用量",
+ "sortBy": "按{{column}}排序",
+ "loading": "正在读取资源用量…",
+ "remoteUnavailableTitle": "远程任务暂不可用",
+ "remoteUnavailableDescription": "此面板仅读取本机进程,仅适用于在此设备上运行的本机任务。",
+ "selectHint": "选择一个进程",
+ "readOnlyHint": "只有用于任务的 Agent 进程可以终止",
+ "terminate": "终止进程",
+ "terminateConfirmTitle": "终止 {{name}} 进程?",
+ "terminateConfirmDescription": "将强制终止该 Agent 进程,使用该进程的所有任务都会中断;之后在任一受影响任务里继续发消息,即可按需重新启动 Agent。",
+ "terminated": "已终止 {{name}} 进程",
+ "terminateFailed": "无法终止该进程,它可能已自行退出;列表会随下一次采样自动更新"
}
},
"update": {
diff --git a/apps/desktop/src/renderer/themes/__tests__/tokenRegistry.test.ts b/apps/desktop/src/renderer/themes/__tests__/tokenRegistry.test.ts
index e576bb869d..854e443da2 100644
--- a/apps/desktop/src/renderer/themes/__tests__/tokenRegistry.test.ts
+++ b/apps/desktop/src/renderer/themes/__tests__/tokenRegistry.test.ts
@@ -16,6 +16,14 @@ import { exportThemeColors } from '../theme-service';
* 不允许再制造新的幽灵。清单随修复增补,删条目 = 该幽灵已注册。
*/
const FORMER_GHOST_TOKENS = ['panel-bg', 'board'] as const;
+const PROCESS_ICON_TOKENS = [
+ 'process-agent-task-icon',
+ 'process-agent-service-icon',
+ 'process-main-icon',
+ 'process-renderer-icon',
+ 'process-gpu-icon',
+ 'process-utility-icon',
+] as const;
describe('主题注册表 · 历史幽灵 token 补注册(D1 地基修复)', () => {
it.each(FORMER_GHOST_TOKENS)(
@@ -46,6 +54,13 @@ describe('主题注册表 · 历史幽灵 token 补注册(D1 地基修复)', ()
});
});
+describe('主题注册表 · 资源用量进程图标', () => {
+ it.each(PROCESS_ICON_TOKENS)('"%s" 有 Light / Dark 双模式颜色', (id) => {
+ expect(colorRegistry.resolveDefault(id, 'light')).not.toBeNull();
+ expect(colorRegistry.resolveDefault(id, 'dark')).not.toBeNull();
+ });
+});
+
describe('主题注册表 · Plan 操作卡文字语义', () => {
it.each(['plan-action-approve-text', 'plan-action-fb-text'])(
'"%s" 使用卡片强调正文而非反相按钮文字',
diff --git a/apps/desktop/src/renderer/themes/colors.ts b/apps/desktop/src/renderer/themes/colors.ts
index dda3fb7994..7052dfaf55 100644
--- a/apps/desktop/src/renderer/themes/colors.ts
+++ b/apps/desktop/src/renderer/themes/colors.ts
@@ -225,6 +225,32 @@ registerColor('warning-accent', {
light: '#EA6B17',
dark: '#EA6B17',
}, 'Thinking orange / warning accent — running 状态色,设计定稿 2026-07-17(取代 #FF6600 冻结红线);全局同值,9 主题无 override 自动跟随');
+// DESIGN.md §2 / §10 窄范围例外:仅资源用量表的 14px 进程类别 glyph 使用,
+// 不表示健康/状态,也不得扩散到行背景、文字或其它进程 UI。
+registerColor('process-agent-task-icon', {
+ light: '#2563EB',
+ dark: '#60A5FA',
+}, '资源用量表:任务 Agent 进程图标');
+registerColor('process-agent-service-icon', {
+ light: '#7C3AED',
+ dark: '#A78BFA',
+}, '资源用量表:Agent 控制面服务图标');
+registerColor('process-main-icon', {
+ light: '#DB2777',
+ dark: '#F472B6',
+}, '资源用量表:主进程图标');
+registerColor('process-renderer-icon', {
+ light: '#0891B2',
+ dark: '#22D3EE',
+}, '资源用量表:界面进程图标');
+registerColor('process-gpu-icon', {
+ light: '#D97706',
+ dark: '#F59E0B',
+}, '资源用量表:GPU 进程图标');
+registerColor('process-utility-icon', {
+ light: '#059669',
+ dark: '#34D399',
+}, '资源用量表:Utility 服务进程图标');
registerColor('shadow-soft-panel', {
light: '0 4px 12px rgb(0 0 0 / 0.08)',
dark: '0 4px 12px rgb(0 0 0 / 0.3)',
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 6e63f6fff7..d2c48ef73c 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -4347,6 +4347,21 @@ interface ElectronAPI {
) => () => void;
};
+ /**
+ * 资源用量面板(process-monitor):订阅期间 main 才采样;terminate 只对
+ * 本产品 spawn 的 agent 根进程有效,归属由 main 重新校验。
+ */
+ processMonitor: {
+ subscribe: () => Promise<void>;
+ unsubscribe: () => Promise<void>;
+ terminate: (
+ request: import('../shared/processMonitor').TerminateAgentProcessRequest,
+ ) => Promise<import('../shared/processMonitor').TerminateAgentProcessResult>;
+ onSample: (
+ cb: (sample: import('../shared/processMonitor').ProcessMonitorSample) => void,
+ ) => () => void;
+ };
+
/**
* Browser backend toggle: 切换 MCP `browser` 工具实际控制的浏览器。
* - `external`: vendored Playwright + 独立 Chrome(**系统默认**)
diff --git a/apps/desktop/src/shared/__tests__/themeImportPalette.test.ts b/apps/desktop/src/shared/__tests__/themeImportPalette.test.ts
index 0aa218ee17..f19740837f 100644
--- a/apps/desktop/src/shared/__tests__/themeImportPalette.test.ts
+++ b/apps/desktop/src/shared/__tests__/themeImportPalette.test.ts
@@ -168,6 +168,17 @@ describe('theme-import 模板 · key 集合与既有 builtin 主题一致', () =
it('模板不产出任何语义豁免族 token(登录/危险/警告/焦点/diff)', () => {
expect(TEMPLATE_TOKEN_IDS.filter((id) => isProtectedToken(id))).toEqual([]);
});
+
+ it.each([
+ 'process-agent-task-icon',
+ 'process-agent-service-icon',
+ 'process-main-icon',
+ 'process-renderer-icon',
+ 'process-gpu-icon',
+ 'process-utility-icon',
+ ])('资源用量类别色 "%s" 不被外部主题导入改写', (id) => {
+ expect(isProtectedToken(id)).toBe(true);
+ });
});
describe.each([
diff --git a/apps/desktop/src/shared/processMonitor.ts b/apps/desktop/src/shared/processMonitor.ts
new file mode 100644
index 0000000000..8a01f13312
--- /dev/null
+++ b/apps/desktop/src/shared/processMonitor.ts
@@ -0,0 +1,76 @@
+/**
+ * process-monitor —— 「资源用量」面板的 main / preload / renderer 共享契约。
+ *
+ * 数据面:main 周期采样(app.getAppMetrics + OS 级 agent 子进程扫描)后经
+ * PROCESS_MONITOR_SAMPLE_CHANNEL 推送;只在有订阅者(面板打开)时采样。
+ * 动作面:terminate 只接受「本产品 spawn 的 agent 根进程」,归属由 main 侧
+ * 重新扫描独立校验,renderer 传来的 pid 只是候选,不是授权依据。
+ */
+
+/** renderer → main(invoke):开始接收采样推送(以 sender webContents 计数)。 */
+export const PROCESS_MONITOR_SUBSCRIBE_CHANNEL = 'process-monitor:subscribe';
+/** renderer → main(invoke):停止接收采样推送。 */
+export const PROCESS_MONITOR_UNSUBSCRIBE_CHANNEL = 'process-monitor:unsubscribe';
+/** main → renderer(push):一次完整采样快照(ProcessMonitorSample)。 */
+export const PROCESS_MONITOR_SAMPLE_CHANNEL = 'process-monitor:sample';
+/** renderer → main(invoke):终止一个 agent 根进程及其子孙(强校验归属)。 */
+export const PROCESS_MONITOR_TERMINATE_CHANNEL = 'process-monitor:terminate-agent';
+
+export type ProcessUsageKind =
+ | 'main'
+ | 'renderer'
+ | 'gpu'
+ | 'utility'
+ | 'agent-claude'
+ | 'agent-codex'
+ | 'agent-pi';
+
+/** Codex 本地 app-server 的产品职责;仅传枚举,不暴露 host key / 凭据 / 命令行。 */
+export type AgentProcessRole = 'task-host' | 'control-plane-service';
+
+export interface ProcessUsageEntry {
+ /** 根进程 pid(agent 条目 = 树根;Chromium 条目 = 进程本身)。 */
+ pid: number;
+ kind: ProcessUsageKind;
+ /**
+ * 展示名:renderer = 页面/窗口标题,utility = serviceName。可能为 null
+ * (renderer 兜底文案由 UI 侧 i18n 提供)。不携带路径与命令行 —— 内部
+ * 绝对路径不出 main(electron-security 规则)。
+ */
+ label: string | null;
+ /** CPU 占用(单核百分比;agent 条目为整棵子进程树求和)。 */
+ cpuPercent: number;
+ /** 内存 working set(KB;agent 条目为整棵子进程树求和)。 */
+ memoryKb: number;
+ /**
+ * 该条目聚合的可见进程数(agent 树含根,但不含 conhost 等 OS 辅助进程;
+ * Chromium 条目恒为 1)。CPU / 内存仍聚合完整进程树。
+ */
+ processCount: number;
+ /** true = 可被「结束进程」终止(仅本产品 spawn 的 agent 根进程)。 */
+ terminable: boolean;
+ /**
+ * OS 提供的进程出生身份。仅可终止的 agent 根进程携带;renderer 原样回传,
+ * main 用它拒绝已经退出并被复用的旧 pid。它不包含路径或命令行。
+ */
+ processInstanceId?: string;
+ /** 仅 Codex 条目可有;普通任务共享宿主与账户/模型控制面服务据此消歧。 */
+ agentRole?: AgentProcessRole;
+}
+
+export interface ProcessMonitorSample {
+ capturedAtMs: number;
+ entries: ProcessUsageEntry[];
+}
+
+/** renderer → main 的终止候选;两个字段都只是候选,main 会同步重新校验归属。 */
+export interface TerminateAgentProcessRequest {
+ pid: number;
+ processInstanceId: string;
+}
+
+/** terminate 成功返回(失败一律走 IPC 错误协议 throwIpcError)。 */
+export interface TerminateAgentProcessResult {
+ pid: number;
+ kind: 'claude' | 'codex' | 'pi';
+}
diff --git a/apps/desktop/src/shared/theme-import/protected-tokens.ts b/apps/desktop/src/shared/theme-import/protected-tokens.ts
index ae4f22f3d1..805bb04758 100644
--- a/apps/desktop/src/shared/theme-import/protected-tokens.ts
+++ b/apps/desktop/src/shared/theme-import/protected-tokens.ts
@@ -42,6 +42,13 @@ const PROTECTED_IDS = new Set<string>([
// 权限语义色(自动审批蓝 / bypass 橙)
'perm-auto-selected-text',
'perm-bypass-selected-text',
+ // 资源用量表的进程类别 glyph(DESIGN.md §2 / §10 窄范围彩色例外)
+ 'process-agent-task-icon',
+ 'process-agent-service-icon',
+ 'process-main-icon',
+ 'process-renderer-icon',
+ 'process-gpu-icon',
+ 'process-utility-icon',
// 无障碍焦点环与文字选中提示色
'focus-ring',
'focus-ring-soft',
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 33721c8ce6..6cc3b618d3 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -78,6 +78,7 @@ The grayscale rule is near-absolute. The following are the **only** sanctioned n
> **Additional narrowly-scoped exceptions** (documented in their respective component specs, do NOT generalize as system semantic colors):
>
> - **Toast Info / Success / Warning / Error** — `#417CDD` / `#2AAE5B` / `#F3A115` / `#D91F37`(finalized 2026-07-17; Toast exemption lifted) — used ONLY on the 16×16 lucide icon inside Toast pill notifications. The pill body (background, text, border, close icon) remains strictly grayscale. Info blue #417CDD equals the focus-ring / Auto Approval value (originally #3B82F6, added 2026-07-14, now finalized); success/warning/error equal the global status colors (done green / status error / warning foreground).
+> - **Resource Usage Process Categories** — the Resource Usage table may color only its 14px process-type glyphs so dense rows can be scanned by category (user-requested 2026-08-06). The six category pairs are task Agent blue `#2563EB / #60A5FA`, Agent service purple `#7C3AED / #A78BFA`, main-process pink `#DB2777 / #F472B6`, renderer cyan `#0891B2 / #22D3EE`, GPU amber `#D97706 / #F59E0B`, and utility green `#059669 / #34D399` (Light / Dark). These colors encode process category, **not health or status**; row backgrounds, labels, metrics, selection and actions remain on the neutral system. Scope is strictly `resource-usage` process glyphs and must not be generalized to other tables or process UI. Tokens: `--process-agent-task-icon`, `--process-agent-service-icon`, `--process-main-icon`, `--process-renderer-icon`, `--process-gpu-icon`, `--process-utility-icon`.
> - **ConfirmDialog Danger** — `#EF4444` used ONLY on the confirm button background in the Danger variant. The cancel button and rest of the dialog remain grayscale.
> - **Permission Selector Mode Highlights** — selected risky permission modes may color only the option text/icon/checkmark and the collapsed trigger text/icon. The selected row background remains grayscale. Auto Approval uses `#417CDD` in both modes (finalized 2026-07-17, same value light/dark; replaces light #000050 / dark #00D9C5). Full Access uses Heart Orange `#EA6B17` in both modes (auto-follows warning-accent, finalized 2026-07-17). These hex values are the **default-theme palette only** — other themes may override `--perm-auto-selected-text` and `--perm-bypass-selected-text` with their own accent colors, provided both modes remain color-coded, distinguishable from each other, and visually distinct from neutral text. Tokens: `--perm-auto-selected-text` and `--perm-bypass-selected-text` in `apps/desktop/src/renderer/styles/globals.css`.
> - **Diff Add Green / Diff Del Red** — GitHub-standard diff syntax colors, used on the `+` / `-` symbol glyph, the changed-line text foreground, **and the full row background** inside code-diff renderings. Applied in three places: (1) the Edit-tool DiffView card (F-MSG-6), (2) markdown ````diff` fenced code blocks in the message stream, and (3) `.diff` / `.patch` files opened in TextLightbox (the document previewer) — there hljs `.hljs-addition` / `.hljs-deletion` are forced `display: block` so the background fills to the right edge instead of stopping at the last glyph. Line-number gutter and ctx (unchanged) lines remain strictly grayscale per the layer system. **Foreground** — Add: `#22863a` Light / `#7ee787` Dark; Del: `#b31d28` Light / `#ff7b72` Dark. **Background** — Add: `#f0fff4` Light / `#033a16` Dark; Del: `#ffeef0` Light / `#67060c` Dark. Tokens: `--diff-add-fg/-bg` and `--diff-del-fg/-bg` in `apps/desktop/src/renderer/styles/globals.css`. Updated 2026-04-21: backgrounds switched from grayscale → GitHub red/green for full-row fill so additions / deletions are unambiguous at a glance.
@@ -422,6 +423,7 @@ Theme switching: `useTheme.ts` provides `theme` (System / Light / Dark mode) plu
| `--perm-auto-selected-text` | `#417CDD` | `#417CDD` | Auto Approval accent, finalized 2026-07-17 (same value both modes; replaces #000050/#00D9C5) |
| Toast `#417CDD / #2AAE5B / #F3A115 / #D91F37` | (hardcoded in Toast.tsx, VARIANT_MAP exported) | same | Finalized 2026-07-17 (Toast exemption lifted, merged into the status-color family) |
| `--file-badge-pdf/-doc/-sheet/-slide/-code` + `--file-badge-fg` | `#B23A26` / `#2C5CA8` / `#2E7D4F` / `#A25A12` / `#5B49A8`, fg `#FFFFFF` | same | File-type badges on the self-drawn attachment icon (2026-07-27). Bound to *what the file is*, not to the theme, so both modes share one value. Each accent is picked for ≥4.5:1 against `--file-badge-fg` (5.96 / 6.56 / 5.05 / 5.24 / 7.09) — the badge label renders at 10px (Micro Label floor, §3), so AA small-text applies. `--file-badge-fg` is a standalone white: `--accent-pure-cta-fg` flips to black in Dark and cannot be borrowed. |
+| `--process-agent-task-icon`, `--process-agent-service-icon`, `--process-main-icon`, `--process-renderer-icon`, `--process-gpu-icon`, `--process-utility-icon` | `#2563EB` / `#7C3AED` / `#DB2777` / `#0891B2` / `#D97706` / `#059669` | `#60A5FA` / `#A78BFA` / `#F472B6` / `#22D3EE` / `#F59E0B` / `#34D399` | Resource Usage 14px process-category glyphs only (2026-08-06). Category cue, not status; all surrounding UI stays neutral. Protected from automatic external-theme import so category identity does not drift. |
Never freestyle these semantic colors as hardcoded hex — always go through the corresponding token.
diff --git a/docs/design-rules/cindy-design-system.md b/docs/design-rules/cindy-design-system.md
index 0d0422bf56..8a5008f888 100644
--- a/docs/design-rules/cindy-design-system.md
+++ b/docs/design-rules/cindy-design-system.md
@@ -15,6 +15,7 @@
## 版本记录
+- **2026-08-06(资源用量进程类别色)**:按用户对资源用量面板“icon 改为彩色”的走查要求,`DESIGN.md §2 / §10` 登记仅限 14px 进程类型 glyph 的六色 Light / Dark 调色板;颜色只编码任务 Agent、控制面服务、主进程、Renderer、GPU、Utility 类别,不表达健康或运行状态,行背景、文字、指标与操作继续保持中性。对应 token 加入外部主题导入保护,防类别色随导入主题漂移;该例外不得扩散到其它表格或进程 UI。
- **2026-07-29(修正:手机端功能区落位回新稿标注值)**:手机短屏 / 长屏的 `loginY` 由 main 原值 694 / 933 改回新稿标注值 **622 / 827**;短屏以下(dh<1334)改为 `min(622, max(0, dh-640))`——保留紧凑底距 18 再钳到短屏档落位(**不是**把锚常量改成 `dh-712`:那会让 dh∈[712,1222) 全段字标被面板压盖,review 实算 dh=1000 压 40 设计px)。起因:2026-07-28 剥离手机端跳过登录时把功能区落位一并退回 main,却保留了已换新稿的品牌簇,两半拼接使「字标底↔面板顶」间距变成 **92 / 131.65** 设计px(稿内为 20 / 25.65),实机肉眼可见一条空白。修正后间距回到稿值;面板 500→440 少掉的 60 落到底部留白(90 / 175,比稿内多 60)——审图拍板「方案 B」,未采纳「品牌簇整体下移 60」的方案 A。`DESIGN.md §16.2` 表与「60 去向」条目、§16 末尾勘误块 (6) 已就地更新;`loginSkinLayout.test.ts` 新增三条不变式:「间距上界不变式」(等于稿值,替代原先只判不重叠的下界)、「锚常量连续性不变式」(dh=1334 上下不跳变)、「间距不变式(短屏以下分支)」(dh∈[850,1334) 采样点面板顶不得压到字标底),防再次只改一半、也防窄屏压盖回归。pad 竖屏不受影响(无新稿帧、品牌簇未换基准,保持 621 / 158)。
- **2026-07-28**:`DESIGN.md §2` 语义色清单新增警告橙合法消费者「workflow agent 状态方块条的运行中格子」(8×8px 方块,后台任务面板详情 + workflow 聊天卡;done/failed/queued 各走自己的语义 token),并明确「不引入新 token 的消费者由 §2 清单登记即可、需要新 token 才必须先进 §10 豁免表」;`DESIGN.md §5` 新增小例外「status micro-cells(2px)」——≤8px 的非交互状态方块保留 2px 圆角(方块条格子与 SystemCard 分类方块),档位圆角在该尺寸会把方块变成圆点、丢掉大编队一眼总览的「方块条」读法,范围严格限定非交互 / ≤8px / 仅状态,按钮·标签·行·徽章·容器一律仍走三档。
- **2026-07-28(勘误:手机端跳过登录剥离)**:手机端「跳过登录」与无账号通路整体从登录改版中剥离(2026-07-24「手机 / pad 必须有账号」拍板仍有效,07-27 的推翻缺产品侧确认);手机端只保留纯视觉改版(品牌簇新稿基准 + 避脸),面板 / 组高 / 圆钮行 / 协议行 / error 槽 / 键盘停靠锚全部回到 main 等价值。`DESIGN.md §16` 末尾新增勘误块界定「哪些值只对桌面成立」,详情与依据归档至 [`design-decision-log.md`](./design-decision-log.md)「2026-07-28」条。
diff --git a/i18n/GLOSSARY.md b/i18n/GLOSSARY.md
index 84a3d34788..f95b6350ea 100644
--- a/i18n/GLOSSARY.md
+++ b/i18n/GLOSSARY.md
@@ -239,6 +239,10 @@ WebAuthn 可发现凭证的用户可见名称,采用 Apple、Google 与 Micros
右侧栏插件面板页签的图钉:钉住 = 面板在所有对话中保留。动词对:Pin=钉住 / Unpin=取消钉住。2026-07-31 随图钉功能提出,待裁决。
+### Process
+
+OS 进程语境(资源用量面板、浏览器 guest 进程、终端)。注意与 Thread→任务(消息流语境)区分:资源用量面板刻意不展示 OS 线程数,避免「线程」撞上 Thread 的既定裁决;若未来要展示,需为 OS thread 立同形异义条目再谈。
+
### Region badge
桌面登录页标题旁的品牌红胶囊(DESIGN.md §16.3),指徽标这个 UI 元素本身。徽标上的标签值另立条目(region-code-cn / region-code-dev)——本条 en 为 Region badge、各语言译文均非英文原词,caseStandardFor 天然返回 null,所以本条约束不到标签值,也无需写 checkCase。作为待产品裁决术语登记:尚未拍板是否改为可译文案(如「中国大陆版 / Mainland China」),先登记以免后续界面自造“国内版/中国版/开发版”等多套说法。
@@ -255,6 +259,10 @@ dev 版登录页区域徽标上的标签值(DESIGN.md §16.3),四语同值
已确定禁用:`开发版(仅当英文含 Dev)`(zh-CN)、`開発版(仅当英文含 Dev)`(ja)、`개발판(仅当英文含 Dev)`(ko)
+### Resource usage
+
+右栏「资源用量」面板(对标 Chromium 任务管理器,展示本机进程 CPU/内存并可终止 Agent 进程)。命名裁决:不可叫「任务管理器」——Session→任务 已 decided,「任务管理器」会被读成管理左侧任务列表;「监控/监视」有隐私负面语感判例(见 shortcut listener permission 条目),弃用。「用量」对齐已裁决的 Usage→用量。
+
### Run records
日志上报文案里对「App 自身运行日志」的用户可见说法。刻意不直接叫「日志」: 设置页同屏已有「日志目录」「Debug 日志」两处指本地文件, 而这里要表达的是被上报的那部分内容(基础设施运行记录, 不含对话)。proposed: 与「日志」的分工尚未产品裁决。
diff --git a/i18n/glossary.json b/i18n/glossary.json
index d0f0793527..90dd151b2b 100644
--- a/i18n/glossary.json
+++ b/i18n/glossary.json
@@ -1335,6 +1335,28 @@
"ko": "벡터"
},
"note": "文本转成的数值向量,用于语义检索。zh-CN 用「向量」而非「嵌入」——设置页的模型分组、UnifiedModelList 的能力分类既有注释都已用「向量」,「嵌入」在中文里更容易被读成动作。指模型本身时说「向量模型」,不说「嵌入模型」。插件 cindy.embed 能力与 embedding-client 的四语文案使用。"
+ },
+ {
+ "id": "resource-usage",
+ "status": "proposed",
+ "en": "Resource usage",
+ "translations": {
+ "zh-CN": "资源用量",
+ "ja": "リソース使用量",
+ "ko": "리소스 사용량"
+ },
+ "note": "右栏「资源用量」面板(对标 Chromium 任务管理器,展示本机进程 CPU/内存并可终止 Agent 进程)。命名裁决:不可叫「任务管理器」——Session→任务 已 decided,「任务管理器」会被读成管理左侧任务列表;「监控/监视」有隐私负面语感判例(见 shortcut listener permission 条目),弃用。「用量」对齐已裁决的 Usage→用量。"
+ },
+ {
+ "id": "process",
+ "status": "proposed",
+ "en": "Process",
+ "translations": {
+ "zh-CN": "进程",
+ "ja": "プロセス",
+ "ko": "프로세스"
+ },
+ "note": "OS 进程语境(资源用量面板、浏览器 guest 进程、终端)。注意与 Thread→任务(消息流语境)区分:资源用量面板刻意不展示 OS 线程数,避免「线程」撞上 Thread 的既定裁决;若未来要展示,需为 OS thread 立同形异义条目再谈。"
}
]
}
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index ab80f3c663..0337a8e926 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -2978,7 +2978,13 @@ describe('DeviceLinkClient', () => {
expect(h.current().sent.some((env) => env.kind === 'presence-set')).toBe(false);
h.current().bufferedAmount = 0;
- await tick(10);
+ for (
+ let attempt = 0;
+ attempt < 40 && !h.current().sent.some((env) => env.kind === 'presence-set');
+ attempt += 1
+ ) {
+ await tick(10);
+ }
expect(h.current().sent.filter((env) => env.kind === 'presence-set')).toEqual([
expect.objectContaining({
payload: {
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 0c2e4048fb..01ad962864 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -239,6 +239,19 @@ export interface CodexExtraSpawnConfig {
codexRemoteCompactionProviderId?: string;
}
+export type CodexAppServerProcessRole = 'task-host' | 'control-plane-service';
+
+export interface CodexAppServerProcessRegistration {
+ pid: number;
+ role: CodexAppServerProcessRole;
+}
+
+export interface LocalAgentProcessRegistration {
+ pid: number;
+ kind: 'claude' | 'pi';
+ role: 'task-host' | 'control-plane-service';
+}
+
export interface CodexLocalCredentialModeSwitchContext {
fromMode?: AgentCredentialMode;
/**
@@ -480,6 +493,22 @@ export interface AgentDeps {
},
) => Promise<CodexExtraSpawnConfig>;
+ /**
+ * Codex 专用:登记本机 stdio app-server 的 PID 与职责。
+ * 返回 disposer 时会跟随 transport close 调用;远端 SSH transport 不触发。
+ */
+ registerLocalCodexAppServerProcess?: (
+ info: CodexAppServerProcessRegistration,
+ ) => void | (() => void);
+
+ /**
+ * Register a locally spawned Claude/Pi root process with the host. The returned
+ * disposer follows that exact process generation; remote transports never call it.
+ */
+ registerLocalAgentProcess?: (
+ info: LocalAgentProcessRegistration,
+ ) => void | (() => void);
+
/**
* Codex 本地 shared app-server 凭证形态要切换前的宿主协调点。
*
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index b20433ead8..62e3a2278c 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -40,6 +40,7 @@ import type {
Settings,
} from '@anthropic-ai/claude-agent-sdk';
import { discoverSubagentDefinitions } from './subagent-definitions.js';
+import { spawnObservedClaudeProcess } from './local-process-spawn.js';
import {
reportSubagentModelDiagnostics,
resolveSubagentModelDefault,
@@ -2818,6 +2819,21 @@ export class ClaudeCodeAgent extends BaseAgent {
...(finalResumeAt ? { resumeSessionAt: finalResumeAt } : {}),
...(finalFork ? { forkSession: true } : {}),
env,
+ ...(this.deps.registerLocalAgentProcess
+ ? {
+ spawnClaudeCodeProcess: (spawnOptions) =>
+ spawnObservedClaudeProcess({
+ spawnOptions,
+ registerProcess: (pid) =>
+ this.deps.registerLocalAgentProcess?.({
+ pid,
+ kind: 'claude',
+ role: 'task-host',
+ }),
+ onStderr: vo.onStderrLine as ((line: string) => void) | undefined,
+ }),
+ }
+ : {}),
// 订阅 token 到期续命回调 —— 仅当本次 spawn 实际注入了订阅 OAuth token
// (oauth-spawn, 见 desktop auth-adapters getAuthEnv)且 host 实现了强刷时接线。
// cc 侧 turn 中途 401 会发 oauth_token_refresh control 请求, SDK 调本回调向
diff --git a/packages/maker-core/src/agents/claude-code/local-process-spawn.test.ts b/packages/maker-core/src/agents/claude-code/local-process-spawn.test.ts
new file mode 100644
index 0000000000..abdff32582
--- /dev/null
+++ b/packages/maker-core/src/agents/claude-code/local-process-spawn.test.ts
@@ -0,0 +1,81 @@
+import { EventEmitter } from 'node:events';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ spawn: vi.fn() }));
+
+vi.mock('node:child_process', () => ({ spawn: mocks.spawn }));
+
+import { spawnObservedClaudeProcess } from './local-process-spawn.js';
+
+function makeChild(pid = 4321) {
+ const child = new EventEmitter() as EventEmitter & {
+ pid: number;
+ stdin: EventEmitter;
+ stdout: EventEmitter;
+ stderr: EventEmitter;
+ killed: boolean;
+ exitCode: number | null;
+ kill: ReturnType<typeof vi.fn>;
+ };
+ child.pid = pid;
+ child.stdin = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.killed = false;
+ child.exitCode = null;
+ child.kill = vi.fn();
+ return child;
+}
+
+function spawnProcess(overrides: {
+ registerProcess?: (pid: number) => void | (() => void);
+ onStderr?: (chunk: string) => void;
+} = {}) {
+ return spawnObservedClaudeProcess({
+ spawnOptions: {
+ command: '/claude',
+ args: ['--output-format', 'stream-json'],
+ cwd: '/work',
+ env: {},
+ signal: new AbortController().signal,
+ },
+ ...overrides,
+ });
+}
+
+beforeEach(() => {
+ mocks.spawn.mockReset();
+});
+
+describe('spawnObservedClaudeProcess', () => {
+ it('registers the concrete PID and disposes that generation once', () => {
+ const child = makeChild();
+ mocks.spawn.mockReturnValue(child);
+ const dispose = vi.fn();
+ const registerProcess = vi.fn(() => dispose);
+
+ spawnProcess({ registerProcess });
+ expect(registerProcess).toHaveBeenCalledWith(4321);
+
+ child.emit('exit', 0, null);
+ child.emit('error', new Error('late error'));
+ expect(dispose).toHaveBeenCalledOnce();
+ });
+
+ it('drains and forwards stderr without making observer failures fatal', () => {
+ const child = makeChild();
+ mocks.spawn.mockReturnValue(child);
+ const onStderr = vi.fn();
+
+ expect(() =>
+ spawnProcess({
+ registerProcess: () => {
+ throw new Error('observer failed');
+ },
+ onStderr,
+ }),
+ ).not.toThrow();
+ child.stderr.emit('data', Buffer.from('diagnostic'));
+ expect(onStderr).toHaveBeenCalledWith('diagnostic');
+ });
+});
diff --git a/packages/maker-core/src/agents/claude-code/local-process-spawn.ts b/packages/maker-core/src/agents/claude-code/local-process-spawn.ts
new file mode 100644
index 0000000000..f59a21a9cf
--- /dev/null
+++ b/packages/maker-core/src/agents/claude-code/local-process-spawn.ts
@@ -0,0 +1,52 @@
+import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
+
+import type { SpawnOptions, SpawnedProcess } from '@anthropic-ai/claude-agent-sdk';
+
+export interface ObservedClaudeProcessOptions {
+ spawnOptions: SpawnOptions;
+ registerProcess?: (pid: number) => void | (() => void);
+ onStderr?: (chunk: string) => void;
+}
+
+/** Mirror the SDK's local spawn while exposing one concrete process generation. */
+export function spawnObservedClaudeProcess(
+ opts: ObservedClaudeProcessOptions,
+): SpawnedProcess {
+ const child: ChildProcessWithoutNullStreams = spawn(
+ opts.spawnOptions.command,
+ opts.spawnOptions.args,
+ {
+ cwd: opts.spawnOptions.cwd,
+ env: opts.spawnOptions.env,
+ signal: opts.spawnOptions.signal,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ windowsHide: true,
+ },
+ );
+ let disposeRegistration: (() => void) | undefined;
+ if (child.pid != null && child.pid > 0) {
+ try {
+ const dispose = opts.registerProcess?.(child.pid);
+ if (typeof dispose === 'function') disposeRegistration = dispose;
+ } catch {
+ // Observation failures must not block Claude startup. Missing registry state
+ // only makes this process fail closed for termination.
+ }
+ }
+
+ let registrationDisposed = false;
+ const disposeOnce = (): void => {
+ if (registrationDisposed) return;
+ registrationDisposed = true;
+ try { disposeRegistration?.(); } catch { /* best-effort cleanup */ }
+ disposeRegistration = undefined;
+ };
+ child.once('exit', disposeOnce);
+ child.once('error', disposeOnce);
+ child.stderr.on('data', (chunk: Buffer) => {
+ // A custom SDK spawn owns stderr forwarding. Always drain the pipe so verbose
+ // Claude output cannot deadlock when no callback is installed.
+ opts.onStderr?.(chunk.toString('utf8'));
+ });
+ return child;
+}
diff --git a/packages/maker-core/src/agents/codex/app-server/stdioTransport.test.ts b/packages/maker-core/src/agents/codex/app-server/stdioTransport.test.ts
new file mode 100644
index 0000000000..0ef81cb884
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/app-server/stdioTransport.test.ts
@@ -0,0 +1,95 @@
+import { EventEmitter } from 'node:events';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ spawn: vi.fn(),
+ createInterface: vi.fn(),
+}));
+
+vi.mock('node:child_process', () => ({ spawn: mocks.spawn }));
+vi.mock('node:readline', () => ({ createInterface: mocks.createInterface }));
+
+import { createStdioTransport } from './stdioTransport.js';
+
+function makeEmitterStream() {
+ const stream = new EventEmitter() as EventEmitter & { setEncoding: ReturnType<typeof vi.fn> };
+ stream.setEncoding = vi.fn();
+ return stream;
+}
+
+function makeChild(pid = 4321) {
+ const child = new EventEmitter() as EventEmitter & {
+ pid: number;
+ stdout: ReturnType<typeof makeEmitterStream>;
+ stderr: ReturnType<typeof makeEmitterStream>;
+ stdin: {
+ writable: boolean;
+ write: ReturnType<typeof vi.fn>;
+ end: ReturnType<typeof vi.fn>;
+ };
+ exitCode: number | null;
+ signalCode: string | null;
+ kill: ReturnType<typeof vi.fn>;
+ };
+ child.pid = pid;
+ child.stdout = makeEmitterStream();
+ child.stderr = makeEmitterStream();
+ child.stdin = {
+ writable: true,
+ write: vi.fn((_line, _encoding, callback: (error?: Error) => void) => {
+ callback();
+ return true;
+ }),
+ end: vi.fn(),
+ };
+ child.exitCode = null;
+ child.signalCode = null;
+ child.kill = vi.fn();
+ return child;
+}
+
+beforeEach(() => {
+ const readline = new EventEmitter() as EventEmitter & { close: ReturnType<typeof vi.fn> };
+ readline.close = vi.fn();
+ mocks.createInterface.mockReset().mockReturnValue(readline);
+ mocks.spawn.mockReset();
+});
+
+describe('createStdioTransport process observer', () => {
+ it('spawn 时登记一次,主动 close 时只清理一次', async () => {
+ const child = makeChild();
+ mocks.spawn.mockReturnValue(child);
+ const dispose = vi.fn();
+ const onProcessSpawned = vi.fn(() => dispose);
+ const transport = createStdioTransport({ binaryPath: '/codex', onProcessSpawned });
+
+ expect(onProcessSpawned).toHaveBeenCalledWith(4321);
+ await transport.close();
+ await transport.close();
+ expect(dispose).toHaveBeenCalledOnce();
+ });
+
+ it('自然退出时清理;随后 close 不重复清理', async () => {
+ const child = makeChild();
+ mocks.spawn.mockReturnValue(child);
+ const dispose = vi.fn();
+ const transport = createStdioTransport({
+ binaryPath: '/codex',
+ onProcessSpawned: () => dispose,
+ });
+
+ child.emit('exit', 0, null);
+ await transport.close();
+ expect(dispose).toHaveBeenCalledOnce();
+ });
+
+ it('观察器抛错不影响 transport 启动', () => {
+ mocks.spawn.mockReturnValue(makeChild());
+ expect(() => createStdioTransport({
+ binaryPath: '/codex',
+ onProcessSpawned: () => {
+ throw new Error('observer failed');
+ },
+ })).not.toThrow();
+ });
+});
diff --git a/packages/maker-core/src/agents/codex/app-server/stdioTransport.ts b/packages/maker-core/src/agents/codex/app-server/stdioTransport.ts
index 42f20a3755..7eadfef4e7 100644
--- a/packages/maker-core/src/agents/codex/app-server/stdioTransport.ts
+++ b/packages/maker-core/src/agents/codex/app-server/stdioTransport.ts
@@ -30,6 +30,8 @@ export interface StdioTransportOptions {
env?: NodeJS.ProcessEnv;
/** `app-server` 子命令之前/之后的额外参数 (一般用于注入 `-c` overrides)。 */
extraArgs?: string[];
+ /** 本地进程生命周期观察器;仅用于宿主诊断,不得影响 transport 启动。 */
+ onProcessSpawned?: (pid: number) => void | (() => void);
}
export function createStdioTransport(opts: StdioTransportOptions): Transport {
@@ -62,6 +64,15 @@ export function createStdioTransport(opts: StdioTransportOptions): Transport {
// Linux/macOS: 跟父进程同 process group, 父进程退出时一并被收割。
detached: false,
});
+ let disposeProcessRegistration: (() => void) | undefined;
+ if (child.pid != null && child.pid > 0) {
+ try {
+ const dispose = opts.onProcessSpawned?.(child.pid);
+ if (typeof dispose === 'function') disposeProcessRegistration = dispose;
+ } catch {
+ // 诊断观察器失败不能阻断 app-server;进程归属仍由既有扫描安全边界判断。
+ }
+ }
// stdout NDJSON 增量解析: readline 处理 \r\n / \n / EOF, 单行触发 callback。
child.stdout.setEncoding('utf8');
@@ -97,6 +108,8 @@ export function createStdioTransport(opts: StdioTransportOptions): Transport {
if (closed) return;
closed = true;
try { rl.close(); } catch { /* already closed */ }
+ try { disposeProcessRegistration?.(); } catch { /* best-effort diagnostic cleanup */ }
+ disposeProcessRegistration = undefined;
for (const cb of closeHandlers) {
try { cb({ reason }); } catch { /* handler should not throw */ }
}
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 28798ee3cb..0941268306 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -17,7 +17,7 @@ import type { AuthAdapter } from '../../interfaces/auth-adapter.js';
import type { AgentEvent, InteractionDecision, InteractionRequest } from '../../types/events.js';
import type { Logger } from '../../interfaces/logger.js';
-const { MockCodexTransport, createdTransports } = vi.hoisted(() => {
+const { MockCodexTransport, createdTransports, createdStdioOptions } = vi.hoisted(() => {
type LineHandler = (line: string) => void;
type StderrHandler = (line: string) => void;
type CloseHandler = (info: { reason: string }) => void;
@@ -232,11 +232,16 @@ const { MockCodexTransport, createdTransports } = vi.hoisted(() => {
}
const createdTransports: MockCodexTransport[] = [];
- return { MockCodexTransport, createdTransports };
+ const createdStdioOptions: Array<{
+ onProcessSpawned?: (pid: number) => void | (() => void);
+ }> = [];
+ return { MockCodexTransport, createdTransports, createdStdioOptions };
});
vi.mock('./app-server/stdioTransport.js', () => ({
- createStdioTransport: () => {
+ createStdioTransport: (opts: { onProcessSpawned?: (pid: number) => void | (() => void) }) => {
+ createdStdioOptions.push(opts);
+ opts.onProcessSpawned?.(7_000 + createdStdioOptions.length);
const transport = new MockCodexTransport();
createdTransports.push(transport);
return transport;
@@ -245,6 +250,7 @@ vi.mock('./app-server/stdioTransport.js', () => ({
beforeEach(() => {
createdTransports.length = 0;
+ createdStdioOptions.length = 0;
MockCodexTransport.threadSeq = 1;
MockCodexTransport.failThreadStart = false;
MockCodexTransport.dropThreadUnsubscribe = false;
@@ -2763,10 +2769,12 @@ describe('CodexAgent.refreshLocalModels', () => {
extraEnv: {},
codexProxyActive: ctx.credentialMode === 'provider-oauth',
}));
+ const registerLocalCodexAppServerProcess = vi.fn();
const agent = new CodexAgent(createDeps({}, {
onCodexLocalModelsListed,
prepareCodexLocalCredentialModeSwitch,
prepareCodexExtraSpawnConfig,
+ registerLocalCodexAppServerProcess,
}));
const xaiHandle = await agent.startSession({
sessionId: 'session-provider-oauth-before-openai-refresh',
@@ -2780,6 +2788,10 @@ describe('CodexAgent.refreshLocalModels', () => {
).resolves.toBe(true);
expect(createdTransports).toHaveLength(2);
+ expect(registerLocalCodexAppServerProcess.mock.calls).toEqual([
+ [{ pid: 7_001, role: 'task-host' }],
+ [{ pid: 7_002, role: 'control-plane-service' }],
+ ]);
expect(createdTransports[0].closed).toBe(false);
expect(prepareCodexLocalCredentialModeSwitch).not.toHaveBeenCalled();
expect(createdTransports[0].lines.some((line) => (
@@ -4219,7 +4231,7 @@ describe('CodexAgent MCP thread context hooks', () => {
expect(createdTransports[0].closed).toBe(true);
});
- it('runs utility calls on the shared local host instead of spawning another local host', async () => {
+ it('keeps utility calls on the task host and account RPCs on an isolated control-plane host', async () => {
const agent = new CodexAgent(createDeps());
const handle = await agent.startSession({
@@ -4235,10 +4247,12 @@ describe('CodexAgent MCP thread context hooks', () => {
rateLimitsByLimitId: null,
rateLimitResetCredits: { availableCount: 2, credits: null },
};
- createdTransports[0].setMockResponse(Method.AccountRateLimitsRead, { result: rateLimits });
- createdTransports[0].setMockResponse(Method.AccountRateLimitResetCreditConsume, {
- result: { outcome: 'reset' },
- });
+ MockCodexTransport.onCreate = (transport) => {
+ transport.setMockResponse(Method.AccountRateLimitsRead, { result: rateLimits });
+ transport.setMockResponse(Method.AccountRateLimitResetCreditConsume, {
+ result: { outcome: 'reset' },
+ });
+ };
await agent.setMemory(true);
const pushCountAfterSet = createdTransports[0].lines
@@ -4259,12 +4273,13 @@ describe('CodexAgent MCP thread context hooks', () => {
creditId: 'credit-earliest',
})).resolves.toEqual({ outcome: 'reset' });
- expect(createdTransports).toHaveLength(1);
+ expect(createdTransports).toHaveLength(2);
expect(createdTransports[0].lines.some((line) => line.includes('skills/list'))).toBe(true);
expect(createdTransports[0].lines.some((line) => line.includes('config/read'))).toBe(true);
expect(createdTransports[0].lines.some((line) => line.includes('memory/reset'))).toBe(true);
- expect(createdTransports[0].lines.some((line) => line.includes('account/rateLimits/read'))).toBe(true);
- expect(createdTransports[0].lines.some((line) => (
+ expect(createdTransports[0].lines.some((line) => line.includes('account/rateLimits/read'))).toBe(false);
+ expect(createdTransports[1].lines.some((line) => line.includes('account/rateLimits/read'))).toBe(true);
+ expect(createdTransports[1].lines.some((line) => (
line.includes('account/rateLimitResetCredit/consume')
&& line.includes('018f4ec7-c6d8-7f10-8d43-9f8791d33000')
&& line.includes('credit-earliest')
@@ -4349,7 +4364,15 @@ describe('CodexAgent MCP thread context hooks', () => {
result: { outcome: 'reset' },
});
};
- const agent = new CodexAgent(createDeps());
+ const registerLocalCodexAppServerProcess = vi.fn();
+ const prepareCodexExtraSpawnConfig = vi.fn(async () => ({
+ extraArgs: [],
+ extraEnv: {},
+ }));
+ const agent = new CodexAgent(createDeps({}, {
+ registerLocalCodexAppServerProcess,
+ prepareCodexExtraSpawnConfig,
+ }));
await expect(agent.readAccountRateLimits()).resolves.toEqual(rateLimits);
await expect(agent.consumeAccountRateLimitResetCredit({
@@ -4357,12 +4380,32 @@ describe('CodexAgent MCP thread context hooks', () => {
})).resolves.toEqual({ outcome: 'reset' });
expect(createdTransports).toHaveLength(1);
+ expect(registerLocalCodexAppServerProcess).toHaveBeenCalledWith({
+ pid: 7_001,
+ role: 'control-plane-service',
+ });
+ expect(prepareCodexExtraSpawnConfig).toHaveBeenCalledWith([], {
+ remoteHostId: undefined,
+ credentialMode: 'oauth-bearer',
+ hostPurpose: 'control-plane',
+ });
+ expect(Array.from(
+ (agent as unknown as { hosts: Map<string, unknown> }).hosts.keys(),
+ )).toEqual(['local-control:oauth-bearer']);
expect(createdTransports[0].lines[0]).toContain('initialize');
expect(createdTransports[0].lines.some((line) => line.includes('account/rateLimits/read'))).toBe(true);
await agent.dispose();
});
- it('refuses account reset RPCs on a differently-authenticated active host', async () => {
+ it('keeps a differently-authenticated task host alive while account RPCs use control-plane', async () => {
+ const rateLimits = {
+ rateLimits: { planType: 'plus', primary: { usedPercent: 42, windowMinutes: 300 } },
+ rateLimitsByLimitId: null,
+ rateLimitResetCredits: { availableCount: 1, credits: null },
+ };
+ MockCodexTransport.onCreate = (transport) => {
+ transport.setMockResponse(Method.AccountRateLimitsRead, { result: rateLimits });
+ };
const agent = new CodexAgent(createDeps());
const handle = await agent.startSession({
sessionId: 'session-gateway-host',
@@ -4371,9 +4414,12 @@ describe('CodexAgent MCP thread context hooks', () => {
workingDir: '/repo',
});
- await expect(agent.readAccountRateLimits()).rejects.toThrow(/active Codex session/i);
- expect(createdTransports).toHaveLength(1);
+ await expect(agent.readAccountRateLimits()).resolves.toEqual(rateLimits);
+ expect(createdTransports).toHaveLength(2);
expect(createdTransports[0].closed).toBe(false);
+ expect(createdTransports[1].lines.some((line) => (
+ line.includes('account/rateLimits/read')
+ ))).toBe(true);
await handle.close();
await agent.dispose();
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index dfd1c941af..455faeac2f 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -2114,7 +2114,11 @@ export class CodexAgent extends BaseAgent {
/** Start the local OAuth host used by non-model account control-plane RPCs. */
private async getStartedAccountHost(): Promise<AppServerHost> {
- const host = await this.getHost(undefined, 'oauth-bearer');
+ const credentialMode = 'oauth-bearer';
+ const host = await this.getHost(undefined, credentialMode, {
+ keyOverride: localControlPlaneHostKey(credentialMode),
+ hostPurpose: 'control-plane',
+ });
const init = await host.ensureStarted();
if (init.codexHome) this.codexHome = init.codexHome;
return host;
@@ -2413,6 +2417,14 @@ export class CodexAgent extends BaseAgent {
binaryPath,
env,
extraArgs,
+ onProcessSpawned: (pid) =>
+ this.deps.registerLocalCodexAppServerProcess?.({
+ pid,
+ role:
+ hostPurpose === 'control-plane'
+ ? 'control-plane-service'
+ : 'task-host',
+ }),
});
}
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 82b2b970bc..61007e1d79 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -1214,6 +1214,12 @@ export class PiAgent extends BaseAgent {
cwd: opts.workingDir,
env: spawnEnv,
logger: this.deps.logger,
+ onProcessSpawned: (pid) =>
+ this.deps.registerLocalAgentProcess?.({
+ pid,
+ kind: 'pi',
+ role: 'task-host',
+ }),
onEvent: (event: PiRpcEvent) => {
if (event.type === 'extension_ui_request') {
this.handleExtensionUiRequest(event, proc, () => ({
@@ -2119,6 +2125,12 @@ export class PiAgent extends BaseAgent {
PI_CODING_AGENT_DIR: forkHome,
},
logger: log,
+ onProcessSpawned: (pid) =>
+ this.deps.registerLocalAgentProcess?.({
+ pid,
+ kind: 'pi',
+ role: 'control-plane-service',
+ }),
onEvent: () => {},
onExit: () => {},
});
diff --git a/packages/maker-core/src/agents/pi/rpc-client.test.ts b/packages/maker-core/src/agents/pi/rpc-client.test.ts
new file mode 100644
index 0000000000..928307fbf8
--- /dev/null
+++ b/packages/maker-core/src/agents/pi/rpc-client.test.ts
@@ -0,0 +1,80 @@
+import { EventEmitter } from 'node:events';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({ spawn: vi.fn() }));
+
+vi.mock('node:child_process', () => ({ spawn: mocks.spawn }));
+
+import { PiRpcProcess } from './rpc-client.js';
+
+function makeStream() {
+ return new EventEmitter();
+}
+
+function makeChild(pid = 4321) {
+ const child = new EventEmitter() as EventEmitter & {
+ pid: number;
+ stdout: EventEmitter;
+ stderr: EventEmitter;
+ stdin: { write: ReturnType<typeof vi.fn> };
+ kill: ReturnType<typeof vi.fn>;
+ };
+ child.pid = pid;
+ child.stdout = makeStream();
+ child.stderr = makeStream();
+ child.stdin = { write: vi.fn() };
+ child.kill = vi.fn();
+ return child;
+}
+
+function createProcess(onProcessSpawned?: (pid: number) => void | (() => void)) {
+ const logger = {
+ trace: vi.fn(),
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ fatal: vi.fn(),
+ child: vi.fn(),
+ };
+ logger.child.mockReturnValue(logger);
+ return new PiRpcProcess({
+ binaryPath: '/pi',
+ args: ['--mode', 'rpc'],
+ cwd: '/work',
+ env: {},
+ logger,
+ onEvent: vi.fn(),
+ onExit: vi.fn(),
+ onProcessSpawned,
+ });
+}
+
+beforeEach(() => {
+ mocks.spawn.mockReset();
+});
+
+describe('PiRpcProcess process observer', () => {
+ it('registers the concrete PID and disposes that generation once on close', () => {
+ const child = makeChild();
+ mocks.spawn.mockReturnValue(child);
+ const dispose = vi.fn();
+ const onProcessSpawned = vi.fn(() => dispose);
+
+ createProcess(onProcessSpawned);
+ expect(onProcessSpawned).toHaveBeenCalledWith(4321);
+
+ child.emit('close', 0, null);
+ child.emit('close', 0, null);
+ expect(dispose).toHaveBeenCalledOnce();
+ });
+
+ it('observer failure does not block process startup', () => {
+ mocks.spawn.mockReturnValue(makeChild());
+ expect(() =>
+ createProcess(() => {
+ throw new Error('observer failed');
+ }),
+ ).not.toThrow();
+ });
+});
diff --git a/packages/maker-core/src/agents/pi/rpc-client.ts b/packages/maker-core/src/agents/pi/rpc-client.ts
index 3c1cef337b..bf8a7c659b 100644
--- a/packages/maker-core/src/agents/pi/rpc-client.ts
+++ b/packages/maker-core/src/agents/pi/rpc-client.ts
@@ -40,6 +40,8 @@ export interface PiRpcSpawnOptions {
/** 进程退出回调(exit code / signal;正常 close() 也会触发)。 */
onExit: (info: { code: number | null; signal: NodeJS.Signals | null }) => void;
onStderrLine?: (line: string) => void;
+ /** 本地进程生命周期观察器;返回值在该 spawn 的 error/close 时幂等调用。 */
+ onProcessSpawned?: (pid: number) => void | (() => void);
}
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
@@ -55,6 +57,7 @@ export class PiRpcProcess {
}>();
private closed = false;
private readonly logger: Logger;
+ private disposeProcessRegistration: (() => void) | undefined;
constructor(private readonly opts: PiRpcSpawnOptions) {
this.logger = opts.logger;
@@ -63,6 +66,15 @@ export class PiRpcProcess {
env: opts.env as NodeJS.ProcessEnv,
stdio: ['pipe', 'pipe', 'pipe'],
});
+ if (this.child.pid != null && this.child.pid > 0) {
+ try {
+ const dispose = opts.onProcessSpawned?.(this.child.pid);
+ if (typeof dispose === 'function') this.disposeProcessRegistration = dispose;
+ } catch {
+ // Observation failures must not block Pi startup. The process simply remains
+ // non-terminable in the resource usage panel.
+ }
+ }
attachJsonlReader(this.child.stdout, (line) => this.handleStdoutLine(line));
attachJsonlReader(this.child.stderr, (line) => {
@@ -72,16 +84,24 @@ export class PiRpcProcess {
});
this.child.on('error', (err) => {
+ this.disposeRegistration();
this.logger.error('pi process error', { message: err.message });
this.failAllPending(new Error(`pi process error: ${err.message}`));
});
this.child.on('close', (code, signal) => {
+ this.disposeRegistration();
this.closed = true;
this.failAllPending(new Error(`pi process exited (code=${code}, signal=${signal})`));
opts.onExit({ code, signal });
});
}
+ private disposeRegistration(): void {
+ const dispose = this.disposeProcessRegistration;
+ this.disposeProcessRegistration = undefined;
+ try { dispose?.(); } catch { /* best-effort diagnostic cleanup */ }
+ }
+
get pid(): number | undefined {
return this.child.pid ?? undefined;
}
diff --git a/scripts/__tests__/test-workspaces.test.mjs b/scripts/__tests__/test-workspaces.test.mjs
index 00939ef674..8adeea4923 100644
--- a/scripts/__tests__/test-workspaces.test.mjs
+++ b/scripts/__tests__/test-workspaces.test.mjs
@@ -938,6 +938,20 @@ test("test gate lock decision prefers an existing owner over an earlier free por
assert.equal(classifyTestGateLockProbeError("ETIMEDOUT"), "collision");
});
+test("test gate lock rejects invalid port counts before deriving candidates", async () => {
+ for (const lockPortCount of [0, -1, 1.5, Number.NaN]) {
+ await assert.rejects(
+ () =>
+ acquireTestGateLock({
+ repoRoot: "unused",
+ owner: { pid: 99, tier: "unit", cwd: "unused" },
+ lockPortCount,
+ }),
+ /lockPortCount must be a positive integer/,
+ );
+ }
+});
+
test("test gate lock reports the holder, waits, and acquires after release", async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "test-gate-lock-"));
let probeRound = 0;
@@ -994,6 +1008,12 @@ test("test gate lock reports the holder, waits, and acquires after release", asy
// fails for reasons unrelated to the lock protocol.
const REAL_LOCK_WAIT_WINDOW_MS = 30_000;
const REAL_LOCK_ACQUIRE_TIMEOUT_MS = 60_000;
+// Windows assigns 49152+ as its default dynamic client-port range. Keep this
+// real socket test outside that range so unrelated CI network traffic cannot
+// occupy all deterministic candidates while preserving the production range.
+const REAL_LOCK_TEST_PORT_START = 10_000;
+const REAL_LOCK_TEST_PORT_COUNT = 30_000;
+const REAL_LOCK_TEST_PORT_STRIDE = 997;
function raceWithDeadline(candidates, deadlineMs, deadlineValue) {
let timer;
@@ -1017,11 +1037,17 @@ test("two real test gate lock holders serialize on the same identity", async ()
firstLock = await acquireTestGateLock({
repoRoot: root,
owner: { pid: 41, tier: "unit", cwd: path.join(root, "first") },
+ lockPortStart: REAL_LOCK_TEST_PORT_START,
+ lockPortCount: REAL_LOCK_TEST_PORT_COUNT,
+ lockPortStride: REAL_LOCK_TEST_PORT_STRIDE,
output: () => {},
});
secondLockPromise = acquireTestGateLock({
repoRoot: root,
owner: { pid: 42, tier: "db", cwd: path.join(root, "second") },
+ lockPortStart: REAL_LOCK_TEST_PORT_START,
+ lockPortCount: REAL_LOCK_TEST_PORT_COUNT,
+ lockPortStride: REAL_LOCK_TEST_PORT_STRIDE,
timeoutMs: REAL_LOCK_ACQUIRE_TIMEOUT_MS,
retryDelayMs: 10,
output: reportWaiting,
@@ -1043,7 +1069,10 @@ test("two real test gate lock holders serialize on the same identity", async ()
await firstLock.release();
firstLock = undefined;
const secondLock = await secondLockPromise;
- assert.ok(secondLock.port >= 49_152);
+ assert.ok(secondLock.port >= REAL_LOCK_TEST_PORT_START);
+ assert.ok(
+ secondLock.port < REAL_LOCK_TEST_PORT_START + REAL_LOCK_TEST_PORT_COUNT,
+ );
} finally {
// Order matters: releasing the first lock lets the second acquisition
// settle immediately instead of waiting out its own timeout.
diff --git a/scripts/test-gate-lock.mjs b/scripts/test-gate-lock.mjs
index d7e15d9d41..72a9a745d3 100644
--- a/scripts/test-gate-lock.mjs
+++ b/scripts/test-gate-lock.mjs
@@ -84,9 +84,15 @@ export function testGateLockIdentity(commonDir, platform = process.platform) {
.digest("hex");
}
-function lockPort(identity, candidate) {
- const baseOffset = Number.parseInt(identity.slice(0, 8), 16) % LOCK_PORT_COUNT;
- return LOCK_PORT_START + ((baseOffset + candidate) % LOCK_PORT_COUNT);
+function lockPort(
+ identity,
+ candidate,
+ portStart = LOCK_PORT_START,
+ portCount = LOCK_PORT_COUNT,
+ portStride = 1,
+) {
+ const baseOffset = Number.parseInt(identity.slice(0, 8), 16) % portCount;
+ return portStart + ((baseOffset + candidate * portStride) % portCount);
}
export function classifyTestGateLockProbeError(code) {
@@ -227,6 +233,9 @@ function createTimeoutError(waitedMs, owner) {
export async function acquireTestGateLock({
repoRoot,
owner,
+ lockPortStart = LOCK_PORT_START,
+ lockPortCount = LOCK_PORT_COUNT,
+ lockPortStride = 1,
timeoutMs = DEFAULT_TEST_GATE_LOCK_TIMEOUT_MS,
retryDelayMs = RETRY_DELAY_MS,
waitReportIntervalMs = WAIT_REPORT_INTERVAL_MS,
@@ -238,11 +247,21 @@ export async function acquireTestGateLock({
} = {}) {
if (!repoRoot) throw new Error("repoRoot is required");
if (!owner || typeof owner !== "object") throw new Error("owner is required");
+ if (!Number.isInteger(lockPortCount) || lockPortCount <= 0) {
+ throw new Error("lockPortCount must be a positive integer");
+ }
const commonDir = await resolveTestGateCommonDir(repoRoot);
const identity = testGateLockIdentity(commonDir);
const ports = Array.from(
{ length: LOCK_PORT_CANDIDATES },
- (_, candidate) => lockPort(identity, candidate),
+ (_, candidate) =>
+ lockPort(
+ identity,
+ candidate,
+ lockPortStart,
+ lockPortCount,
+ lockPortStride,
+ ),
);
const banner = JSON.stringify({
protocol: LOCK_PROTOCOL,