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.

16.2 KB
Raw Blame
// buildRelayApi — assemble a full `NodeTerminalApi` for a remote-desktop (relay) project tab.
//
// A relay tab is a client of ANOTHER desktop's core, exactly as the browser is a client of the
// Server Edition's core (docs/remote-sessions.md, Stage 4). So it reuses the SAME ws-bridge builders
// the browser uses (`buildRealApi`/`buildFilesApi`/`buildAgentApi`/`buildCanvasApi`/`buildPresenceApi`/
// `buildClaudeApi`) — but over the E2EE relay tunnel (`RelayFrameTransport`) instead of a WebSocket.
// This is the 4a "swap the API object" payoff: a remote tab's `useSession().api` is this object, and
// `createSession('relay', api, label)` (Task 6) wires it into the session registry.
//
// ── The API split (binding, from docs/remote-sessions.md line 70–76) ──────────────────────────────
// • CORE-BOUND namespaces (`pty`, `workspace`, `fs`, `git`, `files`, `context`, `canvas`, `presence`,
//   the agent members from `buildAgentApi` except `seedAgentIdentity` (below), `claude.cliCaps`,
//   `userDataDir`) route over the relay RpcClient → they hit the REMOTE core. This is what makes the
//   tab actually remote: its terminals, repos, files, canvas and presence all live on the host's
//   machine.
//   Routing an agent stream here subscribes nothing: Canvas's agent listeners run on the LOCAL api
//   only. The relay session subscribes `onAgentStatus` itself, for its lifetime, into its own store,
//   and then asks `agentStatusSnapshot` once (`session/relay-agent-status.ts`, wired in
//   `relay-tab.ts`). `onSubagentActivity` and `onUnreadClear` are deliberately NOT subscribed on a
//   relay tab: it renders no subagent cards, and its unread marks are this desktop's own, so a read
//   recorded on the host (a phone read-ack) clears nothing here, as a read here acks nothing there.
// • APP-GLOBAL namespaces (`updates`, `license`, `clipboard`, `shell`, `dialog`, `media`,
//   `settings`, `pairing`, `announcements`, `usage`, `ssh*`, `remote*`, `relay*`, notifications, menu events)
//   stay LOCAL (`window.nodeTerminal.*`). Your update banner shows YOUR version, a file picker
//   browses YOUR disk, your UI settings/theme are yours, and the relay-tunnel machinery itself is
//   your local main process. Routing one of these to the remote core would be a latent bug.
//
// ── Two gotchas that make or break the tab ───────────────────────────────────────────────────────
// 1. `pty.onData` is the ONE core-bound member that does NOT go through the RpcClient. Relay pty
//    output is decoded in the main process and re-emitted on a NAMESPACED local `pty:data` channel
//    (`src/main/index.ts` `onPtyData` → `IPC.ptyData(relayPtyDataKey(connectionId, sessionId))` →
//    preload — never the bare host id, which a local pty shares), NOT over the
//    RpcClient frame stream (`RelayFrameTransport.onMessage` only carries JSON frames). So it
//    delegates to the LOCAL preload's `pty.onData` — the same preload member a local pty uses, on the namespaced key. Wire
//    it to the RpcClient instead and the remote terminal is blank.
// 2. `RelayFrameTransport.ready()` resolves on `onApproved`, which fires exactly ONCE. The transport
//    must be constructed (registering that listener) BEFORE the humans confirm the SAS — i.e. Task 6
//    calls `buildRelayApi` while the approval dialog is still open, THEN awaits `ready()`. Building
//    it after approval already fired leaves `ready()` pending forever and the api never comes up.

import type { HostedRole, NodeTerminalApi, PaneKeysResult } from '../../shared/types'
import { type FrameTransport, RelayFrameTransport } from './frame-transport'
import { RoleGatedRpcClient } from './hosted-gate'
import { emitLocalRelayClose } from './relay-local-close'
import {
  RpcClient,
  buildHostedApi,
  buildRealApi,
  buildFilesApi,
  buildAgentApi,
  buildCanvasApi,
  buildPresenceApi,
  buildClaudeApi,
  buildGitHubApi
} from './ws-bridge'
import { buildStubApi } from './stubs'
import { relayPtyDataKey } from '../../shared/relay-pty-channel'
import { mountPickerRoot, openDirectoryPicker } from './dialog-picker'
import { projectIdsBoundToApi } from '../session/session'

