Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions apps/web/src/features/encounters/EncounterPresenceIndicator.tsx
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);
Comment thread
AwsomeFox marked this conversation as resolved.
Resolved
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>
);
}
48 changes: 47 additions & 1 deletion apps/web/src/features/encounters/RunSessionPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { DetailPageWayfinding } from '../../components/DetailPageWayfinding';
import { PrintControl } from '../../components/PrintControl';
import { PrintOnly } from '../../components/PrintOnly';
import { useKeyboardCommandHint, useKeyboardGuardedAction } from '../../components/KeyboardCommandProvider';
import type { ActionSpec, ActionUndoToken, AoeTemplate, CampaignMember, CastSessionCreated, Character, Combatant, CombatantRemoveResult, DiceRoll, DifficultyBand, EncounterDifficulty, EncounterEvent, EncounterWithCombatants, TurnWorkspace as TurnWorkspaceData, FogState, GenerateMapParams, GeneratedMapResult, HpResyncDirection, HpSyncConflict, MapObjectCreate, MapObjectUpdate, MapPing, RulePack, TokenSize, UsableAction } from '@campfire/schema';
import type { ActionSpec, ActionUndoToken, AoeTemplate, CampaignMember, CastSessionCreated, Character, Combatant, CombatantRemoveResult, DiceRoll, DifficultyBand, EncounterDifficulty, EncounterEvent, EncounterPresenceEntry, EncounterWithCombatants, TurnWorkspace as TurnWorkspaceData, FogState, GenerateMapParams, GeneratedMapResult, HpResyncDirection, HpSyncConflict, MapObjectCreate, MapObjectUpdate, MapPing, RulePack, TokenSize, UsableAction } from '@campfire/schema';
import { actionEconomyForAdapter, ARCHMAGE_ADAPTER_ID, STARFINDER_ADAPTER_ID, buildDifficultyExplanation, fogStatesEqual, hasCriticalHitsForAdapter, hasInitiativeRollForAdapter, LAIR_INITIATIVE_COUNT, LEGENDARY_ACTION_SLOT, ruleSystemAdapter } from '@campfire/schema';
import { entityTargetProps, entityHref } from '../../lib/entityLinks';
import { rulesetCapabilitiesForSelection } from '../../lib/rules';
Expand Down Expand Up @@ -90,6 +90,8 @@ import { useAiDmLiveActivity } from '../ai-dm/useAiDmLiveActivity';
import { EncounterAiDriverPanel } from '../ai-dm/EncounterAiDriverPanel';
import { AiDmPresenceTag, AiDmToolActivityRow } from '../ai-dm/AiDmActivityChip';
import { resolveToolActivity, toolResource } from '../ai-dm/toolActivity';
import { useEncounterPresence } from './useEncounterPresence';
import { EncounterPresenceIndicator } from './EncounterPresenceIndicator';
import { GameIcon } from '../../components/GameIcon';
import { TermHelp } from '../../components/TermHelp';
import { useWakeLock } from '../screen/useWakeLock';
Expand Down Expand Up @@ -1925,6 +1927,14 @@ export default function RunSessionPage() {
setSyncRevision(null);
}, [eid]);

