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): ephemeral cards get their own placement, selection and menu

enes1870c535c896
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 71d423809..3517aedcc 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -360,6 +360,22 @@ const NO_EPHEMERAL: { ephemeralNodes: CanvasNode[]; ephemeralEdges: Edge[] } = {
ephemeralEdges: []
}
+/**
+ * An ephemeral card's position: its parent agent's position plus either the offset the user
+ * dragged it to or the laid-out default. Both live in the AGENT's coordinate space (the card
+ * inherits the agent's `parentId`), which is the whole point of storing an offset — grouping or
+ * ungrouping the agent flips that space between absolute and group-relative, and a stored
+ * position would then teleport the card by the group's own x/y.
+ */
+const offsetFrom = (
+ parent: { position: { x: number; y: number } },
+ stored: { x: number; y: number } | undefined,
+ fallback: { x: number; y: number }
+): { x: number; y: number } => {
+ const off = stored ?? fallback
+ return { x: parent.position.x + off.x, y: parent.position.y + off.y }
+}
+
// Delivering an armed node's held launch (canvas-control `--after`) can lose the race against
// that node's own PTY coming up, and a dropped launch is exactly the thing its dependency was
// waiting for — so a refused delivery is retried a few times instead of vanishing.
@@ -947,8 +963,9 @@ export function Canvas() {
// eslint-disable-next-line react-hooks/exhaustive-deps -- armedDepSig/launchRetry are the triggers
}, [nodes, armedDepSig, launchRetry])
- // Selection state for ephemeral nodes (they live outside React Flow's managed nodes).
- const [ephSel, setEphSel] = useState<Record<string, boolean>>({})
+ // Selection state for ephemeral nodes (they live outside React Flow's managed nodes), owned by
+ // the agent-nodes store so the cards themselves can set it — see `selectable: false` below.
+ const ephSelId = useAgentNodes((s) => s.selectedId)
const { ephemeralNodes, ephemeralEdges } = useMemo(() => {
// Common case: no /loop running and no subagents → return a stable empty result so
// this memo (which depends on `nodes`, i.e. recomputes every drag frame) stays cheap
@@ -984,9 +1001,14 @@ export function Canvas() {
// with the group). Deliberately no extent:'parent' — the fan-out may hang below the
// frame border without being clamped into it.
...(parent.parentId ? { parentId: parent.parentId } : {}),
- position: ephemeralPos[lid] ?? { x: parent.position.x - 250, y: parent.position.y + ph + 60 },
+ position: offsetFrom(parent, ephemeralPos[lid], { x: -250, y: ph + 60 }),
draggable: true,
- selected: !!ephSel[lid],
+ // NOT selectable: React Flow's rubber band would otherwise sweep a whole fan-out of cards
+ // into the selection alongside the real nodes, and every selection action (Group,
+ // Duplicate, Delete, colors) would then be handed ids it cannot act on — the frame ends up
+ // drawn around the wrong things. Cards select one at a time, by click (`select` below).
+ selectable: false,
+ selected: ephSelId === lid,
...dims(lid, 230, 460, 92, 320),
data: {
title: st.loop.task ?? '',
@@ -1029,12 +1051,13 @@ export function Canvas() {
type: 'subagent',
// Same coordinate-space rule as the loop card above: inherit the agent's group.
...(parent.parentId ? { parentId: parent.parentId } : {}),
- position: ephemeralPos[cid] ?? {
- x: parent.position.x + (i % COLS) * COL_W,
- y: parent.position.y + ph + 60 + Math.floor(i / COLS) * ROW_H
- },
+ position: offsetFrom(parent, ephemeralPos[cid], {
+ x: (i % COLS) * COL_W,
+ y: ph + 60 + Math.floor(i / COLS) * ROW_H
+ }),
draggable: true,
- selected: !!ephSel[cid],
+ selectable: false, // see the loop card above
+ selected: ephSelId === cid,
...dims(cid, 230, 480, 96, 340),
data: {
title: v.label ?? '',
@@ -1062,7 +1085,7 @@ export function Canvas() {
}
return { ephemeralNodes: eNodes, ephemeralEdges: eEdges }
// eslint-disable-next-line react-hooks/exhaustive-deps -- loopSig stands in for the byId read
- }, [agentById, loopSig, ephemeralPos, ephSizes, ephExpanded, ephSel, nodes])
+ }, [agentById, loopSig, ephemeralPos, ephSizes, ephExpanded, ephSelId, nodes])
// Merge the persisted nodes with the ephemeral ones once per change (not per render),
// so React Flow's array-identity short-circuit holds while panning/zooming.
@@ -1857,6 +1880,23 @@ export function Canvas() {
}, [undo, redo])
// ---- canvas interactions ----
+
+ /** The position of the agent node a card hangs off, in the CARD's own coordinate space (they
+ * share a `parentId`). Undefined when the agent is gone — the card is on its way out too. */
+ const ephParentPosition = useCallback((cardId: string): { x: number; y: number } | undefined => {
+ const pid = cardId.startsWith('loop-')
+ ? cardId.slice('loop-'.length)
+ : useAgentNodes.getState().byId[cardId]?.parentNodeId
+ return pid ? nodesRef.current.find((n) => n.id === pid)?.position : undefined
+ }, [])
+
+ // Selecting a card is a SINGLE selection: React Flow can't clear the managed one for us
+ // (the cards are outside its selection), so clicking a card drops it here.
+ useEffect(() => {
+ if (!ephSelId) return
+ setNodes((ns) => (ns.some((n) => n.selected) ? ns.map((n) => ({ ...n, selected: false })) : ns))
+ }, [ephSelId, setNodes])
+
const handleNodesChange: typeof onNodesChange = useCallback(
(changes) => {
// Ephemeral nodes (subagent / loop) live outside the managed state. Persist their drag
@@ -1867,10 +1907,20 @@ export function Canvas() {
const isEph = (id: string) => isEphemeralNodeId(id, ephIds)
const managed = changes.filter((c) => {
if ('id' in c && isEph(c.id)) {
- if (c.type === 'position' && c.position) useAgentNodes.getState().setPosition(c.id, c.position)
- else if (c.type === 'select') setEphSel((prev) => ({ ...prev, [c.id]: c.selected }))
- else if (c.type === 'dimensions' && c.dimensions && c.resizing)
- useAgentNodes.getState().setSize(c.id, c.dimensions)
+ const store = useAgentNodes.getState()
+ // Stored as an OFFSET from the parent agent, never as a canvas position — see offsetFrom.
+ if (c.type === 'position' && c.position) {
+ const base = ephParentPosition(c.id)
+ store.setPosition(
+ c.id,
+ base ? { x: c.position.x - base.x, y: c.position.y - base.y } : c.position
+ )
+ }
+ // The cards are `selectable: false`, so React Flow never SELECTS one — but it still
+ // emits the deselect when the pane or another node is clicked, and that is what
+ // dismisses the card's resize frame.
+ else if (c.type === 'select' && !c.selected && store.selectedId === c.id) store.select(null)
+ else if (c.type === 'dimensions' && c.dimensions && c.resizing) store.setSize(c.id, c.dimensions)
return false
}
return true
@@ -1878,7 +1928,7 @@ export function Canvas() {
onNodesChange(managed)
if (managed.some((c) => c.type !== 'select')) markDirty()
},
- [onNodesChange, markDirty]
+ [onNodesChange, markDirty, ephParentPosition]
)
// Resolve a node's agent id, with a tags fallback for not-yet-migrated legacy nodes and a
@@ -4548,6 +4598,43 @@ export function Canvas() {
]
)
+ /** Right-click menu for an ephemeral card. The generic node menu is wrong for one: every
+ * entry on it (Group, Duplicate, Align, Delete…) acts through the managed node array, which a
+ * derived card is not in — so all of them silently did nothing. These are the actions a card
+ * actually has. */
+ const ephemeralItems = useCallback((id: string): MenuItem[] => {
+ const st = useAgentNodes.getState()
+ const isLoop = id.startsWith('loop-')
+ return [
+ { type: 'label', label: isLoop ? 'Loop card' : 'Subagent card' },
+ {
+ label: st.expanded[id] ? 'Collapse' : 'Expand',
+ icon: <IconCollapse />,
+ onClick: () => useAgentNodes.getState().toggleExpanded(id)
+ },
+ {
+ label: 'Reset position',
+ icon: <IconGrid />,
+ onClick: () => useAgentNodes.getState().resetPlacement(id)
+ },
+ ...(isLoop
+ ? ([
+ {
+ // Same as the card's own ×: drops the CARD, never the cron/schedule job itself.
+ label: 'Dismiss card',
+ icon: <IconTrash />,
+ danger: true,
+ onClick: () => {
+ const pid = id.slice('loop-'.length)
+ useAgentStatus.getState().setLoop(pid, false)
+ useAgentNodes.getState().clearLoop(pid)
+ }
+ }
+ ] as MenuItem[])
+ : [])
+ ]
+ }, [])
+
const onPaneContextMenu = useCallback(
(e: MouseEvent | React.MouseEvent) => {
e.preventDefault()
@@ -4633,10 +4720,12 @@ export function Canvas() {
const items =
node.type === 'group'
? groupItems(node.id, screenToFlowPosition({ x: e.clientX, y: e.clientY }))
- : selectionItems(targetIds(node), screenToFlowPosition({ x: e.clientX, y: e.clientY }))
+ : node.type === 'subagent' || node.type === 'loop'
+ ? ephemeralItems(node.id)
+ : selectionItems(targetIds(node), screenToFlowPosition({ x: e.clientX, y: e.clientY }))
setMenu({ x: e.clientX, y: e.clientY, items })
},
- [groupItems, selectionItems, targetIds, screenToFlowPosition]
+ [groupItems, ephemeralItems, selectionItems, targetIds, screenToFlowPosition]
)
const onSelectionContextMenu = useCallback(
@@ -4646,7 +4735,8 @@ export function Canvas() {
x: e.clientX,
y: e.clientY,
items: selectionItems(
- selected.map((n) => n.id),
+ // Derived cards can't be acted on; filtering keeps the "N nodes" count honest too.
+ selected.filter((n) => n.type !== 'subagent' && n.type !== 'loop').map((n) => n.id),
screenToFlowPosition({ x: e.clientX, y: e.clientY })
)
})
@@ -7133,7 +7223,7 @@ export function Canvas() {
publisherRef.current?.flush()
markDirty()
}}
- onPaneClick={() => setEphSel({})}
+ onPaneClick={() => useAgentNodes.getState().select(null)}
onPaneContextMenu={onPaneContextMenu}
onNodeContextMenu={onNodeContextMenu}
onSelectionContextMenu={onSelectionContextMenu}
diff --git a/src/renderer/nodes/LoopNode.tsx b/src/renderer/nodes/LoopNode.tsx
index db30dff4b..9670870df 100644
--- a/src/renderer/nodes/LoopNode.tsx
+++ b/src/renderer/nodes/LoopNode.tsx
@@ -43,8 +43,12 @@ export function LoopNode({ id, data, selected }: NodeProps<CanvasNode>) {
useAgentNodes.getState().clearLoop(parentId)
}
+ // The cards are `selectable: false` in React Flow (a rubber band must not sweep a fan-out
+ // into the selection), so selecting one — which is what reveals its resize frame — is ours.
+ const select = () => useAgentNodes.getState().select(id)
+
return (
- <div className={`loop-node${active ? ' working' : ''}`}>
+ <div onPointerDownCapture={select} className={`loop-node${active ? ' working' : ''}`}>
<NodeResizer isVisible={selected} minWidth={180} minHeight={84} color="#bf7af0" />
<Handle type="target" position={Position.Top} isConnectable={false} />
<div className="loop-node__head nodrag" onClick={toggle} style={{ cursor: 'pointer' }}>
diff --git a/src/renderer/nodes/SubagentNode.tsx b/src/renderer/nodes/SubagentNode.tsx
index fcfd8c03e..e5167e146 100644
--- a/src/renderer/nodes/SubagentNode.tsx
+++ b/src/renderer/nodes/SubagentNode.tsx
@@ -53,8 +53,12 @@ export function SubagentNode({ id, data, selected }: NodeProps<CanvasNode>) {
.filter(Boolean)
.join(' · ')
+ // The cards are `selectable: false` in React Flow (a rubber band must not sweep a fan-out
+ // into the selection), so selecting one — which is what reveals its resize frame — is ours.
+ const select = () => useAgentNodes.getState().select(id)
+
return (
- <div className={`subagent-node${working ? ' working' : ' done'}`}>
+ <div onPointerDownCapture={select} className={`subagent-node${working ? ' working' : ' done'}`}>
<NodeResizer isVisible={selected} minWidth={180} minHeight={84} color="#d97757" />
<Handle type="target" position={Position.Top} isConnectable={false} />
<div className="subagent-node__head nodrag" onClick={toggle} style={{ cursor: 'pointer' }}>
diff --git a/src/renderer/state/agentNodes.test.ts b/src/renderer/state/agentNodes.test.ts
index 205ef5d5f..58e346b4c 100644
--- a/src/renderer/state/agentNodes.test.ts
+++ b/src/renderer/state/agentNodes.test.ts
@@ -33,6 +33,60 @@ describe('loop node overrides vs per-turn fan-out', () => {
})
})
+describe('ephemeral card selection', () => {
+ beforeEach(() => {
+ useAgentNodes.setState({
+ byId: {},
+ activityById: {},
+ positions: {},
+ sizes: {},
+ expanded: {},
+ selectedId: null
+ })
+ })
+
+ // Cards are `selectable: false` in React Flow (a rubber band must never sweep a fan-out into
+ // the selection and hand those ids to Group / Duplicate / Delete), so selection lives here —
+ // and it is single: one card at a time.
+ it('selects one card at a time', () => {
+ useAgentNodes.getState().select('tu1')
+ expect(useAgentNodes.getState().selectedId).toBe('tu1')
+ useAgentNodes.getState().select('tu2')
+ expect(useAgentNodes.getState().selectedId).toBe('tu2')
+ useAgentNodes.getState().select(null)
+ expect(useAgentNodes.getState().selectedId).toBeNull()
+ })
+
+ it('drops the selection when the selected card disappears', () => {
+ const s = useAgentNodes.getState()
+ s.start('tu1', { parentNodeId: 'n1' })
+ s.select('tu1')
+ s.clearForParent('n1')
+ expect(useAgentNodes.getState().selectedId).toBeNull()
+ })
+
+ it('keeps the selection when a DIFFERENT parent’s fan-out is cleared', () => {
+ const s = useAgentNodes.getState()
+ s.start('tu1', { parentNodeId: 'n1' })
+ s.start('tu2', { parentNodeId: 'n2' })
+ s.select('tu1')
+ s.clearForParent('n2')
+ expect(useAgentNodes.getState().selectedId).toBe('tu1')
+ })
+
+ it('resetPlacement drops the dragged offset and the resized size', () => {
+ const s = useAgentNodes.getState()
+ s.setPosition('tu1', { x: 120, y: 40 })
+ s.setSize('tu1', { width: 400, height: 300 })
+ s.setPosition('tu2', { x: 1, y: 1 })
+ s.resetPlacement('tu1')
+ const st = useAgentNodes.getState()
+ expect(st.positions['tu1']).toBeUndefined()
+ expect(st.sizes['tu1']).toBeUndefined()
+ expect(st.positions['tu2']).toEqual({ x: 1, y: 1 })
+ })
+})
+
describe('useAgentNodes.finish', () => {
beforeEach(() => {
useAgentNodes.setState({ byId: {}, activityById: {}, positions: {}, sizes: {}, expanded: {} })
@@ -77,20 +131,42 @@ describe('loop card override persistence', () => {
fresh.getState().setPosition('loop-n1', { x: 42, y: 43 })
fresh.getState().setSize('loop-n1', { width: 300, height: 120 })
fresh.getState().setPosition('tu-sub', { x: 1, y: 2 }) // subagent — must NOT persist
- const saved = JSON.parse(mem.get('nodeterm.loopCards')!)
+ const saved = JSON.parse(mem.get('nodeterm.loopCards.v2')!)
expect(saved.positions['loop-n1']).toEqual({ x: 42, y: 43 })
expect(saved.sizes['loop-n1']).toEqual({ width: 300, height: 120 })
expect(saved.positions['tu-sub']).toBeUndefined()
fresh.getState().clearLoop('n1')
- const after = JSON.parse(mem.get('nodeterm.loopCards') ?? '{}')
+ const after = JSON.parse(mem.get('nodeterm.loopCards.v2') ?? '{}')
expect(after.positions?.['loop-n1']).toBeUndefined()
vi.unstubAllGlobals()
})
- it('hydrates persisted loop-* overrides on load', async () => {
+ it('ignores the v1 key, whose positions meant something else', async () => {
+ // v1 stored a canvas POSITION; v2 stores an offset from the parent agent. Reading a v1 entry
+ // as an offset would fling the card across the canvas, so the old key is simply not read.
const mem = new Map<string, string>([
[
'nodeterm.loopCards',
+ JSON.stringify({ positions: { 'loop-n3': { x: 4000, y: 3000 } }, sizes: {}, expanded: {} })
+ ]
+ ])
+ const store = {
+ getItem: (k: string) => mem.get(k) ?? null,
+ setItem: (k: string, v: string) => void mem.set(k, v),
+ removeItem: (k: string) => void mem.delete(k)
+ }
+ const { vi } = await import('vitest')
+ vi.stubGlobal('localStorage', store)
+ vi.resetModules()
+ const { useAgentNodes: fresh } = await import('./agentNodes')
+ expect(fresh.getState().positions['loop-n3']).toBeUndefined()
+ vi.unstubAllGlobals()
+ })
+
+ it('hydrates persisted loop-* overrides on load', async () => {
+ const mem = new Map<string, string>([
+ [
+ 'nodeterm.loopCards.v2',
JSON.stringify({ positions: { 'loop-n2': { x: 9, y: 8 } }, sizes: {}, expanded: { 'loop-n2': true } })
]
])
diff --git a/src/renderer/state/agentNodes.ts b/src/renderer/state/agentNodes.ts
index dc2be29c5..cae95faeb 100644
--- a/src/renderer/state/agentNodes.ts
+++ b/src/renderer/state/agentNodes.ts
@@ -39,13 +39,30 @@ interface AgentNodesState {
* expanded SubagentNode subscribes here, per id.
*/
activityById: Record<string, string>
- /** Per-ephemeral-node UI overrides (keyed by node id: subagent ids + `loop-<parentId>`). */
+ /**
+ * Per-ephemeral-node UI overrides (keyed by node id: subagent ids + `loop-<parentId>`).
+ * `positions` holds an OFFSET FROM THE PARENT AGENT NODE, not a canvas position: the card
+ * always shares the agent's coordinate space (it inherits the agent's `parentId`), so an
+ * offset survives the space CHANGING under it. Storing the position itself meant that
+ * grouping or ungrouping the agent — which flips its position between absolute and
+ * group-relative — teleported every card the user had dragged, by the group's own x/y.
+ */
positions: Record<string, { x: number; y: number }>
sizes: Record<string, { width: number; height: number }>
expanded: Record<string, boolean>
- setPosition(id: string, pos: { x: number; y: number }): void
+ /**
+ * The one selected ephemeral card, or null. Kept here (not in React Flow's selection) because
+ * the cards are `selectable: false`: a rubber-band or select-all must never sweep up a whole
+ * subagent fan-out and hand those ids to Group / Duplicate / Delete, which cannot act on a
+ * derived node. Cards select one at a time, by click, purely to show their resize frame.
+ */
+ selectedId: string | null
+ select(id: string | null): void
+ setPosition(id: string, offset: { x: number; y: number }): void
setSize(id: string, size: { width: number; height: number }): void
toggleExpanded(id: string): void
+ /** Drop a card's dragged position + resized size, returning it to its laid-out spot. */
+ resetPlacement(id: string): void
start(toolUseId: string, viz: Omit<SubagentViz, 'state' | 'startedAt'>): void
finish(toolUseId: string, result: SubagentResult): void
/** Append a chunk of the subagent's live transcript. */
@@ -63,7 +80,10 @@ interface AgentNodesState {
// Loop-card overrides survive restarts: the loop itself is persisted (agentStatus), so its
// dragged position/size must be too, or every launch teleports the card back to the default
// spot. Only `loop-*` keys are stored — subagent cards are per-turn.
-const LOOP_CARDS_KEY = 'nodeterm.loopCards'
+// v2: `positions` changed meaning from a canvas position to an offset from the parent agent
+// node. Reading a v1 entry as an offset would fling the card across the canvas, so the old key is
+// simply abandoned — the cost is one reset of a dragged loop card, not a mystery jump.
+const LOOP_CARDS_KEY = 'nodeterm.loopCards.v2'
type Overrides = Pick<AgentNodesState, 'positions' | 'sizes' | 'expanded'>
@@ -94,11 +114,14 @@ function saveLoopOverrides(s: Overrides): void {
export const useAgentNodes = create<AgentNodesState>((set) => ({
byId: {},
activityById: {},
+ selectedId: null,
...loadLoopOverrides(),
- setPosition: (id, pos) =>
+ select: (id) => set((s) => (s.selectedId === id ? s : { selectedId: id })),
+
+ setPosition: (id, offset) =>
set((s) => {
- const next = { positions: { ...s.positions, [id]: pos } }
+ const next = { positions: { ...s.positions, [id]: offset } }
if (id.startsWith('loop-')) saveLoopOverrides({ ...s, ...next })
return next
}),
@@ -115,6 +138,17 @@ export const useAgentNodes = create<AgentNodesState>((set) => ({
return next
}),
+ resetPlacement: (id) =>
+ set((s) => {
+ if (!(id in s.positions) && !(id in s.sizes)) return s
+ const positions = { ...s.positions }
+ const sizes = { ...s.sizes }
+ delete positions[id]
+ delete sizes[id]
+ if (id.startsWith('loop-')) saveLoopOverrides({ ...s, positions, sizes })
+ return { positions, sizes }
+ }),
+
start: (toolUseId, viz) =>
set((s) => ({
byId: { ...s.byId, [toolUseId]: { ...viz, state: 'working', startedAt: Date.now() } }
@@ -154,7 +188,10 @@ export const useAgentNodes = create<AgentNodesState>((set) => ({
delete sizes[id]
delete expanded[id]
}
- return { byId, activityById, positions, sizes, expanded }
+ // A card that just vanished must not stay "selected" — a later card reusing the id would
+ // come back pre-selected.
+ const selectedId = s.selectedId && ids.includes(s.selectedId) ? null : s.selectedId
+ return { byId, activityById, positions, sizes, expanded, selectedId }
}),
clearLoop: (parentNodeId) =>
@@ -168,6 +205,6 @@ export const useAgentNodes = create<AgentNodesState>((set) => ({
delete sizes[id]
delete expanded[id]
saveLoopOverrides({ positions, sizes, expanded })
- return { positions, sizes, expanded }
+ return { positions, sizes, expanded, selectedId: s.selectedId === id ? null : s.selectedId }
})
}))