/** What Task 6 consumes: the bridged api for `createSession`, an approval gate to await, and a
 *  teardown hook to run on disconnect/revoke. */
export interface RelayApiHandle {
  /** The bridged `NodeTerminalApi` for `createSession('relay', api, label)`. */
  api: NodeTerminalApi
  /** Resolves once BOTH humans confirmed the SAS (the relay frame pipe is live). Delegates to the
   *  transport's `ready()`; see gotcha 2 about construction order. */
  ready(): Promise<void>
  /** Tear the connection down: close the relay socket for this connectionId. */
  close(): void
  /** HOSTED tabs only: tell the role gate which role the host gave this device (the tab asks
   *  `hosted.self()` before anything mounts). Absent on every other relay tab. */
  setHostedRole?(role: HostedRole): void
}

/** How to build a relay tab's api. */
export interface RelayApiOptions {
  /** A relay tab joined by a hosted team's `nodeterm://join` code: it gets `api.hosted` and a role
   *  gate on everything it sends. Absent/false = a Team Access relay tab, built exactly as before. */
  hosted?: boolean
}

/**
 * Build the bridged api for a relay connection. `transport` is a test seam — production passes
 * nothing and a `RelayFrameTransport(connectionId)` is constructed here (which is what registers the
 * one-shot `onApproved` listener; see gotcha 2).
 */
