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.

refactor(bridge): extract FrameTransport seam under RpcClient

enes4872b72b16f4
diff --git a/src/renderer/bridge/frame-transport.test.ts b/src/renderer/bridge/frame-transport.test.ts
new file mode 100644
index 000000000..3cfbab36a
--- /dev/null
+++ b/src/renderer/bridge/frame-transport.test.ts
@@ -0,0 +1,87 @@
+import { describe, it, expect } from 'vitest'
+import { encodePtyData, E_DISCONNECTED } from '../../shared/rpc'
+import type { FrameTransport } from './frame-transport'
+import { RpcClient } from './ws-bridge'
+
+/**
+ * An in-memory `FrameTransport` double. It records what the RpcClient sends, lets the test push
+ * inbound frames (JSON strings OR binary `Uint8Array` pty-data), and can fire `close`. `ready`
+ * resolves immediately — the carrier is "open" the moment it is constructed. This proves the
+ * RpcClient depends only on the FrameTransport seam, never on a WebSocket.
+ */
+class FakeTransport implements FrameTransport {
+ sent: string[] = []
+ private msgCb: ((data: string | Uint8Array) => void) | null = null
+ private closeCb: (() => void) | null = null
+
+ send(json: string): void {
+ this.sent.push(json)
+ }
+ onMessage(cb: (data: string | Uint8Array) => void): void {
+ this.msgCb = cb
+ }
+ onClose(cb: () => void): void {
+ this.closeCb = cb
+ }
+ ready(): Promise<void> {
+ return Promise.resolve()
+ }
+
+ // Test drivers ─────────────────────────────────────────────────────────────
+ emit(data: string | Uint8Array): void {
+ this.msgCb?.(data)
+ }
+ drop(): void {
+ this.closeCb?.()
+ }
+}
+
+describe('RpcClient over a FrameTransport', () => {
+ it('resolves a request on a matching res frame', async () => {
+ const t = new FakeTransport()
+ const client = new RpcClient(t)
+ await client.ready()
+ const p = client.request('any:method', 'ping')
+ // The RpcClient assigned id 1 (first request).
+ const frame = JSON.parse(t.sent[0])
+ expect(frame).toMatchObject({ t: 'req', id: 1, method: 'any:method', args: ['ping'] })
+ t.emit(JSON.stringify({ t: 'res', id: frame.id, ok: true, result: 'pong' }))
+ expect(await p).toBe('pong')
+ })
+
+ it('fans out a JSON ev frame to subscribers', () => {
+ const t = new FakeTransport()
+ const client = new RpcClient(t)
+ const seen: unknown[] = []
+ client.subscribe('pty:exit:s1', (code) => seen.push(code))
+ t.emit(JSON.stringify({ t: 'ev', channel: 'pty:exit:s1', args: [0] }))
+ expect(seen).toEqual([0])
+ })
+
+ it('fans out a binary pty:data frame on ptyData(sessionId)', () => {
+ const t = new FakeTransport()
+ const client = new RpcClient(t)
+ const datas: string[] = []
+ client.subscribe('pty:data:s1', (d) => datas.push(d as string))
+ t.emit(encodePtyData('s1', 'hello'))
+ expect(datas).toEqual(['hello'])
+ })
+
+ it('rejects in-flight requests with E_DISCONNECTED when the transport closes', async () => {
+ const t = new FakeTransport()
+ const client = new RpcClient(t)
+ await client.ready()
+ const a = client.request('git:worktree-add', '/repo')
+ t.drop()
+ await expect(a).rejects.toMatchObject({ code: E_DISCONNECTED })
+ })
+
+ it('notifies onClose hooks when the transport closes', async () => {
+ const t = new FakeTransport()
+ const client = new RpcClient(t)
+ let closed = 0
+ client.onClose(() => closed++)
+ t.drop()
+ expect(closed).toBe(1)
+ })
+})
diff --git a/src/renderer/bridge/frame-transport.ts b/src/renderer/bridge/frame-transport.ts
new file mode 100644
index 000000000..a3059eb74
--- /dev/null
+++ b/src/renderer/bridge/frame-transport.ts
@@ -0,0 +1,103 @@
+// The carrier seam under `RpcClient` (ws-bridge.ts). `RpcClient` speaks the rpc.ts frame protocol
+// (`req`/`res`/`cast`/`ev` + binary pty-data) and needs to send/receive frames — but it does not
+// care WHAT moves them. `FrameTransport` is that "what": a WebSocket to the Server Edition server,
+// or the E2EE relay tunnel to a remote desktop. Extracting it lets the SAME ws-bridge builders
+// (buildRealApi/buildFilesApi/…) power both a browser tab and a remote-desktop tab.
+//
+// A transport carries TWO frame shapes: JSON text frames (requests/responses/events) and binary
+// pty-data frames (rpc.ts `encodePtyData`). `onMessage` therefore hands back `string | Uint8Array`;
+// the RpcClient routes a string through `parseRpcMessage` and a `Uint8Array` through `decodePtyData`.
+
+import type { RelayClientApi } from '../../shared/types'
+
+export interface FrameTransport {
+ /** Send one outbound frame (always a JSON string — pty-data is inbound only). */
+ send(json: string): void
+ /** Register the inbound-frame sink. A string is a JSON frame; a Uint8Array is a binary pty frame. */
+ onMessage(cb: (data: string | Uint8Array) => void): void
+ /** Register the carrier-closed hook (in-flight requests are failed, the reconnect overlay shows). */
+ onClose(cb: () => void): void
+ /** Resolves once the carrier is open and ready to exchange frames; rejects if it fails to open. */
+ ready(): Promise<void>
+}
+
+/**
+ * The Server Edition carrier: ONE WebSocket to `/ws`. This is the pre-refactor `RpcClient` socket
+ * logic moved verbatim — `binaryType='arraybuffer'`, open→ready / error-before-open→reject, and the
+ * message/close events forwarded to the sinks. Binary frames arrive as `ArrayBuffer` in the browser
+ * and as a `Buffer` (a `Uint8Array`) under the `ws` package in tests; both are normalized to a
+ * `Uint8Array` here so the RpcClient only ever sees `string | Uint8Array`.
+ */
+export class WebSocketFrameTransport implements FrameTransport {
+ private ws: WebSocket
+ private readyPromise: Promise<void>
+
+ constructor(url: string) {
+ const ws = new WebSocket(url)
+ ws.binaryType = 'arraybuffer'
+ this.ws = ws
+ this.readyPromise = new Promise<void>((resolve, reject) => {
+ ws.addEventListener('open', () => resolve())
+ ws.addEventListener('error', () => reject(new Error('WebSocket error')))
+ })
+ }
+
+ send(json: string): void {
+ this.ws.send(json)
+ }
+
+ onMessage(cb: (data: string | Uint8Array) => void): void {
+ this.ws.addEventListener('message', (ev: MessageEvent) => {
+ const d = ev.data
+ if (typeof d === 'string') cb(d)
+ else if (d instanceof ArrayBuffer) cb(new Uint8Array(d))
+ else if (d instanceof Uint8Array) cb(d)
+ // Anything else is undecodable — drop it (matches the pre-refactor binary guard).
+ })
+ }
+
+ onClose(cb: () => void): void {
+ this.ws.addEventListener('close', () => cb())
+ }
+
+ ready(): Promise<void> {
+ return this.readyPromise
+ }
+}
+
+/**
+ * The remote-desktop carrier: the E2EE relay tunnel, addressed by `connectionId`, over the preload's
+ * `relayClient` surface (main-process trust machinery lives behind it — see relay-client.ts). Only
+ * JSON frames ride `onMessage` here: pty-data is decoded in the main process and re-emitted on the
+ * per-session `pty:data` channel (relay-client.ts / index.ts), which the remote-tab `pty.onData`
+ * subscribes to — the same shape a local pty uses. `ready` is the mutual-approval gate: it resolves
+ * only once BOTH humans have confirmed the SAS (`onApproved`), which is when the frame pipe is live.
+ */
+export class RelayFrameTransport implements FrameTransport {
+ private readyPromise: Promise<void>
+
+ constructor(
+ private readonly connectionId: string,
+ private readonly relay: RelayClientApi = window.nodeTerminal.relayClient
+ ) {
+ this.readyPromise = new Promise<void>((resolve) => {
+ this.relay.onApproved(connectionId, () => resolve())
+ })
+ }
+
+ send(json: string): void {
+ this.relay.send(this.connectionId, json)
+ }
+
+ onMessage(cb: (data: string | Uint8Array) => void): void {
+ this.relay.onFrame(this.connectionId, (frame) => cb(frame))
+ }
+
+ onClose(cb: () => void): void {
+ this.relay.onClosed(this.connectionId, () => cb())
+ }
+
+ ready(): Promise<void> {
+ return this.readyPromise
+ }
+}
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index da1f7704b..c1e8e8ced 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -34,16 +34,22 @@ import {
import type { PeerIdentity } from '../../shared/presence'
import { buildStubApi } from './stubs'
import { mountPickerRoot, openDirectoryPicker } from './dialog-picker'
+import { type FrameTransport, WebSocketFrameTransport } from './frame-transport'
type Listener = (...args: unknown[]) => void
/**
- * One WebSocket, a pending-request map keyed by an incrementing id, and a channel-listener
- * fan-out map. Exported for the unit test (`ws-bridge.test.ts`). Kept free of any DOM/overlay
- * concerns so the test stays clean — reconnect UI lives in `installWsBridge`.
+ * A `FrameTransport`, a pending-request map keyed by an incrementing id, and a channel-listener
+ * fan-out map. Exported for the unit tests (`ws-bridge.test.ts` / `frame-transport.test.ts`). Kept
+ * free of any DOM/overlay concerns so the tests stay clean — reconnect UI lives in `installWsBridge`.
+ *
+ * `RpcClient` speaks the rpc.ts protocol but is carrier-agnostic: it depends only on a
+ * `FrameTransport` (the WebSocket to the Server Edition server, or the relay tunnel to a remote
+ * desktop). For back-compat a plain URL string is accepted and wrapped in a `WebSocketFrameTransport`
+ * (so the WebSocket path — and its tests — are byte-identical to before the transport was extracted).
*/
export class RpcClient {
- private ws: WebSocket
+ private transport: FrameTransport
private nextId = 1
private pending = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>()
private channels = new Map<string, Set<Listener>>()
@@ -51,21 +57,15 @@ export class RpcClient {
// event in the same macrotask as `open`, so a subscriber registered one microtask later (via
// `await ready()`) would otherwise miss it. Buffered here (capped) and flushed on subscribe.
private early: Array<{ channel: string; args: unknown[] }> = []
- private readyPromise: Promise<void>
private closeCbs = new Set<() => void>()
- constructor(url: string) {
- const ws = new WebSocket(url)
- ws.binaryType = 'arraybuffer'
- this.ws = ws
- this.readyPromise = new Promise<void>((resolve, reject) => {
- ws.addEventListener('open', () => resolve())
- ws.addEventListener('error', () => reject(new Error('WebSocket error')))
- })
- ws.addEventListener('message', (ev: MessageEvent) => this.onMessage(ev.data))
- ws.addEventListener('close', () => {
+ constructor(transport: FrameTransport | string) {
+ this.transport =
+ typeof transport === 'string' ? new WebSocketFrameTransport(transport) : transport
+ this.transport.onMessage((data) => this.onMessage(data))
+ this.transport.onClose(() => {
// Fail the in-flight requests BEFORE the overlay hooks: a response can only arrive over the
- // socket that carried the request, so once it is gone they are unanswerable.
+ // carrier that carried the request, so once it is gone they are unanswerable.
this.failPending()
this.closeCbs.forEach((cb) => cb())
})
@@ -91,9 +91,9 @@ export class RpcClient {
for (const p of waiting) p.reject(err)
}
- /** Resolves once the socket is open; rejects if it errors before opening. */
+ /** Resolves once the carrier is open; rejects if it fails to open. */
ready(): Promise<void> {
- return this.readyPromise
+ return this.transport.ready()
}
/** Register a connection-loss hook (used by the reconnect overlay). */
@@ -101,23 +101,16 @@ export class RpcClient {
this.closeCbs.add(cb)
}
- private onMessage(data: unknown): void {
+ private onMessage(data: string | Uint8Array): void {
if (typeof data === 'string') {
const m = parseRpcMessage(data)
if (!m) return
this.handleJson(m)
return
}
- // Binary pty frame. Browser gives ArrayBuffer (binaryType='arraybuffer'); the `ws` package
- // in tests gives a Buffer (already a Uint8Array). Normalize both to a Uint8Array.
- const bytes =
- data instanceof Uint8Array
- ? data
- : data instanceof ArrayBuffer
- ? new Uint8Array(data)
- : null
- if (!bytes) return
- const decoded = decodePtyData(bytes)
+ // Binary pty frame. The transport has already normalized the carrier's native binary shape
+ // (ArrayBuffer in the browser, Buffer under the `ws` package in tests) to a Uint8Array.
+ const decoded = decodePtyData(data)
if (!decoded) return
this.fanOut(IPC.ptyData(decoded.sessionId), [decoded.data])
}
@@ -152,13 +145,13 @@ export class RpcClient {
this.pending.set(id, { resolve, reject })
// encodeArgs: an OMITTED optional argument must reach the handler as `undefined` (so its
// default fires) while a MEANINGFUL `null` (pty.resize park, presence clears) stays `null`.
- this.ws.send(JSON.stringify({ t: 'req', id, method, ...encodeArgs(args) }))
+ this.transport.send(JSON.stringify({ t: 'req', id, method, ...encodeArgs(args) }))
})
}
/** Send a fire-and-forget cast (no response expected). */
cast(method: string, ...args: unknown[]): void {
- this.ws.send(JSON.stringify({ t: 'cast', method, ...encodeArgs(args) }))
+ this.transport.send(JSON.stringify({ t: 'cast', method, ...encodeArgs(args) }))
}
/** Subscribe to a channel; returns an unsubscribe function. */
@@ -544,7 +537,7 @@ function startReconnect(): void {
* failure path (overlay shown, reconnect loop running) so bootstrap can skip loading the app.
*/
export async function installWsBridge(): Promise<boolean> {
- const client = new RpcClient(wsUrl())
+ const client = new RpcClient(new WebSocketFrameTransport(wsUrl()))
try {
await client.ready()
} catch {