Skip to content

feat(worktree): reuse an existing branch when creating a worktree (#5181) - #5781

Merged
nwparker merged 4 commits into
mainfrom
nwparker/feature-create-new-worktree-with-existing-branch
Jun 19, 2026
Merged

nwparker merged 4 commits into
mainfrom
nwparker/feature-create-new-worktree-with-existing-branch

Conversation

@nwparker

@nwparker nwparker commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #5181 — adds an explicit, discoverable way to reuse an existing branch when creating a worktree, instead of always creating a new branch from it.

When you select an existing local branch in the new‑worktree composer, a "Reuse branch" checkbox appears directly under the branch selection (defaults on). With it checked, Orca checks that branch out into the new worktree; unchecking it creates a fresh branch from the selected ref as base.

Why it's valid

A checkoutExistingBranch path shipped in #2543, but it was implicit: reuse only triggered when the auto‑filled worktree name stayed equal to the branch, and editing the worktree name silently reverted to "create a new branch" with no feedback. There was no discoverable control — the reporter filed this 3 weeks later saying it was "impossible." This PR makes it explicit and durable.

Approach (renderer‑only)

Picking an existing local branch already sets baseBranch === branchNameOverride === <branch>, so the existing backend reuse path (git worktree add <path> <branch>, preserveBranchOnDelete) checks the branch out across local, SSH, and runtime — no backend/IPC/schema changes. The checkbox pins that override via the existing branchNameOverridePreservesNameEdits flag so reuse survives renaming the worktree folder (the folder name lives in Advanced and can differ from the branch).

UX details

  • The checkbox sits under the branch (smart) field, labelled "Reuse branch", visible without expanding Advanced.
  • Dynamic eligibility: hidden for remote‑only refs (origin/…) and for a branch already checked out in another worktree (git allows a branch in only one worktree). When a busy branch is picked, the override isn't pinned, so creation cleanly falls back to a new branch from that ref.
  • The row collapses via a grid‑rows transition (matching the Advanced drawer) so the dialog height changes smoothly when the option appears/disappears.

Verification

  • Real‑git proof of diverged‑branch reuse into an independently‑named folder; pure helpers (resolveComposerBranchReuse, isBranchCheckedOutInWorktrees, resolveComposerReuseOverride) unit‑tested; component render tests (checkbox shown/collapsed, both‑direction toggle); backend integration test (renamed folder still reuses → checkoutExistingBranch + preserveBranchOnDelete).
  • Full typecheck (node/cli/web), oxlint, localization catalog all clean; no regressions.
  • Verified live in an Electron dev build; screenshots in the PR comments.
  • Multi‑dimensional review run to clean (6 low‑severity nits found and fixed: state resets on repo/project switch, collapsed‑checkbox disabled, override‑helper extraction + tests).

)

Adds an explicit "Reuse this branch" checkbox to the new-worktree composer.
When an existing local branch is selected in the smart name field, the
checkbox (default on) checks that branch out instead of creating a new
branch from it — and the choice now survives renaming the worktree folder.

Previously, reusing an existing branch only worked implicitly: it required
keeping the auto-filled worktree name equal to the branch, and editing the
name silently reverted to "create a new branch". There was no discoverable,
durable control — the gap the issue reports.

The fix is renderer-only: picking an existing local branch already sets
baseBranch === branchNameOverride, so the existing backend reuse path
(`git worktree add <path> <branch>`, preserveBranchOnDelete) checks the
branch out correctly across local/SSH/runtime. The checkbox pins that
override via the existing branchNameOverridePreservesNameEdits flag so the
worktree folder can be named independently while the branch is reused;
unchecking creates a fresh branch from the selected ref as base.

- New pure helper resolveComposerBranchReuse (local-vs-remote + default).
- Checkbox hidden for remote-only refs and non-branch sources.
- Tests: pure helper, card render/toggle, and a backend integration test
  proving a renamed folder still reuses the exact branch.
@ghost

ghost commented Jun 19, 2026 •

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 5 individual chapters for you:

Title
1 Define branch reuse logic and helpers
2 Manage branch reuse state in composer hook
3 Add reuse checkbox to composer UI
4 Add localization for reuse strings
5 Verify branch reuse in integration tests
Open in Stage

Chapters generated by Stage for commit dbba976 on Jun 19, 2026 9:42am UTC.

@nwparker

Copy link
Copy Markdown
Contributor Author

Verification evidence

1. Real git: reusing a diverged branch into an independently‑named folder

