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。

fix(desktop): 资源监视器任务标题改为后台缓存,离线 fork 不再误标来源

Zhang Yunjin374daff7cb7b
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index ce30dce344..3d8bf7beed 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -555,7 +555,6 @@ 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,
@@ -2508,9 +2507,10 @@ registerMenubarIpc();
// 本产品 spawn 的 agent 根进程。见 main/process-monitor/。
registerProcessMonitorIpc({
allowsSampling: (sender) => resourceUsageWindowController.allowsProcessMonitorSampling(sender),
- // agent 行显示承载任务标题;标题在本地库里,经 TTL 缓存解耦采样周期。见
- // main/process-monitor/session-label.ts。
- resolveSessionLabel: createSessionLabelResolver(),
+ // agent 行显示承载任务标题。标题查询由采样器后台缓存,不阻塞采样帧;
+ // 只取标题文本,路径与 id 不出 main。
+ resolveSessionLabel: async (sessionId) =>
+ (await getSessionRowSnapshot(sessionId))?.title ?? null,
});
// ── 主界面布局树存储 IPC──────────────────────────────────────────────
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 9f8b610309..78b7fb7823 100644
--- a/apps/desktop/src/main/process-monitor/__tests__/ipc.test.ts
+++ b/apps/desktop/src/main/process-monitor/__tests__/ipc.test.ts
@@ -245,11 +245,12 @@ describe('process monitor IPC authorization', () => {
expect(sender.removeListener).toHaveBeenNthCalledWith(2, 'destroyed', expect.any(Function));
});
- it('生产装配把 resolveSessionLabel 传入采样器,agent 条目带归属标题', async () => {
+ it('生产装配把 resolveSessionLabel 传入采样器,后续帧的 agent 条目带归属标题', async () => {
const sender = fakeSender();
register({
sampler: undefined,
platform: 'linux',
+ sampleIntervalMs: 10,
scanOsProcesses: vi.fn().mockResolvedValue({
rows: [osRow({ pid: 511, ppid: SELF_PID, cmdLineLower: 'pi-marker host' })],
childrenByParent: new Map(),
@@ -266,16 +267,21 @@ describe('process monitor IPC authorization', () => {
});
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: '写发布说明',
- });
- });
+ // 标题查询在后台缓存,首帧可能还没有;轮询后续帧直到标题出现。
+ await vi.waitFor(
+ () => {
+ const withLabel = sender.send.mock.calls
+ .map((call) => call[1] as { entries: Array<{ pid: number; sessionLabel?: string }> })
+ .some((sample) =>
+ sample.entries.some(
+ (entry) => entry.pid === 511 && entry.sessionLabel === '写发布说明',
+ ),
+ );
+ expect(withLabel).toBe(true);
+ },
+ { timeout: 2_000, interval: 20 },
+ );
+ }, 5_000);
});
describe('terminate ownership validation', () => {
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 4547ff4c65..4357b05702 100644
--- a/apps/desktop/src/main/process-monitor/__tests__/sampler.test.ts
+++ b/apps/desktop/src/main/process-monitor/__tests__/sampler.test.ts
@@ -215,7 +215,7 @@ describe('createProcessMonitorSampler', () => {
});
});
- it('agent 条目解析归属任务标题:仅登记了 sessionId 的条目,失败只丢标题', async () => {
+ it('任务标题后台解析:首帧不带,解析完成后下一帧生效;失败与无归属只丢标题', async () => {
const lookups: string[] = [];
const { sampler } = makeHarness({
snapshot: snapshotOf([
@@ -239,17 +239,62 @@ describe('createProcessMonitorSampler', () => {
},
},
});
+ // 首帧立即返回,不等标题查询(库慢不阻塞 CPU / 内存刷新)。
+ expect(entryByPid(await sampler.sample(), 901)?.sessionLabel).toBeUndefined();
+ expect(lookups).toEqual(['session-1', 'session-2']);
+ // 查询落定后,下一帧带上标题;失败/无归属的条目不带 sessionLabel 字段。
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
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;
+ // 缓存未过期时不再重复查询。
+ expect(lookups).toEqual(['session-1', 'session-2']);
+ });
+
+ it('标题缓存按 TTL 后台刷新:刷新期间沿用旧值,不阻塞采样', async () => {
+ const { state, sampler } = makeHarness({
+ snapshot: snapshotOf([
+ osRow({ pid: 911, ppid: SELF_PID, cmdLineLower: 'pi-marker host' }),
+ ]),
+ deps: {
+ sessionLabelTtlMs: 5_000,
+ resolveSessionLabel: (sessionId) =>
+ Promise.resolve(sessionId === 'session-9' ? `标题@${state.nowMs}` : null),
+ resolveAgentProcessRegistration: () => ({
+ kind: 'pi',
+ role: 'task-host',
+ sessionId: 'session-9',
+ instanceId: 'inst:911',
+ }),
+ },
+ });
await sampler.sample();
- expect(lookups.slice(afterFirstRound)).toEqual(['session-1', 'session-2']);
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(entryByPid(await sampler.sample(), 911)).toMatchObject({
+ sessionLabel: '标题@10000',
+ });
+ // TTL 未过期:沿用缓存,不重查。
+ state.nowMs += 4_000;
+ expect(entryByPid(await sampler.sample(), 911)).toMatchObject({
+ sessionLabel: '标题@10000',
+ });
+ // 过期后仍先返回旧值,刷新在后台落定,下一帧生效。
+ state.nowMs += 5_100;
+ expect(entryByPid(await sampler.sample(), 911)).toMatchObject({
+ sessionLabel: '标题@10000',
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(entryByPid(await sampler.sample(), 911)).toMatchObject({
+ sessionLabel: '标题@19100',
+ });
});
it('OS 扫描按周期缓存:未过期不重扫,过期后重扫', async () => {
diff --git a/apps/desktop/src/main/process-monitor/sampler.ts b/apps/desktop/src/main/process-monitor/sampler.ts
index 8e4e0e86b3..4319fb4bb5 100644
--- a/apps/desktop/src/main/process-monitor/sampler.ts
+++ b/apps/desktop/src/main/process-monitor/sampler.ts
@@ -53,8 +53,8 @@ export interface ProcessMonitorSamplerDeps {
/** 本地根进程的 spawn-generation 登记;未知时返回 null,并按不可终止处理。 */
resolveAgentProcessRegistration?(pid: number): AgentProcessRegistration | null;
/**
- * 登记 session id → 用户可见任务标题;解析失败或任务已删返回 null。样本内
- * 只在有归属的 agent 条目上调用,调用方自行缓存。
+ * 登记 session id → 用户可见任务标题;解析失败或任务已删返回 null。采样不
+ * 等待它:查询在后台进行,结果进本采样器的 TTL 缓存,下一帧才可见。
*/
resolveSessionLabel?(sessionId: string): Promise<string | null> | string | null;
selfPid: number;
@@ -65,6 +65,8 @@ export interface ProcessMonitorSamplerDeps {
deferOsScan?: boolean;
/** 注入时钟(测试用;生产缺省 Date.now)。 */
now?: () => number;
+ /** 标题缓存刷新周期(测试用;缺省 30s)。 */
+ sessionLabelTtlMs?: number;
}
/** OS 扫描缓存周期。5s 在「agent 树数据新鲜度」与「powershell 开销」间取平衡。 */
@@ -101,6 +103,33 @@ export function createProcessMonitorSampler(
*/
const computedCpuPercentByPid = new Map<number, number>();
+ /** 任务标题缓存周期。标题极少变化(自动命名/改名),30s 内的陈旧可接受。 */
+ const sessionLabelTtlMs = deps.sessionLabelTtlMs ?? 30_000;
+ /** sessionId → 最近一次解析结果与发起时刻;解析永不阻塞采样,晚一帧生效。 */
+ const sessionLabels = new Map<string, { label: string | null; atMs: number }>();
+
+ /** 后台刷新标题缓存;过期才发起,失败/空结果记 null,下一 TTL 周期重试。 */
+ function refreshSessionLabel(sessionId: string): void {
+ const cached = sessionLabels.get(sessionId);
+ if (cached && now() - cached.atMs < sessionLabelTtlMs) return;
+ sessionLabels.set(sessionId, { label: cached?.label ?? null, atMs: now() });
+ void (async () => {
+ try {
+ const label = (await deps.resolveSessionLabel?.(sessionId)) ?? null;
+ const entry = sessionLabels.get(sessionId);
+ if (entry) sessionLabels.set(sessionId, { label, atMs: entry.atMs });
+ } catch {
+ const entry = sessionLabels.get(sessionId);
+ if (entry) sessionLabels.set(sessionId, { label: null, atMs: entry.atMs });
+ }
+ })();
+ }
+
+ function cachedSessionLabel(sessionId: string): string | null {
+ refreshSessionLabel(sessionId);
+ return sessionLabels.get(sessionId)?.label ?? null;
+ }
+
function onSnapshotRefreshed(snapshot: OsProcessSnapshot, atMs: number): void {
cachedSnapshot = snapshot;
cachedAtMs = atMs;
@@ -170,10 +199,10 @@ export function createProcessMonitorSampler(
return /(?:^|[\\/])conhost\.exe(?:\s|$)/i.test(row.cmdLineLower);
}
- async function collectAgentEntries(): Promise<ProcessUsageEntry[]> {
+ function collectAgentEntries(): ProcessUsageEntry[] {
const { rows, childrenByParent } = cachedSnapshot;
const rowByPid = new Map(rows.map((r) => [r.pid, r]));
- const collected: Array<{ entry: ProcessUsageEntry; sessionId: string | null }> = [];
+ const entries: ProcessUsageEntry[] = [];
for (const row of rows) {
if (row.ppid !== deps.selfPid) continue;
const kind = deps.classify(row.cmdLineLower);
@@ -194,43 +223,26 @@ export function createProcessMonitorSampler(
}
const terminable =
row.startIdentity != null && registrationMatchesKind && registeredRole === 'task-host';
- 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 } : {}),
- },
+ // 标题解析在后台进行(不阻塞采样帧):首帧可能还没有,下一帧生效;
+ // 解析失败或任务已删只丢标题,不影响 CPU / 内存与终止授权。
+ const sessionLabel = registrationMatchesKind && registration?.sessionId
+ ? cachedSessionLabel(registration.sessionId)
+ : null;
+ 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 } : {}),
+ ...(sessionLabel ? { sessionLabel } : {}),
});
}
- // 任务标题在本地库(异步 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;
- });
+ return entries;
}
function chromiumKind(type: string): ProcessUsageKind {
@@ -278,7 +290,7 @@ export function createProcessMonitorSampler(
if (deps.deferOsScan) void refresh;
else await refresh;
const atMs = now();
- const agentEntries = await collectAgentEntries();
+ const agentEntries = 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
deleted file mode 100644
index b166a60553..0000000000
--- a/apps/desktop/src/main/process-monitor/session-label.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * 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 3cca7048ce..284c878311 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
@@ -201,7 +201,7 @@ function EntryRow({
<div className="resource-usage-name-copy">
<div className="resource-usage-name" title={name}>{name}</div>
{details ? (
- <div className="resource-usage-details">
+ <div className="resource-usage-details" title={details}>
<span>{details}</span>
<span className="resource-usage-pid-inline"> · PID {entry.pid}</span>
</div>
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 0b4224cf32..74e83b45a8 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -449,8 +449,8 @@ export interface LocalAgentProcessRegistration {
kind: 'claude' | 'pi';
role: 'task-host' | 'control-plane-service';
/**
- * 承载本进程的宿主 session id,供资源监视器显示归属任务;离线 fork 等控制面
- * 进程填来源 session。远端 transport 不触发登记,宿主可忽略。
+ * 承载本进程的宿主 session id,供资源监视器显示归属任务。远端 transport
+ * 不触发登记,宿主可忽略。
*/
sessionId?: string | null;
}
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index f6ad9bb879..563baa47a8 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -8670,7 +8670,6 @@ export class PiAgent extends BaseAgent {
pid,
kind: 'pi',
role: 'control-plane-service',
- sessionId: opts.sourceSdkSessionId ?? null,
}),
);
const proc = new PiRpcProcess({