diff --git a/README.md b/README.md index 5ffb8d80b6..547c2ad747 100644 --- a/README.md +++ b/README.md @@ -227,6 +227,7 @@ Optional scripts, references, and assets follow the Codex skill folder structure | `bun run storybook` | Start Storybook on a port allocated through the same registry, so two worktrees never announce one port. `OPENBOT_STORYBOOK_PORT` moves where the search starts; `--port` is refused. | | `bun run build-storybook` | Build static Storybook. CI sets `OPENBOT_STORYBOOK_CHECK=true` to skip automatic prop documentation during its build check. | | `bun run dev:automation` | Drive the running dev app over CDP: `instances`, `pages`, `snapshot`, `screenshot`, `click`/`type` by accessible role. `--page=` aims at any window, including embedded browser views; `--wait-for=,` settles on an accessible target instead of polling; mutations need `--allow-mutations` and a named instance (this worktree's record, `--instance=` or `--port=`). | +| `bun run dev:cpu` | Measure idle CPU on the running dev app, per process kind and per page. `--duration=` (default 60000), `--interval=` (default 5000), `--label=`, `--out=` (under `.openbot-build/dev-automation/cpu/`) and `--compare=` for a before/after delta. Read-only. Take a baseline before a change and a second run after it: only the difference between two runs on the same machine is a result, because a dev build carries the Vite server and the source maps as well. | | `bun run check` | Run Biome, both typechecks, offline tests, the browser smoke test, and the production build. | | `bun run typecheck` | Check all 11 projects in parallel with a separate incremental cache for each project in this worktree. | | `bun run check:ui` | Check the renderer against the design system: shared primitives, Kobalte and Lucide confined to `components/ui`, palette tokens instead of colour, size, radius and transition literals. Reads the whole renderer in 60 ms. | diff --git a/package.json b/package.json index a306f4eea7..18f0f19f49 100644 --- a/package.json +++ b/package.json @@ -110,6 +110,7 @@ "mobile:doctor": "bun run --cwd apps/mobile doctor", "dev:seed": "tsx scripts/seed-dev-state.ts", "dev:automation": "bun scripts/dev-automation/cli.ts", + "dev:cpu": "bun scripts/dev-automation/cli.ts cpu", "dev:status": "bun scripts/dev-stack.ts status", "dev:verify": "bun scripts/dev-verify.ts", "dev:stop": "bun scripts/dev-stack.ts stop", diff --git a/scripts/dev-automation/cli.ts b/scripts/dev-automation/cli.ts index 01ac724bff..82cf114a44 100644 --- a/scripts/dev-automation/cli.ts +++ b/scripts/dev-automation/cli.ts @@ -1,7 +1,8 @@ // AI-facing bridge to the live dev app. Read-only by default; anything that // changes app state needs --allow-mutations. This tool never seeds, resets or // copies openbot.db: it drives the instance you already have open. -import { join, resolve } from "node:path"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; import { createOpenBotLogger, redactText } from "@openbot/logging"; import { assertMutationAllowed, @@ -12,6 +13,8 @@ import { readTargetId, resolveAutomationPort, } from "./cdp-client"; +import { compareProfiles, profileCpu } from "./cpu-profile"; +import { parseCpuReport } from "./cpu-sampling"; import { type DevInstanceRecord, type DevInstanceService, @@ -40,6 +43,14 @@ const logger = createOpenBotLogger("dev-automation", (line) => process.stderr.wr const DEFAULT_TIMEOUT_MS = 10_000; const SCREENSHOT_ROOT = join(process.cwd(), ".openbot-build", "dev-automation"); +const CPU_ROOT = join(SCREENSHOT_ROOT, "cpu"); +const DEFAULT_CPU_DURATION_MS = 60_000; +const MAX_CPU_DURATION_MS = 600_000; +const DEFAULT_CPU_INTERVAL_MS = 5_000; +// A sampler that runs every few hundred milliseconds becomes the load it is +// there to measure, and the counters it reads are cumulative, so nothing is +// lost by asking rarely. +const MIN_CPU_INTERVAL_MS = 1_000; // `null` means the flag is absent, `""` means it was passed empty. The two // differ for `--text=`, which legitimately clears a field. @@ -94,6 +105,16 @@ function readWaitTarget(): WaitTarget | null { return parseWaitTarget(raw); } +function readMilliseconds(name: string, fallback: number, minimum: number, maximum: number): number { + const raw = flagValue(name); + if (raw === null) return fallback; + const value = Number(raw); + if (!Number.isInteger(value) || value < minimum || value > maximum) { + throw new Error(`${name} must be an integer of ${minimum}..${maximum} ms.`); + } + return value; +} + function readService(): DevInstanceService { const raw = flagValue("--service"); if (raw === null || raw === "app") return "app"; @@ -104,6 +125,9 @@ function readService(): DevInstanceService { interface AutomationTarget { port: number; expectedRendererPort: number | null; + // The dev supervisor process the registry published, and the anchor for the + // `ps` walk in `cpu`. Null when no record owns this port. + pid: number | null; instanceNamed: boolean; description: string; } @@ -137,6 +161,7 @@ function resolveTarget(records: DevInstanceRecord[], service: DevInstanceService return { port: explicitPort.port, expectedRendererPort: published?.rendererPort ?? null, + pid: published?.pid ?? null, instanceNamed: true, description: published ? describeDevInstance(published) : `:${explicitPort.port}`, }; @@ -164,6 +189,7 @@ function resolveTarget(records: DevInstanceRecord[], service: DevInstanceService return { port: explicitPort.port, expectedRendererPort: null, + pid: null, instanceNamed: false, description: `:${explicitPort.port} (no registry record)`, }; @@ -171,6 +197,7 @@ function resolveTarget(records: DevInstanceRecord[], service: DevInstanceService return { port: selection.record.remoteDebuggingPort, expectedRendererPort: selection.record.rendererPort, + pid: selection.record.pid, // A foreign instance is the dev app of another worktree. Readable, so an // agent can still take a snapshot, but not something to click blind. instanceNamed: selection.match !== "foreign", @@ -178,6 +205,43 @@ function resolveTarget(records: DevInstanceRecord[], service: DevInstanceService }; } +function readComparisonReport(path: string) { + let parsed: unknown; + try { + parsed = JSON.parse(readFileSync(path, "utf8")); + } catch (error) { + throw new Error(`Could not read --compare=${path}: ${error instanceof Error ? error.message : String(error)}`); + } + const report = parseCpuReport(parsed); + if (!report) throw new Error(`--compare=${path} is not a cpu report this tool wrote.`); + return report; +} + +async function measureCpu(target: AutomationTarget): Promise { + const durationMs = readMilliseconds("--duration", DEFAULT_CPU_DURATION_MS, MIN_CPU_INTERVAL_MS, MAX_CPU_DURATION_MS); + const intervalMs = readMilliseconds("--interval", DEFAULT_CPU_INTERVAL_MS, MIN_CPU_INTERVAL_MS, durationMs); + const label = flagValue("--label") ?? "run"; + const comparePath = flagValue("--compare"); + const baseline = comparePath === null || comparePath === "" ? null : readComparisonReport(comparePath); + const browser = await openDevBrowser(target.port, logger); + let profile: Awaited>; + try { + logger.info(`sampling for ${durationMs} ms every ${intervalMs} ms`); + profile = await profileCpu({ browser, rootPid: target.pid, durationMs, intervalMs, label, logger }); + } finally { + await browser.close(); + } + const document = baseline ? { ...profile, delta: compareProfiles(baseline, profile) } : profile; + const out = flagValue("--out"); + if (out !== null && out !== "") { + const path = resolve(CPU_ROOT, out); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, `${JSON.stringify(document, null, 2)}\n`); + logger.info(`wrote ${redactText(path)}`); + } + process.stdout.write(`${JSON.stringify(document, null, 2)}\n`); +} + async function main(): Promise { const command = process.argv[2]; if (command === "instances") { @@ -199,10 +263,11 @@ async function main(): Promise { command !== "snapshot" && command !== "click" && command !== "type" && - command !== "screenshot" + command !== "screenshot" && + command !== "cpu" ) { throw new Error( - "Usage: bun scripts/dev-automation/cli.ts [flags]", + "Usage: bun scripts/dev-automation/cli.ts [flags]", ); } const target = resolveTarget(readDevInstanceRecords(), readService()); @@ -217,6 +282,13 @@ async function main(): Promise { } return; } + // Read-only: it attaches CDP counters and runs `ps`, and changes nothing in + // the app. So it stays out of the mutation gate below and works against an + // instance nobody named. + if (command === "cpu") { + await measureCpu(target); + return; + } if (command === "click" || command === "type") { assertMutationAllowed({ command, diff --git a/scripts/dev-automation/cpu-profile.ts b/scripts/dev-automation/cpu-profile.ts new file mode 100644 index 0000000000..41c97dd43d --- /dev/null +++ b/scripts/dev-automation/cpu-profile.ts @@ -0,0 +1,273 @@ +// Collects the samples `cpu-sampling.ts` does the arithmetic on. Everything +// impure lives here: the CDP calls and the one `ps` invocation. +// +// Two sources, on purpose. CDP knows which Chromium process is which without +// parsing a command line, and it is the only one that works when `ps` does not. +// `ps` is the cross-check: it is the operating system's own accounting, so when +// the two disagree the number in the report is not to be trusted. Neither is +// dropped, because a profiler nobody can falsify is a profiler nobody should +// believe. + +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import type { Logger } from "@openbot/logging"; +import type { Browser, CDPSession, Page } from "playwright-core"; +import { + type ChromiumProcessType, + type CpuReport, + type CpuSample, + collectDescendants, + type ProcessSnapshot, + parseProcessTable, + snapshotProcesses, + summarize, +} from "./cpu-sampling"; +import { describeTarget } from "./page-url"; + +const run = promisify(execFile); + +export interface PageMetrics { + target: string; + // Style recalculations and layouts per second of wall clock. Chromium reports + // no frame rate here - `Frames` is the document's iframe count, not a rate - + // so these two counters are the per-frame proxy. An animation that morphs a + // shape every frame drives both; a JS timer that touches no style drives + // neither. + recalcStyleCountPerSecond: number; + layoutCountPerSecond: number; + taskMsPerSecond: number; + scriptMsPerSecond: number; + recalcStyleMsPerSecond: number; + layoutMsPerSecond: number; +} + +export interface CpuProfile extends CpuReport { + intervalMs: number; + source: "cdp" | "ps"; + // The same run measured the other way, when both sources answered. A wide + // gap between the two totals means the report is not to be acted on. + crossCheck: CpuReport | null; + pages: PageMetrics[]; +} + +export interface CpuProfileOptions { + browser: Browser; + // From the instance registry. Null when no record published this port, which + // is the one case the `ps` cross-check cannot run: without a pid to anchor + // on, the only way to find the tree is by name, and a name matches another + // worktree's dev app too. + rootPid: number | null; + durationMs: number; + intervalMs: number; + label: string; + logger: Logger; +} + +// CDP names the browser process "browser"; in Electron that process is main. +// The other names are taken from what this Electron build actually reports, not +// from the protocol document: the GPU process answers "GPU" in capitals, and a +// utility process answers its Mojo service name rather than "utility". An +// unlisted name falls through to "other", which is why the `ps` cross-check is +// kept - it names the same process independently. +const CDP_PROCESS_TYPES = new Map([ + ["browser", "main"], + ["renderer", "renderer"], + ["GPU", "gpu"], + ["gpu", "gpu"], + ["network.mojom.NetworkService", "network"], + ["network", "network"], + ["utility", "utility"], + ["crashpad-handler", "crashpad"], +]); + +async function sampleOverCdp(session: CDPSession): Promise { + const { processInfo } = await session.send("SystemInfo.getProcessInfo"); + return processInfo.map((process) => ({ + pid: process.id, + type: CDP_PROCESS_TYPES.get(process.type) ?? "other", + cpuSeconds: process.cpuTime, + })); +} + +async function sampleOverPs(rootPid: number): Promise { + const { stdout } = await run("ps", ["-o", "pid=,ppid=,cputime=,command=", "-ax"], { maxBuffer: 16 * 1_024 * 1_024 }); + return snapshotProcesses(collectDescendants(parseProcessTable(stdout), rootPid)); +} + +const METRIC_NAMES = [ + "RecalcStyleCount", + "LayoutCount", + "TaskDuration", + "ScriptDuration", + "RecalcStyleDuration", + "LayoutDuration", +] as const; +// The two counts are plain event counts; the four durations are seconds. +const COUNT_METRICS: ReadonlySet = new Set(["RecalcStyleCount", "LayoutCount"]); +type MetricName = (typeof METRIC_NAMES)[number]; +type MetricReading = Partial>; + +async function readMetrics(session: CDPSession): Promise { + const { metrics } = await session.send("Performance.getMetrics"); + const reading: MetricReading = {}; + for (const metric of metrics) { + if (metric.name === "Timestamp") reading.Timestamp = metric.value; + for (const name of METRIC_NAMES) { + if (metric.name === name) reading[name] = metric.value; + } + } + return reading; +} + +// Chromium reports the durations in seconds, and the report is in milliseconds +// per second of wall clock - "how much of each second this page spent here". A +// missing counter reads as no work rather than as a gap, which is the right +// default: every one of them is absent only when it never ran. +function perSecond(before: MetricReading, after: MetricReading, name: MetricName, spanSeconds: number): number { + const delta = (after[name] ?? 0) - (before[name] ?? 0); + if (delta <= 0 || spanSeconds <= 0) return 0; + return round(COUNT_METRICS.has(name) ? delta / spanSeconds : (delta * 1_000) / spanSeconds); +} + +interface PageProbe { + target: string; + session: CDPSession; + before: MetricReading; +} + +async function openPageProbes(pages: Page[], logger: Logger): Promise { + const probes: PageProbe[] = []; + for (const page of pages) { + const target = describeTarget(page.url()); + try { + const session = await page.context().newCDPSession(page); + await session.send("Performance.enable"); + probes.push({ target, session, before: await readMetrics(session) }); + } catch { + // A page that closes or navigates while we attach is not one this run can + // report on, and it must not take the whole measurement down with it. + logger.warn(`could not attach a performance probe to ${target}`); + } + } + return probes; +} + +async function closePageProbes(probes: PageProbe[], wallMs: number): Promise { + const measured: PageMetrics[] = []; + for (const probe of probes) { + try { + const after = await readMetrics(probe.session); + const spanSeconds = + probe.before.Timestamp !== undefined && after.Timestamp !== undefined + ? after.Timestamp - probe.before.Timestamp + : wallMs / 1_000; + measured.push({ + target: probe.target, + recalcStyleCountPerSecond: perSecond(probe.before, after, "RecalcStyleCount", spanSeconds), + layoutCountPerSecond: perSecond(probe.before, after, "LayoutCount", spanSeconds), + taskMsPerSecond: perSecond(probe.before, after, "TaskDuration", spanSeconds), + scriptMsPerSecond: perSecond(probe.before, after, "ScriptDuration", spanSeconds), + recalcStyleMsPerSecond: perSecond(probe.before, after, "RecalcStyleDuration", spanSeconds), + layoutMsPerSecond: perSecond(probe.before, after, "LayoutDuration", spanSeconds), + }); + } catch { + // The page went away mid-run. The process-level numbers still stand. + } + await probe.session.send("Performance.disable").catch(() => undefined); + await probe.session.detach().catch(() => undefined); + } + return measured; +} + +function delay(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +export async function profileCpu(options: CpuProfileOptions): Promise { + const { browser, rootPid, durationMs, intervalMs, label, logger } = options; + const pages = browser.contexts().flatMap((context) => context.pages()); + const probes = await openPageProbes(pages, logger); + const browserSession = await browser.newBrowserCDPSession(); + const cdpSamples: CpuSample[] = []; + const psSamples: CpuSample[] = []; + let cdpFailed = false; + let psFailed = rootPid === null; + if (psFailed) logger.warn("no registry record published a pid, so the ps cross-check is skipped."); + const startedAt = Date.now(); + try { + // A sample before the first wait and one after the last, so the span the + // arithmetic divides by is the span that was actually observed. + for (;;) { + const atMs = Date.now(); + if (!cdpFailed) { + try { + cdpSamples.push({ atMs, processes: await sampleOverCdp(browserSession) }); + } catch (error) { + cdpFailed = true; + logger.warn(`SystemInfo.getProcessInfo is unavailable: ${describeError(error)}`); + } + } + if (!psFailed && rootPid !== null) { + try { + psSamples.push({ atMs, processes: await sampleOverPs(rootPid) }); + } catch (error) { + psFailed = true; + logger.warn(`ps is unavailable: ${describeError(error)}`); + } + } + const elapsed = Date.now() - startedAt; + if (elapsed >= durationMs) break; + await delay(Math.min(intervalMs, durationMs - elapsed)); + } + } finally { + await browserSession.detach().catch(() => undefined); + } + const wallMs = Date.now() - startedAt; + const pageMetrics = await closePageProbes(probes, wallMs); + if (cdpSamples.length < 2 && psSamples.length < 2) { + throw new Error("Neither CDP nor ps produced two samples, so there is no interval to measure."); + } + const useCdp = cdpSamples.length >= 2; + const primary = summarize(useCdp ? cdpSamples : psSamples, label); + const other = useCdp && psSamples.length >= 2 ? summarize(psSamples, label) : null; + return { + ...primary, + intervalMs, + source: useCdp ? "cdp" : "ps", + crossCheck: other, + pages: pageMetrics, + }; +} + +function describeError(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +function round(value: number): number { + return Math.round(value * 10) / 10; +} + +export interface CpuComparison { + before: string; + after: string; + totalCpuPercent: number; + processes: { type: ChromiumProcessType; cpuPercent: number }[]; +} + +/** The signed change from one report to another. Negative is an improvement. */ +export function compareProfiles(before: CpuReport, after: CpuReport): CpuComparison { + const baseline = new Map(before.processes.map((process) => [process.type, process.cpuPercent])); + const types = new Set([...baseline.keys(), ...after.processes.map((process) => process.type)]); + const processes = [...types].map((type) => ({ + type, + cpuPercent: round( + (after.processes.find((process) => process.type === type)?.cpuPercent ?? 0) - (baseline.get(type) ?? 0), + ), + })); + return { + before: before.label, + after: after.label, + totalCpuPercent: round(after.totalCpuPercent - before.totalCpuPercent), + processes, + }; +} diff --git a/scripts/dev-automation/cpu-sampling.test.ts b/scripts/dev-automation/cpu-sampling.test.ts new file mode 100644 index 0000000000..9904369552 --- /dev/null +++ b/scripts/dev-automation/cpu-sampling.test.ts @@ -0,0 +1,186 @@ +// A profiler that is wrong is worse than no profiler: every fix decision it +// gates would be made on a confident number that does not move. So what these +// cover is the arithmetic that is wrong by default - the `ps` time formats, the +// processes that come and go inside a run, and the rule that tells the Electron +// main process apart from the dev server that started it. +// +// Nothing here waits on a clock. Every input is a literal. +import { describe, expect, it } from "vitest"; +import { + classifyChromiumProcess, + collectDescendants, + cpuPercentBetween, + type ProcessSnapshot, + parseCpuReport, + parseProcessTable, + parseProcessTime, + snapshotProcesses, + summarize, +} from "./cpu-sampling"; + +function snapshot(pid: number, cpuSeconds: number, type: ProcessSnapshot["type"] = "renderer"): ProcessSnapshot { + return { pid, type, cpuSeconds }; +} + +describe("parseProcessTime", () => { + it("reads the minutes, hours and days formats ps prints", () => { + expect(parseProcessTime("0:00.00")).toBe(0); + expect(parseProcessTime("1:02.34")).toBeCloseTo(62.34, 5); + expect(parseProcessTime("123:45.60")).toBeCloseTo(7_425.6, 5); + expect(parseProcessTime("01:02:03.45")).toBeCloseTo(3_723.45, 5); + expect(parseProcessTime("2-03:04:05")).toBe(183_845); + }); + + it("answers null instead of NaN for a field that is not a time", () => { + expect(parseProcessTime("")).toBeNull(); + expect(parseProcessTime("CPU")).toBeNull(); + expect(parseProcessTime("12")).toBeNull(); + // Seconds and minutes above 59 mean the columns were misread. + expect(parseProcessTime("1:60.00")).toBeNull(); + expect(parseProcessTime("1:60:00")).toBeNull(); + // ps only prints a day field with a full HH:MM:SS. + expect(parseProcessTime("2-03:04")).toBeNull(); + }); +}); + +describe("classifyChromiumProcess", () => { + it("calls the Electron binary without a --type= switch the main process", () => { + const electron = + "/worktree/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron /worktree/out/main/index.js"; + expect(classifyChromiumProcess(electron)).toBe("main"); + }); + + it("does not mistake the dev server that started Electron for the main process", () => { + expect(classifyChromiumProcess("/opt/homebrew/bin/bun scripts/dev-services.ts app")).toBe("other"); + expect(classifyChromiumProcess("node /worktree/node_modules/.bin/electron-vite dev")).toBe("other"); + }); + + it("reads the child kind out of the --type= switch", () => { + expect(classifyChromiumProcess("/x/Electron Helper (Renderer) --type=renderer --lang=en")).toBe("renderer"); + expect(classifyChromiumProcess("/x/Electron Helper (GPU) --type=gpu-process")).toBe("gpu"); + expect(classifyChromiumProcess("/x/chrome_crashpad_handler --type=crashpad-handler")).toBe("crashpad"); + expect(classifyChromiumProcess("/x/Electron Helper --type=utility --utility-sub-type=node.mojom.NodeService")).toBe( + "utility", + ); + expect( + classifyChromiumProcess("/x/Electron Helper --type=utility --utility-sub-type=network.mojom.NetworkService"), + ).toBe("network"); + }); +}); + +describe("parseProcessTable and collectDescendants", () => { + const table = [ + " 100 1 0:10.00 /opt/homebrew/bin/bun scripts/dev-services.ts app", + " 101 100 1:00.00 /w/node_modules/electron/dist/Electron.app/Contents/MacOS/Electron /w/out/main/index.js", + " 102 101 0:30.00 /w/Electron Helper (Renderer) --type=renderer", + " 103 101 nonsense /w/Electron Helper (GPU) --type=gpu-process", + " 900 1 5:00.00 /Applications/Other.app/Contents/MacOS/Other", + "PID PPID TIME COMMAND", + ].join("\n"); + + it("drops a row whose time field cannot be read", () => { + const rows = parseProcessTable(table); + expect(rows.map((row) => row.pid)).toEqual([100, 101, 102, 900]); + }); + + it("walks only the tree under the published pid", () => { + const rows = collectDescendants(parseProcessTable(table), 100); + expect(rows.map((row) => row.pid)).toEqual([100, 101, 102]); + expect(snapshotProcesses(rows).map((process) => process.type)).toEqual(["other", "main", "renderer"]); + }); + + it("answers nothing when the published pid is gone", () => { + expect(collectDescendants(parseProcessTable(table), 4_242)).toEqual([]); + }); +}); + +describe("cpuPercentBetween", () => { + it("reports the delta over the interval as percent of one core", () => { + const usage = cpuPercentBetween([snapshot(1, 10)], [snapshot(1, 13)], 10_000); + expect(usage).toEqual([{ pid: 1, type: "renderer", cpuPercent: 30 }]); + }); + + it("drops a process that appeared or died inside the interval", () => { + // 40 cumulative seconds on a renderer that opened mid-run is a lifetime + // total, not work done during this interval. Counting it would read as a + // spike that never happened. + const usage = cpuPercentBetween([snapshot(1, 10)], [snapshot(1, 11), snapshot(2, 40)], 10_000); + expect(usage.map((process) => process.pid)).toEqual([1]); + const closed = cpuPercentBetween([snapshot(1, 10), snapshot(3, 5)], [snapshot(1, 11)], 10_000); + expect(closed.map((process) => process.pid)).toEqual([1]); + }); + + it("drops a pid whose counter went backwards, which means it was recycled", () => { + expect(cpuPercentBetween([snapshot(1, 10)], [snapshot(1, 2)], 10_000)).toEqual([]); + }); + + it("reports nothing rather than dividing by zero", () => { + expect(cpuPercentBetween([snapshot(1, 10)], [snapshot(1, 13)], 0)).toEqual([]); + }); +}); + +describe("summarize", () => { + it("groups the run by process kind over the full span", () => { + const report = summarize( + [ + { atMs: 0, processes: [snapshot(1, 0, "main"), snapshot(2, 0, "renderer")] }, + { atMs: 5_000, processes: [snapshot(1, 0.1, "main"), snapshot(2, 1.5, "renderer")] }, + { atMs: 10_000, processes: [snapshot(1, 0.2, "main"), snapshot(2, 3, "renderer")] }, + ], + "before", + ); + expect(report.label).toBe("before"); + expect(report.durationMs).toBe(10_000); + expect(report.samples).toBe(3); + expect(report.processes).toEqual([ + { type: "main", cpuPercent: 2, processes: 1 }, + { type: "renderer", cpuPercent: 30, processes: 1 }, + ]); + expect(report.totalCpuPercent).toBe(32); + }); + + it("keeps the work of a renderer that only lived for part of the run", () => { + const report = summarize( + [ + { atMs: 0, processes: [snapshot(1, 0, "main")] }, + { atMs: 5_000, processes: [snapshot(1, 0, "main"), snapshot(2, 10, "renderer")] }, + { atMs: 10_000, processes: [snapshot(1, 0, "main"), snapshot(2, 12.5, "renderer")] }, + ], + "after", + ); + // 2.5 s of renderer work over a 10 s span, not over the 5 s it was alive. + expect(report.processes).toContainEqual({ type: "renderer", cpuPercent: 25, processes: 1 }); + }); + + it("reports an empty run rather than dividing by zero", () => { + expect(summarize([], "empty")).toEqual({ + label: "empty", + durationMs: 0, + samples: 0, + processes: [], + totalCpuPercent: 0, + }); + expect(summarize([{ atMs: 5, processes: [] }], "one").durationMs).toBe(0); + }); +}); + +describe("parseCpuReport", () => { + const report = summarize( + [ + { atMs: 0, processes: [snapshot(1, 0, "main")] }, + { atMs: 10_000, processes: [snapshot(1, 1, "main")] }, + ], + "before", + ); + + it("reads back a report this tool wrote", () => { + expect(parseCpuReport(JSON.parse(JSON.stringify(report)))).toEqual(report); + }); + + it("refuses a file that is not one, instead of comparing against undefined", () => { + expect(parseCpuReport(null)).toBeNull(); + expect(parseCpuReport({ ...report, processes: "none" })).toBeNull(); + expect(parseCpuReport({ ...report, totalCpuPercent: "2" })).toBeNull(); + expect(parseCpuReport({ ...report, processes: [{ type: "cpu", cpuPercent: 1, processes: 1 }] })).toBeNull(); + }); +}); diff --git a/scripts/dev-automation/cpu-sampling.ts b/scripts/dev-automation/cpu-sampling.ts new file mode 100644 index 0000000000..3bd43f5ea8 --- /dev/null +++ b/scripts/dev-automation/cpu-sampling.ts @@ -0,0 +1,295 @@ +// The arithmetic behind `dev:automation cpu`. Pure on purpose: no process is +// spawned and no file is read here, so every rule below is testable in Node. +// +// Why this module exists at all, rather than a one-line `ps` pipe: `ps -o %cpu` +// reports total CPU time divided by process *lifetime*. An app that was busy +// for ten seconds at start-up and idle for an hour still reports a high `%cpu`, +// and it reports it stably, run after run. That is the worst possible failure +// for an A/B comparison - a confident wrong number that does not move when the +// code gets better. The only correct reading is a delta of the cumulative +// `cputime` counter across a known wall-clock interval, which is what +// `cpuPercentBetween` does. +// +// "Percent" here is percent of one core. 100 means one core fully used; a +// machine with eight cores can therefore report more than 100 in total. + +import { isDynamicRecord, isNumber, isOneOf, isString } from "@openbot/contracts/runtime-values"; + +export type ChromiumProcessType = "main" | "renderer" | "gpu" | "utility" | "network" | "crashpad" | "other"; + +// One process at one instant. `cpuSeconds` is cumulative since the process +// started, never a rate. +export interface ProcessSnapshot { + pid: number; + type: ChromiumProcessType; + cpuSeconds: number; +} + +export interface CpuSample { + atMs: number; + processes: ProcessSnapshot[]; +} + +export interface ProcessCpuUsage { + pid: number; + type: ChromiumProcessType; + cpuPercent: number; +} + +export interface ProcessTypeUsage { + type: ChromiumProcessType; + cpuPercent: number; + processes: number; +} + +export interface CpuReport { + label: string; + durationMs: number; + samples: number; + processes: ProcessTypeUsage[]; + totalCpuPercent: number; +} + +export interface ProcessTableRow { + pid: number; + ppid: number; + cpuSeconds: number; + command: string; +} + +// `ps -o cputime=` prints `MM:SS.ss`, `HH:MM:SS.ss` or `D-HH:MM:SS`. Minutes +// are unbounded in the two-field form, which is how macOS prints a process +// that has used more than an hour but less than a day. +const PROCESS_TIME_PATTERN = /^(?:(\d+)-)?(\d+):(\d{1,2})(?::(\d{1,2}))?(?:\.(\d+))?$/; + +const SECONDS_PER_MINUTE = 60; +const SECONDS_PER_HOUR = 3_600; +const SECONDS_PER_DAY = 86_400; + +/** + * Cumulative CPU seconds from a `ps -o cputime=` field, or `null` when the + * field is not a time. `null` rather than `NaN` so a single unreadable row + * cannot poison a sum: the caller drops the row instead of reporting a number + * that is silently not a number. + */ +export function parseProcessTime(raw: string): number | null { + const match = PROCESS_TIME_PATTERN.exec(raw.trim()); + if (!match) return null; + const [, days, first, second, third, fraction] = match; + // The day field only ever appears with a full `HH:MM:SS`, so `2-03:04` is + // not a format `ps` produces and is more likely a misread column. + if (days !== undefined && third === undefined) return null; + const hours = third === undefined ? 0 : Number(first); + const minutes = third === undefined ? Number(first) : Number(second); + const seconds = third === undefined ? Number(second) : Number(third); + if (seconds >= SECONDS_PER_MINUTE) return null; + if (third !== undefined && minutes >= SECONDS_PER_MINUTE) return null; + const whole = Number(days ?? 0) * SECONDS_PER_DAY + hours * SECONDS_PER_HOUR + minutes * SECONDS_PER_MINUTE + seconds; + return whole + (fraction === undefined ? 0 : Number(`0.${fraction}`)); +} + +const CHROMIUM_TYPE_SWITCH = /--type=(\S+)/; +const UTILITY_SUB_TYPE_SWITCH = /--utility-sub-type=(\S+)/; +// A macOS bundle executable, which is what both the dev Electron binary and a +// packaged OpenBot are launched as. +const BUNDLE_EXECUTABLE = /\.app\/contents\/macos\//; + +/** + * Which part of the browser a command line belongs to. + * + * A Chromium child announces itself with `--type=`; the browser process - what + * Electron calls main - is the one without it. That rule alone is not enough + * here, because the sampled tree is rooted at the dev supervisor and also holds + * the Vite server and Bun, which carry no `--type=` either. So a process only + * counts as `main` when it is an Electron executable as well; everything else + * unrecognized is `other`, which keeps dev-server cost visible without + * mislabelling it as the app. + */ +export function classifyChromiumProcess(command: string): ChromiumProcessType { + const type = CHROMIUM_TYPE_SWITCH.exec(command)?.[1]; + if (type === undefined) return isElectronExecutable(command) ? "main" : "other"; + if (type === "renderer") return "renderer"; + if (type === "gpu-process") return "gpu"; + if (type === "crashpad-handler") return "crashpad"; + if (type === "utility") { + const subType = UTILITY_SUB_TYPE_SWITCH.exec(command)?.[1] ?? ""; + return subType.includes("NetworkService") ? "network" : "utility"; + } + return "other"; +} + +function isElectronExecutable(command: string): boolean { + const executable = command.trim().split(/\s+/)[0]?.toLowerCase() ?? ""; + if (BUNDLE_EXECUTABLE.test(executable)) return true; + return executable.endsWith("/electron") || executable === "electron"; +} + +const PROCESS_TABLE_ROW = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/; + +/** + * Rows from `ps -o pid=,ppid=,cputime=,command= -ax`. A row whose time field + * does not parse is dropped rather than guessed at. + */ +export function parseProcessTable(stdout: string): ProcessTableRow[] { + const rows: ProcessTableRow[] = []; + for (const line of stdout.split("\n")) { + const match = PROCESS_TABLE_ROW.exec(line); + if (!match) continue; + const cpuSeconds = parseProcessTime(match[3] ?? ""); + if (cpuSeconds === null) continue; + rows.push({ + pid: Number(match[1]), + ppid: Number(match[2]), + cpuSeconds, + command: match[4] ?? "", + }); + } + return rows; +} + +/** + * The root and everything under it. The walk is anchored on a pid the instance + * registry published, never on a name: matching "electron" would pick up + * another worktree's dev app, and attribute its cost to this measurement. + */ +export function collectDescendants(rows: ProcessTableRow[], rootPid: number): ProcessTableRow[] { + const byParent = new Map(); + for (const row of rows) { + const siblings = byParent.get(row.ppid); + if (siblings) siblings.push(row); + else byParent.set(row.ppid, [row]); + } + const collected: ProcessTableRow[] = []; + const seen = new Set(); + const queue = rows.filter((row) => row.pid === rootPid); + while (queue.length > 0) { + const row = queue.shift(); + if (!row || seen.has(row.pid)) continue; + seen.add(row.pid); + collected.push(row); + queue.push(...(byParent.get(row.pid) ?? [])); + } + return collected; +} + +export function snapshotProcesses(rows: ProcessTableRow[]): ProcessSnapshot[] { + return rows.map((row) => ({ pid: row.pid, type: classifyChromiumProcess(row.command), cpuSeconds: row.cpuSeconds })); +} + +interface ProcessCpuSeconds { + pid: number; + type: ChromiumProcessType; + cpuSeconds: number; +} + +// A pid in only one of the two snapshots is dropped, not counted from zero: a +// renderer that started mid-interval would otherwise report its whole lifetime +// of CPU as if it had all happened inside the interval, and a window opened +// during a run would read as a spike that is not there. A negative delta means +// the pid was recycled onto a different process, which is the same problem. +function cpuSecondsBetween(before: ProcessSnapshot[], after: ProcessSnapshot[]): ProcessCpuSeconds[] { + const start = new Map(before.map((process) => [process.pid, process])); + const used: ProcessCpuSeconds[] = []; + for (const process of after) { + const previous = start.get(process.pid); + if (!previous) continue; + const delta = process.cpuSeconds - previous.cpuSeconds; + if (delta < 0) continue; + used.push({ pid: process.pid, type: process.type, cpuSeconds: delta }); + } + return used; +} + +/** Percent of one core, per process, over `wallMs` of wall-clock time. */ +export function cpuPercentBetween( + before: ProcessSnapshot[], + after: ProcessSnapshot[], + wallMs: number, +): ProcessCpuUsage[] { + if (wallMs <= 0) return []; + return cpuSecondsBetween(before, after).map((process) => ({ + pid: process.pid, + type: process.type, + cpuPercent: (process.cpuSeconds / (wallMs / 1_000)) * 100, + })); +} + +const REPORTED_TYPES: readonly ChromiumProcessType[] = [ + "main", + "renderer", + "gpu", + "network", + "utility", + "crashpad", + "other", +]; + +/** + * One report from the whole run. + * + * CPU is accumulated over each consecutive pair of samples rather than from the + * first sample to the last, so a renderer that opened and closed inside the run + * still contributes the work it did. The divisor stays the full span, which is + * what makes two runs of different length comparable. + */ +export function summarize(samples: CpuSample[], label: string): CpuReport { + const first = samples[0]; + const last = samples[samples.length - 1]; + const durationMs = first && last ? last.atMs - first.atMs : 0; + if (!first || !last || durationMs <= 0) { + return { label, durationMs: 0, samples: samples.length, processes: [], totalCpuPercent: 0 }; + } + const secondsByType = new Map(); + const pidsByType = new Map>(); + for (let index = 1; index < samples.length; index += 1) { + const previous = samples[index - 1]; + const current = samples[index]; + if (!previous || !current) continue; + for (const process of cpuSecondsBetween(previous.processes, current.processes)) { + secondsByType.set(process.type, (secondsByType.get(process.type) ?? 0) + process.cpuSeconds); + const pids = pidsByType.get(process.type) ?? new Set(); + pids.add(process.pid); + pidsByType.set(process.type, pids); + } + } + const processes = REPORTED_TYPES.filter((type) => pidsByType.has(type)).map((type) => ({ + type, + cpuPercent: round(((secondsByType.get(type) ?? 0) / (durationMs / 1_000)) * 100), + processes: pidsByType.get(type)?.size ?? 0, + })); + return { + label, + durationMs, + samples: samples.length, + processes, + totalCpuPercent: round(processes.reduce((total, process) => total + process.cpuPercent, 0)), + }; +} + +function round(value: number): number { + return Math.round(value * 10) / 10; +} + +const PROCESS_TYPES: readonly ChromiumProcessType[] = REPORTED_TYPES; + +/** + * A report read back from `--out`, or `null` when the file is not one. + * + * `--compare` points at a file a developer chose, so it can be stale, truncated + * or from another tool. Answering `null` lets the caller say which file is + * wrong, instead of printing a delta against undefined. + */ +export function parseCpuReport(value: unknown): CpuReport | null { + if (!isDynamicRecord(value)) return null; + const { label, durationMs, samples, processes, totalCpuPercent } = value; + if (!isString(label) || !isNumber(durationMs) || !isNumber(samples) || !isNumber(totalCpuPercent)) return null; + if (!Array.isArray(processes)) return null; + const parsed: ProcessTypeUsage[] = []; + for (const process of processes) { + if (!isDynamicRecord(process)) return null; + if (!isOneOf(PROCESS_TYPES, process.type)) return null; + if (!isNumber(process.cpuPercent) || !isNumber(process.processes)) return null; + parsed.push({ type: process.type, cpuPercent: process.cpuPercent, processes: process.processes }); + } + return { label, durationMs, samples, processes: parsed, totalCpuPercent }; +} diff --git a/src/main/browser-picture-in-picture.ts b/src/main/browser-picture-in-picture.ts index 7428dc946a..8fed10c451 100644 --- a/src/main/browser-picture-in-picture.ts +++ b/src/main/browser-picture-in-picture.ts @@ -17,6 +17,8 @@ interface BrowserPictureInPictureOptions { onEvent: (event: BrowserPictureInPictureEvent) => void; } +const HOVER_POLL_INTERVAL_MS = 150; + export class BrowserPictureInPicture { readonly #options: BrowserPictureInPictureOptions; #window: BrowserWindow | null = null; @@ -198,7 +200,15 @@ export class BrowserPictureInPicture { .catch(() => undefined); }; update(); - this.#hoverTimer = setInterval(update, 75); + // The cursor is polled because a window that is not focused gets no mouse + // events, and hover on an unfocused always-on-top window is the whole + // feature. 75 ms was 13 reads of the cursor and the window bounds every + // second, for the life of the window; a control strip that appears within + // 150 ms reads the same to a user and costs half as much. `unref` keeps the + // timer from holding the event loop awake between those reads. + const timer = setInterval(update, HOVER_POLL_INTERVAL_MS); + timer.unref(); + this.#hoverTimer = timer; } #stopHoverTracking(): void { diff --git a/src/renderer/src/features/account/AccountLogin.tsx b/src/renderer/src/features/account/AccountLogin.tsx index 431e3fad05..391d56f4f0 100644 --- a/src/renderer/src/features/account/AccountLogin.tsx +++ b/src/renderer/src/features/account/AccountLogin.tsx @@ -50,12 +50,32 @@ export function AccountLogin(props: AccountLoginProps) { let emailRevertTimer: number | undefined; let emailMessageTimer: number | undefined; - const clock = window.setInterval(() => setNow(Date.now()), 1_000); - onCleanup(() => { - window.clearInterval(clock); - clearEmailErrorTimers(); + onCleanup(clearEmailErrorTimers); + + // `now()` exists for the two countdowns below and nothing else, so the clock + // runs only while one of them is on screen. Arming it at creation instead + // woke the view once a second for its whole life, including the ordinary case + // where there is nothing to count down. + const countdownUntil = createMemo(() => { + const resendAt = props.state.status === "code_sent" ? props.state.resendAvailableAt : 0; + return Math.max(resendAt, issueBlockedUntil()); }); + createEffect( + () => countdownUntil(), + (until) => { + setNow(Date.now()); + if (until <= Date.now()) return; + const clock = window.setInterval(() => { + setNow(Date.now()); + // Stop at the deadline rather than wait for the next state change: the + // label has reached zero and no later tick can change it. + if (Date.now() >= until) window.clearInterval(clock); + }, 1_000); + return () => window.clearInterval(clock); + }, + ); + const codeSent = () => props.state.status === "code_sent"; const verified = () => props.state.status === "signed_in"; const loginStep = (): LoginStep => (codeSent() || verified() ? "code" : "email"); diff --git a/src/renderer/src/features/agents/AgentAvatar.test.tsx b/src/renderer/src/features/agents/AgentAvatar.test.tsx index 16f15f1ba2..a83900f580 100644 --- a/src/renderer/src/features/agents/AgentAvatar.test.tsx +++ b/src/renderer/src/features/agents/AgentAvatar.test.tsx @@ -64,7 +64,7 @@ describe("AgentAvatar playback", () => { {(seed) => ( )} @@ -110,8 +110,8 @@ describe("AgentAvatar playback", () => { }); it.each([ - ["idle", "working", "orbit"], - ["working", "idle", "idle"], + ["connecting", "working", "orbit"], + ["working", "connecting", "orbit"], ] as const)("changes from %s to %s without restarting playback", (from, to, expectedState) => { motionPreference(false); const clock = playback(); @@ -220,6 +220,54 @@ describe("AgentAvatar playback", () => { expect(clock.callbacks.size).toBe(0); }); + it("rests an idle avatar until it is interacted with, and keeps a working one playing", async () => { + motionPreference(false); + const clock = playback(); + render(() => ( + + )); + const target = screen.getByRole("button", { name: "Agent" }); + // Every sidebar row shows `idle` while its agent does nothing, and the + // sidebar is not virtualized, so a playing `idle` avatar is a cost that + // grows with the agent count and never stops. + expect(clock.callbacks.size).toBe(0); + await fireEvent.pointerEnter(target); + expect(clock.callbacks.size).toBe(1); + await fireEvent.pointerLeave(target); + expect(clock.callbacks.size).toBe(0); + }); + + it("keeps playing the motions that report an agent is busy", () => { + motionPreference(false); + const clock = playback(); + // Motion is the only signal the sidebar gives that an agent runs, so these + // two must not follow `idle` into the resting set. + render(() => ); + flush(); + expect(clock.callbacks.size).toBe(1); + clock.callbacks.clear(); + render(() => ); + flush(); + expect(clock.callbacks.size).toBe(1); + }); + + it("stops playback when a busy agent goes back to idle", () => { + motionPreference(false); + const clock = playback(); + const [state, setState] = createStore<{ motion: AvatarMotion }>({ motion: "working" }); + render(() => ); + flush(); + expect(clock.callbacks.size).toBe(1); + setState((draft) => { + draft.motion = "idle"; + }); + flush(); + expect(clock.callbacks.size).toBe(0); + }); + it("initializes the library drawing clock and cycle position together", () => { const clock = playback(); const idle = makeBlock("idle"); diff --git a/src/renderer/src/features/agents/AgentAvatar.tsx b/src/renderer/src/features/agents/AgentAvatar.tsx index 49edbdf84e..fb24224847 100644 --- a/src/renderer/src/features/agents/AgentAvatar.tsx +++ b/src/renderer/src/features/agents/AgentAvatar.tsx @@ -17,6 +17,15 @@ const IDLE_CYCLE: Block[] = [slowerBlock("idle")]; const WORKING_CYCLE: Block[] = [slowerBlock("orbit")]; const CONNECTING_CYCLE: Block[] = [makeBlock("orbit"), makeBlock("swirl")]; +// The motions that rest until the pointer or focus arrives. `idle` is here +// because it is what a sidebar row shows while its agent does nothing, and the +// sidebar is not virtualized, so every row animates for as long as the list is +// on screen. A profile of an idle window found four `idle` avatars driving 83 +// style recalculations a second, and that did not fall when the window lost +// focus or was minimized. `working` and `connecting` keep animating: motion is +// the only sidebar signal that an agent runs. +const STATIC_MOTIONS: ReadonlySet = new Set(["hover", "idle"]); + function slowerBlock(state: StateId): Block { const block = makeBlock(state); return { ...block, duration: block.duration * SIDEBAR_MOTION_HOLD_FACTOR }; @@ -91,7 +100,7 @@ function GeneratedAvatar(props: { const profile = createMemo(() => bloubAvatarProfile(props.seed, props.hue)); const cycle = createMemo(() => offsetCycle(DEFAULT_CYCLE, props.cycleOffset ?? 0)); const animated = () => - !reducedMotion() && (Boolean(props.animationState) || props.motion !== "hover" || interacting()); + !reducedMotion() && (Boolean(props.animationState) || !STATIC_MOTIONS.has(props.motion) || interacting()); const motionCycle = () => { if (props.animationState) return [slowerBlock(props.animationState)]; if (props.motion === "connecting") return CONNECTING_CYCLE; diff --git a/src/renderer/src/features/conversation/conversation.css b/src/renderer/src/features/conversation/conversation.css index 78bf3439aa..16d5481d96 100644 --- a/src/renderer/src/features/conversation/conversation.css +++ b/src/renderer/src/features/conversation/conversation.css @@ -3921,6 +3921,18 @@ button.chat-action-target:active, opacity: 0; } +/* The canvas above rests at `opacity: 0` once the image arrives, but the glow + * inside it keeps two infinite keyframes on `mask-size` and `mask-position`, + * and the compositor can take neither. One finished image in the history + * therefore costs a style recalculation and a repaint every frame for as long + * as the conversation is open. A profile of an idle window measured 60 style + * recalculations a second with no script running at all. The reduced-motion + * block at the end of this file already stops these keyframes for the same + * element, so this only makes the finished state agree with it. */ +.image-generation-ready .image-generation-glow { + animation: none; +} + .image-generation-dots { position: absolute; inset: 2px;