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(b4): client RemoteTransport + remote-access UI (isPremium-gated)
enes682c6503d147
diff --git a/src/main/index.ts b/src/main/index.tsindex 4bd082f64..b7cb1e042 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -26,6 +26,7 @@ import { initTelemetry } from './telemetry'import { initClaudeUsage } from './claude-usage'import { initLicense } from './license'import { initRemoteHost } from './remote/host-service'+import { initRemoteClient } from './remote/client-service'const settingsStore = new SettingsStore()const ptyManager = new PtyManager()@@ -298,6 +299,7 @@ app.whenReady().then(async () => {initTelemetry(() => settingsStore.get())initLicense(win)initRemoteHost(win, ptyManager)+ initRemoteClient(win, { isPackaged: app.isPackaged })app.on('activate', () => {if (BrowserWindow.getAllWindows().length === 0) createWindow()diff --git a/src/main/remote/client-service.ts b/src/main/remote/client-service.tsnew file mode 100644index 000000000..1f9a6d7f2--- /dev/null+++ b/src/main/remote/client-service.ts@@ -0,0 +1,260 @@+// Client service — drive a remote host's PTYs over the relay (main process).+//+// The mirror image of `host-service.ts`. When the user pastes a host's pairing OFFER,+// the app: (1) gates on a valid Pro entitlement (+ the dev gate), (2) decodes the offer,+// (3) connects to the relay as the CLIENT (which triggers the host<->client bridge), and+// (4) returns a `connectionId` the renderer's RemoteTransport addresses.+//+// While connected, the client maps the renderer's TerminalTransport calls onto E2EE+// RPC/frames the host understands (the wire contract is host-service.ts's mirror):+// - `create {cols, rows, cwd?, shell?, persistKey?, agentId?}` -> RPC `pty.create`,+// resolving with the host's `{ streamId }` (used as the renderer-facing sessionId).+// - `write(streamId, data)` -> `OP.Input` frame (payload = UTF-8 bytes)+// - `resize(streamId, cols, rows)` -> `OP.Resize` frame (payload = 2x uint16 LE)+// - `kill(streamId)` -> RPC `pty.kill {streamId}`+// - host `OP.Output` frame -> per-session data event (UTF-8 decoded)+// - host `OP.Error` frame -> per-session exit event ({exitCode} JSON), stream dropped+//+// This file is glue over already-tested units (relay-socket, framing, pairing, e2ee). The+// pure call->RPC/frame mapping lives in `createClientHandlers` so it is unit-testable with+// fakes; `initRemoteClient` wires it to IPC, the license gate, and the relay socket.++import { ipcMain, type BrowserWindow } from 'electron'+import { IPC } from '../../shared/ipc'+import type { PtyCreateOptions } from '../../shared/types'+import { isPremium } from '../license'+import { genKeyPair } from './e2ee'+import { OP, type Frame } from './framing'+import { decodeOffer } from './pairing'+import { connectRelay, type RelaySocket } 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.+const DEV_RELAY_OVERRIDE = process.env.NODETERM_RELAY_URL++const textEncoder = new TextEncoder()+const textDecoder = new TextDecoder()++// --- pure client handlers (TerminalTransport calls <-> RPC/frames) -----------++// The slice of RelaySocket the client needs to drive the host.+export interface ClientRelaySocket {+ rpc(method: string, params?: unknown): Promise<unknown>+ sendFrame(op: number, streamId: number, seq: number, payload: Uint8Array): boolean+}++// Sinks the client raises for a stream's output/exit (the IPC layer forwards these to the+// renderer over per-session events). Pure handlers stay free of Electron.+export interface ClientSessionSinks {+ onData(streamId: number, data: string): void+ onExit(streamId: number, exitCode: number): void+}++export interface ClientHandlers {+ /** Open a remote PTY. Resolves with the host's streamId (the renderer-facing sessionId). */+ create(options: PtyCreateOptions): Promise<number>+ /** Send input bytes to a remote PTY. */+ write(streamId: number, data: string): void+ /** Resize a remote PTY (cols, rows). */+ resize(streamId: number, cols: number, rows: number): void+ /** Kill a remote PTY (the host detaches its client; the host-side tmux session survives). */+ kill(streamId: number): void+ /** Route an inbound host frame (OP.Output / OP.Error) to the matching session sinks. */+ onFrame(frame: Frame): void+ /** Drop all tracked streams (called on disconnect/close); does not RPC the host. */+ closeAll(): void+}++interface Stream {+ /** Outbound OP.Input/OP.Resize sequence counter. */+ seq: number+}++function asRecord(value: unknown): Record<string, unknown> {+ return value && typeof value === 'object' ? (value as Record<string, unknown>) : {}+}++/**+ * Build the call->RPC/frame router that drives a remote host's PTYs. Pure over its two+ * injected dependencies (a relay socket + the session sinks) so it can be unit-tested with+ * fakes — no sockets, no Electron.+ */+export function createClientHandlers(+ socket: ClientRelaySocket,+ sinks: ClientSessionSinks+): ClientHandlers {+ const streams = new Map<number, Stream>()++ function resizePayload(cols: number, rows: number): Uint8Array {+ const buf = new Uint8Array(4)+ const view = new DataView(buf.buffer)+ view.setUint16(0, Math.max(1, Math.min(0xffff, Math.floor(cols))), true)+ view.setUint16(2, Math.max(1, Math.min(0xffff, Math.floor(rows))), true)+ return buf+ }++ return {+ async create(options) {+ const body = asRecord(await socket.rpc('pty.create', options))+ const streamId = body.streamId+ if (typeof streamId !== 'number' || !Number.isFinite(streamId)) {+ throw new Error('Host did not return a streamId.')+ }+ streams.set(streamId, { seq: 0 })+ return streamId+ },+ write(streamId, data) {+ const stream = streams.get(streamId)+ if (!stream) return+ socket.sendFrame(OP.Input, streamId, stream.seq++, textEncoder.encode(data))+ },+ resize(streamId, cols, rows) {+ const stream = streams.get(streamId)+ if (!stream) return+ socket.sendFrame(OP.Resize, streamId, stream.seq++, resizePayload(cols, rows))+ },+ kill(streamId) {+ if (!streams.has(streamId)) return+ streams.delete(streamId)+ // Best-effort; the host forgets the stream regardless of our knowing the outcome.+ void socket.rpc('pty.kill', { streamId }).catch(() => {})+ },+ onFrame(frame) {+ if (!streams.has(frame.streamId)) return+ if (frame.op === OP.Output) {+ sinks.onData(frame.streamId, textDecoder.decode(frame.payload))+ return+ }+ if (frame.op === OP.Error) {+ // PTY exit: payload is {exitCode} JSON. Surface it, then forget the stream.+ let exitCode = 0+ try {+ const parsed = JSON.parse(textDecoder.decode(frame.payload)) as { exitCode?: unknown }+ if (typeof parsed.exitCode === 'number') exitCode = parsed.exitCode+ } catch {+ // Malformed exit payload — fall back to code 0.+ }+ streams.delete(frame.streamId)+ sinks.onExit(frame.streamId, exitCode)+ }+ },+ closeAll() {+ streams.clear()+ }+ }+}++// --- dev gate ----------------------------------------------------------------++// Never hit a real relay from an unpackaged build unless a relay is explicitly targeted+// (mirrors host-service.ts's `relayAllowed()`). Packaged builds are always allowed. We can't+// read `app.isPackaged` here without importing it — kept inline in `initRemoteClient`.++// --- IPC wiring --------------------------------------------------------------++interface ClientConnection {+ id: string+ socket: RelaySocket+ handlers: ClientHandlers+}++/**+ * Wire the client-mode IPC. `remote:client:connect` gates on Pro + the dev gate, decodes the+ * offer, connects to the relay as the client (triggering the host bridge), and returns a+ * `connectionId`. The renderer's RemoteTransport(connectionId) then drives remote PTYs over+ * the per-session create/write/resize/kill IPC, with output/exit arriving on per-session+ * events (`remote:client:data:<connId>:<streamId>` / `...:exit:...`).+ */+export function initRemoteClient(win: BrowserWindow, deps?: { isPackaged?: boolean }): void {+ const connections = new Map<string, ClientConnection>()+ let counter = 0++ function send(channel: string, ...args: unknown[]): void {+ if (!win.isDestroyed()) win.webContents.send(channel, ...args)+ }++ function relayAllowed(): boolean {+ return (deps?.isPackaged ?? true) || !!DEV_RELAY_OVERRIDE+ }++ ipcMain.handle(IPC.remoteClientConnect, async (_e, offerCode: string): Promise<string> => {+ if (!isPremium()) {+ throw new Error('Remote access requires nodeterm Pro.')+ }+ if (!relayAllowed()) {+ throw new Error('Remote access is unavailable in development builds (set NODETERM_RELAY_URL).')+ }+ const offer = decodeOffer(String(offerCode ?? ''))+ if (!offer) {+ throw new Error('That pairing code is invalid or incomplete.')+ }++ const connectionId = `remote-${++counter}`+ // Ephemeral keypair: a client identity is per-connection (the host pins its own long-lived+ // 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.+ let handlers: ClientHandlers | null = null++ const socket = connectRelay({+ url: offer.relayEndpoint,+ token: offer.pairingToken,+ role: 'client',+ ourKeys,+ theirPubB64: offer.hostPublicKeyB64,+ onReady: () => {+ // 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.+ },+ onFrame: (frame) => handlers?.onFrame(frame),+ onClose: () => {+ // Host/relay dropped — tell the renderer so it can tear down remote nodes.+ send(IPC.remoteClientClosed(connectionId))+ }+ })++ handlers = createClientHandlers(socket, {+ onData: (streamId, data) => send(IPC.remoteClientData(connectionId, streamId), data),+ onExit: (streamId, exitCode) => send(IPC.remoteClientExit(connectionId, streamId), exitCode)+ })++ connections.set(connectionId, { id: connectionId, socket, handlers })+ return connectionId+ })++ ipcMain.handle(IPC.remoteClientDisconnect, (_e, connectionId: string) => {+ const conn = connections.get(String(connectionId))+ if (!conn) return+ conn.handlers.closeAll()+ conn.socket.close()+ connections.delete(conn.id)+ })++ ipcMain.handle(+ IPC.remoteClientCreate,+ async (_e, connectionId: string, options: PtyCreateOptions): Promise<string> => {+ const conn = connections.get(String(connectionId))+ if (!conn) throw new Error('Remote connection is no longer available.')+ const streamId = await conn.handlers.create(options)+ return String(streamId)+ }+ )++ ipcMain.on(IPC.remoteClientWrite, (_e, connectionId: string, sessionId: string, data: string) => {+ connections.get(String(connectionId))?.handlers.write(Number(sessionId), data)+ })++ ipcMain.on(+ IPC.remoteClientResize,+ (_e, connectionId: string, sessionId: string, cols: number, rows: number) => {+ connections.get(String(connectionId))?.handlers.resize(Number(sessionId), cols, rows)+ }+ )++ ipcMain.on(IPC.remoteClientKill, (_e, connectionId: string, sessionId: string) => {+ connections.get(String(connectionId))?.handlers.kill(Number(sessionId))+ })+}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 860701969..2d78a0363 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -173,6 +173,36 @@ const api: NodeTerminalApi = {start: () => ipcRenderer.invoke(IPC.remoteHostStart),stop: () => ipcRenderer.invoke(IPC.remoteHostStop)},+ remoteClient: {+ connect: (offer) => ipcRenderer.invoke(IPC.remoteClientConnect, offer),+ disconnect: (connectionId) => ipcRenderer.invoke(IPC.remoteClientDisconnect, connectionId),+ create: (connectionId, options) =>+ ipcRenderer.invoke(IPC.remoteClientCreate, connectionId, options),+ write: (connectionId, sessionId, data) =>+ ipcRenderer.send(IPC.remoteClientWrite, connectionId, sessionId, data),+ resize: (connectionId, sessionId, cols, rows) =>+ ipcRenderer.send(IPC.remoteClientResize, connectionId, sessionId, cols, rows),+ kill: (connectionId, sessionId) =>+ ipcRenderer.send(IPC.remoteClientKill, connectionId, sessionId),+ onData: (connectionId, sessionId, listener) => {+ const channel = IPC.remoteClientData(connectionId, Number(sessionId))+ const handler = (_e: unknown, data: string) => listener(data)+ ipcRenderer.on(channel, handler)+ return () => ipcRenderer.removeListener(channel, handler)+ },+ onExit: (connectionId, sessionId, listener) => {+ const channel = IPC.remoteClientExit(connectionId, Number(sessionId))+ const handler = (_e: unknown, code: number) => listener(code)+ ipcRenderer.on(channel, handler)+ return () => ipcRenderer.removeListener(channel, handler)+ },+ onClosed: (connectionId, listener) => {+ const channel = IPC.remoteClientClosed(connectionId)+ const handler = () => listener()+ ipcRenderer.on(channel, handler)+ return () => ipcRenderer.removeListener(channel, handler)+ }+ },bridge: {configPath: () => ipcRenderer.invoke(IPC.bridgeConfigPath),setTopology: (topology) => ipcRenderer.invoke(IPC.bridgeSetTopology, topology),diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex c08a11236..6f839124c 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -80,6 +80,7 @@ import {createAgentNode,createDiffNode,createEditorNode,+ createRemoteTerminalNode,createStickyNode,createTerminalNode,duplicateNode,@@ -663,6 +664,15 @@ export function Canvas() {/** Open a new terminal that runs a command on start (e.g. gh auth login). */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]+ )+/** Open a file as a code editor node on the canvas. */const openFile = useCallback((filePath: string, center?: { x: number; y: number }) => {@@ -766,12 +776,24 @@ 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.+ useEffect(() => {+ const onOpenRemote = (e: Event) => {+ const connectionId = (e as CustomEvent<{ connectionId: string }>).detail?.connectionId+ if (connectionId) addRemoteTerminal(connectionId)+ }+ window.addEventListener('nodeterm:open-remote-terminal', onOpenRemote)+ return () => window.removeEventListener('nodeterm:open-remote-terminal', onOpenRemote)+ }, [addRemoteTerminal])+// ---- multi-node actions (context menu) ----const deleteNodes = useCallback((ids: string[]) => {const set = new Set(ids)nodesRef.current.forEach((n) => {- if (set.has(n.id) && n.type === 'terminal') transport.destroy(n.id)+ // Remote terminals have no local persistent session — only destroy local ones.+ if (set.has(n.id) && n.type === 'terminal' && !n.data.remote) transport.destroy(n.id)})setNodes((ns) => {// Free children of any deleted group back to absolute positions.diff --git a/src/renderer/components/SettingsPanel.tsx b/src/renderer/components/SettingsPanel.tsxindex 387841dc2..34d9ee752 100644--- a/src/renderer/components/SettingsPanel.tsx+++ b/src/renderer/components/SettingsPanel.tsx@@ -27,6 +27,49 @@ export function SettingsPanel({ onClose }: SettingsPanelProps) {const ent = useEntitlement()const [licenseKey, setLicenseKey] = useState('')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.+ const [hostOffer, setHostOffer] = useState('')+ const [hostBusy, setHostBusy] = useState(false)+ const [remoteError, setRemoteError] = useState('')+ const [clientCode, setClientCode] = useState('')+ const [connecting, setConnecting] = useState(false)+ const startHosting = async () => {+ setRemoteError('')+ setHostBusy(true)+ try {+ const { offer } = await window.nodeTerminal.remoteHost.start()+ setHostOffer(offer)+ } catch (err) {+ setRemoteError((err as Error).message)+ setHostBusy(false)+ }+ }+ const stopHosting = async () => {+ await window.nodeTerminal.remoteHost.stop()+ setHostOffer('')+ setHostBusy(false)+ }+ const connectToHost = async () => {+ const code = clientCode.trim()+ if (!code) return+ setRemoteError('')+ setConnecting(true)+ try {+ const connectionId = await window.nodeTerminal.remoteClient.connect(code)+ setClientCode('')+ // Open a remote terminal node on the canvas bound to this connection.+ window.dispatchEvent(+ new CustomEvent('nodeterm:open-remote-terminal', { detail: { connectionId } })+ )+ onClose()+ } catch (err) {+ setRemoteError((err as Error).message)+ } finally {+ setConnecting(false)+ }+ }useEffect(() => {void ent.hydrate()}, [])@@ -439,6 +482,66 @@ export function SettingsPanel({ onClose }: SettingsPanelProps) {</>)}</section>++ {ent.isPremium ? (+ <section>+ <h3>Remote access</h3>+ <p className="set-note">+ Share this device's terminals with another nodeterm, or connect to one that's+ sharing — end-to-end encrypted over the relay.+ </p>++ <h4 className="set-subhead">Allow remote access</h4>+ {hostOffer ? (+ <>+ <p className="set-note">+ Share this pairing code with the other device (single use):+ </p>+ <label className="set-row">+ <span>Pairing code</span>+ <input type="text" readOnly value={hostOffer} onFocus={(e) => e.target.select()} />+ </label>+ <button+ className="set-btn"+ onClick={() => window.nodeTerminal.clipboard.writeText(hostOffer)}+ >+ Copy code+ </button>+ <button className="set-btn" onClick={() => void stopHosting()}>+ Stop sharing+ </button>+ </>+ ) : (+ <button className="set-btn" disabled={hostBusy} onClick={() => void startHosting()}>+ {hostBusy ? 'Starting…' : 'Allow remote access'}+ </button>+ )}++ <h4 className="set-subhead">Connect to a host</h4>+ <label className="set-row">+ <span>Pairing code</span>+ <input+ type="text"+ placeholder="paste the host's code"+ value={clientCode}+ onChange={(e) => setClientCode(e.target.value)}+ />+ </label>+ <button+ className="set-btn"+ disabled={connecting || !clientCode.trim()}+ onClick={() => void connectToHost()}+ >+ {connecting ? 'Connecting…' : 'Connect'}+ </button>++ {remoteError ? (+ <p className="set-note" style={{ color: '#ff9f0a' }}>+ {remoteError}+ </p>+ ) : null}+ </section>+ ) : null}</div></aside></div>,diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 7b6630d92..685dcb072 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -11,7 +11,9 @@ import { Terminal } from '@xterm/xterm'import { FitAddon } from '@xterm/addon-fit'import { SearchAddon } from '@xterm/addon-search'import { renderMarkdown } from '../lib/markdown'-import { transport } from '../terminal/local-transport'+import { transport as localTransport } from '../terminal/local-transport'+import { RemoteTransport } from '../terminal/remote-transport'+import type { TerminalTransport } from '../terminal/transport'import { patchTerminalScale } from '../terminal/scale-fix'import { FindBar } from '../components/FindBar'import { IconSearch } from '../components/icons'@@ -40,6 +42,15 @@ function escapeDroppedPath(p: string): string {*/export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {const { updateNodeData, deleteElements, getZoom, setNodes } = useReactFlow()+ // Pick the session layer: a remote-bound node (data.remote) talks to a host over the relay+ // via RemoteTransport; otherwise the local PTY (LocalTransport). The connectionId is stable+ // for a node's lifetime, so the instance is created once and held in a ref.+ const transportRef = useRef<TerminalTransport | null>(null)+ if (!transportRef.current) {+ const conn = (data.remote as { connectionId: string } | undefined)?.connectionId+ transportRef.current = conn ? new RemoteTransport(conn) : localTransport+ }+ const transport = transportRef.current// Scoped selectors (not the whole settings object) so this node only re-renders when a// field it actually uses changes — not on every unrelated settings edit.const panHoverDelay = useSettings((s) => s.settings.panHoverDelay)diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex 15390cfab..ea325c1b8 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -43,6 +43,12 @@ export interface NodeData {commitOid?: string/** Which agent runs in this terminal node (claude/codex/gemini/custom). */agentId?: AgentId+ /**+ * When set, this terminal runs on a REMOTE host over the relay (RemoteTransport) rather than+ * the local PTY (LocalTransport). Not persisted — remote nodes are transient to a live+ * connection (see flowToNodeStates).+ */+ remote?: { connectionId: string }[key: string]: unknown}@@ -94,6 +100,33 @@ export function createTerminalNode(}}+/**+ * Creates a terminal node bound to a REMOTE host over the relay. Identical to a local terminal+ * except `data.remote.connectionId` is set, which makes TerminalNode pick RemoteTransport instead+ * of LocalTransport. Not persisted (see flowToNodeStates).+ */+export function createRemoteTerminalNode(+ connectionId: string,+ index: number,+ center?: { x: number; y: number }+): CanvasNode {+ return {+ id: nextId('remote'),+ type: 'terminal',+ position: placeAt(center, index, TERMINAL_SIZE.width, TERMINAL_SIZE.height),+ width: TERMINAL_SIZE.width,+ height: TERMINAL_SIZE.height,+ style: { width: TERMINAL_SIZE.width, height: TERMINAL_SIZE.height },+ data: {+ title: 'Remote terminal',+ color: NODE_COLORS[index % NODE_COLORS.length],+ group: null,+ tags: [],+ remote: { connectionId }+ }+ }+}+/*** Path to the bridge MCP config, fetched once from main at boot (see Canvas). When set, new* Claude nodes launch with `--mcp-config <path>` so the Session Bridge tools are available in@@ -411,33 +444,37 @@ export function flowToNodeStates(nodes: CanvasNode[]): CanvasNodeState[] {: kind === 'diff'? DIFF_SIZE: TERMINAL_SIZE- return nodes.map((n) => {- const kind: NodeKind = (n.type as NodeKind) ?? 'terminal'- const collapsed = !!n.data.collapsed- return {- id: n.id,- kind,- position: n.position,- size: {- width: n.measured?.width ?? n.width ?? sizeFor(kind).width,- // While collapsed, persist the expanded height, not the shrunk one.- height: collapsed- ? n.data.expandedHeight ?? sizeFor(kind).height- : n.measured?.height ?? n.height ?? sizeFor(kind).height- },- title: n.data.title,- color: n.data.color,- group: n.data.group,- tags: n.data.tags,- collapsed: n.data.collapsed,- parentId: n.parentId,- shell: n.data.shell,- cwd: n.data.cwd,- text: n.data.text,- filePath: n.data.filePath,- diffStaged: n.data.diffStaged,- commitOid: n.data.commitOid,- agentId: n.data.agentId- }- })+ return nodes+ // Remote terminals are transient to a live relay connection — never persist them (their+ // connectionId is dead after a restart, and they'd otherwise reattach to a stray local tmux).+ .filter((n) => !n.data.remote)+ .map((n) => {+ const kind: NodeKind = (n.type as NodeKind) ?? 'terminal'+ const collapsed = !!n.data.collapsed+ return {+ id: n.id,+ kind,+ position: n.position,+ size: {+ width: n.measured?.width ?? n.width ?? sizeFor(kind).width,+ // While collapsed, persist the expanded height, not the shrunk one.+ height: collapsed+ ? n.data.expandedHeight ?? sizeFor(kind).height+ : n.measured?.height ?? n.height ?? sizeFor(kind).height+ },+ title: n.data.title,+ color: n.data.color,+ group: n.data.group,+ tags: n.data.tags,+ collapsed: n.data.collapsed,+ parentId: n.parentId,+ shell: n.data.shell,+ cwd: n.data.cwd,+ text: n.data.text,+ filePath: n.data.filePath,+ diffStaged: n.data.diffStaged,+ commitOid: n.data.commitOid,+ agentId: n.data.agentId+ }+ })}diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex ff5eafda7..b5e0b4d3a 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -1857,6 +1857,13 @@ body,color: var(--muted);}+.set-subhead {+ margin: 12px 0 6px;+ font-size: 12px;+ font-weight: 600;+ color: var(--label);+}+/* ---- Source control ---- */.sc-meta {display: flex;diff --git a/src/renderer/terminal/remote-transport.ts b/src/renderer/terminal/remote-transport.tsnew file mode 100644index 000000000..2dec5b99b--- /dev/null+++ b/src/renderer/terminal/remote-transport.ts@@ -0,0 +1,54 @@+import type { PtyCreateOptions } from '@shared/types'+import type { TerminalTransport } from './transport'++/**+ * Remote transport: drives a host's PTYs over the relay by binding the IPC API exposed via+ * preload (window.nodeTerminal.remoteClient) to the TerminalTransport interface — the exact+ * shape of LocalTransport, but every call is scoped to a `connectionId` (a relay session+ * established via remoteClient.connect()).+ *+ * `setFlow` and `destroy` are intentionally no-ops: flow control happens host-side (the host+ * pauses/resumes its own PTYs against relay backpressure), and a remote node closing just+ * detaches the client stream via `kill` — the host-side tmux session survives, exactly like+ * LocalTransport's kill/destroy split, but the client never owns the lifecycle of the host's+ * persistent session.+ */+export class RemoteTransport implements TerminalTransport {+ constructor(private readonly connectionId: string) {}++ private get client() {+ return window.nodeTerminal.remoteClient+ }++ create(options: PtyCreateOptions): Promise<string> {+ return this.client.create(this.connectionId, options)+ }++ write(sessionId: string, data: string): void {+ this.client.write(this.connectionId, sessionId, data)+ }++ resize(sessionId: string, cols: number, rows: number): void {+ this.client.resize(this.connectionId, sessionId, cols, rows)+ }++ setFlow(_sessionId: string, _resume: boolean): void {+ // No-op: the host manages flow control on its own PTYs against relay backpressure.+ }++ kill(sessionId: string): void {+ this.client.kill(this.connectionId, sessionId)+ }++ destroy(_persistKey: string): void {+ // No-op: the client doesn't own the host's persistent (tmux) session lifecycle.+ }++ onData(sessionId: string, listener: (data: string) => void): () => void {+ return this.client.onData(this.connectionId, sessionId, listener)+ }++ onExit(sessionId: string, listener: (exitCode: number) => void): () => void {+ return this.client.onExit(this.connectionId, sessionId, listener)+ }+}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 138f13385..2ae71e443 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -79,5 +79,19 @@ export const IPC = {shellOpenExternal: 'shell:open-external',commitGenerate: 'commit:generate',remoteHostStart: 'remote:host:start',- remoteHostStop: 'remote:host:stop'+ remoteHostStop: 'remote:host:stop',+ // Remote-access CLIENT (drives a host's PTYs over the relay).+ remoteClientConnect: 'remote:client:connect',+ remoteClientDisconnect: 'remote:client:disconnect',+ remoteClientCreate: 'remote:client:create',+ remoteClientWrite: 'remote:client:write',+ remoteClientResize: 'remote:client:resize',+ remoteClientKill: 'remote:client:kill',+ // Per-session events broadcast main->renderer (connectionId + streamId appended).+ remoteClientData: (connectionId: string, streamId: number) =>+ `remote:client:data:${connectionId}:${streamId}`,+ remoteClientExit: (connectionId: string, streamId: number) =>+ `remote:client:exit:${connectionId}:${streamId}`,+ // Fired when a connection's relay socket drops (host/relay gone).+ remoteClientClosed: (connectionId: string) => `remote:client:closed:${connectionId}`} as constdiff --git a/src/shared/types.ts b/src/shared/types.tsindex 1be740e3d..8bfa4a319 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -528,6 +528,35 @@ export interface RemoteHostApi {stop(): Promise<void>}+export interface RemoteClientApi {+ /**+ * Connect to a host by its pairing offer string (`nodeterm://pair?code=…` or a bare code).+ * Gates on a valid Pro entitlement (rejects otherwise, and in dev builds without+ * NODETERM_RELAY_URL). Resolves with a `connectionId` to address with the methods below.+ */+ connect(offer: string): Promise<string>+ /** Close a connection: ends the relay socket and drops access to the host's PTYs. */+ disconnect(connectionId: string): Promise<void>+ /** Open a remote PTY on the connected host; resolves with its session id. */+ create(connectionId: string, options: PtyCreateOptions): Promise<string>+ /** Send input to a remote PTY. */+ write(connectionId: string, sessionId: string, data: string): void+ /** Resize a remote PTY. */+ resize(connectionId: string, sessionId: string, cols: number, rows: number): void+ /** Kill a remote PTY (the host detaches; its tmux session survives host-side). */+ kill(connectionId: string, sessionId: string): void+ /** Listen for a remote PTY's output. Returns an unsubscribe function. */+ onData(connectionId: string, sessionId: string, listener: (data: string) => void): () => void+ /** Fires when a remote PTY exits. Returns an unsubscribe function. */+ onExit(+ connectionId: string,+ sessionId: string,+ listener: (exitCode: number) => void+ ): () => void+ /** Fires when the connection's relay socket drops (host/relay gone). Returns unsubscribe. */+ onClosed(connectionId: string, listener: () => void): () => void+}+export interface NodeTerminalApi {pty: PtyApiworkspace: WorkspaceApi@@ -545,6 +574,7 @@ export interface NodeTerminalApi {context: ContextApiclaude: ClaudeApiremoteHost: RemoteHostApi+ remoteClient: RemoteClientApi/** Fires when the user presses Cmd/Ctrl+M (toggle markdown view). Returns unsubscribe. */onMarkdownToggle(listener: () => void): () => void/** Fires when the user presses Cmd/Ctrl+W (close selected node). Returns unsubscribe. */diff --git a/test/remote/client-handlers.test.ts b/test/remote/client-handlers.test.tsnew file mode 100644index 000000000..01806969f--- /dev/null+++ b/test/remote/client-handlers.test.ts@@ -0,0 +1,142 @@+import { describe, it, expect, vi } from 'vitest'+import {+ createClientHandlers,+ type ClientRelaySocket,+ type ClientSessionSinks+} from '../../src/main/remote/client-service'+import { OP } from '../../src/main/remote/framing'++// A fake relay socket that records RPC calls (resolving them on demand) and frames sent.+function fakeSocket(createBody: unknown = { streamId: 7 }) {+ const rpcs: { method: string; params: unknown }[] = []+ const frames: { op: number; streamId: number; seq: number; payload: Uint8Array }[] = []+ const socket: ClientRelaySocket = {+ rpc: vi.fn(async (method, params) => {+ rpcs.push({ method, params })+ if (method === 'pty.create') return createBody+ return {}+ }),+ sendFrame: vi.fn((op, streamId, seq, payload) => {+ frames.push({ op, streamId, seq, payload })+ return true+ })+ }+ return { socket, rpcs, frames }+}++function fakeSinks() {+ const data: { streamId: number; data: string }[] = []+ const exits: { streamId: number; exitCode: number }[] = []+ const sinks: ClientSessionSinks = {+ onData: (streamId, d) => data.push({ streamId, data: d }),+ onExit: (streamId, exitCode) => exits.push({ streamId, exitCode })+ }+ return { sinks, data, exits }+}++describe('createClientHandlers', () => {+ it('maps create to RPC pty.create and resolves with the host streamId', async () => {+ const sock = fakeSocket({ streamId: 7 })+ const sinks = fakeSinks()+ const h = createClientHandlers(sock.socket, sinks.sinks)++ const streamId = await h.create({ cols: 100, rows: 30, cwd: '/tmp' })++ expect(streamId).toBe(7)+ expect(sock.rpcs).toEqual([{ method: 'pty.create', params: { cols: 100, rows: 30, cwd: '/tmp' } }])+ })++ it('throws when the host does not return a numeric streamId', async () => {+ const sock = fakeSocket({})+ const h = createClientHandlers(sock.socket, fakeSinks().sinks)+ await expect(h.create({ cols: 80, rows: 24 })).rejects.toThrow(/streamId/)+ })++ it('sends OP.Input frames for write with an incrementing seq', async () => {+ const sock = fakeSocket({ streamId: 3 })+ const h = createClientHandlers(sock.socket, fakeSinks().sinks)+ await h.create({ cols: 80, rows: 24 })++ h.write(3, 'ls\n')+ h.write(3, 'pwd\n')++ expect(sock.frames).toHaveLength(2)+ expect(sock.frames[0]).toMatchObject({ op: OP.Input, streamId: 3, seq: 0 })+ expect(Buffer.from(sock.frames[0].payload).toString('utf8')).toBe('ls\n')+ expect(sock.frames[1]).toMatchObject({ op: OP.Input, streamId: 3, seq: 1 })+ })++ it('sends OP.Resize frames as 2x uint16 LE (cols, rows)', async () => {+ const sock = fakeSocket({ streamId: 1 })+ const h = createClientHandlers(sock.socket, fakeSinks().sinks)+ await h.create({ cols: 80, rows: 24 })++ h.resize(1, 120, 40)++ expect(sock.frames).toHaveLength(1)+ const f = sock.frames[0]+ expect(f.op).toBe(OP.Resize)+ const view = new DataView(f.payload.buffer, f.payload.byteOffset, f.payload.byteLength)+ expect(view.getUint16(0, true)).toBe(120)+ expect(view.getUint16(2, true)).toBe(40)+ })++ it('ignores write/resize for unknown streams', async () => {+ const sock = fakeSocket()+ const h = createClientHandlers(sock.socket, fakeSinks().sinks)+ h.write(99, 'x')+ h.resize(99, 10, 10)+ expect(sock.frames).toHaveLength(0)+ })++ it('routes OP.Output frames to onData', async () => {+ const sock = fakeSocket({ streamId: 5 })+ const sinks = fakeSinks()+ const h = createClientHandlers(sock.socket, sinks.sinks)+ await h.create({ cols: 80, rows: 24 })++ h.onFrame({ op: OP.Output, streamId: 5, seq: 0, payload: new TextEncoder().encode('hello') })++ expect(sinks.data).toEqual([{ streamId: 5, data: 'hello' }])+ })++ it('routes OP.Error frames to onExit, parses {exitCode}, and drops the stream', async () => {+ const sock = fakeSocket({ streamId: 2 })+ const sinks = fakeSinks()+ const h = createClientHandlers(sock.socket, sinks.sinks)+ await h.create({ cols: 80, rows: 24 })++ h.onFrame({+ op: OP.Error,+ streamId: 2,+ seq: 0,+ payload: new TextEncoder().encode(JSON.stringify({ exitCode: 42 }))+ })++ expect(sinks.exits).toEqual([{ streamId: 2, exitCode: 42 }])+ // After exit the stream is forgotten → further writes are ignored.+ h.write(2, 'x')+ expect(sock.frames).toHaveLength(0)+ })++ it('kill sends RPC pty.kill and forgets the stream', async () => {+ const sock = fakeSocket({ streamId: 9 })+ const h = createClientHandlers(sock.socket, fakeSinks().sinks)+ await h.create({ cols: 80, rows: 24 })++ h.kill(9)+ expect(sock.rpcs).toContainEqual({ method: 'pty.kill', params: { streamId: 9 } })++ // After kill, input for the dropped stream is ignored.+ h.write(9, 'x')+ expect(sock.frames).toHaveLength(0)+ })++ it('ignores frames for unknown streams', () => {+ const sock = fakeSocket()+ const sinks = fakeSinks()+ const h = createClientHandlers(sock.socket, sinks.sinks)+ h.onFrame({ op: OP.Output, streamId: 1, seq: 0, payload: new TextEncoder().encode('x') })+ expect(sinks.data).toHaveLength(0)+ })+})