: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(customer-analytics): show account list presence (#106304)
Arthur Moreira de Deus57eaf23e18f2
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex 5ea0b53a8f79..74c1fa2b8991 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -3877,6 +3877,32 @@ def list_account_presence_viewers()+def list_accounts_presence(+ team_id: int,+ account_ids: list[str],+ user_access_control: "UserAccessControl",+ *,+ viewer_user_id: int | None,+) -> list[contracts.AccountPresence]:+ accessible_account_ids = list(+ user_access_control.filter_queryset_by_access_level(+ Account.objects.unscoped().filter(team_id=team_id, id__in=account_ids)+ ).values_list("id", flat=True)+ )+ viewers_by_account_id = _account_presence_logic.list_account_presence(+ team_id=team_id, account_ids=[str(account_id) for account_id in accessible_account_ids]+ )+ return [+ contracts.AccountPresence(+ account_id=account_id,+ viewers=[+ viewer for viewer in viewers_by_account_id.get(str(account_id), []) if viewer.user_id != viewer_user_id+ ],+ )+ for account_id in accessible_account_ids+ ]++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.pyindex 7696646a7710..6bb99d0adf94 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -132,6 +132,12 @@ class AccountPresenceViewer:display_name: str+@dataclass(frozen=True)+class AccountPresence:+ account_id: UUID+ viewers: list[AccountPresenceViewer]++@dataclass(frozen=True)class EmailAccountMatch:account_id: strdiff --git a/products/customer_analytics/backend/logic/account_presence.py b/products/customer_analytics/backend/logic/account_presence.pyindex 9efc68b9178b..04f73bff6239 100644--- a/products/customer_analytics/backend/logic/account_presence.py+++ b/products/customer_analytics/backend/logic/account_presence.py@@ -69,3 +69,52 @@ def heartbeat_account_presence(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))+++def list_account_presence(*, team_id: int, account_ids: list[str]) -> dict[str, list[AccountPresenceViewer]]:+ if not account_ids:+ return {}++ now = time.time()+ keys_by_account_id = {account_id: _presence_keys(team_id, account_id) for account_id in account_ids}+ try:+ redis_client = get_client()+ pipeline = redis_client.pipeline()+ for keys in keys_by_account_id.values():+ pipeline.zremrangebyscore(keys.roster, "-inf", now)+ pipeline.zrangebyscore(keys.roster, now, "+inf")+ results = pipeline.execute()+ active_user_ids_by_account_id = {+ account_id: active_user_ids+ for (account_id, _), active_user_ids in zip(keys_by_account_id.items(), results[1::2])+ }+ profile_locations: list[tuple[str, int]] = []+ for account_id, active_user_ids in active_user_ids_by_account_id.items():+ for user_id in active_user_ids:+ try:+ profile_locations.append((account_id, int(user_id)))+ except (TypeError, ValueError):+ continue+ profiles = redis_client.mget(+ [keys_by_account_id[account_id].get_profile_key(user_id) for account_id, user_id in profile_locations]+ )+ except RedisError:+ logger.warning("customer_analytics_account_presence_redis_error", exc_info=True)+ return {}++ viewers_by_account_id: dict[str, list[AccountPresenceViewer]] = {account_id: [] for account_id in account_ids}+ for (account_id, user_id), raw_profile in zip(profile_locations, profiles):+ if 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):+ viewers_by_account_id[account_id].append(AccountPresenceViewer(user_id=user_id, display_name=display_name))++ return {+ account_id: sorted(viewers, key=lambda viewer: (viewer.display_name.casefold(), viewer.user_id))+ for account_id, viewers in viewers_by_account_id.items()+ }diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex 65bcfb710a67..218d514d8f16 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -52,6 +52,7 @@ from products.customer_analytics.backend.facade.contracts import (AccountChannelSummaryView,AccountNotebookView,AccountNoteView,+ AccountPresence,AccountPresenceViewer,AccountRelationship,AccountRelationshipDefinition,@@ -1091,6 +1092,23 @@ class AccountPresenceViewerSerializer(DataclassSerializer):fields = ["user_id", "display_name"]+class AccountPresenceListRequestSerializer(serializers.Serializer):+ account_ids = serializers.ListField(+ child=serializers.UUIDField(),+ max_length=100,+ help_text="Up to 100 account IDs to read presence for.",+ )+++class AccountPresenceSerializer(DataclassSerializer):+ account_id = serializers.UUIDField(read_only=True, help_text="Customer analytics account ID.")+ viewers = AccountPresenceViewerSerializer(many=True, read_only=True, help_text="People viewing this account.")++ class Meta:+ dataclass = AccountPresence+ fields = ["account_id", "viewers"]++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.pyindex aac49d557516..87b602d7cbfe 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -71,6 +71,8 @@ from products.customer_analytics.backend.presentation.views.serializers import (AccountEmailThreadSerializer,AccountNotebookSerializer,AccountNoteSerializer,+ AccountPresenceListRequestSerializer,+ AccountPresenceSerializer,AccountPresenceViewerSerializer,AccountRelationshipDefinitionSerializer,AccountRelationshipSerializer,@@ -1869,6 +1871,28 @@ class AccountViewSet(return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)return Response(AccountPresenceViewerSerializer(instance=viewers, many=True).data)+ @validated_request(+ request_serializer=AccountPresenceListRequestSerializer,+ operation_id="accounts_presence_list",+ responses={200: AccountPresenceSerializer(many=True)},+ )+ @action(+ methods=["POST"],+ detail=False,+ pagination_class=None,+ required_scopes=["account:read"],+ )+ def presence_list(self, request: ValidatedRequest, *args: object, **kwargs: object) -> Response:+ account_ids = [str(account_id) for account_id in request.validated_data["account_ids"]]+ viewer_user_id = None if is_service_auth(request) else cast(User, request.user).id+ presence = api.list_accounts_presence(+ self.team_id,+ account_ids,+ self.user_access_control,+ viewer_user_id=viewer_user_id,+ )+ return Response(AccountPresenceSerializer(instance=presence, 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.pyindex 8ca4e45004b0..dd70c93b41de 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -661,6 +661,43 @@ class TestAccountViewSet(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())self.assertEqual(response.json(), [{"user_id": teammate.id, "display_name": "Alex Rivera"}])+ def test_presence_list_returns_viewers_for_requested_accessible_accounts(self) -> None:+ first_account = self._create_account(name="First account")+ second_account = self._create_account(name="Second 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"])++ self.client.force_login(teammate)+ self.client.post(f"{self.endpoint_base}{first_account.id}/presence/", format="json")+ self.client.post(f"{self.endpoint_base}{second_account.id}/presence/", format="json")++ self.client.force_login(self.user)+ expected_teammate = [{"user_id": teammate.id, "display_name": "Alex Rivera"}]+ self.assertEqual(+ self.client.post(f"{self.endpoint_base}{first_account.id}/presence/", format="json").json(),+ expected_teammate,+ )+ self.assertEqual(+ self.client.post(f"{self.endpoint_base}{second_account.id}/presence/", format="json").json(),+ expected_teammate,+ )+ response = self.client.post(+ f"{self.endpoint_base}presence_list/",+ {"account_ids": [str(first_account.id), str(second_account.id)]},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())+ self.assertEqual(+ {item["account_id"]: item["viewers"] for item in response.json()},+ {+ str(first_account.id): expected_teammate,+ str(second_account.id): expected_teammate,+ },+ )+@patch("products.customer_analytics.backend.logic.account_presence.time")def test_presence_removes_expired_viewers(self, mock_time: MagicMock) -> None:account = self._create_account()diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex 85a97e9940ef..a503b709ccfe 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -156,7 +156,7 @@ Sort safety: removing the current or pinned server-sorted column drops that sort`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.+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. The Accounts list batches teammate presence for its loaded rows, excludes the current viewer, and refreshes every 30 seconds through `cache.disposables`, including immediately after a hidden tab resumes. Empty results invalidate in-flight presence requests before clearing the avatars. `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.diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsxindex 296b0a5d46ae..70bf476da671 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTable.tsx@@ -93,6 +93,7 @@ function parseAssignedUserIds(value: unknown): number[] {}function NameCell({ record }: { record: unknown }): JSX.Element {+ const { accountPresenceByAccountId } = useValues(accountsLogic)const cell = getNameCell(record)return (<AccountsTableNameCell@@ -100,6 +101,7 @@ function NameCell({ record }: { record: unknown }): JSX.Element {name={cell?.name ?? ''}externalId={cell?.external_id}logoDomain={cell?.logo_domain}+ viewers={cell?.id ? (accountPresenceByAccountId[cell.id] ?? []) : []}/>)}diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.test.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.test.tsxindex cec39eadaaff..b02f595b9b82 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.test.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.test.tsx@@ -35,7 +35,7 @@ describe('AccountsTableNameCell', () => {render(<Provider>- <AccountsTableNameCell accountId={ACCOUNT_ID} name="Test account" />+ <AccountsTableNameCell accountId={ACCOUNT_ID} name="Test account" viewers={[]} /></Provider>)@@ -51,7 +51,7 @@ describe('AccountsTableNameCell', () => {render(<Provider>- <AccountsTableNameCell accountId={ACCOUNT_ID} name="Test account" />+ <AccountsTableNameCell accountId={ACCOUNT_ID} name="Test account" viewers={[]} /></Provider>)@@ -66,7 +66,7 @@ describe('AccountsTableNameCell', () => {render(<Provider>- <AccountsTableNameCell accountId={ACCOUNT_ID} name="Test account" />+ <AccountsTableNameCell accountId={ACCOUNT_ID} name="Test account" viewers={[]} /></Provider>)@@ -80,4 +80,28 @@ describe('AccountsTableNameCell', () => {expect(accountsExpansionLogic.values.isAccountExpanded(ACCOUNT_ID)).toBe(false)expect(posthog.capture).toHaveBeenCalledWith(AccountsEvents.AccountOpened)})++ it('shows three viewer indicators and names every viewer in the hover label', () => {+ featureFlagLogic.actions.setFeatureFlags([], {})++ render(+ <Provider>+ <AccountsTableNameCell+ accountId={ACCOUNT_ID}+ name="Test account"+ viewers={[+ { 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' },+ ]}+ />+ </Provider>+ )++ expect(+ screen.getByLabelText('Alex Rivera, Morgan Lee, Sam Patel, and Jordan Kim are viewing this account')+ ).toBeVisible()+ expect(screen.getByText('+1')).toBeVisible()+ })})diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.tsxindex 6b6920f93be9..02a8303ec47b 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTableNameCell.tsx@@ -2,9 +2,13 @@ import { useActions, useValues } from 'kea'import posthog from 'posthog-js'import type { MouseEventHandler } from 'react'+import { ProfilePicture, Tooltip } from '@posthog/lemon-ui'+import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import type { AccountPresenceViewerApi } from 'products/customer_analytics/frontend/generated/api.schemas'+import { AccountNameCell } from './AccountNameCell'import { accountsExpansionLogic } from './accountsExpansionLogic'import { AccountsEvents } from './constants'@@ -14,6 +18,19 @@ export interface AccountsTableNameCellProps {externalId?: string | nulllogoDomain?: string | nullname: string+ viewers: AccountPresenceViewerApi[]+}++const MAX_PRESENCE_AVATARS = 3++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) ?? ''}`}export function AccountsTableNameCell({@@ -21,6 +38,7 @@ export function AccountsTableNameCell({externalId,logoDomain,name,+ viewers,}: AccountsTableNameCellProps): JSX.Element {const { featureFlags } = useValues(featureFlagLogic)const { isAccountExpanded } = useValues(accountsExpansionLogic)@@ -45,13 +63,38 @@ export function AccountsTableNameCell({toggleAccountExpanded(accountId)}+ const shownViewers = viewers.slice(0, MAX_PRESENCE_AVATARS)+ const tooltip = `${formatViewerNames(viewers.map((viewer) => viewer.display_name))} ${+ viewers.length === 1 ? 'is' : 'are'+ } viewing this account`+return (- <AccountNameCell- accountId={accountId}- name={name}- externalId={externalId}- logoDomain={logoDomain}- onClick={handleClick}- />+ <div className="flex items-center gap-2">+ <AccountNameCell+ accountId={accountId}+ name={name}+ externalId={externalId}+ logoDomain={logoDomain}+ onClick={handleClick}+ />+ {shownViewers.length ? (+ <Tooltip title={tooltip}>+ <div className="ProfileBubbles shrink-0" aria-label={tooltip}>+ {shownViewers.map((viewer, index) => (+ <ProfilePicture+ key={viewer.user_id}+ name={viewer.display_name}+ title={viewer.display_name}+ size="sm"+ index={index}+ />+ ))}+ {viewers.length > shownViewers.length ? (+ <div className="ProfileBubbles__more">+{viewers.length - shownViewers.length}</div>+ ) : null}+ </div>+ </Tooltip>+ ) : null}+ </div>)}diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.tsindex 05f81046fb89..e752f9a44c6a 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.test.ts@@ -27,6 +27,7 @@ import {accountRelationshipDefinitionsList,accountsCustomPropertyValuesCreate,accountsPartialUpdate,+ accountsPresenceList,accountsRelationshipsCreate,accountsRelationshipsEndCreate,accountsRelationshipsList,@@ -34,6 +35,7 @@ import {} from 'products/customer_analytics/frontend/generated/api'import type {AccountApi,+ AccountPresenceApi,AccountRelationshipApi,AccountRelationshipDefinitionApi,CustomPropertyDefinitionApi,@@ -49,7 +51,13 @@ import {relationshipAlias,} from './accountsColumnConfigLogic'import { DEFAULT_ACCOUNT_TAB, accountsExpansionLogic } from './accountsExpansionLogic'-import { accountsLogic, customPropertySavingKey, savingRoleKey, SEARCH_DEBOUNCE_MS } from './accountsLogic'+import {+ ACCOUNT_PRESENCE_REFRESH_INTERVAL_MS,+ accountsLogic,+ customPropertySavingKey,+ savingRoleKey,+ SEARCH_DEBOUNCE_MS,+} from './accountsLogic'import { accountsOverviewTilesLogic } from './accountsOverviewTilesLogic'import { readAccountsViewDraft, writeAccountsViewDraft } from './accountsViewState'import { AccountsEvents, DEFAULT_TILES } from './constants'@@ -65,6 +73,7 @@ jest.mock('products/customer_analytics/frontend/generated/api', () => ({customPropertyDefinitionsList: jest.fn(),accountsCustomPropertyValuesCreate: jest.fn(),accountsPartialUpdate: jest.fn(),+ accountsPresenceList: jest.fn(),accountsRelationshipsCreate: jest.fn(),accountsRelationshipsEndCreate: jest.fn(),accountsRelationshipsList: jest.fn(),@@ -85,6 +94,7 @@ const mockCustomPropertyValuesCreate = accountsCustomPropertyValuesCreate as jestypeof accountsCustomPropertyValuesCreate>const mockPartialUpdate = accountsPartialUpdate as jest.MockedFunction<typeof accountsPartialUpdate>+const mockAccountsPresenceList = accountsPresenceList as jest.MockedFunction<typeof accountsPresenceList>const CSM_DEFINITION_ID = '11111111-2222-3333-4444-555555555555'const AE_DEFINITION_ID = '66666666-7777-8888-9999-aaaaaaaaaaaa'@@ -680,6 +690,69 @@ describe('accountsLogic', () => {})})+ describe('account presence', () => {+ const responseWithAccount = (): AccountsTableQueryResponse => ({+ kind: NodeKind.AccountsTableQuery,+ results: [+ {+ id: ACCOUNT_ID,+ name: 'Acme',+ accountFields: {},+ relationships: {},+ customProperties: {},+ customPropertyHistory: {},+ noteCount: 0,+ },+ ],+ hasMore: false,+ limit: 100,+ offset: 0,+ })+ const responsePayload = {+ overrideQuery: undefined,+ pollOnly: true,+ queryId: 'presence-request',+ refresh: undefined,+ }++ it('refreshes presence while account rows remain loaded', async () => {+ jest.useFakeTimers()+ mockAccountsPresenceList.mockResolvedValue([+ { account_id: ACCOUNT_ID, viewers: [{ user_id: 1, display_name: 'Alex Rivera' }] },+ ])++ await expectLogic(logic, () => {+ logic.actions.listLoadDataSuccess(responseWithAccount(), responsePayload)+ }).toFinishAllListeners()++ expect(logic.values.accountPresenceByAccountId[ACCOUNT_ID]).toHaveLength(1)++ mockAccountsPresenceList.mockResolvedValue([])+ await jest.advanceTimersByTimeAsync(ACCOUNT_PRESENCE_REFRESH_INTERVAL_MS)+ await expectLogic(logic).toFinishAllListeners()++ expect(mockAccountsPresenceList).toHaveBeenCalledTimes(2)+ expect(logic.values.accountPresenceByAccountId).toEqual({})+ })++ it('ignores an in-flight response after the account list becomes empty', async () => {+ let resolvePresence!: (presence: AccountPresenceApi[]) => void+ mockAccountsPresenceList.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolvePresence = resolve+ })+ )++ logic.actions.loadAccountPresence([ACCOUNT_ID])+ logic.actions.loadAccountPresence([])+ resolvePresence([{ account_id: ACCOUNT_ID, viewers: [{ user_id: 1, display_name: 'Alex Rivera' }] }])+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.accountPresenceByAccountId).toEqual({})+ })+ })+describe('sortOrder', () => {const response = (hasMore: boolean): AccountsTableQueryResponse => ({kind: NodeKind.AccountsTableQuery,diff --git a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsLogic.tsindex 96ec126016ec..e2ae88171a5e 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsLogic.ts@@ -31,6 +31,7 @@ import type { UserBasicType } from '~/types'import {accountsCustomPropertyValuesCreate,accountsPartialUpdate,+ accountsPresenceList,accountsRelationshipsCreate,accountsRelationshipsEndCreate,accountsRelationshipsList,@@ -44,6 +45,8 @@ import {} from '../../constants'import { customerAnalyticsSceneLogic } from '../../customerAnalyticsSceneLogic'import type {+ AccountPresenceApi,+ AccountPresenceViewerApi,AccountRelationshipDefinitionApi,CustomPropertyDefinitionApi,CustomPropertyValueWriteApi,@@ -81,6 +84,9 @@ export const SEARCH_DEBOUNCE_MS = 300// Debounce tag edits because ObjectTags emits each addition and removal separately.export const TAGS_SAVE_DEBOUNCE_MS = 300+export const ACCOUNT_PRESENCE_REFRESH_INTERVAL_MS = 30_000++type AccountPresenceResponse = AccountPresenceApi[]// Wait for refetched rows before scrolling to an account.const SCROLL_TO_ACCOUNT_POLL_MS = 100@@ -282,6 +288,7 @@ export interface accountsLogicValues {user: UserType | null // userLogicaccountFilters: AccountFilter[]accountIdFilter: string | null+ accountPresenceByAccountId: Record<string, AccountPresenceViewerApi[]>accountsDataTableQuery: DataTableNodeaccountsQuerySource: AccountsTableQuery | nullaccountsTableQueryPlan: AccountsTableQueryPlan@@ -486,6 +493,15 @@ export interface accountsLogicActions {accountId: stringdefinitionId: string}+ loadAccountPresence: (accountIds: string[]) => {+ accountIds: string[]+ }+ loadAccountPresenceFailure: () => {+ value: true+ }+ loadAccountPresenceSuccess: (presence: AccountPresenceResponse) => {+ presence: AccountPresenceResponse+ }openAccount: (accountId: string,externalId: string | null,@@ -823,6 +839,9 @@ export const accountsLogic = kea<accountsLogicType>([completeness: Exclude<AccountListDataCompleteness, 'unknown'>,serverSortOrder: AccountSortOrder) => ({ datasetKey, completeness, serverSortOrder }),+ loadAccountPresence: (accountIds: string[]) => ({ accountIds }),+ loadAccountPresenceSuccess: (presence: AccountPresenceResponse) => ({ presence }),+ loadAccountPresenceFailure: true,toggleSort: (column: AccountSortableColumn) => ({ column }),refresh: true,restoreViewStateFromRoute: (method?: 'POP' | 'PUSH' | 'REPLACE') => ({ method }),@@ -947,6 +966,15 @@ export const accountsLogic = kea<accountsLogicType>([}),},],++ accountPresenceByAccountId: [+ {} as Record<string, AccountPresenceViewerApi[]>,+ {+ loadAccountPresenceSuccess: (_, { presence }) =>+ Object.fromEntries(presence.map(({ account_id, viewers }) => [account_id, [...viewers]])),+ loadAccountPresenceFailure: () => ({}),+ },+ ],savingCustomProperties: [{} as Record<string, true>,{@@ -1442,6 +1470,23 @@ export const accountsLogic = kea<accountsLogicType>([}},listLoadDataSuccess: ({ response, payload }) => {+ const accountIds =+ response && typeof response === 'object' && 'results' in response && Array.isArray(response.results)+ ? response.results.filter(isAccountsTableRow).map((account) => account.id)+ : []+ cache.disposables.dispose('accountPresencePoll')+ if (accountIds.length) {+ cache.disposables.add(() => {+ actions.loadAccountPresence(accountIds)+ const intervalId = window.setInterval(+ () => actions.loadAccountPresence(accountIds),+ ACCOUNT_PRESENCE_REFRESH_INTERVAL_MS+ )+ return () => window.clearInterval(intervalId)+ }, 'accountPresencePoll')+ } else {+ actions.loadAccountPresence([])+ }const queryId = payload?.queryIdconst requestState = cache.latestListRequestStateif (@@ -1464,6 +1509,26 @@ export const accountsLogic = kea<accountsLogicType>([actions.clearCustomPropertyOverrides()}},+ loadAccountPresence: async ({ accountIds }) => {+ cache.accountPresenceRequestSequence = (cache.accountPresenceRequestSequence ?? 0) + 1+ const requestSequence = cache.accountPresenceRequestSequence+ if (!values.currentTeamId || !accountIds.length) {+ actions.loadAccountPresenceSuccess([])+ return+ }+ try {+ const presence = await accountsPresenceList(String(values.currentTeamId), {+ account_ids: accountIds.slice(0, 100),+ })+ if (requestSequence === cache.accountPresenceRequestSequence) {+ actions.loadAccountPresenceSuccess(presence)+ }+ } catch {+ if (requestSequence === cache.accountPresenceRequestSequence) {+ actions.loadAccountPresenceFailure()+ }+ }+ },loadCustomPropertyDefinitionsSuccess: ({ customPropertyDefinitions }) => {cache.customPropertyDefinitionsLoaded = trueif (!cache.relationshipDefinitionsLoaded) {diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 2a21ddea80ee..c28f303eceb4 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -1139,6 +1139,21 @@ export interface PaginatedAccountSupportTicketMessageListApi {results: AccountSupportTicketMessageApi[]}+export interface AccountPresenceListRequestApi {+ /**+ * Up to 100 account IDs to read presence for.+ * @maxItems 100+ */+ account_ids: string[]+}++export interface AccountPresenceApi {+ /** Customer analytics account ID. */+ readonly account_id: string+ /** People viewing this account. */+ readonly viewers: readonly AccountPresenceViewerApi[]+}+export type AccountsTableQueryRequestApiVariablesOverride = { [key: string]: { [key: string]: unknown } } | nullexport type AccountsTableAccountFieldApi =diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex bd6f734ccefd..a392ea53b80f 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -12,6 +12,8 @@ import type {AccountApi,AccountNotebookApi,AccountNotesListParams,+ AccountPresenceApi,+ AccountPresenceListRequestApi,AccountPresenceViewerApi,AccountRelationshipApi,AccountRelationshipDefinitionApi,@@ -957,6 +959,23 @@ export const accountsByExternalIdRetrieve = async (})}+export const getAccountsPresenceListUrl = (projectId: string) => {+ return `/api/projects/${projectId}/accounts/presence_list/`+}++export const accountsPresenceList = async (+ projectId: string,+ accountPresenceListRequestApi: AccountPresenceListRequestApi,+ options?: RequestInit+): Promise<AccountPresenceApi[]> => {+ return apiMutator<AccountPresenceApi[]>(getAccountsPresenceListUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(accountPresenceListRequestApi),+ })+}+export const getCustomerAnalyticsAccountsTableQueryCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/accounts_table_query/`}diff --git a/products/customer_analytics/frontend/generated/api.zod.ts b/products/customer_analytics/frontend/generated/api.zod.tsindex 19f70aa06849..9f35f7f94b14 100644--- a/products/customer_analytics/frontend/generated/api.zod.ts+++ b/products/customer_analytics/frontend/generated/api.zod.ts@@ -414,6 +414,15 @@ export const AccountsPartialUpdateBody = /* @__PURE__ */ zod}).describe('A Customer Analytics account — a logical grouping used to assign customer-success ownership.')+export const accountsPresenceListBodyAccountIdsMax = 100++export const AccountsPresenceListBody = /* @__PURE__ */ zod.object({+ account_ids: zod+ .array(zod.uuid())+ .max(accountsPresenceListBodyAccountIdsMax)+ .describe('Up to 100 account IDs to read presence for.'),+})+/*** Run a Customer Analytics accounts table query.*/diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex 8581d8640c31..ffdb6794d31e 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -353,6 +353,9 @@ tools:accounts-presence-create:operation: accounts_presence_createenabled: false+ accounts-presence-list:+ operation: accounts_presence_list+ enabled: falseaccounts-relationships-create:operation: accounts_relationships_createenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 552739e1b071..b50a8d5ca607 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -1272,6 +1272,21 @@ export namespace Schemas {readonly display_name: string;}+ export interface AccountPresence {+ /** Customer analytics account ID. */+ readonly account_id: string;+ /** People viewing this account. */+ readonly viewers: readonly AccountPresenceViewer[];+ }++ export interface AccountPresenceListRequest {+ /**+ * Up to 100 account IDs to read presence for.+ * @maxItems 100+ */+ account_ids: string[];+ }+/*** A team-defined account relationship type (CSM, Onboarding manager, ...).*/