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): canvas:mut reflector fans node mutations to every client but the sender

enes99674bee3231
diff --git a/src/core/canvas-sync.test.ts b/src/core/canvas-sync.test.ts
new file mode 100644
index 000000000..b15392c70
--- /dev/null
+++ b/src/core/canvas-sync.test.ts
@@ -0,0 +1,157 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { initPlatform, resetPlatformForTests, type CorePlatform } from './platform'
+import { fakePlatform } from './platform-fake'
+import { initCanvasSync, reflectTargets, isCanvasMutation, MUTATION_MAX_BYTES } from './canvas-sync'
+import { IPC } from '../shared/ipc'
+import type { CanvasMutation, CanvasNodeState } from '../shared/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
+
+/** Recording CorePlatform with a cast() that carries the sender id (the Stage-1 onWithSender seam). */
+function testPlatform() {
+ const sent: Array<{ to: number; channel: string; args: unknown[] }> = []
+ const registrations: string[] = []
+ let clients: number[] = []
+ const senderListeners = new Map<string, (senderId: number, ...args: any[]) => void>()
+ const p: CorePlatform = {
+ userDataDir: '/tmp/nodeterm-canvas-sync-test',
+ appVersion: '0.0.0-test',
+ isPackaged: false,
+ handle: () => {},
+ on: () => {},
+ handleWithSender: () => {},
+ onWithSender: (ch, fn) => {
+ registrations.push(ch)
+ senderListeners.set(ch, fn)
+ },
+ clientIds: () => clients,
+ sendTo: (to, channel, ...args) => void sent.push({ to, channel, args }),
+ broadcast: () => {},
+ openExternal: async () => {}
+ }
+ return {
+ p,
+ sent,
+ registrations,
+ setClients: (ids: number[]) => (clients = ids),
+ cast: (senderId: number, ...args: unknown[]) =>
+ senderListeners.get(IPC.canvasMut)?.(senderId, ...args)
+ }
+}
+
+let t: ReturnType<typeof testPlatform>
+
+beforeEach(() => {
+ t = testPlatform()
+ initPlatform(t.p)
+ initCanvasSync()
+})
+afterEach(() => resetPlatformForTests())
+
+describe('reflectTargets', () => {
+ it('is every attached client except the sender', () => {
+ expect(reflectTargets([1, 2, 3], 2)).toEqual([1, 3])
+ expect(reflectTargets([1], 1)).toEqual([])
+ expect(reflectTargets([], 1)).toEqual([])
+ })
+})
+
+describe('isCanvasMutation', () => {
+ it('accepts well-formed mutations and rejects malformed ones', () => {
+ expect(isCanvasMutation({ op: 'remove', id: 'n1' })).toBe(true)
+ expect(isCanvasMutation({ op: 'upsert', node: node('n1') })).toBe(true)
+ expect(isCanvasMutation({ op: 'upsert' })).toBe(false)
+ expect(isCanvasMutation({ op: 'upsert', node: { position: { x: 1, y: 1 } } })).toBe(false)
+ expect(isCanvasMutation({ op: 'remove' })).toBe(false)
+ expect(isCanvasMutation({ op: 'nope', id: 'n1' })).toBe(false)
+ expect(isCanvasMutation(null)).toBe(false)
+ expect(isCanvasMutation('n1')).toBe(false)
+ })
+
+ it('rejects a non-finite position (NaN/Infinity would wedge React Flow)', () => {
+ expect(isCanvasMutation({ op: 'upsert', node: { ...node('n1'), position: { x: NaN, y: 0 } } })).toBe(false)
+ expect(
+ isCanvasMutation({ op: 'upsert', node: { ...node('n1'), position: { x: 0, y: Infinity } } })
+ ).toBe(false)
+ })
+
+ it('bounds what comes off the wire: over-long ids and oversized nodes are rejected', () => {
+ expect(isCanvasMutation({ op: 'remove', id: 'x'.repeat(129) })).toBe(false)
+ expect(isCanvasMutation({ op: 'upsert', node: { ...node('x'.repeat(129)) } })).toBe(false)
+ const fat = { ...node('n1'), data: { text: 'a'.repeat(MUTATION_MAX_BYTES) } }
+ expect(isCanvasMutation({ op: 'upsert', node: fat })).toBe(false)
+ })
+})
+
+describe('initCanvasSync (reflector)', () => {
+ it('echo suppression: the sender never receives its own mutation', () => {
+ t.setClients([1, 2, 3])
+ const m: CanvasMutation = { op: 'upsert', node: node('n1', 42) }
+ t.cast(2, 'p1', m)
+ expect(t.sent).toEqual([
+ { to: 1, channel: IPC.canvasMut, args: ['p1', m] },
+ { to: 3, channel: IPC.canvasMut, args: ['p1', m] }
+ ])
+ })
+
+ it('sends nothing when the sender is the only attached client', () => {
+ t.setClients([1])
+ t.cast(1, 'p1', { op: 'remove', id: 'n1' })
+ expect(t.sent).toEqual([])
+ })
+
+ it('drops a malformed mutation instead of reflecting it', () => {
+ t.setClients([1, 2])
+ t.cast(1, 'p1', { op: 'upsert' })
+ t.cast(1, 'p1', undefined)
+ t.cast(1, undefined, { op: 'remove', id: 'n1' })
+ t.cast(1, 'p'.repeat(129), { op: 'remove', id: 'n1' })
+ expect(t.sent).toEqual([])
+ })
+
+ it('holds no canvas state: it reflects each mutation verbatim, in order', () => {
+ t.setClients([1, 2])
+ t.cast(1, 'p1', { op: 'upsert', node: node('a') })
+ t.cast(2, 'p1', { op: 'remove', id: 'a' })
+ expect(t.sent).toEqual([
+ { to: 2, channel: IPC.canvasMut, args: ['p1', { op: 'upsert', node: node('a') }] },
+ { to: 1, channel: IPC.canvasMut, args: ['p1', { op: 'remove', id: 'a' }] }
+ ])
+ })
+
+ it('is NOT rate-limited: a bulk delete of many nodes reflects every one', () => {
+ t.setClients([1, 2])
+ for (let i = 0; i < 200; i++) t.cast(1, 'p1', { op: 'remove', id: `n${i}` })
+ expect(t.sent).toHaveLength(200)
+ expect(t.sent[199]).toEqual({ to: 2, channel: IPC.canvasMut, args: ['p1', { op: 'remove', id: 'n199' }] })
+ })
+
+ // `on` and `onWithSender` COMPOSE on the same channel — on BOTH shells (see
+ // pty-manager-platform.test.ts). A second, plain listener on canvas:mut would reflect every
+ // mutation TWICE to every peer. Registration must be sender-aware and singular.
+ it('registers canvas:mut EXACTLY ONCE, sender-aware (no composed plain listener)', () => {
+ resetPlatformForTests()
+ const fake = fakePlatform()
+ initPlatform(fake)
+ initCanvasSync()
+ expect(fake.senderListeners[IPC.canvasMut]).toBeDefined()
+ expect(fake.listeners[IPC.canvasMut]).toBeUndefined()
+ expect(fake.handlers[IPC.canvasMut]).toBeUndefined()
+ })
+
+ // ServerPlatform keeps an ORDERED SET of listeners per channel, so a second registration on the
+ // same platform is not an overwrite — it would reflect every mutation twice to every peer.
+ it('is idempotent per platform: initCanvasSync twice registers the listener once', () => {
+ expect(t.registrations).toEqual([IPC.canvasMut]) // beforeEach registered it
+ initCanvasSync()
+ expect(t.registrations).toEqual([IPC.canvasMut])
+ })
+})
diff --git a/src/core/canvas-sync.ts b/src/core/canvas-sync.ts
new file mode 100644
index 000000000..6742466a4
--- /dev/null
+++ b/src/core/canvas-sync.ts
@@ -0,0 +1,103 @@
+// Canvas sync — the reflector.
+//
+// Every attached client (an Electron renderer, a Server-Edition browser tab) casts its LOCAL node
+// mutations on `canvas:mut`. This service sends each one back out on the same channel to every
+// OTHER attached client, so all clients converge on the same node set — a teammate's cursor never
+// hovers over stale geometry, and a client whose canvas still held a node someone else deleted can
+// no longer write it back on the next whole-file workspace.save.
+//
+// It is a pipe, not a store: it holds NO canvas state, applies no policy, and persists nothing.
+// The canvas itself stays where it has always been — React Flow in each renderer — and the disk
+// write stays with WorkspaceStore. Echo suppression is by sender ClientId: a client must never
+// receive its own mutation back (it would fight its own optimistic state, and with the renderer's
+// diff-publisher it would loop).
+//
+// NOT RATE-LIMITED, deliberately — unlike presence (see PRESENCE_RATE_BUDGETS). A presence cast is
+// a SAMPLED signal whose loss is self-correcting: the next cursor frame carries the current
+// position. A mutation is an EDGE: nothing supersedes it and nothing re-announces it, so a dropped
+// one is LOST STATE — a node that never appears on a peer's canvas, or a delete that never lands
+// (and then gets written back to disk by that peer's next save, which is the very bug Stage 3
+// exists to fix). Legitimate traffic is also burstier than any bucket sized for it would survive:
+// a drag emits at 20 Hz, and a bulk delete emits N mutations in ONE tick. What IS bounded is the
+// PAYLOAD (see isCanvasMutation): an oversized or malformed mutation is refused at ingest, so a
+// hostile cast cannot amplify into every peer's socket or wedge a peer's React Flow. If a budget
+// is ever needed here, it must queue — never drop.
+//
+// No electron, no ws, no disk (see no-electron.test.ts).
+
+import { platform, type CorePlatform } from './platform'
+import { IPC } from '../shared/ipc'
+import { REF_MAX_LEN, type ClientId } from '../shared/presence'
+import type { CanvasMutation } from '../shared/types'
+
+/**
+ * Ceiling on one mutation's serialized size. A node carries free text (a sticky's body, an
+ * editor's path), and the whole object is reflected verbatim to every peer — so an unbounded one
+ * is an N-way amplifier straight into everyone's WS send buffer (the same sink pty output rides).
+ * 256 KB is orders of magnitude past any real node and cannot refuse a legitimate edit.
+ */
+export const MUTATION_MAX_BYTES = 256_000
+
+/** Every attached client except the sender. Pure — exported for the test. */
+export function reflectTargets(all: ClientId[], sender: ClientId): ClientId[] {
+ return all.filter((id) => id !== sender)
+}
+
+/** An id off the wire: non-empty and bounded by the shared ref cap (node ids and project ids are
+ * short and generated — `term-ab12`, `project-1` — so this can never refuse a real one). Ids are
+ * REJECTED, never truncated: a truncated id would address the WRONG node on every peer. */
+function isRefId(value: unknown): value is string {
+ return typeof value === 'string' && value.length > 0 && value.length <= REF_MAX_LEN
+}
+
+/**
+ * Shape + size guard: a client cast is untrusted input, and it is reflected to every peer as-is.
+ * A malformed payload would wedge a peer's React Flow (applyCanvasMutation would upsert a node with
+ * no id, or a NaN position, which React Flow cannot lay out); an oversized one would flood their
+ * sockets. Drop it here — the reflector never throws, and never keys anything by a wire string.
+ */
+export function isCanvasMutation(value: unknown): value is CanvasMutation {
+ if (!value || typeof value !== 'object') return false
+ const m = value as { op?: unknown; id?: unknown; node?: unknown }
+ if (m.op === 'remove') return isRefId(m.id)
+ if (m.op !== 'upsert') return false
+ const node = m.node as { id?: unknown; position?: { x?: unknown; y?: unknown } } | undefined
+ if (!node || typeof node !== 'object') return false
+ if (!isRefId(node.id)) return false
+ 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)
+}
+
+function withinSizeLimit(m: unknown): boolean {
+ try {
+ // The wire form is JSON on the server and a structured clone on the desktop; either way this
+ // is a faithful measure of what would be pushed to every peer. A value that cannot even be
+ // stringified (BigInt, a cycle) is not something we should be reflecting.
+ return JSON.stringify(m).length <= MUTATION_MAX_BYTES
+ } catch {
+ return false
+ }
+}
+
+/** The platform this reflector is already installed on. `on`/`onWithSender` COMPOSE on the same
+ * channel (ServerPlatform keeps an ordered SET per channel), so a second registration on the same
+ * platform would reflect every mutation twice. Keyed by platform, not a bare boolean, so a fresh
+ * boot (or a fresh test platform) registers again. */
+let registeredOn: CorePlatform | null = null
+
+/** Install the `canvas:mut` reflector. Call once at boot, after initPlatform(). */
+export function initCanvasSync(): void {
+ const p = platform()
+ if (registeredOn === p) return
+ registeredOn = p
+ p.onWithSender(IPC.canvasMut, (senderId: number, projectId: unknown, mutation: unknown) => {
+ // Which canvas the edit belongs to is client-supplied too, and it is reflected verbatim.
+ if (!isRefId(projectId)) return
+ if (!isCanvasMutation(mutation)) return
+ for (const id of reflectTargets(p.clientIds(), senderId)) {
+ p.sendTo(id, IPC.canvasMut, projectId, mutation)
+ }
+ })
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index 1dc5b5030..2c7ec1722 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -18,6 +18,7 @@ import { fetchCheck } from '../core/check'
import { hookServer } from '../core/agents/hook-server'
import { setMainWindow, getMainWindow, sendToMain, shouldHideOnClose } from './main-window'
import { initAgentStatusMirror, recordAgentEvent } from '../core/agent-status-mirror'
+import { initCanvasSync } from '../core/canvas-sync'
import { retainUntilDismissed } from './notifications'
import { installManagedAgentHooks } from '../core/agents/hooks'
import { createSubagentTail } from '../core/subagent-tail'
@@ -535,6 +536,10 @@ app.whenReady().then(async () => {
})
// Mirror live agent status to <userData>/agent-status.json for the external mobile host agent.
initAgentStatusMirror()
+ // Canvas sync: the same reflector the Server Edition boots. With a single window clientIds()
+ // returns one id, so on the desktop today it is a no-op — wired for parity (and for the
+ // relay-host / multi-window futures), not because Electron needs it right now.
+ initCanvasSync()
// Agent hooks: install the managed hook script into each agent's config, then start the
// local HTTP server that receives hook posts and forwards normalized events to the renderer.
diff --git a/src/server/index.ts b/src/server/index.ts
index 4b53c904f..3d8b6a21b 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -17,6 +17,7 @@ import { hookServer } from '../core/agents/hook-server'
import { installManagedAgentHooks } from '../core/agents/hooks'
import { initAgentStatusMirror } from '../core/agent-status-mirror'
import { presenceHub } from '../core/presence/hub'
+import { initCanvasSync } from '../core/canvas-sync'
import { wireAgentStatus } from './agent-status'
import { IPC } from '@shared/ipc'
@@ -74,6 +75,9 @@ export async function startServer(
ptyManager.init(() => settingsStore.get())
ptyManager.registerIpc()
workspaceStore.registerIpc()
+ // Canvas sync: reflect each browser tab's node mutations to the other attached tabs, so every
+ // client converges on the same node set (and no tab writes back a node another tab deleted).
+ initCanvasSync()
// Team presence (hello / cursor / focus / chat). The hub itself is joined per WebSocket in
// ws.ts; this only registers the RPC surface. Presence is transient — nothing is persisted.
presenceHub.registerIpc()
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 765b7a74c..4b682abaf 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -43,6 +43,10 @@ export const IPC = {
agentSubagentActivity: 'agent:subagent-activity',
agentControl: 'agent:control',
agentControlResult: 'agent:control-result',
+ /** Canvas sync: a client casts its local node mutations here; the core reflector
+ * (src/core/canvas-sync.ts) sends them back out on the SAME channel to every OTHER attached
+ * client. Args (both directions): [projectId: string, CanvasMutation]. */
+ canvasMut: 'canvas:mut',
contextLinkSetLinks: 'context-link:set-links',
contextLinkInfo: 'context-link:info',
appUpdateAvailable: 'app:update-available',