Skip to content

perf(worktrees): delete worktree directories after the removal returns - #12416

Merged
brennanb2025 merged 4 commits into
mainfrom
brennanb2025/perf-worktree-removal-async
Aug 4, 2026
Merged

brennanb2025 merged 4 commits into
mainfrom
brennanb2025/perf-worktree-removal-async

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Summary

Deleting a workspace froze on "Deleting…" for 8–35 s. git worktree remove deletes the whole checkout — usually a multi-GB node_modules — synchronously inside the remove IPC, and Orca holds the file-watcher removal gate and PTY teardown for that entire window (prod traces: worktree.remove.git_remove p50 8–14 s, p90 29 s, max 34.7 s over 21 removals; the worst single git.exec was 31.6 s).

Local worktree removal now does the standard two-phase delete:

  1. Every existing preflight runs unchanged (lock check, clean check, PTY sweep, watcher gate, linked-path/symlink removal).
  2. The checkout is renamed into a hidden sibling trash root (<worktree parent>/.orca-worktree-trash/wt-<epoch>-<nonce>) — a metadata operation on the same volume.
  3. Git's registration for the now-missing path is cleared with git worktree remove --force <path> (falls back to git worktree prune + a strict registration re-check if that ever fails).
  4. The moved tree is deleted in the background, one at a time, after the IPC has returned.
  5. Leftovers from a crash or a quit mid-delete are swept at startup, scoped to the trash roots under known local workspace roots and only for entries matching the generated wt-<digits>-<8 hex> name.

Anything that cannot be renamed falls back to the previous in-place removal with no behavior change: WSL-hosted checkouts (deleted inside the distro), cross-volume paths (EXDEV), Windows open handles (EPERM/EBUSY), and dirty checkouts. recoverLocalWindowsWorktreeRemoval is untouched and still covers the Windows partial-removal path. The SSH/remote provider path and folder workspaces are untouched.

Return payloads, branch deletion (worktree.remove.branch_delete), and all error messages are unchanged. One new span stage, worktree.remove.trash_rename, was added to WorktreeRemoveStage.

Measured before/after

Fixture: scratch repo + worktree holding a committed 100 000-file tree (200 dirs × 500 files), generated programmatically by src/main/git/worktree-removal-large-tree.bench.test.ts (opt-in via ORCA_WORKTREE_REMOVAL_BENCH=1). Baseline measured on the parent commit with the same fixture and harness. macOS/APFS.

user-visible removeWorktree background deletion
Before (parent commit) 6755 ms / 6419 ms — (inline)
After 272 ms / 256 ms / 160 ms 3388 ms / 4019 ms / 2287 ms, after the call returned

~25–40× faster for the user; the recursive delete demonstrably completes afterwards (the bench asserts the trash root is empty once the queue settles). Startup sweep: sweepStaleWorktreeTrash is verified against a simulated leftover trash directory in both src/main/worktree-trash.test.ts and the real-Git suite.

The ~160–270 ms that remains is the cleanliness probe: git worktree remove re-checks the worktree at removal time, so the rename path re-proves the same thing with git status --porcelain --untracked-files=all before moving anything. That check is what Git itself was already running, so it is not new work on the fast path — but on a fallback removal (WSL excepted, which returns before the probe) it is now run twice. That was the deliberate trade: dropping it would let a file written between the IPC preflight and the removal be trashed silently.

Screenshots

No visual change.

Testing

  • npx oxlint on all changed files (clean), plus the pre-commit oxlint + react-doctor + oxfmt gates
  • pnpm run tc
  • pnpm exec vitest run --config config/vitest.config.ts src/main/git/ src/main/worktree-trash.test.ts src/main/ipc/worktrees.test.ts src/main/local-worktree-removal-recovery.test.ts src/main/local-worktree-filesystem.test.ts — 964 passed
  • Real-Git compatibility matrix: src/shared/git-binary-compatibility.test.ts run against Git 2.38.1 and 2.49.1 images locally (CI also runs 2.25.5); the new case proves worktree remove --force deregisters a renamed-away worktree. Manually verified the same on 2.24.4 and 2.26.3 containers, which bracket the 2.25 baseline.
  • ORCA_WORKTREE_REMOVAL_BENCH=1 benchmark, before and after (numbers above)
  • pnpm build — not run (no bundling-relevant change)
  • New tests, and verified they fail on the parent commit where behavior differs

