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.

feat(presence): pulse a peer's chip while their keystrokes land in this terminal

enesf29093c864d4
diff --git a/docs/team-presence.md b/docs/team-presence.md
index 502b000ac..5de3176b1 100644
--- a/docs/team-presence.md
+++ b/docs/team-presence.md
@@ -286,11 +286,15 @@ deviations, recorded here so this document does not lie to the next reader:
table forever — a permanent ghost cursor. The Server Edition now runs a 30 s ping/pong heartbeat
and reaps sockets that miss a pong, so a vanished client leaves within ~60 s. A cleanly closed
tab still leaves immediately, on `close`.
-3. **`PeerState.typing` exists but is always `null` in Stage 1.** The field, the `noteTyping()`
- throttle on the hub (`src/core/presence/hub.ts`) and the renderer's badge decay are all in
- place, but **nothing calls `noteTyping()`** — attribution needs the sender-aware `pty:write`
- handler, which is Stage 2 work (see [Typing attribution](#typing-attribution--and-why-it-is-server-side)).
- Until then no peer ever reports typing, and the UI simply never shows the badge.
+3. ~~**`PeerState.typing` exists but is always `null` in Stage 1.**~~ **Closed in Stage 2.** The
+ sender-aware `pty:write` handler calls `noteTyping()`, and the renderer draws the pulsing ring on
+ the typist's header chip (`src/renderer/lib/typingPeers.ts` + `components/PresenceChips.tsx`).
+ Two rules worth knowing before you touch it: the ring decays against the **local receipt time**,
+ not the host's `typing.at` (a viewer's clock can be minutes off), and it is fed **only** by live
+ `presence:peer` diffs — never by a `presence:sync` snapshot, which can carry a ten-minute-old
+ stamp because the hub never clears `typing`. It is also the one node-scoped signal that is
+ **not** project-filtered: a phone has `projectId: null`, and typing from the phone is exactly
+ what the ring exists to surface (node ids are globally unique, so this is safe).
## Non-goals (v1)
diff --git a/src/renderer/components/PresenceChips.tsx b/src/renderer/components/PresenceChips.tsx
index aa7546384..f3834562f 100644
--- a/src/renderer/components/PresenceChips.tsx
+++ b/src/renderer/components/PresenceChips.tsx
@@ -1,5 +1,6 @@
+import type { CSSProperties } from 'react'
import { useShallow } from 'zustand/react/shallow'
-import { selectFocusedFaces, usePresence } from '../state/presence'
+import { selectFocusedFaces, selectTypingFaces, usePresence } from '../state/presence'
import { useProjects } from '../state/projects'
import { chipStrip } from '../lib/presenceChips'
@@ -12,12 +13,18 @@ import { chipStrip } from '../lib/presenceChips'
* 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.
*
+ * TYPING (co-attach): a chip PULSES while that peer's keystrokes are landing in THIS terminal. One
+ * PTY, N subscribers and no locking, so two people typing into one shell interleave their characters
+ * — the ring is the warning. It is fed by a SECOND selector, deliberately NOT project-filtered (a
+ * phone has no canvas, so the focus list excludes it, yet it can be typing right here) — see
+ * selectTypingFaces — and a typist who is not focused here is chipped anyway (lib/presenceChips.ts).
+ *
* 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.)
+ * cursor re-renders nothing here. The typing selector keeps that property: a cursor patch does not
+ * 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 activeProjectId = useProjects((s) => s.activeProjectId)
@@ -25,16 +32,19 @@ export function PresenceChips({ nodeId }: { nodeId: string }): JSX.Element | nul
const faces = usePresence(
useShallow((s) => selectFocusedFaces(s, nodeId, activeProjectId || null))
)
- if (faces.length === 0) return null
+ const typists = usePresence(useShallow((s) => selectTypingFaces(s, nodeId)))
+ if (faces.length === 0 && typists.length === 0) return null
- const { chips, overflow, overflowTitle } = chipStrip(faces)
+ const { chips, overflow, overflowTitle } = chipStrip(faces, typists)
return (
<span className="presence-chips">
{chips.map((c) => (
<span
key={c.clientId}
- className="presence-chip"
- style={{ background: c.color }}
+ className={`presence-chip${c.typing ? ' presence-chip--typing' : ''}`}
+ // `--peer-color` feeds the pulsing ring's keyframes (styles.css): the ring has to be in
+ // the peer's own color, and a CSS animation cannot read an inline box-shadow.
+ style={{ background: c.color, '--peer-color': c.color } as CSSProperties}
title={c.title}
>
{c.letter}
diff --git a/src/renderer/lib/presenceChips.test.ts b/src/renderer/lib/presenceChips.test.ts
index e1da1ddf3..80c4080e2 100644
--- a/src/renderer/lib/presenceChips.test.ts
+++ b/src/renderer/lib/presenceChips.test.ts
@@ -22,8 +22,8 @@ describe('chipStrip (what a node header draws for the peers focused on it)', ()
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' }
+ { clientId: 8, letter: 'A', color: '#ff9f0a', title: 'ada is here', typing: false },
+ { clientId: 9, letter: 'B', color: '#5ac8fa', title: 'Bo is here', typing: false }
])
})
@@ -37,7 +37,7 @@ describe('chipStrip (what a node header draws for the peers focused on it)', ()
})
it('fills the strip exactly when the peers equal the cap (no "+0" bubble)', () => {
- const strip = chipStrip([face(1), face(2), face(3)], 3)
+ const strip = chipStrip([face(1), face(2), face(3)], [], 3)
expect(strip.chips).toHaveLength(3)
expect(strip.overflow).toBe(0)
})
@@ -51,6 +51,7 @@ describe('chipStrip (what a node header draws for the peers focused on it)', ()
face(4, { name: 'Dee' }),
face(5, { name: 'Eve' })
],
+ [],
3
)
// A cap of 3 spends the last slot on the bubble: 2 faces + "+3".
@@ -66,3 +67,40 @@ describe('chipStrip (what a node header draws for the peers focused on it)', ()
expect(strip.overflow).toBe(5)
})
})
+
+describe('chipStrip typists (co-attach: whose keystrokes are landing in THIS shell)', () => {
+ it('rings the chip of a focused peer who is typing here', () => {
+ const strip = chipStrip([face(1, { name: 'Ada' }), face(2, { name: 'Bo' })], [face(2)])
+ expect(strip.chips.map((c) => [c.clientId, c.typing])).toEqual([
+ [2, true],
+ [1, false]
+ ])
+ expect(strip.chips[0].title).toBe('P2 is typing in this terminal')
+ })
+
+ it('chips a typist who is NOT in the focused list — a phone has no project, and so no focus', () => {
+ // The phone (clientId 5) is filtered out of the project-scoped focus list, but its keystrokes
+ // are landing in this shell right now: it MUST be drawn, or the ring never fires for a phone.
+ const strip = chipStrip([face(1)], [face(5, { name: 'Phone', projectId: null, kind: 'phone' })])
+ expect(strip.chips.map((c) => c.clientId)).toEqual([5, 1])
+ expect(strip.chips[0].typing).toBe(true)
+ })
+
+ it('never chips the same peer twice when they are both focused here and typing here', () => {
+ const strip = chipStrip([face(3)], [face(3)])
+ expect(strip.chips).toHaveLength(1)
+ expect(strip.chips[0].typing).toBe(true)
+ })
+
+ it('never hides a typist behind the "+N" bubble — a warning you cannot see warns nobody', () => {
+ const strip = chipStrip([face(1), face(2), face(3), face(4)], [face(4)], 3)
+ expect(strip.chips.map((c) => c.clientId)).toEqual([4, 1])
+ expect(strip.overflow).toBe(2)
+ expect(strip.overflowTitle).toBe('P2, P3')
+ })
+
+ it('keeps a stable clientId order within each group, so typing never reshuffles the strip', () => {
+ const strip = chipStrip([face(9), face(4)], [face(8), face(2)], 9)
+ expect(strip.chips.map((c) => c.clientId)).toEqual([2, 8, 4, 9])
+ })
+})
diff --git a/src/renderer/lib/presenceChips.ts b/src/renderer/lib/presenceChips.ts
index 4df0d25ae..f99c8767a 100644
--- a/src/renderer/lib/presenceChips.ts
+++ b/src/renderer/lib/presenceChips.ts
@@ -20,6 +20,10 @@ export interface PresenceChip {
letter: string
color: string
title: string
+ /** This peer's keystrokes are landing in THIS shell right now → the chip pulses (styles.css).
+ * One PTY, N subscribers and no locking: two people typing into one shell interleave their
+ * characters, so the ring is the warning that it is happening. */
+ typing: boolean
}
export interface PresenceChipStrip {
@@ -34,16 +38,36 @@ function letterOf(name: string): string {
return name.trim().charAt(0).toUpperCase() || '?'
}
+function byClientId(a: PeerFace, b: PeerFace): number {
+ return a.clientId - b.clientId
+}
+
/**
- * 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).
+ * Project the peers at one node into its header strip: `faces` are the peers FOCUSED here (who is in
+ * this terminal), `typists` the peers whose keystrokes are landing in it right now (state/presence
+ * selectTypingFaces). The two overlap in the normal case — you focus the node you type into — and
+ * are merged by clientId, so a peer is never chipped twice.
+ *
+ * A TYPIST WHO IS NOT IN `faces` STILL GETS A CHIP. That is not an edge case: a phone has no canvas
+ * (`projectId: null`, so the project-filtered focus list excludes it) but can very much be typing
+ * into this shell — which is precisely what you need to know before you touch the keyboard.
+ *
+ * Typists come FIRST, so the ring can never be the thing that falls behind the "+N" bubble: a chip
+ * you cannot see warns nobody. Within each group the order is clientId — i.e. join order — so a chip
+ * does not jump around as the peer table is rebuilt (it is a plain object; we do not depend on its
+ * key order), and typing itself never reshuffles the strip.
*
* 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)
+export function chipStrip(
+ faces: readonly PeerFace[],
+ typists: readonly PeerFace[] = [],
+ max: number = MAX_CHIPS
+): PresenceChipStrip {
+ const typingIds = new Set(typists.map((f) => f.clientId))
+ const rest = faces.filter((f) => !typingIds.has(f.clientId)).sort(byClientId)
+ const ordered = [...[...typists].sort(byClientId), ...rest]
const fits = ordered.length <= max
const shown = fits ? ordered : ordered.slice(0, Math.max(max - 1, 0))
const hidden = fits ? [] : ordered.slice(shown.length)
@@ -52,7 +76,10 @@ export function chipStrip(faces: readonly PeerFace[], max: number = MAX_CHIPS):
clientId: f.clientId,
letter: letterOf(f.name),
color: f.color,
- title: `${f.name} is here`
+ title: typingIds.has(f.clientId)
+ ? `${f.name} is typing in this terminal`
+ : `${f.name} is here`,
+ typing: typingIds.has(f.clientId)
})),
overflow: hidden.length,
overflowTitle: hidden.map((f) => f.name).join(', ')
diff --git a/src/renderer/lib/typingPeers.test.ts b/src/renderer/lib/typingPeers.test.ts
new file mode 100644
index 000000000..916f20928
--- /dev/null
+++ b/src/renderer/lib/typingPeers.test.ts
@@ -0,0 +1,115 @@
+import { describe, it, expect } from 'vitest'
+import {
+ TYPING_DECAY_MS,
+ dropTyping,
+ markTyping,
+ nextTypingSweepDelay,
+ pruneTyping,
+ typingClientIds,
+ type TypingMarks
+} from './typingPeers'
+
+const NOW = 10_000
+
+describe('markTyping (a typing patch is stamped on OUR clock, never the sender\'s)', () => {
+ it('records the node the peer is typing into, stamped with the local receipt time', () => {
+ // `at` is the local `now` we pass, NOT the host stamp that rode the wire.
+ const marks = markTyping({}, 7, 'n1', NOW)
+ expect(marks).toEqual({ 7: { nodeId: 'n1', at: NOW } })
+ })
+
+ it('replaces a peer\'s previous mark (one node at a time; the newest write wins)', () => {
+ const marks = markTyping(markTyping({}, 7, 'n1', NOW - 900), 7, 'n2', NOW)
+ expect(marks).toEqual({ 7: { nodeId: 'n2', at: NOW } })
+ })
+
+ it('does not mutate the map it is given (zustand state must stay immutable)', () => {
+ const before: TypingMarks = { 7: { nodeId: 'n1', at: NOW - 10 } }
+ const after = markTyping(before, 8, 'n1', NOW)
+ expect(before).toEqual({ 7: { nodeId: 'n1', at: NOW - 10 } })
+ expect(Object.keys(after)).toEqual(['7', '8'])
+ })
+})
+
+describe('typingClientIds (who is typing into THIS node, right now)', () => {
+ it('returns the peers typing into this node — never those typing elsewhere', () => {
+ const marks: TypingMarks = {
+ 1: { nodeId: 'n1', at: NOW - 100 },
+ 2: { nodeId: 'n2', at: NOW - 100 }, // typing into another terminal
+ 3: { nodeId: 'n1', at: NOW - 50 }
+ }
+ expect(typingClientIds(marks, 'n1', NOW)).toEqual([1, 3])
+ })
+
+ it('decays a stale stamp (the ring is a live signal, not a history)', () => {
+ const marks: TypingMarks = { 1: { nodeId: 'n1', at: NOW - TYPING_DECAY_MS - 1 } }
+ expect(typingClientIds(marks, 'n1', NOW)).toEqual([])
+ })
+
+ it('keeps a stamp that is exactly at the decay edge', () => {
+ const marks: TypingMarks = { 1: { nodeId: 'n1', at: NOW - TYPING_DECAY_MS } }
+ expect(typingClientIds(marks, 'n1', NOW)).toEqual([1])
+ })
+
+ it('tolerates a mark stamped slightly in the future (a clock that stepped back mid-session)', () => {
+ const marks: TypingMarks = { 1: { nodeId: 'n1', at: NOW + 5 } }
+ expect(typingClientIds(marks, 'n1', NOW)).toEqual([1])
+ })
+
+ it('orders by clientId (join order), so a chip never jumps as peers keep typing', () => {
+ const marks: TypingMarks = {
+ 9: { nodeId: 'n1', at: NOW - 10 },
+ 2: { nodeId: 'n1', at: NOW - 1_900 }
+ }
+ expect(typingClientIds(marks, 'n1', NOW)).toEqual([2, 9])
+ })
+
+ it('allocates nothing when nobody is typing (this runs per node on every store write)', () => {
+ // Identity, not just emptiness: the same frozen array every time, so useShallow bails out.
+ expect(typingClientIds({}, 'n1', NOW)).toBe(typingClientIds({}, 'n2', NOW))
+ })
+})
+
+describe('pruneTyping / nextTypingSweepDelay (the local decay timer)', () => {
+ it('drops the marks that have decayed and keeps the live ones', () => {
+ const marks: TypingMarks = {
+ 1: { nodeId: 'n1', at: NOW - TYPING_DECAY_MS - 1 },
+ 2: { nodeId: 'n1', at: NOW - 10 }
+ }
+ expect(pruneTyping(marks, NOW)).toEqual({ 2: { nodeId: 'n1', at: NOW - 10 } })
+ })
+
+ it('returns the SAME map when nothing decayed (no state write, no re-render)', () => {
+ const marks: TypingMarks = { 2: { nodeId: 'n1', at: NOW - 10 } }
+ expect(pruneTyping(marks, NOW)).toBe(marks)
+ })
+
+ it('sweeps at the earliest expiry, so the ring fades ~TYPING_DECAY_MS after the last keystroke', () => {
+ const marks: TypingMarks = {
+ 1: { nodeId: 'n1', at: NOW - 1_500 },
+ 2: { nodeId: 'n2', at: NOW - 500 }
+ }
+ expect(nextTypingSweepDelay(marks, NOW)).toBe(TYPING_DECAY_MS - 1_500)
+ })
+
+ it('asks for no timer at all when nobody is typing — a solo user pays nothing', () => {
+ expect(nextTypingSweepDelay({}, NOW)).toBeNull()
+ })
+
+ it('never asks for a negative delay (an already-expired mark sweeps immediately)', () => {
+ const marks: TypingMarks = { 1: { nodeId: 'n1', at: NOW - TYPING_DECAY_MS - 5_000 } }
+ expect(nextTypingSweepDelay(marks, NOW)).toBe(0)
+ })
+})
+
+describe('dropTyping (a peer left)', () => {
+ it('removes the peer\'s mark', () => {
+ const marks: TypingMarks = { 1: { nodeId: 'n1', at: NOW }, 2: { nodeId: 'n1', at: NOW } }
+ expect(dropTyping(marks, 1)).toEqual({ 2: { nodeId: 'n1', at: NOW } })
+ })
+
+ it('returns the SAME map for a peer that was not typing (no needless state write)', () => {
+ const marks: TypingMarks = { 1: { nodeId: 'n1', at: NOW } }
+ expect(dropTyping(marks, 99)).toBe(marks)
+ })
+})
diff --git a/src/renderer/lib/typingPeers.ts b/src/renderer/lib/typingPeers.ts
new file mode 100644
index 000000000..756ec5222
--- /dev/null
+++ b/src/renderer/lib/typingPeers.ts
@@ -0,0 +1,123 @@
+// Co-attach: who is typing into a node's terminal RIGHT NOW (the pulsing ring in its header).
+//
+// One PTY, N subscribers: two people can type into the same shell and their characters interleave.
+// There is no locking in v1 — the ring IS the warning, so this deliberately answers with a LIST.
+//
+// Pure, and kept out of the store/component because vitest runs in the node environment (no jsdom):
+// a React component cannot be unit-tested, this can. The store (state/presence.ts) owns the marks
+// and the sweep timer; the component (components/PresenceChips.tsx) draws them.
+//
+// TWO RULES THAT ARE EASY TO GET WRONG, AND ARE THE REASON THIS MODULE EXISTS:
+//
+// 1. THE STAMP IS OURS, NOT THE SENDER'S. `PeerState.typing.at` (src/shared/presence.ts) is stamped
+// on the HOST's clock, and the decay would run on the VIEWER's — a browser or a phone whose
+// clock may be minutes off. Decaying against the wire stamp would pin a ring on forever (host
+// clock ahead) or never light one (behind). So the store re-stamps every typing patch with the
+// LOCAL time it observed it, and `TypingMark.at` below is that local receipt time. One clock,
+// end to end.
+//
+// 2. ONLY A LIVE PATCH MAY LIGHT A RING. The hub keeps no timers and never clears `typing`, so a
+// client joining later gets a `presence:sync` / hello snapshot carrying a peer's OLD typing with
+// an old stamp. The store therefore builds these marks ONLY from `presence:peer` update diffs —
+// it never seeds them from a snapshot — so a keystroke from ten minutes ago cannot ring here.
+
+import { TYPING_DECAY_MS, type ClientId } from '@shared/presence'
+
+/** How long a typing mark stays "live". The hub throttles noteTyping to 1 per 500 ms per
+ * (client, node), so a peer who keeps typing refreshes well inside this window and one who stopped
+ * fades out. Shared with the hub's contract — re-exported so consumers have one import. */
+export { TYPING_DECAY_MS }
+
+/** A peer's last observed write into a node. `at` is the LOCAL receipt time (see rule 1 above),
+ * never the host stamp that rode the wire. */
+export interface TypingMark {
+ nodeId: string
+ at: number
+}
+
+/** clientId → their last write. A peer types into one node at a time, so one mark each. */
+export type TypingMarks = Readonly<Record<ClientId, TypingMark>>
+
+/** The empty answer, shared and frozen: `typingClientIds` runs once per MOUNTED NODE on every store
+ * write, and the overwhelmingly common case (nobody is typing) must allocate NOTHING and keep a
+ * stable identity, so the caller's shallow compare bails out instead of re-rendering the canvas. */
+const NO_IDS: readonly ClientId[] = Object.freeze([])
+
+/** Is this mark still live? `now - at <= decay`, so a mark from the future (a clock that stepped
+ * back mid-session) counts as live rather than instantly stale. */
+function isLive(mark: TypingMark, now: number): boolean {
+ return now - mark.at <= TYPING_DECAY_MS
+}
+
+/** Record "this peer just wrote into `nodeId`", stamped with OUR clock (`now`). Immutable: returns
+ * a new map, so it can be dropped straight into zustand state. */
+export function markTyping(
+ marks: TypingMarks,
+ clientId: ClientId,
+ nodeId: string,
+ now: number
+): TypingMarks {
+ return { ...marks, [clientId]: { nodeId, at: now } }
+}
+
+/** Forget a peer entirely (they left). Returns the SAME map when there was nothing to forget, so a
+ * leave diff for a peer who never typed writes no state and re-renders nothing. */
+export function dropTyping(marks: TypingMarks, clientId: ClientId): TypingMarks {
+ if (!(clientId in marks)) return marks
+ const next = { ...marks }
+ delete next[clientId]
+ return next
+}
+
+/**
+ * The peers typing into `nodeId` right now, ordered by clientId — i.e. by join order, the same
+ * order the header chips use. Deliberately NOT "freshest first": the order would then flip on every
+ * keystroke of whoever is typing faster, and the chips would jitter; freshness is not rendered.
+ *
+ * The decay is applied HERE, on read, and not only by the sweep timer: a background tab's timers are
+ * throttled to ~1/min, so a ring must be able to expire on the next render even if the sweep is late.
+ */
+export function typingClientIds(
+ marks: TypingMarks,
+ nodeId: string,
+ now: number
+): readonly ClientId[] {
+ let ids: ClientId[] | null = null
+ for (const key in marks) {
+ const id = Number(key) as ClientId
+ const mark = marks[id]
+ if (mark.nodeId !== nodeId || !isLive(mark, now)) continue
+ ;(ids ??= []).push(id)
+ }
+ if (!ids) return NO_IDS
+ return ids.sort((a, b) => a - b)
+}
+
+/** Drop the marks that have decayed. Returns the SAME map when none had — the sweep then writes no
+ * state, so a peer who is still typing does not re-render anyone on every tick. */
+export function pruneTyping(marks: TypingMarks, now: number): TypingMarks {
+ const live: Record<ClientId, TypingMark> = {}
+ let dropped = false
+ for (const key in marks) {
+ const id = Number(key) as ClientId
+ if (isLive(marks[id], now)) live[id] = marks[id]
+ else dropped = true
+ }
+ return dropped ? live : marks
+}
+
+/**
+ * When the next mark decays, in ms from `now` — or `null` when nobody is typing, which is the whole
+ * point: the store arms a timer ONLY while this is non-null, so a solo user (no peers → no typing
+ * patches → no marks) never has a timer running at all. Never negative: an already-expired mark
+ * sweeps on the next tick.
+ */
+export function nextTypingSweepDelay(marks: TypingMarks, now: number): number | null {
+ let earliest: number | null = null
+ for (const key in marks) {
+ const at = marks[Number(key) as ClientId].at
+ if (earliest === null || at < earliest) earliest = at
+ }
+ if (earliest === null) return null
+ return Math.max(0, earliest + TYPING_DECAY_MS - now)
+}
diff --git a/src/renderer/state/presence.ts b/src/renderer/state/presence.ts
index 9431434e7..acd20fd58 100644
--- a/src/renderer/state/presence.ts
+++ b/src/renderer/state/presence.ts
@@ -7,6 +7,14 @@ import {
type PeerIdentity,
type PeerState
} from '@shared/presence'
+import {
+ dropTyping,
+ markTyping,
+ nextTypingSweepDelay,
+ pruneTyping,
+ typingClientIds,
+ type TypingMarks
+} from '../lib/typingPeers'
/**
* Transient team-presence store (docs/team-presence.md). Holds the peer table for the current
@@ -69,6 +77,10 @@ export interface PresenceStore {
me: PeerIdentity | null
/** Everyone connected, INCLUDING me (selectOthers filters me out). */
peers: Record<ClientId, PeerState>
+ /** Who is typing into which node, stamped on OUR clock. Built ONLY from live `presence:peer`
+ * update diffs — never from a snapshot (see THE TYPING MARKS below) — and swept by a timer that
+ * only exists while it is non-empty. Not `PeerState.typing`, and not a mirror of it. */
+ typing: TypingMarks
/** True when we are connected but the user has never chosen a name → show the prompt. */
needsName: boolean
setMe(id: PeerIdentity): void
@@ -77,10 +89,26 @@ export interface PresenceStore {
reset(): void
}
-export const usePresence = create<PresenceStore>((set) => ({
+/**
+ * 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) => {
@@ -93,26 +121,71 @@ export const usePresence = create<PresenceStore>((set) => ({
set(() => {
const table: Record<ClientId, PeerState> = {}
for (const p of peers) table[p.clientId] = p
- return { peers: table }
+ return { peers: table } // `typing` untouched: a snapshot may not light a ring (see above)
}),
- applyDiff: (diff) =>
+ 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 }
+ 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
- return { peers: { ...s.peers, [diff.clientId]: { ...prev, ...diff.patch } } }
- }),
+ 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: () => set({ myId: null, peers: {}, needsName: false })
+ 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
@@ -236,6 +309,37 @@ export function selectFocusedFaces(
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
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 4c2f104c8..629417ab7 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -5353,6 +5353,34 @@ body,
border: 1px solid rgba(0, 0, 0, 0.45);
}
+/* Co-attach: this peer's keystrokes are landing in THIS terminal right now. One PTY, N subscribers
+ and no locking — two people typing into one shell interleave their characters, so the ring IS the
+ warning. It decays ~2s after the last keystroke (TYPING_DECAY_MS, swept in state/presence.ts). */
+.presence-chip--typing {
+ animation: nt-typing-pulse 1.1s ease-out infinite;
+}
+
+@keyframes nt-typing-pulse {
+ 0% {
+ box-shadow: 0 0 0 0 var(--peer-color, #fff);
+ }
+ 70% {
+ box-shadow: 0 0 0 5px transparent;
+ }
+ 100% {
+ box-shadow: 0 0 0 0 transparent;
+ }
+}
+
+/* Respect the OS setting: a ring that pulses forever is exactly the motion this asks us to drop.
+ The signal must survive it, so it becomes a static halo instead of an animation. */
+@media (prefers-reduced-motion: reduce) {
+ .presence-chip--typing {
+ animation: none;
+ box-shadow: 0 0 0 2px var(--peer-color, #fff);
+ }
+}
+
/* The "+N" bubble: neutral, so it never reads as one more person's color. */
.presence-chip--more {
width: auto;