Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(canvas-control): a verb never takes the user's screen again

enes8c237760609f
diff --git a/CLAUDE.md b/CLAUDE.md
index 378867b1b..d819075bb 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2144,6 +2144,38 @@ else, and its context links must keep classifying across restarts).
control the desktop's canvas. The shim is generated source no compiler checks:
`canvas-control-shim.test.ts` runs it for real (/bin/sh against a real hook server, port AND
unix-socket transports) — keep it that way.
+ **NO VERB MAY ACTIVATE A PROJECT TAB** (`src/shared/control-off-screen.ts`). Routing is by
+ SOURCE — the request names the agent's own node, and the dispatch must find the canvas that owns
+ it — so for years "that canvas is not on screen" was answered by `travelToProject`. The user was
+ typing in project B; a background agent in project A issued a `close`; the tab switched and A's
+ saved viewport was applied. Their focus, camera and typing context were taken by a call they did
+ not make. Two carve-outs (the cold open for `open-*`, then the display verbs) were each written
+ as if it were the last, because nothing walked the whole table — twenty-one verbs still
+ travelled. Every verb now has a decided disposition and NONE of them is travel:
+ `STORE_ANSWERED_VERBS` (no canvas at either end), `COLD_OPENABLE_VERBS` (a session node, armed
+ and inert until shown), `OFF_CANVAS_VERBS` (a display node, complete when written),
+ `STORED_NODE_VERBS` (`write`/`close`/`rename`/`color`/`link`/`board`/`assign` — each reaches a
+ pane, a store writer or the board file), and `OFF_SCREEN_REFUSALS` (the eleven that genuinely
+ need live React Flow, each with its own reason in the refusal the agent reads). A refusal an
+ agent can act on is strictly better than hijacking someone's screen. Load-bearing details:
+ (1) **`ctlNodes()` is the one name for "the node array this call acts on"** — on screen it is
+ `nodesRef.current` verbatim, off canvas it is the owning project's serialized nodes hydrated by
+ `nodeStatesToFlow`. A verb body that resolves `--node` against the live array while answering
+ for another project does not throw and does not travel; it silently renames, closes or reports
+ on whatever the human happens to be looking at. `control-stored-node.source.test.ts` pins that
+ no stored-node case mentions `nodesRef.current`. (2) **`board`/`assign` read `ctlProject`, not
+ `activeProjectId`** — a second bug that was hiding behind the first, invisible while the travel
+ made the two projects the same. (3) **`closeStoredNodes` is the ONE cross-project teardown**,
+ shared with the sessions sidebar's `closeSession`; it is `deleteNodes` minus the closed-session
+ ledger and ⇧⌘T history, which `deleteNodes` files against the ACTIVE project. `close` still ends
+ the session off canvas because `transport.destroy` resolves a REMOTE node's host from the
+ persisted index with no live client (`core/remote-end.ts`). (4) **There is no
+ `travelToProjectRef` and there must not be one again**; `travelToProject` survives only for the
+ facepile, the user's own navigation. (5) **The regression guard is
+ `test/acceptance/control-verb-disposition.test.ts`**, cross-layer on purpose: it walks MAIN's
+ `VERBS_FOR_TEST` against the RENDERER's disposition, which is the only way "every verb" is a
+ checked claim rather than a list kept by hand. That is what nobody had, and why two carve-outs
+ could ship without anyone noticing the other twenty verbs.
**Keep the agent-facing text in sync with behaviour, in the SAME PR.** The verb help agents
actually read is generated by `buildCanvasSkillBody` (the SKILL.md, rewritten into every config
dir by `installCanvasSkillInto` on launch) and `buildCanvasControlInstructions` (the
@@ -2152,8 +2184,10 @@ else, and its context links must keep classifying across restarts).
`targetBusy` refusal into a deliver-on-idle queue), update those two functions in the same change,
or the docs describe a product that no longer exists and an orchestrating agent acts on the stale
contract. Derive from the code, never re-type: the retry guidance renders from `RETRYABLE`
- (`messagingGuidanceLines`) so a new outcome kind lands in the text the day it is added — prefer
- that shape over prose you have to remember to edit. `canvas-control-core.test.ts` walks both
+ (`messagingGuidanceLines`) so a new outcome kind lands in the text the day it is added, and the
+ off-screen paragraph renders from the verb table itself (`offScreenGuidanceLines`, which is why
+ that table lives in `src/shared` — core cannot import the renderer) — prefer that shape over
+ prose you have to remember to edit. `canvas-control-core.test.ts` walks both
generated bodies and must red on the stale claim (it pins the queue wording and the RETRYABLE
split); a doc line with no such test is a plan, not a fact — see the drift that shipped as #269.
**Flag syntax**: `--flag value`, `--flag=value`, or a valueless flag anywhere on the line. The
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a6878fd22..e6069fb5a 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -143,6 +143,22 @@ lane unaffected.
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`.
+- **Nothing an agent asks for may take the user's screen.** Canvas control routes by SOURCE: the
+ request names the agent's own node, and the dispatch has to find the canvas that owns it. For
+ years "that canvas is not on screen" was answered by switching the project tab — so a background
+ agent's `close` moved a user who was typing in another project, applied that project's saved
+ viewport, and took their camera and typing focus for a call they did not make. Every verb now has
+ a decided off-screen behaviour (`src/shared/control-off-screen.ts`) and none of them is "travel":
+ it is answered against the owning project's serialized nodes, or REFUSED with a reason the agent
+ can act on. If you add a verb, give it an entry — a refusal beats a hijack, and a verb with no
+ entry falls into the generic refusal, which is fail-closed but is nobody's decision. Two traps
+ the old shape hid: a verb body that resolves `--node` against the live `nodesRef.current` while
+ answering for another project silently acts on whatever the human is looking at (use
+ `ctlNodes()`), and reading `activeProjectId` inside a verb has the same bug (use `ctlProject`).
+ The guard is `test/acceptance/control-verb-disposition.test.ts`, which walks main's verb table
+ against the renderer's dispositions — deliberately cross-layer, because that is the only way
+ "every verb" is checked rather than remembered.
+
- **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
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index dc07a7a86..3c283550e 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -12,6 +12,7 @@ import { FANOUT_PER_TURN, PAIR_MIN_INTERVAL_MS } from './agents/agent-message-fl
import { BROWSER_RETRYABLE, BROWSER_OUTCOME_LABEL } from './browser-outcomes'
import { BROWSER_KEYS, BROWSER_TIMEOUT_DEFAULT_MS, BROWSER_TIMEOUT_MAX_MS } from './browser-verb'
import { nodeColorChoices } from '@shared/node-colors'
+import { offScreenGuidanceLines } from '@shared/control-off-screen'
import { codexThreadIdentityResolverSh } from './codex-thread-identity-sh'
/**
@@ -461,6 +462,8 @@ export function buildCanvasControlInstructions(shimPath: string): string {
' to your "In Progress"/"Done" column as work advances.',
...browserVerbDocLines(),
'',
+ ...offScreenGuidanceLines(),
+ '',
...messagingGuidanceLines(),
'',
...browserGuidanceLines(),
@@ -976,6 +979,8 @@ Verbs:
move its card into your "In Progress" / "Done" column so the board tells the real story.
${browserVerbDocLines().join('\n')}
+${offScreenGuidanceLines().join('\n')}
+
${messagingGuidanceLines().join('\n')}
${browserGuidanceLines().join('\n')}
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index 91226b0b3..81f123138 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -19,6 +19,10 @@ import { STRICT_CONTROL_VERBS } from '../core/agents/node-identity-policy'
import { BROWSER_ACTION_KEYS } from '../core/browser-verb'
import { BROWSER_RETRYABLE, BROWSER_OUTCOME_LABEL } from '../core/browser-outcomes'
import { BROWSER_CAPABILITY_OFF_MESSAGE } from './browser-drive'
+import {
+ offScreenDisposition,
+ controlVerbSetsForTests
+} from '../shared/control-off-screen'
describe('parseControlRequest', () => {
it('accepts known verbs', () => {
@@ -786,4 +790,55 @@ describe('the --project clause tells the truth about travel (review #363 I-1 + M
expect(clause, `${name}: not queued`).toMatch(/nothing (here )?is (ever )?\`?queued/i)
}
})
+
+ it('both bodies render the OFF-SCREEN table, and render it from the table', () => {
+ // CLAUDE.md's rule for this subsystem: derive, never re-type — "a doc line with no such test
+ // is a plan, not a fact". The two sides of the table have OPPOSITE consequences for a caller
+ // (act, or ask the human and stop), so a verb documented on the wrong side is worse than one
+ // documented nowhere: an orchestrator would report as done a `close` that never happened.
+ const sets = controlVerbSetsForTests()
+ const answered = [
+ ...sets.storeAnswered,
+ ...sets.coldOpenable,
+ ...sets.offCanvas,
+ ...sets.storedNode
+ ]
+ for (const [name, body] of bodies) {
+ expect(body, `${name}: the promise`).toMatch(/NO VERB EVER SWITCHES THE USER'S VIEW/)
+ const start = body.indexOf("NO VERB EVER SWITCHES THE USER'S VIEW")
+ const end = body.indexOf('Messaging outcomes', start)
+ expect(end, `${name}: the messaging block after it`).toBeGreaterThan(start)
+ const clause = body.slice(start, end)
+ for (const v of answered) {
+ expect(clause, `${name}: ${v} is answered off screen`).toContain(v)
+ expect(offScreenDisposition(v).kind, v).not.toBe('refuse')
+ }
+ // Every refused verb is named AND carries its own reason — a bare list would tell an agent
+ // that `branch` and `arrange` fail for the same cause, and they do not.
+ for (const v of ['group', 'ungroup', 'move', 'arrange', 'align', 'verify', 'spawn-team', 'branch', 'open-worktree', 'close-worktree', 'browser']) {
+ const d = offScreenDisposition(v)
+ expect(d.kind, v).toBe('refuse')
+ if (d.kind !== 'refuse') continue
+ expect(clause, `${name}: ${v}'s reason`).toContain(`${v}: ${d.why}`)
+ }
+ // What the caller must DO about a refusal. Without this an agent retries on a timer against
+ // a project the user may not open for hours.
+ expect(clause, `${name}: what to do`).toMatch(/Ask the user to open it/)
+ expect(clause, `${name}: do not retry on a timer`).toMatch(/do not\s+retry it on a timer/)
+ expect(clause, `${name}: do not report done`).toMatch(/do not report the action as done/)
+ }
+ })
+
+ it('the off-screen table never claims a verb is BOTH answered and refused', () => {
+ // The rendering reads two sources; a verb added to a set without being removed from
+ // OFF_SCREEN_REFUSALS would appear on both sides of the same paragraph.
+ const sets = controlVerbSetsForTests()
+ const answered = new Set([
+ ...sets.storeAnswered,
+ ...sets.coldOpenable,
+ ...sets.offCanvas,
+ ...sets.storedNode
+ ])
+ for (const v of answered) expect(offScreenDisposition(v).kind, v).not.toBe('refuse')
+ })
})
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 29ff89e9c..e58743c00 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -260,6 +260,8 @@ import {
needsLiveCanvas,
canColdOpen,
answersOffCanvas,
+ answersFromStoredNodes,
+ offScreenRefusal,
sourceIsControlCapable,
storedNodeListing,
answerBrowserResolve,
@@ -6051,11 +6053,18 @@ export function Canvas() {
return () => setWorktreeActionHandler(null)
}, [onWorktreeAction])
- // Same reason as worktreeControlRef below: the agent-control handler needs the CURRENT
- // travelToProject (defined far below, after the project actions it composes).
- const travelToProjectRef = useRef<(projectId: string) => void>(() => {})
- /** Latest `travelToNode`, for the agent-control handler's off-canvas notice — same reason as
- * travelToProjectRef: that effect mounts ONCE, so it cannot close over the callback. */
+ /**
+ * Latest `closeStoredNodes`, for the agent-control handler's off-canvas `close` — same reason as
+ * worktreeControlRef below: that effect mounts ONCE, so it cannot close over the callback.
+ *
+ * There is deliberately NO `travelToProjectRef` beside it, and there must not be one again: the
+ * agent-control dispatch may not activate a project tab. It held one until the off-screen verbs
+ * were classified (`lib/controlRouting`); a background agent's `close` on a project the human
+ * was not looking at switched their tab and applied that project's saved viewport.
+ */
+ const closeStoredNodesRef = useRef<(projectId: string, ids: readonly string[]) => void>(() => {})
+ /** Latest `travelToNode`, for the agent-control handler's off-canvas notice. Travel to a NODE is
+ * the user's own click on the notice's "Go there" button, not something a verb does. */
const travelToNodeRef = useRef<(nodeId: string) => void>(() => {})
// Latest worktree callbacks for the agent-control handler. That effect mounts ONCE (empty
@@ -9400,17 +9409,28 @@ export function Canvas() {
// two-and-a-half things ONLY the renderer knows: which project owns the source node, whether that
// source is a control-capable agent, and whether the per-project browser-control capability is on
// RIGHT NOW (read live via projectCapabilityGrantedFor). We answer over the SAME source routing
- // every verb uses — travelling to the owning project so its <webview> guest is live for main to
- // drive — and we NEVER run a CDP command. Main makes the security decision (owner + capability +
- // the CDP allowlist) and does the driving itself (browser-drive.ts / browser-actions.ts).
+ // every verb uses, and we NEVER run a CDP command. Main makes the security decision (owner +
+ // capability + the CDP allowlist) and does the driving itself (browser-drive.ts /
+ // browser-actions.ts).
useEffect(() => {
return api.onBrowserControlResolve(({ requestId, sourceNodeId, browserNodeId }) => {
const { projects, activeProjectId } = useProjects.getState()
const route = routeControlSource(projects, activeProjectId, sourceNodeId)
- // Bring the owning project's canvas up so main can find the live guest (needsLiveCanvas is true
- // for `browser`). A closed/blocked/unknown owner just yields the refusal below.
- if (route.kind === 'switch' || route.kind === 'reopen') travelToProjectRef.current(route.projectId)
const owner = projects.find((p) => p.nodes.some((n) => n.id === sourceNodeId))
+ // This used to travel to the owning project so main would find a live <webview> guest to
+ // drive. That was the same screen hijack the dispatch's verbs had, in its loudest form — a
+ // background agent taking the human's tab in order to script a browser they cannot see. It
+ // is a REFUSAL now: `browser` navigates an existing guest and there is no serialized
+ // counterpart for a mounted webview (`open-browser`, which merely places the node, is in
+ // OFF_CANVAS_VERBS and is unaffected). See `OFF_SCREEN_REFUSALS` in lib/controlRouting.
+ if (route.kind === 'switch' || route.kind === 'reopen') {
+ api.sendBrowserControlResolveResult({
+ requestId,
+ ok: false,
+ refusal: offScreenRefusal('browser', owner?.name)
+ })
+ return
+ }
// `browserNodeId` is passed so the answer can carry the browser node's title for the cookie
// trace; the security decision main makes never reads it.
const answer = answerBrowserResolve(owner as unknown as BrowserResolveProject | undefined, sourceNodeId, browserNodeId)
@@ -9427,10 +9447,14 @@ export function Canvas() {
// main never hangs to its 120s timeout.
useEffect(() => {
return api.onAgentControl(async ({ requestId, sourceNodeId, verb, args }) => {
- // Set by the OFF-CANVAS branch below (`answersOffCanvas`): the verb runs against the owning
- // project's SERIALIZED nodes because that project is not on screen. It stays undefined on
- // every other path, which is what makes the on-screen behaviour byte-identical.
- let offCanvas: { project: Project; closed: boolean; created: string[] } | undefined
+ // Set by the OFF-CANVAS branch below (`answersOffCanvas` / `answersFromStoredNodes`): the
+ // verb runs against the owning project's SERIALIZED nodes because that project is not on
+ // screen. It stays undefined on every other path, which is what makes the on-screen
+ // behaviour byte-identical — `ctlNodes()` and friends below are the one-name-for-two-sources
+ // seam, and on screen they are the live array verbatim.
+ let offCanvas:
+ | { project: Project; closed: boolean; created: string[]; nodes: CanvasNode[] }
+ | undefined
const reply = (r: { ok: boolean; message?: string; result?: unknown; error?: string }) => {
// Say WHERE it went, once, in both voices. The verb bodies already say WHAT they made, so
// none of them has to know about routing: the clause is appended here and the human strip
@@ -10192,18 +10216,23 @@ export function Canvas() {
return
}
// ── OFF CANVAS ──────────────────────────────────────────────────────────────────
- // A DISPLAY verb (`show-image` / `show-video` / `show-web` / `open-browser`) whose own
- // project is not on screen. Same objection as the cold open above and the same answer,
- // one set wider: an agent that renders its output as a node is the commonest reason a
- // background session touches the canvas at all, and every one of those calls used to
- // yank the human out of the project they were typing in.
+ // A DISPLAY verb (`show-image` / `show-video` / `show-web` / `open-browser`) or a verb
+ // that acts on nodes which ALREADY EXIST (`write` / `close` / `rename` / `color` /
+ // `link` / `board` / `assign`), whose own project is not on screen. Same objection as
+ // the cold open above and the same answer, two sets wider: an agent that renders its
+ // output as a node, or tidies up after itself, is the commonest reason a background
+ // session touches the canvas at all, and every one of those calls used to yank the human
+ // out of the project they were typing in.
//
- // The difference from the cold open is that there is nothing to defer. These four make
- // an INERT node — a page, a video, an image, a browser — which is complete the moment it
- // is written, so the verb body runs unchanged and only the three things it touches on
- // the canvas are staged: the node counter, the placement source, and the append.
- // See `answersOffCanvas` in lib/controlRouting for why `browser` is not in the set.
- if (answersOffCanvas(verb)) {
+ // The difference from the cold open is that there is nothing to defer. A display verb
+ // makes an INERT node — a page, a video, an image, a browser — complete the moment it is
+ // written; a stored-node verb reaches a tmux pane, a store writer or the board file,
+ // none of which needs React Flow. So the verb bodies run unchanged and only the canvas
+ // touches are staged: the node array they read (`ctlNodes`), the counter, the placement
+ // source, the append, and the edge/kanban writes.
+ // See `answersOffCanvas` / `answersFromStoredNodes` in lib/controlRouting for the sets,
+ // and `OFF_SCREEN_REFUSALS` for why the structural verbs are in neither.
+ if (answersOffCanvas(verb) || answersFromStoredNodes(verb)) {
const ocStore = useProjects.getState()
const owner = ocStore.getProject(route.projectId)
const ocSrc = owner?.nodes.find((n) => n.id === sourceNodeId)
@@ -10213,22 +10242,31 @@ export function Canvas() {
reply({ ok: false, error: 'source node is not a control-capable agent' })
return
}
- offCanvas = { project: owner, closed: route.kind === 'reopen', created: [] }
- // The body below reads the source for its title, cwd and placement geometry. Hydrate
- // the ONE stored node rather than hand-rolling a partial: `nodeStatesToFlow` is what
- // the project load itself uses, so the shape cannot drift from a live node's. It has
- // no `measured` (nothing rendered it), which `placeBelow` already falls back for.
- src = nodeStatesToFlow([ocSrc])[0] as CanvasNode
+ // The bodies below read the source for its title, cwd and placement geometry, and the
+ // stored-node verbs additionally resolve OTHER node ids. Hydrate the project's WHOLE
+ // node array rather than hand-rolling partials: `nodeStatesToFlow` is what the project
+ // load itself uses, so the shape cannot drift from a live node's, and the parent chain
+ // a display verb's placement walks is present. The array has no `measured` (nothing
+ // rendered it), which `placeBelow` already falls back for — and which is exactly why
+ // the five structural verbs refuse instead of joining this branch.
+ const ocNodes = nodeStatesToFlow(owner.nodes) as CanvasNode[]
+ offCanvas = { project: owner, closed: route.kind === 'reopen', created: [], nodes: ocNodes }
+ src = ocNodes.find((n) => n.id === sourceNodeId)
} else {
- travelToProjectRef.current(route.projectId)
+ // NEVER travel. This is where `travelToProject` used to be called, and it was the
+ // steal: the tab switched and the owning project's SAVED viewport was applied, so the
+ // human's focus, camera and typing context were taken by a call they did not make.
+ // A refusal an agent can act on is strictly better than hijacking someone's screen —
+ // see `offScreenRefusal`, which names the project so the agent can ask for it by name.
+ reply({ ok: false, error: offScreenRefusal(verb, projects.find((p) => p.id === route.projectId)?.name) })
+ return
}
}
- // Wait for the node to show up on the canvas: after a travel, because the active-project
- // effect hydrates React Flow a tick later; on `active`, because a control call can land
- // while the BOOT load of the owning project is still in flight — the very moment a
- // re-adopted agent starts talking again. `unknown`/`blocked` have no canvas to wait for.
- // An off-canvas answer has its source already and is deliberately NOT waiting for a
- // canvas: waiting for one is what travelling was for.
+ // Wait for the node to show up on the canvas: on `active`, a control call can land while
+ // the BOOT load of the owning project is still in flight — the very moment a re-adopted
+ // agent starts talking again. `unknown`/`blocked` have no canvas to wait for, and every
+ // `switch`/`reopen` has already returned above (answered off canvas, or refused). This
+ // wait used to cover the travel too; nothing travels any more.
if (!offCanvas && route.kind !== 'unknown' && route.kind !== 'blocked') {
src = await waitForCanvasNode(() => nodesRef.current.find((n) => n.id === sourceNodeId))
}
@@ -10267,6 +10305,27 @@ export function Canvas() {
})()
const ctlSsh = ctlProject?.ssh
const sshFor = (cwd?: string) => nodeSshFor(ctlSsh, cwd)
+ // The node array THIS control call acts on, and the one name every verb body uses for it.
+ // On screen it IS `nodesRef.current` — same object, so the on-screen path is byte-identical.
+ // Off canvas it is the owning project's serialized nodes, hydrated once in the routing
+ // branch above. Reading the live array off canvas would answer a background agent's call
+ // with whatever the human happens to be looking at, which is how `--node <id>` could resolve
+ // against a stranger's project.
+ const ctlNodes = (): CanvasNode[] =>
+ offCanvas ? offCanvas.nodes : (nodesRef.current as CanvasNode[])
+ // `linkEndpointOf` off canvas. Same answer, read out of the hydrated array: the live one
+ // holds another project's nodes, so every id would resolve to null (or, worse, to a
+ // same-named node over there).
+ const ctlLinkEndpointOf = (id: string): LinkEndpoint | null => {
+ if (!offCanvas) return linkEndpointOf(id)
+ const n = offCanvas.nodes.find((x) => x.id === id)
+ if (!n) return null
+ // `nodeStatesToFlow` has already migrated the legacy `tags:['claude']` marker into
+ // `data.agentId`, so the live helper's third fallback is the only one left to mirror.
+ const a =
+ ((n.data.agentId as AgentId | undefined) ?? useAgentStatus.getState().byId[id]?.agentId)
+ return { kind: n.type ?? 'terminal', contextCapable: !!a && canContextLink(a) }
+ }
// A prompt too long for a typed line goes into a file the pane's own shell reads (#706).
// See lib/promptSpill.ts for the budget and for why an SSH project is excluded: the file
// would land on THIS machine while the pane runs on the host. Fails open in every
@@ -10290,7 +10349,10 @@ export function Canvas() {
const srcH = src.measured?.height ?? (src.height as number) ?? 400
// src.position is group-relative when the agent sits inside a group frame — resolve the
// absolute position first so placements land below the agent regardless of grouping.
- const srcGroup = src.parentId ? nodesRef.current.find((n) => n.id === src.parentId) : undefined
+ // `ctlNodes()`, not the live array: off canvas the parent frame lives in the OWNING
+ // project, and looking it up in the live one resolved either nothing (a group-relative
+ // position then read as absolute) or an unrelated node that happens to share the id.
+ const srcGroup = src.parentId ? ctlNodes().find((n) => n.id === src.parentId) : undefined
const srcAbs = {
x: src.position.x + (srcGroup?.position.x ?? 0),
y: src.position.y + (srcGroup?.position.y ?? 0)
@@ -10329,13 +10391,24 @@ export function Canvas() {
const bridgeTo = (
fromId: string,
targetIds: string[],
- lookup: (id: string) => LinkEndpoint | null = linkEndpointOf
+ lookup: (id: string) => LinkEndpoint | null = ctlLinkEndpointOf
) => {
- const plan = planBridges(fromId, targetIds, lookup, [...linkEdgesRef.current, ...drawn])
+ // Off canvas the existing edges are the OWNING project's persisted `bridges` — React
+ // Flow's array belongs to whatever the human is looking at, so deduping against it would
+ // let a link be drawn twice (or refuse one that does not exist yet).
+ const existing = offCanvas ? (offCanvas.project.bridges ?? []) : linkEdgesRef.current
+ const plan = planBridges(fromId, targetIds, lookup, [...existing, ...drawn])
if (plan.edges.length) {
drawn.push(...plan.edges)
- setLinkEdges((es) => [...es, ...plan.edges])
- markDirty()
+ if (offCanvas) {
+ // The same store path the cold open takes for the bridges IT owes. `appendCanvasLinks`
+ // dedupes by id AND by endpoint pair, so a re-link is a no-op rather than a duplicate.
+ useProjects.getState().appendCanvasLinks(offCanvas.project.id, { bridges: plan.edges })
+ void writeDisk()
+ } else {
+ setLinkEdges((es) => [...es, ...plan.edges])
+ markDirty()
+ }
}
return plan
}
@@ -11016,7 +11089,7 @@ export function Canvas() {
reply({ ok: false, error: 'link requires --to <id,id>' })
return
}
- if (!linkEndpointOf(from)) {
+ if (!ctlLinkEndpointOf(from)) {
reply({ ok: false, error: `link: --from names no existing node (${from})` })
return
}
@@ -11536,7 +11609,7 @@ export function Canvas() {
// THIRD session, and read back by the phone, push alerts and the board log. Landing it
// clean at the door is what keeps a control character out of all of them at once.
const title = oneLine(args.title ?? '')
- const target = nodesRef.current.find((nd) => nd.id === id)
+ const target = ctlNodes().find((nd) => nd.id === id)
if (!target) {
reply({ ok: false, error: `rename: no node with id ${id}` })
return
@@ -11549,10 +11622,19 @@ export function Canvas() {
const prevTitle = (target.data.title as string) ?? ''
// Same semantics as renameSession: an explicit rename takes ownership of the
// name (titleAuto off) and mirrors it into a rename-capable agent's session.
- setNodes((ns) =>
- ns.map((nd) => (nd.id === id ? { ...nd, data: { ...nd.data, title, titleAuto: false } } : nd))
- )
- markDirty()
+ if (offCanvas) {
+ // `renameNode` writes title + titleAuto:false straight into the serialized node —
+ // the store's own writer for a project that is not active, with no round-trip
+ // through the serializers. It is the same call the sessions sidebar makes when it
+ // renames a node in another project.
+ useProjects.getState().renameNode(offCanvas.project.id, id, title)
+ void writeDisk()
+ } else {
+ setNodes((ns) =>
+ ns.map((nd) => (nd.id === id ? { ...nd, data: { ...nd.data, title, titleAuto: false } } : nd))
+ )
+ markDirty()
+ }
const agentId = target.data.agentId as AgentId | undefined
if (agentId && canRename(agentId) && title) {
// Gated twice: on the pane's owner (an agent that opens a node and renames it in the
@@ -11578,21 +11660,29 @@ export function Canvas() {
const ids = [
...new Set((args.node ?? '').split(',').map((id) => id.trim()).filter(Boolean))
]
- const live = nodesRef.current
+ const live = ctlNodes()
const colored = ids.filter((id) => live.some((node) => node.id === id))
if (!colored.length) {
reply({ ok: false, error: 'color: none of the given node ids exist' })
return
}
const selected = new Set(colored)
- setNodes((nodes) =>
- nodes.map((node) =>
- selected.has(node.id)
- ? { ...node, data: { ...node.data, color } }
- : node
+ if (offCanvas) {
+ // `recolorNode` is the store's own per-node writer for a non-active project — one
+ // call per id, no serializer round-trip. Same shape as `rename` above.
+ const rcStore = useProjects.getState()
+ for (const id of colored) rcStore.recolorNode(offCanvas.project.id, id, color)
+ void writeDisk()
+ } else {
+ setNodes((nodes) =>
+ nodes.map((node) =>
+ selected.has(node.id)
+ ? { ...node, data: { ...node.data, color } }
+ : node
+ )
)
- )
- markDirty()
+ markDirty()
+ }
const skipped = ids.length - colored.length
const note = skipped ? ` (${skipped} unknown id(s) skipped)` : ''
reply({
@@ -11784,7 +11874,7 @@ export function Canvas() {
// 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)
+ const targets = parseCloseTargets(args.node, ctlNodes())
if (targets.kind === 'error') {
reply({ ok: false, error: targets.error })
return
@@ -11796,6 +11886,24 @@ export function Canvas() {
: bulkCloseMessage(srcTitle, targets.labels)
const closeLabel = targets.kind === 'single' ? 'Close' : `Close ${closeIds.length}`
const runClose = (): void => {
+ if (offCanvas) {
+ // Off canvas the canonical teardown is unavailable: `deleteNodes` reads the live
+ // node array and records its closed-session / reopen-history entries against the
+ // ACTIVE project, which is somebody else's here. `closeStoredNodes` is the
+ // cross-project teardown the sessions sidebar has always used — it still ends the
+ // tmux session (remote included, resolved from the persisted index) and still
+ // frees a closed frame's children. The control ropes are left alone for the same
+ // reason: `setControlEdges` addresses the wrong project's edges.
+ closeStoredNodesRef.current(offCanvas.project.id, closeIds)
+ reply({
+ ok: true,
+ message:
+ closeIds.length === 1
+ ? `closed ${closeIds[0]}`
+ : `closed ${closeIds.length} nodes: ${closeIds.join(', ')}`
+ })
+ return
+ }
// 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
@@ -11852,14 +11960,18 @@ export function Canvas() {
return
}
case 'board': {
- // Read-only snapshot of the CURRENTLY OPEN project's kanban board: columns + the
- // session cards filed in each, plus the virtual Ungrouped column. The board's cards
- // ARE the canvas session nodes (toKanbanSession), derived live — the board file only
- // stores column assignments, so a session with no/dangling assignment sits Ungrouped.
- const store = useProjects.getState()
- const pid = store.activeProjectId
- const board = store.getProject(pid ?? '')?.kanban
- const sessions = nodesRef.current
+ // Read-only snapshot of the CALLER'S project's kanban board: columns + the session
+ // cards filed in each, plus the virtual Ungrouped column. The board's cards ARE the
+ // canvas session nodes (toKanbanSession), derived from `ctlNodes()` — the board file
+ // only stores column assignments, so a session with no/dangling assignment sits
+ // Ungrouped.
+ //
+ // `ctlProject`, not `activeProjectId`: off canvas those are two different projects, and
+ // reading the active one would answer a background agent's `board` with whatever the
+ // human happens to be looking at. On screen they are the same project, which is why
+ // the old read was never wrong in practice — the travel had already made it true.
+ const board = ctlProject?.kanban
+ const sessions = ctlNodes()
.map(toKanbanSession)
.filter((s): s is KanbanSession => s !== null)
const titleOf = new Map(sessions.map((s) => [s.id, s.title || 'Untitled']))
@@ -11905,15 +12017,17 @@ export function Canvas() {
// board's own scope note called out as missing. Board metadata ONLY: assignNode writes
// an assignment, it never touches the canvas node, its group, or the running session.
const nodeId = (args.node ?? '').trim()
- const target = nodesRef.current.find((n) => n.id === nodeId)
+ const target = ctlNodes().find((n) => n.id === nodeId)
if (!target || toKanbanSession(target) === null) {
reply({ ok: false, error: `assign: --node names no session card (${nodeId || 'missing'})` })
return
}
const store = useProjects.getState()
- const pid = store.activeProjectId
+ // The CALLER'S project, not the active one — see `board` above for why the two used to
+ // look interchangeable and are not.
+ const pid = ctlProject?.id
if (!pid) {
- reply({ ok: false, error: 'assign: no active project' })
+ reply({ ok: false, error: 'assign: no project owns this session' })
return
}
// Read prev fresh so the board-log diff below has the SAME base the write mutates —
@@ -11939,7 +12053,7 @@ export function Canvas() {
// board feed reads identically whether a person or an agent moved the card. cardTitle
// returns '' ONLY for a dead node; a live card with no title maps to 'Untitled'.
const cardTitle = (id: string): string => {
- const n = nodesRef.current.find((x) => x.id === id)
+ const n = ctlNodes().find((x) => x.id === id)
const card = n ? toKanbanSession(n) : null
return card ? card.title || 'Untitled' : ''
}
@@ -11967,6 +12081,53 @@ export function Canvas() {
}, [])
// ---- sessions sidebar actions ----
+ /**
+ * End sessions and drop their nodes from a project that is NOT on screen — the cross-project
+ * teardown, extracted so its two callers cannot drift: the sessions sidebar / session-memory
+ * panel (`closeSession` below) and canvas control's off-canvas `close`.
+ *
+ * It is `deleteNodes` minus the things only a live canvas has. tmux sessions are keyed by node
+ * id, so `transport.destroy` works for a node that was never mounted — including a REMOTE one,
+ * since `runEndSession` resolves the owning SSH host from the persisted index rather than from a
+ * live client (core/remote-end.ts). What is deliberately NOT reproduced: the closed-session
+ * ledger and the ⇧⌘T reopen history, both of which `deleteNodes` records against the ACTIVE
+ * project — recording another project's close there would put the entry on the wrong canvas. The
+ * sidebar's branch has always made that trade; this is the same trade with one copy.
+ *
+ * Known residual, inherited: display ropes (`project.ropes`) that pointed at a removed node stay
+ * in the file. React Flow drops an edge with a missing endpoint on the next load, and
+ * `appendCanvasLinks` is append-only, so pruning them needs a store writer that does not exist
+ * yet. It is decoration, not data.
+ */
+ const closeStoredNodes = useCallback(
+ (projectId: string, ids: readonly string[]) => {
+ const store = useProjects.getState()
+ const nodes = store.getProject(projectId)?.nodes ?? []
+ for (const id of ids) {
+ // A deleted frame's children SURVIVE it (deleteNodes frees them to absolute positions).
+ // `moveNodeToGroup(…, null)` is the serialized twin of that conversion — without it the
+ // children keep a `parentId` pointing at a node that no longer exists.
+ for (const child of nodes) {
+ if (child.parentId === id) store.moveNodeToGroup(projectId, child.id, null)
+ }
+ disposeTerminalOnUnmount(sessionForProject(projectId).id, id) // may be parked from a project switch
+ transport.destroy(id)
+ useAgentStatus.getState().remove(id)
+ // Unmount no longer clears the fan-out (issue #402), so a permanent removal must — the
+ // node unmounted at the project switch with its cards kept in the store.
+ useAgentNodes.getState().clearForParent(id)
+ useAgentNodes.getState().clearLoop(id)
+ // Same teardown symmetry as deleteNodes (review #363 M-1): the attach-consent mirror
+ // dies with the node.
+ clearAttachConsent(id)
+ useWebviewKeepAlive.getState().drop(id)
+ store.removeNode(projectId, id)
+ }
+ void writeDisk()
+ },
+ [writeDisk]
+ )
+
// Close (end) a session. tmux sessions are keyed by node id, so destroy works for an
// inactive project's node even though it isn't mounted; then drop it from the store.
const closeSession = useCallback(
@@ -11985,18 +12146,7 @@ export function Canvas() {
if (projectId === activeProjectId) {
deleteNodes([id])
} else {
- disposeTerminalOnUnmount(sessionForProject(projectId).id, id) // node may be parked from the project switch
- transport.destroy(id)
- useAgentStatus.getState().remove(id)
- // Unmount no longer clears the fan-out (issue #402), so this cross-project delete
- // must — the node unmounted at the project switch with its cards kept in the store.
- useAgentNodes.getState().clearForParent(id)
- // Same teardown symmetry as deleteNodes (review #363 M-1): the attach-consent
- // mirror dies with the node.
- clearAttachConsent(id)
- useWebviewKeepAlive.getState().drop(id)
- useProjects.getState().removeNode(projectId, id)
- void writeDisk()
+ closeStoredNodes(projectId, [id])
}
// The session-memory panel's remote leg (see `killSessionById`): the local destroy above
// cannot reach a HOST's tmux session unless a live client carries `sshRemote`. Runs only
@@ -12006,7 +12156,7 @@ export function Canvas() {
}
})
},
- [activeProjectId, deleteNodes, writeDisk]
+ [activeProjectId, deleteNodes, closeStoredNodes]
)
/**
@@ -13417,10 +13567,10 @@ export function Canvas() {
},
[reopenProject, switchProject]
)
- // Latest project-travel callback for the agent-control handler: that effect mounts ONCE (empty
+ // Latest cross-project teardown for the agent-control handler: that effect mounts ONCE (empty
// deps), so it cannot close over this callback — same reason as worktreeControlRef.
useEffect(() => {
- travelToProjectRef.current = travelToProject
+ closeStoredNodesRef.current = closeStoredNodes
})
// Jump to the node a peer is focused on. focusNodeById already handles the same-project focus and
diff --git a/src/renderer/canvas/control-cold-open.source.test.ts b/src/renderer/canvas/control-cold-open.source.test.ts
index d348aebd3..a840a8d8a 100644
--- a/src/renderer/canvas/control-cold-open.source.test.ts
+++ b/src/renderer/canvas/control-cold-open.source.test.ts
@@ -22,37 +22,40 @@ const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').repla
* follows it. Bounded by that guard rather than by the travel call further down, so the pins
* below judge THIS block and never inherit a passing verdict from the one after it — the two are
* separate branches with separate contracts (`control-off-canvas.source.test.ts`). */
+const OFF_CANVAS_GUARD = 'if (answersOffCanvas(verb) || answersFromStoredNodes(verb)) {'
function coldOpenBody(): string {
const start = src.indexOf('if (canColdOpen(verb)) {')
expect(start, 'the cold-open guard').toBeGreaterThan(-1)
- const end = src.indexOf('if (answersOffCanvas(verb)) {', start)
+ const end = src.indexOf(OFF_CANVAS_GUARD, start)
expect(end, 'the off-canvas guard after the block').toBeGreaterThan(start)
return src.slice(start, end)
}
describe('the cold-open dispatch block (source pins)', () => {
- it('stands IN FRONT of the travel call — an open verb never reaches it', () => {
- // The travel call is what moved the user's screen. Scoped to the dispatch's source-routing
- // block (Canvas has one other, unrelated travel for the browser-verb guest lookup), the
- // cold-open guard must precede the single travel in it, or the block is dead code sitting
- // behind the very thing it replaces.
+ it('stands IN FRONT of the off-screen refusal — an open verb never reaches it', () => {
+ // The travel call this block was written to stand in front of is GONE: nothing in the
+ // agent-control dispatch may activate a project tab, so the fall-through is now a refusal
+ // (`offScreenRefusal`). The cold-open guard must still precede it, or the block is dead code
+ // sitting behind the very thing it replaces — and an `open-claude` from a background agent
+ // would be refused instead of queued.
const from = src.indexOf('routeControlSource(projects, activeId, sourceNodeId)')
expect(from, 'the source-routing lookup').toBeGreaterThan(-1)
const to = src.indexOf('waitForCanvasNode(', from)
expect(to, 'the post-routing canvas wait').toBeGreaterThan(from)
const routing = src.slice(from, to)
- expect(routing.match(/travelToProjectRef\.current\(route\.projectId\)/g)?.length).toBe(1)
+ expect(routing).not.toContain('travelToProjectRef')
const guard = routing.indexOf('if (canColdOpen(verb)) {')
- const travel = routing.indexOf('travelToProjectRef.current(route.projectId)')
+ const refusal = routing.indexOf('reply({ ok: false, error: offScreenRefusal(verb,')
expect(guard, 'the cold-open guard inside the routing block').toBeGreaterThan(-1)
- expect(guard).toBeLessThan(travel)
- // …and it RETURNS, so control cannot fall through to the travel after writing the node.
+ expect(refusal, 'the off-screen refusal').toBeGreaterThan(guard)
+ // …and it RETURNS, so control cannot fall through to the refusal after writing the node —
+ // which would answer an agent "nothing was changed" about a node it just queued.
expect(coldOpenBody()).toMatch(/queuedIds: coldIds\s*\}\s*\}\)\s*return\s*\}/)
})
- it('the guard polarity is not inverted — a NON-cold verb must still travel', () => {
+ it('the guard polarity is not inverted — a NON-cold verb must not be cold-written', () => {
// `if (!canColdOpen(verb))` would cold-write `write`/`close`/`group` into a serialized project
- // (silently doing nothing useful) and travel for every open — the exact swap of the fix.
+ // (silently doing nothing useful) and refuse every open — the exact swap of the fix.
expect(src).toContain('if (canColdOpen(verb)) {')
expect(src).not.toContain('if (!canColdOpen(verb))')
})
diff --git a/src/renderer/canvas/control-off-canvas.source.test.ts b/src/renderer/canvas/control-off-canvas.source.test.ts
index 15fdc61a0..593380c86 100644
--- a/src/renderer/canvas/control-off-canvas.source.test.ts
+++ b/src/renderer/canvas/control-off-canvas.source.test.ts
@@ -18,13 +18,13 @@ import { readFileSync } from 'node:fs'
*/
const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
-/** The off-canvas block: from its `if (answersOffCanvas(verb))` guard to the travel call it stands
- * in front of. */
+/** The off-canvas block: from its guard to the refusal that now stands where the travel did. */
+const OFF_CANVAS_GUARD = 'if (answersOffCanvas(verb) || answersFromStoredNodes(verb)) {'
function offCanvasBody(): string {
- const start = src.indexOf('if (answersOffCanvas(verb)) {')
+ const start = src.indexOf(OFF_CANVAS_GUARD)
expect(start, 'the off-canvas guard').toBeGreaterThan(-1)
- const end = src.indexOf('travelToProjectRef.current(route.projectId)', start)
- expect(end, 'the travel call after the block').toBeGreaterThan(start)
+ const end = src.indexOf('reply({ ok: false, error: offScreenRefusal(verb,', start)
+ expect(end, 'the off-screen refusal after the block').toBeGreaterThan(start)
return src.slice(start, end)
}
@@ -46,29 +46,31 @@ function addAndConnectBody(): string {
}
describe('the off-canvas dispatch block (source pins)', () => {
- it('stands IN FRONT of the travel call — a display verb never reaches it', () => {
- // The travel call is what moved the user's screen. Scoped to the dispatch's source-routing
- // block (Canvas has one other, unrelated travel for the browser-verb guest lookup), the
- // off-canvas guard must precede the single travel in it, or the block is dead code sitting
- // behind the very thing it replaces.
+ it('stands IN FRONT of the refusal that replaced the travel call', () => {
+ // The travel call is what moved the user's screen, and it is gone. Scoped to the dispatch's
+ // source-routing block, the off-canvas guard must precede the refusal, or the block is dead
+ // code sitting behind the very thing it stands in for.
const from = src.indexOf('routeControlSource(projects, activeId, sourceNodeId)')
expect(from, 'the source-routing lookup').toBeGreaterThan(-1)
const to = src.indexOf('waitForCanvasNode(', from)
expect(to, 'the post-routing canvas wait').toBeGreaterThan(from)
const routing = src.slice(from, to)
- expect(routing.match(/travelToProjectRef\.current\(route\.projectId\)/g)?.length).toBe(1)
- const guard = routing.indexOf('if (answersOffCanvas(verb)) {')
- const travel = routing.indexOf('travelToProjectRef.current(route.projectId)')
+ const guard = routing.indexOf(OFF_CANVAS_GUARD)
+ const refusal = routing.indexOf('reply({ ok: false, error: offScreenRefusal(verb,')
expect(guard, 'the off-canvas guard inside the routing block').toBeGreaterThan(-1)
- expect(guard).toBeLessThan(travel)
- // …and the travel is its ELSE, so the two are exclusive by construction rather than by a
+ expect(refusal, 'the off-screen refusal').toBeGreaterThan(guard)
+ // …and the refusal is its ELSE, so the two are exclusive by construction rather than by a
// `return` someone can move.
- expect(routing).toMatch(/\} else \{\s*travelToProjectRef\.current\(route\.projectId\)/)
+ expect(routing).toMatch(/\} else \{[\s\S]{0,800}?reply\(\{ ok: false, error: offScreenRefusal\(verb,/)
+ // A refusal REPLIES and stops — it must never fall through into the canvas wait, which would
+ // burn the 120 s timeout before answering.
+ expect(routing.slice(refusal)).toMatch(/offScreenRefusal\(verb,[\s\S]{0,200}?\n\s*return\n/)
})
it('the guard polarity is not inverted', () => {
- expect(src).toContain('if (answersOffCanvas(verb)) {')
+ expect(src).toContain(OFF_CANVAS_GUARD)
expect(src).not.toContain('if (!answersOffCanvas(verb))')
+ expect(src).not.toContain('if (!answersFromStoredNodes(verb))')
})
it('never travels, activates, reopens or moves the camera', () => {
@@ -103,8 +105,11 @@ describe('the off-canvas dispatch block (source pins)', () => {
expect(body).toContain('ocStore.getProject(route.projectId)')
expect(body).toMatch(/owner\?\.nodes\.find\(\(n\) => n\.id === sourceNodeId\)/)
// Hydrated with the same transform the project load uses, so the shape cannot drift from a
- // live node's — the verb bodies read `src.data.title`, `src.data.cwd` and its geometry.
- expect(body).toContain('nodeStatesToFlow([ocSrc])[0]')
+ // live node's — the verb bodies read `src.data.title`, `src.data.cwd` and its geometry. The
+ // WHOLE array, not just the source: the stored-node verbs resolve other ids against it, and a
+ // display verb's placement walks the source's parent chain.
+ expect(body).toContain('nodeStatesToFlow(owner.nodes) as CanvasNode[]')
+ expect(body).toContain('src = ocNodes.find((n) => n.id === sourceNodeId)')
})
it('the acting project is the SOURCE’s, not whatever is on screen', () => {
diff --git a/src/renderer/canvas/control-stored-node.source.test.ts b/src/renderer/canvas/control-stored-node.source.test.ts
new file mode 100644
index 000000000..8ef9df39b
--- /dev/null
+++ b/src/renderer/canvas/control-stored-node.source.test.ts
@@ -0,0 +1,167 @@
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+
+/**
+ * STRUCTURAL pins for the STORED-NODE branch of the canvas-control dispatch — the sibling of
+ * `control-cold-open.source.test.ts` and `control-off-canvas.source.test.ts`, and for the same
+ * reason: the branch lives inside a 14,000-line React component's IPC listener with no unit seam,
+ * and what it must be pinned on are properties of the SOURCE.
+ *
+ * THE BUG this closes, which the cold-open and display-verb fixes left open (field report,
+ * 2026-09-15): the user was working in ANOTHER project, a background agent issued a `close`, and
+ * the app switched their view to the agent's project. Routing is by SOURCE, so every verb outside
+ * the three earlier carve-outs called `travelToProject` to reach its own canvas — `close`,
+ * `write`, `rename`, `color`, `link`, `board`, `assign` and the eleven that now refuse.
+ *
+ * The hazard this file guards is narrower and sharper than "does it travel" (that is
+ * `test/acceptance/control-verb-disposition.test.ts`): a verb body that resolves `--node` against
+ * `nodesRef.current` while answering for ANOTHER project reads the wrong canvas. It does not throw
+ * and it does not travel — it silently answers about, or writes to, whatever the human happens to
+ * be looking at. Every id-resolving read in these seven cases must go through `ctlNodes()`.
+ */
+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+
+/** One `case '<verb>': {` body, up to the next case label at the same indentation. */
+function caseBody(verb: string): string {
+ const at = src.indexOf(`case '${verb}': {`)
+ expect(at, `case '${verb}'`).toBeGreaterThan(-1)
+ // `assign` is the LAST case, so fall back to the switch's `default:` label.
+ const next = src.indexOf("\n case '", at + 1)
+ const end = next > at ? next : src.indexOf('\n default:', at + 1)
+ expect(end, `the case after '${verb}'`).toBeGreaterThan(at)
+ return src.slice(at, end)
+}
+
+/** Line comments explain what a block must NOT do, so a negative pin has to judge the code. */
+function code(body: string): string {
+ return body
+ .split('\n')
+ .filter((l) => !l.trim().startsWith('//') && !l.trim().startsWith('*'))
+ .join('\n')
+}
+
+const STORED_NODE_CASES = ['close', 'rename', 'color', 'link', 'board', 'assign'] as const
+
+describe('the stored-node dispatch cases (source pins)', () => {
+ it('none of them resolves a node id against the LIVE canvas', () => {
+ // The whole hazard. Off canvas `nodesRef.current` holds the project the HUMAN is looking at,
+ // so `--node term-7` would resolve against a stranger's canvas: `rename` renames their node,
+ // `close` kills their session, `board` reports their board. `ctlNodes()` is the one name for
+ // "the array this call acts on" and is `nodesRef.current` verbatim on screen.
+ for (const verb of STORED_NODE_CASES) {
+ expect(code(caseBody(verb)), verb).not.toContain('nodesRef.current')
+ }
+ })
+
+ it('`write` needs no node array at all — it reaches a pane through main', () => {
+ // It is on the stored-node list only because it used to TRAVEL to get here. If a future edit
+ // gives it a canvas lookup, that lookup owes `ctlNodes()` like every other case.
+ expect(code(caseBody('write'))).not.toContain('nodesRef.current')
+ expect(caseBody('write')).toContain('api.pty.sendText(args.node')
+ })
+
+ it('`close` runs the cross-project teardown off canvas, never deleteNodes', () => {
+ const body = caseBody('close')
+ const off = code(body.slice(body.indexOf('if (offCanvas) {'), body.indexOf('deleteNodes(closeIds)')))
+ expect(off.length, 'the off-canvas branch precedes deleteNodes').toBeGreaterThan(0)
+ // `deleteNodes` reads the live node array and records its closed-session ledger and ⇧⌘T
+ // reopen entry against the ACTIVE project — another project's close filed on the wrong canvas.
+ expect(off).toContain('closeStoredNodesRef.current(offCanvas.project.id, closeIds)')
+ expect(off).not.toContain('deleteNodes(')
+ // ...and it must not touch the live control ropes, which belong to the project on screen.
+ expect(off).not.toContain('setControlEdges')
+ // It still answers. A teardown that returns without replying hangs the CLI to its 120s timeout.
+ expect(off).toContain('reply({')
+ })
+
+ it('`close` still ENDS the session, which is the half that must not be lost', () => {
+ // A refusal would have been acceptable for the node removal; silently leaving a tmux session
+ // running while telling the agent it closed would not. `transport.destroy` reaches a REMOTE
+ // node with no live client because `runEndSession` resolves the owning host from the persisted
+ // index (core/remote-end.ts) — that is the fact this whole branch rests on.
+ const at = src.indexOf('const closeStoredNodes = useCallback(')
+ expect(at, 'closeStoredNodes').toBeGreaterThan(-1)
+ const body = src.slice(at, src.indexOf('const closeSession = useCallback(', at))
+ expect(body).toContain('transport.destroy(id)')
+ expect(body).toContain('store.removeNode(projectId, id)')
+ // A deleted frame's children survive it, exactly as deleteNodes frees them.
+ expect(body).toContain('moveNodeToGroup(projectId, child.id, null)')
+ // The persisted teardown deleteNodes owes: status, fan-out, loop card, consent, keep-alive.
+ for (const call of [
+ 'useAgentStatus.getState().remove(id)',
+ 'useAgentNodes.getState().clearForParent(id)',
+ 'useAgentNodes.getState().clearLoop(id)',
+ 'clearAttachConsent(id)',
+ 'useWebviewKeepAlive.getState().drop(id)'
+ ]) {
+ expect(body, call).toContain(call)
+ }
+ })
+
+ it('the sessions sidebar and canvas control share ONE cross-project teardown', () => {
+ // They were two copies (the sidebar's inline `else` branch, and whatever `close` would have
+ // hand-rolled). Two copies of a teardown is how one of them quietly stops clearing a loop card.
+ const at = src.indexOf('const closeSession = useCallback(')
+ const body = src.slice(at, src.indexOf('const killSessionById = useCallback(', at))
+ expect(body).toContain('closeStoredNodes(projectId, [id])')
+ expect(code(body)).not.toContain('transport.destroy(')
+ })
+
+ it('`rename` and `color` write through the store’s own per-node writers', () => {
+ // `renameNode`/`recolorNode` mutate the serialized node directly. The alternative — hydrate,
+ // patch, `flowToNodeStates` back — is a round-trip through the serializers on a node nobody
+ // asked to re-serialize, and drift there is invisible until the project is next opened.
+ const rename = caseBody('rename')
+ expect(rename).toContain('renameNode(offCanvas.project.id, id, title)')
+ expect(rename).toContain('setNodes((ns) =>') // the on-screen path is untouched
+ const color = caseBody('color')
+ expect(color).toContain('recolorNode(offCanvas.project.id, id, color)')
+ expect(color).toContain('setNodes((nodes) =>')
+ })
+
+ it('`rename` still mirrors the name into the live session either way', () => {
+ // The `/rename` push goes through main to a tmux pane, so it works for an unmounted node too.
+ // Losing it off canvas would leave the node renamed on the canvas and not in the session.
+ expect(caseBody('rename')).toContain('pushSessionRename(api.pty, id, title, prevTitle)')
+ })
+
+ it('`board` and `assign` act on the CALLER’s project, not the active one', () => {
+ // A second bug that was hiding behind the first: both read `store.activeProjectId`, which off
+ // canvas is the human's project. It was never wrong in practice only because the travel had
+ // already made the two the same — remove the travel and it becomes a live misread.
+ expect(code(caseBody('board'))).not.toContain('activeProjectId')
+ expect(code(caseBody('assign'))).not.toContain('activeProjectId')
+ expect(caseBody('board')).toContain('ctlProject?.kanban')
+ expect(caseBody('assign')).toContain('const pid = ctlProject?.id')
+ })
+
+ it('`link` dedupes against the OWNING project’s persisted bridges', () => {
+ const at = src.indexOf('const bridgeTo = (')
+ expect(at).toBeGreaterThan(-1)
+ const body = src.slice(at, src.indexOf('const addAndConnect = (', at))
+ // React Flow's edge array belongs to whatever is on screen; deduping against it off canvas
+ // would draw a link that already exists, or refuse one that does not.
+ expect(body).toContain('offCanvas ? (offCanvas.project.bridges ?? []) : linkEdgesRef.current')
+ expect(body).toContain('appendCanvasLinks(offCanvas.project.id, { bridges: plan.edges })')
+ // The live writers stay on the live branch.
+ const off = code(body.slice(body.indexOf('if (offCanvas) {'), body.indexOf('} else {')))
+ expect(off).not.toContain('setLinkEdges')
+ expect(off).not.toContain('markDirty()')
+ })
+
+ it('the endpoint lookup follows the same array', () => {
+ // `linkEndpointOf` reads `nodesRef.current`. Off canvas every id would answer null — `link`
+ // would refuse every target with "names no existing node", which reads as a broken verb.
+ expect(src).toContain('const ctlLinkEndpointOf = (id: string): LinkEndpoint | null => {')
+ expect(src).toContain('if (!offCanvas) return linkEndpointOf(id)')
+ expect(caseBody('link')).toContain('ctlLinkEndpointOf(from)')
+ })
+
+ it('`ctlNodes` is the live array verbatim on screen', () => {
+ // The byte-identical guarantee for the on-screen path: no copy, no filter, no clone — the same
+ // object `nodesRef.current` returns, so nothing about the existing behaviour can shift.
+ expect(src).toContain(
+ 'offCanvas ? offCanvas.nodes : (nodesRef.current as CanvasNode[])'
+ )
+ })
+})
diff --git a/src/renderer/lib/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.ts
index cc2320140..eca5390ab 100644
--- a/src/renderer/lib/controlRouting.test.ts
+++ b/src/renderer/lib/controlRouting.test.ts
@@ -4,6 +4,9 @@ import {
needsLiveCanvas,
canColdOpen,
answersOffCanvas,
+ answersFromStoredNodes,
+ offScreenDisposition,
+ offScreenRefusal,
controlVerbSetsForTests,
sourceIsControlCapable,
storedNodeListing,
@@ -338,3 +341,81 @@ describe('storedNodeListing', () => {
])
})
})
+
+describe('the off-screen disposition table (the verbs that used to travel)', () => {
+ it('the verbs that act on existing nodes are answered from the store, not by travelling', () => {
+ // The field report: the user was typing in another project, a background agent issued a
+ // `close`, and the app switched their tab. These seven reach a pane, a store writer or the
+ // board file — none of them needs React Flow — so none of them has any business moving a
+ // camera to get there.
+ for (const v of ['write', 'close', 'rename', 'color', 'link', 'board', 'assign']) {
+ expect(answersFromStoredNodes(v), v).toBe(true)
+ expect(offScreenDisposition(v), v).toEqual({ kind: 'stored-node' })
+ }
+ })
+
+ it('the structural verbs refuse, and each says WHY in its own words', () => {
+ // A refusal an agent can act on beats hijacking the human's screen. The reasons are per verb
+ // because the caller's next move differs: an `arrange` can wait for the human, a `branch`
+ // cannot happen at all until that terminal is mounted.
+ const why = (v: string) => {
+ const d = offScreenDisposition(v)
+ expect(d.kind, v).toBe('refuse')
+ return d.kind === 'refuse' ? d.why : ''
+ }
+ expect(why('arrange')).toMatch(/measured/)
+ expect(why('group')).toMatch(/measured/)
+ expect(why('branch')).toMatch(/parks the original/)
+ expect(why('verify')).toMatch(/live canvas/)
+ expect(why('open-worktree')).toMatch(/worktree store/)
+ expect(why('browser')).toMatch(/webview/)
+ // …and no two structural verbs share a copy-pasted sentence that names the wrong mechanism.
+ expect(why('move')).toContain('reparenting')
+ expect(why('align')).toContain('aligning')
+ })
+
+ it('an unknown verb refuses — the fail-closed direction', () => {
+ // Someone adds a verb to main's table and forgets this file. It must not fall through to
+ // anything that could act, and it certainly must not travel.
+ expect(offScreenDisposition('teleport-everything')).toEqual({
+ kind: 'refuse',
+ why: 'it needs the live canvas'
+ })
+ })
+
+ it('the three answering paths keep their own kinds', () => {
+ expect(offScreenDisposition('list')).toEqual({ kind: 'store-answered' })
+ expect(offScreenDisposition('send')).toEqual({ kind: 'store-answered' })
+ expect(offScreenDisposition('notify')).toEqual({ kind: 'store-answered' })
+ expect(offScreenDisposition('open-claude')).toEqual({ kind: 'cold-open' })
+ expect(offScreenDisposition('show-web')).toEqual({ kind: 'off-canvas' })
+ // `open-browser` PLACES a node (off canvas); `browser` DRIVES one (refuses). The pair is the
+ // easiest thing in the table to collapse by accident.
+ expect(offScreenDisposition('open-browser')).toEqual({ kind: 'off-canvas' })
+ expect(offScreenDisposition('browser').kind).toBe('refuse')
+ })
+
+ it('the refusal sentence names the project, the reason and the fact that nothing happened', () => {
+ const msg = offScreenRefusal('group', 'web-app')
+ expect(msg.startsWith('group: project "web-app" is not on screen')).toBe(true)
+ expect(msg).toContain('measured node sizes')
+ expect(msg).toContain('Open that project and run this again')
+ expect(msg).toContain('nothing was changed')
+ })
+
+ it('a verb that is ANSWERED off screen still gets a sane sentence if someone asks for one', () => {
+ // `offScreenRefusal` is only called on the refusing branch, but it must not produce nonsense
+ // (or throw) if a future caller reaches for it on another verb.
+ expect(offScreenRefusal('write', 'web-app')).toContain('write:')
+ })
+
+ it('the four sets are disjoint, so the dispatch order cannot silently decide', () => {
+ const { storeAnswered, coldOpenable, offCanvas, storedNode } = controlVerbSetsForTests()
+ const all = [...storeAnswered, ...coldOpenable, ...offCanvas, ...storedNode]
+ expect(new Set(all).size).toBe(all.length)
+ // …and `needsLiveCanvas` stays TRUE for the three sets that DO need a canvas, which is what
+ // keeps `STORE_ANSWERED_VERBS` the narrow "no canvas at either end" claim it documents.
+ for (const v of [...coldOpenable, ...offCanvas, ...storedNode]) expect(needsLiveCanvas(v), v).toBe(true)
+ for (const v of storeAnswered) expect(needsLiveCanvas(v), v).toBe(false)
+ })
+})
diff --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.ts
index c804f27a7..ae38a576a 100644
--- a/src/renderer/lib/controlRouting.ts
+++ b/src/renderer/lib/controlRouting.ts
@@ -70,150 +70,21 @@ export function routeControlSource(
}
/**
- * Verbs that are answered from the SERIALIZED store instead of the live canvas.
- *
- * `list` reads names only, and it is the verb an agent calls most — answering it out of the store
- * keeps a background agent's polling from yanking the user's view to another project tab on every
- * call.
- *
- * `send`/`reply` are here for a stronger reason than politeness, and it is worth being precise
- * about WHICH travel this prevents: routing here is by SOURCE
- * (`routeControlSource(projects, activeId, sourceNodeId)`), so what the declaration stops is a trip
- * to the SENDER's project — which an off-canvas orchestrator would otherwise trigger on every
- * message it sent, hijacking the human's view on a background agent's say-so and clearing that
- * node's unread badge via `setActive` on the way (G5). A delivery goes to a tmux PANE, not to a
- * canvas, so it needs no live canvas at either end.
- *
- * The other half — never travelling to the TARGET's project — is not this function's doing. It
- * comes from `resolveDeliveryScope` (`src/core/agents/agent-message-scope.ts`) taking the
- * serialized store and having no live-node parameter at all, so there is nothing to travel toward.
- *
- * LIVE AS OF PR 5: Canvas.tsx's dispatch handles `send`/`reply` BEFORE its source-routing
- * machinery, so neither `routeControlSource` nor any travel runs for them — the declaration here
- * and that early-exit are the same decision stated once each, and `controlRouting.test.ts` pins
- * this half.
- */
-/*
- * `sticky` is store-answered for the send/reply reason, not the list reason: its headline use is
- * a SCHEDULED agent rewriting one note every few minutes, and routing is by SOURCE — so a live
- * requirement would yank the human's view to the sync agent's project on every run (G5), which is
- * exactly the behaviour that gets the sync loop turned off. The write lands in the owning
- * project's serialized nodes (`applyNodeMutation`, the same path peer mutations take) when that
- * project is not the active one; the live canvas handles it when it is.
- */
-/*
- * `open-project` (issue #338) is store-answered for the G5 reason in its sharpest form: its
- * headline caller is a background orchestrator registering one repo after another, and routing is
- * by SOURCE — a live requirement would yank the human's view to the CALLER's project on every
- * registration (and clear its unread badge via `setActive` on the way). The verb acts on the
- * projects STORE through the non-activating `registerProject`, and its consent dialog is
- * app-global (`ConfirmState` overlays the window), so no live canvas is needed at either end.
- * Canvas.tsx handles it BEFORE the source-routing machinery — this declaration and that
- * early-exit are the same decision stated once each (spec §2.3, P6), pinned by
- * `controlRouting.test.ts`.
- */
-const STORE_ANSWERED_VERBS: ReadonlySet<string> = new Set([
- 'list',
- 'send',
- 'reply',
- 'sticky',
- 'open-project'
-])
-
-/**
- * Does this verb have to run against the LIVE canvas? Everything that creates, moves, writes to or
- * closes a node does.
- */
-export function needsLiveCanvas(verb: string): boolean {
- return !STORE_ANSWERED_VERBS.has(verb)
-}
-
-/**
- * Verbs that CREATE a session and can therefore be answered by writing into the owning project's
- * SERIALIZED nodes instead of activating its tab.
- *
- * The relationship to `STORE_ANSWERED_VERBS` is the whole point, and the two sets are disjoint
- * (pinned in `controlRouting.test.ts`):
- *
- * - `STORE_ANSWERED_VERBS` — "no canvas is needed at either end". `list` reads names, `send`/
- * `reply` deliver into a tmux PANE, `sticky` rewrites a note, `open-project` acts on the
- * projects store. `needsLiveCanvas` is false for them and they never route at all.
- * - `COLD_OPENABLE_VERBS` — "a canvas IS needed, but the serialized one will do". The node these
- * verbs create is INERT until its project is next shown: the launch command moves into
- * `pendingLaunch` (`armForColdOpen`), the node is upserted through `applyNodeMutation`, and the
- * project's own mount path spawns the PTY and fires the armed launch. `needsLiveCanvas` stays
- * TRUE for them — they do need a canvas — which is exactly why this is a second, narrower set
- * rather than four more entries in the first one.
- *
- * WHY (the bug): routing is by SOURCE, so `open-claude` from an agent in a project the user is not
- * looking at travelled the user's view to that project — the camera jumped, the tab switched and
- * the target project's saved viewport was applied, all on a background agent's say-so. That is the
- * same G5 hijack `send`/`reply`/`sticky` are declared here to avoid; the difference is only that an
- * open needs somewhere to put the node, and a project's serialized nodes are somewhere.
- *
- * Deliberately NOT here: every verb that acts on nodes that already exist (`write`, `close`,
- * `group`, `move`, `arrange`, `align`, `verify`, `spawn-team`, `open-worktree`). They read live
- * canvas state — measured node sizes, worktree staleness, the React Flow edge arrays — that the
- * serialized copy does not carry, so they keep travelling. The verbs that create a node with no
- * session behind it are the third set below.
- */
-const COLD_OPENABLE_VERBS: ReadonlySet<string> = new Set([
- 'open-terminal',
- 'open-claude',
- 'open-agent'
-])
-
-export function canColdOpen(verb: string): boolean {
- return COLD_OPENABLE_VERBS.has(verb)
-}
-
-/**
- * Verbs that create a DISPLAY node — one with no session behind it — and can therefore run against
- * the owning project's serialized nodes without that canvas being on screen.
- *
- * The third set, and the reason it is not folded into `COLD_OPENABLE_VERBS`: a cold open has a
- * launch to defer, so it moves the composed command into `pendingLaunch` and tells the caller the
- * session is QUEUED. These four have nothing to defer. A web page, a video, an image and a browser
- * node are inert wherever they sit; writing one into a project's serialized nodes is the whole
- * effect, and it is complete the moment `writeDisk` returns. One set with two contracts inside it
- * is how a caller ends up told a picture is queued.
- *
- * WHY they were still travelling after the cold-open fix: an agent that renders its output as a
- * node — a report as `show-web`, a screenshot as `show-image` — is the commonest reason a
- * background session touches the canvas at all, and every one of those calls yanked the human out
- * of the project they were typing in. Same G5 objection, same answer as the two sets above.
- *
- * Deliberately NOT here: `browser`, which NAVIGATES an existing node and needs a mounted
- * `<webview>` guest to do it. `open-browser` merely places the node; the guest is created when
- * that project is next shown, exactly as a cold-opened terminal's PTY is.
- *
- * None of the four takes `--group`, which is why this set owes no worktree question. A verb
- * joining it that does would: `cwdForNewNodeIn` subtracts the worktree store's `staleGroupIds`,
- * which is epoch-scoped to the ACTIVE project, so off canvas that subtraction cannot be made.
+ * The off-screen verb table lives in `@shared/control-off-screen` because CORE renders the
+ * agent-facing help from it and core cannot import the renderer. Re-exported here so every
+ * renderer caller keeps one import for "how does canvas control route".
*/
-const OFF_CANVAS_VERBS: ReadonlySet<string> = new Set([
- 'show-image',
- 'show-video',
- 'show-web',
- 'open-browser'
-])
-
-export function answersOffCanvas(verb: string): boolean {
- return OFF_CANVAS_VERBS.has(verb)
-}
-
-/** Test-only view of the three sets, so their disjointness can be asserted rather than eyeballed. */
-export function controlVerbSetsForTests(): {
- storeAnswered: string[]
- coldOpenable: string[]
- offCanvas: string[]
-} {
- return {
- storeAnswered: [...STORE_ANSWERED_VERBS],
- coldOpenable: [...COLD_OPENABLE_VERBS],
- offCanvas: [...OFF_CANVAS_VERBS]
- }
-}
+export {
+ needsLiveCanvas,
+ canColdOpen,
+ answersOffCanvas,
+ answersFromStoredNodes,
+ offScreenDisposition,
+ offScreenRefusal,
+ offScreenGuidanceLines,
+ controlVerbSetsForTests,
+ type OffScreenDisposition
+} from '@shared/control-off-screen'
/**
* The capability half of the guard: may a session in this node drive the canvas?
diff --git a/src/shared/control-off-screen.ts b/src/shared/control-off-screen.ts
new file mode 100644
index 000000000..da9944479
--- /dev/null
+++ b/src/shared/control-off-screen.ts
@@ -0,0 +1,346 @@
+// WHAT A CONTROL VERB DOES WHEN ITS OWN PROJECT IS NOT THE ONE ON SCREEN.
+//
+// IN `src/shared` BECAUSE IT HAS THREE SIDES, which is the whole reason this file exists rather
+// than living beside the dispatch that reads it:
+//
+// - the RENDERER's dispatch (`renderer/canvas/Canvas.tsx`, via `renderer/lib/controlRouting.ts`)
+// branches on it,
+// - CORE renders the agent-facing help from it (`core/canvas-control-core.ts` —
+// `buildCanvasSkillBody` and `buildCanvasControlInstructions`, the two texts orchestrating
+// agents actually read), and core cannot import the renderer,
+// - the cross-layer guard walks it against main's verb table
+// (`test/acceptance/control-verb-disposition.test.ts`).
+//
+// CLAUDE.md's rule for this subsystem is derive, never re-type: "a doc line with no such test is a
+// plan, not a fact — see the drift that shipped as #269". A verb's off-screen behaviour is
+// precisely the kind of fact a prose sentence forgets. So the table is here, once, and the help
+// text is rendered from it.
+//
+// THE INVARIANT IT ENCODES: nothing an agent asks for may activate a project tab. Routing is by
+// SOURCE — the request names the agent's own node, and the dispatch has to find the canvas that
+// owns it — and for a long time the answer to "that canvas is not on screen" was to travel there.
+// The user was typing in project B; a background agent in project A issued a `close`; the tab
+// switched and A's SAVED viewport was applied, so their focus, camera and typing context were
+// taken by a call they did not make. Two carve-outs were added over the years and each was
+// written as if it were the last, because nothing walked the whole table.
+
+/**
+ * Verbs that are answered from the SERIALIZED store instead of the live canvas.
+ *
+ * `list` reads names only, and it is the verb an agent calls most — answering it out of the store
+ * keeps a background agent's polling from yanking the user's view to another project tab on every
+ * call.
+ *
+ * `send`/`reply` are here for a stronger reason than politeness, and it is worth being precise
+ * about WHICH travel this prevents: routing here is by SOURCE
+ * (`routeControlSource(projects, activeId, sourceNodeId)`), so what the declaration stops is a trip
+ * to the SENDER's project — which an off-canvas orchestrator would otherwise trigger on every
+ * message it sent, hijacking the human's view on a background agent's say-so and clearing that
+ * node's unread badge via `setActive` on the way (G5). A delivery goes to a tmux PANE, not to a
+ * canvas, so it needs no live canvas at either end.
+ *
+ * The other half — never travelling to the TARGET's project — is not this function's doing. It
+ * comes from `resolveDeliveryScope` (`src/core/agents/agent-message-scope.ts`) taking the
+ * serialized store and having no live-node parameter at all, so there is nothing to travel toward.
+ *
+ * LIVE AS OF PR 5: Canvas.tsx's dispatch handles `send`/`reply` BEFORE its source-routing
+ * machinery, so neither `routeControlSource` nor any travel runs for them — the declaration here
+ * and that early-exit are the same decision stated once each, and `controlRouting.test.ts` pins
+ * this half.
+ */
+/*
+ * `sticky` is store-answered for the send/reply reason, not the list reason: its headline use is
+ * a SCHEDULED agent rewriting one note every few minutes, and routing is by SOURCE — so a live
+ * requirement would yank the human's view to the sync agent's project on every run (G5), which is
+ * exactly the behaviour that gets the sync loop turned off. The write lands in the owning
+ * project's serialized nodes (`applyNodeMutation`, the same path peer mutations take) when that
+ * project is not the active one; the live canvas handles it when it is.
+ */
+/*
+ * `open-project` (issue #338) is store-answered for the G5 reason in its sharpest form: its
+ * headline caller is a background orchestrator registering one repo after another, and routing is
+ * by SOURCE — a live requirement would yank the human's view to the CALLER's project on every
+ * registration (and clear its unread badge via `setActive` on the way). The verb acts on the
+ * projects STORE through the non-activating `registerProject`, and its consent dialog is
+ * app-global (`ConfirmState` overlays the window), so no live canvas is needed at either end.
+ * Canvas.tsx handles it BEFORE the source-routing machinery — this declaration and that
+ * early-exit are the same decision stated once each (spec §2.3, P6), pinned by
+ * `controlRouting.test.ts`.
+ */
+/*
+ * `notify` rides in `send`/`reply`'s early-exit block and always has — it is the same delivery
+ * with a different destination (an OS notification rather than a pane), so no canvas is needed at
+ * either end. It was simply never DECLARED here, which made it invisible to anything reasoning
+ * about the table; `test/acceptance/control-verb-disposition.test.ts` is what found it. Declaring
+ * it changes no behaviour (it returns above the routing block), and undeclaring it again would
+ * make the only verb whose code and table disagree.
+ */
+const STORE_ANSWERED_VERBS: ReadonlySet<string> = new Set([
+ 'list',
+ 'send',
+ 'reply',
+ 'notify',
+ 'sticky',
+ 'open-project'
+])
+
+/**
+ * Does this verb have to run against the LIVE canvas? Everything that creates, moves, writes to or
+ * closes a node does.
+ */
+export function needsLiveCanvas(verb: string): boolean {
+ return !STORE_ANSWERED_VERBS.has(verb)
+}
+
+/**
+ * Verbs that CREATE a session and can therefore be answered by writing into the owning project's
+ * SERIALIZED nodes instead of activating its tab.
+ *
+ * The relationship to `STORE_ANSWERED_VERBS` is the whole point, and the two sets are disjoint
+ * (pinned in `controlRouting.test.ts`):
+ *
+ * - `STORE_ANSWERED_VERBS` — "no canvas is needed at either end". `list` reads names, `send`/
+ * `reply` deliver into a tmux PANE, `sticky` rewrites a note, `open-project` acts on the
+ * projects store. `needsLiveCanvas` is false for them and they never route at all.
+ * - `COLD_OPENABLE_VERBS` — "a canvas IS needed, but the serialized one will do". The node these
+ * verbs create is INERT until its project is next shown: the launch command moves into
+ * `pendingLaunch` (`armForColdOpen`), the node is upserted through `applyNodeMutation`, and the
+ * project's own mount path spawns the PTY and fires the armed launch. `needsLiveCanvas` stays
+ * TRUE for them — they do need a canvas — which is exactly why this is a second, narrower set
+ * rather than four more entries in the first one.
+ *
+ * WHY (the bug): routing is by SOURCE, so `open-claude` from an agent in a project the user is not
+ * looking at travelled the user's view to that project — the camera jumped, the tab switched and
+ * the target project's saved viewport was applied, all on a background agent's say-so. That is the
+ * same G5 hijack `send`/`reply`/`sticky` are declared here to avoid; the difference is only that an
+ * open needs somewhere to put the node, and a project's serialized nodes are somewhere.
+ *
+ * Deliberately NOT here: every verb that acts on nodes that already exist. Those split between
+ * the FOURTH set below (`STORED_NODE_VERBS` — they reach a pane, a store writer or a board, none
+ * of which needs React Flow) and an outright refusal (`OFF_SCREEN_REFUSALS` — the structural verbs
+ * read live canvas state the serialized copy does not carry: measured node sizes, worktree
+ * staleness, a mounted webview). Neither travels. The verbs that create a node with no session
+ * behind it are the third set below.
+ */
+const COLD_OPENABLE_VERBS: ReadonlySet<string> = new Set([
+ 'open-terminal',
+ 'open-claude',
+ 'open-agent'
+])
+
+export function canColdOpen(verb: string): boolean {
+ return COLD_OPENABLE_VERBS.has(verb)
+}
+
+/**
+ * Verbs that create a DISPLAY node — one with no session behind it — and can therefore run against
+ * the owning project's serialized nodes without that canvas being on screen.
+ *
+ * The third set, and the reason it is not folded into `COLD_OPENABLE_VERBS`: a cold open has a
+ * launch to defer, so it moves the composed command into `pendingLaunch` and tells the caller the
+ * session is QUEUED. These four have nothing to defer. A web page, a video, an image and a browser
+ * node are inert wherever they sit; writing one into a project's serialized nodes is the whole
+ * effect, and it is complete the moment `writeDisk` returns. One set with two contracts inside it
+ * is how a caller ends up told a picture is queued.
+ *
+ * WHY they were still travelling after the cold-open fix: an agent that renders its output as a
+ * node — a report as `show-web`, a screenshot as `show-image` — is the commonest reason a
+ * background session touches the canvas at all, and every one of those calls yanked the human out
+ * of the project they were typing in. Same G5 objection, same answer as the two sets above.
+ *
+ * Deliberately NOT here: `browser`, which NAVIGATES an existing node and needs a mounted
+ * `<webview>` guest to do it. `open-browser` merely places the node; the guest is created when
+ * that project is next shown, exactly as a cold-opened terminal's PTY is.
+ *
+ * None of the four takes `--group`, which is why this set owes no worktree question. A verb
+ * joining it that does would: `cwdForNewNodeIn` subtracts the worktree store's `staleGroupIds`,
+ * which is epoch-scoped to the ACTIVE project, so off canvas that subtraction cannot be made.
+ */
+const OFF_CANVAS_VERBS: ReadonlySet<string> = new Set([
+ 'show-image',
+ 'show-video',
+ 'show-web',
+ 'open-browser'
+])
+
+export function answersOffCanvas(verb: string): boolean {
+ return OFF_CANVAS_VERBS.has(verb)
+}
+
+/**
+ * Verbs that act on nodes that ALREADY EXIST and can be answered against the owning project's
+ * SERIALIZED nodes — the fourth set, and the one that finishes the job the three above started.
+ *
+ * THE BUG, in full. Routing is by SOURCE, and until this set existed everything outside the three
+ * sets above fell through to `travelToProject`. So: the user is typing in project B; a background
+ * agent in project A — a scheduled run, an orchestrator, a session re-adopted at boot — issues a
+ * `close`, a `write`, a `rename`. The tab switches, project A's SAVED viewport is applied, and the
+ * camera appears to jump. Their focus, their camera and their typing context are taken by a call
+ * they did not make. Twenty-one verbs did it; the two carve-outs above were added without anyone
+ * noticing the rest, because nothing pinned the whole table.
+ *
+ * WHAT MAKES THESE FOUR-PLUS-THREE ANSWERABLE OFF SCREEN: none of them needs React Flow. Each one
+ * reaches something that is screen-independent and has a serialized counterpart:
+ *
+ * - `write` reaches a tmux PANE through main and never touches the canvas at all — it does not
+ * so much as look a node up. It is on this list only because it used to travel to get here.
+ * - `close` ends a tmux session (`transport.destroy` resolves a REMOTE node's host from the
+ * persisted index, with no live client — see core/remote-end.ts) and drops the node through
+ * the store's `removeNode`. That is the cross-project teardown the sessions sidebar has always
+ * used for a node in a project that is not on screen; `closeStoredNodes` is now the one copy.
+ * - `rename` / `color` have dedicated store writers (`renameNode` / `recolorNode`) that mutate
+ * the serialized node directly, with no round-trip through the serializers.
+ * - `link` writes persisted `bridges`, which `appendCanvasLinks` appends to a non-active project —
+ * the same call the cold open already makes for the rope and bridge it owes.
+ * - `board` is a read, and `assign` writes board METADATA through `setProjectKanban`. Both used
+ * to read `activeProjectId`, which off canvas was a second bug hiding behind the first: after
+ * the travel the two projects were the same, so the wrong read was never wrong in practice.
+ *
+ * Deliberately NOT here — and these REFUSE rather than travel, see `offScreenDisposition`: the
+ * structural verbs. A refusal an agent can act on is strictly better than hijacking the human's
+ * screen, and every one of these would have to guess at something the serialized copy does not
+ * carry.
+ */
+const STORED_NODE_VERBS: ReadonlySet<string> = new Set([
+ 'write',
+ 'close',
+ 'rename',
+ 'color',
+ 'link',
+ 'board',
+ 'assign'
+])
+
+export function answersFromStoredNodes(verb: string): boolean {
+ return STORED_NODE_VERBS.has(verb)
+}
+
+/**
+ * Why a verb cannot be answered while its own project is off screen — one sentence per verb, which
+ * is also the sentence the agent is told. Written per verb rather than as one generic line because
+ * the caller's next move differs: an `arrange` can wait for the human, a `branch` cannot happen at
+ * all until that terminal is mounted.
+ *
+ * The rule these encode: NOTHING an agent asks for may activate a project tab. Where that leaves a
+ * verb unable to act, it says so.
+ */
+const OFF_SCREEN_REFUSALS: Readonly<Record<string, string>> = {
+ // The five structural verbs rewrite the WHOLE node array through React Flow's parent/extent
+ // model and re-fit frames from MEASURED sizes (`nodeW`/`nodeH` prefer `measured` over the
+ // persisted `size`), which the serialized copy does not carry — nothing rendered it. Laying a
+ // canvas out to geometry the user would not get on screen, and round-tripping every node
+ // through the serializers to persist it, is drift no reply could report.
+ group: 'grouping re-fits frames from measured node sizes, which only a rendered canvas has',
+ ungroup: 'ungrouping re-fits frames from measured node sizes, which only a rendered canvas has',
+ move: 'reparenting re-fits both frames from measured node sizes, which only a rendered canvas has',
+ arrange: 'arranging lays nodes out from measured node sizes, which only a rendered canvas has',
+ align: 'aligning lays nodes out from measured node sizes, which only a rendered canvas has',
+ // Both compose `--after` arming and context bridges over nodes created in the SAME tick, and
+ // check each dep against the live canvas before arming it. A cold open defers ONE node's launch;
+ // these defer a graph, and an armed station is fired by the live canvas effect.
+ verify: 'a review panel arms its reviewers against the live canvas',
+ 'spawn-team': 'a team arms its members against the live canvas',
+ // branchClaude parks the ORIGINAL node's live terminal and resumes it in the new one. Off screen
+ // there is no live terminal to park.
+ branch: 'branching parks the original session, which needs its terminal mounted',
+ // The worktree store is epoch-scoped to the ACTIVE project, so off canvas its repoRoot and
+ // staleness answers describe a different project's checkout.
+ 'open-worktree': 'the worktree store only answers for the project on screen',
+ 'close-worktree': 'the worktree store only answers for the project on screen',
+ // The CDP driving in main needs a mounted <webview> guest. Placing a browser node
+ // (`open-browser`) does not and is in OFF_CANVAS_VERBS; navigating one does.
+ browser: 'driving a browser node needs its webview mounted'
+}
+
+/**
+ * What the dispatch does with `verb` when the source's project is NOT the one on screen.
+ *
+ * Every verb in `ControlVerb` has an entry, and NONE of them is "travel" — that is the whole
+ * invariant, and `test/acceptance/control-verb-disposition.test.ts` walks main's verb table
+ * against this function to pin both halves (full coverage, and no traveller).
+ */
+export type OffScreenDisposition =
+ /** Never routes at all — handled before the source lookup (`needsLiveCanvas` is false). */
+ | { kind: 'store-answered' }
+ /** Creates a session node, armed and inert until that project is next shown. */
+ | { kind: 'cold-open' }
+ /** Creates a display node, complete the moment it is written. */
+ | { kind: 'off-canvas' }
+ /** Acts on nodes that already exist, through the owning project's serialized copy. */
+ | { kind: 'stored-node' }
+ /** Cannot be answered off screen; `why` is the sentence the agent is given. */
+ | { kind: 'refuse'; why: string }
+
+export function offScreenDisposition(verb: string): OffScreenDisposition {
+ if (!needsLiveCanvas(verb)) return { kind: 'store-answered' }
+ if (canColdOpen(verb)) return { kind: 'cold-open' }
+ if (answersOffCanvas(verb)) return { kind: 'off-canvas' }
+ if (answersFromStoredNodes(verb)) return { kind: 'stored-node' }
+ const why = OFF_SCREEN_REFUSALS[verb]
+ // An unknown verb refuses too. The dispatch's own `default` case answers "unknown verb" first on
+ // the on-screen path, so this only ever reads for a verb someone added to main's table and
+ // forgot to classify here — and refusing is the fail-closed direction.
+ return { kind: 'refuse', why: why ?? 'it needs the live canvas' }
+}
+
+/**
+ * The refusal an agent is given for a verb whose project is off screen. It NAMES the project,
+ * because the caller's fix is to have the human open that tab, and an agent that is told only
+ * "not on screen" cannot say which of the user's tabs to ask for.
+ */
+export function offScreenRefusal(verb: string, projectName?: string): string {
+ const where = projectName ? `project "${projectName}"` : 'that project'
+ const d = offScreenDisposition(verb)
+ const why = d.kind === 'refuse' ? d.why : 'it needs the live canvas'
+ return `${verb}: ${where} is not on screen — ${why}. Open that project and run this again; nothing was changed.`
+}
+
+/** Test-only view of the four sets, so their disjointness can be asserted rather than eyeballed. */
+export function controlVerbSetsForTests(): {
+ storeAnswered: string[]
+ coldOpenable: string[]
+ offCanvas: string[]
+ storedNode: string[]
+} {
+ return {
+ storeAnswered: [...STORE_ANSWERED_VERBS],
+ coldOpenable: [...COLD_OPENABLE_VERBS],
+ offCanvas: [...OFF_CANVAS_VERBS],
+ storedNode: [...STORED_NODE_VERBS]
+ }
+}
+
+/**
+ * The agent-facing paragraph about a project that is not on screen, RENDERED from the tables above
+ * rather than re-typed as prose — the same discipline as `messagingGuidanceLines` in
+ * `core/canvas-control-core.ts`, and for the same reason CLAUDE.md gives for this subsystem: a
+ * doc line with no test behind it is a plan, not a fact (#269 shipped exactly that drift).
+ *
+ * `canvas-control-core.test.ts` walks the real tables against the rendered text, so a verb that
+ * changes sides here lands in both generated bodies the day it moves.
+ *
+ * Both consumers are plain-text bodies (a SKILL.md and a marker block), so this returns lines and
+ * lets the caller indent.
+ */
+export function offScreenGuidanceLines(): string[] {
+ const sets = controlVerbSetsForTests()
+ const answered = [
+ ...sets.storeAnswered,
+ ...sets.coldOpenable,
+ ...sets.offCanvas,
+ ...sets.storedNode
+ ].sort()
+ const refused = Object.keys(OFF_SCREEN_REFUSALS).sort()
+ return [
+ "NO VERB EVER SWITCHES THE USER'S VIEW. The canvas your call is answered on is the one your",
+ 'own node lives on, which is often NOT the project the user is looking at — you may be a',
+ 'scheduled run, a background orchestrator, or a session re-adopted after a restart. Their tab,',
+ 'camera and typing focus are never taken to answer you.',
+ `- Answered whether or not that project is on screen: ${answered.join(', ')}.`,
+ ' The reply says where the work landed; say so too rather than assuming the user saw it.',
+ `- REFUSED while that project is off screen, changing nothing: ${refused.join(', ')}.`,
+ ...refused.map((v) => ` - ${v}: ${OFF_SCREEN_REFUSALS[v]}.`),
+ ' The refusal names the project. Ask the user to open it and run the call again; do not',
+ ' retry it on a timer, and do not report the action as done.'
+ ]
+}
diff --git a/test/acceptance/control-verb-disposition.test.ts b/test/acceptance/control-verb-disposition.test.ts
new file mode 100644
index 000000000..d7780c709
--- /dev/null
+++ b/test/acceptance/control-verb-disposition.test.ts
@@ -0,0 +1,120 @@
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { VERBS_FOR_TEST } from '../../src/core/canvas-control-core'
+import {
+ offScreenDisposition,
+ offScreenRefusal,
+ controlVerbSetsForTests
+} from '../../src/renderer/lib/controlRouting'
+
+/**
+ * THE REGRESSION GUARD THIS FEATURE NEVER HAD, and the reason it could regress twice unnoticed.
+ *
+ * Canvas control routes by SOURCE: the request names the agent's own node, and the dispatch has to
+ * find which canvas owns it. When that is not the canvas on screen, the answer used to be
+ * `travelToProject` — the tab switched, the owning project's SAVED viewport was applied, and the
+ * human's focus, camera and typing context were taken by a call they did not make. Two carve-outs
+ * were added over time (the cold open for `open-*`, then the display verbs) and each was written
+ * as if it were the last one, because nothing anywhere walked the WHOLE verb table. Twenty-one
+ * verbs still travelled, `close` among them, which is the field report that finally named it.
+ *
+ * CROSS-LAYER on purpose, which is why it lives here rather than in `src/`: the verb table is
+ * main's (`ControlVerb` belongs to the main-side verb model — see the header of
+ * `src/shared/control-verbs.ts` for why it stays there), the disposition is the renderer's, and
+ * production layering forbids the renderer importing core. Walking one against the other is
+ * exactly what neither side can do alone, and it is the only thing that makes "every verb" a
+ * checked claim instead of a list someone kept up to date by hand.
+ */
+describe('every control verb has an off-screen disposition, and none of them travels', () => {
+ it('covers main’s whole verb table', () => {
+ const unclassified = VERBS_FOR_TEST.filter(
+ (v) => offScreenDisposition(v).kind === 'refuse' && !REFUSERS.has(v)
+ )
+ // A verb main accepts but `controlRouting` has never heard of falls into the generic refusal.
+ // That is the fail-CLOSED direction (it cannot steal a screen), but it is still a verb whose
+ // off-screen behaviour nobody decided — so it fails here, where the decision is cheap, rather
+ // than surfacing as a refusal an agent cannot act on.
+ expect(unclassified, 'verbs with no decided off-screen behaviour').toEqual([])
+ })
+
+ it.each([...VERBS_FOR_TEST])('%s does not travel', (verb) => {
+ const d = offScreenDisposition(verb)
+ // The assertion the whole file exists for, stated per verb so a failure NAMES the one that
+ // regressed. There is no 'travel' kind to assert against — the type has none, which is the
+ // point — so this pins the exhaustive shape instead: a verb is answered somewhere off screen,
+ // or it is refused, and a third option cannot be added without changing this line.
+ expect(['store-answered', 'cold-open', 'off-canvas', 'stored-node', 'refuse']).toContain(d.kind)
+ })
+
+ it('a refusal names the project and says what was NOT done', () => {
+ // The caller is an agent, and its next move is to ask the human for a specific tab. "Not on
+ // screen" alone does not say which of the user's projects to ask for, and a refusal that does
+ // not say "nothing was changed" leaves an orchestrator unable to tell a refusal from a
+ // half-applied call.
+ const msg = offScreenRefusal('arrange', 'api-server')
+ expect(msg).toContain('arrange')
+ expect(msg).toContain('"api-server"')
+ expect(msg).toContain('nothing was changed')
+ // Unnamed project (unreadable file, a race with a close) still answers — it never throws and
+ // never invents a name.
+ expect(offScreenRefusal('branch')).toContain('that project')
+ })
+
+ it('the four answering sets are disjoint', () => {
+ // Each set means something different (see their doc comments), and a verb in two of them
+ // would take whichever branch the dispatch tests first — a silent behaviour change.
+ const sets = controlVerbSetsForTests()
+ const all = [...sets.storeAnswered, ...sets.coldOpenable, ...sets.offCanvas, ...sets.storedNode]
+ expect(all.length).toBe(new Set(all).size)
+ })
+
+ it('every verb the renderer answers is one main will actually forward', () => {
+ // The sets are hand-written strings. A typo ('open-clade') produces a set entry that matches
+ // nothing, so the verb keeps the old behaviour with every test still green.
+ const known = new Set<string>(VERBS_FOR_TEST)
+ const sets = controlVerbSetsForTests()
+ for (const v of [...sets.storeAnswered, ...sets.coldOpenable, ...sets.offCanvas, ...sets.storedNode]) {
+ expect(known.has(v), `${v} is not a verb main forwards`).toBe(true)
+ }
+ })
+
+ it('the dispatch holds no project-travel call at all', () => {
+ // The structural half. Above proves the TABLE is right; this proves the CODE cannot travel
+ // whatever the table says — the ref that used to carry `travelToProject` into the
+ // agent-control and browser-resolve effects is gone, so there is nothing to call.
+ const canvas = readFileSync(
+ new URL('../../src/renderer/canvas/Canvas.tsx', import.meta.url),
+ 'utf8'
+ )
+ const code = canvas
+ .split('\n')
+ .filter((l) => !l.trim().startsWith('//') && !l.trim().startsWith('*'))
+ .join('\n')
+ expect(code).not.toContain('travelToProjectRef')
+ // `travelToProject` itself survives for the facepile — the user's own explicit navigation —
+ // and that is the ONLY place allowed to call it.
+ const calls = [...code.matchAll(/travelToProject\b/g)].length
+ expect(calls, 'travelToProject: its definition plus the facepile prop').toBe(2)
+ })
+})
+
+/** The verbs that deliberately refuse off screen, each with its reason in `OFF_SCREEN_REFUSALS`. */
+const REFUSERS = new Set([
+ // Structural: they re-fit frames / lay out from MEASURED node sizes, which only a rendered
+ // canvas has.
+ 'group',
+ 'ungroup',
+ 'move',
+ 'arrange',
+ 'align',
+ // Compose --after arming and bridges over nodes created in the same tick, against the live canvas.
+ 'verify',
+ 'spawn-team',
+ // Parks the original session's terminal, which must be mounted.
+ 'branch',
+ // The worktree store is epoch-scoped to the active project.
+ 'open-worktree',
+ 'close-worktree',
+ // Needs a mounted <webview> guest to drive.
+ 'browser'
+])