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): start scanner filters from a saved filter (#124460)

Kim Svatos Dugan2904e05ebb4a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index a440f67ee371..376e130c7c98 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -14925,11 +14925,11 @@ snapshots:
scenes-app-replay-vision--scanner-editor-triggers--dark:
hash: v1.k794b7964.9f1bb49fff5845e0b4fa240c76f160d11f6c3191fd9a70e818f6381ccbf73233.4oEBUb1L-2niWMCoHVODRY57bXqKEUrEnBKF0tdmsCc
scenes-app-replay-vision--scanner-editor-triggers--light:
- hash: v1.k794b7964.9c7a56ed797c290a26278811003796db4982b590e9ccc0c6ed6ba18464dfa5fc.yMHxv0KMY6uBnVL6Q-y0zgd6P3dLdv1DLR2LvMCUI_k
+ hash: v1.k794b7964.e17a56bcc7b0d866d8d2eaf27117e674efd463e95a3f331209283a2477b29a58.BRw9CsulwdSg53Q5WrN2Xb32gd6VafjmVvYt1g2Snrs
scenes-app-replay-vision--scanner-editor-triggers-experiment--dark:
hash: v1.k794b7964.6840daeb52b0dd348e8c84a00b15ff2b6ad55aa1524644114909f7835cf136e2.uVGB9n2x91ojCZtbjTG75aqwdBbS2H6Du9erZCHGcnc
scenes-app-replay-vision--scanner-editor-triggers-experiment--light:
- hash: v1.k794b7964.697be936fbb69845903888940b12200ca4d6640a4701b8b4335a6ba93db4da90.vufzFFOy9beUsCj5GtAs4hZxIeGexLKQdiAKNds8vYY
+ hash: v1.k794b7964.d4b09a024eb703d39795d30163abcc944075d571d25bdd2487c2240668a8503d.vz8tgcbgNGUkJaO7uOOf1MVey6BKMh7nw5HxBXLNOCc
scenes-app-replay-vision--scanner-observations--dark:
hash: v1.k794b7964.a730efb9cf4a682d5618dd924bcc733bdb602478dc338e1511ab0eb1e5fc580a.HMSJ-jDOOMyzClRBvAXqP4EdZDWu_oNBrvObUQPQT3A
scenes-app-replay-vision--scanner-observations--light:
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
index 9a7e17fdfa7d..a3263d93d274 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
@@ -1,4 +1,4 @@
-import { useActions, useValues } from 'kea'
+import { useActions, useMountedLogic, useValues } from 'kea'
import { LemonBanner, LemonCard, LemonSelect, LemonTag } from '@posthog/lemon-ui'
@@ -17,7 +17,6 @@ import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { getExperimentVariants } from 'scenes/experiments/utils'
import { DurationFilter } from 'scenes/session-recordings/filters/DurationFilter'
import {
- convertUniversalFiltersToRecordingsQuery,
deriveOperand,
recordingsQueryToUniversalFilters,
} from 'scenes/session-recordings/filters/recordingsQueryConversions'
@@ -34,6 +33,8 @@ import { PropertyFilterType, RecordingUniversalFilters, UniversalFiltersGroup }
import { clampDurationFilter, durationFilterError, MAX_ACTIVE_LABEL } from '../durationBounds'
import { scannerExperimentScope } from '../experimentTargeting'
import { replayScannerLogic } from '../replayScannerLogic'
+import { overlayEditorFilters } from '../scannerQueryFilters'
+import { scannerSavedFilterLogic } from '../scannerSavedFilterLogic'
import { ExperimentScopeFilter } from './ExperimentScopeFilter'
// The wizard holds an unsaved draft, so sending someone to the settings scene to define their test
@@ -64,6 +65,7 @@ function openTestAccountFilterSettings(): void {
// Group properties are appended per-project from groupsModel (see scannerFilterTypes below).
const SCANNER_BASE_FILTER_TYPES: TaxonomicFilterGroupType[] = [
TaxonomicFilterGroupType.SuggestedFilters,
+ TaxonomicFilterGroupType.ReplaySavedFilters,
TaxonomicFilterGroupType.Replay,
TaxonomicFilterGroupType.Events,
TaxonomicFilterGroupType.EventProperties,
@@ -201,6 +203,7 @@ function ExperimentTargeting({ scannerId }: { scannerId: string }): JSX.Element
export function ScannerTriggers({ scannerId }: { scannerId: string }): JSX.Element {
const { scanner, scannerEstimate, scannerEstimateLoading } = useValues(replayScannerLogic({ id: scannerId }))
const { groupsTaxonomicTypes } = useValues(groupsModel)
+ useMountedLogic(scannerSavedFilterLogic({ scannerId }))
const scannerFilterTypes = [...SCANNER_BASE_FILTER_TYPES, ...groupsTaxonomicTypes]
// Waits for the in-flight estimate so an edit can't report on the previous filters.
const noMatchWindowDays =
@@ -223,20 +226,7 @@ export function ScannerTriggers({ scannerId }: { scannerId: string }): JSX.Eleme
const query = value as RecordingsQuery | null
const universal = recordingsQueryToUniversalFilters(query)
const applyUniversal = (next: RecordingUniversalFilters): void => {
- const converted = convertUniversalFiltersToRecordingsQuery(next)
- // Overlay only the dimensions this editor renders so other query fields survive an edit.
- onChange({
- ...query,
- 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,
- })
+ onChange(overlayEditorFilters(query, next))
}
const durationFilter = clampDurationFilter(universal.duration[0] ?? defaultRecordingDurationFilter)
const durationError = durationFilterError(durationFilter)
@@ -246,7 +236,8 @@ export function ScannerTriggers({ scannerId }: { scannerId: string }): JSX.Eleme
<div className="space-y-1">
<LemonLabel>Recording filters</LemonLabel>
<div className="text-xs text-muted">
- Filter by event, action, person, session, or cohort.
+ Filter by event, action, person, session, or cohort, or start from a saved
+ filter.
</div>
</div>
<TestAccountFilterSwitch
diff --git a/products/replay_vision/frontend/replay_scanners/scannerQueryFilters.ts b/products/replay_vision/frontend/replay_scanners/scannerQueryFilters.ts
new file mode 100644
index 000000000000..d3e74a9e2160
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/scannerQueryFilters.ts
@@ -0,0 +1,67 @@
+import {
+ convertUniversalFiltersToRecordingsQuery,
+ recordingsQueryToUniversalFilters,
+} from 'scenes/session-recordings/filters/recordingsQueryConversions'
+import { stripSessionIds } from 'scenes/session-recordings/playlist/playlistUtils'
+import { asUniversalFilters } from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'
+
+import { RecordingsQuery } from '~/queries/schema/schema-general'
+import { RecordingUniversalFilters, SessionRecordingPlaylistType } from '~/types'
+
+import { clampDurationFilter } from './durationBounds'
+
+/** Writes only the dimensions the scanner's filter editor shows, so fields it hides survive an edit. */
+export function overlayEditorFilters(
+ query: RecordingsQuery | null,
+ filters: RecordingUniversalFilters
+): RecordingsQuery {
+ const converted = convertUniversalFiltersToRecordingsQuery(filters)
+ return {
+ ...query,
+ 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,
+ }
+}
+
+export type SavedFilterApplication =
+ | { status: 'applied'; query: RecordingsQuery }
+ | { status: 'experiment-filter' }
+ | { status: 'no-filters' }
+
+export function applySavedFilterToScannerQuery(
+ query: RecordingsQuery | null,
+ savedFilter: Pick<SessionRecordingPlaylistType, 'filters'>
+): SavedFilterApplication {
+ const universal = asUniversalFilters(savedFilter.filters)
+ if (!universal) {
+ return { status: 'no-filters' }
+ }
+ const filters = stripSessionIds(universal)
+ // The query cannot hold experiment exposure, and dropping it would scan sessions outside the experiment.
+ if (filters.experiment_exposure) {
+ return { status: 'experiment-filter' }
+ }
+ // Parts the saved filter leaves out keep their current values, as on the replay page.
+ const merged: RecordingUniversalFilters = {
+ ...recordingsQueryToUniversalFilters(query),
+ ...(Object.fromEntries(
+ Object.entries(filters).filter(([, value]) => value !== undefined)
+ ) as Partial<RecordingUniversalFilters>),
+ }
+ return {
+ status: 'applied',
+ query: {
+ ...overlayEditorFilters(query, { ...merged, duration: merged.duration.map(clampDurationFilter) }),
+ // The editor hides these selection settings, but scans still apply them.
+ recommended_only: merged.recommended_only,
+ event_match_scope: merged.event_match_scope,
+ },
+ }
+}
diff --git a/products/replay_vision/frontend/replay_scanners/scannerSavedFilterLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerSavedFilterLogic.test.ts
new file mode 100644
index 000000000000..5328fa11bb7a
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/scannerSavedFilterLogic.test.ts
@@ -0,0 +1,97 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { sessionRecordingSavedFiltersLogic } from 'scenes/session-recordings/filters/sessionRecordingSavedFiltersLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { FilterLogicalOperator, PropertyFilterType, SessionRecordingPlaylistType } from '~/types'
+
+import { replayScannerLogic } from './replayScannerLogic'
+import { scannerSavedFilterLogic } from './scannerSavedFilterLogic'
+
+function savedFilter(overrides: Record<string, unknown> = {}): SessionRecordingPlaylistType {
+ return {
+ short_id: 'savedFilter1',
+ name: 'Checkout visits',
+ type: 'filters',
+ filters: {
+ date_from: '-3d',
+ date_to: null,
+ filter_test_accounts: true,
+ recommended_only: true,
+ event_match_scope: 'recording',
+ session_ids: ['pinned-session'],
+ duration: [{ type: PropertyFilterType.Recording, key: 'active_seconds', value: 5, operator: 'gt' }],
+ filter_group: {
+ type: FilterLogicalOperator.And,
+ values: [
+ {
+ type: FilterLogicalOperator.And,
+ values: [{ id: '$pageview', name: '$pageview', type: 'events' }],
+ },
+ ],
+ },
+ ...overrides,
+ },
+ } as unknown as SessionRecordingPlaylistType
+}
+
+describe('scannerSavedFilterLogic', () => {
+ let scannerLogic: ReturnType<typeof replayScannerLogic.build>
+ let logic: ReturnType<typeof scannerSavedFilterLogic.build>
+
+ beforeEach(() => {
+ useMocks({
+ get: {
+ '/api/projects/:team/vision/scanners/:id/': () => [404, {}],
+ },
+ })
+ localStorage.clear()
+ sessionStorage.clear()
+ initKeaTests()
+ jest.spyOn(lemonToast, 'success').mockImplementation()
+ jest.spyOn(lemonToast, 'warning').mockImplementation()
+ scannerLogic = replayScannerLogic({ id: 'new' })
+ scannerLogic.mount()
+ logic = scannerSavedFilterLogic({ scannerId: 'new' })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ scannerLogic.unmount()
+ jest.restoreAllMocks()
+ })
+
+ it.each([
+ ['with a duration', {}],
+ ['without a duration', { duration: undefined }],
+ ])('copies a saved filter %s into the scanner query and clears the pending pick', async (_, overrides) => {
+ await expectLogic(logic, () => {
+ sessionRecordingSavedFiltersLogic.actions.requestApplySavedFilter(savedFilter(overrides))
+ }).toFinishAllListeners()
+
+ const query = scannerLogic.values.scanner.query
+ expect(query?.events).toEqual([expect.objectContaining({ id: '$pageview' })])
+ expect(query?.filter_test_accounts).toBe(true)
+ expect(query?.recommended_only).toBe(true)
+ expect(query?.event_match_scope).toBe('recording')
+ expect(query?.session_ids).toBeUndefined()
+ expect(query?.date_from).toBeUndefined()
+ expect(sessionRecordingSavedFiltersLogic.values.pendingFilterApplication).toBeNull()
+ })
+
+ it('refuses a saved filter that targets an experiment', async () => {
+ const before = scannerLogic.values.scanner.query
+
+ await expectLogic(logic, () => {
+ sessionRecordingSavedFiltersLogic.actions.requestApplySavedFilter(
+ savedFilter({ experiment_exposure: { experiment_id: 7, variant: null } })
+ )
+ }).toFinishAllListeners()
+
+ expect(scannerLogic.values.scanner.query).toEqual(before)
+ expect(lemonToast.warning).toHaveBeenCalled()
+ })
+})
diff --git a/products/replay_vision/frontend/replay_scanners/scannerSavedFilterLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerSavedFilterLogic.ts
new file mode 100644
index 000000000000..f1b9f86f7314
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/scannerSavedFilterLogic.ts
@@ -0,0 +1,86 @@
+import { MakeLogicType, connect, kea, key, listeners, path, props } from 'kea'
+import type { FieldName } from 'kea-forms'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import posthog from 'lib/posthog-typed'
+import { sessionRecordingSavedFiltersLogic } from 'scenes/session-recordings/filters/sessionRecordingSavedFiltersLogic'
+
+import { RecordingsQuery } from '~/queries/schema/schema-general'
+import { SessionRecordingPlaylistType } from '~/types'
+
+import { replayScannerLogic } from './replayScannerLogic'
+import { applySavedFilterToScannerQuery } from './scannerQueryFilters'
+
+export interface ScannerSavedFilterLogicProps {
+ scannerId: string
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scannerSavedFilterLogicActions {
+ setScannerValue: (
+ key: FieldName,
+ value: any
+ ) => {
+ name: FieldName
+ value: any
+ } // replayScannerLogic
+ clearPendingFilterApplication: () => {
+ value: true
+ } // sessionRecordingSavedFiltersLogic
+ requestApplySavedFilter: (filter: SessionRecordingPlaylistType) => {
+ filter: SessionRecordingPlaylistType
+ } // sessionRecordingSavedFiltersLogic
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface scannerSavedFilterLogicMeta {
+ key: string
+}
+
+export type scannerSavedFilterLogicType = MakeLogicType<
+ {},
+ scannerSavedFilterLogicActions,
+ ScannerSavedFilterLogicProps,
+ scannerSavedFilterLogicMeta
+>
+
+/** Applies a saved filter pick from the scanner's filter search. Only the scanner filter editor mounts it. */
+export const scannerSavedFilterLogic = kea<scannerSavedFilterLogicType>([
+ path((key) => ['products', 'replay_vision', 'frontend', 'replay_scanners', 'scannerSavedFilterLogic', key]),
+ props({} as ScannerSavedFilterLogicProps),
+ key((props) => props.scannerId),
+ connect((props: ScannerSavedFilterLogicProps) => ({
+ actions: [
+ sessionRecordingSavedFiltersLogic,
+ ['requestApplySavedFilter', 'clearPendingFilterApplication'],
+ replayScannerLogic({ id: props.scannerId }),
+ ['setScannerValue'],
+ ],
+ })),
+ listeners(({ actions, props }) => ({
+ requestApplySavedFilter: ({ filter }) => {
+ // Cleared at once, or the replay page applies this pick the next time it mounts.
+ actions.clearPendingFilterApplication()
+ const scanner = replayScannerLogic({ id: props.scannerId }).values.scanner
+ const result = applySavedFilterToScannerQuery((scanner?.query as RecordingsQuery | null) ?? null, filter)
+ posthog.capture('replay_vision_scanner_saved_filter_applied', {
+ scanner_id: props.scannerId === 'new' ? null : props.scannerId,
+ is_new_scanner: props.scannerId === 'new',
+ saved_filter_short_id: filter.short_id,
+ result: result.status,
+ })
+ if (result.status === 'experiment-filter') {
+ lemonToast.warning(
+ "This saved filter targets an experiment, so it can't be copied to a scanner. Create an experiment scanner from the experiment instead."
+ )
+ return
+ }
+ if (result.status === 'no-filters') {
+ lemonToast.warning('This saved filter has no filters to copy.')
+ return
+ }
+ actions.setScannerValue('query', result.query)
+ lemonToast.success(`Copied the filters from "${filter.name || filter.derived_name || 'Unnamed'}"`)
+ },
+ })),
+])