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(renderer): transient presence store (peers, identity, focus)
enes649372c7a107
diff --git a/src/renderer/state/presence.test.ts b/src/renderer/state/presence.test.tsnew file mode 100644index 000000000..b84c451b2--- /dev/null+++ b/src/renderer/state/presence.test.ts@@ -0,0 +1,231 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { PRESENCE_COLORS, type PeerState } from '@shared/presence'++// The store reads localStorage at call time; each test stubs a fresh in-memory storage and+// re-imports the module (vi.resetModules) so nothing leaks between cases.+function memStorage(seed: Record<string, string> = {}): Storage {+ const m = new Map(Object.entries(seed))+ return {+ getItem: (k: string) => m.get(k) ?? null,+ setItem: (k: string, v: string) => void m.set(k, v),+ removeItem: (k: string) => void m.delete(k),+ clear: () => m.clear(),+ key: () => null,+ get length() {+ return m.size+ }+ } as Storage+}++function peer(clientId: number, over: Partial<PeerState> = {}): PeerState {+ return {+ clientId,+ name: `P${clientId}`,+ color: PRESENCE_COLORS[0],+ cursor: null,+ focus: null,+ chat: null,+ typing: null,+ projectId: 'web',+ kind: 'browser',+ ...over+ }+}++/** A recording window.nodeTerminal.presence. */+function fakePresenceApi(hello = { clientId: 7, peers: [peer(7)] }) {+ const calls: Array<[string, unknown]> = []+ let syncCb: ((peers: PeerState[]) => void) | null = null+ let peerCb: ((diff: unknown) => void) | null = null+ const presence = {+ hello: vi.fn(async (id: unknown) => {+ calls.push(['hello', id])+ return hello+ }),+ cursor: (c: unknown) => calls.push(['cursor', c]),+ focus: (n: unknown) => calls.push(['focus', n]),+ chat: (t: unknown) => calls.push(['chat', t]),+ project: (p: unknown) => calls.push(['project', p]),+ onSync: (cb: (peers: PeerState[]) => void) => {+ syncCb = cb+ return () => (syncCb = null)+ },+ onPeer: (cb: (diff: unknown) => void) => {+ peerCb = cb+ return () => (peerCb = null)+ }+ }+ vi.stubGlobal('window', { nodeTerminal: { presence } })+ return {+ calls,+ presence,+ emitSync: (p: PeerState[]) => syncCb?.(p),+ emitPeer: (d: unknown) => peerCb?.(d)+ }+}++beforeEach(() => vi.resetModules())+afterEach(() => vi.unstubAllGlobals())++describe('identity (the only persisted part of presence)', () => {+ it('round-trips {name,color} through localStorage under nodeterm.presence.me', async () => {+ const store = memStorage()+ vi.stubGlobal('localStorage', store)+ const { loadIdentity, saveIdentity, ME_KEY } = await import('./presence')+ expect(loadIdentity()).toBeNull()+ saveIdentity({ name: 'Enes', color: PRESENCE_COLORS[1] })+ expect(JSON.parse(store.getItem(ME_KEY)!)).toEqual({ name: 'Enes', color: PRESENCE_COLORS[1] })+ expect(loadIdentity()).toEqual({ name: 'Enes', color: PRESENCE_COLORS[1] })+ })++ it('survives corrupt storage (returns null instead of throwing)', async () => {+ vi.stubGlobal('localStorage', memStorage({ 'nodeterm.presence.me': '{not json' }))+ const { loadIdentity } = await import('./presence')+ expect(loadIdentity()).toBeNull()+ })+})++describe('connectPresence', () => {+ it('sends hello with the stored identity, records my id, and seeds the peer table', async () => {+ vi.stubGlobal(+ 'localStorage',+ memStorage({+ 'nodeterm.presence.me': JSON.stringify({ name: 'Enes', color: PRESENCE_COLORS[1] })+ })+ )+ const api = fakePresenceApi({ clientId: 7, peers: [peer(7, { name: 'Enes' }), peer(8)] })+ const { connectPresence, usePresence, selectOthers } = await import('./presence')++ const stop = connectPresence()+ await vi.waitFor(() => expect(usePresence.getState().myId).toBe(7))+ expect(api.calls[0]).toEqual(['hello', { name: 'Enes', color: PRESENCE_COLORS[1] }])+ expect(usePresence.getState().needsName).toBe(false)+ // My own peer is in the table but never in `others` — I must not draw my own cursor.+ expect(selectOthers(usePresence.getState()).map((p) => p.clientId)).toEqual([8])+ stop()+ })++ it('flags needsName (and does not say hello) when no identity is stored', async () => {+ vi.stubGlobal('localStorage', memStorage())+ const api = fakePresenceApi()+ const { connectPresence, usePresence } = await import('./presence')+ const stop = connectPresence()+ expect(usePresence.getState().needsName).toBe(true)+ expect(api.presence.hello).not.toHaveBeenCalled()+ stop()+ })++ it('setMe persists the identity, clears needsName and says hello', async () => {+ vi.stubGlobal('localStorage', memStorage())+ const api = fakePresenceApi()+ const { connectPresence, usePresence } = await import('./presence')+ const stop = connectPresence()+ usePresence.getState().setMe({ name: 'Ada', color: PRESENCE_COLORS[2] })+ await vi.waitFor(() => expect(usePresence.getState().myId).toBe(7))+ expect(usePresence.getState().needsName).toBe(false)+ expect(api.calls[0]).toEqual(['hello', { name: 'Ada', color: PRESENCE_COLORS[2] }])+ stop()+ })+})++describe('diff application', () => {+ it('applies join / update / leave and replaces the table on sync', async () => {+ vi.stubGlobal(+ 'localStorage',+ memStorage({+ 'nodeterm.presence.me': JSON.stringify({ name: 'Enes', color: PRESENCE_COLORS[1] })+ })+ )+ const api = fakePresenceApi({ clientId: 7, peers: [peer(7)] })+ const { connectPresence, usePresence, selectOthers, selectFocused } = await import('./presence')+ const stop = connectPresence()+ await vi.waitFor(() => expect(usePresence.getState().myId).toBe(7))++ api.emitPeer({ op: 'join', peer: peer(8, { name: 'Ada' }) })+ expect(selectOthers(usePresence.getState()).map((p) => p.name)).toEqual(['Ada'])++ api.emitPeer({ op: 'update', clientId: 8, patch: { cursor: { x: 4, y: 5 }, focus: 'node-a' } })+ expect(usePresence.getState().peers[8].cursor).toEqual({ x: 4, y: 5 })+ expect(selectFocused(usePresence.getState(), 'node-a', 'web').map((p) => p.clientId)).toEqual([+ 8+ ])+ // An update for an unknown peer is ignored (no ghost rows).+ api.emitPeer({ op: 'update', clientId: 99, patch: { chat: 'boo' } })+ expect(usePresence.getState().peers[99]).toBeUndefined()++ api.emitPeer({ op: 'leave', clientId: 8 })+ expect(selectOthers(usePresence.getState())).toEqual([])++ api.emitSync([peer(7), peer(9)])+ expect(selectOthers(usePresence.getState()).map((p) => p.clientId)).toEqual([9])+ stop()+ })+})++describe('project scoping (a peer on another canvas is never drawn on mine)', () => {+ it('selectVisible / selectFocused honour the project; selectOthers (facepile) does not', async () => {+ vi.stubGlobal(+ 'localStorage',+ memStorage({+ 'nodeterm.presence.me': JSON.stringify({ name: 'Enes', color: PRESENCE_COLORS[1] })+ })+ )+ const api = fakePresenceApi({ clientId: 7, peers: [peer(7, { projectId: 'web' })] })+ const { connectPresence, usePresence, selectOthers, selectVisible, selectFocused } =+ await import('./presence')+ const stop = connectPresence()+ await vi.waitFor(() => expect(usePresence.getState().myId).toBe(7))++ api.emitPeer({ op: 'join', peer: peer(8, { projectId: 'web', focus: 'node-a' }) })+ api.emitPeer({ op: 'join', peer: peer(9, { projectId: 'api', focus: 'node-b' }) })+ api.emitPeer({ op: 'join', peer: peer(10, { projectId: null, kind: 'phone' }) })+ const s = usePresence.getState()++ // Canvas surfaces: only the peers on MY project.+ expect(selectVisible(s, 'web').map((p) => p.clientId)).toEqual([8])+ expect(selectFocused(s, 'node-a', 'web').map((p) => p.clientId)).toEqual([8])+ // A peer focused on a node of ANOTHER project must not chip a node here (ids are global).+ expect(selectFocused(s, 'node-b', 'web')).toEqual([])+ // No project open (welcome screen) → nothing is drawn at all.+ expect(selectVisible(s, null)).toEqual([])++ // The facepile shows everyone, whatever canvas they are on (including the cursorless phone).+ expect(selectOthers(s).map((p) => p.clientId)).toEqual([8, 9, 10])++ // Peer 8 switches to another project → their cursor leaves my canvas immediately.+ api.emitPeer({ op: 'update', clientId: 8, patch: { projectId: 'api' } })+ expect(selectVisible(usePresence.getState(), 'web')).toEqual([])+ stop()+ })+})++describe('reportFocus / reportProject', () => {+ 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',+ memStorage({+ 'nodeterm.presence.me': JSON.stringify({ name: 'Enes', color: PRESENCE_COLORS[1] })+ })+ )+ const api = fakePresenceApi()+ const { reportFocus, reportProject } = await import('./presence')+ reportFocus('node-a')+ reportFocus('node-a')+ reportFocus(null)+ reportFocus(null)+ expect(api.calls.filter((c) => c[0] === 'focus')).toEqual([+ ['focus', 'node-a'],+ ['focus', null]+ ])++ reportProject('web')+ reportProject('web')+ reportProject('api')+ reportProject(null)+ expect(api.calls.filter((c) => c[0] === 'project')).toEqual([+ ['project', 'web'],+ ['project', 'api'],+ ['project', null]+ ])+ })+})diff --git a/src/renderer/state/presence.ts b/src/renderer/state/presence.tsnew file mode 100644index 000000000..6c2969735--- /dev/null+++ b/src/renderer/state/presence.ts@@ -0,0 +1,189 @@+import { create } from 'zustand'+import {+ PRESENCE_COLORS,+ nextFreeColor,+ peersOnProject,+ type ClientId,+ type PeerDiff,+ type PeerIdentity,+ type PeerState+} from '@shared/presence'++/**+ * Transient team-presence store (docs/team-presence.md). Holds the peer table for the current+ * connection: cursors, focus, chat. NONE of it is persisted — the only thing that survives a+ * reload is the local user's own {name, color} (ME_KEY below).+ *+ * SOLE SUBSCRIBER: this module is the ONLY place that may call presence.onSync / presence.onPeer,+ * and connectPresence() is called exactly once (Canvas, []-effect). The browser bridge buffers the+ * events that arrive before the first subscriber and drains that buffer into it — a SECOND+ * subscriber on the same channel would get nothing, so components must read this store and never+ * subscribe themselves.+ *+ * PERF CONTRACT: only the presence components (PresenceLayer / Facepile / PresenceChips) may+ * subscribe to this store. Canvas.tsx is ~4000 lines — if a cursor at 20 Hz re-rendered it, every+ * mouse move would redraw the whole canvas. Canvas mounts the components and calls+ * connectPresence(); it never reads the store.+ */++export const ME_KEY = 'nodeterm.presence.me'++/** The local user's saved identity, or null on first run / corrupt storage. */+export function loadIdentity(): PeerIdentity | null {+ try {+ const raw = localStorage.getItem(ME_KEY)+ if (!raw) return null+ const parsed = JSON.parse(raw) as Partial<PeerIdentity>+ if (typeof parsed?.name !== 'string' || typeof parsed?.color !== 'string') return null+ return { name: parsed.name, color: parsed.color }+ } catch {+ return null+ }+}++export function saveIdentity(id: PeerIdentity): void {+ try {+ localStorage.setItem(ME_KEY, JSON.stringify(id))+ } catch {+ // ignore quota / serialization errors — presence still works for this session+ }+}++/** A starting point for the name prompt: empty name, an unused-looking color. */+export function suggestIdentity(): PeerIdentity {+ const taken = Object.values(usePresence.getState().peers).map((p) => p.color)+ return { name: '', color: nextFreeColor(taken) || PRESENCE_COLORS[0] }+}++export interface PresenceStore {+ /** This client's own id (from the hello response). Null until hello resolves. */+ myId: ClientId | null+ /** The local user's identity, or null until they pick one. */+ me: PeerIdentity | null+ /** Everyone connected, INCLUDING me (selectOthers filters me out). */+ peers: Record<ClientId, PeerState>+ /** True when we are connected but the user has never chosen a name → show the prompt. */+ needsName: boolean+ setMe(id: PeerIdentity): void+ applySync(peers: PeerState[]): void+ applyDiff(diff: PeerDiff): void+ reset(): void+}++export const usePresence = create<PresenceStore>((set) => ({+ myId: null,+ me: loadIdentity(),+ peers: {},+ needsName: false,++ setMe: (id) => {+ saveIdentity(id)+ set({ me: id, needsName: false })+ void sayHello(id)+ },++ applySync: (peers) =>+ set(() => {+ const table: Record<ClientId, PeerState> = {}+ for (const p of peers) table[p.clientId] = p+ return { peers: table }+ }),++ applyDiff: (diff) =>+ set((s) => {+ if (diff.op === 'join') return { peers: { ...s.peers, [diff.peer.clientId]: diff.peer } }+ if (diff.op === 'leave') {+ if (!(diff.clientId in s.peers)) return s+ const peers = { ...s.peers }+ delete peers[diff.clientId]+ return { peers }+ }+ const prev = s.peers[diff.clientId]+ if (!prev) return s // an update for a peer we never saw join — ignore, never ghost a row+ return { peers: { ...s.peers, [diff.clientId]: { ...prev, ...diff.patch } } }+ }),++ reset: () => set({ myId: null, peers: {}, needsName: false })+}))++/** Everyone except me, on ANY project — the facepile list (it shows who is working where). */+export function selectOthers(s: PresenceStore): PeerState[] {+ return Object.values(s.peers).filter((p) => p.clientId !== s.myId)+}++/** Everyone except me, on THIS project — the ONLY peers that may be drawn on the canvas. A peer+ * on another project has coordinates in another canvas's space (see peersOnProject). */+export function selectVisible(s: PresenceStore, projectId: string | null): PeerState[] {+ return peersOnProject(selectOthers(s), projectId)+}++/** The peers (never me, never off-project) focused on one node — drives the node-header chips.+ * Node ids are globally unique, so without the project filter a peer focused on a node in+ * another project would silently chip a node here. */+export function selectFocused(+ s: PresenceStore,+ nodeId: string,+ projectId: string | null+): PeerState[] {+ return selectVisible(s, projectId).filter((p) => p.focus === nodeId)+}++/**+ * Say hello and seed the peer table from the RESPONSE — not from the presence:sync push. On+ * desktop the hub joins the window at createWindow(), i.e. before the renderer has loaded, so+ * that join-time sync is always lost. The hello response is the only snapshot that is reliable+ * on BOTH surfaces, and it is also how we learn our OWN clientId (so we never draw our cursor).+ */+async function sayHello(id: PeerIdentity): Promise<void> {+ const res = await window.nodeTerminal.presence.hello(id)+ const table: Record<ClientId, PeerState> = {}+ for (const p of res.peers) table[p.clientId] = p+ usePresence.setState({ myId: res.clientId, peers: table })+}++/**+ * Subscribe to the presence stream and announce ourselves. Called EXACTLY ONCE, from Canvas in a+ * []-effect; returns a teardown. Subscribing BEFORE hello matters: any diff that lands while+ * hello is in flight must be applied on top of the snapshot, not dropped. With no stored identity+ * we subscribe but stay anonymous (`needsName`) until the prompt resolves — the hub still knows+ * us as "Someone", so nothing is lost either way.+ */+export function connectPresence(): () => void {+ const unSync = window.nodeTerminal.presence.onSync((peers) =>+ usePresence.getState().applySync(peers)+ )+ const unPeer = window.nodeTerminal.presence.onPeer((diff) =>+ usePresence.getState().applyDiff(diff)+ )+ const me = usePresence.getState().me+ if (me) void sayHello(me)+ else usePresence.setState({ needsName: true })+ return () => {+ unSync()+ unPeer()+ usePresence.getState().reset()+ // Forget what we published, so a reconnect re-announces focus + project from scratch.+ lastFocus = null+ lastProject = null+ }+}++// 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.+let lastFocus: string | null = null+let lastProject: string | null = null++/** Publish "I am working in this node" (null = nowhere). Deduped; safe to call before connect. */+export function reportFocus(nodeId: string | null): void {+ if (lastFocus === nodeId) return+ lastFocus = nodeId+ window.nodeTerminal.presence.focus(nodeId)+}++/** Publish "I am looking at this canvas" (null = no project open). Called from Canvas's+ * active-project effect, so it fires on connect AND on every project switch. Deduped. */+export function reportProject(projectId: string | null): void {+ if (lastProject === projectId) return+ lastProject = projectId+ window.nodeTerminal.presence.project(projectId)+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 79a3eb7bc..8a9211d7b 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1030,9 +1030,13 @@ export interface PresenceApi {/** Publish the project (canvas) we are looking at — peers on other projects are never drawn* on our canvas, and we are never drawn on theirs (null = no project open). */project(projectId: string | null): void- /** Full peer-table snapshot (on join). Returns unsubscribe. */+ /** Full peer-table snapshot (on join). Returns unsubscribe.+ * Exactly one subscriber (the presence store, src/renderer/state/presence.ts): the browser+ * bridge drains its early-event buffer into the FIRST subscriber, so a second one gets nothing.+ * Components read the store; they never subscribe here. */onSync(listener: (peers: PeerState[]) => void): () => void- /** Single-peer diff (join / update / leave). Returns unsubscribe. */+ /** Single-peer diff (join / update / leave). Returns unsubscribe.+ * Exactly one subscriber (the presence store) — same reason as onSync. */onPeer(listener: (diff: PeerDiff) => void): () => void}