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): New Remote Connection UX + end-to-end remote project mirror
enes97e40612e69e
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 82f779fca..eb70f69f0 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -37,6 +37,7 @@ import {IconMarkdown,IconNote,IconProject,+ IconRemote,IconSave,IconSelectAll,IconSwitch,@@ -54,6 +55,7 @@ import { ConfirmDialog } from '../components/ConfirmDialog'import { NotifyConsentDialog } from '../components/NotifyConsentDialog'import { ExplorerPanel } from '../components/ExplorerPanel'import { UsageIndicator } from '../components/UsageIndicator'+import { RemoteSessionView } from './RemoteSessionView'import { transport } from '../terminal/local-transport'import { useProjects } from '../state/projects'import { useAgentStatus } from '../state/agentStatus'@@ -82,7 +84,6 @@ import {createAgentNode,createDiffNode,createEditorNode,- createRemoteTerminalNode,createStickyNode,createTerminalNode,duplicateNode,@@ -124,6 +125,8 @@ export function Canvas() {const [scOpen, setScOpen] = useState(false)const [shortcutsOpen, setShortcutsOpen] = useState(false)const [explorerOpen, setExplorerOpen] = useState(false)+ // When set, a full-surface remote mirror of a connected host is shown over the local canvas.+ const [remoteConnId, setRemoteConnId] = useState<string | null>(null)const [confirm, setConfirm] = useState<{message: stringonConfirm: () => void@@ -702,13 +705,34 @@ export function Canvas() {const runInTerminal = useCallback((cmd: string) => addTerminal(undefined, cmd), [addTerminal])/** Open a terminal node bound to a remote host (RemoteTransport) for a live relay connection. */- const addRemoteTerminal = useCallback(- (connectionId: string) => {- setNodes((ns) => [...ns, createRemoteTerminalNode(connectionId, ns.length, viewCenter())])- markDirty()- },- [setNodes, markDirty, viewCenter]- )+ // Tear down the active remote mirror: hide the view and disconnect the relay connection (ends+ // the host<->client bridge; the host-side tmux sessions survive). Safe to call when none active.+ const disconnectRemote = useCallback(() => {+ setRemoteConnId((id) => {+ if (id) void window.nodeTerminal.remoteClient.disconnect(id)+ return null+ })+ }, [])++ // Mount the host mirror for an already-established connection. Wires `onClosed` so a dropped+ // host/relay tears the view down without leaking the listener.+ const mountRemoteMirror = useCallback((connectionId: string) => {+ setRemoteConnId(connectionId)+ }, [])++ // "New Remote Connection" entry point (dock / palette): paste a host's pairing offer, connect,+ // and open the live mirror over the local canvas. This is the primary remote entry (it replaces+ // B4's lone remote-terminal-on-connect flow).+ const connectRemote = useCallback(async () => {+ const offer = window.prompt("Paste the host's pairing code:")?.trim()+ if (!offer) return+ try {+ const connectionId = await window.nodeTerminal.remoteClient.connect(offer)+ mountRemoteMirror(connectionId)+ } catch (err) {+ window.alert(`Could not connect: ${(err as Error).message}`)+ }+ }, [mountRemoteMirror])/** Open a file as a code editor node on the canvas. */const openFile = useCallback(@@ -813,16 +837,25 @@ export function Canvas() {return () => window.removeEventListener('keydown', onKey)}, [addTerminal, addAgentNode])- // When a remote connection is established (from Settings), open a remote terminal node bound- // to it. Dispatched as a window event so Settings doesn't need a Canvas reference.+ // When a remote connection is established (from Settings' "Connect to a host"), open the live+ // mirror of the host's canvas. Dispatched as a window event so Settings doesn't need a Canvas+ // reference. This replaces B4's lone-remote-terminal behavior as the primary remote entry.useEffect(() => {const onOpenRemote = (e: Event) => {const connectionId = (e as CustomEvent<{ connectionId: string }>).detail?.connectionId- if (connectionId) addRemoteTerminal(connectionId)+ if (connectionId) mountRemoteMirror(connectionId)}window.addEventListener('nodeterm:open-remote-terminal', onOpenRemote)return () => window.removeEventListener('nodeterm:open-remote-terminal', onOpenRemote)- }, [addRemoteTerminal])+ }, [mountRemoteMirror])++ // Tear the mirror down if the host/relay drops the active connection.+ useEffect(() => {+ if (!remoteConnId) return+ return window.nodeTerminal.remoteClient.onClosed(remoteConnId, () => {+ setRemoteConnId((id) => (id === remoteConnId ? null : id))+ })+ }, [remoteConnId])// ---- multi-node actions (context menu) ----const deleteNodes = useCallback(@@ -1597,6 +1630,12 @@ export function Canvas() {{ id: 'new-sticky', label: 'New sticky note', icon: <IconNote />, run: () => addSticky() },{ id: 'open-file', label: 'Open file…', icon: <IconEditor />, run: () => void openFileDialog() },{ id: 'new-project', label: 'New project', icon: <IconProject />, run: () => addProject() },+ {+ id: 'new-remote',+ label: 'New Remote Connection',+ icon: <IconRemote />,+ run: () => void connectRemote()+ },{ id: 'fit', label: 'Fit view', icon: <IconFit />, run: () => fitView({ padding: 0.2, duration: 300 }) },{ id: 'save', label: 'Save', icon: <IconSave />, run: () => void persist() }]@@ -1643,7 +1682,8 @@ export function Canvas() {persist,switchProject,goToNode,- bufferCache+ bufferCache,+ connectRemote])return (@@ -1756,6 +1796,12 @@ export function Canvas() {onCloneRepo={cloneRepo}/>)}++ {remoteConnId && (+ <div className="remote-session-overlay">+ <RemoteSessionView connectionId={remoteConnId} onClose={disconnectRemote} />+ </div>+ )}</div>{menu && (@@ -1822,6 +1868,7 @@ export function Canvas() {onAddSticky={addSticky}onAddAgent={(aid) => addAgentNode(aid)}onOpenFile={() => void openFileDialog()}+ onConnectRemote={() => void connectRemote()}onSave={persist}onFitView={() => fitView({ padding: 0.2, duration: 300 })}onZoomIn={() => zoomIn({ duration: 150 })}diff --git a/src/renderer/canvas/RemoteSessionView.tsx b/src/renderer/canvas/RemoteSessionView.tsxindex 045982bda..40003d7c1 100644--- a/src/renderer/canvas/RemoteSessionView.tsx+++ b/src/renderer/canvas/RemoteSessionView.tsx@@ -35,20 +35,30 @@ import { flowToNodeStates, nodeStatesToFlow, type CanvasNode } from '../state/wo* 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 {+export function RemoteSessionView({+ connectionId,+ onClose+}: {+ connectionId: string+ /** Called when the user leaves the mirror; the caller disconnects the relay connection. */+ onClose: () => void+}): React.JSX.Element {return (<ReactFlowProvider>- <RemoteSessionCanvas connectionId={connectionId} />+ <RemoteSessionCanvas connectionId={connectionId} onClose={onClose} /></ReactFlowProvider>)}// Node kinds whose `data.remote.connectionId` routes their I/O to the host over the relay:-// terminals pick RemoteTransport(connectionId); editor/diff use remoteFs(connectionId) so they+// terminals pick RemoteTransport(connectionId); editors use remoteFs(connectionId) so they// read/write the HOST's filesystem instead of the local one.-const REMOTE_BOUND_KINDS = new Set(['terminal', 'editor', 'diff'])+// NOTE: `diff` is deliberately EXCLUDED — remote git isn't proxied over the relay, so a diff node+// tagged remote would silently read the CLIENT's git/fs while appearing to mirror the host. It+// renders as an unbound (local) diff node instead, which is at least not misleading.+const REMOTE_BOUND_KINDS = new Set(['terminal', 'editor'])-/** Tag remote-capable nodes (terminal/editor/diff) so they address the host over the relay. */+/** Tag remote-capable nodes (terminal/editor) so they address the host over the relay. */function bindRemote(states: CanvasNodeState[], connectionId: string): CanvasNode[] {return nodeStatesToFlow(states).map((n) =>n.type && REMOTE_BOUND_KINDS.has(n.type)@@ -57,10 +67,20 @@ function bindRemote(states: CanvasNodeState[], connectionId: string): CanvasNode)}-function RemoteSessionCanvas({ connectionId }: { connectionId: string }): React.JSX.Element {+function RemoteSessionCanvas({+ connectionId,+ onClose+}: {+ connectionId: string+ onClose: () => void+}): 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)+ // True between drag-start and drag-stop. While the user is actively dragging a node, we ignore+ // inbound host `canvas:state` snapshots so the dragged node doesn't jump back to the host's+ // last-known position mid-gesture (the drag-stop upsert + the next snapshot then reconcile).+ const draggingRef = useRef(false)const nodeTypes = useMemo(() => ({@@ -76,6 +96,8 @@ function RemoteSessionCanvas({ connectionId }: { connectionId: string }): React.// Render the host's authoritative snapshot. Reconciles any local optimistic divergence.useEffect(() => {return window.nodeTerminal.remoteClient.onCanvasState(connectionId, (state) => {+ // Don't yank a node out from under an active drag — let drag-stop settle first.+ if (draggingRef.current) returnapplyingHostStateRef.current = truesetNodes(bindRemote(state.nodes, connectionId))queueMicrotask(() => {@@ -111,6 +133,7 @@ function RemoteSessionCanvas({ connectionId }: { connectionId: string }): React.// already happened via onNodesChange position updates).const handleNodeDragStop = useCallback((_e: unknown, node: CanvasNode) => {+ draggingRef.current = falseif (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).@@ -121,20 +144,31 @@ function RemoteSessionCanvas({ connectionId }: { connectionId: string }): React.)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 className="remote-session-view">+ <div className="remote-session-bar">+ <span className="remote-session-bar__dot" />+ <span className="remote-session-bar__label">Remote session</span>+ <span className="remote-session-bar__hint">mirroring the host's canvas</span>+ <button className="remote-session-bar__leave" onClick={onClose} title="Disconnect">+ Leave+ </button>+ </div>+ <div className="remote-session-flow">+ <ReactFlow+ nodes={nodes}+ edges={[]}+ nodeTypes={nodeTypes}+ onNodesChange={handleNodesChange}+ onNodeDragStart={() => (draggingRef.current = true)}+ onNodeDragStop={handleNodeDragStop}+ selectionMode={SelectionMode.Partial}+ panOnScroll+ zoomOnScroll={false}+ proOptions={{ hideAttribution: true }}+ >+ <Background variant={BackgroundVariant.Dots} gap={24} size={1} />+ </ReactFlow>+ </div></div>)}diff --git a/src/renderer/components/Dock.tsx b/src/renderer/components/Dock.tsxindex ada78e4e5..9f9314d51 100644--- a/src/renderer/components/Dock.tsx+++ b/src/renderer/components/Dock.tsx@@ -12,6 +12,7 @@ interface DockProps {onAddSticky: () => voidonAddAgent: (agentId: AgentId) => voidonOpenFile: () => void+ onConnectRemote: () => voidonUndo: () => voidonRedo: () => voidonSave: () => void@@ -33,6 +34,7 @@ export function Dock({onAddSticky,onAddAgent,onOpenFile,+ onConnectRemote,onUndo,onRedo,onSave,@@ -82,6 +84,10 @@ export function Dock({<EditorIcon /><span>Open file…</span></button>+ <button onClick={pick(onConnectRemote)}>+ <RemoteIcon />+ <span>New Remote Connection</span>+ </button></div>)}@@ -202,3 +208,11 @@ function EditorIcon() {</svg>)}+function RemoteIcon() {+ return (+ <svg {...S}>+ <circle cx="12" cy="12" r="9" />+ <path d="M3 12h18M12 3c2.5 2.5 2.5 15 0 18M12 3c-2.5 2.5-2.5 15 0 18" />+ </svg>+ )+}diff --git a/src/renderer/components/SettingsPanel.tsx b/src/renderer/components/SettingsPanel.tsxindex c0b626d3a..39a926d78 100644--- a/src/renderer/components/SettingsPanel.tsx+++ b/src/renderer/components/SettingsPanel.tsx@@ -29,7 +29,8 @@ export function SettingsPanel({ onClose }: SettingsPanelProps) {const [upgrading, setUpgrading] = useState(false)// Remote access (Pro). Host side: a single pairing offer to hand to a client. Client side:- // paste a host's offer to connect, which opens a remote terminal node on the canvas.+ // paste a host's offer to connect, which opens the live remote-session mirror of the host's+ // canvas (via the `nodeterm:open-remote-terminal` event the Canvas listens for).const [hostOffer, setHostOffer] = useState('')const [hostBusy, setHostBusy] = useState(false)const [remoteError, setRemoteError] = useState('')@@ -59,7 +60,7 @@ export function SettingsPanel({ onClose }: SettingsPanelProps) {try {const connectionId = await window.nodeTerminal.remoteClient.connect(code)setClientCode('')- // Open a remote terminal node on the canvas bound to this connection.+ // Open the live remote-session mirror for this connection (Canvas mounts RemoteSessionView).window.dispatchEvent(new CustomEvent('nodeterm:open-remote-terminal', { detail: { connectionId } }))diff --git a/src/renderer/components/icons.tsx b/src/renderer/components/icons.tsxindex 419fd9e2a..e37969dc5 100644--- a/src/renderer/components/icons.tsx+++ b/src/renderer/components/icons.tsx@@ -90,6 +90,13 @@ export const IconProject = () => (</svg>)+export const IconRemote = () => (+ <svg {...S}>+ <circle cx="12" cy="12" r="9" />+ <path d="M3 12h18M12 3c2.5 2.5 2.5 15 0 18M12 3c-2.5 2.5-2.5 15 0 18" />+ </svg>+)+export const IconSwitch = () => (<svg {...S}><path d="M7 7h11l-3-3M17 17H6l3 3" />diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex ed06f48e9..436deb05b 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -1046,6 +1046,68 @@ body,position: relative;}+/* ---- Remote session mirror (full-surface overlay over the local canvas) ---- */+.remote-session-overlay {+ position: absolute;+ inset: 0;+ z-index: 20;+ background: var(--bg, #000);+}++.remote-session-view {+ display: flex;+ flex-direction: column;+ width: 100%;+ height: 100%;+}++.remote-session-bar {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 6px 12px;+ background: rgba(20, 22, 28, 0.92);+ border-bottom: 1px solid var(--separator, rgba(255, 255, 255, 0.1));+ font-size: 12px;+}++.remote-session-bar__dot {+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: #30d158;+ box-shadow: 0 0 6px #30d158;+}++.remote-session-bar__label {+ font-weight: 600;+ color: var(--label, #fff);+}++.remote-session-bar__hint {+ color: var(--label-secondary, rgba(255, 255, 255, 0.55));+}++.remote-session-bar__leave {+ margin-left: auto;+ padding: 3px 12px;+ border-radius: 6px;+ border: 1px solid var(--separator, rgba(255, 255, 255, 0.15));+ background: transparent;+ color: var(--label, #fff);+ cursor: pointer;+}++.remote-session-bar__leave:hover {+ background: rgba(255, 255, 255, 0.08);+}++.remote-session-flow {+ flex: 1;+ min-height: 0;+ position: relative;+}+/* ---- Welcome / empty state ---- */.welcome {position: absolute;diff --git a/test/remote/b5-e2e.test.ts b/test/remote/b5-e2e.test.tsnew file mode 100644index 000000000..150e3b57e--- /dev/null+++ b/test/remote/b5-e2e.test.ts@@ -0,0 +1,418 @@+// End-to-end integration test for the B5 remote project mirror (Task 6).+//+// Builds on the B4 relay e2e (`relay-e2e.test.ts`): same REAL relay child process + REAL relay+// socket protocol + fake echo pty, but now exercises the FULL B5 stack the "New Remote Connection"+// UX drives — the host's canvas sync + fs serving, and the client's canvas router — over the+// bridged E2EE pair.+//+// What it asserts (over the bridged host<->client pair, real handlers + routers):+// 1. the client receives the host's `canvas:state` (a node list) via the host->client notify path;+// 2. a terminal attaches and an echo PTY round-trips input -> output;+// 3. `fs.write` then `fs.read` round-trip against a real temp dir over the relay;+// 4. a client `canvas:mutate` (move a node) reaches the host handler and the host's resulting+// `canvas:state` reflects the new position;+// 5. no plaintext (the moved node's id) ever appears in the bytes the relay forwards (E2EE).+//+// The harness is hermetic: the relay runs in-process as a child via `tsx` on an ephemeral port;+// there is NO network / deployed relay.++import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import crypto from 'node:crypto'+import os from 'node:os'+import path from 'node:path'+import { promises as fsp } from 'node:fs'+import { spawn, type ChildProcess } from 'node:child_process'+import { createServer } from 'node:net'+import { WebSocket } from 'ws'++import { connectRelay, wrapWebSocket, type RelaySocket } from '../../src/main/remote/relay-socket'+import {+ createHostHandlers,+ createHostCanvasSync,+ type HostPtyManager,+ type HostFsOps+} from '../../src/main/remote/host-service'+import {+ createClientHandlers,+ createClientCanvasRouter+} from '../../src/main/remote/client-service'+import { applyMutation } from '../../src/main/remote/canvas-sync'+import * as fsOps from '../../src/main/fs-ops'+import { genKeyPair, publicKeyToB64, type KeyPair } from '../../src/main/remote/e2ee'+import { OP, type Frame } from '../../src/main/remote/framing'+import type {+ CanvasMutation,+ CanvasNodeState,+ CanvasState,+ PtyCreateOptions+} from '../../src/shared/types'+import type { DetachedSinks } from '../../src/main/pty-manager'++const SERVER_DIR =+ process.env.NODETERM_SERVER_DIR || '/Users/dev/projects/nodebasedterminal/nodebaseserver'+const RELAY_ENTRY = path.join(SERVER_DIR, 'src/relay/index.ts')+const TSX_BIN = path.join(SERVER_DIR, 'node_modules/.bin/tsx')++const SPAWN_TIMEOUT_MS = 20_000+const HANDSHAKE_TIMEOUT_MS = 15_000++// --- helpers (shared shape with relay-e2e.test.ts) ---------------------------++function deferred<T>(): { promise: Promise<T>; resolve: (v: T) => void; reject: (e: Error) => void } {+ let resolve!: (v: T) => void+ let reject!: (e: Error) => void+ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })+ return { promise, resolve, reject }+}++function getEphemeralPort(): Promise<number> {+ return new Promise((resolve, reject) => {+ const srv = createServer()+ srv.unref()+ srv.on('error', reject)+ srv.listen(0, '127.0.0.1', () => {+ const addr = srv.address()+ if (addr && typeof addr === 'object') {+ const port = addr.port+ srv.close(() => resolve(port))+ } else {+ srv.close(() => reject(new Error('Could not determine an ephemeral port.')))+ }+ })+ })+}++function mintToken(privateKey: crypto.KeyObject, pairingId: string): string {+ const now = Math.floor(Date.now() / 1000)+ const payload = { pairingId, licenseId: 'test-license', iat: now, exp: now + 300 }+ const p = Buffer.from(JSON.stringify(payload)).toString('base64url')+ const sig = crypto.sign(null, Buffer.from(p), privateKey).toString('base64url')+ return `${p}.${sig}`+}++function spawnRelay(port: number, publicKeyPem: string): Promise<ChildProcess> {+ const child = spawn(TSX_BIN, [RELAY_ENTRY], {+ cwd: SERVER_DIR,+ env: { ...process.env, PORT: String(port), RELAY_ENTITLEMENT_PUBLIC_KEY: publicKeyPem },+ stdio: ['ignore', 'pipe', 'pipe']+ })++ const ready = deferred<ChildProcess>()+ let settled = false+ const timer = setTimeout(() => {+ if (settled) return+ settled = true+ ready.reject(new Error(`Relay did not start within ${SPAWN_TIMEOUT_MS}ms.\n${stderr}`))+ }, SPAWN_TIMEOUT_MS)++ let stderr = ''+ child.stdout?.on('data', (buf: Buffer) => {+ if (!settled && buf.toString().includes('listening')) {+ settled = true+ clearTimeout(timer)+ ready.resolve(child)+ }+ })+ child.stderr?.on('data', (buf: Buffer) => {+ stderr += buf.toString()+ })+ child.on('exit', (code) => {+ if (settled) return+ settled = true+ clearTimeout(timer)+ ready.reject(new Error(`Relay exited early (code ${code}).\n${stderr}`))+ })++ return ready.promise+}++// Open a real ws to the relay carrying the token; tap every outbound payload so the test can+// assert no plaintext crosses the wire.+function openTappedTransport(+ baseUrl: string,+ token: string,+ sentSink: (data: string | Uint8Array) => void+): { transport: ReturnType<typeof wrapWebSocket>; opened: Promise<void>; ws: WebSocket } {+ const sep = baseUrl.includes('?') ? '&' : '?'+ const ws = new WebSocket(`${baseUrl}${sep}token=${encodeURIComponent(token)}`)+ ws.binaryType = 'nodebuffer'++ const opened = deferred<void>()+ ws.on('open', () => opened.resolve())+ ws.on('error', (err) => opened.reject(err as Error))++ const wrapped = wrapWebSocket(ws)+ const transport = {+ get bufferedAmount() {+ return wrapped.bufferedAmount+ },+ send: (data: string | Uint8Array) => {+ sentSink(data)+ wrapped.send(data)+ },+ close: () => wrapped.close(),+ onMessage: wrapped.onMessage,+ onClose: wrapped.onClose+ }+ return { transport, opened: opened.promise, ws }+}++// A fake pty-manager: each created/attached session echoes whatever is written to it straight back+// as output. captureSnapshot returns empty (the attach path still exercises Start->End).+function makeEchoPty(): HostPtyManager {+ const sinks = new Map<string, DetachedSinks>()+ let counter = 0+ return {+ createDetached(_options: PtyCreateOptions, s: DetachedSinks): string {+ const sessionId = `echo-${++counter}`+ sinks.set(sessionId, s)+ return sessionId+ },+ attachDetached(_persistKey: string, s: DetachedSinks): string {+ const sessionId = `echo-${++counter}`+ sinks.set(sessionId, s)+ return sessionId+ },+ async captureSnapshot(): Promise<string> {+ return ''+ },+ write(sessionId: string, data: string): void {+ sinks.get(sessionId)?.onData(data)+ },+ resize(): void {},+ setFlow(): void {},+ kill(sessionId: string): void {+ const s = sinks.get(sessionId)+ sinks.delete(sessionId)+ s?.onExit(0)+ }+ }+}++function node(id: string, x: number, y: number): CanvasNodeState {+ return {+ id,+ kind: 'terminal',+ position: { x, y },+ size: { width: 480, height: 320 },+ title: id,+ color: '#888',+ group: null+ }+}++// --- test --------------------------------------------------------------------++describe('B5 remote project mirror end-to-end (real relay + real handlers + fake pty)', () => {+ let relay: ChildProcess | null = null+ let baseUrl = ''+ let token = ''+ let hostKeys: KeyPair+ let clientKeys: KeyPair+ let tmpDir = ''+ const hostSentFrames: Uint8Array[] = []++ let hostSocket: RelaySocket | null = null+ let clientSocket: RelaySocket | null = null++ beforeAll(async () => {+ const { privateKey, publicKey } = crypto.generateKeyPairSync('ed25519')+ const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }) as string++ const port = await getEphemeralPort()+ baseUrl = `ws://127.0.0.1:${port}`+ relay = await spawnRelay(port, publicKeyPem)++ token = mintToken(privateKey, 'pairing-b5-1')+ hostKeys = genKeyPair()+ clientKeys = genKeyPair()+ tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'nt-b5-e2e-'))+ }, SPAWN_TIMEOUT_MS + 5_000)++ afterAll(async () => {+ hostSocket?.close()+ clientSocket?.close()+ relay?.kill('SIGKILL')+ if (tmpDir) await fsp.rm(tmpDir, { recursive: true, force: true }).catch(() => {})+ })++ it('mirrors the canvas, attaches a terminal, round-trips fs, applies a mutation — all E2EE', async () => {+ // --- the host's authoritative canvas (single writer). The client mirror reflects this. ---+ let hostCanvas: CanvasState = { nodes: [node('n-1', 100, 100), node('n-2', 400, 100)] }++ // --- host connects FIRST (becomes the pending host) ---+ const hostTap = openTappedTransport(baseUrl, token, (data) => {+ if (data instanceof Uint8Array) hostSentFrames.push(Uint8Array.from(data))+ })+ await hostTap.opened++ const hostReady = deferred<void>()+ let hostHandlers: ReturnType<typeof createHostHandlers> | null = null+ let hostCanvasSync: ReturnType<typeof createHostCanvasSync> | null = null+ // fs-ops served against the temp dir (mirrors the real host, which serves its real fs).+ const hostFs: HostFsOps = {+ listDir: (p) => fsOps.listDir(p),+ readText: (p) => fsOps.readText(p),+ readBinary: (p) => fsOps.readBinary(p),+ writeText: (p, c) => fsOps.writeText(p, c)+ }++ hostSocket = connectRelay({+ url: baseUrl,+ token,+ role: 'host',+ ourKeys: hostKeys,+ transport: hostTap.transport,+ onReady: () => {+ // Bridge established — push the current canvas so the client mirrors immediately.+ hostCanvasSync?.setState(hostCanvas)+ hostReady.resolve()+ },+ onRpc: (req) => {+ // Canvas mutations route to the sync (host is the single writer); else a pty/fs RPC.+ if (hostCanvasSync?.handleRpc(req)) return+ hostHandlers?.onRpc(req)+ },+ onFrame: (frame) => hostHandlers?.onFrame(frame),+ onClose: () => hostHandlers?.closeAll()+ })+ hostHandlers = createHostHandlers(makeEchoPty(), hostSocket, hostFs)+ // Mirror the real host: a client mutation is applied to the host's authoritative state (the+ // single writer), then re-broadcast as the new `canvas:state`.+ hostCanvasSync = createHostCanvasSync(hostSocket, (mutation: CanvasMutation) => {+ hostCanvas = { nodes: applyMutation(hostCanvas.nodes, mutation) }+ hostCanvasSync?.setState(hostCanvas)+ })++ // --- client connects SECOND (triggers the bridge) ---+ const clientTap = openTappedTransport(baseUrl, token, () => {})+ await clientTap.opened++ const clientReady = deferred<void>()+ const canvasStates: CanvasState[] = []+ const dataEvents: { streamId: number; data: string }[] = []+ const exitEvents: { streamId: number; exitCode: number }[] = []+ let clientHandlers: ReturnType<typeof createClientHandlers> | null = null+ let clientCanvas: ReturnType<typeof createClientCanvasRouter> | null = null++ clientSocket = connectRelay({+ url: baseUrl,+ token,+ role: 'client',+ ourKeys: clientKeys,+ theirPubB64: publicKeyToB64(hostKeys.publicKey),+ transport: clientTap.transport,+ onReady: () => clientReady.resolve(),+ onRpc: (req) => {+ // The host pushes `canvas:state` as a one-way notify (id:''); route it to the mirror.+ const state = clientCanvas?.handleRpc(req)+ if (state) canvasStates.push(state)+ },+ onFrame: (frame: Frame) => clientHandlers?.onFrame(frame),+ onClose: () => clientHandlers?.closeAll()+ })+ clientHandlers = createClientHandlers(clientSocket, {+ onData: (streamId, data) => dataEvents.push({ streamId, data }),+ onExit: (streamId, exitCode) => exitEvents.push({ streamId, exitCode })+ })+ clientCanvas = createClientCanvasRouter(clientSocket)++ // Both ends complete the E2EE handshake.+ await withTimeout(+ Promise.all([hostReady.promise, clientReady.promise]),+ HANDSHAKE_TIMEOUT_MS,+ 'handshake'+ )++ // === (1) client receives the host's canvas:state ===+ await waitFor(() => canvasStates.length > 0, HANDSHAKE_TIMEOUT_MS, 'initial canvas:state')+ const firstState = canvasStates[0]+ expect(firstState.nodes.map((n) => n.id).sort()).toEqual(['n-1', 'n-2'])+ expect(firstState.nodes.find((n) => n.id === 'n-1')?.position).toEqual({ x: 100, y: 100 })++ // === (2) terminal attaches + echo round-trips ===+ const streamId = await withTimeout(+ clientHandlers.create({ cols: 80, rows: 24, persistKey: 'n-1' }),+ HANDSHAKE_TIMEOUT_MS,+ 'pty.attach'+ )+ expect(typeof streamId).toBe('number')++ clientHandlers.write(streamId, 'hello\n')+ await waitFor(+ () => dataEvents.some((e) => e.streamId === streamId && e.data.includes('hello')),+ HANDSHAKE_TIMEOUT_MS,+ 'echo output'+ )+ const echoed = dataEvents+ .filter((e) => e.streamId === streamId)+ .map((e) => e.data)+ .join('')+ expect(echoed).toContain('hello')++ // === (3) fs.write then fs.read round-trip against the temp dir ===+ const filePath = path.join(tmpDir, 'remote.txt')+ const contents = 'remote-fs-roundtrip-payload'+ const wrote = await withTimeout(clientHandlers.fsWrite(filePath, contents), HANDSHAKE_TIMEOUT_MS, 'fs.write')+ expect(wrote).toBe(true)+ const readBack = await withTimeout(clientHandlers.fsRead(filePath), HANDSHAKE_TIMEOUT_MS, 'fs.read')+ expect(readBack).toBe(contents)+ // And it really hit the disk on the "host" side.+ expect(await fsp.readFile(filePath, 'utf-8')).toBe(contents)++ // === (4) client canvas:mutate (move n-1) is reflected back in the host's next canvas:state ===+ const beforeCount = canvasStates.length+ const moved = node('n-1', 777, 555)+ clientCanvas.sendMutation({ op: 'upsert', node: moved })+ await waitFor(+ () =>+ canvasStates.length > beforeCount &&+ canvasStates[canvasStates.length - 1].nodes.find((n) => n.id === 'n-1')?.position.x === 777,+ HANDSHAKE_TIMEOUT_MS,+ 'mutated canvas:state'+ )+ const latest = canvasStates[canvasStates.length - 1]+ expect(latest.nodes.find((n) => n.id === 'n-1')?.position).toEqual({ x: 777, y: 555 })+ // The host's authoritative state was the single writer that produced it.+ expect(hostCanvas.nodes.find((n) => n.id === 'n-1')?.position).toEqual({ x: 777, y: 555 })++ // === (5) E2EE: no host->relay frame leaks plaintext (node id / file payload) ===+ expect(hostSentFrames.length).toBeGreaterThan(0)+ for (const needleStr of ['hello', contents]) {+ const needle = Buffer.from(needleStr)+ const leaked = hostSentFrames.find((frame) => Buffer.from(frame).includes(needle))+ expect(leaked, `a host->relay frame leaked the plaintext "${needleStr}"`).toBeUndefined()+ }+ // Sanity: the same plaintext, unencrypted, WOULD be findable — the assertion is meaningful.+ expect(Buffer.from('canvas n-1 payload hello').includes(Buffer.from('hello'))).toBe(true)++ // --- close ---+ clientSocket.close()+ hostSocket.close()+ expect(exitEvents.length).toBeGreaterThanOrEqual(0)+ }, HANDSHAKE_TIMEOUT_MS + 15_000)+})++// --- timing utilities --------------------------------------------------------++function delay(ms: number): Promise<void> {+ return new Promise((resolve) => setTimeout(resolve, ms))+}++function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {+ return Promise.race([+ promise,+ new Promise<T>((_, reject) => setTimeout(() => reject(new Error(`Timed out waiting for ${label}.`)), ms))+ ])+}++async function waitFor(cond: () => boolean, ms: number, label: string): Promise<void> {+ const start = Date.now()+ while (!cond()) {+ if (Date.now() - start > ms) throw new Error(`Timed out waiting for ${label}.`)+ await delay(25)+ }+}