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(server): join/leave the presence hub per WebSocket
enesc8054255ca34
diff --git a/src/server/index.ts b/src/server/index.tsindex 686f3531f..c58f6be8f 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -16,6 +16,7 @@ import { registerCoreHandlers } from './handlers'import { hookServer } from '../core/agents/hook-server'import { installManagedAgentHooks } from '../core/agents/hooks'import { initAgentStatusMirror } from '../core/agent-status-mirror'+import { presenceHub } from '../core/presence/hub'import { wireAgentStatus } from './agent-status'import { IPC } from '@shared/ipc'@@ -73,6 +74,9 @@ export async function startServer(ptyManager.init(() => settingsStore.get())ptyManager.registerIpc()workspaceStore.registerIpc()+ // Team presence (hello / cursor / focus / chat). The hub itself is joined per WebSocket in+ // ws.ts; this only registers the RPC surface. Presence is transient — nothing is persisted.+ presenceHub.registerIpc()// WS backpressure: when a connection's socket send buffer fills while streaming pty// output, pause that tmux client so the OS pipe applies real backpressure (resumes belowdiff --git a/src/server/ws.test.ts b/src/server/ws.test.tsindex 04a9db1a5..da9d690f7 100644--- a/src/server/ws.test.ts+++ b/src/server/ws.test.ts@@ -8,6 +8,7 @@ import { Auth } from './auth'import { ServerPlatform } from './platform-server'import { attachWsServer } from './ws'import { SESSION_COOKIE } from './http'+import { initPlatform } from '../core/platform'let dir: string, server: http.Server, port: number, auth: Auth, platform: ServerPlatform, cookie: string@@ -15,6 +16,9 @@ beforeEach(async () => {dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-ws-'))auth = new Auth(dir)platform = new ServerPlatform({ userDataDir: dir, appVersion: '0.0.0' })+ // The connection handler joins the presence hub, and the hub reaches its shell through the+ // core platform singleton — so this unit test must install the platform, exactly as boot does.+ initPlatform(platform)server = http.createServer((_q, s) => { s.statusCode = 404; s.end() })attachWsServer(server, { platform, auth })await new Promise<void>((r) => server.listen(0, '127.0.0.1', r))@@ -23,6 +27,10 @@ beforeEach(async () => {})afterEach(async () => {await new Promise((r) => server.close(r))+ // Deliberately NOT resetPlatformForTests(): a socket's 'close' can fire a tick after+ // server.close() resolves, and that handler leaves the presence hub — with the platform torn+ // out from under it, that async callback would throw as an uncaught exception. The next+ // beforeEach replaces the singleton anyway.fs.rmSync(dir, { recursive: true, force: true })})diff --git a/src/server/ws.ts b/src/server/ws.tsindex 1156fd06a..74b9d77d2 100644--- a/src/server/ws.ts+++ b/src/server/ws.ts@@ -18,6 +18,7 @@ import type { Auth } from './auth'import type { ServerPlatform } from './platform-server'import { sessionTokenFromCookie } from './http'import { parseRpcMessage } from '../shared/rpc'+import { presenceHub } from '../core/presence/hub'export interface WsServerOpts {platform: ServerPlatform@@ -77,6 +78,10 @@ export function attachWsServer(server: http.Server, opts: WsServerOpts): void {sendBinary: (buf) => ws.send(buf, { binary: true }),bufferedAmount: () => ws.bufferedAmount})+ // Team presence: each authenticated socket is one peer. Joining AFTER attach means the hub's+ // `presence:sync` sendTo lands on a live sink; the browser bridge buffers it until the app+ // subscribes. The peer stays nameless ("Someone") until it sends `presence:hello`.+ presenceHub.join(uiId, 'browser')ws.on('message', (data: unknown, isBinary: boolean) => {// Binary client→server frames are ignored in Phase 2 (pty input rides JSON casts).@@ -105,6 +110,7 @@ export function attachWsServer(server: http.Server, opts: WsServerOpts): void {})ws.on('close', () => {+ presenceHub.leave(uiId)platform.detach(uiId)})})diff --git a/test/server/presence-e2e.test.ts b/test/server/presence-e2e.test.tsnew file mode 100644index 000000000..e591e37f3--- /dev/null+++ b/test/server/presence-e2e.test.ts@@ -0,0 +1,141 @@+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import WebSocket from 'ws'+import { startServer } from '../../src/server/index'+import { SESSION_COOKIE } from '../../src/server/http'+import { IPC } from '../../src/shared/ipc'+import { PRESENCE_COLORS, type PeerDiff, type PeerState } from '../../src/shared/presence'++interface Ev {+ t: 'ev' | 'res'+ id?: number+ channel?: string+ args?: unknown[]+ ok?: boolean+ result?: unknown+}++/** Open an authenticated WS and record every JSON message it receives. */+async function connect(port: number, cookie: string): Promise<{ ws: WebSocket; msgs: Ev[] }> {+ const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`, { headers: { cookie } })+ const msgs: Ev[] = []+ ws.on('message', (d, isBinary) => {+ if (isBinary) return+ msgs.push(JSON.parse(d.toString()) as Ev)+ })+ await new Promise<void>((res, rej) => {+ ws.on('open', () => res())+ ws.on('error', rej)+ })+ return { ws, msgs }+}++/** Poll until `pred` holds (or fail the test after ~2s) — the fan-out is async over sockets. */+async function until(pred: () => boolean, what: string): Promise<void> {+ for (let i = 0; i < 100; i++) {+ if (pred()) return+ await new Promise((r) => setTimeout(r, 20))+ }+ throw new Error(`timed out waiting for: ${what}`)+}++function diffs(msgs: Ev[]): PeerDiff[] {+ return msgs+ .filter((m) => m.t === 'ev' && m.channel === IPC.presencePeer)+ .map((m) => m.args![0] as PeerDiff)+}++describe('server e2e: presence with two clients', () => {+ let dataDir: string, close: () => Promise<void>, port: number, cookie: string++ beforeAll(async () => {+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-presence-'))+ const srv = await startServer({+ port: 0,+ host: '127.0.0.1',+ dataDir,+ rendererDir: path.join(dataDir, 'no-renderer'),+ insecureHttp: false,+ passwordSeed: 'e2e-password-123',+ // Never touch the developer's real ~/.claude (see server-e2e.test.ts).+ installHooks: false+ })+ port = srv.port+ close = srv.close+ const res = await fetch(`http://127.0.0.1:${port}/auth/login`, {+ method: 'POST',+ headers: { 'content-type': 'application/x-www-form-urlencoded' },+ body: 'password=e2e-password-123',+ redirect: 'manual'+ })+ cookie = res.headers.get('set-cookie')!.split(';')[0]+ expect(cookie).toContain(SESSION_COOKIE)+ }, 30_000)++ afterAll(async () => {+ await close?.()+ fs.rmSync(dataDir, { recursive: true, force: true })+ })++ it('hello → own id + snapshot; cursor fans out to the other client; disconnect → leave', async () => {+ const a = await connect(port, cookie)+ const b = await connect(port, cookie)++ // B's join reached A as a diff, and B got its own snapshot on connect.+ await until(() => diffs(a.msgs).some((d) => d.op === 'join'), "A sees B's join")+ await until(+ () => b.msgs.some((m) => m.t === 'ev' && m.channel === IPC.presenceSync),+ 'B receives presence:sync'+ )++ // A says hello: the response carries A's OWN clientId (so A never draws its own cursor).+ a.ws.send(+ JSON.stringify({+ t: 'req',+ id: 1,+ method: IPC.presenceHello,+ args: [{ name: 'Ada', color: PRESENCE_COLORS[2] }]+ })+ )+ await until(() => a.msgs.some((m) => m.t === 'res' && m.id === 1), 'hello response')+ const res = a.msgs.find((m) => m.t === 'res' && m.id === 1)!+ const hello = res.result as { clientId: number; peers: PeerState[] }+ expect(res.ok).toBe(true)+ expect(typeof hello.clientId).toBe('number')+ expect(hello.peers.map((p) => p.clientId)).toContain(hello.clientId)+ expect(hello.peers).toHaveLength(2)+ expect(hello.peers.find((p) => p.clientId === hello.clientId)!.name).toBe('Ada')+ expect(hello.peers.every((p) => p.kind === 'browser')).toBe(true)++ // A moves its cursor → B sees an update diff stamped with A's clientId.+ a.ws.send(JSON.stringify({ t: 'cast', method: IPC.presenceCursor, args: [{ x: 100, y: 200 }] }))+ await until(+ () =>+ diffs(b.msgs).some(+ (d) => d.op === 'update' && d.clientId === hello.clientId && d.patch.cursor?.x === 100+ ),+ "B sees A's cursor"+ )++ // A opens a project → B learns which canvas A is on (the filter that keeps A's cursor off+ // B's screen when they are on different projects).+ a.ws.send(JSON.stringify({ t: 'cast', method: IPC.presenceProject, args: ['web'] }))+ await until(+ () =>+ diffs(b.msgs).some(+ (d) => d.op === 'update' && d.clientId === hello.clientId && d.patch.projectId === 'web'+ ),+ "B sees A's project"+ )++ // A disconnects → B sees the leave.+ a.ws.close()+ await until(+ () => diffs(b.msgs).some((d) => d.op === 'leave' && d.clientId === hello.clientId),+ "B sees A's leave"+ )+ b.ws.close()+ }, 20_000)+})