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): 资源监视器 Agent 进程显示所属任务标题

Zhang Yunjin87af54a58a62
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index a2149567dd..ce30dce344 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -52,6 +52,7 @@ import {
} from './worktree/recycleMaintenance';
import { requestWorktreeRecycle } from './worktree/managedRecycle';
import {
+ getSessionRowSnapshot,
patchSessionMetaInDb,
recycleSessionWorktreeForStatusChange,
} from './localDb/ipc/sessions';
@@ -554,6 +555,7 @@ import { reapClaudeOrphansSync } from './claude-orphan-reaper';
import { reapCodexToolTreesSync } from './codex-tool-tree-reaper';
import { startAgentProcessPriorityWatcher } from './agent-process-priority';
import { registerProcessMonitorIpc } from './process-monitor/ipc.js';
+import { createSessionLabelResolver } from './process-monitor/session-label.js';
import { disposeWindowsProcessScanWorkers } from './process-monitor/windowsProcessScanWorkerClient.js';
import {
initAppBadgeService,
@@ -2506,6 +2508,9 @@ registerMenubarIpc();
// 本产品 spawn 的 agent 根进程。见 main/process-monitor/。
registerProcessMonitorIpc({
allowsSampling: (sender) => resourceUsageWindowController.allowsProcessMonitorSampling(sender),
+ // agent 行显示承载任务标题;标题在本地库里,经 TTL 缓存解耦采样周期。见
+ // main/process-monitor/session-label.ts。
+ resolveSessionLabel: createSessionLabelResolver(),
});
// ── 主界面布局树存储 IPC──────────────────────────────────────────────
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 65736b8bae..4b95f8e009 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -1388,7 +1388,8 @@ export function getMaker(): Maker {
beforeKnownFileWrite: captureKnownFileBefore,
noteOpaqueWrite: noteOpaqueTurnChange,
},
- registerLocalAgentProcess: ({ pid, kind, role }) => registerAgentProcess(pid, kind, role),
+ registerLocalAgentProcess: ({ pid, kind, role, sessionId }) =>
+ registerAgentProcess(pid, kind, role, sessionId),
reviewAutoPermissionAction,
toolLoopReviewer: reviewToolLoop,
// 每个 session 的 cc 子进程 debug 写到 sessions/<id>/cc-debug.raw.log (logger 拼路径
@@ -2523,7 +2524,8 @@ export function getMaker(): Maker {
beforeKnownFileWrite: captureKnownFileBefore,
noteOpaqueWrite: noteOpaqueTurnChange,
},
- registerLocalAgentProcess: ({ pid, kind, role }) => registerAgentProcess(pid, kind, role),
+ registerLocalAgentProcess: ({ pid, kind, role, sessionId }) =>
+ registerAgentProcess(pid, kind, role, sessionId),
reviewAutoPermissionAction,
capabilityAdditions: {
availableModels: deriveAvailableModels(getDesktopSelectableCatalog(), 'pi'),
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
index 6a29b431d3..7eb09f28da 100644
--- 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
@@ -45,4 +45,14 @@ describe('codex process registry', () => {
disposeNew();
expect(resolveAgentProcessRegistration(202)).toBeNull();
});
+
+ it('登记的宿主 sessionId 随登记可查;未传时为 null,换 spawn 时随新值替换', () => {
+ registerAgentProcess(203, 'pi', 'task-host');
+ expect(resolveAgentProcessRegistration(203)?.sessionId).toBeNull();
+
+ registerAgentProcess(204, 'pi', 'task-host', 'session-a');
+ expect(resolveAgentProcessRegistration(204)?.sessionId).toBe('session-a');
+ registerAgentProcess(204, 'pi', 'task-host', 'session-b');
+ expect(resolveAgentProcessRegistration(204)?.sessionId).toBe('session-b');
+ });
});
diff --git a/apps/desktop/src/main/process-monitor/__tests__/ipc.test.ts b/apps/desktop/src/main/process-monitor/__tests__/ipc.test.ts
index 869d2c640d..9f8b610309 100644
--- a/apps/desktop/src/main/process-monitor/__tests__/ipc.test.ts
+++ b/apps/desktop/src/main/process-monitor/__tests__/ipc.test.ts
@@ -81,6 +81,7 @@ function register(overrides: Parameters<typeof registerProcessMonitorIpc>[0] = {
resolveAgentProcessRegistration: (pid) => ({
kind: 'claude',
role: 'task-host',
+ sessionId: null,
instanceId: `start:${pid}`,
}),
killProcessTree: vi.fn().mockReturnValue(true),
@@ -243,6 +244,38 @@ describe('process monitor IPC authorization', () => {
expect(sender.removeListener).toHaveBeenNthCalledWith(1, 'destroyed', expect.any(Function));
expect(sender.removeListener).toHaveBeenNthCalledWith(2, 'destroyed', expect.any(Function));
});
+
+ it('生产装配把 resolveSessionLabel 传入采样器,agent 条目带归属标题', async () => {
+ const sender = fakeSender();
+ register({
+ sampler: undefined,
+ platform: 'linux',
+ scanOsProcesses: vi.fn().mockResolvedValue({
+ rows: [osRow({ pid: 511, ppid: SELF_PID, cmdLineLower: 'pi-marker host' })],
+ childrenByParent: new Map(),
+ }),
+ classify: (cmd) => (cmd.includes('pi-marker') ? 'pi' : null),
+ resolveAgentProcessRegistration: (pid) => ({
+ kind: 'pi',
+ role: 'task-host',
+ sessionId: 'session-9',
+ instanceId: `start:${pid}`,
+ }),
+ resolveSessionLabel: (sessionId) =>
+ sessionId === 'session-9' ? Promise.resolve('写发布说明') : Promise.resolve(null),
+ });
+
+ await handlerFor(PROCESS_MONITOR_SUBSCRIBE_CHANNEL)({ sender });
+ await vi.waitFor(() => {
+ expect(sender.send).toHaveBeenCalled();
+ });
+ const sample = sender.send.mock.calls.at(-1)![1] as {
+ entries: Array<{ pid: number; sessionLabel?: string }>;
+ };
+ expect(sample.entries.find((entry) => entry.pid === 511)).toMatchObject({
+ sessionLabel: '写发布说明',
+ });
+ });
});
describe('terminate ownership validation', () => {
@@ -478,7 +511,7 @@ describe('terminate ownership validation', () => {
}),
classify: () => 'codex',
resolveAgentProcessRegistration: () =>
- role ? { kind: 'codex', role, instanceId: 'start:970' } : null,
+ role ? { kind: 'codex', role, sessionId: null, instanceId: 'start:970' } : null,
killProcessTree: kill,
});
expect(() =>
@@ -510,6 +543,7 @@ describe('terminate ownership validation', () => {
resolveAgentProcessRegistration: () => ({
kind: 'claude',
role: 'task-host',
+ sessionId: null,
instanceId: 'spawn:new',
}),
killProcessTree: kill,
diff --git a/apps/desktop/src/main/process-monitor/__tests__/sampler.test.ts b/apps/desktop/src/main/process-monitor/__tests__/sampler.test.ts
index b9b5396c99..4547ff4c65 100644
--- a/apps/desktop/src/main/process-monitor/__tests__/sampler.test.ts
+++ b/apps/desktop/src/main/process-monitor/__tests__/sampler.test.ts
@@ -74,7 +74,7 @@ function makeHarness(overrides: HarnessOverrides = {}) {
? 'pi'
: null;
return kind
- ? { kind, role: 'task-host', instanceId: `start:${pid}` }
+ ? { kind, role: 'task-host', sessionId: null, instanceId: `start:${pid}` }
: null;
},
selfPid: SELF_PID,
@@ -141,6 +141,7 @@ describe('createProcessMonitorSampler', () => {
resolveAgentProcessRegistration: (pid) => ({
kind: 'codex',
role: pid === 701 ? 'task-host' : 'control-plane-service',
+ sessionId: null,
instanceId: `instance:${pid}`,
}),
},
@@ -214,6 +215,43 @@ describe('createProcessMonitorSampler', () => {
});
});
+ it('agent 条目解析归属任务标题:仅登记了 sessionId 的条目,失败只丢标题', async () => {
+ const lookups: string[] = [];
+ const { sampler } = makeHarness({
+ snapshot: snapshotOf([
+ osRow({ pid: 901, ppid: SELF_PID, cmdLineLower: 'pi-marker one' }),
+ osRow({ pid: 902, ppid: SELF_PID, cmdLineLower: 'pi-marker two' }),
+ // 无归属(如 Codex 共享服务):不查询也不带标题。
+ osRow({ pid: 903, ppid: SELF_PID, cmdLineLower: 'pi-marker three' }),
+ ]),
+ deps: {
+ resolveAgentProcessRegistration: (pid) =>
+ pid === 901
+ ? { kind: 'pi', role: 'task-host', sessionId: 'session-1', instanceId: `i:${pid}` }
+ : pid === 902
+ ? { kind: 'pi', role: 'task-host', sessionId: 'session-2', instanceId: `i:${pid}` }
+ : { kind: 'pi', role: 'task-host', sessionId: null, instanceId: `i:${pid}` },
+ resolveSessionLabel: (sessionId) => {
+ lookups.push(sessionId);
+ if (sessionId === 'session-1') return Promise.resolve('修复登录页');
+ if (sessionId === 'session-2') return Promise.reject(new Error('db busy'));
+ return Promise.resolve(null);
+ },
+ },
+ });
+ expect(entryByPid(await sampler.sample(), 901)).toMatchObject({
+ sessionLabel: '修复登录页',
+ });
+ // 同 id 去重只查一次;解析失败/空标题的条目不带 sessionLabel 字段。
+ expect(lookups).toEqual(['session-1', 'session-2']);
+ expect(entryByPid(await sampler.sample(), 902)?.sessionLabel).toBeUndefined();
+ expect(entryByPid(await sampler.sample(), 903)?.sessionLabel).toBeUndefined();
+ // 采样器自身不缓存(缓存属生产装配层),每轮都对登记的 id 重新解析。
+ const afterFirstRound = lookups.length;
+ await sampler.sample();
+ expect(lookups.slice(afterFirstRound)).toEqual(['session-1', 'session-2']);
+ });
+
it('OS 扫描按周期缓存:未过期不重扫,过期后重扫', async () => {
const { state, sampler } = makeHarness();
await sampler.sample();
diff --git a/apps/desktop/src/main/process-monitor/codex-process-registry.ts b/apps/desktop/src/main/process-monitor/codex-process-registry.ts
index e39b4fd24e..70ffd87d28 100644
--- a/apps/desktop/src/main/process-monitor/codex-process-registry.ts
+++ b/apps/desktop/src/main/process-monitor/codex-process-registry.ts
@@ -14,6 +14,8 @@ import type { MonitoredAgentKind } from './agent-scan.js';
interface Registration {
kind: MonitoredAgentKind;
role: AgentProcessRole;
+ /** 承载的宿主 session id;Codex 共享服务与未知归属为 null。 */
+ sessionId: string | null;
instanceId: string;
identity: symbol;
}
@@ -23,6 +25,7 @@ const registrations = new Map<number, Registration>();
export interface AgentProcessRegistration {
kind: MonitoredAgentKind;
role: AgentProcessRole;
+ sessionId: string | null;
instanceId: string;
}
@@ -30,9 +33,16 @@ export function registerAgentProcess(
pid: number,
kind: MonitoredAgentKind,
role: AgentProcessRole,
+ sessionId?: string | null,
): () => void {
const identity = Symbol(`${kind}-process-${pid}`);
- registrations.set(pid, { kind, role, instanceId: randomUUID(), identity });
+ registrations.set(pid, {
+ kind,
+ role,
+ sessionId: sessionId ?? null,
+ instanceId: randomUUID(),
+ identity,
+ });
let disposed = false;
return () => {
if (disposed) return;
@@ -52,6 +62,7 @@ export function resolveAgentProcessRegistration(pid: number): AgentProcessRegist
return {
kind: registration.kind,
role: registration.role,
+ sessionId: registration.sessionId,
instanceId: registration.instanceId,
};
}
diff --git a/apps/desktop/src/main/process-monitor/ipc.ts b/apps/desktop/src/main/process-monitor/ipc.ts
index de8de82092..bae85247a9 100644
--- a/apps/desktop/src/main/process-monitor/ipc.ts
+++ b/apps/desktop/src/main/process-monitor/ipc.ts
@@ -70,6 +70,11 @@ export interface ProcessMonitorIpcOptions {
scanOsProcessesSync?: () => OsProcessSnapshot;
/** sampler 的异步 OS 扫描。 */
scanOsProcesses?: () => Promise<OsProcessSnapshot>;
+ /**
+ * 登记 session id → 任务标题(生产装配见 session-label.ts)。缺省 =
+ * agent 条目不带归属标题;抛错由 sampler 吞掉,只丢标题。
+ */
+ resolveSessionLabel?: (sessionId: string) => Promise<string | null> | string | null;
/** 隐藏预热窗口等 sender 可保留订阅,但 Main 不允许它触发采样或接收快照。 */
allowsSampling?: (sender: WebContents) => boolean;
classify?: (cmdLineLower: string) => MonitoredAgentKind | null;
@@ -137,6 +142,7 @@ export function registerProcessMonitorIpc(opts: ProcessMonitorIpcOptions = {}):
describeRendererProcess: describeRendererProcessByPid,
classify,
resolveAgentProcessRegistration: resolveAgentRegistration,
+ resolveSessionLabel: opts.resolveSessionLabel,
selfPid,
log,
// Windows 冷启 PowerShell 可达秒级;用户打开后的首帧只等 app.getAppMetrics,
diff --git a/apps/desktop/src/main/process-monitor/sampler.ts b/apps/desktop/src/main/process-monitor/sampler.ts
index f3dbd8393e..8e4e0e86b3 100644
--- a/apps/desktop/src/main/process-monitor/sampler.ts
+++ b/apps/desktop/src/main/process-monitor/sampler.ts
@@ -52,6 +52,11 @@ export interface ProcessMonitorSamplerDeps {
classify(cmdLineLower: string): MonitoredAgentKind | null;
/** 本地根进程的 spawn-generation 登记;未知时返回 null,并按不可终止处理。 */
resolveAgentProcessRegistration?(pid: number): AgentProcessRegistration | null;
+ /**
+ * 登记 session id → 用户可见任务标题;解析失败或任务已删返回 null。样本内
+ * 只在有归属的 agent 条目上调用,调用方自行缓存。
+ */
+ resolveSessionLabel?(sessionId: string): Promise<string | null> | string | null;
selfPid: number;
log: SamplerLogger;
/** OS 扫描的最小间隔;快 tick 之间复用缓存。 */
@@ -165,10 +170,10 @@ export function createProcessMonitorSampler(
return /(?:^|[\\/])conhost\.exe(?:\s|$)/i.test(row.cmdLineLower);
}
- function collectAgentEntries(): ProcessUsageEntry[] {
+ async function collectAgentEntries(): Promise<ProcessUsageEntry[]> {
const { rows, childrenByParent } = cachedSnapshot;
const rowByPid = new Map(rows.map((r) => [r.pid, r]));
- const entries: ProcessUsageEntry[] = [];
+ const collected: Array<{ entry: ProcessUsageEntry; sessionId: string | null }> = [];
for (const row of rows) {
if (row.ppid !== deps.selfPid) continue;
const kind = deps.classify(row.cmdLineLower);
@@ -189,20 +194,43 @@ export function createProcessMonitorSampler(
}
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 } : {}),
+ collected.push({
+ sessionId: registrationMatchesKind ? registration?.sessionId ?? null : null,
+ entry: {
+ 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;
+ // 任务标题在本地库(异步 transport)里;聚合后按去重后的 id 统一解析,
+ // 单条失败或已删除只丢标题,不影响 CPU / 内存。
+ const labelBySession = new Map<string, string | null>();
+ const sessionIds = new Set(
+ collected.map((c) => c.sessionId).filter((v): v is string => v != null),
+ );
+ if (deps.resolveSessionLabel && sessionIds.size > 0) {
+ await Promise.all(
+ [...sessionIds].map(async (sessionId) => {
+ try {
+ labelBySession.set(sessionId, (await deps.resolveSessionLabel!(sessionId)) ?? null);
+ } catch {
+ labelBySession.set(sessionId, null);
+ }
+ }),
+ );
+ }
+ return collected.map(({ entry, sessionId }) => {
+ const label = sessionId ? labelBySession.get(sessionId) : null;
+ return label ? { ...entry, sessionLabel: label } : entry;
+ });
}
function chromiumKind(type: string): ProcessUsageKind {
@@ -250,7 +278,7 @@ export function createProcessMonitorSampler(
if (deps.deferOsScan) void refresh;
else await refresh;
const atMs = now();
- const agentEntries = collectAgentEntries();
+ const agentEntries = await collectAgentEntries();
const agentPids = new Set<number>();
for (const entry of agentEntries) {
for (const pid of collectDescendantPids(entry.pid, cachedSnapshot.childrenByParent)) {
diff --git a/apps/desktop/src/main/process-monitor/session-label.ts b/apps/desktop/src/main/process-monitor/session-label.ts
new file mode 100644
index 0000000000..b166a60553
--- /dev/null
+++ b/apps/desktop/src/main/process-monitor/session-label.ts
@@ -0,0 +1,37 @@
+/**
+ * process-monitor/session-label —— 资源监视器 agent 条目的任务标题解析。
+ *
+ * 标题存在本地库(utility-process 异步 transport)里,而采样每 2s 一轮;
+ * 逐轮直查会变成常驻 DB 轮询,这里按 session id 做 TTL 缓存。查不到
+ * (任务已删 / 库暂不可读,getSessionRowSnapshot 自吞错返 null)同样入缓存,
+ * 让下一轮采样不再重复付出一次往返;缓存只丢标题,不影响 CPU / 内存。
+ */
+
+import { getSessionRowSnapshot } from '../localDb/ipc/sessions.js';
+
+export const SESSION_LABEL_TTL_MS = 30_000;
+/** 活跃 agent 进程数远小于此;触顶整表清空,避免长期驻留陈旧 id。 */
+const CACHE_LIMIT = 128;
+
+export interface SessionLabelResolverDeps {
+ now?: () => number;
+ ttlMs?: number;
+}
+
+export function createSessionLabelResolver(
+ deps: SessionLabelResolverDeps = {},
+): (sessionId: string) => Promise<string | null> {
+ const ttlMs = deps.ttlMs ?? SESSION_LABEL_TTL_MS;
+ const now = deps.now ?? Date.now;
+ const cache = new Map<string, { label: string | null; atMs: number }>();
+ return async (sessionId) => {
+ const atMs = now();
+ const hit = cache.get(sessionId);
+ if (hit && atMs - hit.atMs < ttlMs) return hit.label;
+ const row = await getSessionRowSnapshot(sessionId);
+ const label = row?.title ?? null;
+ if (cache.size >= CACHE_LIMIT) cache.clear();
+ cache.set(sessionId, { label, atMs });
+ return label;
+ };
+}
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
index 6b37900e5b..3cca7048ce 100644
--- 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
@@ -90,15 +90,21 @@ function entryDetails(entry: ProcessUsageEntry, t: TFunction): string | null {
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;
+ // 归属任务标题(main 采样时解析)与角色/树规模并列;多任务并行时用户
+ // 靠它区分同名的 Pi / Claude Code 行。
+ const parts = [
+ entry.sessionLabel
+ ? t('rightSidebar.resourceUsage.sessionDetail', { title: entry.sessionLabel })
+ : null,
+ entry.agentRole === 'task-host'
+ ? t('rightSidebar.resourceUsage.agentRoleDetails.task')
+ : null,
+ entry.agentRole === 'control-plane-service'
+ ? t('rightSidebar.resourceUsage.agentRoleDetails.service')
+ : null,
+ processCount,
+ ].filter((part): part is string => part !== null);
+ return parts.length > 0 ? parts.join(' · ') : null;
}
return entry.label ? t(`rightSidebar.resourceUsage.kinds.${entry.kind}`) : null;
}
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
index 9714a27393..e3f4dd9960 100644
--- 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
@@ -5,7 +5,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { TabKindHostContext } from '../../../types';
vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
+ // 插值参数拼进返回值,让断言能区分「带了 title」与「裸 key」两种调用。
+ useTranslation: () => ({
+ t: (key: string, opts?: { title?: string }) =>
+ opts?.title != null ? `${key}:${opts.title}` : key,
+ }),
}));
vi.mock('@/components/ui/confirm-dialog', () => ({
@@ -209,4 +213,50 @@ describe('ResourceUsageBody local-only gate', () => {
expect(onSample).toHaveBeenCalledOnce();
expect(subscribe).toHaveBeenCalledOnce();
});
+
+ it('agent 行显示归属任务标题,并与进程树规模并列;无归属行不带标题', () => {
+ render(
+ <ResourceUsageBody
+ state={{}}
+ ctx={makeContext({ deviceLinkDeviceId: null })}
+ active
+ shellVisible
+ />,
+ );
+ act(() => {
+ sampleListener?.({
+ capturedAtMs: 1,
+ entries: [
+ {
+ pid: 11,
+ kind: 'agent-pi',
+ label: null,
+ cpuPercent: 1,
+ memoryKb: 2,
+ processCount: 2,
+ terminable: true,
+ sessionLabel: '修复登录页',
+ },
+ {
+ pid: 12,
+ kind: 'agent-pi',
+ label: null,
+ cpuPercent: 1,
+ memoryKb: 2,
+ processCount: 1,
+ terminable: false,
+ },
+ ],
+ });
+ });
+ expect(
+ screen.getByText(
+ 'rightSidebar.resourceUsage.sessionDetail:修复登录页 · rightSidebar.resourceUsage.processCount',
+ ),
+ ).toBeTruthy();
+ // 只有带归属的行出现标题槽位(第 12 行无 sessionLabel)。
+ expect(
+ screen.getAllByText(/^rightSidebar\.resourceUsage\.sessionDetail:/),
+ ).toHaveLength(1);
+ });
});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index f101142894..83d11149cc 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8814,6 +8814,7 @@
"task": "Task runtime",
"service": "Accounts and models"
},
+ "sessionDetail": "Task: {{title}}",
"services": {
"audio": "Audio Service",
"network": "Network Service",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index d6045d00f7..997d91db5b 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8782,6 +8782,7 @@
"task": "タスク実行",
"service": "アカウントとモデル"
},
+ "sessionDetail": "タスク:{{title}}",
"services": {
"audio": "オーディオサービス",
"network": "ネットワークサービス",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 3b010e04af..c17fb8c143 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8782,6 +8782,7 @@
"task": "작업 실행",
"service": "계정 및 모델"
},
+ "sessionDetail": "작업: {{title}}",
"services": {
"audio": "오디오 서비스",
"network": "네트워크 서비스",
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 e9c4eb820a..74ef662c90 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8782,6 +8782,7 @@
"task": "任务运行",
"service": "账户与模型"
},
+ "sessionDetail": "任务:{{title}}",
"services": {
"audio": "音频服务",
"network": "网络服务",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 49a5672021..2725546807 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8782,6 +8782,7 @@
"task": "任務執行",
"service": "帳戶與模型"
},
+ "sessionDetail": "任務:{{title}}",
"services": {
"audio": "音訊服務",
"network": "網路服務",
diff --git a/apps/desktop/src/shared/processMonitor.ts b/apps/desktop/src/shared/processMonitor.ts
index 8a01f13312..8c7968c506 100644
--- a/apps/desktop/src/shared/processMonitor.ts
+++ b/apps/desktop/src/shared/processMonitor.ts
@@ -56,6 +56,11 @@ export interface ProcessUsageEntry {
processInstanceId?: string;
/** 仅 Codex 条目可有;普通任务共享宿主与账户/模型控制面服务据此消歧。 */
agentRole?: AgentProcessRole;
+ /**
+ * 本机 Agent 根进程承载的任务标题(main 在采样时从本地库解析,缺省 =
+ * 无归属或解析不可用)。只含标题文本,不含路径、id 或命令行。
+ */
+ sessionLabel?: string;
}
export interface ProcessMonitorSample {
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index fe92e2952b..0b4224cf32 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -448,6 +448,11 @@ export interface LocalAgentProcessRegistration {
pid: number;
kind: 'claude' | 'pi';
role: 'task-host' | 'control-plane-service';
+ /**
+ * 承载本进程的宿主 session id,供资源监视器显示归属任务;离线 fork 等控制面
+ * 进程填来源 session。远端 transport 不触发登记,宿主可忽略。
+ */
+ sessionId?: string | null;
}
export interface CodexLocalCredentialModeSwitchContext {
diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.ts
index 2eeccc82ad..63496f2e72 100644
--- a/packages/maker-core/src/agents/claude-code/index.ts
+++ b/packages/maker-core/src/agents/claude-code/index.ts
@@ -4409,6 +4409,7 @@ export class ClaudeCodeAgent extends BaseAgent {
pid,
kind: 'claude',
role: 'task-host',
+ sessionId: opts.sessionId ?? null,
}),
trackDebugFile: process.env.XDT_CC_DEBUG_NET === '1' && ccDebugFile
? () => this.deps.trackCcDebugFile?.(ccDebugFile, opts.sessionId) ?? (() => {})
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 89285d7ec6..f6ad9bb879 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -5665,6 +5665,7 @@ export class PiAgent extends BaseAgent {
pid,
kind: 'pi',
role: 'task-host',
+ sessionId: opts.sessionId ?? null,
});
},
opts.remoteHostId,
@@ -8669,6 +8670,7 @@ export class PiAgent extends BaseAgent {
pid,
kind: 'pi',
role: 'control-plane-service',
+ sessionId: opts.sourceSdkSessionId ?? null,
}),
);
const proc = new PiRpcProcess({