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): the rate limiter may only drop self-correcting signals
enese01f7d90cf39
diff --git a/src/core/presence/hub.test.ts b/src/core/presence/hub.test.tsindex 4bba3af09..8bfd06219 100644--- a/src/core/presence/hub.test.ts+++ b/src/core/presence/hub.test.ts@@ -537,6 +537,105 @@ describe('rate limiting (a hostile tab must not degrade the room)', () => {})})+describe('rate limiting must never drop an EDGE signal (a lost clear is lost state, not a lost frame)', () => {+ beforeEach(() => {+ vi.useFakeTimers()+ vi.setSystemTime(0)+ })++ /** Drain a channel's bucket at t=0 with casts that carry a value (the flood-capable shape). */+ function drain(channel: string, cast: (i: number) => void): void {+ for (let i = 0; i < PRESENCE_RATE_BUDGETS[channel].burst + 50; i++) cast(i)+ }++ // THE STUCK BUBBLE: sendChat fires per keystroke, so a held key (X11 repeats ~25/s, macOS with+ // KeyRepeat=0 far faster) drains the chat bucket. On release the renderer retracts with+ // chat(null) — and if THAT is dropped, the hub keeps the last accepted line and every peer keeps+ // a chat bubble pinned to a cursor forever. The renderer has no ack and no retry: it already+ // believes it retracted.+ it('a chat retraction lands (and is broadcast) with the chat bucket drained', () => {+ const hub = new PresenceHub()+ hub.registerIpc()+ hub.join(1, 'browser')++ drain(IPC.presenceChat, (i) => fake.senderListeners[IPC.presenceChat](1, `msg ${i}`))+ const stuck = hub.peers()[0].chat+ expect(stuck).not.toBeNull() // the bubble a peer is currently showing++ const before = diffs().length+ fake.senderListeners[IPC.presenceChat](1, null) // the retraction — must NOT be droppable+ expect(hub.peers()[0].chat).toBeNull()+ expect(diffs().slice(before)).toEqual([{ op: 'update', clientId: 1, patch: { chat: null } }])+ })++ it('a cursor retraction lands with the cursor bucket drained (mouse-leave / blur)', () => {+ const hub = new PresenceHub()+ hub.registerIpc()+ hub.join(1, 'browser')++ drain(IPC.presenceCursor, (i) => fake.senderListeners[IPC.presenceCursor](1, { x: i, y: 0 }))+ expect(hub.peers()[0].cursor).not.toBeNull()++ const before = diffs().length+ fake.senderListeners[IPC.presenceCursor](1, null)+ expect(hub.peers()[0].cursor).toBeNull()+ expect(diffs().slice(before)).toEqual([{ op: 'update', clientId: 1, patch: { cursor: null } }])+ })++ it('a focus release lands with the focus bucket drained (else a ghost chip stays on the node)', () => {+ const hub = new PresenceHub()+ hub.registerIpc()+ hub.join(1, 'browser')++ drain(IPC.presenceFocus, (i) => fake.senderListeners[IPC.presenceFocus](1, `node-${i}`))+ expect(hub.peers()[0].focus).not.toBeNull()++ const before = diffs().length+ fake.senderListeners[IPC.presenceFocus](1, null)+ expect(hub.peers()[0].focus).toBeNull()+ expect(diffs().slice(before)).toEqual([{ op: 'update', clientId: 1, patch: { focus: null } }])+ })++ // Exempting the clears cannot become a flood vector, and this is WHY: the setters ignore an+ // unchanged value, so a clear only broadcasts once — the next one needs an intervening non-null+ // cast to re-arm it, and THAT one is bucketed. So the clear's broadcast rate is bounded by the+ // (rate-limited) value casts, not by the client's send loop.+ it('an exempt clear is self-limiting: a null flood broadcasts at most once', () => {+ const hub = new PresenceHub()+ hub.registerIpc()+ hub.join(1, 'browser')+ fake.senderListeners[IPC.presenceCursor](1, { x: 1, y: 1 })++ const before = diffs().length+ for (let i = 0; i < 5000; i++) fake.senderListeners[IPC.presenceCursor](1, null)+ for (let i = 0; i < 5000; i++) fake.senderListeners[IPC.presenceChat](1, null)+ for (let i = 0; i < 5000; i++) fake.senderListeners[IPC.presenceFocus](1, null)+ expect(diffs().length - before).toBe(1) // the one cursor clear; chat/focus were already null+ })++ // THE WRONG PROJECT: presence:project is a state switch, not a sample — nothing supersedes a+ // dropped one, and the renderer has already recorded it as sent. A dropped switch leaves the hub+ // (and therefore every teammate's canvas, chips and facepile) on the project you LEFT, forever.+ // The budget must be far out of reach of any human input path.+ it('a project switch survives every rate a human input path can produce', () => {+ const hub = new PresenceHub()+ hub.registerIpc()+ hub.join(1, 'browser')+ const budget = PRESENCE_RATE_BUDGETS[IPC.presenceProject]+ expect(budget.perSec).toBeGreaterThanOrEqual(20) // > any key-repeat rate (X11 ~25/s is deduped)+ expect(budget.burst).toBeGreaterThanOrEqual(60) // ~30 s of frantic ⌘1/⌘2 switching, back to back++ // 30 distinct switches inside one second — far past anything a person can click or type — and+ // the last one still lands, because the hub must always know which canvas you are on.+ for (let i = 0; i < 30; i++) {+ vi.setSystemTime(i * 33)+ fake.senderListeners[IPC.presenceProject](1, `p-${i}`)+ }+ expect(hub.peers()[0].projectId).toBe('p-29')+ expect(diffs().at(-1)).toMatchObject({ op: 'update', clientId: 1, patch: { projectId: 'p-29' } })+ })+})+describe('registerIpc', () => {it('registers hello as a sender-aware request and the three signals as sender-aware casts', () => {const hub = new PresenceHub()diff --git a/src/core/presence/hub.ts b/src/core/presence/hub.tsindex b24ad0c38..086147705 100644--- a/src/core/presence/hub.ts+++ b/src/core/presence/hub.ts@@ -38,7 +38,12 @@ export const TYPING_THROTTLE_MS = 500* - cursor: 20/s, exactly the renderer's CURSOR_MIN_INTERVAL_MS (50 ms) throttle, with 2 s of* burst for scheduling jitter,* - chat: one cast per keystroke — faster than any human types,- * - focus / project: one per node hover / tab switch — orders of magnitude of headroom,+ * - focus: one per node hover — orders of magnitude of headroom,+ * - project: one per tab switch. DELIBERATELY generous (see isClearingCast): a dropped project+ * switch is not a lost frame but LOST STATE — the hub, and so every teammate's canvas, chips+ * and facepile, would stay on the project you left, forever. A human input path cannot come+ * near this: holding ⌘1 repeats the SAME id (the renderer dedups it, and the hub's setter+ * ignores an unchanged value anyway), so only DISTINCT switches spend a token.* - hello: sent at connect (and once more when the user names themselves).* Excess casts are DROPPED silently. Never disconnect: an honest client that hits a burst edge* (a wedged event loop suddenly flushing) would lose a frame, not its session — and the next@@ -48,10 +53,36 @@ export const PRESENCE_RATE_BUDGETS: Record<string, { perSec: number; burst: numb[IPC.presenceCursor]: { perSec: 20, burst: 40 },[IPC.presenceChat]: { perSec: 25, burst: 50 },[IPC.presenceFocus]: { perSec: 10, burst: 20 },- [IPC.presenceProject]: { perSec: 5, burst: 10 },+ [IPC.presenceProject]: { perSec: 20, burst: 60 },[IPC.presenceHello]: { perSec: 2, burst: 5 }}+/**+ * Does this cast CLEAR the client's state (a null cursor, a closed chat, a released focus)?+ *+ * Such a cast is EXEMPT from the bucket, because a bucket may only ever drop a signal whose loss+ * is self-correcting. A cursor sample is superseded by the next one, so dropping it costs a frame.+ * A clear is an EDGE: nothing supersedes it, no client acks it, nothing re-announces it — the+ * renderer has already recorded "I retracted that" (publishedRef / lastFocus) and will never send+ * it again. Drop one and the hub keeps the last value it accepted: a chat bubble pinned to a+ * teammate's cursor forever, a ghost cursor, a "who is here" chip on a node nobody is in.+ * Reachable in practice: a held key at X11's ~25/s repeat drains the chat bucket, and the keyup+ * retraction is the very next cast.+ *+ * And it CANNOT become a flood vector, by construction: the setters ignore an unchanged value, so+ * a clear broadcasts at most ONCE — re-arming it takes an intervening value cast, which IS bucketed.+ * The clears' fan-out rate is therefore bounded by the (rate-limited) value casts, not by the+ * client's send loop; an unlimited null flood is a no-op loop inside the hub.+ *+ * The predicates mirror each setter's own "is this null?" rule exactly — keep them in sync.+ */+function isClearingCast(channel: string, payload: unknown): boolean {+ if (channel === IPC.presenceCursor) return !payload+ if (channel === IPC.presenceChat) return typeof payload !== 'string'+ if (channel === IPC.presenceFocus) return typeof payload !== 'string' || payload === ''+ return false+}+// Relay peers (phones) have no webContents id and no ServerPlatform uiId, so their ClientIds are// minted here from a high range that can never collide with either (both start small and count up).let nextRelayId = 1_000_000@@ -130,10 +161,14 @@ export class PresenceHub {* peer); rate-limiting those would throttle the app's own trusted plumbing. The entry point is* the exact seam where an untrusted client's message becomes hub state, which is what needs a* budget — and it is the one place ALL shells funnel through, so no shell can forget it.+ *+ * A CLEARING cast (see isClearingCast) is exempt and spends no token: the bucket may only drop+ * signals whose loss is self-correcting, and a clear is an edge — losing it is lost state.*/- private allow(clientId: ClientId, channel: string): boolean {+ private allow(clientId: ClientId, channel: string, payload?: unknown): boolean {const budget = PRESENCE_RATE_BUDGETS[channel]if (!budget) return true+ if (isClearingCast(channel, payload)) return trueconst key = `${clientId}:${channel}`const now = Date.now()const prev = this.buckets.get(key)@@ -280,23 +315,29 @@ export class PresenceHub {if (!this.allow(senderId, IPC.presenceHello)) return { clientId: senderId, peers: this.peers() }return this.hello(senderId, id)})+ // The payload goes to allow() too: a cast that CLEARS state is exempt from the bucket (a+ // dropped clear is permanent, and it cannot flood — see isClearingCast).p.onWithSender(IPC.presenceCursor,(senderId: number, cursor: { x: number; y: number } | null) => {- if (!this.allow(senderId, IPC.presenceCursor)) return+ if (!this.allow(senderId, IPC.presenceCursor, cursor)) returnthis.setCursor(senderId, cursor)})p.onWithSender(IPC.presenceFocus, (senderId: number, nodeId: string | null) => {- if (!this.allow(senderId, IPC.presenceFocus)) return+ if (!this.allow(senderId, IPC.presenceFocus, nodeId)) returnthis.setFocus(senderId, nodeId)})p.onWithSender(IPC.presenceChat, (senderId: number, text: string | null) => {- if (!this.allow(senderId, IPC.presenceChat)) return+ if (!this.allow(senderId, IPC.presenceChat, text)) returnthis.setChat(senderId, text)})p.onWithSender(IPC.presenceProject, (senderId: number, projectId: string | null) => {- if (!this.allow(senderId, IPC.presenceProject)) return+ // NOT exempted, unlike the clears: every project cast may carry a NEW id, so it always+ // broadcasts — an unlimited one would hand a hostile tab the same N-way amplifier the buckets+ // exist to stop (a clear cannot do that: it broadcasts at most once). Its budget is instead+ // sized so far above any human input path that an honest client can never lose a switch.+ if (!this.allow(senderId, IPC.presenceProject, projectId)) returnthis.setProject(senderId, projectId)})}diff --git a/src/renderer/components/PresenceLayer.tsx b/src/renderer/components/PresenceLayer.tsxindex 565418b02..5fa66ac23 100644--- a/src/renderer/components/PresenceLayer.tsx+++ b/src/renderer/components/PresenceLayer.tsx@@ -59,6 +59,15 @@ export function PresenceLayer(): JSX.Element | null {// whether a `chat(null)` is owed (on close, on the last peer leaving, on unmount).const publishedRef = useRef(false)+ // This flag claims what our PEERS can see, so it must never over-claim a retraction. The hub+ // rate-limits `presence:chat` (one cast per keystroke, and a held key repeats far faster than+ // anyone types), and it drops silently — but a `chat(null)` is EXEMPT from that bucket+ // (src/core/presence/hub.ts, isClearingCast), precisely so that clearing publishedRef here is+ // not a lie. Without the exemption a keyup retraction landing on a drained bucket would leave a+ // chat bubble pinned to our cursor on every peer's canvas, forever: we would already believe we+ // had retracted it, and nothing re-announces.+ // The other direction is safe by construction: a DROPPED non-null cast still sets the flag, so+ // at worst we retract something no peer saw — and the hub ignores an unchanged value.const sendChat = useCallback((text: string | null): void => {if (text === null && !publishedRef.current) return // nothing to retract — don't spam the wirepublishedRef.current = text !== nulldiff --git a/src/renderer/state/presence.test.ts b/src/renderer/state/presence.test.tsindex 2d1c52df9..d2c28867e 100644--- a/src/renderer/state/presence.test.ts+++ b/src/renderer/state/presence.test.ts@@ -446,6 +446,28 @@ describe('selectFocusedFaces: the alone / disconnected fast path', () => {expect(selectFocusedFaces(usePresence.getState(), 'node-a', 'web')).toBe(empty)stop()})++ // The fast path must mean "nobody ELSE to draw", not "fewer than two rows in the table". Our own+ // peer is normally one of those rows — but it need not be (a client that dropped mid-handshake,+ // a hub that answered hello before the join diff landed). A table holding exactly ONE peer, and+ // that peer a REAL teammate, must still chip: the Facepile shows them either way, and the two+ // surfaces must never disagree about who is here.+ it('still chips a lone real peer when my own row is missing from the table', async () => {+ vi.stubGlobal('localStorage', memStorage(STORED_ME))+ const api = fakePresenceApi({ clientId: 7, peers: [] }) // hello answers, but I am not in it+ const { connectPresence, usePresence, selectFocusedFaces, selectFaces } = await import(+ './presence'+ )+ const stop = connectPresence()+ await vi.waitFor(() => expect(usePresence.getState().myId).toBe(7))++ api.emitPeer({ op: 'join', peer: peer(8, { name: 'Ada', projectId: 'web', focus: 'node-a' }) })+ expect(selectFaces(usePresence.getState()).map((f) => f.name)).toEqual(['Ada'])+ expect(selectFocusedFaces(usePresence.getState(), 'node-a', 'web').map((f) => f.name)).toEqual([+ 'Ada'+ ])+ stop()+ })})describe('selectFocusedFaces (the node-header chips — one per node, so cursor traffic must not re-render them)', () => {diff --git a/src/renderer/state/presence.ts b/src/renderer/state/presence.tsindex 51aa3659a..9431434e7 100644--- a/src/renderer/state/presence.ts+++ b/src/renderer/state/presence.ts@@ -194,6 +194,22 @@ export function selectFaces(s: PresenceStore): PeerFace[] {* common case allocates NOTHING and its identity is stable across calls (useShallow bails out). */const NO_FACES: PeerFace[] = []+/** Is there anyone but me in the table? The literal question the chip fast path asks — not a proxy+ * for it (`Object.keys(peers).length < 2` assumed my own row is always one of them: a client that+ * dropped mid-handshake, or a hello answered before our join diff landed, leaves a table of ONE+ * REAL peer — whom the Facepile happily draws while the chips stayed blank; the two surfaces must+ * never disagree about who is here).+ * ALLOCATION-FREE, and that is the point: this runs once per MOUNTED NODE on EVERY store write+ * (~4k times/s on a busy canvas), so it may not build an array — `for…in` walks the keys in place,+ * `Object.keys()` would materialize one every single time. */+function hasOtherPeers(s: PresenceStore): boolean {+ if (s.myId === null) return false // hello unresolved → we cannot tell our own row from a peer's+ for (const key in s.peers) {+ if (s.peers[key as unknown as ClientId].clientId !== s.myId) return true+ }+ return false+}+/** 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.*@@ -206,15 +222,15 @@ const NO_FACES: PeerFace[] = []* 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. */+ * provably no one to chip (hello unresolved, or nobody else in the table), return NO_FACES. */export function selectFocusedFaces(s: PresenceStore,nodeId: string,projectId: string | null): PeerFace[] {- // 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+ // Nobody else here → nothing to compute, which is the overwhelmingly common case. The guard is+ // itself allocation-free (see hasOtherPeers), or it would defeat its own purpose.+ if (!hasOtherPeers(s)) return NO_FACESconst focused = selectFocused(s, nodeId, projectId)if (focused.length === 0) return NO_FACESreturn focused.map(faceFor)@@ -308,6 +324,18 @@ export function connectPresence(): () => void {// The last focus/project we published — a terminal re-focusing the same node, or a tab switch// back to the project we are already on, must not spam the wire.+//+// THE DEDUP IS A CLAIM THAT THE CAST LANDED, so it is only sound for casts the hub cannot drop.+// The hub rate-limits per (client, channel) and drops silently; there is no ack and no re-announce.+// It is sound here because of two hub rules (src/core/presence/hub.ts — keep them in sync):+// - a CLEARING cast (focus null) is exempt from the bucket, so `lastFocus = null` can never be a+// lie. A dropped non-null focus is self-healing anyway: the hub keeps the previous node, and+// the very next focus change — or the exempt release — corrects it.+// - `presence:project` is bucketed, but with a budget no human input path can reach (only+// DISTINCT switches spend a token — this dedup is what makes key-repeat free), so an honest+// client cannot lose the switch it has already recorded here.+// Do not tighten the project budget without revisiting this line: a dropped project cast that we+// have already recorded is permanent — teammates keep drawing us on a canvas we left.let lastFocus: string | null = nulllet lastProject: string | null = null