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): a "don't ask again" that lasts, scoped to one project

enesb7dbcd18a8bb
diff --git a/CLAUDE.md b/CLAUDE.md
index d819075bb..ce9248d38 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2280,15 +2280,38 @@ else, and its context links must keep classifying across restarts).
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`).
+ - **"Don't ask again" is bounded by SCOPE, not by permanence** (2026-09, revised). The checkbox
+ offers two reaches and defaults to the narrower: **"while nodeterm is running"** — the
+ transient `state/controlConfirm.ts`, memory only (not `settings.json`, not `localStorage`), per
+ VERB, so quitting restores the gate — or **"always in <project name>"**, persisted in
+ `settings.controlConfirmWaivers.projects` as `{ [projectId]: verbs }`. The machine-WIDE
+ `always` is still reachable only from Settings → Agents, where the option says "permanently":
+ a dialog that appeared under the user's hands must not switch a destructive gate off
+ *everywhere* on one stray click. The per-project scope is what makes the offer honest — an
+ app-run waiver is not what a user who ticks "don't ask again" means, and with only that and a
+ machine-wide switch the real choices were "be asked forever" or "turn it off everywhere".
+ Load-bearing details: (1) the waiver is keyed on the project the call **acts on**
+ (`ctlProject`), not the active one — canvas control answers a background agent in its own
+ project without moving the user's tab (@shared/control-off-screen), so reading the project on
+ screen would grant, or honour, a waiver in the wrong repo; the same argument applies to the
+ permission MODE the bypass lock weighs, which is why `controlConfirmDecision` takes a project
+ id and resolves both from it. (2) It is **machine-local** — never `.nodeterm/project.json`,
+ which is git-shared; the whole trap `bypassMode` needs two locks for. (3) It is **pruned** on
+ every write (`pruneControlConfirmWaivers`, the rule `pruneCollapsedItems` states for
+ `sidebarCollapsedItems`) against EVERY project including CLOSED ones — a closed project is
+ parked, not gone — because settings.json is forever and a stale entry is a live security
+ waiver keyed to an id nothing can name. The id being granted survives that prune because the
+ merge happens after it, not by an exemption inside it; a safeguard no test can turn red is a
+ comment, not a mechanism. (4) Precedence is narrowest-first among the persisted grants
+ (session → project → always → bypass), so the notice names the waiver the user most likely
+ wants back. (5) A waiver granted by a CANCEL must not exist at all (the grant hangs off
+ `onConfirm`, pinned by `control-destructive.test.ts` and
+ `control-confirm-scope.source.test.ts`), and a per-project grant that cannot be made (no
+ project owns the call) falls back to the app-run waiver rather than silently to nothing.
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.
+ which names the waiver that let it through — and, for the project scope, the PROJECT, since
+ "this project" would point at whatever the user happens to be looking at — and every
+ per-project waiver is listed with a Revoke in Settings → Agents.
- **`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
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index e6069fb5a..472962343 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -127,12 +127,21 @@ lane unaffected.
- **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.
+ canvas-control destructive confirm is the pattern to copy (`@shared/control-confirm`): a CANCEL
+ never grants anything, a waived action still announces itself on screen and NAMES the waiver that
+ let it through, and 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.
+ **What a dialog may grant is bounded by SCOPE, not by permanence.** It offers "while nodeterm is
+ running" (in-memory — not `settings.json`, not `localStorage`, so quitting restores the gate) or
+ "always in this project" (machine-local, keyed by project id, pruned like
+ `settings.sidebarCollapsedItems`). The machine-WIDE waiver stays Settings-only, because that is
+ the one a stray click in a dialog that appeared under the user's hands must not be able to grant.
+ Offering only the app-run one was its own failure: it is not what a user who ticks "don't ask
+ again" means, so the real choices were "be asked forever" or "turn it off everywhere". Two rules
+ come with the project scope: it is keyed on the project the call ACTS ON (canvas control routes
+ by source, so that is often not the project on screen), and it is machine-local — never
+ `.nodeterm/project.json`, which is git-shared, or a cloned repo could switch someone's confirms
+ off.
- **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
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index ff933a617..95cf5038a 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -553,7 +553,7 @@ import {
CONTROL_REQUEST_TIMEOUT_MS
} from '@shared/control-confirm'
import { useControlConfirm } from '../state/controlConfirm'
-import { controlConfirmDecision } from '../state/controlConfirmGate'
+import { controlConfirmDecision, waiveControlConfirmForProject } from '../state/controlConfirmGate'
import {
bulkCloseMessage,
parseCloseTargets,
@@ -682,6 +682,17 @@ interface ConfirmState {
* waiver at click time, where the state is current.
*/
waiveVerb?: string
+ /**
+ * The project a "always in this project" waiver would be granted for, and its NAME for the
+ * checkbox copy. The CALLER's project, not the active one: canvas control routes by source and
+ * a background agent's `write`/`close` is answered in its own project without the user's tab
+ * moving (@shared/control-off-screen), so the dialog must offer — and grant — a waiver for the
+ * project the call actually acts on. Offering "this project" while meaning the one on screen
+ * would grant a waiver in the wrong repo, which is the exact failure the per-project scope
+ * exists to prevent.
+ */
+ waiveProjectId?: string
+ waiveProjectName?: 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
@@ -1643,6 +1654,9 @@ export function Canvas() {
// 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)
+ /** How far the tick above reaches. `session` is the DEFAULT and the pre-existing behaviour — a
+ * waiver a dialog grants must stay the bounded one unless the user says otherwise. */
+ const [controlWaiveScope, setControlWaiveScope] = useState<'session' | 'project'>('session')
/**
* An agent-requested confirm collects itself when its REQUEST has expired.
*
@@ -11822,13 +11836,20 @@ export function Canvas() {
// 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)
+ // `ctlProject?.id`, not the active project: the per-project waiver — and the
+ // permission mode the bypass lock reads — belong to the project this call ACTS ON,
+ // which since @shared/control-off-screen need not be the one on screen.
+ const writeWaiver = controlConfirmDecision(verb, ctlProject?.id)
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)
+ text: waivedNotice(
+ `Agent "${srcTitle}" wrote to ${args.node}`,
+ writeWaiver.via,
+ ctlProject?.name
+ )
})
await runWrite()
return
@@ -11852,11 +11873,14 @@ export function Canvas() {
}
// Destructive → confirm. Replies on confirm AND cancel.
setControlWaive(false)
+ setControlWaiveScope('session')
setConfirm({
message: `Agent "${srcTitle}" wants to send to ${args.node}:\n\n${args.text ?? ''}`,
confirmLabel: 'Send',
requestedBy: srcTitle,
waiveVerb: isWaivableVerb(verb) ? verb : undefined,
+ waiveProjectId: ctlProject?.id,
+ waiveProjectName: ctlProject?.name,
expiresAt: confirmExpiresAt(Date.now()),
onExpire: () => reply({ ok: false, error: 'expired before the user answered' }),
onConfirm: async () => {
@@ -11920,7 +11944,7 @@ export function Canvas() {
})
}
// Waived? Same decision table as `write` (@shared/control-confirm).
- const closeWaiver = controlConfirmDecision(verb)
+ const closeWaiver = controlConfirmDecision(verb, ctlProject?.id)
if (closeWaiver.via) {
setNotice({
kind: 'info',
@@ -11928,7 +11952,8 @@ export function Canvas() {
closeIds.length === 1
? `Agent "${srcTitle}" closed ${closeIds[0]}`
: `Agent "${srcTitle}" closed ${closeIds.length} nodes`,
- closeWaiver.via
+ closeWaiver.via,
+ ctlProject?.name
)
})
runClose()
@@ -11943,12 +11968,15 @@ export function Canvas() {
}
// Destructive → confirm. Replies on confirm AND cancel.
setControlWaive(false)
+ setControlWaiveScope('session')
setConfirm({
message: closeMessage,
requestedBy: srcTitle,
confirmLabel: closeLabel,
danger: true,
waiveVerb: isWaivableVerb(verb) ? verb : undefined,
+ waiveProjectId: ctlProject?.id,
+ waiveProjectName: ctlProject?.name,
expiresAt: confirmExpiresAt(Date.now()),
onExpire: () => reply({ ok: false, error: 'expired before the user answered' }),
onConfirm: () => {
@@ -14768,24 +14796,48 @@ 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}
- // "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.
+ // "Don't ask again" — offered ONLY for a verb the shared table admits, and offered with
+ // a SCOPE, because the app-run-only waiver this used to grant is not what a user who
+ // ticks that box means: it lasts until they quit, and the only durable answer lived in
+ // Settings as a MACHINE-WIDE switch, so the realistic choices were "be asked forever" or
+ // "turn it off everywhere". The narrower durable grant is per project, which is the most
+ // a dialog that appeared under the user's hands may hand out — the machine-wide `always`
+ // stays Settings-only for exactly the reason it always did. Default stays `session`, so
+ // a user who ticks and clicks through gets the old, bounded behaviour.
+ // 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",
+ label: "Don't ask again",
checked: controlWaive,
- onChange: setControlWaive
+ onChange: setControlWaive,
+ scopes: [
+ { value: 'session', label: 'While nodeterm is running' },
+ {
+ value: 'project',
+ // The project NAME, not "this project": the call may well be acting on a
+ // canvas the user is not looking at, so "this" would point at the wrong one.
+ label: confirm.waiveProjectName
+ ? `Always in "${confirm.waiveProjectName}"`
+ : 'Always in this project'
+ }
+ ],
+ scope: controlWaiveScope,
+ onScopeChange: (v) => setControlWaiveScope(v === 'project' ? 'project' : 'session')
}
: undefined
}
onConfirm={() => {
// Granted on CONFIRM only. A denial must never widen anything, whatever is ticked.
if (confirm.waiveVerb && controlWaive) {
- useControlConfirm.getState().waiveForSession(confirm.waiveVerb)
+ // The per-project grant can FAIL (no project owns this call), and it must not fail
+ // silently into nothing: fall back to the app-run waiver the user would have got
+ // before, so a tick always buys what the box promised.
+ const scoped =
+ controlWaiveScope === 'project' &&
+ waiveControlConfirmForProject(confirm.waiveVerb, confirm.waiveProjectId)
+ if (!scoped) useControlConfirm.getState().waiveForSession(confirm.waiveVerb)
}
confirm.onConfirm()
}}
diff --git a/src/renderer/canvas/control-confirm-scope.source.test.ts b/src/renderer/canvas/control-confirm-scope.source.test.ts
new file mode 100644
index 000000000..98365affa
--- /dev/null
+++ b/src/renderer/canvas/control-confirm-scope.source.test.ts
@@ -0,0 +1,105 @@
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+
+/**
+ * STRUCTURAL pins for the canvas-control confirm's "Don't ask again" SCOPE — the checkbox that now
+ * offers "while nodeterm is running" or "always in this project".
+ *
+ * Source-level for the usual reason: the dialog is built inline in a 14,000-line component's render
+ * and the grant happens in its `onConfirm`, neither of which has a unit seam. The BEHAVIOUR of both
+ * halves is proven against real primitives elsewhere — the decision table in
+ * `shared/control-confirm.test.ts`, the store write in `state/controlConfirmGate.test.ts`, the
+ * Settings row in `AgentsSection.controlConfirm.test.tsx`. What is pinned here is the wiring
+ * between them, where a mistake is silent: a waiver granted for the wrong project, granted on a
+ * DENIAL, or carried over from the previous dialog.
+ */
+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+
+/** The control confirm's dialog element, from its option block to its `onCancel`. */
+function dialogBody(): string {
+ const start = src.indexOf('confirm.waiveVerb\n ? {')
+ expect(start, 'the waive option').toBeGreaterThan(-1)
+ const end = src.indexOf('onCancel={() => {', start)
+ expect(end, 'the cancel handler after it').toBeGreaterThan(start)
+ return src.slice(start, end)
+}
+
+describe('the "Don’t ask again" scope (source pins)', () => {
+ it('defaults to the app-run waiver — the pre-existing, bounded behaviour', () => {
+ // A dialog that appeared under the user's hands must not pre-select the durable grant. Ticking
+ // and clicking through has to buy exactly what it always bought.
+ expect(src).toContain(
+ "const [controlWaiveScope, setControlWaiveScope] = useState<'session' | 'project'>('session')"
+ )
+ })
+
+ it('resets BOTH the tick and the scope every time the dispatch raises one', () => {
+ // A scope carried over from the previous dialog would grant a durable, project-scoped waiver
+ // to a user who only meant to tick the box this time. Both destructive cases must reset both.
+ const resets = [...src.matchAll(/setControlWaive\(false\)\n\s*setControlWaiveScope\('session'\)/g)]
+ expect(resets.length, 'write and close both reset both').toBe(2)
+ // …and no case resets only one of the two.
+ const lone = [...src.matchAll(/setControlWaive\(false\)(?!\n\s*setControlWaiveScope)/g)]
+ expect(lone.length, 'every setControlWaive(false) is followed by a scope reset').toBe(0)
+ })
+
+ it('offers the project by NAME, not as "this project"', () => {
+ // Canvas control answers a background agent in its OWN project without moving the user's tab,
+ // so "this project" would name whatever they happen to be looking at while the waiver landed
+ // somewhere else. The fallback wording is only for a call whose project could not be resolved.
+ const body = dialogBody()
+ expect(body).toContain('confirm.waiveProjectName')
+ expect(body).toMatch(/Always in "\$\{confirm\.waiveProjectName\}"/)
+ })
+
+ it('grants on CONFIRM only — a denial must never widen anything', () => {
+ const start = src.indexOf('onConfirm={() => {', src.indexOf('confirm.waiveVerb\n ? {'))
+ const end = src.indexOf('onCancel={() => {', start)
+ const onConfirm = src.slice(start, end)
+ const onCancel = src.slice(end, src.indexOf('/>', end))
+ expect(onConfirm).toContain('waiveControlConfirmForProject(confirm.waiveVerb, confirm.waiveProjectId)')
+ expect(onConfirm).toContain('waiveForSession(confirm.waiveVerb)')
+ // Nothing that grants anything may appear on the cancel path.
+ expect(onCancel).not.toContain('waiveControlConfirmForProject')
+ expect(onCancel).not.toContain('waiveForSession')
+ })
+
+ it('the durable grant uses the CALLER’s project id, never the active one', () => {
+ // `waiveProjectId` is set from `ctlProject`, which is the source's project. Reading
+ // `activeProjectId` at the grant site would waive the confirm in the project the human is
+ // looking at — a waiver in the wrong repo, which is the exact failure this scope prevents.
+ const onConfirm = src.slice(
+ src.indexOf('onConfirm={() => {', src.indexOf('confirm.waiveVerb\n ? {')),
+ src.indexOf('onCancel={() => {', src.indexOf('confirm.waiveVerb\n ? {'))
+ )
+ expect(onConfirm).not.toContain('activeProjectId')
+ for (const field of ['waiveProjectId: ctlProject?.id', 'waiveProjectName: ctlProject?.name']) {
+ expect(src.match(new RegExp(field.replace(/[.?]/g, '\\$&'), 'g'))?.length, field).toBe(2)
+ }
+ })
+
+ it('a failed durable grant falls back to the app-run waiver, never to nothing', () => {
+ // `waiveControlConfirmForProject` returns false when no project owns the call. Losing the tick
+ // there would silently give the user nothing for a box they ticked — and they would find out
+ // by being asked again on the very next call.
+ const onConfirm = src.slice(
+ src.indexOf('onConfirm={() => {', src.indexOf('confirm.waiveVerb\n ? {')),
+ src.indexOf('onCancel={() => {', src.indexOf('confirm.waiveVerb\n ? {'))
+ )
+ expect(onConfirm).toMatch(/if \(!scoped\) useControlConfirm\.getState\(\)\.waiveForSession/)
+ })
+
+ it('the gate is asked about the CALLER’s project, in both destructive cases', () => {
+ // The per-project waiver AND the permission mode the bypass lock reads both belong to the
+ // project the call acts on. Off canvas that is not the active one.
+ expect(src.match(/controlConfirmDecision\(verb, ctlProject\?\.id\)/g)?.length).toBe(2)
+ expect(src).not.toMatch(/controlConfirmDecision\(verb\)/)
+ })
+
+ it('the waived NOTICE names the project, in both cases', () => {
+ // Losing the dialog must not mean losing the record, and "which waiver let this through" is
+ // the part of the record that lets a user revoke the right one.
+ expect(src.match(/waivedNotice\(/g)?.length).toBe(2)
+ expect(src.match(/ctlProject\?\.name\n\s*\)/g)?.length, 'both notices pass the project name').toBe(2)
+ })
+})
diff --git a/src/renderer/canvas/control-destructive.test.ts b/src/renderer/canvas/control-destructive.test.ts
index 784fd6a39..f5bb30370 100644
--- a/src/renderer/canvas/control-destructive.test.ts
+++ b/src/renderer/canvas/control-destructive.test.ts
@@ -84,8 +84,12 @@ describe('the confirm-gated set and the dispatch that reads it stay in agreement
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\)/)
+ // The DECISION comes from the shared, tested table — never an inline condition here, and it
+ // is asked about the CALLER's project (`ctlProject`), not the active one: canvas control
+ // answers a background agent in its own project without moving the user's tab, so reading
+ // the project on screen would weigh the wrong project's waiver and the wrong project's
+ // permission mode.
+ expect(body).toMatch(/controlConfirmDecision\(verb, ctlProject\?\.id\)/)
// 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(')
diff --git a/src/renderer/components/ConfirmDialog.tsx b/src/renderer/components/ConfirmDialog.tsx
index a6dba5206..18c33182f 100644
--- a/src/renderer/components/ConfirmDialog.tsx
+++ b/src/renderer/components/ConfirmDialog.tsx
@@ -16,8 +16,21 @@ interface ConfirmDialogProps {
* "Cancel / Delete" reads as though dismissing it will delete something. */
alert?: boolean
/** An explicit opt-in shown above the buttons (e.g. "Delete the worktree directory from disk
- * too"). The caller owns the value, so it can also swap the confirm label / danger styling. */
- option?: { label: string; checked: boolean; onChange: (checked: boolean) => void }
+ * too"). The caller owns the value, so it can also swap the confirm label / danger styling.
+ *
+ * `scopes` turns it into an opt-in plus a HOW FAR, rendered as radios that appear only once the
+ * box is ticked — the canvas-control "Don't ask again" needs to offer "this app run" or "always
+ * in this project" without asking the user to make that choice before they have said yes to the
+ * first one. Radios, not a second checkbox: the scopes are alternatives, and two checkboxes
+ * would let a user tick neither while the box above says they chose something. */
+ option?: {
+ label: string
+ checked: boolean
+ onChange: (checked: boolean) => void
+ scopes?: { value: string; label: string }[]
+ scope?: string
+ onScopeChange?: (scope: string) => void
+ }
/**
* May Enter confirm this dialog? Default true — the user asked for it. Pass FALSE for a dialog
* the app raised on someone ELSE's behalf (an agent verb like `close-worktree`): the user never
@@ -115,14 +128,34 @@ export function ConfirmDialog({
{body}
<p className="confirm__msg">{message}</p>
{option && (
- <label className="confirm__option">
- <input
- type="checkbox"
- checked={option.checked}
- onChange={(e) => option.onChange(e.target.checked)}
- />
- {option.label}
- </label>
+ <>
+ <label className="confirm__option">
+ <input
+ type="checkbox"
+ checked={option.checked}
+ onChange={(e) => option.onChange(e.target.checked)}
+ />
+ {option.label}
+ </label>
+ {/* Only once they have said yes: an untouched dialog must read as "no waiver", and a
+ scope sitting there pre-selected reads as a decision the user has already made. */}
+ {option.checked && option.scopes?.length ? (
+ <div className="confirm__scopes" role="radiogroup" aria-label={option.label}>
+ {option.scopes.map((s) => (
+ <label key={s.value} className="confirm__scope">
+ <input
+ type="radio"
+ name={`${id}-option-scope`}
+ value={s.value}
+ checked={option.scope === s.value}
+ onChange={() => option.onScopeChange?.(s.value)}
+ />
+ {s.label}
+ </label>
+ ))}
+ </div>
+ ) : null}
+ </>
)}
<div className="confirm__actions">
{/* The DESTRUCTIVE button never takes focus: autoFocus on it is what turned a stray Enter
diff --git a/src/renderer/components/settings/sections/AgentsSection.controlConfirm.test.tsx b/src/renderer/components/settings/sections/AgentsSection.controlConfirm.test.tsx
index bbba644f4..07c2843de 100644
--- a/src/renderer/components/settings/sections/AgentsSection.controlConfirm.test.tsx
+++ b/src/renderer/components/settings/sections/AgentsSection.controlConfirm.test.tsx
@@ -15,6 +15,7 @@ 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 { useProjects } from '../../../state/projects'
import { useControlConfirm } from '../../../state/controlConfirm'
import { AgentsSection } from './AgentsSection'
@@ -171,4 +172,81 @@ describe('destructive canvas-control confirmations in Settings', () => {
expect(text).toMatch(/travels to everyone who clones the repo/)
expect(text).toMatch(/A project that overrides the mode never counts/)
})
+
+ it('lists a PER-PROJECT waiver by project NAME, with a way back', () => {
+ // The row the dialog's durable scope owes: it is granted from a dialog that is gone the moment
+ // it is answered, so without this it would be a permanent loosening findable only by
+ // hand-editing settings.json. A project ID names nothing the user recognises, so the row shows
+ // the name.
+ act(() => {
+ useProjects.setState({
+ projects: [
+ { id: 'p1', name: 'web-app', nodes: [] },
+ { id: 'p2', name: 'api', nodes: [] }
+ ]
+ } as never)
+ useSettings.setState((st) => ({
+ settings: {
+ ...st.settings,
+ controlConfirmWaivers: { projects: { p1: ['close'] } }
+ }
+ }))
+ })
+ expect(host.textContent).toContain('Waived in these projects')
+ expect(host.textContent).toContain('web-app')
+ // …and not the other project, which was never waived.
+ expect(host.textContent).not.toMatch(/Ask before an agent closes nodes — api/)
+ const revoke = [...host.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Revoke' && b.closest('div')?.textContent?.includes('web-app')
+ )
+ expect(revoke, 'a Revoke button beside the waiver').toBeTruthy()
+ act(() => revoke!.dispatchEvent(new MouseEvent('click', { bubbles: true })))
+ // Revoking the only verb takes the whole entry with it, so the map does not keep an empty key.
+ expect(useSettings.getState().settings.controlConfirmWaivers).toEqual({})
+ expect(host.textContent).not.toContain('Waived in these projects')
+ })
+
+ it('a waiver whose project is gone is not rendered as an unnamed row, and is pruned on write', () => {
+ // settings.json is forever and project ids are not. A stale entry is worse than clutter: it is
+ // a live security waiver keyed to an id nothing in the UI can name.
+ act(() => {
+ useProjects.setState({ projects: [{ id: 'p1', name: 'web-app', nodes: [] }] } as never)
+ useSettings.setState((st) => ({
+ settings: {
+ ...st.settings,
+ controlConfirmWaivers: { projects: { p1: ['close'], gone: ['write'] } }
+ }
+ }))
+ })
+ expect(host.textContent).toContain('web-app')
+ expect(host.textContent).not.toContain('gone')
+ const revoke = [...host.querySelectorAll('button')].find((b) => b.textContent === 'Revoke')
+ act(() => revoke!.dispatchEvent(new MouseEvent('click', { bubbles: true })))
+ expect(useSettings.getState().settings.controlConfirmWaivers).toEqual({})
+ })
+
+ it('the verb row says WHERE it is waived, rather than counting projects', () => {
+ // "Waived in 3 projects" tells the user a number when what they need is which ones.
+ act(() => {
+ useProjects.setState({ projects: [{ id: 'p1', name: 'web-app', nodes: [] }] } as never)
+ useSettings.setState((st) => ({
+ settings: {
+ ...st.settings,
+ controlConfirmWaivers: { projects: { p1: ['close'] } }
+ }
+ }))
+ })
+ expect(host.textContent).toMatch(/Waived permanently in "web-app"/)
+ // The machine-wide waiver outranks it and says so on its own; the per-project note must not
+ // ALSO claim it, or the user reads two different explanations for one silenced dialog.
+ act(() => {
+ useSettings.setState((st) => ({
+ settings: {
+ ...st.settings,
+ controlConfirmWaivers: { projects: { p1: ['close'] }, always: ['close'] }
+ }
+ }))
+ })
+ expect(host.textContent).not.toMatch(/Waived permanently in "web-app"/)
+ })
})
diff --git a/src/renderer/components/settings/sections/AgentsSection.tsx b/src/renderer/components/settings/sections/AgentsSection.tsx
index 7126939a3..df18c097d 100644
--- a/src/renderer/components/settings/sections/AgentsSection.tsx
+++ b/src/renderer/components/settings/sections/AgentsSection.tsx
@@ -35,6 +35,7 @@ import { chipFor } from '../../../lib/keybindingOverrides'
import { NODE_IDENTITY_STRICT_DATE } from '@shared/node-identity'
import {
CONFIRM_WAIVABLE_VERBS,
+ pruneControlConfirmWaivers,
sanitizeControlConfirmWaivers
} from '@shared/control-confirm'
import { useControlConfirm } from '../../../state/controlConfirm'
@@ -332,6 +333,36 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.El
controlConfirmWaivers: sanitizeControlConfirmWaivers({ ...waivers, bypassMode: on })
})
}
+ // Every project the store holds, CLOSED ones included: `closeProject` keeps the project, its
+ // nodes and its running sessions, so a closed project is parked and its waiver is still live.
+ // Subscribed, so revoking one repaints the list.
+ const allProjects = useProjects((s) => s.projects)
+ /**
+ * The per-project waivers, as ROWS the user can read: a project id alone names nothing they
+ * recognise. A waiver whose project is gone is not rendered as an unnamed row — it is pruned on
+ * the next write, exactly as `sidebarCollapsedItems` keys are (`pruneControlConfirmWaivers`).
+ */
+ const projectWaiverRows = Object.entries(waivers.projects ?? {})
+ .map(([id, verbs]) => ({
+ id,
+ name: allProjects.find((p) => p.id === id)?.name,
+ verbs
+ }))
+ .filter((r) => r.name !== undefined)
+ .sort((a, b) => (a.name ?? '').localeCompare(b.name ?? ''))
+ /** Revoke one verb's per-project waiver. Prunes dead projects in the same write — this section
+ * is the only surface that ever sees the whole map, so it is the natural place to tidy it. */
+ const revokeProjectWaiver = (projectId: string, verb: string): void => {
+ const live = new Set(allProjects.map((p) => p.id))
+ const pruned = pruneControlConfirmWaivers(waivers, live)
+ const rest = (pruned.projects?.[projectId] ?? []).filter((v) => v !== verb)
+ const projects = { ...(pruned.projects ?? {}) }
+ if (rest.length) projects[projectId] = rest
+ else delete projects[projectId]
+ update({
+ controlConfirmWaivers: sanitizeControlConfirmWaivers({ ...pruned, projects })
+ })
+ }
const activeProjectId = useProjects((s) => s.activeProjectId)
const activeProject = useProjects((s) => s.projects.find((p) => p.id === activeProjectId))
const setProjectCapability = useProjects((s) => s.setProjectCapability)
@@ -341,7 +372,6 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.El
// Stop revokes for real in main (detach + drop), and there is deliberately NO global "disable
// browser control" toggle here: one concept, one switch (the per-project capability below).
const browserLeaseEntries = useBrowserLease((s) => s.entries)
- const allProjects = useProjects((s) => s.projects)
const nodeTitleById = (id: string): string => {
for (const p of allProjects) {
const n = p.nodes.find((node) => node.id === id)
@@ -556,6 +586,9 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.El
({ label: `Ask before an agent runs \`${v}\``, description: '' } as const)
const sessionWaived = sessionWaivedVerbs.includes(v)
const always = (waivers.always ?? []).includes(v)
+ // Named per project below rather than counted here: "waived in 3 projects" tells the
+ // user a number when what they need is which ones.
+ const inProjects = projectWaiverRows.filter((r) => r.verbs.includes(v))
return (
<FieldRow
key={v}
@@ -564,9 +597,13 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.El
// 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
+ always
+ ? undefined
+ : sessionWaived
+ ? 'Waived until nodeterm quits (you ticked "Don\u2019t ask again"). Revoke restores the dialog now.'
+ : inProjects.length
+ ? `Waived permanently in ${inProjects.map((r) => `"${r.name}"`).join(', ')} \u2014 revoke below.`
+ : undefined
}
control={
<div className="flex items-center gap-2">
@@ -594,6 +631,35 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.El
/>
)
})}
+ {projectWaiverRows.length > 0 && (
+ <FieldRow
+ label="Waived in these projects"
+ // The rule this section exists for: every loosening stays visible and revocable. A
+ // per-project waiver is granted from a DIALOG, which is gone the moment it is
+ // answered — so without this row the grant would be permanent, invisible, and
+ // findable only by hand-editing settings.json.
+ description="You ticked \u201cDon\u2019t ask again\u201d and chose one project. These survive restarts, and apply only inside the project named. A project you delete takes its waivers with it."
+ control={
+ <div className="flex flex-col items-end gap-2">
+ {projectWaiverRows.map((row) =>
+ row.verbs.map((v) => (
+ <div key={`${row.id}:${v}`} className="flex items-center gap-2">
+ <span className="text-[12px] opacity-70">
+ {CONTROL_CONFIRM_VERB_COPY[v]?.label ?? v} \u2014 {row.name}
+ </span>
+ <Button
+ variant="default"
+ onClick={() => revokeProjectWaiver(row.id, v)}
+ >
+ Revoke
+ </Button>
+ </div>
+ ))
+ )}
+ </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."
diff --git a/src/renderer/state/controlConfirmGate.test.ts b/src/renderer/state/controlConfirmGate.test.ts
new file mode 100644
index 000000000..99a29c0a3
--- /dev/null
+++ b/src/renderer/state/controlConfirmGate.test.ts
@@ -0,0 +1,177 @@
+// @vitest-environment jsdom
+//
+// jsdom for `window.nodeTerminal` alone: `useSettings.update` schedules a save through the preload
+// bridge, and this file's whole subject is what that write persists.
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ controlConfirmDecision,
+ waiveControlConfirmForProject,
+ activeControlConfirmWaivers
+} from './controlConfirmGate'
+import { useControlConfirm } from './controlConfirm'
+import { useProjects } from './projects'
+import { useSettings } from './settings'
+
+/**
+ * The store-bound half of the canvas-control confirm — `decideControlConfirm`'s wiring, where the
+ * per-project waiver is granted and where "which project is this about" is answered.
+ *
+ * WHY THE PROJECT ARGUMENT IS THE WHOLE STORY HERE: canvas control routes by SOURCE, and since
+ * `@shared/control-off-screen` a background agent's `write`/`close` is answered in ITS OWN project
+ * without the user's tab moving. So "the active project" and "the project this call acts on" are
+ * now routinely different, and every per-project fact the gate reads — the waiver AND the
+ * permission mode the bypass lock weighs — has to follow the caller, not the human's screen.
+ */
+const setProjects = (projects: unknown[]): void => {
+ useProjects.setState({ projects, activeProjectId: 'active' } as never)
+}
+
+beforeEach(() => {
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ settings: { save: vi.fn(async () => undefined) }
+ }
+ useControlConfirm.setState({ sessionWaived: [], sessionWaivedSet: new Set() })
+ useSettings.setState((s) => ({
+ settings: { ...s.settings, controlConfirmWaivers: undefined }
+ }))
+ setProjects([
+ { id: 'active', name: 'On screen', nodes: [] },
+ { id: 'other', name: 'Background', nodes: [] }
+ ])
+})
+
+describe('controlConfirmDecision — which project it asks about', () => {
+ it('defaults to the active project, which is what every pre-existing caller means', () => {
+ useSettings.setState((s) => ({
+ settings: { ...s.settings, controlConfirmWaivers: { projects: { active: ['close'] } } }
+ }))
+ expect(controlConfirmDecision('close').via).toBe('project')
+ })
+
+ it('follows the caller’s project when one is passed', () => {
+ useSettings.setState((s) => ({
+ settings: { ...s.settings, controlConfirmWaivers: { projects: { other: ['close'] } } }
+ }))
+ // The background agent's own project is waived; the one on screen is not. Reading the active
+ // project here would ASK about a call the user already said not to ask about…
+ expect(controlConfirmDecision('close', 'other').via).toBe('project')
+ // …and, the dangerous direction, would SKIP a call in a project the user never waived.
+ useSettings.setState((s) => ({
+ settings: { ...s.settings, controlConfirmWaivers: { projects: { active: ['close'] } } }
+ }))
+ expect(controlConfirmDecision('close', 'other')).toEqual({ skip: false, via: null })
+ })
+
+ it('reads the permission mode from the CALLER’s project too', () => {
+ // The bypass lock weighs `project.defaultPermissionMode`, which is per project. Weighing the
+ // project on screen would let one project's Bypass silence another project's dialog.
+ useSettings.setState((s) => ({
+ settings: {
+ ...s.settings,
+ claudePermissionMode: 'manual',
+ controlConfirmWaivers: { bypassMode: true }
+ }
+ }))
+ setProjects([
+ { id: 'active', name: 'On screen', nodes: [], defaultPermissionMode: 'bypassPermissions' },
+ { id: 'other', name: 'Background', nodes: [] }
+ ])
+ // Even for the active project this must ask: the mode came from the PROJECT file, which is
+ // git-shared — the cloned-repo trap, proven in shared/control-confirm.test.ts and re-checked
+ // here because this is the layer that decides which project's file is read.
+ expect(controlConfirmDecision('close').skip).toBe(false)
+ expect(controlConfirmDecision('close', 'other').skip).toBe(false)
+ })
+
+ it('an unknown project id waives nothing — fail closed', () => {
+ useSettings.setState((s) => ({
+ settings: { ...s.settings, controlConfirmWaivers: { projects: { active: ['close'] } } }
+ }))
+ expect(controlConfirmDecision('close', 'no-such-project')).toEqual({ skip: false, via: null })
+ })
+})
+
+describe('waiveControlConfirmForProject — the durable grant the dialog may make', () => {
+ it('persists one verb for one project', () => {
+ expect(waiveControlConfirmForProject('close', 'other')).toBe(true)
+ expect(activeControlConfirmWaivers()).toEqual({ projects: { other: ['close'] } })
+ expect(controlConfirmDecision('close', 'other').via).toBe('project')
+ expect(controlConfirmDecision('close', 'active').skip).toBe(false)
+ })
+
+ it('adds beside an existing grant instead of replacing it', () => {
+ waiveControlConfirmForProject('close', 'other')
+ waiveControlConfirmForProject('write', 'other')
+ waiveControlConfirmForProject('close', 'active')
+ expect(activeControlConfirmWaivers().projects).toEqual({
+ other: ['close', 'write'],
+ active: ['close']
+ })
+ })
+
+ it('is idempotent — a second tick does not duplicate the verb', () => {
+ waiveControlConfirmForProject('close', 'other')
+ waiveControlConfirmForProject('close', 'other')
+ expect(activeControlConfirmWaivers().projects?.other).toEqual(['close'])
+ })
+
+ it('refuses a verb the shared table does not admit, and a missing project', () => {
+ // The table decides here as well as in the decision: a caller cannot grant `open-project` by
+ // passing the wrong string into the wrong function. Returning false matters — the dialog falls
+ // back to the app-run waiver on a false, so a silent no-op would lose the user's tick.
+ expect(waiveControlConfirmForProject('open-project', 'other')).toBe(false)
+ expect(waiveControlConfirmForProject('close', undefined)).toBe(false)
+ expect(useSettings.getState().settings.controlConfirmWaivers).toBeUndefined()
+ })
+
+ it('prunes dead projects on the way in — settings.json is forever', () => {
+ useSettings.setState((s) => ({
+ settings: {
+ ...s.settings,
+ controlConfirmWaivers: { projects: { gone: ['write'], other: ['write'] } }
+ }
+ }))
+ waiveControlConfirmForProject('close', 'active')
+ expect(activeControlConfirmWaivers().projects).toEqual({
+ other: ['write'],
+ active: ['close']
+ })
+ })
+
+ it('keeps the project being written even if the store no longer lists it', () => {
+ // A project can go away between the dialog appearing and the user answering it; pruning it in
+ // the same breath as granting it would swallow the answer they just gave. This holds because
+ // the grant is merged AFTER the prune — there is deliberately no second mechanism exempting
+ // the id, since nothing could turn such a safeguard red.
+ setProjects([{ id: 'active', name: 'On screen', nodes: [] }])
+ expect(waiveControlConfirmForProject('close', 'vanished')).toBe(true)
+ expect(activeControlConfirmWaivers().projects).toEqual({ vanished: ['close'] })
+ })
+
+ it('the prune happens BEFORE the grant, so the two cannot fight', () => {
+ // The ordering the test above rests on, asserted directly: a dead entry goes AND the new grant
+ // lands, in one write. Reversing them would prune the grant that was just made.
+ setProjects([{ id: 'active', name: 'On screen', nodes: [] }])
+ useSettings.setState((s) => ({
+ settings: { ...s.settings, controlConfirmWaivers: { projects: { gone: ['write'] } } }
+ }))
+ expect(waiveControlConfirmForProject('close', 'active')).toBe(true)
+ expect(activeControlConfirmWaivers().projects).toEqual({ active: ['close'] })
+ })
+
+ it('leaves the machine-wide and bypass waivers alone', () => {
+ useSettings.setState((s) => ({
+ settings: {
+ ...s.settings,
+ controlConfirmWaivers: { always: ['write'], bypassMode: true }
+ }
+ }))
+ waiveControlConfirmForProject('close', 'other')
+ expect(activeControlConfirmWaivers()).toEqual({
+ always: ['write'],
+ bypassMode: true,
+ projects: { other: ['close'] }
+ })
+ })
+})
diff --git a/src/renderer/state/controlConfirmGate.ts b/src/renderer/state/controlConfirmGate.ts
index 7d3cbb2ae..6e23323a7 100644
--- a/src/renderer/state/controlConfirmGate.ts
+++ b/src/renderer/state/controlConfirmGate.ts
@@ -1,5 +1,7 @@
import {
decideControlConfirm,
+ isWaivableVerb,
+ pruneControlConfirmWaivers,
sanitizeControlConfirmWaivers,
type ControlConfirmDecision,
type ControlConfirmWaivers
@@ -27,19 +29,70 @@ import { sessionWaivedVerbs } from './controlConfirm'
* 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 {
+export function controlConfirmDecision(
+ verb: string,
+ /**
+ * The project the request ACTS ON. Defaults to the active one, which is what every pre-existing
+ * caller means — but canvas control routes by SOURCE, and a background agent's `write`/`close`
+ * is now answered in its OWN project without the user's tab moving
+ * (@shared/control-off-screen), so the dispatch passes `ctlProject?.id`. Both halves below have
+ * to follow it: the per-project waiver obviously, and the permission MODE too, because
+ * `project.defaultPermissionMode` is per project and reading the active one would weigh the
+ * wrong project's Bypass.
+ */
+ projectId?: string
+): ControlConfirmDecision {
const { settings } = useSettings.getState()
const { getProject, activeProjectId } = useProjects.getState()
- const { mode, source } = resolvePermissionModeWithSource(getProject(activeProjectId), settings)
+ const pid = projectId ?? activeProjectId
+ const { mode, source } = resolvePermissionModeWithSource(getProject(pid), settings)
return decideControlConfirm({
verb,
sessionWaived: sessionWaivedVerbs(),
persisted: activeControlConfirmWaivers(),
+ projectId: pid,
permissionMode: mode,
permissionModeSource: source
})
}
+/**
+ * Grant a PERMANENT waiver scoped to one project — the durable half of the dialog's "Don't ask
+ * again", and the only persisted waiver a dialog may grant (the machine-wide `always` stays
+ * Settings-only; see `ControlConfirmWaivers.always`).
+ *
+ * It PRUNES on the way in, like every `sidebarCollapsedItems` write: settings.json is forever, and
+ * an entry keyed to a project the user deleted is a live security waiver nothing can show them.
+ * `live` is every project the store holds, closed ones included — a closed project is parked, not
+ * gone.
+ *
+ * The id being GRANTED survives the prune because the merge below happens after it, not because
+ * of any exemption inside it — which matters for a project that went away between the dialog
+ * appearing and the user answering it: their answer is still honoured. (`pruneCollapsedItems` has
+ * an explicit `keepKey` for this; here the write order already says it, and a second mechanism
+ * saying the same thing would be one no test could turn red.)
+ *
+ * Returns false when nothing was granted (an unwaivable verb, or no project), so a caller cannot
+ * report a waiver it did not get.
+ */
+export function waiveControlConfirmForProject(verb: string, projectId: string | undefined): boolean {
+ if (!isWaivableVerb(verb) || !projectId) return false
+ const current = activeControlConfirmWaivers()
+ const live = new Set(useProjects.getState().projects.map((p) => p.id))
+ const pruned = pruneControlConfirmWaivers(current, live)
+ const next = {
+ ...pruned,
+ projects: {
+ ...(pruned.projects ?? {}),
+ [projectId]: [...new Set([...(pruned.projects?.[projectId] ?? []), verb])]
+ }
+ }
+ // Sanitized on the way OUT as well as in: the write is the file, and every other writer of this
+ // key does the same, so a bug here cannot persist a shape the readers would then drop in silence.
+ useSettings.getState().update({ controlConfirmWaivers: sanitizeControlConfirmWaivers(next) })
+ return true
+}
+
/** 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/renderer/styles.css b/src/renderer/styles.css
index a2056408c..71af46af3 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -5489,6 +5489,24 @@ body,
cursor: pointer;
}
+/* The "how far" radios under a confirm's opt-in (canvas control's "Don't ask again"). Indented
+ under the checkbox they qualify, so the pair reads as one control rather than two questions. */
+.confirm__scopes {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ margin: -8px 0 14px 22px;
+}
+
+.confirm__scope {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 12.5px;
+ color: rgba(var(--tint-rgb), 0.55);
+ cursor: pointer;
+}
+
.confirm__input {
width: 100%;
box-sizing: border-box;
diff --git a/src/shared/control-confirm.test.ts b/src/shared/control-confirm.test.ts
index 4ff7adf67..5d6dd59df 100644
--- a/src/shared/control-confirm.test.ts
+++ b/src/shared/control-confirm.test.ts
@@ -7,6 +7,7 @@ import {
decideControlConfirm,
expiredDialogNotice,
isWaivableVerb,
+ pruneControlConfirmWaivers,
sanitizeControlConfirmWaivers,
waivedNotice
} from './control-confirm'
@@ -207,3 +208,150 @@ describe('waivedNotice', () => {
}
})
})
+
+describe('the per-project waiver — a "don\'t ask again" that lasts, without going machine-wide', () => {
+ it('skips only inside the project it was granted for', () => {
+ const persisted = { projects: { p1: ['close'] } }
+ expect(decideControlConfirm({ verb: 'close', persisted, projectId: 'p1' })).toEqual({
+ skip: true,
+ via: 'project'
+ })
+ // The whole point of the scope. A user who trusts the orchestrator in one repo has said
+ // nothing at all about the next one.
+ expect(decideControlConfirm({ verb: 'close', persisted, projectId: 'p2' })).toEqual({
+ skip: false,
+ via: null
+ })
+ // …and nothing about another verb in the same project.
+ expect(decideControlConfirm({ verb: 'write', persisted, projectId: 'p1' })).toEqual({
+ skip: false,
+ via: null
+ })
+ })
+
+ it('needs a real project id — an absent one must not match anything', () => {
+ // Fail closed: canvas control can now answer a call whose owning project it could not resolve,
+ // and `undefined` used as a map key would stringify to "undefined" and match a hand-edited
+ // entry of that name.
+ const persisted = { projects: { undefined: ['close'], '': ['close'] } }
+ expect(decideControlConfirm({ verb: 'close', persisted }).skip).toBe(false)
+ expect(decideControlConfirm({ verb: 'close', persisted, projectId: '' }).skip).toBe(false)
+ })
+
+ it('is outranked by the unwaivable table, like every other lever', () => {
+ expect(
+ decideControlConfirm({
+ verb: 'open-project',
+ persisted: { projects: { p1: ['open-project'] } },
+ projectId: 'p1'
+ })
+ ).toEqual({ skip: false, via: null })
+ })
+
+ it('sits between the app-run waiver and the machine-wide one', () => {
+ // Precedence is narrowest-first among the persisted grants, so the notice names the waiver the
+ // user most likely wants back. A session waiver still outranks it: it is the most recent thing
+ // they said.
+ const persisted = { projects: { p1: ['close'] }, always: ['close'] }
+ expect(decideControlConfirm({ verb: 'close', persisted, projectId: 'p1' }).via).toBe('project')
+ expect(
+ decideControlConfirm({
+ verb: 'close',
+ persisted,
+ projectId: 'p1',
+ sessionWaived: new Set(['close'])
+ }).via
+ ).toBe('session')
+ // A project with no entry still falls through to the machine-wide one.
+ expect(decideControlConfirm({ verb: 'close', persisted, projectId: 'p9' }).via).toBe('always')
+ })
+
+ it('a project entry never opens the bypass branch, and vice versa', () => {
+ // They are independent locks; neither may stand in for the other.
+ expect(
+ decideControlConfirm({
+ verb: 'close',
+ persisted: { projects: { p1: ['close'] } },
+ projectId: 'p2',
+ permissionMode: 'bypassPermissions',
+ permissionModeSource: 'global'
+ }).skip
+ ).toBe(false)
+ })
+})
+
+describe('sanitizeControlConfirmWaivers — the per-project map is hostile input too', () => {
+ it('applies the verb table per project, exactly as it does to `always`', () => {
+ expect(
+ sanitizeControlConfirmWaivers({
+ projects: { p1: ['close', 'open-project', 'nonsense', 'close'] }
+ })
+ ).toEqual({ projects: { p1: ['close'] } })
+ })
+
+ it('drops an entry that would waive nothing, key and all', () => {
+ // An entry waiving nothing is indistinguishable from no entry to every reader, and keeping it
+ // would put a row in Settings offering to revoke a waiver that does not exist.
+ expect(sanitizeControlConfirmWaivers({ projects: { p1: [], p2: ['open-project'] } })).toEqual({})
+ })
+
+ it('degrades a non-object `projects` to nothing rather than throwing', () => {
+ for (const bad of [null, 'close', 42, ['close'], true]) {
+ expect(sanitizeControlConfirmWaivers({ projects: bad })).toEqual({})
+ }
+ expect(sanitizeControlConfirmWaivers({ projects: { '': ['close'] } })).toEqual({})
+ })
+
+ it('keeps the other keys intact', () => {
+ expect(
+ sanitizeControlConfirmWaivers({
+ always: ['write'],
+ projects: { p1: ['close'] },
+ bypassMode: true
+ })
+ ).toEqual({ always: ['write'], projects: { p1: ['close'] }, bypassMode: true })
+ })
+})
+
+describe('pruneControlConfirmWaivers — settings.json is forever, project ids are not', () => {
+ it('drops entries whose project is gone', () => {
+ const w = { projects: { alive: ['close'], dead: ['write'] }, always: ['write'] }
+ expect(pruneControlConfirmWaivers(w, new Set(['alive']))).toEqual({
+ projects: { alive: ['close'] },
+ always: ['write']
+ })
+ })
+
+ it('removes the key entirely when nothing survives', () => {
+ const pruned = pruneControlConfirmWaivers({ projects: { dead: ['close'] } }, new Set())
+ expect(pruned).toEqual({})
+ expect('projects' in pruned).toBe(false)
+ })
+
+ it('returns the SAME object when nothing would change, so a no-op never dirties settings', () => {
+ const w = { projects: { alive: ['close'] } }
+ expect(pruneControlConfirmWaivers(w, new Set(['alive']))).toBe(w)
+ const none = { always: ['close'] }
+ expect(pruneControlConfirmWaivers(none, new Set())).toBe(none)
+ })
+})
+
+describe('waivedNotice names the per-project waiver by project', () => {
+ it('names the project, because "this project" may not be the one on screen', () => {
+ // Canvas control answers a background agent in its OWN project without moving the user's tab,
+ // so a notice saying "this project" would point at whatever they happen to be looking at.
+ expect(waivedNotice('Agent "A" closed n-1', 'project', 'web-app')).toContain('"web-app"')
+ expect(waivedNotice('Agent "A" closed n-1', 'project', 'web-app')).toContain('Settings \u2192 Agents')
+ })
+
+ it('still says something true when the project name is unknown', () => {
+ expect(waivedNotice('x', 'project')).toContain('that project')
+ expect(waivedNotice('x', 'project')).not.toContain('undefined')
+ })
+
+ it('the other three are unchanged', () => {
+ expect(waivedNotice('x', 'session')).toContain('this app run')
+ expect(waivedNotice('x', 'always')).toContain('permanently')
+ expect(waivedNotice('x', 'bypass')).toContain('Bypass')
+ })
+})
diff --git a/src/shared/control-confirm.ts b/src/shared/control-confirm.ts
index 63c2af6f1..17fb109ee 100644
--- a/src/shared/control-confirm.ts
+++ b/src/shared/control-confirm.ts
@@ -74,10 +74,34 @@ export function isWaivableVerb(verb: string): boolean {
* 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. */
+ /** Verbs waived PERMANENTLY on this machine, in EVERY project. Only ever set from Settings →
+ * Agents — the dialog itself may not grant this one, because a permanent MACHINE-WIDE security
+ * waiver must not be one stray checkbox click away in a dialog that appeared under the user's
+ * hands. That reasoning is about the SCOPE, not about permanence: see `projects` below. */
always?: string[]
+ /**
+ * Verbs waived permanently but only inside ONE project — `{ [projectId]: verbs }`.
+ *
+ * The narrower grant that makes the dialog's offer honest. "Don't ask again" that lasts only
+ * until the next restart is not what a user who ticks it means, and the only durable answer used
+ * to be a machine-wide switch buried in Settings — so the realistic choices were "be asked
+ * forever" or "turn it off everywhere". A user who trusts the orchestrator in one repo should be
+ * able to say exactly that, and this is the scope the DIALOG may therefore grant: it is bounded
+ * by a project the user is looking at, revocable from Settings, and it cannot follow them into
+ * the repo where they do not trust it.
+ *
+ * SHAPE follows `settings.sidebarCollapsedItems`, the established per-project machine-local
+ * state, PRUNING INCLUDED (`pruneControlConfirmWaivers`): settings.json is forever and project
+ * ids are not, so without it the file accumulates an entry per project that ever existed, each
+ * one a live security waiver keyed to an id nothing can show the user any more.
+ *
+ * MACHINE-LOCAL, like everything else in this interface. A per-project waiver is emphatically
+ * NOT `.nodeterm/project.json`: that file is git-shared, and a cloned repo must never be able to
+ * turn somebody's confirms off — the same trap `bypassMode` needs two locks for. Keying on the
+ * project ID in `settings.json` is what keeps "in this project" a statement this machine's user
+ * made about this machine.
+ */
+ projects?: Record<string, string[]>
/**
* Skip the confirm while the resolved permission mode is `bypassPermissions` — the "I already
* told this agent to stop asking me" case.
@@ -100,8 +124,10 @@ export interface ControlConfirmWaivers {
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'
+ * action still announces itself and names the waiver that let it through. Losing the dialog must
+ * not mean losing the record, and "which of my four waivers did this" is the part of the record a
+ * user needs in order to revoke the right one. */
+export type ConfirmWaiverVia = 'session' | 'project' | 'always' | 'bypass'
export interface ControlConfirmDecision {
/** True = apply the verb without a dialog. */
@@ -129,14 +155,31 @@ export function decideControlConfirm(input: {
* the user granted in a dialog dies with the process, which is what makes it the safe default. */
sessionWaived?: ReadonlySet<string>
persisted?: ControlConfirmWaivers
+ /**
+ * The project this request ACTS ON — the caller's own project, which is not necessarily the one
+ * on screen: canvas control routes by source, and a background agent's `write`/`close` is now
+ * answered in its own project without the user's tab moving (@shared/control-off-screen). The
+ * waiver that applies is the one the user granted for THAT project; reading the active project
+ * here would let a waiver granted in the repo they trust cover a call made from the one they do
+ * not. Absent (or unknown) simply means no per-project waiver applies — fail closed.
+ */
+ projectId?: string
/** 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
+ const { verb, sessionWaived, persisted, projectId, 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' }
+ // Narrowest persisted grant before the widest: a user with both set has said something true
+ // about this project AND something true about the machine, and naming the narrower one in the
+ // notice points them at the waiver they most likely want back. `projectId` must be a real id —
+ // `undefined` would otherwise index the map with the string "undefined" and match a hand-edited
+ // entry of that name.
+ if (projectId && persisted?.projects?.[projectId]?.includes(verb)) {
+ return { skip: true, via: 'project' }
+ }
// 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
@@ -165,16 +208,61 @@ export function decideControlConfirm(input: {
*/
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 o = raw as { always?: unknown; projects?: unknown; bypassMode?: unknown }
+ const verbs = (v: unknown): string[] =>
+ Array.isArray(v)
+ ? [...new Set(v.filter((x): x is string => typeof x === 'string' && isWaivableVerb(x)))]
+ : []
+ const always = verbs(o.always)
const out: ControlConfirmWaivers = {}
if (always.length) out.always = always
+ // Per-project entries get the SAME treatment as `always` — the verb table decides, so a
+ // hand-edited `{"p1":["open-project"]}` is dropped rather than honoured — plus a key check the
+ // flat list does not need. An empty verb list is dropped with its key: an entry that waives
+ // nothing is indistinguishable from no entry to every reader, and keeping it would leave a row
+ // in Settings offering to revoke a waiver that does not exist.
+ if (o.projects && typeof o.projects === 'object' && !Array.isArray(o.projects)) {
+ const projects: Record<string, string[]> = {}
+ for (const [id, list] of Object.entries(o.projects as Record<string, unknown>)) {
+ if (!id) continue
+ const kept = verbs(list)
+ if (kept.length) projects[id] = kept
+ }
+ if (Object.keys(projects).length) out.projects = projects
+ }
if (o.bypassMode === true) out.bypassMode = true
return out
}
+/**
+ * Drop per-project waivers whose project no longer exists — the rule
+ * `pruneCollapsedItems`/`liveCollapseKeys` states for `settings.sidebarCollapsedItems`, applied to
+ * a map whose stale entries are worse than clutter: each one is a live security waiver keyed to an
+ * id nothing in the UI can name any more, and a project id is reused by nothing, so it can only
+ * ever rot.
+ *
+ * `live` is EVERY project the store holds, CLOSED ones included — `closeProject` keeps the project
+ * and its nodes on disk and its sessions running, so a closed project is parked, not gone. Pruning
+ * on the open tabs would silently revoke a waiver the user still has a canvas for.
+ *
+ * Returns the SAME object when nothing would change, so a no-op write never marks settings dirty.
+ */
+export function pruneControlConfirmWaivers(
+ waivers: ControlConfirmWaivers,
+ live: ReadonlySet<string>
+): ControlConfirmWaivers {
+ const projects = waivers.projects
+ if (!projects) return waivers
+ const dead = Object.keys(projects).filter((id) => !live.has(id))
+ if (dead.length === 0) return waivers
+ const kept: Record<string, string[]> = {}
+ for (const [id, verbs] of Object.entries(projects)) if (live.has(id)) kept[id] = verbs
+ const out: ControlConfirmWaivers = { ...waivers }
+ if (Object.keys(kept).length) out.projects = kept
+ else delete out.projects
+ return out
+}
+
/**
* The user-visible line a dialog raises when it collects itself unanswered — ONE sentence for every
* expiring dialog (`useExpiringDialog`), because a session that raises two differently-worded
@@ -190,12 +278,22 @@ export function expiredDialogNotice(requestedBy?: string): string {
/** 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 {
+export function waivedNotice(
+ action: string,
+ via: ConfirmWaiverVia,
+ /** The project a `project` waiver belongs to. Named in the sentence because the whole point of
+ * that scope is that it does NOT apply everywhere — a user reading "waived for this project"
+ * while looking at a different project's canvas (which canvas control now makes routine) would
+ * read it as covering the one in front of them. */
+ projectName?: string
+): 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'
+ : via === 'project'
+ ? `confirm waived for ${projectName ? `"${projectName}"` : 'that project'}`
+ : via === 'always'
+ ? 'confirm waived permanently'
+ : 'confirm waived while the global permission mode is Bypass'
return `${action} — ${because} (Settings → Agents).`
}