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(worktree): a stale Unbind takes the dead cwd off the children with it
enes3e0df732ac19
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex ac11e01e5..cdaa738d2 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -93,8 +93,7 @@ import { LoopNode } from '../nodes/LoopNode'import type { NormalizedAgentEvent } from '@shared/agents/normalize'import {computeWorktreePath,- descendantIds,- isInsideDir,+ displacedByWorktree,resolveBaseRef,sanitizeWorktreeBranch,worktreeFromCreate,@@ -2153,6 +2152,56 @@ export function Canvas() {[setNodes, markDirty, refreshWorktreeStore])+ /**+ * Move every node that was living in a worktree directory OFF that (now dead) path — back to the+ * group's own cwd, else the project's. `displacedByWorktree` decides who those are: descendants+ * (nested groups included) whose cwd is inside the worktree; anyone else is left alone.+ *+ * Leaving a dead `data.cwd` behind is the trap this whole task exists to remove — it is persisted+ * to project.json, tmux hides it (a warm reattach ignores cwd), and the next machine reboot cold-+ * starts the terminal into a directory that no longer exists, where pty-manager silently falls+ * back to $HOME while the dead path stays in the project file forever.+ *+ * `respawn` separates the two callers:+ * - Remove (true): the directory is being deleted under live sessions, so their tmux sessions are+ * destroyed and the terminals respawn straight into the fallback cwd.+ * - Stale Unbind (false): unbind touches no process, by definition. The dead path is corrected on+ * the node (and on disk); the running session keeps going until it is next cold-started, which+ * is precisely when the corrected cwd is needed.+ */+ const resetDisplacedCwd = useCallback(+ (groupId: string, worktreePath: string, respawn: boolean) => {+ const displaced = displacedByWorktree(nodesRef.current, groupId, worktreePath)+ if (!displaced.size) return+ const fallbackCwd =+ (nodesRef.current.find((n) => n.id === groupId)?.data.cwd as string | undefined) ||+ useProjects.getState().getProject(activeProjectId ?? '')?.cwd+ if (respawn) {+ for (const n of nodesRef.current) {+ if (displaced.has(n.id) && n.type === 'terminal') transport.destroy(n.id)+ }+ }+ setNodes((ns) =>+ ns.map((n) =>+ displaced.has(n.id)+ ? {+ ...n,+ data: {+ ...n.data,+ cwd: fallbackCwd,+ ...(respawn && n.type === 'terminal'+ ? { respawnNonce: ((n.data.respawnNonce as number | undefined) ?? 0) + 1 }+ : {})+ }+ }+ : n+ )+ )+ markDirty()+ },+ [setNodes, markDirty, activeProjectId]+ )+// Confirmed removal: git FIRST, then the child terminals' tmux sessions — a git that refuses must// leave the user's running processes alone (see the numbered steps below).//@@ -2205,34 +2254,10 @@ export function Canvas() {// The respawn (nonce bump) puts the terminal straight back in the fallback cwd rather than// leaving a dead pane behind; its session was destroyed a line earlier either way.// Nodes whose cwd was NOT inside the worktree are left alone: they were never affected.- const under = descendantIds(nodesRef.current, t.groupId)- const fallbackCwd =- (nodesRef.current.find((n) => n.id === t.groupId)?.data.cwd as string | undefined) ||- useProjects.getState().getProject(activeProjectId ?? '')?.cwd- const displaced = (n: CanvasNode): boolean =>- under.has(n.id) &&- (n.type === 'terminal' || n.type === 'chat') &&- isInsideDir(n.data.cwd as string | undefined, wt.path)- for (const n of nodesRef.current) if (displaced(n) && n.type === 'terminal') transport.destroy(n.id)- setNodes((ns) =>- ns.map((n) =>- displaced(n as CanvasNode)- ? {- ...n,- data: {- ...n.data,- cwd: fallbackCwd,- ...(n.type === 'terminal'- ? { respawnNonce: ((n.data.respawnNonce as number | undefined) ?? 0) + 1 }- : {})- }- }- : n- )- )+ resetDisplacedCwd(t.groupId, wt.path, true)clearWorktreeBinding(t.groupId)setNotice({ kind: res.ok ? 'info' : 'error', text: res.message })- }, [removeTarget, deleteFromDisk, clearWorktreeBinding, setNodes, activeProjectId])+ }, [removeTarget, deleteFromDisk, clearWorktreeBinding, resetDisplacedCwd])// Confirmed merge. The push is passed explicitly: `worktreeMerge` never publishes on its own, so// what the dialog said is exactly what runs — and the result banner names the push either way.@@ -2269,6 +2294,15 @@ export function Canvas() {// directory that still exists is never touched, so a wrongly-stale group cannot delete a// live checkout.if (wt && useWorktrees.getState().staleGroupIds.includes(groupId)) {+ // Unbind is the DOCUMENTED RECOVERY PATH for a worktree deleted outside the app — the+ // only action a stale group offers — so it owes the children the same cwd reset Remove+ // gives them. Without it they keep `data.cwd = <dead worktree path>`, persisted to+ // project.json: tmux hides it (a warm reattach ignores cwd) right up until a machine+ // reboot, when the cold start spawns into the dead path, pty-manager silently falls back+ // to $HOME, and the dead path stays in the project file forever.+ // No respawn: unbind ends no process. The correction lands on the node (and on disk),+ // which is exactly where the next cold start reads it from.+ resetDisplacedCwd(groupId, wt.path, false)// AWAIT the prune before re-reconciling: `worktree list` racing an unfinished prune// still lists the pruned path, and the worktree we just cleaned up would pop back as// an orphan the dialog offers.@@ -2313,7 +2347,7 @@ export function Canvas() {break}},- [requestRemoveWorktree, clearWorktreeBinding, activeProjectId]+ [requestRemoveWorktree, clearWorktreeBinding, resetDisplacedCwd, activeProjectId])// Bridge the worktree-action handler to GroupNode (which React Flow instantiates itself).diff --git a/src/shared/worktree.test.ts b/src/shared/worktree.test.tsindex e2829cd82..18853bd76 100644--- a/src/shared/worktree.test.ts+++ b/src/shared/worktree.test.ts@@ -1,6 +1,7 @@import { describe, it, expect } from 'vitest'import {descendantIds,+ displacedByWorktree,isInsideDir,sanitizeWorktreeBranch,computeWorktreePath,@@ -220,6 +221,46 @@ describe('descendantIds', () => {})})+// The one derivation BOTH teardown paths use — Remove (which also ends the sessions) and the stale+// group's Unbind (which does not). Unbind is the documented recovery path for a worktree deleted+// outside the app, and it used to leave `data.cwd = <dead path>` on the children, persisted to+// project.json: tmux hides it (a warm reattach ignores cwd) until a machine reboot, when the cold+// start spawns into the dead path, pty-manager silently falls back to $HOME, and the dead path+// stays in the project file forever.+describe('displacedByWorktree', () => {+ const wt = '/wt/feat'+ const nodes = [+ { id: 'g', type: 'group', data: { cwd: wt } },+ { id: 'term', type: 'terminal', parentId: 'g', data: { cwd: wt } },+ { id: 'chat', type: 'chat', parentId: 'g', data: { cwd: `${wt}/src` } },+ { id: 'inner', type: 'group', parentId: 'g', data: { cwd: wt } },+ { id: 'nested', type: 'terminal', parentId: 'inner', data: { cwd: `${wt}/pkg` } },+ // In the group, but its cwd was pointed somewhere else by hand — it was never displaced.+ { id: 'elsewhere', type: 'terminal', parentId: 'g', data: { cwd: '/repo' } },+ // A sibling directory that merely shares the prefix must not be swept up.+ { id: 'prefix', type: 'terminal', parentId: 'g', data: { cwd: '/wt/feature' } },+ { id: 'nocwd', type: 'terminal', parentId: 'g', data: {} },+ { id: 'sticky', type: 'sticky', parentId: 'g', data: { cwd: wt } },+ // Same cwd, but not in the group: not this group's business.+ { id: 'stranger', type: 'terminal', data: { cwd: wt } }+ ]++ it('collects every descendant terminal and chat living in the worktree, nested ones included', () => {+ expect([...displacedByWorktree(nodes, 'g', wt)].sort()).toEqual(['chat', 'nested', 'term'])+ })++ it('leaves nodes outside the group, outside the path, or without a cwd alone', () => {+ const got = displacedByWorktree(nodes, 'g', wt)+ for (const id of ['elsewhere', 'prefix', 'nocwd', 'sticky', 'stranger', 'g', 'inner']) {+ expect(got.has(id)).toBe(false)+ }+ })++ it('displaces nothing for an empty worktree path (never sweeps the whole canvas)', () => {+ expect(displacedByWorktree(nodes, 'g', '').size).toBe(0)+ })+})+describe('isInsideDir', () => {it('matches the directory itself and anything under it', () => {expect(isInsideDir('/wt/feat', '/wt/feat')).toBe(true)diff --git a/src/shared/worktree.ts b/src/shared/worktree.tsindex fc460b226..0934db976 100644--- a/src/shared/worktree.ts+++ b/src/shared/worktree.ts@@ -191,6 +191,48 @@ export function descendantIds(return out}+/** The shape `displacedByWorktree` needs of a canvas node (structural, so the shared layer stays+ * free of React Flow types). */+interface WorktreeNodeLike {+ id: string+ type?: string+ parentId?: string+ data?: { cwd?: unknown }+}++/**+ * The nodes a worktree teardown DISPLACES: every descendant of the bound group that carries a+ * working directory (a terminal or a chat) inside the worktree path.+ *+ * BOTH teardown paths derive from this — Remove (which also ends their sessions and respawns them)+ * and a stale group's Unbind (which touches no process at all). Unbind is the documented recovery+ * path for a worktree deleted outside the app — the only action a stale group offers — and leaving+ * `data.cwd` on the dead path there is not cosmetic: it is persisted to `project.json`, tmux hides+ * it (a warm reattach ignores cwd), and the next machine reboot cold-starts the terminal into a+ * directory that no longer exists, where pty-manager silently falls back to $HOME while the dead+ * path stays in the project file forever.+ *+ * Nodes whose cwd was never inside the worktree (pointed elsewhere by hand, a sibling directory+ * that merely shares the prefix, no cwd at all) are NOT displaced — they were never affected, and+ * rewriting them would be a change the user never asked for.+ */+export function displacedByWorktree(+ nodes: readonly WorktreeNodeLike[],+ groupId: string,+ worktreePath: string+): Set<string> {+ if (!worktreePath) return new Set()+ const under = descendantIds(nodes, groupId)+ const out = new Set<string>()+ for (const n of nodes) {+ if (!under.has(n.id)) continue+ if (n.type !== 'terminal' && n.type !== 'chat') continue+ const cwd = typeof n.data?.cwd === 'string' ? n.data.cwd : undefined+ if (isInsideDir(cwd, worktreePath)) out.add(n.id)+ }+ return out+}+/** Refuse removals that would nuke the repo, home, or filesystem root. */export function isDangerousWorktreeRemovalPath(worktreePath: string, repoPath: string, homeDir: string): boolean {const wt = (worktreePath || '').replace(/\/+$/, '')