Skip to content

feat(source-control): switch and create branches from the sidepanel - #16403

Open
MhAhmadAli wants to merge 1 commit into
stablyai:mainfrom
MhAhmadAli:feat/source-control-branch-switcher
Open

MhAhmadAli wants to merge 1 commit into
stablyai:mainfrom
MhAhmadAli:feat/source-control-branch-switcher

Conversation

@MhAhmadAli

Copy link
Copy Markdown

ELI5

The Source Control panel shows which branch you are on, but the name is just text. This makes it a button: click it, search your local branches, switch to one, or type a new name and create it.

What Changed

The switching engine already exists and ships on mobile — git.checkout and git.localBranches already reach local, SSH and relay hosts. Desktop had no path to it: the HEAD label was a static span and no IPC channel exposed either call. Branch creation existed nowhere.

Shared, so hosts cannot drift

  • src/shared/git-local-branches.ts — the for-each-ref argv and its parser, replacing the copies src/main/git/checkout.ts and src/relay/git-handler.ts each carried. The format now also asks for %(worktreepath).
  • src/shared/git-branch-name.ts — check-ref-format rules, used by the renderer to explain a bad name before spending a round trip, and by every host entrypoint as defense in depth. The previous guard rejected only a leading dash, which is too weak for a user-typed name.

Hosts — createAndCheckoutBranch; createBranch on the provider contract, the SSH provider and the relay; a git.createBranch RPC method; git:localBranches / git:checkout / git:createBranch IPC channels; preload and web-shim entries.

UI — HeadIdentity moves to its own module and accepts a headSlot, which panel-ready fills with the picker only for a real branch. branch-picker-rows.ts holds the logic and is pure; use-branch-switch.ts drives loading and the two mutations; branch-switcher.tsx is a cmdk popover.

Three behaviors worth reviewing:

  • A branch checked out in another worktree is inert and names the workspace holding it. Git refuses to check a branch out twice, and in a worktree-heavy app that refusal is the common case, not an edge one.
  • A dirty tree is never forced. Git's "would be overwritten by checkout" propagates verbatim so the user decides whether to commit first.
  • git.createBranch is a new RPC method, so a host predating it answers method_not_found; the picker reports that the remote host needs updating rather than surfacing a raw error.

Detached HEAD and folder workspaces keep the static label.

