Skip to content

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

feat(canvas): build node action rows per project

Mina Sameh20e51ecd84c8
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 0dca21f06..ac156b11d 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -115,8 +115,11 @@ import { ContextMenu, type MenuItem } from '../components/ContextMenu'
import { tidySeparators } from '../lib/tidySeparators'
import { createNodeWriteRouter, type NodeWrites } from '../lib/nodeWriteRouter'
import {
+ BOARD_NODE_ACTION_IDS,
buildAccountSwitchRows,
buildNodeActionItems,
+ offCanvasNodeActionCtx,
+ OFF_CANVAS_REFUSAL,
restartAgentIdOf,
type NodeActionCtx,
type NodeActionFilter
@@ -10358,6 +10361,53 @@ export function Canvas() {
[liveNodeActionCtx]
)
+ /** The node action context for a node of `projectId`: the live canvas when React Flow holds
+ * that project, else its stored copy (lib/nodeActionItems `offCanvasNodeActionCtx`). Writes go
+ * through the project's router either way, so a board write can never land on the wrong canvas. */
+ const nodeActionCtxFor = useCallback(
+ (projectId: string): NodeActionCtx => {
+ const writes = nodeWritesFor(projectId)
+ const liveLink = (nodeId: string): MenuItem[] => liveLinkMenuItems(nodeId, projectId)
+ if (liveCanvasHolds(nodesProjectIdRef.current, useProjects.getState().activeProjectId, projectId)) {
+ return {
+ ...liveNodeActionCtx(),
+ setNodesColor: writes.setColor,
+ pickNodeIcon: writes.pickIcon,
+ liveLinkMenuItems: liveLink
+ }
+ }
+ const project = useProjects.getState().getProject(projectId)
+ return offCanvasNodeActionCtx({
+ nodes: project ? nodeStatesToFlow(project.nodes) : [],
+ sessionSource: sessionForProject(projectId).source,
+ gatewayModels,
+ gatewayStatus,
+ gatewayError,
+ grokModels: () => grokModelList(),
+ writes,
+ liveLinkMenuItems: liveLink,
+ connectedProjectIdForHost,
+ refuse: () =>
+ window.dispatchEvent(
+ new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message: OFF_CANVAS_REFUSAL } })
+ )
+ })
+ },
+ [nodeWritesFor, liveLinkMenuItems, liveNodeActionCtx, gatewayModels, gatewayStatus, gatewayError, connectedProjectIdForHost]
+ )
+
+ /** A kanban card's rows from the node builder (BOARD_NODE_ACTION_IDS), for a node of `projectId`. */
+ const boardNodeActionItems = useCallback(
+ (nodeId: string, projectId: string): MenuItem[] =>
+ buildNodeActionItems([nodeId], undefined, nodeActionCtxFor(projectId), { allow: BOARD_NODE_ACTION_IDS }),
+ [nodeActionCtxFor]
+ )
+ // Stable identity for the memoized per-project board, which only ever shows the active project.
+ const activeBoardNodeActionItems = useCallback(
+ (nodeId: string): MenuItem[] => boardNodeActionItems(nodeId, activeProjectId),
+ [boardNodeActionItems, activeProjectId]
+ )
+
/** "New <agent>" creation entries shared by the pane, sidebar and group context menus.
* `at` is the flow position to create at; with `groupId` the node is parented into that group.
*
diff --git a/src/renderer/canvas/node-action-ctx-for.source.test.ts b/src/renderer/canvas/node-action-ctx-for.source.test.ts
new file mode 100644
index 000000000..5ec91b726
--- /dev/null
+++ b/src/renderer/canvas/node-action-ctx-for.source.test.ts
@@ -0,0 +1,57 @@
+// Canvas `nodeActionCtxFor` decides, per project, whether a node's action rows act on the LIVE
+// canvas or on the project's stored copy. The wrong branch lets an Omni lane of a background
+// project act on (or write to) the canvas the user is looking at. Canvas cannot be mounted in a
+// test, so both branches are pinned at source level here; the off-canvas context itself is
+// behaviour-tested in lib/nodeActionItems.offCanvas.test.tsx.
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { describe, expect, it } from 'vitest'
+
+const src = readFileSync(join(__dirname, 'Canvas.tsx'), 'utf8').replace(/\r\n/g, '\n')
+
+function body(): string {
+ const start = src.indexOf('const nodeActionCtxFor = useCallback(')
+ expect(start).toBeGreaterThan(-1)
+ const end = src.indexOf('const boardNodeActionItems = useCallback(', start)
+ expect(end).toBeGreaterThan(start)
+ return src.slice(start, end)
+}
+
+describe('Canvas nodeActionCtxFor', () => {
+ it('takes the live branch only when React Flow holds THAT project', () => {
+ const b = body()
+ expect(b).toMatch(
+ /if \(liveCanvasHolds\(nodesProjectIdRef\.current, useProjects\.getState\(\)\.activeProjectId, projectId\)\) \{/
+ )
+ const live = b.slice(b.indexOf('if (liveCanvasHolds('), b.indexOf('const project = '))
+ // Live: the live context, but color/icon still go through the project's router.
+ expect(live).toContain('...liveNodeActionCtx()')
+ expect(live).toContain('setNodesColor: writes.setColor')
+ expect(live).toContain('pickNodeIcon: writes.pickIcon')
+ expect(live).toContain('liveLinkMenuItems: liveLink')
+ })
+
+ it('every other project gets the stored copy, its own session source and its own router', () => {
+ const b = body()
+ expect(b).toContain('const writes = nodeWritesFor(projectId)')
+ // Up to the dependency array, which legitimately names liveNodeActionCtx.
+ const stored = b.slice(b.indexOf('const project = '), b.indexOf('\n [nodeWritesFor'))
+ expect(stored.length).toBeGreaterThan(0)
+ expect(stored).toContain('useProjects.getState().getProject(projectId)')
+ expect(stored).toContain('offCanvasNodeActionCtx({')
+ expect(stored).toContain('nodes: project ? nodeStatesToFlow(project.nodes) : []')
+ expect(stored).toContain('sessionSource: sessionForProject(projectId).source')
+ expect(stored).toMatch(/\n\s+writes,\n/)
+ expect(stored).toContain('message: OFF_CANVAS_REFUSAL')
+ // Never the live array or the active tab's session in the stored branch.
+ expect(stored).not.toContain('nodesRef.current')
+ expect(stored).not.toContain('session.source')
+ expect(stored).not.toContain('liveNodeActionCtx')
+ })
+
+ it('board rows are filtered to BOARD_NODE_ACTION_IDS', () => {
+ expect(src).toContain(
+ 'buildNodeActionItems([nodeId], undefined, nodeActionCtxFor(projectId), { allow: BOARD_NODE_ACTION_IDS })'
+ )
+ })
+})
diff --git a/src/renderer/canvas/node-menu-golden.source.test.ts b/src/renderer/canvas/node-menu-golden.source.test.ts
index dbee77233..960fcda5b 100644
--- a/src/renderer/canvas/node-menu-golden.source.test.ts
+++ b/src/renderer/canvas/node-menu-golden.source.test.ts
@@ -47,6 +47,7 @@ const GOLDEN_STRINGS = [
'Moves this conversation to the account and resumes it there (same conversation).',
'Not available for relay sessions.',
'Nothing to resume yet — this session has not reported an id.',
+ 'Open this project on the canvas to do that.',
'Pause',
'Pause & end session',
'Pause session',
diff --git a/src/renderer/lib/nodeActionItems.offCanvas.test.tsx b/src/renderer/lib/nodeActionItems.offCanvas.test.tsx
new file mode 100644
index 000000000..82cbc5ac8
--- /dev/null
+++ b/src/renderer/lib/nodeActionItems.offCanvas.test.tsx
@@ -0,0 +1,117 @@
+// @vitest-environment jsdom
+//
+// A kanban card of a project the canvas does NOT hold (an Omni lane of a background project):
+// its rows come from the same builder, over the project's STORED nodes, and nothing may act on
+// the live canvas of another project or fail in silence.
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { DEFAULT_SETTINGS, type CanvasNodeState } from '@shared/types'
+import type { MenuItem } from '../components/ContextMenu'
+import { useAgentStatus } from '../state/agentStatus'
+import { useSettings } from '../state/settings'
+import { nodeStatesToFlow } from '../state/workspace'
+import {
+ BOARD_NODE_ACTION_IDS,
+ buildNodeActionItems,
+ offCanvasNodeActionCtx,
+ type OffCanvasCtxInput
+} from './nodeActionItems'
+
+const stored = (id: string, extra: Partial<CanvasNodeState> = {}): CanvasNodeState =>
+ ({
+ id,
+ kind: 'terminal',
+ position: { x: 0, y: 0 },
+ size: { width: 400, height: 300 },
+ title: id,
+ color: '#fff',
+ group: null,
+ ...extra
+ }) as CanvasNodeState
+
+function input(nodes: CanvasNodeState[], over: Partial<OffCanvasCtxInput> = {}): OffCanvasCtxInput {
+ return {
+ nodes: nodeStatesToFlow(nodes),
+ sessionSource: 'local',
+ gatewayModels: [],
+ gatewayStatus: 'idle',
+ gatewayError: '',
+ grokModels: () => [],
+ writes: { setColor: vi.fn(), pickIcon: vi.fn() },
+ liveLinkMenuItems: () => [],
+ connectedProjectIdForHost: () => undefined,
+ refuse: vi.fn(),
+ ...over
+ }
+}
+
+function row(items: MenuItem[], label: string): Extract<MenuItem, { label: string }> | undefined {
+ for (const it of items) {
+ if (it.type === 'separator' || it.type === 'colors') continue
+ if (it.label === label) return it
+ if (it.type === 'submenu') {
+ const hit = row(it.children, label)
+ if (hit) return hit
+ }
+ }
+ return undefined
+}
+
+beforeEach(() => {
+ useSettings.setState({
+ settings: { ...DEFAULT_SETTINGS, claudeAccounts: [{ id: 'acc1', label: 'Work', createdAt: 0 }] as never }
+ })
+ useAgentStatus.setState({ byId: { a1: { state: 'done', sessionId: 's1' } } } as never)
+})
+
+describe('offCanvasNodeActionCtx — a card of a background project', () => {
+ it('shows the account rows, disabled because the terminal is not attached', () => {
+ const items = buildNodeActionItems(
+ ['a1'],
+ undefined,
+ offCanvasNodeActionCtx(input([stored('a1', { agentId: 'claude' })])),
+ { allow: BOARD_NODE_ACTION_IDS }
+ )
+ const work = row(items, 'Work')
+ expect(work && 'disabled' in work && work.disabled).toBe(true)
+ expect(work && 'hint' in work && work.hint).toBe('This terminal is not attached right now.')
+ })
+
+ it('a relay lane refuses the account switch with the relay reason', () => {
+ const items = buildNodeActionItems(
+ ['a1'],
+ undefined,
+ offCanvasNodeActionCtx(input([stored('a1', { agentId: 'claude' })], { sessionSource: 'relay' })),
+ { allow: BOARD_NODE_ACTION_IDS }
+ )
+ const sw = row(items, 'Switch Claude account')
+ expect(sw && 'hint' in sw && sw.hint).toBe('Not available for relay sessions.')
+ })
+
+ it('color and icon go to the project write router, not the live canvas', () => {
+ const i = input([stored('a1', { agentId: 'claude' })])
+ const items = buildNodeActionItems(['a1'], undefined, offCanvasNodeActionCtx(i), {
+ allow: BOARD_NODE_ACTION_IDS
+ })
+ const colors = items.find((it) => it.type === 'colors')
+ if (!colors || colors.type !== 'colors') throw new Error('no colors row')
+ colors.onPick('#0a84ff')
+ const icon = row(items, 'Set icon…')
+ if (!icon || !('onClick' in icon)) throw new Error('no icon row')
+ icon.onClick()
+ expect(i.writes.setColor).toHaveBeenCalledWith(['a1'], '#0a84ff')
+ expect(i.writes.pickIcon).toHaveBeenCalledWith('a1')
+ })
+
+ it('anything that needs the live canvas refuses out loud', () => {
+ const i = input([stored('a1')])
+ const ctx = offCanvasNodeActionCtx(i)
+ ctx.duplicateNodes(['a1'])
+ ctx.deleteNodes(['a1'])
+ expect(i.refuse).toHaveBeenCalledTimes(2)
+ })
+
+ it('a node of the stored copy that names its agent only by the legacy claude tag is still an agent', () => {
+ const ctx = offCanvasNodeActionCtx(input([stored('a1', { tags: ['claude'] } as never)]))
+ expect(ctx.agentIdOf('a1')).toBe('claude')
+ })
+})
diff --git a/src/renderer/lib/nodeActionItems.tsx b/src/renderer/lib/nodeActionItems.tsx
index aa01f0aa0..28115f4cb 100644
--- a/src/renderer/lib/nodeActionItems.tsx
+++ b/src/renderer/lib/nodeActionItems.tsx
@@ -60,6 +60,7 @@ import { reopenVariants } from './reopenVariants'
import { tidySeparators } from './tidySeparators'
import { transferConversationItems, type TransferConversationHandler } from './transferItems'
import { isHidden } from './ui-visibility'
+import type { NodeWrites } from './nodeWriteRouter'
/** The agent a terminal node was CREATED as. Deliberately NOT `agentIdOf`, whose extra hook-status
* fallback also reports a plain terminal someone typed `claude` into by hand: TerminalNode's
@@ -820,3 +821,77 @@ export function buildAccountSwitchRows(nodeId: string, ctx: NodeActionCtx): Menu
: [])
]
}
+
+/** What a row that needs the live canvas says when its project is not on the canvas. */
+export const OFF_CANVAS_REFUSAL = 'Open this project on the canvas to do that.'
+
+export interface OffCanvasCtxInput {
+ /** The project's stored nodes, hydrated with `nodeStatesToFlow`. */
+ nodes: readonly CanvasNode[]
+ /** `sessionForProject(projectId).source` — a relay lane is gated like a relay tab. */
+ sessionSource: SessionSource
+ gatewayModels: GatewayModel[]
+ gatewayStatus: ModelDiscoveryStatus
+ gatewayError: string
+ grokModels: () => GatewayModel[]
+ /** The project's write router (Canvas `nodeWritesFor(projectId)`). */
+ writes: Pick<NodeWrites, 'setColor' | 'pickIcon'>
+ liveLinkMenuItems: (nodeId: string) => MenuItem[]
+ connectedProjectIdForHost: (host?: string) => string | undefined
+ /** Raised by every row that needs the live canvas. None of them is on a board today
+ * (`BOARD_NODE_ACTION_IDS`); this keeps the day one is added from failing in silence. */
+ refuse: () => void
+}
+
+/**
+ * The context for a node of a project the canvas does NOT hold (an Omni lane of a background
+ * project). Writes go through the project's write router; no terminal is attached (its rows show
+ * disabled with "This terminal is not attached right now." — account switching, restart and pause
+ * all read the live canvas); everything that needs the live canvas refuses with a toast.
+ */
+export function offCanvasNodeActionCtx(o: OffCanvasCtxInput): NodeActionCtx {
+ const refuse = (): void => o.refuse()
+ const refuseLater = async (): Promise<void> => o.refuse()
+ return {
+ nodes: o.nodes,
+ sessionSource: o.sessionSource,
+ attached: () => false,
+ // Canvas `agentIdOf`, over the stored copy.
+ agentIdOf: (nodeId) => {
+ const n = o.nodes.find((x) => x.id === nodeId)
+ if (!n || n.type !== 'terminal') return undefined
+ return (
+ (n.data.agentId as AgentId | undefined) ??
+ (((n.data.tags as string[] | undefined) ?? []).includes('claude') ? 'claude' : undefined) ??
+ useAgentStatus.getState().byId[nodeId]?.agentId
+ )
+ },
+ gatewayModels: o.gatewayModels,
+ gatewayStatus: o.gatewayStatus,
+ gatewayError: o.gatewayError,
+ grokModels: o.grokModels,
+ addToExistingGroup: refuse,
+ groupSelection: refuse,
+ removeFromGroup: refuse,
+ setNodesColor: o.writes.setColor,
+ pickNodeIcon: o.writes.pickIcon,
+ duplicateNodes: refuse,
+ snapNodeToZone: () => {
+ o.refuse()
+ return false
+ },
+ toggleCollapseNodes: refuse,
+ toggleMarkdown: refuse,
+ reloadTerminals: refuse,
+ liveLinkMenuItems: o.liveLinkMenuItems,
+ branchClaude: refuseLater,
+ transferConversation: refuse,
+ restartAgentNode: refuseLater,
+ pauseAgentNode: refuseLater,
+ resumeAgentNode: refuse,
+ switchClaudeAccountNode: refuseLater,
+ switchCodexAccountNode: refuseLater,
+ connectedProjectIdForHost: o.connectedProjectIdForHost,
+ deleteNodes: refuse
+ }
+}