Repository navigation
fix(quit): reap owned helpers before app exit - #18205
joowon-jang wants to merge 10 commits into
Conversation
Join local PTY cleanup to the quit barrier and sweep owned descendants. Gate emulator helper startup during shutdown so late helpers are cleaned instead of surviving app exit.
|
Note Reviews pausedIt 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
Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review.
|
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the full 15-file diff, concentrating on shutdown ordering, the acquire-vs-quit races in the emulator path, and the local-PTY descendant sweep, then traced each new code path against its callers.
- Local PTY teardown —
killAllPty()/LocalPtyProvider.killAll()/killAllLocalPtys()are now async and joined to the will-quit teardown barrier aslocal-ptys. Agent sessions and Windows PTYs route throughkillWithDescendantSweep; plain POSIX keeps the existingnohup-preservingrequestPlainPosixAppQuitTerminationpath. - Exit-callback suppression — new
ptyExitCallbacksSuppressedset prevents a late node-ptyonExitfrom re-entering runtime teardown during quit; it is read by the handler beforeclearPtyStateremoves it, so the ordering is safe. - Emulator shutdown gate — new
EmulatorBridgeShutdowncoordinator gatesregisterActiveEmulator/acquireHelperForDevice, tracks in-flight acquires, and on shutdown drains them and cleans up any helper that finishes starting after the snapshot. - Lease registry tracking —
EmulatorStartLeaseRegistrynow tracks active + in-flight leases with an idempotentshutdown(), cleaning up unreleased/session-started-during-shutdown helpers. - Runtime attach ordering —
registerActiveEmulatormoved inside thetryso a shutdown-refused registration releases the lease withcleanupIfUnused, rather than leaking the helper.
The double tracking (pendingHelperAcquires in the coordinator vs inFlightAcquires in the registry) is intentional and non-overlapping: the coordinator set covers the backendForDevice await window that precedes startLeases.acquire. Both shutdown flags are set in one synchronous block, so no acquire slips the gap. Quit-path liveness stays bounded by the existing settleTeardownWithinDeadline barrier, and killAllPty remains local-only (SSH/daemon PTYs untouched). Ran local-pty-provider-shutdown.test.ts — 24/24 pass.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the incremental commit 90dcad0c63 ("fix(quit): include orphaned helpers in app-shutdown emulator sweep") on top of the previously cleared 29f88cfe13.
- Orphan-inclusive shutdown sweep —
EmulatorBridgeShutdown.destroyAllSessionsInternal()now passesincludeOrphaned: truetostopHelperForDevicefor each managed session. On iOS this sweeps orphanedserve-simhelpers whose command targets the device UDID (in addition to the trackedhelperPid); on Android it removes device-scopedadb forwardleaks via-s <serial> forward --remove-all. - Test coverage — the managed-session sweep assertion now expects
includeOrphaned: true, and the helper-ownership suite's late-attach case already exercised thehelperPid: undefined+includeOrphaned: truepath.
The change is consistent with the pre-existing orphan-inclusive kill paths in EmulatorStartLeaseRegistry (cleanupStartedSession and cleanupIfUnused, which already pass includeOrphaned: true), so the app-quit sweep now reaps the same class of orphans the acquire/lease teardown already handled. Re-ran emulator-bridge.test.ts — 28/28 pass.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Merge current main while preserving OMP and immediate-close teardown behavior. Join the bounded identity-safe descendant verifier to app quit, coalesce updater and will-quit cleanup, cancel delayed startup delivery before capture, and release the POSIX native handle if root signalling fails. Add ten real-sweep regressions covering completion, PID safety and quit races. Validated 137 targeted tests, changed-code quality and scoped TypeScript checks. A real Linux PTY oracle reproduced the old survivor and verified the fix. Full aggregate TypeScript checks exceeded the cloud runner memory budget.
|
| export function killAllPty(): Promise<void> { | ||
| if (localProvider instanceof LocalPtyProvider) { | ||
| localProvider.killAll() | ||
| return localProvider.killAll() |
There was a problem hiding this comment.
killAllPty() now returns an asynchronous descendant sweep, but the update-install path discards that promise and records cleanup immediately. It cannot tell whether the sweep finished, and if the installer exits before the separate will-quit barrier joins it, the sweep can be abandoned. Joining or explicitly coordinating the promise would make update cleanup completion observable.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Reviewed the incremental commit 3f48601fd9 ("fix(quit): await verified local descendants before app exit") on top of the previously cleared 29f88cfe13 and 90dcad0c63, re-read the full 16-file diff end-to-end, and traced the new app-quit path against its callers.
- Awaited descendant verdict on app quit —
shutdownPtyForAppQuitnow passesterminateDescendants(→terminateShutdownDescendants) andawaitEscalation: trueintokillWithDescendantSweep, so the agent/Windows root is signalled only after the snapshot's descendants are SIGTERM'd, escalate to SIGKILL, and a bounded identity-safe verification returns a verdict; a non-exitedverdict is logged and the quit still proceeds. - Single in-flight app-quit sweep —
killAllLocalPtys()memoizes through a module-levelappQuitShutdownpromise (reset on settle), so the updater's earlykillAllPty()and will-quit's join share one sweep instead of racing two. - Final-handle fallback —
killRootdestroys the native PTY handle even when the force signal is rejected, matching the "app exit is the final boundary" contract. - Regression coverage — new
local-pty-app-quit.test.ts(10 tests) drives the real sweep and bounded verifier with only OS reads/signals mocked: awaited SIGKILL/absence ordering, concurrent-quit joining, recycled-PID safety, unreadable/hung/duplicate table bounds, suppressed late root exit, and the plain-POSIX no-sweep path.local-pty-provider-shutdown.test.tsgains an agent-sweep assertion.
The new ordering mirrors the established daemon teardown pattern (daemon/terminal-host-session-shutdown.ts uses the same terminateDescendants + awaitEscalation: true shape), stays local-only (SSH/daemon PTYs untouched), and the ~2.5s verification window sits well inside the 20s will-quit barrier. Verified locally: 72 tests across the 5 touched suites, pnpm tc, and pnpm run check:code-quality:changed all pass.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Tag detached serve-sim launches with a private instance marker and verify the live helper PID, device and marker before signaling. Refuse missing or ambiguous ownership instead of using shared state-file kill or unowned device sweeps. Keep the shared iOS simulator powered on during automatic cleanup; explicit shutdown remains available. Validation: 165 tests across 13 suites; scoped TypeScript, changed-code quality and formatting passed. Real Linux process regression with ps flag adaptation confirms same-device external helper survives. Native macOS execution remains unverified; full project typecheck remains memory-limited locally.
| const table = await execFileText('ps', ['-axo', 'pid=,command=']).catch(() => '') | ||
| const helpers = parseServeSimHelperProcesses(table).filter((helper) => | ||
| containsExactToken(helper.command, deviceUdid) |
There was a problem hiding this comment.
There was a problem hiding this comment.
ℹ️ No critical issues — one minor question inline.
Reviewed changes
Reviewed the incremental commit 24009a109a ("fix(emulator): restrict automatic cleanup to owned helpers") on top of the previously cleared 3f48601fd9, then read the full 25-file diff for context.
- Owned-only automatic cleanup —
EmulatorBridgeShutdown.destroyAllSessionsInternal,EmulatorStartLeaseRegistry.releaseActiveLease/cleanupStartedSession/drainCleanup, and managedstopActiveForWorktreenow passownedOnly: trueinstead ofincludeOrphaned: true, so a quit no longer SIGTERMs another tool's serve-sim helper or powers off a shared simulator.EmulatorHelperStopOptionsandshutdownDevice(device, { ownedOnly })carry the flag. - Per-backend launch ownership —
IosEmulatorBackendstamps each--detachwith a randomORCA_SERVE_SIM_OWNER, and the newkillOwnedServeSimHelperProcessesForDeviceSIGTERMs a PID only afterps -Ewwshows both the device UDID and that exact owner token. Verified against Apple'spssource that-Eappends the environment to thecommandfield as space-delimited tokens and that a pipedps -axouses unlimited width, so the two-stage identification can succeed. - Shutdown-time narrowing —
drainCleanupforcesownedOnlyonce the registry's shutdown flag is set, so a cleanup queued orphan-inclusive is still restricted during quit. - Coverage — new
serve-sim-owned-helper-processes.test.tsexercises PID reuse, non-exact owner/device tokens, ambiguous/malformedpsoutput, and concurrent verification; bridge/registry/backend suites were updated for the new expectations.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| stopHelperForDevice(deviceId: string, options?: EmulatorHelperStopOptions): Promise<void> | ||
| // Power off the underlying device/AVD. | ||
| shutdownDevice(deviceId: string): Promise<void> | ||
| shutdownDevice(deviceId: string, options?: { ownedOnly?: boolean }): Promise<void> |
There was a problem hiding this comment.
shutdownDevice now advertises an ownedOnly option, and every automatic cleanup path passes it — but AndroidEmulatorBackend.shutdownDevice (src/main/emulator/backends/android-emulator-backend.ts:195) declares no options parameter, so Android silently ignores the flag and still runs adb emu kill. Was leaving a shared AVD running after app quit intentionally out of scope, or should Android mirror the iOS guard?
Technical details
# Android `shutdownDevice` ignores the new `ownedOnly` flag
## Affected sites
- `src/main/emulator/backends/emulator-backend.ts:73` — declares `shutdownDevice(deviceId, options?: { ownedOnly?: boolean })`.
- `src/main/emulator/backends/ios-emulator-backend.ts:281` — honors it (early-returns before `shutdownSimulatorDevice`).
- `src/main/emulator/backends/android-emulator-backend.ts:195` — `shutdownDevice(deviceId: string)` has no `options` parameter; TypeScript accepts the narrower signature, so the flag is dropped and `adb emu kill` still runs.
- Call sites that now pass `{ ownedOnly: true }`: `emulator-bridge-shutdown.ts:64`, `emulator-start-lease-registry.ts:152` and `:177-180`.
## Required outcome
Decide whether automatic Android device shutdown should also be suppressed when `ownedOnly` is set. If yes, Android needs the same early-return as iOS; if no, a one-line comment stating that an Orca-booted AVD is deliberately still powered off would keep the interface contract honest.
## Open questions for the human
- Is an Android AVD attached by Orca (rather than booted by it) shared the way an iOS simulator is, or is powering it off on quit intentional?Keep the upstream deletion of the retired startup source-string tests. Cover pending, completed, and rejected local PTY teardown in the existing quit-handler behavior suite.
Combine the notification-dismissal and local PTY test fixtures without losing either teardown barrier's behavior coverage.
Keep ownership-safe Android cleanup, move shutdown regression into the shared runtime suite, and align quit test mocks with current teardown modules.
Preserve pane-grid flush ordering, synchronous SSH detachment and final save, and awaited local PTY teardown. Cover pending grid and PTY cleanup together. Validation: 160 tests passed with Vitest 5.0.5; changed-code quality gate and format checks passed. Full node typecheck exceeded this environment's memory limit; platform/native end-to-end behavior was not exercised.
Preserve awaited PTY cleanup and upstream runtime-fed exit events. Keep managed emulator pruning limited to its recorded owned helper.

ELI5
When Orca quit while a terminal or emulator helper was still starting, the app could stop waiting for that owned child process. This change keeps shutdown connected to the quit barrier and cleans up helpers that finish starting during shutdown, so closing Orca does not leave its work running in the background.
What Changed
nohupbehavior.Why
The quit path previously started local PTY cleanup without joining its asynchronous completion to the app teardown barrier. It also took a session snapshot before an in-flight emulator helper could register, allowing owned descendants to outlive the process that launched them. The new shutdown coordination closes both races without broad process-table reaping.
Linked Issue
Related to #11342 and #16714. This change covers local app-quit cleanup; daemon tab-close and cross-launch daemon ownership remain out of scope.
Visual Proof
N/A — no UI or interaction surface changed.
Testing
Automated verification:
pnpm tcpnpm run check:code-quality:changedpnpm test src/main/emulator/emulator-start-lease-registry.test.ts src/main/emulator/emulator-bridge.test.ts src/main/runtime/orca-runtime-emulator-folder-workspace.test.ts src/main/providers/local-pty-provider-shutdown.test.ts src/main/startup/desktop-startup-ordering.test.ts— 5 files, 80 tests passed on Windows.pnpm testwas attempted, but the full suite was not clean in this Windows environment because of unrelated WSL/App Control/native-module/symlink-dependent failures and timeouts; it is not claimed as passing here.AI Disclosure
OpenAI Codex (GPT-5) implemented the change. Claude performed an independent review of the shutdown paths.
Review
nohupsemantics, and adds no shell or interpreter spawning.Promise.allSettledcoordination rather than adding hot-path polling.Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
No UI, SSH wire, Git provider, or shortcut behavior changed. The implementation keeps remote process ownership on the execution host and limits app-quit cleanup to locally owned resources.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)