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.

docs: hosted team relay — invariants, operator guide and device checklist

reviewa0a1be02510e
diff --git a/CLAUDE.md b/CLAUDE.md
index 68338b707..7b2111822 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -5542,6 +5542,89 @@ to the class, and no bare `.react-flow__viewport` rule carries `will-change`).
being packaged (#575, shipped by #579): without that bundle `pty.attach` spawns a new plain shell
instead of joining the node's session, while `sessionExists` still answers "warm".
+## Hosted team relay (Server Edition as a relay host)
+
+A Server Edition core can host a team over the E2EE relay: a standing listener on the tunnel
+dialect, owner approval, roles, a `team` admin CLI, and desktops joining with a
+`nodeterm://join?code=…` code. Operator guide, roles table, join-error table, limitations and the
+device checklist: **`docs/hosted-team-relay.md`**. The relay mechanism moved to `src/core/relay/`
+(`src/main/remote/` keeps re-export shims), and Team Access and the hosted team run the SAME
+`connectRelayHost`: a host that passes no `RelayHostHooks` (the desktop) takes the unhooked path.
+The invariants, each with its reason:
+
+- **Roles are enforced in core, deny-by-default in BOTH directions** (`core/relay/access-policy.ts`).
+ A Viewer/Commenter reaches a method only if `VIEW`/`COMMENT` lists it, and receives an event only
+ if `VIEW_EVENTS` does: the core broadcasts to every attached client (the debug log, whole project
+ documents), so an allow-by-default filter would hand a viewer whatever nobody remembered to list.
+ **"Read" is not "safe"**: relay peers were fully trusted, so every VIEW entry carries its own
+ argument check. `fs:*` is realpath-jailed to a shared project's realpathed cwd; `git:diff` jails
+ the FILE too (`--no-index` diffs any file on the host); a `git:show-file` ref starting with `-`
+ is an option (`--output=` writes a file); `pty:create` is cut down to a whitelist, because
+ `sshRemote`'s args run `ssh` on the host during the existence probe. Editors pass untouched
+ (Editor is shell access). The UI mirror (`@shared/hosted-access.ts`, `bridge/hosted-gate.ts`) is
+ convenience; `access-policy.guard.test.ts` pins it equal and fails on any relay-API channel
+ nobody classified.
+- **The role is read from `team.json` on every message, never cached on a session**, so a removal
+ or promotion applies to the next message. A session with NO team entry is served nothing: that
+ is the window between a removal's write and its kill. The one exception is `pinFailed` (both
+ humans approved but the pin write failed), served as Viewer. The renderer, by contrast, reads the
+ role once per connection; that is UX only.
+- **A viewer's size never votes, and a viewer's create is join-only.** `sizeVote: false` (a
+ non-voting re-join also WITHDRAWS an earlier vote under the same subscriber key) and `pty:resize`
+ rewritten to `(null, null)`: a small window must not shrink everyone's terminal. `joinOnly`
+ asks the STRICT exact-target probe (`has-session -t =nt-<id>`), refuses when it cannot tell, and
+ reattaches without `-D`. The folded probe reads a tmux error as "exists", which is the safe answer
+ for an owner and would let a viewer's `new-session -A` CREATE the session.
+- **The host key is never silently regenerated** (`host-key.ts`). Its public key IS the team's
+ address (`hostId`), so a new key orphans every bookmark and sends every teammate back through
+ first-join approval. Unreadable ⇒ hosting stays off with `host-key-unreadable`; only
+ `team rotate-key` replaces it.
+- **`team.json` is not the phone's pin file.** Push's `hasPairedPhone` counts the entries of
+ `remote-approved-devices.json`, so a teammate pinned there would read as a paired phone. The same
+ rule on the joiner: `hosted-join.ts` runs the core relay client with NO pin store, and the
+ joiner-side pin is the bookmark's `approvedAt` (valid only for the exact host key it was recorded
+ with).
+- **The admin channel is a 0600 unix socket in a 0700 directory, with no token**
+ (`core/relay/team-admin.ts`). Filesystem permissions are the whole gate, so there is nothing to
+ leak into a pane's environment. The root of trust is the core's unix user, which also means an
+ Editor's shell can run `team add-owner`. With no team, the socket serves only
+ `init`/`status`/`info`. The `relay:hosted:*` verbs are intercepted inside the relay session and
+ never registered on the platform, so a Server Edition browser client cannot call them. An
+ interceptor bypasses `access` and every jail, so each one judges the CALLER's own session key.
+- **LOCAL confirms have exactly three call sites on the host side:** the Team Access dialog
+ (`relay:host:confirm`), `autoApprove` for a key `team.json` pins, and an owner's
+ `relay:hosted:approve`. The joiner side has two: the human's `relay:client:confirm`, and the
+ bookmark auto-confirm. The one remote confirm still arrives only on the encrypted tunnel. A new
+ local confirm is a design change. (The comment in `relay-trust.ts` names the host-side three.)
+- **Nothing is served before mutual approval.** Frames that arrive between approval and open (while
+ the pin is being written) are HELD, at most `HELD_FRAMES_MAX` (256), then served through the same
+ checks. Refusing them would fail a new teammate's first `workspace:load`, which routinely lands
+ inside the host's pin write. Pending join requests go to connected OWNERS only (never a
+ broadcast), at most one per device key and 16 at once, and expire after 10 minutes. A deny or
+ expiry that lands during the pin write wins.
+- **The scheduler's backoff resets only on proof the relay leg works** (an idle listener held to
+ its refresh, or a completed handshake), never on a successful mint. With the API up and the
+ relay down every mint succeeds and every socket dies, and a reset-on-mint re-minted at
+ round-trip speed (relay log, 2026-09-27). Successful mints are also capped at 200 per rolling
+ hour, whatever asks for them (the backend's free limit is 240).
+- **The joiner never mints a device token it cannot keep.** Device mints are damped per HOST device
+ id, so one team shares 10 a day. It probes the bookmarks file before minting and sends a PER-TEAM
+ device id (`<machine id>:<hostId>`), because the backend will not re-register one id for a second
+ host. Every failure carries a stable `[E_JOIN_…]` code, which is the only part of an error that
+ survives Electron IPC. Only `E_JOIN_NETWORK` and `E_JOIN_THROTTLED` (at least 60 s) retry
+ unattended. A drop the host did not explain retries 5 times (1/2/4/8/15 s), then stops and says so.
+
+**Known limitations** (full list in the doc): non-editors still receive cross-project presence and
+`context:update` metadata (deploy one core per team); a viewer's socket backlog over 1 MB still
+pauses the shared pty through Stage 2 backpressure; canvas edits made in a hosted tab are not
+written to the host (a relay tab never saves the host workspace, and the reflector persists
+nothing).
+
+**Surfaces:** Desktop is full (joiner, plus approval and invite code in an owner's hosted tab).
+Server Edition is the host (the `team` CLI; its browser clients cannot approve and are not hosted
+peers). Mobile is N/A for v1: the phone still speaks the legacy dialect, and the host it would join
+now exists in core. The iOS follow-up is the tunnel-dialect migration.
+
## Speech / dictation (desktop + server)
Voice-to-text input captured via microphone, turned into terminal text via on-device Whisper. Works on desktop (Electron) and Server Edition (browser); iOS support is separate (`nodeterm-ios`, private — see the three-surfaces entry under Conventions).
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index aa82a474e..f9f099a56 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -319,6 +319,17 @@ lane unaffected.
unless that table can read its projectId. Add the row in the same PR as the channel, or the verb
is refused for every scoped guest (and `relay-project-scope.test.ts` goes red telling you so).
+- **A new IPC channel a relay tab can call must be classified in `src/core/relay/access-policy.ts`
+ — the guard test fails otherwise.** Every `IPC.*` the relay API's builders reference
+ (`BUILDERS` in `ws-bridge.ts`, plus `relay-api.ts`) goes in `VIEW` or `COMMENT` with its own
+ argument check, or in the reviewed `EDITOR_ONLY` set; `access-policy.guard.test.ts` names every
+ one you missed. A hosted team's Viewers and Commenters are refused anything unlisted, so
+ forgetting is safe but silent, and the guard is what makes someone decide. Opening a channel to
+ viewers also means adding it to the renderer's mirror, `src/shared/hosted-access.ts` (the same
+ test pins the two lists equal). An EVENT a viewer must receive needs a `VIEW_EVENTS` entry, and no
+ test forces that: without one, the event simply never arrives. Deep version: CLAUDE.md § Hosted
+ team relay.
+
- **Normalize BOTH sides of a path comparison, through one function.** A marker normalized where
it is built and matched raw where it is used is a no-op on the machine you wrote it on and a
silent defect on Windows. That is issue #558: the managed-hook marker was folded to `/` while
diff --git a/docs/hosted-team-relay.md b/docs/hosted-team-relay.md
new file mode 100644
index 000000000..b7ed85add
--- /dev/null
+++ b/docs/hosted-team-relay.md
@@ -0,0 +1,443 @@
+# Hosted team relay (a Server Edition as the relay host)
+
+**Status:** sub-project 1 of "team on an SSH host", built on `feat/hosted-team-relay` (2026-09).
+Everything below was checked against the code on that branch. Where the design spec says something
+else, the code wins; the spec is a local planning file and is not the reference.
+
+**Builds on:** `docs/remote-sessions.md` (relay tabs, the trust gate, Team Access) and
+`docs/team-presence.md` (presence, co-attach, canvas sync).
+
+## What it is
+
+A Server Edition core on a Linux host can now be a **standing relay host** for a team. Teammates'
+desktops join it over the same E2EE relay that Team Access uses, with no SSH access of their own
+and no inbound port on the host. The owner does not need their own laptop to be awake: the host
+keeps one idle relay listener registered at all times, and each device an owner approved once is
+pinned in the host's `team.json`, so it reconnects without anyone approving it again. Each member
+has a role (Viewer, Commenter, Editor or Owner), and **the role is enforced in the host core, on
+every message**. The desktop's UI only mirrors it.
+
+## How it fits together
+
+| Piece | Where | Notes |
+|---|---|---|
+| Relay mechanism (E2EE socket, trust gate, host and client sessions) | `src/core/relay/` | Moved from `src/main/remote/`, which now holds re-export shims and the desktop's own wrappers. Team Access and the hosted team run the **same** handshake and tunnel (`relay-host.ts`). |
+| The seam | `relay-host.ts` `PeerAttach`, `PinStore`, `RelayHostHooks` | A host that passes no hooks (the desktop's Team Access) takes the unhooked path, unchanged. |
+| Hosted service | `src/core/relay/hosted-service.ts` | Composes the host key, team store, scheduler and access policy; holds pending join requests; answers the `relay:hosted:*` verbs. |
+| Standing listener | `hosted-scheduler.ts` + `host-token.ts` | A pure scheduler over injected mint / open / timers. |
+| Host identity | `host-key.ts` | `<dataDir>/relay/host-key.json`, 0600, plaintext secret (headless Linux has no keyring). |
+| Membership | `team-store.ts` | `<dataDir>/relay/team.json`, 0600, single writer. |
+| Role policy | `access-policy.ts` | `VIEW`, `COMMENT`, `EDITOR_ONLY`, `VIEW_EVENTS`; the guard test is `access-policy.guard.test.ts`. |
+| Admin channel | `team-admin.ts` (socket) + `src/server/team-cli.ts` (CLI) | `<dataDir>/relay/admin.sock`, 0600 in a 0700 directory. |
+| Server boot | `src/server/index.ts` (search "Hosted team relay") | Booted in headless AND serving mode, after every handler is registered and the workspace index is loaded. |
+| Desktop joiner | `src/main/remote/hosted-join.ts`, `relay-bookmarks.ts`; core `join-code.ts`, `join-token.ts` | Runs the core relay client with **no pin store**. |
+| Renderer | `lib/hostedJoin.ts`, `lib/hostedAttempts.ts`, `lib/hostedOwner.ts`, `lib/hostedPendingQueue.ts`, `components/HostedApprovalDialog.tsx`, `bridge/hosted-gate.ts`, `bridge/relay-local-close.ts`, `@shared/hosted-access.ts` | Every hosted branch sits behind a join code, a hosted api or a hosted role, so a Team Access tab and a local tab take their old paths (`canvas/hosted-team.source.test.ts`). |
+| End-to-end test | `src/server/hosted-e2e.test.ts` | A real headless server boot, the real admin socket, access policy, `PtyManager` and trust gates, with an in-process relay and a fake token API. |
+
+## Setup over SSH
+
+Run every `team` command **as the unix user the nodeterm service runs as**, on the host. The CLI
+never touches `team.json` or the host key itself. It talks to the running server over the admin
+socket, so the service must be up. `install-server.sh` puts the app in `~/.nodeterm-server-app` and
+the data in `~/.nodeterm-server`. When it provisioned its own Node, `node` may not be on `PATH`;
+the service's `ExecStart` line (`systemctl --user cat nodeterm-server`, or the system unit for a
+root install) names the exact binary and script to use.
+
+```bash
+APP=~/.nodeterm-server-app/out/server/main.cjs
+
+node $APP team init # host key + team.json, starts hosting
+node $APP team add-owner <your device key> --label "<you>"
+node $APP team share <projectId> # what the team can see
+node $APP team info --json # address + join code
+```
+
+`--data-dir <dir>` (anywhere on the line) or `NODETERM_DATA_DIR` points the CLI at a server running
+with a non-default data directory. `node $APP team --help` prints the verb list. Exit codes: 0 done,
+1 the server refused or could not be reached (or the command ran but its outcome did not happen,
+such as hosting not starting), 2 the command line is wrong.
+
+| Command | Effect |
+|---|---|
+| `team init` | Creates the host key (once) and `team.json` if absent, then starts hosting. Prints the address and join code when hosting started. An unreadable key is refused, never replaced. |
+| `team add-owner <device-key> [--label <name>]` | Pins that device as an **owner**. An existing member's key is promoted to owner. The key must be the canonical 44-character base64 public key; a typo gets its own message before anything is sent. |
+| `team remove <device-key> [--force]` | Unpins the key and cuts its live sessions (they are told `removed`). Removing the last owner needs `--force`. |
+| `team share <projectId>` / `team unshare <projectId>` | Adds or removes a project in `sharedProjects`. The id is **not** checked against the workspace. |
+| `team info [--json]` | The team address and join code. The plain form prints the join code only while hosting is on; `--json` returns `{enabled, info, joinCode}`. |
+| `team status [--json]` | Hosting state, members, and pending join requests (see [Status and troubleshooting](#status-and-troubleshooting)). |
+| `team rotate-key` | Replaces the host key. Every bookmark and join code stops working. A hosting service restarts on the new key; one that was not hosting stays off. |
+
+With no team on the server, the admin socket answers only `init`, `status` and `info`: every other
+verb would create team state on a server that never asked to host.
+
+### 1. The project must already be on this core
+
+`team share` takes a project id from this core's workspace index, `<dataDir>/workspace.json`
+(`entries[].id`, beside each entry's `name` and `cwd`). A headless install has no UI that creates a
+project, so open the folder once from the Server Edition's browser UI (serving mode, see
+`docs/SERVER.md`); the hosted relay boots in serving mode too. Adopting an existing SSH project
+into the server core is sub-project 3.
+
+A joiner's tab shows **one** project: the first shared project in the host's workspace order
+(`openRelayTab` adopts `projects[0]` of the narrowed workspace). With nothing shared, even an owner
+gets an empty tab, because `workspace:load` is narrowed to `sharedProjects` for every hosted peer,
+owners included.
+
+### 2. Your desktop's device key
+
+The key is the `publicKey` field of `<userData>/remote-peer-key.json` on your desktop
+(`src/main/remote/peer-identity.ts`). The public key is always stored as plaintext base64, even when
+the keyring encrypts the secret next to it (`key-file-codec.ts`), so it is readable either way. On
+macOS:
+
+```bash
+grep -o '"publicKey":"[^"]*"' ~/Library/Application\ Support/nodeterm/remote-peer-key.json | cut -d'"' -f4
+```
+
+(`~/.config/nodeterm/` on Linux, `%APPDATA%\nodeterm\` on Windows.) No UI shows this key in v1;
+sub-project 3 automates this step.
+
+The file is created the first time the desktop uses the relay. If it is not there yet, paste the
+team's join code once (step 3). While your desktop asks you to read a code to an owner, `team status
+--json` lists your device under `pending` with its `peerKeyB64` and `sas`. Take the key whose `sas`
+matches your prompt, press Cancel on the prompt (that ends the request), run `team add-owner` with
+that key, and paste the code again. A request that is still pending when its key becomes an owner is
+not upgraded; it would wait out its 10 minutes.
+
+### 3. The first connect
+
+On the desktop, choose **New Remote Connection** (dock or ⌘K) and paste the
+`nodeterm://join?code=…` code. The host already trusts an owner's key, so it approves its own half
+without anyone. Your desktop has no record of this host yet, so it asks once, with the SAS, to "read
+this code to an owner"; nobody on the host compares it (the host key itself is checked against the
+one in the join code), so press OK. The desktop records the approval in its bookmark, and every
+later connect opens without a prompt.
+
+### 4. Inviting teammates
+
+An owner's hosted tab has **Copy team invite code** in the command palette; `team info` prints the
+same code. A join code carries public material only (relay endpoint, host id, host public key, host
+device id, label). A leaked code lets someone **ask** to join; an owner still approves each device.
+
+The teammate pastes it into New Remote Connection and reads the SAS it shows to an owner (a call
+or a chat). The owner's desktop shows "A device wants to join" with the same SAS, a device-key
+fingerprint (the key's first 8 characters) and a role picker that defaults to **Viewer**. Allow
+grants the chosen role once the joiner has pressed OK too.
+
+## Roles
+
+Generated from `src/core/relay/access-policy.ts`. Owners and editors pass every check (Editor is
+shell access, so gating it would be theatre); Viewers and Commenters get **only** what `VIEW` /
+`COMMENT` list, each with its own argument check. Anything else, including every channel added
+later, is Editor-only until someone decides otherwise.
+
+| Capability | Viewer | Commenter | Editor | Owner |
+|---|---|---|---|---|
+| See the shared projects' canvas, presence and cursors (`workspace:load`, `presence:hello/cursor/focus/project`) | ✓ | ✓ | ✓ | ✓ |
+| Watch a terminal of a shared project that is **already running** | ✓ | ✓ | ✓ | ✓ |
+| Read files and git state inside a shared project | ✓ | ✓ | ✓ | ✓ |
+| Read a shared project's board log | ✓ | ✓ | ✓ | ✓ |
+| Cursor chat (`presence:chat`), board-log comments (`board-log:append`) | — | ✓ | ✓ | ✓ |
+| Type into terminals, start terminals, write files, every git mutation, canvas edits, settings, credentials, logs, GitHub | — | — | ✓ | ✓ |
+| Approve or deny join requests, read the invite code, see pending requests | — | — | — | ✓ |
+
+`relay:hosted:self` (the caller's own role) is open to any member. The `relay:hosted:*` verbs are
+intercepted by `hosted-service.ts` before the table is consulted, and each judges the **caller's own
+session key** in the team store.
+
+**"Read" is not "safe": every viewer channel carries its own check.**
+
+| Channels | What a Viewer / Commenter may do |
+|---|---|
+| `pty:create` | Only for a node of a shared project. The options are rewritten to `persistKey`, `cols`, `rows` and `viewerId`, plus `joinOnly: true` and `sizeVote: false`. Everything else is stripped, including `sshRemote`, whose ssh args would run on the host during the existence probe. A join-only create that would spawn a new session answers `unavailable: 'join-only'`. |
+| `pty:resize` | Rewritten to "not looking" (`null, null`): a viewer's window never sizes the shared terminal. |
+| `pty:flow` | Resume only: a pause would freeze the shared process for everyone. |
+| `pty:kill` | Detaches the caller's own view; the session keeps running. |
+| `pty:capture`, `pty:read-scrollback`, `pty:pane-command` | Nodes of shared projects only. |
+| `pty:tmux-status` | Allowed. |
+| `fs:list`, `fs:read`, `fs:read-binary`, `fs:exists`, `git:status`, `git:repo-root`, `git:history` | The path must be absolute and its **realpath** inside a shared project's cwd (also realpathed). A symlink planted inside the project that points out of it is outside. |
+| `git:diff` | The cwd **and** the file are jailed; a pathspec starting with `:` is refused; an untracked diff (`git diff --no-index`, which diffs any file) needs a real path inside. |
+| `git:show-file` | Cwd jailed; a ref starting with `-` is refused (it would become an option, and `--output=` writes a file). |
+| `agent:subagent-snapshot` | The response is trimmed to shared nodes. |
+| `board-log:read/subscribe/unsubscribe` (+ `append` for Commenters) | Shared projects only. |
+
+**Outbound is deny-by-default too.** The core broadcasts to every attached client, so a non-editor
+receives only the events `VIEW_EVENTS` lists: `canvas:mut`, `workspace:external-change` /
+`server-change` and `project-trust:changed` for shared projects; `agent:status` and
+`agent:unread-clear` for shared nodes; `agent:subagent-activity` for subagents a shared node
+started; `context:update`, `presence:sync` and `presence:peer` for everyone (see
+[Limitations](#limitations-v1)); the per-session pty channels, which only a session's subscribers
+receive; and `board-log:changed:<id>` / `project-setup:event:<id>` for shared projects. Terminal
+bytes pass, because they go only to a session's subscribers.
+
+The renderer mirrors the two allowlists in `@shared/hosted-access.ts` (`bridge/hosted-gate.ts`
+answers a refused call locally, in the host's words), and the guard test pins the mirror equal to
+the host's tables. The mirror is convenience; the host is the boundary.
+
+## Joining and reconnecting (desktop)
+
+A join code runs `joinHostedTeam` in the main process:
+
+1. Decode and verify the code: the host id must derive from the host key, and the relay must be
+ `wss:` (or `ws:` to loopback). The same rule applies to the endpoint the API hands back.
+2. Load this desktop's peer key **before** any mint, so a locked keyring costs nothing.
+3. Get a device token: the bookmarked one, else **one** fresh `POST /v1/relay/device`. The device
+ id sent is `<machine id>:<hostId>`, one per team: the backend refuses to re-register a device id
+ for a second host on the free tier.
+4. Trade it for a client token (`POST /v1/relay/join`). A `401` on a kept token earns one re-mint;
+ a `403` earns none.
+5. Connect with the host key from the code pinned. The core relay client runs with **no pin store**;
+ the joiner-side pin is the bookmark's `approvedAt`.
+
+Bookmarks live in `<userData>/relay-bookmarks.json` (0600, one per `hostId`): the join code, the
+label, the device token, `approvedAt` and `source`. A bookmark auto-confirms only when `approvedAt`
+is set **and** the code carries exactly the key it was recorded for. A host that refuses the device
+(denied, removed, expired) withdraws `approvedAt`, so the next attempt shows the SAS again. The
+token is never sent to the renderer.
+
+A device token is never minted when it could not be kept. Before a mint, the bookmarks file must
+be readable and parseable and its directory writable; a token whose write still fails is kept in
+memory for the rest of the app run. A second join for the same team while one is still minting or
+joining answers `E_JOIN_BUSY`.
+
+**Reconnect, as built:**
+
+- At boot, every **approved** bookmark reconnects in the background. No greyed tab is persisted;
+ the tab appears once the connection is approved.
+- A live hosted tab whose connection dropped with no reason from the host reconnects in place. It
+ waits 1 s first, then tries at most 5 times (1, 2, 4, 8, 15 s, about 30 s in all), then stops
+ with one notice ("Couldn't reconnect to X. Click its tab to try again."). A click is a fresh
+ attempt. A boot reconnect that runs out says to paste the invite code instead.
+- Unattended attempts (boot and drop reconnects) retry `E_JOIN_NETWORK` on 1, 2, 4, 8, 15 s, then
+ every 60 s, and `E_JOIN_THROTTLED` no sooner than 60 s (or the Retry-After), announced once per
+ streak. Nothing else retries, and a pasted code never retries: it is told once.
+- Closing or deleting the tab cancels its team's attempt in any phase. At most one attempt and one
+ live connection exist per team.
+- **Forget hosted team: <name>** in the palette removes the bookmark and stops the reconnect. It
+ changes nothing on the host; the device stays a member until `team remove`.
+- A reconnect in place keeps the tab's last-seen nodes (the pre-existing re-fetch follow-up in
+ `docs/remote-sessions.md`).
+
+**What the joiner is told** (`@shared/relay-join-errors.ts` for the codes, `lib/hostedTeam.ts` for
+the sentences):
+
+| Code | Cause (main) | Retried unattended? | What the user sees |
+|---|---|---|---|
+| `E_JOIN_BAD_CODE` | The code does not decode or verify | No | "The invite code for X is not valid. Ask an owner for a fresh code." |
+| `E_JOIN_REFUSED` | `/device` refused (not 429 or 5xx), a freshly minted token rejected, or an unreadable/unwritable bookmarks file | No | "Could not join X: " + main's sentence (it names the file when that is the cause) |
+| `E_JOIN_RATE` | `/device` 429 without `scope:'ip'`: the free daily device-mint damper | No | "Too many join attempts for X today. Try again tomorrow." |
+| `E_JOIN_THROTTLED` | A 429 with `scope:'ip'` on `/device`, or any 429 on `/join`: the per-IP limiter (30 a minute) | Yes, ≥ 60 s | Unattended: "The nodeterm service is limiting requests from this network — retrying in a minute." (once per streak). A pasted code: "… Try again in a minute." |
+| `E_JOIN_NETWORK` | Fetch failure or timeout, a 5xx, a malformed reply, a relay endpoint the desktop will not dial, anything unexpected | Yes | A pasted code: "Could not reach X: …". An unattended attempt keeps retrying without a notice. |
+| `E_JOIN_REVOKED` | `/join` 403: the backend revoked this device | No | "This device's access to X was revoked. Remove the team and join again with a fresh invite code.", with a **Remove and rejoin** action |
+| `E_JOIN_KEY_LOCKED` | The peer key's keyring is locked | No | "Could not load this device's identity to join X: " + unlock instructions |
+| `E_JOIN_BUSY` | Another join of ours for the same team is still running | No | Nothing: the running attempt answers |
+
+Once connected, the host's own refusals arrive over the encrypted tunnel: "An owner declined the
+request.", "No owner answered the request in time." (a first join waits up to the host's 10-minute
+pending window) and "Your access to this team was removed by an owner.". While a mount is still
+unapproved after 2.5 s, the tab says "Waiting for an owner of X to approve this device…".
+
+## Owner approval
+
+- A device whose key is not in `team.json` becomes a **pending request**: `{pendingId, sas,
+ peerKeyB64, since}`. It is sent to connected **owners only**, never broadcast, so a viewer never
+ learns who is knocking. An owner who connects later is sent the ones still open, and pulls them
+ once more on mount (`relay:hosted:pending`), because that replay can land before the tab
+ subscribed.
+- At most **one** request per device key (a newer connection replaces the older one) and **16** at
+ once. A request expires after **10 minutes** or when the joiner's socket closes. Pending requests
+ live in memory: a service restart drops them, and the joiner tries again.
+- Owners answer from a **desktop** hosted tab. The dialog queues requests (keyed by `pendingId`,
+ oldest first). Enter never approves, Escape denies only once the dialog is armed and never on a
+ held key, and focus lands on Deny. When two owners see one request, the first answer wins; an owner
+ whose screen still showed it is told "Another owner answered this request."
+- An approval is pinned only after **both** humans confirmed. A deny or expiry that lands while that
+ pin is being written wins: the write is skipped, or taken back.
+- The CLI has **no** approve verb. `team status` lists pending requests by SAS and says to approve
+ from an owner's desktop. The only way the CLI admits a device is `team add-owner`, which makes it
+ an owner.
+
+## Status and troubleshooting
+
+`team status --json` returns:
+
+| Field | Meaning |
+|---|---|
+| `enabled` | A scheduler is running (hosting is on). |
+| `off` | `null` while hosting is on; otherwise `{reason}`: `no-team` (run `team init`), `no-host-key`, `host-key-unreadable` (with `detail`, the loader's sentence), or `stopped`. |
+| `scheduler.state` | `running`, `stopped`, or `backend-refused` (a 402/403 from `/v1/relay/host-token`: minting stops until the service restarts; `team init` does not restart it). |
+| `scheduler.lastError` | The most recent failure **since the relay leg was last proven to work**, not a current fault: `network`, `network (<status>)`, `rate-limited (429)`, `refused (402)` / `refused (403)`, `bad-response`, `mint failed: …`, `relay closed the idle listener`, `open failed: …`, or `mint budget`. It clears when an idle listener holds its registration to its refresh, or when a peer completes a handshake. |
+| `scheduler.mintsLastHour` | Host tokens minted in the last (rolling) hour. The scheduler never mints more than **200** in an hour (counted per running service, so a restart starts over); the backend's free limit is 240. |
+| `scheduler.idle` / `scheduler.bridged` | Idle listeners (the target is one) / sessions joined or awaiting approval. |
+| `peers[]` | `{label, role, connected}`. No keys: find them in `team.json`. |
+| `pending[]` | `{pendingId, sas, peerKeyB64, since}`. |
+
+The human `team status` reads `state`, `idle` and `lastError` together:
+
+| Line | Means |
+|---|---|
+| `Hosting: OFF — …` | `off.reason`, spelled out. For `host-key-unreadable` it is the loader's sentence. |
+| `Hosting: STOPPED — the nodeterm API refused to issue relay tokens (…)` | `backend-refused`. Restart the service once the backend side is fixed. |
+| `Hosting: ON — listening for teammates.` | An idle listener is registered. An "Earlier failure" line under it is history, not a fault. |
+| `Hosting: ON, but not reachable yet — retrying. Last error: …` | No idle listener and a recent failure: minting or the relay is failing, with backoff. |
+| `Hosting: ON — opening a listener.` | Starting up. |
+
+**The scheduler's rules**, since they explain most of what `status` shows:
+
+- Keep **one** idle listener registered. Refresh it 30 s before its token expires (measured on the
+ server's clock from the response's `Date` header), never sooner than 15 s. With the relay's
+ 120 s host tokens that is one mint per 90 s, about 40 an hour while idle, plus one per peer that
+ completes a handshake (its listener is replaced).
+- Back off 1, 2, 4, 8, then every 15 s on failure. The backoff resets only on **proof the relay leg
+ works** (an idle listener held to its refresh, or a completed handshake), or on a fresh start.
+ **Never on a successful mint**: when the API is up and the relay is down every mint succeeds and
+ every socket dies, and resetting on the mint re-minted at round-trip speed (relay log,
+ 2026-09-27).
+- A 429 waits at least 60 s (longer if `Retry-After` says so).
+
+**Common situations:**
+
+- **`host-key-unreadable`.** Hosting stays off and the key is **not** replaced (a new key would
+ invalidate every bookmark). Restore `host-key.json` from a backup and run `team init` (no restart
+ needed), or run `team rotate-key` on purpose and hand out new join codes.
+- **A corrupt `team.json`** is set aside as `team.json.corrupt-<ms>` and hosting starts **closed**:
+ no members, so nobody auto-reconnects. Recover with `team add-owner`. A file listing one key twice
+ counts as corrupt.
+- **`team.json` edited by hand while the service runs** is not re-read until the service restarts;
+ the next CLI write replaces it with the service's copy. Use the CLI.
+- **Two servers on one data directory:** the second one finds the admin socket answering and
+ **does not host** (it logs "Hosted team relay: NOT started — another nodeterm server is already
+ running on this data directory …").
+- **"The nodeterm server is not running (no admin socket …)"**: the service is down, runs with
+ another data directory (pass `--data-dir`), or predates this feature and needs a restart after
+ updating.
+- **"Permission denied on …admin.sock"**: run `team` as the service's unix user.
+- **The installer's daily auto-update** (unless installed with `NODETERM_NO_AUTOUPDATE=1`) rebuilds
+ and restarts the service: live tabs drop and reconnect, and pending requests are lost.
+- **Windows:** the admin channel is a unix socket, so both ends refuse by name. A team cannot be
+ created on a Windows Server Edition in v1.
+- **Removing a teammate.** Approved devices are pinned with an **empty label**, and `team status`
+ shows no keys. Find the key in `<dataDir>/relay/team.json` (match `addedAt`, or the 8-character
+ fingerprint the approval dialog showed), then `team remove <key>`.
+- **Changing a role.** There is no verb in v1. `team add-owner` promotes a key to owner; for any
+ other change, `team remove` the key and approve the device again with the new role.
+
+## Threat notes
+
+- **The root of trust is the core's unix user.** Anyone who can run as it can read `host-key.json`
+ and `team.json` and reach the admin socket, so they can make themselves owner. The socket's
+ filesystem permissions are the whole gate (0600 in a 0700 directory); there is no admin token to
+ leak into a pane's environment, but there is also no boundary inside one unix account.
+- **Editor means shell access** as the core's unix user, and so, in practice, owner: an Editor's
+ terminal runs as that user and can run `team add-owner`. The approval dialog says Editor is "the
+ same as SSH access".
+- **A Viewer sees terminal output** (the dialog says "including anything printed in them") and can
+ read **every file** under a shared project's folder, including `.env` files and `.git`.
+- **Nothing is served before mutual approval.** A pre-approval request answers `E_UNAUTHORIZED`
+ and never reaches a handler. Frames that arrive between approval and open (while the pin is
+ written) are held (at most 256), then served through the same checks.
+- **A leaked join code** lets a stranger ask, never enter. At most 16 requests wait at once, one per
+ device key, each for 10 minutes; the 17th is refused.
+- **A pinned device key is a long-lived credential**, like an SSH key: a stolen laptop gets in
+ until `team remove`. A removed key's live sessions are cut and told `removed`, and until the kill
+ lands a session with no team entry is served nothing.
+- **Mid-session key swap** cuts the session on both ends.
+- **No forward secrecy.** The session key is derived from the two static keys plus per-session
+ nonces exchanged in the handshake (`e2ee.ts`), so whoever later obtains either secret key can
+ decrypt a recorded session. This predates the hosted relay.
+- **The host key is never silently regenerated.** Only `team rotate-key` replaces it.
+
+## Limitations (v1)
+
+- **Presence and context metadata cross projects.** Non-editors receive `presence:sync` /
+ `presence:peer` (focus, project ids, cursor chat of every client on the core) and
+ `context:update` (token counts and model per agent session) for everything on the core, shared or
+ not. The recommended deployment is **one core per team**.
+- **A Viewer can still pause a shared terminal indirectly.** `pty:flow` pauses are refused, but a
+ relay peer whose socket backlog passes 1 MB takes Stage 2's socket-backpressure ticket, which
+ pauses the shared pty for every subscriber until that backlog drains below 256 KB or the peer
+ leaves. Past 8 MB its output is dropped (redrawn later) and the pause is handed back
+ (`ui-sink-registry.ts`).
+- **Canvas edits in a hosted tab are not saved on the host.** A relay tab never writes the host's
+ workspace (it would replace the whole host index with one project), and the core's canvas
+ reflector persists nothing. So nodes a teammate adds, moves or deletes are live for everyone
+ connected, but are not in the host's project file: a teammate who connects later, or everyone
+ after a host restart, sees the saved canvas. A terminal an Editor starts that way keeps running
+ on the host, but Viewers cannot watch it, because node membership is read from the saved canvas.
+ Only a client attached directly to the core (a Server Edition browser tab) writes the project
+ file; that combination is untested with a hosted team.
+- **One shared project per tab.** A joiner's tab adopts the first shared project; other shared
+ projects are allowed by the policy but not reachable from the UI.
+- **Viewers watch only what is already running.** A terminal must be live on the host (a tmux
+ session, or a session a client holds open). An SSH-project node is watchable only while the host
+ core holds it live, because `sshRemote` is stripped from a viewer's create.
+- **The role is read once per connection in the renderer.** A promotion or demotion reaches the tab's
+ UI only after a reconnect. The host enforces the current role on every message regardless.
+- **Viewer affordances are offered and then refused:** kanban card moves and column edits (they
+ snap back), the add-node menus (the host refuses the terminal), Source Control and Explorer writes,
+ and the board-log comment box for Viewers. Typing is blocked (`disableStdin`) and nodes cannot be
+ dragged.
+- **Owners approve only from a desktop hosted tab.** A Server Edition browser tab has no hosted api,
+ and the CLI cannot approve.
+- **A `pinFailed` session cannot be removed with `team remove`.** When both humans approved but the
+ pin write failed, the session is served as a Viewer with no team entry, so `team remove` answers
+ "No team member has that key." Restart the service: every session is cut, members reconnect on
+ their own, and that device becomes a pending request again. (`team rotate-key` also works, but
+ invalidates every join code.)
+- **Approved devices have no label** in `team.json` and `team status`, and there is no relabel verb.
+- **Device mints are shared by the team.** The backend's free device-mint damper (10 per 24 h) is
+ keyed by the **host's** device id, so every joiner of one team draws from one budget. A device
+ mint that times out after the backend committed it mints again on the next attempt (the endpoint
+ is not idempotent).
+- **The 17th concurrent join request** (and an older request replaced by a newer one from the same
+ device) is refused with the same `denied` reason an owner's decline sends, so that joiner reads
+ "An owner declined the request."
+- **Tabs are not persisted.** After an app restart the tab comes back when its boot reconnect is
+ approved, never as a greyed placeholder.
+
+## Surfaces
+
+- **Desktop:** full. It joins by code, reconnects from bookmarks, and an owner's hosted tab
+ approves requests and copies the invite code. A Viewer's tab gets the read-only banner, a
+ read-only canvas and read-only terminals (canvas node and kanban card modal).
+- **Server Edition:** the **host**, managed with the `team` CLI over SSH. Its browser clients are
+ not hosted peers; the access policy never applies to them, and they cannot call `relay:hosted:*`
+ (those verbs are intercepted inside the relay session and never registered on the platform). A
+ join code pasted into a browser tab gets one "not supported in the browser build" notice.
+- **Mobile:** N/A for v1. The phone still speaks the legacy relay dialect. The host it would join
+ now exists in core (a standing listener on the tunnel dialect); the phone side needs the
+ tunnel-dialect migration (`docs/ios-protocol-migration.md`) and a join flow modelled on
+ `hosted-join.ts`. Nothing here has run against a phone. That is a follow-up for `nodeterm-ios`.
+
+## Device checklist
+
+Owed before recommending the feature. Run the core on a Linux host under a sub-user, with the owner
+on a Mac and a second desktop as a teammate. Record `team status --json` at each step.
+
+1. **Mac lid closed.** With the owner's Mac lid closed, an Editor teammate keeps typing, and can quit
+ and relaunch the app and reconnect with no prompt on either side.
+2. **Mints over one day.** Sample `scheduler.mintsLastHour` hourly for 24 h. Expected about 40 in an
+ idle hour plus one per teammate connection; pass at 60 or less in an ordinary hour, and never
+ `lastError: mint budget` (the 200 cap).
+3. **Viewer refusals.** As a Viewer: the banner says "You're a Viewer in X — terminals are read-only.
+ Ask an owner for Editor access."; typing into a terminal does nothing; nodes do not drag; an
+ editor-node save and a Source Control commit are refused with "Viewers can't do that here. Ask an
+ owner for Editor access." (record where each surface shows it); a kanban card move snaps back.
+4. **Service restart.** `systemctl --user restart nodeterm-server`: every teammate's tab greys and
+ comes back on its own within about 30 s, with no dialog. If the service takes longer, each tab
+ needs one click.
+5. **Removal.** `team remove <key>` on a connected teammate: their tab says "X: Your access to this
+ team was removed by an owner.", and their next attempt is a new join request.
+6. **Owner offline, new device.** With no owner connected, a new device pastes the code: it shows
+ "Waiting for an owner of X to approve this device…", `team status` lists the request, and after
+ 10 minutes the joiner reads "Could not open X: No owner answered the request in time."
+7. **Corrupt host key.** Corrupt `host-key.json` and restart: the journal says "Hosted team relay:
+ OFF — the host key could not be read", `team status` says why, `team init` refuses, and the key
+ file is left as it was.
+8. **Long session.** A teammate stays connected for over an hour without the tab greying. The host
+ never refreshes a bridged session, and the relay broker's source checks a token only when a
+ socket joins; two code comments (`hosted-scheduler.ts`, `standing-host.ts`) say the relay drops a
+ bridged socket at its token's lifetime. This item settles which is true.
+9. **Viewer size.** A Viewer with a small window does not shrink the Editor's terminal.
+10. **Two owners.** With two owners connected, one approves a request; the other owner's dialog
+ closes with "Another owner answered this request."
diff --git a/docs/remote-sessions.md b/docs/remote-sessions.md
index 5da8ca360..04179438e 100644
--- a/docs/remote-sessions.md
+++ b/docs/remote-sessions.md
@@ -473,6 +473,27 @@ made the **host listener** multi-peer and packaged it.
- **Follow-up:** a seat row shows the invite email + generic connected/pending state; joining a seat
to its presence name/color (different id spaces — renderer UUID vs ClientId) is deferred.
+## Hosted team relay (a Server Edition as the host)
+
+Decision 1's asymmetry ("if the host sleeps, the peer's world freezes") now has an answer for a
+team that can run a Server Edition: that core is the relay host, and the sharer's laptop can be
+off. Operator guide, roles and limitations: **`docs/hosted-team-relay.md`**. What it changed here:
+
+- **The relay moved to core.** `e2ee`, `relay-socket`, the trust gate, `relay-host`, `relay-client`
+ and the rest live in `src/core/relay/`; `src/main/remote/` keeps re-export shims and the desktop's
+ own wrappers. `connectRelayHost` gained injected seams (`PeerAttach`, `PinStore`, `autoApprove`,
+ `RelayHostHooks`, `deny()`). Team Access passes no hooks and takes the unhooked path, unchanged.
+- **A standing host on the tunnel dialect now exists in core**: `hosted-scheduler.ts` (one warm
+ idle listener, refreshed against the token's server-clock expiry, with a backoff that resets only
+ on proof the relay works), driven by `hosted-service.ts`. It is the host-side mechanism the iOS
+ tunnel migration below needs. The desktop's own phone host (`standing-host.ts`) is still on the
+ old dialect; rebuilding it on this scheduler is the remaining desktop step.
+- **Roles exist, for hosted peers only.** Viewer, Commenter, Editor and Owner are enforced in the
+ host core (`core/relay/access-policy.ts`). A Team Access peer is still fully trusted (decision 2).
+- **The bookmark follow-up is partly closed, for hosted teams only.** A joined team is bookmarked
+ (`<userData>/relay-bookmarks.json`) and reconnects at boot with no new code, but the tab itself
+ is still not persisted: it appears once the reconnect is approved.
+
## 4a → 4c interface (landed)
The session layer lives in `src/renderer/session/` (`session.ts` + `localSession.ts`).