Repository navigation
chore(perf): add renderer agent-status benchmark harness - #13905
Conversation
Splits run-idle-cpu-benchmark.mjs into a scale fixture, an in-page timing probe, and process sampling, and records a measured origin/main baseline so the agent-status batching slice has an auditable before. The agent-status write workload is not included: it needs setAgentStatuses, so it lands with the store slice.
📝 WalkthroughWalkthroughThe PR adds cross-platform process-tree sampling with workload-aware timing, process classification, statistics, inventory reporting, and termination. It adds renderer scaling fixtures, census collection, timer and long-task probes, and Zustand publication workloads. The benchmark CLI gains scaling controls, readiness checks, concurrent workload execution, imported sampling, and expanded reports. A renderer agent-status performance specification documents the measured design and acceptance criteria. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
config/scripts/run-idle-cpu-benchmark.mjs (1)
436-454: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick winThe report embeds data that the new specification forbids in a shareable artifact.
docs/reference/renderer-agent-status-performance.mdstates that raw process inventories, temporary paths, pane identifiers, and DOM text are diagnostic-only and must not be embedded in the shareable report. The report assembled here contains all of them:
processInventorycarriescommandSamples, which are full command lines that include the developer home path and username.samples[].processes[].commandcarries the same command lines for every sample.options,fixtureState, andscaleFixtureStatecarry temporary repository paths, worktree IDs, and pane-derived tab IDs.rendererCensus*carriesmountedIdsand the typing-diagnostic census.The console block at Lines 460-476 also prints
processInventory. Split the artifact into a redacted shareable report and an opt-in diagnostic report, or redact command lines and paths before writing.
🧹 Nitpick comments (6)
config/scripts/idle-cpu-process-sampling.mjs (3)
84-109: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueIndex rows by pid to avoid the repeated linear scan.
descendantsOfcallsrows.findfor every visited pid. The process list already exists in memory, and the sampler calls this function on every interval. A pid map removes the quadratic scan.♻️ Proposed refactor
export function descendantsOf(rows, rootPid) { const children = new Map() + const rowByPid = new Map() for (const row of rows) { const list = children.get(row.ppid) ?? [] list.push(row) children.set(row.ppid, list) + rowByPid.set(row.pid, row) } const result = [] const stack = [rootPid] const seen = new Set() while (stack.length > 0) { const pid = stack.pop() if (seen.has(pid)) { continue } seen.add(pid) - const row = rows.find((candidate) => candidate.pid === pid) + const row = rowByPid.get(pid)
58-78: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winWindows sampling reports 0% CPU for every process.
readWindowsProcessessetspercentCpu: 0andcpuTimeSeconds: null. The sampler then falls back torow.percentCpu, so every Windows sample records 0% CPU and the report looks like a valid measurement.docs/reference/renderer-agent-status-performance.mdalready states that Windows CPU collection cannot support this comparison. Make that explicit in the data, for example by adding acpuSupported: falsemarker that the report surfaces, or by readingWin32_ProcessUserModeTime/KernelModeTimeso a CPU-time delta is available.
317-323: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueTerminating by recorded pid can signal a recycled pid.
terminateProcessesreceives the descendant list thatrun-idle-cpu-benchmark.mjscaptures beforeapp.close()and a 250 ms wait. The OS can reuse a pid in that interval. The blast radius is small for a local benchmark, but a pid-existence recheck before the signal removes the risk.config/scripts/idle-cpu-process-sampling.test.mjs (1)
30-65: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for the pure parsing and classification functions.
The suite covers only the sampling window.
parseCpuTimeSeconds,parseUnixProcesses,descendantsOf,classify, andsummarizeSamplesare pure and deterministic, and they carry the platform-specificpsformat assumptions. A rejectedworkloadPromisepath is also untested; the sampler is expected to rethrow that error. These tests are cheap and protect the measurement correctness.config/scripts/idle-cpu-renderer-scale-fixture.mjs (1)
163-167: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueSelect agent rows with a CSS selector instead of scanning every element.
querySelectorAll('*')materializes the whole sidebar subtree, then filters by class. A direct selector is equivalent and avoids the full scan.♻️ Proposed refactor
- const mountedAgentRows = [...(sidebar?.querySelectorAll('*') ?? [])].filter( - (element) => - element.classList.contains('group/agent-row') || - element.classList.contains('compact-agent-row') - ).length + const mountedAgentRows = + sidebar?.querySelectorAll('.group\\/agent-row, .compact-agent-row').length ?? 0config/scripts/idle-cpu-renderer-timing-probe.mjs (1)
102-113: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMake probe installation and stop idempotent.
startRendererTimingProbeoverwriteswindow.__orcaIdleCpuTimingProbewithout stopping a previously installed probe, so a second call leaves an orphan 100 ms timer that adds CPU work to the measurement.stopalso leaves the object in place, so a repeatedstopcall returns a second snapshot from a stopped timer. Clear the previous probe on install and delete the global on stop.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 22f7a30f-889a-453f-b0e7-9e6f6a65ef91
📒 Files selected for processing (7)
.gitignoreconfig/scripts/idle-cpu-process-sampling.mjsconfig/scripts/idle-cpu-process-sampling.test.mjsconfig/scripts/idle-cpu-renderer-scale-fixture.mjsconfig/scripts/idle-cpu-renderer-timing-probe.mjsconfig/scripts/run-idle-cpu-benchmark.mjsdocs/reference/renderer-agent-status-performance.md
| const fixtureState = await page.evaluate(async (repoPath) => { | ||
| const added = await window.api.repos.add({ path: repoPath }) | ||
| if ('error' in added) { | ||
| return { error: added.error } | ||
| } | ||
| const store = window.__store | ||
| await store?.getState().fetchRepos() | ||
| const repo = store?.getState().repos.find((candidate) => candidate.path === repoPath) | ||
| const repo = store?.getState().repos.find((candidate) => candidate.id === added.repo.id) | ||
| if (repo) { | ||
| await store.getState().updateRepo(repo.id, { externalWorktreeVisibility: 'show' }) | ||
| await store.getState().fetchWorktrees(repo.id) | ||
| const detected = await store | ||
| .getState() | ||
| .fetchWorktrees(repo.id, { requireAuthoritative: true }) | ||
| const importedWorktreePaths = ( | ||
| store.getState().detectedWorktreesByRepo[repo.id]?.worktrees ?? [] | ||
| ) | ||
| .filter((worktree) => !worktree.selectedCheckout) | ||
| .map((worktree) => worktree.path) | ||
| const updated = await store.getState().updateRepo(repo.id, { | ||
| externalWorktreeVisibility: 'show', | ||
| importedExternalWorktreePaths: importedWorktreePaths, | ||
| externalWorktreeInboxBaselinePaths: importedWorktreePaths | ||
| }) | ||
| const refreshed = await store | ||
| .getState() | ||
| .fetchWorktrees(repo.id, { requireAuthoritative: true }) | ||
| return { | ||
| detected, | ||
| updated, | ||
| refreshed, | ||
| detectedCount: store.getState().detectedWorktreesByRepo[repo.id]?.worktrees.length ?? 0, | ||
| importedCount: importedWorktreePaths.length, | ||
| visibleCount: store.getState().worktreesByRepo[repo.id]?.length ?? 0 | ||
| } | ||
| } | ||
| return { error: 'repo-not-found' } | ||
| }, repoDir) | ||
| console.log(`[idle-cpu] fixture ${JSON.stringify(fixtureState)}`) | ||
| await page.waitForFunction( | ||
| () => window.__store?.getState().workspaceSessionReady === true, | ||
| (expectedWorktrees) => { | ||
| const state = window.__store?.getState() | ||
| return ( | ||
| state?.workspaceSessionReady === true && | ||
| Object.values(state.worktreesByRepo).flat().length === expectedWorktrees | ||
| ) | ||
| }, | ||
| options.worktrees, | ||
| { timeout: 180_000 } | ||
| ) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Fail fast when repository setup returns an error.
fixtureState can be { error: ... } from Line 348 or { error: 'repo-not-found' } from Line 379. The script only logs it at Line 381 and then enters the 180-second waitForFunction at Line 382, which can never satisfy the worktree count. The run then fails with a timeout that hides the real cause. Throw as soon as fixtureState.error is set.
🐛 Proposed fix
console.log(`[idle-cpu] fixture ${JSON.stringify(fixtureState)}`)
+ if (fixtureState.error) {
+ throw new Error(`Repository fixture setup failed: ${JSON.stringify(fixtureState.error)}`)
+ }
await page.waitForFunction(📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const fixtureState = await page.evaluate(async (repoPath) => { | |
| const added = await window.api.repos.add({ path: repoPath }) | |
| if ('error' in added) { | |
| return { error: added.error } | |
| } | |
| const store = window.__store | |
| await store?.getState().fetchRepos() | |
| const repo = store?.getState().repos.find((candidate) => candidate.path === repoPath) | |
| const repo = store?.getState().repos.find((candidate) => candidate.id === added.repo.id) | |
| if (repo) { | |
| await store.getState().updateRepo(repo.id, { externalWorktreeVisibility: 'show' }) | |
| await store.getState().fetchWorktrees(repo.id) | |
| const detected = await store | |
| .getState() | |
| .fetchWorktrees(repo.id, { requireAuthoritative: true }) | |
| const importedWorktreePaths = ( | |
| store.getState().detectedWorktreesByRepo[repo.id]?.worktrees ?? [] | |
| ) | |
| .filter((worktree) => !worktree.selectedCheckout) | |
| .map((worktree) => worktree.path) | |
| const updated = await store.getState().updateRepo(repo.id, { | |
| externalWorktreeVisibility: 'show', | |
| importedExternalWorktreePaths: importedWorktreePaths, | |
| externalWorktreeInboxBaselinePaths: importedWorktreePaths | |
| }) | |
| const refreshed = await store | |
| .getState() | |
| .fetchWorktrees(repo.id, { requireAuthoritative: true }) | |
| return { | |
| detected, | |
| updated, | |
| refreshed, | |
| detectedCount: store.getState().detectedWorktreesByRepo[repo.id]?.worktrees.length ?? 0, | |
| importedCount: importedWorktreePaths.length, | |
| visibleCount: store.getState().worktreesByRepo[repo.id]?.length ?? 0 | |
| } | |
| } | |
| return { error: 'repo-not-found' } | |
| }, repoDir) | |
| console.log(`[idle-cpu] fixture ${JSON.stringify(fixtureState)}`) | |
| await page.waitForFunction( | |
| () => window.__store?.getState().workspaceSessionReady === true, | |
| (expectedWorktrees) => { | |
| const state = window.__store?.getState() | |
| return ( | |
| state?.workspaceSessionReady === true && | |
| Object.values(state.worktreesByRepo).flat().length === expectedWorktrees | |
| ) | |
| }, | |
| options.worktrees, | |
| { timeout: 180_000 } | |
| ) | |
| const fixtureState = await page.evaluate(async (repoPath) => { | |
| const added = await window.api.repos.add({ path: repoPath }) | |
| if ('error' in added) { | |
| return { error: added.error } | |
| } | |
| const store = window.__store | |
| await store?.getState().fetchRepos() | |
| const repo = store?.getState().repos.find((candidate) => candidate.id === added.repo.id) | |
| if (repo) { | |
| const detected = await store | |
| .getState() | |
| .fetchWorktrees(repo.id, { requireAuthoritative: true }) | |
| const importedWorktreePaths = ( | |
| store.getState().detectedWorktreesByRepo[repo.id]?.worktrees ?? [] | |
| ) | |
| .filter((worktree) => !worktree.selectedCheckout) | |
| .map((worktree) => worktree.path) | |
| const updated = await store.getState().updateRepo(repo.id, { | |
| externalWorktreeVisibility: 'show', | |
| importedExternalWorktreePaths: importedWorktreePaths, | |
| externalWorktreeInboxBaselinePaths: importedWorktreePaths | |
| }) | |
| const refreshed = await store | |
| .getState() | |
| .fetchWorktrees(repo.id, { requireAuthoritative: true }) | |
| return { | |
| detected, | |
| updated, | |
| refreshed, | |
| detectedCount: store.getState().detectedWorktreesByRepo[repo.id]?.worktrees.length ?? 0, | |
| importedCount: importedWorktreePaths.length, | |
| visibleCount: store.getState().worktreesByRepo[repo.id]?.length ?? 0 | |
| } | |
| } | |
| return { error: 'repo-not-found' } | |
| }, repoDir) | |
| console.log(`[idle-cpu] fixture ${JSON.stringify(fixtureState)}`) | |
| if (fixtureState.error) { | |
| throw new Error(`Repository fixture setup failed: ${JSON.stringify(fixtureState.error)}`) | |
| } | |
| await page.waitForFunction( | |
| (expectedWorktrees) => { | |
| const state = window.__store?.getState() | |
| return ( | |
| state?.workspaceSessionReady === true && | |
| Object.values(state.worktreesByRepo).flat().length === expectedWorktrees | |
| ) | |
| }, | |
| options.worktrees, | |
| { timeout: 180_000 } | |
| ) |
| The benchmark launches an E2E-mode Electron build with the store exposed only | ||
| for instrumentation. It creates 100 worktrees in one expanded lineage, verifies | ||
| 100 mounted cards, captures the store listener census, and then applies seeded | ||
| ordered agent-status traffic through the real store action. | ||
|
|
||
| The benchmark measures the synchronous store action, not the live IPC leading | ||
| edge or post-commit notification path. A real-store snapshot test covers the | ||
| end-to-end budget for 100 panes with auto-generated titles enabled: one status, | ||
| one bulk generated-title, and one bulk resolved-title publication. Disabling | ||
| generated titles removes that middle publication, independent of pane count. |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
The "Benchmark contract" section contradicts the "Harness" section.
Lines 168-170 state that the benchmark applies seeded ordered agent-status traffic through the real store action, and Lines 172-176 describe measuring that store action. Lines 219-221 state that the agent-status write workload is not in the harness yet. Mark the write-workload parts of this section as planned, in the same way the Status section does.
| The sampling window extends past `--sample-ms` until the workload settles, and | ||
| fails the run rather than reporting a truncated window if the workload overruns | ||
| the guard. That is why a 2,000-publication run reports a measured window longer | ||
| than the requested one. |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
The stated reason for a longer measured window does not match the documented baseline.
The sampler extends the window only when the workload settles after --sample-ms. The baseline in this document uses --sample-ms 30000 and reports a median completion of 12,325.7 ms, so the window is not extended in that run. Correct the sentence, or state the configuration in which the extension actually applies.
) Splits run-idle-cpu-benchmark.mjs into a scale fixture, an in-page timing probe, and process sampling, and records a measured origin/main baseline so the agent-status batching slice has an auditable before. The agent-status write workload is not included: it needs setAgentStatuses, so it lands with the store slice.
Summary
Splits
run-idle-cpu-benchmark.mjsinto three composable pieces — a renderer scale fixture, an in-page timing probe, and process sampling — and records a measuredorigin/mainbaseline so the agent-status batching slice has an auditable before that someone other than its author can reproduce.Touches nothing under
src/. Worst case is a broken dev script.The baseline
macOS arm64, 100 worktrees at lineage depth 99, 100 agent rows, 10s warmup / 30s sample, 3 reps, median, measured on
origin/main:~11.6 points of mean renderer CPU are attributable to publication fanout alone, with 200 spinner animations running in both arms.
One thing worth knowing before you audit the batching PR
The long-task observer recorded zero entries in all four runs. Individual publications are each well under 50 ms, so at this scale the cost surfaces as scheduling drift and sustained CPU, not as discrete long tasks.
Do not read a zero long-task count as contradicting the "p95 long task 4,653 ms" figure in earlier write-ups — that came from a payload workload, not bare publications.
Deviations
setAgentStatuses/transactAgentStatuses, which are not onmain. It lands with the store slice. The--agent-status-write-modeflags, import, and call site were stripped rather than left dangling, since keeping the import with the module excluded leaves the script unloadable.Validation
typecheck:tsc:webexit 0. 1 test file / 2 tests pass.check:code-quality:changed0 new findings.check:max-lines-ratchetOK.oxfmt --checkandoxlintclean.Test results here are author-reported and were not independently re-run.
Made with Orca 🐋