: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 the user's explicitly chosen recordings list sort (#72495)
Arno Hillend5b29b90ac2d
diff --git a/frontend/src/lib/utils/localStorageSlot.ts b/frontend/src/lib/utils/localStorageSlot.tsnew file mode 100644index 000000000000..8b340bcc9655--- /dev/null+++ b/frontend/src/lib/utils/localStorageSlot.ts@@ -0,0 +1,34 @@+import { z } from 'zod'++export interface LocalStorageSlot<T> {+ get: () => T | null+ set: (value: T) => void+}++// Stored data outlives deploys and can be edited by hand, so reads validate+// against the schema before trusting it. A function key is resolved on every+// access, for keys that depend on runtime context (e.g. the current team)+export function localStorageSlot<T>(key: string | (() => string), schema: z.ZodType<T>): LocalStorageSlot<T> {+ const resolveKey = (): string => (typeof key === 'function' ? key() : key)+ return {+ get: (): T | null => {+ try {+ const raw = localStorage.getItem(resolveKey())+ if (!raw) {+ return null+ }+ const result = schema.safeParse(JSON.parse(raw))+ return result.success ? result.data : null+ } catch {+ return null+ }+ },+ set: (value: T): void => {+ try {+ localStorage.setItem(resolveKey(), JSON.stringify(value))+ } catch {+ // localStorage can be unavailable. Losing the value is fine+ }+ },+ }+}diff --git a/frontend/src/scenes/session-recordings/playlist/SessionRecordingsPlaylistSettings.tsx b/frontend/src/scenes/session-recordings/playlist/SessionRecordingsPlaylistSettings.tsxindex af62be366953..e4709fffe21c 100644--- a/frontend/src/scenes/session-recordings/playlist/SessionRecordingsPlaylistSettings.tsx+++ b/frontend/src/scenes/session-recordings/playlist/SessionRecordingsPlaylistSettings.tsx@@ -25,6 +25,7 @@ import { playerSettingsLogic } from '../player/playerSettingsLogic'import {DELETE_CONFIRMATION_TEXT,MAX_SELECTED_RECORDINGS,+ preferredRecordingsSortStorage,sessionRecordingsPlaylistLogic,} from './sessionRecordingsPlaylistLogic'@@ -91,6 +92,7 @@ function SortedBy({if (sortChangedEvent) {posthog.capture('session recording list sort changed', sortChangedEvent)}+ preferredRecordingsSortStorage.set(sort)setFilters(sort)}diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.tsindex 4e87869c442d..54b298866060 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts@@ -1,3 +1,5 @@+import { MOCK_TEAM_ID } from 'lib/api.mock'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import posthog from 'posthog-js'@@ -27,6 +29,7 @@ import {convertLegacyFiltersToUniversalFilters,convertUniversalFiltersToRecordingsQuery,getDefaultFilters,+ preferredRecordingsSortStorage,sessionRecordingsPlaylistLogic,} from './sessionRecordingsPlaylistLogic'@@ -1447,6 +1450,51 @@ describe('sessionRecordingsPlaylistLogic', () => {})})++ describe('preferred sort', () => {+ it.each<[string, () => void, string, string]>([+ [+ 'an explicitly chosen sort overrides the relevance default',+ () => preferredRecordingsSortStorage.set({ order: 'start_time', order_direction: 'DESC' }),+ DEFAULT_RECORDING_FILTERS_ORDER_BY,+ 'DESC',+ ],+ [+ 'the chosen direction is kept',+ () => preferredRecordingsSortStorage.set({ order: 'start_time', order_direction: 'ASC' }),+ DEFAULT_RECORDING_FILTERS_ORDER_BY,+ 'ASC',+ ],+ [+ 'an unparseable stored preference is ignored',+ () => localStorage.setItem(`${MOCK_TEAM_ID}__replay_list_preferred_sort`, 'not json'),+ 'surfacing_score',+ 'DESC',+ ],+ [+ 'a stored order outside the valid set is ignored',+ () =>+ localStorage.setItem(+ `${MOCK_TEAM_ID}__replay_list_preferred_sort`,+ JSON.stringify({ order: 'unknown', order_direction: 'DESC' })+ ),+ 'surfacing_score',+ 'DESC',+ ],+ ])('%s', (_name, setup, expectedOrder, expectedDirection) => {+ mockFlags({ [FEATURE_FLAGS.REPLAY_PLAYLIST_SURFACING_SCORE]: true })+ setup()+ const result = getDefaultFilters()+ expect(result.order).toBe(expectedOrder)+ expect(result.order_direction).toBe(expectedDirection)+ })++ it('keeps recency on person pages regardless of the stored preference', () => {+ mockFlags({ [FEATURE_FLAGS.REPLAY_PLAYLIST_SURFACING_SCORE]: true })+ preferredRecordingsSortStorage.set({ order: 'activity_score', order_direction: 'DESC' })+ expect(getDefaultFilters('some-person-uuid').order).toBe(DEFAULT_RECORDING_FILTERS_ORDER_BY)+ })+ })})describe('pinnedFilters', () => {diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.tsindex 3b49987906ed..482e423452f4 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts@@ -16,6 +16,7 @@ import {import { lazyLoaders, loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'import posthog from 'posthog-js'+import { z } from 'zod'import { lemonToast } from '@posthog/lemon-ui'@@ -33,13 +34,20 @@ import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { getCurrentTeamId } from 'lib/utils/getAppContext'import { isString } from 'lib/utils/guards'+import { localStorageSlot } from 'lib/utils/localStorageSlot'import { objectClean, objectsEqual } from 'lib/utils/objects'import { toParams } from 'lib/utils/url'import { createPlaylist } from 'scenes/session-recordings/playlist/playlistUtils'import { sessionRecordingEventUsageLogic } from 'scenes/session-recordings/sessionRecordingEventUsageLogic'import { urls } from 'scenes/urls'-import { NodeKind, RecordingOrder, RecordingsQuery, RecordingsQueryResponse } from '~/queries/schema/schema-general'+import {+ NodeKind,+ RecordingOrder,+ RecordingsQuery,+ RecordingsQueryResponse,+ VALID_RECORDING_ORDERS,+} from '~/queries/schema/schema-general'import {AnyPropertyFilter,FilterLogicalOperator,@@ -175,6 +183,15 @@ const getDefaultFilterTestAccounts = (): boolean => {return stored === 'true'}+// The sort the user explicitly picked in the list settings. It wins over the relevance+// rollout/experiment default, so users who prefer another order aren't re-defaulted+// into relevance on every visit and filter reset. Keyed per team, like the playlist+// filter persistence below, so the preference doesn't leak across accounts+export const preferredRecordingsSortStorage = localStorageSlot(+ () => `${getCurrentTeamId()}__replay_list_preferred_sort`,+ z.object({ order: z.enum(VALID_RECORDING_ORDERS), order_direction: z.enum(['ASC', 'DESC']) })+)+export const DEFAULT_RECORDING_FILTERS: RecordingUniversalFilters = {filter_test_accounts: false,date_from: '-3d',@@ -195,17 +212,22 @@ export const getDefaultFilters = (// (urlFilters, e.g. "View recordings" CTAs) come with a specific session in mind,// where recency is the better default than relevanceconst hasSpecificIntent = !!personUUID || !!pinnedFilters || !!urlFilters+ // A sort the user explicitly picked beats the relevance default, but specific-intent+ // surfaces keep recency regardless+ const preferredSort = hasSpecificIntent ? null : preferredRecordingsSortStorage.get()const defaults: RecordingUniversalFilters = {...DEFAULT_RECORDING_FILTERS,filter_test_accounts: filterTestAccounts,date_from: personUUID ? '-30d' : '-3d',// Default to sorting by relevance for the surfacing-score rollout or the relevance-sort experiment's test armorder:- !hasSpecificIntent &&+ preferredSort?.order ??+ (!hasSpecificIntent &&(posthog.getFeatureFlag(FEATURE_FLAGS.REPLAY_PLAYLIST_SURFACING_SCORE) ||posthog.getFeatureFlag(FEATURE_FLAGS.REPLAY_PLAYLIST_RELEVANCE_SORT_EXPERIMENT) === 'test')? 'surfacing_score'- : DEFAULT_RECORDING_FILTERS.order,+ : DEFAULT_RECORDING_FILTERS.order),+ order_direction: preferredSort?.order_direction ?? DEFAULT_RECORDING_FILTERS.order_direction,}if (pinnedFilters) {defaults.filter_group = mergePinnedFilters(defaults.filter_group, pinnedFilters)