: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): add relationships tab to account detail (#68749)
Arthur Moreira de Deus0b10855e86a9
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 43a23ada2d10..90550e9efb23 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -4981,25 +4981,25 @@ snapshots:scenes-app-customer-analytics-accounts--feature-gate-off--light:hash: v1.k794b7964.e8b91bf6a0dd1b5d31064f4cbb94e9791e999c210831c455a498d0c7cc7e6bbb.IkZPJrJz33sKS8zzKwoy8V3s0GvmKpe5EGYTCIljhLsscenes-app-customer-analytics-accounts--row-expanded-empty--dark:- hash: v1.k794b7964.b13cbe3831d8061ef40152025cdd3d6760f914417355679d0f22581de83de586.W8vrcREpOiVfHeVafSDXEU3Iyom5qvydZLiA0lgnvaU+ hash: v1.k794b7964.e2b28b311e14ce6200bac645bddf30c8b97874abd12aca653be7793bebfad902.SGe1vS0-upwRSQigc8WTeVONKGHjwZJD3G5L5PyF9Psscenes-app-customer-analytics-accounts--row-expanded-empty--light:- hash: v1.k794b7964.904bd5b939f99d43408ae3a8a814a3c299bd57bf13a0fd1d98ff6033fd66e343.K1Z16ICEF6-O9kIej8kGnYyarloq2oZH5rdtmx-8Hu0+ hash: v1.k794b7964.ffa47e19f0e59d52f31dc7a978cf944b99b4a9b67906928acffd7bc4af6bfc9a.PORS9supgsHgzAYUclrgIoW-7v8cyPcZti1pFalNFxcscenes-app-customer-analytics-accounts--row-expanded-links-disabled--dark:hash: v1.k794b7964.eb82c630f551bcf603b6ae6993e3bba7b40c2a8e44751b2eb4268b3ec933daa7.Wi33tmhx6YssHXKkt7xHdmg2Meu_RF6kIvTw3b1yqxUscenes-app-customer-analytics-accounts--row-expanded-links-disabled--light:hash: v1.k794b7964.73635ec0fe5ba7adcee656e61aa707fa86f31d999c779fe8a3a49ad728cc7888.29U_MqSrw4nraIw62cWdUY2EORZiGiBpCR1Vlx3i7F4scenes-app-customer-analytics-accounts--row-expanded-usage-not-found--dark:- hash: v1.k794b7964.137c8d62bee6083229b1fd200b955e223176e6776f93fb208ce0a03199b1459f.apnOkM3HfEz6yzXcm0itK4pM0uWHX4IQrxQWyUUt4_Q+ hash: v1.k794b7964.f965d4d9a8f03be382b333ec7dbd94ce2c7c00dcc171ecbbfdcefcb7540b2b19.mao2KMKgwVvpsrCFRFC7YDJFlXExDNilD9Rqb5GKilYscenes-app-customer-analytics-accounts--row-expanded-usage-not-found--light:- hash: v1.k794b7964.3768b29fcaf05cbc939ceaf08b7e402ec648e5dd2f8e16de3661ef3b1d075c95.FBeZ90ynRsfY5ynImaZf270L5Q2aCglgFSZ63yRUPZs+ hash: v1.k794b7964.c2405c1fa64d258225471d9ddb9bf7eb15671abf495a31f9785e0527979442d1.V2s9g14XL2ogDHNCRCcksEppG4zUC9ccLL2tnpwfRRgscenes-app-customer-analytics-accounts--row-expanded-usage-populated--dark:- hash: v1.k794b7964.d5515e69b014fbced298cff975cd908c9de5c9e76dcb2eae3a9bbfe76d8b2b74.t6t8Ea6Q_yUL1m4zKgNts0uqusJ_sCIz0VvuUlkhQQw+ hash: v1.k794b7964.6229daa23ae552cc003a0e9d21dff2c73a5b936743c73111e6aafe8f6e0cc70f.4N0y1wBNjq0WE9ZIMdBoDm7UtXwdnDDZKNwx7n954Asscenes-app-customer-analytics-accounts--row-expanded-usage-populated--light:- hash: v1.k794b7964.93cb526bb006fd64666a3411132840cfc57b1b9496e9fb90518dfc26a4537160.u8Fq6zGylxZL5g0Dr8ufQkwkfKoUjLlXS6T_wwZEYQo+ hash: v1.k794b7964.609c43870977f4ba190826fb6d1d6610b3a1dca1ff0fd7cca448c93da2d0b2d5.Jo-IL9MSKtTdh83GzfovqcJOuKsyNpWb2-PkPVXbNXoscenes-app-customer-analytics-accounts--row-expanded-with-note--dark:- hash: v1.k794b7964.b01bf6d899af56ca21a8012dbc5f27fdaac23e23abcc06ae0746baee28314f26.hHe7tPO3-TwJFxkRB-S57G0esNQKEnufLratIXJKdGk+ hash: v1.k794b7964.887dba0561cd312a76a9fd99fa9d743a804ee9d00a177f808105051cc05ae42f.V_SoLpt6TITgxjyE3yBIoiJ2U4aRVmv__AskXUpY_tQscenes-app-customer-analytics-accounts--row-expanded-with-note--light:- hash: v1.k794b7964.eeed1785fd6398326b36510051130a37b56df20a7b35bec26101b3aa67438850.EulnHstzNwQkR25qYpgjXqjyXQ8dlt1kD7UVC7UAebM+ hash: v1.k794b7964.663478981ad43ec73d1d72dff9a77feb2da02f3c48007190cb6fed8f164e8e22.ZJ1YXEVCqttMKWB00r-GWgf4PqQsfljS_ZsEYXCdtjgscenes-app-customer-analytics-dashboard--b-2-b-mode-with-groups-enabled--dark:hash: v1.k794b7964.cf03f6a65f846aec287042028193b834c567f01226d2e91f6389df5af935530d.bXzRv9MkU0nXN-4tvGbenagVaJuhFr86goke8HVYFJYscenes-app-customer-analytics-dashboard--b-2-b-mode-with-groups-enabled--light:diff --git a/products/customer_analytics/backend/logic/relationships.py b/products/customer_analytics/backend/logic/relationships.pyindex bc085bd95732..566e703c8934 100644--- a/products/customer_analytics/backend/logic/relationships.py+++ b/products/customer_analytics/backend/logic/relationships.py@@ -82,7 +82,9 @@ def sync_from_account_properties(account: Account, *, created_by: User | None =Transitional: Account._properties is still the source of truth for roles, so every JSONrole write calls this to keep the table shadowing it — see backend/COMPROMISES.md.Roles whose definition doesn't exist yet and unresolvable user ids are skipped; the JSON- stays authoritative.+ stays authoritative. Only users who are members of the account's organization resolve —+ the relationships endpoint returns real emails, so resolving arbitrary global user ids+ would let editors enumerate emails of users outside their org."""definitions_by_name = {definition.name: definition@@ -99,5 +101,9 @@ def sync_from_account_properties(account: Account, *, created_by: User | None =user_id = assignment.get("id") if isinstance(assignment, dict) else Noneif user_id is None:end_active(team_id=account.team_id, account=account, definition=definition)- elif (user := User.objects.filter(id=user_id).first()) is not None:+ elif (+ user := User.objects.filter(+ id=user_id, organization_membership__organization__team__id=account.team_id+ ).first()+ ) is not None:assign(team_id=account.team_id, account=account, definition=definition, user=user, created_by=created_by)diff --git a/products/customer_analytics/backend/presentation/views/serializers.py b/products/customer_analytics/backend/presentation/views/serializers.pyindex 8f4965ae69d3..af1210a1273f 100644--- a/products/customer_analytics/backend/presentation/views/serializers.py+++ b/products/customer_analytics/backend/presentation/views/serializers.py@@ -32,8 +32,10 @@ from products.customer_analytics.backend.facade.constants import (CUSTOM_PROPERTY_OPTION_COLORS,)from products.customer_analytics.backend.facade.contracts import (+ AccountAssignment,AccountNotebookView,AccountNoteView,+ AccountRelationship,AccountRelationshipDefinition,AccountView,CustomerJourneyView,@@ -538,3 +540,36 @@ class AccountRelationshipDefinitionSerializer(DataclassSerializer):dataclass = AccountRelationshipDefinitionref_name = "AccountRelationshipDefinition"fields = ["id", "name", "description", "is_single_holder"]+++class AccountAssignmentSerializer(DataclassSerializer):+ """A user assigned to an account relationship (read shape)."""++ id = serializers.IntegerField(read_only=True, help_text="PostHog user id of the assignee.")+ email = serializers.EmailField(read_only=True, help_text="Email of the assignee.")++ class Meta:+ dataclass = AccountAssignment+ ref_name = "AccountAssignment"+ fields = ["id", "email"]+++class AccountRelationshipSerializer(DataclassSerializer):+ """One assignment of a user to an account relationship, with its effective range."""++ id = serializers.UUIDField(read_only=True, help_text="Unique id of this assignment row.")+ definition = AccountRelationshipDefinitionSerializer(+ read_only=True, help_text="The relationship type this assignment belongs to."+ )+ user = AccountAssignmentSerializer(+ read_only=True, allow_null=True, help_text="The assigned user; null when their account was deleted."+ )+ started_at = serializers.DateTimeField(read_only=True, help_text="When this assignment became effective.")+ ended_at = serializers.DateTimeField(+ read_only=True, allow_null=True, help_text="When this assignment ended; null while it is active."+ )++ class Meta:+ dataclass = AccountRelationship+ ref_name = "AccountRelationship"+ fields = ["id", "definition", "user", "started_at", "ended_at"]diff --git a/products/customer_analytics/backend/presentation/views/views.py b/products/customer_analytics/backend/presentation/views/views.pyindex a743a088c008..2c438be705b4 100644--- a/products/customer_analytics/backend/presentation/views/views.py+++ b/products/customer_analytics/backend/presentation/views/views.py@@ -37,6 +37,7 @@ from products.customer_analytics.backend.presentation.views.serializers import (AccountNotebookSerializer,AccountNoteSerializer,AccountRelationshipDefinitionSerializer,+ AccountRelationshipSerializer,AccountSerializer,CustomerJourneySerializer,CustomerProfileConfigSerializer,@@ -1054,3 +1055,48 @@ class CustomPropertyValueViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixraise Conflict(str(exc))return Response(CustomPropertyValueSerializer(value).data, status=status.HTTP_201_CREATED)+++@extend_schema(+ tags=["customer_analytics"],+ parameters=[+ OpenApiParameter(+ name="account_id",+ type=OpenApiTypes.UUID,+ location=OpenApiParameter.PATH,+ description="UUID of the parent account.",+ ),+ ],+)+class AccountRelationshipViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.GenericViewSet):+ scope_object = "account"+ serializer_class = AccountRelationshipSerializer+ pagination_class = None++ def _accessible_account_id(self) -> str | None:+ """The parent account's id when the caller has object-level access to it, else ``None``+ (mapped to 404). Object-access filtering lives behind the facade — the view imports no models."""+ return api.get_accessible_account_id(+ self.team_id, self.parents_query_dict["account_id"], user_access_control=self.user_access_control+ )++ @extend_schema(+ parameters=[+ OpenApiParameter(+ "include_history",+ OpenApiTypes.BOOL,+ description="Include ended assignments (the full timeline), not just active ones.",+ )+ ],+ responses={200: AccountRelationshipSerializer(many=True)},+ )+ def list(self, request: Request, *args, **kwargs) -> Response:+ account_id = self._accessible_account_id()+ if account_id is None:+ return Response({"detail": "Not found."}, status=status.HTTP_404_NOT_FOUND)+ relationships = api.list_account_relationships(+ team_id=self.team_id,+ account_id=account_id,+ include_history=request.query_params.get("include_history", "").lower() == "true",+ )+ return Response(AccountRelationshipSerializer(relationships, many=True).data)diff --git a/products/customer_analytics/backend/routes.py b/products/customer_analytics/backend/routes.pyindex a75c62dfd537..ffdddbc61636 100644--- a/products/customer_analytics/backend/routes.py+++ b/products/customer_analytics/backend/routes.py@@ -7,6 +7,7 @@ from products.customer_analytics.backend.presentation.views.views import (AccountNotebookViewSet,AccountNotesViewSet,AccountRelationshipDefinitionViewSet,+ AccountRelationshipViewSet,AccountViewSet,CustomerJourneyViewSet,CustomerProfileConfigViewSet,@@ -71,3 +72,9 @@ def register_routes(routers: RouterRegistry) -> None:"project_account_custom_property_values",["team_id", "account_id"],)+ project_accounts_router.register(+ r"relationships",+ AccountRelationshipViewSet,+ "project_account_relationships",+ ["team_id", "account_id"],+ )diff --git a/products/customer_analytics/backend/test/test_relationships.py b/products/customer_analytics/backend/test/test_relationships.pyindex 771bec0ce78a..c6e811b7ca4e 100644--- a/products/customer_analytics/backend/test/test_relationships.py+++ b/products/customer_analytics/backend/test/test_relationships.py@@ -1,6 +1,6 @@from posthog.test.base import BaseTest-from posthog.models import Team+from posthog.models import Team, Userfrom posthog.rbac.user_access_control import UserAccessControlfrom products.customer_analytics.backend.facade import (@@ -138,6 +138,12 @@ class TestSyncFromAccountProperties(BaseTest):relationships.sync_from_account_properties(self.account)assert AccountRelationship.objects.for_team(self.team.id).filter(account=self.account).count() == 0+ def test_sync_skips_users_outside_the_organization(self):+ outsider = User.objects.create_user(email="[email protected]", password=None, first_name="Out")+ Account.objects.update_account(self.account, properties={"csm": {"id": outsider.id, "email": outsider.email}})+ relationships.sync_from_account_properties(self.account)+ assert AccountRelationship.objects.for_team(self.team.id).filter(account=self.account).count() == 0+def test_sync_skips_roles_whose_definition_is_missing(self):Account.objects.update_account(self.account,diff --git a/products/customer_analytics/backend/test/test_views.py b/products/customer_analytics/backend/test/test_views.pyindex 88d2b86ef17a..0e7f33295b4c 100644--- a/products/customer_analytics/backend/test/test_views.py+++ b/products/customer_analytics/backend/test/test_views.py@@ -2211,3 +2211,64 @@ class TestAccountRelationshipDefinitionViewSet(APIBaseTest):self.assertEqual(self.client.get(self.endpoint_base).status_code, status.HTTP_200_OK)self.assertEqual(self._create().status_code, status.HTTP_403_FORBIDDEN)+++class TestAccountRelationshipViewSet(APIBaseTest):+ def setUp(self):+ super().setUp()+ self.account = create_account(team_id=self.team.id)+ self.endpoint = f"/api/projects/{self.team.id}/accounts/{self.account.id}/relationships/"++ def _create_relationship_definition(self, name="CSM"):+ return AccountRelationshipDefinition.objects.for_team(self.team.id).create(+ team_id=self.team.id, name=name, created_by=self.user+ )++ def test_lists_active_relationships_by_default(self):+ csm = self._create_relationship_definition("CSM")+ fde = self._create_relationship_definition("FDE")+ active = relationships_logic.assign(+ team_id=self.team.id, account=self.account, definition=csm, user=self.user, created_by=self.user+ )+ ended = relationships_logic.assign(+ team_id=self.team.id, account=self.account, definition=fde, user=self.user, created_by=self.user+ )+ relationships_logic.end_relationship(team_id=self.team.id, relationship_id=str(ended.id))++ response = self.client.get(self.endpoint)++ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())+ rows = response.json()+ self.assertEqual([str(active.id)], [row["id"] for row in rows])+ self.assertEqual(rows[0]["definition"]["id"], str(csm.id))+ self.assertEqual(rows[0]["definition"]["name"], "CSM")+ self.assertEqual(rows[0]["user"], {"id": self.user.id, "email": self.user.email})+ self.assertIsNone(rows[0]["ended_at"])++ def test_include_history_returns_full_timeline(self):+ definition = self._create_relationship_definition()+ successor = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ relationships_logic.assign(+ team_id=self.team.id, account=self.account, definition=definition, user=self.user, created_by=self.user+ )+ relationships_logic.assign(+ team_id=self.team.id, account=self.account, definition=definition, user=successor, created_by=self.user+ )++ response = self.client.get(f"{self.endpoint}?include_history=true")++ self.assertEqual(status.HTTP_200_OK, response.status_code, response.json())+ rows = response.json()+ self.assertEqual(2, len(rows))+ self.assertEqual(rows[0]["user"]["id"], successor.id)+ self.assertIsNone(rows[0]["ended_at"])+ self.assertEqual(rows[1]["user"]["id"], self.user.id)+ self.assertIsNotNone(rows[1]["ended_at"])++ def test_account_from_another_team_returns_404(self):+ other_team = Team.objects.create(organization=self.organization)+ other_account = create_account(team_id=other_team.id)++ response = self.client.get(f"/api/projects/{self.team.id}/accounts/{other_account.id}/relationships/")++ self.assertEqual(status.HTTP_404_NOT_FOUND, response.status_code)diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.mdindex ed64af9409cc..6bc517d2f7c3 100644--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md@@ -8,7 +8,7 @@ This file should carry the full context needed to work here — architecture, da## What this is-An **Account** is a customer organization. The list is a HogQL-backed table over the `system.accounts` table, with per-row expansion into Notes / Users / Usage / Spend / Opportunities, inline role assignment (CSM, AE, owner), configurable columns, overview metric tiles, shareable views, and a Max (AI) contextual tool for opening accounts.+An **Account** is a customer organization. The list is a HogQL-backed table over the `system.accounts` table, with per-row expansion into Notes / Users / Relationships / Usage / Spend / Opportunities, inline role assignment (CSM, AE, owner), configurable columns, overview metric tiles, shareable views, and a Max (AI) contextual tool for opening accounts.`Account.external_id` is the PostHog **group key** — it's how an account joins to its group-analytics data (usage, events, feature flags). Treat it as the account's analytics identity, not a CRM id (CRM/billing ids live in account properties). The account→group bridge lives in the backend query runner and the agent mode, not here — see [Backend touchpoints](#backend-touchpoints). Keep this mechanism out of any user-facing copy (it's a façade — see the agent mode preset).@@ -24,9 +24,10 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc│ "my accounts" on the left, AccountsOverviewTilesButton + AccountsColumnConfigurator on the right├── AccountsOverviewTiles metric tiles across the filtered set└── AccountsHogQLTable the DataTable; per-column renderers; controlled row expansion- └── AccountNotebooksExpansion expanded row: Useful links + LemonTabs(Notes/Users/Usage/Spend/Opportunities)+ └── AccountNotebooksExpansion expanded row: sidebar (Useful links + active-relationships summary) + LemonTabs(Notes/Users/Relationships/Usage/Spend/Opportunities)├── (notes) paginated/searchable/sortable LemonTable + "New note" button (accountNotebooksLogic, keyed by accountId)├── (users) AccountRelatedUsersExpansion (accountRelatedUsersLogic, keyed by externalId)+ ├── (relationships) AccountRelationshipsExpansion (accountRelationshipsLogic, keyed by accountId — full assignment timeline, paginated, read-only)├── (usage) AccountBillingExpansion kind="usage" (accountBillingLogic — a saved billing-usage insight)├── (spend) AccountBillingExpansion kind="spend" (accountBillingLogic — saved billing-spend insights)└── (opportunities) AccountOpportunitiesExpansion (accountOpportunitiesLogic, keyed by accountId — DWH Salesforce opportunities)@@ -43,6 +44,7 @@ AccountsTabContent ── binds dataNodeLogic(ACCOUNTS_HOGQL_DATA_NODE_KEY, acc| `accountsOverviewTilesLogic` | The overview metric tiles (saved in views via `properties.tiles`); its `metrics` feed `accountsLogic.metricsQuery`, the separate metrics-only data node (key `ACCOUNTS_METRICS_DATA_NODE_KEY`) it reads `response`/`responseLoading` back from — independent of the list rows. Reads legacy per-team localStorage tiles **read-only** on mount + emits an `OverviewTilesLocalStorageRead` tombstone; never writes localStorage. || `accountNotebooksLogic` | Notes/notebooks linked to one account (keyed by `accountId`): server-side pagination (`page`/`notebooksCount`), debounced title+content search (`searchTerm`), sort (`sorting` by created date/author), and `createNote` (creates an internal account notebook and opens it in the side panel). || `accountRelatedUsersLogic` | Group members / related users for one account (keyed by `externalId`). |+| `accountRelationshipsLogic` | Relationship assignments for one account (keyed by `accountId`): fetches the full timeline once (`include_history=true` on the nested relationships endpoint) — the full list feeds the (paginated) history tab, the `activeRelationships` selector feeds the sidebar summary. Read-only until the relationships cutover. || `accountBillingLogic` | Billing data behind the Usage and Spend tabs (keyed by `accountId:kind`); injects the account's org + date range into saved billing insights' SQL variables. || `accountOpportunitiesLogic` | Salesforce opportunities behind the Opportunities tab (keyed by `accountId`): fetches the account's `sfdc_id`, then queries the data-warehouse `salesforce.opportunity` table via HogQL. Degrades to an empty state (not an error) when the table is absent — it's production-only. || `accountLinksLogic` | The "Useful links" sidebar for one account (keyed by `accountId`). |@@ -62,9 +64,9 @@ Sort safety: removing the sorted column drops the sort (`clearSortIfColumnRemove## The expanded row-`AccountsHogQLTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `usage` / `spend` / `opportunities` (`AccountExpansionTab`) plus the Useful links sidebar. Active tab comes from `activeTabFor(accountId)` (defaults to `notes`).+`AccountsHogQLTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. The body is `AccountNotebooksExpansion`, a `LemonTabs` over `notes` / `users` / `relationships` / `usage` / `spend` / `opportunities` (`AccountExpansionTab`) plus the sidebar (Useful links + an active-relationships summary, `ActiveRelationships`, hidden when nothing is assigned). Active tab comes from `activeTabFor(accountId)` (defaults to `notes`).-**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `LemonTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountRelatedUsersLogic({ externalId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, and `accountOpportunitiesLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components (`AccountRelatedUsersExpansion`, `AccountBillingExpansion`, `AccountOpportunitiesExpansion`) so both resolve to the same keyed instance. `accountNotebooksLogic` and `accountLinksLogic` already mount at this level (Notes content and the always-rendered sidebar), so they need no explicit mount reference. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live.+**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `LemonTabs` only renders the active tab's content (keyed by `activeKey`), so a tab's logic would normally unmount the moment you switch away and refetch on return. To avoid that, `AccountNotebooksExpansion` holds a mount reference to each per-tab logic via `useMountedLogic` — `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, and `accountOpportunitiesLogic({ accountId })`. Since `AccountNotebooksExpansion` stays mounted for as long as the row is expanded (it's the `expandedRowRender` body), those keyed instances survive tab switches and only tear down when the row collapses. The `useMountedLogic` props must stay identical to the `useValues` props in the tab components (`AccountRelatedUsersExpansion`, `AccountRelationshipsExpansion`, `AccountBillingExpansion`, `AccountOpportunitiesExpansion`) so both resolve to the same keyed instance. `accountNotebooksLogic` and `accountLinksLogic` already mount at this level (Notes content and the always-rendered sidebar), so they need no explicit mount reference. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live.The Users tab reads its loaded data straight off `accountRelatedUsersLogic`, so the root mount above keeps it cached. The **Usage/Spend** tabs are different: `accountBillingLogic` only holds the saved-insight _metadata_ — the actual insight **results** live in the `dataNodeLogic`/`dataVisualizationLogic` that the embedded `<Query>` mounts inside the tab body, which the root mount does **not** keep alive. So `AccountBillingExpansion` passes `attachTo={accountBillingLogic-instance}` to each `<Query>`: `useAttachedLogic` mounts the query's data logics and attaches them to the (root-mounted) `accountBillingLogic`, so they outlive the `<Query>` unmounting on tab switch and only detach when the row collapses. Without `attachTo`, usage/spend refetch on every return to the tab even with the metadata logic mounted. (The Opportunities tab loads its data in `accountOpportunitiesLogic` directly, not via an embedded `<Query>`, so the root `useMountedLogic` above is enough — it needs no `attachTo`.)@@ -180,7 +182,7 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions| `customer analytics accounts note created` | `accountNotebooksLogic` `createNoteSuccess` listener | `notebook_short_id` || `customer analytics accounts notes searched` | `accountNotebooksLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) || `customer analytics accounts notes sorted` | `accountNotebooksLogic` `setSorting` listener | `column` (`created_at` \| `created_by` \| null), `direction` (`asc` \| `desc` \| `cleared`) |-| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `usage` \| `spend` \| `opportunities`) |+| `customer analytics account tab viewed` | `accountsExpansionLogic` `setActiveTab` listener (genuine tab clicks only; programmatic `openAccountTab` navigation does not fire it) | `tab` (`notes` \| `users` \| `relationships` \| `usage` \| `spend` \| `opportunities`) || `customer analytics account related user clicked` | `AccountRelatedUsersExpansion.tsx` user `<Link>` `onClick` | _(none — customer end-user PII kept out)_ || `customer analytics account opportunity clicked` | `AccountOpportunitiesExpansion.tsx` opportunity name `<Link>` `onClick` | _(none — CRM record id/url kept out)_ || `customer analytics notes tab viewed` | `accountNotesLogic` (`../AccountNotes/`) `afterMount` — the top-level Notes tab, not the per-account expansion | _(none — funnel anchor)_ |diff --git a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsxindex 9cf402eba5fd..06f637dc5423 100644--- a/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx+++ b/products/customer_analytics/frontend/components/Accounts/AccountNotebooksExpansion.tsx@@ -5,6 +5,7 @@ import { IconCloud, IconGraph, IconPencil, IconPeople, IconPiggyBank, IconReceipimport {LemonButton,LemonInput,+ LemonLabel,LemonSkeleton,LemonTable,LemonTableColumns,@@ -29,6 +30,8 @@ import { AccountOpportunitiesExpansion } from './AccountOpportunitiesExpansion'import { accountOpportunitiesLogic } from './accountOpportunitiesLogic'import { AccountRelatedUsersExpansion } from './AccountRelatedUsersExpansion'import { accountRelatedUsersLogic } from './accountRelatedUsersLogic'+import { AccountRelationshipsExpansion } from './AccountRelationshipsExpansion'+import { accountRelationshipsLogic } from './accountRelationshipsLogic'import { accountsExpansionLogic } from './accountsExpansionLogic'import { AccountsEvents } from './constants'import { EditAccountLinksButton } from './EditAccountLinksButton'@@ -53,6 +56,33 @@ const LINK_ICONS: Record<string, JSX.Element> = {salesforce: <IconCloud />,}+function ActiveRelationships({ accountId }: { accountId: string }): JSX.Element | null {+ const { activeRelationships } = useValues(accountRelationshipsLogic({ accountId }))+ if (activeRelationships.length === 0) {+ return null+ }+ return (+ <div className="flex flex-col gap-2">+ <h4 className="secondary uppercase text-secondary mb-0">Relationships</h4>+ {activeRelationships.map((relationship) => (+ <div key={relationship.id} className="flex flex-col gap-1">+ <LemonLabel>{relationship.definition.name}</LemonLabel>+ <div className="flex items-center gap-2 border rounded px-2 py-1.5 bg-bg-light">+ {relationship.user ? (+ <>+ <ProfilePicture user={{ email: relationship.user.email }} size="sm" />+ <span className="text-sm">{relationship.user.email}</span>+ </>+ ) : (+ <span className="text-sm text-muted italic">Deleted user</span>+ )}+ </div>+ </div>+ ))}+ </div>+ )+}+function UsefulLinks({ accountId }: { accountId: string }): JSX.Element {const { links, accountLoading } = useValues(accountLinksLogic({ accountId }))return (@@ -106,6 +136,7 @@ export function AccountNotebooksExpansion({// LemonTabs only renders the active tab, so without this the data refetches on every tab switch.useMountedLogic(accountRelatedUsersLogic({ externalId }))+ useMountedLogic(accountRelationshipsLogic({ accountId }))useMountedLogic(accountBillingLogic({ accountId, externalId, kind: 'usage' }))useMountedLogic(accountBillingLogic({ accountId, externalId, kind: 'spend' }))useMountedLogic(accountOpportunitiesLogic({ accountId }))@@ -182,8 +213,9 @@ export function AccountNotebooksExpansion({data-attr="account-expansion"><div className="flex gap-4">- <div className="w-fit shrink-0">+ <div className="w-fit shrink-0 flex flex-col gap-4"><UsefulLinks accountId={accountId} />+ <ActiveRelationships accountId={accountId} /></div><div className="flex-1 min-w-0"><LemonTabs@@ -241,6 +273,11 @@ export function AccountNotebooksExpansion({label: 'Users',content: <AccountRelatedUsersExpansion externalId={externalId} />,},+ {+ key: 'relationships',+ label: 'Relationships',+ content: <AccountRelationshipsExpansion accountId={accountId} />,+ },{key: 'usage',label: 'Usage',diff --git a/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx b/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsxnew file mode 100644index 000000000000..57992e30d48d--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/AccountRelationshipsExpansion.tsx@@ -0,0 +1,68 @@+import { useValues } from 'kea'++import { LemonTable, LemonTableColumns, LemonTag, ProfilePicture } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'++import type { AccountRelationshipApi } from 'products/customer_analytics/frontend/generated/api.schemas'++import { accountRelationshipsLogic } from './accountRelationshipsLogic'++const PAGE_SIZE = 10++export function AccountRelationshipsExpansion({ accountId }: { accountId: string }): JSX.Element {+ const { relationships, relationshipsLoading } = useValues(accountRelationshipsLogic({ accountId }))++ const columns: LemonTableColumns<AccountRelationshipApi> = [+ {+ title: 'Relationship',+ key: 'definition',+ render: (_, relationship) => <span className="font-semibold">{relationship.definition.name}</span>,+ },+ {+ title: 'Assignee',+ key: 'user',+ render: (_, relationship) =>+ relationship.user ? (+ <div className="flex items-center gap-2">+ <ProfilePicture user={{ email: relationship.user.email }} size="sm" />+ <span className="text-sm">{relationship.user.email}</span>+ </div>+ ) : (+ <span className="text-muted italic">Deleted user</span>+ ),+ },+ {+ title: 'Started',+ key: 'started_at',+ width: 140,+ render: (_, relationship) => <TZLabel time={relationship.started_at} />,+ },+ {+ title: 'Ended',+ key: 'ended_at',+ width: 140,+ render: (_, relationship) =>+ relationship.ended_at ? (+ <TZLabel time={relationship.ended_at} />+ ) : (+ <LemonTag type="success">Current</LemonTag>+ ),+ },+ ]++ return (+ <LemonTable<AccountRelationshipApi>+ size="small"+ embedded+ dataSource={relationships ?? []}+ rowKey="id"+ loading={relationshipsLoading}+ columns={columns}+ pagination={{ pageSize: PAGE_SIZE }}+ emptyState={+ relationships === null ? 'Failed to load relationships.' : 'No assignments on this account yet.'+ }+ />+ )+}diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.tsnew file mode 100644index 000000000000..963a39e9dfd7--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.test.ts@@ -0,0 +1,43 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import type { AccountRelationshipApi } from 'products/customer_analytics/frontend/generated/api.schemas'++import { accountRelationshipsLogic } from './accountRelationshipsLogic'++const RELATIONSHIPS_URL = '/api/projects/:team_id/accounts/:account_id/relationships/'++const buildRelationship = (overrides: Partial<AccountRelationshipApi> = {}): AccountRelationshipApi => ({+ id: 'rel-1',+ definition: { id: 'def-1', name: 'CSM', description: null, is_single_holder: true },+ user: { id: 1, email: '[email protected]' },+ started_at: '2026-01-01T00:00:00Z',+ ended_at: null,+ ...overrides,+})++describe('accountRelationshipsLogic', () => {+ let logic: ReturnType<typeof accountRelationshipsLogic.build>++ beforeEach(() => {+ initKeaTests()+ useMocks({+ get: {+ [RELATIONSHIPS_URL]: [+ buildRelationship(),+ buildRelationship({ id: 'rel-2', ended_at: '2026-02-01T00:00:00Z' }),+ ],+ },+ })+ logic = accountRelationshipsLogic({ accountId: 'acc-1' })+ logic.mount()+ })++ it('loads on mount and picks the active assignments for the sidebar summary', async () => {+ await expectLogic(logic).toDispatchActions(['loadRelationships', 'loadRelationshipsSuccess'])+ expect(logic.values.activeRelationships.map((relationship) => relationship.id)).toEqual(['rel-1'])+ expect(logic.values.relationships?.map((relationship) => relationship.id)).toEqual(['rel-1', 'rel-2'])+ })+})diff --git a/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.tsnew file mode 100644index 000000000000..91c63a97016f--- /dev/null+++ b/products/customer_analytics/frontend/components/Accounts/accountRelationshipsLogic.ts@@ -0,0 +1,52 @@+import { afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import { teamLogic } from 'scenes/teamLogic'++import { accountsRelationshipsList } from 'products/customer_analytics/frontend/generated/api'+import type { AccountRelationshipApi } from 'products/customer_analytics/frontend/generated/api.schemas'++import type { accountRelationshipsLogicType } from './accountRelationshipsLogicType'++export interface AccountRelationshipsLogicProps {+ accountId: string+}++export const accountRelationshipsLogic = kea<accountRelationshipsLogicType>([+ path((key) => ['scenes', 'customerAnalytics', 'accounts', 'accountRelationshipsLogic', key]),+ props({} as AccountRelationshipsLogicProps),+ key((props) => props.accountId),+ connect(() => ({+ values: [teamLogic, ['currentTeamId']],+ })),+ loaders(({ props, values }) => ({+ relationships: [+ null as AccountRelationshipApi[] | null,+ {+ // One fetch serves both surfaces: active rows feed the sidebar summary,+ // the full timeline feeds the history tab.+ loadRelationships: async (): Promise<AccountRelationshipApi[]> =>+ accountsRelationshipsList(String(values.currentTeamId), props.accountId, {+ include_history: true,+ }),+ },+ ],+ })),+ selectors({+ activeRelationships: [+ (s) => [s.relationships],+ (relationships): AccountRelationshipApi[] =>+ (relationships ?? []).filter((relationship) => !relationship.ended_at),+ ],+ }),+ listeners(() => ({+ loadRelationshipsFailure: ({ error }) => {+ // No toast: `relationships === null` renders the table's failure empty state.+ posthog.captureException(error, { scope: 'accountRelationshipsLogic.loadRelationships' })+ },+ })),+ afterMount(({ actions }) => {+ actions.loadRelationships()+ }),+])diff --git a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.tsindex ff767f3902b5..690d7cf36e69 100644--- a/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts+++ b/products/customer_analytics/frontend/components/Accounts/accountsExpansionLogic.ts@@ -4,9 +4,16 @@ import posthog from 'posthog-js'import type { accountsExpansionLogicType } from './accountsExpansionLogicType'import { AccountsEvents } from './constants'-export type AccountExpansionTab = 'notes' | 'users' | 'usage' | 'spend' | 'opportunities'+export type AccountExpansionTab = 'notes' | 'users' | 'relationships' | 'usage' | 'spend' | 'opportunities'-export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = ['notes', 'users', 'usage', 'spend', 'opportunities']+export const ACCOUNT_EXPANSION_TABS: AccountExpansionTab[] = [+ 'notes',+ 'users',+ 'relationships',+ 'usage',+ 'spend',+ 'opportunities',+]export const DEFAULT_ACCOUNT_TAB: AccountExpansionTab = 'notes'diff --git a/products/customer_analytics/frontend/generated/api.schemas.ts b/products/customer_analytics/frontend/generated/api.schemas.tsindex 7d2326ff10e1..c7b73543e506 100644--- a/products/customer_analytics/frontend/generated/api.schemas.ts+++ b/products/customer_analytics/frontend/generated/api.schemas.ts@@ -279,6 +279,35 @@ export interface PaginatedAccountNotebookListApi {results: AccountNotebookApi[]}+/**+ * A user assigned to an account relationship (read shape).+ */+export interface AccountAssignmentApi {+ /** PostHog user id of the assignee. */+ readonly id: number+ /** Email of the assignee. */+ readonly email: string+}++/**+ * One assignment of a user to an account relationship, with its effective range.+ */+export interface AccountRelationshipApi {+ /** Unique id of this assignment row. */+ readonly id: string+ /** The relationship type this assignment belongs to. */+ readonly definition: AccountRelationshipDefinitionApi+ /** The assigned user; null when their account was deleted. */+ readonly user: AccountAssignmentApi | null+ /** When this assignment became effective. */+ readonly started_at: string+ /**+ * When this assignment ended; null while it is active.+ * @nullable+ */+ readonly ended_at: string | null+}+/*** Typed account properties: assignment fields (csm, account_executive, account_owner) and external system identifiers (stripe_customer_id, hubspot_deal_id, billing_id, sfdc_id, zendesk_id, slack_channel_id, usage_dashboard_link). Defaults to an empty object. Unknown keys are rejected.* @nullable@@ -953,6 +982,13 @@ export type AccountsNotebooksListParams = {search?: string}+export type AccountsRelationshipsListParams = {+ /**+ * Include ended assignments (the full timeline), not just active ones.+ */+ include_history?: boolean+}+export type CustomPropertyDefinitionsListParams = {/*** Number of results to return per page.diff --git a/products/customer_analytics/frontend/generated/api.ts b/products/customer_analytics/frontend/generated/api.tsindex 2df1c335aec5..5afcca1be321 100644--- a/products/customer_analytics/frontend/generated/api.ts+++ b/products/customer_analytics/frontend/generated/api.ts@@ -12,10 +12,12 @@ import type {AccountApi,AccountNotebookApi,AccountNotesListParams,+ AccountRelationshipApi,AccountRelationshipDefinitionApi,AccountRelationshipDefinitionsListParams,AccountsListParams,AccountsNotebooksListParams,+ AccountsRelationshipsListParams,CustomPropertyDefinitionApi,CustomPropertyDefinitionsListParams,CustomPropertySourceApi,@@ -369,6 +371,38 @@ export const accountsNotebooksDestroy = async (})}+export const getAccountsRelationshipsListUrl = (+ projectId: string,+ accountId: string,+ params?: AccountsRelationshipsListParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/accounts/${accountId}/relationships/?${stringifiedParams}`+ : `/api/projects/${projectId}/accounts/${accountId}/relationships/`+}++export const accountsRelationshipsList = async (+ projectId: string,+ accountId: string,+ params?: AccountsRelationshipsListParams,+ options?: RequestInit+): Promise<AccountRelationshipApi[]> => {+ return apiMutator<AccountRelationshipApi[]>(getAccountsRelationshipsListUrl(projectId, accountId, params), {+ ...options,+ method: 'GET',+ })+}+export const getAccountsRetrieveUrl = (projectId: string, id: string) => {return `/api/projects/${projectId}/accounts/${id}/`}diff --git a/products/customer_analytics/mcp/tools.yaml b/products/customer_analytics/mcp/tools.yamlindex 59c449310308..aa0a5bebe411 100644--- a/products/customer_analytics/mcp/tools.yaml+++ b/products/customer_analytics/mcp/tools.yaml@@ -220,6 +220,9 @@ tools:Tag names to set on the account. Replaces the full existing tag set — pass the complete list, not adelta. Tags are created on demand if they do not already exist for the team.feature_flag: customer-analytics-csp+ accounts-relationships-list:+ operation: accounts_relationships_list+ enabled: falseaccounts-retrieve:operation: accounts_retrieveenabled: truediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex cbdfe9935a2e..3d4702c012c1 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -156,6 +156,16 @@ export namespace Schemas {readonly updated_at: string | null;}+ /**+ * A user assigned to an account relationship (read shape).+ */+ export interface AccountAssignment {+ /** PostHog user id of the assignee. */+ readonly id: number;+ /** Email of the assignee. */+ readonly email: string;+ }+/*** * `engineering` - Engineering* * `data` - Data@@ -278,6 +288,25 @@ export namespace Schemas {is_single_holder?: boolean;}+ /**+ * One assignment of a user to an account relationship, with its effective range.+ */+ export interface AccountRelationship {+ /** Unique id of this assignment row. */+ readonly id: string;+ /** The relationship type this assignment belongs to. */+ readonly definition: AccountRelationshipDefinition;+ /** The assigned user; null when their account was deleted. */+ readonly user: AccountAssignment | null;+ /** When this assignment became effective. */+ readonly started_at: string;+ /**+ * When this assignment ended; null while it is active.+ * @nullable+ */+ readonly ended_at: string | null;+ }+export type BounceRatePageViewMode = typeof BounceRatePageViewMode[keyof typeof BounceRatePageViewMode];@@ -61877,6 +61906,13 @@ export namespace Schemas {search?: string;};+ export type AccountsRelationshipsListParams = {+ /**+ * Include ended assignments (the full timeline), not just active ones.+ */+ include_history?: boolean;+ };+export type ActionsListParams = {format?: ActionsListFormat;/**