From d588d4f0e556ef96d748e9afbe9abf28b437b8d6 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Tue, 3 Nov 2026 13:02:19 +0000 Subject: [PATCH 1/9] measure(idle-chats): probe what the shown chat's page asks for at idle, by call site The idle-chats bench reads the shown agent page's renderer at 5.27% CPU with nothing streaming. debug.agent_pane idle_probe counts that page's animation frames, timeouts, intervals, DOM mutations, running animations and long animation frames by call site for a window; bench_power.py idle-chats runs it after the measured window and keeps it in the JSON. Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-cb01117327fc358e9ba1 --- .../CmuxNextApp/Control/DebugAgentPane.swift | 7 +- scripts/cmux-next/bench_power.py | 6 + webviews/src/agent-session/acpmux/debug.ts | 7 + .../src/agent-session/acpmux/idleProbe.ts | 148 ++++++++++++++++++ .../src/pages/settings/settings.gallery.ts | 16 +- 5 files changed, 180 insertions(+), 4 deletions(-) create mode 100644 webviews/src/agent-session/acpmux/idleProbe.ts diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugAgentPane.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugAgentPane.swift index 53cf6b889842..339801e0c19e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugAgentPane.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugAgentPane.swift @@ -64,7 +64,7 @@ enum DebugAgentPane { "select_session": "selectSession", "answer_permission": "answerPermission", "open_changes": "openChanges", "set_model": "setModel", "models": "models", "stream": "stream", "pick_folder": "pickFolder", "compose_send": "composeSend", "run_mode": "runMode", - "load_seed": "loadSeed", "load_run": "loadRun", "layout_watch": "layoutWatch", + "load_seed": "loadSeed", "load_run": "loadRun", "layout_watch": "layoutWatch", "idle_probe": "idleProbe", ] /// The chat verbs drive the chat as a person does, so each records a user gesture first (as @@ -226,7 +226,7 @@ enum DebugAgentPane { } } guard let function = functions[action] else { - return .object(["error": .string("unknown action; use seed_rows, fling, fling_stats, perf_stats, typing_stats, reset_typing, close_menus, open_menu, acp_log, acp_log_export, chat_state, send_prompt, new_chat, select_session, pick_folder, compose_send, run_mode, answer_permission, open_changes, set_model, models, stream, layout_watch, readiness, cloud_auth, engine, focus_composer, composer_focused, click, open_subagent, pid, full_rate, gesture_state, session_info_action or inspector")]) + return .object(["error": .string("unknown action; use seed_rows, fling, fling_stats, perf_stats, typing_stats, reset_typing, close_menus, open_menu, acp_log, acp_log_export, chat_state, send_prompt, new_chat, select_session, pick_folder, compose_send, run_mode, answer_permission, open_changes, set_model, models, stream, layout_watch, idle_probe, readiness, cloud_auth, engine, focus_composer, composer_focused, click, open_subagent, pid, full_rate, gesture_state, session_info_action or inspector")]) } do { let result = try await view.callPageScript(script, arguments: ["fn": function, "args": arguments(action, params)]) @@ -280,6 +280,9 @@ enum DebugAgentPane { if let value = params[key]?.doubleValue { options[key] = value } } return [options] + case "idle_probe": + // What the page asks for while nobody touches it (idleProbe.ts), over `ms`. + return [params["ms"]?.doubleValue.map { ["ms": $0] as [String: Any] } ?? [:]] case "open_menu": return [params["label"]?.stringValue ?? ""] case "acp_log": diff --git a/scripts/cmux-next/bench_power.py b/scripts/cmux-next/bench_power.py index a2d334c6bddd..610162fa1a99 100755 --- a/scripts/cmux-next/bench_power.py +++ b/scripts/cmux-next/bench_power.py @@ -554,6 +554,12 @@ def run_loaded(args): time.sleep(5) # test script: the debug read's own work ends before the window result = measure_processes(pid, args.app, label, args.measure, roles, peer.pids()) result["load"] = reached + if label == "idle-chats": + # After the window, so it costs the measurement nothing: what the shown chat's page asks + # for while nobody touches it, by call site (idleProbe.ts), for the idle loop's source. + probe = rpc(sock, "debug.agent_pane", {"action": "idle_probe", "ms": 10000}, timeout=45) + result["idle_probe"] = probe + print(f"PERF-IDLE-PROBE {json.dumps(probe)[:20000]}", flush=True) result["renderer_roles"] = "debug.cef_pages" if pages is not None else "none (a build without debug.* methods)" sha = subprocess.run(["git", "rev-parse", "--short=12", "HEAD"], capture_output=True, text=True).stdout.strip() model = subprocess.run(["sysctl", "-n", "hw.model"], capture_output=True, text=True).stdout.strip() diff --git a/webviews/src/agent-session/acpmux/debug.ts b/webviews/src/agent-session/acpmux/debug.ts index a45494a5b48a..e880895b3f3b 100644 --- a/webviews/src/agent-session/acpmux/debug.ts +++ b/webviews/src/agent-session/acpmux/debug.ts @@ -17,6 +17,7 @@ import { shownPresence } from "./multiplayer/LivePresence"; import { acpWire, type AcpWireLog } from "./wire"; import { followTrace } from "./followTrace"; import { composerChips, layoutWatch, type LayoutWatchOptions } from "./layoutWatch"; +import { idleProbe, type IdleProbeOptions } from "./idleProbe"; import { queuedRowsState } from "./queuedRowsState"; import { composerAttachmentsState } from "./composerAttachmentsState"; import { cloudSignedInForDebug } from "./cloudMachines"; @@ -69,6 +70,8 @@ export type AcpmuxDebug = { models(): Record; /** What moved on the page after it first showed its content, watched for `ms` (layoutWatch.ts). */ layoutWatch(options?: LayoutWatchOptions): Promise>; + /** What the page asks for while nobody touches it, by call site, over `ms` (idleProbe.ts). */ + idleProbe(options?: IdleProbeOptions): Promise>; /** Streams a scripted reply into a long synthetic transcript and reports the frames (streamDebug.ts). */ stream(options?: StreamOptions): Promise>; /** Opens a mock session of `turns` heavy turns through the real client (loadDebug.ts). */ @@ -374,6 +377,10 @@ export function createAcpmuxDebug( layoutWatch(options = {}) { return layoutWatch(options); }, + + idleProbe(options = {}) { + return idleProbe(options); + }, stream(options = {}) { return runStream(host.replaceRows, options); }, diff --git a/webviews/src/agent-session/acpmux/idleProbe.ts b/webviews/src/agent-session/acpmux/idleProbe.ts new file mode 100644 index 000000000000..1b353535bcf2 --- /dev/null +++ b/webviews/src/agent-session/acpmux/idleProbe.ts @@ -0,0 +1,148 @@ +// What a pane does while nobody touches it (`debug.agent_pane idle_probe`, bench_power.py idle-chats). +// For `ms` it counts, by call site, every animation frame, timeout and interval the page asks for, +// every DOM mutation by target, the running animations, and Chromium's long animation frames with +// their script attribution. The wrappers are put back when the window ends, so the page pays +// nothing for this outside the probe. A measurement tool: no product code reads it. + +export type IdleProbeOptions = { ms?: number }; + +type Site = { count: number; sample: string }; + +const SITE_FRAMES = 3; + +/** The first frames of the caller's stack outside this file, as one short key. */ +function callSite(): string { + const lines = (new Error().stack ?? "").split("\n").slice(1); + const own = lines.filter((line) => !line.includes("idleProbe")); + return own + .slice(0, SITE_FRAMES) + .map((line) => line.trim().replace(/^at /, "").slice(0, 160)) + .join(" < "); +} + +function describe(node: Node | null): string { + if (!node) return "?"; + const element = node instanceof Element ? node : node.parentElement; + if (!element) return node.nodeName; + const classes = [...element.classList].slice(0, 3).join("."); + return `${element.tagName.toLowerCase()}${classes ? `.${classes}` : ""}`; +} + +function top(map: Map, limit = 12) { + return [...map.entries()] + .sort((a, b) => b[1].count - a[1].count) + .slice(0, limit) + .map(([site, { count, sample }]) => ({ site, count, sample })); +} + +export async function idleProbe(options: IdleProbeOptions = {}): Promise> { + const ms = Math.max(100, Math.min(30_000, options.ms ?? 10_000)); + const frames = new Map(); + const timeouts = new Map(); + const intervals = new Map(); + const mutations = new Map(); + const loafs: Record[] = []; + const note = (map: Map, key: string, sample: () => string) => { + const site = map.get(key); + if (site) site.count++; + else map.set(key, { count: 1, sample: sample() }); + }; + const original = { + raf: window.requestAnimationFrame, + timeout: window.setTimeout, + interval: window.setInterval, + }; + const source = (callback: unknown) => (typeof callback === "function" ? String(callback).slice(0, 160) : ""); + window.requestAnimationFrame = function (callback: FrameRequestCallback) { + note(frames, callSite(), () => source(callback)); + return original.raf.call(window, callback); + }; + window.setTimeout = function (handler: TimerHandler, timeout?: number, ...rest: unknown[]) { + note(timeouts, `${timeout ?? 0}ms ${callSite()}`, () => source(handler)); + return Reflect.apply(original.timeout, window, [handler, timeout, ...rest]) as number; + } as typeof window.setTimeout; + window.setInterval = function (handler: TimerHandler, timeout?: number, ...rest: unknown[]) { + note(intervals, `${timeout ?? 0}ms ${callSite()}`, () => source(handler)); + return Reflect.apply(original.interval, window, [handler, timeout, ...rest]) as number; + } as typeof window.setInterval; + const observer = new MutationObserver((records) => { + for (const record of records) note(mutations, `${record.type} ${describe(record.target)}`, () => ""); + }); + observer.observe(document, { subtree: true, childList: true, attributes: true, characterData: true }); + let loafObserver: PerformanceObserver | undefined; + try { + loafObserver = new PerformanceObserver((list) => { + for (const entry of list.getEntries() as (PerformanceEntry & { + blockingDuration?: number; + scripts?: { + invoker?: string; + invokerType?: string; + sourceURL?: string; + sourceFunctionName?: string; + sourceCharPosition?: number; + duration: number; + }[]; + })[]) { + if (loafs.length >= 40) break; + loafs.push({ + duration: Math.round(entry.duration), + blocking: Math.round(entry.blockingDuration ?? 0), + scripts: (entry.scripts ?? []).slice(0, 5).map((script) => ({ + invoker: script.invoker, + type: script.invokerType, + source: `${script.sourceURL ?? ""}:${script.sourceCharPosition ?? ""} ${script.sourceFunctionName ?? ""}`, + ms: Math.round(script.duration), + })), + }); + } + }); + loafObserver.observe({ type: "long-animation-frame", buffered: false }); + } catch { + loafObserver = undefined; + } + const started = performance.now(); + try { + await new Promise((resolve) => Reflect.apply(original.timeout, window, [resolve, ms])); + } finally { + window.requestAnimationFrame = original.raf; + window.setTimeout = original.timeout; + window.setInterval = original.interval; + observer.disconnect(); + loafObserver?.disconnect(); + } + const seconds = (performance.now() - started) / 1000; + const animations = (document.getAnimations?.() ?? []) + .filter((animation) => animation.playState === "running") + .map((animation) => { + const effect = animation.effect as KeyframeEffect | null; + const properties = new Set(); + for (const frame of effect?.getKeyframes?.() ?? []) + for (const key of Object.keys(frame)) + if (!["offset", "easing", "composite", "computedOffset"].includes(key)) properties.add(key); + return { + name: (animation as CSSAnimation).animationName ?? animation.id ?? animation.constructor.name, + target: describe(effect?.target ?? null), + properties: [...properties], + visible: effect?.target ? ((effect.target as Element).checkVisibility?.() ?? null) : null, + }; + }); + const sum = (map: Map) => [...map.values()].reduce((total, site) => total + site.count, 0); + return { + seconds: Math.round(seconds * 10) / 10, + visibility: document.visibilityState, + focus: document.hasFocus(), + per_second: { + frames: Math.round((sum(frames) / seconds) * 10) / 10, + timeouts: Math.round((sum(timeouts) / seconds) * 10) / 10, + intervals: Math.round((sum(intervals) / seconds) * 10) / 10, + mutations: Math.round((sum(mutations) / seconds) * 10) / 10, + }, + frames: top(frames), + timeouts: top(timeouts), + intervals: top(intervals), + mutations: top(mutations), + animations: animations.slice(0, 20), + animation_count: animations.length, + long_frames: loafs, + }; +} diff --git a/webviews/src/pages/settings/settings.gallery.ts b/webviews/src/pages/settings/settings.gallery.ts index 3606707c2620..38bf6182f8f8 100644 --- a/webviews/src/pages/settings/settings.gallery.ts +++ b/webviews/src/pages/settings/settings.gallery.ts @@ -1255,7 +1255,13 @@ Object.assign(variants, { "accounts-team-invited": variant("accounts", { accounts: withTeams((teams) => { teams.received = [ - { id: "inv-1", teamId: "team-research", team: "Sample team 3", invitedBy: "Sample Person", email: "you@example.com" }, + { + id: "inv-1", + teamId: "team-research", + team: "Sample team 3", + invitedBy: "Sample Person", + email: "you@example.com", + }, { id: "inv-2", teamId: "team-design", team: "Sample team 4", invitedBy: null, email: "you@example.com" }, ]; }), @@ -1264,7 +1270,13 @@ Object.assign(variants, { "accounts-team-joined": variant("accounts", { accounts: withTeams((teams) => { teams.received = [ - { id: "inv-1", teamId: "team-research", team: "Sample team 3", invitedBy: "Sample Person", email: "you@example.com" }, + { + id: "inv-1", + teamId: "team-research", + team: "Sample team 3", + invitedBy: "Sample Person", + email: "you@example.com", + }, ]; teams.run({ action: "team.accept", team: "inv-1" }); }), From 96ab2864f22f7d1d4902b320ca487bdba3c8748b Mon Sep 17 00:00:00 2001 From: Leo Li Date: Tue, 3 Nov 2026 14:03:29 +0000 Subject: [PATCH 2/9] measure(idle-chats): probe in 3.5 s windows; a footprint read as 0 is unread The page host's script call ends at 5 s, so a 10 s probe timed out. A display run read 0 MB for 24 of 46 live renderers and summed them as 0: the role total said 7.3 GB where the same host now reads 12.9. Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-cb01117327fc358e9ba1 --- scripts/cmux-next/bench_power.py | 18 ++++++++++++----- .../tests/test_bench_power_loaded.py | 20 +++++++++++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/scripts/cmux-next/bench_power.py b/scripts/cmux-next/bench_power.py index 610162fa1a99..aafad2163615 100755 --- a/scripts/cmux-next/bench_power.py +++ b/scripts/cmux-next/bench_power.py @@ -391,7 +391,10 @@ def measure_processes(app_pid: int, bundle: str, label: str, seconds: float, rol span = t1 - t0 steps = [100 * (b[1][1] - a[1][1]) / 1e9 / (b[0] - a[0]) for a, b in zip(samples, samples[1:]) if b[0] > a[0]] role = "app" if kind == "app" else roles.get(pid, kind) - rows.append({"pid": pid, "kind": kind, "role": role, "footprint_mb": round(u1[4] / MB, 1), + # The largest footprint the window read. A live process never has none: a 0 is a read that + # failed (24 of 46 renderers in one display run), so it counts as unread, not as 0 MB. + footprint = max(sample[1][4] for sample in samples) + rows.append({"pid": pid, "kind": kind, "role": role, "footprint_mb": round(footprint / MB, 1) if footprint else None, "cpu_pct": round(100 * (u1[1] - u0[1]) / 1e9 / span, 3), "cpu_p95_pct": round(percentile(steps, 0.95), 3), "idle_wakeups_per_s": round((u1[2] - u0[2]) / span, 2), "interrupt_wakeups_per_s": round((u1[3] - u0[3]) / span, 2), @@ -413,7 +416,8 @@ def measure_processes(app_pid: int, bundle: str, label: str, seconds: float, rol lists = steps_by_role.get(role) or [[]] summed = [sum(values) for values in zip(*lists)] # the role's CPU per 1 s step main = [row["main_thread_pct"] for row in members if row["main_thread_pct"] is not None] - totals[role] = {"count": len(members), "footprint_mb": round(sum(r["footprint_mb"] for r in members), 1), + totals[role] = {"count": len(members), "footprint_mb": round(sum(r["footprint_mb"] or 0 for r in members), 1), + "footprint_unread": sum(1 for r in members if r["footprint_mb"] is None), "cpu_pct": round(sum(r["cpu_pct"] for r in members), 3), "cpu_p95_pct": round(percentile(summed, 0.95), 3), "idle_wakeups_per_s": round(sum(r["idle_wakeups_per_s"] for r in members), 2), "interrupt_wakeups_per_s": round(sum(r["interrupt_wakeups_per_s"] for r in members), 2), @@ -421,6 +425,7 @@ def measure_processes(app_pid: int, bundle: str, label: str, seconds: float, rol "main_thread_pct": round(sum(main), 3) if main else None} for role, entry in totals.items(): print(f"PERF-IDLE-COST {label} role={role!r} n={entry['count']} footprint_mb={entry['footprint_mb']} " + f"footprint_unread={entry['footprint_unread']} " f"cpu_pct={entry['cpu_pct']} cpu_p95_pct={entry['cpu_p95_pct']} idle_wakeups_per_s={entry['idle_wakeups_per_s']} " f"interrupt_wakeups_per_s={entry['interrupt_wakeups_per_s']} wakeups_per_s={entry['wakeups_per_s']} main_thread_pct={entry['main_thread_pct']}", flush=True) return {"label": label, "seconds": round(seconds, 1), "roles": totals, "processes": rows} @@ -557,9 +562,12 @@ def run_loaded(args): if label == "idle-chats": # After the window, so it costs the measurement nothing: what the shown chat's page asks # for while nobody touches it, by call site (idleProbe.ts), for the idle loop's source. - probe = rpc(sock, "debug.agent_pane", {"action": "idle_probe", "ms": 10000}, timeout=45) - result["idle_probe"] = probe - print(f"PERF-IDLE-PROBE {json.dumps(probe)[:20000]}", flush=True) + # Three windows of 3.5 s: a Chromium page's script call ends at 5 s (Runtime.evaluate). + result["idle_probe"] = [] + for _ in range(3): + probe = rpc(sock, "debug.agent_pane", {"action": "idle_probe", "ms": 3500}, timeout=20) + result["idle_probe"].append(probe) + print(f"PERF-IDLE-PROBE {json.dumps(probe)[:20000]}", flush=True) result["renderer_roles"] = "debug.cef_pages" if pages is not None else "none (a build without debug.* methods)" sha = subprocess.run(["git", "rev-parse", "--short=12", "HEAD"], capture_output=True, text=True).stdout.strip() model = subprocess.run(["sysctl", "-n", "hw.model"], capture_output=True, text=True).stdout.strip() diff --git a/scripts/cmux-next/tests/test_bench_power_loaded.py b/scripts/cmux-next/tests/test_bench_power_loaded.py index 5711e258b8d8..28f5e0bbeb5f 100644 --- a/scripts/cmux-next/tests/test_bench_power_loaded.py +++ b/scripts/cmux-next/tests/test_bench_power_loaded.py @@ -68,6 +68,26 @@ def test_measure_sums_roles_and_leaves_the_peer_out(self): self.assertAlmostEqual(result["roles"]["total"]["idle_wakeups_per_s"], 6.0) self.assertAlmostEqual(result["roles"]["total"]["wakeups_per_s"], 15.0) # idle 2 + interrupt 3, three processes + def test_footprint_read_as_zero_is_unread_not_zero(self): + # A display run read 0 MB for 24 of 46 live renderers and summed them as 0 (7.3 GB, not ~13). + clock = FakeClock() + saved = (bp.time, bp.bm.owned, bp.usage_v6, bp.main_thread_ns) + try: + bp.time = clock + bp.bm.owned = lambda pid, bundle: {1: ("app", "app"), 2: ("cef-renderer", "r"), 3: ("cef-renderer", "r")} + bp.usage_v6 = lambda pid: (0, int(1e8 * clock.now), 0, 0, 0 if pid == 3 else 100 * 1048576) + bp.main_thread_ns = lambda pid: None + result = bp.measure_processes(1, "/x.app", "idle-chats", 5, {2: "cef-renderer: agent", 3: "cef-renderer: agent"}, set()) + finally: + bp.time, bp.bm.owned, bp.usage_v6, bp.main_thread_ns = saved + unread = next(r for r in result["processes"] if r["pid"] == 3) + self.assertIsNone(unread["footprint_mb"]) + agent = result["roles"]["cef-renderer: agent"] + self.assertEqual((agent["footprint_mb"], agent["footprint_unread"]), (100.0, 1)) + self.assertEqual(result["roles"]["total"]["footprint_unread"], 1) + rows, _ = bp.process_rows({**result, "label": "idle-chats"}, 5.0) + self.assertTrue(any(row.startswith("| cef-renderer: agent | 3 |") and "| | |" in row for row in rows)) + def test_perf_rows(self): before = {"roles": {"total": {"cpu_pct": 70.0, "footprint_mb": 2000.0, "main_thread_pct": None}}} after = {"roles": {"total": {"cpu_pct": 35.0, "footprint_mb": 2100.0, "main_thread_pct": None}}} From 9166a3de6092286616bf1c945e20c9bdf89d6f88 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Tue, 3 Nov 2026 14:55:25 +0000 Subject: [PATCH 3/9] measure(idle-chats): CPU profile and page metrics of the shown chat at idle debug.agent_pane devtools runs a DevTools method on the chat's Chromium page. The idle-chats bench uses it after the measured window: Performance metrics per second and a 10 s V8 profile by function, so the renderer's idle main-thread time has a name. Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-cb01117327fc358e9ba1 --- .../AgentPaneView+DebugReads.swift | 6 ++ .../CmuxNextApp/Control/DebugAgentPane.swift | 28 +++++++- .../CmuxNextPages/PageWebView+Debug.swift | 7 ++ scripts/cmux-next/bench_power.py | 71 +++++++++++++++++-- .../tests/test_bench_power_loaded.py | 10 +++ 5 files changed, 115 insertions(+), 7 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneView+DebugReads.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneView+DebugReads.swift index b5ea6361a097..23fbca379878 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneView+DebugReads.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneView+DebugReads.swift @@ -5,6 +5,12 @@ import Foundation /// `debug.agent_pane` reads of the chat page that the capture scenes and benches use (DEBUG /// builds): its readiness for a still and the ACP Inspector toggle. extension AgentPaneView { + /// `debug.agent_pane devtools`: DevTools `method` on the chat's Chromium page, its JSON reply. + /// Nil when the chat shows in WebKit. + public func debugDevTools(_ method: String, params: [String: any Sendable]) async throws -> String? { + try await page?.debugDevTools(method, params: params) + } + /// `debug.agent_pane readiness`: whether the page drew a transcript and a composer, and (with /// `waitForAnimations`, up to 1 s) whether its menus finished animating. public func debugReadiness(pane: String, waitForAnimations: Bool = false) async -> JSONValue { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugAgentPane.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugAgentPane.swift index 339801e0c19e..1042dd25b3ee 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugAgentPane.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugAgentPane.swift @@ -217,6 +217,20 @@ enum DebugAgentPane { if action == "set_files" { return .object(["pane": .string(pane), "error": await view.debugSetFiles(selector: params["selector"]?.stringValue ?? ".acpmux-attach-input", paths: params["paths"]?.arrayValue?.compactMap(\.stringValue) ?? []).map(JSONValue.string) ?? .null]) } if action == "hover" { return await DebugAgentPaneClick.hover(params, pane: pane, view: view) } + if action == "devtools" { + // A DevTools method on the chat's Chromium page (the idle bench's Profiler and Performance reads). + guard let method = params["method"]?.stringValue else { return .object(["pane": .string(pane), "error": .string("no method")]) } + var arguments: [String: any Sendable] = [:] + for (key, value) in params["params"]?.objectValue ?? [:] { arguments[key] = sendable(value) } + do { + guard let reply = try await view.debugDevTools(method, params: arguments) else { + return .object(["pane": .string(pane), "error": .string("the chat does not show in Chromium")]) + } + return .object(["pane": .string(pane), "result": .string(reply)]) + } catch { + return .object(["pane": .string(pane), "error": .string(String(describing: error))]) + } + } if action == "pacer" { return .object(["pane": .string(pane), "pacer": JSONValue(foundation: view.debugPacerState) ?? .null]) } if action == "inspector" { return await view.debugToggleInspector(open: params["open"]?.boolValue, pane: pane) } if action == "session_info_action" { return view.debugSessionInfoAction(params, pane: pane) } @@ -226,7 +240,7 @@ enum DebugAgentPane { } } guard let function = functions[action] else { - return .object(["error": .string("unknown action; use seed_rows, fling, fling_stats, perf_stats, typing_stats, reset_typing, close_menus, open_menu, acp_log, acp_log_export, chat_state, send_prompt, new_chat, select_session, pick_folder, compose_send, run_mode, answer_permission, open_changes, set_model, models, stream, layout_watch, idle_probe, readiness, cloud_auth, engine, focus_composer, composer_focused, click, open_subagent, pid, full_rate, gesture_state, session_info_action or inspector")]) + return .object(["error": .string("unknown action; use seed_rows, fling, fling_stats, perf_stats, typing_stats, reset_typing, close_menus, open_menu, acp_log, acp_log_export, chat_state, send_prompt, new_chat, select_session, pick_folder, compose_send, run_mode, answer_permission, open_changes, set_model, models, stream, layout_watch, idle_probe, devtools, readiness, cloud_auth, engine, focus_composer, composer_focused, click, open_subagent, pid, full_rate, gesture_state, session_info_action or inspector")]) } do { let result = try await view.callPageScript(script, arguments: ["fn": function, "args": arguments(action, params)]) @@ -251,6 +265,18 @@ enum DebugAgentPane { unsafeBitCast(method_getImplementation(method), to: SetEnabled.self)(webView, selector, false) } + /// A JSON parameter as the Foundation value a DevTools call takes. + private static func sendable(_ value: JSONValue) -> any Sendable { + switch value { + case .null: return NSNull() + case .bool(let bool): return bool + case .number(let number): return number.rounded() == number && abs(number) < 1e15 ? Int(number) as any Sendable : number + case .string(let string): return string + case .array(let items): return items.map(sendable) + case .object(let members): return members.mapValues(sendable) + } + } + /// The page function's positional arguments, as Foundation values. private static func arguments(_ action: String, _ params: [String: JSONValue]) -> [Any] { switch action { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextPages/PageWebView+Debug.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextPages/PageWebView+Debug.swift index a750808df95f..e4385597ec35 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextPages/PageWebView+Debug.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextPages/PageWebView+Debug.swift @@ -249,6 +249,13 @@ extension PageWebView { return true } + /// Runs DevTools `method` on this page in Chromium and returns its JSON reply (`debug.agent_pane + /// devtools`: the idle bench's CPU profile and page metrics). Nil on a WebKit page. + public func debugDevTools(_ method: String, params: [String: any Sendable]) async throws -> String? { + guard let page = chromiumSession?.page else { return nil } + return try await page.devTools(method, params: params) + } + /// The next file input this page opens in WebKit takes `files` instead of showing the panel. public func debugQueueFiles(_ files: [URL]) { fileChooser?.debugAnswer = files } diff --git a/scripts/cmux-next/bench_power.py b/scripts/cmux-next/bench_power.py index aafad2163615..ede587ca2fb3 100755 --- a/scripts/cmux-next/bench_power.py +++ b/scripts/cmux-next/bench_power.py @@ -527,6 +527,65 @@ def idle_cost_markdown(result: dict, budget: float) -> tuple[str, dict]: return "\n".join(lines) + "\n", verdict +def devtools(sock: str, method: str, params: dict | None = None): + """A DevTools method on the shown chat's Chromium page (`debug.agent_pane devtools`): its reply, parsed.""" + reply = rpc(sock, "debug.agent_pane", {"action": "devtools", "method": method, "params": params or {}}, timeout=60) + if reply.get("error") or not isinstance(reply.get("result"), str): + return {"error": reply.get("error") or "no reply"} + try: + return json.loads(reply["result"]) + except ValueError as error: + return {"error": str(error)} + + +def profile_summary(profile: dict, top: int = 25) -> dict: + """A V8 CPU profile's self time by function (name, script, line), busiest first, in ms.""" + nodes = {node["id"]: node for node in profile.get("nodes", [])} + samples, deltas = profile.get("samples", []), profile.get("timeDeltas", []) + self_us: dict[int, float] = {} + for index, node_id in enumerate(samples): + # A sample's time is the gap to the next one (Chrome DevTools' own attribution). + gap = deltas[index + 1] if index + 1 < len(deltas) else 0 + self_us[node_id] = self_us.get(node_id, 0) + max(gap, 0) + by_function: dict[str, float] = {} + for node_id, micros in self_us.items(): + frame = nodes.get(node_id, {}).get("callFrame", {}) + url = (frame.get("url") or "").rsplit("/", 1)[-1] + key = f"{frame.get('functionName') or '(anonymous)'} {url}:{frame.get('lineNumber', -1) + 1}:{frame.get('columnNumber', -1) + 1}" + by_function[key] = by_function.get(key, 0) + micros + total = sum(by_function.values()) + busiest = sorted(by_function.items(), key=lambda item: -item[1])[:top] + return {"total_ms": round(total / 1000, 1), "self_ms": [[key, round(micros / 1000, 1)] for key, micros in busiest]} + + +def idle_profile(sock: str, seconds: float) -> dict: + """What the shown chat's renderer main thread runs while nobody touches it: Chromium's page + metrics (script, style, layout time and counts) per second over `seconds`, and a V8 CPU + profile of the same window by function. The profiler and the metrics are off again after.""" + def metrics(): + reply = devtools(sock, "Performance.getMetrics") + return {m["name"]: m["value"] for m in reply.get("metrics", [])} if "metrics" in reply else reply + out = {"seconds": seconds} + out["enable"] = [devtools(sock, "Performance.enable"), devtools(sock, "Profiler.enable"), + devtools(sock, "Profiler.setSamplingInterval", {"interval": 500}), devtools(sock, "Profiler.start")] + before = metrics() + time.sleep(seconds) # test script: the profiled idle window + after = metrics() + stopped = devtools(sock, "Profiler.stop") + devtools(sock, "Profiler.disable") + devtools(sock, "Performance.disable") + if isinstance(before, dict) and isinstance(after, dict) and "error" not in before and "error" not in after: + keys = ("TaskDuration", "ScriptDuration", "LayoutDuration", "RecalcStyleDuration", "LayoutCount", + "RecalcStyleCount", "JSHeapUsedSize", "Nodes", "JSEventListeners", "Frames") + out["metrics_per_s"] = {key: round((after.get(key, 0) - before.get(key, 0)) / seconds, 4) for key in keys if key in after} + out["heap_mb"] = round(after.get("JSHeapUsedSize", 0) / MB, 1) + out["nodes"] = after.get("Nodes") + else: + out["metrics_error"] = [before, after] + out["profile"] = profile_summary(stopped["profile"]) if "profile" in stopped else stopped + return out + + def run_loaded(args): """An idle-cost scenario (`loaded` or `idle-chats`, see the module): load, settle, measure, report.""" label = getattr(args, "scenario", "loaded") @@ -562,12 +621,12 @@ def run_loaded(args): if label == "idle-chats": # After the window, so it costs the measurement nothing: what the shown chat's page asks # for while nobody touches it, by call site (idleProbe.ts), for the idle loop's source. - # Three windows of 3.5 s: a Chromium page's script call ends at 5 s (Runtime.evaluate). - result["idle_probe"] = [] - for _ in range(3): - probe = rpc(sock, "debug.agent_pane", {"action": "idle_probe", "ms": 3500}, timeout=20) - result["idle_probe"].append(probe) - print(f"PERF-IDLE-PROBE {json.dumps(probe)[:20000]}", flush=True) + # A 3.5 s window: a Chromium page's script call ends at 5 s (Runtime.evaluate). + probe = rpc(sock, "debug.agent_pane", {"action": "idle_probe", "ms": 3500}, timeout=20) + result["idle_probe"] = probe + print(f"PERF-IDLE-PROBE {json.dumps(probe)[:20000]}", flush=True) + result["idle_profile"] = idle_profile(sock, 10) + print(f"PERF-IDLE-PROFILE {json.dumps(result['idle_profile'])[:20000]}", flush=True) result["renderer_roles"] = "debug.cef_pages" if pages is not None else "none (a build without debug.* methods)" sha = subprocess.run(["git", "rev-parse", "--short=12", "HEAD"], capture_output=True, text=True).stdout.strip() model = subprocess.run(["sysctl", "-n", "hw.model"], capture_output=True, text=True).stdout.strip() diff --git a/scripts/cmux-next/tests/test_bench_power_loaded.py b/scripts/cmux-next/tests/test_bench_power_loaded.py index 28f5e0bbeb5f..25bbd38db0e1 100644 --- a/scripts/cmux-next/tests/test_bench_power_loaded.py +++ b/scripts/cmux-next/tests/test_bench_power_loaded.py @@ -88,6 +88,16 @@ def test_footprint_read_as_zero_is_unread_not_zero(self): rows, _ = bp.process_rows({**result, "label": "idle-chats"}, 5.0) self.assertTrue(any(row.startswith("| cef-renderer: agent | 3 |") and "| | |" in row for row in rows)) + def test_profile_summary_self_time_by_function(self): + profile = {"nodes": [{"id": 1, "callFrame": {"functionName": "(root)", "url": "", "lineNumber": -1, "columnNumber": -1}}, + {"id": 2, "callFrame": {"functionName": "(program)", "url": "", "lineNumber": -1, "columnNumber": -1}}, + {"id": 3, "callFrame": {"functionName": "tick", "url": "cmux-page://cmux.agent/pane.js", "lineNumber": 9, "columnNumber": 4}}], + "samples": [2, 3, 3, 2], "timeDeltas": [0, 1000, 3000, 500]} + summary = bp.profile_summary(profile) + self.assertEqual(summary["self_ms"][0], ["tick pane.js:10:5", 3.5]) + self.assertEqual(summary["self_ms"][1], ["(program) :0:0", 1.0]) + self.assertEqual(summary["total_ms"], 4.5) + def test_perf_rows(self): before = {"roles": {"total": {"cpu_pct": 70.0, "footprint_mb": 2000.0, "main_thread_pct": None}}} after = {"roles": {"total": {"cpu_pct": 35.0, "footprint_mb": 2100.0, "main_thread_pct": None}}} From 687f2e7aba476f0654163527f34feeae33d3e089 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Tue, 3 Nov 2026 15:33:33 +0000 Subject: [PATCH 4/9] measure(idle-chats): profile every shown cmux page by browser id The focused chat read 0 ms of tasks in 10 s while a shown agent renderer sat at 2.6%: the busy page is another one. debug.cef_page_devtools runs a DevTools method on one of cmux's own pages by browser id, and debug.cef_pages gives a cmux page's path, so the bench profiles each shown page in one window and names it. Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-cb01117327fc358e9ba1 --- .../AgentPaneView+DebugReads.swift | 6 -- .../CmuxNextApp/Control/AppControl.swift | 5 ++ .../CmuxNextApp/Control/DebugAgentPane.swift | 28 +------- .../CmuxNextApp/Control/DebugCEFPages.swift | 47 +++++++++++++- .../CEF/CEFEngine+RendererPages.swift | 7 ++ .../CmuxNextPages/PageWebView+Debug.swift | 7 -- scripts/cmux-next/bench_power.py | 64 +++++++++++-------- .../src/pages/settings/settings.gallery.ts | 16 +---- 8 files changed, 97 insertions(+), 83 deletions(-) diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneView+DebugReads.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneView+DebugReads.swift index 23fbca379878..b5ea6361a097 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneView+DebugReads.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/AgentPaneView+DebugReads.swift @@ -5,12 +5,6 @@ import Foundation /// `debug.agent_pane` reads of the chat page that the capture scenes and benches use (DEBUG /// builds): its readiness for a still and the ACP Inspector toggle. extension AgentPaneView { - /// `debug.agent_pane devtools`: DevTools `method` on the chat's Chromium page, its JSON reply. - /// Nil when the chat shows in WebKit. - public func debugDevTools(_ method: String, params: [String: any Sendable]) async throws -> String? { - try await page?.debugDevTools(method, params: params) - } - /// `debug.agent_pane readiness`: whether the page drew a transcript and a composer, and (with /// `waitForAnimations`, up to 1 s) whether its menus finished animating. public func debugReadiness(pane: String, waitForAnimations: Bool = false) async -> JSONValue { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/AppControl.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/AppControl.swift index e633c0e2ee64..f798cbd011b9 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/AppControl.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/AppControl.swift @@ -282,6 +282,11 @@ final class AppControl { guard let services else { return .value(.null) } return .value(debugCEFPagesReport(services)) }, + // A DevTools method on one of cmux's own Chromium pages by browser id (bench_power.py idle-chats). + .async("debug.cef_page_devtools") { [weak services] call in + guard let services else { return .null } + return await debugCEFPageDevTools(call.params, services) + }.withDeadline(.fixed(.seconds(30))), // Chromium process failures, restart state, crash reports. .mainActor("debug.crashes") { [weak services] _ in guard let services else { return .value(.null) } diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugAgentPane.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugAgentPane.swift index 1042dd25b3ee..339801e0c19e 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugAgentPane.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugAgentPane.swift @@ -217,20 +217,6 @@ enum DebugAgentPane { if action == "set_files" { return .object(["pane": .string(pane), "error": await view.debugSetFiles(selector: params["selector"]?.stringValue ?? ".acpmux-attach-input", paths: params["paths"]?.arrayValue?.compactMap(\.stringValue) ?? []).map(JSONValue.string) ?? .null]) } if action == "hover" { return await DebugAgentPaneClick.hover(params, pane: pane, view: view) } - if action == "devtools" { - // A DevTools method on the chat's Chromium page (the idle bench's Profiler and Performance reads). - guard let method = params["method"]?.stringValue else { return .object(["pane": .string(pane), "error": .string("no method")]) } - var arguments: [String: any Sendable] = [:] - for (key, value) in params["params"]?.objectValue ?? [:] { arguments[key] = sendable(value) } - do { - guard let reply = try await view.debugDevTools(method, params: arguments) else { - return .object(["pane": .string(pane), "error": .string("the chat does not show in Chromium")]) - } - return .object(["pane": .string(pane), "result": .string(reply)]) - } catch { - return .object(["pane": .string(pane), "error": .string(String(describing: error))]) - } - } if action == "pacer" { return .object(["pane": .string(pane), "pacer": JSONValue(foundation: view.debugPacerState) ?? .null]) } if action == "inspector" { return await view.debugToggleInspector(open: params["open"]?.boolValue, pane: pane) } if action == "session_info_action" { return view.debugSessionInfoAction(params, pane: pane) } @@ -240,7 +226,7 @@ enum DebugAgentPane { } } guard let function = functions[action] else { - return .object(["error": .string("unknown action; use seed_rows, fling, fling_stats, perf_stats, typing_stats, reset_typing, close_menus, open_menu, acp_log, acp_log_export, chat_state, send_prompt, new_chat, select_session, pick_folder, compose_send, run_mode, answer_permission, open_changes, set_model, models, stream, layout_watch, idle_probe, devtools, readiness, cloud_auth, engine, focus_composer, composer_focused, click, open_subagent, pid, full_rate, gesture_state, session_info_action or inspector")]) + return .object(["error": .string("unknown action; use seed_rows, fling, fling_stats, perf_stats, typing_stats, reset_typing, close_menus, open_menu, acp_log, acp_log_export, chat_state, send_prompt, new_chat, select_session, pick_folder, compose_send, run_mode, answer_permission, open_changes, set_model, models, stream, layout_watch, idle_probe, readiness, cloud_auth, engine, focus_composer, composer_focused, click, open_subagent, pid, full_rate, gesture_state, session_info_action or inspector")]) } do { let result = try await view.callPageScript(script, arguments: ["fn": function, "args": arguments(action, params)]) @@ -265,18 +251,6 @@ enum DebugAgentPane { unsafeBitCast(method_getImplementation(method), to: SetEnabled.self)(webView, selector, false) } - /// A JSON parameter as the Foundation value a DevTools call takes. - private static func sendable(_ value: JSONValue) -> any Sendable { - switch value { - case .null: return NSNull() - case .bool(let bool): return bool - case .number(let number): return number.rounded() == number && abs(number) < 1e15 ? Int(number) as any Sendable : number - case .string(let string): return string - case .array(let items): return items.map(sendable) - case .object(let members): return members.mapValues(sendable) - } - } - /// The page function's positional arguments, as Foundation values. private static func arguments(_ action: String, _ params: [String: JSONValue]) -> [Any] { switch action { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugCEFPages.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugCEFPages.swift index f1b556a8a0e2..f4979a70f7c1 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugCEFPages.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugCEFPages.swift @@ -1,4 +1,5 @@ import CmuxNextBrowser +import Foundation import CmuxNextSettings /// `debug.cef_pages`: every live Chromium page's origin (scheme and host only), whether the content @@ -8,7 +9,49 @@ import CmuxNextSettings @MainActor func debugCEFPagesReport(_ services: AppServices) -> JSONValue { .object(["pages": .array(services.cache.cef.rendererPages.map { page in - .object(["browser": .number(Double(page.browserID)), "origin": .string(page.origin), "hidden": .bool(page.hidden), - "renderer_clients": .array(page.rendererClients.map { .number(Double($0)) })]) + var members: [String: JSONValue] = [ + "browser": .number(Double(page.browserID)), "origin": .string(page.origin), "hidden": .bool(page.hidden), + "renderer_clients": .array(page.rendererClients.map { .number(Double($0)) }), + ] + // cmux's own pages also give their path (the agent page's chat or New Tab), never a query; + // a browser tab keeps only its origin. + if page.origin.hasPrefix("cmux-page://") { members["path"] = .string(URL(string: page.url)?.path ?? "") } + return .object(members) })]) } + +/// `debug.cef_page_devtools {browser, method, params}`: a DevTools method on one of cmux's own +/// Chromium pages by browser id (`debug.cef_pages`), its JSON reply. The idle bench reads each +/// shown page's metrics and CPU profile with it. Browser tabs are refused: this reads only cmux's pages. +@MainActor +func debugCEFPageDevTools(_ params: [String: JSONValue], _ services: AppServices) async -> JSONValue { + guard let browser = params["browser"]?.intValue, let method = params["method"]?.stringValue else { + return .object(["error": .string("browser and method are required")]) + } + guard let page = services.cache.cef.rendererPages.first(where: { $0.browserID == Int32(browser) }) else { + return .object(["error": .string("no live page \(browser)")]) + } + guard page.origin.hasPrefix("cmux-page://") else { return .object(["error": .string("only cmux's own pages")]) } + var arguments: [String: any Sendable] = [:] + for (key, value) in params["params"]?.objectValue ?? [:] { arguments[key] = debugDevToolsValue(value) } + do { + guard let reply = try await services.cache.cef.devTools(browserID: Int32(browser), method: method, params: arguments) else { + return .object(["error": .string("no live page \(browser)")]) + } + return .object(["result": .string(reply)]) + } catch { + return .object(["error": .string(String(describing: error))]) + } +} + +/// A JSON parameter as the Foundation value a DevTools call takes. +func debugDevToolsValue(_ value: JSONValue) -> any Sendable { + switch value { + case .null: return NSNull() + case .bool(let bool): return bool + case .number(let number): return number.rounded() == number && abs(number) < 1e15 ? Int(number) as any Sendable : number + case .string(let string): return string + case .array(let items): return items.map(debugDevToolsValue) + case .object(let members): return members.mapValues(debugDevToolsValue) + } +} diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFEngine+RendererPages.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFEngine+RendererPages.swift index 0286839af3b9..2ea745a631aa 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFEngine+RendererPages.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextBrowser/CEF/CEFEngine+RendererPages.swift @@ -33,6 +33,13 @@ extension CEFEngine { } } + /// Runs DevTools `method` on the live page `browserID` (`debug.cef_page_devtools`: the idle + /// bench's page metrics and CPU profile). Nil when no live page has that id. + public func devTools(browserID: Int32, method: String, params: [String: any Sendable]) async throws -> String? { + guard let tab = CEFRuntime.shared.tabsByBrowser[browserID] else { return nil } + return try await tab.devTools(method: method, params: params) + } + /// The browser id of the live page whose content view is `view` (a cmux page's Chromium view, /// such as an agent pane's ``focusTarget``), so `renderers.list` can name its owning tab. public func browserID(showing view: NSView) -> Int32? { diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextPages/PageWebView+Debug.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextPages/PageWebView+Debug.swift index e4385597ec35..a750808df95f 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextPages/PageWebView+Debug.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextPages/PageWebView+Debug.swift @@ -249,13 +249,6 @@ extension PageWebView { return true } - /// Runs DevTools `method` on this page in Chromium and returns its JSON reply (`debug.agent_pane - /// devtools`: the idle bench's CPU profile and page metrics). Nil on a WebKit page. - public func debugDevTools(_ method: String, params: [String: any Sendable]) async throws -> String? { - guard let page = chromiumSession?.page else { return nil } - return try await page.devTools(method, params: params) - } - /// The next file input this page opens in WebKit takes `files` instead of showing the panel. public func debugQueueFiles(_ files: [URL]) { fileChooser?.debugAnswer = files } diff --git a/scripts/cmux-next/bench_power.py b/scripts/cmux-next/bench_power.py index ede587ca2fb3..33919c2f6530 100755 --- a/scripts/cmux-next/bench_power.py +++ b/scripts/cmux-next/bench_power.py @@ -527,9 +527,9 @@ def idle_cost_markdown(result: dict, budget: float) -> tuple[str, dict]: return "\n".join(lines) + "\n", verdict -def devtools(sock: str, method: str, params: dict | None = None): - """A DevTools method on the shown chat's Chromium page (`debug.agent_pane devtools`): its reply, parsed.""" - reply = rpc(sock, "debug.agent_pane", {"action": "devtools", "method": method, "params": params or {}}, timeout=60) +def devtools(sock: str, browser: int, method: str, params: dict | None = None): + """A DevTools method on cmux's own Chromium page `browser` (`debug.cef_page_devtools`): its reply, parsed.""" + reply = rpc(sock, "debug.cef_page_devtools", {"browser": browser, "method": method, "params": params or {}}, timeout=60) if reply.get("error") or not isinstance(reply.get("result"), str): return {"error": reply.get("error") or "no reply"} try: @@ -558,31 +558,39 @@ def profile_summary(profile: dict, top: int = 25) -> dict: return {"total_ms": round(total / 1000, 1), "self_ms": [[key, round(micros / 1000, 1)] for key, micros in busiest]} -def idle_profile(sock: str, seconds: float) -> dict: - """What the shown chat's renderer main thread runs while nobody touches it: Chromium's page - metrics (script, style, layout time and counts) per second over `seconds`, and a V8 CPU - profile of the same window by function. The profiler and the metrics are off again after.""" - def metrics(): - reply = devtools(sock, "Performance.getMetrics") +def idle_profile(sock: str, pages: list[dict], seconds: float) -> list[dict]: + """What each shown cmux page's renderer main thread runs while nobody touches it, all in one + window of `seconds`: Chromium's page metrics (task, script, style and layout time, counts) per + second, and a V8 CPU profile by function. The profilers and the metrics are off again after.""" + shown = [page for page in pages if not page.get("hidden") and str(page.get("origin", "")).startswith("cmux-page://")] + def metrics(browser): + reply = devtools(sock, browser, "Performance.getMetrics") return {m["name"]: m["value"] for m in reply.get("metrics", [])} if "metrics" in reply else reply - out = {"seconds": seconds} - out["enable"] = [devtools(sock, "Performance.enable"), devtools(sock, "Profiler.enable"), - devtools(sock, "Profiler.setSamplingInterval", {"interval": 500}), devtools(sock, "Profiler.start")] - before = metrics() + for page in shown: + for method, params in (("Performance.enable", None), ("Profiler.enable", None), + ("Profiler.setSamplingInterval", {"interval": 500}), ("Profiler.start", None)): + devtools(sock, page["browser"], method, params) + before = {page["browser"]: metrics(page["browser"]) for page in shown} time.sleep(seconds) # test script: the profiled idle window - after = metrics() - stopped = devtools(sock, "Profiler.stop") - devtools(sock, "Profiler.disable") - devtools(sock, "Performance.disable") - if isinstance(before, dict) and isinstance(after, dict) and "error" not in before and "error" not in after: - keys = ("TaskDuration", "ScriptDuration", "LayoutDuration", "RecalcStyleDuration", "LayoutCount", - "RecalcStyleCount", "JSHeapUsedSize", "Nodes", "JSEventListeners", "Frames") - out["metrics_per_s"] = {key: round((after.get(key, 0) - before.get(key, 0)) / seconds, 4) for key in keys if key in after} - out["heap_mb"] = round(after.get("JSHeapUsedSize", 0) / MB, 1) - out["nodes"] = after.get("Nodes") - else: - out["metrics_error"] = [before, after] - out["profile"] = profile_summary(stopped["profile"]) if "profile" in stopped else stopped + after = {page["browser"]: metrics(page["browser"]) for page in shown} + out = [] + for page in shown: + browser = page["browser"] + stopped = devtools(sock, browser, "Profiler.stop") + devtools(sock, browser, "Profiler.disable") + devtools(sock, browser, "Performance.disable") + entry = {"browser": browser, "origin": page.get("origin"), "path": page.get("path"), + "renderer_clients": page.get("renderer_clients"), "seconds": seconds} + first, last = before[browser], after[browser] + if "error" not in first and "error" not in last: + keys = ("TaskDuration", "ScriptDuration", "LayoutDuration", "RecalcStyleDuration", "LayoutCount", "RecalcStyleCount") + entry["metrics_per_s"] = {key: round((last.get(key, 0) - first.get(key, 0)) / seconds, 4) for key in keys if key in last} + entry["heap_mb"] = round(last.get("JSHeapUsedSize", 0) / MB, 1) + entry["nodes"] = last.get("Nodes") + else: + entry["metrics_error"] = [first, last] + entry["profile"] = profile_summary(stopped["profile"]) if "profile" in stopped else stopped + out.append(entry) return out @@ -625,7 +633,9 @@ def run_loaded(args): probe = rpc(sock, "debug.agent_pane", {"action": "idle_probe", "ms": 3500}, timeout=20) result["idle_probe"] = probe print(f"PERF-IDLE-PROBE {json.dumps(probe)[:20000]}", flush=True) - result["idle_profile"] = idle_profile(sock, 10) + pages_now = (rpc(sock, "debug.cef_pages") or {}).get("pages") or [] + result["pages"] = pages_now + result["idle_profile"] = idle_profile(sock, pages_now, 10) print(f"PERF-IDLE-PROFILE {json.dumps(result['idle_profile'])[:20000]}", flush=True) result["renderer_roles"] = "debug.cef_pages" if pages is not None else "none (a build without debug.* methods)" sha = subprocess.run(["git", "rev-parse", "--short=12", "HEAD"], capture_output=True, text=True).stdout.strip() diff --git a/webviews/src/pages/settings/settings.gallery.ts b/webviews/src/pages/settings/settings.gallery.ts index 38bf6182f8f8..3606707c2620 100644 --- a/webviews/src/pages/settings/settings.gallery.ts +++ b/webviews/src/pages/settings/settings.gallery.ts @@ -1255,13 +1255,7 @@ Object.assign(variants, { "accounts-team-invited": variant("accounts", { accounts: withTeams((teams) => { teams.received = [ - { - id: "inv-1", - teamId: "team-research", - team: "Sample team 3", - invitedBy: "Sample Person", - email: "you@example.com", - }, + { id: "inv-1", teamId: "team-research", team: "Sample team 3", invitedBy: "Sample Person", email: "you@example.com" }, { id: "inv-2", teamId: "team-design", team: "Sample team 4", invitedBy: null, email: "you@example.com" }, ]; }), @@ -1270,13 +1264,7 @@ Object.assign(variants, { "accounts-team-joined": variant("accounts", { accounts: withTeams((teams) => { teams.received = [ - { - id: "inv-1", - teamId: "team-research", - team: "Sample team 3", - invitedBy: "Sample Person", - email: "you@example.com", - }, + { id: "inv-1", teamId: "team-research", team: "Sample team 3", invitedBy: "Sample Person", email: "you@example.com" }, ]; teams.run({ action: "team.accept", team: "inv-1" }); }), From 73424ddfdfe5b9cd0337cedb127670e3cc9b3a6a Mon Sep 17 00:00:00 2001 From: Leo Li Date: Tue, 3 Nov 2026 16:31:52 +0000 Subject: [PATCH 5/9] measure(idle-chats): a native sample of each renderer over 1% CPU Every shown cmux page read 0 ms of tasks and an idle V8 profile in 10 s while renderer-client-id=6's main thread still took 2.5%: the work is native. The bench samples each renderer over 1% for 8 s after the window and keeps its main thread's call tree and heaviest frames. Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-cb01117327fc358e9ba1 --- scripts/cmux-next/bench_power.py | 36 ++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/scripts/cmux-next/bench_power.py b/scripts/cmux-next/bench_power.py index 33919c2f6530..2e46a2d4c567 100755 --- a/scripts/cmux-next/bench_power.py +++ b/scripts/cmux-next/bench_power.py @@ -558,6 +558,36 @@ def profile_summary(profile: dict, top: int = 25) -> dict: return {"total_ms": round(total / 1000, 1), "self_ms": [[key, round(micros / 1000, 1)] for key, micros in busiest]} +def native_sample(pid: int, role: str, seconds: int) -> dict: + """`sample PID seconds` (macOS): the main thread's call tree, its first 200 lines, and the + heaviest frames of the whole process (the tool's "Sort by top of stack" section).""" + out_path = os.path.join(tempfile.gettempdir(), f"idle-sample-{pid}.txt") + try: + subprocess.run(["/usr/bin/sample", str(pid), str(seconds), "1", "-mayDie", "-file", out_path], + capture_output=True, timeout=seconds + 60, check=False) + text = open(out_path, errors="replace").read() + except (OSError, subprocess.SubprocessError) as error: + return {"pid": pid, "role": role, "error": str(error)} + finally: + if os.path.exists(out_path): + os.remove(out_path) + lines = text.splitlines() + main, inside = [], False + for line in lines: + if "Thread_" in line and ("main-thread" in line or "DispatchQueue_1" in line or "CrRendererMain" in line): + inside = True + elif inside and re.match(r"\s*\d+ Thread_", line): + break + if inside: + main.append(line[:220]) + if len(main) >= 200: + break + top = [] + if "Sort by top of stack" in text: + top = text.split("Sort by top of stack", 1)[1].splitlines()[1:40] + return {"pid": pid, "role": role, "seconds": seconds, "main": "\n".join(main), "top": "\n".join(line[:200] for line in top)} + + def idle_profile(sock: str, pages: list[dict], seconds: float) -> list[dict]: """What each shown cmux page's renderer main thread runs while nobody touches it, all in one window of `seconds`: Chromium's page metrics (task, script, style and layout time, counts) per @@ -637,6 +667,12 @@ def run_loaded(args): result["pages"] = pages_now result["idle_profile"] = idle_profile(sock, pages_now, 10) print(f"PERF-IDLE-PROFILE {json.dumps(result['idle_profile'])[:20000]}", flush=True) + # A page's script and tasks can read 0 while its renderer's main thread still burns: a native + # sample of each renderer over 1% names that work. + busy = [row for row in result["processes"] if row["kind"] == "cef-renderer" and row["cpu_pct"] > 1][:3] + result["native_samples"] = [native_sample(row["pid"], row["role"], 8) for row in busy] + for entry in result["native_samples"]: + print(f"PERF-IDLE-SAMPLE pid={entry['pid']} role={entry['role']!r}\n{entry.get('main', entry.get('error'))}", flush=True) result["renderer_roles"] = "debug.cef_pages" if pages is not None else "none (a build without debug.* methods)" sha = subprocess.run(["git", "rev-parse", "--short=12", "HEAD"], capture_output=True, text=True).stdout.strip() model = subprocess.run(["sysctl", "-n", "hw.model"], capture_output=True, text=True).stdout.strip() From 0be9ff19e046f96dcc2f522aecd6890bb6607354 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Tue, 3 Nov 2026 16:58:28 +0000 Subject: [PATCH 6/9] measure(idle-chats): profile_before=1 also profiles the shown pages before the window The native samples after the window found every busy renderer's main thread waiting: the idle cost may be work that ends by then. Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-cb01117327fc358e9ba1 --- scripts/cmux-next/bench_power.py | 6 ++++++ scripts/measure/perf-idle-power.sh | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/scripts/cmux-next/bench_power.py b/scripts/cmux-next/bench_power.py index 2e46a2d4c567..360179d15008 100755 --- a/scripts/cmux-next/bench_power.py +++ b/scripts/cmux-next/bench_power.py @@ -653,8 +653,14 @@ def run_loaded(args): time.sleep(args.settle) # test script: let the app settle pages = (rpc(sock, "debug.cef_pages") or {}).get("pages") roles = renderer_roles(pages or [], bm.owned(pid, args.app)) + # IDLE_PROFILE_BEFORE=1: profile the shown pages for 10 s just before the window too, so work + # that stops by the end of the window (post-load GC, compiles) still has a name. + before_profile = idle_profile(sock, pages or [], 10) if label == "idle-chats" and os.environ.get("IDLE_PROFILE_BEFORE") else None time.sleep(5) # test script: the debug read's own work ends before the window result = measure_processes(pid, args.app, label, args.measure, roles, peer.pids()) + if before_profile is not None: + result["idle_profile_before"] = before_profile + print(f"PERF-IDLE-PROFILE-BEFORE {json.dumps(before_profile)[:20000]}", flush=True) result["load"] = reached if label == "idle-chats": # After the window, so it costs the measurement nothing: what the shown chat's page asks diff --git a/scripts/measure/perf-idle-power.sh b/scripts/measure/perf-idle-power.sh index 0cc9a89e7540..8173d005c89e 100755 --- a/scripts/measure/perf-idle-power.sh +++ b/scripts/measure/perf-idle-power.sh @@ -17,7 +17,7 @@ # cmux-ci run --class exclusive --measurement --label measure \ # --script scripts/measure/perf-idle-power.sh --ref SHA --arg=scenarios=idle-chats \ # --arg=config=bench --artifact artifacts/perf-idle-power.json \ -# [--arg=chats=40] [--arg=settle=60] [--arg=measure=120] [--arg=budget=5] +# [--arg=chats=40] [--arg=settle=60] [--arg=measure=120] [--arg=budget=5] [--arg=profile_before=1] # The log prints the per-process table between PERF-IDLE-CHATS-TABLE-BEGIN and -END; # the JSON keeps it as results[0].markdown. # Output: PERF-POWER lines; JSON at artifacts/perf-idle-power.json. @@ -42,6 +42,7 @@ for arg in "$@"; do settings=*) settings="${arg#settings=}" ;; freeze=*) freeze="${arg#freeze=}"; [[ "$freeze" =~ ^[0-9]+$ ]] || { echo "perf-idle-power.sh: freeze=SECONDS" >&2; exit 2; } ;; neighbors=*) neighbors="${arg#neighbors=}"; [[ "$neighbors" =~ ^[0-3]$ ]] || { echo "perf-idle-power.sh: neighbors=0..3" >&2; exit 2; } ;; + profile_before=1) export IDLE_PROFILE_BEFORE=1 ;; *) echo "perf-idle-power.sh: unknown argument $arg" >&2; exit 2 ;; esac done From ef35ed96d75b28a1b476ff4c292c38807c7f09f7 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Tue, 3 Nov 2026 17:17:27 +0000 Subject: [PATCH 7/9] measure(idle-chats): diagnostic before-window profile (temporary) Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-cb01117327fc358e9ba1 --- scripts/cmux-next/bench_power.py | 4 ++-- scripts/measure/perf-idle-power.sh | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/scripts/cmux-next/bench_power.py b/scripts/cmux-next/bench_power.py index 360179d15008..ed770df28fdf 100755 --- a/scripts/cmux-next/bench_power.py +++ b/scripts/cmux-next/bench_power.py @@ -653,9 +653,9 @@ def run_loaded(args): time.sleep(args.settle) # test script: let the app settle pages = (rpc(sock, "debug.cef_pages") or {}).get("pages") roles = renderer_roles(pages or [], bm.owned(pid, args.app)) - # IDLE_PROFILE_BEFORE=1: profile the shown pages for 10 s just before the window too, so work + # DIAGNOSTIC (drop before landing): profile the shown pages for 10 s just before the window too, so work # that stops by the end of the window (post-load GC, compiles) still has a name. - before_profile = idle_profile(sock, pages or [], 10) if label == "idle-chats" and os.environ.get("IDLE_PROFILE_BEFORE") else None + before_profile = idle_profile(sock, pages or [], 10) if label == "idle-chats" else None time.sleep(5) # test script: the debug read's own work ends before the window result = measure_processes(pid, args.app, label, args.measure, roles, peer.pids()) if before_profile is not None: diff --git a/scripts/measure/perf-idle-power.sh b/scripts/measure/perf-idle-power.sh index 8173d005c89e..0cc9a89e7540 100755 --- a/scripts/measure/perf-idle-power.sh +++ b/scripts/measure/perf-idle-power.sh @@ -17,7 +17,7 @@ # cmux-ci run --class exclusive --measurement --label measure \ # --script scripts/measure/perf-idle-power.sh --ref SHA --arg=scenarios=idle-chats \ # --arg=config=bench --artifact artifacts/perf-idle-power.json \ -# [--arg=chats=40] [--arg=settle=60] [--arg=measure=120] [--arg=budget=5] [--arg=profile_before=1] +# [--arg=chats=40] [--arg=settle=60] [--arg=measure=120] [--arg=budget=5] # The log prints the per-process table between PERF-IDLE-CHATS-TABLE-BEGIN and -END; # the JSON keeps it as results[0].markdown. # Output: PERF-POWER lines; JSON at artifacts/perf-idle-power.json. @@ -42,7 +42,6 @@ for arg in "$@"; do settings=*) settings="${arg#settings=}" ;; freeze=*) freeze="${arg#freeze=}"; [[ "$freeze" =~ ^[0-9]+$ ]] || { echo "perf-idle-power.sh: freeze=SECONDS" >&2; exit 2; } ;; neighbors=*) neighbors="${arg#neighbors=}"; [[ "$neighbors" =~ ^[0-3]$ ]] || { echo "perf-idle-power.sh: neighbors=0..3" >&2; exit 2; } ;; - profile_before=1) export IDLE_PROFILE_BEFORE=1 ;; *) echo "perf-idle-power.sh: unknown argument $arg" >&2; exit 2 ;; esac done From 7dd177d8e4e559612376751dc228152cda1c9d23 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Tue, 3 Nov 2026 18:33:50 +0000 Subject: [PATCH 8/9] measure(idle-chats): drop the diagnostic before-window profile Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-cb01117327fc358e9ba1 --- scripts/cmux-next/bench_power.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/scripts/cmux-next/bench_power.py b/scripts/cmux-next/bench_power.py index ed770df28fdf..2e46a2d4c567 100755 --- a/scripts/cmux-next/bench_power.py +++ b/scripts/cmux-next/bench_power.py @@ -653,14 +653,8 @@ def run_loaded(args): time.sleep(args.settle) # test script: let the app settle pages = (rpc(sock, "debug.cef_pages") or {}).get("pages") roles = renderer_roles(pages or [], bm.owned(pid, args.app)) - # DIAGNOSTIC (drop before landing): profile the shown pages for 10 s just before the window too, so work - # that stops by the end of the window (post-load GC, compiles) still has a name. - before_profile = idle_profile(sock, pages or [], 10) if label == "idle-chats" else None time.sleep(5) # test script: the debug read's own work ends before the window result = measure_processes(pid, args.app, label, args.measure, roles, peer.pids()) - if before_profile is not None: - result["idle_profile_before"] = before_profile - print(f"PERF-IDLE-PROFILE-BEFORE {json.dumps(before_profile)[:20000]}", flush=True) result["load"] = reached if label == "idle-chats": # After the window, so it costs the measurement nothing: what the shown chat's page asks From 77ff2e9ce61457654175c42ae466a77ab626560e Mon Sep 17 00:00:00 2001 From: Leo Li Date: Tue, 3 Nov 2026 18:49:23 +0000 Subject: [PATCH 9/9] Review follow-ups: one idle probe at a time; a browser id outside Int32 is an input error A probe that started while another ran saved the first one's wrappers and put them back for good; it is now refused. debug.cef_page_devtools read the browser id with Int32(_:), which traps past Int32's range. Co-Authored-By: Claude Opus 5.5 Agent-Session: https://cmux.com/deeplink/agent?id=aid-cb01117327fc358e9ba1 --- .../CmuxNextApp/Control/DebugCEFPages.swift | 8 ++-- .../src/agent-session/acpmux/idleProbe.ts | 13 +++++ webviews/test/agent-pane-idle-probe.test.ts | 48 +++++++++++++++++++ 3 files changed, 65 insertions(+), 4 deletions(-) create mode 100644 webviews/test/agent-pane-idle-probe.test.ts diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugCEFPages.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugCEFPages.swift index f4979a70f7c1..6f5ca301fb65 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugCEFPages.swift +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugCEFPages.swift @@ -25,17 +25,17 @@ func debugCEFPagesReport(_ services: AppServices) -> JSONValue { /// shown page's metrics and CPU profile with it. Browser tabs are refused: this reads only cmux's pages. @MainActor func debugCEFPageDevTools(_ params: [String: JSONValue], _ services: AppServices) async -> JSONValue { - guard let browser = params["browser"]?.intValue, let method = params["method"]?.stringValue else { - return .object(["error": .string("browser and method are required")]) + guard let id = params["browser"]?.intValue, let browser = Int32(exactly: id), let method = params["method"]?.stringValue else { + return .object(["error": .string("browser (a browser id) and method are required")]) } - guard let page = services.cache.cef.rendererPages.first(where: { $0.browserID == Int32(browser) }) else { + guard let page = services.cache.cef.rendererPages.first(where: { $0.browserID == browser }) else { return .object(["error": .string("no live page \(browser)")]) } guard page.origin.hasPrefix("cmux-page://") else { return .object(["error": .string("only cmux's own pages")]) } var arguments: [String: any Sendable] = [:] for (key, value) in params["params"]?.objectValue ?? [:] { arguments[key] = debugDevToolsValue(value) } do { - guard let reply = try await services.cache.cef.devTools(browserID: Int32(browser), method: method, params: arguments) else { + guard let reply = try await services.cache.cef.devTools(browserID: browser, method: method, params: arguments) else { return .object(["error": .string("no live page \(browser)")]) } return .object(["result": .string(reply)]) diff --git a/webviews/src/agent-session/acpmux/idleProbe.ts b/webviews/src/agent-session/acpmux/idleProbe.ts index 1b353535bcf2..67947da6c55b 100644 --- a/webviews/src/agent-session/acpmux/idleProbe.ts +++ b/webviews/src/agent-session/acpmux/idleProbe.ts @@ -35,7 +35,20 @@ function top(map: Map, limit = 12) { .map(([site, { count, sample }]) => ({ site, count, sample })); } +/** A probe in its window: a second one would save the first one's wrappers and put them back for good. */ +let probing = false; + export async function idleProbe(options: IdleProbeOptions = {}): Promise> { + if (probing) return { error: "an idle probe is already running" }; + probing = true; + try { + return await probe(options); + } finally { + probing = false; + } +} + +async function probe(options: IdleProbeOptions): Promise> { const ms = Math.max(100, Math.min(30_000, options.ms ?? 10_000)); const frames = new Map(); const timeouts = new Map(); diff --git a/webviews/test/agent-pane-idle-probe.test.ts b/webviews/test/agent-pane-idle-probe.test.ts new file mode 100644 index 000000000000..d10304f972ab --- /dev/null +++ b/webviews/test/agent-pane-idle-probe.test.ts @@ -0,0 +1,48 @@ +// The idle probe (`debug.agent_pane idle_probe`) counts a page's timers by call site and puts the +// page's own functions back when its window ends; a second probe while one runs is refused, so it +// can never save the first one's wrappers and leave them installed. +/// +import { afterAll, beforeAll, expect, test } from "bun:test"; +import { Window } from "happy-dom"; + +const window = new Window(); +const saved: Record = {}; +const names = ["window", "document", "MutationObserver", "performance", "Element"] as const; + +beforeAll(() => { + for (const name of names) saved[name] = (globalThis as Record)[name]; + Object.assign(globalThis, { + window, + document: window.document, + MutationObserver: window.MutationObserver, + Element: window.Element, + }); +}); + +afterAll(() => { + for (const name of names) (globalThis as Record)[name] = saved[name]; + void window.happyDOM.close(); +}); + +test("a probe counts timeouts by call site and restores the page's functions", async () => { + const { idleProbe } = await import("../src/agent-session/acpmux/idleProbe"); + const before = { raf: window.requestAnimationFrame, timeout: window.setTimeout, interval: window.setInterval }; + const running = idleProbe({ ms: 150 }); + window.setTimeout(() => undefined, 5); + window.setTimeout(() => undefined, 5); + const result = (await running) as { per_second: { timeouts: number }; timeouts: { count: number }[] }; + expect(result.timeouts.reduce((sum, site) => sum + site.count, 0)).toBe(2); + expect(window.requestAnimationFrame).toBe(before.raf); + expect(window.setTimeout).toBe(before.timeout); + expect(window.setInterval).toBe(before.interval); +}); + +test("a second probe while one runs is refused and the first still restores", async () => { + const { idleProbe } = await import("../src/agent-session/acpmux/idleProbe"); + const original = window.setTimeout; + const first = idleProbe({ ms: 200 }); + const second = await idleProbe({ ms: 100 }); + expect(second).toEqual({ error: "an idle probe is already running" }); + await first; + expect(window.setTimeout).toBe(original); +});