Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(canvas-control): answer an agent from ITS project's canvas, not the active one
enescecb4dfe71d7
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 9f881d0c0..6e2984b34 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -131,6 +131,12 @@ import { PresenceLayer } from '../components/PresenceLayer'import { Facepile } from '../components/Facepile'import { PresenceNamePrompt } from '../components/PresenceNamePrompt'import { nodeTravel, projectTravel } from '../lib/presenceTravel'+import {+ routeControlSource,+ needsLiveCanvas,+ sourceIsControlCapable,+ storedNodeListing+} from '../lib/controlRouting'import {FIT_NODE_OPTIONS,absolutePosition,@@ -189,7 +195,6 @@ import {canRename,canTransferFrom,canContextLink,- canControlCanvas,createdAgentId,resumeCommand,AGENT_CONFIG,@@ -437,6 +442,24 @@ const offsetFrom = (const LAUNCH_DELIVERY_ATTEMPTS = 5const LAUNCH_RETRY_MS = 400+// A canvas-control request whose source node lives in another project switches that project in+// first, and the active-project effect hydrates React Flow ASYNCHRONOUSLY — so the handler waits+// for the node to appear instead of reading an empty canvas one tick too early. Bounded well under+// the CLI's 120s timeout: a canvas that never arrives becomes a plain "not on an open canvas".+const CONTROL_TRAVEL_TIMEOUT_MS = 8000+const CONTROL_TRAVEL_POLL_MS = 60+async function waitForCanvasNode(+ find: () => CanvasNode | undefined,+ timeoutMs = CONTROL_TRAVEL_TIMEOUT_MS+): Promise<CanvasNode | undefined> {+ const deadline = Date.now() + timeoutMs+ for (;;) {+ const hit = find()+ if (hit || Date.now() >= deadline) return hit+ await new Promise((r) => setTimeout(r, CONTROL_TRAVEL_POLL_MS))+ }+}+// A "spawned by" rope: control-capable agent → node it opened (or browser popup → opener).// Display-only (never a context link) but persisted per project as `ropes`, so the lineage// survives restarts. Selectable; removed with ⌫ / double-click like a context link.@@ -3959,6 +3982,10 @@ 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 worktree callbacks for the agent-control handler. That effect mounts ONCE (empty// deps) and these callbacks' identities change with the active project (activeProjectId /// isSshProject in their deps) — calling the first-render closures would run against project@@ -5444,14 +5471,47 @@ export function Canvas() {const reply = (r: { ok: boolean; message?: string; result?: unknown; error?: string }) =>api.sendAgentControlResult({ requestId, ...r })- // Authorization boundary: the source must be a live, control-capable agent node.- // The `?? 'claude'` MIRRORS pty-manager's spawn-time default (`options.agentId ?? 'claude'`):+ // Which canvas answers? React Flow holds only the ACTIVE project's nodes, but every OTHER+ // project's tmux sessions keep running and are re-adopted on the next app start — so after a+ // restart the agents of every project the app did NOT come up on were answered by a canvas+ // that had never heard of them, and got the capability rejection below. Resolve the OWNING+ // project and travel to it first (lib/controlRouting); `list` changes nothing, so it is+ // answered out of that project's serialized nodes rather than yanking the user's view.+ let src = nodesRef.current.find((n) => n.id === sourceNodeId)+ if (!src) {+ const { projects, activeProjectId: activeId } = useProjects.getState()+ const route = routeControlSource(projects, activeId, sourceNodeId)+ if (route.kind === 'switch' || route.kind === 'reopen') {+ if (!needsLiveCanvas(verb)) {+ const rows = storedNodeListing(projects.find((p) => p.id === route.projectId)?.nodes ?? [])+ reply({+ ok: true,+ result: rows,+ message: rows.map((n) => `${n.id} [${n.kind}] ${n.title}`).join('\n')+ })+ return+ }+ travelToProjectRef.current(route.projectId)+ }+ // 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.+ if (route.kind !== 'unknown' && route.kind !== 'blocked') {+ src = await waitForCanvasNode(() => nodesRef.current.find((n) => n.id === sourceNodeId))+ }+ }+ if (!src) {+ reply({ ok: false, error: 'source node is not on an open canvas' })+ return+ }+ // Authorization boundary: the source must be a control-capable agent node. The default for a+ // node with no agentId MIRRORS pty-manager's spawn-time default (`options.agentId ?? 'claude'`):// a PLAIN terminal node (no agentId — including the account "Claude login" node) received// the claude hook env at spawn, so a manual `claude` there holds NODETERM_CANVAS_CONTROL —// rejecting it here contradicted the env it was handed and surfaced as a baffling// "not a control-capable agent" from a session that plainly runs claude.- const src = nodesRef.current.find((n) => n.id === sourceNodeId)- if (!src || !canControlCanvas((src.data.agentId as AgentId | undefined) ?? 'claude')) {+ if (!sourceIsControlCapable(src.data.agentId)) {reply({ ok: false, error: 'source node is not a control-capable agent' })return}@@ -7233,6 +7293,11 @@ export function Canvas() {},[reopenProject, switchProject])+ // Latest project-travel callback 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+ })// Jump to the node a peer is focused on. focusNodeById already handles the same-project focus and// the switch to another OPEN project; the closed-project case has to reopen the tab first and letdiff --git a/src/renderer/lib/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.tsnew file mode 100644index 000000000..f73853c79--- /dev/null+++ b/src/renderer/lib/controlRouting.test.ts@@ -0,0 +1,108 @@+import { describe, it, expect } from 'vitest'+import {+ routeControlSource,+ needsLiveCanvas,+ sourceIsControlCapable,+ storedNodeListing,+ type ControlProject+} from './controlRouting'++const P = (+ id: string,+ nodes: { id: string; kind?: string; title?: string; agentId?: string }[],+ extra: Partial<ControlProject> = {}+): ControlProject => ({ id, nodes, ...extra })++describe('routeControlSource', () => {+ const projects = [+ P('p-active', [{ id: 'term-a-1' }]),+ P('p-open', [{ id: 'term-b-1' }, { id: 'term-b-2' }]),+ P('p-closed', [{ id: 'term-c-1' }], { closed: true }),+ P('p-gone', [{ id: 'term-d-1' }], { closed: true, unavailable: true })+ ]++ it('routes a node on the active canvas to the live canvas', () => {+ expect(routeControlSource(projects, 'p-active', 'term-a-1')).toEqual({ kind: 'active' })+ })++ // THE BUG: after an app restart the app comes up on ONE project, but every other project's+ // tmux sessions are re-adopted and keep running. Their agents' control calls used to be+ // answered by the ACTIVE canvas, which has never heard of the source node — so they were+ // rejected as "not a control-capable agent". The owning project must be resolved instead.+ it('routes a node in another OPEN project to its own project (not a rejection)', () => {+ expect(routeControlSource(projects, 'p-active', 'term-b-2')).toEqual({+ kind: 'switch',+ projectId: 'p-open'+ })+ })++ it('routes a node in a CLOSED project to a reopen (its sessions still run)', () => {+ expect(routeControlSource(projects, 'p-active', 'term-c-1')).toEqual({+ kind: 'reopen',+ projectId: 'p-closed'+ })+ })++ it('blocks a project whose files are unreadable', () => {+ expect(routeControlSource(projects, 'p-active', 'term-d-1')).toEqual({+ kind: 'blocked',+ projectId: 'p-gone'+ })+ })++ it('reports an unknown node as unknown, not as a capability failure', () => {+ expect(routeControlSource(projects, 'p-active', 'term-nope-9')).toEqual({ kind: 'unknown' })+ })++ it('treats the active project as live even when the store lags the live canvas', () => {+ // A node just created on the live canvas is not committed to the store yet: the caller only+ // consults the router when the live canvas MISSED it, so an active-project id must not be+ // reported as travel-worthy.+ expect(routeControlSource(projects, 'p-open', 'term-b-1')).toEqual({ kind: 'active' })+ })+})++describe('needsLiveCanvas', () => {+ it('is false for the read-only listing verb', () => {+ expect(needsLiveCanvas('list')).toBe(false)+ })++ it('is true for every verb that mutates the canvas', () => {+ for (const verb of ['open-terminal', 'spawn-team', 'write', 'close', 'board', 'assign']) {+ expect(needsLiveCanvas(verb)).toBe(true)+ }+ })+})++describe('sourceIsControlCapable', () => {+ it('defaults a plain terminal node (no agentId) to claude, mirroring the spawn-time env', () => {+ expect(sourceIsControlCapable(undefined)).toBe(true)+ expect(sourceIsControlCapable('')).toBe(true)+ })++ it('accepts every canvas-control-capable agent', () => {+ for (const id of ['claude', 'codex', 'gemini', 'opencode', 'grok']) {+ expect(sourceIsControlCapable(id)).toBe(true)+ }+ })++ it('rejects an agent that never gets NODETERM_CANVAS_CONTROL', () => {+ expect(sourceIsControlCapable('cursor')).toBe(false)+ })+})++describe('storedNodeListing', () => {+ it('renders serialized nodes in the same shape the live canvas answers `list` with', () => {+ expect(+ storedNodeListing([+ { id: 'term-b-1', kind: 'terminal', title: 'Claude Code' },+ { id: 'sticky-b-2', kind: 'sticky' },+ { id: 'term-b-3' }+ ])+ ).toEqual([+ { id: 'term-b-1', kind: 'terminal', title: 'Claude Code' },+ { id: 'sticky-b-2', kind: 'sticky', title: '' },+ { id: 'term-b-3', kind: 'terminal', title: '' }+ ])+ })+})diff --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.tsnew file mode 100644index 000000000..927e840df--- /dev/null+++ b/src/renderer/lib/controlRouting.ts@@ -0,0 +1,96 @@+// WHICH CANVAS answers a canvas-control request — the routing half of the `nodeterm` CLI's+// authorization boundary (Canvas's onAgentControl effect). Pure, so it is unit-testable where the+// React component is not (vitest runs in the node environment); same reasoning as presenceTravel,+// whose project-travel rules this reuses.+//+// WHY IT EXISTS: React Flow only ever holds the ACTIVE project's nodes, but tmux sessions of every+// OTHER open project keep running — they survive an app restart and are re-adopted on boot. Their+// agents still hold NODETERM_CANVAS_CONTROL and still reach the (rewritten) hook endpoint, so their+// control calls arrive at a canvas that has never heard of the source node. Looking the source up+// in the live canvas alone therefore rejected every agent outside the project the app happened to+// come up on — reported as "source node is not a control-capable agent", which is what a node+// carrying a non-control agent gets, so the failure read as a lost capability rather than as the+// wrong canvas answering. Resolve the OWNING project instead, then travel to it (or, for a verb+// that reads and changes nothing, answer straight out of its serialized nodes).++import { canControlCanvas, type AgentId } from '@shared/agents/config'+import { projectTravel } from './presenceTravel'++/** The little the routing needs to know about a project (a structural subset of `Project`). */+export interface ControlProject {+ id: string+ closed?: boolean+ unavailable?: boolean+ nodes: readonly { id: string }[]+}++/** A serialized node, as the projects store keeps them for non-active projects. */+export interface StoredNode {+ id: string+ kind?: string+ title?: string+}++/**+ * Where a control request must be applied:+ * - `active` — the source is on the live canvas (or its project is already active): apply here.+ * - `switch` — an open project's canvas: activate that tab first.+ * - `reopen` — a closed project (its sessions still run): restore the tab, then activate it.+ * - `blocked` — a project whose files are unreadable: travelling there would show an empty canvas.+ * - `unknown` — no open project owns this node id.+ */+export type ControlRoute =+ | { kind: 'active' }+ | { kind: 'switch'; projectId: string }+ | { kind: 'reopen'; projectId: string }+ | { kind: 'blocked'; projectId: string }+ | { kind: 'unknown' }++/** Which project owns `sourceNodeId`, and what Canvas must do to be able to act on it. */+export function routeControlSource(+ projects: readonly ControlProject[],+ activeProjectId: string,+ sourceNodeId: string+): ControlRoute {+ const owner = projects.find((p) => p.nodes.some((n) => n.id === sourceNodeId))+ if (!owner) return { kind: 'unknown' }+ const travel = projectTravel(+ projects.map((p) => ({ id: p.id, closed: p.closed, unavailable: p.unavailable, nodes: [] })),+ activeProjectId,+ owner.id+ )+ // `none` means "already there" — the live canvas is the right one even if its store copy lags.+ if (travel.kind === 'none') return { kind: 'active' }+ if (travel.kind === 'blocked') return { kind: 'blocked', projectId: owner.id }+ return travel+}++/**+ * Does this verb have to run against the LIVE canvas? Everything that creates, moves, writes to or+ * closes a node does. `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.+ */+export function needsLiveCanvas(verb: string): boolean {+ return verb !== 'list'+}++/**+ * The capability half of the guard: may a session in this node drive the canvas?+ *+ * The empty/absent default MIRRORS pty-manager's spawn-time default (`options.agentId ?? 'claude'`):+ * a plain terminal node received the claude hook env at spawn, so a manual `claude` there holds+ * NODETERM_CANVAS_CONTROL — rejecting it here would contradict the env it was handed.+ */+export function sourceIsControlCapable(agentId: unknown): boolean {+ const id = typeof agentId === 'string' && agentId ? agentId : 'claude'+ return canControlCanvas(id as AgentId)+}++/** `list`'s rows, built from serialized nodes — the same shape the live canvas answers with+ * (`n.type` is the persisted `kind`, `n.data.title` the persisted `title`). */+export function storedNodeListing(+ nodes: readonly StoredNode[]+): { id: string; kind: string; title: string }[] {+ return nodes.map((n) => ({ id: n.id, kind: n.kind ?? 'terminal', title: n.title ?? '' }))+}