: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
fix(replay): keep a caller's scope when resetting playlist filters (#101905)
Marcel Poelker4cf2702d90b6
diff --git a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsxindex 9afe6069c559..dd3c5b67d3fe 100644--- a/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx+++ b/frontend/src/scenes/experiments/ExperimentView/ExperimentReplayTab.tsx@@ -510,6 +510,10 @@ export function ExperimentReplayTab({ experiment }: { experiment: Experiment }):{...playlistLogicProps}analyticsSource="experiment-recordings-tab"filters={recordingsFilters}+ // The tab's own controls own these filters, so the filter bar resets to them+ // rather than to replay's defaults, which would list people outside the+ // experiment under the variant's label.+ resetToCallerFiltersonFiltersChange={(filters) => playlistFiltersChanged(filters)}onRecordingsLoaded={(recordings, isFirstPage) => recordingsLoaded(recordings, isFirstPage)}onRecordingSelected={(recordingId) => recordingOpened(recordingId)}diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.tsindex 75e18890ff64..2c102a816698 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts@@ -1679,6 +1679,301 @@ describe('sessionRecordingsPlaylistLogic', () => {secondMount.unmount()})+ // The experiment Recordings tab scopes its list to the experiment's exposed people. A reset+ // to replay's defaults there lists, and autoplays, recordings of people outside it.+ it('resets an opted-in caller to its own filters, so the list stays scoped', async () => {+ const experimentExposure = { experiment_id: 1, variant: 'test' }+ const scopedProps = {+ logicKey: 'caller_reset_baseline',+ updateSearchParams: false,+ resetToCallerFilters: true,+ filters: {+ date_from: '2024-03-01',+ date_to: null,+ duration: DEFAULT_RECORDING_FILTERS.duration,+ filter_group: DEFAULT_RECORDING_FILTERS.filter_group,+ experiment_exposure: experimentExposure,+ },+ }+ const listSpy = jest+ .spyOn(api.recordings, 'list')+ .mockImplementation(+ () =>+ Promise.resolve({ results: [aRecording], has_next: false } as unknown) as ReturnType<+ typeof api.recordings.list+ >+ )++ logic = sessionRecordingsPlaylistLogic(scopedProps)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ // the viewer widens the range and adds a filter of their own from the filter bar+ await expectLogic(logic, () => {+ logic.actions.setFilters({ date_from: '-30d', date_to: null })+ logic.actions.setFilters({+ filter_group: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: PropertyFilterType.LogEntry,+ key: 'level',+ operator: PropertyOperator.IContains,+ value: ['error'],+ },+ ],+ },+ ],+ },+ })+ })+ .toDispatchActions(['loadSessionRecordingsSuccess'])+ .toFinishAllListeners()++ // the reset asks for the rows the mount already read, so clear the memo to see the read+ clearMemoizedListResponses()+ await expectLogic(logic, () => {+ logic.actions.resetFilters()+ })+ .toDispatchActions(['loadSessionRecordingsSuccess'])+ .toFinishAllListeners()++ expect(logic.values.filters).toEqual(expect.objectContaining(scopedProps.filters))+ expect(logic.values.totalFiltersCount).toEqual(0)+ expect(listSpy).toHaveBeenLastCalledWith(+ expect.objectContaining({ date_from: '2024-03-01', experiment_exposure: experimentExposure })+ )+ })++ // The tab recomputes its whole filter object on every variant, so a reset that read the+ // props of the mount would put the list back on the variant the viewer left.+ it('resets an opted-in caller to the filters it has now, not the ones it mounted with', async () => {+ const scopedProps = {+ logicKey: 'caller_reset_current_props',+ updateSearchParams: false,+ resetToCallerFilters: true,+ filters: {+ date_from: '-7d',+ duration: DEFAULT_RECORDING_FILTERS.duration,+ filter_group: DEFAULT_RECORDING_FILTERS.filter_group,+ experiment_exposure: { experiment_id: 1, variant: 'control' },+ },+ }++ logic = sessionRecordingsPlaylistLogic(scopedProps)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ // the caller narrows to another variant, then the viewer resets the filter bar+ const laterExposure = { experiment_id: 1, variant: 'test' }+ sessionRecordingsPlaylistLogic({+ ...scopedProps,+ filters: { ...scopedProps.filters, experiment_exposure: laterExposure },+ })+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()+ await expectLogic(logic, () => {+ logic.actions.resetFilters()+ }).toFinishAllListeners()++ expect(logic.values.filters.experiment_exposure).toEqual(laterExposure)+ })++ // An invalid value falls back to the same baseline a reset returns to, so the fallback must+ // keep the caller's scope too. Otherwise one bad value unscopes the list.+ it('keeps an opted-in caller scope when a filter value is invalid', async () => {+ const callerFilters = {+ date_from: '-7d',+ duration: DEFAULT_RECORDING_FILTERS.duration,+ filter_group: DEFAULT_RECORDING_FILTERS.filter_group,+ experiment_exposure: { experiment_id: 2, variant: 'control' },+ }++ logic = sessionRecordingsPlaylistLogic({+ logicKey: 'caller_scope_kept_on_invalid',+ updateSearchParams: false,+ resetToCallerFilters: true,+ filters: callerFilters,+ })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ await expectLogic(logic, () => {+ logic.actions.setFilters({ duration: 'nope' } as any)+ }).toFinishAllListeners()++ expect(logic.values.filters).toEqual(expect.objectContaining(callerFilters))+ })++ // A notebook passes its filters in and writes every change back into them+ // (NotebookNodePlaylist), so the prop carries the viewer's own edits. A reset has to clear+ // those edits: the badge counts them, and no other control puts them back.+ it('clears a viewer filter on a reset when the caller writes its filters back', async () => {+ const baseProps = {+ logicKey: 'caller_writes_filters_back',+ updateSearchParams: false,+ filters: {+ date_from: DEFAULT_RECORDING_FILTERS.date_from,+ date_to: null,+ duration: DEFAULT_RECORDING_FILTERS.duration,+ filter_group: DEFAULT_RECORDING_FILTERS.filter_group,+ },+ }++ logic = sessionRecordingsPlaylistLogic(baseProps)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ // the viewer picks recordings in the filter bar, and the caller stores what it is handed+ await expectLogic(logic, () => {+ logic.actions.setFilters({ session_ids: ['a-session'] })+ }).toFinishAllListeners()+ sessionRecordingsPlaylistLogic({ ...baseProps, filters: logic.values.filters })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.totalFiltersCount).toEqual(1)++ await expectLogic(logic, () => {+ logic.actions.resetFilters()+ }).toFinishAllListeners()++ expect(logic.values.filters.session_ids).toBeUndefined()+ expect(logic.values.totalFiltersCount).toEqual(0)+ })++ // A saved filter set, and the Max apply path, can carry an empty duration. Every list has to+ // count that, caller-scoped or not, because a reset restores the floor.+ it('counts an emptied duration floor on a list that no caller scopes', async () => {+ logic = sessionRecordingsPlaylistLogic({ logicKey: 'no_caller_duration', updateSearchParams: false })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()+ expect(logic.values.totalFiltersCount).toEqual(0)++ await expectLogic(logic, () => {+ logic.actions.setFilters({ duration: [] })+ }).toFinishAllListeners()++ expect(logic.values.totalFiltersCount).toEqual(1)++ await expectLogic(logic, () => {+ logic.actions.resetFilters()+ }).toFinishAllListeners()++ expect(logic.values.filters.duration).toEqual(DEFAULT_RECORDING_FILTERS.duration)+ expect(logic.values.totalFiltersCount).toEqual(0)+ })++ // On the tab the badge used to count the experiment's own range, watch card and metric+ // filters, so it offered the viewer a reset of filters they never added.+ it.each<[string, Partial<RecordingUniversalFilters>]>([+ ['a date range', {}],+ ['session ids from a watch card', { session_ids: ['a-session'], duration: [] }],+ [+ 'a metric event filter',+ {+ filter_group: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: [{ id: '$pageview', type: 'events', order: 0, name: '$pageview' }],+ },+ ],+ },+ },+ ],+ ])('counts no filters for an opted-in caller that scopes by %s', async (_name, callerScope) => {+ const scopedProps = {+ logicKey: 'caller_baseline_count',+ updateSearchParams: false,+ resetToCallerFilters: true,+ filters: {+ date_from: '2024-03-01',+ date_to: null,+ duration: DEFAULT_RECORDING_FILTERS.duration,+ filter_group: DEFAULT_RECORDING_FILTERS.filter_group,+ experiment_exposure: { experiment_id: 1 },+ ...callerScope,+ },+ }++ logic = sessionRecordingsPlaylistLogic(scopedProps)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()++ expect(logic.values.totalFiltersCount).toEqual(0)++ // one filter of the viewer's own counts, so the reset button is theirs to use+ await expectLogic(logic, () => {+ logic.actions.setFilters({ date_from: '-30d', date_to: null })+ }).toFinishAllListeners()++ expect(logic.values.totalFiltersCount).toEqual(1)+ })++ // Every control in the filter bar can move a caller's own filter: remove a metric filter,+ // clear the duration floor, flip the test-account setting, clear the session ids with+ // "Show all". Each one widens or narrows the list, so the count has to notice, or the reset+ // that puts it back stays disabled.+ it.each<[string, Partial<RecordingUniversalFilters>]>([+ [+ 'a filter it scoped with',+ {+ filter_group: {+ type: FilterLogicalOperator.And,+ values: [{ type: FilterLogicalOperator.And, values: [] }],+ },+ },+ ],+ ['the duration floor', { duration: [] }],+ ['the test-account setting', { filter_test_accounts: false }],+ ['the session ids', { session_ids: undefined }],+ ])('counts a change to %s, and a reset puts it back', async (_name, change) => {+ const callerFilters = {+ date_from: '2024-03-01',+ date_to: null,+ duration: DEFAULT_RECORDING_FILTERS.duration,+ filter_test_accounts: true,+ filter_group: {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.And,+ values: [{ id: '$pageview', type: 'events', order: 0, name: '$pageview' } as ActionFilter],+ },+ ],+ },+ experiment_exposure: { experiment_id: 1 },+ session_ids: ['a-session'],+ }+ const scopedProps = {+ logicKey: 'caller_baseline_changed',+ updateSearchParams: false,+ resetToCallerFilters: true,+ filters: callerFilters,+ }++ logic = sessionRecordingsPlaylistLogic(scopedProps)+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toFinishAllListeners()+ expect(logic.values.totalFiltersCount).toEqual(0)++ await expectLogic(logic, () => {+ logic.actions.setFilters(change)+ }).toFinishAllListeners()++ expect(logic.values.totalFiltersCount).toEqual(1)++ await expectLogic(logic, () => {+ logic.actions.resetFilters()+ }).toFinishAllListeners()++ expect(logic.values.filters).toEqual(expect.objectContaining(callerFilters))+ expect(logic.values.totalFiltersCount).toEqual(0)+ })+it('reads the persisted filters once when the caller sets none', async () => {persistFilters(props, { ...DEFAULT_RECORDING_FILTERS, date_from: '-14d' })const listSpy = jestdiff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.tsindex dd7202e79f82..d40c016b7f50 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts@@ -490,6 +490,13 @@ export interface SessionRecordingPlaylistLogicProps {onlyPinned?: booleantype?: 'filters' | 'collection'filters?: RecordingUniversalFilters+ /**+ * Makes the caller's `filters` prop the baseline of the filter bar: a reset returns to it, and+ * `totalFiltersCount` counts what the viewer added on top of it. Set it where those filters scope+ * the list to a population the viewer must not leave. Leave it unset where the caller writes every+ * change back into `filters`, because the prop is then the current state and a reset does nothing.+ */+ resetToCallerFilters?: booleanonFiltersChange?: (filters: RecordingUniversalFilters) => void/*** Called with each freshly loaded page of recordings (not the accumulated list). `isFirstPage`@@ -548,6 +555,23 @@ const applyFilterUpdate = (return newState}+/**+ * The filters a reset, or a fallback from an invalid value, returns to. An opted-in caller's own+ * filters are that baseline. Every other caller returns to replay's defaults, including the keys a+ * caller scopes with: a caller that does not opt in writes each change back into its `filters` prop,+ * so the prop holds the viewer's own edits, and keeping those keys would leave the viewer a filter+ * the badge counts and the reset cannot clear.+ *+ * `props` is read when the reset runs, not at build time: kea assigns new props into the same object,+ * so a caller that recomputed its filters since the mount is only current here.+ */+const getResetFilters = (props: SessionRecordingPlaylistLogicProps): RecordingUniversalFilters => {+ const defaults = getDefaultFilters(props.personUUID, props.pinnedFilters)+ return props.resetToCallerFilters && props.filters+ ? applyFilterUpdate(defaults, props.filters, props.pinnedFilters)+ : defaults+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface sessionRecordingsPlaylistLogicValues {deletedRecordingIds: Set<string> // deletedRecordingsLogic@@ -898,7 +922,7 @@ export interface sessionRecordingsPlaylistLogicMeta {) => booleanpinnedFilters: (arg: any) => UniversalFiltersGroup | undefinedisScopedByCaller: (arg: any) => boolean- totalFiltersCount: (filters: RecordingUniversalFilters, arg: any, arg2: any) => number+ totalFiltersCount: (filters: RecordingUniversalFilters, arg: any, arg2: any, arg3: any, arg4: any) => numberhiddenRecordings: (sessionRecordings: SessionRecordingType[],hideViewedRecordings: HideViewedRecordingsOptions,@@ -1287,16 +1311,16 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogicposthog.captureException(new Error('Invalid filters provided'), {filters,})- return getDefaultFilters(props.personUUID, props.pinnedFilters)+ return getResetFilters(props)}return applyFilterUpdate(state, filters, props.pinnedFilters)} catch (e) {posthog.captureException(e)- return getDefaultFilters(props.personUUID, props.pinnedFilters)+ return getResetFilters(props)}},- resetFilters: () => getDefaultFilters(props.personUUID, props.pinnedFilters),+ resetFilters: () => getResetFilters(props),},],/**@@ -2092,20 +2116,50 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic],totalFiltersCount: [- (s) => [s.filters, (_, props) => props.personUUID, (_, props) => props.pinnedFilters],- (filters: RecordingUniversalFilters, personUUID, pinnedFilters) => {- const defaultFilters = getDefaultFilters(personUUID, pinnedFilters)+ (s) => [+ s.filters,+ (_, props) => props.personUUID,+ (_, props) => props.pinnedFilters,+ (_, props) => props.filters,+ (_, props) => props.resetToCallerFilters,+ ],+ (+ filters: RecordingUniversalFilters,+ personUUID: PersonUUID | undefined,+ pinnedFilters: UniversalFiltersGroup | undefined,+ callerFilters: RecordingUniversalFilters | undefined,+ resetToCallerFilters: boolean | undefined+ ) => {+ // The count is what the viewer can reset, so it counts against what a reset returns+ // to. An opted-in caller's range, duration, session ids and event filters are its own.+ const baselineFilters = resetToCallerFilters+ ? getResetFilters({ personUUID, pinnedFilters, filters: callerFilters, resetToCallerFilters })+ : getDefaultFilters(personUUID, pinnedFilters)const groupFilters = filtersFromUniversalFilterGroups(filters)- const pinnedValues: UniversalFilterValue[] = pinnedFilters?.values ?? []- const userFilterCount = groupFilters.filter((f) => !pinnedValues.some((pv) => equal(f, pv))).length+ const baselineGroupFilters = filtersFromUniversalFilterGroups(baselineFilters)+ // A baseline filter the viewer removed counts like one they added: the filter bar can+ // remove a caller's filter, which widens the list, and a reset is what puts it back.+ const changedGroupCount =+ groupFilters.filter((f) => !baselineGroupFilters.some((bf) => equal(f, bf))).length ++ baselineGroupFilters.filter((bf) => !groupFilters.some((f) => equal(f, bf))).length+ // A duration the state does not carry at all is legacy filter state, which the+ // baseline stands in for. An empty one is a removal, which a reset undoes.+ const durationChanged = !equal(filters.duration ?? baselineFilters.duration, baselineFilters.duration)+ // "Show all" clears the session ids to undefined, which reads the same as an empty+ // list, so both normalize before the comparison. Comparing the lists rather than+ // only the viewer's counts a baseline the viewer cleared, which a reset puts back.+ const sessionIdsChanged = !equal(filters.session_ids ?? [], baselineFilters.session_ids ?? [])return (- userFilterCount +- (equal(filters.duration?.[0] ?? defaultFilters.duration[0], defaultFilters.duration[0]) ? 0 : 1) +- (filters.date_from === defaultFilters.date_from && filters.date_to === defaultFilters.date_to+ changedGroupCount ++ (durationChanged ? 1 : 0) ++ (filters.date_from === baselineFilters.date_from && filters.date_to === baselineFilters.date_to? 0: 1) +- (filters.session_ids?.length ? 1 : 0)+ // The test-account setting has its own control in the filter bar, and a reset+ // returns it to the baseline, so a viewer who only flips it can still reset.+ (!!filters.filter_test_accounts === !!baselineFilters.filter_test_accounts ? 0 : 1) ++ (sessionIdsChanged ? 1 : 0))},],@@ -2367,6 +2421,8 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic// The filters reducer persists to localStorage and rehydrates without validation, so a stale// or malformed entry poisons state and makes every later filter change fall back to defaults.// Drop a bad rehydrated value here, reusing the check that already guards the URL and setFilters paths.+ // Where a caller owns the baseline, the reset returns to its filters, so the one load it+ // starts is already scoped.if (!isValidRecordingFilters(values.filters)) {actions.resetFilters()return