Skip to content

fix(worktrees): stop terminals after external deletion - #11053

Closed
nwparker wants to merge 1 commit into
stablyai:mainfrom
nwparker:nwparker/fix-external-worktree-terminal-teardown
Closed

nwparker wants to merge 1 commit into
stablyai:mainfrom
nwparker:nwparker/fix-external-worktree-terminal-teardown

Conversation

@nwparker

@nwparker nwparker commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Think of each worktree as a room, and the terminals/agents running in it as people inside that room.

When you delete a room from outside Orca (git worktree remove in a shell, or a CLI agent "cleaning up workspaces"), Orca notices on its next look around and erases the room from its map. But nobody ever told the people inside to leave. They keep running — and now there's no door on the map to reach them. You can only find them with ps on the host.

This PR adds the missing step: before erasing the room from the map, ask the machine that owns it to clear the people out.

The critical safety rule: "I can't see the room" is not the same as "the room is gone." If the SSH host is unreachable or the scan fails, Orca must assume the room is fine and touch nothing. Only a successful, authoritative scan that says "that room isn't here" may evict anyone. That guard is enforced twice — once in the renderer, and again by the host, which re-checks for itself before killing anything rather than trusting the request.

Summary

  • detect worktree IDs removed by an authoritative refresh before renderer state is purged
  • ask the owning runtime to revalidate those IDs and sweep graph-, provider-, and registry-visible PTYs
  • route duplicate repo IDs with the exact SSH connection identity instead of guessing an owner
  • preserve non-authoritative scan safety and degrade cleanly against older runtimes
  • retain graph-visible cleanup when an SSH PTY provider disappears during reconciliation
  • (review fix) run teardown per caller instead of inside the shared scan promise, so a caller that coalesced onto an in-flight scan cannot purge renderer state without requesting a sweep
  • (review fix) revalidate against a fresh scan instead of the 30s worktree-scan cache, which could still list an already-deleted directory and silently skip the sweep

Reproduction

Removing a worktree outside Orca updated the sidebar on the next authoritative scan, but the bulk purge path performed no terminal teardown. Local and SSH agents could therefore remain alive after all renderer ownership state was deleted. The new ordering waits for the host-scoped cleanup request before purging that state, while the runtime performs its own authoritative recheck before stopping anything.

Validation

  • 2,047 renderer store tests, 899 runtime tests, 642 RPC/provider/teardown tests
  • pnpm typecheck:node
  • pnpm typecheck:web
  • pnpm check:max-lines-ratchet
  • git diff origin/main...HEAD --check

Two regression tests were added that fail on the pre-review commit and pass after it — see the review comment for the full proof-of-fix and proof-of-no-regression breakdown.

Closes #10562

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@nwparker, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 1 minute

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ffb23062-7682-4d10-9883-dd8d68fd6423

📥 Commits

Reviewing files that changed from the base of the PR and between 2cf91b8 and ec14a28.

📒 Files selected for processing (9)
  • src/main/runtime/missing-worktree-terminal-reconciliation.test.ts
  • src/main/runtime/missing-worktree-terminal-reconciliation.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/worktree-missing-terminal-teardown.test.ts
  • src/main/runtime/rpc/methods/worktree-schemas.ts
  • src/main/runtime/rpc/methods/worktree.ts
  • src/renderer/src/store/slices/worktrees.test.ts
  • src/renderer/src/store/slices/worktrees.ts

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.

@nwparker

Copy link
Copy Markdown
Contributor Author

Review: two defects found and fixed

I reviewed this adversarially and found two bugs that let the original fix silently do nothing — including one where the exact scenario in #10562 still reproduced. Both are fixed in db9d40c, each with a regression test that fails without the fix.


ELI5

Think of each worktree as a room, and the terminals/agents inside it as people.

When you delete a room from outside Orca (git worktree remove in a shell), Orca notices on its next look around and erases the room from its map. But nobody told the people inside to leave. They're still there — still running, still burning CPU — and now there's no door on the map to reach them. You can only find them with ps.

