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(customer-analytics): show account viewers (#97443)

Arthur Moreira de Deuse76980dbd602
diff --git a/docs/internal/customer-analytics-account-presence.md b/docs/internal/customer-analytics-account-presence.md
new file mode 100644
index 000000000000..1300c39a4ebd
--- /dev/null
+++ b/docs/internal/customer-analytics-account-presence.md
@@ -0,0 +1,13 @@
+# Account detail presence
+
+Account detail pages show avatars for other active teammates who can read the same account.
+
+The browser sends `POST /api/projects/:team_id/accounts/:account_id/presence/` when the page opens and every 30 seconds while the tab is visible. The request has no body. The server derives the viewer identity from the authenticated user.
+
+Each heartbeat updates an account-scoped Redis roster. A viewer expires after 90 seconds without another heartbeat. Hidden tabs and unmounted pages stop heartbeats, so another viewer can remain visible for up to 90 seconds after leaving.
+
+The response contains only other active viewers. Each viewer has a `user_id` and `display_name`. The response does not include email addresses. Duplicate tabs from one user appear as one viewer.
+
+The endpoint requires `account:read` and returns 404 when the caller cannot read the account. Service credentials receive an empty list and do not create presence. Redis errors also return an empty list, so presence cannot prevent the account page from loading.
+
+The frontend sequences heartbeat responses. A late response cannot replace newer viewer data.
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index d1961505051b..1eb0954ea995 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -99,6 +99,7 @@ from products.customer_analytics.backend.facade.contracts import (
from products.customer_analytics.backend.facade.email_matching import schedule_email_thread_link_recalculation
from products.customer_analytics.backend.facade.enums import AccountPropertyPinKind
from products.customer_analytics.backend.logic import (
+ account_presence as _account_presence_logic,
account_track_rules as _account_track_rules_logic,
announcements as _announcements_logic,
channel_summaries as _channel_summaries_logic,
@@ -3701,6 +3702,23 @@ def get_accessible_account_id(team_id: int, account_id: str, user_access_control
return str(account.id) if account is not None else None
+def list_account_presence_viewers(
+ team_id: int,
+ account_id: str,
+ user_access_control: "UserAccessControl",
+ user: "User",
+) -> list[contracts.AccountPresenceViewer] | None:
+ accessible_account_id = get_accessible_account_id(team_id, account_id, user_access_control)
+ if accessible_account_id is None:
+ return None
+ display_name = user.get_full_name().strip() or user.first_name.strip() or "A teammate"
+ return _account_presence_logic.heartbeat_account_presence(
+ team_id=team_id,
+ account_id=accessible_account_id,
+ viewer=contracts.AccountPresenceViewer(user_id=user.id, display_name=display_name),
+ )
+
+
def get_editable_account_id(team_id: int, account_id: str, user_access_control: "UserAccessControl") -> str | None:
"""The account_id when the caller can edit that account, else None."""
account = _resolve_accessible_account(team_id, user_access_control, account_id=account_id)
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index f5a3c2628861..018758d33ca0 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -104,6 +104,12 @@ class Account:
created_at: datetime | None
+@dataclass(frozen=True)
+class AccountPresenceViewer:
+ user_id: int
+ display_name: str
+
+
@dataclass(frozen=True)
class EmailAccountMatch:
account_id: str
diff --git a/products/customer_analytics/backend/logic/account_presence.py b/products/customer_analytics/backend/logic/account_presence.py
new file mode 100644
index 000000000000..9efc68b9178b
--- /dev/null
+++ b/products/customer_analytics/backend/logic/account_presence.py
@@ -0,0 +1,71 @@
+import json
+import time
+
+import structlog
+from redis.exceptions import RedisError
+
+from posthog.dataclasses import frozen
+from posthog.redis import get_client
+
+from products.customer_analytics.backend.facade.contracts import AccountPresenceViewer
+
+ACCOUNT_PRESENCE_TTL_SECONDS = 90
+
+logger = structlog.get_logger(__name__)
+
+
+@frozen
+class _AccountPresenceKeys:
+ roster: str
+ profile_prefix: str
+
+ def get_profile_key(self, user_id: int) -> str:
+ return f"{self.profile_prefix}:{user_id}"
+
+
+def _presence_keys(team_id: int, account_id: str) -> _AccountPresenceKeys:
+ prefix = f"customer_analytics:account_presence:{team_id}:{account_id}"
+ return _AccountPresenceKeys(roster=f"{prefix}:viewers", profile_prefix=f"{prefix}:profiles")
+
+
+def heartbeat_account_presence(
+ *, team_id: int, account_id: str, viewer: AccountPresenceViewer
+) -> list[AccountPresenceViewer]:
+ keys = _presence_keys(team_id, account_id)
+ now = time.time()
+ expires_at = now + ACCOUNT_PRESENCE_TTL_SECONDS
+
+ try:
+ redis_client = get_client()
+ pipeline = redis_client.pipeline()
+ pipeline.zadd(keys.roster, {str(viewer.user_id): expires_at})
+ pipeline.set(
+ keys.get_profile_key(viewer.user_id),
+ json.dumps({"display_name": viewer.display_name}),
+ ex=ACCOUNT_PRESENCE_TTL_SECONDS,
+ )
+ pipeline.expire(keys.roster, ACCOUNT_PRESENCE_TTL_SECONDS)
+ pipeline.zremrangebyscore(keys.roster, "-inf", now)
+ pipeline.zrangebyscore(keys.roster, now, "+inf")
+ active_user_ids = pipeline.execute()[-1]
+ profiles = redis_client.mget([keys.get_profile_key(int(user_id)) for user_id in active_user_ids])
+ except RedisError:
+ logger.warning("customer_analytics_account_presence_redis_error", exc_info=True)
+ return []
+
+ peers: list[AccountPresenceViewer] = []
+ for raw_user_id, raw_profile in zip(active_user_ids, profiles):
+ try:
+ user_id = int(raw_user_id)
+ except (TypeError, ValueError):
+ continue
+ if user_id == viewer.user_id or raw_profile is None:
+ continue
+ try:
+ profile = json.loads(raw_profile)
+ except (json.JSONDecodeError, UnicodeDecodeError):
+ continue
+ display_name = profile.get("display_name") if isinstance(profile, dict) else None
+ if isinstance(display_name, str):
+ peers.append(AccountPresenceViewer(user_id=user_id, display_name=display_name))
+ return sorted(peers, key=lambda peer: (peer.display_name.casefold(), peer.user_id))
diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.py
index ca9227a40591..94c34dbffa39 100644
--- a/products/customer_analytics/backend/presentation/views/serializers.py
+++ b/products/customer_analytics/backend/presentation/views/serializers.py
@@ -51,6 +51,7 @@ from products.customer_analytics.backend.facade.contracts import (
AccountChannelSummaryView,
AccountNotebookView,
AccountNoteView,
+ AccountPresenceViewer,
AccountRelationship,
AccountRelationshipDefinition,
AccountTableField,
@@ -1002,6 +1003,17 @@ class AccountSerializer(DataclassSerializer):
return value
+class AccountPresenceViewerSerializer(DataclassSerializer):
+ user_id = serializers.IntegerField(
+ read_only=True, help_text="PostHog user ID of the teammate viewing this account."
+ )
+ display_name = serializers.CharField(read_only=True, help_text="Display name of the teammate viewing this account.")
+
+ class Meta:
+ dataclass = AccountPresenceViewer
+ fields = ["user_id", "display_name"]
+
+
class AccountOrganizationMemberSerializer(serializers.ModelSerializer):
"""Slim organization-member representation for Customer analytics account rows."""
diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.py
index 5c056d2de374..c676c5741bd3 100644
--- a/products/customer_analytics/backend/presentation/views/views.py
+++ b/products/customer_analytics/backend/presentation/views/views.py
@@ -70,6 +70,7 @@ from products.customer_analytics.backend.presentation.views.serializers import (
AccountEmailThreadSerializer,
AccountNotebookSerializer,
AccountNoteSerializer,
+ AccountPresenceViewerSerializer,
AccountRelationshipDefinitionSerializer,
AccountRelationshipSerializer,
AccountRelationshipWriteSerializer,
@@ -1722,6 +1723,27 @@ class AccountViewSet(
raise PermissionDenied()
return Response(AccountSerializer(instance=account).data)
+ @extend_schema(
+ parameters=[_ACCOUNT_ID_PARAM],
+ request=None,
+ responses={200: AccountPresenceViewerSerializer(many=True)},
+ )
+ @action(methods=["POST"], detail=True, pagination_class=None, required_scopes=["account:read"])
+ def presence(self, request: Request, *args, **kwargs) -> Response:
+ if is_service_auth(request):
+ if api.get_account(self.team_id, self.kwargs["pk"]) is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response([])
+ viewers = api.list_account_presence_viewers(
+ self.team_id,
+ self.kwargs["pk"],
+ self.user_access_control,
+ cast(User, request.user),
+ )
+ if viewers is None:
+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)
+ return Response(AccountPresenceViewerSerializer(instance=viewers, many=True).data)
+
@extend_schema(parameters=[_ACCOUNT_ID_PARAM], responses={200: SupportTicketSerializer(many=True)})
@action(methods=["GET"], detail=True, pagination_class=None)
def support_tickets(self, request: Request, *args, **kwargs) -> Response:
diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.py
index 69458d00acb5..6a1b8b07c54f 100644
--- a/products/customer_analytics/backend/test/test_views.py
+++ b/products/customer_analytics/backend/test/test_views.py
@@ -10,6 +10,7 @@ from django.apps import apps
from django.utils import timezone
from parameterized import parameterized
+from redis.exceptions import RedisError
from rest_framework import status
from posthog.constants import AvailableFeature
@@ -551,6 +552,56 @@ class TestAccountViewSet(APIBaseTest):
self.assertEqual(data["properties"]["stripe_customer_id"], "cus_123")
self.assertEqual(data["ignored_at"], ignored_at.isoformat().replace("+00:00", "Z"))
+ def test_presence_returns_other_viewers_once_and_excludes_the_caller(self) -> None:
+ account = self._create_account()
+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ teammate.first_name = "Alex"
+ teammate.last_name = "Rivera"
+ teammate.save(update_fields=["first_name", "last_name"])
+ presence_url = f"{self.endpoint_base}{account.id}/presence/"
+
+ self.client.force_login(teammate)
+ self.assertEqual(self.client.post(presence_url, format="json").json(), [])
+ self.assertEqual(self.client.post(presence_url, format="json").json(), [])
+
+ self.client.force_login(self.user)
+ response = self.client.post(presence_url, format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ self.assertEqual(response.json(), [{"user_id": teammate.id, "display_name": "Alex Rivera"}])
+
+ @patch("products.customer_analytics.backend.logic.account_presence.time")
+ def test_presence_removes_expired_viewers(self, mock_time: MagicMock) -> None:
+ account = self._create_account()
+ teammate = User.objects.create_and_join(self.organization, "[email protected]", "testtest")
+ presence_url = f"{self.endpoint_base}{account.id}/presence/"
+ mock_time.time.side_effect = [100.0, 191.0]
+
+ self.client.force_login(teammate)
+ self.assertEqual(self.client.post(presence_url, format="json").json(), [])
+
+ self.client.force_login(self.user)
+ self.assertEqual(self.client.post(presence_url, format="json").json(), [])
+
+ def test_presence_does_not_leak_accounts_from_other_teams(self) -> None:
+ other_team = Team.objects.create(organization=self.organization)
+ other_account = Account.objects.unscoped().create(team=other_team, name="Other")
+
+ response = self.client.post(f"{self.endpoint_base}{other_account.id}/presence/", format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ @patch(
+ "products.customer_analytics.backend.logic.account_presence.get_client", side_effect=RedisError("unavailable")
+ )
+ def test_presence_redis_failure_returns_an_empty_roster(self, _get_client: MagicMock) -> None:
+ account = self._create_account()
+
+ response = self.client.post(f"{self.endpoint_base}{account.id}/presence/", format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
+ self.assertEqual(response.json(), [])
+
def test_retrieve_hides_retired_role_keys_in_stored_rows(self):
# Rows not yet cleaned by backfill_account_relationships must not leak role keys:
# the frontend read-modify-writes `properties`, and echoing them back would 400.
@@ -1599,6 +1650,23 @@ class TestCustomerAnalyticsAccessControl(APIBaseTest):
create_response = self.client.post(url, {"title": "x"}, format="json")
self.assertEqual(create_response.status_code, status.HTTP_404_NOT_FOUND)
+ def test_account_presence_404_when_object_access_denied(self) -> None:
+ AccessControl.objects.create(
+ team=self.team,
+ resource="account",
+ resource_id=str(self.account.id),
+ access_level="none",
+ organization_member=OrganizationMembership.objects.get(
+ user=self.viewer_user, organization=self.organization
+ ),
+ )
+ self._set_access_level(self.viewer_user, resource="account", access_level="viewer")
+ self.client.force_login(self.viewer_user)
+
+ response = self.client.post(f"{self.accounts_url}{self.account.id}/presence/", format="json")
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
class TestCustomPropertyDefinitionViewSet(APIBaseTest):
def setUp(self):
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 27bcff8ef53f..2b6edba6f2b5 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -149,6 +149,7 @@ Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemove
`CUSTOMER_ANALYTICS_ACCOUNT_SCENE` changes account links from inline row expansion to `CustomerAnalyticsAccountScene` at `/customer_analytics/accounts/:accountId`.
The keyed scene logic loads the account through `accountsRetrieve` when it mounts, including direct navigation between account routes.
The scene renders the account logo in `SceneTitleSection`.
+Authenticated human viewers heartbeat `accountsPresenceCreate` immediately on mount and resume, then every 30 seconds. The Redis roster and each viewer profile expire after 90 seconds, collapses tabs per user, and returns only other viewers. `AccountPresence` renders up to five initial-only avatars before the detail actions. Presence failures clear the roster without affecting account loading or capturing analytics.
`AccountSidebar` holds editable tags and the account property configuration. It sits flush with the scene's left edge and uses only a right border.
Tag edits save through `accountsPartialUpdate` and update optimistically. Only the latest save can replace or reload the account.
Pinned property preferences belong to the current user and project, never to an account. `accountSidebarConfigLogic({ projectId })` owns their load, draft, cancel, reorder, and save lifecycle through generated API functions. Keep that logic keyed by project so switching projects cannot briefly expose another project's preferences.
@@ -322,6 +323,7 @@ The seed command does not create communication data. For the Email threads tab,
- **kea, not hooks** — business logic lives in the logics above; components are thin views. The one DOM concession is the `data-account-id` anchor for scroll. Resources needing cleanup (the scroll poll) go through `cache.disposables`, never a bare `setTimeout` + `beforeUnmount`.
- **Guard network triggers against double-submission** — role assignment disables its control while saving (`isRoleSaving`); follow the same pattern for any new mutation.
- **Capture exceptions** — wrap API calls and report failures with `posthog.captureException(error, { scope: '...' })` plus a `lemonToast`.
+- **Presence is best effort** — keep it account-scoped, human-only, Redis-backed, and separate from account loading. Do not capture heartbeat analytics or send email to avatar components.
- **Tests & stories** — logics have `*.test.ts` siblings (`accountsLogic.test.ts`, etc.); `AccountsTab.stories.tsx` covers the rendered table. Add coverage alongside new behavior.
## Analytics events
diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.ts
index a896a15531e0..d8a99c4990ad 100644
--- a/products/customer_analytics/frontend/generated/api.schemas.ts
+++ b/products/customer_analytics/frontend/generated/api.schemas.ts
@@ -822,6 +822,13 @@ export interface PaginatedMeetingListApi {
results: MeetingApi[]
}
+export interface AccountPresenceViewerApi {
+ /** PostHog user ID of the teammate viewing this account. */
+ readonly user_id: number
+ /** Display name of the teammate viewing this account. */
+ readonly display_name: string
+}
+
/**
* Metadata for one message a channel summary covered — never the message text.
*/
diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.ts
index c772e4ecda4b..96eb13d71d9c 100644
--- a/products/customer_analytics/frontend/generated/api.ts
+++ b/products/customer_analytics/frontend/generated/api.ts
@@ -12,6 +12,7 @@ import type {
AccountApi,
AccountNotebookApi,
AccountNotesListParams,
+ AccountPresenceViewerApi,
AccountRelationshipApi,
AccountRelationshipDefinitionApi,
AccountRelationshipDefinitionsListParams,
@@ -798,6 +799,21 @@ export const accountsMeetingsList = async (
})
}
+export const getAccountsPresenceCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/accounts/${id}/presence/`
+}
+
+export const accountsPresenceCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<AccountPresenceViewerApi[]> => {
+ return apiMutator<AccountPresenceViewerApi[]>(getAccountsPresenceCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getAccountsSummariesListUrl = (projectId: string, id: string, params?: AccountsSummariesListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPresence.test.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPresence.test.tsx
new file mode 100644
index 000000000000..676b55757579
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPresence.test.tsx
@@ -0,0 +1,72 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import { BindLogic } from 'kea'
+
+import { initKeaTests } from '~/test/init'
+
+import { accountsPresenceCreate, accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'
+
+import { AccountPresence } from './AccountPresence'
+import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'
+
+const ACCOUNT_ID = '0190da51-0b0e-7000-8000-000000000001'
+
+jest.mock('products/customer_analytics/frontend/generated/api', () => ({
+ ...jest.requireActual('products/customer_analytics/frontend/generated/api'),
+ accountsPresenceCreate: jest.fn(),
+ accountsRetrieve: jest.fn(),
+}))
+
+const mockAccountsPresenceCreate = accountsPresenceCreate as jest.MockedFunction<typeof accountsPresenceCreate>
+const mockAccountsRetrieve = accountsRetrieve as jest.MockedFunction<typeof accountsRetrieve>
+
+describe('AccountPresence', () => {
+ const logic = customerAnalyticsAccountSceneLogic({ accountId: ACCOUNT_ID })
+
+ beforeEach(() => {
+ initKeaTests()
+ mockAccountsPresenceCreate.mockResolvedValue([])
+ mockAccountsRetrieve.mockResolvedValue({
+ id: ACCOUNT_ID,
+ name: 'Example account',
+ tags: [],
+ notebooks: [],
+ ignored_at: null,
+ created_at: '2026-01-01T00:00:00Z',
+ created_by: null,
+ updated_at: null,
+ })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ cleanup()
+ logic.unmount()
+ })
+
+ it('shows five avatars and describes overflow viewers', () => {
+ logic.actions.loadAccountPresenceSuccess([
+ { user_id: 1, display_name: 'Alex Rivera' },
+ { user_id: 2, display_name: 'Morgan Lee' },
+ { user_id: 3, display_name: 'Sam Patel' },
+ { user_id: 4, display_name: 'Jordan Kim' },
+ { user_id: 5, display_name: 'Taylor Reed' },
+ { user_id: 6, display_name: 'Casey Nguyen' },
+ ])
+
+ const { container } = render(
+ <BindLogic logic={customerAnalyticsAccountSceneLogic} props={{ accountId: ACCOUNT_ID }}>
+ <AccountPresence />
+ </BindLogic>
+ )
+
+ expect(
+ screen.getByLabelText(
+ 'Alex Rivera, Morgan Lee, Sam Patel, Jordan Kim, Taylor Reed, and 1 more are viewing this account'
+ )
+ ).toBeInTheDocument()
+ expect(container.querySelectorAll('.ProfilePicture')).toHaveLength(5)
+ expect(screen.getByText('+1')).toBeInTheDocument()
+ })
+})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPresence.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPresence.tsx
new file mode 100644
index 000000000000..430301a5fd68
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/AccountPresence.tsx
@@ -0,0 +1,57 @@
+import { useValues } from 'kea'
+
+import { ProfilePicture, Tooltip } from '@posthog/lemon-ui'
+
+import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'
+
+const MAX_PRESENCE_AVATARS = 5
+
+function formatViewerNames(names: string[]): string {
+ if (names.length === 1) {
+ return names[0] ?? ''
+ }
+ if (names.length === 2) {
+ return `${names[0]} and ${names[1]}`
+ }
+ return `${names.slice(0, -1).join(', ')}, and ${names.at(-1) ?? ''}`
+}
+
+function presenceTooltip(displayNames: string[], viewerCount: number): string {
+ const overflowCount = viewerCount - displayNames.length
+ const names =
+ overflowCount > 0 ? `${displayNames.join(', ')}, and ${overflowCount} more` : formatViewerNames(displayNames)
+ return `${names} ${viewerCount === 1 ? 'is' : 'are'} viewing this account`
+}
+
+export function AccountPresence(): JSX.Element | null {
+ const { accountPresenceViewers } = useValues(customerAnalyticsAccountSceneLogic)
+
+ if (!accountPresenceViewers.length) {
+ return null
+ }
+
+ const shownViewers = accountPresenceViewers.slice(0, MAX_PRESENCE_AVATARS)
+ const tooltip = presenceTooltip(
+ shownViewers.map((viewer) => viewer.display_name),
+ accountPresenceViewers.length
+ )
+
+ return (
+ <Tooltip title={tooltip}>
+ <div className="ProfileBubbles self-center" aria-label={tooltip}>
+ {shownViewers.map((viewer, index) => (
+ <ProfilePicture
+ key={viewer.user_id}
+ name={viewer.display_name}
+ title={viewer.display_name}
+ size="md"
+ index={index}
+ />
+ ))}
+ {accountPresenceViewers.length > shownViewers.length ? (
+ <div className="ProfileBubbles__more">+{accountPresenceViewers.length - shownViewers.length}</div>
+ ) : null}
+ </div>
+ </Tooltip>
+ )
+}
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
index 133a07078e01..4b00e540d581 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.stories.tsx
@@ -11,6 +11,7 @@ import type { CustomPropertyValueWriteApi, AccountRelationshipWriteApi } from '.
const ACCOUNT_ID = '11111111-2222-4333-8444-555555555555'
const ACCOUNT_RETRIEVE_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/'
const ACCOUNT_NOTEBOOKS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/notebooks/'
+const ACCOUNT_PRESENCE_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/presence/'
const ACCOUNT_ICON_ENDPOINT = 'api/projects/:team_id/accounts/icon/'
const VALUES_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/custom_property_values/'
const ASSIGNMENTS_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/relationships/'
@@ -77,7 +78,11 @@ const meta: Meta = {
],
pageUrl: urls.customerAnalyticsAccount(ACCOUNT_ID),
testOptions: {
- waitForSelector: ['[data-attr="customer-analytics-account-scene"]', '[data-attr="account-notes"]'],
+ waitForSelector: [
+ '[data-attr="customer-analytics-account-scene"]',
+ '[data-attr="account-notes"]',
+ '.ProfileBubbles',
+ ],
viewport: { width: 1280, height: 900 },
},
},
@@ -130,6 +135,16 @@ const meta: Meta = {
patch: {
[ACCOUNT_SIDEBAR_CONFIG_ENDPOINT]: async ({ request }) => [200, await request.json()],
},
+ post: {
+ [ACCOUNT_PRESENCE_ENDPOINT]: [
+ { user_id: 1, display_name: 'Alex Rivera' },
+ { user_id: 2, display_name: 'Morgan Lee' },
+ { user_id: 3, display_name: 'Sam Patel' },
+ { user_id: 4, display_name: 'Jordan Kim' },
+ { user_id: 5, display_name: 'Taylor Reed' },
+ { user_id: 6, display_name: 'Casey Nguyen' },
+ ],
+ },
}),
],
}
@@ -145,7 +160,7 @@ export const Narrow: Story = {
render: () => <App />,
parameters: {
testOptions: {
- waitForSelector: '[data-attr="customer-analytics-account-scene"]',
+ waitForSelector: ['[data-attr="customer-analytics-account-scene"]', '.ProfileBubbles'],
viewport: { width: 800, height: 900 },
},
},
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx
index d06ca494cb57..b763b00b6370 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/CustomerAnalyticsAccountScene.tsx
@@ -19,6 +19,7 @@ import { CustomerAnalyticsScene } from '../../CustomerAnalyticsScene'
import { customerAnalyticsFeaturePreviewGate } from '../../featurePreviewGate'
import type { AccountApi } from '../../generated/api.schemas'
import { AccountDetailActions } from './AccountDetailActions'
+import { AccountPresence } from './AccountPresence'
import { AccountSidebar } from './AccountSidebar'
import {
CustomerAnalyticsAccountSceneLogicProps,
@@ -96,7 +97,12 @@ function CustomerAnalyticsAccountSceneContent(): JSX.Element {
type: 'cohort',
forceIcon: <AccountLogo domain={getAccountLogoDomain(account)} name={account.name} />,
}}
- actions={<AccountDetailActions />}
+ actions={
+ <>
+ <AccountPresence />
+ <AccountDetailActions />
+ </>
+ }
/>
<SceneDivider />
<div className="@container/account-detail flex flex-1 min-h-0 overflow-y-auto @min-[60rem]:-mt-4 @min-[60rem]:-ml-4">
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
index a4d9e051cca0..8fd58313718c 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.test.ts
@@ -10,18 +10,24 @@ import { urls } from 'scenes/urls'
import { initKeaTests } from '~/test/init'
import { AccountsEvents } from 'products/customer_analytics/frontend/components/Accounts/constants'
-import { accountsPartialUpdate, accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'
-import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import {
+ accountsPartialUpdate,
+ accountsPresenceCreate,
+ accountsRetrieve,
+} from 'products/customer_analytics/frontend/generated/api'
+import type { AccountApi, AccountPresenceViewerApi } from 'products/customer_analytics/frontend/generated/api.schemas'
import { customerAnalyticsAccountSceneLogic } from './customerAnalyticsAccountSceneLogic'
jest.mock('products/customer_analytics/frontend/generated/api', () => ({
...jest.requireActual('products/customer_analytics/frontend/generated/api'),
accountsPartialUpdate: jest.fn(),
+ accountsPresenceCreate: jest.fn(),
accountsRetrieve: jest.fn(),
}))
const mockAccountsPartialUpdate = accountsPartialUpdate as jest.MockedFunction<typeof accountsPartialUpdate>
+const mockAccountsPresenceCreate = accountsPresenceCreate as jest.MockedFunction<typeof accountsPresenceCreate>
const mockAccountsRetrieve = accountsRetrieve as jest.MockedFunction<typeof accountsRetrieve>
const ACCOUNT_ID = '0190da51-0b0e-7000-8000-000000000001'
@@ -58,7 +64,9 @@ describe('customerAnalyticsAccountSceneLogic', () => {
beforeEach(() => {
initKeaTests()
+ jest.useRealTimers()
jest.resetAllMocks()
+ mockAccountsPresenceCreate.mockResolvedValue([])
featureFlagLogic.mount()
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.CUSTOMER_ANALYTICS_CSP]: true,
@@ -74,6 +82,7 @@ describe('customerAnalyticsAccountSceneLogic', () => {
}
afterEach(() => {
+ jest.useRealTimers()
logic.unmount()
featureFlagLogic.unmount()
})
@@ -89,6 +98,71 @@ describe('customerAnalyticsAccountSceneLogic', () => {
expect(logic.values.breadcrumbs.at(-1)?.name).toBe(account.name)
})
+ it('heartbeats account presence immediately, polls every 30 seconds, and clears it on failure', async () => {
+ jest.useFakeTimers()
+ const captureException = jest.spyOn(posthog, 'captureException')
+ const viewers: AccountPresenceViewerApi[] = [{ user_id: 2, display_name: 'Alex Rivera' }]
+ mockAccountsRetrieve.mockResolvedValue(account)
+ mockAccountsPresenceCreate.mockResolvedValueOnce(viewers).mockRejectedValueOnce(new Error('Unavailable'))
+
+ try {
+ mountLogic()
+ await Promise.resolve()
+ await Promise.resolve()
+
+ expect(mockAccountsPresenceCreate).toHaveBeenCalledWith(String(logic.values.currentTeamId), ACCOUNT_ID)
+ expect(logic.values.accountPresenceViewers).toEqual(viewers)
+
+ jest.advanceTimersByTime(30_000)
+ await Promise.resolve()
+ await Promise.resolve()
+
+ expect(mockAccountsPresenceCreate).toHaveBeenCalledTimes(2)
+ expect(logic.values.accountPresenceViewers).toEqual([])
+ expect(logic.values.accountPresenceError).toBeInstanceOf(Error)
+ expect(captureException).not.toHaveBeenCalled()
+
+ logic.unmount()
+ jest.advanceTimersByTime(30_000)
+ expect(mockAccountsPresenceCreate).toHaveBeenCalledTimes(2)
+ } finally {
+ jest.useRealTimers()
+ }
+ })
+
+ it('keeps the latest presence response when an earlier request resolves later', async () => {
+ const staleRequest = createDeferred<AccountPresenceViewerApi[]>()
+ const latestRequest = createDeferred<AccountPresenceViewerApi[]>()
+ const staleRequestStarted = createDeferred<void>()
+ const latestRequestStarted = createDeferred<void>()
+ const latestViewers: AccountPresenceViewerApi[] = [{ user_id: 3, display_name: 'Sam Patel' }]
+ mockAccountsRetrieve.mockResolvedValue(account)
+ mockAccountsPresenceCreate
+ .mockImplementationOnce(() => {
+ staleRequestStarted.resolve()
+ return staleRequest.promise
+ })
+ .mockImplementationOnce(() => {
+ latestRequestStarted.resolve()
+ return latestRequest.promise
+ })
+
+ mountLogic()
+ await staleRequestStarted.promise
+ logic.actions.loadAccountPresence()
+ await latestRequestStarted.promise
+
+ latestRequest.resolve(latestViewers)
+ await Promise.resolve()
+ await Promise.resolve()
+ staleRequest.reject(new Error('Unavailable'))
+ await Promise.resolve()
+ await Promise.resolve()
+
+ expect(logic.values.accountPresenceViewers).toEqual(latestViewers)
+ expect(logic.values.accountPresenceError).toBeNull()
+ })
+
it('classifies a missing account without reporting an exception', async () => {
const captureException = jest.spyOn(posthog, 'captureException')
mockAccountsRetrieve.mockRejectedValue(new ApiError('Not found', 404))
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
index f0f13fca8bb1..2d73cd6af929 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/customerAnalyticsAccountSceneLogic.ts
@@ -31,8 +31,14 @@ import {
getVisibleAccountExpansionTab,
} from 'products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic'
import { AccountsEvents } from 'products/customer_analytics/frontend/components/Accounts/constants'
-import { accountsPartialUpdate, accountsRetrieve } from 'products/customer_analytics/frontend/generated/api'
-import type { AccountApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+import {
+ accountsPartialUpdate,
+ accountsPresenceCreate,
+ accountsRetrieve,
+} from 'products/customer_analytics/frontend/generated/api'
+import type { AccountApi, AccountPresenceViewerApi } from 'products/customer_analytics/frontend/generated/api.schemas'
+
+const ACCOUNT_PRESENCE_POLL_INTERVAL_MS = 30_000
export interface CustomerAnalyticsAccountSceneLogicProps {
accountId: string
@@ -49,6 +55,8 @@ export interface customerAnalyticsAccountSceneLogicValues {
account: AccountApi | null
accountLoadError: unknown
accountLoading: boolean
+ accountPresenceError: unknown
+ accountPresenceViewers: AccountPresenceViewerApi[]
activeTab: AccountExpansionTab
breadcrumbs: Breadcrumb[]
isAccountMissing: boolean
@@ -64,6 +72,15 @@ export interface customerAnalyticsAccountSceneLogicActions {
loadAccountFailure: (error: unknown) => {
error: unknown
}
+ loadAccountPresence: () => {
+ value: true
+ }
+ loadAccountPresenceFailure: (error: unknown) => {
+ error: unknown
+ }
+ loadAccountPresenceSuccess: (viewers: AccountPresenceViewerApi[]) => {
+ viewers: AccountPresenceViewerApi[]
+ }
loadAccountSuccess: (account: AccountApi) => {
account: AccountApi
}
@@ -117,6 +134,9 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
loadAccount: true,
loadAccountSuccess: (account: AccountApi) => ({ account }),
loadAccountFailure: (error: unknown) => ({ error }),
+ loadAccountPresence: true,
+ loadAccountPresenceSuccess: (viewers: AccountPresenceViewerApi[]) => ({ viewers }),
+ loadAccountPresenceFailure: (error: unknown) => ({ error }),
setActiveTab: (tab: AccountExpansionTab) => ({ tab }),
restoreActiveTab: (tab: string | undefined) => ({ tab: tab ?? DEFAULT_ACCOUNT_TAB }),
updateTags: (tags: string[]) => ({ tags }),
@@ -147,6 +167,21 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
loadAccountFailure: (_, { error }) => error,
},
],
+ accountPresenceViewers: [
+ [] as AccountPresenceViewerApi[],
+ {
+ loadAccountPresenceSuccess: (_, { viewers }) => viewers,
+ loadAccountPresenceFailure: () => [],
+ },
+ ],
+ accountPresenceError: [
+ null as unknown,
+ {
+ loadAccountPresence: () => null,
+ loadAccountPresenceSuccess: () => null,
+ loadAccountPresenceFailure: (_, { error }) => error,
+ },
+ ],
requestedTab: [
DEFAULT_ACCOUNT_TAB as string,
{
@@ -190,7 +225,7 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
],
],
}),
- listeners(({ actions, props, values }) => ({
+ listeners(({ actions, cache, props, values }) => ({
loadAccount: async () => {
try {
actions.loadAccountSuccess(await accountsRetrieve(String(values.currentTeamId), props.accountId))
@@ -206,6 +241,20 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
scope: 'customerAnalyticsAccountSceneLogic.loadAccount',
})
},
+ loadAccountPresence: async () => {
+ cache.accountPresenceRequestSequence = (cache.accountPresenceRequestSequence ?? 0) + 1
+ const requestSequence = cache.accountPresenceRequestSequence
+ try {
+ const viewers = await accountsPresenceCreate(String(values.currentTeamId), props.accountId)
+ if (requestSequence === cache.accountPresenceRequestSequence) {
+ actions.loadAccountPresenceSuccess(viewers)
+ }
+ } catch (error) {
+ if (requestSequence === cache.accountPresenceRequestSequence) {
+ actions.loadAccountPresenceFailure(error)
+ }
+ }
+ },
setActiveTab: ({ tab }) => {
posthog.capture(AccountsEvents.TabViewed, { tab })
},
@@ -246,7 +295,15 @@ export const customerAnalyticsAccountSceneLogic = kea<customerAnalyticsAccountSc
actions.restoreActiveTab(DEFAULT_ACCOUNT_TAB)
},
})),
- afterMount(({ actions }) => {
+ afterMount(({ actions, cache }) => {
actions.loadAccount()
+ cache.disposables.add(() => {
+ actions.loadAccountPresence()
+ const intervalId = window.setInterval(
+ () => actions.loadAccountPresence(),
+ ACCOUNT_PRESENCE_POLL_INTERVAL_MS
+ )
+ return () => window.clearInterval(intervalId)
+ }, 'accountPresencePolling')
}),
])
diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yaml
index 02a7112b9de8..968ce31539c6 100644
--- a/products/customer_analytics/mcp/tools.yaml
+++ b/products/customer_analytics/mcp/tools.yaml
@@ -347,6 +347,9 @@ tools:
Tag names to set on the account. Replaces the full existing tag set — pass the complete list, not a
delta. Tags are created on demand if they do not already exist for the team.
feature_flag: customer-analytics-csp
+ accounts-presence-create:
+ operation: accounts_presence_create
+ enabled: false
accounts-relationships-create:
operation: accounts_relationships_create
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 735c1a262ed3..f91c97234585 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -872,6 +872,13 @@ export namespace Schemas {
readonly last_modified_by: UserBasic;
}
+ export interface AccountPresenceViewer {
+ /** PostHog user ID of the teammate viewing this account. */
+ readonly user_id: number;
+ /** Display name of the teammate viewing this account. */
+ readonly display_name: string;
+ }
+
/**
* A team-defined account relationship type (CSM, Onboarding manager, ...).
*/