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.

fix(canvas): keep cursor-less new nodes inside the visible canvas (#1233)

eneskirca3b04c5736ec0
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index fd5b10410..72f0c1a37 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -401,7 +401,8 @@ import {
projectTargetFlagRefusal,
resolveProjectTarget,
clearAttachConsent,
- folderName
+ folderName,
+ rootPositionIn
} from '../lib/projectOpen'
import {
absolutePosition,
@@ -696,6 +697,7 @@ import {
} from '../lib/edgeModel'
import { triggerEdges } from '../lib/triggerCard'
import {
+ emptySpotCenter,
freeSpot,
placeBelowSource,
pendingClaimBoxes,
@@ -5266,33 +5268,50 @@ export function Canvas() {
}, [screenToFlowPosition])
/**
- * A non-overlapping drop point for a NODE created without a cursor (dock / palette / kanban
- * board) — otherwise every one lands on the view center and piles into a stack you only discover
- * when you switch back to the canvas. Returns undefined only if the view isn't measured yet.
+ * A non-overlapping drop point for a NODE created without a cursor (dock / palette / keyboard
+ * shortcut / kanban board) — otherwise every one lands on the view center and piles into a stack
+ * you only discover when you switch back to the canvas. Returns undefined only if the view isn't
+ * measured yet.
+ *
+ * Issue #1140: a node's answer stays INSIDE the visible canvas (minus pinned panels, the controls
+ * and the dock — `measureMaximizeInsets`), so a node made from a shortcut never lands where the
+ * user cannot see it; a full view gets the least-covered visible spot instead. The camera is not
+ * moved.
*/
// `box` places something other than a default-sized node — a worktree frame, say. For a box the
- // answer is a TOP-LEFT that centres it on the view (`freeSpot` answers top-lefts); without one
- // the historical point is returned unchanged.
+ // answer is a TOP-LEFT that centres it on the view (`freeSpot` answers top-lefts); without one it
+ // is a CENTRE, which is what the node factories take (`placeAt` subtracts half the size) — the
+ // search itself is made on the centred box the factory will place (`emptySpotCenter`).
const emptyNodePos = useCallback((box?: { w: number; h: number }): { x: number; y: number } | undefined => {
+ const wrapRect = flowWrapRef.current?.getBoundingClientRect()
const center = viewCenter()
- if (!center) return undefined
- const preferred = box ? { x: center.x - box.w / 2, y: center.y - box.h / 2 } : center
- const s = useSettings.getState().settings
- const w = s.defaultNodeWidth || 640
- const h = s.defaultNodeHeight || 440
+ if (!center || !wrapRect) return undefined
+ const insets = measureMaximizeInsets(wrapRect)
+ const a = screenToFlowPosition({ x: wrapRect.left + insets.left, y: wrapRect.top + (insets.top ?? 0) })
+ const b = screenToFlowPosition({ x: wrapRect.right - insets.right, y: wrapRect.bottom - (insets.bottom ?? 0) })
+ const view = b.x > a.x && b.y > a.y ? { x: a.x, y: a.y, w: b.x - a.x, h: b.y - a.y } : undefined
+ const term = terminalNodeSize()
+ const w = term.width
+ const h = term.height
// Real, laid-out nodes only (skip ephemeral subagent/loop cards, which aren't persisted and
- // vanish on their own — see useAgentNodes).
+ // vanish on their own — see useAgentNodes). Positions in ROOT space: a group child's position
+ // is relative to its frame.
const ephemeral = new Set(Object.keys(useAgentNodes.getState().byId))
- const boxes = nodesRef.current
- .filter((n) => !ephemeral.has(n.id))
- .map((n) => ({
- x: n.position.x,
- y: n.position.y,
+ const live = nodesRef.current.filter((n) => !ephemeral.has(n.id))
+ const boxes = live.map((n) => {
+ const at = rootPositionIn(live, n)
+ return {
+ x: at.x,
+ y: at.y,
w: (n.measured?.width as number | undefined) ?? (n.width as number | undefined) ?? w,
h: (n.measured?.height as number | undefined) ?? (n.height as number | undefined) ?? h
- }))
- return freeSpot(boxes, preferred, box ?? { w, h })
- }, [viewCenter])
+ }
+ })
+ // A frame keeps the unbounded search: drawn over existing nodes it would read as containing
+ // them, which is worse than landing beside the view.
+ if (box) return freeSpot(boxes, { x: center.x - box.w / 2, y: center.y - box.h / 2 }, box)
+ return emptySpotCenter(boxes, view, center, { w, h })
+ }, [viewCenter, screenToFlowPosition])
/** The checkout a Source Control action refers to. The panel hands its ACTIVE SCOPE's cwd
* (main checkout or a bound worktree) with every relative path, so the diff/agent node it opens
diff --git a/src/renderer/canvas/empty-node-pos.source.test.ts b/src/renderer/canvas/empty-node-pos.source.test.ts
new file mode 100644
index 000000000..5beda4442
--- /dev/null
+++ b/src/renderer/canvas/empty-node-pos.source.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+/**
+ * Issue #1140: a node created without a cursor (keyboard shortcut, dock, palette, board) must land
+ * inside the visible canvas, and the overlap search must be made on the CENTRED box the factory
+ * places. The geometry is unit-tested in lib/placement.test.ts; this pins that Canvas uses it.
+ */
+const SRC = readFileSync(join(__dirname, 'Canvas.tsx'), 'utf8').replace(/\r\n/g, '\n')
+
+describe('emptyNodePos wiring', () => {
+ const at = SRC.indexOf('const emptyNodePos = useCallback(')
+ const body = SRC.slice(at, SRC.indexOf('}, [viewCenter', at))
+
+ it('bounds a node to the visible canvas and searches in centre terms', () => {
+ expect(at).toBeGreaterThan(-1)
+ expect(body).toContain('measureMaximizeInsets(wrapRect)')
+ expect(body).toContain('return emptySpotCenter(boxes, view, center, { w, h })')
+ })
+
+ it('reads obstacles in root space', () => {
+ expect(body).toContain('rootPositionIn(live, n)')
+ })
+})
diff --git a/src/renderer/canvas/issue-worktree.source.test.ts b/src/renderer/canvas/issue-worktree.source.test.ts
index fd4d8f7b2..6a2bedb67 100644
--- a/src/renderer/canvas/issue-worktree.source.test.ts
+++ b/src/renderer/canvas/issue-worktree.source.test.ts
@@ -160,8 +160,7 @@ describe('Start with agent in a new worktree', () => {
describe('a new issue frame is centred on the view', () => {
it('emptyNodePos(box) answers a TOP-LEFT that centres the box (freeSpot answers top-lefts)', () => {
const pos = between('const emptyNodePos = useCallback(', 'const scmCwd = useCallback(')
- expect(pos).toContain('const preferred = box ? { x: center.x - box.w / 2, y: center.y - box.h / 2 } : center')
- expect(pos).toContain('return freeSpot(boxes, preferred, box ?? { w, h })')
+ expect(pos).toContain('if (box) return freeSpot(boxes, { x: center.x - box.w / 2, y: center.y - box.h / 2 }, box)')
})
})
diff --git a/src/renderer/lib/placement.test.ts b/src/renderer/lib/placement.test.ts
index 98f628a17..083afc1b2 100644
--- a/src/renderer/lib/placement.test.ts
+++ b/src/renderer/lib/placement.test.ts
@@ -1,5 +1,7 @@
import { describe, it, expect } from 'vitest'
import {
+ CASCADE_STEP,
+ emptySpotCenter,
freeSpot,
placeBelowSource,
pendingClaimBoxes,
@@ -191,3 +193,96 @@ describe('placement claims — opens that raced ahead of the render', () => {
expect(pruneClaims(claims, PLACEMENT_CLAIM_TTL_MS + 1).map((c) => c.id)).toEqual(['b'])
})
})
+
+// Issue #1140: a node created by a shortcut / dock / palette landed wherever the unbounded ring
+// search found room — often far outside the view — and the check was made at the wrong place.
+describe('emptySpotCenter (issue #1140)', () => {
+ const size = { w: 100, h: 100 }
+ const view: Box = { x: -300, y: -200, w: 600, h: 400 }
+ const tl = (c: { x: number; y: number }) => ({ x: c.x - size.w / 2, y: c.y - size.h / 2 })
+ const overlaps = (p: { x: number; y: number }, b: Box) =>
+ p.x < b.x + b.w && p.x + size.w > b.x && p.y < b.y + b.h && p.y + size.h > b.y
+ const insideView = (p: { x: number; y: number }) =>
+ p.x >= view.x && p.y >= view.y && p.x + size.w <= view.x + view.w && p.y + size.h <= view.y + view.h
+
+ it('returns the view centre when it is free', () => {
+ expect(emptySpotCenter([], view, { x: 0, y: 0 }, size)).toEqual({ x: 0, y: 0 })
+ })
+
+ it('checks the CENTRED box the factory will place, not a box hanging off the centre', () => {
+ // Overlaps the centred node (-50..50) but not a box whose top-left is the centre (0..100).
+ const box: Box = { x: -120, y: -120, w: 80, h: 80 }
+ const c = emptySpotCenter([box], view, { x: 0, y: 0 }, size)
+ expect(overlaps(tl(c), box)).toBe(false)
+ })
+
+ it('stays inside the view when the centre is taken', () => {
+ const box: Box = { x: -60, y: -60, w: 120, h: 120 }
+ const c = emptySpotCenter([box], view, { x: 0, y: 0 }, size)
+ expect(overlaps(tl(c), box)).toBe(false)
+ expect(insideView(tl(c))).toBe(true)
+ })
+
+ it('a full view never sends the node off screen — it takes the least-covered spot in view', () => {
+ // Everything visible is covered except a strip on the right edge.
+ const wall: Box = { x: -320, y: -220, w: 520, h: 440 }
+ const c = emptySpotCenter([wall], view, { x: 0, y: 0 }, size)
+ expect(insideView(tl(c))).toBe(true)
+ // The old unbounded search answered a clear cell outside the view; this one prefers room in it.
+ const fully: Box = { x: -10_000, y: -10_000, w: 20_000, h: 20_000 }
+ const d = emptySpotCenter([fully], view, { x: 0, y: 0 }, size)
+ expect(insideView(tl(d))).toBe(true)
+ })
+
+ it('two nodes made in a row on a full view do not land exactly on top of each other', () => {
+ const wall: Box = { x: -320, y: -220, w: 640, h: 440 }
+ const first = tl(emptySpotCenter([wall], view, { x: 0, y: 0 }, size))
+ const second = tl(emptySpotCenter([wall, { ...first, ...size }], view, { x: 0, y: 0 }, size))
+ expect(second).not.toEqual(first)
+ expect(insideView(second)).toBe(true)
+ })
+
+ it('a view smaller than the node keeps the node centred on it, stepped off an exact overlap', () => {
+ const tiny: Box = { x: -20, y: -20, w: 40, h: 40 }
+ expect(emptySpotCenter([], tiny, { x: 0, y: 0 }, size)).toEqual({ x: 0, y: 0 })
+ // Exactly where an existing node already sits: cascaded down-right, never stacked on it.
+ expect(emptySpotCenter([{ x: -50, y: -50, w: 100, h: 100 }], tiny, { x: 0, y: 0 }, size)).toEqual({
+ x: CASCADE_STEP,
+ y: CASCADE_STEP
+ })
+ })
+
+ // The review's reproduction: a 1440x864 canvas (top bar 32 px, dock 52 px, optionally a pinned
+ // 308 px sidebar), one default-sized node already centred, then shortcut creates in a row. A view
+ // under about two node-widths has no other in-view cell, so before the cascade every create
+ // landed EXACTLY on the previous one — at zoom 1.38, where goToNode's framing lands, every time.
+ it.each([
+ [1.0, 0],
+ [1.0, 308],
+ [1.2, 0],
+ [1.38, 0],
+ [1.38, 308]
+ ])('creates in a row never share a top-left (zoom %s, pinned %s px)', (zoom, pinned) => {
+ const node = { w: 640, h: 440 }
+ const toFlow = (x: number, y: number) => ({ x: x / zoom, y: y / zoom })
+ const a = toFlow(pinned, 32)
+ const b = toFlow(1440, 864 - 52)
+ const bounds: Box = { x: a.x, y: a.y, w: b.x - a.x, h: b.y - a.y }
+ const center = toFlow(720, 432)
+ const boxes: Box[] = [{ x: center.x - node.w / 2, y: center.y - node.h / 2, ...node }]
+ for (let i = 0; i < 4; i++) {
+ const c = emptySpotCenter(boxes, bounds, center, node)
+ const at = { x: c.x - node.w / 2, y: c.y - node.h / 2 }
+ for (const prev of boxes) {
+ expect(Math.abs(prev.x - at.x) >= CASCADE_STEP || Math.abs(prev.y - at.y) >= CASCADE_STEP).toBe(true)
+ }
+ boxes.push({ ...at, ...node })
+ }
+ })
+
+ it('without a view it is the old unbounded search, in centre terms', () => {
+ const box: Box = { x: -50, y: -50, w: 100, h: 100 }
+ const c = emptySpotCenter([box], undefined, { x: 0, y: 0 }, size)
+ expect(overlaps(tl(c), box)).toBe(false)
+ })
+})
diff --git a/src/renderer/lib/placement.ts b/src/renderer/lib/placement.ts
index d2670ea71..818a3ca5f 100644
--- a/src/renderer/lib/placement.ts
+++ b/src/renderer/lib/placement.ts
@@ -16,20 +16,55 @@ export interface Box {
h: number
}
+/** How far a bounded placement steps down-right off a node whose top-left it would share (#1140):
+ * enough to leave that node's header row showing above the new one. */
+export const CASCADE_STEP = 32
+const CASCADE_MAX_HOPS = 64
+
+/** `p`, moved down-right by `CASCADE_STEP` until no box in `existing` starts within a step of it. */
+function cascadeOff(existing: Box[], p: { x: number; y: number }): { x: number; y: number } {
+ let { x, y } = p
+ for (
+ let hop = 0;
+ hop < CASCADE_MAX_HOPS &&
+ existing.some((b) => Math.abs(b.x - x) < CASCADE_STEP && Math.abs(b.y - y) < CASCADE_STEP);
+ hop++
+ ) {
+ x += CASCADE_STEP
+ y += CASCADE_STEP
+ }
+ return { x, y }
+}
+
/**
* The nearest position (to `preferred`) where a `size` box does not overlap any of `existing`,
* searched outward on a grid stepped by the node size. Returns `preferred` unchanged when it's
* already clear (so a lone node / an empty canvas keeps the centered placement). Pure + testable.
+ * `preferred` and the answer are TOP-LEFT corners.
*
* `gap` is the minimum breathing room kept between boxes. The ring search is capped so a pathological
* canvas can never loop forever — past the cap it gives up and returns `preferred` (overlap is a far
* lesser evil than a hang).
+ *
+ * `bounds` (issue #1140) keeps the answer inside a rectangle — the visible canvas — so a node made
+ * from a shortcut never lands somewhere the user cannot see. Inside it the search runs on a half-step
+ * grid (a view is only a few nodes wide), and when nothing in view is clear it takes the in-view
+ * spot covered LEAST, nearest first: a busy view gets a visible, partly overlapping node rather than
+ * a clear one off screen. The search starts from `preferred` pulled inside `bounds` (a pinned panel
+ * can push the view centre's box past the visible edge), and a node too big for `bounds` at all
+ * (zoomed in past the node's size) stays at `preferred`.
+ *
+ * Whatever the bounded branch answers is CASCADED off any node whose top-left it would share
+ * (`CASCADE_STEP` down-right per hit, like stacked windows): a view under about two node-widths has
+ * no other in-view cell, and without this every node made in a row landed exactly on the last one —
+ * invisible, the very pile this function exists to prevent.
*/
export function freeSpot(
existing: Box[],
preferred: { x: number; y: number },
size: { w: number; h: number },
- gap = 28
+ gap = 28,
+ bounds?: Box
): { x: number; y: number } {
const clear = (x: number, y: number): boolean =>
!existing.some(
@@ -42,6 +77,42 @@ export function freeSpot(
if (clear(preferred.x, preferred.y)) return preferred
+ if (bounds) {
+ // "Does it fit at all" is size against bounds, never where the centred box happens to sit.
+ if (size.w > bounds.w || size.h > bounds.h) return cascadeOff(existing, preferred)
+ const inside = (x: number, y: number): boolean =>
+ x >= bounds.x && y >= bounds.y && x + size.w <= bounds.x + bounds.w && y + size.h <= bounds.y + bounds.h
+ const start = {
+ x: Math.min(Math.max(preferred.x, bounds.x), bounds.x + bounds.w - size.w),
+ y: Math.min(Math.max(preferred.y, bounds.y), bounds.y + bounds.h - size.h)
+ }
+ if (clear(start.x, start.y)) return start
+ const covered = (x: number, y: number): number =>
+ existing.reduce((sum, b) => {
+ const w = Math.min(x + size.w, b.x + b.w) - Math.max(x, b.x)
+ const h = Math.min(y + size.h, b.y + b.h) - Math.max(y, b.y)
+ return w > 0 && h > 0 ? sum + w * h : sum
+ }, 0)
+ const sx = (size.w + gap) / 2
+ const sy = (size.h + gap) / 2
+ const rings = Math.min(200, Math.ceil(Math.max(bounds.w / sx, bounds.h / sy)) + 1)
+ let best = { x: start.x, y: start.y, area: covered(start.x, start.y) }
+ for (let ring = 1; ring <= rings; ring++) {
+ for (let dy = -ring; dy <= ring; dy++) {
+ for (let dx = -ring; dx <= ring; dx++) {
+ if (Math.max(Math.abs(dx), Math.abs(dy)) !== ring) continue // perimeter only
+ const x = start.x + dx * sx
+ const y = start.y + dy * sy
+ if (!inside(x, y)) continue
+ if (clear(x, y)) return { x, y }
+ const area = covered(x, y)
+ if (area < best.area) best = { x, y, area }
+ }
+ }
+ }
+ return cascadeOff(existing, { x: best.x, y: best.y })
+ }
+
const stepX = size.w + gap
const stepY = size.h + gap
// Expanding square rings around `preferred`; within a ring, walk the perimeter and take the first
@@ -59,6 +130,24 @@ export function freeSpot(
return preferred
}
+/**
+ * `freeSpot` in the terms the node factories speak: a CENTRE in, a CENTRE out (`placeAt` turns a
+ * centre into the top-left by subtracting half the size). Issue #1140: `emptyNodePos` used to hand
+ * the view centre to `freeSpot` AS a top-left and then give the answer to the factories AS a centre,
+ * so every overlap check was made half a node away from where the node actually landed.
+ */
+export function emptySpotCenter(
+ existing: Box[],
+ view: Box | undefined,
+ center: { x: number; y: number },
+ size: { w: number; h: number },
+ gap = 28
+): { x: number; y: number } {
+ const topLeft = { x: center.x - size.w / 2, y: center.y - size.h / 2 }
+ const at = freeSpot(existing, topLeft, size, gap, view)
+ return at === topLeft ? center : { x: at.x + size.w / 2, y: at.y + size.h / 2 }
+}
+
/**
* Where a node an AGENT opens lands (canvas-control's `open-*` / `show-*` verbs). Returns a
* TOP-LEFT point in root space.