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 branch 'main' into feat/team-presence

enes5e85f22733da
diff --cc docs/team-presence.md
index f77f6b017,000000000..2ab9c91f4
mode 100644,000000..100644
--- a/docs/team-presence.md
+++ b/docs/team-presence.md
@@@ -1,897 -1,0 +1,917 @@@
+# Team presence — design
+
+**Date:** 2026-07-12
+**Status:** **Stage 1, Stage 2 and Stage 3 landed.**
+**Stage 1** — the `PresenceHub` (`src/core/presence/hub.ts`), both shells joining it (Server Edition
+browsers, the Electron window, cursorless relay phones), a real `window.nodeTerminal.presence` on
+**both** surfaces, and the three UI surfaces: project-scoped live cursors + cursor chat
+(`PresenceLayer`), the `Facepile` (off-project peers included), and per-node focused-avatar chips.
+**Stage 2** — terminal co-attach (the [Terminal co-attach](#terminal-co-attach) section): one pty,
+N subscribers; idempotent `pty:create`; smallest-subscriber-wins sizing; per-client backpressure with
+an 8 MB drop-and-redraw ceiling; typing attribution; and the delete/recycle split.
+**Stage 3** — canvas mutation sync (the [Canvas sync](#canvas-sync) section): a `canvas:mut` reflector
+that stamps one total order (`seq`) and fans each mutation to every client, a diff-based publisher
+with an `adopt()` loop guard and a solo gate, per-node last-write-wins in that order
+(`canvas-order.ts`) so concurrent edits **converge** instead of splitting the canvas in two, an
+in-place apply into the live React Flow array, a real `window.nodeTerminal.canvas` on both surfaces,
+and per-project apply (including into a loaded-but-inactive project's serialized nodes). What it
+resolves and what it does not:
+[Concurrent-edit resolution](#concurrent-edit-resolution-what-converges-and-what-does-not).
+Deltas between this document and what actually shipped are recorded in
+[What Stage 1 changed](#what-stage-1-changed-relative-to-this-spec),
+[What Stage 2 changed](#what-stage-2-changed-relative-to-this-spec) and
+[What Stage 3 changed](#what-stage-3-changed-relative-to-this-spec).
+**Scope:** live cursors with names, ephemeral cursor chat, per-node "who is active here",
+and the terminal co-attach that makes those indicators mean something.
+
+## Goal
+
+Turn nodeterm from a single-operator canvas into one a small team (~5–10 people) can inhabit
+at the same time: you see where your teammates' cursors are, you can say something quickly
+without leaving the canvas, and you can see who is sitting in — and typing into — a given
+terminal. Two people can look at the same terminal at the same time.
+
+This is deliberately a *presence* feature, not a permissions feature. Identity is weak,
+there is no locking, and there are no roles. See Non-goals.
+
+## Constraints discovered in the codebase
+
+Three facts shaped every decision below:
+
+1. **There is no notion of a user anywhere.** Server Edition auth is a single shared
+ password (scrypt) with anonymous session tokens (`src/server/auth.ts`); the license layer
+ identifies a *device*, not a human (`src/core/license.ts`). Identity is invented from scratch.
+2. **Multi-client transport already exists.** `ServerPlatform.sinks` is a real client registry
+ (`src/server/platform-server.ts:104`) and `broadcast()` (`:96`) already fans out
+ `agent:status` and friends to every connected client. Presence needs no new transport.
+3. **Terminals are not shareable today.** PTY output is unicast to the creating client
+ (`Session.webContentsId`, `src/core/pty-manager.ts:251`, flushed at `:780`), and a second
+ client attaching to the same node runs `tmux -A -D` (`:668`) — the `-D` *detaches the other
+ client*. Two browsers on one node fight, and output follows whoever attached last.
+
+## Architecture
+
+### PresenceHub lives in core, not in a shell
+
+New `src/core/presence/hub.ts`: a pure `PresenceHub` holding `Map<clientId, PeerState>`,
+applying events and emitting diffs. No electron, no `ws`, no disk. **Presence is never
+persisted** — it is as transient as the live half of `agentStatus`.
+
+Both shells feed the same hub through the same interface:
+
+- **Server Edition** — `ServerPlatform.attach()/detach()` (`platform-server.ts:104`) is already
+ the client registry; `hub.join(uiId)` / `hub.leave(uiId)` hook in there, and fan-out uses the
+ existing `broadcast()`.
+- **Relay / desktop host** — a `HostSession` connecting calls the same `hub.join()`.
+ `host-canvas-hub` already mirrors canvas state to N clients via its `subs` set; presence
+ rides the same path.
+
+One hub, two adapters — not two implementations.
+
+### Identity: lightweight, unverified, deliberate
+
+Auth is untouched (one shared password stays). On first connect the browser asks for a name;
+`{name, color}` is kept in `localStorage` under `nodeterm.presence.me`, with a color
+auto-assigned from a palette and user-changeable. The client announces itself with
+`presence:hello {name, color}`; the server assigns a `clientId` (the existing `uiId`).
+
+The server does not verify names. Anyone can claim to be anyone. This is sufficient for "who
+is typing in this shell" and insufficient for audit or permissions — an accepted, documented
+trade-off. Two tabs from one person show as two peers (as in Figma).
+
+### Presence is scoped to a project
+
+A project *is* a canvas, with its own node set and its own flow coordinate space. A peer's
+cursor, chat bubble and node chips are therefore rendered **only for peers on the same
+project** (`PeerState.projectId`, filtered through the single pure selector
+`peersOnProject(peers, projectId)`). Without that filter, a teammate looking at project "api"
+while you look at "web" would have their cursor drawn on your canvas at meaningless
+coordinates.
+
+The facepile deliberately does *not* filter: off-project peers appear dimmed, labelled with the
+project they are in, and clicking one switches you to that project and centers on their focused
+node. What would have been a bug becomes the "who is working where" view.
+
+### Peers may have no cursor
+
+`PeerState = { clientId, name, color, cursor: {x,y} | null, focus: nodeId | null, chat: string | null }`
+
+**`cursor`, `focus` and `chat` are three independent signals**, and a cursorless peer is a
+first-class citizen — not a peer with a fabricated position. The mobile companion has no
+mouse; modelling presence as "everyone has an x/y" would have forced it to either invent a
+cursor or vanish. Every UI surface degrades per signal.
+
+### Wire protocol
+
+New `presence:*` channels in `src/shared/ipc.ts`. The server is a dumb reflector: it holds the
+peer table and fans out, and applies no policy.
+
+| Direction | Channel | Payload |
+|---|---|---|
+| client→server (`cast`) | `presence:hello` | `{name, color}` |
+| client→server | `presence:cursor` | `{x, y}` — **flow coordinates**, sampled on rAF, throttled to ~20 Hz |
+| client→server | `presence:focus` | `{nodeId \| null}` |
+| client→server | `presence:chat` | `{text \| null}` — live per-keystroke; `null` closes |
+| client→server | `presence:project` | `{projectId \| null}` — which canvas we are looking at |
+| server→clients (`ev`) | `presence:sync` | full snapshot on join |
+| server→clients | `presence:peer` | single-peer diff (join / update / leave) |
+
+Cursors travel in **flow coordinates** (`screenToFlowPosition`), never screen coordinates, so a
+cursor lands on the correct node regardless of each viewer's zoom and pan. A `presence:project`
+also **clears the cursor**: it belonged to the old canvas, and a keyboard-driven project switch
+sends no new sample.
+
+"Dumb reflector" is about *policy*, not about trust: everything the hub takes from one client it
+fans out to all of them, so the ingest side is hardened. Every string off the wire goes through the
+one truncation rule (`capCodePoints`: chat 200, name 32 — control/bidi characters stripped —
+focus/project ids 128 code points), and every cast is rate-limited per (client, channel) by a token
+bucket (`PRESENCE_RATE_BUDGETS`; the cursor budget is exactly the renderer's own 20 Hz, so an honest
+client never loses a sample — excess is dropped silently, never disconnected). The Server Edition
+socket additionally caps a single frame at `WS_MAX_PAYLOAD` (8 MiB), well above the largest
+legitimate one (an `fs:write` of an editor file).
+
+## Terminal co-attach
+
+The enabling change: two people must be able to watch one terminal.
+
+**One PTY, N subscribers** — *not* "drop tmux's `-D`". When a second client calls `pty.create`
+with a live `persistKey`, we do not spawn a second tmux client; we subscribe it to the existing
+`Session`. The app therefore still has exactly one tmux client per session, `-D` stays as it is,
+and tmux's multi-client size negotiation never engages. The relay path already does exactly this
+(`attachDetached`, `src/core/pty-manager.ts:485`) — we generalize that mechanism rather than
+inventing a second one.
+
+Changes:
+
+1. **`Session.webContentsId: number | null` → `subscribers: Set<ClientId>`**
+ (`pty-manager.ts:251`). `flush()` (`:780`) fans out to the subscriber set instead of
+ unicasting. The relay's `onData`/`onExit` sinks are **not** in that set (they have no
+ `ClientId`): a detached, relay-served pty keeps its own session and is deliberately left out of
+ `subscribers` *and* out of the `byPersistKey` co-attach index, so the relay path is bit-for-bit
+ what it was. `flush()` calls the sink and then fans out to the subscribers — two paths, kept
+ apart on purpose.
+2. **`pty:create` becomes idempotent.** A live session for that `persistKey` means subscribe +
+ return `fresh:false` rather than spawn. Cold-restore and scrollback replay already branch on
+ `fresh`, so they keep working.
+3. **Size: smallest subscriber wins.** Two browsers at different zoom/DPI compute different
+ cols/rows and would corrupt each other's rendering — the classic shared-terminal problem.
+ PtyManager tracks each subscriber's requested size, sets the effective size to
+ **min(cols) × min(rows)**, and broadcasts the authoritative size on `pty:size:<sessionId>`.
+ Each xterm calls `term.resize()` from that broadcast instead of from its own `fit()`, and
+ letterboxes the remainder. With one subscriber, `min` of one element is your own size — the
+ **single-user path stays bit-for-bit identical to today**.
+4. **Backpressure becomes per-client.** Today `paused` is keyed by session
+ (`platform-server.ts:39`) and `detach()` clears the *entire* map on any disconnect — a bug
+ already confessed in a "v1 is single-UI" comment (`:110`). Left alone, one slow phone would
+ stall everyone's output. Rekey to `(clientId, sessionId)`; detach clears only that client's
+ entries. The shared PTY is paused only when *every* client of that session is over
+ high-water, so the slowest link no longer sets the pace for the team.
+
+ That alone would let a slow client's send buffer grow without bound, so it is capped:
+ at `WS_DROP_WATER` (8 MB buffered on one client's socket) we **drop that client's
+ queued output** rather than pause the others, and when its buffer drains we **resynchronise
+ it by redrawing the current screen from tmux** (reusing the existing `capture-pane` path)
+ with a "reconnected — earlier output skipped" separator. For a terminal the current screen
+ is what matters, not the 8 MB of scrollback a bad link missed; tmux is the authoritative
+ source of that screen.
+
+ Three properties of that ceiling, stated honestly:
+ - **The bound is per SOCKET, not per session.** `bufferedAmount` is `ws.bufferedAmount` — one
+ number for the whole connection, which is where the bytes actually sit. So a client that
+ floods past the ceiling on one session desyncs on *every* session it is watching (each on its
+ next chunk). Other **viewers** of those sessions are untouched — they have their own sockets.
+ - **Recovery is per `(client, session)`:** the desync state is keyed that way, so each session
+ gets its own capture and its own redraw.
+ - **The drain is the trigger, not the next chunk.** The common case is a flood that *ends*
+ (`npm run build` finishes; the socket drains; no further output ever arrives). A redraw hung
+ off the next chunk would never fire, leaving the user on a screen truncated mid-flood. A
+ 250 ms sweep — armed on desync, cleared when the desynced set empties, so the healthy path
+ pays nothing — watches the socket and redraws once it is back under the low-water mark.
+ - **An empty capture is never sent.** `captureForResync` returns `''` on any tmux/ssh failure,
+ and the renderer's resync handler resets the terminal; sending `''` would blank a live
+ terminal. An empty/failed capture keeps the client desynced and is retried with backoff
+ (250 ms → 10 s cap). `pty:resync` payloads are therefore guaranteed non-empty.
+
+### Painting the joiner
+
+A joining client gets `fresh:false`, which is what tells the renderer *not* to replay the persisted
+scrollback (tmux is live; a replay would duplicate it). But co-attach adds **no tmux client** — the
+session already has one — so nothing redraws for the joiner either, *unless* the join happens to
+resize the pty: tmux repaints on SIGWINCH, and only a joiner strictly **smaller** than the current
+grid causes one. **Equal is the expected case** (both clients render the node's persisted geometry
+with the same font; canvas zoom is a CSS transform and does not change `clientWidth`), and equal or
+larger resizes nothing. Left alone, the headline path of the feature — open the same terminal in a
+second client — lands on a **blank but live** terminal until the next byte of output, nondeterministically
+(a ±1-cell measurement difference between two machines silently hides the bug).
+
+So a join that did **not** resize the pty carries the session's **current screen** on
+`PtyCreateResult.screen`, captured with the same `captureForResync` (`tmux capture-pane -e`) the
+drop-and-redraw path uses; the renderer writes it into its empty xterm before the live stream starts.
+Three rules:
+
+- It rides the **create result**, not a `pty:resync` event: the renderer only subscribes to a
+ session's channels *after* `create()` resolves, so an event pushed at join time would land on no
+ listener.
+- A join that **did** resize gets nothing — tmux is already painting it, and two paints would splice
+ two different points in time onto one screen.
+- An **empty capture is omitted**, never sent as `''` (same contract as `pty:resync`). A solo user
+ never reaches this path at all: a fresh spawn has nothing to paint, and a warm reattach starts a
+ tmux client, which redraws by itself.
+
++**Post-merge with `main`'s terminal work: `screen` became the joiner's FALLBACK, not its paint.**
++`main` gave every `fresh:false` attach a `warm-history` seed — it hydrates a fresh xterm from
++`transport.captureHistory` (tmux's own scrollback). A joiner is `fresh:false`, so it now lands on
++that path too, and painting *both* would splice the same screen onto the canvas twice. One source
++wins: **`captureHistory`**, because it is a strict superset of `screen` — the same tmux pane *plus*
++the scrollback above it, so the joiner opens on what its teammate sees **and** can scroll back.
++`PtyCreateResult.screen` remains as the fallback for the one case that path cannot cover:
++`captureHistory` returns `''` whenever tmux/ssh is unavailable, whereas `screen` is captured
++server-side inside `create()` and is guaranteed non-empty when present. So the joiner is painted
++**exactly once**, and never blank.
++
++**A `pty:resync` supersedes the seed, and the queue behind it.** `main`'s attach path subscribes to
++`pty:data` *before* awaiting its seed and holds the chunks in a `createDataGate`. A resync that lands
++during that window is a redraw of the CURRENT screen, so everything the gate is holding *predates*
++it: draining the queue would splice the stale flood back over the fresh screen, and the in-flight
++history seed would then write an even older screen on top of that. The resync handler therefore
++`gate.reset()`s (drops the queue, returning its bytes to the flow-control accounting, and switches to
++pass-through) and marks the seed **superseded**, so the seed writes nothing when its capture returns.
++Everything that arrives after the capture streams straight through, in order.
++
+### Typing attribution — and why it is server-side
+
+`cast()` used to discard the sender (`void uiId`). `pty:write` is routed through the sender-aware
+seam (`onWithSender`) instead, so the handler knows WHO typed: it calls `presenceHub.noteTyping(
+clientId, session.nodeId)` directly — there is no `lastWriter` field on the session, because nothing
+would read one (the badge is peer state, and it lives in the hub's peer table, not on the pty). The
+hub throttles the broadcast to 1/500 ms per (client, node); the badge decays after ~2 s. `write`
+skips the call entirely when there is only one peer, so a solo keystroke burst costs nothing.
+
+A write is only accepted from a **subscriber** of that session (session ids are guessable), and the
+same membership check gates `pty:resize` / `pty:flow` / `pty:kill` — everything in a session's
+`pausedBy` / `sizes` therefore belongs to a client that is actually watching it, which is what makes
+`dropClient` a complete cleanup.
+
+Attribution is done **on the server rather than by client self-declaration** specifically
+because of mobile: when the phone writes over the relay, the sender is already known as a
+`HostSession`. So *typing from the phone lights up the "Enes is typing" badge on someone's
+desktop canvas without a single line of Swift.*
+
+### No locking (v1)
+
+Two people can type into one shell simultaneously; both badges pulse and the characters
+interleave in the single tmux session. This is accepted, not overlooked — it is the behavior
+every tmux pair-programmer already knows, and the badge *is* the warning. Locking / handoff is
+v2.
+
+If a node is deleted while others are attached, `destroy(persistKey)` kills the tmux session and
+the remaining subscribers enter a "closed by <name>" state rather than respawning it.
+
+### Deletion vs recycling
+
+Killing a node's tmux session is used for two opposite intents, and PtyManager keeps them apart:
+
+- **Deletion** (× / delete node) → `destroy(persistKey)`. The node leaves the canvas. Co-viewers get
+ `pty:closed:<sid> { by }` and must never respawn it — a respawn would resurrect a terminal its
+ owner deliberately killed, in a fresh shell, and strand a tmux session.
+- **Recycling** ("move into worktree") → `recycle(persistKey)`. Same `tmux kill-session` (otherwise
+ `new-session -A` would just reattach the old working directory), but the node **stays** on every
+ canvas and keeps working. Co-viewers get `pty:recycled:<sid> { ready }`: restart the terminal,
+ the node moved. Their re-create **co-attaches** to the replacement session, so they follow the node
+ into its new cwd and are never left holding the dead pty.
+
+The recycled notice is **withheld until the replacement session is registered** (`ready:true`). Sent
+any earlier, a co-viewer's restart could beat the mover's own `create()` and spawn `nt-<nodeId>` from
+*its* options — i.e. in the node's stale cwd — silently undoing the move for everyone.
+
+A recycler can die between the `kill-session` and its own `create()` (app quit / crash), so a 10 s
+timeout releases the co-viewers anyway — with **`ready:false`**, which means *do not respawn*. This
+is the one case where restarting is worse than not: a co-viewer's create options still carry the
+node's **old cwd** (a cwd change is not broadcast on this branch), so its spawn would put
+`nt-<nodeId>` back in the stale folder — and when the mover's app returns, its own `new-session -A`
+**reattaches** that session (the cwd option is ignored on attach), so *everyone's* node would claim
+the worktree path while the shell sits in the old directory. Silent, and exactly what the withheld
+notice exists to prevent. So the terminal shows **"session ended — reopen to restart"** instead: the
+move can be lost only by an explicit user click, never by a timeout.
+
+### The respawn guard — and the tombstone that backs it
+
+`pty:closed` only reaches a session's **subscribers**. A co-viewer whose project is *inactive or
+closed* has no mounted terminal, so it is not one — yet the node is still on its canvas. Its next
+`create` for that node (opening the project later) would find no session, fail `tmux has-session`,
+and spawn a brand-new one: the deleted terminal, resurrected as a fresh shell.
+
+`PtyManager.tombstones` closes that: a destroyed `persistKey` is remembered, and a later `create`
+for it by **another** client is refused (`PtyCreateResult.closed = { by }`) instead of spawning —
+the renderer lands in the same "closed by <name>" state. The destroying client is **exempt**, so its
+own ⌘Z (undo of a delete) still restores the node, and the single-user path is untouched. A
+`recycle` clears the tombstone (nothing was deleted).
+
+Its limits are real (see Known risks): the tombstone is in-memory, so it lives exactly as long as
+the core process. Stage 3's canvas-delete **mutation** is the structural fix — it removes the node
+from every *attached* client's canvas, so nobody is left holding one to re-create. It did **not**
+make the tombstone removable: the mutation covers the clients that were attached at the moment of
+the delete, and the paths it does not cover still need the respawn guard. See
+[What Stage 3 changed](#what-stage-3-changed-relative-to-this-spec) for the exact list.
+
+The map is also **bounded in size and time** (`TOMBSTONE_MAX` / `TOMBSTONE_TTL_MS`, an LRU), and the
+`pty:destroy` / `pty:recycle` casts are **length-capped** (`REF_MAX_LEN`, like every other
+client-supplied reference) and **rate-limited** per client (`PTY_END_BUDGET`). They have to be: the
+key comes verbatim off the wire, a tombstone is recorded even when no live session exists, and each
+call costs an `fs.rm` plus a `tmux kill-session` subprocess. The burst is sized well past a bulk
+delete (one cast per node in a single tick), so it can never fail a real user; eviction degrades to
+the pre-tombstone behavior, never to something worse.
+
+## Canvas sync
+
+Node edits broadcast as mutations so cursors don't hover over stale geometry.
+
+The vocabulary already exists — `CanvasMutation = {op:'upsert', node} | {op:'remove', id}`
+(`src/shared/types.ts:119`) — and so does the receiving end: `applyCanvasMutation`
+(`Canvas.tsx:917`), written for the relay. We add only the emitting side: `handleNodesChange`
+publishes a mutation (position-only, throttled to 20 Hz, while dragging; a full upsert on
+settle; an upsert on add / remove / color / title / collapse), and the server reflects it to
+every client except the sender.
+
+Convergence makes persistence safe for free: because all clients converge on the same node set,
+whichever client calls `workspace.save` writes the same bytes, which defuses today's
+last-writer-wins save. The existing rev-based conflict bar (`workspace-watcher`) stays as the
+backstop.
+
+Two things are deliberately **not** synced: ephemeral nodes (subagent / loop cards) are derived
+independently on each client from the already-broadcast `agent:status` stream; and undo stays
+**local per user** — you can in principle undo someone else's change (last-write-wins). No CRDT.
+
+**Implemented (Stage 3).** `CanvasMutation` now travels on `canvas:mut` (`src/shared/ipc.ts`):
+
+- **Publisher** (`src/shared/canvas-publish.ts`) — the renderer diffs each settled node snapshot
+ against the last one it published (`diffToMutations`), so edits that never pass through
+ `onNodesChange` (a rename, a color pick, a collapse, a direct `setNodes`) sync too. Position frames
+ are throttled to ~20 Hz while dragging and flushed on drag-stop; everything else is a full upsert.
+ Ephemeral subagent/loop cards are filtered out (`publishableStates`). Every mutation is stamped
+ with `src`, this Canvas's publisher tag.
+- **Solo gate** — `shouldPublish` (fed by the presence peer table, read through a ref so it can never
+ re-render Canvas). With nobody else attached, `publish()` degrades to `adopt()`: it takes the
+ snapshot as the baseline and does **no** diff, no `stableStringify` of every node, no IPC cast. A
+ solo user pays nothing for team sync, and because the baseline still tracks the canvas, the first
+ edit after a peer joins diffs correctly — no resync step, no missed mutation.
+- **Reflector** (`src/core/canvas-sync.ts`) — holds no canvas state and persists nothing, but it is
+ **not** stateless: it stamps every mutation with a monotone **`seq`** and sends it to **every**
+ attached client, the sender included (`CorePlatform.clientIds()` + `onWithSender`). `seq` is
+ server-authoritative (a client-supplied one is overwritten at ingest).
+- **Ordering** (`src/shared/canvas-order.ts`) — the client half, and the reason concurrent edits
+ converge instead of splitting the canvas in two. Per node, the highest `seq` wins. Three rules: (1)
+ our own echo is an **ack**, not an edit — it carries the `seq` our mutation was given, and is never
+ re-applied (re-applying it would rubber-band a node we are still dragging); (2) while one of our
+ own mutations for a node is unacked, we ignore peers' mutations for that node — FIFO delivery means
+ ours is necessarily *later* in the total order, so it will win on every other client too; (3) rule
+ 1 is only sound **while our optimistic value is still on our canvas**. Rule 2's suppression is
+ bounded by `PENDING_TTL_MS` (an ack can be late — the same socket carries pty output, and Stage 2
+ tolerates an 8 MB backlog on it), and once it lapses a peer's mutation can overwrite the value we
+ are still waiting to have acked. From that moment our echo is the **only** copy of a value that
+ already won on every other client, so it is **applied** (a repair), not dropped. Without rule 3 a
+ late ack left that client permanently on the losing value — and its whole-file `workspace.save`
+ then wrote those losing bytes over everyone else's canvas, which is precisely the property this
+ stage exists to guarantee. The pending entry's `since` is refreshed on every local mutation for
+ that node, so a drag longer than the TTL cannot expire its own suppression mid-drag.
+ `order.reset()` is called whenever our presence clientId changes (i.e. on every (re)connect): if
+ the core restarted, its `seq` restarted at 0 while our `seen` map still held high values, and we
+ would silently drop every new mutation as a straggler. Correctness no longer depends on the
+ ws-bridge's `location.reload()`.
+- **A cast the reflector would refuse is never made** — the publisher validates with the **same**
+ predicate the reflector's ingest uses (`isCanvasMutation`, moved to `src/shared/canvas-mutations.ts`
+ so both ends share one verdict) *before* recording a pending entry and *before* casting. A refusal
+ therefore costs neither a pending entry (which would have deafened that node to its peers for the
+ whole TTL — a peer's `remove` landing in that window was dropped and never recovered, so the next
+ whole-file save resurrected the node they deleted) nor the retry: the refused node keeps its
+ **previous baseline entry**, so the very next publish re-emits it and it syncs the moment it becomes
+ castable. The only thing that can legitimately exceed `MUTATION_MAX_BYTES` is free text — a sticky
+ someone pasted a document into — so Canvas **tells the user** ("This note is too large to share with
+ your teammates (over 250 KB)… they will not see it until you shorten it") instead of leaving them
+ with a note the team silently never receives.
+- **Loop guard** — a mutation applied from a peer is `adopt()`ed into the publisher's baseline before
+ the next diff runs, so it can never be re-published (no A→B→C→A ping-pong).
+- **Apply** — the vocabulary is single-sourced in `src/shared/canvas-mutations.ts` and used by both
+ ends. In the renderer, an incoming mutation is patched into the **live React Flow array**
+ (`applyMutationToFlow`, `src/renderer/state/workspace.ts`) — never round-tripped through the
+ (lossy) serializers, which would wipe your selection, delete your relay-remote nodes and re-render
+ every node component on every peer mutation. `window.nodeTerminal.canvas` is real on the preload
+ **and** the ws-bridge.
+- **Undo is rebased, not clobbered** — a peer's mutation is applied to the undo baseline
+ (`committedRef`) rather than replacing it, so a local edit still inside the 300 ms undo debounce
+ survives a peer's mutation landing on top of it.
+
+## UI
+
+`PresenceLayer` renders inside React Flow's `<ViewportPortal>`, so cursors sit in flow
+coordinates and the CSS transform handles zoom/pan. Peers live in a transient zustand store
+(`src/renderer/state/presence.ts`, never persisted) that **only `PresenceLayer` subscribes to** —
+following the existing `viewportRef` + rAF pattern (`Canvas.tsx:162`). If cursor traffic were to
+re-render `Canvas`, every mouse move would redraw a 4000-line component.
+
+- **Cursor** — arrow in the peer's color with a name label. Incoming positions arrive at 20 Hz
+ and are lerped between frames. Your own cursor is never drawn.
+- **Cursor chat** — `/` opens an input beside your cursor, broadcasts on every keystroke, and
+ fades ~5 s after Enter/Esc. **Gotcha:** `/` must not open chat while you are typing in a
+ terminal — the key only fires when the event target is the canvas pane, not xterm / Monaco /
+ an input, matching the command palette's existing guard.
+- **Facepile** (top right) — who is connected, in their colors. Cursorless peers (phones) appear
+ here with a phone icon, since this is their only surface. Clicking an avatar centers the
+ viewport on that peer's focused node.
+- **Node header** — avatar chips for peers focused on the node, with a pulsing ring while they
+ type. Reuses the `agentStatus` badge machinery (per-node badges from a transient store).
+
+## Surfaces
+
+- **Server Edition** — the primary stage; full feature.
+- **Desktop (Electron)** — presence is silent when alone (≤1 peer draws nothing, zero cost).
+ Acting as a relay host, the desktop shows the full peer list.
+- **Mobile (nodeterm-ios, separate repo)** — a phone joins over the relay as a `HostSession`, so
+ `hub.join()` fires for it today; it appears as a cursorless peer named "Phone" until it sends
+ `presence:hello`. Typing attribution already works for it (see above). **Follow-up task in
+ that repo:** send `presence:hello` + `presence:focus`, and render received cursor chat as a
+ banner (it has no cursor to anchor a bubble to). Mobile does not *send* cursor chat in v1.
+
+## What Stage 1 changed relative to this spec
+
+The sections above are the design as approved. Stage 1 implemented them faithfully with three
+deviations, recorded here so this document does not lie to the next reader:
+
+1. **Presence is scoped to a project, and the facepile deliberately breaks that scope.** The peer
+ table carries `PeerState.projectId`, fed by a `presence:project` channel that was not in the
+ original wire table (it is now, above). Cursors, chat bubbles and node chips are filtered
+ through the single pure selector `peersOnProject(peers, projectId)`; the facepile intentionally
+ does *not* filter, showing off-project peers dimmed and labelled with the project they are in,
+ clickable to travel there. This was designed in as the feature described under
+ [Presence is scoped to a project](#presence-is-scoped-to-a-project) — it is called out again
+ here because it is the one place where "presence is per-canvas" is deliberately violated.
+2. **A WebSocket heartbeat was added.** Not in the original design: a browser tab that *vanished*
+ (killed, laptop slept, network dropped) never triggered a WS `close`, so its peer stayed in the
+ table forever — a permanent ghost cursor. The Server Edition now runs a 30 s ping/pong heartbeat
+ and reaps sockets that miss a pong, so a vanished client leaves within ~60 s. A cleanly closed
+ tab still leaves immediately, on `close`.
+3. ~~**`PeerState.typing` exists but is always `null` in Stage 1.**~~ **Closed in Stage 2.** The
+ sender-aware `pty:write` handler calls `noteTyping()`, and the renderer draws the pulsing ring on
+ the typist's header chip (`src/renderer/lib/typingPeers.ts` + `components/PresenceChips.tsx`).
+ Two rules worth knowing before you touch it: the ring decays against the **local receipt time**,
+ not the host's `typing.at` (a viewer's clock can be minutes off), and it is fed **only** by live
+ `presence:peer` diffs — never by a `presence:sync` snapshot, which can carry a ten-minute-old
+ stamp because the hub never clears `typing`. It is also the one node-scoped signal that is
+ **not** project-filtered: a phone has `projectId: null`, and typing from the phone is exactly
+ what the ring exists to surface (node ids are globally unique, so this is safe).
+
+## What Stage 2 changed relative to this spec
+
+Stage 2 implemented [Terminal co-attach](#terminal-co-attach) as approved — one pty with N
+subscribers, an idempotent `pty:create`, smallest-subscriber-wins sizing, per-client backpressure,
+and server-side typing attribution. Four things are **not** in the spec as originally written and
+were added during implementation; the sections above have been amended to match, and they are
+collected here so the delta is legible.
+
+1. **`pty:recycle` — a separate primitive from delete.** The spec had exactly one way to kill a tmux
+ session (`destroy`), and co-viewers of a destroyed session are told "closed by <name>" and must
+ never respawn it. But **"Move into worktree"** also kills the session (`new-session -A` would
+ otherwise just reattach the *old* working directory) — and there the node is **not** going away:
+ it stays on every canvas and must keep working. Routing a worktree move through `destroy` would
+ have shown every co-viewer a false "closed by …" and bricked their node. So the two intents are
+ now distinct primitives with distinct events — `destroy` → `pty:closed {by}` (do not respawn) and
+ `recycle` → `pty:recycled {ready}` (restart and re-attach; the node moved). See
+ [Deletion vs recycling](#deletion-vs-recycling) for the full contract, including why the recycled
+ notice is **withheld** until the replacement session is registered and why the 10 s escape-hatch
+ timeout sends `ready:false` (= *do not respawn*) rather than letting a co-viewer silently re-spawn
+ the node in its stale cwd.
+
+2. **The tombstone — and its limit, stated plainly.** `pty:closed` only reaches a session's
+ **subscribers**. A co-viewer whose project is closed or inactive has no mounted terminal, so it is
+ not one — yet the node is still on its canvas, and its next `create` would spawn a fresh
+ `nt-<nodeId>`: the deleted terminal, resurrected as an empty shell. `PtyManager.tombstones`
+ refuses that create (`PtyCreateResult.closed = {by}`), exempting the destroying client so its own
+ ⌘Z still works.
+ **The limit is real and is not papered over: the tombstone is in-memory.** It lives exactly as
+ long as the core process. Restart the core — the Server Edition process, or the desktop app
+ hosting the relay — and the tombstones are gone; a client whose canvas still carries the deleted
+ node will spawn a fresh session for it the next time it opens that project. This is deliberately
+ **not** fixed by persisting the tombstone, because persistence is not the missing piece: **the
+ node should not be on that canvas at all.** The actual fix is **Stage 3's canvas-delete
+ mutation**, which removes the node from every client so nobody is left holding one to re-create.
+ Until Stage 3 lands this is a bounded, named gap (also listed under [Known risks](#known-risks)),
+ not a promise.
+
+3. **A parked node reports `null`, not a size.** The spec said the pty runs at
+ `min(cols) × min(rows)` over its subscribers, which is only correct for subscribers that are
+ actually *looking*. A **parked** node (project switched away — the xterm is detached from the DOM
+ but the PTY client is still alive and subscribed) has no meaningful size, and a collapsed or
+ zero-height node measures as `0×0`. Either would clamp everyone else's terminal to nothing. So
+ `transport.resize(sid, cols, rows)` takes `number | null`, and `null` means **"subscribed but not
+ viewing"**: the subscriber is *absent* from the size map and is excluded from the min entirely
+ (`reportedSize` in `src/renderer/terminal/terminal-config.ts`; `effectiveSize` in
+ `src/core/pty-size.ts`). Parking a node therefore stops it constraining the shared grid, and
+ un-parking makes it constrain again.
+
+4. **Drop-and-redraw is a two-sided contract.** The 8 MB `WS_DROP_WATER` ceiling drops a slow
+ client's queued output and resynchronises it by redrawing the current screen from tmux — never by
+ replaying the backlog. Two rules, one per side, and **both** are enforced:
+ - **Sender:** an **empty capture is never sent.** `captureForResync` returns `''` on any tmux/ssh
+ failure, and `pty:resync` payloads are guaranteed non-empty (`ServerPlatform.resync`); an empty
+ capture keeps the client desynced and is retried with backoff (250 ms → 10 s cap).
+ - **Receiver:** the renderer **must ignore an empty payload anyway** (`shouldApplyResync`). The
+ resync handler `term.reset()`s before repainting, so acting on `''` would blank a live terminal
+ and leave only the separator. The two guards are redundant on purpose: a wrongly cleared screen
+ is unrecoverable, a skipped repaint is not.
+
+## What Stage 3 changed relative to this spec
+
+Stage 3 implemented [Canvas sync](#canvas-sync) as approved — a publisher, a reflector, echo
+suppression, no CRDT, undo local per user. Five things differ from the spec as originally written, or
+were decided during implementation; the sections above are amended to match, and they are collected
+here so the delta is legible.
+
+1. **The publisher diffs SNAPSHOTS, not React Flow change-lists.** The spec said "`handleNodesChange`
+ publishes a mutation". That would have synced only the edits that flow through `onNodesChange` —
+ drags, selections, resizes. A rename, a color pick, a collapse, an add and a delete all reach the
+ nodes array through direct `setNodes(...)` calls that never touch it, so half the edits would have
+ silently failed to sync. The publisher instead diffs the serialized snapshot against the last one
+ it published (`src/shared/canvas-publish.ts`), which catches every edit whatever path produced it.
+
+2. **The reflector is deliberately NOT rate-limited** (`src/core/canvas-sync.ts`). Every other client
+ cast in this feature is bucketed (presence: `PRESENCE_RATE_BUDGETS`; session-ending pty casts:
+ `PTY_END_BUDGET`). A mutation is different in kind. A presence cast is a **sampled** signal whose
+ loss is self-correcting — the next cursor frame carries the current position. A mutation is an
+ **edge**: nothing supersedes it and nothing re-announces it, so a dropped mutation is *lost state*
+ — a node that never appears on a peer's canvas, or a delete that never lands and then gets written
+ back to disk by that peer's next whole-file save, which is the exact bug this stage exists to kill.
+ Legitimate traffic is also burstier than any bucket sized for it would survive: a drag emits at
+ 20 Hz and a bulk delete emits N mutations in one tick. What **is** bounded is the *payload*:
+ `isCanvasMutation` refuses a malformed or oversized cast at ingest (`MUTATION_MAX_BYTES` = 256 KB,
+ ids capped at `REF_MAX_LEN`), so a hostile cast cannot amplify into every peer's socket or wedge a
+ peer's React Flow. If a budget is ever added here it must **queue**, never drop.
+
+3. **Mutations are project-scoped, and a mutation for a loaded-but-INACTIVE project is applied, not
+ dropped.** Each cast carries a `projectId` (React Flow only ever holds the *active* project's
+ nodes). Dropping a mutation for a project the client is not looking at would have been the
+ data-loss bug in a new costume: that project's nodes still sit in the `projects` store, and the
+ next whole-file `workspace.save` from that client would resurrect a node a peer had deleted. So
+ `Canvas` applies a peer's mutation for a non-active project straight into that project's
+ **serialized** nodes (`useProjects.applyNodeMutation`, `src/renderer/state/projects.ts`) and marks
+ the workspace dirty. An unknown project id is a no-op (nothing to apply). Clients therefore
+ converge **per project**, and the workspace rev-conflict bar stays as the cross-project backstop.
+
+4. **The tombstone stays. It could not honestly be removed.** Stage 2 said the tombstone
+ (`PtyManager.tombstones`, `src/core/pty-manager.ts`) was a stopgap and that Stage 3's canvas-delete
+ mutation was its real replacement. Stage 3 makes it *mostly* redundant — an attached client's
+ canvas loses the node the moment a peer deletes it, so it never asks to `create` it again — but
+ two live paths still reach `create` for a deleted node, and both would spawn a fresh `nt-<id>`
+ (the terminal its owner deliberately killed, as an empty shell) if the tombstone were deleted:
+ - **Project-level operations are not in the mutation vocabulary.** `CanvasMutation` addresses
+ *nodes*. `deleteProject` (`src/renderer/canvas/Canvas.tsx`, the `×` on a "Recently closed"
+ entry) ends every terminal's tmux session via `transport.destroy(nodeId)` and publishes
+ **nothing** — the project itself, with all of its nodes, is still in every peer's `projects`
+ store. A peer that reopens it from *its* "Recently closed" list mounts those nodes and creates
+ their ptys. Only the tombstone refuses that.
+ - **Delivery is best-effort with no catch-up.** The reflector casts to the clients attached *at
+ that instant*; there is no join snapshot and no replay. A client whose socket was down when the
+ delete landed never sees it. In the Server Edition the ws-bridge full-page-reloads on reconnect
+ (so it re-reads the workspace from disk and self-heals) — but only once the deleting client's
+ **debounced** save has flushed; inside that window the client is holding a node the file no
+ longer has.
+ Removing the tombstone would trade a bounded in-memory LRU for a resurrected terminal on those two
+ paths, so it stays. It is unchanged by this stage: still in-memory, still an LRU
+ (`TOMBSTONE_MAX` / `TOMBSTONE_TTL_MS`), still exempting the destroyer so their own ⌘Z works.
+
+5. **What canvas sync does NOT cover** (all deliberate; none of it is fixed by this stage):
+ - **Edges are NOT in the mutation vocabulary** — only nodes are, and edges (`edges`, `bridges`,
+ `ropes`) ride the same whole-file `workspace.save`, which is last-write-wins. So this is worse
+ than a cosmetic gap: an edge you draw does not appear on your peer's canvas, **and their next
+ save — of a canvas that never had it — DELETES it**, because their file write is authoritative
+ for the whole project. (Same in reverse: their edge dies on your save.) A peer's node delete
+ also leaves a **dangling edge** on your canvas until the next save/load drops it. Edge sync is
+ the obvious next slice of this stage; until then, draw links when you are alone on the canvas.
+ - **A peer's node removal unmounts the node and disposes its terminal co-state**
+ (`disposeTerminalOnUnmount` — the module-level xterm/park/co-attach state), but it does **not**
+ run the rest of the local delete path (`useAgentStatus.remove`, chat-driver dispose). The
+ session itself is already dead (the *deleting* client's `transport.destroy` killed it), so
+ nothing leaks server-side; what remains on the peer is a stale `agentStatus` entry for a node id
+ that no longer exists. Disposing the co-state matters because the delete is undoable: if the
+ owner hits ⌘Z, the node comes back **alive**, and a peer that had kept the stale co-state would
+ be looking at a node stuck in "closed by another user" whose only obvious cure (clicking `×`)
+ would kill the owner's live session for real.
+ - **Project lifecycle** (create / rename / close / delete / folder change) is **not** synced.
+ - **Viewport, selection and undo** are not synced. Undo is local per user, by design.
+ - **No conflict resolution beyond per-node last-write-wins.** See
+ [Concurrent-edit resolution](#concurrent-edit-resolution-what-converges-and-what-does-not).
+ No CRDT.
+
+## Concurrent-edit resolution: what converges, and what does not
+
+**Converges — guaranteed, on any interleaving.** Every client ends with the same **node set** and
+the same **value** for every node, because every mutation is ordered by the reflector's `seq` and the
+highest `seq` per node wins everywhere (`src/shared/canvas-order.ts`). This is the property
+persistence depends on: whichever client's whole-file `workspace.save` runs, it writes a canvas the
+others agree with. Proven end-to-end against an **asynchronous** bus (queued casts + FIFO deliveries,
+edits genuinely in flight) in `src/core/canvas-sync.convergence.test.ts`.
+
+That guarantee does **not** rest on any timeout. The pending TTL is a bound on how long we *suppress*
+peers, never on correctness: an ack that arrives after it **repairs** the node (rule 3 above), and a
+cast the reflector would refuse is never made in the first place (the publisher shares the reflector's
+predicate, records no pending entry, and keeps retrying the node until it is castable). Both cases are
+in the convergence suite — a client whose socket is stalled past the TTL, and an oversized sticky cast
+concurrently with a peer's delete.
+
+**Does NOT converge — named, not hidden:**
+
+- **Array order after a resurrection.** If a delete *loses* the order race, the client that issued it
+ removed the node and then re-appended it, so it can sit in a different **slot** in the array than
+ on a client that never removed it. Node set, positions, sizes and data all agree; only the array
+ order (which drives the sidebar listing) can differ, and the next load normalizes it.
+- **Intent, on a contended node.** Two people dragging the same node fight: the node lands wherever
+ the last-ordered frame put it. Two people typing a title get one title. That is last-write-wins,
+ not a merge — by design (no CRDT).
+- **A delete that loses to a concurrent edit — and the node comes back with a DEAD TERMINAL.** If A
+ deletes a node while B is mid-drag, and B's next frame is ordered after A's remove, the node
+ **survives on both canvases** — the last write wins, and it happened to be an upsert. But A's
+ `transport.destroy` had already run `tmux kill-session`, and nothing resurrects a killed session:
+ the node that comes back is a **shell around a dead terminal**. Its scrollback and its running
+ process are gone; the next time it is opened, `pty.create` starts a **fresh** session under the same
+ `nt-<nodeId>` (a cold start: scrollback replay finds nothing, an agent node re-launches its CLI).
+ The canvas is *consistent* everywhere (no split-brain save, which was the whole point) — the node
+ content is not. Deleting a node someone else is actively dragging is a race between two humans;
+ nodeterm resolves the canvas, it cannot un-kill a process. A "delete always wins" tiebreak would
+ trade this for the opposite hazard (a stale drag frame from a disconnected peer erasing a node that
+ was legitimately re-created), so v1 leaves the total order in charge and names the wart here.
+- **Anything outside the node vocabulary** — edges, project lifecycle (see item 5 above).
+
+## Non-goals (v1)
+
+Roles/permissions, follow/spotlight mode, persistent chat history, comment threads, write
+locking, CRDT, character-level cursors inside editor/diff nodes (node-level focus only),
+read-only guests, per-user settings.
+
+## Testing
+
+- `PresenceHub` pure unit tests: join / leave / diff, cursorless peer.
+- Server e2e with **two** WS clients: hello → snapshot, cursor fan-out, echo suppression, leave
+ on disconnect.
+- **Co-attach** (delivered): two clients, one `persistKey` → a single spawn; both receive output;
+ min-size resize; the joiner is painted from the current screen when the join did not resize the
+ pty (and is NOT painted when it did); only a subscriber may write/resize/pause/kill a session, and
+ nothing it owed outlives it; the destroy path is capped, bounded and rate-limited; one client's
+ backpressure does not stall the other; a client that falls 8 MB behind is dropped and redrawn from
+ tmux rather than buffered forever; and a pause is released by the drain sweep even when no further
+ output ever arrives. → `src/core/pty-coattach.test.ts` (60 tests), `src/core/pty-size.test.ts`,
+ `src/server/backpressure.test.ts`, `src/server/platform-server.test.ts`
+- **Typing attribution** (delivered): the sender-aware `pty:write` stamps the writer; the ring decays
+ against local receipt time and is fed only by live diffs. → `src/core/pty-typing.test.ts`,
+ `src/renderer/lib/typingPeers.test.ts`
+- **Renderer co-attach logic** (delivered): reported-vs-effective size, letterboxing, resync-empty
+ guard, recycle action, "closed by" label. → `src/renderer/terminal/terminal-config.test.ts`
+- **Registration guard** (delivered): `pty:write` must stay routed through the *sender-aware* seam —
+ the test fails if a merge resurrects the old sender-less `platform().on(IPC.ptyWrite, …)` beside
+ it. → `src/core/pty-manager-platform.test.ts`
+- **Single-client regression** (delivered): min-size equals your own size and the spawn path is
+ unchanged. → `src/core/pty-single-user.test.ts` (17 tests)
+- **Canvas sync** (delivered): the reflector stamps the total order (`seq`, monotone across senders
+ and projects, never trusted from the client) and fans a mutation to every client *including* the
+ sender, refuses a malformed/oversized cast, and registers exactly once per platform; the publisher
+ diffs snapshots, stamps `src`, throttles drag frames, flushes on settle, `adopt()`s without
+ emitting, and — while solo — emits and diffs **nothing** while still keeping its baseline current.
+ → `src/core/canvas-sync.test.ts`, `src/shared/canvas-publish.test.ts`,
+ `src/shared/canvas-mutations.test.ts`
+- **Ordering** (delivered): an own echo is an ack and is never re-applied; a peer's edit loses to an
+ unacked local edit of the same node (per node, counted per in-flight frame); a superseded straggler
+ is dropped; an ack that never comes expires; a **late** ack repairs a node a peer overwrote after
+ the TTL lapsed (and one that lost the total order is still just an ack); a fresh local edit re-arms
+ the node; a continuous drag keeps its own suppression alive past the TTL.
+ → `src/shared/canvas-order.test.ts` (15 tests)
+- **Canvas convergence** (delivered): two clients running the **real** publisher and **real** ordering
+ against the **real** reflector, over an **ASYNCHRONOUS** bus (casts and deliveries queued, FIFO per
+ link — so several edits are genuinely in flight and the test chooses the interleaving). *The
+ earlier synchronous bus could not express concurrency at all, and therefore "passed" a design that
+ diverged permanently on the first concurrent drag.* Covered: a concurrent move of the same node
+ converges on the ordered winner (both orderings); a concurrent delete-vs-drag converges (both ways
+ round) — no split-brain save; 20 frames of two clients dragging one node converge; three clients
+ editing one node converge; every interleaving × every settle point of a six-edit set converges; a
+ peer's mutation is applied once and **re-published never** (one cast per local edit, no
+ counter-cast, even for a bulk delete across three clients); ephemeral cards never go on the wire; a
+ late joiner converges; a peer's delete is not resurrected by the surviving client's next save; a
+ client whose **inbox is stalled past the TTL** (a backed-up socket) is repaired by its own late ack
+ instead of being left on the losing value; and an **oversized** node the reflector would refuse
+ neither deafens that node to a peer's concurrent delete nor is silently lost (it is retried, and
+ syncs once trimmed). → `src/core/canvas-sync.convergence.test.ts` (18 tests)
+- **Applying a peer's mutation** (delivered): patches the live React Flow array — keeps your
+ selection, keeps relay-remote nodes, keeps local-only node data, keeps every untouched node's
+ object identity, drops the stale `measured` size so a peer's resize is not fought back, and keeps
+ group parents before their children. → `src/renderer/state/workspace.mutation.test.ts` (10 tests)
+
+### Manual smoke test (Stage 1)
+
+Presence needs two clients, which no unit test gives you. The cheapest two-client rig is the Server
+Edition in two browser tabs (see docs/SERVER.md):
+
+```bash
+npm run server:dev # then open the printed URL in TWO browser windows
+```
+
+Use one **normal** window and one **private** window (or two profiles): a second tab in the *same*
+profile shares `localStorage`, so it would not re-prompt for a name and both peers would carry the
+same identity. Call them **A** and **B**; log both in with the shared password.
+
+1. **Name prompt, once.** B prompts for a name on first connect. Enter one. It does **not** prompt
+ again on reload (it is remembered in `localStorage` under `nodeterm.presence.me`). Do the same in
+ A with a different name.
+2. **Names propagate.** Each tab shows the other's avatar in the facepile (top right) in its color,
+ with the name entered in step 1 — not "Someone".
+3. **Cursors, in flow coordinates.** Move the mouse over A's canvas: B draws A's cursor with a name
+ label, tracking it. Now **zoom and pan B** (trackpad pinch / two-finger scroll). A's cursor stays
+ pinned to the same *canvas* point — the same node, the same corner of it — at every zoom level.
+ Neither tab ever draws its own cursor.
+4. **Cursor chat opens on `/`.** With the pointer over A's empty canvas, press `/`. An input opens
+ beside A's cursor; type — the text streams into A's bubble in B *per keystroke*. Enter leaves the
+ bubble up and it fades after ~5 s; Escape clears it at once.
+5. **`/` inside a terminal does NOT open cursor chat.** (The most important negative case.) In A,
+ hover into a terminal node until the hover guard releases and the terminal takes focus, then type
+ `/`. The `/` must reach the **shell** — it appears at the prompt — and **no chat input opens**.
+ Repeat inside an editor node (Monaco) and inside the rename box in a node header: same result.
+6. **Node focus chips.** While A is focused in that terminal, B shows A's avatar chip in **that
+ node's header**. Click A onto a different node → the chip moves. Click A onto empty canvas → the
+ chip disappears.
+7. **Off-project peers: dimmed, labelled, travelable.** In A, switch to (or create) a second project
+ tab. In B: A's cursor and node chip vanish from the canvas **immediately**, and A's facepile
+ avatar goes **dimmed**, labelled with the project A is in ("Ada · api"). Click that avatar in B →
+ B switches to that project and centers on A's focused node. Switch A back → A's cursor reappears
+ on B's canvas.
+8. **Clean close leaves at once.** Close tab A normally → its cursor, chip and avatar disappear from
+ B within a moment (the WS `close`).
+9. **Vanished client leaves on the heartbeat.** Reopen A, then **kill** it without a clean close
+ (kill the browser process, or pull the network). B keeps showing A briefly, then reaps it
+ **within ~60 s** — this is the 30 s ping/pong, and is the expected worst case, not a bug.
+10. **Desktop alone is silent.** Launch the Electron app with no other client: no facepile, no
+ cursors, no name prompt — presence costs nothing when you are the only peer.
+
+### Manual smoke test (Stage 2 — terminal co-attach)
+
+Same two-client rig as Stage 1 above (`npm run server:dev`, one **normal** and one **private**
+window, so the two peers have distinct identities in `localStorage`). Do the Stage 1 script first —
+this one assumes **A** and **B** are logged in, named, and on the **same project**. Everything below
+is about *one terminal node*, so create one in A and let it appear in B.
+
+Co-attach is invisible when it works, so the checks are mostly *negative*: the last one (a solo user
+sees no change) is the one that must never regress.
+
+1. **One pty, two viewers.** Open the same terminal node in A and in B. Run `ls -la` in A. B shows
+ the **same live output**, in the same shell — not a second prompt in a second shell. The server
+ logs exactly **one** spawn: B's `create` subscribed to A's session (`fresh:false`) rather than
+ spawning. `tmux -L node-terminal ls` on the server shows exactly one `nt-<nodeId>` session with
+ exactly **one** client attached (co-attach does not add a tmux client; `-D` is untouched).
+2. **Both can type; characters interleave.** Type `echo hello` in A — the characters appear in B as
+ you type. Now type in **both at once**: the characters interleave in the one shell. This is
+ expected, not a bug (see [No locking](#no-locking-v1)) — the typing ring is the warning, and
+ there is no lock.
+3. **The typing ring.** While A types, B's copy of that node shows a **pulsing ring on A's avatar
+ chip** in the node header. It fades ~2 s after A stops. Type from B → A sees the ring on **B's**
+ chip. (The ring decays against the *viewer's* local receipt time, so a skewed clock on either
+ machine cannot leave a ring stuck on.)
+4. **The smaller window wins; the bigger one letterboxes.** Make B's browser window **narrower**
+ than A's. Both terminals reflow to **B's** (smaller) grid: the shell's own wrapping matches in
+ both, with no wrapping artifacts. In **A** — the larger one — the leftover space is
+ **letterboxed** (dead margin), because A is now rendering B's smaller grid. Run
+ `tput cols; tput lines` in either: it reports the **min**, not A's own size. Widen B again → both
+ grow back and A's letterbox disappears.
+5. **Parking releases the size constraint.** With B still the narrower (constraining) client, in
+ **B** switch to a different project tab. B's node unmounts and **parks** — it stays subscribed but
+ reports `null` ("subscribed, not viewing"), so it drops out of the min. **A's terminal grows back
+ to A's own size and stops letterboxing**, within a moment and without B closing anything. Switch
+ B back → the node re-adopts, re-fits, and constrains A again. (This is the fix for the obvious
+ bug: a teammate who wandered off to another tab must not hold everyone's terminal hostage at a
+ grid they can't even see.)
+6. **Delete shows "closed by", and does NOT respawn.** In **A**, delete the node (× / Delete). In
+ **B**, that terminal enters the **"closed by <A's name>"** state — and **B does not respawn it**:
+ no new shell appears, no new prompt, and `tmux -L node-terminal ls` shows the `nt-<nodeId>`
+ session **gone** and not recreated. Now the harder half: in **B**, *before* deleting, switch to
+ another project (so B has no mounted terminal for that node and cannot receive `pty:closed`), have
+ **A** delete the node, then switch **B** back. B must **still** land in the closed state — the
+ in-memory **tombstone** refuses the create — and must **not** spawn a fresh shell. **Known limit:**
+ restart the server process and repeat this — the tombstone is gone and B *will* spawn a fresh
+ session. That is the documented gap, fixed by Stage 3's canvas-delete mutation (see
+ [Known risks](#known-risks)); it is not a smoke-test failure today.
+7. **"Move into worktree" does NOT say "closed".** Restore/create a shared terminal node in a git
+ project, open it in both. In **A**, use **Move into worktree**. **B must never show "closed by
+ …"** — that would be a lie, the node is alive and on B's canvas too. Instead B's terminal
+ **restarts in place** with a `── session restarted by another user (moved to a new folder) ──`
+ separator, and it **follows the node into the new session**: `pwd` in **B** prints the
+ **worktree** path, the same one A is in, in the *same* shared session (this is `pty:recycle`, not
+ `destroy` — see [Deletion vs recycling](#deletion-vs-recycling)).
+8. **A slow client is dropped, not buffered — and lands on the current screen.** Throttle **B**'s
+ network (DevTools → Network → "Slow 3G") and run `yes | head -5000000` in the shared terminal.
+ **A must keep streaming at full speed** (B's slow socket must not pace the team), and the server
+ process's RSS must **plateau** — past 8 MB buffered, B's queued output is dropped rather than
+ queued forever. Remove the throttle: B lands on the **current screen** with a single
+ `── reconnected — earlier output skipped ──` separator. It must **not** grind through the backlog,
+ and B's screen must **never** go blank (an empty capture is never sent, and is ignored if it were).
+9. **One client leaving does not stall the other.** Close **B**'s browser entirely while output is
+ streaming. **A keeps streaming** — no stall, no stale pause left behind by B's disconnect
+ (`dropClient()`), no dead subscriber holding the grid at B's old size.
+10. **A SOLO user sees no change whatsoever.** The regression that matters most. In the desktop app
+ (`npm run dev`), alone, with no other client: open a terminal, run `yes | head -100000`, resize
+ the node, switch projects and back (park → adopt), quit and relaunch (warm reattach). The min of
+ a one-element set is your own size, so: **no letterbox ever appears**, the grid is exactly your
+ own fit, no resync separator is ever printed, no typing ring, no facepile. Nothing may look or
+ behave differently from `main`.
+
+### Manual smoke test (Stage 3 — canvas sync)
+
+Same two-client rig (`npm run server:dev`, one **normal** and one **private** window). **A** and **B**
+logged in, named, and on the **same project**.
+
+1. **A node created by A appears on B.** Add a terminal node in A. It appears on B's canvas at the
+ same flow coordinates, with the same title and color, within a moment — and B's canvas shows
+ **one** node, not two.
+2. **Move, rename, recolor propagate.** Drag the node in A → it moves on B. Rename it (header
+ click-to-rename) → the title updates on B. Change its color → the color updates on B. Now do the
+ same three from **B** → they land on A. (Rename and color never pass through `onNodesChange`; if
+ they fail to sync, the publisher has regressed to a change-list.)
+3. **A drag is throttled, not per-frame.** Drag a node around A for a few seconds with B's DevTools
+ Network → WS frames open. The `canvas:mut` frames arrive at roughly **20 Hz**, not one per
+ animation frame, and the **last** frame lands on the settled position (the drag-stop flush) — B's
+ node must end up exactly where A dropped it, never one frame short.
+4. **Delete propagates, and does not come back.** Delete the node in A. It disappears from B's canvas
+ (and B's terminal for it lands in the "closed by <A>" state — Stage 2). Now, in **B**, make an
+ unrelated edit (move another node) so B's canvas saves. Reload **both** tabs: the deleted node is
+ **gone** and stays gone. (Before Stage 3, B's whole-file save wrote the deleted node straight back
+ — this is the data-loss bug the stage exists to kill.)
+5. **A delete lands even on a project you are not looking at.** In **B**, switch to a *second* project
+ tab. In **A**, delete a node from the **first** project. Switch B back → the node is **already
+ gone** from B's first-project canvas (the mutation was applied to that project's serialized nodes
+ while it was inactive). Reload B: still gone.
+6. **Ephemeral subagent cards do not duplicate.** Run a prompt in a Claude node in A that spawns a
+ subagent (e.g. "use a subagent to list this repo's files"). The subagent card appears **once** in
+ A and **once** in B (each derives it from the `agent:status` stream) — never twice, and dragging
+ the card in A does not move or duplicate anything in B. Same for a `/loop` card.
+7. **No echo, no ping-pong.** With both tabs idle after an edit, watch the WS frames: `canvas:mut`
+ traffic goes **silent**. A mutation applied from a peer must not be re-published (that would be an
+ endless A→B→A loop); if you see mutation frames with nobody touching either canvas, the `adopt()`
+ loop guard has regressed.
+8. **A SOLO user sees no change whatsoever.** The regression that matters most. In the desktop app
+ (`npm run dev`), alone: add, drag, rename, recolor, group, delete nodes; undo/redo; switch projects
+ and back. With no peer attached the publisher does not even **diff** (the solo gate) — the canvas
+ must look and behave exactly as on `main`, with no extra dirty marks, no undo-stack entries you did
+ not create, and no node ever moving on its own.
+9. **Both drag the same node.** A and B grab the **same** node and drag it in opposite directions for
+ a few seconds, then both let go. It fights (expected — last write wins), but when the dust settles
+ **both canvases show it in the same place**. Reload both: still the same place. (Before the
+ ordering fix, A and B ended up holding the node at two different positions *permanently*, and
+ whoever saved last silently moved it for the other.)
+10. **Delete a node the other is dragging.** B drags a node; A deletes it mid-drag. Whatever happens
+ (it survives on both, or it dies on both — the total order decides), **A and B agree**, and after
+ a reload of both tabs the canvas is the same on each. What must never happen is one of them
+ holding a node the other does not.
+11. **Your selection survives a teammate's drag.** In B, box-select two nodes and hold the selection
+ while A drags a *third* node around. B's selection must stay selected (before the in-place apply,
+ each of A's ~20 Hz mutations wiped it). Likewise, B's relay-remote terminal nodes (if any) must
+ not vanish while A edits.
+12. **Your undo is not eaten.** In B, move a node, and within a moment have A move a *different* node
+ (so a peer mutation lands during B's undo debounce). Now press ⌘Z in **B**: it must undo **B's**
+ move — not skip past it to an older state (which would also revert A's edit).
+
+## Known risks
+
+- **Weak identity** — anyone can claim any name.
+- **Concurrent typing garbles input** — accepted; the badge is the warning.
+- **Cross-user undo** — last-write-wins, no CRDT.
+- **Per-node last-write-wins is a resolution, not an arbitration.** Clients always converge, but a
+ delete can lose to a concurrent drag frame (the node survives everywhere, with a dead session), and
+ two people dragging one node fight over it. Named in full under
+ [Concurrent-edit resolution](#concurrent-edit-resolution-what-converges-and-what-does-not).
+- **A peer's edge (context link / note link) is deleted by your next save.** Edges are not synced but
+ they *are* persisted, in the same whole-file write. See item 5 of
+ [What Stage 3 changed](#what-stage-3-changed-relative-to-this-spec).
+- **The publisher's solo gate reads the presence peer table.** If a client's presence handshake never
+ completes, that client sees no peers and therefore publishes nothing (it still *applies* what it
+ receives, and the first mutation from a peer flips the gate on for good). Presence and canvas sync
+ ride the same transport, so a client that cannot say hello generally cannot cast either — but the
+ coupling is real and is the price of a solo user paying zero.
+- **Cursor traffic** is 20 Hz × peers: comfortable for a 5–10 person team, not for a public room.
+- **Plain-shell (no tmux) co-attach shows a joiner a blank-but-live terminal** until the next output
+ arrives (pressing Enter paints it). A joiner gets `fresh:false`, so it skips the cold-restore
+ replay, and with no tmux there is nothing to capture its current screen from either. With tmux —
+ i.e. every normal install — the joiner IS painted: the create result carries the screen (see
+ [Painting the joiner](#painting-the-joiner)). A plain-shell session has no cross-client continuity
+ to inherit anyway; that is what "no tmux = no persistence" already means everywhere else.
+- **A deleted node can still be resurrected on the paths canvas sync does not cover.** Stage 3 closed
+ the main one: an attached client's canvas loses the node the instant a peer deletes it (active
+ project *and* loaded-but-inactive project), so it never asks to re-create it, and its next
+ whole-file save cannot write it back. The respawn guard behind that is still three layers deep,
+ because the mutation does not reach everywhere: the `pty:closed` event (subscribers only), the
+ canvas-delete mutation (clients attached at that moment), and the in-memory `tombstones` map
+ (everyone else, for as long as the core process lives). What is left:
+ - **A whole project deleted by one client is not synced** (project lifecycle is not in the mutation
+ vocabulary), so a peer can still reopen it from *its* "Recently closed" list and re-create its
+ nodes' ptys. The tombstone is what refuses those creates.
+ - **A client that was disconnected when the delete landed misses it** (no join snapshot, no replay).
+ The browser self-heals on reconnect by reloading the page — but only after the deleting client's
+ debounced save has flushed.
+ - **The tombstone remains in-memory**, so it dies with the core process; across a core restart both
+ of the above degrade to "the node comes back". Bounded and honestly named, not a promise. See
+ [What Stage 3 changed](#what-stage-3-changed-relative-to-this-spec) (item 4).
+- **A peer's node delete can leave a dangling edge.** Edges are not in the mutation vocabulary — only
+ nodes are — so a context-link / note-link edge whose endpoint a peer deleted stays drawn on your
+ canvas until the next save/load drops it. Drawing an edge is likewise not synced.
diff --cc src/core/pty-manager-platform.test.ts
index c4f9eec2f,3500d56fa..b31a01389
--- a/src/core/pty-manager-platform.test.ts
+++ b/src/core/pty-manager-platform.test.ts
@@@ -22,33 -22,10 +22,34 @@@ describe('PtyManager platform registrat
IPC.ptyKill,
IPC.ptyDestroy,
IPC.ptySendText,
- IPC.ptyReadScrollback
+ IPC.ptyReadScrollback,
+ IPC.ptyCaptureHistory
]) {
- expect(fake.handlers[ch] ?? fake.listeners[ch], ch).toBeDefined()
+ // ptyKill is sender-aware (co-attach: unsubscribe ONE client) → senderListeners.
+ expect(fake.handlers[ch] ?? fake.listeners[ch] ?? fake.senderListeners[ch], ch).toBeDefined()
+ }
+ })
+
+ // THE WORST REGRESSION IN THIS FILE, AND THE ONE NOTHING ELSE CATCHES.
+ //
+ // `on` and `onWithSender` COMPOSE on the same channel — on BOTH shells. Electron registers two
+ // separate `ipcMain.on`s; ServerPlatform keeps one ordered registry and invokes every entry. So
+ // a merge that resurrects the old `platform().on(IPC.ptyWrite, …)` line NEXT TO the sender-aware
+ // one does not error, does not typecheck-fail, and does not fail any behavioural test (they all
+ // invoke the sender map, and the fake keeps the two maps apart) — it just runs the handler TWICE:
+ // every keystroke, every paste, every user, doubled into the pty (`lls s`). Resize and flow are
+ // barely better: a doubled resize is a second full-pane tmux redraw, a doubled flow cast
+ // double-counts the pause the client owes.
+ //
+ // Hence this: the four migrated channels must have NO plain listener at all. If you are here
+ // because this went red, you added a second registration for a channel that already has a
+ // sender-aware one — delete it, don't relax the assertion.
+ it('registers the sender-aware pty channels EXACTLY ONCE (no composed plain listener)', async () => {
+ const { PtyManager } = await import('./pty-manager')
+ new PtyManager().registerIpc()
+ for (const ch of [IPC.ptyWrite, IPC.ptyResize, IPC.ptyFlow, IPC.ptyKill, IPC.ptyDestroy]) {
+ expect(fake.senderListeners[ch], ch).toBeDefined()
+ expect(fake.listeners[ch], ch).toBeUndefined()
}
})
})
diff --cc src/core/pty-manager.ts
index 43c99f605,23b401993..d994d449d
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@@ -19,11 -18,12 +19,13 @@@ import
remoteTmuxHasSessionArgs,
remoteTmuxKillArgs,
remoteTmuxPtyArgs,
- remoteCapturePaneArgs
+ remoteCapturePaneArgs,
+ remoteCaptureHistoryArgs
} from './remote-ssh/control-master'
+ import { HISTORY_LINES, HISTORY_MAX_BYTES, clampHistoryLines } from './history-limits'
import { TMUX_SOCKET, sessionName } from './tmux-naming'
import { releasePty, type ReleasablePty } from './pty-release'
+import { effectiveSize, type PtySize } from './pty-size'
import { machOArch, archMismatch } from './macho-arch'
import { writeScrollback, readScrollback, deleteScrollback } from './scrollback-store'
import { claudeConfigDirFor } from './claude-config-dir'
@@@ -1585,23 -881,49 +1612,66 @@@ export class PtyManager
}
}
+ /**
+ * The CURRENT screen of a live session, by sessionId — the redraw sent to a client that fell so
+ * far behind that its socket backlog was discarded (see ServerPlatform's WS_DROP_WATER). Reuses
+ * the existing `tmux capture-pane -e` paths (`captureSnapshot`, which the relay host already
+ * paints a joining mirror with; `captureSession` for an ssh-project node, whose tmux lives on the
+ * remote host) rather than adding a second capture. '' when the session or tmux is unavailable —
+ * the client then just clears and resumes streaming.
+ */
+ async captureForResync(sessionId: string): Promise<string> {
+ const session = this.sessions.get(sessionId)
+ if (!session) return ''
+ const key = session.persistKey ?? session.indexKey
+ if (!key) return ''
+ if (session.sshRemote) return this.captureSession(key)
+ return this.captureSnapshot(key)
+ }
+
+ /**
+ * Capture a session's scrollback for hydrating a fresh emulator on a warm reattach (the app
+ * restarted; tmux kept running and only redraws the visible screen).
+ *
+ * The capture INCLUDES the visible screen (no `-E -1`). tmux's attach redraw starts with
+ * `\x1b[H\x1b[2J`, and xterm's eraseInDisplay(2) resets the viewport lines IN PLACE — it does
+ * not push them into scrollback — so it erases exactly the newest `rows` lines of whatever we
+ * just hydrated. Excluding the visible screen would therefore guarantee a one-screenful gap at
+ * the seam; capturing it and letting the redraw overwrite it gives neither gap nor duplication.
+ * Best-effort: returns '' when tmux/ssh is unavailable.
+ */
+ async captureHistory(persistKey: string, lines = HISTORY_LINES): Promise<string> {
+ // `lines` is untrusted (it arrives from the renderer — a browser client in Server Edition)
+ // and is interpolated into a REMOTE shell command below. Clamp at the entry point.
+ const n = clampHistoryLines(lines)
+ const sshRemote = this.sessionByPersistKey(persistKey)?.sshRemote
+ if (sshRemote) {
+ const ssh = findSsh()
+ if (!ssh) return ''
+ try {
+ const { stdout } = await runAsync(
+ ssh,
+ remoteCaptureHistoryArgs(sshRemote.conn, sshRemote.controlPath, sessionName(persistKey), n),
+ { encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 }
+ )
+ return trimToBytes(stdout, HISTORY_MAX_BYTES)
+ } catch {
+ return ''
+ }
+ }
+ if (!this.tmuxPath) return ''
+ try {
+ const { stdout } = await runAsync(
+ this.tmuxPath,
+ ['-L', TMUX_SOCKET, 'capture-pane', '-p', '-e', '-t', sessionName(persistKey), '-S', `-${n}`],
+ { encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 }
+ )
+ return trimToBytes(stdout, HISTORY_MAX_BYTES)
+ } catch {
+ return ''
+ }
+ }
+
/**
* Snapshot a node's recent scrollback (with colors, `-e`) to disk for cold-restart replay.
* Best-effort: a missing session / unavailable tmux just leaves the prior snapshot in place.
diff --cc src/main/index.ts
index 2c7ec1722,251e3500a..25fd1014c
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@@ -348,7 -327,11 +351,12 @@@ app.whenReady().then(async () =>
ptyManager.registerIpc()
workspaceStore.registerIpc()
gitService.registerIpc()
+ presenceHub.registerIpc()
+ registerClaudeCliIpc()
+ // Warm the `claude --version` probe now (it spawns a login shell + node, ~sub-second) so the
+ // renderer's first `claude.cliCaps()` — awaited on the launch path of a cold-restored agent
+ // node — resolves from cache instead of racing the probe into a conservative "no auto".
+ void claudeCliCaps()
ipcMain.handle(IPC.commitGenerate, (_e, cwd: string) =>
generateCommitMessage(cwd, settingsStore.get())
diff --cc src/main/remote/host-service.ts
index a2a4395f1,07cb1f4e8..9e5530112
--- a/src/main/remote/host-service.ts
+++ b/src/main/remote/host-service.ts
@@@ -11,8 -11,11 +11,12 @@@
// into an `OP.Error` frame (then the stream is dropped).
// - `OP.Input` frame -> `write(sessionId, <utf-8 payload>)`
// - `OP.Resize` frame -> `resize(sessionId, cols, rows)` (payload = 2x uint16 LE)
+ // - RPC `pty.captureHistory {streamId, lines?, maxBytes?}` -> `captureHistory(persistKey, lines)`,
+ // returning `{ output }` (tmux scrollback, so a re-entering client can hydrate its empty
+ // emulator scrollback). `lines`/`maxBytes` are SIZE hints only — clamped, and they can only
+ // SHRINK the reply (a phone on a mobile link asks for far less than the desktop caps).
-// - RPC `pty.kill {streamId}` -> `kill(sessionId)`
+// - RPC `pty.kill {streamId}` -> `kill(null, sessionId)` (null = the relay owns this pty; it has
+// no UI subscribers, so dropping its sinks releases it)
// Output backpressure: when `sendFrame` returns false the host pauses the PTY via `setFlow`
// and resumes it on the next successful send.
//
@@@ -60,21 -63,14 +65,25 @@@ export interface HostPtyManager
): string
/** Current visible screen of a node's tmux session, for the attach snapshot. */
captureSnapshot(persistKey: string): Promise<string>
+ /** Scrollback (history + visible screen) of a node's tmux session, for hydrating a fresh
+ * emulator on re-entry — the client's own scrollback is empty on a warm reattach. `lines` is
+ * clamped by the pty-manager itself (it is interpolated into a tmux command). */
+ captureHistory(persistKey: string, lines?: number): Promise<string>
- write(sessionId: string, data: string): void
- resize(sessionId: string, cols: number, rows: number): void
- setFlow(sessionId: string, resume: boolean): void
- kill(sessionId: string): void
+ /** `clientId` identifies WHO typed (the bridged phone's presence peer), so the keystroke can be
+ * attributed to it — null when this session has no peer, which just means it is not badged. */
+ write(clientId: number | null, sessionId: string, data: string): void
+ /** `clientId` is null for a relay-served (detached) pty — see `kill` below. */
+ resize(
+ clientId: number | null,
+ sessionId: string,
+ cols: number | null,
+ rows: number | null
+ ): void
+ /** `clientId` is null for a relay-served (detached) pty: the pause is owed by the host's sink,
+ * which returns it on drain — see PtyManager.setFlow / Session.pausedBy. */
+ setFlow(clientId: number | null, sessionId: string, resume: boolean): void
+ /** `clientId` is null for a relay-served (detached) pty: the sinks ARE its only subscriber. */
+ kill(clientId: number | null, sessionId: string): void
}
// The slice of RelaySocket the host needs to answer the client.
diff --cc src/preload/index.ts
index b83b28a60,4816c0bd7..8944d47c6
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@@ -294,23 -268,8 +295,24 @@@ const api: NodeTerminalApi =
ensure: (sessionId, cwd, accountId) =>
ipcRenderer.send(IPC.contextEnsure, sessionId, cwd, accountId)
},
+ // Canvas sync: one channel in both directions. The cast goes to the reflector (src/core/canvas-sync),
+ // which stamps it with the total order (`seq`) and fans it to every attached client — INCLUDING us.
+ // Our own mutation coming back is the ACK that tells us where it landed in that order; the renderer
+ // recognizes it by `src` and does not re-apply it (src/shared/canvas-order.ts).
+ canvas: {
+ mutate: (projectId, mutation) => ipcRenderer.send(IPC.canvasMut, projectId, mutation),
+ onMutation: (listener) => {
+ const handler = (
+ _e: unknown,
+ projectId: string,
+ mutation: Parameters<typeof listener>[1]
+ ): void => listener(projectId, mutation)
+ ipcRenderer.on(IPC.canvasMut, handler)
+ return () => ipcRenderer.removeListener(IPC.canvasMut, handler)
+ }
+ },
claude: {
+ cliCaps: () => ipcRenderer.invoke(IPC.claudeCliCaps),
readTranscript: (sessionId, cwd, accountId) =>
ipcRenderer.invoke(IPC.claudeReadTranscript, sessionId, cwd, accountId)
},
diff --cc src/renderer/bridge/ws-bridge.ts
index 0f4a9ca18,bf341f4bd..d1a6c231a
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@@ -8,21 -8,22 +8,24 @@@
import { parseRpcMessage, decodePtyData, type RpcMessage } from '../../shared/rpc'
import { IPC } from '../../shared/ipc'
- import type {
- ContextApi,
- FilesApi,
- FsApi,
- GitApi,
- NodeTerminalApi,
- PresenceApi,
- PtyApi,
- PtyCreateOptions,
- SettingsApi,
- Settings,
- Workspace,
- WorkspaceApi
+ import {
+ UNKNOWN_CLAUDE_CLI_CAPS,
+ type ClaudeApi,
+ type ClaudeCliCaps,
+ type ContextApi,
+ type FilesApi,
+ type FsApi,
+ type GitApi,
+ type NodeTerminalApi,
++ type PresenceApi,
+ type PtyApi,
+ type PtyCreateOptions,
+ type SettingsApi,
+ type Settings,
+ type Workspace,
+ type WorkspaceApi
} from '../../shared/types'
+import type { PeerIdentity } from '../../shared/presence'
import { buildStubApi } from './stubs'
import { mountPickerRoot, openDirectoryPicker } from './dialog-picker'
@@@ -341,44 -334,24 +346,62 @@@ export function buildAgentApi
}
}
+/**
+ * Build the `canvas` namespace over an RpcClient: a cast out (`canvas:mut`) and a subscription in on
+ * the same channel. The server stamps each mutation with the total order (`seq`) and reflects it to
+ * every client, us included — our own frame coming back is the ACK that carries our place in that
+ * order (the renderer recognizes it by `src`; see src/shared/canvas-order.ts). This is a REAL
+ * implementation, not a stub:
+ * the Server Edition (two browsers on one workspace) is the surface that needs canvas sync most.
+ */
+export function buildCanvasApi(client: RpcClient): Pick<NodeTerminalApi, 'canvas'> {
+ return {
+ canvas: {
+ mutate: (projectId, mutation) => client.cast(IPC.canvasMut, projectId, mutation),
+ onMutation: (listener) => client.subscribe(IPC.canvasMut, listener as Listener)
+ }
+ }
+}
+
+/**
+ * Build the `presence` namespace over an RpcClient, mirroring the preload's invoke(→request) /
+ * send(→cast) / on(→subscribe) split member-for-member: `hello` is the only request (its response
+ * is how a client learns its OWN clientId), cursor/focus/chat/project are casts, and the two event
+ * channels are subscriptions. Declared against its `NodeTerminalApi` slice so `satisfies` keeps
+ * the compiler as the completeness gate.
+ */
+export function buildPresenceApi(client: RpcClient): Pick<NodeTerminalApi, 'presence'> {
+ const presence: PresenceApi = {
+ hello: (identity: PeerIdentity) =>
+ client.request(IPC.presenceHello, identity) as ReturnType<PresenceApi['hello']>,
+ cursor: (cursor) => client.cast(IPC.presenceCursor, cursor),
+ focus: (nodeId) => client.cast(IPC.presenceFocus, nodeId),
+ chat: (text) => client.cast(IPC.presenceChat, text),
+ project: (projectId) => client.cast(IPC.presenceProject, projectId),
+ onSync: (listener) => client.subscribe(IPC.presenceSync, listener as Listener),
+ onPeer: (listener) => client.subscribe(IPC.presencePeer, listener as Listener)
+ }
+ return { presence }
+}
+
+ /**
+ * Build the `claude` namespace over an RpcClient. `cliCaps` is a REAL handler on the server
+ * (`registerClaudeCliIpc` runs in the server shell too), so the browser resolves the very same
+ * `--permission-mode auto` version gate as desktop instead of silently no-opping into "auto
+ * unsupported" — which would strip the flag from every Claude launch in the Server Edition.
+ * A failed request degrades to the fail-open caps (bare command), never a rejection: the launch
+ * path awaits this. `readTranscript` has no server handler yet, so it keeps the stub's reject.
+ */
+ export function buildClaudeApi(client: RpcClient, stub: ClaudeApi): ClaudeApi {
+ return {
+ ...stub,
+ cliCaps: () =>
+ (client.request(IPC.claudeCliCaps) as Promise<ClaudeCliCaps>).catch(
+ () => UNKNOWN_CLAUDE_CLI_CAPS
+ )
+ }
+ }
+
/** WS URL for the current page: same host, `/ws`, ws→http / wss→https. */
function wsUrl(): string {
const scheme = location.protocol === 'https:' ? 'wss' : 'ws'
@@@ -488,8 -462,8 +512,10 @@@ export async function installWsBridge()
...buildRealApi(client),
...buildFilesApi(client),
...buildAgentApi(client),
+ ...buildCanvasApi(client),
+ ...buildPresenceApi(client),
+ // Only `cliCaps` is real here — the rest of the namespace stays stubbed (see buildClaudeApi).
+ claude: buildClaudeApi(client, stubApi.claude),
// Web replacement for the Electron native dialog: an in-app server-directory browser over
// fs.list (the stub's E_UNSUPPORTED reject is dropped in favor of this real picker).
dialog: (() => {
diff --cc src/renderer/canvas/Canvas.tsx
index 838d88b9a,c86a7a3e0..b5c262deb
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@@ -288,11 -277,10 +291,15 @@@ export function Canvas()
// (the user must pick a side). One-shot v2→v3 migration note (dismissible strip).
const [conflict, setConflict] = useState<Project | null>(null)
const [migrationNote, setMigrationNote] = useState<string | null>(null)
+ // A local edit team-sync cannot carry (a node over MUTATION_MAX_BYTES — in practice a sticky
+ // whose body someone pasted a document into). The reflector refuses it SILENTLY, so the user is
+ // told here rather than being left with a note their teammates never see. Dismissible; re-armed
+ // by the next refused cast (the publisher keeps retrying that node, so it syncs once trimmed).
+ const [syncNote, setSyncNote] = useState<string | null>(null)
+ // Copy-to-clipboard failure (browser build only): the bridge clipboard stub dispatches
+ // `nodeterm:toast` when neither the Clipboard API nor execCommand can copy — typically a
+ // non-secure context (plain http over a LAN). It must be seen, not swallowed.
+ const [copyError, setCopyError] = useState<string | null>(null)
const [zoomPct, setZoomPct] = useState(100)
const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)
const [remotePicker, setRemotePicker] = useState<{ x: number; y: number } | null>(null)
@@@ -4035,21 -3846,21 +4100,36 @@@
</button>
</div>
)}
+ {syncNote && (
+ <div className="announce-banner announce-banner--info">
+ <span className="announce-banner__dot" />
+ <div className="announce-banner__content">
+ <span className="announce-banner__body">{syncNote}</span>
+ </div>
+ <button
+ className="announce-banner__close"
+ title="Dismiss"
+ onClick={() => setSyncNote(null)}
+ >
+ ✕
+ </button>
+ </div>
+ )}
+ {copyError && (
+ <div className="announce-banner announce-banner--warning">
+ <span className="announce-banner__dot" />
+ <div className="announce-banner__content">
+ <span className="announce-banner__body">{copyError}</span>
+ </div>
+ <button
+ className="announce-banner__close"
+ title="Dismiss"
+ onClick={() => setCopyError(null)}
+ >
+ ✕
+ </button>
+ </div>
+ )}
{conflict && (
<ConflictBar
onReload={() => {
diff --cc src/renderer/nodes/TerminalNode.tsx
index fcc777032,f4dba0e4f..fff20bf1a
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@@ -18,30 -18,25 +18,37 @@@ import { RemoteTransport } from '../ter
import type { TerminalTransport } from '../terminal/transport'
import { patchTerminalScale } from '../terminal/scale-fix'
import { parseOsc52 } from '../terminal/osc52'
- import { FindBar } from '../components/FindBar'
- import { IconSearch, IconChat } from '../components/icons'
- import { NodeTags } from '../components/NodeTags'
- import { Tooltip } from '../components/Tooltip'
- import { useTerminalSearch } from '../terminal/useTerminalSearch'
- import { ContextMeter } from '../components/ContextMeter'
- import { isZoomModifierHeld } from '../lib/zoomModifier'
- import { useSettings } from '../state/settings'
- import { useAgentStatus, inferInterruptAfterSettle } from '../state/agentStatus'
import {
+ attachReplay,
+ closedByLabel,
+ copyKeyAction,
+ createDataGate,
+ disposalAction,
+ forgetNodeTermState,
+ letterboxFor,
+ markRecycled,
+ recycleAction,
+ reportedSize,
+ setFittedSize,
+ shouldApplyResync,
+ stripTrailingNewline,
+ takeRecycled,
- toXtermText
+ toXtermText,
+ xtermScrollback,
+ type SessionLife
} from '../terminal/terminal-config'
+ import { FindBar } from '../components/FindBar'
+ import { IconSearch, IconChat } from '../components/icons'
+ import { NodeTags } from '../components/NodeTags'
+ import { Tooltip } from '../components/Tooltip'
+ import { useTerminalSearch } from '../terminal/useTerminalSearch'
+ import { ContextMeter } from '../components/ContextMeter'
+ import { isZoomModifierHeld } from '../lib/zoomModifier'
+ import { useSettings } from '../state/settings'
+ import { useAgentStatus, inferInterruptAfterSettle } from '../state/agentStatus'
+import { reportFocus, releaseFocus, usePresence } from '../state/presence'
+import type { ClientId } from '@shared/presence'
+import { PresenceChips } from '../components/PresenceChips'
import { useAgentNodes } from '../state/agentNodes'
import { useProjects } from '../state/projects'
import { useSshConn } from '../state/sshConn'
@@@ -134,8 -132,17 +144,15 @@@ interface ParkedTerminal
search: SearchAddon
transport: TerminalTransport
sessionId: string
- sentCols: number
- sentRows: number
/** Session-scoped teardown (transport/xterm listeners) — run only at final dispose. */
cleanups: Array<() => void>
+ /**
+ * Lifetime of the session itself, SHARED with the effect that created it (and with the effect
+ * that later adopts this entry). `dead` flips on the final dispose, `killed` guards the PTY kill
+ * so a session is killed at most once even when a still-in-flight spawn continuation, the effect
+ * cleanup and the park dispose all race for it.
+ */
+ life: SessionLife & { killed: boolean }
timer: ReturnType<typeof setTimeout>
}
const parkedTerminals = new Map<string, ParkedTerminal>()
@@@ -555,14 -405,15 +586,15 @@@ export function TerminalNode({ id, data
term.loadAddon(searchAddon)
term.open(container)
loadWebgl()
- fit.fit()
+ applyFit()
patchTerminalScale(term, getZoom)
- // OSC 52 clipboard write: the remote tmux (set-clipboard on) emits OSC 52 on copy; route the
- // decoded text to the Mac clipboard. WRITE-ONLY — `parseOsc52` returns null for a `?` read
- // query so a remote program can never read the local clipboard. Returning true swallows the
- // sequence (also the read query). This is additive: the local tmux conf also has set-clipboard
- // on, so local tmux DOES emit OSC 52 and this handler fires too — a harmless redundant write of
- // the same selection (pbcopy already wrote it), NOT a no-op.
+ // OSC 52 clipboard write: route the decoded text to the local clipboard. tmux's mouse is off,
+ // so tmux copy-mode no longer emits OSC 52 on our behalf — this handler is now the ONLY
+ // clipboard path for programs that emit OSC 52 themselves (vim "+y, gh, yazi), local and
+ // remote alike (both tmux confs keep `set-clipboard on` so those sequences pass through).
+ // Selection copy is xterm's own (see the Cmd+C / Ctrl+Shift+C handler below), not this.
+ // WRITE-ONLY — `parseOsc52` returns null for a `?` read query so a remote program can never
+ // read the local clipboard. Returning true swallows the sequence (also the read query).
term.parser.registerOscHandler(52, (data) => {
const text = parseOsc52(data)
if (text !== null) window.nodeTerminal.clipboard.writeText(text)
@@@ -570,18 -421,48 +602,41 @@@
})
}
- // Cmd+C copies the terminal selection (xterm renders to canvas, so the DOM-selection
- // copy used elsewhere can't see it). Ctrl+C is left alone so it still sends SIGINT.
+ // Cmd+C (mac) / Ctrl+Shift+C (Linux, Windows) / Ctrl+Insert copy the terminal selection — xterm
+ // renders to a canvas, so the DOM-selection copy used elsewhere can't see it. Plain Ctrl+C is
+ // left alone so it still sends SIGINT.
+ // The chord is swallowed whether or not there is a selection (`copyKeyAction`): with no
+ // selection, falling through would let xterm map ctrl+c to \x03 and SIGINT the foreground
+ // process — the exact opposite of the "copy" we advertise.
+ // Returning false only tells xterm to skip the key; the browser default still runs unless we
+ // preventDefault() ourselves. Note that in Chromium (Server Edition, or `npm run dev` with
+ // DevTools attached) Ctrl+Shift+C is ALSO the browser's inspect-element picker and that one is
+ // NOT preventable by a page — hence Ctrl+Insert, which no browser reserves.
term.attachCustomKeyEventHandler((e) => {
- if (e.type === 'keydown' && e.metaKey && !e.ctrlKey && !e.altKey && e.key.toLowerCase() === 'c') {
- if (term.hasSelection()) {
- window.nodeTerminal.clipboard.writeText(term.getSelection())
- return false
- }
- }
- return true
+ const action = copyKeyAction(e, term.hasSelection())
+ if (action === 'pass') return true
+ e.preventDefault()
+ if (action === 'copy') window.nodeTerminal.clipboard.writeText(term.getSelection())
+ return false
})
- let sessionId: string | null = parked ? parked.sessionId : null
- let disposed = false
+ // Shared with the park entry this session travels through: an adopted terminal keeps the very
+ // same PTY session, so its lifetime (and its kill-once guard) must be the same record.
+ const life: SessionLife & { killed: boolean } = parked
+ ? parked.life
+ : { dead: false, killed: false }
+ // The park entry THIS effect's cleanup handed the session off to, if it parked one. Closure
+ // state on purpose: the parked-terminals MAP cannot answer "was this session handed off?" —
+ // an adoption deletes the entry, so park-then-adopt would read as "never parked".
+ let handedOff: ParkedTerminal | null = null
+ // Kill the PTY client at most once per session: the effect cleanup, a park dispose and a
+ // still-in-flight spawn continuation can all reach for it. `PtyManager.kill` tolerates a
+ // repeat, but `RemoteTransport.kill` forwards to the relay unconditionally.
+ const killSession = (sid: string): void => {
+ if (life.killed) return
+ life.killed = true
+ transport.kill(sid)
+ }
- // Last cols/rows actually sent to the PTY (seeded at create): a resize IPC makes tmux redraw
- // the whole pane, so a same-size fit (e.g. the ResizeObserver's initial tick right after
- // mount) must not send one — on a bulk project load that redraw doubles per node.
- let sentCols = parked ? parked.sentCols : 0
- let sentRows = parked ? parked.sentRows : 0
// Session-scoped teardown. An adopted terminal carries its listeners over (they were wired
// to the still-live session on first mount); everything below that pushes here is gated on
// `!parked` so nothing is wired twice.
@@@ -664,140 -533,120 +719,229 @@@
accountId: data.accountId,
sshRemote
})
- .then(async ({ sessionId: sid, fresh, accountFallback: fellBack }) => {
+ .then(async ({ sessionId: sid, fresh, accountFallback: fellBack, closed, screen }) => {
+ // REFUSED: core's tombstone says another client deleted this node while we weren't
+ // subscribed (our project was closed/inactive, so no `pty:closed` could reach us). Nothing
+ // was spawned — land in the same "closed by <name>" state a subscribed co-viewer gets.
++ // BEFORE `onDisposed()`: there is no session here, so there is nothing to kill or unwire.
+ if (closed) {
+ setCo(id, { closed })
+ if (!disposed) term.write('\r\n\x1b[90m[session closed by another user]\x1b[0m\r\n')
+ return
+ }
- if (disposed) {
- transport.kill(sid)
- return
+ // Disposal while the spawn/seed was in flight is NOT necessarily a teardown: an unmount
+ // with a live session PARKS it (same xterm, same PTY client, same `cleanups` array), and
+ // killing it here would leave the node permanently dead. That holds even if the user
+ // switched straight BACK: the remount adopts the entry and deliberately re-wires nothing —
+ // it relies on this continuation to finish the wiring (gate.open / onExit / onData). So the
+ // question is the closure's `handedOff`, not the (already emptied) parked-terminals map.
+ const onDisposed = (): boolean => {
+ const action = disposalAction({ disposed, handedOff: handedOff?.life })
+ if (action !== 'teardown') return false
+ offData?.()
+ killSession(sid)
+ return true
}
+ // Assigned below, once the data listener exists; before that there is nothing to detach.
+ let offData: (() => void) | undefined
+ if (onDisposed()) return
sessionId = sid
if (fellBack) setAccountFallback(true)
- // Catch up a size change that landed while the spawn was in flight (resize() skips the
+ // Catch up a size change that landed while the spawn was in flight (applyFit skips the
// IPC until sessionId is set, and the observer won't re-fire without another change).
- if (term.cols !== sentCols || term.rows !== sentRows) {
- sentCols = term.cols
- sentRows = term.rows
- transport.resize(sid, term.cols, term.rows)
+ applyFit()
+ // The pty is the authority on the grid: it runs at the SMALLEST subscriber's size, so
+ // render exactly that and letterbox the leftover space. With one subscriber the min is our
+ // own proposal, so a solo user is never sent this at all — nothing re-fits, nothing repaints.
+ if (transport.onSize) {
+ cleanups.push(
+ transport.onSize(sid, (size) => {
+ resizeTerm(term, size.cols, size.rows)
+ // Measured against the CURRENT mount's fit (the registry, not a closure): this
+ // listener outlives the mount that wired it — see terminal-config's fittedByNode.
+ setCo(id, { letterbox: letterboxFor(id, size) })
+ })
+ )
+ }
+ // Someone else permanently destroyed this node (tmux kill-session): show who, and make sure
+ // this component never respawns the session — see CoState.
+ if (transport.onClosed) {
+ cleanups.push(
+ transport.onClosed(sid, ({ by }) => {
+ setCo(id, { closed: { by } })
+ term.write('\r\n\x1b[90m[session closed by another user]\x1b[0m\r\n')
+ })
+ )
+ }
+ // Someone else RECYCLED this node (moved it into a worktree): our session id is dead. If a
+ // replacement is already live under the same node id (`ready`), restart onto it — the node
+ // is still on our canvas and still working, so the closed state above would be a lie, and
+ // parking this now-dead pty would hand a corpse to the next mount. If NO replacement ever
+ // came (the mover's app died mid-move), we must NOT respawn: our options still carry the
+ // node's stale cwd, and spawning it would silently undo the worktree move for everyone —
+ // the terminal ends instead, with a reopen (see CoState.ended / recycleAction).
+ if (transport.onRecycled) {
+ cleanups.push(
+ transport.onRecycled(sid, (info) => {
+ if (recycleAction(info) === 'ended') {
+ disposeParkedTerminal(id) // the park holds a dead pty either way
+ setCo(id, { ended: true })
+ term.write('\r\n\x1b[90m[session ended — reopen to restart]\x1b[0m\r\n')
+ return
+ }
+ const restart = restartSubs.get(id)
+ if (!restart) {
+ disposeParkedTerminal(id) // unmounted: drop the park, the next mount creates fresh
+ return
+ }
+ markRecycled(id)
+ restart()
+ })
+ )
}
+ // A restart we did not ask for: say why once, before the new session's output lands. (We
+ // JOIN the replacement session, so tmux — which already has a client — does not redraw for
+ // us; the first thing on this screen is whatever the new shell prints next.)
+ if (wasRecycled)
+ term.write(
+ '\r\n\x1b[90m── session restarted by another user (moved to a new folder) ──\x1b[0m\r\n'
+ )
- // CO-ATTACH: we joined a session somebody else already has open, so this xterm is empty and
- // nothing else will fill it — `fresh:false` skips the scrollback replay, and tmux only
- // redraws when the join actually resized the pty (i.e. when we are the new smallest client).
- // The create result carries the current screen for exactly the case where it did not, so
- // write it: the terminal opens on what our teammate is looking at, not on a blank rectangle.
- // Guarded like a resync (never paint an empty capture); no reset — the buffer IS empty.
- if (shouldApplyResync(screen)) term.write(toXtermText(screen as string))
+ // Flow control: track xterm's unprocessed write backlog (bytes handed to
+ // term.write but not yet parsed, plus anything still queued in the gate below). Past a
+ // high watermark we pause the source so a flood can't grow this buffer without bound;
+ // we resume once it drains.
+ let pending = 0
+ let paused = false
+ const HIGH_WATER = 1 << 20 // 1 MB
+ const LOW_WATER = 1 << 18 // 256 KB
++ // Bytes left the backlog (parsed by xterm, or dropped by a resync — see below). Both must
++ // return the flow ticket, or a discarded queue would leave `pending` permanently high and
++ // the source paused forever.
++ const relieve = (bytes: number): void => {
++ pending -= bytes
++ if (paused && pending < LOW_WATER) {
++ paused = false
++ transport.setFlow(sid, true)
++ }
++ }
+ const writeChunk = (chunk: string): void => {
- term.write(chunk, () => {
- pending -= chunk.length
- if (paused && pending < LOW_WATER) {
- paused = false
- transport.setFlow(sid, true)
- }
- })
++ term.write(chunk, () => relieve(chunk.length))
+ }
+ // Subscribe BEFORE the seed below: main pushes pty data on a timer regardless of
+ // listeners and an IPC event with no listener is dropped, while tmux emits its attach
+ // redraw within tens of ms — i.e. inside the seed's subprocess/ssh round-trip. The gate
+ // queues those chunks until the seed is written, then drains them in order. Queued bytes
+ // still count towards `pending`, so a flood during the gap pauses the source.
+ const gate = createDataGate(writeChunk)
+ offData = transport.onData(sid, (chunk) => {
+ pending += chunk.length
+ if (!paused && pending > HIGH_WATER) {
+ paused = true
+ transport.setFlow(sid, false)
+ }
+ gate.push(chunk)
+ })
+ cleanups.push(offData)
+ // We fell so far behind that the server discarded our queued output and redrew us from
+ // tmux. The capture IS the current screen, so reset the emulator and write it — writing it
+ // on top of a stale buffer would splice two different points in time. An EMPTY payload is
+ // ignored outright (shouldApplyResync): a wrongly cleared screen is unrecoverable, a
+ // skipped repaint is not. The separator mirrors the cold-restore one.
++ //
++ // It must go THROUGH THE GATE, not around it. A resync can land while the seed below is
++ // still awaiting its capture (both are exactly the "this client is slow" case), and the
++ // gate is holding chunks that PREDATE this redraw: draining them on top of it would splice
++ // the stale flood right back over the screen we just repainted, and the pending history
++ // seed would then write an even older screen over that. So the redraw SUPERSEDES both —
++ // `gate.reset()` drops the queue (returning its bytes to the flow accounting) and switches
++ // to pass-through, and `superseded` tells the seed its capture is now stale and to write
++ // nothing. Everything arriving after the capture streams straight through, in order.
++ let superseded = false
+ if (transport.onResync) {
+ cleanups.push(
+ transport.onResync(sid, (screen) => {
+ if (!shouldApplyResync(screen)) return
++ superseded = true
++ relieve(gate.reset())
+ term.reset()
+ term.write(toXtermText(screen))
+ term.write('\r\n\x1b[90m── reconnected — earlier output skipped ──\x1b[0m\r\n')
+ })
+ )
+ }
- // Cold restart: the tmux session (and anything that was running in it) is gone — replay
- // the last persisted scrollback so the user sees where they left off. Warm reattach
- // (`fresh` false) skips this: tmux redraws the live screen itself, so replaying would
- // duplicate it. Skipped on the very first open too (`fresh` true but initialCommand set).
- if (fresh && !data.initialCommand) {
- const snapshot = await scrollbackPromise
- if (disposed) {
- transport.kill(sid)
- return
- }
- if (snapshot) {
- term.write(snapshot)
- term.write('\r\n\x1b[90m── session restored (process ended by a restart) ──\x1b[0m\r\n')
+ // Seed the (fresh) emulator with the history it can't see: a cold restart replays the
+ // persisted snapshot (the tmux session died with the machine), a warm reattach pulls
+ // tmux's own scrollback. Parked terminals get neither — their buffer is still correct
+ // and seeding it would duplicate content.
+ // The gate MUST be opened whatever happens in here (`finally`): the data listener already
+ // exists, so a throw between it and `gate.open()` would queue chunks forever — the source
+ // pauses at the high-water mark and the terminal freezes silently and permanently. The
+ // only case that leaves it shut is a real teardown, where the xterm is disposed anyway.
+ let toreDown = false
+ try {
+ const replay = attachReplay({
+ parked: !!parked,
+ fresh,
+ hasInitialCommand: !!data.initialCommand
+ })
+ if (replay === 'cold-snapshot') {
+ const snapshot = await scrollbackPromise
+ if ((toreDown = onDisposed())) return
- if (snapshot) {
++ if (snapshot && !superseded) {
+ // The snapshot comes from `capture-pane -p`: LF-separated, no CR bytes. xterm runs
+ // with convertEol:false, so writing it raw would render as a staircase.
+ term.write(toXtermText(snapshot))
+ term.write('\r\n\x1b[90m── session restored (process ended by a restart) ──\x1b[0m\r\n')
+ }
+ } else if (replay === 'warm-history') {
+ // Warm reattach: tmux redraws only the VISIBLE screen, so everything above it would be
+ // missing from this fresh xterm. `captureHistory` includes the visible screen too —
+ // tmux's redraw (\x1b[H\x1b[2J) erases exactly those lines in place, so it overwrites
+ // the tail of what we write here instead of leaving a gap. This is the session's REAL
+ // history, not a restore boundary — it gets no separator line.
+ // Requested only now (not prefetched alongside the spawn): for an SSH node the remote
+ // tmux is only reachable once `create()` has registered the session's ssh target — an
+ // earlier call would silently fall through to the LOCAL tmux and return ''.
+ // Goes through the TRANSPORT, not `window.nodeTerminal.pty`: a relay-backed node's tmux
+ // session lives on the HOST, so the local PtyManager has nothing to capture and the
+ // node would come up with an empty scrollback.
+ const history = await transport.captureHistory(id).catch(() => '')
+ if ((toreDown = onDisposed())) return
++ // A resync repainted this screen from tmux while we were awaiting the capture — it is
++ // strictly newer than what we just fetched. Writing the history now would paint an
++ // older screen over it.
++ if (superseded) return
+ if (history) {
+ // The capture is byte-trimmed at the head, so it can begin mid-escape-sequence —
+ // start the block from a known-clean SGR state rather than an arbitrary one.
+ term.write('\x1b[0m')
+ // capture-pane ends with a trailing newline: writing it would drop the cursor one
+ // row below the last captured row, xterm would scroll, and tmux's redraw would
+ // repaint that row again — one duplicated line at the seam.
+ term.write(toXtermText(stripTrailingNewline(history)))
++ } else if (shouldApplyResync(screen)) {
++ // CO-ATTACH JOINER, history capture failed. A joiner also gets `fresh:false`, so it
++ // lands here — and `captureHistory` is the source that WINS for it: it is a strict
++ // superset of `PtyCreateResult.screen` (the same tmux pane, plus the scrollback above
++ // it), so the joiner opens on what its teammate sees AND can scroll back. Painting
++ // both would splice the same screen onto the canvas twice — hence one source, not two.
++ //
++ // `screen` is the FALLBACK for the one case the history path cannot cover: it is
++ // captured server-side inside `create()` and is guaranteed non-empty when present,
++ // whereas `captureHistory` returns '' whenever tmux/ssh is unavailable. Without this
++ // the joiner would open on a blank-but-live terminal — the exact failure the create
++ // result's screen exists to prevent. No reset: this xterm is empty.
++ term.write(toXtermText(screen))
+ }
}
+ } catch (err) {
+ // Never let a seed failure freeze the terminal: the live stream matters more than the
+ // history. `finally` still opens the gate below.
+ console.error('[terminal] history seed failed', err)
+ } finally {
+ // Seed written — release the PTY output that arrived while it was in flight.
+ if (!toreDown) gate.open()
}
- // Flow control: track xterm's unprocessed write backlog (bytes handed to
- // term.write but not yet parsed). Past a high watermark we pause the source so
- // a flood can't grow this buffer without bound; we resume once it drains.
- let pending = 0
- let paused = false
- const HIGH_WATER = 1 << 20 // 1 MB
- const LOW_WATER = 1 << 18 // 256 KB
- cleanups.push(
- transport.onData(sid, (chunk) => {
- pending += chunk.length
- if (!paused && pending > HIGH_WATER) {
- paused = true
- transport.setFlow(sid, false)
- }
- term.write(chunk, () => {
- pending -= chunk.length
- if (paused && pending < LOW_WATER) {
- paused = false
- transport.setFlow(sid, true)
- }
- })
- })
- )
cleanups.push(
transport.onExit(sid, (code) => {
term.write(`\r\n\x1b[90m[process exited with code ${code}]\x1b[0m\r\n`)
@@@ -886,7 -741,10 +1037,8 @@@
search: searchAddon,
transport,
sessionId,
- sentCols,
- sentRows,
cleanups,
+ life,
timer: setTimeout(() => {
if (parkedTerminals.get(id) === entry) {
parkedTerminals.delete(id)
@@@ -905,17 -770,21 +1064,23 @@@
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data.respawnNonce])
- // Live-apply font/cursor settings to the running terminal. A new font size means new cell
- // geometry, i.e. a different grid — route it through applyFit (not a bare fit.fit()) so the pty
- // is told the new size like any other resize, instead of running at a grid nobody renders.
+ // Live-apply font/cursor/scrollback settings to the running terminal, so a Settings change
+ // reaches the terminals already on the canvas instead of only the next fresh one.
++ //
++ // A new font size means new cell geometry, i.e. a different grid — route it through applyFit
++ // (not a bare fit.fit()) so the pty is told the new size like any other resize, instead of
++ // running at a grid nobody renders. Under co-attach applyFit is also what REPORTS our size, so
++ // a font change must go through it or this client would silently keep clamping the shared pty
++ // to its pre-change grid.
useEffect(() => {
const term = termRef.current
if (!term) return
term.options.fontSize = fontSize
term.options.fontFamily = fontFamily
term.options.cursorBlink = cursorBlink
+ term.options.scrollback = xtermScrollback(tmuxScrollback)
- try {
- fitRef.current?.fit()
- } catch {
- // ignore
- }
+ applyFitRef.current?.()
- }, [fontSize, fontFamily, cursorBlink])
+ }, [fontSize, fontFamily, cursorBlink, tmuxScrollback])
const toggleCollapse = () =>
setNodes((ns) =>
diff --cc src/renderer/state/projects.ts
index d5d68104c,ede92c69b..12cb775d1
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@@ -1,13 -1,7 +1,14 @@@
import { create } from 'zustand'
+ import type { AgentPermissionMode } from '@shared/agents/config'
-import type { BridgeLink, CanvasNodeState, Project, Viewport, Workspace } from '@shared/types'
-import { createProject } from './workspace'
+import type {
+ BridgeLink,
+ CanvasMutation,
+ CanvasNodeState,
+ Project,
+ Viewport,
+ Workspace
+} from '@shared/types'
+import { applyCanvasMutation, createProject } from './workspace'
interface ProjectsState {
projects: Project[]
diff --cc src/renderer/state/workspace.ts
index 1dfd57d27,031d8194e..be1ecb5a5
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@@ -1002,50 -1012,3 +999,50 @@@ export function flowToNodeStates(nodes
}
})
}
+
+/**
+ * Apply ONE peer mutation (canvas sync) to the LIVE React Flow node array — patch/append/remove
+ * just that node, and leave every other node object untouched.
+ *
+ * NOT `nodeStatesToFlow(applyCanvasMutation(flowToNodeStates(nodes), m))`. That whole-canvas round
+ * trip was the first cut, and the serializers are lossy BY DESIGN, so it destroyed live state on
+ * every peer mutation — 20 times a second while a teammate drags:
+ * - SELECTION. `nodeStatesToFlow` never sets `selected`, so a teammate's drag wiped your
+ * box-select / shift-click / select-then-group the instant it landed.
+ * - REMOTE NODES. `flowToNodeStates` filters `!n.data.remote` (they are transient to a relay
+ * connection and must never persist), so round-tripping DELETED every relay terminal on your
+ * canvas.
+ * - LOCAL-ONLY DATA. `initialCommand`, `respawnNonce`, `forkFrom` never survive a serialize.
+ * - IDENTITY. Every node object was rebuilt → every node component re-rendered, per mutation.
+ * Patching in place keeps all four: untouched nodes keep their object identity (React.memo holds),
+ * and the touched one keeps `selected` and its local-only data.
+ *
+ * `measured` is deliberately NOT carried over on the patched node: React Flow's measured size wins
+ * over `width`/`height` in flowToNodeStates, so keeping a stale one would make us serialize the OLD
+ * size after a peer resized the node — and re-publish it, fighting the peer. Dropping it lets React
+ * Flow re-measure from the incoming `style`, which is what the peer sent.
+ */
- export function applyMutationToFlow(nodes: CanvasNode[], m: import('@shared/types').CanvasMutation): CanvasNode[] {
++export function applyMutationToFlow(nodes: CanvasNode[], m: CanvasMutation): CanvasNode[] {
+ if (m.op === 'remove') {
+ if (!nodes.some((n) => n.id === m.id)) return nodes // already gone — keep identity, skip render
+ return nodes.filter((n) => n.id !== m.id)
+ }
+ const incoming = nodeStatesToFlow([m.node])[0]
+ const idx = nodes.findIndex((n) => n.id === m.node.id)
+ if (idx === -1) {
+ // Append, then re-sort: React Flow requires a parent to appear BEFORE its children, and a peer
+ // grouping nodes sends the new group frame and its (already present) children in one burst.
+ return groupsFirst([...nodes, incoming])
+ }
+ const prev = nodes[idx]
+ const next = nodes.slice()
+ next[idx] = {
+ ...incoming,
+ selected: prev.selected,
+ // Local-only data (initialCommand / respawnNonce / remote / forkFrom) is not serialized, so it
+ // is not in `incoming` — carry it. Every serialized key IS present on incoming.data (as a value
+ // or an explicit undefined), so the spread still applies the peer's clears.
+ data: { ...prev.data, ...incoming.data }
+ }
+ return prev.parentId === incoming.parentId ? next : groupsFirst(next)
+}
diff --cc src/renderer/terminal/local-transport.ts
index b2e448fe2,987870a73..b848f45b1
--- a/src/renderer/terminal/local-transport.ts
+++ b/src/renderer/terminal/local-transport.ts
@@@ -36,10 -35,10 +36,14 @@@ export class LocalTransport implements
this.pty.destroy(persistKey)
}
+ recycle(persistKey: string): void {
+ this.pty.recycle(persistKey)
+ }
+
+ captureHistory(persistKey: string): Promise<string> {
+ return this.pty.captureHistory(persistKey)
+ }
+
onData(sessionId: string, listener: (data: string) => void): () => void {
return this.pty.onData(sessionId, listener)
}
diff --cc src/renderer/terminal/remote-transport.ts
index b626bcf45,314decdd6..b3dda88c6
--- a/src/renderer/terminal/remote-transport.ts
+++ b/src/renderer/terminal/remote-transport.ts
@@@ -12,16 -12,11 +12,19 @@@ import type { TerminalTransport } from
* detaches the client stream via `kill` — the host-side tmux session survives, exactly like
* LocalTransport's kill/destroy split, but the client never owns the lifecycle of the host's
* persistent session.
+ *
+ * The co-attach members (`onSize` / `onClosed` / `onRecycled` / `onResync`) are deliberately NOT
+ * implemented: the relay frame protocol carries no size, closed, recycled or resync frame, and a
+ * relay client is a mirror of the host's own terminal rather than an equal subscriber of the pty.
+ * Omitting the optional members makes TerminalNode fall back to today's behavior for relay-backed
+ * nodes (local FitAddon sizing, no closed overlay, no restart-on-recycle, no server-driven repaint)
+ * instead of silently doing nothing behind an implemented-looking method. See CLAUDE.md, "Three
+ * surfaces".
*/
export class RemoteTransport implements TerminalTransport {
+ /** persistKey (host node id) -> the session (host streamId) this client attached for it. */
+ private readonly sessions = new Map<string, string>()
+
constructor(private readonly connectionId: string) {}
private get client() {
diff --cc src/renderer/terminal/terminal-config.test.ts
index 0a7fd2fc7,bdf266829..167c4b95c
--- a/src/renderer/terminal/terminal-config.test.ts
+++ b/src/renderer/terminal/terminal-config.test.ts
@@@ -1,150 -1,256 +1,431 @@@
-import { describe, it, expect } from 'vitest'
+import { describe, it, expect, beforeEach } from 'vitest'
import {
++ attachReplay,
+ closedByLabel,
++ copyKeyAction,
++ createDataGate,
++ disposalAction,
+ forgetNodeTermState,
++ isCopyShortcut,
+ isLetterboxed,
+ letterboxFor,
+ markRecycled,
+ recycleAction,
+ reportedSize,
+ setFittedSize,
+ shouldApplyResync,
++ stripTrailingNewline,
+ takeRecycled,
- toXtermText
++ toXtermText,
+ xtermScrollback,
+ XTERM_SCROLLBACK_MAX,
+ XTERM_SCROLLBACK_MIN,
- isCopyShortcut,
- copyKeyAction,
- attachReplay,
- toXtermText,
- stripTrailingNewline,
- disposalAction,
- createDataGate,
+ type CopyShortcutEvent
} from './terminal-config'
+import type { ClientId } from '@shared/presence'
+ const ev = (p: Partial<CopyShortcutEvent>): CopyShortcutEvent => ({
+ type: 'keydown',
+ key: 'c',
+ code: 'KeyC',
+ metaKey: false,
+ ctrlKey: false,
+ altKey: false,
+ shiftKey: false,
+ ...p
+ })
+
+describe('reportedSize', () => {
+ it('reports the fit proposal, floored at 1 (a collapsed node can propose 0)', () => {
+ expect(reportedSize({ cols: 132, rows: 43 })).toEqual({ cols: 132, rows: 43 })
+ expect(reportedSize({ cols: 0, rows: 0 })).toEqual({ cols: 1, rows: 1 })
+ })
+
+ it('returns null when the fit cannot be measured (hidden / zero-size node)', () => {
+ expect(reportedSize(undefined)).toBeNull()
+ expect(reportedSize(null)).toBeNull()
+ expect(reportedSize({ cols: NaN, rows: 24 })).toBeNull()
+ expect(reportedSize({ cols: 80, rows: Infinity })).toBeNull()
+ expect(reportedSize({ cols: 80 })).toBeNull()
+ })
+})
+
+describe('isLetterboxed', () => {
+ it('is false for a solo user: the effective size IS their own fit', () => {
+ expect(isLetterboxed({ cols: 100, rows: 30 }, { cols: 100, rows: 30 })).toBe(false)
+ })
+
+ it('is true when the pty runs at a smaller subscriber s grid', () => {
+ expect(isLetterboxed({ cols: 80, rows: 30 }, { cols: 100, rows: 30 })).toBe(true)
+ expect(isLetterboxed({ cols: 100, rows: 24 }, { cols: 100, rows: 30 })).toBe(true)
+ })
+
+ it('is false while our own fit is unknown (nothing to letterbox against)', () => {
+ expect(isLetterboxed({ cols: 80, rows: 24 }, null)).toBe(false)
+ })
+})
+
+describe('shouldApplyResync', () => {
+ it('paints a non-empty capture', () => {
+ expect(shouldApplyResync('$ ls\nfoo\n')).toBe(true)
+ })
+
+ it('IGNORES an empty/absent payload — a wrongly reset screen is unrecoverable', () => {
+ expect(shouldApplyResync('')).toBe(false)
+ expect(shouldApplyResync(null)).toBe(false)
+ expect(shouldApplyResync(undefined)).toBe(false)
+ })
+})
+
+ describe('attachReplay', () => {
+ it('replays the persisted snapshot on a cold start (tmux session gone)', () => {
+ expect(attachReplay({ parked: false, fresh: true, hasInitialCommand: false })).toBe('cold-snapshot')
+ })
+
+ it('hydrates from tmux history on a warm reattach (fresh xterm, live session)', () => {
+ expect(attachReplay({ parked: false, fresh: false, hasInitialCommand: false })).toBe('warm-history')
+ })
+
+ it('seeds nothing on a brand-new node (fresh session + launch command)', () => {
+ expect(attachReplay({ parked: false, fresh: true, hasInitialCommand: true })).toBe('none')
+ })
+
+ it('seeds nothing for a parked terminal — its buffer is already correct', () => {
+ // Both fresh values: an adopted xterm must never be seeded, or the content would double.
+ expect(attachReplay({ parked: true, fresh: false, hasInitialCommand: false })).toBe('none')
+ expect(attachReplay({ parked: true, fresh: true, hasInitialCommand: false })).toBe('none')
+ expect(attachReplay({ parked: true, fresh: true, hasInitialCommand: true })).toBe('none')
+ })
+ })
+
describe('toXtermText', () => {
+ it('turns tmux capture LFs into CRLFs, leaving existing CRLFs alone', () => {
+ expect(toXtermText('a\nb')).toBe('a\r\nb')
+ expect(toXtermText('a\r\nb')).toBe('a\r\nb')
+ })
++
+ it('turns tmux capture-pane LFs into CRLFs (xterm runs with convertEol off)', () => {
+ expect(toXtermText('one\ntwo\n')).toBe('one\r\ntwo\r\n')
+ })
+
+ it('leaves existing CRLFs alone', () => {
+ expect(toXtermText('one\r\ntwo')).toBe('one\r\ntwo')
+ })
+
+ it('keeps escape sequences untouched', () => {
+ expect(toXtermText('\x1b[31mred\x1b[0m\n')).toBe('\x1b[31mred\x1b[0m\r\n')
+ })
})
+describe('closedByLabel', () => {
+ const peers = { 7: { name: 'Ada' } } as Record<ClientId, { name: string }>
+
+ it('names the peer who destroyed the node', () => {
+ expect(closedByLabel(7 as ClientId, peers)).toBe('Ada')
+ })
+
+ it('degrades to a neutral label for an unattributed destroy or an unknown/departed peer', () => {
+ expect(closedByLabel(null, peers)).toBe('another user')
+ expect(closedByLabel(99 as ClientId, peers)).toBe('another user')
+ })
+})
+
+// The fitted size is read by the pty:size listener, which is wired ONCE and SURVIVES a park
+// (the terminal is adopted by a later mount with its listeners intact). It therefore may not
+// live in the mounting effect's closure: after a park/adopt, the listener would keep measuring
+// the letterbox against the PRE-PARK grid — so a co-viewer who parks, changes the font size and
+// comes back gets a letterbox he shouldn't have (or loses one he should).
+describe('fitted-size registry (survives a park, like the listeners that read it)', () => {
+ beforeEach(() => forgetNodeTermState('n1'))
+
+ it('measures the letterbox against the fit of the CURRENTLY mounted terminal', () => {
+ // Mount A fits 120×40 and wires the pty:size listener.
+ setFittedSize('n1', { cols: 120, rows: 40 })
+ const onSize = (size: { cols: number; rows: number }): boolean => letterboxFor('n1', size)
+ expect(onSize({ cols: 80, rows: 24 })).toBe(true) // a smaller co-viewer clamps us → letterbox
+
+ // Park + adopt: the SAME listener lives on, but the user bumped the font size, so mount B
+ // fits a smaller grid — which is now exactly the pty's size. No letterbox.
+ setFittedSize('n1', { cols: 80, rows: 24 })
+ expect(onSize({ cols: 80, rows: 24 })).toBe(false)
+ })
+
+ it('reports no letterbox for a node that has never reported a fit', () => {
+ expect(letterboxFor('never-fitted', { cols: 80, rows: 24 })).toBe(false)
+ })
+
+ it('forgets a node on permanent deletion (a recycled node id must not inherit a stale fit)', () => {
+ setFittedSize('n1', { cols: 200, rows: 60 })
+ forgetNodeTermState('n1')
+ expect(letterboxFor('n1', { cols: 80, rows: 24 })).toBe(false)
+ })
+})
+
+// The "session restarted by another user" banner is armed when the recycle notice lands and must
+// be CONSUMED by the spawn it belongs to — even when that spawn is abandoned (the node unmounted
+// while create() was in flight). A flag left behind would print the banner on some unrelated
+// mount hours later.
+describe('recycle banner flag', () => {
+ beforeEach(() => forgetNodeTermState('n1'))
+
+ it('is consumed exactly once', () => {
+ markRecycled('n1')
+ expect(takeRecycled('n1')).toBe(true)
+ expect(takeRecycled('n1')).toBe(false)
+ })
+
+ it('is false for a node that was never recycled', () => {
+ expect(takeRecycled('n1')).toBe(false)
+ })
+
+ it('is dropped with the node (no stale banner on a much later mount)', () => {
+ markRecycled('n1')
+ forgetNodeTermState('n1')
+ expect(takeRecycled('n1')).toBe(false)
+ })
+})
+
+// The recycle notice carries whether a REPLACEMENT session is already live. Without one (the
+// recycler crashed between the kill and the create), restarting would spawn `nt-<id>` from this
+// client's own — stale — cwd, silently undoing the worktree move for everybody. So: only restart
+// when there is something to restart onto.
+describe('recycleAction', () => {
+ it('restarts onto the replacement session when it is live', () => {
+ expect(recycleAction({ ready: true })).toBe('restart')
+ })
+
+ it('ends the terminal (reopen to restart) when no replacement was ever registered', () => {
+ expect(recycleAction({ ready: false })).toBe('ended')
+ })
+
+ it('treats a payload-less/legacy notice as "no replacement" (never spawn in a stale cwd)', () => {
+ expect(recycleAction(undefined)).toBe('ended')
+ })
+})
++
+ describe('stripTrailingNewline', () => {
+ it('drops exactly one trailing LF (tmux capture-pane ends with one)', () => {
+ expect(stripTrailingNewline('one\ntwo\n')).toBe('one\ntwo')
+ })
+
+ it('drops a trailing CRLF as a unit', () => {
+ expect(stripTrailingNewline('one\r\n')).toBe('one')
+ })
+
+ it('keeps blank lines that precede the final one (only ONE newline goes)', () => {
+ expect(stripTrailingNewline('one\n\n\n')).toBe('one\n\n')
+ })
+
+ it('leaves text without a trailing newline alone', () => {
+ expect(stripTrailingNewline('one\ntwo')).toBe('one\ntwo')
+ expect(stripTrailingNewline('')).toBe('')
+ })
+
+ it('composes with toXtermText so the seed leaves the cursor on the LAST captured row', () => {
+ // Writing the trailing newline would push the cursor one row down: xterm scrolls, the top row
+ // of the captured visible screen lands in scrollback, and tmux's redraw repaints it again —
+ // one duplicated line at the seam on every warm reattach.
+ expect(toXtermText(stripTrailingNewline('one\ntwo\n'))).toBe('one\r\ntwo')
+ })
+ })
+
+ describe('disposalAction', () => {
+ it('proceeds while the node is still mounted', () => {
+ expect(disposalAction({ disposed: false, handedOff: null })).toBe('proceed')
+ })
+
+ it('continues the setup when the cleanup PARKED this session', () => {
+ // Project switch during the hydration await: the park entry holds the same xterm, PTY client
+ // and cleanups array, so the session is alive and must be finished wiring — killing it here
+ // would leave a permanently dead node when the user switches back.
+ expect(disposalAction({ disposed: true, handedOff: { dead: false } })).toBe('continue-parked')
+ })
+
+ it('continues the setup when the parked session was already ADOPTED by a remount', () => {
+ // Park-then-adopt inside one hydration await: the remount takes the entry out of the parked
+ // map and deliberately re-wires nothing — it relies on THIS continuation to open the gate and
+ // attach onExit/onData. The handed-off entry is still alive (not dead), so: continue.
+ const handedOff = { dead: false } // adoption does not kill; it only removes the map entry
+ expect(disposalAction({ disposed: true, handedOff })).toBe('continue-parked')
+ })
+
+ it('tears down on a real unmount/delete (the cleanup handed nothing off)', () => {
+ expect(disposalAction({ disposed: true, handedOff: null })).toBe('teardown')
+ expect(disposalAction({ disposed: true, handedOff: undefined })).toBe('teardown')
+ })
+
+ it('tears down when the handed-off session was disposed for good (park expiry / delete)', () => {
+ expect(disposalAction({ disposed: true, handedOff: { dead: true } })).toBe('teardown')
+ })
+ })
+
+ describe('createDataGate', () => {
+ it('queues chunks that arrive before the gate opens, then drains them in order', () => {
+ const written: string[] = []
+ const gate = createDataGate((c) => written.push(c))
+ gate.push('a')
+ gate.push('b')
+ expect(written).toEqual([]) // nothing reaches the emulator while the hydration is in flight
+ gate.open()
+ expect(written).toEqual(['a', 'b'])
+ })
+
+ it('writes straight through once open', () => {
+ const written: string[] = []
+ const gate = createDataGate((c) => written.push(c))
+ gate.open()
+ gate.push('a')
+ gate.push('b')
+ expect(written).toEqual(['a', 'b'])
+ })
+
+ it('is idempotent on open (a second open cannot replay the queue)', () => {
+ const written: string[] = []
+ const gate = createDataGate((c) => written.push(c))
+ gate.push('a')
+ gate.open()
+ gate.open()
+ expect(written).toEqual(['a'])
+ })
+
+ it('keeps ordering when a chunk arrives during the drain', () => {
+ const written: string[] = []
+ const gate: ReturnType<typeof createDataGate> = createDataGate((c) => {
+ written.push(c)
+ if (c === 'a') gate.push('b') // re-entrant push while draining
+ })
+ gate.push('a')
+ gate.open()
+ expect(written).toEqual(['a', 'b'])
+ })
++
++ // A `pty:resync` repaints the CURRENT screen from tmux. Anything the gate is still holding
++ // predates that capture, so draining it would splice the stale flood back over the fresh screen —
++ // the terminal would end up showing output the redraw exists to skip.
++ it('DISCARDS the queue on reset (a resync supersedes everything that predates it)', () => {
++ const written: string[] = []
++ const gate = createDataGate((c) => written.push(c))
++ gate.push('stale-1')
++ gate.push('stale-2')
++ expect(gate.reset()).toBe('stale-1'.length + 'stale-2'.length) // bytes owed back to flow control
++ gate.open() // the seed's `finally` still runs — it must not resurrect the dropped chunks
++ expect(written).toEqual([])
++ })
++
++ it('passes through after a reset (post-capture output must keep streaming)', () => {
++ const written: string[] = []
++ const gate = createDataGate((c) => written.push(c))
++ gate.push('stale')
++ gate.reset()
++ gate.push('fresh')
++ expect(written).toEqual(['fresh'])
++ })
++
++ it('reports nothing dropped when the gate is already open', () => {
++ const written: string[] = []
++ const gate = createDataGate((c) => written.push(c))
++ gate.open()
++ gate.push('a')
++ expect(gate.reset()).toBe(0)
++ expect(written).toEqual(['a'])
++ })
+ })
+
+ describe('xtermScrollback', () => {
+ it('follows the tmux scrollback setting below the cap', () => {
+ expect(xtermScrollback(2000)).toBe(2000)
+ })
+
+ it('caps the default 50000-line tmux scrollback', () => {
+ expect(xtermScrollback(50000)).toBe(XTERM_SCROLLBACK_MAX)
+ expect(XTERM_SCROLLBACK_MAX).toBe(10000)
+ })
+
+ it('floors a tiny setting the same way the tmux conf does (history-limit max(1000, n))', () => {
+ // tmux would still keep 1000 lines of history — an xterm buffer smaller than that would make
+ // them unreachable, since xterm is the buffer the user scrolls.
+ expect(XTERM_SCROLLBACK_MIN).toBe(1000)
+ expect(xtermScrollback(100)).toBe(XTERM_SCROLLBACK_MIN)
+ expect(xtermScrollback(0)).toBe(XTERM_SCROLLBACK_MIN)
+ })
+ })
+
+ describe('isCopyShortcut', () => {
+ it('copies on Cmd+C', () => {
+ expect(isCopyShortcut(ev({ metaKey: true }))).toBe(true)
+ })
+
+ it('copies on Ctrl+Shift+C', () => {
+ expect(isCopyShortcut(ev({ ctrlKey: true, shiftKey: true }))).toBe(true)
+ })
+
+ it('leaves plain Ctrl+C alone so it still sends SIGINT', () => {
+ expect(isCopyShortcut(ev({ ctrlKey: true }))).toBe(false)
+ })
+
+ it('ignores other keys, keyups and extra modifiers', () => {
+ expect(isCopyShortcut(ev({ metaKey: true, key: 'v', code: 'KeyV' }))).toBe(false)
+ expect(isCopyShortcut(ev({ metaKey: true, type: 'keyup' }))).toBe(false)
+ expect(isCopyShortcut(ev({ metaKey: true, altKey: true }))).toBe(false)
+ expect(isCopyShortcut(ev({ ctrlKey: true, shiftKey: true, metaKey: true }))).toBe(false)
+ })
+
+ it('accepts an uppercase key (Shift makes Ctrl+Shift+C report "C")', () => {
+ expect(isCopyShortcut(ev({ ctrlKey: true, shiftKey: true, key: 'C' }))).toBe(true)
+ })
+
+ it('copies on a non-Latin layout, where e.key is not "c" (physical KeyC)', () => {
+ // Cyrillic layout: the C key reports 'с' (U+0441), Greek reports 'ψ'.
+ expect(isCopyShortcut(ev({ metaKey: true, key: 'с', code: 'KeyC' }))).toBe(true)
+ expect(isCopyShortcut(ev({ ctrlKey: true, shiftKey: true, key: 'с', code: 'KeyC' }))).toBe(true)
+ expect(isCopyShortcut(ev({ ctrlKey: true, shiftKey: true, key: 'ψ', code: 'KeyC' }))).toBe(true)
+ // Plain Ctrl on the same layout still reaches the pty as SIGINT.
+ expect(isCopyShortcut(ev({ ctrlKey: true, key: 'с', code: 'KeyC' }))).toBe(false)
+ })
+
+ it('does not copy when neither the printed nor the physical key is C', () => {
+ expect(isCopyShortcut(ev({ metaKey: true, key: 'ц', code: 'KeyW' }))).toBe(false)
+ })
+
+ it('copies on Cmd+Shift+C too (no competing binding; asserted, not accidental)', () => {
+ expect(isCopyShortcut(ev({ metaKey: true, shiftKey: true }))).toBe(true)
+ })
+
+ it('leaves AltGr combos alone (ctrl+alt+shift+C must not copy)', () => {
+ expect(isCopyShortcut(ev({ ctrlKey: true, altKey: true, shiftKey: true }))).toBe(false)
+ expect(isCopyShortcut(ev({ ctrlKey: true, altKey: true }))).toBe(false)
+ })
+
+ it('copies on Ctrl+Insert (the traditional binding no browser reserves)', () => {
+ expect(isCopyShortcut(ev({ ctrlKey: true, key: 'Insert', code: 'Insert' }))).toBe(true)
+ // Shift+Insert is PASTE, not ours; bare Insert is a plain key.
+ expect(isCopyShortcut(ev({ shiftKey: true, key: 'Insert', code: 'Insert' }))).toBe(false)
+ expect(isCopyShortcut(ev({ key: 'Insert', code: 'Insert' }))).toBe(false)
+ expect(
+ isCopyShortcut(ev({ ctrlKey: true, altKey: true, key: 'Insert', code: 'Insert' }))
+ ).toBe(false)
+ })
+ })
+
+ describe('copyKeyAction', () => {
+ it('copies a copy chord when there is a selection', () => {
+ expect(copyKeyAction(ev({ metaKey: true }), true)).toBe('copy')
+ expect(copyKeyAction(ev({ ctrlKey: true, shiftKey: true }), true)).toBe('copy')
+ })
+
+ it('SWALLOWS Ctrl+Shift+C with no selection — it must never reach the pty as SIGINT', () => {
+ // Regression: falling through to xterm here maps ctrl+c to \x03 and kills the foreground
+ // process, right after the user's selection was cleared by a click. We advertise the chord as
+ // copy, so it can only ever copy or do nothing.
+ expect(copyKeyAction(ev({ ctrlKey: true, shiftKey: true }), false)).toBe('swallow')
+ expect(copyKeyAction(ev({ metaKey: true }), false)).toBe('swallow')
+ expect(copyKeyAction(ev({ ctrlKey: true, key: 'Insert', code: 'Insert' }), false)).toBe(
+ 'swallow'
+ )
+ })
+
+ it('passes plain Ctrl+C through to the pty (SIGINT), selection or not', () => {
+ expect(copyKeyAction(ev({ ctrlKey: true }), true)).toBe('pass')
+ expect(copyKeyAction(ev({ ctrlKey: true }), false)).toBe('pass')
+ })
+ })
diff --cc src/renderer/terminal/terminal-config.ts
index fb6d528b6,02baf5d9a..bc8c98a8d
--- a/src/renderer/terminal/terminal-config.ts
+++ b/src/renderer/terminal/terminal-config.ts
@@@ -1,125 -1,54 +1,177 @@@
+import type { ClientId } from '@shared/presence'
+
+/**
+ * Pure decisions behind the xterm instance in `TerminalNode` — extracted so they can be tested
+ * without an xterm/DOM harness (vitest runs in the node environment; there is no jsdom).
+ *
+ * Everything here belongs to co-attach: one pty, N subscribers. The pty runs at the SMALLEST
+ * subscriber's grid, so a terminal no longer owns its own size — it REPORTS what it could render
+ * and RENDERS what the pty broadcasts back.
+ */
+
+/** A terminal grid. `null` cols/rows on the wire means "subscribed, but not viewing" (parked). */
+export interface TermSize {
+ cols: number
+ rows: number
+}
+
+/**
+ * The size a terminal REPORTS to the pty. Under co-attach the renderer proposes what it could
+ * render (`FitAddon.proposeDimensions()`); the pty then broadcasts the min over all subscribers.
+ * `null` means "unmeasurable right now" (a collapsed / zero-size node) — report NOTHING rather
+ * than a bogus 0×0, which would clamp every other viewer's terminal to nothing.
+ */
+export function reportedSize(proposed: Partial<TermSize> | undefined | null): TermSize | null {
+ if (!proposed) return null
+ const { cols, rows } = proposed
+ if (typeof cols !== 'number' || typeof rows !== 'number') return null
+ if (!Number.isFinite(cols) || !Number.isFinite(rows)) return null
+ return { cols: Math.max(1, Math.floor(cols)), rows: Math.max(1, Math.floor(rows)) }
+}
+
+/**
+ * Are we rendering someone else's (smaller) grid? True when the authoritative size the pty
+ * broadcast is smaller than what this node could fit — then the leftover space is letterboxed.
+ * A solo user is always the min of a one-element set, so this is ALWAYS false for them and the
+ * letterbox styling never engages: their terminal looks exactly as it did before co-attach.
+ */
+export function isLetterboxed(effective: TermSize, fitted: TermSize | null): boolean {
+ if (!fitted) return false
+ return effective.cols < fitted.cols || effective.rows < fitted.rows
+}
+
+/**
+ * Per-node terminal state that must OUTLIVE a mount — because the transport listeners that read it
+ * do. `TerminalNode` wires `onSize` / `onClosed` / `onRecycled` ONCE, in the spawn continuation,
+ * and an adopted (parked) terminal carries those listeners into the next mount without
+ * re-subscribing. Anything they read therefore cannot live in the mounting effect's closure: the
+ * live listener would keep reading MOUNT A's variables while mount B updates its own.
+ *
+ * `fitted` is exactly that: the last size THIS client reported, and the reference the letterbox is
+ * measured against (`letterboxFor`). Park, change the font size, come back — mount B fits a
+ * different grid, and a closure-captured `fitted` would leave the surviving `onSize` listener
+ * comparing the pty's size against the pre-park one, permanently letterboxing a terminal that
+ * should fill its node (or un-letterboxing one that shouldn't).
+ */
+const fittedByNode = new Map<string, TermSize>()
+
+/** Record what this client last REPORTED it can render (called from every applyFit). */
+export function setFittedSize(nodeId: string, size: TermSize): void {
+ fittedByNode.set(nodeId, size)
+}
+
+/** `isLetterboxed` against the CURRENT mount's fit — see `fittedByNode`. */
+export function letterboxFor(nodeId: string, effective: TermSize): boolean {
+ return isLetterboxed(effective, fittedByNode.get(nodeId) ?? null)
+}
+
+/**
+ * Node ids whose next spawn is a recycle RESTART: the co-viewer's session was replaced under it
+ * (someone moved the node into a worktree), and the new xterm prints a one-line reason — the
+ * replacement is a fresh shell in a different folder, so the screen legitimately changes and a
+ * silent reset would just look like a glitch.
+ *
+ * `takeRecycled` consumes the flag, and the spawn path consumes it BEFORE `create()` resolves: a
+ * node that unmounts while its create is in flight abandons that spawn, and a flag left behind
+ * would print "session restarted by another user" on some unrelated mount hours later.
+ */
+const recycledIds = new Set<string>()
+
+export function markRecycled(nodeId: string): void {
+ recycledIds.add(nodeId)
+}
+
+/** Consume the recycle flag: true exactly once per `markRecycled`. */
+export function takeRecycled(nodeId: string): boolean {
+ return recycledIds.delete(nodeId)
+}
+
+/** Drop every cross-mount trace of a node — called when it is permanently deleted. */
+export function forgetNodeTermState(nodeId: string): void {
+ fittedByNode.delete(nodeId)
+ recycledIds.delete(nodeId)
+}
+
+/**
+ * What a `pty:recycled` notice means for this terminal.
+ *
+ * `ready` says a REPLACEMENT session is already registered for the node, so restarting is safe:
+ * our re-create co-attaches to it and we follow the node into its new cwd.
+ *
+ * Without one — the recycler's app died between the `tmux kill-session` and its own `create()`, so
+ * the notice fired on the escape-hatch timeout — a restart would be actively harmful: our create
+ * options still carry the node's OLD cwd (a cwd change is not broadcast to other clients), so we
+ * would spawn `nt-<id>` in the stale directory, and the mover's app, on its return, would
+ * `new-session -A` straight into it. Everyone's node would then claim the worktree path while the
+ * shell sits in the old folder — the exact silent failure the withheld notice exists to prevent.
+ * So we DON'T spawn: the terminal ends, and the user reopens it deliberately if they want a shell.
+ */
+export function recycleAction(info: { ready: boolean } | undefined): 'restart' | 'ended' {
+ return info?.ready ? 'restart' : 'ended'
+}
+
+/**
+ * Should a `pty:resync` payload be painted? The server promises never to send an empty capture,
+ * but the renderer guards anyway: a resync RESETS the emulator, and a screen reset on an empty
+ * payload is unrecoverable (the user loses the screen for nothing), while a skipped repaint is
+ * not (the next byte of output redraws through tmux anyway).
+ */
- export function shouldApplyResync(screen: string | null | undefined): boolean {
++export function shouldApplyResync(screen: string | null | undefined): screen is string {
+ return typeof screen === 'string' && screen.length > 0
+}
+
+ /**
+ * Pure decisions behind the xterm instance in `TerminalNode` — extracted so they can be
+ * tested without an xterm/DOM harness.
+ */
+
+ /** Hard cap on xterm's in-memory scrollback: the cost is per node and one canvas holds many. */
+ export const XTERM_SCROLLBACK_MAX = 10000
+
+ /**
+ * Floor, mirroring the tmux conf's own `history-limit ${Math.max(1000, scrollback)}`. Without it a
+ * user who sets `tmuxScrollback: 100` would get 1000 lines of tmux history but a 100-line xterm
+ * buffer — and xterm is the buffer the user actually scrolls, so the tmux history would be
+ * unreachable.
+ */
+ export const XTERM_SCROLLBACK_MIN = 1000
+
+ /**
+ * How many scrollback lines xterm keeps. Scrolling is xterm's job now (tmux's mouse is off),
+ * so it needs a real scrollback — xterm's default is only 1000 lines. It follows the same
+ * `settings.tmuxScrollback` the user picked for tmux's history-limit, but floored and capped
+ * (same floor as the tmux conf, so the two buffers never disagree at the low end).
+ */
+ export function xtermScrollback(tmuxScrollback: number): number {
+ return Math.min(Math.max(XTERM_SCROLLBACK_MIN, tmuxScrollback), XTERM_SCROLLBACK_MAX)
+ }
+
+ /**
+ * What a freshly-created xterm has to be seeded with when its session resolves:
+ * - `cold-snapshot` — the tmux session is gone (first open after a reboot): replay the persisted
+ * scrollback snapshot, with a "session restored" separator.
+ * - `warm-history` — the tmux session is still alive but this xterm is new (app restart): tmux
+ * only redraws the VISIBLE screen, so pull everything above it from tmux's own history.
+ * - `none` — nothing to seed: a parked terminal keeps its buffer (seeding would duplicate
+ * it), and a brand-new node with an `initialCommand` has no history to restore.
+ */
+ export type AttachReplay = 'cold-snapshot' | 'warm-history' | 'none'
+
+ /** Which seeding (if any) applies to a terminal that just attached. */
+ export function attachReplay(opts: {
+ /** The xterm instance was adopted from the park cache — its buffer is already correct. */
+ parked: boolean
+ /** The tmux session did not exist and was created by this attach. */
+ fresh: boolean
+ /** The node carries a one-shot launch command, i.e. it is being opened for the first time. */
+ hasInitialCommand: boolean
+ }): AttachReplay {
+ if (opts.parked) return 'none'
+ if (!opts.fresh) return 'warm-history'
+ return opts.hasInitialCommand ? 'none' : 'cold-snapshot'
+ }
+
++/**
/**
* Make text captured from tmux (`capture-pane`, LF-separated lines) safe to `term.write()`.
* xterm runs with `convertEol: false` — a bare LF moves down but keeps the column, so raw capture
@@@ -129,15 -58,142 +181,169 @@@ export function toXtermText(text: strin
return text.replace(/\r?\n/g, '\r\n')
}
+/**
+ * Who closed this node, for the "closed by …" overlay. `by` is null when the destroy was not
+ * attributed to a client (a local desktop destroy), and an id we have never seen is a peer who
+ * already left — both degrade to a neutral label rather than blocking the overlay on presence.
+ */
+export function closedByLabel(
+ by: ClientId | null,
+ peers: Record<ClientId, { name: string }>
+): string {
+ if (by === null) return 'another user'
+ return peers[by]?.name || 'another user'
+}
++
+ /**
+ * Drop exactly ONE trailing newline from a tmux capture.
+ * `capture-pane -p -e -S -<n>` emits a trailing LF after its last line. Writing it would leave the
+ * cursor one row BELOW the last captured row: xterm scrolls, the topmost row of the captured
+ * visible screen is pushed into scrollback, and tmux's attach redraw (`\x1b[H\x1b[2J`) then
+ * repaints that same screen — so on every warm reattach the first visible row would appear twice.
+ * Strip on the RAW capture (LF-separated), before `toXtermText` turns the LFs into CRLFs.
+ */
+ export function stripTrailingNewline(text: string): string {
+ return text.replace(/\r?\n$/, '')
+ }
+
+ /**
+ * What a spawn continuation must do when it finds the effect already cleaned up while an async
+ * seed (scrollback snapshot / tmux history) was in flight.
+ * - `proceed` — still mounted: carry on.
+ * - `continue-parked` — the cleanup PARKED this very session (the park entry holds the same live
+ * xterm, PTY client and `cleanups` array). Killing or unsubscribing here would leave the node
+ * permanently dead when it is re-adopted, so the setup must simply finish.
+ * - `teardown` — a real unmount/delete: nothing holds this session, so drop the data
+ * listener and kill the PTY client.
+ */
+ export type DisposalAction = 'proceed' | 'continue-parked' | 'teardown'
+
+ /**
+ * The lifetime of one PTY session as seen by the effect that created it. It is SHARED with the
+ * park entry the effect's cleanup hands the session off to (and with the effect that later adopts
+ * that entry), so `dead` means "this session's xterm/PTY have been torn down for good" no matter
+ * who did it.
+ */
+ export interface SessionLife {
+ dead: boolean
+ }
+
+ /**
+ * The question is NOT "is something parked under this node id?" — an adoption removes the park
+ * entry from the map, so a park followed by a remount looks exactly like "never parked", and
+ * killing there would detach the PTY client of the terminal the user is looking at.
+ * The right question is closure state: "did THIS effect's cleanup hand the session off to a park
+ * entry that is still alive?". If it did, the session lives on (parked, or already re-adopted by a
+ * remount that deliberately re-wires nothing and relies on this continuation to finish the job) —
+ * so the setup must simply complete.
+ */
+ export function disposalAction(opts: {
+ /** The effect cleanup has run. */
+ disposed: boolean
+ /** The park entry THIS effect's cleanup created, if it parked the session (else null). */
+ handedOff: SessionLife | null | undefined
+ }): DisposalAction {
+ if (!opts.disposed) return 'proceed'
+ return opts.handedOff && !opts.handedOff.dead ? 'continue-parked' : 'teardown'
+ }
+
+ /** A gate that holds PTY chunks back until the emulator has been seeded. */
+ export interface DataGate {
+ /** Queue (while closed) or write straight through (once open). */
+ push(chunk: string): void
+ /** Drain the queue in arrival order and switch to pass-through. Idempotent. */
+ open(): void
++ /**
++ * DISCARD the queue and switch to pass-through, returning the number of characters dropped.
++ *
++ * For a redraw that supersedes everything queued: a `pty:resync` repaints the CURRENT screen
++ * from tmux, so every chunk still sitting in the gate predates it — draining them would splice a
++ * stale flood back on top of the fresh screen. The caller returns the dropped bytes to its flow
++ * accounting (they will never reach xterm's write callback, so nothing else would).
++ */
++ reset(): number
+ }
+
+ /**
+ * Buffer PTY output that arrives while an async seed (scrollback snapshot / tmux history) is in
+ * flight. The main process does NOT buffer: it pushes `pty:data:<sid>` on a timer whether or not
+ * anyone is listening, and an IPC event with no listener is simply dropped. So we must subscribe
+ * BEFORE awaiting the seed and park the chunks here — on a warm reattach tmux emits its redraw
+ * within tens of ms, well inside a subprocess/ssh round-trip. Once the seed is written, `open()`
+ * replays the queue in order and later chunks stream straight through.
+ */
+ export function createDataGate(write: (chunk: string) => void): DataGate {
+ let queued: string[] | null = []
+ return {
+ push(chunk) {
+ if (queued) queued.push(chunk)
+ else write(chunk)
+ },
+ open() {
+ const pendingChunks = queued
+ queued = null // pass-through first, so a re-entrant push during the drain stays in order
+ pendingChunks?.forEach(write)
++ },
++ reset() {
++ const dropped = queued?.reduce((n, c) => n + c.length, 0) ?? 0
++ queued = null
++ return dropped
+ }
+ }
+ }
+
+ /** The subset of a KeyboardEvent the copy-shortcut decision looks at. */
+ export interface CopyShortcutEvent {
+ type: string
+ key: string
+ code: string
+ metaKey: boolean
+ ctrlKey: boolean
+ altKey: boolean
+ shiftKey: boolean
+ }
+
+ /**
+ * True for the keydowns that should copy the terminal selection: Cmd+C (mac), Ctrl+Shift+C
+ * (Linux, Windows) and Ctrl+Insert (the traditional terminal binding — the only one of the three
+ * that no browser reserves). Plain Ctrl+C is deliberately NOT one of them — it must keep reaching
+ * the pty as SIGINT.
+ *
+ * The letter is matched on the printed key (`e.key`, so Dvorak/AZERTY follow the letter the user
+ * actually presses) OR on the physical `KeyC` position (`e.code`) — on a non-Latin layout
+ * (Cyrillic 'с', Greek 'ψ') `e.key` is never 'c', and without the fallback an xterm selection
+ * would have no keyboard copy at all (the OS Edit menu only copies the DOM selection, not
+ * xterm's canvas one).
+ *
+ * Cmd+Shift+C is deliberately allowed as well: nothing else binds it and it is a harmless
+ * near-miss of Cmd+C. AltGr combos (which report ctrl+alt) never copy.
+ */
+ export function isCopyShortcut(e: CopyShortcutEvent): boolean {
+ if (e.type !== 'keydown') return false
+ const insert = e.key === 'Insert' || e.code === 'Insert'
+ const letterC = e.key.toLowerCase() === 'c' || e.code === 'KeyC'
+ if (!insert && !letterC) return false
+ if (insert) {
+ // Ctrl+Insert = copy (Shift+Insert is paste — not ours). No meta/alt.
+ return e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey
+ }
+ const cmdC = e.metaKey && !e.ctrlKey && !e.altKey
+ const ctrlShiftC = e.ctrlKey && e.shiftKey && !e.metaKey && !e.altKey
+ return cmdC || ctrlShiftC
+ }
+
+ /**
+ * What a terminal keydown that MIGHT be a copy chord should do:
+ * - `copy` — it is a copy chord and there is a selection: copy it, swallow the key.
+ * - `swallow` — it is a copy chord with NO selection: still swallow it. Critical for Ctrl+Shift+C:
+ * letting it through means xterm maps ctrl+c to `\x03` and SIGINTs the foreground process. We
+ * advertise the chord as "copy", so pressing it right after a click cleared the selection must
+ * never kill the user's process.
+ * - `pass` — not a copy chord: xterm handles it as usual.
+ */
+ export type CopyKeyAction = 'copy' | 'swallow' | 'pass'
+
+ export function copyKeyAction(e: CopyShortcutEvent, hasSelection: boolean): CopyKeyAction {
+ if (!isCopyShortcut(e)) return 'pass'
+ return hasSelection ? 'copy' : 'swallow'
+ }
diff --cc src/renderer/terminal/transport.ts
index e110a7c12,5f8cd5791..4d7d21fc5
--- a/src/renderer/terminal/transport.ts
+++ b/src/renderer/terminal/transport.ts
@@@ -22,19 -16,15 +22,27 @@@ export interface TerminalTransport
setFlow(sessionId: string, resume: boolean): void
/** Detaches the client; with tmux the underlying session survives. */
kill(sessionId: string): void
- /** Permanently ends a node's persistent session. */
+ /**
+ * Permanently ends a node's persistent session because the node is being DELETED (× / delete).
+ * Co-viewers are told "closed by <name>" and must never respawn it.
+ */
destroy(persistKey: string): void
+ /**
+ * Ends a node's persistent session so the SAME node id can respawn in a new cwd ("move into
+ * worktree"). The tmux kill is identical to `destroy` — without it the respawn would just
+ * reattach the old session, keeping the old working directory — but the INTENT is the opposite:
+ * the node is not going anywhere. Co-viewers therefore get `onRecycled` (restart, re-attach to
+ * the replacement session), never the permanent, un-respawnable closed state.
+ */
+ recycle(persistKey: string): void
++
+ /**
+ * The persistent session's scrollback (its tmux history + the visible screen), used to hydrate a
+ * fresh xterm on a warm reattach. Part of the transport because the session — and therefore its
+ * history — lives wherever the transport points: in the local tmux server for LocalTransport, on
+ * the HOST for RemoteTransport. Resolves with '' when there is nothing to hydrate from.
+ */
+ captureHistory(persistKey: string): Promise<string>
/** Listens for output; returns an unsubscribe function. */
onData(sessionId: string, listener: (data: string) => void): () => void
/** Fires when the session closes; returns an unsubscribe function. */
diff --cc src/shared/types.ts
index 121652a71,5b28463ff..f33d77fdc
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@@ -2,9 -2,8 +2,9 @@@
import type { CloneProgress } from './clone-url'
import type { NormalizedAgentEvent } from './agents/normalize'
- import type { AgentId, PromptInjectionMode } from './agents/config'
+ import type { AgentId, AgentPermissionMode, PromptInjectionMode } from './agents/config'
import type { GroupWorktree } from './worktree'
+import type { ClientId, PeerDiff, PeerIdentity, PeerState } from './presence'
export interface PtyCreateOptions {
shell?: string