Repository navigation
feat(encounters): render Co-DM presence on the encounter runner (#2212) #2213
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
80 changes: 80 additions & 0 deletions
80
apps/web/src/features/encounters/EncounterPresenceIndicator.tsx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| /** | ||
| * Compact Co-DM presence indicator for the encounter runner (issue #2212, #816 slice 2). | ||
| * | ||
| * Renders the OTHER human collaborators currently on the same running encounter — a chip | ||
| * per person showing their name and coarse activity (`viewing` / `editing`) — resolved | ||
| * from the `encounter.presence` SSE roster maintained by {@link useEncounterPresence}. | ||
| * | ||
| * The current user is never listed (AC #2212.5): the roster this receives may include the | ||
| * caller (they legitimately declared), so they are filtered out here. | ||
| * | ||
| * Presentational only. Secrecy is server-enforced — a non-DM on a hidden encounter never | ||
| * receives the frames in the first place (AC #2212.7) — and name resolution comes from the | ||
| * membership roster every member already reads (`names`), so no new secret crosses the | ||
| * wire. Returns `null` when nobody else is present, so a solo DM sees nothing. | ||
| */ | ||
| import { useTranslation } from 'react-i18next'; | ||
| import type { EncounterPresenceEntry } from '@campfire/schema'; | ||
|
|
||
| export interface EncounterPresenceIndicatorProps { | ||
| /** Live roster (may include the caller). */ | ||
| members: readonly EncounterPresenceEntry[]; | ||
| /** The current user's id (`me.user.id`), stringified for comparison — never rendered. */ | ||
| selfUserId: string | number | null | undefined; | ||
| /** `String(member.userId)` → display name, from the membership roster. */ | ||
| names: ReadonlyMap<string, string>; | ||
| } | ||
|
|
||
| export function EncounterPresenceIndicator({ | ||
| members, | ||
| selfUserId, | ||
| names, | ||
| }: EncounterPresenceIndicatorProps): JSX.Element | null { | ||
| const { t } = useTranslation(); | ||
| // When selfUserId is null/undefined (e.g. while `me` is loading), filter by a | ||
| // sentinel that matches nothing rather than an empty string that could match | ||
| // a real userId, so the caller never briefly sees themselves (AC #2212.5). | ||
| const self = selfUserId == null ? '\u0000SELF_NOT_LOADED' : String(selfUserId); | ||
| const others = members.filter((member) => member.userId !== self); | ||
| if (others.length === 0) return null; | ||
|
|
||
| return ( | ||
| <span | ||
| className="cf-presence-roster" | ||
| data-testid="encounter-presence-roster" | ||
| title={t('encounters.presence.groupTitle')} | ||
| style={{ display: 'inline-flex', alignItems: 'center', gap: 4, flexWrap: 'wrap' }} | ||
| > | ||
| {others.map((member) => { | ||
| const name = names.get(member.userId) ?? member.userId; | ||
| const activity = t(`encounters.presence.${member.activity}`); | ||
| return ( | ||
| <span | ||
| key={member.userId} | ||
| className={`tag ${member.activity === 'editing' ? 'tag-accent' : 'tag-neutral'}`} | ||
| data-testid={`encounter-presence-chip-${member.userId}`} | ||
| style={{ | ||
| fontSize: 10.5, | ||
| display: 'inline-flex', | ||
| alignItems: 'center', | ||
| gap: 4, | ||
| }} | ||
| > | ||
| <span | ||
| aria-hidden={true} | ||
| data-testid={`encounter-presence-dot-${member.userId}`} | ||
| style={{ | ||
| width: 6, | ||
| height: 6, | ||
| borderRadius: '50%', | ||
| background: 'currentColor', | ||
| flexShrink: 0, | ||
| }} | ||
| /> | ||
| {t('encounters.presence.personLabel', { name, activity })} | ||
| </span> | ||
| ); | ||
| })} | ||
| </span> | ||
| ); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
188 changes: 188 additions & 0 deletions
188
apps/web/src/features/encounters/useEncounterPresence.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,188 @@ | ||
| /** | ||
| * Co-DM encounter presence — the web client half of the ephemeral presence | ||
| * foundation delivered by issue #2209 (#816 slice 1). This hook is the UI layer | ||
| * (issue #2212, #816 slice 2): while a DM holds open a RUNNING encounter, it: | ||
| * | ||
| * - DECLARES the caller present (`POST /encounters/:id/presence`) on open and on | ||
| * every coarse-activity change (`viewing` ↔ `editing`), seeding the local roster | ||
| * from the snapshot the server returns (AC #2212.2). | ||
| * - HEARTBEATS that declaration on a cadence well inside the server's 45s TTL | ||
| * (default 30s) while the tab is visible, so the lease never silently expires | ||
| * (AC #2212.3). | ||
| * - LEAVES (`DELETE /encounters/:id/presence`) on unmount / navigate-away / loss of | ||
| * eligibility, via a `keepalive` fetch so the leave survives page teardown. | ||
| * - exposes the live roster (reconciled from those POST responses AND from | ||
| * `encounter.presence` SSE frames routed through {@link EncounterPresenceApi.applySnapshot}) | ||
| * for the runner to render "Alice and Bob are here" (AC #2212.1, #2212.4). | ||
| * | ||
| * Presence is transport-level state, not a domain write (see the schema doc on | ||
| * `EncounterPresenceSnapshot`): it is in-memory only, never audited, and the secrecy | ||
| * invariant — a hidden encounter's presence reaches DMs only — is enforced server-side | ||
| * at emit time (#2209). This hook therefore sends `activity` and reconciles whatever | ||
| * `members` it receives; it performs NO client-side hiding (AC #2212.7). | ||
| * | ||
| * Only DMs declare (AC #2212.2: "When a DM opens a running encounter …"); pass | ||
| * `enabled` false for everyone else. A DM never appears in their own indicator — the | ||
| * caller filters `members` by the current user's id (AC #2212.5) — but the roster this | ||
| * hook holds DOES include the caller, because they legitimately declared. | ||
| */ | ||
| import { useCallback, useEffect, useRef, useState } from 'react'; | ||
| import type { | ||
| EncounterPresenceActivity, | ||
| EncounterPresenceEntry, | ||
| EncounterPresenceSnapshot, | ||
| } from '@campfire/schema'; | ||
| import { api, API } from '../../lib/api'; | ||
|
|
||
| export interface UseEncounterPresenceOptions { | ||
| encounterId: number; | ||
| /** | ||
|
AwsomeFox marked this conversation as resolved.
Resolved
|
||
| * Only eligible viewers declare. Callers should pass `isDm && encounter.status === | ||
| * 'running'` (AC #2212.2). When false the hook sends a keepalive DELETE for any | ||
| * prior declaration and clears local state, so it is safe to mount unconditionally. | ||
| */ | ||
| enabled: boolean; | ||
| /** | ||
| * Coarse activity to declare. The hook re-declares when this changes (the server | ||
| * broadcasts a fresh snapshot on an activity change), so a Co-DM's "editing" surfaces | ||
| * promptly rather than waiting for the next heartbeat. | ||
| */ | ||
| activity: EncounterPresenceActivity; | ||
| /** Heartbeat cadence in ms. Defaults to 30s — well inside the 45s server TTL. */ | ||
| heartbeatMs?: number; | ||
| } | ||
|
|
||
| export interface EncounterPresenceApi { | ||
| /** Current presence roster (a snapshot — replace, never patch). Includes the caller. */ | ||
| members: EncounterPresenceEntry[]; | ||
| /** Replace the roster from an `encounter.presence` SSE frame (or any fresh snapshot). */ | ||
| applySnapshot: (members: EncounterPresenceEntry[]) => void; | ||
| /** Re-declare immediately (used on SSE reconnect/recovery to restore presence). */ | ||
| redeclare: () => void; | ||
| } | ||
|
|
||
| /** Default heartbeat interval (ms). Server presence TTL is 45s; this stays well inside. */ | ||
| export const ENCOUNTER_PRESENCE_HEARTBEAT_MS = 30_000; | ||
|
|
||
| export function useEncounterPresence({ | ||
| encounterId, | ||
| enabled, | ||
| activity, | ||
| heartbeatMs = ENCOUNTER_PRESENCE_HEARTBEAT_MS, | ||
| }: UseEncounterPresenceOptions): EncounterPresenceApi { | ||
| const [members, setMembers] = useState<EncounterPresenceEntry[]>([]); | ||
|
|
||
| // A snapshot is a full replace (see EncounterPresenceSnapshot), so the setter is a | ||
| // trivial stable callback the SSE handler can call without entering the effect deps. | ||
| const applySnapshot = useCallback((next: EncounterPresenceEntry[]) => { | ||
| setMembers(next); | ||
| }, []); | ||
|
|
||
| // Declare (or refresh) presence. The response is the post-declare snapshot, which we | ||
| // reconcile into local state — a same-activity heartbeat still returns the full set, so | ||
| // this keeps the roster fresh even between SSE frames. Best-effort: a failed declare | ||
| // (e.g. a transient network blip, or the encounter being ended/trashed concurrently) | ||
| // leaves the previous roster in place; the next heartbeat, reconnect re-declare, or SSE | ||
| // frame re-syncs. | ||
| // Track the current encounterId inside the declare closure so a response from | ||
| // an obsolete encounter (navigated A -> B while A's POST was in flight) is | ||
| // discarded rather than overwriting B's roster. The ref is updated on every | ||
| // render and read after the await resolves. | ||
| const activeEncounterRef = useRef(encounterId); | ||
| activeEncounterRef.current = encounterId; | ||
|
|
||
| const declare = useCallback( | ||
| async (act: EncounterPresenceActivity): Promise<void> => { | ||
| const declaredFor = encounterId; | ||
| try { | ||
| const snap = await api.post<EncounterPresenceSnapshot>( | ||
| `${API}/encounters/${encounterId}/presence`, | ||
| { activity: act }, | ||
| ); | ||
| // Discard if the user navigated to a different encounter while this POST was pending. | ||
| if (activeEncounterRef.current !== declaredFor) return; | ||
| setMembers(snap.members); | ||
|
AwsomeFox marked this conversation as resolved.
Resolved
AwsomeFox marked this conversation as resolved.
Resolved
|
||
| } catch { | ||
| /* best-effort — heartbeat / reconnect / SSE re-sync */ | ||
| } | ||
| }, | ||
| [encounterId], | ||
| ); | ||
|
|
||
| // Latest activity/enabled, read inside the heartbeat tick and `redeclare` without | ||
| // restarting those effects on every activity flip. | ||
| const activityRef = useRef(activity); | ||
| activityRef.current = activity; | ||
| const enabledRef = useRef(enabled); | ||
| enabledRef.current = enabled; | ||
|
|
||
| // AC #2212.2: declare on open and re-declare on a coarse-activity change so a Co-DM's | ||
| // "editing" is reflected without waiting for the heartbeat. `activity` is a two-state | ||
| // hint tied to discrete DM actions, so this is one declare per action — not a storm. | ||
| useEffect(() => { | ||
| if (!enabled) return; | ||
| void declare(activity); | ||
| }, [enabled, encounterId, activity, declare]); | ||
|
AwsomeFox marked this conversation as resolved.
Resolved
|
||
|
|
||
| // AC #2212.3: heartbeat while the tab is visible. The server TTL is 45s; 30s keeps the | ||
| // lease safe across one missed tick. Pauses while hidden (AC: "while the encounter tab | ||
| // is visible") and re-declares immediately on becoming visible — if the tab was hidden | ||
| // past the TTL the server already reaped the entry, and this restores it. | ||
| useEffect(() => { | ||
| if (!enabled) return; | ||
|
|
||
| let handle: ReturnType<typeof setInterval> | undefined; | ||
| const tick = (): void => { | ||
| void declare(activityRef.current); | ||
| }; | ||
| const stop = (): void => { | ||
| if (handle !== undefined) { | ||
| clearInterval(handle); | ||
| handle = undefined; | ||
| } | ||
| }; | ||
| const start = (): void => { | ||
| if (handle === undefined) handle = setInterval(tick, heartbeatMs); | ||
| }; | ||
| const onVisibilityChange = (): void => { | ||
| if (document.visibilityState === 'visible') { | ||
| tick(); | ||
| start(); | ||
| } else { | ||
| stop(); | ||
| } | ||
| }; | ||
| if (document.visibilityState === 'visible') start(); | ||
| document.addEventListener('visibilitychange', onVisibilityChange); | ||
| return () => { | ||
| document.removeEventListener('visibilitychange', onVisibilityChange); | ||
| stop(); | ||
| }; | ||
| }, [enabled, encounterId, heartbeatMs, declare]); | ||
|
|
||
| // Re-declare immediately on SSE reconnect/recovery — a long outage may have crossed the | ||
| // TTL and let the server reap this entry, so reconnect restores presence rather than | ||
| // waiting up to a heartbeat. No-op when presence is not enabled. | ||
| const redeclare = useCallback((): void => { | ||
| if (!enabledRef.current) return; | ||
| void declare(activityRef.current); | ||
| }, [declare]); | ||
|
|
||
| // AC #2212.2: leave on unmount / navigate-away / loss of eligibility. `keepalive` so the | ||
| // DELETE survives page teardown; a dropped leave is harmless (the server reaps the entry | ||
| // at its TTL). Clearing local state keeps a re-enabled hook from flashing stale names. | ||
| useEffect(() => { | ||
| if (!enabled) return; | ||
| const id = encounterId; | ||
| return () => { | ||
| void api | ||
| .delete(`${API}/encounters/${id}/presence`, { keepalive: true }) | ||
| .catch(() => { | ||
| /* best-effort — TTL reap covers a dropped leave */ | ||
| }); | ||
| setMembers([]); | ||
| }; | ||
| }, [enabled, encounterId]); | ||
|
|
||
| return { members, applySnapshot, redeclare }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.