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(relay): wire the interactive host-accept flow (initRelayHost)
enes16d9197d8b80
diff --git a/src/main/index.ts b/src/main/index.tsindex d2889593c..7e55cc09f 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -64,6 +64,7 @@ import {} from './remote/host-service'import { initStandingHost } from './remote/standing-host'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'@@ -1015,6 +1016,11 @@ app.whenReady().then(async () => {// after the user has connected an SSH project) always sees the live manager.initClaudeAccounts(() => sshProjectManager)initRemoteHost(win, ptyManager, listProjectsOutput)+ // NEW interactive relay host (Stage 4): a connecting peer desktop becomes a first-class+ // CorePlatform client of this desktop after mutual SAS approval. Runs BESIDE initRemoteHost (the+ // phone still uses the legacy flow). Inert until `relay:host:start` — a solo user pays nothing.+ // Revocation reaches its sessions via `killRelayHostsByPeerKey` (peerRevoker, above).+ initRelayHost(win, corePlatform, {})// Standing (phone) relay host: keep a host connection registered so a paired phone can reach// this Mac from anywhere. Honors settings.phoneAccessEnabled + the Pro gate internally.standingHost = initStandingHost(win, ptyManager, () => settingsStore.get(), listProjectsOutput)diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex f0ef69fe9..49c2460ec 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -493,7 +493,9 @@ interface PairTokenResponse {}// Mint a single-use pairing token from our API, proving entitlement with the stored token.-async function mintPairingToken(entitlement: string): Promise<PairTokenResponse> {+// Exported so the NEW interactive relay host (relay-host-service.ts) mints its offer token the same+// way (same `POST /v1/pair/token`, same entitlement proof) instead of duplicating the call.+export async function mintPairingToken(entitlement: string): Promise<PairTokenResponse> {const ctrl = new AbortController()const timer = setTimeout(() => ctrl.abort(), 8000)let res: Responsediff --git a/src/main/remote/relay-host-service.test.ts b/src/main/remote/relay-host-service.test.tsnew file mode 100644index 000000000..f7873c83e--- /dev/null+++ b/src/main/remote/relay-host-service.test.ts@@ -0,0 +1,321 @@+// Task 2 (docs/remote-sessions.md 4c): `initRelayHost` drives the reviewed `connectRelayHost`+// machinery from IPC — a real peer connecting fires the approval prompt, and ONLY after the human+// confirms does the peer become a live CorePlatform client.+//+// The reviewed trust machinery (connectRelayHost / createTrustGate / relay-socket) is exercised for+// REAL here; only the electron shell boundary and the relay WIRE (an in-process RelayTransport pair,+// the same fake relay-host.test.ts drives) are faked. The token mint + keypair + Pro gate are+// injected via `deps` so the test never touches the network or the OS keyring.+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'++const h: {+ handlers: Record<string, (...a: any[]) => unknown>+ sent: Array<{ channel: string; args: any[] }>+} = { handlers: {}, sent: [] }++vi.mock('electron', () => ({+ app: { getPath: () => '/tmp/ud', getVersion: () => '9.9.9', isPackaged: false },+ ipcMain: {+ handle: (ch: string, fn: (...a: any[]) => unknown) => {+ h.handlers[ch] = fn+ },+ on: (ch: string, fn: (...a: any[]) => void) => {+ h.handlers[ch] = fn+ }+ },+ webContents: { fromId: () => undefined },+ shell: { openExternal: vi.fn(async () => {}) }+}))++vi.mock('../main-window', () => ({+ sendToMain: (ch: string, ...args: any[]) => h.sent.push({ channel: ch, args }),+ mainWindowClientIds: () => [] as number[]+}))++import { emptyApprovedDevices, type ApprovedDevices } from './approved-devices-core'+let disk: ApprovedDevices = emptyApprovedDevices()+vi.mock('./approved-devices', () => ({+ loadApprovedDevices: async () => disk,+ saveApprovedDevices: async (s: ApprovedDevices) => {+ disk = s+ }+}))++import { initRelayHost } from './relay-host-service'+import { connectRelay, type RelayTransport } from './relay-socket'+import { createTrustGate, type TrustGate } from './relay-trust'+import { genKeyPair, publicKeyToB64 } from './e2ee'+import { decodeOffer } from './pairing'+import { electronPlatform, type ElectronPlatform } from '../platform-electron'+import { peerRegistry, unregisterPeerSink, wirePeerRegistry } from '../peer-registry'+import { presenceHub } from '../../core/presence/hub'+import { initCanvasSync } from '../../core/canvas-sync'+import { initPlatform, resetPlatformForTests } from '../../core/platform'+import { IPC } from '../../shared/ipc'++const decoder = new TextDecoder()++let platform: ElectronPlatform++/** A fake window that records what the main process pushes to the renderer. */+function fakeWin(): { isDestroyed: () => boolean; webContents: { send: (ch: string, ...a: any[]) => void } } {+ return {+ isDestroyed: () => false,+ webContents: { send: (ch: string, ...args: any[]) => h.sent.push({ channel: ch, args }) }+ }+}++/**+ * Wire an `initRelayHost` whose relay socket is an in-process transport pair, and return a peer that+ * can drive the handshake + trust confirm. The host transport is injected via `deps.transport`; the+ * token mint / keypair / Pro gate are injected so nothing hits the network.+ */+function wireHost(): {+ win: ReturnType<typeof fakeWin>+ hostKeys: ReturnType<typeof genKeyPair>+ peerKeyB64: string+ /** Complete the E2EE handshake from the peer side (creates the peer relay socket). */+ connectPeer: () => void+ /** The peer human presses Confirm over the ENCRYPTED tunnel. */+ peerConfirms: () => void+ /** The relay drops the socket under the host. */+ dropSocket: () => void+} {+ const hostKeys = genKeyPair()+ const peerKeys = genKeyPair()++ let hostOnMsg: ((d: unknown) => void) | null = null+ let peerOnMsg: ((d: unknown) => void) | null = null+ let hostOnClose: (() => void) | null = null+ let peerOnClose: (() => void) | null = null++ const hostT: RelayTransport = {+ bufferedAmount: 0,+ send: (d) => peerOnMsg?.(d),+ close: () => peerOnClose?.(),+ onMessage: (cb) => {+ hostOnMsg = cb+ },+ onClose: (cb) => {+ hostOnClose = cb+ }+ }+ const peerT: RelayTransport = {+ bufferedAmount: 0,+ send: (d) => hostOnMsg?.(d),+ close: () => hostOnClose?.(),+ onMessage: (cb) => {+ peerOnMsg = cb+ },+ onClose: (cb) => {+ peerOnClose = cb+ }+ }++ const win = fakeWin()+ initRelayHost(win as never, platform, {+ transport: hostT,+ loadKeys: async () => hostKeys,+ mintToken: async () => ({ pairingToken: 'tok-123' }),+ isPremium: () => true,+ relayAllowed: () => true,+ getEntitlement: () => 'ent-abc'+ })++ let peerGate: TrustGate | null = null+ let peerStore: ApprovedDevices = emptyApprovedDevices()++ const connectPeer = (): void => {+ const peerSocket = connectRelay({+ url: 'wss://relay.example',+ token: 'tok-123',+ role: 'client',+ ourKeys: peerKeys,+ theirPubB64: publicKeyToB64(hostKeys.publicKey),+ transport: peerT,+ onReady: () => {},+ onRpc: () => {},+ onFrame: () => {},+ onClose: () => {},+ onTunnel: (kind, payload) => {+ if (kind !== 'text') return+ const json = decoder.decode(payload)+ peerGate?.onTunnelText(json)+ }+ })+ peerGate = createTrustGate({+ peerKeyB64: peerSocket.peerPublicKeyB64()!,+ sessionId: 'peer-side',+ sas: () => peerSocket.sas(),+ sendConfirm: (json) => peerSocket.sendTunnelText(json),+ onOpen: () => {},+ load: async () => peerStore,+ save: async (s) => {+ peerStore = s+ }+ })+ }++ return {+ win,+ hostKeys,+ peerKeyB64: publicKeyToB64(peerKeys.publicKey),+ connectPeer,+ peerConfirms: () => peerGate?.confirmHere(),+ dropSocket: () => hostOnClose?.()+ }+}++/** Run `relay:host:start` and return its offer. */+async function start(): Promise<{ offer: string }> {+ return (await h.handlers[IPC.relayHostStart]({})) as { offer: string }+}++function pendingSent(): { id: string; sas: string | null; peerKeyB64: string } | undefined {+ return h.sent.filter((x) => x.channel === IPC.relayHostPeerPending).at(-1)?.args[0]+}++beforeEach(() => {+ h.handlers = {}+ h.sent = []+ disk = emptyApprovedDevices()+ platform = electronPlatform()+ initPlatform(platform)+ wirePeerRegistry({+ setFlow: () => {},+ captureForResync: async () => '',+ onPeerGone: () => {}+ })+ presenceHub.registerIpc()+ initCanvasSync()+})++afterEach(() => {+ for (const id of peerRegistry().ids()) unregisterPeerSink(id)+ for (const pe of presenceHub.peers()) presenceHub.leave(pe.clientId)+ resetPlatformForTests()+})++describe('initRelayHost — start()', () => {+ it('returns a decodable offer carrying the host key + minted token', async () => {+ wireHost()+ const { offer } = await start()+ const decoded = decodeOffer(offer)+ expect(decoded).toBeTruthy()+ expect(decoded!.pairingToken).toBe('tok-123')+ expect(decoded!.hostPublicKeyB64).toBeTruthy()+ })++ it('rejects when not entitled', async () => {+ const win = fakeWin()+ initRelayHost(win as never, platform, {+ isPremium: () => false,+ relayAllowed: () => true,+ getEntitlement: () => 'ent',+ loadKeys: async () => genKeyPair(),+ mintToken: async () => ({ pairingToken: 't' })+ })+ await expect(h.handlers[IPC.relayHostStart]({})).rejects.toThrow(/Pro/)+ })++ it('surfaces a locked peer key as a rejected start', async () => {+ const win = fakeWin()+ initRelayHost(win as never, platform, {+ isPremium: () => true,+ relayAllowed: () => true,+ getEntitlement: () => 'ent',+ loadKeys: async () => {+ throw Object.assign(new Error('locked'), { code: 'E_PEER_KEY_LOCKED' })+ },+ mintToken: async () => ({ pairingToken: 't' })+ })+ await expect(h.handlers[IPC.relayHostStart]({})).rejects.toThrow(/locked/)+ })+})++describe('initRelayHost — nothing is served before mutual approval', () => {+ it('a peer completing the handshake fires relayHostPeerPending with a non-null SAS but no client yet', async () => {+ const host = wireHost()+ await start()+ host.connectPeer()++ const pending = pendingSent()+ expect(pending).toBeTruthy()+ expect(pending!.sas).toMatch(/^\d{3} \d{3}$/)+ expect(pending!.peerKeyB64).toBe(host.peerKeyB64)+ // No client, no presence, no open before the human confirms.+ expect(peerRegistry().ids()).toEqual([])+ expect(presenceHub.peers()).toEqual([])+ expect(h.sent.some((x) => x.channel === IPC.relayHostOpen)).toBe(false)+ })++ it('ONE human confirming (the peer alone) is not enough', async () => {+ const host = wireHost()+ await start()+ host.connectPeer()+ host.peerConfirms() // only the remote human+ await new Promise((r) => setTimeout(r, 20))+ expect(peerRegistry().ids()).toEqual([])+ expect(h.sent.some((x) => x.channel === IPC.relayHostOpen)).toBe(false)+ })+})++describe('initRelayHost — confirm() opens the session', () => {+ it('both humans confirming admits the peer as a CorePlatform client + presence peer', async () => {+ const host = wireHost()+ await start()+ host.connectPeer()+ const id = pendingSent()!.id++ // This human confirms via IPC, the remote human over the tunnel.+ h.handlers[IPC.relayHostConfirm]({}, { id })+ host.peerConfirms()++ await vi.waitFor(() => expect(peerRegistry().ids().length).toBe(1))+ expect(presenceHub.peers().length).toBe(1)+ expect(presenceHub.peers()[0].kind).toBe('desktop')+ const open = h.sent.filter((x) => x.channel === IPC.relayHostOpen).at(-1)+ expect(open?.args[0]).toEqual({ id })+ })++ it('confirm() with an unknown id is a no-op (no throw)', async () => {+ wireHost()+ await start()+ expect(() => h.handlers[IPC.relayHostConfirm]({}, { id: 'nope' })).not.toThrow()+ expect(peerRegistry().ids()).toEqual([])+ })+})++describe('initRelayHost — teardown', () => {+ it('stop() tears the live peer down and notifies the renderer', async () => {+ const host = wireHost()+ await start()+ host.connectPeer()+ const id = pendingSent()!.id+ h.handlers[IPC.relayHostConfirm]({}, { id })+ host.peerConfirms()+ await vi.waitFor(() => expect(peerRegistry().ids().length).toBe(1))++ await h.handlers[IPC.relayHostStop]()++ expect(peerRegistry().ids()).toEqual([])+ expect(presenceHub.peers()).toEqual([])+ })++ it('a socket drop tears the peer down and fires relayHostClosed', async () => {+ const host = wireHost()+ await start()+ host.connectPeer()+ const id = pendingSent()!.id+ h.handlers[IPC.relayHostConfirm]({}, { id })+ host.peerConfirms()+ await vi.waitFor(() => expect(peerRegistry().ids().length).toBe(1))++ host.dropSocket()++ expect(peerRegistry().ids()).toEqual([])+ expect(presenceHub.peers()).toEqual([])+ const closed = h.sent.filter((x) => x.channel === IPC.relayHostClosed).at(-1)+ expect(closed?.args[0]).toEqual({ id })+ })+})diff --git a/src/main/remote/relay-host-service.ts b/src/main/remote/relay-host-service.tsnew file mode 100644index 000000000..988f4b4a2--- /dev/null+++ b/src/main/remote/relay-host-service.ts@@ -0,0 +1,171 @@+// The interactive-host DRIVER (docs/remote-sessions.md 4c): give the reviewed `connectRelayHost`+// machinery an IPC surface. `initRelayHost` is the Stage-4 twin of the legacy `initRemoteHost`+// (host-service.ts) — it runs BESIDE it (the phone still uses the old flow; that is deleted with the+// dialect in Task 10). It shares the same offer format and pairing-token mint, but everything a+// bridged peer does afterwards flows through `connectRelayHost` (→ `platform.dispatch`/`cast`), not+// the legacy phone RPC vocabulary.+//+// SECURITY — nothing is served before MUTUAL approval. This file only FORWARDS the reviewed gate:+// - `onPeerPending` (the E2EE handshake completed, the SAS is known) → send `relay:host:peer-pending`+// to the renderer and WAIT. The peer is NOT a client yet: connectRelayHost registers no sink and+// joins no presence until its trust gate's `onOpen` fires (BOTH humans confirmed the same SAS).+// - the human's `relay:host:confirm` → `session.confirm()` (the ONLY local-confirm call site).+// - `onOpen` (mutual) → `relay:host:open`; `onClose` (socket gone) → `relay:host:closed`.+// This module never dispatches peer traffic, never registers a sink, never touches a handler — it+// cannot serve a peer early even by accident, because it holds none of the machinery that serves.+//+// REVOCATION reaches sessions started here for free: `connectRelayHost` adds every session to its own+// module-level `live` set, and index.ts's revoker calls `killRelayHostsByPeerKey` (relay-host.ts)+// against THAT set — independent of the bookkeeping below.+import { randomUUID } from 'crypto'+import { ipcMain, type BrowserWindow } from 'electron'+import { IPC } from '../../shared/ipc'+import type { ElectronPlatform } from '../platform-electron'+import { connectRelayHost, type RelayHostSession } from './relay-host'+import type { RelayTransport } from './relay-socket'+import { publicKeyToB64, type KeyPair } from './e2ee'+import { encodeOffer } from './pairing'+import { loadOrCreatePeerKeyPair } from './peer-identity'+import { isPremium as licenseIsPremium, getStoredEntitlement } from '../../core/license'+import { RELAY_URL, relayAllowed as hostRelayAllowed, mintPairingToken } from './host-service'++/** Injectable seams — production defaults hit the real license gate / API / OS keyring; tests pass+ * an in-process transport, a fake mint, and a fixed keypair so nothing touches the network. */+export interface RelayHostDeps {+ /** Relay wss URL (defaults to RELAY_URL). */+ url?: string+ /** TEST ONLY: an in-process RelayTransport forwarded into `connectRelayHost`. */+ transport?: RelayTransport+ /** The long-lived peer identity this desktop presents (defaults to loadOrCreatePeerKeyPair). */+ loadKeys?: () => Promise<KeyPair>+ /** Mint the single-use pairing token (defaults to the shared `mintPairingToken`). */+ mintToken?: (entitlement: string) => Promise<{ pairingToken: string }>+ isPremium?: () => boolean+ relayAllowed?: () => boolean+ getEntitlement?: () => string | null+ /** TEST ONLY: override the wire-up (defaults to `connectRelayHost`). */+ connect?: typeof connectRelayHost+}++export interface RelayHost {+ /** Tear down the current listener / bridged peer (app quit). Idempotent. */+ stop(): void+}++/**+ * Wire the interactive relay-host IPC. `relay:host:start` gates on Pro, mints a pairing token,+ * opens a relay host listener via `connectRelayHost`, and returns the offer to hand to a peer.+ * `relay:host:confirm` approves the pending peer; `relay:host:stop` tears the listener down.+ */+export function initRelayHost(+ win: BrowserWindow,+ platform: ElectronPlatform,+ deps: RelayHostDeps = {}+): RelayHost {+ const url = deps.url ?? RELAY_URL+ const connect = deps.connect ?? connectRelayHost+ const loadKeys = deps.loadKeys ?? loadOrCreatePeerKeyPair+ const mintToken = deps.mintToken ?? mintPairingToken+ const isPremium = deps.isPremium ?? licenseIsPremium+ const relayAllowed = deps.relayAllowed ?? hostRelayAllowed+ const getEntitlement = deps.getEntitlement ?? getStoredEntitlement++ // Renderer-facing token → the pending/live session it names. Populated once the peer is pending+ // (its SAS is known); the confirm/close paths resolve the session through it so a stray IPC event+ // can only ever act on the session it addresses. Mirrors initRemoteHost's `pendingApprovalId`.+ const byId = new Map<string, RelayHostSession>()+ // The current listener. A fresh `start()` supersedes it (like initRemoteHost's single `session`),+ // and `stop()` closes it — both idempotent via `RelayHostSession.close()`.+ let current: RelayHostSession | null = null++ function send(channel: string, ...args: unknown[]): void {+ if (!win.isDestroyed()) win.webContents.send(channel, ...args)+ }++ function forget(session: RelayHostSession): void {+ for (const [id, s] of byId) if (s === session) byId.delete(id)+ }++ ipcMain.handle(IPC.relayHostStart, async (): Promise<{ offer: 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 entitlement = getEntitlement()+ if (!entitlement) {+ throw new Error('No entitlement found — please re-activate nodeterm Pro.')+ }++ // Supersede any existing listener before opening a fresh one (single-listener, like the legacy+ // interactive host). close() is idempotent, so an already-dropped one is a no-op.+ current?.close()+ current = null++ // A locked keyring surfaces here as a rejected start() (PeerKeyLockedError / E_PEER_KEY_LOCKED):+ // the identity on disk is intact and must not be rotated — the renderer tells the human to unlock.+ const keys = await loadKeys()+ const { pairingToken } = await mintToken(entitlement)++ // The renderer token for THIS listener's eventual peer. Minted when the peer becomes pending, so+ // onOpen/onClose reference the same id the peer-pending event carried.+ let rendererId: string | null = null++ const session = connect({+ url,+ token: pairingToken,+ ourKeys: keys,+ platform,+ transport: deps.transport,+ // The SAS is known — ask the human to compare it. NOTHING is served yet.+ onPeerPending: (s) => {+ rendererId = randomUUID()+ byId.set(rendererId, s)+ send(IPC.relayHostPeerPending, {+ id: rendererId,+ sas: s.sas(),+ peerKeyB64: s.peerKeyB64() ?? ''+ })+ },+ // Both humans confirmed: the peer is a live CorePlatform client now.+ onOpen: () => {+ if (rendererId) send(IPC.relayHostOpen, { id: rendererId })+ },+ // The relay socket dropped (the peer is already torn down when this fires).+ onClose: () => {+ forget(session)+ if (current === session) current = null+ if (rendererId) send(IPC.relayHostClosed, { id: rendererId })+ }+ })+ current = session++ return {+ offer: encodeOffer({+ relayEndpoint: url,+ pairingToken,+ hostPublicKeyB64: publicKeyToB64(keys.publicKey)+ })+ }+ })++ // The human compared the SAS and pressed Confirm → advance the trust gate for THAT peer. Only the+ // session named by the id is touched; an unknown id (stale event) is a no-op.+ ipcMain.on(IPC.relayHostConfirm, (_e, msg: { id?: string } = {}) => {+ const session = msg?.id ? byId.get(msg.id) : undefined+ session?.confirm()+ })++ const stop = (): void => {+ current?.close()+ current = null+ byId.clear()+ }++ ipcMain.handle(IPC.relayHostStop, () => {+ stop()+ })++ return { stop }+}