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(b4): host service serves PTYs over the relay
enes36e442cf6c7f
diff --git a/src/main/index.ts b/src/main/index.tsindex 1c0d74f80..4bd082f64 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -25,6 +25,7 @@ import { initBridge } from './bridge'import { initTelemetry } from './telemetry'import { initClaudeUsage } from './claude-usage'import { initLicense } from './license'+import { initRemoteHost } from './remote/host-service'const settingsStore = new SettingsStore()const ptyManager = new PtyManager()@@ -296,6 +297,7 @@ app.whenReady().then(async () => {initClaudeUsage(win)initTelemetry(() => settingsStore.get())initLicense(win)+ initRemoteHost(win, ptyManager)app.on('activate', () => {if (BrowserWindow.getAllWindows().length === 0) createWindow()diff --git a/src/main/license.ts b/src/main/license.tsindex 47b26489b..d53abd729 100644--- a/src/main/license.ts+++ b/src/main/license.ts@@ -112,6 +112,20 @@ async function getJson(path: string): Promise<{ active?: boolean; token?: string}}+/**+ * The stored entitlement token (the compact Ed25519 token minted by our API), or null when+ * none is stored. Other main-process features (e.g. the relay pairing call) read this to prove+ * entitlement to the server. Returns the raw stored value — verify with `isPremium()` for gating.+ */+export function getStoredEntitlement(): string | null {+ return load().token ?? null+}++/** True when a valid, unexpired Pro entitlement is stored (offline-verified). Gates premium features. */+export function isPremium(): boolean {+ return verify(load().token) !== null+}+export function initLicense(win: BrowserWindow): void {const deviceId = getDeviceId()const broadcast = (s: LicenseStatus) => {diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.tsindex 153e92e1c..d5769f1a4 100644--- a/src/main/pty-manager.ts+++ b/src/main/pty-manager.ts@@ -70,13 +70,24 @@ function sessionName(persistKey: string): string {interface Session {proc: pty.IPty- webContentsId: number+ /** Renderer webContents to stream output to over IPC, or null for a detached (host) session. */+ webContentsId: number | null+ /** Detached sinks: when set, output/exit go to these callbacks instead of IPC (relay host). */+ onData?: (data: string) => void+ onExit?: (exitCode: number) => void/** Pending output chunks, coalesced into one IPC message per flush. */buf: string[]bufBytes: numberflushTimer: ReturnType<typeof setTimeout> | null}+/** Sinks for a detached session whose output is served somewhere other than the renderer+ * (the relay host). The PTY is otherwise identical to a normal session. */+export interface DetachedSinks {+ onData(data: string): void+ onExit(exitCode: number): void+}+// Output coalescing: a fast producer (e.g. `yes`, a verbose build, tmux full-screen// redraws) emits many small chunks. Buffering them for one short window collapses N// IPC messages + N xterm writes into one, which is the single hottest path in the app.@@ -145,6 +156,24 @@ export class PtyManager {}private create(webContentsId: number, options: PtyCreateOptions): string {+ return this.spawnSession(options, webContentsId, undefined)+ }++ /**+ * Spawn a PTY whose output/exit are delivered to `sinks` instead of the renderer. Used by+ * the relay host (Task 6) to serve PTYs over the E2EE transport: the host pipes `onData`+ * into `OP.Output` frames and maps client RPC/frames back to `write`/`resize`/`kill`. The+ * spawn (tmux session, hook env, shell selection) is identical to a normal renderer session.+ */+ createDetached(options: PtyCreateOptions, sinks: DetachedSinks): string {+ return this.spawnSession(options, null, sinks)+ }++ private spawnSession(+ options: PtyCreateOptions,+ webContentsId: number | null,+ sinks: DetachedSinks | undefined+ ): string {const sessionId = `pty-${++this.counter}`const cwd = options.cwd || os.homedir()@@ -208,14 +237,26 @@ export class PtyManager {env})- const session: Session = { proc, webContentsId, buf: [], bufBytes: 0, flushTimer: null }+ const session: Session = {+ proc,+ webContentsId,+ onData: sinks?.onData,+ onExit: sinks?.onExit,+ buf: [],+ bufBytes: 0,+ flushTimer: null+ }this.sessions.set(sessionId, session)proc.onData((data) => this.queueData(sessionId, session, data))proc.onExit(({ exitCode }) => {this.flush(sessionId, session) // deliver any buffered output before the exit signal- this.send(webContentsId, IPC.ptyExit(sessionId), exitCode)+ if (session.onExit) {+ session.onExit(exitCode)+ } else if (webContentsId !== null) {+ this.send(webContentsId, IPC.ptyExit(sessionId), exitCode)+ }this.sessions.delete(sessionId)})@@ -243,7 +284,11 @@ export class PtyManager {const data = session.buf.join('')session.buf = []session.bufBytes = 0- this.send(session.webContentsId, IPC.ptyData(sessionId), data)+ if (session.onData) {+ session.onData(data)+ } else if (session.webContentsId !== null) {+ this.send(session.webContentsId, IPC.ptyData(sessionId), data)+ }}/**@@ -252,7 +297,7 @@ export class PtyManager {* without bound. node-pty pause()/resume() stops/starts reading the pty fd; the OS* pipe applies backpressure to the producing process.*/- private setFlow(sessionId: string, resume: boolean): void {+ setFlow(sessionId: string, resume: boolean): void {const session = this.sessions.get(sessionId)if (!session) returntry {@@ -263,11 +308,11 @@ export class PtyManager {}}- private write(sessionId: string, data: string): void {+ write(sessionId: string, data: string): void {this.sessions.get(sessionId)?.proc.write(data)}- private resize(sessionId: string, cols: number, rows: number): void {+ resize(sessionId: string, cols: number, rows: number): void {const session = this.sessions.get(sessionId)if (!session) return// cols/rows must be at least 1, otherwise node-pty throws.diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsnew file mode 100644index 000000000..090915c05--- /dev/null+++ b/src/main/remote/host-service.ts@@ -0,0 +1,356 @@+// Host service — serve local PTYs over the relay (main process).+//+// On "host mode" the app: (1) gates on a valid Pro entitlement, (2) mints a single-use+// pairing token from our API with the stored entitlement, (3) connects to the relay as the+// HOST (so it becomes the pending host the client later joins to trigger the bridge), and+// (4) returns the pairing OFFER string for the user to hand to a client.+//+// While connected, the host maps the client's E2EE RPC/frames onto the existing pty-manager:+// - RPC `pty.create {cols, rows, cwd?, shell?, persistKey?, agentId?}` -> `createDetached`,+// returning `{ streamId }`. The PTY's output is piped into `OP.Output` frames; its exit+// into an `OP.Error` frame (then the stream is dropped).+// - `OP.Input` frame -> `write(sessionId, <utf-8 payload>)`+// - `OP.Resize` frame -> `resize(sessionId, cols, rows)` (payload = 2x uint16 LE)+// - RPC `pty.kill {streamId}` -> `kill(sessionId)`+// Output backpressure: when `sendFrame` returns false the host pauses the PTY via `setFlow`+// and resumes it on the next successful send.+//+// This file is glue over already-tested units (relay-socket, framing, pairing, pty-manager).+// The pure RPC/frame -> pty-manager mapping lives in `createHostHandlers` so it is unit-+// testable with fakes; `initRemoteHost` wires it to IPC, the license gate, and the API call.++import { promises as fs } from 'fs'+import path from 'path'+import { app, ipcMain, type BrowserWindow } from 'electron'+import { IPC } from '../../shared/ipc'+import type { PtyCreateOptions } from '../../shared/types'+import type { AgentId } from '../../shared/agents/config'+import { PtyManager, type DetachedSinks } from '../pty-manager'+import { getStoredEntitlement, isPremium } from '../license'+import { genKeyPair, publicKeyToB64, type KeyPair } from './e2ee'+import { OP, type Frame } from './framing'+import { encodeOffer } from './pairing'+import { connectRelay, type RelaySocket, type RpcRequest } from './relay-socket'++// Default relay endpoint; `NODETERM_RELAY_URL` overrides it (mirrors license.ts's API_BASE /+// CHECKOUT_URL env-override pattern — used both as the dev gate and for local testing).+const RELAY_URL = process.env.NODETERM_RELAY_URL || 'wss://relay.nodeterm.dev'++const API_BASE = process.env.NODETERM_API_BASE || 'https://api.nodeterm.dev'++const textEncoder = new TextEncoder()+const textDecoder = new TextDecoder()++// --- pure host handlers (RPC/frame <-> pty-manager) -------------------------++// The slice of pty-manager the host needs. PtyManager satisfies this; tests pass a fake.+export interface HostPtyManager {+ createDetached(options: PtyCreateOptions, sinks: DetachedSinks): string+ write(sessionId: string, data: string): void+ resize(sessionId: string, cols: number, rows: number): void+ setFlow(sessionId: string, resume: boolean): void+ kill(sessionId: string): void+}++// The slice of RelaySocket the host needs to answer the client.+export interface HostRelaySocket {+ respond(id: string, ok: boolean, body: unknown): void+ sendFrame(op: number, streamId: number, seq: number, payload: Uint8Array): boolean+}++export interface HostHandlers {+ onRpc(req: RpcRequest): void+ onFrame(frame: Frame): void+ /** Kill every live PTY this host opened (called on disconnect / stop). */+ closeAll(): void+}++interface Stream {+ sessionId: string+ /** Outbound OP.Output sequence counter. */+ seq: number+ /** True while the PTY is paused due to relay backpressure. */+ paused: boolean+}++function asRecord(value: unknown): Record<string, unknown> {+ return value && typeof value === 'object' ? (value as Record<string, unknown>) : {}+}++function num(value: unknown, fallback: number): number {+ return typeof value === 'number' && Number.isFinite(value) ? value : fallback+}++function str(value: unknown): string | undefined {+ return typeof value === 'string' ? value : undefined+}++/**+ * Build the RPC/frame router that maps a client's requests onto a pty-manager. Pure over its+ * two injected dependencies (no sockets, no Electron) so it can be unit-tested with fakes.+ *+ * `nextStreamId` lets tests assert deterministic ids; production uses a monotonic counter.+ */+export function createHostHandlers(pty: HostPtyManager, socket: HostRelaySocket): HostHandlers {+ // streamId -> Stream, plus the reverse (sessionId -> streamId) so PTY callbacks resolve fast.+ const streams = new Map<number, Stream>()+ const bySession = new Map<string, number>()+ let streamCounter = 0++ function dropStream(streamId: number): void {+ const stream = streams.get(streamId)+ if (!stream) return+ streams.delete(streamId)+ bySession.delete(stream.sessionId)+ }++ function handleCreate(req: RpcRequest): void {+ const p = asRecord(req.params)+ const options: PtyCreateOptions = {+ cols: Math.max(1, num(p.cols, 80)),+ rows: Math.max(1, num(p.rows, 24)),+ cwd: str(p.cwd),+ shell: str(p.shell),+ persistKey: str(p.persistKey),+ agentId: str(p.agentId) as AgentId | undefined+ }++ const streamId = ++streamCounter+ const stream: Stream = { sessionId: '', seq: 0, paused: false }++ const sinks: DetachedSinks = {+ onData: (data) => {+ const bytes = textEncoder.encode(data)+ const ok = socket.sendFrame(OP.Output, streamId, stream.seq++, bytes)+ if (!ok && !stream.paused) {+ // Relay buffer is full — pause the PTY so the OS pipe backpressures the producer.+ stream.paused = true+ pty.setFlow(stream.sessionId, false)+ } else if (ok && stream.paused) {+ stream.paused = false+ pty.setFlow(stream.sessionId, true)+ }+ },+ onExit: (exitCode) => {+ // Signal exit as an OP.Error frame carrying the code, then forget the stream.+ socket.sendFrame(+ OP.Error,+ streamId,+ stream.seq++,+ textEncoder.encode(JSON.stringify({ exitCode }))+ )+ dropStream(streamId)+ }+ }++ let sessionId: string+ try {+ sessionId = pty.createDetached(options, sinks)+ } catch (err) {+ socket.respond(req.id, false, { message: (err as Error).message })+ return+ }+ stream.sessionId = sessionId+ streams.set(streamId, stream)+ bySession.set(sessionId, streamId)+ socket.respond(req.id, true, { streamId })+ }++ function handleKill(req: RpcRequest): void {+ const streamId = num(asRecord(req.params).streamId, -1)+ const stream = streams.get(streamId)+ if (stream) {+ pty.kill(stream.sessionId)+ dropStream(streamId)+ }+ socket.respond(req.id, true, {})+ }++ return {+ onRpc(req) {+ switch (req.method) {+ case 'pty.create':+ handleCreate(req)+ break+ case 'pty.kill':+ handleKill(req)+ break+ default:+ socket.respond(req.id, false, { message: `Unknown method: ${req.method}` })+ }+ },+ onFrame(frame) {+ const stream = streams.get(frame.streamId)+ if (!stream) return+ if (frame.op === OP.Input) {+ pty.write(stream.sessionId, textDecoder.decode(frame.payload))+ return+ }+ if (frame.op === OP.Resize) {+ // Payload is 2x uint16 LE: cols, rows.+ if (frame.payload.length >= 4) {+ const view = new DataView(+ frame.payload.buffer,+ frame.payload.byteOffset,+ frame.payload.byteLength+ )+ pty.resize(stream.sessionId, view.getUint16(0, true), view.getUint16(2, true))+ }+ }+ },+ closeAll() {+ for (const stream of streams.values()) {+ pty.kill(stream.sessionId)+ }+ streams.clear()+ bySession.clear()+ }+ }+}++// --- pairing-token mint ------------------------------------------------------++interface PairTokenResponse {+ pairingId: string+ pairingToken: string+ exp: number+}++// Mint a single-use pairing token from our API, proving entitlement with the stored token.+async function mintPairingToken(entitlement: string): Promise<PairTokenResponse> {+ const ctrl = new AbortController()+ const timer = setTimeout(() => ctrl.abort(), 8000)+ let res: Response+ try {+ res = await fetch(`${API_BASE}/v1/pair/token`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ entitlement }),+ signal: ctrl.signal+ })+ } catch {+ throw new Error('Could not reach the pairing server.')+ } finally {+ clearTimeout(timer)+ }+ const json = (await res.json().catch(() => ({}))) as Partial<PairTokenResponse> & { error?: string }+ if (!res.ok || !json.pairingToken) {+ throw new Error(json.error ? `Pairing failed: ${json.error}` : 'Pairing failed.')+ }+ return { pairingId: json.pairingId ?? '', pairingToken: json.pairingToken, exp: json.exp ?? 0 }+}++// --- persisted host keypair --------------------------------------------------++function keyFile(): string {+ return path.join(app.getPath('userData'), 'remote-host-key.json')+}++// Load the long-lived host NaCl keypair, generating + persisting it on first use. The public+// key is pinned in every offer, so it must be stable across runs.+async function loadOrCreateKeyPair(): Promise<KeyPair> {+ try {+ const raw = JSON.parse(await fs.readFile(keyFile(), 'utf-8')) as {+ publicKey?: string+ secretKey?: string+ }+ if (raw.publicKey && raw.secretKey) {+ return {+ publicKey: Uint8Array.from(Buffer.from(raw.publicKey, 'base64')),+ secretKey: Uint8Array.from(Buffer.from(raw.secretKey, 'base64'))+ }+ }+ } catch {+ // No (valid) stored key — generate a fresh one below.+ }+ const keys = genKeyPair()+ await fs+ .writeFile(+ keyFile(),+ JSON.stringify({+ publicKey: Buffer.from(keys.publicKey).toString('base64'),+ secretKey: Buffer.from(keys.secretKey).toString('base64')+ }),+ 'utf-8'+ )+ .catch(() => {})+ return keys+}++// --- dev gate ----------------------------------------------------------------++// Never hit the real relay/API from an unpackaged build unless a relay is explicitly targeted+// (mirrors license.ts's `allowed()` gate). Packaged builds are always allowed.+function relayAllowed(): boolean {+ return app.isPackaged || !!process.env.NODETERM_RELAY_URL+}++// --- IPC wiring --------------------------------------------------------------++/**+ * Wire the host-mode IPC. `remote:host:start` gates on Pro, mints a pairing token, connects to+ * the relay as host, and returns the offer string. `remote:host:stop` closes the relay socket+ * (which kills the served PTYs and drops the client's access).+ */+export function initRemoteHost(_win: BrowserWindow, ptyManager: PtyManager): void {+ let socket: RelaySocket | null = null+ let handlers: HostHandlers | null = null++ function teardown(): void {+ handlers?.closeAll()+ handlers = null+ socket?.close()+ socket = null+ }++ ipcMain.handle(IPC.remoteHostStart, async (): Promise<{ offer: string }> => {+ if (!isPremium()) {+ throw new Error('Remote access requires nodeterm Pro.')+ }+ if (!relayAllowed()) {+ throw new Error('Remote access is unavailable in development builds (set NODETERM_RELAY_URL).')+ }+ const entitlement = getStoredEntitlement()+ if (!entitlement) {+ throw new Error('No entitlement found — please re-activate nodeterm Pro.')+ }++ // Already hosting → tear the old session down before starting a fresh one.+ teardown()++ const keys = await loadOrCreateKeyPair()+ const { pairingToken } = await mintPairingToken(entitlement)++ // Connect FIRST and register as the pending host (the client joins later to trigger the+ // bridge). The RPC/frame handlers are bound to this socket once it is created.+ socket = connectRelay({+ url: RELAY_URL,+ token: pairingToken,+ role: 'host',+ ourKeys: keys,+ onReady: () => {+ // Bridge established with a client. Nothing extra to do — handlers are already live.+ },+ onRpc: (req) => handlers?.onRpc(req),+ onFrame: (frame) => handlers?.onFrame(frame),+ onClose: () => {+ // The client (or relay) dropped — kill served PTYs. relay-socket may reconnect; the+ // handlers stay bound to the same socket object across reconnects.+ handlers?.closeAll()+ }+ })+ handlers = createHostHandlers(ptyManager, socket)++ return {+ offer: encodeOffer({+ relayEndpoint: RELAY_URL,+ pairingToken,+ hostPublicKeyB64: publicKeyToB64(keys.publicKey)+ })+ }+ })++ ipcMain.handle(IPC.remoteHostStop, () => {+ teardown()+ })+}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 5b842b975..860701969 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -169,6 +169,10 @@ const api: NodeTerminalApi = {readTranscript: (sessionId, cwd) =>ipcRenderer.invoke(IPC.claudeReadTranscript, sessionId, cwd)},+ remoteHost: {+ start: () => ipcRenderer.invoke(IPC.remoteHostStart),+ stop: () => ipcRenderer.invoke(IPC.remoteHostStop)+ },bridge: {configPath: () => ipcRenderer.invoke(IPC.bridgeConfigPath),setTopology: (topology) => ipcRenderer.invoke(IPC.bridgeSetTopology, topology),diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex ec819d36c..138f13385 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -77,5 +77,7 @@ export const IPC = {gitCommitFiles: 'git:commit-files',gitRemoteCommitUrl: 'git:remote-commit-url',shellOpenExternal: 'shell:open-external',- commitGenerate: 'commit:generate'+ commitGenerate: 'commit:generate',+ remoteHostStart: 'remote:host:start',+ remoteHostStop: 'remote:host:stop'} as constdiff --git a/src/shared/types.ts b/src/shared/types.tsindex 1de8b244b..1be740e3d 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -517,6 +517,17 @@ export interface LicenseApi {onChange(listener: (s: LicenseStatus) => void): () => void}+export interface RemoteHostApi {+ /**+ * Enter host mode: mint a pairing token, connect to the relay as the host, and return the+ * pairing offer string (`nodeterm://pair?code=…`) to hand to a client. Rejects if the device+ * is not entitled to Pro (or in a dev build without NODETERM_RELAY_URL).+ */+ start(): Promise<{ offer: string }>+ /** Leave host mode: close the relay connection (ends served PTYs, drops client access). */+ stop(): Promise<void>+}+export interface NodeTerminalApi {pty: PtyApiworkspace: WorkspaceApi@@ -533,6 +544,7 @@ export interface NodeTerminalApi {usage: UsageApicontext: ContextApiclaude: ClaudeApi+ remoteHost: RemoteHostApi/** Fires when the user presses Cmd/Ctrl+M (toggle markdown view). Returns unsubscribe. */onMarkdownToggle(listener: () => void): () => void/** Fires when the user presses Cmd/Ctrl+W (close selected node). Returns unsubscribe. */diff --git a/test/remote/host-handlers.test.ts b/test/remote/host-handlers.test.tsnew file mode 100644index 000000000..5429f164a--- /dev/null+++ b/test/remote/host-handlers.test.ts@@ -0,0 +1,166 @@+import { describe, it, expect, vi } from 'vitest'+import {+ createHostHandlers,+ type HostPtyManager,+ type HostRelaySocket+} from '../../src/main/remote/host-service'+import { OP } from '../../src/main/remote/framing'+import type { DetachedSinks } from '../../src/main/pty-manager'+import type { PtyCreateOptions } from '../../src/shared/types'++// A fake pty-manager that records calls and lets the test fire the captured sinks.+function fakePty() {+ const calls: { method: string; args: unknown[] }[] = []+ let lastSinks: DetachedSinks | null = null+ let lastOptions: PtyCreateOptions | null = null+ let counter = 0+ const mgr: HostPtyManager = {+ createDetached(options, sinks) {+ lastOptions = options+ lastSinks = sinks+ const id = `pty-${++counter}`+ calls.push({ method: 'createDetached', args: [options, id] })+ return id+ },+ write: (sessionId, data) => calls.push({ method: 'write', args: [sessionId, data] }),+ resize: (sessionId, cols, rows) =>+ calls.push({ method: 'resize', args: [sessionId, cols, rows] }),+ setFlow: (sessionId, resume) => calls.push({ method: 'setFlow', args: [sessionId, resume] }),+ kill: (sessionId) => calls.push({ method: 'kill', args: [sessionId] })+ }+ return {+ mgr,+ calls,+ sinks: () => lastSinks!,+ options: () => lastOptions!+ }+}++function fakeSocket(sendOk = true) {+ const responses: { id: string; ok: boolean; body: unknown }[] = []+ const frames: { op: number; streamId: number; seq: number; payload: Uint8Array }[] = []+ const socket: HostRelaySocket = {+ respond: (id, ok, body) => responses.push({ id, ok, body }),+ sendFrame: (op, streamId, seq, payload) => {+ frames.push({ op, streamId, seq, payload })+ return sendOk+ }+ }+ return { socket, responses, frames }+}++const resizePayload = (cols: number, rows: number) => {+ const buf = new Uint8Array(4)+ const view = new DataView(buf.buffer)+ view.setUint16(0, cols, true)+ view.setUint16(2, rows, true)+ return buf+}++describe('createHostHandlers', () => {+ it('maps pty.create to createDetached and returns a streamId', () => {+ const pty = fakePty()+ const sock = fakeSocket()+ const h = createHostHandlers(pty.mgr, sock.socket)++ h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 100, rows: 30, cwd: '/tmp' } })++ expect(pty.options()).toMatchObject({ cols: 100, rows: 30, cwd: '/tmp' })+ expect(sock.responses).toEqual([{ id: 'r1', ok: true, body: { streamId: 1 } }])+ })++ it('pipes PTY output into OP.Output frames with an incrementing seq', () => {+ const pty = fakePty()+ const sock = fakeSocket()+ const h = createHostHandlers(pty.mgr, sock.socket)+ h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 80, rows: 24 } })++ pty.sinks().onData('hello')+ pty.sinks().onData('world')++ expect(sock.frames).toHaveLength(2)+ expect(sock.frames[0]).toMatchObject({ op: OP.Output, streamId: 1, seq: 0 })+ expect(Buffer.from(sock.frames[0].payload).toString('utf8')).toBe('hello')+ expect(sock.frames[1]).toMatchObject({ op: OP.Output, streamId: 1, seq: 1 })+ })++ it('routes OP.Input frames to write and OP.Resize frames to resize', () => {+ const pty = fakePty()+ const sock = fakeSocket()+ const h = createHostHandlers(pty.mgr, sock.socket)+ h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 80, rows: 24 } })++ h.onFrame({ op: OP.Input, streamId: 1, seq: 0, payload: new TextEncoder().encode('ls\n') })+ h.onFrame({ op: OP.Resize, streamId: 1, seq: 0, payload: resizePayload(120, 40) })++ expect(pty.calls).toContainEqual({ method: 'write', args: ['pty-1', 'ls\n'] })+ expect(pty.calls).toContainEqual({ method: 'resize', args: ['pty-1', 120, 40] })+ })++ it('ignores frames for unknown streams', () => {+ const pty = fakePty()+ const sock = fakeSocket()+ const h = createHostHandlers(pty.mgr, sock.socket)+ h.onFrame({ op: OP.Input, streamId: 99, seq: 0, payload: new TextEncoder().encode('x') })+ expect(pty.calls).toHaveLength(0)+ })++ it('pauses the PTY on backpressure and resumes on the next successful send', () => {+ const pty = fakePty()+ const sock = fakeSocket(false) // sendFrame returns false → backpressure+ const h = createHostHandlers(pty.mgr, sock.socket)+ h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 80, rows: 24 } })++ pty.sinks().onData('a') // send fails → pause+ expect(pty.calls).toContainEqual({ method: 'setFlow', args: ['pty-1', false] })++ // Flip the socket to succeed, then deliver more output → resume.+ sock.socket.sendFrame = vi.fn(() => true)+ pty.sinks().onData('b')+ expect(pty.calls).toContainEqual({ method: 'setFlow', args: ['pty-1', true] })+ })++ it('rejects unknown RPC methods', () => {+ const pty = fakePty()+ const sock = fakeSocket()+ const h = createHostHandlers(pty.mgr, sock.socket)+ h.onRpc({ id: 'r9', method: 'pty.bogus', params: {} })+ expect(sock.responses[0]).toMatchObject({ id: 'r9', ok: false })+ })++ it('pty.kill kills the session and forgets the stream', () => {+ const pty = fakePty()+ const sock = fakeSocket()+ const h = createHostHandlers(pty.mgr, sock.socket)+ h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 80, rows: 24 } })+ h.onRpc({ id: 'r2', method: 'pty.kill', params: { streamId: 1 } })++ expect(pty.calls).toContainEqual({ method: 'kill', args: ['pty-1'] })+ // After kill, input for the dropped stream is ignored.+ pty.calls.length = 0+ h.onFrame({ op: OP.Input, streamId: 1, seq: 0, payload: new TextEncoder().encode('x') })+ expect(pty.calls).toHaveLength(0)+ })++ it('emits an OP.Error frame on PTY exit and drops the stream', () => {+ const pty = fakePty()+ const sock = fakeSocket()+ const h = createHostHandlers(pty.mgr, sock.socket)+ h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 80, rows: 24 } })++ pty.sinks().onExit(0)+ const errFrame = sock.frames.find((f) => f.op === OP.Error)+ expect(errFrame).toBeDefined()+ expect(JSON.parse(Buffer.from(errFrame!.payload).toString('utf8'))).toEqual({ exitCode: 0 })+ })++ it('closeAll kills every live session', () => {+ const pty = fakePty()+ const sock = fakeSocket()+ const h = createHostHandlers(pty.mgr, sock.socket)+ h.onRpc({ id: 'r1', method: 'pty.create', params: { cols: 80, rows: 24 } })+ h.onRpc({ id: 'r2', method: 'pty.create', params: { cols: 80, rows: 24 } })+ h.closeAll()+ expect(pty.calls.filter((c) => c.method === 'kill')).toHaveLength(2)+ })+})