Skip to content

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.

refactor(presence): per-session factory; local session reuses default instance

enes4ed8e8f47f99
diff --git a/src/renderer/session/session.ts b/src/renderer/session/session.ts
index 1d7ecdd50..c34b6818f 100644
--- a/src/renderer/session/session.ts
+++ b/src/renderer/session/session.ts
@@ -1,17 +1,16 @@
import { createContext, createElement, useContext, type ReactNode } from 'react'
import type { NodeTerminalApi } from '@shared/types'
+import { createPresenceSession, defaultPresence, type PresenceSession } from '../state/presence'
-// Placeholder store-instance types. Task 2 replaces `PresenceSession` with the real per-session
-// presence store type (`../state/presence`) and Task 4 does the same for `AgentStatusSession`
-// (`../state/agentStatus`) — those stores are not per-instance factories yet, so importing them
-// here would be wrong. Deliberately not exported: nothing may depend on the placeholder shape.
+// Placeholder store-instance type. Task 4 replaces `AgentStatusSession` with the real
+// per-session agent-status store type (`../state/agentStatus`) — that store is not a
+// per-instance factory yet, so importing it here would be wrong. Deliberately not exported:
+// nothing may depend on the placeholder shape.
// BRANDED on purpose: a bare `object` would accept a real store, so wiring one into
// `buildStores()` while forgetting to swap the alias would typecheck cleanly and leave the
// slot typed as a placeholder forever. The unique-symbol brand makes that assignment a compile
// error at the exact line — replacing the alias is the only way to satisfy the compiler.
declare const PLACEHOLDER: unique symbol
-/** Task 2 replaces this with the real per-session presence store type. */
-type PresenceSession = { readonly [PLACEHOLDER]: 'replace in Task 2' }
/** Task 4 replaces this with the real per-session agent-status store type. */
type AgentStatusSession = { readonly [PLACEHOLDER]: 'replace in Task 4' }
@@ -43,10 +42,17 @@ const SESSIONS = new Map<string, Entry>()
let activeId: string | null = null
let remoteSeq = 0
-/** Task 2/4 replace this with the real default instances for the local session. Until then a
- * minimal placeholder keeps the registry shape honest without pulling in the stores. */
-function buildStores(): SessionStores {
- return { presence: {} as PresenceSession, agentStatus: {} as AgentStatusSession }
+/** The per-session store instances. The LOCAL session reuses the module's default presence
+ * instance — the exact object the ~40 historical `state/presence` imports resolve to — so
+ * there is ONE local presence store, never a parallel twin whose connect() would race the
+ * default's subscription for the bridge's first-subscriber replay buffer. A remote session
+ * gets a fresh instance bound to ITS api (a different core, a different peer-id space).
+ * Task 4 replaces the agentStatus placeholder with the real default instance. */
+function buildStores(source: SessionSource, api: NodeTerminalApi): SessionStores {
+ return {
+ presence: source === 'local' ? defaultPresence : createPresenceSession(api),
+ agentStatus: {} as AgentStatusSession
+ }
}
/** Idempotent per id: if the id already exists, the EXISTING session is returned and nothing is
@@ -60,7 +66,7 @@ export function createSession(source: SessionSource, api: NodeTerminalApi, label
const existing = SESSIONS.get(id)
if (existing) return existing.session
const session: WorkspaceSession = { id, source, label, api, status: 'connected' }
- SESSIONS.set(id, { session, stores: buildStores() })
+ SESSIONS.set(id, { session, stores: buildStores(source, api) })
return session
}
diff --git a/src/renderer/state/presence-session.test.ts b/src/renderer/state/presence-session.test.ts
new file mode 100644
index 000000000..cdff39dab
--- /dev/null
+++ b/src/renderer/state/presence-session.test.ts
@@ -0,0 +1,71 @@
+import { describe, it, expect, vi } from 'vitest'
+import type { PeerState } from '@shared/presence'
+import { createPresenceSession } from './presence'
+
+/** A recording fake NodeTerminalApi.presence; onSync/onPeer are spies so we can assert exactly-once. */
+function fakeApi(clientId: number) {
+ const calls: Array<[string, unknown]> = []
+ let syncSubs = 0
+ const presence = {
+ hello: vi.fn(async () => ({ clientId, peers: [] as PeerState[] })),
+ 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: (p: PeerState[]) => void) => {
+ syncSubs++
+ return () => {}
+ },
+ onPeer: (_cb: (d: unknown) => void) => () => {}
+ }
+ return { api: { presence } as any, calls, subs: () => syncSubs }
+}
+
+describe('createPresenceSession — per-instance isolation', () => {
+ it('two instances do not share the lastFocus dedup', () => {
+ const a = fakeApi(1)
+ const b = fakeApi(2)
+ const sa = createPresenceSession(a.api)
+ const sb = createPresenceSession(b.api)
+ // Force "peers exist" so reportFocus casts (it gates on hasPeers).
+ sa.store.setState({ myId: 1, peers: { 1: {} as PeerState, 9: {} as PeerState } })
+ sb.store.setState({ myId: 2, peers: { 2: {} as PeerState, 9: {} as PeerState } })
+ sa.reportFocus('n1')
+ sa.reportFocus('n1') // deduped within A → one cast
+ sb.reportFocus('n1') // B has its OWN lastFocus → still casts
+ expect(a.calls.filter((c) => c[0] === 'focus')).toEqual([['focus', 'n1']])
+ expect(b.calls.filter((c) => c[0] === 'focus')).toEqual([['focus', 'n1']])
+ })
+
+ it('connect() is idempotent per instance (subscribes at most once), independently per session', () => {
+ const a = fakeApi(1)
+ const s = createPresenceSession(a.api)
+ const stop1 = s.connect()
+ const stop2 = s.connect() // second is inert
+ expect(a.subs()).toBe(1)
+ stop2()
+ stop1()
+ })
+
+ it('each instance has its own faceCache (a peer in A never appears in B.selectFaces)', () => {
+ const a = fakeApi(1)
+ const b = fakeApi(2)
+ const sa = createPresenceSession(a.api)
+ const sb = createPresenceSession(b.api)
+ const peer = (id: number): PeerState => ({
+ clientId: id,
+ name: `P${id}`,
+ color: '#fff',
+ cursor: null,
+ focus: null,
+ chat: null,
+ typing: null,
+ projectId: 'web',
+ kind: 'browser'
+ })
+ sa.store.setState({ myId: 1, peers: { 1: peer(1), 5: peer(5) } })
+ sb.store.setState({ myId: 2, peers: { 2: peer(2) } })
+ expect(sa.selectFaces(sa.store.getState()).map((f) => f.clientId)).toEqual([5])
+ expect(sb.selectFaces(sb.store.getState()).map((f) => f.clientId)).toEqual([])
+ })
+})
diff --git a/src/renderer/state/presence.ts b/src/renderer/state/presence.ts
index fb85eb0ce..6943ee931 100644
--- a/src/renderer/state/presence.ts
+++ b/src/renderer/state/presence.ts
@@ -1,4 +1,5 @@
-import { create } from 'zustand'
+import { create, type StoreApi, type UseBoundStore } from 'zustand'
+import type { NodeTerminalApi } from '@shared/types'
import {
nextFreeColor,
peersOnProject,
@@ -17,16 +18,26 @@ import {
} from '../lib/typingPeers'
/**
- * Transient team-presence store (docs/team-presence.md). Holds the peer table for the current
+ * Transient team-presence store (docs/team-presence.md). Holds the peer table for one
* 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() subscribes AT MOST ONCE (the module-level `live` handle below makes that
- * structural, not a convention — a second call is inert). 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.
+ * ONE STORE PER SESSION (stage 4): `createPresenceSession(api)` builds an isolated instance
+ * around one core's api — every stateful piece (the store, the typing-sweep timer, the face
+ * cache, the connect guard, the focus/project dedup, the hello-warned latch) is closed over
+ * the instance, because peer ids from two different cores live in two different id spaces and
+ * must never share a table or a cache. The module keeps a DEFAULT instance bound to
+ * `window.nodeTerminal` (the local core) and re-exports its members under the historical names,
+ * so the existing single-session consumers are untouched. Session instances are built ONLY by
+ * the session registry (`session/session.ts` `createSession`, idempotent per id), never ad hoc —
+ * that is what keeps the subscriber count below structural.
+ *
+ * SOLE SUBSCRIBER: a session's presence store is the ONLY place that may call its api's
+ * presence.onSync / presence.onPeer, and connect() subscribes AT MOST ONCE (the per-instance
+ * `live` handle below makes that structural, not a convention — a second call is inert). 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.
*
* NEVER MY OWN PEER: the hub's table includes us, so every selector filters on `myId` — and while
* `myId` is null (hello in flight, or a failed handshake) they return NOTHING at all. That null
@@ -46,7 +57,10 @@ import {
export const ME_KEY = 'nodeterm.presence.me'
-/** The local user's saved identity, or null on first run / corrupt storage. */
+/** The local user's saved identity, or null on first run / corrupt storage.
+ * DELIBERATELY SHARED ACROSS SESSIONS: {name, color} is who the HUMAN is, not per-core state —
+ * connecting to a teammate's core does not make you a different person, and a per-session key
+ * would force a re-prompt (and allow a diverging color) on every remote host. */
export function loadIdentity(): PeerIdentity | null {
try {
const raw = localStorage.getItem(ME_KEY)
@@ -67,7 +81,8 @@ export function saveIdentity(id: PeerIdentity): void {
}
}
-/** A starting point for the name prompt: empty name, an unused-looking color. */
+/** A starting point for the name prompt: empty name, an unused-looking color.
+ * Reads the DEFAULT (local) session's peers — the prompt is a local-session surface. */
export function suggestIdentity(): PeerIdentity {
const taken = Object.values(usePresence.getState().peers).map((p) => p.color)
return { name: '', color: nextFreeColor(taken) }
@@ -92,107 +107,11 @@ export interface PresenceStore {
reset(): void
}
-/**
- * THE TYPING MARKS — why the ring does not read `PeerState.typing` off the wire.
- *
- * CLOCK: `PeerState.typing.at` is stamped on the HOST's clock; the ~2 s decay runs on the VIEWER's
- * (a browser, a phone), which can be minutes off. Decaying against the wire stamp would pin a ring
- * on forever or suppress it entirely, so every typing patch is RE-STAMPED with the local time we
- * observed it (`markTyping(..., Date.now())`) and the decay runs against that. One clock, end to end.
- *
- * SNAPSHOTS: the hub keeps no timers and never clears `typing`, so a `presence:sync` (or the hello
- * response) can carry a peer's typing from ten minutes ago. We therefore mark ONLY on a live `update`
- * diff and NEVER seed from a snapshot — a stale stamp in a join snapshot can light nothing.
- *
- * A stale mark for a peer who has left is harmless: the selectors skip a clientId that is not in the
- * peer table, and the sweep (armed for as long as any mark exists) removes it within TYPING_DECAY_MS.
- */
-export const usePresence = create<PresenceStore>((set, get) => ({
- myId: null,
- me: loadIdentity(),
- peers: {},
- typing: {},
- 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 } // `typing` untouched: a snapshot may not light a ring (see above)
- }),
-
- applyDiff: (diff) => {
- const marksBefore = get().typing
- 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, typing: dropTyping(s.typing, diff.clientId) }
- }
- const prev = s.peers[diff.clientId]
- if (!prev) return s // an update for a peer we never saw join — ignore, never ghost a row
- const peers = { ...s.peers, [diff.clientId]: { ...prev, ...diff.patch } }
- const t = diff.patch.typing
- if (!t) return { peers }
- return { peers, typing: markTyping(s.typing, diff.clientId, t.nodeId, Date.now()) }
- })
- // Arm (or re-arm) the decay sweep AFTER the write, never inside the reducer — and ONLY when the
- // marks actually moved. A cursor patch (~20/s per peer) must not churn the timer, and a canvas
- // nobody else is typing on must not have one at all.
- const marksAfter = get().typing
- if (marksAfter !== marksBefore) armSweep(marksAfter)
- },
-
- reset: () => {
- cancelSweep()
- set({ myId: null, peers: {}, typing: {}, needsName: false })
- }
-}))
-
-/**
- * The decay sweep: the hub never sends a "stopped typing" event (it keeps no timers), so the ring
- * has to fade on OUR side. ONE timer for the whole app — not one per node — armed at the earliest
- * mark's expiry and re-armed after each sweep while any mark is left.
- *
- * A SOLO USER PAYS NOTHING: no peers → no typing diffs → no marks → nextTypingSweepDelay is null →
- * no timer is ever created. The timer exists only while someone is actually typing into a node.
- */
-let sweepTimer: ReturnType<typeof setTimeout> | null = null
-
-function cancelSweep(): void {
- if (sweepTimer !== null) clearTimeout(sweepTimer)
- sweepTimer = null
-}
-
-function armSweep(marks: TypingMarks): void {
- const delay = nextTypingSweepDelay(marks, Date.now())
- if (delay === null) return cancelSweep() // nobody is typing → no timer at all
- cancelSweep()
- sweepTimer = setTimeout(sweep, delay)
-}
-
-function sweep(): void {
- sweepTimer = null
- const s = usePresence.getState()
- const next = pruneTyping(s.typing, Date.now())
- // pruneTyping returns the SAME map when nothing decayed, so a still-typing peer costs no write
- // (and so re-renders nobody) on the ticks in between.
- if (next !== s.typing) usePresence.setState({ typing: next })
- armSweep(next)
-}
-
/** Everyone except me, on ANY project — the base of every other selector (the facepile shows who
* is working where, so it does NOT filter by project).
* While `myId` is null we cannot tell our own peer from a teammate's, so we return NOBODY: an
- * empty facepile for one round-trip is right; listing yourself as your own teammate never is. */
+ * empty facepile for one round-trip is right; listing yourself as your own teammate never is.
+ * PURE and state-agnostic (no per-session cache), so one function serves every session. */
export function selectOthers(s: PresenceStore): PeerState[] {
if (s.myId === null) return []
return Object.values(s.peers).filter((p) => p.clientId !== s.myId)
@@ -227,47 +146,9 @@ export interface PeerFace {
kind: PeerState['kind']
}
-/** clientId → the last face we handed out, so an unchanged face keeps its object identity. */
-const faceCache = new Map<ClientId, PeerFace>()
-
-/** The cached face for a peer: the SAME object as last time while none of the five projected fields
- * changed — that identity is what makes every face-based selector cursor-immune. */
-function faceFor(p: PeerState): PeerFace {
- const prev = faceCache.get(p.clientId)
- if (
- prev &&
- prev.name === p.name &&
- prev.color === p.color &&
- prev.projectId === p.projectId &&
- prev.kind === p.kind
- ) {
- return prev
- }
- const face: PeerFace = {
- clientId: p.clientId,
- name: p.name,
- color: p.color,
- projectId: p.projectId,
- kind: p.kind
- }
- faceCache.set(p.clientId, face)
- return face
-}
-
-/** The facepile projection: everyone but me, cursor-immune (see PeerFace). Pair it with
- * `useShallow` — the array is fresh each call, its ELEMENTS are not. */
-export function selectFaces(s: PresenceStore): PeerFace[] {
- const others = selectOthers(s)
- const faces = others.map(faceFor)
- // Prune rather than accumulate: a peer that left must not linger in the cache. (This is the only
- // pruner — selectFocusedFaces sees a subset of the peers and must never evict the rest.)
- const alive = new Set(others.map((p) => p.clientId))
- for (const id of faceCache.keys()) if (!alive.has(id)) faceCache.delete(id)
- 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). */
+ * common case allocates NOTHING and its identity is stable across calls (useShallow bails out).
+ * Safe to share across sessions: it is immutable and carries no peer state. */
const NO_FACES: PeerFace[] = []
/** Is there anyone but me in the table? The literal question the chip fast path asks — not a proxy
@@ -286,63 +167,6 @@ function hasOtherPeers(s: PresenceStore): boolean {
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.
- *
- * PERF, and the reason this is not just `selectFocused`: there is one chip strip PER NODE, and
- * `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.
- *
- * 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 nobody else in the table), return NO_FACES. */
-export function selectFocusedFaces(
- s: PresenceStore,
- nodeId: string,
- projectId: string | null
-): PeerFace[] {
- // 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_FACES
- const focused = selectFocused(s, nodeId, projectId)
- if (focused.length === 0) return NO_FACES
- return focused.map(faceFor)
-}
-
-/**
- * The peers TYPING INTO this node right now — the pulsing ring in its header. Same cursor-immune
- * PeerFace projection as the chips (see selectFocusedFaces), so pair it with `useShallow`.
- *
- * DELIBERATELY NOT PROJECT-FILTERED, unlike every other node-scoped selector here. A phone has
- * `projectId: null` (it has no canvas), so `peersOnProject` excludes it — and "someone is typing
- * into this shell from their phone" is exactly the case this feature exists to surface. The filter
- * exists because cursors and focus are only meaningful in a project's own coordinate/node space;
- * `typing.nodeId` is neither: it is the session's persistKey, GLOBALLY unique, so keying the ring
- * off it against the FULL peer table cannot chip the wrong node. If the peer is not typing into a
- * node on our canvas, no mounted header asks about their nodeId and nothing is drawn.
- *
- * CURSOR IMMUNITY: a cursor patch touches `peers` only — never `typing` — and faces are the same
- * objects until a name/color/project/kind changes, so this returns a shallow-equal array (usually
- * the shared NO_FACES) on every cursor tick and re-renders nothing.
- */
-export function selectTypingFaces(s: PresenceStore, nodeId: string): PeerFace[] {
- if (s.myId === null) return NO_FACES // hello unresolved → we cannot rule out our own keystrokes
- const ids = typingClientIds(s.typing, nodeId, Date.now())
- if (ids.length === 0) return NO_FACES // the common case, allocation-free (see typingClientIds)
- const faces: PeerFace[] = []
- for (const id of ids) {
- // Never me: my own writes are echoed back to me as a diff, and a ring on my own keystrokes
- // would be noise. A mark for a peer who has left has no face — skip it.
- if (id === s.myId) continue
- const peer = s.peers[id]
- if (peer) faces.push(faceFor(peer))
- }
- return faces.length > 0 ? faces : NO_FACES
-}
-
/** Sent when the user has not named themselves yet. It claims NOTHING — sanitizeIdentity falls
* back to the peer's current name on an empty string, and to its current color on an off-palette
* one — so the hub keeps the "Someone" + next-free color it assigned at join. Its only job is to
@@ -350,141 +174,393 @@ export function selectTypingFaces(s: PresenceStore, nodeId: string): PeerFace[]
* renames us with a second hello. */
const PROVISIONAL_IDENTITY: PeerIdentity = { name: '', color: '' }
-/** A failed handshake logs once per session, not once per retry. */
-let helloWarned = false
+/** One session's presence: its store, its connection lifecycle, and its face-projecting selectors
+ * (the pure selectors are on here too, so a session-scoped consumer needs only this object). */
+export interface PresenceSession {
+ store: UseBoundStore<StoreApi<PresenceStore>>
+ connect(): () => void
+ reportFocus(nodeId: string | null): void
+ releaseFocus(nodeId: string): void
+ reportProject(projectId: string | null): void
+ selectOthers(s: PresenceStore): PeerState[]
+ selectVisible(s: PresenceStore, projectId: string | null): PeerState[]
+ selectFocused(s: PresenceStore, nodeId: string, projectId: string | null): PeerState[]
+ selectFaces(s: PresenceStore): PeerFace[]
+ selectFocusedFaces(s: PresenceStore, nodeId: string, projectId: string | null): PeerFace[]
+ selectTypingFaces(s: PresenceStore, nodeId: string): PeerFace[]
+}
/**
- * 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).
- *
- * The seed REPLACES the table wholesale, and that is only safe because of two properties — do not
- * move this seed onto an unordered path (a fan-out event, a second channel, a retry queue):
- * 1. the hub snapshots peers() INSIDE the hello handler, so the response is a consistent table
- * as of that moment, and
- * 2. hello's response and the presence:peer diffs share one FIFO transport (ipcRenderer /
- * the single ws), so every diff we already applied is included in that snapshot and every
- * diff we apply after it happened after it.
- * Break either one and a peer who joins mid-handshake gets silently overwritten out of the table.
- *
- * A rejection (ws dropped mid-handshake, a host without the channel) must never become an
- * unhandled rejection: we log once and leave myId null, which the selectors read as "presence is
- * off" — degraded, but never "I am my own peer".
+ * Build the presence store for ONE session (one core's api). Everything stateful lives in this
+ * closure; `api` is dereferenced only at call time (hello/connect/focus/project), never here —
+ * so constructing an instance costs nothing and touches no wire.
*/
-async function sayHello(id: PeerIdentity): Promise<void> {
- try {
- 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 })
- } catch (err) {
- if (!helloWarned) {
- helloWarned = true
- console.warn('[presence] hello failed — presence is off for this session', err)
+export function createPresenceSession(api: NodeTerminalApi): PresenceSession {
+ /**
+ * THE TYPING MARKS — why the ring does not read `PeerState.typing` off the wire.
+ *
+ * CLOCK: `PeerState.typing.at` is stamped on the HOST's clock; the ~2 s decay runs on the VIEWER's
+ * (a browser, a phone), which can be minutes off. Decaying against the wire stamp would pin a ring
+ * on forever or suppress it entirely, so every typing patch is RE-STAMPED with the local time we
+ * observed it (`markTyping(..., Date.now())`) and the decay runs against that. One clock, end to end.
+ *
+ * SNAPSHOTS: the hub keeps no timers and never clears `typing`, so a `presence:sync` (or the hello
+ * response) can carry a peer's typing from ten minutes ago. We therefore mark ONLY on a live `update`
+ * diff and NEVER seed from a snapshot — a stale stamp in a join snapshot can light nothing.
+ *
+ * A stale mark for a peer who has left is harmless: the selectors skip a clientId that is not in the
+ * peer table, and the sweep (armed for as long as any mark exists) removes it within TYPING_DECAY_MS.
+ */
+ const store = create<PresenceStore>((set, get) => ({
+ myId: null,
+ me: loadIdentity(),
+ peers: {},
+ typing: {},
+ 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 } // `typing` untouched: a snapshot may not light a ring (see above)
+ }),
+
+ applyDiff: (diff) => {
+ const marksBefore = get().typing
+ 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, typing: dropTyping(s.typing, diff.clientId) }
+ }
+ const prev = s.peers[diff.clientId]
+ if (!prev) return s // an update for a peer we never saw join — ignore, never ghost a row
+ const peers = { ...s.peers, [diff.clientId]: { ...prev, ...diff.patch } }
+ const t = diff.patch.typing
+ if (!t) return { peers }
+ return { peers, typing: markTyping(s.typing, diff.clientId, t.nodeId, Date.now()) }
+ })
+ // Arm (or re-arm) the decay sweep AFTER the write, never inside the reducer — and ONLY when the
+ // marks actually moved. A cursor patch (~20/s per peer) must not churn the timer, and a canvas
+ // nobody else is typing on must not have one at all.
+ const marksAfter = get().typing
+ if (marksAfter !== marksBefore) armSweep(marksAfter)
+ },
+
+ reset: () => {
+ cancelSweep()
+ set({ myId: null, peers: {}, typing: {}, needsName: false })
}
+ }))
+
+ /**
+ * The decay sweep: the hub never sends a "stopped typing" event (it keeps no timers), so the ring
+ * has to fade on OUR side. ONE timer for the whole session — not one per node — armed at the
+ * earliest mark's expiry and re-armed after each sweep while any mark is left.
+ *
+ * A SOLO USER PAYS NOTHING: no peers → no typing diffs → no marks → nextTypingSweepDelay is null →
+ * no timer is ever created. The timer exists only while someone is actually typing into a node.
+ */
+ let sweepTimer: ReturnType<typeof setTimeout> | null = null
+
+ function cancelSweep(): void {
+ if (sweepTimer !== null) clearTimeout(sweepTimer)
+ sweepTimer = null
}
-}
-/** The live connection, or null. Makes the single-subscriber invariant STRUCTURAL: a second
- * connect (Fast Refresh, a stray double mount) is inert, and a teardown only tears down the
- * connection IT created — otherwise the stale teardown would reset() the store (dropping myId
- * and the whole table) while the live subscription, which will never re-seed, kept running. */
-let live: { stop: () => void } | null = null
+ function armSweep(marks: TypingMarks): void {
+ const delay = nextTypingSweepDelay(marks, Date.now())
+ if (delay === null) return cancelSweep() // nobody is typing → no timer at all
+ cancelSweep()
+ sweepTimer = setTimeout(sweep, delay)
+ }
-/**
- * Subscribe to the presence stream and announce ourselves; returns a teardown. Called from Canvas
- * in a []-effect — but calling it twice is safe (the second call is a no-op returning a no-op).
- * Subscribing BEFORE hello matters: any diff that lands while hello is in flight must be applied
- * on top of the snapshot, not dropped. We say hello even with no stored identity (see
- * PROVISIONAL_IDENTITY): the prompt (`needsName`) then only renames us.
- */
-export function connectPresence(): () => void {
- if (live) return () => {}
-
- 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) usePresence.setState({ needsName: true })
- void sayHello(me ?? PROVISIONAL_IDENTITY)
-
- const handle = {
- stop: () => {
- if (live !== handle) return // already torn down, or superseded — touch nothing
- live = null
- unSync()
- unPeer()
- usePresence.getState().reset()
- faceCache.clear()
- // Forget what we published, so a reconnect re-announces focus + project from scratch.
- lastFocus = null
- lastProject = null
+ function sweep(): void {
+ sweepTimer = null
+ const s = store.getState()
+ const next = pruneTyping(s.typing, Date.now())
+ // pruneTyping returns the SAME map when nothing decayed, so a still-typing peer costs no write
+ // (and so re-renders nobody) on the ticks in between.
+ if (next !== s.typing) store.setState({ typing: next })
+ armSweep(next)
+ }
+
+ /** clientId → the last face we handed out, so an unchanged face keeps its object identity.
+ * PER SESSION: client ids from two cores are two id spaces — one shared map would hand
+ * session B a face cached for a colliding id in session A. */
+ const faceCache = new Map<ClientId, PeerFace>()
+
+ /** The cached face for a peer: the SAME object as last time while none of the five projected fields
+ * changed — that identity is what makes every face-based selector cursor-immune. */
+ function faceFor(p: PeerState): PeerFace {
+ const prev = faceCache.get(p.clientId)
+ if (
+ prev &&
+ prev.name === p.name &&
+ prev.color === p.color &&
+ prev.projectId === p.projectId &&
+ prev.kind === p.kind
+ ) {
+ return prev
}
+ const face: PeerFace = {
+ clientId: p.clientId,
+ name: p.name,
+ color: p.color,
+ projectId: p.projectId,
+ kind: p.kind
+ }
+ faceCache.set(p.clientId, face)
+ return face
}
- live = handle
- return handle.stop
-}
-// 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 = null
-let lastProject: string | null = null
+ /** The facepile projection: everyone but me, cursor-immune (see PeerFace). Pair it with
+ * `useShallow` — the array is fresh each call, its ELEMENTS are not. */
+ function selectFaces(s: PresenceStore): PeerFace[] {
+ const others = selectOthers(s)
+ const faces = others.map(faceFor)
+ // Prune rather than accumulate: a peer that left must not linger in the cache. (This is the only
+ // pruner — selectFocusedFaces sees a subset of the peers and must never evict the rest.)
+ const alive = new Set(others.map((p) => p.clientId))
+ for (const id of faceCache.keys()) if (!alive.has(id)) faceCache.delete(id)
+ return faces
+ }
-/**
- * Publish "I am working in this node" (null = nowhere). Deduped; safe to call before connect.
- *
- * ALONE, IT PUBLISHES NOTHING. A focus only exists to be drawn on somebody else's canvas, and every
- * terminal hover-dwell / leave calls this — so with no peers the cast is pure cost (an IPC
- * round-trip and a hub write per hover, on a path a solo user is on constantly). Same guard
- * PtyManager.write already uses for typing attribution: presence is FREE when you are by yourself.
- *
- * The CLEAR is deliberately not gated: `lastFocus` is only ever non-null because a publish went out
- * while peers existed, and if the last peer leaves while we sit in that node, the hub still holds
- * our focus — the next peer to join would receive it in its snapshot and chip a node we left long
- * ago. So a retraction always goes out (the dedup above makes it a no-op when we never published).
- */
-export function reportFocus(nodeId: string | null): void {
- if (lastFocus === nodeId) return
- if (nodeId !== null && !hasPeers()) return
- lastFocus = nodeId
- window.nodeTerminal.presence.focus(nodeId)
-}
+ /** 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.
+ *
+ * PERF, and the reason this is not just `selectFocused`: there is one chip strip PER NODE, and
+ * `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.
+ *
+ * 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 nobody else in the table), return NO_FACES. */
+ function selectFocusedFaces(
+ s: PresenceStore,
+ nodeId: string,
+ projectId: string | null
+ ): PeerFace[] {
+ // 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_FACES
+ const focused = selectFocused(s, nodeId, projectId)
+ if (focused.length === 0) return NO_FACES
+ return focused.map(faceFor)
+ }
-/** Is anyone else connected? (The table includes me, so "somebody else" is > 1.) */
-function hasPeers(): boolean {
- return Object.keys(usePresence.getState().peers).length > 1
-}
+ /**
+ * The peers TYPING INTO this node right now — the pulsing ring in its header. Same cursor-immune
+ * PeerFace projection as the chips (see selectFocusedFaces), so pair it with `useShallow`.
+ *
+ * DELIBERATELY NOT PROJECT-FILTERED, unlike every other node-scoped selector here. A phone has
+ * `projectId: null` (it has no canvas), so `peersOnProject` excludes it — and "someone is typing
+ * into this shell from their phone" is exactly the case this feature exists to surface. The filter
+ * exists because cursors and focus are only meaningful in a project's own coordinate/node space;
+ * `typing.nodeId` is neither: it is the session's persistKey, GLOBALLY unique, so keying the ring
+ * off it against the FULL peer table cannot chip the wrong node. If the peer is not typing into a
+ * node on our canvas, no mounted header asks about their nodeId and nothing is drawn.
+ *
+ * CURSOR IMMUNITY: a cursor patch touches `peers` only — never `typing` — and faces are the same
+ * objects until a name/color/project/kind changes, so this returns a shallow-equal array (usually
+ * the shared NO_FACES) on every cursor tick and re-renders nothing.
+ */
+ function selectTypingFaces(s: PresenceStore, nodeId: string): PeerFace[] {
+ if (s.myId === null) return NO_FACES // hello unresolved → we cannot rule out our own keystrokes
+ const ids = typingClientIds(s.typing, nodeId, Date.now())
+ if (ids.length === 0) return NO_FACES // the common case, allocation-free (see typingClientIds)
+ const faces: PeerFace[] = []
+ for (const id of ids) {
+ // Never me: my own writes are echoed back to me as a diff, and a ring on my own keystrokes
+ // would be noise. A mark for a peer who has left has no face — skip it.
+ if (id === s.myId) continue
+ const peer = s.peers[id]
+ if (peer) faces.push(faceFor(peer))
+ }
+ return faces.length > 0 ? faces : NO_FACES
+ }
-/** "This node is no longer where I work" — the counterpart of reportFocus(nodeId), for a node that
- * is losing focus (mouse left, unmounted). It clears the focus ONLY if this node is the one we
- * actually published: a node's leave/unmount can land AFTER the next node's enter (the mouse moves
- * on; a project switch unmounts the old canvas), and an unconditional reportFocus(null) would then
- * blank the chips on the node the user just moved into. */
-export function releaseFocus(nodeId: string): void {
- if (lastFocus !== nodeId) return
- reportFocus(null)
-}
+ /** A failed handshake logs once per session, not once per retry. */
+ let helloWarned = false
+
+ /**
+ * 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).
+ *
+ * The seed REPLACES the table wholesale, and that is only safe because of two properties — do not
+ * move this seed onto an unordered path (a fan-out event, a second channel, a retry queue):
+ * 1. the hub snapshots peers() INSIDE the hello handler, so the response is a consistent table
+ * as of that moment, and
+ * 2. hello's response and the presence:peer diffs share one FIFO transport (ipcRenderer /
+ * the single ws), so every diff we already applied is included in that snapshot and every
+ * diff we apply after it happened after it.
+ * Break either one and a peer who joins mid-handshake gets silently overwritten out of the table.
+ *
+ * A rejection (ws dropped mid-handshake, a host without the channel) must never become an
+ * unhandled rejection: we log once and leave myId null, which the selectors read as "presence is
+ * off" — degraded, but never "I am my own peer".
+ */
+ async function sayHello(id: PeerIdentity): Promise<void> {
+ try {
+ const res = await api.presence.hello(id)
+ const table: Record<ClientId, PeerState> = {}
+ for (const p of res.peers) table[p.clientId] = p
+ store.setState({ myId: res.clientId, peers: table })
+ } catch (err) {
+ if (!helloWarned) {
+ helloWarned = true
+ console.warn('[presence] hello failed — presence is off for this session', err)
+ }
+ }
+ }
+
+ /** The live connection, or null. Makes the single-subscriber invariant STRUCTURAL: a second
+ * connect (Fast Refresh, a stray double mount) is inert, and a teardown only tears down the
+ * connection IT created — otherwise the stale teardown would reset() the store (dropping myId
+ * and the whole table) while the live subscription, which will never re-seed, kept running. */
+ let live: { stop: () => void } | null = null
+
+ /**
+ * Subscribe to the presence stream and announce ourselves; returns a teardown. Called from Canvas
+ * in a []-effect — but calling it twice is safe (the second call is a no-op returning a no-op).
+ * Subscribing BEFORE hello matters: any diff that lands while hello is in flight must be applied
+ * on top of the snapshot, not dropped. We say hello even with no stored identity (see
+ * PROVISIONAL_IDENTITY): the prompt (`needsName`) then only renames us.
+ */
+ function connect(): () => void {
+ if (live) return () => {}
+
+ const unSync = api.presence.onSync((peers) => store.getState().applySync(peers))
+ const unPeer = api.presence.onPeer((diff) => store.getState().applyDiff(diff))
+ const me = store.getState().me
+ if (!me) store.setState({ needsName: true })
+ void sayHello(me ?? PROVISIONAL_IDENTITY)
+
+ const handle = {
+ stop: () => {
+ if (live !== handle) return // already torn down, or superseded — touch nothing
+ live = null
+ unSync()
+ unPeer()
+ store.getState().reset()
+ faceCache.clear()
+ // Forget what we published, so a reconnect re-announces focus + project from scratch.
+ lastFocus = null
+ lastProject = null
+ }
+ }
+ live = handle
+ return handle.stop
+ }
+
+ // 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 = null
+ let lastProject: string | null = null
+
+ /**
+ * Publish "I am working in this node" (null = nowhere). Deduped; safe to call before connect.
+ *
+ * ALONE, IT PUBLISHES NOTHING. A focus only exists to be drawn on somebody else's canvas, and every
+ * terminal hover-dwell / leave calls this — so with no peers the cast is pure cost (an IPC
+ * round-trip and a hub write per hover, on a path a solo user is on constantly). Same guard
+ * PtyManager.write already uses for typing attribution: presence is FREE when you are by yourself.
+ *
+ * The CLEAR is deliberately not gated: `lastFocus` is only ever non-null because a publish went out
+ * while peers existed, and if the last peer leaves while we sit in that node, the hub still holds
+ * our focus — the next peer to join would receive it in its snapshot and chip a node we left long
+ * ago. So a retraction always goes out (the dedup above makes it a no-op when we never published).
+ */
+ function reportFocus(nodeId: string | null): void {
+ if (lastFocus === nodeId) return
+ if (nodeId !== null && !hasPeers()) return
+ lastFocus = nodeId
+ api.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)
+ /** Is anyone else connected? (The table includes me, so "somebody else" is > 1.) */
+ function hasPeers(): boolean {
+ return Object.keys(store.getState().peers).length > 1
+ }
+
+ /** "This node is no longer where I work" — the counterpart of reportFocus(nodeId), for a node that
+ * is losing focus (mouse left, unmounted). It clears the focus ONLY if this node is the one we
+ * actually published: a node's leave/unmount can land AFTER the next node's enter (the mouse moves
+ * on; a project switch unmounts the old canvas), and an unconditional reportFocus(null) would then
+ * blank the chips on the node the user just moved into. */
+ function releaseFocus(nodeId: string): void {
+ if (lastFocus !== nodeId) return
+ reportFocus(null)
+ }
+
+ /** 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. */
+ function reportProject(projectId: string | null): void {
+ if (lastProject === projectId) return
+ lastProject = projectId
+ api.presence.project(projectId)
+ }
+
+ return {
+ store,
+ connect,
+ reportFocus,
+ releaseFocus,
+ reportProject,
+ selectOthers,
+ selectVisible,
+ selectFocused,
+ selectFaces,
+ selectFocusedFaces,
+ selectTypingFaces
+ }
}
+
+/**
+ * The DEFAULT instance — the local core's presence, bound to `window.nodeTerminal` BY IDENTITY
+ * (the same capture localSession.ts makes, and safe for the same boot-order reason documented
+ * there: preload/bridge define nodeTerminal before any importer of this module runs). Every
+ * historical export below resolves to this exact object, so the ~40 existing single-session
+ * consumers are untouched; the session registry hands this same instance out for the 'local'
+ * session, so there is ONE local store — never a parallel twin with its own subscription.
+ * The `typeof window` guard exists for node-environment unit tests that exercise only the pure
+ * helpers: `api` is dereferenced at call time, so an undefined capture is harmless there.
+ */
+const defaultPresence = createPresenceSession(
+ (typeof window === 'undefined' ? undefined : window.nodeTerminal) as NodeTerminalApi
+)
+export { defaultPresence }
+
+export const usePresence = defaultPresence.store
+export const connectPresence = defaultPresence.connect
+export const reportFocus = defaultPresence.reportFocus
+export const releaseFocus = defaultPresence.releaseFocus
+export const reportProject = defaultPresence.reportProject
+export const selectFaces = defaultPresence.selectFaces
+export const selectFocusedFaces = defaultPresence.selectFocusedFaces
+export const selectTypingFaces = defaultPresence.selectTypingFaces