Skip to content

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.

feat(canvas): arrange the items inside a group, and size the group to hold them

Fabricio Casalib522230c4452
diff --git a/CLAUDE.md b/CLAUDE.md
index 0a1eed611..11acd001f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4081,10 +4081,30 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
frames, which `group` won't do; a cycle (a frame into itself or its own descendant) is refused.
`arrange`/`align` now run in ONE coordinate space: all top-level, OR all children of one frame
(`commonParentId` decides; a mixed set is refused, not silently subset-arranged — the old
- behavior). When the ids are a frame's children, the frame is shrunk to hug the tidied layout
- (`fitGroupToChildren`) — the fix for "grouping keeps scattered positions so the frame is too
- wide". `move` also re-fits the source + destination frames. All pure + tested in
- `state/workspace.test.ts` + `workspace.layout.test.ts`.
+ behavior). When the ids are a frame's children, that frame AND every ancestor frame are re-fitted
+ to hug the tidied layout (`fitAncestorChain` — fitting only the one frame left a nested frame
+ wider than its parent) — the fix for "grouping keeps scattered positions so the frame is too
+ wide". `arrange` fills its slots in the order the ids are LISTED (`arrangeNodes` used to place in
+ array order, which discarded every caller's sort). `move` also re-fits the source + destination
+ frames. All pure + tested in `state/workspace.test.ts` + `workspace.layout.test.ts`.
+ **`arrange --group <frameId> [--layout grid|row|column|lineage] [--cols N]`** names the FRAME
+ instead of listing its children: the frame's direct children are laid out and the frame chain is
+ re-fitted — `arrangeGroupChildren`, the SAME transform the frame's menu rows run (see
+ **Arrange inside a group** under Canvas interaction). The flag gate is the pure
+ `arrangeArgsRefusal` (`@shared/arrange-verb`, called from `parseControlRequest`): `--nodes` and
+ `--group` together are refused rather than resolved silently, an unknown `--layout` on the
+ `--group` form is refused by name, and `--layout lineage` on the `--nodes` form is refused
+ instead of being delivered as a grid (any OTHER unknown word there still falls back to `grid`,
+ as it always has). What only the canvas knows — no such frame, an empty frame, no lineage among
+ the children — is `groupArrangeRefusal`, replied as `arrange: <reason>`; a frame already in
+ place answers `ok` with `changed: false` and writes nothing. The agent-facing text for the form
+ is `arrangeGroupGuidanceLines`, rendered into BOTH generated bodies from the same layout list the
+ gate checks. **Server Edition: refused by name** — `arrange` is not in `SERVER_V1_VERBS` in either
+ form (headless control keeps no measured node sizes), so `--group` gets the same permanent
+ `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 is refused like the `--nodes` form
+ (`OFF_SCREEN_REFUSALS`); the dispatch branch is deliberately thin so moving `arrange` off-screen
+ touches only where the node array comes from.
**Fan-in (`link`, 2026-07):** a spawned fan-out was previously write-only — nodes an agent
opened were joined to it by a **rope** (`project.ropes`, explicitly *"Display-only — never
context links"*), so an orchestrator could not read back what its own team produced and the
@@ -6472,9 +6492,41 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
processed and is therefore still false on the next line (it would cost every run its `markDirty`
+ `fitAll`). The pane row is then DISABLED with its reason while the palette OMITS it (no
disabled state there). Built ON `arrangeNodes` — one `row` placement per band from a shared left
- origin — so packing, gap and the mixed-container refusal stay in ONE place. 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).
+ origin — so packing, gap and the mixed-container refusal stay in ONE place. **That only holds
+ because `arrangeNodes` fills its slots in the order of the ids it is handed**: it used to place
+ in ARRAY order, which threw away the slot order `lineageLayers` computes (siblings under their
+ opener) AND the reading-order sort `arrangeAllNodes` documents, with every existing test green
+ because 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).
+- **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 all
+ three, pinned by `canvas/arrange-group.source.test.ts`) — the two canvas tidies one level down:
+ organize a frame's own items, then size the frame to hold them. Four rules: **(1)** the members
+ are the frame's DIRECT children, so a nested frame moves as one rigid unit with its own children
+ untouched, exactly as Tidy canvas treats a top-level frame; `lineageLayers` /
+ `arrangeByLineage` take a `containerId` for this, a rope is lifted to the MEMBER that holds its
+ end, and a rope with an end outside the frame is dropped — the opener of a frame's whole team
+ usually sits outside it and says nothing about the order inside. **(2)** the layout starts at
+ the offset a fitted frame keeps its content at (`GROUP_PAD`, plus `GROUP_HEADER`), NOT at the
+ children's bounding box: `fitGroupToChildren` re-anchors a frame to hug its children, so
+ starting from the bounding box moves the frame to wherever its top-left child happened to sit,
+ while starting from the content origin makes the fit re-derive the SAME origin and the frame
+ only grows or shrinks to the right and downward (a frame that was off the grid still moves onto
+ it, by under one cell, when snapping is on). That is also why the action calls no `fitAll` — the
+ thing the user right-clicked must not slide out from under the cursor. **(3)** the fit walks UP
+ the parent chain, innermost first (`fitAncestorChain`): fitting only the frame leaves a parent
+ smaller than the child it holds, and `extent:'parent'` then clamps that child into an inverted
+ range. **(4)** the refusal is the SAME array — a missing or empty frame, a lineage layout with no
+ rope joining two of the children, or a frame whose contents already sit where the layout puts
+ them (compared by geometry, so a second click writes no undo entry and no `project.json`); as
+ with the canvas tidies the verdict is read off `nodesRef` BEFORE the write. The menu rows are
+ DISABLED with the reason `groupArrangeRefusal` gives, the palette OMITS a refused entry, and the
+ CLI replies that reason by name — one sentence, three surfaces. Desktop + Server Edition
+ identical for the menu and palette (pure renderer, no new IPC); the control verb is desktop-only
+ (see Grouping verbs); kanban N/A; Mobile N/A (no canvas).
- **Add menu** = bottom dock (`Dock.tsx`) `+`, mirrored by the pane menu and command palette.
`lib/addMenuSpec` is the one source for WHICH kinds are addable, and since 2026-09 also for how
the two `ContextMenu` surfaces GROUP them: `New terminal` · `New remote…` · the account-capable
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index 91e8494e1..2ea6ac762 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -21,6 +21,7 @@ import { BROWSER_RETRYABLE, BROWSER_OUTCOME_LABEL } from './browser-outcomes'
import { BROWSER_KEYS, BROWSER_TIMEOUT_DEFAULT_MS, BROWSER_TIMEOUT_MAX_MS } from './browser-verb'
import { nodeColorChoices } from '@shared/node-colors'
import { offScreenGuidanceLines } from '@shared/control-off-screen'
+import { arrangeArgsRefusal, arrangeGroupGuidanceLines } from '@shared/arrange-verb'
import { codexThreadIdentityResolverSh } from './codex-thread-identity-sh'
import { ISSUE_SESSION_COLUMNS, issueLaunchPrompt, parseIssueArg } from '../shared/github-issue-ref'
import { BOARD_COMMENT_FROM_PREFIX, BOARD_COMMENT_REPLY_TO } from '../shared/board-comment'
@@ -725,7 +726,12 @@ export function parseControlRequest(
if (v === 'report-outcome' && !args.outcome) {
return { error: 'report-outcome requires --outcome succeeded|failed' }
}
- if ((v === 'group' || v === 'arrange') && !args.nodes) return { error: `${v} requires --nodes <id,id>` }
+ if (v === 'group' && !args.nodes) return { error: 'group requires --nodes <id,id>' }
+ // `arrange` has two forms (`--nodes` or `--group`); the gate is shared with the generated docs.
+ if (v === 'arrange') {
+ const arrangeRefusal = arrangeArgsRefusal(args)
+ if (arrangeRefusal) return { error: arrangeRefusal }
+ }
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>' }
@@ -949,7 +955,9 @@ export function buildCanvasControlInstructions(shimPath: string): string {
'- `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.',
+ ' arrange across frames in one call). `arrange` places the nodes in the order you list them, and',
+ ' arranging a frame\'s children also re-fits that frame and every frame around it.',
+ ...arrangeGroupGuidanceLines(),
'- `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, and the stations you name in `--after`, are already',
@@ -1537,9 +1545,12 @@ ${reportOutcomeDocLines().join('\n')}
Invalid cycles are rejected.
- \`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.
+ arrange nodes from two different frames, or mix framed + loose, in one call). The nodes are placed
+ in the order you list them. When the ids are a frame's children, that frame and every frame around
+ it are also re-fitted to hug the tidied layout.
+${arrangeGroupGuidanceLines().join('\n')}
+ Since grouping preserves each node's scattered position, a fresh frame is usually the wrong size:
+ \`arrange --group\` it 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's
@@ -1696,7 +1707,7 @@ 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/Copilot session" → \`open-agent --agent codex|gemini|copilot\`.
-- "Tidy up / group my terminals" → \`list\`, then \`group --nodes …\`, then \`arrange --nodes <those same ids>\`
+- "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).
- "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>\`.
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index 0116f7743..3478816f0 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -103,6 +103,49 @@ describe('parseControlRequest', () => {
})
})
+ it('arrange --group names a frame; its flag refusals are decided before any canvas is asked', () => {
+ expect(parseControlRequest('arrange', { group: 'g1', layout: 'lineage', cols: '3' })).toEqual({
+ verb: 'arrange',
+ args: { group: 'g1', layout: 'lineage', cols: '3' }
+ })
+ // Both forms at once has two answers to "which nodes" — refused, never silently resolved.
+ const both = parseControlRequest('arrange', { nodes: 'a,b', group: 'g1' })
+ expect('error' in both && both.error).toMatch(/--nodes <id,id> or --group <frameId>, not both/)
+ // An unknown layout on the new form is refused by name, listing what is accepted.
+ expect(parseControlRequest('arrange', { group: 'g1', layout: 'spiral' })).toEqual({
+ error: 'arrange --group: --layout must be grid|row|column|lineage'
+ })
+ // `lineage` is a question about a container: on an id list it would be delivered as a grid.
+ const lineageOnNodes = parseControlRequest('arrange', { nodes: 'a,b', layout: 'lineage' })
+ expect('error' in lineageOnNodes && lineageOnNodes.error).toMatch(/--layout lineage needs --group <frameId>/)
+ })
+
+ it('both bodies document arrange --group: the layouts, the resize up the chain and the stable origin', () => {
+ for (const [name, body] of [
+ ['skill', buildCanvasSkillBody('/x/shim.sh')],
+ ['instructions', buildCanvasControlInstructions('/x/shim.sh')]
+ ] as const) {
+ expect(body, name).toContain('- `arrange --group <frameId> [--layout grid|row|column|lineage] [--cols N]`')
+ // 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\)/)
+ expect(body, name).toMatch(/resizes the frame — and every frame around it — to hold them/)
+ expect(body, name).toMatch(/top-left stays where it is/)
+ expect(body, name).toMatch(/Pass `--nodes` or `--group`, never both/)
+ expect(body, name).toMatch(/it is refused, with the reason, when no opened-by\s+or `--after` connection joins two of them/)
+ // The `--nodes` form's two facts that changed with it: listed order, and the ancestor re-fit.
+ expect(body, name).toMatch(/in the order you list them/)
+ // The stale claim this replaced — a frame was only ever "shrunk", and only the one frame.
+ expect(body, name).not.toMatch(/shrinks the frame to fit|also shrunk to hug/)
+ }
+ })
+
+ it('the skill playbook reaches for arrange --group after grouping, not a re-listed id set', () => {
+ 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>')
+ })
+
it('run requires --node (#925)', () => {
expect(parseControlRequest('run', {})).toEqual({ error: 'run requires --node <id>' })
expect(parseControlRequest('run', { node: 'n1' })).toEqual({ verb: 'run', args: { node: 'n1' } })
@@ -230,10 +273,16 @@ describe('parseControlRequest', () => {
expect(isDestructiveVerb('show-image')).toBe(false)
})
- it('group/arrange require --nodes; align also requires --edge', () => {
+ it('group requires --nodes; arrange takes --nodes or --group; align also requires --edge', () => {
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>' })
+ expect(parseControlRequest('arrange', {})).toEqual({
+ error: 'arrange requires --nodes <id,id> or --group <frameId>'
+ })
+ expect(parseControlRequest('arrange', { nodes: 'a,b', layout: 'row' })).toEqual({
+ verb: 'arrange',
+ args: { nodes: 'a,b', layout: 'row' }
+ })
expect(parseControlRequest('align', { nodes: 'a' })).toEqual({ error: 'align requires --edge' })
expect(parseControlRequest('align', { nodes: 'a', edge: 'left' })).toEqual({
verb: 'align',
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 9b4025ecd..f703ff262 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -765,7 +765,12 @@ import {
COLLAPSED_HEIGHT,
alignNodes,
arrangeByLineage,
+ arrangeGroupChildren,
arrangeNodes,
+ fitAncestorChain,
+ groupArrangeRefusal,
+ GROUP_ARRANGE_LAYOUTS,
+ type GroupArrangeLayout,
lineageLayers,
commonParentId,
fitGroupToChildren,
@@ -8491,6 +8496,32 @@ export function Canvas() {
fitAll()
}, [setNodes, markDirty, fitAll, lineageEdges])
+ // Why a group frame's contents cannot be organized, as the sentence its menu row shows — or
+ // null. The pure half is `groupArrangeRefusal`, which the `arrange --group` verb reads too, so
+ // the row's disabled reason and the CLI's refusal are one definition.
+ const groupArrangeHint = useCallback(
+ (groupId: string, layout: GroupArrangeLayout): string | null => {
+ const why = groupArrangeRefusal(nodesRef.current as CanvasNode[], groupId, layout, lineageEdges())
+ return why ? `${why[0].toUpperCase()}${why.slice(1)}.` : null
+ },
+ [lineageEdges]
+ )
+ // Organize ONE frame's own items and size the frame (and every ancestor frame) to hold them.
+ // Same refusal discipline as the two canvas tidies: decided against nodesRef BEFORE the write,
+ // and `arrangeGroupChildren` returning the SAME array is what keeps a no-op out of the undo
+ // stack and out of project.json. No `fitAll`: the frame's top-left stays where it was, so the
+ // thing the user just right-clicked must not slide out from under the cursor.
+ const arrangeGroupAction = useCallback(
+ (groupId: string, layout: GroupArrangeLayout) => {
+ if (isGlobalKanbanOpen() || isKanbanOpen(useProjects.getState().activeProjectId)) return
+ const opts = { layout, edges: lineageEdges(), grid: snapGridNow() }
+ if (arrangeGroupChildren(nodesRef.current as CanvasNode[], groupId, opts) === nodesRef.current) return
+ setNodes((ns) => arrangeGroupChildren(ns as CanvasNode[], groupId, opts))
+ markDirty()
+ },
+ [setNodes, markDirty, lineageEdges]
+ )
+
/** Report a refusal the user cannot act on any other way. One dismiss button, no default. */
const alertLayout = useCallback(
(message: string) => {
@@ -10275,6 +10306,8 @@ export function Canvas() {
addSelectionToGroup(nodesRef.current as CanvasNode[], selectedIds, groupId) !==
nodesRef.current
const groupHidden = isHidden('group', useSettings.getState().settings.hiddenNodeMenuItems)
+ const tidyRefusal = groupArrangeHint(groupId, 'grid')
+ const lineageRefusal = groupArrangeHint(groupId, 'lineage')
// The group frame has its own colors strip; it answers to the same "Colors" toggle as the
// node menu, so hiding it in Settings hides it everywhere a right-click can reach it.
return tidySeparators([
@@ -10312,6 +10345,24 @@ export function Canvas() {
// `cwdForNewNodeIn` is what makes a frame per branch also mean a file tree per branch.
{ label: 'New file manager', icon: <IconExplorer />, onClick: () => addFiles(at, groupId) },
{ type: 'separator' },
+ // The two canvas tidies, one level down: organize THIS frame's own items and size the
+ // frame (and its ancestors) to hold them. Disabled WITH the reason rather than hidden —
+ // the pane menu's rule: a row that is off for an invisible reason teaches nothing.
+ {
+ label: 'Tidy group',
+ icon: <IconGrid />,
+ disabled: !!tidyRefusal,
+ hint: tidyRefusal ?? 'Pack the items in a grid and resize the group to fit.',
+ onClick: () => arrangeGroupAction(groupId, 'grid')
+ },
+ {
+ label: 'Arrange group by lineage',
+ icon: <IconLineage />,
+ disabled: !!lineageRefusal,
+ hint: lineageRefusal ?? 'One row per level: who opened whom, top to bottom.',
+ onClick: () => arrangeGroupAction(groupId, 'lineage')
+ },
+ { type: 'separator' },
...(isHidden('colors', useSettings.getState().settings.hiddenNodeMenuItems)
? []
: ([{ type: 'colors', onPick: (c) => setNodesColor([groupId], c) }] as MenuItem[])),
@@ -10348,7 +10399,9 @@ export function Canvas() {
agentCreationEntries,
addSticky,
addToExistingGroup,
- groupSelection
+ groupSelection,
+ groupArrangeHint,
+ arrangeGroupAction
]
)
@@ -13981,8 +14034,47 @@ export function Canvas() {
}
case 'arrange':
case 'align': {
- const ids = (args.nodes ?? '').split(',').map((s) => s.trim()).filter(Boolean)
const live = nodesRef.current as CanvasNode[]
+ // `arrange --group <frameId>`: name the FRAME instead of listing its children. The
+ // whole rule set is `arrangeGroupChildren` — the same transform the frame's menu rows
+ // and the palette run — so this branch only parses, refuses by name and replies.
+ if (verb === 'arrange' && args.group) {
+ const gid = args.group.trim()
+ const groupLayout = GROUP_ARRANGE_LAYOUTS.find((l) => l === args.layout) ?? 'grid'
+ const edges = 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}` })
+ return
+ }
+ const cols = args.cols ? parseInt(args.cols, 10) || undefined : undefined
+ const next = arrangeGroupChildren(live, gid, { layout: groupLayout, cols, edges, grid: snapGridNow() })
+ const count = live.filter((nd) => nd.parentId === gid).length
+ // The SAME array means every item already sat where the layout puts it: an answer,
+ // not a failure — and nothing to write.
+ if (next !== live) {
+ setNodes(next)
+ markDirty()
+ }
+ const frame = next.find((nd) => nd.id === gid)
+ reply({
+ ok: true,
+ message:
+ next === live
+ ? `group ${gid} is already arranged as ${groupLayout} — nothing moved`
+ : `arranged ${count} item(s) in group ${gid} as ${groupLayout} and resized the frame to fit`,
+ result: {
+ count,
+ group: gid,
+ layout: groupLayout,
+ changed: next !== live,
+ width: frame?.width,
+ height: frame?.height
+ }
+ })
+ return
+ }
+ const ids = (args.nodes ?? '').split(',').map((s) => s.trim()).filter(Boolean)
const edge = (['left', 'right', 'top', 'bottom', 'hcenter', 'vcenter'] as const).find((e2) => e2 === args.edge)
if (verb === 'align' && !edge) {
reply({ ok: false, error: 'align requires --edge left|right|top|bottom|hcenter|vcenter' })
@@ -14007,9 +14099,11 @@ export function Canvas() {
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, snapGridNow())
+ // Tidying a frame's children usually leaves the frame the wrong size (it was sized to
+ // their old scattered spots) — hug the new layout, and re-fit every ANCESTOR frame too:
+ // a nested frame that grew past its parent would be clamped by `extent:'parent'` into
+ // an inverted range. Top-level sets have no frame.
+ if (container) next = fitAncestorChain(next, container, snapGridNow())
setNodes(next)
markDirty()
const how = verb === 'arrange' ? `as ${layout}` : `to ${edge}`
@@ -17329,6 +17423,38 @@ export function Canvas() {
} as Command
]
: []),
+ // The group tidies need a frame to act on, and the palette has no right-click target: they
+ // are offered for the ONE selected group frame, and each is omitted (never disabled — see
+ // above) when `groupArrangeRefusal` says it has nothing to do there.
+ ...(() => {
+ const selectedGroups = nodesRef.current.filter((n) => n.selected && n.type === 'group')
+ if (selectedGroups.length !== 1) return []
+ const groupId = selectedGroups[0].id
+ return [
+ ...(groupArrangeHint(groupId, 'grid')
+ ? []
+ : [
+ {
+ id: 'arrange-group',
+ label: 'Tidy selected group',
+ hint: 'arrange grid layout organize frame resize fit clean up',
+ icon: <IconGrid />,
+ run: () => arrangeGroupAction(groupId, 'grid')
+ } as Command
+ ]),
+ ...(groupArrangeHint(groupId, 'lineage')
+ ? []
+ : [
+ {
+ id: 'arrange-group-lineage',
+ label: 'Arrange selected group by lineage',
+ hint: 'layers levels who opened whom tree hierarchy organize frame resize',
+ icon: <IconLineage />,
+ run: () => arrangeGroupAction(groupId, 'lineage')
+ } as Command
+ ])
+ ]
+ })(),
{ id: 'zoom-100', label: 'Zoom to 100%', icon: <IconFit />, run: zoomTo100 },
// Layouts mirror the Dock's menu, and both are withheld on a relay tab for the same reason:
// it is a live connection to another machine, never a workspace on this disk. The Dock says
diff --git a/src/renderer/canvas/arrange-group.source.test.ts b/src/renderer/canvas/arrange-group.source.test.ts
new file mode 100644
index 000000000..3f9cc6a24
--- /dev/null
+++ b/src/renderer/canvas/arrange-group.source.test.ts
@@ -0,0 +1,90 @@
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+
+/**
+ * STRUCTURAL pins for "arrange inside a group". The rules themselves are pure and tested where
+ * they live (`state/workspace.layout.test.ts`); what cannot be tested there is that Canvas.tsx —
+ * a React component with no unit seam — reaches them from all three surfaces through ONE
+ * transform. A frame menu that packs with `arrangeGroupChildren` while the `arrange --group` verb
+ * packs with its own copy is two answers to "what does organizing a frame do", and the second one
+ * is the one that forgets to re-fit the ancestors.
+ */
+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+
+/** Line comments say what a block must NOT do, so a pin has to judge the code. */
+const code = (body: string): string =>
+ body
+ .split('\n')
+ .filter((l) => !l.trim().startsWith('//') && !l.trim().startsWith('*'))
+ .join('\n')
+
+function between(start: string, end: string): string {
+ const at = src.indexOf(start)
+ expect(at, start).toBeGreaterThan(-1)
+ const stop = src.indexOf(end, at + start.length)
+ expect(stop, end).toBeGreaterThan(at)
+ return code(src.slice(at, stop))
+}
+
+describe('arrange inside a group (source pins)', () => {
+ const action = between('const arrangeGroupAction = useCallback(', '\n /** Report a refusal')
+ const verb = between(" case 'arrange':\n", "\n case 'link': {")
+ const groupBranch = verb.slice(verb.indexOf("if (verb === 'arrange' && args.group)"), verb.indexOf('const ids ='))
+
+ it('the menu/palette action is arrangeGroupChildren, decided BEFORE the write', () => {
+ // The same-array verdict is read off nodesRef first: a flag set inside the setNodes updater is
+ // still false on the next line, which would cost every run its markDirty.
+ const guard = action.indexOf('=== nodesRef.current) return')
+ const write = action.indexOf('setNodes(')
+ expect(guard).toBeGreaterThan(-1)
+ expect(write).toBeGreaterThan(guard)
+ expect(action.match(/arrangeGroupChildren\(/g)?.length).toBe(2)
+ expect(action).toContain('markDirty()')
+ // The frame's top-left stays put, so the camera has no reason to move.
+ expect(action).not.toContain('fitAll(')
+ // Canvas-only, like the two canvas tidies.
+ expect(action).toContain('isKanbanOpen(')
+ })
+
+ it('the frame menu offers both styles, disabled WITH the reason from the shared refusal', () => {
+ const hint = between('const groupArrangeHint = useCallback(', 'const arrangeGroupAction')
+ expect(hint).toContain('groupArrangeRefusal(')
+ const menu = between('const groupItems = useCallback(', '/** Right-click menu for an ephemeral card.')
+ expect(menu).toContain("label: 'Tidy group'")
+ expect(menu).toContain("label: 'Arrange group by lineage'")
+ expect(menu).toContain("groupArrangeHint(groupId, 'grid')")
+ expect(menu).toContain("groupArrangeHint(groupId, 'lineage')")
+ expect(menu).toContain('disabled: !!tidyRefusal')
+ expect(menu).toContain('disabled: !!lineageRefusal')
+ expect(menu).toContain("arrangeGroupAction(groupId, 'grid')")
+ expect(menu).toContain("arrangeGroupAction(groupId, 'lineage')")
+ })
+
+ it('the palette OMITS a refused entry instead of listing a dead one', () => {
+ const palette = between("id: 'arrange-group',", "{ id: 'zoom-100'")
+ const before = between('const selectedGroups = nodesRef.current', "id: 'arrange-group',")
+ expect(before).toContain('if (selectedGroups.length !== 1) return []')
+ expect(before).toContain("groupArrangeHint(groupId, 'grid')")
+ expect(palette).toContain("groupArrangeHint(groupId, 'lineage')")
+ expect(palette).not.toContain('disabled')
+ })
+
+ it('arrange --group runs the SAME transform and refusal, and writes only on a change', () => {
+ expect(groupBranch).toContain('groupArrangeRefusal(live, gid, groupLayout, edges)')
+ expect(groupBranch).toContain('arrangeGroupChildren(live, gid,')
+ expect(groupBranch).toContain('GROUP_ARRANGE_LAYOUTS.find(')
+ // No second packing or fitting implementation in the branch.
+ expect(groupBranch).not.toMatch(/\barrangeNodes\(|fitGroupToChildren\(|fitAncestorChain\(/)
+ const write = groupBranch.slice(groupBranch.indexOf('if (next !== live)'))
+ expect(write.indexOf('setNodes(next)')).toBeGreaterThan(-1)
+ expect(write.indexOf('markDirty()')).toBeGreaterThan(write.indexOf('setNodes(next)'))
+ // A refusal names the verb and never reports ok.
+ expect(groupBranch).toContain('reply({ ok: false, error: `arrange: ${refusal}` })')
+ })
+
+ it('the --nodes form re-fits the ancestor chain too, not just the one frame', () => {
+ const nodesForm = verb.slice(verb.indexOf('const ids ='))
+ expect(nodesForm).toContain('fitAncestorChain(next, container, snapGridNow())')
+ expect(nodesForm).not.toContain('fitGroupToChildren(')
+ })
+})
diff --git a/src/renderer/state/workspace.layout.test.ts b/src/renderer/state/workspace.layout.test.ts
index 1183f0516..5a8d8bc27 100644
--- a/src/renderer/state/workspace.layout.test.ts
+++ b/src/renderer/state/workspace.layout.test.ts
@@ -1,5 +1,16 @@
import { describe, it, expect } from 'vitest'
-import { arrangeNodes, alignNodes, arrangeByLineage, lineageLayers, type CanvasNode } from './workspace'
+import {
+ arrangeNodes,
+ alignNodes,
+ arrangeByLineage,
+ arrangeGroupChildren,
+ fitGroupToChildren,
+ groupArrangeRefusal,
+ lineageLayers,
+ GROUP_PAD,
+ GROUP_HEADER,
+ type CanvasNode
+} from './workspace'
// 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 =>
@@ -225,3 +236,267 @@ describe('arrangeByLineage', () => {
expect(arrangeByLineage(one, edges)).toBe(one)
})
})
+
+describe('placement order', () => {
+ // `arrangeNodes` used to fill its slots in ARRAY order and ignore the order of the ids it was
+ // handed, which silently discarded every caller's sort: Tidy canvas's reading order, and the
+ // slot order `lineageLayers` computes so siblings sit under their opener.
+ it('arrangeNodes fills its slots in the order of the ids, not in array order', () => {
+ const out = arrangeNodes([n('a', 0, 0), n('b', 300, 0)], ['b', 'a'], {
+ layout: 'row',
+ gap: 10,
+ origin: { x: 0, y: 0 }
+ })
+ expect(out.find((x) => x.id === 'b')!.position).toEqual({ x: 0, y: 0 })
+ expect(out.find((x) => x.id === 'a')!.position).toEqual({ x: 110, y: 0 })
+ // The array itself is not reordered: persistence order is not the layout's to change.
+ expect(out.map((x) => x.id)).toEqual(['a', 'b'])
+ })
+
+ it('a repeated id takes one slot', () => {
+ const out = arrangeNodes([n('a', 0, 0), n('b', 300, 0)], ['a', 'a', 'b'], {
+ layout: 'row',
+ gap: 10,
+ origin: { x: 0, y: 0 }
+ })
+ expect(out.find((x) => x.id === 'b')!.position.x).toBe(110)
+ })
+
+ it('arrangeByLineage PLACES siblings under their opener, not in array order', () => {
+ // The same interleaved canvas as the lineageLayers slot test, asserted on positions: the
+ // layer order is only worth computing if the placement honours it.
+ const nodes = [
+ n('p1', 0, 0),
+ n('p2', 400, 0),
+ n('b1', 600, 300),
+ n('a1', 0, 300),
+ n('b2', 900, 300),
+ n('a2', 300, 300)
+ ]
+ const out = arrangeByLineage(
+ nodes,
+ [
+ { source: 'p1', target: 'a1' },
+ { source: 'p2', target: 'b1' },
+ { source: 'p1', target: 'a2' },
+ { source: 'p2', target: 'b2' }
+ ],
+ { gap: 10 }
+ )
+ const row = out
+ .filter((x) => x.position.y > 0)
+ .sort((x, y) => x.position.x - y.position.x)
+ .map((x) => x.id)
+ expect(row).toEqual(['a1', 'a2', 'b1', 'b2'])
+ })
+})
+
+// A frame nested in another frame.
+const inner = (id: string, parentId: string, x: number, y: number, w = 300, h = 200): CanvasNode =>
+ ({ ...frame(id, x, y, w, h), parentId }) as CanvasNode
+const at = (nodes: CanvasNode[], id: string) => nodes.find((x) => x.id === id)!
+/** `kid` lies fully inside `parent` (kid positions are parent-relative). */
+const holds = (nodes: CanvasNode[], parent: string, kid: string): boolean => {
+ const p = at(nodes, parent)
+ const k = at(nodes, kid)
+ return (
+ k.position.x >= 0 &&
+ k.position.y >= 0 &&
+ k.position.x + (k.width as number) <= (p.width as number) &&
+ k.position.y + (k.height as number) <= (p.height as number)
+ )
+}
+
+describe('lineageLayers inside a frame', () => {
+ it('layers the frame\'s direct children and ignores a rope from outside it', () => {
+ // `coord` opened the whole team from outside the frame: that says nothing about the order
+ // INSIDE it, so only a1→a2 / a1→a3 count.
+ const nodes = [n('coord', 0, 0), frame('g1', 500, 0), child('a1', 'g1'), child('a2', 'g1', 200), child('a3', 'g1', 400), child('note', 'g1', 0, 300)]
+ const { layers, loose } = lineageLayers(
+ nodes,
+ [
+ { source: 'coord', target: 'a1' },
+ { source: 'a1', target: 'a2' },
+ { source: 'a1', target: 'a3' }
+ ],
+ 'g1'
+ )
+ expect(layers).toEqual([['a1'], ['a2', 'a3']])
+ expect(loose).toEqual(['note'])
+ })
+
+ it('lifts a rope that lands inside a NESTED frame up to that frame', () => {
+ const nodes = [frame('g1', 0, 0), child('a1', 'g1'), inner('in', 'g1', 200, 0), child('k', 'in')]
+ const { layers } = lineageLayers(nodes, [{ source: 'a1', target: 'k' }], 'g1')
+ expect(layers).toEqual([['a1'], ['in']])
+ })
+
+ it('the top level is unchanged by the container parameter', () => {
+ const nodes = [n('coord', 0, 0), frame('g1', 500, 0), child('a1', 'g1'), child('a2', 'g1')]
+ const edges = [{ source: 'coord', target: 'a1' }]
+ expect(lineageLayers(nodes, edges)).toEqual(lineageLayers(nodes, edges, null))
+ })
+})
+
+describe('arrangeGroupChildren', () => {
+ // g1 sits at (500, 300); its three children are scattered, one of them outside the frame.
+ const scattered = () => [
+ frame('g1', 500, 300, 300, 200),
+ child('c1', 'g1', 200, 150),
+ child('c2', 'g1', 10, 20),
+ child('c3', 'g1', 400, 400)
+ ]
+
+ it('packs the children in reading order from the frame\'s content origin', () => {
+ const out = arrangeGroupChildren(scattered(), 'g1')
+ // 3 children → 2 columns; reading order is c2 (y 20), c1 (y 150), c3 (y 400).
+ expect(at(out, 'c2').position).toEqual({ x: GROUP_PAD, y: GROUP_PAD + GROUP_HEADER })
+ expect(at(out, 'c1').position).toEqual({ x: GROUP_PAD + 100 + 40, y: GROUP_PAD + GROUP_HEADER })
+ expect(at(out, 'c3').position).toEqual({ x: GROUP_PAD, y: GROUP_PAD + GROUP_HEADER + 50 + 40 })
+ })
+
+ it('keeps the frame\'s own top-left where it was and sizes it to the content', () => {
+ const out = arrangeGroupChildren(scattered(), 'g1')
+ const g = at(out, 'g1')
+ expect(g.position).toEqual({ x: 500, y: 300 })
+ // 2 columns of 100 + one 40 gap, 2 rows of 50 + one 40 gap, padded on every side + header.
+ expect(g.width).toBe(240 + GROUP_PAD * 2)
+ expect(g.height).toBe(140 + GROUP_PAD * 2 + GROUP_HEADER)
+ expect(g.style).toMatchObject({ width: g.width, height: g.height })
+ for (const id of ['c1', 'c2', 'c3']) expect(holds(out, 'g1', id)).toBe(true)
+ })
+
+ it('GROWS a frame whose content does not fit it', () => {
+ // Six children in a column are far taller than the 200-high frame.
+ const nodes = [frame('g1', 0, 0, 300, 200), ...[0, 1, 2, 3, 4, 5].map((i) => child(`c${i}`, 'g1', 10, 10 + i * 5))]
+ const out = arrangeGroupChildren(nodes, 'g1', { layout: 'column' })
+ expect(at(out, 'g1').height).toBe(6 * 50 + 5 * 40 + GROUP_PAD * 2 + GROUP_HEADER)
+ expect((at(out, 'g1').height as number) > 200).toBe(true)
+ for (let i = 0; i < 6; i++) expect(holds(out, 'g1', `c${i}`)).toBe(true)
+ })
+
+ it('SHRINKS a frame that was sized to where its children used to be', () => {
+ const nodes = [frame('g1', 0, 0, 2000, 1500), child('c1', 'g1', 1700, 1300), child('c2', 'g1', 50, 80)]
+ const out = arrangeGroupChildren(nodes, 'g1', { layout: 'row' })
+ expect(at(out, 'g1').width).toBe(240 + GROUP_PAD * 2)
+ expect(at(out, 'g1').position).toEqual({ x: 0, y: 0 })
+ })
+
+ it('honours --cols', () => {
+ const nodes = [frame('g1', 0, 0), ...[0, 1, 2, 3].map((i) => child(`c${i}`, 'g1', 10 + i * 5, 10))]
+ const out = arrangeGroupChildren(nodes, 'g1', { layout: 'grid', cols: 4 })
+ expect(new Set(['c0', 'c1', 'c2', 'c3'].map((id) => at(out, id).position.y)).size).toBe(1)
+ })
+
+ it('moves a nested frame as one rigid unit', () => {
+ const nodes = [frame('g1', 0, 0, 900, 700), child('t', 'g1', 600, 400), inner('in', 'g1', 500, 20), child('k', 'in', 33, 44)]
+ const out = arrangeGroupChildren(nodes, 'g1', { layout: 'row' })
+ // `in` is a member and is placed; what is inside it is not the outer frame's to touch.
+ expect(at(out, 'in').position).toEqual({ x: GROUP_PAD, y: GROUP_PAD + GROUP_HEADER })
+ expect(at(out, 'in').width).toBe(300)
+ expect(at(out, 'k').position).toEqual({ x: 33, y: 44 })
+ expect(at(out, 't').position.x).toBe(GROUP_PAD + 300 + 40)
+ })
+
+ it('re-fits EVERY ancestor frame, so a nested frame never overflows its parent', () => {
+ // top ⊃ mid ⊃ g1. Arranging g1's six children as a row makes it far wider than both.
+ const nodes = [
+ frame('top', 100, 100, 500, 400),
+ inner('mid', 'top', GROUP_PAD, GROUP_PAD + GROUP_HEADER, 400, 300),
+ inner('g1', 'mid', GROUP_PAD, GROUP_PAD + GROUP_HEADER, 300, 200),
+ ...[0, 1, 2, 3, 4, 5].map((i) => child(`c${i}`, 'g1', 10, 10 + i * 5))
+ ]
+ const out = arrangeGroupChildren(nodes, 'g1', { layout: 'row' })
+ expect(at(out, 'g1').width).toBe(6 * 100 + 5 * 40 + GROUP_PAD * 2)
+ expect(holds(out, 'mid', 'g1')).toBe(true)
+ expect(holds(out, 'top', 'mid')).toBe(true)
+ // Nothing jumped: the outermost frame is where it was, and so is everything's root position.
+ expect(at(out, 'top').position).toEqual({ x: 100, y: 100 })
+ expect(at(out, 'mid').position).toEqual({ x: GROUP_PAD, y: GROUP_PAD + GROUP_HEADER })
+ expect(at(out, 'g1').position).toEqual({ x: GROUP_PAD, y: GROUP_PAD + GROUP_HEADER })
+ })
+
+ it('fitting only the frame itself is NOT enough (the mutation this guards)', () => {
+ // The same tree, fitted without the walk up: g1 ends up wider than the frame holding it.
+ const nodes = [
+ frame('top', 100, 100, 500, 400),
+ inner('g1', 'top', GROUP_PAD, GROUP_PAD + GROUP_HEADER, 300, 200),
+ ...[0, 1, 2, 3, 4, 5].map((i) => child(`c${i}`, 'g1', 10, 10 + i * 5))
+ ]
+ const ids = ['c0', 'c1', 'c2', 'c3', 'c4', 'c5']
+ const onlyOwn = fitGroupToChildren(arrangeNodes(nodes, ids, { layout: 'row' }), 'g1')
+ expect(holds(onlyOwn, 'top', 'g1')).toBe(false)
+ expect(holds(arrangeGroupChildren(nodes, 'g1', { layout: 'row' }), 'top', 'g1')).toBe(true)
+ })
+
+ it('lays the children out as lineage bands and sizes the frame to them', () => {
+ const nodes = [frame('g1', 40, 40, 300, 200), child('a2', 'g1', 250, 10), child('a1', 'g1', 10, 300), child('a3', 'g1', 400, 10)]
+ const out = arrangeGroupChildren(nodes, 'g1', {
+ layout: 'lineage',
+ edges: [
+ { source: 'a1', target: 'a2' },
+ { source: 'a1', target: 'a3' }
+ ]
+ })
+ const top = GROUP_PAD + GROUP_HEADER
+ expect(at(out, 'a1').position).toEqual({ x: GROUP_PAD, y: top })
+ expect(at(out, 'a2').position).toEqual({ x: GROUP_PAD, y: top + 50 + 40 })
+ expect(at(out, 'a3').position).toEqual({ x: GROUP_PAD + 100 + 40, y: top + 50 + 40 })
+ expect(at(out, 'g1').position).toEqual({ x: 40, y: 40 })
+ for (const id of ['a1', 'a2', 'a3']) expect(holds(out, 'g1', id)).toBe(true)
+ })
+
+ it('with snapping on, keeps a frame that is on the grid on it', () => {
+ const GRID = 40
+ const nodes = [frame('g1', 400, 200, 320, 200), child('c1', 'g1', 200, 150), child('c2', 'g1', 10, 20)]
+ const out = arrangeGroupChildren(nodes, 'g1', { layout: 'row', grid: GRID })
+ const g = at(out, 'g1')
+ expect(g.position).toEqual({ x: 400, y: 200 })
+ expect((g.width as number) % GRID).toBe(0)
+ expect((g.height as number) % GRID).toBe(0)
+ expect(holds(out, 'g1', 'c1') && holds(out, 'g1', 'c2')).toBe(true)
+ })
+
+ describe('returns the SAME array when there is nothing to do', () => {
+ it('a missing id, a non-group id and an empty frame', () => {
+ const nodes = [frame('g1', 0, 0), n('t', 500, 0)]
+ expect(arrangeGroupChildren(nodes, 'ghost')).toBe(nodes)
+ expect(arrangeGroupChildren(nodes, 't')).toBe(nodes)
+ expect(arrangeGroupChildren(nodes, 'g1')).toBe(nodes)
+ })
+
+ it('a lineage layout with no rope joining two of the children', () => {
+ const nodes = [n('coord', 0, 0), frame('g1', 500, 0), child('a1', 'g1'), child('a2', 'g1', 200)]
+ // The only rope comes from outside the frame.
+ expect(
+ arrangeGroupChildren(nodes, 'g1', { layout: 'lineage', edges: [{ source: 'coord', target: 'a1' }] })
+ ).toBe(nodes)
+ })
+
+ it('a frame that is already arranged — a second run moves nothing', () => {
+ // No undo entry and no project.json write for a click that visibly did nothing.
+ const once = arrangeGroupChildren(
+ [frame('g1', 500, 300, 300, 200), child('c1', 'g1', 200, 150), child('c2', 'g1', 10, 20)],
+ 'g1'
+ )
+ expect(arrangeGroupChildren(once, 'g1')).toBe(once)
+ })
+ })
+})
+
+describe('groupArrangeRefusal', () => {
+ const nodes = [n('t', 0, 0), frame('empty', 0, 0), frame('g1', 500, 0), child('a1', 'g1'), child('a2', 'g1', 200)]
+ it('names each reason, and is null when the layout can run', () => {
+ expect(groupArrangeRefusal(nodes, 'ghost', 'grid')).toBe('no group frame has the id ghost')
+ expect(groupArrangeRefusal(nodes, 't', 'grid')).toBe('no group frame has the id t')
+ expect(groupArrangeRefusal(nodes, 'empty', 'grid')).toBe('this group is empty')
+ expect(groupArrangeRefusal(nodes, 'g1', 'grid')).toBeNull()
+ expect(groupArrangeRefusal(nodes, 'g1', 'lineage')).toBe('nothing in this group was opened by another node in it')
+ expect(groupArrangeRefusal(nodes, 'g1', 'lineage', [{ source: 'a1', target: 'a2' }])).toBeNull()
+ })
+
+ it('agrees with the transform: a refusal is exactly a same-array result', () => {
+ for (const id of ['ghost', 't', 'empty']) expect(arrangeGroupChildren(nodes, id)).toBe(nodes)
+ expect(arrangeGroupChildren(nodes, 'g1')).not.toBe(nodes)
+ })
+})
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index 28c384c44..f423b9cd5 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -1283,7 +1283,9 @@ function groupBox(
}
}
-export type ArrangeLayout = 'grid' | 'row' | 'column'
+import type { ArrangeLayout, GroupArrangeLayout } from '@shared/arrange-verb'
+export type { ArrangeLayout, GroupArrangeLayout }
+export { GROUP_ARRANGE_LAYOUTS } from '@shared/arrange-verb'
/**
* The single container the given ids all live in: `null` (all top-level), a group id (all
@@ -1307,14 +1309,19 @@ export function commonParentId(nodes: CanvasNode[], ids: string[]): string | nul
* 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.
+ *
+ * **Slots are filled in the order of `ids`, not in array order.** Every caller that sorts its ids
+ * is stating the order it wants — `Tidy canvas` by reading order, a lineage band by the slot of
+ * each node's opener — and the array order is persistence order (frames first, then creation),
+ * which is nobody's intent. Placing by array order silently discarded both sorts.
*/
export function arrangeNodes(
nodes: CanvasNode[],
ids: string[],
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))
+ const byId = new Map(nodes.map((nd) => [nd.id, nd]))
+ const members = [...new Set(ids)].flatMap((id) => byId.get(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 nodes
const layout = opts?.layout ?? 'grid'
@@ -1350,38 +1357,43 @@ export interface LineageEdge {
}
/**
- * The top-level ancestor of every node, by id. A rope points at the NODE an agent opened, which is
- * routinely a node inside a frame — and a frame moves as one rigid unit, so a layer layout has to
- * ask which top-level object that rope really reaches. A parentId naming no live node, or a cycle
- * (project.json is hand-editable), resolves to the last node still walkable rather than throwing.
+ * 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
+ * node inside a frame — and a frame moves as one rigid unit, so a layer layout has to ask which
+ * member of the container being arranged that rope really reaches. A node outside the container,
+ * a parentId naming no live node and a cycle (project.json is hand-editable) are simply absent
+ * from the map, so a rope touching one is dropped rather than throwing.
*/
-function topLevelAncestors(nodes: CanvasNode[]): Map<string, string> {
+function containerAncestors(nodes: CanvasNode[], containerId: string | null): Map<string, string> {
const byId = new Map(nodes.map((nd) => [nd.id, nd]))
const out = new Map<string, string>()
for (const nd of nodes) {
- let cur = nd
+ let cur: CanvasNode | undefined = nd
const seen = new Set<string>([nd.id])
- while (cur.parentId) {
- const parent = byId.get(cur.parentId)
- if (!parent || seen.has(parent.id)) break
- seen.add(parent.id)
- cur = parent
+ while (cur && (cur.parentId ?? null) !== containerId) {
+ const parent: CanvasNode | undefined = cur.parentId ? byId.get(cur.parentId) : undefined
+ cur = parent && !seen.has(parent.id) ? parent : undefined
+ if (cur) seen.add(cur.id)
}
- out.set(nd.id, cur.id)
+ if (cur) out.set(nd.id, cur.id)
}
return out
}
/**
- * Splits the TOP-LEVEL nodes into lineage layers: layer 0 is every node nothing opened, layer k is
- * a node whose deepest opener sits in layer k-1, and `loose` holds the nodes no rope touches at all.
+ * Splits the members of ONE container into lineage layers: layer 0 is every node nothing opened,
+ * layer k is a node whose deepest opener sits in layer k-1, and `loose` holds the nodes no rope
+ * touches at all. The container is the top level by default (`containerId` null) or a group frame,
+ * whose DIRECT children are then the members — the same rules one level down, which is what lets
+ * a frame's own contents be arranged by lineage.
*
* Three rules, each of which the naive version gets wrong:
*
- * - **Ropes are LIFTED to the top-level ancestor.** The coordinator opens a team INSIDE a frame, so
- * the rope ends on a child; the frame is what gets placed. An edge whose two ends lift to the
- * same object is dropped — it is internal to that frame and would otherwise make it its own
- * opener.
+ * - **Ropes are LIFTED to the member that holds them.** The coordinator opens a team INSIDE a
+ * frame, so the rope ends on a child; the frame is what gets placed. An edge whose two ends lift
+ * to the same object is dropped — it is internal to that frame and would otherwise make it its
+ * own opener. An edge with an end OUTSIDE the container is dropped too: the opener of a frame's
+ * whole team usually sits outside the frame, and it says nothing about the order inside.
* - **A node's layer is its LONGEST path from a root**, not its first: with `max` every rope points
* strictly downward, which is the whole reason the layout reads as a flow. Taking the shortest
* path would let a rope run backwards up the canvas.
@@ -1395,10 +1407,12 @@ function topLevelAncestors(nodes: CanvasNode[]): Map<string, string> {
*/
export function lineageLayers(
nodes: CanvasNode[],
- edges: readonly LineageEdge[]
+ edges: readonly LineageEdge[],
+ containerId: string | null = null
): { layers: string[][]; loose: string[] } {
- const tops = topLevelAncestors(nodes)
- const topLevel = nodes.filter((nd) => !nd.parentId)
+ const tops = containerAncestors(nodes, containerId)
+ // Named for the default container; with `containerId` set these are that frame's children.
+ const topLevel = nodes.filter((nd) => (nd.parentId ?? null) === containerId)
const live = new Set(topLevel.map((nd) => nd.id))
const preds = new Map<string, string[]>()
@@ -1475,10 +1489,11 @@ export function lineageLayers(
}
/**
- * Lays the top-level nodes out as lineage bands: one row per layer, growing downward, with the
- * nodes no rope touches in a final band of their own. Returns the input unchanged when there is
- * nothing to arrange (under two top-level nodes, or no usable rope) — an unchanged array is the
- * caller's signal to skip the undo entry and the project.json write.
+ * Lays the members of one container (the top level, or `opts.containerId`'s direct children) out
+ * as lineage bands: one row per layer, growing downward, with the nodes no rope touches in a final
+ * band of their own. Returns the input unchanged when there is nothing to arrange (under two
+ * members, or no usable rope) — an unchanged array is the caller's signal to skip the undo entry
+ * and the project.json write.
*
* Built ON `arrangeNodes` rather than beside it: each band is one `row` placement from a shared
* left origin, so the packing, the gap and the mixed-container refusal all stay in ONE place.
@@ -1486,13 +1501,14 @@ export function lineageLayers(
export function arrangeByLineage(
nodes: CanvasNode[],
edges: readonly LineageEdge[],
- opts?: { gap?: number; origin?: { x: number; y: number } }
+ opts?: { gap?: number; origin?: { x: number; y: number }; containerId?: string | null }
): CanvasNode[] {
- const topLevel = nodes.filter((nd) => !nd.parentId)
+ const containerId = opts?.containerId ?? null
+ const topLevel = nodes.filter((nd) => (nd.parentId ?? null) === containerId)
if (topLevel.length < 2) return nodes
- const { layers, loose } = lineageLayers(nodes, edges)
- // No rope reached two different top-level objects: every node would land in the single `loose`
- // band, which is a worse `Tidy canvas`, not a lineage view.
+ const { layers, loose } = lineageLayers(nodes, edges, containerId)
+ // No rope reached two different members: every node would land in the single `loose` band,
+ // which is a worse `Tidy canvas`, not a lineage view.
if (layers.length === 0) return nodes
const gap = opts?.gap ?? 40
@@ -1513,6 +1529,91 @@ export function arrangeByLineage(
return 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's
+ * disabled reason and the CLI's refusal cannot drift apart.
+ */
+export function groupArrangeRefusal(
+ nodes: CanvasNode[],
+ groupId: string,
+ layout: GroupArrangeLayout,
+ edges: readonly LineageEdge[] = []
+): string | null {
+ const group = nodes.find((nd) => nd.id === groupId)
+ if (!group || group.type !== 'group') return `no group frame has the id ${groupId}`
+ if (!nodes.some((nd) => nd.parentId === groupId)) return 'this group is empty'
+ if (layout === 'lineage' && lineageLayers(nodes, edges, groupId).layers.length === 0) {
+ return 'nothing in this group was opened by another node in it'
+ }
+ return null
+}
+
+/**
+ * Organizes a group frame's own contents, then sizes the frame — and every ancestor frame — to
+ * hold them. The members are the frame's DIRECT children: a nested frame moves as one rigid unit
+ * with its own children untouched, exactly as `Tidy canvas` treats a top-level frame.
+ *
+ * - `grid` / `row` / `column` pack the children in their current reading order (y, then x), so the
+ * result roughly keeps what the user built; `lineage` lays them out as `arrangeByLineage` bands
+ * over the ropes that connect two of them.
+ * - **The frame's own top-left stays where it is.** The layout starts at the offset a fitted frame
+ * keeps its content at (`GROUP_PAD`, plus the label header), so the fit that follows re-derives
+ * the same origin and the frame only grows or shrinks to the right and downward. Starting from
+ * the children's current bounding box instead would move the frame to wherever the top-left
+ * child happened to sit. (With snapping on, a frame that was OFF the grid still moves onto it —
+ * by under one cell.)
+ * - **The fit walks UP the parent chain, innermost first** (`fitAncestorChain`). Fitting only the
+ * frame leaves a parent smaller than the child it holds, and `extent:'parent'` then makes React
+ * Flow clamp that child into an inverted range — the snap `groupSelectedNodes` documents.
+ *
+ * Returns the SAME array when there is nothing to do — a missing or empty frame, a lineage layout
+ * with no usable rope, or a frame whose contents already sit exactly where the layout puts them —
+ * which is the caller's signal to skip the undo entry and the project.json write. Pure.
+ */
+export function arrangeGroupChildren(
+ nodes: CanvasNode[],
+ groupId: string,
+ opts?: {
+ layout?: GroupArrangeLayout
+ cols?: number
+ gap?: number
+ edges?: readonly LineageEdge[]
+ grid?: number
+ }
+): CanvasNode[] {
+ const layout = opts?.layout ?? 'grid'
+ const edges = opts?.edges ?? []
+ if (groupArrangeRefusal(nodes, groupId, layout, edges)) return nodes
+ const grid = opts?.grid ?? 0
+ const pad = grid > 0 ? Math.max(GROUP_PAD, grid) : GROUP_PAD
+ const origin = { x: pad, y: pad + GROUP_HEADER }
+ const gap = opts?.gap
+ let next: CanvasNode[]
+ if (layout === 'lineage') {
+ next = arrangeByLineage(nodes, edges, { containerId: groupId, origin, gap })
+ } else {
+ const ids = nodes
+ .filter((nd) => nd.parentId === groupId)
+ .sort((a, b) => a.position.y - b.position.y || a.position.x - b.position.x)
+ .map((nd) => nd.id)
+ next = arrangeNodes(nodes, ids, { layout, cols: opts?.cols, gap, origin })
+ }
+ next = fitAncestorChain(next, groupId, grid)
+ // Every transform above maps the array in place, so index i is the same node before and after.
+ const unchanged = next.every((nd, i) => {
+ const was = nodes[i]
+ return (
+ was === nd ||
+ (was.position.x === nd.position.x &&
+ was.position.y === nd.position.y &&
+ was.width === nd.width &&
+ was.height === nd.height)
+ )
+ })
+ return unchanged ? nodes : next
+}
+
export type AlignEdge = 'left' | 'right' | 'top' | 'bottom' | 'hcenter' | 'vcenter'
/**
@@ -1632,11 +1733,11 @@ export function selectedRootIds(nodes: CanvasNode[], ids: string[]): string[] {
}
/**
- * Grows every ancestor frame of `groupId` to hug its children again, innermost first. A frame
- * that gained a child bigger than itself must be re-fitted BEFORE its own parent is, or the
- * parent is fitted around a size that is about to change.
+ * Re-fits `groupId` and then every ancestor frame above it to hug its children again, innermost
+ * first. A frame that gained a child bigger than itself must be re-fitted BEFORE its own parent
+ * is, or the parent is fitted around a size that is about to change.
*/
-function fitAncestorChain(
+export function fitAncestorChain(
nodes: CanvasNode[],
groupId: string | undefined,
grid = 0
diff --git a/src/server/control-unsupported.test.ts b/src/server/control-unsupported.test.ts
index 4fdec9292..3e3e4ef13 100644
--- a/src/server/control-unsupported.test.ts
+++ b/src/server/control-unsupported.test.ts
@@ -439,6 +439,20 @@ describe('the enabled Server Edition handler parses and dispatches the v1 surfac
expect(reply.message, verb).toContain('do not retry')
}
})
+
+ it('refuses `arrange` by name in both forms — a flag this edition cannot serve is never dropped', async () => {
+ // Headless canvas control keeps no measured node sizes, so the whole verb is deferred here.
+ // `--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' }]
+ 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 })
+ expect(reply.message).toContain('"arrange"')
+ expect(reply.message).toContain('do not retry')
+ }
+ })
})
/**
diff --git a/src/shared/arrange-verb.test.ts b/src/shared/arrange-verb.test.ts
new file mode 100644
index 000000000..bbbe6f1f0
--- /dev/null
+++ b/src/shared/arrange-verb.test.ts
@@ -0,0 +1,59 @@
+import { describe, it, expect } from 'vitest'
+import {
+ ARRANGE_LAYOUTS,
+ GROUP_ARRANGE_LAYOUTS,
+ arrangeArgsRefusal,
+ arrangeGroupGuidanceLines
+} 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>')
+ })
+
+ it('accepts either form on its own', () => {
+ expect(arrangeArgsRefusal({ nodes: 'a,b' })).toBeNull()
+ expect(arrangeArgsRefusal({ group: 'g1' })).toBeNull()
+ for (const layout of GROUP_ARRANGE_LAYOUTS) expect(arrangeArgsRefusal({ group: 'g1', layout })).toBeNull()
+ for (const layout of ARRANGE_LAYOUTS) expect(arrangeArgsRefusal({ nodes: 'a,b', layout })).toBeNull()
+ expect(arrangeArgsRefusal({ group: 'g1', layout: 'grid', cols: '3' })).toBeNull()
+ })
+
+ it('refuses both forms together instead of picking one', () => {
+ // `--group` means "its direct children": with `--nodes` beside it there are two answers to
+ // "which nodes", and a silent choice is a half-honoured flag the caller cannot see.
+ expect(arrangeArgsRefusal({ nodes: 'a,b', group: 'g1' })).toMatch(/not both/)
+ })
+
+ it('refuses an unknown --layout on the --group form by name', () => {
+ expect(arrangeArgsRefusal({ group: 'g1', layout: 'spiral' })).toBe(
+ 'arrange --group: --layout must be grid|row|column|lineage'
+ )
+ })
+
+ it('refuses --layout lineage on the --nodes form rather than delivering a grid', () => {
+ expect(arrangeArgsRefusal({ nodes: 'a,b', layout: 'lineage' })).toMatch(/lineage needs --group <frameId>/)
+ })
+
+ it('leaves the --nodes form lenient about any OTHER unknown layout word', () => {
+ // It has always fallen back to grid there, and callers in the field may lean on it.
+ expect(arrangeArgsRefusal({ nodes: 'a,b', layout: 'spiral' })).toBeNull()
+ })
+})
+
+describe('arrangeGroupGuidanceLines', () => {
+ const text = arrangeGroupGuidanceLines().join('\n')
+
+ it('advertises exactly the layouts the parser accepts', () => {
+ expect(text).toContain(`arrange --group <frameId> [--layout ${GROUP_ARRANGE_LAYOUTS.join('|')}] [--cols N]`)
+ for (const layout of GROUP_ARRANGE_LAYOUTS) expect(arrangeArgsRefusal({ group: 'g', layout })).toBeNull()
+ })
+
+ it('states the contract an orchestrator acts on', () => {
+ expect(text).toContain('direct children')
+ expect(text).toContain('every frame around it')
+ expect(text).toContain('top-left stays where it is')
+ expect(text).toContain('never both')
+ })
+})
diff --git a/src/shared/arrange-verb.ts b/src/shared/arrange-verb.ts
new file mode 100644
index 000000000..0ee7902c4
--- /dev/null
+++ b/src/shared/arrange-verb.ts
@@ -0,0 +1,66 @@
+/**
+ * The `arrange` canvas-control verb's vocabulary, in the one place all three of its readers can
+ * import: the renderer's layout transforms (`renderer/state/workspace.ts`), the request parser and
+ * the generated agent docs (`core/canvas-control-core.ts`). Core cannot import the renderer, and a
+ * layout list typed once per reader is how the docs come to advertise a word the parser refuses.
+ */
+
+/** How a set of sibling nodes is packed. */
+export const ARRANGE_LAYOUTS = ['grid', 'row', 'column'] as const
+export type ArrangeLayout = (typeof ARRANGE_LAYOUTS)[number]
+
+/**
+ * What a group frame's own contents can be laid out as: the three packs, or lineage bands. Lineage
+ * exists only here because it is a question about a CONTAINER ("who opened whom, among the things
+ * in this frame"), which an id list cannot ask.
+ */
+export const GROUP_ARRANGE_LAYOUTS = [...ARRANGE_LAYOUTS, 'lineage'] as const
+export type GroupArrangeLayout = (typeof GROUP_ARRANGE_LAYOUTS)[number]
+
+/**
+ * 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`);
+ * this refuses only what no canvas could act on.
+ *
+ * The two forms are exclusive on purpose: `--group` names a frame and means "its direct children",
+ * so a request carrying both has two answers to "which nodes", and picking one silently is the
+ * kind of half-honoured flag an agent cannot detect from the reply.
+ *
+ * Strictness differs by form, deliberately. `--group` is new, so an unknown `--layout` is refused
+ * by name. `--nodes` has always fallen back to `grid` on an unknown word, and callers in the field
+ * may lean on that — it stays, with ONE exception: `lineage`, which would otherwise be accepted
+ * and quietly delivered as a grid.
+ */
+export function arrangeArgsRefusal(args: Record<string, string>): string | null {
+ const hasNodes = !!args.nodes
+ const hasGroup = !!args.group
+ if (!hasNodes && !hasGroup) return 'arrange requires --nodes <id,id> or --group <frameId>'
+ 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 && layout && !(GROUP_ARRANGE_LAYOUTS as readonly string[]).includes(layout)) {
+ return `arrange --group: --layout must be ${GROUP_ARRANGE_LAYOUTS.join('|')}`
+ }
+ if (hasNodes && layout === 'lineage') {
+ return 'arrange: --layout lineage needs --group <frameId> — it lays out one frame\'s own items by who opened whom'
+ }
+ return null
+}
+
+/**
+ * The agent-facing description of `arrange --group`, rendered into BOTH generated bodies (the
+ * SKILL.md and the marker block) so the two cannot describe different products, with the layout
+ * list taken from the constant the parser checks.
+ */
+export function arrangeGroupGuidanceLines(): string[] {
+ return [
+ `- \`arrange --group <frameId> [--layout ${GROUP_ARRANGE_LAYOUTS.join('|')}] [--cols N]\` — organize a frame by`,
+ ' naming IT instead of listing its children: lays out the frame\'s direct children (a frame nested',
+ ' inside moves as one unit), then resizes the frame — and every frame around it — to hold them, so',
+ ' 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.'
+ ]
+}