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
fix(relay): a throwing hook or dispatch never wedges a core relay session
review2c9b08cee9ec
diff --git a/src/core/relay/relay-host.core.test.ts b/src/core/relay/relay-host.core.test.tsindex 3373f64ee..c81b40bfc 100644--- a/src/core/relay/relay-host.core.test.ts+++ b/src/core/relay/relay-host.core.test.ts@@ -293,3 +293,140 @@ describe('core relay host — hooks and refusals', () => {expect(events).toEqual(['denied:expired', 'close'])})})++// Ruling R11: a hook (or the shell's dispatch) that throws must never escape into the socket's+// message handler — over a real ws that emit is synchronous, so the throw kills the stream: no later+// frame, no `close`, no teardown, the request never answered. Every guard below answers or drops+// instead, and the session keeps serving.+describe('core relay host — a throwing hook or dispatch never wedges the session', () => {+ const errorOf = (frames: string[], id: number) =>+ frames.map((f) => JSON.parse(f)).find((m) => m.t === 'res' && m.id === id)++ it('a throwing access hook answers E_HANDLER, and a later frame on the same session still dispatches', async () => {+ const t = open({+ autoApprove: () => true,+ hooks: {+ access: (_s, _k, method) => {+ if (method === 'boom') throw new Error('access exploded')+ return { allow: true }+ }+ }+ }, true)+ await vi.waitFor(() => expect(t.opened.length).toBe(2))+ t.client.send(JSON.stringify({ t: 'req', id: 1, method: 'boom', args: [] }))+ await vi.waitFor(() => expect(errorOf(t.frames, 1)).toMatchObject({+ ok: false, error: { code: 'E_HANDLER', message: 'access exploded' }+ }))+ t.client.send(JSON.stringify({ t: 'req', id: 2, method: 'fine', args: [] }))+ await vi.waitFor(() => expect(errorOf(t.frames, 2)).toMatchObject({ ok: true, result: 'ok' }))+ expect(t.fa.dispatched.map((r) => r.method)).toEqual(['fine'])+ })++ it('a throwing access hook on a cast drops that cast, and a later cast still arrives', async () => {+ const t = open({+ autoApprove: () => true,+ hooks: {+ access: (_s, kind, method) => {+ if (kind === 'cast' && method === 'boom') throw new Error('nope')+ return { allow: true }+ }+ }+ }, true)+ await vi.waitFor(() => expect(t.opened.length).toBe(2))+ t.client.send(JSON.stringify({ t: 'cast', method: 'boom', args: [] }))+ t.client.send(JSON.stringify({ t: 'cast', method: 'pty:write', args: ['s1', 'x'] }))+ await vi.waitFor(() => expect(t.fa.casts.length).toBe(1))+ expect(t.fa.casts).toEqual([{ method: 'pty:write', args: ['s1', 'x'] }])+ })++ it('a throwing interceptReq answers E_HANDLER and never dispatches', async () => {+ const t = open({+ autoApprove: () => true,+ hooks: {+ interceptReq: (_s, m) => {+ if (m === 'relay:hosted:self') throw new Error('intercept exploded')+ return null+ }+ }+ }, true)+ await vi.waitFor(() => expect(t.opened.length).toBe(2))+ t.client.send(JSON.stringify({ t: 'req', id: 3, method: 'relay:hosted:self', args: [] }))+ await vi.waitFor(() => expect(errorOf(t.frames, 3)).toMatchObject({+ ok: false, error: { code: 'E_HANDLER', message: 'intercept exploded' }+ }))+ expect(t.fa.dispatched).toEqual([])+ })++ it('a rejecting attach.dispatch answers E_HANDLER', async () => {+ const fa = fakeAttach()+ const t = open({+ autoApprove: () => true,+ attach: { ...fa.attach, dispatch: async () => { throw new Error('dispatch exploded') } }+ }, true)+ await vi.waitFor(() => expect(t.opened.length).toBe(2))+ t.client.send(JSON.stringify({ t: 'req', id: 4, method: 'fs:list', args: [] }))+ await vi.waitFor(() => expect(errorOf(t.frames, 4)).toMatchObject({+ ok: false, error: { code: 'E_HANDLER', message: 'dispatch exploded' }+ }))+ })++ it('a dispatch that throws synchronously answers E_HANDLER', async () => {+ const fa = fakeAttach()+ const t = open({+ autoApprove: () => true,+ attach: { ...fa.attach, dispatch: () => { throw new Error('sync dispatch') } }+ }, true)+ await vi.waitFor(() => expect(t.opened.length).toBe(2))+ t.client.send(JSON.stringify({ t: 'req', id: 5, method: 'fs:list', args: [] }))+ await vi.waitFor(() => expect(errorOf(t.frames, 5)).toMatchObject({+ ok: false, error: { code: 'E_HANDLER', message: 'sync dispatch' }+ }))+ })++ it('a throwing narrowResponse answers E_HANDLER, never the unnarrowed result', async () => {+ const t = open({+ autoApprove: () => true,+ hooks: { narrowResponse: () => { throw new Error('narrow exploded') } }+ }, true)+ await vi.waitFor(() => expect(t.opened.length).toBe(2))+ t.client.send(JSON.stringify({ t: 'req', id: 6, method: 'fs:list', args: [] }))+ await vi.waitFor(() => expect(errorOf(t.frames, 6)).toMatchObject({+ ok: false, error: { code: 'E_HANDLER', message: 'narrow exploded' }+ }))+ expect(t.frames.some((f) => f.includes('"result":"ok"'))).toBe(false)+ })++ it('a throwing autoApprove reads as false: the human is asked instead', async () => {+ let pending = 0+ const t = open({+ autoApprove: () => { throw new Error('pin store exploded') },+ onPeerPending: () => pending+++ }, true)+ expect(pending).toBe(1)+ t.hostSession.confirm() // the human+ await vi.waitFor(() => expect(t.opened.sort()).toEqual(['host', 'peer']))+ })++ it('a throwing wrapSink FAILS CLOSED: nothing is attached, the session closes, the shell hears it', async () => {+ let hostClosed = 0+ let clientClosed = 0+ const hostKeys = genKeyPair()+ const { hostT, peerT } = transportPair()+ const fa = fakeAttach()+ const s = connectRelayHost({+ url: 'ws://127.0.0.1/x', token: 't', ourKeys: hostKeys, attach: fa.attach, transport: hostT,+ autoApprove: () => true,+ hooks: { wrapSink: () => { throw new Error('filter exploded') } },+ onPeerPending: () => {}, onOpen: () => { throw new Error('must not open') }, onClose: () => hostClosed+++ })+ connectRelayClient({+ url: 'ws://127.0.0.1/x', token: 't', hostKeyB64: publicKeyToB64(hostKeys.publicKey), ourKeys: genKeyPair(),+ transport: peerT, autoApprove: true, onSas: () => {}, onApproved: () => {}, onFrame: () => {},+ onPtyData: () => {}, onClose: () => clientClosed+++ })+ await vi.waitFor(() => expect(hostClosed).toBe(1))+ expect(clientClosed).toBe(1)+ expect(fa.sinks.size).toBe(0) // an unfiltered sink was never handed to the core+ expect(s.clientId()).toBeNull()+ })+})diff --git a/src/core/relay/relay-host.ts b/src/core/relay/relay-host.tsindex efeacc25a..62d5989e0 100644--- a/src/core/relay/relay-host.ts+++ b/src/core/relay/relay-host.ts@@ -62,6 +62,8 @@ export interface PeerAttach {attach(sink: UiSink): number/** The ONE teardown (presence leave → dropClient → registry prune). */detach(id: number): void+ /** Answer the peer's request. May REJECT (or throw): the host answers that request `E_HANDLER`+ * and the session keeps serving — a failed dispatch never goes unanswered or unhandled. */dispatch(id: number, req: RpcRequest): Promise<RpcOk | RpcErr>cast(id: number, method: string, args: unknown[]): void}@@ -69,7 +71,15 @@ export interface PeerAttach {/** A per-request verdict. `args` (when present) replaces the peer's args for everything downstream. */export type AccessDecision = { allow: true; args?: unknown[] } | { allow: false; message: string }-/** Optional per-session policy. Absent (the desktop) = the unhooked path, byte for byte. */+/**+ * Optional per-session policy. Absent (the desktop) = the unhooked path, byte for byte.+ *+ * A hook that THROWS never reaches the socket (a throw there escapes into the WebSocket's own+ * synchronous message emit, which then delivers nothing more and never closes: the peer hangs and+ * stays attached). Instead: `interceptReq` / `access` on a req → the request is answered+ * `E_HANDLER`; `access` on a cast → the cast is dropped; `narrowResponse` → `E_HANDLER`, never the+ * un-narrowed result; `wrapSink` → the session FAILS CLOSED (see `open`).+ */export interface RelayHostHooks {/** Answer a request here instead of dispatching it. `null` = not intercepted. */interceptReq?(s: RelayHostSession, method: string, args: unknown[]): Promise<unknown> | null@@ -129,6 +139,8 @@ export interface ConnectRelayHostOptions {onClose(): void}+const errorMessage = (err: unknown): string => (err instanceof Error ? err.message : String(err))+/** Live bridged peers, for revocation: unpinning a key refuses the NEXT handshake, but the OPEN* socket keeps full shell access until it is cut (see revocation.ts). */const live = new Set<RelayHostSession>()@@ -234,7 +246,22 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessiosendBinary: (buf) => { if (!socket.sendTunnelBinary(buf)) throw new Error('relay socket is not connected') },bufferedAmount: () => socket.bufferedAmount()}- const id = opts.attach.attach(opts.hooks?.wrapSink ? opts.hooks.wrapSink(session, base) : base)+ let sink: UiSink = base+ if (opts.hooks?.wrapSink) {+ try {+ sink = opts.hooks.wrapSink(session, base)+ } catch (err) {+ // FAIL CLOSED. A wrapSink is a FILTER (a viewer's view of the host); falling back to the bare+ // base sink would hand the peer everything the filter exists to withhold. Attach nothing and+ // end the session. A self-initiated close() never reaches the socket's onClose, so tell the+ // shell here — it did not ask for this, and its bookkeeping (a seat, a dialog) must hear it.+ console.warn(`[relay-host] wrapSink threw; closing the session: ${errorMessage(err)}`)+ session.close()+ opts.onClose()+ return+ }+ }+ const id = opts.attach.attach(sink)clientId = idopts.onOpen(session)}@@ -251,9 +278,25 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio/** The hook's narrowing, for a SUCCESSFUL response only. No hook → the response untouched. */const narrowResponse = (method: string, res: RpcOk | RpcErr): RpcOk | RpcErr => {- const narrow = opts.hooks?.narrowResponse- if (!narrow || res.ok !== true) return res- return { ...res, result: narrow(session, method, res.result) }+ if (!opts.hooks?.narrowResponse || res.ok !== true) return res+ return { ...res, result: opts.hooks.narrowResponse(session, method, res.result) }+ }++ /** The answer to a request whose handler (a hook, or the shell's dispatch) threw or rejected. */+ const handlerError = (id: number, err: unknown): string =>+ JSON.stringify({ t: 'res', id, ok: false, error: { code: 'E_HANDLER', message: errorMessage(err) } })++ /** Send the response `build` produces. If building or serialising it throws (a narrowResponse hook,+ * an unserialisable result), answer `E_HANDLER` instead. Never throws: it runs inside a `.then`,+ * where a throw would be an unhandled rejection and a request nobody ever answers. */+ const respond = (id: number, build: () => RpcOk | RpcErr): void => {+ let json: string+ try {+ json = JSON.stringify(build())+ } catch (err) {+ json = handlerError(id, err)+ }+ socket.sendTunnelText(json)}/** SCOPE jail for the board log (beyond the host registry's own projectId jail): a session bound to@@ -303,8 +346,14 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessioif (!peerKey || gate) return// Bind the session to THIS peer key. Every later approval/dispatch step re-asserts it.sessionPeerKey = peerKey- // Asked with the HANDSHAKE key, before the gate exists: a pinned peer skips the dialog.- const auto = opts.autoApprove?.(peerKey) === true+ // Asked with the HANDSHAKE key, before the gate exists: a pinned peer skips the dialog. A+ // pin-store lookup that throws reads as "not pinned" — the human is asked instead.+ let auto = false+ try {+ auto = opts.autoApprove?.(peerKey) === true+ } catch (err) {+ console.warn(`[relay-host] autoApprove threw; asking the human instead: ${errorMessage(err)}`)+ }gate = createTrustGate({peerKeyB64: peerKey,sessionId: `${peerKey}:${Date.now()}`, // obligation (b): ONE state per pairing attempt@@ -362,16 +411,29 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio}if (m.t === 'req') {// A hook may answer the request itself — it then never reaches a scope check or the core.- const intercepted = opts.hooks?.interceptReq?.(session, m.method, m.args) ?? null+ // Every hook call below is guarded: a throw is ANSWERED (E_HANDLER), never let into the+ // socket's message emit (see RelayHostHooks).+ let intercepted: Promise<unknown> | null+ try {+ intercepted = opts.hooks?.interceptReq?.(session, m.method, m.args) ?? null+ } catch (err) {+ socket.sendTunnelText(handlerError(m.id, err))+ return+ }if (intercepted) {void intercepted.then(- (result) => socket.sendTunnelText(JSON.stringify({ t: 'res', id: m.id, ok: true, result: result ?? null })),- (err) => socket.sendTunnelText(JSON.stringify({ t: 'res', id: m.id, ok: false,- error: { code: 'E_HANDLER', message: err instanceof Error ? err.message : String(err) } }))+ (result) => respond(m.id, () => ({ t: 'res', id: m.id, ok: true, result: result ?? null })),+ (err) => socket.sendTunnelText(handlerError(m.id, err)))return}- const decision = opts.hooks?.access?.(session, 'req', m.method, m.args) ?? { allow: true as const }+ let decision: AccessDecision+ try {+ decision = opts.hooks?.access?.(session, 'req', m.method, m.args) ?? { allow: true as const }+ } catch (err) {+ socket.sendTunnelText(handlerError(m.id, err))+ return+ }if (!decision.allow) {socket.sendTunnelText(JSON.stringify({ t: 'res', id: m.id, ok: false, error: { code: 'E_ROLE', message: decision.message } }))return@@ -392,13 +454,24 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessioreturn}const id = clientId- void opts.attach- .dispatch(id, { ...m, args })- .then((res) =>- socket.sendTunnelText(JSON.stringify(narrowResponse(m.method, scopeResponse(m.method, res))))- )+ let pending: Promise<RpcOk | RpcErr>+ try {+ pending = opts.attach.dispatch(id, { ...m, args })+ } catch (err) {+ socket.sendTunnelText(handlerError(m.id, err))+ return+ }+ void pending.then(+ (res) => respond(m.id, () => narrowResponse(m.method, scopeResponse(m.method, res))),+ (err) => socket.sendTunnelText(handlerError(m.id, err))+ )} else if (m.t === 'cast') {- const d = opts.hooks?.access?.(session, 'cast', m.method, m.args) ?? { allow: true as const }+ let d: AccessDecision+ try {+ d = opts.hooks?.access?.(session, 'cast', m.method, m.args) ?? { allow: true as const }+ } catch {+ return // a cast has no reply channel: a policy that cannot decide drops it+ }if (!d.allow) returnconst args = d.args ?? m.argsif (projectOutOfScope(m.method, args)) return