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-control): dependency edges — `--after` arms a node until its upstream is done
enesd9fea6e2ee69
diff --git a/src/main/canvas-control-core.ts b/src/main/canvas-control-core.tsindex 6732066b0..01667e4c2 100644--- a/src/main/canvas-control-core.ts+++ b/src/main/canvas-control-core.ts@@ -125,11 +125,15 @@ export function buildCanvasControlInstructions(shimPath: string): string {'','Verbs:','- `list` — current nodes (id, kind, title). Start here when you need a node id.',- '- `open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>]` — open N plain terminals.',- '- `open-claude [--count N] [--cwd P] [--prompt T] [--group <id>]` — open N Claude sessions.',- '- `open-agent --agent claude|codex|gemini|opencode|<custom-id> [--count N] [--cwd P] [--prompt T] [--group <id>]` — open',+ '- `open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>]` — open N plain terminals.',+ '- `open-claude [--count N] [--cwd P] [--prompt T] [--group <id>] [--after <id,id>]` — open N Claude sessions.',+ '- `open-agent --agent claude|codex|gemini|opencode|<custom-id> [--count N] [--cwd P] [--prompt T] [--group <id>] [--after <id,id>]` — open',' any agent CLI. `--group` parents the node(s) into a group frame; a worktree-bound group also',- ' hands its worktree path down as the cwd.',+ ' hands its worktree path down as the cwd. `--after <id,id>` opens the node ARMED: it does not',+ ' start until every listed station has gone idle, and is context-linked to them so it can read',+ ' their work when it wakes — use it for "B needs what A produced" instead of polling. Only',+ ' status-reporting agent nodes (claude/codex/gemini) may be waited on; a plain terminal never',+ ' reports finishing, so waiting on one is refused.','- `show-image <path>` / `show-video <path>` — open a media file as a node.','- `show-web (--url U | --file P.html | --html "<...>")` — open a web viewer.','- `open-browser --url U` — open a navigable browser node.',@@ -152,8 +156,9 @@ export function buildCanvasControlInstructions(shimPath: string): string {'','Orchestration ("Build with Nodeterm orchestration"): first decide what is genuinely','independent — for every "and then", ask whether the next step READS the previous step\'s',- 'output. If not, they are separate stations; if it does, sequence it yourself, because a',- 'station cannot wait for another one. Then break the task into 2-5 independent workstreams;',+ 'output. If not, they are separate stations, open them all at once; if it does, open the',+ 'downstream one with `--after <upstream-id>` and it starts itself when the upstream goes',+ 'idle (do not poll for that yourself). Then break the task into 2-5 workstreams;','per stream `open-worktree --branch <slug>` then `open-agent --agent claude --group <groupId>','--prompt "<concrete task>"` (each stream on its own branch, no tree conflicts). Members land','in grid slots inside the frame automatically; align the frames themselves with',@@ -277,11 +282,19 @@ sh "${shimPath}" <verb> [args]Verbs:- \`list\` — list current nodes (id, kind, title). Start here when you need a node id.-- \`open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>]\` — open N plain terminals (default 1).-- \`open-claude [--count N] [--cwd P] [--prompt T] [--group <id>]\` — open N Claude sessions (default 1).-- \`open-agent --agent claude|codex|gemini|opencode|<custom-id> [--count N] [--cwd P] [--prompt T] [--group <id>]\` — open N sessions of any agent CLI.+- \`open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>]\` — open N plain terminals (default 1).+- \`open-claude [--count N] [--cwd P] [--prompt T] [--group <id>] [--after <id,id>]\` — open N Claude sessions (default 1).+- \`open-agent --agent claude|codex|gemini|opencode|<custom-id> [--count N] [--cwd P] [--prompt T] [--group <id>] [--after <id,id>]\` — open N sessions of any agent CLI.\`--group\` parents the node(s) into an existing group frame; a worktree-bound group alsohands its worktree path down as the cwd.+ \`--after <id,id>\` opens the node **armed**: it does NOT start yet, and launches itself once+ every listed station has gone idle — that is how you express "B needs what A produces" without+ sitting in a poll loop. The armed node is also context-linked to each station it waits on, so+ it can read their work the moment it wakes. Only agent nodes that report status+ (claude/codex/gemini) can be waited on — waiting on a plain terminal is refused, because a+ plain terminal never reports finishing and the node would hang forever. Note the semantics:+ "idle" is the end of a station's TURN, not proof its whole job is done — right for a station+ given one self-contained prompt, wrong if you expect a long conversation first.- \`show-image <path>\` — open an image file as a node.- \`show-video <path>\` — open a video file as a player node.- \`show-web (--url U | --file P.html | --html "<...>")\` — open a web viewer (live URL or local HTML you wrote).@@ -332,10 +345,10 @@ across Nodeterm sessions), be the orchestration chef — plan the kitchen, then0. First decide what is actually independent. For every "and then" in your plan, ask: doesthe next step READ the previous step's output? If it does not, there is no dependency and- the wait is wasted — those steps are separate stations. If it does, do NOT open them as- parallel stations: a station cannot wait for another one. Either sequence them yourself- (open the downstream station once the upstream is done and you have read its result), or- keep the dependent part in your own session. Fan out breadth; keep chains to yourself.+ the wait is wasted — those steps are separate stations, open them all at once. If it does,+ the dependency is real: open the downstream station with \`--after <upstream-id>\` and it+ will start itself when the upstream goes idle. Do not fake this by polling in your own+ session; that is what \`--after\` exists to replace.1. Break the task into 2–5 independent workstreams (by subsystem, not by file).2. Per workstream, give it its own branch + kitchen station:\`open-worktree --branch <slug>\` → note the returned \`groupId\`, thendiff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 2aaee5af0..3e72fdd9a 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -178,6 +178,7 @@ import {type RelayTab,} from '../session/relay-tab'import { buildBackgroundLinkMaps, buildContextLinkNote, buildLinkMap, buildNotePushMessage, classifyLink, planBridges, type LinkEndpoint } from '../lib/noteLink'+import { dependencyEdges, launchesToFire, unmetDeps, type ArmedNode } from '../lib/pendingLaunch'import { useSettings } from '../state/settings'import { activePermissionMode } from '../state/permissionMode'import { useContextWindow } from '../state/contextWindow'@@ -333,6 +334,12 @@ const NO_EPHEMERAL: { ephemeralNodes: CanvasNode[]; ephemeralEdges: Edge[] } = {ephemeralEdges: []}+// 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.+const LAUNCH_DELIVERY_ATTEMPTS = 5+const LAUNCH_RETRY_MS = 400+// 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.@@ -835,6 +842,63 @@ export function Canvas() {}return sig})+ // The states this canvas is actually WAITING on — armed nodes' deps only. Same discipline as+ // loopSig: subscribing to the whole byId map would re-render the canvas on every hook event+ // of every node. Reads nodesRef (assigned during render) so it stays current without adding+ // `nodes` to a store selector.+ const armedDepSig = useAgentStatus((s) => {+ let sig = ''+ for (const n of nodesRef.current) {+ const p = n.data.pendingLaunch+ if (!p) continue+ sig += `${n.id}:`+ for (const d of p.after) sig += `${d}=${s.byId[d]?.state ?? ''},`+ sig += '|'+ }+ return sig+ })+ // Bumped to re-run the launch effect after a refused delivery (see LAUNCH_RETRY_MS).+ const [launchRetry, setLaunchRetry] = useState(0)+ // Ids whose held launch has been handed to the pty. An id stays here FOREVER once delivery+ // succeeded — clearing `pendingLaunch` is a state update that can lag a re-render, and this+ // action is irreversible, so the set (not the node data) is what guarantees exactly-once.+ const launchInFlight = useRef<Set<string>>(new Set())+ const launchAttempts = useRef<Map<string, number>>(new Map())+ // Fire armed nodes whose upstream stations have all gone idle. This is the edge that makes+ // the canvas a graph rather than a fan-out: the dependent starts itself, with no orchestrator+ // sitting in a poll loop burning context.+ useEffect(() => {+ const live = new Set(nodes.map((n) => n.id))+ const ready = launchesToFire(+ nodes as unknown as ArmedNode[],+ useAgentStatus.getState().byId,+ live+ ).filter((f) => !launchInFlight.current.has(f.id))+ for (const f of ready) {+ launchInFlight.current.add(f.id)+ const attempt = (launchAttempts.current.get(f.id) ?? 0) + 1+ launchAttempts.current.set(f.id, attempt)+ void api.pty.sendText(f.id, f.command).then((ok) => {+ if (ok) {+ setNodes((ns) =>+ ns.map((n) => (n.id === f.id ? { ...n, data: { ...n.data, pendingLaunch: undefined } } : n))+ )+ markDirty()+ return+ }+ // Refused: the node's tmux session is most likely still coming up. Let it back out of+ // flight and re-run shortly — a launch that silently vanishes is worse than a late one.+ launchInFlight.current.delete(f.id)+ if (attempt < LAUNCH_DELIVERY_ATTEMPTS) {+ setTimeout(() => setLaunchRetry((v) => v + 1), LAUNCH_RETRY_MS)+ } else {+ console.warn('[pending-launch] gave up delivering held launch for', f.id)+ }+ })+ }+ // 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>>({})const { ephemeralNodes, ephemeralEdges } = useMemo(() => {@@ -1012,9 +1076,30 @@ export function Canvas() {}: e)- const extra = ephemeralEdges.length || ropes.length ? [...ephemeralEdges, ...ropes] : []+ // Waiting edges for armed nodes (`--after`): dep → dependent, dashed and animated while the+ // wait is on. Derived from node data every time rather than persisted — a pending dependency+ // is a STATE that ends when the launch fires, unlike the context bridge `--after` also draws,+ // which is a durable relation and stays.+ const deps = dependencyEdges(nodes as unknown as ArmedNode[], new Set(nodes.map((n) => n.id))).map(+ (e) => ({+ ...e,+ type: 'default' as const,+ animated: true,+ label: '⏳ waits for',+ labelStyle: { fill: '#8e8e93', fontSize: 11, fontWeight: 600 },+ labelBgStyle: { fill: '#1c1c1e', fillOpacity: 0.85 },+ labelBgPadding: [6, 3] as [number, number],+ labelBgBorderRadius: 5,+ style: { stroke: '#8e8e93', strokeWidth: 1.5, strokeDasharray: '6 4' },+ markerEnd: { type: MarkerType.ArrowClosed, color: '#8e8e93', width: 14, height: 14 }+ })+ )+ const extra =+ ephemeralEdges.length || ropes.length || deps.length+ ? [...ephemeralEdges, ...ropes, ...deps]+ : []return extra.length ? [...decorated, ...extra] : decorated- }, [linkEdges, ephemeralEdges, controlEdges, accent, stickySig])+ }, [linkEdges, ephemeralEdges, controlEdges, accent, stickySig, nodes])// Header pin button (and ⌘⇧L): toggle the persisted pin preference. Clears the transient// dismiss so (re)pinning shows the docked panel; unpinning collapses it to hover-peek.@@ -4619,13 +4704,19 @@ export function Canvas() {// `lookup` defaults to the live canvas, but the open/spawn verbs pass their own: they// create and bridge nodes in the SAME tick, and setNodes is async — nodesRef has not// seen them yet, so resolving them off the canvas would skip every one as "no such node".+ // `drawn` accumulates across the calls ONE command makes (--after bridges each new node to+ // each dep after already bridging them to the opener): linkEdgesRef is a render-time ref,+ // so it cannot see edges added earlier in this same tick, and without the accumulator a+ // pair reachable twice would be added twice under two different ids.+ const drawn: { source: string; target: string }[] = []const bridgeTo = (fromId: string,targetIds: string[],lookup: (id: string) => LinkEndpoint | null = linkEndpointOf) => {- const plan = planBridges(fromId, targetIds, lookup, linkEdgesRef.current)+ const plan = planBridges(fromId, targetIds, lookup, [...linkEdgesRef.current, ...drawn])if (plan.edges.length) {+ drawn.push(...plan.edges)setLinkEdges((es) => [...es, ...plan.edges.map((e) => ({ ...e, type: 'default' }))])markDirty()}@@ -4673,6 +4764,56 @@ export function Canvas() {}return g.id}+ // Validate `--after` (open-terminal / open-claude / open-agent): the ids this node's+ // launch waits on. Only a node running a hook-REPORTING agent may be waited on — a plain+ // terminal never emits a done event, so waiting on one would stall the dependent forever.+ // Refusing here is the whole guardrail: `launchesToFire` cannot tell "will never report"+ // from "has not reported yet", and it must not, or a fan-out would fire every dependent+ // instantly. Returns the ids, or null with the error already replied.+ const resolveAfter = (): string[] | null | undefined => {+ if (!args.after) return undefined+ const ids = (args.after ?? '').split(',').map((s) => s.trim()).filter(Boolean)+ if (ids.length === 0) return undefined+ for (const depId of ids) {+ const dep = nodesRef.current.find((nd) => nd.id === depId)+ if (!dep) {+ reply({ ok: false, error: `${verb}: --after names no existing node (${depId})` })+ return null+ }+ const depAgent = agentIdOf(depId)+ if (!depAgent || !hasHooks(depAgent)) {+ reply({+ ok: false,+ error: `${verb}: --after ${depId} is not an agent session that reports when it is done — only claude/codex/gemini nodes can be waited on`+ })+ return null+ }+ }+ return ids+ }+ // Hold a freshly-built node's launch instead of running it on open. The factories already+ // composed the exact command (agent CLI + permission-mode flag + prompt, or --cmd), so it+ // is MOVED rather than rebuilt — a second construction site is how the two drift apart.+ const armAfter = (node: CanvasNode, after: string[]): CanvasNode => {+ const command = node.data.initialCommand as string | undefined+ if (!after.length || !command) return node+ // If the wait is ALREADY over, don't arm at all — leave the command as the node's+ // `initialCommand` so its own mount path delivers it through `writeWhenShellReady`+ // (which waits for the shell prompt and echo-verifies). Arming would instead hand+ // delivery to the canvas effect, which would race the node's PTY into existence and+ // could fire into a session that does not exist yet.+ const live = new Set(nodesRef.current.map((nd) => nd.id))+ const unmet = unmetDeps(+ { id: node.id, data: { pendingLaunch: { after, command } } },+ useAgentStatus.getState().byId,+ live+ )+ if (!unmet.length) return node+ return {+ ...node,+ data: { ...node.data, initialCommand: undefined, pendingLaunch: { after, command } }+ }+ }// Open `count` nodes INTO a group frame: grow the frame FIRST (extent:'parent' would// clamp children landing outside it), then drop each node into the next grid slot// after the existing children. Shared by the terminal and agent open verbs.@@ -4732,20 +4873,27 @@ export function Canvas() {const groupCwd = intoGroupId? worktreeControlRef.current.cwdForNewNodeIn(intoGroupId): undefined+ const after = resolveAfter()+ if (after === null) return // bad --after, already repliedconst make = (i: number): CanvasNode =>- createTerminalNode(- nodesRef.current.length + i,- args.cwd || groupCwd || srcCwd,- placeBelow(i),- args.cmd+ armAfter(+ createTerminalNode(+ nodesRef.current.length + i,+ args.cwd || groupCwd || srcCwd,+ placeBelow(i),+ args.cmd+ ),+ after ?? [])const ids = intoGroupId? addGrouped(intoGroupId, count, make): Array.from({ length: count }, (_, i) => addAndConnect(make(i)))reply({ok: true,- message: `opened ${count} terminal(s): ${ids.join(', ')}`,- result: { ids, id: ids[0] }+ message:+ `opened ${count} terminal(s): ${ids.join(', ')}` ++ (after?.length ? `\nwaiting for ${after.join(', ')} before running` : ''),+ result: { ids, id: ids[0], after: after ?? [] }})return}@@ -4771,16 +4919,21 @@ export function Canvas() {projStore.getProject(projStore.activeProjectId ?? ''),useSettings.getState().settings.claudeAccounts)+ const after = resolveAfter()+ if (after === null) return // bad --after, already repliedconst make = (i: number): CanvasNode =>- createAgentNode(- agentId,- nodesRef.current.length + i,- args.cwd || groupCwd || srcCwd,- placeBelow(i),- args.prompt,- undefined,- account,- activePermissionMode()+ armAfter(+ createAgentNode(+ agentId,+ nodesRef.current.length + i,+ args.cwd || groupCwd || srcCwd,+ placeBelow(i),+ args.prompt,+ undefined,+ account,+ activePermissionMode()+ ),+ after ?? [])const ids = intoGroupId? addGrouped(intoGroupId, count, make)@@ -4793,14 +4946,24 @@ export function Canvas() {? linkEndpointOf(id): ids.includes(id)? { kind: 'terminal', contextCapable: canContextLink(agentId) }- : null+ : linkEndpointOf(id)const bridged = bridgeTo(sourceNodeId, ids, openedEndpoint).linked+ // A dependency is also a READING relationship: the whole reason to wait for a+ // station is to consume what it produced. So `--after` additionally bridges each new+ // node to each dep — that link is durable and outlives the dashed waiting edge.+ const depLinked = (after ?? []).length+ ? ids.flatMap((nid) => bridgeTo(nid, after ?? [], openedEndpoint).linked)+ : []reply({ok: true,message:`opened ${count} ${agentId} session(s): ${ids.join(', ')}` +- (bridged.length ? `\ncontext-linked to you: ${bridged.join(', ')}` : ''),- result: { ids, linked: bridged }+ (bridged.length ? `\ncontext-linked to you: ${bridged.join(', ')}` : '') ++ (after?.length+ ? `\nwaiting for ${after.join(', ')} before running` ++ (depLinked.length ? ` (and linked to read them)` : '')+ : ''),+ result: { ids, linked: bridged, after: after ?? [] }})return}diff --git a/src/renderer/lib/pendingLaunch.test.ts b/src/renderer/lib/pendingLaunch.test.tsnew file mode 100644index 000000000..7966b2c66--- /dev/null+++ b/src/renderer/lib/pendingLaunch.test.ts@@ -0,0 +1,80 @@+import { describe, it, expect } from 'vitest'+import { dependencyEdges, launchesToFire, unmetDeps, type ArmedNode, type StatusById } from './pendingLaunch'++const armed = (id: string, after: string[], command = `echo ${id}`): ArmedNode => ({+ id,+ data: { pendingLaunch: { after, command } }+})+const plain = (id: string): ArmedNode => ({ id, data: {} })++describe('launchesToFire', () => {+ const live = new Set(['a', 'b', 'c'])++ it('fires when every dep has reported done', () => {+ const status: StatusById = { a: { state: 'done' }, b: { state: 'done' } }+ expect(launchesToFire([armed('c', ['a', 'b'])], status, live)).toEqual([+ { id: 'c', command: 'echo c' }+ ])+ })++ it('does NOT fire while a dep is still working', () => {+ const status: StatusById = { a: { state: 'done' }, b: { state: 'working' } }+ expect(launchesToFire([armed('c', ['a', 'b'])], status, live)).toEqual([])+ })++ it('does NOT fire on an unknown state — "no news" is not "finished"', () => {+ // The whole point: right after a fan-out the upstream stations have emitted nothing yet.+ expect(launchesToFire([armed('c', ['a'])], {}, live)).toEqual([])+ })++ it('treats waiting/blocked as not satisfied — the station still needs its user', () => {+ expect(launchesToFire([armed('c', ['a'])], { a: { state: 'waiting' } }, live)).toEqual([])+ expect(launchesToFire([armed('c', ['a'])], { a: { state: 'blocked' } }, live)).toEqual([])+ })++ it('treats a dep that is no longer on the canvas as satisfied', () => {+ // A deleted node can never report; waiting on it would strand the dependent forever.+ const status: StatusById = { a: { state: 'done' } }+ expect(launchesToFire([armed('c', ['a', 'ghost'])], status, new Set(['a', 'c']))).toEqual([+ { id: 'c', command: 'echo c' }+ ])+ })++ it('ignores nodes that are not armed, and armed nodes with an empty command', () => {+ const status: StatusById = { a: { state: 'done' } }+ expect(launchesToFire([plain('c'), armed('d', ['a'], '')], status, live)).toEqual([])+ })++ it('fires immediately when there are no deps left to wait on', () => {+ expect(launchesToFire([armed('c', [])], {}, live)).toEqual([{ id: 'c', command: 'echo c' }])+ })+})++describe('unmetDeps', () => {+ it('reports only the deps still outstanding', () => {+ const live = new Set(['a', 'b', 'c'])+ const status: StatusById = { a: { state: 'done' }, b: { state: 'working' } }+ expect(unmetDeps(armed('c', ['a', 'b']), status, live)).toEqual(['b'])+ })++ it('is empty for a node that is not armed', () => {+ expect(unmetDeps(plain('c'), {}, new Set(['c']))).toEqual([])+ })+})++describe('dependencyEdges', () => {+ it('draws one edge per live dep, pointing dep → dependent', () => {+ expect(dependencyEdges([armed('c', ['a', 'b'])], new Set(['a', 'b', 'c']))).toEqual([+ { id: 'dep-a-c', source: 'a', target: 'c' },+ { id: 'dep-b-c', source: 'b', target: 'c' }+ ])+ })++ it('draws nothing for a dep that is gone', () => {+ expect(dependencyEdges([armed('c', ['ghost'])], new Set(['c']))).toEqual([])+ })++ it('draws nothing once the node is no longer armed', () => {+ expect(dependencyEdges([plain('c')], new Set(['c']))).toEqual([])+ })+})diff --git a/src/renderer/lib/pendingLaunch.ts b/src/renderer/lib/pendingLaunch.tsnew file mode 100644index 000000000..936ffc10f--- /dev/null+++ b/src/renderer/lib/pendingLaunch.ts@@ -0,0 +1,100 @@+// Pure logic for ARMED terminal nodes — the canvas-control `--after` dependency edge. A node+// opened with `--after <ids>` holds its launch command (see PendingLaunch in @shared/types)+// until every station it waits on has gone idle; this module decides when that is, and which+// dependency edges to draw meanwhile. Kept free of React/store imports so the satisfaction+// matrix is unit-testable — Canvas.tsx only wraps these in an effect and a setState.+import type { AgentState } from '@shared/agents/normalize'+import type { PendingLaunch } from '@shared/types'++/** The subset of a canvas node this module reads. */+export interface ArmedNode {+ id: string+ data: { pendingLaunch?: PendingLaunch }+}++/** The subset of the agentStatus store this module reads. */+export type StatusById = Record<string, { state?: AgentState } | undefined>++export interface LaunchToFire {+ id: string+ command: string+}++/**+ * Is one dependency satisfied?+ *+ * `done` is the agent's busy→idle edge — the same signal that drives the completion badge and+ * notification. It means "this station has produced something and stopped", which is exactly+ * when a downstream station should start reading it. It does NOT mean "this station will never+ * run again": an agent that finishes turn 1 and awaits more input is also `done`. That is the+ * intended semantics for a station given one self-contained prompt, and it is documented as+ * such rather than being papered over with a turn counter that would guess differently.+ *+ * A dep that is no longer on the canvas counts as satisfied — a deleted node can never report,+ * so treating it as pending would strand the dependent forever. An UNKNOWN state (the dep+ * exists but has reported nothing yet) is deliberately NOT satisfied: right after a fan-out the+ * upstream stations have not emitted a hook event yet, and reading "no news" as "finished"+ * would fire every dependent immediately — the exact bug that makes a dependency edge useless.+ */+function depSatisfied(depId: string, status: StatusById, live: ReadonlySet<string>): boolean {+ if (!live.has(depId)) return true+ return status[depId]?.state === 'done'+}++/**+ * Which armed nodes are ready to launch, given the live canvas and the current agent states.+ * `live` is passed in (rather than derived from `nodes`) because the caller already holds the+ * full node list while `nodes` here may be pre-filtered.+ */+export function launchesToFire(+ nodes: readonly ArmedNode[],+ status: StatusById,+ live: ReadonlySet<string>+): LaunchToFire[] {+ const out: LaunchToFire[] = []+ for (const n of nodes) {+ const p = n.data.pendingLaunch+ if (!p || !p.command) continue+ if (p.after.every((d) => depSatisfied(d, status, live))) out.push({ id: n.id, command: p.command })+ }+ return out+}++/** The deps an armed node is still waiting on — what the node badge and tooltip report. */+export function unmetDeps(+ node: ArmedNode,+ status: StatusById,+ live: ReadonlySet<string>+): string[] {+ const p = node.data.pendingLaunch+ if (!p) return []+ return p.after.filter((d) => !depSatisfied(d, status, live))+}++export interface DependencyEdge {+ id: string+ source: string+ target: string+}++/**+ * The dashed dep→node edges to draw for everything still waiting. Derived from node data on+ * every render rather than persisted as edges: a pending dependency is a STATE, not a durable+ * relation, and it disappears when the launch fires. (The durable relation `--after` also+ * creates is an ordinary context bridge, so the downstream node can still read its upstream+ * long after the arrow is gone.)+ */+export function dependencyEdges(+ nodes: readonly ArmedNode[],+ live: ReadonlySet<string>+): DependencyEdge[] {+ const out: DependencyEdge[] = []+ for (const n of nodes) {+ for (const dep of n.data.pendingLaunch?.after ?? []) {+ // A dep that is gone draws nothing — it is already satisfied, and an edge to a node that+ // isn't there would be dropped by React Flow anyway.+ if (live.has(dep)) out.push({ id: `dep-${dep}-${n.id}`, source: dep, target: n.id })+ }+ }+ return out+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 70bccbec0..4ddb91a03 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -25,7 +25,7 @@ import {makeDirListingLookup} from '../terminal/file-links'import { sshFs } from '../terminal/ssh-fs'-import type { FsApi } from '@shared/types'+import type { FsApi, PendingLaunch } from '@shared/types'import {attachReplay,closedByLabel,@@ -444,6 +444,13 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN!remoteSession &&(data.cwd as string | undefined) !== parentWtPathconst status = useAgentStatus((s) => s.byId[id])+ // Held launch (canvas-control `--after`). Canvas owns firing it; the node only surfaces that+ // it is armed, and by WHAT it is blocked — dep titles read straight off the live canvas, since+ // "waits for term-17" tells the user nothing.+ const pendingLaunch = data.pendingLaunch as PendingLaunch | undefined+ const pendingWaitingOn = (pendingLaunch?.after ?? [])+ .map((depId) => ((getNode(depId) as CanvasNode | undefined)?.data.title as string) || depId)+ .join(', ')// Use the chat panel only for a chat-capable agent with a known session; otherwise the// markdown-of-output view (computed in the capture effect below) is shown as a fallback.const useChat = mdMode && showChat && !!status?.sessionId@@ -1689,6 +1696,31 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN{status.loop.count > 0 ? ` ×${status.loop.count}` : ''}</span>)}+ {/* Armed by canvas-control `--after`: this node holds its launch until the stations it+ waits on go idle. Shown because an armed node is otherwise indistinguishable from one+ that simply failed to start — and it carries the manual escape, because agent state is+ transient: after an app restart nothing will ever report `done` again, so without a+ "run now" an armed node left over from before the restart would be a dead end. */}+ {pendingLaunch && (+ <span+ className="term-node__status term-node__status--queued nodrag"+ title={`Waiting for ${pendingWaitingOn} to finish, then runs:\n${pendingLaunch.command}`}+ >+ <span className="term-node__status-dot" />+ QUEUED+ <button+ className="term-node__queued-run"+ title="Run now without waiting"+ onClick={(e) => {+ e.stopPropagation()+ void api.pty.sendText(id, pendingLaunch.command)+ updateNodeData(id, { pendingLaunch: undefined })+ }}+ >+ ▶+ </button>+ </span>+ )}{(status?.state === 'waiting' || status?.state === 'blocked') && (<spanclassName="term-node__status term-node__status--attention"diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.tsindex 1a9464b48..614b4fe52 100644--- a/src/renderer/state/workspace.test.ts+++ b/src/renderer/state/workspace.test.ts@@ -254,6 +254,45 @@ describe('accountId serialization', () => {})})+describe('pendingLaunch round-trip', () => {+ // Unlike initialCommand (one-shot, deliberately NOT persisted), an armed node's held launch+ // must survive a reload — the station it waits on can take hours, and a restart in between+ // must not silently turn the node into an idle shell that never runs anything.+ it('persists the held launch and its dependencies', () => {+ const node = {+ id: 'term-3',+ type: 'terminal',+ position: { x: 0, y: 0 },+ width: 600,+ height: 400,+ data: {+ title: 'T',+ color: '#888',+ group: null,+ agentId: 'claude',+ pendingLaunch: { after: ['term-1', 'term-2'], command: 'claude "go"' }+ }+ } as unknown as CanvasNode+ const states = flowToNodeStates([node])+ expect(states[0].pendingLaunch).toEqual({ after: ['term-1', 'term-2'], command: 'claude "go"' })+ expect(nodeStatesToFlow(states)[0].data.pendingLaunch).toEqual({+ after: ['term-1', 'term-2'],+ command: 'claude "go"'+ })+ })++ it('stays undefined for an ordinary node', () => {+ const node = {+ id: 'term-4', type: 'terminal', position: { x: 0, y: 0 }, width: 1, height: 1,+ data: { title: 'T', color: '#888', group: null, initialCommand: 'claude' }+ } as unknown as CanvasNode+ const states = flowToNodeStates([node])+ expect(states[0].pendingLaunch).toBeUndefined()+ // initialCommand is still not persisted — arming is what makes a launch durable.+ expect((states[0] as { initialCommand?: string }).initialCommand).toBeUndefined()+ })+})+describe('createAccountLoginNode', () => {it('produces a terminal node that logs the given account in', () => {const node = createAccountLoginNode('acct-1', 0)diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 4b36175eb..690ac62d4 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -1,5 +1,5 @@import type { Node } from '@xyflow/react'-import type { CanvasMutation, CanvasNodeState, ClaudeAccount, NodeKind, Project } from '@shared/types'+import type { CanvasMutation, CanvasNodeState, ClaudeAccount, NodeKind, PendingLaunch, Project } from '@shared/types'import type { AgentId, AgentPermissionMode } from '@shared/agents/config'import { agentConfig, withPermissionMode } from '@shared/agents/config'import { sshHostKey } from '@shared/ssh'@@ -56,6 +56,12 @@ export interface NodeData {expandedHeight?: number/** One-shot command run once when the terminal first opens (not persisted). */initialCommand?: string+ /**+ * Terminal nodes armed with canvas-control's `--after`: the launch is held until every node+ * in `after` reports idle. Unlike `initialCommand` this IS persisted — the wait is durable+ * state, not a one-shot open event. Cleared the moment it fires.+ */+ pendingLaunch?: PendingLaunch/*** Transient respawn trigger: bumping this number tears down a terminal node's session and* recreates it (used to move an existing terminal into a worktree cwd). Not persisted —@@ -939,6 +945,7 @@ export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {highScore: n.highScore,agentId,accountId: n.accountId,+ pendingLaunch: n.pendingLaunch,ssh: n.ssh,sshRemoteTmux: n.sshRemoteTmux,sshFs: n.sshFs,@@ -1001,6 +1008,7 @@ export function flowToNodeStates(nodes: CanvasNode[]): CanvasNodeState[] {highScore: n.data.highScore,agentId: n.data.agentId,accountId: n.data.accountId,+ pendingLaunch: n.data.pendingLaunch,ssh: n.data.ssh,sshRemoteTmux: n.data.sshRemoteTmux,sshFs: n.data.sshFs,diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 75c67d63a..f1ca3eb90 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -1205,6 +1205,30 @@ body,color: var(--accent);}+/* QUEUED: a node armed with canvas-control `--after`, holding its launch until the stations it+ waits on go idle. Grey — it is not an alert, it is "not started yet". */+.term-node__status--queued {+ color: #8e8e93;+ gap: 4px;+}++.term-node__queued-run {+ background: none;+ border: none;+ padding: 0 2px;+ margin-left: 2px;+ color: inherit;+ cursor: pointer;+ font-size: 10px;+ line-height: 1;+ opacity: 0.7;+}++.term-node__queued-run:hover {+ opacity: 1;+ color: var(--accent);+}+/* Deterministic hook-reply approvals: compact Approve/Deny buttons beside the NEEDS YOU badge. */.term-node__approve {display: inline-flex;diff --git a/src/shared/types.ts b/src/shared/types.tsindex baeff70ba..68a623541 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -94,6 +94,28 @@ export interface RecycledInfo {export type NodeKind = 'terminal' | 'sticky' | 'group' | 'editor' | 'diff' | 'video' | 'web' | 'browser' | 'subagent' | 'loop' | 'dino'/** Persisted state of a single canvas node (terminal, sticky note, group frame, or editor). */+/**+ * A launch a terminal node OWES once every station in `after` has gone idle — what the+ * canvas-control `--after` flag arms instead of running the command on open. This is the+ * difference between a fan-out and a graph: a downstream station starts when the upstream+ * ones have produced something for it to read, without an orchestrator sitting in a poll loop.+ *+ * Persisted, because the wait can outlive an app restart — and note that agent state is NOT+ * (it is rebuilt from live hook events), so after a restart an armed node has no way to learn+ * that its deps already finished. That is why the node carries a manual "run now" escape:+ * a stalled station must never be a dead end.+ */+export interface PendingLaunch {+ /**+ * Node ids to wait for. Only nodes running a hook-reporting agent may appear here — a plain+ * terminal never reports `done`, so waiting on one would stall forever (refused at creation).+ * A dep that no longer exists counts as satisfied: a deleted node can never report.+ */+ after: string[]+ /** Delivered to the node's shell once the wait is over (agent CLI + prompt, or a plain command). */+ command: string+}+export interface CanvasNodeState {id: stringkind: NodeKind@@ -119,6 +141,8 @@ export interface CanvasNodeState {cwd?: string/** Which agent runs in this terminal node (claude/codex/gemini/custom). */agentId?: AgentId+ /** Set while this node is armed but not yet launched — see PendingLaunch. */+ pendingLaunch?: PendingLaunch/*** Claude-only: managed account this node runs on (CLAUDE_CONFIG_DIR injection).* Resolved once at node creation (explicit pick → project default → system default)