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
feat(canvas): publish local node mutations to peers and apply theirs (loop-guarded)
enes5c7410f73dbe
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 16eb96132..b8f7fad9a 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -125,7 +125,13 @@ import { requireProOr } from '../state/upgradeGate'import { useEntitlement } from '../state/entitlement'import type { SshServer } from '@shared/ssh'import { sshHostKey } from '@shared/ssh'-import type { Project, SshProjectStatus, TranscriptHit } from '@shared/types'+import type { CanvasNodeState, Project, SshProjectStatus, TranscriptHit } from '@shared/types'+import {+ createCanvasPublisher,+ isEphemeralNodeId,+ publishableStates,+ type CanvasPublisher+} from '@shared/canvas-publish'import {applyCanvasMutation,claudeLaunchCommand,@@ -372,6 +378,8 @@ export function Canvas() {const futureRef = useRef<CanvasNode[][]>([])const committedRef = useRef<CanvasNode[]>([])const draggingRef = useRef(false)+ // Canvas sync (emitting side) — see the publish effect below.+ const publisherRef = useRef<CanvasPublisher | null>(null)const [, bumpHist] = useState(0)const { setViewport, getViewport, fitView, zoomIn, zoomOut, screenToFlowPosition, setCenter, getZoom } =useReactFlow()@@ -816,6 +824,13 @@ export function Canvas() {if (!loadingRef.current) setDirty(true)}, [])+ // The node states that go on the wire: React Flow's managed nodes minus the ephemeral cards+ // (subagent / loop), which every client derives for itself from the agent:status stream.+ const publishableNow = useCallback((flow: CanvasNode[]): CanvasNodeState[] => {+ const ephIds = new Set(Object.keys(useAgentNodes.getState().byId))+ return publishableStates(flowToNodeStates(flow), ephIds)+ }, [])+// ---- persistence helpers ----const commitActiveToStore = useCallback(() => {const id = useProjects.getState().activeProjectId@@ -941,6 +956,83 @@ export function Canvas() {return window.nodeTerminal.remoteHost.onPeerPending((info) => setPendingPeer(info))}, [])+ // ---- canvas sync (team) ----+ // Emitting side: diff each settled node snapshot against the last one we published and cast the+ // mutations on `canvas:mut`. The core reflector (src/core/canvas-sync.ts) fans each one out to+ // every OTHER attached client, so all clients converge on the same node set — no teammate's+ // cursor hovering over stale geometry, and no client writing back a node someone else deleted on+ // its next whole-file workspace.save. Declared BEFORE the [nodes] publish effect so the publisher+ // exists by the time that one first runs on mount.+ useEffect(() => {+ const pub = createCanvasPublisher((m) => {+ const projectId = useProjects.getState().activeProjectId+ if (projectId) window.nodeTerminal.canvas.mutate(projectId, m)+ })+ publisherRef.current = pub+ return () => {+ pub.dispose()+ publisherRef.current = null+ }+ }, [])++ // Publish on every settled node change. While dragging we throttle to ~20 Hz (position frames);+ // the drag-stop handlers flush, and every other change (add / remove / color / title / collapse /+ // resize) is a full upsert, because this effect diffs the whole serialized snapshot — so edits+ // made through a direct setNodes(...) (which never reaches handleNodesChange) sync too.+ //+ // A programmatic project load (`loadingRef`) ADOPTS instead of publishing: the newly loaded+ // project's nodes are not an edit, and republishing them would cast the entire canvas as N+ // upserts to every peer on each tab switch. Same suppression precedent as `markDirty`.+ useEffect(() => {+ const pub = publisherRef.current+ if (!pub) return+ const states = publishableNow(nodes)+ if (loadingRef.current) {+ pub.adopt(states)+ return+ }+ pub.publish(states, { throttle: draggingRef.current })+ }, [nodes, publishableNow])++ // Receiving side: apply a PEER's mutation. Deliberately separate from the relay+ // `remoteHost.onApplyMutation` effect above — that one is host↔client, this one is peer↔peer.+ //+ // `adopt` is the loop guard: the publisher takes the resulting snapshot as its baseline BEFORE+ // the [nodes] effect above can diff it, so the applied mutation diffs to nothing and cannot be+ // re-published (A→B→C→A forever). The reflector's sender-id echo suppression is the other half.+ //+ // A mutation for a project that is loaded but NOT active is applied to that project's SERIALIZED+ // nodes in the projects store (React Flow only ever holds the active project's nodes). Dropping+ // it would leave that canvas stale AND let our next whole-file save resurrect a node the peer+ // deleted — the exact bug this stage exists to fix. Unknown project → nothing to apply.+ //+ // markDirty on both paths: a peer's mutation makes our in-memory canvas differ from disk, and a+ // direct setNodes() bypasses handleNodesChange (which is where local edits mark dirty). Two+ // clients saving the same converged state is harmless; never saving it is not.+ useEffect(() => {+ return window.nodeTerminal.canvas.onMutation((projectId, mutation) => {+ if (projectId !== useProjects.getState().activeProjectId) {+ if (useProjects.getState().applyNodeMutation(projectId, mutation)) markDirty()+ return+ }+ const next = applyCanvasMutation(flowToNodeStates(nodesRef.current), mutation)+ // Adopt the ROUND-TRIPPED snapshot (nodeStatesToFlow defaults a few fields), so the baseline+ // is byte-identical to what the [nodes] effect will serialize next.+ const flow = nodeStatesToFlow(next)+ // Keep the ref in step immediately: a burst (a peer's bulk delete) arrives within one tick,+ // before React re-renders, and each mutation must build on the previous one.+ nodesRef.current = flow+ publisherRef.current?.adopt(publishableNow(flow))+ // Undo stays LOCAL: a peer's edit is not something YOU did, so it must not become an entry in+ // your undo stack. Taking it as the committed baseline makes the debounced snapshot effect+ // see `nodes === committedRef.current` and record nothing. (Your own undo still publishes —+ // it goes through setNodes → the [nodes] effect → a normal diff.)+ committedRef.current = flow+ setNodes(flow)+ markDirty()+ })+ }, [setNodes, markDirty, publishableNow])+// Record an undo snapshot when the canvas settles (debounced; skips drag frames/loads).useEffect(() => {if (loadingRef.current) {@@ -1003,8 +1095,10 @@ export function Canvas() {(changes) => {// Ephemeral nodes (subagent / loop) live outside the managed state. Persist their drag// positions to the agent-nodes store; drop their other changes from the managed updater.- const eph = useAgentNodes.getState().byId- const isEph = (id: string) => id in eph || id.startsWith('loop-')+ // One definition of "ephemeral", shared with the publisher (which must never put these on+ // the wire — every client derives them from agent:status), so the two cannot drift.+ const ephIds = new Set(Object.keys(useAgentNodes.getState().byId))+ const isEph = (id: string) => isEphemeralNodeId(id, ephIds)const managed = changes.filter((c) => {if ('id' in c && isEph(c.id)) {if (c.type === 'position' && c.position) useAgentNodes.getState().setPosition(c.id, c.position)@@ -3951,11 +4045,14 @@ export function Canvas() {onNodeDragStart={() => (draggingRef.current = true)}onNodeDragStop={() => {draggingRef.current = false+ // Send the final position now instead of waiting for the throttle's trailing timer.+ publisherRef.current?.flush()markDirty()}}onSelectionDragStart={() => (draggingRef.current = true)}onSelectionDragStop={() => {draggingRef.current = false+ publisherRef.current?.flush()markDirty()}}onPaneClick={() => setEphSel({})}diff --git a/src/renderer/state/projects.mutation.test.ts b/src/renderer/state/projects.mutation.test.tsnew file mode 100644index 000000000..e24c5878c--- /dev/null+++ b/src/renderer/state/projects.mutation.test.ts@@ -0,0 +1,77 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { useProjects } from './projects'+import type { CanvasNodeState } from '@shared/types'++const node = (id: string, x = 0): CanvasNodeState => ({+ id,+ kind: 'terminal',+ position: { x, y: 0 },+ size: { width: 480, height: 320 },+ title: id,+ color: '#fff',+ group: ''+})++beforeEach(() => {+ useProjects.getState().hydrate({ version: 2, activeProjectId: '', projects: [] })+})++/** A peer's mutation for a project that is loaded but NOT the active canvas. React Flow only+ * holds the ACTIVE project's nodes, so the mutation has to land in the serialized copy the+ * projects store keeps — otherwise the next whole-file workspace.save writes back a stale+ * canvas (resurrecting a node the peer deleted), which is the exact bug Stage 3 exists to kill. */+describe('applyNodeMutation', () => {+ it('upserts a node into a background project and reports it applied', () => {+ const p = useProjects.getState().addProject('p', '/tmp/p')+ useProjects.getState().commitCanvas(p.id, [node('a')], { x: 0, y: 0, zoom: 1 })++ const applied = useProjects.getState().applyNodeMutation(p.id, {+ op: 'upsert',+ node: node('b', 100)+ })++ expect(applied).toBe(true)+ expect(useProjects.getState().getProject(p.id)?.nodes.map((n) => n.id)).toEqual(['a', 'b'])+ })++ it('replaces an existing node (a peer moved / renamed it)', () => {+ const p = useProjects.getState().addProject('p')+ useProjects.getState().commitCanvas(p.id, [node('a'), node('b')], { x: 0, y: 0, zoom: 1 })++ useProjects.getState().applyNodeMutation(p.id, { op: 'upsert', node: node('a', 999) })++ const nodes = useProjects.getState().getProject(p.id)?.nodes ?? []+ expect(nodes.map((n) => n.id)).toEqual(['a', 'b'])+ expect(nodes[0].position.x).toBe(999)+ })++ it('removes a node a peer deleted, so the next whole-file save cannot resurrect it', () => {+ const p = useProjects.getState().addProject('p')+ useProjects.getState().commitCanvas(p.id, [node('a'), node('b')], { x: 0, y: 0, zoom: 1 })++ useProjects.getState().applyNodeMutation(p.id, { op: 'remove', id: 'a' })++ expect(useProjects.getState().getProject(p.id)?.nodes.map((n) => n.id)).toEqual(['b'])+ expect(useProjects.getState().toWorkspace().projects[0].nodes.map((n) => n.id)).toEqual(['b'])+ })++ it('leaves other projects untouched', () => {+ const a = useProjects.getState().addProject('a')+ const b = useProjects.getState().addProject('b')+ useProjects.getState().commitCanvas(a.id, [node('n1')], { x: 0, y: 0, zoom: 1 })+ useProjects.getState().commitCanvas(b.id, [node('n2')], { x: 0, y: 0, zoom: 1 })++ useProjects.getState().applyNodeMutation(a.id, { op: 'remove', id: 'n1' })++ expect(useProjects.getState().getProject(b.id)?.nodes.map((n) => n.id)).toEqual(['n2'])+ })++ // A mutation for a project this client does not have (a peer opened a folder we never did):+ // nothing to apply, and we must NOT invent a project — report it so the caller can skip the+ // dirty flag rather than scheduling a pointless save.+ it('reports false for an unknown project and creates nothing', () => {+ const applied = useProjects.getState().applyNodeMutation('nope', { op: 'remove', id: 'x' })+ expect(applied).toBe(false)+ expect(useProjects.getState().projects).toHaveLength(0)+ })+})diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.tsindex 92742269a..d5d68104c 100644--- a/src/renderer/state/projects.ts+++ b/src/renderer/state/projects.ts@@ -1,6 +1,13 @@import { create } from 'zustand'-import type { BridgeLink, CanvasNodeState, Project, Viewport, Workspace } from '@shared/types'-import { createProject } from './workspace'+import type {+ BridgeLink,+ CanvasMutation,+ CanvasNodeState,+ Project,+ Viewport,+ Workspace+} from '@shared/types'+import { applyCanvasMutation, createProject } from './workspace'interface ProjectsState {projects: Project[]@@ -36,6 +43,16 @@ interface ProjectsState {bridges?: BridgeLink[],ropes?: BridgeLink[]): void+ /**+ * 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+ * false if the project is unknown here (nothing applied, nothing created).+ *+ * 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.+ */+ applyNodeMutation(projectId: string, mutation: CanvasMutation): boolean/** Renames a node within a project (source of truth for inactive projects). */renameNode(projectId: string, nodeId: string, title: string): void/** Recolors a node within a project. */@@ -183,6 +200,16 @@ export const useProjects = create<ProjectsState>((set, get) => ({}))},+ applyNodeMutation(projectId, mutation) {+ if (!get().projects.some((p) => p.id === projectId)) return false+ set((s) => ({+ projects: mapProjectNodes(s.projects, projectId, (nodes) =>+ applyCanvasMutation(nodes, mutation)+ )+ }))+ return true+ },+renameNode(projectId, nodeId, title) {set((s) => ({projects: mapProjectNodes(s.projects, projectId, (nodes) =>