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.

Merge origin/main into feat/live-share-link

reviewf1abce394a51
diff --cc CLAUDE.md
index fdda26f59,ef1965189..04362a67d
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@@ -5117,29 -5655,141 +5655,164 @@@ detaching + an always-true pressure sig
disappearing" rather than as an occasional cull. The `vm_stat` reader is what makes the pool safe
again; the grace window was never the thing that was wrong.
+## Live links (Pro, read-only browser link to one terminal)
+
+A live link shows ONE node, read-only, in a plain browser until it expires (≤ 24 h) or is stopped;
+creating one is Pro and the backend is the gate. Reference: **`docs/live-links.md`**. Invariants:
+- `watchLink:*` (owner IPC) is host-only: no relay peer, hosted editors included, may create, list (a
+ view carries the secret URL), stop, kick or chat. The viewer protocol is `watch:*` and must never
+ start with `watchLink:` — relay-host refuses host-only channels before any policy, so it could never
+ arrive (`src/shared/host-control.test.ts`, `src/core/relay/scoped-guest-policy.test.ts`).
+- A watcher never goes through `decideAccess` (it would get the VIEW table): `watcher-policy.ts` refuses
+ all but a Commenter's `watch:chat` cast, passes out only `watch:*`, its own pty frames and `pty:size`,
+ and takes no `interceptReq` (`watcher-policy.test.ts`, `chat-cast.guard.test.ts`).
+- Watchers are QUIET (no broadcast, not in `clientIds()`) and SELF-PACED (never paused, dropped or
+ resynced by the registry); the reaper reads `quietClientIds()` too, or it releases a session only a
+ viewer holds (`ui-sink-registry.watcher.test.ts`, `pty-reap.test.ts`).
+- The stream filter sees every byte, has NO length cap (a cap leaked a measured clipboard), and every
+ join resets it `midStream`, never to text mode and never on a keyframe. `captureVisible` never returns
- history (exact `=nt-<id>:`, no `-S`; session host and plain shell get no keyframe). A viewer sizes
- nothing: `joinOnly` + `sizeVote: false`; its own tmux client is `-E -f ignore-size,read-only`.
++ history (exact `=nt-<id>:`, no `-S`; session host, plain shell and a Zellij node get no keyframe). A
++ viewer sizes nothing: `joinOnly` + `sizeVote: false`; its own tmux client is `-E -f ignore-size,read-only`,
++ and a Zellij node never gets one (refused, never a Zellij attach — that client could type).
+- Node gone is tri-state (only ABSENT ends a link; a lost or corrupt index is never a complete read).
+ Link state is never canvas content, no canvas-control verb touches links, the chip is not hideable
+ (`src/renderer/lib/live-link.guard.test.ts`); both shells wire one core service, the Server Edition as
+ `unsupported` until it has a license layer (`src/main/watch-link-wiring.test.ts`).
+ ## Dev-server ports (the Ports chip + same-port SSH forwarding)
+
+ An agent starts a dev server inside a node's session; on an SSH project it listens on the HOST's
+ `127.0.0.1:<port>`, and before this the person had to build a tunnel by hand before a browser node
+ could show it. A terminal node's header (and its kanban card modal — one component, `PortsChip`)
+ now shows the TCP ports that node's session listens on; a row opens `http://localhost:<port>` in a
+ browser node beside it, and on an SSH project it first forwards the SAME port number over the
+ project's existing ControlMaster, so the URL the tool itself printed just works here. Pieces:
+ `core/dev-ports.ts` (probe + parsers), `core/remote-ssh/port-forward.ts` (lifecycle),
+ `core/dev-ports-service.ts` (routing), `renderer/components/PortsChip.tsx`,
+ `renderer/state/devPorts.ts` + `canvas/useDevPortScanner.ts` (cadence), `lib/devPorts.ts` (pure).
+
+ - **Discovery is by OWNERSHIP, never by probing.** A port is attributed to a node only when its
+ listening socket belongs to a process inside that node's tmux pane tree (every pane of `nt-<id>`,
+ the same tree session memory rolls up — `indexProcesses` is shared). Nothing is ever connected to,
+ and another user's or another program's port is never reported. The owning pid comes from
+ `ss -ltnp` (Linux), else `lsof -nP -iTCP -sTCP:LISTEN -Fpcn` (macOS, Linux without iproute2 — its
+ exit 1 with no output is an ANSWER, "nothing listening"), else `/proc/net/tcp{,6}` joined to
+ `ls -l /proc/*/fd` by socket inode (one `ls`, never a `readlink` per descriptor). No tool at all is
+ its own failure (`no-listener-tool`), never "no ports".
+ - **The listener tools' output is attacker-influenced text — parse it as such** (review of #1063,
+ reproduced on the dev host). ss prints a holder as `("<name>",pid=N,fd=M)` with the process NAME
+ raw, and any process can rename itself: as root, a listener owned by `nobody` named
+ `vite",pid=12345` printed `users:(("vite",pid=12345",pid=219072,fd=3))`. Collecting every `pid=`
+ on the line handed that stranger's port to whichever node's tree holds 12345 (pane pids are
+ visible to every user via `ps`), and the forward then served the attacker's page on
+ `localhost:P` — where it receives the cookies of every OTHER localhost dev app (cookies are not
+ port-scoped). Two defences: each `(…)` group is parsed on its own and only its LAST
+ `,pid=N,fd=M` counts (ss cannot print `)` inside a name, so a greedy `[^)]*` cannot be steered
+ past it), and `assembleDevPorts` requires the tool's name for that pid to agree with `ps`'s
+ (prefix-tolerant: Linux comm is 15 bytes, lsof's `c` 9, macOS ps prints the full basename). The
+ `/proc` branch had the same class: GNU `ls -l` prints a NEWLINE in an fd's link target raw, so a
+ target `a\n/proc/100/fd:\nl -> socket:[999]` forged a pid header; it is `ls -lq` now. Both
+ are tested under a real `/bin/sh`, and the ss one also END TO END: a real process outside the
+ pane tree renames itself (`prctl(PR_SET_NAME)`) to name the pane's pid, real `ss` prints the
+ forged group, and the port is not attributed.
+ - **The LOCAL scan asks the app's own tmux** (`tmuxBin: ptyManager.getTmuxBin()`, the resolver
+ session memory is given, quoted into the script). A bare `tmux` answered 127 on both sockets for
+ a Mac whose only tmux is the bundled one and for a Linux tmux reachable only on the login-shell
+ PATH (nix, linuxbrew) — `unreachable`, no chip ever — and a different tmux client against the
+ app's server can hit a protocol mismatch. No tmux at all is `unsupported` (plain shells own no
+ pane tree). An SSH host keeps `tmux` via the PATH append.
+ - **One generated script, run on BOTH machines.** `devPortsProbeCommand` is POSIX sh; a local project
+ runs it through `/bin/sh -c`, an SSH project over the master — one round trip carrying the panes of
+ both nodeterm sockets (fenced per socket with the SAME `fencedListPanesCommand`/`parseFencedPanes`
+ session memory uses, so "no server running" is an answer and a broken tmux on every socket is
+ `unreachable`), `ps -eo pid=,ppid=,comm=`, and the listener section. One script, one parser: a
+ separately written local leg is the drift the session-memory ledger records three times. PATH is
+ APPENDED with the tmux dirs and `/usr/sbin:/sbin` (where `ss`/`lsof` live on some distros and a
+ non-login exec channel's PATH lacks them). Every marker is quoted (`echo ##X` prints an empty line
+ under POSIX sh). Tested under a real `/bin/sh` against a fake host tree, one case per branch, AND
+ end to end on Linux: a real tmux session (private socket, sandboxed TMUX_TMPDIR) running a real
+ listener two processes below its pane, read back through real `ps` + `ss`
+ (`dev-ports.realsh.test.ts`).
+ - **Ports in the ephemeral range (≥ 32768) are listed but not counted.** A headless browser's
+ debugging endpoint or an MCP helper asks for "any port" and lands there; a dev server a person
+ means to open almost never does. The chip counts only the rest and is absent when there are none;
+ the others sit one level down in the menu ("Other ports").
+ - **Cadence** (`lib/devPorts.ts`): a scan when the project comes on screen and on window focus; a
+ debounced trailing scan 4 s after the project's agents report activity (`onHookEvent` — a dev
+ server is usually an agent's tool call); a slow poll (30 s local, 60 s SSH) ONLY while the window is
+ focused and visible — a server started by hand in a plain terminal fires no hook; and on demand when
+ the chip's menu opens. **Both automatic triggers — the hook lull AND the poll — check "someone is
+ watching" at fire time**; the hook one did not at first, so every agent turn in a backgrounded
+ window cost an exec on the host (`ps` + `ss -p` across every process's fds as root). Automatic scans keep a 10 s gap; concurrent ones coalesce in core. An SSH
+ project is scanned only while connected. One scan costs one `ps` plus one `ss` (a few lines) — an
+ exec over the master on a host, never a login.
+ - **Forwarding rules — each a refusal, never a guess** (`PortForwardRegistry`):
+ - The renderer names a node and a port, never an address. Core re-scans at click time and forwards
+ only a port that scan attributes to THAT node; the host-side target FOLLOWS THE BIND
+ (`forwardTarget`: any IPv4 wildcard/loopback → `127.0.0.1`, else `::1`, else the one specific
+ address), because a server bound only to `::1` refuses `127.0.0.1`. The target is re-validated as
+ an IP literal — it came off another machine's command output and lands in an ssh argument.
+ - The local side binds `127.0.0.1` ONLY (`localForwardArgs`), never `*`: an unfinished app must not
+ be published to the network the laptop is on. `localFwdSpec` re-validates both ports and the
+ target at the argv site (rule 13) and throws, which the registry reports as a failed forward.
+ An IPv4-mapped bind (`::ffff:127.0.0.1`) is normalized to its IPv4 address first — it used to
+ make `forwardTarget` answer null, reported as a misleading SSH refusal (now its own
+ `unreachable-address`).
+ - **A taken local port is refused with the reason, never silently moved.** "Taken" means anything
+ answers on `127.0.0.1:P` OR `[::1]:P`, or 127.0.0.1 cannot be bound: a local app bound only to
+ `::1` leaves 127.0.0.1 free, the forward would succeed, and the browser's `localhost` (IPv6 first)
+ would show the LOCAL app under the host's name. A different local port is only ever the person's
+ explicit choice (a confirm naming a suggested free port, and saying the tool's printed links will
+ not reach it). The facts are two connects and one bind, ordered by the pure `localPortVerdict`:
+ an answer on `::1` is busy; a bind refused with EACCES/EPERM is `local-port-denied` (a confirmed
+ privileged port on Linux as non-root — "already in use" was a lie), with a free unprivileged port
+ offered; a bind refused as IN USE may be OUR OWN master's listener — after an app crash the
+ adopted ControlPersist orphan keeps its forwards while the registry starts empty — so the
+ identical forward is re-issued: the holding master acknowledges it with 0 (measured) and it is
+ re-adopted, anything else answers 255 and it stays busy; a v4 answer we could still bind beside
+ (BSD wildcard + SO_REUSEADDR) is busy, never shadowed.
+ - A privileged port (< 1024, either side) is never forwarded until the person confirms it.
+ - Lifecycle: cancelled (`-O cancel` with the exact spec) when the node's session ends
+ (`PtyManager.onSessionEnded` — delete and recycle) or when a SUCCESSFUL scan no longer lists the
+ host port UNDER THE NODE THAT OWNS THE FORWARD (the same number under another node is not the
+ server the person opened). The renderer scans only the project on screen, so core re-checks on
+ its own: a sweep (`FORWARD_SWEEP_MS`, 60 s) armed ONLY while a forward is held re-scans each
+ forwarding project, skipping one reconciled within the interval — without it, a project switched
+ away from or closed (neither disconnects) kept its forwards bound after the dev server died, the
+ local port stayed taken (a local dev server silently moved to P+1), and whatever later bound the
+ host's P got the traffic; dropped without ssh when the project leaves `connected` (the master takes its
+ listeners with it). A failed scan cancels nothing — a failed read is never evidence. A master
+ rebuilt behind our back by `ControlMaster=auto` (issue #735's mechanism) carries no `-L`, so every
+ successful scan re-checks that the local listener is still held and forgets one that is not — the
+ menu then offers to forward again instead of claiming a dead forward.
+ - Main wires both lifecycle hooks; `main/dev-ports-wiring.test.ts` pins them at source level,
+ because a dropped listener compiles and leaves forwards open after their node closed.
+ - **MEASURED against a real OpenSSH 9.6p1 sshd + mux master (2026-09-30, lab on loopback):**
+ `-O forward -L 127.0.0.1:P:[::1]:P` exits 0 and `http://localhost:P` answers 200 through it (the
+ bracketed IPv6 target works); the IDENTICAL forward again exits 0 (the master dedups it); a local
+ port already bound by another process exits **255** with `mux_client_forward: forwarding request
+ failed: Port forwarding failed` — synchronous, so a refusal is known at click time; `-O cancel`
+ closes the listener (curl then gets connection refused) and exits **0 even when nothing was
+ forwarded** (it only prints an error), which is why its exit code is ignored; `-O exit` takes every
+ forward with it.
+ - **Surfaces.** Desktop: full (local projects: discovery + open, no forward — the port is already on
+ this machine; SSH projects: discovery on the host + same-port forward). Windows: the local probe
+ answers `unsupported` (no `/bin/sh`, no tmux) and the chip is not drawn; an SSH project from a
+ Windows desktop still works (the probe runs on the host). **Server Edition: not served, on
+ purpose** — the browser node is an Electron `<webview>` a browser tab does not have, and a page the
+ viewer opened would load on the VIEWER's machine, where the server's port is not. Its bridge stub
+ answers `unsupported`; nothing registers the service in `src/server`. Relay tabs: the same stub
+ (their sessions live on the host). Kanban: the card modal draws the chip when the card's project is
+ the one on the canvas; opening a port hands over to the canvas, where the browser node appears
+ beside the node. **Mobile: follow-up** — the phone would need the port list over the relay and a
+ forward of its own (it has no local browser node); noted for nodeterm-ios. All three channels are
+ in `HOST_ONLY_CHANNELS` (a forward binds a port on the host machine's loopback).
+ - **Known limits, stated:** a re-adopted orphan forward (above) is only re-claimed when the person
+ opens that port again; until then the chip does not show it as forwarded. A server that DAEMONIZES (double-fork, reparented to init) leaves the
+ pane tree and is not found; `ss` without `-p` information for our own processes (hidepid, a
+ container) finds listeners but no owner, so nothing is attributed; the Mac leg (lsof, the local
+ bind/connect probes under BSD socket rules) has not been run on a Mac — device checklist in the PR.
+
## Node colors (one palette, two sections)
`src/shared/node-colors.ts` is the palette AND the control boundary — the picker's list and the
diff --cc docs/live-links.md
index f5e311a2d,000000000..bd997483a
mode 100644,000000..100644
--- a/docs/live-links.md
+++ b/docs/live-links.md
@@@ -1,540 -1,0 +1,547 @@@
+# Live links (a Pro, read-only, expiring browser link to one terminal)
+
+**Status:** built on `feat/live-share-link` (2026-09/10). Everything below was checked against the code
+on that branch. The design spec (`docs/superpowers/specs/2026-09-28-live-share-link-design.md`) is the
+record of how the design was reached; where it and this file disagree, the code and this file win.
+
+**Builds on:** `docs/hosted-team-relay.md` (the core relay host, `RelayHostHooks`, the hosted
+scheduler), `docs/team-presence.md` (co-attach), `docs/remote-sessions.md` (the relay and its trust
+gate).
+
+## What it is
+
+A **live link** is a URL, `https://nodeterm.dev/s/<linkId>#1.<S>`, that shows ONE terminal or agent
+node live in a plain browser tab: no install, no account, no Team Access seat. The viewer cannot type,
+paste, click, resize or pause anything. The link ends when it expires (15 min, 1 h (default), 8 h or
+24 h, never extended), when the owner stops it, or when its node is deleted.
+
+- **Creating one is Pro, and the backend is the gate** (`POST /v1/watch-links` checks a live license;
+ a `free:` or companion token is refused). The renderer's `requireProOr('Sharing a live link', …)` is
+ UX only. The repo is public, so a local `isPremium()` is an honesty gate; a feature that runs through
+ `api.nodeterm.dev` and the relay cannot be patched out.
+- **Viewing is free.** Every viewer lands on nodeterm.dev.
+- **The owner's terminal is unaffected by viewers**: no input, no size vote, no pause ticket, no
+ slowdown. A leaked link exposes that node's live screen and nothing else, and only until it expires.
+ The relay and the API never see terminal content.
+- **Viewer** links watch; **Commenter** links watch and chat (ephemeral, memory-only, never written to
+ a file). The role is host-side record state, never in the URL, so a holder cannot upgrade themselves.
+
+Names: in this codebase "share" means a project shared with a hosted team, so the UI says **"Live
+link"**, the code says **`watchLink`** (owner IPC, `src/core/watch-link/`), the relay role is the
+**watcher**, and a connected browser is a **viewer session**.
+
+## How it fits together
+
+| Piece | Where | Notes |
+|---|---|---|
+| Keys, URL, wire, protocol, browser client | `src/shared/watch-link/` (`keys.ts`, `link.ts`, `wire.ts`, `protocol.ts`, `client.ts`, `vectors.json`) | Isomorphic: tweetnacl + WebCrypto, no Node API. **nodeterm-web vendors it byte-identically** and runs the same vectors. A protocol change lands here first, with new vectors, then is copied. |
+| Owner types | `src/shared/watch-link-types.ts` | NOT vendored. TTLs, `MAX_LINKS_PER_MACHINE` (5), `LABEL_MAX` (40) / `TITLE_MAX` (80, UTF-16 units), the renderer-facing `WatchLinkApi`, `stripBidiControls`. |
+| Registry / service | `src/core/watch-link/service.ts` | Lifecycle, limits, persistence, node-gone, owner state, the ten owner channels (`registerWatchLinkIpc`). Both shells create it. |
+| Link host | `src/core/watch-link/link-host.ts` | One hosted scheduler per link, a `connectRelayHost` session per viewer, joins, keyframes, throttling, chat, kick. |
+| Watcher policy | `src/core/watch-link/watcher-policy.ts` | The `RelayHostHooks` of a viewer session: `watcherAccess` (inbound) and `wrapWatcherSink` (outbound). |
+| Output filter | `src/core/watch-link/stream-filter.ts` | Strips string-type escape sequences from the viewer's stream. |
+| Token bucket | `src/core/watch-link/token-bucket.ts` | Per viewer, 256 KB/s sustained, 1 MB burst. |
+| Visible capture | `src/core/watch-link/capture-route.ts` + `PtyManager.captureVisible` | The keyframe. Never history. |
+| Watcher's own tmux client | `src/core/watch-link/watcher-client.ts` + `PtyManager.joinAsWatcher` / `syncWatcherClientSize` | Only when no owner `Session` is held for the node. |
+| Pty seam | `src/core/watch-link/pty-seam.ts` (`createWatchPty`) | ONE definition of the join rules, both shells wire it. |
+| Store | `src/core/watch-link/store.ts` | `<userData>/watch-links.json`, sealed. |
+| API client | `src/core/watch-link/api.ts` | create / host-token / status / revoke / revoke-all. |
+| Existing-code seams | `ui-sink-registry.ts` (`quiet`, `selfPaced`), `pty-reap.ts` (`liveClientIds`), `hosted-scheduler.ts` (`maxBridged`), `host-control.ts` (`watchLink:`), `workspace-store.ts` (`knownNodeIds`, `indexRebuiltThisRun`) | The registry and scheduler options are inert for every caller that passes none. `knownNodeIds()` answering unknown after a rebuilt index is NOT link-only: the agent-status mirror's existence pruning pauses for that run too (R54). |
+| Shell wiring | `src/main/index.ts`, `src/server/index.ts` (search "Live links") | Pinned at source level by `src/main/watch-link-wiring.test.ts`. |
+| Renderer | `state/watchLinks.ts`, `lib/liveLink.ts`, `lib/liveLinkEntry.tsx`, `components/LiveLinkChip.tsx`, `LiveLinkPopover.tsx`, `LiveLinkDialog.tsx`, `settings/sections/LiveLinksSection.tsx` | One chip on four surfaces; availability before the Pro gate. |
+| API | nodeterm-server `watch_links` table + six routes | Merged (server#8). |
+| Viewer page | nodeterm-web `src/pages/s/[id].astro` + the vendored client | web#2. |
+
+End-to-end coverage lives in `src/core/watch-link/link-host.test.ts` (the REAL relay host, the REAL
+hosted scheduler and the REAL browser client `connectWatchClient` over an in-process transport) and
+`src/core/watch-link/client.test.ts` (the browser client against the real host socket).
+
+## The link and its keys
+
+`linkId` is 16 random bytes chosen by the **server** (base64url, 22 chars): it names a link and
+unlocks nothing. `S` is 32 random bytes chosen by the **host** (base64url, 43 chars), carried in the
+**fragment**, so it never reaches an HTTP request, a server log or a referrer. `1.` versions the
+fragment format. The fragment is not removed from the address bar (the link must stay copyable).
+
+Everything is derived from `S` (`keys.ts`), hash-based and synchronous so Node and the browser compute
+identical bytes:
+
+| Value | Derivation | Known to |
+|---|---|---|
+| Host key pair | `nacl.box.keyPair.fromSecretKey(SHA512("nodeterm-watch-link-v1/host" ‖ S)[0..32])` | host, any link holder |
+| Viewer key pair | the same with `…/viewer` | host, any link holder |
+| `joinKey` | `SHA512("nodeterm-watch-link-v1/join" ‖ S)[0..32]` | + the API, which stores only `sha256(joinKey)` (hex) and sees `joinKey` only in a join request |
+
+The three are domain-separated, so the API learning `joinKey` reveals nothing about the key pairs.
+Test vectors: `src/shared/watch-link/vectors.json`.
+
+**The relay handshake is unchanged, and so is the broker.** The viewer is an ordinary relay client
+whose key pair happens to be derived: it sends `e2ee_hello` with the viewer public key, the host
+answers from `e2ee.ts` as for any peer, and the encrypted auth exchange runs as today. Nothing in
+`relay-socket.ts` or the broker changed. The pairing id is `wl.<linkId>` (the broker validates no
+format; the prefix makes watch-link traffic recognisable in its 12-char log lines). What changed is
+the trust gate's input:
+
+- `autoApprove(peerKeyB64)` compares the handshake's key with the viewer key **derived from the host's
+ own link record**, never with anything the peer sent. Any other key reaches `onPeerPending`, which
+ **denies at once**: a link session never raises an approval dialog, shows no SAS and has no pin
+ store. This is one of the six LOCAL confirm sites `src/core/relay/relay-trust.ts` enumerates.
+- The viewer sends its own `trust:confirm` automatically: holding the link is its consent.
+- Host authenticity: a link holder can derive the host key pair, but registering as host in
+ `wl.<linkId>` needs a host token minted with the owner's entitlement for that link's license.
+
+The viewer protocol's namespace is **`watch:`**, never `watchLink:`. The owner's IPC is `watchLink:*`,
+which `relay-host` refuses from every peer as host-only BEFORE any policy runs, so a viewer cast in that
+namespace could never arrive.
+
+Host → viewer: `ev watch:meta {v, role, label, title, expiresAt, cols, rows}` (after EVERY join, not
+only the first: the page leaves "waiting" on a meta), pty output as binary `encodePtyData` frames,
+`ev pty:size:<sid>`, `ev watch:keyframe {sessionId, screen, altScreen, cursor?}`, `ev watch:chat`,
+`ev watch:waiting {}`, `ev watch:end {reason}`. Viewer → host: `cast watch:chat {name, text}`
+(Commenter only), `trust:confirm`, keepalives. **There is no input, resize or flow message in the
+protocol.** `session-ended` is a defined end reason the host never sends in v1: a session that exits
+answers `watch:waiting`, and the host rejoins when one appears.
+
+## The watcher role
+
+A viewer is a core client, so the risk of this design is that some existing outbound path reaches it.
+Two independent layers close that, plus deny-by-default in both directions.
+
+**Inbound** (`watcherAccess`): every request and every cast is refused, except a Commenter link's
+`watch:chat` **cast** (never a request). Host-only channels are refused `E_FORBIDDEN` by relay-host
+before the hook runs; everything else answers `E_ROLE`. The link host's own `PeerAttach` is a second
+layer that FAILS CLOSED: a request or a non-chat cast that reaches it means the access hook let
+something through, so the session is closed. No `interceptReq` is ever supplied (it would bypass
+`access`). A `watch:chat` cast is accepted only from the link host's own viewer sessions:
+`chat-cast.guard.test.ts` fails on any source outside a four-file allowlist that names it, so no
+platform handler can let a hosted Editor or a Server Edition tab inject viewer chat.
+
+**Outbound** (`wrapWatcherSink`, controller ruling R16): `watch:*` events, this viewer's own pty data
+frames (filtered and paced) and its own session's `pty:size`, and nothing else.
+
+- `pty:exit` / `pty:closed` / `pty:recycled` are CONSUMED (`onLifecycle` → `watch:waiting`) and never
+ forwarded: `pty:closed` carries `{by: ClientId}`, which identifies another client of this core.
+- `pty:resync` is refused: its payload is the registry's default capture, which is history on the SSH
+ and session-host paths and carries OSC 8 verbatim. A watcher repaints only through `watch:keyframe`.
+- Another session's binary frame is rejected on its header alone and never reaches this viewer's
+ parser.
+
+**Quiet** (layer two): a watcher is registered `{quiet: true, selfPaced: true}` (desktop
+`registerPeerSink`, Server Edition `platform.attach`), with no presence join (no cursor or facepile on
+the owner's canvas). Quiet means absent from
+`broadcast()` and `clientIds()`, reachable only by `sendTo`. Canvas ops, presence, agent status and
+context updates therefore cannot reach it by either path. **The pty reaper is the one consumer that must
+still count it**: it decides "is anyone watching this session?" from the client list, and a session
+only a watcher holds would be released after 10 minutes with no event. So the reaper reads
+`liveClientIds()` = `clientIds()` ∪ `quietClientIds()` (`pty-reap.ts`).
+
+**Why not `decideAccess`.** `access-policy.ts` evaluates any non-editor role against the whole VIEW
+table (files, git, presence, board log, each with an argument check). A live link may reach none of it,
+so it has its own two-line policy rather than a row in a table built for teammates.
+
+**Why no argument comes from the viewer.** The host joins the node's session itself:
+`joinAsWatcher(clientId, {persistKey: nodeId, viewerId: v-<8 hex>})` with `joinOnly: true` and
+`sizeVote: false` forced after any spread, and for an SSH-project node `requireRemote: true` plus the
+`sshRemote` of that project's own ControlMaster from THIS machine's records (a downed master must not
+let the local strict probe attach a same-named local orphan). The hosted Viewer path strips a
+peer-supplied `sshRemote`; here there is nothing to strip, because nothing is taken.
+
+## Backpressure and the stream filter
+
+**A viewer never slows the owner.** A watcher is **self-paced**: the sink registry hands it every pty
+frame and never takes a pause ticket for it, never drops for it and never resyncs it
+(`ui-sink-registry.ts` returns before `dropOrDesync`, the only way into a desync). The watcher's own
+sink does the drop-and-redraw, because only it can keep the stream filter in step with the pty: a frame
+the registry dropped would never reach the parser, and a string sequence cut in half would leak its tail
+as text. (This closes, for links, the residual `docs/hosted-team-relay.md` documents for hosted Viewers,
+whose backlog still pauses the shared pty.)
+
+The watcher's bounds, since the registry no longer bounds it:
+
+- pty frames stop at **512 KB** buffered (`WATCHER_BUFFER_LIMIT`); the viewer is repainted with a
+ keyframe once its socket drains below **256 KB** (`WATCHER_RESUME_BELOW`);
+- a per-viewer token bucket, **256 KB/s sustained, 1 MB burst**, counted in encoded bytes; past it the
+ stream stops and at most one keyframe a second is sent (bounds relay traffic under `yes` or a verbose
+ build). A frame larger than the burst can never pass, and goes over budget like any refusal;
+- chat is skipped for a viewer past 512 KB, and a viewer past **8 MiB** is closed (viewer gone, not a
+ revoke): a socket that never drains must not grow the host's memory.
+
+**The filter sees every byte.** `stream-filter.ts` removes every string-type sequence (OSC, DCS, APC,
+PM, SOS, 7- and 8-bit): clipboard contents (OSC 52 — tmux emits one on every copy with `set-clipboard
+on`), titles, hyperlink targets, file transfers, palette changes. CSI, other ESC sequences and text pass
+unchanged. It is stateful across chunks and must parse every byte **even while nothing is forwarded**
+(throttled, over budget, before the keyframe): a frame that skipped the parser would leave it
+mid-sequence and print the tail of an OSC 52 as text. It is reset only when the viewer joins a pty
+session, never on a keyframe. Where a string starts and ends follows xterm 5.5's VT500 table (checked by
+a differential test against the verbatim table in `__fixtures__/xterm-vt500.ts`); where xterm ends a
+string on something this parser does not (CAN, SUB, other C1, non-ASCII inside SOS/PM/APC), the viewer
+misses a little text, never sees more than the owner. Output guarantee: no push emits an 8-bit
+introducer or ends on ESC, so the viewer's parser can never be put into a string state, even by
+drop-and-redraw.
+
+**There is no length cap** (controller ruling R15). A string is swallowed until its terminator, however
+long. xterm has none (it stays in a string until ESC, ST, BEL for an OSC, CAN or SUB), so a cap could
+only ever show a viewer bytes the owner's screen does not show. An earlier version resumed text past
+1 MiB; measured on tmux 3.4 with the app's clipboard settings, a 900 KB copy became one 1.2 MB OSC 52
+and 151,428 characters of the clipboard's base64 reached the viewer. The filter keeps no buffer, so
+there is nothing for a cap to bound. Tests pin a 2 MiB and a 16 MiB OSC 52 swallowed whole (the latter
+past xterm's own 10,000,000-char payload limit, the value most tempting to re-add).
+
+**Every join starts mid-stream** (R12). A viewer co-attaches to a RUNNING session, so its first byte may
+fall inside an OSC 52, or right after an ESC the previous read ended on (`]52;c;…` would then read as
+text: the whole clipboard). Measured before the fix: 19,148 of 200,000 random joins leaked. So every
+join does `reset({midStream: true})`: the filter starts as if an unknown DCS-kind string had just begun
+(BEL does NOT end it, since the unknown string may be a DCS or APC where BEL is data) and shows nothing
+until the next ESC, ST or 8-bit introducer. Frames that arrive before the session id is known never
+reach the filter, so a join can never start in text mode. The filter is never reset to text mode to
+"unstick" it: inside a string that prints the string's payload.
+
+**`onSettled`** (R23): the filter reports once when it leaves that unknown start state. The join
+keyframe is sent at once; if the filter had not settled by then, one follow-up keyframe is taken when it
+does, plus one at `SETTLE_BOUND_MS` (2 s) after the join if it still has not.
+
+## Keyframes
+
+A keyframe is `PtyManager.captureVisible(sessionId)`: **the visible screen, never history**.
+
+- **local tmux:** `capture-pane -p -e -t =nt-<id>: ; display-message -p -t =nt-<id>: '#{cursor_x}
+ #{cursor_y}'` in ONE invocation, so screen and cursor describe the same instant (no `-S`, which is
+ what makes it visible-only);
+- **SSH:** the same over the project's ControlMaster (`remoteCaptureVisibleArgs`), again without the
+ `-S -200` the existing remote builder always adds; proven under a real `/bin/sh`;
+- **Windows session host and the direct Windows pty: none.** `sessionHostCapture` returns ~200 lines of
+ scrollback, not the visible screen; a visible-only read needs an additive, negotiated session-host
+ command (a follow-up). Never history instead. **A plain shell with no tmux: none.**
++- **A Zellij node (the optional local backend, `settings.sessionBackend`): none.** Its Session is marked
++ `tmuxBacked` like a tmux one, but there is no tmux session to capture, so `visibleCaptureRoute` routes
++ it to none rather than aiming the tmux socket at it. A viewer still co-attaches to a Zellij painter
++ this process holds; with none held it is refused (`join-only`) — a watcher's own client is a
++ read-only TMUX client, and a Zellij attach would be a full, typing one. A visible-only Zellij capture
++ (`zellijCapture … viewport`) exists but has no cursor read; wiring it is a follow-up.
+
+**The target is exact, `=nt-<id>:`.** Node ids end in a counter, so `nt-x-1` is a prefix of `nt-x-12`,
+and tmux resolves a bare target by fnmatch then PREFIX on a miss. Measured on tmux 3.4 with only
+`nt-x-12` alive: `capture-pane -t nt-x-1` printed 12's screen, exit 0 — another node's terminal sent to
+this link's viewers. `=nt-x-1` alone never resolves a pane target at all; `=name:` is exact AND
+resolves, and a miss is a failed command with empty stdout.
+
+**The cursor** (R10) rides the keyframe because tmux's following stream moves the cursor RELATIVE to
+where it believes the tty cursor is, and a capture trims trailing blanks: without it every keyframe
+offsets typed text until a full redraw. **`altScreen`** comes from the join (a tmux-backed client ⇒
+`true`), never from `#{alternate_on}` (R18): a watcher co-attaches to the tmux CLIENT's output, which
+tmux paints on the alternate screen whatever the pane's app does.
+
+**Every keyframe passes a FRESH filter** (R9): `capture-pane -e` emits OSC 8 hyperlinks verbatim
+(measured, tmux 3.4). Fresh, because the session's stream filter is mid-stream state. The viewer page
+also swallows OSC 8 and uses an inert link handler.
+
+**No capture is not an empty screen** (R36). A backend with no visible capture, or a capture that
+failed, answers `unavailable`, and then NO keyframe is sent: the viewer paints a keyframe as reset +
+clear, so an empty one would erase what the stream had drawn. At the join the viewer still gets meta and
+follows the stream; a throttled viewer resumes without a repaint.
+
+Captures are single-flight per session and shared by that link's viewers (R27): a JOIN keyframe may
+share a capture already running, any other keyframe needs one started after it asked, and a per-viewer
+sequence makes sure an older result is never painted after a newer one. A session found gone after a
+join or a capture (`alive()`, R30) takes the lifecycle path, not a keyframe. Split panes: a keyframe
+captures the ACTIVE pane only; the stream repairs the rest as tmux redraws.
+
+## The watcher's own tmux client and sizing
+
+When the owner's process holds a `Session` for the node, the watcher co-attaches to it (a subscriber of
+the same client) and its size never votes. When it does not — after an app restart, for a closed
+project, a released or park-expired node, which is exactly when resumed links reopen — the watcher
+spawns its OWN tmux client (`watcher-client.ts`), and the owner's spelling, `new-session -A`, is wrong
+three ways (measured, tmux 3.4, `watcher-client.realtty.test.ts`):
+
+- **Size.** Under tmux's `window-size latest` the newest client sets the window size: a watcher at
+ 40x10 shrank the owner's 120x39 window to 40x9 — a SIGWINCH to the agent running there, because
+ somebody opened a link. The watcher attaches with **`-f ignore-size,read-only`**.
+- **Environment.** Attaching runs `update-environment`, which STRIPS every listed name the attaching
+ client lacks — the account scope (`CLAUDE_CONFIG_DIR`, …) included. **`-E`** skips it.
+- **Creation.** `new-session -A` re-creates a session that died between the existence verdict and the
+ spawn, bare, on a viewer's behalf. **`attach-session`** never creates.
+
+So: `attach-session -E -f ignore-size,read-only -t =nt-<id>:` (`R19`). Client flags need **tmux ≥ 3.2**:
+locally the version is probed and an older or unreadable one refuses the watcher (only a definite
+answer is memoised); over SSH the remote tmux rejects the flags itself. Either way the join fails
+closed: the viewer sees "waiting", the host backs off. Ubuntu 22.04 (3.2a), Debian 12 (3.3a) and the
+macOS bundled tmux are fine.
+
+**`ignore-size` has a condition tmux does not document** (R20, measured): it is honoured only while at
+least one client WITHOUT the flag is attached to some session on that server. A watcher that is the
+only client sizes the window like any other (spawned at 40x10 alone → window 40x10; an owner joins at
+200x50 and leaves → the window snaps back). Therefore:
+
+- the client is spawned at the window's CURRENT size, read by exact target just before the spawn
+ (`#{window_width} #{window_height} #{status}`, status lines included), and the spawn is **refused**
+ when that read fails — never a guessed size (a join without a size is refused too, never 80×24);
+- `syncWatcherClientSize` resizes the watcher CLIENT's own pty to exactly the window's size (never a
+ vote, never a viewer's size) before every keyframe capture and every `WATCHER_SIZE_SYNC_MS` (10 s)
+ while the link has a joined viewer; serialized per session in PtyManager (one read in flight, one
+ shared rerun — R24), so two links on one node share it;
+- **residual:** when the watcher becomes the sole client, the window lands on the last-synced size
+ until another client sizes it — drift for up to one interval, and a read racing an owner's resize or
+ departure keeps the size read a moment before.
+
+A second viewer shares the watcher client (refcounted by subscribers); the watcher client is unindexed,
+so every persistKey lookup behaves as "no watcher". An owner attaching with `-D` detaches the watcher's
+client once locally: viewers see one `watch:waiting` and a rejoin.
+
+**Rejoin** (R26, R35): a session that ends sends `watch:waiting` once per waiting episode and rejoins on
+`REJOIN_BACKOFF_MS` = 2, 4, 8, 15 s (the last repeats). The backoff resets only once a joined session
+stayed up `REJOIN_STABLE_MS` (30 s) from its join keyframe — never on a join or a lifecycle event: an
+old remote tmux that rejects the client flags, or an owner's repeated `-D`, attaches then exits at once,
+and resetting on success turned that into a spawn + read + capture every 2 s forever.
+
+The meta's size is the joined session's CURRENT size (`PtyManager.sessionSize`, R25), never a viewer's;
+a later change arrives as `pty:size`. The viewer page has fixed cols/rows and no FitAddon.
+
+## Lifecycle
+
+**Create** (`service.create`, in order): `unsupported` shell → parse (`bad-request`) → a build that may
+not relay (`relay-unavailable`) → wait for `init()` (bounded) → the node must be **present**
+(`node-missing` otherwise; `unknown` answers node-missing too, so the dialog flushes the canvas save
+first — R47) → 5 per machine (`limit-machine`, counting links being written and opaque entries) → an
+entitlement (`not-entitled`) → `POST /v1/watch-links` (its refusals pass through: `not-entitled`,
+`limit-active` (15 per license), `limit-daily` (50 per 24 h), `rate-limited`, `license-check`,
+`network` — which covers timeouts, 5xx and a malformed reply, so the copy never says "offline") → the
+record is written (bounded at `PERSIST_TIMEOUT_MS`, 10 s; on failure the server row is revoked and the
+answer is `persist-failed`: no half-created link survives) → the node is checked AGAIN (absent → revoke,
+`node-missing`) → the host starts. Label and title lose C0/C1, DEL and bidi controls and are capped by
+UTF-16 units without splitting a pair.
+
+**The clock.** The expiry timer is derived from the server's `expiresAt` and the response's `Date`
+header (`tokenTtlMs`'s rule), never from the local clock alone; it is re-checked on every host change,
+because a closed lid pauses timers.
+
+**Persist.** `<userData>/watch-links.json` (the Server Edition: its data dir), through
+`writeFileAtomic`, saves serialized in call order (two overlapping atomic writes can land out of order
+and resurrect a revoked link at the next boot).
+
+- What is sealed is the **base64 TEXT** of the secret (R21): the desktop seam is a string seam
+ (`safeStorage.encryptString(b.toString('utf8'))`), so raw random bytes, almost never valid UTF-8, came
+ back as different bytes — every link dropped at relaunch (0/200,000 round-tripped). The Server Edition
+ has no seam and stores the base64 of the raw bytes in a 0600 file, like its node secrets. There is no
+ plaintext fallback on the desktop, and a raw secret found on a desktop is refused.
+- **The store never writes over a file it could not read** (R22): only ENOENT means "no links"; any
+ other read error, a file over 1 MiB or an unknown version latches the store (every save answers
+ `failed`, the file survives for the next boot or a newer build) and the run is memory-only, told on
+ every create. JSON that does not parse is set aside as `.corrupt-<ts>`.
+- **Opaque entries** (R42): a sealed secret the keychain REFUSES to unseal this run (locked at login,
+ reset) is carried back verbatim on every write until its own `expiresAt`, never erased at boot.
+- **A keychain that stops sealing mid-run** (R45): the store keeps a digest-keyed cache of every sealed
+ form it read or wrote and never re-seals, so only a link that was never sealed (the one just created)
+ is left out; the owner is told "This link wasn't saved on `thisMachine()` — it keeps working until
+ you quit." (R59: the copy claims nothing about earlier links, because the renderer cannot tell the
+ causes apart.)
+- `init()` writes only when it actually pruned something, so a boot never rewrites the file.
+
+**Resume** (`init()`, idempotent, never rejects): wait for the boot workspace load (bounded,
+`WORKSPACE_READY_TIMEOUT_MS` 10 s), load, drop expired, revoke and drop ABSENT, KEEP unknown, cap at 5
+(extras revoked: a hand-edited file of 200 entries must not start 200 schedulers), start hosts only when
+`relayAllowed()` (an unpackaged dev build lists them `refused` and hosts nothing: a dev run must not host
+the installed app's links).
+
+**Node gone is tri-state** (R40, `workspaceNodeState`). Present = some project holds it; absent = the
+store has a complete read of every project (`knownNodeIds()`) and the id is not in it; anything else is
+unknown. **Only absent** ends a link (`node-gone`, server revoke). An empty answer during the launch-time
+load, or for a node in a project whose file was not read, is not evidence, and a revoke cannot be
+undone. The check runs on every workspace load/save (`onWorkspaceChanged`, which also covers a node
+removed by the canvas authority on a peer's op) and before every join (R29). **An index rebuilt from
+nothing is never a complete read** (R44, R54, R55): a `workspace.json` that is missing, unreadable,
+corrupt, or parses but is no index this build recognises marks the run, and `knownNodeIds()` answers
+unknown until the next launch — otherwise the renderer's empty boot save made every node absent and
+every link was revoked a second after launch (probe-confirmed). A genuinely empty v2/v3 index is not
+flagged.
+
+**End** (expiry, owner Stop, node gone, server 410): drop the record, ISSUE the write (never awaited
+before the server revoke — a hung disk must not keep a revoked link's viewers connected or its row
+alive), `watch:end` to every viewer, stop the scheduler, emit state, notify (expiry, 410, node-gone only;
+the owner's own Stop raises nothing), then the best-effort server revoke. Local revoke is complete even
+offline, because the host is the only listener. **Stop all** is `POST /v1/watch-links/revoke-all`:
+every link of the LICENSE, other machines included, so both entry points (palette, Settings) confirm
+first; it also discards opaque entries (else they would host again once the keychain unlocks).
+
+**The listener pool.** One hosted scheduler per link with `maxBridged: 10`: at 10 bridged viewers no
+replacement listener opens, so the broker closes an 11th client ("no host waiting"). The scheduler's
+existing rules apply unchanged: refresh 30 s before expiry (120 s host tokens refresh at 90 s, before
+the broker's exp + 30 s close of an unbridged listener), backoff reset only on proof the relay works,
+429 waits ≥ 60 s, 402/403 stop minting, 200 mints/hour. A bridged peer that has not confirmed within
+`CONFIRM_DEADLINE_MS` (30 s) is closed so it cannot hold a slot.
+
+**Server 410.** The relay checks a token only at join and cannot cut a bridge; the host does. A
+server-side revoke reaches the host through its next mint (≤ ~90 s) — or, while the link is FULL (no
+idle listener, so no mint), through a status poll every 5 min (`FULL_STATUS_POLL_MS`). A 410 from either
+ends the link locally with the reason it names and tells the owner.
+
+**Entitlement re-arm** (R41). A host never mints with an empty entitlement (the API would answer 400,
+which stops minting for good): it answers itself a local 402. A 402 also means the 7-day entitlement
+token expired under a running link — the ordinary case — so `onEntitlementChanged()` (wired from
+`initLicense`'s change callback) restarts every host whose status is `refused`; bridged viewers are
+untouched. A Pro lapse lets open links run out their term (≤ 24 h): host tokens check the token and the
+link row, not keygen.
+
+**Hung-disk and quit rules.** Create waits for its write ≤ 10 s; revoke / revoke-all wait for `init()`
+only boundedly, so Stop all still reaches the server on a hung disk; `init()`'s own workspace bound fires
+before any wait on it, so a slow workspace never reads as a failed write. Desktop: `shutdown()` runs on
+the FIRST before-quit pass, before `ptyManager.killAll()`, inside the 1.5 s raced flush — viewers get
+`host-stopping` while the sockets are up; the records stay on disk and resume at the next launch. Server
+Edition: `shutdownWithin(watchLinks, 2 s)` after `hosted.stop()` in both close paths.
+
+**Owner state.** `watchLink:state` (the FULL list, coalesced per tick), `watchLink:chat` and
+`watchLink:notice` go to owner clients only (`sendToOwners`): every view carries the URL, and the URL
+carries the secret. Chat history (200 per link) is memory-only, cleared on revoke or restart. Everything
+a viewer wrote reaches the owner bidi-stripped and is rendered as text. **Link state is never canvas
+content:** no field on `CanvasNodeState`, `ProjectKanban` or any `CanvasMutation` — canvas sync would
+carry it to teammates and the canvas authority would write it into the git-shared `project.json`.
+
+## Surfaces
+
+- **Desktop:** full. Entry points: node right-click "Share live link…" (`selectionItems`, shared by the
+ sessions-sidebar row; hideable as `live-link`), the kanban card menu (per-project board AND the Omni
+ board's lanes, non-active projects included — `joinOnly` attaches in core, so the node need not be on
+ screen), the card modal header action, the palette ("Manage live links", "Stop all live links (every
+ machine on this license)"), Settings → Live links (Remote & team). ProCompare lists "Live read-only
+ links to a terminal — viewers need nothing installed"; the Core list is untouched. **Availability is
+ checked before the Pro gate** (`liveLinkUnavailable` then `requireProOr`), so a Server Edition or relay
+ tab never sees an Upgrade dialog; an unavailable row is disabled with its reason, never hidden.
+- **The LIVE chip** (`LiveLinkChip`, one component): node header (beside `PresenceChips`), kanban card,
+ card modal header, sessions-sidebar row. `● LIVE`, `● LIVE · 2`, amber `LIVE · offline`
+ (reconnecting), muted `LIVE · refused`; an unread dot for Commenter chat. **Not hideable** — it is the
+ owner's signal that a terminal is being broadcast. It shows only for a node viewed through a LOCAL
+ session (R57): a relay tab's copy of a git-shared node with the same id must not show this machine's
+ chip, and the boards and the sidebar sit outside the node's SessionProvider, so they resolve the
+ session from the project id. The popover (per link): role, countdown, Copy, Stop, viewers with Kick,
+ Commenter chat with reply and "Copy to card comments" (an explicit act, as the owner; mention tokens
+ defused). A join raises an info strip, "Someone started watching <title> (2 watching)." — how an owner
+ notices a leaked link.
+- **Server Edition:** the same core service is registered, with `entitlement: () => null` and
+ `unsupported: true` (R43), because that edition has no license layer yet (`initLicense` is
+ desktop-only). Create answers `unsupported` and the renderer shows "Live links need a Pro license on
+ this server — not available in the Server Edition yet", no Upgrade button; list answers `[]`; nothing
+ is loaded or hosted. The ws-bridge has a REAL `watchLink` member (`buildWatchLinkApi`, spread only into
+ the Server Edition's own api, never a relay-shared builder): its browser clients are the host's own
+ user, not relay peers, so the host-only prefix does not refuse them. A server license layer is the
+ follow-up. A Server Edition that does not own its data dir skips `init()` and logs it.
+- **Relay tab:** the API is an inert stub (`stubs.ts`); the row is disabled with "Live links are created
+ on the machine that runs this terminal."; the chip is not shown. On the peer, every `watchLink:`
+ channel is host-only, refused `E_FORBIDDEN` to every relay peer — Team Access guests and hosted owners
+ and editors included (an editor passes every access check, and a link spends the host's Pro and
+ publishes a host terminal to the world). `scoped-guest-policy.test.ts` proves the refusal on the real
+ relay host with and without hooks.
+- **Kanban:** first-class, as above (card chip, card menu row, card modal chip + action — the action is
+ disabled with its reason as its title, because the canvas notice strip sits under the modal scrim).
+- **Mobile:** N/A in v1. Links open in Safari. **Follow-up for nodeterm-ios (@eneskirca):**
+ create/list/revoke from the phone (needs `watchLink.*` verbs on the phone dialect of the desktop's host
+ service), and optionally an in-app viewer for `nodeterm.dev/s/` universal links.
+- **No canvas-control verb** creates, lists or revokes a link: an agent must never be able to publish a
+ terminal (`live-link.guard.test.ts` reads both verb tables).
+
+## Threat notes and residuals
+
+From the spec, verbatim:
+
+- **Residual — no forward secrecy**, as for the relay today: a recorded session plus a later-leaked
+ `S` is plaintext. `S` is deleted from the registry on revoke/expiry; lifetime ≤ 24 h.
+- **Residual — all viewers of a link share one viewer key**, so they are cryptographically
+ indistinguishable; identity is the session. Kick is per session; only Stop ends access.
+- **Residual — the fragment lives in browser history** and can be synced by the browser to the
+ viewer's other devices. Answered by the short default expiry and Stop.
+- **Residual — the owner-supplied label and node title are shown to viewers.** They are rendered as
+ text inside fixed nodeterm chrome, marked as sharer-set; terminal output cannot draw over the
+ chrome and has no clickable links.
+
+Found while building it:
+
+- **Filter CPU scales with viewers** during a flood (R13): the filter is per viewer, ~2.7 % of a core
+ per viewer at a 2.7 MB/s flood (measured), ≤ 10 viewers per link.
+- **Text typed with no escape after a co-attach join lags** until the next escape or the 2 s keyframe
+ (R23): the mid-stream filter swallows it by design.
- - **On a backend with no visible capture** (Windows session host, direct Windows pty, plain shell) a
- throttled viewer shows gaps until the app repaints (R36).
++- **On a backend with no visible capture** (Windows session host, direct Windows pty, plain shell,
++ Zellij) a throttled viewer shows gaps until the app repaints (R36). A Zellij node with no painter held
++ in this process (a closed project, after a restart) cannot be watched at all until one is.
+- **A single capture failure on a tmux/SSH backend is treated as "no capture"**: no repaint until the
+ next keyframe or the app's redraw. Retrying there would stall the stream for good on the backends that
+ genuinely have no capture, and the flag cannot tell the two apart.
+- **Frames between a capture and its delivery are dropped for that viewer** (inherent to
+ capture-then-stream; the next redraw repairs). A keyframe shows the active pane only.
+- **Window-size drift** for up to one sync interval when the watcher becomes the sole client (above).
+- **A tmux < 3.2 host cannot be watched** (fail closed, "waiting").
+- **After a run whose index was missing, unreadable or corrupt, node-gone waits for the next launch**
+ (R44/R54): a link to a node deleted in that run lives until its expiry (≤ 24 h) with nobody able to
+ join it (its session is destroyed), and the agent-status mirror's existence pruning is off that run.
+ Likewise a link to a truly deleted node in an unread project lingers until the next complete read.
+- **Opaque entries** (an unsealable secret) live in the file ≤ 24 h.
+- **A node cold-opened into a background project** whose disk write has not landed answers
+ `node-missing` (no flush for a non-active project, R47).
+- **A create racing Stop all** finishes after the stop and its link lives (it was not a link when Stop
+ all ran); the server's revoke-all may have raced the row, and then the host's next mint gets 410.
+- **Relay bridge lifetime is unverified**: whether production ends a bridged socket at its token's
+ lifetime is the same open question as hosted checklist item 8 (device item 15 below).
+- **Idle viewers depend on the host's keepalive**: the page drops a leg after 75 s of silence, relying on
+ the sealed 25 s keepalive `relay-socket` starts at handshake-ready. Viewer sessions run on
+ `connectRelayHost` for exactly that reason.
+- Pre-existing, not introduced here: `mintHostToken` (`src/core/relay/host-token.ts`) reads a reset
+ mid-body as a bad response and parses Retry-After loosely (the watch-link API client does not);
+ `UpgradeDialog` is not on the dialog stack, so opened over a card modal its Escape closes the modal
+ underneath; Canvas's existing `session.source === 'relay'` checks in `selectionItems` read the app's
+ local session for every tab.
+
+## Device checklist (owed — this server cannot run Electron)
+
+From the spec:
+
+1. Create a link on a Mac; open it in Safari on a phone.
+2. Typing in the viewer does nothing.
+3. Narrowing the viewer's window does not resize the owner's terminal.
+4. The owner scrolling back (tmux copy-mode) is visible to the viewer.
+5. Stop sharing cuts viewers immediately.
+6. Expiry ends the link with the expired message.
+7. Quit and relaunch: the link resumes and the viewer page reconnects by itself.
+8. Lid closed and reopened: the link recovers.
+9. A non-Pro account gets the upgrade dialog; the server refuses a forged request.
+10. The 11th concurrent viewer sees the "offline or at its limit" message.
+11. `yes` in the shared terminal with a throttled viewer: the owner's terminal stays smooth.
+12. Text copied in tmux does not appear in the viewer's decoded stream (debug flag).
+13. A Server Edition browser tab offers the action and gets the honest `unsupported` answer (no dead
+ Upgrade button).
+14. The chip appears on all four surfaces; Kick and chat work both ways.
+15. **A viewer stays connected for more than 2 minutes without a drop** — whether production ends a
+ bridged socket at its token's lifetime is unverified (the same open question as hosted checklist
+ item 8).
+
+Added while building it:
+
+16. An idle terminal for more than 3 minutes, with the viewer page visible AND hidden: 0 rejoins. Again
+ with nodeterm hidden on macOS (App Nap).
+17. A link on a node whose project is closed (or after a relaunch, no owner Session held): the watcher's
+ own client attaches, the owner's window size does not change when the owner then opens the node,
+ and the account environment of the session is intact.
+18. The owner attaches the same session with `-D` elsewhere: viewers see one "waiting" and come back.
+19. A link on an SSH-project node: keyframe and stream over the ControlMaster; a downed master shows
+ "waiting", never a local shell.
+20. Relaunch with the login keychain locked: links come back once it unlocks (opaque entries), none are
+ erased.
+21. A relay tab showing a git-shared node with the same id as a locally linked node shows no chip.
+
+Visual checks (renderer, Mac and a Server Edition browser tab):
+
+22. Node right-click: "Share live link…" right after Refresh terminal, the broadcast glyph at 16 px; a
+ DISABLED row's tooltip (relay tab, 5 links).
+23. Sessions sidebar row menu — active project and a non-active project (Duplicate · Share live link… ·
+ End session).
+24. Kanban card menu (per-project, after the account rows) and the Omni board lane card menu.
+25. Card modal header: the broadcast action between ✦ and the comments button; disabled look + tooltip
+ (Chromium shows `title` on disabled buttons — confirm on the packaged build).
+26. The create dialog: 460 px `.confirm` shell, radios wrapping, the warning wash, the URL row with
+ Copy/Copied!, "until HH:MM" in 12/24 h locales; long node titles; dark + light; Liquid Glass.
+27. The dialog opened from the card modal (z 70 over 55), and the UpgradeDialog opened from the card
+ modal / board.
+28. Palette: "Manage live links" and "Stop all live links (every machine on this license)" with the
+ glyph; the Stop-all confirm after the palette closes.
+29. Settings → Live links: nav glyph, rows with long titles, Copy/Stop, the Stop-all confirm over the
+ Settings overlay, the pitch; the Server Edition sentence in a browser tab.
+30. The sticky `not-persistent` strip after a create, visible after closing a card modal.
+31. The chip popover over a zoomed canvas node, near the bottom edge (flips above), over the card modal,
+ and in the hover-peek sidebar (it must stay open); under Liquid Glass (opaque, `.live-pop`).
diff --cc docs/session-backends.md
index 000000000,a770ff6c6..e02f61e47
mode 000000,100644..100644
--- a/docs/session-backends.md
+++ b/docs/session-backends.md
@@@ -1,0 -1,140 +1,141 @@@
+ # Session backends: Zellij and herdr beside tmux
+
+ nodeterm keeps a local terminal alive across app restarts by running it inside a multiplexer
+ session named `nt-<node id>`: tmux on macOS/Linux, the session host on Windows. Some people live
+ in **Zellij** or **herdr** and want their canvas terminals to *be* sessions of that tool, so they
+ can attach to them from anywhere else. This document is the measurement behind v1: what
+ `PtyManager` needs from its backend, what each tool offers, which one v1 implements and why, and
+ what that backend does not do.
+
+ ## How it was measured
+
+ - **Zellij 0.45.1** (`zellij-x86_64-unknown-linux-musl`, the latest GitHub release on 2026-09-30).
+ - **herdr 0.9.3** (`herdr-linux-x86_64`, latest release on 2026-09-30; source at 0.9.1 read for
+ paste framing and config paths).
+ - Both run from `/var/tmp` with a throwaway `HOME`, `XDG_CONFIG_HOME`, `XDG_DATA_HOME`,
+ `XDG_CACHE_HOME`, `XDG_RUNTIME_DIR`, plus `ZELLIJ_SOCKET_DIR` (Zellij) / `HERDR_HOME` (herdr). The
+ user's tmux servers were never touched; every server started was killed afterwards.
+ - A painter was a real client in a real pty (a 60-line Python `pty.fork` harness that writes
+ scripted input, resizes, and sends SIGHUP). Linux, x86_64. **Nothing was measured on macOS.**
+
+ ## What PtyManager needs, and what each tool answers
+
+ | Need (tmux today) | Zellij 0.45.1 | herdr 0.9.3 |
+ |---|---|---|
+ | **Create-or-attach by stable name** (`new-session -A -s nt-<id>`) | `zellij --config <kdl> --layout-string 'layout { pane; }' attach --create --close-on-exit nt-<id> -- <shell> [args]`. Atomic. The initial command is ignored on a reattach. `options --default-layout <file>` and a `default_layout` line both still produced the tab bar and status bar; `--layout-string` did not, and a reattach with it adds no tab. `options --default-shell` was ignored on a created session, hence the explicit initial command. | A *session* is a whole server holding workspaces/tabs/panes (`herdr --session <name> server`). A node would be a pane made with `workspace create --cwd … --env K=V` — and the only way to attach a pty to ONE pane is `agent attach <pane>`, which answered `agent_not_found` for a plain shell pane. A full `herdr --session X` attach draws herdr's own workspace UI. |
+ | **Detach, leave running** (client exit) | SIGHUP to the client: "Bye from Zellij!", session stays. | Server-side; clients detach. |
+ | **Strict exists** (`has-session -t =name`) | `list-sessions -n` lines `name [Created …]` (`(EXITED - attach to resurrect)` for serialized ones). No sessions = exit **1** plus "No active zellij sessions found" — exit status alone cannot tell absence from failure. Exact names only. | `session list --json` (`running: true/false`). |
+ | **Shell exit ends the session** | With a client attached: yes (client prints "Bye", session gone). **With no client attached: the session stays listed with no terminal pane** ("zombie"); an `attach --create` to it connects and exits at once. Right after creation a session also has no terminal pane *for a moment*. | Pane closes inside a still-running server. |
+ | **Capture screen + history** (`capture-pane -p [-e] -S`) | `action dump-screen --pane-id <p> --full [--ansi]` (viewport, or viewport + scrollback; `--ansi` keeps SGR). ~16 ms per call. | `pane read <pane> --source visible\|recent [--ansi] [--lines N]`. |
+ | **Send text as ONE paste honouring the app's paste mode, then Enter** (`paste-buffer -p`) | `action paste --pane-id <p> <text>`: **plain** when the app never asked, **framed** `ESC[200~…ESC[201~` after `printf '\e[?2004h'` (both measured against `cat -v`); `\n` stays `\n`. Enter = `action write --pane-id <p> 13`. Text rides ONE argv element: 131,000 bytes delivered, 140,000 failed (exit 126, Linux `MAX_ARG_STRLEN`). No stdin form. | `pane send-text` is **never framed** — measured: text arrived raw after `?2004h`. The mode-aware paste (`paste_payload` in `src/pane.rs`) is only behind `agent prompt`, which requires herdr's own agent detection. |
+ | **Targeting with no client** | An action without `--pane-id` silently did nothing headless (no focused pane without a client). `action list-panes --all --json` gives ids; the target is the focused live terminal pane, else the lowest id. | Pane ids (`w1:p1`) from `pane list`. |
+ | **Kill** (`kill-session -t =name`) | `kill-session <name>`, exact match (`nt-e` did not touch `nt-e1`). With `session_serialization false` the session is gone, not resurrectable. | `session stop` / `pane close`. |
+ | **List sessions + attached-client counts** (reaper, session memory) | Names: `list-sessions -n`. Clients: `--session <s> action list-clients` (one row per client). Not wired in v1 (see gaps). | `session list`; client counts not measured. |
+ | **Per-session environment at creation, no secrets on argv** (`-e` + `update-environment`) | Each session is its **own server process**, forked by the client that created it, so the session env IS the creating client's env. Measured: a variable exported only to the creating client was visible in the pane; nothing on argv. `ZELLIJ_SESSION_NAME` is set in the pane. | Per-pane `--env KEY=VALUE` is **argv** (visible in `/proc/<pid>/cmdline` while the CLI runs). A server started with a variable does pass it to its panes, but then one server per node. |
+ | **Pane foreground command** (`#{pane_current_command}`, restart/Eco gates) | No headless CLI: `list-clients` shows a running command only with a client attached (`N/A` for a shell); `list-panes` gives the launch command. The process table does: `zellij --server <socketdir>/contract_version_1/<name>` → its child shell → the shell's `tpgid` → that process. Measured `server → bash (tpgid = sleep) → sleep`. | `pane process-info --pane <id>` returns `foreground_processes` with argv and cwd — the best answer of the three. |
+ | **Resize / size ownership** | Pty resize → client SIGWINCH. Two clients: the session takes the **smallest** (100×30 + 80×20 → 80×20). | Not measured. |
+ | **Mouse / scroll / copy** | Client enters the alternate screen (`?1049h`) and enables `?1000h ?1002h ?1003h ?1006h`; wheel scrolls Zellij's own scrollback; a mouse drag emitted **OSC 52** (`ESC]52;c;<base64>`) to the client — the same model as tmux in nodeterm. | Own UI; not measured. |
+ | **Key passthrough** | Keybindings are **session-wide** (a session created with cleared keybinds ignored a second client's own config). In `default_mode "locked"` Ctrl-g, Ctrl-p, Ctrl-t, Ctrl-o all reached `cat -v`; with the unlock moved to Ctrl-Alt-g, Ctrl-Alt-g then Ctrl-o d detached. | Not measured. |
+
+ ## Decision: Zellij for v1
+
+ Zellij maps onto the tmux contract nearly one to one: an atomic create-or-attach by name, a real
+ client as the painter (alternate screen, mouse, OSC 52 — the renderer needs nothing new), a paste
+ that applies the application's own bracketed-paste mode, and environment delivery with nothing on
+ argv. herdr is a workspace manager whose unit is a server of many panes: a node would have to be
+ one pane, which cannot be attached to on its own (`agent attach` refuses a non-agent pane), per-pane
+ environment is argv, and its text send does not honour paste mode.
+
+ **herdr gaps, for whoever picks it up:** single-pane attach for a non-agent pane; mode-aware paste
+ from the CLI (`pane send-text` framing like `paste_payload`); a per-pane environment that is not
+ argv (stdin or a file). herdr's `pane process-info` is better than anything Zellij offers for the
+ foreground-process question and would be the model for that leg.
+
+ ## v1 design (what shipped)
+
+ - **Setting:** `settings.sessionBackend` = `tmux` (default) | `zellij`, Settings → Session
+ protection → *Session backend*. Read through `normalizeSessionBackend`: anything else is tmux.
+ The row is shown only by a core that reports Zellij discovery (POSIX), and says when Zellij is
+ selected but not installed (new terminals then use tmux).
+ - **The backend follows the session that exists.** A warm tmux session is reattached in tmux; a
+ live Zellij session is reattached in Zellij, whatever the setting says now; only a node with no
+ session anywhere is created in the selected backend. Switching the setting therefore never
+ strands a running agent in one multiplexer while cold restore relaunches it in the other.
+ - **Local projects only.** SSH projects keep the remote tmux; Windows keeps the session host.
+ - **Our config** (`<userData>/zellij.kdl`, rewritten when it changes): locked mode with the lock
+ toggle on Ctrl-Alt-g, no pane frames, no startup tips, `session_serialization false`, mouse on;
+ plus the bare one-pane layout. When nodeterm starts the default shell, it passes `-l` for
+ bash/zsh/fish, as tmux runs its default shell as a login shell.
+ - **Zombies:** a session listed with no terminal pane is only believed after five pane-less reads
+ 300 ms apart (a just-created session looks the same for a moment); a confirmed zombie is killed
+ before the node is created again.
+ - **Unknown is warm, whatever the setting.** When Zellij cannot be asked about a node, the create
+ is never cold — even with tmux selected — because a node that may still run in Zellij must not
+ get its snapshot replayed and its agent `--resume`d a second time in a new tmux shell (found in
+ review: a first version folded to warm only when Zellij was selected). `sessionExists`, by
+ contrast, claims a Zellij session only from a listing that parsed and shows it live.
+ - **Session names may contain spaces** (measured: `my work [Created 0s ago]`); the listing parser
+ takes everything before the last ` [Created `. The first version rejected such a line, and one
+ personal session made every probe `unknown`.
+ - **`--` before every positional text** (`paste`, `write-chars`): measured, `- item one` was
+ refused as an unknown argument and `-h` printed help with exit 0 while delivering nothing.
+ - **Only when Zellij is in play.** Probes of nodes we know nothing about (the per-create
+ `list-sessions`, the per-delete `kill-session`, the relay listing) run only when Zellij is
+ selected or has been used on this machine (our `zellij.kdl` exists; it is written only when a
+ Zellij terminal is created). A tmux user who merely has Zellij installed runs exactly the old
+ path.
+ - **Socket path length.** Zellij refuses a socket path over the platform limit ("IPC socket path is
+ too long (108 bytes, max 107)", measured in review on Linux; macOS allows 103). With the setting on and a
+ path that would not fit, new terminals fall back to tmux and the Settings row says why. A stock
+ Mac (no `XDG_RUNTIME_DIR`, 49-character `$TMPDIR`) with a real node id computes to ~104 bytes —
+ over the limit — so on such a Mac the row is expected to say so until `XDG_RUNTIME_DIR` or
+ `ZELLIJ_SOCKET_DIR` is set short. Calculated, not run.
+ - **Delete** kills `nt-<id>` in Zellij (exact name) whenever Zellij is in play, so a node deleted
+ after a restart, never mounted since, does not leave its session running.
+ - **Paste:** refused (not split) above 120,000 UTF-8 bytes.
+ - **Session memory:** the sweep reads tmux; the panel reports how many Zellij sessions it did not
+ measure instead of "No sessions are running here.".
+
+ ### Not available with Zellij (named in the Settings row)
+
+ - Agent-to-agent messaging and triggers into Zellij sessions are refused (no pane-owner or paste-mode probe).
+ - Model switch refuses: it cannot stop the foreground process of a Zellij pane.
+ - The session-memory panel counts Zellij sessions but does not measure them; the idle-session reaper does not see them.
+ - Pasted text reaches Zellij as a command-line argument (readable by other local users while the call runs); pastes over 120 KB are refused.
+ - The stale-folder banner and the live pane folder for file links are unavailable.
++- A live link to a Zellij node gets no screen snapshot (viewers start from the live stream), and can be watched only while its terminal is attached in this app.
+ - SSH projects and Windows keep tmux / the session host.
+ - nodeterm mobile’s direct SSH attach only finds tmux sessions.
+
+ Also true and not in that list: control-mode shadow clients do not exist for Zellij (a released
+ Zellij node is re-attached by a painter, not a zero-pty control client); the late cold-start check
+ is SSH-only anyway; `paneCursor` is unknown, so a resync paint leaves the cursor where it lands.
+
+ ## Surfaces
+
+ - **Desktop:** measured and tested on Linux only. macOS is untested: see the checklist, whose
+ first item decides whether Zellij can be used there at all without a short socket dir.
+ - **Server Edition:** the same core. The Settings row appears whenever the server host reports
+ Zellij discovery; sessions are created on the server host.
+ - **Mobile:** over the relay, the phone's `pty.attach` goes through the same core and joins the
+ Zellij session (`listNodetermSessions` includes Zellij sessions and remembers them for the attach).
+ The phone's **direct SSH** path runs `tmux` on the host and cannot see Zellij sessions — an iOS
+ follow-up.
+
+ ## Device checklist (not run here)
+
+ 1. **macOS socket path**: on a stock Mac, does the Settings row report the socket path as too long
+ (expected, see above), and with `ZELLIJ_SOCKET_DIR` set short, do Zellij nodes open? Also run
+ the `*.realzellij.test.ts` suites on a Mac (their sandbox falls back to a short `/tmp` socket
+ dir when the sandbox path would not fit).
+ 2. macOS: `ps -A -o pid=,ppid=,tpgid=,comm=,args=` shape and `tpgid` for the pane shell
+ (Restart agent / Eco read the pane command from it).
+ 3. macOS: Zellij from Homebrew is found from a Finder-launched app (`/opt/homebrew/bin`).
+ 4. A canvas node in Zellij: typing, resize, wheel scroll, drag-copy (OSC 52 pill), Shift+Enter in
+ an agent CLI, Ctrl-g reaching Claude Code.
+ 5. Attach from an outside terminal with `zellij attach nt-<id>`; both clients see the same pane;
+ the smaller one sizes it.
+ 6. App restart with a Zellij node: warm reattach, no cold restore, agent still running.
+ 7. Machine reboot: cold restore replays the scrollback snapshot and resumes the agent in a new
+ Zellij session.
+ 8. Server Edition on a Linux host with Zellij installed: create, reattach from a second tab.
diff --cc src/core/pty-manager.ts
index 5501d0eb2,7138ac7f5..2383b7b06
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@@ -766,14 -768,11 +797,18 @@@ interface Session
* `captureForResync`, the final kill in `destroySession`) branches on this the same way it
* already branches on `sshRemote`.
*/
+ /** Held by a Zellij session (zellij-backend.ts) rather than tmux. `tmuxBacked` is ALSO true for it —
+ * that field answers "does releasing this client destroy anything", and for Zellij it does not —
+ * so every path that would talk to the tmux socket asks this first. */
+ zellij?: boolean
sessionHost?: boolean
+ /**
+ * A live link watcher's OWN tmux client (`attach-session -E -f ignore-size,read-only`, spawned by
+ * `joinAsWatcher` when no Session was held). Never indexed, and invisible to the persistKey lookups
+ * (`sessionByPersistKey`, `liveSessionForNode`): it is read-only, so an owner joining it, or a
+ * background write going through it, would lose every keystroke. Only watchers ever reach it.
+ */
+ watcherClient?: boolean
}
/** Sinks for a detached session whose output is served somewhere other than the renderer
@@@ -2448,24 -2474,30 +2521,52 @@@ export class PtyManager
// IS its probe, see above), so it is refused there too rather than sent a round trip that could
// create. Fails closed: a viewer never starts anything. One refusal value for both reasons —
// the renderer's sentence claims only that no running terminal was found.
- if (options.joinOnly && (fresh || freshUnverified || joinOnlyLocalVerdict === 'unknown'))
+ // The optional Zellij backend — see `decideZellij` for the rule ("the backend follows the
+ // session that exists"). Asked only for a LOCAL persistent node whose tmux session is not there:
+ // a warm tmux session is reattached exactly as before, and SSH projects keep the remote tmux.
+ const zellijChoice =
+ !options.sshRemote &&
+ options.persistKey &&
+ !warmWindowsBackend &&
+ this.runtimePlatform !== 'win32' &&
+ this.getSettings().tmuxEnabled &&
+ !(tmuxBacked && !fresh)
+ ? await this.decideZellij(options.persistKey)
+ : undefined
+ if (zellijChoice?.use) fresh = zellijChoice.fresh
+ // Zellij could not be asked about this node: it may be live there, so never COLD in tmux.
+ else if (zellijChoice?.state === 'unknown') fresh = false
+ // A join-only create on Zellij needs a session we SAW live; anything else could create one.
+ const joinRefused = zellijChoice?.use
+ ? zellijChoice.state !== 'live'
+ : fresh ||
+ freshUnverified ||
+ joinOnlyLocalVerdict === 'unknown' ||
+ zellijChoice?.state === 'unknown'
+ if (options.joinOnly && joinRefused)
+ return { sessionId: '', fresh: false, unavailable: 'join-only' }
++ // A watcher's own client is a read-only TMUX client (`attach-session -E -f ignore-size,read-only`),
++ // and a Zellij session has no such client to spawn: refused, never a Zellij attach (which would be
++ // a full, typing client). A watcher still co-attaches to a Zellij session this process holds (the
++ // `join` above); it just gets no keyframe (`visibleCaptureRoute`).
++ if (isWatcherCreate(options) && zellijChoice?.use)
+ return { sessionId: '', fresh: false, unavailable: 'join-only' }
+ // A watcher's own LOCAL client needs client flags (tmux >= 3.2). Without them it would either fail
+ // to attach or — worse, spelled without the flags — resize the owner's window. Refused the same
+ // way as a session that cannot be confirmed. Over SSH the host's version is unknown here: the
+ // flags are passed and an old remote tmux rejects them (see `remoteTmuxWatcherArgs`).
+ if (isWatcherCreate(options) && !options.sshRemote && !(await this.localTmuxSupportsWatcherClient()))
+ return { sessionId: '', fresh: false, unavailable: 'join-only' }
+ // A watcher's own client is spawned at the window's CURRENT size, read here, just before the spawn
+ // — never at a guessed one (the caller's, a remembered size, a default). `ignore-size` only holds
+ // while an unflagged client is attached somewhere on the server; if the watcher is ever the only
+ // one, tmux sizes the window to it, so a wrong spawn size is a wrong window size. Unknown ⇒ refused
+ // ("not now": the link host backs off and asks again).
+ if (isWatcherCreate(options)) {
+ const windowSize = await this.readWindowSize(options.persistKey as string, options.sshRemote)
+ if (!windowSize) return { sessionId: '', fresh: false, unavailable: 'join-only' }
+ options = { ...options, cols: windowSize.cols, rows: windowSize.rows }
+ }
// Ensure the login-shell PATH is resolved (prewarmed in init(); usually already settled)
// so the session env below picks it up — awaiting keeps the event loop free either way.
await resolveShellPath()
@@@ -3758,7 -4013,7 +4108,8 @@@
pausedBy: new Set<string>(),
accountFallback,
sessionHost: useSessionHost,
- ...(isWatcherCreate(options) ? { watcherClient: true } : {})
++ ...(isWatcherCreate(options) ? { watcherClient: true } : {}),
+ ...(useLocalZellij ? { zellij: true } : {})
}
// Both shared timers are armed by the first session that needs them: the scrollback snapshots
// and the idle reap are both about tmux-backed sessions and nothing else.
diff --cc src/core/pty-zellij-fold.test.ts
index 000000000,7fbe61016..4d45617e0
mode 000000,100644..100644
--- a/src/core/pty-zellij-fold.test.ts
+++ b/src/core/pty-zellij-fold.test.ts
@@@ -1,0 -1,131 +1,155 @@@
+ // PtyManager's Zellij DECISIONS with a stub `zellij` (a shell script), so they run everywhere —
+ // no real binary needed. Review of #1067: a probe that answers "unknown" must never let a node be
+ // cold-started in tmux (snapshot replayed + agent resumed a SECOND time while it may still run in
+ // Zellij); `sessionExists` must not claim every node exists; a tmux user with Zellij merely
+ // installed must pay nothing; a socket path Zellij would refuse must fall back to tmux.
+ import fs from 'fs'
+ import path from 'path'
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+ import { initPlatform, resetPlatformForTests } from './platform'
+ import { fakePlatform } from './platform-fake'
+ import { DEFAULT_SETTINGS, type Settings } from '../shared/types'
+ import { testTmpDir } from './test-tmp'
+
+ const h = vi.hoisted(() => ({ spawns: [] as Array<{ file: string; args: string[] }> }))
+
+ vi.mock('./session-host-backend', async () =>
+ (await import('./__fixtures__/no-session-host')).noSessionHost()
+ )
+ vi.mock('./pty-devices', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./pty-devices')>()),
+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })
+ }))
+ vi.mock('node-pty', () => ({
+ spawn: (file: string, args: string[]) => {
+ h.spawns.push({ file, args })
+ return {
+ onData: () => ({ dispose() {} }),
+ onExit: () => ({ dispose() {} }),
+ write: () => {},
+ resize: () => {},
+ pause: () => {},
+ resume: () => {},
+ kill: () => {},
+ pid: 4321
+ }
+ }
+ }))
+
+ let dir: string
+ let userData: string
+ let log: string
+ let savedSockDir: string | undefined
+
+ /** A stub zellij: logs its argv, then `list-sessions` answers per `mode`. */
+ function stub(mode: 'broken' | 'none'): string {
+ const file = path.join(dir, `zellij-${mode}`)
+ const body =
+ mode === 'broken'
+ ? 'echo "zellij: could not connect" >&2; exit 2'
+ : 'case "$1" in list-sessions) echo "No active zellij sessions found."; exit 1;; esac; exit 0'
+ fs.writeFileSync(file, `#!/bin/sh\necho "$@" >> '${log}'\n${body}\n`, { mode: 0o755 })
+ return file
+ }
+ const calls = (): string => (fs.existsSync(log) ? fs.readFileSync(log, 'utf8') : '')
+
+ async function manager(bin: string, settings: Partial<Settings>, tmuxAbsent = true) {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager({ zellijBin: bin })
+ ;(m as unknown as { getSettings: () => Settings }).getSettings = () => ({
+ ...DEFAULT_SETTINGS,
+ ...settings
+ })
+ ;(m as unknown as { tmuxPath: string }).tmuxPath = '/usr/bin/tmux'
+ vi.spyOn(m as unknown as { tmuxSessionExists: () => Promise<boolean> }, 'tmuxSessionExists').mockResolvedValue(
+ !tmuxAbsent
+ )
+ vi.spyOn(m as unknown as { paneCwdStale: () => Promise<boolean> }, 'paneCwdStale').mockResolvedValue(false)
+ return m
+ }
+ const inPlay = (): void => fs.writeFileSync(path.join(userData, 'zellij.kdl'), '// used before\n')
+
+ beforeEach(() => {
+ h.spawns.length = 0
+ dir = testTmpDir('zfold-')
+ userData = path.join(dir, 'ud')
+ fs.mkdirSync(userData)
+ log = path.join(dir, 'calls.log')
+ savedSockDir = process.env.ZELLIJ_SOCKET_DIR
+ process.env.ZELLIJ_SOCKET_DIR = path.join(dir, 's')
+ initPlatform(fakePlatform({ userDataDir: userData }))
+ })
+ afterEach(() => {
+ if (savedSockDir === undefined) delete process.env.ZELLIJ_SOCKET_DIR
+ else process.env.ZELLIJ_SOCKET_DIR = savedSockDir
+ resetPlatformForTests()
+ })
+
+ describe('an unknown Zellij answer is WARM whatever the setting (the #1067 blocker)', () => {
+ it('tmux selected, Zellij in play but unreadable: the tmux create is NOT cold', async () => {
+ inPlay()
+ const m = await manager(stub('broken'), { sessionBackend: 'tmux' })
+ const r = await m.createHeadless({ cols: 80, rows: 24, persistKey: 'n1' })
+ expect(r.fresh).toBe(false)
+ expect(h.spawns.at(-1)?.file).toBe('/usr/bin/tmux')
+ })
+ it('Zellij selected and unreadable: warm, in Zellij', async () => {
+ const bin = stub('broken')
+ const m = await manager(bin, { sessionBackend: 'zellij' })
+ const r = await m.createHeadless({ cols: 80, rows: 24, persistKey: 'n1' })
+ expect(r.fresh).toBe(false)
+ expect(h.spawns.at(-1)?.file).toBe(bin)
+ })
+ it('sessionExists does not claim a node Zellij could not be asked about', async () => {
+ inPlay()
+ const m = await manager(stub('broken'), { sessionBackend: 'tmux' })
+ ;(m as unknown as { tmuxPath: string | null }).tmuxPath = null
+ expect(await m.sessionExists('never-existed')).toBe(false)
+ })
+ })
+
+ describe('a tmux user with Zellij merely installed pays nothing', () => {
+ it('no zellij.kdl (never used) + tmux selected: zellij is never executed', async () => {
+ const m = await manager(stub('broken'), { sessionBackend: 'tmux' })
+ const r = await m.createHeadless({ cols: 80, rows: 24, persistKey: 'n2' })
+ expect(r.fresh).toBe(true)
+ await m.destroySession(null, 'n2')
+ expect(await m.sessionExists('n2')).toBe(false)
+ expect(calls()).toBe('')
+ })
+ })
+
+ describe('a socket path Zellij would refuse falls back to tmux', () => {
+ it('selected, absent, over the limit: tmux, cold', async () => {
+ process.env.ZELLIJ_SOCKET_DIR = `/${'d'.repeat(120)}`
+ const m = await manager(stub('none'), { sessionBackend: 'zellij' })
+ const r = await m.createHeadless({ cols: 80, rows: 24, persistKey: 'n3' })
+ expect(r.fresh).toBe(true)
+ expect(h.spawns.at(-1)?.file).toBe('/usr/bin/tmux')
+ expect(m.tmuxStatus().zellij).toMatchObject({ selected: true, socketTooLong: true })
+ })
+ })
++
++describe('a live link watcher never spawns into a Zellij session', () => {
++ it('a live Zellij node with no held session: the watcher is refused before any tmux probe', async () => {
++ // A watcher's own client is a read-only TMUX client; for a Zellij node the only honest answer
++ // is "not now" — never a Zellij attach, which would be a full, typing client.
++ const file = path.join(dir, 'zellij-live')
++ fs.writeFileSync(
++ file,
++ `#!/bin/sh\necho "$@" >> '${log}'\n` +
++ 'case "$1" in list-sessions) echo "nt-w1 [Created 1s ago]"; exit 0;; esac\n' +
++ 'case "$*" in *list-panes*) echo \'[{"id":0,"is_plugin":false,"is_focused":true}]\'; exit 0;; esac\n' +
++ 'exit 0\n',
++ { mode: 0o755 }
++ )
++ const m = await manager(file, { sessionBackend: 'zellij' })
++ vi.spyOn(m as unknown as { strictTmuxVerdict: () => Promise<string> }, 'strictTmuxVerdict').mockResolvedValue('absent')
++ const readWindowSize = vi.spyOn(m, 'readWindowSize')
++ const r = await m.joinAsWatcher(1 as never, { persistKey: 'w1', viewerId: 'v1', cols: 80, rows: 24 })
++ expect(r).toMatchObject({ sessionId: '', unavailable: 'join-only' })
++ expect(readWindowSize).not.toHaveBeenCalled()
++ expect(h.spawns).toHaveLength(0)
++ expect(calls()).not.toMatch(/attach/)
++ })
++})
diff --cc src/core/relay/hosted-scheduler.test.ts
index bf6964e05,87b8fbfeb..a4a9c607d
--- a/src/core/relay/hosted-scheduler.test.ts
+++ b/src/core/relay/hosted-scheduler.test.ts
@@@ -410,162 -410,191 +414,349 @@@ describe('hosted scheduler', () =>
await h.advance(HOUR)
expect(h.mintCalls() - before).toBeLessThanOrEqual(200)
})
+
+ // --- relay proof of possession (relay-pop.ts) ---
+
+ const popRefused = (reason: 'pop_required' | 'pop_invalid' = 'pop_invalid'): MintResult =>
+ ({ ok: false, kind: 'refused', status: 403, reason })
+
+ it.each(['pop_required', 'pop_invalid'] as const)(
+ 'two %s refusals in a row stop with backend-refused and the proof message; the first backs off',
+ async (reason) => {
+ const h = harness([popRefused(reason), popRefused(reason)])
+ h.s.start(); await flush()
+ // The first is transient (a POP_SECRET rotation mid challenge→mint looks exactly like this),
+ // and says so: an operator reading `team status` must not see a bare `network (403)`.
+ expect(h.s.status()).toMatchObject({
+ state: 'running',
+ lastError: `key proof refused once (${reason}) — retrying with a fresh challenge`
+ })
+ expect(h.timers).toHaveLength(1) // the backoff owns the next mint (a fresh challenge)
+ await h.advance(1000)
+ expect(h.mintCalls()).toBe(2)
+ expect(h.s.status()).toMatchObject({ state: 'backend-refused', lastError: POP_REFUSED_MESSAGE })
+ expect(h.timers).toHaveLength(0)
+ }
+ )
+
+ it.each<[string, MintResult]>([
+ ['a 503', { ok: false, kind: 'network', status: 503 }],
+ ['a 429', { ok: false, kind: 'rate-limited', status: 429 }],
+ ['a bad response', { ok: false, kind: 'bad-response' }]
+ ])('a transient failure between two refusals does not reset the count: refusal, %s, refusal stops', async (_label, transient) => {
+ // Only a successful mint (or start()) proves the key is accepted. Resetting on a transient
+ // failure would let a backend that refuses every proof, behind a flaky challenge, loop forever.
+ const h = harness([popRefused(), transient, popRefused()])
+ h.s.start(); await flush()
+ expect(h.s.status().state).toBe('running')
+ await h.advance(1000) // the backoff → the transient failure
+ expect(h.mintCalls()).toBe(2)
+ expect(h.s.status().state).toBe('running')
+ await h.advance(60_000) // the next backoff step (or the 429's 60 s floor) → refused again
+ expect(h.mintCalls()).toBe(3)
+ expect(h.s.status()).toMatchObject({ state: 'backend-refused', lastError: POP_REFUSED_MESSAGE })
+ expect(h.timers).toHaveLength(0)
+ })
+
+ it('each key-proof refusal is logged with its kind: warn on the first, error on the terminal one', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ try {
+ const h = harness([popRefused('pop_required'), popRefused('pop_invalid')])
+ h.s.start(); await flush()
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(String(warn.mock.calls[0][0])).toContain('pop_required')
+ expect(error).not.toHaveBeenCalled()
+ await h.advance(1000)
+ expect(h.s.status().state).toBe('backend-refused')
+ expect(warn).toHaveBeenCalledTimes(1)
+ expect(error).toHaveBeenCalledTimes(1)
+ expect(String(error.mock.calls[0][0])).toContain('pop_invalid')
+ } finally {
+ warn.mockRestore()
+ error.mockRestore()
+ }
+ })
+
+ it('a refusal that is not a key proof (402) logs nothing', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})
+ try {
+ const h = harness([{ ok: false, kind: 'refused', status: 402 }])
+ h.s.start(); await flush()
+ expect(h.s.status()).toMatchObject({ state: 'backend-refused', lastError: 'refused (402)' })
+ expect(warn).not.toHaveBeenCalled()
+ expect(error).not.toHaveBeenCalled()
+ } finally {
+ warn.mockRestore()
+ error.mockRestore()
+ }
+ })
+
+ it('one PoP refusal then a successful mint: hosting keeps running', async () => {
+ const h = harness([popRefused(), ok()])
+ h.s.start(); await flush()
+ await h.advance(1000)
+ expect(h.s.status()).toMatchObject({ state: 'running', idle: 1 })
+ expect(h.opened).toHaveLength(1)
+ })
+
+ it('a successful mint resets the count: refusal, success, refusal is still transient', async () => {
+ const h = harness([popRefused(), ok(), popRefused(), popRefused()])
+ h.s.start(); await flush()
+ await h.advance(1000) // retry → success
+ expect(h.opened).toHaveLength(1)
+ h.opened[0].ev.onBridged(); await flush() // bridged → a replacement is minted, and refused
+ expect(h.mintCalls()).toBe(3)
+ expect(h.s.status().state).toBe('running') // the first refusal since the success
+ await h.advance(1000)
+ expect(h.mintCalls()).toBe(4)
+ expect(h.s.status().state).toBe('backend-refused') // the second in a row
+ })
+
+ it('start() resets the count: a refusal before a stop does not make the next one terminal', async () => {
+ const h = harness([popRefused(), popRefused()])
+ h.s.start(); await flush()
+ expect(h.s.status().state).toBe('running')
+ h.s.stop()
+ h.s.start(); await flush()
+ expect(h.mintCalls()).toBe(2)
+ expect(h.s.status().state).toBe('running') // the first refusal of THIS run
+ })
+
+ it('a POP_SECRET rotated between the challenge and the mint: the real mint backs off, re-challenges and proves', async () => {
+ // Backend A issues the challenge, backend B (the new secret) verifies the mint: an honest host
+ // earns pop_invalid once. Stopping there would stop every host mid-mint at the rotation.
+ const keys = nacl.box.keyPair()
+ const pub = Buffer.from(keys.publicKey).toString('base64')
+ const oldSecret = createTestPopServer('old-secret-'.padEnd(40, 'o'))
+ const newSecret = createTestPopServer('new-secret-'.padEnd(40, 'n'))
+ let issuer = oldSecret
+ const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status })
+ const f = (async (u: string, init: RequestInit) => {
+ const body = JSON.parse(String(init.body)) as Record<string, unknown>
+ if (u.endsWith('/v1/relay/challenge')) {
+ const c = issuer.issue(pub, 'host-token')
+ issuer = newSecret // the rotation lands right after the first challenge
+ return json(200, c)
+ }
+ const proven = newSecret.verify({ hostPublicKeyB64: pub, purpose: 'host-token', subject: String(body.deviceId ?? ''), popChallenge: body.popChallenge, popProof: body.popProof })
+ return proven ? json(200, { pairingToken: 'T', hostId: 'H', exp: 0 }) : json(403, { error: 'pop_invalid' })
+ }) as typeof fetch
+ const mint = () => mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: pub, hostSecretKey: keys.secretKey, fetch: f })
+ const h = harness([mint, mint])
+ h.s.start(); await flush()
+ expect(h.s.status().state).toBe('running')
+ await h.advance(1000); await flush()
+ expect(h.opened).toHaveLength(1)
+ expect(h.s.status().state).toBe('running')
+ })
+
+ it('a pop_required answer to an unproven mint (challenge 404 mid-redeploy) backs off and proves on the retry', async () => {
+ // The real mint against a fake API: while the backend redeploys its proxy answers the challenge
+ // 404, the unproven mint lands on the fresh backend and earns pop_required. That must be a retry,
+ // never backend-refused — and the retry asks for a fresh challenge and proves.
+ const keys = nacl.box.keyPair()
+ const pub = Buffer.from(keys.publicKey).toString('base64')
+ const pop = createTestPopServer()
+ let redeploying = true
+ const urls: string[] = []
+ const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status })
+ const f = (async (u: string, init: RequestInit) => {
+ urls.push(u)
+ const body = JSON.parse(String(init.body)) as Record<string, unknown>
+ if (u.endsWith('/v1/relay/challenge')) return redeploying ? json(404, {}) : json(200, pop.issue(pub, 'host-token'))
+ if (!pop.verify({ hostPublicKeyB64: pub, purpose: 'host-token', subject: String(body.deviceId ?? ''), popChallenge: body.popChallenge, popProof: body.popProof }))
+ return json(403, { error: 'pop_required' })
+ return json(200, { pairingToken: 'T', hostId: 'H', exp: 0 })
+ }) as typeof fetch
+ const mint = () => mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: pub, hostSecretKey: keys.secretKey, fetch: f })
+ const h = harness([mint, mint])
+ h.s.start(); await flush()
+ expect(h.s.status()).toMatchObject({ state: 'running', lastError: 'network (403)' })
+ expect(h.timers).toHaveLength(1) // the backoff owns the next mint
+ expect(h.opened).toHaveLength(0)
+ redeploying = false
+ await h.advance(1000); await flush()
+ expect(h.opened).toHaveLength(1)
+ expect(urls.map((u) => u.replace('https://api', ''))).toEqual([
+ '/v1/relay/challenge', '/v1/relay/host-token', '/v1/relay/challenge', '/v1/relay/host-token'
+ ])
+ })
+
+ it('a rate-limited challenge (429, shared per-IP limit) waits the 60 s floor before the next mint', async () => {
+ const keys = nacl.box.keyPair()
+ const pub = Buffer.from(keys.publicKey).toString('base64')
+ let challenges = 0
+ const f = (async (u: string) => {
+ if (u.endsWith('/v1/relay/challenge')) { challenges++; return new Response('{}', { status: 429 }) }
+ throw new Error('no mint may follow a refused challenge')
+ }) as typeof fetch
+ const mint = () => mintHostToken({ apiBase: 'https://api', deviceId: 'd', hostPublicKeyB64: pub, hostSecretKey: keys.secretKey, fetch: f })
+ const h = harness([mint, mint])
+ h.s.start(); await flush()
+ expect(h.s.status()).toMatchObject({ state: 'running', lastError: 'rate-limited (429)' })
+ await h.advance(59_999)
+ expect(challenges).toBe(1)
+ await h.advance(1)
+ expect(challenges).toBe(2)
+ })
})
+
+// A live link's viewer cap: at maxBridged bridged sessions no idle listener is opened, so the broker
+// turns further clients away ("no host waiting"); a session ending reopens one through the usual top().
+describe('hosted scheduler maxBridged', () => {
+ it('opens no idle listener while maxBridged sessions are bridged, and reopens when one ends', async () => {
+ const opened: { ev: { onBridged(): void; onClose(): void }; closed: boolean }[] = []
+ const s = createHostedScheduler(
+ {
+ mint: async () => ({ ok: true, pairingToken: 't', hostId: 'h', ttlMs: 120_000 }),
+ open: (_t, ev) => {
+ const l = { ev, closed: false }
+ opened.push(l)
+ return { bridged: false, close: () => { l.closed = true } }
+ },
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
+ clearTimeout: (h) => clearTimeout(h as ReturnType<typeof setTimeout>),
+ maxBridged: 2
+ },
+ () => Date.now()
+ )
+ s.start()
+ await vi.waitFor(() => expect(opened).toHaveLength(1))
+ opened[0].ev.onBridged()
+ await vi.waitFor(() => expect(opened).toHaveLength(2))
+ opened[1].ev.onBridged()
+ await new Promise((r) => setTimeout(r, 30))
+ expect(opened).toHaveLength(2)
+ opened[0].ev.onClose()
+ await vi.waitFor(() => expect(opened).toHaveLength(3))
+ s.stop()
+ })
+
+ it('absent maxBridged (or an explicit undefined) keeps the old behaviour: every bridge gets a replacement', async () => {
+ for (const opts of [{}, { maxBridged: undefined }]) {
+ const h = harness(okMany(20), opts)
+ h.s.start(); await flush()
+ for (let i = 0; i < 12; i++) {
+ h.opened[h.opened.length - 1].ev.onBridged(); await flush()
+ }
+ expect(h.opened).toHaveLength(13)
+ expect(h.mintCalls()).toBe(13)
+ expect(h.s.status()).toMatchObject({ state: 'running', idle: 1, bridged: 12 })
+ }
+ })
+
+ it('maxBridged: 1 serves one peer at a time: no listener while it is connected, one again when it leaves', async () => {
+ const h = harness(okMany(10), { maxBridged: 1 })
+ h.s.start(); await flush()
+ expect(h.opened).toHaveLength(1)
+ h.opened[0].ev.onBridged(); await flush()
+ expect(h.opened).toHaveLength(1)
+ expect(h.s.status()).toMatchObject({ state: 'running', idle: 0, bridged: 1 })
+ await h.advance(HOUR)
+ expect(h.mintCalls()).toBe(1)
+ h.opened[0].ev.onClose(); await flush()
+ expect(h.opened).toHaveLength(2)
+ expect(h.s.status()).toMatchObject({ idle: 1, bridged: 0 })
+ h.opened[1].ev.onBridged(); await flush()
+ expect(h.opened).toHaveLength(2)
+ expect(h.mintCalls()).toBe(2)
+ })
+
+ it('at the cap nothing is minted, no timer is armed, no status churns and nothing is written into the backoff', async () => {
+ const statuses: SchedulerStatus[] = []
+ const h = harness(okMany(10), { maxBridged: 2, onStatus: (st) => statuses.push(st) })
+ h.s.start(); await flush()
+ h.opened[0].ev.onBridged(); await flush()
+ h.opened[1].ev.onBridged(); await flush()
+ expect(h.opened).toHaveLength(2)
+ expect(h.s.status()).toMatchObject({ state: 'running', idle: 0, bridged: 2, lastError: null })
+ // Bridged listeners hold no refresh and the cap arms no retry: there is nothing to wake up and spin.
+ expect(h.timers).toHaveLength(0)
+ const delaysAtCap = h.delays.length
+ const emitsAtCap = statuses.length
+ await h.advance(HOUR)
+ expect(h.mintCalls()).toBe(2)
+ expect(h.delays).toHaveLength(delaysAtCap)
+ expect(statuses).toHaveLength(emitsAtCap)
+ expect(h.s.status()).toMatchObject({ state: 'running', idle: 0, bridged: 2, lastError: null })
+ // Leaving the cap is not a relay failure: the replacement is minted at once, and a relay that then
+ // drops it starts the backoff at its FIRST step — the time spent full advanced nothing.
+ h.opened[0].ev.onClose(); await flush()
+ expect(h.opened).toHaveLength(3)
+ expect(h.timers.map((x) => x.ms)).toEqual([90_000]) // only the new idle listener's refresh
+ h.opened[2].ev.onClose(); await flush()
+ expect(h.timers.map((x) => x.ms)).toEqual([1000])
+ })
+
+ it('sessions ending together reopen ONE idle listener, not one per ended session', async () => {
+ const h = harness(okMany(10), { maxBridged: 3 })
+ h.s.start(); await flush()
+ for (let i = 0; i < 3; i++) {
+ h.opened[i].ev.onBridged(); await flush()
+ }
+ expect(h.opened).toHaveLength(3)
+ expect(h.s.status()).toMatchObject({ idle: 0, bridged: 3 })
+ // All three peers leave in the same tick (the relay dropping them together).
+ h.opened[0].ev.onClose(); h.opened[1].ev.onClose(); h.opened[2].ev.onClose()
+ await flush()
+ expect(h.mintCalls()).toBe(4)
+ expect(h.opened).toHaveLength(4)
+ expect(h.s.status()).toMatchObject({ idle: 1, bridged: 0 })
+ await h.advance(60_000) // and nothing more arrives later
+ expect(h.mintCalls()).toBe(4)
+ })
+
+ it('sessions ending one after another from the cap still leave exactly one idle listener', async () => {
+ const h = harness(okMany(10), { maxBridged: 2 })
+ h.s.start(); await flush()
+ h.opened[0].ev.onBridged(); await flush()
+ h.opened[1].ev.onBridged(); await flush()
+ h.opened[0].ev.onClose(); await flush()
+ expect(h.opened).toHaveLength(3)
+ h.opened[1].ev.onClose(); await flush() // the idle replacement already exists
+ expect(h.opened).toHaveLength(3)
+ expect(h.mintCalls()).toBe(3)
+ expect(h.s.status()).toMatchObject({ idle: 1, bridged: 0 })
+ })
+
+ it('a link that fills just as the mint budget runs out arms nothing; the budget owns the wait only once a session ends', async () => {
+ const h = harness(okMany(300), { maxBridged: 1 })
+ h.s.start(); await flush()
+ // A peer joins and leaves 199 times inside the hour: every leave is one mint, 200 in all.
+ for (let i = 0; i < 199; i++) {
+ const l = h.opened[h.opened.length - 1]
+ l.ev.onBridged(); await flush()
+ l.ev.onClose(); await flush()
+ }
+ expect(h.s.status()).toMatchObject({ mintsLastHour: 200, idle: 1, bridged: 0 })
+ h.opened[h.opened.length - 1].ev.onBridged(); await flush() // full, with the budget spent
+ expect(h.timers).toHaveLength(0)
+ expect(h.s.status()).toMatchObject({ idle: 0, bridged: 1, lastError: null })
+ h.opened[h.opened.length - 1].ev.onClose(); await flush() // below the cap: now the budget speaks
+ expect(h.s.status().lastError).toBe('mint budget')
+ expect(h.mintCalls()).toBe(200)
+ await h.advance(HOUR) // the window still holds the mints made at t=0
+ expect(h.mintCalls()).toBe(200)
+ await h.advance(1)
+ expect(h.mintCalls()).toBe(201)
+ expect(h.s.status()).toMatchObject({ state: 'running', idle: 1, bridged: 0 })
+ })
+
+ it('a reopen from the cap answered 429 still waits the full 60 s, even when another session ends meanwhile', async () => {
+ const h = harness([ok(), ok(), { ok: false, kind: 'rate-limited', status: 429 }, ok(), ok()], { maxBridged: 2 })
+ h.s.start(); await flush()
+ h.opened[0].ev.onBridged(); await flush()
+ h.opened[1].ev.onBridged(); await flush()
+ h.opened[0].ev.onClose(); await flush() // the reopen mint is answered 429
+ expect(h.mintCalls()).toBe(3)
+ h.opened[1].ev.onClose(); await flush() // below the cap now, but the 429 wait owns the next mint
+ await h.advance(59_999)
+ expect(h.mintCalls()).toBe(3)
+ await h.advance(1)
+ expect(h.mintCalls()).toBe(4)
+ expect(h.opened).toHaveLength(3)
+ expect(h.s.status()).toMatchObject({ idle: 1, bridged: 0 })
+ })
+})
diff --cc src/core/relay/hosted-scheduler.ts
index a6bfe79db,8cfa7682f..2d3901783
--- a/src/core/relay/hosted-scheduler.ts
+++ b/src/core/relay/hosted-scheduler.ts
@@@ -12,11 -12,16 +12,19 @@@
// - at most MINT_BUDGET_PER_HOUR successful mints in any rolling hour, whatever asks for them. The
// backend's free limit is 240/h, the 15 s backoff ceiling alone reaches exactly 240/h, and a peer
// joining and leaving every 10 s asks for 360/h — so no per-path rule can hold the line on its own;
- // - a 429 waits at least 60 s (longer if Retry-After says so); a 402/403 stops minting;
+ // - a 429 waits at least 60 s (longer if Retry-After says so); a 402/403 stops minting (a refused
+ // key proof names itself in `lastError`; a 403 host-token.ts judges transient arrives as
+ // `network` and backs off);
+ // - a key-proof refusal stops minting only on the SECOND in a row: a POP_SECRET rotation, or a
+ // secret mismatch between backend instances, inside ONE challenge→mint pair refuses an honest
+ // host once. The first is backed off like a transient 403 (the retry fetches a fresh challenge);
+ // only a successful mint or start() resets the count — a transient failure in between does not,
+ // or a backend refusing every proof behind a flaky challenge would retry forever. Both refusals
+ // are logged with their kind (warn, then error), so an operator can tell the two apart;
-// - while a backoff timer is armed it owns the next mint: nothing else may mint early.
+// - while a backoff timer is armed it owns the next mint: nothing else may mint early;
+// - a live link caps its bridged sessions (`maxBridged`): while full, no idle listener is kept (the
+// broker turns further clients away), nothing is minted and no timer is armed; a session ending
+// reopens ONE through the usual top().
// Everything the injected deps can throw is caught: a scheduler that swallowed an exception would sit
// in 'running' with no listener and no timer, i.e. hosting silently dead until a restart.
import type { MintResult } from './host-token'
diff --cc src/core/watch-link/capture-route.test.ts
index 0fdac7fad,000000000..0605900af
mode 100644,000000..100644
--- a/src/core/watch-link/capture-route.test.ts
+++ b/src/core/watch-link/capture-route.test.ts
@@@ -1,138 -1,0 +1,142 @@@
+import { describe, it, expect } from 'vitest'
+import {
+ VISIBLE_CAPTURE_FORMAT,
+ exactPaneTarget,
+ localCaptureVisibleArgs,
+ parseVisibleCapture,
+ unavailableCapture,
+ visibleCaptureRoute
+} from './capture-route'
+
+describe('visibleCaptureRoute', () => {
+ it('never routes to a capture that returns history', () => {
+ expect(visibleCaptureRoute({ sessionHost: {} }, true)).toBe('none')
+ expect(visibleCaptureRoute({ nativeWindowsPane: {} }, true)).toBe('none')
+ expect(visibleCaptureRoute({ sshRemote: {} }, true)).toBe('ssh')
+ expect(visibleCaptureRoute({ tmuxBacked: true }, true)).toBe('tmux')
+ expect(visibleCaptureRoute({ tmuxBacked: true }, false)).toBe('none')
+ expect(visibleCaptureRoute({ tmuxBacked: false }, true)).toBe('none')
+ })
+
+ it('a session-host session is none even when it is also marked tmux-backed or remote', () => {
+ // The session host's only capture is ~200 lines of scrollback; nothing may route around that.
+ expect(visibleCaptureRoute({ sessionHost: true, tmuxBacked: true }, true)).toBe('none')
+ expect(visibleCaptureRoute({ sessionHost: true, sshRemote: {} }, true)).toBe('none')
+ expect(visibleCaptureRoute({ nativeWindowsPane: {}, tmuxBacked: true }, true)).toBe('none')
+ })
++
++ it('a Zellij session is none although it is marked tmux-backed: there is no tmux session to capture', () => {
++ expect(visibleCaptureRoute({ zellij: true, tmuxBacked: true }, true)).toBe('none')
++ })
+})
+
+describe('exactPaneTarget', () => {
+ it('is the exact-session, active-pane spelling measured on tmux 3.4', () => {
+ // `=name` alone is "can't find pane" for capture-pane (and silently EMPTY for display-message);
+ // a bare `name` prefix-matches another node's session. Only `=name:` is exact AND resolves.
+ expect(exactPaneTarget('nt-abc')).toBe('=nt-abc:')
+ })
+})
+
+describe('localCaptureVisibleArgs', () => {
+ const args = localCaptureVisibleArgs('sock', 'nt-abc')
+
+ it('captures the visible screen with SGR and asks for the cursor in the SAME invocation', () => {
+ expect(args).toEqual([
+ '-L',
+ 'sock',
+ 'capture-pane',
+ '-p',
+ '-e',
+ '-t',
+ '=nt-abc:',
+ ';',
+ 'display-message',
+ '-p',
+ '-t',
+ '=nt-abc:',
+ VISIBLE_CAPTURE_FORMAT
+ ])
+ })
+
+ it('never asks for history', () => {
+ expect(args).not.toContain('-S')
+ expect(args).not.toContain('-a')
+ })
+
+ it('targets EXACTLY — never a bare name tmux would prefix-match', () => {
+ expect(args.filter((a) => a.includes('nt-abc'))).toEqual(['=nt-abc:', '=nt-abc:'])
+ })
+
+ it('asks for the cursor and nothing else — no alternate-screen flag (R18)', () => {
+ // A keyframe's altScreen comes from the JOIN (tmux-backed client => true), never the capture:
+ // the pane's `#{alternate_on}` describes a different screen than the tmux client's stream.
+ expect(VISIBLE_CAPTURE_FORMAT).toBe('#{cursor_x} #{cursor_y}')
+ expect(args.join(' ')).not.toContain('alternate_on')
+ })
+})
+
+describe('parseVisibleCapture', () => {
+ it('splits the trailing cursor line off a real tmux 3.4 reply', () => {
+ // Measured: a 20x4 pane after 10 lines of output — only the visible rows, then the cursor line.
+ expect(parseVisibleCapture('L8\nL9\nL10\n\n0 3\n')).toEqual({
+ screen: 'L8\nL9\nL10\n\n',
+ cursor: { x: 0, y: 3 }
+ })
+ })
+
+ it('carries no alternate-screen field at all', () => {
+ expect(Object.keys(parseVisibleCapture('\n ALT\n\n\n5 1\n')).sort()).toEqual(['cursor', 'screen'])
+ expect(Object.keys(parseVisibleCapture('no cursor line\n')).sort()).toEqual(['cursor', 'screen'])
+ })
+
+ it('keeps the screen byte-identical to what capture-pane printed on its own', () => {
+ const screen = '\u001b[1mbold\u001b[0m\nplain\n'
+ expect(parseVisibleCapture(`${screen}12 1\n`).screen).toBe(screen)
+ })
+
+ it('an empty screen is an empty string, not the cursor line', () => {
+ expect(parseVisibleCapture('0 0\n')).toEqual({ screen: '', cursor: { x: 0, y: 0 } })
+ })
+
+ it('a screen whose own last line looks like a cursor line keeps that line', () => {
+ // Only the LAST line is the cursor; a numeric-ish row above it is screen text.
+ expect(parseVisibleCapture('10 20\n3 4\n')).toEqual({ screen: '10 20\n', cursor: { x: 3, y: 4 } })
+ })
+
+ it('reads CRLF line endings', () => {
+ expect(parseVisibleCapture('a\r\nb\r\n7 1\r\n')).toEqual({
+ screen: 'a\r\nb\r\n',
+ cursor: { x: 7, y: 1 }
+ })
+ })
+
+ it('without a cursor line the whole output is the screen and the cursor is unknown', () => {
+ for (const out of ['a\nb\n', 'a\nb', 'a\n3 4 5\n', 'a\n3 4 0\n', 'a\n3\n', 'a\nx 1\n', 'a\n \n', '']) {
+ expect(parseVisibleCapture(out)).toEqual({ screen: out, cursor: null })
+ }
+ })
+
+ it('does not accept a padded or signed cursor line', () => {
+ for (const line of [' 1 2', '1 2 ', '-1 2', '1 2', '1\t2']) {
+ const out = `s\n${line}\n`
+ expect(parseVisibleCapture(out)).toEqual({ screen: out, cursor: null })
+ }
+ })
+})
+
+describe('unavailableCapture', () => {
+ it('is NO capture: flagged, with an empty screen and nothing known', () => {
+ expect(unavailableCapture()).toEqual({ screen: '', cursor: null, unavailable: true })
+ })
+
+ it('a real capture of an empty pane is not "no capture" (R36): it carries no flag', () => {
+ expect(parseVisibleCapture('0 0\n')).toEqual({ screen: '', cursor: { x: 0, y: 0 } })
+ expect(parseVisibleCapture('')).toEqual({ screen: '', cursor: null })
+ expect('unavailable' in parseVisibleCapture('\n\n0 0\n')).toBe(false)
+ })
+
+ it('is a fresh object each time (a caller may mutate what it was handed)', () => {
+ expect(unavailableCapture()).not.toBe(unavailableCapture())
+ })
+})
diff --cc src/core/watch-link/capture-route.ts
index df3574e08,000000000..fb5cb2df5
mode 100644,000000..100644
--- a/src/core/watch-link/capture-route.ts
+++ b/src/core/watch-link/capture-route.ts
@@@ -1,117 -1,0 +1,121 @@@
+// A live link's KEYFRAME: the visible screen of a node's session, never the history above it.
+//
+// Pure: no tmux, no ssh, no PtyManager. `PtyManager.captureVisible` runs the argv built here (locally,
+// or over the ControlMaster through `remoteCaptureVisibleArgs`) and parses the reply here.
+//
+// Which backend gets one (`visibleCaptureRoute`): the session host's capture is ~200 lines of
+// scrollback and a direct Windows pane has no visible-only read, so both get NO keyframe (the viewer
- // starts from the live stream) rather than history. A plain shell has no tmux to ask.
++// starts from the live stream) rather than history. A plain shell has no tmux to ask, and neither has
++// a Zellij session (the optional local backend, zellij-backend.ts).
+//
+// The screen and the cursor are read in ONE tmux invocation (`capture-pane … ; display-message …`), so
+// both describe the same instant: a cursor read in a second round trip could describe a screen that has
+// since scrolled.
+//
+// The target is EXACT (`exactPaneTarget`). Node ids end in a counter, so `nt-x-1` is a prefix of
+// `nt-x-12`, and tmux resolves a bare target by fnmatch then PREFIX on a miss: a bare target would
+// capture ANOTHER node's screen and send it to this link's viewers. Measured on tmux 3.4, with only
+// `nt-x-12` alive:
+// capture-pane -t nt-x-1 → 12's screen, exit 0 (the trap)
+// capture-pane -t =nt-x-1 → "can't find pane", exit 1 (also for =nt-x-12: `=name` alone never
+// resolves a target-PANE)
+// capture-pane -t =nt-x-1: → "can't find session", exit 1
+// capture-pane -t =nt-x-12: → 12's screen, exit 0 (exact AND resolves)
+// display-message -t =nt-x-1: → exit 0, every format EMPTY
+// and the combined `capture-pane -t =nt-x-1: ; display-message …` stops at the failed capture: exit 1,
+// nothing on stdout. So an exact miss is a failed command, which the caller reads as unavailable.
+
+/**
+ * What a visible-only capture returns: the screen and the cursor, read at one instant.
+ *
+ * Deliberately NO alternate-screen flag (controller ruling R18). A keyframe's `altScreen` is decided
+ * by the CALLER from the join (a tmux-backed client ⇒ `true`), not from the capture: a watcher
+ * co-attaches to the tmux CLIENT's output, and tmux paints its client on the alternate screen
+ * whatever the pane's application does, so every `tmux`/`ssh`-route join means `altScreen: true`.
+ * The pane's own `#{alternate_on}` (vim, a TUI) describes a different screen — a shell pane reads 0
+ * while the stream is on the alternate screen — and mapping it into the keyframe would scroll every
+ * tmux redraw into the viewer's history.
+ */
+export interface VisibleCapture {
+ /** The visible screen with SGR, byte-identical to what `capture-pane -p -e` prints on its own
+ * (one `\n`-terminated line per row); '' when there is none. Never history. */
+ screen: string
+ /** The pane's cursor at capture time, 0-based (`#{cursor_x}`, `#{cursor_y}`); null when unread. */
+ cursor: { x: number; y: number } | null
+ /**
+ * There is NO capture: the backend has no visible-only one, or the capture failed. Set only by
+ * `unavailableCapture()`; a real capture of an empty pane never carries it. The difference matters
+ * (controller ruling R36): a viewer paints a keyframe as reset + clear, so an empty keyframe sent for
+ * "no capture" would erase everything the stream had drawn. The link host sends no keyframe for it.
+ */
+ unavailable?: true
+}
+
+/** A session with no visible-only capture, or one that failed: nothing to paint, nothing known. */
+export function unavailableCapture(): VisibleCapture {
+ return { screen: '', cursor: null, unavailable: true }
+}
+
+export function visibleCaptureRoute(
- s: { sessionHost?: unknown; nativeWindowsPane?: unknown; sshRemote?: unknown; tmuxBacked?: boolean },
++ s: { sessionHost?: unknown; nativeWindowsPane?: unknown; sshRemote?: unknown; tmuxBacked?: boolean; zellij?: boolean },
+ tmuxAvailable: boolean
+): 'none' | 'ssh' | 'tmux' {
- if (s.sessionHost || s.nativeWindowsPane) return 'none'
++ // A Zellij session is `tmuxBacked` too (that field means "releasing a client destroys nothing"),
++ // but there is no tmux session to capture: never aim the tmux socket at it (pty-manager's rule
++ // for every path that would talk to tmux). No keyframe — the viewer starts from the live stream.
++ if (s.sessionHost || s.nativeWindowsPane || s.zellij) return 'none'
+ if (s.sshRemote) return 'ssh'
+ return tmuxAvailable && s.tmuxBacked ? 'tmux' : 'none'
+}
+
+/** The tmux format read beside the screen: cursor column and cursor row, 0-based. */
+export const VISIBLE_CAPTURE_FORMAT = '#{cursor_x} #{cursor_y}'
+
+/** "Exactly this session, its active pane" — the only spelling that is exact AND resolves for a
+ * target-pane command (see the measurement at the top of this file). */
+export function exactPaneTarget(sessionName: string): string {
+ return `=${sessionName}:`
+}
+
+/**
+ * The local tmux argv (after the binary): visible screen with SGR, then the cursor line, in one
+ * invocation. The `;` is tmux's own command separator, passed as its own argv element (no shell).
+ * No `-S`: capture-pane without it starts at the first VISIBLE row.
+ */
+export function localCaptureVisibleArgs(socket: string, sessionName: string): string[] {
+ const target = exactPaneTarget(sessionName)
+ return [
+ '-L',
+ socket,
+ 'capture-pane',
+ '-p',
+ '-e',
+ '-t',
+ target,
+ ';',
+ 'display-message',
+ '-p',
+ '-t',
+ target,
+ VISIBLE_CAPTURE_FORMAT
+ ]
+}
+
+const CURSOR_LINE = /^(\d+) (\d+)$/
+
+/**
+ * Split the combined reply: the LAST line is the cursor line when it has exactly the format's shape,
+ * and everything before it is the screen. Anything else (no such line, an older tmux that printed
+ * something different) leaves the whole output as the screen and the cursor unknown.
+ */
+export function parseVisibleCapture(stdout: string): VisibleCapture {
+ const body = stdout.replace(/\r?\n$/, '')
+ const cut = body.lastIndexOf('\n')
+ const last = cut === -1 ? body : body.slice(cut + 1)
+ const m = CURSOR_LINE.exec(last)
+ if (!m) return { screen: stdout, cursor: null }
+ return {
+ screen: cut === -1 ? '' : body.slice(0, cut + 1),
+ cursor: { x: Number(m[1]), y: Number(m[2]) }
+ }
+}
diff --cc src/main/index.ts
index 89aa787ad,8fd0903e0..beebdef90
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@@ -3160,49 -3230,41 +3248,84 @@@ app.whenReady().then(async () =>
}
}
})
+ // Live links (docs/live-links.md): a Pro, read-only, expiring browser link to one terminal, hosted
+ // by this machine over the E2E relay. The viewer is a QUIET, SELF-PACED relay peer (never in a
+ // broadcast, never a pause ticket); the pty seam and the node-gone rule are core's, shared with the
+ // Server Edition. `init()` decides nothing before the boot workspace load (R40): an empty answer
+ // while the index is still being read is not evidence that a node is gone.
+ watchLinks = createWatchLinkService({
+ api: createWatchLinkApi({ apiBase: RELAY_API_BASE }),
+ relayUrl: RELAY_URL,
+ // Sealed through the keychain seam; if it refuses, links live in memory and the owner is told.
+ store: new WatchLinkStore({
+ file: join(corePlatform.userDataDir, 'watch-links.json'),
+ seal: corePlatform.sealSecret?.bind(corePlatform),
+ unseal: corePlatform.unsealSecret?.bind(corePlatform)
+ }),
+ entitlement: getStoredEntitlement,
+ relayAllowed,
+ nodeState: (nodeId) => workspaceNodeState(workspaceStore, nodeId),
+ workspaceReady: () => bootWorkspaceLoad,
+ clients: {
+ attach: (sink) => {
+ const id = allocateRelayClientId()
+ // No presence join: a viewer puts no cursor or facepile on the owner's canvas.
+ registerPeerSink(id, sink, { quiet: true, selfPaced: true })
+ return id
+ },
+ // → presenceHub.leave (a no-op for an id that never joined) and PtyManager.dropClient.
+ detach: (id) => unregisterPeerSink(id)
+ },
+ // A node of an SSH project is watched on ITS host over that project's master, or not at all:
+ // `requireRemote` for every such node, and the remote fields from this machine's own records.
+ pty: createWatchPty(ptyManager, (nodeId) => {
+ const projectId = workspaceStore.sshProjectIdForNode(nodeId)
+ if (!projectId) return {}
+ const ref = sshProjectManager?.refForProject(projectId)
+ return {
+ requireRemote: true,
+ ...(ref ? { sshRemote: { conn: ref.conn, controlPath: ref.controlPath, remoteCwd: ref.remoteCwd ?? '~' } } : {})
+ }
+ }),
+ emit: (channel, ...args) => sendToOwners(corePlatform, channel, ...args)
+ })
+ registerWatchLinkIpc(corePlatform, watchLinks)
+ void watchLinks.init()
+ // Dev-server ports (CLAUDE.md → Dev-server ports). Same identity predicate and the same
+ // exit-code-gated runner shape as session memory above; forwarding rides the project's master.
+ const devPorts = startDevPortsService({
+ tmuxBin: () => ptyManager.getTmuxBin(),
+ remote: {
+ isRemoteProject: sshScopePredicate({
+ sshProjectIds: () => workspaceStore.sshProjectIds(),
+ connectedProjectIds: () =>
+ (sshProjectManager?.connectedHosts() ?? []).map((h) => h.projectId)
+ }),
+ run: async (projectId, command) => {
+ const mgr = sshProjectManager
+ const ref = mgr?.refForProject(projectId)
+ if (!mgr || !ref) return null
+ try {
+ // The script always ends with an unconditional echo: a non-zero code is ssh itself failing.
+ const { code, stdout } = await mgr.sshRun(childArgs(ref.conn, ref.controlPath, command))
+ return code === 0 ? stdout : null
+ } catch {
+ return null
+ }
+ },
+ forward: {
+ refForProject: (projectId) => sshProjectManager?.refForProject(projectId),
+ run: (args) =>
+ sshProjectManager ? sshProjectManager.sshRun(args) : Promise.resolve({ code: -1, stdout: '' })
+ }
+ }
+ })
+ // A node's session ending (delete, recycle) takes its dev server with it — cancel its forwards.
+ ptyManager.onSessionEnded((nodeId) => void devPorts.registry?.nodeEnded(nodeId))
+ // A master that went away took its listeners with it; forget them so the menu offers again.
+ onSshProjectStatus((e) => {
+ if (e.status !== 'connected' && e.status !== 'connecting') devPorts.registry?.projectDisconnected(e.projectId)
+ })
const ackSweeper = createAckSweeper({
handlers: { ackDone, onUnreadClear: (id) => sendToMain(IPC.agentUnreadClear, id) }
})
diff --cc src/preload/index.ts
index e9f9e8de6,b0eddc084..ea90e4ec9
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@@ -23,7 -24,7 +24,8 @@@ import type
} from '../shared/types'
import type { ClientId, PeerDiff, PeerIdentity, PeerState } from '../shared/presence'
import type { ProjectConsentRequest, ProjectSetupEvent } from '../shared/project-settings'
+import type { WatchChatMessage, WatchLinkNotice, WatchLinkView } from '../shared/watch-link-types'
+ import type { DevPortForwardRequest, DevPortsQuery } from '../shared/dev-ports'
// Fan a single ipcRenderer listener per channel out to many renderer subscribers. Without
// this, every node that subscribes (e.g. Cmd+M markdown toggle on each terminal/editor) adds
diff --cc src/renderer/bridge/relay-api.ts
index ed36e88e1,7dad7267d..35440842a
--- a/src/renderer/bridge/relay-api.ts
+++ b/src/renderer/bridge/relay-api.ts
@@@ -194,12 -199,9 +199,13 @@@ export function buildRelayApi
// 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,
+ // Live links publish THIS machine's terminals; a relay tab shows another machine's, so it takes
+ // the inert stub (create answers `unsupported`). Never the local preload's real member, which
+ // `...local` would otherwise hand it: that would offer to publish a node id this core does not run.
+ watchLink: stub.watchLink,
// 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
diff --cc src/renderer/bridge/ws-bridge.ts
index bfe975901,b3b46b081..8bfa04f4e
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@@ -1324,7 -1308,7 +1352,8 @@@ export async function installWsBridge()
...buildSpeechApi(client),
...buildUsageApi(client),
...buildSessionMemoryApi(client),
+ ...buildWatchLinkApi(client),
+ ...buildRecentConversationsApi(client),
...buildWallpaperApi(client),
...buildTriggersApi(client),
...buildGitHubApi(client),
diff --cc src/renderer/components/SessionRow.test.tsx
index c661f2c9f,f63be0d3d..a1abe7b3d
--- a/src/renderer/components/SessionRow.test.tsx
+++ b/src/renderer/components/SessionRow.test.tsx
@@@ -39,3 -38,31 +39,32 @@@ describe('SessionRow status age', () =
expect(html).toContain('Entered this state 5m ago')
})
})
+
+ // Issue #291: the icon shows wherever the node is listed — the sidebar row draws it through the
+ // same NodeIconView as the canvas header.
+ describe('SessionRow icon', () => {
+ const render = (icon: SessionRowVM['icon']): string =>
+ renderToStaticMarkup(
+ <SessionRow
+ row={{ ...row, icon }}
++ liveLinkSource="local"
+ onClick={vi.fn()}
+ onClose={vi.fn()}
+ onRename={vi.fn()}
+ onAiName={vi.fn()}
+ onContextMenu={vi.fn()}
+ onDragStart={vi.fn()}
+ onDragEnd={vi.fn()}
+ />
+ )
+
+ it('draws a glyph icon as an svg inside the row icon slot', () => {
+ const html = render({ type: 'lucide', name: 'database' })
+ expect(html).toMatch(/<span class="node-icon ss-row__icon"[^>]*><svg[^>]*lucide-database/)
+ })
+
+ it('draws nothing for a glyph name the allowlist does not know', () => {
+ const html = render({ type: 'lucide', name: 'skull' } as SessionRowVM['icon'])
+ expect(html).not.toContain('ss-row__icon')
+ })
+ })
diff --cc src/renderer/components/kanban/CardModal.test.tsx
index e5499d168,d29979891..6dd257c44
--- a/src/renderer/components/kanban/CardModal.test.tsx
+++ b/src/renderer/components/kanban/CardModal.test.tsx
@@@ -120,6 -120,45 +120,46 @@@ describe('CardModal', () =>
document.body.innerHTML = ''
})
+ // #291 review: the header slot decided smiley-vs-icon on the RAW stored value, while
+ // NodeIconView normalizes — so an invalid stored icon drew an empty, un-muted slot.
+ it('shows the smiley "Set icon" slot for an icon that fails validation', () => {
+ const icon = (value: unknown): HTMLButtonElement => {
+ const root = createRoot(host)
+ act(() =>
+ root.render(
+ <CardModal
++ projectId="p1"
+ session={{ id: 'n1', title: 'db', color: '#fff', kind: 'sticky', text: '', spawn: {}, icon: value as never }}
+ columnTitle="To Do"
+ board={board}
+ onChangeBoard={vi.fn()}
+ onClose={vi.fn()}
+ onOpenCanvas={vi.fn()}
+ onRename={vi.fn()}
+ onEditSticky={vi.fn()}
+ onSetIcon={vi.fn()}
+ onBrowserNav={vi.fn()}
+ />
+ )
+ )
+ const button = document.body.querySelector<HTMLButtonElement>('.kanban-modal__icon')!
+ const snapshot = button.cloneNode(true) as HTMLButtonElement
+ act(() => root.unmount())
+ return snapshot
+ }
+ for (const bad of [{ type: 'lucide', name: '__proto__' }, { type: 'lucide', name: 'heart' }, { type: 'image', path: '/etc/passwd' }]) {
+ const button = icon(bad)
+ expect(button.title, JSON.stringify(bad)).toBe('Set icon')
+ expect(button.className).toContain('kanban-modal__icon--empty')
+ expect(button.querySelector('svg'), 'the smiley').toBeTruthy()
+ expect(button.querySelector('.node-icon')).toBeNull()
+ }
+ const good = icon({ type: 'lucide', name: 'database' })
+ expect(good.title).toBe('Change icon')
+ expect(good.className).not.toContain('kanban-modal__icon--empty')
+ expect(good.querySelector('.node-icon svg')).toBeTruthy()
+ })
+
it('writes through raw textarea value on sticky note edit (including whitespace and newlines)', () => {
const session: KanbanSession = {
id: 'node-sticky-1',
diff --cc src/renderer/components/kanban/CardModal.tsx
index faf9ed233,0d72b5a13..e436c6bd7
--- a/src/renderer/components/kanban/CardModal.tsx
+++ b/src/renderer/components/kanban/CardModal.tsx
@@@ -20,12 -19,10 +20,14 @@@ import { normalizeNodeIcon, type NodeIc
import { ContextMeter } from '../ContextMeter'
import { isRemoteSessionNode } from '@shared/worktree'
import { AccountChip, useAccountChip } from '../AccountChip'
+import { LiveLinkChip, projectSessionSource } from '../LiveLinkChip'
+import { useWatchLinks } from '../../state/watchLinks'
+import { liveLinkUnavailable } from '../../lib/liveLinkEntry'
+import { isBrowserRuntime } from '@renderer/bridge/runtime'
import { IssueRefChip } from '../IssueRefChip'
import { TeamProgressChip } from '../TeamProgressChip'
+ import { PortsChip } from '../PortsChip'
+ import { useProjects } from '../../state/projects'
import type { TeamStation } from '../../lib/teamProgress'
import { sessionNameRepeatsTitle } from '../../lib/cardRedundancy'
import type { IssueRef } from '@shared/github-issue-ref'
@@@ -110,19 -105,11 +115,22 @@@ interface CardModalProps
* canvas under it) stay mounted. Terminal cards carry the node header's actions too:
* search / dictate / AI-name / the ⌘M view — ChatPanel or the output markdown, the same face the
* canvas node shows (the node itself is hidden under the board). */
- export function CardModal({ session, projectId, columnTitle, board, onChangeBoard, onClose, onOpenCanvas, onRename, onEditSticky, onBrowserNav, onSetIcon, onOpenIssue, mentionables, team, onTravel }: CardModalProps) {
-export function CardModal({ session, columnTitle, board, onChangeBoard, onClose, portsProjectId, onOpenCanvas, onRename, onEditSticky, onBrowserNav, onSetIcon, onOpenIssue, mentionables, team, onTravel }: CardModalProps) {
++export function CardModal({ session, projectId, columnTitle, board, onChangeBoard, onClose, portsProjectId, onOpenCanvas, onRename, onEditSticky, onBrowserNav, onSetIcon, onOpenIssue, mentionables, team, onTravel }: CardModalProps) {
const { api } = useSession()
+ // The header slot decides "icon or smiley" on the NORMALIZED value, the answer NodeIconView
+ // itself gives — on the raw one, an invalid stored icon drew an empty, un-muted slot.
+ const sessionIcon = normalizeNodeIcon(session.icon)
+ // Which machine this node runs on, for the live-link chip and action (R57, H4).
+ const liveLinkSource = projectSessionSource(projectId)
+ const activeLiveLinks = useWatchLinks((s) => s.links.length)
+ // The ONE availability rule every opener checks before the Pro gate. The modal paints ABOVE the
+ // canvas's notice strip, so the reason goes on the button (disabled + title) rather than into a
+ // notice nobody could see.
+ const liveLinkWhy = liveLinkUnavailable({
+ serverEdition: isBrowserRuntime(),
+ source: liveLinkSource,
+ activeLinks: activeLiveLinks
+ })
const idRef = useRef<string>()
if (!idRef.current) idRef.current = nextDialogId()
const id = idRef.current
diff --cc src/shared/session-backend.ts
index 000000000,6cc78b03a..2044e791e
mode 000000,100644..100644
--- a/src/shared/session-backend.ts
+++ b/src/shared/session-backend.ts
@@@ -1,0 -1,38 +1,39 @@@
+ /**
+ * Which multiplexer holds a LOCAL terminal's persistent session on POSIX (issue: Zellij as a
+ * session backend). tmux is the default and stays the default; `zellij` is opt-in per machine.
+ *
+ * settings.json is hand-editable, so every reader goes through `normalizeSessionBackend`: an
+ * unknown value — a typo, a future backend this build does not know, a non-string — reads as
+ * `tmux`, never as "no persistence". The setting only decides where a NEW session is created: a
+ * node whose session already lives in one backend keeps reattaching there (see pty-manager.ts,
+ * "the backend follows the session that exists").
+ *
+ * Windows keeps the session host whatever this says; SSH projects keep the remote tmux.
+ */
+ export type SessionBackend = 'tmux' | 'zellij'
+
+ export const SESSION_BACKENDS: readonly SessionBackend[] = ['tmux', 'zellij']
+
+ export const DEFAULT_SESSION_BACKEND: SessionBackend = 'tmux'
+
+ export function normalizeSessionBackend(value: unknown): SessionBackend {
+ return value === 'zellij' ? 'zellij' : 'tmux'
+ }
+
+ /**
+ * What a Zellij-backed terminal does NOT get, named so the Settings row can say it out loud.
+ * Every entry is a capability whose tmux leg has no Zellij equivalent this build uses; each one
+ * degrades to "unknown" / "refused" rather than to a guess (docs/session-backends.md has the
+ * measurement behind every line). Kept in @shared so the list the UI prints is the list the
+ * docs test pins.
+ */
+ export const ZELLIJ_BACKEND_GAPS: readonly string[] = [
+ 'Agent-to-agent messaging and triggers into Zellij sessions are refused (no pane-owner or paste-mode probe).',
+ 'Model switch refuses: it cannot stop the foreground process of a Zellij pane.',
+ 'The session-memory panel counts Zellij sessions but does not measure them; the idle-session reaper does not see them.',
+ 'Pasted text reaches Zellij as a command-line argument (readable by other local users while the call runs); pastes over 120 KB are refused.',
+ 'The stale-folder banner and the live pane folder for file links are unavailable.',
++ 'A live link to a Zellij node gets no screen snapshot (viewers start from the live stream), and can be watched only while its terminal is attached in this app.',
+ 'SSH projects and Windows keep tmux / the session host.',
+ 'nodeterm mobile’s direct SSH attach only finds tmux sessions.'
+ ]