: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(today): show who is active in each space on the sidebar (#109579)
Shy Altera05d33b5c47d
diff --git a/frontend/src/layout/today/TodaySpacesRow.tsx b/frontend/src/layout/today/TodaySpacesRow.tsxindex 161374be46f5..e5a9c1a09fbe 100644--- a/frontend/src/layout/today/TodaySpacesRow.tsx+++ b/frontend/src/layout/today/TodaySpacesRow.tsx@@ -6,6 +6,18 @@ import { LinkPrimitive } from 'lib/lemon-ui/Link'import { TodayOverflowText } from './TodayOverflowText'+// The label's right padding for the icon-sized slots that sit over the end of the row, at rest and on hover.+const TRAILING_PADDING = ['', 'pr-8', 'pr-12', 'pr-16', 'pr-20', 'pr-24'] as const+const HOVER_TRAILING_PADDING = [+ '',+ 'group-hover/row:pr-8 group-focus-within/row:pr-8 group-has-[[data-popup-open]]/row:pr-8',+ 'group-hover/row:pr-12 group-focus-within/row:pr-12 group-has-[[data-popup-open]]/row:pr-12',+ 'group-hover/row:pr-16 group-focus-within/row:pr-16 group-has-[[data-popup-open]]/row:pr-16',+ 'group-hover/row:pr-20 group-focus-within/row:pr-20 group-has-[[data-popup-open]]/row:pr-20',+ 'group-hover/row:pr-24 group-focus-within/row:pr-24 group-has-[[data-popup-open]]/row:pr-24',+ 'group-hover/row:pr-28 group-focus-within/row:pr-28 group-has-[[data-popup-open]]/row:pr-28',+] as const+interface TodaySpacesRowProps {label: stringicon: JSX.Element@@ -15,8 +27,8 @@ interface TodaySpacesRowProps {action?: JSX.Element | null/** Stays visible at the end of the row, after the hover action. */badge?: JSX.Element | null- /** How many stacked badges `badge` holds, so the label truncates before them. */- badgeCount?: 1 | 2+ /** How many icon-sized slots `badge` takes, so the label truncates before them. */+ badgeCount?: 1 | 2 | 3/** How many icon buttons `action` holds, so the label truncates before them. */actionCount?: 1 | 2unread?: boolean@@ -42,6 +54,12 @@ export function TodaySpacesRow({}: TodaySpacesRowProps): JSX.Element {const [hovered, setHovered] = useState(false)const [keyboardFocused, setKeyboardFocused] = useState(false)+ const badgeSlots = badge ? badgeCount : 0+ const actionSlots = action ? actionCount : 0+ const showUnreadDot = unread && unreadDot && !active+ // Like PostHog Desktop, a row with badges shows its unread dot after them.+ const trailingDot = showUnreadDot && !!badge+ const restSlots = badgeSlots + (trailingDot ? 1 : 0)return (<divclassName="group/row relative flex min-w-0 items-center"@@ -64,8 +82,8 @@ export function TodaySpacesRow({className={cn('min-w-0 text-xs font-medium text-foreground',active && 'bg-fill-selected',- action && !badge && (actionCount === 2 ? 'pr-12' : 'pr-8'),- badge && (badgeCount === 2 ? 'pr-16' : 'pr-12')+ TRAILING_PADDING[restSlots],+ HOVER_TRAILING_PADDING[restSlots + actionSlots])}><span className="flex size-3.5 shrink-0 items-center justify-center">{icon}</span>@@ -79,23 +97,36 @@ export function TodaySpacesRow({) : (<span className={cn('min-w-0 flex-1 truncate', unread && 'font-semibold')}>{label}</span>)}- {unread && unreadDot && !active && (- <span- role="img"- aria-label="Unread"- className="size-1.5 shrink-0 rounded-full bg-primary"- data-attr="today-unread-dot"- />+ {trailingDot ? (+ <span className="sr-only">Unread</span>+ ) : (+ showUnreadDot && (+ <span+ role="img"+ aria-label="Unread"+ className="size-1.5 shrink-0 rounded-full bg-primary"+ data-attr="today-unread-dot"+ />+ ))}</Button>{(action || badge) && (+ // Like PostHog Desktop, the badges sit at the end of the row and move left for the hover action.+ // The action stays while its menu is open, so the menu keeps its anchor after the pointer leaves.<div className="absolute right-1 flex min-w-0 items-center gap-0.5">+ {badge}+ {trailingDot && (+ <span+ aria-hidden+ className="mx-1 size-1.5 shrink-0 rounded-full bg-primary"+ data-attr="today-unread-dot"+ />+ )}{action && (- <div className="flex opacity-0 transition-opacity group-focus-within/row:opacity-100 group-hover/row:opacity-100">+ <div className="hidden group-focus-within/row:flex group-hover/row:flex group-has-[[data-popup-open]]/row:flex">{action}</div>)}- {badge}</div>)}</div>diff --git a/frontend/src/layout/today/TodaySpacesSidebar.tsx b/frontend/src/layout/today/TodaySpacesSidebar.tsxindex ecab79508410..8c3edac71dd9 100644--- a/frontend/src/layout/today/TodaySpacesSidebar.tsx+++ b/frontend/src/layout/today/TodaySpacesSidebar.tsx@@ -9,6 +9,7 @@ import { LinkPrimitive } from 'lib/lemon-ui/Link'import { urls } from 'scenes/urls'import { newSpaceLogic } from 'products/tasks/frontend/spaces/newSpaceLogic'+import { SpacePresenceAvatars } from 'products/tasks/frontend/spaces/SpacePresenceAvatars'import { TodayPaneSection, TodayPaneSectionProps } from './TodayPaneSection'import { TodayRecentFilterMenu } from './TodayRecentFilterMenu'@@ -35,6 +36,7 @@ export function TodaySpacesSidebar(): JSX.Element {collapsedSections,unreadSessionIds,unreadSpaceIds,+ spacePresence,} = useValues(todaySpacesLogic)const { loadSpaces, loadRecentTasks, toggleSection, setRecentSearchOpen, clearRecentSearchAndFilters } =useActions(todaySpacesLogic)@@ -267,27 +269,32 @@ export function TodaySpacesSidebar(): JSX.Element {loadError('Spaces didn’t load.', loadSpaces, 'today-spaces-retry')) : (<>- {visibleSpaces.map((space) => (- <TodaySpacesRow- key={space.id}- label={spaceLabel(space)}- icon={- isLockedSpace(space) ? (- <IconLock className="text-muted-foreground" />- ) : (- <span aria-hidden className="font-mono text-muted-foreground">- #- </span>- )- }- to={urls.taskSpace(space.id)}- active={location.pathname.includes(urls.taskSpace(space.id))}- dataAttr="today-space-row"- action={<TodaySpaceActions space={space} />}- actionCount={2}- unread={unreadSpaceIds.has(space.id)}- />- ))}+ {visibleSpaces.map((space) => {+ const presence = spacePresence[space.id]+ return (+ <TodaySpacesRow+ key={space.id}+ label={spaceLabel(space)}+ icon={+ isLockedSpace(space) ? (+ <IconLock className="text-muted-foreground" />+ ) : (+ <span aria-hidden className="font-mono text-muted-foreground">+ #+ </span>+ )+ }+ to={urls.taskSpace(space.id)}+ active={location.pathname.includes(urls.taskSpace(space.id))}+ dataAttr="today-space-row"+ action={<TodaySpaceActions space={space} />}+ actionCount={2}+ badge={presence ? <SpacePresenceAvatars presence={presence} /> : null}+ badgeCount={Math.min(presence?.people.length ?? 1, 3) as 1 | 2 | 3}+ unread={unreadSpaceIds.has(space.id)}+ />+ )+ })}{visibleSpaces.length <= 1 && (<Buttonvariant="outline"diff --git a/frontend/src/layout/today/todaySpacesLogic.ts b/frontend/src/layout/today/todaySpacesLogic.tsindex 457c6a32036d..b395b477529b 100644--- a/frontend/src/layout/today/todaySpacesLogic.ts+++ b/frontend/src/layout/today/todaySpacesLogic.ts@@ -28,6 +28,7 @@ import {TaskActivityReadMarkerApi,TaskListItemApi,} from 'products/tasks/frontend/generated/api.schemas'+import { SpacePresence, presenceBySpace } from 'products/tasks/frontend/spaces/spacePresence'import { pullRequestStates, sessionIdsWithPullRequests } from 'products/tasks/frontend/spaces/taskPullRequests'import {@@ -63,6 +64,10 @@ const RECENT_ITEM_LIMIT = 30const UNREAD_ACTIVITY_LIMIT = 200// The sidebar and a space scene both refresh on mount, so collapse their requests into one.const UNREAD_ACTIVITY_DEBOUNCE_MS = 100+// Like PostHog Desktop: one page of the team's newest activity across all spaces, polled slowly.+// A space whose latest activity sits below this page shows no faces.+const SPACE_PRESENCE_FETCH_LIMIT = 100+const SPACE_PRESENCE_POLL_INTERVAL_MS = 90_000export type TodayWorkSectionId = 'pinned' | 'recent' | 'spaces'@@ -142,6 +147,8 @@ export interface todaySpacesLogicValues {sectionHeights: Partial<Record<TodayWorkSectionId, number>>sortedSpaces: ChannelDTOApi[]spaceNames: Record<string, string>+ spacePresence: Record<string, SpacePresence>+ spacePresenceLoading: booleanspaces: ChannelDTOApi[]spacesLoading: booleanspacesUnavailable: boolean@@ -217,6 +224,21 @@ export interface todaySpacesLogicActions {recentTasks: TaskListItemApi[]payload?: any}+ loadSpacePresence: () => any+ loadSpacePresenceFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSpacePresenceSuccess: (+ spacePresence: Record<string, SpacePresence>,+ payload?: any+ ) => {+ spacePresence: Record<string, SpacePresence>+ payload?: any+ }loadSpaces: () => anyloadSpacesFailure: (error: string,@@ -420,6 +442,22 @@ export const todaySpacesLogic = kea<todaySpacesLogicType>([},},],+ spacePresence: [+ {} as Record<string, SpacePresence>,+ {+ loadSpacePresence: async () => {+ if (!values.currentTeamId) {+ return {}+ }+ const response = await tasksList(String(values.currentTeamId), {+ ordering: '-last_activity_at',+ basic: true,+ limit: SPACE_PRESENCE_FETCH_LIMIT,+ })+ return presenceBySpace(response.results, Date.now())+ },+ },+ ],taskActivity: [[] as TaskActivityDTOApi[],{@@ -639,9 +677,15 @@ export const todaySpacesLogic = kea<todaySpacesLogicType>([}},})),- afterMount(({ actions }) => {+ afterMount(({ actions, cache }) => {actions.loadSpaces()actions.loadPinnedTasks()actions.loadRecentTasks()+ // Setup runs now and again whenever the tab comes back, so the faces refresh on return.+ cache.disposables.add(() => {+ actions.loadSpacePresence()+ const pollTimer = window.setInterval(() => actions.loadSpacePresence(), SPACE_PRESENCE_POLL_INTERVAL_MS)+ return () => clearInterval(pollTimer)+ }, 'spacePresencePoll')}),])diff --git a/frontend/src/scenes/project-homepage/today/Today.stories.tsx b/frontend/src/scenes/project-homepage/today/Today.stories.tsxindex 0749b036adb4..6a7e3876f5b2 100644--- a/frontend/src/scenes/project-homepage/today/Today.stories.tsx+++ b/frontend/src/scenes/project-homepage/today/Today.stories.tsx@@ -75,7 +75,7 @@ const PINNED_SESSIONS = [channel: 'space-checkout',description_preview: 'The checkout test fails about once in ten runs. Find the race and make the test stable.',repository: 'example-org/webapp',- created_by: { id: 1, first_name: 'Ada', last_name: 'Lovelace', email: '[email protected]' },+ created_by: { id: 1, uuid: 'user-ada', first_name: 'Ada', last_name: 'Lovelace', email: '[email protected]' },},]@@ -95,7 +95,7 @@ const RECENT_SESSIONS = [},description_preview: 'Retry the billing webhook three times with a backoff before it reports a failure.',repository: 'example-org/webapp',- created_by: { id: 179, first_name: 'John', last_name: 'Baker', email: '[email protected]' },+ created_by: { id: 179, uuid: 'user-john', first_name: 'John', last_name: 'Baker', email: '[email protected]' },},{id: 'task-2',@@ -106,10 +106,26 @@ const RECENT_SESSIONS = [latest_run: { status: 'failed', environment: 'cloud', output: null },description_preview: 'Trial starts dropped last week. Find the step where people leave.',repository: null,- created_by: { id: 1, first_name: 'Ada', last_name: 'Lovelace', email: '[email protected]' },+ created_by: { id: 1, uuid: 'user-ada', first_name: 'Ada', last_name: 'Lovelace', email: '[email protected]' },},]+// The unfiltered team-wide page the sidebar reads presence from: a teammate is working in the space right now.+const TEAM_SESSIONS = [+ {+ id: 'task-teammate',+ channel: 'space-checkout',+ title: 'Speed up the checkout page',+ archived: false,+ last_activity_at: '2026-09-28T18:28:00Z',+ latest_run: { id: 'run-teammate', status: 'in_progress', environment: 'cloud', output: null },+ description_preview: 'The checkout page takes too long to load. Find the slow requests.',+ repository: 'example-org/webapp',+ created_by: { id: 7, uuid: 'user-grace', first_name: 'Grace', last_name: 'Hopper', email: '[email protected]' },+ },+ ...RECENT_SESSIONS,+]+const LIBRARY = [{ id: 'fs-1', path: 'Unfiled/Insights/Checkout funnel', type: 'insight', ref: 'abc123' },{ id: 'fs-2', path: 'Unfiled/Dashboards/Growth overview', type: 'dashboard', ref: '12' },@@ -203,7 +219,9 @@ const meta: Meta = {? PINNED_SESSIONS: params.get('created_by') || params.get('channel') === 'space-checkout'? RECENT_SESSIONS- : []+ : params.get('channel')+ ? []+ : TEAM_SESSIONSreturn [200, { results, count: results.length, next: null, previous: null }]},'/api/projects/:team_id/task_activity/': {diff --git a/frontend/src/styles/quill-bridge.scss b/frontend/src/styles/quill-bridge.scssindex 4f2e48f32276..f5b9786f796c 100644--- a/frontend/src/styles/quill-bridge.scss+++ b/frontend/src/styles/quill-bridge.scss@@ -244,6 +244,10 @@--tw-ring-color: var(--border);}+[data-quill] .ring-background {+ --tw-ring-color: var(--background);+}+[data-quill] .ring-ring {--tw-ring-color: var(--ring);}diff --git a/products/tasks/frontend/spaces/SpaceFeedCard.tsx b/products/tasks/frontend/spaces/SpaceFeedCard.tsxindex 498d5473b42b..a3cf4261bbde 100644--- a/products/tasks/frontend/spaces/SpaceFeedCard.tsx+++ b/products/tasks/frontend/spaces/SpaceFeedCard.tsx@@ -2,8 +2,6 @@ import { useValues } from 'kea'import { IconGitBranch } from '@posthog/icons'import {- Avatar,- AvatarFallback,Badge,Button,Card,@@ -34,6 +32,7 @@ import { spaceFeedStatus } from './spaceFeedStatus'import { SpaceFeedStatusIcon } from './SpaceFeedStatusIcon'import { TaskPullRequestChip } from './TaskPullRequestChip'import { pullRequestLabel, splitPullRequests } from './taskPullRequests'+import { TaskUserAvatar, taskUserName } from './TaskUserAvatar'interface SpaceFeedCardProps {task: TaskListItemApi@@ -53,14 +52,7 @@ export function SpaceFeedCard({ task, pinned, unread, repository }: SpaceFeedCarconst pullRequests = splitPullRequests(item.pullRequests)const preview = spaceFeedPreview('description_preview' in task ? task.description_preview : task.description)const author = task.created_by- const authorName = author ? [author.first_name, author.last_name].filter(Boolean).join(' ') || author.email : null- const initials = authorName- ? authorName- .split(/\s+/)- .slice(0, 2)- .map((part) => part[0]?.toUpperCase())- .join('')- : ''+ const authorName = author ? taskUserName(author) : nullreturn (<Card@@ -173,14 +165,18 @@ export function SpaceFeedCard({ task, pinned, unread, repository }: SpaceFeedCar</PopoverContent></Popover>)}- {authorName && (+ {author && authorName && (<Tooltip><TooltipTriggerrender={- <Avatar size="xs" className="relative ml-auto shrink-0" aria-label={authorName} />+ <span+ role="img"+ aria-label={authorName}+ className="relative ml-auto flex shrink-0"+ />}>- <AvatarFallback>{initials}</AvatarFallback>+ <TaskUserAvatar user={author} /></TooltipTrigger><TooltipContent>{authorName}</TooltipContent></Tooltip>diff --git a/products/tasks/frontend/spaces/SpacePresenceAvatars.tsx b/products/tasks/frontend/spaces/SpacePresenceAvatars.tsxnew file mode 100644index 000000000000..1cb8137e8179--- /dev/null+++ b/products/tasks/frontend/spaces/SpacePresenceAvatars.tsx@@ -0,0 +1,38 @@+import { AvatarGroup, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'++import { SpacePresence } from './spacePresence'+import { TaskUserAvatar, taskUserName } from './TaskUserAvatar'++/**+ * Who has been active in a space lately, like PostHog Desktop. A pulsing dot marks who is working right now.+ * The newest person sits on top at the right, so their dot shows; the stack tucks the others behind them.+ */+export function SpacePresenceAvatars({ presence }: { presence: SpacePresence }): JSX.Element | null {+ if (!presence.people.length) {+ return null+ }+ return (+ <AvatarGroup stacked reverse size="xs" data-attr="today-space-presence">+ {[...presence.people].reverse().map((person) => {+ const live = presence.liveUuids.includes(person.uuid)+ const label = live ? `${taskUserName(person)} is working here now` : taskUserName(person)+ return (+ <Tooltip key={person.uuid}>+ <TooltipTrigger+ render={<span role="img" aria-label={label} className="relative flex shrink-0" />}+ >+ <TaskUserAvatar user={person} />+ {live && (+ <span className="absolute right-0 bottom-0 flex size-2 items-center justify-center">+ <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>+ )}+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ )+ })}+ </AvatarGroup>+ )+}diff --git a/products/tasks/frontend/spaces/TaskUserAvatar.tsx b/products/tasks/frontend/spaces/TaskUserAvatar.tsxnew file mode 100644index 000000000000..1f84080252cc--- /dev/null+++ b/products/tasks/frontend/spaces/TaskUserAvatar.tsx@@ -0,0 +1,53 @@+import { Avatar, AvatarFallback, AvatarImage } from '@posthog/quill'++import { NUM_LETTERMARK_STYLES } from 'lib/lemon-ui/Lettermark/Lettermark'+import { inStorybookTestRunner } from 'lib/utils/dom'+import { gravatarUrl } from 'lib/utils/gravatar'++import { TaskUserBasicInfoApi } from '../generated/api.schemas'++export type TaskAvatarUser = Pick<TaskUserBasicInfoApi, 'first_name' | 'last_name' | 'email'> & {+ uuid?: string | null+}++export function taskUserName(user: TaskAvatarUser): string {+ return [user.first_name, user.last_name].filter(Boolean).join(' ') || user.email+}++function initials(name: string): string {+ return name+ .split(/\s+/)+ .slice(0, 2)+ .map((part) => part[0]?.toUpperCase())+ .join('')+}++/** PostHog Desktop's seed hash, so a person keeps the same color in both apps. */+export function avatarColorIndex(seed: string): number {+ let hash = 0+ for (let index = 0; index < seed.length; index += 1) {+ hash = (hash + seed.charCodeAt(index) * (index + 1)) % 9973+ }+ return (hash % NUM_LETTERMARK_STYLES) + 1+}++/** A person's Gravatar, or their initials on their own lettermark color. */+export function TaskUserAvatar({ user, className }: { user: TaskAvatarUser; className?: string }): JSX.Element {+ const name = taskUserName(user)+ const color = avatarColorIndex(user.uuid || user.email || name)+ return (+ <Avatar size="xs" className={className}>+ {/* A Gravatar loads at an unknown time, so snapshots keep the initials. */}+ {user.email && !inStorybookTestRunner() && <AvatarImage src={gravatarUrl(user.email)} alt={name} />}+ <AvatarFallback+ // The palette is 16 theme-independent pairs in base.scss, picked per person at runtime.+ style={{+ backgroundColor: `var(--lettermark-${color}-bg)`,+ color: `var(--lettermark-${color}-text)`,+ }}+ >+ {initials(name)}+ </AvatarFallback>+ </Avatar>+ )+}diff --git a/products/tasks/frontend/spaces/spacePresence.test.ts b/products/tasks/frontend/spaces/spacePresence.test.tsnew file mode 100644index 000000000000..fc11964a2d17--- /dev/null+++ b/products/tasks/frontend/spaces/spacePresence.test.ts@@ -0,0 +1,67 @@+import { TaskUserBasicInfoApi } from '../generated/api.schemas'+import { presenceBySpace } from './spacePresence'++const NOW = Date.parse('2026-09-28T18:30:00Z')++const person = (uuid: string): TaskUserBasicInfoApi => ({+ id: uuid.length,+ uuid,+ distinct_id: uuid,+ first_name: uuid,+ last_name: '',+ email: `${uuid}@example.com`,+})++const task = (+ author: string | null,+ minutesAgo: number,+ channel: string | null = 'space-a',+ archived = false+): Parameters<typeof presenceBySpace>[0][number] => ({+ created_by: author ? person(author) : null,+ last_activity_at: new Date(NOW - minutesAgo * 60_000).toISOString(),+ channel,+ archived,+})++describe('presenceBySpace', () => {+ test.each([+ {+ name: 'orders people newest first and marks only those active in the last 3 minutes as live',+ tasks: [task('ada', 30), task('grace', 1)],+ expected: { 'space-a': { people: ['grace', 'ada'], liveUuids: ['grace'] } },+ },+ {+ name: 'decides a person is live from their newest task, and lists them once',+ tasks: [task('ada', 50), task('ada', 2), task('ada', 10)],+ expected: { 'space-a': { people: ['ada'], liveUuids: ['ada'] } },+ },+ {+ name: 'keeps the three freshest people and never marks a dropped person live',+ tasks: [task('a', 10), task('b', 20), task('c', 30), task('d', 40), task('d', 1)],+ expected: { 'space-a': { people: ['d', 'a', 'b'], liveUuids: ['d'] } },+ },+ {+ name: 'drops activity older than two hours, archived sessions, and sessions without a space or author',+ tasks: [task('old', 121), task('gone', 1, 'space-a', true), task('loose', 1, null), task(null, 1)],+ expected: {},+ },+ {+ name: 'keeps each space separate',+ tasks: [task('ada', 5, 'space-a'), task('grace', 5, 'space-b')],+ expected: {+ 'space-a': { people: ['ada'], liveUuids: [] },+ 'space-b': { people: ['grace'], liveUuids: [] },+ },+ },+ ])('$name', ({ tasks, expected }) => {+ const result = presenceBySpace(tasks, NOW)+ const simplified = Object.fromEntries(+ Object.entries(result).map(([space, presence]) => [+ space,+ { people: presence.people.map((p) => p.uuid), liveUuids: presence.liveUuids },+ ])+ )+ expect(simplified).toEqual(expected)+ })+})diff --git a/products/tasks/frontend/spaces/spacePresence.ts b/products/tasks/frontend/spaces/spacePresence.tsnew file mode 100644index 000000000000..56f543d2a470--- /dev/null+++ b/products/tasks/frontend/spaces/spacePresence.ts@@ -0,0 +1,69 @@+import { TaskListItemApi, TaskUserBasicInfoApi } from '../generated/api.schemas'++// The same windows as PostHog Desktop, so both apps show the same faces.+/** A face pulses while its person was active this recently: work is happening now. */+export const PRESENCE_LIVE_WINDOW_MS = 3 * 60_000+/** A face stays, without the pulse, this long after its person's last activity. */+export const PRESENCE_RECENT_WINDOW_MS = 2 * 60 * 60_000+/** How many faces a space row shows, so the row stays a glance. */+export const SPACE_PRESENCE_LIMIT = 3++export type PresenceTier = 'live' | 'recent' | 'idle'++/** A future timestamp (clock skew) reads as live. */+export function presenceTier(ts: number, now: number): PresenceTier {+ const age = now - ts+ return age < PRESENCE_LIVE_WINDOW_MS ? 'live' : age < PRESENCE_RECENT_WINDOW_MS ? 'recent' : 'idle'+}++export interface SpacePresence {+ /** The recently active people, most recent first. */+ people: TaskUserBasicInfoApi[]+ /** The uuids of the people in `people` who are working right now. */+ liveUuids: string[]+}++type PresenceTask = Pick<TaskListItemApi, 'created_by' | 'last_activity_at' | 'channel' | 'archived'>++/**+ * The recently active people in each space, keyed by space id, from one page of the team's tasks.+ * A space with nobody recent has no entry.+ */+export function presenceBySpace(+ tasks: readonly PresenceTask[],+ now: number,+ limit = SPACE_PRESENCE_LIMIT+): Record<string, SpacePresence> {+ const dated = tasks+ .map((task) => ({+ space: task.channel ?? null,+ author: task.archived ? null : (task.created_by ?? null),+ ts: task.last_activity_at ? Date.parse(task.last_activity_at) : Number.NaN,+ }))+ .filter(+ (entry): entry is { space: string; author: TaskUserBasicInfoApi; ts: number } =>+ entry.space !== null && entry.author !== null && !Number.isNaN(entry.ts)+ )+ .sort((first, second) => second.ts - first.ts)++ const result: Record<string, SpacePresence> = {}+ for (const { space, author, ts } of dated) {+ const tier = presenceTier(ts, now)+ if (tier === 'idle') {+ continue+ }+ const entry = (result[space] ??= { people: [], liveUuids: [] })+ if (entry.people.some((person) => person.uuid === author.uuid)) {+ continue+ }+ if (entry.people.length >= limit) {+ continue+ }+ entry.people.push(author)+ // The list is newest first, so a person's first task decides whether they are live.+ if (tier === 'live') {+ entry.liveUuids.push(author.uuid)+ }+ }+ return result+}