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): save, restore, rename and delete named canvas layouts

Bas Milius66b9d50b073e
diff --git a/CLAUDE.md b/CLAUDE.md
index 7bbde2e50..108b78a97 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2923,6 +2923,69 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
shells boot — no new bridge member); mobile is N/A (no canvas, no camera); the kanban board is
likewise N/A, and a project that activates ON the board neither shows nor spends its
once-per-run resume card (it would sit invisible under the opaque overlay).
+- **Canvas layouts** (`@shared/canvas-layout`, `renderer/lib/canvasLayout.ts` capture/apply +
+ `renderer/lib/canvasLayoutView.ts` for the menu wording and the fallback camera; Dock button
+ after "Fit view", mirrored in ⌘K) - a NAMED SNAPSHOT OF NODE GEOMETRY (position, size,
+ collapse state) per project, so an arrangement built for the ultrawide can be restored after a
+ day on the laptop screen. Load-bearing rules:
+ - **Geometry only, and that is the whole safety story.** A restore never creates, deletes,
+ renames, recolors, reparents or respawns a node, and never touches a tmux session - so the
+ worst a bad layout can do is move things, which ⌘Z takes back (the debounced history effect
+ picks up the `setNodes` like any other placement, which is why restore has no confirm and
+ delete does).
+ - **The content half is git-shared, the camera half is machine-local.** `Project.layouts` rides
+ `.nodeterm/project.json` beside `nodes` and `kanban`, because node geometry is already shared
+ content in that file and a restore writes exactly those fields. `Project.layoutViewports` (this
+ machine's camera per layout) rides `IndexEntryV3` in `workspace.json`. **The camera precedent
+ (`viewport`, `breadcrumbs`) deliberately does NOT reach the geometry**: those are facts about
+ where one person was looking, and nobody else's canvas moves when I pan - but where the nodes
+ SIT is the canvas itself, and sharing an arrangement with the repo is the point.
+ - **Restore rules** (`applyLayout`, pure + tested): a live node the layout does not mention is
+ left exactly where it is, never tidied or stacked at the origin; an entry whose node is gone is
+ skipped and counted, never resurrected; a frame the layout addresses gets the rect the user
+ saved and is NOT re-fitted afterwards (the fit would overwrite it and the arrangement would
+ drift a little on every restore), while a frame the layout does not mention but whose
+ descendant just moved IS re-fitted, deepest first, so an out-of-layout child cannot be clamped
+ by `extent:'parent'` into an inverted range. The whole layout lands in ONE transform as an
+ explicit two-pass (resolve every target root origin, then emit) - a reduce over N placements
+ re-fits an ancestor between two of them, so the second node is measured against a frame the
+ first just moved and the result is differently wrong depending on array order. `collapsed` is
+ restored with the CHROME height on the node and the real one in `expandedHeight` (the
+ `flowToNodeStates` rule: the stored height is ALWAYS the expanded one, or a
+ save-while-collapsed shrinks the node permanently). `premaxRect` and every non-geometry field
+ ride the spread untouched - a restore is a placement, not a maximize.
+ - **The camera is applied with `setViewport`, NEVER `fitView`** - the "Go to node" invariant
+ above, and a canvas that has just been rearranged is exactly the unmeasured state where a
+ queued fit collapses the bounds and flies to the origin. This machine's recorded camera wins;
+ a layout restored here for the first time (a teammate's, or one saved on another machine) gets
+ `layoutFramingViewport`, which is the core `framingViewport` rule rewritten locally because the
+ renderer has no import path into `src/core` and because a layout's rects are ROOT-space, so
+ unlike `CanvasNodeState` positions every entry anchors the camera.
+ - **The window size is a LABEL, never a matcher.** `CanvasLayout.window` is the author's window
+ at save time, shown in the menu so the user can tell the two arrangements apart. Nothing
+ auto-applies a layout on a display change: the file travels, so matching on it would pick a
+ stranger's monitor for this user's screen - and a canvas that rearranges itself when you plug
+ in a projector is worse than one that does not.
+ - **Cap 20** (`CANVAS_LAYOUTS_CAP`; a full node-geometry list in a file that is committed and
+ cloned), name capped at 60, and **both sanitized on BOTH serializer seams** (`fileToProject`
+ on the way in, `projectToFile` on the way out) - the same two-seam rule `normalizeNodeIcon`
+ and `sanitizeNodeTriggers` follow, because live node data is reachable by a peer canvas
+ mutation and whatever we write is what the next machine trusts. `sanitizeLayouts` DROPS a
+ layout whole rather than repairing it: a repaired layout no longer describes the arrangement it
+ is named after, and a non-finite coordinate is a white-screen crash (`adoptUserNodes`
+ dereferences the position unguarded) that `JSON.stringify` then writes back as `null`.
+ - **Downgrade note:** a build older than this one drops `layouts` on its first save, because
+ `projectToFile` builds an explicit object and simply does not know the field. The layouts are
+ gone from that checkout's file until someone on a current build saves again; nothing else
+ breaks, and the machine-local cameras are pruned to match on the next load.
+ - **Surfaces:** Desktop full; **Server Edition full with NO new IPC** (pure renderer plus
+ `workspace.save`, which both shells already boot); **relay tabs REFUSED with the reason** -
+ the Dock button is disabled with "Layouts are managed on the host" and the ⌘K entries are
+ omitted (the palette has no disabled row), because a relay tab is a live connection to another
+ machine and never a workspace on this disk; kanban N/A (a board shows cards, and geometry is
+ what a column layout discards); mobile N/A - *nodeterm mobile* attaches to tmux sessions over
+ the transport protocol and has no canvas, so surfacing a layout means extending that protocol
+ (follow-up in the iOS repo).
- **Command palette** (`CommandPalette.tsx`): ⌘/Ctrl+K; `Canvas.buildCommands` (create,
switch project, jump to node by title/tag, open file…).
- **Explorer** (`ExplorerPanel.tsx`, 🗂 / ⌘⇧E): lazy file tree of the active project `cwd`
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 65aef4472..ff0fba812 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -379,6 +379,13 @@ from the target's `pendingLaunch` (`renderer/lib/edgeModel.ts`), and the context
writes stays hidden underneath it. One `open-claude --after` used to land three edges on one node.
`src/renderer/canvas/edge-model.source.test.ts` pins both halves.
+**A canvas layout is GEOMETRY, and its two halves live in different files.** A saved layout moves
+nodes and nothing else: it never creates, deletes, renames, reparents or respawns one, and never
+touches a tmux session. The snapshot itself (`Project.layouts`) is CONTENT and rides the git-shared
+`.nodeterm/project.json`, while this machine's camera per layout (`Project.layoutViewports`) is
+machine-local and rides `workspace.json` beside `viewport` and `breadcrumbs`. Restoring applies its
+camera with `setViewport`, per the `fitView` rule below.
+
**React Flow's `fitView` is queued, not immediate — never use it to frame something automatically.**
Calling it sets `fitViewQueued` and the fit runs from a later `setNodes` (only once every node is
measured) or the next `updateNodeInternals`, against whatever the node lookup holds by then; a fit
diff --git a/src/core/workspace-files.test.ts b/src/core/workspace-files.test.ts
index 93d104ca0..fd23c40bc 100644
--- a/src/core/workspace-files.test.ts
+++ b/src/core/workspace-files.test.ts
@@ -5,6 +5,7 @@ import {
sameProjectContent, splitWorkspace, serializeProjectFile
} from './workspace-files'
import { legacyFileId } from '../shared/project-id'
+import { CANVAS_LAYOUTS_CAP, type CanvasLayout } from '../shared/canvas-layout'
import type { ProjectFileV1 } from './workspace-files'
const node = (over: Partial<CanvasNodeState> = {}): CanvasNodeState => ({
@@ -172,6 +173,102 @@ describe('breadcrumbs are MACHINE-LOCAL, like viewport/capabilityAck', () => {
})
})
+describe('canvas layouts: shared CONTENT, machine-local CAMERAS', () => {
+ const layout = (over: Partial<CanvasLayout> = {}): CanvasLayout => ({
+ id: 'lay-1', name: 'Ultrawide', createdAt: 1000, updatedAt: 2000,
+ nodes: [{ id: 'term-abc', x: 10, y: 20, width: 400, height: 300 }], ...over
+ })
+
+ it('round-trips the layouts through the shared file and the cameras through the entry', () => {
+ const layouts = [layout()]
+ const layoutViewports = { 'lay-1': { x: 5, y: 6, zoom: 2 } }
+ const { index, files } = splitWorkspace(
+ { version: 2, activeProjectId: 'p1', projects: [project({ cwd: '/a/foo', layouts, layoutViewports })] },
+ () => 1,
+ '2026-09-07T00:00:00.000Z'
+ )
+ const file = files.get('/a/foo')!
+ expect(file.layouts).toEqual(layouts)
+ expect(index.entries[0].layoutViewports).toEqual(layoutViewports)
+
+ const restored = fileToProject(file, { id: 'p1', cwd: '/a/foo', layoutViewports })
+ expect(restored.layouts).toEqual(layouts)
+ expect(restored.layoutViewports).toEqual(layoutViewports)
+ })
+
+ it('never writes layoutViewports into the committed file, and never reads one planted there', () => {
+ const { files } = splitWorkspace(
+ {
+ version: 2, activeProjectId: 'p1',
+ projects: [project({ cwd: '/a/foo', layouts: [layout()], layoutViewports: { 'lay-1': { x: 5, y: 6, zoom: 2 } } })]
+ },
+ () => 1,
+ 'ts'
+ )
+ const raw = serializeProjectFile(files.get('/a/foo')!)
+ expect(raw).not.toContain('layoutViewports')
+
+ // A file-borne `layoutViewports` is a forgery (a repo carrying one person's camera).
+ const forged = fileToProject(
+ { ...files.get('/a/foo')!, layoutViewports: { 'lay-1': { x: 9, y: 9, zoom: 9 } } } as never,
+ { id: 'p1', cwd: '/a/foo' }
+ )
+ expect(forged.layoutViewports).toBeUndefined()
+ })
+
+ it('a project with no layouts adds no bytes to the committed file', () => {
+ const f = projectToFile(project(), 1, 'ts')
+ expect('layouts' in f).toBe(false)
+ expect(serializeProjectFile(f)).not.toContain('layouts')
+ })
+
+ // Mutation pin, the shape the node-icon rules use: each seam must refuse a hostile layout on its
+ // own, because validating one direction passes every round-trip test while leaving the other one
+ // open to a peer canvas mutation or a hand edit.
+ it('drops a hostile layout INDEPENDENTLY in each direction', () => {
+ const hostile = layout({ nodes: [{ id: 'term-abc', x: NaN, y: 0, width: 1, height: 1 }] })
+
+ // Way out: a bad layout on live project data never reaches the committed file.
+ const f = projectToFile(project({ layouts: [hostile] }), 1, 'ts')
+ expect(f.layouts).toBeUndefined()
+ expect(serializeProjectFile(f)).not.toContain('Ultrawide')
+
+ // Way in: a bad layout planted in the file never reaches the live project.
+ const planted = fileToProject(
+ { ...projectToFile(project(), 1, 'ts'), layouts: [hostile] },
+ { id: 'p1' }
+ )
+ expect(planted.layouts).toBeUndefined()
+ })
+
+ it('prunes a camera naming no live layout, on save and on load', () => {
+ const layouts = [layout()]
+ const layoutViewports = {
+ 'lay-1': { x: 1, y: 2, zoom: 1 },
+ 'lay-gone': { x: 3, y: 4, zoom: 2 }
+ }
+ const { index, files } = splitWorkspace(
+ { version: 2, activeProjectId: 'p1', projects: [project({ cwd: '/a/foo', layouts, layoutViewports })] },
+ () => 1,
+ 'ts'
+ )
+ expect(index.entries[0].layoutViewports).toEqual({ 'lay-1': { x: 1, y: 2, zoom: 1 } })
+
+ // …and again on the way in, so a layout a teammate deleted cannot leave a permanent orphan.
+ const restored = fileToProject(files.get('/a/foo')!, { id: 'p1', cwd: '/a/foo', layoutViewports })
+ expect(restored.layoutViewports).toEqual({ 'lay-1': { x: 1, y: 2, zoom: 1 } })
+ })
+
+ it('caps an over-long list in both directions', () => {
+ const many = Array.from({ length: CANVAS_LAYOUTS_CAP + 3 }, (_, i) => layout({ id: `lay-${i}` }))
+ const f = projectToFile(project({ layouts: many }), 1, 'ts')
+ expect(f.layouts).toHaveLength(CANVAS_LAYOUTS_CAP)
+
+ const back = fileToProject({ ...f, layouts: many }, { id: 'p1' })
+ expect(back.layouts).toHaveLength(CANVAS_LAYOUTS_CAP)
+ })
+})
+
describe('sameProjectContent', () => {
it('ignores rev and savedAt, sees node changes', () => {
const a = projectToFile(project(), 1, '2026-01-01T00:00:00.000Z')
diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.ts
index faf80c888..3a4105af6 100644
--- a/src/core/workspace-files.ts
+++ b/src/core/workspace-files.ts
@@ -14,6 +14,12 @@ import { projectCapabilityFields, readProjectCapabilities } from '../shared/proj
import { loadedAgentBrowserPartition } from '../shared/browser-partition'
import { sanitizeProjectIcon, type ProjectIcon } from '../shared/project-icon'
import { sanitizeTriggerSpec } from '../shared/trigger'
+import {
+ pruneLayoutViewports,
+ sanitizeLayouts,
+ type CanvasLayout,
+ type LayoutViewports
+} from '../shared/canvas-layout'
/**
* Drop a browser node's persisted `partition` unless it is exactly the jar THIS project (its
@@ -147,6 +153,16 @@ export interface ProjectFileV1 {
agentMessaging?: boolean
dinoHighScore?: number
kanban?: ProjectKanban
+ /**
+ * Named geometry snapshots for this canvas (@shared/canvas-layout). CONTENT, exactly like
+ * `kanban`: an arrangement is a fact about the nodes this file already carries, and restoring
+ * one writes those same node fields, so a teammate's checkout is entitled to it.
+ *
+ * Re-sanitized in BOTH directions (`fileToProject` on the way in, `projectToFile` on the way
+ * out), see `sanitizeLayouts`. The per-layout CAMERA is not here and never will be: it is
+ * machine-local and rides `IndexEntryV3.layoutViewports`, the same rule as `viewport`.
+ */
+ layouts?: CanvasLayout[]
// NOTE: closedSessions is deliberately NOT here — see `Project.closedSessions` /
// `IndexEntryV3.closedSessions`. It is machine-local, like `viewport`/`breadcrumbs`.
}
@@ -203,6 +219,14 @@ export interface IndexEntryV3 {
/** MACHINE-LOCAL camera navigation history for a ref'd project. Same rule as `viewport`: this
* user's "where was I" is not something a repo shares. See NavStop. */
breadcrumbs?: NavStop[]
+ /**
+ * MACHINE-LOCAL camera per canvas layout, keyed by layout id (@shared/canvas-layout). The
+ * layouts themselves are shared CONTENT in the project file; where THIS user was looking when
+ * they saved one is not, same rule as `viewport` and `breadcrumbs` above. Pruned against the
+ * live layouts on every load and save (`pruneLayoutViewports`), because workspace.json is
+ * forever and a canvas churns through ids.
+ */
+ layoutViewports?: LayoutViewports
/**
* MACHINE-LOCAL closed-session history for a ref'd project (folder or ssh) — see
* `Project.closedSessions`. Whose trash can holds what deleted nodes is a per-machine fact, not
@@ -327,6 +351,12 @@ export function projectToFile(
stripSharedNodeExec(p.cwd ? toPortableNodes(p.nodes, p.cwd) : p.nodes)
)
const icon = sanitizeProjectIcon(p.icon)
+ // The SECOND seam for layouts. Live project data is reachable by a peer canvas mutation and by a
+ // hand edit that already got past a read, and whatever we write is what the next machine trusts:
+ // the same reason `normalizeNodeIcon` and `sanitizeNodeTriggers` validate on the way OUT as well
+ // as IN. Validating one direction only passes every round-trip test while leaving the other one
+ // open. See @shared/canvas-layout.
+ const layouts = sanitizeLayouts(p.layouts)
return {
version: 1,
rev,
@@ -345,7 +375,10 @@ export function projectToFile(
// the acknowledgment is machine-local (IndexEntryV3.capabilityAck) and must never travel.
...projectCapabilityFields(p),
...(p.dinoHighScore ? { dinoHighScore: p.dinoHighScore } : {}),
- ...(p.kanban ? { kanban: p.kanban } : {})
+ ...(p.kanban ? { kanban: p.kanban } : {}),
+ // `layoutViewports` is deliberately absent: a field of that name in the shared file is a
+ // forgery (a repo carrying one person's camera), and `fileToProject` never reads one.
+ ...(layouts ? { layouts } : {})
}
}
@@ -453,6 +486,10 @@ export function fileToProject(
capabilityAck?: import('../shared/project-capability-consent').CapabilityAckMap
/** This machine's navigation history for this entry (never from the file). */
breadcrumbs?: NavStop[]
+ /** This machine's camera per canvas layout for this entry. Taken from the index entry ONLY: a
+ * field of this name in the shared file is a forgery and is never read. Pruned below against
+ * the layouts the file actually carries. */
+ layoutViewports?: LayoutViewports
/** This machine's closed-session history for this entry (never from the file) — already
* validated/capped/trigger-sanitized by the caller (`sanitizeLoadedClosedSessions`). */
closedSessions?: ClosedSessionEntry[]
@@ -464,6 +501,11 @@ export function fileToProject(
): Project {
const defaultAccountId = base.defaultAccountId ?? f.defaultAccountId
const icon = sanitizeProjectIcon(f.icon)
+ const layouts = sanitizeLayouts(f.layouts)
+ // A camera for a layout the file no longer carries names nothing: a teammate deleted the layout
+ // (they are shared content, the cameras are not), or a hand edit dropped it. Pruning on the way
+ // in as well as out is what stops workspace.json accumulating orphans forever.
+ const layoutViewports = pruneLayoutViewports(base.layoutViewports, layouts)
return {
id: base.id,
// A project whose stored name IS its own path is one this machine (or a teammate's) created
@@ -508,7 +550,10 @@ export function fileToProject(
...(base.breadcrumbs?.length ? { breadcrumbs: base.breadcrumbs } : {}),
// Machine-local, from the index entry ONLY, same rule as `breadcrumbs`: a file field named
// `closedSessions` is never read here — the shared file cannot carry this machine's trash can.
- ...(base.closedSessions?.length ? { closedSessions: base.closedSessions } : {})
+ ...(base.closedSessions?.length ? { closedSessions: base.closedSessions } : {}),
+ ...(layouts ? { layouts } : {}),
+ // Machine-local, from the index entry ONLY, same rule as `breadcrumbs`.
+ ...(layoutViewports ? { layoutViewports } : {})
}
}
@@ -608,6 +653,7 @@ export function splitWorkspace(
// empty stand-in, and writing it would forget where the user actually was; `WorkspaceStore.save`
// restores both from the previous entry instead, exactly as it does for `cache`/`localExec`.
// Inline entries need none of this: they store the whole Project verbatim.
+ const layoutViews = pruneLayoutViewports(p.layoutViewports, sanitizeLayouts(p.layouts))
const localState = {
...(p.viewport ? { viewport: p.viewport } : {}),
...(p.defaultAccountId ? { defaultAccountId: p.defaultAccountId } : {}),
@@ -620,7 +666,10 @@ export function splitWorkspace(
// written back uncapped.
...(p.closedSessions?.length
? { closedSessions: p.closedSessions.slice(0, CLOSED_SESSIONS_CAP) }
- : {})
+ : {}),
+ // The layouts themselves are content and ride the file; only this machine's camera per
+ // layout is kept here, pruned against the layouts that will actually be written.
+ ...(layoutViews ? { layoutViewports: layoutViews } : {})
}
if (p.unavailable) {
// Placeholder (folder missing / server unreachable at load): its nodes:[] is not real
diff --git a/src/core/workspace-store.test.ts b/src/core/workspace-store.test.ts
index cddb9d9bc..02aa55621 100644
--- a/src/core/workspace-store.test.ts
+++ b/src/core/workspace-store.test.ts
@@ -88,6 +88,71 @@ describe('save → load round trip (v3)', () => {
expect(loaded.projects[0].breadcrumbs).toEqual(breadcrumbs)
})
+ // A canvas layout is shared CONTENT (it describes the nodes the file already carries), while the
+ // camera the author had per layout is one person's, exactly like `breadcrumbs`.
+ it('keeps layouts in the shared file and their cameras machine-local', async () => {
+ const layouts = [{
+ id: 'lay-1', name: 'Ultrawide', createdAt: 1_700_000_000_000, updatedAt: 1_700_000_000_000,
+ window: { width: 3440, height: 1440 },
+ nodes: [{ id: 'term-1', x: 40, y: 60, width: 800, height: 600 }]
+ }]
+ const layoutViewports = { 'lay-1': { x: 5, y: 6, zoom: 1.5 } }
+ await new WorkspaceStore().save(ws([project({ cwd: projRoot, layouts, layoutViewports })]))
+
+ const fileRaw = await fs.readFile(path.join(projRoot, '.nodeterm/project.json'), 'utf-8')
+ expect(JSON.parse(fileRaw).layouts).toEqual(layouts)
+ expect(fileRaw).not.toContain('layoutViewports')
+ const index = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))
+ expect(index.entries[0].layoutViewports).toEqual(layoutViewports)
+
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects[0].layouts).toEqual(layouts)
+ expect(loaded.projects[0].layoutViewports).toEqual(layoutViewports)
+ })
+
+ it('drops a hand-edited layout and prunes the camera it left behind', async () => {
+ const layouts = [{
+ id: 'lay-1', name: 'Ultrawide', createdAt: 1, updatedAt: 2,
+ nodes: [{ id: 'term-1', x: 0, y: 0, width: 10, height: 10 }]
+ }]
+ await new WorkspaceStore().save(ws([project({ cwd: projRoot, layouts, layoutViewports: { 'lay-1': { x: 1, y: 2, zoom: 1 } } })]))
+
+ // A `null` coordinate is what `JSON.stringify` writes for a NaN, so this is the shape a
+ // corrupted file really arrives in - and unguarded it reaches React Flow's adoptUserNodes.
+ const file = path.join(projRoot, '.nodeterm/project.json')
+ const parsed = JSON.parse(await fs.readFile(file, 'utf-8'))
+ parsed.layouts[0].nodes[0].x = null
+ await fs.writeFile(file, JSON.stringify(parsed, null, 2))
+
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects[0].nodes[0].id).toBe('term-1') // the rest of the file still loaded
+ expect(loaded.projects[0].layouts).toBeUndefined()
+ expect(loaded.projects[0].layoutViewports).toBeUndefined()
+ })
+
+ it('sanitizes an inline project\'s embedded layouts, which never pass through fileToProject', async () => {
+ const index = {
+ version: 3,
+ activeProjectId: 'p2',
+ entries: [{
+ id: 'p2', name: 'inline', color: '#fff',
+ project: {
+ ...project({ id: 'p2', name: 'inline' }),
+ layouts: [
+ { id: 'lay-ok', name: 'Laptop', createdAt: 1, updatedAt: 2, nodes: [] },
+ { id: 'lay-bad', name: 'Broken', createdAt: 1, updatedAt: 2, nodes: [{ id: 'term-1', x: null, y: 0, width: 1, height: 1 }] }
+ ],
+ layoutViewports: { 'lay-ok': { x: 1, y: 2, zoom: 1 }, 'lay-bad': { x: 0, y: 0, zoom: 1 } }
+ }
+ }]
+ }
+ await fs.writeFile(path.join(userData, 'workspace.json'), JSON.stringify(index))
+
+ const loaded = await new WorkspaceStore().load()
+ expect(loaded.projects[0].layouts?.map((l) => l.id)).toEqual(['lay-ok'])
+ expect(loaded.projects[0].layoutViewports).toEqual({ 'lay-ok': { x: 1, y: 2, zoom: 1 } })
+ })
+
it('does not rewrite (or bump rev of) an unchanged project file', async () => {
const store = new WorkspaceStore()
const w = ws([project({ cwd: projRoot })])
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index dd881aee2..c18803c48 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -26,6 +26,11 @@ import { readProjectCapabilities, type ProjectCapability } from '../shared/proje
import type { CapabilityAckMap } from './project-capability-consent'
import { hoistLegacyNodeExec, type LocalNodeExecMap } from '../shared/node-exec'
import { collisionSeed, derivedProjectId, freshProjectId } from '../shared/project-id'
+import {
+ pruneLayoutViewports,
+ sanitizeLayoutViewports,
+ sanitizeLayouts
+} from '../shared/canvas-layout'
import { appendProjectNode, removeProjectNode, type RemoteNodeInput } from './project-node-append'
/** Checked remote read: `absent` (no file — safe to push our cache) is NOT `error` (connection
@@ -292,6 +297,11 @@ export class WorkspaceStore {
// re-normalize each snapshot's trigger spec. Sanitized ONCE here so every downstream reader
// of `e.closedSessions` (fileToProject, readLocalRef, the ssh reconcile paths) can trust it.
entry.closedSessions = sanitizeLoadedClosedSessions(entry.closedSessions)
+ // Same rule for this machine's per-layout cameras: workspace.json is hand-editable input,
+ // and a non-finite `zoom` reaching `setViewport` blanks the canvas. Pruning against the live
+ // layouts happens later, in `fileToProject`, which is the first point that knows what the
+ // project file actually carries.
+ entry.layoutViewports = sanitizeLayoutViewports(entry.layoutViewports)
}
this.index = index
const built: LoadedEntry[] = []
@@ -308,8 +318,13 @@ export class WorkspaceStore {
// same kanban shape guard here — a v1/hand-edited board would otherwise crash the render —
// and the same trigger shape rule (workspace.json is hand-editable input too).
// `rest` drops BOTH guarded fields; each is added back below only if it passes its guard.
- const { kanban, closedSessions, ...rest } = e.project
+ const { kanban, closedSessions, layouts, layoutViewports, ...rest } = e.project
const base = validKanban(kanban) ? { ...rest, kanban } : rest
+ // An inline project's embedded layouts are hand-editable input exactly like a git-shared
+ // file's, and they never pass through `fileToProject` on this branch, so they are
+ // sanitized (and their cameras pruned against them) here instead.
+ const admitted = sanitizeLayouts(layouts)
+ const views = pruneLayoutViewports(sanitizeLayoutViewports(layoutViewports), admitted)
// Same treatment for `closedSessions` as the ref'd-project entries above, and for the
// same reason: a malformed value here reaches `mergeClosedHistory`, which iterates it (a
// non-array throws and takes the whole sidebar render down) and hands each entry's node
@@ -320,7 +335,9 @@ export class WorkspaceStore {
project: {
...base,
nodes: sanitizeNodeTriggers(base.nodes),
- ...(history ? { closedSessions: history } : {})
+ ...(history ? { closedSessions: history } : {}),
+ ...(admitted ? { layouts: admitted } : {}),
+ ...(views ? { layoutViewports: views } : {})
}
})
} else if (e.cwd) {
@@ -345,6 +362,7 @@ export class WorkspaceStore {
defaultAccountId: e.defaultAccountId,
breadcrumbs: e.breadcrumbs,
closedSessions: e.closedSessions,
+ layoutViewports: e.layoutViewports,
capabilityAck: e.capabilityAck,
localExec: this.execOverlay(e, p)
})
@@ -367,6 +385,7 @@ export class WorkspaceStore {
defaultAccountId: e.defaultAccountId,
breadcrumbs: e.breadcrumbs,
closedSessions: e.closedSessions,
+ layoutViewports: e.layoutViewports,
capabilityAck: e.capabilityAck,
localExec: this.execOverlay(e, e.cache)
})
@@ -852,6 +871,7 @@ export class WorkspaceStore {
defaultAccountId: e.defaultAccountId,
breadcrumbs: e.breadcrumbs,
closedSessions: e.closedSessions,
+ layoutViewports: e.layoutViewports,
capabilityAck: e.capabilityAck,
localExec: this.execOverlay(e, read.file)
})
@@ -972,6 +992,10 @@ export class WorkspaceStore {
// deleted), so without this an unavailable window would silently forget the user's trash
// can the moment splitWorkspace rebuilds the index.
if (old?.closedSessions) e.closedSessions = old.closedSessions
+ // Same rule again: a placeholder carries no layouts, so `splitWorkspace` pruned its
+ // cameras away against an empty list. Restoring them keeps the user's per-layout camera
+ // for when the ref becomes readable again.
+ if (old?.layoutViewports) e.layoutViewports = old.layoutViewports
// The clone-notice acknowledgment must also survive an unavailable window: forgetting it
// would re-raise a notice the user already answered the moment the folder remounts.
if (old?.capabilityAck) e.capabilityAck = old.capabilityAck
@@ -1227,6 +1251,7 @@ export class WorkspaceStore {
defaultAccountId: e.defaultAccountId,
breadcrumbs: e.breadcrumbs,
closedSessions: e.closedSessions,
+ layoutViewports: e.layoutViewports,
capabilityAck: e.capabilityAck,
localExec: e.localExec
})
@@ -1590,6 +1615,7 @@ export class WorkspaceStore {
defaultAccountId: e.defaultAccountId,
breadcrumbs: e.breadcrumbs,
closedSessions: e.closedSessions,
+ layoutViewports: e.layoutViewports,
capabilityAck: e.capabilityAck,
localExec: e.localExec
})
@@ -1648,6 +1674,7 @@ export class WorkspaceStore {
defaultAccountId: e.defaultAccountId,
breadcrumbs: e.breadcrumbs,
closedSessions: e.closedSessions,
+ layoutViewports: e.layoutViewports,
capabilityAck: e.capabilityAck,
localExec: e.localExec
})
@@ -1716,7 +1743,7 @@ export class WorkspaceStore {
return fileToProject(e.cache, {
id: e.id, ssh: e.ssh, closed: e.closed, closedAt: e.closedAt,
viewport: e.viewport, defaultAccountId: e.defaultAccountId, breadcrumbs: e.breadcrumbs,
- closedSessions: e.closedSessions,
+ closedSessions: e.closedSessions, layoutViewports: e.layoutViewports,
capabilityAck: e.capabilityAck, localExec: e.localExec
})
}
@@ -1864,7 +1891,7 @@ export class WorkspaceStore {
return fileToProject(adopted, {
id: e.id, ssh: e.ssh, closed: e.closed, closedAt: e.closedAt,
viewport: e.viewport, defaultAccountId: e.defaultAccountId, breadcrumbs: e.breadcrumbs,
- closedSessions: e.closedSessions,
+ closedSessions: e.closedSessions, layoutViewports: e.layoutViewports,
capabilityAck: e.capabilityAck, localExec: e.localExec
})
}
@@ -1880,7 +1907,7 @@ export class WorkspaceStore {
merged = fileToProject(e.cache, {
id: e.id, ssh: e.ssh, closed: e.closed, closedAt: e.closedAt,
viewport: e.viewport, defaultAccountId: e.defaultAccountId, breadcrumbs: e.breadcrumbs,
- closedSessions: e.closedSessions,
+ closedSessions: e.closedSessions, layoutViewports: e.layoutViewports,
capabilityAck: e.capabilityAck, localExec: e.localExec
})
}
@@ -1942,9 +1969,22 @@ function migrateLegacy(parsed: unknown): Workspace {
// runs and takes the sidebar render down on the very first load.
const projects = ws.projects.map((p) => {
const history = sanitizeLoadedClosedSessions(p.closedSessions)
- if (history === p.closedSessions) return p
- const { closedSessions: _dropped, ...rest } = p
- return history ? { ...rest, closedSessions: history } : rest
+ // Same reason as `closedSessions` above, for the geometry snapshots: this path skips loadV3
+ // entirely, so a non-finite coordinate would reach React Flow before the first save ever
+ // migrates the file.
+ const layouts = sanitizeLayouts(p.layouts)
+ const views = pruneLayoutViewports(sanitizeLayoutViewports(p.layoutViewports), layouts)
+ const unchanged = history === p.closedSessions
+ && layouts === p.layouts
+ && views === p.layoutViewports
+ if (unchanged) return p
+ const { closedSessions: _c, layouts: _l, layoutViewports: _v, ...rest } = p
+ return {
+ ...rest,
+ ...(history ? { closedSessions: history } : {}),
+ ...(layouts ? { layouts } : {}),
+ ...(views ? { layoutViewports: views } : {})
+ }
})
return { version: 2, activeProjectId: active, projects }
}
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 3097cf267..6a58947d4 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -461,6 +461,14 @@ import {
stateToReopenSnapshot
} from '../lib/closedHistory'
import { uuid } from '../lib/uuid'
+import { CANVAS_LAYOUTS_CAP, findLayoutByName, type CanvasLayout } from '@shared/canvas-layout'
+import { applyLayout, captureLayout } from '../lib/canvasLayout'
+import {
+ layoutFramingViewport,
+ restoreSummary,
+ saveLayoutRefusal,
+ sortedLayouts
+} from '../lib/canvasLayoutView'
import { planReopen, type ReopenPlan } from '../lib/reopenPlan'
import { oneLine } from '@shared/one-line'
import { invalidNodeColorMessage, isNodeColor } from '@shared/node-colors'
@@ -6714,6 +6722,168 @@ export function Canvas() {
fitAll()
}, [setNodes, markDirty, fitAll])
+ /** Report a refusal the user cannot act on any other way. One dismiss button, no default. */
+ const alertLayout = useCallback(
+ (message: string) => {
+ setConfirm({ message, alert: true, onConfirm: () => setConfirm(null) })
+ },
+ [setConfirm]
+ )
+
+ /**
+ * Save the live canvas geometry as a named layout.
+ *
+ * The two halves land together (`saveLayout` writes the shared snapshot and this machine's camera
+ * in ONE store update), and the name is asked for BEFORE anything is captured so a cancel costs
+ * nothing. A name that already exists offers to replace, reusing that layout's id: appending a
+ * second "Ultrawide" would leave the user with two rows they cannot tell apart, and the menu is
+ * sorted by name so they would sit on top of each other.
+ */
+ const saveCanvasLayout = useCallback(async () => {
+ const projectId = useProjects.getState().activeProjectId
+ if (!projectId) return
+ const typed = await promptDialog({
+ message: 'Name this layout',
+ placeholder: 'e.g. Ultrawide',
+ confirmLabel: 'Save'
+ })
+ if (typed === null) return
+ const name = typed.trim()
+ if (!name) {
+ alertLayout('A layout needs a name.')
+ return
+ }
+ const store = () => useProjects.getState()
+ const write = (id: string): void => {
+ const layout = captureLayout(nodesRef.current, {
+ id,
+ name,
+ now: Date.now(),
+ // The AUTHOR's window, kept as a label so they can tell the ultrawide arrangement from the
+ // laptop one. Never a matcher: the file travels, so nothing here selects a layout for you.
+ window: { width: window.innerWidth, height: window.innerHeight }
+ })
+ const refusal = saveLayoutRefusal(store().saveLayout(projectId, layout, getViewport(), Date.now()))
+ if (refusal) alertLayout(refusal)
+ }
+ // Re-read the project rather than closing over it: the dialog above is awaited, and a git pull
+ // or a teammate's save can land a layout with this name while it is open.
+ const existing = findLayoutByName(store().getProject(projectId)?.layouts, name)
+ if (!existing) {
+ write(uuid())
+ return
+ }
+ setConfirm({
+ message: `A layout named "${existing.name}" already exists. Replace it?`,
+ confirmLabel: 'Replace',
+ onConfirm: () => {
+ setConfirm(null)
+ write(existing.id)
+ }
+ })
+ }, [alertLayout, setConfirm, getViewport])
+
+ /**
+ * Put the canvas back the way a layout recorded it.
+ *
+ * No confirm, deliberately: this moves nodes and does nothing else - no session is touched, no
+ * node is created or deleted - and the debounced history effect picks the `setNodes` up, so ⌘Z
+ * takes it back.
+ *
+ * The camera is applied with `setViewport` and NEVER `fitView`, for the reason `frameNode`
+ * states at length: a fitView is QUEUED and resolves later against whatever is measured by then,
+ * which on a canvas that has just been rearranged is the origin jump. This machine's own camera
+ * for the layout wins; a layout restored here for the first time (a teammate's, or one saved on
+ * another machine) gets a camera derived from the layout's own rects instead.
+ */
+ const restoreCanvasLayout = useCallback(
+ (layout: CanvasLayout) => {
+ const projectId = useProjects.getState().activeProjectId
+ if (!projectId) return
+ const before = nodesRef.current
+ const result = applyLayout(before, layout)
+ // Same array back = the layout addressed nothing live. Marking dirty there would bump the
+ // project rev, and write a new revision of a shared file, for a canvas that did not move.
+ if (result.nodes !== before) {
+ setNodes(result.nodes)
+ markDirty()
+ }
+ const project = useProjects.getState().getProject(projectId)
+ const viewport = project?.layoutViewports?.[layout.id] ?? layoutFramingViewport(layout.nodes)
+ void setViewport(viewport, { duration: 300 })
+ // Machine-local, so this rewrites the index entry and not the shared project file: the next
+ // restore on THIS machine lands on the camera the user is looking at now.
+ useProjects.getState().recordLayoutViewport(projectId, layout.id, viewport)
+ setNotice({ kind: 'info', text: restoreSummary(layout.name, result) })
+ },
+ [setNodes, markDirty, setViewport]
+ )
+
+ /**
+ * Rename a layout.
+ *
+ * A name another layout already holds is REFUSED rather than offered as a replace. Replacing on
+ * save overwrites the snapshot the user is looking at, which is what they asked for; replacing on
+ * rename would DELETE a different layout the user never named in the gesture - a destructive act
+ * hiding inside an edit.
+ */
+ const renameCanvasLayout = useCallback(
+ async (layout: CanvasLayout) => {
+ const projectId = useProjects.getState().activeProjectId
+ if (!projectId) return
+ const typed = await promptDialog({
+ message: 'Rename layout',
+ initialValue: layout.name,
+ confirmLabel: 'Rename'
+ })
+ if (typed === null) return
+ const name = typed.trim()
+ if (!name) {
+ alertLayout('A layout needs a name.')
+ return
+ }
+ const clash = findLayoutByName(useProjects.getState().getProject(projectId)?.layouts, name)
+ if (clash && clash.id !== layout.id) {
+ alertLayout(`Another layout is already called "${clash.name}". Pick a different name.`)
+ return
+ }
+ useProjects.getState().renameLayout(projectId, layout.id, name, Date.now())
+ },
+ [alertLayout]
+ )
+
+ /**
+ * Delete a layout. Confirmed because it is the one action here that cannot be undone - a restore
+ * only moves nodes, and this drops the arrangement itself.
+ *
+ * A project with a folder says so in the dialog: `layouts` rides the git-shared
+ * `.nodeterm/project.json`, so the delete reaches everyone on their next pull.
+ */
+ const deleteCanvasLayout = useCallback(
+ (layout: CanvasLayout) => {
+ const projectId = useProjects.getState().activeProjectId
+ if (!projectId) return
+ // A layout is CONTENT, so it lives in the project's own .nodeterm/project.json wherever that
+ // file is: in the repo for a folder project, on the host for an SSH one. Both are shared with
+ // whoever else opens that project, so both get the sentence. Only a cwd-less canvas keeps its
+ // file inside this machine's userData and is genuinely nobody else's.
+ const project = useProjects.getState().getProject(projectId)
+ const shared = !!(project?.cwd || project?.ssh)
+ setConfirm({
+ message: shared
+ ? `Delete the layout "${layout.name}"? It is shared with the project, so it goes for everyone who opens it. This cannot be undone.`
+ : `Delete the layout "${layout.name}"? This cannot be undone.`,
+ confirmLabel: 'Delete',
+ danger: true,
+ onConfirm: () => {
+ setConfirm(null)
+ useProjects.getState().deleteLayout(projectId, layout.id)
+ }
+ })
+ },
+ [setConfirm]
+ )
+
const toggleCollapseNodes = useCallback(
(ids: string[]) => {
const set = new Set(ids)
@@ -13081,6 +13251,30 @@ export function Canvas() {
]
: []),
{ id: 'zoom-100', label: 'Zoom to 100%', icon: <IconFit />, run: zoomTo100 },
+ // Layouts mirror the Dock's menu, and both are withheld on a relay tab for the same reason:
+ // it is a live connection to another machine, never a workspace on this disk. The Dock says
+ // so on a disabled button; the palette has no disabled row, so the entries are omitted.
+ ...(activeProject?.remote
+ ? []
+ : [
+ {
+ id: 'save-layout',
+ label: 'Save canvas layout…',
+ hint: 'arrangement snapshot monitor screen restore',
+ section: 'View',
+ icon: <IconCanvasView />,
+ run: () => void saveCanvasLayout()
+ } satisfies Command,
+ ...sortedLayouts(activeProject?.layouts).map(
+ (layout): Command => ({
+ id: `restore-layout-${layout.id}`,
+ label: `Restore layout: ${layout.name}`,
+ section: 'View',
+ icon: <IconCanvasView />,
+ run: () => restoreCanvasLayout(layout)
+ })
+ )
+ ]),
{ id: 'save', label: 'Save', icon: <IconSave />, run: () => void persist() },
// Hidden when the canvas has no restartable agent node — the row would have nothing to act
// on. `hint` is searchable, so "new model" / "update" find it too.
@@ -13188,6 +13382,8 @@ export function Canvas() {
zoomTo100,
arrangeAllNodes,
hasArrangeableNodes,
+ saveCanvasLayout,
+ restoreCanvasLayout,
toggleFocusMode
])
@@ -14232,6 +14428,10 @@ export function Canvas() {
onAddWorktree={() => openWorktreeDialog(null)}
onSave={persist}
onFitView={fitAll}
+ onSaveLayout={() => void saveCanvasLayout()}
+ onRestoreLayout={restoreCanvasLayout}
+ onRenameLayout={(layout) => void renameCanvasLayout(layout)}
+ onDeleteLayout={deleteCanvasLayout}
onZoomIn={() => zoomIn({ duration: ZOOM_STEP_DURATION_MS })}
onZoomOut={() => zoomOut({ duration: ZOOM_STEP_DURATION_MS })}
onZoomTo={zoomToPct}
diff --git a/src/renderer/components/Dock.tsx b/src/renderer/components/Dock.tsx
index 612afd246..ad1bd34a8 100644
--- a/src/renderer/components/Dock.tsx
+++ b/src/renderer/components/Dock.tsx
@@ -1,5 +1,6 @@
import { useState } from 'react'
import { AGENT_CONFIG, BUILTIN_AGENT_IDS, type AgentId, type BuiltinAgentId } from '@shared/agents/config'
+import type { CanvasLayout } from '@shared/canvas-layout'
import type { CustomAgent } from '@shared/types'
import { formatShortcut, isHoldChord } from '@shared/shortcut'
import { hasSpeechModel } from '@shared/speech'
@@ -9,6 +10,7 @@ import { useSettings } from '../state/settings'
import { useProjects } from '../state/projects'
import { accountsForProject, sshAccountsHint } from '../state/workspace'
import { CONTENT_ADD_ITEMS, contentAddItemsToDockRows, type AddHandlers } from '../lib/addMenuSpec'
+import { layoutSubtitle, sortedLayouts } from '../lib/canvasLayoutView'
import { ZOOM_PRESETS, activeZoomPreset } from '../lib/zoomPresets'
import { Tooltip } from './Tooltip'
@@ -44,6 +46,13 @@ interface DockProps {
onGoForward: () => void
onSave: () => void
onFitView: () => void
+ /** Saves the current arrangement under a name the user is asked for. */
+ onSaveLayout: () => void
+ /** Puts the canvas back the way `layout` recorded it. No confirm: it moves nodes and nothing
+ * else, and the undo stack picks it up like any other placement. */
+ onRestoreLayout: (layout: CanvasLayout) => void
+ onRenameLayout: (layout: CanvasLayout) => void
+ onDeleteLayout: (layout: CanvasLayout) => void
onZoomIn: () => void
onZoomOut: () => void
/** Jump to an exact zoom (a preset percentage), holding the screen centre still. */
@@ -83,6 +92,10 @@ export function Dock({
onGoForward,
onSave,
onFitView,
+ onSaveLayout,
+ onRestoreLayout,
+ onRenameLayout,
+ onDeleteLayout,
onZoomIn,
onZoomOut,
onZoomTo,
@@ -91,6 +104,7 @@ export function Dock({
}: DockProps) {
const [menuOpen, setMenuOpen] = useState(false)
const [zoomMenuOpen, setZoomMenuOpen] = useState(false)
+ const [layoutMenuOpen, setLayoutMenuOpen] = useState(false)
// Which builtin's flyout submenu is open (at most one). A builtin earns a flyout only when it has
// ≥1 inheriting custom agent (one with a `baseAgent` matching it); otherwise it stays a flat
// button, byte-identical to before this nesting existed.
@@ -143,6 +157,20 @@ export function Dock({
setZoomMenuOpen(false)
}
+ const pickLayout = (fn: () => void) => () => {
+ fn()
+ setLayoutMenuOpen(false)
+ }
+
+ // A relay tab is a live connection to another machine, never a workspace on this disk, so there
+ // is nothing here to write a layout into. Disabled with the reason rather than hidden - the rule
+ // this repo sets for the cwd-less add-menu rows and the trigger card.
+ const layoutsDisabled = !!activeProject?.remote
+ // Re-asked at render, not only at the click: switching to a relay tab while the menu is open
+ // would otherwise leave it (and its backdrop) standing over a canvas it cannot act on.
+ const layoutMenuVisible = layoutMenuOpen && !layoutsDisabled
+ const layoutRows = sortedLayouts(activeProject?.layouts)
+
// The preset the readout currently sits on, or null between two — the menu's tick.
const activePreset = activeZoomPreset(zoomPct)
@@ -173,12 +201,13 @@ export function Dock({
return (
<>
- {(menuOpen || zoomMenuOpen) && (
+ {(menuOpen || zoomMenuOpen || layoutMenuVisible) && (
<div
className="dock-backdrop"
onClick={() => {
setMenuOpen(false)
setZoomMenuOpen(false)
+ setLayoutMenuOpen(false)
}}
/>
)}
@@ -316,6 +345,7 @@ export function Dock({
aria-label="Add node"
onClick={() => {
setZoomMenuOpen(false)
+ setLayoutMenuOpen(false)
setMenuOpen((v) => !v)
}}
>
@@ -364,6 +394,87 @@ export function Dock({
<FrameIcon />
</button>
</Tooltip>
+ {/* An arrangement is view state, not a node you add, so it sits in the view cluster rather
+ than behind the "+". */}
+ <div className="dock-layouts-wrap">
+ {layoutMenuVisible && (
+ <div className="dock-menu dock-layouts-menu">
+ {layoutRows.length === 0 ? (
+ // Never an empty popover: a menu that opens onto nothing reads as broken rather
+ // than as empty.
+ <button disabled>
+ <span>No layouts saved yet</span>
+ </button>
+ ) : (
+ layoutRows.map((layout) => (
+ <div key={layout.id} className="dock-menu__row">
+ <button
+ className="dock-menu__row-main"
+ onClick={pickLayout(() => onRestoreLayout(layout))}
+ >
+ <LayoutsIcon />
+ <span className="dock-menu__row-text">
+ <span className="dock-menu__row-name">{layout.name}</span>
+ <span className="dock-menu__row-sub">{layoutSubtitle(layout)}</span>
+ </span>
+ </button>
+ <span className="dock-menu__row-actions">
+ <button
+ className="dock-menu__row-act"
+ aria-label={`Rename layout ${layout.name}`}
+ title="Rename"
+ onClick={(e) => {
+ // The row itself restores; these two must not.
+ e.stopPropagation()
+ setLayoutMenuOpen(false)
+ onRenameLayout(layout)
+ }}
+ >
+ <PencilIcon />
+ </button>
+ <button
+ className="dock-menu__row-act"
+ aria-label={`Delete layout ${layout.name}`}
+ title="Delete"
+ onClick={(e) => {
+ e.stopPropagation()
+ setLayoutMenuOpen(false)
+ onDeleteLayout(layout)
+ }}
+ >
+ <CrossIcon />
+ </button>
+ </span>
+ </div>
+ ))
+ )}
+ <span className="dock-menu__rule" />
+ <button onClick={pickLayout(onSaveLayout)}>
+ <PlusSmallIcon />
+ <span>Save current layout…</span>
+ </button>
+ </div>
+ )}
+ <Tooltip
+ label={layoutsDisabled ? 'Layouts are managed on the host' : 'Layouts'}
+ placement="top"
+ >
+ <button
+ className={`dock-btn${layoutMenuOpen ? ' active' : ''}`}
+ aria-label="Layouts"
+ aria-haspopup="menu"
+ aria-expanded={layoutMenuOpen}
+ disabled={layoutsDisabled}
+ onClick={() => {
+ setMenuOpen(false)
+ setZoomMenuOpen(false)
+ setLayoutMenuOpen((v) => !v)
+ }}
+ >
+ <LayoutsIcon />
+ </button>
+ </Tooltip>
+ </div>
<Tooltip
label={
dictationOff
@@ -424,6 +535,7 @@ export function Dock({
aria-expanded={zoomMenuOpen}
onClick={() => {
setMenuOpen(false)
+ setLayoutMenuOpen(false)
setZoomMenuOpen((v) => !v)
}}
>
@@ -515,6 +627,28 @@ function FrameIcon() {
</svg>
)
}
+function LayoutsIcon() {
+ return (
+ <svg {...S}>
+ <rect x="3" y="4" width="18" height="16" rx="2" />
+ <path d="M10 4v16M10 12h11" />
+ </svg>
+ )
+}
+function PencilIcon() {
+ return (
+ <svg {...S} width={13} height={13}>
+ <path d="M4 20h4L19 9l-4-4L4 16v4zM14 6l4 4" />
+ </svg>
+ )
+}
+function CrossIcon() {
+ return (
+ <svg {...S} width={13} height={13}>
+ <path d="M6 6l12 12M18 6L6 18" />
+ </svg>
+ )
+}
function TerminalIcon() {
return (
<svg {...S}>
diff --git a/src/renderer/lib/canvasLayout.test.ts b/src/renderer/lib/canvasLayout.test.ts
new file mode 100644
index 000000000..d94b9a234
--- /dev/null
+++ b/src/renderer/lib/canvasLayout.test.ts
@@ -0,0 +1,412 @@
+import { describe, it, expect } from 'vitest'
+import type { CanvasLayout } from '@shared/canvas-layout'
+import { COLLAPSED_HEIGHT, rootPosition, type CanvasNode } from '../state/workspace'
+import { applyLayout, captureLayout } from './canvasLayout'
+
+// Minimal node stub: only the fields capture/apply read. Sizes are written to both `width`/`height`
+// and `style`, which is the shape `nodeStatesToFlow` produces for a node loaded from disk.
+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 group = (
+ id: string,
+ x: number,
+ y: number,
+ w = 400,
+ h = 300,
+ extra: Partial<CanvasNode> = {}
+): CanvasNode => n(id, x, y, w, h, { type: 'group', ...extra })
+
+const child = (parentId: string, node: CanvasNode): CanvasNode =>
+ ({ ...node, parentId, extent: 'parent' }) as CanvasNode
+
+const layoutOf = (nodes: CanvasLayout['nodes']): CanvasLayout => ({
+ id: 'l1',
+ name: 'Ultrawide',
+ createdAt: 1,
+ updatedAt: 1,
+ nodes
+})
+
+const byId = (nodes: CanvasNode[], id: string): CanvasNode => nodes.find((node) => node.id === id)!
+
+describe('captureLayout', () => {
+ it('records every node in ROOT space, with its size and collapse state', () => {
+ const nodes = [
+ group('g1', 100, 100, 400, 300),
+ child('g1', n('kid', 20, 30, 120, 60)),
+ n('solo', 700, 800, 200, 90)
+ ]
+ const layout = captureLayout(nodes, { id: 'l1', name: 'Ultrawide', now: 42 })
+ expect(layout.createdAt).toBe(42)
+ expect(layout.updatedAt).toBe(42)
+ expect(layout.nodes).toEqual([
+ { id: 'g1', x: 100, y: 100, width: 400, height: 300 },
+ { id: 'kid', x: 120, y: 130, width: 120, height: 60, parentId: 'g1' },
+ { id: 'solo', x: 700, y: 800, width: 200, height: 90 }
+ ])
+ })
+
+ it('stores the EXPANDED height of a collapsed node, not the chrome height', () => {
+ const collapsed = n('a', 0, 0, 100, COLLAPSED_HEIGHT, {
+ data: { title: 'a', color: '#fff', group: null, collapsed: true, expandedHeight: 260 }
+ } as Partial<CanvasNode>)
+ const layout = captureLayout([collapsed], { id: 'l1', name: 'x', now: 1 })
+ expect(layout.nodes).toEqual([
+ { id: 'a', x: 0, y: 0, width: 100, height: 260, collapsed: true }
+ ])
+ })
+
+ it('prefers React Flow measurements over the written size', () => {
+ const measured = n('a', 0, 0, 100, 50, { measured: { width: 333, height: 222 } })
+ expect(captureLayout([measured], { id: 'l1', name: 'x', now: 1 }).nodes[0]).toMatchObject({
+ width: 333,
+ height: 222
+ })
+ })
+
+ it('skips ephemeral kinds, whose ids nothing can ever resolve again', () => {
+ const nodes = [n('a', 0, 0), n('sub', 10, 10, 100, 50, { type: 'subagent' }), n('loop', 20, 20, 100, 50, { type: 'loop' })]
+ expect(captureLayout(nodes, { id: 'l1', name: 'x', now: 1 }).nodes.map((e) => e.id)).toEqual(['a'])
+ })
+
+ it('skips a node whose size cannot be established rather than guessing one', () => {
+ const sizeless = { id: 'a', type: 'terminal', position: { x: 0, y: 0 }, data: { title: 'a', color: '#fff', group: null } } as CanvasNode
+ expect(captureLayout([sizeless], { id: 'l1', name: 'x', now: 1 }).nodes).toEqual([])
+ })
+
+ it('trims and caps the name so the layout survives its own sanitizer', () => {
+ const long = captureLayout([], { id: 'l1', name: ` ${'x'.repeat(90)} `, now: 1 })
+ expect(long.name).toHaveLength(60)
+ expect(long.name.startsWith('x')).toBe(true)
+ })
+
+ it('carries the author window only when one is given', () => {
+ expect(captureLayout([], { id: 'l1', name: 'x', now: 1 }).window).toBeUndefined()
+ expect(
+ captureLayout([], { id: 'l1', name: 'x', now: 1, window: { width: 3440, height: 1440 } }).window
+ ).toEqual({ width: 3440, height: 1440 })
+ })
+})
+
+describe('applyLayout', () => {
+ it('rule 1: a node the layout does not know is left exactly where it is', () => {
+ const nodes = [n('a', 0, 0), n('newcomer', 500, 600, 120, 70)]
+ const out = applyLayout(nodes, layoutOf([{ id: 'a', x: 900, y: 900, width: 100, height: 50 }]))
+ expect(byId(out.nodes, 'newcomer')).toBe(nodes[1]) // same object: not moved, not tidied
+ expect(out.extra).toBe(1)
+ })
+
+ it('rule 1: an ephemeral node is not reported as extra, since nothing could address it', () => {
+ const nodes = [n('a', 0, 0), n('sub', 10, 10, 100, 50, { type: 'subagent' })]
+ const out = applyLayout(nodes, layoutOf([{ id: 'a', x: 5, y: 5, width: 100, height: 50 }]))
+ expect(out.extra).toBe(0)
+ })
+
+ it('rule 2: an entry whose node is gone is counted and never recreated', () => {
+ const nodes = [n('a', 0, 0)]
+ const out = applyLayout(
+ nodes,
+ layoutOf([
+ { id: 'a', x: 10, y: 10, width: 100, height: 50 },
+ { id: 'ghost', x: 0, y: 0, width: 100, height: 50 }
+ ])
+ )
+ expect(out.nodes.map((node) => node.id)).toEqual(['a'])
+ expect(out).toMatchObject({ moved: 1, missing: 1, extra: 0 })
+ })
+
+ it('rule 3: a frame the layout addresses gets its saved rect and is NOT re-fitted', () => {
+ const nodes = [group('g1', 0, 0, 400, 300), child('g1', n('kid', 20, 20, 100, 50))]
+ const out = applyLayout(
+ nodes,
+ layoutOf([
+ { id: 'g1', x: 10, y: 10, width: 400, height: 300 },
+ { id: 'kid', x: 500, y: 500, width: 100, height: 50, parentId: 'g1' }
+ ])
+ )
+ const g1 = byId(out.nodes, 'g1')
+ // A re-fit would have shrunk the frame around the child that just moved 500px away.
+ expect(g1.position).toEqual({ x: 10, y: 10 })
+ expect([g1.width, g1.height]).toEqual([400, 300])
+ expect(rootPosition(byId(out.nodes, 'kid'), out.nodes)).toEqual({ x: 500, y: 500 })
+ })
+
+ it('rule 3 exception: a frame grows around an out-of-layout child instead of letting it clamp', () => {
+ // `newcomer` was created after the layout was saved and sits outside g1's saved rect. Restoring
+ // g1 to that rect would put the child outside its own parent extent, and React Flow would clamp
+ // it - a node the layout never mentioned, moved, with nothing on screen to explain it.
+ const nodes = [
+ group('g1', 0, 0, 400, 300),
+ child('g1', n('kid', 20, 20, 100, 50)),
+ child('g1', n('newcomer', 600, 700, 100, 50))
+ ]
+ const out = applyLayout(
+ nodes,
+ layoutOf([
+ { id: 'g1', x: 0, y: 0, width: 400, height: 300 },
+ { id: 'kid', x: 20, y: 20, width: 100, height: 50, parentId: 'g1' }
+ ])
+ )
+ const g1 = byId(out.nodes, 'g1')
+ const frame = { ...rootPosition(g1, out.nodes), width: g1.width as number, height: g1.height as number }
+ // The unaddressed node did not move an inch.
+ expect(rootPosition(byId(out.nodes, 'newcomer'), out.nodes)).toEqual({ x: 600, y: 700 })
+ // And the addressed one still landed on its saved rect.
+ expect(rootPosition(byId(out.nodes, 'kid'), out.nodes)).toEqual({ x: 20, y: 20 })
+ // The frame grew outward only: the saved rect is the floor, never re-centered or shrunk.
+ expect(frame.x).toBeLessThanOrEqual(0)
+ expect(frame.y).toBeLessThanOrEqual(0)
+ expect(frame.x + frame.width).toBeGreaterThanOrEqual(600 + 100 + 28)
+ expect(frame.y + frame.height).toBeGreaterThanOrEqual(700 + 50 + 28)
+ })
+
+ it('rule 3 exception: a frame nothing forces open lands on exactly its saved rect', () => {
+ const nodes = [group('g1', 90, 90, 400, 300), child('g1', n('kid', 20, 20, 100, 50))]
+ const out = applyLayout(
+ nodes,
+ layoutOf([
+ { id: 'g1', x: 5, y: 6, width: 400, height: 300 },
+ { id: 'kid', x: 25, y: 26, width: 100, height: 50, parentId: 'g1' }
+ ])
+ )
+ const g1 = byId(out.nodes, 'g1')
+ expect(rootPosition(g1, out.nodes)).toEqual({ x: 5, y: 6 })
+ expect([g1.width, g1.height]).toEqual([400, 300])
+ })
+
+ it('a restore applied twice changes nothing the second time', () => {
+ const nodes = [
+ group('g_outer', 0, 0, 600, 500),
+ child('g_outer', group('g_inner', 50, 50, 300, 200)),
+ child('g_inner', n('kid', 20, 20, 100, 50)),
+ child('g_inner', n('newcomer', 400, 500, 100, 50)),
+ n('solo', 900, 900, 100, 50)
+ ]
+ const layout = layoutOf([
+ { id: 'g_inner', x: 40, y: 40, width: 300, height: 200, parentId: 'g_outer' },
+ { id: 'kid', x: 60, y: 60, width: 100, height: 50, parentId: 'g_inner' }
+ ])
+ const once = applyLayout(nodes, layout)
+ const twice = applyLayout(once.nodes, layout)
+ expect(twice.nodes).toEqual(once.nodes)
+ expect(twice).toMatchObject({ moved: once.moved, missing: once.missing, extra: once.extra })
+ })
+
+ it('an out-of-layout child holds its canvas position when its frame moves under it', () => {
+ const nodes = [group('g1', 0, 0, 400, 300), child('g1', n('newcomer', 20, 20, 100, 50))]
+ const out = applyLayout(
+ nodes,
+ layoutOf([{ id: 'g1', x: 500, y: 500, width: 400, height: 300 }])
+ )
+ expect(rootPosition(byId(out.nodes, 'newcomer'), out.nodes)).toEqual({ x: 20, y: 20 })
+ })
+
+ it('rule 3: a frame the layout does NOT mention is re-fitted around its moved child', () => {
+ const nodes = [group('g1', 0, 0, 400, 300), child('g1', n('kid', 20, 20, 100, 50))]
+ const out = applyLayout(
+ nodes,
+ layoutOf([{ id: 'kid', x: 200, y: 300, width: 100, height: 50 }])
+ )
+ const g1 = byId(out.nodes, 'g1')
+ // groupBox: pad 28 all round, plus a 34px label header above.
+ expect(g1.position).toEqual({ x: 172, y: 238 })
+ expect([g1.width, g1.height]).toEqual([156, 140])
+ // The child keeps the root position the layout asked for, whatever the frame did.
+ expect(rootPosition(byId(out.nodes, 'kid'), out.nodes)).toEqual({ x: 200, y: 300 })
+ })
+
+ it('rule 4: nested frames resolve against target origins, so the result is order-independent', () => {
+ // g_outer > g_inner > kid, with only g_inner and kid in the layout. g_outer must end up
+ // hugging the pair, and neither placed node may be measured against a frame the other moved.
+ const nodes = [
+ group('g_outer', 0, 0, 600, 500),
+ child('g_outer', group('g_inner', 50, 50, 300, 200)),
+ child('g_inner', n('kid', 20, 20, 100, 50))
+ ]
+ const layout = layoutOf([
+ { id: 'g_inner', x: 400, y: 400, width: 300, height: 200, parentId: 'g_outer' },
+ { id: 'kid', x: 460, y: 470, width: 100, height: 50, parentId: 'g_inner' }
+ ])
+ const out = applyLayout(nodes, layout)
+ expect(rootPosition(byId(out.nodes, 'g_inner'), out.nodes)).toEqual({ x: 400, y: 400 })
+ expect(rootPosition(byId(out.nodes, 'kid'), out.nodes)).toEqual({ x: 460, y: 470 })
+ // kid's parent IS in the layout, so its relative position comes from the two saved rects.
+ expect(byId(out.nodes, 'kid').position).toEqual({ x: 60, y: 70 })
+
+ const reversed = applyLayout(nodes, layoutOf([...layout.nodes].reverse()))
+ expect(reversed.nodes).toEqual(out.nodes)
+ })
+
+ it('rule 4: an out-of-layout frame between two placed nodes does not shift either of them', () => {
+ const nodes = [
+ group('g_outer', 0, 0, 600, 500),
+ child('g_outer', group('g_inner', 50, 50, 300, 200)),
+ child('g_inner', n('kid', 20, 20, 100, 50)),
+ n('solo', 900, 900, 100, 50)
+ ]
+ const out = applyLayout(
+ nodes,
+ layoutOf([
+ { id: 'kid', x: 250, y: 260, width: 100, height: 50 },
+ { id: 'solo', x: 10, y: 20, width: 100, height: 50 }
+ ])
+ )
+ expect(rootPosition(byId(out.nodes, 'kid'), out.nodes)).toEqual({ x: 250, y: 260 })
+ expect(byId(out.nodes, 'solo').position).toEqual({ x: 10, y: 20 })
+ // Both un-addressed frames hugged the child again, innermost first.
+ const inner = byId(out.nodes, 'g_inner')
+ const outer = byId(out.nodes, 'g_outer')
+ expect([inner.width, inner.height]).toEqual([156, 140])
+ const innerRoot = rootPosition(inner, out.nodes)
+ const outerRoot = rootPosition(outer, out.nodes)
+ expect(outerRoot.x).toBeLessThanOrEqual(innerRoot.x)
+ expect(outerRoot.y).toBeLessThanOrEqual(innerRoot.y)
+ expect(outer.width as number).toBeGreaterThanOrEqual(inner.width as number)
+ })
+
+ it('rule 5: a collapsed entry restores the chrome height and keeps the expanded one honest', () => {
+ const nodes = [n('a', 0, 0, 100, 300, { data: { title: 'a', color: '#fff', group: null, expandedHeight: 300 } } as Partial<CanvasNode>)]
+ const out = applyLayout(
+ nodes,
+ layoutOf([{ id: 'a', x: 0, y: 0, width: 100, height: 260, collapsed: true }])
+ )
+ const a = byId(out.nodes, 'a')
+ expect(a.height).toBe(COLLAPSED_HEIGHT)
+ expect(a.style?.height).toBe(COLLAPSED_HEIGHT)
+ expect(a.data.collapsed).toBe(true)
+ expect(a.data.expandedHeight).toBe(260)
+ })
+
+ it('rule 5: an expanded entry un-collapses a currently collapsed node at the stored height', () => {
+ const nodes = [
+ n('a', 0, 0, 100, COLLAPSED_HEIGHT, {
+ data: { title: 'a', color: '#fff', group: null, collapsed: true, expandedHeight: 90 }
+ } as Partial<CanvasNode>)
+ ]
+ const out = applyLayout(nodes, layoutOf([{ id: 'a', x: 0, y: 0, width: 100, height: 400 }]))
+ const a = byId(out.nodes, 'a')
+ expect(a.data.collapsed).toBe(false)
+ expect(a.height).toBe(400)
+ expect(a.style?.height).toBe(400)
+ expect(a.data.expandedHeight).toBe(400)
+ })
+
+ it('rule 6: a maximized node keeps its restore rect', () => {
+ const premaxRect = { x: 1, y: 2, width: 3, height: 4 }
+ const nodes = [n('a', 0, 0, 100, 50, { data: { title: 'a', color: '#fff', group: null, premaxRect } } as Partial<CanvasNode>)]
+ const out = applyLayout(nodes, layoutOf([{ id: 'a', x: 9, y: 9, width: 100, height: 50 }]))
+ expect(byId(out.nodes, 'a').data.premaxRect).toEqual(premaxRect)
+ })
+
+ it('rule 7: `measured` is cleared on every node the transform touches', () => {
+ const nodes = [
+ n('a', 0, 0, 100, 50, { measured: { width: 111, height: 222 } }),
+ n('b', 0, 0, 100, 50, { measured: { width: 333, height: 444 } })
+ ]
+ const out = applyLayout(nodes, layoutOf([{ id: 'a', x: 5, y: 5, width: 100, height: 50 }]))
+ expect(byId(out.nodes, 'a').measured).toBeUndefined()
+ // The untouched node keeps its own measurement; nothing else was rewritten.
+ expect(byId(out.nodes, 'b').measured).toEqual({ width: 333, height: 444 })
+ })
+
+ it('rule 8: nothing outside geometry is touched, and nothing is reparented', () => {
+ const data = {
+ title: 'agent',
+ color: '#ff0000',
+ group: 'g',
+ tags: ['x'],
+ cwd: '/repo',
+ agentId: 'claude',
+ accountId: 'acc-1',
+ pendingLaunch: { after: ['dep'], command: 'claude' },
+ icon: { type: 'emoji', value: '🚀' }
+ }
+ const nodes = [group('g1', 0, 0, 400, 300), child('g1', n('kid', 20, 20, 100, 50, { data } as Partial<CanvasNode>))]
+ const out = applyLayout(
+ nodes,
+ layoutOf([
+ // A recorded parentId naming a different frame must change nothing structural.
+ { id: 'kid', x: 40, y: 40, width: 100, height: 50, parentId: 'some-other-frame' }
+ ])
+ )
+ const kid = byId(out.nodes, 'kid')
+ expect(kid.parentId).toBe('g1')
+ expect(kid.extent).toBe('parent')
+ expect(kid.type).toBe('terminal')
+ expect(kid.id).toBe('kid')
+ for (const [key, value] of Object.entries(data)) {
+ expect(kid.data[key as keyof typeof data]).toEqual(value)
+ }
+ })
+
+ it('round trip: capture then apply changes no geometry', () => {
+ const nodes = [
+ group('g_outer', 10, 20, 600, 500),
+ child('g_outer', group('g_inner', 50, 60, 300, 200)),
+ child('g_inner', n('kid', 20, 30, 100, 50)),
+ n('solo', 700, 800, 200, 90),
+ n('folded', 900, 100, 150, COLLAPSED_HEIGHT, {
+ data: { title: 'folded', color: '#fff', group: null, collapsed: true, expandedHeight: 310 }
+ } as Partial<CanvasNode>)
+ ]
+ const out = applyLayout(nodes, captureLayout(nodes, { id: 'l1', name: 'same', now: 1 }))
+ for (const before of nodes) {
+ const after = byId(out.nodes, before.id)
+ expect(after.position).toEqual(before.position)
+ expect(after.width).toBe(before.width)
+ expect(after.height).toBe(before.height)
+ expect(after.data.collapsed ?? false).toBe(before.data.collapsed ?? false)
+ }
+ expect(out).toMatchObject({ moved: 5, missing: 0, extra: 0 })
+ })
+
+ it('counts moved / missing / extra exactly, so the toast cannot drift from what happened', () => {
+ const nodes = [n('a', 0, 0), n('b', 0, 0), n('newcomer', 0, 0)]
+ const out = applyLayout(
+ nodes,
+ layoutOf([
+ { id: 'a', x: 1, y: 1, width: 100, height: 50 },
+ { id: 'b', x: 2, y: 2, width: 100, height: 50 },
+ { id: 'gone', x: 3, y: 3, width: 100, height: 50 }
+ ])
+ )
+ expect(out).toMatchObject({ moved: 2, missing: 1, extra: 1 })
+ })
+
+ it('counts a duplicated entry id once, so the report describes nodes and not file lines', () => {
+ const nodes = [n('a', 0, 0)]
+ const out = applyLayout(
+ nodes,
+ layoutOf([
+ { id: 'a', x: 1, y: 1, width: 100, height: 50 },
+ { id: 'a', x: 900, y: 900, width: 100, height: 50 }
+ ])
+ )
+ expect(out).toMatchObject({ moved: 1, missing: 0, extra: 0 })
+ expect(byId(out.nodes, 'a').position).toEqual({ x: 1, y: 1 })
+ })
+
+ it('a layout addressing nothing live hands back the SAME array, so no save is triggered', () => {
+ const nodes = [n('a', 0, 0)]
+ const out = applyLayout(nodes, layoutOf([{ id: 'ghost', x: 0, y: 0, width: 100, height: 50 }]))
+ expect(out.nodes).toBe(nodes)
+ expect(out).toMatchObject({ moved: 0, missing: 1, extra: 1 })
+ })
+})
diff --git a/src/renderer/lib/canvasLayout.ts b/src/renderer/lib/canvasLayout.ts
new file mode 100644
index 000000000..294a00e9f
--- /dev/null
+++ b/src/renderer/lib/canvasLayout.ts
@@ -0,0 +1,373 @@
+import type { CanvasLayout, CanvasLayoutNode } from '@shared/canvas-layout'
+import { CANVAS_LAYOUT_NAME_MAX } from '@shared/canvas-layout'
+import {
+ COLLAPSED_HEIGHT,
+ fitGroupToChildren,
+ GROUP_HEADER,
+ GROUP_PAD,
+ rootPosition,
+ type CanvasNode
+} from '../state/workspace'
+
+/**
+ * Capture and restore of a canvas layout: a named snapshot of node GEOMETRY for one project (see
+ * the trust model in @shared/canvas-layout).
+ *
+ * Pure on purpose. Everything here is array in, array out, so the two halves that decide where a
+ * canvas ends up can be tested under vitest's default node environment instead of behind React
+ * Flow, a zustand store and a mounted canvas.
+ */
+
+/**
+ * Node kinds that exist only as a live render and are never serialized (`subagent`, `loop` in
+ * CLAUDE.md's node-kinds list). A layout entry for one is an id nothing can ever resolve again -
+ * the next turn clears the card - so capture skips them and the restore's `extra` count ignores
+ * them rather than reporting a "node the layout does not mention" the user cannot act on.
+ */
+const EPHEMERAL_KINDS: ReadonlySet<string> = new Set(['subagent', 'loop'])
+
+/** A rect in ROOT space, the coordinate space a layout entry and `withNodeRect` both speak. */
+interface RootRect {
+ x: number
+ y: number
+ width: number
+ height: number
+}
+
+const finiteNumber = (value: unknown): number | undefined =>
+ typeof value === 'number' && Number.isFinite(value) ? value : undefined
+
+/** A node's on-canvas width, preferring React Flow's own measurement the way `flowToNodeStates`
+ * does, so a captured rect matches what the user actually sees rather than the last size written. */
+function capturedWidth(node: CanvasNode): number | undefined {
+ return (
+ finiteNumber(node.measured?.width) ??
+ finiteNumber(node.width) ??
+ finiteNumber(node.style?.width)
+ )
+}
+
+/**
+ * A node's EXPANDED height, which is the only height a layout may store.
+ *
+ * While a node is collapsed its on-screen height is chrome (`COLLAPSED_HEIGHT`), not a size the
+ * user chose, so the measurement is ignored in favor of `data.expandedHeight` - the same rule
+ * `flowToNodeStates` applies when it serializes a collapsed node. Storing the shrunk height would
+ * make every save-while-collapsed permanently shrink the node on the next restore.
+ */
+function capturedExpandedHeight(node: CanvasNode): number | undefined {
+ if (node.data.collapsed) return finiteNumber(node.data.expandedHeight)
+ return (
+ finiteNumber(node.measured?.height) ??
+ finiteNumber(node.height) ??
+ finiteNumber(node.style?.height)
+ )
+}
+
+/**
+ * Snapshot the live canvas: every node's ROOT-space rect, its collapse state and its parent.
+ *
+ * Root space rather than parent-relative because a frame that has since been ungrouped, moved or
+ * re-fitted must not drag its old children hundreds of pixels off screen when the layout is
+ * restored - the same reasoning `maximizeNodeToRect` gives for storing `premaxRect` in root space.
+ *
+ * A node whose size cannot be established is SKIPPED rather than captured at a guessed rect: an
+ * unaddressed node is left exactly where it is on restore (rule 1), which is always safe, while a
+ * guessed rect would resize it. In practice every node carries a size - `nodeStatesToFlow` and the
+ * node factories both write one - so this is a refusal, not a fallback.
+ *
+ * The name is trimmed and capped here so the layout survives its own reader: `sanitizeLayouts`
+ * drops a layout WHOLE when its name is empty after trimming, and a capture that produced an
+ * unreadable snapshot would look like a save that silently did nothing.
+ */
+export function captureLayout(
+ nodes: CanvasNode[],
+ opts: { id: string; name: string; now: number; window?: { width: number; height: number } }
+): CanvasLayout {
+ const entries: CanvasLayoutNode[] = []
+ for (const node of nodes) {
+ if (EPHEMERAL_KINDS.has(node.type ?? '')) continue
+ const width = capturedWidth(node)
+ const height = capturedExpandedHeight(node)
+ if (width === undefined || height === undefined) continue
+ const root = rootPosition(node, nodes)
+ entries.push({
+ id: node.id,
+ x: root.x,
+ y: root.y,
+ width,
+ height,
+ ...(node.data.collapsed ? { collapsed: true } : {}),
+ ...(node.parentId ? { parentId: node.parentId } : {})
+ })
+ }
+ return {
+ id: opts.id,
+ name: opts.name.trim().slice(0, CANVAS_LAYOUT_NAME_MAX),
+ createdAt: opts.now,
+ updatedAt: opts.now,
+ ...(opts.window ? { window: opts.window } : {}),
+ nodes: entries
+ }
+}
+
+/** What a restore did, in the terms the user-facing toast reports. Counted by the transform itself
+ * so the sentence cannot drift from what happened on the canvas. */
+export interface ApplyLayoutResult {
+ nodes: CanvasNode[]
+ /** Nodes the layout addressed and actually placed. */
+ moved: number
+ /** Entries in the layout whose node no longer exists. Never recreated. */
+ missing: number
+ /** Live nodes the layout does not mention. Left untouched. */
+ extra: number
+}
+
+/** A node's rect as it is drawn right now: the rendered height, so a collapsed node contributes its
+ * chrome height rather than the size it would have if expanded. */
+function renderedRootRect(node: CanvasNode, nodes: CanvasNode[]): RootRect {
+ const root = rootPosition(node, nodes)
+ const width =
+ finiteNumber(node.measured?.width) ?? finiteNumber(node.width) ?? finiteNumber(node.style?.width) ?? 0
+ const height =
+ finiteNumber(node.measured?.height) ??
+ finiteNumber(node.height) ??
+ finiteNumber(node.style?.height) ??
+ 0
+ return { x: root.x, y: root.y, width, height }
+}
+
+/**
+ * Grow `saved` until it also contains `boxes` with the clearance `fitGroupToChildren` gives a
+ * frame, or return `saved` untouched when it already does.
+ *
+ * `saved` is the FLOOR and is never padded: it is the rect the user consented to, so a frame that
+ * nothing forces open comes back at exactly the size they saved. Growing only outward is also what
+ * makes a repeated restore idempotent - a rule that could shrink or re-center the frame would
+ * drift a little further on every apply.
+ */
+function grownToContain(saved: RootRect, boxes: RootRect[]): RootRect {
+ if (boxes.length === 0) return saved
+ const minX = Math.min(...boxes.map((b) => b.x)) - GROUP_PAD
+ const minY = Math.min(...boxes.map((b) => b.y)) - GROUP_PAD - GROUP_HEADER
+ const maxX = Math.max(...boxes.map((b) => b.x + b.width)) + GROUP_PAD
+ const maxY = Math.max(...boxes.map((b) => b.y + b.height)) + GROUP_PAD
+ const x = Math.min(saved.x, minX)
+ const y = Math.min(saved.y, minY)
+ const right = Math.max(saved.x + saved.width, maxX)
+ const bottom = Math.max(saved.y + saved.height, maxY)
+ return { x, y, width: right - x, height: bottom - y }
+}
+
+/**
+ * Move and resize one frame to `rect` while every one of its children stays exactly where it is on
+ * canvas, by shifting their parent-relative positions against the frame's own move - the same
+ * re-anchoring `fitGroupToChildren` performs. A frame is a background container, so resizing it is
+ * not supposed to be visible on anything inside it.
+ */
+function withFrameRect(nodes: CanvasNode[], frameId: string, rect: RootRect): CanvasNode[] {
+ const frame = nodes.find((node) => node.id === frameId)
+ if (!frame) return nodes
+ const origin = rootPosition(frame, nodes)
+ const dx = rect.x - origin.x
+ const dy = rect.y - origin.y
+ return nodes.map((node) => {
+ if (node.id === frameId) {
+ return {
+ ...node,
+ position: { x: node.position.x + dx, y: node.position.y + dy },
+ width: rect.width,
+ height: rect.height,
+ style: { ...node.style, width: rect.width, height: rect.height },
+ measured: undefined
+ }
+ }
+ if (node.parentId === frameId && (dx !== 0 || dy !== 0)) {
+ return { ...node, position: { x: node.position.x - dx, y: node.position.y - dy } }
+ }
+ return node
+ })
+}
+
+/** Ancestor count, used to re-fit frames innermost-first. Read off the ORIGINAL array because a
+ * restore never reparents anything (rule 8), so the chain is the same before and after. */
+function depthOf(node: CanvasNode, byId: Map<string, CanvasNode>): number {
+ let depth = 0
+ const seen = new Set<string>([node.id])
+ let parentId = node.parentId
+ while (parentId && !seen.has(parentId)) {
+ seen.add(parentId)
+ const parent = byId.get(parentId)
+ if (!parent) break
+ depth += 1
+ parentId = parent.parentId
+ }
+ return depth
+}
+
+/**
+ * Put the canvas back the way `layout` recorded it. Pure.
+ *
+ * The whole layout lands in ONE transform, as an explicit two-pass: resolve every target root
+ * origin first, then emit the nodes against those origins. A reduce over per-node placements would
+ * re-fit an ancestor frame between two placements, so the second node would be measured against a
+ * frame the first node had just moved and the arrangement would come back subtly wrong - and
+ * differently wrong depending on array order.
+ *
+ * Geometry only. Nothing here creates, deletes, reparents, renames or respawns anything, and the
+ * layout's recorded `parentId` is read for nothing at all: it is a label for the reader, and
+ * honoring it would turn a restore into a structural edit.
+ */
+export function applyLayout(nodes: CanvasNode[], layout: CanvasLayout): ApplyLayoutResult {
+ const byId = new Map(nodes.map((node) => [node.id, node]))
+
+ // First-wins on a duplicate id: a hand-edited file can name one node twice, and the counts below
+ // must describe nodes, not entries, or the toast reports more moves than there are nodes.
+ const entries = new Map<string, CanvasLayoutNode>()
+ for (const entry of layout.nodes) {
+ if (!entries.has(entry.id)) entries.set(entry.id, entry)
+ }
+
+ // Rule 2: an entry whose node is gone is skipped and counted. A layout is geometry; resurrecting
+ // a node would be content, and content this file has no honest copy of.
+ let missing = 0
+ const placed = new Map<string, CanvasLayoutNode>()
+ for (const [id, entry] of entries) {
+ if (byId.has(id)) placed.set(id, entry)
+ else missing += 1
+ }
+
+ // Rule 1: a node the layout does not know is left exactly where it is - not tidied, not stacked
+ // at the origin. It is only counted, so the user learns the layout predates it.
+ let extra = 0
+ for (const node of nodes) {
+ if (EPHEMERAL_KINDS.has(node.type ?? '')) continue
+ if (!placed.has(node.id)) extra += 1
+ }
+
+ // Nothing to place: hand back the SAME array so a no-op restore cannot mark the workspace dirty
+ // and write a project.json revision for a canvas that did not change.
+ if (placed.size === 0) return { nodes, moved: 0, missing, extra }
+
+ const currentRoot = new Map(nodes.map((node) => [node.id, rootPosition(node, nodes)]))
+
+ /**
+ * Pass one, the target ROOT origin of every node: the saved one for a node the layout addresses,
+ * and the CURRENT one for a node it does not (rule 1, which holds even when the frame the node
+ * sits in is about to move out from under it). Resolving all of them before anything is emitted
+ * is what makes the transform order-independent. A dangling parentId resolves to the root,
+ * matching how `containerOrigin` treats one.
+ */
+ const targetRoot = (id: string): { x: number; y: number } => {
+ const entry = placed.get(id)
+ if (entry) return { x: entry.x, y: entry.y }
+ return currentRoot.get(id) ?? { x: 0, y: 0 }
+ }
+ const originOf = (parentId: string | undefined): { x: number; y: number } =>
+ parentId && byId.has(parentId) ? targetRoot(parentId) : { x: 0, y: 0 }
+
+ // Pass two. Group frames are placed here like any other node (rule 3): a frame the layout
+ // addresses gets the rect the user saved, and is deliberately NOT re-fitted around the children
+ // the layout ALSO addressed, or the fit would overwrite that rect and the arrangement would
+ // drift a little on every restore.
+ let next = nodes.map((node) => {
+ const origin = originOf(node.parentId)
+ const entry = placed.get(node.id)
+ if (!entry) {
+ // An unaddressed node holds its root position rather than riding its frame: "left where it
+ // is" is a claim about the canvas, not about a parent-relative offset.
+ const root = currentRoot.get(node.id) ?? node.position
+ const position = { x: root.x - origin.x, y: root.y - origin.y }
+ if (position.x === node.position.x && position.y === node.position.y) return node
+ return { ...node, position }
+ }
+ // Rule 5: the stored height is ALWAYS the expanded one, so a collapsed entry emits the chrome
+ // height on the node while `expandedHeight` keeps the real size. Getting this the other way
+ // round makes expanding a restored node snap it to a stale height.
+ const collapsed = entry.collapsed === true
+ const height = collapsed ? COLLAPSED_HEIGHT : entry.height
+ return {
+ ...node,
+ position: { x: entry.x - origin.x, y: entry.y - origin.y },
+ width: entry.width,
+ height,
+ style: { ...node.style, width: entry.width, height },
+ // Rule 7, the reason `withNodeRect` gives: `flowToNodeStates` prefers `measured` over
+ // `width`/`height`, so a save racing the re-measure would persist the OLD size.
+ measured: undefined,
+ // Rule 6 and rule 8 ride on this spread: `premaxRect` and every non-geometry field (title,
+ // color, cwd, agentId, accountId, pendingLaunch, trigger, icon, ...) survive untouched. A
+ // restore is a placement, not a maximize, so a maximized node keeps its restore rect - the
+ // same rule `placeNodeInRect` states for zone snaps.
+ data: { ...node.data, collapsed, expandedHeight: entry.height }
+ }
+ })
+
+ /**
+ * Rule 3's one exception, and it exists to protect rule 1. A frame the layout addresses may hold
+ * descendants the layout predates; those keep their root position, so a saved rect too small to
+ * contain them would let React Flow's `extent: 'parent'` CLAMP them - a node the layout never
+ * mentioned would move, with nothing on screen explaining why. So the frame is grown to contain
+ * them instead of the node being pushed. Growing a frame is ordinary behavior the user already
+ * sees from `fitGroupToChildren`; a terminal that teleports is not. The saved rect stays the
+ * floor, so a frame nothing forces open still lands on it exactly.
+ */
+ const childIds = new Map<string, string[]>()
+ for (const node of nodes) {
+ if (!node.parentId) continue
+ const siblings = childIds.get(node.parentId)
+ if (siblings) siblings.push(node.id)
+ else childIds.set(node.parentId, [node.id])
+ }
+ const unplacedDescendants = (frameId: string): CanvasNode[] => {
+ const out: CanvasNode[] = []
+ const seen = new Set<string>([frameId])
+ const queue = [...(childIds.get(frameId) ?? [])]
+ while (queue.length) {
+ const id = queue.shift()!
+ if (seen.has(id)) continue
+ seen.add(id)
+ const node = byId.get(id)
+ if (!node) continue
+ // Every level down, not just direct children: a deep node is clamped by its own frame, and
+ // that frame is only safe from clamping if this one contains it too.
+ if (!placed.has(id) && !EPHEMERAL_KINDS.has(node.type ?? '')) out.push(node)
+ queue.push(...(childIds.get(id) ?? []))
+ }
+ return out
+ }
+ for (const [id, entry] of placed) {
+ if (byId.get(id)?.type !== 'group') continue
+ const saved: RootRect = { x: entry.x, y: entry.y, width: entry.width, height: entry.height }
+ const grown = grownToContain(
+ saved,
+ unplacedDescendants(id).map((node) => renderedRootRect(node, nodes))
+ )
+ if (grown === saved) continue
+ next = withFrameRect(next, id, grown)
+ }
+
+ // Rule 3's other half: a frame the layout does NOT mention, but whose descendant just moved, is
+ // re-fitted around its children so it still hugs them. Deepest first, because a frame must be
+ // sized before the frame that has to wrap it (`fitAncestorChain`'s ordering, applied across
+ // every moved chain at once rather than per node).
+ const toFit = new Map<string, number>()
+ for (const id of placed.keys()) {
+ const seen = new Set<string>([id])
+ let parentId = byId.get(id)?.parentId
+ while (parentId && !seen.has(parentId)) {
+ seen.add(parentId)
+ const parent = byId.get(parentId)
+ if (!parent) break
+ if (!placed.has(parentId) && parent.type === 'group') {
+ toFit.set(parentId, depthOf(parent, byId))
+ }
+ parentId = parent.parentId
+ }
+ }
+ for (const id of [...toFit.keys()].sort((a, b) => (toFit.get(b) ?? 0) - (toFit.get(a) ?? 0))) {
+ next = fitGroupToChildren(next, id)
+ }
+
+ return { nodes: next, moved: placed.size, missing, extra }
+}
diff --git a/src/renderer/lib/canvasLayoutView.test.ts b/src/renderer/lib/canvasLayoutView.test.ts
new file mode 100644
index 000000000..202af6c17
--- /dev/null
+++ b/src/renderer/lib/canvasLayoutView.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest'
+import type { CanvasLayout } from '@shared/canvas-layout'
+import {
+ layoutFramingViewport,
+ layoutSubtitle,
+ restoreSummary,
+ saveLayoutRefusal,
+ sortedLayouts
+} from './canvasLayoutView'
+
+const layout = (over: Partial<CanvasLayout> = {}): CanvasLayout => ({
+ id: 'l1',
+ name: 'Ultrawide',
+ createdAt: 1,
+ updatedAt: 1,
+ nodes: [],
+ ...over
+})
+
+describe('sortedLayouts', () => {
+ it('orders by name, ignoring case', () => {
+ const rows = sortedLayouts([layout({ id: 'a', name: 'zen' }), layout({ id: 'b', name: 'Ample' })])
+ expect(rows.map((l) => l.id)).toEqual(['b', 'a'])
+ })
+
+ it('answers an empty list for a project that has none', () => {
+ expect(sortedLayouts(undefined)).toEqual([])
+ })
+
+ it('never reorders the array it was handed', () => {
+ const input = [layout({ id: 'a', name: 'zen' }), layout({ id: 'b', name: 'Ample' })]
+ sortedLayouts(input)
+ expect(input.map((l) => l.id)).toEqual(['a', 'b'])
+ })
+})
+
+describe('layoutSubtitle', () => {
+ it('names the window it was saved on beside the node count', () => {
+ expect(
+ layoutSubtitle(layout({ window: { width: 3440, height: 1440 } }))
+ ).toBe('3440 x 1440 - 0 nodes')
+ })
+
+ it('drops the window clause rather than inventing a size', () => {
+ expect(layoutSubtitle(layout({ nodes: [{ id: 'n', x: 0, y: 0, width: 1, height: 1 }] }))).toBe(
+ '1 node'
+ )
+ })
+})
+
+describe('layoutFramingViewport', () => {
+ it('parks the top-left rect just inside the corner at zoom 1', () => {
+ expect(
+ layoutFramingViewport([
+ { id: 'a', x: 4000, y: 2000, width: 10, height: 10 },
+ { id: 'b', x: 4200, y: 1900, width: 10, height: 10 }
+ ])
+ ).toEqual({ x: 80 - 4000, y: 80 - 1900, zoom: 1 })
+ })
+
+ it('anchors on a framed child too - layout rects are root-space', () => {
+ // The core `framingViewport` skips a node with a parent because ITS position is
+ // parent-relative. A layout of nothing but framed children would otherwise open on empty space.
+ expect(
+ layoutFramingViewport([{ id: 'a', x: 900, y: 700, width: 10, height: 10, parentId: 'g' }])
+ ).toEqual({ x: 80 - 900, y: 80 - 700, zoom: 1 })
+ })
+
+ it('falls back to the origin for a layout that addresses nothing', () => {
+ expect(layoutFramingViewport([])).toEqual({ x: 0, y: 0, zoom: 1 })
+ })
+})
+
+describe('saveLayoutRefusal', () => {
+ it('says nothing when the save landed', () => {
+ expect(saveLayoutRefusal('saved')).toBeNull()
+ })
+
+ it('gives every refusal a sentence, including the unreachable ones', () => {
+ for (const result of ['cap-reached', 'invalid-name', 'unknown-project'] as const) {
+ expect(saveLayoutRefusal(result)).toBeTruthy()
+ }
+ expect(saveLayoutRefusal('cap-reached')).toContain('20')
+ })
+})
+
+describe('restoreSummary', () => {
+ it('reports only the counts that are not zero', () => {
+ expect(restoreSummary('Ultrawide', { moved: 12, missing: 0, extra: 2 })).toBe(
+ 'Restored "Ultrawide": 12 nodes moved, 2 not in this layout.'
+ )
+ })
+
+ it('speaks of one node in the singular', () => {
+ expect(restoreSummary('Laptop', { moved: 1, missing: 0, extra: 0 })).toBe(
+ 'Restored "Laptop": 1 node moved.'
+ )
+ })
+
+ it('says so when the restore changed nothing', () => {
+ expect(restoreSummary('Laptop', { moved: 0, missing: 0, extra: 0 })).toBe(
+ 'Restored "Laptop": nothing changed.'
+ )
+ })
+})
diff --git a/src/renderer/lib/canvasLayoutView.ts b/src/renderer/lib/canvasLayoutView.ts
new file mode 100644
index 000000000..accb9b742
--- /dev/null
+++ b/src/renderer/lib/canvasLayoutView.ts
@@ -0,0 +1,101 @@
+import { CANVAS_LAYOUTS_CAP, type CanvasLayout, type CanvasLayoutNode } from '@shared/canvas-layout'
+import type { Viewport } from '@shared/types'
+import type { SaveLayoutResult } from '../state/projects'
+
+/**
+ * What the layout SURFACES need: the menu's row order and subtitle, the camera a restore falls back
+ * to, and the sentence that reports what a restore did.
+ *
+ * Pure, and separate from `canvasLayout.ts` (which owns capture and apply) because these are
+ * presentation decisions rather than geometry ones. Keeping them here lets the Dock and Canvas share
+ * one wording and one ordering instead of each spelling their own.
+ */
+
+/**
+ * The layouts in menu order: by name, case-insensitively.
+ *
+ * A list of named things is SCANNED for the one you want, not replayed in the order it was written,
+ * so the storage order (append on save) is the wrong order to read in. Stable within a tie, so two
+ * layouts that differ only in case keep the order the file gave them.
+ */
+export function sortedLayouts(layouts: CanvasLayout[] | undefined): CanvasLayout[] {
+ return [...(layouts ?? [])].sort((a, b) =>
+ a.name.toLowerCase().localeCompare(b.name.toLowerCase())
+ )
+}
+
+/**
+ * The line under a layout's name: the window it was saved on and how many nodes it addresses.
+ *
+ * The window size is a LABEL and never a matcher (see `CanvasLayout.window`) - it is here so the
+ * user can tell the ultrawide arrangement from the laptop one, which is the whole reason they saved
+ * two. A layout with no recorded window shows the node count alone rather than an invented size.
+ */
+export function layoutSubtitle(layout: CanvasLayout): string {
+ const count = `${layout.nodes.length} node${layout.nodes.length === 1 ? '' : 's'}`
+ if (!layout.window) return count
+ return `${layout.window.width} x ${layout.window.height} - ${count}`
+}
+
+/**
+ * The camera for a layout this machine has never restored: zoom 1, panned so the top-left node sits
+ * just inside the corner.
+ *
+ * The same rule `framingViewport` (core/workspace-files.ts) applies to a canvas nobody here has
+ * framed, reimplemented rather than imported: the renderer has no import path into `src/core`, and
+ * that function reads `CanvasNodeState.position` and skips children (whose positions are
+ * parent-relative). A layout's rects are ROOT-space, so here EVERY entry anchors the camera - a
+ * layout of nothing but framed children would otherwise open on empty space.
+ */
+export function layoutFramingViewport(nodes: CanvasLayoutNode[]): Viewport {
+ let minX = Infinity
+ let minY = Infinity
+ for (const node of nodes) {
+ if (Number.isFinite(node.x) && node.x < minX) minX = node.x
+ if (Number.isFinite(node.y) && node.y < minY) minY = node.y
+ }
+ return {
+ x: Number.isFinite(minX) ? 80 - minX : 0,
+ y: Number.isFinite(minY) ? 80 - minY : 0,
+ zoom: 1
+ }
+}
+
+/**
+ * What to tell the user when a save did not land, or `null` when it did.
+ *
+ * Every refusal gets a sentence, including the two the Dock's own path cannot reach (a name that
+ * survived the trim, a project that is on screen): the store is not this feature's only writer, and
+ * a save that reports nothing is indistinguishable from one that worked until the layout is missing
+ * from the menu.
+ */
+export function saveLayoutRefusal(result: SaveLayoutResult): string | null {
+ switch (result) {
+ case 'saved':
+ return null
+ case 'cap-reached':
+ return `This project already holds the maximum of ${CANVAS_LAYOUTS_CAP} layouts. Delete one before saving another.`
+ case 'invalid-name':
+ return 'That name is empty once trimmed, so the layout was not saved.'
+ case 'unknown-project':
+ return 'This project is no longer open, so the layout was not saved.'
+ }
+}
+
+/**
+ * What a restore did, in one sentence, BUILT FROM THE COUNTS `applyLayout` returned so it cannot
+ * claim something the transform did not do.
+ *
+ * A clause whose count is zero is omitted rather than printed as "0" - the ordinary restore then
+ * reads as a plain confirmation instead of a report full of nothing.
+ */
+export function restoreSummary(
+ name: string,
+ counts: { moved: number; missing: number; extra: number }
+): string {
+ const parts: string[] = []
+ if (counts.moved) parts.push(`${counts.moved} node${counts.moved === 1 ? '' : 's'} moved`)
+ if (counts.missing) parts.push(`${counts.missing} no longer on this canvas`)
+ if (counts.extra) parts.push(`${counts.extra} not in this layout`)
+ return `Restored "${name}": ${parts.length ? parts.join(', ') : 'nothing changed'}.`
+}
diff --git a/src/renderer/state/projects.layouts.test.ts b/src/renderer/state/projects.layouts.test.ts
new file mode 100644
index 000000000..8e3703c19
--- /dev/null
+++ b/src/renderer/state/projects.layouts.test.ts
@@ -0,0 +1,182 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { CANVAS_LAYOUTS_CAP, CANVAS_LAYOUT_NAME_MAX, type CanvasLayout } from '@shared/canvas-layout'
+import { useProjects } from './projects'
+
+const layout = (over: Partial<CanvasLayout> = {}): CanvasLayout => ({
+ id: 'lay-1',
+ name: 'Ultrawide',
+ createdAt: 1000,
+ updatedAt: 1000,
+ nodes: [{ id: 'term-a', x: 10, y: 20, width: 400, height: 300 }],
+ ...over
+})
+
+const view = (x: number) => ({ x, y: 0, zoom: 1 })
+
+const seed = (over: Record<string, unknown> = {}) => {
+ useProjects.getState().hydrate({
+ version: 2,
+ activeProjectId: 'p1',
+ projects: [{
+ id: 'p1', name: 'x', color: '#fff', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [], ...over
+ }]
+ })
+}
+
+const stored = () => useProjects.getState().getProject('p1')
+
+beforeEach(() => seed())
+
+describe('saveLayout', () => {
+ it('writes the shared layout and this machine camera in one go', () => {
+ const result = useProjects.getState().saveLayout('p1', layout(), view(5), 4000)
+ expect(result).toBe('saved')
+ expect(stored()?.layouts).toEqual([{ ...layout(), createdAt: 4000, updatedAt: 4000 }])
+ expect(stored()?.layoutViewports).toEqual({ 'lay-1': view(5) })
+ })
+
+ it('replaces by id, keeping createdAt and bumping updatedAt', () => {
+ useProjects.getState().saveLayout('p1', layout(), view(5), 4000)
+ const result = useProjects.getState().saveLayout(
+ 'p1',
+ layout({ createdAt: 9999, nodes: [{ id: 'term-a', x: 99, y: 0, width: 1, height: 1 }] }),
+ view(6),
+ 7000
+ )
+ expect(result).toBe('saved')
+ expect(stored()?.layouts).toHaveLength(1)
+ expect(stored()?.layouts?.[0].createdAt).toBe(4000)
+ expect(stored()?.layouts?.[0].updatedAt).toBe(7000)
+ expect(stored()?.layouts?.[0].nodes[0].x).toBe(99)
+ expect(stored()?.layoutViewports).toEqual({ 'lay-1': view(6) })
+ })
+
+ it('trims and caps the name', () => {
+ const long = 'a'.repeat(CANVAS_LAYOUT_NAME_MAX + 10)
+ useProjects.getState().saveLayout('p1', layout({ name: ` ${long} ` }), view(0), 1)
+ expect(stored()?.layouts?.[0].name).toBe('a'.repeat(CANVAS_LAYOUT_NAME_MAX))
+ })
+
+ it('refuses a name that is empty once trimmed, without mutating', () => {
+ const result = useProjects.getState().saveLayout('p1', layout({ name: ' ' }), view(0), 1)
+ expect(result).toBe('invalid-name')
+ expect(stored()?.layouts).toBeUndefined()
+ })
+
+ it('refuses an unknown project instead of creating a stub', () => {
+ const result = useProjects.getState().saveLayout('nope', layout(), view(0), 1)
+ expect(result).toBe('unknown-project')
+ expect(useProjects.getState().projects).toHaveLength(1)
+ })
+
+ // The store is not the only writer of `layouts` - a git pull delivers them too - so the cap can
+ // be reached by work this user never did, and a Save must say so rather than evict a teammate's.
+ it('refuses a new layout at the cap but still allows a replace', () => {
+ const full = Array.from({ length: CANVAS_LAYOUTS_CAP }, (_, i) =>
+ layout({ id: `lay-${i}`, name: `L${i}` }))
+ seed({ layouts: full })
+
+ const refused = useProjects.getState().saveLayout('p1', layout({ id: 'lay-new' }), view(1), 5000)
+ expect(refused).toBe('cap-reached')
+ expect(stored()?.layouts).toHaveLength(CANVAS_LAYOUTS_CAP)
+ expect(stored()?.layoutViewports).toBeUndefined()
+
+ const replaced = useProjects.getState().saveLayout(
+ 'p1', layout({ id: 'lay-3', name: 'Renamed' }), view(2), 6000
+ )
+ expect(replaced).toBe('saved')
+ expect(stored()?.layouts).toHaveLength(CANVAS_LAYOUTS_CAP)
+ expect(stored()?.layouts?.find((l) => l.id === 'lay-3')?.name).toBe('Renamed')
+ })
+})
+
+describe('renameLayout', () => {
+ beforeEach(() => {
+ useProjects.getState().saveLayout('p1', layout(), view(5), 4000)
+ })
+
+ it('renames and bumps updatedAt, keeping createdAt', () => {
+ useProjects.getState().renameLayout('p1', 'lay-1', ' Laptop ', 8000)
+ expect(stored()?.layouts?.[0].name).toBe('Laptop')
+ expect(stored()?.layouts?.[0].createdAt).toBe(4000)
+ expect(stored()?.layouts?.[0].updatedAt).toBe(8000)
+ })
+
+ it('caps the name at CANVAS_LAYOUT_NAME_MAX', () => {
+ useProjects.getState().renameLayout('p1', 'lay-1', 'b'.repeat(CANVAS_LAYOUT_NAME_MAX + 5), 8000)
+ expect(stored()?.layouts?.[0].name).toBe('b'.repeat(CANVAS_LAYOUT_NAME_MAX))
+ })
+
+ it('refuses an empty name and leaves the layout untouched', () => {
+ useProjects.getState().renameLayout('p1', 'lay-1', ' ', 8000)
+ expect(stored()?.layouts?.[0].name).toBe('Ultrawide')
+ expect(stored()?.layouts?.[0].updatedAt).toBe(4000)
+ })
+
+ it('is a no-op for an unknown project or layout id', () => {
+ useProjects.getState().renameLayout('nope', 'lay-1', 'Laptop', 8000)
+ useProjects.getState().renameLayout('p1', 'lay-gone', 'Laptop', 8000)
+ expect(stored()?.layouts?.[0].name).toBe('Ultrawide')
+ })
+})
+
+describe('deleteLayout', () => {
+ it('drops the layout AND its machine-local camera', () => {
+ useProjects.getState().saveLayout('p1', layout(), view(5), 4000)
+ useProjects.getState().saveLayout('p1', layout({ id: 'lay-2', name: 'Laptop' }), view(6), 4000)
+
+ useProjects.getState().deleteLayout('p1', 'lay-1')
+ expect(stored()?.layouts?.map((l) => l.id)).toEqual(['lay-2'])
+ expect(stored()?.layoutViewports).toEqual({ 'lay-2': view(6) })
+
+ useProjects.getState().deleteLayout('p1', 'lay-2')
+ expect(stored()?.layouts).toBeUndefined()
+ expect(stored()?.layoutViewports).toBeUndefined()
+ })
+
+ it('is a no-op for an unknown project or layout id', () => {
+ useProjects.getState().saveLayout('p1', layout(), view(5), 4000)
+ useProjects.getState().deleteLayout('nope', 'lay-1')
+ useProjects.getState().deleteLayout('p1', 'lay-gone')
+ expect(stored()?.layouts).toHaveLength(1)
+ expect(stored()?.layoutViewports).toEqual({ 'lay-1': view(5) })
+ })
+})
+
+describe('recordLayoutViewport', () => {
+ it('writes the machine-local half only, leaving the shared layout byte-identical', () => {
+ useProjects.getState().saveLayout('p1', layout(), view(5), 4000)
+ const before = stored()?.layouts
+ useProjects.getState().recordLayoutViewport('p1', 'lay-1', view(42))
+ expect(stored()?.layoutViewports).toEqual({ 'lay-1': view(42) })
+ expect(stored()?.layouts).toEqual(before)
+ })
+
+ it('refuses a layout id nothing names rather than creating an orphan camera', () => {
+ useProjects.getState().recordLayoutViewport('p1', 'lay-gone', view(42))
+ useProjects.getState().recordLayoutViewport('nope', 'lay-1', view(42))
+ expect(stored()?.layoutViewports).toBeUndefined()
+ })
+})
+
+// The layout dialog and the palette schedule no canvas save of their own, so without this seam a
+// saved layout is lost on restart - the same gap the capability setters close.
+describe('layout writes schedule a workspace save', () => {
+ it('rings on a save that landed and stays silent on one that was refused', async () => {
+ const { registerWorkspaceDirty } = await import('./workspaceDirty')
+ let dirtied = 0
+ const unregister = registerWorkspaceDirty(() => dirtied++)
+ try {
+ useProjects.getState().saveLayout('p1', layout(), view(5), 4000)
+ expect(dirtied).toBe(1)
+ useProjects.getState().saveLayout('p1', layout({ id: 'x', name: ' ' }), view(5), 4000)
+ useProjects.getState().renameLayout('p1', 'lay-gone', 'Laptop', 5000)
+ useProjects.getState().deleteLayout('p1', 'lay-gone')
+ expect(dirtied).toBe(1)
+ useProjects.getState().deleteLayout('p1', 'lay-1')
+ expect(dirtied).toBe(2)
+ } finally {
+ unregister()
+ }
+ })
+})
diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.ts
index 24efa589f..79ada0201 100644
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@ -16,6 +16,12 @@ import { collisionSeed, derivedProjectId } from '@shared/project-id'
import type { ProjectCapability } from '@shared/project-capabilities'
import type { ProjectIcon } from '@shared/project-icon'
import { recordCapabilityAck, type CapabilityAnswer } from '@shared/project-capability-consent'
+import {
+ CANVAS_LAYOUTS_CAP,
+ CANVAS_LAYOUT_NAME_MAX,
+ pruneLayoutViewports,
+ type CanvasLayout
+} from '@shared/canvas-layout'
import { applyCanvasMutation, createProject, reorderGroupWithinParent } from './workspace'
import { markWorkspaceDirty } from './workspaceDirty'
import { folderName } from '../lib/projectOpen'
@@ -23,6 +29,17 @@ import { folderName } from '../lib/projectOpen'
// rope and the bridge it covers are recognized as one relationship here too.
import { pairKey as bridgePairKey } from '../lib/noteLink'
+/**
+ * What `saveLayout` did.
+ *
+ * A union rather than a boolean because the refusals need different sentences: the cap is a state
+ * the user has to resolve (delete one first), while an unusable name is a typo. Neither may be
+ * swallowed - this store is not the only writer of `layouts` (a git pull delivers them too), so
+ * the cap can be reached by work the user never did, and a Save button that quietly does nothing
+ * is exactly the failure this return value exists to prevent.
+ */
+export type SaveLayoutResult = 'saved' | 'cap-reached' | 'invalid-name' | 'unknown-project'
+
interface ProjectsState {
projects: Project[]
activeProjectId: string
@@ -169,6 +186,43 @@ interface ProjectsState {
/** Removes a closed-session entry without reopening it. */
discardClosedSession(projectId: string, entryId: string): void
+ /**
+ * Saves a layout (replacing by id) together with this machine's camera for it.
+ *
+ * The two halves land in ONE write because they are meaningless apart: the layout is CONTENT in
+ * the git-shared project file, the camera is machine-local index state, and a camera whose
+ * layout never landed is orphan bytes in a file that is forever.
+ *
+ * `now` is the caller's clock rather than a `Date.now()` in here, so the snapshot the caller
+ * built and the timestamps stored beside it cannot disagree, and a test can prove `createdAt`
+ * survived a replace. The store stamps both timestamps itself: they order the list the user
+ * reads, and a caller must not be able to backdate a layout into someone else's slot.
+ */
+ saveLayout(
+ projectId: string,
+ layout: CanvasLayout,
+ viewport: Viewport,
+ now: number
+ ): SaveLayoutResult
+ /**
+ * Renames a layout and bumps its `updatedAt`. No-op for an unknown project or layout id, and
+ * for a name that is empty once trimmed.
+ *
+ * Void where `saveLayout` reports, because every refusal here is one the call site can test for
+ * itself before calling - it knows the name it typed and the id it picked, so a return value
+ * would tell it nothing it did not already have.
+ */
+ renameLayout(projectId: string, layoutId: string, name: string, now: number): void
+ /** Deletes a layout AND this machine's camera for it. Both halves move together: a camera keyed
+ * to a layout nobody can restore is litter in a file that is forever, the rule
+ * `pruneCollapsedItems` states for `settings.sidebarCollapsedItems`. */
+ deleteLayout(projectId: string, layoutId: string): void
+ /** Records this machine's camera for a layout without touching the shared half - where I was
+ * looking after a restore is a fact about this screen, and writing it into
+ * `.nodeterm/project.json` would move everyone else's canvas. An unknown layout id is refused
+ * rather than answered with a stub, for the same reason `deleteLayout` prunes. */
+ recordLayoutViewport(projectId: string, layoutId: string, viewport: Viewport): void
+
/**
* Registers (or finds) the project for a local directory WITHOUT activating it — the store half
* of the `open-project` control verb (issue #338, spec §2.1 steps 2–4). The human paths
@@ -678,6 +732,95 @@ export const useProjects = create<ProjectsState>((set, get) => ({
}))
},
+ saveLayout(projectId, layout, viewport, now) {
+ // The dialog validates too, but the command palette reaches this action directly, so the
+ // store is the last gate before a name lands in a git-shared file.
+ const name = layout.name.trim().slice(0, CANVAS_LAYOUT_NAME_MAX)
+ if (!name) return 'invalid-name'
+ const project = get().projects.find((p) => p.id === projectId)
+ if (!project) return 'unknown-project'
+ const layouts = project.layouts ?? []
+ const idx = layouts.findIndex((l) => l.id === layout.id)
+ // Replace-by-id never counts against the cap. A genuinely new layout past it is refused rather
+ // than evicting the oldest: the list is shared, so the entry dropped to make room could be a
+ // teammate's, and losing their work to make one Save succeed is worse than a Save that says no.
+ if (idx === -1 && layouts.length >= CANVAS_LAYOUTS_CAP) return 'cap-reached'
+ const stored: CanvasLayout = {
+ ...layout,
+ name,
+ // A replace keeps the original creation moment: it is still the layout the user made that
+ // day, whatever the caller stamped on the snapshot it has just rebuilt.
+ createdAt: idx === -1 ? now : layouts[idx].createdAt,
+ updatedAt: now
+ }
+ const next = idx === -1 ? [...layouts, stored] : layouts.map((l, i) => (i === idx ? stored : l))
+ set((s) => ({
+ projects: s.projects.map((p) =>
+ p.id !== projectId
+ ? p
+ : {
+ ...p,
+ layouts: next,
+ layoutViewports: { ...(p.layoutViewports ?? {}), [stored.id]: viewport }
+ }
+ )
+ }))
+ // Saving a layout touches no node, so no canvas edit will schedule the write for us - the same
+ // persistence gap the capability setters close.
+ markWorkspaceDirty()
+ return 'saved'
+ },
+
+ renameLayout(projectId, layoutId, name, now) {
+ const clean = name.trim().slice(0, CANVAS_LAYOUT_NAME_MAX)
+ if (!clean) return
+ let changed = false
+ set((s) => ({
+ projects: s.projects.map((p) => {
+ if (p.id !== projectId || !p.layouts?.some((l) => l.id === layoutId)) return p
+ changed = true
+ return {
+ ...p,
+ layouts: p.layouts.map((l) =>
+ l.id === layoutId ? { ...l, name: clean, updatedAt: now } : l
+ )
+ }
+ })
+ }))
+ if (changed) markWorkspaceDirty()
+ },
+
+ deleteLayout(projectId, layoutId) {
+ let changed = false
+ set((s) => ({
+ projects: s.projects.map((p) => {
+ if (p.id !== projectId || !p.layouts?.some((l) => l.id === layoutId)) return p
+ changed = true
+ const layouts = p.layouts.filter((l) => l.id !== layoutId)
+ // Both halves move together, and the shared pruner is what decides which cameras survive
+ // so the store cannot grow a second opinion about it.
+ return {
+ ...p,
+ layouts: layouts.length ? layouts : undefined,
+ layoutViewports: pruneLayoutViewports(p.layoutViewports, layouts)
+ }
+ })
+ }))
+ if (changed) markWorkspaceDirty()
+ },
+
+ recordLayoutViewport(projectId, layoutId, viewport) {
+ let changed = false
+ set((s) => ({
+ projects: s.projects.map((p) => {
+ if (p.id !== projectId || !p.layouts?.some((l) => l.id === layoutId)) return p
+ changed = true
+ return { ...p, layoutViewports: { ...(p.layoutViewports ?? {}), [layoutId]: viewport } }
+ })
+ }))
+ if (changed) markWorkspaceDirty()
+ },
+
reopenProject(id) {
set((s) => {
if (!s.projects.some((p) => p.id === id)) return s
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index 4c940c4e3..949f0da35 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -1171,8 +1171,12 @@ export function createProject(
}
}
-const GROUP_PAD = 28
-const GROUP_HEADER = 34
+/** Clearance a group frame keeps around its children on every side, and the extra strip above
+ * them for its label pill. Exported so anything that has to size a frame the way
+ * `fitGroupToChildren` does (canvas layouts grow a restored frame around nodes the layout
+ * predates) matches it exactly instead of re-guessing the numbers. */
+export const GROUP_PAD = 28
+export const GROUP_HEADER = 34
const nodeW = (n: CanvasNode) => n.measured?.width ?? (n.width as number) ?? 0
const nodeH = (n: CanvasNode) => n.measured?.height ?? (n.height as number) ?? 0
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 540e3f1b7..2aa41e6e7 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -758,6 +758,104 @@ body,
flex-shrink: 0;
}
+/* Saved layouts, anchored to their own button like the zoom presets rather than to the dock's left
+ edge. Wider than the add menu because each row carries a name plus its subtitle. */
+.dock-layouts-wrap {
+ position: relative;
+ display: inline-flex;
+}
+
+.dock-layouts-menu {
+ left: 50%;
+ transform: translateX(-50%);
+ min-width: 260px;
+ max-width: 340px;
+}
+
+/* A row is a container, not a button: the restore action and the two per-row actions are separate
+ buttons, and a button cannot legally nest inside another one. */
+.dock-menu__row {
+ display: flex;
+ align-items: center;
+ border-radius: 8px;
+}
+
+.dock-menu__row:hover,
+.dock-menu__row:focus-within {
+ background: var(--panel-header);
+}
+
+/* Qualified with `button` throughout this group: the generic `.dock-menu button` rules above are
+ (0,1,1) and would otherwise out-specify a bare class whatever the source order. */
+.dock-menu button.dock-menu__row-main {
+ flex: 1;
+ min-width: 0;
+}
+
+/* The row already carries the hover background; a second one on the button would sit on top of it
+ with square corners at the trailing edge. */
+.dock-menu button.dock-menu__row-main:hover:not(:disabled) {
+ background: transparent;
+}
+
+.dock-menu__row-text {
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ min-width: 0;
+}
+
+.dock-menu__row-name,
+.dock-menu__row-sub {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.dock-menu__row-sub {
+ font-size: 11px;
+ color: var(--muted);
+ font-variant-numeric: tabular-nums;
+}
+
+/* Revealed on hover or keyboard focus. Kept in the layout at all times (opacity, not display) so a
+ row's width does not jump as the pointer crosses it. */
+.dock-menu__row-actions {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ padding-right: 6px;
+ opacity: 0;
+}
+
+.dock-menu__row:hover .dock-menu__row-actions,
+.dock-menu__row:focus-within .dock-menu__row-actions {
+ opacity: 1;
+}
+
+.dock-menu button.dock-menu__row-act {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 22px;
+ height: 22px;
+ padding: 0;
+ background: transparent;
+ border: none;
+ border-radius: 6px;
+ color: var(--muted);
+ cursor: pointer;
+}
+
+.dock-menu button.dock-menu__row-act:hover {
+ background: var(--surface-overlay);
+ color: var(--text);
+}
+
+.dock-menu button.dock-menu__row-act:hover svg {
+ color: inherit;
+}
+
/* One level of flyout submenu — for a builtin harness that has inheriting custom agents (e.g. a
* claude-compatible proxy). The parent button carries a ▸ chevron; hovering/focusing it opens the
* flyout to the right of the menu. Reused only when there is something to nest, so a menu with no
diff --git a/src/shared/canvas-layout.test.ts b/src/shared/canvas-layout.test.ts
new file mode 100644
index 000000000..f0bdef4af
--- /dev/null
+++ b/src/shared/canvas-layout.test.ts
@@ -0,0 +1,228 @@
+import { describe, it, expect } from 'vitest'
+import {
+ CANVAS_LAYOUTS_CAP,
+ CANVAS_LAYOUT_NAME_MAX,
+ findLayoutByName,
+ pruneLayoutViewports,
+ sanitizeLayoutViewports,
+ sanitizeLayouts,
+ type CanvasLayout,
+ type CanvasLayoutNode
+} from './canvas-layout'
+
+const layoutNode = (over: Partial<CanvasLayoutNode> = {}): CanvasLayoutNode => ({
+ id: 'term-abc', x: 10, y: 20, width: 400, height: 300, ...over
+})
+const layout = (over: Partial<CanvasLayout> = {}): CanvasLayout => ({
+ id: 'lay-1', name: 'Ultrawide', createdAt: 1000, updatedAt: 2000, nodes: [layoutNode()], ...over
+})
+
+describe('sanitizeLayouts admits a well-formed list', () => {
+ it('keeps every known field and normalizes the optional ones', () => {
+ const admitted = sanitizeLayouts([
+ layout({
+ window: { width: 3440, height: 1440 },
+ nodes: [layoutNode({ collapsed: true, parentId: 'grp-1' })]
+ })
+ ])
+ expect(admitted).toEqual([{
+ id: 'lay-1', name: 'Ultrawide', createdAt: 1000, updatedAt: 2000,
+ window: { width: 3440, height: 1440 },
+ nodes: [{ id: 'term-abc', x: 10, y: 20, width: 400, height: 300, collapsed: true, parentId: 'grp-1' }]
+ }])
+ })
+
+ it('drops unknown fields on the layout and on its nodes', () => {
+ const admitted = sanitizeLayouts([
+ { ...layout({ nodes: [{ ...layoutNode(), cwd: '/etc' } as never] }), initialCommand: 'rm -rf /' }
+ ])
+ expect(admitted![0]).not.toHaveProperty('initialCommand')
+ expect(admitted![0].nodes[0]).not.toHaveProperty('cwd')
+ })
+
+ it('keeps `collapsed` only when it is literally true, `parentId` only when a non-empty string', () => {
+ const admitted = sanitizeLayouts([
+ layout({ nodes: [layoutNode({ collapsed: 'yes' as never, parentId: '' })] })
+ ])
+ expect(admitted![0].nodes[0]).toEqual({ id: 'term-abc', x: 10, y: 20, width: 400, height: 300 })
+ })
+})
+
+describe('sanitizeLayouts drops rather than repairs', () => {
+ it('refuses anything that is not an array', () => {
+ for (const bad of [undefined, null, 0, 'layouts', {}, { 0: layout() }]) {
+ expect(sanitizeLayouts(bad)).toBeUndefined()
+ }
+ })
+
+ it('drops a layout that is not an object', () => {
+ expect(sanitizeLayouts(['x', 42, null, [layout()]])).toBeUndefined()
+ })
+
+ it('drops a layout with a non-string id or name', () => {
+ expect(sanitizeLayouts([layout({ id: 7 as never })])).toBeUndefined()
+ expect(sanitizeLayouts([layout({ id: '' })])).toBeUndefined()
+ expect(sanitizeLayouts([layout({ name: 7 as never })])).toBeUndefined()
+ })
+
+ it('drops a layout whose timestamps are not finite numbers', () => {
+ expect(sanitizeLayouts([layout({ createdAt: NaN })])).toBeUndefined()
+ expect(sanitizeLayouts([layout({ updatedAt: Infinity })])).toBeUndefined()
+ expect(sanitizeLayouts([layout({ createdAt: '1000' as never })])).toBeUndefined()
+ })
+
+ it('drops a layout whose nodes are not an array', () => {
+ expect(sanitizeLayouts([layout({ nodes: {} as never })])).toBeUndefined()
+ expect(sanitizeLayouts([layout({ nodes: undefined as never })])).toBeUndefined()
+ })
+
+ it('drops the WHOLE layout when any one node entry is malformed', () => {
+ // A repaired layout silently no longer describes the arrangement it is named after.
+ const withBadNode = (bad: unknown) => sanitizeLayouts([
+ layout({ nodes: [layoutNode(), bad as CanvasLayoutNode, layoutNode({ id: 'term-z' })] })
+ ])
+ expect(withBadNode(null)).toBeUndefined()
+ expect(withBadNode('term-b')).toBeUndefined()
+ expect(withBadNode(layoutNode({ id: 42 as never }))).toBeUndefined()
+ expect(withBadNode(layoutNode({ id: '' }))).toBeUndefined()
+ })
+
+ it('drops a layout with a non-finite coordinate or size - the React Flow crash', () => {
+ for (const key of ['x', 'y', 'width', 'height'] as const) {
+ expect(sanitizeLayouts([layout({ nodes: [layoutNode({ [key]: NaN })] })])).toBeUndefined()
+ expect(sanitizeLayouts([layout({ nodes: [layoutNode({ [key]: Infinity })] })])).toBeUndefined()
+ expect(sanitizeLayouts([layout({ nodes: [layoutNode({ [key]: null as never })] })])).toBeUndefined()
+ expect(sanitizeLayouts([layout({ nodes: [layoutNode({ [key]: '10' as never })] })])).toBeUndefined()
+ }
+ })
+
+ it('drops a bad layout without taking the good ones with it', () => {
+ const admitted = sanitizeLayouts([layout(), layout({ id: 'lay-2', createdAt: NaN }), layout({ id: 'lay-3' })])
+ expect(admitted?.map((l) => l.id)).toEqual(['lay-1', 'lay-3'])
+ })
+})
+
+describe('sanitizeLayouts names and caps', () => {
+ it('trims the name and drops a layout whose trimmed name is empty', () => {
+ expect(sanitizeLayouts([layout({ name: ' Laptop ' })])![0].name).toBe('Laptop')
+ expect(sanitizeLayouts([layout({ name: ' ' })])).toBeUndefined()
+ expect(sanitizeLayouts([layout({ name: '' })])).toBeUndefined()
+ })
+
+ it('caps the name at CANVAS_LAYOUT_NAME_MAX', () => {
+ const admitted = sanitizeLayouts([layout({ name: 'x'.repeat(CANVAS_LAYOUT_NAME_MAX + 40) })])
+ expect(admitted![0].name).toHaveLength(CANVAS_LAYOUT_NAME_MAX)
+ })
+
+ it('caps the list at CANVAS_LAYOUTS_CAP, keeping the first N', () => {
+ const many = Array.from({ length: CANVAS_LAYOUTS_CAP + 5 }, (_, i) => layout({ id: `lay-${i}` }))
+ const admitted = sanitizeLayouts(many)
+ expect(admitted).toHaveLength(CANVAS_LAYOUTS_CAP)
+ expect(admitted![0].id).toBe('lay-0')
+ expect(admitted![CANVAS_LAYOUTS_CAP - 1].id).toBe(`lay-${CANVAS_LAYOUTS_CAP - 1}`)
+ })
+})
+
+describe('sanitizeLayouts window', () => {
+ it('admits it only when both numbers are finite and positive', () => {
+ const win = (w: unknown) => sanitizeLayouts([layout({ window: w as never })])![0].window
+ expect(win({ width: 1440, height: 900 })).toEqual({ width: 1440, height: 900 })
+ expect(win({ width: 0, height: 900 })).toBeUndefined()
+ expect(win({ width: -1, height: 900 })).toBeUndefined()
+ expect(win({ width: NaN, height: 900 })).toBeUndefined()
+ expect(win({ width: 1440 })).toBeUndefined()
+ expect(win('3440x1440')).toBeUndefined()
+ expect(win(null)).toBeUndefined()
+ })
+
+ it('a bad window never takes the layout with it', () => {
+ const admitted = sanitizeLayouts([layout({ window: { width: NaN, height: 0 } })])
+ expect(admitted).toHaveLength(1)
+ expect(admitted![0].nodes).toHaveLength(1)
+ })
+})
+
+describe('sanitizeLayouts returns undefined, never []', () => {
+ it('for an empty list and for a list where nothing survives', () => {
+ expect(sanitizeLayouts([])).toBeUndefined()
+ expect(sanitizeLayouts([layout({ name: ' ' }), 'junk'])).toBeUndefined()
+ })
+
+ it('a layout with no nodes is still a layout (an empty canvas has an arrangement)', () => {
+ expect(sanitizeLayouts([layout({ nodes: [] })])![0].nodes).toEqual([])
+ })
+})
+
+describe('sanitizeLayoutViewports', () => {
+ it('keeps well-formed entries and normalizes to exactly x/y/zoom', () => {
+ const views = sanitizeLayoutViewports({ 'lay-1': { x: 1, y: 2, zoom: 0.5, extra: 9 } })
+ expect(views).toEqual({ 'lay-1': { x: 1, y: 2, zoom: 0.5 } })
+ })
+
+ it('drops entries whose key is empty or whose numbers are not finite', () => {
+ expect(sanitizeLayoutViewports({ '': { x: 1, y: 2, zoom: 1 } })).toBeUndefined()
+ expect(sanitizeLayoutViewports({ 'lay-1': { x: NaN, y: 2, zoom: 1 } })).toBeUndefined()
+ expect(sanitizeLayoutViewports({ 'lay-1': { x: 1, y: 2, zoom: Infinity } })).toBeUndefined()
+ expect(sanitizeLayoutViewports({ 'lay-1': { x: 1, y: 2 } })).toBeUndefined()
+ expect(sanitizeLayoutViewports({ 'lay-1': 'centered' })).toBeUndefined()
+ })
+
+ it('drops a bad entry without taking the good ones with it', () => {
+ const views = sanitizeLayoutViewports({
+ 'lay-1': { x: 1, y: 2, zoom: 1 },
+ 'lay-2': { x: NaN, y: 0, zoom: 1 }
+ })
+ expect(views).toEqual({ 'lay-1': { x: 1, y: 2, zoom: 1 } })
+ })
+
+ it('refuses anything that is not a plain object, and answers undefined when empty', () => {
+ for (const bad of [undefined, null, 0, 'views', [], [{ x: 1, y: 2, zoom: 1 }]]) {
+ expect(sanitizeLayoutViewports(bad)).toBeUndefined()
+ }
+ expect(sanitizeLayoutViewports({})).toBeUndefined()
+ })
+})
+
+describe('pruneLayoutViewports', () => {
+ it('drops keys naming no live layout', () => {
+ const views = { 'lay-1': { x: 1, y: 2, zoom: 1 }, 'lay-gone': { x: 3, y: 4, zoom: 2 } }
+ expect(pruneLayoutViewports(views, [layout({ id: 'lay-1' })])).toEqual({
+ 'lay-1': { x: 1, y: 2, zoom: 1 }
+ })
+ })
+
+ it('answers undefined when nothing survives, or when there are no layouts at all', () => {
+ const views = { 'lay-gone': { x: 3, y: 4, zoom: 2 } }
+ expect(pruneLayoutViewports(views, [layout({ id: 'lay-1' })])).toBeUndefined()
+ expect(pruneLayoutViewports(views, undefined)).toBeUndefined()
+ expect(pruneLayoutViewports(views, [])).toBeUndefined()
+ expect(pruneLayoutViewports(undefined, [layout()])).toBeUndefined()
+ })
+
+ it('keeps every entry that still names a live layout', () => {
+ const views = { 'lay-1': { x: 1, y: 2, zoom: 1 }, 'lay-2': { x: 3, y: 4, zoom: 2 } }
+ expect(pruneLayoutViewports(views, [layout({ id: 'lay-1' }), layout({ id: 'lay-2' })])).toEqual(views)
+ })
+})
+
+describe('findLayoutByName', () => {
+ const layouts = [layout({ id: 'lay-1', name: 'Ultrawide' }), layout({ id: 'lay-2', name: 'Laptop' })]
+
+ it('matches ignoring case and surrounding space', () => {
+ expect(findLayoutByName(layouts, ' ULTRAwide ')?.id).toBe('lay-1')
+ expect(findLayoutByName(layouts, 'laptop')?.id).toBe('lay-2')
+ })
+
+ it('answers undefined for a name nothing carries, an empty needle or no list', () => {
+ expect(findLayoutByName(layouts, 'Vertical')).toBeUndefined()
+ expect(findLayoutByName(layouts, ' ')).toBeUndefined()
+ expect(findLayoutByName(undefined, 'Ultrawide')).toBeUndefined()
+ })
+
+ // The ask must normalize exactly the way the save does, or an over-long name matches nothing,
+ // passes the ask, and is then stored under the capped name it collides with.
+ it('caps the needle the way a save caps the stored name', () => {
+ const capped = 'a'.repeat(CANVAS_LAYOUT_NAME_MAX)
+ expect(findLayoutByName([layout({ name: capped })], `${capped}bbbb`)?.name).toBe(capped)
+ })
+})
diff --git a/src/shared/canvas-layout.ts b/src/shared/canvas-layout.ts
new file mode 100644
index 000000000..aa355179d
--- /dev/null
+++ b/src/shared/canvas-layout.ts
@@ -0,0 +1,237 @@
+import type { Viewport } from './types'
+
+/**
+ * A canvas layout is a NAMED SNAPSHOT OF NODE GEOMETRY for one project: where every node sat, how
+ * big it was, and whether it was collapsed. It exists so an arrangement made for an ultrawide
+ * monitor can be restored after a day on the laptop screen, without rebuilding it by hand.
+ *
+ * It carries GEOMETRY ONLY, and that is the whole safety story. A restore never creates, deletes,
+ * renames, recolors, reparents or respawns a node, and never touches a tmux session - so the worst
+ * a bad layout can do is move things, which the user can undo. The moment a layout could carry a
+ * node's identity (a `cwd`, a command, an agent id) it would become a second, stale copy of the
+ * canvas competing with `project.json`, and restoring it would be a merge rather than a move.
+ *
+ * The snapshot is CONTENT: it rides the git-shared `.nodeterm/project.json` beside `nodes` and
+ * `kanban`, because node geometry is already shared content in that file and a restore writes
+ * exactly those fields. The camera precedent (`viewport`, `breadcrumbs`) deliberately does NOT
+ * reach here - those are camera facts, and nobody else's canvas moves when I pan. This machine's
+ * camera per layout is the separate, machine-local `LayoutViewports`.
+ *
+ * Everything here therefore treats its input as hostile: `.nodeterm/project.json` is git-shared,
+ * cloned and hand-editable, exactly like the node icons and trigger specs beside it. The readers
+ * below DROP rather than repair, for the same reason `sanitizeLoadedClosedSessions` does - a
+ * half-honored geometry is a canvas that is wrong in a way nobody can see.
+ */
+
+/**
+ * One node's remembered rect inside a layout.
+ *
+ * The rect is ROOT-space - the coordinate space `withNodeRect` (renderer/state/workspace.ts)
+ * already speaks - so a node whose frame was ungrouped, moved or re-fitted since the layout was
+ * saved still lands where the author put it on screen, rather than a few hundred pixels off its
+ * old parent's origin.
+ */
+export interface CanvasLayoutNode {
+ id: string
+ x: number
+ y: number
+ width: number
+ /**
+ * Always the EXPANDED height, matching the rule `flowToNodeStates` uses when it serializes a
+ * collapsed node: a collapsed node's on-screen height is chrome, not a size the user chose, and
+ * storing it would make every save-while-collapsed shrink the node permanently.
+ */
+ height: number
+ collapsed?: boolean
+ /**
+ * The parent frame at capture time. Recorded so a restore can be HONEST about what changed (a
+ * node that has since moved to another frame is a fact worth reporting); never used to reparent
+ * anything, which would make a restore a structural edit rather than a move.
+ */
+ parentId?: string
+}
+
+/** A named geometry snapshot for one project. See the module doc block for the trust model. */
+export interface CanvasLayout {
+ id: string
+ /** Trimmed, at most `CANVAS_LAYOUT_NAME_MAX` characters. */
+ name: string
+ createdAt: number
+ updatedAt: number
+ /**
+ * The AUTHOR's window size when they saved it. A LABEL for the reader ("this one was made on the
+ * 34 inch"), never a matcher and never a claim about the machine reading it: the file travels,
+ * so auto-selecting a layout from it would pick a stranger's monitor for the user's screen.
+ */
+ window?: { width: number; height: number }
+ nodes: CanvasLayoutNode[]
+}
+
+/**
+ * This machine's camera per layout, keyed by layout id.
+ *
+ * MACHINE-LOCAL: it rides `IndexEntryV3.layoutViewports` and is never written into the shared
+ * project file, the same rule `viewport` and `breadcrumbs` follow. Where a teammate was looking
+ * when they saved the arrangement is not something a repo carries.
+ */
+export type LayoutViewports = Record<string, Viewport>
+
+/** How many layouts one project may keep. A layout is a full node-geometry list, and the file it
+ * lives in is committed and cloned, so the list is bounded rather than left to grow. */
+export const CANVAS_LAYOUTS_CAP = 20
+
+/** Longest a layout name may be. It is rendered in a menu, and the file it rides is git-shared,
+ * so an unbounded string is a blob in everyone's checkout (the `NodeIcon` emoji rule). */
+export const CANVAS_LAYOUT_NAME_MAX = 60
+
+const isFiniteNumber = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
+
+/**
+ * The tolerant reader for one layout node entry, or `null` when the entry is unusable.
+ *
+ * A non-finite coordinate is the crash, not a tidiness concern: a restore assigns these straight
+ * onto `node.position` / the node size, and React Flow's `adoptUserNodes` dereferences the
+ * position unguarded - a white-screen renderer crash from a file anyone can commit. `NaN` also
+ * survives a round trip in the worst possible way: `JSON.stringify` writes it back into the
+ * committed file as `null`, so one bad edit becomes a permanently broken shared document.
+ *
+ * Unknown fields are dropped rather than carried: whatever we admit is what a later
+ * `projectToFile` writes back, so passing an unrecognized key through would let a hand edit
+ * accumulate in everyone's checkout.
+ */
+function sanitizeLayoutNode(x: unknown): CanvasLayoutNode | null {
+ if (!x || typeof x !== 'object') return null
+ const n = x as Partial<CanvasLayoutNode>
+ if (typeof n.id !== 'string' || !n.id) return null
+ if (!isFiniteNumber(n.x) || !isFiniteNumber(n.y)) return null
+ if (!isFiniteNumber(n.width) || !isFiniteNumber(n.height)) return null
+ return {
+ id: n.id,
+ x: n.x,
+ y: n.y,
+ width: n.width,
+ height: n.height,
+ ...(n.collapsed === true ? { collapsed: true } : {}),
+ ...(typeof n.parentId === 'string' && n.parentId ? { parentId: n.parentId } : {})
+ }
+}
+
+/** The author's window size, or `undefined`: both numbers must be finite and positive, because the
+ * value is only ever shown as a label and a `0 x 0` or `NaN x NaN` label is worse than none. */
+function sanitizeLayoutWindow(x: unknown): { width: number; height: number } | undefined {
+ if (!x || typeof x !== 'object') return undefined
+ const w = x as Partial<{ width: number; height: number }>
+ if (!isFiniteNumber(w.width) || !isFiniteNumber(w.height)) return undefined
+ if (w.width <= 0 || w.height <= 0) return undefined
+ return { width: w.width, height: w.height }
+}
+
+/**
+ * The tolerant reader for a project's layouts, applied on BOTH sides of the shared-file boundary
+ * (`fileToProject` on the way in, `projectToFile` on the way out) - the same two-seam rule
+ * `normalizeNodeIcon` and `sanitizeNodeTriggers` follow. Live node data is reachable by a peer
+ * canvas mutation, and whatever we write is what the next machine trusts, so validating only the
+ * read direction passes every round-trip test while leaving the other one open.
+ *
+ * It DROPS rather than repairs. A layout is dropped WHOLE when any part of it is wrong: a repaired
+ * layout is one that silently no longer describes the arrangement it is named after, and a
+ * half-restored canvas is wrong in a way the user cannot see. See `sanitizeLayoutNode` for why a
+ * non-finite coordinate in particular is a crash rather than a blemish.
+ *
+ * Returns `undefined` - never `[]` - for anything that fails or has nothing to admit, the
+ * convention `sanitizeLoadedClosedSessions` sets: an absent field adds no bytes to the committed
+ * file, while an empty array does.
+ */
+export function sanitizeLayouts(x: unknown): CanvasLayout[] | undefined {
+ if (!Array.isArray(x)) return undefined
+ const out: CanvasLayout[] = []
+ for (const raw of x) {
+ if (out.length >= CANVAS_LAYOUTS_CAP) break
+ if (!raw || typeof raw !== 'object') continue
+ const l = raw as Partial<CanvasLayout>
+ if (typeof l.id !== 'string' || !l.id) continue
+ if (typeof l.name !== 'string') continue
+ if (!isFiniteNumber(l.createdAt) || !isFiniteNumber(l.updatedAt)) continue
+ if (!Array.isArray(l.nodes)) continue
+ const name = l.name.trim().slice(0, CANVAS_LAYOUT_NAME_MAX)
+ if (!name) continue
+ const nodes: CanvasLayoutNode[] = []
+ let bad = false
+ for (const entry of l.nodes) {
+ const node = sanitizeLayoutNode(entry)
+ if (!node) { bad = true; break }
+ nodes.push(node)
+ }
+ if (bad) continue
+ const window = sanitizeLayoutWindow(l.window)
+ out.push({
+ id: l.id,
+ name,
+ createdAt: l.createdAt,
+ updatedAt: l.updatedAt,
+ ...(window ? { window } : {}),
+ nodes
+ })
+ }
+ return out.length ? out : undefined
+}
+
+/**
+ * The tolerant reader for this machine's per-layout cameras. Same rules as `sanitizeLayouts`, one
+ * layer down: workspace.json is hand-editable too, and a non-finite `zoom` reaching `setViewport`
+ * blanks the canvas just as effectively as a non-finite position does.
+ */
+export function sanitizeLayoutViewports(x: unknown): LayoutViewports | undefined {
+ if (!x || typeof x !== 'object' || Array.isArray(x)) return undefined
+ const out: LayoutViewports = {}
+ for (const [key, value] of Object.entries(x as Record<string, unknown>)) {
+ if (!key) continue
+ if (!value || typeof value !== 'object') continue
+ const v = value as Partial<Viewport>
+ if (!isFiniteNumber(v.x) || !isFiniteNumber(v.y) || !isFiniteNumber(v.zoom)) continue
+ out[key] = { x: v.x, y: v.y, zoom: v.zoom }
+ }
+ return Object.keys(out).length ? out : undefined
+}
+
+/**
+ * Drops camera entries naming no live layout.
+ *
+ * workspace.json is forever and a canvas churns through ids, so an id-keyed machine-local map that
+ * is only ever added to grows without bound - the rule `pruneCollapsedItems` states for
+ * `settings.sidebarCollapsedItems`. Run on both save and load, so a layout deleted by a teammate
+ * (the layouts are shared, the cameras are not) cannot leave a permanent orphan here.
+ */
+export function pruneLayoutViewports(
+ views: LayoutViewports | undefined,
+ layouts: CanvasLayout[] | undefined
+): LayoutViewports | undefined {
+ if (!views) return undefined
+ const live = new Set((layouts ?? []).map((l) => l.id))
+ const out: LayoutViewports = {}
+ for (const [key, value] of Object.entries(views)) {
+ if (live.has(key)) out[key] = value
+ }
+ return Object.keys(out).length ? out : undefined
+}
+
+/**
+ * The layout whose name matches `name`, ignoring case and surrounding space.
+ *
+ * Name uniqueness is enforced HERE, at the point of save, and deliberately NOT as an invariant
+ * over the list: the layouts are git-shared, so a merge can legitimately land two called
+ * "Ultrawide", and silently dropping a teammate's on load is the worse failure. The UI asks this
+ * before saving and offers to replace; nothing repairs a list that already holds a duplicate.
+ *
+ * The needle is normalized exactly the way a save normalizes it (trim, then the same cap), or a
+ * 70-character name would match nothing, pass the ask, and then be stored under the 60-character
+ * name it collides with.
+ */
+export function findLayoutByName(
+ layouts: CanvasLayout[] | undefined,
+ name: string
+): CanvasLayout | undefined {
+ const needle = name.trim().slice(0, CANVAS_LAYOUT_NAME_MAX).toLowerCase()
+ if (!needle) return undefined
+ return (layouts ?? []).find((l) => l.name.trim().toLowerCase() === needle)
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 609b10b9c..92ec3aac5 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -13,6 +13,7 @@ import type { WhisperModelInfo } from './speech'
import type { ProjectKanbanGitHub } from './github-issues'
import type { CodexAccount } from './codex-account'
import type { ProjectIcon, ProjectIconPickResult } from './project-icon'
+import type { CanvasLayout, LayoutViewports } from './canvas-layout'
import type {
ModelDiscoveryResult,
ModelGatewayCredentialStatus,
@@ -754,6 +755,19 @@ export interface Project {
* `IndexEntryV3.breadcrumbs`, never emitted into the shared project file (a repo must not carry
* one person's wandering camera history). */
breadcrumbs?: NavStop[]
+ /**
+ * Named geometry snapshots for this canvas - see @shared/canvas-layout for what a layout may
+ * carry and why it may carry nothing else.
+ *
+ * CONTENT, git-shared via `.nodeterm/project.json` like `kanban`: node geometry is already
+ * shared content in that file and a restore writes exactly those fields, so the snapshot belongs
+ * beside them. The camera precedent (`viewport`, `breadcrumbs`) deliberately does NOT reach
+ * here - those are camera facts, and nobody else's canvas moves when I pan.
+ */
+ layouts?: CanvasLayout[]
+ /** This machine's camera per layout, keyed by layout id. MACHINE-LOCAL: rides
+ * `IndexEntryV3.layoutViewports`, never the shared file - same rule as `breadcrumbs`. */
+ layoutViewports?: LayoutViewports
/**
* Closed projects are hidden from the tab bar but kept on disk with all their nodes (and their
* tmux sessions left running) so they can be reopened from the start screen's "Recently closed"