Repository navigation
fix(runtime): harden watcher and PTY teardown ownership - #8661
Conversation
…on-safety-followup
|
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:
📝 WalkthroughWalkthroughThe pull request reworks watcher and PTY lifecycle management around shared capacity limits, cancellation tracking, physical-exit confirmation, retryable teardown, and removal fencing. It adds runtime and relay watcher coordination, updates local, WSL, SSH, and filesystem watcher behavior, makes PTY and terminal shutdown asynchronous, strengthens worktree deletion preflight and cleanup ordering, refactors file-watch RPC and renderer replay handling, and expands reliability-gate evidence with a resource probe and additional test coverage. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
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: 7
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (5)
src/relay/relay-filesystem-watch-registry.ts (1)
275-298: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winNon-
Errorrejections are silently swallowed instead of propagating.
if (!expectedAbort && error instanceof Error) { ...; throw error }only rethrows when the rejection is anErrorinstance. Any non-Errorthrow that isn't an expected abort falls through toreturn, making a failed setup look successful to the caller.🐛 Propagate unexpected non-Error rejections too
- const expectedAbort = - (error instanceof Error && error.name === 'AbortError') || - (isWatcherProcessFailure(error) && error.code === 'subscribe_aborted') - if (!expectedAbort && error instanceof Error) { - process.stderr.write( - `[relay] File watcher not available for ${state.rootPath}: ${error.message}\n` - ) - throw error - } - return + const expectedAbort = + (error instanceof Error && error.name === 'AbortError') || + (isWatcherProcessFailure(error) && error.code === 'subscribe_aborted') + if (expectedAbort) { + return + } + const message = error instanceof Error ? error.message : String(error) + process.stderr.write(`[relay] File watcher not available for ${state.rootPath}: ${message}\n`) + throw errorsrc/main/daemon/daemon-server.ts (1)
149-174: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winGuard
this.host.dispose()so shutdown always continuesBoth
shutdown()and theshutdownRPC path awaitthis.host.dispose()directly. SinceTerminalHost.dispose()can reject,shutdown()can stop before closing the server and clearing client sockets, and thekillSessionsbranch can skip schedulingthis.shutdown(). Wrap the dispose call so cleanup and shutdown still run.src/main/ipc/parcel-watcher-process-entry.ts (1)
244-260: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winHandle
unsubscribe-failedon the host sideThis adds a new wire message and stops sending
unsubscribedon failure, so the host must recognizeunsubscribe-failedand settle the pending unsubscribe; otherwise callers can hang indefinitely.src/main/ipc/runtime-watcher-process-pool.ts (1)
58-69: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winRelease the acquired assignment if the post-await active check fails. If
dispose()wins the race afterassignmentForRoot()resolves,assertActive()throws and the lease stays attached to the slot becausereleaseRoot()never runs. Wrap that check, release the assignment, then rethrow.src/relay/pty-handler.ts (1)
1163-1189: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
revive()aborts all remaining entries ifbeginPtyCreationthrows for one.Unlike the
process.kill(entry.pid, 0)liveness check just above it (wrapped in try/catch +continue), thebeginPtyCreationcall here is unguarded. If it throws for one entry — hittingMAX_RELAY_PTY_SESSIONS, a worktree-removal fence conflict, orcreationFencedduring shutdown — the exception propagates out of the loop and every subsequent serialized entry is skipped, even though its backing process may still be alive and otherwise revivable.disposePtyselsewhere in this file deliberately usesPromise.allSettledto avoid exactly this "one failure blocks the rest" pattern; the revive loop should follow the same discipline.🐛 Proposed fix: don't let one entry's admission failure abort the rest
const ownedPath = entry.worktreeId ? splitWorktreeId(entry.worktreeId)?.worktreePath : undefined - const finishCreation = this.beginPtyCreation([ownedPath, entry.cwd]) + let finishCreation: () => void + try { + finishCreation = this.beginPtyCreation([ownedPath, entry.cwd]) + } catch { + continue + } this.pendingReviveIds.add(entry.id) try { await this.reviveEntry(entry) } finally { this.pendingReviveIds.delete(entry.id) finishCreation() }
🧹 Nitpick comments (6)
src/main/runtime/runtime-root-watch-ownership.ts (1)
33-38: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winPrevent potential unhandled promise rejections.
If the
physicalExitpromise rejects (for instance, if tracking the physical process exit fails for any reason), the unhandled rejection could crash the Node.js process. Additionally, if tracking fails, you likely still want to release the root rather than holding it indefinitely.♻️ Proposed fix
- void error.physicalExit.then(() => { - if (root.terminalReleaseError === error) { - root.terminalReleaseError = null - release(root) - } - }) + void error.physicalExit + .catch(() => {}) + .then(() => { + if (root.terminalReleaseError === error) { + root.terminalReleaseError = null + release(root) + } + })src/main/ipc/worktrees.ts (1)
1519-1534: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the repeated watcher-removal-gate boilerplate.
The acquire-gate → try/finally(
removalCompleted) →stopPtysForDestructiveWorktreeRemovalpattern is repeated near-verbatim 5 times in this file. A small helper would reduce duplication and the risk of a future call site missing a step.Example helper (place near
stopPtysForDestructiveWorktreeRemoval, outside the selected ranges):async function withFileWatcherRemovalGate<T>( runtime: OrcaRuntimeService, worktreePath: string, connectionId: string | undefined, fn: () => Promise<T> ): Promise<T> { const removalGate = await runtime.acquireFileWatcherRemoval(worktreePath, connectionId) let removalCompleted = false try { const result = await fn() removalCompleted = true return result } finally { await removalGate.finish(removalCompleted) } }♻️ Example call-site simplification (lines 1519-1534)
- const removalGate = await runtime.acquireFileWatcherRemoval( - worktreePath, - repo.connectionId - ) - let removalCompleted = false - try { - await stopPtysForDestructiveWorktreeRemoval( - runtime, - args.worktreeId, - repo.connectionId - ) - await fsProvider!.deletePath(worktreePath, true) - removalCompleted = true - } finally { - await removalGate.finish(removalCompleted) - } + await withFileWatcherRemovalGate(runtime, worktreePath, repo.connectionId, async () => { + await stopPtysForDestructiveWorktreeRemoval(runtime, args.worktreeId, repo.connectionId) + await fsProvider!.deletePath(worktreePath, true) + })The same simplification applies to the other four sites.
Also applies to: 1543-1551, 1588-1596, 1731-1745, 1819-1920
src/relay/relay-watcher-terminal-notifier.ts (1)
3-7: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate type instead of reusing
RelayWatcherTeardownState.
RelayTerminalWatchOwnersre-declaresrootPath/clients/clientWatchIdsthat already exist onRelayWatcherTeardownState(relay-watcher-teardown-tracker.ts). If that shape changes, this type won't be forced to follow.♻️ Reuse via Pick
-type RelayTerminalWatchOwners = { - rootPath: string - clients: Map<number, () => boolean> - clientWatchIds: Map<number, number> -} +import type { RelayWatcherTeardownState } from './relay-watcher-teardown-tracker' + +type RelayTerminalWatchOwners = Pick< + RelayWatcherTeardownState, + 'rootPath' | 'clients' | 'clientWatchIds' +>src/main/ipc/parcel-watcher-supervisor-capacity-wait.test.ts (1)
9-35: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider adding coverage for
run()anddispose().This suite only exercises
wait()/cancellation.run()(capacity-error retry wrapping) anddispose()(lifecycle invalidation of in-flight waits) are the other two public surfaces ofWatcherSupervisorCapacityWaitand currently have no dedicated test here.src/main/ipc/parcel-watcher-disconnect-termination.test.ts (1)
1-52: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicates the shared fake-child helper introduced in this PR.
This file re-implements
FakeChild,currentChild(), andackSubscribe()locally instead of importingFakeWatcherChild,currentWatcherChild, andacknowledgeWatcherSubscribefrom the new./parcel-watcher-process-test-childhelper, which the three sibling suites in this same PR (parcel-watcher-supervisor-capacity.test.ts,parcel-watcher-unsubscribe-timeout.test.ts,parcel-watcher-process.test.ts) all consume. The local copy has already drifted (nopid, and itsSentMessagetype omitsdir).♻️ Proposed fix to consume the shared helper
-import { EventEmitter } from 'node:events' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { WATCHER_PROCESS_CANCEL_TIMEOUT_MS } from './parcel-watcher-cancellation-tracker' import { WATCHER_PROCESS_EXIT_DEADLINE_MS } from './parcel-watcher-child-termination' +import { + acknowledgeWatcherSubscribe as ackSubscribe, + currentWatcherChild, + FakeWatcherChild as FakeChild +} from './parcel-watcher-process-test-child' const { existsSyncMock, forkMock, mkdtempSyncMock, rmSyncMock } = vi.hoisted(() => ({ existsSyncMock: vi.fn(), forkMock: vi.fn(), mkdtempSyncMock: vi.fn(() => '/tmp/orca-watcher-disconnect-test'), rmSyncMock: vi.fn() })) vi.mock('node:child_process', () => ({ fork: forkMock })) vi.mock('node:fs', () => ({ existsSync: existsSyncMock, mkdtempSync: mkdtempSyncMock, rmSync: rmSyncMock })) import { createWatcherProcessSupervisor, disposeWatcherProcess, resetWatcherProcessForTest, subscribeViaWatcherProcess } from './parcel-watcher-process' import type { WatcherProcessSubscription } from './parcel-watcher-process-subscription' -type SentMessage = { op: string; id: number } - -class FakeChild extends EventEmitter { - connected = true - exitCode: number | null = null - signalCode: NodeJS.Signals | null = null - sent: SentMessage[] = [] - stderr = new EventEmitter() - kill = vi.fn(() => { - this.connected = false - }) - send = vi.fn((message: SentMessage) => { - this.sent.push(message) - return true - }) -} - -function currentChild(): FakeChild { - return forkMock.mock.results.at(-1)?.value as FakeChild -} - -function ackSubscribe(child: FakeChild): void { - const message = child.sent.findLast((candidate) => candidate.op === 'subscribe') - child.emit('message', { op: 'subscribed', id: message?.id }) -} +const currentChild = (): FakeChild => currentWatcherChild(forkMock)config/scripts/runtime-file-watcher-resource-probe.mjs (1)
14-21: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDerive the physical-child cap from the registry instead of duplicating it.
PHYSICAL_CHILD_CAP = 8and the hardcoded7/4reservation counts passed toassertRegistryCapacityare independent of the realMAX_PHYSICAL_WATCHER_CHILDRENconstant this script already bundles fromparcel-watcher-child-registry.ts. If that constant ever changes, this probe silently drifts out of sync with the invariant it's meant to enforce.♻️ Proposed fix to import the real cap
const { RuntimeWatcherProcessPool, WatcherProcessFailure, reserveWatcherChild } = - await loadProbe(bundleDir) + var { MAX_PHYSICAL_WATCHER_CHILDREN } // add to destructure belowcontents: [ `export { RuntimeWatcherProcessPool } from ${JSON.stringify(POOL_SOURCE)}`, `export { WatcherProcessFailure } from ${JSON.stringify(FAILURE_SOURCE)}`, - `export { reserveWatcherChild } from ${JSON.stringify(REGISTRY_SOURCE)}` + `export { reserveWatcherChild, MAX_PHYSICAL_WATCHER_CHILDREN } from ${JSON.stringify(REGISTRY_SOURCE)}` ].join('\n'),Then destructure
MAX_PHYSICAL_WATCHER_CHILDRENfromloadProbe(bundleDir)and use it in place of the localPHYSICAL_CHILD_CAPconstant and the7/4call-site literals (e.g.MAX_PHYSICAL_WATCHER_CHILDREN - 1/MAX_PHYSICAL_WATCHER_CHILDREN - 4).Also applies to: 35-36, 54-54, 80-80, 115-118
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro
Run ID: 592186e1-58b8-4c4a-a54d-5ed23bde4ad7
📒 Files selected for processing (140)
config/reliability-gates.jsoncconfig/scripts/runtime-file-watcher-resource-probe.mjssrc/main/daemon/daemon-main.test.tssrc/main/daemon/daemon-pty-adapter.test.tssrc/main/daemon/daemon-pty-adapter.tssrc/main/daemon/daemon-pty-provider.test.tssrc/main/daemon/daemon-server.test.tssrc/main/daemon/daemon-server.tssrc/main/daemon/daemon-spawner.test.tssrc/main/daemon/pty-subprocess.test.tssrc/main/daemon/pty-subprocess.tssrc/main/daemon/session.test.tssrc/main/daemon/session.tssrc/main/daemon/slow-daemon-session-verification.test.tssrc/main/daemon/terminal-host-session-reaping-leak.test.tssrc/main/daemon/terminal-host-session-shutdown.tssrc/main/daemon/terminal-host.test.tssrc/main/daemon/terminal-host.tssrc/main/git/remove-worktree.test.tssrc/main/git/worktree.tssrc/main/index.tssrc/main/ipc/filesystem-watcher-local-unsubscribe.test.tssrc/main/ipc/filesystem-watcher-native-capacity.test.tssrc/main/ipc/filesystem-watcher-wsl.test.tssrc/main/ipc/filesystem-watcher-wsl.tssrc/main/ipc/filesystem-watcher.test.tssrc/main/ipc/filesystem-watcher.tssrc/main/ipc/parcel-watcher-cancellation-restart.tssrc/main/ipc/parcel-watcher-cancellation-tracker.tssrc/main/ipc/parcel-watcher-child-launch.test.tssrc/main/ipc/parcel-watcher-child-launch.tssrc/main/ipc/parcel-watcher-child-messaging.tssrc/main/ipc/parcel-watcher-child-recovery.tssrc/main/ipc/parcel-watcher-child-registry.test.tssrc/main/ipc/parcel-watcher-child-registry.tssrc/main/ipc/parcel-watcher-child-termination.tssrc/main/ipc/parcel-watcher-disconnect-termination.test.tssrc/main/ipc/parcel-watcher-entry-path.test.tssrc/main/ipc/parcel-watcher-entry-path.tssrc/main/ipc/parcel-watcher-host-subscriptions.tssrc/main/ipc/parcel-watcher-interrupted-cancellation.tssrc/main/ipc/parcel-watcher-pending-cancellation.tssrc/main/ipc/parcel-watcher-pending-subscribe.tssrc/main/ipc/parcel-watcher-process-entry.test.tssrc/main/ipc/parcel-watcher-process-entry.tssrc/main/ipc/parcel-watcher-process-failure.tssrc/main/ipc/parcel-watcher-process-protocol.tssrc/main/ipc/parcel-watcher-process-supervisor.tssrc/main/ipc/parcel-watcher-process-test-child.tssrc/main/ipc/parcel-watcher-process.test.tssrc/main/ipc/parcel-watcher-process.tssrc/main/ipc/parcel-watcher-supervisor-capacity-wait.test.tssrc/main/ipc/parcel-watcher-supervisor-capacity-wait.tssrc/main/ipc/parcel-watcher-supervisor-capacity.test.tssrc/main/ipc/parcel-watcher-supervisor-disposal.tssrc/main/ipc/parcel-watcher-supervisor-message.tssrc/main/ipc/parcel-watcher-supervisor-subscribe.tssrc/main/ipc/parcel-watcher-unsubscribe-timeout.test.tssrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/main/ipc/runtime-watcher-pending-assignment.test.tssrc/main/ipc/runtime-watcher-pending-assignment.tssrc/main/ipc/runtime-watcher-pool-lifecycle.tssrc/main/ipc/runtime-watcher-pool-state.tssrc/main/ipc/runtime-watcher-predecessor-barriers.tssrc/main/ipc/runtime-watcher-process-pool.test.tssrc/main/ipc/runtime-watcher-process-pool.tssrc/main/ipc/runtime-watcher-quarantine-queue.tssrc/main/ipc/runtime-watcher-subscription-failure.tssrc/main/ipc/watcher-removal-gate.test.tssrc/main/ipc/watcher-removal-gate.tssrc/main/ipc/worktree-symlinks.test.tssrc/main/ipc/worktree-symlinks.tssrc/main/ipc/worktrees-windows.test.tssrc/main/ipc/worktrees.test.tssrc/main/ipc/worktrees.tssrc/main/ipc/wsl-watcher-process-exit.tssrc/main/local-worktree-removal-recovery.test.tssrc/main/local-worktree-removal-recovery.tssrc/main/providers/local-pty-provider.test.tssrc/main/providers/local-pty-provider.tssrc/main/providers/ssh-filesystem-provider-watch-waiters.test.tssrc/main/providers/ssh-filesystem-provider-watch.tssrc/main/providers/ssh-filesystem-provider.test.tssrc/main/providers/ssh-filesystem-provider.tssrc/main/providers/ssh-filesystem-watch-notifications.tssrc/main/providers/ssh-pty-provider.test.tssrc/main/providers/types.tssrc/main/runtime/file-watcher-host.test.tssrc/main/runtime/file-watcher-host.tssrc/main/runtime/orca-runtime-files-watch.test.tssrc/main/runtime/orca-runtime-files.test.tssrc/main/runtime/orca-runtime-files.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/file-watch-stream-lifecycle.tssrc/main/runtime/rpc/methods/files-watch-cancellation.test.tssrc/main/runtime/rpc/methods/files-watch-cleanup.test.tssrc/main/runtime/rpc/methods/files.test.tssrc/main/runtime/rpc/methods/files.tssrc/main/runtime/runtime-root-watch-ownership.tssrc/main/runtime/runtime-root-watch-teardown.tssrc/main/runtime/worktree-teardown.test.tssrc/main/runtime/worktree-teardown.tssrc/relay/dispatcher.test.tssrc/relay/dispatcher.tssrc/relay/fs-handler.test.tssrc/relay/fs-handler.tssrc/relay/git-handler.test.tssrc/relay/git-handler.tssrc/relay/pty-handler.test.tssrc/relay/pty-handler.tssrc/relay/relay-filesystem-watch-registry.test.tssrc/relay/relay-filesystem-watch-registry.tssrc/relay/relay-watcher-event-emitter.tssrc/relay/relay-watcher-parent-removal.test.tssrc/relay/relay-watcher-pending-setup-join.tssrc/relay/relay-watcher-pending-setup-waiters.test.tssrc/relay/relay-watcher-removal-fence.tssrc/relay/relay-watcher-root-capacity.tssrc/relay/relay-watcher-setup-tracking.tssrc/relay/relay-watcher-setup-wait.test.tssrc/relay/relay-watcher-setup-wait.tssrc/relay/relay-watcher-stale-client-release.tssrc/relay/relay-watcher-state.tssrc/relay/relay-watcher-teardown-tracker.tssrc/relay/relay-watcher-terminal-notifier.tssrc/relay/relay.tssrc/relay/subprocess.test.tssrc/renderer/src/runtime/runtime-file-client.test.tssrc/renderer/src/runtime/runtime-file-client.tssrc/renderer/src/web/web-runtime-client.test.tssrc/renderer/src/web/web-runtime-client.tssrc/shared/cross-platform-path.test.tssrc/shared/cross-platform-path.tssrc/shared/physical-exit-tracker.test.tssrc/shared/physical-exit-tracker.tssrc/shared/promise-settlement-waiters.test.tssrc/shared/promise-settlement-waiters.tssrc/shared/runtime-file-watch-limits.ts
👮 Files not reviewed due to content moderation or server errors (8)
- src/main/ipc/runtime-watcher-quarantine-queue.ts
- src/main/index.ts
- src/main/ipc/worktrees-windows.test.ts
- src/main/ipc/watcher-removal-gate.test.ts
- src/renderer/src/runtime/runtime-file-client.ts
- src/main/ipc/filesystem-watcher-local-unsubscribe.test.ts
- src/main/ipc/worktrees.test.ts
- src/main/ipc/filesystem-watcher.ts
| import { isWatcherProcessFailure } from '../main/ipc/parcel-watcher-process-failure' | ||
| import type { PromiseSettlementWaiters } from '../shared/promise-settlement-waiters' | ||
|
|
||
| export function shouldRetryInitialRelayWatch(error: unknown): boolean { | ||
| return ( | ||
| isWatcherProcessFailure(error) && | ||
| error.code !== 'entry_missing' && | ||
| error.code !== 'subscribe_aborted' && | ||
| error.code !== 'supervisor_disposed' && | ||
| (error.scope === 'supervisor' || error.code === 'subscribe_timeout') | ||
| ) | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win
Avoid importing main app bundle modules from relay code.
As per learnings, src/relay is bundled separately for remote deployment. Importing isWatcherProcessFailure from src/main will leak app-bundle references into the relay compilation graph and break the separate remote bundle. Please remove the import and implement a local type check in src/relay instead.
♻️ Proposed fix
-import { isWatcherProcessFailure } from '../main/ipc/parcel-watcher-process-failure'
import type { PromiseSettlementWaiters } from '../shared/promise-settlement-waiters'
export function shouldRetryInitialRelayWatch(error: unknown): boolean {
+ const isWatcherFailure = error instanceof Error && error.name === 'WatcherProcessFailure'
+ if (!isWatcherFailure) {
+ return false
+ }
+ const err = error as any
return (
- isWatcherProcessFailure(error) &&
- error.code !== 'entry_missing' &&
- error.code !== 'subscribe_aborted' &&
- error.code !== 'supervisor_disposed' &&
- (error.scope === 'supervisor' || error.code === 'subscribe_timeout')
+ err.code !== 'entry_missing' &&
+ err.code !== 'subscribe_aborted' &&
+ err.code !== 'supervisor_disposed' &&
+ (err.scope === 'supervisor' || err.code === 'subscribe_timeout')
)
}📝 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.
| import { isWatcherProcessFailure } from '../main/ipc/parcel-watcher-process-failure' | |
| import type { PromiseSettlementWaiters } from '../shared/promise-settlement-waiters' | |
| export function shouldRetryInitialRelayWatch(error: unknown): boolean { | |
| return ( | |
| isWatcherProcessFailure(error) && | |
| error.code !== 'entry_missing' && | |
| error.code !== 'subscribe_aborted' && | |
| error.code !== 'supervisor_disposed' && | |
| (error.scope === 'supervisor' || error.code === 'subscribe_timeout') | |
| ) | |
| } | |
| import type { PromiseSettlementWaiters } from '../shared/promise-settlement-waiters' | |
| export function shouldRetryInitialRelayWatch(error: unknown): boolean { | |
| const isWatcherFailure = error instanceof Error && error.name === 'WatcherProcessFailure' | |
| if (!isWatcherFailure) { | |
| return false | |
| } | |
| const err = error as any | |
| return ( | |
| err.code !== 'entry_missing' && | |
| err.code !== 'subscribe_aborted' && | |
| err.code !== 'supervisor_disposed' && | |
| (err.scope === 'supervisor' || err.code === 'subscribe_timeout') | |
| ) | |
| } |
Source: Learnings
A rejecting host.dispose() (unreapable child past its exit deadline) left the shutdown RPC without its process.nextTick(shutdown) and skipped socket cleanup in shutdown(), stranding the daemon as an unreachable orphan after the stale-daemon replacement flow unlinks its socket. Log and continue: daemon exit reparents the child to init instead of blocking on it.
An idle child that outlived the exit deadline set shutdownRequested on the shared desktop supervisor, which has no retire-and-replace path — every later subscribe rejected supervisor_disposed and the roots were cached unwatchable, silently ending local file watching for the session. The idle path owns zero records, so there is no double-watch hazard; the zombie keeps its capacity reservation until physical exit and the next subscribe gets a fresh child.
Transparent replay removed the implicit resync the old close-and-rebuild path provided: a replayed files.watch only reports changes from its own native setup, so changes during the reconnect gap were silently lost. Deliver a conservative overflow to consumers once the replayed watch is ready, matching the overflow-after-interruption contract everywhere else.
…on-safety-followup # Conflicts: # src/main/providers/local-pty-provider.ts # src/relay/pty-handler.test.ts # src/relay/pty-handler.ts
…on-safety-followup
…on-safety-followup
…on-safety-followup # Conflicts: # src/main/daemon/session.test.ts # src/main/daemon/session.ts # src/main/daemon/terminal-host.ts # src/main/providers/local-pty-provider.ts # src/main/runtime/worktree-teardown.ts
Only conflict was the import list in src/main/runtime/orca-runtime-files.ts: main's stablyai#8661 (watcher/PTY teardown hardening) added beginWatcherInstall while this branch added the native-chat mobile file-path search imports at the same spot. Kept both — both are used in the merged body (beginWatcherInstall at the watcher-install gate, the mobile search cache/rank in the file-list path). typecheck:node/web + mobile tsc clean; runtime-files tests 85/85.
* fix(runtime): retain watcher and PTY teardown ownership * fix(runtime): restore watchers after interrupted cleanup * fix(runtime): prevent stale watcher revival * test(runtime): cover watcher shutdown ownership * test(daemon): model physical PTY exit * fix(daemon): keep shutdown terminating when disposal cannot prove exit A rejecting host.dispose() (unreapable child past its exit deadline) left the shutdown RPC without its process.nextTick(shutdown) and skipped socket cleanup in shutdown(), stranding the daemon as an unreachable orphan after the stale-daemon replacement flow unlinks its socket. Log and continue: daemon exit reparents the child to init instead of blocking on it. * fix(runtime): keep local watching alive after an idle-kill deadline miss An idle child that outlived the exit deadline set shutdownRequested on the shared desktop supervisor, which has no retire-and-replace path — every later subscribe rejected supervisor_disposed and the roots were cached unwatchable, silently ending local file watching for the session. The idle path owns zero records, so there is no double-watch hazard; the zombie keeps its capacity reservation until physical exit and the next subscribe gets a fresh child. * fix(renderer): resync replayed paired-web file watches Transparent replay removed the implicit resync the old close-and-rebuild path provided: a replayed files.watch only reports changes from its own native setup, so changes during the reconnect gap were silently lost. Deliver a conservative overflow to consumers once the replayed watch is ready, matching the overflow-after-interruption contract everywhere else. * fix(runtime): address teardown review findings * fix(runtime): retry watches after teardown deadlines * Fix PTY descendant leaks on forced teardown * Fix jitter-sensitive terminal lifecycle test
Summary
ELI5
Orca watches your project folders so the UI can react when files change. That watcher leans on fragile native OS code that can crash under heavy load — and before #8370, a watcher crash took down all of
orca serve(issue #8212). #8370 moved the watcher into small disposable helper processes, so a crash only kills a helper and Orca hires a new one.This PR fixes the firing side of that system. Before, when Orca was done with a helper (or a terminal process), it sometimes just assumed the process was gone. If it was actually stuck, Orca could delete a worktree folder something still had open, lose track of who owned the cleanup, or silently drop a file watch and never bring it back. Now:
Why the diff is big: about half of it is tests (+7k lines) pinning down the crash/timeout races so they can't regress, plus ~800 lines of CI reliability gates. The rest is the same "wait for proof of death" rule applied consistently to every place Orca runs processes — desktop, serve, SSH relay, WSL, the terminal daemon, and paired web clients.
Why this matters — the user problems this fixes
Current main (with #8370) stopped watcher crashes from killing
orca serve. But teardown — everything that happens when a worktree is deleted, a tab is closed, a connection drops, or a stuck process is killed — remained assume-it-worked. Each assumption below is a user-visible failure that exists on main today; every mechanism was verified during review.1. Deleting a busy worktree can fail, or leave the crash window open.
Teardown was best-effort: watcher children and PTYs could outlive the folder they hold handles into. Delete a worktree while agents are writing and (a) on Windows the deletion intermittently fails with "directory in use", and (b) on macOS/Linux native FSEvents teardown runs against a vanishing directory — the same crash-prone native path behind #8212's SIGSEGVs, just moved to deletion time. Now: destructive removal is fail-closed everywhere (desktop, serve, SSH, WSL): Orca proves every process and watch is physically gone — bounded SIGTERM → SIGKILL at 5s → 10s deadline — and refuses with a retryable error instead of gambling with the folder.
2. Terminal teardown can still declare success before the process is actually gone.
Main already protects against the known node-pty SIGHUP-to-recycled-PID hazard and several double-close and SIGKILL races (#1327, #1454, #8140). However, some local, daemon, and relay shutdown paths still treat a kill request—or even a rejected kill—as proof of exit, then discard the PTY/session owner before the OS reports
onExit. A wedged agent can therefore survive untracked, consuming CPU, battery, and API tokens, while worktree deletion races a still-live process. Now: teardown retains the same PTY/session record and physical-exit tracker until OS-confirmed exit, uses bounded escalation and retry, and fails closed before destructive removal. Later retries rejoin that retained owner, while the existing post-exit recycled-PID protections remain intact.3. File watches silently die; git status and the file tree freeze until restart.
A failed deletion, a dropped SSH connection, or crash recovery could leave a workspace with no watch and no error — the sidebar just stops updating and only an app restart heals it. Now: interrupted cleanup restores exactly the watches that should exist (never ones you explicitly closed), and every recovery path emits an overflow so the UI re-scans instead of trusting a gap.
4. Paired phone/browser clients show stale state after reconnecting.
Mobile connections flap constantly (NAT idle timeouts, wifi↔cellular handoff). Changes that land during the gap produce no events, so the remote client's git status and file tree stay stale until some unrelated change nudges them. Now: active watches are replayed on reconnect and followed by a conservative re-scan signal covering the whole gap.
5. A native-fault storm could pile up helper processes.
Crash/replace cycles could accumulate watcher children beyond the intended pools, with slots freed on assumption rather than proof. Now: a hard global cap of 8 physical watcher children, with each slot held until the OS confirms the old child is gone — a bad day degrades politely instead of leaking processes.
The common thread: #8370 made watcher crashes survivable; this PR makes their cleanup honest. Every "assume it worked" in teardown became "prove it or fail closed" — because each assumption was a window for exactly the stuck-state and native-crash class that #8212 reported from production.
Scope
This is a runtime reliability follow-up only. It introduces no UI or product-flow changes and does not merge or close the already completed issue.
Validation
Known gaps
Live validation was on macOS arm64. Linux, Windows, WSL, live SSH, packaged paired-web fault injection, and sustained six-writer soak remain platform or environment coverage gaps; deterministic cross-platform contracts and production bundles passed.
Related: #8212