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.

refactor(canvas): one reducer for node, edge and board ops

review990b0d3e127b
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 8fa02b554..0ed2bc93f 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -598,6 +598,7 @@ import { sshHostKey } from '@shared/ssh'
import type {
BridgeLink,
ClaudeSessionCopyResult,
+ CanvasMutation,
CanvasNodeState,
ClosedSessionEntry,
HostedSessionApi,
@@ -3835,6 +3836,16 @@ export function Canvas() {
if (!pub || !pub.hasOwed() || loadingRef.current) return
pub.publish(publishableLater(nodesRef.current))
}
+ // A peer op for a project React Flow does not hold lands in its STORED copy. Save only when
+ // that copy actually changed: the store writes nothing for an op that changes nothing (a
+ // duplicate cast — every Server Edition tab re-casts what it receives — or a remove of something
+ // already gone), so the project object's identity is the answer, and a no-op schedules no save.
+ const applyToStored = (projectId: string, mutation: CanvasMutation): void => {
+ const store = useProjects.getState()
+ const before = store.getProject(projectId)
+ if (store.applyCanvasOp(projectId, mutation) && useProjects.getState().getProject(projectId) !== before)
+ markDirty()
+ }
return activeSession.api.canvas.onMutation((projectId, mutation) => {
hasPeersRef.current = true // proof of a peer, whatever the presence table says
const order = orderRef.current
@@ -3854,7 +3865,7 @@ export function Canvas() {
// Live only while React Flow holds that project (the epoch tag), not merely while it is the
// active one — the same rule as the node branch below (`liveCanvasHolds`).
if (!liveCanvasHolds(nodesProjectIdRef.current, useProjects.getState().activeProjectId, projectId)) {
- if (useProjects.getState().applyEdgeMutation(projectId, mutation)) markDirty()
+ applyToStored(projectId, mutation)
return
}
// One id is one edge (`applyEdgeMutationToScene`): an upsert of one kind also takes that id
@@ -3909,7 +3920,7 @@ export function Canvas() {
// its page running invisibly until the next switch.
useWebviewKeepAlive.getState().drop(mutation.id)
}
- if (useProjects.getState().applyNodeMutation(projectId, mutation)) markDirty()
+ applyToStored(projectId, mutation)
return
}
// PATCH THE LIVE ARRAY — do not round-trip the canvas through the (lossy) serializers. That
diff --git a/src/renderer/state/projects.mutation.test.ts b/src/renderer/state/projects.mutation.test.ts
index 488e55ac0..900af2256 100644
--- a/src/renderer/state/projects.mutation.test.ts
+++ b/src/renderer/state/projects.mutation.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { useProjects } from './projects'
-import type { CanvasNodeState } from '@shared/types'
+import type { CanvasMutation, CanvasNodeState } from '@shared/types'
+import { defaultKanbanFor } from '@shared/kanban-default-board'
const node = (id: string, x = 0): CanvasNodeState => ({
id,
@@ -123,3 +124,95 @@ describe('applyEdgeMutation', () => {
expect(useProjects.getState().getProject(p.id)?.ropes).toEqual([])
})
})
+
+/**
+ * The store's ONE apply path (`applyCanvasOp`, over @shared/canvas-content's reducer): node, edge
+ * and board ops for a project React Flow does not hold. `applyNodeMutation` / `applyEdgeMutation`
+ * delegate to it. `false` means only "no such project here".
+ */
+describe('applyCanvasOp', () => {
+ const link = (id: string, source = 'a', target = 'b') => ({ id, source, target })
+ const setup = () => {
+ const p = useProjects.getState().addProject('p')
+ useProjects.getState().commitCanvas(p.id, [node('a'), node('b')], { x: 0, y: 0, zoom: 1 })
+ return p.id
+ }
+
+ it('applies a node op', () => {
+ const id = setup()
+ expect(useProjects.getState().applyCanvasOp(id, { op: 'upsert', node: node('c', 7) })).toBe(true)
+ expect(useProjects.getState().getProject(id)?.nodes.map((n) => n.id)).toEqual(['a', 'b', 'c'])
+ })
+
+ it('applies an edge op', () => {
+ const id = setup()
+ expect(
+ useProjects.getState().applyCanvasOp(id, { op: 'edge-upsert', kind: 'bridge', edge: link('x') })
+ ).toBe(true)
+ expect(useProjects.getState().getProject(id)?.bridges).toEqual([link('x')])
+ })
+
+ it('applies a board op, materializing the lazy default board', () => {
+ const id = setup()
+ expect(useProjects.getState().getProject(id)?.kanban).toBeUndefined()
+ const col = defaultKanbanFor(id).columns[1].id
+ expect(
+ useProjects.getState().applyCanvasOp(id, { op: 'kb-card', assignment: { nodeId: 'a', columnId: col } })
+ ).toBe(true)
+ const board = useProjects.getState().getProject(id)?.kanban
+ expect(board?.columns).toEqual(defaultKanbanFor(id).columns)
+ expect(board?.assignments).toEqual([{ nodeId: 'a', columnId: col }])
+ })
+
+ it('reports false for an unknown project and creates nothing', () => {
+ expect(useProjects.getState().applyCanvasOp('nope', { op: 'kb-card-remove', nodeId: 'a' })).toBe(false)
+ expect(useProjects.getState().projects).toHaveLength(0)
+ })
+
+ // A duplicate op (every Server Edition tab re-casts what it receives) must not rebuild `projects`:
+ // every subscriber to the store re-runs on a new array, and the caller would schedule a save of a
+ // canvas that did not change.
+ it('an op that changes nothing is applied (true) without touching the store', () => {
+ const id = setup()
+ useProjects.getState().applyCanvasOp(id, { op: 'edge-upsert', kind: 'rope', edge: link('r') })
+ const projects = useProjects.getState().projects
+ const dup: CanvasMutation[] = [
+ { op: 'upsert', node: node('a') },
+ { op: 'remove', id: 'ghost' },
+ { op: 'edge-upsert', kind: 'rope', edge: link('r') },
+ { op: 'edge-remove', kind: 'bridge', id: 'ghost' },
+ { op: 'kb-card-remove', nodeId: 'a' }
+ ]
+ for (const m of dup) {
+ expect(useProjects.getState().applyCanvasOp(id, m)).toBe(true)
+ expect(useProjects.getState().projects, JSON.stringify(m)).toBe(projects)
+ }
+ // The two legacy entry points keep the same contract.
+ expect(useProjects.getState().applyNodeMutation(id, { op: 'upsert', node: node('b') })).toBe(true)
+ expect(useProjects.getState().applyEdgeMutation(id, { op: 'edge-upsert', kind: 'rope', edge: link('r') })).toBe(true)
+ expect(useProjects.getState().projects).toBe(projects)
+ })
+
+ it('writes back only what changed — an absent list or board stays absent', () => {
+ const id = setup()
+ useProjects.getState().applyCanvasOp(id, { op: 'upsert', node: node('c') })
+ const p = useProjects.getState().getProject(id)
+ expect(p?.bridges).toBeUndefined()
+ expect(p?.ropes).toBeUndefined()
+ expect(p?.kanban).toBeUndefined()
+ expect(p && 'kanban' in p).toBe(false)
+ })
+
+ it('the node and edge entry points route a board op too (one reducer)', () => {
+ const id = setup()
+ const col = defaultKanbanFor(id).columns[0].id
+ useProjects.getState().applyNodeMutation(id, { op: 'kb-card', assignment: { nodeId: 'b', columnId: col } })
+ expect(useProjects.getState().getProject(id)?.kanban?.assignments).toEqual([{ nodeId: 'b', columnId: col }])
+ })
+
+ it('never lets a peer set our shell', () => {
+ const id = setup()
+ useProjects.getState().applyCanvasOp(id, { op: 'upsert', node: { ...node('evil'), shell: '/bin/evil' } })
+ expect(useProjects.getState().getProject(id)?.nodes.find((n) => n.id === 'evil')?.shell).toBeUndefined()
+ })
+})
diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.ts
index 5157788fe..0f28b2c70 100644
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@ -22,8 +22,8 @@ import {
pruneLayoutViewports,
type CanvasLayout
} from '@shared/canvas-layout'
-import { applyEdgeMutationToScene } from '@shared/canvas-mutations'
-import { applyCanvasMutation, createProject, reorderGroupWithinParent } from './workspace'
+import { applyCanvasOp as applyCanvasOpTo, contentOf } from '@shared/canvas-content'
+import { createProject, reorderGroupWithinParent } from './workspace'
import { markWorkspaceDirty } from './workspaceDirty'
import { folderName } from '../lib/projectOpen'
// One order-independent key for an edge's endpoints — the SAME rule `hiddenLinkIds` uses, so a
@@ -145,6 +145,20 @@ interface ProjectsState {
* `ctrl-<source>-<target>` — two ids, one relationship each. No-op for an unknown project.
*/
appendCanvasLinks(projectId: string, links: { bridges?: BridgeLink[]; ropes?: BridgeLink[] }): void
+ /**
+ * Applies ONE canvas mutation — node, edge or board — to a project's serialized content, through
+ * the ONE reducer (`applyCanvasOp`, @shared/canvas-content) every client and the Server Edition
+ * canvas authority share — the path for a project React Flow does not hold (it only ever holds
+ * the active project's nodes). Returns false only if the project is unknown here (nothing
+ * applied, nothing created); an op that changes nothing is still `true` but writes NOTHING — no
+ * new `projects` array, so no subscriber re-runs — and callers that schedule a save compare the
+ * project object before and after to tell the two apart.
+ *
+ * Only the fields the op changed are written back, so an absent `bridges` / `ropes` / `kanban`
+ * stays absent (materializing `"bridges": []` or a lazy default board would dirty a file nobody
+ * edited). Side-effect free beyond the store: it marks nothing dirty and publishes nothing.
+ */
+ applyCanvasOp(projectId: string, mutation: CanvasMutation): boolean
/**
* Applies ONE peer canvas mutation to a project's serialized nodes — the path for a project
* that is loaded but NOT active (React Flow only holds the active project's nodes). Returns
@@ -153,6 +167,8 @@ interface ProjectsState {
* This must not be skipped for background projects: their serialized nodes are what the next
* whole-file `workspace.save` writes, so dropping a peer's `remove` would resurrect the node
* they deleted on the very next save — the data-loss shape canvas sync exists to fix.
+ *
+ * Delegates to `applyCanvasOp` (one reducer), so it takes any family.
*/
applyNodeMutation(projectId: string, mutation: CanvasMutation): boolean
/**
@@ -161,7 +177,7 @@ interface ProjectsState {
* peer's edge mutation for a project we are not looking at has the identical failure mode: our
* next save writes a project without their edge, deleting it for everyone.
*
- * Returns false if the project is unknown here (nothing applied).
+ * Returns false if the project is unknown here (nothing applied). Delegates to `applyCanvasOp`.
*/
applyEdgeMutation(projectId: string, mutation: CanvasMutation): boolean
/** Renames a node within a project (source of truth for inactive projects). */
@@ -591,37 +607,32 @@ export const useProjects = create<ProjectsState>((set, get) => ({
}))
},
- applyNodeMutation(projectId, mutation) {
- if (!get().projects.some((p) => p.id === projectId)) return false
+ applyCanvasOp(projectId, mutation) {
+ const p = get().projects.find((x) => x.id === projectId)
+ if (!p) return false
+ // Compare against the object handed to the reducer: `contentOf` builds a new one per call (and
+ // a fresh `[]` for an absent list), so only this reference can say "nothing changed".
+ const before = contentOf(p)
+ const after = applyCanvasOpTo(before, mutation, projectId)
+ if (after === before) return true
+ // Write back ONLY what the op changed — an absent list or board must stay absent.
+ const patch: Partial<Project> = {}
+ if (after.nodes !== before.nodes) patch.nodes = after.nodes
+ if (after.bridges !== before.bridges) patch.bridges = after.bridges
+ if (after.ropes !== before.ropes) patch.ropes = after.ropes
+ if (after.kanban !== before.kanban) patch.kanban = after.kanban
set((s) => ({
- projects: mapProjectNodes(s.projects, projectId, (nodes) =>
- applyCanvasMutation(nodes, mutation)
- )
+ projects: s.projects.map((x) => (x.id === projectId ? { ...x, ...patch } : x))
}))
return true
},
+ applyNodeMutation(projectId, mutation) {
+ return get().applyCanvasOp(projectId, mutation)
+ },
+
applyEdgeMutation(projectId, mutation) {
- if (!get().projects.some((p) => p.id === projectId)) return false
- set((s) => ({
- projects: s.projects.map((p) => {
- if (p.id !== projectId) return p
- // One id is one edge across BOTH lists (applyEdgeMutationToScene), which returns the SAME
- // array for a list the mutation does not change — so the untouched kind keeps its identity,
- // and a project whose stored list was `undefined` stays `undefined` rather than being
- // materialized as an empty array on every peer edge (which would dirty the file with
- // `"bridges": []` on projects that have never had one). The base is built ONCE for that
- // compare: two separate `?? []` literals are never the same array, which is how the branch
- // this was ported from wrote `[]` anyway.
- const base = { bridges: p.bridges ?? [], ropes: p.ropes ?? [] }
- const next = applyEdgeMutationToScene(base, mutation)
- const nextBridges = next.bridges === base.bridges ? p.bridges : next.bridges
- const nextRopes = next.ropes === base.ropes ? p.ropes : next.ropes
- if (nextBridges === p.bridges && nextRopes === p.ropes) return p
- return { ...p, bridges: nextBridges, ropes: nextRopes }
- })
- }))
- return true
+ return get().applyCanvasOp(projectId, mutation)
},
renameNode(projectId, nodeId, title) {
diff --git a/src/shared/canvas-content.test.ts b/src/shared/canvas-content.test.ts
new file mode 100644
index 000000000..3411b28f4
--- /dev/null
+++ b/src/shared/canvas-content.test.ts
@@ -0,0 +1,255 @@
+import { describe, it, expect } from 'vitest'
+import { applyCanvasOp, contentOf, diffContent, type CanvasContent } from './canvas-content'
+import { MUTATION_MAX_BYTES } from './canvas-mutations'
+import { defaultKanbanFor } from './kanban-default-board'
+import type { CanvasMutation, CanvasNodeState, ProjectKanban } from './types'
+
+const node = (id: string, x = 0) => ({ id, kind: 'terminal', position: { x, y: 0 } }) as any
+const empty: CanvasContent = { nodes: [], bridges: [], ropes: [] }
+
+describe('applyCanvasOp', () => {
+ it('routes each family to its applier', () => {
+ let c = applyCanvasOp(empty, { op: 'upsert', node: node('n1') }, 'p')
+ c = applyCanvasOp(c, { op: 'edge-upsert', kind: 'bridge', edge: { id: 'b', source: 'n1', target: 'n1' } }, 'p')
+ c = applyCanvasOp(c, { op: 'kb-card', assignment: { nodeId: 'n1', columnId: 'c' } }, 'p')
+ expect(c.nodes.map((n) => n.id)).toEqual(['n1'])
+ expect(c.bridges.map((b) => b.id)).toEqual(['b'])
+ expect(c.kanban?.assignments).toEqual([{ nodeId: 'n1', columnId: 'c' }])
+ })
+ it('strips exec fields from an inbound node (a peer may not set our shell)', () => {
+ const c = applyCanvasOp(empty, { op: 'upsert', node: { ...node('n1'), shell: '/bin/evil' } }, 'p')
+ expect((c.nodes[0] as { shell?: string }).shell).toBeUndefined()
+ })
+ it('refuses an edge op with a bad endpoint id', () => {
+ const c = applyCanvasOp(empty, { op: 'edge-upsert', kind: 'rope', edge: { id: 'r', source: '', target: 'x' } } as any, 'p')
+ expect(c.ropes).toEqual([])
+ })
+ it('an unchanged content is the same object (no spurious flush)', () => {
+ const c = applyCanvasOp(empty, { op: 'remove', id: 'ghost' }, 'p')
+ expect(c).toBe(empty)
+ })
+})
+
+/**
+ * "Nothing changed" is the SAME object, for every family — the authority skips a flush on it and
+ * the projects store skips a setState (and the save it would schedule). A duplicate op is the
+ * common case, not a corner: every Server Edition tab re-casts what it received, the authority's
+ * own published diff echoes back to it, and a reconnect replays.
+ */
+describe('applyCanvasOp — identity when nothing changed', () => {
+ const held: CanvasContent = {
+ nodes: [
+ { id: 'a', kind: 'terminal', position: { x: 1, y: 2 }, size: { width: 10, height: 20 }, title: 'A', tags: ['x'] } as CanvasNodeState,
+ node('b')
+ ],
+ bridges: [{ id: 'e1', source: 'a', target: 'b' }],
+ ropes: []
+ }
+
+ it('a duplicate node upsert (a fresh object of the same value) is a no-op', () => {
+ const copy = JSON.parse(JSON.stringify(held.nodes[0])) as CanvasNodeState
+ expect(applyCanvasOp(held, { op: 'upsert', node: copy }, 'p')).toBe(held)
+ })
+
+ it('a key order difference is still the same value', () => {
+ const n = held.nodes[0]
+ const reordered = { tags: n.tags, title: n.title, size: { height: 20, width: 10 }, position: { y: 2, x: 1 }, kind: n.kind, id: n.id } as CanvasNodeState
+ expect(applyCanvasOp(held, { op: 'upsert', node: reordered }, 'p')).toBe(held)
+ })
+
+ it('an upsert that changes one field is a change, and only that node is replaced', () => {
+ const out = applyCanvasOp(held, { op: 'upsert', node: { ...held.nodes[0], tags: ['y'] } }, 'p')
+ expect(out).not.toBe(held)
+ expect(out.nodes[0].tags).toEqual(['y'])
+ expect(out.nodes[1]).toBe(held.nodes[1])
+ expect(out.bridges).toBe(held.bridges)
+ })
+
+ it('a peer upsert without OUR exec field is a no-op when nothing else differs (we keep our shell)', () => {
+ const mine: CanvasContent = { ...held, nodes: [{ ...node('s'), shell: '/bin/zsh' }] }
+ const out = applyCanvasOp(mine, { op: 'upsert', node: node('s') }, 'p')
+ expect(out).toBe(mine)
+ const moved = applyCanvasOp(mine, { op: 'upsert', node: node('s', 50) }, 'p')
+ expect(moved.nodes[0]).toMatchObject({ shell: '/bin/zsh', position: { x: 50, y: 0 } })
+ })
+
+ // `carryLocalNodeExec` re-attaches our `ssh.extraArgs` together with `execTrusted: undefined`
+ // when we never had one — a key JSON drops. Counting it as a difference would make every peer
+ // drag of an ssh terminal with jump-host args a "change" even when nothing moved.
+ it('a duplicate upsert of our ssh node (extraArgs carried back) is a no-op', () => {
+ const ssh = { host: 'h', user: 'u', extraArgs: '-J jump' }
+ const mine: CanvasContent = { ...held, nodes: [{ ...node('s'), ssh }] }
+ expect(applyCanvasOp(mine, { op: 'upsert', node: { ...node('s'), ssh: { host: 'h', user: 'u' } } }, 'p')).toBe(mine)
+ })
+
+ it('a duplicate edge upsert, and a remove of an edge we lack, are no-ops', () => {
+ expect(applyCanvasOp(held, { op: 'edge-upsert', kind: 'bridge', edge: { id: 'e1', source: 'a', target: 'b' } }, 'p')).toBe(held)
+ expect(applyCanvasOp(held, { op: 'edge-remove', kind: 'rope', id: 'nope' }, 'p')).toBe(held)
+ })
+
+ it('a board op that changes nothing on a held board is a no-op', () => {
+ const board: ProjectKanban = { columns: [{ id: 'k1', title: 'T', color: '#000' }], assignments: [{ nodeId: 'a', columnId: 'k1' }] }
+ const c: CanvasContent = { ...held, kanban: board }
+ expect(applyCanvasOp(c, { op: 'kb-card', assignment: { nodeId: 'a', columnId: 'k1' } }, 'p')).toBe(c)
+ expect(applyCanvasOp(c, { op: 'kb-card-remove', nodeId: 'zz' }, 'p')).toBe(c)
+ expect(applyCanvasOp(c, { op: 'kb-column', column: { id: 'k1', title: 'T', color: '#000' } }, 'p')).toBe(c)
+ // No `meta` / `labels` / `views` list at all reads exactly like an empty one — writing `[]`
+ // into the file for a remove of something that was never there is not a change.
+ expect(applyCanvasOp(c, { op: 'kb-meta-remove', nodeId: 'a' }, 'p')).toBe(c)
+ expect(applyCanvasOp(c, { op: 'kb-label-remove', id: 'l1' }, 'p')).toBe(c)
+ expect(applyCanvasOp(c, { op: 'kb-view-remove', id: 'v1' }, 'p')).toBe(c)
+ })
+
+ it('a board op that leaves the LAZY default as it was keeps the board absent', () => {
+ const def = defaultKanbanFor('p')
+ const out1 = applyCanvasOp(held, { op: 'kb-card-remove', nodeId: 'a' }, 'p')
+ expect(out1).toBe(held)
+ const out2 = applyCanvasOp(held, { op: 'kb-column-order', ids: def.columns.map((c) => c.id) }, 'p')
+ expect(out2).toBe(held)
+ expect(applyCanvasOp(held, { op: 'kb-column', column: def.columns[0] }, 'p')).toBe(held)
+ })
+
+ it('a board op that DOES change the lazy default materializes the board', () => {
+ const out = applyCanvasOp(held, { op: 'kb-card', assignment: { nodeId: 'a', columnId: defaultKanbanFor('p').columns[0].id } }, 'p')
+ expect(out).not.toBe(held)
+ expect(out.kanban?.columns).toEqual(defaultKanbanFor('p').columns)
+ expect(out.nodes).toBe(held.nodes)
+ })
+})
+
+describe('applyCanvasOp — refusals', () => {
+ const c: CanvasContent = { nodes: [node('a')], bridges: [], ropes: [] }
+ const refused: unknown[] = [
+ null,
+ { op: 'nope' },
+ { op: 'upsert', node: { id: '', position: { x: 0, y: 0 } } },
+ { op: 'upsert', node: { id: 'b', position: { x: Number.NaN, y: 0 } } },
+ { op: 'remove', id: '' },
+ { op: 'edge-upsert', kind: 'bridges', edge: { id: 'x', source: 'a', target: 'a' } },
+ { op: 'edge-remove', kind: 'rope', id: 'r'.repeat(200) },
+ { op: 'kb-card', assignment: { nodeId: '', columnId: 'k' } },
+ { op: 'kb-nope' }
+ ]
+ for (const m of refused) {
+ it(`leaves the content untouched for ${JSON.stringify(m)?.slice(0, 60)}`, () => {
+ expect(applyCanvasOp(c, m as CanvasMutation, 'p')).toBe(c)
+ })
+ }
+
+ it('a board op is applied in its sanitized form (an off-palette label colour is repaired)', () => {
+ const out = applyCanvasOp(c, { op: 'kb-label', label: { id: 'l1', name: 'Bug', color: 'hotpink' as never } }, 'p')
+ expect(out.kanban?.labels).toEqual([{ id: 'l1', name: 'Bug', color: 'default' }])
+ })
+
+ // The byte cap is the TRANSPORT's (the reflector refuses, the publisher never casts): an op that
+ // reached a reducer has already passed it or never travelled at all. The projects store also
+ // takes this client's OWN writes to a background project through here (cold open, a canvas-control
+ // sticky write), and silently dropping one of those would lose the user's edit.
+ it('does not re-apply the wire byte cap', () => {
+ const big = { ...node('big'), kind: 'sticky', text: 'x'.repeat(MUTATION_MAX_BYTES) }
+ const out = applyCanvasOp(c, { op: 'upsert', node: big }, 'p')
+ expect(out.nodes.map((n) => n.id)).toEqual(['a', 'big'])
+ })
+
+ it('a node remove leaves its card on the board (placements are pruned lazily, spec §2)', () => {
+ const board: ProjectKanban = { columns: [{ id: 'k1', title: 'T', color: '#000' }], assignments: [{ nodeId: 'a', columnId: 'k1' }] }
+ const out = applyCanvasOp({ ...c, kanban: board }, { op: 'remove', id: 'a' }, 'p')
+ expect(out.nodes).toEqual([])
+ expect(out.kanban).toBe(board)
+ })
+
+ it('never mutates its input', () => {
+ const frozen: CanvasContent = Object.freeze({
+ nodes: Object.freeze([Object.freeze(node('a'))]) as CanvasNodeState[],
+ bridges: Object.freeze([]) as never,
+ ropes: Object.freeze([]) as never
+ })
+ expect(() => {
+ applyCanvasOp(frozen, { op: 'upsert', node: node('a', 9) }, 'p')
+ applyCanvasOp(frozen, { op: 'edge-upsert', kind: 'rope', edge: { id: 'r', source: 'a', target: 'a' } }, 'p')
+ applyCanvasOp(frozen, { op: 'kb-card', assignment: { nodeId: 'a', columnId: 'k' } }, 'p')
+ }).not.toThrow()
+ })
+})
+
+describe('contentOf', () => {
+ it('reads absent edge lists as empty and carries the board only when present', () => {
+ const nodes = [node('a')]
+ expect(contentOf({ nodes })).toEqual({ nodes, bridges: [], ropes: [] })
+ expect('kanban' in contentOf({ nodes })).toBe(false)
+ const kanban = defaultKanbanFor('p')
+ expect(contentOf({ nodes, kanban }).kanban).toBe(kanban)
+ })
+})
+
+describe('diffContent', () => {
+ it('replaying the diff reproduces next', () => {
+ const prev: CanvasContent = { nodes: [node('a'), node('b')], bridges: [], ropes: [] }
+ const next: CanvasContent = {
+ nodes: [node('a', 5), node('c')],
+ bridges: [{ id: 'x', source: 'a', target: 'c' }],
+ ropes: [],
+ kanban: { columns: [{ id: 'k1', title: 'T', color: '#000' }], assignments: [{ nodeId: 'a', columnId: 'k1' }] }
+ }
+ const replayed = diffContent(prev, next, 'p').reduce((c, m) => applyCanvasOp(c, m, 'p'), prev)
+ expect(replayed.nodes).toEqual(next.nodes)
+ expect(replayed.bridges).toEqual(next.bridges)
+ expect(replayed.kanban?.assignments).toEqual(next.kanban?.assignments)
+ })
+
+ it('an identical content diffs to nothing', () => {
+ const c: CanvasContent = { nodes: [node('a')], bridges: [{ id: 'x', source: 'a', target: 'a' }], ropes: [], kanban: defaultKanbanFor('p') }
+ expect(diffContent(c, { ...c, nodes: [node('a')] }, 'p')).toEqual([])
+ })
+
+ it('orders the batch: node adds, then edges and board, then node removes', () => {
+ const prev: CanvasContent = { nodes: [node('a'), node('gone')], bridges: [{ id: 'old', source: 'a', target: 'gone' }], ropes: [] }
+ const next: CanvasContent = {
+ nodes: [node('a'), node('new')],
+ bridges: [],
+ ropes: [{ id: 'r', source: 'a', target: 'new' }],
+ kanban: { ...defaultKanbanFor('p'), assignments: [{ nodeId: 'new', columnId: defaultKanbanFor('p').columns[0].id }] }
+ }
+ const ops = diffContent(prev, next, 'p').map((m) => m.op)
+ expect(ops).toEqual(['upsert', 'edge-upsert', 'edge-remove', 'kb-card', 'remove'])
+ })
+
+ // An outside edit (git pull, a hand edit) is not a lazy prune: a placement whose node is gone in
+ // the NEW file was removed by someone, so the removal is cast — unlike a client's publisher, which
+ // must not cast the prune of a card whose node op may simply not have arrived yet.
+ it('casts the removal of a card whose node is gone (every removal is real)', () => {
+ const k1 = { id: 'k1', title: 'T', color: '#000' }
+ const prev: CanvasContent = {
+ nodes: [node('a')],
+ bridges: [],
+ ropes: [],
+ kanban: { columns: [k1], assignments: [{ nodeId: 'a', columnId: 'k1' }], meta: [{ nodeId: 'a', priority: 'high' }] }
+ }
+ const next: CanvasContent = { nodes: [], bridges: [], ropes: [], kanban: { columns: [k1], assignments: [], meta: [] } }
+ const ops = diffContent(prev, next, 'p')
+ expect(ops).toContainEqual({ op: 'kb-card-remove', nodeId: 'a' })
+ expect(ops).toContainEqual({ op: 'kb-meta-remove', nodeId: 'a' })
+ const replayed = ops.reduce((c, m) => applyCanvasOp(c, m, 'p'), prev)
+ expect(replayed.kanban?.assignments).toEqual([])
+ expect(replayed.kanban?.meta).toEqual([])
+ })
+
+ // A file with no `kanban` block renders as the project's lazy default on every client — so an
+ // outside edit that REMOVED the block (a checkout from before the board was first edited) turns
+ // every replica's board back into that default, instead of casting nothing and leaving each
+ // client's old board in place over a file that no longer has one.
+ it('a removed board diffs to the lazy default', () => {
+ const prev: CanvasContent = {
+ nodes: [node('a')],
+ bridges: [],
+ ropes: [],
+ kanban: { columns: [{ id: 'k1', title: 'T', color: '#000' }], assignments: [{ nodeId: 'a', columnId: 'k1' }] }
+ }
+ const next: CanvasContent = { nodes: [node('a')], bridges: [], ropes: [] }
+ const replayed = diffContent(prev, next, 'p').reduce((c, m) => applyCanvasOp(c, m, 'p'), prev)
+ expect(replayed.kanban?.columns).toEqual(defaultKanbanFor('p').columns)
+ expect(replayed.kanban?.assignments).toEqual([])
+ // …and a project that never had a board still casts nothing for it.
+ expect(diffContent(next, { ...next }, 'p')).toEqual([])
+ })
+})
diff --git a/src/shared/canvas-content.ts b/src/shared/canvas-content.ts
new file mode 100644
index 000000000..88662c924
--- /dev/null
+++ b/src/shared/canvas-content.ts
@@ -0,0 +1,166 @@
+// The ONE reducer for canvas content (spec §2 "One reducer"). Every client applies a peer's
+// mutation through this, and so does the Server Edition canvas authority — two implementations of
+// "apply" is how an authority and its clients would silently diverge. Pure: no DOM, no fs.
+
+import {
+ applyCanvasMutation,
+ applyEdgeMutationToScene,
+ diffToMutations,
+ isEdgeMutation,
+ isWellFormedMutation
+} from './canvas-mutations'
+import { defaultKanbanFor } from './kanban-default-board'
+import { applyKanbanOp, diffKanbanOps, isKanbanOp, sanitizeKanbanOp } from './kanban-ops'
+import type { BridgeLink, CanvasMutation, CanvasNodeState, Project, ProjectKanban } from './types'
+
+/**
+ * The part of a project that `canvas:mut` addresses: the nodes, the two persisted edge lists and
+ * the board. Everything else on a `Project` (name, colour, viewport, the machine-local half) is
+ * outside the vocabulary and never touched by `applyCanvasOp`.
+ */
+export interface CanvasContent {
+ nodes: CanvasNodeState[]
+ bridges: BridgeLink[]
+ ropes: BridgeLink[]
+ /** Absent = the project's deterministic lazy default board (@shared/kanban-default-board). */
+ kanban?: ProjectKanban
+}
+
+/** A project's content, with absent edge lists read as empty. The board stays absent when absent:
+ * "no board yet" and "the default board" read the same everywhere, and materializing one here
+ * would put a `kanban` block into a file nobody edited a board in. */
+export function contentOf(p: Pick<Project, 'nodes' | 'bridges' | 'ropes' | 'kanban'>): CanvasContent {
+ return {
+ nodes: p.nodes ?? [],
+ bridges: p.bridges ?? [],
+ ropes: p.ropes ?? [],
+ ...(p.kanban ? { kanban: p.kanban } : {})
+ }
+}
+
+/**
+ * Apply ONE mutation to canvas content. Returns the SAME object when the op changes nothing — a
+ * duplicate cast, a remove of something already gone, a board op that leaves the board as it was —
+ * so a caller can skip a flush (the authority) or a setState and the save it would schedule (the
+ * projects store). Duplicates are the common case, not a corner: every Server Edition tab re-casts
+ * what it receives, the authority's own published diff echoes back to it, and a reconnect replays.
+ * "The same" is decided BY VALUE, because an upsert always arrives as a fresh object.
+ *
+ * Each family goes to its one applier:
+ * - node ops → `applyCanvasMutation`, which strips the exec-enabling fields a peer may not set and
+ * carries OUR values across the replace (@shared/node-exec);
+ * - edge ops → `applyEdgeMutationToScene` (one id is one edge, across both lists);
+ * - board ops → `sanitizeKanbanOp` then `applyKanbanOp`, against the lazy default when the project
+ * has no board yet.
+ *
+ * The guard is `isWellFormedMutation` — the reflector's shape verdict without its byte cap (see its
+ * header for why a reducer must not re-apply a transport limit). A malformed op is a no-op.
+ */
+export function applyCanvasOp(c: CanvasContent, m: CanvasMutation, projectId: string): CanvasContent {
+ if (!isWellFormedMutation(m)) return c
+ if (isKanbanOp(m)) {
+ const op = sanitizeKanbanOp(m)
+ if (!op) return c
+ const before = c.kanban ?? defaultKanbanFor(projectId)
+ const after = applyKanbanOp(c.kanban, op, projectId)
+ return sameBoard(before, after) ? c : { ...c, kanban: after }
+ }
+ if (isEdgeMutation(m)) {
+ const s = applyEdgeMutationToScene({ bridges: c.bridges, ropes: c.ropes }, m)
+ return s.bridges === c.bridges && s.ropes === c.ropes ? c : { ...c, bridges: s.bridges, ropes: s.ropes }
+ }
+ const nodes = applyCanvasMutation(c.nodes, m)
+ return sameNodes(c.nodes, nodes) ? c : { ...c, nodes }
+}
+
+/**
+ * The ops that turn `prev` into `next`, for an OUTSIDE edit (a git pull, a hand edit) that the
+ * authority must publish to every client as if someone had cast it. Every removal in it is real:
+ * the board part is diffed with EVERY node id of both sides as live, so a card whose node is gone
+ * from the new file has its removal cast — unlike a client's publisher, which must not cast the
+ * lazy prune of a card whose node op may simply not have arrived yet.
+ *
+ * A `next` with no board while `prev` had one diffs to the LAZY DEFAULT, not to nothing: a file with
+ * no `kanban` block renders as the default board on every client, so an outside edit that removed
+ * the block (a checkout from before the board was first edited) must turn every replica's board
+ * back into that default — casting nothing would leave each client's old board in place over a file
+ * that no longer has one.
+ *
+ * Batch order: node upserts, then edges (upserts before removes) and the board, then node removes —
+ * a receiver applies one op at a time, so an edge or a card must never name a node that has not
+ * arrived yet, and an edge-remove must land while its node still exists.
+ */
+export function diffContent(prev: CanvasContent, next: CanvasContent, projectId: string): CanvasMutation[] {
+ const scene = diffToMutations(
+ { nodes: prev.nodes, bridges: prev.bridges, ropes: prev.ropes },
+ { nodes: next.nodes, bridges: next.bridges, ropes: next.ropes }
+ )
+ const all = new Set([...prev.nodes, ...next.nodes].map((n) => n.id))
+ const nextBoard = next.kanban ?? (prev.kanban ? defaultKanbanFor(projectId) : undefined)
+ const board = diffKanbanOps(prev.kanban, nextBoard, projectId, all)
+ const nodeAdds = scene.filter((m) => m.op === 'upsert')
+ const nodeRemoves = scene.filter((m) => m.op === 'remove')
+ const edges = scene.filter((m) => m.op === 'edge-upsert' || m.op === 'edge-remove')
+ return [...nodeAdds, ...edges, ...board, ...nodeRemoves]
+}
+
+/** Same node list, by value? Unchanged entries are compared by reference (O(1)); only a replaced
+ * entry — at most one per op — is compared structurally. */
+function sameNodes(a: CanvasNodeState[], b: CanvasNodeState[]): boolean {
+ if (a === b) return true
+ if (a.length !== b.length) return false
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i] && !sameJson(a[i], b[i])) return false
+ return true
+}
+
+/**
+ * Same board, as every reader sees it? Keys the op left alone are the same reference (the applier
+ * spreads the board), so only the one or two lists it rebuilt are compared structurally. One rule
+ * beyond plain JSON equality: an ABSENT list and an EMPTY one are the same board — every reader
+ * treats a missing `meta` / `labels` / `views` as empty (they are "tolerated as absent" by type),
+ * and writing `"meta": []` into a file for the removal of something that was never there is not a
+ * change anyone made.
+ */
+function sameBoard(a: ProjectKanban, b: ProjectKanban): boolean {
+ if (a === b) return true
+ const ra = a as unknown as Record<string, unknown>
+ const rb = b as unknown as Record<string, unknown>
+ for (const k of new Set([...Object.keys(ra), ...Object.keys(rb)])) {
+ const va = ra[k]
+ const vb = rb[k]
+ if (Object.is(va, vb)) continue
+ if (emptyOrAbsent(va) && emptyOrAbsent(vb)) continue
+ if (!sameJson(va, vb)) return false
+ }
+ return true
+}
+
+const emptyOrAbsent = (v: unknown): boolean => v === undefined || (Array.isArray(v) && v.length === 0)
+
+const isPlainObject = (v: unknown): v is Record<string, unknown> => {
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return false
+ const proto = Object.getPrototypeOf(v)
+ return proto === Object.prototype || proto === null
+}
+
+/**
+ * Structural equality as JSON sees it: key order is irrelevant and a key whose value is `undefined`
+ * is absent (`JSON.stringify` drops it — `carryLocalNodeExec` writes `execTrusted: undefined`).
+ * Conservative in the only direction that matters: anything it cannot compare by value (a non-plain
+ * object) compares by reference, so it can report "changed" for equal content — costing one
+ * pointless write — but never "unchanged" for different content, which would strand an edit.
+ */
+function sameJson(a: unknown, b: unknown): boolean {
+ if (Object.is(a, b)) return true
+ if (Array.isArray(a)) {
+ if (!Array.isArray(b) || a.length !== b.length) return false
+ for (let i = 0; i < a.length; i++) if (!sameJson(a[i], b[i])) return false
+ return true
+ }
+ if (!isPlainObject(a) || !isPlainObject(b)) return false
+ const ka = Object.keys(a).filter((k) => a[k] !== undefined)
+ const kb = Object.keys(b).filter((k) => b[k] !== undefined)
+ if (ka.length !== kb.length) return false
+ for (const k of ka) if (!Object.prototype.hasOwnProperty.call(b, k) || !sameJson(a[k], b[k])) return false
+ return true
+}
diff --git a/src/shared/canvas-mutations.test.ts b/src/shared/canvas-mutations.test.ts
index d93ffbe0d..ae71341b8 100644
--- a/src/shared/canvas-mutations.test.ts
+++ b/src/shared/canvas-mutations.test.ts
@@ -6,6 +6,7 @@ import {
createMutationGuard,
diffToMutations,
isCanvasMutation,
+ isWellFormedMutation,
MUTATION_MAX_BYTES,
sanitizeCanvasMutation
} from './canvas-mutations'
@@ -270,6 +271,65 @@ describe('isCanvasMutation — edge ops', () => {
).toBe(false)
expect(isCanvasMutation({ op: 'edge-upsert', kind: 'bridge' })).toBe(false)
})
+
+ // One case per check, each breaking exactly ONE field of an otherwise valid op, so every check is
+ // pinned on its own (a test that breaks two fields at once still passes with either check gone).
+ describe('one check per field', () => {
+ const ok = { op: 'edge-upsert', kind: 'rope', edge: e('x', 'a', 'b') }
+ const okRemove = { op: 'edge-remove', kind: 'bridge', id: 'x' }
+ const long = 'z'.repeat(129)
+
+ it('the valid baselines pass', () => {
+ expect(isCanvasMutation(ok)).toBe(true)
+ expect(isCanvasMutation(okRemove)).toBe(true)
+ })
+ it('edge-upsert: kind must be bridge or rope', () => {
+ expect(isCanvasMutation({ ...ok, kind: 'link' })).toBe(false)
+ })
+ it('edge-remove: kind must be bridge or rope', () => {
+ expect(isCanvasMutation({ ...okRemove, kind: 'Rope' })).toBe(false)
+ })
+ it('edge-upsert: edge.id must be a ref id', () => {
+ expect(isCanvasMutation({ ...ok, edge: e('', 'a', 'b') })).toBe(false)
+ expect(isCanvasMutation({ ...ok, edge: e(long, 'a', 'b') })).toBe(false)
+ })
+ it('edge-upsert: edge.source must be a ref id', () => {
+ expect(isCanvasMutation({ ...ok, edge: { id: 'x', source: 7, target: 'b' } })).toBe(false)
+ })
+ it('edge-upsert: edge.target must be a ref id', () => {
+ expect(isCanvasMutation({ ...ok, edge: e('x', 'a', '') })).toBe(false)
+ expect(isCanvasMutation({ ...ok, edge: e('x', 'a', long) })).toBe(false)
+ })
+ it('edge-remove: id must be a ref id', () => {
+ expect(isCanvasMutation({ ...okRemove, id: '' })).toBe(false)
+ expect(isCanvasMutation({ ...okRemove, id: long })).toBe(false)
+ expect(isCanvasMutation({ ...okRemove, id: 3 })).toBe(false)
+ })
+ it('edge-upsert: edge must be an object', () => {
+ expect(isCanvasMutation({ ...ok, edge: 'x' })).toBe(false)
+ })
+ })
+})
+
+describe('isWellFormedMutation — the reducer guard', () => {
+ it('is isCanvasMutation without the wire byte cap', () => {
+ const big = { op: 'upsert', node: { ...n('big'), text: 'x'.repeat(MUTATION_MAX_BYTES) } }
+ expect(isCanvasMutation(big)).toBe(false)
+ expect(isWellFormedMutation(big)).toBe(true)
+ const cases: unknown[] = [
+ null,
+ { op: 'remove', id: 'a' },
+ { op: 'remove', id: '' },
+ { op: 'upsert', node: n('a') },
+ { op: 'upsert', node: { id: 'a', position: { x: Number.NaN, y: 0 } } },
+ { op: 'edge-upsert', kind: 'rope', edge: e('x') },
+ { op: 'edge-upsert', kind: 'ropes', edge: e('x') },
+ { op: 'edge-remove', kind: 'bridge', id: 'x' },
+ { op: 'kb-card', assignment: { nodeId: 'a', columnId: 'k' } },
+ { op: 'kb-card', assignment: { nodeId: '', columnId: 'k' } }
+ ]
+ for (const c of cases) expect(isWellFormedMutation(c), JSON.stringify(c)).toBe(isCanvasMutation(c))
+ })
})
describe('diffToMutations — scenes', () => {
diff --git a/src/shared/canvas-mutations.ts b/src/shared/canvas-mutations.ts
index 6e710d071..2e4c70640 100644
--- a/src/shared/canvas-mutations.ts
+++ b/src/shared/canvas-mutations.ts
@@ -74,9 +74,31 @@ export function isRefId(value: unknown): value is string {
* repaired by `sanitizeCanvasMutation` before anyone applies or reflects it.
*/
export function isCanvasMutation(value: unknown): value is CanvasMutation {
+ return checkMutation(value, true)
+}
+
+/**
+ * `isCanvasMutation` WITHOUT the byte cap — the guard of the one reducer (`applyCanvasOp`,
+ * @shared/canvas-content). Same shape verdict, field for field (one implementation, so the two
+ * cannot drift); only `MUTATION_MAX_BYTES` is skipped.
+ *
+ * The cap is a TRANSPORT rule: it bounds what one cast pushes into every peer's socket, and both
+ * ends of the wire already apply it (the reflector refuses, the publisher never casts). An op that
+ * reaches a reducer either passed it or never travelled at all — the projects store takes this
+ * client's OWN writes to a background project through the same reducer (cold open, a canvas-control
+ * sticky write, a pending-launch patch), and silently dropping one of those because its node is big
+ * would lose the user's edit while the caller reports success. The shape half is what keeps a
+ * malformed op from wedging a canvas, and that half stays.
+ */
+export function isWellFormedMutation(value: unknown): value is CanvasMutation {
+ return checkMutation(value, false)
+}
+
+function checkMutation(value: unknown, sized: boolean): value is CanvasMutation {
if (!value || typeof value !== 'object') return false
+ const fits = (x: unknown): boolean => !sized || withinSizeLimit(x)
const m = value as { op?: unknown; id?: unknown; node?: unknown; kind?: unknown; edge?: unknown }
- if (isKanbanOp(m)) return sanitizeKanbanOp(value) !== null && withinSizeLimit(value)
+ if (isKanbanOp(m)) return sanitizeKanbanOp(value) !== null && fits(value)
if (m.op === 'remove') return isRefId(m.id)
if (m.op === 'edge-remove') return isEdgeKind(m.kind) && isRefId(m.id)
if (m.op === 'edge-upsert') {
@@ -86,7 +108,7 @@ export function isCanvasMutation(value: unknown): value is CanvasMutation {
// All three ids are ADDRESSES — an edge with a truncated endpoint would attach to the wrong
// node on every peer — so they are rejected rather than capped, exactly like a node id.
if (!isRefId(edge.id) || !isRefId(edge.source) || !isRefId(edge.target)) return false
- return withinSizeLimit(m)
+ return fits(m)
}
if (m.op !== 'upsert') return false
const node = m.node as { id?: unknown; position?: { x?: unknown; y?: unknown } } | undefined
@@ -95,7 +117,7 @@ export function isCanvasMutation(value: unknown): value is CanvasMutation {
const pos = node.position
if (!pos || typeof pos !== 'object') return false
if (!Number.isFinite(pos.x) || !Number.isFinite(pos.y)) return false
- return withinSizeLimit(m)
+ return fits(m)
}
/**