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.

fix(worktree): no session dies into a dead path — not on ↪, not on Remove

enesd9037ab4196d
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index ef38a0457..f0d953149 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -93,6 +93,8 @@ import { LoopNode } from '../nodes/LoopNode'
import type { NormalizedAgentEvent } from '@shared/agents/normalize'
import {
computeWorktreePath,
+ descendantIds,
+ isInsideDir,
resolveBaseRef,
sanitizeWorktreeBranch,
worktreeFromCreate,
@@ -2105,7 +2107,10 @@ export function Canvas() {
const requestRemoveWorktree = useCallback(async (groupId: string) => {
const wt = nodesRef.current.find((n) => n.id === groupId)?.data.worktree
if (!wt) return
- const status = await window.nodeTerminal.git.status(wt.path)
+ // The probe is a courtesy (it only enriches the warning), so a rejected IPC (WS-RPC transport
+ // error on the Server Edition) must not swallow the whole action: without this catch the dialog
+ // silently never opens and Remove looks broken. Fail open — ask without the dirty-file count.
+ const status = await window.nodeTerminal.git.status(wt.path).catch(() => null)
const dirtyCount = (status?.staged.length ?? 0) + (status?.changes.length ?? 0)
const warning = dirtyCount > 0 ? `${dirtyCount} uncommitted file(s) in the worktree.` : ''
// A worktree the user created outside nodeterm is not ours to delete: Unbind is the default
@@ -2167,15 +2172,47 @@ export function Canvas() {
setNotice({ kind: 'error', text: res.message })
return // sessions untouched: nothing was removed.
}
- // 3) The directory is gone — end the child terminals' tmux sessions, which are now sitting in
- // a directory that no longer exists.
- const childIds = nodesRef.current
- .filter((n) => n.parentId === t.groupId && n.type === 'terminal')
- .map((n) => n.id)
- for (const id of childIds) transport.destroy(id)
+ // 3) The directory is gone. Two things must happen to every node that was living in it —
+ // and "every node" means ALL DESCENDANTS, not just direct children (a terminal inside a
+ // nested group was missed), and chat nodes as well as terminals (a chat's cwd is just as
+ // dead):
+ // a. terminals: end the tmux session, which is now sitting in a directory that no longer
+ // exists;
+ // b. terminals AND chats: reset `data.cwd` off the deleted path. Leaving it there is the
+ // exact trap this whole task exists to remove — on the next mount the node spawns into
+ // a path that is gone, pty-manager silently falls back to $HOME, and the dead cwd is
+ // persisted forever — only reached through the SANCTIONED Remove path.
+ // 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
+ )
+ )
clearWorktreeBinding(t.groupId)
setNotice({ kind: res.ok ? 'info' : 'error', text: res.message })
- }, [removeTarget, deleteFromDisk, clearWorktreeBinding])
+ }, [removeTarget, deleteFromDisk, clearWorktreeBinding, setNodes, activeProjectId])
// 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.
@@ -2288,7 +2325,7 @@ export function Canvas() {
[cwdForNewNodeIn]
)
- const confirmMoveIntoWorktree = useCallback(() => {
+ const confirmMoveIntoWorktree = useCallback(async () => {
const id = moveTarget
setMoveTarget(null)
if (!id) return
@@ -2305,6 +2342,21 @@ export function Canvas() {
})
return
}
+ // …and staleness itself only ever arrives by POLL (a 4 s poke against a 4 s throttle, twice
+ // over — so ↪ can still be live ~8-16 s after an external `rm -rf`). Everywhere else that window
+ // is cosmetic; HERE it costs the user a running process. So probe the directory once, right
+ // before the irreversible step. This is the second (and last) sanctioned direct git read outside
+ // the worktrees store — cheap, one-shot, and only on an explicit destructive confirm.
+ const probe = await window.nodeTerminal.git.status(wtPath).catch(() => null)
+ if (!probe?.hasRepo) {
+ setNotice({
+ kind: 'error',
+ text: 'That worktree directory is missing. The terminal was left where it is.'
+ })
+ // Nudge the store (throttled, best effort) so the chip catches up with what we just saw.
+ void useWorktrees.getState().refreshStatus(wtPath, node.parentId)
+ return
+ }
// Permanently end the old tmux session (destroy, not kill) so the respawned create() opens
// a fresh session in the new cwd instead of reattaching to the existing `nt-<id>` session
// (which would keep the old working directory). The node id / persistKey is unchanged.
diff --git a/src/shared/worktree.test.ts b/src/shared/worktree.test.ts
index 4ed2fe674..e2829cd82 100644
--- a/src/shared/worktree.test.ts
+++ b/src/shared/worktree.test.ts
@@ -1,5 +1,7 @@
import { describe, it, expect } from 'vitest'
import {
+ descendantIds,
+ isInsideDir,
sanitizeWorktreeBranch,
computeWorktreePath,
parseWorktreePorcelain,
@@ -185,3 +187,50 @@ describe('decideMergeStrategy', () => {
expect(r.kind).toBe('blocked')
})
})
+
+// Removing a worktree has to reach every node that was living in its directory — a terminal inside
+// a NESTED group is in that directory just as much as a direct child, and a chat node's cwd dies
+// with it too. A one-level filter left them holding a dead cwd, which is the exact trap the
+// destructive-edges work exists to remove.
+describe('descendantIds', () => {
+ const nodes = [
+ { id: 'g' },
+ { id: 't1', parentId: 'g' },
+ { id: 'inner', parentId: 'g' },
+ { id: 't2', parentId: 'inner' }, // two levels down
+ { id: 'deep', parentId: 't2' },
+ { id: 'outside' }
+ ]
+
+ it('collects children AND grandchildren, never a node outside the group', () => {
+ expect([...descendantIds(nodes, 'g')].sort()).toEqual(['deep', 'inner', 't1', 't2'])
+ })
+
+ it('is empty for a group with no children', () => {
+ expect(descendantIds(nodes, 'outside').size).toBe(0)
+ })
+
+ it('terminates on a corrupt parent cycle instead of hanging', () => {
+ const cyclic = [
+ { id: 'a', parentId: 'g' },
+ { id: 'b', parentId: 'a' },
+ { id: 'g', parentId: 'b' } // g is its own descendant
+ ]
+ expect([...descendantIds(cyclic, 'g')].sort()).toEqual(['a', 'b', 'g'])
+ })
+})
+
+describe('isInsideDir', () => {
+ it('matches the directory itself and anything under it', () => {
+ expect(isInsideDir('/wt/feat', '/wt/feat')).toBe(true)
+ expect(isInsideDir('/wt/feat/src', '/wt/feat')).toBe(true)
+ expect(isInsideDir('/wt/feat/', '/wt/feat')).toBe(true)
+ })
+ it('does not match a sibling that merely shares a prefix', () => {
+ expect(isInsideDir('/wt/feature', '/wt/feat')).toBe(false)
+ })
+ it('is false for an unset cwd (nothing to displace)', () => {
+ expect(isInsideDir(undefined, '/wt/feat')).toBe(false)
+ expect(isInsideDir('', '/wt/feat')).toBe(false)
+ })
+})
diff --git a/src/shared/worktree.ts b/src/shared/worktree.ts
index 415d3ddbb..fc460b226 100644
--- a/src/shared/worktree.ts
+++ b/src/shared/worktree.ts
@@ -151,12 +151,46 @@ export function parseWorktreePorcelain(out: string): WorktreeEntry[] {
return entries
}
-const isAncestorPath = (parent: string, child: string): boolean => {
+/** Is `child` the directory `parent` itself, or somewhere inside it? (Trailing slashes ignored.) */
+export const isAncestorPath = (parent: string, child: string): boolean => {
const p = parent.replace(/\/+$/, '')
const c = child.replace(/\/+$/, '')
return c === p || c.startsWith(p + '/')
}
+/** `isAncestorPath` for an optional cwd: "does this node live in that directory?" */
+export const isInsideDir = (cwd: string | undefined, dir: string): boolean =>
+ !!cwd && !!dir && isAncestorPath(dir, cwd)
+
+/**
+ * Every node under `rootId` — children, grandchildren, … — not just the direct children.
+ *
+ * Worktree teardown has to reach ALL of them: a terminal inside a nested group is living in the
+ * worktree directory just as much as a direct child, and a removal that only walked one level left
+ * it holding a session (and a cwd) in a directory that no longer exists.
+ */
+export function descendantIds(
+ nodes: readonly { id: string; parentId?: string }[],
+ rootId: string
+): Set<string> {
+ const byParent = new Map<string, string[]>()
+ for (const n of nodes) {
+ if (!n.parentId) continue
+ const siblings = byParent.get(n.parentId) ?? []
+ siblings.push(n.id)
+ byParent.set(n.parentId, siblings)
+ }
+ const out = new Set<string>()
+ const stack = [...(byParent.get(rootId) ?? [])]
+ while (stack.length) {
+ const id = stack.pop() as string
+ if (out.has(id)) continue // cycle guard: a corrupt parentId chain must not hang the app
+ out.add(id)
+ stack.push(...(byParent.get(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(/\/+$/, '')