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): mutation publisher (diff, 20Hz drag throttle, adopt loop guard, ephemeral filter)

enesf20a6e963714
diff --git a/src/shared/canvas-publish.test.ts b/src/shared/canvas-publish.test.ts
new file mode 100644
index 000000000..e849d2709
--- /dev/null
+++ b/src/shared/canvas-publish.test.ts
@@ -0,0 +1,143 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import {
+ createCanvasPublisher,
+ isEphemeralNodeId,
+ publishableStates,
+ PUBLISH_INTERVAL_MS
+} from './canvas-publish'
+import type { CanvasMutation, CanvasNodeState } from './types'
+
+const node = (id: string, x = 0): CanvasNodeState =>
+ ({
+ id,
+ kind: 'terminal',
+ title: 't',
+ color: '#fff',
+ position: { x, y: 0 },
+ size: { width: 10, height: 10 }
+ }) as CanvasNodeState
+
+function collect() {
+ const sent: CanvasMutation[] = []
+ return { sent, send: (m: CanvasMutation) => sent.push(m) }
+}
+
+beforeEach(() => vi.useFakeTimers())
+afterEach(() => vi.useRealTimers())
+
+describe('createCanvasPublisher', () => {
+ it('publishes the diff against the last snapshot (add, move, remove)', () => {
+ const c = collect()
+ const p = createCanvasPublisher(c.send)
+ p.publish([node('a')])
+ p.publish([node('a', 5)])
+ p.publish([])
+ expect(c.sent).toEqual([
+ { op: 'upsert', node: node('a') },
+ { op: 'upsert', node: node('a', 5) },
+ { op: 'remove', id: 'a' }
+ ])
+ })
+
+ it('publishes nothing when the snapshot is unchanged', () => {
+ const c = collect()
+ const p = createCanvasPublisher(c.send)
+ p.publish([node('a')])
+ p.publish([node('a')])
+ expect(c.sent).toHaveLength(1)
+ })
+
+ it('throttles drag frames to ~20 Hz: leading send, one trailing send per interval', () => {
+ const c = collect()
+ const p = createCanvasPublisher(c.send)
+ p.adopt([node('a')])
+ // 5 drag frames inside one interval → 1 leading send, the rest coalesced.
+ for (let x = 1; x <= 5; x++) p.publish([node('a', x)], { throttle: true })
+ expect(c.sent).toEqual([{ op: 'upsert', node: node('a', 1) }])
+ vi.advanceTimersByTime(PUBLISH_INTERVAL_MS)
+ // The trailing send carries the LATEST position, not the intermediate ones.
+ expect(c.sent).toEqual([
+ { op: 'upsert', node: node('a', 1) },
+ { op: 'upsert', node: node('a', 5) }
+ ])
+ })
+
+ it('an unthrottled publish (drag settle) sends immediately and cancels the pending frame', () => {
+ const c = collect()
+ const p = createCanvasPublisher(c.send)
+ p.adopt([node('a')])
+ p.publish([node('a', 1)], { throttle: true })
+ p.publish([node('a', 2)], { throttle: true })
+ p.publish([node('a', 9)]) // settle
+ vi.advanceTimersByTime(PUBLISH_INTERVAL_MS * 4)
+ expect(c.sent).toEqual([
+ { op: 'upsert', node: node('a', 1) },
+ { op: 'upsert', node: node('a', 9) }
+ ])
+ })
+
+ it('flush() sends a coalesced drag frame right away', () => {
+ const c = collect()
+ const p = createCanvasPublisher(c.send)
+ p.adopt([node('a')])
+ p.publish([node('a', 1)], { throttle: true })
+ p.publish([node('a', 2)], { throttle: true })
+ p.flush()
+ expect(c.sent).toEqual([
+ { op: 'upsert', node: node('a', 1) },
+ { op: 'upsert', node: node('a', 2) }
+ ])
+ })
+
+ // THE LOOP GUARD: a snapshot that arrived FROM a peer is adopted, never re-published.
+ it('adopt() takes a snapshot as baseline without sending — no infinite echo', () => {
+ const c = collect()
+ const p = createCanvasPublisher(c.send)
+ p.publish([node('a')])
+ c.sent.length = 0
+ // A peer's mutation lands: Canvas applies it and adopts the result.
+ const afterPeer = [node('a'), node('b', 3)]
+ p.adopt(afterPeer)
+ expect(c.sent).toEqual([])
+ // The React effect then fires with exactly that snapshot → the diff is empty → nothing is sent.
+ p.publish(afterPeer)
+ expect(c.sent).toEqual([])
+ // A genuinely local change afterwards still publishes (and only the delta).
+ p.publish([node('a'), node('b', 8)])
+ expect(c.sent).toEqual([{ op: 'upsert', node: node('b', 8) }])
+ })
+
+ it('dispose() drops a pending drag frame', () => {
+ const c = collect()
+ const p = createCanvasPublisher(c.send)
+ p.adopt([node('a')])
+ p.publish([node('a', 1)], { throttle: true })
+ p.publish([node('a', 2)], { throttle: true })
+ p.dispose()
+ vi.advanceTimersByTime(PUBLISH_INTERVAL_MS * 4)
+ expect(c.sent).toEqual([{ op: 'upsert', node: node('a', 1) }])
+ })
+})
+
+describe('ephemeral nodes are never published', () => {
+ it('isEphemeralNodeId matches subagent cards (by id set) and loop cards (by prefix)', () => {
+ const eph = new Set(['sub-123'])
+ expect(isEphemeralNodeId('sub-123', eph)).toBe(true)
+ expect(isEphemeralNodeId('loop-n1', eph)).toBe(true)
+ expect(isEphemeralNodeId('n1', eph)).toBe(false)
+ })
+
+ it('publishableStates strips them, so no mutation is ever emitted for one', () => {
+ const c = collect()
+ const p = createCanvasPublisher(c.send)
+ const eph = new Set(['sub-123'])
+ const states = [node('n1'), node('sub-123'), node('loop-n1')]
+ expect(publishableStates(states, eph).map((n) => n.id)).toEqual(['n1'])
+ p.publish(publishableStates(states, eph))
+ expect(c.sent).toEqual([{ op: 'upsert', node: node('n1') }])
+ // Moving an ephemeral card produces NO mutation at all.
+ const moved = [node('n1'), node('sub-123', 99), node('loop-n1', 99)]
+ p.publish(publishableStates(moved, eph))
+ expect(c.sent).toHaveLength(1)
+ })
+})
diff --git a/src/shared/canvas-publish.ts b/src/shared/canvas-publish.ts
new file mode 100644
index 000000000..bf87bb02e
--- /dev/null
+++ b/src/shared/canvas-publish.ts
@@ -0,0 +1,124 @@
+// Canvas sync — the emitting side.
+//
+// The renderer holds its nodes in React Flow (the single live source of truth). This publisher turns
+// successive serialized snapshots of that list into the minimal CanvasMutation stream for the peers:
+//
+// publish(states) → diff vs the last published snapshot, send each mutation
+// publish(states, {throttle:true}) → a drag frame: at most one send per PUBLISH_INTERVAL_MS
+// adopt(states) → LOOP GUARD: take the snapshot as baseline, send NOTHING
+//
+// Snapshots, NOT React Flow change-lists: a rename, a color pick, a collapse and an add all reach the
+// nodes array through direct setNodes(...) calls that never pass through onNodesChange, so a
+// change-list-driven publisher would silently fail to sync half the edits. Diffing the serialized
+// snapshot catches every one of them, whatever path produced it.
+//
+// `adopt` is what stops an infinite echo: when a mutation arrives FROM a peer, Canvas applies it and
+// adopts the result, so the React effect that fires for the resulting `nodes` change diffs to nothing.
+// (Same shape as the existing `loadingRef` suppression that keeps a programmatic project load from
+// marking the project dirty.) The reflector already suppresses a client's OWN echo by ClientId; this
+// guard is the other half — without it, A's mutation applied on B would be re-published by B to C
+// (and back at A) forever.
+//
+// Pure + DOM-free (vitest runs in the node environment): only setTimeout, no React, no window.
+
+import { diffToMutations } from './canvas-mutations'
+import type { CanvasMutation, CanvasNodeState } from './types'
+
+/** ~20 Hz while dragging — the same budget the presence cursor stream uses. */
+export const PUBLISH_INTERVAL_MS = 50
+
+export interface CanvasPublisher {
+ /** Diff `next` against the last published snapshot and send the mutations.
+ * `throttle` (drag frames) coalesces to at most one send per PUBLISH_INTERVAL_MS. */
+ publish(next: CanvasNodeState[], opts?: { throttle?: boolean }): void
+ /** Take `next` as the new baseline WITHOUT sending — the loop guard (a peer's mutation, or a
+ * programmatic project load). The next diff against it is empty. */
+ adopt(next: CanvasNodeState[]): void
+ /** Send any coalesced drag frame immediately (drag settle / unmount). */
+ flush(): void
+ dispose(): void
+}
+
+export function createCanvasPublisher(
+ send: (m: CanvasMutation) => void,
+ opts: { intervalMs?: number } = {}
+): CanvasPublisher {
+ const intervalMs = opts.intervalMs ?? PUBLISH_INTERVAL_MS
+ let last: CanvasNodeState[] = []
+ let pending: CanvasNodeState[] | null = null
+ let timer: ReturnType<typeof setTimeout> | null = null
+
+ const emit = (next: CanvasNodeState[]): void => {
+ const mutations = diffToMutations(last, next)
+ last = next
+ for (const m of mutations) send(m)
+ }
+
+ const onTimer = (): void => {
+ timer = null
+ if (!pending) return
+ const next = pending
+ pending = null
+ emit(next)
+ }
+
+ return {
+ publish(next, o) {
+ if (o?.throttle) {
+ // Leading edge sends at once; further frames inside the window coalesce into one trailing send.
+ if (timer) {
+ pending = next
+ return
+ }
+ emit(next)
+ timer = setTimeout(onTimer, intervalMs)
+ return
+ }
+ if (timer) {
+ clearTimeout(timer)
+ timer = null
+ }
+ pending = null
+ emit(next)
+ },
+ adopt(next) {
+ last = next
+ pending = null
+ },
+ flush() {
+ if (timer) {
+ clearTimeout(timer)
+ timer = null
+ }
+ if (pending) {
+ const next = pending
+ pending = null
+ emit(next)
+ }
+ },
+ dispose() {
+ if (timer) clearTimeout(timer)
+ timer = null
+ pending = null
+ }
+ }
+}
+
+/**
+ * Ephemeral canvas nodes — subagent cards (ids tracked in the agentNodes store) and /loop, /schedule
+ * and /cron cards (`loop-<parentId>`). They are DERIVED on every client from the already-broadcast
+ * `agent:status` stream, live outside React Flow's managed `nodes` array, and are never persisted.
+ * Publishing them would render each card twice on a peer. They are never published — full stop.
+ * This is the one definition of "ephemeral"; Canvas's own change-list filter uses it too.
+ */
+export function isEphemeralNodeId(id: string, ephemeralIds: ReadonlySet<string>): boolean {
+ return ephemeralIds.has(id) || id.startsWith('loop-')
+}
+
+/** The node states that may go on the wire: everything except the ephemeral cards. */
+export function publishableStates(
+ states: CanvasNodeState[],
+ ephemeralIds: ReadonlySet<string>
+): CanvasNodeState[] {
+ return states.filter((n) => !isEphemeralNodeId(n.id, ephemeralIds))
+}