Skip to content

fix(terminal): reap Windows agent trees with Job Objects - #9752

Closed
bbingz wants to merge 8 commits into
stablyai:mainfrom
bbingz:bbingz/fix-9704-windows-pty-descendants
Closed

bbingz wants to merge 8 commits into
stablyai:mainfrom
bbingz:bbingz/fix-9704-windows-pty-descendants

Conversation

@bbingz

@bbingz bbingz commented Jul 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Opt agent-owned Windows ConPTY roots into a kill-on-close Job Object before their primary thread is resumed.
  • Reap descendants on explicit kill and on natural root exit without a PID snapshot or PowerShell/taskkill sweep.
  • Keep plain terminals, WSL, Unix, and the current SSH relay path on their existing behavior.
  • Force patched Windows node-pty installs to build the matching native addon from source.

Fixes #9704

Screenshots

No visual change.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

Focused verification passed: 10 files / 350 tests, changed-file oxlint and oxfmt, max-lines, patch-hash, lockfile, and diff checks. pnpm run build:desktop also passed.

On Windows 11 10.0.22631 with Node 24.10.0 and VS2019 Build Tools, the final package patch installed cleanly and Orca's product path, npm_config_build_from_source=true pnpm rebuild node-pty, produced winpty-agent.exe, winpty.dll, conpty.node, conpty_console_list.node, and pty.node (gyp info ok). A native ConPTY smoke verified that explicit kill and natural root exit both reaped parent/child/grandchild processes, while the plain-terminal control left detached descendants alive until harness cleanup.

The full pnpm lint command is currently blocked by the existing src/renderer/src/components/skills/skill-freshness-group.ts:101 switch-exhaustiveness error on origin/main. The full repository test command and the exact template command pnpm build were not run; focused tests plus pnpm run build:desktop and the Windows native build/smoke were used instead.

AI Review Report

Independent AI reviews checked Job Object ownership, suspend/assign/resume ordering, handle races, natural-exit cleanup, resume failure, direct-root fallback, daemon/local ownership, plain-terminal and WSL exclusion, patch integrity, and cross-platform routing. Earlier review findings about cleanup lock placement and native warning-prone handle reuse were corrected and covered by contract tests; the final review returned spec-compliance PASS and code-quality APPROVED.

The cross-platform review explicitly covered macOS, Linux, Windows, WSL, daemon/local providers, Electron native rebuild selection, shell behavior, and SSH relay scope. No shortcut, label, or UI behavior changed.

Security Audit

Reviewed process-termination scope, native handle lifetime, failure cleanup, command execution, path handling, IPC/API threading, dependencies, and secrets. Job Object ownership is opt-in only for recognized agent PTYs; ordinary terminals are excluded. The implementation removes the proposed PowerShell/PID sweep, introduces no user-derived shell command, adds no dependency or secret handling, and falls back only to terminating the known root when Job setup fails.

Notes

Windows local and daemon-owned agent PTYs are covered, including the remote-server daemon path. Windows SSH relay remains unchanged because it installs vanilla node-pty; shipping the patched native addon through that boundary is tracked separately by TODO #1693.

The issue also discusses why kill requests may be initiated, transient EAGAIN, and stale registry entries. This PR fixes descendant cleanup once the agent PTY is killed; it does not claim to change those separate initiators or diagnostics.

ELI5

On Windows, killing an agent terminal could leave child processes behind. Agent ConPTY sessions join a kill-on-close Job Object so the whole tree dies with the root without sweeping every PID by hand.

@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Ready for first review — fixes #9704 (Windows agent PTY descendant reaping via Job Objects; also covers the #9045 orphaned-tree failure mode).

MERGEABLE on current main. Focused tests + Windows native smoke described in the PR body.

@bbingz

bbingz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current origin/main (6d55c7fa16).

Conflicts were pnpm-lock.yaml (node-pty patch hash) and the final node-pty patch file; resolved to the tip patch + matching lock hash.

Focused tests: pty-subprocess / local-pty-provider / descendant-termination / job-object contract 232/232 green.

@bbingz
bbingz force-pushed the bbingz/fix-9704-windows-pty-descendants branch from 6be9473 to 186e042 Compare July 23, 2026 02:22
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The changes patch node-pty for Windows Job Object support, native handle cleanup, console process-list fallback, Unix symbol compatibility, and structured POSIX spawn errors. Runtime rebuild scripts now detect platform-specific native artifacts and enable source builds for patched node-pty. PTY spawning selectively propagates useConptyJobObject for native Windows agent sessions while excluding WSL shells. Local PTY shutdown now coordinates root ownership, Job Object termination, descendant cleanup, and physical-exit settlement. Tests cover native patch contracts, rebuild behavior, spawn option propagation, and teardown sequencing.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.84% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately reflects the main change: Windows agent process trees are reaped with Job Objects.
Description check ✅ Passed The description covers Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes with the required details.
Linked Issues check ✅ Passed The changes implement Windows Job Object cleanup for agent PTYs, matching #9704's descendant-reaping requirement while leaving other paths unchanged.
Out of Scope Changes check ✅ Passed The patch set stays focused on the Windows Job Object fix, related rebuild logic, typings, and tests without clear unrelated additions.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6d8483ac-a942-4af5-a6e6-216b07c905e8

