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): Tidy canvas keeps each orchestrator beside the team it opened
review9ea9afb951b4
diff --git a/CLAUDE.md b/CLAUDE.mdindex 50e7e7fea..3faf8be0e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4211,7 +4211,17 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile`control-unsupported-on-this-edition` reply and is never dropped on the way to an `ok`(`control-unsupported.test.ts` pins it). Off screen it works like the `--nodes` form: thestored nodes are laid out and written back through `commitCtlNodes`, and the lineage ropes are- the OWNING project's (`offCanvas.project.ropes`), never the live canvas's.+ the OWNING project's (`offCanvas.project.ropes`, re-marked with `markLegacyWaitRopes` exactly as a+ load would — a project that has not been opened since waits were marked still holds unmarked+ ones), never the live canvas's. The rope **id** rides along on both paths: it is the only thing+ that tells a wait from an opener, and stripping it (as the first revision did) makes every wait+ read as an opener. **`arrange --group top [--layout tidy|lineage]`** (2026-10, issue #1114 — an+ orchestrator asked for a programmatic Tidy) names the canvas's TOP LEVEL with the same words+ `move` reads (`top`/`none`/`ungrouped`, `isTopLevelGroupArg`) and runs the user's own **Tidy+ canvas** (`tidyCanvas`, default) or its bands (`arrangeByLineage`) — the same transforms as the+ pane menu, nothing re-implemented. `grid`/`row`/`column` are refused there by name: `--nodes`+ already says them, and a top-level grid that ignores lineage is what Tidy no longer is. Same+ Server Edition refusal, same off-screen path.**Fan-in (`link`, 2026-07):** a spawned fan-out was previously write-only — nodes an agentopened were joined to it by a **rope** (`project.ropes`, explicitly *"Display-only — nevercontext links"*), so an orchestrator could not read back what its own team produced and the@@ -6646,9 +6656,9 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea- **Context menus** (`components/ContextMenu.tsx`, portal, icons from `components/icons.tsx`):pane right-click = add nodes at cursor (terminal / Claude / sticky / open file) + select- all + fit + **Tidy canvas** (`arrangeAllNodes` — packs every top-level node, including group- frames as rigid units, into a non-overlapping grid via `arrangeNodes`, sorted by current- (y, x) so the pack roughly preserves reading order; mirrored in ⌘K as "Tidy canvas" and in the+ all + fit + **Tidy canvas** (`arrangeAllNodes` → `tidyCanvas` — packs every top-level node,+ including group frames as rigid units, without overlap, keeping each ORCHESTRATOR legible; see+ the Tidy canvas bullet below; mirrored in ⌘K as "Tidy canvas" and in thekeybinding registry as `canvas.tidy` (default ⌘/Ctrl+Shift+A, remappable); bothhidden below 2 top-level nodes, where it could only be a visual no-op that still writes`project.json`) + restart-idle-agents (the bulk in-place agent restart, mirrored in ⌘K; both@@ -6675,6 +6685,38 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord meaids it knows — so Delete, restart-agent, branch/transfer, terminal Search and Close can neverbe hidden, whatever settings.json says. The group-frame menu's colors strip answers to the same`colors` id; builders run through `tidySeparators` so a hidden row leaves no dangling rule.+- **Tidy canvas keeps the orchestrator** (`tidyCanvas` in `state/workspace.ts`, 2026-10 — user+ feedback: *"I lose the sense who is orchestrator"*). The old Tidy packed every top-level unit+ into one reading-order grid, so an orchestrator landed wherever its (y, x) fell — routinely LAST,+ after the stations it opened and the loose notes between them. Now a unit that opened other units+ is placed first, at the top-left of its own cluster, with the units it opened packed in a ~square+ grid directly to its RIGHT, and a sub-orchestrator's own team clustered the same way inside that+ grid (recursive blocks, `flowBlocks` = `arrangeNodes`' row flow over rectangles). Clusters are+ packed in reading order of their orchestrators; every unit with NO lineage is packed after them,+ below, by the plain grid. Rules a refactor must keep:+ **(1) The relation is the OPENER only, and it is `openerByTarget`** (`lib/teamProgress.ts`) —+ the ONE definition team progress reads too (`data.openedBy` when recorded, else the first+ non-wait rope into the node; `stationsByOpener` now sits on it), so the ring and the layout+ cannot disagree about whose station a node is. Waits are NOT followed: a verify panel's+ reviewers wait on the reviewed node, but the orchestrator opened all of them — following waits+ would split its team under one of its own stations. And one opener per node makes the clusters+ a forest, so the layout has one answer.+ **(2) Ropes are lifted to the top-level unit** (the #1114 shape: a coordinator opens a lead+ INSIDE a frame, so the frame joins the coordinator's team). A frame whose contents were opened+ by different units belongs to the one that opened the MOST of them, ties to the earliest rope; a+ plain node's own opener always wins for it. A rope internal to one frame is dropped.+ **(3) A cycle never hangs** — lifting makes one easily (a in frame g opens b outside, b opens a2+ inside g); the cycle member that reads first loses its opener and leads.+ **(4) No lineage ⇒ exactly the old call**: `arrangeNodes(grid)` over the reading-order ids —+ pinned against that call verbatim, waits-only canvases included. (Not byte-identical to the+ pre-#836 *build*: `arrangeNodes` then placed in array order, ignoring the sort this action always+ documented — see Arrange by lineage below.)+ **(5) Same array when nothing moves**, so a second Tidy writes no undo entry and no+ `project.json` (it still fits the view). The layout is idempotent by construction: every block+ places its members in reading order, so a tidied canvas reads back in the order it was laid out.+ A dead opener (deleted; the rope pruned, or a stored file's unpruned rope) leads nothing — its+ stations fall loose. Desktop + Server Edition identical (pure renderer, no new IPC); kanban N/A+ (a board has no geometry); Mobile N/A (no canvas). Agents reach it as `arrange --group top`.- **Arrange by lineage** (`arrangeByLineage` / `lineageLayers` in `state/workspace.ts`; pane menubeside Tidy canvas, ⌘K, and the registry command `canvas.tidyLineage`, which ships UNBOUND —⌘⇧A is already the first tidy) — the second tidy: one row per LAYER of the lineage ropes@@ -6702,9 +6744,15 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord meain ARRAY order, which threw away the slot order `lineageLayers` computes (siblings under theiropener) AND the reading-order sort `arrangeAllNodes` documents, with every existing test greenbecause each asserted the layer LIST and never the positions. The interleaved case is now- asserted on positions. Desktop + Server Edition identical (pure renderer, no new IPC); kanban- N/A (a board shows cards, and geometry is exactly what a column layout discards); Mobile N/A- (no canvas).+ asserted on positions. **Bands read BOTH relations, slots read the opener first** (2026-10):+ layering follows openers AND waits (a wait is a flow edge too, and longest-path keeps it pointing+ down — a verify panel reads target → reviewers → judge), but a node's slot in its band follows+ its OPENER's slot when the opener is in the band above, else its earliest predecessor's, so a+ node opened by B that waits on A sits under B with the rest of B's team. Kept as its own command+ rather than folded into Tidy: bands answer "in what order does the work flow", Tidy answers+ "whose team is this", and on a pipeline the two disagree. Desktop + Server Edition identical+ (pure renderer, no new IPC); kanban N/A (a board shows cards, and geometry is exactly what a+ column layout discards); Mobile N/A (no canvas).- **Arrange inside a group** (`arrangeGroupChildren` / `groupArrangeRefusal` in`state/workspace.ts`; the group-frame menu's **Tidy group** and **Arrange group by lineage**,⌘K for the ONE selected frame, and the `arrange --group` control verb — one transform behind alldiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 52fdf7cb3..39af3f67c 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -182,7 +182,9 @@ opener's `ctrl-<source>-<node>` shape: rope ORDER does not survive the canvas prdeleted nodes, so the id is the only thing that tells a wait from an opener. A node opened by acontrol verb also RECORDS its opener (`data.openedBy`); readers that ask "who opened this"(`stationsByOpener`, the station-failure notice) prefer that record and still require the opener's-rope to exist.+rope to exist. In the renderer that rule is ONE function, `openerByTarget` (`lib/teamProgress.ts`):+team progress and Tidy canvas both read it, and so must anything new that asks "who opened this+node" — and pass the rope `id` through, or every wait reads as an opener.Before adding a GitHub read, check what the existing poll already fetches. Pull request cardsneeded no new request at all: `/repos/{repo}/issues` returns pull requests, and the client used todiff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.tsindex abccbce05..a4b21769c 100644--- a/src/core/canvas-control-core.ts+++ b/src/core/canvas-control-core.ts@@ -1725,6 +1725,8 @@ Typical requests this skill covers:- "Open a Codex/Gemini/Copilot session" → \`open-agent --agent codex|gemini|copilot\`.- "Tidy up / group my terminals" → \`list\`, then \`group --nodes …\`, then \`arrange --group <the new frame's id>\`to tidy the new frame's contents (grouping keeps each node's scattered spot, so arrange after grouping).+- "Tidy the canvas" / "clean up the layout" → \`arrange --group top\` — the user's own Tidy canvas: you stay at the+ top-left of the team you opened. Once, after the team is open — not after every \`open-*\`.- "Move this node into that group" → \`move --nodes <id> --group <targetGroupId>\` (not \`group\`, which onlywraps loose nodes). "Break up this group" → \`ungroup --group <id>\`.- "Rename this node/group" → \`rename\`.diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.tsindex b2a020e59..e29bdf838 100644--- a/src/main/canvas-control-core.test.ts+++ b/src/main/canvas-control-core.test.ts@@ -127,6 +127,9 @@ describe('parseControlRequest', () => {['instructions', buildCanvasControlInstructions('/x/shim.sh')]] as const) {expect(body, name).toContain('- `arrange --group <frameId> [--layout grid|row|column|lineage] [--cols N]`')+ // The whole-canvas form is in both bodies, and says what Tidy does with an orchestrator.+ expect(body, name).toContain('- `arrange --group top [--layout tidy|lineage]` — tidy the WHOLE canvas')+ expect(body, name).toMatch(/each orchestrator is placed first, at the top-left of the nodes and\s+frames it opened/)// The `--nodes` form is still there, and still says what it accepts.expect(body, name).toContain('`arrange --nodes <id,id> [--layout grid|row|column] [--cols N]`')expect(body, name).toMatch(/frame's direct children \(a frame nested\s+inside moves as one unit\)/)@@ -145,6 +148,8 @@ describe('parseControlRequest', () => {const body = buildCanvasSkillBody('/x/shim.sh')expect(body).toContain("then `arrange --group <the new frame's id>`")expect(body).not.toContain('arrange --nodes <those same ids>')+ // An orchestrator asked to tidy the canvas reaches for the user's own Tidy (#1114).+ expect(body).toContain('"Tidy the canvas" / "clean up the layout" → `arrange --group top`')})it('run requires --node (#925)', () => {@@ -278,7 +283,12 @@ describe('parseControlRequest', () => {expect(parseControlRequest('group', {})).toEqual({ error: 'group requires --nodes <id,id>' })expect(parseControlRequest('group', { nodes: 'a,b' })).toEqual({ verb: 'group', args: { nodes: 'a,b' } })expect(parseControlRequest('arrange', {})).toEqual({- error: 'arrange requires --nodes <id,id> or --group <frameId>'+ error: 'arrange requires --nodes <id,id>, --group <frameId> or --group top'+ })+ // The whole-canvas form: Tidy canvas, from an agent (#1114).+ expect(parseControlRequest('arrange', { group: 'top' })).toEqual({ verb: 'arrange', args: { group: 'top' } })+ expect(parseControlRequest('arrange', { group: 'top', layout: 'grid' })).toEqual({+ error: 'arrange --group top: --layout must be tidy|lineage'})expect(parseControlRequest('arrange', { nodes: 'a,b', layout: 'row' })).toEqual({verb: 'arrange',diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 9c129e9cc..2f26da1b1 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -9,7 +9,7 @@ import { VisibleMiniMap } from './VisibleMiniMap'import { MinimapDock } from './MinimapDock'import { keepGlassBlurWhileMoving } from '../lib/glassContrast'import { LINK_ENDPOINT_NOT_FOUND } from '@shared/canvas-link'-import { arrangeArgsRefusal } from '@shared/arrange-verb'+import { arrangeArgsRefusal, isTopLevelGroupArg, TOP_ARRANGE_LAYOUTS } from '@shared/arrange-verb'import { createControlOpenBatch } from '../lib/controlOpenBatch'import { commitOwnedLaunchAttempt, registerLaunchCommit } from '../terminal/launch-attempt'import { hasLaunchWriter, launchCommand } from '../terminal/launch-command'@@ -826,6 +826,7 @@ import {alignNodes,arrangeByLineage,arrangeGroupChildren,+ tidyCanvas,arrangeNodes,fitAncestorChain,groupArrangeRefusal,@@ -8950,37 +8951,31 @@ export function Canvas() {// Pane-level "Tidy canvas": packs every top-level node (terminal, agent, sticky, editor, diff,// group frame — a frame moves as one unit, its children ride along untouched) into a- // non-overlapping grid via the same `arrangeNodes` selection/canvas-control already use.- // `arrangeNodes` no-ops on a mixed-container id set (workspace.ts commonParentId), which is why- // only top-level ids (`!n.parentId`) are collected here — a populated group frame would- // otherwise silently block the whole action. Sorted by current (y, x) first so the packed grid- // roughly preserves the canvas's existing reading order instead of falling back to array/- // persistence order (which puts every group frame first).+ // non-overlapping layout, keeping each orchestrator at the top-left of the team it opened+ // (`tidyCanvas`, state/workspace.ts — opener ropes only, lifted to the top-level unit; a canvas+ // with no lineage gets exactly the reading-order grid this action always produced).const hasArrangeableNodes = useCallback((): boolean => {return nodesRef.current.filter((n) => !n.parentId).length >= 2}, [])+ // The lineage ropes as the layouts read them: `controlEdges` is the live copy of what the+ // project persists as `ropes` ("opened by" and `--after`), already re-marked at load by+ // `markLegacyWaitRopes`. The rope id rides along — it is what tells a wait from an opener.+ const lineageEdges = useCallback(+ () => controlEdgesRef.current.map((e) => ({ id: e.id, source: e.source, target: e.target })),+ []+ )const arrangeAllNodes = useCallback(() => {if (isGlobalKanbanOpen() || isKanbanOpen(useProjects.getState().activeProjectId)) return- const targets = nodesRef.current- .filter((n) => !n.parentId)- .sort((a, b) => a.position.y - b.position.y || a.position.x - b.position.x)- // Fewer than 2 nodes: nothing to tidy — and running arrangeNodes anyway would still emit a- // fresh node array (a no-op position rewrite), triggering an undo entry + markDirty + a- // project.json write for a canvas that visibly didn't change.- if (targets.length < 2) return- const ids = targets.map((n) => n.id)- setNodes((ns) => arrangeNodes(ns, ids, { layout: 'grid' }))- markDirty()+ const edges = lineageEdges()+ // The SAME array means nothing moves (under 2 units, or already tidy): no undo entry, no+ // project.json write. Decided against nodesRef BEFORE the write — see arrangeByLineageAction.+ if (tidyCanvas(nodesRef.current as CanvasNode[], edges) !== nodesRef.current) {+ setNodes((ns) => tidyCanvas(ns as CanvasNode[], edges))+ markDirty()+ }fitAll()- }, [setNodes, markDirty, fitAll])+ }, [setNodes, markDirty, fitAll, lineageEdges])- // The lineage ropes as the layout reads them: `controlEdges` is the live copy of what the- // project persists as `ropes` ("opened by" and `--after`), which is exactly the relation the- // user means by "who opened whom".- const lineageEdges = useCallback(- () => controlEdgesRef.current.map((e) => ({ source: e.source, target: e.target })),- []- )// Whether the lineage tidy has anything to say. Asked when the menu OPENS so the row can be// disabled with its reason instead of silently doing nothing on click: on a canvas nobody// spawned anything into, every node is loose and the result would just be a worse Tidy canvas.@@ -14743,9 +14738,34 @@ export function Canvas() {// and the palette run — so this branch only parses, refuses by name and replies.if (verb === 'arrange' && args.group) {const gid = args.group.trim()+ // Off canvas the lineage ropes are the OWNING project's, not the live canvas's — and a+ // stored file may predate the wait mark, so it is re-marked exactly as a load would.+ // The rope id rides along: it is what tells a wait from an opener.+ const edges = (offCanvas ? markLegacyWaitRopes(offCanvas.project.ropes ?? []) : controlEdgesRef.current).map(+ (e) => ({ id: e.id, source: e.source, target: e.target })+ )+ // `arrange --group top`: the user's Tidy canvas (or its lineage bands), on the canvas+ // that owns the caller — the same pure transforms the pane menu runs.+ if (isTopLevelGroupArg(gid)) {+ const topLayout = TOP_ARRANGE_LAYOUTS.find((l) => l === args.layout) ?? 'tidy'+ const next = topLayout === 'lineage' ? arrangeByLineage(live, edges) : tidyCanvas(live, edges)+ const count = live.filter((nd) => !nd.parentId).length+ if (next !== live) commitCtlNodes(next)+ reply({+ ok: true,+ message:+ next !== live+ ? `arranged ${count} top-level item(s) as ${topLayout}`+ : count < 2+ ? 'fewer than two top-level items — nothing to arrange'+ : topLayout === 'lineage' && lineageLayers(live, edges).layers.length === 0+ ? 'no opened-by or --after connection joins two top-level items — nothing moved'+ : `the canvas is already arranged as ${topLayout} — nothing moved`,+ result: { count, group: 'top', layout: topLayout, changed: next !== live }+ })+ return+ }const groupLayout = GROUP_ARRANGE_LAYOUTS.find((l) => l === args.layout) ?? 'grid'- // Off canvas the lineage ropes are the OWNING project's, not the live canvas's.- const edges = (offCanvas ? offCanvas.project.ropes ?? [] : controlEdgesRef.current).map((e) => ({ source: e.source, target: e.target }))const refusal = groupArrangeRefusal(live, gid, groupLayout, edges)if (refusal) {reply({ ok: false, error: `arrange: ${refusal}` })diff --git a/src/renderer/canvas/arrange-group.source.test.ts b/src/renderer/canvas/arrange-group.source.test.tsindex 324bc6df7..5c86a121a 100644--- a/src/renderer/canvas/arrange-group.source.test.ts+++ b/src/renderer/canvas/arrange-group.source.test.ts@@ -79,7 +79,10 @@ describe('arrange inside a group (source pins)', () => {// `commitCtlNodes` is the one write for on- and off-screen projects (it marks dirty itself).expect(write).toMatch(/^if \(next !== live\) commitCtlNodes\(next\)/)// Off screen the lineage ropes are the owning project's, never the live canvas's.- expect(groupBranch).toContain('offCanvas ? offCanvas.project.ropes')+ // A stored file may predate the wait mark, so it is re-marked as a load would.+ expect(groupBranch).toContain('offCanvas ? markLegacyWaitRopes(offCanvas.project.ropes ?? [])')+ // The rope id rides along — it is what tells a wait from an opener.+ expect(groupBranch).toContain('({ id: e.id, source: e.source, target: e.target })')// A refusal names the verb and never reports ok.expect(groupBranch).toContain('reply({ ok: false, error: `arrange: ${refusal}` })')})@@ -112,4 +115,23 @@ describe('arrange inside a group (source pins)', () => {expect(nodesForm).toContain('fitAncestorChain(next, container, snapGridNow())')expect(nodesForm).not.toContain('fitGroupToChildren(')})++ it('Tidy canvas is tidyCanvas over the ropes WITH their ids, and a no-op writes nothing', () => {+ const tidy = between('const arrangeAllNodes = useCallback(', '\n // Whether the lineage tidy')+ const guard = tidy.indexOf('tidyCanvas(nodesRef.current as CanvasNode[], edges) !== nodesRef.current')+ expect(guard).toBeGreaterThan(-1)+ expect(tidy.indexOf('setNodes((ns) => tidyCanvas(ns as CanvasNode[], edges))')).toBeGreaterThan(guard)+ expect(tidy).not.toContain('arrangeNodes(')+ expect(tidy).toContain('isKanbanOpen(')+ const edges = between('const lineageEdges = useCallback(', 'const arrangeAllNodes')+ expect(edges).toContain('({ id: e.id, source: e.source, target: e.target })')+ })++ it('arrange --group top runs the same Tidy canvas (or its bands) and writes only on a change', () => {+ const top = groupBranch.slice(groupBranch.indexOf('if (isTopLevelGroupArg(gid))'), groupBranch.indexOf('const groupLayout'))+ expect(top).toContain("TOP_ARRANGE_LAYOUTS.find((l) => l === args.layout) ?? 'tidy'")+ expect(top).toContain("topLayout === 'lineage' ? arrangeByLineage(live, edges) : tidyCanvas(live, edges)")+ expect(top).toContain('if (next !== live) commitCtlNodes(next)')+ expect(top).not.toMatch(/\barrangeNodes\(/)+ })})diff --git a/src/renderer/lib/teamProgress.ts b/src/renderer/lib/teamProgress.tsindex 249d56edf..35b8a822b 100644--- a/src/renderer/lib/teamProgress.ts+++ b/src/renderer/lib/teamProgress.ts@@ -114,6 +114,39 @@ function sameStations(a: readonly TeamStation[], b: readonly TeamStation[]): boo)}+/**+ * Rule 1 as a map: every node a rope says was OPENED, to the node that opened it, in rope order.+ * Wait ropes never name an opener; the first opener rope into a node claims it; a node that records+ * its opener (`recordedOf`) is claimed only by that opener's rope. A claim stands whether or not+ * its source is still on the canvas — a stored (unpruned) file can still hold the rope of an opener+ * that was deleted, and the caller decides what a dead source means.+ *+ * ONE definition, read by team progress (`stationsByOpener`) and by the canvas layout+ * (`tidyCanvas` / `lineageLayers` in state/workspace), so "who opened this node" cannot answer one+ * way on the ring and another way when the canvas is tidied.+ */+export function openerByTarget(+ ropes: unknown,+ recordedOf: (target: string) => string | undefined+): Map<string, string> {+ const out = new Map<string, string>()+ if (!Array.isArray(ropes)) return out+ for (const raw of ropes) {+ const rope = readOpenerRope(raw)+ if (!rope || out.has(rope.target)) continue+ const recorded = recordedOf(rope.target)+ if (recorded && recorded !== rope.source) continue+ out.set(rope.target, rope.source)+ }+ return out+}++/** The opener a node records, read off live node data (`data.openedBy`), checked like the+ * serialized field: an id we would address, and not the node itself. */+export function recordedOpenerOf(node: { id: string; data?: { openedBy?: unknown } } | undefined): string | undefined {+ return node ? recordedOpener({ id: node.id, kind: undefined, openedBy: node.data?.openedBy }) : undefined+}+/*** Stations grouped by the node that opened them (rule 1 above), in rope order. Pass the previous* result to keep each group's array identity — and the map's own identity — when nothing changed:@@ -130,28 +163,18 @@ export function stationsByOpener(if (n && typeof n.id === 'string' && n.kind === 'terminal') sessions.set(n.id, n)}const grouped = new Map<string, TeamStation[]>()- if (Array.isArray(ropes) && sessions.size > 0) {- const opened = new Set<string>()- for (const raw of ropes) {- const rope = readOpenerRope(raw)- if (!rope || opened.has(rope.target)) continue- // A recorded opener names the one rope that may claim this node (rule 1); any other rope- // into it is passed over, not allowed to claim it first.- const recorded = recordedOpener(sessions.get(rope.target))- if (recorded && recorded !== rope.source) continue- // The first opener rope into a target claims it, whether or not its source is still here —- // a stored (unpruned) file can still hold the rope of an opener that was deleted.- opened.add(rope.target)- const node = sessions.get(rope.target)- if (!node || !sessions.has(rope.source)) continue- const list = grouped.get(rope.source) ?? []+ if (sessions.size > 0) {+ for (const [target, source] of openerByTarget(ropes, (id) => recordedOpener(sessions.get(id)))) {+ const node = sessions.get(target)+ if (!node || !sessions.has(source)) continue+ const list = grouped.get(source) ?? []list.push({- id: rope.target,+ id: target,title: typeof node.title === 'string' ? node.title : '',...(typeof node.agentId === 'string' && node.agentId ? { agentId: node.agentId } : {}),queued: !!node.queued})- grouped.set(rope.source, list)+ grouped.set(source, list)}}const out = new Map<string, readonly TeamStation[]>()diff --git a/src/renderer/state/workspace.layout.test.ts b/src/renderer/state/workspace.layout.test.tsindex 5a8d8bc27..225fd54ae 100644--- a/src/renderer/state/workspace.layout.test.ts+++ b/src/renderer/state/workspace.layout.test.ts@@ -7,10 +7,12 @@ import {fitGroupToChildren,groupArrangeRefusal,lineageLayers,+ tidyCanvas,GROUP_PAD,GROUP_HEADER,type CanvasNode} from './workspace'+import { markLegacyWaitRopes, pruneRopes, waitRopeId } from '../lib/edgeModel'// Minimal node stub: only the fields the layout fns read (id, position, width/height, parentId).const n = (id: string, x: number, y: number, w = 100, h = 50): CanvasNode =>@@ -500,3 +502,156 @@ describe('groupArrangeRefusal', () => {expect(arrangeGroupChildren(nodes, 'g1')).not.toBe(nodes)})})++// Ropes as the canvas mints them: an opener is `ctrl-<source>-<target>`, a wait `ctrl-after-…`.+const opens = (source: string, target: string) => ({ id: `ctrl-${source}-${target}`, source, target })+const waits = (dep: string, node: string) => ({ id: waitRopeId(dep, node), source: dep, target: node })+const withOpenedBy = (nd: CanvasNode, openedBy: string): CanvasNode =>+ ({ ...nd, data: { ...nd.data, openedBy } }) as CanvasNode+/** Today's Tidy canvas, verbatim: the reading-order grid over every top-level node. */+const plainTidy = (nodes: CanvasNode[]) =>+ arrangeNodes(+ nodes,+ nodes+ .filter((x) => !x.parentId)+ .sort((a, b) => a.position.y - b.position.y || a.position.x - b.position.x)+ .map((x) => x.id),+ { layout: 'grid' }+ )+const positions = (nodes: CanvasNode[]) => nodes.map((x) => [x.id, x.position.x, x.position.y])++describe('tidyCanvas', () => {+ // The orchestrator reads LAST (bottom-right) and a loose note sits between its stations, which+ // is exactly where the plain grid lost it: packed after everything else, away from its team.+ const team = () => [n('s1', 0, 0), n('s2', 500, 0), n('note', 200, 300), n('orch', 1000, 800)]+ const teamRopes = [opens('orch', 's1'), opens('orch', 's2')]++ it('with no lineage, is exactly the plain reading-order grid', () => {+ const nodes = [n('a', 300, 0), n('b', 0, 0), frame('g', 0, 400), child('k', 'g'), n('c', 900, 100)]+ expect(positions(tidyCanvas(nodes, []))).toEqual(positions(plainTidy(nodes)))+ // Waits alone are not lineage: sequencing between peers does not make anyone an orchestrator.+ expect(positions(tidyCanvas(nodes, [waits('a', 'b'), waits('b', 'c')]))).toEqual(positions(plainTidy(nodes)))+ })++ it('puts the orchestrator first, at its cluster\'s top-left, with its team right beside it', () => {+ const out = tidyCanvas(team(), teamRopes)+ // origin = the units' bounding-box top-left = (0, 0)+ expect(at(out, 'orch').position).toEqual({ x: 0, y: 0 })+ // two stations → a 2-column team grid starting one gap right of the orchestrator+ expect(at(out, 's1').position).toEqual({ x: 140, y: 0 })+ expect(at(out, 's2').position).toEqual({ x: 280, y: 0 })+ // the node nobody opened is packed after the cluster, below it+ expect(at(out, 'note').position).toEqual({ x: 0, y: 90 })+ // and the old grid did put the orchestrator last — what this test exists to catch+ expect(at(plainTidy(team()), 'orch').position).not.toEqual({ x: 0, y: 0 })+ })++ it('clusters a nested team under its own orchestrator, inside the parent\'s team', () => {+ // coord opened lead + solo; lead opened w1 + w2.+ const nodes = [n('w1', 0, 0), n('w2', 900, 0), n('solo', 0, 500), n('lead', 400, 400), n('coord', 800, 800)]+ const out = tidyCanvas(nodes, [opens('coord', 'lead'), opens('coord', 'solo'), opens('lead', 'w1'), opens('lead', 'w2')])+ expect(at(out, 'coord').position).toEqual({ x: 0, y: 0 })+ // coord's team, in reading order: lead (y 400) then solo (y 500), 2 columns.+ expect(at(out, 'lead').position).toEqual({ x: 140, y: 0 })+ // lead's own block: lead, then its team (w1, w2) to its right+ expect(at(out, 'w1').position).toEqual({ x: 280, y: 0 })+ expect(at(out, 'w2').position).toEqual({ x: 420, y: 0 })+ // solo follows lead's whole block in coord's team row+ expect(at(out, 'solo').position).toEqual({ x: 560, y: 0 })+ })++ it('keeps a frame as one rigid unit and lifts a rope into it to the frame', () => {+ // The #1114 shape: a coordinator opens a lead INSIDE a frame; the frame is what moves.+ const nodes = [frame('g', 0, 0, 300, 200), child('lead', 'g', 30, 70), child('w', 'g', 150, 70), n('coord', 600, 600)]+ const out = tidyCanvas(nodes, [opens('coord', 'lead'), opens('lead', 'w')])+ expect(at(out, 'coord').position).toEqual({ x: 0, y: 0 })+ expect(at(out, 'g').position).toEqual({ x: 140, y: 0 })+ // children keep their frame-relative spots+ expect(at(out, 'lead').position).toEqual({ x: 30, y: 70 })+ expect(at(out, 'w').position).toEqual({ x: 150, y: 70 })+ })++ it('follows openers, not waits: a verify panel stays the orchestrator\'s team', () => {+ // orch opened the target and both reviewers; the reviewers WAIT on the target.+ const nodes = [n('t', 0, 0), n('r1', 0, 300), n('r2', 300, 300), n('orch', 900, 900)]+ const out = tidyCanvas(nodes, [opens('orch', 't'), waits('t', 'r1'), opens('orch', 'r1'), waits('t', 'r2'), opens('orch', 'r2')])+ expect(at(out, 'orch').position).toEqual({ x: 0, y: 0 })+ // one team of three (2 columns), in reading order — the target does not lead its reviewers+ expect(at(out, 't').position).toEqual({ x: 140, y: 0 })+ expect(at(out, 'r1').position).toEqual({ x: 280, y: 0 })+ expect(at(out, 'r2').position).toEqual({ x: 140, y: 90 })+ })++ it('reads a legacy canvas (no openedBy, waits unmarked) through the load-time mark', () => {+ // Saved before waits had their own id: the second rope into `x` is p's wait, minted as an opener.+ const legacy = [opens('o', 'x'), opens('p', 'x')]+ const nodes = [n('x', 0, 0), n('p', 400, 0), n('o', 800, 800)]+ const out = tidyCanvas(nodes, markLegacyWaitRopes(legacy))+ expect(at(out, 'o').position).toEqual({ x: 0, y: 0 })+ expect(at(out, 'x').position).toEqual({ x: 140, y: 0 })+ })++ it('honours a recorded openedBy over a surviving rope that is not the opener\'s', () => {+ // x records `o` as its opener; o is gone and its rope with it. p's surviving rope (an unmarked+ // wait from an old file) must not promote p to x's orchestrator.+ const nodes = [withOpenedBy(n('x', 0, 0), 'o'), n('p', 400, 0)]+ expect(positions(tidyCanvas(nodes, [opens('p', 'x')]))).toEqual(positions(plainTidy(nodes)))+ // Without the record, the legacy rope rule makes p the opener.+ const unrecorded = [n('x', 0, 0), n('p', 400, 0)]+ expect(at(tidyCanvas(unrecorded, [opens('p', 'x')]), 'p').position).toEqual({ x: 0, y: 0 })+ })++ it('drops a deleted station and lets a deleted orchestrator\'s team fall loose', () => {+ const live = team().filter((x) => x.id !== 's2')+ const ropes = pruneRopes(teamRopes, new Set(live.map((x) => x.id)))+ const out = tidyCanvas(live, ropes)+ expect(at(out, 'orch').position).toEqual({ x: 0, y: 0 })+ expect(at(out, 's1').position).toEqual({ x: 140, y: 0 })+ // orchestrator deleted: nothing leads anything, so it is the plain grid again — even with the+ // dead rope still in hand (a stored file is not pruned).+ const orphaned = team().filter((x) => x.id !== 'orch')+ expect(positions(tidyCanvas(orphaned, teamRopes))).toEqual(positions(plainTidy(orphaned)))+ })++ it('survives an opener cycle, led by the member that reads first', () => {+ const nodes = [n('b', 500, 0), n('a', 0, 0), n('c', 0, 500)]+ const out = tidyCanvas(nodes, [opens('a', 'b'), opens('b', 'a')])+ expect(at(out, 'a').position).toEqual({ x: 0, y: 0 })+ expect(at(out, 'b').position).toEqual({ x: 140, y: 0 })+ // A cycle that only exists once ropes are lifted to frames: a (in g) opens b, b opens a2 (in g).+ const lifted = [frame('g', 0, 0), child('a', 'g'), child('a2', 'g'), n('b', 600, 0)]+ const out2 = tidyCanvas(lifted, [opens('a', 'b'), opens('b', 'a2')])+ expect(at(out2, 'g').position).toEqual({ x: 0, y: 0 })+ expect(at(out2, 'b').position).toEqual({ x: 340, y: 0 })+ })++ it('gives a frame to the unit that opened most of its contents', () => {+ const nodes = [frame('g', 0, 600), child('k1', 'g'), child('k2', 'g'), child('k3', 'g'), n('x', 0, 0), n('y', 400, 0)]+ const out = tidyCanvas(nodes, [opens('x', 'k1'), opens('y', 'k2'), opens('y', 'k3')])+ // y opened two of g's three children, so g is y's team; x leads nothing and packs loose.+ expect(at(out, 'g').position.x).toBe(at(out, 'y').position.x + 100 + 40)+ expect(at(out, 'g').position.y).toBe(at(out, 'y').position.y)+ // A tie goes to the earliest rope: x opened k1 first, y opened k2 after.+ const tied = tidyCanvas(nodes, [opens('x', 'k1'), opens('y', 'k2')])+ expect(at(tied, 'g').position.x).toBe(at(tied, 'x').position.x + 100 + 40)+ expect(at(tied, 'g').position.y).toBe(at(tied, 'x').position.y)+ })++ it('returns the SAME array when nothing moves', () => {+ const once = tidyCanvas(team(), teamRopes)+ expect(tidyCanvas(once, teamRopes)).toBe(once)+ const single = [n('a', 5, 5)]+ expect(tidyCanvas(single, [])).toBe(single)+ const plain = plainTidy([n('a', 300, 0), n('b', 0, 0), n('c', 0, 300)])+ expect(tidyCanvas(plain, [])).toBe(plain)+ })+})++describe('lineageLayers slots siblings under their OPENER first', () => {+ it('places a node opened by B under B even when it also waits on A', () => {+ // o opened a and b; d was opened by a; c was opened by b but waits on a. c reads before d.+ const nodes = [n('o', 0, 0), n('a', 0, 200), n('b', 300, 200), n('c', 0, 400), n('d', 300, 400)]+ const { layers } = lineageLayers(nodes, [opens('o', 'a'), opens('o', 'b'), opens('a', 'd'), opens('b', 'c'), waits('a', 'c')])+ expect(layers).toEqual([['o'], ['a', 'b'], ['d', 'c']])+ })+})diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex df316738d..bf1573fd4 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -35,6 +35,7 @@ import { sshHostKey } from '@shared/ssh'import { normalizeNodeIcon } from '@shared/node-icon'import { normalizeIssueRef, type IssueRef } from '@shared/github-issue-ref'import { isSafeNodeId } from '@shared/safe-id'+import { openerByTarget, recordedOpenerOf } from '../lib/teamProgress'import { normalizePendingLaunch } from '@shared/pending-launch-shape'import { normalizeTerminalFontSize } from '../terminal/terminal-font-zoom'import { useSettings } from './settings'@@ -1374,12 +1375,24 @@ export function arrangeNodes(return nodes.map((nd) => (pos.has(nd.id) ? { ...nd, position: pos.get(nd.id)! } : nd))}-/** One lineage rope, as the canvas persists it (`project.ropes`): "opened by" / "--after". */+/**+ * One lineage rope, as the canvas persists it (`project.ropes`): "opened by" or a wait (`--after`).+ * The `id` is what tells the two apart (`waitRopeId`, lib/edgeModel): pass it through, or every+ * rope reads as an opener rope.+ */export interface LineageEdge {+ id?: stringsource: stringtarget: string}+/** Every node's opener (rule 1 of lib/teamProgress — `data.openedBy` first, else the first opener+ * rope into it; wait ropes never), keyed by the opened node's id. */+function openersOf(nodes: CanvasNode[], edges: readonly LineageEdge[]): Map<string, string> {+ const byId = new Map(nodes.map((nd) => [nd.id, nd]))+ return openerByTarget(edges, (id) => recordedOpenerOf(byId.get(id)))+}+/*** For every node INSIDE `containerId` (`null` = the top level), the direct member of that* container it belongs to, by id. A rope points at the NODE an agent opened, which is routinely a@@ -1489,9 +1502,22 @@ export function lineageLayers(layers[level].push(nd.id)}- // Inside a layer, siblings sit together: a node follows its earliest opener's slot in the layer- // above, so the ropes fan out instead of crossing. Layer 0 and `loose` have no opener to follow- // and keep the canvas's own reading order.+ // The member that OPENED each member (lifted like the ropes), for the slot rule below.+ const openerOfMember = new Map<string, string>()+ for (const [target, source] of openersOf(nodes, edges)) {+ const to = tops.get(target)+ const from = tops.get(source)+ if (to && from && to !== from && live.has(to) && live.has(from) && !openerOfMember.has(to)) {+ openerOfMember.set(to, from)+ }+ }++ // Inside a layer, siblings sit together: a node follows its OPENER's slot in the layer above when+ // the opener is there, else its earliest predecessor's, so the ropes fan out instead of crossing.+ // Opener first because layering reads BOTH relations (a wait is a flow edge too, and longest-path+ // keeps it pointing down) while a node has exactly one opener — the team it belongs to. A node+ // opened by B that waits on A sits under B, with the rest of B's team. Layer 0 and `loose` have+ // no opener to follow and keep the canvas's own reading order.layers.forEach((layer, level) => {if (level === 0) {layer.sort(byReadingOrder)@@ -1499,6 +1525,9 @@ export function lineageLayers(}const above = new Map(layers[level - 1].map((id, i) => [id, i]))const slotOf = (id: string): number => {+ const opener = openerOfMember.get(id)+ const openerSlot = opener !== undefined ? above.get(opener) : undefined+ if (openerSlot !== undefined) return openerSlotlet best = Number.MAX_SAFE_INTEGERfor (const from of preds.get(id) ?? []) {const slot = above.get(from)@@ -1553,6 +1582,181 @@ export function arrangeByLineage(return out}+/** A laid-out rectangle of units, positions relative to its own top-left. */+interface TidyBlock {+ w: number+ h: number+ place: { id: string; x: number; y: number }[]+}++/** `arrangeNodes`' grid flow, over blocks: left to right, wrapping at `cols`, each row advancing+ * by its tallest block. */+function flowBlocks(blocks: TidyBlock[], cols: number, gap: number): TidyBlock {+ const place: TidyBlock['place'] = []+ let x = 0+ let y = 0+ let rowH = 0+ let w = 0+ blocks.forEach((b, i) => {+ if (i > 0 && i % cols === 0) {+ x = 0+ y += rowH + gap+ rowH = 0+ }+ for (const p of b.place) place.push({ id: p.id, x: p.x + x, y: p.y + y })+ w = Math.max(w, x + b.w)+ x += b.w + gap+ rowH = Math.max(rowH, b.h)+ })+ return { w, h: y + rowH, place }+}++/** Reading order of the canvas as it stands — Tidy canvas's own comparator, stable on array order. */+const byReadingPosition = (a: CanvasNode, b: CanvasNode): number =>+ a.position.y - b.position.y || a.position.x - b.position.x++/**+ * **Tidy canvas.** Packs every top-level node (a group frame is one rigid unit, its children ride+ * along) into a non-overlapping layout — and keeps each ORCHESTRATOR legible: a unit that opened+ * other units is placed first, at the top-left of its own cluster, with the units it opened packed+ * in a grid directly to its right, and a unit THEY opened clustered the same way inside that grid.+ * Clusters are packed in reading order of their orchestrators; every unit with no lineage at all is+ * packed after them, below, exactly as the plain grid packs it.+ *+ * The relation is OPENER ONLY (rule 1 of lib/teamProgress, through `openerByTarget`: the node's+ * recorded `data.openedBy` when it has one, else the first non-wait rope into it). Not waits:+ * a wait is sequencing between peers — a verify panel's reviewers wait on the node they review,+ * but the orchestrator opened them — so following waits would pull an orchestrator's team apart+ * under whichever station it waits on. And a node has exactly one opener, so the clusters are a+ * forest and the layout has one answer. (The bands of `arrangeByLineage` read both relations;+ * they answer "in what order does work flow", this answers "whose team is this".)+ *+ * - **Ropes are lifted to the top-level unit that holds their end**, as `lineageLayers` does: an+ * orchestrator opens its stations inside a frame, and the frame is what moves. A rope internal+ * to one frame says nothing at this level. A frame whose children were opened by different units+ * belongs to the one that opened the most of them (ties: the earliest rope); a node's own opener+ * always wins for that node.+ * - **A cycle never hangs.** Openers are not supposed to form one, but frames lift ropes into one+ * easily (A in frame F opens B outside, B opens C inside F) and project.json is hand-editable.+ * The member of a cycle that comes first in reading order loses its opener and leads the cluster.+ * - **A rope whose end is gone is ignored** — the canvas prunes it, and an opener that is not here+ * cannot lead anything; its stations simply become loose.+ * - **No lineage ⇒ exactly the plain grid**: `arrangeNodes(grid)` over the reading-order ids, the+ * transform this command has always run.+ *+ * Returns the SAME array when no unit moves (fewer than two units, or a canvas already tidied),+ * which is the caller's signal to skip the undo entry and the project.json write. Pure.+ */+export function tidyCanvas(+ nodes: CanvasNode[],+ edges: readonly LineageEdge[] = [],+ opts?: { gap?: number }+): CanvasNode[] {+ const units = nodes.filter((nd) => !nd.parentId).sort(byReadingPosition)+ if (units.length < 2) return nodes+ const gap = opts?.gap ?? 40+ const order = new Map(units.map((u, i) => [u.id, i]))+ const unitOf = containerAncestors(nodes, null)++ // Opener of each UNIT. A node's own opener is its opener; a frame takes the unit that opened the+ // most of its contents, ties going to the earliest rope.+ const parent = new Map<string, string>()+ const votes = new Map<string, Map<string, number>>()+ for (const [target, source] of openersOf(nodes, edges)) {+ const u = unitOf.get(target)+ const o = unitOf.get(source)+ if (!u || !o || u === o) continue+ if (target === u) {+ parent.set(u, o)+ continue+ }+ const forU = votes.get(u) ?? new Map<string, number>()+ forU.set(o, (forU.get(o) ?? 0) + 1) // first insertion = earliest rope, kept on a tie below+ votes.set(u, forU)+ }+ for (const [u, forU] of votes) {+ if (parent.has(u)) continue+ let best: string | undefined+ let bestN = 0+ for (const [o, n] of forU) {+ if (n > bestN) {+ best = o+ bestN = n+ }+ }+ if (best !== undefined) parent.set(u, best)+ }++ // Break every cycle at its member that reads first.+ for (const u of units) {+ for (;;) {+ const path: string[] = []+ const onPath = new Set<string>()+ let cur: string | undefined = u.id+ while (cur !== undefined && !onPath.has(cur)) {+ path.push(cur)+ onPath.add(cur)+ cur = parent.get(cur)+ }+ if (cur === undefined) break+ const cycle = path.slice(path.indexOf(cur))+ const lead = cycle.reduce((a, b) => ((order.get(a) ?? 0) <= (order.get(b) ?? 0) ? a : b))+ parent.delete(lead)+ }+ }++ const children = new Map<string, string[]>()+ for (const u of units) {+ const p = parent.get(u.id)+ if (p === undefined) continue+ const list = children.get(p) ?? []+ list.push(u.id) // `units` is in reading order, so every list is too+ children.set(p, list)+ }++ const roots = units.filter((u) => !parent.has(u.id) && children.has(u.id))+ const loose = units.filter((u) => !parent.has(u.id) && !children.has(u.id)).map((u) => u.id)+ const unmoved = (out: CanvasNode[]): CanvasNode[] =>+ out.every((nd, i) => nd.position.x === nodes[i].position.x && nd.position.y === nodes[i].position.y)+ ? nodes+ : out+ if (roots.length === 0) return unmoved(arrangeNodes(nodes, units.map((u) => u.id), { layout: 'grid', gap }))++ const byId = new Map(units.map((u) => [u.id, u]))+ const blockOf = (id: string): TidyBlock => {+ const self = byId.get(id)!+ const w = nodeW(self)+ const h = nodeH(self)+ const kids = children.get(id) ?? []+ if (kids.length === 0) return { w, h, place: [{ id, x: 0, y: 0 }] }+ const team = flowBlocks(kids.map(blockOf), Math.ceil(Math.sqrt(kids.length)), gap)+ return {+ w: w + gap + team.w,+ h: Math.max(h, team.h),+ place: [{ id, x: 0, y: 0 }, ...team.place.map((p) => ({ id: p.id, x: p.x + w + gap, y: p.y }))]+ }+ }+ const clusters = flowBlocks(roots.map((r) => blockOf(r.id)), Math.ceil(Math.sqrt(roots.length)), gap)++ const origin = {+ x: Math.min(...units.map((u) => u.position.x)),+ y: Math.min(...units.map((u) => u.position.y))+ }+ const pos = new Map(clusters.place.map((p) => [p.id, { x: origin.x + p.x, y: origin.y + p.y }]))+ let out = nodes.map((nd) => {+ const p = pos.get(nd.id)+ return p && (p.x !== nd.position.x || p.y !== nd.position.y) ? { ...nd, position: p } : nd+ })+ if (loose.length > 0) {+ out = arrangeNodes(out, loose, {+ layout: 'grid',+ gap,+ origin: { x: origin.x, y: origin.y + clusters.h + gap }+ })+ }+ return unmoved(out)+}+/*** Why `arrangeGroupChildren` has nothing to do for this frame, as a sentence a menu row can show* and a control reply can carry — or `null` when it can run. ONE definition for both, so the row'sdiff --git a/src/server/control-unsupported.test.ts b/src/server/control-unsupported.test.tsindex 3e3e4ef13..6e48335e3 100644--- a/src/server/control-unsupported.test.ts+++ b/src/server/control-unsupported.test.ts@@ -445,7 +445,7 @@ describe('the enabled Server Edition handler parses and dispatches the v1 surfac// `--group` must take that same named refusal rather than be ignored on the way to something// that answers ok.const handler = createServerEditionControlHandler(actions())- const forms: Record<string, string>[] = [{ nodes: 'a,b' }, { group: 'g1', layout: 'lineage' }]+ const forms: Record<string, string>[] = [{ nodes: 'a,b' }, { group: 'g1', layout: 'lineage' }, { group: 'top' }]for (const args of forms) {const reply = await handler({ verb: 'arrange', nodeId: 'term-source', args, verified: true })expect(reply).toMatchObject({ ok: false, error: CONTROL_UNSUPPORTED_ERROR })diff --git a/src/shared/arrange-verb.test.ts b/src/shared/arrange-verb.test.tsindex bbbe6f1f0..b2ac2953a 100644--- a/src/shared/arrange-verb.test.ts+++ b/src/shared/arrange-verb.test.ts@@ -3,13 +3,15 @@ import {ARRANGE_LAYOUTS,GROUP_ARRANGE_LAYOUTS,arrangeArgsRefusal,- arrangeGroupGuidanceLines+ arrangeGroupGuidanceLines,+ isTopLevelGroupArg,+ TOP_ARRANGE_LAYOUTS} from './arrange-verb'describe('arrangeArgsRefusal', () => {it('needs one of the two forms', () => {- expect(arrangeArgsRefusal({})).toBe('arrange requires --nodes <id,id> or --group <frameId>')- expect(arrangeArgsRefusal({ layout: 'row' })).toBe('arrange requires --nodes <id,id> or --group <frameId>')+ expect(arrangeArgsRefusal({})).toBe('arrange requires --nodes <id,id>, --group <frameId> or --group top')+ expect(arrangeArgsRefusal({ layout: 'row' })).toBe('arrange requires --nodes <id,id>, --group <frameId> or --group top')})it('accepts either form on its own', () => {@@ -42,6 +44,23 @@ describe('arrangeArgsRefusal', () => {})})+describe('arrange --group top', () => {+ it('names the top level with the same words move reads', () => {+ for (const g of ['top', 'none', 'ungrouped', ' top ']) expect(isTopLevelGroupArg(g)).toBe(true)+ for (const g of [undefined, '', 'g1', 'topnot']) expect(isTopLevelGroupArg(g)).toBe(false)+ })++ it('takes tidy (the default) or lineage, and refuses anything else by name', () => {+ expect(arrangeArgsRefusal({ group: 'top' })).toBeNull()+ for (const layout of TOP_ARRANGE_LAYOUTS) expect(arrangeArgsRefusal({ group: 'top', layout })).toBeNull()+ // A top-level grid that ignores lineage is what Tidy no longer is; --nodes still says it.+ expect(arrangeArgsRefusal({ group: 'top', layout: 'grid' })).toBe('arrange --group top: --layout must be tidy|lineage')+ // `tidy` names the whole canvas; on a frame it is not a layout.+ expect(arrangeArgsRefusal({ group: 'g1', layout: 'tidy' })).toMatch(/--layout must be grid\|row\|column\|lineage/)+ expect(arrangeArgsRefusal({ group: 'top', nodes: 'a,b' })).toMatch(/not both/)+ })+})+describe('arrangeGroupGuidanceLines', () => {const text = arrangeGroupGuidanceLines().join('\n')@@ -56,4 +75,11 @@ describe('arrangeGroupGuidanceLines', () => {expect(text).toContain('top-left stays where it is')expect(text).toContain('never both')})++ it('documents the whole-canvas form with the layouts the parser accepts', () => {+ expect(text).toContain(`arrange --group top [--layout ${TOP_ARRANGE_LAYOUTS.join('|')}]`)+ expect(text).toContain("exactly as the\n user's Tidy canvas command does")+ expect(text).toMatch(/top-left of the nodes and\s+frames it opened/)+ expect(text).toMatch(/opened-by only; an\s+`--after` wait does not move anything/)+ })})diff --git a/src/shared/arrange-verb.ts b/src/shared/arrange-verb.tsindex 0ee7902c4..8bd95b05a 100644--- a/src/shared/arrange-verb.ts+++ b/src/shared/arrange-verb.ts@@ -17,6 +17,24 @@ export type ArrangeLayout = (typeof ARRANGE_LAYOUTS)[number]export const GROUP_ARRANGE_LAYOUTS = [...ARRANGE_LAYOUTS, 'lineage'] as constexport type GroupArrangeLayout = (typeof GROUP_ARRANGE_LAYOUTS)[number]+/**+ * What the TOP LEVEL of the canvas can be laid out as, through `arrange --group top`: `tidy` is the+ * Tidy canvas command itself (every top-level unit packed, each orchestrator at the top-left of the+ * team it opened), `lineage` its bands. The id-list packs are not offered here — `--nodes` already+ * says them, and a top-level grid that ignores lineage is exactly what Tidy no longer does.+ */+export const TOP_ARRANGE_LAYOUTS = ['tidy', 'lineage'] as const+export type TopArrangeLayout = (typeof TOP_ARRANGE_LAYOUTS)[number]++/**+ * `--group` values that name the canvas's top level instead of a frame — the same words `move`+ * reads as "out of every frame", so the two verbs agree about what `top` means.+ */+export function isTopLevelGroupArg(group: string | undefined): boolean {+ const g = group?.trim()+ return g === 'top' || g === 'none' || g === 'ungrouped'+}+/*** The shape gate for `arrange`'s flags, or `null` when the request is well-formed. Whether the* frame exists, has children or has any lineage is the canvas's to answer (`groupArrangeRefusal`);@@ -34,11 +52,17 @@ export type GroupArrangeLayout = (typeof GROUP_ARRANGE_LAYOUTS)[number]export function arrangeArgsRefusal(args: Record<string, string>): string | null {const hasNodes = !!args.nodesconst hasGroup = !!args.group- if (!hasNodes && !hasGroup) return 'arrange requires --nodes <id,id> or --group <frameId>'+ if (!hasNodes && !hasGroup) return 'arrange requires --nodes <id,id>, --group <frameId> or --group top'if (hasNodes && hasGroup) {return 'arrange takes --nodes <id,id> or --group <frameId>, not both — name the frame to arrange its own items, or list sibling nodes'}const layout = args.layout+ if (hasGroup && isTopLevelGroupArg(args.group)) {+ if (layout && !(TOP_ARRANGE_LAYOUTS as readonly string[]).includes(layout)) {+ return `arrange --group top: --layout must be ${TOP_ARRANGE_LAYOUTS.join('|')}`+ }+ return null+ }if (hasGroup && layout && !(GROUP_ARRANGE_LAYOUTS as readonly string[]).includes(layout)) {return `arrange --group: --layout must be ${GROUP_ARRANGE_LAYOUTS.join('|')}`}@@ -61,6 +85,13 @@ export function arrangeGroupGuidanceLines(): string[] {' nothing overflows. The frame\'s top-left stays where it is. `--layout lineage` stacks one row per',' level of who opened whom among those children; it is refused, with the reason, when no opened-by',' or `--after` connection joins two of them. Pass `--nodes` or `--group`, never both. This is the',- ' one call to make after `group`, or after opening stations into a frame.'+ ' one call to make after `group`, or after opening stations into a frame.',+ `- \`arrange --group top [--layout ${TOP_ARRANGE_LAYOUTS.join('|')}]\` — tidy the WHOLE canvas, exactly as the`,+ ' user\'s Tidy canvas command does: every top-level node and frame (a frame moves as one unit) is',+ ' packed without overlap, and each orchestrator is placed first, at the top-left of the nodes and',+ ' frames it opened, with the team it opened packed directly to its right (opened-by only; an',+ ' `--after` wait does not move anything). Nodes nobody opened are packed after the teams.',+ ' `--layout lineage` instead stacks one row per level of opened-by and `--after`. Call it once',+ ' after spawning teams, not after every open.']}