Skip to content

fix(runtime): harden watcher and PTY teardown ownership - #8661

Merged
brennanb2025 merged 17 commits into
mainfrom
fix/watcher-termination-safety-followup
Jul 15, 2026
Merged

brennanb2025 merged 17 commits into
mainfrom
fix/watcher-termination-safety-followup

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Follow up fix(runtime): prevent file watcher SIGSEGV from crashing orca serve #8370 by retaining watcher and PTY cleanup ownership until native processes and handles physically exit, with bounded termination and an eight-child global watcher cap.
  • Restore local, SSH, runtime, and paired-web watches after interrupted cleanup or failed worktree deletion while ensuring explicitly stopped or destroyed listeners never revive.
  • Replay active paired-web file watches across reconnects, evict terminal setup failures before synchronous retry, and preserve conservative overflow refresh after interruption.
  • Keep destructive worktree removal fail-closed across desktop, serve, SSH/relay, WSL, and terminal/session teardown paths.

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:

  • Nothing is assumed dead until the OS confirms it. Orca asks a process to exit, force-kills it after 5 seconds, and waits up to 10 seconds for proof. If proof never comes, the error remembers the process so a later retry can pick up where it left off.
  • Worktree deletion fails closed. If Orca can't prove every process and watch touching a folder is gone, it refuses to delete rather than risk deleting under a live handle — on desktop, headless serve, SSH, WSL, everywhere.
  • Interrupted cleanup heals itself. If a deletion fails or a connection drops mid-teardown, the watches you still need come back — but anything you explicitly closed stays closed.
  • A bad day can't fork-bomb your machine. At most 8 watcher helpers can ever exist at once, even while crashing and replacing them.
  • Phone/browser clients don't miss changes while offline. On reconnect their file watches are replayed, plus a "re-check everything" nudge covering whatever changed during the gap.

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

  • 39 watcher/session/PTY files: 2,051 tests passed.
  • Relay/package gate: 233 tests passed.
  • Typecheck, changed-file oxlint, reliability manifest, max-lines ratchet, and production Electron build passed.
  • Relay production builds passed for Linux, macOS, Windows x64/arm64, and WSL.
  • Node and Electron-as-Node SIGSEGV harnesses kept the host alive, replaced and resubscribed the watcher child, and delivered a post-crash event.
  • Relay SIGSEGV harness preserved the relay PID and existing PTY, emitted overflow, and delivered a post-crash event.
  • Resource probe: one healthy child at 50,528 KiB RSS / 7.1% CPU; four quarantine children at 201,904 KiB / 27.2% CPU; physical cap 8; exact-PID cleanup true.
  • Two independent scoped correctness reviewers and one scoped performance reviewer returned clean on the pushed head.

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

@coderabbitai

coderabbitai Bot commented Jul 14, 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 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.94% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description omits most required template sections, including Screenshots, Testing, AI Review Report, Security Audit, and Notes. Add the missing template sections, including a testing checklist, screenshots or No visual change, cross-platform AI review notes, a security audit summary, and notes.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title is concise and accurately summarizes the main teardown-hardening change.

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: 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 win

Non-Error rejections are silently swallowed instead of propagating.

if (!expectedAbort && error instanceof Error) { ...; throw error } only rethrows when the rejection is an Error instance. Any non-Error throw that isn't an expected abort falls through to return, 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 error
src/main/daemon/daemon-server.ts (1)

149-174: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard this.host.dispose() so shutdown always continues

Both shutdown() and the shutdown RPC path await this.host.dispose() directly. Since TerminalHost.dispose() can reject, shutdown() can stop before closing the server and clearing client sockets, and the killSessions branch can skip scheduling this.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 win

Handle unsubscribe-failed on the host side

This adds a new wire message and stops sending unsubscribed on failure, so the host must recognize unsubscribe-failed and settle the pending unsubscribe; otherwise callers can hang indefinitely.

src/main/ipc/runtime-watcher-process-pool.ts (1)

58-69: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Release the acquired assignment if the post-await active check fails. If dispose() wins the race after assignmentForRoot() resolves, assertActive() throws and the lease stays attached to the slot because releaseRoot() 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 if beginPtyCreation throws for one.

Unlike the process.kill(entry.pid, 0) liveness check just above it (wrapped in try/catch + continue), the beginPtyCreation call here is unguarded. If it throws for one entry — hitting MAX_RELAY_PTY_SESSIONS, a worktree-removal fence conflict, or creationFenced during 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. disposePtys elsewhere in this file deliberately uses Promise.allSettled to 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 win

Prevent potential unhandled promise rejections.

If the physicalExit promise 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 win

Extract the repeated watcher-removal-gate boilerplate.

The acquire-gate → try/finally(removalCompleted) → stopPtysForDestructiveWorktreeRemoval pattern 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 win

Duplicate type instead of reusing RelayWatcherTeardownState.

