: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(experiments): Show recordings on experiments page (#71919)
Marcel Poelker11f1c4fe0170
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 34060dcaf2c6..39ff5d0dd986 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -307,6 +307,7 @@ export const FEATURE_FLAGS = {ERROR_TRACKING_WEEKLY_DIGEST: 'error-tracking-weekly-digest', // owner: #team-error-trackingEVENT_MEDIA_PREVIEWS: 'event-media-previews', // owner: @alexliderEXPERIMENT_FLAG_CLEANUP_PR: 'experiment-flag-cleanup-pr', // owner: @jurajmajerik #team-experiments+ EXPERIMENT_RECORDINGS_TAB: 'experiment-recordings-tab', // owner: @mp-hog #team-experimentsEXPERIMENT_SESSION_REPLAYS_SKILL: 'experiment-session-replays-skill', // owner: @rodrigoi #team-experimentsEXPERIMENTS_DW_AA_TEST: 'experiments-dw-aa-test', // owner: @rodrigoi #team-experimentsEXPERIMENTS_END_MODAL_CONCLUSION_FIRST: 'experiments-end-modal-conclusion-first', // owner: @ruby.c #team-experimentsdiff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex e6a9355f40cd..357eadc09372 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -33454,6 +33454,7 @@"data warehouse sources table","experiment created","experiment analyzed",+ "experiment view recordings","feature flag created","session_replay_set_filters","session_replay_experiment_link_clicked",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex f05f3babc9a4..760a8cf92234 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -8278,6 +8278,7 @@ export enum ProductIntentContext {// ExperimentsEXPERIMENT_CREATED = 'experiment created',EXPERIMENT_ANALYZED = 'experiment analyzed',+ EXPERIMENT_VIEW_RECORDINGS = 'experiment view recordings',// Feature FlagsFEATURE_FLAG_CREATED = 'feature flag created',diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsxnew file mode 100644index 000000000000..72cd91a01bf7--- /dev/null+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx@@ -0,0 +1,53 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonSegmentedButton } from '@posthog/lemon-ui'++import { SessionRecordingsPlaylist } from 'scenes/session-recordings/playlist/SessionRecordingsPlaylist'++import { Experiment } from '~/types'++import { isLaunched } from '../experimentStatus'+import { EXPOSURE_UNLINKABLE_REASON } from '../viewRecordingsLinkabilityLogic'+import { experimentReplayTabLogic } from './experimentReplayTabLogic'++// LemonSegmentedButton values must be strings; the logic stores null for "All". Variant keys are+// restricted to [a-zA-Z0-9_-], so the '$' prefix guarantees no collision with a real variant — a+// variant literally named "all" just renders as its own option after the built-in "All".+const ALL_VARIANTS = '$all'++export function ExperimentReplayTab({ experiment }: { experiment: Experiment }): JSX.Element {+ const logic = experimentReplayTabLogic({ experiment })+ const { effectiveVariantKey, variantKeys, recordingsFilters, exposureUnlinkable } = useValues(logic)+ const { setSelectedVariantKey } = useActions(logic)++ if (!isLaunched(experiment)) {+ return <LemonBanner type="info">Launch the experiment to see recordings of participants.</LemonBanner>+ }++ if (exposureUnlinkable) {+ return <LemonBanner type="warning">{EXPOSURE_UNLINKABLE_REASON}</LemonBanner>+ }++ return (+ <div data-attr="experiment-recordings-tab">+ <div className="mb-2">+ <LemonSegmentedButton+ size="small"+ value={effectiveVariantKey ?? ALL_VARIANTS}+ onChange={(value) => setSelectedVariantKey(value === ALL_VARIANTS ? null : value)}+ options={[+ { value: ALL_VARIANTS, label: 'All' },+ ...variantKeys.map((key) => ({ value: key, label: key })),+ ]}+ />+ </div>+ <div className="SessionRecordingPlaylistHeightWrapper">+ <SessionRecordingsPlaylist+ logicKey={`experiment-${experiment.id}`}+ filters={recordingsFilters}+ updateSearchParams={false}+ />+ </div>+ </div>+ )+}diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsxindex 9f98ef84ef0b..75f7ad3a8de4 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentView.tsx@@ -34,6 +34,7 @@ import { ExperimentDebugPanel } from './ExperimentExecutionPathComparison'import { ExperimentFeedbackTab } from './ExperimentFeedbackTab'import { ExperimentHeader } from './ExperimentHeader'import { EditConclusionModal } from './ExperimentModals'+import { ExperimentReplayTab } from './ExperimentReplayTab'import { ExperimentWarningBanner } from './ExperimentWarningBanners'import { ExposureCriteriaModal } from './ExposureCriteria'import { Exposures } from './Exposures'@@ -131,6 +132,7 @@ const VariantsTab = (): JSX.Element => {export function ExperimentView(): JSX.Element {const { experimentLoading, experimentId, experiment, isExperimentDraft, exposureCriteria, showDebugPanel } =useValues(experimentLogic)+ const { featureFlags } = useValues(featureFlagLogic)const {setExperiment,setExposureCriteria,@@ -201,6 +203,15 @@ export function ExperimentView(): JSX.Element {),content: <AiAnalysisTab />,},+ ...(featureFlags[FEATURE_FLAGS.EXPERIMENT_RECORDINGS_TAB]+ ? [+ {+ key: 'recordings',+ label: 'Recordings',+ content: <ExperimentReplayTab experiment={experiment} />,+ },+ ]+ : []),...(!isExperimentDraft? [{diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.tsnew file mode 100644index 000000000000..d2039a1b111c--- /dev/null+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts@@ -0,0 +1,151 @@+import { expectLogic } from 'kea-test-utils'++import api from 'lib/api'++import { initKeaTests } from '~/test/init'+import { Experiment, FilterLogicalOperator } from '~/types'++import { getViewRecordingFiltersForVariant } from '../utils'+import { experimentReplayTabLogic } from './experimentReplayTabLogic'++jest.mock('lib/utils/product-intents', () => ({+ addProductIntentForCrossSell: jest.fn().mockResolvedValue(null),+}))++const EXPERIMENT = {+ id: 42,+ feature_flag_key: 'my-flag',+ start_date: '2026-01-01T00:00:00Z',+ end_date: '2026-02-01T00:00:00Z',+ exposure_criteria: { filterTestAccounts: true },+ feature_flag: {+ filters: {+ multivariate: {+ variants: [+ { key: 'control', rollout_percentage: 50 },+ { key: 'test', rollout_percentage: 50 },+ ],+ },+ },+ },+} as unknown as Experiment++describe('experimentReplayTabLogic', () => {+ let logic: ReturnType<typeof experimentReplayTabLogic.build>+ let seenTogetherSpy: jest.SpyInstance++ beforeEach(() => {+ // The facet reducer is persisted; clear so no test inherits another's selection.+ localStorage.clear()+ initKeaTests()+ seenTogetherSpy = jest.spyOn(api.propertyDefinitions, 'seenTogether')+ seenTogetherSpy.mockResolvedValue({ $feature_flag_called: true })+ logic = experimentReplayTabLogic({ experiment: EXPERIMENT })+ logic.mount()+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ it('defaults to the "All" facet and lists the experiment variants', async () => {+ await expectLogic(logic).toMatchValues({+ selectedVariantKey: null,+ variantKeys: ['control', 'test'],+ })+ })++ it('builds an exposure-only filter pinned to the run window', () => {+ const { recordingsFilters } = logic.values++ expect(recordingsFilters.date_from).toBe('2026-01-01T00:00:00Z')+ expect(recordingsFilters.date_to).toBe('2026-02-01T00:00:00Z')+ expect(recordingsFilters.filter_test_accounts).toBe(true)+ // All facet: the inner filter is the exposure helper's "all variants" output, nothing metric-shaped.+ expect(recordingsFilters.filter_group).toEqual({+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: getViewRecordingFiltersForVariant(EXPERIMENT, undefined),+ },+ ],+ })+ })++ it('keeps the selected variant across remounts, in step with the playlist persisting its filters', async () => {+ await expectLogic(logic, () => {+ logic.actions.setSelectedVariantKey('test')+ }).toMatchValues({ selectedVariantKey: 'test' })+ logic.unmount()++ const remounted = experimentReplayTabLogic({ experiment: EXPERIMENT })+ remounted.mount()+ expect(remounted.values.selectedVariantKey).toBe('test')+ remounted.unmount()+ })++ it('falls back to "All" when the persisted variant no longer exists', async () => {+ await expectLogic(logic, () => {+ logic.actions.setSelectedVariantKey('test')+ }).toMatchValues({ selectedVariantKey: 'test' })+ logic.unmount()++ // Same experiment id, so the persisted "test" rehydrates — but the variant has since been renamed.+ const renamed = {+ ...EXPERIMENT,+ feature_flag: {+ filters: {+ multivariate: {+ variants: [+ { key: 'control', rollout_percentage: 50 },+ { key: 'test_v2', rollout_percentage: 50 },+ ],+ },+ },+ },+ } as unknown as Experiment+ const remounted = experimentReplayTabLogic({ experiment: renamed })+ remounted.mount()++ expect(remounted.values.selectedVariantKey).toBe('test')+ expect(remounted.values.effectiveVariantKey).toBeNull()+ // The stale key must not leak into the query; the filter falls back to all variants.+ expect(remounted.values.recordingsFilters.filter_group.values).toEqual([+ {+ type: FilterLogicalOperator.And,+ values: getViewRecordingFiltersForVariant(renamed, undefined),+ },+ ])+ remounted.unmount()+ })++ it('narrows the filter to the selected variant, keeping the run window', async () => {+ await expectLogic(logic, () => {+ logic.actions.setSelectedVariantKey('test')+ }).toMatchValues({ selectedVariantKey: 'test' })++ const { recordingsFilters } = logic.values+ expect(recordingsFilters.date_from).toBe('2026-01-01T00:00:00Z')+ expect(recordingsFilters.filter_group.values).toEqual([+ {+ type: FilterLogicalOperator.And,+ values: getViewRecordingFiltersForVariant(EXPERIMENT, 'test'),+ },+ ])+ })++ it('flags a server-side exposure event as unlinkable, so the tab can explain the empty list', async () => {+ seenTogetherSpy.mockResolvedValue({ $feature_flag_called: false })+ // Distinct id: both this logic and the linkability lookup are keyed by experiment id.+ const serverSide = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 43 } as Experiment })+ serverSide.mount()++ await expectLogic(serverSide).toFinishAllListeners().toMatchValues({ exposureUnlinkable: true })+ serverSide.unmount()+ })++ it('keeps the list when the exposure event is session-linkable', async () => {+ await expectLogic(logic).toFinishAllListeners().toMatchValues({ exposureUnlinkable: false })+ })+})diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.tsnew file mode 100644index 000000000000..4765e3b65ac9--- /dev/null+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts@@ -0,0 +1,130 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, path, props, reducers, selectors } from 'kea'++import { addProductIntentForCrossSell } from 'lib/utils/product-intents'+import { DEFAULT_RECORDING_FILTERS } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'++import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'+import { Experiment, FilterLogicalOperator, RecordingUniversalFilters } from '~/types'++import type { ExperimentIdType } from '../../../types'+import { applySessionLinkability, getExperimentVariants, getViewRecordingFiltersForVariant } from '../utils'+import { viewRecordingsLinkabilityLogic } from '../viewRecordingsLinkabilityLogic'++export interface ExperimentReplayTabLogicProps {+ experiment: Experiment+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface experimentReplayTabLogicValues {+ linkabilityLoaded: boolean // viewRecordingsLinkabilityLogic+ unlinkableEventNames: Set<string> // viewRecordingsLinkabilityLogic+ effectiveVariantKey: string | null+ exposureUnlinkable: boolean+ recordingsFilters: RecordingUniversalFilters+ selectedVariantKey: string | null+ variantKeys: string[]+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface experimentReplayTabLogicActions {+ setSelectedVariantKey: (variantKey: string | null) => {+ variantKey: string | null+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface experimentReplayTabLogicMeta {+ key: ExperimentIdType+ __keaTypeGenInternalSelectorTypes: {+ variantKeys: (arg: any) => string[]+ exposureUnlinkable: (linkabilityLoaded: boolean, unlinkableEventNames: Set<string>, arg: any) => boolean+ effectiveVariantKey: (selectedVariantKey: string | null, variantKeys: string[]) => string | null+ recordingsFilters: (effectiveVariantKey: string | null, arg: any) => RecordingUniversalFilters+ }+}++export type experimentReplayTabLogicType = MakeLogicType<+ experimentReplayTabLogicValues,+ experimentReplayTabLogicActions,+ ExperimentReplayTabLogicProps,+ experimentReplayTabLogicMeta+>++/**+ * Backs the experiment "Recordings" tab: sessions exposed to the experiment over its run window,+ * narrowed by the variant facet.+ */+export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([+ props({} as ExperimentReplayTabLogicProps),+ key((props) => props.experiment.id ?? 'new'),+ path((key) => ['scenes', 'experiments', 'ExperimentView', 'experimentReplayTabLogic', String(key)]),+ connect((props: ExperimentReplayTabLogicProps) => ({+ // Same key as the metric buttons' lookup, so the two surfaces share one `seen_together` request.+ values: [+ viewRecordingsLinkabilityLogic({ experiment: props.experiment }),+ ['unlinkableEventNames', 'linkabilityLoaded'],+ ],+ })),+ actions({+ setSelectedVariantKey: (variantKey: string | null) => ({ variantKey }),+ }),+ reducers({+ // null = "All" (every exposed session, regardless of variant). Persisted (keyed per+ // experiment via the logic path) so the facet stays in step with the playlist across tab+ // switches — the playlist persists its own filters and rehydrates them on remount.+ selectedVariantKey: [+ null as string | null,+ { persist: true },+ {+ setSelectedVariantKey: (_, { variantKey }) => variantKey,+ },+ ],+ }),+ selectors({+ variantKeys: [+ () => [(_, props) => props.experiment],+ (experiment: Experiment): string[] => getExperimentVariants(experiment).map((variant) => variant.key),+ ],+ // Exposure is the whole list here, so an unmatchable exposure event means there is nothing to+ // show at all. Fails open while the check is in flight, matching the metric buttons.+ exposureUnlinkable: [+ (s) => [s.linkabilityLoaded, s.unlinkableEventNames, (_, props) => props.experiment],+ (linkabilityLoaded: boolean, unlinkableEventNames: Set<string>, experiment: Experiment): boolean =>+ // Fail open while the check is in flight, matching the metric buttons' posture.+ linkabilityLoaded &&+ applySessionLinkability(getViewRecordingFiltersForVariant(experiment), unlinkableEventNames)+ .exposureUnlinkable,+ ],+ effectiveVariantKey: [+ (s) => [s.selectedVariantKey, s.variantKeys],+ (selectedVariantKey: string | null, variantKeys: string[]): string | null =>+ selectedVariantKey !== null && variantKeys.includes(selectedVariantKey) ? selectedVariantKey : null,+ ],+ recordingsFilters: [+ (s) => [s.effectiveVariantKey, (_, props) => props.experiment],+ (effectiveVariantKey: string | null, experiment: Experiment): RecordingUniversalFilters => ({+ ...DEFAULT_RECORDING_FILTERS,+ date_from: experiment.start_date ?? DEFAULT_RECORDING_FILTERS.date_from,+ date_to: experiment.end_date ?? null,+ filter_test_accounts: experiment.exposure_criteria?.filterTestAccounts ?? false,+ filter_group: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: getViewRecordingFiltersForVariant(experiment, effectiveVariantKey ?? undefined),+ },+ ],+ },+ }),+ ],+ }),+ afterMount(() => {+ // Opening the tab is a session-replay cross-sell from experiments.+ void addProductIntentForCrossSell({+ from: ProductKey.EXPERIMENTS,+ to: ProductKey.SESSION_REPLAY,+ intent_context: ProductIntentContext.EXPERIMENT_VIEW_RECORDINGS,+ })+ }),+])diff --git a/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsx b/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsxindex 2ddc46b83501..58774e535489 100644--- a/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsx+++ b/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsx@@ -12,6 +12,10 @@ import { FunnelChart } from 'scenes/experiments/charts/funnel/FunnelChart'import { experimentLogic } from 'scenes/experiments/experimentLogic'import { VariantTag } from 'scenes/experiments/ExperimentView/VariantTag'import { applySessionLinkability, getViewRecordingFilters } from 'scenes/experiments/utils'+import {+ EXPOSURE_UNLINKABLE_REASON,+ viewRecordingsLinkabilityLogic,+} from 'scenes/experiments/viewRecordingsLinkabilityLogic'import {CachedNewExperimentQueryResponse,@@ -41,7 +45,6 @@ import {isBayesianResult,isFrequentistResult,} from '../shared/utils'-import { viewRecordingsLinkabilityLogic } from './viewRecordingsLinkabilityLogic'/*** Convert new experiment results directly to DataDrivenFunnel format@@ -295,7 +298,7 @@ export function ResultDetails({disabled={safeFilters.length === 0}disabledReason={exposureUnlinkable- ? "This experiment's exposure event is captured server-side without a session ID, so recordings can't be matched."+ ? EXPOSURE_UNLINKABLE_REASON: filters.length === 0? 'Unable to identify recordings for this metric': undefineddiff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.tsindex f483f1b9c9cf..a9d1c2b90ec7 100644--- a/frontend/src/scenes/experiments/utils.test.ts+++ b/frontend/src/scenes/experiments/utils.test.ts@@ -39,6 +39,7 @@ import {getOrderedMetricsWithResults,getSessionLinkabilityEventNames,getViewRecordingFilters,+ getViewRecordingFiltersForVariant,getViewRecordingFiltersLegacy,isEvenlyDistributed,isLegacyExperiment,@@ -365,6 +366,132 @@ describe('getViewRecordingFilters', () => {})})+describe('getViewRecordingFiltersForVariant', () => {+ const experimentBase = {+ id: 1,+ name: 'test experiment',+ feature_flag_key: 'my-flag',+ feature_flag: {+ id: 1,+ team_id: 1,+ key: 'my-flag',+ name: '',+ filters: {+ groups: [],+ multivariate: {+ variants: [+ { key: 'control', rollout_percentage: 50 },+ { key: 'test', rollout_percentage: 50 },+ ],+ },+ },+ deleted: false,+ active: true,+ ensure_experience_continuity: null,+ },+ exposure_criteria: undefined,+ filters: {},+ metrics: [],+ metrics_secondary: [],+ primary_metrics_ordered_uuids: null,+ secondary_metrics_ordered_uuids: null,+ saved_metrics_ids: [],+ saved_metrics: [],+ parameters: {},+ secondary_metrics: [],+ created_at: null,+ created_by: null,+ updated_at: null,+ user_access_level: AccessControlLevel.Editor,+ } satisfies Experiment++ const customExposure = {+ exposure_criteria: {+ exposure_config: {+ kind: NodeKind.ExperimentEventExposureConfig,+ event: 'exposure_event',+ properties: [+ { key: 'foo', value: 'bar', operator: PropertyOperator.IsNot, type: PropertyFilterType.Event },+ ],+ },+ },+ } satisfies Pick<Experiment, 'exposure_criteria'>++ const variantIn = (key: string, variantKeys: string[]): Record<string, any> => ({+ key,+ type: PropertyFilterType.Event,+ value: variantKeys,+ operator: PropertyOperator.Exact,+ })+ const variantIsSet = (key: string): Record<string, any> => ({+ key,+ type: PropertyFilterType.Event,+ value: PropertyOperator.IsSet,+ operator: PropertyOperator.IsSet,+ })+ const flagExact = {+ key: '$feature_flag',+ type: PropertyFilterType.Event,+ value: 'my-flag',+ operator: PropertyOperator.Exact,+ }+ const customExposureProperty = {+ key: 'foo',+ value: 'bar',+ operator: PropertyOperator.IsNot,+ type: PropertyFilterType.Event,+ }++ it.each([+ {+ desc: 'default exposure, specific variant: matches exactly that response',+ experiment: experimentBase,+ variantKey: 'variantA',+ expected: [variantIn('$feature_flag_response', ['variantA']), flagExact],+ },+ {+ desc: 'default exposure, all variants: matches the response against every variant, excluding non-enrolled evaluations',+ experiment: experimentBase,+ variantKey: undefined,+ expected: [variantIn('$feature_flag_response', ['control', 'test']), flagExact],+ },+ {+ desc: 'default exposure, all variants with unknown flag variants: falls back to the response being set',+ experiment: { ...experimentBase, feature_flag: undefined },+ variantKey: undefined,+ expected: [variantIsSet('$feature_flag_response'), flagExact],+ },+ {+ desc: 'custom exposure, specific variant: matches exactly that variant stamp',+ experiment: { ...experimentBase, ...customExposure },+ variantKey: 'variantA',+ expected: [customExposureProperty, variantIn('$feature/my-flag', ['variantA'])],+ },+ {+ desc: 'custom exposure, all variants: matches the stamp against every variant, excluding non-enrolled events',+ experiment: { ...experimentBase, ...customExposure },+ variantKey: undefined,+ expected: [customExposureProperty, variantIn('$feature/my-flag', ['control', 'test'])],+ },+ {+ desc: 'custom exposure, all variants with unknown flag variants: falls back to the enrollment stamp being set',+ experiment: { ...experimentBase, ...customExposure, feature_flag: undefined },+ variantKey: undefined,+ expected: [customExposureProperty, variantIsSet('$feature/my-flag')],+ },+ ])('$desc', ({ experiment, variantKey, expected }) => {+ const isCustom = !!experiment.exposure_criteria?.exposure_config+ expect(getViewRecordingFiltersForVariant(experiment, variantKey)).toEqual([+ {+ id: isCustom ? 'exposure_event' : '$feature_flag_called',+ name: isCustom ? 'exposure_event' : '$feature_flag_called',+ type: 'events',+ properties: expected,+ },+ ])+ })+})+describe('getSessionLinkabilityEventNames', () => {const experimentBase = {id: 1,diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.tsindex 03010f383f81..a348e1df8a22 100644--- a/frontend/src/scenes/experiments/utils.ts+++ b/frontend/src/scenes/experiments/utils.ts@@ -30,6 +30,7 @@ import {} from '~/queries/schema/schema-general'import { isFunnelsQuery, isNodeWithSource, isTrendsQuery, isValidQueryForExperiment } from '~/queries/utils'import {+ AnyPropertyFilter,ChartDisplayType,Experiment,ExperimentMetricGoal,@@ -214,10 +215,35 @@ function seriesToFilter(series: AnyEntityNode | ExperimentMetricSource): Universreturn null}+/**+ * Mirrors the backend's exposure semantics (`build_common_exposure_conditions`, also behind the+ * replay player's experiment session context): the variant property must be IN the experiment's+ * variant keys. Matching only on the event would include sessions of users who evaluated the flag+ * but were never enrolled, e.g. `$feature_flag_called` with a `false` response on a partial rollout.+ */+function variantPropertyFilter(propertyKey: string, variantKeys: string[]): AnyPropertyFilter {+ if (variantKeys.length === 0) {+ // Variants unknown (flag not loaded) — the variant property being stamped at all is the+ // closest available enrollment marker.+ return {+ key: propertyKey,+ type: PropertyFilterType.Event,+ value: PropertyOperator.IsSet,+ operator: PropertyOperator.IsSet,+ }+ }+ return {+ key: propertyKey,+ type: PropertyFilterType.Event,+ value: variantKeys,+ operator: PropertyOperator.Exact,+ }+}+function createExposureFilter(exposureConfig: ExperimentExposureConfig,featureFlagKey: string,- variantKey: string+ variantKeys: string[]): UniversalFiltersGroupValue {const isEvent = isEventExposureConfig(exposureConfig)return {@@ -226,49 +252,35 @@ function createExposureFilter(type: isEvent ? 'events' : 'actions',properties: [...(exposureConfig.properties || []),- {- key: featureFlagVariantProperty(featureFlagKey),- type: PropertyFilterType.Event,- value: [variantKey],- operator: PropertyOperator.Exact,- },+ variantPropertyFilter(featureFlagVariantProperty(featureFlagKey), variantKeys),],}}/**- * Gets the Filters to ExperimentMetrics, Can't quite use `exposureConfigToFilter` or- * `metricToFilter` because the format is not quite the same, but we can use `seriesToFilter`- *- * TODO: refactor the *ToFilter functions so we can use bits of them.+ * Exposure filter for an experiment's recordings: one variant, or every enrolled session (variant+ * property IN the experiment's variants) when `variantKey` is omitted. Exposure-only — metric+ * steps are never added, so a metric event captured without a `$session_id` can't zero out the+ * result.*/-export function getViewRecordingFilters(+export function getViewRecordingFiltersForVariant(experiment: Experiment,- metric: ExperimentMetric,- variantKey: string+ variantKey?: string): UniversalFiltersGroupValue[] {- const filters: UniversalFiltersGroupValue[] = []- /**- * We need to check the exposure criteria as the first on the filter chain.- */- const exposureCriteria = experiment.exposure_criteria?.exposure_config- if (- exposureCriteria &&- !(isEventExposureConfig(exposureCriteria) && exposureCriteria.event === EXPOSURE_DEFAULT_EVENT)- ) {- filters.push(createExposureFilter(exposureCriteria, experiment.feature_flag_key, variantKey))- } else {- filters.push({+ const variantKeys =+ variantKey !== undefined ? [variantKey] : getExperimentVariants(experiment).map((variant) => variant.key)+ const exposureConfig = experiment.exposure_criteria?.exposure_config+ if (exposureConfig && !(isEventExposureConfig(exposureConfig) && exposureConfig.event === EXPOSURE_DEFAULT_EVENT)) {+ return [createExposureFilter(exposureConfig, experiment.feature_flag_key, variantKeys)]+ }++ return [+ {id: EXPOSURE_DEFAULT_EVENT,name: EXPOSURE_DEFAULT_EVENT,type: 'events',properties: [- {- key: EXPOSURE_FEATURE_FLAG_RESPONSE_PROPERTY,- type: PropertyFilterType.Event,- value: [variantKey],- operator: PropertyOperator.Exact,- },+ variantPropertyFilter(EXPOSURE_FEATURE_FLAG_RESPONSE_PROPERTY, variantKeys),{key: EXPOSURE_FEATURE_FLAG_PROPERTY,type: PropertyFilterType.Event,@@ -276,8 +288,25 @@ export function getViewRecordingFilters(operator: PropertyOperator.Exact,},],- })- }+ },+ ]+}++/**+ * Gets the Filters to ExperimentMetrics, Can't quite use `exposureConfigToFilter` or+ * `metricToFilter` because the format is not quite the same, but we can use `seriesToFilter`+ *+ * TODO: refactor the *ToFilter functions so we can use bits of them.+ */+export function getViewRecordingFilters(+ experiment: Experiment,+ metric: ExperimentMetric,+ variantKey: string+): UniversalFiltersGroupValue[] {+ /**+ * The exposure criteria is always the first link in the filter chain.+ */+ const filters: UniversalFiltersGroupValue[] = getViewRecordingFiltersForVariant(experiment, variantKey)/*** for mean metrics, we add the single action/event to the filtersdiff --git a/frontend/src/scenes/experiments/MetricsView/new/viewRecordingsLinkabilityLogic.test.ts b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.test.tssimilarity index 100%rename from frontend/src/scenes/experiments/MetricsView/new/viewRecordingsLinkabilityLogic.test.tsrename to frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.test.tsdiff --git a/frontend/src/scenes/experiments/MetricsView/new/viewRecordingsLinkabilityLogic.ts b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.tssimilarity index 89%rename from frontend/src/scenes/experiments/MetricsView/new/viewRecordingsLinkabilityLogic.tsrename to frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.tsindex 2344157b97fb..7daa43f7ee46 100644--- a/frontend/src/scenes/experiments/MetricsView/new/viewRecordingsLinkabilityLogic.ts+++ b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts@@ -6,13 +6,16 @@ import { objectsEqual } from 'lib/utils/objects'import { Experiment } from '~/types'-import type { ExperimentIdType } from '../../../../types'-import { getSessionLinkabilityEventNames } from '../../utils'+import type { ExperimentIdType } from '../../types'+import { getSessionLinkabilityEventNames } from './utils'export interface ViewRecordingsLinkabilityLogicProps {experiment: Experiment}+export const EXPOSURE_UNLINKABLE_REASON =+ "This experiment's exposure event is captured server-side without a session ID, so recordings can't be matched."+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface viewRecordingsLinkabilityLogicValues {linkabilityLoaded: boolean@@ -59,13 +62,13 @@ export type viewRecordingsLinkabilityLogicType = MakeLogicType</*** Checks, once per experiment page, which of the experiment's events have ever been seen with* `$session_id` — events captured server-side never carry one, so a recordings filter on them- * can only match zero sessions. Keyed on the experiment id so every "View recordings" button- * (inline result details and the details modal) shares a single lookup.+ * can only match zero sessions. Keyed on the experiment id so every recordings surface (the+ * per-variant "View recordings" buttons, the recordings tab) shares a single lookup.*/export const viewRecordingsLinkabilityLogic = kea<viewRecordingsLinkabilityLogicType>([props({} as ViewRecordingsLinkabilityLogicProps),key((props) => props.experiment.id ?? 'new'),- path((key) => ['scenes', 'experiments', 'MetricsView', 'new', 'viewRecordingsLinkabilityLogic', key]),+ path((key) => ['scenes', 'experiments', 'viewRecordingsLinkabilityLogic', String(key)]),loaders(({ props }) => ({seenTogetherMap: [null as Record<string, boolean> | null,diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex 3d5edc7cc406..31b5d05c8a59 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -2880,6 +2880,7 @@ class ProductIntentContext(StrEnum):DATA_WAREHOUSE_SOURCES_TABLE = "data warehouse sources table"EXPERIMENT_CREATED = "experiment created"EXPERIMENT_ANALYZED = "experiment analyzed"+ EXPERIMENT_VIEW_RECORDINGS = "experiment view recordings"FEATURE_FLAG_CREATED = "feature flag created"SESSION_REPLAY_SET_FILTERS = "session_replay_set_filters"SESSION_REPLAY_EXPERIMENT_LINK_CLICKED = "session_replay_experiment_link_clicked"