New/updated coverage:

  • src/main/git/worktree-deferred-removal-real-git.test.ts (real Git binary): registration cleared and git worktree list no longer shows the path; sibling worktrees stay registered; branch deletion identical; a dirty checkout is never renamed aside; startup sweep removes leftover trash. The first case fails on the parent commit (no trash root is ever created there) — verified by stashing the source change and re-running.
  • src/main/git/remove-worktree.test.ts: rename-then-deregister taken on success; prune fallback when deregistration fails; restore + in-place removal when the registration survives pruning; in-place removal when the rename is unavailable (the Windows EPERM / cross-volume shape); dirty checkout never renamed; WSL never renamed.
  • src/main/worktree-trash.test.ts: rename/restore semantics, background deletion, sweep removes only generated entry names (a stray directory, a stray file, live worktrees and deeper trash roots all survive), and sweep-root derivation skips SSH repos and folder workspaces.
  • Full src/main suite: the only failures are 13 pre-existing local false reds in pty.test.ts / updater.test.ts / worktree-base-directory-poller.test.ts — confirmed identical on origin/main with the same command.

src/main/ipc/worktrees.test.ts mocks removeWorktree wholesale, so it needed no new cases: the change lives entirely below that seam, and its existing 200+ cases (including the removal span-stage assertions) pass unchanged.

AI Review Report

Self-review focused on: safety-gate preservation, Git-version compatibility, cross-platform path/rename semantics, and blast radius of the sweep.

  • Cleanliness gate. The rename must not bypass the check Git performs at removal time, so the fast path re-proves cleanliness and declines (falling through to the untouched in-place path) if that check throws for any reason. That keeps orphan-worktree handling working: a corrupt/missing checkout still errors out of git worktree remove exactly as before, and the IPC's isOrphanedWorktreeError recovery still fires.
  • Git compatibility. git worktree remove --force on a missing directory was verified to succeed and to touch only the targeted entry on 2.24.4, 2.26.3, 2.38.1 and 2.49.1 — it works at and below the 2.25 baseline, so no GitCapabilityCache capability was added; a plain try/prune fallback with a strict registration re-check covers any binary that behaves differently. The boundary is now asserted in the real-binary CI contract.
  • Cross-platform. All paths use path.join/dirname; the trash root is always the worktree's own parent, so the rename never crosses a volume by construction. Windows EPERM/EBUSY from open handles and EXDEV both resolve to "deferral unavailable" → previous behavior; background deletion reuses removeHostTree, which already carries the Windows transient-retry contract. WSL returns before the probe so nothing renames a distro-owned path from the Windows side. No shortcuts, labels, or UI touched.
  • Failure atomicity. If the registration cannot be cleared, the directory is renamed back and the original in-place removal runs, so a partial failure leaves the worktree exactly as Git registered it. If the restore itself fails, the underlying error is thrown rather than a success being reported.
  • Watcher interaction. The base-directory poller only reacts to <worktree>/.git creation and <worktree> deletion, so the trash root (kept in place, never deleted) produces no structural rescans, and the background deletion happens under a name no watcher or PTY can be spawned into.

Security Audit

  • Path handling. No user input reaches the trash path: the root is derived from the worktree's parent directory and the entry name is wt-<Date.now()>-<4 random bytes hex>. Nothing is interpolated into a shell — Git is invoked through the existing execFile-based runner with argument arrays.
  • Deletion blast radius. The background delete only ever targets a path this process just created by rename. The startup sweep is bounded three ways: only the trash roots at, or one level under, workspace roots of local git repos; only entries matching ^wt-\d+-[0-9a-f]{8}$; at most 200 repo containers per root. Stray files/directories inside a trash root are left alone (asserted in tests). fs.rm does not traverse symlinks, so a planted symlink inside a trash root cannot redirect the delete.
  • Privilege/secrets. No new IPC surface, no new permissions, no credentials or secrets touched; warnings log paths only, matching the surrounding removal logging.
  • Follow-up. None identified.

