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
feat(core): PresenceHub — peer table, project scope, diffs, typing throttle
enes8772f1750509
diff --git a/src/core/presence/hub.test.ts b/src/core/presence/hub.test.tsnew file mode 100644index 000000000..0c49bc570--- /dev/null+++ b/src/core/presence/hub.test.ts@@ -0,0 +1,266 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform, type FakePlatform } from '../platform-fake'+import { PresenceHub, allocateRelayClientId, TYPING_THROTTLE_MS } from './hub'+import { IPC } from '../../shared/ipc'+import { PRESENCE_COLORS, type PeerDiff, type PeerState } from '../../shared/presence'++let fake: FakePlatform++beforeEach(() => {+ fake = fakePlatform()+ initPlatform(fake)+})+afterEach(() => {+ resetPlatformForTests()+ vi.useRealTimers()+})++/** Every `presence:peer` diff broadcast so far, in order. */+function diffs(): PeerDiff[] {+ return fake.sent+ .filter((s) => s.to === 'broadcast' && s.channel === IPC.presencePeer)+ .map((s) => s.args[0] as PeerDiff)+}++describe('PresenceHub join/leave', () => {+ it('join creates a peer with a default name + next-free color, snapshots the newcomer, and broadcasts', () => {+ const hub = new PresenceHub()+ hub.join(1, 'browser')+ hub.join(2, 'phone')++ expect(hub.peers()).toEqual([+ {+ clientId: 1,+ name: 'Someone',+ color: PRESENCE_COLORS[0],+ cursor: null,+ focus: null,+ chat: null,+ typing: null,+ projectId: null,+ kind: 'browser'+ },+ {+ clientId: 2,+ name: 'Phone',+ color: PRESENCE_COLORS[1],+ cursor: null,+ focus: null,+ chat: null,+ typing: null,+ projectId: null,+ kind: 'phone'+ }+ ])+ // The newcomer gets the full table (it may never be able to make a request — see the phone).+ const syncs = fake.sent.filter((s) => s.channel === IPC.presenceSync)+ expect(syncs.map((s) => s.to)).toEqual([1, 2])+ expect((syncs[1].args[0] as PeerState[]).map((p) => p.clientId)).toEqual([1, 2])+ expect(diffs()).toEqual([+ { op: 'join', peer: hub.peers()[0] },+ { op: 'join', peer: hub.peers()[1] }+ ])+ })++ it('a phone is a first-class cursorless peer (no fabricated position)', () => {+ const hub = new PresenceHub()+ hub.join(9, 'phone')+ expect(hub.peers()[0].cursor).toBeNull()+ expect(hub.peers()[0].kind).toBe('phone')+ })++ it('join is idempotent, and leave drops the peer + broadcasts', () => {+ const hub = new PresenceHub()+ hub.join(1, 'browser')+ hub.join(1, 'browser')+ expect(hub.peers()).toHaveLength(1)+ hub.leave(1)+ expect(hub.peers()).toEqual([])+ expect(diffs().at(-1)).toEqual({ op: 'leave', clientId: 1 })+ // Leaving twice is a silent no-op (no second diff).+ const before = diffs().length+ hub.leave(1)+ expect(diffs()).toHaveLength(before)+ })++ it('a departing peer frees its color for the next joiner', () => {+ const hub = new PresenceHub()+ hub.join(1, 'browser')+ hub.leave(1)+ hub.join(2, 'browser')+ expect(hub.peers()[0].color).toBe(PRESENCE_COLORS[0])+ })+})++describe('PresenceHub hello', () => {+ it('returns the caller its own id + the full table, and broadcasts the identity update', () => {+ const hub = new PresenceHub()+ hub.join(1, 'browser')+ hub.join(2, 'browser')+ const res = hub.hello(2, { name: ' Enes ', color: PRESENCE_COLORS[3] })+ expect(res.clientId).toBe(2)+ expect(res.peers.map((p) => p.clientId)).toEqual([1, 2])+ expect(hub.peers()[1]).toMatchObject({ name: 'Enes', color: PRESENCE_COLORS[3] })+ expect(diffs().at(-1)).toEqual({+ op: 'update',+ clientId: 2,+ patch: { name: 'Enes', color: PRESENCE_COLORS[3] }+ })+ })++ it('sanitizes junk (off-palette color / empty name) and ignores an unknown client', () => {+ const hub = new PresenceHub()+ hub.join(1, 'browser')+ hub.hello(1, { name: '', color: 'url(evil)' } as never)+ expect(hub.peers()[0]).toMatchObject({ name: 'Someone', color: PRESENCE_COLORS[0] })+ // A hello from a client that never joined must not create a ghost peer.+ const res = hub.hello(99, { name: 'Ghost', color: PRESENCE_COLORS[1] })+ expect(res).toEqual({ clientId: 99, peers: hub.peers() })+ expect(hub.peers()).toHaveLength(1)+ })+})++describe('PresenceHub signals', () => {+ it('setCursor / setFocus / setChat / setProject patch the peer and broadcast an update diff', () => {+ const hub = new PresenceHub()+ hub.join(1, 'browser')+ 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',+ chat: 'hey',+ projectId: 'web'+ })+ expect(diffs().slice(-4)).toEqual([+ { 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' } }+ ])+ hub.setCursor(1, null)+ hub.setChat(1, null)+ expect(hub.peers()[0]).toMatchObject({ cursor: null, chat: null })+ })++ it('setProject: switching canvases re-broadcasts, the same project is a silent no-op, and a peer with no project open goes back to null', () => {+ const hub = new PresenceHub()+ hub.join(1, 'browser')+ hub.setProject(1, 'web')+ const after = diffs().length+ hub.setProject(1, 'web') // no change → no diff (a tab switch back must not spam the wire)+ expect(diffs()).toHaveLength(after)+ hub.setProject(1, 'api')+ expect(diffs().at(-1)).toEqual({ op: 'update', clientId: 1, patch: { projectId: 'api' } })+ hub.setProject(1, null) // closed the last project → welcome screen+ expect(hub.peers()[0].projectId).toBeNull()+ // Unknown client: silent no-op, no ghost peer.+ hub.setProject(42, 'web')+ expect(hub.peers()).toHaveLength(1)+ })++ it('drops garbage input instead of broadcasting it (NaN cursor, over-long chat, unknown client)', () => {+ const hub = new PresenceHub()+ hub.join(1, 'browser')+ const before = diffs().length+ hub.setCursor(1, { x: Number.NaN, y: 0 })+ hub.setCursor(2, { x: 1, y: 1 }) // never joined+ hub.setFocus(2, 'node-a')+ expect(diffs()).toHaveLength(before)+ hub.setChat(1, 'y'.repeat(500))+ expect(hub.peers()[0].chat).toHaveLength(200)+ })++ it('caps chat at CHAT_MAX_LEN *code points*, so an emoji is never cut into a lone surrogate', () => {+ const hub = new PresenceHub()+ hub.join(1, 'browser')+ // 300 astral code points (600 UTF-16 units): a naive slice() would cut one in half.+ hub.setChat(1, '🙂'.repeat(300))+ const chat = hub.peers()[0].chat as string+ expect([...chat]).toHaveLength(200)+ expect(chat).toBe('🙂'.repeat(200))+ // The cap is enforced at ingest, so the broadcast diff carries the capped text too.+ expect(diffs().at(-1)).toEqual({ op: 'update', clientId: 1, patch: { chat } })+ })+})++describe('PresenceHub noteTyping (Stage 2 caller; wired here)', () => {+ it('throttles to one broadcast per node per 500ms and re-fires for a different node', () => {+ vi.useFakeTimers()+ vi.setSystemTime(1_000_000)+ const hub = new PresenceHub()+ hub.join(1, 'browser')+ const before = diffs().length++ hub.noteTyping(1, 'node-a')+ hub.noteTyping(1, 'node-a') // inside the throttle window → swallowed+ expect(diffs()).toHaveLength(before + 1)+ expect(hub.peers()[0].typing).toEqual({ nodeId: 'node-a', at: 1_000_000 })++ // A different node always re-fires (it's a different badge).+ hub.noteTyping(1, 'node-b')+ expect(diffs()).toHaveLength(before + 2)++ vi.setSystemTime(1_000_000 + TYPING_THROTTLE_MS + 1)+ hub.noteTyping(1, 'node-a')+ expect(diffs()).toHaveLength(before + 3)+ })+})++describe('registerIpc', () => {+ it('registers hello as a sender-aware request and the three signals as sender-aware casts', () => {+ const hub = new PresenceHub()+ hub.registerIpc()+ hub.join(4, 'browser')++ const res = fake.handlers[IPC.presenceHello](4, { name: 'Ada', color: PRESENCE_COLORS[2] })+ expect(res).toMatchObject({ clientId: 4 })++ 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 },+ focus: 'node-z',+ chat: 'yo',+ projectId: 'web'+ })+ })++ // The shell's listener registry does NOT dedup identical function references, so a second+ // registration would make every cast fire twice. The hub guards against that itself.+ it('is idempotent: a second call registers nothing', () => {+ const registered: string[] = []+ initPlatform(+ fakePlatform({+ handleWithSender: (ch) => registered.push(ch),+ onWithSender: (ch) => registered.push(ch)+ })+ )+ const hub = new PresenceHub()+ hub.registerIpc()+ expect(registered).toEqual([+ IPC.presenceHello,+ IPC.presenceCursor,+ IPC.presenceFocus,+ IPC.presenceChat,+ IPC.presenceProject+ ])+ hub.registerIpc()+ expect(registered).toHaveLength(5)+ })+})++describe('allocateRelayClientId', () => {+ it('mints monotonic ids from a range that cannot collide with a UI id', () => {+ const a = allocateRelayClientId()+ const b = allocateRelayClientId()+ expect(a).toBeGreaterThanOrEqual(1_000_000)+ expect(b).toBe(a + 1)+ })+})diff --git a/src/core/presence/hub.ts b/src/core/presence/hub.tsnew file mode 100644index 000000000..3d9fee66c--- /dev/null+++ b/src/core/presence/hub.ts@@ -0,0 +1,186 @@+// PresenceHub — the peer table for team presence (docs/team-presence.md).+//+// One hub, two adapters: the Server Edition joins/leaves each authenticated WebSocket+// (src/server/ws.ts), and the desktop joins its own window plus every bridged relay peer+// (src/main/index.ts, src/main/remote/standing-host.ts). The hub itself is a dumb reflector:+// it holds Map<clientId, PeerState>, applies events, and emits diffs. No electron, no ws, no+// disk, no timers — it talks to its shell only through platform() (see src/core/platform.ts).+//+// PRESENCE IS NEVER PERSISTED. Nothing here reaches workspace.json / project.json / settings.json.++import { IPC } from '../../shared/ipc'+import { platform } from '../platform'+import {+ CHAT_MAX_LEN,+ capCodePoints,+ defaultNameFor,+ nextFreeColor,+ sanitizeIdentity,+ type ClientId,+ type PeerDiff,+ type PeerIdentity,+ type PeerState+} from '../../shared/presence'++/** A typing badge re-broadcasts at most this often per (client, node) — see noteTyping. */+export const TYPING_THROTTLE_MS = 500++// 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++/** Mint a ClientId for a relay peer (a bridged HostSession). Monotonic, collision-free. */+export function allocateRelayClientId(): ClientId {+ return nextRelayId+++}++export class PresenceHub {+ private table = new Map<ClientId, PeerState>()+ /** `${clientId}:${nodeId}` → last typing broadcast (throttle window). */+ private lastTyping = new Map<string, number>()+ private ipcRegistered = false++ /** A UI connected. Colors are assigned next-free; the name is a placeholder until hello. */+ join(clientId: ClientId, kind: PeerState['kind']): void {+ if (this.table.has(clientId)) return+ const peer: PeerState = {+ clientId,+ name: defaultNameFor(kind),+ color: nextFreeColor([...this.table.values()].map((p) => p.color)),+ cursor: null,+ focus: null,+ chat: null,+ typing: null,+ // Unknown until the client reports its active project (a phone never does in Stage 1) —+ // so it is drawn on nobody's canvas and lives in the facepile only.+ projectId: null,+ kind+ }+ this.table.set(clientId, peer)+ // The newcomer gets the whole table up front. A relay/phone peer cannot make a request, and a+ // browser's ws-bridge buffers events that land before it subscribes — so this is safe for both.+ platform().sendTo(clientId, IPC.presenceSync, this.peers())+ this.emit({ op: 'join', peer })+ }++ /** A UI disconnected. Its color frees up for the next joiner. */+ leave(clientId: ClientId): void {+ if (!this.table.delete(clientId)) return+ for (const key of [...this.lastTyping.keys()]) {+ if (key.startsWith(`${clientId}:`)) this.lastTyping.delete(key)+ }+ this.emit({ op: 'leave', clientId })+ }++ /** The client claims an identity. Returns its own clientId (so it never draws its own cursor)+ * plus the current table. Names are unverified by design — see docs/team-presence.md. */+ hello(clientId: ClientId, id: PeerIdentity): { clientId: ClientId; peers: PeerState[] } {+ const peer = this.table.get(clientId)+ if (!peer) return { clientId, peers: this.peers() }+ const { name, color } = sanitizeIdentity(id, { name: peer.name, color: peer.color })+ peer.name = name+ peer.color = color+ this.emit({ op: 'update', clientId, patch: { name, color } })+ return { clientId, peers: this.peers() }+ }++ /** Flow coordinates, or null for a peer that has no cursor (a phone, or a mouse that left). */+ setCursor(clientId: ClientId, cursor: { x: number; y: number } | null): void {+ const peer = this.table.get(clientId)+ if (!peer) return+ let next: PeerState['cursor'] = null+ if (cursor) {+ if (!Number.isFinite(cursor.x) || !Number.isFinite(cursor.y)) return+ next = { x: cursor.x, y: cursor.y }+ }+ peer.cursor = next+ this.emit({ op: 'update', clientId, patch: { cursor: next } })+ }++ setFocus(clientId: ClientId, nodeId: string | null): void {+ const peer = this.table.get(clientId)+ if (!peer) return+ const next = typeof nodeId === 'string' && nodeId ? nodeId : null+ if (peer.focus === next) return+ peer.focus = next+ this.emit({ op: 'update', clientId, patch: { focus: next } })+ }++ /** Live cursor-chat text; null closes the bubble. THE single ingest point for chat, so the+ * CHAT_MAX_LEN cap lives here and cannot drift between the hub and the renderer. Capped by+ * code point (capCodePoints), never by UTF-16 slice: a bubble ending in half an emoji would+ * render as "�" for every peer. */+ setChat(clientId: ClientId, text: string | null): void {+ const peer = this.table.get(clientId)+ if (!peer) return+ const next = typeof text === 'string' ? capCodePoints(text, CHAT_MAX_LEN) : null+ peer.chat = next+ this.emit({ op: 'update', clientId, patch: { chat: next } })+ }++ /** Which project (canvas) this client is on. Everyone else uses it to decide whether this+ * peer's cursor/focus belongs on THEIR screen (peersOnProject) — a project is a separate+ * canvas with its own nodes and its own flow coordinates. null = no project open. */+ setProject(clientId: ClientId, projectId: string | null): void {+ const peer = this.table.get(clientId)+ if (!peer) return+ const next = typeof projectId === 'string' && projectId ? projectId : null+ if (peer.projectId === next) return+ peer.projectId = next+ this.emit({ op: 'update', clientId, patch: { projectId: next } })+ }++ /** Someone wrote into a node's terminal. Throttled to 1 broadcast / TYPING_THROTTLE_MS per+ * (client, node) — a keystroke storm must not become a broadcast storm. The badge's ~2s decay+ * is the renderer's job (TYPING_DECAY_MS): the hub keeps no timers.+ * Stage 2 calls this from the sender-aware pty:write handler; nothing calls it in Stage 1. */+ noteTyping(clientId: ClientId, nodeId: string): void {+ const peer = this.table.get(clientId)+ if (!peer || !nodeId) return+ const now = Date.now()+ const key = `${clientId}:${nodeId}`+ const last = this.lastTyping.get(key) ?? 0+ if (peer.typing?.nodeId === nodeId && now - last < TYPING_THROTTLE_MS) return+ this.lastTyping.set(key, now)+ const typing = { nodeId, at: now }+ peer.typing = typing+ this.emit({ op: 'update', clientId, patch: { typing } })+ }++ /** The current table, in join order. Copies so a caller can't mutate hub state. */+ peers(): PeerState[] {+ return [...this.table.values()].map((p) => ({ ...p }))+ }++ /** Wire the presence channels into the shell. Idempotent on purpose: the shell's listener+ * registry does not dedup identical function references, so a second registration would make+ * every cast fire (and broadcast) twice. */+ registerIpc(): void {+ if (this.ipcRegistered) return+ this.ipcRegistered = true+ const p = platform()+ p.handleWithSender(IPC.presenceHello, (senderId: number, id: PeerIdentity) =>+ this.hello(senderId, id)+ )+ p.onWithSender(+ IPC.presenceCursor,+ (senderId: number, cursor: { x: number; y: number } | null) => this.setCursor(senderId, cursor)+ )+ p.onWithSender(IPC.presenceFocus, (senderId: number, nodeId: string | null) =>+ this.setFocus(senderId, nodeId)+ )+ p.onWithSender(IPC.presenceChat, (senderId: number, text: string | null) =>+ this.setChat(senderId, text)+ )+ p.onWithSender(IPC.presenceProject, (senderId: number, projectId: string | null) =>+ this.setProject(senderId, projectId)+ )+ }++ private emit(diff: PeerDiff): void {+ platform().broadcast(IPC.presencePeer, diff)+ }+}++/** The process-wide hub. Both shells (and the relay host) feed this one instance. */+export const presenceHub = new PresenceHub()diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 8629d9c4e..3e4966408 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -61,6 +61,18 @@ export const IPC = {usageUpdate: 'usage:update',contextUpdate: 'context:update',contextEnsure: 'context:ensure',+ // Team presence (docs/team-presence.md). `presence:hello` is a REQUEST: its response tells the+ // client its own clientId, so it never draws its own cursor. The rest are casts (client→server)+ // and events (server→clients); the server is a dumb reflector and applies no policy.+ presenceHello: 'presence:hello',+ presenceCursor: 'presence:cursor',+ presenceFocus: 'presence:focus',+ presenceChat: 'presence:chat',+ // Which project (canvas) the client is looking at. Cursors/focus are only meaningful to a+ // viewer on the same project — each project has its own nodes and coordinate space.+ presenceProject: 'presence:project',+ presenceSync: 'presence:sync',+ presencePeer: 'presence:peer',// Events broadcast from main to the renderer (sessionId is appended to the channel name).ptyData: (sessionId: string) => `pty:data:${sessionId}`,ptyExit: (sessionId: string) => `pty:exit:${sessionId}`,diff --git a/src/shared/presence.ts b/src/shared/presence.tsindex ec0f2895c..d905ebe03 100644--- a/src/shared/presence.ts+++ b/src/shared/presence.ts@@ -86,12 +86,18 @@ export function peersOnProject(peers: PeerState[], projectId: string | null): Pereturn peers.filter((p) => p.projectId === projectId)}-/** Cap a name at NAME_MAX_LEN *code points*, not UTF-16 code units: `slice` would cut a- * surrogate pair (emoji, CJK extensions) in half and leave a lone surrogate, which renders as- * "�" in every peer's facepile. Trim runs again AFTER the cut, so a truncation landing on a- * space doesn't leave a trailing one. */+/** Cap a string at `max` *code points*, not UTF-16 code units: `slice` would cut a surrogate+ * pair (emoji, CJK extensions) in half and leave a lone surrogate, which renders as "�" in+ * every peer's facepile / chat bubble. The single truncation rule for the whole feature — the+ * hub caps chat with it (CHAT_MAX_LEN) and capName caps names with it. */+export function capCodePoints(text: string, max: number): string {+ return [...text].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. */function capName(name: string): string {- return [...name.trim()].slice(0, NAME_MAX_LEN).join('').trim()+ return capCodePoints(name.trim(), NAME_MAX_LEN).trim()}/** Coerce an untrusted {name, color} off the wire into a safe identity. Names are unverified