: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): open selected recording even when outside list filters (#62982)
Arno Hillen2ac69b0dbfc9
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex a4187de38a5c..312442cdd22c 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -38815,6 +38815,10 @@"keypress_count": {"type": "number"},+ "matches_filters": {+ "description": "False when the recording was included in list results via a direct link despite not matching the filters.",+ "type": "boolean"+ },"matching_events": {"description": "List of matching events. *","items": {diff --git a/frontend/src/scenes/session-recordings/playlist/Playlist.tsx b/frontend/src/scenes/session-recordings/playlist/Playlist.tsxindex 8dbc99ddd370..5776f8bdb49f 100644--- a/frontend/src/scenes/session-recordings/playlist/Playlist.tsx+++ b/frontend/src/scenes/session-recordings/playlist/Playlist.tsx@@ -94,6 +94,7 @@ export function Playlist({visiblePinnedRecordings: pinnedRecordings,otherRecordings,hasNext,+ selectedRecordingOutsideFilters,} = useValues(sessionRecordingsPlaylistLogic)const { maybeLoadSessionRecordings, setFilters, setSelectedRecordingId } =useActions(sessionRecordingsPlaylistLogic)@@ -301,6 +302,12 @@ export function Playlist({</DraggableToNotebook><LemonTableLoader loading={sessionRecordingsResponseLoading} /></div>+ {selectedRecordingOutsideFilters && (+ <LemonBanner type="info" className="m-2 text-xs">+ The selected recording doesn't match the current filters. It's shown because it was+ opened from a direct link.+ </LemonBanner>+ )}<div className="overflow-y-auto flex-1 min-h-0" onScroll={handleScroll} ref={contentRef}>{sectionCount > 1 ? (<LemonCollapsediff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.tsindex 6333161289e1..31f31c4e5889 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts@@ -59,6 +59,17 @@ describe('sessionRecordingsPlaylistLogic', () => {viewers: [],snapshot_source: 'web' as const,}+ const outsideFiltersRecording = {+ id: 'outside-filters-rec',+ viewed: false,+ recording_duration: 10,+ start_time: '2023-01-12T16:55:36.404000Z',+ end_time: '2023-01-12T16:55:46.404000Z',+ console_error_count: 0,+ viewers: [],+ snapshot_source: 'web' as const,+ matches_filters: false,+ }beforeEach(() => {useMocks({@@ -91,6 +102,15 @@ describe('sessionRecordingsPlaylistLogic', () => {results: ["List of specific user's recordings from server"],},]+ } else if (searchParams.get('session_recording_id') === outsideFiltersRecording.id) {+ // a recording requested via direct link that doesn't match the filters+ // is included in results flagged with matches_filters false+ return [+ 200,+ {+ results: [outsideFiltersRecording, ...listOfSessionRecordings],+ },+ ]} else if (searchParams.get('offset') !== null) {return [200,@@ -214,6 +234,32 @@ describe('sessionRecordingsPlaylistLogic', () => {})})+ describe('selectedRecordingOutsideFilters', () => {+ it('is false when no recording is selected', async () => {+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess']).toMatchValues({+ selectedRecordingOutsideFilters: false,+ })+ })++ it('is false when the selected recording matches the filters', async () => {+ await expectLogic(logic, () => logic.actions.setSelectedRecordingId('abc'))+ .toDispatchActions(['loadSessionRecordingsSuccess'])+ .toMatchValues({+ selectedRecordingId: 'abc',+ selectedRecordingOutsideFilters: false,+ })+ })++ it('is true when the selected recording is flagged as not matching the filters', async () => {+ await expectLogic(logic, () => logic.actions.setSelectedRecordingId(outsideFiltersRecording.id))+ .toDispatchActions(['loadSessionRecordingsSuccess'])+ .toMatchValues({+ selectedRecordingId: outsideFiltersRecording.id,+ selectedRecordingOutsideFilters: true,+ })+ })+ })+describe('nextSessionRecording', () => {it('returns undefined when autoplay direction is null (autoplay off)', async () => {playerSettingsLogic.mount()diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.tsindex ad2bec06cfa2..6b359b0c29f3 100644--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts@@ -1277,6 +1277,16 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic},],+ selectedRecordingOutsideFilters: [+ (s) => [s.selectedRecordingId, s.recordings],+ (selectedRecordingId, recordings): boolean => {+ if (!selectedRecordingId) {+ return false+ }+ return recordings.find((rec) => rec.id === selectedRecordingId)?.matches_filters === false+ },+ ],+nextSessionRecording: [(s) => [s.activeSessionRecording, s.recordings, s.autoplayDirection],(activeSessionRecording, recordings, autoplayDirection): Partial<SessionRecordingType> | undefined => {diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 01ec92e08757..db8835ce11be 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -1927,6 +1927,8 @@ export interface SessionRecordingType {summary_outcome?: { success?: boolean | null; description?: string | null } | null/** External references to third party issues. */external_references?: SessionRecordingExternalReference[]+ /** False when the recording was included in list results via a direct link despite not matching the filters. */+ matches_filters?: boolean}export interface SessionRecordingUpdateType {diff --git a/posthog/schema.py b/posthog/schema.pyindex 3aa49f551146..2b829469c546 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -9040,6 +9040,12 @@ class SessionRecordingType(BaseModel):id: strinactive_seconds: float | None = Nonekeypress_count: float | None = None+ matches_filters: bool | None = Field(+ default=None,+ description=(+ "False when the recording was included in list results via a direct link despite not matching the filters."+ ),+ )matching_events: list[MatchedRecording] | None = Field(default=None, description="List of matching events. *")mouse_activity_count: float | None = Field(default=None,diff --git a/posthog/session_recordings/models/session_recording.py b/posthog/session_recordings/models/session_recording.pyindex 46868d87cf27..94f2e790faa0 100644--- a/posthog/session_recordings/models/session_recording.py+++ b/posthog/session_recordings/models/session_recording.py@@ -92,6 +92,9 @@ class SessionRecording(UUIDTModel):summary_outcome: Optional[dict] = Noneexpiry_time: Optional[datetime] = Nonerecording_ttl: Optional[int] = None+ # False when this recording was included in listing results via session_recording_id+ # despite not matching the listing filters+ matches_filters: Optional[bool] = None# Metadata can be loaded from Clickhouse or S3_metadata: Optional[RecordingMetadata] = Nonediff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.pyindex ceb03bf6485d..70ee19079568 100644--- a/posthog/session_recordings/session_recording_api.py+++ b/posthog/session_recordings/session_recording_api.py@@ -301,6 +301,10 @@ class SessionRecordingSerializer(serializers.ModelSerializer, UserAccessControlSactivity_score = serializers.SerializerMethodField()has_summary = serializers.SerializerMethodField()summary_outcome = serializers.SerializerMethodField()+ matches_filters = serializers.SerializerMethodField(+ help_text="Whether this recording matched the filters of the listing query that returned it. "+ "False only when a recording requested via session_recording_id was included despite not matching the filters."+ )# Dynamic attrs set on the model instance — not Django fields, so declare explicitlyexpiry_time = serializers.DateTimeField(read_only=True, allow_null=True)recording_ttl = serializers.IntegerField(read_only=True, allow_null=True)@@ -309,6 +313,11 @@ class SessionRecordingSerializer(serializers.ModelSerializer, UserAccessControlS# ongoing is a custom field that we add if loading from ClickHousereturn getattr(obj, "ongoing", False)+ def get_matches_filters(self, obj: SessionRecording) -> bool:+ # matches_filters is a custom field set when a recording requested via+ # session_recording_id is included in listing results despite not matching the filters+ return getattr(obj, "matches_filters", None) is not False+def get_viewed(self, obj: SessionRecording) -> bool:# viewed is a custom field that we load from PG Sql and merge into the modelreturn getattr(obj, "viewed", False)@@ -400,6 +409,7 @@ class SessionRecordingSerializer(serializers.ModelSerializer, UserAccessControlS"has_summary","summary_outcome","external_references",+ "matches_filters",]read_only_fields = [@@ -1958,6 +1968,23 @@ def _load_recording_if_matches_filters(return None+def _load_selected_recording_ignoring_filters(session_id: str, team: Team) -> SessionRecording | None:+ """+ Load a recording directly by session id, ignoring listing filters.++ Used when a recording explicitly requested via session_recording_id (e.g. a shared link)+ doesn't match the current filters: we still want the link to open it, flagged with+ matches_filters=False so the UI can explain why it's shown.+ """+ recording = SessionRecording.get_or_build(session_id=session_id, team=team)+ if recording.deleted:+ return None+ if not recording.load_metadata():+ return None+ recording.matches_filters = False+ return recording++# TODO i guess this becomes the query runner for our _internal_ use of RecordingsQuerydef list_recordings_from_query(query: RecordingsQuery, user: User | None, team: Team, allow_event_property_expansion: bool = False@@ -1998,6 +2025,10 @@ def list_recordings_from_query(team,allow_event_property_expansion,)+ if prepend_recording is None:+ # The recording was explicitly requested (e.g. a shared link) but doesn't match+ # the current filters - include it anyway so the link still opens it+ prepend_recording = _load_selected_recording_ignoring_filters(session_recording_id_to_prepend, team)if prepend_recording:recordings.append(prepend_recording)diff --git a/posthog/session_recordings/test/test_session_recordings.py b/posthog/session_recordings/test/test_session_recordings.pyindex 336b203fcf16..36d9c852099c 100644--- a/posthog/session_recordings/test/test_session_recordings.py+++ b/posthog/session_recordings/test/test_session_recordings.py@@ -444,6 +444,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)"has_summary": False,"summary_outcome": None,"external_references": [],+ "matches_filters": True,},]@@ -855,6 +856,7 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)"has_summary": False,"summary_outcome": None,"external_references": [],+ "matches_filters": True,}@freeze_time("2023-01-01T12:00:00.000Z")@@ -1960,14 +1962,15 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)"session_recording_id": "session_5",},# session_5 matches the date filter (-3d) even though it would be on a later page- # so it should be prepended to results- ["session_5"], # must be in results+ # so it should be prepended to results, and marked as matching the filters+ {"session_5": True}, # must be in results, with expected matches_filters[], # must NOT be in results),(- "recording_outside_date_range_is_excluded",+ "recording_outside_date_range_is_included_but_flagged",# Create a recording from 10 days ago, request with date_from=-3d- # The recording doesn't match the date filter, so should NOT be included+ # The recording doesn't match the date filter, but was explicitly requested+ # (e.g. a shared link), so it should still be included, flagged as not matching{"recordings": [{"session_id": "recent_session", "days_ago": 1},@@ -1976,8 +1979,21 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)"date_from": "-3d","session_recording_id": "old_session",},- ["recent_session"], # must be in results- ["old_session"], # must NOT be in results - doesn't match date filter+ {"recent_session": True, "old_session": False}, # must be in results, with expected matches_filters+ [], # must NOT be in results+ ),+ (+ "nonexistent_recording_is_excluded",+ # Ask for a session_recording_id that was never recorded - nothing to include+ {+ "recordings": [+ {"session_id": "recent_session", "days_ago": 1},+ ],+ "date_from": "-3d",+ "session_recording_id": "no_such_session",+ },+ {"recent_session": True}, # must be in results, with expected matches_filters+ ["no_such_session"], # must NOT be in results),])@@ -1985,17 +2001,18 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)self,_name: str,config: dict,- must_be_in_results: list[str],+ must_be_in_results: dict[str, bool],must_not_be_in_results: list[str],):"""- Test that session_recording_id only includes recordings that match the current filters.+ Test how session_recording_id interacts with the current filters.- A recording should be prepended to results if:- - It matches all filters (date range, properties, etc.) but is on a different page+ A recording requested via session_recording_id should always be included if it exists:+ - matches_filters=True when it matches all filters (e.g. it's just on a different page)+ - matches_filters=False when it doesn't match the filters (e.g. outside date range),+ so the UI can explain why it's shown- A recording should NOT be included if:- - It doesn't match the filters (e.g., outside date range)+ It should NOT be included only when it doesn't exist at all."""base_time = now()@@ -2015,10 +2032,15 @@ class TestSessionRecordings(APIBaseTest, ClickhouseTestMixin, QueryMatchingTest)assert response.status_code == status.HTTP_200_OKresponse_data = response.json()- session_ids = [r["id"] for r in response_data["results"]]+ recordings_by_id = {r["id"]: r for r in response_data["results"]}+ session_ids = list(recordings_by_id.keys())- for expected in must_be_in_results:+ for expected, expected_matches_filters in must_be_in_results.items():assert expected in session_ids, f"Expected {expected} to be in results, but got {session_ids}"+ assert recordings_by_id[expected]["matches_filters"] == expected_matches_filters, (+ f"Expected {expected} to have matches_filters={expected_matches_filters}, "+ f"but got {recordings_by_id[expected]['matches_filters']}"+ )for unexpected in must_not_be_in_results:assert unexpected not in session_ids, f"Expected {unexpected} to NOT be in results, but got {session_ids}"diff --git a/products/replay/frontend/generated/api.schemas.ts b/products/replay/frontend/generated/api.schemas.tsindex 626b1cf7f880..efa1a4e3edd7 100644--- a/products/replay/frontend/generated/api.schemas.ts+++ b/products/replay/frontend/generated/api.schemas.ts@@ -259,6 +259,8 @@ export interface SessionRecordingApi {readonly summary_outcome: OutcomeApi | null/** Load external references (linked issues) for this recording */readonly external_references: readonly SessionRecordingApiExternalReferencesItem[]+ /** Whether this recording matched the filters of the listing query that returned it. False only when a recording requested via session_recording_id was included despite not matching the filters. */+ readonly matches_filters: boolean}export interface PaginatedSessionRecordingListApi {@@ -319,6 +321,8 @@ export interface PatchedSessionRecordingApi {readonly summary_outcome?: OutcomeApi | null/** Load external references (linked issues) for this recording */readonly external_references?: readonly PatchedSessionRecordingApiExternalReferencesItem[]+ /** Whether this recording matched the filters of the listing query that returned it. False only when a recording requested via session_recording_id was included despite not matching the filters. */+ readonly matches_filters?: boolean}/**diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 108c0d3d4e5b..de0983a311d8 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -21212,6 +21212,8 @@ export namespace Schemas {id: string;inactive_seconds?: number | null;keypress_count?: number | null;+ /** False when the recording was included in list results via a direct link despite not matching the filters. */+ matches_filters?: boolean | null;/** List of matching events. * */matching_events?: MatchedRecording[] | null;/** count of all mouse activity in the recording, not just clicks */@@ -26521,6 +26523,8 @@ export namespace Schemas {readonly summary_outcome: Outcome | null;/** Load external references (linked issues) for this recording */readonly external_references: readonly SessionRecordingExternalReferencesItem[];+ /** Whether this recording matched the filters of the listing query that returned it. False only when a recording requested via session_recording_id was included despite not matching the filters. */+ readonly matches_filters: boolean;}export interface PaginatedSessionRecordingList {@@ -33062,6 +33066,8 @@ export namespace Schemas {readonly summary_outcome?: Outcome | null;/** Load external references (linked issues) for this recording */readonly external_references?: readonly PatchedSessionRecordingExternalReferencesItem[];+ /** Whether this recording matched the filters of the listing query that returned it. False only when a recording requested via session_recording_id was included despite not matching the filters. */+ readonly matches_filters?: boolean;}/**