Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
refactor(canvas): one shared canvas mutation vocabulary (apply + diff)
enesd5835e03138e
diff --git a/src/main/remote/canvas-sync.ts b/src/main/remote/canvas-sync.tsindex 6c19d0cb8..49db445eb 100644--- a/src/main/remote/canvas-sync.ts+++ b/src/main/remote/canvas-sync.ts@@ -3,30 +3,16 @@// host broadcast and the client mirror in later tasks.import type { CanvasMutation, CanvasNodeState, CanvasState } from '@shared/types'+import { applyCanvasMutation } from '@shared/canvas-mutations'export type { CanvasMutation, CanvasState } from '@shared/types'-/**- * Apply a single mutation to a node list, returning a NEW array (the input is never- * mutated). `upsert` replaces the node with the matching id, or appends it if absent;- * `remove` filters out the node with the given id.- */-export function applyMutation(- nodes: CanvasNodeState[],- m: CanvasMutation-): CanvasNodeState[] {- if (m.op === 'remove') {- return nodes.filter((node) => node.id !== m.id)- }- // upsert- const idx = nodes.findIndex((node) => node.id === m.node.id)- if (idx === -1) {- return [...nodes, m.node]- }- const next = nodes.slice()- next[idx] = m.node- return next-}+// The mutation vocabulary itself lives in `@shared/canvas-mutations` (one implementation for the+// relay host, the renderer and src/core); only the host-authority policy below is local.+export { diffToMutations } from '@shared/canvas-mutations'++/** Back-compat alias: the relay host/client call this `applyMutation`. */+export const applyMutation = applyCanvasMutation/*** R7 — sanitize a CLIENT-supplied mutation before the host applies it.@@ -71,46 +57,3 @@ export function sanitizeClientMutation(}return { op: 'upsert', node }}--/** Stable JSON stringify (keys sorted) so deep-equality is order-independent. */-function stableStringify(value: unknown): string {- return JSON.stringify(value, (_key, val) => {- if (val && typeof val === 'object' && !Array.isArray(val)) {- const sorted: Record<string, unknown> = {}- for (const k of Object.keys(val as Record<string, unknown>).sort()) {- sorted[k] = (val as Record<string, unknown>)[k]- }- return sorted- }- return val- })-}--/**- * Diff two node snapshots into the minimal mutation list (deterministic): an `upsert`- * for every node that was added or changed (deep-equal via stable stringify), and a- * `remove` for every node that was dropped. Never throws on normal input.- */-export function diffToMutations(- prev: CanvasNodeState[],- next: CanvasNodeState[]-): CanvasMutation[] {- const mutations: CanvasMutation[] = []- const prevById = new Map(prev.map((node) => [node.id, node]))- const nextIds = new Set(next.map((node) => node.id))-- // upserts: added or changed nodes (in next-array order for determinism).- for (const node of next) {- const before = prevById.get(node.id)- if (!before || stableStringify(before) !== stableStringify(node)) {- mutations.push({ op: 'upsert', node })- }- }- // removes: nodes present in prev but gone from next (in prev-array order).- for (const node of prev) {- if (!nextIds.has(node.id)) {- mutations.push({ op: 'remove', id: node.id })- }- }- return mutations-}diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 2b30cde23..0b5d2a87b 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -1,10 +1,15 @@import type { Node } from '@xyflow/react'-import type { CanvasMutation, CanvasNodeState, ClaudeAccount, NodeKind, Project } from '@shared/types'+import type { CanvasNodeState, ClaudeAccount, NodeKind, Project } from '@shared/types'import type { AgentId } from '@shared/agents/config'import { agentConfig } from '@shared/agents/config'import { sshHostKey } from '@shared/ssh'import { useSettings } from './settings'+// Re-exported so Canvas (and anything else in the renderer) keeps importing it from here, while the+// single implementation lives in src/shared and is shared with the relay host + the canvas-sync+// reflector.+export { applyCanvasMutation } from '@shared/canvas-mutations'+/** Preset color palette — macOS system colors (dark mode). */export const NODE_COLORS = ['#0a84ff', // systemBlue@@ -880,24 +885,6 @@ export function reorderNodeBefore(}/** Converts persisted node states into live React Flow nodes (parents first). */-/**- * Apply a single canvas mutation to a list of node states (renderer mirror of- * `main/remote/canvas-sync`'s `applyMutation`, kept here to keep the renderer off the main-process- * boundary). `upsert` replaces-or-appends by id; `remove` filters by id. Returns a NEW array- * (the input is never mutated).- */-export function applyCanvasMutation(- states: CanvasNodeState[],- m: CanvasMutation-): CanvasNodeState[] {- if (m.op === 'remove') return states.filter((n) => n.id !== m.id)- const idx = states.findIndex((n) => n.id === m.node.id)- if (idx === -1) return [...states, m.node]- const next = states.slice()- next[idx] = m.node- return next-}-export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {// React Flow requires a parent node to appear before its children in the array.const ordered = [...states].sort((a, b) => {diff --git a/src/shared/canvas-mutations.test.ts b/src/shared/canvas-mutations.test.tsnew file mode 100644index 000000000..17dc5d4ba--- /dev/null+++ b/src/shared/canvas-mutations.test.ts@@ -0,0 +1,61 @@+import { describe, it, expect } from 'vitest'+import { applyCanvasMutation, diffToMutations } from './canvas-mutations'+import type { CanvasNodeState } from './types'++const n = (id: string, x = 0, title = 't'): CanvasNodeState =>+ ({+ id,+ kind: 'terminal',+ title,+ color: '#fff',+ position: { x, y: 0 },+ size: { width: 100, height: 100 }+ }) as CanvasNodeState++describe('applyCanvasMutation', () => {+ it('upserts by id (append when absent, replace when present) without mutating the input', () => {+ const a = [n('1')]+ expect(applyCanvasMutation(a, { op: 'upsert', node: n('2') }).map((x) => x.id)).toEqual([+ '1',+ '2'+ ])+ expect(applyCanvasMutation(a, { op: 'upsert', node: n('1', 9) })[0].position.x).toBe(9)+ expect(a[0].position.x).toBe(0)+ })++ it('removes by id', () => {+ expect(+ applyCanvasMutation([n('1'), n('2')], { op: 'remove', id: '1' }).map((x) => x.id)+ ).toEqual(['2'])+ })+})++describe('diffToMutations', () => {+ it('emits an upsert for added and changed nodes and a remove for dropped ones', () => {+ expect(diffToMutations([n('1')], [n('1', 5)])).toEqual([{ op: 'upsert', node: n('1', 5) }])+ expect(diffToMutations([n('1')], [n('1'), n('2')])).toEqual([{ op: 'upsert', node: n('2') }])+ expect(diffToMutations([n('1'), n('2')], [n('1')])).toEqual([{ op: 'remove', id: '2' }])+ })++ it('emits nothing when the snapshots are deep-equal regardless of key order', () => {+ const a = {+ id: '1',+ kind: 'terminal',+ position: { x: 1, y: 2 },+ size: { width: 3, height: 4 }+ } as CanvasNodeState+ const b = {+ size: { height: 4, width: 3 },+ position: { y: 2, x: 1 },+ kind: 'terminal',+ id: '1'+ } as CanvasNodeState+ expect(diffToMutations([a], [b])).toEqual([])+ })++ it('detects a title/color/collapsed change, not just geometry', () => {+ expect(diffToMutations([n('1')], [n('1', 0, 'renamed')])).toEqual([+ { op: 'upsert', node: n('1', 0, 'renamed') }+ ])+ })+})diff --git a/src/shared/canvas-mutations.ts b/src/shared/canvas-mutations.tsnew file mode 100644index 000000000..d37531ecb--- /dev/null+++ b/src/shared/canvas-mutations.ts@@ -0,0 +1,63 @@+// The canvas mutation vocabulary — ONE implementation, imported by every surface:+// the relay host (src/main/remote), the renderer (Canvas), and the canvas-sync reflector+// (src/core). Pure: no electron, no sockets, no disk.++import type { CanvasMutation, CanvasNodeState } from './types'++/**+ * Apply a single mutation to a node list, returning a NEW array (the input is never mutated).+ * `upsert` replaces the node with the matching id, or appends it if absent; `remove` filters+ * out the node with the given id.+ */+export function applyCanvasMutation(+ states: CanvasNodeState[],+ m: CanvasMutation+): CanvasNodeState[] {+ if (m.op === 'remove') return states.filter((n) => n.id !== m.id)+ const idx = states.findIndex((n) => n.id === m.node.id)+ if (idx === -1) return [...states, m.node]+ const next = states.slice()+ next[idx] = m.node+ return next+}++/** Stable JSON stringify (keys sorted) so deep-equality is order-independent. */+function stableStringify(value: unknown): string {+ return JSON.stringify(value, (_key, val) => {+ if (val && typeof val === 'object' && !Array.isArray(val)) {+ const sorted: Record<string, unknown> = {}+ for (const k of Object.keys(val as Record<string, unknown>).sort()) {+ sorted[k] = (val as Record<string, unknown>)[k]+ }+ return sorted+ }+ return val+ })+}++/**+ * Diff two node snapshots into the minimal mutation list (deterministic): an `upsert` for every+ * node that was added or changed (deep-equal via stable stringify), and a `remove` for every node+ * that was dropped. Never throws on normal input.+ */+export function diffToMutations(+ prev: CanvasNodeState[],+ next: CanvasNodeState[]+): CanvasMutation[] {+ const mutations: CanvasMutation[] = []+ const prevById = new Map(prev.map((node) => [node.id, node]))+ const nextIds = new Set(next.map((node) => node.id))++ // upserts: added or changed nodes (in next-array order for determinism).+ for (const node of next) {+ const before = prevById.get(node.id)+ if (!before || stableStringify(before) !== stableStringify(node)) {+ mutations.push({ op: 'upsert', node })+ }+ }+ // removes: nodes present in prev but gone from next (in prev-array order).+ for (const node of prev) {+ if (!nextIds.has(node.id)) mutations.push({ op: 'remove', id: node.id })+ }+ return mutations+}