📥 Commits

Reviewing files that changed from the base of the PR and between 6d55c7f and 186e0422de0cccb617b5f55cdc1d8e0d5eca9699.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (13)
  • config/patches/[email protected]
  • config/scripts/ensure-native-runtime.mjs
  • config/scripts/node-pty-windows-job-object-contract.test.mjs
  • config/scripts/rebuild-native-deps.mjs
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/daemon/pty-subprocess.ts
  • src/main/daemon/terminal-session-teardown.test.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/providers/local-pty-utils-windows-fallback.test.ts
  • src/main/providers/local-pty-utils.ts
  • src/main/pty-descendant-termination.test.ts
  • src/main/pty-descendant-termination.ts

Comment thread config/patches/[email protected] Resolved
@bbingz

bbingz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Restack note

Rebased onto latest main (force-with-lease). All 6 commits applied cleanly.

Remains the Windows Job Object reaping path that #9804 explicitly deferred (authorized kill of agent ConPTY trees without PowerShell/taskkill). Orthogonal to closeLifecycle / host-authoritative session work.

Coordinates with:

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
config/scripts/ensure-native-runtime.mjs (1)

67-67: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add direct coverage for the Windows source-build contract.

The supplied tests skip the Windows artifact path and do not assert npm_config_build_from_source=true. Add coverage confirming that Windows requires conpty.node, enables patched source-build eligibility, and passes the environment flag to pnpm rebuild node-pty; otherwise regressions in this critical path can go undetected.

Also applies to: 303-307, 321-327, 339-346


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 06a031cc-cf96-48a4-a860-17163c3356de

📥 Commits

Reviewing files that changed from the base of the PR and between 186e0422de0cccb617b5f55cdc1d8e0d5eca9699 and 7b6fd0b9b4f797c92829fa93de123539f60a253f.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (13)
  • config/patches/[email protected]
  • config/scripts/ensure-native-runtime.mjs
  • config/scripts/node-pty-windows-job-object-contract.test.mjs
  • config/scripts/rebuild-native-deps.mjs
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/daemon/pty-subprocess.ts
  • src/main/daemon/terminal-session-teardown.test.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/providers/local-pty-utils-windows-fallback.test.ts
  • src/main/providers/local-pty-utils.ts
  • src/main/pty-descendant-termination.test.ts
  • src/main/pty-descendant-termination.ts
🚧 Files skipped from review as they are similar to previous changes (11)
  • src/main/providers/local-pty-utils-windows-fallback.test.ts
  • src/main/pty-descendant-termination.test.ts
  • config/scripts/rebuild-native-deps.mjs
  • src/main/daemon/terminal-session-teardown.test.ts
  • src/main/providers/local-pty-provider.test.ts
  • config/scripts/node-pty-windows-job-object-contract.test.mjs
  • src/main/providers/local-pty-provider.ts
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/providers/local-pty-utils.ts
  • src/main/daemon/pty-subprocess.ts
  • config/patches/[email protected]

@bbingz
bbingz force-pushed the bbingz/fix-9704-windows-pty-descendants branch from 7b6fd0b to b9ee8d8 Compare July 24, 2026 09:01
@bbingz

bbingz commented Jul 24, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (981653f27d). The scope of this PR changed materially in the process, so flagging it rather than leaving it in the diff:

Upstream #10100 (fix(win): taskkill agent PTY descendant trees on stop) landed after this branch's base and solves the stop-time half of #9704 with taskkill /T /F. The early commits here implemented their own taskkill/PID-identity path, so during the rebase those were resolved in favor of upstream's structure — this PR no longer competes with #10100. What remains on top is the Job Object layer only, which cuts the diff down to 14 files.

Why it is still worth having on top of #10100: the Job Object binds at spawn (agent ConPTY, useConptyJobObject gated on isAgentPty) rather than at stop, so membership is kernel-tracked at creation instead of walked from a root PID at teardown. That keeps reaping correct for reparented children and removes the PID-reuse race a /T walk is exposed to. Plain shells and WSL are unaffected — the opt-in is agent-only, and windows-process-tree-kill.ts stays on main's path for everything else.

Adjacent upstream work checked and not overlapping: #10069 (never sweep descendants of an already-exited PTY root, POSIX hardening) and #10011 (orphan terminal recovery).

Verified: tsc --noEmit -p config/tsconfig.node.json clean, and 6 test files / 235 tests passing across pty-descendant-termination, local-pty-provider, local-pty-utils-windows-fallback, windows-process-tree-kill, pty-subprocess, terminal-session-teardown. Not verified on a real Windows host — the Job Object path is covered by mocks here, so a Windows run before merge would be worthwhile.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
config/patches/[email protected] (1)