Notes

  • A hidden .orca-worktree-trash directory now persists (empty) beside worktrees after the first deletion in a repo. Removing it on drain would fire a spurious structural rescan in the workspace-root poller, which is exactly the churn this PR reduces, so it is deliberately left in place.
  • The trashed tree occupies disk for a few seconds longer than before, since deletion no longer completes before the IPC returns.
  • Windows and WSL were reasoned about and covered by the fallback path and unit tests, but not live-tested on this change; the fallback is the unmodified pre-existing code path.
  • The benchmark file is opt-in (ORCA_WORKTREE_REMOVAL_BENCH=1) and skipped in CI; it exists so the before/after numbers are reproducible.

`git worktree remove` deleted the whole checkout inline, so the remove IPC held the
watcher/PTY gate for the entire recursive delete (prod traces: worktree.remove.git_remove
p50 8-14s, p90 29s, max 34.7s). Local removals now rename the checkout into a hidden
sibling trash root, clear Git's registration for the missing path, and delete the moved
tree in the background. Renames that cannot run (WSL, other volume, Windows open handles)
fall back to the previous in-place removal unchanged.
@coderabbitai

coderabbitai Bot commented Aug 4, 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 Plus

Run ID: 355e475b-5732-4d90-a21f-c3f3c220af84

📥 Commits

Reviewing files that changed from the base of the PR and between 99690aa and df09d69.

📒 Files selected for processing (4)
  • src/main/git/remove-worktree.test.ts
  • src/main/git/worktree.ts
  • src/main/worktree-trash.test.ts
  • src/main/worktree-trash.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • src/main/worktree-trash.ts
  • src/main/git/worktree.ts
  • src/main/git/remove-worktree.test.ts
  • src/main/worktree-trash.test.ts

📝 Walkthrough

Walkthrough

Worktree removal now stages clean checkouts in a sibling trash directory, deregisters them from Git, and deletes staged directories asynchronously. It falls back to inline removal for unsupported or failed staging cases and restores staged paths when deregistration fails. Startup sweeps stale trash entries from eligible workspace roots. Tests cover mocked flows, real Git behavior, Git compatibility, cleanup, and large-tree performance.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 58.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: deferring worktree directory deletion until after removal returns.
Description check ✅ Passed The description covers the required sections with detailed behavior, testing, AI review, security audit, and platform-specific notes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ 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.

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

🧹 Nitpick comments (6)
src/main/worktree-trash.ts (2)

126-144: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider the effect of the container cap on repeated sweeps.

collectExistingTrashRoots caps containers at 200 using the readdir order. If a workspace root holds more than 200 container directories, and the order is stable, the trash roots beyond the cap are never swept. Leftovers there stay on disk permanently.

Two options keep the sweep cheap and still make progress:

  • Skip the cap and only join the candidate names, because building paths is cheap and the cost is dominated by the per-root readdir in sweepStaleWorktreeTrash.
  • Rotate the starting offset per run so later containers are eventually reached.

The name also states existence, but the function does not check it. collectCandidateTrashRoots describes the behavior more exactly.


152-155: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Keep runtime-host repos out of the local trash sweep.

Runtime repos are distinguished by executionHostId; a runtime repo with connectionId: null currently passes this filter and computes a local repo.path workspace root, despite the comment saying sweep roots are only local git repos. Add the same runtime-host/host-qualification exclusion and reuse a shared local-repo predicate.

src/main/git/worktree.ts (1)

1239-1246: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚖️ Poor tradeoff

git worktree prune acts on the whole repository.

The comment at line 1226 correctly notes that worktree remove --force touches one entry. The fallback at line 1239 does not. git worktree prune deregisters every worktree whose directory Git cannot find. If another worktree of the same repo sits on a volume that is temporarily unmounted, and it is not locked, this fallback silently deletes its registration too.

Consider scoping the recovery, for example by running git worktree prune only after confirming that no other registered worktree path is missing, or by preferring git worktree remove --force retries before pruning.

src/main/git/remove-worktree.test.ts (1)

425-474: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a forced-removal case to this group.

The suite covers the clean, dirty, WSL, prune-fallback, and restore paths. It does not cover force === true. On that path tryRemoveWorktreeWithDeferredDirectoryDeletion skips the cleanliness probe and still renames the checkout aside. A test would pin that behavior, because a future guard that requires a clean probe would silently disable deferred removal for forced deletes.

