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
feat(canvas): persist cron/schedule cards and control ropes
enesfdb4a5297c4d
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 173fa9026..c64f87436 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -1,6 +1,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import {addEdge,+ applyEdgeChanges,Background,BackgroundVariant,Controls,@@ -12,6 +13,7 @@ import {useNodesState,useReactFlow,type Connection,+ type EdgeChange,type Viewport} from '@xyflow/react'import type { Edge, Node } from '@xyflow/react'@@ -164,6 +166,19 @@ const NO_EPHEMERAL: { ephemeralNodes: CanvasNode[]; ephemeralEdges: Edge[] } = {ephemeralEdges: []}+// 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.+const ropeEdge = (id: string, source: string, target: string, color: string): Edge => ({+ id,+ source,+ sourceHandle: 'flow-out',+ target,+ targetHandle: 'flow-in',+ style: { stroke: color, strokeWidth: 1.5 },+ markerEnd: { type: MarkerType.ArrowClosed, color, width: 14, height: 14 }+})+const minimapNodeColor = (n: Node): string =>(n.data as { color?: string })?.color ?? '#0a84ff'@@ -239,10 +254,13 @@ export function Canvas() {const [linkEdges, setLinkEdges, onLinkEdgesChange] = useEdgesState<Edge>([])const linkEdgesRef = useRef<Edge[]>([])linkEdgesRef.current = linkEdges- // Display-only edges drawn from a control-capable agent to the nodes it spawns via the- // `nodeterm` CLI (see the onAgentControl effect). Like ephemeralEdges, these are merged only at- // the <ReactFlow> prop: never persisted (not bridges) and never turned into context links.+ // "Spawned by" ropes drawn from a control-capable agent to the nodes it opens via the+ // `nodeterm` CLI (see the onAgentControl effect) and from browser popups to their opener.+ // Merged only at the <ReactFlow> prop and never turned into context links, but PERSISTED+ // per project (`ropes`) so the lineage survives restarts; deletable like a context link.const [controlEdges, setControlEdges] = useState<Edge[]>([])+ const controlEdgesRef = useRef<Edge[]>([])+ controlEdgesRef.current = controlEdgesconst [dirty, setDirty] = useState(false)const [zoomPct, setZoomPct] = useState(100)const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)@@ -548,7 +566,22 @@ export function Canvas() {: { markerStart: { type: MarkerType.ArrowClosed, color: stroke, width: 14, height: 14 } })}})- const extra = ephemeralEdges.length || controlEdges.length ? [...ephemeralEdges, ...controlEdges] : []+ // Control ropes: white + a removal hint while selected (mirrors the context-link look).+ const ropes = controlEdges.map((e) =>+ e.selected+ ? {+ ...e,+ label: '⌫ to remove',+ labelStyle: { fill: '#ffffff', fontSize: 11, fontWeight: 600 },+ labelBgStyle: { fill: '#1c1c1e', fillOpacity: 0.85 },+ labelBgPadding: [6, 3] as [number, number],+ labelBgBorderRadius: 5,+ style: { ...e.style, stroke: '#ffffff', strokeWidth: 3 },+ markerEnd: { type: MarkerType.ArrowClosed, color: '#ffffff', width: 14, height: 14 }+ }+ : e+ )+ const extra = ephemeralEdges.length || ropes.length ? [...ephemeralEdges, ...ropes] : []return extra.length ? [...decorated, ...extra] : decorated}, [linkEdges, ephemeralEdges, controlEdges, accent, stickySig])@@ -697,6 +730,14 @@ export function Canvas() {const flow = nodeStatesToFlow(project.nodes)setNodes(flow)setLinkEdges((project.bridges ?? []).map((b) => ({ id: b.id, source: b.source, target: b.target })))+ // Restore control ropes with the source agent's color (falls back to the browser blue).+ setControlEdges(+ (project.ropes ?? []).map((r) => {+ const srcState = project.nodes.find((n) => n.id === r.source)+ const color = agentConfig((srcState?.agentId as AgentId) ?? '')?.color ?? '#0a84ff'+ return ropeEdge(r.id, r.source, r.target, color)+ })+ )// Reset history for the newly loaded project.committedRef.current = flowpastRef.current = []@@ -753,7 +794,8 @@ export function Canvas() {id,flowToNodeStates(nodesRef.current),viewportRef.current,- linkEdgesRef.current.map((e) => ({ id: e.id, source: e.source, target: e.target }))+ linkEdgesRef.current.map((e) => ({ id: e.id, source: e.source, target: e.target })),+ controlEdgesRef.current.map((e) => ({ id: e.id, source: e.source, target: e.target })))}, [])@@ -974,6 +1016,12 @@ export function Canvas() {// Double-click a context link to remove it (ephemeral subagent/loop edges are left alone).const onEdgeDoubleClick = useCallback((_e: React.MouseEvent, edge: Edge) => {+ // Control ropes are removable the same way as context links (ephemeral edges are not).+ if (controlEdgesRef.current.some((b) => b.id === edge.id)) {+ setControlEdges((es) => es.filter((b) => b.id !== edge.id))+ markDirty()+ return+ }if (!linkEdgesRef.current.some((b) => b.id === edge.id)) returnsetLinkEdges((es) => es.filter((b) => b.id !== edge.id))markDirty()@@ -981,6 +1029,29 @@ export function Canvas() {[setLinkEdges, markDirty])+ // Route edge changes (selection) to the right store: `ctrl-` ids are control ropes (local+ // state), everything else is a context link. Ephemeral subagent/loop edges emit no changes+ // worth applying — applyEdgeChanges on unknown ids is a no-op either way.+ const handleEdgesChange = useCallback(+ (changes: EdgeChange[]) => {+ const rope: EdgeChange[] = []+ const link: EdgeChange[] = []+ for (const c of changes) ('id' in c && String(c.id).startsWith('ctrl-') ? rope : link).push(c)+ if (rope.length) setControlEdges((es) => applyEdgeChanges(rope, es))+ if (link.length) onLinkEdgesChange(link)+ },+ [onLinkEdgesChange]+ )++ // Prune ropes whose endpoints were deleted (mirrors the context-link pruning below).+ useEffect(() => {+ const ids = new Set(nodes.map((n) => n.id))+ setControlEdges((es) => {+ const valid = es.filter((e) => ids.has(e.source) && ids.has(e.target))+ return valid.length === es.length ? es : valid+ })+ }, [nodes])+// Prune links whose endpoints were deleted, then push the link map to main (debounced) so// it can rewrite the per-node link files the context CLI reads.useEffect(() => {@@ -1274,11 +1345,14 @@ export function Canvas() {)const addSticky = useCallback(- (center?: { x: number; y: number }) => {- setNodes((ns) => [...ns, createStickyNode(ns.length, center ?? viewCenter())])+ (center?: { x: number; y: number }, groupId?: string) => {+ setNodes((ns) => {+ const node = createStickyNode(ns.length, center ?? viewCenter())+ return [...ns, groupId ? parentInto(node, groupId) : node]+ })markDirty()},- [setNodes, markDirty, viewCenter]+ [setNodes, markDirty, viewCenter, parentInto])const addDino = useCallback(@@ -1312,20 +1386,21 @@ export function Canvas() {)const addChatNode = useCallback(- (center?: { x: number; y: number }, accountId?: string) => {+ (center?: { x: number; y: number }, accountId?: string, groupId?: string) => {const project = useProjects.getState().getProject(activeProjectId)+ const cwd = cwdForNewNodeIn(groupId) ?? project?.cwdconst account = resolveNewNodeAccount(accountId,project,useSettings.getState().settings.claudeAccounts)- setNodes((ns) => [- ...ns,- createChatNode(ns.length, project?.cwd, center ?? viewCenter(), undefined, account)- ])+ setNodes((ns) => {+ const node = createChatNode(ns.length, cwd, center ?? viewCenter(), undefined, account)+ return [...ns, groupId ? parentInto(node, groupId) : node]+ })markDirty()},- [setNodes, markDirty, activeProjectId, viewCenter]+ [setNodes, markDirty, activeProjectId, viewCenter, cwdForNewNodeIn, parentInto])// Terminal → chat fork (Task 10): a Claude terminal node dispatches 'nodeterm:open-chat'@@ -1526,8 +1601,10 @@ export function Canvas() {useChatSessions.getState().drop(n.id)}// Permanent deletion → drop the node's persisted agent status (sessionId/session/- // unread). Node unmount no longer does this, so deletion must.+ // unread/loop). Node unmount no longer does this, so deletion must. The loop card's+ // UI overrides live in agentNodes and are skipped by unmount's clearForParent.useAgentStatus.getState().remove(n.id)+ useAgentNodes.getState().clearLoop(n.id)})// Tear down relay connections owned solely by the deleted remote node(s). The model is// N:1 (one connection per remote node), but dedupe defensively: only disconnect a@@ -1577,12 +1654,19 @@ export function Canvas() {if (tag === 'input' || tag === 'textarea') returnconst ids = nodesRef.current.filter((n) => n.selected).map((n) => n.id)if (!ids.length) {- // No node selected → remove any selected context link(s).+ // No node selected → remove any selected context link(s) / control rope(s).const edgeIds = linkEdgesRef.current.filter((b) => b.selected).map((b) => b.id)- if (edgeIds.length) {+ const ropeIds = controlEdgesRef.current.filter((b) => b.selected).map((b) => b.id)+ if (edgeIds.length || ropeIds.length) {e.preventDefault()- const drop = new Set(edgeIds)- setLinkEdges((es) => es.filter((b) => !drop.has(b.id)))+ if (edgeIds.length) {+ const drop = new Set(edgeIds)+ setLinkEdges((es) => es.filter((b) => !drop.has(b.id)))+ }+ if (ropeIds.length) {+ const drop = new Set(ropeIds)+ setControlEdges((es) => es.filter((b) => !drop.has(b.id)))+ }markDirty()}return@@ -2037,9 +2121,18 @@ export function Canvas() {const selectionItems = useCallback((ids: string[]): MenuItem[] => [{ type: 'label', label: ids.length > 1 ? `${ids.length} nodes` : '1 node' },- ...(ids.length > 1+ // Shown only when something is actually groupable: top-level and not itself a group+ // (groupSelectedNodes silently skips the rest, so the item would otherwise no-op).+ ...(ids.some((nid) => {+ const n = nodesRef.current.find((nd) => nd.id === nid)+ return !!n && !n.parentId && n.type !== 'group'+ })? ([- { label: 'Group selection', icon: <IconGroup />, onClick: () => groupSelection(ids) },+ {+ label: ids.length > 1 ? 'Group selection' : 'Group node',+ icon: <IconGroup />,+ onClick: () => groupSelection(ids)+ },{ type: 'separator' }] as MenuItem[]): []),@@ -2111,14 +2204,89 @@ export function Canvas() {])+ /** "New <agent>" / "New chat" creation entries shared by the pane and group context menus.+ * `at` is the flow position to create at; with `groupId` the node is parented into that group. */+ const agentCreationItems = useCallback(+ (at?: { x: number; y: number }, groupId?: string): MenuItem[] => {+ const disabled = useSettings.getState().settings.disabledAgents+ // Accounts selectable in the active project: local accounts for a local project, or this+ // host's accounts for an SSH project (pending logins always excluded).+ const accounts = accountsForProject(+ useSettings.getState().settings.claudeAccounts,+ useProjects.getState().getProject(activeProjectId)+ )+ return [+ ...BUILTIN_AGENT_IDS.filter((aid) => !disabled.includes(aid)).map((aid): MenuItem => {+ // Claude gets an account picker submenu when ≥1 account exists; System = project+ // default (resolved). Other agents stay flat (accounts are Claude-only).+ if (aid === 'claude' && accounts.length > 0) {+ return {+ type: 'submenu',+ label: `New ${AGENT_CONFIG[aid].label}`,+ icon: <AgentIcon agentId={aid} />,+ children: [+ { label: 'System account', onClick: () => addAgentNode('claude', at, groupId) },+ ...accounts.map(+ (a): MenuItem => ({+ label: a.label,+ onClick: () => addAgentNode('claude', at, groupId, a.id)+ })+ )+ ]+ }+ }+ return {+ label: `New ${AGENT_CONFIG[aid].label}`,+ icon: <AgentIcon agentId={aid} />,+ onClick: () => addAgentNode(aid, at, groupId)+ }+ }),+ ...useSettings+ .getState()+ .settings.customAgents.filter((c) => !disabled.includes(c.id))+ .map(+ (c): MenuItem => ({+ label: `New ${c.label}`,+ icon: <AgentIcon agentId={c.id} />,+ onClick: () => addAgentNode(c.id, at, groupId)+ })+ ),+ accounts.length > 0+ ? {+ type: 'submenu',+ label: 'New chat',+ icon: <IconChat />,+ children: [+ { label: 'System account', onClick: () => addChatNode(at, undefined, groupId) },+ ...accounts.map(+ (a): MenuItem => ({+ label: a.label,+ onClick: () => addChatNode(at, a.id, groupId)+ })+ )+ ]+ }+ : {+ label: 'New chat',+ icon: <IconChat />,+ onClick: () => addChatNode(at, undefined, groupId)+ }+ ]+ },+ [activeProjectId, addAgentNode, addChatNode]+ )+const groupItems = useCallback(- (groupId: string): MenuItem[] => [+ (groupId: string, at?: { x: number; y: number }): MenuItem[] => [{ type: 'label', label: 'Group' },{- label: 'New terminal in group',+ label: 'New terminal',icon: <IconTerminal />,- onClick: () => addTerminal(undefined, undefined, groupId)+ onClick: () => addTerminal(at, undefined, groupId)},+ ...agentCreationItems(at, groupId),+ { label: 'New sticky note', icon: <IconNote />, onClick: () => addSticky(at, groupId) },+ { type: 'separator' },{ type: 'colors', onPick: (c) => setNodesColor([groupId], c) },{ type: 'separator' },...(groupHasWorktree(groupId)@@ -2133,76 +2301,27 @@ export function Canvas() {{ label: 'Ungroup', icon: <IconUngroup />, onClick: () => ungroup(groupId) },{ label: 'Delete (keeps nodes)', icon: <IconTrash />, danger: true, onClick: () => ungroup(groupId) }],- [setNodesColor, ungroup, groupHasWorktree, bindGroupToWorktree, addTerminal]+ [+ setNodesColor,+ ungroup,+ groupHasWorktree,+ bindGroupToWorktree,+ addTerminal,+ agentCreationItems,+ addSticky+ ])const onPaneContextMenu = useCallback((e: MouseEvent | React.MouseEvent) => {e.preventDefault()const at = screenToFlowPosition({ x: e.clientX, y: e.clientY })- const disabled = useSettings.getState().settings.disabledAgents- // Accounts selectable in the active project: local accounts for a local project, or this- // host's accounts for an SSH project (pending logins always excluded).- const accounts = accountsForProject(- useSettings.getState().settings.claudeAccounts,- useProjects.getState().getProject(activeProjectId)- )setMenu({x: e.clientX,y: e.clientY,items: [{ label: 'New terminal', icon: <IconTerminal />, onClick: () => addTerminal(at) },- ...BUILTIN_AGENT_IDS.filter((aid) => !disabled.includes(aid)).map((aid): MenuItem => {- // Claude gets an account picker submenu when ≥1 account exists; System = project- // default (resolved). Other agents stay flat (accounts are Claude-only).- if (aid === 'claude' && accounts.length > 0) {- return {- type: 'submenu',- label: `New ${AGENT_CONFIG[aid].label}`,- icon: <AgentIcon agentId={aid} />,- children: [- { label: 'System account', onClick: () => addAgentNode('claude', at) },- ...accounts.map(- (a): MenuItem => ({- label: a.label,- onClick: () => addAgentNode('claude', at, undefined, a.id)- })- )- ]- }- }- return {- label: `New ${AGENT_CONFIG[aid].label}`,- icon: <AgentIcon agentId={aid} />,- onClick: () => addAgentNode(aid, at)- }- }),- ...useSettings- .getState()- .settings.customAgents.filter((c) => !disabled.includes(c.id))- .map(- (c): MenuItem => ({- label: `New ${c.label}`,- icon: <AgentIcon agentId={c.id} />,- onClick: () => addAgentNode(c.id, at)- })- ),- accounts.length > 0- ? {- type: 'submenu',- label: 'New chat',- icon: <IconChat />,- children: [- { label: 'System account', onClick: () => addChatNode(at) },- ...accounts.map(- (a): MenuItem => ({- label: a.label,- onClick: () => addChatNode(at, a.id)- })- )- ]- }- : { label: 'New chat', icon: <IconChat />, onClick: () => addChatNode(at) },+ ...agentCreationItems(at),{ label: 'New browser', icon: <IconRemote />, onClick: () => addBrowser(at) },{ label: 'New sticky note', icon: <IconNote />, onClick: () => addSticky(at) },{ label: 'New dino game', icon: <IconDino />, onClick: () => addDino(at) },@@ -2221,26 +2340,29 @@ export function Canvas() {[screenToFlowPosition,addTerminal,- addAgentNode,- addChatNode,+ agentCreationItems,addSticky,addDino,addBrowser,openFileDialog,openRemotePicker,selectAll,- fitView,- activeProjectId+ fitView])const onNodeContextMenu = useCallback((e: React.MouseEvent, node: Node) => {e.preventDefault()- const items = node.type === 'group' ? groupItems(node.id) : selectionItems(targetIds(node))+ // For a group frame, remember WHERE inside it the user right-clicked so "New …" creation+ // entries can place the node at the cursor (parentInto converts to group-relative).+ const items =+ node.type === 'group'+ ? groupItems(node.id, screenToFlowPosition({ x: e.clientX, y: e.clientY }))+ : selectionItems(targetIds(node))setMenu({ x: e.clientX, y: e.clientY, items })},- [groupItems, selectionItems, targetIds]+ [groupItems, selectionItems, targetIds, screenToFlowPosition])const onSelectionContextMenu = useCallback(@@ -2414,18 +2536,7 @@ export function Canvas() {y: src.position.y + srcH + 80 + 280})setNodes((ns) => [...ns, node])- setControlEdges((es) => [- ...es,- {- id: `ctrl-${sourceNodeId}-${node.id}`,- source: sourceNodeId,- sourceHandle: 'flow-out',- target: node.id,- targetHandle: 'flow-in',- style: { stroke: '#0a84ff', strokeWidth: 1.5 },- markerEnd: { type: MarkerType.ArrowClosed, color: '#0a84ff', width: 14, height: 14 }- }- ])+ setControlEdges((es) => [...es, ropeEdge(`ctrl-${sourceNodeId}-${node.id}`, sourceNodeId, node.id, '#0a84ff')])markDirty()})// eslint-disable-next-line react-hooks/exhaustive-deps@@ -2460,18 +2571,7 @@ export function Canvas() {const edgeColor = agentConfig((src.data.agentId as string) ?? 'claude')?.color ?? '#d97757'const placeBelow = (i = 0) => ({ x: src.position.x + srcW / 2 + i * 460, y: belowY + 210 })const connect = (newId: string) =>- setControlEdges((es) => [- ...es,- {- id: `ctrl-${sourceNodeId}-${newId}`,- source: sourceNodeId,- sourceHandle: 'flow-out',- target: newId,- targetHandle: 'flow-in',- style: { stroke: edgeColor, strokeWidth: 1.5 },- markerEnd: { type: MarkerType.ArrowClosed, color: edgeColor, width: 14, height: 14 }- }- ])+ setControlEdges((es) => [...es, ropeEdge(`ctrl-${sourceNodeId}-${newId}`, sourceNodeId, newId, edgeColor)])// Append a freshly-created node, draw its connecting edge, and mark the canvas dirty so it// persists. Returns the new node id.const addAndConnect = (node: CanvasNode) => {@@ -3008,15 +3108,26 @@ export function Canvas() {})breakcase 'recurring':- if (e.recurringKind)+ if (e.recurringEnd) {+ // The recurring job itself was removed (CronDelete) — take the card down.+ cs.setLoop(e.nodeId, false)+ an.clearLoop(e.nodeId)+ } else if (e.recurringKind) {cs.setLoop(e.nodeId, true, e.recurringKind, { schedule: e.schedule, task: e.task })+ }breakcase 'session':if (e.sessionTitle) cs.setSession(e.nodeId, e.sessionTitle)if (e.sessionPhase === 'start') cs.setState(e.nodeId, undefined, e.agentId)if (e.sessionPhase === 'end') {cs.setState(e.nodeId, undefined, e.agentId)- cs.setLoop(e.nodeId, false)+ // In-session /loop dies with its session; cron (and scheduled cloud routines)+ // keep running after it — their cards stay until CronDelete / manual dismiss.+ const kind = cs.byId[e.nodeId]?.loop?.kind+ if (kind === 'loop') {+ cs.setLoop(e.nodeId, false)+ an.clearLoop(e.nodeId)+ }an.clearForParent(e.nodeId)}break@@ -3468,7 +3579,7 @@ export function Canvas() {edges={displayEdges}nodeTypes={nodeTypes}onNodesChange={handleNodesChange}- onEdgesChange={onLinkEdgesChange}+ onEdgesChange={handleEdgesChange}onConnect={onConnect}onEdgeDoubleClick={onEdgeDoubleClick}onMove={onMove}diff --git a/src/renderer/nodes/LoopNode.tsx b/src/renderer/nodes/LoopNode.tsxindex 488890377..a024c3aff 100644--- a/src/renderer/nodes/LoopNode.tsx+++ b/src/renderer/nodes/LoopNode.tsx@@ -2,6 +2,7 @@ import { useEffect, useRef } from 'react'import { Handle, NodeResizer, Position, type NodeProps } from '@xyflow/react'import type { CanvasNode } from '../state/workspace'import { useAgentNodes } from '../state/agentNodes'+import { useAgentStatus } from '../state/agentStatus'/*** Loop/schedule/cron node — first-class (select/drag/resize). Shows the kind, schedule, full@@ -29,6 +30,16 @@ export function LoopNode({ id, data, selected }: NodeProps<CanvasNode>) {if (task) void window.nodeTerminal.pty.sendText(id.replace(/^loop-/, ''), task)}+ // Manual dismiss: cron/schedule cards persist across turns/sessions/restarts, so a job+ // removed while the app wasn't watching (or one the user just wants gone) needs an ×.+ // Dismissing only drops the CARD — it does not touch the cron job itself.+ const dismiss = (e: React.MouseEvent) => {+ e.stopPropagation()+ const parentId = id.replace(/^loop-/, '')+ useAgentStatus.getState().setLoop(parentId, false)+ useAgentNodes.getState().clearLoop(parentId)+ }+return (<div className={`loop-node${active ? ' working' : ''}`}><NodeResizer isVisible={selected} minWidth={180} minHeight={84} color="#bf7af0" />@@ -53,6 +64,13 @@ export function LoopNode({ id, data, selected }: NodeProps<CanvasNode>) {▶</button>)}+ <button+ className="loop-node__close"+ title="Dismiss card (does not remove the job)"+ onClick={dismiss}+ >+ ×+ </button></div>{(task || schedule) && !expanded && <div className="loop-node__task">{task || schedule}</div>}{expanded && (diff --git a/src/renderer/state/agentNodes.test.ts b/src/renderer/state/agentNodes.test.tsindex 6b6c73fc0..7be5194d7 100644--- a/src/renderer/state/agentNodes.test.ts+++ b/src/renderer/state/agentNodes.test.ts@@ -1,6 +1,38 @@import { beforeEach, describe, expect, it } from 'vitest'import { useAgentNodes } from './agentNodes'+describe('loop node overrides vs per-turn fan-out', () => {+ beforeEach(() => {+ useAgentNodes.setState({ byId: {}, activityById: {}, positions: {}, sizes: {}, expanded: {} })+ })++ // A loop/cron card outlives turns: a new prompt clears the subagent fan-out but must NOT+ // reset where the user dragged the loop card.+ it('clearForParent drops subagent overrides but keeps the loop card position', () => {+ const s = useAgentNodes.getState()+ s.start('tu1', { parentNodeId: 'n1' })+ s.setPosition('tu1', { x: 1, y: 2 })+ s.setPosition('loop-n1', { x: 5, y: 6 })+ s.clearForParent('n1')+ expect(useAgentNodes.getState().positions['tu1']).toBeUndefined()+ expect(useAgentNodes.getState().positions['loop-n1']).toEqual({ x: 5, y: 6 })+ })++ it('clearLoop drops only the loop card overrides', () => {+ const s = useAgentNodes.getState()+ s.start('tu1', { parentNodeId: 'n1' })+ s.setPosition('tu1', { x: 1, y: 2 })+ s.setPosition('loop-n1', { x: 5, y: 6 })+ s.setSize('loop-n1', { width: 300, height: 200 })+ s.clearLoop('n1')+ const st = useAgentNodes.getState()+ expect(st.positions['loop-n1']).toBeUndefined()+ expect(st.sizes['loop-n1']).toBeUndefined()+ expect(st.positions['tu1']).toEqual({ x: 1, y: 2 })+ expect(st.byId['tu1']).toBeDefined()+ })+})+describe('useAgentNodes.finish', () => {beforeEach(() => {useAgentNodes.setState({ byId: {}, activityById: {}, positions: {}, sizes: {}, expanded: {} })diff --git a/src/renderer/state/agentNodes.ts b/src/renderer/state/agentNodes.tsindex 154e139ae..a9a7d7939 100644--- a/src/renderer/state/agentNodes.ts+++ b/src/renderer/state/agentNodes.ts@@ -52,6 +52,12 @@ interface AgentNodesState {appendActivity(toolUseId: string, chunk: string): void/** Remove all subagents spawned by a given parent node (turn/session ended, or node closed). */clearForParent(parentNodeId: string): void+ /**+ * Drop the loop card's UI overrides (position/size/expanded) for a parent. Separate from+ * clearForParent on purpose: a loop/cron card outlives turns, so the per-turn fan-out+ * clear must not reset where the user dragged it — this runs only when the loop ends.+ */+ clearLoop(parentNodeId: string): void}export const useAgentNodes = create<AgentNodesState>((set) => ({@@ -95,16 +101,28 @@ export const useAgentNodes = create<AgentNodesState>((set) => ({const positions = { ...s.positions }const sizes = { ...s.sizes }const expanded = { ...s.expanded }- const drop = [...ids, `loop-${parentNodeId}`]+ // Loop-card overrides (`loop-<pid>`) are deliberately NOT dropped here — the card+ // outlives turns; its overrides go via clearLoop when the loop itself ends.for (const id of ids) {delete byId[id]delete activityById[id]- }- for (const id of drop) {delete positions[id]delete sizes[id]delete expanded[id]}return { byId, activityById, positions, sizes, expanded }+ }),++ clearLoop: (parentNodeId) =>+ set((s) => {+ const id = `loop-${parentNodeId}`+ if (!(id in s.positions) && !(id in s.sizes) && !(id in s.expanded)) return s+ const positions = { ...s.positions }+ const sizes = { ...s.sizes }+ const expanded = { ...s.expanded }+ delete positions[id]+ delete sizes[id]+ delete expanded[id]+ return { positions, sizes, expanded }})}))diff --git a/src/renderer/state/agentStatus.persist.test.ts b/src/renderer/state/agentStatus.persist.test.tsnew file mode 100644index 000000000..997f6bb8e--- /dev/null+++ b/src/renderer/state/agentStatus.persist.test.ts@@ -0,0 +1,60 @@+import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'++// The store binds localStorage at import time, so each test stubs a fresh in-memory+// storage and re-imports the module (vi.resetModules) to exercise load()/save().+function memStorage(seed: Record<string, string> = {}): Storage {+ const m = new Map(Object.entries(seed))+ return {+ getItem: (k: string) => m.get(k) ?? null,+ setItem: (k: string, v: string) => void m.set(k, v),+ removeItem: (k: string) => void m.delete(k),+ clear: () => m.clear(),+ key: () => null,+ get length() {+ return m.size+ }+ } as Storage+}++beforeEach(() => vi.resetModules())+afterEach(() => vi.unstubAllGlobals())++describe('loop persistence (cron/schedule survive an app restart)', () => {+ it('persists an active loop to localStorage and drops it on setLoop(false)', async () => {+ const store = memStorage()+ vi.stubGlobal('localStorage', store)+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().setLoop('n1', true, 'cron', { schedule: '0 9 * * *', task: 'daily report' })+ let saved = JSON.parse(store.getItem('nodeterm.agentStatus')!)+ expect(saved.n1.loop).toMatchObject({ kind: 'cron', schedule: '0 9 * * *', task: 'daily report' })+ useAgentStatus.getState().setLoop('n1', false)+ saved = JSON.parse(store.getItem('nodeterm.agentStatus') ?? '{}')+ expect(saved.n1?.loop).toBeUndefined()+ })++ it('restores a persisted cron loop on load', async () => {+ vi.stubGlobal(+ 'localStorage',+ memStorage({+ 'nodeterm.agentStatus': JSON.stringify({+ n2: { unread: false, loop: { count: 3, kind: 'cron', schedule: '*/5 * * * *', task: 't', items: [] } }+ })+ })+ )+ const { useAgentStatus } = await import('./agentStatus')+ expect(useAgentStatus.getState().byId['n2']?.loop).toMatchObject({+ kind: 'cron',+ schedule: '*/5 * * * *'+ })+ })++ it('tolerates a persisted entry without loop (older format)', async () => {+ vi.stubGlobal(+ 'localStorage',+ memStorage({ 'nodeterm.agentStatus': JSON.stringify({ n3: { unread: true, sessionId: 's' } }) })+ )+ const { useAgentStatus } = await import('./agentStatus')+ expect(useAgentStatus.getState().byId['n3']).toMatchObject({ unread: true, sessionId: 's' })+ expect(useAgentStatus.getState().byId['n3'].loop).toBeUndefined()+ })+})diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.tsindex 5720803fa..dd6880296 100644--- a/src/renderer/state/agentStatus.ts+++ b/src/renderer/state/agentStatus.ts@@ -96,6 +96,17 @@ function load(): Record<string, AgentNodeStatus> {const out: Record<string, AgentNodeStatus> = {}for (const [id, v] of Object.entries(data)) {out[id] = { unread: !!v.unread, session: v.session, sessionId: v.sessionId }+ // A recurring job (cron/schedule — and tmux keeps in-session loops alive too) outlives+ // the app: restore its card. Minimal shape check so a corrupt entry can't break load.+ if (v.loop && typeof v.loop === 'object' && v.loop.kind) {+ out[id].loop = {+ count: v.loop.count ?? 0,+ kind: v.loop.kind,+ schedule: v.loop.schedule,+ task: v.loop.task,+ items: Array.isArray(v.loop.items) ? v.loop.items : []+ }+ }}return out} catch {@@ -108,8 +119,8 @@ function save(byId: Record<string, AgentNodeStatus>): void {try {const out: Record<string, Partial<AgentNodeStatus>> = {}for (const [id, v] of Object.entries(byId)) {- if (v.unread || v.session || v.sessionId) {- out[id] = { unread: v.unread, session: v.session, sessionId: v.sessionId }+ if (v.unread || v.session || v.sessionId || v.loop) {+ out[id] = { unread: v.unread, session: v.session, sessionId: v.sessionId, loop: v.loop }}}localStorage.setItem(KEY, JSON.stringify(out))@@ -207,16 +218,19 @@ export const useAgentStatus = create<AgentStatusStore>((set) => ({setLoop: (id, active, kind = 'loop', opts) =>set((s) => {const prev = s.byId[id] ?? EMPTY- if (active)- return {- byId: {- ...s.byId,- [id]: { ...prev, loop: { count: 0, kind, schedule: opts?.schedule, task: opts?.task, items: [] } }- }+ if (active) {+ const byId = {+ ...s.byId,+ [id]: { ...prev, loop: { count: 0, kind, schedule: opts?.schedule, task: opts?.task, items: [] } }}+ save(byId)+ return { byId }+ }if (!prev.loop) return sconst { loop: _drop, ...rest } = prev- return { byId: { ...s.byId, [id]: rest } }+ const byId = { ...s.byId, [id]: rest }+ save(byId)+ return { byId }}),bumpLoop: (id, message) =>@@ -227,9 +241,12 @@ export const useAgentStatus = create<AgentStatusStore>((set) => ({const items = message? [...prev.loop.items, message.trim().slice(0, 4000)].slice(-100): prev.loop.items- return {- byId: { ...s.byId, [id]: { ...prev, loop: { ...prev.loop, count: prev.loop.count + 1, items } } }+ const byId = {+ ...s.byId,+ [id]: { ...prev, loop: { ...prev.loop, count: prev.loop.count + 1, items } }}+ save(byId)+ return { byId }}),remove: (id) =>diff --git a/src/renderer/state/projects.sessions.test.ts b/src/renderer/state/projects.sessions.test.tsindex e4a3171f7..dd4bf80c3 100644--- a/src/renderer/state/projects.sessions.test.ts+++ b/src/renderer/state/projects.sessions.test.ts@@ -155,3 +155,23 @@ describe('reorderNode', () => {expect(useProjects.getState().getProject('p1')!.nodes).toBe(before)})})++describe('control ropes persistence', () => {+ // Visual "spawned by" ropes (agent CLI → new node) persist like bridges: committed with+ // the canvas and carried into the workspace written to disk.+ it('commitCanvas stores ropes and toWorkspace carries them', () => {+ useProjects+ .getState()+ .commitCanvas(+ 'p1',+ [mkNode('n1')],+ { x: 0, y: 0, zoom: 1 },+ [{ id: 'b1', source: 'n1', target: 'n2' }],+ [{ id: 'ctrl-n1-n2', source: 'n1', target: 'n2' }]+ )+ const p = useProjects.getState().projects[0]+ expect(p.bridges).toEqual([{ id: 'b1', source: 'n1', target: 'n2' }])+ expect(p.ropes).toEqual([{ id: 'ctrl-n1-n2', source: 'n1', target: 'n2' }])+ expect(useProjects.getState().toWorkspace().projects[0].ropes).toHaveLength(1)+ })+})diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.tsindex cec070280..6e914258d 100644--- a/src/renderer/state/projects.ts+++ b/src/renderer/state/projects.ts@@ -16,8 +16,14 @@ interface ProjectsState {setProjectCwd(id: string, cwd: string): void/** Sets (or clears, with undefined) the project's default Claude account for new nodes. */setProjectDefaultAccount(id: string, accountId: string | undefined): void- /** Writes the serialized canvas (nodes + viewport + bridge links) back into a project. */- commitCanvas(id: string, nodes: CanvasNodeState[], viewport: Viewport, bridges?: BridgeLink[]): void+ /** Writes the serialized canvas (nodes + viewport + bridge links + control ropes) back into a project. */+ commitCanvas(+ id: string,+ nodes: CanvasNodeState[],+ viewport: Viewport,+ bridges?: BridgeLink[],+ ropes?: BridgeLink[]+ ): void/** Renames a node within a project (source of truth for inactive projects). */renameNode(projectId: string, nodeId: string, title: string): void/** Recolors a node within a project. */@@ -115,10 +121,12 @@ export const useProjects = create<ProjectsState>((set, get) => ({}))},- commitCanvas(id, nodes, viewport, bridges) {+ commitCanvas(id, nodes, viewport, bridges, ropes) {set((s) => ({projects: s.projects.map((p) =>- p.id === id ? { ...p, nodes, viewport, ...(bridges ? { bridges } : {}) } : p+ p.id === id+ ? { ...p, nodes, viewport, ...(bridges ? { bridges } : {}), ...(ropes ? { ropes } : {}) }+ : p)}))},diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.tsindex 0095f8d7f..6dffd91b1 100644--- a/src/renderer/state/workspace.test.ts+++ b/src/renderer/state/workspace.test.ts@@ -5,10 +5,12 @@ import {createChatNode,createDinoNode,flowToNodeStates,+ groupSelectedNodes,nodeStatesToFlow,reorderNodeBefore,reparentNode,- resolveNewNodeAccount+ resolveNewNodeAccount,+ ungroupNodes} from './workspace'import type { CanvasNode } from './workspace'@@ -70,6 +72,60 @@ describe('reparentNode', () => {})})+describe('groupSelectedNodes', () => {+ it('wraps the selection in a group frame with group-relative child positions', () => {+ const nodes = [term('t1', { x: 100, y: 100 }), term('t2', { x: 500, y: 300 })]+ const out = groupSelectedNodes(nodes, ['t1', 't2'], 0)+ const group = out[0]+ expect(group.type).toBe('group') // parent placed first (React Flow requirement)+ const t1 = out.find((n) => n.id === 't1')!+ expect(t1.parentId).toBe(group.id)+ expect(t1.extent).toBe('parent')+ // absolute position preserved: group position + relative child position+ expect(group.position.x + t1.position.x).toBe(100)+ expect(group.position.y + t1.position.y).toBe(100)+ // frame encloses both members (t2 spans to x=820, y=540)+ expect(group.position.x + (group.width as number)).toBeGreaterThanOrEqual(820)+ expect(group.position.y + (group.height as number)).toBeGreaterThanOrEqual(540)+ })++ it('groups a single node', () => {+ const out = groupSelectedNodes([term('t1', { x: 100, y: 100 })], ['t1'], 0)+ expect(out[0].type).toBe('group')+ expect(out.find((n) => n.id === 't1')!.parentId).toBe(out[0].id)+ })++ it('skips already-grouped children and group frames; all-skipped is a no-op', () => {+ const nodes = [grp('g1', { x: 0, y: 0 }), term('t1', { x: 10, y: 10 }, 'g1')]+ expect(groupSelectedNodes(nodes, ['g1', 't1'], 1)).toBe(nodes)+ })+})++describe('ungroupNodes', () => {+ it('removes the frame and restores children to absolute positions', () => {+ const nodes = [grp('g1', { x: 50, y: 50 }), term('t1', { x: 10, y: 10 }, 'g1')]+ const out = ungroupNodes(nodes, 'g1')+ expect(out.find((n) => n.id === 'g1')).toBeUndefined()+ const t1 = out.find((n) => n.id === 't1')!+ expect(t1.parentId).toBeUndefined()+ expect(t1.extent).toBeUndefined()+ expect(t1.position).toEqual({ x: 60, y: 60 })+ })++ it('round-trips with groupSelectedNodes', () => {+ const nodes = [term('t1', { x: 100, y: 100 }), term('t2', { x: 500, y: 300 })]+ const grouped = groupSelectedNodes(nodes, ['t1', 't2'], 0)+ const out = ungroupNodes(grouped, grouped[0].id)+ expect(out.find((n) => n.id === 't1')!.position).toEqual({ x: 100, y: 100 })+ expect(out.find((n) => n.id === 't2')!.position).toEqual({ x: 500, y: 300 })+ })++ it('is a no-op when the group is missing', () => {+ const nodes = [term('t1', { x: 0, y: 0 })]+ expect(ungroupNodes(nodes, 'nope')).toBe(nodes)+ })+})+describe('reorderNodeBefore', () => {const ids = (out: CanvasNode[]): string[] => out.filter((n) => n.type !== 'group').map((n) => n.id)diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex e1c227a20..49b8cbbc9 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -3775,6 +3775,33 @@ body,background: rgba(191, 122, 240, 0.32);}+/* Dismiss the card (job itself is untouched). Sits at the right edge; when Play is present+ it follows Play with a small gap instead of both auto-margins splitting the space. */+.loop-node__close {+ margin-left: auto;+ flex: none;+ width: 22px;+ height: 22px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ background: transparent;+ border: 1px solid var(--border);+ border-radius: 6px;+ color: var(--muted);+ font-size: 13px;+ cursor: pointer;+}++.loop-node__play + .loop-node__close {+ margin-left: 6px;+}++.loop-node__close:hover {+ background: rgba(255, 255, 255, 0.08);+ color: var(--text);+}+.loop-node__task {margin-top: 6px;color: var(--muted);diff --git a/src/shared/agents/normalize.test.ts b/src/shared/agents/normalize.test.tsindex b687635a6..296e6d7a0 100644--- a/src/shared/agents/normalize.test.ts+++ b/src/shared/agents/normalize.test.ts@@ -74,6 +74,32 @@ describe('normalizeClaude — async subagents', () => {})})+describe('normalizeClaude — recurring (cron/schedule/loop)', () => {+ it('CronCreate PreToolUse → recurring cron with schedule + task', () => {+ const e = normalizeClaude(+ env({+ hook_event_name: 'PreToolUse',+ tool_name: 'CronCreate',+ tool_input: { cron: '0 9 * * *', prompt: 'daily report' }+ })+ )+ expect(e).toMatchObject({+ kind: 'recurring',+ recurringKind: 'cron',+ schedule: '0 9 * * *',+ task: 'daily report'+ })+ expect(e?.recurringEnd).toBeFalsy()+ })++ // A cron outlives turns and sessions — its card should only leave the canvas when the+ // cron itself is removed. CronDelete is that signal.+ it('CronDelete PreToolUse → recurring END (clears the cron card)', () => {+ const e = normalizeClaude(env({ hook_event_name: 'PreToolUse', tool_name: 'CronDelete' }))+ expect(e).toMatchObject({ kind: 'recurring', recurringEnd: true })+ })+})+describe('normalizeClaude — permission signals', () => {it('PermissionRequest → blocked', () => {const e = normalizeClaude(env({ hook_event_name: 'PermissionRequest' }))diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex ab0b5b405..35eba9105 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -31,6 +31,8 @@ export interface NormalizedAgentEvent {result?: string// recurringrecurringKind?: 'loop' | 'schedule' | 'cron'+ /** The recurring job was REMOVED (e.g. CronDelete) — take the card down. */+ recurringEnd?: booleantask?: stringschedule?: string}@@ -114,6 +116,11 @@ export function normalizeClaude(env: RawHookEnvelope): NormalizedAgentEvent | nu.join('\n')}}+ // A cron outlives turns and sessions — its card leaves the canvas only when the cron+ // itself is removed.+ if (ev === 'PreToolUse' && tool === 'CronDelete') {+ return { ...base, kind: 'recurring', recurringKind: 'cron', recurringEnd: true }+ }if (ev === 'PreToolUse' && RECURRING_TOOLS.has(tool)) {let recurringKind: NormalizedAgentEvent['recurringKind']if (tool === 'Skill') {diff --git a/src/shared/types.ts b/src/shared/types.tsindex 44af6cb81..a44aad2f0 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -149,6 +149,12 @@ export interface Project {defaultAccountId?: string/** Bridge links between Claude nodes (optional; absent in pre-bridge files). */bridges?: BridgeLink[]+ /**+ * Visual "spawned by" ropes (control-capable agent → node it opened via the `nodeterm` CLI,+ * or browser popup → its opener). Display-only — never context links — but persisted so the+ * lineage survives restarts; deletable like any selected edge.+ */+ ropes?: BridgeLink[]/*** Closed projects are hidden from the tab bar but kept on disk with all their nodes (and their* tmux sessions left running) so they can be reopened from the start screen's "Recently closed"