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.

test(relay): delete old-dialect e2e/handler tests (Stage 4 Task 10)

enes221d56fe548b
diff --git a/test/remote/b5-e2e.test.ts b/test/remote/b5-e2e.test.ts
deleted file mode 100644
index 6831c7cef..000000000
--- a/test/remote/b5-e2e.test.ts
+++ /dev/null
@@ -1,421 +0,0 @@
-// End-to-end integration test for the B5 remote project mirror (Task 6).
-//
-// Builds on the B4 relay e2e (`relay-e2e.test.ts`): same REAL relay child process + REAL relay
-// socket protocol + fake echo pty, but now exercises the FULL B5 stack the "New Remote Connection"
-// UX drives — the host's canvas sync + fs serving, and the client's canvas router — over the
-// bridged E2EE pair.
-//
-// What it asserts (over the bridged host<->client pair, real handlers + routers):
-// 1. the client receives the host's `canvas:state` (a node list) via the host->client notify path;
-// 2. a terminal attaches and an echo PTY round-trips input -> output;
-// 3. `fs.write` then `fs.read` round-trip against a real temp dir over the relay;
-// 4. a client `canvas:mutate` (move a node) reaches the host handler and the host's resulting
-// `canvas:state` reflects the new position;
-// 5. no plaintext (the moved node's id) ever appears in the bytes the relay forwards (E2EE).
-//
-// The harness is hermetic: the relay runs in-process as a child via `tsx` on an ephemeral port;
-// there is NO network / deployed relay.
-
-import { afterAll, beforeAll, describe, expect, it } from 'vitest'
-import crypto from 'node:crypto'
-import os from 'node:os'
-import path from 'node:path'
-import { existsSync, promises as fsp } from 'node:fs'
-import { spawn, type ChildProcess } from 'node:child_process'
-import { createServer } from 'node:net'
-import { WebSocket } from 'ws'
-
-import { connectRelay, wrapWebSocket, type RelaySocket } from '../../src/main/remote/relay-socket'
-import {
- createHostHandlers,
- createHostCanvasSync,
- type HostPtyManager,
- type HostFsOps
-} from '../../src/main/remote/host-service'
-import {
- createClientHandlers,
- createClientCanvasRouter
-} from '../../src/main/remote/client-service'
-import { applyMutation } from '../../src/main/remote/canvas-sync'
-import * as fsOps from '../../src/core/fs-ops'
-import { genKeyPair, publicKeyToB64, type KeyPair } from '../../src/main/remote/e2ee'
-import { OP, type Frame } from '../../src/main/remote/framing'
-import type {
- CanvasMutation,
- CanvasNodeState,
- CanvasState,
- PtyCreateOptions
-} from '../../src/shared/types'
-import type { DetachedSinks } from '../../src/main/pty-manager'
-
-// Companion server repo holding the REAL relay (not part of this repo) — the suite below is
-// skipped when it isn't checked out alongside as ./nodebaseserver.
-const SERVER_DIR =
- process.env.NODETERM_SERVER_DIR || path.resolve('nodebaseserver')
-const RELAY_ENTRY = path.join(SERVER_DIR, 'src/relay/index.ts')
-const TSX_BIN = path.join(SERVER_DIR, 'node_modules/.bin/tsx')
-
-const SPAWN_TIMEOUT_MS = 20_000
-const HANDSHAKE_TIMEOUT_MS = 15_000
-
-// --- helpers (shared shape with relay-e2e.test.ts) ---------------------------
-
-function deferred<T>(): { promise: Promise<T>; resolve: (v: T) => void; reject: (e: Error) => void } {
- let resolve!: (v: T) => void
- let reject!: (e: Error) => void
- const promise = new Promise<T>((res, rej) => {
- resolve = res
- reject = rej
- })
- return { promise, resolve, reject }
-}
-
-function getEphemeralPort(): Promise<number> {
- return new Promise((resolve, reject) => {
- const srv = createServer()
- srv.unref()
- srv.on('error', reject)
- srv.listen(0, '127.0.0.1', () => {
- const addr = srv.address()
- if (addr && typeof addr === 'object') {
- const port = addr.port
- srv.close(() => resolve(port))
- } else {
- srv.close(() => reject(new Error('Could not determine an ephemeral port.')))
- }
- })
- })
-}
-
-function mintToken(privateKey: crypto.KeyObject, pairingId: string): string {
- const now = Math.floor(Date.now() / 1000)
- const payload = { pairingId, licenseId: 'test-license', iat: now, exp: now + 300 }
- const p = Buffer.from(JSON.stringify(payload)).toString('base64url')
- const sig = crypto.sign(null, Buffer.from(p), privateKey).toString('base64url')
- return `${p}.${sig}`
-}
-
-function spawnRelay(port: number, publicKeyPem: string): Promise<ChildProcess> {
- const child = spawn(TSX_BIN, [RELAY_ENTRY], {
- cwd: SERVER_DIR,
- env: { ...process.env, PORT: String(port), RELAY_ENTITLEMENT_PUBLIC_KEY: publicKeyPem },
- stdio: ['ignore', 'pipe', 'pipe']
- })
-
- const ready = deferred<ChildProcess>()
- let settled = false
- const timer = setTimeout(() => {
- if (settled) return
- settled = true
- ready.reject(new Error(`Relay did not start within ${SPAWN_TIMEOUT_MS}ms.\n${stderr}`))
- }, SPAWN_TIMEOUT_MS)
-
- let stderr = ''
- child.stdout?.on('data', (buf: Buffer) => {
- if (!settled && buf.toString().includes('listening')) {
- settled = true
- clearTimeout(timer)
- ready.resolve(child)
- }
- })
- child.stderr?.on('data', (buf: Buffer) => {
- stderr += buf.toString()
- })
- child.on('exit', (code) => {
- if (settled) return
- settled = true
- clearTimeout(timer)
- ready.reject(new Error(`Relay exited early (code ${code}).\n${stderr}`))
- })
-
- return ready.promise
-}
-
-// Open a real ws to the relay carrying the token; tap every outbound payload so the test can
-// assert no plaintext crosses the wire.
-function openTappedTransport(
- baseUrl: string,
- token: string,
- sentSink: (data: string | Uint8Array) => void
-): { transport: ReturnType<typeof wrapWebSocket>; opened: Promise<void>; ws: WebSocket } {
- const sep = baseUrl.includes('?') ? '&' : '?'
- const ws = new WebSocket(`${baseUrl}${sep}token=${encodeURIComponent(token)}`)
- ws.binaryType = 'nodebuffer'
-
- const opened = deferred<void>()
- ws.on('open', () => opened.resolve())
- ws.on('error', (err) => opened.reject(err as Error))
-
- const wrapped = wrapWebSocket(ws)
- const transport = {
- get bufferedAmount() {
- return wrapped.bufferedAmount
- },
- send: (data: string | Uint8Array) => {
- sentSink(data)
- wrapped.send(data)
- },
- close: () => wrapped.close(),
- onMessage: wrapped.onMessage,
- onClose: wrapped.onClose
- }
- return { transport, opened: opened.promise, ws }
-}
-
-// A fake pty-manager: each created/attached session echoes whatever is written to it straight back
-// as output. captureSnapshot returns empty (the attach path still exercises Start->End).
-function makeEchoPty(): HostPtyManager {
- const sinks = new Map<string, DetachedSinks>()
- let counter = 0
- return {
- createDetached(_options: PtyCreateOptions, s: DetachedSinks): string {
- const sessionId = `echo-${++counter}`
- sinks.set(sessionId, s)
- return sessionId
- },
- attachDetached(_persistKey: string, s: DetachedSinks): string {
- const sessionId = `echo-${++counter}`
- sinks.set(sessionId, s)
- return sessionId
- },
- async captureSnapshot(): Promise<string> {
- return ''
- },
- write(sessionId: string, data: string): void {
- sinks.get(sessionId)?.onData(data)
- },
- resize(): void {},
- setFlow(): void {},
- kill(sessionId: string): void {
- const s = sinks.get(sessionId)
- sinks.delete(sessionId)
- s?.onExit(0)
- }
- }
-}
-
-function node(id: string, x: number, y: number): CanvasNodeState {
- return {
- id,
- kind: 'terminal',
- position: { x, y },
- size: { width: 480, height: 320 },
- title: id,
- color: '#888',
- group: null
- }
-}
-
-// --- test --------------------------------------------------------------------
-
-describe.skipIf(!existsSync(RELAY_ENTRY))('B5 remote project mirror end-to-end (real relay + real handlers + fake pty)', () => {
- let relay: ChildProcess | null = null
- let baseUrl = ''
- let token = ''
- let hostKeys: KeyPair
- let clientKeys: KeyPair
- let tmpDir = ''
- const hostSentFrames: Uint8Array[] = []
-
- let hostSocket: RelaySocket | null = null
- let clientSocket: RelaySocket | null = null
-
- beforeAll(async () => {
- const { privateKey, publicKey } = crypto.generateKeyPairSync('ed25519')
- const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }) as string
-
- const port = await getEphemeralPort()
- baseUrl = `ws://127.0.0.1:${port}`
- relay = await spawnRelay(port, publicKeyPem)
-
- token = mintToken(privateKey, 'pairing-b5-1')
- hostKeys = genKeyPair()
- clientKeys = genKeyPair()
- tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'nt-b5-e2e-'))
- }, SPAWN_TIMEOUT_MS + 5_000)
-
- afterAll(async () => {
- hostSocket?.close()
- clientSocket?.close()
- relay?.kill('SIGKILL')
- if (tmpDir) await fsp.rm(tmpDir, { recursive: true, force: true }).catch(() => {})
- })
-
- it('mirrors the canvas, attaches a terminal, round-trips fs, applies a mutation — all E2EE', async () => {
- // --- the host's authoritative canvas (single writer). The client mirror reflects this. ---
- let hostCanvas: CanvasState = { nodes: [node('n-1', 100, 100), node('n-2', 400, 100)] }
-
- // --- host connects FIRST (becomes the pending host) ---
- const hostTap = openTappedTransport(baseUrl, token, (data) => {
- if (data instanceof Uint8Array) hostSentFrames.push(Uint8Array.from(data))
- })
- await hostTap.opened
-
- const hostReady = deferred<void>()
- let hostHandlers: ReturnType<typeof createHostHandlers> | null = null
- let hostCanvasSync: ReturnType<typeof createHostCanvasSync> | null = null
- // fs-ops served against the temp dir (mirrors the real host, which serves its real fs).
- const hostFs: HostFsOps = {
- listDir: (p) => fsOps.listDir(p),
- readText: (p) => fsOps.readText(p),
- readBinary: (p) => fsOps.readBinary(p),
- writeText: (p, c) => fsOps.writeText(p, c)
- }
-
- hostSocket = connectRelay({
- url: baseUrl,
- token,
- role: 'host',
- ourKeys: hostKeys,
- transport: hostTap.transport,
- onReady: () => {
- // Bridge established — push the current canvas so the client mirrors immediately.
- hostCanvasSync?.setState(hostCanvas)
- hostReady.resolve()
- },
- onRpc: (req) => {
- // Canvas mutations route to the sync (host is the single writer); else a pty/fs RPC.
- if (hostCanvasSync?.handleRpc(req)) return
- hostHandlers?.onRpc(req)
- },
- onFrame: (frame) => hostHandlers?.onFrame(frame),
- onClose: () => hostHandlers?.closeAll()
- })
- // Share the temp dir as the allowed fs root (fs jail) so the client's fs.* RPCs are served.
- hostHandlers = createHostHandlers(makeEchoPty(), hostSocket, hostFs, () => [tmpDir])
- // Mirror the real host: a client mutation is applied to the host's authoritative state (the
- // single writer), then re-broadcast as the new `canvas:state`.
- hostCanvasSync = createHostCanvasSync(hostSocket, (mutation: CanvasMutation) => {
- hostCanvas = { nodes: applyMutation(hostCanvas.nodes, mutation) }
- hostCanvasSync?.setState(hostCanvas)
- })
-
- // --- client connects SECOND (triggers the bridge) ---
- const clientTap = openTappedTransport(baseUrl, token, () => {})
- await clientTap.opened
-
- const clientReady = deferred<void>()
- const canvasStates: CanvasState[] = []
- const dataEvents: { streamId: number; data: string }[] = []
- const exitEvents: { streamId: number; exitCode: number }[] = []
- let clientHandlers: ReturnType<typeof createClientHandlers> | null = null
- let clientCanvas: ReturnType<typeof createClientCanvasRouter> | null = null
-
- clientSocket = connectRelay({
- url: baseUrl,
- token,
- role: 'client',
- ourKeys: clientKeys,
- theirPubB64: publicKeyToB64(hostKeys.publicKey),
- transport: clientTap.transport,
- onReady: () => clientReady.resolve(),
- onRpc: (req) => {
- // The host pushes `canvas:state` as a one-way notify (id:''); route it to the mirror.
- const state = clientCanvas?.handleRpc(req)
- if (state) canvasStates.push(state)
- },
- onFrame: (frame: Frame) => clientHandlers?.onFrame(frame),
- onClose: () => clientHandlers?.closeAll()
- })
- clientHandlers = createClientHandlers(clientSocket, {
- onData: (streamId, data) => dataEvents.push({ streamId, data }),
- onExit: (streamId, exitCode) => exitEvents.push({ streamId, exitCode })
- })
- clientCanvas = createClientCanvasRouter(clientSocket)
-
- // Both ends complete the E2EE handshake.
- await withTimeout(
- Promise.all([hostReady.promise, clientReady.promise]),
- HANDSHAKE_TIMEOUT_MS,
- 'handshake'
- )
-
- // === (1) client receives the host's canvas:state ===
- await waitFor(() => canvasStates.length > 0, HANDSHAKE_TIMEOUT_MS, 'initial canvas:state')
- const firstState = canvasStates[0]
- expect(firstState.nodes.map((n) => n.id).sort()).toEqual(['n-1', 'n-2'])
- expect(firstState.nodes.find((n) => n.id === 'n-1')?.position).toEqual({ x: 100, y: 100 })
-
- // === (2) terminal attaches + echo round-trips ===
- const streamId = await withTimeout(
- clientHandlers.create({ cols: 80, rows: 24, persistKey: 'n-1' }),
- HANDSHAKE_TIMEOUT_MS,
- 'pty.attach'
- )
- expect(typeof streamId).toBe('number')
-
- clientHandlers.write(streamId, 'hello\n')
- await waitFor(
- () => dataEvents.some((e) => e.streamId === streamId && e.data.includes('hello')),
- HANDSHAKE_TIMEOUT_MS,
- 'echo output'
- )
- const echoed = dataEvents
- .filter((e) => e.streamId === streamId)
- .map((e) => e.data)
- .join('')
- expect(echoed).toContain('hello')
-
- // === (3) fs.write then fs.read round-trip against the temp dir ===
- const filePath = path.join(tmpDir, 'remote.txt')
- const contents = 'remote-fs-roundtrip-payload'
- const wrote = await withTimeout(clientHandlers.fsWrite(filePath, contents), HANDSHAKE_TIMEOUT_MS, 'fs.write')
- expect(wrote).toBe(true)
- const readBack = await withTimeout(clientHandlers.fsRead(filePath), HANDSHAKE_TIMEOUT_MS, 'fs.read')
- expect(readBack).toBe(contents)
- // And it really hit the disk on the "host" side.
- expect(await fsp.readFile(filePath, 'utf-8')).toBe(contents)
-
- // === (4) client canvas:mutate (move n-1) is reflected back in the host's next canvas:state ===
- const beforeCount = canvasStates.length
- const moved = node('n-1', 777, 555)
- clientCanvas.sendMutation({ op: 'upsert', node: moved })
- await waitFor(
- () =>
- canvasStates.length > beforeCount &&
- canvasStates[canvasStates.length - 1].nodes.find((n) => n.id === 'n-1')?.position.x === 777,
- HANDSHAKE_TIMEOUT_MS,
- 'mutated canvas:state'
- )
- const latest = canvasStates[canvasStates.length - 1]
- expect(latest.nodes.find((n) => n.id === 'n-1')?.position).toEqual({ x: 777, y: 555 })
- // The host's authoritative state was the single writer that produced it.
- expect(hostCanvas.nodes.find((n) => n.id === 'n-1')?.position).toEqual({ x: 777, y: 555 })
-
- // === (5) E2EE: no host->relay frame leaks plaintext (node id / file payload) ===
- expect(hostSentFrames.length).toBeGreaterThan(0)
- for (const needleStr of ['hello', contents, 'n-1']) {
- const needle = Buffer.from(needleStr)
- const leaked = hostSentFrames.find((frame) => Buffer.from(frame).includes(needle))
- expect(leaked, `a host->relay frame leaked the plaintext "${needleStr}"`).toBeUndefined()
- }
- // Sanity: the same plaintext, unencrypted, WOULD be findable — the assertion is meaningful.
- expect(Buffer.from('canvas n-1 payload hello').includes(Buffer.from('hello'))).toBe(true)
-
- // --- close ---
- clientSocket.close()
- hostSocket.close()
- expect(exitEvents.length).toBeGreaterThanOrEqual(0)
- }, HANDSHAKE_TIMEOUT_MS + 15_000)
-})
-
-// --- timing utilities --------------------------------------------------------
-
-function delay(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms))
-}
-
-function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
- return Promise.race([
- promise,
- new Promise<T>((_, reject) => setTimeout(() => reject(new Error(`Timed out waiting for ${label}.`)), ms))
- ])
-}
-
-async function waitFor(cond: () => boolean, ms: number, label: string): Promise<void> {
- const start = Date.now()
- while (!cond()) {
- if (Date.now() - start > ms) throw new Error(`Timed out waiting for ${label}.`)
- await delay(25)
- }
-}
diff --git a/test/remote/client-canvas-router.test.ts b/test/remote/client-canvas-router.test.ts
deleted file mode 100644
index 751a58702..000000000
--- a/test/remote/client-canvas-router.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { describe, it, expect, vi } from 'vitest'
-import {
- createClientCanvasRouter,
- type CanvasMutateSocket
-} from '../../src/main/remote/client-service'
-import {
- CANVAS_MUTATE_METHOD,
- CANVAS_STATE_METHOD
-} from '../../src/main/remote/host-service'
-import type { CanvasMutation, CanvasNodeState, CanvasState } from '../../src/shared/types'
-
-function fakeSocket() {
- const rpcs: { method: string; params: unknown }[] = []
- const socket: CanvasMutateSocket = {
- rpc: vi.fn(async (method, params) => {
- rpcs.push({ method, params })
- return {}
- })
- }
- return { socket, rpcs }
-}
-
-function node(id: string): CanvasNodeState {
- return {
- id,
- kind: 'terminal',
- position: { x: 0, y: 0 },
- size: { width: 480, height: 320 },
- title: id,
- color: '#888',
- group: null
- }
-}
-
-const state = (nodes: CanvasNodeState[]): CanvasState => ({ nodes })
-
-describe('createClientCanvasRouter', () => {
- it('returns the CanvasState for an inbound canvas:state notify (id:"")', () => {
- const { socket } = fakeSocket()
- const router = createClientCanvasRouter(socket)
-
- const s = state([node('a'), node('b')])
- const result = router.handleRpc({ id: '', method: CANVAS_STATE_METHOD, params: s })
-
- expect(result).toEqual(s)
- })
-
- it('ignores non-canvas methods and malformed state (returns null)', () => {
- const { socket } = fakeSocket()
- const router = createClientCanvasRouter(socket)
-
- expect(router.handleRpc({ id: 'r1', method: 'pty.create', params: {} })).toBeNull()
- expect(router.handleRpc({ id: '', method: CANVAS_STATE_METHOD, params: null })).toBeNull()
- expect(router.handleRpc({ id: '', method: CANVAS_STATE_METHOD, params: { foo: 1 } })).toBeNull()
- // nodes must be an array
- expect(
- router.handleRpc({ id: '', method: CANVAS_STATE_METHOD, params: { nodes: 'x' } })
- ).toBeNull()
- })
-
- it('sendMutation forwards the mutation to the host as a canvas:mutate RPC', () => {
- const { socket, rpcs } = fakeSocket()
- const router = createClientCanvasRouter(socket)
-
- const mutation: CanvasMutation = { op: 'upsert', node: node('x') }
- router.sendMutation(mutation)
-
- expect(rpcs).toEqual([{ method: CANVAS_MUTATE_METHOD, params: mutation }])
- })
-
- it('sendMutation swallows a rejected RPC (best-effort)', async () => {
- const socket: CanvasMutateSocket = { rpc: vi.fn(async () => Promise.reject(new Error('gone'))) }
- const router = createClientCanvasRouter(socket)
-
- expect(() => router.sendMutation({ op: 'remove', id: 'z' })).not.toThrow()
- // Let the rejected promise settle; the .catch() must absorb it (no unhandled rejection).
- await Promise.resolve()
- })
-})
diff --git a/test/remote/client-handlers.test.ts b/test/remote/client-handlers.test.ts
deleted file mode 100644
index 3e1799e65..000000000
--- a/test/remote/client-handlers.test.ts
+++ /dev/null
@@ -1,166 +0,0 @@
-import { describe, it, expect, vi } from 'vitest'
-import {
- createClientHandlers,
- type ClientRelaySocket,
- type ClientSessionSinks
-} from '../../src/main/remote/client-service'
-import { OP } from '../../src/main/remote/framing'
-
-// A fake relay socket that records RPC calls (resolving them on demand) and frames sent.
-function fakeSocket(createBody: unknown = { streamId: 7 }) {
- const rpcs: { method: string; params: unknown }[] = []
- const frames: { op: number; streamId: number; seq: number; payload: Uint8Array }[] = []
- const socket: ClientRelaySocket = {
- rpc: vi.fn(async (method, params) => {
- rpcs.push({ method, params })
- // RemoteTransport is remote-only, so `create` maps to `pty.attach` (attach-to-existing).
- if (method === 'pty.attach') return createBody
- return {}
- }),
- sendFrame: vi.fn((op, streamId, seq, payload) => {
- frames.push({ op, streamId, seq, payload })
- return true
- })
- }
- return { socket, rpcs, frames }
-}
-
-function fakeSinks() {
- const data: { streamId: number; data: string }[] = []
- const exits: { streamId: number; exitCode: number }[] = []
- const sinks: ClientSessionSinks = {
- onData: (streamId, d) => data.push({ streamId, data: d }),
- onExit: (streamId, exitCode) => exits.push({ streamId, exitCode })
- }
- return { sinks, data, exits }
-}
-
-describe('createClientHandlers', () => {
- it('maps create to RPC pty.attach (nodeId from persistKey) and resolves with the host streamId', async () => {
- const sock = fakeSocket({ streamId: 7 })
- const sinks = fakeSinks()
- const h = createClientHandlers(sock.socket, sinks.sinks)
-
- const streamId = await h.create({ cols: 100, rows: 30, cwd: '/tmp', persistKey: 'node-9' })
-
- expect(streamId).toBe(7)
- expect(sock.rpcs).toEqual([
- { method: 'pty.attach', params: { nodeId: 'node-9', cols: 100, rows: 30 } }
- ])
- })
-
- it('delivers a buffered snapshot (Start→Chunk*→End) as the first onData before live output', async () => {
- const sock = fakeSocket({ streamId: 4 })
- const sinks = fakeSinks()
- const h = createClientHandlers(sock.socket, sinks.sinks)
- await h.create({ cols: 80, rows: 24, persistKey: 'node-x' })
-
- h.onFrame({ op: OP.SnapshotStart, streamId: 4, seq: 0, payload: new Uint8Array(0) })
- h.onFrame({ op: OP.SnapshotChunk, streamId: 4, seq: 1, payload: new TextEncoder().encode('cur') })
- h.onFrame({ op: OP.SnapshotChunk, streamId: 4, seq: 2, payload: new TextEncoder().encode('rent') })
- // Nothing delivered until End.
- expect(sinks.data).toEqual([])
- h.onFrame({ op: OP.SnapshotEnd, streamId: 4, seq: 3, payload: new Uint8Array(0) })
- // Snapshot first, then live output.
- h.onFrame({ op: OP.Output, streamId: 4, seq: 4, payload: new TextEncoder().encode('live') })
-
- expect(sinks.data).toEqual([
- { streamId: 4, data: 'current' },
- { streamId: 4, data: 'live' }
- ])
- })
-
- it('throws when the host does not return a numeric streamId', async () => {
- const sock = fakeSocket({})
- const h = createClientHandlers(sock.socket, fakeSinks().sinks)
- await expect(h.create({ cols: 80, rows: 24 })).rejects.toThrow(/streamId/)
- })
-
- it('sends OP.Input frames for write with an incrementing seq', async () => {
- const sock = fakeSocket({ streamId: 3 })
- const h = createClientHandlers(sock.socket, fakeSinks().sinks)
- await h.create({ cols: 80, rows: 24 })
-
- h.write(3, 'ls\n')
- h.write(3, 'pwd\n')
-
- expect(sock.frames).toHaveLength(2)
- expect(sock.frames[0]).toMatchObject({ op: OP.Input, streamId: 3, seq: 0 })
- expect(Buffer.from(sock.frames[0].payload).toString('utf8')).toBe('ls\n')
- expect(sock.frames[1]).toMatchObject({ op: OP.Input, streamId: 3, seq: 1 })
- })
-
- it('sends OP.Resize frames as 2x uint16 LE (cols, rows)', async () => {
- const sock = fakeSocket({ streamId: 1 })
- const h = createClientHandlers(sock.socket, fakeSinks().sinks)
- await h.create({ cols: 80, rows: 24 })
-
- h.resize(1, 120, 40)
-
- expect(sock.frames).toHaveLength(1)
- const f = sock.frames[0]
- expect(f.op).toBe(OP.Resize)
- const view = new DataView(f.payload.buffer, f.payload.byteOffset, f.payload.byteLength)
- expect(view.getUint16(0, true)).toBe(120)
- expect(view.getUint16(2, true)).toBe(40)
- })
-
- it('ignores write/resize for unknown streams', async () => {
- const sock = fakeSocket()
- const h = createClientHandlers(sock.socket, fakeSinks().sinks)
- h.write(99, 'x')
- h.resize(99, 10, 10)
- expect(sock.frames).toHaveLength(0)
- })
-
- it('routes OP.Output frames to onData', async () => {
- const sock = fakeSocket({ streamId: 5 })
- const sinks = fakeSinks()
- const h = createClientHandlers(sock.socket, sinks.sinks)
- await h.create({ cols: 80, rows: 24 })
-
- h.onFrame({ op: OP.Output, streamId: 5, seq: 0, payload: new TextEncoder().encode('hello') })
-
- expect(sinks.data).toEqual([{ streamId: 5, data: 'hello' }])
- })
-
- it('routes OP.Error frames to onExit, parses {exitCode}, and drops the stream', async () => {
- const sock = fakeSocket({ streamId: 2 })
- const sinks = fakeSinks()
- const h = createClientHandlers(sock.socket, sinks.sinks)
- await h.create({ cols: 80, rows: 24 })
-
- h.onFrame({
- op: OP.Error,
- streamId: 2,
- seq: 0,
- payload: new TextEncoder().encode(JSON.stringify({ exitCode: 42 }))
- })
-
- expect(sinks.exits).toEqual([{ streamId: 2, exitCode: 42 }])
- // After exit the stream is forgotten → further writes are ignored.
- h.write(2, 'x')
- expect(sock.frames).toHaveLength(0)
- })
-
- it('kill sends RPC pty.kill and forgets the stream', async () => {
- const sock = fakeSocket({ streamId: 9 })
- const h = createClientHandlers(sock.socket, fakeSinks().sinks)
- await h.create({ cols: 80, rows: 24 })
-
- h.kill(9)
- expect(sock.rpcs).toContainEqual({ method: 'pty.kill', params: { streamId: 9 } })
-
- // After kill, input for the dropped stream is ignored.
- h.write(9, 'x')
- expect(sock.frames).toHaveLength(0)
- })
-
- it('ignores frames for unknown streams', () => {
- const sock = fakeSocket()
- const sinks = fakeSinks()
- const h = createClientHandlers(sock.socket, sinks.sinks)
- h.onFrame({ op: OP.Output, streamId: 1, seq: 0, payload: new TextEncoder().encode('x') })
- expect(sinks.data).toHaveLength(0)
- })
-})
diff --git a/test/remote/relay-e2e.test.ts b/test/remote/relay-e2e.test.ts
deleted file mode 100644
index bb2bb58c8..000000000
--- a/test/remote/relay-e2e.test.ts
+++ /dev/null
@@ -1,358 +0,0 @@
-// End-to-end integration test for the B4 relay (Task 8).
-//
-// Wires the REAL relay broker + REAL relay-socket protocol + a fake PTY end-to-end over real
-// WebSockets, and asserts a terminal stream works and stays E2EE.
-//
-// What it exercises:
-// - the REAL relay server (from the companion server repo — see SERVER_DIR below; the whole
-// suite is skipped when it isn't checked out) spawned as a child process on an
-// ephemeral port via `tsx`, trusting a test Ed25519 public key;
-// - a single-use pairing token minted INLINE in the same compact format the relay verifies
-// (`base64url(payloadJSON).base64url(ed25519 sig over the base64url-payload bytes)`);
-// - the host side: a real `connectRelay({role:'host'})` + the pure `createHostHandlers(...)`
-// backed by a FAKE pty that simply echoes input back as output;
-// - the client side: a real `connectRelay({role:'client'})` + the pure
-// `createClientHandlers(...)`;
-// - the full E2EE handshake + RPC/frame state machine over real `ws` sockets through the relay.
-//
-// Assertions: the client opens a stream (RPC `pty.create`), sends OP.Input "hello\n", receives
-// OP.Output echoing "hello", sends OP.Resize, then closes. AND: a passive observer of every
-// binary frame the host puts on the wire toward the relay can never find the plaintext "hello"
-// substring (the E2EE box differs from the plaintext bytes) — proving the relay never sees
-// plaintext.
-//
-// ---------------------------------------------------------------------------------------------
-// MANUAL SMOKE TEST (documented here, NOT automated — Task 8 Step 3):
-//
-// Two local nodeterm instances + the deployed (or a local) relay:
-// 1. Instance A (host): enable Host mode → the app mints a pairing token and connects to
-// the relay as the pending host → copy the generated OFFER string.
-// 2. Instance B (client): paste the OFFER → the app connects as the client, which triggers
-// the host<->client bridge over the relay.
-// 3. In B: open a Remote terminal node against that connection.
-// 4. Run a command on the HOST machine from B (e.g. `whoami`) and confirm the output shows
-// the host's identity (not the client's) — proving the PTY runs on A.
-// 5. Resize the remote terminal node (drag its corner) → the host PTY reflows.
-// 6. Close the remote node / disconnect → the client detaches; the host-side tmux session
-// survives (reopen reattaches).
-// Throughout, the relay only ever forwards opaque E2EE boxes — it never sees plaintext.
-// ---------------------------------------------------------------------------------------------
-
-import { afterAll, beforeAll, describe, expect, it } from 'vitest'
-import crypto from 'node:crypto'
-import path from 'node:path'
-import { spawn, type ChildProcess } from 'node:child_process'
-import { existsSync } from 'node:fs'
-import { createServer } from 'node:net'
-import { WebSocket } from 'ws'
-
-import { connectRelay, wrapWebSocket, type RelaySocket } from '../../src/main/remote/relay-socket'
-import { createHostHandlers, type HostPtyManager } from '../../src/main/remote/host-service'
-import { createClientHandlers } from '../../src/main/remote/client-service'
-import { genKeyPair, publicKeyToB64, type KeyPair } from '../../src/main/remote/e2ee'
-import { OP, type Frame } from '../../src/main/remote/framing'
-import type { PtyCreateOptions } from '../../src/shared/types'
-import type { DetachedSinks } from '../../src/main/pty-manager'
-
-// Absolute path to the companion server repo holding the REAL relay (not part of this repo —
-// the suite below is skipped when it isn't checked out alongside as ./nodebaseserver). Allow an
-// env override for unusual layouts / CI.
-const SERVER_DIR =
- process.env.NODETERM_SERVER_DIR || path.resolve('nodebaseserver')
-const RELAY_ENTRY = path.join(SERVER_DIR, 'src/relay/index.ts')
-const TSX_BIN = path.join(SERVER_DIR, 'node_modules/.bin/tsx')
-
-// Generous timeouts: spawning tsx + two ws handshakes need real wall-clock time.
-const SPAWN_TIMEOUT_MS = 20_000
-const HANDSHAKE_TIMEOUT_MS = 15_000
-
-// --- helpers -----------------------------------------------------------------
-
-function deferred<T>(): { promise: Promise<T>; resolve: (v: T) => void; reject: (e: Error) => void } {
- let resolve!: (v: T) => void
- let reject!: (e: Error) => void
- const promise = new Promise<T>((res, rej) => {
- resolve = res
- reject = rej
- })
- return { promise, resolve, reject }
-}
-
-// Find a free TCP port by binding to :0 and reading back the assigned port.
-function getEphemeralPort(): Promise<number> {
- return new Promise((resolve, reject) => {
- const srv = createServer()
- srv.unref()
- srv.on('error', reject)
- srv.listen(0, '127.0.0.1', () => {
- const addr = srv.address()
- if (addr && typeof addr === 'object') {
- const port = addr.port
- srv.close(() => resolve(port))
- } else {
- srv.close(() => reject(new Error('Could not determine an ephemeral port.')))
- }
- })
- })
-}
-
-// Mint a pairing token in the exact compact format the relay verifies
-// (mirrors the relay server's pairing-token module):
-// base64url(JSON {pairingId, licenseId, iat, exp}).base64url(ed25519 sig over the b64url bytes)
-function mintToken(privateKey: crypto.KeyObject, pairingId: string): string {
- const now = Math.floor(Date.now() / 1000)
- const payload = { pairingId, licenseId: 'test-license', iat: now, exp: now + 300 }
- const p = Buffer.from(JSON.stringify(payload)).toString('base64url')
- const sig = crypto.sign(null, Buffer.from(p), privateKey).toString('base64url')
- return `${p}.${sig}`
-}
-
-// Spawn the REAL relay as a child process; resolve once it logs that it is listening.
-function spawnRelay(port: number, publicKeyPem: string): Promise<ChildProcess> {
- const child = spawn(TSX_BIN, [RELAY_ENTRY], {
- cwd: SERVER_DIR,
- env: { ...process.env, PORT: String(port), RELAY_ENTITLEMENT_PUBLIC_KEY: publicKeyPem },
- stdio: ['ignore', 'pipe', 'pipe']
- })
-
- const ready = deferred<ChildProcess>()
- let settled = false
- const timer = setTimeout(() => {
- if (settled) return
- settled = true
- ready.reject(new Error(`Relay did not start within ${SPAWN_TIMEOUT_MS}ms.\n${stderr}`))
- }, SPAWN_TIMEOUT_MS)
-
- let stderr = ''
- child.stdout?.on('data', (buf: Buffer) => {
- if (!settled && buf.toString().includes('listening')) {
- settled = true
- clearTimeout(timer)
- ready.resolve(child)
- }
- })
- child.stderr?.on('data', (buf: Buffer) => {
- stderr += buf.toString()
- })
- child.on('exit', (code) => {
- if (settled) return
- settled = true
- clearTimeout(timer)
- ready.reject(new Error(`Relay exited early (code ${code}).\n${stderr}`))
- })
-
- return ready.promise
-}
-
-// Open a real ws to the relay carrying the token, wrap it as a RelayTransport, and tap every
-// outbound payload so the test can assert no plaintext ever crosses the wire.
-function openTappedTransport(
- baseUrl: string,
- token: string,
- sentSink: (data: string | Uint8Array) => void
-): { transport: ReturnType<typeof wrapWebSocket>; opened: Promise<void>; ws: WebSocket } {
- const sep = baseUrl.includes('?') ? '&' : '?'
- const ws = new WebSocket(`${baseUrl}${sep}token=${encodeURIComponent(token)}`)
- ws.binaryType = 'nodebuffer'
-
- const opened = deferred<void>()
- ws.on('open', () => opened.resolve())
- ws.on('error', (err) => opened.reject(err as Error))
-
- const wrapped = wrapWebSocket(ws)
- const transport = {
- get bufferedAmount() {
- return wrapped.bufferedAmount
- },
- send: (data: string | Uint8Array) => {
- sentSink(data)
- wrapped.send(data)
- },
- close: () => wrapped.close(),
- onMessage: wrapped.onMessage,
- onClose: wrapped.onClose
- }
- return { transport, opened: opened.promise, ws }
-}
-
-// A fake pty-manager: each created session echoes whatever is written to it straight back as
-// output (so OP.Input "hello\n" -> OP.Output "hello\n"). No node-pty, no tmux.
-function makeEchoPty(): HostPtyManager {
- const sinks = new Map<string, DetachedSinks>()
- let counter = 0
- return {
- createDetached(_options: PtyCreateOptions, s: DetachedSinks): string {
- const sessionId = `echo-${++counter}`
- sinks.set(sessionId, s)
- return sessionId
- },
- attachDetached(_persistKey: string, s: DetachedSinks): string {
- // Same echo semantics as create — the client now opens streams via pty.attach.
- const sessionId = `echo-${++counter}`
- sinks.set(sessionId, s)
- return sessionId
- },
- async captureSnapshot(): Promise<string> {
- // No prior screen in the fake; an empty snapshot still exercises the Start→End path.
- return ''
- },
- write(sessionId: string, data: string): void {
- sinks.get(sessionId)?.onData(data)
- },
- resize(): void {
- // No-op: the echo pty has no real geometry; the test only asserts the frame arrives.
- },
- setFlow(): void {
- // No-op: no real backpressure in the fake.
- },
- kill(sessionId: string): void {
- const s = sinks.get(sessionId)
- sinks.delete(sessionId)
- s?.onExit(0)
- }
- }
-}
-
-// --- test --------------------------------------------------------------------
-
-describe.skipIf(!existsSync(RELAY_ENTRY))('B4 relay end-to-end (real relay + real protocol + fake pty)', () => {
- let relay: ChildProcess | null = null
- let baseUrl = ''
- let token = ''
- let hostKeys: KeyPair
- let clientKeys: KeyPair
- const hostSentFrames: Uint8Array[] = []
-
- let hostSocket: RelaySocket | null = null
- let clientSocket: RelaySocket | null = null
-
- beforeAll(async () => {
- const { privateKey, publicKey } = crypto.generateKeyPairSync('ed25519')
- const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }) as string
-
- const port = await getEphemeralPort()
- baseUrl = `ws://127.0.0.1:${port}`
- relay = await spawnRelay(port, publicKeyPem)
-
- // SAME token (same pairingId) for both ends: the relay treats the first connector as the
- // host and the second as the client.
- token = mintToken(privateKey, 'pairing-e2e-1')
-
- hostKeys = genKeyPair()
- clientKeys = genKeyPair()
- }, SPAWN_TIMEOUT_MS + 5_000)
-
- afterAll(() => {
- hostSocket?.close()
- clientSocket?.close()
- relay?.kill('SIGKILL')
- })
-
- it('streams a remote PTY over E2EE and never leaks plaintext to the relay', async () => {
- // --- host connects FIRST (becomes the pending host) ---
- const hostTap = openTappedTransport(baseUrl, token, (data) => {
- if (data instanceof Uint8Array) hostSentFrames.push(Uint8Array.from(data))
- })
- await hostTap.opened
-
- const hostReady = deferred<void>()
- let hostHandlers: ReturnType<typeof createHostHandlers> | null = null
- hostSocket = connectRelay({
- url: baseUrl,
- token,
- role: 'host',
- ourKeys: hostKeys,
- transport: hostTap.transport,
- onReady: () => hostReady.resolve(),
- onRpc: (req) => hostHandlers?.onRpc(req),
- onFrame: (frame) => hostHandlers?.onFrame(frame),
- onClose: () => hostHandlers?.closeAll()
- })
- hostHandlers = createHostHandlers(makeEchoPty(), hostSocket)
-
- // --- client connects SECOND (triggers the bridge) ---
- const clientTap = openTappedTransport(baseUrl, token, () => {})
- await clientTap.opened
-
- const clientReady = deferred<void>()
- const dataEvents: { streamId: number; data: string }[] = []
- const exitEvents: { streamId: number; exitCode: number }[] = []
- let clientHandlers: ReturnType<typeof createClientHandlers> | null = null
- clientSocket = connectRelay({
- url: baseUrl,
- token,
- role: 'client',
- ourKeys: clientKeys,
- theirPubB64: publicKeyToB64(hostKeys.publicKey),
- transport: clientTap.transport,
- onReady: () => clientReady.resolve(),
- onRpc: () => {
- // The host never initiates RPC toward the client in this MVP.
- },
- onFrame: (frame: Frame) => clientHandlers?.onFrame(frame),
- onClose: () => clientHandlers?.closeAll()
- })
- clientHandlers = createClientHandlers(clientSocket, {
- onData: (streamId, data) => dataEvents.push({ streamId, data }),
- onExit: (streamId, exitCode) => exitEvents.push({ streamId, exitCode })
- })
-
- // Both ends complete the E2EE handshake.
- await withTimeout(Promise.all([hostReady.promise, clientReady.promise]), HANDSHAKE_TIMEOUT_MS, 'handshake')
-
- // --- client opens a stream via RPC pty.attach (persistKey = host node id) ---
- const streamId = await withTimeout(
- clientHandlers.create({ cols: 80, rows: 24, persistKey: 'node-e2e' }),
- HANDSHAKE_TIMEOUT_MS,
- 'pty.attach'
- )
- expect(typeof streamId).toBe('number')
-
- // --- client sends OP.Input "hello\n" and awaits the echoed OP.Output ---
- clientHandlers.write(streamId, 'hello\n')
- await waitFor(() => dataEvents.some((e) => e.data.includes('hello')), HANDSHAKE_TIMEOUT_MS, 'echo output')
-
- const echoed = dataEvents.filter((e) => e.streamId === streamId).map((e) => e.data).join('')
- expect(echoed).toContain('hello')
-
- // --- client sends OP.Resize (host echo pty ignores geometry; assert it does not throw/close) ---
- clientHandlers.resize(streamId, 120, 40)
- // Give the resize frame time to traverse the relay and reach the host.
- await delay(200)
-
- // --- E2EE assertion: no host->relay binary frame contains the plaintext "hello" ---
- expect(hostSentFrames.length).toBeGreaterThan(0)
- const needle = Buffer.from('hello')
- const leaked = hostSentFrames.find((frame) => Buffer.from(frame).includes(needle))
- expect(leaked, 'a host->relay frame leaked the plaintext "hello"').toBeUndefined()
-
- // Sanity: the same plaintext, unencrypted, WOULD be findable — proving the assertion above
- // is meaningful (not just because "hello" never crossed the wire).
- expect(Buffer.from('hello\n').includes(needle)).toBe(true)
-
- // --- close ---
- clientSocket.close()
- hostSocket.close()
- }, HANDSHAKE_TIMEOUT_MS + 10_000)
-})
-
-// --- timing utilities --------------------------------------------------------
-
-function delay(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms))
-}
-
-function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
- return Promise.race([
- promise,
- new Promise<T>((_, reject) => setTimeout(() => reject(new Error(`Timed out waiting for ${label}.`)), ms))
- ])
-}
-
-async function waitFor(cond: () => boolean, ms: number, label: string): Promise<void> {
- const start = Date.now()
- while (!cond()) {
- if (Date.now() - start > ms) throw new Error(`Timed out waiting for ${label}.`)
- await delay(25)
- }
-}
diff --git a/test/remote/remote-fs.test.ts b/test/remote/remote-fs.test.ts
deleted file mode 100644
index df39ec429..000000000
--- a/test/remote/remote-fs.test.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-// Remote filesystem round-trip (Task 5).
-//
-// Wires the pure CLIENT handlers' `fs.*` RPC senders straight into the pure HOST handlers' `fs.*`
-// RPC handlers via a fake relay pair (no sockets, no Electron). The host handlers run the REAL
-// shared fs-ops against a real temp dir, so this proves the full client→host→fs round-trip:
-// client.fsWrite(tmp, 'hi') → host writes the real file
-// client.fsRead(tmp) → host reads it back → 'hi'
-// client.fsList(tmpdir) → host lists it → includes the file
-// client.fsReadBinary(tmp) → host reads base64 → decodes to 'hi'
-
-import { afterAll, beforeAll, describe, expect, it } from 'vitest'
-import { promises as fs } from 'node:fs'
-import os from 'node:os'
-import path from 'node:path'
-
-import {
- createHostHandlers,
- type HostPtyManager,
- type HostRelaySocket
-} from '../../src/main/remote/host-service'
-import {
- createClientHandlers,
- type ClientRelaySocket,
- type ClientSessionSinks
-} from '../../src/main/remote/client-service'
-
-// The fs RPCs never touch the PTY; a no-op pty-manager satisfies the host's required shape.
-function noopPty(): HostPtyManager {
- return {
- createDetached: () => 'pty-1',
- attachDetached: () => 'pty-1',
- captureSnapshot: async () => '',
- write: () => {},
- resize: () => {},
- setFlow: () => {},
- kill: () => {}
- }
-}
-
-const noopSinks: ClientSessionSinks = { onData: () => {}, onExit: () => {} }
-
-// A fake relay pair: the client's `rpc(method, params)` is routed straight into the host handlers'
-// `onRpc` (resolved lazily so the host can be built after the pair), and the host's
-// `respond(id, ok, body)` resolves the matching client promise. This is the synchronous in-memory
-// equivalent of the relay carrying the request/response.
-function fakePair(getHost: () => ReturnType<typeof createHostHandlers>) {
- let counter = 0
- const pending = new Map<string, (body: unknown) => void>()
-
- const hostSocket: HostRelaySocket = {
- respond: (id, _ok, body) => pending.get(id)?.(body),
- sendFrame: () => true
- }
-
- const clientSocket: ClientRelaySocket = {
- rpc: (method, params) =>
- new Promise((resolve) => {
- const id = `rpc-${++counter}`
- pending.set(id, resolve)
- getHost().onRpc({ id, method, params })
- }),
- sendFrame: () => true
- }
-
- return { hostSocket, clientSocket }
-}
-
-describe('remote filesystem round-trip (client fs RPC → host fs-ops → real temp dir)', () => {
- let dir = ''
-
- beforeAll(async () => {
- dir = await fs.mkdtemp(path.join(os.tmpdir(), 'nodeterm-remote-fs-'))
- })
-
- afterAll(async () => {
- await fs.rm(dir, { recursive: true, force: true })
- })
-
- it('writes, reads, lists and reads-binary a host file over the relay', async () => {
- // Build the host handlers first so the fake pair can route the client's RPCs into them; then
- // wire the host's `respond` back through the same pair.
- let host!: ReturnType<typeof createHostHandlers>
- const pair = fakePair(() => host)
- // The temp dir is the shared root so the client's fs.* RPCs are permitted (fs jail).
- host = createHostHandlers(noopPty(), pair.hostSocket, undefined, () => [dir])
- const client = createClientHandlers(pair.clientSocket, noopSinks)
-
- const file = path.join(dir, 'note.txt')
-
- // write
- expect(await client.fsWrite(file, 'hi')).toBe(true)
- expect(await fs.readFile(file, 'utf-8')).toBe('hi')
-
- // read
- expect(await client.fsRead(file)).toBe('hi')
-
- // list includes the new file
- const entries = await client.fsList(dir)
- expect(entries.map((e) => e.name)).toContain('note.txt')
- expect(entries.find((e) => e.name === 'note.txt')?.dir).toBe(false)
-
- // readBinary round-trips through base64
- const b64 = await client.fsReadBinary(file)
- expect(Buffer.from(b64, 'base64').toString('utf-8')).toBe('hi')
- })
-
- it('degrades to empty/false on host fs errors (read/list/write of a bad path)', async () => {
- let host!: ReturnType<typeof createHostHandlers>
- const pair = fakePair(() => host)
- host = createHostHandlers(noopPty(), pair.hostSocket, undefined, () => [dir])
- const client = createClientHandlers(pair.clientSocket, noopSinks)
-
- expect(await client.fsRead(path.join(dir, 'does-not-exist.txt'))).toBe('')
- expect(await client.fsList(path.join(dir, 'no-such-dir'))).toEqual([])
- expect(await client.fsWrite(path.join(dir, 'no', 'such', 'parent.txt'), 'x')).toBe(false)
- })
-})