💚 Suggested additional test
it('renames a dirty checkout aside when removal is forced', async () => {
  mockGitCommands({
    'git worktree list --porcelain': {
      stdout: `worktree /repo
HEAD abc123
branch refs/heads/main

worktree /repo-feature
HEAD def456
branch refs/heads/feature/test
`
    },
    'git worktree list --porcelain#2': {
      stdout: `worktree /repo
HEAD abc123
branch refs/heads/main
`
    }
  })
  moveWorktreeDirectoryToTrashMock.mockResolvedValue('/trash/wt-4-abcdef04')

  await removeWorktree('/repo', '/repo-feature', true)

  expect(getGitCalls()).not.toContain('git status --porcelain --untracked-files=all')
  expect(scheduleWorktreeTrashDeletionMock).toHaveBeenCalledWith('/trash/wt-4-abcdef04')
})
src/main/git/worktree.test.ts (1)

26-30: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Set the default resolved value outside the mock factory.

Line 27 configures mockResolvedValue inside the factory expression. It works because mockResolvedValue returns the mock, but it hides the default from readers and it is lost if any suite-wide vi.resetAllMocks() runs. Declare the export plainly and set the default in beforeEach.

♻️ Proposed change
-// Default: the checkout cannot be renamed aside, so removal deletes it in place.
 vi.mock('../worktree-trash', () => ({
-  moveWorktreeDirectoryToTrash: moveWorktreeDirectoryToTrashMock.mockResolvedValue(undefined),
+  moveWorktreeDirectoryToTrash: moveWorktreeDirectoryToTrashMock,
   restoreWorktreeDirectoryFromTrash: vi.fn().mockResolvedValue(true),
   scheduleWorktreeTrashDeletion: vi.fn()
 }))

Then in the existing beforeEach:

// Default: the checkout cannot be renamed aside, so removal deletes it in place.
moveWorktreeDirectoryToTrashMock.mockResolvedValue(undefined)
src/main/git/worktree-removal-large-tree.bench.test.ts (1)

44-52: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Limit the concurrent writeFile calls in the fixture build.

Line 47 starts 500 concurrent writeFile operations per directory. Each one holds a file descriptor, and Node does not throttle them. On a machine with a low soft ulimit -n this fails with EMFILE before the benchmark runs. Write the batch in smaller chunks.

♻️ Proposed change
     for (let dirIndex = 0; dirIndex < FIXTURE_DIRECTORIES; dirIndex += 1) {
       const dir = join(worktreePath, 'node_modules', `pkg-${dirIndex}`)
       await mkdir(dir, { recursive: true })
-      await Promise.all(
-        Array.from({ length: FIXTURE_FILES_PER_DIRECTORY }, (_unused, fileIndex) =>
-          writeFile(join(dir, `file-${fileIndex}.js`), `module.exports = ${fileIndex}\n`)
-        )
-      )
+      for (let start = 0; start < FIXTURE_FILES_PER_DIRECTORY; start += WRITE_BATCH_SIZE) {
+        const size = Math.min(WRITE_BATCH_SIZE, FIXTURE_FILES_PER_DIRECTORY - start)
+        await Promise.all(
+          Array.from({ length: size }, (_unused, offset) => {
+            const fileIndex = start + offset
+            return writeFile(join(dir, `file-${fileIndex}.js`), `module.exports = ${fileIndex}\n`)
+          })
+        )
+      }
     }

Add the constant beside the existing fixture constants:

const WRITE_BATCH_SIZE = 64

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 02c6f997-9645-4c14-a810-2bbf2974f3b0

📥 Commits

Reviewing files that changed from the base of the PR and between 50594c5 and 5775bbc.

📒 Files selected for processing (10)
  • src/main/git/remove-worktree.test.ts
  • src/main/git/worktree-deferred-removal-real-git.test.ts
  • src/main/git/worktree-removal-large-tree.bench.test.ts
  • src/main/git/worktree.test.ts
  • src/main/git/worktree.ts
  • src/main/index.ts
  • src/main/observability/instrumentation.ts
  • src/main/worktree-trash.test.ts
  • src/main/worktree-trash.ts
  • src/shared/git-binary-compatibility.test.ts

