fix(terminal): confirm the agent from ConPTY console presence to avoid false exits
Follow-up to #9244. #9244 covered the Windows foreground-scan timeout case; this eliminates the remaining false "agent done" cause by not running the whole-process-table scan on the hot path at all.
Problem
On Windows, "is the agent still the terminal's foreground process?" is answered by a whole-process-table Get-CimInstance Win32_Process PowerShell fork (3s timeout). Under load (many agents doing heavy work) that scan either exceeds its timeout or returns an incomplete snapshot (the agent row missing). Either way the completion coordinator reads the shell as the foreground, concludes the agent exited, and fires a false "agent done" while the agent is still working — multiplied across many worktrees, that's the notification flood.
Fix
While a recognized agent is still active on a pty, confirm it with a cheap, terminal-scoped ConPTY console-membership read (readWindowsConptyProcessIds, which Orca already vendors) instead of the whole-table scan:
- When node-pty only names the shell (so a scan would otherwise run) and an agent was already recognized here → read the console process list. A child process still attached to this console means the agent is working → keep it, skip the whole-table scan.
- Only when the console is shell-only (or the read degrades) → fall through to the authoritative scan (with #9244's degraded-scan fallback).
Why this is strictly better than #9244
- Common case (agent working, console has a child): the whole-table scan never runs → neither the timeout nor the incomplete-snapshot can happen → no false completion.
- Console shell-only / read degrades: falls through to the existing scan + #9244 fallback → identical to today, never worse.
- Fail-safe direction: the only imprecision is if the agent exits and the shell immediately runs another command (console still has a child) — we'd briefly keep the agent name (a stale name, never a false "done"), self-correcting once the console goes child-less.
It's a no-op off Windows (the console read only runs on win32).
Testing
- New pure gate helper
canConfirmAgentFromConsolePresence— 4/4. - Two new win32 provider tests: console presence → keep the agent without a second scan; shell-only → fall through to the scan.
- Full
src/main/providerssuite (467 tests) green;typecheck:nodeclean; oxlint/oxfmt clean.
Live validation on real Windows (does the console read reliably show a child while the agent runs, under the same load that times out the CIM scan) is in progress against this branch.
[!NOTE]
Reviews paused
It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the
reviews.auto_review.auto_pause_after_reviewed_commitssetting.Use the following commands to manage reviews:
@coderabbitai resumeto resume automatic reviews.@coderabbitai reviewto trigger a single review.Use the checkboxes below for quick actions:
- [ ] ▶️ Resume reviews
- [ ] 🔍 Trigger review
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 697718e0-579c-449f-9a1b-c86d33ebb964
📥 Commits
Reviewing files that changed from the base of the PR and between 1c05afbfba884d23ea4bde8f8428693f6574ad00 and 3a152c005bab1924b438181a515f9b524bbefc08.
📒 Files selected for processing (2)
src/main/providers/windows-conpty-process-membership.test.tssrc/main/providers/windows-conpty-process-membership.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/providers/windows-conpty-process-membership.test.ts
📝 Walkthrough
Walkthrough
Windows foreground-process detection now uses cached agent identity and ConPTY console membership to confirm active agents before running the full resolution scan. ConPTY results are validated and filtered to exclude the helper process. A new confirmation helper defines the fast-path conditions, while daemon refresh logic preserves cached identities during degraded scans and retires them only after shell-only confirmation. Tests cover membership filtering, fast confirmation, fallback scans, and identity retention.
🚥 Pre-merge checks | ✅ 3 | ❌ 2
❌ Failed checks (2 warnings)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Description check | ⚠️ Warning | The description is detailed, but it does not follow the required template and is missing several required sections. | Add the required template sections: Summary, Screenshots (or 'No visual change'), Testing checklist, AI Review Report, Security Audit, and Notes. |
| Docstring Coverage | ⚠️ Warning | Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (3 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | ✅ Passed | The title clearly summarizes the Windows ConPTY foreground-detection fix and matches the main change. |
| Linked Issues check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
| Out of Scope Changes check | ✅ Passed | Check skipped because no linked issues were found for this pull request. |
✨ Finishing Touches
📝 Generate docstrings
- [ ] Create stacked PR
- [ ] Commit on current branch
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 @coderabbitai help to get the list of available commands.
Windows validation: the fix is correct but lands on a path that doesn't run on Windows-with-daemon
Validated on real Windows 11. Summary: the technique is sound, but as written this change does not engage on the default Windows configuration, so it does not fix the false "agent done" it targets. The same is true of the already-merged sibling change in local-pty-provider.ts.
The routing gap (root cause of "we can't see it engage live")
On Windows the terminal daemon hosts PTYs. initDaemonPtyProvider swaps the local provider for the daemon adapter (setLocalPtyProvider), so getForegroundProcess / confirmForegroundProcess route over the socket to the daemon and are resolved by src/main/daemon/pty-subprocess.ts — not local-pty-provider.ts. This PR only modifies local-pty-provider.ts, which on Windows is exercised only in daemon-unavailable fallback.
Direct proof (instrumented both paths, verified compiled into the running build, then drove a real agent):
local-pty-provider.getForegroundProcess— 0 invocations- daemon foreground path (
pty-subprocess.ts) — 326 invocations
Every foreground resolution went through the daemon; the modified code never ran.
The false-exit reproduces on the daemon path
With a recognized agent genuinely working ("Running 1 shell command · 2m 16s", status "Working…"), under the load that times out the whole-table CIM scan (CIM 31/31 timed out, avg ~3175ms):
- daemon
getForegroundProcess→ shell (powershell.exe) 95/95 - daemon
confirmForegroundProcess→ null 30/30 (not the agent) - the daemon's async
scheduleAgentForegroundRefreshcleared the cached agent on the degraded scan (available === false,hadCachedAgent: true)
Mechanism: scheduleAgentForegroundRefresh (pty-subprocess.ts ~L986) ignores the scan's available flag; a timeout returns "no recognized agent," which clears cachedAgentForeground (~L1001), so the next getForegroundProcess returns the shell. The confirmation step can't save it either — resolveWindowsAgentForegroundProcessWithAvailability returns available: false and bails before the ConPTY console-membership read (windows-agent-foreground-process.ts:51), so the console read is unreachable under a CIM timeout. Downstream, getTerminalAgentStatus (orca-runtime.ts ~L11181) flips isRunningAgent to false via terminalHasShellForegroundProcess → false "agent done."
The good news: the technique is validated
The ConPTY console-membership read is reliable under exactly the load that times out the CIM scan. Standalone rig against the real readWindowsConptyProcessIds, under representative concurrent-scan load:
- 20/20 non-null reads while the CIM scan degraded 8/20
- console read avg ~1.4s / max ~1.9s (under its 3s cap), vs the 3s+ CIM timeout
So the approach is right — it just has to live in the daemon.
Where the fix belongs
Apply the same idea to the daemon's scheduleAgentForegroundRefresh (pty-subprocess.ts): (a) don't clear the cached agent when the scan is degraded (available === false) — mirrors the sibling local-pty-provider change; and (b) for the incomplete-snapshot case (available: true but the agent row is missing), gate the clear behind a console-presence read — mirrors this PR. The pure helpers (resolveStableForegroundProcess, canConfirmAgentFromConsolePresence) are reusable as-is; only the daemon's cache/refresh wiring is new.
Net: keep this change (correct, no-regression on the fallback path), but the Windows-with-daemon fix needs to move into pty-subprocess.ts for users to actually get it.
Expanded to the primary Windows path (daemon)
Validation on real Windows showed the initial change never engaged: it lived in the local PTY provider, but Windows PTYs are hosted by the terminal daemon, whose own foreground-identity refresh is what runs by default. Instrumented hit counts confirmed the local-provider path was bypassed entirely.
Added the same protection to the daemon foreground path (pty-subprocess.ts), which is where the false exit actually originates — the refresh was retiring the cached agent on a timed-out/incomplete CIM scan:
- A degraded scan (
available: false) no longer retires the identity. - An authoritative scan that resolves no agent is confirmed against a ConPTY console-membership read before retiring — an incomplete snapshot with a child still attached keeps the agent; only a shell-only console retires it. Scoped to a shell fallback so the deliberate wrapper (
npm-after-exit) retirement is unaffected. The membership read stays off the sync foreground read. - The sync foreground read serves the cached agent across a Windows shell fallback (an unreliable exit signal under ConPTY lag) until the refresh authoritatively retires it.
New daemon degraded-scan tests cover keep-on-degraded, keep-on-incomplete-snapshot-with-console-child, and retire-on-shell-only-console. Full daemon + providers suites green; typecheck/lint clean. Head is now bf9320257.
Windows re-validation: the relocation to the daemon path works — false-exit-under-load is genuinely fixed
Validated on real Windows 11. Instrumented the daemon (pty-subprocess.ts getForegroundProcess + the refresh .then console read), rebuilt the daemon bundle (confirmed the dev daemon runs this worktree's out/main/daemon-entry.js), and drove a real heavy agent task under the load that times out the whole-table CIM scan.
#1 — Fast path fires; no false "agent done" under load: PASS
With the agent genuinely working, under CIM load (CIM 23/23 timed out, avg ~3.1s):
- daemon
getForegroundProcess→ agent 70/70, shell 0/70 (previous revision was shell 95/95) unreadAgentCompletionPanes(this pane) → never fired
Daemon decision log confirms the mechanism:
- serve-cached-agent-on-Windows-shell-fallback 434× (sync path returns the agent, not the shell)
- keep-on-degraded-scan (
available:false) 42× — timed-out scans no longer retire the identity - retire calls: 0 while working
The primary bug — the false "agent done" when the CIM scan times out under load — is fixed on the path that actually runs on Windows (the terminal daemon).
#2 — Real exit detection: a regression was found in this revision, root-caused, and has since been fixed
On the revision first validated, after a real exit the daemon kept reporting the exited agent's name indefinitely (40s+, 0 retires). Root cause: the ConPTY console-membership helper attaches to the console to read it, so it counts its own probe process — a bare shell read as size 2 ([helperPid, shellPid]), so "shell-only" was never detectable and the retire guard never fired. Controlled probe at the time: bare shell → non-null size 2; shell+agent → size 3, with the membership check only rejecting length <= 1.
Fix direction (now landed): drop the helper's own PID before judging membership and treat "only the shell remaining" as no-child, in the shared helper so both the daemon and local-provider paths are covered — plus a real-function unit test for the [helper, shell] → null / [helper, shell, agent] → {shell, agent} cases the mocked tests couldn't reach. Re-validation of the exit path against the fixed head follows.
Net: keep this change — the false-exit-under-load is genuinely fixed on the daemon path, and the exit-detection regression it briefly introduced has been root-caused and corrected in the same shared helper.