Skip to content

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

Merged
nwparker merged 8 commits into
mainfrom
nwparker/fix-external-worktree-terminal-teardown
Jul 30, 2026
Merged

nwparker merged 8 commits into
mainfrom
nwparker/fix-external-worktree-terminal-teardown

Conversation

@nwparker

@nwparker nwparker commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

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

What it does

  • 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 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 knownWorktreeIds snapshot, 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 remove invalidates 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. killAllProcessesForWorktree calls provider.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 (SshPtyProvider is 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 requirePhysicalStop re-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, and requirePhysicalStop: false is 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. resolveRepoSelectorForConnection matched the selector as a bare repo id, so path:/name: selectors — valid everywhere else, and accepted by the sibling worktree.detectedList RPC — resolved to repo_not_found on this path alone. Separately, teardown rescanned via `id:${repo.id}`, and that re-resolution throws selector_ambiguous when 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.get receiver, so a provider whose own shutdown() re-read state via this.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-listProcesses members are now bound to the target.

Merge with main

main refactored the detected-worktree refresh into a lease/admission model (DetectedWorktreeRefreshOutcome, directSshAuthority, mergeFetchedWorktrees). The per-caller teardown is reapplied on that structure — requested before every admitted return on both the runtime and lease paths — and knownWorktreeIds is optional, where absent means "nothing to reconcile", never "purge everything".

Validation

Suite Result
src/main/runtime/ + src/renderer/src/store/ 5076 passed, 5 skipped
pnpm typecheck:node / typecheck:web clean
pnpm check:max-lines-ratchet OK — no new bypasses

Seven 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

  • SSH disconnected / scan failure → no teardown. Both the runtime (ok: false when the provider is absent or throws) and the IPC path return authoritative: 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.
  • Folder workspaces. Enumerated from persisted metadata, so never spuriously "missing"; sibling instances sharing one directory don't sweep each other.
  • Repo-ID prefix confusion. repo-1 vs repo-10 doesn't leak — IDs are compared for equality, not prefix.
  • Duplicate repo IDs across hosts. resolveRepoSelectorForConnection requires exact connection identity and throws selector_ambiguous rather 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 🐋

nwparker and others added 5 commits July 27, 2026 19:22
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]>
@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 is detailed, but it does not follow the required template and omits the mandated sections. Reformat the PR body to the repository template and add all required sections, especially Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes implement trigger-time teardown for externally deleted worktrees and preserve the no-teardown guard on disconnected or failing SSH scans, matching #10562.
Out of Scope Changes check ✅ Passed The modified files and tests all support the worktree-terminal reconciliation fix; no clearly unrelated changes are evident.
Title check ✅ Passed The title clearly matches the main change: stopping terminals after external worktree deletion.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

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]>
@nwparker
nwparker force-pushed the nwparker/fix-external-worktree-terminal-teardown branch from ded67d8 to 609daf4 Compare July 28, 2026 23:03
@nwparker

Copy link
Copy Markdown
Contributor Author

Merge-readiness status

Branch is current with main (merged twice during review; latest at 13c193a) and all 23 CI checks pass. mergeable: true.

CI 23/23 pass (e2e skipped — no e2e path changes; Greptile is advisory, non-blocking)
src/main/runtime/ + src/renderer/src/store/ 5073 passed, 5 skipped
worktrees + reconciliation + runtime (post-merge) 1144 passed
typecheck:node / typecheck:web clean
check:max-lines-ratchet OK — no new bypasses

Final review summary

Three defects were found and fixed during review, each with a regression test that fails on the commit before its fix:

  1. Coalesced callers purged state without requesting teardown — the original [Bug]: Externally deleted worktrees (git worktree remove outside Orca) strand their terminal/agent processes — reconcile paths run no teardown #10562 leak still reproduced verbatim (0 teardown RPCs issued, state purged anyway).
  2. The authoritative recheck read a 30s cache an external git worktree remove never invalidates — and since the renderer purges regardless with no retry, the leak was permanent.
  3. O(N) host enumerations per sweep — 30 relay round-trips carrying O(N²) rows for a 30-worktree cleanup, reduced to 1.

