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(server): enable headless canvas organization
freshjuicez0d1a55f6d956
diff --git a/src/renderer/lib/noteLink.ts b/src/renderer/lib/noteLink.tsindex 1cfaaec29..2b4a4b697 100644--- a/src/renderer/lib/noteLink.ts+++ b/src/renderer/lib/noteLink.ts@@ -2,96 +2,23 @@// agent nodes vs. note link between a sticky and a terminal), build the one-shot push// message a note link injects into an agent session, and re-export the link-map builders.// Kept free of React/store imports so the connection matrix is unit-testable.-import type { BridgeLink } from '@shared/types'import { oneLine } from '@shared/one-line'+import {+ classifyLink,+ planBridges,+ type LinkEndpoint+} from '@shared/canvas-link'-export interface LinkEndpoint {- /** React Flow node type: 'terminal' | 'sticky' | 'editor' | … */- kind: string- /** Terminal node whose agent is CONTEXT_LINK_CAPABLE (claude/codex/gemini). */- contextCapable: boolean-}--export type LinkKind = 'context' | 'note'--/** Decide what kind of link (if any) a new edge between two nodes forms. */-export function classifyLink(a: LinkEndpoint, b: LinkEndpoint): LinkKind | null {- const stickies = (a.kind === 'sticky' ? 1 : 0) + (b.kind === 'sticky' ? 1 : 0)- if (stickies === 0) return a.contextCapable && b.contextCapable ? 'context' : null- if (stickies === 2) return null- const other = a.kind === 'sticky' ? b : a- return other.kind === 'terminal' ? 'note' : null-}--/** One node the plan refused to link, with the reason to report back to the caller. */-export interface SkippedBridge {- id: string- why: string-}--export interface BridgePlan {- /** Edges to append (already deduped against `existing` AND within the batch). */- edges: BridgeLink[]- linked: string[]- skipped: SkippedBridge[]-}--/**- * Plan the link edges connecting `fromId` to each of `targetIds` — the batch form of what- * onConnect does for one hand-drawn edge, used by the canvas-control `link` verb and by the- * open-agent / spawn-team fan-out (which link every session they open back to the opener).- *- * Pure so the refusal matrix is testable: the callers live inside Canvas.tsx, where node- * lookup is a ref read and the result is a setState. `lookup` is injected because a caller- * that links nodes it created in the SAME tick cannot resolve them off the canvas yet- * (setNodes is async), and `existing` is passed in rather than read, so a batch also dedupes- * against itself and not just against what is already on screen.- */-export function planBridges(- fromId: string,- targetIds: string[],- lookup: (id: string) => LinkEndpoint | null,- existing: readonly { source: string; target: string }[]-): BridgePlan {- const edges: BridgeLink[] = []- const linked: string[] = []- const skipped: SkippedBridge[] = []- const se = lookup(fromId)- const linkedAlready = (a: string, b: string) =>- [...existing, ...edges].some(- (e) => (e.source === a && e.target === b) || (e.source === b && e.target === a)- )- for (const tid of targetIds) {- if (tid === fromId) {- skipped.push({ id: tid, why: 'same node' })- continue- }- const te = lookup(tid)- if (!se || !te) {- skipped.push({ id: tid, why: 'no such node' })- continue- }- const kind = classifyLink(se, te)- if (!kind) {- skipped.push({- id: tid,- why: 'not linkable (needs two context-capable agents, or a sticky + terminal)'- })- continue- }- // Note edges are stored sticky→terminal regardless of the direction they were requested- // in, so styling and the link map can key off "source is sticky" (mirrors onConnect).- const source = kind === 'note' && te.kind === 'sticky' ? tid : fromId- const target = source === fromId ? tid : fromId- if (linkedAlready(source, target)) {- skipped.push({ id: tid, why: 'already linked' })- continue- }- edges.push({ id: `bridge-${source}-${target}`, source, target })- linked.push(tid)- }- return { edges, linked, skipped }-}+// Kept as renderer-facing re-exports so existing canvas and tests retain one import surface while+// Server Edition consumes the same pure planner directly from shared.+export {+ classifyLink,+ planBridges,+ type BridgePlan,+ type LinkEndpoint,+ type LinkKind,+ type SkippedBridge+} from '@shared/canvas-link'/** Order-independent key for an edge's endpoints (a↔b and b↔a are the same connection). */export function pairKey(a: string, b: string): string {diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.tsindex 21d86f03a..e9abe8098 100644--- a/src/server/canvas-control.ts+++ b/src/server/canvas-control.ts@@ -168,6 +168,9 @@ export async function initServerCanvasControl(factory.openTerminal(sourceNodeId, args, verified),openAgent: (sourceNodeId, args, verified) => factory.openAgent(sourceNodeId, args, verified),close: (sourceNodeId, args, verified) => factory.close(sourceNodeId, args, verified),+ link: (sourceNodeId, args, verified) => factory.link(sourceNodeId, args, verified),+ group: (sourceNodeId, args) => factory.group(sourceNodeId, args),+ rename: (sourceNodeId, args) => factory.rename(sourceNodeId, args),sticky: (sourceNodeId, args) => factory.sticky(sourceNodeId, args),deliver: async (input) => (await deliverFromControl(input, messaging)).reply}diff --git a/src/server/control-unsupported.test.ts b/src/server/control-unsupported.test.tsindex c63e3ca9c..a0de1318a 100644--- a/src/server/control-unsupported.test.ts+++ b/src/server/control-unsupported.test.ts@@ -176,6 +176,9 @@ describe('the enabled Server Edition handler parses and dispatches the v1 surfacopenTerminal: vi.fn(async () => ({ ok: true as const, result: { id: 'term-new' } })),openAgent: vi.fn(async () => ({ ok: true as const, result: { id: 'agent-new' } })),close: vi.fn(async () => ({ ok: true as const, result: { id: 'closed' } })),+ link: vi.fn(async () => ({ ok: true as const, result: { linked: ['term-target'] } })),+ group: vi.fn(async () => ({ ok: true as const, result: { groupId: 'group-new' } })),+ rename: vi.fn(async () => ({ ok: true as const, result: { id: 'renamed' } })),sticky: vi.fn(async () => ({ ok: true as const, result: { id: 'sticky-new' } })),deliver: vi.fn(async () => ({ ok: true as const, message: 'queued' }))})@@ -258,9 +261,42 @@ describe('the enabled Server Edition handler parses and dispatches the v1 surfac})})+ it('dispatches headless link, group, and rename while preserving link identity', async () => {+ const a = actions()+ const handler = createServerEditionControlHandler(a)+ await handler({+ verb: 'link',+ nodeId: 'term-source',+ args: { from: 'term-a', to: 'term-b' },+ verified: true+ })+ await handler({+ verb: 'group',+ nodeId: 'term-source',+ args: { nodes: 'term-a,term-b', label: 'Pair' },+ verified: true+ })+ await handler({+ verb: 'rename',+ nodeId: 'term-source',+ args: { node: 'term-a', title: 'A' },+ verified: true+ })+ expect(a.link).toHaveBeenCalledWith(+ 'term-source',+ { from: 'term-a', to: 'term-b' },+ true+ )+ expect(a.group).toHaveBeenCalledWith('term-source', {+ nodes: 'term-a,term-b',+ label: 'Pair'+ })+ expect(a.rename).toHaveBeenCalledWith('term-source', { node: 'term-a', title: 'A' })+ })+it('keeps every deferred or unknown verb a clean permanent edition refusal', async () => {const handler = createServerEditionControlHandler(actions())- for (const verb of ['list', 'browser', 'open-project', 'not-a-verb']) {+ for (const verb of ['list', 'browser', 'open-project', 'write', 'not-a-verb']) {const reply = await handler({ verb, nodeId: 'term-source', args: {}, verified: true })expect(reply, verb).toMatchObject({ ok: false, error: CONTROL_UNSUPPORTED_ERROR })expect(reply.message, verb).toContain('do not retry')diff --git a/src/server/control-unsupported.ts b/src/server/control-unsupported.tsindex 3b717057e..2b8d13d54 100644--- a/src/server/control-unsupported.ts+++ b/src/server/control-unsupported.ts@@ -79,6 +79,13 @@ export interface ServerEditionControlActions {args: Record<string, string>,verified: boolean): Promise<ServerControlReply>+ link(+ sourceNodeId: string,+ args: Record<string, string>,+ verified: boolean+ ): Promise<ServerControlReply>+ group(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply>+ rename(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply>sticky(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply>deliver(input: {verb: 'send' | 'reply' | 'notify'@@ -92,6 +99,9 @@ const SERVER_V1_VERBS: ReadonlySet<string> = new Set(['open-terminal','open-agent','close',+ 'link',+ 'group',+ 'rename','send','reply','notify',@@ -137,6 +147,12 @@ export function createServerEditionControlHandler(actions: ServerEditionControlAreturn actions.openAgent(nodeId, command.args, verified)case 'close':return actions.close(nodeId, command.args, verified)+ case 'link':+ return actions.link(nodeId, command.args, verified)+ case 'group':+ return actions.group(nodeId, command.args)+ case 'rename':+ return actions.rename(nodeId, command.args)case 'sticky':return actions.sticky(nodeId, command.args)case 'send':diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.tsindex edc73c504..4232fbd59 100644--- a/src/server/headless-node-factory.test.ts+++ b/src/server/headless-node-factory.test.ts@@ -257,6 +257,214 @@ describe('HeadlessNodeFactory', () => {expect(pty.destroys).toEqual([])})+ it('links the caller to an existing node, persists the read graph, and fans out without writing to a pane', async () => {+ const reply = await factory.link('term-source', { to: 'term-upstream' }, true)++ expect(reply).toMatchObject({+ ok: true,+ result: { from: 'term-source', linked: ['term-upstream'], skipped: [] }+ })+ expect(pty.sends).toEqual([])+ const workspace = await new WorkspaceStore().load({ sideline: false })+ expect(workspace.projects[0].bridges).toEqual([+ {+ id: 'bridge-term-source-term-upstream',+ source: 'term-source',+ target: 'term-upstream'+ }+ ])+ const projectFile = JSON.parse(+ fs.readFileSync(path.join(projectDir, '.nodeterm', 'project.json'), 'utf8')+ ) as { bridges?: Array<{ source: string; target: string }> }+ expect(projectFile.bridges).toEqual([+ expect.objectContaining({ source: 'term-source', target: 'term-upstream' })+ ])+ expect(published).toEqual([])+ expect(publishedProjects.at(-1)?.bridges).toEqual(workspace.projects[0].bridges)+ })++ it('links two arbitrary existing nodes in the caller project', async () => {+ const workspace = await store.load({ sideline: false })+ workspace.projects[0].nodes.push(terminal('term-third', 'Third', 'gemini', 900))+ await store.save(workspace)++ await expect(+ factory.link('term-source', { from: 'term-upstream', to: 'term-third' }, true)+ ).resolves.toMatchObject({+ ok: true,+ result: { from: 'term-upstream', linked: ['term-third'] }+ })+ expect((await store.load({ sideline: false })).projects[0].bridges).toEqual([+ expect.objectContaining({ source: 'term-upstream', target: 'term-third' })+ ])+ expect(pty.sends).toEqual([])+ })++ it('refuses unverified and cross-project link endpoints without a partial graph edit', async () => {+ await expect(factory.link('term-source', { to: 'term-upstream' }, false)).resolves.toMatchObject({+ ok: false,+ error: expect.stringContaining('link-identity-refused')+ })++ const workspace = await store.load({ sideline: false })+ const otherDir = path.join(dataDir, 'other-project')+ fs.mkdirSync(otherDir, { recursive: true })+ workspace.projects.push({+ id: 'project-2',+ name: 'Other',+ color: '#32d74b',+ cwd: otherDir,+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [terminal('term-other-project', 'Elsewhere', 'claude')],+ bridges: [],+ ropes: []+ })+ await store.save(workspace)++ await expect(+ factory.link('term-source', { to: 'term-upstream,term-other-project' }, true)+ ).resolves.toMatchObject({+ ok: false,+ error: expect.stringContaining('link-project-refused')+ })+ expect((await store.load({ sideline: false })).projects[0].bridges).toEqual([])+ expect(publishedProjects).toEqual([])+ expect(pty.sends).toEqual([])+ })++ it('wraps loose nodes in a labeled persisted group and fans out every structural mutation', async () => {+ const before = (await store.load({ sideline: false })).projects[0]+ const beforePositions = new Map(before.nodes.map((node) => [node.id, node.position]))+ const reply = await factory.group('term-source', {+ nodes: 'term-source,term-upstream',+ label: 'Director team'+ })+ expect(reply).toMatchObject({+ ok: true,+ result: {+ groupId: expect.stringMatching(/^group-/),+ grouped: ['term-source', 'term-upstream'],+ skipped: 0+ }+ })+ const groupId = (reply.result as { groupId: string }).groupId+ const project = (await new WorkspaceStore().load({ sideline: false })).projects[0]+ const group = project.nodes.find((node) => node.id === groupId)!+ expect(project.nodes[0]).toMatchObject({ id: groupId, kind: 'group' })+ expect(group.title).toBe('Director team')+ for (const id of ['term-source', 'term-upstream']) {+ const child = project.nodes.find((node) => node.id === id)!+ expect(child.parentId).toBe(groupId)+ expect({+ x: group.position.x + child.position.x,+ y: group.position.y + child.position.y+ }).toEqual(beforePositions.get(id))+ }+ expect(published.map((node) => node.id)).toEqual(+ expect.arrayContaining([groupId, 'term-source', 'term-upstream'])+ )+ expect(publishedProjects.at(-1)?.nodes.find((node) => node.id === groupId)?.title).toBe(+ 'Director team'+ )+ const projectFile = JSON.parse(+ fs.readFileSync(path.join(projectDir, '.nodeterm', 'project.json'), 'utf8')+ ) as { nodes: CanvasNodeState[] }+ expect(projectFile.nodes.find((node) => node.id === groupId)).toMatchObject({+ kind: 'group',+ title: 'Director team'+ })+ })++ it('refuses grouping across containers or across an ancestor boundary', async () => {+ const workspace = await store.load({ sideline: false })+ const frame: CanvasNodeState = {+ id: 'group-existing',+ kind: 'group',+ position: { x: 700, y: 20 },+ size: { width: 760, height: 560 },+ title: 'Existing frame',+ color: '#32d74b',+ group: null+ }+ const child = terminal('term-inside', 'Inside', 'gemini', 40)+ child.parentId = frame.id+ workspace.projects[0].nodes.unshift(frame)+ workspace.projects[0].nodes.push(child)+ await store.save(workspace)++ for (const nodes of ['term-inside,term-source', 'group-existing,term-inside']) {+ await expect(factory.group('term-source', { nodes })).resolves.toMatchObject({+ ok: false,+ error: expect.stringContaining('siblings in one container')+ })+ }+ const after = await store.load({ sideline: false })+ expect(after.projects[0].nodes.filter((node) => node.kind === 'group')).toHaveLength(1)+ expect(after.projects[0].nodes.find((node) => node.id === 'term-inside')?.parentId).toBe(+ 'group-existing'+ )+ expect(publishedProjects).toEqual([])+ })++ it('renames a node, group, and sticky durably without ever writing into their panes', async () => {+ const grouped = await factory.group('term-source', {+ nodes: 'term-source,term-upstream',+ label: 'Old group'+ })+ const groupId = (grouped.result as { groupId: string }).groupId+ const workspace = await store.load({ sideline: false })+ workspace.projects[0].nodes.push({+ id: 'sticky-status',+ kind: 'sticky',+ position: { x: 1200, y: 30 },+ size: { width: 240, height: 200 },+ title: 'Old note',+ color: '#ffd60a',+ group: null,+ text: 'ready'+ })+ await store.save(workspace)+ published.length = 0+ publishedProjects.length = 0++ await expect(+ factory.rename('term-source', { node: 'term-upstream', title: 'Reviewed\nUpstream' })+ ).resolves.toMatchObject({ ok: true })+ await expect(+ factory.rename('term-source', { node: groupId, title: 'Director group' })+ ).resolves.toMatchObject({ ok: true })+ await expect(+ factory.rename('term-source', { node: 'sticky-status', title: 'Round status' })+ ).resolves.toMatchObject({ ok: true })++ const project = (await new WorkspaceStore().load({ sideline: false })).projects[0]+ expect(project.nodes.find((node) => node.id === 'term-upstream')).toMatchObject({+ title: 'Reviewed Upstream',+ titleAuto: false+ })+ expect(project.nodes.find((node) => node.id === groupId)).toMatchObject({+ title: 'Director group',+ titleAuto: false+ })+ expect(project.nodes.find((node) => node.id === 'sticky-status')).toMatchObject({+ title: 'Round status',+ titleAuto: false+ })+ expect(published.map((node) => node.id)).toEqual([+ 'term-upstream',+ groupId,+ 'sticky-status'+ ])+ expect(publishedProjects).toHaveLength(3)+ expect(pty.sends).toEqual([])+ const projectFile = JSON.parse(+ fs.readFileSync(path.join(projectDir, '.nodeterm', 'project.json'), 'utf8')+ ) as { nodes: CanvasNodeState[] }+ expect(projectFile.nodes.find((node) => node.id === 'sticky-status')?.title).toBe(+ 'Round status'+ )+ })+it('places repeated spawns in the first free deterministic slots without overlapping busy nodes', async () => {const workspace = await store.load({ sideline: false })// Slot zero to the right of the source is already busy before any control request arrives.diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.tsindex 0d7df6960..dc4175f29 100644--- a/src/server/headless-node-factory.ts+++ b/src/server/headless-node-factory.ts@@ -2,6 +2,7 @@ import { randomBytes, randomUUID } from 'node:crypto'import { publishCanvasMutation } from '../core/canvas-sync'import { gateProjectTarget } from '../core/project-grants'+import { planBridges, type LinkEndpoint } from '../shared/canvas-link'import { applyStickyWrite, parseStickyArgs, resolveStickyRef } from '../shared/sticky-write'import type { WorkspaceStore } from '../core/workspace-store'import {@@ -76,6 +77,8 @@ const TERMINAL_SIZE = { width: 640, height: 440 }const STICKY_SIZE = { width: 240, height: 200 }const H_GAP = 80const V_GAP = 36+const GROUP_PAD = 28+const GROUP_HEADER = 34const AFTER_RETRY_MS = 500const AFTER_RETRY_LIMIT = 5const SERVER_AGENTS: ReadonlySet<string> = new Set(['claude', 'codex', 'gemini'])@@ -84,7 +87,7 @@ function token(): string {return randomBytes(4).toString('hex')}-function nextId(prefix: 'term' | 'sticky'): string {+function nextId(prefix: 'term' | 'sticky' | 'group'): string {return `${prefix}-${Date.now().toString(36)}-${token()}`}@@ -202,6 +205,166 @@ function addEdge(list: BridgeLink[], source: string, target: string, prefix: strlist.push({ id: edgeId(prefix, source, target), source, target })}+function nodeProjects(workspace: Workspace, nodeId: string): Project[] {+ return workspace.projects.filter((project) => project.nodes.some((node) => node.id === nodeId))+}++function headlessLinkEndpoint(+ node: CanvasNodeState,+ runtimeAgentId: ((nodeId: string) => string | undefined) | undefined+): LinkEndpoint {+ const agentId = node.kind === 'terminal' ? node.agentId ?? runtimeAgentId?.(node.id) : undefined+ return {+ kind: node.kind,+ contextCapable: !!agentId && canContextLink(agentId as AgentId)+ }+}++function isDescendant(+ nodes: readonly CanvasNodeState[],+ candidateId: string,+ ancestorId: string+): boolean {+ const byId = new Map(nodes.map((node) => [node.id, node]))+ const seen = new Set<string>()+ let current = byId.get(candidateId)+ while (current?.parentId && !seen.has(current.parentId)) {+ if (current.parentId === ancestorId) return true+ seen.add(current.parentId)+ current = byId.get(current.parentId)+ }+ return false+}++/** Persist frames before their descendants, matching React Flow's hydration requirement. */+function groupsFirst(nodes: CanvasNodeState[]): CanvasNodeState[] {+ const byId = new Map(nodes.map((node) => [node.id, node]))+ const emitted = new Set<string>()+ const visiting = new Set<string>()+ const groups: CanvasNodeState[] = []+ const emit = (node: CanvasNodeState): void => {+ if (emitted.has(node.id) || node.kind !== 'group') return+ if (visiting.has(node.id)) return+ visiting.add(node.id)+ const parent = node.parentId ? byId.get(node.parentId) : undefined+ if (parent?.kind === 'group') emit(parent)+ visiting.delete(node.id)+ if (!emitted.has(node.id)) {+ emitted.add(node.id)+ groups.push(node)+ }+ }+ nodes.forEach(emit)+ return [...groups, ...nodes.filter((node) => node.kind !== 'group')]+}++/** Re-fit one persisted group around its direct children without moving them in parent space. */+function fitGroupToChildren(+ nodes: CanvasNodeState[],+ groupId: string+): CanvasNodeState[] {+ const group = nodes.find((node) => node.id === groupId)+ if (!group || group.kind !== 'group') return nodes+ const children = nodes.filter((node) => node.parentId === groupId)+ if (!children.length) return nodes+ const absoluteX = (child: CanvasNodeState): number => group.position.x + child.position.x+ const absoluteY = (child: CanvasNodeState): number => group.position.y + child.position.y+ const minX = Math.min(...children.map(absoluteX))+ const minY = Math.min(...children.map(absoluteY))+ const maxX = Math.max(...children.map((child) => absoluteX(child) + child.size.width))+ const maxY = Math.max(...children.map((child) => absoluteY(child) + child.size.height))+ const x = minX - GROUP_PAD+ const y = minY - GROUP_PAD - GROUP_HEADER+ const size = {+ width: maxX - minX + GROUP_PAD * 2,+ height: maxY - minY + GROUP_PAD * 2 + GROUP_HEADER+ }+ return nodes.map((node) => {+ if (node.id === groupId) return { ...node, position: { x, y }, size }+ if (node.parentId === groupId) {+ return {+ ...node,+ position: { x: absoluteX(node) - x, y: absoluteY(node) - y }+ }+ }+ return node+ })+}++function fitAncestorChain(+ nodes: CanvasNodeState[],+ groupId: string | undefined+): CanvasNodeState[] {+ let next = nodes+ let currentId = groupId+ const seen = new Set<string>()+ while (currentId && !seen.has(currentId)) {+ seen.add(currentId)+ next = fitGroupToChildren(next, currentId)+ currentId = next.find((node) => node.id === currentId)?.parentId+ }+ return next+}++function groupPersistedNodes(+ nodes: CanvasNodeState[],+ ids: string[],+ groupIndex: number,+ label: string | undefined+): { nodes: CanvasNodeState[]; groupId: string; changed: CanvasNodeState[] } | null {+ const selected = new Set(ids)+ const members = nodes.filter((node) => selected.has(node.id))+ if (!members.length || new Set(members.map((node) => node.parentId ?? null)).size !== 1) {+ return null+ }+ if (+ members.some((member) =>+ members.some(+ (other) => other.id !== member.id && isDescendant(nodes, other.id, member.id)+ )+ )+ ) {+ return null+ }++ const minX = Math.min(...members.map((node) => node.position.x))+ const minY = Math.min(...members.map((node) => node.position.y))+ const maxX = Math.max(...members.map((node) => node.position.x + node.size.width))+ const maxY = Math.max(...members.map((node) => node.position.y + node.size.height))+ const x = minX - GROUP_PAD+ const y = minY - GROUP_PAD - GROUP_HEADER+ const parentId = members[0].parentId+ const group: CanvasNodeState = {+ id: nextId('group'),+ kind: 'group',+ position: { x, y },+ size: {+ width: maxX - minX + GROUP_PAD * 2,+ height: maxY - minY + GROUP_PAD * 2 + GROUP_HEADER+ },+ title: label || `Group ${groupIndex + 1}`,+ color: NODE_COLORS[groupIndex % NODE_COLORS.length],+ group: null,+ ...(parentId ? { parentId } : {})+ }+ const before = new Map(nodes.map((node) => [node.id, node]))+ const updated = nodes.map((node) =>+ selected.has(node.id)+ ? {+ ...node,+ parentId: group.id,+ position: { x: node.position.x - x, y: node.position.y - y }+ }+ : node+ )+ const next = groupsFirst(fitAncestorChain(groupsFirst([group, ...updated]), parentId))+ return {+ nodes: next,+ groupId: group.id,+ changed: next.filter((node) => !before.has(node.id) || before.get(node.id) !== node)+ }+}+function ptyOptions(project: Project, node: CanvasNodeState): PtyCreateOptions {return {cwd: node.cwd || project.cwd,@@ -421,6 +584,160 @@ export class HeadlessNodeFactory {})}+ link(+ sourceNodeId: string,+ args: Record<string, string>,+ verified: boolean+ ): Promise<ServerControlReply> {+ return this.runExclusive(async () => {+ const flagError = unsupportedFlags(args, new Set(['from', 'to']))+ if (flagError) return { ok: false, error: `link: ${flagError}` }+ if (!verified) {+ return {+ ok: false,+ error: 'link-identity-refused: Server Edition link requires verified node identity'+ }+ }++ const workspace = await this.deps.workspaceStore.load({ sideline: false })+ const source = sourceProject(workspace, sourceNodeId)+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {+ return { ok: false, error: 'source node is not a control-capable agent' }+ }++ const from = (args.from ?? sourceNodeId).trim()+ const targets = (args.to ?? '').split(',').map((id) => id.trim()).filter(Boolean)+ if (!targets.length) return { ok: false, error: 'link requires --to <id,id>' }++ // An arbitrary `--from` is allowed, but every endpoint still belongs to the caller's one+ // project. Refuse the whole request before appending anything if a named id resolves across+ // that boundary (or ambiguously in more than one saved project).+ for (const id of [from, ...targets]) {+ const projects = nodeProjects(workspace, id)+ if (projects.length && (projects.length !== 1 || projects[0].id !== source.project.id)) {+ return {+ ok: false,+ error: `link-project-refused: ${id} is not exclusively in the caller's project`+ }+ }+ }++ const byId = new Map(source.project.nodes.map((node) => [node.id, node]))+ if (!byId.has(from)) {+ return { ok: false, error: `link: --from names no existing node (${from})` }+ }+ const existing = [...(source.project.bridges ?? [])]+ const plan = planBridges(+ from,+ targets,+ (id) => {+ const node = byId.get(id)+ return node ? headlessLinkEndpoint(node, this.deps.agentIdOf) : null+ },+ existing+ )+ if (!plan.edges.length) {+ return {+ ok: false,+ error: `link: nothing linked — ${plan.skipped+ .map((skipped) => `${skipped.id}: ${skipped.why}`)+ .join('; ')}`+ }+ }++ source.project.bridges = [...existing, ...plan.edges]+ await this.deps.workspaceStore.save(workspace)+ // An edge-only change has no node mutation to publish; the full-project event is the fanout.+ this.publish(source.project, [])+ const note = plan.skipped.length+ ? ` (skipped ${plan.skipped.map((skipped) => `${skipped.id}: ${skipped.why}`).join('; ')})`+ : ''+ return {+ ok: true,+ message: `linked ${from} ↔ ${plan.linked.join(', ')}${note}`,+ result: { from, linked: plan.linked, skipped: plan.skipped }+ }+ })+ }++ group(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply> {+ return this.runExclusive(async () => {+ const flagError = unsupportedFlags(args, new Set(['nodes', 'label']))+ if (flagError) return { ok: false, error: `group: ${flagError}` }+ const workspace = await this.deps.workspaceStore.load({ sideline: false })+ const source = sourceProject(workspace, sourceNodeId)+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {+ return { ok: false, error: 'source node is not a control-capable agent' }+ }++ const ids = (args.nodes ?? '').split(',').map((id) => id.trim()).filter(Boolean)+ const resolvable = ids.filter((id) => source.project.nodes.some((node) => node.id === id))+ if (!resolvable.length) {+ return { ok: false, error: 'group: none of the given node ids exist' }+ }+ const grouped = groupPersistedNodes(+ source.project.nodes,+ resolvable,+ source.project.nodes.filter((node) => node.kind === 'group').length,+ args.label ? oneLine(args.label) : undefined+ )+ if (!grouped) {+ return {+ ok: false,+ error:+ 'group: nodes must be siblings in one container and may not include an ancestor with its descendant'+ }+ }++ source.project.nodes = grouped.nodes+ await this.deps.workspaceStore.save(workspace)+ this.publish(source.project, grouped.changed)+ const skipped = ids.length - resolvable.length+ const note = skipped ? ` (${skipped} unknown id(s) skipped)` : ''+ return {+ ok: true,+ message: `grouped ${resolvable.length} node(s) into ${grouped.groupId}${note}`,+ result: { groupId: grouped.groupId, grouped: resolvable, skipped }+ }+ })+ }++ rename(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply> {+ return this.runExclusive(async () => {+ const flagError = unsupportedFlags(args, new Set(['node', 'title']))+ if (flagError) return { ok: false, error: `rename: ${flagError}` }+ const workspace = await this.deps.workspaceStore.load({ sideline: false })+ const source = sourceProject(workspace, sourceNodeId)+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {+ return { ok: false, error: 'source node is not a control-capable agent' }+ }++ const id = (args.node ?? '').trim()+ const projects = nodeProjects(workspace, id)+ if (projects.length && (projects.length !== 1 || projects[0].id !== source.project.id)) {+ return {+ ok: false,+ error: `rename-project-refused: ${id} is not exclusively in the caller's project`+ }+ }+ const target = source.project.nodes.find((node) => node.id === id)+ if (!target) return { ok: false, error: `rename: no node with id ${id}` }++ const title = oneLine(args.title ?? '')+ const renamed = { ...target, title, titleAuto: false }+ source.project.nodes = source.project.nodes.map((node) =>+ node.id === id ? renamed : node+ )+ await this.deps.workspaceStore.save(workspace)+ // Metadata only. In particular, Server Edition never mirrors `/rename` into the pane.+ this.publish(source.project, [renamed])+ return { ok: true, message: `renamed ${id} to "${title}"` }+ })+ }+private open(sourceNodeId: string,verb: 'open-terminal' | 'open-agent',diff --git a/src/shared/canvas-link.ts b/src/shared/canvas-link.tsnew file mode 100644index 000000000..2652fd8c9--- /dev/null+++ b/src/shared/canvas-link.ts@@ -0,0 +1,88 @@+// Pure planning for persisted canvas links. Both the desktop renderer and the headless server+// use this exact refusal/deduplication matrix; neither shell may grow its own approximation.+import type { BridgeLink } from './types'++export interface LinkEndpoint {+ /** Canvas node kind: 'terminal' | 'sticky' | 'editor' | … */+ kind: string+ /** Terminal node whose agent is CONTEXT_LINK_CAPABLE (claude/codex/gemini). */+ contextCapable: boolean+}++export type LinkKind = 'context' | 'note'++/** Decide what kind of link (if any) a new edge between two nodes forms. */+export function classifyLink(a: LinkEndpoint, b: LinkEndpoint): LinkKind | null {+ const stickies = (a.kind === 'sticky' ? 1 : 0) + (b.kind === 'sticky' ? 1 : 0)+ if (stickies === 0) return a.contextCapable && b.contextCapable ? 'context' : null+ if (stickies === 2) return null+ const other = a.kind === 'sticky' ? b : a+ return other.kind === 'terminal' ? 'note' : null+}++/** One node the plan refused to link, with the reason to report back to the caller. */+export interface SkippedBridge {+ id: string+ why: string+}++export interface BridgePlan {+ /** Edges to append (already deduped against `existing` AND within the batch). */+ edges: BridgeLink[]+ linked: string[]+ skipped: SkippedBridge[]+}++/**+ * Plan the link edges connecting `fromId` to each of `targetIds`.+ *+ * The caller supplies node lookup and the already-persisted edges, so this stays independent of+ * React/store/server state. Note edges normalize to sticky→terminal; every pair dedupes in either+ * direction. Creating the edges has no delivery side effect: context is always read on demand.+ */+export function planBridges(+ fromId: string,+ targetIds: string[],+ lookup: (id: string) => LinkEndpoint | null,+ existing: readonly { source: string; target: string }[]+): BridgePlan {+ const edges: BridgeLink[] = []+ const linked: string[] = []+ const skipped: SkippedBridge[] = []+ const se = lookup(fromId)+ const linkedAlready = (a: string, b: string) =>+ [...existing, ...edges].some(+ (edge) =>+ (edge.source === a && edge.target === b) ||+ (edge.source === b && edge.target === a)+ )++ for (const targetId of targetIds) {+ if (targetId === fromId) {+ skipped.push({ id: targetId, why: 'same node' })+ continue+ }+ const te = lookup(targetId)+ if (!se || !te) {+ skipped.push({ id: targetId, why: 'no such node' })+ continue+ }+ const kind = classifyLink(se, te)+ if (!kind) {+ skipped.push({+ id: targetId,+ why: 'not linkable (needs two context-capable agents, or a sticky + terminal)'+ })+ continue+ }+ const source = kind === 'note' && te.kind === 'sticky' ? targetId : fromId+ const target = source === fromId ? targetId : fromId+ if (linkedAlready(source, target)) {+ skipped.push({ id: targetId, why: 'already linked' })+ continue+ }+ edges.push({ id: `bridge-${source}-${target}`, source, target })+ linked.push(targetId)+ }+ return { edges, linked, skipped }+}