Skip to content

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.

feat(relay): tunnel rpc.ts frames over the E2EE socket (+ honest bufferedAmount)

enes85823d5ce2ab
diff --git a/src/main/remote/relay-socket.ts b/src/main/remote/relay-socket.ts
index d5491ef16..5502ce6d0 100644
--- a/src/main/remote/relay-socket.ts
+++ b/src/main/remote/relay-socket.ts
@@ -80,6 +80,18 @@ export type RelaySocket = {
// passed in; for a host it is learned from the client's `e2ee_hello`. Null before then. Used by
// the standing (phone) host to look the connecting device up in its pin-once approval list.
peerPublicKeyB64(): string | null
+ // --- 4c tunnel: the Server Edition's rpc.ts protocol, carried inside the E2EE box ------------
+ // Send one rpc.ts TEXT frame (a JSON RpcMessage). False if the channel is not ready — a tunnel
+ // frame is NEVER sent in the clear.
+ sendTunnelText(json: string): boolean
+ // Send one rpc.ts BINARY frame (encodePtyData bytes). False if the channel is not ready.
+ sendTunnelBinary(bytes: Uint8Array): boolean
+ // Bytes handed to the underlying socket but not yet flushed (ws.bufferedAmount + anything still
+ // sitting in the pre-open queue). This is the number Stage 2's per-client backpressure and the
+ // 8 MB WS_DROP_WATER drop-and-redraw ceiling key on (see src/core/ui-sink-registry.ts): a sink
+ // that reports 0 silently disables the ceiling, and a slow peer then queues pty output without
+ // bound until the host process dies. It must stay honest.
+ bufferedAmount(): number
// Tear down: stops reconnects and closes the transport.
close(): void
}
@@ -103,11 +115,21 @@ export type ConnectRelayOptions = {
onRpc(msg: RpcRequest): void
onFrame(f: Frame): void
onClose(): void
+ // An rpc.ts frame arrived over the ENCRYPTED, session-keyed, role-tagged, replay-checked
+ // channel. This is the ONLY inbound path 4c's trust + RPC layers may trust: anything that did
+ // not come out of the E2EE box never reaches here.
+ onTunnel?(kind: 'text' | 'binary', payload: Uint8Array): void
}
// Plaintext-tag bytes for decrypted peer payloads.
const TAG_RPC = 0x01
const TAG_FRAME = 0x02
+// 4c tunnel: the Server Edition's rpc.ts protocol, carried verbatim inside the E2EE box. Text = a
+// JSON RpcMessage; binary = an encodePtyData frame. Both ride the SAME encrypted stream as
+// everything else — same sendSeq counter, same FIFO delivery — because Stage 3's canvas
+// convergence needs a single ordered channel per client.
+const TAG_TUNNEL_TEXT = 0x03
+const TAG_TUNNEL_BIN = 0x04
const RPC_TIMEOUT_MS = 30_000
const KEEPALIVE_INTERVAL_MS = 25_000
@@ -393,6 +415,14 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {
}
const tag = plain[0]
const body = plain.subarray(1)
+ if (tag === TAG_TUNNEL_TEXT) {
+ opts.onTunnel?.('text', body)
+ return
+ }
+ if (tag === TAG_TUNNEL_BIN) {
+ opts.onTunnel?.('binary', body)
+ return
+ }
if (tag === TAG_FRAME) {
const frame = decodeFrame(body)
if (frame) {
@@ -542,6 +572,18 @@ export function connectRelay(opts: ConnectRelayOptions): RelaySocket {
}
return sendEncrypted(tagged(TAG_FRAME, encodeFrame(op, streamId, seq, payload)))
},
+ sendTunnelText(json) {
+ return sendEncrypted(tagged(TAG_TUNNEL_TEXT, textEncoder.encode(json)))
+ },
+ sendTunnelBinary(bytes) {
+ return sendEncrypted(tagged(TAG_TUNNEL_BIN, bytes))
+ },
+ bufferedAmount() {
+ // Honest by construction: the transport reports what it has been handed and has not yet
+ // flushed. No backpressure decision is made here — the caller (ui-sink-registry) owns the
+ // thresholds; this only has to tell the truth. Not connected => nothing is queued => 0.
+ return transport?.bufferedAmount ?? 0
+ },
sas() {
return baseKey ? sasFromSharedKey(baseKey) : null
},
@@ -648,21 +690,28 @@ function openWebSocketTransport(url: string): RelayTransport {
// Buffer sends issued before 'open'.
const queue: (string | Uint8Array)[] = []
let open = false
+ // Bytes sitting in `queue`. They are real, un-flushed bytes that `ws.bufferedAmount` cannot see
+ // (the socket has not been handed them yet), so leaving them out would make bufferedAmount lie
+ // during exactly the window in which a burst can pile up — and a backpressure ceiling that
+ // believes the lie stops capping, letting the host queue pty output without bound.
+ let queuedBytes = 0
ws.on('open', () => {
open = true
for (const item of queue.splice(0)) {
ws.send(item)
}
+ queuedBytes = 0
})
return {
get bufferedAmount() {
- return ws.bufferedAmount
+ return ws.bufferedAmount + queuedBytes
},
send: (data) => {
if (open) {
ws.send(data)
} else {
queue.push(data)
+ queuedBytes += typeof data === 'string' ? Buffer.byteLength(data) : data.byteLength
}
},
close: () => ws.close(),
diff --git a/test/remote/relay-tunnel.test.ts b/test/remote/relay-tunnel.test.ts
new file mode 100644
index 000000000..6bf12b487
--- /dev/null
+++ b/test/remote/relay-tunnel.test.ts
@@ -0,0 +1,193 @@
+// Stage 4c, task 1: the Server Edition's WS-RPC protocol (`src/shared/rpc.ts`) carried verbatim
+// inside the relay's E2EE box. A remote tab is then "a Server Edition client whose socket happens
+// to be a relay" — same frames, same ordering, encrypted end to end.
+//
+// Additive: the legacy opcode dialect (rpc/notify/respond/sendFrame) is untouched, so
+// test/remote/relay-socket.test.ts and test/remote/framing.test.ts still pass unmodified.
+import { describe, it, expect } from 'vitest'
+import { connectRelay, type RelayTransport } from '../../src/main/remote/relay-socket'
+import { genKeyPair, publicKeyToB64 } from '../../src/main/remote/e2ee'
+import { encodePtyData, decodePtyData } from '../../src/shared/rpc'
+
+// A pair of in-process fake duplex transports: whatever one `send`s is delivered asynchronously to
+// the other's onMessage. Copied from test/remote/relay-socket.test.ts (that file is a merge gate —
+// it must stay byte-for-byte unchanged, so it is duplicated rather than refactored into a helper).
+function makeTransportPair(): { a: RelayTransport; b: RelayTransport } {
+ let aOnMessage: ((data: unknown) => void) | null = null
+ let bOnMessage: ((data: unknown) => void) | null = null
+ let aOnClose: (() => void) | null = null
+ let bOnClose: (() => void) | null = null
+ let closed = false
+
+ const deliver = (cb: ((data: unknown) => void) | null, data: unknown): void => {
+ queueMicrotask(() => {
+ if (!closed) cb?.(data)
+ })
+ }
+ const teardown = (): void => {
+ if (closed) return
+ closed = true
+ queueMicrotask(() => {
+ aOnClose?.()
+ bOnClose?.()
+ })
+ }
+
+ const a: RelayTransport = {
+ bufferedAmount: 0,
+ send: (data) => deliver(bOnMessage, data),
+ close: teardown,
+ onMessage: (cb) => {
+ aOnMessage = cb
+ },
+ onClose: (cb) => {
+ aOnClose = cb
+ }
+ }
+ const b: RelayTransport = {
+ bufferedAmount: 0,
+ send: (data) => deliver(aOnMessage, data),
+ close: teardown,
+ onMessage: (cb) => {
+ bOnMessage = cb
+ },
+ onClose: (cb) => {
+ bOnClose = cb
+ }
+ }
+ return { a, b }
+}
+
+function deferred(): { promise: Promise<void>; resolve: () => void } {
+ let resolve!: () => void
+ const promise = new Promise<void>((r) => {
+ resolve = r
+ })
+ return { promise, resolve }
+}
+
+describe('relay tunnel — rpc.ts frames over the E2EE socket', () => {
+ it('round-trips a text frame and a binary pty frame, and reports an honest bufferedAmount', async () => {
+ const hostKeys = genKeyPair()
+ const clientKeys = genKeyPair()
+ const { a: ht, b: ct } = makeTransportPair()
+ const seen: Array<{ kind: 'text' | 'binary'; text?: string; bin?: Uint8Array }> = []
+
+ const host = connectRelay({
+ url: 'wss://x/ws',
+ token: 't',
+ role: 'host',
+ ourKeys: hostKeys,
+ transport: ht,
+ onReady: () => {},
+ onRpc: () => {},
+ onFrame: () => {},
+ onClose: () => {},
+ onTunnel: (kind, payload) =>
+ seen.push(
+ kind === 'text'
+ ? { kind, text: new TextDecoder().decode(payload) }
+ : { kind, bin: payload }
+ )
+ })
+
+ const clientReady = deferred()
+ const client = connectRelay({
+ url: 'wss://x/ws',
+ token: 't',
+ role: 'client',
+ ourKeys: clientKeys,
+ theirPubB64: publicKeyToB64(hostKeys.publicKey),
+ transport: ct,
+ onReady: () => clientReady.resolve(),
+ onRpc: () => {},
+ onFrame: () => {},
+ onClose: () => {}
+ })
+ await clientReady.promise
+
+ expect(
+ client.sendTunnelText(JSON.stringify({ t: 'req', id: 1, method: 'fs:list', args: ['/'] }))
+ ).toBe(true)
+ expect(client.sendTunnelBinary(encodePtyData('s1', 'hello'))).toBe(true)
+ await new Promise((r) => setTimeout(r, 20))
+
+ expect(seen.map((s) => s.kind)).toEqual(['text', 'binary'])
+ expect(JSON.parse(seen[0]!.text!)).toEqual({ t: 'req', id: 1, method: 'fs:list', args: ['/'] })
+ expect(decodePtyData(seen[1]!.bin!)).toEqual({ sessionId: 's1', data: 'hello' })
+ expect(typeof client.bufferedAmount()).toBe('number')
+
+ host.close()
+ client.close()
+ })
+
+ // Single-stream FIFO: canvas convergence (Stage 3) relies on a server-stamped `seq` arriving
+ // monotonically per client, which only holds on ONE ordered channel. Tunnel frames must therefore
+ // ride the same E2EE stream as everything else, interleaved in send order — never a side channel.
+ it('preserves send order across text, binary and legacy frames on the one stream', async () => {
+ const hostKeys = genKeyPair()
+ const clientKeys = genKeyPair()
+ const { a: ht, b: ct } = makeTransportPair()
+ const order: string[] = []
+
+ const hostReady = deferred()
+ const host = connectRelay({
+ url: 'wss://x/ws',
+ token: 't',
+ role: 'host',
+ ourKeys: hostKeys,
+ transport: ht,
+ onReady: () => hostReady.resolve(),
+ onRpc: (msg) => order.push(`rpc:${msg.method}`),
+ onFrame: () => order.push('frame'),
+ onClose: () => {},
+ onTunnel: (kind, payload) =>
+ order.push(kind === 'text' ? `text:${new TextDecoder().decode(payload)}` : 'binary')
+ })
+
+ const clientReady = deferred()
+ const client = connectRelay({
+ url: 'wss://x/ws',
+ token: 't',
+ role: 'client',
+ ourKeys: clientKeys,
+ theirPubB64: publicKeyToB64(hostKeys.publicKey),
+ transport: ct,
+ onReady: () => clientReady.resolve(),
+ onRpc: () => {},
+ onFrame: () => {},
+ onClose: () => {}
+ })
+ await Promise.all([hostReady.promise, clientReady.promise])
+
+ client.sendTunnelText('1')
+ client.sendTunnelBinary(encodePtyData('s', 'x'))
+ client.notify('legacy', {})
+ client.sendTunnelText('2')
+ await new Promise((r) => setTimeout(r, 20))
+
+ expect(order).toEqual(['text:1', 'binary', 'rpc:legacy', 'text:2'])
+
+ host.close()
+ client.close()
+ })
+
+ it('a tunnel frame sent before the handshake completes is refused (never leaks plaintext)', () => {
+ const { a } = makeTransportPair()
+ const s = connectRelay({
+ url: 'wss://x/ws',
+ token: 't',
+ role: 'host',
+ ourKeys: genKeyPair(),
+ transport: a,
+ onReady: () => {},
+ onRpc: () => {},
+ onFrame: () => {},
+ onClose: () => {}
+ })
+ expect(s.sendTunnelText('{"t":"cast","method":"pty:write","args":[]}')).toBe(false)
+ expect(s.sendTunnelBinary(encodePtyData('s1', 'x'))).toBe(false)
+ expect(s.bufferedAmount()).toBe(0)
+ s.close()
+ })
+})