Repository navigation
fix(worktrees): stop terminals after external deletion - #11237
Conversation
Two defects let the original fix silently strand PTYs: - teardown rode the scan's coalescing promise, so any caller that joined an in-flight scan purged its renderer state without ever asking for a sweep; it now runs per caller against its own known-id snapshot, deduped on the request it actually produces so fan-out still shares one host sweep. - the runtime's authoritative recheck was served from the 30s worktree-scan cache, which can still list a directory git already dropped. The renderer purges either way, so a stale miss leaked those processes permanently. Co-authored-by: Orca <[email protected]>
An agent cleaning up N workspaces made killAllProcessesForWorktree issue one full provider enumeration per missing worktree: O(N) relay round-trips carrying O(N^2) rows. At 30 worktrees over an 80ms-RTT SSH link that is 30 scans and ~1.3s of stalled teardown; it scales linearly from there. Share one point-in-time process list across the sweep — every worktree in it is already known-missing, so a single snapshot answers all of them. A failed scan is never shared: it falls back to a per-caller scan so one transient relay error cannot suppress the sweep for the whole batch. Pinned requirePhysicalStop:false since that path re-lists after shutdown and must not read a pre-shutdown snapshot. Co-authored-by: Orca <[email protected]>
main refactored the detected-worktree refresh into a lease/admission model (DetectedWorktreeRefreshOutcome, directSshAuthority, mergeFetchedWorktrees). Reapplied the per-caller teardown on top of that structure: - carry connectionId/knownWorktreeIds on DetectedWorktreeRefreshOptions - request teardown before every 'admitted' return (runtime and lease paths), so a caller that joined a coalesced scan still stops its terminals - knownWorktreeIds is optional: absent means "nothing to reconcile", never "purge everything" - update the three teardown tests to main's host-qualified listDetected mock Co-authored-by: Orca <[email protected]>
…-worktree-terminal-teardown-2
📝 WalkthroughWalkthroughAdds best-effort teardown for terminals associated with worktrees absent from authoritative detection results. The runtime now supports connection-scoped repository resolution, authoritative revalidation, local and SSH provider selection, and fallback graph teardown. A new validated RPC exposes the operation. Renderer refresh flows pass connection and known-worktree context, deduplicate teardown requests, and delay purging until teardown completes. Tests cover provider behavior, runtime revalidation, RPC dispatch, refresh coalescing, disconnected SSH targets, and teardown ordering. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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 |
main's new directSshAuthority gate bails before any refresh when an SSH target is not connected. That is exactly the #10562 safety rule — "host unreachable" must never be read as "worktree deleted" — so pin it: a disconnected target issues no teardown RPC and keeps its renderer state. Co-authored-by: Orca <[email protected]>
ded67d8 to
609daf4
Compare
Merge-readiness statusBranch is current with
Final review summaryThree defects were found and fixed during review, each with a regression test that fails on the commit before its fix:
Plus two correctness traps inside the perf fix itself, both caught by tests written against it (sharing a rejected scan; Merge interaction worth a reviewer's eye
That refactor also strengthens the #10562 safety invariant for free:
Known follow-up (not blocking)The renderer discards the teardown result and purges regardless of whether the sweep succeeded. That's correct for UI responsiveness, but the sweep gets exactly one chance — which is what made defect 2 permanent rather than transient. A backstop that reconciles on SSH reconnect (cf. #9820) would add defense in depth. |
Greptile SummaryThis PR fixes a leak where externally-deleted worktrees (via
Confidence Score: 5/5Safe to merge. The change adds a well-guarded sweep step with the non-authoritative safety property enforced independently at both the renderer and runtime layers, and all regression tests pass. The implementation is thorough and directly addresses the root causes described. Both layers independently re-derive whether a scan was authoritative before touching any PTYs, so a disconnected SSH host or a failed scan cannot trigger teardown. The O(1)-round-trip batching is carefully isolated to the best-effort path with explicit constraints against misuse on re-verification paths. Seven new regression tests are each documented to fail before their specific fix, and no existing assertions were relaxed. No defects found that would affect current behaviour. Files Needing Attention: No files require special attention.
|
| Filename | Overview |
|---|---|
| src/main/runtime/missing-worktree-terminal-reconciliation.ts | New module implementing the O(1)-round-trip sweep; shared-snapshot proxy guards against rejected-scan propagation and provider-internal listProcesses rebinding are both correct and covered by dedicated tests. |
| src/main/runtime/orca-runtime.ts | Adds teardownMissingManagedWorktreeTerminals with cache invalidation before revalidation (fixing the 30s-cache defect), refactors resolveRepoSelector into a shared selectReposBySelector helper, and introduces resolveRepoSelectorForConnection that narrows by connection identity without changing selector grammar; all three paths are tested. |
| src/renderer/src/store/slices/worktrees.ts | Adds per-caller teardownMissingWorktreeTerminalsBestEffort outside the scan coalescer with in-flight deduplication keyed on the actual request; correctly returns early on non-authoritative scans, absent knownWorktreeIds, and disconnected SSH targets. |
| src/main/runtime/rpc/methods/worktree.ts | Registers the new worktree.teardownMissingTerminals RPC method; existing worktree.detectedList is unchanged and the new method degrades cleanly on older runtimes via method_not_found handling in the renderer. |
| src/main/runtime/rpc/methods/worktree-schemas.ts | Adds WorktreeTeardownMissingTerminalsParams extending existing list params with bounded worktreeIds array (max 10 000) and optional nullable connectionId; schema validation is correct. |
Sequence Diagram
sequenceDiagram
participant R as Renderer (worktrees.ts)
participant RPC as IPC / RPC Bridge
participant RT as Runtime (orca-runtime.ts)
participant Rec as stopMissingWorktreeTerminals
participant Git as Git (listWorktrees)
participant PTY as PTY Provider
Note over R: External `git worktree remove` ran<br/>on repo-1::/path/deleted
R->>R: "fetchWorktrees('repo1')<br/>snapshot knownWorktreeIds = [deleted, surviving]"
R->>RPC: worktree.detectedList (coalesced scan)
RPC->>Git: listWorktrees() [cache invalidated]
Git-->>RPC: [surviving] (deleted is gone)
RPC-->>R: "{authoritative:true, worktrees:[surviving]}"
Note over R: teardown fires per-caller, outside coalescer
R->>RPC: "worktree.teardownMissingTerminals<br/>{repo, worktreeIds:[deleted], connectionId}"
RPC->>RT: teardownMissingManagedWorktreeTerminals()
RT->>RT: invalidateWorktreeScanCacheForRepo()
RT->>Git: listWorktrees() [fresh, no cache]
Git-->>RT: [surviving]
RT->>RT: authoritative? ✓ → proceed
RT->>Rec: stopMissingWorktreeTerminals(repo, [deleted], [surviving])
Rec->>PTY: listProcesses() [shared snapshot, 1 call for all missing]
PTY-->>Rec: "[deleted@@session-1, surviving@@session-2]"
Rec->>PTY: "shutdown(deleted@@session-1, {immediate:true})"
PTY-->>Rec: ok
Rec-->>RT: "{stoppedWorktreeIds: [deleted]}"
RT-->>RPC: "{stoppedWorktreeIds: [deleted]}"
RPC-->>R: "{ok: true, result: {stoppedWorktreeIds: [deleted]}}"
Note over R: teardown awaited → now purge renderer state
R->>R: "purge worktreesByRepo[deleted]<br/>purge tabsByWorktree[deleted]"
Reviews (2): Last reviewed commit: "fix(worktrees): keep the shared snapshot..." | Re-trigger Greptile
resolveRepoSelectorForConnection matched the selector as a bare repo id, so an explicit connection identity silently changed the grammar: `path:` and `name:` selectors resolved to repo_not_found on that path alone, losing the whole sweep. A connection identity should only *narrow* the candidate set. Extract the selector matching both paths now share, and stop re-resolving an already-resolved repo: teardown rescanned via `id:<repo.id>`, which throws selector_ambiguous when an id is duplicated across hosts even though the caller's own selector was unambiguous. Reported as a P2 by Greptile (as redundant work); it is load-bearing. Co-authored-by: Orca <[email protected]>
Greptile P2 was real — and worse than reportedGreptile flagged the double Two distinct defects behind that one symptom: 1. An explicit connection identity silently changed the selector grammar. const repoId = repoSelector.startsWith('id:') ? repoSelector.slice(3) : repoSelectorSo on this path alone, After the fix, the same call resolves and sweeps: 2. Re-resolving an already-resolved repo can throw. Teardown rescanned via The renderer always sends a bare repo id, so no user-facing path hits this today — but the RPC is public and reachable by CLI/runtime clients, and the sibling detected-list method accepts these selectors. This is a trap for the next caller, not a live outage. Also extracted the selector matching that both resolution paths now share, so the two can't drift again. Four existing tests were repointed from the public wrapper to the new internal seam — behavior unchanged; they were stubbing a method the destructive path no longer calls. Validation: 5075 passed / 5 skipped across |
The snapshot proxy passed itself as the Reflect.get receiver, so prototype methods invoked through it ran with `this` bound to the proxy. A provider whose own shutdown() re-read state via `this.listProcesses()` would then silently get this sweep's cached snapshot instead of the live host — batching leaking past the calls it was built for. Bind non-listProcesses members to the target so only the sweep's own calls share the snapshot. No shipped provider does this today; the point is that adding one must not quietly change teardown semantics. Raised by Greptile as an undocumented implicit constraint; closed structurally rather than by comment. Co-authored-by: Orca <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/renderer/src/store/slices/worktrees.ts (2)
686-690: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winModule-level dedup map isn't reset between test runs.
missingWorktreeTeardownsInFlightis process/module-scoped and only cleared once an in-flight promise settles. That's fine in production (one renderer process), but inworktrees.test.ts— which recreates the store per test but never touches this module map — a future test that reuses the same(target, repoId, connectionId, missingIds)combination while a prior test's promise is still pending (e.g. a test that forgets to resolve its mocked RPC) would silently await the stale promise instead of exercising a fresh call, causing hard-to-diagnose flake.♻️ Suggested mitigation
-const missingWorktreeTeardownsInFlight = new Map<string, Promise<void>>() +const missingWorktreeTeardownsInFlight = new Map<string, Promise<void>>() +// Exposed for test-only cleanup between cases that reuse repo/connection/worktree ids. +export function __resetMissingWorktreeTeardownsInFlightForTests(): void { + missingWorktreeTeardownsInFlight.clear() +}
691-742: 🩺 Stability & Availability | 🔵 TrivialTeardown latency blocks the whole coalesced refresh, not just the purge of the missing entry.
teardownMissingWorktreeTerminalsBestEffortis awaited beforelistDetectedWorktreesForRepoCoalescedreturns its "admitted" result, so a slow/hanging runtime RPC (up to the 30s timeout) delays the entire refresh — including fresh data for surviving worktrees unrelated to the deletion — not just the purge of the stale entry. This appears intentional (confirmed by the "awaits missing-worktree terminal teardown before purging renderer state" test), but it's worth keeping in mind operationally: a flaky/slow SSH host with an externally-deleted worktree will now visibly stall that repo's worktree-list refresh for up to 30s on every coalesced call that observes the deletion, until the dedup entry settles.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: bfbd195c-d1f9-47d9-99a7-9f29f6eb7d6f
📒 Files selected for processing (9)
src/main/runtime/missing-worktree-terminal-reconciliation.test.tssrc/main/runtime/missing-worktree-terminal-reconciliation.tssrc/main/runtime/orca-runtime.test.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/worktree-missing-terminal-teardown.test.tssrc/main/runtime/rpc/methods/worktree-schemas.tssrc/main/runtime/rpc/methods/worktree.tssrc/renderer/src/store/slices/worktrees.test.tssrc/renderer/src/store/slices/worktrees.ts
Second Greptile finding also real — fixed in
|
Green — ready to mergeBoth bot reviews re-ran against
Both bots' outstanding inline comments are the same selector defect, now fixed. Final tally: five defects, none of which the original implementation would have surfaced at runtime as an error
Plus two traps inside the perf fix itself, caught by tests written against it (sharing a rejected scan; Seven regression tests, each verified to fail on the commit before its fix. No existing assertion was changed or relaxed — the only edits to existing tests are additions, a mock-shape update for main's lease/admission refactor, and four stubs repointed to the seam the destructive path now uses. Reviewer notes
|
* fix(worktrees): stop terminals after external deletion * fix(worktrees): request teardown per caller and revalidate uncached Two defects let the original fix silently strand PTYs: - teardown rode the scan's coalescing promise, so any caller that joined an in-flight scan purged its renderer state without ever asking for a sweep; it now runs per caller against its own known-id snapshot, deduped on the request it actually produces so fan-out still shares one host sweep. - the runtime's authoritative recheck was served from the 30s worktree-scan cache, which can still list a directory git already dropped. The renderer purges either way, so a stale miss leaked those processes permanently. Co-authored-by: Orca <[email protected]> * perf(worktrees): enumerate the host once per teardown sweep An agent cleaning up N workspaces made killAllProcessesForWorktree issue one full provider enumeration per missing worktree: O(N) relay round-trips carrying O(N^2) rows. At 30 worktrees over an 80ms-RTT SSH link that is 30 scans and ~1.3s of stalled teardown; it scales linearly from there. Share one point-in-time process list across the sweep — every worktree in it is already known-missing, so a single snapshot answers all of them. A failed scan is never shared: it falls back to a per-caller scan so one transient relay error cannot suppress the sweep for the whole batch. Pinned requirePhysicalStop:false since that path re-lists after shutdown and must not read a pre-shutdown snapshot. Co-authored-by: Orca <[email protected]> * test(worktrees): pin the disconnected-SSH no-teardown invariant main's new directSshAuthority gate bails before any refresh when an SSH target is not connected. That is exactly the stablyai#10562 safety rule — "host unreachable" must never be read as "worktree deleted" — so pin it: a disconnected target issues no teardown RPC and keeps its renderer state. Co-authored-by: Orca <[email protected]> * fix(worktrees): keep selector grammar intact when scoping by connection resolveRepoSelectorForConnection matched the selector as a bare repo id, so an explicit connection identity silently changed the grammar: `path:` and `name:` selectors resolved to repo_not_found on that path alone, losing the whole sweep. A connection identity should only *narrow* the candidate set. Extract the selector matching both paths now share, and stop re-resolving an already-resolved repo: teardown rescanned via `id:<repo.id>`, which throws selector_ambiguous when an id is duplicated across hosts even though the caller's own selector was unambiguous. Reported as a P2 by Greptile (as redundant work); it is load-bearing. Co-authored-by: Orca <[email protected]> * fix(worktrees): keep the shared snapshot out of provider internals The snapshot proxy passed itself as the Reflect.get receiver, so prototype methods invoked through it ran with `this` bound to the proxy. A provider whose own shutdown() re-read state via `this.listProcesses()` would then silently get this sweep's cached snapshot instead of the live host — batching leaking past the calls it was built for. Bind non-listProcesses members to the target so only the sweep's own calls share the snapshot. No shipped provider does this today; the point is that adding one must not quietly change teardown semantics. Raised by Greptile as an undocumented implicit constraint; closed structurally rather than by comment. Co-authored-by: Orca <[email protected]> --------- Co-authored-by: Orca <[email protected]>
Replaces #11053, which became permanently detached from its head branch (GitHub kept it pinned at the original commit and never re-synced after the branch was deleted and restored). Same branch, same work, plus three review fixes and a merge with
main.Closes #10562
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 removein 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 withpson 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.
What it does
Review fixes on top of the original
The original implementation had two bugs that made it silently do nothing — including one where the exact #10562 scenario still reproduced — plus one perf defect.
1. Coalesced callers purged state without ever requesting teardown. Teardown ran inside the shared scan promise, so any caller that joined an in-flight scan returned early and skipped it — while still running its own purge. Not a rare interleaving: teardown is gated on a per-caller
knownWorktreeIdssnapshot, and startup fan-out routinely has one caller start pre-hydration (empty snapshot, no-op) and another join post-hydration (should sweep, didn't). Fixed by running teardown per caller, deduped on the request it actually produces.2. The "authoritative recheck" read a 30s cache. The runtime revalidated through a cache invalidated only by Orca's own mutations — an external
git worktree removeinvalidates nothing. The renderer uses a different 5s cache, so it could correctly see the deletion while the runtime still reported the worktree present, skipping the sweep. Since the renderer purges regardless and nothing retries, the leak was permanent. Fixed by invalidating the repo's scan cache before revalidating (destructive path only).3. O(N) host enumerations per sweep.
killAllProcessesForWorktreecallsprovider.listProcesses()— a full enumeration of every PTY on the host — once per missing worktree, with nothing shared: O(N) round-trips carrying O(N²) rows. No layer coalesces these (SshPtyProvideris a bare relay round-trip; the daemon router fans out to every adapter). This is the primary #10562 scenario, where an agent deletes many worktrees at once. Measured at 30 worktrees / 80ms RTT: 30 round-trips → 1, wall clock 1298ms → 732ms.Two correctness traps in that perf fix, both caught by tests written against it: sharing a rejected scan would let one transient relay error suppress the sweep for the whole batch (worse than the original), and
requirePhysicalStopre-lists after shutdown to prove a PTY exited, so a pre-shutdown snapshot would make that proof read stale rows. Only the success path is shared, andrequirePhysicalStop: falseis pinned at the call site with the invariant documented.Two further defects came from Greptile's bot review, both verified to reproduce before fixing:
4. An explicit connection identity silently changed the selector grammar.
resolveRepoSelectorForConnectionmatched the selector as a bare repo id, sopath:/name:selectors — valid everywhere else, and accepted by the siblingworktree.detectedListRPC — resolved torepo_not_foundon this path alone. Separately, teardown rescanned via`id:${repo.id}`, and that re-resolution throwsselector_ambiguouswhen an id is duplicated across hosts even though the caller's selector was unambiguous. The renderer always sends a bare repo id so no user-facing path hits this today, but the RPC is public. Both paths now share one selector grammar, and teardown scans the already-resolved repo.5. The shared snapshot leaked into provider internals. The snapshot proxy passed itself as the
Reflect.getreceiver, so a provider whose ownshutdown()re-read state viathis.listProcesses()would silently get the cached snapshot instead of the live host. No shipped provider does this, but adding one must not quietly change teardown semantics. Non-listProcessesmembers are now bound to the target.Merge with main
mainrefactored the detected-worktree refresh into a lease/admission model (DetectedWorktreeRefreshOutcome,directSshAuthority,mergeFetchedWorktrees). The per-caller teardown is reapplied on that structure — requested before everyadmittedreturn on both the runtime and lease paths — andknownWorktreeIdsis optional, where absent means "nothing to reconcile", never "purge everything".Validation
src/main/runtime/+src/renderer/src/store/pnpm typecheck:node/typecheck:webpnpm check:max-lines-ratchetSeven regression tests added, each failing on the commit before its fix. No existing assertion was changed or relaxed; the only edits to existing tests are additions and a mock-shape update to match main's refactor.
Adversarial checks that came back clean
ok: falsewhen the provider is absent or throws) and the IPC path returnauthoritative: false, short-circuiting 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.repo-1vsrepo-10doesn't leak — IDs are compared for equality, not prefix.resolveRepoSelectorForConnectionrequires exact connection identity and throwsselector_ambiguousrather than guessing.Note for reviewers
The renderer discards the teardown result and purges regardless of whether the sweep succeeded. That's right for UI responsiveness, but it means the sweep gets exactly one chance — which is what made defect 2 permanent rather than transient. A follow-up backstop (reconciling on SSH reconnect, cf. #9820) would add defense in depth.
Made with Orca 🐋