diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/AppControl.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/AppControl.swift index 2cae57e23f63..d29464da4b1d 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 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/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugCEFPages.swift b/Packages/macOS/CmuxNext/Sources/CmuxNextApp/Control/DebugCEFPages.swift index f1b556a8a0e2..6f5ca301fb65 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 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 == 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: 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/scripts/cmux-next/bench_power.py b/scripts/cmux-next/bench_power.py index a2d334c6bddd..2e46a2d4c567 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} @@ -522,6 +527,103 @@ def idle_cost_markdown(result: dict, budget: float) -> tuple[str, dict]: return "\n".join(lines) + "\n", verdict +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: + 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 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 + 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 + 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 = {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 + + def run_loaded(args): """An idle-cost scenario (`loaded` or `idle-chats`, see the module): load, settle, measure, report.""" label = getattr(args, "scenario", "loaded") @@ -554,6 +656,23 @@ 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. + # 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) + 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) + # 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() diff --git a/scripts/cmux-next/tests/test_bench_power_loaded.py b/scripts/cmux-next/tests/test_bench_power_loaded.py index 5711e258b8d8..25bbd38db0e1 100644 --- a/scripts/cmux-next/tests/test_bench_power_loaded.py +++ b/scripts/cmux-next/tests/test_bench_power_loaded.py @@ -68,6 +68,36 @@ 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_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}}} diff --git a/webviews/src/agent-session/acpmux/debug.ts b/webviews/src/agent-session/acpmux/debug.ts index bd20f8e68e7b..e1d79dd21964 100644 --- a/webviews/src/agent-session/acpmux/debug.ts +++ b/webviews/src/agent-session/acpmux/debug.ts @@ -11,6 +11,7 @@ import { shownPresence } from "./multiplayer/LivePresence"; import { acpWire, type AcpWireLog } from "./wire"; import { followTrace } from "./followTrace"; import { composerChips, layoutWatch, type LayoutWatchOptions } from "./layoutWatch"; +import type { IdleProbeOptions } from "./idleProbe"; import { queuedRowsState } from "./queuedRowsState"; import { composerAttachmentsState } from "./composerAttachmentsState"; import { cloudSignedInForDebug } from "./cloudMachines"; @@ -63,6 +64,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). */ @@ -380,6 +383,11 @@ export function createAcpmuxDebug( layoutWatch(options = {}) { return layoutWatch(options); }, + + async idleProbe(options = {}) { + const { idleProbe } = await import("./idleProbe"); + return idleProbe(options); + }, async stream(options = {}) { const { runStream } = await import("./streamDebug"); 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..67947da6c55b --- /dev/null +++ b/webviews/src/agent-session/acpmux/idleProbe.ts @@ -0,0 +1,161 @@ +// 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 })); +} + +/** 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(); + 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/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); +});