196-247: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard the spawn-error helpers for OpenBSD too.

PtyFork now calls pty_posix_spawn(...) and pty_format_spawn_error(...), and those helpers use pty_errno_name and pty_set_spawn_error, but all of them are defined only inside #if defined(__APPLE__) even though the declarations and OpenBSD call path also include __OpenBSD__. This can leave an OpenBSD build with unresolved-spawn-error symbols or a miscompiled error path; wrap the helper definitions in the same __APPLE__ || __OpenBSD__ guard as the declarations.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fcc861ce-674c-4a73-8e3a-4ad140ce9f46

📥 Commits

Reviewing files that changed from the base of the PR and between 7b6fd0b9b4f797c92829fa93de123539f60a253f and b9ee8d868d609dbd4cdd81bb20bb0b3d5a08dadd.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (13)
  • config/patches/[email protected]
  • config/scripts/ensure-native-runtime.mjs
  • config/scripts/node-pty-windows-job-object-contract.test.mjs
  • config/scripts/rebuild-native-deps.mjs
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/daemon/pty-subprocess.ts
  • src/main/daemon/terminal-session-teardown.test.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/providers/local-pty-utils-windows-fallback.test.ts
  • src/main/providers/local-pty-utils.ts
  • src/main/pty-descendant-termination.test.ts
  • src/main/pty-descendant-termination.ts
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/main/daemon/terminal-session-teardown.test.ts
  • src/main/providers/local-pty-utils-windows-fallback.test.ts
  • src/main/providers/local-pty-provider.ts
  • config/scripts/node-pty-windows-job-object-contract.test.mjs
  • config/scripts/rebuild-native-deps.mjs
  • config/scripts/ensure-native-runtime.mjs
  • src/main/daemon/pty-subprocess.ts

@bbingz
bbingz force-pushed the bbingz/fix-9704-windows-pty-descendants branch from b9ee8d8 to 563bb9b Compare July 25, 2026 02:41

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
config/scripts/ensure-native-runtime.mjs (1)

303-307: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add or verify Windows regression coverage for the new rebuild contract.

The supplied config/scripts/ensure-native-runtime.test.mjs case is skipped on win32, so it does not exercise conpty.node selection or verify npm_config_build_from_source on the target platform. Please confirm the separate contract/smoke tests cover both behaviors; otherwise add a Windows-safe test.

Also applies to: 339-346


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 3905e60e-5dd2-4747-bdc3-cc5ee7915ce0

📥 Commits

Reviewing files that changed from the base of the PR and between b9ee8d868d609dbd4cdd81bb20bb0b3d5a08dadd and 563bb9b.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (11)
  • config/patches/[email protected]
  • config/scripts/ensure-native-runtime.mjs
  • config/scripts/node-pty-windows-job-object-contract.test.mjs
  • config/scripts/rebuild-native-deps.mjs
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/daemon/pty-subprocess.ts
  • src/main/daemon/terminal-session-teardown.test.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/providers/local-pty-utils-windows-fallback.test.ts
  • src/main/providers/local-pty-utils.ts
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/main/daemon/terminal-session-teardown.test.ts
  • src/main/providers/local-pty-utils-windows-fallback.test.ts
  • config/scripts/rebuild-native-deps.mjs
  • config/scripts/node-pty-windows-job-object-contract.test.mjs
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/daemon/pty-subprocess.ts
  • config/patches/[email protected]

@bbingz
bbingz force-pushed the bbingz/fix-9704-windows-pty-descendants branch 2 times, most recently from 24f55b3 to e78365c Compare July 26, 2026 14:26
@nwparker nwparker added the bug Something isn't working label Jul 27, 2026
bbingz added 7 commits August 5, 2026 12:49
After rebase, useConptyJobObject referenced isAgentPty before definition.
Hoist the agent-session predicate and restore tip local-pty tests.
Drop redundant Windows root-identity plumbing already covered by
upstream stablyai#10484/stablyai#10674, document Job Object as the primary reaper with
identity-gated taskkill as fallback, guard Apple/OpenBSD spawn helpers
to avoid unused-function -Werror noise, and regenerate the node-pty
patch so it applies cleanly to 1.1.0.
Rebase conflicts kept main's local-pty suite; re-add the Windows Job
Object opt-in and WSL sweep assertions from the pre-rebase tip.
@bbingz
bbingz force-pushed the bbingz/fix-9704-windows-pty-descendants branch from e78365c to 9a170e3 Compare August 5, 2026 04:52
@bbingz

bbingz commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

Closing as part of fork PR backlog cleanup.

This branch is long-conflicted (DIRTY) against current main and is not on the active campaign rebase list. Feel free to reopen or cut a fresh PR from an updated branch if the change is still needed.

@bbingz bbingz closed this Aug 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Windows: PTY descendants survive session kill — orphaned agent process trees accumulate (~1.1GB)

3 participants