:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay): pin a primary property from the session replay inspector (#60812)
Paul D'Ambra5db280ea55d3
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex e1cd4112e2a8..9df91cbd00af 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -3048,6 +3048,9 @@ const api = {const params = names && names.length > 0 ? toParams({ names }, true) : ''return new ApiRequest().eventDefinitions().withAction('primary_properties').withQueryString(params).get()},+ async byName({ name }: { name: string }): Promise<EventDefinition> {+ return new ApiRequest().eventDefinitions().withAction('by_name').withQueryString(toParams({ name })).get()+ },async getMetrics({eventDefinitionId,}: {diff --git a/frontend/src/lib/components/SimpleKeyValueList.tsx b/frontend/src/lib/components/SimpleKeyValueList.tsxindex 5dcb8c139332..4d75e5255947 100644--- a/frontend/src/lib/components/SimpleKeyValueList.tsx+++ b/frontend/src/lib/components/SimpleKeyValueList.tsx@@ -1,5 +1,5 @@// A React component that renders a list of key-value pairs in a simple way.-import { ReactNode, useMemo } from 'react'+import { ReactNode, useMemo, useState } from 'react'import { JSONViewer } from 'lib/components/JSONViewer'import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'@@ -18,6 +18,41 @@ export interface SimpleKeyValueListProps {*/promotedKeys?: string[]sortItems?: boolean+ /**+ * Optional action rendered at the end of each row. The second argument is whether the row is+ * currently hovered, so the action can reveal itself on hover without reaching for a CSS class.+ */+ rowActions?: (key: string, isRowHovered: boolean) => ReactNode+}++function SimpleKeyValueRow({+ name,+ value,+ rowActions,+}: {+ name: string+ value: any+ rowActions?: (key: string, isRowHovered: boolean) => ReactNode+}): JSX.Element {+ const [isHovered, setIsHovered] = useState(false)+ const isComplexStructure = Array.isArray(value) || isObject(value)+ return (+ <div+ className="flex gap-4 items-start justify-between overflow-hidden"+ onMouseEnter={() => setIsHovered(true)}+ onMouseLeave={() => setIsHovered(false)}+ >+ <span className="font-semibold flex items-center gap-1 min-w-0">+ <PropertyKeyInfo value={name} />+ {rowActions ? rowActions(name, isHovered) : null}+ </span>+ {isComplexStructure ? (+ <JSONViewer src={value} collapsed={1} />+ ) : (+ <pre className="text-primary-alt break-all mb-0">{String(value)}</pre>+ )}+ </div>+ )}export function SimpleKeyValueList({@@ -26,6 +61,7 @@ export function SimpleKeyValueList({promotedKeys,header,sortItems = true,+ rowActions,}: SimpleKeyValueListProps): JSX.Element {const sortedItemsPromotedFirst = useMemo(() => {const sortedItems = sortItems@@ -58,21 +94,9 @@ export function SimpleKeyValueList({return (<div className="text-xs deprecated-space-y-1 max-w-full">{header}- {sortedItemsPromotedFirst.map(([key, value]) => {- const isComplexStructure = Array.isArray(value) || isObject(value)- return (- <div key={key} className="flex gap-4 items-start justify-between overflow-hidden">- <span className="font-semibold">- <PropertyKeyInfo value={key} />- </span>- {isComplexStructure ? (- <JSONViewer src={value} collapsed={1} />- ) : (- <pre className="text-primary-alt break-all mb-0">{String(value)}</pre>- )}- </div>- )- })}+ {sortedItemsPromotedFirst.map(([key, value]) => (+ <SimpleKeyValueRow key={key} name={key} value={value} rowActions={rowActions} />+ ))}{Object.keys(item).length === 0 && emptyMessage}</div>)diff --git a/frontend/src/models/primaryEventPropertiesModel.test.ts b/frontend/src/models/primaryEventPropertiesModel.test.tsnew file mode 100644index 000000000000..fba6d033d993--- /dev/null+++ b/frontend/src/models/primaryEventPropertiesModel.test.ts@@ -0,0 +1,117 @@+import { expectLogic } from 'kea-test-utils'++import { useMocks } from '~/mocks/jest'+import { primaryEventPropertiesModel } from '~/models/primaryEventPropertiesModel'+import { initKeaTests } from '~/test/init'++describe('the primary event properties model', () => {+ let logic: ReturnType<typeof primaryEventPropertiesModel.build>++ beforeEach(() => {+ useMocks({+ get: {+ '/api/projects/:team_id/event_definitions/primary_properties/': () => [+ 200,+ { primary_properties: { my_event: 'existing_prop' } },+ ],+ '/api/projects/:team_id/event_definitions/by_name/': () => [200, { id: 'def-1', name: 'my_event' }],+ },+ patch: {+ '/api/projects/:team_id/event_definitions/:id/': (req) => [+ 200,+ {+ id: 'def-1',+ name: 'my_event',+ primary_property: (req.body as Record<string, any>).primary_property,+ },+ ],+ },+ })+ initKeaTests()+ logic = primaryEventPropertiesModel()+ logic.mount()+ })++ it('only loads team overrides for events without a taxonomy default', async () => {+ await expectLogic(logic, () => {+ logic.actions.ensureLoadedForEvents(['my_event', '$pageview'])+ })+ .toDispatchActions(['loadPrimaryPropertiesSuccess'])+ .toMatchValues({+ primaryProperties: { my_event: 'existing_prop' },+ loadedEventNames: ['my_event'],+ })+ })++ it('folds the API response into the loaded map when a pin succeeds', async () => {+ await expectLogic(logic, () => {+ logic.actions.updatePrimaryProperty({ eventName: 'my_event', propertyKey: 'chosen_prop' })+ })+ .toDispatchActions(['updatePrimaryProperty', 'updatePrimaryPropertySuccess'])+ .toMatchValues({ primaryProperties: { my_event: 'chosen_prop' } })+ })++ it('reports loading while a pin update is in flight', async () => {+ logic.actions.updatePrimaryProperty({ eventName: 'my_event', propertyKey: 'chosen_prop' })+ expect(logic.values.primaryPropertiesLoading).toBe(true)++ await expectLogic(logic).toDispatchActions(['updatePrimaryPropertySuccess'])+ expect(logic.values.primaryPropertiesLoading).toBe(false)+ })++ it('removes the entry when unpinned', async () => {+ logic.actions.loadPrimaryPropertiesSuccess({ my_event: 'existing_prop' }, { names: ['my_event'] })++ await expectLogic(logic, () => {+ logic.actions.updatePrimaryProperty({ eventName: 'my_event', propertyKey: null })+ })+ .toDispatchActions(['updatePrimaryPropertySuccess'])+ .toMatchValues({ primaryProperties: {} })+ })++ it('leaves the loaded map unchanged when the update request fails', async () => {+ useMocks({+ patch: { '/api/projects/:team_id/event_definitions/:id/': () => [403, { detail: 'nope' }] },+ })+ logic.actions.loadPrimaryPropertiesSuccess({ my_event: 'existing_prop' }, { names: ['my_event'] })++ await expectLogic(logic, () => {+ logic.actions.updatePrimaryProperty({ eventName: 'my_event', propertyKey: 'chosen_prop' })+ })+ .toDispatchActions(['updatePrimaryProperty', 'updatePrimaryPropertySuccess'])+ .toMatchValues({ primaryProperties: { my_event: 'existing_prop' } })+ })++ it('does not attempt an update when the event definition lookup fails', async () => {+ let updateAttempted = false+ useMocks({+ get: { '/api/projects/:team_id/event_definitions/by_name/': () => [404, { detail: 'not found' }] },+ patch: {+ '/api/projects/:team_id/event_definitions/:id/': () => {+ updateAttempted = true+ return [200, {}]+ },+ },+ })++ await expectLogic(logic, () => {+ logic.actions.updatePrimaryProperty({ eventName: 'missing_event', propertyKey: 'some_prop' })+ })+ .toDispatchActions(['updatePrimaryProperty', 'updatePrimaryPropertySuccess'])+ .toMatchValues({ primaryProperties: {} })++ expect(updateAttempted).toBe(false)+ })++ it('does not mark events as loaded when the load request fails, so they can be retried', async () => {+ useMocks({+ get: { '/api/projects/:team_id/event_definitions/primary_properties/': () => [500, {}] },+ })++ await expectLogic(logic, () => {+ logic.actions.loadPrimaryProperties({ names: ['flaky_event'] })+ }).toDispatchActions(['loadPrimaryPropertiesFailure'])++ expect(logic.values.loadedEventNames).toEqual([])+ })+})diff --git a/frontend/src/models/primaryEventPropertiesModel.ts b/frontend/src/models/primaryEventPropertiesModel.tsindex 509275275456..cc06d1b2f949 100644--- a/frontend/src/models/primaryEventPropertiesModel.ts+++ b/frontend/src/models/primaryEventPropertiesModel.ts@@ -1,7 +1,9 @@import { actions, kea, listeners, path, reducers } from 'kea'import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'import api from 'lib/api'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { hasTaxonomyPrimaryProperty } from 'lib/utils/primaryEventProperty'import type { primaryEventPropertiesModelType } from './primaryEventPropertiesModelType'@@ -26,13 +28,47 @@ export const primaryEventPropertiesModel = kea<primaryEventPropertiesModelType>(}return { ...next, ...response.primary_properties }},+ updatePrimaryProperty: async ({+ eventName,+ propertyKey,+ }: {+ eventName: string+ propertyKey: string | null+ }) => {+ let definitionId: string+ try {+ definitionId = (await api.eventDefinitions.byName({ name: eventName })).id+ } catch (error) {+ posthog.captureException(error, { action: 'update-primary-property', stage: 'lookup' })+ lemonToast.error(`We couldn't find a definition for "${eventName}" yet. Please try again shortly.`)+ return values.primaryProperties+ }+ try {+ const updated = await api.eventDefinitions.update({+ eventDefinitionId: definitionId,+ eventDefinitionData: { primary_property: propertyKey },+ })+ const next = { ...values.primaryProperties }+ if (updated.primary_property) {+ next[eventName] = updated.primary_property+ } else {+ delete next[eventName]+ }+ return next+ } catch (error) {+ posthog.captureException(error, { action: 'update-primary-property', stage: 'update' })+ lemonToast.error('Could not update the pinned property. Please try again.')+ return values.primaryProperties+ }+ },},})),reducers({loadedEventNames: [[] as string[],{- loadPrimaryProperties: (state, { names }) => Array.from(new Set([...state, ...names])),+ loadPrimaryPropertiesSuccess: (state, { payload }) =>+ Array.from(new Set([...state, ...(payload?.names ?? [])])),},],}),@@ -51,5 +87,8 @@ export const primaryEventPropertiesModel = kea<primaryEventPropertiesModelType>(actions.loadPrimaryProperties({ names: values.loadedEventNames })}},+ loadPrimaryPropertiesFailure: ({ errorObject }) => {+ posthog.captureException(errorObject, { action: 'load-primary-properties' })+ },})),])diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.tsxindex d59eeb2a40bc..16e5f5867a9c 100644--- a/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.tsx+++ b/frontend/src/scenes/session-recordings/player/inspector/components/ItemEvent.tsx@@ -15,8 +15,10 @@ import { PropertyKeyInfo } from 'lib/components/PropertyKeyInfo'import { SimpleKeyValueList } from 'lib/components/SimpleKeyValueList'import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'import { TitledSnack } from 'lib/components/TitledSnack'+import { FEATURE_FLAGS } from 'lib/constants'import { IconOpenInNew } from 'lib/lemon-ui/icons'import { Spinner } from 'lib/lemon-ui/Spinner'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { autoCaptureEventToDescription, capitalizeFirstLetter, ceilMsToClosestSecond, isString } from 'lib/utils'import { AutocapturePreviewImage } from 'lib/utils/autocapture-previews'import { getPrimaryPropertyForEvent } from 'lib/utils/primaryEventProperty'@@ -29,6 +31,7 @@ import { ItemTimeDisplay } from '../../../components/ItemTimeDisplay'import { sessionRecordingPlayerLogic } from '../../sessionRecordingPlayerLogic'import { InspectorListItemEvent } from '../playerInspectorLogic'import { AIEventExpanded, AIEventSummary } from './AIEventItems'+import { PinPrimaryPropertyButton } from './PinPrimaryPropertyButton'export interface ItemEventProps {item: InspectorListItemEvent@@ -215,6 +218,18 @@ export function ItemEventMenu({ item }: ItemEventProps): JSX.Element {}function SingleEventDetail({ item }: ItemEventProps): JSX.Element {+ const { featureFlags } = useValues(featureFlagLogic)+ const canPinPrimaryProperty = !!featureFlags[FEATURE_FLAGS.PROMOTED_EVENT_PROPERTIES_EDIT]+ const eventName = item.data.event++ const primaryPropertyActions =+ canPinPrimaryProperty && isString(eventName)+ ? (key: string, isRowHovered: boolean): JSX.Element | null =>+ key in item.data.properties ? (+ <PinPrimaryPropertyButton eventName={eventName} propertyKey={key} isRowHovered={isRowHovered} />+ ) : null+ : undefined+return item.data.fullyLoaded ? (<EventPropertyTabssize="small"@@ -265,6 +280,14 @@ function SingleEventDetail({ item }: ItemEventProps): JSX.Element {)case 'error_display':return <ErrorDisplay eventProperties={properties} eventId={idFrom(event as ErrorEventType)} />+ case 'properties':+ return (+ <SimpleKeyValueList+ item={properties}+ promotedKeys={promotedKeys}+ rowActions={primaryPropertyActions}+ />+ )default:return <SimpleKeyValueList item={properties} promotedKeys={promotedKeys} />}diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/PinPrimaryPropertyButton.test.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/PinPrimaryPropertyButton.test.tsxnew file mode 100644index 000000000000..2d673cb46b86--- /dev/null+++ b/frontend/src/scenes/session-recordings/player/inspector/components/PinPrimaryPropertyButton.test.tsx@@ -0,0 +1,74 @@+import '@testing-library/jest-dom'++import { cleanup, render } from '@testing-library/react'+import { Provider } from 'kea'++import { getPrimaryPropertyForEvent } from 'lib/utils/primaryEventProperty'++import { primaryEventPropertiesModel } from '~/models/primaryEventPropertiesModel'+import { initKeaTests } from '~/test/init'++import { PinPrimaryPropertyButton } from './PinPrimaryPropertyButton'++const INTERACTIVE = '[data-attr="replay-pin-primary-property"]'+const BUILT_IN = '[data-attr="replay-pin-primary-property-builtin"]'++describe('PinPrimaryPropertyButton', () => {+ let logic: ReturnType<typeof primaryEventPropertiesModel.build>++ beforeEach(() => {+ initKeaTests()+ logic = primaryEventPropertiesModel()+ logic.mount()+ })++ afterEach(() => {+ cleanup()+ })++ const renderButton = (eventName: string, propertyKey: string, isRowHovered: boolean): HTMLElement =>+ render(+ <Provider>+ <PinPrimaryPropertyButton eventName={eventName} propertyKey={propertyKey} isRowHovered={isRowHovered} />+ </Provider>+ ).container++ it('shows a disabled built-in pin for the taxonomy primary property', () => {+ const taxonomyKey = getPrimaryPropertyForEvent('$pageview')+ expect(taxonomyKey).toBeTruthy()++ const container = renderButton('$pageview', taxonomyKey!, false)++ const builtIn = container.querySelector(BUILT_IN)+ expect(builtIn).toBeInTheDocument()+ expect(builtIn).toHaveAttribute('aria-disabled', 'true')+ expect(container.querySelector(INTERACTIVE)).not.toBeInTheDocument()+ })++ it('renders nothing for non-primary rows of a taxonomy-locked event', () => {+ const taxonomyKey = getPrimaryPropertyForEvent('$pageview')+ const container = renderButton('$pageview', `${taxonomyKey}_something_else`, true)++ expect(container.querySelector(BUILT_IN)).not.toBeInTheDocument()+ expect(container.querySelector(INTERACTIVE)).not.toBeInTheDocument()+ })++ const revealCases: { name: string; pinned: boolean; hovered: boolean; hidden: boolean }[] = [+ { name: 'hidden when not pinned and the row is not hovered', pinned: false, hovered: false, hidden: true },+ { name: 'revealed when the row is hovered', pinned: false, hovered: true, hidden: false },+ { name: 'always shown when pinned, even without hover', pinned: true, hovered: false, hidden: false },+ ]++ it.each(revealCases)('$name', ({ pinned, hovered, hidden }) => {+ if (pinned) {+ logic.actions.loadPrimaryPropertiesSuccess({ my_event: 'my_prop' }, { names: ['my_event'] })+ }++ const container = renderButton('my_event', 'my_prop', hovered)++ const button = container.querySelector(INTERACTIVE)+ expect(button).toBeInTheDocument()+ expect(container.querySelector(BUILT_IN)).not.toBeInTheDocument()+ expect(button?.classList.contains('opacity-0')).toBe(hidden)+ })+})diff --git a/frontend/src/scenes/session-recordings/player/inspector/components/PinPrimaryPropertyButton.tsx b/frontend/src/scenes/session-recordings/player/inspector/components/PinPrimaryPropertyButton.tsxnew file mode 100644index 000000000000..85762cad95bf--- /dev/null+++ b/frontend/src/scenes/session-recordings/player/inspector/components/PinPrimaryPropertyButton.tsx@@ -0,0 +1,60 @@+import { useActions, useValues } from 'kea'++import { IconPin, IconPinFilled } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { getPrimaryPropertyForEvent, hasTaxonomyPrimaryProperty } from 'lib/utils/primaryEventProperty'++import { primaryEventPropertiesModel } from '~/models/primaryEventPropertiesModel'++export function PinPrimaryPropertyButton({+ eventName,+ propertyKey,+ isRowHovered,+}: {+ eventName: string+ propertyKey: string+ isRowHovered: boolean+}): JSX.Element | null {+ const { primaryProperties, primaryPropertiesLoading } = useValues(primaryEventPropertiesModel)+ const { updatePrimaryProperty } = useActions(primaryEventPropertiesModel)++ if (hasTaxonomyPrimaryProperty(eventName)) {+ if (getPrimaryPropertyForEvent(eventName) !== propertyKey) {+ return null+ }+ return (+ <LemonButton+ size="xsmall"+ noPadding+ active+ icon={<IconPinFilled />}+ disabledReason="Built-in primary property — can't be changed"+ data-attr="replay-pin-primary-property-builtin"+ />+ )+ }++ const currentPrimary = primaryProperties[eventName] ?? null+ const isPinned = currentPrimary === propertyKey++ const tooltip = isPinned+ ? `Unpin "${propertyKey}" — it will stop showing next to ${eventName} events`+ : currentPrimary+ ? `Pin "${propertyKey}" as the primary property, replacing "${currentPrimary}". Shown next to ${eventName} events for your whole team.`+ : `Pin "${propertyKey}" so its value always shows next to ${eventName} events — here and on the timeline. Applies for your whole team.`++ return (+ <LemonButton+ size="xsmall"+ noPadding+ active={isPinned}+ loading={primaryPropertiesLoading}+ icon={isPinned ? <IconPinFilled /> : <IconPin />}+ tooltip={tooltip}+ onClick={() => updatePrimaryProperty({ eventName, propertyKey: isPinned ? null : propertyKey })}+ className={isPinned || isRowHovered ? undefined : 'opacity-0 focus:opacity-100'}+ data-attr="replay-pin-primary-property"+ />+ )+}