The core capability — git worktree add <folder> <branch> checks out the exact branch at its own tip, even though it has diverged from main, and the folder name is unrelated to the branch:

$ git worktree add ../wt-another feature-x
Preparing worktree (checking out 'feature-x')
worktree folder: wt-another | checked-out branch: feature-x
worktree HEAD = 707833c…   feature-x = 707833c…   main = 589ff7d… (diverged → not used)

This is exactly what the composer produces when "Reuse this branch" is checked: baseBranch === branchNameOverride === feature-x, so the existing backend reuse path runs.

2. Automated tests (project vitest config)

$ npx vitest run --config config/vitest.config.ts \
    src/renderer/src/hooks/composer-branch-selection.test.ts \
    src/renderer/src/components/NewWorkspaceComposerCard.test.tsx \
    src/main/ipc/worktrees.test.ts

 Test Files  3 passed (3)
      Tests  157 passed (157)

Covering:

  • resolveComposerBranchReuse (pure): local branch → eligible + default on; slash‑named local branch → eligible; remote‑only origin/foo → not eligible (checkbox hidden); custom worktree name → eligible but default off.
  • NewWorkspaceComposerCard (renders the real production component): the checkbox appears only when a local branch is reusable, shows the label + hint, and toggling it fires onReuseSelectedBranchChange(false).
  • worktrees.test.ts (backend contract): creating with name: 'my-folder', baseBranch: 'fix/bug-0', branchNameOverride: 'fix/bug-0' calls addWorktree(…, 'fix/bug-0', 'fix/bug-0', false, false, { checkoutExistingBranch: true }) and stamps preserveBranchOnDelete: true — i.e. a renamed folder still reuses the exact branch.

3. No regressions

renderer hooks + composer suites … 204 passed
worktrees.test.ts ……………………………… 144 passed

4. Static checks

  • pnpm run typecheck (node + cli + web) — clean
  • oxlint on changed files — clean
  • verify:localization-catalog + verify:localization-coverage — clean

@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR introduces a "Reuse this branch" checkbox in the workspace composer UI. Three new shared functions in composer-branch-selection.ts determine whether a selected branch ref matches an existing local branch, whether reuse should default to enabled, and whether to suppress the branch override when the branch is checked out elsewhere. The useComposerState hook is extended with reuseEligibleBranch and reuseSelectedBranch state, handlers that update branch name override preservation and auto-name behavior, and reset logic on base branch change, repo change, project change, or smart name clear. NewWorkspaceComposerCard receives three new props and conditionally renders a controlled checkbox with hint text in the main section. Locale files (en, es, ja, ko, zh) receive the two new i18n keys. New tests cover the three shared helper functions, UI checkbox rendering and toggle behavior, and the IPC worktrees:create backend path for existing-branch checkout.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% 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 PR description thoroughly covers the feature, approach, and verification, but is missing several required sections from the template. Add Screenshots section, Testing checklist with all five items marked, AI Review Report (with cross-platform compatibility confirmation), Security Audit section, and Notes section as specified in the template.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary feature: adding the ability to reuse an existing branch when creating a worktree, which is the main objective of this PR.
Linked Issues check ✅ Passed The PR directly addresses issue #5181 by implementing the requested feature: a checkbox in the new worktree dialog to reuse an existing branch instead of always creating a new one, eliminating manual git checkout steps.
Out of Scope Changes check ✅ Passed All changes are directly scoped to the feature: worktree branch reuse helpers, composer state management, UI checkbox, i18n strings, and comprehensive tests. No extraneous modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 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 and usage tips.

@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: 50337285-f5ec-49f9-9348-88f16c46b84d

📥 Commits

Reviewing files that changed from the base of the PR and between b5b018c and 7b1cf97.

📒 Files selected for processing (12)
  • src/main/ipc/worktrees.test.ts
  • src/renderer/src/components/NewWorkspaceComposerCard.test.tsx
  • src/renderer/src/components/NewWorkspaceComposerCard.tsx
  • src/renderer/src/hooks/composer-branch-selection.test.ts
  • src/renderer/src/hooks/composer-branch-selection.ts
  • src/renderer/src/hooks/useComposerState.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/shared/composer-branch-selection.ts

