Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(canvas-control): open verbs no longer yank the screen to another project
enese592f4afeb42
diff --git a/CLAUDE.md b/CLAUDE.mdindex 9ec130c8b..5a20fd508 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1733,6 +1733,37 @@ else, and its context links must keep classifying across restarts).**A new verb must not DEPEND on the fix**: the shim is rewritten locally every app boot but ontoan SSH host only inside `RemoteHooks.setup()` (on connect), so an already-connected project keepsthe old loop with no signal on the wire. Give every flag a value and both loops agree.+ **WHICH CANVAS ANSWERS, and why an open never moves the camera** (`renderer/lib/controlRouting.ts`+ + `renderer/lib/coldOpen.ts`). React Flow holds only the ACTIVE project's nodes, but every other+ open project's tmux sessions keep running, so a control call routinely arrives from a node the+ live canvas has never heard of. `routeControlSource` resolves the OWNING project+ (`active | switch | reopen | blocked | unknown`) — before that, every agent outside the project+ the app happened to come up on was rejected as *"source node is not a control-capable agent"*,+ which is a capability sentence for a routing failure. **That fix must not regress.** What it+ originally did with the answer was TRAVEL there (`travelToProjectRef`), and that was a screen+ hijack: the user looks at project B, an agent in project A runs `open-claude`, the tab switches+ and A's saved viewport is applied, so the camera appears to jump and zoom on a background agent's+ say-so. Two membership lists now decide, and their difference is the whole design:+ - `STORE_ANSWERED_VERBS` (`needsLiveCanvas` false) = **no canvas is needed at either end** —+ `list` reads names, `send`/`reply` deliver into a tmux PANE, `sticky` rewrites a note,+ `open-project` acts on the projects store.+ - `COLD_OPENABLE_VERBS` (`canColdOpen` — `open-terminal`/`open-claude`/`open-agent`) = **a canvas+ IS needed, but the serialized one will do.** `needsLiveCanvas` stays TRUE for them; they take+ the `--project` cold-open path (issue #338 §2.2) applied to their own project: the composed+ launch MOVES into `pendingLaunch` (`armForColdOpen` — `initialCommand` is never serialized), the+ node is upserted through `applyNodeMutation`, edges go through `appendCanvasLinks` (the edge+ counterpart, so the opener's rope and the fan-in bridge are not lost), `writeDisk` persists, and+ the reply is the ONE shared `coldOpenMessage` sentence with `queued: true`.+ Everything else keeps travelling **on purpose**: `write`/`close`/`group`/`move`/`arrange`/+ `align`/`verify`/`spawn-team`/`open-worktree`/`open-browser`/`show-*` read live canvas state the+ serialized copy does not carry (measured node sizes, worktree staleness, the React Flow edge+ arrays). Route `active` is byte-identical to before. Route **`reopen` (a CLOSED project) cold-writes+ too and does NOT reopen the tab** — closing is the user's explicit "park this, keep it running", so+ restoring the tab *and* activating it is the loudest form of the hijack; the reply names the closure+ so a caller does not report a session as started. On the cold path `--group`/`--after` ARE resolved+ (unlike with `--project`, where the ids would live in another project) against the serialized+ nodes, defaults come from the OWNING project (`projectPermissionMode(owner, …)`, its account,+ its `ssh`), and `--after`'s dep ropes are left to `missingDepRopes` at that project's next load.**Grouping verbs** (`group` / `ungroup` / `move` / `arrange` / `align`): `group` wraps **sibling**objects — nodes or frames — into a new frame in their shared container (a mixed-container set, oran ancestor plus its descendant, is refused with that reason); `ungroup --group <id>` dissolves adiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 5acc29586..88d4ecf6e 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -285,6 +285,20 @@ reply carries it (`queued` / `queuedIds`), because a user who cannot see the faiorchestrator that is told "opened" both act on a session that is not there. If you add a boundedretry anywhere, ask what the clock actually starts on and where its exhaustion becomes visible.+**Never move the user's view on a background agent's say-so.** Canvas-control requests route by+SOURCE, and React Flow holds only the ACTIVE project's nodes — so the dispatch used to travel to the+caller's project before answering. For an OPEN that was a screen hijack: the user is looking at+project B, an agent in project A runs `open-claude`, the tab switches and A's saved viewport is+applied, so the camera appears to jump and zoom. The rule now has two tiers, both membership lists in+`renderer/lib/controlRouting.ts`: `STORE_ANSWERED_VERBS` ("no canvas is needed at either end" —+`list`, `send`, `reply`, `sticky`, `open-project`) and `canColdOpen` ("a canvas IS needed, but the+serialized one will do" — `open-terminal`, `open-claude`, `open-agent`, which write into the owning+project's stored nodes with their launch armed and report `queued: true`). Everything that acts on+nodes which already exist still travels, because it reads live state the serialized copy does not+carry. When you add a verb, decide which tier it is in — and if you change what a verb DOES, update+`buildCanvasSkillBody` / `buildCanvasControlInstructions` in the same PR, with a test that goes red+on the stale claim (`src/main/canvas-control-core.test.ts`).+**Pointing a project at a folder is a WRITE — probe before you bind.** A project's canvas iswritten to `<cwd>/.nodeterm/project.json`, so the moment a project gains a `cwd` the next autosaveowns that file. "Open folder…" always probed and adopted; "Set folder…" (tab ⌄) used to binddiff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.tsindex f9adab6a2..d3420525d 100644--- a/src/core/canvas-control-core.ts+++ b/src/core/canvas-control-core.ts@@ -331,15 +331,23 @@ export function buildCanvasControlInstructions(shimPath: string): string {' dependents even though it is idle (`list` marks it LAST TURN ERRORED); nudge or retry it, or',' run the armed node yourself. Only',` status-reporting agent nodes (${statusAgents}, or custom agents based on them) may be waited on; a plain terminal never`,- ' reports finishing, so waiting on one is refused. `--project <id>` opens the node(s) in another',+ ' reports finishing, so waiting on one is refused.',+ ' AN OPEN NEVER SWITCHES THE USER\'S VIEW. If your own project is not the one on screen, the',+ ' node is opened COLD into it: it is created and saved, and its session starts when the user',+ ' next views that project. The reply says so and reports `queued: true` — do not poll for it,',+ ' and do not report the session as started. `--cwd`/`--count`/`--group`/`--after`/`--prompt`',+ ' all still apply. If your project is CLOSED the node is still saved into it and the reply',+ ' says the project is closed; the tab is not reopened for you.',+ ' `--project <id>` opens the node(s) in another',' project instead of yours. It accepts exactly two things — any other id is refused: your OWN',- ' project id, which behaves exactly as if the flag were omitted (a normal open, view switch',- ' included); or an id `open-project` returned to YOU in this session, which never switches the',- ' user\'s view. A session opened into a non-active project starts when the user next views that',- ' project — do not poll for it. `--group`/`--after` cannot be combined with `--project`.',+ ' project id, which behaves exactly as if the flag were omitted; or an id `open-project`',+ ' returned to YOU in this session. A session opened into a non-active project',+ ' starts when the user next views that project — do not poll for it.',+ ' `--group`/`--after` cannot be combined with `--project`.',' The reply reports whether anything actually started: `queued` is true (and `queuedIds`',' lists which) when a node was opened ARMED — waiting on `--after`, on a worktree\'s',- ' setup script, or on a `--project` target the user has not viewed yet. A queued node',+ ' setup script, or on a project the user has not viewed yet (a `--project` target, or your',+ ' own project while they are looking elsewhere). A queued node',' exists on the canvas but has no process behind it: do not route work to it, do not',' `send` to it and do not report it as started. It launches itself when its wait ends,',' then reports through the ordinary status hooks — there is nothing to poll.',@@ -765,15 +773,24 @@ Verbs:one successful turn releases everything armed behind it — or run the armed node yourself.\`--project <id>\` opens the node(s) in another project instead of yours. It accepts exactlytwo things — any other id is refused: your OWN project id, which behaves exactly as if the flag- were omitted (a normal open, view switch included); or an id \`open-project\` returned to YOU- in this session, which never switches the user's view. Defaults inside the target are the+ were omitted; or an id \`open-project\` returned to YOU+ in this session. Neither switches the user's view. Defaults inside the target are theTARGET project's (its cwd, its default account and permission mode). A session opened into anon-active project starts when the user next views that project — do not poll for it; the replysays so. \`--group\`/\`--after\` cannot be combined with \`--project\`.+ **An open NEVER switches the user's view — not even into your own project.** If the project you+ are running in is not the one on screen, the node is opened **cold**: created and saved there,+ with its session starting when the user next views that project. Every flag still applies+ (\`--cwd\`, \`--count\`, \`--group\`, \`--after\`, \`--prompt\`), the rope and the context link+ back to you are still drawn, and the reply says the session is queued. If your project is+ **closed**, the node is still saved into it and the reply says so; the tab is not reopened for+ you. So: opening a station is safe to do at any time, but a station you opened while the user was+ elsewhere is not running yet — read \`queued\` before you route work to it.**The reply tells you whether anything actually started.** \`queued\` is true — and\`queuedIds\` names which of the returned ids — whenever a node was opened **armed**: waiting on- \`--after\`, on a worktree's setup script, or on a \`--project\` target the user has not viewed- yet. A queued node exists on the canvas but has **no process behind it**, so do not route work+ \`--after\`, on a worktree's setup script, or on a project the user has not viewed yet (a+ \`--project\` target, or your own project while they are looking elsewhere).+ A queued node exists on the canvas but has **no process behind it**, so do not route workto it, do not \`send\` to it and do not report it as started. It launches itself when its waitends and then reports through the ordinary status hooks, so there is nothing to poll.\`queued: false\` means the session is running.diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.tsindex b7841133b..41cd89dfa 100644--- a/src/main/canvas-control-core.test.ts+++ b/src/main/canvas-control-core.test.ts@@ -697,7 +697,7 @@ describe('the --project clause tells the truth about travel (review #363 I-1 + M['instructions', buildCanvasControlInstructions('/x/shim.sh')]]- it('no-travel is promised ONLY for a returned id; own id is documented as flag-omitted (travel included)', () => {+ it('no open switches the view — the own-id "travel included" claim is GONE from both bodies', () => {for (const [name, body] of bodies) {// The clause slice: from the `--project` flag doc to the open-project entry that follows// it in both bodies — anchored, so a caveat cannot drift into another paragraph (the@@ -707,17 +707,17 @@ describe('the --project clause tells the truth about travel (review #363 I-1 + Mexpect(start, `${name}: clause start`).toBeGreaterThan(-1)expect(end, `${name}: clause before the open-project entry`).toBeGreaterThan(start)const clause = body.slice(start, end)- // Own id ≡ the flag omitted, view switch included — the REAL behavior (Canvas.tsx's- // own-id leg falls through to the legacy path, travel included; pinned in- // control-open-project.source.test.ts). The doc must say the same, not more.+ // Own id ≡ the flag omitted — still true, and still the whole of what that leg promises.expect(clause, name).toMatch(/behaves exactly as if the flag\s+were omitted/)- expect(clause, name).toMatch(/view switch\s+included/)- // The no-travel promise exists only attached to the RETURNED id…- expect(clause, name).toMatch(- /returned to YOU\s+in this session, which never switches the\s+user'?s view/- )- // …and the old universal phrasing ("without switching the user's view", said of the whole- // flag) is gone from the body entirely.+ // THE STALE CLAIM. Passing your own id (or omitting the flag) used to switch the user's+ // view to your project; it no longer does — an open whose own project is not on screen is+ // written COLD into it (lib/coldOpen, `canColdOpen`). A body still promising a view switch+ // describes a product that no longer exists, and an orchestrator reading it would expect+ // the user to be looking at what it opened.+ expect(body, name).not.toMatch(/view switch\s+included/)+ expect(body, name).not.toMatch(/a normal open, view switch/)+ // The old universal phrasing ("without switching the user's view", said of the whole flag)+ // stays gone too — the promise now belongs to EVERY open, stated in its own sentence.expect(body, name).not.toMatch(/without switching/)// M-3: the do-not-poll caveat and the refusal rule live in the clause ITSELF — dropping// them here while the recipe's copy survives is red.@@ -725,4 +725,20 @@ describe('the --project clause tells the truth about travel (review #363 I-1 + Mexpect(clause, name).toContain('any other id is refused')}})++ it('both bodies document the OWN-project cold open: never switches the view, queued, closed case', () => {+ // The behaviour change this test exists for. All four facts an orchestrator acts on:+ // (1) an open never moves the user, (2) a node opened into a project they are not viewing+ // starts when they next view it, (3) the reply says so via `queued`, (4) a CLOSED project is+ // still written into and the tab is NOT reopened.+ for (const [name, body] of bodies) {+ expect(body, `${name}: never switches the view`).toMatch(+ /open NEVER switches the user'?s view|OPEN NEVER SWITCHES THE USER'?S VIEW/i+ )+ expect(body, `${name}: cold`).toMatch(/cold/i)+ expect(body, `${name}: queued`).toContain('queued')+ expect(body, `${name}: closed project`).toMatch(/closed/i)+ expect(body, `${name}: tab not reopened`).toMatch(/not reopened/i)+ }+ })})diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 0528a1fa7..e520a56e1 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -246,11 +246,24 @@ import { useWebviewKeepAlive } from '../state/webviewKeepAlive'import {routeControlSource,needsLiveCanvas,+ canColdOpen,sourceIsControlCapable,storedNodeListing,answerBrowserResolve,type BrowserResolveProject} from '../lib/controlRouting'+import {+ coldGroupCwd,+ coldGroupChildCount,+ coldOpenMessage,+ coldPlaceBelow,+ coldResolveAfter,+ coldResolveGroup,+ groupSizeFor,+ groupSlot,+ storedAgentIdOf,+ type ColdNode+} from '../lib/coldOpen'import { applyStickyWrite, parseStickyArgs, resolveStickyRef } from '@shared/sticky-write'import {unavailableRecovery,@@ -452,6 +465,7 @@ import { useEntitlement } from '../state/entitlement'import type { SshServer } from '@shared/ssh'import { sshHostKey } from '@shared/ssh'import type {+ BridgeLink,CanvasNodeState,ClosedSessionEntry,NodeKind,@@ -9151,9 +9165,10 @@ export function Canvas() {void writeDisk()reply({ok: true,- message:- `opened ${tgCount} ${tgWhat} session(s) in "${target.name}" (${tgIds.join(', ')}) — ` +- 'queued; starts when that project is next viewed',+ // ONE sentence for "queued into a project you are not looking at", shared with the+ // own-project cold open below (lib/coldOpen) so an orchestrator never meets two+ // phrasings for one outcome.+ message: coldOpenMessage(tgCount, tgWhat, target.name, tgIds),// Every node on this branch is armed by `armForColdOpen`, so the whole batch is// QUEUED. Said in the reply as a field, not only in the sentence, so an orchestrator// does not have to report a session as started when it is not (#569 item 1).@@ -9286,6 +9301,280 @@ export function Canvas() {})return}+ // ── COLD OPEN ───────────────────────────────────────────────────────────────────+ // An OPEN verb whose own project is not on screen is answered out of that project's+ // SERIALIZED nodes instead of travelling to it. Travelling here was a screen hijack: the+ // user is looking at project B, an agent in project A runs `open-claude`, and the tab+ // switches while A's saved viewport is applied — the camera appears to jump and zoom, on+ // a background agent's say-so (present since cecb4dfe, v0.2.43). It is the G5 rule+ // `send`/`reply`/`sticky`/`open-project` already state, one set wider: see+ // `canColdOpen` in lib/controlRouting for how the two sets differ.+ //+ // This is the `--project` path (issue #338 spec §2.2) applied to an open that did NOT+ // pass `--project`, and it is deliberately the same mechanism: MOVE the composed launch+ // into `pendingLaunch` (`armForColdOpen` — `initialCommand` is never serialized, so a+ // command left there would be silently dropped), upsert through `applyNodeMutation`,+ // persist with `writeDisk`, and say in the reply that the session starts when that+ // project is next viewed.+ //+ // `reopen` (a CLOSED project) takes this branch too, and does NOT reopen the tab. Closing+ // is the user's explicit "park this, keep it running"; restoring the tab AND activating+ // it is the loudest version of exactly the hijack this fixes, and refusing would undo+ // what cecb4dfe fixed (an agent in another project must be ANSWERED). The node is+ // persisted with the project, and the reply names the closure so a caller does not report+ // a session as started.+ if (canColdOpen(verb)) {+ const coldStore = useProjects.getState()+ const owner = coldStore.getProject(route.projectId)+ const coldSrc = owner?.nodes.find((n) => n.id === sourceNodeId)+ // Same authorization boundary and same sentence as every other path — a stored node+ // carries the agent id the live one would (`data.agentId` is serialized).+ if (!owner || !coldSrc || !sourceIsControlCapable(coldSrc.agentId)) {+ reply({ ok: false, error: 'source node is not a control-capable agent' })+ return+ }+ const coldNodes = owner.nodes as unknown as ColdNode[]+ const coldSrcNode = coldSrc as unknown as ColdNode+ const coldTerminal = verb === 'open-terminal'+ const coldAgentId = (verb === 'open-agent' ? args.agent : 'claude') as AgentId+ const coldCount = Math.max(+ 1,+ Math.min(coldTerminal ? 8 : 5, parseInt(args.count || '1', 10) || 1)+ )+ // `--group` / `--after` name ids INSIDE this project, which is the caller's own — the+ // reason `--project` refuses both (spec §2.2) does not apply here, so both are resolved+ // against the serialized nodes rather than declined.+ const coldGroup = coldResolveGroup(coldNodes, args.group, verb)+ if (!coldGroup.ok) {+ reply({ ok: false, error: coldGroup.error })+ return+ }+ const coldStatusAgent = (id: string): string | undefined =>+ useAgentStatus.getState().byId[id]?.agentId+ const coldAfter = coldResolveAfter(+ coldNodes,+ args.after,+ verb,+ (a) => hasHooks(a as AgentId),+ coldStatusAgent+ )+ if (!coldAfter.ok) {+ reply({ ok: false, error: coldAfter.error })+ return+ }+ const coldAfterIds = coldAfter.after ?? []+ const coldCwd =+ args.cwd || coldGroupCwd(coldNodes, coldGroup.groupId, !!owner.ssh) || coldSrc.cwd+ // Same SSH rule as the live path: a node an agent opens has to run on the same host the+ // agent runs on, and the effective cwd rides `remoteCwd` or the factory replaces it.+ const coldSsh = nodeSshFor(owner.ssh, coldCwd)+ const coldPromptFile = (args['prompt-file'] ?? '').trim() || undefined+ if (!coldTerminal && coldPromptFile && args.prompt) {+ reply({ ok: false, error: `${verb}: pass either --prompt or --prompt-file, not both` })+ return+ }+ if (!coldTerminal && coldPromptFile) {+ const pfErr = promptFilePathError(coldPromptFile)+ if (pfErr) {+ reply({ ok: false, error: `${verb}: --prompt-file ${pfErr}` })+ return+ }+ // Read from the filesystem the NODE will read it from (the host's on an SSH project).+ // Fails OPEN like the live path: a check that itself errors must not refuse an open.+ const pfFs = owner.ssh ? sshFs(owner.id) : api.fs+ const pfExists = await pfFs.exists(coldPromptFile).catch(() => true)+ if (!pfExists) {+ reply({ ok: false, error: `${verb}: --prompt-file not found: ${coldPromptFile}` })+ return+ }+ }+ if (dryRun) {+ if (!coldTerminal) {+ const dryKnownAgent =+ !!agentConfig(coldAgentId) ||+ useSettings.getState().settings.customAgents.some((c) => c.id === coldAgentId)+ if (!dryKnownAgent) {+ reply({+ ok: false,+ error: `${verb}: unknown agent "${coldAgentId}" — pass a builtin id or a custom agent id from Settings`+ })+ return+ }+ }+ reply({+ ok: true,+ message: [+ DRY_RUN_PREFIX,+ `${verb} would open ${coldCount} ${coldTerminal ? 'terminal' : coldAgentId} session(s)` ++ ` in "${owner.name}"` ++ (coldGroup.groupId ? ` in group ${coldGroup.groupId}` : '') ++ (coldCwd ? `, cwd ${coldCwd}` : ''),+ ...(coldAfterIds.length ? [`armed to wait for: ${coldAfterIds.join(', ')}`] : []),+ 'That project is not on screen, so the session(s) would be queued and start when it is next viewed.'+ ].join('\n'),+ result: {+ dryRun: true,+ count: coldCount,+ group: coldGroup.groupId ?? null,+ cwd: coldCwd ?? null,+ after: coldAfterIds,+ projectId: owner.id+ }+ })+ return+ }+ // Defaults come from the OWNING project — its default account, its permission mode, its+ // `.nodeterm/settings.json` launch override. `activePermissionMode` would read the+ // project the user happens to be looking at, which is not the one this node runs in.+ const coldAccount = coldTerminal+ ? undefined+ : resolveNewNodeAccount(+ coldSrc.accountId,+ owner,+ useSettings.getState().settings.claudeAccounts+ )+ const coldMode = coldTerminal ? undefined : projectPermissionMode(owner, coldAgentId)+ const coldExistingInGroup = coldGroup.groupId+ ? coldGroupChildCount(coldNodes, coldGroup.groupId)+ : 0+ const coldMade: CanvasNode[] = []+ for (let i = 0; i < coldCount; i++) {+ const built = coldTerminal+ ? createTerminalNode(+ coldNodes.length + i,+ coldCwd,+ coldPlaceBelow(coldNodes, coldSrcNode, i),+ args.cmd,+ coldSsh+ )+ : createAgentNode(+ coldAgentId,+ coldNodes.length + i,+ coldCwd,+ coldPlaceBelow(coldNodes, coldSrcNode, i),+ args.prompt,+ coldSsh,+ coldAccount,+ coldMode,+ owner.id,+ args.model,+ coldPromptFile+ )+ // Arm it: the project is not mounted, so nothing would deliver an `initialCommand`+ // and serialization drops it. `--after` rides the same held launch — an empty `after`+ // is vacuously ready, so a node with no deps fires on that project's first view.+ const armed = armForColdOpen(built)+ const held = armed.data.pendingLaunch as PendingLaunch | undefined+ const node =+ held && coldAfterIds.length+ ? {+ ...armed,+ data: { ...armed.data, pendingLaunch: { ...held, after: coldAfterIds } }+ }+ : armed+ if (coldGroup.groupId) {+ const w = (node.width as number) ?? 600+ const h = (node.height as number) ?? 400+ node.position = groupSlot(coldExistingInGroup + i, w, h)+ node.parentId = coldGroup.groupId+ node.extent = 'parent'+ }+ coldMade.push(node)+ }+ // Grow the frame BEFORE the children land, exactly as `addGrouped` does — `extent:+ // 'parent'` clamps a child that falls outside it.+ if (coldGroup.groupId) {+ const frame = owner.nodes.find((n) => n.id === coldGroup.groupId)+ if (frame) {+ const w = (coldMade[0]?.width as number) ?? 600+ const h = (coldMade[0]?.height as number) ?? 400+ const need = groupSizeFor(coldExistingInGroup + coldCount, w, h)+ coldStore.applyNodeMutation(owner.id, {+ op: 'upsert',+ node: {+ ...frame,+ size: {+ width: Math.max(frame.size?.width ?? 0, need.width),+ height: Math.max(frame.size?.height ?? 0, need.height)+ }+ }+ })+ }+ }+ for (const node of coldMade) {+ coldStore.applyNodeMutation(owner.id, {+ op: 'upsert',+ node: flowToNodeStates([node])[0]+ })+ }+ const coldIds = coldMade.map((n) => n.id)+ // The lineage rope and the fan-in bridge are what an orchestrator LOSES if a cold open+ // only writes nodes — a spawned team it cannot read back is the write-only fan-out the+ // `link` work existed to end. `appendCanvasLinks` is the edge counterpart of+ // `applyNodeMutation`. The `--after` dep ropes are deliberately NOT written here:+ // `missingDepRopes` mints them at that project's load, which is the first moment the+ // armed node is on screen to need one.+ const coldRopes = coldIds.map((id) => ({+ id: `ctrl-${sourceNodeId}-${id}`,+ source: sourceNodeId,+ target: id+ }))+ const coldEndpoint = (id: string): LinkEndpoint | null => {+ if (coldIds.includes(id)) {+ return { kind: 'terminal', contextCapable: canContextLink(coldAgentId) }+ }+ const n = coldNodes.find((x) => x.id === id)+ if (!n) return null+ const a = storedAgentIdOf(n, coldStatusAgent)+ return {+ kind: n.kind ?? 'terminal',+ contextCapable: !!a && canContextLink(a as AgentId)+ }+ }+ const coldExistingBridges = [...(owner.bridges ?? [])]+ const coldPlan = coldTerminal+ ? { edges: [] as BridgeLink[], linked: [] as string[] }+ : planBridges(sourceNodeId, coldIds, coldEndpoint, coldExistingBridges)+ const coldDepPlans = coldTerminal+ ? []+ : coldIds.map((nid) =>+ planBridges(nid, coldAfterIds, coldEndpoint, [+ ...coldExistingBridges,+ ...coldPlan.edges+ ])+ )+ const coldBridges = [...coldPlan.edges, ...coldDepPlans.flatMap((p) => p.edges)]+ coldStore.appendCanvasLinks(owner.id, { bridges: coldBridges, ropes: coldRopes })+ void writeDisk()+ const coldWhat = coldTerminal ? 'terminal' : coldAgentId+ const coldDepLinked = coldDepPlans.flatMap((p) => p.linked)+ reply({+ ok: true,+ message:+ coldOpenMessage(coldCount, coldWhat, owner.name, coldIds, {+ closed: route.kind === 'reopen'+ }) ++ (coldPlan.linked.length+ ? `\ncontext-linked to you: ${coldPlan.linked.join(', ')}`+ : '') ++ (coldAfterIds.length+ ? `\nwaiting for ${coldAfterIds.join(', ')} before running` ++ (coldDepLinked.length ? ' (and linked to read them)' : '')+ : ''),+ // Every node on this branch has no process behind it until that project is viewed,+ // whether or not it holds a command — the same rule the `--project` branch states.+ result: {+ ids: coldIds,+ id: coldIds[0],+ projectId: owner.id,+ linked: coldPlan.linked,+ after: coldAfterIds,+ queued: true,+ queuedIds: coldIds+ }+ })+ return+ }travelToProjectRef.current(route.projectId)}// Wait for the node to show up on the canvas: after a travel, because the active-project@@ -9397,21 +9686,9 @@ export function Canvas() {}// Grid slots INSIDE a group frame (open-agent --group): 2 columns of terminal-sized// cells under the header. Pure geometry — the frame is grown to fit before children land.- const GROUP_PAD_X = 24- const GROUP_PAD_TOP = 56- const GROUP_GAP = 24- const groupSlot = (slot: number, w: number, h: number) => ({- x: GROUP_PAD_X + (slot % 2) * (w + GROUP_GAP),- y: GROUP_PAD_TOP + Math.floor(slot / 2) * (h + GROUP_GAP)- })- const groupSizeFor = (children: number, w: number, h: number) => {- const cols = Math.min(2, Math.max(1, children))- const rows = Math.max(1, Math.ceil(children / 2))- return {- width: GROUP_PAD_X * 2 + cols * w + (cols - 1) * GROUP_GAP,- height: GROUP_PAD_TOP + rows * h + (rows - 1) * GROUP_GAP + GROUP_PAD_X- }- }+ // `groupSlot`/`groupSizeFor` live in lib/coldOpen so the COLD path (an open answered out of a+ // non-active project's serialized nodes) lands children on the identical grid; two copies of+ // this arithmetic would be two layouts.// Validate `--group` (open-terminal / open-claude / open-agent): must name an existing// group frame. Returns its id, or null with the error already replied.const resolveIntoGroup = (): string | null | undefined => {diff --git a/src/renderer/canvas/control-cold-open.source.test.ts b/src/renderer/canvas/control-cold-open.source.test.tsnew file mode 100644index 000000000..4342b85d3--- /dev/null+++ b/src/renderer/canvas/control-cold-open.source.test.ts@@ -0,0 +1,157 @@+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'++/**+ * STRUCTURAL pins for the COLD-OPEN branch of the canvas-control dispatch — the same class of test+ * as `control-open-project.source.test.ts`, and for the same reason: the branch lives inside a+ * 12,000-line React component's IPC listener with no unit seam, and what it must be pinned on are+ * properties of the SOURCE (what it calls and, above all, what it never calls).+ *+ * Every behavioural half is proven separately against real primitives: the verb set and its+ * disjointness from the store-answered set in `lib/controlRouting.test.ts`, the flag resolution,+ * placement and reply sentence in `lib/coldOpen.test.ts`, the arming round-trip in+ * `lib/projectOpen.test.ts`, and the edge append in `state/projects.links.test.ts`.+ *+ * THE BUG: the user is looking at project B; an agent in project A runs `nodeterm open-claude`; the+ * app switched to A and applied A's saved viewport, so the camera appeared to jump and zoom+ * (cecb4dfe, first shipped v0.2.43).+ */+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')++/** The cold-open block: from its `if (canColdOpen(verb))` guard to the travel call it stands in+ * front of. */+function coldOpenBody(): string {+ const start = src.indexOf('if (canColdOpen(verb)) {')+ expect(start, 'the cold-open guard').toBeGreaterThan(-1)+ const end = src.indexOf('travelToProjectRef.current(route.projectId)', start)+ expect(end, 'the travel call after the block').toBeGreaterThan(start)+ return src.slice(start, end)+}++describe('the cold-open dispatch block (source pins)', () => {+ it('stands IN FRONT of the travel call — an open verb never reaches it', () => {+ // The travel call is what moved the user's screen. Scoped to the dispatch's source-routing+ // block (Canvas has one other, unrelated travel for the browser-verb guest lookup), the+ // cold-open guard must precede the single travel in it, or the block is dead code sitting+ // behind the very thing it replaces.+ const from = src.indexOf('routeControlSource(projects, activeId, sourceNodeId)')+ expect(from, 'the source-routing lookup').toBeGreaterThan(-1)+ const to = src.indexOf('waitForCanvasNode(', from)+ expect(to, 'the post-routing canvas wait').toBeGreaterThan(from)+ const routing = src.slice(from, to)+ expect(routing.match(/travelToProjectRef\.current\(route\.projectId\)/g)?.length).toBe(1)+ const guard = routing.indexOf('if (canColdOpen(verb)) {')+ const travel = routing.indexOf('travelToProjectRef.current(route.projectId)')+ expect(guard, 'the cold-open guard inside the routing block').toBeGreaterThan(-1)+ expect(guard).toBeLessThan(travel)+ // …and it RETURNS, so control cannot fall through to the travel after writing the node.+ expect(coldOpenBody()).toMatch(/queuedIds: coldIds\s*\}\s*\}\)\s*return\s*\}/)+ })++ it('the guard polarity is not inverted — a NON-cold verb must still travel', () => {+ // `if (!canColdOpen(verb))` would cold-write `write`/`close`/`group` into a serialized project+ // (silently doing nothing useful) and travel for every open — the exact swap of the fix.+ expect(src).toContain('if (canColdOpen(verb)) {')+ expect(src).not.toContain('if (!canColdOpen(verb))')+ })++ it('never travels, activates, or reopens anything', () => {+ const body = coldOpenBody()+ expect(body).not.toContain('travelToProject')+ expect(body).not.toContain('setActive')+ expect(body).not.toContain('reopenProject')+ expect(body).not.toContain('goToNode')+ expect(body).not.toContain('focusNodeById')+ })++ it('never touches the LIVE canvas — no setNodes, no edge state, no nodesRef', () => {+ // React Flow holds the ACTIVE project's nodes. Writing the new node there would put it on the+ // wrong canvas, which is worse than the travel it replaces.+ const body = coldOpenBody()+ expect(body).not.toContain('setNodes(')+ expect(body).not.toContain('setControlEdges')+ expect(body).not.toContain('setLinkEdges')+ expect(body).not.toContain('nodesRef.current')+ expect(body).not.toContain('addAndConnect')+ })++ it('writes through the store: applyNodeMutation for nodes, appendCanvasLinks for edges', () => {+ const body = coldOpenBody()+ expect(body).toContain('applyNodeMutation(owner.id, {')+ expect(body).toContain('appendCanvasLinks(owner.id,')+ expect(body).toContain('writeDisk()')+ })++ it('arms every node through armForColdOpen — the launch must survive serialization', () => {+ // `flowToNodeStates` drops `initialCommand` by design, so a node upserted without moving its+ // command into `pendingLaunch` is the silent-never-starts mutation.+ const body = coldOpenBody()+ expect(body).toMatch(/const armed = armForColdOpen\(built\)/)+ expect(body).toMatch(/flowToNodeStates\(\[node\]\)\[0\]/)+ // `--after` rides that same held launch rather than a second mechanism.+ expect(body).toMatch(/pendingLaunch: \{ \.\.\.held, after: coldAfterIds \}/)+ })++ it('refusal-before-write: every refusal precedes the first store write', () => {+ const body = coldOpenBody()+ const firstWrite = Math.min(+ ...['applyNodeMutation', 'appendCanvasLinks'].map((s) => {+ const i = body.indexOf(s)+ return i === -1 ? body.length : i+ })+ )+ expect(firstWrite).toBeLessThan(body.length)+ for (const refusal of [+ 'source node is not a control-capable agent',+ 'coldGroup.error',+ 'coldAfter.error',+ '--prompt-file not found'+ ]) {+ const at = body.indexOf(refusal)+ expect(at, refusal).toBeGreaterThan(-1)+ expect(at, `${refusal} after a write`).toBeLessThan(firstWrite)+ }+ })++ it('keeps cecb4dfe’s fix: the refusal is the capability sentence, not a new rejection', () => {+ // Before cecb4dfe an agent outside the active project was rejected as "not a control-capable+ // agent" purely because the wrong canvas answered. The cold path must not reintroduce a+ // refusal for being off-screen — the ONLY refusal on the source is the capability one.+ const body = coldOpenBody()+ expect(body).toContain("error: 'source node is not a control-capable agent'")+ expect(body).not.toContain('is not on an open canvas')+ expect(body).not.toContain('not the active project')+ })++ it('reports the batch as QUEUED — no process exists until that project is viewed', () => {+ const body = coldOpenBody()+ expect(body).toMatch(/queued: true/)+ expect(body).toMatch(/queuedIds: coldIds/)+ // The sentence comes from the ONE shared builder, not a second phrasing.+ expect(body).toContain('coldOpenMessage(')+ })++ it('resolves defaults from the OWNING project, never from whatever is on screen', () => {+ // `activePermissionMode` / the active project's account list describe the project the user+ // happens to be looking at, which is not the one this node runs in.+ const body = coldOpenBody()+ expect(body).toContain('projectPermissionMode(owner, coldAgentId)')+ expect(body).not.toContain('activePermissionMode(')+ expect(body).toMatch(/resolveNewNodeAccount\(\s*coldSrc\.accountId,\s*owner,/)+ expect(body).toContain('nodeSshFor(owner.ssh, coldCwd)')+ })++ it('supports the documented flags on the cold path', () => {+ const body = coldOpenBody()+ for (const flag of ['args.count', 'args.cwd', 'args.group', 'args.after', 'args.prompt', 'args.model', 'args.cmd']) {+ expect(body, flag).toContain(flag)+ }+ })++ it('a CLOSED project is written into, and the reply says so', () => {+ // The deliberate choice for route `reopen`: restoring a tab AND activating it is the loudest+ // version of the hijack this fixes, and refusing would undo cecb4dfe.+ const body = coldOpenBody()+ expect(body).toMatch(/closed: route\.kind === 'reopen'/)+ })+})diff --git a/src/renderer/canvas/control-open-project.source.test.ts b/src/renderer/canvas/control-open-project.source.test.tsindex 265c7fdea..a2de4190e 100644--- a/src/renderer/canvas/control-open-project.source.test.ts+++ b/src/renderer/canvas/control-open-project.source.test.ts@@ -145,7 +145,10 @@ describe('the --project targeted-opens block (source pins)', () => {it('the store path persists (writeDisk) and states the cold-open contract in the reply', () => {const body = targetedOpensBody()expect(body).toContain('writeDisk()')- expect(body).toContain('starts when that project is next viewed')+ // The sentence itself now lives in the ONE builder both cold-open sites share+ // (lib/coldOpen `coldOpenMessage`, whose wording is pinned in coldOpen.test.ts) — this leg+ // must reach it rather than re-typing a second phrasing for the same outcome.+ expect(body).toMatch(/message: coldOpenMessage\(/)})it('the caller’s OWN project id falls through to the legacy path (B3a) — no return on that leg', () => {diff --git a/src/renderer/lib/coldOpen.test.ts b/src/renderer/lib/coldOpen.test.tsnew file mode 100644index 000000000..52c728f01--- /dev/null+++ b/src/renderer/lib/coldOpen.test.ts@@ -0,0 +1,220 @@+import { describe, it, expect } from 'vitest'+import {+ coldGroupChildCount,+ coldGroupCwd,+ coldOpenMessage,+ coldPlaceBelow,+ coldResolveAfter,+ coldResolveGroup,+ groupSizeFor,+ groupSlot,+ storedAgentIdOf,+ type ColdNode+} from './coldOpen'++const N = (id: string, extra: Partial<ColdNode> = {}): ColdNode => ({+ id,+ position: { x: 0, y: 0 },+ ...extra+})++const hasHooks = (a: string) => ['claude', 'codex', 'gemini', 'grok'].includes(a)++describe('storedAgentIdOf — the serialized counterpart of Canvas.agentIdOf', () => {+ it('reads the persisted agentId', () => {+ expect(storedAgentIdOf(N('a', { agentId: 'codex' }))).toBe('codex')+ })++ it('migrates the legacy tags marker', () => {+ expect(storedAgentIdOf(N('a', { tags: ['claude'] }))).toBe('claude')+ })++ it('falls back to live agent status — a hand-launched CLI is known nowhere else', () => {+ expect(storedAgentIdOf(N('a'), (id) => (id === 'a' ? 'gemini' : undefined))).toBe('gemini')+ })++ it('answers nothing for a non-terminal node, whatever it carries', () => {+ // A group frame or a sticky is not a session. Reading an agent off one would let `--after`+ // wait on something that can never report.+ expect(storedAgentIdOf(N('g', { kind: 'group', agentId: 'claude' }))).toBeUndefined()+ expect(storedAgentIdOf(undefined)).toBeUndefined()+ })+})++describe('coldResolveGroup', () => {+ const nodes = [N('g1', { kind: 'group' }), N('t1'), N('s1', { kind: 'sticky' })]++ it('passes through when the flag is absent', () => {+ expect(coldResolveGroup(nodes, undefined, 'open-claude')).toEqual({ ok: true })+ })++ it('resolves an existing frame', () => {+ expect(coldResolveGroup(nodes, 'g1', 'open-claude')).toEqual({ ok: true, groupId: 'g1' })+ })++ it('refuses a name that is not a frame, with the live path’s sentence', () => {+ // Unlike `--project` (which refuses --group outright because the id would live in ANOTHER+ // project), here the target project IS the caller's own, so the id is resolvable — a refusal+ // must therefore only fire for a genuinely wrong id.+ for (const id of ['t1', 's1', 'nope']) {+ expect(coldResolveGroup(nodes, id, 'open-agent')).toEqual({+ ok: false,+ error: 'open-agent: --group must name an existing group frame'+ })+ }+ })+})++describe('coldGroupCwd', () => {+ it('takes the nearest ancestor frame’s worktree path', () => {+ const nodes = [+ N('outer', { kind: 'group', worktree: { path: '/wt/feature' } }),+ N('inner', { kind: 'group', parentId: 'outer' })+ ]+ expect(coldGroupCwd(nodes, 'inner', false)).toBe('/wt/feature')+ })++ it('prefers a frame’s own cwd over an ancestor’s worktree', () => {+ const nodes = [+ N('outer', { kind: 'group', worktree: { path: '/wt/feature' } }),+ N('inner', { kind: 'group', parentId: 'outer', cwd: '/repo/sub' })+ ]+ expect(coldGroupCwd(nodes, 'inner', false)).toBe('/repo/sub')+ })++ it('never hands out a worktree path on an SSH project', () => {+ // A worktree path was computed from the LOCAL data dir and means nothing on the host —+ // the same rule `cwdForNewNodeIn` states for the live path.+ const nodes = [N('g', { kind: 'group', worktree: { path: '/wt/feature' } })]+ expect(coldGroupCwd(nodes, 'g', true)).toBeUndefined()+ })++ it('answers undefined for no group, an unknown group, and a bare frame', () => {+ expect(coldGroupCwd([], undefined, false)).toBeUndefined()+ expect(coldGroupCwd([], 'ghost', false)).toBeUndefined()+ expect(coldGroupCwd([N('g', { kind: 'group' })], 'g', false)).toBeUndefined()+ })++ it('terminates on a parent cycle rather than hanging the dispatch', () => {+ // project.json is hand-editable, git-shared input; a cycle there must not spin the handler.+ const nodes = [+ N('a', { kind: 'group', parentId: 'b' }),+ N('b', { kind: 'group', parentId: 'a' })+ ]+ expect(coldGroupCwd(nodes, 'a', false)).toBeUndefined()+ })+})++describe('coldResolveAfter', () => {+ const nodes = [+ N('agent1', { agentId: 'claude' }),+ N('agent2', { agentId: 'codex' }),+ N('plain'),+ N('frame', { kind: 'group' })+ ]++ it('passes through when the flag is absent or empty', () => {+ expect(coldResolveAfter(nodes, undefined, 'open-claude', hasHooks)).toEqual({ ok: true })+ expect(coldResolveAfter(nodes, ' , ', 'open-claude', hasHooks)).toEqual({ ok: true })+ })++ it('dedupes — `--after a,a` is ONE wait', () => {+ // Two dep ropes for one pair would collide on the single id `ctrl-a-<node>`.+ expect(coldResolveAfter(nodes, 'agent1,agent1', 'open-claude', hasHooks)).toEqual({+ ok: true,+ after: ['agent1']+ })+ })++ it('refuses an id that names no node', () => {+ expect(coldResolveAfter(nodes, 'ghost', 'open-claude', hasHooks)).toEqual({+ ok: false,+ error: 'open-claude: --after names no existing node (ghost)'+ })+ })++ it('refuses a plain terminal — it never reports finishing, so the wait would never end', () => {+ expect(coldResolveAfter(nodes, 'plain', 'open-terminal', hasHooks)).toEqual({+ ok: false,+ error: 'open-terminal: --after plain is not an agent session that reports when it is done'+ })+ })++ it('refuses a group frame', () => {+ expect(coldResolveAfter(nodes, 'frame', 'open-claude', hasHooks).ok).toBe(false)+ })++ it('accepts a node whose agent is known only from live status', () => {+ expect(+ coldResolveAfter(nodes, 'plain', 'open-claude', hasHooks, (id) =>+ id === 'plain' ? 'claude' : undefined+ )+ ).toEqual({ ok: true, after: ['plain'] })+ })+})++describe('coldPlaceBelow — the live path’s placeBelow, off persisted geometry', () => {+ it('centers below the source and fans siblings right', () => {+ const src = N('src', { position: { x: 100, y: 200 }, size: { width: 600, height: 400 } })+ expect(coldPlaceBelow([src], src, 0)).toEqual({ x: 400, y: 890 })+ expect(coldPlaceBelow([src], src, 1)).toEqual({ x: 860, y: 890 })+ })++ it('resolves a grouped source to ROOT space', () => {+ // A stored child's position is frame-relative; placing off it directly would land the new+ // node by the frame's own offset away from the agent it hangs from.+ const frame = N('g', { kind: 'group', position: { x: 1000, y: 1000 } })+ const src = N('src', {+ parentId: 'g',+ position: { x: 10, y: 20 },+ size: { width: 600, height: 400 }+ })+ expect(coldPlaceBelow([frame, src], src, 0)).toEqual({ x: 1310, y: 1710 })+ })++ it('falls back to the default node size when none is persisted', () => {+ const src = N('src', { position: { x: 0, y: 0 } })+ expect(coldPlaceBelow([src], src, 0)).toEqual({ x: 300, y: 690 })+ })+})++describe('group grid geometry (shared with the live addGrouped path)', () => {+ it('lays children out in two columns under the frame header', () => {+ expect(groupSlot(0, 600, 400)).toEqual({ x: 24, y: 56 })+ expect(groupSlot(1, 600, 400)).toEqual({ x: 648, y: 56 })+ expect(groupSlot(2, 600, 400)).toEqual({ x: 24, y: 480 })+ })++ it('sizes the frame to hold N children', () => {+ expect(groupSizeFor(1, 600, 400)).toEqual({ width: 648, height: 480 })+ expect(groupSizeFor(3, 600, 400)).toEqual({ width: 1272, height: 904 })+ })++ it('counts only DIRECT children of the frame', () => {+ const nodes = [+ N('g'),+ N('a', { parentId: 'g' }),+ N('b', { parentId: 'g' }),+ N('c', { parentId: 'other' }),+ N('d')+ ]+ expect(coldGroupChildCount(nodes, 'g')).toBe(2)+ })+})++describe('coldOpenMessage — ONE sentence for both cold-open sites', () => {+ it('names the count, the agent, the project and the ids, and says when it starts', () => {+ expect(coldOpenMessage(2, 'claude', 'Backend', ['t1', 't2'])).toBe(+ 'opened 2 claude session(s) in "Backend" (t1, t2) — queued; starts when that project is next viewed'+ )+ })++ it('adds — and only adds — a clause when the project is CLOSED', () => {+ // The base sentence must stay byte-identical, because the `--project` branch emits it too and+ // an orchestrator should not have to learn two phrasings for one outcome.+ const open = coldOpenMessage(1, 'terminal', 'Docs', ['t1'])+ const closed = coldOpenMessage(1, 'terminal', 'Docs', ['t1'], { closed: true })+ expect(closed.startsWith(open)).toBe(true)+ expect(closed).toContain('that project is closed')+ })+})diff --git a/src/renderer/lib/coldOpen.ts b/src/renderer/lib/coldOpen.tsnew file mode 100644index 000000000..2d1da9872--- /dev/null+++ b/src/renderer/lib/coldOpen.ts@@ -0,0 +1,220 @@+// COLD OPEN — answering canvas-control's node-opening verbs out of a project's SERIALIZED nodes,+// so a background agent's `open-claude` never yanks the user's screen to another project.+//+// WHY IT EXISTS. `routeControlSource` resolves the OWNING project of the source node, and Canvas+// then travelled to it (`travelToProjectRef`) because React Flow holds only the ACTIVE project's+// nodes. Travelling is correct for a verb that needs live canvas state; for an OPEN it is a+// screen hijack on a background agent's say-so — the tab switches and the target project's saved+// viewport is applied, so the camera appears to jump and zoom (present since 2026-08-11, cecb4dfe,+// first shipped in v0.2.43). What cecb4dfe fixed must not regress: an agent in another project is+// still ANSWERED, never rejected as "not a control-capable agent".+//+// The mechanism is not new. `--project`-targeted opens (issue #338, spec §2.2) already insert into+// a non-active project without travelling: build the node, MOVE its launch command into+// `pendingLaunch` (`armForColdOpen`), upsert it through `applyNodeMutation`, persist with+// `writeDisk`, and tell the caller the session starts when that project is next viewed. This+// module is the pure half of applying that same path to an open whose OWN project is not active.+//+// Everything here is a decision, never a mutation: Canvas wires the store calls. Same reasoning as+// controlRouting.ts / projectOpen.ts / pendingLaunch.ts — vitest runs in the node environment, so+// the React component is not testable and these are.++import { rootPositionIn, type PlacedNode } from './projectOpen'++/** A serialized node, as the projects store keeps them for non-active projects. Structural subset+ * of `CanvasNodeState` — deliberately not the type itself, so tests can build one in a line. */+export interface ColdNode {+ id: string+ kind?: string+ title?: string+ parentId?: string+ position: { x: number; y: number }+ size?: { width: number; height: number }+ cwd?: string+ agentId?: string+ accountId?: string+ tags?: string[]+ worktree?: { path?: string }+}++const asPlaced = (n: ColdNode): PlacedNode => ({+ id: n.id,+ parentId: n.parentId,+ position: n.position,+ size: n.size+})++const widthOf = (n: ColdNode): number => n.size?.width ?? 600+const heightOf = (n: ColdNode): number => n.size?.height ?? 400++/**+ * Which agent (if any) runs in a stored node — the serialized counterpart of Canvas's `agentIdOf`,+ * including its legacy `tags:['claude']` leg and its agent-status fallback (a hand-launched CLI in+ * a plain terminal is known nowhere else). The status lookup is injected rather than imported so+ * this stays pure.+ */+export function storedAgentIdOf(+ node: ColdNode | undefined,+ statusAgentId?: (id: string) => string | undefined+): string | undefined {+ if (!node || (node.kind ?? 'terminal') !== 'terminal') return undefined+ return (+ node.agentId ??+ ((node.tags ?? []).includes('claude') ? 'claude' : undefined) ??+ statusAgentId?.(node.id)+ )+}++/**+ * `--group` against a project that is not on screen. It must name an existing GROUP FRAME in the+ * SAME project as the source — the ids `--group` and `--after` speak are project-local, and here+ * (unlike `--project`, which refuses both flags outright) the target project IS the caller's own,+ * so they are resolvable rather than out of reach.+ */+export function coldResolveGroup(+ nodes: readonly ColdNode[],+ groupId: string | undefined,+ verb: string+): { ok: true; groupId?: string } | { ok: false; error: string } {+ if (!groupId) return { ok: true }+ const g = nodes.find((n) => n.id === groupId)+ if (!g || (g.kind ?? 'terminal') !== 'group') {+ return { ok: false, error: `${verb}: --group must name an existing group frame` }+ }+ return { ok: true, groupId }+}++/**+ * The cwd a node opened into a frame inherits, read off the SERIALIZED tree: the nearest ancestor+ * frame that states a worktree path, else one that states a cwd. Mirrors Canvas's+ * `cwdForNewNodeIn`, with two deliberate differences, both forced by the frame not being on screen:+ *+ * - **No staleness check.** `useWorktrees` is epoch-scoped to the ACTIVE project, so for any other+ * project we simply do not know whether a bound worktree directory still exists. Answering+ * "unknown ⇒ not stale" is the same answer the persisted nodes already carry (every node created+ * in that frame before today holds the same path), so a cold open is no worse off than the+ * canvas it is writing into.+ * - **No SSH exclusion by project.** The caller passes `sshProject`; a worktree path was computed+ * from the LOCAL data dir and means nothing on a host, exactly as `cwdForNewNodeIn` says.+ */+export function coldGroupCwd(+ nodes: readonly ColdNode[],+ groupId: string | undefined,+ sshProject: boolean+): string | undefined {+ const seen = new Set<string>()+ let currentId = groupId+ while (currentId && !seen.has(currentId)) {+ seen.add(currentId)+ const parent = nodes.find((n) => n.id === currentId)+ if (!parent) return undefined+ if (parent.worktree?.path && !sshProject) return parent.worktree.path+ if (parent.cwd) return parent.cwd+ currentId = parent.parentId+ }+ return undefined+}++/**+ * `--after` against a stored project. Same guardrail as Canvas's `resolveAfter`, and it is the+ * whole point of the flag: only a node running a hook-REPORTING agent may be waited on, because+ * `launchesToFire` cannot tell "will never report" from "has not reported yet" — waiting on a plain+ * terminal would hold the dependent forever. Deduped, since `--after a,a` is one wait and two dep+ * ropes for one pair would collide on a single id.+ */+export function coldResolveAfter(+ nodes: readonly ColdNode[],+ after: string | undefined,+ verb: string,+ hasHooksFor: (agentId: string) => boolean,+ statusAgentId?: (id: string) => string | undefined+): { ok: true; after?: string[] } | { ok: false; error: string } {+ if (!after) return { ok: true }+ const ids = [...new Set(after.split(',').map((s) => s.trim()).filter(Boolean))]+ if (!ids.length) return { ok: true }+ for (const depId of ids) {+ const dep = nodes.find((n) => n.id === depId)+ if (!dep) return { ok: false, error: `${verb}: --after names no existing node (${depId})` }+ const agent = storedAgentIdOf(dep, statusAgentId)+ if (!agent || !hasHooksFor(agent)) {+ return {+ ok: false,+ error: `${verb}: --after ${depId} is not an agent session that reports when it is done`+ }+ }+ }+ return { ok: true, after: ids }+}++/**+ * Where the i-th opened node lands when the source IS in this project: the same geometry the live+ * path's `placeBelow` uses (below the source, fanned right), computed from the source's PERSISTED+ * size and resolved to ROOT space so a source sitting inside a frame still places correctly.+ * Returns a CENTER point — the factories' `center` parameter.+ */+export function coldPlaceBelow(+ nodes: readonly ColdNode[],+ source: ColdNode,+ i: number+): { x: number; y: number } {+ const abs = rootPositionIn(nodes.map(asPlaced), asPlaced(source))+ return {+ x: abs.x + widthOf(source) / 2 + i * 460,+ y: abs.y + heightOf(source) + 80 + 210+ }+}++// Grid geometry for nodes opened INTO a group frame. Exported so Canvas's LIVE path uses these+// exact numbers too — the cold and live placements are the same layout, and two copies of a+// magic-number grid drift into two layouts.+export const GROUP_PAD_X = 24+export const GROUP_PAD_TOP = 56+export const GROUP_GAP = 24++export function groupSlot(slot: number, w: number, h: number): { x: number; y: number } {+ return {+ x: GROUP_PAD_X + (slot % 2) * (w + GROUP_GAP),+ y: GROUP_PAD_TOP + Math.floor(slot / 2) * (h + GROUP_GAP)+ }+}++export function groupSizeFor(+ children: number,+ w: number,+ h: number+): { width: number; height: number } {+ const cols = Math.min(2, Math.max(1, children))+ const rows = Math.max(1, Math.ceil(children / 2))+ return {+ width: GROUP_PAD_X * 2 + cols * w + (cols - 1) * GROUP_GAP,+ height: GROUP_PAD_TOP + rows * h + (rows - 1) * GROUP_GAP + GROUP_PAD_X+ }+}++/** How many direct children a stored frame already holds — the `existing` offset for `groupSlot`. */+export function coldGroupChildCount(nodes: readonly ColdNode[], groupId: string): number {+ return nodes.filter((n) => n.parentId === groupId).length+}++/**+ * The reply sentence for a session that was opened into a project the user is not looking at.+ *+ * ONE builder, used by BOTH cold-open sites (`--project` into another project, and this module's+ * own-project cold open), so an orchestrator never has to learn two phrasings for one outcome. The+ * `closed` clause is the only variation and it is additive: a closed project's canvas is still+ * "next viewed", it just has to be reopened first, and an agent that is told nothing would report a+ * session as started that has no process behind it.+ */+export function coldOpenMessage(+ count: number,+ what: string,+ projectName: string,+ ids: readonly string[],+ opts: { closed?: boolean } = {}+): string {+ return (+ `opened ${count} ${what} session(s) in "${projectName}" (${ids.join(', ')}) — ` ++ 'queued; starts when that project is next viewed' ++ (opts.closed ? ' (that project is closed — reopen it from the welcome screen)' : '')+ )+}diff --git a/src/renderer/lib/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.tsindex 5ccab3331..ba93786e7 100644--- a/src/renderer/lib/controlRouting.test.ts+++ b/src/renderer/lib/controlRouting.test.ts@@ -2,6 +2,8 @@ import { describe, it, expect } from 'vitest'import {routeControlSource,needsLiveCanvas,+ canColdOpen,+ controlVerbSetsForTests,sourceIsControlCapable,storedNodeListing,answerBrowserResolve,@@ -102,6 +104,74 @@ describe('needsLiveCanvas', () => {})})+describe('canColdOpen — an OPEN is answered out of the store, not by moving the user', () => {+ it('is true for exactly the three node-opening verbs', () => {+ expect(canColdOpen('open-terminal')).toBe(true)+ expect(canColdOpen('open-claude')).toBe(true)+ expect(canColdOpen('open-agent')).toBe(true)+ })++ it('is false for every verb that acts on nodes which already exist', () => {+ // These read live canvas state the serialized copy does not carry — measured sizes, worktree+ // staleness, the React Flow edge arrays — so they keep travelling. Widening this set is a+ // behaviour change per verb, never a tidy-up.+ for (const verb of [+ 'write',+ 'close',+ 'group',+ 'ungroup',+ 'move',+ 'arrange',+ 'align',+ 'link',+ 'rename',+ 'color',+ 'verify',+ 'spawn-team',+ 'open-worktree',+ 'open-browser',+ 'browser',+ 'show-image',+ 'show-video',+ 'show-web',+ 'board',+ 'assign'+ ]) {+ expect(canColdOpen(verb), verb).toBe(false)+ }+ })++ it('still NEEDS a canvas — cold-openable is a narrower claim than store-answered', () => {+ // The whole reason this is a second set: `needsLiveCanvas` stays TRUE for an open (it does+ // need somewhere to put the node), it just does not need the LIVE one. Collapsing the two+ // sets would send `open-claude` down the `list` branch and answer it with a node listing.+ for (const verb of ['open-terminal', 'open-claude', 'open-agent']) {+ expect(needsLiveCanvas(verb), verb).toBe(true)+ expect(canColdOpen(verb), verb).toBe(true)+ }+ })++ it('the two sets are DISJOINT', () => {+ const { storeAnswered, coldOpenable } = controlVerbSetsForTests()+ expect(storeAnswered.filter((v) => coldOpenable.includes(v))).toEqual([])+ // …and neither is empty, so the assertion above cannot pass vacuously.+ expect(storeAnswered.length).toBeGreaterThan(0)+ expect(coldOpenable.length).toBeGreaterThan(0)+ })++ it('does NOT change which project answers — routing is still by source (cecb4dfe stands)', () => {+ // The regression this fix must not cause: cecb4dfe made an agent OUTSIDE the active project+ // answerable at all (before it, the active canvas had never heard of the node and reported+ // "not a control-capable agent"). Cold-opening changes only HOW the owning project is+ // written to, never WHETHER it is found.+ const projects = [P('p-active', [{ id: 'a1' }]), P('p-other', [{ id: 'b1' }])]+ expect(routeControlSource(projects, 'p-active', 'b1')).toEqual({+ kind: 'switch',+ projectId: 'p-other'+ })+ })+})+describe('sourceIsControlCapable', () => {it('does not relabel a plain terminal node as Claude', () => {expect(sourceIsControlCapable(undefined)).toBe(false)diff --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.tsindex a4dbfd3db..1281e7380 100644--- a/src/renderer/lib/controlRouting.ts+++ b/src/renderer/lib/controlRouting.ts@@ -128,6 +128,49 @@ export function needsLiveCanvas(verb: string): boolean {return !STORE_ANSWERED_VERBS.has(verb)}+/**+ * Verbs that CREATE a session and can therefore be answered by writing into the owning project's+ * SERIALIZED nodes instead of activating its tab.+ *+ * The relationship to `STORE_ANSWERED_VERBS` is the whole point, and the two sets are disjoint+ * (pinned in `controlRouting.test.ts`):+ *+ * - `STORE_ANSWERED_VERBS` — "no canvas is needed at either end". `list` reads names, `send`/+ * `reply` deliver into a tmux PANE, `sticky` rewrites a note, `open-project` acts on the+ * projects store. `needsLiveCanvas` is false for them and they never route at all.+ * - `COLD_OPENABLE_VERBS` — "a canvas IS needed, but the serialized one will do". The node these+ * verbs create is INERT until its project is next shown: the launch command moves into+ * `pendingLaunch` (`armForColdOpen`), the node is upserted through `applyNodeMutation`, and the+ * project's own mount path spawns the PTY and fires the armed launch. `needsLiveCanvas` stays+ * TRUE for them — they do need a canvas — which is exactly why this is a second, narrower set+ * rather than four more entries in the first one.+ *+ * WHY (the bug): routing is by SOURCE, so `open-claude` from an agent in a project the user is not+ * looking at travelled the user's view to that project — the camera jumped, the tab switched and+ * the target project's saved viewport was applied, all on a background agent's say-so. That is the+ * same G5 hijack `send`/`reply`/`sticky` are declared here to avoid; the difference is only that an+ * open needs somewhere to put the node, and a project's serialized nodes are somewhere.+ *+ * Deliberately NOT here: every verb that acts on nodes that already exist (`write`, `close`,+ * `group`, `move`, `arrange`, `align`, `verify`, `spawn-team`, `open-worktree`, `open-browser`,+ * `show-*`). They read live canvas state — measured node sizes, worktree staleness, the React Flow+ * edge arrays — that the serialized copy does not carry, so they keep travelling.+ */+const COLD_OPENABLE_VERBS: ReadonlySet<string> = new Set([+ 'open-terminal',+ 'open-claude',+ 'open-agent'+])++export function canColdOpen(verb: string): boolean {+ return COLD_OPENABLE_VERBS.has(verb)+}++/** Test-only view of the two sets, so their disjointness can be asserted rather than eyeballed. */+export function controlVerbSetsForTests(): { storeAnswered: string[]; coldOpenable: string[] } {+ return { storeAnswered: [...STORE_ANSWERED_VERBS], coldOpenable: [...COLD_OPENABLE_VERBS] }+}+/*** The capability half of the guard: may a session in this node drive the canvas?*diff --git a/src/renderer/lib/projectOpen.ts b/src/renderer/lib/projectOpen.tsindex dbe7a5118..828e07fa2 100644--- a/src/renderer/lib/projectOpen.ts+++ b/src/renderer/lib/projectOpen.ts@@ -234,6 +234,19 @@ function rootPosition(n: PlacedNode, byId: Map<string, PlacedNode>): { x: numberreturn { x, y }}+/**+ * A stored node's ROOT-space position — the public face of `rootPosition`, so the cold-open+ * planner does not need a third copy of a parent walk this repo already carries two of.+ */+export function rootPositionIn(+ nodes: readonly PlacedNode[],+ node: PlacedNode+): { x: number; y: number } {+ const byId = new Map<string, PlacedNode>()+ for (const n of nodes) if (n.id) byId.set(n.id, n)+ return rootPosition(node, byId)+}+/*** Where a node opened INTO another project lands (spec §2.2): centered below the lowest existing* node, because `placeBelow(src)` is meaningless in a project that does not contain the source.diff --git a/src/renderer/state/projects.links.test.ts b/src/renderer/state/projects.links.test.tsnew file mode 100644index 000000000..125f71e7c--- /dev/null+++ b/src/renderer/state/projects.links.test.ts@@ -0,0 +1,90 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { useProjects } from './projects'+import type { BridgeLink } from '@shared/types'++const link = (source: string, target: string, prefix = 'bridge'): BridgeLink => ({+ id: `${prefix}-${source}-${target}`,+ source,+ target+})++beforeEach(() => {+ useProjects.getState().hydrate({ version: 2, activeProjectId: '', projects: [] })+})++/**+ * `appendCanvasLinks` is the EDGE counterpart of `applyNodeMutation`, and it exists for the same+ * reason: React Flow holds only the active project's edges, so a cold open (canvas control's+ * `open-*` answered out of a non-active project's serialized nodes) has nowhere else to put the+ * opener's rope and the fan-in bridge it owes. Without it a spawned team would be a write-only+ * fan-out — the thing the `link` work exists to have ended.+ */+describe('appendCanvasLinks', () => {+ it('appends bridges and ropes to a project that is not active', () => {+ const p = useProjects.getState().addProject('p')+ useProjects.getState().appendCanvasLinks(p.id, {+ bridges: [link('a', 'b')],+ ropes: [link('a', 'b', 'ctrl')]+ })+ const got = useProjects.getState().getProject(p.id)+ expect(got?.bridges).toEqual([link('a', 'b')])+ expect(got?.ropes).toEqual([link('a', 'b', 'ctrl')])+ })++ it('keeps what is already there', () => {+ const p = useProjects.getState().addProject('p')+ useProjects+ .getState()+ .commitCanvas(p.id, [], { x: 0, y: 0, zoom: 1 }, [link('x', 'y')], [link('x', 'y', 'ctrl')])+ useProjects.getState().appendCanvasLinks(p.id, { bridges: [link('a', 'b')] })+ const got = useProjects.getState().getProject(p.id)+ expect(got?.bridges?.map((e) => e.id)).toEqual(['bridge-x-y', 'bridge-a-b'])+ expect(got?.ropes?.map((e) => e.id)).toEqual(['ctrl-x-y'])+ })++ it('dedupes by ENDPOINT PAIR, in either direction — one relationship, one edge', () => {+ // `planBridges` mints `bridge-<source>-<target>` and a rope is `ctrl-<source>-<target>`, so id+ // equality alone would let a repeated open stack duplicate arrows between the same two nodes.+ const p = useProjects.getState().addProject('p')+ useProjects.getState().appendCanvasLinks(p.id, { bridges: [link('a', 'b')] })+ useProjects.getState().appendCanvasLinks(p.id, { bridges: [link('b', 'a', 'other')] })+ expect(useProjects.getState().getProject(p.id)?.bridges).toEqual([link('a', 'b')])+ })++ it('dedupes WITHIN one call too', () => {+ const p = useProjects.getState().addProject('p')+ useProjects+ .getState()+ .appendCanvasLinks(p.id, { bridges: [link('a', 'b'), link('a', 'b'), link('a', 'c')] })+ expect(useProjects.getState().getProject(p.id)?.bridges?.map((e) => e.id)).toEqual([+ 'bridge-a-b',+ 'bridge-a-c'+ ])+ })++ it('keeps ropes and bridges in SEPARATE arrays — a rope and the bridge it covers coexist', () => {+ // `hiddenLinkIds` hides the bridge under the rope at render time; they are two facts (lineage+ // vs readable context) and collapsing them here would lose the link when the rope is deleted.+ const p = useProjects.getState().addProject('p')+ useProjects.getState().appendCanvasLinks(p.id, {+ bridges: [link('a', 'b')],+ ropes: [link('a', 'b', 'ctrl')]+ })+ expect(useProjects.getState().getProject(p.id)?.bridges).toHaveLength(1)+ expect(useProjects.getState().getProject(p.id)?.ropes).toHaveLength(1)+ })++ it('leaves the field ABSENT when nothing is appended', () => {+ // A project that never had bridges must not gain an empty array — the shared project.json is+ // committed, and an empty key is a diff for everyone on the repo.+ const p = useProjects.getState().addProject('p')+ useProjects.getState().appendCanvasLinks(p.id, { ropes: [link('a', 'b', 'ctrl')] })+ expect(useProjects.getState().getProject(p.id)?.bridges).toBeUndefined()+ })++ it('is a no-op for an unknown project', () => {+ const before = useProjects.getState().projects+ useProjects.getState().appendCanvasLinks('nope', { bridges: [link('a', 'b')] })+ expect(useProjects.getState().projects).toEqual(before)+ })+})diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.tsindex cd1eafe43..24efa589f 100644--- a/src/renderer/state/projects.ts+++ b/src/renderer/state/projects.ts@@ -19,6 +19,9 @@ import { recordCapabilityAck, type CapabilityAnswer } from '@shared/project-capaimport { applyCanvasMutation, createProject, reorderGroupWithinParent } from './workspace'import { markWorkspaceDirty } from './workspaceDirty'import { folderName } from '../lib/projectOpen'+// One order-independent key for an edge's endpoints — the SAME rule `hiddenLinkIds` uses, so a+// rope and the bridge it covers are recognized as one relationship here too.+import { pairKey as bridgePairKey } from '../lib/noteLink'interface ProjectsState {projects: Project[]@@ -106,6 +109,15 @@ interface ProjectsState {bridges?: BridgeLink[],ropes?: BridgeLink[]): void+ /**+ * Appends context bridges / control ropes to a project that is loaded but NOT active — the edge+ * counterpart of `applyNodeMutation`, and for the same reason: React Flow holds only the active+ * project's edges, so a cold open (canvas control's `open-*` answered out of the store) has+ * nowhere else to put the opener's rope and the fan-in bridge it owes. Deduped by edge id AND by+ * endpoint pair, since `planBridges` mints `bridge-<source>-<target>` while a rope is+ * `ctrl-<source>-<target>` — two ids, one relationship each. No-op for an unknown project.+ */+ appendCanvasLinks(projectId: string, links: { bridges?: BridgeLink[]; ropes?: BridgeLink[] }): void/*** Applies ONE peer canvas mutation to a project's serialized nodes — the path for a project* that is loaded but NOT active (React Flow only holds the active project's nodes). Returns@@ -458,6 +470,30 @@ export const useProjects = create<ProjectsState>((set, get) => ({}))},+ appendCanvasLinks(projectId, links) {+ const add = (existing: BridgeLink[] | undefined, incoming: BridgeLink[] | undefined) => {+ if (!incoming?.length) return existing+ const kept = existing ?? []+ const seenId = new Set(kept.map((e) => e.id))+ const seenPair = new Set(kept.map((e) => bridgePairKey(e.source, e.target)))+ const fresh = incoming.filter((e) => {+ const pair = bridgePairKey(e.source, e.target)+ if (seenId.has(e.id) || seenPair.has(pair)) return false+ seenId.add(e.id)+ seenPair.add(pair)+ return true+ })+ return fresh.length ? [...kept, ...fresh] : existing+ }+ set((s) => ({+ projects: s.projects.map((p) =>+ p.id === projectId+ ? { ...p, bridges: add(p.bridges, links.bridges), ropes: add(p.ropes, links.ropes) }+ : p+ )+ }))+ },+applyNodeMutation(projectId, mutation) {if (!get().projects.some((p) => p.id === projectId)) return falseset((s) => ({