export function buildRelayApi(
  connectionId: string,
  transport?: FrameTransport,
  opts?: RelayApiOptions
): RelayApiHandle {
  // The LOCAL preload — this is a desktop-only path (relay hosting/joining is Electron), so
  // `window.nodeTerminal` is the full real preload, not the browser stub surface.
  const local = (window as unknown as { nodeTerminal: NodeTerminalApi }).nodeTerminal
  const carrier = transport ?? new RelayFrameTransport(connectionId)
  // A hosted tab's role, once the host has said it. Unknown = the lowest role (hosted-gate.ts).
  let hostedRole: HostedRole | null = null
  const hosted = opts?.hosted === true
  const client = hosted ? new RoleGatedRpcClient(carrier, () => hostedRole) : new RpcClient(carrier)

  const real = buildRealApi(client) // { pty, workspace, settings, userDataDir }
  const files = buildFilesApi(client) // { fs, git, files, context }
  const github = buildGitHubApi(client)
  const stub = buildStubApi()

  const api: NodeTerminalApi = {
    // ── Base: every APP-GLOBAL namespace stays LOCAL. Spreading the whole preload gives the real
    //    desktop implementations (updates/license/clipboard/shell/dialog/media/settings/pairing/
    //    announcements/usage/ssh*/remote*/relay*/notifications/menu events). The core-bound spreads
    //    below override the handful that must hit the remote core.
    ...local,

    // ── CORE-BOUND: route to the REMOTE core over the relay RpcClient. ──
    workspace: real.workspace, // the host's canvas/project files
    userDataDir: real.userDataDir, // the host's writable base
    fs: files.fs,
    git: files.git,
    files: files.files,
    context: files.context,
    githubIssues: github.githubIssues,
    githubControl: local.githubControl,
    // The host's agent hooks. Only `onAgentStatus` (+ `agentStatusSnapshot`) is used on a relay tab,
    // by session/relay-agent-status.ts; `onSubagentActivity` / `onUnreadClear` stay unsubscribed.
    ...buildAgentApi(client),
    ...buildCanvasApi(client), // canvas sync against the host's reflector
    ...buildPresenceApi(client), // the host's presence hub
    // `cliCaps` is REAL over the relay so the --permission-mode auto version gate probes the HOST's
    // claude CLI (a remote node launches on the host); `readTranscript` stays LOCAL (v1 degrade —
    // transcripts aren't relayed, so it reads this machine's; the only consumer reads the global api).
    claude: buildClaudeApi(client, local.claude),

    // pty is core-bound EXCEPT `onData` (gotcha 1): its output arrives on the LOCAL per-session
    // channel, so subscribe on the local preload, same shape as a local pty.
    pty: {
      ...real.pty,
      // Host-only: a relay tab never types into the host's panes by id.
      sendPaneKeys: async () => ({ ok: false, reason: 'unsupported-backend' }) as PaneKeysResult,
      // On the NAMESPACED key main delivers relay output on — never the bare host id, which is a
      // LOCAL terminal's channel too (shared/relay-pty-channel.ts).
      onData: (sessionId, listener) => local.pty.onData(relayPtyDataKey(connectionId, sessionId), listener)
    },

    // boardLog is CORE-BOUND: a relay guest reads and writes the HOST project's board comments/activity
    // (with its OWN presence identity in each entry), routed to the host's registry-jailed board-log
    // handlers (and scope-jailed to the shared project host-side in connectRelayHost). Version-skew
    // degrade: an OLDER host with no board-log rpc answers E_NO_HANDLER, which we map to today's
    // behavior — read → `{ entries: [], unsupported: true }`, append → `false` — instead of a rejection.
    // `onChanged` casts subscribe/unsubscribe (fire-and-forget, no reject) and rides the host push.
    boardLog: {
      append: (projectId, entry) => files.boardLog.append(projectId, entry).catch(() => false),
      read: (projectId, opts) =>
        files.boardLog.read(projectId, opts).catch(() => ({ entries: [], unsupported: true })),
      onChanged: (projectId, cb) => files.boardLog.onChanged(projectId, cb)
    },

    // `settings` stays LOCAL (font/cursor/theme render in YOUR window). It came in via `...local`;
    // `real.settings` is deliberately left unused so a remote tab never adopts the host's prefs.

    // `dialog` REFINES Task 5's coarse "dialog → local". `selectFolder`/`selectFile` are the only
    // members `DialogApi` exposes, and in a remote tab BOTH are host-path pickers, not local ones:
    // the chosen path is fed to the SESSION core (a clone destination for `api.git.clone`, an
    // "open folder/file" target on the host fs), so a native LOCAL picker would land the op on the
    // wrong machine (obligation d). Route both to the SAME in-app directory browser the Server
    // Edition uses, over the HOST's `fs.list` (`files.fs`, already core-bound). There is no other,
    // genuinely-local `dialog.*` method that would want to stay on `...local`. Desktop-only path, so
    // `document` exists for `mountPickerRoot`.
    dialog: (() => {
      mountPickerRoot()
      const startDir = '/' // navigable up/down from the host root; no cross-call memory in v1
      // "New folder" writes through the HOST's `fs.mkdir`/`fs.exists` (same core handlers, reached
      // over the relay), so the folder is created on the machine whose path the picker returns.
      const write = { mkdir: files.fs.mkdir, exists: files.fs.exists }
      return {
        selectFolder: () =>
          openDirectoryPicker({ mode: 'folder', startDir, list: files.fs.list, write }),
        selectFile: () => openDirectoryPicker({ mode: 'file', startDir, list: files.fs.list })
      }
    })(),

    // ── Deferred over the relay in v1 — documented degrades (a clean refusal, not a wrong-machine
    //    silent no-op): ──
    // `chat` is readTranscript + transcriptExists + catalog (the SDK chat node was removed). `catalog`
    // rejects like `readTranscript` (the stub's E_UNSUPPORTED): the composer then offers the shared
    // built-in table alone, never this machine's command folders under the peer's node. It has
    // no relay builder: reading a transcript over the relay would read THIS machine's transcript,
    // not the host's, so `readTranscript` refuses with E_UNSUPPORTED instead. `transcriptExists`
    // takes the stub's `'unknown'` for the same reason and the opposite shape — its consumer acts
    // on a NEGATIVE, so answering about the wrong machine would drop a live conversation's
    // `--resume`; `unknown` is exactly "we could not look", i.e. resume as before. contextLink / transcripts / handoff stay LOCAL by way of
    // `...local` (a v1 degrade: they read/write on this machine, not the host). boardLog is now
    // bridged to the host (see above) — it no longer rides `...local`.
    chat: stub.chat,
    // `recentConversations` stays on `...local` ON PURPOSE: "Open recent" lists THIS machine's agent
    // histories and resumes them into this machine's local projects only. The host's list is
    // host-only (`HOST_ONLY_CHANNELS`) — a peer never reads the host's conversation titles.
    // Agent canvas-control (`agent:control`) is not wired over the relay (matches the Server
    // Edition); inert no-ops rather than a local subscription that never carries the host's events.
    onAgentControl: stub.onAgentControl,
    sendAgentControlResult: stub.sendAgentControlResult,
    // Browser control never rides the relay either (no CDP off the desktop) — inert no-ops.
    onBrowserControlResolve: stub.onBrowserControlResolve,
    sendBrowserControlResolveResult: stub.sendBrowserControlResolveResult,
    // The phone Chat round-trip is the LOCAL desktop main's, never a relay peer's — inert here.
    onHostChatQuery: stub.onHostChatQuery,
    sendHostChatReply: stub.sendHostChatReply,
    // Messaging rides the same decision: the browser client is never a sender (constraint 5 of
    // the messaging plan — the phone drives canvas control over relay→IPC, not /control/*).
    agentMessage: stub.agentMessage,
    // Station-failure notices are about THIS machine's stations and its own orchestrators; a relay
    // tab's nodes live in the host's core, whose notices are the host's renderer's to draw.
    stationNotice: stub.stationNotice,
    boardDispatch: stub.boardDispatch,
    stationOutcome: stub.stationOutcome,
    stationHandover: stub.stationHandover,
    // Share with team drives THIS machine's ssh for one of THIS machine's SSH projects; a relay
    // tab's projects are the host's, so `...local` would aim a host project id at the local ssh
    // manager. The stub answers E_UNSUPPORTED instead.
    shareTeam: stub.shareTeam,
    // The mirror identity seed is a deliberate no-op here: a relay tab's nodes belong to the HOST's
    // core, whose mirror is seeded by the host's own renderer from its own localStorage. This
    // machine's localStorage holds no identity for them, and `...local` would plant this machine's
    // ids into this machine's mirror under the peer's node ids.
    seedAgentIdentity: () => undefined,

    // Which of this tab's projects publish their canvas ops even when nobody else is attached. A
    // HOSTED tab's host runs the canvas authority (docs/hosted-team-relay.md), which governs every
    // project it shares, and a hosted tab holds shared projects only: so every project bound to THIS
    // connection is governed. Answered here, from the session registry, never over the wire (a
    // viewer could not ask anyway, and the host's answer names the host's projects, which is what the
    // binding already holds). A Team Access tab's host is a desktop, which governs nothing: `local`.
    canvasAuthority: hosted
      ? {
          // Answered at once from the bindings, so nothing needs to be assumed before it.
          assumeAllUntilAnswered: false,
          governed: async () => projectIdsBoundToApi(api),
          // The set changes only when a tab binds or unbinds, and Canvas re-reads it on every bind.
          onChanged: () => () => {}
        }
      : local.canvasAuthority,

    // The hosted team verbs — ONLY on a tab joined by a hosted team's code. A Team Access relay
    // tab's host answers none of them, so there the key is absent altogether (never `undefined`),
    // and every `api.hosted` check in the renderer takes its old path.
    ...(hosted ? buildHostedApi(client) : {})
  } satisfies NodeTerminalApi

  return {
    api,
    ready: () => client.ready(),
    close: () => {
      local.relayClient.disconnect(connectionId)
      // A hosted connection's own close is announced locally: main never reports it (see
      // relay-local-close.ts), and this tab's team is held until its connection ends.
      if (hosted) emitLocalRelayClose(connectionId)
    },
    ...(hosted ? { setHostedRole: (role: HostedRole) => { hostedRole = role } } : {})
  }
}