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.

fix(presence): key the one-store-per-core guarantee on api identity, fail open on a missing api

enesc2b43b716a03
diff --git a/src/renderer/session/session.test.ts b/src/renderer/session/session.test.ts
index 0930463f0..0f72401d0 100644
--- a/src/renderer/session/session.test.ts
+++ b/src/renderer/session/session.test.ts
@@ -48,10 +48,14 @@ describe('createSession', () => {
expect(getSessionStores(first.id).presence).toBe(storesBefore.presence)
})
- it('gives distinct remote sessions distinct ids and distinct store objects', () => {
- // The property Tasks 2/4 and 4c depend on: per-session stores are never shared.
- const relay = createSession('relay', fakeApi, "Ayşe's Mac")
- const server = createSession('server', fakeApi, 'prod-box')
+ it('gives distinct remote sessions (distinct apis) distinct ids and distinct store objects', () => {
+ // The property Tasks 2/4 and 4c depend on: stores for DIFFERENT cores are never shared.
+ // Each session gets its own api object here — presence is keyed by api identity, so two
+ // sessions on the same api deliberately share a presence store (see the adversarial test).
+ const relayApi = { marker: 'relay' } as unknown as NodeTerminalApi
+ const serverApi = { marker: 'server' } as unknown as NodeTerminalApi
+ const relay = createSession('relay', relayApi, "Ayşe's Mac")
+ const server = createSession('server', serverApi, 'prod-box')
expect(relay.id).not.toBe(server.id)
const relayStores = getSessionStores(relay.id)
const serverStores = getSessionStores(server.id)
@@ -60,6 +64,18 @@ describe('createSession', () => {
expect(relayStores.agentStatus).not.toBe(serverStores.agentStatus)
})
+ it('ADVERSARIAL: a non-local session handed the local api shares the local presence store', () => {
+ // The one-store-per-core guarantee must rest on api IDENTITY, not on the source string a
+ // caller can get wrong. A relay/server session built against the SAME api (a loopback debug
+ // session, a careless test double handing over window.nodeTerminal) must resolve to the
+ // SAME presence store — a second store on the same bridge would subscribe second and miss
+ // the pre-subscribe replay buffer (Stage 1: first subscriber only), silently diverging.
+ const local = createSession('local', fakeApi, 'This Mac')
+ const relay = createSession('relay', fakeApi, 'loopback')
+ expect(relay.id).not.toBe(local.id) // still two sessions…
+ expect(getSessionStores(relay.id).presence).toBe(getSessionStores(local.id).presence) // …ONE store
+ })
+
it('tracks the active session and exposes its api to non-components', () => {
const s = createSession('local', fakeApi, 'This Mac')
setActiveSession(s.id)
diff --git a/src/renderer/session/session.ts b/src/renderer/session/session.ts
index c34b6818f..c3ae112c9 100644
--- a/src/renderer/session/session.ts
+++ b/src/renderer/session/session.ts
@@ -1,6 +1,6 @@
import { createContext, createElement, useContext, type ReactNode } from 'react'
import type { NodeTerminalApi } from '@shared/types'
-import { createPresenceSession, defaultPresence, type PresenceSession } from '../state/presence'
+import { createPresenceSession, type PresenceSession } from '../state/presence'
// Placeholder store-instance type. Task 4 replaces `AgentStatusSession` with the real
// per-session agent-status store type (`../state/agentStatus`) — that store is not a
@@ -42,15 +42,17 @@ const SESSIONS = new Map<string, Entry>()
let activeId: string | null = null
let remoteSeq = 0
-/** 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).
+/** The per-session store instances. `createPresenceSession` is memoized BY API IDENTITY, so the
+ * one-store-per-core guarantee needs no source branch here: the local session's api is
+ * `window.nodeTerminal`, which resolves to the module's default presence instance — the exact
+ * object the ~40 historical `state/presence` imports use — and ANY session handed a repeat api
+ * (a loopback debug session, a test double) shares that api's existing store rather than
+ * racing it for the bridge's first-subscriber replay buffer. A different api (a different
+ * core, a different peer-id space) gets a fresh instance.
* Task 4 replaces the agentStatus placeholder with the real default instance. */
-function buildStores(source: SessionSource, api: NodeTerminalApi): SessionStores {
+function buildStores(api: NodeTerminalApi): SessionStores {
return {
- presence: source === 'local' ? defaultPresence : createPresenceSession(api),
+ presence: createPresenceSession(api),
agentStatus: {} as AgentStatusSession
}
}
@@ -66,7 +68,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(source, api) })
+ SESSIONS.set(id, { session, stores: buildStores(api) })
return session
}
diff --git a/src/renderer/state/presence-session.test.ts b/src/renderer/state/presence-session.test.ts
index cdff39dab..be59ac6de 100644
--- a/src/renderer/state/presence-session.test.ts
+++ b/src/renderer/state/presence-session.test.ts
@@ -21,6 +21,23 @@ function fakeApi(clientId: number) {
return { api: { presence } as any, calls, subs: () => syncSubs }
}
+describe('createPresenceSession — one store per api (memoized by identity)', () => {
+ it('returns the SAME instance for a repeat api object', () => {
+ // Stage 1 invariant: the ws-bridge replays its pre-subscribe buffer to the FIRST subscriber
+ // only, so a second store against the same api would silently miss the join-time sync.
+ const a = fakeApi(1)
+ const first = createPresenceSession(a.api)
+ const second = createPresenceSession(a.api)
+ expect(second).toBe(first)
+ })
+
+ it('returns DIFFERENT instances for different apis', () => {
+ const a = fakeApi(1)
+ const b = fakeApi(2)
+ expect(createPresenceSession(a.api)).not.toBe(createPresenceSession(b.api))
+ })
+})
+
describe('createPresenceSession — per-instance isolation', () => {
it('two instances do not share the lastFocus dedup', () => {
const a = fakeApi(1)
diff --git a/src/renderer/state/presence.ts b/src/renderer/state/presence.ts
index 6943ee931..a99876fbf 100644
--- a/src/renderer/state/presence.ts
+++ b/src/renderer/state/presence.ts
@@ -22,15 +22,19 @@ import {
* 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).
*
- * ONE STORE PER SESSION (stage 4): `createPresenceSession(api)` builds an isolated instance
+ * ONE STORE PER CORE (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.
+ * must never share a table or a cache. The factory is MEMOIZED BY API IDENTITY (a WeakMap): a
+ * repeat call with the same api object returns the existing instance, never a second one. That
+ * is what makes the invariant structural rather than a caller convention — the browser bridge
+ * drains its pre-subscribe event buffer into the FIRST subscriber only (see SOLE SUBSCRIBER),
+ * so a second store on the same api would miss the join-time sync and silently diverge. 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; the memo means any path that asks for a store for `window.nodeTerminal` — the
+ * session registry included — gets that same instance back.
*
* 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
@@ -190,12 +194,33 @@ export interface PresenceSession {
selectTypingFaces(s: PresenceStore, nodeId: string): PeerFace[]
}
+/** One instance per api OBJECT — the one-store-per-core guarantee, keyed on identity (a WeakMap,
+ * so a dropped api never pins its store). Seeded implicitly: `defaultPresence` below is built
+ * through the memoizing factory, so `window.nodeTerminal` maps to it from module load on. */
+const instanceByApi = new WeakMap<NodeTerminalApi, PresenceSession>()
+
/**
- * 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.
+ * The presence store for ONE core (one api). MEMOIZED BY API IDENTITY: a repeat call with the
+ * same api object returns the existing instance — building a second store on the same api would
+ * subscribe to the same channel SECOND, and the bridge replays its pre-subscribe buffer to the
+ * first subscriber only (see the module docblock). A nullish api (node-environment tests that
+ * exercise only the pure helpers) is not memoizable and gets a fresh, inert instance.
*/
export function createPresenceSession(api: NodeTerminalApi): PresenceSession {
+ const existing = api ? instanceByApi.get(api) : undefined
+ if (existing) return existing
+ const session = buildPresenceSession(api)
+ if (api) instanceByApi.set(api, session)
+ return session
+}
+
+/**
+ * Build the presence store for 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. NEVER export this: every consumer must go
+ * through the memoizing `createPresenceSession` above.
+ */
+function buildPresenceSession(api: NodeTerminalApi): PresenceSession {
/**
* THE TYPING MARKS — why the ring does not read `PeerState.typing` off the wire.
*
@@ -441,6 +466,18 @@ export function createPresenceSession(api: NodeTerminalApi): PresenceSession {
* PROVISIONAL_IDENTITY): the prompt (`needsName`) then only renames us.
*/
function connect(): () => void {
+ // FAIL OPEN on a missing api: the module-load capture of `window.nodeTerminal` is safe only
+ // by boot order (see defaultPresence below), and the `as NodeTerminalApi` cast hides a future
+ // violation from the compiler. If someone ever hoists a presence importer ahead of the bridge
+ // install, the failure mode must be "presence is off" (the same degradation the sayHello
+ // catch models) — not a TypeError inside Canvas's effect and a blank app.
+ if (!api?.presence) {
+ if (!helloWarned) {
+ helloWarned = true
+ console.warn('[presence] no presence api — presence is off for this session')
+ }
+ return () => {}
+ }
if (live) return () => {}
const unSync = api.presence.onSync((peers) => store.getState().applySync(peers))
@@ -546,10 +583,13 @@ export function createPresenceSession(api: NodeTerminalApi): PresenceSession {
* (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.
+ * consumers are untouched. Built through the MEMOIZING factory, so this line also seeds the
+ * WeakMap with `window.nodeTerminal → defaultPresence`: any later `createPresenceSession(
+ * window.nodeTerminal)` — the session registry's local session, a loopback debug session, an
+ * adversarial test double — resolves to this same instance, never a parallel twin whose
+ * connect() would race this one for the bridge's first-subscriber replay buffer.
* 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.
+ * helpers: an undefined api is never memoized, and connect() fails open on it.
*/
const defaultPresence = createPresenceSession(
(typeof window === 'undefined' ? undefined : window.nodeTerminal) as NodeTerminalApi