Plus two correctness traps inside the perf fix itself, both caught by tests written against it (sharing a rejected scan; requirePhysicalStop reading a pre-shutdown snapshot).

Merge interaction worth a reviewer's eye

main landed a lease/admission refactor (DetectedWorktreeRefreshOutcome, directSshAuthority, mergeFetchedWorktrees) mid-review. The teardown was reapplied on that structure and verified to fire before both status: 'admitted' returns (runtime-environment and local/direct-SSH lease paths) and on none of the not-admitted paths.

That refactor also strengthens the #10562 safety invariant for free: directSshAuthority now bails out before any refresh when an SSH target isn't connected, so a disconnected host can't even reach the teardown call. That's pinned by a new test (never stops terminals for a disconnected SSH target) so a future change can't silently regress it into killing PTYs on an unreachable host.

knownWorktreeIds is optional on the options type — absent means "nothing to reconcile", never "purge everything".

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.

Comment thread src/main/runtime/orca-runtime.ts Resolved
@greptile-apps

greptile-apps Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a leak where externally-deleted worktrees (via git worktree remove or a CLI agent) left their terminal sessions running and permanently unreachable in Orca. It adds a per-caller teardown step that fires before the renderer purges its state, routing an IPC request to the owning runtime to sweep PTYs for any worktree IDs that vanished from the authoritative scan.

  • New stopMissingWorktreeTerminals reconciliation module batches the host process list into a single round-trip per sweep (O(N) → O(1)) using a shared-snapshot proxy, with correctness guards ensuring failed snapshots don't suppress sibling teardowns and provider-internal listProcesses calls receive live data.
  • teardownMissingManagedWorktreeTerminals runtime RPC invalidates the 30s scan cache before revalidating so an external deletion is never masked by a stale hit, and independently re-derives the authoritative flag rather than trusting the renderer.
  • Renderer-side teardownMissingWorktreeTerminalsBestEffort runs per-caller (outside the scan coalescer) and deduplicates concurrent identical requests; non-authoritative scans and disconnected SSH targets are guarded at both layers.

Confidence Score: 5/5

Safe 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.

Important Files Changed

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]"
Loading

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]>
@nwparker

Copy link
Copy Markdown
Contributor Author

Greptile P2 was real — and worse than reported

Greptile flagged the double resolveRepoSelectorForConnection call as redundant work ("harmless because the store doesn't mutate between the two awaits"). I verified it rather than taking the severity at face value, and the redundancy is load-bearing: it can fail the entire sweep. Fixed in 8ff7d13.

Two distinct defects behind that one symptom:

1. An explicit connection identity silently changed the selector grammar. resolveRepoSelectorForConnection matched the selector as a bare repo id:

const repoId = repoSelector.startsWith('id:') ? repoSelector.slice(3) : repoSelector

So on this path alone, path: and name: selectors — valid everywhere else, and accepted by the sibling worktree.detectedList RPC — never match anything. A connection identity should only narrow the candidate set, never reinterpret it.

PROBE result: null err: repo_not_found
PROBE shutdowns: 0

After the fix, the same call resolves and sweeps:

PROBE result: {"stoppedWorktreeIds":["r1::/repo/gone"]}
PROBE shutdowns: 1

2. Re-resolving an already-resolved repo can throw. Teardown rescanned via `id:${repo.id}`. When a repo id is duplicated across hosts (local + SSH — the case this PR's resolveRepoSelectorForConnection exists to handle), that second lookup throws selector_ambiguous even though the caller's original selector was unambiguous. Now it scans via the already-resolved repo through a new listDetectedWorktreesForResolvedRepo seam.

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 src/main/runtime/ + src/renderer/src/store/; typecheck:node, typecheck:web, max-lines ratchet, and oxlint all clean. New regression test resolves non-id selectors when a connection identity is supplied fails on the prior commit with repo_not_found.

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]>

@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: 1

🧹 Nitpick comments (2)
src/renderer/src/store/slices/worktrees.ts (2)

686-690: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Module-level dedup map isn't reset between test runs.

missingWorktreeTeardownsInFlight is process/module-scoped and only cleared once an in-flight promise settles. That's fine in production (one renderer process), but in worktrees.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 | 🔵 Trivial

