Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(desktop): show live presence faces on spaces, tasks, and canvases (#93321)

Peter Kirkham97093079b54d
diff --git a/products/desktop/packages/core/src/canvas/presence.test.ts b/products/desktop/packages/core/src/canvas/presence.test.ts
new file mode 100644
index 000000000000..8d908390062e
--- /dev/null
+++ b/products/desktop/packages/core/src/canvas/presence.test.ts
@@ -0,0 +1,136 @@
+import {
+ liveUuidsFromTasks,
+ PRESENCE_LIVE_WINDOW_MS,
+ PRESENCE_RECENT_WINDOW_MS,
+ presenceByChannel,
+ presenceTier,
+} from "@posthog/core/canvas/presence";
+import type { Task, UserBasic } from "@posthog/shared/domain-types";
+import { describe, expect, it } from "vitest";
+
+const NOW = 1_700_000_000_000;
+
+function user(uuid: string): UserBasic {
+ return { id: 1, uuid, email: `${uuid}@example.com` };
+}
+
+function task(
+ createdBy: UserBasic | null,
+ agoMs: number,
+): Pick<Task, "created_by" | "last_activity_at"> {
+ return {
+ created_by: createdBy,
+ last_activity_at: new Date(NOW - agoMs).toISOString(),
+ };
+}
+
+describe("presenceTier", () => {
+ it.each([
+ ["just now", 0, "live"],
+ ["inside the live window", PRESENCE_LIVE_WINDOW_MS - 1, "live"],
+ ["at the live boundary", PRESENCE_LIVE_WINDOW_MS, "recent"],
+ ["inside the recent window", PRESENCE_RECENT_WINDOW_MS - 1, "recent"],
+ ["at the recent boundary", PRESENCE_RECENT_WINDOW_MS, "idle"],
+ ["long ago", PRESENCE_RECENT_WINDOW_MS * 2, "idle"],
+ ])("reads %s as %s", (_label, agoMs, expected) => {
+ expect(presenceTier(NOW - agoMs, NOW)).toBe(expected);
+ });
+
+ it("treats a future timestamp (clock skew) as live", () => {
+ expect(presenceTier(NOW + 60_000, NOW)).toBe("live");
+ });
+});
+
+describe("liveUuidsFromTasks", () => {
+ it("includes only authors active within the live window", () => {
+ const live = liveUuidsFromTasks(
+ [
+ task(user("a"), 60_000), // live
+ task(user("b"), PRESENCE_LIVE_WINDOW_MS + 60_000), // recent, not live
+ task(user("c"), PRESENCE_RECENT_WINDOW_MS + 60_000), // idle
+ ],
+ NOW,
+ );
+ expect([...live].sort()).toEqual(["a"]);
+ });
+
+ it("marks a person live from their most recent task, ignoring older ones", () => {
+ const live = liveUuidsFromTasks(
+ [task(user("a"), PRESENCE_LIVE_WINDOW_MS * 5), task(user("a"), 30_000)],
+ NOW,
+ );
+ expect(live.has("a")).toBe(true);
+ });
+
+ it("skips tasks with no author or an unparseable timestamp", () => {
+ const live = liveUuidsFromTasks(
+ [
+ task(null, 0),
+ { created_by: user("a"), last_activity_at: "not-a-date" },
+ { created_by: user("b"), last_activity_at: undefined },
+ ],
+ NOW,
+ );
+ expect(live.size).toBe(0);
+ });
+});
+
+describe("presenceByChannel", () => {
+ function chanTask(
+ channel: string | null,
+ createdBy: UserBasic | null,
+ agoMs: number,
+ ): Pick<Task, "created_by" | "last_activity_at" | "channel"> {
+ return {
+ channel,
+ created_by: createdBy,
+ last_activity_at: new Date(NOW - agoMs).toISOString(),
+ };
+ }
+
+ it("groups recently-active people by channel, most-recent first", () => {
+ const map = presenceByChannel(
+ [
+ chanTask("c1", user("a"), 30_000), // most recent in c1
+ chanTask("c1", user("b"), 90_000),
+ chanTask("c2", user("c"), 60_000),
+ chanTask("c1", user("d"), PRESENCE_RECENT_WINDOW_MS + 1), // idle, dropped
+ ],
+ { now: NOW, limit: 5 },
+ );
+ expect(map.get("c1")?.people.map((p) => p.uuid)).toEqual(["a", "b"]);
+ expect(map.get("c2")?.people.map((p) => p.uuid)).toEqual(["c"]);
+ });
+
+ it("marks only the live people, and only ones it kept", () => {
+ const map = presenceByChannel(
+ [
+ chanTask("c1", user("a"), 30_000), // live
+ chanTask("c1", user("b"), PRESENCE_LIVE_WINDOW_MS + 60_000), // recent
+ ],
+ { now: NOW, limit: 5 },
+ );
+ expect([...(map.get("c1")?.liveUuids ?? [])]).toEqual(["a"]);
+ });
+
+ it("dedupes a person across their tasks and caps at the limit", () => {
+ const map = presenceByChannel(
+ [
+ chanTask("c1", user("a"), 10_000),
+ chanTask("c1", user("a"), 20_000),
+ chanTask("c1", user("b"), 30_000),
+ chanTask("c1", user("c"), 40_000),
+ ],
+ { now: NOW, limit: 2 },
+ );
+ expect(map.get("c1")?.people.map((p) => p.uuid)).toEqual(["a", "b"]);
+ });
+
+ it("skips tasks with no channel", () => {
+ const map = presenceByChannel([chanTask(null, user("a"), 0)], {
+ now: NOW,
+ limit: 5,
+ });
+ expect(map.size).toBe(0);
+ });
+});
diff --git a/products/desktop/packages/core/src/canvas/presence.ts b/products/desktop/packages/core/src/canvas/presence.ts
new file mode 100644
index 000000000000..4b7af09744f9
--- /dev/null
+++ b/products/desktop/packages/core/src/canvas/presence.ts
@@ -0,0 +1,151 @@
+import type { Task, UserBasic } from "@posthog/shared/domain-types";
+
+/**
+ * How long an item counts as "someone is here right now". Within this window of
+ * the last activity a face pulses. Kept short so a pulsing ring means work is
+ * happening, not that it happened this morning.
+ */
+export const PRESENCE_LIVE_WINDOW_MS = 3 * 60_000;
+
+/**
+ * How long a (still) face lingers after the last activity. Presence here is
+ * "recently active", so a face stays a while once its person steps away, then
+ * fades — rather than blinking out the instant a run ends.
+ */
+export const PRESENCE_RECENT_WINDOW_MS = 2 * 60 * 60_000;
+
+export type PresenceTier = "live" | "recent" | "idle";
+
+export interface PresenceWindows {
+ liveWindowMs?: number;
+ recentWindowMs?: number;
+}
+
+/**
+ * Where an item's last activity sits: `live` while it is happening, `recent`
+ * for a while after, `idle` once it is old enough that a face would be noise.
+ *
+ * `ts` and `now` are epoch milliseconds. A `ts` in the future (clock skew)
+ * reads as `live`.
+ */
+export function presenceTier(
+ ts: number,
+ now: number,
+ {
+ liveWindowMs = PRESENCE_LIVE_WINDOW_MS,
+ recentWindowMs = PRESENCE_RECENT_WINDOW_MS,
+ }: PresenceWindows = {},
+): PresenceTier {
+ const age = now - ts;
+ if (age < liveWindowMs) return "live";
+ if (age < recentWindowMs) return "recent";
+ return "idle";
+}
+
+type ActivityTask = Pick<Task, "created_by" | "last_activity_at">;
+
+/**
+ * The uuids of the people whose latest activity in `tasks` is within the live
+ * window — the faces that should pulse. Tasks with no author or an
+ * unparseable timestamp are skipped.
+ *
+ * Callers pass the same recently-active people they already show (creator,
+ * recent authors); this only decides which of those faces are working right
+ * now, so the list of who appears never depends on the clock.
+ */
+export function liveUuidsFromTasks(
+ tasks: readonly ActivityTask[],
+ now: number,
+ windows: PresenceWindows = {},
+): ReadonlySet<string> {
+ const live = new Set<string>();
+ for (const task of tasks) {
+ const author = task.created_by;
+ if (!author || !task.last_activity_at) continue;
+ const ts = Date.parse(task.last_activity_at);
+ if (Number.isNaN(ts)) continue;
+ if (presenceTier(ts, now, windows) === "live") live.add(author.uuid);
+ }
+ return live;
+}
+
+/** An empty presence result, shared so a quiet surface's props stay stable. */
+export const NO_LIVE_UUIDS: ReadonlySet<string> = new Set<string>();
+
+/** Who is around in one channel: the recently-active people, and who's live. */
+export interface ChannelPresence {
+ /** Recently-active people, most-recent first, deduped, capped by `limit`. */
+ people: UserBasic[];
+ /** Of `people`, whoever is working right now. */
+ liveUuids: ReadonlySet<string>;
+}
+
+type ChannelActivityTask = Pick<
+ Task,
+ "created_by" | "last_activity_at" | "channel"
+>;
+
+interface PresenceByChannelOptions extends PresenceWindows {
+ now: number;
+ /** How many faces a channel keeps — the freshest, once sorted. */
+ limit: number;
+}
+
+/**
+ * The recently-active people in each channel, keyed by channel id, built from a
+ * flat page of tasks across all channels. A task with no channel, no author, or
+ * an unparseable timestamp is skipped; a channel with nobody recent is absent
+ * from the map entirely.
+ *
+ * Tasks are sorted most-recent first here, so the result never depends on the
+ * order the caller fetched them in.
+ */
+export function presenceByChannel(
+ tasks: readonly ChannelActivityTask[],
+ { now, limit, liveWindowMs, recentWindowMs }: PresenceByChannelOptions,
+): Map<string, ChannelPresence> {
+ const dated = tasks
+ .map((task) => ({
+ channel: task.channel ?? null,
+ author: task.created_by ?? null,
+ ts: task.last_activity_at
+ ? Date.parse(task.last_activity_at)
+ : Number.NaN,
+ }))
+ .filter(
+ (t): t is { channel: string; author: UserBasic; ts: number } =>
+ t.channel != null && t.author != null && !Number.isNaN(t.ts),
+ )
+ .sort((a, b) => b.ts - a.ts);
+
+ const byChannel = new Map<
+ string,
+ { people: UserBasic[]; liveUuids: Set<string>; seen: Set<string> }
+ >();
+ for (const { channel, author, ts } of dated) {
+ const tier = presenceTier(ts, now, { liveWindowMs, recentWindowMs });
+ if (tier === "idle") continue;
+ let entry = byChannel.get(channel);
+ if (!entry) {
+ entry = { people: [], liveUuids: new Set(), seen: new Set() };
+ byChannel.set(channel, entry);
+ }
+ if (!entry.seen.has(author.uuid)) {
+ if (entry.people.length >= limit) continue;
+ entry.seen.add(author.uuid);
+ entry.people.push(author);
+ }
+ // Only after the author is on the list, so a live mark never names a face
+ // the cap dropped. The first task per author is their most recent (sorted),
+ // so this decides liveness on that one.
+ if (tier === "live") entry.liveUuids.add(author.uuid);
+ }
+
+ const result = new Map<string, ChannelPresence>();
+ for (const [channel, entry] of byChannel) {
+ result.set(channel, { people: entry.people, liveUuids: entry.liveUuids });
+ }
+ return result;
+}
+
+export type { UserBasic };
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
index 6958e9490d91..c81a469613e2 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelItemRow.tsx
@@ -1,4 +1,5 @@
import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";
+import { presenceTier } from "@posthog/core/canvas/presence";
import {
AlertDialog,
AlertDialogClose,
@@ -16,10 +17,12 @@ import {
TooltipTrigger,
} from "@posthog/quill";
import { formatRelativeTimeShort } from "@posthog/shared";
+import type { AvatarPerson } from "@posthog/ui/features/auth/UserAvatar";
import { useCurrentUser } from "@posthog/ui/features/auth/useCurrentUser";
import { writeCanvasDragData } from "@posthog/ui/features/canvas/canvasDrag";
import { ChannelItemHoverCard } from "@posthog/ui/features/canvas/components/ChannelItemHoverCard";
import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";
+import { PresenceAvatar } from "@posthog/ui/features/canvas/components/PresenceAvatars";
import {
type TaskRowBulkMenu,
TaskRowContextMenu,
@@ -28,6 +31,7 @@ import {
import { useChannelItemMetadata } from "@posthog/ui/features/canvas/hooks/useChannelItemFacts";
import { useChannelTaskStatus } from "@posthog/ui/features/canvas/hooks/useChannelTaskStatus";
import { useIsCanvasPendingDelete } from "@posthog/ui/features/canvas/stores/pendingCanvasDeleteStore";
+import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";
import { InlineEditInput } from "@posthog/ui/features/sidebar/components/items/TaskItem";
import {
PinnedBadge,
@@ -45,6 +49,7 @@ import { writeTaskDragData } from "@posthog/ui/features/sidebar/taskDrag";
import { SESSION_ROW_ATTRIBUTE } from "@posthog/ui/features/sidebar/useMarqueeSelection";
import { HandoffTaskDialog } from "@posthog/ui/features/task-detail/components/HandoffTaskDialog";
import { useMountedOnceOpened } from "@posthog/ui/hooks/useMountedOnceOpened";
+import { useNow } from "@posthog/ui/hooks/useNow";
import {
type DragEvent,
type ReactNode,
@@ -146,6 +151,71 @@ function CanvasBadgeStack({
);
}
+/** The person a row is attributed to, as a face can draw them. */
+function rowAuthor(
+ item: ChannelItemModel,
+): { user: AvatarPerson; label: string } | null {
+ if (item.kind === "task") {
+ if (!item.authorUser) return null;
+ return { user: item.authorUser, label: userDisplayName(item.authorUser) };
+ }
+ // A canvas carries only a display name and uuid — no email or photo — so its
+ // face is an initials bubble seeded off the uuid.
+ const name = item.authorName;
+ if (!name && !item.authorUuid) return null;
+ const [first, ...rest] = (name ?? "").split(/\s+/).filter(Boolean);
+ return {
+ user: {
+ uuid: item.authorUuid,
+ first_name: first ?? null,
+ last_name: rest.join(" ") || null,
+ },
+ label: name ?? "Unknown",
+ };
+}
+
+/**
+ * The face of whoever is working on a row, shown only while the item is live or
+ * recently active — a quiet row stays clean.
+ *
+ * Idle is decided here, once, off the clock: an item's activity time is fixed,
+ * so a row that is idle now stays idle until its item changes, and re-rendering
+ * it every minute would buy nothing. Only a row with a face to fade subscribes.
+ */
+function RowPresence({ item }: { item: ChannelItemModel }) {
+ const author = rowAuthor(item);
+ if (!author) return null;
+ if (presenceTier(item.ts, Date.now()) === "idle") return null;
+ return <ActiveRowPresence item={item} author={author} />;
+}
+
+/**
+ * Subscribed to the clock rather than reading it once: the row is memoized on
+ * its item, which a poll returning the same rows leaves untouched, so nothing
+ * else would re-render it as the live window closes and the recent one ends.
+ */
+function ActiveRowPresence({
+ item,
+ author,
+}: {
+ item: ChannelItemModel;
+ author: NonNullable<ReturnType<typeof rowAuthor>>;
+}) {
+ const tier = presenceTier(item.ts, useNow());
+ if (tier === "idle") return null;
+ return (
+ <PresenceAvatar
+ user={author.user}
+ tier={tier}
+ label={
+ tier === "live"
+ ? `${author.label} is working on this`
+ : `${author.label} was here recently`
+ }
+ />
+ );
+}
+
/**
* A row's leading mark, always the task-list state vocabulary. Canvases have no
* live run, so they take the quiet dot and move their glyph to the trailing
@@ -220,6 +290,9 @@ export function ChannelItemRowView({
onClick={onClick}
endContent={
<span className={TRAILING_CLASS}>
+ {/* Who's here, ahead of the badges: presence is the row's most
+ time-sensitive fact, and it's absent on a quiet row. */}
+ <RowPresence item={item} />
{/* Badges take the timestamp's slot: identity (pin, source, cloud,
PR) is what you scan a task list for, and the age is still on the
preview card. */}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx
index 39346d3f2e02..9b58b8c1ab80 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.test.tsx
@@ -93,6 +93,7 @@ vi.mock(
vi.mock("@posthog/ui/features/canvas/hooks/useRecentSpaceTasks", () => ({
NO_TASKS: { items: [], total: 0 },
usePrefetchSpaceTasks: () => () => undefined,
+ useSpacePresence: () => new Map(),
useRecentSpaceTasks: (spaceIds: string[]) =>
new Map(
spaceIds.map((spaceId) => {
diff --git a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
index 0c91e98ec344..8707fb038554 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/ChannelsList.tsx
@@ -12,6 +12,7 @@ import {
TrashIcon,
} from "@phosphor-icons/react";
import type { ChannelItemModel } from "@posthog/core/canvas/channelItems";
+import type { ChannelPresence } from "@posthog/core/canvas/presence";
import {
AlertDialogClose,
AlertDialogContent,
@@ -57,6 +58,7 @@ import {
} from "@posthog/ui/features/canvas/components/ChannelItemHoverCard";
import type { ChannelActionItem } from "@posthog/ui/features/canvas/components/channelActions";
import { channelGlyph } from "@posthog/ui/features/canvas/components/channelGlyph";
+import { PresenceAvatars } from "@posthog/ui/features/canvas/components/PresenceAvatars";
import { RenameChannelModal } from "@posthog/ui/features/canvas/components/RenameChannelModal";
import { SidebarSearchHeader } from "@posthog/ui/features/canvas/components/SidebarSearchHeader";
import type { SpacePreviewPayload } from "@posthog/ui/features/canvas/components/SpacePreview";
@@ -78,6 +80,7 @@ import {
type SpaceTasks,
usePrefetchSpaceTasks,
useRecentSpaceTasks,
+ useSpacePresence,
} from "@posthog/ui/features/canvas/hooks/useRecentSpaceTasks";
import {
SpaceTaskActionsProvider,
@@ -1012,6 +1015,7 @@ const ChannelSection = memo(
hotkeySlot,
expanded = false,
tasks,
+ presence,
onToggleExpanded,
}: {
channel: Channel;
@@ -1026,6 +1030,8 @@ const ChannelSection = memo(
expanded?: boolean;
/** The space's recent sessions and its total; only read while expanded. */
tasks?: SpaceTasks;
+ /** Who's recently active here, shown as faces after the name. */
+ presence?: ChannelPresence;
/**
* Absent while searching, where the list is flat. Takes the space id rather
* than closing over it, so the list can hand every row the same function and
@@ -1047,6 +1053,10 @@ const ChannelSection = memo(
const [menuOpen, setMenuOpen] = useState(false);
const { reveal, hoverProps, focusProps } = useOverflowTickerReveal();
const hasAttention = unreadSessions > 0 || blockedSessions > 0;
+ const people = presence?.people ?? [];
+ // Faces and dots share one trailing slot, so the row's hover margin belongs
+ // to whichever the space has rather than to whichever ends the row.
+ const hasMarks = hasAttention || people.length > 0;
const prefetchSessions = usePrefetchSpaceTasks();
const prefetchTimer = useRef<ReturnType<typeof setTimeout> | undefined>(
undefined,
@@ -1174,9 +1184,9 @@ const ChannelSection = memo(
"text-[13px]",
// mr-11 clears the two icon-xs hover buttons pinned at
// right-1. It belongs on whatever ends the row's content —
- // put it on the name while the dot is there and the gap
- // opens between them, carrying the dot off to the buttons.
- !hasAttention && "group-hover/chan:mr-11",
+ // put it on the name while the marks are there and the gap
+ // opens between them, carrying them off to the buttons.
+ !hasMarks && "group-hover/chan:mr-11",
// Bold is unread's alone; full contrast is shared with the
// channel you're in. Either way there's no hover brighten
// left to do, so those rows skip it.
@@ -1189,29 +1199,42 @@ const ChannelSection = memo(
>
{channel.name}
</OverflowTickerText>
- {/* Both dots in one slot, so the hover margin belongs to the
- pair rather than to whichever of them happens to end the
- row. */}
- {hasAttention && (
+ {/* Faces and dots in one slot, so the hover margin belongs
+ to the group rather than to whichever of them happens to
+ end the row. */}
+ {hasMarks && (
<span
className={cn(
- "flex shrink-0 items-center gap-1",
+ "flex shrink-0 items-center gap-1.5",
"group-hover/chan:mr-11",
menuOpen && "mr-11",
)}
>
+ {/* Who's recently active here, faded while the space is
+ open — the sessions below carry their own faces then. */}
+ {people.length > 0 && (
+ <PresenceAvatars
+ people={people}
+ liveUuids={presence?.liveUuids}
+ className={cn(expanded && "opacity-60")}
+ />
+ )}
{/* Blue first, because the rows below are sorted with
what wants you at the top — the pair reads as a
summary of that list, in its order. */}
- <SpaceAttentionDot
- count={blockedSessions}
- tone="blocked"
- faded={expanded}
- />
- <SpaceAttentionDot
- count={unreadSessions}
- faded={expanded}
- />
+ {hasAttention && (
+ <span className="flex shrink-0 items-center gap-1">
+ <SpaceAttentionDot
+ count={blockedSessions}
+ tone="blocked"
+ faded={expanded}
+ />
+ <SpaceAttentionDot
+ count={unreadSessions}
+ faded={expanded}
+ />
+ </span>
+ )}
</span>
)}
{/* `!mr-0` undoes quill's `.quill-button kbd { margin-right: -4px }`,
@@ -1352,6 +1375,9 @@ const ChannelSection = memo(
prev.blockedSessions === next.blockedSessions &&
prev.hotkeySlot === next.hotkeySlot &&
prev.tasks === next.tasks &&
+ // By reference: useSpacePresence reuses a channel's object until its faces
+ // change, so this stays equal across polls that touched other spaces.
+ prev.presence === next.presence &&
prev.onToggleExpanded === next.onToggleExpanded &&
prev.channel.id === next.channel.id &&
prev.channel.name === next.channel.name &&
@@ -1777,6 +1803,9 @@ export function ChannelsList() {
[allChannels, expandedSpaceIds, treeOn],
);
const tasksBySpace = useRecentSpaceTasks(openSpaceIds);
+ // Who's recently active in each space, for the faces on every row — one
+ // project-wide query, not one per space.
+ const presenceBySpace = useSpacePresence();
// Pin / archive / command centre for every session row, built once here
// rather than once per row.
const spaceTaskActions = useSpaceTaskActions();
@@ -1963,6 +1992,7 @@ export function ChannelsList() {
isUnread={isUnread(channel.id)}
unreadSessions={unreadSessions(channel.id)}
blockedSessions={blockedSessions(channel.id)}
+ presence={presenceBySpace.get(channel.id)}
/>
))}
{noMatches && (
@@ -1999,6 +2029,7 @@ export function ChannelsList() {
hotkeySlot={channelsLayout ? slotFor(channel) : undefined}
expanded={isExpanded(channel.id)}
tasks={tasksOf(channel.id)}
+ presence={presenceBySpace.get(channel.id)}
onToggleExpanded={toggleSpace}
/>
))}
@@ -2027,6 +2058,7 @@ export function ChannelsList() {
blockedSessions={blockedSessions(channel.id)}
expanded={isExpanded(channel.id)}
tasks={tasksOf(channel.id)}
+ presence={presenceBySpace.get(channel.id)}
onToggleExpanded={toggleSpace}
/>
))}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/PresenceAvatars.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/PresenceAvatars.test.tsx
new file mode 100644
index 000000000000..643c4abf5de4
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/PresenceAvatars.test.tsx
@@ -0,0 +1,48 @@
+import type { UserBasic } from "@posthog/shared/domain-types";
+import { render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+import { PresenceAvatar, PresenceAvatars } from "./PresenceAvatars";
+
+function user(uuid: string, first: string): UserBasic {
+ return {
+ id: 1,
+ uuid,
+ email: `${first.toLowerCase()}@example.com`,
+ first_name: first,
+ };
+}
+
+describe("PresenceAvatars", () => {
+ it("draws one labelled face per person", () => {
+ render(<PresenceAvatars people={[user("a", "Ada"), user("b", "Bruno")]} />);
+ expect(screen.getByRole("img", { name: "Ada" })).toBeTruthy();
+ expect(screen.getByRole("img", { name: "Bruno" })).toBeTruthy();
+ });
+
+ it("marks the lead as the space creator", () => {
+ render(<PresenceAvatars people={[user("a", "Ada")]} leadUuid="a" />);
+ expect(
+ screen.getByRole("img", { name: "Ada created this space" }),
+ ).toBeTruthy();
+ });
+
+ it("renders nothing when there are no people", () => {
+ const { container } = render(<PresenceAvatars people={[]} />);
+ expect(container.firstChild).toBeNull();
+ });
+});
+
+describe("PresenceAvatar", () => {
+ it("labels a single owner face", () => {
+ render(
+ <PresenceAvatar
+ user={user("a", "Ada")}
+ tier="live"
+ label="Ada is working on this"
+ />,
+ );
+ expect(
+ screen.getByRole("img", { name: "Ada is working on this" }),
+ ).toBeTruthy();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/canvas/components/PresenceAvatars.tsx b/products/desktop/packages/ui/src/features/canvas/components/PresenceAvatars.tsx
new file mode 100644
index 000000000000..ce01c290cd3a
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/canvas/components/PresenceAvatars.tsx
@@ -0,0 +1,173 @@
+import { CrownSimpleIcon } from "@phosphor-icons/react";
+import type { PresenceTier } from "@posthog/core/canvas/presence";
+import {
+ AvatarGroup,
+ cn,
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@posthog/quill";
+import type { UserBasic } from "@posthog/shared/domain-types";
+import {
+ type AvatarPerson,
+ UserAvatar,
+} from "@posthog/ui/features/auth/UserAvatar";
+import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";
+
+type AvatarSize = "lg" | "default" | "sm" | "xs";
+
+/** A tier that draws something. `idle` faces don't show, so callers filter it. */
+type ActiveTier = Exclude<PresenceTier, "idle">;
+
+/** Matches the rows' own tooltip delay, so a face doesn't feel slower. */
+const TOOLTIP_DELAY_MS = 200;
+
+/**
+ * The corner mark that turns a face into presence: a pulsing dot while the
+ * person is working right now, a quiet one for a while after they step away.
+ * The `ring-background` gap is what lifts it off the avatar the way a stacked
+ * group's own gaps do.
+ */
+function PresenceDot({ tier }: { tier: ActiveTier }) {
+ if (tier === "live") {
+ return (
+ <span className="absolute right-0 bottom-0 flex size-2 items-center justify-center">
+ {/* The halo does the "live" work; a static dot alone reads as a badge. */}
+ <span className="absolute inline-flex size-full animate-ping rounded-full bg-primary opacity-75" />
+ <span className="relative inline-flex size-1.5 rounded-full bg-primary ring-1 ring-background" />
+ </span>
+ );
+ }
+ return (
+ <span className="absolute right-0 bottom-0 size-1.5 rounded-full bg-muted-foreground/70 ring-1 ring-background" />
+ );
+}
+
+/**
+ * One person's face with a presence mark and a name tooltip. Use this for a
+ * single owner beside a row; the group below draws its own faces for a space.
+ */
+export function PresenceAvatar({
+ user,
+ tier,
+ label,
+ size = "xs",
+ className,
+}: {
+ user: AvatarPerson | null | undefined;
+ tier: ActiveTier;
+ /** Overrides the name shown on hover; defaults to the user's display name. */
+ label?: string;
+ size?: AvatarSize;
+ className?: string;
+}) {
+ const name = label ?? userDisplayName(user);
+ return (
+ <Tooltip disableHoverablePopup>
+ <TooltipTrigger
+ render={
+ // `flex`, not `block`: quill's avatar is an inline-flex box, so a
+ // block wrapper adds the line box's descender space under it and the
+ // avatar rides high in a taller container.
+ <span
+ aria-label={name}
+ role="img"
+ className={cn("relative flex shrink-0", className)}
+ >
+ <UserAvatar size={size} user={user} />
+ <PresenceDot tier={tier} />
+ </span>
+ }
+ />
+ <TooltipContent side="top" className="pointer-events-none select-none">
+ {name}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+/**
+ * One face in a space's group: the person, a crown when they created the space,
+ * and a live dot when they are working right now. Non-live people stay plain,
+ * so the group reads as "who's here" and the dots pick out who's active.
+ */
+function GroupPerson({
+ user,
+ isLead,
+ isLive,
+}: {
+ user: UserBasic;
+ isLead: boolean;
+ isLive: boolean;
+}) {
+ const name = userDisplayName(user);
+ const label = isLead ? `${name} created this space` : name;
+ return (
+ <Tooltip disableHoverablePopup>
+ <TooltipTrigger
+ render={
+ <span
+ aria-label={label}
+ role="img"
+ className="relative flex shrink-0"
+ >
+ <UserAvatar size="xs" user={user} />
+ {isLead && (
+ // Top-left rather than top-right: the stack tucks each face behind
+ // the one after it, so the creator's right corner is under its
+ // neighbour and a crown there is a sliver nobody can read. The live
+ // dot takes the bottom-right, so the two never collide.
+ <span className="-top-1 -left-1 absolute rounded-full bg-background p-px">
+ <CrownSimpleIcon
+ size={9}
+ weight="fill"
+ className="block text-primary"
+ />
+ </span>
+ )}
+ {isLive && <PresenceDot tier="live" />}
+ </span>
+ }
+ />
+ <TooltipContent side="top" className="pointer-events-none select-none">
+ {label}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+/**
+ * A space's people, stacked so each face tucks behind the one after it — which
+ * is what `reverse` gives, and why the lead's crown sits on the left corner of
+ * its avatar rather than the right. Live people wear a pulsing dot.
+ */
+export function PresenceAvatars({
+ people,
+ liveUuids,
+ leadUuid,
+ className,
+}: {
+ people: UserBasic[];
+ /** Of `people`, the uuids working right now — their faces pulse. */
+ liveUuids?: ReadonlySet<string>;
+ /** The person to mark with a crown (a space's creator), if shown. */
+ leadUuid?: string;
+ className?: string;
+}) {
+ if (people.length === 0) return null;
+ return (
+ <TooltipProvider delay={TOOLTIP_DELAY_MS}>
+ <AvatarGroup stacked reverse size="xs" className={className}>
+ {people.map((user) => (
+ <GroupPerson
+ key={user.uuid}
+ user={user}
+ isLead={user.uuid === leadUuid}
+ isLive={liveUuids?.has(user.uuid) ?? false}
+ />
+ ))}
+ </AvatarGroup>
+ </TooltipProvider>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/SpacePreview.stories.tsx b/products/desktop/packages/ui/src/features/canvas/components/SpacePreview.stories.tsx
index dd479b6968c2..4d69cd06161d 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/SpacePreview.stories.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/SpacePreview.stories.tsx
@@ -12,9 +12,14 @@ import { SpacePreviewContent, type SpacePreviewPayload } from "./SpacePreview";
*/
function CardFrame({
people,
+ liveUuids,
total,
...payload
-}: SpacePreviewPayload & { people: UserBasic[]; total: number | null }) {
+}: SpacePreviewPayload & {
+ people: UserBasic[];
+ liveUuids?: string[];
+ total: number | null;
+}) {
return (
<div className="p-4">
<Card
@@ -24,6 +29,7 @@ function CardFrame({
<SpacePreviewContent
payload={payload}
people={people}
+ liveUuids={liveUuids ? new Set(liveUuids) : undefined}
total={total}
onAction={() => {}}
/>
@@ -95,6 +101,11 @@ type Story = StoryObj<typeof meta>;
/** Nothing owed: the gutter stays empty and the card is who and what. */
export const Quiet: Story = {};
+/** Two people working right now — their faces wear a pulsing live dot. */
+export const LiveNow: Story = {
+ args: { liveUuids: ["user-2", "user-3"] },
+};
+
/** Both dots the row can show, spelled out. */
export const WantsYou: Story = {
args: { unreadSessions: 3, blockedSessions: 2 },
diff --git a/products/desktop/packages/ui/src/features/canvas/components/SpacePreview.tsx b/products/desktop/packages/ui/src/features/canvas/components/SpacePreview.tsx
index f2fef446f4f6..abed537a6b91 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/SpacePreview.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/SpacePreview.tsx
@@ -1,6 +1,5 @@
-import { CrownSimpleIcon, GitBranchIcon } from "@phosphor-icons/react";
+import { GitBranchIcon } from "@phosphor-icons/react";
import {
- AvatarGroup,
Item,
ItemActions,
ItemContent,
@@ -8,20 +7,15 @@ import {
ItemGroup,
ItemSeparator,
ItemTitle,
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
} from "@posthog/quill";
import type { UserBasic } from "@posthog/shared/domain-types";
-import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";
import {
type ChannelActionItem,
ChannelActionList,
} from "@posthog/ui/features/canvas/components/channelActions";
+import { PresenceAvatars } from "@posthog/ui/features/canvas/components/PresenceAvatars";
import type { Channel } from "@posthog/ui/features/canvas/hooks/useChannels";
import { useSpaceOverview } from "@posthog/ui/features/canvas/hooks/useRecentSpaceTasks";
-import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";
import { DOT_TONE_VAR } from "@posthog/ui/features/sidebar/components/items/taskStatusVocabulary";
/** What the card is about: the space that is being pointed at. */
@@ -34,9 +28,6 @@ export interface SpacePreviewPayload {
actions: ChannelActionItem[];
}
-/** Matches the rows' own tooltip delay, so the card doesn't feel slower. */
-const TOOLTIP_DELAY_MS = 200;
-
/**
* How many faces the group shows. Past this the stack stops reading as people
* and starts reading as texture, and the card is a glance.
@@ -46,79 +37,6 @@ const MAX_PEOPLE = 5;
/** Repos past this are counted rather than named — the card has one line. */
const MAX_REPOS = 3;
-/**
- * One person in the space, as their avatar. The creator wears a crown, because
- * "who made this" is the one thing about a space's people the space itself
- * knows — everyone else in the stack is there for having run something lately.
- */
-function Person({ user, isCreator }: { user: UserBasic; isCreator: boolean }) {
- const name = userDisplayName(user);
- const label = isCreator ? `${name} created this space` : name;
- return (
- <Tooltip disableHoverablePopup>
- <TooltipTrigger
- render={
- // `flex`, not `block`: quill's avatar is an inline-flex box, so a
- // block wrapper adds the line box's descender space under it and the
- // avatar rides at the top of a taller container — enough to knock one
- // face out of line with its neighbours.
- <span
- aria-label={label}
- role="img"
- className="relative flex shrink-0"
- >
- <UserAvatar size="xs" user={user} />
- {isCreator && (
- // Top-left rather than top-right: the stack tucks each face
- // behind the one after it, so the creator's right corner is
- // under its neighbour and a crown there is a sliver of gold
- // nobody can read. Its left corner is the one nothing covers.
- <span className="-top-1 -left-1 absolute rounded-full bg-background p-px">
- <CrownSimpleIcon
- size={9}
- weight="fill"
- className="block text-primary"
- />
- </span>
- )}
- </span>
- }
- />
- <TooltipContent side="top" className="pointer-events-none select-none">
- {label}
- </TooltipContent>
- </Tooltip>
- );
-}
-
-/**
- * The space's people, stacked so each face tucks behind the one after it —
- * which is what `reverse` gives, and why the creator's crown sits on the left
- * corner of its avatar rather than the right.
- */
-function SpacePeople({
- people,
- creatorUuid,
-}: {
- people: UserBasic[];
- creatorUuid: string | undefined;
-}) {
- if (people.length === 0) return null;
- return (
- <TooltipProvider delay={TOOLTIP_DELAY_MS}>
- <AvatarGroup stacked reverse size="xs">
- {people.map((user) => (
- <Person
- key={user.uuid}
- user={user}
- isCreator={user.uuid === creatorUuid}
- />
- ))}
- </AvatarGroup>
- </TooltipProvider>
- );
-}
-
/** A counted signal, drawn as the dot the row shows for it plus the words. */
function CountSignal({
count,
@@ -218,11 +136,14 @@ function SpaceSignals({
export function SpacePreviewContent({
payload,
people,
+ liveUuids,
total,
onAction,
}: {
payload: SpacePreviewPayload;
people: UserBasic[];
+ /** Of `people`, whoever is working right now — their faces pulse. */
+ liveUuids?: ReadonlySet<string>;
/** Sessions in the space, or `null` while the page hasn't arrived. */
total: number | null;
onAction: () => void;
@@ -262,7 +183,11 @@ export function SpacePreviewContent({
{/* Top-aligned: the people belong to the space's name, not to the
block of text under it. */}
<ItemActions className="self-start">
- <SpacePeople people={people} creatorUuid={channel.createdBy?.uuid} />
+ <PresenceAvatars
+ people={people}
+ liveUuids={liveUuids}
+ leadUuid={channel.createdBy?.uuid}
+ />
</ItemActions>
</Item>
<SpaceSignals
@@ -302,6 +227,7 @@ export function SpacePreview({
<SpacePreviewContent
payload={payload}
people={overview.people}
+ liveUuids={overview.liveUuids}
total={overview.total}
onAction={onAction}
/>
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts
index f7a38da88609..c9fe49e8db01 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useRecentSpaceTasks.ts
@@ -2,6 +2,12 @@ import {
buildChannelItems,
type ChannelItemModel,
} from "@posthog/core/canvas/channelItems";
+import {
+ type ChannelPresence,
+ liveUuidsFromTasks,
+ NO_LIVE_UUIDS,
+ presenceByChannel,
+} from "@posthog/core/canvas/presence";
import type { Task, UserBasic } from "@posthog/shared/domain-types";
import { useArchivedTaskIds } from "@posthog/ui/features/archive/useArchivedTaskIds";
import { useOptionalAuthenticatedClient } from "@posthog/ui/features/auth/authClient";
@@ -13,6 +19,7 @@ import {
} from "@posthog/ui/features/canvas/hooks/useUnreadSessionCount";
import { usePinnedTasks } from "@posthog/ui/features/sidebar/usePinnedTasks";
import { useTaskViewed } from "@posthog/ui/features/sidebar/useTaskViewed";
+import { useNow } from "@posthog/ui/hooks/useNow";
import { useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback, useMemo, useRef } from "react";
import {
@@ -281,6 +288,8 @@ export function usePrefetchSpaceTasks(): (spaceId: string) => void {
export interface SpaceOverview {
/** Who has been working here, creator first. Capped by `peopleLimit`. */
people: UserBasic[];
+ /** Of `people`, whoever is working right now — their faces pulse. */
+ liveUuids: ReadonlySet<string>;
/**
* Sessions in the space, by the same reckoning the tree's total uses, or
* `null` until the page arrives — a space's count is not zero just because
@@ -289,7 +298,11 @@ export interface SpaceOverview {
total: number | null;
}
-const NO_OVERVIEW: SpaceOverview = { people: [], total: null };
+const NO_OVERVIEW: SpaceOverview = {
+ people: [],
+ liveUuids: NO_LIVE_UUIDS,
+ total: null,
+};
/**
* A space's people and its session count, off the same page the tree draws its
@@ -315,19 +328,24 @@ export function useSpaceOverview(
...spaceTaskPageQuery(client, spaceId),
enabled: !!client,
});
+ // A dependency, not `Date.now()` inline: the query keeps `data` referentially
+ // equal across polls that return the same rows, so without the clock in the
+ // memo a live dot would never fade while nobody touched the space.
+ const now = useNow();
return useMemo(() => {
if (!data) return NO_OVERVIEW;
const live = data.tasks.filter((task) => !archivedTaskIds.has(task.id));
return {
people: spacePeople(live, createdBy, peopleLimit),
+ liveUuids: liveUuidsFromTasks(live, now),
// A page that came back short is the whole space, so the count is exact
// once the archived ones are dropped. A full page falls back to the
// server's total, which excludes archived tasks — bar any this device has
// archived and not yet mirrored.
total: data.tasks.length < TREE_FETCH_LIMIT ? live.length : data.count,
};
- }, [data, archivedTaskIds, createdBy, peopleLimit]);
+ }, [data, archivedTaskIds, createdBy, peopleLimit, now]);
}
/**
@@ -355,3 +373,85 @@ export function spacePeople(
for (const task of tasks) add(task.created_by);
return people;
}
+
+/** Faces a collapsed space row shows — kept small so the row stays a glance. */
+const SPACE_PRESENCE_LIMIT = 3;
+/**
+ * One page of the team's most recently active tasks across every space, which
+ * the whole list's presence is aggregated from. Full task records are heavy, so
+ * this is a short page polled slowly — presence here is "recently active", not
+ * a live cursor, so a minute of lag is invisible.
+ *
+ * The page is a global cut, so it is also a bound on what can show: a space
+ * whose newest activity sits below this many newer tasks elsewhere shows no
+ * faces even inside the recent window. The task list has no date filter to ask
+ * for "the last two hours" instead, so the fix for a team that outruns this is a
+ * slim per-channel participants field on the server, not a bigger page here.
+ */
+const SPACE_PRESENCE_FETCH_LIMIT = 100;
+const SPACE_PRESENCE_POLL_INTERVAL_MS = 90_000;
+
+const NO_PRESENCE: ReadonlyMap<string, ChannelPresence> = new Map();
+
+/** Whether two channels' presence draw the same, so a row can reuse the old object. */
+function samePresence(a: ChannelPresence, b: ChannelPresence): boolean {
+ if (a.people.length !== b.people.length) return false;
+ if (a.liveUuids.size !== b.liveUuids.size) return false;
+ for (let index = 0; index < a.people.length; index++) {
+ if (a.people[index]?.uuid !== b.people[index]?.uuid) return false;
+ }
+ for (const uuid of a.liveUuids) if (!b.liveUuids.has(uuid)) return false;
+ return true;
+}
+
+/**
+ * Who is recently active in each space, keyed by space id — the faces a
+ * collapsed space row wears without expanding it. One project-wide query feeds
+ * the whole list, rather than one per space.
+ *
+ * Each channel's entry keeps its object identity across polls while its faces
+ * don't change, so a memoized space row only re-renders when its own presence
+ * does.
+ */
+export function useSpacePresence(): ReadonlyMap<string, ChannelPresence> {
+ const client = useOptionalAuthenticatedClient();
+ const archivedTaskIds = useArchivedTaskIds();
+ const { data } = useQuery({
+ queryKey: ["space-presence"],
+ queryFn: async (): Promise<SpaceTaskPage> => {
+ if (!client) throw new Error("Not authenticated");
+ return (await client.getTasksPage({
+ limit: SPACE_PRESENCE_FETCH_LIMIT,
+ ordering: "-last_activity_at",
+ })) as SpaceTaskPage;
+ },
+ enabled: !!client,
+ refetchInterval: SPACE_PRESENCE_POLL_INTERVAL_MS,
+ gcTime: SPACE_QUERY_GC_TIME_MS,
+ meta: AUTH_SCOPED_QUERY_META,
+ staleTime: SPACE_QUERY_STALE_TIME_MS,
+ });
+
+ // In the memo for the same reason `useSpaceOverview` has it: the tiers are
+ // clock-derived, and the query alone would never move them.
+ const now = useNow();
+
+ // The last object handed out per channel, so a row can be given the same one
+ // back. Entries are set in place rather than the map swapped, as the sibling
+ // cache above does; a channel that leaves the page keeps a stale entry until
+ // it returns, which costs one small object per space ever seen.
+ const cache = useRef(new Map<string, ChannelPresence>());
+ return useMemo(() => {
+ if (!data) return NO_PRESENCE;
+ const live = data.tasks.filter((task) => !archivedTaskIds.has(task.id));
+ const fresh = presenceByChannel(live, { now, limit: SPACE_PRESENCE_LIMIT });
+ const stable = new Map<string, ChannelPresence>();
+ for (const [channelId, next] of fresh) {
+ const prev = cache.current.get(channelId);
+ const kept = prev && samePresence(prev, next) ? prev : next;
+ cache.current.set(channelId, kept);
+ stable.set(channelId, kept);
+ }
+ return stable;
+ }, [data, archivedTaskIds, now]);
+}
diff --git a/products/desktop/packages/ui/src/hooks/useNow.test.ts b/products/desktop/packages/ui/src/hooks/useNow.test.ts
new file mode 100644
index 000000000000..dca7a8e74954
--- /dev/null
+++ b/products/desktop/packages/ui/src/hooks/useNow.test.ts
@@ -0,0 +1,38 @@
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useNow } from "./useNow";
+
+const MINUTE = 60 * 1000;
+
+describe("useNow", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("re-renders with the moved clock once a minute", () => {
+ const { result } = renderHook(() => useNow());
+ const first = result.current;
+
+ act(() => {
+ vi.advanceTimersByTime(MINUTE);
+ });
+
+ expect(result.current).toBeGreaterThanOrEqual(first + MINUTE);
+ });
+
+ it("shares one timer across subscribers and stops it when the last leaves", () => {
+ const a = renderHook(() => useNow());
+ const b = renderHook(() => useNow());
+ expect(vi.getTimerCount()).toBe(1);
+
+ a.unmount();
+ expect(vi.getTimerCount()).toBe(1);
+
+ b.unmount();
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
diff --git a/products/desktop/packages/ui/src/hooks/useNow.ts b/products/desktop/packages/ui/src/hooks/useNow.ts
new file mode 100644
index 000000000000..7a67374ed6e1
--- /dev/null
+++ b/products/desktop/packages/ui/src/hooks/useNow.ts
@@ -0,0 +1,46 @@
+import { useSyncExternalStore } from "react";
+
+/**
+ * How often subscribers see the clock move. Presence tiers are minutes wide,
+ * so a minute is fine grain, and the tick is shared by every subscriber.
+ */
+const TICK_MS = 60_000;
+
+const listeners = new Set<() => void>();
+let now = Date.now();
+let timer: ReturnType<typeof setInterval> | undefined;
+
+function subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ // One interval for the whole app, started by the first subscriber and
+ // stopped by the last: dozens of rows reading the clock should not mean
+ // dozens of timers.
+ if (!timer) {
+ timer = setInterval(() => {
+ now = Date.now();
+ for (const notify of listeners) notify();
+ }, TICK_MS);
+ }
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0 && timer) {
+ clearInterval(timer);
+ timer = undefined;
+ }
+ };
+}
+
+function snapshot(): number {
+ return now;
+}
+
+/**
+ * The wall clock, in epoch milliseconds, re-rendering the caller once a minute.
+ *
+ * For anything derived from "how long ago": a value memoized on data alone
+ * never notices the clock moving, so a face that should stop pulsing after
+ * three minutes keeps pulsing until the data happens to change.
+ */
+export function useNow(): number {
+ return useSyncExternalStore(subscribe, snapshot, snapshot);
+}