Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): Windows 资源用量窗口延迟进程扫描
DavidShenb0d8d2becaf3
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex ef6d18472e..455e11be1a 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -2272,7 +2272,9 @@ registerAppearanceSettingsIpc();// ── 资源用量面板 IPC ─────────────────────────────────────────────────// 订阅驱动采样(面板不开不采样),interval 已 unref 不拖退出;terminate 只认// 本产品 spawn 的 agent 根进程。见 main/process-monitor/。-registerProcessMonitorIpc();+registerProcessMonitorIpc({+ allowsSampling: (sender) => resourceUsageWindowController.allowsProcessMonitorSampling(sender),+});// ── 主界面布局树存储 IPC──────────────────────────────────────────────// renderer 首帧 sendSync 拉布局(规则 7 无跳变)、set/reset 写路径、changeddiff --git a/apps/desktop/src/main/process-monitor/__tests__/ipc.test.ts b/apps/desktop/src/main/process-monitor/__tests__/ipc.test.tsindex 30bdca59be..869d2c640d 100644--- a/apps/desktop/src/main/process-monitor/__tests__/ipc.test.ts+++ b/apps/desktop/src/main/process-monitor/__tests__/ipc.test.ts@@ -114,6 +114,71 @@ describe('process monitor IPC authorization', () => {expect(mocks.assertTrustedAppRendererEvent).toHaveBeenCalledTimes(3);});+ it('Main retains but does not sample a hidden prewarm subscription', async () => {+ const sample = vi.fn().mockResolvedValue({ capturedAtMs: 1, entries: [] });+ const allowsSampling = vi.fn().mockReturnValue(false);+ const sender = fakeSender();+ register({ sampler: { sample }, allowsSampling });++ await handlerFor(PROCESS_MONITOR_SUBSCRIBE_CHANNEL)({ sender });+ await Promise.resolve();++ expect(allowsSampling).toHaveBeenCalledWith(sender);+ expect(sample).not.toHaveBeenCalled();+ expect(sender.once).toHaveBeenCalledOnce();+ expect(sender.send).not.toHaveBeenCalled();+ });++ it('rechecks the Main sampling gate before each tick and before publishing', async () => {+ let resolveFirstSample!: (sample: { capturedAtMs: number; entries: [] }) => void;+ const firstSample = new Promise<{ capturedAtMs: number; entries: [] }>((resolve) => {+ resolveFirstSample = resolve;+ });+ const sample = vi+ .fn()+ .mockImplementationOnce(() => firstSample)+ .mockResolvedValue({ capturedAtMs: 2, entries: [] });+ let allowed = true;+ const sender = fakeSender();+ register({ sampler: { sample }, allowsSampling: () => allowed, sampleIntervalMs: 5 });+ const subscribe = handlerFor(PROCESS_MONITOR_SUBSCRIBE_CHANNEL);+ const unsubscribe = handlerFor(PROCESS_MONITOR_UNSUBSCRIBE_CHANNEL);++ await subscribe({ sender });+ await vi.waitFor(() => expect(sample).toHaveBeenCalledOnce());+ allowed = false;+ resolveFirstSample({ capturedAtMs: 1, entries: [] });+ await new Promise((resolve) => setTimeout(resolve, 20));++ expect(sender.send).not.toHaveBeenCalled();+ expect(sample).toHaveBeenCalledOnce();++ allowed = true;+ await vi.waitFor(() => expect(sample.mock.calls.length).toBeGreaterThan(1));+ await unsubscribe({ sender });+ });++ it('logs a stable child-process source before the first Windows OS scan', async () => {+ const scanOsProcesses = vi.fn().mockResolvedValue({ rows: [], childrenByParent: new Map() });+ const log = { info: vi.fn(), warn: vi.fn() };+ const sender = fakeSender();+ register({+ sampler: undefined,+ scanOsProcesses,+ platform: 'win32',+ log,+ });++ await handlerFor(PROCESS_MONITOR_SUBSCRIBE_CHANNEL)({ sender });+ await vi.waitFor(() => expect(scanOsProcesses).toHaveBeenCalledOnce());++ expect(log.info).toHaveBeenCalledWith(+ 'Windows OS process scan requested by resource usage sampling',+ { childProcessSource: 'process-monitor.windows-os-scan' },+ );+ expect(JSON.stringify(log.info.mock.calls)).not.toContain('-NoProfile');+ });+it('订阅后立即推送一帧;窗口不再可信时不推', async () => {const sample = { capturedAtMs: 7, entries: [] };const sampleNow = vi.fn().mockResolvedValue(sample);@@ -138,6 +203,30 @@ describe('process monitor IPC authorization', () => {expect(sender.removeListener).toHaveBeenCalledTimes(1);});+ it('does not fabricate an empty snapshot after failure and recovers on the next tick', async () => {+ const recovered = { capturedAtMs: 8, entries: [] };+ const sample = vi+ .fn()+ .mockRejectedValueOnce(+ Object.assign(new Error('read ENOTCONN'), { code: 'ENOTCONN', syscall: 'read' }),+ )+ .mockResolvedValue(recovered);+ const log = { info: vi.fn(), warn: vi.fn() };+ const sender = fakeSender();+ register({ sampler: { sample }, log, sampleIntervalMs: 5 });++ await handlerFor(PROCESS_MONITOR_SUBSCRIBE_CHANNEL)({ sender });+ await vi.waitFor(() => expect(sample).toHaveBeenCalledOnce());+ expect(sender.send).not.toHaveBeenCalled();+ expect(log.warn).toHaveBeenCalledWith('process monitor sample failed', {+ error: 'read ENOTCONN',+ });++ await vi.waitFor(() => {+ expect(sender.send).toHaveBeenCalledWith(PROCESS_MONITOR_SAMPLE_CHANNEL, recovered);+ });+ });+it('反复切换面板时清理旧 destroyed 监听器', async () => {register();const sender = fakeSender();diff --git a/apps/desktop/src/main/process-monitor/__tests__/sampler.test.ts b/apps/desktop/src/main/process-monitor/__tests__/sampler.test.tsindex 9ac2a4b71d..b9b5396c99 100644--- a/apps/desktop/src/main/process-monitor/__tests__/sampler.test.ts+++ b/apps/desktop/src/main/process-monitor/__tests__/sampler.test.ts@@ -283,11 +283,14 @@ describe('createProcessMonitorSampler', () => {expect(entryByPid(sample, 100)?.kind).toBe('main');expect(log.warn).toHaveBeenCalledWith('process monitor os scan failed',- expect.objectContaining({ error: 'ps blew up' }),+ expect.objectContaining({+ childProcessSource: 'process-monitor.os-process-scan',+ error: 'ps blew up',+ }),);});- it('Windows 预热首帧不等待 OS 扫描,完成后由下一 tick 补齐 agent', async () => {+ it('Windows active sampling does not await OS scan before its first frame', async () => {let resolveScan!: (snapshot: OsProcessSnapshot) => void;const pendingScan = new Promise<OsProcessSnapshot>((resolve) => {resolveScan = resolve;diff --git a/apps/desktop/src/main/process-monitor/ipc.ts b/apps/desktop/src/main/process-monitor/ipc.tsindex 24675431dd..de8de82092 100644--- a/apps/desktop/src/main/process-monitor/ipc.ts+++ b/apps/desktop/src/main/process-monitor/ipc.ts@@ -21,6 +21,7 @@ import {PROCESS_MONITOR_SUBSCRIBE_CHANNEL,PROCESS_MONITOR_TERMINATE_CHANNEL,PROCESS_MONITOR_UNSUBSCRIBE_CHANNEL,+ type ProcessMonitorSample,type TerminateAgentProcessResult,} from '../../shared/processMonitor.js';import { registerUserDataMarkers } from '../agent-process-priority.js';@@ -69,6 +70,8 @@ export interface ProcessMonitorIpcOptions {scanOsProcessesSync?: () => OsProcessSnapshot;/** sampler 的异步 OS 扫描。 */scanOsProcesses?: () => Promise<OsProcessSnapshot>;+ /** 隐藏预热窗口等 sender 可保留订阅,但 Main 不允许它触发采样或接收快照。 */+ allowsSampling?: (sender: WebContents) => boolean;classify?: (cmdLineLower: string) => MonitoredAgentKind | null;resolveAgentProcessRegistration?: (pid: number) => AgentProcessRegistration | null;killProcessTree?: (pid: number, childrenByParent: Map<number, number[]>) => boolean;@@ -101,6 +104,16 @@ export function registerProcessMonitorIpc(opts: ProcessMonitorIpcOptions = {}):});const platform = opts.platform ?? process.platform;const sampleIntervalMs = opts.sampleIntervalMs ?? SAMPLE_INTERVAL_MS;+ let windowsScanSourceLogged = false;+ const sampleScanWithSource = (): Promise<OsProcessSnapshot> => {+ if (platform === 'win32' && !windowsScanSourceLogged) {+ windowsScanSourceLogged = true;+ log.info('Windows OS process scan requested by resource usage sampling', {+ childProcessSource: 'process-monitor.windows-os-scan',+ });+ }+ return sampleScan();+ };if (!opts.sampler) {// 运行时 userData 可被重定向(XDG_CONFIG_HOME / --user-data-dir),静态品牌@@ -120,13 +133,13 @@ export function registerProcessMonitorIpc(opts: ProcessMonitorIpcOptions = {}):opts.sampler ??createProcessMonitorSampler({getMetrics: () => app.getAppMetrics(),- scanOsProcesses: sampleScan,+ scanOsProcesses: sampleScanWithSource,describeRendererProcess: describeRendererProcessByPid,classify,resolveAgentProcessRegistration: resolveAgentRegistration,selfPid,log,- // Windows 冷启 PowerShell 可达秒级;隐藏窗口预热首帧只等 app.getAppMetrics,+ // Windows 冷启 PowerShell 可达秒级;用户打开后的首帧只等 app.getAppMetrics,// Worker 扫描完成后由下一次 2s tick 补齐 agent 树。deferOsScan: platform === 'win32',});@@ -136,6 +149,43 @@ export function registerProcessMonitorIpc(opts: ProcessMonitorIpcOptions = {}):let timer: ReturnType<typeof setInterval> | null = null;let sampling = false;+ function samplingAllowed(wc: WebContents): boolean {+ return !opts.allowsSampling || opts.allowsSampling(wc);+ }++ function hasActiveSubscriber(): boolean {+ let active = false;+ for (const wc of [...subscribers]) {+ if (wc.isDestroyed()) {+ dropSubscriber(wc);+ continue;+ }+ if (samplingAllowed(wc)) active = true;+ }+ return active;+ }++ function publishSample(sample: ProcessMonitorSample): void {+ for (const wc of [...subscribers]) {+ if (wc.isDestroyed()) {+ dropSubscriber(wc);+ continue;+ }+ // 窗口可能在采样 in-flight 期间被隐藏;Main gate 重新检查,禁止把结果发回。+ if (!samplingAllowed(wc)) continue;+ // 出站闸:快照含页面标题(用户内容),窗口导航离开 Cindy 页面后不再推。+ if (!isTrustedAppRendererWindow(BrowserWindow.fromWebContents(wc))) {+ dropSubscriber(wc);+ continue;+ }+ try {+ wc.send(PROCESS_MONITOR_SAMPLE_CHANNEL, sample);+ } catch {+ // 窗口可能在枚举与 send 之间被销毁。+ }+ }+ }+function dropSubscriber(wc: WebContents): void {subscribers.delete(wc);const destroyListener = destroyListeners.get(wc);@@ -150,30 +200,17 @@ export function registerProcessMonitorIpc(opts: ProcessMonitorIpcOptions = {}):}async function tick(): Promise<void> {- if (sampling || subscribers.size === 0) return; // 采样慢于周期时跳过,不排队叠加+ if (sampling || !hasActiveSubscriber()) 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 之间被销毁。- }- }+ publishSample(sample);} catch (err) {log.warn('process monitor sample failed', {error: err instanceof Error ? err.message : String(err),});+ // 不把顶层失败伪装成有效的「0 个进程」快照。已展示的最后一份数据继续保留;+ // 冷打开则保持 Loading,定时器会在下一 tick 自动重试。} finally {sampling = false;}@@ -182,6 +219,11 @@ export function registerProcessMonitorIpc(opts: ProcessMonitorIpcOptions = {}):ipcMain.handle(PROCESS_MONITOR_SUBSCRIBE_CHANNEL, (event) => {assertTrustedAppRendererEvent(event);const wc = event.sender;+ if (!samplingAllowed(wc)) {+ log.info('process monitor subscription deferred while resource window is prewarmed', {+ source: 'resource-usage-window-prewarm',+ });+ }if (!subscribers.has(wc)) {const destroyListener = () => dropSubscriber(wc);subscribers.add(wc);diff --git a/apps/desktop/src/main/process-monitor/sampler.ts b/apps/desktop/src/main/process-monitor/sampler.tsindex b7707dbf27..f3dbd8393e 100644--- a/apps/desktop/src/main/process-monitor/sampler.ts+++ b/apps/desktop/src/main/process-monitor/sampler.ts@@ -56,7 +56,7 @@ export interface ProcessMonitorSamplerDeps {log: SamplerLogger;/** OS 扫描的最小间隔;快 tick 之间复用缓存。 */osScanIntervalMs?: number;- /** Windows 首帧先返回 Chromium 指标,OS 扫描在后台刷新后由下一 tick 合并。 */+ /** Windows 激活采样的首帧先返回 Chromium 指标,OS 扫描由下一 tick 合并。 */deferOsScan?: boolean;/** 注入时钟(测试用;生产缺省 Date.now)。 */now?: () => number;@@ -139,8 +139,12 @@ export function createProcessMonitorSampler(// 扫描失败降级为「本轮无 agent 条目」,Chromium 部分照常。缓存时间戳// 也推进,避免每个快 tick 都重试昂贵的失败扫描。onSnapshotRefreshed({ rows: [], childrenByParent: new Map() }, now());+ const errno = err as NodeJS.ErrnoException;deps.log.warn('process monitor os scan failed', {+ childProcessSource: 'process-monitor.os-process-scan',error: err instanceof Error ? err.message : String(err),+ ...(typeof errno?.code === 'string' ? { code: errno.code } : {}),+ ...(typeof errno?.syscall === 'string' ? { syscall: errno.syscall } : {}),});}).finally(() => {diff --git a/apps/desktop/src/main/resource-usage-window/__tests__/controller.test.ts b/apps/desktop/src/main/resource-usage-window/__tests__/controller.test.tsindex b0078ae709..416ee90ef3 100644--- a/apps/desktop/src/main/resource-usage-window/__tests__/controller.test.ts+++ b/apps/desktop/src/main/resource-usage-window/__tests__/controller.test.ts@@ -109,6 +109,7 @@ function makeHarness(timeoutMs = 5000,prewarmTimeoutMs = 10_000,recoveryStabilityMs = 30_000,+ platform: NodeJS.Platform = 'linux',) {const windows: FakeWindow[] = [];const mainSender = { id: 100 } as WebContents;@@ -122,6 +123,7 @@ function makeHarness(openTimeoutMs: timeoutMs,prewarmTimeoutMs,recoveryStabilityMs,+ platform,});return { controller, windows, mainSender };}@@ -135,6 +137,36 @@ beforeEach(() => vi.useFakeTimers());afterEach(() => vi.useRealTimers());describe('ResourceUsageWindowController', () => {+ it('keeps Windows prewarm sampling paused until the user explicitly opens the window', () => {+ const { controller, windows, mainSender } = makeHarness(5000, 10_000, 30_000, 'win32');++ controller.prewarm();+ expect(controller.allowsProcessMonitorSampling(windows[0]!.webContents)).toBe(false);+ expect(controller.markRendererReady(windows[0]!.webContents)).toBe(true);+ expect(windows[0]?.send).toHaveBeenLastCalledWith(+ RESOURCE_USAGE_WINDOW_SAMPLING_ACTIVE_CHANNEL,+ false,+ );++ windows[0]?.emitWebContents('did-start-loading');+ expect(windows[0]?.send).toHaveBeenLastCalledWith(+ RESOURCE_USAGE_WINDOW_SAMPLING_ACTIVE_CHANNEL,+ false,+ );+ expect(controller.markRendererReady(windows[0]!.webContents)).toBe(true);++ expect(controller.open(mainSender)).toBe(true);+ expect(controller.allowsProcessMonitorSampling(windows[0]!.webContents)).toBe(true);+ expect(windows[0]?.send).toHaveBeenLastCalledWith(+ RESOURCE_USAGE_WINDOW_SAMPLING_ACTIVE_CHANNEL,+ true,+ );+ expect(windows[0]?.show).not.toHaveBeenCalled();++ expect(controller.markPresentationReady(windows[0]!.webContents)).toBe(true);+ expect(windows[0]?.show).toHaveBeenCalledOnce();+ });+it('prewarms a complete presentation without showing or focusing it', () => {const { controller, windows } = makeHarness();diff --git a/apps/desktop/src/main/resource-usage-window/controller.ts b/apps/desktop/src/main/resource-usage-window/controller.tsindex 167956cc8d..35b62c244c 100644--- a/apps/desktop/src/main/resource-usage-window/controller.ts+++ b/apps/desktop/src/main/resource-usage-window/controller.ts@@ -1,8 +1,8 @@/*** 资源用量独立窗口的预热、显示和回收状态机。*- * 窗口在主界面稳定后提前创建。renderer 挂载与首份采样都发生在隐藏阶段;用户打开时- * 只恢复采样并显示已有内容。普通关闭仅隐藏,主窗口真正销毁或应用退出时才销毁窗口。+ * 窗口在主界面稳定后提前创建。renderer 在隐藏阶段挂载;Windows 的首份采样延迟到用户+ * 主动打开,其他平台保留隐藏快照预热。普通关闭仅隐藏,主窗口真正销毁或退出时才销毁。*/import type { BrowserWindow, WebContents } from 'electron';@@ -61,7 +61,7 @@ export class ResourceUsageWindowController {private prewarmTimeout: NodeJS.Timeout | null = null;private recoveryStabilityTimeout: NodeJS.Timeout | null = null;private leaveTimeout: NodeJS.Timeout | null = null;- private samplingActive = true;+ private samplingActive = false;private automaticRecoveryAttempts = 0;private destroyingWindow = false;private disposed = false;@@ -119,10 +119,11 @@ export class ResourceUsageWindowController {this.rendererReady = true;if (this.locale) this.sendLocale(win, this.locale);this.setSamplingActive(win, this.samplingActive);+ if (!this.samplingActive && !this.visible && !this.pendingOpen) this.clearPrewarmTimeout();return true;}- /** 首份快照已提交;隐藏预热到此结束,停止后台采样但保留表格状态。 */+ /** 首份快照已提交;完成待显示内容,隐藏时停止后台采样但保留表格状态。 */markPresentationReady(sender: WebContents): boolean {const win = this.windowForSender(sender);if (!win) return false;@@ -205,6 +206,16 @@ export class ResourceUsageWindowController {return this.winRef !== null && !this.winRef.isDestroyed();}+ /**+ * process-monitor 的 Main 侧二次门禁。资源窗口隐藏预热时即使 renderer 错误订阅,+ * Windows 也不能因此拉起 OS 进程扫描;主窗口里可见的旧兼容页签不受影响。+ */+ allowsProcessMonitorSampling(sender: WebContents): boolean {+ const win = this.winRef;+ if (!win || win.isDestroyed() || sender !== win.webContents) return true;+ return this.samplingActive;+ }+private ensureWindow(): BrowserWindow | null {if (this.winRef && !this.winRef.isDestroyed()) return this.winRef;let win: BrowserWindow;@@ -221,7 +232,9 @@ export class ResourceUsageWindowController {this.rendererReady = false;this.presentationReady = false;this.visible = false;- this.samplingActive = true;+ // Windows 预热只加载 BrowserWindow / renderer。昂贵且可能触发安全软件管道异常的+ // OS 扫描必须等用户显式 open;其他平台保留既有首份快照预热体验。+ this.samplingActive = this.pendingOpen || this.platform() !== 'win32';this.destroyingWindow = false;this.fullscreenTransition = 'idle';this.applyNativeTitle(win);@@ -494,7 +507,7 @@ export class ResourceUsageWindowController {this.presentationReady = false;this.visible = false;this.pendingOpen = false;- this.samplingActive = true;+ this.samplingActive = false;this.destroyingWindow = false;if (!options.preserveOwner) {this.unbindOwnerVisibility();@@ -570,7 +583,7 @@ export class ResourceUsageWindowController {if (this.visible) win.hide();this.rendererReady = false;this.presentationReady = false;- this.setSamplingActive(win, true);+ this.setSamplingActive(win, shouldRestore || this.platform() !== 'win32');if (shouldRestore) {this.pendingOpen = true;this.scheduleOpenFallback(win);diff --git a/apps/desktop/src/renderer/components/resource-usage/ResourceUsageWindowLayout.tsx b/apps/desktop/src/renderer/components/resource-usage/ResourceUsageWindowLayout.tsxindex 04e37bd865..78803853ef 100644--- a/apps/desktop/src/renderer/components/resource-usage/ResourceUsageWindowLayout.tsx+++ b/apps/desktop/src/renderer/components/resource-usage/ResourceUsageWindowLayout.tsx@@ -50,8 +50,11 @@ export function ResourceUsageWindowLayout() {const presentationReadyAttemptRef = useRef(0);const presentationReadyRetryRef = useRef<ReturnType<typeof setTimeout> | null>(null);const presentationReadyDisposedRef = useRef(false);- // 首次隐藏挂载需要采一份数据完成预热;main 在 presentationReady 后会切回 false。- const [samplingActive, setSamplingActive] = useState(true);+ // Windows 隐藏预热只挂载 renderer,不触发 OS 进程扫描;用户显式打开后由 Main+ // 发送 true。其他平台保留现有首份快照预热行为。+ const [samplingActive, setSamplingActive] = useState(+ window.electronAPI.platform !== 'win32',+ );// BrowserWindow hide 后 Chromium 不会继续更新鼠标命中,复用窗口时自绘按钮可能保留// 上一次点击留下的 focus / :hover。隐藏时重建一次 chrome,确保下次 show 从干净状态开始。const [windowChromeRevision, setWindowChromeRevision] = useState(0);diff --git a/apps/desktop/src/renderer/components/resource-usage/__tests__/ResourceUsageWindowLayout.test.tsx b/apps/desktop/src/renderer/components/resource-usage/__tests__/ResourceUsageWindowLayout.test.tsxindex cd68d2e65c..6aff5853ba 100644--- a/apps/desktop/src/renderer/components/resource-usage/__tests__/ResourceUsageWindowLayout.test.tsx+++ b/apps/desktop/src/renderer/components/resource-usage/__tests__/ResourceUsageWindowLayout.test.tsx@@ -86,17 +86,18 @@ describe('ResourceUsageWindowRoot prewarm lifecycle', () => {expect(screen.getByText('titleBar.menuItems.resourceUsage')).toBeTruthy();});- it('mounts hidden prewarm sampling, reports renderer readiness, then follows main visibility', async () => {+ it('keeps Windows hidden prewarm idle, then samples only after Main activates it', async () => {render(<ResourceUsageWindowRoot />);expect(rendererReady).toHaveBeenCalledOnce();- expect(resourceBodyProps).toMatchObject({ active: true, shellVisible: true });-- await act(async () => samplingListener?.(false));expect(resourceBodyProps).toMatchObject({ active: false, shellVisible: false });+ expect(presentationReady).not.toHaveBeenCalled();await act(async () => samplingListener?.(true));expect(resourceBodyProps).toMatchObject({ active: true, shellVisible: true });++ await act(async () => samplingListener?.(false));+ expect(resourceBodyProps).toMatchObject({ active: false, shellVisible: false });});it('applies locale changes received while the window is prewarmed', async () => {