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
refactor(relay): delete remoteClient dialect + migrate settings dialogs (Stage 4 Task 10)
enesfc1b2bc15802
diff --git a/src/main/index.ts b/src/main/index.tsindex c655f755d..11dca74e9 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -67,7 +67,6 @@ import { killRelayHostsByPeerKey } from './remote/relay-host'import { initRelayHost } from './remote/relay-host-service'import { createRevoker } from './remote/revocation'import { loadApprovedDevices, saveApprovedDevices } from './remote/approved-devices'-import { initRemoteClient } from './remote/client-service'import { connectRelayClient, type RelayClientSession } from './remote/relay-client'import { decodeOffer } from './remote/pairing'import { loadOrCreatePeerKeyPair } from './remote/peer-identity'@@ -1030,11 +1029,11 @@ app.whenReady().then(async () => {ipcMain.on(IPC.remoteStandingHostSet, (_e, enabled: boolean) => standingHost?.setEnabled(!!enabled))// Reconcile from persisted settings on launch (starts hosting if enabled + Pro).standingHost.syncFromSettings()- initRemoteClient(win, { isPackaged: app.isPackaged })- // NEW interactive relay CLIENT (Stage 4): connect OUT to another desktop's host. `connectRelayClient`+ // Interactive relay CLIENT (Stage 4): connect OUT to another desktop's host. `connectRelayClient`// runs the client half of mutual SAS approval and, once BOTH humans confirm, exposes the raw rpc.ts- // frame pipe (`relay:client:send`/`relay:client:frame`) that Task 4's RpcClient drives. Runs BESIDE- // the legacy client (initRemoteClient). Inert until `relay:client:connect` — a solo user pays nothing.+ // frame pipe (`relay:client:send`/`relay:client:frame`) that Task 4's RpcClient drives. This is the+ // ONLY desktop client path now — the legacy `initRemoteClient` dialect was deleted in Task 10.+ // Inert until `relay:client:connect` — a solo user pays nothing.{const relayClients = new Map<string, RelayClientSession>()const sendTo = (channel: string, ...args: unknown[]): void => {@@ -1042,7 +1041,7 @@ app.whenReady().then(async () => {}ipcMain.handle(IPC.relayClientConnect, async (_e, offerCode: string): Promise<string> => {// No Pro gate on the client: the paywall is the HOST minting the pairing token, so a valid offer- // is the credential (mirrors initRemoteClient). The dev/relay gate still applies.+ // is the credential (the paywall is host-side). The dev/relay gate still applies.if (!relayAllowed()) {throw new Error('Remote access is unavailable in development builds (set NODETERM_RELAY_URL).')}diff --git a/src/main/remote/client-service.ts b/src/main/remote/client-service.tsdeleted file mode 100644index 2c188d1ce..000000000--- a/src/main/remote/client-service.ts+++ /dev/null@@ -1,383 +0,0 @@-// 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 { CanvasMutation, CanvasState, DirEntry, PtyCreateOptions } from '../../shared/types'-import { genKeyPair } from './e2ee'-import { OP, type Frame } from './framing'-import { CANVAS_MUTATE_METHOD, CANVAS_REQUEST_METHOD, CANVAS_STATE_METHOD } from './host-service'-import { decodeOffer } from './pairing'-import { connectRelay, type RelaySocket, type RpcRequest } from './relay-socket'-import { createSnapshotReassembler, type SnapshotReassembler } from './snapshot'--// 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- /** List a directory on the host's filesystem (over `fs.list` RPC). */- fsList(path: string): Promise<DirEntry[]>- /** Read a host file's UTF-8 text (over `fs.read` RPC). */- fsRead(path: string): Promise<string>- /** Read a host file as base64 (over `fs.readBinary` RPC). */- fsReadBinary(path: string): Promise<string>- /** Write UTF-8 text to a host file (over `fs.write` RPC). */- fsWrite(path: string, content: string): Promise<boolean>-}--interface Stream {- /** Outbound OP.Input/OP.Resize sequence counter. */- seq: number- /** Reassembles the host's SnapshotStart→Chunk*→End into the initial screen text. */- snapshot: SnapshotReassembler-}--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) {- // RemoteTransport is only ever used for mirrored (remote) nodes, so `create` maps to- // `pty.attach` — the client attaches to the host's EXISTING tmux session for this node id- // (the persistKey is the host node id from the mirror) and gets a snapshot of the current- // screen before live output, instead of spawning a fresh blank PTY (B4's blank-terminal bug).- const body = asRecord(- await socket.rpc('pty.attach', {- nodeId: options.persistKey,- cols: options.cols,- rows: options.rows- })- )- 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, snapshot: createSnapshotReassembler() })- 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) {- const stream = streams.get(frame.streamId)- if (!stream) return- if (- frame.op === OP.SnapshotStart ||- frame.op === OP.SnapshotChunk ||- frame.op === OP.SnapshotEnd- ) {- // Buffer the snapshot; on End deliver the reassembled current screen as the FIRST onData- // so the mirrored xterm paints it before any live output arrives.- const res = stream.snapshot.accept(frame)- if (res.done && res.text) sinks.onData(frame.streamId, res.text)- 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()- },- async fsList(path) {- const body = asRecord(await socket.rpc('fs.list', { path }))- return Array.isArray(body.entries) ? (body.entries as DirEntry[]) : []- },- async fsRead(path) {- const body = asRecord(await socket.rpc('fs.read', { path }))- return typeof body.content === 'string' ? body.content : ''- },- async fsReadBinary(path) {- const body = asRecord(await socket.rpc('fs.readBinary', { path }))- return typeof body.base64 === 'string' ? body.base64 : ''- },- async fsWrite(path, content) {- const body = asRecord(await socket.rpc('fs.write', { path, content }))- return body.ok === true- }- }-}--// --- 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-// (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- canvas: ClientCanvasRouter-}--/**- * Wire the client-mode IPC. `remote:client:connect` gates on the dev gate only (the host's Pro- * mints the pairing token, so the client needs no entitlement), 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> => {- // No Pro gate on the client: the paywall is the HOST minting the pairing token- // (/v1/pair/token requires the host's entitlement). A valid offer is the credential, so a- // user's free device can connect to their own Pro host. The dev/relay gate still applies.- 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 + canvas router lazily so their `onRpc` can reference the socket below.- let handlers: ClientHandlers | null = null- let canvas: ClientCanvasRouter | null = null-- const socket = connectRelay({- url: offer.relayEndpoint,- token: offer.pairingToken,- role: 'client',- ourKeys,- theirPubB64: offer.hostPublicKeyB64,- onReady: () => {- // Bridge established. Surface the channel SAS so the client human can compare it with the- // code the host shows before approving. Then ask the host to (re-)push its current canvas.- send(IPC.remoteClientSas(connectionId), socket.sas())- socket.notify(CANVAS_REQUEST_METHOD)- },- 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: () => {- // 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)- })- canvas = createClientCanvasRouter(socket)-- connections.set(connectionId, { id: connectionId, socket, handlers, canvas })- 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))- })-- // 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)- })-- // Remote filesystem: the client renderer's `remoteFs(connectionId)` proxies the local `fs:*`- // shape onto the host's filesystem over the relay's `fs.*` RPCs. A missing connection degrades- // to the same empty/false values the host's fs-ops would return on error.- ipcMain.handle(IPC.remoteClientFsList, (_e, connectionId: string, path: string) =>- connections.get(String(connectionId))?.handlers.fsList(path) ?? Promise.resolve([])- )- ipcMain.handle(IPC.remoteClientFsRead, (_e, connectionId: string, path: string) =>- connections.get(String(connectionId))?.handlers.fsRead(path) ?? Promise.resolve('')- )- ipcMain.handle(IPC.remoteClientFsReadBinary, (_e, connectionId: string, path: string) =>- connections.get(String(connectionId))?.handlers.fsReadBinary(path) ?? Promise.resolve('')- )- ipcMain.handle(- IPC.remoteClientFsWrite,- (_e, connectionId: string, path: string, content: string) =>- connections.get(String(connectionId))?.handlers.fsWrite(path, content) ??- Promise.resolve(false)- )-}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 07bce6086..6708adfba 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -45,7 +45,7 @@ const subscribeMutation = subscribe<[CanvasMutation]>(IPC.remoteHostApplyMutatioconst subscribePeerPending = subscribe<[{ sas: string | null; id: string }]>(IPC.remoteHostPeerPending)// New relay tunnel (Stage 4). Non-per-id host events reuse the fan-out helper; per-connection-// client events (sas/approved/frame/closed) attach directly, like remoteClient's per-session ones.+// client events (sas/approved/frame/closed) attach directly per connectionId.const subscribeRelayPeerPending = subscribe<[RelayPeerPending]>(IPC.relayHostPeerPending)const subscribeRelayHostOpen = subscribe<[{ id: string }]>(IPC.relayHostOpen)const subscribeRelayHostClosed = subscribe<[{ id: string }]>(IPC.relayHostClosed)@@ -364,56 +364,6 @@ const api: NodeTerminalApi = {reject: (id: string) => ipcRenderer.send(IPC.remoteHostReject, { id }),setPhoneAccess: (enabled) => ipcRenderer.send(IPC.remoteStandingHostSet, enabled)},- 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)- },- 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)- },- onSas: (connectionId, listener) => {- const channel = IPC.remoteClientSas(connectionId)- const handler = (_e: unknown, sas: string | null) => listener(sas)- ipcRenderer.on(channel, handler)- return () => ipcRenderer.removeListener(channel, handler)- },- sendMutation: (connectionId, mutation) =>- ipcRenderer.send(IPC.remoteClientMutate, connectionId, mutation),- fsList: (connectionId, path) => ipcRenderer.invoke(IPC.remoteClientFsList, connectionId, path),- fsRead: (connectionId, path) => ipcRenderer.invoke(IPC.remoteClientFsRead, connectionId, path),- fsReadBinary: (connectionId, path) =>- ipcRenderer.invoke(IPC.remoteClientFsReadBinary, connectionId, path),- fsWrite: (connectionId, path, content) =>- ipcRenderer.invoke(IPC.remoteClientFsWrite, connectionId, path, content)- },relayHost: {start: () => ipcRenderer.invoke(IPC.relayHostStart),stop: () => ipcRenderer.invoke(IPC.relayHostStop),diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 895ac6eb5..f27205930 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -250,27 +250,6 @@ export function buildStubApi(): Omit<reject: (_id: string) => {},setPhoneAccess: noop},- remoteClient: {- connect: U('remoteClient.connect'),- disconnect: U('remoteClient.disconnect'),- create: U('remoteClient.create'),- write: noop,- resize: noop,- kill: noop,- // Relay client mode is desktop-only (the whole `remoteClient` block is unsupported here), so- // there is no host session to hydrate from — '' is the same "nothing to seed" the local- // hydration degrades to, and it keeps TerminalNode's warm-attach path from rejecting.- onData: noopUnsub,- onExit: noopUnsub,- onClosed: noopUnsub,- onCanvasState: noopUnsub,- onSas: noopUnsub,- sendMutation: noop,- fsList: U('remoteClient.fsList'),- fsRead: U('remoteClient.fsRead'),- fsReadBinary: U('remoteClient.fsReadBinary'),- fsWrite: U('remoteClient.fsWrite')- },// New relay tunnel (Stage 4). Hosting/connecting a peer-to-peer relay is a desktop-only// (Electron) capability — the Server Edition is itself the remote host, reached over its own WS// bridge — so the entry points (`start`/`connect`) reject with E_UNSUPPORTED and the UI hidesdiff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 65a6f3072..626b7d8e0 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -1903,18 +1903,29 @@ export function Canvas() {[mountRemoteMirror])+ // Connect to a host from an already-collected pairing offer: open the relay socket, then run the+ // shared SAS-compare + mount flow. The SINGLE place `relayClient.connect` + `confirmAndMount` live,+ // so every entry (dock/palette prompt below, and the Settings/tab-menu dialogs via the+ // `nodeterm:open-remote-terminal` event) reuses it instead of re-implementing the SAS handshake.+ const connectOffer = useCallback(+ async (offer: string) => {+ try {+ const connectionId = await window.nodeTerminal.relayClient.connect(offer)+ confirmAndMount(connectionId, 'Remote host')+ } catch (err) {+ window.alert(`Could not connect: ${(err as Error).message}`)+ }+ },+ [confirmAndMount]+ )+// "New Remote Connection" entry point (dock / palette): paste a host's pairing offer, connect,// compare the SAS, confirm, and open the host as a project tab. This is the primary remote entry.const connectRemote = useCallback(async () => {const offer = (await promptDialog({ message: "Paste the host's pairing code:" }))?.trim()if (!offer) return- try {- const connectionId = await window.nodeTerminal.relayClient.connect(offer)- confirmAndMount(connectionId, 'Remote host')- } catch (err) {- window.alert(`Could not connect: ${(err as Error).message}`)- }- }, [confirmAndMount])+ void connectOffer(offer)+ }, [connectOffer])// Reconnect an offline (dropped) relay tab IN PLACE (Stage 4 Task 7). The relay offer is// single-use (main/remote/pairing.ts), so v1 has no silent/pinned reconnect — prompt for a FRESH@@ -2314,17 +2325,17 @@ export function Canvas() {return () => window.removeEventListener('keydown', onKey)}, [addTerminal, addAgentNode])- // 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.+ // "Connect to a host" from the Settings section / tab-menu dialog: they collect the pairing offer+ // and dispatch it here (a window event, so they need no Canvas reference), and this runs the SAME+ // relay connect → SAS compare → mount-as-tab flow the dock/palette entry uses (`connectOffer`).useEffect(() => {const onOpenRemote = (e: Event) => {- const connectionId = (e as CustomEvent<{ connectionId: string }>).detail?.connectionId- if (connectionId) mountRemoteMirror(connectionId)+ const offer = (e as CustomEvent<{ offer: string }>).detail?.offer?.trim()+ if (offer) void connectOffer(offer)}window.addEventListener('nodeterm:open-remote-terminal', onOpenRemote)return () => window.removeEventListener('nodeterm:open-remote-terminal', onOpenRemote)- }, [mountRemoteMirror])+ }, [connectOffer])/*** Move every node that was living in a worktree directory OFF that (now dead) path — back to thediff --git a/src/renderer/components/RemoteAccessDialog.tsx b/src/renderer/components/RemoteAccessDialog.tsxindex 6ad37ef11..5f51aec25 100644--- a/src/renderer/components/RemoteAccessDialog.tsx+++ b/src/renderer/components/RemoteAccessDialog.tsx@@ -2,19 +2,18 @@ import { useEffect, useState } from 'react'import { createPortal } from 'react-dom'import { useDialogStack } from './dialog-stack'import { useEntitlement } from '../state/entitlement'-import { useRemoteHosting } from '../state/remoteHosting'import { Button } from '@renderer/ui/Button'import { CopyButton } from '@renderer/ui/CopyButton'import { Input } from '@renderer/ui/Input'/*** Remote access dialog — a self-contained popup reachable from the project (tab) caret menu, so- * remote access isn't buried in Settings. Mirrors the Settings RemoteSection flow:+ * remote access isn't buried in Settings. Mirrors the Settings RemoteSection flow over the NEW+ * relay tunnel (`relayHost` / `relayClient`):* - Host "Allow remote access" (Pro): start → show the single-use pairing offer + copy/stop.* - Non-Pro: hosting is gated — show the upgrade popup (Upgrade → Stripe checkout).- * - Client "Connect to a host" (free): paste an offer → open the live mirror.- * It deliberately does NOT import RemoteSection (which the Settings redesign owns); the small- * remote IPC flow is duplicated here. A future refactor can hoist it into a shared hook.+ * - Client "Connect to a host" (free): paste an offer → Canvas runs the SAS-compare + open-tab flow.+ * It deliberately does NOT import RemoteSection (which the Settings redesign owns).*/export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.JSX.Element {const isPremium = useEntitlement((s) => s.isPremium)@@ -23,9 +22,6 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.const [hostBusy, setHostBusy] = useState(false)const [error, setError] = useState('')const [clientCode, setClientCode] = useState('')- const [connecting, setConnecting] = useState(false)- const [clientSas, setClientSas] = useState<string | null>(null)- const [connectedId, setConnectedId] = useState<string | null>(null)// Only the topmost modal answers a key (./dialog-stack) — the host approval ConfirmDialog opens// on top of THIS dialog, and its Escape must not also close the one underneath.@@ -42,49 +38,36 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.return () => window.removeEventListener('keydown', onKey)}, [isTop, onClose])+ // HOST side — the NEW relay tunnel (`relayHost`). `start()` returns the single-use pairing offer;+ // a connecting peer's approval + canvas sync are handled globally by Canvas (`relayHost.onPeerPending`+ // / `relayHost.confirm`, and the CorePlatform seq-stamped reflector).const startHosting = async () => {setError('')setHostBusy(true)try {- const { offer } = await window.nodeTerminal.remoteHost.start()+ const { offer } = await window.nodeTerminal.relayHost.start()setHostOffer(offer)- useRemoteHosting.getState().setHosting(true) // Canvas starts mirroring the canvas to main} catch (err) {setError((err as Error).message)setHostBusy(false)}}const stopHosting = async () => {- await window.nodeTerminal.remoteHost.stop()- useRemoteHosting.getState().setHosting(false)+ await window.nodeTerminal.relayHost.stop()setHostOffer('')setHostBusy(false)}- // Surface the channel SAS once the handshake completes, so the user can verify it matches the- // code the host shows before approving there. Keep the dialog open to display it.- useEffect(() => {- if (!connectedId) return- return window.nodeTerminal.remoteClient.onSas(connectedId, (sas) => setClientSas(sas))- }, [connectedId])-- const connect = async () => {+ // CLIENT side — hand the offer to Canvas, which runs the relay connect → SAS compare (window.confirm)+ // → open-tab flow (the same `connectOffer` the dock/palette entry uses). No `relayClient.connect`+ // here, so the SAS handshake lives in exactly one place.+ const connect = () => {const code = clientCode.trim()if (!code) return- setError('')- setConnecting(true)- try {- const connectionId = await window.nodeTerminal.remoteClient.connect(code)- window.dispatchEvent(- new CustomEvent('nodeterm:open-remote-terminal', { detail: { connectionId } })- )- // Don't close yet: show the verification code + "waiting for host approval" status. The- // mirror node already opened; the user can close this dialog once approved.- setConnectedId(connectionId)- } catch (err) {- setError((err as Error).message)- } finally {- setConnecting(false)- }+ setClientCode('')+ window.dispatchEvent(+ new CustomEvent('nodeterm:open-remote-terminal', { detail: { offer: code } })+ )+ onClose()}return createPortal(@@ -133,28 +116,17 @@ export function RemoteAccessDialog({ onClose }: { onClose: () => void }): React.)}<h4 className="remote-dialog__head4">Connect to a host</h4>- {connectedId ? (- <div className="remote-dialog__block">- <p className="remote-dialog__hint">- Connected — waiting for the host to approve. Verify this code matches the one shown on- the host:- </p>- <Input className="w-full" readOnly value={clientSas ?? 'establishing…'} />- <Button onClick={onClose}>Done</Button>- </div>- ) : (- <div className="remote-dialog__block">- <Input- className="w-full"- placeholder="paste the host's code"- value={clientCode}- onChange={(e) => setClientCode(e.target.value)}- />- <Button disabled={connecting || !clientCode.trim()} onClick={() => void connect()}>- {connecting ? 'Connecting…' : 'Connect'}- </Button>- </div>- )}+ <div className="remote-dialog__block">+ <Input+ className="w-full"+ placeholder="paste the host's code"+ value={clientCode}+ onChange={(e) => setClientCode(e.target.value)}+ />+ <Button disabled={!clientCode.trim()} onClick={connect}>+ Connect+ </Button>+ </div>{error ? <p className="remote-dialog__err">{error}</p> : null}</div>diff --git a/src/renderer/components/settings/sections/RemoteSection.tsx b/src/renderer/components/settings/sections/RemoteSection.tsxindex 73277c0d4..0e876a52d 100644--- a/src/renderer/components/settings/sections/RemoteSection.tsx+++ b/src/renderer/components/settings/sections/RemoteSection.tsx@@ -1,6 +1,5 @@import { useState } from 'react'import { useEntitlement } from '../../../state/entitlement'-import { useRemoteHosting } from '../../../state/remoteHosting'import { SettingsSection } from '../SettingsSection'import { SearchableRow } from '../SearchableRow'import { FieldRow } from '../FieldRow'@@ -30,41 +29,39 @@ export function RemoteSection({const [remoteError, setRemoteError] = useState('')const [clientCode, setClientCode] = useState('')const [connecting, setConnecting] = useState(false)+ // HOST side — the NEW relay tunnel (`relayHost`). `start()` returns the single-use pairing offer;+ // a connecting peer's approval + canvas sync are handled globally by Canvas (`relayHost.onPeerPending`+ // / `relayHost.confirm`, and the CorePlatform seq-stamped reflector — no old canvas-mirror flag).const startHosting = async () => {setRemoteError('')setHostBusy(true)try {- const { offer } = await window.nodeTerminal.remoteHost.start()+ const { offer } = await window.nodeTerminal.relayHost.start()setHostOffer(offer)- useRemoteHosting.getState().setHosting(true) // Canvas starts mirroring the canvas to main} catch (err) {setRemoteError((err as Error).message)setHostBusy(false)}}const stopHosting = async () => {- await window.nodeTerminal.remoteHost.stop()- useRemoteHosting.getState().setHosting(false)+ await window.nodeTerminal.relayHost.stop()setHostOffer('')setHostBusy(false)}- const connectToHost = async () => {+ // CLIENT side — hand the offer to Canvas, which runs the relay connect → SAS compare → open-tab+ // flow (the same `connectOffer` the dock/palette "New Remote Connection" uses). We deliberately do+ // NOT call `relayClient.connect` here, so the SAS handshake lives in exactly one place.+ const connectToHost = () => {const code = clientCode.trim()if (!code) returnsetRemoteError('')setConnecting(true)- try {- const connectionId = await window.nodeTerminal.remoteClient.connect(code)- setClientCode('')- window.dispatchEvent(- new CustomEvent('nodeterm:open-remote-terminal', { detail: { connectionId } })- )- onClose()- } catch (err) {- setRemoteError((err as Error).message)- } finally {- setConnecting(false)- }+ setClientCode('')+ window.dispatchEvent(+ new CustomEvent('nodeterm:open-remote-terminal', { detail: { offer: code } })+ )+ setConnecting(false)+ onClose()}return (<SettingsSectiondiff --git a/src/renderer/terminal/remote-fs.ts b/src/renderer/terminal/remote-fs.tsdeleted file mode 100644index 6fab9174e..000000000--- a/src/renderer/terminal/remote-fs.ts+++ /dev/null@@ -1,27 +0,0 @@-// Remote filesystem API (renderer).-//-// `remoteFs(connectionId)` returns an object satisfying the same `FsApi` contract as-// `window.nodeTerminal.fs`, but scoped to a remote connection: every call proxies onto the HOST's-// filesystem over the E2EE relay (renderer → `remoteClient.fs*` IPC → client-service `fs.*` RPC →-// host-service `fs.*` handler → shared fs-ops). Because the shape matches the local `FsApi`-// exactly, nodes (Editor/Diff/Explorer) can pick `remoteFs(connectionId)` instead of the local fs-// when they are rendered inside a remote session, with behaviour identical to local.--import type { FsApi } from '@shared/types'--/** Build an `FsApi` bound to a remote connection (proxies to the host's filesystem). */-export function remoteFs(connectionId: string): FsApi {- const client = window.nodeTerminal.remoteClient- return {- list: (dirPath) => client.fsList(connectionId, dirPath),- read: (filePath) => client.fsRead(connectionId, filePath),- readBinary: (filePath) => client.fsReadBinary(connectionId, filePath),- write: (filePath, content) => client.fsWrite(connectionId, filePath, content),- // mkdir/exists are not yet plumbed through the E2EE relay RPC (RemoteClientApi has no- // fsMkdir/fsExists). Until the host-service surface gains them, degrade gracefully: a relay- // Explorer reports "does not exist" and cannot create dirs, rather than throwing. See the- // fs.mkdir/exists task follow-up.- mkdir: () => Promise.resolve(false),- exists: () => Promise.resolve(false)- }-}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 62c4ba8be..fbb6f9f02 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -213,36 +213,10 @@ export const IPC = {// handshake — the open relay socket keeps full shell access — so this ALSO cuts the live session// (revocation.ts's whole point; see relay-host.ts's killRelayHostsByPeerKey).remoteRevokePeer: 'remote:revoke-peer',- // 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',- // 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',- // Remote filesystem: the client proxies the local `fs:*` shape onto the host over the relay.- remoteClientFsList: 'remote:client:fs-list',- remoteClientFsRead: 'remote:client:fs-read',- remoteClientFsReadBinary: 'remote:client:fs-read-binary',- remoteClientFsWrite: 'remote:client:fs-write',- // The channel SAS pushed main->renderer once the client handshake completes, so the client- // human can compare it with the code shown on the host before the host approves.- remoteClientSas: (connectionId: string) => `remote:client:sas:${connectionId}`,- // 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}`,- 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}`,// ── New E2EE relay tunnel (Stage 4) ─────────────────────────────────────────────────────────- // The successor to the legacy `remote:host:*` / `remote:client:*` dialect above. Both coexist- // during the migration (the phone still speaks the old channels until Task 10 deletes them), so+ // The successor to the legacy `remote:host:*` dialect above (the `remote:client:*` desktop-client+ // channels were deleted in Task 10; the desktop client is now the `relay:*` tunnel). The phone+ // still speaks `remote:host:*` until the iOS repo migrates (docs/ios-protocol-migration.md), so// these deliberately use a distinct `relay:*` namespace. A connected peer is a first-class// CorePlatform client: the client casts raw rpc.ts frames (JSON strings) at the host and receives// frames back, rather than a bespoke per-verb channel set.diff --git a/src/shared/types.ts b/src/shared/types.tsindex fd2787262..047e6c2c5 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -577,9 +577,8 @@ export interface SshProjectApi {/*** SSH-project Explorer/Editor filesystem API: the same `FsApi` contract scoped to a project,* proxied over the project's ControlMaster (renderer → `sshFs:*` IPC → main `SshFs`). The renderer- * `sshFs(projectId)` helper closes over `projectId` to expose a plain `FsApi`. Mirrors- * `RemoteClientApi.fs*` for relay connections; fails open ([]/''/false) when the project is not- * connected.+ * `sshFs(projectId)` helper closes over `projectId` to expose a plain `FsApi`. Fails open+ * ([]/''/false) when the project is not connected.*/export interface SshFsApi {list(projectId: string, path: string): Promise<DirEntry[]>@@ -1111,58 +1110,6 @@ export interface RemoteHostApi {setPhoneAccess(enabled: boolean): 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- /**- * 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- /**- * Listen for the channel SAS once the handshake completes, so the client human can compare it- * with the code shown on the host before the host approves. Returns an unsubscribe function.- */- onSas(connectionId: string, listener: (sas: string | null) => 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- /** List a directory on the host's filesystem (the `FsApi.list` shape over the relay). */- fsList(connectionId: string, path: string): Promise<DirEntry[]>- /** Read a host file's UTF-8 text (the `FsApi.read` shape over the relay). */- fsRead(connectionId: string, path: string): Promise<string>- /** Read a host file as base64 (the `FsApi.readBinary` shape over the relay). */- fsReadBinary(connectionId: string, path: string): Promise<string>- /** Write UTF-8 text to a host file (the `FsApi.write` shape over the relay). */- fsWrite(connectionId: string, path: string, content: string): Promise<boolean>-}-/*** Payload of `relayHost.onPeerPending`: a client has finished the E2EE handshake over the new* relay tunnel and is awaiting the host human's approval. `id` addresses this pending peer for@@ -1203,8 +1150,8 @@ export interface RelayHostApi {}/**- * CLIENT side of the new E2EE relay tunnel (Stage 4) — the successor to `RemoteClientApi`. The- * client exchanges raw rpc.ts frames (JSON strings) with the host over the encrypted tunnel rather+ * CLIENT side of the new E2EE relay tunnel (Stage 4) — the successor to the deleted legacy relay+ * client dialect. The client exchanges raw rpc.ts frames (JSON strings) with the host over the encrypted tunnel rather* than a per-verb channel set. Desktop-only (Electron); the Server Edition browser build degrades* every member to `E_UNSUPPORTED`/no-op.*/@@ -1308,7 +1255,6 @@ export interface NodeTerminalApi {claudeAccounts: ClaudeAccountsApitranscripts: TranscriptsApiremoteHost: RemoteHostApi- remoteClient: RemoteClientApirelayHost: RelayHostApirelayClient: RelayClientApihandoff: HandoffApi