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(relay): route presence components + cursor/chat write to the active session (collab Task 2)
enesf4b7f416fc1a
diff --git a/src/renderer/components/Facepile.tsx b/src/renderer/components/Facepile.tsxindex c2d22cf7e..b1572ff90 100644--- a/src/renderer/components/Facepile.tsx+++ b/src/renderer/components/Facepile.tsx@@ -1,6 +1,6 @@import { useShallow } from 'zustand/react/shallow'-import { selectFaces, selectOthers, usePresence } from '../state/presence'import { useProjects } from '../state/projects'+import { useActiveSessionPresence } from '../session/session'import { faceClickTarget, facepileEntries, type FacepileFocus } from '../lib/facepile'/**@@ -28,14 +28,17 @@ export function Facepile({onJump: (nodeId: string) => voidonSwitchProject: (projectId: string) => void}): JSX.Element | null {+ // Read the ACTIVE session's presence (provider-independent — this stays mounted OUTSIDE the+ // Canvas SessionProvider, and prunes the face cache; see the mount comment in Canvas.tsx).+ const presence = useActiveSessionPresence()// useShallow: the selector derives a new array each call (its ELEMENTS are cached — that is what// makes cursor traffic invisible here). See PresenceLayer for the same pattern.- const faces = usePresence(useShallow(selectFaces))+ const faces = presence.store(useShallow(presence.selectFaces))// Where each peer is working. A record of strings, so useShallow can actually compare it.- const focus = usePresence(+ const focus = presence.store(useShallow((s): FacepileFocus => {const map: Record<number, string | null> = {}- for (const p of selectOthers(s)) map[p.clientId] = p.focus ?? null+ for (const p of presence.selectOthers(s)) map[p.clientId] = p.focus ?? nullreturn map}))@@ -73,7 +76,7 @@ export function Facepile({if (!e.actionable) return// Read focus live: the subscribed map above is what decided actionability, but by// click time the peer may well have moved to another node.- const live = usePresence.getState().peers[e.clientId]?.focus ?? null+ const live = presence.store.getState().peers[e.clientId]?.focus ?? nullconst target = faceClickTarget(e, live)if (target?.kind === 'node') onJump(target.nodeId)else if (target?.kind === 'project') onSwitchProject(target.projectId)diff --git a/src/renderer/components/PresenceChips.tsx b/src/renderer/components/PresenceChips.tsxindex f3834562f..f8ef22858 100644--- a/src/renderer/components/PresenceChips.tsx+++ b/src/renderer/components/PresenceChips.tsx@@ -1,7 +1,7 @@import type { CSSProperties } from 'react'import { useShallow } from 'zustand/react/shallow'-import { selectFocusedFaces, selectTypingFaces, usePresence } from '../state/presence'import { useProjects } from '../state/projects'+import { useActiveSessionPresence } from '../session/session'import { chipStrip } from '../lib/presenceChips'/**@@ -27,12 +27,13 @@ import { chipStrip } from '../lib/presenceChips'* touch the typing marks, so it returns the very same (usually empty and shared) array.*/export function PresenceChips({ nodeId }: { nodeId: string }): JSX.Element | null {+ const presence = useActiveSessionPresence()const activeProjectId = useProjects((s) => s.activeProjectId)// useShallow: the array is derived fresh each call — its ELEMENTS are the cached faces.- const faces = usePresence(- useShallow((s) => selectFocusedFaces(s, nodeId, activeProjectId || null))+ const faces = presence.store(+ useShallow((s) => presence.selectFocusedFaces(s, nodeId, activeProjectId || null)))- const typists = usePresence(useShallow((s) => selectTypingFaces(s, nodeId)))+ const typists = presence.store(useShallow((s) => presence.selectTypingFaces(s, nodeId)))if (faces.length === 0 && typists.length === 0) return nullconst { chips, overflow, overflowTitle } = chipStrip(faces, typists)diff --git a/src/renderer/components/PresenceLayer.tsx b/src/renderer/components/PresenceLayer.tsxindex bc00a4c94..b3090f239 100644--- a/src/renderer/components/PresenceLayer.tsx+++ b/src/renderer/components/PresenceLayer.tsx@@ -2,9 +2,8 @@ import { useCallback, useEffect, useRef, useState } from 'react'import { useShallow } from 'zustand/react/shallow'import { ViewportPortal, useReactFlow, useStore } from '@xyflow/react'import { CHAT_MAX_LEN } from '@shared/presence'-import { selectVisible, usePresence } from '../state/presence'import { useProjects } from '../state/projects'-import { useSession } from '../session/session'+import { useActiveSessionApi, useActiveSessionPresence } from '../session/session'import {CHAT_ANCHOR_OFFSET_PX,CURSOR_HOTSPOT_PX,@@ -35,16 +34,18 @@ const CHAT_LINGER_MS = 5000* Canvas.*/export function PresenceLayer(): JSX.Element | null {- // The session's core API — where cursor/chat casts go. A plain context read (no store- // subscription): the session object is stable for this component's lifetime, so the rAF- // callbacks and effect cleanups below may close over `api` directly.- const { api } = useSession()+ // The ACTIVE session's core API — where cursor/chat casts go — and its presence store, both+ // resolved provider-independently (reactive on the active project) so they always agree on the+ // session. Stable per active session, and both are listed in the effect/callback deps below, so+ // a tab switch that changes the active session rebinds the rAF sampler and effect cleanups.+ const api = useActiveSessionApi()+ const presence = useActiveSessionPresence()const activeProjectId = useProjects((s) => s.activeProjectId)// Hard project filter — not a style: an off-project peer is not rendered at all.// useShallow: the selector derives a NEW array each call, and zustand's default Object.is// equality would make React 18's useSyncExternalStore complain (and re-render on every store// write). Shallow-compare the array instead.- const others = usePresence(useShallow((s) => selectVisible(s, activeProjectId || null)))+ const others = presence.store(useShallow((s) => presence.selectVisible(s, activeProjectId || null)))const hasOthers = others.length > 0const { screenToFlowPosition } = useReactFlow()// Live viewport zoom, straight from React Flow's store: this subscribes THIS component, so adiff --git a/src/renderer/components/PresenceNamePrompt.tsx b/src/renderer/components/PresenceNamePrompt.tsxindex 6582c1631..6f9becbd0 100644--- a/src/renderer/components/PresenceNamePrompt.tsx+++ b/src/renderer/components/PresenceNamePrompt.tsx@@ -1,7 +1,7 @@import { useState } from 'react'import { NAME_MAX_LEN, PRESENCE_COLORS } from '@shared/presence'-import { selectOthers, suggestIdentity, usePresence } from '../state/presence'-import { setMeAll } from '../session/session'+import { suggestIdentity } from '../state/presence'+import { setMeAll, useActiveSessionPresence } from '../session/session'/*** First-connect identity prompt: pick a name + color. Saved to localStorage@@ -16,8 +16,12 @@ import { setMeAll } from '../session/session'* the count) cannot re-render this.*/export function PresenceNamePrompt(): JSX.Element | null {- const needsName = usePresence((s) => s.needsName)- const otherCount = usePresence((s) => selectOthers(s).length)+ // Read the ACTIVE session's presence (provider-independent — this prompt renders OUTSIDE the+ // Canvas SessionProvider), so a relay tab prompts on the relay session's peers. The WRITE below+ // is `setMeAll`, which re-helloes EVERY live session, so no per-session write is needed here.+ const presence = useActiveSessionPresence()+ const needsName = presence.store((s) => s.needsName)+ const otherCount = presence.store((s) => presence.selectOthers(s).length)// suggestIdentity is read ONCE (lazy initializer): a peer joining later must not swap the// suggested color out from under a user who is mid-typing.const [draft] = useState(suggestIdentity)diff --git a/src/renderer/session/session.test.ts b/src/renderer/session/session.test.tsindex 07314b353..260c3fefd 100644--- a/src/renderer/session/session.test.ts+++ b/src/renderer/session/session.test.ts@@ -15,6 +15,7 @@ import {setSessionStatus,takeSessionOffline,activeSessionPresence,+ presenceForProject,} from './session'import { defaultPresence } from '../state/presence'import type { NodeTerminalApi } from '@shared/types'@@ -275,6 +276,36 @@ describe('activeSessionPresence (Task 1 — the ACTIVE session presence, non-hoo})})+describe('presenceForProject (Task 2 — the provider-INDEPENDENT resolver the active-session presence hook is built on)', () => {+ it('resolves a project BOUND to a relay session to that relay session\'s presence', () => {+ // This is what makes Facepile / PresenceNamePrompt (rendered OUTSIDE the SessionProvider) and+ // the presence-reading components see the ACTIVE (relay) session without moving in the tree:+ // the hook passes the store's activeProjectId here, and a relay tab's project is bound to it.+ const local = createSession('local', fakeApi, 'This Mac')+ setActiveSession(local.id)+ const relay = createSession('relay', { marker: 'relay' } as unknown as NodeTerminalApi, "Ayşe's Mac")+ bindProjectToSession('remote-tab', relay.id)++ const p = presenceForProject('remote-tab')+ expect(p).toBe(getSessionStores(relay.id).presence)+ expect(p).not.toBe(getSessionStores(local.id).presence)+ })++ it('resolves an unbound (local) project to the LOCAL session\'s presence — byte-identical to today', () => {+ const local = createSession('local', fakeApi, 'This Mac')+ setActiveSession(local.id)+ createSession('relay', { marker: 'relay' } as unknown as NodeTerminalApi, "Ayşe's Mac")+ // A local project is never bound — it must resolve to the local session's presence (the exact+ // store the historical components read today), NOT the merely-active or relay one.+ expect(presenceForProject('some-local-tab')).toBe(getSessionStores(local.id).presence)+ })++ it('falls back to defaultPresence for an empty/unknown project id with no local session (node-env safe)', () => {+ expect(() => presenceForProject('')).not.toThrow()+ expect(presenceForProject('')).toBe(defaultPresence)+ })+})+describe('setMeAll (obligation 2 — a rename re-helloes EVERY live session)', () => {it('re-helloes and updates identity on all registered sessions, not just the active one', () => {const a = apiWithHelloSpy('a')diff --git a/src/renderer/session/session.ts b/src/renderer/session/session.tsindex fdce80050..4b3757531 100644--- a/src/renderer/session/session.ts+++ b/src/renderer/session/session.ts@@ -3,6 +3,7 @@ import type { NodeTerminalApi } from '@shared/types'import type { PeerIdentity } from '@shared/presence'import { createPresenceSession, defaultPresence, type PresenceSession } from '../state/presence'import { agentStatusForApi, type AgentStatusSession } from '../state/agentStatus'+import { useProjects } from '../state/projects'export type SessionSource = 'local' | 'relay' | 'server'@@ -231,12 +232,42 @@ function presenceForSession(sessionId: string | null): PresenceSession {return local ? local.stores.presence : defaultPresence}-/** The ACTIVE session's presence store, for components rendered UNDER the Canvas `SessionProvider`- * (so `useSession()` resolves the active session, not the app-chrome default). A local tab yields- * `defaultPresence`; a relay tab yields the relay session's presence. Allocation-free — returns the- * memoized `PresenceSession` directly — and never throws in render (see `presenceForSession`). */+/** The presence store for the session a project belongs to — the provider-INDEPENDENT resolution+ * the active-session presence hook is built on. Runs through `sessionForProject` (a relay tab →+ * its bound session, every local tab → the local session), so a local tab yields `defaultPresence`+ * (byte-identical to the historical `state/presence` default the components read today). Exported+ * for unit tests — the hook itself needs a React tree. Allocation-free; never throws in render. */+export function presenceForProject(projectId: string): PresenceSession {+ // Mirror `sessionForProject`'s resolution (bound → its session; stale binding pruned; unbound →+ // LOCAL, never the merely-active), but resolve to the presence store and NEVER throw in render:+ // an empty/local-less registry (a node-env test) falls back to `defaultPresence`.+ const boundId = PROJECT_BINDINGS.get(projectId)+ if (boundId) {+ const e = SESSIONS.get(boundId)+ if (e) return e.stores.presence+ PROJECT_BINDINGS.delete(projectId) // stale binding (session disposed) → resolve local+ }+ return presenceForSession(null) // unbound → the local session's presence (defaultPresence in-app)+}++/** The ACTIVE session's presence store. Resolves the active session REACTIVELY from the projects+ * store — NOT from the `SessionProvider` context — so it yields the identical session Canvas's+ * provider is keyed on (`sessionForProject(activeProjectId)`) whether the caller renders inside+ * that provider (`PresenceLayer`, `PresenceChips`) or outside it (`Facepile`, `PresenceNamePrompt`),+ * and re-renders on a tab switch (activeProjectId changes). A local tab yields `defaultPresence`;+ * a relay tab yields the relay session's presence. */export function useActiveSessionPresence(): PresenceSession {- return presenceForSession(useSession().id)+ const activeProjectId = useProjects((s) => s.activeProjectId)+ return presenceForProject(activeProjectId ?? '')+}++/** The ACTIVE session's core API — where the cursor/chat casts go — resolved provider-independently+ * from the projects store, matching `useActiveSessionPresence` session-for-session (both go through+ * `sessionForProject(activeProjectId)`, and presence is keyed by that session's api identity). A+ * local tab yields `window.nodeTerminal`; a relay tab yields the relay session's api. */+export function useActiveSessionApi(): NodeTerminalApi {+ const activeProjectId = useProjects((s) => s.activeProjectId)+ return sessionForProject(activeProjectId ?? '').api}/** Non-hook counterpart of `useActiveSessionPresence` for imperative (non-render) Canvas use: the