Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(canvas-control): open nodes into free cells, never onto one spot
reviewb3849a9604da
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 8552a5f2c..7ddbee2f1 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -294,7 +294,6 @@ import {coldGroupCwd,coldGroupChildCount,coldOpenMessage,- coldPlaceBelow,offCanvasNoticeText,offCanvasReplyClause,coldResolveAfter,@@ -490,7 +489,14 @@ import {} from '../lib/pendingLaunch'import { WAIT_LABEL, dropAfterDep, edgeHidden, hiddenEdgeNodeIds, missingDepRopes, ropeInfoOf, ropeVisual } from '../lib/edgeModel'import { triggerEdges } from '../lib/triggerCard'-import { freeSpot } from '../lib/placement'+import {+ freeSpot,+ placeBelowSource,+ pendingClaimBoxes,+ pruneClaims,+ type PlaceableNode,+ type PlacementClaim+} from '../lib/placement'import { pushSessionRename, sessionNameUnchanged } from '../lib/sessionRename'import { useReopenHistory, type ReopenEntry } from '../state/reopenHistory'import { snapshotNode, recreateNodeFromSnapshot } from '../lib/reopenNode'@@ -1922,6 +1928,9 @@ export function Canvas() {// succeeded — clearing `pendingLaunch` is a state update that can lag a re-render, and this// action is irreversible, so the set (not the node data) is what guarantees exactly-once.const launchInFlight = useRef<Set<string>>(new Set())+ // Cells canvas-control opens have taken but the node array may not show yet (see+ // `PlacementClaim`): two `open-claude` calls racing each other must not pick the same cell.+ const controlPlaceClaims = useRef<PlacementClaim[]>([])const launchAttempts = useRef<Map<string, number>>(new Map())// Per-node "the gate is open but nothing has come up to deliver into" timers — the source of the// visible `stalled` warning. One per armed node, armed once and cleared the moment the node@@ -9990,6 +9999,36 @@ export function Canvas() {let offCanvas:| { project: Project; closed: boolean; created: string[]; nodes: CanvasNode[] }| undefined+ // The ONE place an agent-opened node's cell is chosen (`slotBelowSource`): the live, the+ // off-canvas and the cold path all land here, so the three cannot drift into three layouts.+ // `nodes` is the array of the project the node goes into; the claim makes the cell visible+ // to the next node of this batch and to a racing call before either shows up in `nodes`.+ // Returns the node with its ROOT-space top-left set (callers still parent it afterwards), or+ // unchanged when the source is not in `nodes`.+ const settleBelowSource = <+ T extends { id: string; position: { x: number; y: number }; width?: number | null; height?: number | null }+ >(+ nodes: readonly PlaceableNode[],+ projectId: string,+ node: T+ ): T => {+ const w = (node.width as number | undefined) ?? 600+ const h = (node.height as number | undefined) ?? 400+ const now = Date.now()+ controlPlaceClaims.current = pruneClaims(controlPlaceClaims.current, now)+ const at = placeBelowSource(nodes, sourceNodeId, { w, h }, {+ extra: pendingClaimBoxes(+ controlPlaceClaims.current,+ projectId,+ new Set(nodes.map((n) => n.id)),+ now+ ),+ snapGrid: snapGridNow()+ })+ if (!at) return node+ controlPlaceClaims.current.push({ projectId, id: node.id, box: { ...at, w, h }, at: now })+ return { ...node, position: at }+ }const reply = (r: { ok: boolean; message?: string; result?: unknown; error?: string }) => {// Say WHERE it went, once, in both voices. The verb bodies already say WHAT they made, so// none of them has to know about routing: the clause is appended here and the human strip@@ -10617,7 +10656,6 @@ export function Canvas() {return}const coldNodes = owner.nodes as unknown as ColdNode[]- const coldSrcNode = coldSrc as unknown as ColdNodeconst coldTerminal = verb === 'open-terminal'const coldAgentId = (verb === 'open-agent' ? args.agent : 'claude') as AgentIdconst coldCount = Math.max(@@ -10723,18 +10761,12 @@ export function Canvas() {const coldMade: CanvasNode[] = []for (let i = 0; i < coldCount; i++) {const built = coldTerminal- ? createTerminalNode(- coldNodes.length + i,- coldCwd,- coldPlaceBelow(coldNodes, coldSrcNode, i),- args.cmd,- coldSsh- )+ ? createTerminalNode(coldNodes.length + i, coldCwd, undefined, args.cmd, coldSsh): createAgentNode(coldAgentId,coldNodes.length + i,coldCwd,- coldPlaceBelow(coldNodes, coldSrcNode, i),+ undefined,args.prompt,coldSsh,coldAccount,@@ -10761,8 +10793,12 @@ export function Canvas() {node.position = groupSlot(coldExistingInGroup + i, w, h)node.parentId = coldGroup.groupIdnode.extent = 'parent'+ coldMade.push(node)+ } else {+ // The live path's cell rule, off the serialized nodes (the factory's position was+ // only a seed). The claim is what lets the 2nd node of this batch see the 1st.+ coldMade.push(settleBelowSource(coldNodes as PlaceableNode[], owner.id, node))}- coldMade.push(node)}// Grow the frame BEFORE the children land, exactly as `addGrouped` does — `extent:// 'parent'` clamps a child that falls outside it.@@ -10986,8 +11022,9 @@ export function Canvas() {}// Place opened nodes BELOW the source and rope them to it (source flow-out → target// flow-in), mirroring how subagent/loop nodes attach — so they read as "hanging off" the- // conversation instead of landing on top of unrelated nodes. `placeBelow` returns a node- // centerpoint; `i` fans multiple nodes out horizontally so they don't stack.+ // conversation. `placeBelow` is only a SEED centerpoint now: `addAndConnect` re-places every+ // unparented node into the first free cell of the grid under the source+ // (`settleBelowSource`), and the team/verify/worktree frames are settled the same way.const srcW = src.measured?.width ?? (src.width as number) ?? 600const srcH = src.measured?.height ?? (src.height as number) ?? 400// src.position is group-relative when the agent sits inside a group frame — resolve the@@ -11063,7 +11100,17 @@ export function Canvas() {// A node that arrives ALREADY parented (open-agent --group placed it into a frame with// relative coords) must pass through untouched — re-running parentInto would read its// relative position as absolute and land it off-frame.- const placed = node.parentId ? node : src.parentId ? parentInto(node, src.parentId) : node+ // An unparented node gets its cell HERE, whatever seed position its factory was handed:+ // every open/show verb funnels through this line, and `placeBelow` alone never looked at+ // the canvas — four one-node opens from one agent landed on one spot.+ const settled = node.parentId+ ? node+ : settleBelowSource(ctlNodes() as PlaceableNode[], ctlProject?.id ?? '', node)+ const placed = settled.parentId+ ? settled+ : src.parentId+ ? parentInto(settled, src.parentId)+ : settledif (offCanvas) {// The staged twin of the three lines below, and the whole of the off-canvas write. The// live setters all address the ACTIVE canvas, which is some other project's here — they@@ -11832,9 +11879,17 @@ export function Canvas() {const vGroup = next.find((node) => node.type === 'group' && !existingGroupIds.has(node.id))!+ // The panel was laid out at the fixed seed under the caller; move the whole FRAME into+ // the first free cell (its members are frame-relative and ride along), or a second+ // `verify` lands its panel exactly on the first.+ const vAt = settleBelowSource(live as PlaceableNode[], ctlProject?.id ?? '', vGroup).positionnext = next.map((nd) =>nd.id === vGroup.id- ? { ...nd, data: { ...nd.data, title: args.label || `Verify: ${targetTitle}` } }+ ? {+ ...nd,+ position: vAt,+ data: { ...nd.data, title: args.label || `Verify: ${targetTitle}` }+ }: nd)setNodes(next)@@ -11973,8 +12028,12 @@ export function Canvas() {const teamGroup = next.find((node) => node.type === 'group' && !existingGroupIds.has(node.id))!+ // Same as `verify`: settle the whole frame, members ride along.+ const teamAt = settleBelowSource(live as PlaceableNode[], ctlProject?.id ?? '', teamGroup).positionnext = next.map((nd) =>- nd.id === teamGroup.id ? { ...nd, data: { ...nd.data, title: args.label || 'Team' } } : nd+ nd.id === teamGroup.id+ ? { ...nd, position: teamAt, data: { ...nd.data, title: args.label || 'Team' } }+ : nd)setNodes(next)memberIds.forEach((mid) => connect(mid))@@ -12114,15 +12173,17 @@ export function Canvas() {reply({ ok: false, error: `open-worktree: ${res.message}` })return}- // Fan successive frames out horizontally (frame width + gap) so several- // open-worktree calls in one orchestration land side by side, not stacked.- const groupFan = nodesRef.current.filter(- (nd) => nd.type === 'group' && !nd.parentId- ).length- const frameAt = {- x: placeBelow(0).x + groupFan * (WORKTREE_GROUP_SIZE.width + 60),- y: placeBelow(0).y- }+ // A fresh frame takes the first free cell under the caller, like every other open.+ // (This used to fan by the number of top-level frames on the canvas, which landed a+ // frame on whatever terminal happened to sit at that offset.) The claim is keyed by a+ // placeholder id — `attachWorktree` mints the real one — so it simply ages out.+ const frameAt = bindGroupId+ ? undefined+ : settleBelowSource(nodesRef.current as PlaceableNode[], ctlProject?.id ?? '', {+ id: `pending-worktree-${requestId}`,+ position: { x: 0, y: 0 },+ ...WORKTREE_GROUP_SIZE+ }).positionconst groupId = worktreeControlRef.current.attachWorktree({ groupId: bindGroupId, at: frameAt },worktreeFromCreate({ repoPath: repoRoot, mode: 'new', branch, baseRef, path: wtPath })diff --git a/src/renderer/lib/coldOpen.test.ts b/src/renderer/lib/coldOpen.test.tsindex b5f9a0736..8f54cf7bd 100644--- a/src/renderer/lib/coldOpen.test.ts+++ b/src/renderer/lib/coldOpen.test.ts@@ -3,7 +3,6 @@ import {coldGroupChildCount,coldGroupCwd,coldOpenMessage,- coldPlaceBelow,coldResolveAfter,coldResolveGroup,groupSizeFor,@@ -155,31 +154,6 @@ describe('coldResolveAfter', () => {})})-describe('coldPlaceBelow — the live path’s placeBelow, off persisted geometry', () => {- it('centers below the source and fans siblings right', () => {- const src = N('src', { position: { x: 100, y: 200 }, size: { width: 600, height: 400 } })- expect(coldPlaceBelow([src], src, 0)).toEqual({ x: 400, y: 890 })- expect(coldPlaceBelow([src], src, 1)).toEqual({ x: 860, y: 890 })- })-- it('resolves a grouped source to ROOT space', () => {- // A stored child's position is frame-relative; placing off it directly would land the new- // node by the frame's own offset away from the agent it hangs from.- const frame = N('g', { kind: 'group', position: { x: 1000, y: 1000 } })- const src = N('src', {- parentId: 'g',- position: { x: 10, y: 20 },- size: { width: 600, height: 400 }- })- expect(coldPlaceBelow([frame, src], src, 0)).toEqual({ x: 1310, y: 1710 })- })-- it('falls back to the default node size when none is persisted', () => {- const src = N('src', { position: { x: 0, y: 0 } })- expect(coldPlaceBelow([src], src, 0)).toEqual({ x: 300, y: 690 })- })-})-describe('group grid geometry (shared with the live addGrouped path)', () => {it('lays children out in two columns under the frame header', () => {expect(groupSlot(0, 600, 400)).toEqual({ x: 24, y: 56 })diff --git a/src/renderer/lib/coldOpen.ts b/src/renderer/lib/coldOpen.tsindex 5e17aa843..81ecad699 100644--- a/src/renderer/lib/coldOpen.ts+++ b/src/renderer/lib/coldOpen.ts@@ -19,8 +19,6 @@// controlRouting.ts / projectOpen.ts / pendingLaunch.ts — vitest runs in the node environment, so// the React component is not testable and these are.-import { rootPositionIn, type PlacedNode } from './projectOpen'-/** A serialized node, as the projects store keeps them for non-active projects. Structural subset* of `CanvasNodeState` — deliberately not the type itself, so tests can build one in a line. */export interface ColdNode {@@ -37,16 +35,6 @@ export interface ColdNode {worktree?: { path?: string }}-const asPlaced = (n: ColdNode): PlacedNode => ({- id: n.id,- parentId: n.parentId,- position: n.position,- size: n.size-})--const widthOf = (n: ColdNode): number => n.size?.width ?? 600-const heightOf = (n: ColdNode): number => n.size?.height ?? 400-/*** Which agent (if any) runs in a stored node — the serialized counterpart of Canvas's `agentIdOf`,* including its legacy `tags:['claude']` leg and its agent-status fallback (a hand-launched CLI in@@ -146,24 +134,6 @@ export function coldResolveAfter(return { ok: true, after: ids }}-/**- * Where the i-th opened node lands when the source IS in this project: the same geometry the live- * path's `placeBelow` uses (below the source, fanned right), computed from the source's PERSISTED- * size and resolved to ROOT space so a source sitting inside a frame still places correctly.- * Returns a CENTER point — the factories' `center` parameter.- */-export function coldPlaceBelow(- nodes: readonly ColdNode[],- source: ColdNode,- i: number-): { x: number; y: number } {- const abs = rootPositionIn(nodes.map(asPlaced), asPlaced(source))- return {- x: abs.x + widthOf(source) / 2 + i * 460,- y: abs.y + heightOf(source) + 80 + 210- }-}-// Grid geometry for nodes opened INTO a group frame. Exported so Canvas's LIVE path uses these// exact numbers too — the cold and live placements are the same layout, and two copies of a// magic-number grid drift into two layouts.diff --git a/src/renderer/lib/placement.test.ts b/src/renderer/lib/placement.test.tsindex 0a16a8234..98f628a17 100644--- a/src/renderer/lib/placement.test.ts+++ b/src/renderer/lib/placement.test.ts@@ -1,5 +1,13 @@import { describe, it, expect } from 'vitest'-import { freeSpot, type Box } from './placement'+import {+ freeSpot,+ placeBelowSource,+ pendingClaimBoxes,+ pruneClaims,+ slotBelowSource,+ PLACEMENT_CLAIM_TTL_MS,+ type Box+} from './placement'const size = { w: 100, h: 100 }@@ -52,3 +60,134 @@ describe('freeSpot', () => {expect(clear).toBe(true)})})++describe('slotBelowSource — where an agent-opened node lands', () => {+ const source: Box = { x: 100, y: 200, w: 800, h: 600 }+ const node = { w: 640, h: 440 }+ const gap = 40+ const overlap = (a: Box, b: Box): boolean =>+ a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y++ it('lands the first node left-aligned under its source, clear of the source', () => {+ expect(slotBelowSource([source], source, node, { gap })).toEqual({ x: 100, y: 880 })+ })++ it('never stacks: four separate opens from one source land in four distinct cells', () => {+ // The field report: an orchestrator opened one session per worktree — four calls, each with+ // count 1 — and every one landed on the same point.+ const occupied: Box[] = [source]+ const placed: Box[] = []+ for (let i = 0; i < 4; i++) {+ const at = slotBelowSource(occupied, source, node, { gap })+ const box = { ...at, ...node }+ occupied.push(box)+ placed.push(box)+ }+ expect(placed.map((b) => b.x)).toEqual([100, 780, 1460, 2140])+ expect(new Set(placed.map((b) => b.y))).toEqual(new Set([880]))+ for (let i = 0; i < placed.length; i++) {+ expect(overlap(placed[i], source)).toBe(false)+ for (let j = i + 1; j < placed.length; j++) expect(overlap(placed[i], placed[j])).toBe(false)+ }+ })++ it('wraps to the next row once a row holds `cols` nodes', () => {+ const occupied: Box[] = [source]+ let last = { x: 0, y: 0 }+ for (let i = 0; i < 5; i++) {+ last = slotBelowSource(occupied, source, node, { gap, cols: 4 })+ occupied.push({ ...last, ...node })+ }+ expect(last).toEqual({ x: 100, y: 880 + 440 + gap })+ })++ it('steps past an unrelated node already sitting under the source', () => {+ const stranger: Box = { x: 150, y: 900, w: 300, h: 200 }+ expect(slotBelowSource([source, stranger], source, node, { gap })).toEqual({ x: 780, y: 880 })+ })++ it('checks the SNAPPED cell, so grid rounding cannot slide a node onto its neighbour', () => {+ const grid = 24+ const snap = (p: { x: number; y: number }) => ({+ x: Math.round(p.x / grid) * grid,+ y: Math.round(p.y / grid) * grid+ })+ // The blocker takes cell 0; cell 1 is raw (780, 880) and snaps to (792, 888). Whatever comes+ // back must be ON the grid and still keep the full gap from everything.+ const blocker: Box = { x: 60, y: 880, w: 40, h: 40 }+ const at = slotBelowSource([source, blocker], source, node, { gap, snap })+ expect(at.x % grid).toBe(0)+ expect(at.y % grid).toBe(0)+ const box = { ...at, ...node }+ const padded = { x: blocker.x - gap, y: blocker.y - gap, w: blocker.w + 2 * gap, h: blocker.h + 2 * gap }+ expect(overlap(box, padded)).toBe(false)+ })++ it('falls back to below EVERYTHING when the grid under the source is walled off — never onto a node', () => {+ const wall: Box = { x: -1e6, y: 850, w: 2e6, h: 1e6 }+ const at = slotBelowSource([source, wall], source, node, { gap })+ expect(at.x).toBe(source.x)+ expect(at.y).toBeGreaterThanOrEqual(wall.y + wall.h + gap)+ })+})++describe('placeBelowSource — slotBelowSource over a real node array', () => {+ const size = { w: 640, h: 440 }++ it('resolves a source nested in frames to ROOT space', () => {+ const outer = { id: 'g1', type: 'group', position: { x: 1000, y: 1000 }, width: 3000, height: 3000 }+ const inner = { id: 'g2', type: 'group', parentId: 'g1', position: { x: 100, y: 100 }, width: 2000, height: 2000 }+ const src = { id: 's', parentId: 'g2', position: { x: 50, y: 60 }, width: 600, height: 400 }+ expect(placeBelowSource([outer, inner, src], 's', size)).toEqual({ x: 1150, y: 1640 })+ })++ it('does not treat the frames CONTAINING the source as obstacles, but does treat any other frame as one', () => {+ const own = { id: 'g1', type: 'group', position: { x: 0, y: 0 }, width: 5000, height: 5000 }+ const src = { id: 's', parentId: 'g1', position: { x: 0, y: 0 }, width: 600, height: 400 }+ expect(placeBelowSource([own, src], 's', size)).toEqual({ x: 0, y: 480 })+ const other = { id: 'g9', type: 'group', position: { x: -10, y: 470 }, width: 700, height: 300 }+ expect(placeBelowSource([other, { ...src, parentId: undefined }], 's', size)).not.toEqual({+ x: 0,+ y: 480+ })+ })++ it("prefers React Flow's measured size, then the persisted size, then the width field", () => {+ const measured = { id: 's', position: { x: 0, y: 0 }, width: 600, height: 400, measured: { width: 600, height: 900 } }+ expect(placeBelowSource([measured], 's', size)!.y).toBe(980)+ const stored = { id: 's', position: { x: 0, y: 0 }, size: { width: 600, height: 700 } }+ expect(placeBelowSource([stored], 's', size)!.y).toBe(780)+ })++ it('counts boxes placed earlier in the same batch (setNodes has not committed them yet)', () => {+ const src = { id: 's', position: { x: 0, y: 0 }, width: 600, height: 400 }+ const first = placeBelowSource([src], 's', size)!+ const second = placeBelowSource([src], 's', size, { extra: [{ ...first, ...size }] })!+ expect(second).not.toEqual(first)+ expect(second.y).toBe(first.y)+ })++ it('returns undefined when the source is not in the array (the caller keeps its old answer)', () => {+ expect(placeBelowSource([], 'nope', size)).toBeUndefined()+ })+})++describe('placement claims — opens that raced ahead of the render', () => {+ const box: Box = { x: 0, y: 0, w: 10, h: 10 }+ it('answers only for the same project, while young, and until the node itself is present', () => {+ const claims = [+ { projectId: 'p', id: 'a', box, at: 1000 },+ { projectId: 'q', id: 'b', box, at: 1000 },+ { projectId: 'p', id: 'c', box, at: 1000 - PLACEMENT_CLAIM_TTL_MS },+ { projectId: 'p', id: 'd', box, at: 1000 }+ ]+ expect(pendingClaimBoxes(claims, 'p', new Set(['d']), 1000)).toEqual([box])+ })+ it('prunes expired claims', () => {+ const claims = [+ { projectId: 'p', id: 'a', box, at: 0 },+ { projectId: 'p', id: 'b', box, at: 5 }+ ]+ expect(pruneClaims(claims, PLACEMENT_CLAIM_TTL_MS + 1).map((c) => c.id)).toEqual(['b'])+ })+})diff --git a/src/renderer/lib/placement.ts b/src/renderer/lib/placement.tsindex 6bbdab706..d2670ea71 100644--- a/src/renderer/lib/placement.ts+++ b/src/renderer/lib/placement.ts@@ -2,6 +2,12 @@// session", the dock's add menu, the command palette). Those all fell back to the view center, so// every node created that way piled up on the same spot — switch to the canvas and you'd find a// stack of overlapping nodes. `freeSpot` instead finds the nearest empty position.+//+// `slotBelowSource` is the same problem for a node an AGENT opens (canvas-control's open/show+// verbs), where there IS an anchor — the agent's own node — and the layout should read as "hanging+// off that conversation".++import { rootPositionIn, type PlacedNode } from './projectOpen'export interface Box {x: number@@ -52,3 +58,134 @@ export function freeSpot(}return preferred}++/**+ * Where a node an AGENT opens lands (canvas-control's `open-*` / `show-*` verbs). Returns a+ * TOP-LEFT point in root space.+ *+ * The old rule was a fixed point under the source, fanned right by 460 px per node of the SAME+ * call, with no look at the canvas. So the ordinary orchestration shape — one `open-claude` per+ * worktree, each a separate call with count 1 — put every session on exactly one spot, and even a+ * single `--count 3` overlapped itself (a default node is 640 px wide).+ *+ * Now: a grid under the source, left-aligned to it, filled row by row (`cols` per row), taking the+ * first cell that keeps `gap` clear of everything in `occupied`. The cell is tested AFTER `snap`,+ * so grid rounding cannot slide a node onto a neighbour after the check passed. `occupied` must be+ * root-space and must include every node placed earlier in the same batch. Past the search cap it+ * drops below everything, which is clear by construction — overlap is never the fallback.+ */+export function slotBelowSource(+ occupied: readonly Box[],+ source: Box,+ size: { w: number; h: number },+ opts: {+ gap?: number+ cols?: number+ snap?: (p: { x: number; y: number }) => { x: number; y: number }+ } = {}+): { x: number; y: number } {+ const gap = opts.gap ?? 40+ const cols = Math.max(1, Math.floor(opts.cols ?? 4))+ const snap = opts.snap ?? ((p) => p)+ const clear = (p: { x: number; y: number }): boolean =>+ !occupied.some(+ (b) =>+ p.x < b.x + b.w + gap &&+ p.x + size.w + gap > b.x &&+ p.y < b.y + b.h + gap &&+ p.y + size.h + gap > b.y+ )+ // 80 px under the source: the room the lineage rope has always had.+ const top = source.y + source.h + 80+ for (let row = 0; row < 200; row++) {+ for (let col = 0; col < cols; col++) {+ const p = snap({ x: source.x + col * (size.w + gap), y: top + row * (size.h + gap) })+ if (clear(p)) return p+ }+ }+ const bottom = occupied.reduce((m, b) => Math.max(m, b.y + b.h + gap), top)+ // Snap can round up to half a cell back toward the box above; a whole extra gap absorbs it.+ return snap({ x: source.x, y: bottom + gap })+}++/** A node as the live canvas (React Flow, with `measured`) or the serialized store (`size`) holds+ * it — enough to place something next to it. */+export interface PlaceableNode extends PlacedNode {+ id: string+ measured?: { width?: number; height?: number }+}++const DEFAULT_W = 600+const DEFAULT_H = 400++const boxOf = (n: PlaceableNode, at: { x: number; y: number }): Box => ({+ x: at.x,+ y: at.y,+ w: n.measured?.width ?? n.size?.width ?? (n.width as number | undefined) ?? DEFAULT_W,+ h: n.measured?.height ?? n.size?.height ?? (n.height as number | undefined) ?? DEFAULT_H+})++/**+ * `slotBelowSource` over a project's node array: resolves every node (and the source) to ROOT+ * space, and leaves out the frames that CONTAIN the source — the opened node is parented into the+ * source's frame, so that frame is where it belongs, not an obstacle. Any other frame is one: a+ * top-level node drawn over a frame reads as inside it while it is not. `extra` is what this batch+ * (or a racing call) already placed and the array does not show yet. `undefined` when the source+ * is not in `nodes`.+ */+export function placeBelowSource(+ nodes: readonly PlaceableNode[],+ sourceId: string,+ size: { w: number; h: number },+ opts: { extra?: readonly Box[]; snapGrid?: number } = {}+): { x: number; y: number } | undefined {+ const src = nodes.find((n) => n.id === sourceId)+ if (!src) return undefined+ const ancestors = new Set<string>()+ const byId = new Map(nodes.map((n) => [n.id, n]))+ for (let p = src.parentId; p && !ancestors.has(p); p = byId.get(p)?.parentId) ancestors.add(p)+ const occupied = nodes+ .filter((n) => !ancestors.has(n.id))+ .map((n) => boxOf(n, rootPositionIn(nodes, n)))+ const g = opts.snapGrid ?? 0+ return slotBelowSource(+ [...occupied, ...(opts.extra ?? [])],+ boxOf(src, rootPositionIn(nodes, src)),+ size,+ g > 0+ ? { snap: (p) => ({ x: Math.round(p.x / g) * g + 0, y: Math.round(p.y / g) * g + 0 }) }+ : {}+ )+}++/**+ * A box an open has taken but the node array may not show yet: `setNodes` commits on the next+ * render and the cold path's snapshot is read before its awaits, so two opens racing each other+ * (an agent firing `open-claude … &` per worktree) would otherwise both see the same empty cell.+ */+export interface PlacementClaim {+ projectId: string+ id: string+ box: Box+ at: number+}++/** Long enough to outlive any render/IPC lag, short enough that a deleted node's cell frees up. */+export const PLACEMENT_CLAIM_TTL_MS = 10_000++export function pruneClaims(claims: readonly PlacementClaim[], now: number): PlacementClaim[] {+ return claims.filter((c) => now - c.at < PLACEMENT_CLAIM_TTL_MS)+}++/** The claims that still answer for a cell: same project, still young, and not yet in the array —+ * once the node is present its REAL box (which the user may have moved) speaks for it. */+export function pendingClaimBoxes(+ claims: readonly PlacementClaim[],+ projectId: string,+ presentIds: ReadonlySet<string>,+ now: number+): Box[] {+ return claims+ .filter((c) => c.projectId === projectId && now - c.at < PLACEMENT_CLAIM_TTL_MS && !presentIds.has(c.id))+ .map((c) => c.box)+}