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): a bridged peer is a CorePlatform client (sink + presence + dispatch)
enes749215366db5
diff --git a/src/main/index.ts b/src/main/index.tsindex c6308405a..3c0332ce0 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -63,6 +63,9 @@ import {RELAY_URL} from './remote/host-service'import { initStandingHost } from './remote/standing-host'+import { killRelayHostsByPeerKey } from './remote/relay-host'+import { createRevoker } from './remote/revocation'+import { loadApprovedDevices, saveApprovedDevices } from './remote/approved-devices'import { initRemoteClient } from './remote/client-service'import { initSshProject } from './remote-ssh/ssh-project'import { setGitRemoteResolver, type GitRemoteRef } from '../core/remote-ssh/remote-git'@@ -516,6 +519,21 @@ app.whenReady().then(async () => {ipcMain.handle(IPC.pairingListDevices, () => pairingService.listDevices())ipcMain.handle(IPC.pairingRevokeDevice, (_e, id: string) => pairingService.revokeDevice(id))+ // Revoking a bridged PEER must CUT THE LIVE SESSION, not just unpin it (revocation.ts): unpinning+ // refuses only the NEXT handshake, while the open relay socket keeps full shell access — "the+ // person I just removed is still sitting in my terminal, typing". `killByPeerKey` closes every+ // live session with that key, and each close runs the peer teardown (presence leave →+ // PtyManager.dropClient → sink prune). Host-security control plane, so it stays on raw ipcMain:+ // a remote peer must never be able to revoke anyone.+ const peerRevoker = createRevoker({+ load: loadApprovedDevices,+ save: saveApprovedDevices,+ onRevoke: (peerKeyB64) => killRelayHostsByPeerKey(peerKeyB64)+ })+ ipcMain.handle(IPC.remoteRevokePeer, (_e, peerKeyB64: string) =>+ peerRevoker.revoke(String(peerKeyB64))+ )+ipcMain.on(IPC.shellReveal, (_e, p: string) => {if (p) shell.showItemInFolder(p)})diff --git a/src/main/remote/relay-host.test.ts b/src/main/remote/relay-host.test.tsnew file mode 100644index 000000000..9fc8fa755--- /dev/null+++ b/src/main/remote/relay-host.test.ts@@ -0,0 +1,436 @@+// The merge gate for Stage 4c Task 5 (docs/remote-sessions.md): a bridged relay peer is a+// FIRST-CLASS CorePlatform client of this desktop's core.+//+// Nothing is faked here except the electron shell boundary (electron + ./main-window, mocked exactly+// as platform-electron.test.ts / peer-integration.test.ts do) and the relay WIRE (an in-process+// RelayTransport pair — the same fake relay-trust.test.ts drives). The E2EE handshake, the tunnel,+// the trust gate, electronPlatform, the peer registry (with the real Stage-2 UiSinkRegistry+// backpressure), the presence hub and the canvas reflector are all the REAL, wired objects.+//+// OBLIGATION 2 (the merge gate, first test below): the peer sink's bufferedAmount() must report the+// RELAY SOCKET's real buffered bytes. Stage 2's per-client backpressure and the 8 MB WS_DROP_WATER+// drop-and-redraw ceiling key on that ONE number. A sink that returns a constant 0 passes every+// other test in this file and silently disables the ceiling: a slow peer then queues pty output+// without bound, nothing pauses the pty or drops its backlog, and the HOST'S MEMORY GROWS UNTIL THE+// PROCESS DIES.+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'++const h: {+ handlers: Record<string, (...a: any[]) => unknown>+ sent: Array<{ id?: number; channel: string; args: any[] }>+ clientIds: number[]+} = { handlers: {}, sent: [], clientIds: [] }++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: (id: number) =>+ id === 1+ ? {+ isDestroyed: () => false,+ send: (ch: string, ...args: any[]) => h.sent.push({ id, channel: ch, args })+ }+ : undefined+ },+ shell: { openExternal: vi.fn(async () => {}) }+}))++vi.mock('../main-window', () => ({+ sendToMain: (ch: string, ...args: any[]) => h.sent.push({ channel: ch, args }),+ mainWindowClientIds: () => h.clientIds+}))++// The on-disk pin store, in memory (relay-trust's default load/save path).+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 { connectRelayHost, killRelayHostsByPeerKey, type RelayHostSession } from './relay-host'+import { connectRelay, type RelayTransport } from './relay-socket'+import { createTrustGate, type TrustGate } from './relay-trust'+import { genKeyPair, publicKeyToB64 } from './e2ee'+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'+import { decodePtyData, E_UNAUTHORIZED } from '../../shared/rpc'++const decoder = new TextDecoder()++/** Everything the boot wiring feeds the registry (index.ts wires the real PtyManager here). */+let flow: Array<{ id: number; sid: string; resume: boolean; owner: string }> = []+let gone: number[] = []+let capture = 'CURRENT SCREEN'+let platform: ElectronPlatform++/**+ * A host session bridged to a REAL peer relay socket over an in-process transport pair. `buffered`+ * is the host transport's ws.bufferedAmount — the number the sink must surface.+ */+function openHostAgainstFakeRelay(opts?: { bufferedAmount?: () => number }): {+ session: RelayHostSession+ peerKeyB64: string+ textFrames: string[]+ binaryFrames: Uint8Array[]+ resyncs: string[]+ pending: RelayHostSession[]+ opens: RelayHostSession[]+ closes: () => number+ peerSendsTunnelText: (json: string) => void+ /** The relay drops the socket under the host (what a vanished peer looks like). */+ dropSocket: () => void+ /** Both humans press Confirm; resolves once the peer is a platform client. */+ openMutually: () => Promise<void>+} {+ const hostKeys = genKeyPair()+ const peerKeys = genKeyPair()+ const bufferedAmount = opts?.bufferedAmount ?? ((): number => 0)++ 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 = {+ get bufferedAmount() {+ return bufferedAmount()+ },+ 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 pending: RelayHostSession[] = []+ const opens: RelayHostSession[] = []+ let closes = 0++ // The host FIRST: it waits passively for the peer's e2ee_hello.+ const session = connectRelayHost({+ url: 'wss://relay.example',+ token: 'tok',+ ourKeys: hostKeys,+ platform,+ transport: hostT,+ onPeerPending: (s) => pending.push(s),+ onOpen: (s) => opens.push(s),+ onClose: () => {+ closes+++ }+ })++ const textFrames: string[] = []+ const binaryFrames: Uint8Array[] = []+ const resyncs: string[] = []+ let peerGate: TrustGate | null = null+ let peerStore: ApprovedDevices = emptyApprovedDevices()++ const peerSocket = connectRelay({+ url: 'wss://relay.example',+ token: 'tok',+ role: 'client',+ ourKeys: peerKeys,+ theirPubB64: publicKeyToB64(hostKeys.publicKey),+ transport: peerT,+ onReady: () => {},+ onRpc: () => {},+ onFrame: () => {},+ onClose: () => {},+ onTunnel: (kind, payload) => {+ if (kind === 'binary') {+ binaryFrames.push(payload)+ return+ }+ const json = decoder.decode(payload)+ if (peerGate?.onTunnelText(json)) return // the host's own trust confirm+ textFrames.push(json)+ const m = JSON.parse(json)+ if (m.t === 'ev' && String(m.channel).startsWith('pty:resync:')) resyncs.push(String(m.args[0]))+ }+ })++ 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 {+ session,+ peerKeyB64: publicKeyToB64(peerKeys.publicKey),+ textFrames,+ binaryFrames,+ resyncs,+ pending,+ opens,+ closes: () => closes,+ peerSendsTunnelText: (json) => {+ peerSocket.sendTunnelText(json)+ },+ dropSocket: () => hostOnClose?.(),+ openMutually: async () => {+ session.confirm() // this human+ peerGate!.confirmHere() // the other human, over the ENCRYPTED tunnel+ await vi.waitFor(() => expect(session.clientId()).not.toBeNull())+ }+ }+}++beforeEach(() => {+ h.handlers = {}+ h.sent = []+ h.clientIds = [1] // the main window (a webContents client)+ disk = emptyApprovedDevices()+ flow = []+ gone = []+ capture = 'CURRENT SCREEN'+ platform = electronPlatform()+ initPlatform(platform)+ // The BOOT wiring (src/main/index.ts:120) — wired once, with the real PtyManager in production.+ wirePeerRegistry({+ setFlow: (id, sid, resume, owner) => flow.push({ id, sid, resume, owner }),+ captureForResync: async () => capture,+ onPeerGone: (id) => gone.push(id)+ })+ presenceHub.registerIpc()+ initCanvasSync()+})++afterEach(() => {+ for (const id of peerRegistry().ids()) unregisterPeerSink(id)+ for (const pe of presenceHub.peers()) presenceHub.leave(pe.clientId)+ resetPlatformForTests()+})++describe('relay host — obligation 2: the sink reports the relay socket’s REAL buffered bytes', () => {+ it('a slow peer trips the 8 MB ceiling and is dropped-and-redrawn, stalling neither a fast peer nor the desktop window', async () => {+ const slowBytes = { n: 0 }+ const slow = openHostAgainstFakeRelay({ bufferedAmount: () => slowBytes.n })+ await slow.openMutually()+ const fast = openHostAgainstFakeRelay() // a healthy link: nothing ever queues+ await fast.openMutually()++ const slowId = slow.session.clientId()!+ const fastId = fast.session.clientId()!++ // 1. pty output reaches the peer as a BINARY rpc.ts frame, over the E2EE tunnel.+ platform.sendTo(slowId, IPC.ptyData('s1'), 'hello')+ expect(decodePtyData(slow.binaryFrames[0])).toEqual({ sessionId: 's1', data: 'hello' })++ // 2. Past WS_DROP_WATER (8 MB) the chunk is DROPPED — bounded memory, not an unbounded backlog.+ // This can ONLY happen if the sink surfaced the socket's real buffered bytes.+ slowBytes.n = 9_000_000+ platform.sendTo(slowId, IPC.ptyData('s1'), 'flood')+ expect(slow.binaryFrames).toHaveLength(1)++ // 3. The drowning peer stalls nobody: the fast peer and the desktop's own window keep streaming,+ // and the SHARED pty is never paused for the dropped peer.+ platform.sendTo(fastId, IPC.ptyData('s1'), 'chunk')+ platform.sendTo(1, IPC.ptyData('s1'), 'chunk')+ expect(fast.binaryFrames).toHaveLength(1)+ expect(decodePtyData(fast.binaryFrames[0])).toEqual({ sessionId: 's1', data: 'chunk' })+ expect(h.sent.filter((x) => x.id === 1 && x.channel === IPC.ptyData('s1'))).toHaveLength(1)+ expect(flow).toEqual([])++ // 4. The socket drains → the peer is redrawn from tmux exactly once (current screen, not a+ // replay of the 8 MB it missed).+ slowBytes.n = 1_000+ await vi.waitFor(() => expect(slow.resyncs).toEqual(['CURRENT SCREEN']))+ expect(fast.binaryFrames).toHaveLength(1) // untouched throughout+ })++ it('pauses the shared pty at the high-water mark and resumes below low, under the socket owner', async () => {+ const bytes = { n: 0 }+ const s = openHostAgainstFakeRelay({ bufferedAmount: () => bytes.n })+ await s.openMutually()+ const id = s.session.clientId()!++ bytes.n = 1_500_000 // above WS_HIGH_WATER (1 MB), below the drop ceiling+ platform.sendTo(id, IPC.ptyData('s1'), 'chunk')+ expect(flow).toEqual([{ id, sid: 's1', resume: false, owner: 'socket' }])++ bytes.n = 100_000 // drained below WS_LOW_WATER+ platform.sendTo(id, IPC.ptyData('s1'), 'chunk')+ expect(flow).toEqual([+ { id, sid: 's1', resume: false, owner: 'socket' },+ { id, sid: 's1', resume: true, owner: 'socket' }+ ])+ })+})++describe('relay host — presence, canvas and RPC reach a bridged peer', () => {+ it('an open peer joins presence and receives presence:sync + a seq-stamped canvas:mut', async () => {+ presenceHub.join(1, 'desktop') // the desktop's own window+ const s = openHostAgainstFakeRelay()+ await s.openMutually()+ const id = s.session.clientId()!++ const frames = s.textFrames.map((j) => JSON.parse(j))+ const sync = frames.find((m) => m.channel === IPC.presenceSync)+ expect(sync).toBeTruthy()+ expect(sync.args[0].some((pe: any) => pe.clientId === 1)).toBe(true) // not blind: it sees the host+ // A peer desktop is a 'desktop' peer, and the host sees it join.+ expect(presenceHub.peers().find((pe) => pe.clientId === id)?.kind).toBe('desktop')++ // The canvas reflector fans a host-side mutation out to the peer, seq-stamped.+ s.textFrames.length = 0+ h.handlers[IPC.canvasMut](+ { sender: { id: 1 } },+ 'proj',+ { op: 'upsert', node: { id: 'n1', position: { x: 0, y: 0 } }, seq: 999 }+ )+ const mut = s.textFrames.map((j) => JSON.parse(j)).find((m) => m.channel === IPC.canvasMut)+ expect(mut).toBeTruthy()+ expect(mut.args[1].seq).toBe(1)+ })++ it('a peer RPC reaches the core and its response goes back over the tunnel', async () => {+ platform.handle('fs:list', async (dir: string) => [`${dir}/a.ts`])+ const s = openHostAgainstFakeRelay()+ await s.openMutually()++ s.peerSendsTunnelText(JSON.stringify({ t: 'req', id: 1, method: 'fs:list', args: ['/w'] }))+ await vi.waitFor(() =>+ expect(JSON.parse(s.textFrames.at(-1)!)).toMatchObject({+ t: 'res',+ id: 1,+ ok: true,+ result: ['/w/a.ts']+ })+ )+ })++ it('a peer CAST is attributed to the peer clientId', async () => {+ const casts: Array<[number, string]> = []+ platform.onWithSender('pty:write', (clientId: number, data: string) => casts.push([clientId, data]))+ const s = openHostAgainstFakeRelay()+ await s.openMutually()+ const id = s.session.clientId()!++ s.peerSendsTunnelText(JSON.stringify({ t: 'cast', method: 'pty:write', args: ['ls\r'] }))+ await vi.waitFor(() => expect(casts).toEqual([[id, 'ls\r']]))+ })+})++describe('relay host — nothing is served before mutual approval', () => {+ it('a peer RPC BEFORE mutual approval is refused (no dispatch, no sink, no presence)', async () => {+ let created = 0+ platform.handle('pty:create', async () => {+ created+++ return { id: 'x' }+ })+ const s = openHostAgainstFakeRelay() // E2EE is up, approval is NOT given+ expect(s.pending).toHaveLength(1) // the SAS is known: ask the human+ expect(s.session.sas()).toMatch(/^\d{3} \d{3}$/)++ s.peerSendsTunnelText(+ JSON.stringify({ t: 'req', id: 1, method: 'pty:create', args: [{ cols: 80, rows: 24 }] })+ )+ await new Promise((r) => setTimeout(r, 20))++ // Answered (an unanswered request would hang the peer's await) but REFUSED.+ expect(JSON.parse(s.textFrames.at(-1)!)).toMatchObject({+ t: 'res',+ id: 1,+ ok: false,+ error: { code: E_UNAUTHORIZED }+ })+ expect(created).toBe(0)+ expect(s.session.clientId()).toBeNull()+ expect(peerRegistry().ids()).toEqual([])+ expect(presenceHub.peers()).toEqual([])+ expect(s.opens).toEqual([])+ })++ it('ONE human confirming is not enough — the peer is still not a client', async () => {+ const s = openHostAgainstFakeRelay()+ s.session.confirm() // only this side+ await new Promise((r) => setTimeout(r, 20))+ expect(s.session.clientId()).toBeNull()+ expect(peerRegistry().ids()).toEqual([])+ })+})++describe('relay host — teardown mirrors src/server/ws.ts', () => {+ it('a socket close runs the FULL teardown exactly once (leave + dropClient + prune)', async () => {+ const s = openHostAgainstFakeRelay()+ await s.openMutually()+ const id = s.session.clientId()!+ expect(peerRegistry().ids()).toContain(id)++ s.dropSocket()++ expect(presenceHub.peers().some((pe) => pe.clientId === id)).toBe(false) // 1. no ghost peer+ expect(gone).toEqual([id]) // 2. PtyManager.dropClient+ expect(peerRegistry().ids()).not.toContain(id) // 3. sink + backpressure pruned+ expect(s.session.clientId()).toBeNull()+ expect(s.closes()).toBe(1)++ // Idempotent: an explicit close() after the socket already went does not tear down twice.+ s.session.close()+ expect(gone).toEqual([id])+ })++ it('close() tears the peer down and is idempotent', async () => {+ const s = openHostAgainstFakeRelay()+ await s.openMutually()+ const id = s.session.clientId()!++ s.session.close()+ s.session.close()++ expect(gone).toEqual([id])+ expect(peerRegistry().ids()).toEqual([])+ expect(presenceHub.peers().some((pe) => pe.clientId === id)).toBe(false)+ })++ it('revoking a peer key CUTS the live session (not just the pin)', async () => {+ const s = openHostAgainstFakeRelay()+ await s.openMutually()+ const id = s.session.clientId()!++ killRelayHostsByPeerKey(s.peerKeyB64)++ expect(peerRegistry().ids()).not.toContain(id)+ expect(gone).toEqual([id])+ expect(presenceHub.peers().some((pe) => pe.clientId === id)).toBe(false)+ // A stranger's key cuts nothing.+ killRelayHostsByPeerKey('some-other-key')+ })+})diff --git a/src/main/remote/relay-host.ts b/src/main/remote/relay-host.tsnew file mode 100644index 000000000..a169e1600--- /dev/null+++ b/src/main/remote/relay-host.ts@@ -0,0 +1,195 @@+// The JOIN POINT on the host (docs/remote-sessions.md 4c): once two humans have mutually approved+// each other, the bridged peer becomes a FIRST-CLASS CorePlatform client of this desktop's core.+//+// There is very little code here on purpose. 4b already made `electronPlatform` multi-client (a+// client is a webContents OR a UiSink in the peer registry), and Stages 1-3 wrote presence, the+// canvas reflector and terminal co-attach against CorePlatform. So the whole of "a remote desktop+// opens as a project tab" reduces to: mint one ClientId, register one sink, join presence, and route+// the encrypted tunnel into `platform.dispatch` / `platform.cast`. Everything else just works+// (src/main/peer-integration.test.ts proved it against a fake sink; this module supplies the socket).+//+// It is the electron-side twin of `src/server/ws.ts`, and it deliberately mirrors that file's shape:+// attach the sink, join the hub, req → dispatch → respond, cast → cast, and on close run the ONE+// teardown (leave → dropClient → prune). Divergence between the two remote surfaces is a bug.+//+// SECURITY — nothing is served before MUTUAL approval. The peer is registered (and therefore able to+// reach any channel the shell registered on the platform) only from the trust gate's `onOpen`, i.e.+// after BOTH humans compared the same SAS and pressed Confirm. The E2EE handshake completing+// (`onReady`) proves only that SOMEONE holds the pairing token — a pre-approval request is answered+// with E_UNAUTHORIZED and never touches a handler. A pairing grants shell access; the SAS is the+// only thing between a relay MITM and that shell.+//+// SCOPE: this is the DESKTOP-peer vocabulary (the invited peer is fully trusted, as the invite copy+// states). The standing PHONE host keeps its existing legacy vocabulary in `host-service.ts` — with+// its deny-by-default fs jail — and is deliberately NOT routed through this dispatch path.+import { connectRelay, type RelayTransport } from './relay-socket'+import { createTrustGate, type TrustGate } from './relay-trust'+import type { KeyPair } from './e2ee'+import type { ElectronPlatform } from '../platform-electron'+import { registerPeerSink, unregisterPeerSink } from '../peer-registry'+import { allocateRelayClientId, presenceHub } from '../../core/presence/hub'+import { E_UNAUTHORIZED, parseRpcMessage } from '../../shared/rpc'++export interface RelayHostSession {+ /** The peer's presence/platform ClientId once it is open, else null. */+ clientId(): number | null+ /** The 6-digit SAS both humans compare, or null before the key is derived. */+ sas(): string | null+ /** The peer's stable box public key (base64), or null before the handshake learned it. */+ peerKeyB64(): string | null+ /** This human confirmed the SAS (from the approve dialog). */+ confirm(): void+ /** Tear down: unregister the sink (leave + dropClient + prune), close the socket. Idempotent. */+ close(): void+}++export interface ConnectRelayHostOptions {+ url: string+ token: string+ ourKeys: KeyPair+ platform: ElectronPlatform+ /** TEST ONLY: an in-process RelayTransport. Production opens a real ws (relay-socket.ts). */+ transport?: RelayTransport+ /** The SAS is known — ask the human to compare it. */+ onPeerPending(session: RelayHostSession): void+ /** Mutually approved: the peer is a CorePlatform client of this core now. */+ onOpen(session: RelayHostSession): void+ /** The relay socket dropped (the peer is already torn down when this fires). */+ onClose(): void+}++/** Live bridged peers, for revocation: unpinning a key refuses the NEXT handshake, but the OPEN+ * socket keeps full shell access until it is cut (see revocation.ts). */+const live = new Set<RelayHostSession>()++/** Cut every live session with this peer key. The revoker's `onRevoke` (src/main/index.ts). */+export function killRelayHostsByPeerKey(peerKeyB64: string): void {+ for (const session of [...live]) {+ if (session.peerKeyB64() === peerKeyB64) session.close()+ }+}++export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSession {+ let clientId: number | null = null+ let gate: TrustGate | null = null+ let closed = false++ /** The ONE teardown, mirroring src/server/ws.ts's close path exactly: `unregisterPeerSink` IS the+ * three steps (presenceHub.leave → onPeerGone → PtyManager.dropClient → registry prune). Do NOT+ * re-implement them here, and do NOT call `wirePeerRegistry` — it is wired once at boot. */+ const detach = (): void => {+ if (clientId === null) return+ unregisterPeerSink(clientId)+ clientId = null+ }++ const session: RelayHostSession = {+ clientId: () => clientId,+ sas: () => gate?.sas() ?? null,+ peerKeyB64: () => gate?.peerKeyB64() ?? null,+ confirm: () => gate?.confirmHere(),+ close() {+ if (closed) return+ closed = true+ live.delete(session)+ detach()+ socket.close()+ }+ }++ /** Both humans confirmed: the peer joins this core as a client. */+ const open = (): void => {+ if (closed || clientId !== null) return+ const id = allocateRelayClientId()+ registerPeerSink(id, {+ // A DEAD socket must THROW (the registry evicts a sink after 2 consecutive throws and runs the+ // full teardown), and a healthy one must NOT (two throws in a row would kick a live peer out).+ // sendTunnel* returns false only when the channel is gone — turn exactly that into a throw.+ sendText: (json) => {+ if (!socket.sendTunnelText(json)) throw new Error('relay socket is not connected')+ },+ sendBinary: (buf) => {+ if (!socket.sendTunnelBinary(buf)) throw new Error('relay socket is not connected')+ },+ // OBLIGATION 2. The number Stage 2's per-client backpressure AND the 8 MB WS_DROP_WATER+ // drop-and-redraw ceiling key on (src/core/ui-sink-registry.ts). `bufferedAmount` is OPTIONAL+ // on UiSink and defaults to 0, so a sink that omits it — or stubs it — typechecks, passes every+ // test, and silently disables the ceiling: a slow peer then queues pty output without bound,+ // nothing pauses the pty or drops its backlog, and the HOST'S MEMORY GROWS UNTIL THE PROCESS+ // DIES. RelaySocket.bufferedAmount() is honest (ws.bufferedAmount + the pre-open queue).+ // Never make this a constant.+ bufferedAmount: () => socket.bufferedAmount()+ })+ // Join AFTER registering the sink, so the hub's `presence:sync` sendTo lands on a live sink (the+ // order src/server/ws.ts uses). A peer desktop is a 'desktop' peer, not a 'phone'.+ presenceHub.join(id, 'desktop')+ clientId = id+ opts.onOpen(session)+ }++ const socket = connectRelay({+ url: opts.url,+ token: opts.token,+ role: 'host',+ ourKeys: opts.ourKeys,+ transport: opts.transport,+ onReady: () => {+ // E2EE is up. This proves only that SOMEONE holds the pairing token — NOT that the human at+ // the other end is who we think. Serve nothing yet: build the gate and ask for the SAS.+ const peerKey = socket.peerPublicKeyB64()+ if (!peerKey || gate) return+ gate = createTrustGate({+ peerKeyB64: peerKey,+ sessionId: `${peerKey}:${Date.now()}`, // obligation (b): ONE state per pairing attempt+ sas: () => socket.sas(),+ sendConfirm: (json) => socket.sendTunnelText(json),+ onOpen: open+ })+ live.add(session)+ opts.onPeerPending(session)+ },+ // The legacy phone dialect is not served here: nothing is wired to onRpc / onFrame.+ onRpc: () => {},+ onFrame: () => {},+ onTunnel: (kind, payload) => {+ // Binary peer→host frames are ignored: pty input rides JSON casts, exactly as on the WS.+ if (kind !== 'text') return+ const json = new TextDecoder().decode(payload)+ // Trust frames are consumed BEFORE dispatch and never reach the core.+ if (gate?.onTunnelText(json)) return+ const m = parseRpcMessage(json)+ if (!m) return+ if (clientId === null) {+ // Not mutually approved: refuse — but ANSWER, or the peer's `await` would hang forever.+ if (m.t === 'req') {+ socket.sendTunnelText(+ JSON.stringify({+ t: 'res',+ id: m.id,+ ok: false,+ error: { code: E_UNAUTHORIZED, message: 'Awaiting mutual approval.' }+ })+ )+ }+ return+ }+ if (m.t === 'req') {+ const id = clientId+ void opts.platform+ .dispatch(id, m)+ .then((res) => socket.sendTunnelText(JSON.stringify(res)))+ } else if (m.t === 'cast') {+ opts.platform.cast(clientId, m.method, m.args)+ }+ // res/ev from a peer are ignored (mirrors src/server/ws.ts).+ },+ onClose: () => {+ // The peer is GONE — the same state a closed browser tab leaves the core in.+ live.delete(session)+ detach()+ opts.onClose()+ }+ })++ return session+}diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex e01814d82..28e0ea4a5 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -209,6 +209,10 @@ export const IPC = {// Standing (phone) relay host: renderer toggles it on/off (settings.phoneAccessEnabled). Main// starts/stops the always-on host connection so a paired phone can reach this Mac over the relay.remoteStandingHostSet: 'remote:standing-host:set',+ // Revoke a paired PEER (by its stable box public key). Unpinning alone only refuses the NEXT+ // 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',