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): per-node presence chips + focus reporting
enes775cb2fd5abd
diff --git a/src/renderer/components/PresenceChips.tsx b/src/renderer/components/PresenceChips.tsxnew file mode 100644index 000000000..aa7546384--- /dev/null+++ b/src/renderer/components/PresenceChips.tsx@@ -0,0 +1,52 @@+import { useShallow } from 'zustand/react/shallow'+import { selectFocusedFaces, usePresence } from '../state/presence'+import { useProjects } from '../state/projects'+import { chipStrip } from '../lib/presenceChips'++/**+ * Avatar chips for the peers focused on ONE node OF THIS PROJECT, drawn in its header beside the+ * agent badge: "who else is in this terminal". Everyone beyond the cap collapses into a "+N" bubble+ * (see lib/presenceChips.ts); the facepile is where you go to see the whole room.+ *+ * PROJECT SCOPE: node ids are globally unique, so a peer focused on a node in ANOTHER project would+ * otherwise chip the same-id node here. selectFocusedFaces takes the active project id and filters+ * on it (via selectVisible) — the same single filter the cursors go through. No hand-filtering.+ *+ * PERF: THIS component subscribes to the presence store, not TerminalNode — and it subscribes to+ * FACES, not PeerStates. A cursor patch rebuilds a peer's PeerState object ~20×/s, so a PeerState+ * selector would re-render every terminal node on the canvas at cursor rate; faces are the same+ * objects until a name/color/project/kind actually changes, so `useShallow` bails out and a moving+ * cursor re-renders nothing here. (`PeerState.typing` is Stage 2's; Stage 1 leaves it null and+ * draws no typing indicator.)+ */+export function PresenceChips({ nodeId }: { nodeId: string }): JSX.Element | null {+ 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))+ )+ if (faces.length === 0) return null++ const { chips, overflow, overflowTitle } = chipStrip(faces)+ return (+ <span className="presence-chips">+ {chips.map((c) => (+ <span+ key={c.clientId}+ className="presence-chip"+ style={{ background: c.color }}+ title={c.title}+ >+ {c.letter}+ </span>+ ))}+ {overflow > 0 && (+ <span className="presence-chip presence-chip--more" title={overflowTitle}>+ +{overflow}+ </span>+ )}+ </span>+ )+}++export default PresenceChipsdiff --git a/src/renderer/lib/presenceChips.test.ts b/src/renderer/lib/presenceChips.test.tsnew file mode 100644index 000000000..e1da1ddf3--- /dev/null+++ b/src/renderer/lib/presenceChips.test.ts@@ -0,0 +1,68 @@+import { describe, it, expect } from 'vitest'+import { chipStrip, MAX_CHIPS } from './presenceChips'+import type { PeerFace } from '../state/presence'++function face(clientId: number, over: Partial<PeerFace> = {}): PeerFace {+ return {+ clientId,+ name: `P${clientId}`,+ color: '#5ac8fa',+ projectId: 'web',+ kind: 'browser',+ ...over+ }+}++describe('chipStrip (what a node header draws for the peers focused on it)', () => {+ it('draws nothing when nobody is focused here', () => {+ expect(chipStrip([])).toEqual({ chips: [], overflow: 0, overflowTitle: '' })+ })++ it('draws one chip per peer (initial + color + name tooltip) when they all fit', () => {+ const strip = chipStrip([face(8, { name: 'ada', color: '#ff9f0a' }), face(9, { name: 'Bo' })])+ expect(strip.overflow).toBe(0)+ expect(strip.chips).toEqual([+ { clientId: 8, letter: 'A', color: '#ff9f0a', title: 'ada is here' },+ { clientId: 9, letter: 'B', color: '#5ac8fa', title: 'Bo is here' }+ ])+ })++ it('orders by clientId (join order), whatever order the peer table hands them over in', () => {+ const strip = chipStrip([face(11), face(2), face(7)])+ expect(strip.chips.map((c) => c.clientId)).toEqual([2, 7, 11])+ })++ it('falls back to "?" for a peer with a blank name', () => {+ expect(chipStrip([face(8, { name: ' ' })]).chips[0].letter).toBe('?')+ })++ it('fills the strip exactly when the peers equal the cap (no "+0" bubble)', () => {+ const strip = chipStrip([face(1), face(2), face(3)], 3)+ expect(strip.chips).toHaveLength(3)+ expect(strip.overflow).toBe(0)+ })++ it('overflows into a "+N" bubble that names everyone it hides', () => {+ const strip = chipStrip(+ [+ face(1, { name: 'Ada' }),+ face(2, { name: 'Bo' }),+ face(3, { name: 'Cy' }),+ face(4, { name: 'Dee' }),+ face(5, { name: 'Eve' })+ ],+ 3+ )+ // A cap of 3 spends the last slot on the bubble: 2 faces + "+3".+ expect(strip.chips.map((c) => c.letter)).toEqual(['A', 'B'])+ expect(strip.overflow).toBe(3)+ expect(strip.overflowTitle).toBe('Cy, Dee, Eve')+ })++ it('has a sane default cap', () => {+ expect(MAX_CHIPS).toBeGreaterThanOrEqual(2)+ const strip = chipStrip(Array.from({ length: MAX_CHIPS + 4 }, (_, i) => face(i + 1)))+ expect(strip.chips).toHaveLength(MAX_CHIPS - 1)+ expect(strip.overflow).toBe(5)+ })+})diff --git a/src/renderer/lib/presenceChips.ts b/src/renderer/lib/presenceChips.tsnew file mode 100644index 000000000..4df0d25ae--- /dev/null+++ b/src/renderer/lib/presenceChips.ts@@ -0,0 +1,60 @@+// Pure logic behind the per-node presence chips (components/PresenceChips.tsx): which of the peers+// focused on a node get an avatar in its header, in what order, and when they collapse into a "+N"+// bubble. Kept out of the component because vitest runs in the node environment (no jsdom), so a+// React component cannot be unit-tested — this can.+//+// The chips answer "who else is in THIS terminal". The project filter that makes that question+// meaningful (node ids are globally unique) lives in selectFocusedFaces — by the time faces reach+// here they are already the peers on our canvas, focused on our node.++import type { PeerFace } from '../state/presence'++/** How many avatars a node header shows before collapsing the rest into "+N". A terminal header is+ * a crowded strip (account chip, SSH chip, context meter, RUNNING badge…), so the budget is small;+ * the facepile is where you go to see everyone. */+export const MAX_CHIPS = 3++export interface PresenceChip {+ clientId: number+ /** The single letter drawn in the circle (upper-cased first letter of the name). */+ letter: string+ color: string+ title: string+}++export interface PresenceChipStrip {+ chips: PresenceChip[]+ /** How many focused peers are hidden behind the "+N" bubble; 0 = no bubble. */+ overflow: number+ /** The hidden peers' names, for the bubble's tooltip. '' when there is no bubble. */+ overflowTitle: string+}++function letterOf(name: string): string {+ return name.trim().charAt(0).toUpperCase() || '?'+}++/**+ * Project the peers focused on one node into its header strip. Ordered by clientId — i.e. by join+ * order — so a chip never jumps around as the peer table is rebuilt (it is a plain object, and we+ * do not want to depend on its key order).+ *+ * Overflow spends the LAST slot on the bubble: with a cap of 3 and five peers you get two faces and+ * "+3" — never three faces and a fourth item, which would blow the header's width budget.+ */+export function chipStrip(faces: readonly PeerFace[], max: number = MAX_CHIPS): PresenceChipStrip {+ const ordered = [...faces].sort((a, b) => a.clientId - b.clientId)+ const fits = ordered.length <= max+ const shown = fits ? ordered : ordered.slice(0, Math.max(max - 1, 0))+ const hidden = fits ? [] : ordered.slice(shown.length)+ return {+ chips: shown.map((f) => ({+ clientId: f.clientId,+ letter: letterOf(f.name),+ color: f.color,+ title: `${f.name} is here`+ })),+ overflow: hidden.length,+ overflowTitle: hidden.map((f) => f.name).join(', ')+ }+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex da1592060..0582ca52d 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -27,6 +27,8 @@ import { ContextMeter } from '../components/ContextMeter'import { isZoomModifierHeld } from '../lib/zoomModifier'import { useSettings } from '../state/settings'import { useAgentStatus, inferInterruptAfterSettle } from '../state/agentStatus'+import { reportFocus, releaseFocus } from '../state/presence'+import { PresenceChips } from '../components/PresenceChips'import { useAgentNodes } from '../state/agentNodes'import { useProjects } from '../state/projects'import { useSshConn } from '../state/sshConn'@@ -586,6 +588,10 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNif (resizeTimer) clearTimeout(resizeTimer)if (dwellRef.current) clearTimeout(dwellRef.current)useAgentStatus.getState().setActive(id, false)+ // Teammates stop seeing us in this node's header. releaseFocus, not reportFocus(null): on a+ // project switch every node unmounts, and an unconditional clear could undo the focus the+ // node we just moved into already published.+ releaseFocus(id)// Unmount happens on a project switch (a detach — the tmux session keeps running) as// well as on real deletion, and we can't tell them apart here. Don't wipe the node's// persisted status (that would drop the sessionId the context meter looks up on remount,@@ -680,6 +686,10 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNtermRef.current?.focus()useAgentStatus.getState().setActive(id, true)useAgentStatus.getState().clearUnread(id)+ // "I am working in this node" — the same signal the agent-status active flag uses, i.e. the+ // dwell has elapsed and the terminal actually took the keyboard (a mouse merely passing over+ // never gets here). Deduped in the store, so re-entering the same node costs nothing.+ reportFocus(id)}dwellRef.current = setTimeout(enter, panHoverDelay)}@@ -688,6 +698,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNsetArmed(true)termRef.current?.blur()useAgentStatus.getState().setActive(id, false)+ releaseFocus(id)}// While armed, a mousedown might start a node drag — pause the dwell timer so the// terminal doesn't grab focus mid-drag; restart it on release.@@ -740,6 +751,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNterm.focus()term.paste(paths.join(' ') + ' ')useAgentStatus.getState().setActive(id, true)+ reportFocus(id)}// A rename-capable agent's session name follows the node title: push `/rename <name>` into@@ -1010,6 +1022,8 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN</span>) : null}{showUsage && <ContextMeter sessionId={status?.sessionId ?? null} />}+ {/* Who else is in this node. Subscribes to presence itself — see PresenceChips. */}+ <PresenceChips nodeId={id} />{status?.state === 'working' && (<span className="term-node__status term-node__status--busy" title={`${agentLabel} is working`}><span className="term-node__status-dot" />diff --git a/src/renderer/state/presence.test.ts b/src/renderer/state/presence.test.tsindex 0dc497e64..b7684a308 100644--- a/src/renderer/state/presence.test.ts+++ b/src/renderer/state/presence.test.ts@@ -389,4 +389,63 @@ describe('reportFocus / reportProject', () => {['project', null]])})++ it('releaseFocus only clears the focus THIS node published (a leaving node cannot steal the next one)', async () => {+ vi.stubGlobal('localStorage', memStorage(STORED_ME))+ const api = fakePresenceApi()+ const { reportFocus, releaseFocus } = await import('./presence')++ reportFocus('node-a')+ // node-b took over (its dwell fired before node-a's unmount cleanup ran) — node-a going away+ // must NOT report "nobody is focused", which would blank the chips on node-b.+ reportFocus('node-b')+ releaseFocus('node-a')+ expect(api.calls.filter((c) => c[0] === 'focus')).toEqual([+ ['focus', 'node-a'],+ ['focus', 'node-b']+ ])++ // The node we ARE focused on leaving does clear it.+ releaseFocus('node-b')+ expect(api.calls.filter((c) => c[0] === 'focus')).toEqual([+ ['focus', 'node-a'],+ ['focus', 'node-b'],+ ['focus', null]+ ])+ })+})++describe('selectFocusedFaces (the node-header chips — one per node, so cursor traffic must not re-render them)', () => {+ it('projects the focused peers of THIS project and keeps object identity across cursor updates', async () => {+ vi.stubGlobal('localStorage', memStorage(STORED_ME))+ const api = fakePresenceApi({ clientId: 7, peers: [peer(7, { projectId: 'web' })] })+ const { connectPresence, usePresence, selectFocusedFaces } = await import('./presence')+ const stop = connectPresence()+ await vi.waitFor(() => expect(usePresence.getState().myId).toBe(7))++ api.emitPeer({ op: 'join', peer: peer(8, { name: 'Ada', projectId: 'web', focus: 'node-a' }) })+ // Same node id, ANOTHER project: node ids are globally unique, so without the project filter+ // this peer would chip node-a's header on my canvas.+ api.emitPeer({ op: 'join', peer: peer(9, { name: 'Bo', projectId: 'api', focus: 'node-a' }) })++ const before = selectFocusedFaces(usePresence.getState(), 'node-a', 'web')+ expect(before.map((f) => f.name)).toEqual(['Ada'])+ expect(selectFocusedFaces(usePresence.getState(), 'node-b', 'web')).toEqual([])++ // A cursor patch replaces the whole PeerState object (~20/s). The projected face must stay the+ // SAME object, so useShallow bails out and the chips do not re-render at cursor rate.+ api.emitPeer({ op: 'update', clientId: 8, patch: { cursor: { x: 1, y: 2 } } })+ const after = selectFocusedFaces(usePresence.getState(), 'node-a', 'web')+ expect(after[0]).toBe(before[0])++ // Something the chip actually shows changes → a new object (the chip updates).+ api.emitPeer({ op: 'update', clientId: 8, patch: { name: 'Ada L.' } })+ expect(selectFocusedFaces(usePresence.getState(), 'node-a', 'web')[0]).not.toBe(before[0])++ // Focus moves → the chip moves with it.+ api.emitPeer({ op: 'update', clientId: 8, patch: { focus: 'node-b' } })+ expect(selectFocusedFaces(usePresence.getState(), 'node-a', 'web')).toEqual([])+ expect(selectFocusedFaces(usePresence.getState(), 'node-b', 'web').map((f) => f.clientId)).toEqual([8])+ stop()+ })})diff --git a/src/renderer/state/presence.ts b/src/renderer/state/presence.tsindex 9a7303ee8..4c11b5e5d 100644--- a/src/renderer/state/presence.ts+++ b/src/renderer/state/presence.ts@@ -154,31 +154,58 @@ export interface PeerFace {/** 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 faces: PeerFace[] = []- const fresh = new Map<ClientId, PeerFace>()- for (const p of selectOthers(s)) {- const prev = faceCache.get(p.clientId)- const same =- prev &&- prev.name === p.name &&- prev.color === p.color &&- prev.projectId === p.projectId &&- prev.kind === p.kind- const face: PeerFace = same- ? prev- : { clientId: p.clientId, name: p.name, color: p.color, projectId: p.projectId, kind: p.kind }- fresh.set(p.clientId, face)- faces.push(face)- }- // Rebuild rather than accumulate: a peer that left must not linger in the cache.- faceCache.clear()- for (const [id, face] of fresh) faceCache.set(id, face)+ 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}+/** 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. */+export function selectFocusedFaces(+ s: PresenceStore,+ nodeId: string,+ projectId: string | null+): PeerFace[] {+ return selectFocused(s, nodeId, projectId).map(faceFor)+}+/** 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@@ -277,6 +304,16 @@ export function reportFocus(nodeId: string | null): void {window.nodeTerminal.presence.focus(nodeId)}+/** "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)+}+/** 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 {diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex edf65e72f..a1581190e 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -5299,6 +5299,40 @@ body,line-height: 1;}+/* ---- per-node chips: who else is in THIS terminal (components/PresenceChips.tsx) ---- */+.presence-chips {+ display: inline-flex;+ align-items: center;+ gap: 3px;+ margin-left: 6px;+ flex-shrink: 0;+}++.presence-chip {+ width: 16px;+ height: 16px;+ border-radius: 50%;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ font-size: 9px;+ font-weight: 700;+ line-height: 1;+ color: #000;+ border: 1px solid rgba(0, 0, 0, 0.45);+}++/* The "+N" bubble: neutral, so it never reads as one more person's color. */+.presence-chip--more {+ width: auto;+ min-width: 16px;+ padding: 0 4px;+ border-radius: 8px;+ background: rgba(255, 255, 255, 0.16);+ color: var(--label);+ border-color: rgba(255, 255, 255, 0.18);+}+/* ---- first-connect name/color prompt ---- */.presence-prompt {position: absolute;