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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(kanban): issue-worktree review round — placement, stale attach, guards
reviewf0b73bbefa80
diff --git a/CLAUDE.md b/CLAUDE.mdindex b5b6b006a..e50c5cfee 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -5251,22 +5251,35 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord meaupdater 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+ worktree ▸" on an issue card and its summary modal: branch `issue-<N>-<slug>` at the templated+ path, off the SAME base the New worktree dialog defaults to (`effectiveWorktreeBaseRef`: the+ project's base-ref override, else the MAIN CHECKOUT's current branch — not `origin/HEAD`; a main+ checkout parked on a feature branch forks from it, so the success notice names the base), 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. Whatever+ `addAgentNode` would refuse (canvas not the active project's, an unusable Codex account) is asked+ BEFORE git runs (`agentCreateRefusal`, same functions and wording) — a refusal after it would+ leave a fresh worktree with no agent. The agent's launch rides `pendingLaunch` held on the+ frame's setup gate, so it shows QUEUED for the moment the setup ack takes even when the project+ has no setup script. **The title is attacker-controlled**: the slug isan allowlist `[a-z0-9-]` (lower-cased, NFKD with marks stripped so `café` → `cafe`; every otherscript, 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 onlyever 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+ through an injected probe; a probe that REJECTS reads as "taken" — the app's `fs.exists` folds a+ stat error into `false`, and git refusing a non-empty folder is the backstop there) 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, under the branch's OWN spelling — the+ match is case-insensitive, git's lookup is not; the new folder is the app's, so `createdByApp`+ is true exactly as the dialog's "Existing branch" mode sets it) — 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. Reuse is re-checked at the dialog's click+ (a frame on that folder now, else a worktree git still lists), and one `runExclusive` key per+ issue covers the planning AND a dialog-confirmed create, so a second click cannot race the first+ for the same `-2`. Disabled WITH its reason on a relay tab, an SSH project, a cwd-lessproject 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`.diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 43aa2bb71..2d322eedb 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -481,9 +481,11 @@ import {} from '@shared/github-issue-ref'import { planIssueWorktree } from '@shared/issue-worktree'import {+ frameAgentPlacement,issueWorktreeChoiceCopy,issueWorktreeRefusal,issueWorktreeRenamedNotice,+ runExclusive,type IssueWorktreeChoice,type IssueWorktreeMenuAnswer} from '../lib/issueWorktree'@@ -897,6 +899,12 @@ const WORKTREE_SSH_NOTICE = 'Worktrees are not supported in SSH projects yet.'const WORKTREE_NO_CWD_NOTICE ='This project has no folder, so it has no git repository to add a worktree to. Set one first (tab ⌄ → “Set folder…”).'const FOCUS_NO_TARGET_NOTICE = 'Select a terminal or agent node to focus.'+/** `addAgentNode`'s up-front refusals, shared with `agentCreateRefusal` (one wording per reason). */+const CANVAS_NOT_ACTIVE_NOTICE =+ 'Could not create the node: the canvas on screen is not the active project’s. Switch tabs once and try again.'+const CODEX_ACCOUNT_NO_CONNECTION_NOTICE =+ 'That Codex account lives on a host that is not connected — connect its SSH project first.'+const CODEX_ACCOUNT_GONE_NOTICE = 'That Codex account is no longer available. Nothing was created.'// The webview's file loader renders off the LOCAL disk and has no remote counterpart, so a host// path from a remote agent could only resolve to a same-named local file — or nothing. Refuse and@@ -4072,10 +4080,13 @@ 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.*/- // `box` places something other than a default-sized node — a worktree frame, say.+ // `box` places something other than a default-sized node — a worktree frame, say. For a box the+ // answer is a TOP-LEFT that centres it on the view (`freeSpot` answers top-lefts); without one+ // the historical point is returned unchanged.const emptyNodePos = useCallback((box?: { w: number; h: number }): { x: number; y: number } | undefined => {- const preferred = viewCenter()- if (!preferred) return undefined+ const center = viewCenter()+ if (!center) return undefined+ const preferred = box ? { x: center.x - box.w / 2, y: center.y - box.h / 2 } : centerconst s = useSettings.getState().settingsconst w = s.defaultNodeWidth || 640const h = s.defaultNodeHeight || 440@@ -5145,6 +5156,31 @@ export function Canvas() {.projects.find((p) => p.ssh && sshHostKey(p.ssh.server) === host && conn[p.id])?.id}, [])+ /**+ * The refusals `addAgentNode` makes before it builds anything, asked AHEAD of it by a caller that+ * does something expensive on the node's behalf first — the issue card's "Start with agent in a+ * new worktree" runs `git worktree add` before the agent exists, and a refusal after that would+ * leave a fresh worktree with no agent in it. Same functions, same wording, same inputs.+ */+ const agentCreateRefusal = useCallback(+ (agentId: AgentId, accountId?: string | null): string | null => {+ if (!canCreateOnCanvas(nodesProjectIdRef.current, useProjects.getState().activeProjectId)) {+ return CANVAS_NOT_ACTIVE_NOTICE+ }+ if (agentId !== 'codex') return null+ const decision = resolveNewCodexNodeAccount(+ accountId ?? undefined,+ useSettings.getState().settings.codexAccounts,+ connectedProjectIdForHost+ )+ if (decision.create) return null+ return decision.reason === 'no-connection'+ ? CODEX_ACCOUNT_NO_CONNECTION_NOTICE+ : CODEX_ACCOUNT_GONE_NOTICE+ },+ [connectedProjectIdForHost]+ )+const addAgentNode = useCallback((agentId: AgentId,@@ -5173,10 +5209,7 @@ export function Canvas() {console.warn(`[nodeterm] node-create refused: canvas holds ${nodesProjectIdRef.current ?? 'nothing'} but the active project is ${targetProjectId || 'none'}`)- setNotice({- kind: 'error',- text: 'Could not create the node: the canvas on screen is not the active project’s. Switch tabs once and try again.'- })+ setNotice({ kind: 'error', text: CANVAS_NOT_ACTIVE_NOTICE })return}const project = useProjects.getState().getProject(targetProjectId)@@ -5197,8 +5230,8 @@ export function Canvas() {kind: 'error',text:decision.reason === 'no-connection'- ? 'That Codex account lives on a host that is not connected — connect its SSH project first.'- : 'That Codex account is no longer available. Nothing was created.'+ ? CODEX_ACCOUNT_NO_CONNECTION_NOTICE+ : CODEX_ACCOUNT_GONE_NOTICE})return}@@ -6208,15 +6241,25 @@ export function Canvas() {/** 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). */+ * caller that must open a node into the frame in the SAME tick (the issue action).+ *+ * The default `attach` resolves `attachWorktree` through `worktreeControlRef` WHEN IT RUNS, after+ * the git await — never the instance of the render that built these deps. `attachWorktree`'s+ * store refresh closes over that render's active project, and `open-worktree` binds to whatever+ * canvas is on screen when git returns: a tab switch in between would otherwise refresh the+ * worktree store with the PREVIOUS project's folder against the new canvas's frames, and the+ * stale refresh wins the store's epoch — the hazard `worktreeControlRef` exists for. */const worktreeCreateDeps = useCallback(- (attach: CreateBoundWorktreeDeps['attach'] = attachWorktree): CreateBoundWorktreeDeps => ({+ (+ attach: CreateBoundWorktreeDeps['attach'] = (target, wt) =>+ worktreeControlRef.current.attachWorktree(target, wt)+ ): CreateBoundWorktreeDeps => ({worktreeAdd: (repoPath, wtPath, branch, baseRef, isNew) =>api.git.worktreeAdd(repoPath, wtPath, branch, baseRef, isNew),activeProjectId: () => useProjects.getState().activeProjectId,attach}),- [api, attachWorktree]+ [api])const createWorktreeAndGroup = useCallback(@@ -10091,17 +10134,6 @@ export function Canvas() {)// ---- GitHub issue → agent session ("Start with agent ▸") ----- /**- * Start an agent on a GitHub issue card: a normal agent node in the project cwd, bound to the- * issue (`data.issueRef`), launched with a prompt that carries only the REFERENCE — the issue's- * title and body are attacker-writable on a public repository and never reach the pane; the- * agent reads them itself with `gh`. The reference comes from the card's GitHub URL and is- * validated before anything is created; a card whose URL does not parse starts nothing.- *- * The new session card is filed 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). The issue card's run history gets `run-started`.- *//*** 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`@@ -10150,7 +10182,9 @@ export function Canvas() {[seedBoard, markDirty, api])- /** The reference + first prompt of an issue start, or a notice saying why nothing started. */+ /** The reference + first prompt of an issue start, or a notice saying why nothing started. The+ * reference comes from the card's GitHub URL and is validated before anything is created; a card+ * whose URL does not parse starts nothing. The issue's title and body never reach the prompt. */const issueStartPrompt = useCallback((issue: GitHubIssueCardView): { ref: IssueRef; prompt: string } | undefined => {const ref = issueRefFromHtmlUrl(issue.htmlUrl, issue.number)@@ -10167,6 +10201,13 @@ export function Canvas() {[])+ /**+ * Start an agent on a GitHub issue card: a normal agent node in the project cwd, bound to the+ * issue (`data.issueRef`), launched with a prompt that carries only the REFERENCE — the issue's+ * title and body are attacker-writable on a public repository and never reach the pane; the+ * agent reads them itself with `gh`. The new session card is filed under the issue card's column+ * and the issue card's run history gets `run-started` (`fileIssueSession`).+ */const startIssueAgent = useCallback((issue: GitHubIssueCardView, agentId: AgentId, accountId?: string | null) => {const start = issueStartPrompt(issue)@@ -10199,7 +10240,7 @@ export function Canvas() {value: IssueWorktreeChoicerun: (choice: IssueWorktreeChoice) => void} | null>(null)- /** Issues with a start in flight — a second click while git works is refused, not doubled. */+ /** Issues with a start in flight (`runExclusive`) — planning AND a dialog-confirmed create. */const issueWorktreeInFlightRef = useRef(new Set<string>())/** Why "Start with agent in a new worktree" cannot run on the ACTIVE project, or null. Read at@@ -10219,8 +10260,8 @@ export function Canvas() {* 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`).+ * so the agent's cwd would fall back to the project folder. The slot is the control opens' grid+ * (`frameAgentPlacement`), and the frame grows to hold the node as actually built.*/const openIssueAgentInFrame = useCallback((@@ -10233,24 +10274,12 @@ export function Canvas() {const all = nodesRef.currentconst 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 { center } = frameAgentPlacement(origin, children, terminalNodeSize())const created = addAgentNode(agentId,- { x: origin.x + slot.x, y: origin.y + slot.y },+ center,groupId,accountId,start.prompt,@@ -10259,6 +10288,23 @@ export function Canvas() {{ issueRef: start.ref, awaitSetupGroup: setupHoldGroup(groupId) })if (!created) return false // addAgentNode already said why+ // Grow the frame to hold the node as BUILT (snap-to-grid can round its size up). Queued after+ // the node's own insert, so both land in one render; `extent: 'parent'` then has room.+ const built = created.node+ const { frame } = frameAgentPlacement(origin, children, {+ width: (built.width as number | undefined) ?? terminalNodeSize().width,+ height: (built.height as number | undefined) ?? terminalNodeSize().height+ })+ const width = Math.max((group.width as number | undefined) ?? 0, frame.width)+ const height = Math.max((group.height as number | undefined) ?? 0, frame.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[]))+ }fileIssueSession(issue, start.ref, created, agentId)return true},@@ -10267,7 +10313,8 @@ export function Canvas() {/*** "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+ * `issue-<N>-<slug>` (at the configured worktree location, off the same base the New worktree+ * dialog defaults to — the project's base-ref override, else the main checkout's branch), 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.@@ -10287,27 +10334,86 @@ export function Canvas() {const start = issueStartPrompt(issue)if (!start) returnconst key = issueKey(start.ref) ?? `#${issue.number}`- if (issueWorktreeInFlightRef.current.has(key)) {+ const busy = (): void =>setNotice({ kind: 'info', text: `A worktree for #${issue.number} is already being prepared.` })- return+ /** Refuse BEFORE git whatever `addAgentNode` would refuse after it — a fresh worktree with no+ * agent in it is the one outcome this action must not leave behind. Asked again at a click. */+ const agentRefused = (): boolean => {+ const why = agentCreateRefusal(agentId, accountId)+ if (why) setNotice({ kind: 'error', text: why })+ return !!why}+ if (agentRefused()) returnconst projectId = useProjects.getState().activeProjectIdconst 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+ const projectMoved = (): boolean => {+ if (useProjects.getState().activeProjectId === projectId) return false+ setNotice({ kind: 'info', text: `The project changed, so nothing was started for #${issue.number}.` })+ return true+ }+ // Same defaults as the New worktree dialog and `open-worktree`: a project override, else the+ // main checkout's 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+ )+ const size = terminalNodeSize()+ const { frame: need } = frameAgentPlacement({ x: 0, y: 0 }, 0, size)+ 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 —+ * inside the attach, in the same tick as the frame. */+ 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 = worktreeControlRef.current.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 })- // 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.+ 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+ const where = mode === 'new' ? `off ${baseRef} ` : ''+ setNotice({+ kind: 'info',+ text: renamedFrom+ ? `${issueWorktreeRenamedNotice(renamedFrom, target.branch)} It is ${where}at ${target.path}.`+ : `Worktree ${target.branch} created ${where}at ${target.path}; the agent opens there.`+ })+ }+ const ran = await runExclusive(issueWorktreeInFlightRef.current, key, async () => {+ // Local branches, so a taken name is seen before git refuses it. An unreadable list comes+ // back empty: git then has the last word, and its refusal is what the notice shows.const branches = await api.git.status(repoRoot).then((st) => st.branches ?? null,() => null@@ -10321,64 +10427,11 @@ export function Canvas() {)// 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 (projectMoved()) returnif (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@@ -10387,52 +10440,58 @@ export function Canvas() {const copy = issueWorktreeChoiceCopy(start.ref.number, existing, alternative, baseRef)setIssueWorktreeAsk({...copy,+ // Everything re-asked at the click: the dialog stays up for as long as the person reads it.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}.` })+ if (projectMoved() || agentRefused()) return+ if (choice === 'new' || existing.kind === 'branch') {+ const target = choice === 'new' ? alternative : existing+ if (!target) return+ void runExclusive(issueWorktreeInFlightRef.current, key, () =>+ create({ branch: target.branch, path: target.path }, choice === 'new' ? 'new' : 'existing')+ ).then((started) => started || busy())return}- if (choice === 'new') {- if (alternative) void create(alternative, 'new')- return- }- if (existing.kind === 'branch') {- void create({ branch: existing.branch, path: existing.path }, 'existing')+ // A frame bound to this worktree now — the one the plan found, or one that adopted the+ // orphan while the dialog was open — takes the agent. Never a second frame on one folder.+ const live = boundGroups(nodesRef.current).find(+ (b) =>+ normWorktreePath(b.worktree.path) === normWorktreePath(existing.path) &&+ !useWorktrees.getState().staleGroupIds.includes(b.groupId)+ )+ if (live) {+ openIssueAgentInFrame(live.groupId, issue, start, agentId, accountId)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)+ // The frame the plan found is gone or no longer bound, or the unbound worktree is no+ // longer listed (removed, or pruned): say so rather than bind a folder that may be gone.+ const listed = useWorktrees+ .getState()+ .entries.find((e) => normWorktreePath(e.path) === normWorktreePath(existing.path))+ if (existing.kind === 'bound' || !listed || listed.prunable || !listed.branch) {+ setNotice({+ kind: 'error',+ text: `The worktree for #${issue.number} at ${existing.path} is gone or no longer bound. Nothing was started.`+ })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))+ const wt = worktreeFromEntry(listed, repoRoot, resolveBaseRef(useWorktrees.getState().entries))if (!wt) return- const groupId = attachWorktree(newFrame(), wt)+ const groupId = worktreeControlRef.current.attachWorktree(newFrame(), wt)openIssueAgentInFrame(groupId, issue, start, agentId, accountId)}})- } finally {- issueWorktreeInFlightRef.current.delete(key)- }+ })+ if (!ran) busy()},[issueWorktreeUnavailable,issueStartPrompt,+ agentCreateRefusal,api,emptyNodePos,worktreeCreateDeps,- attachWorktree,openIssueAgentInFrame])diff --git a/src/renderer/canvas/issue-worktree.source.test.ts b/src/renderer/canvas/issue-worktree.source.test.tsindex 8ba48c856..fc7c29cdd 100644--- a/src/renderer/canvas/issue-worktree.source.test.ts+++ b/src/renderer/canvas/issue-worktree.source.test.ts@@ -43,6 +43,17 @@ describe('one create-and-bind for every way the app makes a worktree', () => {expect(body).toContain('`Could not create the worktree: ${res.message}`')})+ it('the default attach is resolved WHEN IT RUNS (after git), never frozen at the call', () => {+ // `worktreeCreateDeps()` is evaluated before the git await. Defaulting `attach` to that render's+ // `attachWorktree` refreshed the worktree store with the PREVIOUS project's folder after a tab+ // switch — the hazard `worktreeControlRef` exists for.+ const deps = between('const worktreeCreateDeps = useCallback(', 'const createWorktreeAndGroup = useCallback(')+ expect(deps).toMatch(+ /attach: CreateBoundWorktreeDeps\['attach'\] = \(target, wt\) =>\s*worktreeControlRef\.current\.attachWorktree\(target, wt\)/+ )+ expect(deps).not.toMatch(/=\s*attachWorktree\b/)+ })+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)'))@@ -89,25 +100,38 @@ describe('Start with agent in a new worktree', () => {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,/+ /worktreeCreateDeps\(\(t, wt\) => \{\s*const groupId = worktreeControlRef\.current\.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\)/+ /const groupId = worktreeControlRef\.current\.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', () => {+ it('refuses before anything else when the project cannot take a worktree', () => {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('asks what addAgentNode would refuse BEFORE git runs, and again at the dialog click', () => {+ // A refusal after `git worktree add` would leave a fresh worktree with no agent in it.+ expect(body).toContain('const why = agentCreateRefusal(agentId, accountId)')+ const pre = body.indexOf('if (agentRefused()) return')+ expect(pre).toBeGreaterThan(-1)+ expect(pre).toBeLessThan(body.indexOf('runExclusive('))+ expect(body).toContain('if (projectMoved() || agentRefused()) return')+ })++ it('holds the in-flight key across planning AND a dialog-confirmed create', () => {+ const guarded = body.match(/runExclusive\(issueWorktreeInFlightRef\.current, key,/g) ?? []+ expect(guarded).toHaveLength(2)+ const inRun = body.slice(body.indexOf('run: (choice) => {'))+ expect(inRun).toMatch(/void runExclusive\(issueWorktreeInFlightRef\.current, key, \(\) =>\s*create\(/)})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)+ expect(body.match(/projectMoved\(\)/g)?.length ?? 0).toBeGreaterThanOrEqual(2)// …and the create itself passes the project, so git finishing after a tab switch binds nothing.expect(body).toContain('{ target: newFrame, projectId }')})@@ -117,9 +141,25 @@ describe('Start with agent in a new worktree', () => {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')+ it('reuse is re-validated at the click: a live, non-stale frame on that folder, else a still-listed worktree', () => {+ const inRun = body.slice(body.indexOf('run: (choice) => {'))+ expect(inRun).toContain('normWorktreePath(b.worktree.path) === normWorktreePath(existing.path)')+ expect(inRun).toContain('!useWorktrees.getState().staleGroupIds.includes(b.groupId)')+ expect(inRun).toContain("existing.kind === 'bound' || !listed || listed.prunable || !listed.branch")+ })++ it('places the agent through frameAgentPlacement (a CENTER), never a raw slot', () => {+ const open = between('const openIssueAgentInFrame = useCallback(', 'const startIssueAgentInWorktree = useCallback(')+ expect(open).toContain('const { center } = frameAgentPlacement(origin, children, terminalNodeSize())')+ expect(open).not.toContain('groupSlot(')+ })+})++describe('a new issue frame is centred on the view', () => {+ it('emptyNodePos(box) answers a TOP-LEFT that centres the box (freeSpot answers top-lefts)', () => {+ const pos = between('const emptyNodePos = useCallback(', 'const scmCwd = useCallback(')+ expect(pos).toContain('const preferred = box ? { x: center.x - box.w / 2, y: center.y - box.h / 2 } : center')+ expect(pos).toContain('return freeSpot(boxes, preferred, box ?? { w, h })')})})diff --git a/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsx b/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsxindex 019064099..2a819595f 100644--- a/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsx+++ b/src/renderer/components/kanban/GitHubIssueSummaryModal.test.tsx@@ -4,6 +4,7 @@ import { createRoot } from 'react-dom/client'import { describe, expect, it, vi } from 'vitest'import type { GitHubIssueCardView } from '@shared/github-issues'import { GitHubIssueSummaryModal } from './GitHubIssueSummaryModal'+import { popDialog, pushDialog } from '../dialog-stack'vi.mock('../../session/session', () => ({useSession: () => ({@@ -73,6 +74,25 @@ describe('GitHubIssueSummaryModal', () => {vi.unstubAllGlobals()})+ it('Escape closes the modal, but not while a dialog stacked over it owns the key', () => {+ const host = document.createElement('div')+ document.body.append(host)+ const root = createRoot(host)+ const onClose = vi.fn()+ act(() => root.render(+ <GitHubIssueSummaryModal issue={issue} columns={[]} moving={false} readOnly={false}+ onMove={vi.fn()} onClose={onClose} />+ ))+ pushDialog('stacked-confirm')+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))+ expect(onClose).not.toHaveBeenCalled()+ popDialog('stacked-confirm')+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))+ expect(onClose).toHaveBeenCalledTimes(1)+ act(() => root.unmount())+ host.remove()+ })+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')diff --git a/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx b/src/renderer/components/kanban/GitHubIssueSummaryModal.tsxindex 3e20e6a4a..456f9378b 100644--- a/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx+++ b/src/renderer/components/kanban/GitHubIssueSummaryModal.tsx@@ -12,6 +12,7 @@ import { useSession } from '../../session/session'import { Button } from '@renderer/ui/Button'import { Select } from '@renderer/ui/Select'import { ContextMenu, type MenuItem } from '../ContextMenu'+import { openDialogCount } from '../dialog-stack'import { NO_ISSUE_RUNS, type IssueRun } from '../../lib/issueRuns'import { IssueRunChips } from './IssueRunChips'import { BoardLogPanel } from './BoardLogPanel'@@ -94,7 +95,9 @@ export function GitHubIssueSummaryModal({}, [])useEffect(() => {const key = (event: KeyboardEvent) => {- if (event.key === 'Escape') onClose()+ // A dialog stacked over this modal (the close/reopen confirm, the worktree reuse-or-new+ // choice) owns its own Escape: closing the modal underneath it too took two answers for one key.+ if (event.key === 'Escape' && openDialogCount() === 0) onClose()if (event.key === 'Tab' && dialog.current) {const focusable = [...dialog.current.querySelectorAll<HTMLElement>('button:not([disabled]), select:not([disabled]), [href], [tabindex]:not([tabindex="-1"])'diff --git a/src/renderer/lib/issueWorktree.test.ts b/src/renderer/lib/issueWorktree.test.tsindex 080cd7bd9..bd08a9196 100644--- a/src/renderer/lib/issueWorktree.test.ts+++ b/src/renderer/lib/issueWorktree.test.ts@@ -1,5 +1,9 @@import { describe, expect, it } from 'vitest'+import { createAgentNode, terminalNodeSize } from '../state/workspace'+import { GROUP_PAD_TOP, GROUP_PAD_X } from './coldOpen'import {+ frameAgentPlacement,+ runExclusive,ISSUE_WORKTREE_LABEL,ISSUE_WORKTREE_NO_REPO_HINT,ISSUE_WORKTREE_RELAY_HINT,@@ -106,3 +110,53 @@ describe('issueWorktreeRenamedNotice', () => {)})})++describe('frameAgentPlacement', () => {+ const size = terminalNodeSize()+ const origin = { x: 1000, y: 2000 }++ it('hands addAgentNode a CENTER whose node lands at the frame\'s first slot, inside the frame', () => {+ const { center, frame } = frameAgentPlacement(origin, 0, size)+ // The REAL factory, which centres the node on the point it is given.+ const node = createAgentNode('claude', 0, '/w', center)+ expect(node.position).toEqual({ x: origin.x + GROUP_PAD_X, y: origin.y + GROUP_PAD_TOP })+ // Below the label band (the frame's drag handle), and wholly inside the frame.+ expect(node.position.y - origin.y).toBeGreaterThanOrEqual(GROUP_PAD_TOP)+ expect(node.position.x + (node.width as number)).toBeLessThanOrEqual(origin.x + frame.width)+ expect(node.position.y + (node.height as number)).toBeLessThanOrEqual(origin.y + frame.height)+ })++ it('a second agent takes the next slot without overlapping the first, and the frame grows to hold both', () => {+ const first = createAgentNode('claude', 0, '/w', frameAgentPlacement(origin, 0, size).center)+ const next = frameAgentPlacement(origin, 1, size)+ const second = createAgentNode('claude', 1, '/w', next.center)+ expect(second.position.x).toBeGreaterThanOrEqual(first.position.x + (first.width as number))+ expect(second.position.y).toBe(first.position.y)+ expect(second.position.x + (second.width as number)).toBeLessThanOrEqual(origin.x + next.frame.width)+ })+})++describe('runExclusive', () => {+ it('refuses a second start while the first is running, and frees the key when it ends', async () => {+ const inFlight = new Set<string>()+ let release!: () => void+ const first = runExclusive(inFlight, 'o/r#12', () => new Promise<void>((r) => (release = r)))+ expect(await runExclusive(inFlight, 'o/r#12', async () => {})).toBe(false)+ // Another issue is not blocked.+ expect(await runExclusive(inFlight, 'o/r#13', async () => {})).toBe(true)+ release()+ expect(await first).toBe(true)+ expect(inFlight.has('o/r#12')).toBe(false)+ expect(await runExclusive(inFlight, 'o/r#12', async () => {})).toBe(true)+ })++ it('frees the key when the task throws', async () => {+ const inFlight = new Set<string>()+ await expect(+ runExclusive(inFlight, 'k', async () => {+ throw new Error('boom')+ })+ ).rejects.toThrow('boom')+ expect(inFlight.has('k')).toBe(false)+ })+})diff --git a/src/renderer/lib/issueWorktree.ts b/src/renderer/lib/issueWorktree.tsindex b7ca04dc8..9c5202338 100644--- a/src/renderer/lib/issueWorktree.ts+++ b/src/renderer/lib/issueWorktree.ts@@ -2,6 +2,7 @@ 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'+import { groupSizeFor, groupSlot } from './coldOpen'// 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@@ -16,7 +17,11 @@ 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'+/** `repoRoot` is null both for a folder that is not a repository and while (or after) the store's+ * read failed — so the reason names both, rather than claiming absence on a read that did not+ * happen. */+export const ISSUE_WORKTREE_NO_REPO_HINT =+ 'No git repository was found for this project’s folder (or git could not be read)'/*** Why the action cannot run on this project, or `null` when it can. The rows are shown DISABLED@@ -99,3 +104,46 @@ export function issueWorktreeMenuRow(answer: IssueWorktreeMenuAnswer, icon?: Rea}return { type: 'submenu', label: ISSUE_WORKTREE_LABEL, icon, children: answer.items }}++/**+ * Where the next agent opened INTO a worktree frame goes, in root space, and how big the frame must+ * then be. The same grid the control opens use (`groupSlot` / `groupSizeFor`). Returns a CENTER,+ * because that is what `addAgentNode` takes — the node factories centre a node on the point they+ * are given (`placeAt`) — while `groupSlot` is a TOP-LEFT offset inside the frame. Handing the slot+ * over as-is put the agent half a node up and left: over the frame's label, its only drag handle.+ */+export function frameAgentPlacement(+ frameOrigin: { x: number; y: number },+ children: number,+ size: { width: number; height: number }+): { center: { x: number; y: number }; frame: { width: number; height: number } } {+ const slot = groupSlot(children, size.width, size.height)+ return {+ center: {+ x: frameOrigin.x + slot.x + size.width / 2,+ y: frameOrigin.y + slot.y + size.height / 2+ },+ frame: groupSizeFor(children + 1, size.width, size.height)+ }+}++/**+ * Run `task` unless one is already running under `key`; `false` = refused (a start for this issue is+ * in flight). Held across EVERYTHING the start awaits — the planning reads AND a create confirmed+ * from the reuse-or-new dialog — so a second click while git works cannot plan against the store as+ * it was before the first worktree existed and race it for the same name.+ */+export async function runExclusive(+ inFlight: Set<string>,+ key: string,+ task: () => Promise<void>+): Promise<boolean> {+ if (inFlight.has(key)) return false+ inFlight.add(key)+ try {+ await task()+ } finally {+ inFlight.delete(key)+ }+ return true+}diff --git a/src/shared/issue-worktree.test.ts b/src/shared/issue-worktree.test.tsindex 8ee0fbb7e..26c4333b4 100644--- a/src/shared/issue-worktree.test.ts+++ b/src/shared/issue-worktree.test.ts@@ -234,9 +234,38 @@ describe('planIssueWorktree', () => {})})- it('treats branch names case-insensitively (a case-insensitive filesystem cannot hold both)', async () => {+ it('treats branch names case-insensitively, and offers the existing one under its OWN spelling', async () => {+ // A case-insensitive filesystem cannot hold both; and git resolves the name it is given, so the+ // checkout must name `Issue-12-Fix-Login`, not the lower-case name the app would have created.const plan = await planIssueWorktree(base({ branches: ['main', 'Issue-12-Fix-Login'] }), nothingOnDisk)- expect(plan.kind === 'choose' && plan.existing.kind).toBe('branch')+ 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('a differently-cased branch still takes the name when its folder is taken too (no second branch that differs only in case)', 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('skips a suffix whose branch exists under another case', async () => {+ const plan = await planIssueWorktree(+ base({ branches: ['main', 'Issue-12-Fix-Login', 'ISSUE-12-FIX-LOGIN-2'] }),+ nothingOnDisk+ )+ expect(plan.kind === 'choose' && plan.alternative).toEqual({+ branch: 'issue-12-fix-login-3',+ path: wt('issue-12-fix-login-3')+ })})it('never overwrites a folder that already exists — it moves to the next free suffix', async () => {diff --git a/src/shared/issue-worktree.ts b/src/shared/issue-worktree.tsindex 02c5f1789..f6a4fccde 100644--- a/src/shared/issue-worktree.ts+++ b/src/shared/issue-worktree.ts@@ -126,14 +126,16 @@ export interface IssueWorktreeInput {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). */+ /** Local branch names; null or empty 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`. */+/** Does anything live at this path? A probe that REJECTS reads as "yes": a failed read is never+ * evidence of absence, and the cost of the wrong answer is only a `-2`. (A probe that folds a stat+ * error into `false` — the app's `fs.exists` does — is backstopped by git, which refuses to add a+ * worktree into a folder that is not empty.) */export type PathProbe = (path: string) => Promise<boolean>/**@@ -206,13 +208,17 @@ export async function planIssueWorktree(// 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`.)+ // The branch is offered under ITS OWN spelling: `known` is case-folded, but git resolves the+ // name it is given, and `issue-12-x` does not name a local `Issue-12-X` on a case-sensitive+ // filesystem or in packed refs.const checkedOut = input.entries.some((e) => e.branch?.toLowerCase() === canonical)- if (branchTaken(canonical) && !checkedOut) {+ const existingBranch = (input.branches ?? []).find((b) => b.toLowerCase() === canonical)+ if (existingBranch && !checkedOut) {const path = pathFor(canonical)if (!(await pathTaken(path))) {return {kind: 'choose',- existing: { kind: 'branch', branch: canonical, path },+ existing: { kind: 'branch', branch: existingBranch, path },alternative: await firstFree(2)}}