This PR adds the missing step: before erasing the room from the map, ask the machine that owns it to clear the people out.

The critical safety rule: "I can't see the room" is not the same as "the room is gone." If the SSH host is unreachable or the scan fails, Orca must assume the room is fine and touch nothing. Only a successful, authoritative scan that says "that room isn't here" is allowed to evict anyone.

What I found wrong:

  1. The eviction request was attached to the wrong thing. Orca shares one "look around" between everyone who asks at the same time (a performance optimization). The teardown was bolted onto that shared look, not onto each asker. So if you were the second person to ask, you got handed the shared result — erased your map — and never sent the eviction request. The original bug reproduced verbatim.

  2. The double-check was reading a stale answer. Before killing anything, the host re-checks "is this room really gone?" — good. But that re-check could be answered from a cache up to 30 seconds old, which could still say "the room is there." So the sweep would skip. And since the renderer erases its map regardless, nothing ever asks again — the processes leak forever.


Defect 1 — coalesced callers purged state without ever requesting teardown

teardownMissingWorktreeTerminalsBestEffort ran inside the shared scan promise in listDetectedWorktreesForRepoCoalesced. Callers that joined an in-flight scan returned early at if (existing) return existing, skipping teardown entirely — while still running their own buildWorktreePurgeState.

This is not a rare interleaving. Teardown is gated on knownWorktreeIds.length === 0, and knownWorktreeIds is snapshotted per caller. Startup fan-out routinely has caller A begin before hydration (empty snapshot → no-op) and caller B join after hydration (full snapshot → should sweep, but doesn't).

Proof of bug — reverting only worktrees.ts and running the new test:

× stops terminals for a caller that coalesced onto an in-flight scan
  AssertionError: expected "vi.fn()" to be called with arguments: [ { …(2) } ]
  Number of calls: 0

Zero teardown RPCs, yet tabsByWorktree[deleted.id] was purged — the #10562 leak, unchanged.

Fix: the scan still coalesces; teardown now runs per caller against its own snapshot. To avoid trading one bug for N redundant host sweeps, teardown deduplicates on the request it actually produces (target + repo + connection + sorted missing IDs).

Defect 2 — the authoritative recheck was served from a 30s cache

teardownMissingManagedWorktreeTerminals calls listDetectedManagedWorktrees, which routes through listRepoWorktreesForResolution — a cache with a 30s TTL (WORKTREE_SCAN_CACHE_TTL_MS), invalidated only by Orca's own mutations. An external git worktree remove invalidates nothing.

The renderer's scan uses a different 5s cache (DETECTED_WORKTREE_SCAN_CACHE_TTL_MS), so the renderer can correctly observe the deletion while the runtime's recheck still reports the worktree present. The sweep is skipped, the renderer purges anyway, and nothing retries — a permanent leak.

Proof of bug — reverting only orca-runtime.ts:

× revalidates against a fresh scan instead of a warm worktree-scan cache
  AssertionError: expected { stoppedWorktreeIds: [] } to deeply equal { stoppedWorktreeIds: [ 'repo-1::/tmp/deleted' ] }

Fix: invalidate the repo's scan cache before revalidating. Killing processes must be proven against the host now, not against a cached observation. This is scoped to the destructive path only — read-only listing keeps its cache.


Proof of fix

Both regression tests fail on the parent commit and pass on db9d40c:

Test Without fix With fix
stops terminals for a caller that coalesced onto an in-flight scan ❌ 0 teardown RPCs ✅
revalidates against a fresh scan instead of a warm worktree-scan cache ❌ stoppedWorktreeIds: [] ✅
shares one teardown sweep across identical concurrent refreshes — (guards the fix's own fan-out risk) ✅

Proof of no regression

Suite Result
src/renderer/src/store/ (134 files) 2047 passed
src/main/runtime/orca-runtime.test.ts 899 passed
src/main/runtime/rpc/methods/ + teardown suites (57 files) 642 passed
pnpm typecheck:node / typecheck:web clean
pnpm check:max-lines-ratchet OK — no new bypasses
git diff --check clean

No existing assertion was changed or relaxed — the only edits to existing tests are additions.


Adversarial checks that came back clean

I probed these and confirmed the existing behavior is correct — no changes needed:

  • SSH disconnected / scan failure → no teardown. Both the runtime (listRepoWorktreesForResolutionUncached returns ok: false when the provider is absent or throws) and the IPC path return authoritative: false, which short-circuits before any sweep. The [Bug]: Externally deleted worktrees (git worktree remove outside Orca) strand their terminal/agent processes — reconcile paths run no teardown #10562 "critical guard" holds on both sides — and the runtime re-derives it independently rather than trusting the renderer.
  • Folder workspaces. listRuntimeFolderWorkspaces enumerates from persisted metadata, so a folder instance is never spuriously "missing" from a git scan. Verified that sibling instances sharing one directory (::workspace:<uuid>) don't sweep each other — the ${worktreeId}@@ prefix contract keeps them distinct.
  • Repo-ID prefix confusion. repo-1 vs repo-10 does not leak across repos; splitWorktreeId splits on the first :: and the result is compared for equality, not prefix.
  • Duplicate repo IDs across hosts. resolveRepoSelectorForConnection requires an exact connection-identity match and throws selector_ambiguous rather than guessing an owner — correct, and stricter than resolveRepoSelector.
  • Non-authoritative scans. Guarded on both sides (renderer and runtime) independently.

One note for reviewers (not blocking)

The renderer discards the teardown result and purges regardless of whether the sweep succeeded. That's the right call for UI responsiveness — but it means the sweep has exactly one chance to run, which is precisely what made Defect 2 permanent rather than transient. Worth keeping in mind for any future change to this path: there is no retry, so correctness here has to be right the first time. A follow-up backstop (e.g. reconciling on SSH reconnect, cf. #9820) would add defense in depth.

@nwparker

Copy link
Copy Markdown
Contributor Author

⚠️ Note on this PR's diff view

The head branch nwparker/fix-external-worktree-terminal-teardown was deleted from the remote at some point while this PR stayed open. I've restored it, and it now contains both commits:

  • ec14a28 — the original change
  • db9d40c — fix(worktrees): request teardown per caller and revalidate uncached (the two review fixes above)

GitHub has not re-attached the PR to the restored branch, so the Files-changed tab still shows only ec14a28 (9 files, +511) and is missing the review fixes. Verified via API — the branch is correct:

$ gh api repos/stablyai/orca/compare/main...nwparker/fix-external-worktree-terminal-teardown
commits: ["ec14a28181a00da...", "db9d40cf4c3a967..."]

To review the actual state, use the branch compare rather than this PR's cached diff:
main...nwparker/fix-external-worktree-terminal-teardown

If the PR doesn't self-heal, closing and reopening it (or opening a fresh PR from the same branch) will re-sync the head. I didn't do either, since that's a call for whoever owns this PR — the code and branch are in their final state either way.

@nwparker

Copy link
Copy Markdown
Contributor Author

Second review pass — one perf defect found and fixed

Re-reviewed with a focus on performance. Found one real perf defect, fixed in 60a6e3b. Everything else came back clean.

Defect 3 — O(N) host enumerations per teardown sweep

stopMissingWorktreeTerminals fans out over missing worktrees and calls killAllProcessesForWorktree for each. That function calls provider.listProcesses() — a full enumeration of every PTY on the host — and nothing shares it across the batch.

So sweeping N missing worktrees costs N full host enumerations, each returning all N+ session rows: O(N) round-trips carrying O(N²) data.

This is not a hypothetical batch size. It's the primary scenario in #10562 — "a CLI agent told to 'clean up workspaces' running raw git" deletes many worktrees at once, and every one of them lands in a single sweep.

No layer coalesces these. SshPtyProvider.listProcesses is a bare mux.request('pty.listProcesses') — one real relay round-trip per call. DaemonPtyAdapter.listProcesses is a listSessions IPC round-trip. DaemonPtyRouter/DegradedDaemonPtyProvider fan out to every adapter, so the multiplier is worse there.

Measured (30 worktrees, 80ms RTT — a normal cross-region SSH link):

before after
listProcesses round-trips 30 1
rows transferred 30 × 30 1 × 30
wall clock 1298ms 732ms

The round-trip count is the load-bearing number — it scales linearly, so a 100-worktree cleanup was 100 enumerations. Wall clock understates the win because the remaining time is the shutdown calls, which are genuinely per-PTY work.

Proof of bug — reverting only missing-worktree-terminal-reconciliation.ts:

× enumerates the host once for the whole sweep
  AssertionError: expected "vi.fn()" to be called 1 times, but got 25 times

Fix: share one point-in-time process list across the sweep. Every worktree in the batch is already known-missing, so a single snapshot answers all of them.

Two correctness traps in the fix itself, both caught by tests I wrote against it

Worth calling out, because the naive version of this optimization is wrong in two ways:

  1. Sharing a rejected scan. My first version cached the promise unconditionally. A single transient relay hiccup would then suppress the provider sweep for every worktree in the batch — strictly worse than the O(N) behavior, and precisely the leak this reconciliation exists to prevent. A failed scan now falls back to a per-caller scan, restoring pre-batching failure isolation; only the success path is shared. Covered by does not reuse a failed process scan.

  2. requirePhysicalStop reading a stale snapshot. That path re-lists after shutdown to prove a PTY actually exited. A pre-shutdown snapshot would make that proof read stale rows and report success for a PTY that's still alive. This sweep never sets the flag, but relying on that implicitly is a trap for the next person — so it's now pinned requirePhysicalStop: false at the call site with the invariant documented on the wrapper.

Also verified the wrapper preserves this binding for prototype-based providers (all the real ones are classes) — covered by keeps provider method binding intact while batching, which fails without the fix.

Perf surfaces checked and found clean

  • Renderer teardown dedupe (from the previous pass) — identical fan-out requests share one sweep; no per-caller RPC storm. Covered by shares one teardown sweep across identical concurrent refreshes.
  • Scan-cache invalidation (Defect 2's fix) — scoped to the destructive path only. Read-only listing keeps its cache; listResolvedWorktrees keeps its own 1s cache, so the graph sweep isn't re-derived per worktree.
  • mapWithConcurrency bound of 4 — correct as-is; it caps the shutdown fan-out without serializing it.
  • No N+1 in the missing-ID computation — detectedIds is a Set, and dedupe is a single Set pass.

Validation

Suite Result
src/main/runtime/ + src/renderer/src/store/ (319 files) 4976 passed, 5 skipped
pnpm typecheck:node / typecheck:web clean
pnpm check:max-lines-ratchet OK — no new bypasses
git diff --check clean

Three new regression tests, all failing on the prior commit and passing on 60a6e3b. No existing assertion changed or relaxed.


Branch tip is now 60a6e3b (3 commits). This PR's Files-changed tab is still detached and shows only ec14a28 — see my note above; use the branch compare for the real diff.

@nwparker

Copy link
Copy Markdown
Contributor Author

Superseded by #11237.

This PR became permanently detached from its head branch — GitHub kept it pinned at ec14a28 and never re-synced after the branch was deleted and restored, so its Files-changed tab never showed the three review fixes or the merge with main.

#11237 is the same branch with the complete work (5 commits, correctly synced). All review discussion from this PR is summarized in its description.

@nwparker nwparker closed this Jul 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Externally deleted worktrees (git worktree remove outside Orca) strand their terminal/agent processes — reconcile paths run no teardown

1 participant