: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
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import React from 'react'
import { IconClock, IconCursorClick, IconHourglass, IconKeyboard, IconWarning } from '@posthog/icons'
import { PropertyFilterIcon } from 'lib/components/PropertyFilters/components/PropertyFilterIcon'
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { Dayjs } from 'lib/dayjs'
import { COUNTRY_CODE_TO_LONG_NAME } from 'lib/utils/country'
import { ceilMsToClosestSecond, humanFriendlyDuration } from 'lib/utils/durations'
import { isEmptyObject } from 'lib/utils/guards'
import { percentage } from 'lib/utils/numbers'
import { capitalizeFirstLetter } from 'lib/utils/strings'
import { OverviewItem } from 'scenes/session-recordings/components/OverviewGrid'
import { Timestamp } from 'scenes/session-recordings/player/controller/PlayerControllerTime'
import { sessionRecordingDataCoordinatorLogic } from 'scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic'
import {
SessionRecordingPlayerLogicProps,
sessionRecordingPlayerLogic,
} from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
import { getCoreFilterDefinition, getFirstFilterTypeFor } from '~/taxonomy/helpers'
import { PersonType, PropertyFilterType, SessionRecordingType } from '~/types'
import type {
RecordingEventType,
RecordingSegment,
SessionPlayerData,
SessionRecordingPropertiesType,
} from '../../../../types'
import { sessionRecordingsListPropertiesLogic } from '../../playlist/sessionRecordingsListPropertiesLogic'
import type { MiniFilterKey } from '../inspector/miniFiltersLogic'
import { playerInspectorLogic } from '../inspector/playerInspectorLogic'
import type { InspectorListItem } from '../inspector/playerInspectorLogic'
import { countryTitleFrom } from './countryTitleFrom'
import { OverviewTab, groupOverviewItemsByTab } from './overviewTabs'
import { sessionRecordingPinnedPropertiesLogic } from './sessionRecordingPinnedPropertiesLogic'
import { HARDCODED_DISPLAY_LABELS } from './sessionRecordingPinnedPropertiesLogic'
const recordingPropertyKeys = ['click_count', 'keypress_count', 'console_error_count'] as const
function getAllPersonProperties(sessionPlayerMetaData: SessionRecordingType | null): Record<string, any> {
return sessionPlayerMetaData?.person?.properties ?? {}
}
function canRenderDirectly(value: any): boolean {
return typeof value === 'string' || typeof value === 'number' || React.isValidElement(value)
}
/**
* Get human-readable property label and type information
* @param property - The property key (e.g., '$browser', 'email')
* @param recordingProperties - Recording properties to determine if it's an event property
* @returns Object with label, originalKey, and type information
*/
export function getPropertyDisplayInfo(
property: string,
recordingProperties?: Record<string, any>
): {
label: string
originalKey: string
type: TaxonomicFilterGroupType
propertyFilterType?: PropertyFilterType
} {
const propertyType =
recordingProperties && property in recordingProperties
? // anything the query returned that doesn't match a core definition must be an event property
getFirstFilterTypeFor(property) || TaxonomicFilterGroupType.EventProperties
: // a pinned key this recording lacks still has a type: a core session property stays a session property
getFirstFilterTypeFor(property) || TaxonomicFilterGroupType.PersonProperties
const propertyFilterType: PropertyFilterType | undefined =
propertyType === TaxonomicFilterGroupType.EventProperties
? PropertyFilterType.Event
: propertyType === TaxonomicFilterGroupType.SessionProperties
? PropertyFilterType.Session
: PropertyFilterType.Person
const label = getCoreFilterDefinition(property, propertyType)?.label ?? property
return {
label,
originalKey: property,
type: propertyType,
propertyFilterType,
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface playerMetaLogicValues {
allItemsByMiniFilterKey: Record<MiniFilterKey, InspectorListItem[]> // playerInspectorLogic
sessionEventsData: RecordingEventType[] | null // sessionRecordingDataCoordinatorLogic
sessionPlayerData: SessionPlayerData // sessionRecordingDataCoordinatorLogic
sessionPlayerMetaData: SessionRecordingType | null // sessionRecordingDataCoordinatorLogic
trackedWindow: number | null // sessionRecordingDataCoordinatorLogic
urls: {
timestamp: number
url: string
}[] // sessionRecordingDataCoordinatorLogic
windowIds: number[] // sessionRecordingDataCoordinatorLogic
pinnedProperties: string[] // sessionRecordingPinnedPropertiesLogic
currentPlayerTime: number // sessionRecordingPlayerLogic
currentSegment: RecordingSegment | null // sessionRecordingPlayerLogic
currentTimestamp: number | undefined // sessionRecordingPlayerLogic
currentURL: string | undefined // sessionRecordingPlayerLogic
resolution: {
height: number
width: number
} | null // sessionRecordingPlayerLogic
scale: number // sessionRecordingPlayerLogic
recordingPropertiesById: Record<string, SessionRecordingPropertiesType[]> // sessionRecordingsListPropertiesLogic
recordingPropertiesLoading: boolean // sessionRecordingsListPropertiesLogic
allOverviewItems: OverviewItem[]
currentWindowIndex: number
displayOverviewItems: OverviewItem[]
endTime: Dayjs | null
isPropertyPopoverOpen: boolean
lastPageviewEvent: RecordingEventType | null | undefined
loading: boolean
locationDisplay: string
overviewItemsByTab: Record<OverviewTab, OverviewItem[]>
resolutionDisplay: string
scaleDisplay: string
sessionPerson: PersonType | null
showFeedbackSurvey: boolean
snapshotAt: any
startTime: Dayjs | null
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface playerMetaLogicActions {
loadRecordingMetaSuccess: (
sessionPlayerMetaData: SessionRecordingType | null,
payload?:
| {
value: true
}
| undefined
) => {
payload?: {
value: true
}
sessionPlayerMetaData: SessionRecordingType | null
} // sessionRecordingDataCoordinatorLogic
setTrackedWindow: (windowId: number | null) => {
windowId: number | null
} // sessionRecordingDataCoordinatorLogic
setPinnedProperties: (properties: string[]) => {
properties: string[]
} // sessionRecordingPinnedPropertiesLogic
togglePropertyPin: (propertyKey: string) => {
propertyKey: string
} // sessionRecordingPinnedPropertiesLogic
loadPropertiesForSessionsSuccess: (
recordingProperties: SessionRecordingPropertiesType[],
payload?:
| {
sessions: SessionRecordingType[]
}
| undefined
) => {
payload?: {
sessions: SessionRecordingType[]
}
recordingProperties: SessionRecordingPropertiesType[]
} // sessionRecordingsListPropertiesLogic
maybeLoadPropertiesForSessions: (sessions: SessionRecordingType[]) => {
sessions: SessionRecordingType[]
} // sessionRecordingsListPropertiesLogic
setIsPropertyPopoverOpen: (isOpen: boolean) => {
isOpen: boolean
}
setShowFeedbackSurvey: (show: boolean) => {
show: boolean
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface playerMetaLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
loading: (
sessionPlayerMetaData: SessionRecordingType | null,
recordingPropertiesById: Record<string, SessionRecordingPropertiesType[]>
) => boolean
sessionPerson: (sessionPlayerData: SessionPlayerData) => PersonType | null
resolutionDisplay: (
resolution: {
height: number
width: number
} | null
) => string
scaleDisplay: (scale: number) => string
startTime: (sessionPlayerData: SessionPlayerData) => Dayjs | null
endTime: (sessionPlayerData: SessionPlayerData) => Dayjs | null
snapshotAt: (startTime: Dayjs | null) => any
currentWindowIndex: (currentSegment: null | import('@common/replay-shared/src').RecordingSegment) => number
lastPageviewEvent: (
sessionEventsData: RecordingEventType[] | null,
currentPlayerTime: number
) => RecordingEventType | null | undefined
allOverviewItems: (
sessionPlayerMetaData: SessionRecordingType | null,
startTime: Dayjs | null,
recordingPropertiesById: Record<string, SessionRecordingPropertiesType[]>,
pinnedProperties: string[]
) => OverviewItem[]
displayOverviewItems: (allOverviewItems: OverviewItem[], pinnedProperties: string[]) => OverviewItem[]
overviewItemsByTab: (displayOverviewItems: OverviewItem[]) => Record<OverviewTab, OverviewItem[]>
locationDisplay: (
sessionPlayerMetaData: SessionRecordingType | null,
recordingPropertiesById: Record<string, SessionRecordingPropertiesType[]>
) => string
}
}
export type playerMetaLogicType = MakeLogicType<
playerMetaLogicValues,
playerMetaLogicActions,
SessionRecordingPlayerLogicProps,
playerMetaLogicMeta
>
export const playerMetaLogic = kea<playerMetaLogicType>([
path((key) => ['scenes', 'session-recordings', 'player', 'playerMetaLogic', key]),
props({} as SessionRecordingPlayerLogicProps),
key((props: SessionRecordingPlayerLogicProps) => `${props.playerKey}-${props.sessionRecordingId}`),
connect((props: SessionRecordingPlayerLogicProps) => ({
values: [
sessionRecordingDataCoordinatorLogic(props),
['urls', 'sessionPlayerData', 'sessionEventsData', 'sessionPlayerMetaData', 'windowIds', 'trackedWindow'],
sessionRecordingPlayerLogic(props),
['scale', 'currentTimestamp', 'currentPlayerTime', 'currentSegment', 'currentURL', 'resolution'],
sessionRecordingsListPropertiesLogic,
['recordingPropertiesById', 'recordingPropertiesLoading'],
sessionRecordingPinnedPropertiesLogic,
['pinnedProperties'],
playerInspectorLogic(props),
['allItemsByMiniFilterKey'],
],
actions: [
sessionRecordingDataCoordinatorLogic(props),
['loadRecordingMetaSuccess', 'setTrackedWindow'],
sessionRecordingsListPropertiesLogic,
['maybeLoadPropertiesForSessions', 'loadPropertiesForSessionsSuccess'],
sessionRecordingPinnedPropertiesLogic,
['setPinnedProperties', 'togglePropertyPin'],
],
})),
actions({
setIsPropertyPopoverOpen: (isOpen: boolean) => ({ isOpen }),
setShowFeedbackSurvey: (show: boolean) => ({ show }),
}),
reducers(() => ({
showFeedbackSurvey: [
false,
{
setShowFeedbackSurvey: (_, { show }) => show,
},
],
isPropertyPopoverOpen: [
false,
{
setIsPropertyPopoverOpen: (_, { isOpen }) => isOpen,
},
],
})),
selectors(() => ({
loading: [
(s) => [s.sessionPlayerMetaData, s.recordingPropertiesById],
(
sessionPlayerMetaData: SessionRecordingType | null,
recordingPropertiesById: Record<string, import('~/types').SessionRecordingPropertiesType[]>
) => {
const hasSessionPlayerMetadata = !!sessionPlayerMetaData && !isEmptyObject(sessionPlayerMetaData)
const hasRecordingProperties = !!recordingPropertiesById && !isEmptyObject(recordingPropertiesById)
return !hasSessionPlayerMetadata || !hasRecordingProperties
},
],
sessionPerson: [
(s) => [s.sessionPlayerData],
(playerData: import('~/types').SessionPlayerData): PersonType | null => {
return playerData?.person ?? null
},
],
resolutionDisplay: [
(s) => [s.resolution],
(
resolution: {
height: number
width: number
} | null
) => {
return `${resolution?.width || '--'} x ${resolution?.height || '--'}`
},
],
scaleDisplay: [
(s) => [s.scale],
(scale: number) => {
// Whole-percent precision: the decimal added no useful information and flickered
// as the fit-scale settled between near-identical values.
return `${percentage(scale, 0, true)}`
},
],
startTime: [
(s) => [s.sessionPlayerData],
(sessionPlayerData: import('~/types').SessionPlayerData) => {
return sessionPlayerData.start ?? null
},
],
endTime: [
(s) => [s.sessionPlayerData],
(sessionPlayerData: import('~/types').SessionPlayerData) => {
return sessionPlayerData.end ?? null
},
],
snapshotAt: [
(s) => [s.startTime],
(startTime: Dayjs | null) => {
return startTime
? ((startTime as any).toISOString?.() ??
(typeof startTime === 'string' ? startTime : String(startTime)))
: undefined
},
],
currentWindowIndex: [
(s) => [s.currentSegment],
(currentSegment: null | import('~/types').RecordingSegment) => {
// windowId is already 1-indexed from the registry
return currentSegment?.windowId ?? 1
},
],
lastPageviewEvent: [
(s) => [s.sessionEventsData, s.currentPlayerTime],
(sessionEventsData: import('~/types').RecordingEventType[] | null, currentPlayerTime: number) => {
const playerTimeClosestSecond = ceilMsToClosestSecond(currentPlayerTime ?? 0)
if (!sessionEventsData?.length) {
return null
}
// Go through the events in reverse to find the latest pageview
for (let i = sessionEventsData.length - 1; i >= 0; i--) {
const event = sessionEventsData[i]
if (
(event.event === '$screen' || event.event === '$pageview') &&
(event.playerTime ?? 0) < playerTimeClosestSecond
) {
return event
}
}
},
],
allOverviewItems: [
(s) => [s.sessionPlayerMetaData, s.startTime, s.recordingPropertiesById, s.pinnedProperties],
(
sessionPlayerMetaData: SessionRecordingType | null,
startTime: string | null,
recordingPropertiesById: Record<string, Record<string, any>>,
pinnedProperties: string[]
) => {
const items: OverviewItem[] = []
if (startTime) {
items.push({
label: 'Start',
icon: <IconClock />,
value: <Timestamp size="small" noPadding hideIcon fixedTimestamp={startTime} />,
type: 'text',
})
}
if (sessionPlayerMetaData?.recording_duration) {
items.push({
label: 'Duration',
icon: <IconClock />,
value: humanFriendlyDuration(sessionPlayerMetaData.recording_duration),
type: 'text',
})
}
if (sessionPlayerMetaData?.retention_period_days && sessionPlayerMetaData?.recording_ttl) {
items.push({
icon: <IconHourglass />,
label: 'TTL',
value: `${sessionPlayerMetaData.recording_ttl}d / ${sessionPlayerMetaData.retention_period_days}d`,
type: 'text',
keyTooltip: 'The number of days left before this recording expires',
})
}
recordingPropertyKeys.forEach((property) => {
if (sessionPlayerMetaData?.[property] !== undefined) {
items.push({
icon:
property === 'click_count' ? (
<IconCursorClick />
) : property === 'keypress_count' ? (
<IconKeyboard />
) : property === 'console_error_count' ? (
<IconWarning />
) : undefined,
label:
getCoreFilterDefinition(property, TaxonomicFilterGroupType.Replay)?.label ?? property,
value: `${sessionPlayerMetaData[property]}`,
type: 'text',
})
}
})
const recordingProperties = sessionPlayerMetaData?.id
? recordingPropertiesById[sessionPlayerMetaData?.id] || {}
: {}
const personProperties = getAllPersonProperties(sessionPlayerMetaData)
// session properties win, person properties may be from a later session
const allProperties = { ...personProperties, ...recordingProperties }
if (allProperties['$os_name'] && allProperties['$os']) {
// we don't need both, prefer $os_name in case mobile sends better value in that field
delete allProperties['$os']
}
const allPropertyKeys = new Set(Object.keys(allProperties))
// There may be pinned properties that don't exist as keys on this specific user,
// we still want to show them, albeit with a value of '-'.
// However, we don't want to add duplicates for hardcoded processed properties like "Start", "Duration", "TTL"...
pinnedProperties.forEach((property: string) => {
if (!allPropertyKeys.has(property) && !HARDCODED_DISPLAY_LABELS.includes(property as any)) {
allPropertyKeys.add(property)
}
})
Array.from(allPropertyKeys).forEach((property) => {
if (property === '$geoip_subdivision_1_name' || property === '$geoip_city_name') {
// they're just shown in the title for Country
return
}
// Skip recording property keys that we've already processed
if (recordingPropertyKeys.includes(property as any)) {
return
}
const propertyInfo = getPropertyDisplayInfo(property, recordingProperties)
const value = allProperties[property]
const safeValue =
value == null
? '-'
: typeof value === 'string'
? value
: typeof value === 'number'
? value.toString()
: JSON.stringify(value, null, 2)
items.push({
icon: <PropertyFilterIcon type={propertyInfo.propertyFilterType} />,
label: propertyInfo.label,
value: safeValue,
keyTooltip:
propertyInfo.label !== propertyInfo.originalKey
? `Sent as: ${propertyInfo.originalKey}`
: propertyInfo.propertyFilterType
? `${capitalizeFirstLetter(propertyInfo.propertyFilterType)} property`
: undefined,
valueTooltip:
property === '$geoip_country_code' && safeValue in COUNTRY_CODE_TO_LONG_NAME
? countryTitleFrom(recordingProperties, personProperties)
: // we don't want to pass arbitrary objects to the overview grid's tooltip here, so we stringify them
canRenderDirectly(value)
? value
: JSON.stringify(value),
type: 'property',
property,
propertyFilterType: propertyInfo.propertyFilterType,
})
})
return items
},
],
displayOverviewItems: [
(s) => [s.allOverviewItems, s.pinnedProperties],
(allOverviewItems: OverviewItem[], pinnedProperties: string[]) => {
// Filter to show only pinned properties and sort by pinned order
const pinnedItems = allOverviewItems.filter((item) => {
const key = item.type === 'property' ? item.property : item.label
return pinnedProperties.includes(String(key))
})
// Sort by the order in pinnedProperties array
// without this pins jump around as they load in
return pinnedItems.sort((a, b) => {
const aKey = a.type === 'property' ? a.property : a.label
const bKey = b.type === 'property' ? b.property : b.label
const aIndex = pinnedProperties.indexOf(String(aKey))
const bIndex = pinnedProperties.indexOf(String(bKey))
return aIndex - bIndex
})
},
],
overviewItemsByTab: [
(s) => [s.displayOverviewItems],
(displayOverviewItems: OverviewItem[]): Record<OverviewTab, OverviewItem[]> =>
groupOverviewItemsByTab(displayOverviewItems),
],
locationDisplay: [
(s) => [s.sessionPlayerMetaData, s.recordingPropertiesById],
(
sessionPlayerMetaData: SessionRecordingType | null,
recordingPropertiesById: Record<string, Record<string, any>>
): string => {
const recordingProperties = sessionPlayerMetaData?.id
? recordingPropertiesById[sessionPlayerMetaData.id]
: undefined
return countryTitleFrom(recordingProperties, getAllPersonProperties(sessionPlayerMetaData))
},
],
})),
listeners(({ actions, values }) => {
// Skip if the list-wide fetch is in flight; calling again cancels it via breakpoint.
const maybeLoadRecordingProperties = (): void => {
if (values.sessionPlayerMetaData && !values.recordingPropertiesLoading) {
actions.maybeLoadPropertiesForSessions([values.sessionPlayerMetaData])
}
}
return {
// a newly pinned session property may not be in the cached recording properties yet
setPinnedProperties: maybeLoadRecordingProperties,
loadRecordingMetaSuccess: () => {
maybeLoadRecordingProperties()
},
}
}),
])