listWorktreesMock
.mockResolvedValueOnce([
{
path: '/workspace/repo',

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use path.join(...) in test paths to keep cross-platform behavior deterministic.

These POSIX-only literals can break on Windows path separators; build expected paths with Node path helpers in mocks and assertions.

Suggested patch
+import path from 'node:path'
...
-          path: '/workspace/repo',
+          path: path.join('/workspace', 'repo'),
...
-          path: '/workspace/repo',
+          path: path.join('/workspace', 'repo'),
...
-          path: '/workspace/my-folder',
+          path: path.join('/workspace', 'my-folder'),
...
-      '/workspace/repo',
-      '/workspace/my-folder',
+      path.join('/workspace', 'repo'),
+      path.join('/workspace', 'my-folder'),
...
-      'repo-1::/workspace/my-folder',
+      `repo-1::${path.join('/workspace', 'my-folder')}`,
...
-        path: '/workspace/my-folder',
+        path: path.join('/workspace', 'my-folder'),

As per coding guidelines: “Use path.join or Electron/Node path utilities for file paths — never assume / or \ for cross-platform compatibility.”

Also applies to: 1046-1046, 1053-1053, 1070-1071, 1079-1079, 1084-1084

Source: Coding guidelines

@nwparker

Copy link
Copy Markdown
Contributor Author

Screenshots — "Reuse this branch" in the new-worktree composer

Captured from a local Orca dev build of this branch (repo orca, existing local branch add-rpm-linux-target).

1. Default — reuse on. Selecting an existing local branch shows the checkbox checked, so the branch is checked out instead of branching off it.

Reuse this branch checked by default

2. Opt out — reuse off. Unchecking creates a new branch from the selected ref as base (prior behavior).

Reuse this branch unchecked

3. The fix — reuse survives a folder rename. Worktree folder renamed to resume-rpm-fix while the branch stays add-rpm-linux-target and reuse stays checked. Before this PR, editing the name silently reverted to "create a new branch."

Reuse persists after renaming the worktree folder

…ility)

Address review feedback on the "Reuse branch" control:

- Move the checkbox directly under the branch (smart) selection instead of the
  Advanced "Name" field — the worktree folder name can legitimately differ from
  the branch, so the choice belongs next to the branch pick and is now visible
  without expanding Advanced.
- Rename the label "Reuse this branch" -> "Reuse branch".
- Make eligibility dynamic: reuse is impossible when the branch is already
  checked out in another worktree (git allows a branch in only one worktree), so
  the checkbox is now hidden in that case (it was already hidden for remote-only
  refs). When a busy branch is picked, the override is no longer pinned to it, so
  creation cleanly falls back to a new branch from that ref as base instead of a
  silently-suffixed branch.

Adds isBranchCheckedOutInWorktrees (pure, unit-tested) and threads the repo's
worktree branch list from the store into the selection logic.
@nwparker

Copy link
Copy Markdown
Contributor Author

Updated per review feedback

Captured from a fresh local dev build of the latest commit. (Supersedes the earlier screenshots — placement + label changed.)

1 + 2 — "Reuse branch" now sits directly under the branch selection (not under the Advanced "Name" field), and is renamed to "Reuse branch". It's visible without expanding Advanced.

Reuse branch checkbox under the branch field

3 — Dynamic: it's only shown when reuse is actually possible. Reuse is impossible when the branch is already checked out in another worktree (git allows a branch in only one worktree), so the checkbox is hidden there (it was already hidden for remote-only refs). Here nwparker/idle-spinner is checked out in another worktree → no checkbox:

No checkbox for a branch checked out elsewhere

Why under the branch, not the name: the worktree folder name is separate (in Advanced) and can differ from the branch. Reuse stays checked even after renaming the worktree to resume-rpm-work:

Reuse stays checked while the worktree name differs

When a busy branch is picked, the branch override is no longer pinned to it, so creation cleanly falls back to a new branch from that ref as base instead of a silently-suffixed branch.

nwparker added 2 commits June 19, 2026 02:28
Keep the "Reuse branch" row mounted and collapse it with a grid-rows
transition (same pattern as the Advanced drawer) instead of conditionally
rendering it, so the create-worktree dialog grows and shrinks smoothly when the
option appears/disappears as the selected branch changes. The checkbox is taken
out of the tab order while collapsed.
From a multi-dimensional review of the branch (all findings low severity):

- Reset reuse state (reuseEligibleBranch, reuseSelectedBranch,
  branchNameOverridePreservesNameEdits) on repo and project switches, matching
  the other reset paths — avoids carrying stale branch-scoped state.
- Disable the reuse checkbox while collapsed so no focusable control lives
  inside the aria-hidden row.
- Extract the busy-branch override decision into a pure resolveComposerReuseOverride
  helper and unit-test it (busy local branch drops the override; remote-only ref
  keeps it) — pins the "no suffixed-branch collision" guarantee.
- Note the worktreesByRepo visibility limitation near the busy-branch check
  (a branch busy only in a hidden external worktree is caught by the backend).
- Strengthen tests: reuse-checkbox toggle in both directions, empty worktree
  list case.
@nwparker
nwparker merged commit ae77156 into main Jun 19, 2026
1 check passed
@shaharmor

Copy link
Copy Markdown
Contributor

@nwparker can we please extend this so that it will also appear on non-local branches (e.g origin/my-branch), and that when checked, will checkout the same branch name locally and set the target branch to the origin one?

Currently if you create a new worktree from an existing remote-only branch, it will create a new (differently named) local branch and will NOT set the upstream target to the origin/* one.

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ablyai#5181) (stablyai#5781)

* feat(worktree): reuse an existing branch when creating a worktree (stablyai#5181)

Adds an explicit "Reuse this branch" checkbox to the new-worktree composer.
When an existing local branch is selected in the smart name field, the
checkbox (default on) checks that branch out instead of creating a new
branch from it — and the choice now survives renaming the worktree folder.

Previously, reusing an existing branch only worked implicitly: it required
keeping the auto-filled worktree name equal to the branch, and editing the
name silently reverted to "create a new branch". There was no discoverable,
durable control — the gap the issue reports.

The fix is renderer-only: picking an existing local branch already sets
baseBranch === branchNameOverride, so the existing backend reuse path
(`git worktree add <path> <branch>`, preserveBranchOnDelete) checks the
branch out correctly across local/SSH/runtime. The checkbox pins that
override via the existing branchNameOverridePreservesNameEdits flag so the
worktree folder can be named independently while the branch is reused;
unchecking creates a fresh branch from the selected ref as base.

- New pure helper resolveComposerBranchReuse (local-vs-remote + default).
- Checkbox hidden for remote-only refs and non-branch sources.
- Tests: pure helper, card render/toggle, and a backend integration test
  proving a renamed folder still reuses the exact branch.

* fix(worktree): refine reuse-branch checkbox (placement, label, eligibility)

Address review feedback on the "Reuse branch" control:

- Move the checkbox directly under the branch (smart) selection instead of the
  Advanced "Name" field — the worktree folder name can legitimately differ from
  the branch, so the choice belongs next to the branch pick and is now visible
  without expanding Advanced.
- Rename the label "Reuse this branch" -> "Reuse branch".
- Make eligibility dynamic: reuse is impossible when the branch is already
  checked out in another worktree (git allows a branch in only one worktree), so
  the checkbox is now hidden in that case (it was already hidden for remote-only
  refs). When a busy branch is picked, the override is no longer pinned to it, so
  creation cleanly falls back to a new branch from that ref as base instead of a
  silently-suffixed branch.

Adds isBranchCheckedOutInWorktrees (pure, unit-tested) and threads the repo's
worktree branch list from the store into the selection logic.

* feat(worktree): animate the reuse-branch row's show/hide

Keep the "Reuse branch" row mounted and collapse it with a grid-rows
transition (same pattern as the Advanced drawer) instead of conditionally
rendering it, so the create-worktree dialog grows and shrinks smoothly when the
option appears/disappears as the selected branch changes. The checkbox is taken
out of the tab order while collapsed.

* refactor(worktree): address review nits on reuse-branch control

From a multi-dimensional review of the branch (all findings low severity):

- Reset reuse state (reuseEligibleBranch, reuseSelectedBranch,
  branchNameOverridePreservesNameEdits) on repo and project switches, matching
  the other reset paths — avoids carrying stale branch-scoped state.
- Disable the reuse checkbox while collapsed so no focusable control lives
  inside the aria-hidden row.
- Extract the busy-branch override decision into a pure resolveComposerReuseOverride
  helper and unit-test it (busy local branch drops the override; remote-only ref
  keeps it) — pins the "no suffixed-branch collision" guarantee.
- Note the worktreesByRepo visibility limitation near the busy-branch check
  (a branch busy only in a hidden external worktree is caught by the backend).
- Strengthen tests: reuse-checkbox toggle in both directions, empty worktree
  list case.
@montella1507

Copy link
Copy Markdown

Hey, where is that "Reuse branch" checkbox? i dont see it anywhere
CleanShot 2026-10-31 at 15 38 24

@montella1507

Copy link
Copy Markdown

Ah got it.. i need to sleect "branch" that UI / UX there is super strange.. will prepare issue for this

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.

[Feature]: Create new worktree with existing branch

3 participants