Skip to content

The agent that grows with you

fix(desktop): mount one worktree dialog instead of one per composer

ethernetb818c427c830
diff --git a/apps/desktop/e2e/worktree-branch-status.spec.ts b/apps/desktop/e2e/worktree-branch-status.spec.ts
index a3d5dac217e..971a1f6b412 100644
--- a/apps/desktop/e2e/worktree-branch-status.spec.ts
+++ b/apps/desktop/e2e/worktree-branch-status.spec.ts
@@ -2,21 +2,40 @@ import { execFileSync } from 'node:child_process'
import * as fs from 'node:fs'
import * as path from 'node:path'
-import { test, expect } from './test'
-
import {
buildAppEnv,
createSandbox,
launchDesktop,
- writeEnvFile,
- writeMockProviderConfig,
type MockBackendFixture,
waitForAppReady,
+ writeEnvFile,
+ writeMockProviderConfig,
} from './fixtures'
import { startMockServer } from './mock-server'
+import { expect, test } from './test'
+import { expectVisualSnapshot } from './visual-snapshot'
const BRANCH_NAME = 'e2e-composer-branch'
+/**
+ * Enough branches to make both the base-branch popover and the convert-branch
+ * list taller than their default height. That is the condition in which the
+ * dialog's own scroll box clips the popover, and that regression is what the
+ * visual snapshots here guard against.
+ */
+const EXTRA_BRANCHES = [
+ 'feature/alpha-one',
+ 'feature/beta-two',
+ 'feature/gamma-three',
+ 'fix/delta-four',
+ 'fix/epsilon-five',
+ 'chore/zeta-six',
+ 'chore/eta-seven',
+ 'spike/theta-eight',
+ 'spike/iota-nine',
+ 'release/kappa-ten',
+]
+
function createGitRepo(root: string): string {
const repo = path.join(root, 'repo')
@@ -28,6 +47,10 @@ function createGitRepo(root: string): string {
execFileSync('git', ['add', 'README.md'], { cwd: repo })
execFileSync('git', ['commit', '-m', 'initial'], { cwd: repo })
+ for (const branch of EXTRA_BRANCHES) {
+ execFileSync('git', ['branch', branch], { cwd: repo })
+ }
+
return repo
}
@@ -39,6 +62,23 @@ function configureRepoCwd(hermesHome: string, mockUrl: string, repo: string): vo
let fixture: MockBackendFixture | null = null
+/** A dialog renders as `[data-slot="dialog-content"]` (components/ui/dialog.tsx). */
+const DIALOG = '[data-slot="dialog-content"]'
+
+/** Open the worktree dialog with the global ⌘⇧B / ctrl+shift+B hotkey. */
+async function openWorktreeDialog(): Promise<void> {
+ const page = fixture!.page
+ await page.keyboard.press('Control+Shift+B')
+ await expect(page.locator(DIALOG)).toBeVisible()
+}
+
+/** Close the open dialog and wait until it leaves the DOM. */
+async function closeDialog(): Promise<void> {
+ const page = fixture!.page
+ await page.keyboard.press('Escape')
+ await expect(page.locator(DIALOG)).toHaveCount(0)
+}
+
test.beforeAll(async () => {
const sandbox = createSandbox('worktree-branch-status')
const repo = createGitRepo(sandbox.root)
@@ -61,18 +101,10 @@ test.beforeAll(async () => {
}
await waitForAppReady(fixture, 120_000)
-})
-
-test.afterAll(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-test('creating a branch with ctrl-shift-b updates the composer git-status branch', async ({}, testInfo) => {
- const page = fixture!.page
- const codingRow = page.locator('.coding-status-bar')
+ // The coding rail, and thus the ⌘⇧B worktree dialog, mounts only after the
+ // session resolves a cwd that holds a repo. This happens on the first turn.
const composer = page.locator('[contenteditable="true"]').first()
-
await composer.click()
await composer.type('create a repo-backed e2e session', { delay: 2 })
await page.keyboard.press('Enter')
@@ -81,14 +113,131 @@ test('creating a branch with ctrl-shift-b updates the composer git-status branch
'create a repo-backed e2e session',
{ timeout: 15_000 },
)
- await expect(codingRow).toContainText('main')
- await page.keyboard.press('Control+Shift+B')
+ await expect(page.locator('.coding-status-bar')).toContainText('main')
+})
+
+test.afterAll(async () => {
+ await fixture?.cleanup()
+ fixture = null
+})
+
+test('worktree dialog renders the base-branch picker over the dialog, not clipped by it', async () => {
+ const page = fixture!.page
+
+ await openWorktreeDialog()
+
+ // Open the base-branch combobox. With 11 branches, the list is taller than
+ // the space below the trigger. A popover that portals into the dialog's
+ // `overflow-y-auto` box is therefore cut off. This snapshot catches that bug.
+ await page.getByRole('button', { name: /branch off/i }).click()
+ await expect(page.getByPlaceholder('Search branches…')).toBeVisible()
+ await expect(page.getByRole('option', { name: 'feature/alpha-one' })).toBeVisible()
+
+ await expectVisualSnapshot(page, { name: 'worktree-dialog-base-branch-picker', app: fixture!.app })
+
+ // This check does not depend on pixels: the dialog's scroll box must not crop
+ // the painted box of the popover. Measure the geometry, so a headless run
+ // fails on this regression before a person looks at a diff image.
+ const clipped = await page.evaluate(() => {
+ const popover = document.querySelector('[data-slot="popover-content"]')
+ const dialog = document.querySelector('[data-slot="dialog-content"]')
+
+ if (!popover || !dialog) {
+ return { reason: 'missing', clipped: true }
+ }
+
+ const p = popover.getBoundingClientRect()
+ const d = dialog.getBoundingClientRect()
+ const scrolls = window.getComputedStyle(dialog).overflowY
+
+ return {
+ reason: 'measured',
+ // Only a clipping ancestor can crop the popover. The popover is cut when
+ // the dialog scrolls its overflow AND the popover goes past the box of
+ // the dialog.
+ clipped: (scrolls === 'auto' || scrolls === 'scroll' || scrolls === 'hidden') &&
+ (p.bottom > d.bottom + 1 || p.top < d.top - 1 || p.right > d.right + 1 || p.left < d.left - 1),
+ }
+ })
+
+ expect(clipped.clipped, `base-branch popover is clipped by the dialog (${clipped.reason})`).toBe(false)
+
+ await page.keyboard.press('Escape')
+ await closeDialog()
+})
+
+test('worktree dialog convert-an-existing-branch sub-view lists the repo branches', async () => {
+ const page = fixture!.page
+
+ await openWorktreeDialog()
+ await page.getByRole('button', { name: 'Convert an existing branch' }).click()
+
+ await expect(page.getByPlaceholder('Search branches…')).toBeVisible()
+ await expect(page.getByRole('option', { name: /feature\/alpha-one/ })).toBeVisible()
+
+ await expectVisualSnapshot(page, { name: 'worktree-dialog-convert-branch', app: fixture!.app })
+
+ await closeDialog()
+})
+
+test('creating a branch with ctrl-shift-b updates the composer git-status branch and leaves no dialog behind', async ({}, testInfo) => {
+ const page = fixture!.page
+ const codingRow = page.locator('.coding-status-bar')
+
+ await openWorktreeDialog()
+ // Exactly one dialog instance. A second dialog here, hidden or empty, is the
+ // symptom of the double-open bug.
+ await expect(page.locator(DIALOG)).toHaveCount(1)
const branchInput = page.locator('input[placeholder="e.g. my-feature"]').first()
await expect(branchInput).toBeVisible()
await branchInput.fill(BRANCH_NAME)
+ // Select a base branch, so this test uses the same path as the user: open the
+ // picker, select a branch, then submit. It does not use the default value.
+ // The keyboard drives this step. The dialog still clips the popover, so a
+ // mouse click on an option is not reliable until that bug is corrected. The
+ // double-open check below is therefore independent of the clipping bug.
+ await page.getByRole('button', { name: /branch off/i }).click()
+ await page.getByPlaceholder('Search branches…').fill('main')
+ await expect(page.getByRole('option', { name: 'main' }).first()).toBeVisible()
+ await page.keyboard.press('Enter')
+ await expect(page.locator('[data-slot="popover-content"]')).toHaveCount(0)
+
await page.getByRole('button', { name: 'New worktree' }).click()
await expect(codingRow).toContainText(BRANCH_NAME, { timeout: 15_000 })
+
+ // The dialog must close and stay closed. No empty second dialog can remain
+ // after the new worktree session starts.
+ await expect(page.locator(DIALOG)).toHaveCount(0)
+ await page.waitForTimeout(2000)
+ await expect(page.locator(DIALOG)).toHaveCount(0)
+
await page.screenshot({ path: testInfo.outputPath('composer-branch-after-create.png') })
})
+
+test('ctrl-shift-b opens exactly one worktree dialog when a second composer is on screen', async ({}, testInfo) => {
+ const page = fixture!.page
+
+ // ⌘T / ctrl+T stacks a second session tile. That gives a second live composer
+ // and therefore a second coding rail. Each rail mounted its own
+ // WorktreeDialog, and each rail subscribed to the same global token. One
+ // keypress therefore opened two stacked dialogs, and the dialog the user
+ // dismissed showed an identical empty one behind it. One mount in the sidebar
+ // makes that impossible by structure.
+ await page.keyboard.press('Control+T')
+ await expect(page.locator('.coding-status-bar')).toHaveCount(2, { timeout: 20_000 })
+
+ await page.keyboard.press('Control+Shift+B')
+ await expect(page.locator(DIALOG).first()).toBeVisible()
+ // Wait: let the effect of every subscriber flush before the count.
+ await page.waitForTimeout(500)
+
+ const count = await page.locator(DIALOG).count()
+ await page.screenshot({ path: testInfo.outputPath('worktree-dialog-two-composers.png') })
+
+ expect(count, 'one hotkey press must open exactly one worktree dialog').toBe(1)
+
+ // A dismissal then leaves nothing behind.
+ await closeDialog()
+})
diff --git a/apps/desktop/src/app/chat/composer/status-stack/coding-row.tsx b/apps/desktop/src/app/chat/composer/status-stack/coding-row.tsx
index 842b1ac37ec..664196e3362 100644
--- a/apps/desktop/src/app/chat/composer/status-stack/coding-row.tsx
+++ b/apps/desktop/src/app/chat/composer/status-stack/coding-row.tsx
@@ -1,7 +1,6 @@
import { useStore } from '@nanostores/react'
-import { memo, useEffect, useRef, useState } from 'react'
+import { memo, useEffect } from 'react'
-import { WorktreeDialog } from '@/app/chat/sidebar/projects/worktree-dialog'
import { StatusRow } from '@/components/chat/status-row'
import {
type ActionItemSpec,
@@ -17,9 +16,8 @@ import { DiffCount } from '@/components/ui/diff-count'
import type { HermesGitBranch } from '@/global'
import { useI18n } from '@/i18n'
import { displayPath } from '@/lib/display-path'
-import { registerRepoStatusCwd, repoStatusForCwd, repoWorktreesForCwd } from '@/store/coding-status'
+import { openWorktreeDialog, registerRepoStatusCwd, repoStatusForCwd, repoWorktreesForCwd } from '@/store/coding-status'
import { notifyError } from '@/store/notifications'
-import { $newWorktreeRequest } from '@/store/projects'
// Tiny uppercase section header, matching the composer "+" menu's labels.
const MENU_SECTION = 'text-[0.625rem] font-semibold uppercase tracking-wider text-(--ui-text-tertiary)'
@@ -79,11 +77,6 @@ export const CodingStatusRow = memo(function CodingStatusRow({
// only refreshed when the MAIN cwd probe happened to cover them).
useEffect(() => registerRepoStatusCwd(resolvedRepoPath), [resolvedRepoPath])
- // Shared worktree dialog — replaces the old inline dialog. Opened by the
- // dropdown menu's "branch off" items and the global ⌘⇧B hotkey.
- const [worktreeOpen, setWorktreeOpen] = useState(false)
- const [worktreeBase, setWorktreeBase] = useState<string | undefined>(undefined)
-
const switchToBranch = async (branch: string) => {
if (!onSwitchBranch) {
return
@@ -96,33 +89,13 @@ export const CodingStatusRow = memo(function CodingStatusRow({
}
}
- // Global ⌘⇧B (workspace.newWorktree): open the shared worktree dialog. The
- // coding row only renders inside a repo, so the hotkey naturally no-ops
- // elsewhere. Guarded by a token ref so it fires on the keypress, not on
- // mount or unrelated re-renders.
- const worktreeReq = useStore($newWorktreeRequest)
- const lastWorktreeReqRef = useRef(worktreeReq)
-
- // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
- useEffect(() => {
- if (worktreeReq === lastWorktreeReqRef.current) {
- return
- }
-
- lastWorktreeReqRef.current = worktreeReq
-
- if (!resolvedRepoPath || !onOpenWorktree) {
- return
- }
-
- setWorktreeBase(undefined)
- setWorktreeOpen(true)
- }, [onOpenWorktree, resolvedRepoPath, worktreeReq])
-
- // Open the worktree dialog from the dropdown menu with a pre-selected base.
+ // useKeybinds now handles the ⌘⇧B hotkey globally, through
+ // openWorktreeDialog. One dialog is mounted in the sidebar, so N mounted
+ // rails can no longer each open their own copy. The menu items below only
+ // publish the intent. They pin the repo of THIS rail, so the kebab of a tile
+ // targets the worktree of that tile.
const startBranch = (base: string | undefined) => {
- setWorktreeBase(base)
- setTimeout(() => setWorktreeOpen(true), 0)
+ void openWorktreeDialog({ base, repoPath: resolvedRepoPath })
}
if (!status) {
@@ -333,16 +306,6 @@ export const CodingStatusRow = memo(function CodingStatusRow({
)}
</StatusRow>
</ActionsContextMenu>
-
- {resolvedRepoPath && onOpenWorktree && (
- <WorktreeDialog
- initialBase={worktreeBase}
- onOpenChange={setWorktreeOpen}
- onStarted={onOpenWorktree}
- open={worktreeOpen}
- repoPath={resolvedRepoPath}
- />
- )}
</>
)
})
diff --git a/apps/desktop/src/app/chat/sidebar/index.tsx b/apps/desktop/src/app/chat/sidebar/index.tsx
index 10ec6e47209..30f07be1158 100644
--- a/apps/desktop/src/app/chat/sidebar/index.tsx
+++ b/apps/desktop/src/app/chat/sidebar/index.tsx
@@ -130,6 +130,7 @@ import {
StartWorkButton,
useRepoWorktreeMap
} from './projects'
+import { WorktreeDialog } from './projects/worktree-dialog'
import { SidebarBlankState, SidebarPinnedEmptyState, SidebarSessionSkeletons } from './section-states'
import { buildSessionByAnyId } from './session-index'
import { SidebarSessionsSection, VIRTUALIZE_THRESHOLD } from './sessions-section'
@@ -1335,7 +1336,7 @@ export function ChatSidebar({
inProject && enteredProject ? (
<div className="group/workspace flex shrink-0 items-center gap-0.5">
{enteredProject.path && (
- <StartWorkButton onStarted={onNewSessionInWorkspace} repoPath={enteredProject.path} />
+ <StartWorkButton repoPath={enteredProject.path} />
)}
{/* Home has no folder and no record to rename, theme, or delete. */}
{!enteredProject.isNoProject && (
@@ -1518,6 +1519,8 @@ export function ChatSidebar({
</div>
</SidebarContent>
<ProjectDialog />
+ {/* One mount for the whole app. The header of WorktreeDialog tells why. */}
+ <WorktreeDialog />
</Sidebar>
)
}
diff --git a/apps/desktop/src/app/chat/sidebar/projects/workspace-header.test.tsx b/apps/desktop/src/app/chat/sidebar/projects/workspace-header.test.tsx
index e03c14ac1f6..adb462e586d 100644
--- a/apps/desktop/src/app/chat/sidebar/projects/workspace-header.test.tsx
+++ b/apps/desktop/src/app/chat/sidebar/projects/workspace-header.test.tsx
@@ -27,11 +27,11 @@ vi.mock('@/store/projects', () => ({
revealPath: vi.fn()
}))
-// StartWorkButton renders the full WorktreeDialog (branch picker, git combobox,
-// etc.) as soon as it's open — none of that is relevant to the tooltip fix, so
-// stub it to keep this test focused on the trigger button.
-vi.mock('./worktree-dialog', () => ({
- WorktreeDialog: () => null
+// StartWorkButton no longer renders a dialog. It publishes an intent to the one
+// WorktreeDialog that is mounted in the sidebar. Stub the store action, so this
+// test keeps the button separate from the git probes of the resolver.
+vi.mock('@/store/coding-status', () => ({
+ openWorktreeDialog: vi.fn()
}))
const tipTrigger = (button: HTMLElement) => button.closest('[data-slot="tooltip-trigger"]')
@@ -73,7 +73,7 @@ describe('WorkspaceMenu', () => {
describe('StartWorkButton', () => {
it('wraps the git-branch trigger in a Tip', () => {
- render(<StartWorkButton onStarted={vi.fn()} repoPath="/repo" />)
+ render(<StartWorkButton repoPath="/repo" />)
const button = screen.getByRole('button', { name: 'New worktree' })
expect(tipTrigger(button)).toBeTruthy()
diff --git a/apps/desktop/src/app/chat/sidebar/projects/workspace-header.tsx b/apps/desktop/src/app/chat/sidebar/projects/workspace-header.tsx
index 5144919c9f3..102f43ff501 100644
--- a/apps/desktop/src/app/chat/sidebar/projects/workspace-header.tsx
+++ b/apps/desktop/src/app/chat/sidebar/projects/workspace-header.tsx
@@ -1,5 +1,4 @@
import type * as React from 'react'
-import { useState } from 'react'
import { ActionsContextMenu, ActionsMenu, type MenuKit, renderActionItem } from '@/components/ui/actions-menu'
import { Codicon } from '@/components/ui/codicon'
@@ -7,11 +6,11 @@ import { DisclosureCaret } from '@/components/ui/disclosure-caret'
import { Tip } from '@/components/ui/tooltip'
import { useI18n } from '@/i18n'
import { cn } from '@/lib/utils'
+import { openWorktreeDialog } from '@/store/coding-status'
import { copyPath, revealPath } from '@/store/projects'
import { SidebarRowLead } from '../chrome'
-import { WorktreeDialog } from './worktree-dialog'
// Branch/worktree labels routinely share a long prefix (`bb/coding-context-…`),
// so plain end-truncation (`truncate`) hides exactly the suffix that tells two
@@ -158,25 +157,23 @@ export function WorkspaceContextMenu({
// inside it. Naming is explicit — no auto-generated `hermes/work-<ts>` trees.
// The base branch defaults to the remote default (origin/HEAD); the user can
// pick any local or remote-tracking branch via a filterable combobox.
-export function StartWorkButton({ repoPath, onStarted }: { repoPath: string; onStarted: (path: string) => void }) {
+export function StartWorkButton({ repoPath }: { repoPath: string }) {
const { t } = useI18n()
const p = t.sidebar.projects
- const [open, setOpen] = useState(false)
return (
- <>
- <Tip label={p.startWork}>
- <button
- aria-label={p.startWork}
- className="grid size-4 shrink-0 place-items-center rounded-sm bg-transparent text-(--ui-text-quaternary) opacity-0 transition-opacity hover:bg-(--ui-control-hover-background) hover:text-foreground group-hover/section:opacity-100 focus-visible:opacity-100"
- onClick={() => setOpen(true)}
- type="button"
- >
- <Codicon name="git-branch" size="0.75rem" />
- </button>
- </Tip>
- <WorktreeDialog onOpenChange={setOpen} onStarted={onStarted} open={open} repoPath={repoPath} />
- </>
+ <Tip label={p.startWork}>
+ <button
+ aria-label={p.startWork}
+ className="grid size-4 shrink-0 place-items-center rounded-sm bg-transparent text-(--ui-text-quaternary) opacity-0 transition-opacity hover:bg-(--ui-control-hover-background) hover:text-foreground group-hover/section:opacity-100 focus-visible:opacity-100"
+ // Publish the intent. The one WorktreeDialog in the sidebar renders it.
+ // This button pins its own repo, so it targets this section.
+ onClick={() => void openWorktreeDialog({ repoPath })}
+ type="button"
+ >
+ <Codicon name="git-branch" size="0.75rem" />
+ </button>
+ </Tip>
)
}
diff --git a/apps/desktop/src/app/chat/sidebar/projects/worktree-dialog.tsx b/apps/desktop/src/app/chat/sidebar/projects/worktree-dialog.tsx
index 4cb4093bba1..9b418470156 100644
--- a/apps/desktop/src/app/chat/sidebar/projects/worktree-dialog.tsx
+++ b/apps/desktop/src/app/chat/sidebar/projects/worktree-dialog.tsx
@@ -1,4 +1,5 @@
-import { useCallback, useEffect, useState } from 'react'
+import { useStore } from '@nanostores/react'
+import { useCallback, useEffect, useMemo, useState } from 'react'
import { Button } from '@/components/ui/button'
import { Codicon } from '@/components/ui/codicon'
@@ -11,12 +12,22 @@ import {
DialogHeader,
DialogTitle
} from '@/components/ui/dialog'
+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { SanitizedInput } from '@/components/ui/sanitized-input'
import type { HermesGitBranch } from '@/global'
import { useI18n } from '@/i18n'
import { gitRef } from '@/lib/sanitize'
import { notifyError } from '@/store/notifications'
-import { listRepoBranches, startWorkInRepo, switchBranchInRepo } from '@/store/projects'
+import {
+ $projectTree,
+ $worktreeDialog,
+ closeWorktreeDialog,
+ listRepoBranches,
+ projectRootCwd,
+ requestStartWorkSession,
+ startWorkInRepo,
+ switchBranchInRepo
+} from '@/store/projects'
import { BaseBranchPicker } from './base-branch-picker'
@@ -34,50 +45,77 @@ const branchActionLabel = (branch: HermesGitBranch, copy: BranchActionCopy) => {
return branch.isDefault ? copy.branchSwitchHome : copy.branchCreateWorktree
}
-export interface WorktreeDialogProps {
- /** Repo root path for git operations. */
- repoPath: string
- /** Called with the new/converted worktree path on success. */
- onStarted: (path: string) => void
- /** Controlled open state. */
- open: boolean
- /** Called when the user requests the dialog to close (cancel, Esc, backdrop). */
- onOpenChange: (open: boolean) => void
- /** Pre-select a base branch when opening (from "branch off from X" menus). */
- initialBase?: string
-}
-
/**
- * Shared "new worktree" dialog — used by the sidebar's StartWorkButton and the
- * composer's ⌘⇧B shortcut. Features:
- * - Branch name input (sanitized as a git ref)
- * - Base branch picker (filterable combobox — the sidebar's BaseBranchPicker)
- * - Convert mode: check out an existing branch into a worktree
+ * The "new worktree" dialog. It is mounted exactly once, in the sidebar beside
+ * ProjectDialog, and the `$worktreeDialog` atom drives it. Every entry point
+ * (⌘⇧B, the kebab of the coding rail, the + button of the sidebar) publishes
+ * its intent to that atom. No entry point mounts its own copy. N composers on
+ * screen gave N stacked dialogs for one keypress.
*
- * The caller owns the open state so both the sidebar button and the global
- * hotkey can trigger the same dialog instance.
+ * Features:
+ * - Project picker: change the repo before you name the branch
+ * - Branch name input, made safe as a git ref
+ * - Base branch picker: a combobox with a filter
+ * - Convert mode: check an existing branch out into a worktree
*/
-export function WorktreeDialog({ repoPath, onStarted, open, onOpenChange, initialBase }: WorktreeDialogProps) {
+export function WorktreeDialog() {
const { t } = useI18n()
const p = t.sidebar.projects
+ const state = useStore($worktreeDialog)
+ const open = state !== null
+ const projectTree = useStore($projectTree)
+
const [name, setName] = useState('')
const [pending, setPending] = useState(false)
const [convertMode, setConvertMode] = useState(false)
const [branches, setBranches] = useState<HermesGitBranch[]>([])
const [branchesLoading, setBranchesLoading] = useState(false)
const [selectedBase, setSelectedBase] = useState('')
+ // The repo that the dialog targets. It is seeded from the resolved intent.
+ // This component then owns it, so the project picker can change the target
+ // and the user does not reopen the dialog.
+ const [repoPath, setRepoPath] = useState('')
+ const [projectOpen, setProjectOpen] = useState(false)
+
+ // Every project with a working root is a valid target. The list is deduped by
+ // path, because an auto project and a user project can share one folder.
+ const projectOptions = useMemo(() => {
+ const seen = new Set<string>()
+
+ return projectTree.flatMap(node => {
+ const path = projectRootCwd(node)
+
+ if (!path || seen.has(path)) {
+ return []
+ }
+
+ seen.add(path)
+
+ return [{ label: node.label, path }]
+ })
+ }, [projectTree])
- // Reset to a fresh state each time the dialog opens, applying any pre-selected
- // base branch from the caller (e.g. "branch off from main" in the coding row's
- // dropdown menu). When `initialBase` changes while open (shouldn't happen in
- // practice), the effect re-syncs.
+ const activeProjectLabel =
+ projectOptions.find(option => option.path === repoPath)?.label ?? repoPath.split('/').pop() ?? repoPath
+
+ // Reset to a fresh state each time the dialog opens. Apply the resolved repo
+ // and the base branch that the caller selected, for example "branch off from
+ // main" in the dropdown menu of the coding row.
useEffect(() => {
- if (open) {
+ if (state) {
setName('')
setConvertMode(false)
- setSelectedBase(initialBase ?? '')
+ setSelectedBase(state.base ?? '')
+ setRepoPath(state.repoPath)
+ setBranches([])
}
- }, [open, initialBase])
+ }, [state])
+
+ const onOpenChange = (next: boolean) => {
+ if (!next && !pending) {
+ closeWorktreeDialog()
+ }
+ }
const loadBranches = useCallback(async () => {
if (!repoPath) {
@@ -95,6 +133,12 @@ export function WorktreeDialog({ repoPath, onStarted, open, onOpenChange, initia
}
}, [repoPath])
+ // Give the new worktree to a fresh session, then close the dialog.
+ const started = (path: string) => {
+ requestStartWorkSession(path)
+ closeWorktreeDialog()
+ }
+
const submit = async () => {
const branch = name.trim()
@@ -108,8 +152,7 @@ export function WorktreeDialog({ repoPath, onStarted, open, onOpenChange, initia
const result = await startWorkInRepo(repoPath, { base: selectedBase || undefined, branch, name: branch })
if (result) {
- onStarted(result.path)
- onOpenChange(false)
+ started(result.path)
setName('')
}
} catch (err) {
@@ -139,8 +182,7 @@ export function WorktreeDialog({ repoPath, onStarted, open, onOpenChange, initia
}
if (result) {
- onStarted(result.path)
- onOpenChange(false)
+ started(result.path)
}
} catch (err) {
notifyError(err, p.startWorkFailed)
@@ -155,13 +197,67 @@ export function WorktreeDialog({ repoPath, onStarted, open, onOpenChange, initia
}
return (
- <Dialog onOpenChange={next => !pending && onOpenChange(next)} open={open}>
+ <Dialog onOpenChange={onOpenChange} open={open}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>{convertMode ? p.convertBranchTitle : p.newWorktreeTitle}</DialogTitle>
<DialogDescription>{convertMode ? p.convertBranchDesc : p.newWorktreeDesc}</DialogDescription>
</DialogHeader>
+ {/* Project picker: change the repo that the worktree is cut from. Show
+ it only when there is another project to select. */}
+ {projectOptions.length > 1 && (
+ <Popover onOpenChange={setProjectOpen} open={projectOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ className="group w-full flex justify-start items-center min-w-0 gap-1.5 hover:no-underline hover:text-muted-foreground"
+ disabled={pending}
+ size="inline"
+ variant="text"
+ >
+ <Codicon className="shrink-0 text-(--ui-text-tertiary)" name="folder" size="0.8rem" />
+ <span className="shrink-0">{p.worktreeProjectLabel}</span>
+ <span className="truncate text-primary underline-offset-4 decoration-current/20 group-hover:underline">
+ {activeProjectLabel}
+ </span>
+ <Codicon className="shrink-0 text-(--ui-text-tertiary)" name="chevron-down" size="0.75rem" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="z-(--z-modal-popover) min-w-(--radix-popover-trigger-width) p-0">
+ <Command
+ filter={(value, search) => (value.toLowerCase().includes(search.toLowerCase()) ? 1 : 0)}
+ >
+ <CommandInput autoFocus placeholder={p.worktreeProjectPlaceholder} />
+ <CommandList className="max-h-64">
+ <CommandEmpty>{p.worktreeProjectNone}</CommandEmpty>
+ <CommandGroup>
+ {projectOptions.map(option => (
+ <CommandItem
+ key={option.path}
+ onSelect={() => {
+ setRepoPath(option.path)
+ // The new repo has its own branches. Drop the old
+ // list and the old base, so nothing stale stays.
+ setBranches([])
+ setSelectedBase('')
+ setProjectOpen(false)
+ }}
+ value={`${option.label} ${option.path}`}
+ >
+ <Codicon className="shrink-0 text-(--ui-text-tertiary)" name="repo" size="0.8rem" />
+ <span className="truncate">{option.label}</span>
+ {option.path === repoPath && (
+ <Codicon className="ml-auto shrink-0 text-(--ui-accent)" name="check" size="0.8rem" />
+ )}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ )}
+
{convertMode ? (
<Command
className="rounded-md border border-(--ui-stroke-tertiary)"
@@ -208,6 +304,9 @@ export function WorktreeDialog({ repoPath, onStarted, open, onOpenChange, initia
/>
<BaseBranchPicker
disabled={pending}
+ // Remount on a repo change, so the picker loads the branches of
+ // the new repo and does not show those of the previous project.
+ key={repoPath}
onValueChange={setSelectedBase}
repoPath={repoPath}
value={selectedBase}
diff --git a/apps/desktop/src/app/hooks/use-keybinds.ts b/apps/desktop/src/app/hooks/use-keybinds.ts
index fa41cad2389..8a30c3049ff 100644
--- a/apps/desktop/src/app/hooks/use-keybinds.ts
+++ b/apps/desktop/src/app/hooks/use-keybinds.ts
@@ -16,7 +16,7 @@ import { findBarClaimsCombo } from '@/lib/find-in-page'
import { contributedKeybindHandler, PROFILE_SLOT_COUNT, SESSION_SLOT_COUNT } from '@/lib/keybinds/actions'
import { comboAllowedInInput, comboFromEvent, isEditableTarget } from '@/lib/keybinds/combo'
import { composerFocusKeysAllowed, isComposerFocusSoftCombo, typeToFocusChar } from '@/lib/keybinds/composer-focus-keys'
-import { $repoStatus } from '@/store/coding-status'
+import { openWorktreeDialog } from '@/store/coding-status'
import { toggleCommandPalette } from '@/store/command-palette'
import {
$findInPage,
@@ -40,7 +40,7 @@ import {
switchToDefaultProfile,
toggleShowAllProfiles
} from '@/store/profile'
-import { openFolderAsProject, requestNewWorktree } from '@/store/projects'
+import { openFolderAsProject } from '@/store/projects'
import { toggleReview } from '@/store/review'
import { $selectedStoredSessionId, setModelPickerOpen } from '@/store/session'
import { reopenLastClosedTile } from '@/store/session-states'
@@ -208,9 +208,11 @@ export function useKeybinds(deps: KeybindRuntimeDeps): void {
...sessionSlotHandlers,
'session.focusSearch': requestSessionSearchFocus,
'session.togglePin': deps.toggleSelectedPin,
- // Only meaningful inside a git repo — a no-op otherwise (the key falls
- // through instead of silently doing nothing).
- 'workspace.newWorktree': () => $repoStatus.get() && requestNewWorktree(),
+ // openWorktreeDialog resolves the target. There is no test for a repo
+ // here, so the key works from a detached session that sits inside a
+ // project, and not only from a session with a repo. When no repo is in
+ // reach, openWorktreeDialog does nothing.
+ 'workspace.newWorktree': () => void openWorktreeDialog(),
// ⌘O: native folder picker → open the folder as a project (upsert) with a
// fresh session anchored there.
'workspace.openFolder': () => void openFolderAsProject(),
diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.ts
index 79bb9aee367..26f72e7f4d9 100644
--- a/apps/desktop/src/i18n/ar.ts
+++ b/apps/desktop/src/i18n/ar.ts
@@ -1596,6 +1596,9 @@ export const ar = defineLocale({
newWorktreeDesc: 'سمِّ الفرع لشجرة العمل هذه.',
branchPlaceholder: 'مثال: my-feature',
startWorkFailed: 'تعذّر إنشاء شجرة العمل',
+ worktreeProjectLabel: 'المشروع',
+ worktreeProjectPlaceholder: 'ابحث في المشاريع…',
+ worktreeProjectNone: 'لا توجد مشاريع بمجلد',
convertBranch: 'تحويل فرع...',
convertBranchTitle: 'تحويل فرع',
convertBranchDesc: 'افتح الفروع المسحوبة، أو أنشئ شجرة عمل لفرع حر.',
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index 60a8d298add..0914021c0d2 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -1902,6 +1902,9 @@ export const en: Translations = {
baseBranchPlaceholder: 'Search branches…',
baseBranchNone: 'No branches found',
startWorkFailed: 'Could not create worktree',
+ worktreeProjectLabel: 'Project',
+ worktreeProjectPlaceholder: 'Search projects…',
+ worktreeProjectNone: 'No projects with a folder',
convertBranch: 'Convert a branch…',
convertBranchTitle: 'Convert a branch',
convertBranchDesc: 'Open checked-out branches, or create a worktree for a free branch.',
diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts
index 85444e123de..a8ae05042b7 100644
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@ -1739,6 +1739,9 @@ export const ja = defineLocale({
baseBranchPlaceholder: 'ブランチを検索…',
baseBranchNone: 'ブランチが見つかりません',
startWorkFailed: 'ワークツリーを作成できませんでした',
+ worktreeProjectLabel: 'プロジェクト',
+ worktreeProjectPlaceholder: 'プロジェクトを検索…',
+ worktreeProjectNone: 'フォルダのあるプロジェクトがありません',
convertBranch: 'ブランチを変換…',
convertBranchTitle: 'ブランチを変換',
convertBranchDesc: 'チェックアウト済みのブランチを開くか、空いているブランチのワークツリーを作成します。',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index e5d1fe4bcea..f3ef8501205 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -1598,6 +1598,9 @@ export interface Translations {
baseBranchPlaceholder: string
baseBranchNone: string
startWorkFailed: string
+ worktreeProjectLabel: string
+ worktreeProjectPlaceholder: string
+ worktreeProjectNone: string
convertBranch: string
convertBranchTitle: string
convertBranchDesc: string
diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts
index 452313c1121..fc7feb8f395 100644
--- a/apps/desktop/src/i18n/zh-hant.ts
+++ b/apps/desktop/src/i18n/zh-hant.ts
@@ -1682,6 +1682,9 @@ export const zhHant = defineLocale({
baseBranchPlaceholder: '搜尋分支…',
baseBranchNone: '未找到分支',
startWorkFailed: '無法建立工作樹',
+ worktreeProjectLabel: '專案',
+ worktreeProjectPlaceholder: '搜尋專案…',
+ worktreeProjectNone: '沒有包含資料夾的專案',
convertBranch: '轉換分支…',
convertBranchTitle: '轉換分支',
convertBranchDesc: '開啟已簽出的分支,或為可用分支建立工作樹。',
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index e4f8cae9347..927d5c1b25f 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -2095,6 +2095,9 @@ export const zh: Translations = {
baseBranchPlaceholder: '搜索分支…',
baseBranchNone: '未找到分支',
startWorkFailed: '无法创建工作树',
+ worktreeProjectLabel: '项目',
+ worktreeProjectPlaceholder: '搜索项目…',
+ worktreeProjectNone: '没有包含文件夹的项目',
convertBranch: '转换分支…',
convertBranchTitle: '转换分支',
convertBranchDesc: '打开已检出的分支,或为可用分支创建工作树。',
diff --git a/apps/desktop/src/store/coding-status.ts b/apps/desktop/src/store/coding-status.ts
index 5e434e0744d..fa524530234 100644
--- a/apps/desktop/src/store/coding-status.ts
+++ b/apps/desktop/src/store/coding-status.ts
@@ -3,8 +3,16 @@ import { atom, computed, type ReadableAtom } from 'nanostores'
import type { HermesGitWorktree, HermesRepoStatus } from '@/global'
import { desktopGit } from '@/lib/desktop-git'
-import { $worktreeRefreshToken } from './projects'
+import {
+ $projectScope,
+ $projectTree,
+ $worktreeDialog,
+ $worktreeRefreshToken,
+ ALL_PROJECTS,
+ projectRootCwd
+} from './projects'
import { $busy, $currentCwd, $selectedStoredSessionId } from './session'
+import { $focusedRuntimeId, $sessionStates } from './session-states'
import { $workspaceChangeTick } from './workspace-events'
// Live working-tree status for every git surface on screen — the data backbone
@@ -72,6 +80,33 @@ export function repoStatusForCwd(cwd?: null | string): ReadableAtom<HermesRepoSt
return $slice
}
+/**
+ * Is this path a git repo? This function reads the probe cache, and probes on
+ * demand when the cache has no entry for the path. Use it to validate any repo
+ * that was picked out of candidate FOLDERS: a path in a project row is not
+ * evidence that git can branch from it. False on a remote backend, because
+ * there is no local git truth to probe.
+ */
+export async function isGitRepoPath(cwd: string): Promise<boolean> {
+ const key = normalizeCwd(cwd)
+
+ if (!key) {
+ return false
+ }
+
+ if (key in $repoStatusByCwd.get()) {
+ return $repoStatusByCwd.get()[key] !== null
+ }
+
+ if (!desktopGit()?.repoStatus) {
+ return false
+ }
+
+ await refreshRepoStatus(key)
+
+ return ($repoStatusByCwd.get()[key] ?? null) !== null
+}
+
/** Reactive worktree list for one repo cwd. Stable per cwd. */
export function repoWorktreesForCwd(cwd?: null | string): ReadableAtom<HermesGitWorktree[]> {
const key = normalizeCwd(cwd)
@@ -434,3 +469,47 @@ export function _resetCodingStatusForTests(): void {
$repoWorktreesByCwd.set({})
$repoStatusLoading.set(false)
}
+
+// ── New-worktree target resolution ───────────────────────────────────────────
+// This code lives here and not in projects.ts. To pick the target, it must read
+// both the project state and the git truth, and coding-status already depends
+// on projects. A dependency in the other direction is a cycle.
+
+// The repo that a new worktree is cut from: the cwd of the focused surface, or
+// the root of the project the user entered. Both are things the user points at.
+// There is no "use some other project's repo" step, because that branches
+// somewhere the user never selected.
+//
+// A project root is not always a repo, so existence alone is not proof. Each
+// candidate is validated against the probe cache. This function is the only
+// authority on the target, so the hotkey no longer tests `$repoStatus` first,
+// and ⌘⇧B now works from a detached session inside a project. '' means that no
+// repo is in reach. That is a no-op and not an error, because a worktree only
+// exists inside a repo.
+export async function resolveWorktreeRepoPath(): Promise<string> {
+ const runtimeId = $focusedRuntimeId.get()
+ const scope = $projectScope.get()
+
+ const candidates = [
+ runtimeId ? ($sessionStates.get()[runtimeId]?.cwd ?? '') : '',
+ scope === ALL_PROJECTS ? '' : projectRootCwd($projectTree.get().find(node => node.id === scope))
+ ]
+
+ for (const candidate of candidates) {
+ const path = candidate.trim()
+
+ if (path && (await isGitRepoPath(path))) {
+ return path
+ }
+ }
+
+ return ''
+}
+
+export async function openWorktreeDialog(options?: { base?: string; repoPath?: string }): Promise<void> {
+ const repoPath = options?.repoPath?.trim() || (await resolveWorktreeRepoPath())
+
+ if (repoPath) {
+ $worktreeDialog.set({ base: options?.base, repoPath })
+ }
+}
diff --git a/apps/desktop/src/store/projects.ts b/apps/desktop/src/store/projects.ts
index 6bb3451a88b..c44365a9cb4 100644
--- a/apps/desktop/src/store/projects.ts
+++ b/apps/desktop/src/store/projects.ts
@@ -1138,15 +1138,26 @@ export interface StartWorkSessionRequest {
export const $startWorkSessionRequest = atom<StartWorkSessionRequest | null>(null)
-// Keyboard-driven "spin up a new worktree" intent. The composer's coding rail
-// owns the name dialog (it has the active repo + branch context), so a global
-// hotkey just bumps this token; the rail opens its branch-off dialog in
-// response. A monotonic token re-fires even on repeat presses. No-ops off a
-// repo (the rail isn't mounted), which is the right "nothing to branch" outcome.
-export const $newWorktreeRequest = atom(0)
-
-export function requestNewWorktree(): void {
- $newWorktreeRequest.set($newWorktreeRequest.get() + 1)
+// The "make a new worktree" intent, from the keyboard or a menu. One dialog is
+// mounted, in the sidebar beside ProjectDialog, and it reads this atom. This
+// mirrors $projectDialog. This atom was a monotonic token that every mounted
+// coding rail subscribed to. N composers on screen therefore gave N stacked
+// dialogs for one ⌘⇧B, and the dialog the user dismissed showed an identical
+// empty one behind it. One mount cannot double-open.
+//
+// `repoPath` is resolved when the dialog opens (see resolveWorktreeRepoPath).
+// It is not read from the rail that received the key, so the dialog always
+// targets the surface the user looks at.
+export interface WorktreeDialogState {
+ repoPath: string
+ /** The base branch selected in a "branch off from X" menu. */
+ base?: string
+}
+
+export const $worktreeDialog = atom<null | WorktreeDialogState>(null)
+
+export function closeWorktreeDialog(): void {
+ $worktreeDialog.set(null)
}
let startWorkToken = 0