Comment on lines +1 to +3
// Manual benchmark for the `worktree.remove.git_remove` stage on a large checkout.
// Opt in (it builds ~100k files): ORCA_WORKTREE_REMOVAL_BENCH=1 pnpm exec vitest run \
// --config config/vitest.config.ts src/main/git/worktree-removal-large-tree.bench.test.ts

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Correct the stage name in the header comment.

The comment names worktree.remove.git_remove. This PR adds the worktree.remove.trash_rename stage, and the benchmark at line 66 measures the whole removeWorktree call rather than one stage.

📝 Proposed change
-// Manual benchmark for the `worktree.remove.git_remove` stage on a large checkout.
+// Manual benchmark for user-visible `removeWorktree` latency on a large checkout.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Manual benchmark for the `worktree.remove.git_remove` stage on a large checkout.
// Opt in (it builds ~100k files): ORCA_WORKTREE_REMOVAL_BENCH=1 pnpm exec vitest run \
// --config config/vitest.config.ts src/main/git/worktree-removal-large-tree.bench.test.ts
// Manual benchmark for user-visible `removeWorktree` latency on a large checkout.
// Opt in (it builds ~100k files): ORCA_WORKTREE_REMOVAL_BENCH=1 pnpm exec vitest run \
// --config config/vitest.config.ts src/main/git/worktree-removal-large-tree.bench.test.ts
🧰 Tools
🪛 ast-grep (0.45.0)

[warning] 3-3: Importing child_process exposes a command-execution surface; ensure any command/argument built from input is validated, and prefer execFile/spawn with an argument array over exec.
Context: import { execFile } from 'node:child_process'
Note: [CWE-78] Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection').

(detect-child-process-typescript)

Comment thread src/main/index.ts
Comment on lines +2599 to +2603
void sweepStaleWorktreeTrash(
collectWorktreeTrashSweepRoots(store.getRepos(), store.getSettings())
).catch((error) => {
console.warn('[worktrees] Failed to sweep leftover worktree directories:', error)
})

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 | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect the enclosing function and any narrowing of `store` before the sweep call.
fd -t f 'index.ts' src/main --max-depth 1 | while IFS= read -r file; do
  sed -n '2520,2610p' "$file"
done
rg -nP '"strict(NullChecks)?"\s*:' -g 'tsconfig*.json'

Repository: stablyai/orca

Length of output: 4280


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="$(fd -t f '^index\.ts$' src/main --max-depth 1 | head -n 1)"
sed -n '2450,2545p' "$file"
sed -n '300,325p' "$file"

printf '\n--- tsconfig strict settings ---\n'
for f in $(git ls-files 'tsconfig*.json'); do
  echo "# $f"
  rg -n '"strict(NullChecks)?"\s*:' "$f" || true
done

printf '\n--- direct store null checks before call ---\n'
python3 - <<'PY'
from pathlib import Path
p=next(Path('src/main').glob('index.ts'))
lines=p.read_text().splitlines()
for i,l in enumerate(lines,1):
    if 'let store:' in l:
        print(f"{i}: {l}")
    if 'collectWorktreeTrashSweepRoots(store.getRepos(), store.getSettings())' in l:
        for n in range(max(1,i-180), i+1):
            print(f"{n}: {lines[n-1]}")
        print(f"CALL_LINE={i}")
PY

Repository: stablyai/orca

Length of output: 15248


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="$(fd -t f '^index\.ts$' src/main --max-depth 1 | head -n 1)"
ast-grep outline "$file" --match 'app.isPackaged|function |const |export' --view compact | sed -n '1,220p'

printf '\n--- relevant enclosing declarations around store ---\n'
sed -n '2450,2615p' "$file"

printf '\n--- tsconfig strict settings ---\n'
while IFS= read -r f; do
  echo "# $f"
  rg -n '"strict(NullChecks)?"\s*:' "$f" || true
done < <(git ls-files 'tsconfig*.json')

Repository: stablyai/orca

Length of output: 302


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="$(fd -t f '^index\.ts$' src/main --max-depth 1 | head -n 1)"

printf '%s\n' '# tsconfig files'
git ls-files 'tsconfig*.json'

printf '%s\n' '# each tsconfig top-level non-auto-extracted strict flags'
python3 - <<'PY'
import json, glob
for f in sorted(glob.glob('tsconfig*.json')):
    print(f"## {f}")
    txt=open(f).read().splitlines()
    for i,l in enumerate(txt,1):
        s=l.strip()
        if s.startswith('"strict'):
            print(f"{i}: {s}")
