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
fix(presence): stale cursor on project switch, per-node selector churn, name spoofing
enese9e27e73a7f5
diff --git a/docs/team-presence.md b/docs/team-presence.mdindex 58076b29a..41c2be009 100644--- a/docs/team-presence.md+++ b/docs/team-presence.md@@ -106,7 +106,18 @@ peer table and fans out, and applies no policy.| 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.+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-attachdiff --git a/src/core/presence/hub.test.ts b/src/core/presence/hub.test.tsindex e0b1d9505..4bba3af09 100644--- a/src/core/presence/hub.test.ts+++ b/src/core/presence/hub.test.ts@@ -154,10 +154,13 @@ describe('PresenceHub signals', () => {it('setCursor / setFocus / setChat / setProject patch the peer and broadcast an update diff', () => {const hub = new PresenceHub()hub.join(1, 'browser')+ // The project comes FIRST, as it does in the app (Canvas reports the canvas it loaded, then+ // the pointer starts moving on it) — a later setProject would drop the cursor with the old+ // canvas it belongs to (see the project-switch test below).+ hub.setProject(1, 'web')hub.setCursor(1, { x: 12.4, y: -3 })hub.setFocus(1, 'node-a')hub.setChat(1, 'hey')- hub.setProject(1, 'web')expect(hub.peers()[0]).toMatchObject({cursor: { x: 12.4, y: -3 },focus: 'node-a',@@ -165,10 +168,10 @@ describe('PresenceHub signals', () => {projectId: 'web'})expect(diffs().slice(-4)).toEqual([+ { op: 'update', clientId: 1, patch: { projectId: 'web' } },{ op: 'update', clientId: 1, patch: { cursor: { x: 12.4, y: -3 } } },{ op: 'update', clientId: 1, patch: { focus: 'node-a' } },- { op: 'update', clientId: 1, patch: { chat: 'hey' } },- { op: 'update', clientId: 1, patch: { projectId: 'web' } }+ { op: 'update', clientId: 1, patch: { chat: 'hey' } }])hub.setCursor(1, null)hub.setChat(1, null)@@ -191,6 +194,31 @@ describe('PresenceHub signals', () => {expect(hub.peers()).toHaveLength(1)})+ // A project switch can be keyboard-driven (⌘1/⌘2, the palette) with the mouse parked, so no+ // pointermove follows it and the renderer's sampler never sends a new position. Leaving the old+ // cursor in the table would draw this peer on the NEW canvas at the OLD canvas's flow+ // coordinates — a ghost pointing at nothing, indefinitely, for everyone on that project.+ it('setProject drops the cursor with the old canvas (one coherent diff carries both)', () => {+ const hub = new PresenceHub()+ hub.join(1, 'browser')+ hub.setProject(1, 'web')+ hub.setCursor(1, { x: 400, y: 250 })++ hub.setProject(1, 'api')+ expect(hub.peers()[0]).toMatchObject({ projectId: 'api', cursor: null })+ // ONE diff, carrying both changes: a peer applying it can never see the new project with the+ // stale cursor, in either order.+ expect(diffs().at(-1)).toEqual({+ op: 'update',+ clientId: 1,+ patch: { projectId: 'api', cursor: null }+ })++ // Nothing to drop → the patch stays minimal (no redundant cursor: null on every switch).+ hub.setProject(1, 'web')+ expect(diffs().at(-1)).toEqual({ op: 'update', clientId: 1, patch: { projectId: 'web' } })+ })+it('drops garbage input instead of broadcasting it (NaN cursor, over-long chat, unknown client)', () => {const hub = new PresenceHub()hub.join(1, 'browser')@@ -518,10 +546,12 @@ describe('registerIpc', () => {const res = fake.handlers[IPC.presenceHello](4, { name: 'Ada', color: PRESENCE_COLORS[2] })expect(res).toMatchObject({ clientId: 4 })+ // Project first, cursor after — the app's own order (a cursor only means something once the+ // canvas it was sampled on is known; a later switch drops it).+ fake.senderListeners[IPC.presenceProject](4, 'web')fake.senderListeners[IPC.presenceCursor](4, { x: 5, y: 6 })fake.senderListeners[IPC.presenceFocus](4, 'node-z')fake.senderListeners[IPC.presenceChat](4, 'yo')- fake.senderListeners[IPC.presenceProject](4, 'web')expect(hub.peers()[0]).toMatchObject({name: 'Ada',cursor: { x: 5, y: 6 },diff --git a/src/core/presence/hub.ts b/src/core/presence/hub.tsindex 65e833be9..b24ad0c38 100644--- a/src/core/presence/hub.ts+++ b/src/core/presence/hub.ts@@ -225,7 +225,18 @@ export class PresenceHub {typeof projectId === 'string' && projectId ? capCodePoints(projectId, REF_MAX_LEN) : nullif (peer.projectId === next) returnpeer.projectId = next- this.emit({ op: 'update', clientId, patch: { projectId: next } })+ const patch: Partial<Omit<PeerState, 'clientId'>> = { projectId: next }+ // The cursor belonged to the OLD canvas. A project switch can be keyboard-driven (⌘1/⌘2, the+ // palette) with the mouse parked, so no pointermove follows it and the renderer's sampler+ // never sends a new position — the stale coordinates would then be drawn on the NEW project's+ // canvas, forever, for everyone on it. Drop it HERE (the one place that knows the canvas+ // changed) and carry both changes in ONE diff, so no peer can ever apply the new project with+ // the old cursor still attached.+ if (peer.cursor !== null) {+ peer.cursor = null+ patch.cursor = null+ }+ this.emit({ op: 'update', clientId, patch })}/** Someone wrote into a node's terminal. Throttled to 1 broadcast / TYPING_THROTTLE_MS perdiff --git a/src/renderer/state/presence.test.ts b/src/renderer/state/presence.test.tsindex b7684a308..2d1c52df9 100644--- a/src/renderer/state/presence.test.ts+++ b/src/renderer/state/presence.test.ts@@ -415,6 +415,39 @@ describe('reportFocus / reportProject', () => {})})+describe('selectFocusedFaces: the alone / disconnected fast path', () => {+ // This selector runs once PER MOUNTED NODE on EVERY store write — 40 nodes x 5 peers x 20 Hz is+ // ~4k runs/s, each allocating a filtered array and a mapped one for a canvas that, most of the+ // time, has nobody else on it. When there is provably no one to draw, bail out to ONE shared+ // empty array (also stable identity → useShallow bails out too).+ it('returns the SAME empty array while I am alone, or while myId is unknown', async () => {+ vi.stubGlobal('localStorage', memStorage(STORED_ME))+ const api = fakePresenceApi({ clientId: 7, peers: [peer(7, { projectId: 'web' })] })+ const { connectPresence, usePresence, selectFocusedFaces } = await import('./presence')++ // Before hello resolves: myId is null, so nothing may be drawn at all.+ const empty = selectFocusedFaces(usePresence.getState(), 'node-a', 'web')+ expect(empty).toEqual([])++ const stop = connectPresence()+ await vi.waitFor(() => expect(usePresence.getState().myId).toBe(7))++ // Connected, but the table holds only me → still nobody to chip, same array object.+ const alone = selectFocusedFaces(usePresence.getState(), 'node-a', 'web')+ expect(alone).toBe(empty)++ // A peer arrives → the selector does its real work again.+ api.emitPeer({ op: 'join', peer: peer(8, { name: 'Ada', projectId: 'web', focus: 'node-a' }) })+ const faces = selectFocusedFaces(usePresence.getState(), 'node-a', 'web')+ expect(faces.map((f) => f.name)).toEqual(['Ada'])++ // …and when they leave, back to the shared empty array.+ api.emitPeer({ op: 'leave', clientId: 8 })+ expect(selectFocusedFaces(usePresence.getState(), 'node-a', 'web')).toBe(empty)+ stop()+ })+})+describe('selectFocusedFaces (the node-header chips — one per node, so cursor traffic must not re-render them)', () => {it('projects the focused peers of THIS project and keeps object identity across cursor updates', async () => {vi.stubGlobal('localStorage', memStorage(STORED_ME))diff --git a/src/renderer/state/presence.ts b/src/renderer/state/presence.tsindex 4c11b5e5d..51aa3659a 100644--- a/src/renderer/state/presence.ts+++ b/src/renderer/state/presence.ts@@ -190,6 +190,10 @@ export function selectFaces(s: PresenceStore): PeerFace[] {return faces}+/** The one empty result every "nobody to draw" path returns — a shared, frozen constant, so the+ * common case allocates NOTHING and its identity is stable across calls (useShallow bails out). */+const NO_FACES: PeerFace[] = []+/** What ONE node's header chips draw: the peers (never me, never off-project) focused on that node,* projected to the same cursor-immune face objects as the facepile.*@@ -197,13 +201,23 @@ export function selectFaces(s: PresenceStore): PeerFace[] {* `applyDiff` rebuilds a peer's whole PeerState object on every cursor patch (~20/s per peer). A* selector returning PeerStates would therefore hand every node a fresh object 20×/s and re-render* every terminal on the canvas — even under `useShallow`, which compares the ELEMENTS. Faces are- * reused objects, so a moving cursor changes nothing here and every strip bails out. */+ * reused objects, so a moving cursor changes nothing here and every strip bails out.+ *+ * The early-out is the other half of that: this runs once per MOUNTED NODE on every store write+ * (40 nodes × 5 peers × 20 Hz ≈ 4k runs/s), and each run would otherwise allocate a filtered array+ * plus a mapped one — ~20k throwaway arrays/s — even on a canvas nobody else is on. When there is+ * provably no one to chip (hello unresolved, or the table holds only me), return NO_FACES. */export function selectFocusedFaces(s: PresenceStore,nodeId: string,projectId: string | null): PeerFace[] {- return selectFocused(s, nodeId, projectId).map(faceFor)+ // myId === null → the selectors draw nobody (see NEVER MY OWN PEER); < 2 peers → the table holds+ // at most me. Either way there is nothing to compute, which is the overwhelmingly common case.+ if (s.myId === null || Object.keys(s.peers).length < 2) return NO_FACES+ const focused = selectFocused(s, nodeId, projectId)+ if (focused.length === 0) return NO_FACES+ return focused.map(faceFor)}/** Sent when the user has not named themselves yet. It claims NOTHING — sanitizeIdentity fallsdiff --git a/src/server/platform-server.ts b/src/server/platform-server.tsindex 9b8a7b3a6..1bb0d4b93 100644--- a/src/server/platform-server.ts+++ b/src/server/platform-server.ts@@ -120,8 +120,22 @@ export class ServerPlatform implements CorePlatform {detach(uiId: number): void {this.sinks.delete(uiId)- // v1 is single-UI: every paused session belonged to the departing connection, so drop the- // whole backpressure map to avoid a stale pause leaking into the next attach.+ // KNOWN WRONG, and knowingly left so — do not read this as a design.+ //+ // This clears the backpressure flags of EVERY connection, not just the departing one. It was+ // written when the Server Edition was single-UI ("every paused session belonged to the+ // departing connection"), which team presence has made false: two browsers are now a normal+ // configuration, and browser B disconnecting drops browser A's pause flags. The consequence is+ // bounded — a session A had paused is treated as unpaused, so the next high-water send+ // re-pauses it (sendTo re-asserts the pause on EVERY high send, not just the rising edge) —+ // but until then A can take one burst it should not have.+ //+ // The real fix is not a smaller patch here: `paused` is keyed by sessionId ALONE, so it cannot+ // represent "paused for A, flowing for B" at all, and neither can `flowController`, which+ // pauses the ONE tmux client behind that session. Stage 2 rekeys the map to (clientId,+ // sessionId) and decides the pty-side policy (pause when ANY viewer is behind); a half-fix here+ // — e.g. only clearing this uiId's entries — would silently leak a stale pause into the next+ // attach, which is worse than the over-clear.this.paused.clear()}diff --git a/src/shared/presence.test.ts b/src/shared/presence.test.tsindex c4e4791d5..17cd61d29 100644--- a/src/shared/presence.test.ts+++ b/src/shared/presence.test.ts@@ -107,6 +107,38 @@ describe('sanitizeIdentity', () => {expect(out).not.toContain('�')})+ // Names are unverified BY DESIGN (anyone may claim any name), but they must not be able to+ // MISRENDER: this is the one untrusted-input door into every peer's facepile and cursor label.+ // The hostile characters are written as escapes on purpose - pasted raw, they would reorder this+ // very source file in your editor, which is exactly the attack.+ it('strips control characters, newlines and bidi overrides (no visual name spoofing)', () => {+ const RLO = '' // RIGHT-TO-LEFT OVERRIDE: displays everything after it backwards+ // Stored as "Ada" + RLO + "gnihsihp", this DISPLAYS as "Adaphishing" in every facepile.+ expect(+ sanitizeIdentity({ name: `Ada${RLO}gnihsihp`, color: PRESENCE_COLORS[0] }, fallback).name+ ).toBe('Adagnihsihp')++ // The whole bidi family - marks, embeddings, overrides, isolates - plus the zero-width space+ // and the BOM.+ const bidi = 'ABC'+ expect(sanitizeIdentity({ name: bidi, color: PRESENCE_COLORS[0] }, fallback).name).toBe('ABC')++ // C0/C1 controls and newlines (a multi-line name would break out of its one-line chip).+ // Ordinary spaces INSIDE the name survive - only the control characters go.+ expect(+ sanitizeIdentity({ name: 'Ada\n\r\tLove lace', color: PRESENCE_COLORS[0] }, fallback).name+ ).toBe('AdaLove lace')++ // Nothing left after stripping -> the fallback, never an empty label.+ expect(+ sanitizeIdentity({ name: `${RLO}\n`, color: PRESENCE_COLORS[0] }, fallback).name+ ).toBe(fallback.name)++ // Legitimate names (spaces, accents, CJK, emoji) are untouched.+ const real = 'Enes Kırca 库 🐙'+ expect(sanitizeIdentity({ name: real, color: PRESENCE_COLORS[0] }, fallback).name).toBe(real)+ })+it('trims after truncating, so a cap landing on a space leaves no trailing space', () => {const name = 'a'.repeat(NAME_MAX_LEN - 1) + ' tail'const out = sanitizeIdentity({ name, color: PRESENCE_COLORS[0] }, fallback).namediff --git a/src/shared/presence.ts b/src/shared/presence.tsindex 43350903d..812419f24 100644--- a/src/shared/presence.ts+++ b/src/shared/presence.ts@@ -116,15 +116,30 @@ export function capCodePoints(text: string, max: number): string {return bounded.slice(0, max).join('')}-/** Cap a name at NAME_MAX_LEN code points. Trim runs again AFTER the cut, so a truncation- * landing on a space doesn't leave a trailing one. */+/**+ * Characters a display name may never contain. Names are UNVERIFIED by design (anyone may claim+ * any name), but they must not be able to MISRENDER: a bidi override (U+202E) reverses everything+ * after it, so a name stored as "Ada" + U+202E + "gnihsihp" DISPLAYS as "Adaphishing" — one peer+ * visually impersonating another with a string that inspects as something else. The marks/isolates+ * (U+200B-200F, U+2066-2069, U+FEFF) do the same job more quietly, and C0/C1 controls (newlines,+ * NUL, escapes) break a name out of its one-line chip. Strip them all; ordinary spaces, accents,+ * CJK and emoji are untouched.+ */+// eslint-disable-next-line no-control-regex+const UNSAFE_NAME_CHARS = /[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g++/** Cap a name at NAME_MAX_LEN code points, after stripping the characters that could spoof or+ * break the rendering of another peer's name (UNSAFE_NAME_CHARS). Trim runs again AFTER the cut,+ * so a truncation landing on a space doesn't leave a trailing one. */function capName(name: string): string {- return capCodePoints(name.trim(), NAME_MAX_LEN).trim()+ return capCodePoints(name.replace(UNSAFE_NAME_CHARS, '').trim(), NAME_MAX_LEN).trim()}-/** Coerce an untrusted {name, color} off the wire into a safe identity. Names are unverified- * (anyone can claim any name — documented trade-off) but they are length-capped, and the color- * must be one of ours so it can never be injected into a style attribute as arbitrary text. */+/** Coerce an untrusted {name, color} off the wire into a safe identity — THE one door for+ * client-supplied identity. Names are unverified (anyone can claim any name — documented+ * trade-off) but they are length-capped and stripped of control/bidi characters (capName), so a+ * peer cannot visually spoof another's name, and the color must be one of ours so it can never be+ * injected into a style attribute as arbitrary text. */export function sanitizeIdentity(raw: unknown, fallback: PeerIdentity): PeerIdentity {const r = (raw ?? {}) as Partial<PeerIdentity>const name = typeof r.name === 'string' ? capName(r.name) : ''