Repository navigation
perf: dedupe relay process-table scans behind a short-TTL cache (#6288) - #6667
Conversation
Agent foreground-process inspection runs `ps -axo pid=,ppid=,stat=,command=` (a full system process-table scan) on a 750ms/2000ms per-pane cadence. On a shared SSH relay every tracked agent terminal drives it, so concurrent panes each forked their own `ps` — sustaining up to the per-second inspection cap of full-table scans for as long as agents are open, pinning idle relay CPU and amplified by AV process scanning. This is the CPU half of #6288 (PR #6564 covers the memory-leak half). Memoize the scan behind a single in-flight promise + 500ms TTL shared by the relay and local main-process call sites. 500ms sits below the active poll's minimum inter-poll gap (~675ms after jitter), so a single pane never reuses a snapshot older than it would have scanned itself — same data and freshness, just deduplicated within the cadence window (worst case ~8 scans/sec -> ~2). Failures are never cached (in-flight cleared on settle) so a transient `ps` error retries and the existing best-effort fall-through is preserved. Windows branches are untouched; no git-provider implications. Co-authored-by: Orca <[email protected]>
📝 WalkthroughWalkthroughA new shared module, 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 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 |
Drives the real local foreground-inspection call site under the documented 750ms agent-completion cadence across 6 concurrently-inspecting agent panes over a 30s window, counting actual `ps -axo pid=,ppid=,stat=,command=` full-table scans. Reproduces the waste on `main` (240 inspections -> 240 scans, 1.0/inspection; the test fails there) and proves the fix (240 inspections -> 40 scans, 0.167/inspection — bounded by poll ticks, not pane count) while every pane still resolves its foreground agent. Guards against regressing the cache back to a per-call scan. Co-authored-by: Orca <[email protected]>
… staleness (#6288) Co-authored-by: Orca <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 88ab0f5f-bfd7-4700-9883-57680e9ec8ca
📒 Files selected for processing (7)
src/main/providers/agent-foreground-process-ps-scan-volume.test.tssrc/main/providers/agent-foreground-process.test.tssrc/main/providers/agent-foreground-process.tssrc/relay/pty-shell-utils.test.tssrc/relay/pty-shell-utils.tssrc/shared/process-table-snapshot.test.tssrc/shared/process-table-snapshot.ts
| const totalInspections = PANE_COUNT * TICKS | ||
| // Pre-fix this equals totalInspections (one scan per inspection). With the | ||
| // shared cache, concurrent panes within a tick share one scan and the 500ms | ||
| // TTL forces a fresh scan each new 750ms tick -> ~one scan per tick. | ||
| expect(psScanCount.value).toBeLessThanOrEqual(TICKS + 1) | ||
| expect(psScanCount.value).toBeLessThan(totalInspections / 2) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Make the scan-count assertion prove per-tick refresh.
psScanCount.value === 1 still satisfies both expectations here, so a reader that never expires its cache across the full 30-second window would pass this regression. Add a lower bound near TICKS so this test actually fails when the default reader stops rescanning once per 750ms tick.
Proposed fix
- expect(psScanCount.value).toBeLessThanOrEqual(TICKS + 1)
+ expect(psScanCount.value).toBeGreaterThanOrEqual(TICKS - 1)
+ expect(psScanCount.value).toBeLessThanOrEqual(TICKS + 1)
expect(psScanCount.value).toBeLessThan(totalInspections / 2)📝 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 totalInspections = PANE_COUNT * TICKS | |
| // Pre-fix this equals totalInspections (one scan per inspection). With the | |
| // shared cache, concurrent panes within a tick share one scan and the 500ms | |
| // TTL forces a fresh scan each new 750ms tick -> ~one scan per tick. | |
| expect(psScanCount.value).toBeLessThanOrEqual(TICKS + 1) | |
| expect(psScanCount.value).toBeLessThan(totalInspections / 2) | |
| const totalInspections = PANE_COUNT * TICKS | |
| // Pre-fix this equals totalInspections (one scan per inspection). With the | |
| // shared cache, concurrent panes within a tick share one scan and the 500ms | |
| // TTL forces a fresh scan each new 750ms tick -> ~one scan per tick. | |
| expect(psScanCount.value).toBeGreaterThanOrEqual(TICKS - 1) | |
| expect(psScanCount.value).toBeLessThanOrEqual(TICKS + 1) | |
| expect(psScanCount.value).toBeLessThan(totalInspections / 2) |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/shared/process-table-snapshot.ts (1)
13-20: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winShorten the inline rationale comment.
The rationale is helpful, but this is well beyond the guideline’s “one or two lines” limit. Please keep the non-obvious reason inline and move the extra cadence math/context to the PR, design doc, or test names.
✂️ Suggested trim
-// Why: 500ms is below the active cadence poll's minimum inter-poll gap (~675ms -// = 750ms less jitter), so a cadence-driven pane never reuses a snapshot older -// than it would have scanned itself; a burst of panes polling in the same -// window collapses from up to 8 scans/sec down to ~2/sec. The faster -// event-driven follow-up inspections (e.g. the pending-title confirmation, -// which can re-fire <500ms apart) intentionally accept a <=500ms-stale table: -// they only confirm the same agent still owns the pane, and process-exit is -// debounced across repeated samples, so a near-instant cached scan answers -// identically to a fresh fork. +// Why: 500ms stays below the poll cadence floor, so panes do not reuse a +// snapshot older than they would have observed from their own `ps` scan.As per coding guidelines, "Keep comments short — one or two lines, capturing only the non-obvious reason".
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: eed4682b-92cf-4140-99d4-547158862a8b
📒 Files selected for processing (1)
src/shared/process-table-snapshot.ts
…6693) A terminal pane that has ever run an agent keeps polling the OS process table for completion detection even while HIDDEN. The cadence (750ms active / 2000ms idle) did not depend on visibility, so a backgrounded pane forked a `ps`-scan every ~750ms purely to keep the process-exit backstop alive — wasting idle CPU, especially on shared SSH relays. Follow-up to #6288 / PR #6667 (merged), which deduped scans WITHIN a poll tick via a 500ms-TTL snapshot cache. This attacks the orthogonal axis: the number of ticks a hidden pane runs. Hidden panes now poll at a 3s cadence (HIDDEN_POLL_INTERVAL_MS). This is safe because the process poll is only a BACKSTOP: the primary completion signals — Orca-managed agent hooks (observeHookStatus, push via IPC) and xterm title changes (observeTitle) — are event-driven and fire regardless of poll cadence or visibility. Only a non-hooked agent with no recognizable completion title relies solely on the poll; for that case worst-case hidden completion-notification latency rises to ~2x3s (~6s, repeat-idle-sample) from ~2x750ms. Visible-pane cadence is unchanged (750ms). Becoming visible re-arms the slow hidden timer at full cadence immediately, so switching back to a throttled pane is not sluggish (scheduleNextPoll previously no-oped while any timer was pending). Measured inspection calls over 60s: hidden 78->20 (-74%); visible 78->78. Co-authored-by: Orca <[email protected]>
#7384) * perf(windows): dedupe per-pane process-table scans in agent inspection Windows agent foreground-process inspection forks a whole-process-table PowerShell/CIM scan per pane on the same 750ms/2000ms cadence the POSIX path uses. The POSIX side routes through getProcessTableSnapshot (500ms TTL + single in-flight, #6288/#6667), collapsing N concurrent panes to ~2 scans/sec. The Windows path (queryWindowsProcessDescendants) had no such dedup: K concurrent agent panes forked K powershell.exe cold-starts, each enumerating the ENTIRE process table then filtering per-pid in JS — ~10-40x heavier than `ps` (a powershell cold start is ~150-400ms CPU + tens of MB RSS). The degraded/local PTY provider path calls it with no per-pane throttle at all. This is the Windows analogue of the idle-CPU churn #6288 fixed for POSIX. Generalize the existing createProcessTableSnapshotReader factory to be generic over its scan result (default T = string, so the POSIX path and its test are byte-identical) and add a Windows singleton reader that caches parsed WindowsProcessRow[]. queryWindowsProcessDescendants now reads the shared snapshot and runs its own descendant walk; runWindowsProcessRows throws on total enumeration failure so the miss is not cached and the prior null-fallback contract (callers fall through to node-pty's name) is preserved. Windows scan-volume regression test (mirrors the POSIX #6288 guard) drives PANE_COUNT concurrent panes over the cadence window and asserts powershell.exe spawns are bounded by ticks, not pane count, while every pane still resolves its descendant. Reverting the dedup fails both cases. POSIX snapshot + volume tests unchanged and green; node/web/cli typecheck clean. Co-authored-by: Orca <[email protected]> * test: reset windows process-rows snapshot between agent-foreground cases The new module-level Windows rows reader caches for 500ms with real Date.now(), so one case's mocked process table was served to the next case's assertions (7 CI failures in agent-foreground-process.test.ts). Mirror the suite's existing POSIX resetProcessTableSnapshotForTests() with the Windows reset in beforeEach. Co-authored-by: Orca <[email protected]> --------- Co-authored-by: Orca <[email protected]>
…#7518) getProcessTableSnapshot deduped the ps fork (#6288/#6667) but cached only the raw stdout string on POSIX, so every concurrent agent pane re-ran parsePsRows over the identical output within each 500ms TTL window — O(M*P) redundant tokenization + row allocation. The Windows reader already caches parsed rows; this makes the POSIX default reader do the same by parsing inside the deduped scan and returning ProcessTableRow[]. Collapses the duplicate parsePsRows in the main and relay foreground resolvers into one shared parseProcessTableRows. Co-authored-by: Orca <[email protected]>
…gate Review fixes on the PID-identity guard. The probe read the process table through a new uncached export, bypassing the reader that worktree teardown depends on: worktree-teardown.ts fans out 32-wide inside a 10s deadline, so a delete forked 32 powershell cold-starts (the churn windows-foreground-process-rows.ts:25-32 warns about, #6288/#6667). getFreshSnapshot() already guarantees a scan that starts after the request -- the exact property the bypass existed for -- and coalesces concurrent callers, so use it. Measured on the new test: 32 scans -> 1. The PhysicalExitTracker.hasExited gate could never fire. markExited() is only reached at local-pty-provider.ts:985/:1431, and both are followed synchronously by clearPtyState(), which deletes the ptyProcesses entry -- so ownsRoot's map check is already false whenever hasExited is true. Reverting it broke no test. Drop it and the shared getter it added; the identity probe already covers every ownsRoot caller from inside killWithDescendantSweep. Also point the Windows terminal-restart E2E job at the files that own this behavior, so a change to the new Windows-only module runs the one job that executes on a real Windows host.
…#10484) * fix(terminal): verify Windows PTY root identity before taskkill /T /F killWithDescendantSweep guarded its Windows tree kill with ownsRoot() alone, which is JS state only. node-pty's ConPTY exit watcher closes the last shell handle before it queues the JS exit callback, so Windows can recycle the PID while the session map still looks live — force-killing an unrelated process and its whole descendant tree. Walk the recycled PID's ancestry back to this process before taskkill: skip the sweep when the root is gone or resolves to a stranger, and keep the sweep when identity is unknown so #10004 orphan cleanup still runs. Also gate the local provider's ownsRoot on observed physical exit. * fix(terminal): dedupe the Windows root-identity scan, drop dead exit gate Review fixes on the PID-identity guard. The probe read the process table through a new uncached export, bypassing the reader that worktree teardown depends on: worktree-teardown.ts fans out 32-wide inside a 10s deadline, so a delete forked 32 powershell cold-starts (the churn windows-foreground-process-rows.ts:25-32 warns about, #6288/#6667). getFreshSnapshot() already guarantees a scan that starts after the request -- the exact property the bypass existed for -- and coalesces concurrent callers, so use it. Measured on the new test: 32 scans -> 1. The PhysicalExitTracker.hasExited gate could never fire. markExited() is only reached at local-pty-provider.ts:985/:1431, and both are followed synchronously by clearPtyState(), which deletes the ptyProcesses entry -- so ownsRoot's map check is already false whenever hasExited is true. Reverting it broke no test. Drop it and the shared getter it added; the identity probe already covers every ownsRoot caller from inside killWithDescendantSweep. Also point the Windows terminal-restart E2E job at the files that own this behavior, so a change to the new Windows-only module runs the one job that executes on a real Windows host. * docs(terminal): state what the Windows root probe actually proves The probe checks subtree membership, not root identity: a recycle that lands on another Orca descendant (another pane's shell, an agent CLI, a git.exe we spawned) still reads `own`, and that is not remote during teardown when Orca is itself allocating pids. It bounds the blast radius rather than closing the class. Say so at the type and at classifyWindowsTreeKillTarget, and name what a real close would need (a CreationDate baseline -- the analogue of the POSIX lstart check already used here -- or an inherited handle / Job Object). Also note why our own pid must classify `foreign`. * ci(windows): trigger the terminal-restart E2E on the shared snapshot reader The Windows root-identity probe now reads through getFreshSnapshot, so an edit to that module changes Windows teardown behavior without touching any path the job already watches. * test(terminal): guard the teardown probe against a reintroduced scan bypass The existing volume guard covers queryWindowsProcessRowsFresh directly, but the identity-probe cases all inject readRows, so nothing exercised the DEFAULT reader wiring -- a bypass reintroduced inside windows-pty-root-identity would have gone unnoticed. Drive verifyWindowsTreeKillTarget 32-wide through the real reader and assert one scan. Verified it fails at 32 when the bypass is put back.
…lyai#6288) (stablyai#6667) * perf: dedupe relay process-table scans behind a short-TTL cache (stablyai#6288) Agent foreground-process inspection runs `ps -axo pid=,ppid=,stat=,command=` (a full system process-table scan) on a 750ms/2000ms per-pane cadence. On a shared SSH relay every tracked agent terminal drives it, so concurrent panes each forked their own `ps` — sustaining up to the per-second inspection cap of full-table scans for as long as agents are open, pinning idle relay CPU and amplified by AV process scanning. This is the CPU half of stablyai#6288 (PR stablyai#6564 covers the memory-leak half). Memoize the scan behind a single in-flight promise + 500ms TTL shared by the relay and local main-process call sites. 500ms sits below the active poll's minimum inter-poll gap (~675ms after jitter), so a single pane never reuses a snapshot older than it would have scanned itself — same data and freshness, just deduplicated within the cadence window (worst case ~8 scans/sec -> ~2). Failures are never cached (in-flight cleared on settle) so a transient `ps` error retries and the existing best-effort fall-through is preserved. Windows branches are untouched; no git-provider implications. Co-authored-by: Orca <[email protected]> * test: regression guard for stablyai#6288 ps-scan volume (repro + measurement) Drives the real local foreground-inspection call site under the documented 750ms agent-completion cadence across 6 concurrently-inspecting agent panes over a 30s window, counting actual `ps -axo pid=,ppid=,stat=,command=` full-table scans. Reproduces the waste on `main` (240 inspections -> 240 scans, 1.0/inspection; the test fails there) and proves the fix (240 inspections -> 40 scans, 0.167/inspection — bounded by poll ticks, not pane count) while every pane still resolves its foreground agent. Guards against regressing the cache back to a per-call scan. Co-authored-by: Orca <[email protected]> * docs: clarify 500ms TTL covers cadence floor + tolerated event-driven staleness (stablyai#6288) Co-authored-by: Orca <[email protected]> --------- Co-authored-by: Orca <[email protected]>
…tablyai#6693) A terminal pane that has ever run an agent keeps polling the OS process table for completion detection even while HIDDEN. The cadence (750ms active / 2000ms idle) did not depend on visibility, so a backgrounded pane forked a `ps`-scan every ~750ms purely to keep the process-exit backstop alive — wasting idle CPU, especially on shared SSH relays. Follow-up to stablyai#6288 / PR stablyai#6667 (merged), which deduped scans WITHIN a poll tick via a 500ms-TTL snapshot cache. This attacks the orthogonal axis: the number of ticks a hidden pane runs. Hidden panes now poll at a 3s cadence (HIDDEN_POLL_INTERVAL_MS). This is safe because the process poll is only a BACKSTOP: the primary completion signals — Orca-managed agent hooks (observeHookStatus, push via IPC) and xterm title changes (observeTitle) — are event-driven and fire regardless of poll cadence or visibility. Only a non-hooked agent with no recognizable completion title relies solely on the poll; for that case worst-case hidden completion-notification latency rises to ~2x3s (~6s, repeat-idle-sample) from ~2x750ms. Visible-pane cadence is unchanged (750ms). Becoming visible re-arms the slow hidden timer at full cadence immediately, so switching back to a throttled pane is not sluggish (scheduleNextPoll previously no-oped while any timer was pending). Measured inspection calls over 60s: hidden 78->20 (-74%); visible 78->78. Co-authored-by: Orca <[email protected]>
stablyai#7384) * perf(windows): dedupe per-pane process-table scans in agent inspection Windows agent foreground-process inspection forks a whole-process-table PowerShell/CIM scan per pane on the same 750ms/2000ms cadence the POSIX path uses. The POSIX side routes through getProcessTableSnapshot (500ms TTL + single in-flight, stablyai#6288/stablyai#6667), collapsing N concurrent panes to ~2 scans/sec. The Windows path (queryWindowsProcessDescendants) had no such dedup: K concurrent agent panes forked K powershell.exe cold-starts, each enumerating the ENTIRE process table then filtering per-pid in JS — ~10-40x heavier than `ps` (a powershell cold start is ~150-400ms CPU + tens of MB RSS). The degraded/local PTY provider path calls it with no per-pane throttle at all. This is the Windows analogue of the idle-CPU churn stablyai#6288 fixed for POSIX. Generalize the existing createProcessTableSnapshotReader factory to be generic over its scan result (default T = string, so the POSIX path and its test are byte-identical) and add a Windows singleton reader that caches parsed WindowsProcessRow[]. queryWindowsProcessDescendants now reads the shared snapshot and runs its own descendant walk; runWindowsProcessRows throws on total enumeration failure so the miss is not cached and the prior null-fallback contract (callers fall through to node-pty's name) is preserved. Windows scan-volume regression test (mirrors the POSIX stablyai#6288 guard) drives PANE_COUNT concurrent panes over the cadence window and asserts powershell.exe spawns are bounded by ticks, not pane count, while every pane still resolves its descendant. Reverting the dedup fails both cases. POSIX snapshot + volume tests unchanged and green; node/web/cli typecheck clean. Co-authored-by: Orca <[email protected]> * test: reset windows process-rows snapshot between agent-foreground cases The new module-level Windows rows reader caches for 500ms with real Date.now(), so one case's mocked process table was served to the next case's assertions (7 CI failures in agent-foreground-process.test.ts). Mirror the suite's existing POSIX resetProcessTableSnapshotForTests() with the Windows reset in beforeEach. Co-authored-by: Orca <[email protected]> --------- Co-authored-by: Orca <[email protected]>
…stablyai#7518) getProcessTableSnapshot deduped the ps fork (stablyai#6288/stablyai#6667) but cached only the raw stdout string on POSIX, so every concurrent agent pane re-ran parsePsRows over the identical output within each 500ms TTL window — O(M*P) redundant tokenization + row allocation. The Windows reader already caches parsed rows; this makes the POSIX default reader do the same by parsing inside the deduped scan and returning ProcessTableRow[]. Collapses the duplicate parsePsRows in the main and relay foreground resolvers into one shared parseProcessTableRows. Co-authored-by: Orca <[email protected]>
…stablyai#10484) * fix(terminal): verify Windows PTY root identity before taskkill /T /F killWithDescendantSweep guarded its Windows tree kill with ownsRoot() alone, which is JS state only. node-pty's ConPTY exit watcher closes the last shell handle before it queues the JS exit callback, so Windows can recycle the PID while the session map still looks live — force-killing an unrelated process and its whole descendant tree. Walk the recycled PID's ancestry back to this process before taskkill: skip the sweep when the root is gone or resolves to a stranger, and keep the sweep when identity is unknown so stablyai#10004 orphan cleanup still runs. Also gate the local provider's ownsRoot on observed physical exit. * fix(terminal): dedupe the Windows root-identity scan, drop dead exit gate Review fixes on the PID-identity guard. The probe read the process table through a new uncached export, bypassing the reader that worktree teardown depends on: worktree-teardown.ts fans out 32-wide inside a 10s deadline, so a delete forked 32 powershell cold-starts (the churn windows-foreground-process-rows.ts:25-32 warns about, stablyai#6288/stablyai#6667). getFreshSnapshot() already guarantees a scan that starts after the request -- the exact property the bypass existed for -- and coalesces concurrent callers, so use it. Measured on the new test: 32 scans -> 1. The PhysicalExitTracker.hasExited gate could never fire. markExited() is only reached at local-pty-provider.ts:985/:1431, and both are followed synchronously by clearPtyState(), which deletes the ptyProcesses entry -- so ownsRoot's map check is already false whenever hasExited is true. Reverting it broke no test. Drop it and the shared getter it added; the identity probe already covers every ownsRoot caller from inside killWithDescendantSweep. Also point the Windows terminal-restart E2E job at the files that own this behavior, so a change to the new Windows-only module runs the one job that executes on a real Windows host. * docs(terminal): state what the Windows root probe actually proves The probe checks subtree membership, not root identity: a recycle that lands on another Orca descendant (another pane's shell, an agent CLI, a git.exe we spawned) still reads `own`, and that is not remote during teardown when Orca is itself allocating pids. It bounds the blast radius rather than closing the class. Say so at the type and at classifyWindowsTreeKillTarget, and name what a real close would need (a CreationDate baseline -- the analogue of the POSIX lstart check already used here -- or an inherited handle / Job Object). Also note why our own pid must classify `foreign`. * ci(windows): trigger the terminal-restart E2E on the shared snapshot reader The Windows root-identity probe now reads through getFreshSnapshot, so an edit to that module changes Windows teardown behavior without touching any path the job already watches. * test(terminal): guard the teardown probe against a reintroduced scan bypass The existing volume guard covers queryWindowsProcessRowsFresh directly, but the identity-probe cases all inject readRows, so nothing exercised the DEFAULT reader wiring -- a bypass reintroduced inside windows-pty-root-identity would have gone unnoticed. Drive verifyWindowsTreeKillTarget 32-wide through the real reader and assert one scan. Verified it fails at 32 when the bypass is put back.
🧑🤝🧑 Impact & ELI5
What's slow today (ELI5). To label each terminal with the agent running in it (e.g. "codex", "gemini"), Orca peeks at the system's process list. The cheap way would be to ask "what's running under this terminal?" — but the code instead photographs the entire machine's process table and then sifts it down to the one terminal. Every open agent terminal does this on a ~0.75–2s loop. On a shared remote/SSH server with a few projects open, that's a stream of full-table
psscans running forever, and antivirus scans each one — so the server's CPU stays elevated even when nothing is happening. This is the CPU half of #6288; the existing PR #6564 fixes the memory-leak half (leaked IPC listeners on flaky reconnects). They're complementary.What this PR does (ELI5). When many terminals want that photo at nearly the same moment, take one photo and hand the same copy to all of them, and keep it for half a second before taking a fresh one. Same picture, same freshness for any single terminal — just not re-shot N times per tick.
What was happening
Agent foreground-process inspection runs a full system process-table scan:
then filters to one pid's subtree in JS. It's called per-pane on a 750ms (active) / 2000ms (idle) cadence by the agent-completion coordinator, and keeps running for any pane with agent evidence — even when the pane is hidden (
shouldRunCadenceInspectionreturns true whilehasAgentRunEvidence || lastForegroundAgent !== null). With multiple agent terminals across a few projects on one relay, the daemon sustains repeated full-table scans indefinitely, each forked independently with no caching or batching. The same scan exists on the local main-process path (agent-foreground-process.ts), but it's acutely felt on the shared relay daemon.src/relay/pty-shell-utils.ts→getRecognizedForegroundDescendantsrc/main/providers/agent-foreground-process.ts→resolveAgentForegroundProcesssrc/renderer/src/components/terminal-pane/agent-completion-coordinator.ts(ACTIVE_POLL_INTERVAL_MS = 750,IDLE_POLL_INTERVAL_MS = 2000); global capMAX_INSPECTION_STARTS_PER_SECOND = 8inagent-process-inspection-queue.tsReproduction + measured evidence
Added a deterministic repro/regression test,
src/main/providers/agent-foreground-process-ps-scan-volume.test.ts, that drives the real call site (resolveAgentForegroundProcess) under the documented 750ms cadence across 6 concurrently-inspecting agent panes over a 30-second window (40 ticks → 240 inspections) and counts actualps -axospawns. A realpsreturns the whole system, so the fixture contains every pane's process tree; each pane must still resolve its own foreground agent.ps -axofull-table scanscodex?main)≈83% fewer full-table scans (6×). Scan volume is now bounded by poll ticks, not by pane count — adding panes no longer multiplies
psspawns. The test fails onmain(ps_scans == inspections) and passes here, so it locks in the win. Measured by overlayingmain's pre-cache call site and re-running the identical harness:(
pshere is mocked to count spawns deterministically — the cost being removed is the spawn itself, which on a real shared relay is also scanned by AV per the issue. The count is the proxy for that CPU.)The fix
A shared
getProcessTableSnapshot()(src/shared/process-table-snapshot.ts) memoizes the scan behind a single in-flight promise + a 500ms TTL, used by both call sites.pscan't hand back a snapshot that's already past its TTL.pstimeout/error retries on the next call and the existing best-effort fall-through (node-pty's process name) is preserved — terminal identity never breaks PTY operation.This deletes redundant work rather than adding more caching layers; no behavior change (same
psdata, same fall-through, same Windows branches — Windows uses PowerShell/WMIC, untouched). No git-provider implications (process inspection, not source control).Scope vs #6564 / #5075
agent-completion-coordinator.tsis a complementary lever (lengthening the hidden-pane idle interval) left out here to keep the change minimal and behavior-preserving; can follow up if measurements warrant.Testing
src/main/providers/agent-foreground-process-ps-scan-volume.test.ts— the repro/regression guard above (before 240 → after 40 scans).src/shared/process-table-snapshot.test.ts(5 cases): concurrent calls collapse to one scan; cached reuse within TTL; rescan after TTL; capture-time stamped post-scan; failures not cached + retried.agent-foreground-process.test.tsandpty-shell-utils.test.tsupdated with a test-only cache reset inbeforeEach(the module cache otherwise carries one mocked-pscase into the next within the TTL).pnpm run typecheck✅ · oxlint ✅ · oxfmt ✅ · 37 tests pass across the four files.