Skip to content

: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.

feat(replay-vision): prefill the scanner wizard from an experiment deep link (#77965)

Kim Svatos Dugana7aea27c35da
diff --git a/frontend/src/scenes/experiments/utils.ts b/frontend/src/scenes/experiments/utils.ts
index e5f4aa9766b8..2c517bdfa94d 100644
--- a/frontend/src/scenes/experiments/utils.ts
+++ b/frontend/src/scenes/experiments/utils.ts
@@ -241,6 +241,13 @@ function variantPropertyFilter(propertyKey: string, variantKeys: string[]): AnyP
}
}
+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,
@@ -259,17 +266,16 @@ function createExposureFilter(
}
/**
- * Exposure filter for an experiment's recordings: one variant, or every enrolled session (variant
- * property IN the experiment's variants) when `variantKey` is omitted. Exposure-only — metric
- * steps are never added, so a metric event captured without a `$session_id` can't zero out the
- * result.
+ * 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
+ variantKey?: string | string[]
): UniversalFiltersGroupValue[] {
- const variantKeys =
- variantKey !== undefined ? [variantKey] : getExperimentVariants(experiment).map((variant) => variant.key)
+ 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)]
@@ -306,14 +312,13 @@ export function getViewRecordingFiltersForVariant(
*/
export function getExposureFallbackFilter(
experiment: Experiment,
- variantKey?: string
+ 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 =
- variantKey !== undefined ? [variantKey] : getExperimentVariants(experiment).map((variant) => variant.key)
+ 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
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 29ba26aa87b4..13a95c3eba59 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -702,13 +702,37 @@ class ReplayScannerFilter(django_filters.FilterSet):
raise ValidationError({"created_by": f"Non-numeric value(s) {invalid}; user IDs must be integers."})
return queryset.filter(created_by_id__in=tokens)
- @staticmethod
- def _filter_experiment_id(queryset: QuerySet[ReplayScanner], _name: str, value: str) -> QuerySet[ReplayScanner]:
+ def _filter_experiment_id(
+ self, queryset: QuerySet[ReplayScanner], _name: str, value: str
+ ) -> QuerySet[ReplayScanner]:
# An int, not NumberFilter's Decimal, which the JSONField lookup can't serialize to JSON.
# isdecimal, not isdigit: isdigit accepts characters like superscripts that int() rejects.
- if not value.strip().isdecimal() or int(value) < 1:
+ # Cap at the Postgres bigint max the id column can hold: a larger value can't be a real PK,
+ # and feeding it to the id lookup below raises NumericValueOutOfRange (a 500) instead of a 400.
+ stripped = value.strip()
+ if not stripped.isdecimal() or not 1 <= int(stripped) <= 9223372036854775807:
raise ValidationError({"experiment_id": "Must be a positive integer."})
- return queryset.filter(experiment_targeting__experiment_id=int(value))
+ experiment_id = int(stripped)
+ # Gate on the caller's experiment access, mirroring validate_experiment_targeting and
+ # _can_view_targeted_experiment: without it, a scanner-viewer could pass ?experiment_id= to
+ # confirm (by match count and returned scanner names) that a scanner targets an experiment
+ # they can't otherwise see. An inaccessible or nonexistent id reads as no matches.
+ if not self._caller_accessible_experiments().filter(id=experiment_id).exists():
+ return queryset.none()
+ return queryset.filter(experiment_targeting__experiment_id=experiment_id)
+
+ def _caller_accessible_experiments(self) -> QuerySet[Experiment]:
+ # Reuse the viewset's resolved team and access control rather than reparsing the URL:
+ # view.team_id handles @current and token-derived teams, and user_access_control is already
+ # built. The scanner queryset is already scoped to this same team.
+ view = self.request.parser_context.get("view") if self.request else None
+ if view is None:
+ return Experiment.objects.none()
+ team_experiments = Experiment.objects.filter(team_id=view.team_id)
+ access = view.user_access_control
+ if access is None:
+ return team_experiments
+ return access.filter_queryset_by_access_level(team_experiments)
@staticmethod
def _filter_search(queryset: QuerySet[ReplayScanner], _name: str, value: str) -> QuerySet[ReplayScanner]:
diff --git a/products/replay_vision/backend/tests/test_access_control.py b/products/replay_vision/backend/tests/test_access_control.py
index 8b69f42359b0..0407b383d30c 100644
--- a/products/replay_vision/backend/tests/test_access_control.py
+++ b/products/replay_vision/backend/tests/test_access_control.py
@@ -244,6 +244,38 @@ class TestReplayScannerAccessControl(_AccessControlTestCase):
resp = self.client.get(f"{self.scanners_url}{scanner.id}/")
self.assertEqual(resp.json()["experiment_targeting"], targeting)
+ def test_experiment_id_filter_returns_no_matches_for_an_inaccessible_experiment(self) -> None:
+ # Guards the ?experiment_id= disclosure: a scanner-viewer who can't access the experiment must
+ # not confirm a scanner targets it via the filter's match count. Distinct code path from the
+ # serializer redaction above — the scanner is hidden from the list entirely, not just nulled.
+ experiment = create_experiment(self.team, "hidden-flag")
+ targeting = {"experiment_id": experiment.id, "variant_keys": ["test"], "use_exposure_fallback": False}
+ self._create_scanner(name="targeted", experiment_targeting=targeting)
+ self._set_resource_default("replay_scanner", "viewer")
+ self._set_resource_default("experiment", "none")
+ self._grant_object_access(self.other_user, "experiment", str(experiment.id), "none")
+
+ self.client.force_login(self.other_user)
+ resp = self.client.get(f"{self.scanners_url}?experiment_id={experiment.id}")
+ self.assertEqual(resp.status_code, 200, resp.json())
+ self.assertEqual(resp.json()["results"], [])
+
+ # The creator, who can view the experiment, gets the match.
+ self.client.force_login(self.user)
+ resp = self.client.get(f"{self.scanners_url}?experiment_id={experiment.id}")
+ self.assertEqual([s["name"] for s in resp.json()["results"]], ["targeted"])
+
+ def test_experiment_id_filter_resolves_the_current_project_alias(self) -> None:
+ # The filter must resolve @current the way the viewset does, not pass the literal string to
+ # the DB lookup (which 500s). The user's current team is set by the test harness.
+ experiment = create_experiment(self.team, "aliased-flag")
+ targeting = {"experiment_id": experiment.id, "variant_keys": [], "use_exposure_fallback": False}
+ self._create_scanner(name="targeted", experiment_targeting=targeting)
+
+ resp = self.client.get(f"/api/environments/@current/vision/scanners/?experiment_id={experiment.id}")
+ self.assertEqual(resp.status_code, 200, resp.json())
+ self.assertEqual([s["name"] for s in resp.json()["results"]], ["targeted"])
+
class TestVisionActionAccessControlInheritance(_VisionActionAPITestCase):
def setUp(self) -> None:
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 41a02490e3f0..661ec36ba277 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -786,7 +786,17 @@ class TestScannerExperimentTargeting(_VisionAPITestCase):
self.assertEqual(resp.status_code, 200, resp.json())
self.assertEqual([row["name"] for row in resp.json()["results"]], ["for-exp"])
- @parameterized.expand([("superscript", "\u00b2"), ("zero", "0"), ("negative", "-1"), ("word", "abc")])
+ @parameterized.expand(
+ [
+ ("superscript", "\u00b2"),
+ ("zero", "0"),
+ ("negative", "-1"),
+ ("word", "abc"),
+ # One past the Postgres bigint max: feeding it to the id lookup would raise
+ # NumericValueOutOfRange (a 500) rather than the 400 a malformed filter should get.
+ ("above_bigint_max", "9223372036854775808"),
+ ]
+ )
def test_list_filter_rejects_non_positive_integers(self, _name: str, value: str) -> None:
resp = self.client.get(f"{self.scanners_url}?experiment_id={value}")
self.assertEqual(resp.status_code, 400)
diff --git a/products/replay_vision/frontend/replay_scanners/experimentTargeting.test.ts b/products/replay_vision/frontend/replay_scanners/experimentTargeting.test.ts
new file mode 100644
index 000000000000..c9650626a593
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/experimentTargeting.test.ts
@@ -0,0 +1,137 @@
+import { Experiment, PropertyFilterType, PropertyOperator } from '~/types'
+
+import {
+ buildExperimentScannerQuery,
+ experimentScannerName,
+ experimentScannerParams,
+ parseExperimentScannerParams,
+ reconcileVariantKeys,
+} from './experimentTargeting'
+
+const experiment = {
+ id: 7,
+ name: 'Checkout redesign',
+ feature_flag_key: 'checkout-redesign',
+ feature_flag: {
+ filters: {
+ multivariate: {
+ variants: [
+ { key: 'control', rollout_percentage: 50 },
+ { key: 'test', rollout_percentage: 50 },
+ ],
+ },
+ },
+ },
+ exposure_criteria: { filterTestAccounts: true },
+} as unknown as Experiment
+
+describe('experimentTargeting', () => {
+ it.each([
+ [{ experimentId: 7, variantKeys: [], useExposureFallback: false }],
+ [{ experimentId: 7, variantKeys: ['test'], useExposureFallback: false }],
+ [{ experimentId: 7, variantKeys: ['control', 'test'], useExposureFallback: true }],
+ ])('deep-link params round-trip through the parser: %j', (params) => {
+ expect(parseExperimentScannerParams(experimentScannerParams(params))).toEqual(params)
+ })
+
+ it.each([
+ [{}],
+ [{ experiment: 'not-a-number' }],
+ [{ experiment: '-3' }],
+ [{ variants: 'test' }],
+ // kea-router coerces `?experiment=true` to boolean true, and Number(true) is 1; without a
+ // type guard that would prefill experiment 1 rather than parse as null.
+ [{ experiment: true }],
+ [{ experiment: false }],
+ ])('params without a valid experiment id parse as null: %j', (searchParams) => {
+ expect(parseExperimentScannerParams(searchParams)).toBeNull()
+ })
+
+ it.each([
+ // kea-router hands single numeric query values back as numbers, not strings. The router
+ // values, not the stringified ones experimentScannerParams emits, are what the parser sees.
+ [{ experiment: 7 }, { experimentId: 7, variantKeys: [], useExposureFallback: false }],
+ [
+ { experiment: 7, variants: 1 },
+ { experimentId: 7, variantKeys: ['1'], useExposureFallback: false },
+ ],
+ [
+ { experiment: '7', variants: '1,2' },
+ { experimentId: 7, variantKeys: ['1', '2'], useExposureFallback: false },
+ ],
+ ])('parses raw router values (numbers, not strings): %j', (searchParams, expected) => {
+ expect(parseExperimentScannerParams(searchParams)).toEqual(expected)
+ })
+
+ it.each([
+ // No selection means every variant, so an empty request stays empty.
+ [[], []],
+ // A stale key that the experiment no longer has is dropped rather than persisted.
+ [['test', 'old-variant'], ['test']],
+ // When every requested key is unknown, fall back to the full variant set rather than the
+ // empty list that would broaden to an IsSet filter matching every enrolled session.
+ [['old-variant'], ['control', 'test']],
+ ])('reconciles requested variant keys against the experiment: %j', (requested, expected) => {
+ expect(reconcileVariantKeys(experiment, requested)).toEqual(expected)
+ })
+
+ it('compiles the default exposure event filter with the selected variants', () => {
+ const query = buildExperimentScannerQuery(experiment, ['test'], false)
+ expect(query.events).toEqual([
+ expect.objectContaining({
+ id: '$feature_flag_called',
+ properties: [
+ {
+ key: '$feature_flag_response',
+ type: PropertyFilterType.Event,
+ value: ['test'],
+ operator: PropertyOperator.Exact,
+ },
+ {
+ key: '$feature_flag',
+ type: PropertyFilterType.Event,
+ value: ['checkout-redesign'],
+ operator: PropertyOperator.Exact,
+ },
+ ],
+ }),
+ ])
+ expect(query.filter_test_accounts).toBe(true)
+ })
+
+ it('targets every variant when no subset is selected', () => {
+ const query = buildExperimentScannerQuery(experiment, [], false)
+ expect(query.events?.[0]?.properties?.[0]).toMatchObject({
+ key: '$feature_flag_response',
+ value: ['control', 'test'],
+ })
+ })
+
+ it('compiles the flag-value property filter in fallback mode', () => {
+ const query = buildExperimentScannerQuery(experiment, ['test'], true)
+ expect(query.events).toEqual([])
+ expect(query.properties).toEqual([
+ {
+ key: '$feature/checkout-redesign',
+ type: PropertyFilterType.Event,
+ value: ['test'],
+ operator: PropertyOperator.Exact,
+ },
+ ])
+ })
+
+ it('never persists playlist-only query fields', () => {
+ const query = buildExperimentScannerQuery(experiment, [], false)
+ expect(Object.keys(query)).toEqual(
+ expect.not.arrayContaining(['date_from', 'date_to', 'order', 'session_ids', 'limit'])
+ )
+ })
+
+ it.each([
+ ['Frustration score', 'Checkout redesign', 'Frustration score: Checkout redesign'],
+ ['', 'Checkout redesign', 'Checkout redesign'],
+ ['Base', 'x'.repeat(300), `Base: ${'x'.repeat(249)}`],
+ ])('experimentScannerName(%j, …) fits the 255-char model limit', (base, experimentName, expected) => {
+ expect(experimentScannerName(base, experimentName)).toEqual(expected)
+ })
+})
diff --git a/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts b/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts
new file mode 100644
index 000000000000..bdf233184146
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/experimentTargeting.ts
@@ -0,0 +1,168 @@
+import {
+ getExperimentVariants,
+ getExposureFallbackFilter,
+ getViewRecordingFiltersForVariant,
+} from 'scenes/experiments/utils'
+import { convertUniversalFiltersToRecordingsQuery } from 'scenes/session-recordings/filters/recordingsQueryConversions'
+import { DEFAULT_RECORDING_FILTERS } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'
+
+import { RecordingsQuery } from '~/queries/schema/schema-general'
+import { Experiment, FilterLogicalOperator, UniversalFiltersGroupValue } from '~/types'
+
+import type { ReplayScanner } from './types'
+
+/**
+ * Experiment context a scanner is being created against. Held by replayScannerLogic for the
+ * lifetime of the wizard so the Triggers step can offer variant targeting instead of raw filters.
+ * An empty `variantKeys` means every variant of the experiment.
+ */
+export interface ExperimentScannerContext {
+ experiment: Experiment
+ variantKeys: string[]
+ /**
+ * When the experiment's default exposure event is captured server-side (no `$session_id`),
+ * the entry point passes this so the scanner filters on `$feature/<flag_key>` instead of an
+ * exposure event that can never match a recording. Mirrors the experiment Recordings tab's
+ * fallback behavior; the linkability check already ran there, so the deep link carries the
+ * answer rather than re-running it here.
+ */
+ useExposureFallback: boolean
+}
+
+export interface ExperimentScannerParams {
+ experimentId: number
+ variantKeys: string[]
+ useExposureFallback: boolean
+}
+
+/** Builds the search params an entry point appends to a new-scanner wizard URL. */
+export function experimentScannerParams(params: ExperimentScannerParams): Record<string, string> {
+ const result: Record<string, string> = { experiment: String(params.experimentId) }
+ if (params.variantKeys.length > 0) {
+ result.variants = params.variantKeys.join(',')
+ }
+ if (params.useExposureFallback) {
+ result.exposure = 'fallback'
+ }
+ return result
+}
+
+/** Reads the experiment context params off a wizard URL. Null when the URL carries none. */
+export function parseExperimentScannerParams(searchParams: Record<string, any>): ExperimentScannerParams | null {
+ const experimentRaw = searchParams.experiment
+ // kea-router coerces `?experiment=true` to boolean `true`, and `Number(true)` is 1, which would
+ // pass the check below and silently prefill experiment 1. Only a string or number is a real id.
+ if (typeof experimentRaw !== 'string' && typeof experimentRaw !== 'number') {
+ return null
+ }
+ const experimentId = Number(experimentRaw)
+ if (!Number.isInteger(experimentId) || experimentId <= 0) {
+ return null
+ }
+ // kea-router coerces `?variants=1` to the number 1, so stringify before splitting.
+ const variantsRaw = searchParams.variants
+ const variantKeys =
+ typeof variantsRaw === 'string' || typeof variantsRaw === 'number'
+ ? String(variantsRaw)
+ .split(',')
+ .map((key) => key.trim())
+ .filter(Boolean)
+ : []
+ return { experimentId, variantKeys, useExposureFallback: searchParams.exposure === 'fallback' }
+}
+
+/**
+ * The exposure filter for the selected variants, in the same shape the experiment Recordings tab
+ * uses, so a scanner watches exactly the sessions that tab lists.
+ */
+export function buildExperimentExposureFilter(
+ experiment: Experiment,
+ variantKeys: string[],
+ useExposureFallback: boolean
+): UniversalFiltersGroupValue | null {
+ const variantArg = variantKeys.length > 0 ? variantKeys : undefined
+ if (useExposureFallback) {
+ // Null only for custom exposure configs, which carry semantics a flag-value filter can't
+ // stand in for; those keep the real exposure filter below.
+ const fallback = getExposureFallbackFilter(experiment, variantArg)
+ if (fallback) {
+ return fallback
+ }
+ }
+ return getViewRecordingFiltersForVariant(experiment, variantArg)[0] ?? null
+}
+
+/**
+ * A scanner `query` targeting the experiment's selected variants. The exposure filter is the
+ * first (and only) leaf so the Triggers step can later swap it when the variant selection
+ * changes without touching filters the user added by hand.
+ */
+export function buildExperimentScannerQuery(
+ experiment: Experiment,
+ variantKeys: string[],
+ useExposureFallback: boolean
+): RecordingsQuery {
+ const exposureFilter = buildExperimentExposureFilter(experiment, variantKeys, useExposureFallback)
+ const converted = convertUniversalFiltersToRecordingsQuery({
+ ...DEFAULT_RECORDING_FILTERS,
+ filter_test_accounts: experiment.exposure_criteria?.filterTestAccounts ?? false,
+ filter_group: {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: exposureFilter ? [exposureFilter] : [],
+ },
+ ],
+ },
+ })
+ // Only the dimensions the Triggers editor persists; the rest (dates, order, session ids) are
+ // playlist concerns the scanner model strips or never stores.
+ return {
+ kind: converted.kind,
+ events: converted.events,
+ actions: converted.actions,
+ properties: converted.properties,
+ console_log_filters: converted.console_log_filters,
+ having_predicates: converted.having_predicates,
+ comment_text: converted.comment_text,
+ filter_test_accounts: converted.filter_test_accounts,
+ operand: converted.operand,
+ }
+}
+
+/**
+ * Keeps only the requested variant keys that the loaded experiment actually has. A URL can carry a
+ * stale `?variants=old-key`, which would build an exposure filter that never matches yet still
+ * persist on save; dropping the unknown keys prevents that. When some keys are valid and some are
+ * not, only the valid ones survive. When every requested key is unknown but the experiment does
+ * have variants, this returns the full variant set rather than the empty list that would broaden to
+ * an `IsSet` filter matching every session that evaluated the flag. An experiment with no variants
+ * loaded still yields an empty list, which is the only enrollment marker available there.
+ */
+export function reconcileVariantKeys(experiment: Experiment, requestedKeys: string[]): string[] {
+ if (requestedKeys.length === 0) {
+ return []
+ }
+ const known = new Set(getExperimentVariants(experiment).map((variant) => variant.key))
+ const valid = requestedKeys.filter((key) => known.has(key))
+ if (valid.length > 0) {
+ return valid
+ }
+ return [...known]
+}
+
+/** Scanner name for an experiment-scoped scanner, within the model's 255-char limit. */
+export function experimentScannerName(baseName: string, experimentName: string): string {
+ const name = baseName ? `${baseName}: ${experimentName}` : experimentName
+ return name.slice(0, 255)
+}
+
+/** Applies the experiment context to a fresh (or freshly templated) scanner: targeted query, scoped name. */
+export function prefillScannerForExperiment(scanner: ReplayScanner, context: ExperimentScannerContext): ReplayScanner {
+ return {
+ ...scanner,
+ name: experimentScannerName(scanner.name, context.experiment.name),
+ query: buildExperimentScannerQuery(context.experiment, context.variantKeys, context.useExposureFallback),
+ }
+}
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
index 61d4be1ee575..cf4b2188d209 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
@@ -322,6 +322,27 @@ describe('replayScannerLogic', () => {
expect(readScannerDraft(teamId)?.scanner.name).toBe('Drafted')
})
+ it('preserves an existing draft when the wizard is entered from an experiment deep link', async () => {
+ // A deep link prefills a fresh scanner but must not wipe the draft the user already has;
+ // the prefill runs under restoringDraft so persistDraft can't clear it.
+ useMocks({
+ get: {
+ '/api/projects/:team/experiments/:id/': () => [200, { id: 7, name: 'Checkout redesign' }],
+ },
+ })
+ const teamId = teamLogic.values.currentTeamId!
+ logic.actions.setScannerValues({ name: 'Drafted' })
+ expect(readScannerDraft(teamId)?.scanner.name).toBe('Drafted')
+ logic.unmount()
+
+ router.actions.push(urls.replayVisionScannerConfigure('new'), { experiment: '7' })
+ logic = replayScannerLogic({ id: 'new' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(readScannerDraft(teamId)?.scanner.name).toBe('Drafted')
+ })
+
it('discards back to the loaded baseline, so the leave guard stays disarmed', async () => {
router.actions.push(urls.replayVisionScannerTemplate('new'), { template: 'dead_end' })
logic.unmount()
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index ef81863dc1e6..a5c81b366f0a 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -18,6 +18,7 @@ import { loaders } from 'kea-loaders'
import { actionToUrl, beforeUnload, router, urlToAction } from 'kea-router'
import { CombinedLocation } from 'kea-router/lib/utils'
+import api from 'lib/api'
import { scrollToFormError } from 'lib/forms/scrollToFormError'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { copyToClipboard } from 'lib/utils/copyToClipboard'
@@ -60,6 +61,12 @@ import {
serializeSortParam,
} from '../utils/urlParams'
import { clampDurationFilter, durationFilterError } from './durationBounds'
+import {
+ ExperimentScannerContext,
+ parseExperimentScannerParams,
+ prefillScannerForExperiment,
+ reconcileVariantKeys,
+} from './experimentTargeting'
import { clearScannerDraft, readScannerDraft, writeScannerDraft } from './scannerDraft'
import {
SCANNER_EDITOR_STEPS,
@@ -261,6 +268,7 @@ export interface replayScannerLogicValues {
copyingAllObservations: boolean
durationValidationError: string | null
estimateRequestVersion: number
+ experimentContext: ExperimentScannerContext | null
hasActiveObservationFilters: boolean
hasObservationsInFlight: boolean
hasUnsavedChanges: boolean
@@ -475,6 +483,9 @@ export interface replayScannerLogicActions {
dateFrom: string | null
dateTo: string | null
}
+ setExperimentContext: (context: ExperimentScannerContext | null) => {
+ context: ExperimentScannerContext | null
+ }
setObservationBackfillFilter: (value: string | null) => {
value: string | null
}
@@ -637,6 +648,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
loadScanner: true,
loadScannerSuccess: (scanner: ReplayScanner) => ({ scanner }),
loadScannerFailure: true,
+ setExperimentContext: (context: ExperimentScannerContext | null) => ({ context }),
saveAffectedCohort: (tag?: string) => ({ tag }),
setScannerType: (scannerType: ScannerType) => ({ scannerType }),
startFromTemplate: (templateKey: string | null) => ({ templateKey }),
@@ -861,6 +873,12 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
saveAffectedCohortFailure: () => null,
},
],
+ experimentContext: [
+ null as ExperimentScannerContext | null,
+ {
+ setExperimentContext: (_, { context }) => context,
+ },
+ ],
originalScanner: [
null as ReplayScanner | null,
{
@@ -1309,9 +1327,49 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
// strip the param so the URL matches what the user actually gets.
const templateKey =
!draft && urlTemplateKey && findScannerTemplate(urlTemplateKey) ? urlTemplateKey : null
+ const experimentParams = parseExperimentScannerParams(router.values.searchParams)
+ // Strip the params the wizard has now consumed so a reload doesn't re-run the prefill
+ // over the user's edits: an unknown template that fell back to from-scratch (a valid
+ // template stays), and the experiment deep-link params. One replace covers both and
+ // preserves the URL hash, which a second back-to-back replace would drop.
+ const nextParams = { ...router.values.searchParams }
if (urlTemplateKey && !templateKey) {
- const { template: _drop, ...rest } = router.values.searchParams
- router.actions.replace(router.values.location.pathname, rest)
+ delete nextParams.template
+ }
+ if (experimentParams) {
+ delete nextParams.experiment
+ delete nextParams.variants
+ delete nextParams.exposure
+ }
+ if (Object.keys(nextParams).length !== Object.keys(router.values.searchParams).length) {
+ router.actions.replace(router.values.location.pathname, nextParams, router.values.hashParams)
+ }
+ if (experimentParams) {
+ // An experiment deep link expresses fresh intent, so it outranks a saved
+ // draft; restoringDraft guards persistDraft so the prefill can't clobber the
+ // draft this user may already have for the next plain entry.
+ cache.restoringDraft = true
+ try {
+ const experiment = await api.experiments.get(experimentParams.experimentId)
+ const context: ExperimentScannerContext = {
+ experiment,
+ variantKeys: reconcileVariantKeys(experiment, experimentParams.variantKeys),
+ useExposureFallback: experimentParams.useExposureFallback,
+ }
+ const prefilled = prefillScannerForExperiment(newScanner(templateKey), context)
+ // Set the context only after the prefill is built, so a throw inside it
+ // doesn't leave a dangling context that the next startFromTemplate re-applies.
+ actions.setExperimentContext(context)
+ actions.loadScannerSuccess(prefilled)
+ } catch {
+ // Clear any context a partial run left set before surfacing the failure.
+ actions.setExperimentContext(null)
+ lemonToast.error("Couldn't load the experiment. Set recording filters manually instead.")
+ actions.loadScannerSuccess(newScanner(templateKey))
+ } finally {
+ cache.restoringDraft = false
+ }
+ return
}
cache.restoringDraft = true
try {
@@ -1349,6 +1407,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
}
},
+ // Changing type keeps the rest of the form: it spreads `current`, so an experiment
+ // prefill's name and query carry over untouched. Only the config is reset for the new type.
setScannerType: ({ scannerType }) => {
const current = values.scanner
if (!current) {
@@ -1403,7 +1463,11 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
startFromTemplate: ({ templateKey }) => {
clearScannerDraft()
actions.setScannerDraftSavedAt(null)
- actions.resetScanner(newScanner(templateKey))
+ // An experiment prefill (targeted query, scoped name) has to survive the template
+ // reset, so re-apply it when the wizard was entered from an experiment.
+ const base = newScanner(templateKey)
+ const context = values.experimentContext
+ actions.resetScanner(context ? prefillScannerForExperiment(base, context) : base)
},
discardScannerDraft: () => {
// Storage holds one draft, and it belongs to the new-scanner wizard.
@@ -1411,6 +1475,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
clearScannerDraft()
actions.setScannerDraftSavedAt(null)
}
+ // Discarding ends the experiment flow; a scanner started next must not inherit it.
+ actions.setExperimentContext(null)
actions.resetScanner(values.originalScanner ?? newScanner(null))
},
scannerSaved: () => {
@@ -1420,6 +1486,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
if (props.id === 'new') {
clearScannerDraft()
actions.setScannerDraftSavedAt(null)
+ // The saved scanner's experiment association ends here; a new scanner started in
+ // the same session must not re-apply this experiment's query and name.
+ actions.setExperimentContext(null)
}
},