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): client remote-session mirror view + mutations
enes4d83ddcfed5c
diff --git a/src/main/remote/client-service.ts b/src/main/remote/client-service.tsindex 914e40225..2b3e26469 100644--- a/src/main/remote/client-service.ts+++ b/src/main/remote/client-service.ts@@ -21,11 +21,12 @@import { 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 { genKeyPair } from './e2ee'import { OP, type Frame } from './framing'+import { CANVAS_MUTATE_METHOD, CANVAS_STATE_METHOD } from './host-service'import { decodeOffer } from './pairing'-import { connectRelay, type RelaySocket } from './relay-socket'+import { connectRelay, type RelaySocket, type RpcRequest } from './relay-socket'// Default relay endpoint override gate — mirrors host-service.ts. Used only for the dev gate;// the actual endpoint a client connects to comes from the decoded offer.@@ -143,6 +144,46 @@ export function createClientHandlers(}}+// --- pure client canvas mirror router (relay <-> client renderer) ------------++// The slice of RelaySocket the client canvas router needs: a one-way client->host RPC for+// mutations. (Inbound host->client `canvas:state` arrives via `connectRelay.onRpc`, not here.)+export interface CanvasMutateSocket {+ rpc(method: string, params?: unknown): Promise<unknown>+}++export interface ClientCanvasRouter {+ /** Route an inbound host RPC/notify; returns the CanvasState when it is a `canvas:state` push. */+ handleRpc(req: RpcRequest): CanvasState | null+ /** Send the client's optimistic mutation to the host (best-effort; never throws). */+ sendMutation(mutation: CanvasMutation): void+}++/**+ * Build the client-side canvas mirror router. Pure over its single injected dependency (the relay+ * socket for client->host mutation RPC) so it is unit-testable with a fake — no Electron, no real+ * socket. The host's React Flow stays the single writer: the client renders the host's pushed+ * `canvas:state` (surfaced here from `handleRpc`) and sends back mutations the host applies, then+ * the next `canvas:state` reconciles.+ */+export function createClientCanvasRouter(socket: CanvasMutateSocket): ClientCanvasRouter {+ return {+ handleRpc(req) {+ if (req.method !== CANVAS_STATE_METHOD) return null+ const state = req.params as CanvasState+ if (!state || typeof state !== 'object' || !Array.isArray((state as { nodes?: unknown }).nodes)) {+ return null+ }+ return state+ },+ sendMutation(mutation) {+ // Best-effort: the host forgets the client's edit regardless of our knowing the outcome+ // (the next `canvas:state` is authoritative and reconciles any divergence).+ void socket.rpc(CANVAS_MUTATE_METHOD, mutation).catch(() => {})+ }+ }+}+// --- dev gate ----------------------------------------------------------------// Never hit a real relay from an unpackaged build unless a relay is explicitly targeted@@ -155,6 +196,7 @@ interface ClientConnection {id: stringsocket: RelaySockethandlers: ClientHandlers+ canvas: ClientCanvasRouter}/**@@ -194,8 +236,9 @@ export function initRemoteClient(win: BrowserWindow, deps?: { isPackaged?: boole// key in the offer; the client just needs a fresh keypair to derive the shared secret).const ourKeys = genKeyPair()- // Bind handlers lazily so they can reference the socket created just below.+ // Bind handlers + canvas router lazily so their `onRpc` can reference the socket below.let handlers: ClientHandlers | null = null+ let canvas: ClientCanvasRouter | null = nullconst socket = connectRelay({url: offer.relayEndpoint,@@ -206,8 +249,11 @@ export function initRemoteClient(win: BrowserWindow, deps?: { isPackaged?: booleonReady: () => {// Bridge established with the host. Handlers are already live; nothing extra to do.},- onRpc: () => {- // The host never initiates RPC toward the client in this MVP.+ onRpc: (req) => {+ // The host pushes its canvas snapshot as a one-way `canvas:state` notify (id:''). Route it+ // to the client renderer's mirror; the host initiates no other RPC toward the client.+ const state = canvas?.handleRpc(req)+ if (state) send(IPC.remoteClientCanvasState(connectionId), state)},onFrame: (frame) => handlers?.onFrame(frame),onClose: () => {@@ -220,8 +266,9 @@ export function initRemoteClient(win: BrowserWindow, deps?: { isPackaged?: booleonData: (streamId, data) => send(IPC.remoteClientData(connectionId, streamId), data),onExit: (streamId, exitCode) => send(IPC.remoteClientExit(connectionId, streamId), exitCode)})+ canvas = createClientCanvasRouter(socket)- connections.set(connectionId, { id: connectionId, socket, handlers })+ connections.set(connectionId, { id: connectionId, socket, handlers, canvas })return connectionId})@@ -257,4 +304,9 @@ export function initRemoteClient(win: BrowserWindow, deps?: { isPackaged?: booleipcMain.on(IPC.remoteClientKill, (_e, connectionId: string, sessionId: string) => {connections.get(String(connectionId))?.handlers.kill(Number(sessionId))})++ // The client renderer's optimistic canvas edit → forward to the host as a `canvas:mutate` RPC.+ ipcMain.on(IPC.remoteClientMutate, (_e, connectionId: string, mutation: CanvasMutation) => {+ connections.get(String(connectionId))?.canvas.sendMutation(mutation)+ })}diff --git a/src/preload/index.ts b/src/preload/index.tsindex c0dd20e0d..6f976842b 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -2,6 +2,7 @@ import { clipboard, contextBridge, ipcRenderer, webUtils } from 'electron'import { IPC } from '../shared/ipc'import type {CanvasMutation,+ CanvasState,NodeTerminalApi,PtyCreateOptions,UpdateInfo,@@ -208,7 +209,15 @@ const api: NodeTerminalApi = {const handler = () => listener()ipcRenderer.on(channel, handler)return () => ipcRenderer.removeListener(channel, handler)- }+ },+ onCanvasState: (connectionId, listener) => {+ const channel = IPC.remoteClientCanvasState(connectionId)+ const handler = (_e: unknown, state: Parameters<typeof listener>[0]) => listener(state)+ ipcRenderer.on(channel, handler)+ return () => ipcRenderer.removeListener(channel, handler)+ },+ sendMutation: (connectionId, mutation) =>+ ipcRenderer.send(IPC.remoteClientMutate, connectionId, mutation)},handoff: {build: (sessionId, agentId, sourceNodeId, cwd) =>diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 80ed041ca..82f779fca 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -61,7 +61,6 @@ 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,@@ -77,6 +76,7 @@ import { branchClaudeSession } from '../lib/claudeBranch'import { useSettings } from '../state/settings'import { useContextWindow } from '../state/contextWindow'import {+ applyCanvasMutation,claudeLaunchCommand,COLLAPSED_HEIGHT,createAgentNode,@@ -96,19 +96,6 @@ 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[] } = {diff --git a/src/renderer/canvas/RemoteSessionView.tsx b/src/renderer/canvas/RemoteSessionView.tsxnew file mode 100644index 000000000..50deff7ea--- /dev/null+++ b/src/renderer/canvas/RemoteSessionView.tsx@@ -0,0 +1,133 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import {+ Background,+ BackgroundVariant,+ ReactFlow,+ ReactFlowProvider,+ SelectionMode,+ useNodesState,+ type NodeChange+} from '@xyflow/react'+import type { CanvasMutation, CanvasNodeState } from '@shared/types'+import { TerminalNode } from '../nodes/TerminalNode'+import { StickyNode } from '../nodes/StickyNode'+import { GroupNode } from '../nodes/GroupNode'+import { EditorNode } from '../nodes/EditorNode'+import { DiffNode } from '../nodes/DiffNode'+import { withNodeBoundary } from '../components/NodeBoundary'+import { flowToNodeStates, nodeStatesToFlow, type CanvasNode } from '../state/workspace'++/**+ * RemoteSessionView — the CLIENT's transient mirror of a host's active-project canvas.+ *+ * It is fed by the host's pushed `canvas:state` (over `remoteClient.onCanvasState`) which it+ * renders with `nodeStatesToFlow`. Terminal nodes are bound to `RemoteTransport(connectionId)` by+ * injecting `data.remote = { connectionId }` — the host node id stays the React Flow node id, so a+ * terminal addresses the host's matching PTY/tmux session.+ *+ * The mirror is NOT persisted: nodes live only in this component's local state, never in the+ * workspace store / `flowToNodeStates` save path. The host's React Flow remains the single writer:+ * the client applies its own edits (drag-stop / delete) OPTIMISTICALLY to the local mirror and+ * sends a `CanvasMutation` to the host via `remoteClient.sendMutation`; the next authoritative+ * `canvas:state` reconciles any divergence.+ *+ * NOTE (Task 6): this component is not yet mounted anywhere. The "New Remote Connection" UX ++ * routing that swaps the main Canvas for this view (when a `connectionId` is active) is Task 6;+ * mounting is simply `<RemoteSessionView connectionId={id} onClose={...} />`.+ */+export function RemoteSessionView({ connectionId }: { connectionId: string }): React.JSX.Element {+ return (+ <ReactFlowProvider>+ <RemoteSessionCanvas connectionId={connectionId} />+ </ReactFlowProvider>+ )+}++/** Tag every terminal node as remote-bound so TerminalNode picks RemoteTransport(connectionId). */+function bindRemote(states: CanvasNodeState[], connectionId: string): CanvasNode[] {+ return nodeStatesToFlow(states).map((n) =>+ n.type === 'terminal' ? { ...n, data: { ...n.data, remote: { connectionId } } } : n+ )+}++function RemoteSessionCanvas({ connectionId }: { connectionId: string }): React.JSX.Element {+ const [nodes, setNodes, onNodesChange] = useNodesState<CanvasNode>([])+ // Guard so applying an inbound host snapshot doesn't echo back as a client mutation.+ const applyingHostStateRef = useRef(false)++ const nodeTypes = useMemo(+ () => ({+ terminal: withNodeBoundary(TerminalNode),+ sticky: withNodeBoundary(StickyNode),+ group: withNodeBoundary(GroupNode),+ editor: withNodeBoundary(EditorNode),+ diff: withNodeBoundary(DiffNode)+ }),+ []+ )++ // Render the host's authoritative snapshot. Reconciles any local optimistic divergence.+ useEffect(() => {+ return window.nodeTerminal.remoteClient.onCanvasState(connectionId, (state) => {+ applyingHostStateRef.current = true+ setNodes(bindRemote(state.nodes, connectionId))+ queueMicrotask(() => {+ applyingHostStateRef.current = false+ })+ })+ }, [connectionId, setNodes])++ // Send the client's optimistic edit upstream (the host applies it; the next snapshot reconciles).+ const sendMutation = useCallback(+ (mutation: CanvasMutation) => {+ window.nodeTerminal.remoteClient.sendMutation(connectionId, mutation)+ },+ [connectionId]+ )++ // Position changes are applied locally by React Flow; we forward the final layout on drag-stop.+ const handleNodesChange = useCallback(+ (changes: NodeChange<CanvasNode>[]) => {+ onNodesChange(changes)+ if (applyingHostStateRef.current) return+ // A removal is final immediately (no drag-stop), so forward it here. Drop the matching+ // remote PTY stream too — handled host-side once it sees the node gone, but the local+ // terminal already unmounts (its kill on unmount detaches the stream).+ for (const c of changes) {+ if (c.type === 'remove') sendMutation({ op: 'remove', id: c.id })+ }+ },+ [onNodesChange, sendMutation]+ )++ // On drag-stop, forward the dragged node's final state as an upsert (optimistic local apply+ // already happened via onNodesChange position updates).+ const handleNodeDragStop = useCallback(+ (_e: unknown, node: CanvasNode) => {+ if (applyingHostStateRef.current) return+ // Serialize just this node back to a CanvasNodeState (reuse the shared serializer, then+ // pick the one we moved — keeps size/position/kind logic in one place).+ const state = flowToNodeStates([node]).find((n) => n.id === node.id)+ if (state) sendMutation({ op: 'upsert', node: state })+ },+ [sendMutation]+ )++ return (+ <div className="remote-session-view" style={{ width: '100%', height: '100%' }}>+ <ReactFlow+ nodes={nodes}+ edges={[]}+ nodeTypes={nodeTypes}+ onNodesChange={handleNodesChange}+ onNodeDragStop={handleNodeDragStop}+ selectionMode={SelectionMode.Partial}+ panOnScroll+ zoomOnScroll={false}+ proOptions={{ hideAttribution: true }}+ >+ <Background variant={BackgroundVariant.Dots} gap={24} size={1} />+ </ReactFlow>+ </div>+ )+}diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex ea325c1b8..d672ed1e4 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -1,5 +1,5 @@import type { Node } from '@xyflow/react'-import type { CanvasNodeState, NodeKind, Project } from '@shared/types'+import type { CanvasMutation, CanvasNodeState, NodeKind, Project } from '@shared/types'import type { AgentId } from '@shared/agents/config'import { agentConfig } from '@shared/agents/config'import { useSettings } from './settings'@@ -391,6 +391,24 @@ export function ungroupNodes(nodes: CanvasNode[], groupId: string): CanvasNode[]}/** 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/ipc.ts b/src/shared/ipc.tsindex 7e7469fc4..161ff418d 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -91,6 +91,11 @@ export const IPC = {remoteClientWrite: 'remote:client:write',remoteClientResize: 'remote:client:resize',remoteClientKill: 'remote:client:kill',+ // Client canvas mirror: main pushes the host's full canvas snapshot to the client renderer;+ // the client renderer sends its local mutations back for main to RPC to the host.+ remoteClientMutate: 'remote:client:mutate',+ // Host canvas snapshot pushed main->renderer for a connection (connectionId appended).+ remoteClientCanvasState: (connectionId: string) => `remote:client:canvas-state:${connectionId}`,// Per-session events broadcast main->renderer (connectionId + streamId appended).remoteClientData: (connectionId: string, streamId: number) =>`remote:client:data:${connectionId}:${streamId}`,diff --git a/src/shared/types.ts b/src/shared/types.tsindex 407eec00d..7a6fdfb4d 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -600,6 +600,16 @@ export interface RemoteClientApi {): () => void/** Fires when the connection's relay socket drops (host/relay gone). Returns unsubscribe. */onClosed(connectionId: string, listener: () => void): () => void+ /**+ * Listen for the host's full canvas snapshot for a connection (the mirror source of truth).+ * Returns an unsubscribe function.+ */+ onCanvasState(connectionId: string, listener: (state: CanvasState) => void): () => void+ /**+ * Send a canvas mutation to the host (the client's optimistic edit). Main forwards it as a+ * `canvas:mutate` RPC; the host applies it and the next `canvas:state` reconciles.+ */+ sendMutation(connectionId: string, mutation: CanvasMutation): void}export interface NodeTerminalApi {diff --git a/test/remote/client-canvas-router.test.ts b/test/remote/client-canvas-router.test.tsnew file mode 100644index 000000000..751a58702--- /dev/null+++ b/test/remote/client-canvas-router.test.ts@@ -0,0 +1,79 @@+import { describe, it, expect, vi } from 'vitest'+import {+ createClientCanvasRouter,+ type CanvasMutateSocket+} from '../../src/main/remote/client-service'+import {+ CANVAS_MUTATE_METHOD,+ CANVAS_STATE_METHOD+} from '../../src/main/remote/host-service'+import type { CanvasMutation, CanvasNodeState, CanvasState } from '../../src/shared/types'++function fakeSocket() {+ const rpcs: { method: string; params: unknown }[] = []+ const socket: CanvasMutateSocket = {+ rpc: vi.fn(async (method, params) => {+ rpcs.push({ method, params })+ return {}+ })+ }+ return { socket, rpcs }+}++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('createClientCanvasRouter', () => {+ it('returns the CanvasState for an inbound canvas:state notify (id:"")', () => {+ const { socket } = fakeSocket()+ const router = createClientCanvasRouter(socket)++ const s = state([node('a'), node('b')])+ const result = router.handleRpc({ id: '', method: CANVAS_STATE_METHOD, params: s })++ expect(result).toEqual(s)+ })++ it('ignores non-canvas methods and malformed state (returns null)', () => {+ const { socket } = fakeSocket()+ const router = createClientCanvasRouter(socket)++ expect(router.handleRpc({ id: 'r1', method: 'pty.create', params: {} })).toBeNull()+ expect(router.handleRpc({ id: '', method: CANVAS_STATE_METHOD, params: null })).toBeNull()+ expect(router.handleRpc({ id: '', method: CANVAS_STATE_METHOD, params: { foo: 1 } })).toBeNull()+ // nodes must be an array+ expect(+ router.handleRpc({ id: '', method: CANVAS_STATE_METHOD, params: { nodes: 'x' } })+ ).toBeNull()+ })++ it('sendMutation forwards the mutation to the host as a canvas:mutate RPC', () => {+ const { socket, rpcs } = fakeSocket()+ const router = createClientCanvasRouter(socket)++ const mutation: CanvasMutation = { op: 'upsert', node: node('x') }+ router.sendMutation(mutation)++ expect(rpcs).toEqual([{ method: CANVAS_MUTATE_METHOD, params: mutation }])+ })++ it('sendMutation swallows a rejected RPC (best-effort)', async () => {+ const socket: CanvasMutateSocket = { rpc: vi.fn(async () => Promise.reject(new Error('gone'))) }+ const router = createClientCanvasRouter(socket)++ expect(() => router.sendMutation({ op: 'remove', id: 'z' })).not.toThrow()+ // Let the rejected promise settle; the .catch() must absorb it (no unhandled rejection).+ await Promise.resolve()+ })+})