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): place cursor-less new nodes in free space, not on a pile (#76)

eneskircac4901ccdeb88
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index f079a0dcc..5a60e2632 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -194,6 +194,7 @@ import {
} from '../session/relay-tab'
import { buildBackgroundLinkMaps, buildContextLinkNote, buildLinkMap, buildNotePushMessage, classifyLink, hiddenLinkIds, linkIdsCoveredByRopes, pairKey, planBridges, type LinkEndpoint } from '../lib/noteLink'
import { dependencyEdges, launchesToFire, unmetDeps, type ArmedNode } from '../lib/pendingLaunch'
+import { freeSpot } from '../lib/placement'
import { pushSessionRename } from '../lib/sessionRename'
import { parseLenses, verifyLensPrompt, verifySynthesisPrompt } from '../lib/verifyPanel'
import { useSettings } from '../state/settings'
@@ -2260,6 +2261,31 @@ export function Canvas() {
return screenToFlowPosition({ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 })
}, [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.
+ */
+ const emptyNodePos = useCallback((): { x: number; y: number } | undefined => {
+ const preferred = viewCenter()
+ if (!preferred) return undefined
+ const s = useSettings.getState().settings
+ const w = s.defaultNodeWidth || 640
+ const h = s.defaultNodeHeight || 440
+ // Real, laid-out nodes only (skip ephemeral subagent/loop cards, which aren't persisted and
+ // vanish on their own — see useAgentNodes).
+ 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,
+ 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, { w, h })
+ }, [viewCenter])
+
/** 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
* is rooted in the same checkout the panel is showing — reconstructing the project's own cwd here
@@ -2381,12 +2407,12 @@ export function Canvas() {
setNodes((ns) => {
// In an SSH project the node is stamped remote (runs over the project's master); the
// factory takes the project's ssh and roots the terminal at its remoteCwd.
- const node = createTerminalNode(ns.length, cwd, center ?? viewCenter(), initialCommand, project?.ssh)
+ const node = createTerminalNode(ns.length, cwd, center ?? emptyNodePos(), initialCommand, project?.ssh)
return [...ns, groupId ? parentInto(node, groupId) : node]
})
markDirty()
},
- [setNodes, markDirty, activeProjectId, viewCenter, cwdForNewNodeIn, parentInto]
+ [setNodes, markDirty, activeProjectId, emptyNodePos, cwdForNewNodeIn, parentInto]
)
/** Open a new terminal that runs a command on start (e.g. gh auth login). `cwd` lets a caller
@@ -2756,12 +2782,12 @@ export function Canvas() {
const addSticky = useCallback(
(center?: { x: number; y: number }, groupId?: string) => {
setNodes((ns) => {
- const node = createStickyNode(ns.length, center ?? viewCenter())
+ const node = createStickyNode(ns.length, center ?? emptyNodePos())
return [...ns, groupId ? parentInto(node, groupId) : node]
})
markDirty()
},
- [setNodes, markDirty, viewCenter, parentInto]
+ [setNodes, markDirty, emptyNodePos, parentInto]
)
const addDino = useCallback(
@@ -2786,10 +2812,10 @@ export function Canvas() {
const input = await promptDialog({ message: 'Open web view — enter a URL:' })
const url = input?.trim()
if (!url) return
- setNodes((ns) => [...ns, createWebNode(ns.length, { url }, center ?? viewCenter())])
+ setNodes((ns) => [...ns, createWebNode(ns.length, { url }, center ?? emptyNodePos())])
markDirty()
},
- [setNodes, markDirty, viewCenter]
+ [setNodes, markDirty, emptyNodePos]
)
const addBrowser = useCallback(
@@ -2797,10 +2823,10 @@ export function Canvas() {
// Open a blank browser node — the user types the URL in the node's own address bar (like a
// browser's new tab). We deliberately don't use window.prompt: Electron doesn't support it
// (it throws "prompt() is and will not be supported"), and a browser node doesn't need it.
- setNodes((ns) => [...ns, createBrowserNode(ns.length, '', center ?? viewCenter())])
+ setNodes((ns) => [...ns, createBrowserNode(ns.length, '', center ?? emptyNodePos())])
markDirty()
},
- [setNodes, markDirty, viewCenter]
+ [setNodes, markDirty, emptyNodePos]
)
// Task 6: the Settings → Accounts "Add account" flow dispatches 'nodeterm:add-account-login'
@@ -2863,7 +2889,7 @@ export function Canvas() {
agentId,
ns.length,
cwd,
- center ?? viewCenter(),
+ center ?? emptyNodePos(),
undefined,
project?.ssh,
account,
@@ -2873,7 +2899,7 @@ export function Canvas() {
})
markDirty()
},
- [setNodes, markDirty, activeProjectId, viewCenter, cwdForNewNodeIn, parentInto]
+ [setNodes, markDirty, activeProjectId, emptyNodePos, cwdForNewNodeIn, parentInto]
)
// Open a terminal node that ssh's into a saved server. `screenPos` (a pane/dock cursor) is
@@ -2881,14 +2907,14 @@ export function Canvas() {
// selected (and others deselected) so it's the active focus right away.
const addSshTerminal = useCallback(
(server: SshServer, screenPos?: { x: number; y: number }) => {
- const at = screenPos ? screenToFlowPosition(screenPos) : viewCenter()
+ const at = screenPos ? screenToFlowPosition(screenPos) : emptyNodePos()
setNodes((ns) => [
...ns.map((n) => ({ ...n, selected: false })),
{ ...createSshTerminalNode(server, ns.length, at), selected: true }
])
markDirty()
},
- [setNodes, markDirty, screenToFlowPosition, viewCenter]
+ [setNodes, markDirty, screenToFlowPosition, emptyNodePos]
)
// Open the SSH server picker. Remote SSH terminals are free (Core).
@@ -4933,7 +4959,7 @@ export function Canvas() {
(choice: KanbanCreateChoice, columnId: string | null) => {
const project = useProjects.getState().getProject(activeProjectId)
const index = nodesRef.current.length
- const at = viewCenter()
+ const at = emptyNodePos() // board has no cursor — drop it in free canvas space, not on a pile
const node =
choice.kind === 'terminal'
? createTerminalNode(index, project?.cwd, at, undefined, project?.ssh)
@@ -4984,7 +5010,7 @@ export function Canvas() {
event: { type: 'card-created', to: toName, title }
})
},
- [activeProjectId, viewCenter, setNodes, markDirty, seedBoard, api]
+ [activeProjectId, emptyNodePos, setNodes, markDirty, seedBoard, api]
)
// Delete a session from the board — same confirm + teardown as the canvas Delete key.
diff --git a/src/renderer/lib/placement.test.ts b/src/renderer/lib/placement.test.ts
new file mode 100644
index 000000000..0a16a8234
--- /dev/null
+++ b/src/renderer/lib/placement.test.ts
@@ -0,0 +1,54 @@
+import { describe, it, expect } from 'vitest'
+import { freeSpot, type Box } from './placement'
+
+const size = { w: 100, h: 100 }
+
+describe('freeSpot', () => {
+ it('returns the preferred spot on an empty canvas', () => {
+ expect(freeSpot([], { x: 0, y: 0 }, size)).toEqual({ x: 0, y: 0 })
+ })
+
+ it('returns the preferred spot when it does not overlap anything', () => {
+ const existing: Box[] = [{ x: 500, y: 500, w: 100, h: 100 }]
+ expect(freeSpot(existing, { x: 0, y: 0 }, size)).toEqual({ x: 0, y: 0 })
+ })
+
+ it('moves the node off an occupied spot to a nearby clear one', () => {
+ const existing: Box[] = [{ x: 0, y: 0, w: 100, h: 100 }]
+ const spot = freeSpot(existing, { x: 0, y: 0 }, size)
+ expect(spot).not.toEqual({ x: 0, y: 0 })
+ // the chosen spot must not overlap the occupied box (with the default gap)
+ const overlaps = spot.x < 128 && spot.x + 128 > 0 && spot.y < 128 && spot.y + 128 > 0
+ expect(overlaps).toBe(false)
+ })
+
+ it('respects the gap: an adjacent-but-too-close spot is rejected, a spot a full step away is taken', () => {
+ // One box at origin; the first clear cell is a full (size+gap) step out.
+ const existing: Box[] = [{ x: 0, y: 0, w: 100, h: 100 }]
+ const spot = freeSpot(existing, { x: 0, y: 0 }, size, 28)
+ // nearest ring cell is 128px away on an axis
+ expect(Math.max(Math.abs(spot.x), Math.abs(spot.y))).toBe(128)
+ })
+
+ it('finds a hole in a packed grid rather than piling on', () => {
+ // Fill a 3x3 grid around origin EXCEPT the center; preferred=center → it should stay (clear),
+ // so instead leave the center occupied and a hole at (128,0).
+ const step = 128
+ const existing: Box[] = []
+ for (let gx = -1; gx <= 1; gx++)
+ for (let gy = -1; gy <= 1; gy++)
+ if (!(gx === 1 && gy === 0)) existing.push({ x: gx * step, y: gy * step, w: 100, h: 100 })
+ const spot = freeSpot(existing, { x: 0, y: 0 }, size)
+ expect(spot).toEqual({ x: 128, y: 0 }) // the one hole
+ })
+
+ it('never overlaps any existing node across a dense fill', () => {
+ const existing: Box[] = []
+ for (let i = 0; i < 20; i++) existing.push({ x: (i % 5) * 128, y: Math.floor(i / 5) * 128, w: 100, h: 100 })
+ const spot = freeSpot(existing, { x: 0, y: 0 }, size)
+ const clear = !existing.some(
+ (b) => spot.x < b.x + b.w + 28 && spot.x + 128 > b.x && spot.y < b.y + b.h + 28 && spot.y + 128 > b.y
+ )
+ expect(clear).toBe(true)
+ })
+})
diff --git a/src/renderer/lib/placement.ts b/src/renderer/lib/placement.ts
new file mode 100644
index 000000000..6bbdab706
--- /dev/null
+++ b/src/renderer/lib/placement.ts
@@ -0,0 +1,54 @@
+// Where to drop a NEW node when there is no cursor to place it at (the kanban board's "+ New
+// 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.
+
+export interface Box {
+ x: number
+ y: number
+ w: number
+ h: number
+}
+
+/**
+ * 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.
+ *
+ * `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).
+ */
+export function freeSpot(
+ existing: Box[],
+ preferred: { x: number; y: number },
+ size: { w: number; h: number },
+ gap = 28
+): { x: number; y: number } {
+ const clear = (x: number, y: number): boolean =>
+ !existing.some(
+ (b) =>
+ x < b.x + b.w + gap &&
+ x + size.w + gap > b.x &&
+ y < b.y + b.h + gap &&
+ y + size.h + gap > b.y
+ )
+
+ if (clear(preferred.x, preferred.y)) return preferred
+
+ 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
+ // clear cell. Nearest-first keeps new nodes close to where the user is looking.
+ for (let ring = 1; ring <= 60; 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 = preferred.x + dx * stepX
+ const y = preferred.y + dy * stepY
+ if (clear(x, y)) return { x, y }
+ }
+ }
+ }
+ return preferred
+}