Skip to content

fix(worktree): don't let a WSL selector_not_found abort worktree deletion (#9197) - #9601

Closed
OrcaWin wants to merge 2 commits into
stablyai:mainfrom
OrcaWin:OrcaWin/fix-9197-wsl-worktree-delete
Closed

OrcaWin wants to merge 2 commits into
stablyai:mainfrom
OrcaWin:OrcaWin/fix-9197-wsl-worktree-delete

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Jul 20, 2026

Copy link
Copy Markdown
Collaborator

Problem — Fixes #9197

Deleting a worktree in a WSL-runtime project fails with
Error invoking remote method 'worktrees:remove': Error: selector_not_found
and leaves the worktree half-deleted. Triggers when the project lives at
\wsl.localhost\Ubuntu\... with worktrees under \wsl.localhost\Ubuntu\root\orca\workspaces.

Root cause (code-verified)

Destructive removal runs stopPtysForDestructiveWorktreeRemoval →
killAllProcessesForWorktree(worktreeId) → the runtime sweep
runtime.stopTerminalsForWorktree(worktreeId) →
resolveWorktreeSelector(worktreeId), which resolves the selector before
touching any PTY.

  • killAllProcessesForWorktree passes the raw composite id (repoId::path, no
    id:/path: prefix), so resolveWorktreeSelector falls to the exact-string
    else-branch (worktree.id === selector, orca-runtime.ts).
  • Every other comparator in the removal path is normalization-tolerant (it folds
    the \wsl.localhost ↔ \wsl$ UNC aliases + distro casing), so the removal
    preflight matches and the delete begins — then the exact id-match misses
    and resolveWorktreeSelector throws selector_not_found.
  • The teardown fail-closes on every error except runtime_unavailable
    (worktree-teardown.ts), so that throw propagates and aborts the whole delete.

A slow WSL git worktree list exceeding RESOLVED_WORKTREE_REPO_TIMEOUT_MS
(degrades to an empty list) reproduces the same asymmetry. Distinct from #9045,
which fails later at the PTY-kill gate.

Fix

The runtime sweep only stops renderer-graph terminals. If the runtime can't
resolve the worktree at all, there are simply no such terminals to stop — that
must never fail-close a destructive delete. So selector_not_found is treated as
benign there, exactly like runtime_unavailable (matching existing precedent that
already swallows selector_not_found elsewhere in orca-runtime.ts).

Safety is preserved: the independent provider sweep (which also matches PTYs by
cwd-inside-worktree, tolerant of the UNC aliasing) and registry sweep, plus the
requirePhysicalStop gate, remain the proof that any PTY that truly exists was
physically stopped. The invariant ("nothing to stop must never abort a delete")
holds on native/SSH too, so those paths are untouched — a generic runtime-sweep
error still fails closed.

-        (error) => !(error instanceof Error && error.message === 'runtime_unavailable')
+        (error) => !isBenignRuntimeSweepError(error)   // runtime_unavailable OR selector_not_found

Reproduction & verification

