Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(canvas-control): move nodes between frames + tidy inside a frame
enesd4375749ebdc
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.tsindex c4678aeec..d693f118e 100644--- a/src/main/canvas-control-core.test.ts+++ b/src/main/canvas-control-core.test.ts@@ -130,6 +130,20 @@ describe('parseControlRequest', () => {expect(isDestructiveVerb('rename')).toBe(false)})+ it('ungroup requires --group; move requires --nodes; neither is destructive', () => {+ expect(parseControlRequest('ungroup', {})).toEqual({ error: 'ungroup requires --group <id>' })+ expect(parseControlRequest('ungroup', { group: 'g1' })).toEqual({ verb: 'ungroup', args: { group: 'g1' } })+ expect(parseControlRequest('move', {})).toEqual({ error: 'move requires --nodes <id,id>' })+ // --group is optional on move (omitting it pulls the nodes out to the top level).+ expect(parseControlRequest('move', { nodes: 'n1,n2' })).toEqual({ verb: 'move', args: { nodes: 'n1,n2' } })+ expect(parseControlRequest('move', { nodes: 'n1', group: 'g2' })).toEqual({+ verb: 'move',+ args: { nodes: 'n1', group: 'g2' }+ })+ expect(isDestructiveVerb('ungroup')).toBe(false)+ expect(isDestructiveVerb('move')).toBe(false)+ })+it('board takes no required args and is not destructive', () => {expect(parseControlRequest('board', {})).toEqual({ verb: 'board', args: {} })expect(isDestructiveVerb('board')).toBe(false)@@ -163,7 +177,7 @@ describe('parseControlRequest', () => {it('instructions cover the verb set and the confirm caveat', () => {const body = buildCanvasControlInstructions('/tmp/nodeterm.sh')- for (const verb of ['list', 'open-agent', 'spawn-team', 'group', 'arrange', 'rename', 'write', 'close', 'board', 'assign']) {+ for (const verb of ['list', 'open-agent', 'spawn-team', 'group', 'ungroup', 'move', 'arrange', 'rename', 'write', 'close', 'board', 'assign']) {expect(body).toContain(verb)}expect(body.toLowerCase()).toContain('confirm')diff --git a/src/main/canvas-control-core.ts b/src/main/canvas-control-core.tsindex 279f6e7c3..50b6d6067 100644--- a/src/main/canvas-control-core.ts+++ b/src/main/canvas-control-core.ts@@ -12,6 +12,8 @@ export type ControlVerb =| 'show-web'| 'open-browser'| 'group'+ | 'ungroup'+ | 'move'| 'arrange'| 'align'| 'link'@@ -41,6 +43,8 @@ const VERBS: ControlVerb[] = ['show-web','open-browser','group',+ 'ungroup',+ 'move','arrange','align','link',@@ -81,6 +85,8 @@ export function parseControlRequest(if (v === 'open-browser' && !args.url) return { error: 'open-browser requires --url' }if (v === 'open-agent' && !args.agent) return { error: 'open-agent requires --agent <id>' }if ((v === 'group' || v === 'arrange') && !args.nodes) return { error: `${v} requires --nodes <id,id>` }+ if (v === 'ungroup' && !args.group) return { error: 'ungroup requires --group <id>' }+ if (v === 'move' && !args.nodes) return { error: 'move requires --nodes <id,id>' }if (v === 'align' && !args.nodes) return { error: 'align requires --nodes <id,id>' }if (v === 'align' && !args.edge) return { error: 'align requires --edge' }if (v === 'link' && !args.to) return { error: 'link requires --to <id,id>' }@@ -145,8 +151,15 @@ export function buildCanvasControlInstructions(shimPath: string): string {'- `show-image <path>` / `show-video <path>` — open a media file as a node.','- `show-web (--url U | --file P.html | --html "<...>")` — open a web viewer.','- `open-browser --url U` — open a navigable browser node.',- '- `group --nodes <id,id> [--label L]` / `arrange --nodes <id,id> [--layout grid|row|column] [--cols N]` /',- ' `align --nodes <id,id> --edge left|right|top|bottom|hcenter|vcenter` — organize the canvas.',+ '- `group --nodes <id,id> [--label L]` — wrap TOP-LEVEL nodes in a new labeled frame (nodes already',+ ' inside another frame are skipped — use `move` for those). `ungroup --group <id>` dissolves a frame,',+ ' freeing its nodes to the top level. `move --nodes <id,id> [--group <id>]` reparents nodes INTO an',+ ' existing frame (omit `--group`, or pass `top`/`none`, to pull them out to the top level) — this is',+ ' how you move a node from one frame to another.',+ '- `arrange --nodes <id,id> [--layout grid|row|column] [--cols N]` /',+ ' `align --nodes <id,id> --edge left|right|top|bottom|hcenter|vcenter` — tidy a layout. Works on',+ ' top-level nodes OR on the children of ONE frame (all ids must share a container — you cannot',+ ' arrange across frames in one call); arranging a frame\'s children also shrinks the frame to fit.','- `link --to <id,id> [--from <id>]` — context-link nodes so each can READ the other\'s transcript',' on demand (nodeterm linked-context CLI). `--from` defaults to you; nothing is pushed into the',' linked sessions. Agent sessions you open are linked to you automatically — use `link` for nodes',@@ -322,9 +335,22 @@ Verbs:render on the DESKTOP: \`show-image\` and \`show-video\` still work with a host path (thefile is read/fetched back over the connection), but \`show-web --file/--html\` is refused —use \`--url\`, or copy the file to the desktop first.-- \`group --nodes <id,id> [--label "Frontend Team"]\` — wrap nodes in a labeled group frame.-- \`arrange --nodes <id,id> [--layout grid|row|column] [--cols N]\` — tidy layout, no overlap.-- \`align --nodes <id,id> --edge left|right|top|bottom|hcenter|vcenter\` — align edges/centers.+- \`group --nodes <id,id> [--label "Frontend Team"]\` — wrap TOP-LEVEL nodes in a new labeled+ group frame. Nodes that are ALREADY inside another frame are skipped (the reply says how many) —+ use \`move\` to pull those across, not \`group\`.+- \`ungroup --group <id>\` — dissolve a group frame, freeing its nodes back to the top level (the+ nodes stay put; only the frame is removed).+- \`move --nodes <id,id> [--group <id>]\` — reparent nodes INTO an existing group frame, keeping+ each where it sits on the canvas. Omit \`--group\` (or pass \`top\`/\`none\`) to pull them OUT to the+ top level. This is how you move a node from one frame to another: \`move --nodes n1,n2 --group g2\`.+ (\`group\` only wraps loose top-level nodes; it will not steal a node out of its current frame.)+- \`arrange --nodes <id,id> [--layout grid|row|column] [--cols N]\` — tidy layout, no overlap. Works+ on top-level nodes OR on the children of ONE frame — every id must share a container (you cannot+ arrange nodes from two different frames, or mix framed + loose, in one call). When the ids are a+ frame's children, the frame is also shrunk to hug the tidied layout. Since grouping preserves each+ node's scattered position, a fresh frame is usually too wide: \`arrange\` its children to fix that.+- \`align --nodes <id,id> --edge left|right|top|bottom|hcenter|vcenter\` — align edges/centers. Same+ one-container rule as \`arrange\`.- \`link --to <id,id> [--from <id>]\` — context-link nodes, so each can READ the other'stranscript on demand with the get-linked-context skill. \`--from\` defaults to you. Nothing ispushed into the linked sessions — reading is on demand, so linking never interrupts anyone.@@ -378,7 +404,10 @@ Typical requests this skill covers:group), or \`open-claude\`/\`open-agent\` per node followed by \`group --nodes ... --label\`per subject and \`arrange\` inside each.- "Open a codex/gemini session" → \`open-agent --agent codex|gemini\`.-- "Tidy up / group my terminals" → \`list\`, then \`group\` + \`arrange\` + \`align\`.+- "Tidy up / group my terminals" → \`list\`, then \`group --nodes …\`, then \`arrange --nodes <those same ids>\`+ to tidy the new frame's contents (grouping keeps each node's scattered spot, so arrange after grouping).+- "Move this node into that group" → \`move --nodes <id> --group <targetGroupId>\` (not \`group\`, which only+ wraps loose nodes). "Break up this group" → \`ungroup --group <id>\`.- "Rename this node/group" → \`rename\`.## Nodeterm orchestration ("Build with Nodeterm orchestration")diff --git a/src/main/canvas-control-shim.test.ts b/src/main/canvas-control-shim.test.tsindex 6bcf1f620..e421535b9 100644--- a/src/main/canvas-control-shim.test.ts+++ b/src/main/canvas-control-shim.test.ts@@ -112,6 +112,13 @@ describe('canvas-control shim', () => {expect(received.at(-1)).toMatchObject({ verb: 'assign', args: { node: 'node-7', column: 'In Progress' } })})+ it('carries the frame verbs (ungroup / move) through', async () => {+ await callShim(['ungroup', '--group', 'g1'])+ expect(received.at(-1)).toMatchObject({ verb: 'ungroup', args: { group: 'g1' } })+ await callShim(['move', '--nodes', 'n1,n2', '--group', 'g2'])+ expect(received.at(-1)).toMatchObject({ verb: 'move', args: { nodes: 'n1,n2', group: 'g2' } })+ })+it('reports server-side failures on stderr with a non-zero exit', async () => {await expect(callShim(['boom'])).rejects.toMatchObject({code: 1,diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 3e56beb79..e533c3502 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -262,6 +262,8 @@ import {COLLAPSED_HEIGHT,alignNodes,arrangeNodes,+ commonParentId,+ fitGroupToChildren,createAccountLoginNode,isAccountLoginNode,systemAccountDisplay,@@ -5827,40 +5829,111 @@ export function Canvas() {}setNodes(grouped)markDirty()- reply({ ok: true, message: `grouped ${resolvable.length} node(s) into ${groupNode.id}`, result: { groupId: groupNode.id } })+ // Nodes already inside another frame are skipped (group only wraps loose nodes) — say+ // so, and point at `move`, so the agent isn't left wondering why a node stayed put.+ const skippedGrouped = ids.length - resolvable.length+ const groupNote = skippedGrouped > 0+ ? ` (${skippedGrouped} already in a frame were skipped — use \`move --group ${groupNode.id}\` for those)`+ : ''+ reply({+ ok: true,+ message: `grouped ${resolvable.length} node(s) into ${groupNode.id}${groupNote}`,+ result: { groupId: groupNode.id, grouped: resolvable, skipped: skippedGrouped }+ })+ return+ }+ case 'ungroup': {+ const gid = (args.group ?? '').trim()+ const live = nodesRef.current as CanvasNode[]+ const frame = live.find((nd) => nd.id === gid && nd.type === 'group')+ if (!frame) {+ reply({ ok: false, error: `ungroup: --group names no group frame (${gid || 'missing'})` })+ return+ }+ const freed = live.filter((nd) => nd.parentId === gid).map((nd) => nd.id)+ setNodes(ungroupNodes(live, gid))+ markDirty()+ reply({ ok: true, message: `ungrouped ${gid}, freed ${freed.length} node(s)`, result: { freed } })return}- case 'arrange': {+ case 'move': {+ // Reparent nodes INTO an existing frame (or out to the top level) — the one way to+ // move a node OUT of its current frame, which `group` deliberately won't do. `reparentNode`+ // keeps each node fixed on the canvas via absolute↔relative conversion.const ids = (args.nodes ?? '').split(',').map((s) => s.trim()).filter(Boolean)const live = nodesRef.current as CanvasNode[]- const layout = (['grid', 'row', 'column'] as const).find((l) => l === args.layout) ?? 'grid'- const cols = args.cols ? parseInt(args.cols, 10) || undefined : undefined- const next = arrangeNodes(live, ids, { layout, cols })- if (next === live) {- reply({ ok: false, error: 'arrange: none of the given node ids are top-level nodes' })+ const rawTarget = (args.group ?? '').trim().toLowerCase()+ const toTop = !rawTarget || rawTarget === 'top' || rawTarget === 'none' || rawTarget === 'ungrouped'+ const targetGroup = toTop ? null : args.group!.trim()+ if (targetGroup && !live.some((nd) => nd.id === targetGroup && nd.type === 'group')) {+ reply({ ok: false, error: `move: --group names no group frame (${targetGroup})` })return}+ let next = live+ const moved: string[] = []+ for (const id of ids) {+ const before = next+ const nd = next.find((n) => n.id === id)+ // Skip a group id, an unknown id, or a node already in the requested container.+ if (nd && nd.type !== 'group') next = reparentNode(next, id, targetGroup)+ if (next !== before) moved.push(id)+ }+ if (moved.length === 0) {+ reply({ ok: false, error: 'move: nothing moved (unknown ids, group ids, or already there)' })+ return+ }+ // The source frame(s) the nodes LEFT, and the destination, may now be the wrong size —+ // hug whatever each ends up holding so no oversized/updated box is left behind.+ const affected = new Set<string>()+ if (targetGroup) affected.add(targetGroup)+ for (const id of moved) {+ const was = live.find((n) => n.id === id)+ if (was?.parentId) affected.add(was.parentId)+ }+ for (const g of affected) {+ if (next.some((n) => n.parentId === g)) next = fitGroupToChildren(next, g)+ }setNodes(next)markDirty()- reply({ ok: true, message: `arranged ${ids.length} node(s) as ${layout}`, result: { count: ids.length } })+ const where = targetGroup ? `into ${targetGroup}` : 'to the top level'+ reply({ ok: true, message: `moved ${moved.length} node(s) ${where}`, result: { moved, group: targetGroup } })return}+ case 'arrange':case 'align': {const ids = (args.nodes ?? '').split(',').map((s) => s.trim()).filter(Boolean)+ const live = nodesRef.current as CanvasNode[]const edge = (['left', 'right', 'top', 'bottom', 'hcenter', 'vcenter'] as const).find((e2) => e2 === args.edge)- if (!edge) {+ if (verb === 'align' && !edge) {reply({ ok: false, error: 'align requires --edge left|right|top|bottom|hcenter|vcenter' })return}- const live = nodesRef.current as CanvasNode[]- const next = alignNodes(live, ids, edge)- if (next === live) {- reply({ ok: false, error: 'align: none of the given node ids are top-level nodes' })+ // arrange/align run in ONE coordinate space: all top-level, or all children of one+ // frame. A mixed set (framed + loose, or two frames) is refused with a clear reason+ // rather than the old misleading "none are top-level".+ const container = commonParentId(live, ids)+ if (container === undefined) {+ const known = ids.filter((id) => live.some((n) => n.id === id))+ reply({+ ok: false,+ error: known.length === 0+ ? `${verb}: none of the given node ids exist`+ : `${verb}: the nodes are in different containers — arrange the children of one frame (or top-level nodes) at a time`+ })return}+ const layout = (['grid', 'row', 'column'] as const).find((l) => l === args.layout) ?? 'grid'+ const cols = args.cols ? parseInt(args.cols, 10) || undefined : undefined+ let next = verb === 'arrange'+ ? arrangeNodes(live, ids, { layout, cols })+ : alignNodes(live, ids, edge!)+ // Tidying a frame's children usually leaves the frame oversized (it was sized to their+ // old scattered spots) — shrink it to hug the new layout. Top-level sets have no frame.+ if (container) next = fitGroupToChildren(next, container)setNodes(next)markDirty()- reply({ ok: true, message: `aligned ${ids.length} node(s) to ${edge}`, result: { count: ids.length } })+ const how = verb === 'arrange' ? `as ${layout}` : `to ${edge}`+ reply({ ok: true, message: `${verb === 'arrange' ? 'arranged' : 'aligned'} ${ids.length} node(s) ${how}`, result: { count: ids.length, container } })return}case 'link': {diff --git a/src/renderer/state/workspace.layout.test.ts b/src/renderer/state/workspace.layout.test.tsindex cd0ad3546..667d3631b 100644--- a/src/renderer/state/workspace.layout.test.ts+++ b/src/renderer/state/workspace.layout.test.ts@@ -33,13 +33,22 @@ describe('arrangeNodes', () => {expect(out.find((x) => x.id === 'c')!.position).toEqual({ x: 0, y: 90 })})- it('skips unknown ids and parented nodes; empty selection is a no-op', () => {+ it('refuses a set mixing containers, and no-ops an empty/ghost selection', () => {+ // A top-level node + a group child cannot be co-arranged (their coordinate spaces differ),+ // so a MIXED set is a deliberate no-op — NOT "silently arrange the top-level ones" (that+ // silent subset-arrange was the surprise this replaced). Same for unknown ids.const child = { ...n('kid', 5, 5), parentId: 'g1' } as CanvasNodeconst nodes = [n('a', 7, 7), child]- const out = arrangeNodes(nodes, ['a', 'kid', 'ghost'], { layout: 'row', origin: { x: 0, y: 0 } })- expect(out.find((x) => x.id === 'kid')!.position).toEqual({ x: 5, y: 5 }) // untouched- expect(out.find((x) => x.id === 'a')!.position).toEqual({ x: 0, y: 0 })+ expect(arrangeNodes(nodes, ['a', 'kid', 'ghost'], { layout: 'row', origin: { x: 0, y: 0 } })).toBe(nodes)expect(arrangeNodes(nodes, ['ghost'])).toBe(nodes) // nothing resolvable → same array+ // Same-container sets still arrange: two children of one frame lay out in frame space.+ const framed = [+ { ...n('c1', 40, 40), parentId: 'g1' } as CanvasNode,+ { ...n('c2', 300, 5), parentId: 'g1' } as CanvasNode+ ]+ const laid = arrangeNodes(framed, ['c1', 'c2'], { layout: 'row', gap: 20 })+ expect(laid.find((x) => x.id === 'c1')!.position).toEqual({ x: 40, y: 5 })+ expect(laid.find((x) => x.id === 'c2')!.position).toEqual({ x: 40 + 100 + 20, y: 5 })})})diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.tsindex ac82fd06c..b444309b8 100644--- a/src/renderer/state/workspace.test.ts+++ b/src/renderer/state/workspace.test.ts@@ -1,8 +1,12 @@import { describe, it, expect } from 'vitest'import {+ alignNodes,+ arrangeNodes,+ commonParentId,createAccountLoginNode,createAgentNode,createDinoNode,+ fitGroupToChildren,flowToNodeStates,groupSelectedNodes,nodeStatesToFlow,@@ -72,6 +76,95 @@ describe('reparentNode', () => {})})+describe('commonParentId', () => {+ it('is null when every id is top-level', () => {+ const nodes = [term('t1', { x: 0, y: 0 }), grp('g1', { x: 5, y: 5 })]+ expect(commonParentId(nodes, ['t1', 'g1'])).toBeNull()+ })+ it('is the group id when every id is a child of the same group', () => {+ const nodes = [grp('g1', { x: 0, y: 0 }), term('t1', { x: 10, y: 10 }, 'g1'), term('t2', { x: 20, y: 20 }, 'g1')]+ expect(commonParentId(nodes, ['t1', 't2'])).toBe('g1')+ })+ it('is undefined for a mixed set (framed + loose, or two frames) or no matching ids', () => {+ const nodes = [+ grp('g1', { x: 0, y: 0 }),+ term('t1', { x: 10, y: 10 }, 'g1'),+ term('loose', { x: 500, y: 0 })+ ]+ expect(commonParentId(nodes, ['t1', 'loose'])).toBeUndefined()+ expect(commonParentId(nodes, ['nope'])).toBeUndefined()+ })+})++describe('arrange/align inside a frame', () => {+ // Children of one frame arrange in the frame's coordinate space — the gap this closes: after+ // grouping, the frame's contents could not be tidied from the canvas-control CLI.+ const framed = () => [+ grp('g1', { x: 100, y: 100 }),+ term('a', { x: 5, y: 5 }, 'g1'),+ term('b', { x: 400, y: 300 }, 'g1'), // scattered inside the frame+ term('c', { x: 900, y: 40 }, 'g1')+ ]++ it('arranges a frame\'s children in a row without touching the frame or top-level nodes', () => {+ const out = arrangeNodes(framed(), ['a', 'b', 'c'], { layout: 'row', gap: 40 })+ const pos = (id: string) => out.find((n) => n.id === id)!.position+ // Row starts at the bounding-box top-left of the children (relative coords), y shared.+ expect(pos('a')).toEqual({ x: 5, y: 5 })+ expect(pos('b')).toEqual({ x: 5 + 320 + 40, y: 5 })+ expect(pos('c')).toEqual({ x: 5 + (320 + 40) * 2, y: 5 })+ })++ it('refuses a set spanning two containers (no-op)', () => {+ const nodes = [+ grp('g1', { x: 0, y: 0 }),+ term('a', { x: 10, y: 10 }, 'g1'),+ term('loose', { x: 800, y: 0 })+ ]+ expect(arrangeNodes(nodes, ['a', 'loose'], { layout: 'row' })).toBe(nodes)+ expect(alignNodes(nodes, ['a', 'loose'], 'left')).toBe(nodes)+ })++ it('aligns a frame\'s children to a shared left edge', () => {+ const out = alignNodes(framed(), ['a', 'b', 'c'], 'left')+ const xs = ['a', 'b', 'c'].map((id) => out.find((n) => n.id === id)!.position.x)+ expect(new Set(xs)).toEqual(new Set([5])) // all snapped to the leftmost (a.x = 5)+ })+})++describe('fitGroupToChildren', () => {+ it('shrinks the frame to hug its children and keeps them fixed on canvas', () => {+ // Frame is oversized (400×300) but its two children sit in a small cluster.+ const nodes = [+ grp('g1', { x: 100, y: 100 }),+ term('a', { x: 20, y: 40 }, 'g1'), // abs (120,140), 320×240+ term('b', { x: 60, y: 20 }, 'g1') // abs (160,120)+ ]+ const out = fitGroupToChildren(nodes, 'g1')+ const g = out.find((n) => n.id === 'g1')!+ const a = out.find((n) => n.id === 'a')!+ const b = out.find((n) => n.id === 'b')!+ // Children keep their ABSOLUTE canvas positions (frame origin + relative pos unchanged).+ expect({ x: g.position.x + a.position.x, y: g.position.y + a.position.y }).toEqual({ x: 120, y: 140 })+ expect({ x: g.position.x + b.position.x, y: g.position.y + b.position.y }).toEqual({ x: 160, y: 120 })+ // Frame hugs the child bbox with the standard pad (28) + header (34) on top.+ const GROUP_PAD = 28+ const GROUP_HEADER = 34+ const minX = 120, minY = 120+ const maxX = 160 + 320, maxY = 140 + 240+ expect(g.position).toEqual({ x: minX - GROUP_PAD, y: minY - GROUP_PAD - GROUP_HEADER })+ expect(g.width).toBe(maxX - minX + GROUP_PAD * 2)+ expect(g.height).toBe(maxY - minY + GROUP_PAD * 2 + GROUP_HEADER)+ })++ it('is a no-op for a missing id, a non-group, or an empty frame', () => {+ const nodes = [grp('g1', { x: 0, y: 0 }), term('t1', { x: 0, y: 0 })]+ expect(fitGroupToChildren(nodes, 'nope')).toBe(nodes)+ expect(fitGroupToChildren(nodes, 't1')).toBe(nodes)+ expect(fitGroupToChildren(nodes, 'g1')).toBe(nodes) // g1 has no children+ })+})+describe('groupSelectedNodes', () => {it('wraps the selection in a group frame with group-relative child positions', () => {const nodes = [term('t1', { x: 100, y: 100 }), term('t2', { x: 500, y: 300 })]diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex ac2dd7dec..1a08e9459 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -668,11 +668,27 @@ const nodeH = (n: CanvasNode) => n.measured?.height ?? (n.height as number) ?? 0export type ArrangeLayout = 'grid' | 'row' | 'column'/**- * Repositions the given top-level ids into a non-overlapping layout starting at `origin`- * (default: the bounding-box top-left of their current positions). 'row' packs left-to-right,- * 'column' top-to-bottom, 'grid' wraps at `cols` (default ~square) with each row advancing by- * its tallest member. Unknown ids and parented (grouped) nodes are skipped; returns the input- * array unchanged when nothing resolves. Pure and deterministic.+ * The single container the given ids all live in: `null` (all top-level), a group id (all+ * children of that one group), or `undefined` when they resolve to no node OR span more than+ * one container (a group's children mixed with top-level, or two different groups). Positions+ * are only comparable within one container — top-level positions are absolute, a group child's+ * are relative to its frame — so arrange/align refuse a mixed set rather than scramble it.+ */+export function commonParentId(nodes: CanvasNode[], ids: string[]): string | null | undefined {+ const set = new Set(ids)+ const members = nodes.filter((nd) => set.has(nd.id))+ if (members.length === 0) return undefined+ const parents = new Set(members.map((m) => m.parentId ?? null))+ return parents.size === 1 ? members[0].parentId ?? null : undefined+}++/**+ * Repositions the given ids into a non-overlapping layout starting at `origin` (default: the+ * bounding-box top-left of their current positions). 'row' packs left-to-right, 'column'+ * top-to-bottom, 'grid' wraps at `cols` (default ~square) with each row advancing by its tallest+ * member. The ids must share ONE container — all top-level, or all children of the same group+ * (the layout then runs in that group's coordinate space); a mixed set is a no-op. Unknown ids+ * are skipped; returns the input array unchanged when nothing resolves. Pure and deterministic.*/export function arrangeNodes(nodes: CanvasNode[],@@ -680,8 +696,9 @@ export function arrangeNodes(opts?: { layout?: ArrangeLayout; cols?: number; gap?: number; origin?: { x: number; y: number } }): CanvasNode[] {const set = new Set(ids)- const members = nodes.filter((nd) => set.has(nd.id) && !nd.parentId)- if (members.length === 0) return nodes+ const members = nodes.filter((nd) => set.has(nd.id))+ // Only meaningful within one coordinate space (see commonParentId) — mixed containers → no-op.+ if (members.length === 0 || new Set(members.map((m) => m.parentId ?? null)).size > 1) return nodesconst layout = opts?.layout ?? 'grid'const gap = opts?.gap ?? 40const origin = opts?.origin ?? {@@ -711,14 +728,15 @@ export function arrangeNodes(export type AlignEdge = 'left' | 'right' | 'top' | 'bottom' | 'hcenter' | 'vcenter'/**- * Snaps the given top-level ids to a shared edge/center computed from their joint bounding box.- * left/right/hcenter move x; top/bottom/vcenter move y. Unknown/parented ids are skipped;- * returns the input array unchanged when nothing resolves. Pure.+ * Snaps the given ids to a shared edge/center computed from their joint bounding box.+ * left/right/hcenter move x; top/bottom/vcenter move y. The ids must share ONE container (all+ * top-level, or all children of the same group — see `arrangeNodes`); a mixed set is a no-op.+ * Unknown ids are skipped; returns the input array unchanged when nothing resolves. Pure.*/export function alignNodes(nodes: CanvasNode[], ids: string[], edge: AlignEdge): CanvasNode[] {const set = new Set(ids)- const members = nodes.filter((nd) => set.has(nd.id) && !nd.parentId)- if (members.length === 0) return nodes+ const members = nodes.filter((nd) => set.has(nd.id))+ if (members.length === 0 || new Set(members.map((m) => m.parentId ?? null)).size > 1) return nodesconst minX = Math.min(...members.map((m) => m.position.x))const maxR = Math.max(...members.map((m) => m.position.x + nodeW(m)))const minY = Math.min(...members.map((m) => m.position.y))@@ -801,6 +819,40 @@ export function duplicateNode(node: CanvasNode, offset = 28): CanvasNode {}}+/**+ * Resizes a group frame to hug its current children (same padding as `groupSelectedNodes`), and+ * re-anchors the frame + rewrites the children's relative positions so nothing moves on canvas.+ * Used after arranging inside a frame: the frame's width came from wherever the children happened+ * to sit when they were grouped, so a tidy inner layout still leaves an oversized box. No-op for a+ * missing/non-group id or a frame with no children. Pure.+ */+export function fitGroupToChildren(nodes: CanvasNode[], groupId: string): CanvasNode[] {+ const group = nodes.find((n) => n.id === groupId)+ if (!group || group.type !== 'group') return nodes+ const children = nodes.filter((n) => n.parentId === groupId)+ if (children.length === 0) return nodes+ // Child positions are group-relative; convert to absolute via the current frame origin.+ const absX = (c: CanvasNode) => group.position.x + c.position.x+ const absY = (c: CanvasNode) => group.position.y + c.position.y+ const minX = Math.min(...children.map(absX))+ const minY = Math.min(...children.map(absY))+ const maxX = Math.max(...children.map((c) => absX(c) + nodeW(c)))+ const maxY = Math.max(...children.map((c) => absY(c) + nodeH(c)))+ const gx = minX - GROUP_PAD+ const gy = minY - GROUP_PAD - GROUP_HEADER+ const width = maxX - minX + GROUP_PAD * 2+ const height = maxY - minY + GROUP_PAD * 2 + GROUP_HEADER+ return nodes.map((n) => {+ if (n.id === groupId) {+ return { ...n, position: { x: gx, y: gy }, width, height, style: { ...n.style, width, height } }+ }+ if (n.parentId === groupId) {+ return { ...n, position: { x: absX(n) - gx, y: absY(n) - gy } }+ }+ return n+ })+}+/** Removes a group frame and restores its children to absolute positions. */export function ungroupNodes(nodes: CanvasNode[], groupId: string): CanvasNode[] {const group = nodes.find((n) => n.id === groupId)