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): add account replay widget (#113557)

Arthur Moreira de Deus5d0946667ea3
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 34b40d715c81..4383b28fd921 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2660,6 +2660,42 @@ snapshots:
hash: v1.k794b7964.536f41c62e83935877a0b961d6b2a1aa0e4199dfab49f84587178447e844a8ba.tpDdDBmJuJBZKOX_RFz8CcNUGsUdse6LfVJWG1XNDeQ
components-verticalnesteddnd--base--light:
hash: v1.k794b7964.d5489b1b81f5796e1828217bfd382f980062e90cae10ebe23fb4e8aa5aea07e6.12qSy0lIe-5pOxJ9lBpDJoSa1oh-a24bC0-yeEIbfrg
+ customer-analytics-account-views-session-replays--denied--dark:
+ hash: v1.k794b7964.2304f82c1c16764ec651e0b4bb28cb3c7c658780abfb01f2dd5635f38de72d81.bvPDtHA-qvNVNIwVaFMcp8CY6zisesc0e9rO9IVL7LE
+ customer-analytics-account-views-session-replays--denied--light:
+ hash: v1.k794b7964.5fd2d77f341908e1263c5d8151935fad6e2bc35ef2d37b6a4669c4fc8e097dc0.NV6-YDNwQlazqwQLlRo40Ti57xPRy2-VHIZQLSW4gZg
+ customer-analytics-account-views-session-replays--empty--dark:
+ hash: v1.k794b7964.f38e5695ba545d90f9de15331e9a1c544145dde8f08e5b298879e659b6dcc1cd.9vKvWsk1rV-hyPUyGG1o-XS_HulyglDB0ESnJ-_0b24
+ customer-analytics-account-views-session-replays--empty--light:
+ hash: v1.k794b7964.63bfb3f2f9b46ac1d3d4aae4e6b81431c2a2dfa265345ee353e9f6db0a2bd2cc.GRS_6ZMwsadhKeD53cgLVuF0iPf5klJAr5JxDCv7Fw0
+ customer-analytics-account-views-session-replays--error--dark:
+ hash: v1.k794b7964.6c97e24bbf0c777704806b00a7424e7ecda891197f5371c852f05e563387fa81.MFgng_JIgopDqoKquLU9ki13D_ks65yzsiF-CgG3gB4
+ customer-analytics-account-views-session-replays--error--light:
+ hash: v1.k794b7964.d8ca1a70dd8dda763e6afc024bf19f46b0d4eb1f338a20ef13f701cba0756533.O-YUl8OvNknCFPhXtYs7rPDqSu0No0LYvkQFm0D7Mc0
+ customer-analytics-account-views-session-replays--loading--dark:
+ hash: v1.k794b7964.e81523805afa09476dffb79c9751488da2eb71d8f4b1b9e8e55c41778b0ffa59.jn2yLM6-LK9qW6aXUqjuK9T2oQzaNrU5QT_P6c_qxOM
+ customer-analytics-account-views-session-replays--loading--light:
+ hash: v1.k794b7964.310f75db8eef88aa07b3f320d2b6849f16783e1cae5af5b5ab61e260bea87be9.Bgp5CG2xRkpZbuUnmiFIRcYH-d2H817rNCyuxqeM-ZY
+ customer-analytics-account-views-session-replays--narrow--dark:
+ hash: v1.k794b7964.353e509e28487bcdeda7f0462f793c1087b4ed3a152115b62772bfa2d91438d3.FwD_ls_e3uXDXQq97-l-aXHI7qKk8EJJEF8whls_VHk
+ customer-analytics-account-views-session-replays--narrow--light:
+ hash: v1.k794b7964.a52a77cdeb1c310a814f01b5c66dd5aad17dbb9cf31b085d48ad0f9feaacc6d5.Dyb3reK46v-HllwaUPsNIWKrqG2bmQdYY-iNbJa-AIA
+ customer-analytics-account-views-session-replays--overflow--dark:
+ hash: v1.k794b7964.ff2494d2091341f5a597d188e11739eaf19827463be16087f2aeee518be716ee.iwB0gZquU2VflkC1fijdx216F6Enkd2TYIwGQhquImc
+ customer-analytics-account-views-session-replays--overflow--light:
+ hash: v1.k794b7964.cdf3f4fcaee9999d83714aac8888a08359e8d4a9e63fa4ef7bbb854a5b04da45.s-g2jEzSNzmxLaGKYrI_ev2efkYPkOGD185J_r5gcv8
+ customer-analytics-account-views-session-replays--overflow-narrow--dark:
+ hash: v1.k794b7964.d650b533a1161facc303eafbf8fdef3717a0b62938b05f8ad97de0d65dfb7f07.-b8VgSZKht4_MEeuWZBF6Z8equYKj0gGaZdncNStSwU
+ customer-analytics-account-views-session-replays--overflow-narrow--light:
+ hash: v1.k794b7964.e7f51c3d53a789180080f15df41fad182fae26ea01376c0650ffa78a900b74b6.rUG9oZqpurqr57b5w1sX-91puAoq_bLF2VggOPHePxo
+ customer-analytics-account-views-session-replays--recordings--dark:
+ hash: v1.k794b7964.02a6c1bd4de1f441e7db24741f9372fe3dd3aa222503331a36730f45bebb47eb.prHzwGOYg2eKXPZfD4X5vsbDk6zLePZTcRBzlH4qylU
+ customer-analytics-account-views-session-replays--recordings--light:
+ hash: v1.k794b7964.2669829deff8c7a44b583e41b5de3372ea81256b9f6cad46e02363db31090134.F15A4WWV6eoSYPH-vF3VAV1T7IFKbkjYzZRpVm64C9A
+ customer-analytics-account-views-session-replays--setup--dark:
+ hash: v1.k794b7964.2405cba5f543579b53954f29c8f5c5ca7eb4c9d289d1c952347ba1bbde7f75cb.pe0E5bRxPnNA2UtHGjIVJC5XLvuSXgMTf5phaPFUSUw
+ customer-analytics-account-views-session-replays--setup--light:
+ hash: v1.k794b7964.d29506555b71927bd36ed55b64336cb5da13f1c014d06bf72df89598c28fb248.szC9Unwuopg3KVYDYKX3VIol0LEd7NWscfNKgdwX4JM
customer-analytics-custom-property-sync-runs--account-lifecycle--dark:
hash: v1.k794b7964.4c68902b4f73221926fdd50c1aec035ad5342b685c967b040bf217264747ea5a.NpTBSnGrlQly4iiuvI6iXwVcpKA3PLSxc9pbDo4Vrqs
customer-analytics-custom-property-sync-runs--account-lifecycle--light:
diff --git a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
index fa0862b6d1c7..4d48d23f5688 100644
--- a/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
+++ b/posthog/session_recordings/queries/test/listing_recordings/test_session_recording_list_from_query.py
@@ -5014,6 +5014,44 @@ class TestSessionRecordingsListFromQuery(ClickhouseTestMixin, APIBaseTest):
[],
)
+ @time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
+ def test_account_event_tag_selects_whole_sessions_not_all_sessions_of_the_person(self) -> None:
+ create_person(team=self.team, distinct_ids=["account-user"])
+ session_ids = {
+ name: str(uuid7()) for name in ["account-one-only", "account-two-only", "both-accounts", "untagged"]
+ }
+ for session_id in session_ids.values():
+ produce_replay_summary(
+ distinct_id="account-user",
+ session_id=session_id,
+ first_timestamp=self.an_hour_ago,
+ team_id=self.team.pk,
+ )
+ for session_id, event_account_key in [
+ ("account-one-only", "account-one"),
+ ("account-two-only", "account-two"),
+ ("both-accounts", "account-one"),
+ ("both-accounts", "account-two"),
+ ("untagged", None),
+ ]:
+ create_event(
+ distinct_id="account-user",
+ timestamp=self.an_hour_ago,
+ team=self.team,
+ event_name="account activity",
+ properties={
+ "$session_id": session_ids[session_id],
+ **({"$group_0": event_account_key} if event_account_key else {}),
+ },
+ )
+ self._assert_query_matches_session_ids(
+ {
+ "properties": [{"key": "$group_0", "value": ["account-one"], "operator": "exact", "type": "event"}],
+ "event_match_scope": "session",
+ },
+ [session_ids["account-one-only"], session_ids["both-accounts"]],
+ )
+
@time_machine.travel("2021-01-21T20:00:00.000Z", tick=False)
@snapshot_clickhouse_queries
def test_ordering(self):
diff --git a/products/customer_analytics/backend/logic/account_views.py b/products/customer_analytics/backend/logic/account_views.py
index 980da4a9ecec..8eabace3b345 100644
--- a/products/customer_analytics/backend/logic/account_views.py
+++ b/products/customer_analytics/backend/logic/account_views.py
@@ -23,6 +23,7 @@ ACCOUNT_VIEW_COMPONENT_LABELS = {
"Opportunities": "Opportunities",
"Conversations": "Conversations",
"Meetings": "Meetings",
+ "SessionReplays": "Session replays",
}
ACCOUNT_VIEW_ALLOWED_PROPS = {"config", "nodeId", "span", "title"}
ACCOUNT_VIEW_COMPONENT_TITLE_MAX_LENGTH = 400
diff --git a/products/customer_analytics/backend/test/test_account_views.py b/products/customer_analytics/backend/test/test_account_views.py
index 844e8118138f..dd62482e08ca 100644
--- a/products/customer_analytics/backend/test/test_account_views.py
+++ b/products/customer_analytics/backend/test/test_account_views.py
@@ -30,6 +30,14 @@ def account_view_content(*components: str) -> dict:
class TestAccountViewContentValidation(SimpleTestCase):
+ def test_accepts_replay_tile_with_date_config(self) -> None:
+ content = account_view_content(
+ '<SessionReplays nodeId="replay-one" title="Recent recordings" config={{"dateRange":{"date_from":"-7d","date_to":null}}} />'
+ )
+ validated, text_content = validate_account_view_content(content)
+ self.assertEqual(validated, content)
+ self.assertEqual(text_content, "Recent recordings")
+
def test_rejects_span_outside_twelve_columns(self) -> None:
with self.assertRaises(InvalidAccountViewContent) as context:
validate_account_view_content(account_view_content('<Usage nodeId="usage-one" span={13} />'))
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 8e48d31d6b2c..24c140528e51 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -165,7 +165,7 @@ Tag edits save through `accountsPartialUpdate` and update optimistically. Only t
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.
Project admins set the ordered defaults under Customer analytics > Accounts settings. A user config without `properties.pinned_properties` reads those current defaults without copying them into the user row. The first personal save stores a complete override. An explicit empty list is an override with no pins.
Omitting `pinned_properties` from a PATCH leaves existing pins unchanged. Personal API keys and OAuth tokens need `account:write` for PATCH. Session-authenticated viewers can still personalize their own sidebar.
-Account views store a reusable Markdown document, not an account ID. `accountViewComponents.ts` lists the system tabs and view components. `accountViewsLogic` owns view editing and tile settings. The account scene supplies the current account ID when it renders a view. Each tile keeps a stable `nodeId`, so two tiles of the same kind keep separate settings. `UserCustomerAnalyticsConfig.account_detail_tabs` stores each user's tab order, hidden tabs, and default for the project. A direct link can still open a hidden tab. View components render in document order and use `span` to share a row in a wide container. They stack in a narrow container.
+Account views store a reusable Markdown document, not an account ID. `accountViewComponents.ts` lists the system tabs and view components. `listAvailableAccountSystemTabs` selects only entries with a `systemTabId`, so widget-only entries cannot become standalone tabs. `accountViewsLogic` owns view editing and tile settings. The account scene supplies the current account ID when it renders a view. Each tile keeps a stable `nodeId`, so two tiles of the same kind keep separate settings. `UserCustomerAnalyticsConfig.account_detail_tabs` stores each user's tab order, hidden tabs, and default for the project. A direct link can still open a hidden tab. View components render in document order and use `span` to share a row in a wide container. They stack in a narrow container.
The configuration is one ordered list containing both account custom-property and relationship references. Definitions load across every API page, account custom properties are filtered by target, and the shared limit is 50. Missing definitions remain visible as a stale warning; opening the configurator omits them from its draft, so the next save cleans them up.
The empty Properties state uses the hedgehog and primary **Pin properties** action, with no gear. Once at least one reference is pinned, the gear opens the same configurator.
Property reference keys at the component boundary are namespaced as `custom:<uuid>` and `relationship:<uuid>`; persistence maps custom keys back to the API's `custom_property` kind.
@@ -177,6 +177,10 @@ On wide layouts, the sidebar and the active account-detail tab are separate vert
Tables use borders in the detail scene and remain embedded in expanded rows.
Configure tabs and New view sit in the scene header. They open the tab configurator and view editor when their separate flags are on.
+`AccountSessionReplays` is an account-view tile only. `accountSessionReplaysLogic` keys state by project, account, external ID, and tile instance. It reuses replay preview rows and the global player modal. Dates save through the existing tile config callback as relative or absolute strings. User selection is temporary and uses person UUIDs from recordings loaded for this account, never Cloud organization members. The user menu excludes autocapture in its portal so option labels cannot enter analytics. The replay list always filters event properties on the configured `$group_N` and current account external ID. Missing identity or configuration makes no replay request. Matching selects whole recordings, including activity for other accounts. Pages contain 20 rows, newest first. The list grows naturally through ten preview rows, then scrolls vertically with a cap measured from those rendered rows. Filters, the description, and Load more stay outside the scrollport. Cursor pagination falls back to raw-page offsets and merges by recording ID. Loading, setup, denied, empty, and failed requests have separate UI states. A next-page failure retains loaded rows and retries the same page. The replay endpoint retains its existing permissions and throttles. The account scene retains account authorization.
+
+The generated replay list client describes Django pagination rather than the endpoint's cursor response. `accountSessionReplaysQuery` uses the generated route, shared `RecordingsQuery`/`RecordingsQueryResponse` types, and the Orval transport without a duplicate API contract.
+
The active tab is path-backed at `/customer_analytics/accounts/:accountId/:tab`.
The bare path uses the saved default tab or the first available system tab. An unavailable system tab falls back the same way. A direct link to a hidden tab remains available. A missing custom view shows an unavailable-view message.
User tab changes preserve URL search and hash state and capture `TabViewed`; URL restoration does not capture that event.
@@ -198,7 +202,7 @@ Loading, failed requests, refresh failures, and missing definitions remain disti
`AccountsTable.useExpandable()` makes expansion **controlled** by `accountsExpansionLogic`: `isRowExpanded` reads `expandedAccountIds`, `onRowExpand`/`onRowCollapse` dispatch `toggleAccountExpanded`. With `CUSTOMER_ANALYTICS_ACCOUNT_SCENE` enabled, the body is `AccountPinnedPropertiesExpansion`.
With the flag disabled, the body is `AccountNotebooksExpansion`: the Useful links and active-relationships sidebar plus the shared `AccountDetailTabs` over `notes` / `tasks` / `users` / `relationships` / `feature_requests` / `usage` / `spend` / `opportunities` / `conversations` / `meetings` / `event_stream` (`AccountExpansionTab`; the `tasks` tab is gated by the `CUSTOMER_ANALYTICS_CUSTOMER_TASKS` flag and the `event_stream` tab is gated by the `CUSTOMER_ANALYTICS_CSP` flag). `AccountNotesExpansion` owns the shared Notes body. Active tab comes from `activeTabFor(accountId)` (defaults to `notes`). Pagination inside these tabs keeps its page state out of the URL so changing pages does not rerun deep-link restoration and replace the active tab.
-`AccountDetailTabs` builds its tabs from the `ACCOUNT_VIEW_COMPONENTS` registry in `accountViewComponents.ts` (`listAvailableAccountViewComponents` drops flag-gated entries) and renders each body through `AccountViewComponent`, the same switch that renders personal account-view tiles. Add a new tab to the registry and to `AccountViewComponent`, not to `AccountDetailTabs`.
+`AccountDetailTabs` builds its tabs from the `ACCOUNT_VIEW_COMPONENTS` registry in `accountViewComponents.ts` (`listAvailableAccountSystemTabs` drops flag-gated and widget-only entries) and renders each body through `AccountViewComponent`, the same switch that renders personal account-view tiles. Add a new tab to the registry and to `AccountViewComponent`, not to `AccountDetailTabs`.
Each per-tab logic key ends in an `instanceId` segment (`accountId:instanceId`, `externalId:instanceId`, or `accountId:kind:instanceId` for billing). Tabs omit `instanceId`, so they share the `default` instance with the mounts below. Account-view tiles pass their own `instanceId`, so two tiles of one kind keep separate state.
**Tab data is cached for the row's expanded lifetime, not refetched per tab switch.** `AccountDetailTabs` 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` — `accountNotebooksLogic({ accountId })`, `accountRelatedUsersLogic({ externalId })`, `accountRelationshipsLogic({ accountId })`, `accountBillingLogic` for both `kind: 'usage'` and `kind: 'spend'`, `accountOpportunitiesLogic({ accountId })`, `accountSummariesLogic({ accountId })`, `accountConversationsLogic({ accountId })`, `accountEmailThreadsLogic({ accountId })`, and `accountMeetingsLogic({ 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 so both resolve to the same keyed instance. `accountLinksLogic` mounts through the always-rendered sidebar. `CustomerTasksMount` keeps the account task logic mounted only when `CUSTOMER_ANALYTICS_CUSTOMER_TASKS` is enabled. Data is loaded once on mount and not auto-refreshed while the row stays open — acceptable since this data needn't be live. Flag-gated tabs load only when their flag is enabled.
@@ -385,6 +389,8 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions
### Tracked events
+Account detail view events use singular `accountViewsLogic`, separate from Accounts list views in plural `accountsViewsLogic`.
+
| Event | Fires from | Properties |
| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `customer analytics accounts list viewed` | `accountsLogic` `afterMount` | _(none — funnel anchor; account count and saved-config aren't loaded at mount)_ |
@@ -428,6 +434,28 @@ We track user actions on the Accounts list with `posthog.capture()`. Conventions
| `customer analytics account meeting matching saved` | `accountMeetingsLogic` `saveMatching` listener (after the PATCH succeeds) | `domain_count`, `email_count` (no raw domains/emails — customer PII kept out) |
| `customer analytics account meetings searched` | `accountMeetingsLogic` `setSearchTerm` listener (post-debounce) | `has_query`, `query_length` (no raw text) |
| `customer analytics account meeting attendee clicked` | `AccountMeetingsExpansion.tsx` attendee `<Link>` `onClick` (person links only) | _(none — attendee email/person id is customer PII and kept out)_ |
+| `customer analytics account view editor opened` | `accountViewsLogic` create/edit entry while the editor is closed; reloads while open do not emit | `is_new` |
+| `customer analytics account view saved` | `accountViewsLogic.saveEditor` after API acknowledgement, not the shared `saveEditorSuccess` action | `is_new`, `component_count` |
+| `customer analytics account view save failed` | `accountViewsLogic.saveEditor` validation or failed request | `is_new`, `failure_type` (`validation`, `conflict`, or `request`) |
+| `customer analytics account view tile editor opened` | `accountViewsLogic.openTileEditor` | None |
+| `customer analytics account view tile renamed` | `accountViewsLogic.saveTileEditor` after API acknowledgement | `component_count` |
+| `customer analytics account view tile rename failed` | `accountViewsLogic.saveTileEditor` validation or failed request | `failure_type` (`validation`, `conflict`, or `request`) |
+| `customer analytics account view tile removal started` | `accountViewsLogic.removeViewComponent` after validation, before the queued API write | None |
+| `customer analytics account view tile removed` | `accountViewsLogic.removeViewComponent` after API acknowledgement | `component_count` |
+| `customer analytics account view tile removal failed` | `accountViewsLogic.removeViewComponent` validation or failed request | `failure_type` (`validation`, `conflict`, or `request`) |
+| `customer analytics account view deletion started` | `accountViewsLogic.deleteView` before the API write | None |
+| `customer analytics account view deleted` | `accountViewsLogic.deleteView` after API acknowledgement | None |
+| `customer analytics account view deletion failed` | `accountViewsLogic.deleteView` failed request | `failure_type` (`conflict` or `request`) |
+| `customer analytics account view tab settings opened` | `accountViewsLogic.openConfigure` while the configurator is closed | None |
+| `customer analytics account view tab settings save started` | `accountViewsLogic.saveConfig` after the existing config-availability guard | None |
+| `customer analytics account view tab settings saved` | `accountViewsLogic.saveConfig` after API acknowledgement | `has_default`, `ordered_count`, `hidden_count` (submitted settings summary only) |
+| `customer analytics account view tab settings save failed` | `accountViewsLogic.saveConfig` blocked or failed write; tab settings have no optimistic-version conflict handling | `failure_type` (`unavailable` or `request`) |
+| `customer analytics account replays viewed` | `accountSessionReplaysLogic` on mount | None |
+| `customer analytics account replays filter changed` | `accountSessionReplaysLogic` date or user filter action | `filter_type` (`date` or `user`), `is_cleared` for user selection |
+| `customer analytics account replay opened` | `accountSessionReplaysLogic` opens a loaded row | None |
+| `customer analytics account replays load more` | `accountSessionReplaysLogic` accepts a pagination action | `page_size` |
+| `customer analytics account replays load failed` | `accountSessionReplaysLogic` receives a current request failure | `failure_type` (`denied` or `request`) |
+| `customer analytics account replays retried` | `accountSessionReplaysLogic` accepts retry | None |
| `customer analytics account gong call opened` | `AccountMeetingsExpansion.tsx` "Open in Gong" button | _(none; meeting and Gong identifiers stay out)_ |
| `customer analytics account event stream toggled` | `eventStreamLogic` (`../EventStream/`) `setAccountMembership` listener — the "Include in event stream" toggle in the expanded row's Event stream tab | `account_id`, `included`, `member_count` |
| `customer analytics event stream config saved` | `eventStreamLogic` `saveEventStreamSuccess` listener — the Save button in the Event stream settings section | `enabled`, `event_count`, `has_slack_channel`, `member_count` |
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx b/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx
index 99dcdcaa78ce..1b4f30deb42a 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountDetailTabs.tsx
@@ -8,7 +8,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { accountBillingLogic } from './accountBillingLogic'
import { AccountExpansionTab, getVisibleAccountExpansionTab } from './accountsExpansionLogic'
import { AccountViewComponent } from './AccountViewComponent'
-import { listAvailableAccountViewComponents } from './accountViewComponents'
+import { listAvailableAccountSystemTabs } from './accountViewComponents'
interface AccountDetailTabsProps {
accountId: string
@@ -30,7 +30,7 @@ export function AccountDetailTabs({
useMountedLogic(accountBillingLogic({ accountId, externalId, kind: 'usage' }))
const { featureFlags } = useValues(featureFlagLogic)
const visibleActiveTab = getVisibleAccountExpansionTab(activeTab, featureFlags)
- const components = listAvailableAccountViewComponents(featureFlags)
+ const components = listAvailableAccountSystemTabs(featureFlags)
return (
<LemonTabs
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountSessionReplays.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountSessionReplays.stories.tsx
new file mode 100644
index 000000000000..7bc58887b6eb
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/AccountSessionReplays.stories.tsx
@@ -0,0 +1,151 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import type { Meta, StoryObj } from '@storybook/react'
+import { useEffect } from 'react'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { mswDecorator } from '~/mocks/browser'
+import type { MockResolverInfo } from '~/mocks/utils'
+import type { SessionRecordingType } from '~/types'
+
+import { AccountSessionReplays } from './AccountSessionReplays'
+
+const RECORDINGS_ENDPOINT = 'api/projects/:team_id/session_recordings/'
+const recordings: SessionRecordingType[] = [0, 1, 2].map((index) => ({
+ id: `example-recording-${index}`,
+ viewed: false,
+ viewers: [],
+ recording_duration: 90 + index * 30,
+ start_time: `2026-06-01T1${2 - index}:00:00Z`,
+ end_time: `2026-06-01T1${2 - index}:02:00Z`,
+ snapshot_source: 'web',
+ start_url: 'https://example.com/settings',
+ click_count: 3,
+ keypress_count: 12,
+ person: {
+ id: String(42 + index),
+ uuid: `11111111-2222-4333-8444-55555555555${index}`,
+ name: `Example user ${index + 1}`,
+ distinct_ids: [`example-user-${index}`],
+ properties: {},
+ },
+}))
+
+const meta: Meta<typeof AccountSessionReplays> = {
+ title: 'Customer Analytics/Account views/Session replays',
+ component: AccountSessionReplays,
+ args: { accountId: 'example-account', externalId: 'example-account-key', instanceId: 'example-replay-tile' },
+ parameters: {
+ mockDate: '2026-06-02T12:00:00Z',
+ testOptions: { waitForSelector: '[data-attr="account-replays-open-recording"]' },
+ },
+ decorators: [
+ (Story, { parameters }) => {
+ useEffect(() => {
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...MOCK_DEFAULT_TEAM,
+ customer_analytics_config: {
+ ...MOCK_DEFAULT_TEAM.customer_analytics_config,
+ account_group_type_index: 0,
+ },
+ })
+ }, [])
+ return (
+ <div className={parameters.narrow ? 'w-128 p-2' : 'w-192 p-2'}>
+ <Story />
+ </div>
+ )
+ },
+ ],
+}
+export default meta
+
+type Story = StoryObj<typeof AccountSessionReplays>
+
+function createRecordingsMocks(recordings: SessionRecordingType[], pageSize: number): ReturnType<typeof mswDecorator> {
+ return mswDecorator({
+ get: {
+ [RECORDINGS_ENDPOINT]: ({ request }: MockResolverInfo) => {
+ const params = new URL(request.url).searchParams
+ const personUUID = params.get('person_uuid')
+ const filtered = personUUID
+ ? recordings.filter((recording) => recording.person?.uuid === personUUID)
+ : recordings
+ const offset = Number(params.get('after') ?? params.get('offset') ?? 0)
+ const nextOffset = offset + pageSize
+ const hasNext = filtered.length > nextOffset
+ return {
+ results: filtered.slice(offset, nextOffset),
+ has_next: hasNext,
+ next_cursor: hasNext ? String(nextOffset) : undefined,
+ }
+ },
+ },
+ })
+}
+
+const recordingsMocks = createRecordingsMocks(recordings, 2)
+
+export const Recordings: Story = { decorators: [recordingsMocks] }
+
+export const Narrow: Story = { parameters: { narrow: true }, decorators: [recordingsMocks] }
+
+const overflowRecordings: SessionRecordingType[] = Array.from({ length: 40 }, (_, index) => ({
+ ...recordings[index % recordings.length],
+ id: `example-overflow-recording-${index}`,
+ recording_duration: 120,
+ start_time: new Date(Date.UTC(2026, 5, 1, 12, -index)).toISOString(),
+ end_time: new Date(Date.UTC(2026, 5, 1, 12, 2 - index)).toISOString(),
+ start_url: index % 2 === 0 ? 'https://example.com/settings' : undefined,
+}))
+
+const overflowMocks = createRecordingsMocks(overflowRecordings, 20)
+
+export const Overflow: Story = {
+ parameters: { testOptions: { waitForSelector: '[data-attr="account-replays-list"][data-height-ready="true"]' } },
+ decorators: [overflowMocks],
+}
+
+export const OverflowNarrow: Story = {
+ parameters: {
+ narrow: true,
+ testOptions: { waitForSelector: '[data-attr="account-replays-list"][data-height-ready="true"]' },
+ },
+ decorators: [overflowMocks],
+}
+
+export const Loading: Story = {
+ parameters: {
+ testOptions: { waitForSelector: '[data-attr="account-replays-loading"]', waitForLoadersToDisappear: false },
+ },
+ decorators: [
+ mswDecorator({
+ get: {
+ [RECORDINGS_ENDPOINT]: async () => {
+ return new Promise<never>(() => {})
+ },
+ },
+ }),
+ ],
+}
+
+export const Empty: Story = {
+ parameters: { testOptions: { waitForSelector: '[data-attr="account-replays-empty"]' } },
+ decorators: [mswDecorator({ get: { [RECORDINGS_ENDPOINT]: { results: [], has_next: false } } })],
+}
+
+export const Setup: Story = {
+ args: { externalId: '' },
+ parameters: { testOptions: { waitForSelector: '[data-attr="account-replays-setup"]' } },
+}
+
+export const Denied: Story = {
+ parameters: { testOptions: { waitForSelector: '[data-attr="account-replays-denied"]' } },
+ decorators: [mswDecorator({ get: { [RECORDINGS_ENDPOINT]: [403, { detail: 'Access denied' }] } })],
+}
+
+export const Error: Story = {
+ parameters: { testOptions: { waitForSelector: '[data-attr="account-replays-error"]' } },
+ decorators: [mswDecorator({ get: { [RECORDINGS_ENDPOINT]: [500, { detail: 'Request failed' }] } })],
+}
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountSessionReplays.test.tsx b/products/customer_analytics/frontend/components/Accounts/AccountSessionReplays.test.tsx
new file mode 100644
index 000000000000..53171643a26f
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/AccountSessionReplays.test.tsx
@@ -0,0 +1,110 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+
+import { userHasAccess } from 'lib/utils/accessControlUtils'
+
+import { initKeaTests } from '~/test/init'
+import type { SessionRecordingType } from '~/types'
+
+import { AccountSessionReplays } from './AccountSessionReplays'
+import { getAccountReplayRecordings } from './accountSessionReplaysQuery'
+
+jest.mock('./accountSessionReplaysQuery', () => ({
+ ...jest.requireActual('./accountSessionReplaysQuery'),
+ getAccountReplayRecordings: jest.fn(),
+}))
+jest.mock('lib/utils/accessControlUtils', () => ({
+ ...jest.requireActual('lib/utils/accessControlUtils'),
+ userHasAccess: jest.fn(),
+}))
+
+const PERSON_UUID = '11111111-2222-4333-8444-555555555555'
+const recording: SessionRecordingType = {
+ id: '019781d7-0000-7000-8000-000000000001',
+ viewed: false,
+ viewers: [],
+ recording_duration: 60,
+ start_time: '2026-06-01T10:00:00Z',
+ end_time: '2026-06-01T10:01:00Z',
+ snapshot_source: 'web',
+ person: {
+ id: '42',
+ uuid: PERSON_UUID,
+ distinct_ids: ['example-user'],
+ properties: {},
+ },
+}
+
+const mockList = jest.mocked(getAccountReplayRecordings)
+
+describe('AccountSessionReplays', () => {
+ beforeEach(() => {
+ initKeaTests(true, {
+ ...MOCK_DEFAULT_TEAM,
+ customer_analytics_config: { ...MOCK_DEFAULT_TEAM.customer_analytics_config, account_group_type_index: 0 },
+ })
+ jest.mocked(userHasAccess).mockReturnValue(true)
+ mockList.mockReset()
+ mockList.mockResolvedValue({ results: [recording], has_next: false })
+ })
+
+ afterEach(cleanup)
+
+ it('excludes user option labels from autocapture without blocking selection', async () => {
+ render(<AccountSessionReplays accountId="example-account" externalId="example-account-key" />)
+ await screen.findByLabelText('Open recording')
+ fireEvent.click(screen.getByLabelText('Filter recordings by user'))
+ const option = await screen.findByText('[email protected]')
+ expect(option.closest('.ph-no-capture')).not.toBeNull()
+ fireEvent.click(option)
+ await waitFor(() =>
+ expect(mockList).toHaveBeenLastCalledWith(
+ MOCK_DEFAULT_TEAM.id,
+ expect.objectContaining({ person_uuid: PERSON_UUID })
+ )
+ )
+ })
+
+ it('keeps every paged row in the scrollport with filters, description, and Load more outside', async () => {
+ const names = Array.from({ length: 12 }, (_, index) => `example-user-${index + 1}`)
+ const loadedRecordings = names.map((distinctId, index) => ({
+ ...recording,
+ id: `example-loaded-recording-${index}`,
+ person: { ...recording.person!, distinct_ids: [distinctId] },
+ }))
+ mockList.mockResolvedValue({
+ results: loadedRecordings.slice(0, 11),
+ has_next: true,
+ next_cursor: 'example-cursor',
+ })
+ const { container } = render(
+ <AccountSessionReplays accountId="example-account" externalId="example-account-key" />
+ )
+ await screen.findByText('example-user-11')
+ const scrollport = container.querySelector('[data-attr="account-replays-list"]')
+ const getRowNames = (): (string | null)[] =>
+ Array.from(
+ scrollport?.querySelectorAll<HTMLButtonElement>('button[data-attr="account-replays-open-recording"]') ??
+ []
+ ).map((row) => within(row).getByText(/^example-user-\d+$/).textContent)
+ expect(getRowNames()).toEqual(names.slice(0, 11))
+ const dateFilter = container.querySelector('[data-attr="date-filter"]')
+ expect(dateFilter).not.toBeNull()
+ expect(dateFilter?.closest('[data-attr="account-replays-list"]')).toBeNull()
+ expect(
+ screen.getByLabelText('Filter recordings by user').closest('[data-attr="account-replays-list"]')
+ ).toBeNull()
+ expect(
+ screen
+ .getByText(/Recordings include activity for this account/)
+ .closest('[data-attr="account-replays-list"]')
+ ).toBeNull()
+ expect(screen.getByText('Load more').closest('[data-attr="account-replays-list"]')).toBeNull()
+ mockList.mockResolvedValueOnce({ results: loadedRecordings.slice(11), has_next: false })
+ fireEvent.click(screen.getByText('Load more'))
+ await waitFor(() => expect(getRowNames()).toEqual(names))
+ expect(screen.queryByText('Load more')).toBeNull()
+ })
+})
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountSessionReplays.tsx b/products/customer_analytics/frontend/components/Accounts/AccountSessionReplays.tsx
new file mode 100644
index 000000000000..ef9e78e7aae3
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/AccountSessionReplays.tsx
@@ -0,0 +1,176 @@
+import { useActions, useValues } from 'kea'
+import { useLayoutEffect, useRef } from 'react'
+
+import { LemonBanner, LemonButton, LemonSelect } from '@posthog/lemon-ui'
+
+import { DateFilter } from 'lib/components/DateFilter/DateFilter'
+import {
+ SessionRecordingPreview,
+ SessionRecordingPreviewSkeleton,
+} from 'scenes/session-recordings/playlist/SessionRecordingPreview'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { accountSessionReplaysLogic } from './accountSessionReplaysLogic'
+import type { AccountViewTileLogicProps } from './accountViewTileConfig'
+
+const MAX_VISIBLE_REPLAY_ROWS = 10
+
+interface AccountSessionReplaysProps extends AccountViewTileLogicProps {
+ accountId: string
+ externalId: string
+}
+
+export function AccountSessionReplays({
+ accountId,
+ externalId,
+ ...tileProps
+}: AccountSessionReplaysProps): JSX.Element {
+ const { currentTeamId } = useValues(teamLogic)
+ const logic = accountSessionReplaysLogic({ projectId: currentTeamId, accountId, externalId, ...tileProps })
+ const { replayList, replayListLoading, dateRange, selectedUser, availableUsers, canViewReplays } = useValues(logic)
+ const { setDateRange, setUser, loadMore, retry, openRecording } = useActions(logic)
+ const recordings = replayList?.recordings ?? []
+ const scrollportRef = useRef<HTMLDivElement>(null)
+ const rowsRef = useRef<HTMLDivElement>(null)
+
+ useLayoutEffect(() => {
+ const scrollport = scrollportRef.current
+ const rows = rowsRef.current
+ if (!scrollport || !rows) {
+ return
+ }
+ const visibleRows = Array.from(rows.children).slice(0, MAX_VISIBLE_REPLAY_ROWS)
+ const measureHeight = (): void => {
+ const firstRow = visibleRows[0]
+ const lastRow = visibleRows[visibleRows.length - 1]
+ // Preview height varies with content and width. Row bounds also cancel the current scroll offset.
+ const height =
+ firstRow && lastRow ? lastRow.getBoundingClientRect().bottom - firstRow.getBoundingClientRect().top : 0
+ const maxHeight = rows.childElementCount > MAX_VISIBLE_REPLAY_ROWS && height > 0 ? `${height}px` : ''
+ if (scrollport.style.maxHeight !== maxHeight) {
+ scrollport.style.maxHeight = maxHeight
+ }
+ scrollport.dataset.heightReady = String(height > 0)
+ }
+ measureHeight()
+ if (typeof ResizeObserver === 'undefined') {
+ return
+ }
+ const observer = new ResizeObserver(measureHeight)
+ observer.observe(rows)
+ visibleRows.forEach((row) => observer.observe(row, { box: 'border-box' }))
+ return () => observer.disconnect()
+ }, [recordings, canViewReplays, replayList?.status])
+
+ if (!canViewReplays || replayList?.status === 'denied') {
+ return (
+ <LemonBanner type="warning" className="mb-2">
+ <span data-attr="account-replays-denied">
+ You don't have access to these recordings. Ask a project admin for Customer analytics and Session
+ replay access.
+ </span>
+ </LemonBanner>
+ )
+ }
+
+ if (replayList?.status === 'setup') {
+ return (
+ <LemonBanner type="info" className="mb-2">
+ <span data-attr="account-replays-setup">
+ This account isn't linked to analytics. Ask a project admin to configure accounts in Customer
+ analytics settings and link this account.
+ </span>
+ </LemonBanner>
+ )
+ }
+
+ const userOptions =
+ selectedUser && !availableUsers.some((user) => user.value === selectedUser.value)
+ ? [...availableUsers, selectedUser]
+ : availableUsers
+
+ return (
+ <div className="min-w-0 mb-2 flex flex-col gap-2 ph-no-capture" data-attr="account-session-replays">
+ <div className="flex flex-wrap items-center gap-2">
+ <DateFilter dateFrom={dateRange.date_from} dateTo={dateRange.date_to} onChange={setDateRange} />
+ <LemonSelect<string | null>
+ value={selectedUser?.value ?? null}
+ onChange={(value) => setUser(userOptions.find((user) => user.value === value) ?? null)}
+ options={[{ value: null, label: 'All users' }, ...userOptions]}
+ menu={{ className: 'ph-no-capture' }}
+ size="small"
+ aria-label="Filter recordings by user"
+ data-attr="account-replays-user-filter"
+ tooltip="Users from recordings loaded for this account"
+ truncateText={{ maxWidthClass: 'max-w-48' }}
+ />
+ </div>
+ <p className="mb-0 text-xs text-secondary">
+ Recordings include activity for this account. Playback shows the whole session, including activity for
+ other accounts.
+ </p>
+ {replayList?.status === 'error' && (
+ <LemonBanner type="error">
+ <div className="flex flex-wrap items-center gap-2" data-attr="account-replays-error">
+ <span>Couldn't load recordings. Try again.</span>
+ <LemonButton
+ size="small"
+ type="secondary"
+ onClick={retry}
+ loading={replayListLoading}
+ data-attr="account-replays-retry"
+ >
+ Retry
+ </LemonButton>
+ </div>
+ </LemonBanner>
+ )}
+ {recordings.length > 0 && (
+ <div
+ ref={scrollportRef}
+ className="min-h-0 min-w-0 overflow-x-hidden overflow-y-auto"
+ data-attr="account-replays-list"
+ >
+ <div ref={rowsRef} className="flex flex-col gap-2">
+ {recordings.map((recording) => (
+ <button
+ key={recording.id}
+ type="button"
+ className="w-full min-w-0 border-0 border-b bg-transparent p-0 text-left cursor-pointer focus-visible:-outline-offset-2 ph-no-capture"
+ onClick={() => openRecording(recording.id)}
+ aria-label="Open recording"
+ data-attr="account-replays-open-recording"
+ >
+ <SessionRecordingPreview recording={recording} order="start_time" />
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ {(replayListLoading || !replayList || replayList.status === 'waiting') && recordings.length === 0 && (
+ <div aria-label="Loading recordings" data-attr="account-replays-loading">
+ {Array.from({ length: 3 }, (_, index) => (
+ <SessionRecordingPreviewSkeleton key={index} />
+ ))}
+ </div>
+ )}
+ {replayList?.status === 'ready' && !replayListLoading && recordings.length === 0 && (
+ <div className="p-4 text-center text-secondary" data-attr="account-replays-empty">
+ No recordings match this account and these filters. Try another date range or clear the user filter.
+ </div>
+ )}
+ {replayList?.status === 'ready' && replayList.hasMore && (
+ <LemonButton
+ size="small"
+ type="secondary"
+ onClick={loadMore}
+ loading={replayListLoading}
+ fullWidth
+ data-attr="account-replays-load-more"
+ >
+ Load more
+ </LemonButton>
+ )}
+ </div>
+ )
+}
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx b/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx
index f1fad8dabb48..1ffbbcf270e6 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountViewComponent.tsx
@@ -11,6 +11,7 @@ import { AccountNotesExpansion } from './AccountNotesExpansion'
import { AccountOpportunitiesExpansion } from './AccountOpportunitiesExpansion'
import { AccountRelatedUsersExpansion } from './AccountRelatedUsersExpansion'
import { AccountRelationshipsExpansion } from './AccountRelationshipsExpansion'
+import { AccountSessionReplays } from './AccountSessionReplays'
import type { AccountViewComponentKind } from './accountViewComponents'
import type { AccountViewTileConfig } from './accountViewTileConfig'
@@ -35,6 +36,8 @@ export function AccountViewComponent({
}: AccountViewComponentProps): JSX.Element {
const tileProps = { instanceId, initialConfig, onConfigChange }
switch (kind) {
+ case 'session_replays':
+ return <AccountSessionReplays accountId={accountId} externalId={externalId} {...tileProps} />
case 'notes':
return <AccountNotesExpansion accountId={accountId} embedded={embedded} {...tileProps} />
case 'tasks':
diff --git a/products/customer_analytics/frontend/components/Accounts/accountSessionReplaysLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountSessionReplaysLogic.test.ts
new file mode 100644
index 000000000000..96d3587486b4
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/accountSessionReplaysLogic.test.ts
@@ -0,0 +1,300 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import { waitFor } from '@testing-library/react'
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { ApiError } from 'lib/api'
+import { userHasAccess } from 'lib/utils/accessControlUtils'
+import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import type { RecordingsQueryResponse } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+import { AccessControlResourceType, type SessionRecordingType } from '~/types'
+
+import { accountSessionReplaysLogic, type AccountSessionReplaysLogicProps } from './accountSessionReplaysLogic'
+import { getAccountReplayRecordings } from './accountSessionReplaysQuery'
+import { AccountsEvents } from './constants'
+
+jest.mock('./accountSessionReplaysQuery', () => ({
+ ...jest.requireActual('./accountSessionReplaysQuery'),
+ getAccountReplayRecordings: jest.fn(),
+}))
+jest.mock('lib/utils/accessControlUtils', () => ({
+ ...jest.requireActual('lib/utils/accessControlUtils'),
+ userHasAccess: jest.fn(),
+}))
+
+const mockList = jest.mocked(getAccountReplayRecordings)
+const mockAccess = jest.mocked(userHasAccess)
+const PERSON_UUID = '11111111-2222-4333-8444-555555555555'
+const createRecording = (id: string): SessionRecordingType => ({
+ id,
+ viewed: false,
+ viewers: [],
+ recording_duration: 60,
+ start_time: '2026-06-01T10:00:00Z',
+ end_time: '2026-06-01T10:01:00Z',
+ snapshot_source: 'web',
+ person: { id: '42', uuid: PERSON_UUID, name: 'Example user', distinct_ids: ['example-user'], properties: {} },
+})
+const createResponse = (ids: string[], hasNext = false, cursor?: string): RecordingsQueryResponse => ({
+ results: ids.map(createRecording),
+ has_next: hasNext,
+ next_cursor: cursor,
+})
+const DEFAULT_PROPS: AccountSessionReplaysLogicProps = {
+ projectId: MOCK_DEFAULT_TEAM.id,
+ accountId: 'account-one',
+ externalId: 'account-key-one',
+ instanceId: 'tile-one',
+}
+
+function createDeferred<T>(): { promise: Promise<T>; resolve: (value: T) => void; reject: (error: Error) => void } {
+ let resolve!: (value: T) => void
+ let reject!: (error: Error) => void
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ return { promise, resolve, reject }
+}
+
+describe('accountSessionReplaysLogic', () => {
+ const mounted: ReturnType<typeof accountSessionReplaysLogic>[] = []
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockList.mockReset()
+ initKeaTests(true, {
+ ...MOCK_DEFAULT_TEAM,
+ customer_analytics_config: { ...MOCK_DEFAULT_TEAM.customer_analytics_config, account_group_type_index: 0 },
+ })
+ mockAccess.mockReturnValue(true)
+ mockList.mockResolvedValue(createResponse(['recording-one'], true, 'cursor-one'))
+ })
+
+ afterEach(() => {
+ mounted.splice(0).forEach((logic) => logic.unmount())
+ jest.restoreAllMocks()
+ })
+
+ const mount = (
+ props: Partial<AccountSessionReplaysLogicProps> = {}
+ ): ReturnType<typeof accountSessionReplaysLogic> => {
+ const logic = accountSessionReplaysLogic({ ...DEFAULT_PROPS, ...props })
+ logic.mount()
+ mounted.push(logic)
+ return logic
+ }
+
+ it.each([
+ { dateFrom: '-14d', requestFrom: '-14d' },
+ { dateFrom: null, requestFrom: 'all' },
+ ])(
+ 'ignores restored identity, filters, and user selection, preserving only dates: %p',
+ async ({ dateFrom, requestFrom }) => {
+ const logic = mount({
+ initialConfig: {
+ externalId: 'another-account',
+ properties: [],
+ person_uuid: PERSON_UUID,
+ dateRange: { date_from: dateFrom, date_to: null },
+ },
+ })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockList).toHaveBeenLastCalledWith(
+ MOCK_DEFAULT_TEAM.id,
+ expect.objectContaining({
+ properties: [{ key: '$group_0', type: 'event', operator: 'exact', value: ['account-key-one'] }],
+ date_from: requestFrom,
+ date_to: null,
+ person_uuid: undefined,
+ limit: 20,
+ order: 'start_time',
+ order_direction: 'DESC',
+ event_match_scope: 'session',
+ })
+ )
+ expect(mockList.mock.calls.at(-1)?.[1]).not.toHaveProperty('offset')
+ expect(mockList.mock.calls.at(-1)?.[1]).not.toHaveProperty('after')
+ expect(logic.values.selectedUser).toBeNull()
+ }
+ )
+
+ it('waits for a group mapping, ignoring tile config, then shows loading instead of stale setup', async () => {
+ initKeaTests(true, {
+ ...MOCK_DEFAULT_TEAM,
+ customer_analytics_config: {
+ ...MOCK_DEFAULT_TEAM.customer_analytics_config,
+ account_group_type_index: null,
+ },
+ })
+ const logic = mount({ initialConfig: { group_type_index: 0 } })
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.replayList?.status).toBe('setup')
+ expect(mockList).not.toHaveBeenCalled()
+ mockList.mockReturnValueOnce(createDeferred<RecordingsQueryResponse>().promise)
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...MOCK_DEFAULT_TEAM,
+ customer_analytics_config: { ...MOCK_DEFAULT_TEAM.customer_analytics_config, account_group_type_index: 0 },
+ })
+ expect(mockList).toHaveBeenCalledTimes(1)
+ expect(logic.values).toMatchObject({ replayList: null, replayListLoading: true })
+ })
+
+ it.each([AccessControlResourceType.CustomerAnalytics, AccessControlResourceType.SessionRecording])(
+ 'does not request recordings when access is denied to %s',
+ async (resource) => {
+ mockAccess.mockImplementation((requestedResource) => requestedResource !== resource)
+ const logic = mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.replayList?.status).toBe('denied')
+ expect(mockList).not.toHaveBeenCalled()
+ }
+ )
+
+ it('appends without duplicate rows, guards repeat clicks, and stops at the final page', async () => {
+ const logic = mount()
+ await expectLogic(logic).toFinishAllListeners()
+ const page = createDeferred<RecordingsQueryResponse>()
+ mockList.mockReturnValueOnce(page.promise)
+ logic.actions.loadMore()
+ logic.actions.loadMore()
+ expect(mockList).toHaveBeenCalledTimes(2)
+ expect(mockList).toHaveBeenLastCalledWith(
+ MOCK_DEFAULT_TEAM.id,
+ expect.objectContaining({ after: 'cursor-one' })
+ )
+ page.resolve(createResponse(['recording-one', 'recording-two']))
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.replayList?.recordings.map(({ id }) => id)).toEqual(['recording-one', 'recording-two'])
+ expect(logic.values.replayList?.hasMore).toBe(false)
+ logic.actions.loadMore()
+ expect(mockList).toHaveBeenCalledTimes(2)
+ })
+
+ it('uses raw page progress for offset fallback rather than the deduplicated row count', async () => {
+ mockList.mockResolvedValueOnce(createResponse(['recording-one', 'recording-two'], true))
+ const logic = mount()
+ await expectLogic(logic).toFinishAllListeners()
+ mockList.mockResolvedValueOnce(createResponse(['recording-two', 'recording-three'], true))
+ logic.actions.loadMore()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.loadMore()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockList).toHaveBeenLastCalledWith(MOCK_DEFAULT_TEAM.id, expect.objectContaining({ offset: 4 }))
+ })
+
+ it.each([
+ { scope: 'tile', props: { instanceId: 'tile-two' }, externalId: 'account-key-one' },
+ {
+ scope: 'account',
+ props: { accountId: 'account-two', externalId: 'account-key-two' },
+ externalId: 'account-key-two',
+ },
+ ])('keeps $scope state separate and saves dates without the temporary user', async ({ props, externalId }) => {
+ const onConfigChange = jest.fn()
+ const first = mount({ onConfigChange })
+ const second = mount({
+ ...props,
+ initialConfig: { dateRange: { date_from: '-30d', date_to: null } },
+ })
+ await expectLogic(first).toFinishAllListeners()
+ await expectLogic(second).toFinishAllListeners()
+ const secondList = second.values.replayList
+ expect(mockList).toHaveBeenLastCalledWith(
+ MOCK_DEFAULT_TEAM.id,
+ expect.objectContaining({
+ properties: [{ key: '$group_0', type: 'event', operator: 'exact', value: [externalId] }],
+ person_uuid: undefined,
+ })
+ )
+ first.actions.setUser(first.values.availableUsers[0])
+ await expectLogic(first).toFinishAllListeners()
+ expect(mockList).toHaveBeenLastCalledWith(
+ MOCK_DEFAULT_TEAM.id,
+ expect.objectContaining({ person_uuid: PERSON_UUID })
+ )
+ expect(mockList.mock.calls.at(-1)?.[1]).not.toHaveProperty('offset')
+ expect(mockList.mock.calls.at(-1)?.[1]).not.toHaveProperty('after')
+ expect(onConfigChange).not.toHaveBeenCalled()
+ first.actions.setDateRange('-14d', null)
+ await expectLogic(first).toFinishAllListeners()
+ expect(onConfigChange).toHaveBeenLastCalledWith({ dateRange: { date_from: '-14d', date_to: null } })
+ expect(second.values.dateRange.date_from).toBe('-30d')
+ expect(second.values.selectedUser).toBeNull()
+ expect(second.values.replayList).toBe(secondList)
+ })
+
+ it.each(['success', 'denied'])('discards an older filter %s after the new filter resolves', async (outcome) => {
+ const oldPage = createDeferred<RecordingsQueryResponse>()
+ mockList.mockReturnValueOnce(oldPage.promise)
+ const logic = mount()
+ logic.actions.setDateRange('-30d', null)
+ await waitFor(() => expect(logic.values.replayList?.status).toBe('ready'))
+ if (outcome === 'success') {
+ oldPage.resolve(createResponse(['stale-recording']))
+ } else {
+ oldPage.reject(new ApiError('Access denied', 403))
+ }
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.replayList?.status).toBe('ready')
+ expect(logic.values.replayList?.recordings.map(({ id }) => id)).toEqual(['recording-one'])
+ })
+
+ it.each([401, 403, 500])('distinguishes denied requests from retryable errors: %s', async (status) => {
+ mockList.mockRejectedValueOnce(new ApiError('Request failed', status))
+ const logic = mount()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.replayList?.status).toBe(status === 500 ? 'error' : 'denied')
+ logic.actions.retry()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.replayList?.status).toBe('ready')
+ })
+
+ it('retries a failed next page without clearing already loaded rows', async () => {
+ const logic = mount()
+ await expectLogic(logic).toFinishAllListeners()
+ mockList.mockRejectedValueOnce(new ApiError('Request failed', 500))
+ logic.actions.loadMore()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.replayList?.recordings.map(({ id }) => id)).toEqual(['recording-one'])
+ expect(logic.values.replayList?.status).toBe('error')
+ mockList.mockResolvedValueOnce(createResponse(['recording-two']))
+ logic.actions.retry()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockList).toHaveBeenLastCalledWith(
+ MOCK_DEFAULT_TEAM.id,
+ expect.objectContaining({ after: 'cursor-one' })
+ )
+ expect(logic.values.replayList?.recordings.map(({ id }) => id)).toEqual(['recording-one', 'recording-two'])
+ })
+
+ it('opens the global player without changing filters or rows and emits no customer data', async () => {
+ const capture = jest.spyOn(posthog, 'capture')
+ sessionPlayerModalLogic.mount()
+ try {
+ const logic = mount()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setUser(logic.values.availableUsers[0])
+ await expectLogic(logic).toFinishAllListeners()
+ const list = logic.values.replayList
+ logic.actions.openRecording('recording-one')
+ expect(sessionPlayerModalLogic.values.activeSessionRecording).toEqual({ id: 'recording-one' })
+ sessionPlayerModalLogic.actions.closeSessionPlayer()
+ expect(logic.values.replayList).toBe(list)
+ expect(logic.values.selectedUser?.value).toBe(PERSON_UUID)
+ expect(capture).toHaveBeenCalledWith(AccountsEvents.ReplaysRecordingOpened)
+ const replayCalls = capture.mock.calls.filter(([event]) =>
+ event.startsWith('customer analytics account replay')
+ )
+ expect(JSON.stringify(replayCalls)).not.toMatch(
+ /account-key-one|recording-one|Example user|example-user|11111111/
+ )
+ } finally {
+ sessionPlayerModalLogic.unmount()
+ }
+ })
+})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountSessionReplaysLogic.ts b/products/customer_analytics/frontend/components/Accounts/accountSessionReplaysLogic.ts
new file mode 100644
index 000000000000..56fea7b7ab66
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/accountSessionReplaysLogic.ts
@@ -0,0 +1,284 @@
+import {
+ LogicWrapper,
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ isBreakpoint,
+ kea,
+ key,
+ listeners,
+ path,
+ props,
+ reducers,
+ selectors,
+} from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import { ApiError } from 'lib/api'
+import { userHasAccess } from 'lib/utils/accessControlUtils'
+import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'
+import { teamLogic } from 'scenes/teamLogic'
+
+import type { CustomerAnalyticsConfig } from '~/queries/schema/schema-general'
+import { AccessControlLevel, AccessControlResourceType, type SessionRecordingType } from '~/types'
+
+import {
+ ACCOUNT_REPLAYS_PAGE_SIZE,
+ createAccountReplayQuery,
+ getAccountReplayDateRange,
+ getAccountReplayRecordings,
+ type AccountReplayDateRange,
+} from './accountSessionReplaysQuery'
+import type { AccountViewTileLogicProps } from './accountViewTileConfig'
+import { AccountsEvents } from './constants'
+
+export interface AccountSessionReplaysLogicProps extends AccountViewTileLogicProps {
+ projectId: number | null
+ accountId: string
+ externalId: string
+}
+
+export interface AccountReplayUserOption {
+ value: string
+ label: string
+}
+
+export interface AccountReplayListState {
+ status: 'ready' | 'setup' | 'denied' | 'error' | 'waiting'
+ recordings: SessionRecordingType[]
+ hasMore: boolean
+ nextCursor?: string
+ nextOffset: number
+ failedPage?: 'first' | 'more'
+}
+
+const EMPTY_LIST: AccountReplayListState = { status: 'waiting', recordings: [], hasMore: false, nextOffset: 0 }
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountSessionReplaysLogicValues {
+ customerAnalyticsConfig: CustomerAnalyticsConfig // teamLogic
+ availableUsers: AccountReplayUserOption[]
+ canViewReplays: boolean
+ dateRange: AccountReplayDateRange
+ replayList: AccountReplayListState | null
+ replayListLoading: boolean
+ selectedUser: AccountReplayUserOption | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountSessionReplaysLogicActions {
+ loadMore: () => {
+ value: true
+ }
+ loadReplayList: ({ append }: { append: boolean }) => {
+ append: boolean
+ }
+ loadReplayListFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadReplayListSuccess: (
+ replayList: AccountReplayListState,
+ payload?: {
+ append: boolean
+ }
+ ) => {
+ replayList: AccountReplayListState
+ payload?: {
+ append: boolean
+ }
+ }
+ openRecording: (id: string) => {
+ id: string
+ }
+ retry: () => {
+ value: true
+ }
+ setDateRange: (
+ dateFrom: string | null,
+ dateTo: string | null
+ ) => {
+ dateFrom: string | null
+ dateTo: string | null
+ }
+ setUser: (user: AccountReplayUserOption | null) => {
+ user: AccountReplayUserOption | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface accountSessionReplaysLogicMeta {
+ key: string
+}
+
+export type accountSessionReplaysLogicType = MakeLogicType<
+ accountSessionReplaysLogicValues,
+ accountSessionReplaysLogicActions,
+ AccountSessionReplaysLogicProps,
+ accountSessionReplaysLogicMeta
+>
+
+export const accountSessionReplaysLogic: LogicWrapper<accountSessionReplaysLogicType> =
+ kea<accountSessionReplaysLogicType>([
+ props({} as AccountSessionReplaysLogicProps),
+ key((props) => `${props.projectId}:${props.accountId}:${props.externalId}:${props.instanceId ?? 'default'}`),
+ path((key) => ['products', 'customerAnalytics', 'accountSessionReplaysLogic', key]),
+ connect({ values: [teamLogic, ['customerAnalyticsConfig']] }),
+ actions({
+ setDateRange: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
+ setUser: (user: AccountReplayUserOption | null) => ({ user }),
+ loadMore: true,
+ retry: true,
+ openRecording: (id: string) => ({ id }),
+ }),
+ loaders(({ props, values }) => ({
+ replayList: [
+ null as AccountReplayListState | null,
+ {
+ loadReplayList: async (
+ { append }: { append: boolean },
+ breakpoint
+ ): Promise<AccountReplayListState> => {
+ const previous = append ? values.replayList : null
+ if (!values.canViewReplays) {
+ return { ...EMPTY_LIST, status: 'denied' }
+ }
+ if (props.projectId == null) {
+ return EMPTY_LIST
+ }
+ const query = createAccountReplayQuery(
+ props.externalId,
+ values.customerAnalyticsConfig.account_group_type_index,
+ values.dateRange,
+ values.selectedUser?.value ?? null,
+ previous ? { cursor: previous.nextCursor, offset: previous.nextOffset } : undefined
+ )
+ if (!query) {
+ return { ...EMPTY_LIST, status: 'setup' }
+ }
+ try {
+ const response = await getAccountReplayRecordings(props.projectId, query)
+ breakpoint()
+ const recordings = [
+ ...new Map(
+ [...(previous?.recordings ?? []), ...response.results].map((recording) => [
+ recording.id,
+ recording,
+ ])
+ ).values(),
+ ]
+ return {
+ status: 'ready',
+ recordings,
+ hasMore:
+ response.has_next &&
+ response.results.length > 0 &&
+ (!response.next_cursor || response.next_cursor !== previous?.nextCursor),
+ nextCursor: response.next_cursor,
+ nextOffset: (previous?.nextOffset ?? 0) + response.results.length,
+ }
+ } catch (error) {
+ if (error instanceof Error && isBreakpoint(error)) {
+ throw error
+ }
+ breakpoint()
+ const denied = error instanceof ApiError && (error.status === 401 || error.status === 403)
+ posthog.capture(AccountsEvents.ReplaysLoadFailed, {
+ failure_type: denied ? 'denied' : 'request',
+ })
+ return denied
+ ? { ...EMPTY_LIST, status: 'denied' }
+ : {
+ ...(previous ?? EMPTY_LIST),
+ status: 'error',
+ failedPage: append ? 'more' : 'first',
+ }
+ }
+ },
+ },
+ ],
+ })),
+ reducers(({ props }) => ({
+ dateRange: [
+ getAccountReplayDateRange(props.initialConfig),
+ { setDateRange: (_, { dateFrom, dateTo }) => ({ date_from: dateFrom, date_to: dateTo }) },
+ ],
+ selectedUser: [null as AccountReplayUserOption | null, { setUser: (_, { user }) => user }],
+ replayList: {
+ loadReplayList: (state, { append }) => (append ? state : null),
+ setDateRange: () => null,
+ setUser: () => null,
+ },
+ availableUsers: [
+ [] as AccountReplayUserOption[],
+ {
+ setDateRange: () => [],
+ loadReplayListSuccess: (users, { replayList }) => {
+ if (replayList?.status !== 'ready') {
+ return replayList?.status === 'denied' || replayList?.status === 'setup' ? [] : users
+ }
+ const options = replayList.recordings.flatMap(({ person }) =>
+ person?.uuid ? [{ value: person.uuid, label: person.name || person.uuid }] : []
+ )
+ return [...new Map([...users, ...options].map((user) => [user.value, user])).values()]
+ },
+ },
+ ],
+ })),
+ selectors({
+ canViewReplays: [
+ () => [],
+ (): boolean =>
+ userHasAccess(AccessControlResourceType.CustomerAnalytics, AccessControlLevel.Viewer) &&
+ userHasAccess(AccessControlResourceType.SessionRecording, AccessControlLevel.Viewer),
+ ],
+ }),
+ listeners(({ actions, values, props }) => ({
+ setDateRange: () => {
+ props.onConfigChange?.({ dateRange: values.dateRange })
+ posthog.capture(AccountsEvents.ReplaysFilterChanged, { filter_type: 'date' })
+ actions.loadReplayList({ append: false })
+ },
+ setUser: () => {
+ posthog.capture(AccountsEvents.ReplaysFilterChanged, {
+ filter_type: 'user',
+ is_cleared: !values.selectedUser,
+ })
+ actions.loadReplayList({ append: false })
+ },
+ loadMore: () => {
+ if (values.replayListLoading || !values.replayList?.hasMore || values.replayList.status !== 'ready') {
+ return
+ }
+ posthog.capture(AccountsEvents.ReplaysLoadMore, { page_size: ACCOUNT_REPLAYS_PAGE_SIZE })
+ actions.loadReplayList({ append: true })
+ },
+ retry: () => {
+ if (!values.replayListLoading) {
+ posthog.capture(AccountsEvents.ReplaysRetried)
+ actions.loadReplayList({ append: values.replayList?.failedPage === 'more' })
+ }
+ },
+ openRecording: ({ id }) => {
+ if (
+ values.canViewReplays &&
+ values.replayList?.status !== 'denied' &&
+ values.replayList?.recordings.some((recording) => recording.id === id)
+ ) {
+ posthog.capture(AccountsEvents.ReplaysRecordingOpened)
+ sessionPlayerModalLogic.actions.openSessionPlayer({ id })
+ }
+ },
+ [teamLogic.actionTypes.loadCurrentTeamSuccess]: () => actions.loadReplayList({ append: false }),
+ [teamLogic.actionTypes.updateCurrentTeamSuccess]: () => actions.loadReplayList({ append: false }),
+ })),
+ afterMount(({ actions }) => {
+ posthog.capture(AccountsEvents.ReplaysViewed)
+ actions.loadReplayList({ append: false })
+ }),
+ ])
diff --git a/products/customer_analytics/frontend/components/Accounts/accountSessionReplaysQuery.test.ts b/products/customer_analytics/frontend/components/Accounts/accountSessionReplaysQuery.test.ts
new file mode 100644
index 000000000000..94383a70a8f7
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/accountSessionReplaysQuery.test.ts
@@ -0,0 +1,17 @@
+import { createAccountReplayQuery } from './accountSessionReplaysQuery'
+
+const dateRange = { date_from: '-7d', date_to: null }
+
+describe('createAccountReplayQuery', () => {
+ it.each([
+ { externalId: '', groupTypeIndex: 0 },
+ { externalId: ' ', groupTypeIndex: 0 },
+ { externalId: 'account-key', groupTypeIndex: undefined },
+ { externalId: 'account-key', groupTypeIndex: null },
+ { externalId: 'account-key', groupTypeIndex: -1 },
+ { externalId: 'account-key', groupTypeIndex: 5 },
+ { externalId: 'account-key', groupTypeIndex: 0.5 },
+ ])('rejects invalid account identity or group mapping: %p', ({ externalId, groupTypeIndex }) => {
+ expect(createAccountReplayQuery(externalId, groupTypeIndex, dateRange, null)).toBeNull()
+ })
+})
diff --git a/products/customer_analytics/frontend/components/Accounts/accountSessionReplaysQuery.ts b/products/customer_analytics/frontend/components/Accounts/accountSessionReplaysQuery.ts
new file mode 100644
index 000000000000..c12ccddf31b6
--- /dev/null
+++ b/products/customer_analytics/frontend/components/Accounts/accountSessionReplaysQuery.ts
@@ -0,0 +1,73 @@
+import { apiMutator } from 'lib/api-orval-mutator'
+import { toParams } from 'lib/utils/url'
+
+import { NodeKind, type RecordingsQuery, type RecordingsQueryResponse } from '~/queries/schema/schema-general'
+import { PropertyFilterType, PropertyOperator } from '~/types'
+
+import { getSessionRecordingsListUrl } from 'products/replay/frontend/generated/api'
+
+import { getTileRecord, type AccountViewTileConfig } from './accountViewTileConfig'
+
+export const ACCOUNT_REPLAYS_PAGE_SIZE = 20
+
+export interface AccountReplayDateRange {
+ date_from: string | null
+ date_to: string | null
+}
+
+export function getAccountReplayDateRange(config?: AccountViewTileConfig): AccountReplayDateRange {
+ const dateRange = getTileRecord(config, 'dateRange')
+ return {
+ date_from:
+ typeof dateRange?.date_from === 'string' || dateRange?.date_from === null ? dateRange.date_from : '-7d',
+ date_to: typeof dateRange?.date_to === 'string' ? dateRange.date_to : null,
+ }
+}
+
+export function createAccountReplayQuery(
+ externalId: string,
+ groupTypeIndex: number | null | undefined,
+ dateRange: AccountReplayDateRange,
+ personUUID: string | null,
+ page?: { cursor?: string; offset: number }
+): RecordingsQuery | null {
+ if (
+ !externalId.trim() ||
+ !Number.isInteger(groupTypeIndex) ||
+ groupTypeIndex == null ||
+ groupTypeIndex < 0 ||
+ groupTypeIndex > 4
+ ) {
+ return null
+ }
+ return {
+ kind: NodeKind.RecordingsQuery,
+ ...dateRange,
+ date_from: dateRange.date_from ?? 'all',
+ properties: [
+ {
+ key: `$group_${groupTypeIndex}`,
+ type: PropertyFilterType.Event,
+ operator: PropertyOperator.Exact,
+ value: [externalId],
+ },
+ ],
+ event_match_scope: 'session',
+ person_uuid: personUUID ?? undefined,
+ order: 'start_time',
+ order_direction: 'DESC',
+ limit: ACCOUNT_REPLAYS_PAGE_SIZE,
+ // An explicit offset disables replay cursor pagination, including offset zero.
+ ...(page?.cursor ? { after: page.cursor } : page ? { offset: page.offset } : {}),
+ }
+}
+
+export async function getAccountReplayRecordings(
+ projectId: number,
+ query: RecordingsQuery
+): Promise<RecordingsQueryResponse> {
+ // The generated list response describes Django pagination, but replay returns the RecordingsQuery cursor envelope.
+ // Keep the generated route and the shared query schema instead of copying that contract or changing the replay API.
+ const url = `${getSessionRecordingsListUrl(String(projectId))}?${toParams(query)}`
+ return apiMutator<RecordingsQueryResponse>(url, { method: 'GET' })
+}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountViewComponents.ts b/products/customer_analytics/frontend/components/Accounts/accountViewComponents.ts
index 120a247275ba..c8a111738710 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountViewComponents.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountViewComponents.ts
@@ -3,17 +3,28 @@ import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import type { AccountExpansionTab } from './accountsExpansionLogic'
-export type AccountViewComponentKind = AccountExpansionTab
+export type AccountViewComponentKind = AccountExpansionTab | 'session_replays'
-export interface AccountViewComponentDefinition {
- kind: AccountViewComponentKind
+interface AccountViewComponentBase {
tagName: string
label: string
- systemTabId: `system:${AccountViewComponentKind}`
featureFlag?: FeatureFlagKey
}
+export interface AccountSystemTabDefinition extends AccountViewComponentBase {
+ kind: AccountExpansionTab
+ systemTabId: `system:${AccountExpansionTab}`
+}
+
+export type AccountViewComponentDefinition =
+ | AccountSystemTabDefinition
+ | (AccountViewComponentBase & {
+ kind: 'session_replays'
+ systemTabId?: never
+ })
+
export const ACCOUNT_VIEW_COMPONENTS: AccountViewComponentDefinition[] = [
+ { kind: 'session_replays', tagName: 'SessionReplays', label: 'Session replays' },
{ kind: 'notes', tagName: 'Notes', label: 'Notes', systemTabId: 'system:notes' },
{
kind: 'tasks',
@@ -65,6 +76,12 @@ export function listAvailableAccountViewComponents(featureFlags: FeatureFlagsSet
)
}
+export function listAvailableAccountSystemTabs(featureFlags: FeatureFlagsSet): AccountSystemTabDefinition[] {
+ return listAvailableAccountViewComponents(featureFlags).filter(
+ (component): component is AccountSystemTabDefinition => component.systemTabId !== undefined
+ )
+}
+
export function getAccountViewComponentByKind(
kind: AccountViewComponentKind
): AccountViewComponentDefinition | undefined {
diff --git a/products/customer_analytics/frontend/components/Accounts/constants.ts b/products/customer_analytics/frontend/components/Accounts/constants.ts
index cc5a97d7814f..1c2634721d77 100644
--- a/products/customer_analytics/frontend/components/Accounts/constants.ts
+++ b/products/customer_analytics/frontend/components/Accounts/constants.ts
@@ -70,6 +70,12 @@ export const AccountsEvents = {
MeetingsSearched: 'customer analytics account meetings searched',
MeetingAttendeeClicked: 'customer analytics account meeting attendee clicked',
GongCallOpened: 'customer analytics account gong call opened',
+ ReplaysViewed: 'customer analytics account replays viewed',
+ ReplaysFilterChanged: 'customer analytics account replays filter changed',
+ ReplaysRecordingOpened: 'customer analytics account replay opened',
+ ReplaysLoadMore: 'customer analytics account replays load more',
+ ReplaysLoadFailed: 'customer analytics account replays load failed',
+ ReplaysRetried: 'customer analytics account replays retried',
AccountEditorOpened: 'customer analytics account editor opened',
AccountEdited: 'customer analytics account edited',
EventStreamModalOpened: 'customer analytics account event stream modal opened',
@@ -83,6 +89,22 @@ export const AccountsEvents = {
NotesTabFiltered: 'customer analytics notes tab filtered',
NotesTabNoteClicked: 'customer analytics notes tab note clicked',
NotesTabAccountClicked: 'customer analytics notes tab account clicked',
+ AccountViewEditorOpened: 'customer analytics account view editor opened',
+ AccountViewSaved: 'customer analytics account view saved',
+ AccountViewSaveFailed: 'customer analytics account view save failed',
+ AccountViewTileEditorOpened: 'customer analytics account view tile editor opened',
+ AccountViewTileRenamed: 'customer analytics account view tile renamed',
+ AccountViewTileRenameFailed: 'customer analytics account view tile rename failed',
+ AccountViewTileRemovalStarted: 'customer analytics account view tile removal started',
+ AccountViewTileRemoved: 'customer analytics account view tile removed',
+ AccountViewTileRemovalFailed: 'customer analytics account view tile removal failed',
+ AccountViewDeletionStarted: 'customer analytics account view deletion started',
+ AccountViewDeleted: 'customer analytics account view deleted',
+ AccountViewDeletionFailed: 'customer analytics account view deletion failed',
+ AccountViewTabSettingsOpened: 'customer analytics account view tab settings opened',
+ AccountViewTabSettingsSaveStarted: 'customer analytics account view tab settings save started',
+ AccountViewTabSettingsSaved: 'customer analytics account view tab settings saved',
+ AccountViewTabSettingsSaveFailed: 'customer analytics account view tab settings save failed',
} as const
export type NotesTabFilterType = 'created_by' | 'account' | 'my_notes' | 'my_accounts'
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.test.ts
index a63ab91c48be..0cea51b2ad10 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.test.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.test.ts
@@ -1,9 +1,11 @@
+import { listAvailableAccountViewComponents } from '../../components/Accounts/accountViewComponents'
import type { AccountDetailTabsConfigApi, AccountViewApi } from '../../generated/api.schemas'
import {
getActiveAccountTabId,
getDefaultAccountTabId,
isAccountTabVisible,
listOrderedAccountTabs,
+ listAccountTabs,
listVisibleAccountTabs,
reorderAccountTab,
setAccountTabVisibility,
@@ -29,6 +31,11 @@ const tabs: AccountTabDefinition[] = [
]
describe('account tabs', () => {
+ it('offers replay tiles without adding a system tab', () => {
+ expect(listAvailableAccountViewComponents({}).map((component) => component.kind)).toContain('session_replays')
+ expect(listAccountTabs({}, []).map((tab) => tab.routeKey)).not.toContain('session_replays')
+ })
+
it('falls back from an unavailable system route but keeps an unknown view route', () => {
expect(getActiveAccountTabId(tabs, emptyConfig, 'system:tasks', 1)).toBe('system:notes')
expect(getActiveAccountTabId(tabs, emptyConfig, 'view:missing', 1)).toBe('view:missing')
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.ts
index 420aa7497ede..4c33c14734ee 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountTabs.ts
@@ -1,7 +1,7 @@
import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
import {
- listAvailableAccountViewComponents,
+ listAvailableAccountSystemTabs,
type AccountViewComponentKind,
} from '../../components/Accounts/accountViewComponents'
import type { AccountDetailTabsConfigApi, AccountViewApi } from '../../generated/api.schemas'
@@ -17,7 +17,7 @@ export interface AccountTabDefinition {
export function listAccountTabs(featureFlags: FeatureFlagsSet, views: AccountViewApi[]): AccountTabDefinition[] {
return [
- ...listAvailableAccountViewComponents(featureFlags).map(
+ ...listAvailableAccountSystemTabs(featureFlags).map(
(component): AccountTabDefinition => ({
id: component.systemTabId,
routeKey: component.kind,
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewDocument.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewDocument.test.ts
new file mode 100644
index 000000000000..7635dcbe78e5
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewDocument.test.ts
@@ -0,0 +1,36 @@
+import type { AccountViewContentApi } from '../../generated/api.schemas'
+import {
+ createAccountViewContent,
+ parseAccountViewContent,
+ type AccountViewComponentInstance,
+} from './accountViewDocument'
+
+const components: AccountViewComponentInstance[] = [
+ {
+ nodeId: 'replay-one',
+ kind: 'session_replays',
+ span: 6,
+ title: 'Recent recordings',
+ config: { dateRange: { date_from: '-14d', date_to: null } },
+ },
+]
+const savedContent: AccountViewContentApi = {
+ type: 'doc',
+ content: [
+ {
+ type: 'ph-markdown-notebook',
+ attrs: {
+ nodeId: 'markdown-notebook-v2',
+ markdown:
+ '<SessionReplays nodeId="replay-one" span={6} title="Recent recordings" config={{"dateRange":{"date_from":"-14d","date_to":null}}} />',
+ },
+ },
+ ],
+}
+
+describe('account view document', () => {
+ it('reads and writes replay tile dates in saved Markdown', () => {
+ expect(parseAccountViewContent(savedContent)).toEqual(components)
+ expect(createAccountViewContent(components)).toEqual(savedContent)
+ })
+})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.test.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.test.ts
new file mode 100644
index 000000000000..a6fb0142af01
--- /dev/null
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.test.ts
@@ -0,0 +1,352 @@
+import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
+
+import { ApiError } from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import { AccountsEvents } from '../../components/Accounts/constants'
+import {
+ accountViewsCreate,
+ accountViewsDestroy,
+ accountViewsList,
+ accountViewsPartialUpdate,
+ accountViewsRetrieve,
+ userCustomerAnalyticsConfigPartialUpdate,
+ userCustomerAnalyticsConfigRetrieve,
+} from '../../generated/api'
+import type {
+ AccountDetailTabsConfigApi,
+ AccountViewApi,
+ UserCustomerAnalyticsConfigApi,
+} from '../../generated/api.schemas'
+import { createAccountViewContent, type AccountViewComponentInstance } from './accountViewDocument'
+import { accountViewsLogic, type accountViewsLogicValues } from './accountViewsLogic'
+
+jest.mock('../../generated/api', () => ({
+ ...jest.requireActual('../../generated/api'),
+ accountViewsCreate: jest.fn(),
+ accountViewsDestroy: jest.fn(),
+ accountViewsList: jest.fn(),
+ accountViewsPartialUpdate: jest.fn(),
+ accountViewsRetrieve: jest.fn(),
+ userCustomerAnalyticsConfigPartialUpdate: jest.fn(),
+ userCustomerAnalyticsConfigRetrieve: jest.fn(),
+}))
+
+const components: AccountViewComponentInstance[] = [
+ {
+ nodeId: 'example-private-note',
+ kind: 'notes',
+ span: 6,
+ title: 'Invented private tile title',
+ config: { searchTerm: 'invented-private-search' },
+ },
+ {
+ nodeId: 'example-private-usage',
+ kind: 'usage',
+ span: 6,
+ config: { dateRange: { date_from: '-14d', date_to: null } },
+ },
+]
+const view: AccountViewApi = {
+ id: '11111111-2222-4333-8444-555555555555',
+ name: 'Invented private view name',
+ visibility: 'private',
+ content: createAccountViewContent(components),
+ text_content: 'Invented private view content',
+ version: 1,
+ created_by: 1,
+ last_modified_by: 1,
+ created_at: '2026-06-01T00:00:00Z',
+ updated_at: '2026-06-01T00:00:00Z',
+ can_edit: true,
+ can_delete: true,
+ can_change_visibility: true,
+}
+const updatedView: AccountViewApi = { ...view, version: 2 }
+const createdView: AccountViewApi = { ...updatedView, id: '66666666-7777-4888-8999-000000000000' }
+const removedTileView: AccountViewApi = { ...updatedView, content: createAccountViewContent(components.slice(1)) }
+const tabSettings: AccountDetailTabsConfigApi = {
+ ordered_tab_ids: ['system:notes', `view:${view.id}`],
+ hidden_tab_ids: ['system:usage'],
+ default_tab_id: `view:${view.id}`,
+}
+const userConfig: UserCustomerAnalyticsConfigApi = {
+ pinned_properties: [],
+ task_digest: { enabled: false, send_time: '09:00', cadence: 'weekdays' },
+ account_detail_tabs: { ordered_tab_ids: [], hidden_tab_ids: [], default_tab_id: null },
+}
+const updatedUserConfig: UserCustomerAnalyticsConfigApi = { ...userConfig, account_detail_tabs: tabSettings }
+
+type Capture = Parameters<typeof posthog.capture>
+type WriteFailure = { status: number; failureType: 'conflict' | 'request' }
+interface WriteScenario {
+ operation: 'create' | 'save' | 'rename' | 'remove' | 'delete' | 'tabs'
+ start: () => void
+ mockWrite: (write: () => Promise<void>) => void
+ entries: Capture[]
+ success: Capture
+ successValues: Partial<accountViewsLogicValues>
+ failureValues: Partial<accountViewsLogicValues>
+ showsEditorConflict: boolean
+ failureEvent: string
+ failureContext?: { is_new: boolean }
+ failures: WriteFailure[]
+}
+const conflictFailures: WriteFailure[] = [
+ { status: 409, failureType: 'conflict' },
+ { status: 500, failureType: 'request' },
+]
+
+function createDeferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
+ let resolve!: (value: T) => void
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise
+ })
+ return { promise, resolve }
+}
+
+describe('accountViewsLogic tracking', () => {
+ let logic: ReturnType<typeof accountViewsLogic.build>
+ let capture: jest.SpiedFunction<typeof posthog.capture>
+ const mockCreate = jest.mocked(accountViewsCreate)
+ const mockUpdate = jest.mocked(accountViewsPartialUpdate)
+ const mockDelete = jest.mocked(accountViewsDestroy)
+ const mockConfigUpdate = jest.mocked(userCustomerAnalyticsConfigPartialUpdate)
+ const scenarios: WriteScenario[] = [
+ {
+ operation: 'create',
+ start: () => {
+ logic.actions.openCreateEditor()
+ logic.actions.setEditorName('Invented private input name')
+ logic.actions.addEditorComponent('notes')
+ logic.actions.addEditorComponent('usage')
+ logic.actions.saveEditor()
+ },
+ mockWrite: (write) => mockCreate.mockImplementationOnce(() => write().then(() => createdView)),
+ entries: [[AccountsEvents.AccountViewEditorOpened, { is_new: true }]],
+ success: [AccountsEvents.AccountViewSaved, { is_new: true, component_count: 2 }],
+ successValues: { views: [view, createdView] },
+ failureValues: { editorOpen: true },
+ showsEditorConflict: true,
+ failureEvent: AccountsEvents.AccountViewSaveFailed,
+ failureContext: { is_new: true },
+ failures: conflictFailures,
+ },
+ {
+ operation: 'save',
+ start: () => {
+ logic.actions.openEditEditor(view)
+ logic.actions.setEditorName('Invented private input name')
+ logic.actions.saveEditor()
+ },
+ mockWrite: (write) => mockUpdate.mockImplementationOnce(() => write().then(() => updatedView)),
+ entries: [[AccountsEvents.AccountViewEditorOpened, { is_new: false }]],
+ success: [AccountsEvents.AccountViewSaved, { is_new: false, component_count: 2 }],
+ successValues: { views: [updatedView] },
+ failureValues: { editorOpen: true },
+ showsEditorConflict: true,
+ failureEvent: AccountsEvents.AccountViewSaveFailed,
+ failureContext: { is_new: false },
+ failures: conflictFailures,
+ },
+ {
+ operation: 'rename',
+ start: () => {
+ logic.actions.openTileEditor(view.id, components[0].nodeId, 'Invented private input title')
+ logic.actions.saveTileEditor()
+ },
+ mockWrite: (write) => mockUpdate.mockImplementationOnce(() => write().then(() => updatedView)),
+ entries: [[AccountsEvents.AccountViewTileEditorOpened]],
+ success: [AccountsEvents.AccountViewTileRenamed, { component_count: 2 }],
+ successValues: { views: [updatedView] },
+ failureValues: {},
+ showsEditorConflict: false,
+ failureEvent: AccountsEvents.AccountViewTileRenameFailed,
+ failures: conflictFailures,
+ },
+ {
+ operation: 'remove',
+ start: () => logic.actions.removeViewComponent(view.id, components[0].nodeId),
+ mockWrite: (write) => mockUpdate.mockImplementationOnce(() => write().then(() => removedTileView)),
+ entries: [[AccountsEvents.AccountViewTileRemovalStarted]],
+ success: [AccountsEvents.AccountViewTileRemoved, { component_count: 1 }],
+ successValues: { views: [removedTileView] },
+ failureValues: {},
+ showsEditorConflict: false,
+ failureEvent: AccountsEvents.AccountViewTileRemovalFailed,
+ failures: conflictFailures,
+ },
+ {
+ operation: 'delete',
+ start: () => logic.actions.deleteView(view.id, view.version),
+ mockWrite: (write) => mockDelete.mockImplementationOnce(write),
+ entries: [[AccountsEvents.AccountViewDeletionStarted]],
+ success: [AccountsEvents.AccountViewDeleted],
+ successValues: { views: [] },
+ failureValues: { views: [view] },
+ showsEditorConflict: true,
+ failureEvent: AccountsEvents.AccountViewDeletionFailed,
+ failures: conflictFailures,
+ },
+ {
+ operation: 'tabs',
+ start: () => {
+ logic.actions.openConfigure(tabSettings)
+ logic.actions.saveConfig()
+ },
+ mockWrite: (write) => mockConfigUpdate.mockImplementationOnce(() => write().then(() => updatedUserConfig)),
+ entries: [
+ [AccountsEvents.AccountViewTabSettingsOpened],
+ [AccountsEvents.AccountViewTabSettingsSaveStarted],
+ ],
+ success: [
+ AccountsEvents.AccountViewTabSettingsSaved,
+ { has_default: true, ordered_count: 2, hidden_count: 1 },
+ ],
+ successValues: { config: updatedUserConfig, configureOpen: false },
+ failureValues: { configureOpen: true, configSaving: false },
+ showsEditorConflict: false,
+ failureEvent: AccountsEvents.AccountViewTabSettingsSaveFailed,
+ failures: [
+ { status: 409, failureType: 'request' },
+ { status: 500, failureType: 'request' },
+ ],
+ },
+ ]
+
+ beforeEach(async () => {
+ jest.clearAllMocks()
+ initKeaTests(false)
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.CUSTOMER_ANALYTICS_ACCOUNT_VIEWS]: true })
+ jest.mocked(accountViewsList).mockResolvedValue([view])
+ jest.mocked(accountViewsRetrieve).mockResolvedValue(updatedView)
+ jest.mocked(userCustomerAnalyticsConfigRetrieve).mockResolvedValue(userConfig)
+ mockCreate.mockReset().mockResolvedValue(view)
+ mockUpdate.mockReset().mockResolvedValue(view)
+ mockDelete.mockReset().mockResolvedValue(undefined)
+ mockConfigUpdate.mockReset().mockResolvedValue(userConfig)
+ jest.spyOn(lemonToast, 'error').mockImplementation(() => 'example-error-toast')
+ capture = jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
+ logic = accountViewsLogic({ projectId: 1 })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ featureFlagLogic.unmount()
+ jest.restoreAllMocks()
+ })
+
+ function getAccountViewCaptures(): Capture[] {
+ return capture.mock.calls.filter(([event]) => event.startsWith('customer analytics account view '))
+ }
+
+ it.each(scenarios)(
+ 'reports $operation only after acknowledgement with exactly the allowed properties',
+ async (scenario) => {
+ const response = createDeferred<void>()
+ const started = createDeferred<void>()
+ scenario.mockWrite(async () => {
+ started.resolve(undefined)
+ await response.promise
+ })
+ scenario.start()
+ await started.promise
+ expect(getAccountViewCaptures()).toEqual(scenario.entries)
+ response.resolve(undefined)
+ await expectLogic(logic).toFinishAllListeners()
+ expect(getAccountViewCaptures()).toEqual([...scenario.entries, scenario.success])
+ expect(logic.values).toMatchObject(scenario.successValues)
+ }
+ )
+
+ it.each(scenarios.flatMap((scenario) => scenario.failures.map((failure) => ({ ...scenario, ...failure }))))(
+ 'reports failed $operation ($status) without success or private error content',
+ async (scenario) => {
+ scenario.mockWrite(async () => {
+ throw new ApiError('Invented private error message', scenario.status, undefined, {
+ detail: 'Invented private error response',
+ })
+ })
+ scenario.start()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(getAccountViewCaptures()).toEqual([
+ ...scenario.entries,
+ [scenario.failureEvent, { ...scenario.failureContext, failure_type: scenario.failureType }],
+ ])
+ expect(JSON.stringify(capture.mock.calls)).not.toMatch(
+ /Invented|11111111|example-private|invented-private|-14d/
+ )
+ expect(logic.values).toMatchObject({
+ ...scenario.failureValues,
+ editorConflict: scenario.showsEditorConflict && scenario.failureType === 'conflict',
+ })
+ }
+ )
+
+ it.each(['editor', 'tabs'])(
+ 'does not report another %s entry or save for reloads or generic success actions',
+ async (surface) => {
+ if (surface === 'editor') {
+ logic.actions.openEditEditor(view)
+ logic.actions.reloadEditor()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.saveEditorSuccess(view)
+ logic.actions.updateViewComponentConfig(view.id, components[0].nodeId, {
+ searchTerm: 'Invented private new config',
+ })
+ } else {
+ logic.actions.openConfigure(tabSettings)
+ logic.actions.openConfigure(tabSettings)
+ logic.actions.loadConfigSuccess(userConfig)
+ logic.actions.saveConfigSuccess(userConfig)
+ }
+ await expectLogic(logic).toFinishAllListeners()
+ const expectedEntry =
+ surface === 'editor'
+ ? [AccountsEvents.AccountViewEditorOpened, { is_new: false }]
+ : [AccountsEvents.AccountViewTabSettingsOpened]
+ expect(getAccountViewCaptures()).toEqual([expectedEntry])
+ if (surface === 'editor') {
+ logic.actions.setEditorOpen(false)
+ logic.actions.openEditEditor(view)
+ } else {
+ logic.actions.setConfigureOpen(false)
+ logic.actions.openConfigure(tabSettings)
+ }
+ expect(getAccountViewCaptures()).toEqual([expectedEntry, expectedEntry])
+ }
+ )
+
+ it.each(['editor', 'tabs'])('reports a blocked %s save without a write or success', async (surface) => {
+ if (surface === 'editor') {
+ logic.actions.openCreateEditor()
+ logic.actions.saveEditor()
+ } else {
+ logic.actions.openConfigure(tabSettings)
+ logic.actions.loadConfigFailure(new ApiError('Invented private load error', 500))
+ logic.actions.saveConfig()
+ }
+ await expectLogic(logic).toFinishAllListeners()
+ expect(mockCreate).not.toHaveBeenCalled()
+ expect(mockConfigUpdate).not.toHaveBeenCalled()
+ expect(getAccountViewCaptures()).toEqual(
+ surface === 'editor'
+ ? [
+ [AccountsEvents.AccountViewEditorOpened, { is_new: true }],
+ [AccountsEvents.AccountViewSaveFailed, { is_new: true, failure_type: 'validation' }],
+ ]
+ : [
+ [AccountsEvents.AccountViewTabSettingsOpened],
+ [AccountsEvents.AccountViewTabSettingsSaveFailed, { failure_type: 'unavailable' }],
+ ]
+ )
+ })
+})
diff --git a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.ts b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.ts
index f16f5c52a23b..8b509fd5c80b 100644
--- a/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.ts
+++ b/products/customer_analytics/frontend/scenes/CustomerAnalyticsAccountScene/accountViewsLogic.ts
@@ -1,13 +1,14 @@
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import posthog from 'posthog-js'
import { ApiError } from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic, type FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
-import type { AccountExpansionTab } from '../../components/Accounts/accountsExpansionLogic'
import type { AccountViewComponentKind } from '../../components/Accounts/accountViewComponents'
import type { AccountViewTileConfig } from '../../components/Accounts/accountViewTileConfig'
+import { AccountsEvents } from '../../components/Accounts/constants'
import {
accountViewsCreate,
accountViewsDestroy,
@@ -88,7 +89,7 @@ export interface accountViewsLogicActions {
variants: Record<string, boolean | string>
} // featureFlagLogic
addEditorComponent: (kind: AccountViewComponentKind) => {
- kind: AccountExpansionTab
+ kind: AccountViewComponentKind
}
closeTileEditor: () => {
value: true
@@ -257,6 +258,10 @@ export type accountViewsLogicType = MakeLogicType<
accountViewsLogicMeta
>
+function getAccountViewFailureType(error: unknown): 'conflict' | 'request' {
+ return error instanceof ApiError && error.status === 409 ? 'conflict' : 'request'
+}
+
function updateAccountViewComponents(
projectId: number,
view: AccountViewApi,
@@ -604,18 +609,40 @@ export const accountViewsLogic = kea<accountViewsLogicType>([
actions.setConfigDraft(config.account_detail_tabs)
}
},
- openCreateEditor: () => actions.setEditorOpen(true),
- openEditEditor: () => actions.setEditorOpen(true),
- openConfigure: () => actions.setConfigureOpen(true),
+ openCreateEditor: () => {
+ if (!values.editorOpen) {
+ posthog.capture(AccountsEvents.AccountViewEditorOpened, { is_new: true })
+ }
+ actions.setEditorOpen(true)
+ },
+ openEditEditor: () => {
+ // Reloading an open editor reuses this action.
+ if (!values.editorOpen) {
+ posthog.capture(AccountsEvents.AccountViewEditorOpened, { is_new: false })
+ }
+ actions.setEditorOpen(true)
+ },
+ openTileEditor: () => {
+ posthog.capture(AccountsEvents.AccountViewTileEditorOpened)
+ },
+ openConfigure: () => {
+ if (!values.configureOpen) {
+ posthog.capture(AccountsEvents.AccountViewTabSettingsOpened)
+ }
+ actions.setConfigureOpen(true)
+ },
saveEditor: async () => {
const editingView = values.editingView
+ const isNew = !editingView
const canEditContent = !editingView || editingView.can_edit
if (canEditContent && (!values.editorDraft.name.trim() || values.editorDraft.components.length === 0)) {
+ posthog.capture(AccountsEvents.AccountViewSaveFailed, { is_new: isNew, failure_type: 'validation' })
actions.saveEditorFailure()
return
}
try {
const content = createAccountViewContent(values.editorDraft.components)
+ const componentCount = values.editorDraft.components.length
const view = editingView
? await accountViewsPartialUpdate(String(props.projectId), editingView.id, {
...(editingView.can_edit ? { name: values.editorDraft.name.trim(), content } : {}),
@@ -626,10 +653,19 @@ export const accountViewsLogic = kea<accountViewsLogicType>([
name: values.editorDraft.name.trim(),
content,
})
+ posthog.capture(AccountsEvents.AccountViewSaved, {
+ is_new: isNew,
+ component_count: componentCount,
+ })
actions.saveEditorSuccess(view)
actions.setEditorOpen(false)
} catch (error) {
- if (error instanceof ApiError && error.status === 409) {
+ const failureType = getAccountViewFailureType(error)
+ posthog.capture(AccountsEvents.AccountViewSaveFailed, {
+ is_new: isNew,
+ failure_type: failureType,
+ })
+ if (failureType === 'conflict') {
actions.setEditorConflict(true)
} else {
lemonToast.error("Couldn't save the view. Try again.")
@@ -650,12 +686,18 @@ export const accountViewsLogic = kea<accountViewsLogicType>([
}
},
deleteView: async ({ viewId, version }) => {
+ posthog.capture(AccountsEvents.AccountViewDeletionStarted)
try {
await accountViewsDestroy(String(props.projectId), viewId, { version })
+ posthog.capture(AccountsEvents.AccountViewDeleted)
actions.deleteViewSuccess(viewId)
actions.setEditorOpen(false)
} catch (error) {
- if (error instanceof ApiError && error.status === 409) {
+ const failureType = getAccountViewFailureType(error)
+ posthog.capture(AccountsEvents.AccountViewDeletionFailed, {
+ failure_type: failureType,
+ })
+ if (failureType === 'conflict') {
actions.setEditorConflict(true)
} else {
lemonToast.error("Couldn't delete the view. Try again.")
@@ -666,6 +708,7 @@ export const accountViewsLogic = kea<accountViewsLogicType>([
saveTileEditor: async () => {
const tileEditor = values.tileEditor
if (!tileEditor) {
+ posthog.capture(AccountsEvents.AccountViewTileRenameFailed, { failure_type: 'validation' })
actions.saveViewComponentFailure()
return
}
@@ -673,6 +716,7 @@ export const accountViewsLogic = kea<accountViewsLogicType>([
const view = values.views.find((candidate) => candidate.id === tileEditor.viewId)
const name = tileEditor.name.trim()
if (!view || !name) {
+ posthog.capture(AccountsEvents.AccountViewTileRenameFailed, { failure_type: 'validation' })
actions.saveViewComponentFailure()
return
}
@@ -680,11 +724,17 @@ export const accountViewsLogic = kea<accountViewsLogicType>([
component.nodeId === tileEditor.nodeId ? { ...component, title: name } : component
)
try {
- actions.saveEditorSuccess(await updateAccountViewComponents(props.projectId, view, components))
+ const updatedView = await updateAccountViewComponents(props.projectId, view, components)
+ posthog.capture(AccountsEvents.AccountViewTileRenamed, { component_count: components.length })
+ actions.saveEditorSuccess(updatedView)
actions.closeTileEditor()
} catch (error) {
+ const failureType = getAccountViewFailureType(error)
+ posthog.capture(AccountsEvents.AccountViewTileRenameFailed, {
+ failure_type: failureType,
+ })
lemonToast.error(
- error instanceof ApiError && error.status === 409
+ failureType === 'conflict'
? 'This view changed. Refresh and try again.'
: "Couldn't rename the tile. Try again."
)
@@ -727,16 +777,25 @@ export const accountViewsLogic = kea<accountViewsLogicType>([
},
saveConfig: async () => {
if (values.configError || !values.config) {
+ posthog.capture(AccountsEvents.AccountViewTabSettingsSaveFailed, { failure_type: 'unavailable' })
actions.saveConfigFailure()
return
}
+ const settingsSummary = {
+ has_default: !!values.configDraft.default_tab_id,
+ ordered_count: values.configDraft.ordered_tab_ids.length,
+ hidden_count: values.configDraft.hidden_tab_ids.length,
+ }
+ posthog.capture(AccountsEvents.AccountViewTabSettingsSaveStarted)
try {
const config = await userCustomerAnalyticsConfigPartialUpdate(String(props.projectId), '@me', {
account_detail_tabs: values.configDraft,
})
+ posthog.capture(AccountsEvents.AccountViewTabSettingsSaved, settingsSummary)
actions.saveConfigSuccess(config)
actions.setConfigureOpen(false)
} catch {
+ posthog.capture(AccountsEvents.AccountViewTabSettingsSaveFailed, { failure_type: 'request' })
actions.saveConfigFailure()
lemonToast.error("Couldn't save the tab settings. Try again.")
}
@@ -745,6 +804,7 @@ export const accountViewsLogic = kea<accountViewsLogicType>([
await queueViewWrite(cache, viewId, async () => {
const view = values.views.find((candidate) => candidate.id === viewId)
if (!view) {
+ posthog.capture(AccountsEvents.AccountViewTileRemovalFailed, { failure_type: 'validation' })
actions.saveViewComponentFailure()
return
}
@@ -752,14 +812,22 @@ export const accountViewsLogic = kea<accountViewsLogicType>([
(component) => component.nodeId !== nodeId
)
if (components.length === 0) {
+ posthog.capture(AccountsEvents.AccountViewTileRemovalFailed, { failure_type: 'validation' })
actions.saveViewComponentFailure()
return
}
+ posthog.capture(AccountsEvents.AccountViewTileRemovalStarted)
try {
- actions.saveEditorSuccess(await updateAccountViewComponents(props.projectId, view, components))
+ const updatedView = await updateAccountViewComponents(props.projectId, view, components)
+ posthog.capture(AccountsEvents.AccountViewTileRemoved, { component_count: components.length })
+ actions.saveEditorSuccess(updatedView)
} catch (error) {
+ const failureType = getAccountViewFailureType(error)
+ posthog.capture(AccountsEvents.AccountViewTileRemovalFailed, {
+ failure_type: failureType,
+ })
lemonToast.error(
- error instanceof ApiError && error.status === 409
+ failureType === 'conflict'
? 'This view changed. Refresh and try again.'
: "Couldn't remove the tile. Try again."
)