Teardown latency blocks the whole coalesced refresh, not just the purge of the missing entry.

teardownMissingWorktreeTerminalsBestEffort is awaited before listDetectedWorktreesForRepoCoalesced returns 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

📥 Commits

Reviewing files that changed from the base of the PR and between 25da91d and 609daf4.

📒 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

Comment thread src/main/runtime/orca-runtime.ts Resolved
@nwparker

Copy link
Copy Markdown
Contributor Author

Second Greptile finding also real — fixed in c3a201b

Greptile's "Comments Outside Diff" flagged that withSharedProcessSnapshot passes the proxy as the Reflect.get receiver, so prototype methods invoked through it run with this bound to the proxy. A provider whose own shutdown() re-read state via this.listProcesses() would silently receive this sweep's cached snapshot instead of a live enumeration.

Verified it reproduces:

PROBE listCalls: 1   (1 => shutdown reused the cached snapshot)

A provider that lists twice internally saw only one real call — the batching leaked past the calls it was built for.

Fix: bind non-listProcesses members to target rather than the proxy, so only the sweep's own calls share the snapshot:

PROBE listCalls: 3   (1 shared sweep scan + 2 genuine internal reads)

Greptile suggested a comment; I closed it structurally instead. An implicit constraint documented only in prose is exactly the kind of thing that gets violated later — and the failure mode here is silent (stale rows, no error). The comment now explains why the binding is deliberate rather than asking future maintainers to remember a rule.

No shipped IPtyProvider does this today, so nothing was broken in practice. Pinned by does not serve the shared snapshot to provider-internal listProcesses, which fails on the prior commit (expected 1 to be 3).

Validation: 5076 passed / 5 skipped; typecheck:node, typecheck:web, max-lines ratchet, oxlint all clean.


Both of Greptile's findings were real, and both were things my own two review passes missed — worth recording plainly. Its severity call was off in the first case (labelled redundant work; it could fail the sweep outright), but the findings themselves were sound.

@nwparker

Copy link
Copy Markdown
Contributor Author

Green — ready to merge

Both bot reviews re-ran against c3a201b and came back clean:

Required CI 24/24 pass (e2e skipped — no e2e path changes)
Greptile pass, confidence 5/5 (was 4/5), no new findings
CodeRabbit its one actionable finding was the selector issue, marked ✅ Addressed in commits 8ff7d13 to c3a201b
Mergeable mergeable_state: clean
Local suites 5076 passed, 5 skipped

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

  1. Coalesced callers purged state without requesting teardown — the original [Bug]: Externally deleted worktrees (git worktree remove outside Orca) strand their terminal/agent processes — reconcile paths run no teardown #10562 leak reproduced verbatim (0 teardown RPCs, state purged anyway).
  2. Authoritative recheck read a 30s cache an external git worktree remove never invalidates — and with no retry, the leak was permanent.
  3. O(N) host enumerations per sweep — 30 relay round-trips carrying O(N²) rows for a 30-worktree cleanup, now 1.
  4. Connection scoping silently changed the selector grammar, and re-resolving an already-resolved repo could throw selector_ambiguous on the exact duplicate-id case this PR handles.
  5. Shared snapshot leaked into provider internals via the Proxy receiver — silent stale reads for any provider that re-lists inside shutdown().

Plus two traps inside the perf fix itself, caught by tests written against it (sharing a rejected scan; requirePhysicalStop reading a pre-shutdown snapshot).

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

  • The safety invariant is enforced twice and pinned. Renderer and runtime each independently require an authoritative scan; main's new directSshAuthority gate additionally bails before any refresh when an SSH target is disconnected. never stops terminals for a disconnected SSH target locks that in, so a future change can't regress it into killing PTYs on an unreachable host.
  • The sweep gets exactly one chance. The renderer purges regardless of the teardown result — right for UI responsiveness, but it's what made defect 2 permanent rather than transient. A backstop reconciling on SSH reconnect (cf. fix(ssh): reap orphaned relay PTYs on reconnect before they exhaust the session cap #9820) would add defense in depth. Not blocking.

@nwparker
nwparker merged commit 5f64284 into main Jul 30, 2026
25 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* 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]>
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