// Issue #2212 (#816 slice 2): Co-DM presence. The roster lives in `useEncounterPresence`
// (called below, once `headerBusy` is in scope for the activity hint), but the SSE
// handlers wired in `useCampaignEvents` below need to reach it. A ref bridge closes the
// order gap the same way `useCampaignEvents` itself mirrors its own `handlersRef`: the
// ref is assigned during render (before any SSE frame can arrive), so the handlers read
// the live functions without entering the `useCallback` deps.
const presenceApplyRef = useRef<((members: EncounterPresenceEntry[]) => void) | null>(null);
const presenceRedeclareRef = useRef<(() => void) | null>(null);
// Live updates over SSE (issue #4) — players waiting for the DM to hit "Start" (or
// take a turn, adjust HP, …) see it pushed instantly. Rather than a manual reload, an
// event just invalidates the encounter's reads and Query refetches. On a remote delete,
Expand Down Expand Up @@ -1978,6 +1988,15 @@ export default function RunSessionPage() {
invalidateCampaignCheckRequests(queryClient, cid);
return;
}
// Issue #2212 (#816 slice 2): a Co-DM joined/left/heartbeat-expired on this
// encounter. The frame is a FULL snapshot (see EncounterPresenceSnapshot), so the
// roster is replaced rather than patched — a late or reconnecting client reconciles
// by swapping its local set. Handle it before the encounter-type filter below (which
// only admits the encounter.* change signals), and ignore frames for other encounters.
if (event.type === 'encounter.presence') {
if (event.encounterId === eid) presenceApplyRef.current?.(event.members);
return;
}
if (event.type !== 'encounter.updated' && event.type !== 'encounter.deleted' && event.type !== 'encounter.ping' && event.type !== 'encounter.turn_changed') return;
if (event.encounterId !== eid) return;
if (event.type === 'encounter.deleted') {
Expand Down Expand Up @@ -2123,6 +2142,10 @@ export default function RunSessionPage() {
// frame outright — re-arm the REST turn-beat baseline resync (see
// `awaitingTurnBeatResyncRef`'s own comment) so the catch-up encounter read above
// re-derives it.
// Issue #2212: an outage that crossed the 45s presence TTL let the server reap this
// DM's entry — re-declare so reconnect restores presence rather than waiting up to a
// heartbeat. No-op when presence is not enabled.
presenceRedeclareRef.current?.();
}, [queryClient, eid, cid, invalidateCampaignCharactersForOwnership, refreshCampaigns]),
// Parser recovery (connection stayed up) — same catch-up refetch.
onStreamRecovery: useCallback(() => {
Expand All @@ -2134,6 +2157,8 @@ export default function RunSessionPage() {
void queryClient.invalidateQueries({ queryKey: queryKeys.encounterTurn(eid) });
invalidateTableSafety(queryClient, cid);
void refreshCampaigns();
// Issue #2212: same presence-restore rationale as `onReconnect` above.
presenceRedeclareRef.current?.();
}, [queryClient, eid, cid, invalidateCampaignCharactersForOwnership, refreshCampaigns]),
onStatusChange: useCallback((status: CampaignEventsStatus) => setEventStatus(status), []),
});
Expand Down Expand Up @@ -3961,6 +3986,17 @@ export default function RunSessionPage() {
// is unavailable, which is the "reconcile before another action is allowed" rule.
const headerBusy =
runControl.isPending || nextTurnMut.isPending || hpMutationCount > 0 || bulkHpApplyPending || undoTurnMut.isPending || deleteEncounterMut.isPending || escalationControl.isPending || reconcileBlocks;
// Issue #2212 (#816 slice 2): Co-DM presence. Only a DM on a running encounter declares
// (AC #2212.2); the coarse activity is `editing` while a cockpit write is in flight and
// `viewing` otherwise. The hook owns the roster; the ref bridge hands its reconciler /
// re-declarer to the SSE handlers wired further up.
const presence = useEncounterPresence({
encounterId: eid,
enabled: isDm && encounter?.status === 'running' && Number.isFinite(eid),
activity: headerBusy ? 'editing' : 'viewing',
Comment thread
AwsomeFox marked this conversation as resolved.
Resolved
});
presenceApplyRef.current = presence.applySnapshot;
presenceRedeclareRef.current = presence.redeclare;
const nextTurnShortcut = useKeyboardCommandHint('encounterNextTurn');

useKeyboardGuardedAction(
Expand Down Expand Up @@ -4663,6 +4699,16 @@ export default function RunSessionPage() {
{/* AI-DM presence chip (#344) — the Driver's live session chat is available
on this running encounter. */}
{liveActivity.mode === 'driver' && <AiDmPresenceTag turnActive={liveActivity.turnActive} />}
{/* Co-DM presence (#2212, #816 slice 2) — the other human collaborators
currently on this encounter, from the `encounter.presence` SSE roster. The
current user is filtered out inside the indicator. Hidden when nobody else
is here. Secrecy is server-enforced (a non-DM on a hidden encounter never
receives the frames), so this renders purely from the roster it is given. */}
<EncounterPresenceIndicator
members={presence.members}
selfUserId={myUserId}
names={aoeDeclarerNames}
/>
<button
type="button"
className="btn btn-ghost"
Expand Down
188 changes: 188 additions & 0 deletions apps/web/src/features/encounters/useEncounterPresence.ts
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;
/**
Comment thread
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);
Comment thread
AwsomeFox marked this conversation as resolved.
Resolved
Comment thread
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]);
Comment thread
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 };
}
6 changes: 6 additions & 0 deletions apps/web/src/i18n/locales/ar/encounters.json
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,12 @@
"roll": "ارمِ أي نرد — تظهر النتيجة على كل شاشة حول الطاولة",
"noMapTitle": "لا توجد خريطة معركة بعد",
"noMapHint": "لم يشارك سيد اللعبة خريطة لهذه المواجهة. ترتيب الأدوار وشخصيتك موجودان في اللوحة الجانبية."
},
"presence": {
"viewing": "مشاهدة",
"editing": "تحرير",
"personLabel": "{{name}} · {{activity}}",
"groupTitle": "مساهمون آخرون في هذه المواجهة"
}
}
}
Loading
Loading