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.

feat(canvas-control): waivable destructive confirms, bulk close, self-expiring dialogs

enes630a471ff7f7
diff --git a/CLAUDE.md b/CLAUDE.md
index ffa1b3628..88145206c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1981,6 +1981,74 @@ else, and its context links must keep classifying across restarts).
(unlike with `--project`, where the ids would live in another project) against the serialized
nodes, defaults come from the OWNING project (`projectPermissionMode(owner, …)`, its account,
its `ssh`), and `--after`'s dep ropes are left to `missingDepRopes` at that project's next load.
+ **The destructive confirm, and who may waive it** (`@shared/control-confirm`, 2026-09). The
+ dialog `write` / `close` / `open-project` raise is the ONLY place a human stands between a
+ canvas-control agent and the workspace — per-node identity is not enforced until
+ `NODE_IDENTITY_STRICT_AFTER`, so a `legacy` caller still reaches the dispatch — and it used to
+ ask EVERY time with no way to say "yes, all of them". Closing 14 finished stations was 14
+ dialogs, and the 15th request was refused with `a confirmation is already pending`. Three things
+ changed, and the last one was the actual bug:
+ - **`close --node a,b,c` is ONE dialog** (`lib/closeTargets.ts`, pure). The grammar is not new —
+ the Server Edition's headless `close` has read a comma list since it shipped, including its
+ "validate the whole list before killing anything" rule; the DESKTOP dispatch read the flag as
+ one id, so a comma list called `deleteNodes(['a,b,c'])` (a no-op) and answered `closed a,b,c`.
+ A destructive verb reporting success for work it did not do is worse than either doing or
+ refusing it. The single-id form is bit-identical, **deliberately including its lack of an
+ existence check**; the bulk form refuses the WHOLE list on an unknown id and names it, because
+ with 14 ids the user cannot audit the list themselves. Capped at `CLOSE_BULK_MAX` (50) and the
+ dialog spells out at most 12 names then counts the rest — a name the user cannot see is not
+ consent.
+ - **"Don't ask again" is bounded by the app's lifetime, and the permanent version is not
+ reachable from the dialog.** The checkbox grants a waiver in the transient
+ `state/controlConfirm.ts` (memory only — not `settings.json`, not `localStorage`), per VERB, so
+ quitting restores the gate; the PERMANENT waiver exists only in Settings → Agents, where the
+ option says "permanently". A dialog that appeared under the user's hands must not be able to
+ switch a destructive gate off forever on one stray click, and a waiver granted by a CANCEL must
+ not exist at all (the grant hangs off `onConfirm`, pinned by `control-destructive.test.ts`).
+ Waiving is not silence: every waived application raises the info strip through `waivedNotice`,
+ which names the waiver that let it through and points at Settings.
+ - **`bypassPermissions` needs TWO locks, and this is the trap to understand before touching it.**
+ The permission mode is persisted to `.nodeterm/project.json`, which is **git-shared** — so
+ keying the waiver on the mode alone would let a repository the user CLONED silently disable
+ their destructive-action gate. It therefore requires a machine-local opt-in
+ (`controlConfirmWaivers.bypassMode`, default off) **and** a mode that came from the user's own
+ GLOBAL setting: `resolvePermissionModeWithSource` answers `project | global | default`, and
+ only `global` can waive. `default` is its own answer rather than folded into `global` because
+ nobody chose it, and reading an unset setting as a deliberate choice is reading consent into
+ silence. The claude version gate is deliberately NOT applied here (it exists to degrade `auto`
+ for an old CLI; a security decision must not hang on a `claude --version` probe).
+ - **`open-project` can never be waived**, by table (`CONFIRM_WAIVABLE_VERBS`) rather than by a
+ line somebody forgot at one of three call sites. It widens the app's blast radius (a new
+ directory registered as a project, plus a grant the caller feeds to `--project`) instead of
+ acting inside it, and it cannot produce the dialog storm the waiver exists to end —
+ `recordAttachConsent` already dedupes it per (caller, project).
+ **An agent-requested dialog knows its own request's lifetime** (`ConfirmState.expiresAt` /
+ `onExpire`, `CONTROL_REQUEST_TIMEOUT_MS` now shared with main). Main abandons a control request
+ after 120 s and tells the renderer NOTHING, so the dialog stayed on screen asking about work
+ nobody was waiting for — and, worse, kept `confirmBusy()` true, which refused every later
+ `write`/`close` with `a confirmation is already pending — try again` for the rest of the app run.
+ **That is the "the same dialog keeps coming back" report**, and it is a single-canvas loop: the
+ reply says retryable, the agent retries, every retry is refused by the orphan, and the moment the
+ user finally answers it a queued retry raises a fresh dialog for the same node. The deadline is
+ measured from the RENDERER's receipt, so it always fires a hair AFTER main gave up, never before
+ (the other direction would abandon a dialog whose answer main would still accept); it replies
+ `expired` rather than `denied by user` (nobody denied anything, and a reply main has already
+ timed out is simply dropped); and the notice is a fading info strip, because raising an alert
+ would keep `confirmBusy()` true — i.e. reproduce the bug with better wording. `close-worktree
+ --mode remove`'s dialog is deliberately outside this: it replies to the CLI immediately
+ ("the user decides") so there is no pending request to expire — its own `confirmBusy` hold is a
+ separate, still-open gap.
+ **MEASURED, and the answer is no: two canvases cannot raise two dialogs for one request.** The
+ suspicion was worth checking because the same project can be open on a desktop and in a Server
+ Edition browser at once. Desktop main forwards each request to `getMainWindow()` — one
+ BrowserWindow, so at most one dialog exists per request; the Server Edition raises none at all
+ (its control is HEADLESS — `HeadlessNodeFactory.close` is gated by verified identity plus
+ process-local creator ownership, and the browser bridge's `onAgentControl` is `noopUnsub`); and
+ the shim's endpoint failover cannot duplicate a request either, because the control POST carries
+ **no `--max-time`**, so a POST waiting on a human eventually gets an HTTP answer and
+ `nt_reached()` is true — failover fires only on a dead transport (`000`/empty). If a future change
+ gives that curl a timeout, this paragraph stops being true: a confirm-gated verb would then fail
+ over mid-wait and a second instance WOULD open a second dialog for the same logical request.
**Grouping verbs** (`group` / `ungroup` / `move` / `arrange` / `align`): `group` wraps **sibling**
objects — nodes or frames — into a new frame in their shared container (a mixed-container set, or
an ancestor plus its descendant, is refused with that reason); `ungroup --group <id>` dissolves a
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d2fbb0374..734e290d9 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -97,6 +97,33 @@ lane unaffected.
PR; copy that really is macOS-specific (the ptmx-limit banner, the notch step) is exempt by name
with its reason. Comments are not scanned.
+- **Every loosening of a security gate must be a SETTING the user can see and revoke.** A "don't
+ ask again" that lives only in a dialog is a permission granted once and never findable again. The
+ canvas-control destructive confirm is the pattern to copy (`@shared/control-confirm`): the dialog
+ can grant only an APP-RUN waiver (in-memory — not `settings.json`, not `localStorage`, so
+ quitting restores the gate), the permanent one exists only in Settings where the option says
+ "permanently", a CANCEL never grants anything, and a waived action still announces itself on
+ screen. Which gates may be waived at all is a TABLE, not an `if` at each call site — so "this one
+ can never be waived" is a tested fact rather than a line somebody forgot to write.
+
+- **A permission mode (or anything else) that rides `project.json` is GIT-SHARED — never key a
+ local gate on it alone.** `project.defaultPermissionMode` travels to everyone who clones the
+ repo, so binding a confirmation-skip to "the mode is bypassPermissions" would let a cloned
+ repository silently switch off a user's destructive-action gate. The rule that came out of it:
+ ask `resolvePermissionModeWithSource` WHO chose the value (`project` / `global` / `default`) and
+ act only on the user's own machine-local choice — and keep `default` distinct from `global`,
+ because reading an unset setting as a deliberate choice is reading consent into silence. Anything
+ machine-local goes in `settings.json`; nothing that grants a capability goes in `project.json`.
+
+- **A dialog raised on someone else's behalf must know that request's lifetime.** Main abandons a
+ canvas-control request after 120 s and tells the renderer nothing, so an unanswered dialog sat
+ there forever AND held the one-confirm-at-a-time guard, which refused every later destructive
+ verb with "a confirmation is already pending" for the rest of the app run — the agent, told the
+ refusal was retryable, retried into it in a loop. If you raise a dialog for a bounded request,
+ give it the deadline (`ConfirmState.expiresAt`), import the bound rather than re-typing it, have
+ it expire slightly AFTER the requester gives up, and answer with "expired" — never "denied by
+ user", which claims a decision the human never made.
+
- **Anything path-shaped: Windows is a delivery target.** Most of this was written on
macOS/Linux, so the recurring defect is code that is genuinely correct on POSIX —
`split('/')`, `startsWith('/')` as an is-absolute test, a bare `fs.rename`. Use
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index 6548ce7c9..d76660f1f 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -425,9 +425,14 @@ export function buildCanvasControlInstructions(shimPath: string): string {
' Renaming to the title the node ALREADY has is a no-op: nothing is typed into its agent',
' session, and the reply says `already named`. Re-assert your own name as often as you like.',
`- \`color --node <id,id> --color C\` — recolor nodes, frames, or stickies. C is one of: ${NODE_COLORS.join(', ')}.`,
- '- `write --node <id> --text "..."` / `close --node <id>` — type into / close a node.',
+ '- `write --node <id> --text "..."` / `close --node <id,id>` — type into / close nodes.',
+ ' `close` takes a COMMA LIST and asks about the whole list in ONE dialog, so close a finished',
+ ' wave in a single call rather than one call per node. Every id must exist on the canvas: an',
+ ' unknown one refuses the whole request and closes nothing.',
' Desktop asks the user to confirm both. `denied by user` is FINAL; `no answer within 120s`',
- ' means nobody reached the dialog and is worth one retry when the user is back. Server Edition',
+ ' means nobody reached the dialog and is worth one retry when the user is back. The user may',
+ ' have turned the dialog off for a verb, in which case it simply applies — you cannot tell,',
+ ' and nothing changes about how you call it. Server Edition',
' is narrower: close requires a node this caller opened during the current server run, and all',
' node-mutating verbs accept only current-run creations. Every other target receives a named',
' ownership refusal before any partial mutation.',
@@ -921,7 +926,12 @@ Verbs:
session, and the reply says \`already named\`. Re-assert your own name as often as you like.
- \`color --node <id,id> --color C\` — recolor nodes, frames, or stickies. C is one of: ${NODE_COLORS.join(', ')}.
- \`write --node <id> --text "..."\` — type text into a terminal node. (Asks the user to confirm.)
-- \`close --node <id>\` — close a node. Desktop asks the user to confirm. Server Edition closes
+- \`close --node <id,id>\` — close one node or several. \`--node\` takes a COMMA LIST, and the whole
+ list is confirmed in ONE dialog — so when a wave of stations is finished, close them in a single
+ call instead of one call per node (which asked the user once per node, and refused every call
+ after the first while a dialog was still open). Every id must exist on the canvas: an unknown one
+ refuses the whole request and closes NOTHING, naming the ids it could not find. Desktop asks the
+ user to confirm. Server Edition closes
only nodes this caller opened during the current server run, without a dialog. Its other
node-mutating verbs (link/group/rename/color/sticky update) likewise accept only current-run
creations, and refuse the whole request before any partial mutation.
@@ -969,7 +979,12 @@ ${browserGuidanceLines().join('\n')}
Notes:
- Desktop \`write\` and \`close\` require the user to approve a confirmation dialog. A
\`denied by user\` reply is FINAL; \`no answer within 120s\` is worth one retry when the user
- is back. Server Edition uses the process-local ownership rule for \`close\` instead.
+ is back — the dialog dismisses itself at that point, so the retry is not blocked by it. The user
+ can also turn a verb's dialog off (for the session or permanently), and then the verb just
+ applies: you are never told which of the two happened, and you must not change how you call it —
+ in particular, never re-send a \`denied by user\` request hoping the dialog is off now.
+ \`a confirmation is already pending\` means a dialog for an EARLIER request is open: wait for
+ the user, do not spin. Server Edition uses the process-local ownership rule for \`close\` instead.
- \`board\` and \`assign\` act on the CURRENTLY OPEN project's board — the same one you see when you
toggle the kanban view. They need no confirmation.
- If the CLI says canvas control is unavailable, you are not in a controllable nodeterm session — do not retry.
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index 1f5088f00..91226b0b3 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -459,6 +459,32 @@ describe('parseControlRequest', () => {
}
})
+ it('both agent-facing texts say `close` takes a COMMA LIST, confirmed in ONE dialog', () => {
+ for (const body of [buildCanvasSkillBody('/x/shim.sh'), buildCanvasControlInstructions('/tmp/nodeterm.sh')]) {
+ // The grammar exists on both surfaces now (the desktop used to read the whole flag as one
+ // id), and an orchestrator that does not know it closes a finished wave one call at a time —
+ // which is one dialog per node, with every call after the first refused while a dialog is
+ // open. That was the reported pain; the text is what makes the fix reachable.
+ expect(body).toContain('close --node <id,id>')
+ expect(body.toUpperCase()).toContain('COMMA LIST')
+ expect(body.toUpperCase()).toContain('ONE dialog'.toUpperCase())
+ // …and that a bad id refuses the WHOLE list, so a caller does not have to guess which of its
+ // fourteen nodes survived.
+ expect(body).toMatch(/refuses the whole request/i)
+ }
+ })
+
+ it('the skill tells an agent NOT to retry a denial in the hope the dialog is off', () => {
+ // A user may waive a verb's dialog (for the session, or permanently). The verb then just
+ // applies, and the caller cannot tell which happened — so the one behaviour to rule out
+ // explicitly is re-sending a `denied by user` request to see whether it lands this time.
+ const body = buildCanvasSkillBody('/x/shim.sh')
+ expect(body).toMatch(/never re-send a `denied by user` request/i)
+ // And "a confirmation is already pending" must not read as an invitation to spin.
+ expect(body).toContain('a confirmation is already pending')
+ expect(body).toMatch(/do not spin/i)
+ })
+
it('both agent-facing texts state the Server creator-ownership and inert-boot contract', () => {
for (const body of [buildCanvasSkillBody('/x/shim.sh'), buildCanvasControlInstructions('/tmp/nodeterm.sh')]) {
expect(body).toContain('ownership is fail-closed')
diff --git a/src/main/index.ts b/src/main/index.ts
index 06c853272..4a1d0a717 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -225,6 +225,7 @@ import { initContextLink, setNodeTranscript } from '../core/context-link'
import { transcriptPathOf } from '../core/context-link-core'
import { initCanvasControl, installCanvasSkillInto } from './canvas-control'
import { DRY_RUN_VERBS, dryRunRequested, dryRunRefusal } from '../shared/control-verbs'
+import { CONTROL_REQUEST_TIMEOUT_MS } from '../shared/control-confirm'
import { initTranscriptIndex, searchTranscripts } from '../core/transcript-index'
import { initTelemetry } from './telemetry'
import { initClaudeUsage } from './claude-usage'
@@ -3067,7 +3068,10 @@ app.whenReady().then(async () => {
// which we forward to the renderer and await a reply. A pending-request map (keyed by a random
// requestId) bridges the two async hops; both the reply and the timeout below clear the entry.
// The window is generous because a confirm-gated verb waits on a human, not on the renderer.
- const CONTROL_REQUEST_TIMEOUT_MS = 120_000
+ // IMPORTED, not declared here: the renderer needs the same number to make an agent-requested
+ // confirm dialog collect itself once this timer has already abandoned the request (main sends
+ // no expiry event), and two copies of the deadline is the drift this repo keeps paying for.
+ // See @shared/control-confirm.
const pendingControl = new Map<
string,
{
@@ -3412,7 +3416,10 @@ app.whenReady().then(async () => {
// an unanswered dialog treated it as a refusal and gave up.
resolve({
ok: false,
- error: `no answer within ${CONTROL_REQUEST_TIMEOUT_MS / 1000}s — the confirmation dialog may still be open; safe to retry`
+ // The dialog is not left behind any more: it carries the same deadline and dismisses
+ // itself (ConfirmState.expiresAt), which is what stops a retry hitting "a confirmation
+ // is already pending" for the rest of the app run.
+ error: `no answer within ${CONTROL_REQUEST_TIMEOUT_MS / 1000}s — the confirmation dialog has been dismissed; safe to retry`
})
}, CONTROL_REQUEST_TIMEOUT_MS)
pendingControl.set(requestId, { resolve, timer })
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 2b6fd39e9..ba766eaf1 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -520,6 +520,19 @@ import { chordHeld, isHoldChord, isModifierEventKey, matchesShortcut } from '@sh
// write/close as "the confirm-gated pair" from inside `src/main` — which this project cannot see —
// while the gating lived in two hand-written blocks here, so the set decided nothing.
import { isDestructiveVerb, dryRunRequested } from '@shared/control-verbs'
+import {
+ confirmExpiresAt,
+ isWaivableVerb,
+ waivedNotice,
+ CONTROL_REQUEST_TIMEOUT_MS
+} from '@shared/control-confirm'
+import { useControlConfirm } from '../state/controlConfirm'
+import { controlConfirmDecision } from '../state/controlConfirmGate'
+import {
+ bulkCloseMessage,
+ parseCloseTargets,
+ CLOSE_BULK_MAX
+} from '../lib/closeTargets'
import { canvasSyncTarget } from './collab-sync'
import {
applyCanvasMutation,
@@ -632,6 +645,29 @@ interface ConfirmState {
/** Set when an AGENT asked for this dialog: it is answered by an explicit click, never by an
* Enter the user aimed at their terminal (see components/confirm-key). */
requestedBy?: string
+ /**
+ * The verb whose confirm a "Don't ask again" checkbox may waive for this app run
+ * (@shared/control-confirm). Set ONLY by the canvas-control dispatch, and only for a verb the
+ * shared table admits — `open-project` never carries it.
+ *
+ * A verb string rather than a ready-made `option`: the checkbox is live UI state and this object
+ * is a snapshot taken when the dialog opened, so an `option.checked` stored here would be frozen
+ * at `false` for the dialog's whole life. The render site builds the control and applies the
+ * waiver at click time, where the state is current.
+ */
+ waiveVerb?: string
+ /**
+ * When the request behind this dialog expires (`Date.now()`-scale). Set by the canvas-control
+ * dispatch, because main abandons the request after `CONTROL_REQUEST_TIMEOUT_MS` and tells the
+ * renderer nothing — so the dialog outlived the thing it was asking about AND kept `confirmBusy`
+ * true, which refused every later verb with "a confirmation is already pending" for the rest of
+ * the app run. Absent = no deadline (every human-initiated confirm).
+ */
+ expiresAt?: number
+ /** Runs when `expiresAt` passes with the dialog still open — the dispatch's chance to answer the
+ * (probably already abandoned) request honestly instead of leaving it to time out. Never
+ * `onCancel`: nobody denied anything. */
+ onExpire?: () => void
}
interface RemoveState {
groupId: string
@@ -1551,6 +1587,51 @@ export function Canvas() {
confirmFlags.current.confirm = !!v
setConfirmState(v)
}, [])
+ // "Don't ask again" on an agent-requested destructive confirm. Canvas state rather than a field
+ // on `ConfirmState` so the checkbox reads and writes LIVE (see `ConfirmState.waiveVerb`); reset
+ // by the dispatch every time it raises one of those dialogs, so a tick never carries over to the
+ // next request.
+ const [controlWaive, setControlWaive] = useState(false)
+ /**
+ * An agent-requested confirm collects itself when its REQUEST has expired.
+ *
+ * Main gives up on a control request after `CONTROL_REQUEST_TIMEOUT_MS` and sends the renderer
+ * nothing, so the dialog sat there for the rest of the app run — asking about work nobody was
+ * waiting for, and holding `confirmBusy` true, which refused every subsequent `write`/`close`
+ * with "a confirmation is already pending — try again". That is the loop the user saw: the same
+ * node asked about again and again, because the agent was told to retry and every retry hit a
+ * dialog that could no longer be answered.
+ *
+ * It replies `expired` on the way out rather than cancelling: `denied by user` would be a lie
+ * about a decision the human never made, and a reply main has already timed out is simply
+ * dropped (`if (!pending) return`). If the renderer's timer fires while main IS still waiting —
+ * a background tab's throttled `setTimeout`, a clock jump — that reply is what stops the caller
+ * waiting out the remaining budget for a dialog that is gone.
+ *
+ * The notice is deliberately non-blocking: raising an alert would keep `confirmBusy` true, i.e.
+ * reproduce the bug this closes with better wording.
+ */
+ useEffect(() => {
+ const at = confirm?.expiresAt
+ if (!at) return
+ const fire = (): void => {
+ confirm?.onExpire?.()
+ setConfirm(null)
+ setNotice({
+ kind: 'info',
+ text: `The request from ${confirm?.requestedBy ?? 'an agent'} expired before it was answered — nothing was done.`
+ })
+ }
+ const ms = at - Date.now()
+ if (ms <= 0) {
+ fire()
+ return
+ }
+ const t = setTimeout(fire, ms)
+ return () => clearTimeout(t)
+ // `confirm` is replaced wholesale per dialog, so its identity is the right key.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [confirm, setConfirm])
const setRemoveTarget = useCallback((v: RemoveState | null) => {
confirmFlags.current.remove = !!v
setRemoveTargetState(v)
@@ -9185,6 +9266,13 @@ export function Canvas() {
message: opPlan.message,
confirmLabel: opPlan.confirmLabel,
requestedBy: opTitle,
+ // NO `waiveVerb`. `open-project` is outside `CONFIRM_WAIVABLE_VERBS` and must stay
+ // outside it: it widens the app's blast radius (a new directory registered as a project,
+ // plus a grant the caller then feeds to `--project`) rather than acting inside it, and it
+ // cannot produce the dialog storm the waiver exists to end — `recordAttachConsent`
+ // already dedupes it per (caller, project). The table refuses it too; this is the belt.
+ expiresAt: confirmExpiresAt(Date.now()),
+ onExpire: () => reply({ ok: false, error: 'expired before the user answered' }),
onConfirm: () => {
setConfirm(null)
opFinish(
@@ -11244,6 +11332,56 @@ export function Canvas() {
reply({ ok: false, error: 'write requires --node' })
return
}
+ // The write itself, extracted so the waived path and the confirmed path are the SAME
+ // code. A waiver must change WHETHER the human is asked and nothing else — a second
+ // copy of the delivery is how the un-asked path quietly loses the per-node lock below.
+ const runWrite = async (): Promise<void> => {
+ // The SAME per-node lock the restart, hibernate-exit and wake-resume runs take.
+ // Its doc comment spells out why they take it: a second write arriving while a
+ // line sits un-submitted in the pane is spliced into that line. Every other
+ // `api.pty.sendText` caller was outside the lock, this one included, so a
+ // confirmed `write` could land in the middle of a hibernate exit's blind
+ // KILL_LINE + `/exit` (agent-restart.ts) or into an echo-verified launch line
+ // still waiting on its verification (command-delivery.ts). The dialog makes that
+ // rare, not impossible — the human confirms on their own clock, not the pane's.
+ let thrown: string | null = null
+ const outcome = await guardConcurrentRestart(args.node, async () => {
+ try {
+ const ok = await api.pty.sendText(args.node, args.text ?? '')
+ return ok ? ('sent' as const) : ('failed' as const)
+ } catch (e) {
+ thrown = String(e)
+ return 'failed' as const
+ }
+ })()
+ if (outcome === 'not-eligible') {
+ // A distinct, retryable refusal rather than a corrupted pane. `not-eligible` is
+ // the guard's own word for "that node is mid-run"; the run holding it will
+ // finish and the agent can send again.
+ reply({ ok: false, error: 'target is busy with a restart or wake — try again' })
+ return
+ }
+ reply({
+ ok: outcome === 'sent',
+ message: outcome === 'sent' ? 'sent' : 'failed',
+ error: outcome === 'sent' ? undefined : (thrown ?? 'sendText failed')
+ })
+ }
+ // Has the user waived this verb's dialog (this app run / permanently / while their own
+ // GLOBAL permission mode is Bypass)? The whole decision is the pure
+ // `decideControlConfirm` — see @shared/control-confirm for why the bypass branch needs
+ // both a machine-local opt-in AND a mode the user set globally.
+ const writeWaiver = controlConfirmDecision(verb)
+ if (writeWaiver.via) {
+ // A waived destructive action still ANNOUNCES itself, and names the waiver that let
+ // it through. Losing the dialog must not mean losing the record.
+ setNotice({
+ kind: 'info',
+ text: waivedNotice(`Agent "${srcTitle}" wrote to ${args.node}`, writeWaiver.via)
+ })
+ await runWrite()
+ 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 — and a second dialog
// mounted on top of a destructive one (the worktree-removal confirm) turned an Enter
@@ -11262,50 +11400,69 @@ export function Canvas() {
return
}
// Destructive → confirm. Replies on confirm AND cancel.
+ setControlWaive(false)
setConfirm({
message: `Agent "${srcTitle}" wants to send to ${args.node}:\n\n${args.text ?? ''}`,
confirmLabel: 'Send',
requestedBy: srcTitle,
+ waiveVerb: isWaivableVerb(verb) ? verb : undefined,
+ expiresAt: confirmExpiresAt(Date.now()),
+ onExpire: () => reply({ ok: false, error: 'expired before the user answered' }),
onConfirm: async () => {
setConfirm(null)
- // The SAME per-node lock the restart, hibernate-exit and wake-resume runs take.
- // Its doc comment spells out why they take it: a second write arriving while a
- // line sits un-submitted in the pane is spliced into that line. Every other
- // `api.pty.sendText` caller was outside the lock, this one included, so a
- // confirmed `write` could land in the middle of a hibernate exit's blind
- // KILL_LINE + `/exit` (agent-restart.ts) or into an echo-verified launch line
- // still waiting on its verification (command-delivery.ts). The dialog makes that
- // rare, not impossible — the human confirms on their own clock, not the pane's.
- let thrown: string | null = null
- const outcome = await guardConcurrentRestart(args.node, async () => {
- try {
- const ok = await api.pty.sendText(args.node, args.text ?? '')
- return ok ? ('sent' as const) : ('failed' as const)
- } catch (e) {
- thrown = String(e)
- return 'failed' as const
- }
- })()
- if (outcome === 'not-eligible') {
- // A distinct, retryable refusal rather than a corrupted pane. `not-eligible` is
- // the guard's own word for "that node is mid-run"; the run holding it will
- // finish and the agent can send again.
- reply({ ok: false, error: 'target is busy with a restart or wake — try again' })
- return
- }
- reply({
- ok: outcome === 'sent',
- message: outcome === 'sent' ? 'sent' : 'failed',
- error: outcome === 'sent' ? undefined : (thrown ?? 'sendText failed')
- })
+ await runWrite()
},
onCancel: () => reply({ ok: false, error: 'denied by user' })
})
return
}
case 'close': {
- if (!args.node) {
- reply({ ok: false, error: 'close requires --node' })
+ // `--node` is a LIST (`a,b,c`), which is how the Server Edition's headless close has
+ // always read it — this dispatch used the raw string as one id, so a comma list called
+ // `deleteNodes(['a,b,c'])` (a no-op) and answered `closed a,b,c`. The single-id form is
+ // untouched, deliberately including its lack of an existence check; see
+ // `lib/closeTargets.ts` for that asymmetry and why the bulk form refuses the whole
+ // request instead.
+ const targets = parseCloseTargets(args.node, nodesRef.current)
+ if (targets.kind === 'error') {
+ reply({ ok: false, error: targets.error })
+ return
+ }
+ const closeIds = targets.kind === 'single' ? [targets.id] : targets.ids
+ const closeMessage =
+ targets.kind === 'single'
+ ? `Agent "${srcTitle}" wants to close node ${targets.id}. Close it?`
+ : bulkCloseMessage(srcTitle, targets.labels)
+ const closeLabel = targets.kind === 'single' ? 'Close' : `Close ${closeIds.length}`
+ const runClose = (): void => {
+ // Canonical teardown: deleteNodes() destroys the local tmux session (remote-guarded),
+ // drops persisted agentStatus, and reparents any group children. Don't hand-roll it.
+ // ONE call for the whole list — its own paths are batched, and N calls would give N
+ // undo entries and N writeDisk passes for one decision.
+ deleteNodes(closeIds)
+ const dead = new Set(closeIds)
+ setControlEdges((es) => es.filter((e) => !dead.has(e.source) && !dead.has(e.target)))
+ reply({
+ ok: true,
+ message:
+ closeIds.length === 1
+ ? `closed ${closeIds[0]}`
+ : `closed ${closeIds.length} nodes: ${closeIds.join(', ')}`
+ })
+ }
+ // Waived? Same decision table as `write` (@shared/control-confirm).
+ const closeWaiver = controlConfirmDecision(verb)
+ if (closeWaiver.via) {
+ setNotice({
+ kind: 'info',
+ text: waivedNotice(
+ closeIds.length === 1
+ ? `Agent "${srcTitle}" closed ${closeIds[0]}`
+ : `Agent "${srcTitle}" closed ${closeIds.length} nodes`,
+ closeWaiver.via
+ )
+ })
+ runClose()
return
}
// One confirm dialog at a time (see `write`): reject rather than orphan a pending one —
@@ -11316,20 +11473,18 @@ export function Canvas() {
return
}
// Destructive → confirm. Replies on confirm AND cancel.
+ setControlWaive(false)
setConfirm({
- message: `Agent "${srcTitle}" wants to close node ${args.node}. Close it?`,
+ message: closeMessage,
requestedBy: srcTitle,
- confirmLabel: 'Close',
+ confirmLabel: closeLabel,
danger: true,
+ waiveVerb: isWaivableVerb(verb) ? verb : undefined,
+ expiresAt: confirmExpiresAt(Date.now()),
+ onExpire: () => reply({ ok: false, error: 'expired before the user answered' }),
onConfirm: () => {
setConfirm(null)
- // Canonical teardown: deleteNodes() destroys the local tmux session (remote-guarded),
- // drops persisted agentStatus, and reparents any group children. Don't hand-roll it.
- deleteNodes([args.node])
- setControlEdges((es) =>
- es.filter((e) => e.source !== args.node && e.target !== args.node)
- )
- reply({ ok: true, message: `closed ${args.node}` })
+ runClose()
},
onCancel: () => reply({ ok: false, error: 'denied by user' })
})
@@ -14036,7 +14191,27 @@ export function Canvas() {
// The user did not open this one — an agent did. It appeared under their hands, so it is
// answered by a click, never by a keystroke aimed somewhere else (components/confirm-key).
enterConfirms={!confirm.requestedBy}
- onConfirm={confirm.onConfirm}
+ // "Don't ask again" — offered ONLY for a verb the shared table admits, and only ever for
+ // THIS APP RUN. The permanent waiver deliberately lives in Settings → Agents instead: a
+ // dialog that appeared under the user's hands must not be able to switch a destructive
+ // gate off forever on one stray click. Built here rather than stored on `ConfirmState`
+ // because the checkbox is live state and that object is a snapshot.
+ option={
+ confirm.waiveVerb
+ ? {
+ label: "Don't ask again while nodeterm is running",
+ checked: controlWaive,
+ onChange: setControlWaive
+ }
+ : undefined
+ }
+ onConfirm={() => {
+ // Granted on CONFIRM only. A denial must never widen anything, whatever is ticked.
+ if (confirm.waiveVerb && controlWaive) {
+ useControlConfirm.getState().waiveForSession(confirm.waiveVerb)
+ }
+ confirm.onConfirm()
+ }}
onCancel={() => {
confirm.onCancel?.()
setConfirm(null)
diff --git a/src/renderer/canvas/control-destructive.test.ts b/src/renderer/canvas/control-destructive.test.ts
index 16d057b8b..784fd6a39 100644
--- a/src/renderer/canvas/control-destructive.test.ts
+++ b/src/renderer/canvas/control-destructive.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { isDestructiveVerb, DESTRUCTIVE_VERBS } from '@shared/control-verbs'
+import { isWaivableVerb } from '@shared/control-confirm'
/**
* A STRUCTURAL test on purpose.
@@ -73,6 +74,63 @@ describe('the confirm-gated set and the dispatch that reads it stay in agreement
})
}
+ /**
+ * The WAIVER gate (@shared/control-confirm) is the second thing every gated case must read, and
+ * a case that forgot it would keep asking forever — annoying but safe — while a case that read
+ * the wrong thing (or hard-coded a skip) would be a destructive verb with no human gate and no
+ * failing test. So it is pinned in both directions, exactly like the set above.
+ */
+ for (const verb of ['write', 'close'] as const) {
+ it(`${verb} reaches its confirm through the shared waiver decision`, () => {
+ expect(isWaivableVerb(verb)).toBe(true)
+ const body = dispatchBody(verb)
+ // The DECISION comes from the shared, tested table — never an inline condition here.
+ expect(body).toMatch(/controlConfirmDecision\(verb\)/)
+ // A skip must announce itself. `waivedNotice` is what puts the action on screen when the
+ // dialog is gone; without it a waiver makes destructive work silent.
+ expect(body).toContain('waivedNotice(')
+ // And the dialog it raises must offer the app-run waiver, gated on the same table.
+ expect(body).toContain('waiveVerb: isWaivableVerb(verb) ? verb : undefined')
+ // The request deadline, so an abandoned dialog cannot hold `confirmBusy` for the app run.
+ expect(body).toContain('expiresAt: confirmExpiresAt(')
+ expect(body).toContain('onExpire:')
+ })
+ }
+
+ it('open-project raises the SAME dialog but can never be waived', () => {
+ // It is outside CONFIRM_WAIVABLE_VERBS on purpose (it registers a new directory and records a
+ // grant), and it is already deduped per (caller, project), so it cannot produce the dialog
+ // storm the waiver exists to end. Both halves are asserted: no waiver, but still a deadline.
+ expect(isWaivableVerb('open-project')).toBe(false)
+ const body = dispatchBody('open-project')
+ // The FIELD, not the word: the block carries a comment explaining why it has no waiver, and
+ // that comment is the thing a future reader needs most.
+ expect(body).not.toMatch(/waiveVerb:/)
+ expect(body).not.toContain('controlConfirmDecision(')
+ expect(body).toContain('expiresAt: confirmExpiresAt(')
+ })
+
+ it('no case hard-codes a skip of its confirm', () => {
+ // The only admissible way past one of these dialogs is `controlConfirmDecision`. A literal
+ // shortcut (an env check, a `true`, a settings flag read inline) would be a silent loosening.
+ for (const verb of ['write', 'close', 'open-project'] as const) {
+ const body = dispatchBody(verb)
+ expect(body).not.toMatch(/skipConfirm|dontAskAgain|SKIP_CONFIRM/)
+ }
+ })
+
+ it('a DENIAL never grants a waiver', () => {
+ // The checkbox is ticked before the user has decided, so the grant must hang off the confirm
+ // button and nothing else. Cancelling a dialog with "Don't ask again" ticked has to leave the
+ // gate exactly where it was — the opposite would turn a refusal into a permanent yes.
+ const site = src.slice(src.indexOf('{confirm && ('), src.indexOf('{pendingPeer && ('))
+ expect(site).toContain('waiveForSession(confirm.waiveVerb)')
+ expect(site.slice(site.indexOf('onCancel={'))).not.toContain('waiveForSession')
+ // Only ever the app-run waiver from a dialog: the permanent one is a Settings write, and
+ // `controlConfirmWaivers` must not be reachable from here.
+ expect(site).not.toContain('controlConfirmWaivers')
+ })
+
it('no other case reads isDestructiveVerb', () => {
// Every `isDestructiveVerb(verb)` in the dispatch must sit in a case the set actually holds.
// If a third case ever grows one, either the set or the dispatch is wrong — say so here rather
diff --git a/src/renderer/components/settings/sections/AgentsSection.controlConfirm.test.tsx b/src/renderer/components/settings/sections/AgentsSection.controlConfirm.test.tsx
new file mode 100644
index 000000000..bbba644f4
--- /dev/null
+++ b/src/renderer/components/settings/sections/AgentsSection.controlConfirm.test.tsx
@@ -0,0 +1,174 @@
+// @vitest-environment jsdom
+//
+// The house rule this row exists to satisfy: every loosening of a security gate must be VISIBLE as
+// a setting and revocable there. A "Don't ask again" that lives only in a dialog is a permission
+// the user granted once and can never find again — so the section has to show what is waived
+// right now (including the app-run waiver granted from a dialog that is already gone), and offer
+// the way back.
+//
+// The other half is the git-shared trap, and it is asserted as COPY here because the copy is the
+// only place a user learns it: a `bypassPermissions` in `.nodeterm/project.json` travels to
+// everyone who clones the repo, so this switch must say — in the row itself — that a project
+// override does not count. The behaviour is proven in shared/control-confirm.test.ts.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { CONFIRM_WAIVABLE_VERBS } from '@shared/control-confirm'
+import { useSettings } from '../../../state/settings'
+import { useControlConfirm } from '../../../state/controlConfirm'
+import { AgentsSection } from './AgentsSection'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+let root: Root
+let host: HTMLElement
+
+function selectFor(label: string): HTMLSelectElement {
+ const el = host.querySelector<HTMLSelectElement>(`select[aria-label="${label}"]`)
+ expect(el, `a row for "${label}" must be in the Agents section`).toBeTruthy()
+ return el!
+}
+
+function choose(label: string, value: string): void {
+ const el = selectFor(label)
+ act(() => {
+ el.value = value
+ el.dispatchEvent(new Event('change', { bubbles: true }))
+ })
+}
+
+function bypassSwitch(): HTMLElement {
+ const el = host.querySelector<HTMLElement>(
+ '[aria-label="Skip destructive canvas-control confirmations in Bypass permissions mode"]'
+ )
+ expect(el, 'the bypass opt-in must be in the Agents section').toBeTruthy()
+ return el!
+}
+
+const CLOSE_LABEL = 'Ask before an agent closes nodes'
+const WRITE_LABEL = 'Ask before an agent types into a node'
+
+async function render(): Promise<void> {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ await act(async () => {
+ root.render(<AgentsSection isActive />)
+ })
+}
+
+beforeEach(async () => {
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ settings: { save: vi.fn(async () => undefined) },
+ claude: { cliCaps: vi.fn(async () => null) }
+ }
+ useSettings.setState((s) => ({ settings: { ...s.settings, controlConfirmWaivers: undefined } }))
+ useControlConfirm.setState({ sessionWaived: [], sessionWaivedSet: new Set() })
+ await render()
+})
+
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ useSettings.setState((s) => ({ settings: { ...s.settings, controlConfirmWaivers: undefined } }))
+ useControlConfirm.setState({ sessionWaived: [], sessionWaivedSet: new Set() })
+})
+
+describe('destructive canvas-control confirmations in Settings', () => {
+ it('shows one row per waivable verb, derived from the shared table', () => {
+ // Derived, not hand-listed: a verb that becomes waivable in code but invisible here would be a
+ // loosening the user cannot see or revoke.
+ expect(CONFIRM_WAIVABLE_VERBS.size).toBe(2)
+ selectFor(WRITE_LABEL)
+ selectFor(CLOSE_LABEL)
+ })
+
+ it('defaults to Always ask with no setting stored', () => {
+ expect(selectFor(CLOSE_LABEL).value).toBe('ask')
+ expect(useSettings.getState().settings.controlConfirmWaivers).toBeUndefined()
+ })
+
+ it('says "permanently" on the permanent option — the dialog cannot grant this one', () => {
+ const option = [...selectFor(CLOSE_LABEL).options].find((o) => o.value === 'never')
+ expect(option?.textContent).toMatch(/permanently/i)
+ })
+
+ it('persists a permanent waiver per verb, and revokes it', () => {
+ choose(CLOSE_LABEL, 'never')
+ expect(useSettings.getState().settings.controlConfirmWaivers).toEqual({ always: ['close'] })
+ // Waiving `close` must not waive `write`.
+ expect(selectFor(WRITE_LABEL).value).toBe('ask')
+ choose(CLOSE_LABEL, 'ask')
+ expect(useSettings.getState().settings.controlConfirmWaivers).toEqual({})
+ })
+
+ it('normalizes a hand-edited settings.json on the first UI write', () => {
+ // The gates read through the sanitizer, so a bogus entry is already inert — but leaving it in
+ // the file makes the UI and the file disagree about what is waived.
+ act(() => {
+ useSettings.setState((s) => ({
+ settings: {
+ ...s.settings,
+ controlConfirmWaivers: { always: ['open-project', 'close', 'close'] } as never
+ }
+ }))
+ })
+ // It never showed as waived…
+ expect(selectFor(CLOSE_LABEL).value).toBe('never')
+ choose(WRITE_LABEL, 'never')
+ // …and the write drops the entry the table forbids instead of carrying it forward.
+ expect(useSettings.getState().settings.controlConfirmWaivers).toEqual({
+ always: ['close', 'write']
+ })
+ })
+
+ it('surfaces an app-run waiver granted from a dialog, and offers Revoke', () => {
+ expect(host.textContent).not.toContain('Waived until nodeterm quits')
+ act(() => useControlConfirm.getState().waiveForSession('close'))
+ const text = host.textContent ?? ''
+ // The dialog that granted it is gone, so this row is the only place it can be seen or ended.
+ expect(text).toContain('Waived until nodeterm quits')
+ const revoke = [...host.querySelectorAll('button')].find((b) => b.textContent === 'Revoke')
+ expect(revoke, 'an app-run waiver must be revocable here').toBeTruthy()
+ act(() => revoke!.dispatchEvent(new MouseEvent('click', { bubbles: true })))
+ expect(useControlConfirm.getState().sessionWaived).toEqual([])
+ expect(host.textContent).not.toContain('Waived until nodeterm quits')
+ // Revoking an app-run waiver must not write anything to disk.
+ expect(useSettings.getState().settings.controlConfirmWaivers).toBeUndefined()
+ })
+
+ it('does not offer Revoke for a PERMANENT waiver — the dropdown is that control', () => {
+ choose(CLOSE_LABEL, 'never')
+ act(() => useControlConfirm.getState().waiveForSession('close'))
+ expect(host.textContent).not.toContain('Waived until nodeterm quits')
+ // A Revoke beside a permanent waiver would clear the app-run one and change nothing the user
+ // can see, since the permanent waiver still applies — a button that appears to do nothing.
+ expect([...host.querySelectorAll('button')].some((b) => b.textContent === 'Revoke')).toBe(false)
+ })
+
+ it('does not honour a hand-edited waiver the GATES will refuse', () => {
+ // `settings.json` is hand-editable and unvalidated on load, so this row must show what
+ // `decideControlConfirm` will actually do — not what the file says. A string where a list
+ // belongs is the case that separates the two: `'close'.includes('close')` is true, so a raw
+ // read reports the verb as waived while the sanitized gate keeps asking.
+ act(() => {
+ useSettings.setState((s) => ({
+ settings: { ...s.settings, controlConfirmWaivers: { always: 'close' } as never }
+ }))
+ })
+ expect(selectFor(CLOSE_LABEL).value).toBe('ask')
+ })
+
+ it('has the bypass opt-in OFF by default and persists it', () => {
+ expect(bypassSwitch().getAttribute('aria-checked')).toBe('false')
+ act(() => bypassSwitch().dispatchEvent(new MouseEvent('click', { bubbles: true })))
+ expect(useSettings.getState().settings.controlConfirmWaivers).toEqual({ bypassMode: true })
+ })
+
+ it('tells the user that a project override does NOT count', () => {
+ const text = host.textContent ?? ''
+ expect(text).toContain('.nodeterm/project.json')
+ expect(text).toMatch(/travels to everyone who clones the repo/)
+ expect(text).toMatch(/A project that overrides the mode never counts/)
+ })
+})
diff --git a/src/renderer/components/settings/sections/AgentsSection.tsx b/src/renderer/components/settings/sections/AgentsSection.tsx
index 2bf875e54..6a8b922c5 100644
--- a/src/renderer/components/settings/sections/AgentsSection.tsx
+++ b/src/renderer/components/settings/sections/AgentsSection.tsx
@@ -33,6 +33,11 @@ import {
import { AgentIcon } from '../../../lib/agentIcons'
import { chipFor } from '../../../lib/keybindingOverrides'
import { NODE_IDENTITY_STRICT_DATE } from '@shared/node-identity'
+import {
+ CONFIRM_WAIVABLE_VERBS,
+ sanitizeControlConfirmWaivers
+} from '@shared/control-confirm'
+import { useControlConfirm } from '../../../state/controlConfirm'
import { SegmentedPill } from '@renderer/ui/SegmentedPill'
import { Button } from '@renderer/ui/Button'
import { Input } from '@renderer/ui/Input'
@@ -91,6 +96,25 @@ const ROWS = {
title: 'One-click approvals',
keywords: ['approve', 'deny', 'approval', 'permission', 'hook', 'phone', 'canvas', 'one click', 'claude']
},
+ controlConfirm: {
+ title: 'Destructive canvas-control confirmations',
+ keywords: [
+ 'confirm',
+ 'confirmation',
+ 'dialog',
+ 'ask',
+ "don't ask again",
+ 'dont ask again',
+ 'waive',
+ 'write',
+ 'close',
+ 'destructive',
+ 'canvas control',
+ 'bypass',
+ 'permission mode',
+ 'security'
+ ]
+ },
nodeIdentity: {
title: 'Verified node identity',
keywords: [
@@ -182,6 +206,38 @@ function permissionModeDescription(): string {
.join(' ')
}
+/**
+ * The waivable destructive verbs, in the order they are shown, with a sentence each.
+ *
+ * The LIST comes from the shared table (`CONFIRM_WAIVABLE_VERBS`) rather than being typed here, so
+ * a verb that becomes waivable cannot be waivable-in-code and invisible-in-Settings — a loosening
+ * the user cannot see or revoke is exactly what this section exists to prevent. An unknown verb
+ * falls back to its own name, which is honest and ugly rather than absent.
+ */
+const CONTROL_CONFIRM_VERB_COPY: Record<string, { label: string; description: string }> = {
+ write: {
+ label: 'Ask before an agent types into a node',
+ description:
+ 'The `write` verb sends text straight into another session\u2019s terminal. Waiving the dialog lets any canvas-control agent do that without asking.'
+ },
+ close: {
+ label: 'Ask before an agent closes nodes',
+ description:
+ 'The `close` verb deletes nodes and ends their terminal sessions. Waiving the dialog lets any canvas-control agent do that without asking.'
+ }
+}
+
+const CONTROL_CONFIRM_CHOICES = ['ask', 'never'] as const
+type ControlConfirmChoice = (typeof CONTROL_CONFIRM_CHOICES)[number]
+
+const CONTROL_CONFIRM_LABELS: Record<ControlConfirmChoice, string> = {
+ ask: 'Always ask',
+ // Says "permanently" in the option itself: the only other way to waive one of these is the
+ // dialog's own checkbox, which is bounded by the app's lifetime, and the difference between the
+ // two is the entire safety story.
+ never: 'Never ask (permanently, this computer)'
+}
+
// The agents claude's version gate does NOT apply to — every other capable agent. Module level: the
// capable list cannot change while the app runs.
const otherModeAgents = permissionModeAgentIds({ exclude: ['claude'] })
@@ -220,6 +276,28 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.El
// off-toggle re-renders immediately — and consumers read the switch per call from the store,
// never from a snapshot taken when a lease started (agents-capabilities.test.tsx "takes effect
// LIVE"; browser PR 4 / messaging PR 6 rely on that shape).
+ // Destructive canvas-control confirmations (@shared/control-confirm). Read through the SANITIZER,
+ // never raw: `settings.json` is hand-editable and a bogus entry there must degrade to "ask", so
+ // the section shows what the GATES will actually honour rather than what the file happens to say.
+ const waivers = sanitizeControlConfirmWaivers(settings.controlConfirmWaivers)
+ const waivableVerbs = [...CONFIRM_WAIVABLE_VERBS]
+ // Subscribed, not getState(): granting or revoking an app-run waiver must repaint this row.
+ const sessionWaivedVerbs = useControlConfirm((s) => s.sessionWaived)
+ /** Persist a PERMANENT waiver. Writes the sanitized shape back, so a hand-edited file is
+ * normalized by the first UI touch instead of silently surviving beside it. */
+ const setAlwaysWaived = (verb: string, on: boolean): void => {
+ const next = on
+ ? [...new Set([...(waivers.always ?? []), verb])]
+ : (waivers.always ?? []).filter((v) => v !== verb)
+ update({
+ controlConfirmWaivers: sanitizeControlConfirmWaivers({ ...waivers, always: next })
+ })
+ }
+ const setBypassWaived = (on: boolean): void => {
+ update({
+ controlConfirmWaivers: sanitizeControlConfirmWaivers({ ...waivers, bypassMode: on })
+ })
+ }
const activeProjectId = useProjects((s) => s.activeProjectId)
const activeProject = useProjects((s) => s.projects.find((p) => p.id === activeProjectId))
const setProjectCapability = useProjects((s) => s.setProjectCapability)
@@ -400,6 +478,65 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.El
}
/>
</SearchableRow>
+ <SearchableRow {...ROWS.controlConfirm}>
+ <div className="space-y-4">
+ {waivableVerbs.map((v) => {
+ const copy =
+ CONTROL_CONFIRM_VERB_COPY[v] ??
+ ({ label: `Ask before an agent runs \`${v}\``, description: '' } as const)
+ const sessionWaived = sessionWaivedVerbs.includes(v)
+ const always = (waivers.always ?? []).includes(v)
+ return (
+ <FieldRow
+ key={v}
+ label={copy.label}
+ description={copy.description}
+ // A live app-run waiver is a STATE, not help text — the warning accent is right,
+ // and it must name how to end it, because the dialog that granted it is gone.
+ note={
+ sessionWaived && !always
+ ? 'Waived until nodeterm quits (you ticked "Don\u2019t ask again"). Revoke restores the dialog now.'
+ : undefined
+ }
+ control={
+ <div className="flex items-center gap-2">
+ {sessionWaived && !always ? (
+ <Button
+ variant="default"
+ onClick={() => useControlConfirm.getState().revokeForSession(v)}
+ >
+ Revoke
+ </Button>
+ ) : null}
+ <Select
+ aria-label={copy.label}
+ value={always ? 'never' : 'ask'}
+ onChange={(e) => setAlwaysWaived(v, e.target.value === 'never')}
+ >
+ {CONTROL_CONFIRM_CHOICES.map((c) => (
+ <option key={c} value={c}>
+ {CONTROL_CONFIRM_LABELS[c]}
+ </option>
+ ))}
+ </Select>
+ </div>
+ }
+ />
+ )
+ })}
+ <FieldRow
+ label="Also skip them while your permission mode is Bypass"
+ description="When YOUR global permission mode (above) is Bypass permissions, treat that as covering these dialogs too. A project that overrides the mode never counts \u2014 an override is saved in .nodeterm/project.json and travels to everyone who clones the repo, so a repository you cloned must not be able to switch your confirmations off."
+ control={
+ <Switch
+ checked={waivers.bypassMode === true}
+ ariaLabel="Skip destructive canvas-control confirmations in Bypass permissions mode"
+ onChange={setBypassWaived}
+ />
+ }
+ />
+ </div>
+ </SearchableRow>
<SearchableRow {...ROWS.nodeIdentity}>
<FieldRow
label="Require verified node identity for canvas control"
diff --git a/src/renderer/lib/closeTargets.test.ts b/src/renderer/lib/closeTargets.test.ts
new file mode 100644
index 000000000..c613152fb
--- /dev/null
+++ b/src/renderer/lib/closeTargets.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ CLOSE_BULK_MAX,
+ CLOSE_LIST_PREVIEW,
+ bulkCloseMessage,
+ parseCloseTargets
+} from './closeTargets'
+
+const live = [
+ { id: 'a', title: 'Backend tests' },
+ { id: 'b', title: '' },
+ { id: 'c', title: 'Docs' }
+]
+
+describe('parseCloseTargets — the single-node form is unchanged', () => {
+ it('reads one id as one id', () => {
+ expect(parseCloseTargets('a', live)).toEqual({ kind: 'single', id: 'a' })
+ })
+
+ it('does NOT existence-check a single id', () => {
+ // Deliberate: `close --node <gone>` behaves exactly as it did before this change (dialog,
+ // then `closed <id>`). Correcting that pre-existing lie is its own change; doing it here would
+ // alter the form every agent already uses in the same commit that adds the new one.
+ expect(parseCloseTargets('ghost', live)).toEqual({ kind: 'single', id: 'ghost' })
+ })
+
+ it('trims, and a trailing comma is still one id', () => {
+ expect(parseCloseTargets(' a ', live)).toEqual({ kind: 'single', id: 'a' })
+ expect(parseCloseTargets('a,', live)).toEqual({ kind: 'single', id: 'a' })
+ })
+
+ it('refuses an empty flag', () => {
+ for (const raw of [undefined, '', ' ', ',', ',,']) {
+ const r = parseCloseTargets(raw, live)
+ expect(r.kind).toBe('error')
+ if (r.kind === 'error') expect(r.error).toBe('close requires --node')
+ }
+ })
+})
+
+describe('parseCloseTargets — the bulk form', () => {
+ it('splits a comma list and labels each id', () => {
+ const r = parseCloseTargets('a,c', live)
+ expect(r).toEqual({
+ kind: 'bulk',
+ ids: ['a', 'c'],
+ labels: ['Backend tests (a)', 'Docs (c)']
+ })
+ })
+
+ it('falls back to the bare id when a node has no title', () => {
+ const r = parseCloseTargets('a,b', live)
+ if (r.kind !== 'bulk') throw new Error('expected bulk')
+ expect(r.labels).toEqual(['Backend tests (a)', 'b'])
+ })
+
+ it('de-duplicates, which can collapse a list back to the single form', () => {
+ expect(parseCloseTargets('a,a', live)).toEqual({ kind: 'single', id: 'a' })
+ const r = parseCloseTargets('a,c,a', live)
+ if (r.kind !== 'bulk') throw new Error('expected bulk')
+ expect(r.ids).toEqual(['a', 'c'])
+ })
+
+ it('preserves the caller order', () => {
+ const r = parseCloseTargets('c,b,a', live)
+ if (r.kind !== 'bulk') throw new Error('expected bulk')
+ expect(r.ids).toEqual(['c', 'b', 'a'])
+ })
+
+ it('refuses the WHOLE request when any id is unknown, and names it', () => {
+ const r = parseCloseTargets('a,ghost,c', live)
+ expect(r.kind).toBe('error')
+ if (r.kind !== 'error') return
+ expect(r.error).toContain('ghost')
+ expect(r.error).toContain('nothing was closed')
+ // Not a partial success: the known ids must not appear as "closed".
+ expect(r.error).not.toContain('closed a')
+ })
+
+ it('names at most the preview count of missing ids and counts the rest', () => {
+ const many = Array.from({ length: CLOSE_LIST_PREVIEW + 3 }, (_, i) => `x${i}`)
+ const r = parseCloseTargets(['a', ...many].join(','), live)
+ if (r.kind !== 'error') throw new Error('expected error')
+ expect(r.error).toContain('+3 more')
+ expect(r.error).toContain('x0')
+ expect(r.error).not.toContain(`x${CLOSE_LIST_PREVIEW + 2}`)
+ })
+
+ it('refuses a list longer than the cap without consulting the canvas', () => {
+ const ids = Array.from({ length: CLOSE_BULK_MAX + 1 }, (_, i) => `n${i}`)
+ const nodes = ids.map((id) => ({ id }))
+ const r = parseCloseTargets(ids.join(','), nodes)
+ expect(r.kind).toBe('error')
+ if (r.kind === 'error') expect(r.error).toContain(String(CLOSE_BULK_MAX))
+ })
+
+ it('accepts a list exactly at the cap', () => {
+ const ids = Array.from({ length: CLOSE_BULK_MAX }, (_, i) => `n${i}`)
+ const r = parseCloseTargets(ids.join(','), ids.map((id) => ({ id })))
+ expect(r.kind).toBe('bulk')
+ })
+})
+
+describe('bulkCloseMessage', () => {
+ it('names every node when they fit, and says what closing costs', () => {
+ const msg = bulkCloseMessage('orchestrator', ['Backend tests (a)', 'Docs (c)'])
+ expect(msg).toContain('close 2 nodes')
+ expect(msg).toContain('Backend tests (a)')
+ expect(msg).toContain('Docs (c)')
+ expect(msg).toContain('terminal sessions end')
+ })
+
+ it('caps the list and counts the remainder — a name the user cannot see is not consent', () => {
+ const labels = Array.from({ length: 14 }, (_, i) => `node ${i}`)
+ const msg = bulkCloseMessage('orchestrator', labels)
+ expect(msg).toContain('close 14 nodes')
+ expect(msg.match(/•/g)?.length).toBe(CLOSE_LIST_PREVIEW)
+ expect(msg).toContain(`and ${14 - CLOSE_LIST_PREVIEW} more`)
+ })
+})
diff --git a/src/renderer/lib/closeTargets.ts b/src/renderer/lib/closeTargets.ts
new file mode 100644
index 000000000..cbdae3b73
--- /dev/null
+++ b/src/renderer/lib/closeTargets.ts
@@ -0,0 +1,96 @@
+// `close --node <id[,id…]>` — turning one flag into either the historical single-node close or a
+// ONE-DIALOG bulk close.
+//
+// WHY: the desktop dispatch read `args.node` as a whole id, so `close --node a,b,c` called
+// `deleteNodes(['a,b,c'])` — a no-op, since no node has that id — and replied `closed a,b,c`. A
+// destructive verb reporting success for work it did not do is the worst of the three possible
+// behaviours (do it, refuse it, or lie about it). Meanwhile the Server Edition's headless `close`
+// has accepted a comma list since it shipped (`HeadlessNodeFactory.close`), including its rule
+// that the WHOLE list is validated before anything is killed. So the grammar already existed on
+// one surface and the other silently mis-parsed it.
+//
+// The second reason is the one the user hit: closing 14 nodes meant 14 separate dialogs, each
+// refusing the next request with `a confirmation is already pending`. One list, one decision.
+//
+// PURE, so it is testable where the 11k-line component is not — same reasoning as
+// `controlRouting.ts` and `pendingLaunch.ts`.
+
+/** The most ids one `close` call may name. */
+export const CLOSE_BULK_MAX = 50
+
+/** How many names the dialog spells out before it summarises the rest. */
+export const CLOSE_LIST_PREVIEW = 12
+
+/** The little this needs to know about a canvas node. */
+export interface CloseCandidate {
+ id: string
+ title?: string
+}
+
+export type CloseTargets =
+ /** Exactly one id — the historical path, applied WITHOUT an existence check (see below). */
+ | { kind: 'single'; id: string }
+ /** Two or more ids, every one of them resolved against the live canvas. */
+ | { kind: 'bulk'; ids: string[]; labels: string[] }
+ | { kind: 'error'; error: string }
+
+/**
+ * Split, trim and de-duplicate `--node`, then decide which shape of close this is.
+ *
+ * **The single-id path is deliberately NOT existence-checked**, so it stays bit-for-bit what it
+ * was: `close --node <gone>` still opens the same dialog and still answers `closed <id>`. That is
+ * a lie about a node that no longer exists, and it is a pre-existing one — correcting it here
+ * would change the behaviour of the form every agent already uses, in the same change that adds
+ * the new one. It belongs in its own change.
+ *
+ * A BULK list IS checked, and an unknown id refuses the whole call. The asymmetry is the point:
+ * with 14 ids the user cannot audit the list themselves, so "closed 14" must mean 14 — silently
+ * closing 13 and claiming 14 is exactly the failure the single-id lie makes harmless only because
+ * one id is one thing the caller can check.
+ */
+export function parseCloseTargets(raw: string | undefined, live: readonly CloseCandidate[]): CloseTargets {
+ const ids = [...new Set((raw ?? '').split(',').map((id) => id.trim()).filter(Boolean))]
+ if (!ids.length) return { kind: 'error', error: 'close requires --node' }
+ if (ids.length === 1) return { kind: 'single', id: ids[0] }
+ if (ids.length > CLOSE_BULK_MAX) {
+ return {
+ kind: 'error',
+ error: `close: ${ids.length} ids is more than the ${CLOSE_BULK_MAX} one call may name — split it`
+ }
+ }
+ const byId = new Map(live.map((n) => [n.id, n]))
+ const missing = ids.filter((id) => !byId.has(id))
+ if (missing.length) {
+ // Named, not counted: an orchestrator that mistyped one id of fourteen needs to know which.
+ const shown = missing.slice(0, CLOSE_LIST_PREVIEW).join(', ')
+ const rest = missing.length > CLOSE_LIST_PREVIEW ? ` (+${missing.length - CLOSE_LIST_PREVIEW} more)` : ''
+ return {
+ kind: 'error',
+ error: `close: no node on this canvas with id ${shown}${rest} — nothing was closed`
+ }
+ }
+ return {
+ kind: 'bulk',
+ ids,
+ labels: ids.map((id) => {
+ const title = (byId.get(id)?.title ?? '').trim()
+ return title ? `${title} (${id})` : id
+ })
+ }
+}
+
+/**
+ * The bulk dialog's message. Names every node it can fit and COUNTS the rest — an unbounded list
+ * is a dialog the user cannot read, and a scrolled-off name is one they did not consent to.
+ */
+export function bulkCloseMessage(srcTitle: string, labels: readonly string[]): string {
+ const shown = labels.slice(0, CLOSE_LIST_PREVIEW)
+ const hidden = labels.length - shown.length
+ const lines = shown.map((l) => ` • ${l}`)
+ if (hidden > 0) lines.push(` … and ${hidden} more`)
+ return (
+ `Agent "${srcTitle}" wants to close ${labels.length} nodes:\n\n` +
+ `${lines.join('\n')}\n\n` +
+ 'Their terminal sessions end. Close them all?'
+ )
+}
diff --git a/src/renderer/state/controlConfirm.test.ts b/src/renderer/state/controlConfirm.test.ts
new file mode 100644
index 000000000..f4ecc0212
--- /dev/null
+++ b/src/renderer/state/controlConfirm.test.ts
@@ -0,0 +1,61 @@
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import { useControlConfirm, sessionWaivedVerbs } from './controlConfirm'
+
+beforeEach(() => {
+ useControlConfirm.setState({ sessionWaived: [], sessionWaivedSet: new Set() })
+})
+
+describe('the app-run waiver store', () => {
+ it('starts empty — the default is to ask', () => {
+ expect(useControlConfirm.getState().sessionWaived).toEqual([])
+ expect(sessionWaivedVerbs().size).toBe(0)
+ })
+
+ it('waives and revokes per verb', () => {
+ useControlConfirm.getState().waiveForSession('close')
+ expect(sessionWaivedVerbs().has('close')).toBe(true)
+ expect(sessionWaivedVerbs().has('write')).toBe(false)
+ useControlConfirm.getState().revokeForSession('close')
+ expect(sessionWaivedVerbs().has('close')).toBe(false)
+ })
+
+ it('refuses a verb the shared table does not admit', () => {
+ // The gate is applied here as well as in the decision: a caller cannot grant a waiver for
+ // `open-project` by passing the wrong string into the wrong function.
+ useControlConfirm.getState().waiveForSession('open-project')
+ useControlConfirm.getState().waiveForSession('list')
+ expect(useControlConfirm.getState().sessionWaived).toEqual([])
+ })
+
+ it('is idempotent', () => {
+ useControlConfirm.getState().waiveForSession('write')
+ useControlConfirm.getState().waiveForSession('write')
+ expect(useControlConfirm.getState().sessionWaived).toEqual(['write'])
+ })
+
+ it('rebuilds the Set on every change, so identity is a usable change signal', () => {
+ const before = sessionWaivedVerbs()
+ useControlConfirm.getState().waiveForSession('write')
+ expect(sessionWaivedVerbs()).not.toBe(before)
+ // …and a no-op change does not churn it.
+ const after = sessionWaivedVerbs()
+ useControlConfirm.getState().waiveForSession('write')
+ expect(sessionWaivedVerbs()).toBe(after)
+ })
+
+ it('persists NOTHING — the app-run waiver must die with the process', () => {
+ // The whole safety argument for letting a dialog grant this at all is that quitting restores
+ // it. A localStorage write here would silently turn it into a permanent one.
+ const keys: string[] = []
+ const store = {
+ setItem: (k: string) => keys.push(k),
+ getItem: () => null,
+ removeItem: () => undefined
+ }
+ Object.defineProperty(globalThis, 'localStorage', { value: store, configurable: true })
+ useControlConfirm.getState().waiveForSession('close')
+ useControlConfirm.getState().revokeForSession('close')
+ expect(keys).toEqual([])
+ })
+})
diff --git a/src/renderer/state/controlConfirm.ts b/src/renderer/state/controlConfirm.ts
new file mode 100644
index 000000000..fc99b45f0
--- /dev/null
+++ b/src/renderer/state/controlConfirm.ts
@@ -0,0 +1,50 @@
+import { create } from 'zustand'
+
+import { isWaivableVerb } from '@shared/control-confirm'
+
+/**
+ * Canvas-control confirm waivers granted for THIS APP RUN — the "Don't ask again" checkbox in the
+ * destructive-verb dialog.
+ *
+ * **In memory, and that is the feature, not a shortcut.** It is neither persisted here nor mirrored
+ * into `settings.json` (`localStorage` included — a browser-origin store would outlive the process
+ * exactly the way this must not). Restarting nodeterm restores the dialog, so the widest thing a
+ * user can grant from inside a dialog that appeared under their hands is bounded by the app's own
+ * lifetime. The PERMANENT waiver exists too, and it lives in Settings → Agents where it is
+ * labelled as permanent and cannot be granted by a stray click on a confirm.
+ *
+ * It is a store rather than a module-level `Set` for one reason: Settings renders the live list, so
+ * granting a waiver must re-render the row that revokes it.
+ */
+interface ControlConfirmState {
+ /** Verbs waived for this app run, insertion-ordered. */
+ sessionWaived: string[]
+ /** The set the pure decision takes. Rebuilt per change, so identity is a usable change signal. */
+ sessionWaivedSet: ReadonlySet<string>
+ waiveForSession(verb: string): void
+ revokeForSession(verb: string): void
+}
+
+export const useControlConfirm = create<ControlConfirmState>((set) => ({
+ sessionWaived: [],
+ sessionWaivedSet: new Set<string>(),
+ waiveForSession: (verb) =>
+ set((s) => {
+ // The table decides, here as well as in `decideControlConfirm` — a caller cannot grant a
+ // waiver for a verb that may not be waived, even by passing the wrong string.
+ if (!isWaivableVerb(verb) || s.sessionWaived.includes(verb)) return s
+ const next = [...s.sessionWaived, verb]
+ return { sessionWaived: next, sessionWaivedSet: new Set(next) }
+ }),
+ revokeForSession: (verb) =>
+ set((s) => {
+ if (!s.sessionWaived.includes(verb)) return s
+ const next = s.sessionWaived.filter((v) => v !== verb)
+ return { sessionWaived: next, sessionWaivedSet: new Set(next) }
+ })
+}))
+
+/** The set for a non-reactive reader (the control dispatch runs inside an IPC listener). */
+export function sessionWaivedVerbs(): ReadonlySet<string> {
+ return useControlConfirm.getState().sessionWaivedSet
+}
diff --git a/src/renderer/state/controlConfirmGate.ts b/src/renderer/state/controlConfirmGate.ts
new file mode 100644
index 000000000..7d3cbb2ae
--- /dev/null
+++ b/src/renderer/state/controlConfirmGate.ts
@@ -0,0 +1,46 @@
+import {
+ decideControlConfirm,
+ sanitizeControlConfirmWaivers,
+ type ControlConfirmDecision,
+ type ControlConfirmWaivers
+} from '@shared/control-confirm'
+import { resolvePermissionModeWithSource } from '@shared/agents/config'
+
+import { useProjects } from './projects'
+import { useSettings } from './settings'
+import { sessionWaivedVerbs } from './controlConfirm'
+
+/**
+ * Binds the pure `decideControlConfirm` to the live stores — the canvas-control confirm's
+ * counterpart to `activePermissionMode`, and in its own module for the same reason that one is:
+ * `projects.ts` imports `workspace.ts`, so a store that imports the projects store cannot live
+ * anywhere those two can reach.
+ *
+ * The permission-mode half is where the git-shared-file trap is closed, and BOTH locks are applied
+ * here: the machine-local `bypassMode` opt-in comes out of `settings.json`, and
+ * `resolvePermissionModeWithSource` reports whether the resolved mode was the user's own GLOBAL
+ * choice or an override that arrived in `.nodeterm/project.json` — which travels to everyone who
+ * clones the repo. Only `'global'` can waive anything.
+ *
+ * **The version gate is deliberately NOT applied.** `gatePermissionMode` exists to degrade `auto`
+ * to a bare command line for an old Claude CLI; it never touches `bypassPermissions`, and asking
+ * it here would tie a security decision to a `claude --version` probe on a canvas whose agent may
+ * not even be claude.
+ */
+export function controlConfirmDecision(verb: string): ControlConfirmDecision {
+ const { settings } = useSettings.getState()
+ const { getProject, activeProjectId } = useProjects.getState()
+ const { mode, source } = resolvePermissionModeWithSource(getProject(activeProjectId), settings)
+ return decideControlConfirm({
+ verb,
+ sessionWaived: sessionWaivedVerbs(),
+ persisted: activeControlConfirmWaivers(),
+ permissionMode: mode,
+ permissionModeSource: source
+ })
+}
+
+/** The sanitized persisted waivers. `settings.json` is hand-editable, so this is the ONE read. */
+export function activeControlConfirmWaivers(): ControlConfirmWaivers {
+ return sanitizeControlConfirmWaivers(useSettings.getState().settings.controlConfirmWaivers)
+}
diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.ts
index a48f4eaed..c8d8ce28c 100644
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@ -695,7 +695,32 @@ export function resolvePermissionMode(
project: { defaultPermissionMode?: AgentPermissionMode } | undefined,
settings: { claudePermissionMode: AgentPermissionMode }
): AgentPermissionMode {
- if (isPermissionMode(project?.defaultPermissionMode)) return project.defaultPermissionMode
- if (isPermissionMode(settings.claudePermissionMode)) return settings.claudePermissionMode
- return DEFAULT_PERMISSION_MODE
+ return resolvePermissionModeWithSource(project, settings).mode
+}
+
+/**
+ * The same resolution, plus WHO chose the mode — and that second half is a security fact, not a
+ * nicety.
+ *
+ * `project.defaultPermissionMode` is persisted to `.nodeterm/project.json`, which is git-shared:
+ * a `bypassPermissions` override travels to everyone who clones the repo. So anything that
+ * LOOSENS a gate on the strength of the mode (today: the canvas-control confirm waiver,
+ * `decideControlConfirm` in @shared/control-confirm) must be able to tell "the user set this
+ * globally on this machine" from "this arrived in somebody's repo". `'default'` is its own answer
+ * rather than being folded into `'global'`: nobody has chosen anything, and a caller that treats
+ * an unset setting as a deliberate global choice is reading consent into silence.
+ *
+ * `resolvePermissionMode` delegates here so the two can never disagree about which half wins.
+ */
+export function resolvePermissionModeWithSource(
+ project: { defaultPermissionMode?: AgentPermissionMode } | undefined,
+ settings: { claudePermissionMode: AgentPermissionMode }
+): { mode: AgentPermissionMode; source: 'project' | 'global' | 'default' } {
+ if (isPermissionMode(project?.defaultPermissionMode)) {
+ return { mode: project.defaultPermissionMode, source: 'project' }
+ }
+ if (isPermissionMode(settings.claudePermissionMode)) {
+ return { mode: settings.claudePermissionMode, source: 'global' }
+ }
+ return { mode: DEFAULT_PERMISSION_MODE, source: 'default' }
}
diff --git a/src/shared/agents/permission-mode-source.test.ts b/src/shared/agents/permission-mode-source.test.ts
new file mode 100644
index 000000000..d025449b4
--- /dev/null
+++ b/src/shared/agents/permission-mode-source.test.ts
@@ -0,0 +1,68 @@
+import { describe, expect, it } from 'vitest'
+
+import { resolvePermissionMode, resolvePermissionModeWithSource } from './config'
+
+/**
+ * WHO chose the permission mode is a security fact, not a nicety: `project.defaultPermissionMode`
+ * is persisted to `.nodeterm/project.json`, which is git-shared, so a `bypassPermissions` there
+ * arrives with somebody else's repository. Anything that loosens a gate on the strength of the
+ * mode (the canvas-control confirm waiver) must be able to tell that from a mode the user set on
+ * this machine.
+ */
+describe('resolvePermissionModeWithSource', () => {
+ it('reports a project override as `project`', () => {
+ expect(
+ resolvePermissionModeWithSource(
+ { defaultPermissionMode: 'bypassPermissions' },
+ { claudePermissionMode: 'manual' }
+ )
+ ).toEqual({ mode: 'bypassPermissions', source: 'project' })
+ })
+
+ it('reports the global setting as `global`', () => {
+ expect(
+ resolvePermissionModeWithSource(undefined, { claudePermissionMode: 'bypassPermissions' })
+ ).toEqual({ mode: 'bypassPermissions', source: 'global' })
+ // An absent override is not a choice either way.
+ expect(
+ resolvePermissionModeWithSource({}, { claudePermissionMode: 'plan' })
+ ).toEqual({ mode: 'plan', source: 'global' })
+ })
+
+ it('reports an unchosen mode as `default`, NOT `global`', () => {
+ // Nobody has decided anything, and a caller that read this as a deliberate global choice would
+ // be reading consent into silence. (`auto` is the shipped default, so it cannot waive anything
+ // anyway — but the distinction must not depend on which mode happens to be the default.)
+ expect(
+ resolvePermissionModeWithSource(undefined, { claudePermissionMode: 'nonsense' as never })
+ ).toEqual({ mode: 'auto', source: 'default' })
+ })
+
+ it('ignores an invalid project override, exactly as resolvePermissionMode does', () => {
+ // project.json is hand-editable; a bogus value must fall through, not become a mode.
+ expect(
+ resolvePermissionModeWithSource(
+ { defaultPermissionMode: 'bypass' as never },
+ { claudePermissionMode: 'manual' }
+ )
+ ).toEqual({ mode: 'manual', source: 'global' })
+ })
+
+ it('agrees with resolvePermissionMode on the mode, always', () => {
+ const projects = [
+ undefined,
+ {},
+ { defaultPermissionMode: 'plan' as const },
+ { defaultPermissionMode: 'bypassPermissions' as const },
+ { defaultPermissionMode: 'junk' as never }
+ ]
+ const settings = ['manual', 'auto', 'acceptEdits', 'bypassPermissions', 'junk' as never] as const
+ for (const p of projects) {
+ for (const claudePermissionMode of settings) {
+ expect(resolvePermissionModeWithSource(p, { claudePermissionMode }).mode).toBe(
+ resolvePermissionMode(p, { claudePermissionMode })
+ )
+ }
+ }
+ })
+})
diff --git a/src/shared/control-confirm.test.ts b/src/shared/control-confirm.test.ts
new file mode 100644
index 000000000..4ade5289d
--- /dev/null
+++ b/src/shared/control-confirm.test.ts
@@ -0,0 +1,186 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ CONFIRM_WAIVABLE_VERBS,
+ CONTROL_REQUEST_TIMEOUT_MS,
+ confirmExpiresAt,
+ decideControlConfirm,
+ isWaivableVerb,
+ sanitizeControlConfirmWaivers,
+ waivedNotice
+} from './control-confirm'
+import { DESTRUCTIVE_VERBS } from './control-verbs'
+
+describe('which verbs may be waived', () => {
+ it('is a strict subset of the confirm-gated set', () => {
+ for (const v of CONFIRM_WAIVABLE_VERBS) expect(DESTRUCTIVE_VERBS.has(v)).toBe(true)
+ expect(CONFIRM_WAIVABLE_VERBS.size).toBeLessThan(DESTRUCTIVE_VERBS.size)
+ })
+
+ it('never admits open-project, whatever the user asks for', () => {
+ expect(isWaivableVerb('open-project')).toBe(false)
+ // Every lever: the app-run set, the persisted list, and the bypass pair.
+ expect(
+ decideControlConfirm({ verb: 'open-project', sessionWaived: new Set(['open-project']) })
+ ).toEqual({ skip: false, via: null })
+ expect(
+ decideControlConfirm({ verb: 'open-project', persisted: { always: ['open-project'] } })
+ ).toEqual({ skip: false, via: null })
+ expect(
+ decideControlConfirm({
+ verb: 'open-project',
+ persisted: { bypassMode: true },
+ permissionMode: 'bypassPermissions',
+ permissionModeSource: 'global'
+ })
+ ).toEqual({ skip: false, via: null })
+ })
+
+ it('does not answer for a verb that has no dialog at all', () => {
+ expect(isWaivableVerb('list')).toBe(false)
+ expect(decideControlConfirm({ verb: 'list', sessionWaived: new Set(['list']) }).skip).toBe(false)
+ })
+})
+
+describe('decideControlConfirm — the default is to ask', () => {
+ it('asks when nothing is waived', () => {
+ for (const verb of ['write', 'close']) {
+ expect(decideControlConfirm({ verb })).toEqual({ skip: false, via: null })
+ }
+ })
+
+ it('honours an app-run waiver, per verb', () => {
+ expect(decideControlConfirm({ verb: 'close', sessionWaived: new Set(['close']) })).toEqual({
+ skip: true,
+ via: 'session'
+ })
+ // Waiving `close` says nothing about `write` — the whole point of keying on the verb.
+ expect(decideControlConfirm({ verb: 'write', sessionWaived: new Set(['close']) }).skip).toBe(
+ false
+ )
+ })
+
+ it('honours a permanent waiver', () => {
+ expect(decideControlConfirm({ verb: 'write', persisted: { always: ['write'] } })).toEqual({
+ skip: true,
+ via: 'always'
+ })
+ })
+
+ it('re-checks a hand-edited `always` entry against the table', () => {
+ // Reachable: settings.json is hand-editable and the sanitizer runs at read, but the decision
+ // must not depend on somebody having called it.
+ expect(
+ decideControlConfirm({ verb: 'open-project', persisted: { always: ['open-project'] } }).skip
+ ).toBe(false)
+ })
+})
+
+describe('the bypassPermissions branch needs BOTH locks', () => {
+ const bypassGlobal = {
+ verb: 'close',
+ permissionMode: 'bypassPermissions',
+ permissionModeSource: 'global'
+ } as const
+
+ it('skips when the machine opted in AND the mode is the user own global choice', () => {
+ expect(decideControlConfirm({ ...bypassGlobal, persisted: { bypassMode: true } })).toEqual({
+ skip: true,
+ via: 'bypass'
+ })
+ })
+
+ it('asks when the machine did not opt in', () => {
+ expect(decideControlConfirm({ ...bypassGlobal }).skip).toBe(false)
+ expect(decideControlConfirm({ ...bypassGlobal, persisted: { bypassMode: false } }).skip).toBe(
+ false
+ )
+ })
+
+ it('asks when bypassPermissions came from the PROJECT file — the cloned-repo trap', () => {
+ // `.nodeterm/project.json` is git-shared, so `project.defaultPermissionMode` arrives with
+ // somebody else's repository. It must never waive a local confirmation.
+ expect(
+ decideControlConfirm({
+ verb: 'close',
+ persisted: { bypassMode: true },
+ permissionMode: 'bypassPermissions',
+ permissionModeSource: 'project'
+ }).skip
+ ).toBe(false)
+ })
+
+ it('asks when nobody chose the mode at all', () => {
+ expect(
+ decideControlConfirm({
+ verb: 'close',
+ persisted: { bypassMode: true },
+ permissionMode: 'bypassPermissions',
+ permissionModeSource: 'default'
+ }).skip
+ ).toBe(false)
+ })
+
+ it('asks under every other permission mode', () => {
+ for (const mode of ['manual', 'auto', 'acceptEdits', 'plan'] as const) {
+ expect(
+ decideControlConfirm({
+ verb: 'close',
+ persisted: { bypassMode: true },
+ permissionMode: mode,
+ permissionModeSource: 'global'
+ }).skip
+ ).toBe(false)
+ }
+ })
+})
+
+describe('sanitizeControlConfirmWaivers — settings.json is hostile input', () => {
+ it('drops unwaivable and unknown verb names', () => {
+ expect(
+ sanitizeControlConfirmWaivers({ always: ['close', 'open-project', 'rm -rf', 42] })
+ ).toEqual({ always: ['close'] })
+ })
+
+ it('collapses duplicates and omits an empty list', () => {
+ expect(sanitizeControlConfirmWaivers({ always: ['write', 'write'] })).toEqual({
+ always: ['write']
+ })
+ expect(sanitizeControlConfirmWaivers({ always: [] })).toEqual({})
+ })
+
+ it('accepts only a literal true for bypassMode', () => {
+ expect(sanitizeControlConfirmWaivers({ bypassMode: true })).toEqual({ bypassMode: true })
+ for (const v of ['true', 1, {}, null]) {
+ expect(sanitizeControlConfirmWaivers({ bypassMode: v })).toEqual({})
+ }
+ })
+
+ it('degrades any non-object to "ask"', () => {
+ for (const raw of [undefined, null, 'close', 7, ['close']]) {
+ expect(sanitizeControlConfirmWaivers(raw)).toEqual({})
+ }
+ })
+})
+
+describe('the dialog deadline', () => {
+ it('is main own request budget, measured from the renderer receipt', () => {
+ expect(confirmExpiresAt(1_000)).toBe(1_000 + CONTROL_REQUEST_TIMEOUT_MS)
+ // Later than main started waiting, never earlier: the renderer receives the request after the
+ // timer starts, so the dialog can never abandon a request main would still accept.
+ expect(confirmExpiresAt(1_000)).toBeGreaterThan(CONTROL_REQUEST_TIMEOUT_MS)
+ })
+})
+
+describe('waivedNotice', () => {
+ it('names the action and the waiver that let it through', () => {
+ expect(waivedNotice('Agent "x" closed 3 nodes', 'session')).toContain('this app run')
+ expect(waivedNotice('Agent "x" closed 3 nodes', 'always')).toContain('permanently')
+ expect(waivedNotice('Agent "x" closed 3 nodes', 'bypass')).toContain('Bypass')
+ // Every variant points at where to undo it — a waived destructive action is never silent.
+ for (const via of ['session', 'always', 'bypass'] as const) {
+ expect(waivedNotice('did a thing', via)).toContain('Settings → Agents')
+ expect(waivedNotice('did a thing', via)).toContain('did a thing')
+ }
+ })
+})
diff --git a/src/shared/control-confirm.ts b/src/shared/control-confirm.ts
new file mode 100644
index 000000000..895b77454
--- /dev/null
+++ b/src/shared/control-confirm.ts
@@ -0,0 +1,189 @@
+// The human gate in front of a canvas-control agent's DESTRUCTIVE verbs: who may waive the
+// confirm dialog, for how long, and what may never waive it.
+//
+// WHY THIS FILE EXISTS AT ALL. The confirm dialog raised by `write` / `close` / `open-project`
+// (Canvas.tsx's control dispatch) is the only place a human stands between an agent holding
+// NODETERM_CANVAS_CONTROL and the user's workspace. Per-node identity is not fully enforced until
+// `NODE_IDENTITY_STRICT_AFTER` (docs/node-identity.md), so until then a `legacy` caller — one we
+// cannot judge — still reaches that dispatch. Everything here loosens that gate, so every rule is
+// written to fail CLOSED, and every loosening is a setting the user can see and revoke.
+//
+// SURFACES. This is the DESKTOP gate and only the desktop gate. Server Edition canvas control
+// (opt-in, `NODETERM_SERVER_CANVAS_CONTROL=1`) is HEADLESS and has no dialog to waive: its
+// `close` is gated by verified node identity plus process-local creator ownership
+// (`HeadlessNodeFactory.close` — "did this caller spawn that node during this server run"), which
+// is a different mechanism, not a weaker copy of this one. Nothing here loosens it, and a waiver
+// must never be plumbed into it: the server's rule does not ask a human at all, so "the human
+// said don't ask again" has nothing to attach to. Mobile is N/A (the phone issues no control
+// verbs).
+//
+// IN `src/shared` for the same two-sided reason as `control-verbs.ts`: the renderer decides
+// (Canvas.tsx + the Settings section) and main owns the request timeout the expiry reads, and
+// `tsconfig.web` gives the renderer no path into `src/main` or `src/core`.
+
+import type { AgentPermissionMode } from './agents/config'
+
+/**
+ * How long main waits for the renderer's answer to one control request
+ * (`src/main/index.ts`, `setControlHandler`'s pending-control timer).
+ *
+ * MOVED HERE from a local const in main because the renderer now needs the same number: a dialog
+ * whose request has already expired must collect itself instead of sitting on `confirmBusy` and
+ * refusing every later request (see `confirmExpiresAt`). Two copies of this number is exactly the
+ * drift this repo keeps paying for — main's timer and the dialog's deadline are one fact.
+ */
+export const CONTROL_REQUEST_TIMEOUT_MS = 120_000
+
+/**
+ * The deadline a control confirm dialog should collect itself at, given when the renderer received
+ * the request.
+ *
+ * Deliberately measured from the RENDERER's receipt, which is strictly LATER than main's — the IPC
+ * hop sits in between — so the dialog always expires a hair AFTER main gave up, never before. The
+ * other direction would abandon a dialog whose reply main would still have accepted.
+ */
+export function confirmExpiresAt(receivedAt: number): number {
+ return receivedAt + CONTROL_REQUEST_TIMEOUT_MS
+}
+
+/**
+ * The destructive verbs whose confirm a user MAY waive — a deliberate subset of
+ * `DESTRUCTIVE_VERBS`.
+ *
+ * `open-project` is absent ON PURPOSE and must stay absent. It is the only one of the three that
+ * widens the app's blast radius rather than acting inside it: it registers a new directory as a
+ * project and records a grant the caller then feeds to `--project`. It also cannot produce the
+ * dialog storm this waiver exists to end — its consent is already deduped per (caller, project)
+ * by `recordAttachConsent`, so a repeat registration is silent anyway. A verb here must be one
+ * whose repetition is the problem; `open-project`'s repetition is already solved.
+ */
+export const CONFIRM_WAIVABLE_VERBS: ReadonlySet<string> = new Set(['write', 'close'])
+
+/** May this verb's confirm be waived at all? Table-driven, so "open-project can never be waived"
+ * is a tested fact rather than a line somebody forgot to write at one of three call sites. */
+export function isWaivableVerb(verb: string): boolean {
+ return CONFIRM_WAIVABLE_VERBS.has(verb)
+}
+
+/**
+ * The persisted (machine-local) half of the waivers — `settings.controlConfirmWaivers`.
+ *
+ * NEVER `project.json`. A permission mode already travels through a git-shared project file, and
+ * the whole trap this feature had to close is a cloned repo turning somebody's confirms off (see
+ * `bypassMode`). A waiver is a statement about THIS machine's trust in its own agents; it has no
+ * business in a file a teammate can commit.
+ */
+export interface ControlConfirmWaivers {
+ /** Verbs waived PERMANENTLY on this machine. Only ever set from Settings → Agents — the dialog
+ * itself can grant the app-run waiver and nothing more, because a permanent security waiver
+ * must not be one stray checkbox click away in a dialog that appeared under the user's hands. */
+ always?: string[]
+ /**
+ * Skip the confirm while the resolved permission mode is `bypassPermissions` — the "I already
+ * told this agent to stop asking me" case.
+ *
+ * OFF by default, and it is an opt-in for a measured reason, not caution. The permission mode
+ * lives in `.nodeterm/project.json`, which is git-shared: `project.defaultPermissionMode =
+ * 'bypassPermissions'` travels to everyone who clones the repo. Binding the confirm to the mode
+ * alone would let a cloned repository silently disable a user's destructive-action gate. So
+ * there are TWO locks and both must be open: this machine-local opt-in, AND the mode having
+ * come from the user's own GLOBAL setting (`permissionModeSource === 'global'`). A project
+ * override never waives anything, whatever this is set to.
+ */
+ bypassMode?: boolean
+}
+
+/**
+ * Where the resolved permission mode came from. `resolvePermissionMode` answers WHAT the mode is;
+ * this answers WHO said so, which is the only thing that makes the bypass waiver safe.
+ */
+export type PermissionModeSource = 'project' | 'global' | 'default'
+
+/** Why a confirm was skipped — carried into the user-visible notice, so a waived destructive
+ * action still announces itself and names the waiver that let it through. */
+export type ConfirmWaiverVia = 'session' | 'always' | 'bypass'
+
+export interface ControlConfirmDecision {
+ /** True = apply the verb without a dialog. */
+ skip: boolean
+ /** Which waiver decided it (null when `skip` is false). */
+ via: ConfirmWaiverVia | null
+}
+
+const ASK: ControlConfirmDecision = { skip: false, via: null }
+
+/**
+ * Does this destructive verb still need a dialog?
+ *
+ * Pure, and the ONLY place the three waivers are weighed — the dispatch cases call this and do as
+ * they are told, so there is one table to audit rather than three `if`s in an 11,000-line
+ * component.
+ *
+ * Order is precedence, and it is fail-closed at every step: an unwaivable verb never skips (the
+ * `open-project` rule, applied before anything else is even read), a hand-edited `always` entry
+ * naming an unwaivable verb is ignored rather than honoured, and the bypass lock demands both keys.
+ */
+export function decideControlConfirm(input: {
+ verb: string
+ /** Verbs waived for THIS APP RUN. In-memory only (renderer/state/controlConfirm.ts): a waiver
+ * the user granted in a dialog dies with the process, which is what makes it the safe default. */
+ sessionWaived?: ReadonlySet<string>
+ persisted?: ControlConfirmWaivers
+ /** The mode a session launched right now would start in, and who chose it. */
+ permissionMode?: AgentPermissionMode
+ permissionModeSource?: PermissionModeSource
+}): ControlConfirmDecision {
+ const { verb, sessionWaived, persisted, permissionMode, permissionModeSource } = input
+ // The gate that outranks every waiver: this verb's confirm is not the user's to waive.
+ if (!isWaivableVerb(verb)) return ASK
+ if (sessionWaived?.has(verb)) return { skip: true, via: 'session' }
+ // No second table check here: the `isWaivableVerb(verb)` gate above already refuses a
+ // hand-edited `always: ["open-project"]` before this line is reached (proven by the
+ // open-project test's `always` case, and by mutating that gate). A duplicate check would be
+ // unreachable code claiming to be a safeguard — this repo has shipped that mistake, and a
+ // safeguard no test can turn red is a comment, not a mechanism.
+ if (persisted?.always?.includes(verb)) return { skip: true, via: 'always' }
+ // BOTH locks, per the `bypassMode` doc above: the machine-local opt-in and a mode the user set
+ // globally. A `bypassPermissions` that arrived in a cloned `project.json` opens neither.
+ if (
+ persisted?.bypassMode === true &&
+ permissionMode === 'bypassPermissions' &&
+ permissionModeSource === 'global'
+ ) {
+ return { skip: true, via: 'bypass' }
+ }
+ return ASK
+}
+
+/**
+ * Read `settings.controlConfirmWaivers` the way the gates must read it: hand-editable JSON,
+ * sanitized at READ, exactly as `sanitizeKeybindingOverrides` is (`settings.json` is a file users
+ * edit, and a garbage value there must degrade to "ask", never to "skip").
+ *
+ * Returns a fresh normalized object: unknown/unwaivable verb names dropped, duplicates collapsed,
+ * `bypassMode` only ever the literal `true`.
+ */
+export function sanitizeControlConfirmWaivers(raw: unknown): ControlConfirmWaivers {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {}
+ const o = raw as { always?: unknown; bypassMode?: unknown }
+ const always = Array.isArray(o.always)
+ ? [...new Set(o.always.filter((v): v is string => typeof v === 'string' && isWaivableVerb(v)))]
+ : []
+ const out: ControlConfirmWaivers = {}
+ if (always.length) out.always = always
+ if (o.bypassMode === true) out.bypassMode = true
+ return out
+}
+
+/** The user-visible line a WAIVED destructive action raises (Canvas's info banner). A waiver
+ * makes the dialog go away — it must not make the ACTION go quiet, which is why this exists and
+ * why it names the waiver that let the action through. */
+export function waivedNotice(action: string, via: ConfirmWaiverVia): string {
+ const because =
+ via === 'session'
+ ? 'confirm waived for this app run'
+ : via === 'always'
+ ? 'confirm waived permanently'
+ : 'confirm waived while the global permission mode is Bypass'
+ return `${action} — ${because} (Settings → Agents).`
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 5d3f4a421..2df752497 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -5,6 +5,7 @@ import type { CloneProgress } from './clone-url'
import type { KeybindingOverrides, TerminalShortcutPolicy } from './keybindings'
import type { NormalizedAgentEvent } from './agents/normalize'
import type { AgentId, AgentPermissionMode, BuiltinAgentId, PromptInjectionMode } from './agents/config'
+import type { ControlConfirmWaivers } from './control-confirm'
import type { AgentMessageDeliverRequest, AgentMessageReply } from './agents/agent-messaging'
import type { BrowserLeasePush } from './browser-indicator'
import type { GroupWorktree } from './worktree'
@@ -1648,6 +1649,15 @@ export interface Settings {
* strands a live session gets their canvas back without downgrading the app. Neither value ever
* admits a forged token. */
hookIdentityStrict?: boolean
+ /** Machine-local waivers for the canvas-control destructive confirm dialog
+ * (@shared/control-confirm). Absent — and absent from DEFAULT_SETTINGS — means "always ask",
+ * which is the pre-feature behavior bit for bit.
+ *
+ * MACHINE-LOCAL BY CONSTRUCTION, and the reason is the trap this closed: a permission mode
+ * rides `.nodeterm/project.json` and is git-shared, so anything keyed on the mode alone could
+ * be turned off for a user by a repository they cloned. A waiver is a statement about this
+ * machine's trust in its own agents, so it lives here and NEVER in a project file. */
+ controlConfirmWaivers?: ControlConfirmWaivers
}
export const DEFAULT_SETTINGS: Settings = {