Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(kanban): start an issue's agent in its own worktree, one click

reviewdd5dce6a29ed
diff --git a/CLAUDE.md b/CLAUDE.md
index c543e3bf6..b5b6b006a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -5234,6 +5234,50 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
safe slug is appended automatically. The shipped `../${repoName}.worktrees/${branch}` keeps
worktrees beside — not nested inside — the main checkout. There is no general project-settings
surface today, so the setting is intentionally global rather than hidden in a one-off menu.
+ - **One create-and-bind** (`renderer/lib/worktreeCreate.ts`, `createBoundWorktree`) — the New
+ worktree dialog, the `open-worktree` verb and the issue card's "Start with agent in a new
+ worktree" all create through it: `git worktree add` (a REJECTED call becomes a failure, never a
+ throw out of the caller), then `attachWorktree`. The frame's place is asked only once git
+ succeeded. `projectId` opts in to the "the canvas moved on during the await" refusal: the dialog
+ and the issue action pass it; `open-worktree` does not, and still binds to whatever is on screen
+ when git returns (unchanged, and a known gap). `git worktree add` is reached from ONE place
+ (`worktreeCreateDeps`), pinned by `canvas/issue-worktree.source.test.ts`. Three same-tick rules
+ the issue action rests on: `attachWorktree` writes the new frame into `nodesRef` beside its
+ `setNodes`, so a caller can open a node INTO a frame it just made; it closes the frame's setup
+ gate from the bind (`markGroupPending` before the `sharedPaths` materialize, released in a
+ `finally` once `startWorktreeSetup` took its own count), so a node opened into it at once holds
+ its launch — the hold is ONE rule, `setupHoldGroup`, shared with the control opens' `armAfter`;
+ and `addAgentNode` parents the node BEFORE `setNodes`, never inside the updater, because the
+ updater runs at render time and a zustand-flushed SyncLane render may already have mirrored
+ `nodesRef` back to a list without the fresh frame (the `nodesEpoch` lesson).
+ - **A worktree per GitHub issue** (`@shared/issue-worktree`) — "Start with agent in a new
+ worktree ▸" on an issue card and its summary modal: branch `issue-<N>-<slug>` off the repo's
+ default (`effectiveWorktreeBaseRef`) at the templated path, a frame titled `Issue #N`, and the
+ agent opened inside it with the same ref-only prompt and `issueRef` as "Start with agent" (one
+ `issueStartPrompt`, one `fileIssueSession` for both). The frame's binding is what links a pull
+ request from that branch to the session card. **The title is attacker-controlled**: the slug is
+ an allowlist `[a-z0-9-]` (lower-cased, NFKD with marks stripped so `café` → `cafe`; every other
+ script, lookalike, bidi or zero-width character is dropped), capped at `ISSUE_BRANCH_SLUG_MAX`
+ (40) and cut back to a word boundary, and `issue-<N>` alone when nothing survives; the name only
+ ever reaches git as one argv element, and the tests run the real `git check-ref-format --branch`
+ over the hostile set. **Nothing on disk is overwritten**: `planIssueWorktree` (filesystem only
+ through an injected probe; a probe that fails reads as "taken") offers REUSE of what the issue
+ already has — a frame on this canvas bound to `issue-<N>` / `issue-<N>-…` (open the agent in it),
+ an unbound worktree of the issue (adopt it, `createdByApp: false`), or the exact branch existing
+ but checked out nowhere (check it out) — beside the next free `-2` … `-20`; a name or folder that
+ is merely taken moves to the next suffix and the notice says why. Never the main checkout, never
+ a prunable registration. Disabled WITH its reason on a relay tab, an SSH project, a cwd-less
+ project and a folder with no repository (`issueWorktreeRefusal`). **There is no `--worktree`
+ flag**: an agent composes `open-worktree --branch issue-<N>-<slug>` then `open-agent --group
+ <groupId> --issue #N`, and both agent bodies render that convention from `issueWorktreeBranch`.
+ A flag was judged not worth it: the two calls already reach the identical end state; the
+ "worktree already exists" question needs a person's answer, which an agent gets from `list`
+ instead; the slug needs the issue title, which the control dispatch does not hold reliably (only
+ a subscribed board does), so the flag would name one issue's branch two ways; and a second copy
+ of `open-worktree`'s surface (`--base`, `--path`, dry run, setup holds, refusals) inside
+ `open-agent` is the drift this file warns about. Surfaces: Desktop and Server Edition (the
+ whole path is renderer + the existing git/fs/worktree bridges); a relay tab is refused (above);
+ the Omni board has no issue lanes; Mobile N/A like every worktree affordance.
- **One store, one poller** — `renderer/state/worktrees.ts` is the **only** caller of the worktree
/status *read* IPCs (`git.repoRoot`, `git.worktreeList`, `git.status`); the group chip, the
creation dialog and the Source Control panel all read that store. Three independent pollers would
@@ -5243,8 +5287,9 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
*deletion*) and **fails open**. Exactly **two** direct `git.status` reads live outside it, both in
`Canvas.tsx` and both deliberate: the one-shot probes on the **Remove** confirm (the dirty-file
count in the warning) and on **↪ Move into worktree** (staleness only arrives by poll, so the
- directory is re-checked immediately before an irreversible session kill). Anything recurring
- belongs in the store.
+ directory is re-checked immediately before an irreversible session kill). Two more one-shot
+ reads take only the local BRANCH list: the New worktree dialog's dropdown and the issue action's
+ planner (so a taken name is seen before git refuses it). Anything recurring belongs in the store.
- **Scoped Source Control** — the panel operates on a selected `ScmScope` (the main checkout or a
bound worktree). A worktree scope's **id is its group node id**, which is what lets the canvas
selection preselect it. `scmScopes` / `defaultScmScope` / `selectedScmGroupId`
@@ -5554,8 +5599,10 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
request) that opens the issue on the board (`openIssueOnBoard` →
`viewMode.requestedIssue`) ONLY when that board has GitHub sync — otherwise straight to GitHub,
rather than flipping the project's persisted view to a board that cannot show it — and the board
- itself falls back to GitHub when the issue is not on a fetched page. Never a dead click. No "start in a new worktree" UI yet: compose `open-worktree` + `open-agent --group --issue`
- (the skill says how). Surfaces: Desktop + Server Edition (renderer + core); Omni board shows no
+ itself falls back to GitHub when the issue is not on a fetched page. Never a dead click. **"Start
+ with agent in a new worktree ▸"** sits beside it on the card menu and in the summary modal: a
+ fresh `issue-<N>-<slug>` worktree frame with the agent inside, reuse offered when the issue
+ already has one — see the Worktrees bullet ("A worktree per GitHub issue"). Surfaces: Desktop + Server Edition (renderer + core); Omni board shows no
issue lanes; **Mobile does not render the binding** — `issueRef` reaches the phone inside the
project file, and nodeterm-ios ignores the unknown field (follow-up there).
**Where a card comes from is a registry, not a branch per call site** (`renderer/lib/kanbanSources.ts`,
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 45965b308..b86b0f013 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -311,6 +311,16 @@ anything else. Board-level fields survive every transform — `pullLinks` is one
against the renderer's dispositions — deliberately cross-layer, because that is the only way
"every verb" is checked rather than remembered.
+- **A node you just created is not in `nodesRef` yet, and a `setNodes` updater is not "now".**
+ `nodesRef` mirrors React state at render time, so a frame made this tick is invisible to the next
+ line that looks it up — and an updater runs at RENDER time, after any zustand write may already
+ have flushed a render that mirrored `nodesRef` back to a list without it. Compute anything that
+ reads `nodesRef` (parenting, a cwd, a position) BEFORE `setNodes`, and when one flow creates a
+ frame and a node inside it, do both in one synchronous block (`attachWorktree` writes the new
+ frame into `nodesRef` for exactly this). Every worktree creation goes through
+ `createBoundWorktree` (`renderer/lib/worktreeCreate.ts`); do not add a fourth copy of
+ "`git worktree add`, then bind".
+
- **A dialog raised on someone else's behalf must know that request's lifetime.** Main abandons a
canvas-control request after 120 s and tells the renderer nothing, so an unanswered dialog sat
there forever AND held the one-confirm-at-a-time guard, which refused every later destructive
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index dd6617b1c..a6601b893 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -16,6 +16,7 @@ import { nodeColorChoices } from '@shared/node-colors'
import { offScreenGuidanceLines } from '@shared/control-off-screen'
import { codexThreadIdentityResolverSh } from './codex-thread-identity-sh'
import { ISSUE_SESSION_COLUMNS, issueLaunchPrompt, parseIssueArg } from '../shared/github-issue-ref'
+import { ISSUE_BRANCH_SLUG_MAX, issueWorktreeBranch } from '../shared/issue-worktree'
/**
* The messaging verbs' retry guidance, RENDERED from `RETRYABLE` — the table is the source, and
@@ -52,6 +53,9 @@ function messagingGuidanceLines(): string[] {
function issueBindingDocLines(): string[] {
const { started, delivered } = ISSUE_SESSION_COLUMNS
const example = issueLaunchPrompt({ owner: 'owner', repo: 'repo', number: 123 })
+ // Rendered from the function the board's "Start with agent in a new worktree" names its branch
+ // with, so the convention an agent reads is the one the button follows.
+ const exampleBranch = issueWorktreeBranch(123, 'Fix login crash on Safari')
return [
'Issue-bound sessions (`--issue`):',
'- `open-agent --agent <id> --issue <owner/repo#N | #N>` (and `open-claude --issue …`) starts a session ON',
@@ -65,8 +69,14 @@ function issueBindingDocLines(): string[] {
' `#N` means the repository this project\'s kanban board syncs with; with no repository configured it is',
' refused — pass `owner/repo#N`. The value must be exactly `owner/repo#N` or `#N`: anything else is refused,',
' never repaired. With `--prompt-file` the file is the whole brief, so name the issue in it.',
- ' `--dry-run` reports the resolved reference. For a branch per issue:',
- ' `open-worktree --branch issue-<N>-<slug>`, then `open-agent --agent <id> --group <groupId> --issue #N`.',
+ ' `--dry-run` reports the resolved reference.',
+ '- A worktree per issue is two calls — what the board\'s "Start with agent in a new worktree" does:',
+ ` \`open-worktree --branch ${exampleBranch}\` (\`issue-<N>-\` then the title in lower-case ASCII letters,`,
+ ` digits and \`-\`, at most ${ISSUE_BRANCH_SLUG_MAX} characters), then`,
+ ' `open-agent --agent <id> --group <groupId> --issue #N` with the `groupId` it replied. The frame\'s branch is',
+ ' what links a pull request from it to the session card. Check `list` first: a frame titled `Issue #N` or',
+ ' `issue-<N>-…` already holds that issue\'s worktree — open into it with `--group` instead of making a second',
+ ' one. `open-worktree` never overwrites: a branch that already exists fails, so pick the next `-2`.',
'- If YOUR session was started on an issue (your first prompt names it; `list` marks your row',
' `issue owner/repo#N`), keep this contract:',
' - Unless your first prompt named a narrower task, the issue IS your task: read it, then investigate,',
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index 0b270f626..d884364d6 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect } from 'vitest'
+import { ISSUE_BRANCH_SLUG_MAX } from '../shared/issue-worktree'
import {
parseControlRequest,
isDestructiveVerb,
@@ -1198,6 +1199,18 @@ describe('--issue: GitHub issue-bound sessions', () => {
expect(flat).toContain('The end of a turn moves nothing')
})
+ it.each(bodies)('%s documents a worktree per issue as the two-call composition, with the board\'s own branch rule', (_name, body) => {
+ const flat = body.replace(/\s+/g, ' ')
+ // Rendered from `issueWorktreeBranch`, the function the board's button names its branch with.
+ expect(flat).toContain('`open-worktree --branch issue-123-fix-login-crash-on-safari`')
+ expect(flat).toContain(`at most ${ISSUE_BRANCH_SLUG_MAX} characters`)
+ expect(flat).toContain('`open-agent --agent <id> --group <groupId> --issue #N`')
+ expect(flat).toContain('Check `list` first: a frame titled `Issue #N` or `issue-<N>-…` already holds')
+ expect(flat).toContain('`open-worktree` never overwrites')
+ // No `--worktree` flag exists; the docs must not invent one.
+ expect(body).not.toMatch(/--issue[^\n]*--worktree|--worktree[^\n]*--issue/)
+ })
+
it.each(bodies)('%s never promises an automatic post to GitHub', (_name, body) => {
expect(body).not.toMatch(/automatically (post|comment|close)/i)
expect(body).not.toMatch(/nodeterm (posts|comments|closes)/i)
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 511f221a8..43aa2bb71 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -416,7 +416,6 @@ import {
isRemoteSessionNode,
resolveBaseRef,
sanitizeWorktreeBranch,
- worktreeFromCreate,
worktreeFromEntry,
worktreeRemoveMessage,
resolveWorktreeBase,
@@ -474,11 +473,20 @@ import { applyIconChoice } from '../lib/nodeIconChoice'
import type { NodeIcon } from '@shared/node-icon'
import {
formatIssueRef,
+ issueKey,
issueLaunchPrompt,
issueRefFromHtmlUrl,
normalizeIssueRef,
type IssueRef
} from '@shared/github-issue-ref'
+import { planIssueWorktree } from '@shared/issue-worktree'
+import {
+ issueWorktreeChoiceCopy,
+ issueWorktreeRefusal,
+ issueWorktreeRenamedNotice,
+ type IssueWorktreeChoice,
+ type IssueWorktreeMenuAnswer
+} from '../lib/issueWorktree'
import { runEndedEntry, runStartedEntry } from '../lib/issueRuns'
import { resolveIssueFlagFor, type IssueFlagResult } from '../lib/issueFlag'
import type { GitHubIssueCardView } from '@shared/github-issues'
@@ -514,6 +522,11 @@ import {
LAUNCH_STALL_MS,
type ArmedNode
} from '../lib/pendingLaunch'
+import {
+ createBoundWorktree,
+ type CreateBoundWorktreeDeps,
+ type WorktreeAttachTarget
+} from '../lib/worktreeCreate'
import { WAIT_LABEL, dropAfterDep, edgeHidden, hiddenEdgeNodeIds, missingDepRopes, ropeInfoOf, ropeVisual } from '../lib/edgeModel'
import { triggerEdges } from '../lib/triggerCard'
import {
@@ -692,6 +705,7 @@ import {
refitMaximizedNode,
restoreMaximizedNode,
placeNodeInRect,
+ terminalNodeSize,
type CanvasNode
} from '../state/workspace'
import { codexAccountSelectable, codexAccountSwitchStillEligible } from './codex-account-switch'
@@ -1990,6 +2004,25 @@ export function Canvas() {
const s = useProjectSetup.getState()
return setupGateDone(s.runForGroup(groupId), s.pendingForGroup(groupId) > 0)
}, [])
+ /**
+ * Should a node opened INTO this frame hold its launch for the frame's setup script? Returns the
+ * group to wait on (`PendingLaunch.awaitSetupGroup`), or undefined to launch as usual. A group
+ * counts while its launch is still PENDING (the ack — and with it `waitForSetup` — has not come
+ * back yet; holding is the safe side of that unknown, and a non-waiting ack releases it again) or
+ * while its acked run said `waitForSetup` and has not finished. Shared by the control opens
+ * (`armAfter`) and the issue card's "Start with agent in a new worktree".
+ */
+ const setupHoldGroup = useCallback(
+ (groupId: string | null | undefined): string | undefined => {
+ if (!groupId) return undefined
+ const holds =
+ (useProjectSetup.getState().pendingForGroup(groupId) > 0 ||
+ setupWaitGroupsRef.current.has(groupId)) &&
+ !setupDoneForGroup(groupId)
+ return holds ? groupId : undefined
+ },
+ [setupDoneForGroup]
+ )
// A signature over the setup-run state of every group an armed node is waiting on, so a run going
// `done` re-runs the launch effect — the same trick as `armedDepSig`. Subscribing to the whole
// store would re-render the canvas on every output chunk of every script.
@@ -4039,7 +4072,8 @@ export function Canvas() {
* board) — otherwise every one lands on the view center and piles into a stack you only discover
* when you switch back to the canvas. Returns undefined only if the view isn't measured yet.
*/
- const emptyNodePos = useCallback((): { x: number; y: number } | undefined => {
+ // `box` places something other than a default-sized node — a worktree frame, say.
+ const emptyNodePos = useCallback((box?: { w: number; h: number }): { x: number; y: number } | undefined => {
const preferred = viewCenter()
if (!preferred) return undefined
const s = useSettings.getState().settings
@@ -4056,7 +4090,7 @@ export function Canvas() {
w: (n.measured?.width as number | undefined) ?? (n.width as number | undefined) ?? w,
h: (n.measured?.height as number | undefined) ?? (n.height as number | undefined) ?? h
}))
- return freeSpot(boxes, preferred, { w, h })
+ return freeSpot(boxes, preferred, box ?? { w, h })
}, [viewCenter])
/** The checkout a Source Control action refers to. The panel hands its ACTIVE SCOPE's cwd
@@ -5123,7 +5157,10 @@ export function Canvas() {
// A GitHub issue binding (Start with agent on an issue card). Stamped on the node AFTER the
// factory: it drives chips and run history only — the launch prompt was already composed
// from it by `issueLaunchPrompt`, the one place a reference may become text in a pane.
- extra?: { issueRef?: IssueRef }
+ // `awaitSetupGroup` holds the launch for that worktree frame's setup script (the issue card's
+ // "Start with agent in a new worktree" opens the agent in the same tick as the frame) — the
+ // same `PendingLaunch` hold a control open into a preparing frame gets (`setupHoldGroup`).
+ extra?: { issueRef?: IssueRef; awaitSetupGroup?: string }
): { node: CanvasNode; projectId: string } | undefined => {
// Resolve the target project LIVE, at click time — never from this callback's render
// closure. Menu onClick closures outlive the render that built them (`setMenu` freezes
@@ -5208,8 +5245,13 @@ export function Canvas() {
model
)
const issueRef = normalizeIssueRef(extra?.issueRef)
- const node = issueRef ? { ...created, data: { ...created.data, issueRef } } : created
- setNodes((ns) => [...ns, groupId ? parentInto(node, groupId) : node])
+ const bound = issueRef ? { ...created, data: { ...created.data, issueRef } } : created
+ const node = extra?.awaitSetupGroup ? queueControlLaunch(bound, [], extra.awaitSetupGroup) : bound
+ // Parented HERE, not inside the updater: the updater runs at render time, and a render that
+ // a zustand write flushes first (SyncLane, skipping this DefaultLane update) mirrors
+ // `nodesRef` back to state — which does not hold a frame `attachWorktree` created this tick.
+ const placed = groupId ? parentInto(node, groupId) : node
+ setNodes((ns) => [...ns, placed])
markDirty()
// The project this node was charged to — the caller files anything else about the node (a
// board card, its run history) against THIS id, never a second live read of the store.
@@ -6105,24 +6147,27 @@ export function Canvas() {
// carries no cwd of its own — the worktree's path is what its children inherit
// (`cwdForNewNodeIn`), so the frame IS the binding.
const attachWorktree = useCallback(
- (
- target: { groupId: string | null; at?: { x: number; y: number }; size?: { width: number; height: number } },
- wt: GroupWorktree
- ): string => {
+ (target: WorktreeAttachTarget, wt: GroupWorktree): string => {
let groupId = target.groupId
if (groupId) {
- setNodes((ns) =>
+ const bind = (ns: CanvasNode[]): CanvasNode[] =>
ns.map((n) => (n.id === groupId ? { ...n, data: { ...n.data, worktree: wt } } : n))
- )
+ // The ref too, not only state: a caller that opens a node into this frame in the SAME tick
+ // (the issue card's "Start with agent in a new worktree") resolves the frame's cwd and
+ // position through `nodesRef`, which otherwise catches up only at the next render.
+ nodesRef.current = bind(nodesRef.current)
+ setNodes((ns) => bind(ns as CanvasNode[]))
} else {
const group = createGroupNode(
target.at ?? viewCenter() ?? { x: 0, y: 0 },
- WORKTREE_GROUP_SIZE,
+ target.size ?? WORKTREE_GROUP_SIZE,
nodesRef.current.length
)
- group.data = { ...group.data, title: wt.branch, worktree: wt }
+ group.data = { ...group.data, title: target.title ?? wt.branch, worktree: wt }
groupId = group.id
- // Parents must come first — React Flow requires a group before its children.
+ // Parents must come first — React Flow requires a group before its children. The ref gets
+ // it at once for the same reason as the bind branch above.
+ nodesRef.current = [group, ...nodesRef.current]
setNodes((ns) => [group, ...(ns as CanvasNode[])])
}
markDirty()
@@ -6135,12 +6180,24 @@ export function Canvas() {
// BEFORE the setup script runs, so a setup `npm install` sees those links. Fire-and-forget re
// the bind (it never blocks the frame), but ORDERED before `startWorktreeSetup` — main reads
// the sharedPaths list itself by projectId and validates `wt.path`, so a `[]`/reject is safe.
+ //
+ // The setup gate is closed from THIS moment, not only once `startWorktreeSetup` asks for the
+ // run: a node opened into the frame while the shared paths are still being linked (the issue
+ // card opens its agent in the same tick; an `open-agent --group` right after the
+ // `open-worktree` reply can land there too) must hold like one opened a moment later. The
+ // count is released in `finally`, after `startWorktreeSetup` took its own.
+ const setupGroupId = groupId
+ useProjectSetup.getState().markGroupPending(setupGroupId)
void (async () => {
- const projectId = useProjects.getState().activeProjectId
- if (projectId) {
- await window.nodeTerminal.worktree.materializeShared(projectId, wt.path).catch(() => {})
+ try {
+ const projectId = useProjects.getState().activeProjectId
+ if (projectId) {
+ await window.nodeTerminal.worktree.materializeShared(projectId, wt.path).catch(() => {})
+ }
+ startWorktreeSetup(setupGroupId, wt.path)
+ } finally {
+ useProjectSetup.getState().clearGroupPending(setupGroupId)
}
- startWorktreeSetup(groupId, wt.path)
})()
// The bound group's id (fresh one when created here) — nodesRef lags setNodes, so
// callers that need the id (agent-control's open-worktree reply) take it from here.
@@ -6149,6 +6206,19 @@ export function Canvas() {
[setNodes, markDirty, viewCenter, refreshWorktreeStore, startWorktreeSetup]
)
+ /** What `createBoundWorktree` (lib/worktreeCreate) runs on: this session's git, the live active
+ * project, and `attachWorktree`. One builder for all three callers. `attach` may be wrapped by a
+ * caller that must open a node into the frame in the SAME tick (the issue action). */
+ const worktreeCreateDeps = useCallback(
+ (attach: CreateBoundWorktreeDeps['attach'] = attachWorktree): CreateBoundWorktreeDeps => ({
+ worktreeAdd: (repoPath, wtPath, branch, baseRef, isNew) =>
+ api.git.worktreeAdd(repoPath, wtPath, branch, baseRef, isNew),
+ activeProjectId: () => useProjects.getState().activeProjectId,
+ attach
+ }),
+ [api, attachWorktree]
+ )
+
const createWorktreeAndGroup = useCallback(
async (v: WorktreeCreateValue) => {
const target = worktreeDialog
@@ -6157,26 +6227,24 @@ export function Canvas() {
setWorktreeError(null)
// A REJECTED ipc is not the same as a failed op, and both have to land here. The Server
// Edition reaches git over WS-RPC, and a socket that drops mid-create rejects this promise
- // (`E_DISCONNECTED`) — without the catch the `await` threw straight out of the callback,
- // `setWorktreeBusy(false)` never ran, and the dialog sat on "Creating…" with its own Cancel
- // button disabled by `busy`: no error, no way out but Escape. Fail closed — clear busy, say so
- // inline, and leave the dialog open so the user can retry. (The sibling READS in this feature
- // catch for exactly this reason; the three destructive calls did not.)
- const res = await api.git
- .worktreeAdd(v.repoPath, v.path, v.branch, v.baseRef, v.mode === 'new')
- .catch((e: unknown) => ({
- ok: false as const,
- message: `Could not create the worktree: ${e instanceof Error ? e.message : String(e)}`
- }))
+ // (`E_DISCONNECTED`) — `createBoundWorktree` turns that into a failure instead of throwing
+ // out of this callback, where `setWorktreeBusy(false)` never ran and the dialog sat on
+ // "Creating…" with its own Cancel disabled. Fail closed — clear busy, say so inline, and
+ // leave the dialog open so the user can retry.
+ const res = await createBoundWorktree(worktreeCreateDeps(), v, {
+ target: () => target,
+ projectId: target.projectId
+ })
setWorktreeBusy(false)
- if (!res.ok) {
- setWorktreeError(res.message) // inline, never window.alert
+ if (!res.ok && res.reason === 'git') {
+ // inline, never window.alert
+ setWorktreeError(res.rejected ? `Could not create the worktree: ${res.message}` : res.message)
return
}
// The worktree exists now, but the canvas may have moved on during the await: binding it to
- // whatever is on screen would attach ANOTHER repo's worktree to this project. Leave it as an
- // orphan (the dialog will offer it again on its own project) and say so.
- if (useProjects.getState().activeProjectId !== target.projectId) {
+ // whatever is on screen would attach ANOTHER repo's worktree to this project. Left as an
+ // orphan (the dialog will offer it again on its own project) — say so.
+ if (!res.ok) {
setWorktreeDialog(null)
setNotice({
kind: 'info',
@@ -6184,11 +6252,9 @@ export function Canvas() {
})
return
}
- // We created this directory, so `createdByApp` is true — Remove may delete it.
- attachWorktree(target, worktreeFromCreate(v))
setWorktreeDialog(null)
},
- [attachWorktree, worktreeDialog]
+ [worktreeCreateDeps, worktreeDialog]
)
const bindExistingWorktree = useCallback(
@@ -6519,6 +6585,7 @@ export function Canvas() {
// '' (refresh no-ops, wrong SSH gate). The ref always holds this render's instances.
const worktreeControlRef = useRef({
attachWorktree,
+ worktreeCreateDeps,
releaseWorktreeBinding,
clearWorktreeBinding,
requestRemoveWorktree,
@@ -6527,6 +6594,7 @@ export function Canvas() {
useEffect(() => {
worktreeControlRef.current = {
attachWorktree,
+ worktreeCreateDeps,
releaseWorktreeBinding,
clearWorktreeBinding,
requestRemoveWorktree,
@@ -10034,19 +10102,21 @@ export function Canvas() {
* unpruned direct write `createNodeInColumn` uses, for the same reason: the fresh node is not in
* the derived session list yet). The issue card's run history gets `run-started`.
*/
- const startIssueAgent = useCallback(
- (issue: GitHubIssueCardView, agentId: AgentId, accountId?: string | null) => {
- const ref = issueRefFromHtmlUrl(issue.htmlUrl, issue.number)
- const prompt = ref ? issueLaunchPrompt(ref) : undefined
- if (!ref || !prompt) {
- setNotice({
- kind: 'error',
- text: `Could not start an agent on #${issue.number}: its GitHub address could not be read. Nothing was started.`
- })
- return
- }
- const created = addAgentNode(agentId, undefined, undefined, accountId, prompt, { issueRef: ref })
- if (!created) return // addAgentNode already said why
+ /**
+ * What every issue start does once its agent node exists: file the new session card under the
+ * issue card's column (board metadata only — the same unpruned direct write `createNodeInColumn`
+ * uses, for the same reason: the fresh node is not in the derived session list yet), log its
+ * `card-created`, and record `run-started` on the issue card's history. ONE place for both
+ * "Start with agent" and "Start with agent in a new worktree", so the two cannot file a run
+ * differently.
+ */
+ const fileIssueSession = useCallback(
+ (
+ issue: GitHubIssueCardView,
+ ref: IssueRef,
+ created: { node: CanvasNode; projectId: string },
+ agentId: AgentId
+ ) => {
const { node, projectId: targetProjectId } = created
const nodeId = node.id
// The project addAgentNode charged the node to (its guarded, live read) — not a second read.
@@ -10077,7 +10147,37 @@ export function Canvas() {
})
if (started) useBoardLog.getState().append(api, targetProjectId, started)
},
- [addAgentNode, seedBoard, markDirty, api]
+ [seedBoard, markDirty, api]
+ )
+
+ /** The reference + first prompt of an issue start, or a notice saying why nothing started. */
+ const issueStartPrompt = useCallback(
+ (issue: GitHubIssueCardView): { ref: IssueRef; prompt: string } | undefined => {
+ const ref = issueRefFromHtmlUrl(issue.htmlUrl, issue.number)
+ const prompt = ref ? issueLaunchPrompt(ref) : undefined
+ if (!ref || !prompt) {
+ setNotice({
+ kind: 'error',
+ text: `Could not start an agent on #${issue.number}: its GitHub address could not be read. Nothing was started.`
+ })
+ return undefined
+ }
+ return { ref, prompt }
+ },
+ []
+ )
+
+ const startIssueAgent = useCallback(
+ (issue: GitHubIssueCardView, agentId: AgentId, accountId?: string | null) => {
+ const start = issueStartPrompt(issue)
+ if (!start) return
+ const created = addAgentNode(agentId, undefined, undefined, accountId, start.prompt, {
+ issueRef: start.ref
+ })
+ if (!created) return // addAgentNode already said why
+ fileIssueSession(issue, start.ref, created, agentId)
+ },
+ [addAgentNode, issueStartPrompt, fileIssueSession]
)
/** The "Start with agent ▸" rows for one issue card: the canvas's own agent + account picker
@@ -10091,6 +10191,268 @@ export function Canvas() {
[agentCreationEntries, startIssueAgent]
)
+ // ---- GitHub issue → agent session in its OWN worktree ("Start with agent in a new worktree ▸") ----
+ /** The reuse-or-new question, when the issue already has a worktree (or its branch exists). */
+ const [issueWorktreeAsk, setIssueWorktreeAsk] = useState<{
+ message: string
+ options: { value: IssueWorktreeChoice; label: string }[]
+ value: IssueWorktreeChoice
+ run: (choice: IssueWorktreeChoice) => void
+ } | null>(null)
+ /** Issues with a start in flight — a second click while git works is refused, not doubled. */
+ const issueWorktreeInFlightRef = useRef(new Set<string>())
+
+ /** Why "Start with agent in a new worktree" cannot run on the ACTIVE project, or null. Read at
+ * click time (menus are built then), so it always describes the canvas on screen. */
+ const issueWorktreeUnavailable = useCallback((): string | null => {
+ const projectId = useProjects.getState().activeProjectId
+ const project = useProjects.getState().getProject(projectId ?? '')
+ return issueWorktreeRefusal({
+ relay: sessionForProject(projectId ?? '').source === 'relay',
+ ssh: !!project?.ssh,
+ cwd: project?.cwd,
+ repoRoot: useWorktrees.getState().repoRoot
+ })
+ }, [])
+
+ /**
+ * Open the issue's agent INTO a worktree frame, in the same tick the frame was made (or found).
+ * Synchronous on purpose: `attachWorktree` has just put the frame in `nodesRef`, and a render in
+ * between — a zustand write flushes one — would mirror the ref back to a node list without it,
+ * so the agent's cwd would fall back to the project folder. The frame grows when the new slot
+ * would not fit (the same grid the control opens use, `groupSlot` / `groupSizeFor`).
+ */
+ const openIssueAgentInFrame = useCallback(
+ (
+ groupId: string,
+ issue: GitHubIssueCardView,
+ start: { ref: IssueRef; prompt: string },
+ agentId: AgentId,
+ accountId: string | null | undefined
+ ): boolean => {
+ const all = nodesRef.current
+ const group = all.find((n) => n.id === groupId)
+ if (!group) return false
+ const size = terminalNodeSize()
+ const children = all.filter((n) => n.parentId === groupId).length
+ const need = groupSizeFor(children + 1, size.width, size.height)
+ const width = Math.max((group.width as number | undefined) ?? 0, need.width)
+ const height = Math.max((group.height as number | undefined) ?? 0, need.height)
+ if (width !== group.width || height !== group.height) {
+ const grow = (ns: CanvasNode[]): CanvasNode[] =>
+ ns.map((n) =>
+ n.id === groupId ? { ...n, width, height, style: { ...n.style, width, height } } : n
+ )
+ nodesRef.current = grow(nodesRef.current)
+ setNodes((ns) => grow(ns as CanvasNode[]))
+ }
+ const slot = groupSlot(children, size.width, size.height)
+ const origin = absolutePosition(group as FocusableNode, all as FocusableNode[])
+ const created = addAgentNode(
+ agentId,
+ { x: origin.x + slot.x, y: origin.y + slot.y },
+ groupId,
+ accountId,
+ start.prompt,
+ // A frame whose setup script is still preparing the checkout holds the launch, exactly like
+ // a control open into it; a frame with nothing to prepare launches at once.
+ { issueRef: start.ref, awaitSetupGroup: setupHoldGroup(groupId) }
+ )
+ if (!created) return false // addAgentNode already said why
+ fileIssueSession(issue, start.ref, created, agentId)
+ return true
+ },
+ [setNodes, addAgentNode, setupHoldGroup, fileIssueSession]
+ )
+
+ /**
+ * "Start with agent in a new worktree" on a GitHub issue card: a git worktree on a branch named
+ * `issue-<N>-<slug>` off the repo's default branch (at the configured worktree location), a group
+ * frame titled after the issue number bound to it, and the issue's agent opened inside — the same
+ * ref-only launch prompt and `issueRef` as "Start with agent". The frame's binding is what lets a
+ * pull request from that branch find this session card by branch.
+ *
+ * The branch is slugged from the issue TITLE, which anyone can write on a public repository, so
+ * `@shared/issue-worktree` owns every rule about it; nothing here builds a name. An existing
+ * worktree for the issue (or an existing branch of the same name) is offered for reuse beside a
+ * fresh `-2`; nothing on disk is ever overwritten.
+ */
+ const startIssueAgentInWorktree = useCallback(
+ async (issue: GitHubIssueCardView, agentId: AgentId, accountId?: string | null) => {
+ const refusal = issueWorktreeUnavailable()
+ if (refusal) {
+ setNotice({ kind: 'error', text: `Could not start on #${issue.number} in a new worktree: ${refusal}.` })
+ return
+ }
+ const start = issueStartPrompt(issue)
+ if (!start) return
+ const key = issueKey(start.ref) ?? `#${issue.number}`
+ if (issueWorktreeInFlightRef.current.has(key)) {
+ setNotice({ kind: 'info', text: `A worktree for #${issue.number} is already being prepared.` })
+ return
+ }
+ const projectId = useProjects.getState().activeProjectId
+ const project = useProjects.getState().getProject(projectId ?? '')
+ const { repoRoot, entries, staleGroupIds } = useWorktrees.getState()
+ if (!projectId || !project || !repoRoot) return // issueWorktreeUnavailable already refused these
+ issueWorktreeInFlightRef.current.add(key)
+ try {
+ // Same defaults as the New worktree dialog and `open-worktree`: a project override, else
+ // the repo's default branch and the global location template.
+ const pw = projectLaunchInfoNow(project.id)?.resolved.worktree
+ const defaults = { basePath: pw?.basePath?.value, baseRef: pw?.baseRef?.value }
+ const baseRef = effectiveWorktreeBaseRef(defaults, entries)
+ const template = effectiveWorktreeTemplate(
+ defaults,
+ useSettings.getState().settings.worktreePathTemplate
+ )
+ // Local branches, so a taken name is seen before git refuses it. Unreadable = null: git
+ // then has the last word, and says so in the notice.
+ const branches = await api.git.status(repoRoot).then(
+ (st) => st.branches ?? null,
+ () => null
+ )
+ const bound = boundGroups(nodesRef.current)
+ .filter((b) => !staleGroupIds.includes(b.groupId))
+ .map((b) => ({ groupId: b.groupId, branch: b.worktree.branch, path: b.worktree.path }))
+ const plan = await planIssueWorktree(
+ { number: start.ref.number, title: issue.title, repoRoot, template, entries, branches, bound },
+ (path) => api.fs.exists(path)
+ )
+ // The canvas may have moved on while git and the filesystem answered: everything below
+ // writes into the canvas on screen.
+ if (useProjects.getState().activeProjectId !== projectId) {
+ setNotice({ kind: 'info', text: `The project changed, so nothing was started for #${issue.number}.` })
+ return
+ }
+ if (plan.kind === 'refused') {
+ setNotice({ kind: 'error', text: `Could not start on #${issue.number} in a new worktree: ${plan.reason}` })
+ return
+ }
+ const size = terminalNodeSize()
+ const need = groupSizeFor(1, size.width, size.height)
+ const frame = {
+ width: Math.max(WORKTREE_GROUP_SIZE.width, need.width),
+ height: Math.max(WORKTREE_GROUP_SIZE.height, need.height)
+ }
+ const newFrame = (): WorktreeAttachTarget => ({
+ groupId: null,
+ at: emptyNodePos({ w: frame.width, h: frame.height }),
+ size: frame,
+ title: `Issue #${start.ref.number}`
+ })
+ /** Create (`mode: 'new'`, or check out an existing branch) and bind, then open the agent. */
+ const create = async (
+ target: { branch: string; path: string },
+ mode: 'new' | 'existing',
+ renamedFrom?: string
+ ): Promise<void> => {
+ let opened = false
+ const out = await createBoundWorktree(
+ worktreeCreateDeps((t, wt) => {
+ const groupId = attachWorktree(t, wt)
+ opened = openIssueAgentInFrame(groupId, issue, start, agentId, accountId)
+ return groupId
+ }),
+ { repoPath: repoRoot, mode, branch: target.branch, baseRef, path: target.path },
+ { target: newFrame, projectId }
+ )
+ if (!out.ok && out.reason === 'git') {
+ setNotice({
+ kind: 'error',
+ text: `Could not create the worktree for #${issue.number}: ${out.message}`
+ })
+ return
+ }
+ if (!out.ok) {
+ setNotice({
+ kind: 'info',
+ text: `Created worktree ${target.branch} at ${target.path}. The project changed, so no group or agent was started.`
+ })
+ return
+ }
+ if (!opened) return // the frame is bound; addAgentNode already said why the agent is not
+ setNotice({
+ kind: 'info',
+ text: renamedFrom
+ ? issueWorktreeRenamedNotice(renamedFrom, target.branch)
+ : `Worktree ${target.branch} created at ${target.path}; the agent opens there.`
+ })
+ }
+ if (plan.kind === 'create') {
+ await create(plan.target, 'new', plan.renamedFrom)
+ return
+ }
+ const { existing, alternative } = plan
+ const copy = issueWorktreeChoiceCopy(start.ref.number, existing, alternative, baseRef)
+ setIssueWorktreeAsk({
+ ...copy,
+ run: (choice) => {
+ // Re-asked at the click: the dialog stays up for as long as the person reads it.
+ if (useProjects.getState().activeProjectId !== projectId) {
+ setNotice({ kind: 'info', text: `The project changed, so nothing was started for #${issue.number}.` })
+ return
+ }
+ if (choice === 'new') {
+ if (alternative) void create(alternative, 'new')
+ return
+ }
+ if (existing.kind === 'branch') {
+ void create({ branch: existing.branch, path: existing.path }, 'existing')
+ return
+ }
+ if (existing.kind === 'bound') {
+ const live = nodesRef.current.find((n) => n.id === existing.groupId)
+ const stale = useWorktrees.getState().staleGroupIds.includes(existing.groupId)
+ if (!live || stale || live.data.worktree?.path !== existing.path) {
+ setNotice({
+ kind: 'error',
+ text: `The worktree group for #${issue.number} is gone or no longer bound. Nothing was started.`
+ })
+ return
+ }
+ openIssueAgentInFrame(existing.groupId, issue, start, agentId, accountId)
+ return
+ }
+ // An unbound worktree on disk: adopt it (the app did not create it, so Remove will
+ // never delete it), then open the agent inside, in the same tick.
+ const wt = worktreeFromEntry(existing.entry, repoRoot, resolveBaseRef(entries))
+ if (!wt) return
+ const groupId = attachWorktree(newFrame(), wt)
+ openIssueAgentInFrame(groupId, issue, start, agentId, accountId)
+ }
+ })
+ } finally {
+ issueWorktreeInFlightRef.current.delete(key)
+ }
+ },
+ [
+ issueWorktreeUnavailable,
+ issueStartPrompt,
+ api,
+ emptyNodePos,
+ worktreeCreateDeps,
+ attachWorktree,
+ openIssueAgentInFrame
+ ]
+ )
+
+ /** The "Start with agent in a new worktree ▸" rows (the same agent + account picker), or the
+ * reason the action cannot run on this project — the board shows that DISABLED, never hidden. */
+ const issueWorktreeMenu = useCallback(
+ (issue: GitHubIssueCardView): IssueWorktreeMenuAnswer => {
+ const refusal = issueWorktreeUnavailable()
+ if (refusal) return { refusal }
+ return {
+ items: agentCreationEntries(undefined, undefined, {
+ onPick: (aid, acct) => void startIssueAgentInWorktree(issue, aid, acct),
+ label: (agentLabel) => agentLabel
+ }).map((entry) => entry.item)
+ }
+ },
+ [agentCreationEntries, issueWorktreeUnavailable, startIssueAgentInWorktree]
+ )
+
// Global kanban swimlane "New session" path — creates a node in the target project's
// swimlane even when that project is not the active canvas. The per-column create
// menu in GlobalKanbanView dispatches this, and we switch to the target project
@@ -11717,15 +12079,7 @@ export function Canvas() {
): CanvasNode => {
const command = node.data.initialCommand as string | undefined
if (!command) return node
- // A group counts while its launch is still PENDING (the ack — and with it `waitForSetup` —
- // has not come back yet; holding is the safe side of that unknown, and a non-waiting ack
- // releases these again) or while its acked run said `waitForSetup` and has not finished.
- const holdsForSetup =
- !!intoGroup &&
- (useProjectSetup.getState().pendingForGroup(intoGroup) > 0 ||
- setupWaitGroupsRef.current.has(intoGroup)) &&
- !setupDoneForGroup(intoGroup)
- const awaitSetupGroup = holdsForSetup ? intoGroup ?? undefined : undefined
+ const awaitSetupGroup = setupHoldGroup(intoGroup)
// Always retain the command until the PTY-ready delivery loop acknowledges it.
// Node creation (even on screen) is not command delivery.
return queueControlLaunch(node, after, awaitSetupGroup)
@@ -12700,31 +13054,34 @@ export function Canvas() {
})
return
}
- const res = await api.git
- .worktreeAdd(repoRoot, wtPath, branch, baseRef, true)
- .catch((e: unknown) => ({
- ok: false as const,
- message: e instanceof Error ? e.message : String(e)
- }))
- if (!res.ok) {
- reply({ ok: false, error: `open-worktree: ${res.message}` })
+ // The shared create-and-bind (lib/worktreeCreate), WITHOUT its project-changed refusal:
+ // this verb has always bound to the canvas on screen when git returns.
+ const created = await createBoundWorktree(
+ worktreeControlRef.current.worktreeCreateDeps(),
+ { repoPath: repoRoot, mode: 'new', branch, baseRef, path: wtPath },
+ {
+ // A fresh frame takes the first free cell under the caller, like every other open.
+ // (This used to fan by the number of top-level frames on the canvas, which landed a
+ // frame on whatever terminal happened to sit at that offset.) The claim is keyed by
+ // a placeholder id — `attachWorktree` mints the real one — so it simply ages out.
+ // Asked only once git succeeded, against the canvas as it is then.
+ target: () => ({
+ groupId: bindGroupId,
+ at: bindGroupId
+ ? undefined
+ : settleBelowSource(nodesRef.current as PlaceableNode[], ctlProject?.id ?? '', {
+ id: `pending-worktree-${requestId}`,
+ position: { x: 0, y: 0 },
+ ...WORKTREE_GROUP_SIZE
+ }).position
+ })
+ }
+ )
+ if (!created.ok) {
+ reply({ ok: false, error: `open-worktree: ${created.reason === 'git' ? created.message : 'the project changed'}` })
return
}
- // A fresh frame takes the first free cell under the caller, like every other open.
- // (This used to fan by the number of top-level frames on the canvas, which landed a
- // frame on whatever terminal happened to sit at that offset.) The claim is keyed by a
- // placeholder id — `attachWorktree` mints the real one — so it simply ages out.
- const frameAt = bindGroupId
- ? undefined
- : settleBelowSource(nodesRef.current as PlaceableNode[], ctlProject?.id ?? '', {
- id: `pending-worktree-${requestId}`,
- position: { x: 0, y: 0 },
- ...WORKTREE_GROUP_SIZE
- }).position
- const groupId = worktreeControlRef.current.attachWorktree(
- { groupId: bindGroupId, at: frameAt },
- worktreeFromCreate({ repoPath: repoRoot, mode: 'new', branch, baseRef, path: wtPath })
- )
+ const groupId = created.groupId
reply({
ok: true,
message: `opened worktree ${branch} (off ${baseRef || 'the repo default branch'}${baseNote}) at ${wtPath} in group ${groupId}`,
@@ -15740,6 +16097,7 @@ export function Canvas() {
accountMenuItems={accountSwitchRows}
onAutoMoveFromPulls={autoMoveCardFromPulls}
issueAgentMenu={issueAgentMenu}
+ issueWorktreeMenu={issueWorktreeMenu}
/>
)}
<UpdateCard />
@@ -16460,6 +16818,30 @@ export function Canvas() {
/>
)}
+ {issueWorktreeAsk && (
+ // "Start with agent in a new worktree" found the issue's worktree (or its branch) already
+ // there. Asked, never decided for the person: reuse is the likely answer, but a second,
+ // independent checkout is a legitimate one too. Nothing on disk is overwritten either way.
+ <ConfirmDialog
+ message={issueWorktreeAsk.message}
+ choice={{
+ label: 'Start the agent in',
+ options: issueWorktreeAsk.options,
+ value: issueWorktreeAsk.value,
+ onChange: (value) =>
+ setIssueWorktreeAsk((ask) => (ask ? { ...ask, value: value as IssueWorktreeChoice } : ask))
+ }}
+ confirmLabel="Start agent"
+ danger={false}
+ onConfirm={() => {
+ const ask = issueWorktreeAsk
+ setIssueWorktreeAsk(null)
+ ask.run(ask.value)
+ }}
+ onCancel={() => setIssueWorktreeAsk(null)}
+ />
+ )}
+
{worktreeDialog && (
<WorktreeDialog
// Opened from a group's "Bind to worktree…" (groupId set) vs. the pane/palette's
diff --git a/src/renderer/canvas/issue-binding.source.test.ts b/src/renderer/canvas/issue-binding.source.test.ts
index 06ac03d11..a85af766e 100644
--- a/src/renderer/canvas/issue-binding.source.test.ts
+++ b/src/renderer/canvas/issue-binding.source.test.ts
@@ -114,19 +114,49 @@ describe('run history in the node-removal funnels', () => {
})
describe('Start with agent (issue card)', () => {
+ it('both issue starts compose the prompt from the reference alone — never the issue title or body', () => {
+ // ONE composer for both "Start with agent" and "Start with agent in a new worktree".
+ const prompt = code(between('const issueStartPrompt = useCallback(', 'const startIssueAgent = useCallback('))
+ expect(prompt).toContain('issueRefFromHtmlUrl(issue.htmlUrl, issue.number)')
+ expect(prompt).toContain('issueLaunchPrompt(ref)')
+ expect(prompt).not.toMatch(/issue\.title|issue\.body/)
+ expect(code(src).match(/issueLaunchPrompt\(ref\)/g) ?? []).toHaveLength(1)
+ })
+
it('launches with the reference prompt and binds the node — never the issue title or body', () => {
const body = code(between('const startIssueAgent = useCallback(', 'const issueAgentMenu = useCallback('))
- expect(body).toContain('issueRefFromHtmlUrl(issue.htmlUrl, issue.number)')
- expect(body).toContain('issueLaunchPrompt(ref)')
- expect(body).toContain('{ issueRef: ref }')
+ expect(body).toContain('issueStartPrompt(issue)')
+ expect(body).toContain('start.prompt, {\n issueRef: start.ref\n }')
+ expect(body).toContain('fileIssueSession(issue, start.ref, created, agentId)')
// The attacker-writable fields of the issue never reach this function's launch.
expect(body).not.toMatch(/issue\.title|issue\.body/)
})
+ it('in a new worktree: the title reaches ONLY the branch planner, never a prompt or a launch line', () => {
+ const open = code(between('const openIssueAgentInFrame = useCallback(', 'const startIssueAgentInWorktree = useCallback('))
+ expect(open).toContain('start.prompt,')
+ expect(open).toContain('{ issueRef: start.ref, awaitSetupGroup: setupHoldGroup(groupId) }')
+ expect(open).not.toMatch(/issue\.title|issue\.body/)
+ const body = code(between('const startIssueAgentInWorktree = useCallback(', 'const issueWorktreeMenu = useCallback('))
+ expect(body).toContain('issueStartPrompt(issue)')
+ // Exactly one read of the title: the slug input of `planIssueWorktree` (@shared/issue-worktree
+ // owns every rule about it — allowlist, cap, check-ref-format; proven there against git).
+ expect(body.match(/issue\.title/g) ?? []).toHaveLength(1)
+ expect(body).toMatch(/planIssueWorktree\(\s*\{ number: start\.ref\.number, title: issue\.title,/)
+ expect(body).not.toMatch(/issue\.body/)
+ // The frame is named after the NUMBER, not the title.
+ expect(body).toContain('title: `Issue #${start.ref.number}`')
+ })
+
it('the menu reuses the canvas agent + account picker instead of a fourth copy', () => {
- const body = code(between('const issueAgentMenu = useCallback(', '// Global kanban swimlane'))
+ const body = code(between('const issueAgentMenu = useCallback(', '// ---- GitHub issue → agent session in its OWN worktree'))
expect(body).toContain('agentCreationEntries(undefined, undefined, {')
expect(body).toContain('startIssueAgent(issue, aid, acct)')
+ const wt = code(between('const issueWorktreeMenu = useCallback(', '// Global kanban swimlane'))
+ expect(wt).toContain('agentCreationEntries(undefined, undefined, {')
+ expect(wt).toContain('startIssueAgentInWorktree(issue, aid, acct)')
+ // Refused projects answer with the reason (rendered DISABLED), never an empty or missing row.
+ expect(wt).toContain('if (refusal) return { refusal }')
})
})
diff --git a/src/renderer/canvas/issue-worktree.source.test.ts b/src/renderer/canvas/issue-worktree.source.test.ts
new file mode 100644
index 000000000..8ba48c856
--- /dev/null
+++ b/src/renderer/canvas/issue-worktree.source.test.ts
@@ -0,0 +1,152 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+
+/**
+ * STRUCTURAL pins for the worktree create-and-bind wiring inside Canvas.tsx: the one create site
+ * shared by the New worktree dialog, the `open-worktree` control verb and the issue card's "Start
+ * with agent in a new worktree", and the two same-tick guarantees the issue action rests on. They
+ * live inside a 16,000-line component with no unit seam, so — like `issue-binding.source.test.ts` —
+ * the BEHAVIOUR is proven elsewhere against real code: the create/bind sequence in
+ * `lib/worktreeCreate.test.ts`, the branch and reuse rules in `shared/issue-worktree.test.ts`
+ * (including the real `git check-ref-format`), the refusals in `lib/issueWorktree.test.ts`.
+ */
+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+
+function code(body: string): string {
+ return body
+ .split('\n')
+ .filter((l) => !l.trim().startsWith('//'))
+ .join('\n')
+}
+
+function between(start: string, end: string): string {
+ const a = src.indexOf(start)
+ expect(a, start).toBeGreaterThan(-1)
+ const b = src.indexOf(end, a + start.length)
+ expect(b, end).toBeGreaterThan(a)
+ return code(src.slice(a, b))
+}
+
+describe('one create-and-bind for every way the app makes a worktree', () => {
+ it('git worktree add is reached from exactly one place: the shared deps builder', () => {
+ const body = code(src)
+ expect(body.match(/\.worktreeAdd\(/g) ?? []).toHaveLength(1)
+ const deps = between('const worktreeCreateDeps = useCallback(', 'const createWorktreeAndGroup = useCallback(')
+ expect(deps).toContain('api.git.worktreeAdd(repoPath, wtPath, branch, baseRef, isNew)')
+ })
+
+ it('the dialog creates through it WITH the project-changed refusal', () => {
+ const body = between('const createWorktreeAndGroup = useCallback(', 'const bindExistingWorktree = useCallback(')
+ expect(body).toContain('createBoundWorktree(worktreeCreateDeps(), v, {')
+ expect(body).toContain('projectId: target.projectId')
+ // A rejected call keeps its historical inline wording.
+ expect(body).toContain('`Could not create the worktree: ${res.message}`')
+ })
+
+ it('open-worktree creates through it WITHOUT one, and replies as it always did', () => {
+ const body = between("case 'open-worktree': {", "case 'close-worktree': {")
+ const call = body.slice(body.indexOf('createBoundWorktree('), body.indexOf('if (!created.ok)'))
+ expect(call).toContain('worktreeControlRef.current.worktreeCreateDeps()')
+ expect(call).not.toContain('projectId')
+ expect(body).toContain("`open-worktree: ${created.reason === 'git' ? created.message")
+ // The frame's place is asked only after git succeeded (a thunk), against the canvas as it is then.
+ expect(call).toContain('target: () => ({')
+ })
+})
+
+describe('attachWorktree', () => {
+ const body = between('const attachWorktree = useCallback(', 'const worktreeCreateDeps = useCallback(')
+
+ it('puts the frame in nodesRef in the same tick, for a caller that opens a node into it at once', () => {
+ const created = body.indexOf('nodesRef.current = [group, ...nodesRef.current]')
+ expect(created).toBeGreaterThan(-1)
+ expect(created).toBeLessThan(body.indexOf('setNodes((ns) => [group, ...(ns as CanvasNode[])])'))
+ const bound = body.indexOf('nodesRef.current = bind(nodesRef.current)')
+ expect(bound).toBeGreaterThan(-1)
+ expect(bound).toBeLessThan(body.indexOf('setNodes((ns) => bind(ns as CanvasNode[]))'))
+ })
+
+ it('names a new frame from the target when asked (an issue frame is "Issue #N"), else the branch', () => {
+ expect(body).toContain('title: target.title ?? wt.branch')
+ expect(body).toContain('target.size ?? WORKTREE_GROUP_SIZE')
+ })
+
+ it('closes the setup gate from the bind, and releases its own count only after the run was asked for', () => {
+ const mark = body.indexOf('useProjectSetup.getState().markGroupPending(setupGroupId)')
+ const task = body.indexOf('void (async () => {')
+ expect(mark).toBeGreaterThan(-1)
+ expect(mark).toBeLessThan(task)
+ const start = body.indexOf('startWorktreeSetup(setupGroupId, wt.path)')
+ const fin = body.indexOf('} finally {', start)
+ expect(start).toBeGreaterThan(task)
+ expect(fin).toBeGreaterThan(start)
+ expect(body.indexOf('useProjectSetup.getState().clearGroupPending(setupGroupId)', fin)).toBeGreaterThan(fin)
+ })
+})
+
+describe('Start with agent in a new worktree', () => {
+ const body = between('const startIssueAgentInWorktree = useCallback(', 'const issueWorktreeMenu = useCallback(')
+
+ it('opens the agent INSIDE the attach, so no render can drop the fresh frame from nodesRef first', () => {
+ expect(body).toMatch(
+ /worktreeCreateDeps\(\(t, wt\) => \{\s*const groupId = attachWorktree\(t, wt\)\s*opened = openIssueAgentInFrame\(groupId,/
+ )
+ // Adopting an unbound worktree does the same, with nothing awaited in between.
+ expect(body).toMatch(
+ /const groupId = attachWorktree\(newFrame\(\), wt\)\s*openIssueAgentInFrame\(groupId, issue, start, agentId, accountId\)/
+ )
+ })
+
+ it('refuses before anything else when the project cannot take a worktree, and never doubles a start', () => {
+ const refusal = body.indexOf('const refusal = issueWorktreeUnavailable()')
+ expect(refusal).toBeGreaterThan(-1)
+ expect(refusal).toBeLessThan(body.indexOf('await '))
+ expect(body).toContain('issueWorktreeInFlightRef.current.has(key)')
+ expect(body).toContain('issueWorktreeInFlightRef.current.delete(key)')
+ })
+
+ it('re-checks the project after every await and again at the dialog click', () => {
+ const checks = body.match(/useProjects\.getState\(\)\.activeProjectId !== projectId/g) ?? []
+ expect(checks.length).toBeGreaterThanOrEqual(2)
+ // …and the create itself passes the project, so git finishing after a tab switch binds nothing.
+ expect(body).toContain('{ target: newFrame, projectId }')
+ })
+
+ it('uses the dialog\'s defaults: project override, else the repo default branch and the template', () => {
+ expect(body).toContain('effectiveWorktreeBaseRef(defaults, entries)')
+ expect(body).toContain('useSettings.getState().settings.worktreePathTemplate')
+ })
+
+ it('a reused frame is re-validated at the click (still there, still bound, not stale)', () => {
+ expect(body).toContain('useWorktrees.getState().staleGroupIds.includes(existing.groupId)')
+ expect(body).toContain('live.data.worktree?.path !== existing.path')
+ })
+})
+
+describe('addAgentNode parents OUTSIDE the setNodes updater', () => {
+ it('so a render flushed by a zustand write cannot parent the agent against a ref without its frame', () => {
+ // The updater runs at render time. A SyncLane render (any zustand write) that skips this
+ // DefaultLane update first mirrors `nodesRef` back to state, which does not yet hold a frame
+ // `attachWorktree` created this tick — `parentInto` would then find no group and leave the
+ // agent top-level, outside the worktree frame it was opened for.
+ const add = between('const addAgentNode = useCallback(', 'return { node, projectId: targetProjectId }')
+ const placed = add.indexOf('const placed = groupId ? parentInto(node, groupId) : node')
+ expect(placed).toBeGreaterThan(-1)
+ expect(placed).toBeLessThan(add.indexOf('setNodes((ns) => [...ns, placed])'))
+ expect(add).not.toMatch(/setNodes\(\(ns\) => \[[^\]]*parentInto\(/)
+ })
+})
+
+describe('the setup hold is one rule', () => {
+ it('control opens and the issue action ask the same helper', () => {
+ const arm = between('const armAfter = (', 'const addGrouped = (')
+ expect(arm).toContain('const awaitSetupGroup = setupHoldGroup(intoGroup)')
+ const open = between('const openIssueAgentInFrame = useCallback(', 'const startIssueAgentInWorktree = useCallback(')
+ expect(open).toContain('awaitSetupGroup: setupHoldGroup(groupId)')
+ const add = between('const addAgentNode = useCallback(', 'const issueRef = normalizeIssueRef(extra?.issueRef)')
+ expect(add).toContain('awaitSetupGroup?: string')
+ expect(code(src)).toContain(
+ 'const node = extra?.awaitSetupGroup ? queueControlLaunch(bound, [], extra.awaitSetupGroup) : bound'
+ )
+ })
+})
diff --git a/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsx b/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsx
index 0b01fb2fa..019064099 100644
--- a/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsx
+++ b/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsx
@@ -73,15 +73,57 @@ describe('GitHubIssueSummaryModal', () => {
vi.unstubAllGlobals()
})
+ it('offers "Start in a new worktree" beside it, with the same picker rows', () => {
+ vi.stubGlobal('ResizeObserver', class { observe(): void {} unobserve(): void {} disconnect(): void {} })
+ const host = document.createElement('div')
+ document.body.append(host)
+ const root = createRoot(host)
+ const pick = vi.fn()
+ act(() => root.render(
+ <GitHubIssueSummaryModal issue={issue} columns={[]} moving={false} readOnly={false}
+ onMove={vi.fn()} onClose={vi.fn()} startMenu={() => []}
+ worktreeMenu={() => ({ items: [{ label: 'Codex', onClick: pick }] })} />
+ ))
+ const button = [...host.querySelectorAll('button')].find((b) => b.textContent?.startsWith('Start in a new worktree'))!
+ expect(button.disabled).toBe(false)
+ act(() => button.dispatchEvent(new MouseEvent('click', { bubbles: true })))
+ const row = [...document.body.querySelectorAll<HTMLElement>('.ctx-item')].find((el) => el.textContent?.includes('Codex'))!
+ act(() => row.dispatchEvent(new MouseEvent('click', { bubbles: true })))
+ expect(pick).toHaveBeenCalled()
+ act(() => root.unmount())
+ host.remove()
+ vi.unstubAllGlobals()
+ })
+
+ it('a project that cannot take a worktree gets the button DISABLED with its reason', () => {
+ const host = document.createElement('div')
+ document.body.append(host)
+ const root = createRoot(host)
+ act(() => root.render(
+ <GitHubIssueSummaryModal issue={issue} columns={[]} moving={false} readOnly={false}
+ onMove={vi.fn()} onClose={vi.fn()}
+ worktreeMenu={() => ({ refusal: 'Not supported in SSH projects yet' })} />
+ ))
+ const button = [...host.querySelectorAll('button')].find((b) => b.textContent?.startsWith('Start in a new worktree'))!
+ expect(button.disabled).toBe(true)
+ expect(button.title).toBe('Not supported in SSH projects yet')
+ act(() => button.dispatchEvent(new MouseEvent('click', { bubbles: true })))
+ expect(document.body.querySelector('.ctx-menu')).toBeNull()
+ act(() => root.unmount())
+ host.remove()
+ })
+
it('a pull request offers no "Start with agent" and no run history', () => {
const host = document.createElement('div')
document.body.append(host)
const root = createRoot(host)
act(() => root.render(
<GitHubIssueSummaryModal issue={issue} kind="pull" columns={[]} moving={false} readOnly={false}
- onMove={vi.fn()} onClose={vi.fn()} showRunHistory startMenu={() => []} />
+ onMove={vi.fn()} onClose={vi.fn()} showRunHistory startMenu={() => []}
+ worktreeMenu={() => ({ items: [] })} />
))
expect(host.textContent).not.toContain('Start with agent')
+ expect(host.textContent).not.toContain('new worktree')
expect(host.textContent).not.toContain('Agent runs')
act(() => root.unmount())
host.remove()
diff --git a/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx b/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx
index fccf8bbbb..3e20e6a4a 100644
--- a/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx
+++ b/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx
@@ -15,6 +15,7 @@ import { ContextMenu, type MenuItem } from '../ContextMenu'
import { NO_ISSUE_RUNS, type IssueRun } from '../../lib/issueRuns'
import { IssueRunChips } from './IssueRunChips'
import { BoardLogPanel } from './BoardLogPanel'
+import { ISSUE_WORKTREE_BUTTON_LABEL, type IssueWorktreeMenuAnswer } from '../../lib/issueWorktree'
export function GitHubIssueSummaryModal({
issue,
@@ -31,6 +32,7 @@ export function GitHubIssueSummaryModal({
pullFreshness = 'fresh',
pullObservedAt,
startMenu,
+ worktreeMenu,
runs = NO_ISSUE_RUNS,
onOpenRun,
showRunHistory = false
@@ -56,6 +58,9 @@ export function GitHubIssueSummaryModal({
/** The "Start with agent ▸" rows (the canvas's own agent + account picker, pointed at this
* issue). Absent = no button — a pull request, or a board with no canvas behind it. */
startMenu?: () => MenuItem[]
+ /** "Start with agent in a new worktree": the same picker pointed at a fresh worktree frame, or
+ * the reason it cannot run here (the button is then DISABLED and says why). Absent = no button. */
+ worktreeMenu?: () => IssueWorktreeMenuAnswer
/** Sessions already working on this issue — the same live chips the card shows. */
runs?: readonly IssueRun[]
onOpenRun?: (nodeId: string) => void
@@ -65,6 +70,13 @@ export function GitHubIssueSummaryModal({
const isPull = kind === 'pull'
const { api } = useSession()
const [startAt, setStartAt] = useState<{ x: number; y: number } | null>(null)
+ // The worktree picker's rows are built at the click that opens them, like the canvas menus: they
+ // describe the canvas as it is then.
+ const [worktreeAt, setWorktreeAt] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)
+ // Read at render: whether the project can take a worktree does not change while the modal is up
+ // without a re-render (a project switch unmounts the board).
+ const worktreeAnswer = !isPull && worktreeMenu ? worktreeMenu() : undefined
+ const worktreeRefusal = worktreeAnswer && 'refusal' in worktreeAnswer ? worktreeAnswer.refusal : undefined
// The run history is filed under the issue card's synthetic board-log id. No id (a card whose
// URL did not parse) = no history panel, rather than a panel keyed on something made up.
const logId = !isPull && showRunHistory
@@ -147,6 +159,21 @@ export function GitHubIssueSummaryModal({
Start with agent ▾
</Button>
)}
+ {worktreeAnswer && (
+ <Button
+ aria-haspopup="menu"
+ disabled={!!worktreeRefusal}
+ title={worktreeRefusal}
+ onClick={(event) => {
+ const answer = worktreeMenu?.()
+ if (!answer || 'refusal' in answer) return
+ const r = (event.currentTarget as HTMLElement).getBoundingClientRect()
+ setWorktreeAt({ x: r.left, y: r.bottom + 4, items: answer.items })
+ }}
+ >
+ {ISSUE_WORKTREE_BUTTON_LABEL} ▾
+ </Button>
+ )}
<Button onClick={() => void api.shell.openExternal(issue.htmlUrl)}>Open on GitHub</Button>
</div>
{!isPull && onOpenRun && runs.length > 0 && (
@@ -200,6 +227,15 @@ export function GitHubIssueSummaryModal({
onClose={() => setStartAt(null)}
/>
)}
+ {worktreeAt && (
+ <ContextMenu
+ x={worktreeAt.x}
+ y={worktreeAt.y}
+ zIndex={60}
+ items={worktreeAt.items}
+ onClose={() => setWorktreeAt(null)}
+ />
+ )}
</section>
</div>
)
diff --git a/src/renderer/components/kanban/KanbanView.issueBinding.test.tsx b/src/renderer/components/kanban/KanbanView.issueBinding.test.tsx
index e362a5b3c..122aa79e8 100644
--- a/src/renderer/components/kanban/KanbanView.issueBinding.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.issueBinding.test.tsx
@@ -87,6 +87,7 @@ async function render(opts: {
sessions?: KanbanSession[]
onChange?: (b: ProjectKanban) => void
issueAgentMenu?: (issue: GitHubIssueCardView) => MenuItem[]
+ issueWorktreeMenu?: (issue: GitHubIssueCardView) => { items: MenuItem[] } | { refusal: string }
}): Promise<void> {
host = document.createElement('div')
document.body.appendChild(host)
@@ -107,6 +108,7 @@ async function render(opts: {
onBrowserNav={noop}
onSetIcon={noop}
issueAgentMenu={opts.issueAgentMenu}
+ issueWorktreeMenu={opts.issueWorktreeMenu}
/>
)
})
@@ -157,6 +159,46 @@ describe('KanbanView — GitHub issue ↔ session binding', () => {
expect(menu).toHaveBeenCalledWith(expect.objectContaining({ number: 42 }))
})
+ it('the issue card menu offers "Start with agent in a new worktree ▸" with the same picker', async () => {
+ const pick = vi.fn()
+ const menu = vi.fn((issue: GitHubIssueCardView) => ({
+ items: [{ label: 'Claude', onClick: () => pick(issue.number) }] as MenuItem[]
+ }))
+ await render({ issueAgentMenu: () => [], issueWorktreeMenu: menu })
+ act(() => {
+ issueCard().dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 5, clientY: 5 }))
+ })
+ expect(menu).toHaveBeenCalledWith(expect.objectContaining({ number: 42 }))
+ const row = [...document.body.querySelectorAll<HTMLElement>('.ctx-item--submenu')].find((el) =>
+ el.textContent?.includes('Start with agent in a new worktree')
+ )
+ expect(row).toBeDefined()
+ act(() => {
+ row!.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }))
+ })
+ const claude = [...document.body.querySelectorAll<HTMLElement>('.ctx-item')].filter((el) =>
+ el.textContent === 'Claude'
+ )
+ act(() => claude[claude.length - 1].dispatchEvent(new MouseEvent('click', { bubbles: true })))
+ expect(pick).toHaveBeenCalledWith(42)
+ })
+
+ it('a project that cannot take a worktree shows the row DISABLED with its reason, never hides it', async () => {
+ await render({
+ issueAgentMenu: () => [],
+ issueWorktreeMenu: () => ({ refusal: 'Not supported in SSH projects yet' })
+ })
+ act(() => {
+ issueCard().dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 5, clientY: 5 }))
+ })
+ const row = [...document.body.querySelectorAll<HTMLElement>('.ctx-item')].find((el) =>
+ el.textContent?.includes('Start with agent in a new worktree')
+ )
+ expect(row).toBeDefined()
+ expect(row!.getAttribute('title')).toBe('Not supported in SSH projects yet')
+ expect((row as HTMLButtonElement).disabled).toBe(true)
+ })
+
it("a session card's #N opens that issue's summary on the board", async () => {
await render({})
const chip = document.querySelector<HTMLElement>('.kanban-card--session .issue-ref-chip')!
diff --git a/src/renderer/components/kanban/KanbanView.tsx b/src/renderer/components/kanban/KanbanView.tsx
index fcb7ac9d4..d37c6c991 100644
--- a/src/renderer/components/kanban/KanbanView.tsx
+++ b/src/renderer/components/kanban/KanbanView.tsx
@@ -34,7 +34,8 @@ import { GitHubPullCard } from './GitHubPullCard'
import { kanbanSource, sourceVisible } from '../../lib/kanbanSources'
import type { ModalSpawn } from './ModalTerminal'
import { ContextMenu, type MenuItem } from '../ContextMenu'
-import { IconAgent, IconExternal, IconNote, IconSwitch, IconTerminal, IconTrash, IconWeb } from '../icons'
+import { IconAgent, IconBranch, IconExternal, IconNote, IconSwitch, IconTerminal, IconTrash, IconWeb } from '../icons'
+import { issueWorktreeMenuRow, type IssueWorktreeMenuAnswer } from '../../lib/issueWorktree'
import type { GitHubCloseReason, GitHubIssueCardView } from '@shared/github-issues'
import { issueKey, issueRefFromHtmlUrl, issueUrl, type IssueRef } from '@shared/github-issue-ref'
import { NO_ISSUE_RUNS, boundRunsByIssue, type IssueRun } from '../../lib/issueRuns'
@@ -142,6 +143,13 @@ export interface KanbanViewProps {
* same reason as `accountMenuItems`: a board with no canvas behind it offers none.
*/
issueAgentMenu?: (issue: GitHubIssueCardView) => MenuItem[]
+ /**
+ * "Start with agent in a new worktree ▸" for a GitHub issue card: the same picker, pointed at a
+ * fresh `issue-<N>-<slug>` worktree frame — or the reason it cannot run on this project (an SSH
+ * project, a shared tab, a project with no folder or no repository), which the card menu and the
+ * summary modal show DISABLED rather than hide. Optional like `issueAgentMenu`.
+ */
+ issueWorktreeMenu?: (issue: GitHubIssueCardView) => IssueWorktreeMenuAnswer
}
type Drag =
@@ -211,7 +219,8 @@ function useCanvasCovered(): void {
export const KanbanView = memo(function KanbanView({
board, sessions, onChange, onOpenNode, onCreateNode, onRenameNode, onEditSticky, onDeleteNode,
- onModalNodeChange, onBrowserNav, onSetIcon, accountMenuItems, onAutoMoveFromPulls, issueAgentMenu
+ onModalNodeChange, onBrowserNav, onSetIcon, accountMenuItems, onAutoMoveFromPulls, issueAgentMenu,
+ issueWorktreeMenu
}: KanbanViewProps) {
useCanvasCovered()
const { api } = useSession()
@@ -1177,6 +1186,7 @@ export const KanbanView = memo(function KanbanView({
children: issueAgentMenu(issueMenu.issue)
}] as MenuItem[])
: []),
+ ...(issueWorktreeMenu ? [issueWorktreeMenuRow(issueWorktreeMenu(issueMenu.issue), <IconBranch />)] : []),
{
label: 'Open summary',
icon: <IconExternal />,
@@ -1232,6 +1242,9 @@ export const KanbanView = memo(function KanbanView({
startMenu={modalIssue.kind === 'issue' && issueAgentMenu
? () => issueAgentMenu(modalIssue.item)
: undefined}
+ worktreeMenu={modalIssue.kind === 'issue' && issueWorktreeMenu
+ ? () => issueWorktreeMenu(modalIssue.item)
+ : undefined}
runs={modalIssue.kind === 'issue' ? runsFor(modalIssue.item) : NO_ISSUE_RUNS}
onOpenRun={(nodeId) => {
setModalIssue(null)
diff --git a/src/renderer/components/kanban/board-writers.guard.test.ts b/src/renderer/components/kanban/board-writers.guard.test.ts
index 0b37a0b0e..8a577509a 100644
--- a/src/renderer/components/kanban/board-writers.guard.test.ts
+++ b/src/renderer/components/kanban/board-writers.guard.test.ts
@@ -23,7 +23,8 @@ const BOARD_WRITERS: Record<string, string[]> = {
'canvas/Canvas.tsx': [
'onKanbanChange — the per-project board committing a person\'s drag/edit',
'createNodeInColumn — a person\'s "+ New" in a column',
- 'startIssueAgent — a person\'s "Start with agent" filing the new session under the issue card\'s column',
+ 'fileIssueSession — a person\'s "Start with agent" or "Start with agent in a new worktree" filing ' +
+ 'the new session under the issue card\'s column',
'the `assign` control verb — a session moving its OWN card (the issue-bound contract)',
'autoMoveCardFromPulls — the merge-driven move: a person switched it on for this machine in ' +
'Settings, and it fires only on a pull request MERGE this machine observed after that (never on ' +
diff --git a/src/renderer/lib/issueWorktree.test.ts b/src/renderer/lib/issueWorktree.test.ts
new file mode 100644
index 000000000..080cd7bd9
--- /dev/null
+++ b/src/renderer/lib/issueWorktree.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, it } from 'vitest'
+import {
+ ISSUE_WORKTREE_LABEL,
+ ISSUE_WORKTREE_NO_REPO_HINT,
+ ISSUE_WORKTREE_RELAY_HINT,
+ issueWorktreeChoiceCopy,
+ issueWorktreeMenuRow,
+ issueWorktreeRefusal,
+ issueWorktreeRenamedNotice
+} from './issueWorktree'
+import { WORKTREE_NO_CWD_HINT, WORKTREE_SSH_HINT } from './addMenuSpec'
+import type { MenuItem } from '../components/ContextMenu'
+
+const OK = { relay: false, ssh: false, cwd: '/work/repo', repoRoot: '/work/repo' }
+
+describe('issueWorktreeRefusal', () => {
+ it('lets a local project with a repository through', () => {
+ expect(issueWorktreeRefusal(OK)).toBeNull()
+ })
+
+ it('refuses the surfaces worktrees do not reach in v1, each with its own reason', () => {
+ expect(issueWorktreeRefusal({ ...OK, relay: true })).toBe(ISSUE_WORKTREE_RELAY_HINT)
+ expect(issueWorktreeRefusal({ ...OK, ssh: true })).toBe(WORKTREE_SSH_HINT)
+ expect(issueWorktreeRefusal({ ...OK, cwd: undefined })).toBe(WORKTREE_NO_CWD_HINT)
+ expect(issueWorktreeRefusal({ ...OK, cwd: ' ' })).toBe(WORKTREE_NO_CWD_HINT)
+ expect(issueWorktreeRefusal({ ...OK, repoRoot: null })).toBe(ISSUE_WORKTREE_NO_REPO_HINT)
+ })
+
+ it('names the tab kind before anything about its project (a shared tab is refused as such)', () => {
+ expect(issueWorktreeRefusal({ relay: true, ssh: true, cwd: undefined, repoRoot: null })).toBe(
+ ISSUE_WORKTREE_RELAY_HINT
+ )
+ // An SSH project has no LOCAL folder or repository to speak of — say SSH, not "no folder".
+ expect(issueWorktreeRefusal({ relay: false, ssh: true, cwd: undefined, repoRoot: null })).toBe(
+ WORKTREE_SSH_HINT
+ )
+ })
+})
+
+describe('issueWorktreeMenuRow', () => {
+ it('is a submenu of the agent rows when the action can run', () => {
+ const items: MenuItem[] = [{ label: 'Claude', onClick: () => {} }]
+ expect(issueWorktreeMenuRow({ items })).toEqual({
+ type: 'submenu',
+ label: ISSUE_WORKTREE_LABEL,
+ icon: undefined,
+ children: items
+ })
+ })
+
+ it('is the same label DISABLED with the reason when it cannot — never a missing row', () => {
+ const row = issueWorktreeMenuRow({ refusal: WORKTREE_SSH_HINT })
+ expect(row).toMatchObject({ label: ISSUE_WORKTREE_LABEL, disabled: true, hint: WORKTREE_SSH_HINT })
+ })
+})
+
+describe('issueWorktreeChoiceCopy', () => {
+ const alt = { branch: 'issue-12-fix-2', path: '/w/issue-12-fix-2' }
+
+ it('offers reuse (preselected) and a DIFFERENT new branch, and promises nothing is overwritten', () => {
+ const copy = issueWorktreeChoiceCopy(
+ 12,
+ { kind: 'bound', groupId: 'g', branch: 'issue-12-fix', path: '/w/issue-12-fix' },
+ alt,
+ 'main'
+ )
+ expect(copy.value).toBe('reuse')
+ expect(copy.options.map((o) => o.value)).toEqual(['reuse', 'new'])
+ expect(copy.message).toContain('issue-12-fix')
+ expect(copy.message).toContain('Nothing will be overwritten')
+ expect(copy.options[1].label).toContain('issue-12-fix-2 off main')
+ })
+
+ it('says an adopted worktree is not the app\'s to delete', () => {
+ const copy = issueWorktreeChoiceCopy(
+ 12,
+ {
+ kind: 'orphan',
+ branch: 'issue-12-fix',
+ path: '/w/issue-12-fix',
+ entry: { path: '/w/issue-12-fix', branch: 'issue-12-fix', head: 'a', isBare: false }
+ },
+ alt,
+ 'main'
+ )
+ expect(copy.options[0].label).toContain('Remove will not delete')
+ })
+
+ it('offers to check out an existing branch, and only reuse when no free name is left', () => {
+ const copy = issueWorktreeChoiceCopy(
+ 12,
+ { kind: 'branch', branch: 'issue-12-fix', path: '/w/issue-12-fix' },
+ null,
+ 'main'
+ )
+ expect(copy.options).toHaveLength(1)
+ expect(copy.options[0].label).toBe('Check out issue-12-fix in a new worktree at /w/issue-12-fix')
+ expect(copy.message).toContain('only reuse is offered')
+ })
+})
+
+describe('issueWorktreeRenamedNotice', () => {
+ it('says why the new worktree has a suffix', () => {
+ expect(issueWorktreeRenamedNotice('issue-12-fix', 'issue-12-fix-2')).toBe(
+ 'issue-12-fix was already taken (a branch or folder of that name exists), so the new worktree is issue-12-fix-2.'
+ )
+ })
+})
diff --git a/src/renderer/lib/issueWorktree.ts b/src/renderer/lib/issueWorktree.ts
new file mode 100644
index 000000000..b7ca04dc8
--- /dev/null
+++ b/src/renderer/lib/issueWorktree.ts
@@ -0,0 +1,101 @@
+import type { ReactNode } from 'react'
+import type { IssueWorktreeExisting, IssueWorktreeTarget } from '@shared/issue-worktree'
+import type { MenuItem } from '../components/ContextMenu'
+import { WORKTREE_NO_CWD_HINT, WORKTREE_SSH_HINT } from './addMenuSpec'
+
+// The renderer half of "Start with agent in a new worktree" on a GitHub issue card: when the
+// action is unavailable (and why), and what the reuse-or-new choice says. The branch/plan rules
+// themselves live in `@shared/issue-worktree`.
+
+/** The label every surface uses, so the card menu and the summary modal cannot drift apart. */
+export const ISSUE_WORKTREE_LABEL = 'Start with agent in a new worktree'
+/** The summary modal's button, beside its "Start with agent ▾" — the shorter form of the same
+ * action (the modal's action row has room for one long label, not two). */
+export const ISSUE_WORKTREE_BUTTON_LABEL = 'Start in a new worktree'
+
+/** Worktrees are made on THIS machine's filesystem; a relay tab's canvas belongs to another one. */
+export const ISSUE_WORKTREE_RELAY_HINT = 'Not available in a shared tab — worktrees are local to this machine in this version'
+
+export const ISSUE_WORKTREE_NO_REPO_HINT = 'No git repository was found in this project’s folder'
+
+/**
+ * Why the action cannot run on this project, or `null` when it can. The rows are shown DISABLED
+ * with this reason rather than hidden — the rule every worktree affordance follows: a row that
+ * silently vanishes takes its reason with it. Worktrees are local-only in v1, so a relay tab and
+ * an SSH project are refused before a cwd-less project or a folder that is not a repository.
+ */
+export function issueWorktreeRefusal(p: {
+ relay: boolean
+ ssh: boolean
+ cwd: string | undefined
+ repoRoot: string | null
+}): string | null {
+ if (p.relay) return ISSUE_WORKTREE_RELAY_HINT
+ if (p.ssh) return WORKTREE_SSH_HINT
+ if (!p.cwd?.trim()) return WORKTREE_NO_CWD_HINT
+ if (!p.repoRoot?.trim()) return ISSUE_WORKTREE_NO_REPO_HINT
+ return null
+}
+
+/** The two answers the reuse-or-new dialog can give. */
+export type IssueWorktreeChoice = 'reuse' | 'new'
+
+/**
+ * The dialog shown when the issue already has a worktree (or the branch it would create already
+ * exists): what is there, and the two ways forward. Nothing is ever overwritten, so "new" is always
+ * a DIFFERENT branch and folder. Reuse is preselected — the common reason to start a second agent
+ * on an issue is to continue in the checkout the first one used.
+ */
+export function issueWorktreeChoiceCopy(
+ issueNumber: number,
+ existing: IssueWorktreeExisting,
+ alternative: IssueWorktreeTarget | null,
+ baseRef: string
+): {
+ message: string
+ options: { value: IssueWorktreeChoice; label: string }[]
+ value: IssueWorktreeChoice
+} {
+ const what =
+ existing.kind === 'bound'
+ ? `Issue #${issueNumber} already has a worktree on this canvas: ⎇ ${existing.branch} (${existing.path}).`
+ : existing.kind === 'orphan'
+ ? `Issue #${issueNumber} already has a worktree that no group is bound to: ⎇ ${existing.branch} (${existing.path}).`
+ : `The branch ${existing.branch} already exists, but it is not checked out anywhere.`
+ const reuse =
+ existing.kind === 'bound'
+ ? 'Reuse it — open the agent in that group'
+ : existing.kind === 'orphan'
+ ? 'Reuse it — bind a new group to that worktree (Remove will not delete a worktree the app did not create)'
+ : `Check out ${existing.branch} in a new worktree at ${existing.path}`
+ const options: { value: IssueWorktreeChoice; label: string }[] = [{ value: 'reuse', label: reuse }]
+ if (alternative) {
+ options.push({
+ value: 'new',
+ label: `Create ⎇ ${alternative.branch} off ${baseRef} at ${alternative.path}`
+ })
+ }
+ const message = alternative
+ ? `${what} Nothing will be overwritten.`
+ : `${what} No free branch name was found for a new one, so only reuse is offered.`
+ return { message, options, value: 'reuse' }
+}
+
+/** The notice after a start that created a worktree under a different name than the usual one. */
+export function issueWorktreeRenamedNotice(wanted: string, created: string): string {
+ return `${wanted} was already taken (a branch or folder of that name exists), so the new worktree is ${created}.`
+}
+
+/** What the canvas answers for one issue card: the agent rows, or why there are none. */
+export type IssueWorktreeMenuAnswer = { items: MenuItem[] } | { refusal: string }
+
+/**
+ * The issue card's menu row: a submenu of agents, or the same label DISABLED with its reason (a
+ * submenu row cannot be disabled, and a row that vanishes takes its reason with it).
+ */
+export function issueWorktreeMenuRow(answer: IssueWorktreeMenuAnswer, icon?: ReactNode): MenuItem {
+ if ('refusal' in answer) {
+ return { label: ISSUE_WORKTREE_LABEL, icon, disabled: true, hint: answer.refusal, onClick: () => {} }
+ }
+ return { type: 'submenu', label: ISSUE_WORKTREE_LABEL, icon, children: answer.items }
+}
diff --git a/src/renderer/lib/worktreeCreate.test.ts b/src/renderer/lib/worktreeCreate.test.ts
new file mode 100644
index 000000000..b5986ad82
--- /dev/null
+++ b/src/renderer/lib/worktreeCreate.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it, vi } from 'vitest'
+import { createBoundWorktree, type CreateBoundWorktreeDeps, type WorktreeAttachTarget } from './worktreeCreate'
+import type { WorktreeCreateValue } from '@shared/worktree'
+
+const VALUE: WorktreeCreateValue = {
+ repoPath: '/work/repo',
+ mode: 'new',
+ branch: 'issue-12-fix',
+ baseRef: 'main',
+ path: '/work/repo.worktrees/issue-12-fix'
+}
+
+function deps(over: Partial<CreateBoundWorktreeDeps> = {}): CreateBoundWorktreeDeps & {
+ attach: ReturnType<typeof vi.fn>
+ worktreeAdd: ReturnType<typeof vi.fn>
+} {
+ return {
+ worktreeAdd: vi.fn(async () => ({ ok: true, message: 'Worktree ready.' })),
+ activeProjectId: () => 'p1',
+ attach: vi.fn(() => 'group-1'),
+ ...over
+ } as never
+}
+
+describe('createBoundWorktree', () => {
+ it('creates the worktree, then binds a frame to it with createdByApp', async () => {
+ const d = deps()
+ const target: WorktreeAttachTarget = { groupId: null, at: { x: 1, y: 2 }, title: 'Issue #12' }
+ const out = await createBoundWorktree(d, VALUE, { target: () => target, projectId: 'p1' })
+ expect(d.worktreeAdd).toHaveBeenCalledWith(VALUE.repoPath, VALUE.path, VALUE.branch, VALUE.baseRef, true)
+ expect(d.attach).toHaveBeenCalledWith(target, {
+ repoPath: VALUE.repoPath,
+ branch: VALUE.branch,
+ baseRef: 'main',
+ path: VALUE.path,
+ createdByApp: true
+ })
+ expect(out).toMatchObject({ ok: true, groupId: 'group-1' })
+ })
+
+ it('checks out an EXISTING branch when the mode says so (isNew false)', async () => {
+ const d = deps()
+ await createBoundWorktree(d, { ...VALUE, mode: 'existing' }, { target: () => ({ groupId: null }) })
+ expect(d.worktreeAdd.mock.calls[0][4]).toBe(false)
+ })
+
+ it('asks where the frame goes only AFTER git succeeded', async () => {
+ const order: string[] = []
+ const d = deps({
+ worktreeAdd: vi.fn(async () => {
+ order.push('git')
+ return { ok: true, message: '' }
+ })
+ })
+ await createBoundWorktree(d, VALUE, {
+ target: () => {
+ order.push('target')
+ return { groupId: null }
+ }
+ })
+ expect(order).toEqual(['git', 'target'])
+ })
+
+ it('reports a git failure with git\'s own message and binds nothing', async () => {
+ const d = deps({ worktreeAdd: vi.fn(async () => ({ ok: false, message: 'fatal: a branch named x exists' })) })
+ const target = vi.fn(() => ({ groupId: null }))
+ const out = await createBoundWorktree(d, VALUE, { target })
+ expect(out).toEqual({ ok: false, reason: 'git', message: 'fatal: a branch named x exists', rejected: false })
+ expect(d.attach).not.toHaveBeenCalled()
+ expect(target).not.toHaveBeenCalled()
+ })
+
+ it('turns a REJECTED call into a failure instead of throwing out of the caller', async () => {
+ const d = deps({ worktreeAdd: vi.fn(async () => Promise.reject(new Error('E_DISCONNECTED'))) })
+ const out = await createBoundWorktree(d, VALUE, { target: () => ({ groupId: null }) })
+ expect(out).toEqual({ ok: false, reason: 'git', message: 'E_DISCONNECTED', rejected: true })
+ expect(d.attach).not.toHaveBeenCalled()
+ })
+
+ it('leaves the worktree unbound when the canvas moved to another project during the await', async () => {
+ let active = 'p1'
+ const d = deps({
+ activeProjectId: () => active,
+ worktreeAdd: vi.fn(async () => {
+ active = 'p2'
+ return { ok: true, message: '' }
+ })
+ })
+ const out = await createBoundWorktree(d, VALUE, { target: () => ({ groupId: null }), projectId: 'p1' })
+ expect(out).toMatchObject({ ok: false, reason: 'project-changed', worktree: { branch: VALUE.branch } })
+ expect(d.attach).not.toHaveBeenCalled()
+ })
+
+ it('without a projectId (the control verb) it binds whatever is on screen, as it always did', async () => {
+ const d = deps({ activeProjectId: () => 'somewhere-else' })
+ const out = await createBoundWorktree(d, VALUE, { target: () => ({ groupId: 'g' }) })
+ expect(out.ok).toBe(true)
+ expect(d.attach).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/renderer/lib/worktreeCreate.ts b/src/renderer/lib/worktreeCreate.ts
new file mode 100644
index 000000000..1adea1017
--- /dev/null
+++ b/src/renderer/lib/worktreeCreate.ts
@@ -0,0 +1,76 @@
+import { worktreeFromCreate, type GroupWorktree, type WorktreeCreateValue } from '@shared/worktree'
+
+/**
+ * "Create a git worktree, then bind a group frame to it" — the ONE sequence behind every way the
+ * app makes a worktree: the New worktree dialog, the `open-worktree` control verb, and "Start with
+ * agent in a new worktree" on a GitHub issue card. Each used to carry its own copy of the create +
+ * catch + bind steps, and the issue action would have been the third.
+ *
+ * What each caller still owns, because it differs between them on purpose: how the branch, base and
+ * path were chosen, where the frame goes, and how a failure is worded (the dialog shows it inline,
+ * the verb replies `open-worktree: …`, the board raises a notice).
+ */
+
+/** Where the frame goes: an existing group to bind (`groupId`), or a new frame at `at`. */
+export interface WorktreeAttachTarget {
+ groupId: string | null
+ at?: { x: number; y: number }
+ /** A new frame's size (default: the worktree frame size). */
+ size?: { width: number; height: number }
+ /** A new frame's title (default: the branch). */
+ title?: string
+}
+
+export interface CreateBoundWorktreeDeps {
+ worktreeAdd(
+ repoPath: string,
+ wtPath: string,
+ branch: string,
+ baseRef: string,
+ isNew: boolean
+ ): Promise<{ ok: boolean; message: string }>
+ /** The project on screen NOW — asked after the git await, never before. */
+ activeProjectId(): string | null | undefined
+ /** Bind (or create and bind) the frame; returns the frame's id. */
+ attach(target: WorktreeAttachTarget, wt: GroupWorktree): string
+}
+
+export type CreateBoundWorktreeOutcome =
+ | { ok: true; groupId: string; worktree: GroupWorktree }
+ /** `git worktree add` failed (`rejected: false`, git's own message) or the call itself was
+ * rejected — a Server Edition socket that dropped mid-create (`rejected: true`, the raw error). */
+ | { ok: false; reason: 'git'; message: string; rejected: boolean }
+ /** The worktree was created, but the canvas moved to another project during the await: binding
+ * it to what is on screen would attach one repository's worktree to another project. It is left
+ * on disk as an orphan, and the New worktree dialog offers it again on its own project. */
+ | { ok: false; reason: 'project-changed'; worktree: GroupWorktree }
+
+/**
+ * Create the worktree, then bind it. `target` is asked only AFTER git succeeded, so a caller that
+ * places the frame relative to the live canvas places it against the canvas as it is then.
+ * `projectId` opts in to the "the canvas moved on" refusal (the dialog and the issue action pass
+ * it; the control verb does not, and keeps its historical behaviour).
+ */
+export async function createBoundWorktree(
+ deps: CreateBoundWorktreeDeps,
+ value: WorktreeCreateValue,
+ opts: { target: () => WorktreeAttachTarget; projectId?: string }
+): Promise<CreateBoundWorktreeOutcome> {
+ // A REJECTED ipc is not the same as a failed op, and both have to land here: without the catch
+ // the await throws straight out of the caller, and the dialog sat on "Creating…" with its own
+ // Cancel disabled — no error, no way out but Escape.
+ const res = await deps
+ .worktreeAdd(value.repoPath, value.path, value.branch, value.baseRef, value.mode === 'new')
+ .then(
+ (r) => ({ ...r, rejected: false }),
+ (e: unknown) => ({ ok: false, message: e instanceof Error ? e.message : String(e), rejected: true })
+ )
+ if (!res.ok) return { ok: false, reason: 'git', message: res.message, rejected: res.rejected }
+ // We created this directory, so `createdByApp` is true — Remove may delete it.
+ const worktree = worktreeFromCreate(value)
+ if (opts.projectId !== undefined && deps.activeProjectId() !== opts.projectId) {
+ return { ok: false, reason: 'project-changed', worktree }
+ }
+ const groupId = deps.attach(opts.target(), worktree)
+ return { ok: true, groupId, worktree }
+}
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index faa7a0879..debfd98c2 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -271,7 +271,7 @@ function placeNode(
* to sane canvas bounds — settings.json is hand-editable, and a 0×0 or NaN node would be
* unclickable/ungrabbable forever. Falls back to the historical 600×400.
*/
-function terminalNodeSize(): { width: number; height: number } {
+export function terminalNodeSize(): { width: number; height: number } {
const s = useSettings.getState().settings
const clamp = (v: unknown, lo: number, hi: number, dflt: number): number => {
const n = typeof v === 'number' && Number.isFinite(v) ? Math.round(v) : dflt
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 66ef67d5e..71f6503c5 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -10985,6 +10985,7 @@ button.pull-checks__name {
}
.github-issue-modal__actions {
display: flex;
+ flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: 12px;
diff --git a/src/shared/issue-worktree.test.ts b/src/shared/issue-worktree.test.ts
new file mode 100644
index 000000000..8ee0fbb7e
--- /dev/null
+++ b/src/shared/issue-worktree.test.ts
@@ -0,0 +1,315 @@
+import { execFileSync } from 'node:child_process'
+import { describe, expect, it } from 'vitest'
+import {
+ ISSUE_BRANCH_SLUG_MAX,
+ ISSUE_BRANCH_SUFFIX_MAX,
+ isIssueBranch,
+ issueBranchSlug,
+ issueWorktreeBranch,
+ planIssueWorktree,
+ type IssueWorktreeInput
+} from './issue-worktree'
+import { computeWorktreePath, DEFAULT_WORKTREE_PATH_TEMPLATE, isValidGitRef } from './worktree'
+
+// Issue titles are writable by anyone on a public repository. Every one of these must come out as
+// a branch in the `[a-z0-9-]` alphabet that git accepts, and never as anything else.
+const HOSTILE_TITLES: string[] = [
+ '../../etc/passwd',
+ '..',
+ '; rm -rf ~',
+ '`touch /tmp/pwned`',
+ '$(whoami) and ${HOME}',
+ "' OR 1=1 --",
+ '--upload-pack=touch /tmp/x',
+ '-b evil',
+ 'refs/heads/main',
+ 'HEAD@{1}',
+ 'feature.lock',
+ 'a..b~^:?*[\\',
+ ' ',
+ '',
+ '🔥🔥🔥',
+ '中文标题',
+ 'mаin', // Cyrillic а
+ 'main', // fullwidth
+ 'fix\u202Egnp.exe', // bidi override
+ 'zero\u200Bwidth\u200Djoin',
+ 'tab\tnew\nline\r\u0000nul\u001b[31mred',
+ 'İstanbul çalışıyor', // Turkish dotted capital I
+ 'x'.repeat(500),
+ 'word '.repeat(200),
+ '---',
+ '-- leading and trailing --',
+ '\\\\server\\share',
+ 'C:\\Windows\\System32'
+]
+
+const BRANCH_SHAPE = /^issue-[1-9][0-9]*(-[a-z0-9]+)*$/
+
+describe('issueBranchSlug', () => {
+ it('keeps readable ASCII words and drops everything else', () => {
+ expect(issueBranchSlug('Fix login crash on Safari')).toBe('fix-login-crash-on-safari')
+ expect(issueBranchSlug('Café: déjà vu (again!)')).toBe('cafe-deja-vu-again')
+ expect(issueBranchSlug('İstanbul çalışıyor')).toBe('istanbul-cal-s-yor')
+ expect(issueBranchSlug(' --Hello-- ')).toBe('hello')
+ })
+
+ it('is empty when nothing survives, so the branch falls back to issue-<N>', () => {
+ for (const t of ['', ' ', '🔥🔥🔥', '中文标题', '---', undefined, null, 42, { toString: () => 'x' }]) {
+ expect(issueBranchSlug(t)).toBe('')
+ expect(issueWorktreeBranch(7, t)).toBe('issue-7')
+ }
+ })
+
+ it('caps the slug, backing up to a word boundary when the cap lands mid-word', () => {
+ const long = 'fix login crash on safari when the user has two factor enabled'
+ const slug = issueBranchSlug(long)
+ expect(slug.length).toBeLessThanOrEqual(ISSUE_BRANCH_SLUG_MAX)
+ expect(slug).toBe('fix-login-crash-on-safari-when-the-user')
+ expect(issueBranchSlug('x'.repeat(500))).toBe('x'.repeat(ISSUE_BRANCH_SLUG_MAX))
+ expect(issueBranchSlug('word '.repeat(200)).endsWith('-')).toBe(false)
+ })
+
+ it('drops lookalikes and invisible characters instead of letting them pass for letters', () => {
+ // A Cyrillic а must not read as the Latin a in "main".
+ expect(issueBranchSlug('mаin')).toBe('m-in')
+ expect(issueBranchSlug('fix\u202Egnp.exe')).toBe('fix-gnp-exe')
+ expect(issueBranchSlug('zero\u200Bwidth\u200Djoin')).toBe('zero-width-join')
+ })
+})
+
+describe('issueWorktreeBranch', () => {
+ it('names the branch issue-<N>-<slug>, with -k for a suffix of 2 or more', () => {
+ expect(issueWorktreeBranch(12, 'Fix it')).toBe('issue-12-fix-it')
+ expect(issueWorktreeBranch(12, 'Fix it', 1)).toBe('issue-12-fix-it')
+ expect(issueWorktreeBranch(12, 'Fix it', 2)).toBe('issue-12-fix-it-2')
+ expect(issueWorktreeBranch(12, '', 3)).toBe('issue-12-3')
+ })
+
+ it('refuses a number that is not an issue number', () => {
+ for (const n of [0, -1, 1.5, NaN, 2 ** 31, '12', null, undefined]) {
+ expect(issueWorktreeBranch(n, 'x')).toBe('')
+ }
+ })
+
+ it.each(HOSTILE_TITLES)('a hostile title yields a plain, valid branch: %j', (title) => {
+ const branch = issueWorktreeBranch(4242, title)
+ expect(branch).toMatch(BRANCH_SHAPE)
+ expect(branch.length).toBeLessThanOrEqual('issue-4242-'.length + ISSUE_BRANCH_SLUG_MAX)
+ expect(isValidGitRef(branch)).toBe(true)
+ // The worktree folder is one segment under the template's base — no traversal, no separator.
+ const path = computeWorktreePath('/work/repo', branch, DEFAULT_WORKTREE_PATH_TEMPLATE)
+ expect(path).toBe(`/work/repo.worktrees/${branch}`)
+ })
+
+ it('every hostile branch passes the REAL git check-ref-format --branch', () => {
+ for (const title of HOSTILE_TITLES) {
+ for (const suffix of [1, 2, ISSUE_BRANCH_SUFFIX_MAX]) {
+ const branch = issueWorktreeBranch(4242, title, suffix)
+ // argv, never a shell: execFileSync passes the name as ONE argument.
+ const out = execFileSync('git', ['check-ref-format', '--branch', branch], { encoding: 'utf8' })
+ expect(out.trim()).toBe(branch)
+ }
+ }
+ })
+})
+
+describe('isIssueBranch', () => {
+ it('matches the issue and its suffixes, never another issue', () => {
+ expect(isIssueBranch('issue-12', 12)).toBe(true)
+ expect(isIssueBranch('issue-12-fix', 12)).toBe(true)
+ expect(isIssueBranch('Issue-12-Fix', 12)).toBe(true)
+ expect(isIssueBranch('issue-123', 12)).toBe(false)
+ expect(isIssueBranch('issue-1', 12)).toBe(false)
+ expect(isIssueBranch('feature/issue-12', 12)).toBe(false)
+ expect(isIssueBranch(undefined, 12)).toBe(false)
+ })
+})
+
+const ROOT = '/work/repo'
+const TEMPLATE = DEFAULT_WORKTREE_PATH_TEMPLATE
+const wt = (b: string): string => `/work/repo.worktrees/${b}`
+const base = (over: Partial<IssueWorktreeInput> = {}): IssueWorktreeInput => ({
+ number: 12,
+ title: 'Fix login',
+ repoRoot: ROOT,
+ template: TEMPLATE,
+ entries: [{ path: ROOT, branch: 'main', head: 'a', isBare: false }],
+ branches: ['main'],
+ bound: [],
+ ...over
+})
+const nothingOnDisk = async (): Promise<boolean> => false
+
+describe('planIssueWorktree', () => {
+ it('creates issue-<N>-<slug> at the templated path when nothing is in the way', async () => {
+ expect(await planIssueWorktree(base(), nothingOnDisk)).toEqual({
+ kind: 'create',
+ target: { branch: 'issue-12-fix-login', path: wt('issue-12-fix-login') }
+ })
+ })
+
+ it('offers to reuse a worktree a frame on this canvas is already bound to, with -2 as the alternative', async () => {
+ const plan = await planIssueWorktree(
+ base({
+ entries: [
+ { path: ROOT, branch: 'main', head: 'a', isBare: false },
+ { path: wt('issue-12-fix-login'), branch: 'issue-12-fix-login', head: 'b', isBare: false }
+ ],
+ branches: ['main', 'issue-12-fix-login'],
+ bound: [{ groupId: 'g1', branch: 'issue-12-fix-login', path: wt('issue-12-fix-login') }]
+ }),
+ nothingOnDisk
+ )
+ expect(plan).toEqual({
+ kind: 'choose',
+ existing: { kind: 'bound', groupId: 'g1', branch: 'issue-12-fix-login', path: wt('issue-12-fix-login') },
+ alternative: { branch: 'issue-12-fix-login-2', path: wt('issue-12-fix-login-2') }
+ })
+ })
+
+ it('finds the issue\'s worktree even after its title changed, and offers the new name as the alternative', async () => {
+ const plan = await planIssueWorktree(
+ base({
+ title: 'Fix login on Safari',
+ entries: [
+ { path: ROOT, branch: 'main', head: 'a', isBare: false },
+ { path: wt('issue-12-fix-login'), branch: 'issue-12-fix-login', head: 'b', isBare: false }
+ ],
+ branches: ['main', 'issue-12-fix-login']
+ }),
+ nothingOnDisk
+ )
+ expect(plan.kind).toBe('choose')
+ if (plan.kind !== 'choose') return
+ expect(plan.existing).toMatchObject({ kind: 'orphan', branch: 'issue-12-fix-login' })
+ expect(plan.alternative).toEqual({
+ branch: 'issue-12-fix-login-on-safari',
+ path: wt('issue-12-fix-login-on-safari')
+ })
+ })
+
+ it('prefers a bound frame over an unbound worktree of the same issue', async () => {
+ const plan = await planIssueWorktree(
+ base({
+ entries: [
+ { path: ROOT, branch: 'main', head: 'a', isBare: false },
+ { path: wt('issue-12-fix-login'), branch: 'issue-12-fix-login', head: 'b', isBare: false },
+ { path: wt('issue-12-old'), branch: 'issue-12-old', head: 'c', isBare: false }
+ ],
+ bound: [{ groupId: 'g9', branch: 'issue-12-old', path: wt('issue-12-old') }]
+ }),
+ nothingOnDisk
+ )
+ expect(plan.kind === 'choose' && plan.existing).toMatchObject({ kind: 'bound', groupId: 'g9' })
+ })
+
+ it('never offers the main checkout, a prunable registration or another issue\'s worktree for reuse', async () => {
+ const plan = await planIssueWorktree(
+ base({
+ entries: [
+ { path: ROOT, branch: 'issue-12-fix-login', head: 'a', isBare: false },
+ { path: wt('issue-12-gone'), branch: 'issue-12-gone', head: 'b', isBare: false, prunable: true },
+ { path: wt('issue-123-x'), branch: 'issue-123-x', head: 'c', isBare: false }
+ ],
+ branches: ['issue-12-fix-login', 'issue-12-gone', 'issue-123-x']
+ }),
+ nothingOnDisk
+ )
+ // The wanted branch is checked out in the main checkout: taken, not reusable → -2, and the
+ // caller is told why the name changed.
+ expect(plan).toEqual({
+ kind: 'create',
+ target: { branch: 'issue-12-fix-login-2', path: wt('issue-12-fix-login-2') },
+ renamedFrom: 'issue-12-fix-login'
+ })
+ })
+
+ it('offers to check out the existing branch when it is checked out nowhere', async () => {
+ const plan = await planIssueWorktree(base({ branches: ['main', 'issue-12-fix-login'] }), nothingOnDisk)
+ expect(plan).toEqual({
+ kind: 'choose',
+ existing: { kind: 'branch', branch: 'issue-12-fix-login', path: wt('issue-12-fix-login') },
+ alternative: { branch: 'issue-12-fix-login-2', path: wt('issue-12-fix-login-2') }
+ })
+ })
+
+ it('treats branch names case-insensitively (a case-insensitive filesystem cannot hold both)', async () => {
+ const plan = await planIssueWorktree(base({ branches: ['main', 'Issue-12-Fix-Login'] }), nothingOnDisk)
+ expect(plan.kind === 'choose' && plan.existing.kind).toBe('branch')
+ })
+
+ it('never overwrites a folder that already exists — it moves to the next free suffix', async () => {
+ const taken = new Set([wt('issue-12-fix-login'), wt('issue-12-fix-login-2')])
+ const plan = await planIssueWorktree(base(), async (p) => taken.has(p))
+ expect(plan).toEqual({
+ kind: 'create',
+ target: { branch: 'issue-12-fix-login-3', path: wt('issue-12-fix-login-3') },
+ renamedFrom: 'issue-12-fix-login'
+ })
+ })
+
+ it('reads a failed existence probe as "taken", never as absence', async () => {
+ const plan = await planIssueWorktree(base(), async (p) => {
+ if (p === wt('issue-12-fix-login')) throw new Error('EACCES')
+ return false
+ })
+ expect(plan.kind === 'create' && plan.target.branch).toBe('issue-12-fix-login-2')
+ })
+
+ it('does not offer to check out an existing branch into a folder that is taken', async () => {
+ const plan = await planIssueWorktree(
+ base({ branches: ['main', 'issue-12-fix-login'] }),
+ async (p) => p === wt('issue-12-fix-login')
+ )
+ expect(plan).toEqual({
+ kind: 'create',
+ target: { branch: 'issue-12-fix-login-2', path: wt('issue-12-fix-login-2') },
+ renamedFrom: 'issue-12-fix-login'
+ })
+ })
+
+ it('counts a bound frame\'s branch as taken even when the worktree list could not be read', async () => {
+ // Bound somewhere OTHER than the templated folder (a --path create, a template changed since):
+ // only the branch says the name is taken, and offering it again would fail at git.
+ const plan = await planIssueWorktree(
+ base({
+ entries: [],
+ branches: null,
+ bound: [{ groupId: 'g1', branch: 'issue-12-fix-login', path: '/elsewhere/issue-12-fix-login' }]
+ }),
+ nothingOnDisk
+ )
+ expect(plan.kind === 'choose' && plan.alternative?.branch).toBe('issue-12-fix-login-2')
+ })
+
+ it('counts a bound frame\'s folder as taken too', async () => {
+ const plan = await planIssueWorktree(
+ base({
+ entries: [],
+ branches: null,
+ bound: [{ groupId: 'g1', branch: 'someone-else', path: wt('issue-12-fix-login') }]
+ }),
+ nothingOnDisk
+ )
+ expect(plan).toMatchObject({ kind: 'create', target: { branch: 'issue-12-fix-login-2' } })
+ })
+
+ it('refuses when every suffix is taken, when there is no repository, or no path', async () => {
+ expect((await planIssueWorktree(base(), async () => true)).kind).toBe('refused')
+ expect((await planIssueWorktree(base({ repoRoot: ' ' }), nothingOnDisk)).kind).toBe('refused')
+ // A template that climbs to the filesystem root yields no path (computeWorktreePath's guard).
+ expect((await planIssueWorktree(base({ template: '../../../../..' }), nothingOnDisk)).kind).toBe('refused')
+ expect((await planIssueWorktree(base({ number: 0 }), nothingOnDisk)).kind).toBe('refused')
+ })
+
+ it('a hostile title still plans a folder directly under the template base', async () => {
+ for (const title of HOSTILE_TITLES) {
+ const plan = await planIssueWorktree(base({ title }), nothingOnDisk)
+ expect(plan.kind).toBe('create')
+ if (plan.kind !== 'create') continue
+ expect(plan.target.branch).toMatch(BRANCH_SHAPE)
+ expect(plan.target.path).toBe(wt(plan.target.branch))
+ }
+ })
+})
diff --git a/src/shared/issue-worktree.ts b/src/shared/issue-worktree.ts
new file mode 100644
index 000000000..02c5f1789
--- /dev/null
+++ b/src/shared/issue-worktree.ts
@@ -0,0 +1,230 @@
+import { computeWorktreePath, type WorktreeEntry } from './worktree'
+import { normWorktreePath } from './worktree-reconcile'
+
+// "Start with agent in a new worktree" on a GitHub issue card: the branch it creates, and what it
+// does when that branch (or its folder) is already taken.
+//
+// The branch is named from the issue NUMBER and a slug of its TITLE, and the title is attacker-
+// controlled: anyone can open an issue on a public repository and put whatever they like in it. So
+// the slug is an ALLOWLIST (`[a-z0-9-]`, nothing else survives), it is capped, and the result never
+// travels through a shell — it reaches git as one argv element (`worktree-ops.worktreeAdd`, which
+// also refuses a leading `-`). A branch built here always passes `git check-ref-format --branch`:
+// the alphabet has no `.`, `@`, `/`, `~`, `^`, `:`, `?`, `*`, `[`, `\`, space or control byte, and
+// every name starts with the literal `issue-` (`issue-worktree.test.ts` runs the real git over the
+// hostile cases).
+//
+// What is already on disk is never overwritten. An existing worktree for the same issue is offered
+// for REUSE; a name or folder that is merely taken moves to the next free `-2`, `-3`, … suffix.
+
+/** The longest slug a branch carries. Long enough to read, short enough for a path segment and a
+ * group chip. */
+export const ISSUE_BRANCH_SLUG_MAX = 40
+
+/** How many `-k` suffixes the planner tries before it gives up (a folder of 20 attempts for one
+ * issue is a mess a person should look at, not one the app should keep extending). */
+export const ISSUE_BRANCH_SUFFIX_MAX = 20
+
+/** Bounds the work a hostile 1 MB title can cause before the cap applies. */
+const TITLE_SCAN_MAX = 1000
+
+const MAX_ISSUE_NUMBER = 2 ** 31 - 1
+
+function validNumber(value: unknown): value is number {
+ return (
+ typeof value === 'number' && Number.isSafeInteger(value) && value >= 1 && value <= MAX_ISSUE_NUMBER
+ )
+}
+
+/**
+ * The title as a branch slug: lower-case ASCII letters and digits, runs of anything else collapsed
+ * to one `-`, trimmed, capped at {@link ISSUE_BRANCH_SLUG_MAX} (cut back to a word boundary when the
+ * cap lands mid-word). Accented Latin keeps its base letter (`café` → `cafe`); every other script,
+ * emoji, lookalike, bidi or zero-width character is dropped. `''` when nothing survives — the
+ * caller then names the branch `issue-<N>` alone.
+ */
+export function issueBranchSlug(title: unknown): string {
+ if (typeof title !== 'string') return ''
+ // Lower-case BEFORE decomposing: `İ`.toLowerCase() is `i` + a combining dot, which the mark strip
+ // below must see.
+ const folded = title
+ .slice(0, TITLE_SCAN_MAX)
+ .toLowerCase()
+ .normalize('NFKD')
+ .replace(/\p{M}+/gu, '')
+ let slug = folded.replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
+ if (slug.length > ISSUE_BRANCH_SLUG_MAX) {
+ const cut = slug.slice(0, ISSUE_BRANCH_SLUG_MAX)
+ // Mid-word? Back up to the last separator, as long as that keeps at least half the budget.
+ const midWord = slug[ISSUE_BRANCH_SLUG_MAX] !== '-'
+ const lastDash = cut.lastIndexOf('-')
+ slug = midWord && lastDash >= ISSUE_BRANCH_SLUG_MAX / 2 ? cut.slice(0, lastDash) : cut
+ slug = slug.replace(/-+$/g, '')
+ }
+ return slug
+}
+
+/**
+ * `issue-<N>-<slug>` (or `issue-<N>` when the title leaves no slug), with `-<suffix>` appended for
+ * a suffix of 2 or more. `''` for a number that is not a real issue number.
+ */
+export function issueWorktreeBranch(number: unknown, title?: unknown, suffix = 1): string {
+ if (!validNumber(number)) return ''
+ const slug = issueBranchSlug(title)
+ const base = slug ? `issue-${number}-${slug}` : `issue-${number}`
+ return Number.isSafeInteger(suffix) && suffix >= 2 ? `${base}-${suffix}` : base
+}
+
+/** Is this branch one of the issue's own (`issue-<N>` or `issue-<N>-…`)? `issue-12` is not
+ * `issue-123`'s. Case-insensitive: a hand-made `Issue-12-x` is still that issue's. */
+export function isIssueBranch(branch: unknown, number: number): boolean {
+ if (typeof branch !== 'string' || !validNumber(number)) return false
+ const b = branch.toLowerCase()
+ return b === `issue-${number}` || b.startsWith(`issue-${number}-`)
+}
+
+/** Where a new worktree would go. */
+export interface IssueWorktreeTarget {
+ branch: string
+ path: string
+}
+
+/** A worktree group frame on the canvas, and the branch it is bound to (stale frames excluded by
+ * the caller: a directory that is gone is nothing to reuse). */
+export interface IssueWorktreeBoundGroup {
+ groupId: string
+ branch: string
+ path: string
+}
+
+/** Something already on disk (or on the canvas) the user may want to reuse for this issue. */
+export type IssueWorktreeExisting =
+ /** A worktree for this issue that a group frame on this canvas is already bound to: reuse = open
+ * the agent in that frame. */
+ | { kind: 'bound'; groupId: string; branch: string; path: string }
+ /** A worktree for this issue on disk that no frame is bound to: reuse = adopt it (never deleted by
+ * Remove, because the app did not create it). */
+ | { kind: 'orphan'; branch: string; path: string; entry: WorktreeEntry }
+ /** The branch the app would create exists, but is checked out nowhere: reuse = check THAT branch
+ * out in a new worktree at `path`. */
+ | { kind: 'branch'; branch: string; path: string }
+
+export type IssueWorktreePlan =
+ | { kind: 'refused'; reason: string }
+ /** Nothing in the way (or only a name/folder that is merely taken — `renamedFrom` then names the
+ * branch that was wanted, so the caller can say why the new one ends in `-2`). */
+ | { kind: 'create'; target: IssueWorktreeTarget; renamedFrom?: string }
+ /** An existing worktree/branch for this issue: the person picks reuse or `alternative` (null when
+ * no free name was found within {@link ISSUE_BRANCH_SUFFIX_MAX} attempts). */
+ | { kind: 'choose'; existing: IssueWorktreeExisting; alternative: IssueWorktreeTarget | null }
+
+export interface IssueWorktreeInput {
+ number: number
+ /** The issue title — hostile input, only ever slugged. */
+ title: unknown
+ repoRoot: string
+ /** The effective path template (`effectiveWorktreeTemplate`). */
+ template: string
+ /** `git worktree list` in git's order: the MAIN checkout is first. */
+ entries: readonly WorktreeEntry[]
+ /** Local branch names, or null when they could not be read (git then has the last word). */
+ branches: readonly string[] | null
+ /** Non-stale worktree-bound group frames on this canvas. */
+ bound: readonly IssueWorktreeBoundGroup[]
+}
+
+/** Does anything live at this path? A probe that FAILS answers "yes": a failed read is never
+ * evidence of absence, and the cost of the wrong answer is only a `-2`. */
+export type PathProbe = (path: string) => Promise<boolean>
+
+/**
+ * Decide what "Start with agent in a new worktree" does for this issue. Reads the filesystem only
+ * through `pathExists`, so the whole matrix is testable without a repository.
+ */
+export async function planIssueWorktree(
+ input: IssueWorktreeInput,
+ pathExists: PathProbe
+): Promise<IssueWorktreePlan> {
+ const canonical = issueWorktreeBranch(input.number, input.title)
+ if (!canonical) return { kind: 'refused', reason: 'That is not a valid issue number.' }
+ const repoRoot = input.repoRoot.trim()
+ if (!repoRoot) return { kind: 'refused', reason: 'No git repository was found in this project’s folder.' }
+ const pathFor = (branch: string): string => computeWorktreePath(repoRoot, branch, input.template)
+ if (!pathFor(canonical)) {
+ return {
+ kind: 'refused',
+ reason: 'No worktree location could be derived from the worktree path setting. Nothing was created.'
+ }
+ }
+
+ const known = new Set<string>()
+ for (const b of input.branches ?? []) known.add(b.toLowerCase())
+ for (const e of input.entries) if (e.branch) known.add(e.branch.toLowerCase())
+ // A frame's binding counts too: `entries` may be a failed (empty) read, and a bound branch or
+ // folder is taken whatever git managed to list.
+ for (const g of input.bound) known.add(g.branch.toLowerCase())
+ // Every name this module builds is lower-case already; `known` is folded on the way in.
+ const branchTaken = (b: string): boolean => known.has(b)
+ const entryPaths = new Set(
+ [...input.entries.map((e) => e.path), ...input.bound.map((g) => g.path)].map(normWorktreePath)
+ )
+ const pathTaken = async (p: string): Promise<boolean> => {
+ if (entryPaths.has(normWorktreePath(p))) return true
+ return pathExists(p).catch(() => true)
+ }
+ /** The first `base`, `base-2`, `base-3`, … whose branch AND folder are both free. */
+ const firstFree = async (fromSuffix: number): Promise<IssueWorktreeTarget | null> => {
+ for (let k = fromSuffix; k <= ISSUE_BRANCH_SUFFIX_MAX; k++) {
+ const branch = issueWorktreeBranch(input.number, input.title, k)
+ if (branchTaken(branch)) continue
+ const path = pathFor(branch)
+ if (!path || (await pathTaken(path))) continue
+ return { branch, path }
+ }
+ return null
+ }
+
+ // 1. A worktree this issue already has. A frame bound to it beats an unbound one (that is where
+ // the issue's other sessions already are), and the exact name beats a sibling of it.
+ const byName = <T extends { branch: string }>(xs: T[]): T | undefined =>
+ xs.find((x) => x.branch.toLowerCase() === canonical) ?? xs[0]
+ const boundHere = input.bound.filter((g) => isIssueBranch(g.branch, input.number))
+ const boundPaths = new Set(input.bound.map((g) => normWorktreePath(g.path)))
+ const orphans = input.entries
+ .slice(1) // the main checkout is never "a worktree to reuse"
+ .filter((e) => !e.isBare && !e.prunable && e.branch && isIssueBranch(e.branch, input.number))
+ .filter((e) => !boundPaths.has(normWorktreePath(e.path)))
+ .map((e) => ({ branch: e.branch as string, path: e.path, entry: e }))
+ const bound = byName(boundHere)
+ const orphan = bound ? undefined : byName(orphans)
+ if (bound || orphan) {
+ const existing: IssueWorktreeExisting = bound
+ ? { kind: 'bound', groupId: bound.groupId, branch: bound.branch, path: bound.path }
+ : { kind: 'orphan', branch: orphan!.branch, path: orphan!.path, entry: orphan!.entry }
+ return { kind: 'choose', existing, alternative: await firstFree(1) }
+ }
+
+ // 2. The branch exists but is checked out NOWHERE: offer to check it out. (Checked out somewhere
+ // — the main checkout, or a registration whose folder is gone — it cannot be, so it is simply
+ // taken, and case 3 moves on to `-2`.)
+ const checkedOut = input.entries.some((e) => e.branch?.toLowerCase() === canonical)
+ if (branchTaken(canonical) && !checkedOut) {
+ const path = pathFor(canonical)
+ if (!(await pathTaken(path))) {
+ return {
+ kind: 'choose',
+ existing: { kind: 'branch', branch: canonical, path },
+ alternative: await firstFree(2)
+ }
+ }
+ }
+
+ // 3. A fresh worktree — under the wanted name when it is free, else the next free suffix.
+ const target = await firstFree(1)
+ if (!target) {
+ return {
+ kind: 'refused',
+ reason: `Every name from ${canonical} to ${canonical}-${ISSUE_BRANCH_SUFFIX_MAX} is taken. Nothing was created.`
+ }
+ }
+ return target.branch === canonical ? { kind: 'create', target } : { kind: 'create', target, renamedFrom: canonical }
+}