A live slow-WSL Electron host is impractical to drive deterministically, so — as the
issue's own repro note allows — this uses a focused unit reproduction that forces
the exact failure mode: the runtime sweep rejects with selector_not_found under
requirePhysicalStop, using a \wsl.localhost composite id.

  • Red (before): the new test throws Error: selector_not_found — the destructive
    teardown aborts (reproduces [Bug]: Cannot delete worktree in WSL environment (selector_not_found) #9197).
  • Green (after): the delete completes, runtimeStopped: 0, and the provider sweep
    still tears down the live PTY (providerStopped: 1).
  • Full worktree-teardown.test.ts suite: 22/22 pass. oxlint clean;
    tsc -p config/tsconfig.node.json clean.

Trade-offs / user-visible changes

None beyond the fix: WSL worktree deletion now completes instead of aborting with
selector_not_found. No behavior change for native or SSH removal. A live WSL
Electron end-to-end pass is still worth a maintainer's confirmation before merge.

…tion (stablyai#9197)

Deleting a worktree in a WSL-runtime project failed with
`selector_not_found` and left it half-deleted.

Destructive removal runs `killAllProcessesForWorktree`, whose runtime
sweep calls `stopTerminalsForWorktree(worktreeId)` →
`resolveWorktreeSelector(worktreeId)`. That resolves the selector before
touching any PTY. Passed a raw composite id (no `id:`/`path:` prefix), it
falls to the exact-string else-branch (`worktree.id === selector`). On
WSL the removal preflight matches tolerantly (folding the
`\wsl.localhost` ↔ `\wsl$` UNC aliases + distro casing, so the delete
begins), but the exact id-match then misses and throws
`selector_not_found`. The teardown fail-closes on every error except
`runtime_unavailable`, so that throw aborted the whole delete. A slow WSL
`git worktree list` degrading to an empty list reproduces the same
asymmetry.

The runtime sweep only stops renderer-graph terminals; "no worktree
resolved" just means there are none to stop, which must never fail-close
a delete. Treat `selector_not_found` as benign there, exactly like
`runtime_unavailable`. The independent provider (cwd-tolerant) and
registry sweeps plus the physical-stop gate remain the proof that any PTY
that truly exists was stopped, so this does not weaken teardown. The
invariant holds on native/SSH too, so those paths are untouched.

Regression test drives the runtime sweep to reject with
`selector_not_found` under `requirePhysicalStop` and asserts the delete
still completes while the provider sweep tears down a live PTY.

Fixes stablyai#9197
@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 944d6f79-c93c-4806-962a-88dc4b09ebf7

📥 Commits

Reviewing files that changed from the base of the PR and between 59ae062 and 6bbd970.

📒 Files selected for processing (1)
  • src/main/runtime/worktree-teardown.test.ts

📝 Walkthrough

Walkthrough

Updated worktree teardown error handling to treat selector_not_found as benign alongside runtime_unavailable. Added tests verifying that runtime shutdown can report zero stopped processes while the provider stops the worktree’s PTY, and that provider physical-stop failures still reject teardown.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the WSL selector_not_found worktree-deletion fix.
Description check ✅ Passed It covers the required content in substance, including summary, testing, AI review, audit, and notes, though it doesn't follow the template verbatim.
Linked Issues check ✅ Passed The code and tests address the WSL deletion failure caused by selector_not_found and preserve the physical-stop invariant for [#9197].
Out of Scope Changes check ✅ Passed Only targeted teardown logic and regression tests changed; no unrelated features or broad refactors are introduced.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 261fe937-7db1-4fa5-93bd-bd2ccabb8054

📥 Commits

Reviewing files that changed from the base of the PR and between 99df415 and 59ae062.

📒 Files selected for processing (2)
  • src/main/runtime/worktree-teardown.test.ts
  • src/main/runtime/worktree-teardown.ts

Comment on lines +591 to +607
const stopTerminalsForWorktree = vi.fn().mockRejectedValue(new Error('selector_not_found'))
const runtime = {
stopTerminalsForWorktree
} as unknown as Parameters<typeof killAllProcessesForWorktree>[1]['runtime']
const localProvider = createProviderStub(async () => [
{ id: `${worktreeId}@@live-1`, cwd: '/wsl/wt', title: 'shell' }
])
listRegisteredPtysMock.mockReturnValue([])

const result = await killAllProcessesForWorktree(worktreeId, {
runtime,
localProvider,
requirePhysicalStop: true
})

expect(result.runtimeStopped).toBe(0)
expect(result.providerStopped).toBe(1)

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the implementation and nearby tests relevant to killAllProcessesForWorktree.
echo "== file list =="
git ls-files 'src/main/runtime/*worktree*'

echo
echo "== outline of implementation and test file =="
ast-grep outline src/main/runtime/worktree-teardown.ts --view expanded || true
echo "---"
ast-grep outline src/main/runtime/worktree-teardown.test.ts --view expanded || true

echo
echo "== relevant implementation slice =="
nl -ba src/main/runtime/worktree-teardown.ts | sed -n '1,260p'

echo
echo "== relevant test slice =="
nl -ba src/main/runtime/worktree-teardown.test.ts | sed -n '520,660p'

Repository: stablyai/orca

Length of output: 1299


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Search for existing assertions on stopTerminalsForWorktree to judge duplication/coverage.
rg -n "stopTerminalsForWorktree|killAllProcessesForWorktree|selector_not_found|runtimeStopped|providerStopped" src/main/runtime/worktree-teardown.test.ts src/main/runtime/worktree-teardown.ts

Repository: stablyai/orca

Length of output: 9581


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== implementation around runtime call =="
sed -n '75,130p' src/main/runtime/worktree-teardown.ts

echo
echo "== tests around runtime call and benign-error cases =="
sed -n '300,380p' src/main/runtime/worktree-teardown.test.ts

echo
echo "== tests around selector_not_found case =="
sed -n '548,616p' src/main/runtime/worktree-teardown.test.ts

Repository: stablyai/orca

Length of output: 8123


Assert the runtime call in the selector_not_found case. The current result checks still pass if killAllProcessesForWorktree skips runtime.stopTerminalsForWorktree entirely here. Add an assertion that stopTerminalsForWorktree was called with worktreeId and the expected options so this test covers the benign-error branch.

@OrcaWin

OrcaWin commented Jul 21, 2026

Copy link
Copy Markdown
Collaborator Author

Did a deep review of this fix (logic + regression tests + native/SSH impact). It holds up well — the core reasoning is sound:

  • Swallowing selector_not_found cannot orphan a live PTY. stopTerminalsForWorktree calls resolveWorktreeSelector before enumerating any leaves, so when resolution throws there are literally zero renderer-graph terminals it could have stopped — nothing is skipped. The provider and registry sweeps operate on the raw worktreeId string (they never go through resolveWorktreeSelector), so they remain the physical-stop proof for any PTY that truly exists, and the requirePhysicalStop gate over stopAttempts still fails the delete closed if any provider/registry-visible PTY can't be stopped. When requirePhysicalStop is set, provider.listProcesses() is still un-caught (failClosed=true), so a wedged provider list also fails closed — untouched by this change.
  • Narrowly scoped. Only selector_not_found and runtime_unavailable are treated benign; selector_ambiguous and every other error still fail-close. Good.
  • Native & SSH unaffected. Those ids resolve normally, so the new branch never triggers; even in the rare "git no longer lists the worktree" case, the provider sweep still covers it. This also nicely mirrors the existing tolerance already in resolveWorktreeRemovalTarget, which treats selector_not_found as recoverable for removal — the teardown was the one place that hadn't caught up.

One change I pushed (6bbd970be): added a regression test that locks the invariant the fix depends on — when selector_not_found is swallowed and a real provider-visible PTY refuses to stop, the destructive delete must still fail closed (Failed to physically stop every PTY). The original test only exercised the happy path where the provider succeeds; this guards against a future change accidentally letting the swallow bypass the physical-stop guarantee.

Full worktree-teardown suite (23 tests) + typecheck are green. No production-code changes needed. Residual risk is low and pre-existing: if a PTY were ever spawned under a different UNC-alias id form than the deletion target, all three sweeps (including the old runtime sweep) would miss it equally — this fix neither introduces nor worsens that. LGTM. 🚢

@nwparker

Copy link
Copy Markdown
Contributor

Closing as superseded — main already carries this exact fix.

What happened

The production change in this PR is the runtime-sweep predicate in src/main/runtime/worktree-teardown.ts, treating selector_not_found as benign alongside runtime_unavailable. That same predicate landed on main in 5786513 (#9625, merged 2026-07-21T01:18Z, ~17h before the last push here) as one of six e2e-flake fixes, under the description "Tolerate selector_not_found during destructive worktree removal."

The two changes are semantically identical — same two error messages, same instanceof Error guard, same call site. This PR factors it into a named isBenignRuntimeSweepError helper; #9625 inlines it. No behavioral difference.

Verified, not assumed

I grafted this PR's own WSL reproduction tests (the \\wsl.localhost composite id, requirePhysicalStop: true) onto unmodified main and ran them:

$ git checkout origin/main -- src/main/runtime/worktree-teardown.ts
$ npx vitest run --config config/vitest.config.ts src/main/runtime/worktree-teardown.test.ts
 Test Files  1 passed (1)
      Tests  28 passed (28)

Against this PR's base commit (ccd72f5909), the same tests fail with the exact #9197 symptom:

 × WSL selector_not_found does not abort a destructive delete (#9197)
   Error: selector_not_found
 × WSL selector_not_found still fails closed when a provider PTY refuses to stop (#9197)
   AssertionError: expected [Function] to throw error including
   'Failed to physically stop every PTY' but got 'selector_not_found'
 Tests  6 failed | 22 passed (28)

So the repro is valid and main genuinely fixes it — this isn't a "looks similar" judgment call.

Why not just merge it anyway

Rebasing would be a net regression risk rather than a no-op. main has moved 428 commits past this branch, and worktree-teardown.ts conflicts (git merge-tree confirms). This branch's copy of the file predates #10252, which added the cwdFallbackPath guard to sweepProviderByPrefix — that guard stops a folder-workspace instance deletion from sweeping sibling instances' PTYs. Resolving the conflict toward this branch would silently drop it.

Note on the root-cause analysis

The write-up in this PR and in #9197 is careful and correct, and worth preserving for anyone who hits this again: selector_not_found here is Orca's own error from resolveWorktreeSelector, not anything wsl.exe emits. The WSL angle is that killAllProcessesForWorktree passes the raw repoId::path composite id, forcing the exact-string match branch, while every other comparator on the removal path folds the \\wsl.localhost ↔ \\wsl$ UNC aliases — so the preflight matches, deletion begins, and the exact match then misses. Since the call is in-process (no RPC error wrapping between stopTerminalsForWorktree and the predicate), the exact-string match is a sound way to catch it.

The underlying id-normalization asymmetry is not fixed by either patch — both only stop it from aborting the delete. Worth a separate issue if it resurfaces elsewhere.

Salvageable

One test here covers a combination main doesn't: selector_not_found swallowed and a provider-visible PTY refusing to stop must still fail closed with Failed to physically stop every PTY. main has a fail-closed test for the wedged-daemon-RPC case (#9500) but not this pairing. It locks the invariant the swallow depends on. Happy to land it standalone if a maintainer wants it.

Thanks @OrcaWin — the diagnosis was right and independently arrived at the same fix that shipped; it just lost a race by about half a day.

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]: Cannot delete worktree in WSL environment (selector_not_found)

2 participants