Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
perf(presence): publish focus only when someone can see it + fix stale docs
enesebe3d0c1512a
diff --git a/docs/team-presence.md b/docs/team-presence.mdindex 240c0cd23..82965996f 100644--- a/docs/team-presence.md+++ b/docs/team-presence.md@@ -137,7 +137,11 @@ Changes:1. **`Session.webContentsId: number | null` → `subscribers: Set<ClientId>`**(`pty-manager.ts:251`). `flush()` (`:780`) fans out to the subscriber set instead of- unicasting. Relay `onData` sinks live in the same set — two paths collapse into one.+ 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.@@ -208,10 +212,17 @@ Three rules:### Typing attribution — and why it is server-side-`cast()` currently discards the sender (`platform-server.ts:136`, `void uiId`). We route-`pty:write` through the existing `handleWithSender` seam (`:55`), so the handler can stamp-`session.lastWriter = {clientId, at}`. The hub broadcasts that, throttled to 1/500 ms per node;-the badge decays after ~2 s.+`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** specificallybecause of mobile: when the phone writes over the relay, the sender is already known as a@@ -272,6 +283,14 @@ Its limits are real (see Known risks): the tombstone is in-memory, so it lives ethe core process. The complete fix is Stage 3's canvas-delete **mutation**, which removes the nodefrom every canvas so no client is left holding one to re-create.+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 syncNode edits broadcast as mutations so cursors don't hover over stale geometry.@@ -422,9 +441,12 @@ read-only guests, per-user settings.- Server e2e with **two** WS clients: hello → snapshot, cursor fan-out, echo suppression, leaveon disconnect.- **Co-attach** (delivered): two clients, one `persistKey` → a single spawn; both receive output;- min-size resize; one client's backpressure does not stall the other, and a client that falls 8 MB- behind is dropped and redrawn from tmux rather than buffered forever. →- `src/core/pty-coattach.test.ts` (44 tests), `src/core/pty-size.test.ts`,+ 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 decaysagainst local receipt time and is fed only by live diffs. → `src/core/pty-typing.test.ts`,diff --git a/src/renderer/state/presence.test.ts b/src/renderer/state/presence.test.tsindex d2c28867e..8099330ab 100644--- a/src/renderer/state/presence.test.ts+++ b/src/renderer/state/presence.test.ts@@ -361,6 +361,51 @@ describe('project scoping (a peer on another canvas is never drawn on mine)', ()})describe('reportFocus / reportProject', () => {+ /** Two peers in the table — me and somebody else. Focus is only published when there IS somebody+ * to draw the chip: alone, the cast is pure cost (see the solo test below). */+ async function withPeer() {+ const mod = await import('./presence')+ mod.usePresence.setState({ myId: 7, peers: { 7: peer(7), 8: peer(8) } })+ return mod+ }++ it('publishes NOTHING while alone: a hover must not cost an IPC round-trip', async () => {+ vi.stubGlobal('localStorage', memStorage(STORED_ME))+ const api = fakePresenceApi()+ const { reportFocus, releaseFocus, usePresence } = await import('./presence')+ usePresence.setState({ myId: 7, peers: { 7: peer(7) } }) // just me++ reportFocus('node-a') // hover-dwell into a terminal+ releaseFocus('node-a') // …and out again+ expect(api.calls.filter((c) => c[0] === 'focus')).toEqual([])++ // A peer shows up: focus is published from the next hover on, and its retraction with it.+ usePresence.setState({ peers: { 7: peer(7), 8: peer(8) } })+ reportFocus('node-a')+ releaseFocus('node-a')+ expect(api.calls.filter((c) => c[0] === 'focus')).toEqual([+ ['focus', 'node-a'],+ ['focus', null]+ ])+ })++ it('still retracts a published focus after the last peer leaves (never a stale chip)', async () => {+ vi.stubGlobal('localStorage', memStorage(STORED_ME))+ const api = fakePresenceApi()+ const { reportFocus, releaseFocus, usePresence } = await import('./presence')+ usePresence.setState({ myId: 7, peers: { 7: peer(7), 8: peer(8) } })+ reportFocus('node-a')++ // Peer 8 closed its tab while we sit in the node. The clear is NOT gated: the hub still holds+ // our focus, and the next peer to join would get it in the snapshot and chip a node we left.+ usePresence.setState({ peers: { 7: peer(7) } })+ releaseFocus('node-a')+ expect(api.calls.filter((c) => c[0] === 'focus')).toEqual([+ ['focus', 'node-a'],+ ['focus', null]+ ])+ })+it('send only on change (a terminal re-focusing the same node, or a tab switch back, must not spam the wire)', async () => {vi.stubGlobal('localStorage',@@ -369,7 +414,7 @@ describe('reportFocus / reportProject', () => {}))const api = fakePresenceApi()- const { reportFocus, reportProject } = await import('./presence')+ const { reportFocus, reportProject } = await withPeer()reportFocus('node-a')reportFocus('node-a')reportFocus(null)@@ -393,7 +438,7 @@ describe('reportFocus / reportProject', () => {it('releaseFocus only clears the focus THIS node published (a leaving node cannot steal the next one)', async () => {vi.stubGlobal('localStorage', memStorage(STORED_ME))const api = fakePresenceApi()- const { reportFocus, releaseFocus } = await import('./presence')+ const { reportFocus, releaseFocus } = await withPeer()reportFocus('node-a')// node-b took over (its dwell fired before node-a's unmount cleanup ran) — node-a going awaydiff --git a/src/renderer/state/presence.ts b/src/renderer/state/presence.tsindex acd20fd58..e27762d7d 100644--- a/src/renderer/state/presence.ts+++ b/src/renderer/state/presence.ts@@ -443,13 +443,31 @@ export function connectPresence(): () => void {let lastFocus: string | null = nulllet lastProject: string | null = null-/** Publish "I am working in this node" (null = nowhere). Deduped; safe to call before connect. */+/**+ * Publish "I am working in this node" (null = nowhere). Deduped; safe to call before connect.+ *+ * ALONE, IT PUBLISHES NOTHING. A focus only exists to be drawn on somebody else's canvas, and every+ * terminal hover-dwell / leave calls this — so with no peers the cast is pure cost (an IPC+ * round-trip and a hub write per hover, on a path a solo user is on constantly). Same guard+ * PtyManager.write already uses for typing attribution: presence is FREE when you are by yourself.+ *+ * The CLEAR is deliberately not gated: `lastFocus` is only ever non-null because a publish went out+ * while peers existed, and if the last peer leaves while we sit in that node, the hub still holds+ * our focus — the next peer to join would receive it in its snapshot and chip a node we left long+ * ago. So a retraction always goes out (the dedup above makes it a no-op when we never published).+ */export function reportFocus(nodeId: string | null): void {if (lastFocus === nodeId) return+ if (nodeId !== null && !hasPeers()) returnlastFocus = nodeIdwindow.nodeTerminal.presence.focus(nodeId)}+/** Is anyone else connected? (The table includes me, so "somebody else" is > 1.) */+function hasPeers(): boolean {+ return Object.keys(usePresence.getState().peers).length > 1+}+/** "This node is no longer where I work" — the counterpart of reportFocus(nodeId), for a node that* is losing focus (mouse left, unmounted). It clears the focus ONLY if this node is the one we* actually published: a node's leave/unmount can land AFTER the next node's enter (the mouse moves