PY

printf '%s\n' '# enclosing scopes and control-flow between store declaration and sweep call'
python3 - <<'PY'
from pathlib import Path
import re
p=next(Path('src/main').glob('index.ts'))
lines=p.read_text().splitlines()
store_line=None
sweep_line=None
for i,l in enumerate(lines,1):
    if 'let store:' in l: store_line=i
    if 'collectWorktreeTrashSweepRoots(store.getRepos(), store.getSettings())'  in l: sweep_line=i
print(f"store_line={store_line}, sweep_line={sweep_line}")
if store_line and sweep_line:
    block=[]
    for n in range(store_line, sweep_line+1):
        tag=[]
        if 'function ' in lines[n-1] or '=> ' in lines[n-1] or '{' in lines[n-1] or '}' in lines[n-1] or 'if ' in lines[n-1] or 'while ' in lines[n-1] or 'store' in lines[n-1]:
            tag='#'
        print(f"{n:4} {tag} {lines[n-1]}")
PY

printf '%s\n' '# explicit Store-null checks between declaration and sweep call'
python3 - <<'PY'
from pathlib import Path
p=next(Path('src/main').glob('index.ts'))
lines=p.read_text().splitlines()
store_line=None
sweep_line=None
for i,l in enumerate(lines,1):
    if 'let store:' in l: store_line=i
    if 'collectWorktreeTrashSweepRoots(store.getRepos(), store.getSettings())'  in l: sweep_line=i
query=[]
for n in range(store_line or 1, sweep_line or len(lines)+1):
    if re.search(r'\bstore\b', lines[n-1]) and re.search(r'(==|!==|=|getRepos\(|getSettings\(|onSettingsChanged\()', lines[n-1]):
        query.append((n, lines[n-1]))
print(query)
PY

Repository: stablyai/orca

Length of output: 50370


Add a null guard before the first direct store property access.

store is only declared as Store | null; the subsequent direct call on line 2600 is no longer controlled by the null-check. Use store!.getSettings(...) consistently with the other asserted accesses in this function, or add an explicit guard before this code path.

@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 Plus

Run ID: 92905db2-b7d5-4540-9624-d27bf4c27d9a

📥 Commits

Reviewing files that changed from the base of the PR and between 5775bbc and 99690aa.

📒 Files selected for processing (4)
  • src/main/git/remove-worktree.test.ts
  • src/main/git/worktree.ts
  • src/main/worktree-trash.test.ts
  • src/main/worktree-trash.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/git/remove-worktree.test.ts
  • src/main/worktree-trash.ts
  • src/main/worktree-trash.test.ts

Comment thread src/main/git/worktree.ts Resolved
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Electron QA evidence — macOS, CDP, df09d69e7c

  • Created a disposable local repo/worktree through the running dev app.
  • Confirmed deletion through the real Delete Workspace dialog.
  • Verified the row disappeared, Git no longer listed the worktree, the checkout path was removed, and the deferred trash queue drained to an empty root.
  • 100,000-file benchmark: removeWorktree returned in 420 ms; recursive deletion finished in 4,264 ms afterward.

Before deletion

pr-12416-worktree-before-delete.png

Confirmation

pr-12416-worktree-delete-confirmation.png

After deletion

pr-12416-worktree-after-delete.png

@brennanb2025
brennanb2025 merged commit 9deee5a into main Aug 4, 2026
42 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
stablyai#12416)

* perf(worktrees): delete worktree directories after the removal returns

`git worktree remove` deleted the whole checkout inline, so the remove IPC held the
watcher/PTY gate for the entire recursive delete (prod traces: worktree.remove.git_remove
p50 8-14s, p90 29s, max 34.7s). Local removals now rename the checkout into a hidden
sibling trash root, clear Git's registration for the missing path, and delete the moved
tree in the background. Renames that cannot run (WSL, other volume, Windows open handles)
fall back to the previous in-place removal unchanged.

* test(worktrees): keep no empty trash root when the rename cannot run

* fix(worktrees): harden deferred trash cleanup

* fix(worktrees): keep WSL trash on its owning host
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.

1 participant