:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): create a scanner from replay filters (#79976)
Kim Svatos Dugan3dd88a98e3c7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a17f9fd7cdcf..286ce1ab3a06 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6132,6 +6132,10 @@ snapshots:hash: v1.k794b7964.9621e94ace22f6b0c839d8f7890e3cdf4aa9951c7bfee8f2a089e46a5f7f977a.dZbjaDtE-CMiMTkhTxV1u5NVSvEugAeaZ5oBS64HcH4replay-tabs-home-filters-banner--product-analytics-under-limit--light:hash: v1.k794b7964.621980b6676868038ef6fda307d5b134d3879bc0638acf8936832351dc325f9e.q32al8_1uMGCjpaxXcoxMHz611C3uiHkep-dhcwXkjM+ replay-tabs-home-filters-banner--scanner-cross-sell--dark:+ hash: v1.k794b7964.c27886267fbfa39c64398e447e3cf63d5929fc3c9ede6fc8bf9c30bfaeea87a7.YxiOImD793nydIZ3ort6IyBzGmOcsZQb9RmqCuyx0tk+ replay-tabs-home-filters-banner--scanner-cross-sell--light:+ hash: v1.k794b7964.6cf63eeaf5abe507d73ec12a3ec9f404ce02e3c07e0aab059a3a1ea97ccfeb8d.O72XHqs276ly-AWZdwJvr_leOyBMigsKLK1SWFQ3XBoreplay-tabs-home-success--filters-expanded--dark:hash: v1.k794b7964.e85cac90eb14f279e3367d8d2ab0db3011d7bb6c5d85fee2fb5cd2d0095ea956.9KZY5n5cdZIaHcp8HzrLMg-rgB2x7i_uH93bqNN_MzUreplay-tabs-home-success--filters-expanded--light:@@ -6997,9 +7001,9 @@ snapshots:scenes-app-engineering-analytics-repo-overview--repo-overview--light:hash: v1.k794b7964.f709ff67c44f86f69d951fc6fbb18b17b6090f6c5793bf6bc16fc803e0a0498c.SmWuVYGMNsp3hU9ipmoQyalTt57uRsG0DrLJlw7LzPUscenes-app-engineering-analytics-repo-overview--repo-overview-with-trunk-queue-data--dark:- hash: v1.k794b7964.1a470083e7a94ff46652f4368277eae5d35c927d65b58685e43ce34881e1e728.JjIWr0Wfj8Nzl407D1c7pkfeDecNV2UVZEKUSyLdGrE+ hash: v1.k794b7964.99bcc4aa618c0c6ceb0f5589213426fb51865d6353f30beaed25b64578f5ffc0.F-ci8KA9aLO2BdWqAoyqoJe0vw3cdwL870yzUWI1ilIscenes-app-engineering-analytics-repo-overview--repo-overview-with-trunk-queue-data--light:- hash: v1.k794b7964.f709ff67c44f86f69d951fc6fbb18b17b6090f6c5793bf6bc16fc803e0a0498c.CCyr3jIgq9vy0b1RORwsIhSMVbL0qyRKSNgdK6Y_oZg+ hash: v1.k794b7964.fb0d3e9e51c16c40878d5b96d93d31aad8842801049a97f647ad0635b4a224c4.a9xQ7QWBiUGQMZHwjUBzX1e93fYB2mxdleiXIswFwnMscenes-app-engineering-analytics-run-activity-chart--default--dark:hash: v1.k794b7964.7f17c5ac7c6862493f7c4d59e6e3c3146c42e3d7b08908ee1716d387c129ba64.lPsE9KrOSZee9wJq8zjqYnvk09numvEFWOn4mdCOgJEscenes-app-engineering-analytics-run-activity-chart--default--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex c677d9c85d15..d61943423dcf 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -530,6 +530,7 @@ export const FEATURE_FLAGS = {UX_HIDE_PROJECT_NOTICE: 'ux-hide-project-notice', // owner: #team-platform-ux, hides the project notice banner across all scenesUX_REMOVE_SIDEPANEL: 'ux-remove-sidepanel', // owner: #team-surveysVISION_ENTRYPOINT_EXPERIMENTS: 'vision-entrypoint-experiments', // owner: #team-replay, cross-sell entry points from experiments+ VISION_ENTRYPOINT_REPLAY_FILTERS: 'vision-entrypoint-replay-filters', // owner: #team-replay, cross-sell entry point from the replay filters panelVISION_GOAL_BASED_CREATION_FLOW: 'vision-goal-based-creation-flow', // owner: #team-replay multivariate=control,test — gate on === 'test'; a truthy check turns on for control tooVISUAL_REVIEW: 'visual-review', // owner: #team-devexWAREHOUSE_MULTI_DESTINATION: 'warehouse-multi-destination', // owner: #team-warehouse-sourcesdiff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex fb0870148de9..4a73a86d2678 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -39694,6 +39694,7 @@"feature flag created","session_replay_set_filters","session_replay_experiment_link_clicked",+ "session_replay_save_filters_as_scanner","error_tracking_exception_autocapture_enabled","error_tracking_issue_sorting","error_tracking_docs_viewed",diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex b4203c45dc5e..bc8c9cb0ca2e 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -10151,6 +10151,7 @@ export enum ProductIntentContext {// Session ReplaySESSION_REPLAY_SET_FILTERS = 'session_replay_set_filters',SESSION_REPLAY_EXPERIMENT_LINK_CLICKED = 'session_replay_experiment_link_clicked',+ SESSION_REPLAY_SAVE_FILTERS_AS_SCANNER = 'session_replay_save_filters_as_scanner',// Error TrackingERROR_TRACKING_EXCEPTION_AUTOCAPTURE_ENABLED = 'error_tracking_exception_autocapture_enabled',diff --git a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsx b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsxindex 62cf159183cf..408bf863429f 100644--- a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsx+++ b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsx@@ -1,6 +1,7 @@import { Meta, StoryObj } from '@storybook/react'import { combineUrl } from 'kea-router'+import { FEATURE_FLAGS } from 'lib/constants'import { App } from 'scenes/App'import recordingEventsJson from 'scenes/session-recordings/__mocks__/recording_events_query'import { recordingPlaylists } from 'scenes/session-recordings/__mocks__/recording_playlists'@@ -65,3 +66,23 @@ export const ProductAnalyticsUnderLimit: Story = {}),],}++// The footer action row with the Replay vision cross-sell shown, so the divider that splits it+// from the filter-management buttons stays covered by visual review. The event filter is what makes+// the button actionable: a scanner keeps neither the date range nor pinned sessions, so filtering by+// those alone leaves it disabled.+export const ScannerCrossSell: Story = {+ parameters: {+ featureFlags: [FEATURE_FLAGS.VISION_ENTRYPOINT_REPLAY_FILTERS],+ pageUrl: combineUrl(urls.replay(), {+ showFilters: true,+ filters: {+ filter_group: {+ type: 'AND',+ values: [{ type: 'AND', values: [{ id: '$pageview', name: '$pageview', type: 'events' }] }],+ },+ },+ }).url,+ testOptions: { waitForSelector: '[data-attr="replay-save-filters-as-scanner"]' },+ },+}diff --git a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsxindex 8aee7d53b61d..58f27cb131f8 100644--- a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx+++ b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.tsx@@ -1,7 +1,8 @@import clsx from 'clsx'import { deepEqual as equal } from 'fast-equals'import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'-import { useEffect, useId, useRef, useState } from 'react'+import { combineUrl, router } from 'kea-router'+import { useEffect, useId, useMemo, useRef, useState } from 'react'import {IconAsterisk,@@ -15,6 +16,7 @@ import {IconRefresh,IconRevert,IconSearch,+ IconSparkles,IconTrash,IconX,} from '@posthog/icons'@@ -51,15 +53,17 @@ import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { getProjectEventExistence } from 'lib/utils/getAppContext'+import { addProductIntentForCrossSell } from 'lib/utils/product-intents'import { TestAccountFilter } from 'scenes/insights/filters/TestAccountFilter'import { MaxTool } from 'scenes/max/MaxTool'import { TimestampFormatToLabel } from 'scenes/session-recordings/utils'+import { urls } from 'scenes/urls'import { actionsModel } from '~/models/actionsModel'import { cohortsModel } from '~/models/cohortsModel'import { groupsModel } from '~/models/groupsModel'import { AndOrFilterSelect } from '~/queries/nodes/InsightViz/PropertyGroupFilters/AndOrFilterSelect'-import { NodeKind, RecordingsQuery } from '~/queries/schema/schema-general'+import { NodeKind, ProductIntentContext, ProductKey, RecordingsQuery } from '~/queries/schema/schema-general'import {PropertyFilterType,PropertyOperator,@@ -70,6 +74,7 @@ import {import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'import type { AttachedContextItem } from 'products/posthog_ai/frontend/api/types'+import { scannerHandoffFromFilters } from 'products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters'import { sessionRecordingSavedFiltersLogic } from '../filters/sessionRecordingSavedFiltersLogic'import { TimestampFormat, playerSettingsLogic } from '../player/playerSettingsLogic'@@ -740,6 +745,10 @@ export const ReplayFiltersTab = ({featureFlags[FEATURE_FLAGS.TAXONOMIC_FILTER_CATEGORY_DROPDOWN])const showFeedbackButton = useFeatureFlag('SHOW_REPLAY_FILTERS_FEEDBACK_BUTTON')+ const scannerCrossSellEnabled = useFeatureFlag('VISION_ENTRYPOINT_REPLAY_FILTERS')+ // A scanner keeps less of the filter set than this panel does, so what it would actually watch+ // decides both the destination and whether the button is worth offering.+ const scannerHandoff = useMemo(() => scannerHandoffFromFilters(filters), [filters])useMountedLogic(cohortsModel)useMountedLogic(actionsModel)@@ -1029,6 +1038,41 @@ export const ReplayFiltersTab = ({</LemonButton>)}<div className="flex gap-2 ml-auto">+ {scannerCrossSellEnabled && (+ <>+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconSparkles className="text-ai" />}+ data-attr="replay-save-filters-as-scanner"+ tooltip="Create a Replay vision scanner that keeps watching sessions matching these filters. The date range does not carry over, so the scanner watches sessions from now on."+ disabledReason={+ scannerHandoff.narrowsSessions+ ? undefined+ : 'Add an event or property filter. A date range and pinned sessions do not carry over to a scanner.'+ }+ onClick={() => {+ void addProductIntentForCrossSell({+ from: ProductKey.SESSION_REPLAY,+ to: ProductKey.REPLAY_VISION,+ intent_context:+ ProductIntentContext.SESSION_REPLAY_SAVE_FILTERS_AS_SCANNER,+ })+ router.actions.push(+ combineUrl(+ urls.replayVisionScannerConfigure('new'),+ scannerHandoff.searchParams+ ).url+ )+ }}+ >+ Create scanner+ </LemonButton>+ {/* Grouped away from the buttons that act on the filters themselves:+ this one leaves for another product. */}+ <LemonDivider vertical className="mx-1 self-stretch" />+ </>+ )}{resetButton}<LemonButton type="primary" size="small" onClick={() => setIsSaveFiltersModalOpen(true)}>Save as new filterdiff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex d8566c6f27d2..94a84a943834 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -3586,6 +3586,7 @@ class ProductIntentContext(StrEnum):FEATURE_FLAG_CREATED = "feature flag created"SESSION_REPLAY_SET_FILTERS = "session_replay_set_filters"SESSION_REPLAY_EXPERIMENT_LINK_CLICKED = "session_replay_experiment_link_clicked"+ SESSION_REPLAY_SAVE_FILTERS_AS_SCANNER = "session_replay_save_filters_as_scanner"ERROR_TRACKING_EXCEPTION_AUTOCAPTURE_ENABLED = "error_tracking_exception_autocapture_enabled"ERROR_TRACKING_ISSUE_SORTING = "error_tracking_issue_sorting"ERROR_TRACKING_DOCS_VIEWED = "error_tracking_docs_viewed"diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.tsindex 77b0ce494d0e..2bf7d2eeedd9 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts@@ -24,7 +24,7 @@ import {import { readScannerDraft, writeScannerDraft } from './scannerDraft'import { scannerEditorSceneLogic } from './scannerEditorSceneLogic'import { observationsDrilldownSearchParams } from './scannerOverviewLogic'-import { defaultScannerTemplates } from './scannerTemplates'+import { defaultScannerTemplates, newScanner } from './scannerTemplates'import { ClassifierScanner, ReplayScanner, ScorerScanner } from './types'jest.mock('lib/forms/scrollToFormError', () => ({@@ -104,6 +104,71 @@ describe('replayScannerLogic', () => {}),})})++ it('new scanner seeds its query from a ?filters= deep link', async () => {+ const query = {+ kind: 'RecordingsQuery',+ events: [{ id: '$pageview', name: '$pageview', type: 'events' }],+ }+ router.actions.push(urls.replayVisionScannerConfigure('new'), { filters: JSON.stringify(query) })+ await expectLogic(logic, () => logic.actions.loadScanner()).toMatchValues({+ scanner: expect.objectContaining({ query: expect.objectContaining({ events: query.events }) }),+ })+ })++ it('a ?filters= deep link outranks a saved draft', async () => {+ const query = { kind: 'RecordingsQuery', events: [{ id: '$autocapture', type: 'events' }] }+ writeScannerDraft(teamLogic.values.currentTeamId!, { ...newScanner(null), name: 'stale draft' })+ router.actions.push(urls.replayVisionScannerConfigure('new'), { filters: JSON.stringify(query) })+ await expectLogic(logic, () => logic.actions.loadScanner()).toMatchValues({+ scanner: expect.objectContaining({+ name: newScanner(null, teamLogic.values.currentTeam?.name).name,+ query: expect.objectContaining({ events: query.events }),+ }),+ })+ })++ // A crafted or truncated param must not reach the filter UI, which spreads what it gets:+ // a list field holding a string renders one filter per character.+ it.each([+ ['unparseable JSON', 'not-json{'],+ ['a JSON array', '[]'],+ ['a list field that is not a list', '{"kind":"RecordingsQuery","events":"x"}'],+ ])('a ?filters= param carrying %s falls back to the blank wizard', async (_label, filters) => {+ router.actions.push(urls.replayVisionScannerConfigure('new'), { filters })+ await expectLogic(logic, () => logic.actions.loadScanner()).toMatchValues({+ scanner: expect.objectContaining({+ scanner_type: 'monitor',+ query: { kind: 'RecordingsQuery' },+ }),+ })+ })++ it('strips the consumed ?filters= param, so a reload does not re-seed over the user edits', async () => {+ const query = { kind: 'RecordingsQuery', events: [{ id: '$pageview', type: 'events' }] }+ router.actions.push(urls.replayVisionScannerConfigure('new'), { filters: JSON.stringify(query) })+ await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()+ expect(router.values.searchParams.filters).toBeUndefined()+ })++ // The replay filters entry point sends both when the filters scope to an experiment, since+ // exposure can't ride inside the query. Keeping only the targeting would silently widen the+ // scanner to every session; keeping only the filters would drop the experiment entirely.+ it('combines an experiment deep link with a ?filters= query rather than dropping either', async () => {+ useMocks({+ get: { '/api/projects/:team/experiments/:id/': () => [200, { id: 7, name: 'Checkout redesign' }] },+ })+ const query = { kind: 'RecordingsQuery', events: [{ id: '$pageview', type: 'events' }] }+ router.actions.push(urls.replayVisionScannerConfigure('new'), {+ experiment: '7',+ filters: JSON.stringify(query),+ })++ await expectLogic(logic, () => logic.actions.loadScanner()).toFinishAllListeners()++ expect(logic.values.scanner?.experiment_targeting).toMatchObject({ experiment_id: 7 })+ expect(logic.values.scanner?.query).toMatchObject({ events: query.events })+ })})describe('draftScannerFromGoal', () => {@@ -652,6 +717,23 @@ describe('replayScannerLogic', () => {expect(readScannerDraft(teamId)?.scanner.name).toBe('Drafted')})+ it('preserves an existing draft when the wizard is entered from a ?filters= deep link', async () => {+ // The prefill outranks the draft for this entry but must not delete it; without the+ // restoringDraft guard, persistDraft sees scanner === originalScanner and clears it.+ const teamId = teamLogic.values.currentTeamId!+ logic.actions.setScannerValues({ name: 'Drafted' })+ expect(readScannerDraft(teamId)?.scanner.name).toBe('Drafted')+ logic.unmount()++ const query = { kind: 'RecordingsQuery', events: [{ id: '$pageview', type: 'events' }] }+ router.actions.push(urls.replayVisionScannerConfigure('new'), { filters: JSON.stringify(query) })+ 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.tsindex 790401aa7b13..e86043d6fb91 100644--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts@@ -30,7 +30,7 @@ import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'-import type { RecordingsQuery } from '~/queries/schema/schema-general'+import { NodeKind, type RecordingsQuery } from '~/queries/schema/schema-general'import {visionScannersAffectedCohortCreate,@@ -125,6 +125,46 @@ function currentTemplateKey(): string | null {return typeof value === 'string' ? value : null}+// The filter UI spreads each of these straight into its list of filter values, so a string here+// renders one filter per character instead of failing.+const PREFILL_QUERY_LIST_FIELDS = [+ 'events',+ 'actions',+ 'properties',+ 'console_log_filters',+ 'having_predicates',+] as const++function isValidPrefillQuery(parsed: unknown): parsed is RecordingsQuery {+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ return false+ }+ const query = parsed as Record<string, unknown>+ if ('kind' in query && query.kind !== NodeKind.RecordingsQuery) {+ return false+ }+ return PREFILL_QUERY_LIST_FIELDS.every((field) => !(field in query) || Array.isArray(query[field]))+}++/**+ * A `RecordingsQuery` handed to the new-scanner wizard via `?filters=<url-encoded JSON>`, used by+ * cross-sell entry points (e.g. "save these filters as a scanner" in the replay playlist) to seed+ * the scanner's query. Returns null on a missing, unparseable, or wrong-shaped param so a malformed+ * link just opens the blank wizard rather than throwing or rendering nonsense filters.+ */+function prefillQueryFromUrl(): RecordingsQuery | null {+ const value = router.values.searchParams.filters+ if (typeof value !== 'string' || !value) {+ return null+ }+ try {+ const parsed = JSON.parse(value)+ return isValidPrefillQuery(parsed) ? parsed : null+ } catch {+ return null+ }+}+function defaultConfigForType(scannerType: ScannerType): ScannerConfig {if (scannerType === 'summarizer') {return { prompt: '', length: 'medium' }@@ -1607,10 +1647,12 @@ export const replayScannerLogic = kea<replayScannerLogicType>([// free-text goal. A URL carrying both ?filters= and ?goal= deterministically// takes the filters and drops the goal.const hasFiltersPrefill = 'filters' in router.values.searchParams+ const prefillQuery = prefillQueryFromUrl()// 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), the experiment deep-link params, and the goal param. One replace- // covers all of them and preserves the URL hash, which a second back-to-back replace+ // template stays), the experiment deep-link params, the goal param, and the+ // `?filters=` prefill. One replace covers all of them and preserves the URL hash,+ // which a second back-to-back replace// would drop.const nextParams = { ...router.values.searchParams }if (urlTemplateKey && !templateKey) {@@ -1623,10 +1665,19 @@ export const replayScannerLogic = kea<replayScannerLogicType>([if (nextParams.goal !== undefined) {delete nextParams.goal}+ if ('filters' in nextParams) {+ delete nextParams.filters+ }if (Object.keys(nextParams).length !== Object.keys(router.values.searchParams).length) {router.actions.replace(router.values.location.pathname, nextParams, router.values.hashParams)}if (experimentParams) {+ // The two deep links combine rather than compete: the replay filters entry+ // point sends targeting and filters together, because exposure can't ride+ // inside `query` and dropping either one silently rescopes the scanner.+ const experimentBase = prefillQuery+ ? { ...newScanner(templateKey, teamName), query: prefillQuery }+ : newScanner(templateKey, teamName)// 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.@@ -1637,7 +1688,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([experiment,variantKey: reconcileVariantKey(experiment, experimentParams.variantKey),}- const prefilled = prefillScannerForExperiment(newScanner(templateKey, teamName), context)+ const prefilled = prefillScannerForExperiment(experimentBase, 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)@@ -1646,7 +1697,21 @@ export const replayScannerLogic = kea<replayScannerLogicType>([// 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, teamName))+ // Keep the filters that came with the link: they're the part of the+ // hand-off that survived, and re-entering them by hand is the fallback.+ actions.loadScannerSuccess(experimentBase)+ } finally {+ cache.restoringDraft = false+ }+ return+ }+ // A `?filters=` deep link expresses fresh intent (e.g. "save these playlist+ // filters as a scanner"), so it seeds the query and outranks a saved draft;+ // restoringDraft guards persistDraft so the prefill can't delete that draft.+ if (prefillQuery) {+ cache.restoringDraft = true+ try {+ actions.loadScannerSuccess({ ...newScanner(templateKey, teamName), query: prefillQuery })} finally {cache.restoringDraft = false}diff --git a/products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters.test.ts b/products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters.test.tsnew file mode 100644index 000000000000..22e7bdf81aa2--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters.test.ts@@ -0,0 +1,96 @@+import { defaultRecordingDurationFilter } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'++import {+ FilterLogicalOperator,+ PropertyFilterType,+ PropertyOperator,+ RecordingDurationFilter,+ RecordingUniversalFilters,+ UniversalFiltersGroupValue,+} from '~/types'++import { scannerHandoffFromFilters } from './scannerHandoffFromFilters'++/** A default replay filter set, with `values` filling the inner filter group the converter reads. */+function filters(+ partial: Partial<RecordingUniversalFilters> & { values?: UniversalFiltersGroupValue[] } = {}+): RecordingUniversalFilters {+ const { values = [], ...rest } = partial+ return {+ filter_test_accounts: false,+ date_from: '-3d',+ date_to: null,+ duration: [defaultRecordingDurationFilter],+ order: 'start_time',+ order_direction: 'DESC',+ filter_group: {+ type: FilterLogicalOperator.And,+ values: [{ type: FilterLogicalOperator.And, values }],+ },+ ...rest,+ } as RecordingUniversalFilters+}++const PAGEVIEW = { id: '$pageview', type: 'events' } as unknown as UniversalFiltersGroupValue+const LONG_SESSIONS: RecordingDurationFilter = {+ type: PropertyFilterType.Recording,+ key: 'active_seconds',+ value: 600,+ operator: PropertyOperator.GreaterThan,+}++function handoffQuery(f: RecordingUniversalFilters): Record<string, any> {+ return JSON.parse(scannerHandoffFromFilters(f).searchParams.filters)+}++describe('scannerHandoffFromFilters', () => {+ // A scanner carrying session IDs is pinned to recordings that already exist, so it matches+ // nothing ever while still looking healthy in the scanner list.+ it('drops pinned session IDs from the query', () => {+ const query = handoffQuery(filters({ values: [PAGEVIEW], session_ids: ['abc-123'] }))++ expect(query.session_ids).toBeUndefined()+ expect(query.events).toHaveLength(1)+ })++ // The API rejects exposure inside `query`, so leaving it there opens a wizard that can't be+ // saved. It has to travel as the experiment deep link the wizard access-checks instead.+ it('sends experiment exposure as targeting params, never inside the query', () => {+ const { searchParams } = scannerHandoffFromFilters(+ filters({ values: [PAGEVIEW], experiment_exposure: { experiment_id: 42, variant: 'test' } })+ )++ expect(searchParams).toMatchObject({ experiment: '42', variant: 'test' })+ expect(JSON.parse(searchParams.filters)).not.toHaveProperty('experiment_exposure')+ })++ it('omits the variant param when the filters cover every variant', () => {+ const { searchParams } = scannerHandoffFromFilters(+ filters({ values: [PAGEVIEW], experiment_exposure: { experiment_id: 42 } })+ )++ expect(searchParams.experiment).toEqual('42')+ expect(searchParams).not.toHaveProperty('variant')+ })++ describe('narrowsSessions', () => {+ // Guards the one-click path to a scanner pointed at every session: the replay list counts+ // these as filters, but a scanner keeps none of them.+ it.each([+ ['an untouched filter set', filters()],+ ['only a date range', filters({ date_from: '-7d' })],+ ['only pinned session IDs', filters({ session_ids: ['abc-123'] })],+ ['only the default duration floor', filters({ duration: [defaultRecordingDurationFilter] })],+ ])('is false for %s', (_label, f) => {+ expect(scannerHandoffFromFilters(f).narrowsSessions).toBe(false)+ })++ it.each([+ ['an event filter', filters({ values: [PAGEVIEW] })],+ ['a duration the user moved off the default', filters({ duration: [LONG_SESSIONS] })],+ ['experiment exposure', filters({ experiment_exposure: { experiment_id: 42 } })],+ ])('is true for %s', (_label, f) => {+ expect(scannerHandoffFromFilters(f).narrowsSessions).toBe(true)+ })+ })+})diff --git a/products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters.ts b/products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters.tsnew file mode 100644index 000000000000..84e7d7f6811a--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/scannerHandoffFromFilters.ts@@ -0,0 +1,64 @@+import { objectsEqual } from 'lib/utils/objects'+import { convertUniversalFiltersToRecordingsQuery } from 'scenes/session-recordings/filters/recordingsQueryConversions'+import { stripSessionIds } from 'scenes/session-recordings/playlist/playlistUtils'+import { defaultRecordingDurationFilter } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'+import { filtersFromUniversalFilterGroups } from 'scenes/session-recordings/utils'++import type { RecordingUniversalFilters } from '~/types'++import { experimentScannerParams } from './experimentTargeting'++/** The wizard hand-off for "create a scanner from these replay filters". */+export interface ScannerHandoffFromFilters {+ /** Params for the new-scanner wizard URL: the encoded query, plus experiment targeting when the filters carry it. */+ searchParams: Record<string, string>+ /**+ * Whether the resulting scanner would watch a subset of sessions rather than all of them.+ *+ * Deliberately not the replay list's filter count, which also counts the date range and pinned+ * session IDs. A scanner keeps neither, so counting them offers a one-click path to a scanner+ * aimed at every session.+ */+ narrowsSessions: boolean+}++/**+ * Converts the replay list's filters into the scanner the wizard should open with.+ *+ * A scanner keeps less of a filter set than this panel does, and each difference fails silently:+ * the dropped pieces save into a scanner that matches nothing, or one that matches everything, and+ * both look healthy in the scanner list. So the lossy fields are resolved here rather than at the+ * call site.+ *+ * - Session IDs pin the query to recordings that already exist. Nothing downstream removes them and+ * the sweep only moves forward, so a scanner carrying them never matches again.+ * - Experiment exposure is rejected inside `query` by the API, which resolves it from+ * `experiment_targeting` at scan time so the experiment stays behind that field's access check.+ * Left in, the wizard can't be saved; dropped, the scanner silently widens past the experiment.+ * It becomes the wizard's experiment deep link instead, which carries the same targeting the+ * experiment's own entry point uses.+ * - The date range is dropped by the backend on save, because a scanner's schedule owns time.+ */+export function scannerHandoffFromFilters(filters: RecordingUniversalFilters): ScannerHandoffFromFilters {+ const { experiment_exposure: exposure, ...query } = convertUniversalFiltersToRecordingsQuery(+ stripSessionIds(filters)+ )++ return {+ searchParams: {+ filters: JSON.stringify(query),+ ...(exposure+ ? experimentScannerParams({+ experimentId: exposure.experiment_id,+ variantKey: exposure.variant ?? null,+ })+ : {}),+ },+ narrowsSessions:+ filtersFromUniversalFilterGroups(filters).length > 0 ||+ // Every filter set carries a duration floor, so only one the user moved off the default+ // counts as narrowing.+ (filters.duration ?? []).some((predicate) => !objectsEqual(predicate, defaultRecordingDurationFilter)) ||+ !!exposure,+ }+}