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(security): a stray Enter can no longer delete a worktree an agent asked to remove
enesd11d314a930d
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 3ce0634e1..01c63ed59 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -106,6 +106,7 @@ import {sanitizeWorktreeBranch,worktreeFromCreate,worktreeFromEntry,+ worktreeRemoveMessage,type GroupWorktree,type WorktreeCreateValue,type WorktreeEntry@@ -475,7 +476,22 @@ export function Canvas() {groupId: stringwarning: stringcanDelete: boolean+ /** Named in the dialog, so the user approves the worktree they were shown — not whichever one+ * the group happens to point at by the time they hit Enter. */+ branch: string+ path: string+ /** Set when an AGENT asked (canvas-control `close-worktree --mode remove`); the dialog says so,+ * exactly like the agent `write`/`close` confirms do. */+ requestedBy?: string} | null>(null)+ /**+ * True from the instant a removal confirm is REQUESTED until its dialog closes. `removeTarget`+ * alone cannot carry this: `requestRemoveWorktree` awaits `git.status` before opening, and two+ * rapid `close-worktree --mode remove` calls both got through that gap — the second silently+ * SWAPPED the target under an open dialog, so the user could approve the deletion of a worktree+ * they never read.+ */+ const removePendingRef = useRef(false)const [deleteFromDisk, setDeleteFromDisk] = useState(false)// Group awaiting confirmation to merge its worktree into the base branch. `hasOrigin` decides// whether the dialog offers (and warns about) the push to origin — a repo with no `origin` must@@ -534,10 +550,24 @@ export function Canvas() {* WORKTREE_SSH_HINT). Reactive, so the menus rebuild when the user switches projects. */const isSshProject = !!activeSshServernodesRef.current = nodes- // Mirror the open-confirm state into a ref so the []-dep agent-control effect can see the- // CURRENT dialog (it closes over a stale `confirm`), to reject overlapping destructive verbs.- const confirmRef = useRef(confirm)- confirmRef.current = confirm+ /**+ * ONE confirm dialog at a time — mirrored into a ref so the []-dep agent-control effect sees the+ * CURRENT dialogs (it closes over a stale `confirm`).+ *+ * This used to mirror `confirm` ONLY, which is how an agent could get a worktree deleted with an+ * Enter the user aimed elsewhere: `close-worktree --mode remove` opened the (independent)+ * `removeTarget` dialog, a following `write` saw a null `confirm` and mounted the benign "Agent+ * wants to send…" dialog ON TOP of it, and the user's Enter answered both. ConfirmDialog now only+ * answers keys while it is topmost (see components/dialog-stack), but a destructive dialog the+ * user cannot even SEE must not exist in the first place: every confirm state is in this guard.+ */+ const confirmOpenRef = useRef(false)+ confirmOpenRef.current = !!(confirm || removeTarget || moveTarget || mergeTarget || pendingPeer)+ /** Is any confirm open — or being opened (the async gap in `requestRemoveWorktree`)? */+ const confirmBusy = useCallback(+ () => confirmOpenRef.current || removePendingRef.current,+ []+ )const nodeTypes = useMemo(() => ({@@ -2565,21 +2595,50 @@ export function Canvas() {// 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.worktree- if (!wt) return- // 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- // 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 })- }, [])+ const requestRemoveWorktree = useCallback(+ async (+ groupId: string,+ opts?: { requestedBy?: string }+ ): Promise<{ ok: boolean; error?: string }> => {+ // One confirm at a time — for EVERY caller, not just the agent one. Two rapid requests used+ // to swap `removeTarget` under an open dialog (the user reads worktree A, approves the+ // deletion of worktree B), and an unrelated confirm stacked on top of this one used to make+ // it invisible while still live (see `confirmOpenRef`). Refuse instead.+ if (confirmBusy()) return { ok: false, error: 'a confirmation is already pending — try again' }+ const wt = nodesRef.current.find((n) => n.id === groupId)?.data.worktree+ if (!wt) return { ok: false, error: `${groupId} is not a worktree-bound group` }+ // Held across the `await` below: without it a second call slips through the gap before+ // `removeTarget` exists.+ removePendingRef.current = true+ try {+ // 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+ // 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,+ branch: wt.branch,+ path: wt.path,+ requestedBy: opts?.requestedBy+ })+ return { ok: true }+ } catch (e) {+ // Nothing opened → nothing is pending. Never leave the guard latched.+ removePendingRef.current = false+ return { ok: false, error: e instanceof Error ? e.message : String(e) }+ }+ },+ [confirmBusy]+ )/** 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. */@@ -2606,6 +2665,9 @@ export function Canvas() {// swallows that — the result message says whether the branch actually went.const confirmRemoveWorktree = useCallback(async () => {const t = removeTarget+ // The dialog is being answered → the "a removal confirm is open" guard is released (both exits,+ // here and the dialog's onCancel, clear it; nothing else may).+ removePendingRef.current = falseif (!t) returnconst wt = nodesRef.current.find((n) => n.id === t.groupId)?.data.worktreeif (!wt) {@@ -4000,9 +4062,16 @@ export function Canvas() {return}if (mode === 'remove') {- // Destructive → the existing ask-first safety dialog decides; reply now (once).- void ctl.requestRemoveWorktree(id)- reply({ ok: true, message: 'removal confirmation shown to the user — they decide' })+ // Destructive → the existing ask-first safety dialog decides. It REFUSES while any+ // other confirm is open (`confirmBusy`): stacking a second dialog on this one hid a+ // pre-ticked "delete from disk" behind a benign one, and the user's Enter answered+ // both. The dialog also names this agent and the branch/path it wants gone.+ const res = await ctl.requestRemoveWorktree(id, { requestedBy: srcTitle })+ reply(+ res.ok+ ? { ok: true, message: 'removal confirmation shown to the user — they decide' }+ : { ok: false, error: res.error ?? 'could not open the removal confirmation' }+ )return}reply({ ok: false, error: `close-worktree: unknown --mode ${mode} (unbind|remove)` })@@ -4055,8 +4124,11 @@ export function Canvas() {return}// One confirm dialog at a time: setConfirm would replace a pending one, orphaning its- // reply and hanging that earlier request to its 120s timeout. Reject instead.- if (confirmRef.current) {+ // reply and hanging that earlier request to its 120s timeout — and a second dialog+ // mounted on top of a destructive one (the worktree-removal confirm) turned an Enter+ // aimed at THIS harmless prompt into a deletion. `confirmBusy` covers every confirm+ // state, not just `confirm`. Reject instead.+ if (confirmBusy()) {reply({ ok: false, error: 'a confirmation is already pending — try again' })return}@@ -4086,8 +4158,9 @@ export function Canvas() {reply({ ok: false, error: 'close requires --node' })return}- // One confirm dialog at a time (see `write`): reject rather than orphan a pending one.- if (confirmRef.current) {+ // One confirm dialog at a time (see `write`): reject rather than orphan a pending one —+ // or stack this one over a destructive dialog the user then cannot see.+ if (confirmBusy()) {reply({ ok: false, error: 'a confirmation is already pending — try again' })return}@@ -5370,21 +5443,17 @@ export function Canvas() {{removeTarget && (<ConfirmDialog- message={- (removeTarget.canDelete- ? // Promise only what we will actually do. `git branch -d` REFUSES an unmerged branch- // (and we never escalate to -D), so "its branch is deleted" was a promise the op- // could not keep — the removal now reports which way it went, and the confirm says- // up front that the branch survives if it still holds unmerged work.- 'Remove this worktree? Its directory is deleted, and its branch too — unless the ' +- 'branch still has unmerged commits, in which case it is kept.'- : '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 : '')- }+ // Says WHO asked (an agent, or nobody = the user) and WHAT is destroyed (branch + path):+ // this dialog is reachable from canvas-control, and it used to be byte-identical to a+ // user-initiated removal. Pure + tested in @shared/worktree.+ message={worktreeRemoveMessage({+ branch: removeTarget.branch,+ path: removeTarget.path,+ canDelete: removeTarget.canDelete,+ deleteFromDisk,+ warning: removeTarget.warning,+ requestedBy: removeTarget.requestedBy+ })}confirmLabel={deleteFromDisk ? 'Delete' : 'Unbind'}danger={deleteFromDisk}option={@@ -5399,7 +5468,11 @@ export function Canvas() {}}onConfirm={confirmRemoveWorktree}- onCancel={() => setRemoveTarget(null)}+ onCancel={() => {+ // Both exits release the one-at-a-time guard (see `removePendingRef`).+ removePendingRef.current = false+ setRemoveTarget(null)+ }}/>)}diff --git a/src/renderer/components/ConfirmDialog.tsx b/src/renderer/components/ConfirmDialog.tsxindex dbbf9a0c7..2b7a74163 100644--- a/src/renderer/components/ConfirmDialog.tsx+++ b/src/renderer/components/ConfirmDialog.tsx@@ -1,5 +1,6 @@-import { useEffect } from 'react'+import { useEffect, useRef } from 'react'import { createPortal } from 'react-dom'+import { isTopDialog, nextDialogId, popDialog, pushDialog } from './dialog-stack'interface ConfirmDialogProps {message: string@@ -13,7 +14,11 @@ interface ConfirmDialogProps {onCancel: () => void}-/** A small themed confirm dialog. Enter confirms, Esc cancels. */+/**+ * A small themed confirm dialog. Enter confirms, Esc cancels — but ONLY while this dialog is the+ * topmost one (see ./dialog-stack): the listener is on `window`, and a dialog painted underneath+ * another must never answer a key the user aimed at the one they can see.+ */export function ConfirmDialog({message,confirmLabel = 'Delete',@@ -23,8 +28,21 @@ export function ConfirmDialog({onConfirm,onCancel}: ConfirmDialogProps) {+ // One id per instance, for the lifetime of the component (mount order == paint order == stack).+ const idRef = useRef<string>()+ if (!idRef.current) idRef.current = nextDialogId()+ const id = idRef.current++ useEffect(() => {+ pushDialog(id)+ return () => popDialog(id)+ }, [id])+useEffect(() => {const onKey = (e: KeyboardEvent) => {+ // Not the dialog on top → this key is not ours. Do not preventDefault either: the topmost+ // dialog's own listener still has to see it.+ if (!isTopDialog(id)) returnif (e.key === 'Escape') {e.preventDefault()onCancel()@@ -35,7 +53,7 @@ export function ConfirmDialog({}window.addEventListener('keydown', onKey)return () => window.removeEventListener('keydown', onKey)- }, [onConfirm, onCancel])+ }, [id, onConfirm, onCancel])return createPortal(<div className="confirm-overlay" onClick={onCancel}>diff --git a/src/renderer/components/dialog-stack.test.ts b/src/renderer/components/dialog-stack.test.tsnew file mode 100644index 000000000..7392f7de1--- /dev/null+++ b/src/renderer/components/dialog-stack.test.ts@@ -0,0 +1,70 @@+import { describe, it, expect, beforeEach } from 'vitest'+import {+ isTopDialog,+ nextDialogId,+ openDialogCount,+ popDialog,+ pushDialog,+ resetDialogStack+} from './dialog-stack'++beforeEach(() => resetDialogStack())++describe('dialog stack (which dialog owns Enter/Escape)', () => {+ it('a lone dialog owns the keyboard', () => {+ const a = nextDialogId()+ pushDialog(a)+ expect(isTopDialog(a)).toBe(true)+ })++ it('the exploit pairing: the dialog underneath does NOT answer the key', () => {+ // 1. agent: close-worktree --mode remove → the destructive dialog mounts…+ const remove = nextDialogId()+ pushDialog(remove)+ // 2. agent: write → the benign "Agent wants to send…" dialog mounts on top (portals paint in+ // mount order), hiding it.+ const send = nextDialogId()+ pushDialog(send)+ // 3. the user presses Enter at the dialog they can see. Only that one may act.+ expect(isTopDialog(send)).toBe(true)+ expect(isTopDialog(remove)).toBe(false) // ← the worktree survives+ })++ it('closing the top hands the keyboard back to the one below', () => {+ const a = nextDialogId()+ const b = nextDialogId()+ pushDialog(a)+ pushDialog(b)+ popDialog(b)+ expect(isTopDialog(a)).toBe(true)+ expect(openDialogCount()).toBe(1)+ })++ it('an out-of-order unmount keeps the remaining order intact', () => {+ const a = nextDialogId()+ const b = nextDialogId()+ const c = nextDialogId()+ pushDialog(a)+ pushDialog(b)+ pushDialog(c)+ popDialog(b) // the middle one closes first+ expect(isTopDialog(c)).toBe(true)+ popDialog(c)+ expect(isTopDialog(a)).toBe(true)+ })++ it('no dialog is top when none is open, and ids are unique', () => {+ const a = nextDialogId()+ expect(isTopDialog(a)).toBe(false)+ expect(nextDialogId()).not.toBe(nextDialogId())+ })++ it('push is idempotent (a re-registered dialog does not double-stack)', () => {+ const a = nextDialogId()+ pushDialog(a)+ pushDialog(a)+ expect(openDialogCount()).toBe(1)+ popDialog(a)+ expect(openDialogCount()).toBe(0)+ })+})diff --git a/src/renderer/components/dialog-stack.ts b/src/renderer/components/dialog-stack.tsnew file mode 100644index 000000000..419f1c735--- /dev/null+++ b/src/renderer/components/dialog-stack.ts@@ -0,0 +1,52 @@+/**+ * The open-modal stack — which dialog owns the keyboard.+ *+ * Every `ConfirmDialog` is a portal to `document.body` and listens on `window` for Enter/Escape.+ * With two of them mounted, the LATER one paints on top (portals append in mount order) while the+ * earlier one stays live and invisible underneath — and BOTH window listeners fired, so a single+ * Enter aimed at the dialog the user could actually see also answered the one they could not. That+ * was reachable purely from an agent: a `close-worktree --mode remove` (delete dialog, "delete from+ * disk" pre-ticked) immediately followed by a benign `write` (Send dialog on top) turned the user's+ * Enter on "Send" into a worktree deletion.+ *+ * Keys therefore belong to the TOP of this stack and to nothing else. Mount order is the stack+ * order, which is exactly the paint order, so "topmost" is always the dialog the user is looking at.+ *+ * Module state, not React state: the check runs inside a window keydown handler, and a dialog that+ * must decide "is this key mine?" cannot wait for a re-render to find out.+ */++const stack: string[] = []+let seq = 0++/** A fresh id for one dialog instance (kept in a ref for the life of the component). */+export function nextDialogId(): string {+ seq += 1+ return `dialog-${seq}`+}++/** Register a dialog as open (call on mount). Idempotent. */+export function pushDialog(id: string): void {+ if (!stack.includes(id)) stack.push(id)+}++/** Unregister a dialog (call on unmount). Removing a non-top id keeps the rest in order. */+export function popDialog(id: string): void {+ const i = stack.indexOf(id)+ if (i !== -1) stack.splice(i, 1)+}++/** Does this dialog own the keyboard? Only the most recently mounted one does. */+export function isTopDialog(id: string): boolean {+ return stack.length > 0 && stack[stack.length - 1] === id+}++/** How many modal dialogs are currently open (tests / diagnostics). */+export function openDialogCount(): number {+ return stack.length+}++/** Tests only: forget every registration. */+export function resetDialogStack(): void {+ stack.length = 0+}diff --git a/src/shared/worktree.test.ts b/src/shared/worktree.test.tsindex 42db22d88..903df55c0 100644--- a/src/shared/worktree.test.ts+++ b/src/shared/worktree.test.ts@@ -13,6 +13,7 @@ import {resolveBaseRef,worktreeFromCreate,worktreeFromEntry,+ worktreeRemoveMessage,DEFAULT_BASE_REF,type WorktreeEntry} from './worktree'@@ -341,3 +342,37 @@ describe('isInsideDir', () => {expect(isInsideDir('', '/wt/feat')).toBe(false)})})++describe('worktreeRemoveMessage', () => {+ const base = { branch: 'feat/x', path: '/wt/feat-x', canDelete: true, deleteFromDisk: true }++ it('names the branch and the directory that will be destroyed', () => {+ const msg = worktreeRemoveMessage(base)+ expect(msg).toContain('Branch: feat/x')+ expect(msg).toContain('Directory: /wt/feat-x')+ })++ it('attributes an agent-opened removal (it used to be identical to a user-initiated one)', () => {+ expect(worktreeRemoveMessage({ ...base, requestedBy: 'claude-1' })).toContain(+ 'Agent "claude-1" wants to remove this worktree.'+ )+ // A user-initiated removal claims no agent.+ expect(worktreeRemoveMessage(base)).not.toContain('Agent "')+ })++ it('an adopted worktree defaults to unbind, and says so; the disk opt-in is spelled out', () => {+ const adopted = { ...base, canDelete: false, deleteFromDisk: false }+ const unbind = worktreeRemoveMessage(adopted)+ expect(unbind).toContain('not created by nodeterm')+ expect(unbind).not.toContain('DELETED')+ expect(worktreeRemoveMessage({ ...adopted, deleteFromDisk: true })).toContain(+ '⚠ The worktree directory will be DELETED. Its branch is kept.'+ )+ })++ it('carries the uncommitted-work warning', () => {+ expect(worktreeRemoveMessage({ ...base, warning: '3 uncommitted file(s) in the worktree.' })).toContain(+ '⚠ 3 uncommitted file(s) in the worktree.'+ )+ })+})diff --git a/src/shared/worktree.ts b/src/shared/worktree.tsindex 94bedb404..378c3c0ba 100644--- a/src/shared/worktree.ts+++ b/src/shared/worktree.ts@@ -303,3 +303,48 @@ export function decideMergeStrategy(args: { baseCheckedOutPath: string | null; b}return { kind: 'merge-in-place', path: args.baseCheckedOutPath }}++/** What the removal confirm needs to say — WHO asked, and WHAT exactly gets destroyed. */+export interface WorktreeRemovePrompt {+ branch: string+ path: string+ /** nodeterm created the directory → deleting it is the action; otherwise Unbind is the default. */+ canDelete: boolean+ /** The live value of the "delete from disk too" box (for an adopted worktree). */+ deleteFromDisk: boolean+ /** e.g. "3 uncommitted file(s) in the worktree." */+ warning?: string+ /** Title of the AGENT that asked for this. Absent = the user asked for it themselves. */+ requestedBy?: string+}++/**+ * The removal dialog's text. Pure, so it can be read (and tested) without the canvas.+ *+ * Two things it must never omit again:+ * - ATTRIBUTION. An agent can open this dialog (canvas-control `close-worktree --mode remove`).+ * The old text was byte-identical to a user-initiated removal, so a user who never asked for it+ * had no way to tell where it came from — while `write`/`close` have always said+ * `Agent "<title>" wants to …`.+ * - THE TARGET. It named neither the branch nor the directory, so an agent could open it for one+ * worktree and the user could approve the deletion of a worktree they never looked at.+ */+export function worktreeRemoveMessage(p: WorktreeRemovePrompt): string {+ const who = p.requestedBy+ ? `Agent "${p.requestedBy}" wants to remove this worktree.\n\n`+ : ''+ const what = `Branch: ${p.branch}\nDirectory: ${p.path}\n\n`+ const body = p.canDelete+ ? // Promise only what we will actually do. `git branch -d` REFUSES an unmerged branch (and we+ // never escalate to -D), so "its branch is deleted" was a promise the op could not keep.+ 'Remove this worktree? Its directory is deleted, and its branch too — unless the branch ' ++ 'still has unmerged commits, in which case it is kept.'+ : 'This worktree was not created by nodeterm.\n\nUnbind detaches this group and leaves the ' ++ 'worktree untouched on disk.'+ const optIn =+ p.deleteFromDisk && !p.canDelete+ ? '\n\n⚠ The worktree directory will be DELETED. Its branch is kept.'+ : ''+ const warn = p.warning ? `\n\n⚠ ${p.warning}` : ''+ return `${who}${what}${body}${optIn}${warn}`+}