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(b5): host broadcasts active-project canvas + applies client mutations
enes046cb697119d
diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex 322e707f4..644924907 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -23,7 +23,7 @@ import { promises as fs } from 'fs'import path from 'path'import { app, ipcMain, type BrowserWindow } from 'electron'import { IPC } from '../../shared/ipc'-import type { PtyCreateOptions } from '../../shared/types'+import type { CanvasMutation, CanvasState, PtyCreateOptions } from '../../shared/types'import type { AgentId } from '../../shared/agents/config'import { PtyManager, type DetachedSinks } from '../pty-manager'import { getStoredEntitlement, isPremium } from '../license'@@ -203,6 +203,62 @@ export function createHostHandlers(pty: HostPtyManager, socket: HostRelaySocket)}}+// --- pure canvas mirror sync (host renderer <-> relay) -----------------------++// The wire methods for the host-authoritative canvas mirror (host->client push of the+// full state, client->host one-way mutation command). Kept as constants so both sides agree.+export const CANVAS_STATE_METHOD = 'canvas:state'+export const CANVAS_MUTATE_METHOD = 'canvas:mutate'++// The slice of RelaySocket the canvas sync needs: a one-way host->client push.+export interface CanvasNotifySocket {+ notify(method: string, params?: unknown): boolean+}++export interface HostCanvasSync {+ /** Record the latest active-project canvas snapshot and broadcast it to the client. */+ setState(state: CanvasState): void+ /** Push the current known state now (e.g. on a fresh client connect). No-op if none yet. */+ broadcastCurrent(): void+ /** Route an inbound client RPC/notify; returns the mutation when it is a canvas:mutate. */+ handleRpc(req: RpcRequest): CanvasMutation | null+}++/**+ * Build the host-side canvas mirror router. Pure over its two injected dependencies (the relay+ * socket for host->client push + a sink the IPC layer forwards to the host renderer), so it is+ * unit-testable with fakes — no Electron, no real socket. The host's React Flow stays the single+ * writer: client mutations are surfaced via `onMutation` and applied there, which re-triggers the+ * renderer's debounced `setState` broadcast.+ */+export function createHostCanvasSync(+ socket: CanvasNotifySocket,+ onMutation: (mutation: CanvasMutation) => void+): HostCanvasSync {+ let current: CanvasState | null = null++ function broadcastCurrent(): void {+ if (current) socket.notify(CANVAS_STATE_METHOD, current)+ }++ return {+ setState(state) {+ current = state+ broadcastCurrent()+ },+ broadcastCurrent,+ handleRpc(req) {+ if (req.method !== CANVAS_MUTATE_METHOD) return null+ const mutation = req.params as CanvasMutation+ if (!mutation || typeof mutation !== 'object' || typeof (mutation as { op?: unknown }).op !== 'string') {+ return null+ }+ onMutation(mutation)+ return mutation+ }+ }+}+// --- pairing-token mint ------------------------------------------------------interface PairTokenResponse {@@ -288,17 +344,49 @@ function relayAllowed(): boolean {* the relay as host, and returns the offer string. `remote:host:stop` closes the relay socket* (which kills the served PTYs and drops the client's access).*/-export function initRemoteHost(_win: BrowserWindow, ptyManager: PtyManager): void {+export function initRemoteHost(win: BrowserWindow, ptyManager: PtyManager): void {let socket: RelaySocket | null = nulllet handlers: HostHandlers | null = null+ let canvasSync: HostCanvasSync | null = null+ // Latest snapshot pushed from the renderer, kept across (re)connects so a freshly joined+ // client always gets the current state even if it connected after the last edit.+ let latestCanvas: CanvasState | null = null++ function send(channel: string, ...args: unknown[]): void {+ if (!win.isDestroyed()) win.webContents.send(channel, ...args)+ }function teardown(): void {+ if (broadcastTimer) {+ clearTimeout(broadcastTimer)+ broadcastTimer = null+ }handlers?.closeAll()handlers = null+ canvasSync = nullsocket?.close()socket = null}+ // Re-broadcasting the *full* canvas on every renderer keystroke would be wasteful; the+ // renderer already debounces, but a small main-side debounce coalesces bursts further.+ let broadcastTimer: ReturnType<typeof setTimeout> | null = null+ function scheduleBroadcast(): void {+ if (broadcastTimer) return+ broadcastTimer = setTimeout(() => {+ broadcastTimer = null+ if (latestCanvas) canvasSync?.setState(latestCanvas)+ }, 120)+ broadcastTimer.unref?.()+ }++ // Renderer pushes its serialized active-project canvas; remember it and (debounced) broadcast.+ // Safe to receive when not hosting — it just updates the snapshot a future client will get.+ ipcMain.on(IPC.remoteHostCanvasState, (_e, state: CanvasState) => {+ latestCanvas = state+ scheduleBroadcast()+ })+ipcMain.handle(IPC.remoteHostStart, async (): Promise<{ offer: string }> => {if (!isPremium()) {throw new Error('Remote access requires nodeterm Pro.')@@ -325,9 +413,15 @@ export function initRemoteHost(_win: BrowserWindow, ptyManager: PtyManager): voirole: 'host',ourKeys: keys,onReady: () => {- // Bridge established with a client. Nothing extra to do — handlers are already live.+ // Bridge established with a client — push the current canvas so it mirrors immediately.+ if (latestCanvas) canvasSync?.setState(latestCanvas)+ },+ onRpc: (req) => {+ // Canvas mutations route to the canvas sync (which forwards them to the host renderer,+ // the single writer); everything else is a pty RPC.+ if (canvasSync?.handleRpc(req)) return+ handlers?.onRpc(req)},- onRpc: (req) => handlers?.onRpc(req),onFrame: (frame) => handlers?.onFrame(frame),onClose: () => {// The client (or relay) dropped — kill served PTYs. relay-socket may reconnect; the@@ -336,6 +430,10 @@ export function initRemoteHost(_win: BrowserWindow, ptyManager: PtyManager): voi}})handlers = createHostHandlers(ptyManager, socket)+ // The host renderer applies inbound client mutations to its React Flow (single writer).+ canvasSync = createHostCanvasSync(socket, (mutation) =>+ send(IPC.remoteHostApplyMutation, mutation)+ )return {offer: encodeOffer({diff --git a/src/main/remote/relay-socket.ts b/src/main/remote/relay-socket.tsindex d941cb281..d0acc5c5f 100644--- a/src/main/remote/relay-socket.ts+++ b/src/main/remote/relay-socket.ts@@ -55,6 +55,10 @@ export type RelaySocket = {// Send an RPC request to the peer; resolves with the peer's response body (or// rejects on a non-ok response / timeout / closed connection).rpc(method: string, params?: unknown): Promise<unknown>+ // Fire a one-way notification to the peer (no response expected, never rejects).+ // The peer receives it in `onRpc` with an empty `id` — answering it is a no-op+ // (notifications carry no correlation id). Returns false if not connected.+ notify(method: string, params?: unknown): boolean// Answer a received RPC request (from onRpc) by its id.respond(id: string, ok: boolean, body: unknown): void// Send a terminal frame to the peer. Returns false when the transport is over@@ -95,6 +99,7 @@ const RECONNECT_DELAYS_MS = [500, 1000, 2000, 4000, 8000, 15_000]type RpcEnvelope =| { kind: 'req'; id: string; method: string; params: unknown }+ | { kind: 'notify'; method: string; params: unknown }| { kind: 'res'; id: string; ok: boolean; body: unknown }| { kind: 'keepalive' }@@ -317,6 +322,12 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {opts.onRpc({ id: env.id, method: env.method, params: env.params })return}+ if (env.kind === 'notify') {+ // One-way notification: surface it like an RPC but with an empty id, so a+ // `respond` (if any) is a no-op (no matching pending request on our side).+ opts.onRpc({ id: '', method: env.method, params: env.params })+ return+ }if (env.kind === 'res') {const waiter = pending.get(env.id)if (!waiter) {@@ -422,6 +433,11 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {}})},+ notify(method, params) {+ return sendEncrypted(+ tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ kind: 'notify', method, params })))+ )+ },respond(id, ok, body) {sendEncrypted(tagged(TAG_RPC, textEncoder.encode(JSON.stringify({ kind: 'res', id, ok, body }))))},diff --git a/src/preload/index.ts b/src/preload/index.tsindex 77367cbb3..c0dd20e0d 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -1,6 +1,7 @@import { clipboard, contextBridge, ipcRenderer, webUtils } from 'electron'import { IPC } from '../shared/ipc'import type {+ CanvasMutation,NodeTerminalApi,PtyCreateOptions,UpdateInfo,@@ -30,6 +31,10 @@ function subscribe<A extends unknown[] = []>(channel: string) {}}+// Fan-out subscriber for the host's inbound apply-mutation events (a single ipcRenderer+// listener shared by all renderer subscribers, like the other event channels).+const subscribeMutation = subscribe<[CanvasMutation]>(IPC.remoteHostApplyMutation)+const api: NodeTerminalApi = {pty: {create: (options: PtyCreateOptions) => ipcRenderer.invoke(IPC.ptyCreate, options),@@ -171,7 +176,9 @@ const api: NodeTerminalApi = {},remoteHost: {start: () => ipcRenderer.invoke(IPC.remoteHostStart),- stop: () => ipcRenderer.invoke(IPC.remoteHostStop)+ stop: () => ipcRenderer.invoke(IPC.remoteHostStop),+ sendCanvasState: (state) => ipcRenderer.send(IPC.remoteHostCanvasState, state),+ onApplyMutation: subscribeMutation},remoteClient: {connect: (offer) => ipcRenderer.invoke(IPC.remoteClientConnect, offer),diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex d1c19ed68..80ed041ca 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -61,6 +61,7 @@ import { useAgentNodes } from '../state/agentNodes'import { SubagentNode } from '../nodes/SubagentNode'import { LoopNode } from '../nodes/LoopNode'import type { NormalizedAgentEvent } from '@shared/agents/normalize'+import type { CanvasMutation, CanvasNodeState } from '@shared/types'import {agentConfig,hasHooks,@@ -95,6 +96,19 @@ import {const GRID = 24+// Apply a single client mutation to a serialized node list (renderer-local copy of the pure+// `applyMutation` from main/remote/canvas-sync — duplicated 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).+function applyCanvasMutation(nodes: CanvasNodeState[], m: CanvasMutation): CanvasNodeState[] {+ if (m.op === 'remove') return nodes.filter((n) => n.id !== m.id)+ const idx = nodes.findIndex((n) => n.id === m.node.id)+ if (idx === -1) return [...nodes, m.node]+ const next = nodes.slice()+ next[idx] = m.node+ return next+}+// Stable identity for the common case of no subagent/loop fan-out, so the ephemeral// memo doesn't allocate fresh arrays on every node change (e.g. each drag frame).const NO_EPHEMERAL: { ephemeralNodes: CanvasNode[]; ephemeralEdges: Edge[] } = {@@ -418,6 +432,38 @@ export function Canvas() {return () => clearTimeout(t)}, [dirty, persist])+ // ---- remote canvas mirror (host side) ----+ // While hosting, push the serialized active-project canvas to main (debounced ~120ms) on every+ // change, so a connected client mirrors the layout. Main holds the latest snapshot regardless+ // of whether a client is connected and only broadcasts when one is — so this is safe to send+ // unconditionally (no host-mode flag in the renderer). Skips programmatic loads to avoid a+ // redundant push on project switch (the post-load value is captured by the next real change).+ useEffect(() => {+ if (loadingRef.current) return+ const t = setTimeout(() => {+ window.nodeTerminal.remoteHost.sendCanvasState({ nodes: flowToNodeStates(nodesRef.current) })+ }, 120)+ return () => clearTimeout(t)+ }, [nodes])++ // Apply a client's mutation to React Flow — the host's single writer. Serialize the live nodes,+ // apply the mutation, and convert back, guarded by `loadingRef` so the resulting `setNodes` does+ // not mark the project dirty (it's a remote edit; the normal change path persists it). The+ // change re-triggers the broadcast effect above, echoing the authoritative state to the client.+ useEffect(() => {+ return window.nodeTerminal.remoteHost.onApplyMutation((mutation) => {+ loadingRef.current = true+ setNodes((ns) => {+ const next = applyCanvasMutation(flowToNodeStates(ns), mutation)+ return nodeStatesToFlow(next)+ })+ // Release the guard after the state flush so dirty-marking resumes for local edits.+ queueMicrotask(() => {+ loadingRef.current = false+ })+ })+ }, [setNodes])+// Record an undo snapshot when the canvas settles (debounced; skips drag frames/loads).useEffect(() => {if (loadingRef.current) {diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex edc487492..7e7469fc4 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -80,6 +80,10 @@ export const IPC = {commitGenerate: 'commit:generate',remoteHostStart: 'remote:host:start',remoteHostStop: 'remote:host:stop',+ // Host canvas mirror: renderer pushes its serialized active-project canvas to main;+ // main pushes a client's mutation back to the host renderer to apply.+ remoteHostCanvasState: 'remote:host:canvas-state',+ remoteHostApplyMutation: 'remote:host:apply-mutation',// Remote-access CLIENT (drives a host's PTYs over the relay).remoteClientConnect: 'remote:client:connect',remoteClientDisconnect: 'remote:client:disconnect',diff --git a/src/shared/types.ts b/src/shared/types.tsindex 8850038f5..407eec00d 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -561,6 +561,16 @@ export interface RemoteHostApi {start(): Promise<{ offer: string }>/** Leave host mode: close the relay connection (ends served PTYs, drops client access). */stop(): Promise<void>+ /**+ * Push the host's current active-project canvas snapshot to main. Main keeps the latest+ * and (re)broadcasts it to a connected client (debounced). Safe to call when not hosting.+ */+ sendCanvasState(state: CanvasState): void+ /**+ * Listen for a client's mutation command that the host renderer must apply to its React+ * Flow (the single writer). Returns an unsubscribe function.+ */+ onApplyMutation(listener: (mutation: CanvasMutation) => void): () => void}export interface RemoteClientApi {diff --git a/test/remote/host-canvas-sync.test.ts b/test/remote/host-canvas-sync.test.tsnew file mode 100644index 000000000..7402a80dc--- /dev/null+++ b/test/remote/host-canvas-sync.test.ts@@ -0,0 +1,85 @@+import { describe, it, expect } from 'vitest'+import {+ createHostCanvasSync,+ CANVAS_STATE_METHOD,+ CANVAS_MUTATE_METHOD,+ type CanvasNotifySocket+} from '../../src/main/remote/host-service'+import type { CanvasMutation, CanvasNodeState, CanvasState } from '../../src/shared/types'++function fakeNotifySocket() {+ const sent: { method: string; params: unknown }[] = []+ const socket: CanvasNotifySocket = {+ notify: (method, params) => {+ sent.push({ method, params })+ return true+ }+ }+ return { socket, sent }+}++function node(id: string): CanvasNodeState {+ return {+ id,+ kind: 'terminal',+ position: { x: 0, y: 0 },+ size: { width: 480, height: 320 },+ title: id,+ color: '#888',+ group: null+ }+}++const state = (nodes: CanvasNodeState[]): CanvasState => ({ nodes })++describe('createHostCanvasSync', () => {+ it('broadcasts the state to the client on setState', () => {+ const { socket, sent } = fakeNotifySocket()+ const sync = createHostCanvasSync(socket, () => {})++ const s = state([node('a')])+ sync.setState(s)++ expect(sent).toEqual([{ method: CANVAS_STATE_METHOD, params: s }])+ })++ it('broadcastCurrent re-sends the latest known state (and is a no-op before any)', () => {+ const { socket, sent } = fakeNotifySocket()+ const sync = createHostCanvasSync(socket, () => {})++ sync.broadcastCurrent()+ expect(sent).toHaveLength(0) // nothing known yet++ const s = state([node('a'), node('b')])+ sync.setState(s)+ sync.broadcastCurrent() // e.g. a fresh client connect++ expect(sent).toEqual([+ { method: CANVAS_STATE_METHOD, params: s },+ { method: CANVAS_STATE_METHOD, params: s }+ ])+ })++ it('routes a canvas:mutate RPC to onMutation and returns the parsed mutation', () => {+ const { socket } = fakeNotifySocket()+ const received: CanvasMutation[] = []+ const sync = createHostCanvasSync(socket, (m) => received.push(m))++ const mutation: CanvasMutation = { op: 'upsert', node: node('x') }+ const result = sync.handleRpc({ id: '', method: CANVAS_MUTATE_METHOD, params: mutation })++ expect(result).toEqual(mutation)+ expect(received).toEqual([mutation])+ })++ it('ignores non-canvas RPC methods and malformed mutations (returns null, no callback)', () => {+ const { socket } = fakeNotifySocket()+ const received: CanvasMutation[] = []+ const sync = createHostCanvasSync(socket, (m) => received.push(m))++ expect(sync.handleRpc({ id: 'r1', method: 'pty.create', params: {} })).toBeNull()+ expect(sync.handleRpc({ id: '', method: CANVAS_MUTATE_METHOD, params: null })).toBeNull()+ expect(sync.handleRpc({ id: '', method: CANVAS_MUTATE_METHOD, params: { foo: 1 } })).toBeNull()+ expect(received).toHaveLength(0)+ })+})diff --git a/test/remote/relay-socket.test.ts b/test/remote/relay-socket.test.tsindex 1f3fa7e9e..c6889f650 100644--- a/test/remote/relay-socket.test.ts+++ b/test/remote/relay-socket.test.ts@@ -125,4 +125,52 @@ describe('relay-socket', () => {host.close()client.close()})++ it('delivers a host->client notify to the client onRpc with an empty id', async () => {+ const hostKeys = genKeyPair()+ const clientKeys = genKeyPair()+ const { a: hostTransport, b: clientTransport } = makeTransportPair()++ const hostReady = deferred()+ const clientReady = deferred()+ const received: { id: string; method: string; params: unknown }[] = []++ const host = connectRelay({+ url: 'wss://relay.example/ws',+ token: 'pairing-token',+ role: 'host',+ ourKeys: hostKeys,+ transport: hostTransport,+ onReady: () => hostReady.resolve(),+ onRpc: () => {},+ onFrame: () => {},+ onClose: () => {}+ })++ const client = connectRelay({+ url: 'wss://relay.example/ws',+ token: 'pairing-token',+ role: 'client',+ ourKeys: clientKeys,+ theirPubB64: publicKeyToB64(hostKeys.publicKey),+ transport: clientTransport,+ onReady: () => clientReady.resolve(),+ onRpc: (msg) => received.push(msg),+ onFrame: () => {},+ onClose: () => {}+ })++ await Promise.all([hostReady.promise, clientReady.promise])++ const ok = host.notify('canvas:state', { nodes: [{ id: 'a' }] })+ expect(ok).toBe(true)++ await new Promise((r) => setTimeout(r, 20))+ expect(received).toEqual([+ { id: '', method: 'canvas:state', params: { nodes: [{ id: 'a' }] } }+ ])++ host.close()+ client.close()+ })})