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-control): arrange --gap, resize, place and geometry in list (#1288)

reviewbf93f74bae38
diff --git a/CLAUDE.md b/CLAUDE.md
index 4b2c9ba85..b12cce83c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -5138,6 +5138,50 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
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.
+ **Geometry verbs (issue #1288, 2026-10): `arrange --gap`, `resize`, `place`, `list --geometry`** —
+ so an agent can rebuild an exact layout (the report: 8 sessions in two tight columns on a
+ vertical monitor, rebuilt every time a session is replaced) instead of a human dragging. Every
+ packing always took `opts.gap`; the verb simply never handed it the flag. The shape gate is ONE
+ pure module, `@shared/geometry-verbs` (`geometryArgsRefusal`; `--gap` lives with the rest of
+ `arrange` in `arrangeArgsRefusal`), called in the same THREE places as the arrange gate — desktop
+ main before the forward, `parseControlRequest`, and Canvas's belt (once, BEFORE the routing, so
+ the live AND the stored `list` read a well-formed call). Every flag takes a value (the SSH
+ shim-loop rule) and the new verbs refuse an unknown flag by name (#539). The rules a refactor
+ must keep: **(1) `--gap`** is a whole number 0–`ARRANGE_GAP_MAX` (400, ten times the default 40)
+ for all three forms; above it the call is REFUSED, never clamped. Snapping cannot undo it:
+ `arrangeNodes` never snaps positions, and with snapping on the `--group` form snaps only the
+ frame's PADDING and the frame fit (which keeps root positions). Frame padding is not the gap.
+ **(2) `resize`** (`resizeNodes`) CLAMPS each named axis to the kind's resizer minimum
+ (`NODE_MIN_SIZES`) and `NODE_SIZE_MAX` (the default-size setting's ceiling) and reports what it
+ applied; it applies exactly (no grid snap); a group frame refuses the WHOLE call (a frame is
+ sized by what it holds); a **collapsed** node keeps drawing header-only — the width applies now,
+ the height becomes `expandedHeight` (what the expand gives back and what `flowToNodeStates`
+ persists); a **maximized** node is restored first (left holding `premaxRect`, the next panel-pin
+ refit would put it back over the viewport); `measured` is dropped in the same tick (the
+ serializer prefers it); the ancestor frames re-fit. Terminal cols/rows follow through the node's
+ own ResizeObserver — there is no second path to tmux. **(3) `place`** (`placeNodes`) is a NEW
+ verb, NOT `--x` on `move`: `move` without `--group` means "to the top level", so `move --nodes a
+ --x 10` would pull a framed node out of its frame and ignore the `--x` — `move` now REFUSES
+ `--x/--y/--dx/--dy/--width/--height` by name, naming `place`/`resize`. Coordinates are ROOT space
+ (what `list` reports); a framed node keeps its parent (the root delta is applied to its relative
+ position, then `fitAncestorChain`, which keeps root positions, so it lands exactly). Several ids
+ with `--x/--y` move as ONE block (bounding-box top-left lands on the point — not stacked: every
+ node on one point is not a layout); `--dx/--dy` shift each; the two forms are refused together; a
+ listed descendant of a listed frame is carried, not moved twice; |coord| ≤ `PLACE_COORD_MAX`
+ (100 000, a typo bound, refused not clamped). **(4) `list`**: the JSON rows ALWAYS carry `x`,
+ `y` (root, whole px), `width`, `height`, `parent` (+ `collapsed`/`expandedHeight`); the text form
+ only behind `--geometry on`. The live canvas reports React Flow's MEASURED size
+ (`liveNodeGeometry`), persisted only before the first measure; an off-screen project reports the
+ persisted size (`storedNodeGeometry`). **(5) Off screen** `resize`/`place` are stored-node verbs
+ like `arrange` (`commitCtlNodes` → `geometryMutations`), which is also the shared-canvas path; for
+ that, `premaxRect` joined the stored geometry fields — before, an off-screen `arrange` restored a
+ maximized node in memory and left its restore rect on disk. **Surfaces:** desktop only for the
+ verbs. The Server Edition never reaches the renderer dispatch (its bridge's `onAgentControl` is a
+ noop and `createServerEditionControlHandler` serves no layout verb, `list` included), so all four
+ take the named permanent `control-unsupported-on-this-edition` refusal. Relay tabs: an agent's
+ call is answered by the HOST desktop's canvas, and the guest sees the result through canvas sync.
+ Mobile N/A. Follow-up: `--width/--height` on the open verbs (today they ignore an unknown flag).
+ Pure rules in `state/workspace.geometry.test.ts`; wiring pins in `canvas/geometry-verbs.source.test.ts`.
**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
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 64b57672c..a7c234025 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -892,6 +892,17 @@ named refusal. Validate Server upgrades against a disposable data directory and
shared live service is
an explicit operator action, never a test or an automatic repair step.
+**A canvas-control verb you add in `Canvas.tsx` does not exist on the Server Edition.** The verbs
+run in the DESKTOP renderer's dispatch; the browser bridge never subscribes to `onAgentControl`, and
+the Server Edition answers `/control/*` itself (`src/server/control-unsupported.ts`), serving only
+`SERVER_V1_VERBS` through the headless node factory. Everything else — `list`, `arrange`, `move`,
+`resize`, `place` included — gets the named permanent `control-unsupported-on-this-edition` refusal.
+So "it is in the renderer, so both shells have it" is false here; either add a headless action or
+leave the refusal, and pin which in `control-unsupported.test.ts`. A new verb's flag gate goes in
+`src/shared` and is called from desktop main's control handler too (it never runs
+`parseControlRequest`), and a new verb should refuse a flag it does not read by name (#539) rather
+than ignore it.
+
**A plain terminal is not a Claude node.** It may carry the generic node/endpoint wiring needed for
a hand-launched agent to report hooks, but it gets no `NODETERM_AGENT_ID` and no
`NODETERM_CANVAS_CONTROL` until the serialized node explicitly names an agent.
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index 86a5c2ef6..61e1c5a46 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -23,6 +23,7 @@ import { BROWSER_FLAGS, BROWSER_KEYS, BROWSER_TIMEOUT_DEFAULT_MS, BROWSER_TIMEOU
import { nodeColorChoices } from '@shared/node-colors'
import { offScreenGuidanceLines } from '@shared/control-off-screen'
import { arrangeArgsRefusal, arrangeGroupGuidanceLines } from '@shared/arrange-verb'
+import { geometryArgsRefusal, geometryGuidanceLines } from '@shared/geometry-verbs'
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'
@@ -487,6 +488,8 @@ export type ControlVerb =
| 'move'
| 'arrange'
| 'align'
+ | 'resize'
+ | 'place'
| 'link'
| 'verify'
| 'spawn-team'
@@ -531,6 +534,10 @@ const VERBS: ControlVerb[] = [
'move',
'arrange',
'align',
+ // Issue #1288: size existing nodes and put them at canvas coordinates — the geometry `arrange`
+ // cannot express. Layout writes like `arrange`; their flag shape is @shared/geometry-verbs.
+ 'resize',
+ 'place',
'link',
'verify',
'spawn-team',
@@ -756,6 +763,10 @@ export function parseControlRequest(
const arrangeRefusal = arrangeArgsRefusal(args)
if (arrangeRefusal) return { error: arrangeRefusal }
}
+ // `resize` / `place` / `list --geometry` / a coordinate on `move` (issue #1288): the same gate desktop
+ // main runs before forwarding (it never runs this parser) and the renderer runs as its belt.
+ const geometryRefusal = geometryArgsRefusal(v, args)
+ if (geometryRefusal) return { error: geometryRefusal }
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>' }
@@ -888,7 +899,8 @@ export function buildCanvasControlInstructions(shimPath: string): string {
'refusal still applies) and `run` reaches only nodes you opened during this server run.',
'',
'Verbs:',
- '- `list` — current nodes (id, kind, title). Start here when you need a node id.',
+ '- `list [--geometry on|off]` — current nodes (id, kind, title; the JSON rows also carry each node\'s',
+ ' place and size — see `list --geometry` below). Start here when you need a node id.',
'- `help` — print the verb list. Answered by the shim itself, so it works even if the app is down.',
'- `open-terminal [--count N] [--cwd P] [--cmd C] [--group <id>] [--after <id,id>] [--after-success <id,id>] [--success-deadline <90m|12h|3d>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--run-now]` — open N plain terminals. `--cmd` requires verified node identity.',
'- `open-claude [--count N] [--cwd P] [--prompt T | --prompt-file F] [--model M] [--group <id>] [--after <id,id>] [--after-success <id,id>] [--success-deadline <90m|12h|3d>] [--after-pr <N:checks|N:merged>] [--pr-deadline <90m|12h|3d>] [--project <id>] [--issue <owner/repo#N | #N>] [--run-now]` — open N Claude sessions.',
@@ -993,12 +1005,13 @@ export function buildCanvasControlInstructions(shimPath: string): string {
' children into the frame\'s parent. `move --nodes <id,id> [--group <id>]` reparents nodes or groups INTO an',
' existing frame (omit `--group`, or pass `top`/`none`, to pull them out to the top level) — this is',
' how you move a node from one frame to another.',
- '- `arrange --nodes <id,id> [--layout grid|row|column] [--cols N]` /',
+ '- `arrange --nodes <id,id> [--layout grid|row|column] [--cols N] [--gap px]` /',
' `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). `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(),
+ ...geometryGuidanceLines(),
'- `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',
@@ -1422,7 +1435,7 @@ export function buildCanvasSkillBody(shimPath: string, dialect: ShimDialect = 'p
const agentLabels = BUILTIN_AGENT_IDS.map((id) => AGENT_CONFIG[id].label).join(' / ')
return `---
name: manage-nodeterm-canvas
-description: Create, organize and control nodes on the nodeterm canvas — open ${agentLabels} / terminal nodes, spawn agent teams, create git worktrees as bound groups, group/arrange/align/rename/move nodes, link nodes to read back their work, move kanban cards, show an image/video/web page, write to or close a terminal. Use when the user says "Build with Nodeterm orchestration", asks to open nodes/sessions/terminals on the canvas, or wants work run in separate, visible canvas sessions or worktrees; wants the canvas or kanban board organized; wants results read back from nodes it opened; or wants output shown as a node. Not for in-process background subagents. Only works inside a nodeterm agent session.
+description: Create, organize and control nodes on the nodeterm canvas — open ${agentLabels} / terminal nodes, spawn agent teams, create git worktrees as bound groups, group/arrange/align/resize/place/rename/move nodes, link nodes to read back their work, move kanban cards, show an image/video/web page, write to or close a terminal. Use when the user says "Build with Nodeterm orchestration", asks to open nodes/sessions/terminals on the canvas, or wants work run in separate, visible canvas sessions or worktrees; wants the canvas or kanban board organized; wants results read back from nodes it opened; or wants output shown as a node. Not for in-process background subagents. Only works inside a nodeterm agent session.
---
# Manage the nodeterm canvas
@@ -1453,7 +1466,8 @@ Edition \`--run-now\` changes nothing else (opens start at once; the \`--after\`
applies) and \`run\` reaches only nodes you opened during this server run.
Verbs:
-- \`list\` — list current nodes (id, kind, title). Start here when you need a node id.
+- \`list [--geometry on|off]\` — list current nodes (id, kind, title; the JSON rows also carry each node's
+ place and size — see \`list --geometry\` below). Start here when you need a node id.
A row ending **LAST TURN ERRORED** is a station whose last turn died on an API/model error:
it is idle, but it produced nothing, so do not read its output or build on it. The marker
is on the row on purpose — a fan-out of seven stations should cost one call to learn this,
@@ -1594,7 +1608,7 @@ ${reportOutcomeDocLines().join('\n')}
each where it sits on the canvas. Omit \`--group\` (or pass \`top\`/\`none\`) to pull them OUT to the
top level. This is how you move a node from one frame to another: \`move --nodes n1,n2 --group g2\`.
Invalid cycles are rejected.
-- \`arrange --nodes <id,id> [--layout grid|row|column] [--cols N]\` — tidy layout, no overlap. Works
+- \`arrange --nodes <id,id> [--layout grid|row|column] [--cols N] [--gap px]\` — 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). The nodes are placed
in the order you list them. When the ids are a frame's children, that frame and every frame around
@@ -1604,6 +1618,7 @@ ${arrangeGroupGuidanceLines().join('\n')}
\`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\`.
+${geometryGuidanceLines().join('\n')}
- \`link --to <id,id> [--from <id>]\` — context-link nodes, so each can READ the other's
transcript on demand with the get-linked-context skill. \`--from\` defaults to you. Nothing is
pushed into the linked sessions — reading is on demand, so linking never interrupts anyone.
@@ -1767,6 +1782,8 @@ Typical requests this skill covers:
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-*\`.
+- "Lay my sessions out exactly / the same way every time" → \`list --geometry on\` to read where everything is,
+ then \`resize\` + \`arrange --gap\` + \`place\` (the worked example under \`place\`). Rerun it after a session is replaced.
- "Move this node into that group" → \`move --nodes <id> --group <targetGroupId>\` (not \`group\`, which only
wraps loose nodes). "Break up this group" → \`ungroup --group <id>\`.
- "Rename this node/group" → \`rename\`.
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index 391c6429b..5748b60dc 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -2,6 +2,9 @@ import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
import { ISSUE_BRANCH_SLUG_MAX } from '../shared/issue-worktree'
+import { ARRANGE_GAP_MAX, arrangeGapGuidanceLines } from '../shared/arrange-verb'
+import { geometryGuidanceLines } from '../shared/geometry-verbs'
+import { NODE_SIZE_MAX } from '../shared/default-node-size'
import {
GITHUB_READ_LIMIT_DEFAULT as GH_READ_LIMIT_DEFAULT,
GITHUB_READ_LIMIT_MAX as GH_READ_LIMIT_MAX,
@@ -130,12 +133,12 @@ describe('parseControlRequest', () => {
['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]`')
+ expect(body, name).toContain('- `arrange --group <frameId> [--layout grid|row|column|lineage] [--cols N] [--gap px]`')
// 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).toContain('- `arrange --group top [--layout tidy|lineage] [--gap px]` — 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).toContain('`arrange --nodes <id,id> [--layout grid|row|column] [--cols N] [--gap px]`')
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/)
@@ -1769,3 +1772,68 @@ describe('the browser verb text matches #539 behaviour, in both bodies', () => {
expect(flat).toContain('sizes the page\'s viewport to the full content height')
})
})
+
+// Issue #1288 — the geometry verbs. The SHAPE gate is @shared/geometry-verbs (one gate for desktop
+// main, this parser and the renderer belt); these pin that the Server Edition's parser runs it, that
+// main's verb table knows the verbs, and that both agent-facing bodies describe them from the same
+// constants — `geometryGuidanceLines` / `arrangeGapGuidanceLines` — rather than retyping them.
+describe('canvas geometry from the CLI (issue #1288)', () => {
+ it('main forwards resize and place (an unknown verb would answer "Unknown verb")', () => {
+ expect(VERBS_FOR_TEST).toContain('resize')
+ expect(VERBS_FOR_TEST).toContain('place')
+ expect(parseControlRequest('resize', { nodes: 'a', width: '540' })).toEqual({
+ verb: 'resize',
+ args: { nodes: 'a', width: '540' }
+ })
+ expect(parseControlRequest('place', { nodes: 'a', x: '0', y: '-40' })).toEqual({
+ verb: 'place',
+ args: { nodes: 'a', x: '0', y: '-40' }
+ })
+ })
+
+ it('refuses a malformed request before any canvas sees it', () => {
+ expect(parseControlRequest('resize', { nodes: 'a' })).toEqual({
+ error: 'resize requires --width <px>, --height <px>, or both'
+ })
+ expect(parseControlRequest('place', { nodes: 'a', x: '1', dx: '1' })).toEqual({
+ error: 'place takes --x/--y (where) or --dx/--dy (how far), not both'
+ })
+ expect(parseControlRequest('list', { geometry: '' })).toEqual({ error: 'list: --geometry takes on or off (got "")' })
+ expect(parseControlRequest('arrange', { nodes: 'a,b', gap: '-4' })).toMatchObject({
+ error: expect.stringContaining('--gap must be a whole number')
+ })
+ expect(parseControlRequest('list', { geometry: 'on' })).toEqual({ verb: 'list', args: { geometry: 'on' } })
+ })
+
+ it('refuses a coordinate on move — it would pull a framed node to the top level and ignore the x', () => {
+ const r = parseControlRequest('move', { nodes: 'a', x: '10', y: '20' })
+ expect(r).toMatchObject({ error: expect.stringContaining('place --nodes <id> --x <n>') })
+ // Without coordinates `move` is exactly what it was.
+ expect(parseControlRequest('move', { nodes: 'a', group: 'g' })).toEqual({ verb: 'move', args: { nodes: 'a', group: 'g' } })
+ })
+
+ it('both bodies carry the geometry verbs, the gap and the worked example', () => {
+ const skill = buildCanvasSkillBody('/x/shim.sh')
+ const instructions = buildCanvasControlInstructions('/x/shim.sh')
+ for (const [name, body] of [['skill', skill], ['instructions', instructions]] as const) {
+ for (const line of geometryGuidanceLines()) expect(body, `${name}: ${line}`).toContain(line)
+ for (const line of arrangeGapGuidanceLines()) expect(body, `${name}: ${line}`).toContain(line)
+ expect(body, name).toContain('[--cols N] [--gap px]')
+ expect(body, name).toContain('`arrange --nodes a,e,b,f,c,g,d,h --layout grid --cols 2 --gap 0`')
+ expect(body, name).toMatch(/`list \[--geometry on\|off\]`/)
+ expect(body, name).toContain(`${NODE_SIZE_MAX.width}×${NODE_SIZE_MAX.height}`)
+ expect(body, name).toContain(`to ${ARRANGE_GAP_MAX}; omitted, it is`)
+ }
+ // The skill's playbook reaches for the three verbs when asked for an exact, repeatable layout.
+ expect(skill).toContain('"Lay my sessions out exactly / the same way every time" → `list --geometry on`')
+ // The trigger text names them, so the skill is chosen for "resize these nodes".
+ expect(skill).toContain('group/arrange/align/resize/place/rename/move nodes')
+ })
+
+ it('the off-screen paragraph answers resize and place like arrange', () => {
+ const text = buildCanvasControlInstructions('/x/shim.sh')
+ const answered = text.split('\n').find((l) => l.includes('Answered whether or not that project is on screen'))!
+ expect(answered).toMatch(/\bresize\b/)
+ expect(answered).toMatch(/\bplace\b/)
+ })
+})
diff --git a/src/main/control-shim-parse.test.ts b/src/main/control-shim-parse.test.ts
index 699a8d05e..5314a6134 100644
--- a/src/main/control-shim-parse.test.ts
+++ b/src/main/control-shim-parse.test.ts
@@ -130,6 +130,37 @@ describe('the control shim tags each run with its own request id', () => {
})
})
+// The shim loop as it stood before 2026-08-15: it took the token after ANY flag as that flag's
+// value. It still runs on an SSH host until that project reconnects (the shim is rewritten there only
+// on connect), which is why every flag of a new verb must take a value.
+const oldLoop = [
+ 'nt_count=$#',
+ 'nt_i=0',
+ 'while [ "$nt_i" -lt "$nt_count" ]; do',
+ ' nt_a="$1"; shift; nt_i=$((nt_i + 1))',
+ ' case "$nt_a" in',
+ ' --*)',
+ ' nt_k=${nt_a#--}',
+ ' nt_v=""',
+ ' if [ "$nt_i" -lt "$nt_count" ]; then nt_v="$1"; shift; nt_i=$((nt_i + 1)); fi',
+ ' set -- "$@" --data-urlencode "arg.$nt_k=$nt_v"',
+ ' ;;',
+ ' esac',
+ 'done',
+ 'for a in "$@"; do case "$a" in arg.*) printf \'%s\\n\' "$a" ;; esac; done'
+].join('\n')
+// What the server reads: curl's `--data-urlencode name=content` splits on the FIRST `=`.
+const oldShim = (flags: string[]): Record<string, string> =>
+ Object.fromEntries(
+ execFileSync('sh', ['-c', oldLoop, 'sh', ...flags], { encoding: 'utf8' })
+ .split('\n')
+ .filter(Boolean)
+ .map((pair) => {
+ const at = pair.indexOf('=')
+ return [pair.slice('arg.'.length, at), pair.slice(at + 1)]
+ })
+ )
+
describe('the control shim translates flags', () => {
it('a --flag followed by another --flag does NOT eat it', () => {
// THE BUG: this used to yield ['arg.read=--node'] and `b1` was lost with no error anywhere.
@@ -183,33 +214,6 @@ describe('the control shim translates flags', () => {
// had no `--*=*` branch. An SSH host keeps whatever shim it got at its last connect, so this
// loop can still be what an agent there runs. Executed under real `sh`, not modelled.
it('on the pre-2026-08-15 shim loop --run-now survives only LAST on the line, in either form (#925)', () => {
- const oldLoop = [
- 'nt_count=$#',
- 'nt_i=0',
- 'while [ "$nt_i" -lt "$nt_count" ]; do',
- ' nt_a="$1"; shift; nt_i=$((nt_i + 1))',
- ' case "$nt_a" in',
- ' --*)',
- ' nt_k=${nt_a#--}',
- ' nt_v=""',
- ' if [ "$nt_i" -lt "$nt_count" ]; then nt_v="$1"; shift; nt_i=$((nt_i + 1)); fi',
- ' set -- "$@" --data-urlencode "arg.$nt_k=$nt_v"',
- ' ;;',
- ' esac',
- 'done',
- 'for a in "$@"; do case "$a" in arg.*) printf \'%s\\n\' "$a" ;; esac; done'
- ].join('\n')
- // What the server reads: curl's `--data-urlencode name=content` splits on the FIRST `=`.
- const oldShim = (flags: string[]): Record<string, string> =>
- Object.fromEntries(
- execFileSync('sh', ['-c', oldLoop, 'sh', ...flags], { encoding: 'utf8' })
- .split('\n')
- .filter(Boolean)
- .map((pair) => {
- const at = pair.indexOf('=')
- return [pair.slice('arg.'.length, at), pair.slice(at + 1)]
- })
- )
// Last on the line: both forms are on, and nothing is lost.
for (const last of ['--run-now', '--run-now=1']) {
const args = oldShim(['--agent', 'claude', '--project', 'p2', last])
@@ -297,3 +301,24 @@ describe('the control shim translates flags', () => {
])
})
})
+
+// Issue #1288: every new flag takes a value, so the current loop and the pre-2026-08-15 one (still on
+// an SSH host until it reconnects) read the same request — including a negative coordinate.
+describe('the geometry flags reach the server intact, on the current and the old shim loop', () => {
+ const lines: Array<[string[], string[]]> = [
+ [['arrange', '--nodes', 'a,b', '--layout', 'grid', '--cols', '2', '--gap', '0'], ['arg.nodes=a,b', 'arg.layout=grid', 'arg.cols=2', 'arg.gap=0']],
+ [['resize', '--nodes', 'a,b', '--width', '540', '--height', '480'], ['arg.nodes=a,b', 'arg.width=540', 'arg.height=480']],
+ [['place', '--nodes', 'a', '--x', '-120', '--y', '0'], ['arg.nodes=a', 'arg.x=-120', 'arg.y=0']],
+ [['place', '--nodes', 'a', '--dx', '-8', '--dy', '-8'], ['arg.nodes=a', 'arg.dx=-8', 'arg.dy=-8']],
+ [['list', '--geometry', 'on'], ['arg.geometry=on']]
+ ]
+
+ it.each(lines)('%j', (argv, expected) => {
+ expect(run(argv)).toEqual(expected)
+ const [, ...flags] = argv
+ expect(oldShim(flags)).toEqual(
+ Object.fromEntries(expected.map((pair) => [pair.slice('arg.'.length, pair.indexOf('=')), pair.slice(pair.indexOf('=') + 1)]))
+ )
+ })
+})
+
diff --git a/src/main/index.ts b/src/main/index.ts
index 74389b509..4d7aaef0b 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -349,6 +349,7 @@ import { DRY_RUN_VERBS, dryRunRequested, dryRunRefusal } from '../shared/control
import { browserFlagRefusal, issueFlagRefusal } from '../core/canvas-control-core'
import { afterPrFlagRefusal } from '../shared/pr-wait'
import { arrangeArgsRefusal } from '../shared/arrange-verb'
+import { geometryArgsRefusal } from '../shared/geometry-verbs'
import { CONTROL_REQUEST_TIMEOUT_MS } from '../shared/control-confirm'
import { createControlForwarder, type ControlForwardReply } from './control-forward'
import { claimOpenedBrowser } from './browser-open-claim'
@@ -4565,6 +4566,11 @@ app.whenReady().then(async () => {
// ran as a grid.
const arrangeRefusal = verb === 'arrange' ? arrangeArgsRefusal(args) : null
if (arrangeRefusal) return { ok: false, error: arrangeRefusal, message: arrangeRefusal }
+ // `resize` / `place` / `list --geometry` / a coordinate or size flag on `move` (issue #1288): same
+ // placement, same reason — without it `move --nodes a --x 10` reached the renderer and pulled a
+ // framed node out to the top level, and a bad `--width` would be the renderer's to explain.
+ const geometryRefusal = geometryArgsRefusal(verb, args)
+ if (geometryRefusal) return { ok: false, error: geometryRefusal, message: geometryRefusal }
// A station's report about ITSELF: recorded in main's store, board-logged on its own card, and
// never forwarded — there is no canvas work in it, and the renderer hears the store's push.
if (verb === 'report-outcome') {
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 52c14c47d..1930f7585 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -9,7 +9,10 @@ import { VisibleMiniMap } from './VisibleMiniMap'
import { MinimapDock } from './MinimapDock'
import { keepGlassBlurWhileMoving } from '../lib/glassContrast'
import { LINK_ENDPOINT_NOT_FOUND } from '@shared/canvas-link'
-import { arrangeArgsRefusal, isTopLevelGroupArg, TOP_ARRANGE_LAYOUTS } from '@shared/arrange-verb'
+import { arrangeArgsRefusal, isTopLevelGroupArg, parseArrangeGap, TOP_ARRANGE_LAYOUTS } from '@shared/arrange-verb'
+import { geometryArgsRefusal, listGeometryRequested, parsePlaceArgs, parseResizeArgs } from '@shared/geometry-verbs'
+import { liveNodeGeometry } from '../lib/nodeGeometry'
+import { placeReply, resizeReply } from '../lib/geometryReply'
import { createControlOpenBatch } from '../lib/controlOpenBatch'
import { commitOwnedLaunchAttempt, registerLaunchCommit } from '../terminal/launch-attempt'
import { hasLaunchWriter, launchCommand } from '../terminal/launch-command'
@@ -959,6 +962,8 @@ import {
refitMaximizedNode,
restoreMaximizedNode,
placeNodeInRect,
+ placeNodes,
+ resizeNodes,
terminalNodeSize,
type CanvasNode
} from '../state/workspace'
@@ -13132,6 +13137,15 @@ export function Canvas() {
// each runs the SAME validation as a real call and stops just before the mutation.
const dryRun = dryRunRequested(args)
const DRY_RUN_PREFIX = 'DRY RUN — nothing was opened or changed.'
+ // The geometry flags' shape (`resize`, `place`, `list --geometry`, a coordinate on `move`):
+ // refused in main already (`geometryArgsRefusal`); this is the belt, and it sits BEFORE the
+ // routing so both `list` answers (live and stored) and every verb case read only a well-formed
+ // request — nothing below has to re-decide what a bad `--width` means.
+ const geometryRefusal = geometryArgsRefusal(verb, args)
+ if (geometryRefusal) {
+ reply({ ok: false, error: geometryRefusal })
+ return
+ }
// `--issue` (open-agent / open-claude): the GitHub issue the new session is started on. Its
// SHAPE was refused in main (`issueFlagRefusal`); what `#N` means is this renderer's question,
@@ -14010,11 +14024,13 @@ export function Canvas() {
return
}
if (!needsLiveCanvas(verb)) {
+ // Stored nodes carry their persisted geometry, which the listing turns into each row's
+ // place and size (nothing off screen was measured — see lib/nodeGeometry).
const rows = storedNodeListing(projects.find((p) => p.id === route.projectId)?.nodes ?? [], useAgentStatus.getState().byId, useLaunchDelivery.getState().byId, Date.now(), useStationOutcomes.getState().byId, useStationHandovers.getState().byId)
reply({
ok: true,
result: rows,
- message: controlListingText(rows)
+ message: controlListingText(rows, { geometry: listGeometryRequested(args) })
})
return
}
@@ -14738,12 +14754,15 @@ export function Canvas() {
// separately would be seven round trips to learn the one thing that changes what it
// does next.
const st = useAgentStatus.getState().byId
+ // Geometry is the MEASURED size on the live canvas (`liveNodeGeometry`), the persisted one
+ // only for a node React Flow has not measured yet.
const list = storedNodeListing(nodesRef.current.map((n) => ({
id: n.id, kind: n.type, title: n.data.title as string,
pendingLaunch: n.data.pendingLaunch, agentId: n.data.agentId as string | undefined,
- issueRef: n.data.issueRef
+ issueRef: n.data.issueRef,
+ geometry: liveNodeGeometry(n, nodesRef.current)
})), st, useLaunchDelivery.getState().byId, Date.now(), useStationOutcomes.getState().byId, useStationHandovers.getState().byId)
- reply({ ok: true, result: list, message: controlListingText(list) })
+ reply({ ok: true, result: list, message: controlListingText(list, { geometry: listGeometryRequested(args) }) })
return
}
case 'open-terminal': {
@@ -15194,6 +15213,45 @@ export function Canvas() {
reply({ ok: true, message: `moved ${moved.length} node(s) ${where}`, result: { moved, group: targetGroup } })
return
}
+ case 'resize': {
+ // Size existing nodes (issue #1288). The rules — kind minimum and canvas maximum, frames
+ // refused, collapsed/maximized handled, ancestor frames re-fitted — are all
+ // `resizeNodes`; this case only parses, writes on a change and says what was applied.
+ const req = parseResizeArgs(args)
+ if ('error' in req) {
+ reply({ ok: false, error: req.error })
+ return
+ }
+ const live = ctlNodes()
+ const out = resizeNodes(live, req.ids, { width: req.width, height: req.height }, snapGridNow())
+ if (!out.ok) {
+ reply({ ok: false, error: out.error })
+ return
+ }
+ // The SAME array means every node already had that size: an answer, nothing to write.
+ if (out.nodes !== live) commitCtlNodes(out.nodes)
+ reply({ ok: true, ...resizeReply(out, out.nodes !== live) })
+ return
+ }
+ case 'place': {
+ // Put nodes at canvas coordinates, or shift them (issue #1288). NOT a flag on `move`:
+ // without `--group`, `move` takes a node out of its frame. `placeNodes` keeps the parent,
+ // converts root space to parent-relative and re-fits the frames around what moved.
+ const req = parsePlaceArgs(args)
+ if ('error' in req) {
+ reply({ ok: false, error: req.error })
+ return
+ }
+ const live = ctlNodes()
+ const out = placeNodes(live, req.ids, req, snapGridNow())
+ if (!out.ok) {
+ reply({ ok: false, error: out.error })
+ return
+ }
+ if (out.nodes !== live) commitCtlNodes(out.nodes)
+ reply({ ok: true, ...placeReply(out, req, out.nodes !== live) })
+ return
+ }
case 'arrange':
case 'align': {
const live = ctlNodes()
@@ -15205,6 +15263,10 @@ export function Canvas() {
reply({ ok: false, error: shapeRefusal })
return
}
+ // `--gap` (issue #1288), well-formed by now (the gate above): every arrange form passes it
+ // on; absent stays `undefined`, so each transform keeps its own default. `align` has none.
+ const parsedGap = parseArrangeGap(args.gap)
+ const gap = 'gap' in parsedGap ? parsedGap.gap : undefined
// `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.
@@ -15220,7 +15282,7 @@ export function 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 next = topLayout === 'lineage' ? arrangeByLineage(live, edges, { gap }) : tidyCanvas(live, edges, { gap })
const count = live.filter((nd) => !nd.parentId).length
if (next !== live) commitCtlNodes(next)
reply({
@@ -15244,7 +15306,7 @@ export function Canvas() {
return
}
const cols = args.cols ? parseInt(args.cols, 10) || undefined : undefined
- const next = arrangeGroupChildren(live, gid, { layout: groupLayout, cols, edges, grid: snapGridNow() })
+ const next = arrangeGroupChildren(live, gid, { layout: groupLayout, cols, gap, 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.
@@ -15290,7 +15352,7 @@ export function Canvas() {
const layout = (['grid', 'row', 'column'] as const).find((l) => l === args.layout) ?? 'grid'
const cols = args.cols ? parseInt(args.cols, 10) || undefined : undefined
let next = verb === 'arrange'
- ? arrangeNodes(live, ids, { layout, cols })
+ ? arrangeNodes(live, ids, { layout, cols, gap })
: alignNodes(live, ids, edge!)
// 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:
diff --git a/src/renderer/canvas/arrange-group.source.test.ts b/src/renderer/canvas/arrange-group.source.test.ts
index 5c86a121a..4153906f6 100644
--- a/src/renderer/canvas/arrange-group.source.test.ts
+++ b/src/renderer/canvas/arrange-group.source.test.ts
@@ -130,7 +130,7 @@ describe('arrange inside a group (source pins)', () => {
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("topLayout === 'lineage' ? arrangeByLineage(live, edges, { gap }) : tidyCanvas(live, edges, { gap })")
expect(top).toContain('if (next !== live) commitCtlNodes(next)')
expect(top).not.toMatch(/\barrangeNodes\(/)
})
diff --git a/src/renderer/canvas/geometry-verbs.source.test.ts b/src/renderer/canvas/geometry-verbs.source.test.ts
new file mode 100644
index 000000000..0852eafd3
--- /dev/null
+++ b/src/renderer/canvas/geometry-verbs.source.test.ts
@@ -0,0 +1,115 @@
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+
+/**
+ * STRUCTURAL pins for the geometry verbs (issue #1288). The rules are pure and tested where they
+ * live (`state/workspace.geometry.test.ts`, `@shared/geometry-verbs`, `lib/nodeGeometry`); what
+ * cannot be tested there is that Canvas.tsx — a component with no unit seam — and desktop main's
+ * control handler actually REACH them. Each pin below is one wire whose loss leaves every unit test
+ * green: a flag the parser accepts and the dispatch never passes on is the exact bug this issue was
+ * filed for (`arrange` took `opts.gap` for years; the verb never handed it the flag).
+ */
+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+const mainSrc = readFileSync(new URL('../../main/index.ts', import.meta.url), 'utf8').replace(/\r\n/g, '\n')
+
+/** 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(text: string, start: string, end: string): string {
+ const at = text.indexOf(start)
+ expect(at, start).toBeGreaterThan(-1)
+ const stop = text.indexOf(end, at + start.length)
+ expect(stop, end).toBeGreaterThan(at)
+ return code(text.slice(at, stop))
+}
+
+const dispatch = between(src, 'return api.onAgentControl(async ({ requestId, sourceNodeId, verb, args }) => {', "case 'open-terminal': {")
+const arrangeCase = between(src, " case 'arrange':\n", "\n case 'link': {")
+const groupBranch = arrangeCase.slice(arrangeCase.indexOf("if (verb === 'arrange' && args.group)"), arrangeCase.indexOf('const ids ='))
+const topBranch = groupBranch.slice(groupBranch.indexOf('if (isTopLevelGroupArg(gid))'), groupBranch.indexOf('const groupLayout'))
+const nodesForm = arrangeCase.slice(arrangeCase.indexOf('const ids ='))
+
+describe('arrange --gap is handed to every form', () => {
+ it('is parsed once, after the shape gate refused a bad value', () => {
+ const gate = arrangeCase.indexOf("verb === 'arrange' ? arrangeArgsRefusal(args) : null")
+ const parse = arrangeCase.indexOf('parseArrangeGap(args.gap)')
+ expect(gate).toBeGreaterThan(-1)
+ expect(parse).toBeGreaterThan(gate)
+ expect(parse).toBeLessThan(arrangeCase.indexOf("if (verb === 'arrange' && args.group)"))
+ })
+
+ it('--group top: both Tidy canvas and the lineage bands', () => {
+ expect(topBranch).toContain('arrangeByLineage(live, edges, { gap })')
+ expect(topBranch).toContain('tidyCanvas(live, edges, { gap })')
+ })
+
+ it('--group <frameId>', () => {
+ expect(groupBranch).toMatch(/arrangeGroupChildren\(live, gid, \{[^}]*\bgap\b[^}]*\}\)/)
+ })
+
+ it('--nodes (and align, which has no gap, is untouched)', () => {
+ expect(nodesForm).toContain('arrangeNodes(live, ids, { layout, cols, gap })')
+ expect(nodesForm).toContain('alignNodes(live, ids, edge!)')
+ })
+})
+
+describe('resize and place', () => {
+ const resize = between(src, " case 'resize': {", " case 'place': {")
+ const place = between(src, " case 'place': {", " case 'arrange':\n")
+
+ it('resize runs the ONE transform over the call\'s own node array and writes only on a change', () => {
+ expect(resize).toContain('parseResizeArgs(args)')
+ expect(resize).toContain('const live = ctlNodes()')
+ expect(resize).toContain('resizeNodes(live, req.ids, { width: req.width, height: req.height }, snapGridNow())')
+ // `commitCtlNodes` is the one write for on- and off-screen projects (dirty + the shared-canvas
+ // op path ride on it); a bare setNodes here would skip an off-screen project entirely.
+ expect(resize).toContain('if (out.nodes !== live) commitCtlNodes(out.nodes)')
+ expect(resize).not.toMatch(/\bsetNodes\(|fitAncestorChain\(|fitGroupToChildren\(/)
+ expect(resize).toContain('resizeReply(out, out.nodes !== live)')
+ })
+
+ it('place runs the ONE transform and writes only on a change', () => {
+ expect(place).toContain('parsePlaceArgs(args)')
+ expect(place).toContain('placeNodes(live, req.ids, req, snapGridNow())')
+ expect(place).toContain('if (out.nodes !== live) commitCtlNodes(out.nodes)')
+ expect(place).not.toMatch(/\bsetNodes\(|reparentNode\(|fitAncestorChain\(/)
+ expect(place).toContain('placeReply(out, req, out.nodes !== live)')
+ })
+})
+
+describe('the shape gate runs before anything reads a geometry flag', () => {
+ it('in the renderer: once, before the routing — so both `list` answers see a well-formed call', () => {
+ const belt = dispatch.indexOf('geometryArgsRefusal(verb, args)')
+ expect(belt).toBeGreaterThan(-1)
+ expect(dispatch.slice(belt, belt + 200)).toContain('reply({ ok: false, error: geometryRefusal })')
+ expect(belt).toBeLessThan(dispatch.indexOf('routeControlSource('))
+ expect(belt).toBeLessThan(dispatch.indexOf('if (!needsLiveCanvas(verb)) {'))
+ })
+
+ it('in desktop main: before the forward to the renderer (that handler never runs parseControlRequest)', () => {
+ const handler = code(mainSrc.slice(mainSrc.indexOf('hookServer.setControlHandler(')))
+ const gate = handler.indexOf('const geometryRefusal = geometryArgsRefusal(verb, args)')
+ expect(gate).toBeGreaterThan(-1)
+ expect(handler.slice(gate, gate + 200)).toContain(
+ 'if (geometryRefusal) return { ok: false, error: geometryRefusal, message: geometryRefusal }'
+ )
+ expect(gate).toBeLessThan(handler.indexOf("'window unavailable'"))
+ })
+})
+
+describe('list carries geometry on both paths', () => {
+ it('the live canvas reports the MEASURED geometry; the text form follows --geometry', () => {
+ const live = between(src, " case 'list': {", " case 'open-terminal': {")
+ expect(live).toContain('geometry: liveNodeGeometry(n, nodesRef.current)')
+ expect(live).toContain('controlListingText(list, { geometry: listGeometryRequested(args) })')
+ })
+
+ it('the off-screen answer reads the stored nodes (persisted geometry) with the same flag', () => {
+ const stored = between(src, ' if (!needsLiveCanvas(verb)) {', '// ── COLD OPEN')
+ expect(stored).toContain('controlListingText(rows, { geometry: listGeometryRequested(args) })')
+ })
+})
diff --git a/src/renderer/lib/controlRouting.test.ts b/src/renderer/lib/controlRouting.test.ts
index db8176fc4..477d53092 100644
--- a/src/renderer/lib/controlRouting.test.ts
+++ b/src/renderer/lib/controlRouting.test.ts
@@ -353,6 +353,48 @@ describe('storedNodeListing', () => {
})
})
+// Issue #1288: `list` reads the geometry back, so a script can copy a size the user set by hand and
+// check what `resize` / `place` did. JSON rows ALWAYS carry it; the text form only behind the flag.
+describe('storedNodeListing — geometry', () => {
+ const stored = [
+ { id: 'g', kind: 'group', title: 'Team', position: { x: 1000, y: 500 }, size: { width: 800, height: 600 } },
+ { id: 'a', kind: 'terminal', title: 'A', parentId: 'g', position: { x: 28, y: 62.4 }, size: { width: 540, height: 480 } },
+ { id: 'b', kind: 'terminal', title: 'B', collapsed: true, position: { x: -10, y: 0 }, size: { width: 600, height: 400 } }
+ ]
+
+ it('every row carries x, y (canvas space), width, height and its parent — no flag needed', () => {
+ const rows = storedNodeListing(stored)
+ expect(rows[0]).toMatchObject({ x: 1000, y: 500, width: 800, height: 600, parent: null })
+ // Root space: the frame's origin is added in, and values are whole px.
+ expect(rows[1]).toMatchObject({ x: 1028, y: 562, width: 540, height: 480, parent: 'g' })
+ // A collapsed node occupies its header bar, and says what it opens to.
+ expect(rows[2]).toMatchObject({ x: -10, y: 0, width: 600, height: 40, collapsed: true, expandedHeight: 400 })
+ })
+
+ it('a precomputed (live, measured) geometry wins over the persisted fields', () => {
+ const [row] = storedNodeListing([
+ { ...stored[1], parentId: undefined, geometry: { x: 1, y: 2, width: 3, height: 4, parent: null } }
+ ])
+ expect(row).toMatchObject({ x: 1, y: 2, width: 3, height: 4, parent: null })
+ })
+
+ it('the text form stays one short line by default, and shows geometry only when asked', () => {
+ const rows = storedNodeListing(stored)
+ expect(controlListingText(rows)).toBe('g [group] Team\na [terminal] A\nb [terminal] B')
+ expect(controlListingText(rows, { geometry: true })).toBe(
+ 'g [group] Team @ 1000,500 800×600\n' +
+ 'a [terminal] A @ 1028,562 540×480 in g\n' +
+ 'b [terminal] B @ -10,0 600×40 collapsed (expands to 400)'
+ )
+ })
+
+ it('a row with no geometry to report renders as before, flag or not', () => {
+ const rows = storedNodeListing([{ id: 't', kind: 'terminal', title: 'T' }])
+ expect(rows[0]).not.toHaveProperty('x')
+ expect(controlListingText(rows, { geometry: true })).toBe('t [terminal] T')
+ })
+})
+
describe('storedNodeListing — a dependent held by work handed to its station (core/station-handover.ts)', () => {
it('names the station whose `done` is from before the work just handed to it', () => {
const nodes = [
diff --git a/src/renderer/lib/controlRouting.ts b/src/renderer/lib/controlRouting.ts
index e8771f41a..3a2d34cd4 100644
--- a/src/renderer/lib/controlRouting.ts
+++ b/src/renderer/lib/controlRouting.ts
@@ -34,6 +34,7 @@ import {
type StatusById
} from './pendingLaunch'
import { projectTravel } from './presenceTravel'
+import { geometryText, storedNodeGeometry, type NodeGeometry } from './nodeGeometry'
import {
projectCapabilityGrantedFor,
type CapabilityAckMap
@@ -56,6 +57,14 @@ export interface StoredNode {
agentId?: string
/** The GitHub issue the session was started on — hostile until `formatIssueRef` says otherwise. */
issueRef?: unknown
+ /** Persisted geometry (`CanvasNodeState`): an off-screen project's rows derive their place and
+ * size from these (`storedNodeGeometry`). */
+ position?: { x: number; y: number }
+ size?: { width: number; height: number }
+ parentId?: string
+ collapsed?: boolean
+ /** Precomputed by the LIVE canvas (`liveNodeGeometry` — measured sizes); wins over the fields above. */
+ geometry?: NodeGeometry
}
/**
@@ -200,6 +209,15 @@ export function storedNodeListing(
handovers: HandoverById = {}
) {
const live = new Set(nodes.map((n) => n.id))
+ // Every row carries its geometry (issue #1288), so a script needs no flag to read it; the TEXT form
+ // shows it only behind `list --geometry on`. A row of the live canvas arrives with it measured; a
+ // stored row's is derived here from the persisted fields, parent chain included.
+ const placed = nodes.filter(
+ (n): n is StoredNode & { position: { x: number; y: number }; size: { width: number; height: number } } =>
+ !!n.position && !!n.size
+ )
+ const geometryOf = (n: StoredNode): NodeGeometry | undefined =>
+ n.geometry ?? (n.position && n.size ? storedNodeGeometry({ ...n, position: n.position, size: n.size }, placed) : undefined)
const titleOf = (id: string): string => {
const t = nodes.find((n) => n.id === id)?.title
return t ? `${id} "${t}"` : id
@@ -252,8 +270,10 @@ export function storedNodeListing(
handovers
)
: []
+ const geometry = geometryOf(n)
return {
id: n.id, kind: n.kind ?? 'terminal', title: n.title ?? '',
+ ...(geometry ?? {}),
...(issue ? { issue } : {}),
...(status?.lastTurnError ? { lastTurnErrored: true } : {}),
...(status?.lastTurnInterrupted && !status.lastTurnError ? { lastTurnInterrupted: true } : {}),
@@ -301,8 +321,24 @@ const launchLabels = {
'blocked-failure': 'BLOCKED BY FAILURE (will not start on its own; run it with `run`)'
} as const
-export function controlListingText(rows: ReturnType<typeof storedNodeListing>): string {
+/** The `--geometry on` suffix of one row (`storedNodeListing` spreads the geometry flat), or '' for a
+ * row that has none. */
+function rowGeometryText(n: ReturnType<typeof storedNodeListing>[number]): string {
+ const g = n as Partial<NodeGeometry>
+ if (typeof g.x !== 'number' || typeof g.y !== 'number' || typeof g.width !== 'number' || typeof g.height !== 'number') {
+ return ''
+ }
+ return geometryText({ x: g.x, y: g.y, width: g.width, height: g.height, parent: g.parent ?? null, collapsed: g.collapsed, expandedHeight: g.expandedHeight })
+}
+
+/** `list`'s text answer. `geometry` (`list --geometry on`) adds each node's place and size; off by
+ * default so the line an agent reads most stays short. */
+export function controlListingText(
+ rows: ReturnType<typeof storedNodeListing>,
+ opts: { geometry?: boolean } = {}
+): string {
return rows.map((n) => `${n.id} [${n.kind}] ${n.title}` +
+ (opts.geometry ? rowGeometryText(n) : '') +
(n.issue ? ` — issue ${n.issue}` : '') +
(n.launchState ? ` — ${launchLabels[n.launchState]}` : '') +
(n.prWait ? ` — waits on ${n.prWait}` : '') +
diff --git a/src/renderer/lib/geometryReply.test.ts b/src/renderer/lib/geometryReply.test.ts
new file mode 100644
index 000000000..015629764
--- /dev/null
+++ b/src/renderer/lib/geometryReply.test.ts
@@ -0,0 +1,59 @@
+import { describe, it, expect } from 'vitest'
+import { placeReply, resizeReply } from './geometryReply'
+
+describe('resizeReply', () => {
+ it('says what was APPLIED — clamped, collapsed and restored nodes each say so', () => {
+ const { message, result } = resizeReply(
+ {
+ applied: [
+ { id: 'a', width: 540, height: 480, clamped: false, collapsed: false, restored: false },
+ { id: 'b', width: 260, height: 480, clamped: true, collapsed: false, restored: false },
+ { id: 'c', width: 540, height: 480, clamped: false, collapsed: true, restored: true }
+ ],
+ unknown: ['ghost']
+ },
+ true
+ )
+ expect(message).toBe(
+ 'resized 3 node(s): a 540×480, b 260×480 (clamped to what this kind of node allows), ' +
+ 'c 540×480 (collapsed: the width applies now, the height when it is expanded; was maximized: restored first)' +
+ ' (1 unknown id(s) skipped: ghost)'
+ )
+ expect(result).toMatchObject({ changed: true, unknown: ['ghost'] })
+ expect((result.resized as unknown[])[1]).toMatchObject({ id: 'b', width: 260, clamped: true })
+ })
+
+ it('an unchanged call is an answer, not a failure', () => {
+ const { message, result } = resizeReply(
+ { applied: [{ id: 'a', width: 540.2, height: 480, clamped: false, collapsed: false, restored: false }], unknown: [] },
+ false
+ )
+ expect(message).toBe('already that size — nothing changed: a 540×480')
+ expect(result).toMatchObject({ changed: false, resized: [{ width: 540 }] })
+ })
+})
+
+describe('placeReply', () => {
+ const placed = [
+ { id: 'a', x: 0, y: 0, restored: false },
+ { id: 'b', x: 540.4, y: 0, restored: true }
+ ]
+
+ it('names the form: one node, a block, or an offset', () => {
+ expect(placeReply({ placed: placed.slice(0, 1), unknown: [], carried: [] }, { x: 0, y: 0 }, true).message).toBe(
+ 'placed 1 node(s): a at 0,0'
+ )
+ expect(placeReply({ placed, unknown: [], carried: ['k'] }, { x: 0, y: 0 }, true).message).toBe(
+ 'placed 2 node(s) as one block: a at 0,0, b at 540,0 (was maximized: restored first) (k moved with the frame that holds it)'
+ )
+ expect(placeReply({ placed, unknown: ['z'], carried: [] }, { dx: 8 }, true).message).toBe(
+ 'moved 2 node(s) by 8,0: a at 0,0, b at 540,0 (was maximized: restored first) (1 unknown id(s) skipped: z)'
+ )
+ })
+
+ it('an unchanged call says nothing moved, and the result carries whole-px positions', () => {
+ const { message, result } = placeReply({ placed: placed.slice(0, 1), unknown: [], carried: [] }, { x: 0 }, false)
+ expect(message).toBe('already there — nothing moved: a at 0,0')
+ expect(result).toEqual({ placed: [{ id: 'a', x: 0, y: 0, restored: false }], carried: [], unknown: [], changed: false })
+ })
+})
diff --git a/src/renderer/lib/geometryReply.ts b/src/renderer/lib/geometryReply.ts
new file mode 100644
index 000000000..a71bc926e
--- /dev/null
+++ b/src/renderer/lib/geometryReply.ts
@@ -0,0 +1,70 @@
+// The replies of `resize` and `place` (issue #1288), kept pure so the sentences an agent acts on are
+// tested where Canvas.tsx — a component with no unit seam — cannot be.
+//
+// The rule both follow: say what was APPLIED, not what was asked. A clamped size, a node that was
+// restored from maximized first, a collapsed node whose height waits for its expand, a framed child
+// that rode along with its frame — each is a difference between the request and the canvas, and an
+// agent that cannot see the difference builds its next call on the wrong numbers.
+
+import type { PlaceApplied, ResizeApplied } from '../state/workspace'
+
+const px = (v: number): number => Math.round(v) + 0
+
+const skipped = (unknown: readonly string[]): string =>
+ unknown.length ? ` (${unknown.length} unknown id(s) skipped: ${unknown.join(', ')})` : ''
+
+/** One line for a `resize` call, plus the JSON `result` beside it. */
+export function resizeReply(
+ out: { applied: readonly ResizeApplied[]; unknown: readonly string[] },
+ changed: boolean
+): { message: string; result: Record<string, unknown> } {
+ const notes = (a: ResizeApplied): string => {
+ const n: string[] = []
+ if (a.clamped) n.push('clamped to what this kind of node allows')
+ if (a.collapsed) n.push('collapsed: the width applies now, the height when it is expanded')
+ if (a.restored) n.push('was maximized: restored first')
+ return n.length ? ` (${n.join('; ')})` : ''
+ }
+ const each = out.applied.map((a) => `${a.id} ${px(a.width)}×${px(a.height)}${notes(a)}`).join(', ')
+ const message = changed
+ ? `resized ${out.applied.length} node(s): ${each}${skipped(out.unknown)}`
+ : `already that size — nothing changed: ${each}${skipped(out.unknown)}`
+ return {
+ message,
+ result: {
+ resized: out.applied.map((a) => ({ ...a, width: px(a.width), height: px(a.height) })),
+ unknown: [...out.unknown],
+ changed
+ }
+ }
+}
+
+/** One line for a `place` call, plus the JSON `result` beside it. */
+export function placeReply(
+ out: { placed: readonly PlaceApplied[]; unknown: readonly string[]; carried: readonly string[] },
+ to: { x?: number; y?: number; dx?: number; dy?: number },
+ changed: boolean
+): { message: string; result: Record<string, unknown> } {
+ const at = out.placed.map((p) => `${p.id} at ${px(p.x)},${px(p.y)}${p.restored ? ' (was maximized: restored first)' : ''}`).join(', ')
+ const how =
+ to.dx !== undefined || to.dy !== undefined
+ ? `moved ${out.placed.length} node(s) by ${to.dx ?? 0},${to.dy ?? 0}`
+ : out.placed.length > 1
+ ? `placed ${out.placed.length} node(s) as one block`
+ : `placed ${out.placed.length} node(s)`
+ const carried = out.carried.length
+ ? ` (${out.carried.join(', ')} moved with the frame that holds ${out.carried.length > 1 ? 'them' : 'it'})`
+ : ''
+ const message = changed
+ ? `${how}: ${at}${carried}${skipped(out.unknown)}`
+ : `already there — nothing moved: ${at}${carried}${skipped(out.unknown)}`
+ return {
+ message,
+ result: {
+ placed: out.placed.map((p) => ({ ...p, x: px(p.x), y: px(p.y) })),
+ carried: [...out.carried],
+ unknown: [...out.unknown],
+ changed
+ }
+ }
+}
diff --git a/src/renderer/lib/nodeGeometry.test.ts b/src/renderer/lib/nodeGeometry.test.ts
new file mode 100644
index 000000000..2e249bab4
--- /dev/null
+++ b/src/renderer/lib/nodeGeometry.test.ts
@@ -0,0 +1,59 @@
+import { describe, it, expect } from 'vitest'
+import { geometryText, liveNodeGeometry, storedNodeGeometry } from './nodeGeometry'
+import { COLLAPSED_HEIGHT } from './nodeSizing'
+
+const live = (id: string, extra: Record<string, unknown> = {}) => ({
+ id,
+ position: { x: 0, y: 0 },
+ data: {},
+ ...extra
+})
+
+describe('liveNodeGeometry', () => {
+ it('reports the MEASURED size first — what is on screen — then the persisted one', () => {
+ const measured = live('a', { width: 600, height: 400, measured: { width: 612.4, height: 398.6 } })
+ expect(liveNodeGeometry(measured, [measured])).toMatchObject({ width: 612, height: 399 })
+ const fresh = live('b', { width: 600, height: 400 })
+ expect(liveNodeGeometry(fresh, [fresh])).toMatchObject({ width: 600, height: 400 })
+ const styleOnly = live('c', { style: { width: 300, height: 200 } })
+ expect(liveNodeGeometry(styleOnly, [styleOnly])).toMatchObject({ width: 300, height: 200 })
+ })
+
+ it('adds every ancestor frame origin: x/y are canvas coordinates, the numbers `place` takes', () => {
+ const outer = live('o', { position: { x: 100, y: 200 } })
+ const inner = live('i', { position: { x: 10, y: 20 }, parentId: 'o' })
+ const a = live('a', { position: { x: 1.4, y: -2.6 }, parentId: 'i', width: 50, height: 50 })
+ expect(liveNodeGeometry(a, [outer, inner, a])).toEqual({ x: 111, y: 217, width: 50, height: 50, parent: 'i' })
+ })
+
+ it('a collapsed node reports its header bar and the height it opens to', () => {
+ const a = live('a', { width: 600, height: COLLAPSED_HEIGHT, data: { collapsed: true, expandedHeight: 400 } })
+ expect(liveNodeGeometry(a, [a])).toEqual({
+ x: 0, y: 0, width: 600, height: COLLAPSED_HEIGHT, parent: null, collapsed: true, expandedHeight: 400
+ })
+ })
+})
+
+describe('storedNodeGeometry', () => {
+ it('reads the persisted size; a collapsed node persists the height it EXPANDS to', () => {
+ const f = { id: 'f', position: { x: 5, y: 5 }, size: { width: 900, height: 700 } }
+ const a = { id: 'a', position: { x: 10, y: 10 }, size: { width: 600, height: 400 }, parentId: 'f', collapsed: true }
+ expect(storedNodeGeometry(a, [f, a])).toEqual({
+ x: 15, y: 15, width: 600, height: COLLAPSED_HEIGHT, parent: 'f', collapsed: true, expandedHeight: 400
+ })
+ })
+
+ it('never throws on a self-parented node (hand-edited project.json)', () => {
+ const a = { id: 'a', position: { x: 10, y: 10 }, size: { width: 600, height: 400 }, parentId: 'a' }
+ expect(storedNodeGeometry(a, [a])).toMatchObject({ x: 10, y: 10 })
+ })
+})
+
+describe('geometryText', () => {
+ it('is the `list --geometry on` suffix', () => {
+ expect(geometryText({ x: 0, y: -40, width: 540, height: 480, parent: null })).toBe(' @ 0,-40 540×480')
+ expect(geometryText({ x: 1, y: 2, width: 3, height: 40, parent: 'g', collapsed: true, expandedHeight: 9 })).toBe(
+ ' @ 1,2 3×40 in g collapsed (expands to 9)'
+ )
+ })
+})
diff --git a/src/renderer/lib/nodeGeometry.ts b/src/renderer/lib/nodeGeometry.ts
new file mode 100644
index 000000000..9cba29095
--- /dev/null
+++ b/src/renderer/lib/nodeGeometry.ts
@@ -0,0 +1,101 @@
+// Where a node is and how big it is, as `list` reports it (issue #1288): the numbers `place` and
+// `resize` take back, so a script can read a layout, copy a size the user set by hand onto the
+// other nodes, and check the result.
+//
+// Two sources, one shape. The LIVE canvas reports what React Flow MEASURED from the DOM — the size
+// actually on screen — and falls back to the persisted width/height for a node that has not been
+// measured yet (the first tick after a load). A project that is NOT on screen was never rendered,
+// so its rows are the PERSISTED size: what the node was born with, or the last size the user (or
+// `resize`) gave it — which is what it will be drawn at when the project is next shown.
+//
+// Light on purpose (shared + lib/nodeSizing only): the control listing imports it, and the listing
+// is imported by modules that must not pull the whole node-state module in.
+
+import { rootPositionWith } from '@shared/root-position'
+import { COLLAPSED_HEIGHT } from './nodeSizing'
+
+export interface NodeGeometry {
+ /** Top-left in ROOT (canvas) space — a framed node's frame origins are added in. Whole px. */
+ x: number
+ y: number
+ /** The size it occupies now (a collapsed node: its header bar). Whole px. */
+ width: number
+ height: number
+ /** The frame it sits in, or null at the top level. */
+ parent: string | null
+ /** Header-only. `expandedHeight` is the height it opens to — the one `resize --height` sets. */
+ collapsed?: true
+ expandedHeight?: number
+}
+
+// Rounded: sub-pixel positions are routine (a drag at fractional zoom), and the verbs that take these
+// numbers back take whole pixels. `+ 0` normalizes a -0.
+const px = (v: number): number => Math.round(v) + 0
+
+/** The slice of a live React Flow node this reads. */
+interface LiveGeometryNode {
+ id: string
+ position: { x: number; y: number }
+ parentId?: string
+ measured?: { width?: number; height?: number }
+ width?: number | null
+ height?: number | null
+ style?: { width?: unknown; height?: unknown }
+ data: { collapsed?: unknown; expandedHeight?: unknown }
+}
+
+const num = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) ? v : undefined)
+
+/** A node on the LIVE canvas: measured size first, persisted second (see the header). */
+export function liveNodeGeometry(node: LiveGeometryNode, nodes: readonly LiveGeometryNode[]): NodeGeometry {
+ const byId = new Map(nodes.map((n) => [n.id, n]))
+ const root = rootPositionWith(node, (id) => byId.get(id))
+ const width = num(node.measured?.width) ?? num(node.width) ?? num(node.style?.width) ?? 0
+ const height = num(node.measured?.height) ?? num(node.height) ?? num(node.style?.height) ?? 0
+ const collapsed = !!node.data.collapsed
+ const expanded = num(node.data.expandedHeight)
+ return {
+ x: px(root.x),
+ y: px(root.y),
+ width: px(width),
+ height: px(height),
+ parent: node.parentId ?? null,
+ ...(collapsed ? { collapsed: true as const, ...(expanded !== undefined ? { expandedHeight: px(expanded) } : {}) } : {})
+ }
+}
+
+/** The slice of a SERIALIZED node (`CanvasNodeState`) this reads. */
+interface StoredGeometryNode {
+ id: string
+ position: { x: number; y: number }
+ size: { width: number; height: number }
+ parentId?: string
+ collapsed?: boolean
+}
+
+/**
+ * A node of a project that is NOT on screen: the persisted size. A collapsed node persists the
+ * height it EXPANDS to (`flowToNodeStates`), so its drawn height is the header bar's.
+ */
+export function storedNodeGeometry(node: StoredGeometryNode, nodes: readonly StoredGeometryNode[]): NodeGeometry {
+ const byId = new Map(nodes.map((n) => [n.id, n]))
+ const root = rootPositionWith(node, (id) => byId.get(id))
+ const collapsed = !!node.collapsed
+ return {
+ x: px(root.x),
+ y: px(root.y),
+ width: px(node.size.width),
+ height: px(collapsed ? COLLAPSED_HEIGHT : node.size.height),
+ parent: node.parentId ?? null,
+ ...(collapsed ? { collapsed: true as const, expandedHeight: px(node.size.height) } : {})
+ }
+}
+
+/** The text form behind `list --geometry on`: ` @ x,y w×h`, then where it sits and whether it is folded. */
+export function geometryText(g: NodeGeometry): string {
+ return (
+ ` @ ${g.x},${g.y} ${g.width}×${g.height}` +
+ (g.parent ? ` in ${g.parent}` : '') +
+ (g.collapsed ? ` collapsed${g.expandedHeight !== undefined ? ` (expands to ${g.expandedHeight})` : ''}` : '')
+ )
+}
diff --git a/src/renderer/lib/nodeSizing.ts b/src/renderer/lib/nodeSizing.ts
index 40ac55b58..b47878504 100644
--- a/src/renderer/lib/nodeSizing.ts
+++ b/src/renderer/lib/nodeSizing.ts
@@ -29,6 +29,9 @@ export const NODE_MIN_SIZES: Record<NodeKind, { width: number; height: number }>
whiteboard: { width: 320, height: 220 }
}
+/** Height of a node when collapsed (header only). Re-exported by `state/workspace`. */
+export const COLLAPSED_HEIGHT = 40
+
export interface Rect {
x: number
y: number
diff --git a/src/renderer/lib/storedGeometry.test.ts b/src/renderer/lib/storedGeometry.test.ts
index 73499d734..35cb53d0e 100644
--- a/src/renderer/lib/storedGeometry.test.ts
+++ b/src/renderer/lib/storedGeometry.test.ts
@@ -1,6 +1,14 @@
import { describe, it, expect } from 'vitest'
import type { CanvasNodeState } from '@shared/types'
-import { applyOwnCanvasMutation, groupSelectedNodes, nodeStatesToFlow, ungroupNodes } from '../state/workspace'
+import {
+ applyOwnCanvasMutation,
+ arrangeNodes,
+ groupSelectedNodes,
+ nodeStatesToFlow,
+ placeNodes,
+ resizeNodes,
+ ungroupNodes
+} from '../state/workspace'
import { groupsFirst } from '@shared/node-order'
import { geometryMutations } from './storedGeometry'
@@ -60,4 +68,45 @@ describe('geometryMutations — a structural verb run off screen', () => {
const ms = geometryMutations(stored, nodeStatesToFlow(stored.slice(0, 2)))
expect(ms).toEqual([])
})
+
+ // Issue #1288: `resize` / `place` run off screen through the same write. Their whole effect is
+ // geometry, so the patch must carry it and nothing else.
+ it('resize writes the new persisted size, and leaves every other stored field alone', () => {
+ const out = resizeNodes(nodeStatesToFlow(stored), ['a', 'b'], { width: 540, height: 480 })
+ if (!out.ok) throw new Error(out.error)
+ const after = apply(stored, geometryMutations(stored, out.nodes))
+ expect(after.find((n) => n.id === 'a')!.size).toEqual({ width: 540, height: 480 })
+ expect(after.find((n) => n.id === 'b')!.size).toEqual({ width: 540, height: 480 })
+ expect(after.find((n) => n.id === 'c')!.size).toEqual({ width: 600, height: 400 })
+ expect(after.find((n) => n.id === 'a')!.pendingLaunch).toEqual({ after: [], command: 'claude' })
+ })
+
+ it('a collapsed stored node keeps collapsed, and stores the height it will expand to', () => {
+ const folded = [term('f', 0, { collapsed: true })]
+ const out = resizeNodes(nodeStatesToFlow(folded), ['f'], { height: 500 })
+ if (!out.ok) throw new Error(out.error)
+ const [f] = apply(folded, geometryMutations(folded, out.nodes))
+ expect(f.collapsed).toBe(true)
+ expect(f.size).toEqual({ width: 600, height: 500 })
+ })
+
+ it('place writes the position; a maximized stored node loses its restore rect (premaxRect is geometry)', () => {
+ const premaxRect = { x: 50, y: 60, width: 600, height: 400 }
+ const maxed = [term('m', 0, { premaxRect, size: { width: 1900, height: 1000 } } as Partial<CanvasNodeState>), term('o', 2000)]
+ const out = placeNodes(nodeStatesToFlow(maxed), ['m'], { x: 10, y: 20 })
+ if (!out.ok) throw new Error(out.error)
+ const [m] = apply(maxed, geometryMutations(maxed, out.nodes))
+ expect(m.position).toEqual({ x: 10, y: 20 })
+ expect(m.size).toEqual({ width: 600, height: 400 })
+ expect(m.premaxRect).toBeUndefined()
+ })
+
+ it('an arrange over a maximized stored node clears its restore rect too (it was left behind before)', () => {
+ const premaxRect = { x: 50, y: 60, width: 600, height: 400 }
+ const maxed = [term('m', 0, { premaxRect, size: { width: 1900, height: 1000 } } as Partial<CanvasNodeState>), term('o', 2000)]
+ const next = arrangeNodes(nodeStatesToFlow(maxed), ['m', 'o'], { layout: 'row', gap: 0 })
+ const [m] = apply(maxed, geometryMutations(maxed, next))
+ expect(m.premaxRect).toBeUndefined()
+ })
})
+
diff --git a/src/renderer/lib/storedGeometry.ts b/src/renderer/lib/storedGeometry.ts
index 4c7f2fbd2..3c99ba57a 100644
--- a/src/renderer/lib/storedGeometry.ts
+++ b/src/renderer/lib/storedGeometry.ts
@@ -1,5 +1,5 @@
-// The write half of a structural control verb (`group`, `ungroup`, `move`, `arrange`, `align`) run
-// against a project that is NOT on screen.
+// The write half of a structural control verb (`group`, `ungroup`, `move`, `arrange`, `align`,
+// `resize`, `place`) run against a project that is NOT on screen.
//
// Those verbs compute a whole new node array through the same pure transforms the live canvas uses
// (`groupSelectedNodes`, `reparentNode`, `arrangeNodes`, …), over the owning project's serialized
@@ -16,8 +16,13 @@
import type { CanvasMutation, CanvasNodeState } from '@shared/types'
import { flowToNodeStates, type CanvasNode } from '../state/workspace'
-/** The fields a structural verb may change on a node that already exists. */
-const GEOMETRY = ['position', 'size', 'parentId', 'group'] as const
+/**
+ * The fields a structural verb may change on a node that already exists. `premaxRect` is geometry
+ * too: every layout pass restores a maximized node first (`restoreMaximizedWhere`), and leaving the
+ * stored rect behind kept the node "maximized" on disk — the next panel pin re-claimed the viewport
+ * for it, and its Restore button teleported it back to where it was before the layout.
+ */
+const GEOMETRY = ['position', 'size', 'parentId', 'group', 'premaxRect'] as const
// null and absent are the same fact here (`group: null` vs no `group`), or an untouched node would
// be rewritten just for its spelling.
diff --git a/src/renderer/state/workspace.geometry.test.ts b/src/renderer/state/workspace.geometry.test.ts
new file mode 100644
index 000000000..2d9ec17d7
--- /dev/null
+++ b/src/renderer/state/workspace.geometry.test.ts
@@ -0,0 +1,291 @@
+import { describe, it, expect } from 'vitest'
+import {
+ arrangeByLineage,
+ arrangeGroupChildren,
+ arrangeNodes,
+ COLLAPSED_HEIGHT,
+ flowToNodeStates,
+ GROUP_HEADER,
+ GROUP_PAD,
+ placeNodes,
+ reparentNode,
+ resizeNodes,
+ rootPosition,
+ tidyCanvas,
+ type CanvasNode
+} from './workspace'
+import { NODE_MIN_SIZES } from '../lib/nodeSizing'
+import { NODE_SIZE_MAX } from '@shared/default-node-size'
+import { geometryArgsRefusal } from '@shared/geometry-verbs'
+
+// Issue #1288 — the geometry an agent could not set: the arrange gap, an existing node's size, and
+// a node's place. Pure transforms, so every rule is pinned here; Canvas only parses and writes.
+
+const n = (id: string, x: number, y: number, w = 100, h = 50, extra: Partial<CanvasNode> = {}): CanvasNode =>
+ ({
+ id,
+ type: 'terminal',
+ position: { x, y },
+ width: w,
+ height: h,
+ style: { width: w, height: h },
+ data: { title: id, color: '#fff', group: null },
+ ...extra
+ }) as CanvasNode
+const frame = (id: string, x: number, y: number, w: number, h: number, parentId?: string): CanvasNode =>
+ n(id, x, y, w, h, { type: 'group', ...(parentId ? { parentId, extent: 'parent' as const } : {}) })
+const kid = (id: string, parentId: string, x: number, y: number, w = 100, h = 50): CanvasNode =>
+ n(id, x, y, w, h, { parentId, extent: 'parent' as const })
+const get = (nodes: CanvasNode[], id: string): CanvasNode => nodes.find((x) => x.id === id)!
+
+describe('arrange --gap reaches every packing', () => {
+ it('--nodes: gap 0 packs the nodes touching, 8 leaves 8 px', () => {
+ const nodes = [n('a', 0, 0), n('b', 500, 0), n('c', 900, 900), n('d', 50, 700)]
+ const tight = arrangeNodes(nodes, ['a', 'b', 'c', 'd'], { layout: 'grid', cols: 2, gap: 0 })
+ expect(get(tight, 'b').position).toEqual({ x: 100, y: 0 })
+ expect(get(tight, 'c').position).toEqual({ x: 0, y: 50 })
+ expect(get(tight, 'd').position).toEqual({ x: 100, y: 50 })
+ const eight = arrangeNodes(nodes, ['a', 'b', 'c', 'd'], { layout: 'grid', cols: 2, gap: 8 })
+ expect(get(eight, 'd').position).toEqual({ x: 108, y: 58 })
+ // Absent = the default 40, which is what every caller got before the flag existed.
+ expect(get(arrangeNodes(nodes, ['a', 'b'], { layout: 'row' }), 'b').position).toEqual({ x: 140, y: 0 })
+ })
+
+ it('--group <frameId>: grid snapping does NOT undo a small gap — only the frame padding snaps', () => {
+ const nodes = [frame('g', 0, 0, 900, 900), kid('a', 'g', 300, 300), kid('b', 'g', 40, 500)]
+ const grid = 20
+ const out = arrangeGroupChildren(nodes, 'g', { layout: 'row', gap: 0, grid })
+ const a = rootPosition(get(out, 'a'), out)
+ const b = rootPosition(get(out, 'b'), out)
+ // Reading order (y, x): a then b. Touching, although 0 and 100 are not both "nice" grid numbers.
+ expect(b.x - a.x).toBe(100)
+ expect(b.y).toBe(a.y)
+ const eight = arrangeGroupChildren(nodes, 'g', { layout: 'row', gap: 8, grid })
+ expect(rootPosition(get(eight, 'b'), eight).x - rootPosition(get(eight, 'a'), eight).x).toBe(108)
+ // The frame still keeps its OWN margin around the children: padding is not the gap.
+ const pad = Math.max(GROUP_PAD, grid)
+ expect(get(out, 'a').position).toEqual({ x: pad, y: pad + GROUP_HEADER })
+ })
+
+ it('--group top: Tidy canvas and lineage bands take it too', () => {
+ const nodes = [n('a', 0, 0), n('b', 400, 0)]
+ expect(get(tidyCanvas(nodes, [], { gap: 0 }), 'b').position).toEqual({ x: 100, y: 0 })
+ const banded = arrangeByLineage([n('o', 0, 0), n('s', 0, 300)], [{ source: 'o', target: 's' }], { gap: 0 })
+ expect(get(banded, 's').position).toEqual({ x: 0, y: 50 })
+ })
+})
+
+describe('resizeNodes', () => {
+ it('sets both axes, or one and keeps the other, and drops the stale measurement', () => {
+ const nodes = [n('a', 0, 0, 600, 400, { measured: { width: 600, height: 400 } })]
+ const both = resizeNodes(nodes, ['a'], { width: 540, height: 480 })
+ if (!both.ok) throw new Error(both.error)
+ const a = get(both.nodes, 'a')
+ expect([a.width, a.height, a.style?.width, a.style?.height]).toEqual([540, 480, 540, 480])
+ // flowToNodeStates prefers `measured`; a save racing the re-measure would persist the OLD size.
+ expect(a.measured).toBeUndefined()
+ expect(flowToNodeStates(both.nodes)[0].size).toEqual({ width: 540, height: 480 })
+ expect(both.applied).toEqual([{ id: 'a', width: 540, height: 480, clamped: false, collapsed: false, restored: false }])
+
+ const widthOnly = resizeNodes(nodes, ['a'], { width: 700 })
+ if (!widthOnly.ok) throw new Error(widthOnly.error)
+ expect([get(widthOnly.nodes, 'a').width, get(widthOnly.nodes, 'a').height]).toEqual([700, 400])
+ })
+
+ it('clamps to the kind minimum and the canvas maximum, and says so', () => {
+ const nodes = [n('a', 0, 0, 600, 400), n('s', 0, 0, 240, 200, { type: 'sticky' })]
+ const small = resizeNodes(nodes, ['a', 's'], { width: 10, height: 10 })
+ if (!small.ok) throw new Error(small.error)
+ const t = NODE_MIN_SIZES.terminal
+ const st = NODE_MIN_SIZES.sticky
+ expect(small.applied).toEqual([
+ { id: 'a', width: t.width, height: t.height, clamped: true, collapsed: false, restored: false },
+ { id: 's', width: st.width, height: st.height, clamped: true, collapsed: false, restored: false }
+ ])
+ expect(get(small.nodes, 'a').width).toBe(t.width)
+ const big = resizeNodes(nodes, ['a'], { width: 99_999 })
+ if (!big.ok) throw new Error(big.error)
+ expect(big.applied[0]).toMatchObject({ width: NODE_SIZE_MAX.width, height: 400, clamped: true })
+ })
+
+ it('applies the size exactly — no grid snapping', () => {
+ const out = resizeNodes([n('a', 0, 0, 600, 400)], ['a'], { width: 545, height: 333 }, 20)
+ if (!out.ok) throw new Error(out.error)
+ expect([get(out.nodes, 'a').width, get(out.nodes, 'a').height]).toEqual([545, 333])
+ })
+
+ it('refuses a group frame by name and changes NOTHING, even beside valid ids', () => {
+ const nodes = [frame('g', 0, 0, 400, 300), n('a', 500, 0)]
+ expect(resizeNodes(nodes, ['a', 'g'], { width: 300 })).toEqual({
+ ok: false,
+ error: 'resize: g is a group frame — a frame sizes itself to what it holds; resize the nodes inside it, or `arrange --group g`'
+ })
+ })
+
+ it('skips unknown ids, and refuses when none resolve', () => {
+ const nodes = [n('a', 0, 0, 600, 400)]
+ const out = resizeNodes(nodes, ['ghost', 'a'], { width: 300 })
+ expect(out.ok && out.unknown).toEqual(['ghost'])
+ expect(resizeNodes(nodes, ['ghost'], { width: 300 })).toEqual({ ok: false, error: 'resize: none of the given node ids exist' })
+ })
+
+ it('returns the SAME array when every node already has that size', () => {
+ const nodes = [n('a', 0, 0, 540, 480, { measured: { width: 540.3, height: 480 } })]
+ const out = resizeNodes(nodes, ['a'], { width: 540, height: 480 })
+ expect(out.ok && out.nodes).toBe(nodes)
+ })
+
+ it('a COLLAPSED node keeps its header-only look: width now, height when it is expanded', () => {
+ const folded = n('a', 0, 0, 600, COLLAPSED_HEIGHT, { data: { title: 'a', color: '#fff', group: null, collapsed: true, expandedHeight: 400 } })
+ const out = resizeNodes([folded], ['a'], { width: 540, height: 480 })
+ if (!out.ok) throw new Error(out.error)
+ const a = get(out.nodes, 'a')
+ expect(a.width).toBe(540)
+ expect(a.height).toBe(COLLAPSED_HEIGHT)
+ expect(a.data.collapsed).toBe(true)
+ expect(a.data.expandedHeight).toBe(480)
+ // Persisted as the height it opens to — the collapsed-node rule of flowToNodeStates.
+ expect(flowToNodeStates(out.nodes)[0].size).toEqual({ width: 540, height: 480 })
+ expect(out.applied[0]).toMatchObject({ collapsed: true, height: 480 })
+ // Unchanged expand height ⇒ only the width counts as a change.
+ const same = resizeNodes(out.nodes, ['a'], { height: 480 })
+ expect(same.ok && same.nodes).toBe(out.nodes)
+ })
+
+ it('a MAXIMIZED node is restored first, then sized — never left holding its restore rect', () => {
+ const premaxRect = { x: 50, y: 60, width: 600, height: 400 }
+ const maxed = n('a', 0, 0, 1900, 1000, { data: { title: 'a', color: '#fff', group: null, premaxRect } })
+ const out = resizeNodes([maxed], ['a'], { width: 540 })
+ if (!out.ok) throw new Error(out.error)
+ const a = get(out.nodes, 'a')
+ expect(a.data.premaxRect).toBeUndefined()
+ // Back at its own spot, with its own height (the axis not named), at the new width.
+ expect(a.position).toEqual({ x: 50, y: 60 })
+ expect([a.width, a.height]).toEqual([540, 400])
+ expect(out.applied[0]).toMatchObject({ restored: true })
+ expect(flowToNodeStates(out.nodes)[0].premaxRect).toBeUndefined()
+ })
+
+ it('re-fits the frame — and every frame around it — around a resized child', () => {
+ const nodes = [
+ frame('outer', 0, 0, 400, 300),
+ frame('inner', GROUP_PAD, GROUP_PAD + GROUP_HEADER, 200, 150, 'outer'),
+ kid('a', 'inner', GROUP_PAD, GROUP_PAD + GROUP_HEADER, 100, 50)
+ ]
+ const before = rootPosition(get(nodes, 'a'), nodes)
+ const out = resizeNodes(nodes, ['a'], { width: 900, height: 600 })
+ if (!out.ok) throw new Error(out.error)
+ const inner = get(out.nodes, 'inner')
+ const outer = get(out.nodes, 'outer')
+ expect(inner.width).toBe(900 + GROUP_PAD * 2)
+ expect(outer.width as number).toBeGreaterThanOrEqual((inner.width as number) + GROUP_PAD * 2)
+ // Resizing grows to the right and down; the node itself did not move.
+ expect(rootPosition(get(out.nodes, 'a'), out.nodes)).toEqual(before)
+ })
+})
+
+describe('placeNodes', () => {
+ it('puts a top-level node at canvas coordinates, one axis or both', () => {
+ const nodes = [n('a', 300, 300), n('b', 0, 0)]
+ const out = placeNodes(nodes, ['a'], { x: 0, y: -40 })
+ if (!out.ok) throw new Error(out.error)
+ expect(get(out.nodes, 'a').position).toEqual({ x: 0, y: -40 })
+ expect(get(out.nodes, 'b')).toBe(nodes[1])
+ const xOnly = placeNodes(nodes, ['a'], { x: 10 })
+ expect(xOnly.ok && get(xOnly.nodes, 'a').position).toEqual({ x: 10, y: 300 })
+ })
+
+ it('a framed node STAYS in its frame, lands exactly on the root coordinates, and the frames re-fit', () => {
+ const nodes = [
+ frame('outer', 1000, 1000, 400, 300),
+ frame('inner', GROUP_PAD, GROUP_PAD + GROUP_HEADER, 200, 150, 'outer'),
+ kid('a', 'inner', GROUP_PAD, GROUP_PAD + GROUP_HEADER),
+ kid('b', 'inner', GROUP_PAD + 120, GROUP_PAD + GROUP_HEADER)
+ ]
+ const out = placeNodes(nodes, ['a'], { x: 200, y: 150 }, 20)
+ if (!out.ok) throw new Error(out.error)
+ const a = get(out.nodes, 'a')
+ expect(a.parentId).toBe('inner')
+ expect(rootPosition(a, out.nodes)).toEqual({ x: 200, y: 150 })
+ // Its sibling did not move on the canvas, and both frames grew to hold the pair.
+ expect(rootPosition(get(out.nodes, 'b'), out.nodes)).toEqual(rootPosition(get(nodes, 'b'), nodes))
+ const inner = get(out.nodes, 'inner')
+ const innerRoot = rootPosition(inner, out.nodes)
+ expect(innerRoot.x).toBeLessThanOrEqual(200 - GROUP_PAD)
+ expect(get(out.nodes, 'outer').position.x).toBeLessThanOrEqual(innerRoot.x)
+ expect(out.placed).toEqual([{ id: 'a', x: 200, y: 150, restored: false }])
+ })
+
+ it('several ids with --x/--y move as ONE block: shape kept, top-left on (x, y)', () => {
+ const nodes = [n('a', 100, 100), n('b', 200, 100), n('c', 100, 150)]
+ const out = placeNodes(nodes, ['a', 'b', 'c'], { x: 0, y: 0 })
+ if (!out.ok) throw new Error(out.error)
+ expect(['a', 'b', 'c'].map((id) => get(out.nodes, id).position)).toEqual([
+ { x: 0, y: 0 },
+ { x: 100, y: 0 },
+ { x: 0, y: 50 }
+ ])
+ // The BLOCK's top-left, not the first id's: listing order does not change where the block lands.
+ for (const order of [['b', 'c', 'a'], ['c', 'b', 'a']]) {
+ const reordered = placeNodes(nodes, order, { x: 0, y: 0 })
+ if (!reordered.ok) throw new Error(reordered.error)
+ expect(reordered.nodes.map((x) => x.position), order.join()).toEqual(out.nodes.map((x) => x.position))
+ }
+ })
+
+ it('--dx/--dy shifts every node by the offset, framed or not', () => {
+ const nodes = [frame('g', 0, 0, 300, 200), kid('k', 'g', 30, 70), n('a', 500, 500)]
+ const before = rootPosition(get(nodes, 'k'), nodes)
+ const out = placeNodes(nodes, ['k', 'a'], { dx: 8, dy: -8 })
+ if (!out.ok) throw new Error(out.error)
+ expect(rootPosition(get(out.nodes, 'k'), out.nodes)).toEqual({ x: before.x + 8, y: before.y - 8 })
+ expect(get(out.nodes, 'a').position).toEqual({ x: 508, y: 492 })
+ })
+
+ it('a frame carries its subtree, and a listed descendant is not moved twice', () => {
+ const nodes = [frame('g', 0, 0, 300, 200), kid('k', 'g', 30, 70)]
+ const out = placeNodes(nodes, ['g', 'k'], { dx: 100, dy: 0 })
+ if (!out.ok) throw new Error(out.error)
+ expect(get(out.nodes, 'g').position).toEqual({ x: 100, y: 0 })
+ expect(get(out.nodes, 'k').position).toEqual({ x: 30, y: 70 })
+ expect(out.carried).toEqual(['k'])
+ })
+
+ it('a MAXIMIZED node is restored first, then placed', () => {
+ const premaxRect = { x: 50, y: 60, width: 600, height: 400 }
+ const maxed = n('a', 0, 0, 1900, 1000, { data: { title: 'a', color: '#fff', group: null, premaxRect } })
+ const out = placeNodes([maxed], ['a'], { x: 10, y: 20 })
+ if (!out.ok) throw new Error(out.error)
+ const a = get(out.nodes, 'a')
+ expect(a.data.premaxRect).toBeUndefined()
+ expect(a.position).toEqual({ x: 10, y: 20 })
+ expect([a.width, a.height]).toEqual([600, 400])
+ expect(out.placed[0].restored).toBe(true)
+ })
+
+ it('places exactly — grid snapping on or off', () => {
+ const out = placeNodes([n('a', 0, 0)], ['a'], { x: 13, y: 7 }, 20)
+ expect(out.ok && get(out.nodes, 'a').position).toEqual({ x: 13, y: 7 })
+ })
+
+ it('returns the SAME array when nothing moves, and refuses when no id resolves', () => {
+ const nodes = [n('a', 10, 20)]
+ const out = placeNodes(nodes, ['a', 'ghost'], { x: 10, y: 20 })
+ expect(out.ok && out.nodes).toBe(nodes)
+ expect(out.ok && out.unknown).toEqual(['ghost'])
+ expect(placeNodes(nodes, ['ghost'], { x: 0 })).toEqual({ ok: false, error: 'place: none of the given node ids exist' })
+ })
+})
+
+describe('why placement is not a flag on move', () => {
+ it('move without --group takes a framed node OUT of its frame — so move refuses --x/--y', () => {
+ const nodes = [frame('g', 100, 100, 300, 200), kid('k', 'g', 30, 70)]
+ // What `move --nodes k` does: reparent to the top level. An `--x` riding along would be ignored,
+ // and the agent would read "moved" while the node left the frame it was arranged in.
+ expect(get(reparentNode(nodes, 'k', null), 'k').parentId).toBeUndefined()
+ expect(geometryArgsRefusal('move', { nodes: 'k', x: '10' })).toMatch(/takes it OUT of its frame/)
+ // `place` keeps the frame.
+ const placed = placeNodes(nodes, ['k'], { x: 10 })
+ expect(placed.ok && get(placed.nodes, 'k').parentId).toBe('g')
+ })
+})
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index f0a34d3d9..8c417a27e 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -24,7 +24,7 @@ import { agentAccountColor } from '@shared/agents/account-color'
import { boundAccountId } from '@shared/agents/account-binding'
import { agentEnvSnapshot } from '../lib/agentEnv'
import { uuid } from '@renderer/lib/uuid'
-import { expandRectToGrid, NODE_MIN_SIZES, snapNodeToGrid, type Rect } from '../lib/nodeSizing'
+import { COLLAPSED_HEIGHT, expandRectToGrid, NODE_MIN_SIZES, snapNodeToGrid, type Rect } from '../lib/nodeSizing'
import { claudeCliCapsNow, grokCliCapsNow } from './permissionMode'
import { ensureGrokTakenIds, grokTakenIdsNow } from './grokSessionIds'
import { mintFreeGrokSessionId } from '@shared/agents/grok-session-mint'
@@ -89,8 +89,9 @@ const SIMULATOR_SIZE = { width: 360, height: 760 }
/** Landscape and roomy: a whiteboard is for sketching, and the board pans and zooms inside itself. */
const WHITEBOARD_SIZE = { width: 900, height: 600 }
-/** Height of a node when collapsed (header only). */
-export const COLLAPSED_HEIGHT = 40
+// Height of a node when collapsed (header only). Defined in lib/nodeSizing (a light module, so the
+// control listing can report a collapsed node's size without importing this one) and re-exported.
+export { COLLAPSED_HEIGHT }
/** The node kinds that render a header-only collapsed state. Any other kind squashed to
* COLLAPSED_HEIGHT crushes its content (a group frame strands its children outside it), so
@@ -1519,6 +1520,7 @@ function groupBox(
}
import type { ArrangeLayout, GroupArrangeLayout } from '@shared/arrange-verb'
+import { ARRANGE_GAP_DEFAULT } from '@shared/arrange-verb'
export type { ArrangeLayout, GroupArrangeLayout }
export { GROUP_ARRANGE_LAYOUTS } from '@shared/arrange-verb'
@@ -1564,7 +1566,7 @@ export function arrangeNodes(
byId = new Map(nodes.map((nd) => [nd.id, nd]))
members = [...memberIds].flatMap((id) => byId.get(id) ?? [])
const layout = opts?.layout ?? 'grid'
- const gap = opts?.gap ?? 40
+ const gap = opts?.gap ?? ARRANGE_GAP_DEFAULT
const origin = opts?.origin ?? {
x: Math.min(...members.map((m) => m.position.x)),
y: Math.min(...members.map((m) => m.position.y))
@@ -1779,7 +1781,7 @@ export function arrangeByLineage(
nodes = restoreMaximizedWhere(nodes, (nd) => (nd.parentId ?? null) === containerId)
const topLevel = nodes.filter((nd) => (nd.parentId ?? null) === containerId)
- const gap = opts?.gap ?? 40
+ const gap = opts?.gap ?? ARRANGE_GAP_DEFAULT
const origin = opts?.origin ?? {
x: Math.min(...topLevel.map((nd) => nd.position.x)),
y: Math.min(...topLevel.map((nd) => nd.position.y))
@@ -1871,7 +1873,7 @@ export function tidyCanvas(
// Every unit moves, and a frame is packed at the size its (maximized) child inflated it to.
nodes = restoreMaximizedWhere(nodes, () => true)
const units = nodes.filter((nd) => !nd.parentId).sort(byReadingPosition)
- const gap = opts?.gap ?? 40
+ const gap = opts?.gap ?? ARRANGE_GAP_DEFAULT
const order = new Map(units.map((u, i) => [u.id, i]))
const unitOf = containerAncestors(nodes, null)
@@ -2245,6 +2247,206 @@ function clampToMinSize(node: CanvasNode, rect: { width: number; height: number
return { width: Math.max(rect.width, min.width), height: Math.max(rect.height, min.height) }
}
+/** What `resizeNodes` did to one node: the size it now has, and what the reply must say about it. */
+export interface ResizeApplied {
+ id: string
+ width: number
+ /** For a COLLAPSED node this is the height it will expand to — it still draws header-only. */
+ height: number
+ /** A requested axis was outside [kind minimum, NODE_SIZE_MAX] and was held to the bound. */
+ clamped: boolean
+ /** Header-only: the width applied now, the height was recorded for when it is expanded. */
+ collapsed: boolean
+ /** It was maximized, and went back to its own rect before the new size was applied. */
+ restored: boolean
+}
+
+export type ResizeOutcome =
+ | { ok: false; error: string }
+ | {
+ ok: true
+ /** The SAME array when nothing changed — the caller's signal to skip the write. */
+ nodes: CanvasNode[]
+ applied: ResizeApplied[]
+ /** Ids that name no node, skipped (the rest still applied, like `group`). */
+ unknown: string[]
+ }
+
+/**
+ * `resize` (issue #1288): give existing nodes an explicit size, one axis or both. Pure.
+ *
+ * - **Clamped, never refused, on size**: each REQUESTED axis is held between the kind's resizer
+ * minimum (`NODE_MIN_SIZES` — the smallest the user can drag it to; a programmatic resize bypasses
+ * the resizer, lib/nodeSizing.ts) and `NODE_SIZE_MAX` (the ceiling of the default-size setting,
+ * `terminalNodeSize`). An axis the caller did not name is kept as it is. `clamped` tells the reply
+ * to say what was actually applied.
+ * - **Exact, no grid snapping.** The caller named the pixels; a snapped size is one it did not ask
+ * for. (Align-to-grid is there for whoever wants it.)
+ * - **A group frame refuses the WHOLE call**, naming the frame: a frame is sized by what it holds
+ * (`fitGroupToChildren`), so any size given to it is undone by the next fit. Refusing beats
+ * resizing the rest — a refusal means nothing happened.
+ * - **Collapsed** (header-only): the width applies now; the height becomes `expandedHeight`, which
+ * is what the expand gives back and what `flowToNodeStates` persists for a collapsed node. The
+ * node keeps its collapsed look — expanding it is the user's call, not a side effect of sizing.
+ * - **Maximized**: restored to its own rect first, then sized. Left maximized, the explicit size
+ * would be undone by the next panel-pin refit (`refitMaximizedNode` re-claims the viewport for
+ * any node holding `premaxRect`), and the restore button would later teleport it back to the
+ * old rect. Same rule every layout pass follows (`restoreMaximizedWhere`).
+ * - The stale `measured` is dropped in the same tick (as `withNodeRect` does): `flowToNodeStates`
+ * prefers it, and a save racing the re-measure would persist the OLD size. A terminal's cols/rows
+ * follow through its own ResizeObserver — there is no second path to tmux here.
+ * - A framed node's frame — and every frame around it — re-fits (`fitAncestorChain`), or
+ * `extent:'parent'` clamps a child that outgrew its frame into an inverted range.
+ */
+export function resizeNodes(
+ nodes: CanvasNode[],
+ ids: readonly string[],
+ size: { width?: number; height?: number },
+ grid = 0
+): ResizeOutcome {
+ const wanted = [...new Set(ids)]
+ const byId = new Map(nodes.map((n) => [n.id, n]))
+ const unknown = wanted.filter((id) => !byId.has(id))
+ const known = wanted.filter((id) => byId.has(id))
+ if (known.length === 0) return { ok: false, error: 'resize: none of the given node ids exist' }
+ const frame = known.find((id) => byId.get(id)!.type === 'group')
+ if (frame) {
+ return {
+ ok: false,
+ error: `resize: ${frame} is a group frame — a frame sizes itself to what it holds; resize the nodes inside it, or \`arrange --group ${frame}\``
+ }
+ }
+ const set = new Set(known)
+ const wasMaximized = new Set(known.filter((id) => !!byId.get(id)!.data.premaxRect))
+ let next = restoreMaximizedWhere(nodes, (n) => set.has(n.id))
+ const applied: ResizeApplied[] = []
+ const touchedParents = new Set<string>()
+ let changed = wasMaximized.size > 0
+ next = next.map((n) => {
+ if (!set.has(n.id)) return n
+ const kind = n.type ?? 'terminal'
+ const min = NODE_MIN_SIZES[kind] ?? { width: 0, height: 0 }
+ const collapsed = !!n.data.collapsed
+ const curW = nodeW(n) || (n.style?.width as number) || 0
+ const curH = collapsed
+ ? ((n.data.expandedHeight as number | undefined) ?? COLLAPSED_FALLBACK_HEIGHT[kind] ?? 300)
+ : nodeH(n) || (n.style?.height as number) || 0
+ const hold = (v: number, lo: number, hi: number): number => Math.min(hi, Math.max(lo, v))
+ const width = size.width === undefined ? curW : hold(size.width, min.width, NODE_SIZE_MAX.width)
+ const height = size.height === undefined ? curH : hold(size.height, min.height, NODE_SIZE_MAX.height)
+ const clamped =
+ (size.width !== undefined && width !== size.width) || (size.height !== undefined && height !== size.height)
+ const restored = wasMaximized.has(n.id)
+ applied.push({ id: n.id, width, height, clamped, collapsed, restored })
+ if (samePx(curW, width) && samePx(curH, height)) return n
+ changed = true
+ if (n.parentId) touchedParents.add(n.parentId)
+ // Collapsed: it keeps drawing header-only, so only the width and the recorded expand height move.
+ const drawnH = collapsed ? ((n.height as number | undefined) ?? COLLAPSED_HEIGHT) : height
+ return {
+ ...n,
+ width,
+ height: drawnH,
+ style: { ...n.style, width, height: drawnH },
+ measured: undefined,
+ data: { ...n.data, expandedHeight: height }
+ }
+ })
+ if (!changed) return { ok: true, nodes, applied, unknown }
+ for (const parentId of touchedParents) next = fitAncestorChain(next, parentId, grid)
+ return { ok: true, nodes: next, applied, unknown }
+}
+
+/** Where `placeNodes` put one of the nodes it was asked to move, in ROOT (canvas) space. */
+export interface PlaceApplied {
+ id: string
+ x: number
+ y: number
+ /** It was maximized, and went back to its own size before it was placed. */
+ restored: boolean
+}
+
+export type PlaceOutcome =
+ | { ok: false; error: string }
+ | {
+ ok: true
+ /** The SAME array when nothing moved — the caller's signal to skip the write. */
+ nodes: CanvasNode[]
+ placed: PlaceApplied[]
+ unknown: string[]
+ /** Listed ids that rode along inside a listed frame instead of being moved twice. */
+ carried: string[]
+ }
+
+/**
+ * `place` (issue #1288): put nodes at canvas coordinates, or shift them by an offset. Pure.
+ *
+ * - **Root space in, parent kept.** `x`/`y` are canvas coordinates — the numbers `list` reports —
+ * and a framed node STAYS in its frame: the root-space delta is applied to its parent-relative
+ * position (the two differ by the parent chain's origin, which is not moving), and its frame plus
+ * every frame around it re-fit to hold it (`fitAncestorChain`, which keeps root positions fixed —
+ * so the node ends exactly where it was put). That is why this is not `move --x`: `move` without
+ * `--group` means "to the top level".
+ * - **Several ids with `x`/`y` move as ONE block**: the set keeps its own shape and its bounding
+ * box's top-left lands on (x, y). It is the only reading in which the call is a placement rather
+ * than a collision — every node at the same point is not a layout — and it makes "pin this
+ * arranged block to the corner" one call. With `dx`/`dy` each node simply shifts.
+ * - **A frame carries its subtree**: a listed frame moves with everything in it, and a listed
+ * descendant of a listed frame is NOT moved a second time (`selectedRootIds`) — it is reported as
+ * `carried`.
+ * - **Maximized** nodes in what moves are restored first (same reason as `resizeNodes`: left
+ * maximized, the next panel-pin refit would put them back over the viewport). Collapsed nodes need
+ * nothing: placement does not touch a size.
+ * - **Exact, no grid snapping** — only a frame's own re-fit snaps (to the grid, as every frame does),
+ * and that never moves what it holds.
+ */
+export function placeNodes(
+ nodes: CanvasNode[],
+ ids: readonly string[],
+ to: { x?: number; y?: number; dx?: number; dy?: number },
+ grid = 0
+): PlaceOutcome {
+ const wanted = [...new Set(ids)]
+ const known = wanted.filter((id) => nodes.some((n) => n.id === id))
+ const unknown = wanted.filter((id) => !known.includes(id))
+ if (known.length === 0) return { ok: false, error: 'place: none of the given node ids exist' }
+ const roots = selectedRootIds(nodes, known)
+ const rootSet = new Set(roots)
+ const carried = known.filter((id) => !rootSet.has(id))
+ const moves = (n: CanvasNode): boolean => rootSet.has(n.id) || roots.some((r) => isDescendant(nodes, n.id, r))
+ const wasMaximized = new Set(roots.filter((id) => !!nodes.find((n) => n.id === id)!.data.premaxRect))
+ const restoredAny = nodes.some((n) => !!n.data.premaxRect && moves(n))
+ let next = restoreMaximizedWhere(nodes, moves)
+ const at = new Map(roots.map((id) => [id, rootPosition(next.find((n) => n.id === id)!, next)]))
+ let dx = to.dx ?? 0
+ let dy = to.dy ?? 0
+ if (to.x !== undefined || to.y !== undefined) {
+ const xs = [...at.values()].map((p) => p.x)
+ const ys = [...at.values()].map((p) => p.y)
+ dx = to.x === undefined ? 0 : to.x - Math.min(...xs)
+ dy = to.y === undefined ? 0 : to.y - Math.min(...ys)
+ }
+ const placedAt = (out: CanvasNode[]): PlaceApplied[] =>
+ roots.map((id) => {
+ const p = rootPosition(out.find((n) => n.id === id)!, out)
+ return { id, x: p.x, y: p.y, restored: wasMaximized.has(id) }
+ })
+ if (dx === 0 && dy === 0) {
+ return restoredAny
+ ? { ok: true, nodes: next, placed: placedAt(next), unknown, carried }
+ : { ok: true, nodes, placed: placedAt(nodes), unknown, carried }
+ }
+ const parents = new Set<string>()
+ next = next.map((n) => {
+ if (!rootSet.has(n.id)) return n
+ if (n.parentId) parents.add(n.parentId)
+ // `+ 0` normalizes a -0 that would otherwise ride out to project.json.
+ return { ...n, position: { x: n.position.x + dx + 0, y: n.position.y + dy + 0 } }
+ })
+ for (const parentId of parents) next = fitAncestorChain(next, parentId, grid)
+ return { ok: true, nodes: next, placed: placedAt(next), unknown, carried }
+}
+
/**
* The shared placement core: put `node` at the ROOT-space `rect` (converted to parent-relative),
* patch its data, and re-fit the ancestor frames in the same transform — `extent:'parent'` would
diff --git a/src/server/control-unsupported.test.ts b/src/server/control-unsupported.test.ts
index bf8344ae1..3cd5126df 100644
--- a/src/server/control-unsupported.test.ts
+++ b/src/server/control-unsupported.test.ts
@@ -483,6 +483,26 @@ describe('the enabled Server Edition handler parses and dispatches the v1 surfac
expect(reply.message).toContain('do not retry')
}
})
+
+ // They run in the DESKTOP renderer's dispatch. This edition's browser bridge never subscribes to
+ // `onAgentControl`, and its headless handler serves no layout verb (`arrange`, `move`, `align`,
+ // `list` included), so they take the same named permanent refusal — never "Unknown verb", which
+ // reads like a typo to retry, and never a dropped flag answered ok.
+ it('refuses the geometry verbs by name, permanently (issue #1288)', async () => {
+ const handler = createServerEditionControlHandler(actions())
+ const calls: Array<[string, Record<string, string>]> = [
+ ['resize', { nodes: 'a', width: '540' }],
+ ['place', { nodes: 'a', x: '0', y: '0' }],
+ ['list', { geometry: 'on' }],
+ ['arrange', { nodes: 'a,b', gap: '0' }]
+ ]
+ for (const [verb, args] of calls) {
+ const reply = await handler({ verb, nodeId: 'term-source', args, verified: true })
+ expect(reply, verb).toMatchObject({ ok: false, error: CONTROL_UNSUPPORTED_ERROR })
+ expect(reply.message, verb).toContain(`"${verb}"`)
+ expect(reply.message, verb).toContain('do not retry')
+ }
+ })
})
/**
diff --git a/src/shared/arrange-verb.test.ts b/src/shared/arrange-verb.test.ts
index b2ac2953a..9392b162c 100644
--- a/src/shared/arrange-verb.test.ts
+++ b/src/shared/arrange-verb.test.ts
@@ -1,10 +1,14 @@
import { describe, it, expect } from 'vitest'
import {
+ ARRANGE_GAP_DEFAULT,
+ ARRANGE_GAP_MAX,
ARRANGE_LAYOUTS,
GROUP_ARRANGE_LAYOUTS,
arrangeArgsRefusal,
+ arrangeGapGuidanceLines,
arrangeGroupGuidanceLines,
isTopLevelGroupArg,
+ parseArrangeGap,
TOP_ARRANGE_LAYOUTS
} from './arrange-verb'
@@ -83,3 +87,50 @@ describe('arrangeGroupGuidanceLines', () => {
expect(text).toMatch(/opened-by only; an\s+`--after` wait does not move anything/)
})
})
+
+// Issue #1288: the gap was always a parameter of every packing (`opts.gap`), but the verb never read
+// the flag, so an agent could not lay sessions out touching. The gate decides the SHAPE here, for
+// main, core's parser and the renderer belt at once.
+describe('arrange --gap', () => {
+ it('reads a whole number from 0 (touching) to the maximum; absent keeps each transform default', () => {
+ expect(parseArrangeGap(undefined)).toEqual({ gap: undefined })
+ expect(parseArrangeGap('0')).toEqual({ gap: 0 })
+ expect(parseArrangeGap('8')).toEqual({ gap: 8 })
+ expect(parseArrangeGap(` ${ARRANGE_GAP_MAX} `)).toEqual({ gap: ARRANGE_GAP_MAX })
+ })
+
+ it('refuses above the maximum BY NAME instead of clamping', () => {
+ const r = parseArrangeGap(String(ARRANGE_GAP_MAX + 1))
+ expect(r).toEqual({
+ error: `arrange: --gap ${ARRANGE_GAP_MAX + 1} is wider than the ${ARRANGE_GAP_MAX} px maximum — nothing was arranged`
+ })
+ })
+
+ it('refuses a negative, fractional, empty or non-numeric gap — never "overlap a little"', () => {
+ // '' is what the shim sends for a valueless `--gap`.
+ for (const raw of ['-8', '8.5', '', ' ', 'tight', '8px', '0x10']) {
+ expect(parseArrangeGap(raw), raw).toEqual({
+ error: `arrange: --gap must be a whole number of pixels from 0 to ${ARRANGE_GAP_MAX} (got "${raw}")`
+ })
+ }
+ })
+
+ it('is checked for every form — --nodes, --group <frameId> and --group top', () => {
+ const forms: Record<string, string>[] = [{ nodes: 'a,b' }, { group: 'g1' }, { group: 'top' }]
+ for (const form of forms) {
+ expect(arrangeArgsRefusal({ ...form, gap: '0' }), JSON.stringify(form)).toBeNull()
+ expect(arrangeArgsRefusal({ ...form, gap: '-1' }), JSON.stringify(form)).toMatch(/--gap must be a whole number/)
+ expect(arrangeArgsRefusal({ ...form, gap: '9999' }), JSON.stringify(form)).toMatch(/px maximum/)
+ }
+ })
+
+ it('the agent text states the numbers the parser checks', () => {
+ const text = arrangeGapGuidanceLines().join('\n')
+ expect(text).toContain(`from 0 (touching) to ${ARRANGE_GAP_MAX}; omitted, it is ${ARRANGE_GAP_DEFAULT}`)
+ expect(text).toContain(`Above ${ARRANGE_GAP_MAX} the call is refused, not\n clamped`)
+ expect(text).toMatch(/NOT a frame's inner padding/)
+ // And it rides along with the rest of `arrange` into both generated bodies.
+ expect(arrangeGroupGuidanceLines().join('\n')).toContain(text)
+ expect(arrangeGroupGuidanceLines().join('\n')).toContain('[--cols N] [--gap px]')
+ })
+})
diff --git a/src/shared/arrange-verb.ts b/src/shared/arrange-verb.ts
index 8bd95b05a..5465c4369 100644
--- a/src/shared/arrange-verb.ts
+++ b/src/shared/arrange-verb.ts
@@ -26,6 +26,37 @@ export type GroupArrangeLayout = (typeof GROUP_ARRANGE_LAYOUTS)[number]
export const TOP_ARRANGE_LAYOUTS = ['tidy', 'lineage'] as const
export type TopArrangeLayout = (typeof TOP_ARRANGE_LAYOUTS)[number]
+/** The space every packing leaves between two items when the caller names none, in px. */
+export const ARRANGE_GAP_DEFAULT = 40
+
+/**
+ * The widest `arrange --gap` accepted, in px: ten times the default. Wider than that is not
+ * spacing, it is two separate layouts, and a typo (`--gap 4000` for `40`) should come back as a
+ * refusal rather than as a canvas scattered across a screen and a half. Above it the call is
+ * REFUSED by name, never clamped — a clamped gap is a layout the caller did not ask for and cannot
+ * see in the reply.
+ */
+export const ARRANGE_GAP_MAX = 400
+
+/**
+ * `--gap` as a number of px, or the sentence that refuses it. A whole number from 0 (items
+ * touching) to `ARRANGE_GAP_MAX`; absent = `undefined`, which every transform reads as its
+ * `ARRANGE_GAP_DEFAULT`. A negative gap is refused rather than read as "overlap a little": every
+ * packing here promises no overlap.
+ */
+export function parseArrangeGap(raw: string | undefined): { gap: number | undefined } | { error: string } {
+ if (raw === undefined) return { gap: undefined }
+ const s = raw.trim()
+ if (!/^\d+$/.test(s)) {
+ return { error: `arrange: --gap must be a whole number of pixels from 0 to ${ARRANGE_GAP_MAX} (got "${raw}")` }
+ }
+ const gap = Number(s)
+ if (gap > ARRANGE_GAP_MAX) {
+ return { error: `arrange: --gap ${gap} is wider than the ${ARRANGE_GAP_MAX} px maximum — nothing was arranged` }
+ }
+ return { gap }
+}
+
/**
* `--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.
@@ -56,6 +87,9 @@ export function arrangeArgsRefusal(args: Record<string, string>): string | null
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'
}
+ // Every form packs with a gap, so `--gap` is checked once, before the forms split.
+ const gap = parseArrangeGap(args.gap)
+ if ('error' in gap) return gap.error
const layout = args.layout
if (hasGroup && isTopLevelGroupArg(args.group)) {
if (layout && !(TOP_ARRANGE_LAYOUTS as readonly string[]).includes(layout)) {
@@ -72,6 +106,19 @@ export function arrangeArgsRefusal(args: Record<string, string>): string | null
return null
}
+/**
+ * The `--gap` paragraph, with its numbers taken from the constants `parseArrangeGap` checks. Part
+ * of `arrangeGroupGuidanceLines`, so it lands in both generated bodies with the rest of `arrange`.
+ */
+export function arrangeGapGuidanceLines(): string[] {
+ return [
+ `- \`--gap <px>\` (every \`arrange\` form) is the space left between two packed items: a whole number`,
+ ` from 0 (touching) to ${ARRANGE_GAP_MAX}; omitted, it is ${ARRANGE_GAP_DEFAULT}. Above ${ARRANGE_GAP_MAX} the call is refused, not`,
+ ' clamped. It is applied exactly, grid snapping on or off. It is NOT a frame\'s inner padding: a',
+ ' frame still keeps its margin around what it holds.'
+ ]
+}
+
/**
* 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
@@ -79,19 +126,20 @@ export function arrangeArgsRefusal(args: Record<string, string>): string | null
*/
export function arrangeGroupGuidanceLines(): string[] {
return [
- `- \`arrange --group <frameId> [--layout ${GROUP_ARRANGE_LAYOUTS.join('|')}] [--cols N]\` — organize a frame by`,
+ `- \`arrange --group <frameId> [--layout ${GROUP_ARRANGE_LAYOUTS.join('|')}] [--cols N] [--gap px]\` — 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.',
- `- \`arrange --group top [--layout ${TOP_ARRANGE_LAYOUTS.join('|')}]\` — tidy the WHOLE canvas, exactly as the`,
+ `- \`arrange --group top [--layout ${TOP_ARRANGE_LAYOUTS.join('|')}] [--gap px]\` — 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.'
+ ' after spawning teams, not after every open.',
+ ...arrangeGapGuidanceLines()
]
}
diff --git a/src/shared/control-off-screen.ts b/src/shared/control-off-screen.ts
index 06465d11f..33800fc3d 100644
--- a/src/shared/control-off-screen.ts
+++ b/src/shared/control-off-screen.ts
@@ -212,7 +212,8 @@ export function answersOffCanvas(verb: string): boolean {
* to read `activeProjectId`, which off canvas was a second bug hiding behind the first: after
* the travel the two projects were the same, so the wrong read was never wrong in practice.
*
- * - `group` / `ungroup` / `move` / `arrange` / `align` lay out from persisted sizes (below).
+ * - `group` / `ungroup` / `move` / `arrange` / `align` / `resize` / `place` lay out from
+ * persisted sizes (below).
*
* Deliberately NOT here — and these REFUSE rather than travel, see `offScreenDisposition`: the
* verbs that arm a graph, park a live terminal, read the worktree store or drive a webview. A refusal an agent can act on is strictly better than hijacking the human's
@@ -230,6 +231,11 @@ const STORED_NODE_VERBS: ReadonlySet<string> = new Set([
'move',
'arrange',
'align',
+ // `resize` / `place` (issue #1288) are the same kind of write: pure transforms over the stored
+ // nodes, geometry-only mutations back (`geometryMutations`). An orchestrator rebuilding a layout
+ // after replacing a session is typically NOT the project the user is looking at.
+ 'resize',
+ 'place',
'write',
'close',
'run',
diff --git a/src/shared/geometry-verbs.test.ts b/src/shared/geometry-verbs.test.ts
new file mode 100644
index 000000000..d154f408b
--- /dev/null
+++ b/src/shared/geometry-verbs.test.ts
@@ -0,0 +1,166 @@
+import { describe, it, expect } from 'vitest'
+import { NODE_SIZE_MAX } from './default-node-size'
+import {
+ LIST_GEOMETRY_VALUES,
+ PLACE_COORD_MAX,
+ geometryArgsRefusal,
+ geometryGuidanceLines,
+ moveArgsRefusal,
+ listGeometryRequested,
+ parseListGeometry,
+ parsePlaceArgs,
+ parseResizeArgs
+} from './geometry-verbs'
+
+describe('resize: the flag shape', () => {
+ it('reads --nodes and one axis or both', () => {
+ expect(parseResizeArgs({ nodes: 'a, b,', width: '540' })).toEqual({ ids: ['a', 'b'], width: 540 })
+ expect(parseResizeArgs({ nodes: 'a', height: '480' })).toEqual({ ids: ['a'], height: 480 })
+ expect(parseResizeArgs({ nodes: 'a', width: '540', height: '480' })).toEqual({ ids: ['a'], width: 540, height: 480 })
+ })
+
+ it('does NOT range-check the size — the canvas clamps it to the kind and reports it', () => {
+ // A value above the canvas maximum is a size the transform holds to NODE_SIZE_MAX and SAYS so.
+ expect(parseResizeArgs({ nodes: 'a', width: String(NODE_SIZE_MAX.width * 10) })).toEqual({
+ ids: ['a'],
+ width: NODE_SIZE_MAX.width * 10
+ })
+ })
+
+ it('refuses what no canvas could act on', () => {
+ expect(parseResizeArgs({ width: '10' })).toEqual({ error: 'resize requires --nodes <id,id>' })
+ expect(parseResizeArgs({ nodes: ' , ' , width: '10' })).toEqual({ error: 'resize requires --nodes <id,id>' })
+ expect(parseResizeArgs({ nodes: 'a' })).toEqual({ error: 'resize requires --width <px>, --height <px>, or both' })
+ for (const raw of ['0', '-5', '1.5', '', 'wide', '1e3', '99999999999999999999']) {
+ expect(parseResizeArgs({ nodes: 'a', width: raw }), raw).toEqual({
+ error: `resize: --width must be a whole number of pixels above 0 (got "${raw}")`
+ })
+ }
+ })
+
+ it('refuses an unknown flag by name — a dropped `--heigth` would read as success', () => {
+ expect(parseResizeArgs({ nodes: 'a', width: '500', heigth: '400' })).toEqual({ error: 'resize: unknown flag --heigth' })
+ // The spelling the issue used, answered with the one that works.
+ expect(parseResizeArgs({ node: 'a', width: '500' })).toEqual({
+ error: 'resize: takes --nodes <id,id> (plural, like arrange and move), not --node'
+ })
+ })
+})
+
+describe('place: the flag shape', () => {
+ it('reads absolute (one axis or both) or relative coordinates, negatives included', () => {
+ expect(parsePlaceArgs({ nodes: 'a', x: '0', y: '-120' })).toEqual({ ids: ['a'], x: 0, y: -120 })
+ expect(parsePlaceArgs({ nodes: 'a', x: '40' })).toEqual({ ids: ['a'], x: 40 })
+ expect(parsePlaceArgs({ nodes: 'a,b', dx: '-8', dy: '16' })).toEqual({ ids: ['a', 'b'], dx: -8, dy: 16 })
+ // A typed "-0" is 0, not a -0 that would ride out to project.json.
+ expect(Object.is((parsePlaceArgs({ nodes: 'a', x: '-0' }) as { x: number }).x, 0)).toBe(true)
+ })
+
+ it('refuses mixing where with how-far, and a call naming neither', () => {
+ expect(parsePlaceArgs({ nodes: 'a', x: '1', dy: '2' })).toEqual({
+ error: 'place takes --x/--y (where) or --dx/--dy (how far), not both'
+ })
+ expect(parsePlaceArgs({ nodes: 'a' })).toMatchObject({ error: expect.stringMatching(/^place requires --x\/--y/) })
+ expect(parsePlaceArgs({ x: '1' })).toEqual({ error: 'place requires --nodes <id,id>' })
+ })
+
+ it('refuses a coordinate that is not a whole number, or beyond the bound, by name', () => {
+ for (const raw of ['1.5', '', '1e3', 'left', '--3']) {
+ expect(parsePlaceArgs({ nodes: 'a', x: raw }), raw).toEqual({
+ error: `place: --x must be a whole number of pixels (got "${raw}")`
+ })
+ }
+ expect(parsePlaceArgs({ nodes: 'a', dy: String(-(PLACE_COORD_MAX + 1)) })).toEqual({
+ error: `place: --dy ${-(PLACE_COORD_MAX + 1)} is beyond ±${PLACE_COORD_MAX} px — nothing was placed`
+ })
+ expect(parsePlaceArgs({ nodes: 'a', x: String(PLACE_COORD_MAX) })).toEqual({ ids: ['a'], x: PLACE_COORD_MAX })
+ })
+
+ it('refuses an unknown flag by name', () => {
+ expect(parsePlaceArgs({ nodes: 'a', x: '1', group: 'g1' })).toEqual({ error: 'place: unknown flag --group' })
+ expect(parsePlaceArgs({ node: 'a', x: '1' })).toMatchObject({ error: expect.stringContaining('not --node') })
+ })
+})
+
+describe('list --geometry', () => {
+ it('takes on or off, and is off when absent', () => {
+ expect(parseListGeometry({})).toEqual({ geometry: false })
+ expect(parseListGeometry({ geometry: 'on' })).toEqual({ geometry: true })
+ expect(parseListGeometry({ geometry: ' OFF ' })).toEqual({ geometry: false })
+ })
+
+ it('refuses a valueless flag rather than guessing: every flag takes a value (the SSH shim-loop rule)', () => {
+ expect(parseListGeometry({ geometry: '' })).toEqual({ error: 'list: --geometry takes on or off (got "")' })
+ expect(parseListGeometry({ geometry: 'yes' })).toEqual({ error: 'list: --geometry takes on or off (got "yes")' })
+ })
+
+ it('listGeometryRequested is true only for on', () => {
+ expect(listGeometryRequested({ geometry: 'on' })).toBe(true)
+ expect(listGeometryRequested({ geometry: 'off' })).toBe(false)
+ expect(listGeometryRequested({})).toBe(false)
+ })
+})
+
+describe('move refuses coordinates and sizes', () => {
+ // The issue proposed `move --node <id> --x <n> --y <n>`. Without `--group`, `move` means "out of
+ // every frame": that call would pull a framed node to the top level and ignore the `--x`, and
+ // answer ok. The transform half of that is pinned in workspace.geometry.test.ts.
+ it('names the verb that does what was asked', () => {
+ expect(moveArgsRefusal({ nodes: 'a' })).toBeNull()
+ expect(moveArgsRefusal({ nodes: 'a', group: 'g1' })).toBeNull()
+ for (const flag of ['x', 'y', 'dx', 'dy']) {
+ const r = moveArgsRefusal({ nodes: 'a', [flag]: '10' })
+ expect(r, flag).toContain(`move: --${flag} is not a move flag`)
+ expect(r, flag).toContain('takes it OUT of its frame')
+ expect(r, flag).toContain(`place --nodes <id> --${flag} <n>`)
+ }
+ expect(moveArgsRefusal({ nodes: 'a', width: '10' })).toContain('resize --nodes <id> --width <px>')
+ })
+})
+
+describe('geometryArgsRefusal: one gate per verb', () => {
+ it('routes each verb to its own parser and leaves the rest alone', () => {
+ expect(geometryArgsRefusal('resize', { nodes: 'a' })).toMatch(/^resize requires --width/)
+ expect(geometryArgsRefusal('place', { nodes: 'a' })).toMatch(/^place requires/)
+ expect(geometryArgsRefusal('list', { geometry: 'maybe' })).toMatch(/^list: --geometry/)
+ expect(geometryArgsRefusal('move', { nodes: 'a', x: '1' })).toMatch(/^move: --x/)
+ expect(geometryArgsRefusal('list', {})).toBeNull()
+ expect(geometryArgsRefusal('resize', { nodes: 'a', width: '300' })).toBeNull()
+ // Not its verbs: `arrange --gap` is `arrangeArgsRefusal`'s, and `open-terminal` has no width.
+ expect(geometryArgsRefusal('arrange', { nodes: 'a', gap: '-1' })).toBeNull()
+ expect(geometryArgsRefusal('open-terminal', { width: 'x' })).toBeNull()
+ })
+})
+
+describe('geometryGuidanceLines', () => {
+ const text = geometryGuidanceLines().join('\n')
+
+ it('renders every number from the constant the code checks', () => {
+ expect(text).toContain(`${NODE_SIZE_MAX.width}×${NODE_SIZE_MAX.height}`)
+ expect(text).toContain(`within ±${PLACE_COORD_MAX}`)
+ expect(text).toContain(`list --geometry ${LIST_GEOMETRY_VALUES.join('|')}`)
+ })
+
+ it('states the contract an agent builds a layout on', () => {
+ expect(text).toContain('resize --nodes <id,id> [--width <px>] [--height <px>]')
+ expect(text).toContain('place --nodes <id> --x <n> --y <n>')
+ expect(text).toContain('place --nodes <id,id> --dx <n> --dy <n>')
+ expect(text).toMatch(/JSON result rows ALWAYS carry `x`, `y`, `width`, `height`\s+and `parent`/)
+ expect(text).toMatch(/group frame\s+is refused/)
+ expect(text).toMatch(/COLLAPSED node keeps its header-only look/)
+ expect(text).toMatch(/MAXIMIZED node is restored first/)
+ expect(text).toMatch(/framed node STAYS in its frame/)
+ expect(text).toMatch(/move as ONE block/)
+ expect(text).toMatch(/`move` takes none of these flags/)
+ })
+
+ it('carries the worked example the issue needs: two tight columns of four', () => {
+ expect(text).toContain('resize --nodes a,b,c,d,e,f,g,h --width 540 --height 480')
+ expect(text).toContain('arrange --nodes a,e,b,f,c,g,d,h --layout grid --cols 2 --gap 0')
+ expect(text).toContain('place --nodes a,b,c,d,e,f,g,h --x 0 --y 0')
+ // Every call in it passes its own gate.
+ expect(geometryArgsRefusal('resize', { nodes: 'a,b,c,d,e,f,g,h', width: '540', height: '480' })).toBeNull()
+ expect(geometryArgsRefusal('place', { nodes: 'a,b,c,d,e,f,g,h', x: '0', y: '0' })).toBeNull()
+ expect(geometryArgsRefusal('list', { geometry: 'on' })).toBeNull()
+ })
+})
diff --git a/src/shared/geometry-verbs.ts b/src/shared/geometry-verbs.ts
new file mode 100644
index 000000000..31c95af7a
--- /dev/null
+++ b/src/shared/geometry-verbs.ts
@@ -0,0 +1,227 @@
+/**
+ * The geometry half of canvas control (issue #1288): `resize`, `place` and `list --geometry` — the
+ * verbs that let an agent rebuild an exact layout (two tight columns of four sessions filling a
+ * vertical monitor, say) every time a session is replaced, instead of a human dragging windows.
+ *
+ * In `src/shared` for the same reason as `arrange-verb.ts`: the shape gate has three readers that
+ * cannot import each other — desktop main refuses a malformed call before it is forwarded (that
+ * handler never runs `parseControlRequest`), core's `parseControlRequest` (the Server Edition's
+ * parser), and the renderer's dispatch belt — and the generated agent docs render their numbers
+ * from the constants here. A limit typed once per reader is how the docs come to advertise a value
+ * the parser refuses.
+ *
+ * What is decided HERE is only what no canvas could act on: a missing flag, a value that is not a
+ * whole number, a flag the verb does not read. Whether an id exists, is a frame, is collapsed or
+ * is maximized is the canvas's question (`resizeNodes` / `placeNodes` in renderer/state/workspace).
+ *
+ * EVERY FLAG TAKES A VALUE — the SSH shim-loop rule: an older shim on an SSH host takes the token
+ * after any flag as its value, so a valueless `--geometry` would swallow whatever follows it.
+ */
+
+import { NODE_SIZE_MAX } from './default-node-size'
+
+/**
+ * The farthest from the canvas origin `place` puts anything, in px, on either axis. A canvas has no
+ * edge, so this is not a bound on the canvas: it is a bound on a TYPO — 100 000 px is over forty
+ * 2400 px-wide nodes side by side, and a node sent past it would take a zoom-out to find. Refused
+ * above it, never clamped (a clamped coordinate is a placement the caller did not ask for).
+ */
+export const PLACE_COORD_MAX = 100_000
+
+/** The values `list --geometry` reads. Absent = off, so the default text answer stays one short line per node. */
+export const LIST_GEOMETRY_VALUES = ['on', 'off'] as const
+
+/** The flags each geometry verb reads. Anything else is refused by name (#539: a silently dropped
+ * `--heigth 400` is indistinguishable from success to the agent that typed it). */
+const RESIZE_FLAGS: ReadonlySet<string> = new Set(['nodes', 'width', 'height'])
+const PLACE_FLAGS: ReadonlySet<string> = new Set(['nodes', 'x', 'y', 'dx', 'dy'])
+
+/** The coordinate/size flags `move` must refuse — see `moveArgsRefusal`. */
+const MOVE_GEOMETRY_FLAGS = ['x', 'y', 'dx', 'dy', 'width', 'height'] as const
+
+/** The ids a `--nodes` list names, in order, blanks dropped. */
+export function geometryIds(raw: string | undefined): string[] {
+ return (raw ?? '').split(',').map((s) => s.trim()).filter(Boolean)
+}
+
+/** A whole, positive px count, or the refusal. The ceiling is NOT checked here: `resize` clamps to
+ * the kind's minimum and the canvas maximum and reports what it applied (`resizeNodes`). */
+function parseSize(flag: 'width' | 'height', raw: string): number | string {
+ const s = raw.trim()
+ const n = /^\d+$/.test(s) ? Number(s) : NaN
+ if (!Number.isSafeInteger(n) || n <= 0) {
+ return `resize: --${flag} must be a whole number of pixels above 0 (got "${raw}")`
+ }
+ return n
+}
+
+/** A whole, signed px coordinate within ±PLACE_COORD_MAX, or the refusal. */
+function parseCoord(flag: 'x' | 'y' | 'dx' | 'dy', raw: string): number | string {
+ const s = raw.trim()
+ if (!/^-?\d+$/.test(s)) return `place: --${flag} must be a whole number of pixels (got "${raw}")`
+ const n = Number(s) + 0 // `+ 0` turns a typed "-0" into 0
+ if (Math.abs(n) > PLACE_COORD_MAX) {
+ return `place: --${flag} ${n} is beyond ±${PLACE_COORD_MAX} px — nothing was placed`
+ }
+ return n
+}
+
+function unknownFlag(verb: string, args: Record<string, string>, allowed: ReadonlySet<string>): string | null {
+ const unknown = Object.keys(args).find((key) => !allowed.has(key))
+ if (unknown === undefined) return null
+ if (unknown === 'node') return `${verb}: takes --nodes <id,id> (plural, like arrange and move), not --node`
+ return `${verb}: unknown flag --${unknown}`
+}
+
+export interface ResizeRequest {
+ ids: string[]
+ width?: number
+ height?: number
+}
+
+/** `resize --nodes <id,id> [--width <px>] [--height <px>]`, parsed, or the sentence that refuses it. */
+export function parseResizeArgs(args: Record<string, string>): ResizeRequest | { error: string } {
+ const flag = unknownFlag('resize', args, RESIZE_FLAGS)
+ if (flag) return { error: flag }
+ const ids = geometryIds(args.nodes)
+ if (ids.length === 0) return { error: 'resize requires --nodes <id,id>' }
+ if (args.width === undefined && args.height === undefined) {
+ return { error: 'resize requires --width <px>, --height <px>, or both' }
+ }
+ const out: ResizeRequest = { ids }
+ for (const axis of ['width', 'height'] as const) {
+ if (args[axis] === undefined) continue
+ const v = parseSize(axis, args[axis])
+ if (typeof v === 'string') return { error: v }
+ out[axis] = v
+ }
+ return out
+}
+
+export interface PlaceRequest {
+ ids: string[]
+ /** Absolute: where the top-left goes, in canvas (root) coordinates — the numbers `list` reports. */
+ x?: number
+ y?: number
+ /** Relative: how far to shift, in px. Never mixed with `x`/`y` (`parsePlaceArgs` refuses it). */
+ dx?: number
+ dy?: number
+}
+
+/** `place --nodes <id,id> (--x <n> | --y <n> | --dx <n> | --dy <n>)…`, parsed, or the refusal. */
+export function parsePlaceArgs(args: Record<string, string>): PlaceRequest | { error: string } {
+ const flag = unknownFlag('place', args, PLACE_FLAGS)
+ if (flag) return { error: flag }
+ const ids = geometryIds(args.nodes)
+ if (ids.length === 0) return { error: 'place requires --nodes <id,id>' }
+ const absolute = args.x !== undefined || args.y !== undefined
+ const relative = args.dx !== undefined || args.dy !== undefined
+ if (!absolute && !relative) {
+ return { error: 'place requires --x/--y (canvas coordinates, as `list` reports them) or --dx/--dy (an offset)' }
+ }
+ // Two answers to "where": a silent precedence would be a half-honoured call the agent cannot see.
+ if (absolute && relative) {
+ return { error: 'place takes --x/--y (where) or --dx/--dy (how far), not both' }
+ }
+ const out: PlaceRequest = { ids }
+ for (const axis of ['x', 'y', 'dx', 'dy'] as const) {
+ if (args[axis] === undefined) continue
+ const v = parseCoord(axis, args[axis])
+ if (typeof v === 'string') return { error: v }
+ out[axis] = v
+ }
+ return out
+}
+
+/** Whether `list` was asked for its geometry, or the refusal for a value it does not read. */
+export function parseListGeometry(args: Record<string, string>): { geometry: boolean } | { error: string } {
+ const raw = args.geometry
+ if (raw === undefined) return { geometry: false }
+ const v = raw.trim().toLowerCase()
+ if (!(LIST_GEOMETRY_VALUES as readonly string[]).includes(v)) {
+ return { error: `list: --geometry takes ${LIST_GEOMETRY_VALUES.join(' or ')} (got "${raw}")` }
+ }
+ return { geometry: v === 'on' }
+}
+
+/** `list --geometry on`, for a request the gate already passed — a refused value never gets here. */
+export function listGeometryRequested(args: Record<string, string>): boolean {
+ const r = parseListGeometry(args)
+ return 'geometry' in r && r.geometry
+}
+
+/**
+ * `move` with a coordinate or a size flag, refused by name. The issue that asked for placement
+ * spelled it `move --node <id> --x <n> --y <n>`, and that is the one spelling that must NOT work:
+ * `move` without `--group` means "out of every frame, to the top level", so `move --nodes a --x 10`
+ * would pull a framed node out of its frame and then ignore the `--x` — a structural change nobody
+ * asked for, reported as a success. `place` keeps the parent.
+ */
+export function moveArgsRefusal(args: Record<string, string>): string | null {
+ const flag = MOVE_GEOMETRY_FLAGS.find((f) => args[f] !== undefined)
+ if (flag === undefined) return null
+ return flag === 'width' || flag === 'height'
+ ? `move: --${flag} is not a move flag — move only changes which frame a node is in; size it with \`resize --nodes <id> --${flag} <px>\``
+ : `move: --${flag} is not a move flag — move only changes which frame a node is in (and without --group takes it OUT of its frame); put it at coordinates with \`place --nodes <id> --${flag} <n>\`, which keeps its frame`
+}
+
+/**
+ * The shape gate for every geometry-bearing verb, or `null`. `arrange --gap` is checked by
+ * `arrangeArgsRefusal` with the rest of `arrange`'s flags; this covers the verbs this file owns.
+ */
+export function geometryArgsRefusal(verb: string, args: Record<string, string>): string | null {
+ if (verb === 'resize') {
+ const r = parseResizeArgs(args)
+ return 'error' in r ? r.error : null
+ }
+ if (verb === 'place') {
+ const r = parsePlaceArgs(args)
+ return 'error' in r ? r.error : null
+ }
+ if (verb === 'list') {
+ const r = parseListGeometry(args)
+ return 'error' in r ? r.error : null
+ }
+ if (verb === 'move') return moveArgsRefusal(args)
+ return null
+}
+
+/**
+ * The agent-facing description of the geometry verbs, rendered into BOTH generated bodies (the
+ * SKILL.md and the marker block) with every number taken from the constants the parser and the
+ * transforms check — so the two bodies cannot describe different products, and neither can name a
+ * limit the code does not hold.
+ */
+export function geometryGuidanceLines(): string[] {
+ return [
+ `- \`list --geometry ${LIST_GEOMETRY_VALUES.join('|')}\` — the text form adds each node's place and size:`,
+ ' `@ x,y w×h` in canvas coordinates (whole px), plus `in <frameId>` for a framed node and',
+ ' `collapsed` for a header-only one. The JSON result rows ALWAYS carry `x`, `y`, `width`, `height`',
+ ' and `parent` (the frame id, or null), so a script reads them without the flag. `x`/`y` are the',
+ ' numbers `place` takes; `width`/`height` the ones `resize` takes.',
+ '- `resize --nodes <id,id> [--width <px>] [--height <px>]` — set the size of existing nodes (give',
+ ' one axis or both; the other is kept). Each value is held between that node kind\'s minimum (the',
+ ` smallest the user can drag it to) and ${NODE_SIZE_MAX.width}×${NODE_SIZE_MAX.height}, and applied exactly (no grid snapping); the reply`,
+ ' reports the size actually applied and says when it was clamped. A terminal\'s rows and columns',
+ ' follow by themselves. A group frame',
+ ' is refused — a frame sizes itself to what it holds, so resize or `arrange` its contents. A',
+ ' COLLAPSED node keeps its header-only look: the width applies now, the height when it is',
+ ' expanded. A MAXIMIZED node is restored first, then sized. A framed node\'s frames re-fit around it.',
+ '- `place --nodes <id> --x <n> --y <n>` — put a node\'s top-left at canvas coordinates (the numbers',
+ ' `list` reports; give one axis to move along it only). `place --nodes <id,id> --dx <n> --dy <n>`',
+ ' shifts nodes by an offset instead; the two forms do not mix. With several ids and `--x`/`--y`',
+ ' the nodes move as ONE block: they keep their places relative to each other and the block\'s',
+ ` top-left lands on (x, y). Whole px, within ±${PLACE_COORD_MAX}. A framed node STAYS in its frame, which`,
+ ' grows or shrinks to hold it (to take it out, `move` it first); a frame moves with everything in',
+ ' it. A MAXIMIZED node is restored first. Values are applied exactly — no grid snapping.',
+ ' `move` takes none of these flags: it only changes which frame a node is in, and without',
+ ' `--group` it takes a node OUT of its frame — so it refuses `--x`/`--y`/`--width` rather than',
+ ' doing that silently.',
+ '- Worked example — two tight columns of four sessions on a 1080×1920 vertical screen (at 100%',
+ ' zoom a canvas px is a screen px): `resize --nodes a,b,c,d,e,f,g,h --width 540 --height 480`, then',
+ ' `arrange --nodes a,e,b,f,c,g,d,h --layout grid --cols 2 --gap 0` (ids are laid out row by row,',
+ ' so pair each row\'s left and right node), then `place --nodes a,b,c,d,e,f,g,h --x 0 --y 0` to pin',
+ ' the block to the corner, and `list --geometry on` to check. Rerun the same calls after a session',
+ ' is replaced, with the new id in its slot.'
+ ]
+}