: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): Let show-recordings button link to recordings tab + add dropdown to button for filters (#100657)
Marcel Poelkerd3c939999103
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 4437ab308715..1c76837729db 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -7721,17 +7721,17 @@ snapshots:scenes-app-experiments--draft-experiment--light:hash: v1.k794b7964.c25f2146cdcd2142f7b2c1bcd45890b6a0a7d9b03e82bccb1ef891b64cf2f493.2D2m-q3OCoqqC_zQqtJPYL4me6M9Ajd-esVxbM8bur4scenes-app-experiments--experiment-asymmetric-intervals--dark:- hash: v1.k794b7964.25b7273e653bdd78015b2d6acadf7aad47d18e9014aa157777a6a0a287010942.CbEyCcV1KrfGsAjJfXcT2jeCool4dX8ThRkba-04xGE+ hash: v1.k794b7964.d89f83f41100211a6cef7c57343636d2a1b967b7e73665d1da6960b00910bce8.EX_KXEGpMiROBYUwODGsEJZ_zlENbPdzPZYJRteldXsscenes-app-experiments--experiment-asymmetric-intervals--light:- hash: v1.k794b7964.e5db52ed6527caf62ce7a416888a488c6fe78f25cea9030d3fe24619ca82fa0f.bxY4DBldoJ3pjqWxTGzJsmULViFPqoN77yIg0PaS9qs+ hash: v1.k794b7964.8e3f162f5a69dcbad2e7415f2caa94d90562233171eb27d57f5863b698c742bf.xbKxSoLCyA7JKu_TAejH_PFaxfob2VAvTToPWuY03GMscenes-app-experiments--experiment-code-tab--dark:hash: v1.k794b7964.a6d2aea20a3beea31a02b496003e06c9ead29a5739b67fe373f3a6691483667e.9NjTP48PGseyxT2-jbYawzRWiiSE7acbF_ES5TbLi4wscenes-app-experiments--experiment-code-tab--light:hash: v1.k794b7964.e7058a4c235c2202d5a63a7c5e32ab4eae2c69a422def4f9b494f7e18a61681a.30IpMGKStgL22CU4wcSp_p3KotOGPoTX5L146C-9tLgscenes-app-experiments--experiment-exposures-expanded--dark:- hash: v1.k794b7964.ee65875e3b67107023e8f3510a704409e1de46e186d52f24722a7a20853b37bb.Koj3ViybR9T1SAz-JL_EHQDwX1KZ_a5kHgtd4agb72U+ hash: v1.k794b7964.403c4909f3c7b56c04e5df689aefe04e57750693c6ea873fb4d8d76c7b0efe83.V81XJTc14hYczYSef86i3dD4SP84TldkEHgoO4C1osMscenes-app-experiments--experiment-exposures-expanded--light:- hash: v1.k794b7964.b43a61521ec468223e1f818fbd57d87da5c3c3b4847d15af48196113e0d4faa7.k2DtgH--SFjDVk6EXLhWudpVGMcQZjzgXB-k7OQ_Umg+ hash: v1.k794b7964.29b32e3bd78e5ce5b3afa42fbc7ea31d731e62155b706c33c0a9f8969f025d78.Uzk95ShEEEhwjWYclHPXRla4Fp37qmQn7bfGrFOm0ukscenes-app-experiments--experiment-frequentist-five-variants--dark:hash: v1.k794b7964.5c82d4d12d7dfeba6573e0aafc424e487c88e600493924b5ca529ba21e9039f5.EDShC6F9fYtHFtt5hi9ViDYNo8h5LGXAWGmu8igr2eIscenes-app-experiments--experiment-frequentist-five-variants--light:@@ -7744,18 +7744,22 @@ snapshots:hash: v1.k794b7964.557c37efd8493be197bc3abf9814f8e3cbc9436cea359aa6f0e2c4a476a017b9.qLJQ9vTIuxXylC9XI8GS2Jbqjcl8XDfW5dnyVMEbM9Escenes-app-experiments--experiment-recordings-empty-ended-past-retention--light:hash: v1.k794b7964.a4d9fac8514518ee888d7cc5c45aebbb5c990cb6958841d70dd882aad31e137c.LObzOkyk1zK5TzXl2RkvPQ8dRRDBBHNEbleI_FktK1I+ scenes-app-experiments--experiment-recordings-empty-from-results-row--dark:+ hash: v1.k794b7964.77abc6620cc32c244fb4d5ffc739cf8a556681f60a69482c2ccd2e1fdaf60832.Fe1H1P8AOcjOUe9S2eK09069d9mKr0BpxJobn5e7xEM+ scenes-app-experiments--experiment-recordings-empty-from-results-row--light:+ hash: v1.k794b7964.983f2ee8590f27fde6d75338e8d92966e13a0d465cd9fd1c2e673794b18486a4.a_BBcol68yK5lD2wRF5PC5cpQkfMWkKwHlJjwni04u8scenes-app-experiments--experiment-recordings-empty-in-session-has-none--dark:hash: v1.k794b7964.8e0fae0206a2c6a689489769c4f4c54afcb5e2e7dff7f3e691093d52d40f2b66.gGmGSdURcQqQYiaRAMoU9e0QLqZ60iBgu5Y3TXSAYIEscenes-app-experiments--experiment-recordings-empty-in-session-has-none--light:hash: v1.k794b7964.17ae28c96ffb6e5f325c1d6472a3d0daf74ebc5f587e71c6e1e519c3ae90cfde.gxIuB-JGrgOu019Z-fO3qd5xJdDjYnakTZFb8ifWRd4scenes-app-experiments--experiment-recordings-empty-metric-filter-failed--dark:- hash: v1.k794b7964.de0dcdbb378afe30e253b77bf6f65f0951ade1d64f1130b0f434d84b860aae75.XeFu9_MgfbNR9OcHkHT1GfxXwqLVh5l1sZdIMUyCDwU+ hash: v1.k794b7964.a5c92ce6b4ad7a701b88dc1cc2d7579854c7e5b6d6b20fb2ac77c92b86de3007._5YtS4fFU4eqLcwWgFX3YzRihkbMpVz_y772rPBGmCYscenes-app-experiments--experiment-recordings-empty-metric-filter-failed--light:- hash: v1.k794b7964.4b69ebc9a53ee1741178c1594b08d25d3eb43fa5a834db4c6299d009b62c4953.HF9LK-eTwE5qJzSb23ClXWYy-gXrOQohPVPC6zS2uJ0+ hash: v1.k794b7964.a1c39631bb948d1d89f3c206f224782c22ff6426b4acca9d3da95ac3ae9c4243.-F8y74aNTowGDOeya9i1vFpY6nKuqGQqF5MV3FqzKWEscenes-app-experiments--experiment-recordings-empty-metric-filter-matched-nothing--dark:- hash: v1.k794b7964.7501d0ad4714cc8f2fb695e0b521711d71782ef89f65f214f0caa59bd823d331.rE7WfJJeJxDyWv4g_1KTSck6M8mbXISvSdqO4XuDd_k+ hash: v1.k794b7964.5a10df4324cead8ad02c4209955afc737f5ece532fe0c6904fd55f99cb90ef6a.oOQZPuVHBr5m2CY_SdnL_eWAnJulioFJEw2qGx3DTecscenes-app-experiments--experiment-recordings-empty-metric-filter-matched-nothing--light:- hash: v1.k794b7964.c3d237d41b22bc16d68bf8bca2baf3fb2b680130fa285095c0a6c030e3c85832.9_we98SUgw_Q58Ew7VB7ZYmfk1qNxr5KH5HSmcmhAq0+ hash: v1.k794b7964.0e8490053ae25cf7eefa0d164e3244145b3e8c853d5a0dc6ee3ae664ef8b28e5.RW9Zp4iUj0XXRtP23uKkLHFegRvoi156kKh23lRxu0Uscenes-app-experiments--experiment-recordings-empty-too-early--dark:hash: v1.k794b7964.461cc90ab6b2e52b99111e0631d253e47347647f994b2500ceb87eeb77c6b771.3taB8yr84NutLTUwM3FMvtp-Z9R0KSmjXY1j9hUx5R0scenes-app-experiments--experiment-recordings-empty-too-early--light:@@ -7772,6 +7776,22 @@ snapshots:hash: v1.k794b7964.ebc31572406f9a52425ac28a209784b99a852c92116fe1ed90df19fc3d73b899.-MGnNAnX0zGAKvPu8HLxqQph4wxAX97lMphrQZdYQBoscenes-app-experiments--experiment-replay-scanner-backlink--light:hash: v1.k794b7964.19d61ab9fd6ce3e4db819e93ba3b246b9b3b7618cb8d0a4d3dfcd5c888a20f32.mDpS1PbH6T6TkXxoijLxGHh6OC3nR3A02jmkJGbzH10+ scenes-app-experiments--experiment-results-row-recording-links-funnel--dark:+ hash: v1.k794b7964.7ef2f65c796ee2e1378b4407889ae520398ffaf60d872a026a1a9fb29b0981c3.mHOOszE4TP4K0mk-BeZJXC6xKhg0KfSuytsEj-sCLgk+ scenes-app-experiments--experiment-results-row-recording-links-funnel--light:+ hash: v1.k794b7964.015989b7d3aa52083851562d5c5aff6dbb47b23d89b294843cce5a772fa3ed9e.5Bf4eDvrN_YEO9SC3jvasrrj27NDu2NzTwAe7Wo4hCU+ scenes-app-experiments--experiment-results-row-recording-links-funnel-menu--dark:+ hash: v1.k794b7964.23b4eed9455c1a1287cfdb30111a5e6b0af2eed84e5d6fda2fd73303a959e476.xl7koSW1_jNbSn5CPPl9ZvSGIhIDRZJ8pkpoFpx9BeI+ scenes-app-experiments--experiment-results-row-recording-links-funnel-menu--light:+ hash: v1.k794b7964.de86e5c36d7d0a5de5c89887d0832624b87f3e52423bffab7fe89d66e039a5a5.VeNRwlT9wlhMCEIF6mSHmMXQ7Vt7Jyw0nxEZ0PVhUss+ scenes-app-experiments--experiment-results-row-recording-links-mean-menu--dark:+ hash: v1.k794b7964.d81dec7f90c2d80cc815a717ba223a442d4ae28fb5e2fb450fa7d20ad7065b24._BBUPxz9cz8nnh0rdY2dHPNiP4LdnBdCeYpdtOR-tKA+ scenes-app-experiments--experiment-results-row-recording-links-mean-menu--light:+ hash: v1.k794b7964.ed6d11256895e165a5b826dae808b3a0451212bd0ca21cd096206c7dd26a3aca.LSLSzuVwj-zZ-5nteupI7DIQO52Z82jRMIxtN_Kr-3k+ scenes-app-experiments--experiment-results-row-recording-links-narrow--dark:+ hash: v1.k794b7964.3f165672892e5dd4df5d38df6526833dc4db99e4e35930fa4fe3d3fd4b1f12a8.B_2KJg022Ypa6oThtqLsngXvU0YeWoIc9q0-PgBYl6c+ scenes-app-experiments--experiment-results-row-recording-links-narrow--light:+ hash: v1.k794b7964.51601e5cdf3ee801c3cb93ef4d805ec9ce0401bab611a957001b911f66676e4e.P9mT7PBVcRd9xPGUgJRcxtIsVAjHHLDz6H6fB40Vkt0scenes-app-experiments--experiment-stopped-with-conclusion--dark:hash: v1.k794b7964.e347bbe9e217d7cbd915b09b362a9d995285c1f6492229235ce3dcef74e49f30.5xV99CaEDXp-xFACHoS4M9vQ6zFGOjestb-iW79F5Q4scenes-app-experiments--experiment-stopped-with-conclusion--light:@@ -7817,9 +7837,9 @@ snapshots:scenes-app-experiments--experiment-with-legacy-trends-query--light:hash: v1.k794b7964.42c2f3656a5c989d4b1ee34296ca4bb59e186241920a5f8ca21f319069cc6825.6R2u2nPGBnbJYFX2aAn-ZEDtNpa4m1bQA-1aYg8Y7sMscenes-app-experiments--experiment-with-mean-metric--dark:- hash: v1.k794b7964.ce8d959db74a7ae405159561dbadebb90f89b6e2b9dadb51ab009116936abe88.XdKMTtjWT5MtQTxTPzDsPnMh2DUnqeEubZg54gEULOo+ hash: v1.k794b7964.3135638bd99a0bafb611bedcf83cf2fcbfe9b3f78592d75345491ddd03db4a6f.LiMc47WRusrkVhxtPPW9SSKPWb64MnjHrKcrT8K-Xk4scenes-app-experiments--experiment-with-mean-metric--light:- hash: v1.k794b7964.e2a3caea1b01b51e6f8a22718347b246145e033e5fc111e066fbc607fdd75df7.D_j9aQf_UV0NH1PRSqzDtsNptYcEOr0epkpxNjJCMWw+ hash: v1.k794b7964.c042cf2b9b7416b5278ad99ac316ae8380705877211020fd6530303eab68157c.vtCbDg0AK1SW0bMm1E3eRtLHRBlleGL_g0zNl1YDbDMscenes-app-experiments--experiment-with-multi-step-funnel-metric--dark:hash: v1.k794b7964.980b559b32f54de08e32932b4d9e14e203c2ff084a7dd0fd16bce311dff6540e.RjlN-Zl7Betwf5MoCvu-4XAx75Dqu5OI8f_qbvOsQ20scenes-app-experiments--experiment-with-multi-step-funnel-metric--light:@@ -7833,9 +7853,9 @@ snapshots:scenes-app-experiments--experiment-with-multiple-metrics-reordered--light:hash: v1.k794b7964.0587837efd7de868fdd36fe510c67061000245a3f452626997ca1b2abe1798ee.HRp_xAeT4-TdYyop38KB2aaQ6cOED7U0Md4U9l9qOzwscenes-app-experiments--experiment-with-ratio-metric--dark:- hash: v1.k794b7964.13d3da54abdcec5660775b4539d0597a4c0f85a7630c849b2f998cb5d060241e.WXP11KTleCqfzYeN-cuWDmrM3sNgxNbnuTpMP1skazA+ hash: v1.k794b7964.38b4a765481fc47f840b5de775cce025ce89efda424ce7f20ad3250140860474.TiOIF_xA1Xub7iLxtsnGI4jP73WdaT85oEH_HQcM5K0scenes-app-experiments--experiment-with-ratio-metric--light:- hash: v1.k794b7964.80eb7180004ce58bf899e2edcc49d7e2b3f876eb27386f1f3b8c6fdfa694caff.-rmdm9HY3ji3x_6EBmP8n1As861ZbWWkfS5gLYpYtsM+ hash: v1.k794b7964.69a8ad8ce233ae68bb4d13814b6c80db5bfb6d1566bff48d1b59f119bf4ad865.m6bP4wU_AbcvcOcvJVAtqnuMdqRetoDg7F-9pMWg2Ikscenes-app-experiments--experiments--dark:hash: v1.k794b7964.02690ce57556848e6499d55ebdea346c56b0a7f0c291fc7e6ce0dbea43338c3e.CmF_cYWu6htlQfgz-p47OvL1KNUyS5xNcA_b2p10J8gscenes-app-experiments--experiments--light:diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.tsindex c50fdeda31fe..003252192d0c 100644--- a/frontend/src/lib/utils/eventUsageLogic.ts+++ b/frontend/src/lib/utils/eventUsageLogic.ts@@ -129,6 +129,12 @@ export enum GraphSeriesAddedSource {* empty opens nothing, and empty lists are the outcome the in-session scope most affects.*/export interface ExperimentRecordingsTabContext {+ /**+ * What put the tab in the state it opened in, when it was not the viewer: 'results_button' or+ * 'results_menu' for a results-table link. Null when the viewer opened the tab themselves,+ * which is the ordinary case, so this is what separates the two populations in a report.+ */+ entry_point: string | nullvariant_count: numbermetric_count: numberlinkable_metric_count: number@@ -158,6 +164,12 @@ export interface ExperimentRecordingsFilterContext {* This is the success metric for the behavior comparison: opens it drove versus opens the* plain list drove. */watch_card_kind: string | null+ /**+ * What set these facets, when it was not the viewer: 'results_button' or 'results_menu' for a+ * results-table link. Null once the viewer moves a facet themselves, so an empty list that a+ * results row produced can be told from one somebody narrowed into by hand.+ */+ entry_point: string | null}/**diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsxindex f16b7e13445d..9afe6069c559 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx@@ -33,9 +33,10 @@ import { scannerTypeLabel } from 'products/replay_vision/frontend/replay_scannerimport { NOT_A_FUNNEL_REASON } from '../utils'import { ExperimentBehaviorComparison, ExperimentBehaviorComparisonToggle } from './ExperimentBehaviorComparison'+import { EXPERIMENT_RECORDING_MODE_OPTIONS } from './experimentRecordingModes'+import { type ExperimentReplayMetricFilterMode, isFunnelMode } from './experimentRecordingsDeepLink'import { ExperimentRecordingsListEmptyState } from './ExperimentRecordingsListEmptyState'import {- ExperimentReplayMetricFilterMode,ExperimentReplayMetricOption,ExperimentSessionBucket,LinkedScanner,@@ -95,6 +96,7 @@ const MODE_SUMMARIES: Record<ExperimentReplayMetricFilterMode, string> = {fired_any: 'fired events from at least one selected metric',no_metric_activity: 'fired no events from the selected metrics',funnel_dropoff: "were exposed but didn't finish the funnel",+ funnel_completed: 'were exposed and finished the funnel',}/**@@ -110,9 +112,10 @@ function metricFilterTriggerLabel(selectedUuids: string[],options: ExperimentReplayMetricOption[]): string {- if (mode === 'funnel_dropoff') {+ if (isFunnelMode(mode)) {+ const label = mode === 'funnel_completed' ? 'Finished funnel' : "Didn't finish funnel"const selected = options.find((option) => option.uuid === selectedUuids[0])- return selected ? `Didn't finish funnel: ${selected.name}` : "Didn't finish funnel"+ return selected ? `${label}: ${selected.name}` : label}if (selectedUuids.length === 0) {// Never fall back to the neutral label for a non-default mode: the mode is on, and the@@ -136,7 +139,7 @@ function metricFilterTriggerLabel(/** Why a picked mode isn't narrowing the list — it needs a selection it doesn't have yet. */function unappliedModeReason(mode: ExperimentReplayMetricFilterMode): string {- return mode === 'funnel_dropoff'+ return isFunnelMode(mode)? 'Pick a funnel metric whose last step can be matched to recordings. Showing every exposed recording until then.': 'Pick at least one metric. Showing every exposed recording until then.'}@@ -195,30 +198,6 @@ function MetricOptionLabel({ option }: { option: ExperimentReplayMetricOption }))}-const METRIC_FILTER_MODE_OPTIONS: { value: ExperimentReplayMetricFilterMode; label: string; tooltip: string }[] = [- {- value: 'fired_all',- label: 'Fired all',- tooltip: 'Sessions that fired events for every selected metric.',- },- {- value: 'fired_any',- label: 'Fired any',- tooltip: 'Sessions that fired events for at least one of the selected metrics.',- },- {- value: 'no_metric_activity',- label: 'Fired none',- tooltip: 'Sessions that fired no events for any of the selected metrics.',- },- {- value: 'funnel_dropoff',- label: "Didn't finish funnel",- tooltip:- "Sessions that saw the experiment but didn't fire a funnel metric's last step during the recording. The exposure counts as the funnel's first step. The same person may have finished it in a later session.",- },-]-/** Placeholder for the watching-scanners card while the lookup is in flight, so the tab doesn't* flash the cross-sell banner before the card resolves. */function LinkedScannersSkeletonCard(): JSX.Element {@@ -335,13 +314,13 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):// different reasons (server-side events, a retention window, data-warehouse-only sources, or// simply not being a funnel while the drop-off mode is on).const linkableMetricOptions = metricOptions.filter(- (option) => !option.unlinkable && (metricFilterMode !== 'funnel_dropoff' || option.dropoffReason === null)+ (option) => !option.unlinkable && (!isFunnelMode(metricFilterMode) || option.dropoffReason === null))const unselectableOptionsByReason = new Map<string, ExperimentReplayMetricOption[]>()for (const option of metricOptions) {const reason = option.unlinkable? option.unlinkableReason- : metricFilterMode === 'funnel_dropoff'+ : isFunnelMode(metricFilterMode)? option.dropoffReason: nullif (reason) {@@ -349,6 +328,13 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):}}+ // Both client-side modes narrow the list themselves, and the trigger label already says which+ // metric they narrowed it by, so the caption has nothing left to add once one is picked.+ const clientSideFilterApplied =+ !sessionBucketRequest &&+ (metricFilterMode === 'fired_all' || metricFilterMode === 'funnel_completed') &&+ effectiveMetricUuids.length > 0+const scannerSetupUrl = combineUrl(urls.replayVisionScannerTemplate('new'),experimentScannerParams({@@ -437,7 +423,7 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):fullWidthvalue={metricFilterMode}onChange={(value) => setMetricFilterMode(value)}- options={METRIC_FILTER_MODE_OPTIONS}+ options={EXPERIMENT_RECORDING_MODE_OPTIONS}/></div><DropdownMenuSeparator />@@ -491,12 +477,10 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):{/* The default mode also uses the endpoint for a single multi-source metric, so thecaption follows the request, not the mode. */}<div className="mb-2 flex items-center gap-2 text-xs text-secondary">- {!sessionBucketRequest && metricFilterMode === 'fired_all' ? (- effectiveMetricUuids.length === 0 ? (- <span data-attr="experiment-recordings-population-caption">- {effectiveExposureScope === 'in_session' ? inSessionCopy.caption : ALL_EXPOSED_CAPTION}- </span>- ) : null+ {clientSideFilterApplied ? null : !sessionBucketRequest && metricFilterMode === 'fired_all' ? (+ <span data-attr="experiment-recordings-population-caption">+ {effectiveExposureScope === 'in_session' ? inSessionCopy.caption : ALL_EXPOSED_CAPTION}+ </span>) : !sessionBucketRequest ? (<span>{unappliedModeReason(metricFilterMode)}</span>) : sessionBucketError !== null ? (diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentRecordingModes.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentRecordingModes.test.tsnew file mode 100644index 000000000000..dbcb673b48c2--- /dev/null+++ b/frontend/src/scenes/experiments/ExperimentView/experimentRecordingModes.test.ts@@ -0,0 +1,200 @@+import { ExperimentMetric, ExperimentMetricType, NodeKind } from '~/queries/schema/schema-general'++import {+ DATA_WAREHOUSE_UNLINKABLE_REASON,+ FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON,+ FUNNEL_SERVER_SIDE_COMPLETION_REASON,+ METRIC_UNLINKABLE_REASON,+ RETENTION_UNLINKABLE_REASON,+} from '../utils'+import { METRIC_WITHOUT_UUID_REASON, getMetricRecordingModes } from './experimentRecordingModes'++const meanMetric = (source: Record<string, unknown>): ExperimentMetric =>+ ({+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.MEAN,+ uuid: 'metric-mean',+ source,+ }) as unknown as ExperimentMetric++const funnelMetric = (series: Record<string, unknown>[]): ExperimentMetric =>+ ({+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.FUNNEL,+ uuid: 'metric-funnel',+ series,+ }) as unknown as ExperimentMetric++const ratioMetric = (numerator: Record<string, unknown>, denominator: Record<string, unknown>): ExperimentMetric =>+ ({+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.RATIO,+ uuid: 'metric-ratio',+ numerator,+ denominator,+ }) as unknown as ExperimentMetric++const event = (name: string): Record<string, unknown> => ({ kind: NodeKind.EventsNode, event: name })++describe('getMetricRecordingModes', () => {+ it.each([+ {+ case: 'a funnel whose last step can be matched opens the finished half first',+ metric: funnelMetric([event('checkout_started'), event('checkout_finished')]),+ unlinkable: [],+ expected: {+ metricSelectable: true,+ defaultMode: 'funnel_completed',+ labels: ['Finished funnel', "Didn't finish funnel"],+ disabledReasons: [null, null],+ },+ },+ {+ // The earlier steps stay matchable, so the metric itself is still selectable. Only the+ // two modes that read the last step are refused.+ case: 'a funnel finishing on a server-side step falls back to the fired mode',+ metric: funnelMetric([event('checkout_started'), event('checkout_finished')]),+ unlinkable: ['checkout_finished'],+ expected: {+ metricSelectable: true,+ defaultMode: 'fired_all',+ labels: ['Finished funnel', "Didn't finish funnel"],+ disabledReasons: [FUNNEL_SERVER_SIDE_COMPLETION_REASON, FUNNEL_SERVER_SIDE_COMPLETION_REASON],+ },+ },+ {+ case: 'a funnel finishing in the data warehouse falls back to the fired mode',+ metric: funnelMetric([+ event('checkout_started'),+ { kind: NodeKind.ExperimentDataWarehouseNode, table_name: 'stripe_charges' },+ ]),+ unlinkable: [],+ expected: {+ metricSelectable: true,+ defaultMode: 'fired_all',+ labels: ['Finished funnel', "Didn't finish funnel"],+ disabledReasons: [FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON, FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON],+ },+ },+ {+ case: 'a mean metric names the event a session has to have fired',+ metric: meanMetric(event('purchase')),+ unlinkable: [],+ expected: {+ metricSelectable: true,+ defaultMode: 'fired_all',+ labels: ['Fired purchase', "Didn't fire purchase"],+ disabledReasons: [null, null],+ },+ },+ {+ // An action matches several events and names none of them, so naming its source would+ // promise an event the recordings filter never matches on.+ case: 'a mean metric on an action keeps the generic label',+ metric: meanMetric({ kind: NodeKind.ActionsNode, id: 12, name: 'Signed up' }),+ unlinkable: [],+ expected: {+ metricSelectable: true,+ defaultMode: 'fired_all',+ labels: ['Fired metric events', "Didn't fire metric events"],+ disabledReasons: [null, null],+ },+ },+ {+ // Naming the numerator alone would be wrong: a metric counting two events resolves as+ // the fired_any bucket, so a session matches on either one.+ case: 'a ratio metric names both of its events',+ metric: ratioMetric(event('revenue'), event('$pageview')),+ unlinkable: [],+ expected: {+ metricSelectable: true,+ defaultMode: 'fired_all',+ labels: ['Fired revenue or $pageview', "Didn't fire revenue or $pageview"],+ disabledReasons: [null, null],+ },+ },+ {+ case: 'a ratio metric on one event names it once',+ metric: ratioMetric(event('purchase'), event('purchase')),+ unlinkable: [],+ expected: {+ metricSelectable: true,+ defaultMode: 'fired_all',+ labels: ['Fired purchase', "Didn't fire purchase"],+ disabledReasons: [null, null],+ },+ },+ {+ case: 'a metric whose only event is captured server-side carries no metric',+ metric: meanMetric(event('purchase')),+ unlinkable: ['purchase'],+ expected: {+ metricSelectable: false,+ defaultMode: null,+ labels: ['Fired purchase', "Didn't fire purchase"],+ disabledReasons: [METRIC_UNLINKABLE_REASON, METRIC_UNLINKABLE_REASON],+ },+ },+ {+ case: 'a retention metric carries no metric',+ metric: {+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.RETENTION,+ uuid: 'metric-retention',+ start_event: event('$pageview'),+ completion_event: event('$pageview'),+ } as unknown as ExperimentMetric,+ unlinkable: [],+ expected: {+ metricSelectable: false,+ defaultMode: null,+ labels: ['Fired metric events', "Didn't fire metric events"],+ disabledReasons: [RETENTION_UNLINKABLE_REASON, RETENTION_UNLINKABLE_REASON],+ },+ },+ {+ case: 'a data-warehouse-only metric carries no metric',+ metric: meanMetric({ kind: NodeKind.ExperimentDataWarehouseNode, table_name: 'stripe_charges' }),+ unlinkable: [],+ expected: {+ metricSelectable: false,+ defaultMode: null,+ labels: ['Fired metric events', "Didn't fire metric events"],+ disabledReasons: [DATA_WAREHOUSE_UNLINKABLE_REASON, DATA_WAREHOUSE_UNLINKABLE_REASON],+ },+ },+ {+ // The tab selects a metric by uuid, so a link to one without a uuid would land on a+ // list the metric filter never reaches.+ case: 'a metric without a uuid carries no metric',+ metric: { ...meanMetric(event('purchase')), uuid: undefined } as ExperimentMetric,+ unlinkable: [],+ expected: {+ metricSelectable: false,+ defaultMode: null,+ labels: ['Fired purchase', "Didn't fire purchase"],+ disabledReasons: [METRIC_WITHOUT_UUID_REASON, METRIC_WITHOUT_UUID_REASON],+ },+ },+ ])('$case', ({ metric, unlinkable, expected }) => {+ // The default mode decides which population one click opens, and the label is what promises+ // it. A wrong pairing sends the viewer to the opposite set of people without saying so.+ const modes = getMetricRecordingModes(metric, new Set(unlinkable))++ expect({+ metricSelectable: modes.metricSelectable,+ defaultMode: modes.defaultMode,+ labels: modes.menuItems.map((item) => item.label),+ disabledReasons: modes.menuItems.map((item) => item.disabledReason),+ }).toEqual(expected)+ })++ it('keeps everything enabled while the linkability check has not answered', () => {+ // The check resolves after the results table renders. Disabling until it lands would flash+ // a disabled menu on every visit.+ const modes = getMetricRecordingModes(meanMetric(event('purchase')), new Set())++ expect(modes.metricSelectable).toBe(true)+ expect(modes.menuItems.map((item) => item.disabledReason)).toEqual([null, null])+ })+})diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentRecordingModes.ts b/frontend/src/scenes/experiments/ExperimentView/experimentRecordingModes.tsnew file mode 100644index 000000000000..2c154b9e5858--- /dev/null+++ b/frontend/src/scenes/experiments/ExperimentView/experimentRecordingModes.ts@@ -0,0 +1,199 @@+import { ExperimentMetric, isExperimentFunnelMetric } from '~/queries/schema/schema-general'++import {+ getFunnelDropoffReason,+ getMetricSessionFilters,+ getMetricSourceEventNames,+ getMetricUnlinkableReason,+} from '../utils'+import type { ExperimentReplayMetricFilterMode } from './experimentRecordingsDeepLink'++export const METRIC_WITHOUT_UUID_REASON = "This metric can't be selected on the Recordings tab."++/**+ * The modes a results row offers. A row's link carries a single metric, and over one metric+ * "fired any" asks the same question as "fired all", so only the tab's own control offers it.+ */+type ExperimentRecordingMenuMode = Exclude<ExperimentReplayMetricFilterMode, 'fired_any'>++interface ExperimentRecordingModeLabel {+ label: string+ tooltip: string+}++/**+ * What each mode is called on the two surfaces that offer it. The Recordings tab picks a mode and a+ * metric separately, so its control names the mode alone. A results row carries one metric, so its+ * menu item can name what that metric counts. Both phrasings sit together, so a copy change lands+ * in one place.+ */+type ExperimentRecordingModeCopy<M extends ExperimentReplayMetricFilterMode> = {+ control: ExperimentRecordingModeLabel+} & (M extends ExperimentRecordingMenuMode+ ? { menu: (eventNames: string[]) => ExperimentRecordingModeLabel }+ : { menu?: undefined })++/**+ * A metric that counts several events resolves `fired_all` as the `fired_any` bucket, so a session+ * matches on any one of them. The copy says "or" for that reason.+ */+const MODE_COPY: { [M in ExperimentReplayMetricFilterMode]: ExperimentRecordingModeCopy<M> } = {+ fired_all: {+ control: {+ label: 'Fired all',+ tooltip: 'Sessions that fired events for every selected metric.',+ },+ menu: (eventNames) => {+ const events = eventNames.join(' or ')+ return {+ label: events ? `Fired ${events}` : 'Fired metric events',+ tooltip: events+ ? `Watch sessions of this variant that fired ${events}.`+ : "Watch sessions of this variant that fired the metric's events.",+ }+ },+ },+ fired_any: {+ control: {+ label: 'Fired any',+ tooltip: 'Sessions that fired events for at least one of the selected metrics.',+ },+ },+ no_metric_activity: {+ control: {+ label: 'Fired none',+ tooltip: 'Sessions that fired no events for any of the selected metrics.',+ },+ menu: (eventNames) => {+ const events = eventNames.join(' or ')+ return {+ label: events ? `Didn't fire ${events}` : "Didn't fire metric events",+ tooltip: events+ ? `Watch sessions of this variant that never fired ${events}. The same person may have fired one in another session.`+ : "Watch sessions of this variant that fired none of the metric's events. The same person may have fired them in another session.",+ }+ },+ },+ funnel_completed: {+ control: {+ label: 'Finished funnel',+ tooltip:+ "Sessions that saw the experiment and fired a funnel metric's last step during the recording. The same person may have finished it in a different session.",+ },+ menu: () => ({+ label: 'Finished funnel',+ tooltip:+ "Watch sessions of this variant that fired the funnel's last step. The same person may have finished the funnel in another session.",+ }),+ },+ funnel_dropoff: {+ control: {+ label: "Didn't finish funnel",+ tooltip:+ "Sessions that saw the experiment but didn't fire a funnel metric's last step during the recording. The exposure counts as the funnel's first step. The same person may have finished it in a later session.",+ },+ menu: () => ({+ label: "Didn't finish funnel",+ tooltip:+ "Watch sessions of this variant that didn't fire the funnel's last step. The same person may have finished the funnel in another session.",+ }),+ },+}++/**+ * The Recordings tab's mode control. Listed from the widest population to the narrowest, which is+ * not the order the parse list uses.+ */+const MODE_CONTROL_ORDER: ExperimentReplayMetricFilterMode[] = [+ 'fired_all',+ 'fired_any',+ 'no_metric_activity',+ 'funnel_completed',+ 'funnel_dropoff',+]++export const EXPERIMENT_RECORDING_MODE_OPTIONS: {+ value: ExperimentReplayMetricFilterMode+ label: string+ tooltip: string+}[] = MODE_CONTROL_ORDER.map((value) => ({ value, ...MODE_COPY[value].control }))++/**+ * The distinct events a label may name. An action matches several events and names none of them,+ * and a data-warehouse source has no session event at all, so a metric that counts either keeps the+ * generic label rather than naming a source the recordings filter doesn't match on.+ */+function labelEventNames(metric: ExperimentMetric): string[] {+ const filters = getMetricSessionFilters(metric)+ if (filters.length === 0 || !filters.every((filter) => 'type' in filter && filter.type === 'events')) {+ return []+ }+ return getMetricSourceEventNames(metric)+}++/** One mode a results row offers for its metric, resolved to what the menu item renders. */+export interface ExperimentRecordingModeItem {+ mode: ExperimentRecordingMenuMode+ label: string+ tooltip: string+ /** Why the mode can't be applied to this metric, or null when it can. */+ disabledReason: string | null+}++export interface ExperimentRecordingModes {+ /** False when the Recordings tab would drop this metric, so a link to it must carry no metric. */+ metricSelectable: boolean+ unselectableReason: string | null+ /** The mode a one-click link applies. Null when the metric can't be selected. */+ defaultMode: ExperimentReplayMetricFilterMode | null+ /**+ * The two modes that read this metric. "All recordings of this variant" is not here: it carries+ * no metric, and its label names the variant, which this module doesn't know.+ */+ menuItems: [ExperimentRecordingModeItem, ExperimentRecordingModeItem]+}++/**+ * Which recordings a results row can open for one metric, and what to call each of them.+ *+ * Every eligibility rule comes from the helpers the Recordings tab itself uses, so a row can only+ * offer what the tab would accept.+ *+ * Pass an empty `unlinkableEventNames` while the linkability check loads. Both reasons fail open on+ * it, so nothing is disabled until the check says otherwise.+ */+export function getMetricRecordingModes(+ metric: ExperimentMetric,+ unlinkableEventNames: Set<string>+): ExperimentRecordingModes {+ // The tab selects a metric by uuid and skips the ones without it, so a link to a uuid-less+ // metric would land on a list the metric filter never reaches.+ const unselectableReason =+ (metric.uuid ? null : METRIC_WITHOUT_UUID_REASON) ?? getMetricUnlinkableReason(metric, unlinkableEventNames)+ const funnel = isExperimentFunnelMetric(metric)+ // Both funnel modes read the last step, so a step no recording can be matched on disables the+ // pair rather than one half of it.+ const funnelReason = funnel ? getFunnelDropoffReason(metric, unlinkableEventNames) : null+ const modes: [ExperimentRecordingMenuMode, ExperimentRecordingMenuMode] = funnel+ ? ['funnel_completed', 'funnel_dropoff']+ : ['fired_all', 'no_metric_activity']+ const eventNames = funnel ? [] : labelEventNames(metric)+ const disabledReason = unselectableReason ?? funnelReason++ let defaultMode: ExperimentReplayMetricFilterMode | null = null+ if (!unselectableReason) {+ // A funnel whose last step can't be matched still narrows on its earlier steps, so the+ // one-click link falls back to the mode that reads them.+ defaultMode = funnelReason ? 'fired_all' : modes[0]+ }++ return {+ metricSelectable: unselectableReason === null,+ unselectableReason,+ defaultMode,+ menuItems: [+ { mode: modes[0], ...MODE_COPY[modes[0]].menu(eventNames), disabledReason },+ { mode: modes[1], ...MODE_COPY[modes[1]].menu(eventNames), disabledReason },+ ],+ }+}diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentRecordingsDeepLink.ts b/frontend/src/scenes/experiments/ExperimentView/experimentRecordingsDeepLink.tsnew file mode 100644index 000000000000..80c74441458a--- /dev/null+++ b/frontend/src/scenes/experiments/ExperimentView/experimentRecordingsDeepLink.ts@@ -0,0 +1,93 @@+import { combineUrl } from 'kea-router'++import { urls } from 'scenes/urls'++import type { ExperimentIdType } from '~/types'++/**+ * How the selected metrics narrow the list.+ *+ * `fired_all` and `funnel_completed` compose event filters client-side and are uncapped. The other+ * three are server computed: the recordings query carries one operator for its whole filter tree,+ * so an OR, an absence, and a drop-off can only come back as an explicit session-id list, which the+ * endpoint bounds. Those modes show a capped, most-recent-first slice.+ */+export const EXPERIMENT_REPLAY_METRIC_FILTER_MODES = [+ 'fired_all',+ 'fired_any',+ 'no_metric_activity',+ 'funnel_dropoff',+ 'funnel_completed',+] as const++export type ExperimentReplayMetricFilterMode = (typeof EXPERIMENT_REPLAY_METRIC_FILTER_MODES)[number]++/**+ * Whether the mode reads a funnel metric's last step, so it only accepts a funnel whose last step+ * can be matched to recordings. Both funnel modes share that eligibility rule.+ */+export function isFunnelMode(mode: ExperimentReplayMetricFilterMode): boolean {+ return mode === 'funnel_dropoff' || mode === 'funnel_completed'+}++/**+ * Which control on a results row opened the tab. Telemetry reads it to tell the one-click button+ * apart from a mode picked out of the menu, and to measure what either sends to the tab.+ */+export const EXPERIMENT_RECORDINGS_ENTRY_POINTS = ['results_button', 'results_menu'] as const++export type ExperimentRecordingsEntryPoint = (typeof EXPERIMENT_RECORDINGS_ENTRY_POINTS)[number]++/**+ * The search params that preselect the recordings tab, so a results row can open the population it+ * names instead of the replay page's own list. The tab consumes them on mount and removes them from+ * the URL, after which its persisted state is the source of truth. `metric` is taken by the+ * create flow's prefill, so the metric param here is `metric_uuid`.+ */+export const EXPERIMENT_RECORDINGS_DEEP_LINK_PARAMS = ['variant', 'metric_uuid', 'metric_filter', 'entry'] as const++export interface ExperimentRecordingsDeepLink {+ /** A variant key of the experiment's flag. Null selects every variant. */+ variantKey: string | null+ /** One metric uuid. Null leaves the metric filter menu unselected. */+ metricUuid: string | null+ /** Null falls back to the tab's default mode. */+ metricFilterMode: ExperimentReplayMetricFilterMode | null+ /** Null for a link that names no control, which leaves the reported entry point null. */+ entry: ExperimentRecordingsEntryPoint | null+}++/** The recordings tab's key in the experiment scene's tab bar. */+const RECORDINGS_TAB = 'recordings'++export function experimentRecordingsUrl(experimentId: ExperimentIdType, link: ExperimentRecordingsDeepLink): string {+ return combineUrl(urls.experiment(experimentId), {+ tab: RECORDINGS_TAB,+ ...(link.variantKey !== null ? { variant: link.variantKey } : {}),+ ...(link.metricUuid !== null ? { metric_uuid: link.metricUuid } : {}),+ ...(link.metricFilterMode !== null ? { metric_filter: link.metricFilterMode } : {}),+ ...(link.entry !== null ? { entry: link.entry } : {}),+ }).url+}++/**+ * Null when the URL carries none of the three keys, which is the ordinary case and must not move+ * the tab's persisted state. A value the experiment does not own is left to the tab's own+ * selectors, which drop an unknown variant key or metric uuid, so a stale link degrades to the+ * tab's defaults. An unknown mode or entry point is dropped here instead, against the closed lists+ * above.+ */+export function parseExperimentRecordingsDeepLink(+ searchParams: Record<string, any>+): ExperimentRecordingsDeepLink | null {+ if (!EXPERIMENT_RECORDINGS_DEEP_LINK_PARAMS.some((param) => searchParams[param] !== undefined)) {+ return null+ }+ return {+ variantKey: typeof searchParams.variant === 'string' ? searchParams.variant : null,+ metricUuid: typeof searchParams.metric_uuid === 'string' ? searchParams.metric_uuid : null,+ metricFilterMode:+ EXPERIMENT_REPLAY_METRIC_FILTER_MODES.find((mode) => mode === searchParams.metric_filter) ?? null,+ entry: EXPERIMENT_RECORDINGS_ENTRY_POINTS.find((entry) => entry === searchParams.entry) ?? null,+ }+}diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.tsindex 0cfb101bbbf9..447eba128c96 100644--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts@@ -1,5 +1,6 @@import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'@@ -30,8 +31,12 @@ import {} from 'products/experiments/frontend/generated/api'import { visionScannersList } from 'products/replay_vision/frontend/generated/api'-import { FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON, FUNNEL_SERVER_SIDE_COMPLETION_REASON } from '../utils'-import { RETENTION_UNLINKABLE_REASON, viewRecordingsLinkabilityLogic } from '../viewRecordingsLinkabilityLogic'+import {+ FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON,+ FUNNEL_SERVER_SIDE_COMPLETION_REASON,+ RETENTION_UNLINKABLE_REASON,+} from '../utils'+import { viewRecordingsLinkabilityLogic } from '../viewRecordingsLinkabilityLogic'import {type ExperimentReplayRecording,ExperimentReplayListEmptyReason,@@ -940,10 +945,168 @@ describe('experimentReplayTabLogic', () => {selected_metric_count: 0,is_bucketed: false,watch_card_kind: null,+ entry_point: null,})filled.unmount()})+ it('reports the entry point a deep link set, and clears it when the viewer moves a facet', async () => {+ // The entry point is what separates a list a results row opened from one somebody narrowed+ // by hand, so an empty rate can be read per entry point. Left set after a manual change, it+ // would credit the results row with lists it never asked for.+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)+ teamLogic.actions.loadCurrentTeamSuccess(MOCK_DEFAULT_TEAM)+ router.actions.push('/experiments/63', { tab: 'recordings', variant: 'test', entry: 'results_button' })+ const fromResults = experimentReplayTabLogic({+ experiment: { ...EXPERIMENT, id: 63, start_date: daysAgo(10), end_date: daysAgo(2) } as Experiment,+ })+ fromResults.mount()+ await expectLogic(fromResults).toFinishAllListeners()++ fromResults.actions.recordingsLoaded(loadedPage(['s1']))+ await expectLogic(fromResults).toFinishAllListeners()+ expect(listsRendered(captureSpy, 63)[0][1]).toMatchObject({ entry_point: 'results_button', variant: 'test' })++ fromResults.actions.setSelectedVariantKey(null)+ fromResults.actions.recordingsLoaded(loadedPage(['s1']))+ await expectLogic(fromResults).toFinishAllListeners()+ expect(listsRendered(captureSpy, 63)[1][1]).toMatchObject({ entry_point: null, variant: null })+ fromResults.unmount()+ })++ it('drops the entry point once the viewer narrows the list from the playlist bar', async () => {+ // A filter added in the playlist bar narrows the list past what the link asked for, so the+ // results row must stop being credited with it. The variant facet is left alone here, since+ // moving one is the other way to clear the entry point and would hide this one failing.+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)+ teamLogic.actions.loadCurrentTeamSuccess(MOCK_DEFAULT_TEAM)+ router.actions.push('/experiments/67', { tab: 'recordings', variant: 'test', entry: 'results_button' })+ const fromResults = experimentReplayTabLogic({+ experiment: { ...EXPERIMENT, id: 67, start_date: daysAgo(10), end_date: daysAgo(2) } as Experiment,+ })+ fromResults.mount()+ await expectLogic(fromResults).toFinishAllListeners()++ fromResults.actions.playlistFiltersChanged({+ ...fromResults.values.recordingsFilters,+ filter_group: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: [{ id: '$pageview', name: '$pageview', type: 'events', order: 0 }],+ },+ ],+ },+ })+ fromResults.actions.recordingsLoaded(loadedPage(['s1']))+ await expectLogic(fromResults).toFinishAllListeners()++ expect(fromResults.values.entryPoint).toBe('results_button')+ expect(listsRendered(captureSpy, 67)[0][1]).toMatchObject({ entry_point: null, variant: 'test' })+ fromResults.unmount()+ })++ it('applies a deep link once and takes its params out of the URL', async () => {+ router.actions.push('/experiments/64', {+ tab: 'recordings',+ variant: 'test',+ metric_uuid: 'metric-purchase',+ metric_filter: 'no_metric_activity',+ entry: 'results_menu',+ })+ const deepLinked = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 64 } as Experiment })+ deepLinked.mount()+ await expectLogic(deepLinked).toFinishAllListeners()++ expect(deepLinked.values.selectedVariantKey).toBe('test')+ expect(deepLinked.values.effectiveMetricUuids).toEqual(['metric-purchase'])+ expect(deepLinked.values.metricFilterMode).toBe('no_metric_activity')+ // Which control opened the tab has to survive the trip, or a menu selection and a plain+ // button click become the same row in the report.+ expect(deepLinked.values.entryPoint).toBe('results_menu')+ // One request for the three facets: they arrive in one dispatch, and afterMount asks for+ // the same bucket, so a second call here means the two are no longer collapsing.+ expect(experimentsSessionBucketsCreate).toHaveBeenCalledTimes(1)+ expect(experimentsSessionBucketsCreate).toHaveBeenLastCalledWith(expect.any(String), 64, {+ bucket: 'no_metric_activity',+ metric_uuids: ['metric-purchase'],+ variant: 'test',+ })+ // The tab the link named stays; the three it consumed go, so a later remount reads the+ // persisted state instead of applying the link again.+ expect(router.values.searchParams).toEqual({ tab: 'recordings' })+ deepLinked.unmount()+ })++ it('leaves a change made after a deep link in place when the tab remounts', async () => {+ router.actions.push('/experiments/65', {+ tab: 'recordings',+ metric_uuid: 'metric-purchase',+ metric_filter: 'no_metric_activity',+ })+ const deepLinked = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 65 } as Experiment })+ deepLinked.mount()+ await expectLogic(deepLinked).toFinishAllListeners()+ deepLinked.actions.setMetricFilterMode('fired_all')+ deepLinked.unmount()++ // The tab bar renders only the active tab, so this logic unmounts on a tab switch and+ // mounts again on return. A link still in the URL would re-apply and undo the change.+ const remounted = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 65 } as Experiment })+ remounted.mount()+ await expectLogic(remounted).toFinishAllListeners()+ expect(remounted.values.metricFilterMode).toBe('fired_all')+ remounted.unmount()+ })++ it('starts a deep link from the whole exposed set, whatever scope the last visit left', async () => {+ // The scope persists, and 'in_session' narrows to the sessions carrying exposure evidence.+ // Left in place it would cut the population the row's label promised, with nothing on+ // screen saying why.+ const earlier = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 68 } as Experiment })+ earlier.mount()+ await expectLogic(earlier).toFinishAllListeners()+ earlier.actions.setExposureScope('in_session')+ await expectLogic(earlier).toMatchValues({ effectiveExposureScope: 'in_session' })+ earlier.unmount()++ router.actions.push('/experiments/68', { tab: 'recordings', variant: 'test', entry: 'results_button' })+ const fromResults = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 68 } as Experiment })+ fromResults.mount()+ await expectLogic(fromResults).toFinishAllListeners()++ expect(fromResults.values.effectiveExposureScope).toBe('all_exposed')+ expect(fromResults.values.recordingsFilters.experiment_exposure).toEqual({+ experiment_id: 68,+ variant: 'test',+ })+ fromResults.unmount()+ })++ it('degrades a deep link the experiment cannot answer to the tab defaults', async () => {+ router.actions.push('/experiments/66', {+ tab: 'recordings',+ variant: 'nope',+ metric_uuid: 'nope',+ metric_filter: 'nope',+ })+ const stale = experimentReplayTabLogic({ experiment: { ...EXPERIMENT, id: 66 } as Experiment })+ stale.mount()+ await expectLogic(stale).toFinishAllListeners()++ // A link that names a renamed variant, a deleted metric, or a mode that no longer exists+ // has to land on the tab's own defaults rather than on a stuck filter or a refused request.+ expect(stale.values.effectiveVariantKey).toBeNull()+ // The facet persists, so a variant the experiment doesn't have must never be written: it+ // would outlive this visit and show as a selection on the next one.+ expect(stale.values.selectedVariantKey).toBeNull()+ expect(stale.values.effectiveMetricUuids).toEqual([])+ expect(stale.values.metricFilterMode).toBe('fired_all')+ expect(experimentsSessionBucketsCreate).not.toHaveBeenCalled()+ stale.unmount()+ })+it.each([{name: 'a floor the viewer raised, on another duration key',@@ -1135,7 +1298,7 @@ describe('experimentReplayTabLogic', () => {expect(recordingsFilters.filter_group).toEqual(EMPTY_FILTER_GROUP)})- it.each(['fired_any', 'no_metric_activity', 'funnel_dropoff'] as const)(+ it.each(['fired_any', 'no_metric_activity', 'funnel_dropoff', 'funnel_completed'] as const)('leaves the list untouched when %s has no metric to apply',async (mode) => {await expectLogic(logic).toFinishAllListeners()@@ -1166,6 +1329,26 @@ describe('experimentReplayTabLogic', () => {expect(logic.values.recordingsFilters.session_ids).toBeUndefined()})+ it("matches the funnel's last step for finished funnels, without asking the endpoint", async () => {+ await expectLogic(logic, () => {+ logic.actions.setMetricSelected('metric-funnel', true)+ logic.actions.setMetricFilterMode('funnel_completed')+ }).toFinishAllListeners()++ // Every other mode matches a funnel on its entry step, which is where a session starts the+ // funnel rather than finishes it. Completion is an ordinary event filter on the last step,+ // so it stays exact and uncapped instead of going to the capped bucket endpoint.+ expect(logic.values.sessionBucketRequest).toBeNull()+ expect(experimentsSessionBucketsCreate).not.toHaveBeenCalled()+ expect(logic.values.recordingsFilters.session_ids).toBeUndefined()+ expect(logic.values.recordingsFilters.filter_group.values).toEqual([+ {+ type: FilterLogicalOperator.And,+ values: [{ id: 'client_step', name: 'client_step', type: 'events', properties: [] }],+ },+ ])+ })+it('takes one funnel metric for drop-off and leaves the rest unselectable', async () => {await expectLogic(logic, () => {logic.actions.setMetricSelected('metric-purchase', true)@@ -1227,6 +1410,14 @@ describe('experimentReplayTabLogic', () => {// Nothing is asked of the endpoint, which would refuse this funnel anyway.expect(unmatchableFinish.values.sessionBucketRequest).toBeNull()expect(unmatchableFinish.values.recordingsFilters.session_ids).toBeUndefined()++ // Both funnel modes read the same last step, so the one that filters client-side has to+ // refuse the funnel too rather than matching on a step that isn't the completion.+ await expectLogic(unmatchableFinish, () =>+ unmatchableFinish.actions.setMetricFilterMode('funnel_completed')+ ).toFinishAllListeners()+ expect(unmatchableFinish.values.effectiveMetricUuids).toEqual([])+ expect(unmatchableFinish.values.recordingsFilters.filter_group).toEqual(EMPTY_FILTER_GROUP)unmatchableFinish.unmount()})diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.tsindex 97e4b90fe881..d8d2ec63e971 100644--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.ts@@ -13,6 +13,7 @@ import {selectors,} from 'kea'import { loaders } from 'kea-loaders'+import { router, urlToAction } from 'kea-router'import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'@@ -39,13 +40,7 @@ import {import { filtersFromUniversalFilterGroups } from 'scenes/session-recordings/utils'import { teamLogic } from 'scenes/teamLogic'-import {- ExperimentMetric,- NodeKind,- ProductIntentContext,- ProductKey,- isExperimentRetentionMetric,-} from '~/queries/schema/schema-general'+import { ExperimentMetric, NodeKind, ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'import {Experiment,FilterLogicalOperator,@@ -85,14 +80,19 @@ import {getExposureLinkabilityEventName,getFunnelDropoffReason,getMetricSessionFilters,+ getMetricSourceEventNames,+ getMetricUnlinkableReason,isUnlinkableEventFilter,} from '../utils'+import { viewRecordingsLinkabilityLogic } from '../viewRecordingsLinkabilityLogic'import {- DATA_WAREHOUSE_UNLINKABLE_REASON,- METRIC_UNLINKABLE_REASON,- RETENTION_UNLINKABLE_REASON,- viewRecordingsLinkabilityLogic,-} from '../viewRecordingsLinkabilityLogic'+ type ExperimentRecordingsDeepLink,+ type ExperimentRecordingsEntryPoint,+ type ExperimentReplayMetricFilterMode,+ EXPERIMENT_RECORDINGS_DEEP_LINK_PARAMS,+ isFunnelMode,+ parseExperimentRecordingsDeepLink,+} from './experimentRecordingsDeepLink'export interface ExperimentReplayTabLogicProps {experiment: Experiment@@ -120,16 +120,6 @@ export interface ExperimentReplayMetricOption {eventNames: string[]}-/**- * How the selected metrics narrow the list.- *- * `fired_all` composes event filters client-side and is uncapped. The other three are server- * computed: the recordings query carries one operator for its whole filter tree, so an OR, an- * absence, and a drop-off can only come back as an explicit session-id list — which the endpoint- * bounds, so those modes show a capped, most-recent-first slice.- */-export type ExperimentReplayMetricFilterMode = 'fired_all' | 'fired_any' | 'no_metric_activity' | 'funnel_dropoff'-/*** Which of an exposed participant's sessions the list shows: every session from first exposure* onward (the default, matching the population the analysis counts), or only the ones carrying@@ -282,18 +272,6 @@ function metricDisplayOrder(experiment: Experiment): (a: { uuid: string }, b: {return (a, b) => rank(a.uuid) - rank(b.uuid)}-/**- * The distinct events a metric counts. A metric's name is free text ("Rageclicks per user"), so- * on its own it doesn't say what a session has to have fired to match.- */-function metricSourceEventNames(metric: ExperimentMetric): string[] {- const names = getMetricSessionFilters(metric)- // Only entity filters name an event; a nested filter group (which the type allows) doesn't.- .flatMap((filter) => ('id' in filter ? [String(filter.name ?? filter.id ?? '')] : []))- .filter(Boolean)- return [...new Set(names)]-}-// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface experimentReplayTabLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogic@@ -313,6 +291,7 @@ export interface experimentReplayTabLogicValues {effectiveExposureScope: ExperimentReplayExposureScopeeffectiveMetricUuids: string[]effectiveVariantKey: string | null+ entryPoint: ExperimentRecordingsEntryPoint | nullexposureInSessionUnavailableReason: string | nullexposureLinkable: boolean | nullexposureScope: ExperimentReplayExposureScope@@ -450,6 +429,9 @@ export interface experimentReplayTabLogicActions {payload?: anyseenTogetherMap: Record<string, boolean>} // viewRecordingsLinkabilityLogic+ applyDeepLink: (link: ExperimentRecordingsDeepLink) => {+ link: ExperimentRecordingsDeepLink+ }listEmptyActionClicked: (action: ExperimentRecordingsEmptyAction) => {action: ExperimentRecordingsEmptyAction}@@ -558,7 +540,7 @@ export interface experimentReplayTabLogicActions {scope: ExperimentReplayExposureScope}setMetricFilterMode: (mode: ExperimentReplayMetricFilterMode) => {- mode: ExperimentReplayMetricFilterMode+ mode: 'fired_all' | 'fired_any' | 'funnel_completed' | 'funnel_dropoff' | 'no_metric_activity'}setMetricSelected: (metricUuid: string,@@ -650,10 +632,12 @@ export interface experimentReplayTabLogicMeta {filterContext: (effectiveVariantKey: string | null,effectiveExposureScope: ExperimentReplayExposureScope,- metricFilterMode: ExperimentReplayMetricFilterMode,+ metricFilterMode: 'fired_all' | 'fired_any' | 'funnel_completed' | 'funnel_dropoff' | 'no_metric_activity',effectiveMetricUuids: string[],bucketSessionIds: string[] | undefined,- selectedWatchCard: ExperimentWatchCardApi | null+ selectedWatchCard: ExperimentWatchCardApi | null,+ entryPoint: 'results_button' | 'results_menu' | null,+ filtersCustomized: boolean) => ExperimentRecordingsFilterContexttabViewContext: (variantKeys: string[],@@ -661,7 +645,8 @@ export interface experimentReplayTabLogicMeta {effectiveExposureScope: ExperimentReplayExposureScope,inSessionExposure: ExperimentInSessionExposureApi | null,behaviorComparisonAvailable: boolean,- behaviorComparisonUnavailableReason: 'group_aggregated' | null+ behaviorComparisonUnavailableReason: 'group_aggregated' | null,+ entryPoint: 'results_button' | 'results_menu' | null) => ExperimentRecordingsTabContextmetricOptions: (linkabilityLoaded: boolean,@@ -671,10 +656,10 @@ export interface experimentReplayTabLogicMeta {effectiveMetricUuids: (selectedMetricUuids: string[],metricOptions: ExperimentReplayMetricOption[],- metricFilterMode: ExperimentReplayMetricFilterMode+ metricFilterMode: 'fired_all' | 'fired_any' | 'funnel_completed' | 'funnel_dropoff' | 'no_metric_activity') => string[]sessionBucketRequest: (- metricFilterMode: ExperimentReplayMetricFilterMode,+ metricFilterMode: 'fired_all' | 'fired_any' | 'funnel_completed' | 'funnel_dropoff' | 'no_metric_activity',effectiveMetricUuids: string[],effectiveVariantKey: string | null,metricOptions: ExperimentReplayMetricOption[]@@ -689,6 +674,7 @@ export interface experimentReplayTabLogicMeta {effectiveExposureScope: ExperimentReplayExposureScope,effectiveMetricUuids: string[],metricOptions: ExperimentReplayMetricOption[],+ metricFilterMode: 'fired_all' | 'fired_any' | 'funnel_completed' | 'funnel_dropoff' | 'no_metric_activity',unlinkableEventNames: Set<string>,seenTogetherMapLoading: boolean,bucketSessionIds: string[] | undefined,@@ -751,6 +737,9 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([],})),actions({+ // One action for the three facets a deep link carries, so they move together and one+ // listener issues one bucket load.+ applyDeepLink: (link: ExperimentRecordingsDeepLink) => ({ link }),setSelectedVariantKey: (variantKey: string | null) => ({ variantKey }),setExposureScope: (scope: ExperimentReplayExposureScope) => ({ scope }),setMetricSelected: (metricUuid: string, selected: boolean) => ({ metricUuid, selected }),@@ -938,6 +927,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([{ persist: true },{setSelectedVariantKey: (_, { variantKey }) => variantKey,+ applyDeepLink: (_, { link }) => link.variantKey,// A card's recordings are one variant's, so the facet moves with it — visibly, so// nothing narrows unannounced. Here rather than from a listener dispatching// setSelectedVariantKey, which would let that action stay the user's own and so@@ -953,6 +943,10 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([{ persist: true },{setExposureScope: (_, { scope }) => scope,+ // A link names the population it opens. An 'in_session' scope left over from an+ // earlier visit would narrow that population further, with nothing on screen+ // saying why, so the link starts from the whole exposed set.+ applyDeepLink: () => 'all_exposed' as ExperimentReplayExposureScope,},],// Empty = no metric filter. Every selected metric narrows the playlist further (AND) —@@ -967,6 +961,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([selected? [...state.filter((uuid) => uuid !== metricUuid), metricUuid]: state.filter((uuid) => uuid !== metricUuid),+ applyDeepLink: (_, { link }) => (link.metricUuid ? [link.metricUuid] : []),// Cleared alongside the mode reset below. Carrying a selection through would invert// what it meant: "didn't fire this metric" would silently become "fired it".selectWatchCard: (state, { card }) => (card ? [] : state),@@ -979,6 +974,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([{ persist: true },{setMetricFilterMode: (_, { mode }) => mode,+ applyDeepLink: (_, { link }) => link.metricFilterMode ?? 'fired_all',// A bucket answers its own question with a capped session set, which would fight the// card's own session set. Reset here rather than from a listener: dispatching// setMetricFilterMode would clear the card this action just selected.@@ -1062,11 +1058,28 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([setSelectedVariantKey: () => null,setExposureScope: () => null,setMetricSelected: () => null,+ // A card picked on an earlier visit would otherwise survive the deep link and+ // answer with its own session set instead of the one the link names.+ applyDeepLink: () => null,// Closing the shelf takes away the only way to deselect, so the list would stay// narrowed with nothing on screen saying why.toggleBehaviorComparison: () => null,},],+ // Not persisted: it describes how this visit arrived at the state it is in, so the next+ // visit starts without one. Any facet the viewer moves themselves replaces the deep link's+ // question with their own, which is no longer what the results row asked for.+ entryPoint: [+ null as ExperimentRecordingsEntryPoint | null,+ {+ applyDeepLink: (_, { link }) => link.entry,+ setSelectedVariantKey: () => null,+ setExposureScope: () => null,+ setMetricSelected: () => null,+ setMetricFilterMode: () => null,+ selectWatchCard: () => null,+ },+ ],}),selectors({loadedRecordingsById: [@@ -1326,6 +1339,8 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([s.effectiveMetricUuids,s.bucketSessionIds,s.selectedWatchCard,+ s.entryPoint,+ s.filtersCustomized,],(effectiveVariantKey: string | null,@@ -1333,7 +1348,9 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([metricFilterMode: ExperimentReplayMetricFilterMode,effectiveMetricUuids: string[],bucketSessionIds: string[] | undefined,- selectedWatchCard: ExperimentWatchCardApi | null+ selectedWatchCard: ExperimentWatchCardApi | null,+ entryPoint: ExperimentRecordingsEntryPoint | null,+ filtersCustomized: boolean): ExperimentRecordingsFilterContext => ({variant: effectiveVariantKey,exposure_scope: effectiveExposureScope,@@ -1341,6 +1358,10 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([selected_metric_count: effectiveMetricUuids.length,is_bucketed: bucketSessionIds !== undefined,watch_card_kind: selectedWatchCard?.kind ?? null,+ // A filter the viewer added in the playlist bar narrows the list past what the link+ // asked for, the same as moving one of the tab's own facets. Read off the playlist+ // rather than its change action, which also fires on the tab's own pushes.+ entry_point: filtersCustomized ? null : entryPoint,}),],// The `experiment recordings tab viewed` payload, in a selector so the settled-checks@@ -1353,6 +1374,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([s.inSessionExposure,s.behaviorComparisonAvailable,s.behaviorComparisonUnavailableReason,+ s.entryPoint,],(variantKeys: string[],@@ -1360,8 +1382,10 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([effectiveExposureScope: ExperimentReplayExposureScope,inSessionExposure: ExperimentInSessionExposureApi | null,behaviorComparisonAvailable: boolean,- behaviorComparisonUnavailableReason: ExperimentBehaviorComparisonUnavailableReason | null+ behaviorComparisonUnavailableReason: ExperimentBehaviorComparisonUnavailableReason | null,+ entryPoint: ExperimentRecordingsEntryPoint | null): ExperimentRecordingsTabContext => ({+ entry_point: entryPoint,variant_count: variantKeys.length,metric_count: metricOptions.length,linkable_metric_count: metricOptions.filter((option) => !option.unlinkable).length,@@ -1380,12 +1404,8 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([// `resolve_metric_events` scans, deduped by uuid so a shared metric linked more than once// shows one option. Metrics without a uuid are skipped, as the backend does: the selection// persists across remounts, and any positional stand-in id could re-attach it to a- // different metric after the metric list is edited. A metric is unlinkable when every one- // of its sources is a never-session-linked event, or when it yields no session filter at- // all (a retention metric, or one measured only in the data warehouse) — either way its- // filter could only match zero sessions. Those stay listed with their reason rather than- // vanishing, which reads as the metric having been forgotten. Fails open while the check- // loads.+ // different metric after the metric list is edited. An unlinkable metric stays listed with+ // its reason rather than vanishing, which reads as the metric having been forgotten.metricOptions: [(s) => [s.linkabilityLoaded, s.unlinkableEventNames, (_, props) => props.experiment],(@@ -1398,6 +1418,8 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([(saved) => saved.query)const seenUuids = new Set<string>()+ // An empty set while the check loads, so both reasons fail open on it.+ const checkedEventNames = linkabilityLoaded ? unlinkableEventNames : new Set<string>()return [...inlineMetrics, ...savedMetrics].filter((metric): metric is ExperimentMetric => metric?.kind === NodeKind.ExperimentMetric).flatMap((metric) =>@@ -1407,14 +1429,9 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([uuid: metric.uuid,name: metric.name || getDefaultMetricTitle(metric),filters: getMetricSessionFilters(metric),- dropoffReason: getFunnelDropoffReason(- metric,- linkabilityLoaded ? unlinkableEventNames : new Set<string>()- ),- eventNames: metricSourceEventNames(metric),- noFilterReason: isExperimentRetentionMetric(metric)- ? RETENTION_UNLINKABLE_REASON- : DATA_WAREHOUSE_UNLINKABLE_REASON,+ dropoffReason: getFunnelDropoffReason(metric, checkedEventNames),+ eventNames: getMetricSourceEventNames(metric),+ unlinkableReason: getMetricUnlinkableReason(metric, checkedEventNames),},]: []@@ -1427,18 +1444,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([return true}).sort(metricDisplayOrder(experiment))- .map(({ noFilterReason, ...option }) => {- const unlinkableReason =- option.filters.length === 0- ? noFilterReason- : linkabilityLoaded &&- option.filters.every((filter) =>- isUnlinkableEventFilter(filter, unlinkableEventNames)- )- ? METRIC_UNLINKABLE_REASON- : null- return { ...option, unlinkable: unlinkableReason !== null, unlinkableReason }- })+ .map((option) => ({ ...option, unlinkable: option.unlinkableReason !== null }))},],effectiveMetricUuids: [@@ -1453,11 +1459,11 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([if (!option || option.unlinkable) {return false}- return metricFilterMode !== 'funnel_dropoff' || option.dropoffReason === null+ return !isFunnelMode(metricFilterMode) || option.dropoffReason === null})// Selections persist across mode switches, so a mode that takes exactly one metric// keeps the most recently picked rather than rejecting the whole selection.- return metricFilterMode === 'funnel_dropoff' ? selectable.slice(-1) : selectable+ return isFunnelMode(metricFilterMode) ? selectable.slice(-1) : selectable},],/**@@ -1484,6 +1490,11 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([metric_uuids: effectiveMetricUuids,variant: effectiveVariantKey,})+ if (metricFilterMode === 'funnel_completed') {+ // Completion is an ordinary event filter on the funnel's last step, which the+ // recordings query can express, so it stays on the uncapped client-side path.+ return null+ }if (metricFilterMode === 'funnel_dropoff') {return effectiveMetricUuids.length === 1 ? request('funnel_dropoff') : null}@@ -1533,6 +1544,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([s.effectiveExposureScope,s.effectiveMetricUuids,s.metricOptions,+ s.metricFilterMode,s.unlinkableEventNames,s.seenTogetherMapLoading,s.bucketSessionIds,@@ -1544,6 +1556,7 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([effectiveExposureScope: ExperimentReplayExposureScope,effectiveMetricUuids: string[],metricOptions: ExperimentReplayMetricOption[],+ metricFilterMode: ExperimentReplayMetricFilterMode,unlinkableEventNames: Set<string>,seenTogetherMapLoading: boolean,bucketSessionIds: string[] | undefined,@@ -1574,7 +1587,14 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([const linkable = (metricOptions.find((option) => option.uuid === uuid)?.filters ?? []).filter((filter) => !isUnlinkableEventFilter(filter, unlinkableEventNames))- return linkable[0]+ // "Finished the funnel" is the last step, where every other mode+ // reads the primary event. A funnel that lists one event as+ // several steps ("the third view") counts as finished on the+ // first occurrence here, while the server bucket counts+ // occurrences, so the two disagree on that shape.+ return metricFilterMode === 'funnel_completed'+ ? linkable[linkable.length - 1]+ : linkable[0]}).filter((filter): filter is UniversalFiltersGroupValue => {// Two metrics can share a primary event; the duplicate filter adds nothing.@@ -1640,6 +1660,14 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([setMetricFilterMode: () => {actions.loadSessionBucket()},+ // The three facets land in one dispatch, so one load covers them. afterMount reloads a+ // persisted bucket too, and the loader's breakpoint collapses the duplicate whichever of+ // the two runs first.+ applyDeepLink: () => {+ if (values.sessionBucketRequest) {+ actions.loadSessionBucket()+ }+ },setMetricSelected: () => {if (values.sessionBucketRequest) {actions.loadSessionBucket()@@ -1855,6 +1883,51 @@ export const experimentReplayTabLogic = kea<experimentReplayTabLogicType>([}},})),+ urlToAction(({ actions, props, cache }) => {+ // Both experiment routes, so a link that carries a form mode lands the same way the scene+ // logic's own handlers do.+ const applyFromUrl = (id: string | undefined, searchParams: Record<string, any>): void => {+ // kea-router replays urlToAction on mount with the current location, so a tab that+ // mounts after the URL already carries the params still sees them.+ if (Number(id) !== Number(props.experiment.id)) {+ return+ }+ const parsed = parseExperimentRecordingsDeepLink(searchParams)+ if (!parsed) {+ return+ }+ // A renamed or deleted variant is dropped before it reaches the facet, which persists.+ // The query selector already ignores an unknown key, but the stored one would outlive+ // this visit and show as a selected variant the experiment doesn't have.+ const variantKeys = getExperimentVariants(props.experiment).map((variant) => variant.key)+ const link = {+ ...parsed,+ variantKey:+ parsed.variantKey !== null && variantKeys.includes(parsed.variantKey) ? parsed.variantKey : null,+ }+ // The replace below re-enters here without the params, so this only guards against a+ // repeat of the same link. Keyed on the link rather than set once, so a second link+ // arriving while the tab stays mounted still moves the facets.+ const linkKey = JSON.stringify(link)+ if (cache.appliedDeepLink === linkKey) {+ return+ }+ cache.appliedDeepLink = linkKey+ actions.applyDeepLink(link)+ // The tab unmounts on a tab switch and remounts on return, so params left in the URL+ // would re-apply and overwrite whatever the viewer changed by hand in between. Every+ // other param stays, including the `tab` the link came in on.+ const remaining = { ...searchParams }+ for (const param of EXPERIMENT_RECORDINGS_DEEP_LINK_PARAMS) {+ delete remaining[param]+ }+ router.actions.replace(router.values.location.pathname, remaining, router.values.hashParams)+ }+ return {+ '/experiments/:id': ({ id }, searchParams) => applyFromUrl(id, searchParams),+ '/experiments/:id/:formMode': ({ id }, searchParams) => applyFromUrl(id, searchParams),+ }+ }),afterMount(({ values, actions }) => {actions.setDefaultTab(SessionRecordingSidebarTab.OVERVIEW)// Resolve whether the in-session scope can answer before the viewer picks it, so the optiondiff --git a/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsx b/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsxindex 35ec9e3a1827..2e224d0ce55c 100644--- a/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsx+++ b/frontend/src/scenes/experiments/MetricsView/new/ResultDetails.tsx@@ -1,21 +1,16 @@import { useValues } from 'kea'-import posthog from 'posthog-js'import { useState } from 'react'import { LemonCollapse, LemonTable, LemonTableColumns, LemonTabs } from '@posthog/lemon-ui'import { CodeSnippet, Language } from 'lib/components/CodeSnippet'-import ViewRecordingsPlaylistButton from 'lib/components/ViewRecordingButton/ViewRecordingsPlaylistButton'import { FEATURE_FLAGS } from 'lib/constants'import { humanFriendlyNumber } from 'lib/utils/numbers'import { ExperimentFunnelChart } from 'scenes/experiments/charts/funnel/ExperimentFunnelChart'import { experimentLogic } from 'scenes/experiments/experimentLogic'+import { getMetricRecordingModes } from 'scenes/experiments/ExperimentView/experimentRecordingModes'import { VariantTag } from 'scenes/experiments/ExperimentView/VariantTag'-import { applySessionLinkability, getExposureFallbackFilter, getViewRecordingFilters } from 'scenes/experiments/utils'-import {- EXPOSURE_UNLINKABLE_REASON,- viewRecordingsLinkabilityLogic,-} from 'scenes/experiments/viewRecordingsLinkabilityLogic'+import { viewRecordingsLinkabilityLogic } from 'scenes/experiments/viewRecordingsLinkabilityLogic'import {CachedNewExperimentQueryResponse,@@ -26,7 +21,7 @@ import {isExperimentMeanMetric,isExperimentRatioMetric,} from '~/queries/schema/schema-general'-import { Experiment, FilterLogicalOperator, RecordingUniversalFilters } from '~/types'+import { Experiment } from '~/types'import {ExperimentVariantResult,@@ -38,6 +33,7 @@ import {isBayesianResult,isFrequentistResult,} from '../shared/utils'+import { type ExperimentResultsSurface, VariantRecordingsButton } from './VariantRecordingsButton'function SqlCollapsible({hogql,@@ -106,17 +102,22 @@ export function ResultDetails({result,metric,embedded = false,+ surface = 'inline',}: {experiment: Experimentresult: CachedNewExperimentQueryResponsemetric: ExperimentMetric/** Renders the table, funnel, and SQL as divider-separated sections of a parent panel instead of standalone cards. */embedded?: boolean+ surface?: ExperimentResultsSurface}): JSX.Element {const { featureFlags } = useValues(experimentLogic)const { unlinkableEventNames, linkabilityLoaded } = useValues(viewRecordingsLinkabilityLogic({ experiment }))const baselineKey = result.baseline?.key+ // Every row links to the same metric, so the labels and the reasons are decided once. An empty+ // set while the check is in flight keeps today's fail-open behavior.+ const recordingModes = getMetricRecordingModes(metric, linkabilityLoaded ? unlinkableEventNames : new Set<string>())const columns: LemonTableColumns<ExperimentVariantResult & { key: string }> = [{@@ -188,71 +189,18 @@ export function ResultDetails({{key: 'recordings',title: '',- render: (_, item) => {- const variantKey = item.key- const filters = getViewRecordingFilters(experiment, metric, variantKey)-- // While the seenTogether check is in flight, keep today's behavior (fail open).- const {- filters: safeFilters,- droppedMetricEventCount,- exposureUnlinkable,- usedExposureFallback,- } = linkabilityLoaded- ? applySessionLinkability(- filters,- unlinkableEventNames,- getExposureFallbackFilter(experiment, variantKey)- )- : { filters, droppedMetricEventCount: 0, exposureUnlinkable: false, usedExposureFallback: false }-- const filterGroup: Partial<RecordingUniversalFilters> = {- filter_group: {- type: FilterLogicalOperator.And,- values: [- {- type: FilterLogicalOperator.And,- values: safeFilters,- },- ],- },- date_from: experiment?.start_date,- date_to: experiment?.end_date,- filter_test_accounts: experiment.exposure_criteria?.filterTestAccounts ?? false,- }-- return (- <ViewRecordingsPlaylistButton- filters={filterGroup}- size="xsmall"- type="secondary"- tooltip={[- usedExposureFallback- ? "Watch recordings of sessions where this variant's flag was active. The exposure event is captured server-side without a session ID, so exact exposures can't be matched."- : 'Watch recordings of people who were exposed to this variant.',- ...(droppedMetricEventCount > 0- ? [- `Excluded ${droppedMetricEventCount} server-side ${- droppedMetricEventCount === 1 ? 'event' : 'events'- } captured without a session ID, which can't match recordings.`,- ]- : []),- ].join(' ')}- disabled={safeFilters.length === 0}- disabledReason={- exposureUnlinkable- ? EXPOSURE_UNLINKABLE_REASON- : filters.length === 0- ? 'Unable to identify recordings for this metric'- : undefined- }- data-attr="experiment-metrics-view-recordings"- onClick={() => {- posthog.capture('viewed recordings from experiment', { variant: variantKey })- }}+ render: (_, item) => (+ <div className="flex justify-end">+ <VariantRecordingsButton+ experiment={experiment}+ metric={metric}+ variantKey={item.key}+ isBaseline={item.key === baselineKey}+ surface={surface}+ modes={recordingModes}/>- )- },+ </div>+ ),},]diff --git a/frontend/src/scenes/experiments/MetricsView/new/VariantRecordingsButton.test.tsx b/frontend/src/scenes/experiments/MetricsView/new/VariantRecordingsButton.test.tsxnew file mode 100644index 000000000000..d5e2f6243c4e--- /dev/null+++ b/frontend/src/scenes/experiments/MetricsView/new/VariantRecordingsButton.test.tsx@@ -0,0 +1,69 @@+import { render } from '@testing-library/react'++import { type ExperimentRecordingModes } from 'scenes/experiments/ExperimentView/experimentRecordingModes'++import { ExperimentMetric, ExperimentMetricType, NodeKind } from '~/queries/schema/schema-general'+import { Experiment } from '~/types'++import { VariantRecordingsButton } from './VariantRecordingsButton'++const experiment = { id: 7 } as Experiment++const metric = {+ kind: NodeKind.ExperimentMetric,+ metric_type: ExperimentMetricType.MEAN,+ uuid: 'metric-mean',+ source: { kind: NodeKind.EventsNode, event: 'purchase' },+} as unknown as ExperimentMetric++const modes = (overrides: Partial<ExperimentRecordingModes>): ExperimentRecordingModes => ({+ metricSelectable: true,+ unselectableReason: null,+ defaultMode: 'fired_all',+ menuItems: [+ { mode: 'fired_all', label: 'Fired purchase', tooltip: '', disabledReason: null },+ { mode: 'no_metric_activity', label: "Didn't fire purchase", tooltip: '', disabledReason: null },+ ],+ ...overrides,+})++describe('VariantRecordingsButton', () => {+ it.each([+ {+ case: 'a metric the tab accepts links straight to its default population',+ modes: modes({}),+ expectedHref: expect.stringContaining('metric_filter=fired_all'),+ expectedDisabled: 'false',+ },+ {+ // Without this the one click opens the variant's whole list under a label that promises+ // the metric's population, which is the question the row was asked.+ case: 'a metric the tab would drop disables the one-click link',+ modes: modes({+ metricSelectable: false,+ unselectableReason: 'Retention metrics cannot be matched to recordings.',+ defaultMode: null,+ }),+ expectedHref: null,+ expectedDisabled: 'true',+ },+ ])('$case', ({ modes: recordingModes, expectedHref, expectedDisabled }) => {+ const { container } = render(+ <VariantRecordingsButton+ experiment={experiment}+ metric={metric}+ variantKey="test"+ isBaseline={false}+ surface="inline"+ modes={recordingModes}+ />+ )++ const button = container.querySelector('[data-attr="experiment-metrics-view-recordings"]')++ expect(button?.getAttribute('aria-disabled')).toEqual(expectedDisabled)+ expect(button?.getAttribute('href')).toEqual(expectedHref)+ // The caret keeps offering the variant's whole list, named, even when the metric is dropped.+ expect(container.querySelector('[data-attr="experiment-metrics-recordings-menu"]')).not.toBeNull()+ })+})diff --git a/frontend/src/scenes/experiments/MetricsView/new/VariantRecordingsButton.tsx b/frontend/src/scenes/experiments/MetricsView/new/VariantRecordingsButton.tsxnew file mode 100644index 000000000000..746201a31975--- /dev/null+++ b/frontend/src/scenes/experiments/MetricsView/new/VariantRecordingsButton.tsx@@ -0,0 +1,137 @@+import posthog from 'posthog-js'++import { IconChevronDown, IconRewindPlay } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu'+import { type ExperimentRecordingModes } from 'scenes/experiments/ExperimentView/experimentRecordingModes'+import {+ type ExperimentRecordingsEntryPoint,+ type ExperimentReplayMetricFilterMode,+ experimentRecordingsUrl,+} from 'scenes/experiments/ExperimentView/experimentRecordingsDeepLink'++import { ExperimentMetric } from '~/queries/schema/schema-general'+import { Experiment } from '~/types'++/** Where the results table is rendered, so telemetry can tell the inline table from the modal. */+export type ExperimentResultsSurface = 'inline' | 'details_modal'++export interface VariantRecordingsButtonProps {+ experiment: Experiment+ metric: ExperimentMetric+ variantKey: string+ /** The baseline row answers a different question, so its clicks are counted separately. */+ isBaseline: boolean+ surface: ExperimentResultsSurface+ /** Resolved once for the whole table, since every row links to the same metric. */+ modes: ExperimentRecordingModes+}++/**+ * The recordings link on a variant row: one click opens the Recordings tab on the metric's default+ * population, and the caret offers the other populations plus every recording of the variant.+ *+ * The tab scopes its list per person through the experiment's exposure, so no link here needs an+ * exposure filter of its own.+ */+export function VariantRecordingsButton({+ experiment,+ metric,+ variantKey,+ isBaseline,+ surface,+ modes,+}: VariantRecordingsButtonProps): JSX.Element {+ const { metricSelectable, unselectableReason, defaultMode, menuItems } = modes+ // A metric the tab would drop must not reach the URL, or the list would answer without the+ // filter the label promised.+ const metricUuid = metricSelectable ? (metric.uuid ?? null) : null++ const linkTo = (+ metricFilterMode: ExperimentReplayMetricFilterMode | null,+ entry: ExperimentRecordingsEntryPoint+ ): string =>+ experimentRecordingsUrl(experiment.id, {+ variantKey,+ metricUuid: metricFilterMode === null ? null : metricUuid,+ metricFilterMode,+ entry,+ })++ const trackClick = (+ metricFilterMode: ExperimentReplayMetricFilterMode | null,+ trigger: 'button' | 'menu'+ ): void => {+ // Pinned: a dashboard counts this event name.+ posthog.capture('viewed recordings from experiment', {+ variant: variantKey,+ metric_kind: metric.metric_type,+ metric_filter: metricFilterMode,+ trigger,+ surface,+ is_baseline: isBaseline,+ })+ }++ return (+ <LemonButton+ size="xsmall"+ type="secondary"+ truncate+ icon={<IconRewindPlay />}+ tooltip="Watch recordings of this variant on the Recordings tab."+ // Without a default mode the one click would open the variant's whole list under a+ // label that promises the metric's population. The caret still offers that list, named.+ disabledReason={defaultMode === null ? unselectableReason : null}+ to={linkTo(defaultMode, 'results_button')}+ data-attr="experiment-metrics-view-recordings"+ onClick={() => trackClick(defaultMode, 'button')}+ sideAction={{+ icon: <IconChevronDown />,+ 'data-attr': 'experiment-metrics-recordings-menu',+ tooltip: 'Pick which recordings to watch',+ dropdown: {+ placement: 'bottom-end',+ onVisibilityChange: (visible) => {+ if (visible) {+ posthog.capture('experiment recordings menu opened', {+ variant: variantKey,+ metric_kind: metric.metric_type,+ surface,+ })+ }+ },+ overlay: (+ <LemonMenuOverlay+ items={[+ {+ title: `Watch recordings of ${variantKey}`,+ items: [+ ...menuItems.map((item) => ({+ label: item.label,+ tooltip: item.tooltip,+ disabledReason: item.disabledReason ?? undefined,+ to: linkTo(item.mode, 'results_menu'),+ 'data-attr': `experiment-metrics-recordings-menu-${item.mode}`,+ onClick: () => trackClick(item.mode, 'menu'),+ })),+ {+ label: 'All recordings of this variant',+ tooltip: 'Watch every recording of this variant, with no metric filter.',+ to: linkTo(null, 'results_menu'),+ 'data-attr': 'experiment-metrics-recordings-menu-all',+ onClick: () => trackClick(null, 'menu'),+ },+ ],+ },+ ]}+ />+ ),+ },+ }}+ >+ View recordings+ </LemonButton>+ )+}diff --git a/frontend/src/scenes/experiments/experimentSceneLogic.tsx b/frontend/src/scenes/experiments/experimentSceneLogic.tsxindex 02dd5d6d2390..5a7e3c8eaa45 100644--- a/frontend/src/scenes/experiments/experimentSceneLogic.tsx+++ b/frontend/src/scenes/experiments/experimentSceneLogic.tsx@@ -35,6 +35,7 @@ import {type FormModes,experimentLogic,} from './experimentLogic'+import { EXPERIMENT_RECORDINGS_DEEP_LINK_PARAMS } from './ExperimentView/experimentRecordingsDeepLink'import { stepStorageKey } from './ExperimentWizard/experimentWizardLogic'import { modalsLogic } from './modalsLogic'import { isLegacyExperiment } from './utils'@@ -457,13 +458,20 @@ export const experimentSceneLogic = kea<experimentSceneLogicType>([// 'new' keeps the full search so the ?metric=/?name= prefill survives, while numeric ids// keep only the params this scene owns: shared links (?tab=, ?activity=) survive the- // initial setSceneState, and the create flow still drops the prefill params.+ // initial setSceneState, and the create flow still drops the prefill params. The+ // recordings tab's deep-link params are kept for the same reason: the tab consumes them+ // on mount and removes them itself (see `experimentRecordingsDeepLink.ts`).const currentSearch = router.values.currentLocation.searchParamsconst search =id === 'new'? currentSearch: Object.fromEntries(- Object.entries(currentSearch).filter(([key]) => key === 'tab' || key === 'activity')+ Object.entries(currentSearch).filter(+ ([key]) =>+ key === 'tab' ||+ key === 'activity' ||+ EXPERIMENT_RECORDINGS_DEEP_LINK_PARAMS.some((param) => param === key)+ ))return [urls.experiment(id, effectiveFormMode), search, router.values.hashParams]}diff --git a/frontend/src/scenes/experiments/stories/ExperimentRecordingsListEmpty.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentRecordingsListEmpty.stories.tsxindex d32cdf9fba13..0573792780ee 100644--- a/frontend/src/scenes/experiments/stories/ExperimentRecordingsListEmpty.stories.tsx+++ b/frontend/src/scenes/experiments/stories/ExperimentRecordingsListEmpty.stories.tsx@@ -155,3 +155,33 @@ export const ExperimentRecordingsEmptyMetricFilterFailed: Story = {decorators: [mswDecorator({ post: { [SESSION_BUCKETS_PATH]: [400, { detail: 'Could not resolve the filter' }] } })],play: pickFiredNone,}++/**+ * The same matched-nothing state, reached by a results-row link rather than by hand. This is the+ * one place the whole deep link runs end to end: the scene keeps the params through its first URL+ * pass, and the tab applies them on mount, so the variant facet and the drop-off trigger label are+ * already set when the list lands.+ */+export const ExperimentRecordingsEmptyFromResultsRow: Story = {+ parameters: {+ pageUrl: `${urls.experiment(EXPERIMENT_WITH_FUNNEL_METRIC.id)}?tab=recordings&variant=test-1&metric_uuid=${+ EXPERIMENT_WITH_FUNNEL_METRIC.metrics[0].uuid+ }&metric_filter=funnel_dropoff`,+ testOptions: { waitForSelector: '[data-attr="experiment-recordings-empty-state"] .LemonBanner' },+ },+ decorators: [+ mswDecorator({+ post: {+ [SESSION_BUCKETS_PATH]: {+ session_ids: [],+ truncated: false,+ considered_metrics: [{ metric_uuid: 'funnel', metric_name: 'Checkout funnel' }],+ excluded_metrics: [],+ date_from: '2025-05-25T00:00:00Z',+ date_to: '2025-06-01T00:00:00Z',+ filter_test_accounts: true,+ },+ },+ }),+ ],+}diff --git a/frontend/src/scenes/experiments/stories/ExperimentResultsRowRecordingLinks.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentResultsRowRecordingLinks.stories.tsxnew file mode 100644index 000000000000..b654cf51d45a--- /dev/null+++ b/frontend/src/scenes/experiments/stories/ExperimentResultsRowRecordingLinks.stories.tsx@@ -0,0 +1,123 @@+import { Meta, StoryObj } from '@storybook/react'+import { waitFor } from '@testing-library/dom'+import userEvent from '@testing-library/user-event'++import { App } from 'scenes/App'+import { urls } from 'scenes/urls'++import { mswDecorator } from '~/mocks/browser'+import EXPERIMENT_WITH_FUNNEL_METRIC from '~/mocks/fixtures/api/experiments/experiment_with_funnel_metric.json'+import EXPERIMENT_WITH_MEAN_METRIC from '~/mocks/fixtures/api/experiments/experiment_with_mean_metric.json'+import EXPOSURE_QUERY_RESULT from '~/mocks/fixtures/api/experiments/exposure_query_result.json'+import FUNNELS_METRIC_RESULT from '~/mocks/fixtures/api/experiments/funnel_metric_result.json'+import MEAN_METRIC_RESULT from '~/mocks/fixtures/api/experiments/mean_metric_result.json'+import { NodeKind } from '~/queries/schema/schema-general'++// The split button each variant row offers. The menu is the feature: it names the populations the+// Recordings tab can open for this metric, and a funnel names different ones from a mean metric.+const MAIN_BUTTON = '[data-attr="experiment-metrics-view-recordings"]'++const meta: Meta = {+ component: App,+ title: 'Scenes-App/Experiments',+ parameters: {+ layout: 'fullscreen',+ viewMode: 'story',+ mockDate: '2025-01-27',+ pageUrl: urls.experiment(EXPERIMENT_WITH_FUNNEL_METRIC.id),+ testOptions: { waitForSelector: MAIN_BUTTON },+ },+ decorators: [+ mswDecorator({+ get: {+ [`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_FUNNEL_METRIC.id}/`]:+ EXPERIMENT_WITH_FUNNEL_METRIC,+ [`/api/projects/:team_id/experiments/${EXPERIMENT_WITH_MEAN_METRIC.id}/`]: EXPERIMENT_WITH_MEAN_METRIC,+ '/api/projects/:team_id/experiment_holdouts': [],+ '/api/projects/:team_id/experiment_saved_metrics/': [],+ [`/api/projects/:team_id/feature_flags/${EXPERIMENT_WITH_FUNNEL_METRIC.feature_flag.id}/`]: {},+ [`/api/projects/:team_id/feature_flags/${EXPERIMENT_WITH_FUNNEL_METRIC.feature_flag.id}/status/`]: {},+ [`/api/projects/:team_id/feature_flags/${EXPERIMENT_WITH_MEAN_METRIC.feature_flag.id}/`]: {},+ [`/api/projects/:team_id/feature_flags/${EXPERIMENT_WITH_MEAN_METRIC.feature_flag.id}/status/`]: {},+ '/api/environments/:team_id/default_release_conditions/': [],+ '/api/environments/:team_id/experiments_config/': {},+ // The linkability check decides whether the menu items are offered or disabled, so+ // it is answered here rather than left to fail open on a missing handler.+ '/api/projects/:team_id/property_definitions/seen_together': {},+ },+ post: {+ // Answered so the scene does not raise a failure toast over the table.+ '/api/projects/:team_id/experiments/calculate_running_time/': {},+ '/api/environments/:team_id/query/:kind': async ({ request }) => {+ const body = (await request.json()) as Record<string, any>++ if (body.query.kind === NodeKind.ExperimentExposureQuery) {+ return [200, EXPOSURE_QUERY_RESULT]+ }++ return [200, FUNNELS_METRIC_RESULT]+ },+ },+ }),+ ],+}+export default meta++type Story = StoryObj<{}>++const meanMetricDecorator = mswDecorator({+ post: {+ '/api/environments/:team_id/query/:kind': async ({ request }) => {+ const body = (await request.json()) as Record<string, any>++ if (body.query.kind === NodeKind.ExperimentExposureQuery) {+ return [200, EXPOSURE_QUERY_RESULT]+ }++ return [200, MEAN_METRIC_RESULT]+ },+ },+})++/**+ * Opens the first row's menu. Storybook leaves testing-library's test id attribute at its default,+ * unlike jest and Playwright, so a `data-attr` has to be matched as a plain attribute.+ */+const openFirstRowMenu: Story['play'] = async ({ canvasElement }) => {+ const caret = await waitFor(() => {+ const button = canvasElement.querySelector<HTMLElement>('[data-attr="experiment-metrics-recordings-menu"]')+ if (!button) {+ throw new Error('recordings menu caret not yet rendered')+ }+ return button+ })+ await userEvent.click(caret)+}++/** The one-click path: the button names the action, not the population it opens. */+export const ExperimentResultsRowRecordingLinksFunnel: Story = {}++/** A funnel's menu: the two halves of the funnel, then every recording of the variant. */+export const ExperimentResultsRowRecordingLinksFunnelMenu: Story = {+ play: openFirstRowMenu,+}++/** A mean metric's menu names the event a session has to have fired. */+export const ExperimentResultsRowRecordingLinksMeanMenu: Story = {+ parameters: { pageUrl: urls.experiment(EXPERIMENT_WITH_MEAN_METRIC.id) },+ decorators: [meanMetricDecorator],+ play: openFirstRowMenu,+}++/**+ * The ~520px of scene a nav sidebar and an open side panel leave, where the button has to hold its+ * column rather than push the rest of the table out of reach.+ */+export const ExperimentResultsRowRecordingLinksNarrow: Story = {+ parameters: {+ testOptions: {+ waitForSelector: MAIN_BUTTON,+ viewport: { width: 767, height: 1200 },+ },+ },+}diff --git a/frontend/src/scenes/experiments/utils.test.ts b/frontend/src/scenes/experiments/utils.test.tsindex 49834f8cbef1..a734724e43a3 100644--- a/frontend/src/scenes/experiments/utils.test.ts+++ b/frontend/src/scenes/experiments/utils.test.ts@@ -24,7 +24,6 @@ import {FeatureFlagType,PropertyFilterType,PropertyOperator,- UniversalFiltersGroupValue,} from '~/types'import { filterToMetricConfig } from './metricQueryUtils'@@ -33,18 +32,14 @@ import {FUNNEL_DATA_WAREHOUSE_COMPLETION_REASON,FUNNEL_SERVER_SIDE_COMPLETION_REASON,NOT_A_FUNNEL_REASON,- applySessionLinkability,exposureConfigToFilter,featureFlagEligibleForExperiment,filterToExposureConfig,getBaselineVariantKey,getEventCountQuery,- getExposureFallbackFilter,getFunnelDropoffReason,getOrderedMetricsWithResults,getSessionLinkabilityEventNames,- getViewRecordingFilters,- getViewRecordingFiltersForVariant,getViewRecordingFiltersLegacy,isEvenlyDistributed,isLegacyExperiment,@@ -139,411 +134,6 @@ describe('getNiceTickValues', () => {})})-describe('getViewRecordingFilters', () => {- const experimentBase = {- id: 1,- name: 'test experiment',- feature_flag_key: 'my-flag',- 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,- }-- it('adds exposure criteria if present', () => {- const experiment = {- ...experimentBase,- exposure_criteria: {- exposure_config: {- kind: NodeKind.ExperimentEventExposureConfig,- event: 'exposure_event',- properties: [- {- key: 'foo',- value: 'bar',- operator: PropertyOperator.IsNot,- type: PropertyFilterType.Event,- },- ],- },- },- } satisfies Experiment-- const metric = {- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: 'event1', name: 'event1' },- } satisfies ExperimentMetric-- const filters = getViewRecordingFilters(experiment, metric, 'variantA')- expect(filters[0]).toEqual({- id: 'exposure_event',- name: 'exposure_event',- type: 'events',- properties: [- {- key: 'foo',- value: 'bar',- operator: PropertyOperator.IsNot,- type: PropertyFilterType.Event,- },- {- key: '$feature/my-flag',- type: PropertyFilterType.Event,- value: ['variantA'],- operator: PropertyOperator.Exact,- },- ],- })- })-- it('adds default exposure event if no exposure criteria', () => {- const experiment = { ...experimentBase }- const metric = {- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: 'event1', name: 'event1' },- } satisfies ExperimentMetric-- const filters = getViewRecordingFilters(experiment, metric, 'variantA')- expect(filters[0]).toEqual({- id: '$feature_flag_called',- name: '$feature_flag_called',- type: 'events',- properties: [- {- key: '$feature_flag_response',- type: PropertyFilterType.Event,- value: ['variantA'],- operator: PropertyOperator.Exact,- },- {- key: '$feature_flag',- type: PropertyFilterType.Event,- value: 'my-flag',- operator: PropertyOperator.Exact,- },- ],- })- })-- it('falls back to default exposure event if exposure_criteria exists but exposure_config is undefined', () => {- const experiment = {- ...experimentBase,- exposure_criteria: {- exposure_config: undefined,- },- } satisfies Experiment-- const metric = {- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: 'event1', name: 'event1' },- } satisfies ExperimentMetric-- const filters = getViewRecordingFilters(experiment, metric, 'variantA')- expect(filters[0]).toEqual({- id: '$feature_flag_called',- name: '$feature_flag_called',- type: 'events',- properties: [- {- key: '$feature_flag_response',- type: PropertyFilterType.Event,- value: ['variantA'],- operator: PropertyOperator.Exact,- },- {- key: '$feature_flag',- type: PropertyFilterType.Event,- value: 'my-flag',- operator: PropertyOperator.Exact,- },- ],- })- })-- it('adds mean metric event filter (no extra properties)', () => {- const experiment = { ...experimentBase }- const metric = {- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.EventsNode, event: 'event1', name: 'event1' },- } satisfies ExperimentMetric-- const filters = getViewRecordingFilters(experiment, metric, 'variantA')- expect(filters[1]).toEqual({- id: 'event1',- name: 'event1',- type: 'events',- properties: [],- })- })-- it('adds mean metric event filter (with properties)', () => {- const experiment = { ...experimentBase }- const metric = {- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: {- kind: NodeKind.EventsNode,- event: 'event1',- name: 'event1',- properties: [- { key: 'foo', value: 'bar', operator: PropertyOperator.Exact, type: PropertyFilterType.Event },- ],- },- } satisfies ExperimentMetric-- const filters = getViewRecordingFilters(experiment, metric, 'variantA')- expect(filters[1]).toEqual({- id: 'event1',- name: 'event1',- type: 'events',- properties: [- {- key: 'foo',- value: 'bar',- operator: PropertyOperator.Exact,- type: PropertyFilterType.Event,- },- ],- })- })-- it('adds mean metric action filter', () => {- const experiment = { ...experimentBase }- const metric = {- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.MEAN,- source: { kind: NodeKind.ActionsNode, id: 123, name: 'action1' },- } satisfies ExperimentMetric-- const filters = getViewRecordingFilters(experiment, metric, 'variantA')- expect(filters[1]).toEqual({- id: 123,- name: 'action1',- type: 'actions',- })- })-- it('adds funnel metric filters for each series', () => {- const experiment = { ...experimentBase }- const metric = {- kind: NodeKind.ExperimentMetric,- metric_type: ExperimentMetricType.FUNNEL,- series: [- {- kind: NodeKind.EventsNode,- event: 'event1',- name: 'event1',- properties: [- { key: 'bar', value: 'baz', operator: PropertyOperator.Exact, type: PropertyFilterType.Event },- ],- },- { kind: NodeKind.ActionsNode, id: 123, name: 'action1' },- ],- } satisfies ExperimentMetric-- const filters = getViewRecordingFilters(experiment, metric, 'variantA')- expect(filters[1]).toEqual({- id: 'event1',- name: 'event1',- type: 'events',- properties: [- { key: 'bar', value: 'baz', operator: PropertyOperator.Exact, type: PropertyFilterType.Event },- ],- })- expect(filters[2]).toEqual({- id: 123,- name: 'action1',- type: 'actions',- })- })-})--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('getExposureFallbackFilter', () => {- it.each([- {- desc: 'default exposure, specific variant: property filter on the flag value',- experiment: experimentBase,- variantKey: 'variantA',- expected: {- key: '$feature/my-flag',- type: PropertyFilterType.Event,- value: ['variantA'],- operator: PropertyOperator.Exact,- },- },- {- desc: 'default exposure, all variants: matches the flag value against every variant',- experiment: experimentBase,- variantKey: undefined,- expected: {- key: '$feature/my-flag',- type: PropertyFilterType.Event,- value: ['control', 'test'],- operator: PropertyOperator.Exact,- },- },- {- desc: 'default exposure, unknown flag variants: falls back to the flag value being set',- experiment: { ...experimentBase, feature_flag: undefined },- variantKey: undefined,- expected: {- key: '$feature/my-flag',- type: PropertyFilterType.Event,- value: PropertyOperator.IsSet,- operator: PropertyOperator.IsSet,- },- },- {- desc: 'custom exposure: no fallback, a flag-value filter cannot stand in for custom criteria',- experiment: { ...experimentBase, ...customExposure },- variantKey: 'variantA',- expected: null,- },- ])('$desc', ({ experiment, variantKey, expected }) => {- expect(getExposureFallbackFilter(experiment, variantKey)).toEqual(expected)- })- })-})-describe('getSessionLinkabilityEventNames', () => {const experimentBase = {id: 1,@@ -631,113 +221,6 @@ describe('getSessionLinkabilityEventNames', () => {})})-describe('applySessionLinkability', () => {- const exposureFilter: UniversalFiltersGroupValue = {- id: '$feature_flag_called',- name: '$feature_flag_called',- type: 'events',- properties: [],- }- const purchaseEventFilter: UniversalFiltersGroupValue = {- id: 'purchase',- name: 'purchase',- type: 'events',- properties: [],- }- const checkoutEventFilter: UniversalFiltersGroupValue = {- id: 'checkout',- name: 'checkout',- type: 'events',- properties: [],- }- const purchaseActionFilter: UniversalFiltersGroupValue = { id: 123, name: 'purchase', type: 'actions' }- const fallbackFilter: UniversalFiltersGroupValue = {- key: '$feature/my-flag',- type: PropertyFilterType.Event,- value: ['test'],- operator: PropertyOperator.Exact,- }-- it.each([- {- case: 'keeps everything when nothing is unlinkable',- filters: [exposureFilter, purchaseEventFilter],- unlinkable: new Set<string>(),- fallback: null,- expected: {- filters: [exposureFilter, purchaseEventFilter],- droppedMetricEventCount: 0,- exposureUnlinkable: false,- usedExposureFallback: false,- },- },- {- case: 'drops unlinkable metric event steps but keeps the rest',- filters: [exposureFilter, purchaseEventFilter, checkoutEventFilter],- unlinkable: new Set(['purchase']),- fallback: null,- expected: {- filters: [exposureFilter, checkoutEventFilter],- droppedMetricEventCount: 1,- exposureUnlinkable: false,- usedExposureFallback: false,- },- },- {- case: 'lets action steps pass through unchecked even when their name matches',- filters: [exposureFilter, purchaseActionFilter],- unlinkable: new Set(['purchase']),- fallback: null,- expected: {- filters: [exposureFilter, purchaseActionFilter],- droppedMetricEventCount: 0,- exposureUnlinkable: false,- usedExposureFallback: false,- },- },- {- case: 'empties the filters when the exposure event is unlinkable and there is no fallback',- filters: [exposureFilter, purchaseEventFilter],- unlinkable: new Set(['$feature_flag_called']),- fallback: null,- expected: {- filters: [],- droppedMetricEventCount: 0,- exposureUnlinkable: true,- usedExposureFallback: false,- },- },- {- case: 'substitutes the fallback for an unlinkable exposure event, still dropping unlinkable metric steps',- filters: [exposureFilter, purchaseEventFilter, checkoutEventFilter],- unlinkable: new Set(['$feature_flag_called', 'purchase']),- fallback: fallbackFilter,- expected: {- filters: [fallbackFilter, checkoutEventFilter],- droppedMetricEventCount: 1,- exposureUnlinkable: false,- usedExposureFallback: true,- },- },- {- case: 'keeps the exposure event over the fallback when it is linkable',- filters: [exposureFilter, purchaseEventFilter],- unlinkable: new Set<string>(),- fallback: fallbackFilter,- expected: {- filters: [exposureFilter, purchaseEventFilter],- droppedMetricEventCount: 0,- exposureUnlinkable: false,- usedExposureFallback: false,- },- },- ])('$case', ({ filters, unlinkable, fallback, expected }) => {- const input = [...filters]- expect(applySessionLinkability(filters, unlinkable, fallback)).toEqual(expected)- expect(filters).toEqual(input) // does not mutate its input- })-})-describe('getFunnelDropoffReason', () => {const unlinkable = new Set(['server_side_step'])const clientStep = { kind: NodeKind.EventsNode, event: 'client_step' }diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.tsindex 797f6075ca64..b11cd0abfc74 100644--- a/frontend/src/scenes/experiments/utils.ts+++ b/frontend/src/scenes/experiments/utils.ts@@ -30,7 +30,6 @@ import {} from '~/queries/schema/schema-general'import { isFunnelsQuery, isNodeWithSource, isTrendsQuery, isValidQueryForExperiment } from '~/queries/utils'import {- AnyPropertyFilter,ChartDisplayType,Experiment,ExperimentMetricGoal,@@ -216,188 +215,6 @@ 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 resolveVariantKeys(experiment: Experiment, variantKey?: string | string[]): string[] {- if (variantKey === undefined) {- return getExperimentVariants(experiment).map((variant) => variant.key)- }- return Array.isArray(variantKey) ? variantKey : [variantKey]-}--function createExposureFilter(- exposureConfig: ExperimentExposureConfig,- featureFlagKey: string,- variantKeys: string[]-): UniversalFiltersGroupValue {- const isEvent = isEventExposureConfig(exposureConfig)- return {- id: isEvent ? exposureConfig.event || 'unknown' : exposureConfig.id,- name: isEvent ? exposureConfig.event || 'Unknown Event' : exposureConfig.name || `Action ${exposureConfig.id}`,- type: isEvent ? 'events' : 'actions',- properties: [- ...(exposureConfig.properties || []),- variantPropertyFilter(featureFlagVariantProperty(featureFlagKey), variantKeys),- ],- }-}--/**- * Exposure filter for an experiment's recordings: one variant (or a subset, when given an array),- * 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 getViewRecordingFiltersForVariant(- experiment: Experiment,- variantKey?: string | string[]-): UniversalFiltersGroupValue[] {- const variantKeys = resolveVariantKeys(experiment, variantKey)- const exposureConfig = experiment.exposure_criteria?.exposure_config- if (exposureConfig && !(isEventExposureConfig(exposureConfig) && exposureConfig.event === EXPOSURE_DEFAULT_EVENT)) {- return [createExposureFilter(exposureConfig, experiment.feature_flag_key, variantKeys)]- }-- const exposureEvent = resolvedExposureEvent(experiment)- return [- {- id: exposureEvent,- name: exposureEvent,- type: 'events',- properties: [- variantPropertyFilter(EXPOSURE_FEATURE_FLAG_RESPONSE_PROPERTY, variantKeys),- {- key: EXPOSURE_FEATURE_FLAG_PROPERTY,- type: PropertyFilterType.Event,- value: experiment.feature_flag_key,- operator: PropertyOperator.Exact,- },- ],- },- ]-}--/**- * Stand-in exposure filter for when the default `$feature_flag_called` exposure event is captured- * server-side and can never match a session. `posthog-js` stamps `$feature/<flag_key>` on every- * client-side event captured after flags load, so this property filter matches sessions where the- * flag was active regardless of where the flag was evaluated. It is an approximation of exposure,- * not the real thing: the property reflects the flag's value on each event, not the enrollment- * moment. Custom exposure criteria carry semantics (a specific event plus its property filters)- * that a flag-value filter can't stand in for, so those return null and keep the- * blank-with-explanation behavior.- */-export function getExposureFallbackFilter(- experiment: Experiment,- variantKey?: string | string[]-): UniversalFiltersGroupValue | null {- const exposureConfig = experiment.exposure_criteria?.exposure_config- if (exposureConfig && !(isEventExposureConfig(exposureConfig) && exposureConfig.event === EXPOSURE_DEFAULT_EVENT)) {- return null- }- const variantKeys = resolveVariantKeys(experiment, variantKey)- const propertyKey = featureFlagVariantProperty(experiment.feature_flag_key)- // Typed as an event property, not PropertyFilterType.Feature: the recordings query backend- // only routes event-typed filters through its events subquery (see `is_event_property` in- // posthog/session_recordings/queries/utils.py) and treats feature-typed ones as unexpected.- if (variantKeys.length === 0) {- return {- key: propertyKey,- type: PropertyFilterType.Event,- value: PropertyOperator.IsSet,- operator: PropertyOperator.IsSet,- }- }- return {- key: propertyKey,- type: PropertyFilterType.Event,- value: variantKeys,- 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 filters- */- if (- isExperimentMeanMetric(metric) &&- (metric.source.kind === NodeKind.EventsNode || metric.source.kind === NodeKind.ActionsNode)- ) {- const meanFilter = seriesToFilter(metric.source)- if (meanFilter) {- filters.push(meanFilter)- }- }-- /**- * for funnel metrics, we need to add each element in the series as a filter- */- if (isExperimentFunnelMetric(metric)) {- metric.series.forEach((series) => {- const funnelMetric = seriesToFilter(series)- if (funnelMetric) {- filters.push(funnelMetric)- }- })- }-- /**- * for ratio metrics, we add both numerator and denominator events to the filters- */- if (isExperimentRatioMetric(metric)) {- const numeratorFilter = seriesToFilter(metric.numerator)- const denominatorFilter = seriesToFilter(metric.denominator)-- if (numeratorFilter) {- filters.push(numeratorFilter)- }- if (denominatorFilter) {- filters.push(denominatorFilter)- }- }-- return filters-}-/*** Event/action filters for one metric's sources — the "session reached this metric" part of a* recordings query. Data-warehouse sources have no session events and are skipped, so a metric@@ -418,8 +235,19 @@ export function getMetricSessionFilters(metric: ExperimentMetric): UniversalFilt.filter((filter): filter is UniversalFiltersGroupValue => filter !== null)}-export const NOT_A_FUNNEL_REASON =- "This filter shows sessions that didn't finish a funnel, so it needs a funnel metric."+/**+ * The distinct events a metric counts. A metric's name is free text ("Rageclicks per user"), so+ * on its own it doesn't say what a session has to have fired to match.+ */+export function getMetricSourceEventNames(metric: ExperimentMetric): string[] {+ const names = getMetricSessionFilters(metric)+ // Only entity filters name an event; a nested filter group (which the type allows) doesn't.+ .flatMap((filter) => ('id' in filter ? [String(filter.name ?? filter.id ?? '')] : []))+ .filter(Boolean)+ return [...new Set(names)]+}++export const NOT_A_FUNNEL_REASON = "This filter reads a funnel's last step, so it needs a funnel metric."export const FUNNEL_SERVER_SIDE_COMPLETION_REASON ="This filter reads a funnel's last step. This one is captured server-side without a session ID, so recordings can't be matched."@@ -467,6 +295,32 @@ export function isUnlinkableEventFilter()}+export const METRIC_UNLINKABLE_REASON =+ "This metric's events are captured server-side without a session ID, so recordings can't be matched."++export const RETENTION_UNLINKABLE_REASON =+ 'Retention metrics measure a return visit, which happens in a later session than the one that starts it. No single recording can show both, so these metrics are left out of the filter.'++export const DATA_WAREHOUSE_UNLINKABLE_REASON =+ 'This metric is measured entirely in the data warehouse, which has no session events to match recordings on.'++/**+ * Why a metric can't narrow a recordings list, or null when it can. A metric is unlinkable when+ * every one of its sources is a never-session-linked event, or when it yields no session filter at+ * all (a retention metric, or one measured only in the data warehouse). Either way its filter could+ * only match zero sessions. Pass an empty `unlinkableEventNames` while the linkability check loads,+ * which fails open, the posture every linkability consumer shares.+ */+export function getMetricUnlinkableReason(metric: ExperimentMetric, unlinkableEventNames: Set<string>): string | null {+ const filters = getMetricSessionFilters(metric)+ if (filters.length === 0) {+ return isExperimentRetentionMetric(metric) ? RETENTION_UNLINKABLE_REASON : DATA_WAREHOUSE_UNLINKABLE_REASON+ }+ return filters.every((filter) => isUnlinkableEventFilter(filter, unlinkableEventNames))+ ? METRIC_UNLINKABLE_REASON+ : null+}+/*** The single event an experiment's exposure is counted on, for the session-linkability check.* Null for an action exposure config, which can match several events, so no one name applies.@@ -482,9 +336,8 @@ export function getExposureLinkabilityEventName(experiment: Experiment): string/*** Event names whose session-linkability must be checked before building "View recordings" links:* the exposure event plus every plain-event metric step across primary, secondary and shared- * metrics, mirroring how `getViewRecordingFilters` enumerates them. Action and data warehouse- * steps pass through unchecked (same as the replay playlist's own check), as do "all events"- * steps, which have no event name.+ * metrics. Action and data warehouse steps pass through unchecked (same as the replay playlist's+ * own check), as do "all events" steps, which have no event name.*/export function getSessionLinkabilityEventNames(experiment: Experiment): string[] {const eventNames = new Set<string>()@@ -518,50 +371,6 @@ export function getSessionLinkabilityEventNames(experiment: Experiment): string[return Array.from(eventNames)}-/**- * Post-filters `getViewRecordingFilters` output. Recordings are matched through events carrying- * a `$session_id`, so an event filter the project has never seen with that property (e.g. one- * captured server-side) would zero out the whole AND-combined recordings query. The exposure- * filter is always first. When it is itself unlinkable, `exposureFallbackFilter` (see- * `getExposureFallbackFilter`) takes its place with `usedExposureFallback: true`, so callers can- * label the result as "flag was active" rather than "exposed"; without a fallback there are no- * recordings to show at all.- */-export function applySessionLinkability(- filters: UniversalFiltersGroupValue[],- unlinkableEventNames: Set<string>,- exposureFallbackFilter: UniversalFiltersGroupValue | null = null-): {- filters: UniversalFiltersGroupValue[]- droppedMetricEventCount: number- exposureUnlinkable: boolean- usedExposureFallback: boolean-} {- const isUnlinkable = (filter: UniversalFiltersGroupValue): boolean =>- isUnlinkableEventFilter(filter, unlinkableEventNames)-- if (filters.length === 0) {- return { filters: [], droppedMetricEventCount: 0, exposureUnlinkable: false, usedExposureFallback: false }- }-- const [exposureFilter, ...metricFilters] = filters- const exposureIsUnlinkable = isUnlinkable(exposureFilter)- if (exposureIsUnlinkable && !exposureFallbackFilter) {- return { filters: [], droppedMetricEventCount: 0, exposureUnlinkable: true, usedExposureFallback: false }- }-- const keptMetricFilters = metricFilters.filter((filter) => !isUnlinkable(filter))- return {- filters: [- exposureIsUnlinkable && exposureFallbackFilter ? exposureFallbackFilter : exposureFilter,- ...keptMetricFilters,- ],- droppedMetricEventCount: metricFilters.length - keptMetricFilters.length,- exposureUnlinkable: false,- usedExposureFallback: exposureIsUnlinkable,- }-}-export function getViewRecordingFiltersLegacy(metric: ExperimentMetric | ExperimentTrendsQuery | ExperimentFunnelsQuery,featureFlagKey: string,diff --git a/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.tsindex 5e1f3b9b4d76..ac7c80a231ad 100644--- a/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts+++ b/frontend/src/scenes/experiments/viewRecordingsLinkabilityLogic.ts@@ -13,18 +13,6 @@ 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."--export const METRIC_UNLINKABLE_REASON =- "This metric's events are captured server-side without a session ID, so recordings can't be matched."--export const RETENTION_UNLINKABLE_REASON =- 'Retention metrics measure a return visit, which happens in a later session than the one that starts it. No single recording can show both, so these metrics are left out of the filter.'--export const DATA_WAREHOUSE_UNLINKABLE_REASON =- 'This metric is measured entirely in the data warehouse, which has no session events to match recordings on.'-/** Only an explicit `false` marks an event unlinkable; absent keys stay linkable (fail open). */export function unlinkableEventNamesFromSeenTogether(seenTogetherMap: Record<string, boolean> | null | undefineddiff --git a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsxindex 698da8071a86..17742de85030 100644--- a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx+++ b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarExperimentsSection.tsx@@ -287,8 +287,8 @@ function ExposureTime({ offsetMs, placement, onSeek }: ExposureTimeProps): JSX.E// The experiment analysis counts exposure events, and this session has none: that is the one claim// that holds wherever the viewer came from. The copy must not reference the recordings tab's list,-// because when the exposure event is server-side that tab falls back to listing flag-active sessions-// (see applySessionLinkability), and enrolled-only sessions are then exactly what its list shows.+// because when the exposure event is server-side that tab's in-session scope falls back to listing+// flag-active sessions, and enrolled-only sessions are then exactly what its list shows.const NOT_EXPOSED_CAVEAT ="The flag was active in this session, but no exposure event was captured here, so this session isn't where the experiment analysis counted this person's exposure."diff --git a/products/experiments/frontend/modals/DetailsModal/DetailsModal.tsx b/products/experiments/frontend/modals/DetailsModal/DetailsModal.tsxindex e7d18c921cab..73f2f4b53f1c 100644--- a/products/experiments/frontend/modals/DetailsModal/DetailsModal.tsx+++ b/products/experiments/frontend/modals/DetailsModal/DetailsModal.tsx@@ -26,7 +26,12 @@ export function DetailsModal({ isOpen, onClose, metric, result, experiment }: De</LemonButton>}>- <ResultDetails result={result} experiment={experiment} metric={metric as ExperimentMetric} />+ <ResultDetails+ result={result}+ experiment={experiment}+ metric={metric as ExperimentMetric}+ surface="details_modal"+ /></LemonModal>)}