RelayTerminalWatchOwners re-declares rootPath/clients/clientWatchIds that already exist on RelayWatcherTeardownState (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 win

Consider adding coverage for run() and dispose().

This suite only exercises wait()/cancellation. run() (capacity-error retry wrapping) and dispose() (lifecycle invalidation of in-flight waits) are the other two public surfaces of WatcherSupervisorCapacityWait and currently have no dedicated test here.

src/main/ipc/parcel-watcher-disconnect-termination.test.ts (1)

1-52: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicates the shared fake-child helper introduced in this PR.

This file re-implements FakeChild, currentChild(), and ackSubscribe() locally instead of importing FakeWatcherChild, currentWatcherChild, and acknowledgeWatcherSubscribe from the new ./parcel-watcher-process-test-child helper, 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 (no pid, and its SentMessage type omits dir).

♻️ 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 win

Derive the physical-child cap from the registry instead of duplicating it.

PHYSICAL_CHILD_CAP = 8 and the hardcoded 7/4 reservation counts passed to assertRegistryCapacity are independent of the real MAX_PHYSICAL_WATCHER_CHILDREN constant this script already bundles from parcel-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 below
       contents: [
         `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_CHILDREN from loadProbe(bundleDir) and use it in place of the local PHYSICAL_CHILD_CAP constant and the 7/4 call-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

📥 Commits

Reviewing files that changed from the base of the PR and between 5a3e4b4 and a97e3cd.

📒 Files selected for processing (140)
  • config/reliability-gates.jsonc
  • config/scripts/runtime-file-watcher-resource-probe.mjs
  • src/main/daemon/daemon-main.test.ts
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-pty-provider.test.ts
  • src/main/daemon/daemon-server.test.ts
  • src/main/daemon/daemon-server.ts
  • src/main/daemon/daemon-spawner.test.ts
  • src/main/daemon/pty-subprocess.test.ts
  • src/main/daemon/pty-subprocess.ts
  • src/main/daemon/session.test.ts
  • src/main/daemon/session.ts
  • src/main/daemon/slow-daemon-session-verification.test.ts
  • src/main/daemon/terminal-host-session-reaping-leak.test.ts
  • src/main/daemon/terminal-host-session-shutdown.ts
  • src/main/daemon/terminal-host.test.ts
  • src/main/daemon/terminal-host.ts
  • src/main/git/remove-worktree.test.ts
  • src/main/git/worktree.ts
  • src/main/index.ts
  • src/main/ipc/filesystem-watcher-local-unsubscribe.test.ts
  • src/main/ipc/filesystem-watcher-native-capacity.test.ts
  • src/main/ipc/filesystem-watcher-wsl.test.ts
  • src/main/ipc/filesystem-watcher-wsl.ts
  • src/main/ipc/filesystem-watcher.test.ts
  • src/main/ipc/filesystem-watcher.ts
  • src/main/ipc/parcel-watcher-cancellation-restart.ts
  • src/main/ipc/parcel-watcher-cancellation-tracker.ts
  • src/main/ipc/parcel-watcher-child-launch.test.ts
  • src/main/ipc/parcel-watcher-child-launch.ts
  • src/main/ipc/parcel-watcher-child-messaging.ts
  • src/main/ipc/parcel-watcher-child-recovery.ts
  • src/main/ipc/parcel-watcher-child-registry.test.ts
  • src/main/ipc/parcel-watcher-child-registry.ts
  • src/main/ipc/parcel-watcher-child-termination.ts
  • src/main/ipc/parcel-watcher-disconnect-termination.test.ts
  • src/main/ipc/parcel-watcher-entry-path.test.ts
  • src/main/ipc/parcel-watcher-entry-path.ts
  • src/main/ipc/parcel-watcher-host-subscriptions.ts
  • src/main/ipc/parcel-watcher-interrupted-cancellation.ts
  • src/main/ipc/parcel-watcher-pending-cancellation.ts
  • src/main/ipc/parcel-watcher-pending-subscribe.ts
  • src/main/ipc/parcel-watcher-process-entry.test.ts
  • src/main/ipc/parcel-watcher-process-entry.ts
  • src/main/ipc/parcel-watcher-process-failure.ts
  • src/main/ipc/parcel-watcher-process-protocol.ts
  • src/main/ipc/parcel-watcher-process-supervisor.ts
  • src/main/ipc/parcel-watcher-process-test-child.ts
  • src/main/ipc/parcel-watcher-process.test.ts
  • src/main/ipc/parcel-watcher-process.ts
  • src/main/ipc/parcel-watcher-supervisor-capacity-wait.test.ts
  • src/main/ipc/parcel-watcher-supervisor-capacity-wait.ts
  • src/main/ipc/parcel-watcher-supervisor-capacity.test.ts
  • src/main/ipc/parcel-watcher-supervisor-disposal.ts
  • src/main/ipc/parcel-watcher-supervisor-message.ts
  • src/main/ipc/parcel-watcher-supervisor-subscribe.ts
  • src/main/ipc/parcel-watcher-unsubscribe-timeout.test.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/ipc/runtime-watcher-pending-assignment.test.ts
  • src/main/ipc/runtime-watcher-pending-assignment.ts
  • src/main/ipc/runtime-watcher-pool-lifecycle.ts
  • src/main/ipc/runtime-watcher-pool-state.ts
  • src/main/ipc/runtime-watcher-predecessor-barriers.ts
  • src/main/ipc/runtime-watcher-process-pool.test.ts
  • src/main/ipc/runtime-watcher-process-pool.ts
  • src/main/ipc/runtime-watcher-quarantine-queue.ts
  • src/main/ipc/runtime-watcher-subscription-failure.ts
  • src/main/ipc/watcher-removal-gate.test.ts
  • src/main/ipc/watcher-removal-gate.ts
  • src/main/ipc/worktree-symlinks.test.ts
  • src/main/ipc/worktree-symlinks.ts
  • src/main/ipc/worktrees-windows.test.ts
  • src/main/ipc/worktrees.test.ts
  • src/main/ipc/worktrees.ts
  • src/main/ipc/wsl-watcher-process-exit.ts
  • src/main/local-worktree-removal-recovery.test.ts
  • src/main/local-worktree-removal-recovery.ts
  • src/main/providers/local-pty-provider.test.ts
  • src/main/providers/local-pty-provider.ts
  • src/main/providers/ssh-filesystem-provider-watch-waiters.test.ts
  • src/main/providers/ssh-filesystem-provider-watch.ts
  • src/main/providers/ssh-filesystem-provider.test.ts
  • src/main/providers/ssh-filesystem-provider.ts
  • src/main/providers/ssh-filesystem-watch-notifications.ts
  • src/main/providers/ssh-pty-provider.test.ts
  • src/main/providers/types.ts
  • src/main/runtime/file-watcher-host.test.ts
  • src/main/runtime/file-watcher-host.ts
  • src/main/runtime/orca-runtime-files-watch.test.ts
  • src/main/runtime/orca-runtime-files.test.ts
  • src/main/runtime/orca-runtime-files.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/file-watch-stream-lifecycle.ts
  • src/main/runtime/rpc/methods/files-watch-cancellation.test.ts
  • src/main/runtime/rpc/methods/files-watch-cleanup.test.ts
  • src/main/runtime/rpc/methods/files.test.ts
  • src/main/runtime/rpc/methods/files.ts
  • src/main/runtime/runtime-root-watch-ownership.ts
  • src/main/runtime/runtime-root-watch-teardown.ts
  • src/main/runtime/worktree-teardown.test.ts
  • src/main/runtime/worktree-teardown.ts
  • src/relay/dispatcher.test.ts
  • src/relay/dispatcher.ts
  • src/relay/fs-handler.test.ts
  • src/relay/fs-handler.ts
  • src/relay/git-handler.test.ts
  • src/relay/git-handler.ts
  • src/relay/pty-handler.test.ts
  • src/relay/pty-handler.ts
  • src/relay/relay-filesystem-watch-registry.test.ts
  • src/relay/relay-filesystem-watch-registry.ts
  • src/relay/relay-watcher-event-emitter.ts
  • src/relay/relay-watcher-parent-removal.test.ts
  • src/relay/relay-watcher-pending-setup-join.ts
  • src/relay/relay-watcher-pending-setup-waiters.test.ts
  • src/relay/relay-watcher-removal-fence.ts
  • src/relay/relay-watcher-root-capacity.ts
  • src/relay/relay-watcher-setup-tracking.ts
  • src/relay/relay-watcher-setup-wait.test.ts
  • src/relay/relay-watcher-setup-wait.ts
  • src/relay/relay-watcher-stale-client-release.ts
  • src/relay/relay-watcher-state.ts
  • src/relay/relay-watcher-teardown-tracker.ts
  • src/relay/relay-watcher-terminal-notifier.ts
  • src/relay/relay.ts
  • src/relay/subprocess.test.ts
  • src/renderer/src/runtime/runtime-file-client.test.ts
  • src/renderer/src/runtime/runtime-file-client.ts
  • src/renderer/src/web/web-runtime-client.test.ts
  • src/renderer/src/web/web-runtime-client.ts
  • src/shared/cross-platform-path.test.ts
  • src/shared/cross-platform-path.ts
  • src/shared/physical-exit-tracker.test.ts
  • src/shared/physical-exit-tracker.ts
  • src/shared/promise-settlement-waiters.test.ts
  • src/shared/promise-settlement-waiters.ts
  • src/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

Comment thread src/main/daemon/terminal-host.ts Resolved
Comment thread src/main/ipc/watcher-removal-gate.ts Resolved
Comment thread src/main/runtime/orca-runtime.ts Resolved
Comment thread src/main/runtime/worktree-teardown.ts Resolved
Comment thread src/main/runtime/worktree-teardown.ts Resolved
Comment on lines +1 to +12
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')
)
}

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.

🗄️ 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.

Suggested change
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

# 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
@brennanb2025
brennanb2025 merged commit 64be819 into main Jul 15, 2026
6 checks passed
brennanb2025 added a commit to gsxdsm/orca-stably that referenced this pull request Jul 15, 2026
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.
@AmethystLiang AmethystLiang added the orca-remote-server Remote Orca Server / orca serve / paired remote runtime label Jul 22, 2026
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

orca-remote-server Remote Orca Server / orca serve / paired remote runtime

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants