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): honest removal, merge confirm, recoverable stale bindings, no alert()
enes9fcd86b52c35
diff --git a/src/core/git-service.ts b/src/core/git-service.tsindex a0cc55f82..f774a26fd 100644--- a/src/core/git-service.ts+++ b/src/core/git-service.ts@@ -222,8 +222,8 @@ export class GitService {platform().handle(IPC.gitWorktreeMerge, (repoPath: string, branch: string, baseRef: string) =>this.worktreeMerge(repoPath, branch, baseRef))- platform().handle(IPC.gitWorktreeRemove, (repoPath: string, wtPath: string, deleteBranch: boolean) =>- this.worktreeRemove(repoPath, wtPath, deleteBranch)+ platform().handle(IPC.gitWorktreeRemove, (repoPath: string, wtPath: string, deleteBranch: boolean, pruneOnly?: boolean) =>+ this.worktreeRemove(repoPath, wtPath, deleteBranch, pruneOnly))}@@ -239,8 +239,8 @@ export class GitService {worktreeMerge(repoPath: string, branch: string, baseRef: string) {return worktreeOps.worktreeMerge(git, repoPath, branch, baseRef)}- worktreeRemove(repoPath: string, wtPath: string, deleteBranch: boolean) {- return worktreeOps.worktreeRemove(git, repoPath, wtPath, os.homedir(), deleteBranch)+ worktreeRemove(repoPath: string, wtPath: string, deleteBranch: boolean, pruneOnly = false) {+ return worktreeOps.worktreeRemove(git, repoPath, wtPath, os.homedir(), deleteBranch, pruneOnly)}async status(cwd: string): Promise<GitStatus> {diff --git a/src/preload/index.ts b/src/preload/index.tsindex 4816c0bd7..729e72b9f 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -170,8 +170,8 @@ const api: NodeTerminalApi = {ipcRenderer.invoke(IPC.gitWorktreeAdd, repoPath, wtPath, branch, baseRef, isNew),worktreeMerge: (repoPath, branch, baseRef) =>ipcRenderer.invoke(IPC.gitWorktreeMerge, repoPath, branch, baseRef),- worktreeRemove: (repoPath, wtPath, deleteBranch) =>- ipcRenderer.invoke(IPC.gitWorktreeRemove, repoPath, wtPath, deleteBranch),+ worktreeRemove: (repoPath, wtPath, deleteBranch, pruneOnly) =>+ ipcRenderer.invoke(IPC.gitWorktreeRemove, repoPath, wtPath, deleteBranch, pruneOnly),setActiveRemote: (projectId) => ipcRenderer.invoke(IPC.gitSetActiveRemote, projectId)},clipboard: {diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 5621ae9b3..7ebff6225 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -301,12 +301,13 @@ export function buildFilesApi(branch,baseRef) as ReturnType<GitApi['worktreeMerge']>,- worktreeRemove: (repoPath, wtPath, deleteBranch) =>+ worktreeRemove: (repoPath, wtPath, deleteBranch, pruneOnly) =>client.request(IPC.gitWorktreeRemove,repoPath,wtPath,- deleteBranch+ deleteBranch,+ pruneOnly) as ReturnType<GitApi['worktreeRemove']>,setActiveRemote: (projectId) =>client.request(IPC.gitSetActiveRemote, projectId) as Promise<void>diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 5f1980184..c0b82c537 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -172,6 +172,9 @@ import {const GRID = 24+/** How long a successful worktree notice stays on screen before fading itself out. */+const NOTICE_MS = 6000+// Group labels counter-scale when zoomed OUT so they stay readable/clickable from afar// (like map labels): full inverse of the zoom, capped so far-out labels don't get huge,// and never below 1 (zooming IN doesn't shrink them). Written as a CSS var once per@@ -294,6 +297,15 @@ export function Canvas() {// `nodeterm:toast` when neither the Clipboard API nor execCommand can copy — typically a// non-secure context (plain http over a LAN). It must be seen, not swallowed.const [copyError, setCopyError] = useState<string | null>(null)+ // Result of a worktree operation (merge / remove). These used to be `window.alert`s — a modal+ // that blocks the whole app to say "Merged feat into main." Shown as a strip in the existing+ // top-banner column instead; an 'info' one fades itself out, an 'error' stays until dismissed.+ const [notice, setNotice] = useState<{ kind: 'info' | 'error'; text: string } | null>(null)+ useEffect(() => {+ if (notice?.kind !== 'info') return+ const t = setTimeout(() => setNotice(null), NOTICE_MS)+ return () => clearTimeout(t)+ }, [notice])const [zoomPct, setZoomPct] = useState(100)const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)const [remotePicker, setRemotePicker] = useState<{ x: number; y: number } | null>(null)@@ -364,6 +376,10 @@ export function Canvas() {const [worktreeDialog, setWorktreeDialog] = useState<{groupId: string | nullat?: { x: number; y: number }+ /** The project the dialog was opened for. `worktreeAdd` is awaited, and a project switch in+ * the meantime would otherwise bind the new worktree to a group on ANOTHER project's canvas+ * (a different repo entirely). */+ projectId: string} | null>(null)const [worktreeBusy, setWorktreeBusy] = useState(false)const [worktreeError, setWorktreeError] = useState<string | null>(null)@@ -419,9 +435,15 @@ export function Canvas() {// Terminal node id awaiting confirmation to move into its group's worktree.const [moveTarget, setMoveTarget] = useState<string | null>(null)// Group awaiting confirmation to remove its worktree (drives the ask-first safety dialog).- const [removeTarget, setRemoveTarget] = useState<{ groupId: string; warning: string } | null>(- null- )+ // `canDelete` = nodeterm created this directory (`worktree.createdByApp`), so deleting it is+ // ours to offer as the default. For a worktree the user made outside the app and merely bound,+ // the default is Unbind and deleting from disk is an explicit opt-in (`deleteFromDisk`).+ const [removeTarget, setRemoveTarget] = useState<{+ groupId: string+ warning: string+ canDelete: boolean+ } | null>(null)+ const [deleteFromDisk, setDeleteFromDisk] = useState(false)const settings = useSettings((s) => s.settings)const viewportRef = useRef<Viewport>({ x: 0, y: 0, zoom: 1 })const nodesRef = useRef<CanvasNode[]>(nodes)@@ -1323,12 +1345,49 @@ export function Canvas() {return screenToFlowPosition({ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 })}, [screenToFlowPosition])+ /** The checkout a Source Control action refers to. The panel hands its ACTIVE SCOPE's cwd+ * (main checkout or a bound worktree) with every relative path, so the diff/agent node it opens+ * is rooted in the same checkout the panel is showing — reconstructing the project's own cwd here+ * would silently open the main checkout's file while a worktree scope is active. Falling back to+ * the project keeps callers that have no scope (none today) working.+ * SSH project: the exact `remoteCwd` (the git remote registry matches by exact string; same value+ * passed to connect) — SSH projects have no worktrees in v1, so the scope is always the project. */+ const scmCwd = useCallback(+ (scopeCwd?: string) => {+ const project = useProjects.getState().getProject(activeProjectId)+ return project?.ssh?.remoteCwd ?? scopeCwd ?? project?.cwd+ },+ [activeProjectId]+ )++ // Re-read git's facts after a mutation, so the store never lies: an adopted worktree must leave+ // the orphan list (or the dialog would offer it again and a SECOND group could bind the same+ // path) and a created one must enter `entries`. `extra` is the binding we just made — React's+ // setNodes has not committed yet, so it is merged in by hand. Fire-and-forget: `refresh` is+ // epoch-guarded and fails open.+ const refreshWorktreeStore = useCallback(+ (change?: { bind?: BoundGroup; unbound?: string }) => {+ const project = useProjects.getState().getProject(activeProjectId ?? '')+ if (!project?.cwd || project.ssh) return+ const touched = new Set([change?.bind?.groupId, change?.unbound].filter(Boolean))+ const bound: BoundGroup[] = boundGroups(nodesRef.current).filter((b) => !touched.has(b.groupId))+ if (change?.bind) bound.push(change.bind)+ void useWorktrees.getState().refresh(project.cwd, bound)+ },+ [activeProjectId]+ )+// cwd for a node being created INTO a group: prefer the group's bound worktree path,// then its default cwd, else undefined (caller falls back to the project cwd).+ // A STALE binding (the worktree directory was deleted outside the app) must never be handed out:+ // the terminal would spawn into a directory that no longer exists and fail at launch. Fall back+ // to the group's own cwd / the project instead, so the node still opens somewhere real.const cwdForNewNodeIn = useCallback((parentId: string | undefined): string | undefined => {if (!parentId) return undefinedconst parent = nodesRef.current.find((n) => n.id === parentId)- return parent?.data.worktree?.path || parent?.data.cwd || undefined+ const stale = useWorktrees.getState().staleGroupIds.includes(parentId)+ if (parent?.data.worktree && !stale) return parent.data.worktree.path+ return parent?.data.cwd || undefined}, [])// Reparent a freshly-created node into a group (parentId + extent 'parent', position made@@ -1366,10 +1425,12 @@ export function Canvas() {)/** Open a new terminal that runs a command on start (e.g. gh auth login). `cwd` lets a caller- * (Source Control) run it in the checkout it is scoped to instead of the project's own. */+ * (Source Control) run it in the checkout it is scoped to instead of the project's own — routed+ * through `scmCwd` so an SSH project's remoteCwd wins and a missing scope still falls back to the+ * project, rather than depending on the panel having pre-resolved the value. */const runInTerminal = useCallback(- (cmd: string, cwd?: string) => addTerminal(undefined, cmd, undefined, cwd),- [addTerminal]+ (cmd: string, cwd?: string) => addTerminal(undefined, cmd, undefined, scmCwd(cwd)),+ [addTerminal, scmCwd])/** Open a terminal node bound to a remote host (RemoteTransport) for a live relay connection. */@@ -1457,21 +1518,6 @@ export function Canvas() {setReveal((r) => ({ path: relPath, nonce: (r?.nonce ?? 0) + 1 }))}, [])- /** The checkout a Source Control action refers to. The panel hands its ACTIVE SCOPE's cwd- * (main checkout or a bound worktree) with every relative path, so the diff/agent node it opens- * is rooted in the same checkout the panel is showing — reconstructing the project's own cwd here- * would silently open the main checkout's file while a worktree scope is active. Falling back to- * the project keeps callers that have no scope (none today) working.- * SSH project: the exact `remoteCwd` (the git remote registry matches by exact string; same value- * passed to connect) — SSH projects have no worktrees in v1, so the scope is always the project. */- const scmCwd = useCallback(- (scopeCwd?: string) => {- const project = useProjects.getState().getProject(activeProjectId)- return project?.ssh?.remoteCwd ?? scopeCwd ?? project?.cwd- },- [activeProjectId]- )-/** Open a git diff editor node for a changed file (from Source Control). */const openDiff = useCallback((relPath: string, staged: boolean, scopeCwd?: string) => {@@ -1509,9 +1555,9 @@ export function Canvas() {createAgentNode('claude',ns.length,- // A worktree scope is local-only (SSH projects have none in v1), so the scope's cwd is- // safe to take verbatim; without one the project's own checkout stands.- scopeCwd ?? project?.cwd,+ // Same scope resolution as every other Source Control action (`scmCwd`): the panel's+ // active scope, an SSH project's remoteCwd, else the project's own checkout.+ scmCwd(scopeCwd),viewCenter(),prompt,undefined,@@ -1521,7 +1567,7 @@ export function Canvas() {])markDirty()},- [setNodes, markDirty, activeProjectId, viewCenter]+ [setNodes, markDirty, activeProjectId, viewCenter, scmCwd])/** Pick a file via the native dialog and open it as an editor node. */@@ -1809,8 +1855,12 @@ export function Canvas() {)})markDirty()+ // A deleted group takes its worktree BINDING with it while the worktree stays on disk — so+ // re-reconcile, or the orphan would not be offered again until a project switch.+ const boundGone = nodesRef.current.find((n) => set.has(n.id) && !!n.data.worktree)+ if (boundGone) refreshWorktreeStore({ unbound: boundGone.id })},- [setNodes, markDirty]+ [setNodes, markDirty, refreshWorktreeStore])// When an account is removed in Settings, patch the ACTIVE project's live nodes (the projects@@ -1920,10 +1970,14 @@ export function Canvas() {const ungroup = useCallback((groupId: string) => {+ // Dissolving the frame destroys its worktree binding (the frame IS the binding) while the+ // worktree stays on disk — re-reconcile so it is offered as an orphan right away.+ const wasBound = !!nodesRef.current.find((n) => n.id === groupId)?.data.worktreesetNodes((ns) => ungroupNodes(ns as CanvasNode[], groupId))markDirty()+ if (wasBound) refreshWorktreeStore({ unbound: groupId })},- [setNodes, markDirty]+ [setNodes, markDirty, refreshWorktreeStore])const groupHasWorktree = useCallback(@@ -1933,29 +1987,14 @@ export function Canvas() {const openWorktreeDialog = useCallback((groupId: string | null, at?: { x: number; y: number }) => {+ const projectId = useProjects.getState().activeProjectId+ if (!projectId) returnsetWorktreeError(null)- setWorktreeDialog({ groupId, at })+ setWorktreeDialog({ groupId, at, projectId })},[])- // Re-read git's facts after a mutation, so the store never lies: an adopted worktree must leave- // the orphan list (or the dialog would offer it again and a SECOND group could bind the same- // path) and a created one must enter `entries`. `extra` is the binding we just made — React's- // setNodes has not committed yet, so it is merged in by hand. Fire-and-forget: `refresh` is- // epoch-guarded and fails open.- const refreshWorktreeStore = useCallback(- (change?: { bind?: BoundGroup; unbound?: string }) => {- const project = useProjects.getState().getProject(activeProjectId ?? '')- if (!project?.cwd || project.ssh) return- const touched = new Set([change?.bind?.groupId, change?.unbound].filter(Boolean))- const bound: BoundGroup[] = boundGroups(nodesRef.current).filter((b) => !touched.has(b.groupId))- if (change?.bind) bound.push(change.bind)- void useWorktrees.getState().refresh(project.cwd, bound)- },- [activeProjectId]- )-// Bind the worktree to an EXISTING group, or create a group around a new one. A group node// carries no cwd of its own — the worktree's path is what its children inherit// (`cwdForNewNodeIn`), so the frame IS the binding.@@ -2001,6 +2040,17 @@ export function Canvas() {setWorktreeError(res.message) // inline, never window.alertreturn}+ // 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) {+ setWorktreeDialog(null)+ setNotice({+ kind: 'info',+ text: `Created worktree ${v.branch} at ${v.path}. The project changed, so no group was bound to it.`+ })+ return+ }// We created this directory, so `createdByApp` is true — Remove may delete it.attachWorktree(target, worktreeFromCreate(v))setWorktreeDialog(null)@@ -2013,34 +2063,64 @@ export function Canvas() {const target = worktreeDialogconst { repoRoot, entries } = useWorktrees.getState()if (!target || !repoRoot) return+ if (useProjects.getState().activeProjectId !== target.projectId) {+ setWorktreeDialog(null)+ return+ }// The user (or a previous Unbind) made this one — `createdByApp` is false, so Remove must// not delete it by default. The base ref is the MAIN checkout's branch, not a hardcoded// 'main' (a master/trunk repo would later merge at a ref that does not exist).const wt = worktreeFromEntry(e, repoRoot, resolveBaseRef(entries))- if (!wt) return+ if (!wt) {+ // Detached HEAD (the row is disabled, but never fail silently if it is ever reachable).+ setWorktreeError('That worktree has a detached HEAD. Check out a branch in it first.')+ return+ }attachWorktree(target, wt)setWorktreeDialog(null)},[attachWorktree, worktreeDialog])- // Ask-first worktree removal (Task 9). Gather any uncommitted-work info, then open a safety- // dialog before doing anything destructive. GitStatus has no `files` field — the dirty count- // is staged + unstaged changes.+ // Ask-first worktree removal. Gather any uncommitted-work info, then open a safety dialog+ // before doing anything destructive. GitStatus has no `files` field — the dirty count is+ // staged + unstaged changes.const requestRemoveWorktree = useCallback(async (groupId: string) => {const wt = nodesRef.current.find((n) => n.id === groupId)?.data.worktreeif (!wt) returnconst status = await window.nodeTerminal.git.status(wt.path)const dirtyCount = (status?.staged.length ?? 0) + (status?.changes.length ?? 0)const warning = dirtyCount > 0 ? `${dirtyCount} uncommitted file(s) in the worktree.` : ''- setRemoveTarget({ groupId, warning })+ // A worktree the user created outside nodeterm is not ours to delete: Unbind is the default+ // and deleting it from disk is an opt-in checkbox. One we created may be deleted (still behind+ // the confirm).+ setDeleteFromDisk(wt.createdByApp)+ setRemoveTarget({ groupId, warning, canDelete: wt.createdByApp })}, [])+ /** Clear a group's worktree binding and re-read git's facts (the worktree, if it still exists,+ * becomes an orphan the dialog can offer again). The one place a binding is dropped. */+ const clearWorktreeBinding = useCallback(+ (groupId: string) => {+ setNodes((ns) =>+ ns.map((n) => (n.id === groupId ? { ...n, data: { ...n.data, worktree: undefined } } : n))+ )+ markDirty()+ refreshWorktreeStore({ unbound: groupId })+ },+ [setNodes, markDirty, refreshWorktreeStore]+ )+// Confirmed removal: process BEFORE git. End each child terminal's tmux session first so git- // never touches a directory with live processes inside it, then remove the worktree + branch.+ // never touches a directory with live processes inside it, then act.+ //+ // What "remove" means depends on WHO created the worktree (`createdByApp`, made truthful in the+ // bind path):+ // - we created it → delete the directory AND the branch (today's behavior).+ // - the user created it → unbind only, unless they ticked "Delete from disk too"; even+ // then the BRANCH is theirs and is kept.// worktreeRemove uses `git branch -d`, which refuses to delete an unmerged branch; that failure- // is swallowed, so the worktree directory is removed, the branch is kept, and res.ok is still- // true — the binding is cleared either way (res.ok is false only if the worktree remove fails).+ // is swallowed, so the directory goes, the branch stays, and res.ok is still true.const confirmRemoveWorktree = useCallback(async () => {const t = removeTargetif (!t) return@@ -2049,52 +2129,71 @@ export function Canvas() {setRemoveTarget(null)return}+ setRemoveTarget(null)+ // Unbind-only: touch no disk at all.+ if (!deleteFromDisk) {+ clearWorktreeBinding(t.groupId)+ setNotice({ kind: 'info', text: `Unbound ${wt.branch}. The worktree is still on disk.` })+ return+ }// 1) Kill the group's terminals' sessions BEFORE git touches the directory.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)- // 2) Remove the worktree (and try to delete its branch). The branch delete uses `git -d`,- // which refuses unmerged branches; that refusal is swallowed (branch kept), so res.ok is- // false only when the worktree-directory removal itself fails.- const res = await window.nodeTerminal.git.worktreeRemove(wt.repoPath, wt.path, true)- if (!res.ok) {- window.alert(res.message)- setRemoveTarget(null)+ // 2) Remove the worktree; only delete the branch if the branch is ours (we created it).+ const res = await window.nodeTerminal.git.worktreeRemove(wt.repoPath, wt.path, wt.createdByApp)+ // 3) A failure that means "the worktree is already gone" must STILL clear the binding —+ // returning early there is exactly what turns a deleted directory into an unrecoverable+ // group (Remove keeps failing, and the dead path keeps being handed to new terminals).+ if (!res.ok && !res.worktreeGone) {+ setNotice({ kind: 'error', text: res.message })return}- // 3) Clear the binding from the group node, and re-read git: the worktree is gone from disk,- // so `entries` must drop it (a stale entry would be offered as an orphan).- setNodes((ns) =>- ns.map((n) => (n.id === t.groupId ? { ...n, data: { ...n.data, worktree: undefined } } : n))- )- setRemoveTarget(null)- markDirty()- refreshWorktreeStore({ unbound: t.groupId })- }, [removeTarget, setNodes, markDirty, refreshWorktreeStore])+ clearWorktreeBinding(t.groupId)+ setNotice({ kind: res.ok ? 'info' : 'error', text: res.message })+ }, [removeTarget, deleteFromDisk, clearWorktreeBinding])// Worktree action dispatcher for GroupNode's header chip. Structured as a switch so the// merge / remove teardown actions (Tasks 8 & 9) slot in as new cases. `unbind` forgets the// binding without touching disk; `merge` merges to base; `remove` opens the safety dialog.const onWorktreeAction = useCallback(- async (groupId: string, action: 'merge' | 'remove' | 'unbind') => {+ (groupId: string, action: 'merge' | 'remove' | 'unbind') => {switch (action) {- case 'unbind':- setNodes((ns) =>- ns.map((n) =>- n.id === groupId ? { ...n, data: { ...n.data, worktree: undefined } } : n- )- )- markDirty()+ case 'unbind': {+ const wt = nodesRef.current.find((n) => n.id === groupId)?.data.worktree+ // A STALE binding (directory deleted behind git's back) is still REGISTERED in git, so a+ // later `worktree add` at the same path fails with git's raw "missing but already+ // registered worktree". Prune that registration on the way out. `pruneOnly` guarantees a+ // directory that still exists is never touched, so a wrongly-stale group cannot delete a+ // live checkout.+ if (wt && useWorktrees.getState().staleGroupIds.includes(groupId)) {+ void window.nodeTerminal.git.worktreeRemove(wt.repoPath, wt.path, false, true)+ }// The worktree is now an ORPHAN (it stays on disk) — re-reconcile so the dialog offers// it again instead of waiting for a project switch.- refreshWorktreeStore({ unbound: groupId })+ clearWorktreeBinding(groupId)break+ }case 'merge': {const wt = nodesRef.current.find((n) => n.id === groupId)?.data.worktreeif (!wt) return- const res = await window.nodeTerminal.git.worktreeMerge(wt.repoPath, wt.branch, wt.baseRef)- window.alert(res.message) // success or the blocked/conflict reason+ // NEVER merge on a single click of a small header button: `worktreeMerge` merges into the+ // base checkout when that base is checked out somewhere — i.e. straight into the user's+ // main working tree. Ask first, and say so.+ setConfirm({+ message:+ `Merge ${wt.branch} into ${wt.baseRef}?\n\n` ++ `If ${wt.baseRef} is checked out somewhere, this merges into that working tree.`,+ confirmLabel: 'Merge',+ danger: false,+ onConfirm: () => {+ setConfirm(null)+ void window.nodeTerminal.git+ .worktreeMerge(wt.repoPath, wt.branch, wt.baseRef)+ .then((res) => setNotice({ kind: res.ok ? 'info' : 'error', text: res.message }))+ }+ })break}case 'remove':@@ -2104,7 +2203,7 @@ export function Canvas() {break}},- [setNodes, markDirty, requestRemoveWorktree, refreshWorktreeStore]+ [requestRemoveWorktree, clearWorktreeBinding])// Bridge the worktree-action handler to GroupNode (which React Flow instantiates itself).@@ -4018,6 +4117,25 @@ export function Canvas() {</button></div>)}+ {notice && (+ <div+ className={`announce-banner announce-banner--${+ notice.kind === 'error' ? 'warning' : 'success'+ }`}+ >+ <span className="announce-banner__dot" />+ <div className="announce-banner__content">+ <span className="announce-banner__body">{notice.text}</span>+ </div>+ <button+ className="announce-banner__close"+ title="Dismiss"+ onClick={() => setNotice(null)}+ >+ ✕+ </button>+ </div>+ )}{conflict && (<ConflictBaronReload={() => {@@ -4376,11 +4494,29 @@ export function Canvas() {{removeTarget && (<ConfirmDialog- message={`Remove this worktree and delete its branch?${- removeTarget.warning ? '\n\n⚠ ' + removeTarget.warning : ''- }`}- confirmLabel="Remove"- danger+ message={+ (removeTarget.canDelete+ ? 'Remove this worktree? Its directory and branch are deleted.'+ : 'This worktree was not created by nodeterm.\n\nUnbind detaches this group and ' ++ 'leaves the worktree untouched on disk.') ++ (deleteFromDisk && !removeTarget.canDelete+ ? '\n\n⚠ The worktree directory will be DELETED. Its branch is kept.'+ : '') ++ (removeTarget.warning ? '\n\n⚠ ' + removeTarget.warning : '')+ }+ confirmLabel={deleteFromDisk ? 'Delete' : 'Unbind'}+ danger={deleteFromDisk}+ option={+ // We created it → deletion is the point of the action, no opt-in to make. The user+ // created it → deleting from disk is a deliberate extra choice, never the default.+ removeTarget.canDelete+ ? undefined+ : {+ label: 'Delete the worktree directory from disk too',+ checked: deleteFromDisk,+ onChange: setDeleteFromDisk+ }+ }onConfirm={confirmRemoveWorktree}onCancel={() => setRemoveTarget(null)}/>diff --git a/src/renderer/components/ConfirmDialog.tsx b/src/renderer/components/ConfirmDialog.tsxindex 5bba9449e..dbbf9a0c7 100644--- a/src/renderer/components/ConfirmDialog.tsx+++ b/src/renderer/components/ConfirmDialog.tsx@@ -6,6 +6,9 @@ interface ConfirmDialogProps {confirmLabel?: stringcancelLabel?: stringdanger?: boolean+ /** An explicit opt-in shown above the buttons (e.g. "Delete the worktree directory from disk+ * too"). The caller owns the value, so it can also swap the confirm label / danger styling. */+ option?: { label: string; checked: boolean; onChange: (checked: boolean) => void }onConfirm: () => voidonCancel: () => void}@@ -16,6 +19,7 @@ export function ConfirmDialog({confirmLabel = 'Delete',cancelLabel = 'Cancel',danger = true,+ option,onConfirm,onCancel}: ConfirmDialogProps) {@@ -37,6 +41,16 @@ export function ConfirmDialog({<div className="confirm-overlay" onClick={onCancel}><div className="confirm" onClick={(e) => e.stopPropagation()}><p className="confirm__msg">{message}</p>+ {option && (+ <label className="confirm__option">+ <input+ type="checkbox"+ checked={option.checked}+ onChange={(e) => option.onChange(e.target.checked)}+ />+ {option.label}+ </label>+ )}<div className="confirm__actions"><button className="confirm__btn" onClick={onCancel}>{cancelLabel}diff --git a/src/renderer/components/WorktreeDialog.tsx b/src/renderer/components/WorktreeDialog.tsxindex f2ef97393..fced4600c 100644--- a/src/renderer/components/WorktreeDialog.tsx+++ b/src/renderer/components/WorktreeDialog.tsx@@ -64,8 +64,10 @@ export function WorktreeDialog({}, [onCancel])// No writable base dir is known, so we refuse to *suggest* a path — an empty base would- // otherwise propose `/worktrees/…` at the filesystem root. The user can still type one.- const pathUnknown = !pathEdited && !path.trim()+ // otherwise propose `/worktrees/…` at the filesystem root. The user can still type one. The hint+ // tracks the FIELD, not `pathEdited`: clearing the box after editing it also leaves Create+ // disabled, and a disabled button with no explanation is a dead end.+ const pathUnknown = !path.trim()const valid = !!repoPath.trim() && !!branch.trim() && !!path.trim() && !busyconst title = intent === 'bind' ? 'Bind to worktree' : 'New worktree'const createLabel = intent === 'bind' ? 'Create & bind' : 'Create'@@ -83,14 +85,23 @@ export function WorktreeDialog({<div className="bind-existing"><div className="bind-existing__title">Existing worktrees</div>{existing.map((e) => (+ // A detached-HEAD worktree cannot be bound (there is no branch to merge or name the+ // group after), so the row is DISABLED and says why — clicking it used to be a+ // silent no-op.<buttonkey={e.path}className="bind-existing__row"- disabled={busy}+ disabled={busy || !e.branch}onClick={() => onBindExisting(e)}- title={e.path}+ title={+ e.branch+ ? e.path+ : `${e.path}\nDetached HEAD — check out a branch in this worktree first.`+ }>- <span className="bind-existing__branch">⎇ {e.branch ?? '(detached)'}</span>+ <span className="bind-existing__branch">+ {e.branch ? `⎇ ${e.branch}` : '⎇ (detached HEAD — check out a branch first)'}+ </span><span className="bind-existing__path">{e.path}</span></button>))}diff --git a/src/renderer/nodes/GroupNode.tsx b/src/renderer/nodes/GroupNode.tsxindex db9e988fb..a9ed12ec6 100644--- a/src/renderer/nodes/GroupNode.tsx+++ b/src/renderer/nodes/GroupNode.tsx@@ -40,17 +40,41 @@ export function GroupNode({ id, data, selected }: NodeProps<CanvasNode>) {// when the node last happened to render (verified — it sat at "0 changed" until the canvas was// clicked). Hence a tick. It owns no cache and no `git status` of its own: it just pokes the// store, whose throttle still decides whether a real read happens (so N frames don't mean N- // reads, and a mid-window render still coalesces). A stale worktree has no directory left to- // stat, so it isn't polled.+ // reads, and a mid-window render still coalesces).+ //+ // A STALE worktree is polled too (that is how a group un-stales when the directory comes back —+ // e.g. the user restored it, or a git read failed transiently), and the poke carries the group id+ // so the store can flip staleness live instead of only at project load.+ //+ // `git status` is the full Source-Control read (~10 git subprocesses), so it is gated on page+ // visibility: a hidden tab / minimized window polls nothing, and a `visibilitychange` back to+ // visible pokes immediately so the chip is correct the moment it is seen again. (Gating here+ // rather than hoisting a single store-owned timer keeps the poll tied to the node's own+ // mount/unmount lifecycle — no registry to leak — and the store's throttle already coalesces+ // several groups on the same path.)useEffect(() => {- if (!wtPath || stale) return- const poke = () => void useWorktrees.getState().refreshStatus(wtPath)+ if (!wtPath) return+ const poke = (): void => {+ if (document.visibilityState === 'hidden') return+ void useWorktrees.getState().refreshStatus(wtPath, id)+ }poke()const t = setInterval(poke, WORKTREE_STATUS_THROTTLE_MS)- return () => clearInterval(t)- }, [wtPath, stale])+ document.addEventListener('visibilitychange', poke)+ return () => {+ clearInterval(t)+ document.removeEventListener('visibilitychange', poke)+ }+ }, [wtPath, id])- const ungroup = () => setNodes((ns) => ungroupNodes(ns as CanvasNode[], id))+ // Dissolving the frame destroys the worktree binding (the frame IS the binding) while the+ // worktree itself stays on disk. Route that through Canvas's `unbind` first, so the store+ // re-reconciles (the worktree is offered as an orphan again, and a stale registration is+ // pruned) instead of the binding silently vanishing until the next project switch.+ const ungroup = (): void => {+ if (wt) worktreeActionHandler?.(id, 'unbind')+ setNodes((ns) => ungroupNodes(ns as CanvasNode[], id))+ }// A bound frame must read as a checkout at a glance: solid border + a stronger tint of the// group's OWN color (no new palette). Stale drops the hue entirely and goes muted/warning.@@ -156,7 +180,11 @@ export function GroupNode({ id, data, selected }: NodeProps<CanvasNode>) {)}<buttonclassName="group-node__wt-btn"- title="Unbind worktree (keeps the worktree on disk)"+ title={+ stale+ ? 'Unbind (the directory is gone — also prunes the stale git registration)'+ : 'Unbind worktree (keeps the worktree on disk)'+ }onClick={() => worktreeActionHandler?.(id, 'unbind')}>Unbinddiff --git a/src/renderer/state/worktrees.test.ts b/src/renderer/state/worktrees.test.tsindex a92b87e5d..b9e77c020 100644--- a/src/renderer/state/worktrees.test.ts+++ b/src/renderer/state/worktrees.test.ts@@ -186,6 +186,41 @@ describe('useWorktrees.refreshStatus', () => {expect(useWorktrees.getState().statusByPath['/wt/gone']).toBeUndefined()})+ // `refresh()` only runs on project load / mutation, so without this the chip of a worktree+ // deleted WHILE THE USER WATCHES would keep claiming to be healthy until a reload.+ it('marks the group stale when its worktree stops being a repo', async () => {+ gitMock.status.mockResolvedValue(okStatus({ hasRepo: false, branch: '' }))++ await useWorktrees.getState().refreshStatus('/wt/gone', 'group-1')++ expect(useWorktrees.getState().staleGroupIds).toEqual(['group-1'])+ })++ it('un-marks a stale group once its worktree answers again', async () => {+ const t0 = 1_700_000_000_000+ vi.useFakeTimers()+ vi.setSystemTime(t0)+ gitMock.status.mockResolvedValue(okStatus({ hasRepo: false, branch: '' }))+ await useWorktrees.getState().refreshStatus('/wt/feat', 'group-1')+ expect(useWorktrees.getState().staleGroupIds).toEqual(['group-1'])++ // Restored (or the previous read failed transiently) — past the throttle window.+ vi.setSystemTime(t0 + WORKTREE_STATUS_THROTTLE_MS + 1)+ gitMock.status.mockResolvedValue(okStatus())+ await useWorktrees.getState().refreshStatus('/wt/feat', 'group-1')++ expect(useWorktrees.getState().staleGroupIds).toEqual([])+ expect(useWorktrees.getState().statusByPath['/wt/feat'].branch).toBe('feat')+ })++ it('leaves staleness alone when no group id is given', async () => {+ gitMock.status.mockResolvedValue(okStatus({ hasRepo: false, branch: '' }))++ await useWorktrees.getState().refreshStatus('/wt/gone')++ expect(useWorktrees.getState().staleGroupIds).toEqual([])+ })+// Callers fire this from React effects; over the Server Edition's WS-RPC bridge a transport// error REJECTS, which would become an unhandled rejection.it('swallows an IPC rejection and leaves the previous status intact', async () => {diff --git a/src/renderer/state/worktrees.ts b/src/renderer/state/worktrees.tsindex 87b4b8494..c32b2bf7e 100644--- a/src/renderer/state/worktrees.ts+++ b/src/renderer/state/worktrees.ts@@ -24,7 +24,14 @@ interface WorktreesState {staleGroupIds: string[]statusByPath: Record<string, WorktreeStatus>refresh(projectCwd: string, bound: BoundGroup[]): Promise<void>- refreshStatus(path: string): Promise<void>+ /**+ * Poll one bound worktree's status. Pass the bound group's id to also keep its staleness LIVE:+ * `refresh()` only runs on project load / mutation, so without this a worktree deleted while the+ * user watches would keep a healthy-looking chip (and a restored one would keep saying "missing")+ * until a reload. `hasRepo === false` = the directory is gone → mark the group stale; a repo+ * answering again un-marks it.+ */+ refreshStatus(path: string, groupId?: string): Promise<void>reset(): void}@@ -90,7 +97,7 @@ export const useWorktrees = create<WorktreesState>((set) => ({}},- async refreshStatus(path) {+ async refreshStatus(path, groupId) {const mineEpoch = epochconst now = Date.now()const prev = lastStatusAt.get(path) ?? 0@@ -107,9 +114,23 @@ export const useWorktrees = create<WorktreesState>((set) => ({if (mineEpoch !== epoch) return// A deleted worktree does NOT reject: git-service answers with an empty status. Writing it// would render a dead worktree as a healthy one on a blank branch — `staleGroupIds` is what- // tells that story, so keep the last known status instead.- if (!status.hasRepo) return+ // tells that story, so mark the group stale instead of keeping a lie on screen.+ if (!status.hasRepo) {+ if (groupId) {+ set((s) =>+ s.staleGroupIds.includes(groupId)+ ? s+ : { staleGroupIds: [...s.staleGroupIds, groupId] }+ )+ }+ return+ }set((s) => ({+ // The directory answers again (restored, or a transient read failure passed) → not stale.+ staleGroupIds:+ groupId && s.staleGroupIds.includes(groupId)+ ? s.staleGroupIds.filter((g) => g !== groupId)+ : s.staleGroupIds,statusByPath: {...s.statusByPath,[path]: {diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex babc26632..eda6fcffb 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -3324,6 +3324,17 @@ body,color: var(--text);}+/* Explicit opt-in inside a confirm dialog (e.g. "also delete the directory from disk"). */+.confirm__option {+ display: flex;+ align-items: center;+ gap: 8px;+ margin: -6px 0 14px;+ font-size: 12.5px;+ color: var(--label-secondary, rgba(255, 255, 255, 0.55));+ cursor: pointer;+}+.confirm__input {width: 100%;box-sizing: border-box;diff --git a/src/shared/types.ts b/src/shared/types.tsindex 5b28463ff..4c49d97d1 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -533,6 +533,9 @@ export interface GitStatus {export interface GitResult {ok: booleanmessage: string+ /** worktreeRemove() only: the worktree is no longer on disk (registration pruned, or never+ * registered), so the caller must clear its binding even when `ok` is false. */+ worktreeGone?: boolean/** Set by publish() when no usable GitHub credential was found, so the UI can* fall back to an interactive `gh auth login` instead of just showing an error. */needsAuth?: boolean@@ -605,7 +608,9 @@ export interface GitApi {worktreeList(repoPath: string): Promise<import('./worktree').WorktreeEntry[]>worktreeAdd(repoPath: string, wtPath: string, branch: string, baseRef: string, isNew: boolean): Promise<GitResult>worktreeMerge(repoPath: string, branch: string, baseRef: string): Promise<GitResult>- worktreeRemove(repoPath: string, wtPath: string, deleteBranch: boolean): Promise<GitResult>+ /** `pruneOnly`: clean up git's registration only — never delete a directory. Used to prune a+ * stale binding whose worktree was already deleted outside the app. */+ worktreeRemove(repoPath: string, wtPath: string, deleteBranch: boolean, pruneOnly?: boolean): Promise<GitResult>/** Scope remote git routing to the active project: pass its id to route git over that SSH* project's master, or null for a local project so all git ops run locally. */setActiveRemote(projectId: string | null): Promise<void>diff --git a/src/shared/worktree-ops.test.ts b/src/shared/worktree-ops.test.tsindex 94b113866..eb5455c9f 100644--- a/src/shared/worktree-ops.test.ts+++ b/src/shared/worktree-ops.test.ts@@ -70,6 +70,19 @@ describe('worktreeMerge', () => {const r = await worktreeMerge(git, '/repo', 'feature/x', 'main')expect(r.ok).toBe(false)})+ it('sends the user to the base checkout on an in-place merge conflict, not the worktree', async () => {+ // The base branch IS checked out and clean → merge-in-place → the conflict is in the BASE dir.+ const list = 'worktree /base\nHEAD aaa\nbranch refs/heads/main\n'+ const { git } = fakeGit({+ 'worktree list --porcelain': ok(list),+ 'status --porcelain': ok(''),+ 'merge --no-ff --no-edit feature/x': ko('CONFLICT (content): Merge conflict in a.ts')+ })+ const r = await worktreeMerge(git, '/repo', 'feature/x', 'main')+ expect(r.ok).toBe(false)+ expect(r.message).toContain('/base')+ expect(r.message).not.toContain('worktree terminal')+ })})describe('worktreeRemove', () => {@@ -99,4 +112,40 @@ describe('worktreeRemove', () => {expect(calls.some((c) => c.join(' ') === 'worktree prune')).toBe(true)expect(calls.some((c) => c.join(' ') === 'branch -d feature/x')).toBe(true)})+ it('keeps the branch when the caller does not own it', async () => {+ const list = 'worktree /repo\nbranch refs/heads/main\n\nworktree /wt/x\nbranch refs/heads/feature/x\n'+ const { git, calls } = fakeGit({ 'worktree list --porcelain': ok(list) })+ const r = await worktreeRemove(git, '/repo', '/wt/x', '/home', false)+ expect(r.ok).toBe(true)+ expect(calls.some((c) => c[0] === 'branch')).toBe(false)+ })+ it('prunes (and never removes) a worktree whose directory is already gone', async () => {+ const list =+ 'worktree /repo\nbranch refs/heads/main\n\nworktree /wt/x\nbranch refs/heads/feature/x\nprunable gitdir file points to non-existent location\n'+ const { git, calls } = fakeGit({ 'worktree list --porcelain': ok(list) })+ const r = await worktreeRemove(git, '/repo', '/wt/x', '/home', true)+ expect(r.ok).toBe(true)+ expect(r.worktreeGone).toBe(true)+ expect(calls.some((c) => c[1] === 'remove')).toBe(false)+ expect(calls.some((c) => c.join(' ') === 'worktree prune')).toBe(true)+ })+ it('reports an unregistered worktree as gone (and prunes) so the caller can clear the binding', async () => {+ const { git, calls } = fakeGit({+ 'worktree list --porcelain': ok('worktree /repo\nbranch refs/heads/main\n')+ })+ const r = await worktreeRemove(git, '/repo', '/wt/ghost', '/home', false)+ expect(r.ok).toBe(false)+ expect(r.worktreeGone).toBe(true)+ expect(calls.some((c) => c.join(' ') === 'worktree prune')).toBe(true)+ expect(calls.some((c) => c[1] === 'remove')).toBe(false)+ })+ it('pruneOnly never touches a worktree directory that still exists', async () => {+ const list = 'worktree /repo\nbranch refs/heads/main\n\nworktree /wt/x\nbranch refs/heads/feature/x\n'+ const { git, calls } = fakeGit({ 'worktree list --porcelain': ok(list) })+ const r = await worktreeRemove(git, '/repo', '/wt/x', '/home', true, true)+ expect(r.ok).toBe(false)+ expect(calls.some((c) => c[1] === 'remove')).toBe(false)+ expect(calls.some((c) => c[0] === 'branch')).toBe(false)+ expect(calls.some((c) => c.join(' ') === 'worktree prune')).toBe(false)+ })})diff --git a/src/shared/worktree-ops.ts b/src/shared/worktree-ops.tsindex dbbae9498..f39dc6f9d 100644--- a/src/shared/worktree-ops.ts+++ b/src/shared/worktree-ops.ts@@ -11,7 +11,17 @@ export interface GitExec { ok: boolean; out: string; err: string }/** Injected git runner: runs `git <args>` in `cwd`. */export type GitExecutor = (cwd: string, args: string[]) => Promise<GitExec>/** Renderer-facing result (structurally a `GitResult`). */-export interface WorktreeOpResult { ok: boolean; message: string }+export interface WorktreeOpResult {+ ok: boolean+ message: string+ /**+ * `worktreeRemove` only: the worktree is no longer on disk (its registration was pruned, or it+ * was never registered). The caller MUST clear its binding even when `ok` is false — otherwise a+ * group whose directory was deleted behind git's back can never be cleaned up: removal keeps+ * failing and the dead path keeps being handed to new terminals.+ */+ worktreeGone?: boolean+}export async function repoRoot(git: GitExecutor, cwd: string): Promise<string | null> {if (!cwd) return null@@ -65,7 +75,12 @@ export async function worktreeMerge(const r = await git(plan.path, ['merge', '--no-ff', '--no-edit', branch])if (!r.ok) {await git(plan.path, ['merge', '--abort'])- return { ok: false, message: 'Merge conflict. Resolve it in the worktree terminal.' }+ // The merge ran in the BASE checkout, so that is where the conflict is — sending the user to+ // the worktree terminal (as this message used to) points at the wrong directory entirely.+ return {+ ok: false,+ message: `Merge conflict in the base checkout (${plan.path}). Resolve it there, then try again.`+ }}}// Best-effort push if a remote exists; ignore failure (offline / no remote).@@ -74,8 +89,18 @@ export async function worktreeMerge(return { ok: true, message: `Merged ${branch} into ${baseRef}.` }}+/**+ * Remove a worktree (and optionally its branch).+ *+ * `pruneOnly` = clean up git's REGISTRATION only, never the filesystem. It is what a stale binding+ * (directory deleted behind git's back) needs: without a prune, git keeps listing the path and a+ * later `git worktree add` at the same place fails with "missing but already registered worktree".+ * A directory that still exists is left completely alone in that mode — a wrongly-stale group must+ * never be able to delete a live checkout.+ */export async function worktreeRemove(- git: GitExecutor, repoPath: string, wtPath: string, homeDir: string, deleteBranch: boolean+ git: GitExecutor, repoPath: string, wtPath: string, homeDir: string, deleteBranch: boolean,+ pruneOnly = false): Promise<WorktreeOpResult> {// Reject a path that could be parsed as an option flag (argv injection).if (!wtPath || wtPath.startsWith('-')) return { ok: false, message: 'Invalid worktree path.' }@@ -84,8 +109,30 @@ export async function worktreeRemove(}const list = await worktreeList(git, repoPath)const entry = list.find((e) => e.path.replace(/\/+$/, '') === wtPath.replace(/\/+$/, ''))- if (!entry) return { ok: false, message: 'Worktree is not registered.' }+ if (!entry) {+ // Nothing to remove: git does not know this path (deleted + already pruned, or never a+ // worktree of this repo). Prune anyway — a leftover registration elsewhere would block a+ // future `worktree add` — and tell the caller the worktree is gone so it clears its binding.+ if (!pruneOnly) await git(repoPath, ['worktree', 'prune'])+ return { ok: false, worktreeGone: true, message: 'Worktree is not registered — it is already gone.' }+ }const branch = entry.branch+ if (entry.prunable) {+ // git still lists it, but the directory is gone. `worktree remove` would fail; prune the+ // registration instead and touch no files.+ await git(repoPath, ['worktree', 'prune'])+ if (!pruneOnly && deleteBranch && branch && isValidGitRef(branch)) {+ await git(repoPath, ['branch', '-d', branch])+ }+ return {+ ok: true,+ worktreeGone: true,+ message: 'The worktree directory was already gone; its registration was pruned.'+ }+ }+ if (pruneOnly) {+ return { ok: false, message: 'The worktree directory still exists; nothing was pruned.' }+ }// `--` ends option parsing so wtPath can never be read as a flag (verified git ≥2.39).const rm = await git(repoPath, ['worktree', 'remove', '--force', '--', wtPath])if (!rm.ok) return { ok: false, message: rm.err }