Stash is deliberately excluded. The issue also asks for it; it is a much larger separate feature with its own open PR (#11571), and bundling it would make this unreviewable.

Why

Issue #16362 asks to switch and create branches from the Source Control blade. #12984 asks for the same capability from the project view. Today the only in-app way to reach another branch is to create a whole workspace, or to drop to a terminal.

The desktop already reconciles a branch switch made outside the UI — worktree-git-identity-update.ts re-derives auto-generated display names and clears branch-scoped review links, and worktree-listing-branch-switch.ts exists to win the race between the two refresh paths that observe one. An in-app checkout inherits all of that by calling the same refresh trio, so this needs no new reconciliation machinery.

Extracting the shared parser rather than adding a third copy follows the note in git-handler.ts about paths that must be kept in sync by hand.

Linked Issue

Fixes #16362

Also addresses #12984 (same capability, requested from the project view) — worth closing or cross-linking.

Visual Proof

Missing — flagging rather than claiming N/A, because this is a UI change and the template requires it.

I could not launch the app: the Electron postinstall never ran in my environment, so no $electron / Playwright CDP pass was possible. Screenshots of the picker (closed trigger, open list, occupied-branch row, create row) are needed before this merges, and I would rather say so than attach nothing and tick the box.

Testing

Everything below ran on Linux (Node 24, container) against this branch.

  • pnpm typecheck — clean, all projects.
  • pnpm lint — every gate passes: oxlint, both code-quality audits, reliability gates, max-lines ratchet, runtime-electron ratchet, skill guides/manifest, and all three localization checks. No max-lines suppression added; two files that crossed their budget were split (web-git-branch-api.ts, head-identity.tsx).
  • 59 new tests across 4 files, all passing:
    • src/shared/git-local-branches.test.ts — parser: occupancy, current-first, detached HEAD, malformed lines, empty repo.
    • src/shared/git-branch-name.test.ts — accept/reject table across the check-ref-format rules, plus control characters and flag injection.
    • src/main/git/checkout.test.ts — exact argv for switch and create, the -- terminator, rejection before spawn, and git's dirty-tree refusal propagating.
    • branch-picker-rows.test.ts — filtering, create-row gating, occupancy labelling, Windows path comparison, and the older-host fallback.
  • Full suite: 94 failed files with this branch vs 81 on a clean-tree baseline of the same commit. I chased all 13 of the difference; every one passes in isolation — they are timing assertions and timeouts (-performance, -complexity, -leak, parallelism) that trip under container load. The 81 baseline failures are environmental in my setup: node-pty's native module (I installed with --ignore-scripts), Electron tests, live-shell tests, Windows tests.

Not run:

  • pnpm build.

  • tests/e2e/cross-version-wire/… — needs vX.Y.Z release tags, which my fork has none of. It covers the terminal wire, untouched here, but it is the enforcement gate for the compatibility rules below.

  • Mobile typecheck (separate workspace/lockfile). Mobile reads only .current / .branches off this type, both unchanged.

  • macOS and Windows.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable — this change touches no skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Security — branch names are validated at the RPC schema, the IPC handler, the relay entrypoint and the git helper. checkout/checkout -b argv ends with -- so a name can never be read as a pathspec, and a leading dash is rejected before spawn. No new secrets, no new network surface.
  • Cross-platform — no hardcoded separators; worktree paths are compared through normalizeRuntimePathForComparison, covered by a Windows-path test. %(worktreepath) is Git 2.23, under the documented 2.25 baseline, so no capability gate is needed; checkout -b is used rather than switch -c, which is 2.23 and still experimental at that baseline.
  • Remote SSH — routed through the repo owner host like every other source-control call, via the existing SSH provider and relay handlers.
  • Backwards compatibility — the entries field on the listing is optional per remote-wire-compatibility.md rule 1; an older host omitting it degrades to "occupancy unknown" and lets git's own refusal surface, rather than hiding the branch. The new RPC method fails loudly with method_not_found against an older host, and that is translated into a clear message.
  • Mobile — reads only current / branches, both unchanged. The mobile picker keeps working exactly as before.
  • Performance — the listing is fetched only when the picker opens; row building is pure and synchronous over local branches.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason — see Visual Proof; genuinely missing
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass — lint/typecheck/test pass; build not run

The branch-switching engine already existed and shipped on mobile
(git.checkout / git.localBranches reach local, SSH and relay hosts).
Desktop had no path to it: the HEAD label in the Source Control blade
was a static span, and no IPC channel exposed either call. Branch
creation existed nowhere.

Make the HEAD label a picker that lists local branches, switches to
one, and creates a new branch from the typed name.

Shared, so the hosts cannot drift:

- git-local-branches: the for-each-ref argv and its parser, replacing
  the copies main and the relay each carried. The format now asks for
  %(worktreepath) (Git 2.23, under the 2.25 baseline) so the picker
  knows which worktree holds a branch.
- git-branch-name: check-ref-format rules, used by the renderer to
  explain a bad name before spending a round trip and by every host
  entrypoint as defense in depth. The previous guard rejected only a
  leading dash, which is too weak for a user-typed name.

Behavior worth noting:

- A branch checked out in another worktree is inert and names the
  workspace holding it. Git refuses to check a branch out twice, and
  in a worktree-heavy app that refusal is the common case, not an
  edge one.
- A dirty tree is never forced. Git's "would be overwritten by
  checkout" propagates verbatim so the user decides whether to commit
  first.
- git.createBranch is a new RPC method, so a host that predates it
  answers method_not_found; the picker reports that the remote host
  needs updating instead of surfacing a raw error. The added entries
  field on the listing is optional per remote-wire-compatibility.md
  rule 1, and an older host omitting it degrades to occupancy unknown
  rather than to a hidden branch.

Detached HEAD and folder workspaces keep the static label: the picker
is injected through a headSlot the caller fills only for a real branch.

Stash is deliberately excluded — separate feature, separate change.

Refs stablyai#16362, stablyai#12984
@coderabbitai

coderabbitai Bot commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds shared Git branch-name validation and local branch listing with worktree occupancy. Adds checkout and branch creation across local, SSH, IPC, RPC, preload, and web runtime paths. Adds a Source Control branch picker with search, creation, checkout, occupancy indicators, loading states, error handling, refreshes, localization, and tests.

Merge Risk: 🔵 Low · up to 91056

The branch picker can treat occupancy information missing from older hosts as available, and worktree paths containing tabs can be displayed incorrectly. These are bounded edge-case correctness issues, so the PR is mergeable with explicit owner follow-up to preserve unknown occupancy and full paths.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 39.39% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 33 functions across 30 files. (2 skipped:… 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: switching and creating branches from the Source Control sidepanel.
Description check ✅ Passed The description follows the repository template and explains the change, rationale, linked issue, testing, compatibility considerations, and known limitations. It explicitly identifies missing visual …
Linked Issues check ✅ Passed The implementation satisfies issue #16362 by adding sidepanel branch listing, branch switching, and branch creation across the UI, local hosts, SSH, relay, IPC, RPC, and preload layers. It also includ…
Out of Scope Changes check ✅ Passed The changes remain aligned with the linked issue. Shared parsing, validation, host plumbing, compatibility handling, tests, and UI support directly enable branch switching and creation. Stash support …
Full details: Description check

Explanation

The description follows the repository template and explains the change, rationale, linked issue, testing, compatibility considerations, and known limitations. It explicitly identifies missing visual proof, manual testing, build validation, and AI disclosure instead of claiming completion.

Full details: Linked Issues check

Explanation

The implementation satisfies issue #16362 by adding sidepanel branch listing, branch switching, and branch creation across the UI, local hosts, SSH, relay, IPC, RPC, and preload layers. It also includes validation, worktree occupancy handling, and dirty-tree protection.

Full details: Out of Scope Changes check

Explanation

The changes remain aligned with the linked issue. Shared parsing, validation, host plumbing, compatibility handling, tests, and UI support directly enable branch switching and creation. Stash support is explicitly excluded and no unrelated feature work is present.

Full details: Docstring Coverage

Explanation

Docstring coverage is 39.39% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 33 functions across 30 files. (2 skipped: 1 unsupported, 1 too large.)


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 (1)
src/renderer/src/components/right-sidebar/source-control/panel/branch-switcher.tsx (1)

33-42: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use intent-named localization IDs and named placeholders.

Replace the new auto... IDs and {{value0}} placeholders with intent-named IDs and named placeholders.

  • src/renderer/src/components/right-sidebar/source-control/panel/branch-switcher.tsx#L33-L42: update new picker labels and validation text.
  • src/renderer/src/components/right-sidebar/source-control/sync/use-branch-switch.ts#L122-L157: update new success, failure, and unsupported-host messages.
    Based on learnings: “For newly added user-facing strings in stablyai/orca TypeScript and TSX files, follow config/i18n-translation-source.md: use intent-named localization IDs with named interpolation placeholders.”

Source: Learnings


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9bae4a1c-b23d-4bf5-ab53-5920d87d5a4c

📥 Commits

Reviewing files that changed from the base of the PR and between 6103b78 and 9105686.

📒 Files selected for processing (32)
  • src/main/git/checkout.test.ts
  • src/main/git/checkout.ts
  • src/main/ipc/filesystem.ts
  • src/main/providers/git-provider-contract.ts
  • src/main/providers/ssh-git-working-tree-provider.ts
  • src/main/runtime/orca-runtime-git.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/git-params.ts
  • src/main/runtime/rpc/methods/git.ts
  • src/main/runtime/runtime-rpc.ts
  • src/preload/api/git-inspection-api.ts
  • src/preload/api/git-operation-api.ts
  • src/preload/index.ts
  • src/relay/git-handler.ts
  • src/renderer/src/components/right-sidebar/source-control/panel/branch-context-row.tsx
  • src/renderer/src/components/right-sidebar/source-control/panel/branch-picker-rows.test.ts
  • src/renderer/src/components/right-sidebar/source-control/panel/branch-picker-rows.ts
  • src/renderer/src/components/right-sidebar/source-control/panel/branch-switcher.tsx
  • src/renderer/src/components/right-sidebar/source-control/panel/head-identity.tsx
  • src/renderer/src/components/right-sidebar/source-control/panel/header-toolbar.tsx
  • src/renderer/src/components/right-sidebar/source-control/panel/panel-ready.tsx
  • src/renderer/src/components/right-sidebar/source-control/panel/use-panel-model.ts
  • src/renderer/src/components/right-sidebar/source-control/sync/use-branch-switch.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/runtime/runtime-git-client.ts
  • src/renderer/src/web/preload-api/web-git-api.ts
  • src/renderer/src/web/preload-api/web-git-branch-api.ts
  • src/shared/git-branch-name.test.ts
  • src/shared/git-branch-name.ts
  • src/shared/git-local-branches.test.ts
  • src/shared/git-local-branches.ts
  • src/shared/runtime-types.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +49 to +65
const entries: readonly GitLocalBranchEntry[] =
listing?.entries ?? listing?.branches.map((name): GitLocalBranchEntry => ({ name })) ?? []
for (const entry of entries) {
if (trimmedQuery.length > 0 && !matchesQuery(entry.name, trimmedQuery)) {
continue
}
const entryPath = entry.worktreePath
? normalizeRuntimePathForComparison(entry.worktreePath)
: null
const occupiedElsewhere = entryPath !== null && entryPath !== selfPath
rows.push({
kind: 'branch',
name: entry.name,
isCurrent: entry.name === listing?.current,
occupiedBy: occupiedElsewhere
? (worktreeLabelByPath?.get(entryPath) ?? entry.worktreePath ?? null)
: null

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

Do not treat missing occupancy data as free.

An older host omits entries. The current code converts that state to occupiedBy: null, then enables the branch row. GitLocalBranchListing requires occupancy to degrade to unknown, not free.

  • src/renderer/src/components/right-sidebar/source-control/panel/branch-picker-rows.ts#L49-L65: model unknown occupancy separately from known-free occupancy.
  • src/renderer/src/components/right-sidebar/source-control/panel/branch-switcher.tsx#L57-L64: do not enable an occupancy-unknown branch as a known-free checkout.
  • src/renderer/src/components/right-sidebar/source-control/panel/branch-picker-rows.test.ts#L92-L100: assert the occupancy-unknown behavior instead of asserting free branches.
📍 Affects 3 files
  • src/renderer/src/components/right-sidebar/source-control/panel/branch-picker-rows.ts#L49-L65 (this comment)
  • src/renderer/src/components/right-sidebar/source-control/panel/branch-switcher.tsx#L57-L64
  • src/renderer/src/components/right-sidebar/source-control/panel/branch-picker-rows.test.ts#L92-L100

Comment on lines +44 to +55
for (const line of stdout.split('\n')) {
if (line.length === 0) {
continue
}
const [marker, name, worktreePath] = line.split('\t')
if (!name) {
continue
}
if (marker === '*') {
current = name
}
entries.push(worktreePath ? { name, worktreePath } : { name })

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

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -euo pipefail

tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT
main="$tmp_dir/main"
tab=$'\t'

git init -q "$main"
git -C "$main" config user.email [email protected]
git -C "$main" config user.name reviewer
printf 'x\n' >"$main/file"
git -C "$main" add file
git -C "$main" commit -qm initial
git -C "$main" branch -M main
git -C "$main" worktree add -q -b feature "$tmp_dir/linked${tab}path"

git -C "$main" for-each-ref \
  '--format=%(HEAD)%09%(refname:short)%09%(worktreepath)' \
  refs/heads/ | sed -n l

Repository: stablyai/orca

Length of output: 232


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- src/shared/git-local-branches.ts ---'
cat -n src/shared/git-local-branches.ts | sed -n '1,120p'

printf '%s\n' '--- references to parseLocalBranchListing and worktreePath ---'
rg -n -C 3 'parseLocalBranchListing|worktreePath' src --glob '*.{ts,tsx,js,jsx}'

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail

cat -n src/shared/git-local-branches.ts | sed -n '1,90p'
printf '%s\n' '--- direct symbol references ---'
rg -n -C 4 'parseLocalBranchListing' src --glob '*.{ts,tsx}'
printf '%s\n' '--- picker occupancy references ---'
rg -n -C 4 'entries.*worktreePath|worktreePath.*entries|worktreePath' src/renderer/src/components/right-sidebar/source-control src/main src/shared --glob '*.{ts,tsx}' | head -n 240

Repository: stablyai/orca

Length of output: 38253


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- checkout flow ---'
cat -n src/main/git/checkout.ts | sed -n '1,180p'

printf '%s\n' '--- occupancy logic ---'
rg -n -C 6 'worktreePath|occupied|checked.?out|checkout' src/renderer/src --glob '*.{ts,tsx}' \
  | rg -B 6 -A 6 'worktreePath|occupied|checked.?out' \
  | head -n 260

Repository: stablyai/orca

Length of output: 25655


Preserve embedded tabs in worktreePath.

When a worktree path contains a tab, parseLocalBranchListing truncates it at line.split('\t'). Split only the first two separators and preserve the remaining path text.

@akshad-exe

Copy link
Copy Markdown

Hi @MhAhmadAli — I hit this feature gap personally and found your PR while checking #16362 and #12984. Are you still planning to continue this work?

Current main now already exposes git.localBranches and git.checkout through runtime RPC, and mobile routes them across supported hosts. That may make a smaller desktop-only first slice possible: switch existing branches from Source Control, preserve Git's dirty-tree/worktree safety, refresh identity afterward, and leave branch creation/stash for follow-ups.

I do not want to duplicate or take over your work without asking. If you are still active, I am happy to help test/review or contribute a focused update you prefer. If you are no longer pursuing it, would you be comfortable with me proposing the narrower current-main implementation, with credit and a link back to this PR?

This branch has not been deployed

No deployments
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]: Ability to switch and create branch from the sidepanel Source Control UI

2 participants