:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(web-analytics): Add session replays to web analytics live dashboard (#59318)
Jordan Mryyan60b4a245d373
diff --git a/frontend/src/scenes/activity/live/LiveEventsFeed.tsx b/frontend/src/scenes/activity/live/LiveEventsFeed.tsxindex 7d4e5802d77f..8356631b20be 100644--- a/frontend/src/scenes/activity/live/LiveEventsFeed.tsx+++ b/frontend/src/scenes/activity/live/LiveEventsFeed.tsx@@ -9,6 +9,7 @@ import { Spinner, Tooltip } from '@posthog/lemon-ui'import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { TZLabel } from 'lib/components/TZLabel'+import ViewRecordingButton, { RecordingPlayerType } from 'lib/components/ViewRecordingButton/ViewRecordingButton'import { More } from 'lib/lemon-ui/LemonButton/More'import { LemonTable, LemonTableColumn } from 'lib/lemon-ui/LemonTable'import { PersonDisplay } from 'scenes/persons/PersonDisplay'@@ -16,9 +17,9 @@ import { PersonDisplay } from 'scenes/persons/PersonDisplay'import { EventCopyLinkButton } from '~/queries/nodes/DataTable/EventRowActions'import { LiveEvent } from '~/types'-export type LiveEventsFeedColumn = 'event' | 'person' | 'url' | 'timestamp' | 'more'+export type LiveEventsFeedColumn = 'event' | 'person' | 'url' | 'recording' | 'timestamp' | 'more'-const ALL_COLUMNS: LiveEventsFeedColumn[] = ['event', 'person', 'url', 'timestamp', 'more']+const ALL_COLUMNS: LiveEventsFeedColumn[] = ['event', 'person', 'url', 'recording', 'timestamp', 'more']const COLUMN_DEFINITIONS: Record<LiveEventsFeedColumn, LemonTableColumn<LiveEvent, keyof LiveEvent | undefined>> = {event: {@@ -53,6 +54,28 @@ const COLUMN_DEFINITIONS: Record<LiveEventsFeedColumn, LemonTableColumn<LiveEven)},},+ recording: {+ title: '',+ key: 'recording' as any,+ width: 0,+ render: function Render(_, event: LiveEvent) {+ const sessionId = event.properties.$session_id+ if (typeof sessionId !== 'string' || !sessionId) {+ return null+ }+ return (+ <ViewRecordingButton+ iconOnly+ sessionId={sessionId}+ timestamp={event.timestamp}+ openPlayerIn={RecordingPlayerType.NewTab}+ size="xsmall"+ type="secondary"+ data-attr="live-events-feed-watch"+ />+ )+ },+ },timestamp: {title: 'Time',key: 'timestamp',diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDown.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDown.tsxindex cd6274a94a8d..7bf630a0250d 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDown.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDown.tsx@@ -26,8 +26,16 @@ const LivePersonDrillDownInner = ({ selection }: { selection: LivePersonDrillDowbreakdownType: selection.breakdownType,breakdownValue: selection.breakdownValue,}- const { persons, personsLoading, totalCount, identifiedCount, anonymousCount, newVisitorCount, isTruncated } =- useValues(livePersonDrillDownLogic(logicProps))+ const {+ persons,+ personsLoading,+ totalCount,+ identifiedCount,+ anonymousCount,+ newVisitorCount,+ isTruncated,+ recordingCountByPersonKey,+ } = useValues(livePersonDrillDownLogic(logicProps))const { refresh } = useActions(livePersonDrillDownLogic(logicProps))const title = `${BREAKDOWN_TITLE_PREFIX[selection.breakdownType]} ${selection.breakdownLabel}`@@ -93,9 +101,16 @@ const LivePersonDrillDownInner = ({ selection }: { selection: LivePersonDrillDow{isTruncated ? ` of ${identifiedCount.toLocaleString()}` : ''})</div><div className="flex flex-col">- {persons.map((person) => (- <LivePersonDrillDownRow key={person.id ?? person.uuid} person={person} />- ))}+ {persons.map((person) => {+ const key = person.id ?? person.uuid+ return (+ <LivePersonDrillDownRow+ key={key}+ person={person}+ recordingCount={key ? recordingCountByPersonKey[key] : undefined}+ />+ )+ })}</div>{isTruncated && (<div className="text-xs text-muted mt-2">diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsxindex 096a246b321e..c2f61f46a8ec 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LivePersonDrillDownRow.tsx@@ -1,13 +1,16 @@-import { Link } from '@posthog/lemon-ui'+import { IconPlay } from '@posthog/icons'+import { LemonButton, Link } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'+import { pluralize } from 'lib/utils'import { PersonDisplay } from 'scenes/persons/PersonDisplay'import { urls } from 'scenes/urls'-import { PersonType } from '~/types'+import { PersonsTabType, PersonType } from '~/types'interface LivePersonDrillDownRowProps {person: PersonType+ recordingCount?: number}const pickSecondaryProperty = (person: PersonType): { key: string; value: string } | null => {@@ -21,29 +24,46 @@ const pickSecondaryProperty = (person: PersonType): { key: string; value: stringreturn null}-export const LivePersonDrillDownRow = ({ person }: LivePersonDrillDownRowProps): JSX.Element => {+const recordingsUrlForPerson = (distinctId: string): string =>+ `${urls.personByDistinctId(distinctId)}#activeTab=${PersonsTabType.SESSION_RECORDINGS}`++export const LivePersonDrillDownRow = ({ person, recordingCount }: LivePersonDrillDownRowProps): JSX.Element => {const distinctId = person.distinct_ids?.[0]const secondary = pickSecondaryProperty(person)const href = distinctId ? urls.personByDistinctId(distinctId) : undefinedreturn (- <Link- to={href}- subtle- className="flex items-center gap-3 px-2 py-2 -mx-2 rounded hover:bg-bg-3000"- data-attr="live-person-drilldown-row"- >- <PersonDisplay person={person} withIcon noPopover noLink />- {secondary && (- <span className="flex-1 min-w-0 text-xs text-muted truncate ph-no-capture">- {secondary.key === 'email' ? secondary.value : `${secondary.key}: ${secondary.value}`}- </span>+ <div className="flex items-center gap-3" data-attr="live-person-drilldown-row">+ <Link+ to={href}+ subtle+ className="flex items-center gap-3 min-w-0 flex-1 px-2 py-2 -mx-2 rounded hover:bg-bg-3000"+ >+ <PersonDisplay person={person} withIcon noPopover noLink />+ {secondary && (+ <span className="min-w-0 text-xs text-muted truncate ph-no-capture">+ {secondary.key === 'email' ? secondary.value : `${secondary.key}: ${secondary.value}`}+ </span>+ )}+ </Link>+ {recordingCount && recordingCount > 0 && distinctId && (+ <LemonButton+ size="xsmall"+ type="secondary"+ icon={<IconPlay />}+ to={recordingsUrlForPerson(distinctId)}+ targetBlank+ tooltip={`Watch ${pluralize(recordingCount, 'recording')} from the last 30 minutes`}+ data-attr="live-person-drilldown-row-watch"+ >+ {recordingCount.toLocaleString()}+ </LemonButton>)}{person.last_seen_at && (- <span className="text-xs text-muted shrink-0 ml-auto">+ <span className="text-xs text-muted shrink-0"><TZLabel time={person.last_seen_at} /></span>)}- </Link>+ </div>)}diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsxindex 80c07dca484e..3b312885dbb5 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/LiveWebAnalyticsMetrics.tsx@@ -26,6 +26,7 @@ import { IconWithCount } from 'lib/lemon-ui/icons/icons'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { COUNTRY_CODE_TO_LONG_NAME, countryCodeToFlag } from 'lib/utils/geography/country'import { LiveEventsFeed, LiveEventsFeedColumn } from 'scenes/activity/live/LiveEventsFeed'+import { teamLogic } from 'scenes/teamLogic'import { PropertyOperator } from '~/types'@@ -55,7 +56,8 @@ import {} from './LiveWebAnalyticsMetricsTypes'import { LiveWorldMap } from './LiveWorldMap'-const LIVE_FEED_COLUMNS: LiveEventsFeedColumn[] = ['event', 'person', 'url', 'timestamp']+const LIVE_FEED_COLUMNS_WITH_RECORDINGS: LiveEventsFeedColumn[] = ['event', 'person', 'url', 'recording', 'timestamp']+const LIVE_FEED_COLUMNS_WITHOUT_RECORDINGS: LiveEventsFeedColumn[] = ['event', 'person', 'url', 'timestamp']const STATS_POLL_INTERVAL_MS = 1000const renderBrowserIcon = (d: BrowserBreakdownItem): JSX.Element => {@@ -291,8 +293,12 @@ export const LiveWebAnalyticsMetrics = (): JSX.Element => {const { setStatOrder, setCardOrder, setEditing, resetLayout } = useActions(liveWebAnalyticsLayoutLogic)const { featureFlags } = useValues(featureFlagLogic)+ const { currentTeam } = useValues(teamLogic)const canEditLayout = !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_LIVE_EDIT_LAYOUT]const drillDownEnabled = !!featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_LIVE_PERSON_DRILLDOWN]+ const liveFeedColumns = currentTeam?.session_recording_opt_in+ ? LIVE_FEED_COLUMNS_WITH_RECORDINGS+ : LIVE_FEED_COLUMNS_WITHOUT_RECORDINGSconst { openDrillDown } = useActions(livePersonDrillDownDrawerLogic)const isEditing = canEditLayout && isEditingRaw@@ -493,7 +499,7 @@ export const LiveWebAnalyticsMetrics = (): JSX.Element => {case 'live_events':return (<LiveChartCard title="Live events" isLoading={false} contentClassName="max-h-80 overflow-y-auto">- <LiveEventsFeed events={recentEvents} columns={LIVE_FEED_COLUMNS} />+ <LiveEventsFeed events={recentEvents} columns={liveFeedColumns} /></LiveChartCard>)}diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownLogic.test.ts b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownLogic.test.tsindex 6f21b372999d..6c3c6c86425a 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownLogic.test.ts+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownLogic.test.ts@@ -1,9 +1,22 @@import { expectLogic } from 'kea-test-utils'import { initKeaTests } from '~/test/init'+import { PersonType } from '~/types'import { livePersonDrillDownDrawerLogic, LivePersonDrillDownSelection } from './livePersonDrillDownDrawerLogic'-import { COOKIELESS_DISTINCT_ID_PREFIX, partitionDistinctIds } from './livePersonDrillDownLogic'+import {+ aggregateRecordingCountsByPerson,+ COOKIELESS_DISTINCT_ID_PREFIX,+ partitionDistinctIds,+} from './livePersonDrillDownLogic'++const makePerson = (overrides: Partial<PersonType> & { id?: string | number; uuid?: string }): PersonType =>+ ({+ distinct_ids: [],+ properties: {},+ created_at: '2020-01-01T00:00:00Z',+ ...overrides,+ }) as PersonTypedescribe('partitionDistinctIds', () => {it('separates cookieless ids from identified ones', () => {@@ -48,6 +61,49 @@ describe('partitionDistinctIds', () => {})})+describe('aggregateRecordingCountsByPerson', () => {+ it("sums counts across each person's distinct_ids", () => {+ const persons = [+ makePerson({ id: 'person-a', distinct_ids: ['d1', 'd2'] }),+ makePerson({ id: 'person-b', distinct_ids: ['d3'] }),+ ]+ const counts = { d1: 2, d2: 3, d3: 1 }+ expect(aggregateRecordingCountsByPerson(persons, counts)).toEqual({+ 'person-a': 5,+ 'person-b': 1,+ })+ })++ it('omits persons with zero recordings', () => {+ const persons = [+ makePerson({ id: 'person-a', distinct_ids: ['d1'] }),+ makePerson({ id: 'person-b', distinct_ids: ['d2'] }),+ ]+ const counts = { d2: 4 }+ expect(aggregateRecordingCountsByPerson(persons, counts)).toEqual({ 'person-b': 4 })+ })++ it('falls back to uuid when id is missing', () => {+ const persons = [makePerson({ uuid: 'uuid-1', distinct_ids: ['d1'] })]+ expect(aggregateRecordingCountsByPerson(persons, { d1: 7 })).toEqual({ 'uuid-1': 7 })+ })++ it('skips persons with no id and no uuid', () => {+ const persons = [makePerson({ distinct_ids: ['d1'] })]+ expect(aggregateRecordingCountsByPerson(persons, { d1: 1 })).toEqual({})+ })++ it('ignores distinct_ids that are not present in the counts map', () => {+ const persons = [makePerson({ id: 'person-a', distinct_ids: ['d1', 'd-missing'] })]+ expect(aggregateRecordingCountsByPerson(persons, { d1: 2 })).toEqual({ 'person-a': 2 })+ })++ it('returns an empty object when no persons have recordings', () => {+ const persons = [makePerson({ id: 'person-a', distinct_ids: ['d1'] })]+ expect(aggregateRecordingCountsByPerson(persons, {})).toEqual({})+ })+})+describe('livePersonDrillDownDrawerLogic', () => {let logic: ReturnType<typeof livePersonDrillDownDrawerLogic.build>diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownLogic.ts b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownLogic.tsindex 4c61832e9cc3..797f65d4cdbe 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownLogic.ts+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/livePersonDrillDownLogic.ts@@ -3,6 +3,7 @@ import { actions, connect, events, kea, key, listeners, path, props, reducers, simport { loaders } from 'kea-loaders'import { parsePersonFromHogQLRow } from 'scenes/persons/person-utils'+import { teamLogic } from 'scenes/teamLogic'import { WEB_ANALYTICS_DEFAULT_QUERY_TAGS } from 'scenes/web-analytics/common'import { performQuery } from '~/queries/query'@@ -36,6 +37,27 @@ export const partitionDistinctIds = (distinctIds: string[]): { identified: strinreturn { identified, anonymous }}+export const aggregateRecordingCountsByPerson = (+ persons: PersonType[],+ countsByDistinctId: Record<string, number>+): Record<string, number> => {+ const byKey: Record<string, number> = {}+ for (const person of persons) {+ const key = person.id ?? person.uuid+ if (!key) {+ continue+ }+ let total = 0+ for (const distinctId of person.distinct_ids ?? []) {+ total += countsByDistinctId[distinctId] ?? 0+ }+ if (total > 0) {+ byKey[key] = total+ }+ }+ return byKey+}+export const livePersonDrillDownLogic = kea<livePersonDrillDownLogicType>([props({} as LivePersonDrillDownLogicProps),key((p) => `${p.breakdownType}:${p.breakdownValue}`),@@ -46,12 +68,14 @@ export const livePersonDrillDownLogic = kea<livePersonDrillDownLogicType>([['slidingWindow', 'eventsVersion', 'geoVersion'],livePersonDrillDownDrawerLogic,['currentSelection'],+ teamLogic,+ ['currentTeam'],],})),actions({refresh: true,}),- loaders(() => ({+ loaders(({ values }) => ({persons: [[] as PersonType[],{@@ -108,6 +132,43 @@ export const livePersonDrillDownLogic = kea<livePersonDrillDownLogicType>([},},],+ recordingCountsByDistinctId: [+ {} as Record<string, number>,+ {+ loadRecordingCounts: async ({ distinctIds }: { distinctIds: string[] }) => {+ if (!values.currentTeam?.session_recording_opt_in) {+ return {}+ }+ const { identified } = partitionDistinctIds(distinctIds)+ if (identified.length === 0) {+ return {}+ }+ const limitedIds = identified.slice(0, PERSON_HYDRATION_LIMIT)+ const query = hogql`SELECT+ distinct_id,+ count(DISTINCT session_id) AS recording_count+ FROM session_replay_events+ WHERE distinct_id IN ${limitedIds}+ AND min_first_timestamp >= now() - INTERVAL 30 MINUTE+ GROUP BY distinct_id`++ const response = (await performQuery({+ kind: NodeKind.HogQLQuery,+ query,+ tags: WEB_ANALYTICS_DEFAULT_QUERY_TAGS,+ })) as HogQLQueryResponse+ const rows = (response.results ?? []) as [string, number | string][]+ const counts: Record<string, number> = {}+ for (const [distinctId, recordingCount] of rows) {+ const n = Number(recordingCount)+ if (distinctId && Number.isFinite(n) && n > 0) {+ counts[distinctId] = n+ }+ }+ return counts+ },+ },+ ],})),reducers({displayedDistinctIds: [@@ -163,15 +224,27 @@ export const livePersonDrillDownLogic = kea<livePersonDrillDownLogicType>([(s) => [s.identifiedCount],(identifiedCount: number): boolean => identifiedCount > PERSON_HYDRATION_LIMIT,],+ recordingCountByPersonKey: [+ (s) => [s.persons, s.recordingCountsByDistinctId],+ (persons: PersonType[], counts: Record<string, number>): Record<string, number> =>+ aggregateRecordingCountsByPerson(persons, counts),+ { resultEqualityCheck: equal },+ ],}),listeners(({ actions, values }) => ({refresh: () => {actions.loadPersons({ distinctIds: values.identifiedDistinctIds })+ if (values.currentTeam?.session_recording_opt_in) {+ actions.loadRecordingCounts({ distinctIds: values.identifiedDistinctIds })+ }},})),events(({ actions, values }) => ({afterMount: () => {actions.loadPersons({ distinctIds: values.identifiedDistinctIds })+ if (values.currentTeam?.session_recording_opt_in) {+ actions.loadRecordingCounts({ distinctIds: values.identifiedDistinctIds })+ }},})),])diff --git a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsxindex eb8e5132be6d..eddf3ed3659d 100644--- a/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx+++ b/frontend/src/scenes/web-analytics/LiveMetricsDashboard/liveWebAnalyticsMetricsLogic.tsx@@ -493,7 +493,8 @@ export const liveWebAnalyticsMetricsLogic = kea<liveWebAnalyticsMetricsLogicTypeconst cityColumns = values.featureFlags[FEATURE_FLAGS.WEB_ANALYTICS_LIVE_CITY_BREAKDOWN]? ',$geoip_city_name,$geoip_country_code': ''- url.searchParams.append('columns', `${baseColumns}${cityColumns}`)+ const recordingColumn = values.currentTeam?.session_recording_opt_in ? ',$session_id' : ''+ url.searchParams.append('columns', `${baseColumns}${cityColumns}${recordingColumn}`)appendFilterParams(url, values.liveFilters)cache.batch = cache.batch ?? ([] as LiveEvent[])