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(dashboards): let session replay widget use a saved filter (#63611)

Matt Pua82aaa236a6bc
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e38c0d431b76..f89a82e69f0e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1637,17 +1637,17 @@ snapshots:
dashboards-dashboard-widgets-widget-types-error-tracking-top-issues-widget-settings--default--light:
hash: v1.k794b7964.af604b406115bf252f107bd8599029b5e34b473e76cac0c368f12228895186ed.xLjKRF0exewyVhp-Zz52PwMmAJbqO6trsSNRtXbzIEY
dashboards-dashboard-widgets-widget-types-session-replay-recent-recordings--default--dark:
- hash: v1.k794b7964.f1698058cec0af37a2fb4d427bc7b15083559fa9227e94e49e9593625481c9b4.j-4sLHULNBCXVrl8NcFjxdVp2-ZEhpoDz4VLre5w_34
+ hash: v1.k794b7964.1a5baf14a6ff53a6072ebc87ed92ec20014d81c90e9718dd144c869c7c0f1a6d.mntf80pED3WsfNCXd5dto32xdxLBogMzx9mjVP0E4Qk
dashboards-dashboard-widgets-widget-types-session-replay-recent-recordings--default--light:
- hash: v1.k794b7964.81a1378fee1d06b6ab6694275f3445452a7d8b5ce58fc32a983aa7f47ce8a39f.Y6bQeZ31a5YYx9Aqf843Qox9J-TEx7r8d25rOlSzWAU
+ hash: v1.k794b7964.174eba9fddf2ca4e75de26df89877be8be3806118de31a51783172d0bb65ef77._au5PQmFg3Hwy24YPtpsX8E-Yduc0ryiTtiwbl9Ph-Y
dashboards-dashboard-widgets-widget-types-session-replay-recent-recordings--empty--dark:
- hash: v1.k794b7964.be226977d5f72fdb0301d4e864449748e415b98c8ca5c0c13c7875c753e6d0a8.lNuA0SSyrtLdg4y9GDpAtvGiua2_SBEn_euJuQQpnSs
+ hash: v1.k794b7964.592a89356f71503b99b8d0a6f86d0d0fcb8e19dc02a831fb2a2039b6fed6b458.4Odr8Kn6Nr083ssZqxMyogCHqVcXlE1olBFe8iFtdCE
dashboards-dashboard-widgets-widget-types-session-replay-recent-recordings--empty--light:
- hash: v1.k794b7964.8594cb806e039b6acc39aa154cc9d615cf617ccc94a233dc994d2d6458660524.sKo_0DMoN3WolbzfcIrukqUvlRMTmvv3arMQXGhDJFo
+ hash: v1.k794b7964.136e47e823367ddde1e45ad2029549d3d54c6c265a0fca15a2e013c10acad739.wzHAAYGHHBJKmNw2wT20CcWdc90sm7rjuyE0U0hahtk
dashboards-dashboard-widgets-widget-types-session-replay-recent-recordings--loading--dark:
- hash: v1.k794b7964.8c716c7fa337951ad08fef65d72c00bb666cb084b29f985198b9cb524732f099.KK_xA5RwbUvuQeFem6S-3nUPFw-CZhUqskMJ44PJlas
+ hash: v1.k794b7964.35d12cc442584f42f106f08dad08f7c982cd62456d8b17f339282811181ed433.E7b7wXwG8qjMLhV4ZcBi9wji-LIVO1ziUzXQ2JZMwnA
dashboards-dashboard-widgets-widget-types-session-replay-recent-recordings--loading--light:
- hash: v1.k794b7964.50c3acf529b880149a25537357a26f11635c90484822568c711dacf59b6d7ed8.bHVMkCbmy8bQEjO3TflvMy1TZyJJyX6Fdiqvl2SGrhU
+ hash: v1.k794b7964.51c40a376b640aee32bc2ab8eb0aa2972fcddae0d716bca64479cdb6be7d4a19.58GccMzkk2kg1UOBSWJLCxMTYffpCnhMrJoulJVe3Xg
dashboards-dashboard-widgets-widget-types-session-replay-recent-recordings--setup-unavailable--dark:
hash: v1.k794b7964.4d843ded3453a2be0dd16f6bb4efe34dd8de634388ed8073cf7c748b6614e186.RKgAGczYSH33uEfBaYGMSlXx7pa4c2QToaJprdtWnKs
dashboards-dashboard-widgets-widget-types-session-replay-recent-recordings--setup-unavailable--light:
@@ -1657,9 +1657,9 @@ snapshots:
dashboards-dashboard-widgets-widget-types-session-replay-recent-recordings--tile-filters-read-only--light:
hash: v1.k794b7964.c85c4bac88ef878a5a72f1eb276184f6b9091e2c8f1e19b4db2d555220e21558.RlnAWW9XRd6OuL1cQI18TrVcWv0JpjB_VLaXD4ZIRKQ
dashboards-dashboard-widgets-widget-types-session-replay-recent-recordings-widget-settings--default--dark:
- hash: v1.k794b7964.7a360d33ee768adcdd8eacfa769a936e2363321adc21eaff60683098c29d847c.N0ylw1z2Ul0sGiYOCkdb1ot4ON-BoCRxW7s3lJS0tmQ
+ hash: v1.k794b7964.0600e1578c99c4388b9a2251ce03d1dd782ada03f7c370ab4c6ca3d1fc439299.N_1E05hIQbLpHPRr30SVKVe7RO841TkG8ge6oZtF8Bo
dashboards-dashboard-widgets-widget-types-session-replay-recent-recordings-widget-settings--default--light:
- hash: v1.k794b7964.b7d9d2ce3520e09307823e43268a6146b27df0cf47fbef8d9a383b9f396ee784.837NbehGBSlkrvdWDWH0ZyZMxaOJQxynzTmQphDuoqY
+ hash: v1.k794b7964.a54fd854672dbfd9bca0120f80eda64b5f26fa50d07f65a20e491d0726110732.6B1Uq49T3-NH5rQ_Aqdrk4Ov0eHWtT2BzWYbQ_jLsg8
dashboards-dashboard-widgets-widgetcard--default--dark:
hash: v1.k794b7964.131c8ca3c5e54927f05d636bbbf578d239f0caaaaa672df4a3d258a95262b360.QaO0tmZaChmZ6GKYLMewEm-GpVqdiEYVpLJTMv78RgI
dashboards-dashboard-widgets-widgetcard--default--light:
diff --git a/posthog/session_recordings/playlist_filters.py b/posthog/session_recordings/playlist_filters.py
new file mode 100644
index 000000000000..b7c0cd27e1f7
--- /dev/null
+++ b/posthog/session_recordings/playlist_filters.py
@@ -0,0 +1,240 @@
+from typing import Any, Optional
+
+from prometheus_client import Counter
+from pydantic import ValidationError
+from structlog import get_logger
+
+from posthog.schema import (
+ FilterLogicalOperator,
+ PropertyFilterType,
+ PropertyOperator,
+ RecordingPropertyFilter,
+ RecordingsQuery,
+)
+
+from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
+from posthog.session_recordings.utils import filter_from_params_to_query
+
+logger = get_logger(__name__)
+
+REPLAY_PLAYLIST_LEGACY_FILTERS_CONVERTED = Counter(
+ "replay_playlist_legacy_filters_converted",
+ "when a count task for a playlist converts legacy filters to universal filters",
+)
+
+DEFAULT_RECORDING_FILTERS = {
+ "date_from": "-3d",
+ "date_to": None,
+ "filter_test_accounts": False,
+ "duration": [
+ {
+ "type": PropertyFilterType.RECORDING,
+ "key": "active_seconds",
+ "value": 5,
+ "operator": PropertyOperator.GT,
+ }
+ ],
+ "order": "start_time",
+}
+
+
+def asRecordingPropertyFilter(filter: dict[str, Any]) -> RecordingPropertyFilter:
+ return RecordingPropertyFilter(
+ key=filter["key"],
+ operator=filter["operator"],
+ value=filter["value"],
+ )
+
+
+def convert_legacy_filters_to_universal_filters(filters: Optional[dict[str, Any]] = None) -> dict[str, Any]:
+ """
+ Convert legacy filters to universal filters format.
+ This is the Python equivalent of the frontend's convertLegacyFiltersToUniversalFilters function.
+ """
+ filters = filters or {}
+
+ if not filters:
+ return {}
+
+ events = filters.get("events", [])
+ actions = filters.get("actions", [])
+ properties = filters.get("properties", [])
+
+ log_level_filters = []
+ if filters.get("console_logs"):
+ log_level_filters.append(
+ {
+ "key": "level",
+ "value": filters["console_logs"],
+ "operator": PropertyOperator.EXACT,
+ "type": PropertyFilterType.LOG_ENTRY,
+ }
+ )
+
+ log_query_filters = []
+ if filters.get("console_search_query"):
+ log_query_filters.append(
+ {
+ "key": "message",
+ "value": [filters["console_search_query"]],
+ "operator": PropertyOperator.EXACT,
+ "type": PropertyFilterType.LOG_ENTRY,
+ }
+ )
+
+ duration = []
+ if filters.get("session_recording_duration"):
+ duration.append(
+ {
+ **filters["session_recording_duration"],
+ "key": filters.get(
+ "duration_type_filter", filters.get("session_recording_duration", {}).get("key", "active_seconds")
+ ),
+ }
+ )
+
+ return {
+ "date_from": filters.get("date_from") or DEFAULT_RECORDING_FILTERS["date_from"],
+ "date_to": filters.get("date_to") or DEFAULT_RECORDING_FILTERS["date_to"],
+ "filter_test_accounts": filters.get("filter_test_accounts", DEFAULT_RECORDING_FILTERS["filter_test_accounts"]),
+ "duration": duration or DEFAULT_RECORDING_FILTERS["duration"],
+ "filter_group": {
+ "type": FilterLogicalOperator.AND_,
+ "values": [
+ {
+ "type": FilterLogicalOperator.AND_,
+ "values": events + actions + properties + log_level_filters + log_query_filters,
+ }
+ ],
+ },
+ "order": DEFAULT_RECORDING_FILTERS["order"],
+ }
+
+
+def convert_playlist_to_recordings_query(
+ playlist: SessionRecordingPlaylist, *, persist_legacy_conversion: bool = True
+) -> RecordingsQuery:
+ """Convert playlist with filters to a RecordingsQuery object.
+
+ When ``persist_legacy_conversion`` is False the legacy->universal conversion happens
+ in-memory only — callers on a read path (e.g. rendering a dashboard widget) should not
+ write to the shared playlist row as a side effect.
+ """
+ # Copy so the popping below never mutates the shared playlist.filters dict in-place.
+ filters = dict(playlist.filters)
+
+ # we used to send `version` and it's not part of query, so we pop to make sure
+ filters.pop("version", None)
+ # we used to send `hogql_filtering` and it's not part of query, so we pop to make sure
+ filters.pop("hogql_filtering", None)
+
+ # Check if we have legacy filters (they don't have filter_group)
+ if "filter_group" not in filters:
+ if not filters:
+ return filter_from_params_to_query(filters)
+ else:
+ # then we have a legacy filter
+ # because we know we don't have a query
+ filters = convert_legacy_filters_to_universal_filters(filters)
+ if persist_legacy_conversion:
+ playlist.filters = filters
+ playlist.save(update_fields=["filters"])
+ REPLAY_PLAYLIST_LEGACY_FILTERS_CONVERTED.inc()
+
+ return convert_filters_to_recordings_query(filters)
+
+
+def convert_filters_to_recordings_query(filters: dict[str, Any]) -> RecordingsQuery:
+ """
+ Convert universal filters to a RecordingsQuery object.
+ This is the Python equivalent of the frontend's convertUniversalFiltersToRecordingsQuery function.
+ """
+
+ # Extract filters from the filter group
+ extracted_filters = []
+ if filters.get("filter_group") and filters["filter_group"].get("values"):
+ # Get the first group (which should be the only one)
+ group = filters["filter_group"]["values"][0]
+ if group and group.get("values"):
+ extracted_filters = group["values"]
+
+ events = []
+ actions = []
+ properties = []
+ console_log_filters = []
+ having_predicates = []
+
+ # Get order and duration filter
+ order = filters.get("order")
+ duration_filters = filters.get("duration", [])
+ if duration_filters and len(duration_filters) > 0:
+ having_predicates.append(asRecordingPropertyFilter(duration_filters[0]))
+
+ # Process each filter
+ for f in extracted_filters:
+ filter_type = f.get("type")
+
+ if filter_type == "events":
+ events.append(f)
+ elif filter_type == "actions":
+ actions.append(f)
+ elif filter_type == "log_entry":
+ console_log_filters.append(f)
+ elif filter_type == "hogql":
+ properties.append(f)
+ elif filter_type == "recording":
+ if f.get("key") == "visited_page":
+ events.append(
+ {
+ "id": "$pageview",
+ "name": "$pageview",
+ "type": "events",
+ "properties": [
+ {
+ "type": "event",
+ "key": "$current_url",
+ "value": f.get("value"),
+ "operator": f.get("operator"),
+ }
+ ],
+ }
+ )
+ elif f.get("key") == "snapshot_source" and f.get("value"):
+ having_predicates.append(f)
+ else:
+ having_predicates.append(asRecordingPropertyFilter(f))
+ else:
+ # For any other property filter
+ properties.append(f)
+
+ try:
+ # Construct the RecordingsQuery
+ return RecordingsQuery(
+ order=order,
+ date_from=filters.get("date_from"),
+ date_to=filters.get("date_to"),
+ properties=properties,
+ events=events,
+ actions=actions,
+ console_log_filters=console_log_filters,
+ having_predicates=having_predicates,
+ filter_test_accounts=filters.get("filter_test_accounts"),
+ operand=filters.get("filter_group", {}).get("type", FilterLogicalOperator.AND_),
+ limit=filters.get("limit"),
+ )
+ except ValidationError as e:
+ # we were seeing errors here and it was hard to debug
+ # so we're logging all the data and the error
+ logger.exception(
+ "Failed to convert universal filters to RecordingsQuery",
+ filters=filters,
+ error=e,
+ having_predicates=having_predicates,
+ properties=properties,
+ events=events,
+ actions=actions,
+ console_log_filters=console_log_filters,
+ filter_test_accounts=filters.get("filter_test_accounts"),
+ operand=filters.get("filter_group", {}).get("type", FilterLogicalOperator.AND_),
+ )
+ raise
diff --git a/posthog/temporal/session_replay/count_playlist_items/__init__.py b/posthog/temporal/session_replay/count_playlist_items/__init__.py
index 2e4b244e93e1..845b79f6035d 100644
--- a/posthog/temporal/session_replay/count_playlist_items/__init__.py
+++ b/posthog/temporal/session_replay/count_playlist_items/__init__.py
@@ -1,11 +1,11 @@
+from posthog.session_recordings.playlist_filters import (
+ convert_filters_to_recordings_query,
+ convert_playlist_to_recordings_query,
+)
from posthog.temporal.session_replay.count_playlist_items.activities import (
count_recordings_for_playlist,
fetch_playlists_to_count,
)
-from posthog.temporal.session_replay.count_playlist_items.counting_logic import (
- convert_filters_to_recordings_query,
- convert_playlist_to_recordings_query,
-)
from posthog.temporal.session_replay.count_playlist_items.workflow import (
CountAllPlaylistsWorkflow,
CountPlaylistWorkflow,
diff --git a/posthog/temporal/session_replay/count_playlist_items/counting_logic.py b/posthog/temporal/session_replay/count_playlist_items/counting_logic.py
index a6e99d6639c2..a9fd8b20f375 100644
--- a/posthog/temporal/session_replay/count_playlist_items/counting_logic.py
+++ b/posthog/temporal/session_replay/count_playlist_items/counting_logic.py
@@ -1,6 +1,6 @@
import json
from datetime import datetime, timedelta
-from typing import Any, Optional
+from typing import Any
from django.conf import settings
from django.db.models import Count, F, Q
@@ -8,22 +8,16 @@ from django.utils import timezone
import posthoganalytics
from prometheus_client import Counter, Gauge, Histogram
-from pydantic import ValidationError
from structlog import get_logger
-from posthog.schema import (
- FilterLogicalOperator,
- PropertyFilterType,
- PropertyOperator,
- RecordingPropertyFilter,
- RecordingsQuery,
-)
+from posthog.schema import RecordingsQuery
from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
from posthog.helpers.session_recording_playlist_templates import DEFAULT_PLAYLIST_NAMES
from posthog.redis import get_client
from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
-from posthog.session_recordings.session_recording_api import filter_from_params_to_query, list_recordings_from_query
+from posthog.session_recordings.playlist_filters import DEFAULT_RECORDING_FILTERS, convert_playlist_to_recordings_query
+from posthog.session_recordings.session_recording_api import list_recordings_from_query
from posthog.session_recordings.session_recording_playlist_api import PLAYLIST_COUNT_REDIS_PREFIX
logger = get_logger(__name__)
@@ -51,11 +45,6 @@ REPLAY_TEAM_PLAYLIST_COUNT_SKIPPED = Counter(
labelnames=["reason"],
)
-REPLAY_PLAYLIST_LEGACY_FILTERS_CONVERTED = Counter(
- "replay_playlist_legacy_filters_converted",
- "when a count task for a playlist converts legacy filters to universal filters",
-)
-
REPLAY_PLAYLIST_COULD_NOT_ADD_ERROR_COUNT = Counter(
"replay_playlist_could_not_add_error_count",
"when a count task for a playlist could not add an error count",
@@ -78,21 +67,6 @@ REPLAY_PLAYLISTS_IN_REDIS_GAUGE = Gauge(
"Number of playlists in Redis",
)
-DEFAULT_RECORDING_FILTERS = {
- "date_from": "-3d",
- "date_to": None,
- "filter_test_accounts": False,
- "duration": [
- {
- "type": PropertyFilterType.RECORDING,
- "key": "active_seconds",
- "value": 5,
- "operator": PropertyOperator.GT,
- }
- ],
- "order": "start_time",
-}
-
def count_playlists_in_redis() -> int:
redis_client = get_client()
@@ -106,199 +80,6 @@ def count_playlists_in_redis() -> int:
return playlist_count
-def asRecordingPropertyFilter(filter: dict[str, Any]) -> RecordingPropertyFilter:
- return RecordingPropertyFilter(
- key=filter["key"],
- operator=filter["operator"],
- value=filter["value"],
- )
-
-
-def convert_legacy_filters_to_universal_filters(filters: Optional[dict[str, Any]] = None) -> dict[str, Any]:
- """
- Convert legacy filters to universal filters format.
- This is the Python equivalent of the frontend's convertLegacyFiltersToUniversalFilters function.
- """
- filters = filters or {}
-
- if not filters:
- return {}
-
- events = filters.get("events", [])
- actions = filters.get("actions", [])
- properties = filters.get("properties", [])
-
- log_level_filters = []
- if filters.get("console_logs"):
- log_level_filters.append(
- {
- "key": "level",
- "value": filters["console_logs"],
- "operator": PropertyOperator.EXACT,
- "type": PropertyFilterType.LOG_ENTRY,
- }
- )
-
- log_query_filters = []
- if filters.get("console_search_query"):
- log_query_filters.append(
- {
- "key": "message",
- "value": [filters["console_search_query"]],
- "operator": PropertyOperator.EXACT,
- "type": PropertyFilterType.LOG_ENTRY,
- }
- )
-
- duration = []
- if filters.get("session_recording_duration"):
- duration.append(
- {
- **filters["session_recording_duration"],
- "key": filters.get(
- "duration_type_filter", filters.get("session_recording_duration", {}).get("key", "active_seconds")
- ),
- }
- )
-
- return {
- "date_from": filters.get("date_from") or DEFAULT_RECORDING_FILTERS["date_from"],
- "date_to": filters.get("date_to") or DEFAULT_RECORDING_FILTERS["date_to"],
- "filter_test_accounts": filters.get("filter_test_accounts", DEFAULT_RECORDING_FILTERS["filter_test_accounts"]),
- "duration": duration or DEFAULT_RECORDING_FILTERS["duration"],
- "filter_group": {
- "type": FilterLogicalOperator.AND_,
- "values": [
- {
- "type": FilterLogicalOperator.AND_,
- "values": events + actions + properties + log_level_filters + log_query_filters,
- }
- ],
- },
- "order": DEFAULT_RECORDING_FILTERS["order"],
- }
-
-
-def convert_playlist_to_recordings_query(playlist: SessionRecordingPlaylist) -> RecordingsQuery:
- """Convert playlist with filters to a RecordingsQuery object."""
- filters = playlist.filters
-
- # we used to send `version` and it's not part of query, so we pop to make sure
- filters.pop("version", None)
- # we used to send `hogql_filtering` and it's not part of query, so we pop to make sure
- filters.pop("hogql_filtering", None)
-
- # Check if we have legacy filters (they don't have filter_group)
- if "filter_group" not in filters:
- if not filters:
- return filter_from_params_to_query(filters)
- else:
- # then we have a legacy filter
- # because we know we don't have a query
- filters = convert_legacy_filters_to_universal_filters(filters)
- playlist.filters = filters
- playlist.save(update_fields=["filters"])
- REPLAY_PLAYLIST_LEGACY_FILTERS_CONVERTED.inc()
-
- return convert_filters_to_recordings_query(filters)
-
-
-def convert_filters_to_recordings_query(filters: dict[str, Any]) -> RecordingsQuery:
- """
- Convert universal filters to a RecordingsQuery object.
- This is the Python equivalent of the frontend's convertUniversalFiltersToRecordingsQuery function.
- """
-
- # Extract filters from the filter group
- extracted_filters = []
- if filters.get("filter_group") and filters["filter_group"].get("values"):
- # Get the first group (which should be the only one)
- group = filters["filter_group"]["values"][0]
- if group and group.get("values"):
- extracted_filters = group["values"]
-
- events = []
- actions = []
- properties = []
- console_log_filters = []
- having_predicates = []
-
- # Get order and duration filter
- order = filters.get("order")
- duration_filters = filters.get("duration", [])
- if duration_filters and len(duration_filters) > 0:
- having_predicates.append(asRecordingPropertyFilter(duration_filters[0]))
-
- # Process each filter
- for f in extracted_filters:
- filter_type = f.get("type")
-
- if filter_type == "events":
- events.append(f)
- elif filter_type == "actions":
- actions.append(f)
- elif filter_type == "log_entry":
- console_log_filters.append(f)
- elif filter_type == "hogql":
- properties.append(f)
- elif filter_type == "recording":
- if f.get("key") == "visited_page":
- events.append(
- {
- "id": "$pageview",
- "name": "$pageview",
- "type": "events",
- "properties": [
- {
- "type": "event",
- "key": "$current_url",
- "value": f.get("value"),
- "operator": f.get("operator"),
- }
- ],
- }
- )
- elif f.get("key") == "snapshot_source" and f.get("value"):
- having_predicates.append(f)
- else:
- having_predicates.append(asRecordingPropertyFilter(f))
- else:
- # For any other property filter
- properties.append(f)
-
- try:
- # Construct the RecordingsQuery
- return RecordingsQuery(
- order=order,
- date_from=filters.get("date_from"),
- date_to=filters.get("date_to"),
- properties=properties,
- events=events,
- actions=actions,
- console_log_filters=console_log_filters,
- having_predicates=having_predicates,
- filter_test_accounts=filters.get("filter_test_accounts"),
- operand=filters.get("filter_group", {}).get("type", FilterLogicalOperator.AND_),
- limit=filters.get("limit"),
- )
- except ValidationError as e:
- # we were seeing errors here and it was hard to debug
- # so we're logging all the data and the error
- logger.exception(
- "Failed to convert universal filters to RecordingsQuery",
- filters=filters,
- error=e,
- having_predicates=having_predicates,
- properties=properties,
- events=events,
- actions=actions,
- console_log_filters=console_log_filters,
- filter_test_accounts=filters.get("filter_test_accounts"),
- operand=filters.get("filter_group", {}).get("type", FilterLogicalOperator.AND_),
- )
- raise
-
-
def try_to_store_error_count(playlist_short_id: str | None) -> None:
try:
if not playlist_short_id:
diff --git a/products/dashboards/backend/api/test/test_run_widgets.py b/products/dashboards/backend/api/test/test_run_widgets.py
index fc9ec78bc439..ff8a67ccda27 100644
--- a/products/dashboards/backend/api/test/test_run_widgets.py
+++ b/products/dashboards/backend/api/test/test_run_widgets.py
@@ -9,15 +9,18 @@ from django.test.utils import override_settings
from parameterized import parameterized
from rest_framework import status
+from posthog.schema import RecordingOrder, RecordingOrderDirection
+
from posthog.api.test.dashboards import DashboardAPI
from posthog.clickhouse.client.execute import UntaggedQueryError
from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags
-from posthog.models import Person
+from posthog.models import Person, Team
from posthog.models.personal_api_key import PersonalAPIKey
from posthog.models.utils import generate_random_token_personal, hash_key_value
from posthog.rbac.user_access_control import AccessControlLevel, UserAccessControl
from posthog.scopes import APIScopeObject
from posthog.session_recordings.models.session_recording import SessionRecording
+from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
from posthog.slo.types import SloOperation, SloOutcome
from products.dashboards.backend.api import widget_openapi_serializers as widget_openapi_serializers_module
@@ -347,6 +350,132 @@ class TestDashboardRunWidgets(APIBaseTest):
assert query.properties[0].operator == "exact"
assert query.properties[0].value == ["Chrome"]
+ @staticmethod
+ def _saved_filter_for_browser(team: Team, browser: str) -> SessionRecordingPlaylist:
+ return SessionRecordingPlaylist.objects.create(
+ team=team,
+ name="My saved filter",
+ type="filters",
+ filters={
+ "date_from": "-14d",
+ "filter_group": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [{"type": "person", "key": "$browser", "value": [browser], "operator": "exact"}],
+ }
+ ],
+ },
+ "order": "start_time",
+ },
+ )
+
+ @staticmethod
+ def _widget_browser_filter(browser: str) -> dict[str, Any]:
+ return {
+ "filter-1": {
+ "filterId": "filter-1",
+ "propertyName": "$browser",
+ "optionId": "opt-1",
+ "operator": "exact",
+ "value": browser,
+ }
+ }
+
+ @patch("posthog.session_recordings.session_recording_api.list_recordings_from_query")
+ def test_session_replay_widget_uses_saved_filter_as_source_of_truth(self, mock_list_recordings: MagicMock) -> None:
+ mock_list_recordings.return_value = ([], False, None, None)
+ saved_filter = self._saved_filter_for_browser(self.team, "Firefox")
+
+ run_session_replay_list_widget(
+ self.team,
+ {
+ "limit": 5,
+ "orderBy": "click_count",
+ "orderDirection": "ASC",
+ "savedFilterId": saved_filter.short_id,
+ # The widget's own date range and property filters must be ignored.
+ "dateRange": {"date_from": "-7d"},
+ "widgetFilters": self._widget_browser_filter("Chrome"),
+ },
+ user=self.user,
+ )
+
+ query = mock_list_recordings.call_args.kwargs["query"]
+ # Saved filter drives the date range and property filters...
+ assert query.date_from == "-14d"
+ assert query.properties is not None
+ assert len(query.properties) == 1
+ assert query.properties[0].key == "$browser"
+ assert query.properties[0].value == ["Firefox"]
+ # ...while the widget still layers its own sort and limit on top.
+ assert query.limit == 5
+ assert query.order == RecordingOrder.CLICK_COUNT
+ assert query.order_direction == RecordingOrderDirection.ASC
+
+ @patch("posthog.session_recordings.session_recording_api.list_recordings_from_query")
+ def test_session_replay_widget_falls_back_when_saved_filter_missing(self, mock_list_recordings: MagicMock) -> None:
+ mock_list_recordings.return_value = ([], False, None, None)
+
+ run_session_replay_list_widget(
+ self.team,
+ {
+ "limit": 5,
+ "savedFilterId": "does_not_exist",
+ "dateRange": {"date_from": "-7d"},
+ "widgetFilters": self._widget_browser_filter("Chrome"),
+ },
+ user=self.user,
+ )
+
+ query = mock_list_recordings.call_args.kwargs["query"]
+ assert query.properties is not None
+ assert query.properties[0].value == ["Chrome"]
+
+ @patch("posthog.session_recordings.session_recording_api.list_recordings_from_query")
+ def test_session_replay_widget_ignores_saved_filter_from_other_team(self, mock_list_recordings: MagicMock) -> None:
+ mock_list_recordings.return_value = ([], False, None, None)
+ other_team = Team.objects.create(organization=self.organization, name="other team")
+ saved_filter = self._saved_filter_for_browser(other_team, "Firefox")
+
+ run_session_replay_list_widget(
+ self.team,
+ {
+ "limit": 5,
+ "savedFilterId": saved_filter.short_id,
+ "dateRange": {"date_from": "-7d"},
+ "widgetFilters": self._widget_browser_filter("Chrome"),
+ },
+ user=self.user,
+ )
+
+ query = mock_list_recordings.call_args.kwargs["query"]
+ # A saved filter owned by another team must not be reachable; fall back to the widget's filters.
+ assert query.properties is not None
+ assert query.properties[0].value == ["Chrome"]
+
+ @patch("posthog.session_recordings.session_recording_api.list_recordings_from_query")
+ def test_session_replay_widget_does_not_persist_legacy_filter_conversion(
+ self, mock_list_recordings: MagicMock
+ ) -> None:
+ mock_list_recordings.return_value = ([], False, None, None)
+ # A legacy-format playlist (no filter_group) — rendering must not write the converted filters back.
+ legacy_filters = {"events": [{"id": "$pageview", "type": "events", "order": 0, "name": "$pageview"}]}
+ saved_filter = SessionRecordingPlaylist.objects.create(
+ team=self.team, name="Legacy filter", type="filters", filters=legacy_filters
+ )
+
+ run_session_replay_list_widget(
+ self.team,
+ {"limit": 5, "savedFilterId": saved_filter.short_id},
+ user=self.user,
+ )
+
+ saved_filter.refresh_from_db()
+ assert saved_filter.filters == legacy_filters
+ assert "filter_group" not in saved_filter.filters
+
@patch("posthog.session_recordings.session_recording_api.list_recordings_from_query")
def test_session_replay_widget_serializes_recordings_with_person(self, mock_list_recordings: MagicMock) -> None:
person = Person.objects.create(team=self.team, properties={"email": "[email protected]"})
@@ -370,12 +499,12 @@ class TestDashboardRunWidgets(APIBaseTest):
self.assertIsNone(body["results"][0]["error"])
self.assertEqual(body["results"][0]["result"]["results"][0]["person"]["name"], "[email protected]")
- @patch("products.dashboards.backend.widgets.session_replay_list._run_session_replay_list_query")
+ @patch("products.dashboards.backend.widgets.session_replay_list._run_recordings_query")
def test_session_replay_widget_returns_total_count_when_page_has_more(self, mock_run_query: MagicMock) -> None:
recording = {"id": "recording-1"}
- def run_side_effect(_team: object, config: dict[str, object], _user: object) -> dict[str, object]:
- limit = config["limit"]
+ def run_side_effect(_team: object, query: object, _user: object) -> dict[str, object]:
+ limit = query.limit # type: ignore[attr-defined]
if limit == 1:
return {"results": [recording, {**recording, "id": "recording-2"}], "has_next": True}
return {
@@ -399,8 +528,8 @@ class TestDashboardRunWidgets(APIBaseTest):
self.assertFalse(result["totalCountCapped"])
self.assertEqual(len(result["results"]), 1)
self.assertEqual(mock_run_query.call_count, 2)
- count_call_config = mock_run_query.call_args_list[1].args[1]
- self.assertEqual(count_call_config["limit"], MAX_WIDGET_RESULT_LIMIT)
+ count_call_query = mock_run_query.call_args_list[1].args[1]
+ self.assertEqual(count_call_query.limit, MAX_WIDGET_RESULT_LIMIT)
@patch("products.dashboards.backend.widgets.error_tracking_list.ErrorTrackingQueryRunner")
def test_run_widgets_requests_listing_volume_resolution(self, mock_runner_cls: MagicMock) -> None:
diff --git a/products/dashboards/backend/widget_specs/configs.py b/products/dashboards/backend/widget_specs/configs.py
index 2dc18c169217..303f4c86d3ff 100644
--- a/products/dashboards/backend/widget_specs/configs.py
+++ b/products/dashboards/backend/widget_specs/configs.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from typing import Literal
-from pydantic import BaseModel, ConfigDict, Field
+from pydantic import BaseModel, ConfigDict, Field, field_validator
from products.dashboards.backend.constants import DEFAULT_WIDGET_LIST_LIMIT
from products.dashboards.backend.widget_specs.common import WidgetLimit, WidgetListConfigBase, WidgetOrderDirection
@@ -40,3 +40,19 @@ class SessionReplayListWidgetConfig(WidgetListConfigBase):
limit: WidgetLimit = Field(default=DEFAULT_WIDGET_LIST_LIMIT, description="Maximum number of recordings to return.")
orderBy: SessionReplayOrderBy = Field(default="start_time", description="Recording ranking column.")
orderDirection: WidgetOrderDirection = Field(default="DESC", description="Sort direction for orderBy.")
+ savedFilterId: str | None = Field(
+ default=None,
+ description=(
+ "short_id of a saved session replay filter to use as the recordings source. When set, the saved filter "
+ "owns the date range and property filters; only orderBy, orderDirection, and limit still apply."
+ ),
+ )
+
+ @field_validator("savedFilterId", mode="before")
+ @classmethod
+ def validate_saved_filter_id(cls, value: object) -> str | None:
+ if value is None or value == "":
+ return None
+ if not isinstance(value, str):
+ raise ValueError("savedFilterId must be a string.")
+ return value
diff --git a/products/dashboards/backend/widgets/session_replay_list.py b/products/dashboards/backend/widgets/session_replay_list.py
index 6f14e0b574fb..6af39ceeb130 100644
--- a/products/dashboards/backend/widgets/session_replay_list.py
+++ b/products/dashboards/backend/widgets/session_replay_list.py
@@ -1,13 +1,15 @@
from __future__ import annotations
import logging
-from typing import Any, cast
+from typing import Any
-from posthog.schema import RecordingOrder
+from posthog.schema import RecordingOrder, RecordingOrderDirection, RecordingsQuery
from posthog.clickhouse.query_tagging import Feature, Product, tags_context
from posthog.models.team import Team
from posthog.models.user import User
+from posthog.session_recordings.models.session_recording_playlist import SessionRecordingPlaylist
+from posthog.session_recordings.playlist_filters import convert_playlist_to_recordings_query
from posthog.session_recordings.session_recording_api import run_recordings_list_query
from posthog.session_recordings.utils import filter_from_params_to_query
@@ -31,7 +33,36 @@ ORDER_BY_TO_RECORDING_ORDER: dict[str, RecordingOrder] = {
}
-def _build_recordings_query(team: Team, config: ValidatedSessionReplayListWidgetConfig):
+def _build_saved_filter_recordings_query(
+ team: Team,
+ config: ValidatedSessionReplayListWidgetConfig,
+ saved_filter_id: str,
+) -> RecordingsQuery | None:
+ # The saved filter (SessionRecordingPlaylist of type "filters") is the source of truth for
+ # date range and property filters; the widget only layers its own sort and limit on top.
+ playlist = SessionRecordingPlaylist.objects.filter(
+ team=team, short_id=saved_filter_id, deleted=False, type="filters"
+ ).first()
+ if playlist is None:
+ logger.warning("session_replay_widget_saved_filter_not_found", extra={"short_id": saved_filter_id})
+ return None
+
+ # Read path: convert legacy filters in-memory, never write back to the shared playlist row.
+ query = convert_playlist_to_recordings_query(playlist, persist_legacy_conversion=False)
+ query.limit = config["limit"]
+ query.offset = 0
+ query.order = ORDER_BY_TO_RECORDING_ORDER[config["orderBy"]]
+ query.order_direction = RecordingOrderDirection(config["orderDirection"])
+ return query
+
+
+def _build_recordings_query(team: Team, config: ValidatedSessionReplayListWidgetConfig) -> RecordingsQuery:
+ saved_filter_id = config.get("savedFilterId")
+ if saved_filter_id:
+ saved_filter_query = _build_saved_filter_recordings_query(team, config, saved_filter_id)
+ if saved_filter_query is not None:
+ return saved_filter_query
+
date_range_raw = config.get("dateRange")
date_from = "-7d"
if date_range_raw is not None:
@@ -54,12 +85,7 @@ def _build_recordings_query(team: Team, config: ValidatedSessionReplayListWidget
return filter_from_params_to_query(params)
-def _run_session_replay_list_query(
- team: Team,
- config: ValidatedSessionReplayListWidgetConfig,
- user: User | None,
-) -> dict[str, Any]:
- query = _build_recordings_query(team, config)
+def _run_recordings_query(team: Team, query: RecordingsQuery, user: User | None) -> dict[str, Any]:
with tags_context(product=Product.REPLAY, feature=Feature.QUERY, team_id=team.pk):
return run_recordings_list_query(
query=query,
@@ -71,13 +97,15 @@ def _run_session_replay_list_query(
def _count_matching_session_recordings(
team: Team,
- config: ValidatedSessionReplayListWidgetConfig,
+ query: RecordingsQuery,
user: User | None,
*,
cap: int = MAX_WIDGET_RESULT_LIMIT,
) -> tuple[int, bool]:
- count_config = cast(ValidatedSessionReplayListWidgetConfig, {**config, "limit": cap})
- data = _run_session_replay_list_query(team, count_config, user)
+ # Reuse the already-built query (a saved-filter playlist is only fetched/converted once) and
+ # only raise the limit to the count cap.
+ count_query = query.model_copy(update={"limit": cap})
+ data = _run_recordings_query(team, count_query, user)
raw_results_value = data.get("results")
raw_results = raw_results_value if isinstance(raw_results_value, list) else []
return len(raw_results), bool(data.get("has_next"))
@@ -92,7 +120,8 @@ def run_session_replay_list_widget(
) -> dict[str, Any]:
typed_config = validate_widget_config(SESSION_REPLAY_LIST_WIDGET_TYPE, config)
limit = typed_config["limit"]
- data = _run_session_replay_list_query(team, typed_config, user)
+ query = _build_recordings_query(team, typed_config)
+ data = _run_recordings_query(team, query, user)
raw_results_value = data.get("results")
raw_results = raw_results_value if isinstance(raw_results_value, list) else []
results = raw_results[:limit]
@@ -109,7 +138,7 @@ def run_session_replay_list_widget(
if has_more:
if include_total_count:
try:
- total_count, total_count_capped = _count_matching_session_recordings(team, typed_config, user)
+ total_count, total_count_capped = _count_matching_session_recordings(team, query, user)
payload["totalCount"] = total_count
payload["totalCountCapped"] = total_count_capped
except Exception:
diff --git a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx
index 66a96c4c60cd..2eb74ec68bfa 100644
--- a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx
+++ b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx
@@ -213,6 +213,7 @@ function DashboardWidgetItemContent({
widgetTypeLabel={widgetTypeLabel}
config={widget.config}
headerMeta={headerCatalogEntry.headerMeta}
+ TopHeading={definition?.TopHeading}
description={description}
showDescription={showDescription}
loading={loading}
diff --git a/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.test.tsx b/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.test.tsx
index 262f2fc5099d..b814a5c994c4 100644
--- a/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.test.tsx
+++ b/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.test.tsx
@@ -40,6 +40,22 @@ describe('WidgetCardHeader', () => {
expect(screen.getByText('Last 7 days')).toBeInTheDocument()
})
+ it('renders an injected per-widget top heading in place of the default date range', () => {
+ render(
+ <WidgetCardHeader
+ layout="dashboard_tile"
+ title="Recent recordings"
+ widgetTypeLabel="Session replay"
+ config={{ dateRange: { date_from: '-14d' }, savedFilterId: 'abc123' }}
+ headerMeta={{ showWidgetType: true, showDateRange: true }}
+ TopHeading={({ widgetTypeLabel }) => <span>{widgetTypeLabel} • My saved filter</span>}
+ />
+ )
+
+ expect(screen.getByText('Session replay • My saved filter')).toBeInTheDocument()
+ expect(screen.queryByText('Last 14 days')).not.toBeInTheDocument()
+ })
+
it('derives date-only top heading when widget type is hidden', () => {
render(
<WidgetCardHeader
diff --git a/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.tsx b/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.tsx
index 8b3d946deb05..538c2cebb599 100644
--- a/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.tsx
+++ b/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.tsx
@@ -1,5 +1,5 @@
import clsx from 'clsx'
-import React from 'react'
+import React, { type ComponentType } from 'react'
import { CardMeta } from 'lib/components/Cards/CardMeta'
import { CardTopHeadingRow } from 'lib/components/Cards/CardTopHeadingRow'
@@ -13,6 +13,15 @@ import { DashboardPlacement } from '~/types'
import type { DashboardWidgetHeaderLayout, DashboardWidgetHeaderMeta } from '../../widget_types/catalog'
+/** Props a widget type's optional TopHeading override receives so it can compose its own
+ * CardTopHeadingRow — e.g. resolving a saved filter's name the generic header can't derive from config. */
+export type DashboardWidgetTopHeadingProps = {
+ config: Record<string, unknown>
+ widgetTypeLabel?: string
+ showWidgetType: boolean
+ dateText?: string | null
+}
+
export type WidgetCardHeaderProps = {
layout: DashboardWidgetHeaderLayout
title: string
@@ -23,6 +32,8 @@ export type WidgetCardHeaderProps = {
widgetTypeLabel?: string
config?: Record<string, unknown>
headerMeta?: DashboardWidgetHeaderMeta
+ /** Optional per-widget-type top heading row; falls back to the type + date range when absent. */
+ TopHeading?: ComponentType<DashboardWidgetTopHeadingProps>
description?: string
showDescription?: boolean
loading?: boolean
@@ -154,6 +165,7 @@ export function WidgetCardHeader({
widgetTypeLabel,
config,
headerMeta,
+ TopHeading,
description,
showDescription = true,
loading,
@@ -171,7 +183,19 @@ export function WidgetCardHeader({
: null
const derivedTopHeading =
widgetTypeLabel && (showWidgetType || dateText) ? (
- <CardTopHeadingRow typeLabel={widgetTypeLabel} showTypeLabel={showWidgetType} dateText={dateText} />
+ // A widget type can supply its own top heading row (e.g. session replay surfaces the active
+ // saved filter name in place of the now-overridden date range); otherwise fall back to the
+ // type + date range.
+ TopHeading ? (
+ <TopHeading
+ config={config ?? {}}
+ widgetTypeLabel={widgetTypeLabel}
+ showWidgetType={showWidgetType}
+ dateText={dateText}
+ />
+ ) : (
+ <CardTopHeadingRow typeLabel={widgetTypeLabel} showTypeLabel={showWidgetType} dateText={dateText} />
+ )
) : null
const resolvedTopHeading = topHeading !== undefined ? topHeading : derivedTopHeading
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index f78accf5db56..27d8bce1688d 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -560,6 +560,8 @@ export interface SessionReplayListWidgetConfigApi {
orderBy?: SessionReplayListWidgetConfigApiOrderBy
/** Sort direction for orderBy. */
orderDirection?: SessionReplayListWidgetConfigApiOrderDirection
+ /** short_id of a saved session replay filter to use as the recordings source. When set, the saved filter owns the date range and property filters; only orderBy, orderDirection, and limit still apply. */
+ savedFilterId?: string | null
}
export type DashboardWidgetConfigApi = ErrorTrackingListWidgetConfigApi | SessionReplayListWidgetConfigApi
diff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.ts
index df46e819150d..670c674cd4d9 100644
--- a/products/dashboards/frontend/generated/api.zod.ts
+++ b/products/dashboards/frontend/generated/api.zod.ts
@@ -483,6 +483,12 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoOrderDirectionDefault
)
.describe('Sort direction for orderBy.'),
+ savedFilterId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'short_id of a saved session replay filter to use as the recordings source. When set, the saved filter owns the date range and property filters; only orderBy, orderDirection, and limit still apply.'
+ ),
}),
])
.optional()
@@ -999,6 +1005,12 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod
dashboardsWidgetsBatchCreateBodyWidgetsItemTwoConfigOneOrderDirectionDefault
)
.describe('Sort direction for orderBy.'),
+ savedFilterId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'short_id of a saved session replay filter to use as the recordings source. When set, the saved filter owns the date range and property filters; only orderBy, orderDirection, and limit still apply.'
+ ),
})
.describe('Configuration for the recent recordings widget.'),
}),
diff --git a/products/dashboards/frontend/generated/widget-config-property-keys.json b/products/dashboards/frontend/generated/widget-config-property-keys.json
index 7b1f7c520805..2a7f4cffa143 100644
--- a/products/dashboards/frontend/generated/widget-config-property-keys.json
+++ b/products/dashboards/frontend/generated/widget-config-property-keys.json
@@ -16,6 +16,7 @@
"limit",
"orderBy",
"orderDirection",
+ "savedFilterId",
"widgetFilters"
]
},
@@ -182,6 +183,9 @@
},
"orderDirection": {
"$enum": ["ASC", "DESC"]
+ },
+ "savedFilterId": {
+ "$type": "string"
}
}
}
diff --git a/products/dashboards/frontend/generated/widget-config-schemas/sessionReplayListWidgetConfig.zod.ts b/products/dashboards/frontend/generated/widget-config-schemas/sessionReplayListWidgetConfig.zod.ts
index e5baf4fe4001..b880bed17d46 100644
--- a/products/dashboards/frontend/generated/widget-config-schemas/sessionReplayListWidgetConfig.zod.ts
+++ b/products/dashboards/frontend/generated/widget-config-schemas/sessionReplayListWidgetConfig.zod.ts
@@ -33,6 +33,12 @@ export const SessionReplayListWidgetConfig = /* @__PURE__ */ zod.object({
.enum(['ASC', 'DESC'])
.default(sessionReplayListWidgetConfigOrderDirectionDefault)
.describe('Sort direction for orderBy.'),
+ savedFilterId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'short_id of a saved session replay filter to use as the recordings source. When set, the saved filter owns the date range and property filters; only orderBy, orderDirection, and limit still apply.'
+ ),
})
export type SessionReplayListWidgetConfig = zod.input<typeof SessionReplayListWidgetConfig>
diff --git a/products/dashboards/frontend/widgets/registry.tsx b/products/dashboards/frontend/widgets/registry.tsx
index df0f7b81724b..450ab355a5dd 100644
--- a/products/dashboards/frontend/widgets/registry.tsx
+++ b/products/dashboards/frontend/widgets/registry.tsx
@@ -1,6 +1,7 @@
import posthog from 'posthog-js'
import type { ComponentType } from 'react'
+import type { DashboardWidgetTopHeadingProps } from '../components/WidgetCard/WidgetCardHeader'
import type { DashboardWidgetProductAccess } from '../types'
import { DASHBOARD_WIDGET_CATALOG, type DashboardWidgetCatalogKey } from '../widget_types/catalog'
import type { WidgetAvailabilityConfig } from '../widget_types/widgetAvailability'
@@ -20,7 +21,7 @@ import { ErrorTrackingWidget } from './error_tracking/ErrorTrackingWidget'
import { parseErrorTrackingWidgetConfigApiError } from './error_tracking/errorTrackingWidgetConfigValidation'
import { ErrorTrackingWidgetTileFilters } from './error_tracking/ErrorTrackingWidgetTileFilters'
import { EditSessionReplayWidgetModal } from './session_replay/EditSessionReplayWidgetModal'
-import { SessionReplayWidget } from './session_replay/SessionReplayWidget'
+import { SessionReplayWidget, SessionReplayWidgetTopHeading } from './session_replay/SessionReplayWidget'
import { parseSessionReplayWidgetConfigApiError } from './session_replay/sessionReplayWidgetConfigValidation'
import { SessionReplayWidgetTileFilters } from './session_replay/SessionReplayWidgetTileFilters'
@@ -75,6 +76,7 @@ export type DashboardWidgetDefinition = {
Component: ComponentType<DashboardWidgetComponentProps>
TileFilters?: ComponentType<DashboardWidgetTileFiltersProps>
EditModal?: ComponentType<DashboardWidgetEditModalProps>
+ TopHeading?: ComponentType<DashboardWidgetTopHeadingProps>
productAccess?: DashboardWidgetProductAccess
/** Maps dashboard PATCH API errors to edit-modal field errors for this widget type. */
parseConfigApiError: DashboardWidgetConfigApiErrorParser
@@ -134,6 +136,7 @@ export const DASHBOARD_WIDGET_REGISTRY = {
Component: SessionReplayWidget,
TileFilters: SessionReplayWidgetTileFilters,
EditModal: EditSessionReplayWidgetModal,
+ TopHeading: SessionReplayWidgetTopHeading,
productAccess: 'session_recording',
parseConfigApiError: parseSessionReplayWidgetConfigApiError,
},
diff --git a/products/dashboards/frontend/widgets/session_replay/EditSessionReplayWidgetModal.tsx b/products/dashboards/frontend/widgets/session_replay/EditSessionReplayWidgetModal.tsx
index 7219b92e51c4..6482f0243ff2 100644
--- a/products/dashboards/frontend/widgets/session_replay/EditSessionReplayWidgetModal.tsx
+++ b/products/dashboards/frontend/widgets/session_replay/EditSessionReplayWidgetModal.tsx
@@ -95,8 +95,8 @@ function EditSessionReplayWidgetModalContents(): JSX.Element {
setFilterTestAccounts={setFilterTestAccounts}
>
<p className="text-sm text-muted m-0 sm:col-span-2">
- Date range and property filters are on the tile filter bar (collapsible on the tile).
- Use this modal for test-account filtering, list size, and sort.
+ Date range, property filters, and saved filters are on the tile filter bar (collapsible
+ on the tile). Use this modal for test-account filtering, list size, and sort.
</p>
<LemonField.Pure
label="Number of recordings"
diff --git a/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.test.tsx b/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.test.tsx
index f85490986b28..303b4c95856b 100644
--- a/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.test.tsx
+++ b/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.test.tsx
@@ -64,5 +64,6 @@ describe('SessionReplayWidget', () => {
expect(container.querySelector('[data-attr="session-replay-widget-empty-state"]')).toBeInTheDocument()
expect(screen.getByText('No recordings yet')).toBeInTheDocument()
+ expect(screen.getByText('No session recordings matched your filters.')).toBeInTheDocument()
})
})
diff --git a/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.tsx b/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.tsx
index 00227a94f05c..cfb68313238e 100644
--- a/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.tsx
+++ b/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.tsx
@@ -1,5 +1,6 @@
-import { useActions } from 'kea'
+import { useActions, useValues } from 'kea'
+import { CardTopHeadingRow } from 'lib/components/Cards/CardTopHeadingRow'
import { FilmCameraHog } from 'lib/components/hedgehogs'
import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'
import 'scenes/session-recordings/playlist/SessionRecordingPreview.scss'
@@ -19,8 +20,10 @@ import {
WidgetListCount,
WIDGET_LIST_COUNT_RECORDINGS,
} from '../../components/WidgetCard'
+import type { DashboardWidgetTopHeadingProps } from '../../components/WidgetCard/WidgetCardHeader'
import type { DashboardWidgetComponentProps } from '../registry'
import { parseSessionReplayWidgetConfig } from './sessionReplayWidgetConfigValidation'
+import { sessionReplayWidgetSavedFiltersLogic } from './sessionReplayWidgetSavedFiltersLogic'
type SessionReplayWidgetResult = {
results?: SessionRecordingType[]
@@ -56,7 +59,8 @@ function SessionReplayWidgetRecordingRow({
export function SessionReplayWidget({ result, loading, config }: DashboardWidgetComponentProps): JSX.Element {
const payload = result as SessionReplayWidgetResult | null | undefined
const recordings = payload?.results ?? []
- const order = parseSessionReplayWidgetConfig(config).orderBy as RecordingsQuery['order']
+ const parsedConfig = parseSessionReplayWidgetConfig(config)
+ const order = parsedConfig.orderBy as RecordingsQuery['order']
if (loading) {
return (
@@ -80,9 +84,7 @@ export function SessionReplayWidget({ result, loading, config }: DashboardWidget
>
<FilmCameraHog className="size-20 shrink-0" />
<p className="m-0 text-base font-semibold text-primary">No recordings yet</p>
- <p className="m-0 text-sm text-muted">
- No session recordings matched your filters for this date range.
- </p>
+ <p className="m-0 text-sm text-muted">No session recordings matched your filters.</p>
</div>
</WidgetCardBodyMessage>
</WidgetCardContent>
@@ -111,3 +113,23 @@ export function SessionReplayWidget({ result, loading, config }: DashboardWidget
</>
)
}
+
+// A saved filter overrides the widget's date range, so the header shows the filter's name in its place.
+export function SessionReplayWidgetTopHeading({
+ config,
+ widgetTypeLabel,
+ showWidgetType,
+ dateText,
+}: DashboardWidgetTopHeadingProps): JSX.Element {
+ const rawSavedFilterId = config.savedFilterId
+ const savedFilterId = typeof rawSavedFilterId === 'string' && rawSavedFilterId.length > 0 ? rawSavedFilterId : null
+ const { savedFilterLabelById } = useValues(sessionReplayWidgetSavedFiltersLogic)
+
+ return (
+ <CardTopHeadingRow
+ typeLabel={widgetTypeLabel}
+ showTypeLabel={showWidgetType}
+ dateText={savedFilterId ? (savedFilterLabelById[savedFilterId] ?? 'Saved filter') : dateText}
+ />
+ )
+}
diff --git a/products/dashboards/frontend/widgets/session_replay/SessionReplayWidgetTileFilters.tsx b/products/dashboards/frontend/widgets/session_replay/SessionReplayWidgetTileFilters.tsx
index 850359ce816f..53c82578c576 100644
--- a/products/dashboards/frontend/widgets/session_replay/SessionReplayWidgetTileFilters.tsx
+++ b/products/dashboards/frontend/widgets/session_replay/SessionReplayWidgetTileFilters.tsx
@@ -2,8 +2,11 @@ import equal from 'fast-deep-equal'
import { useValues } from 'kea'
import { useMemo, useRef } from 'react'
+import { IconExternal } from '@posthog/icons'
+
import { quickFiltersLogic } from 'lib/components/QuickFilters/quickFiltersLogic'
import { LemonSelect } from 'lib/lemon-ui/LemonSelect'
+import { urls } from 'scenes/urls'
import { WIDGET_DATE_RANGE_SELECT_OPTIONS, type WidgetDateFromValue } from '../../widget_types/widgetConfigShared'
import type { DashboardWidgetTileFiltersProps } from '../registry'
@@ -15,12 +18,16 @@ import {
WidgetTileFiltersBar,
} from '../widgetTileFiltersReadOnly'
import {
- patchSessionReplayWidgetFilterFields,
parseSessionReplayWidgetConfig,
+ patchSessionReplayWidgetFilterFields,
} from './sessionReplayWidgetConfigValidation'
+import { sessionReplayWidgetSavedFiltersLogic } from './sessionReplayWidgetSavedFiltersLogic'
export type SessionReplayWidgetTileFiltersProps = DashboardWidgetTileFiltersProps
+const NO_SAVED_FILTER_OPTION = { value: null as string | null, label: 'No saved filter' }
+const CREATE_SAVED_FILTER_VALUE = '__create_saved_filter__'
+
export function SessionReplayWidgetTileFilters({
config,
onUpdateConfig,
@@ -30,15 +37,35 @@ export function SessionReplayWidgetTileFilters({
const parsed = parseSessionReplayWidgetConfig(config)
const dateFrom = (parsed.dateRange?.date_from ?? '-7d') as WidgetDateFromValue
const widgetFilters = parsed.widgetFilters ?? {}
+ const savedFilterId = parsed.savedFilterId ?? null
+ const hasSavedFilter = !!savedFilterId
const { quickFilters: projectFilterDefinitions } = useValues(
quickFiltersLogic({ context: filterDefinitionsContext })
)
+ const { savedFilterOptions, savedFiltersLoading, savedFilterLabelById } = useValues(
+ sessionReplayWidgetSavedFiltersLogic
+ )
const filterDefinitions = useMemo(
() => projectFilterDefinitions.filter(isAllowed),
[projectFilterDefinitions, isAllowed]
)
+ const savedFilterSelectOptions = useMemo(
+ () => [
+ NO_SAVED_FILTER_OPTION,
+ ...savedFilterOptions,
+ // Always offer a shortcut to create a new saved filter in session replay.
+ {
+ value: CREATE_SAVED_FILTER_VALUE,
+ label: 'Create a saved filter',
+ sideIcon: <IconExternal className="size-3.5" />,
+ },
+ ],
+ [savedFilterOptions]
+ )
+ const savedFilterLabel = savedFilterId ? (savedFilterLabelById[savedFilterId] ?? savedFilterId) : savedFilterId
+
const configRef = useRef(config)
configRef.current = config
const { persistConfigDebounced, persistConfigNow } = useWidgetTileConfigPersist(onUpdateConfig)
@@ -52,6 +79,17 @@ export function SessionReplayWidgetTileFilters({
await persistConfigNow(nextConfig)
}
+ const applySavedFilter = async (value: string | null): Promise<void> => {
+ // The "create" item is a navigation shortcut, not a persisted value.
+ if (value === CREATE_SAVED_FILTER_VALUE) {
+ window.open(urls.replay(), '_blank', 'noopener,noreferrer')
+ return
+ }
+ const nextConfig = patchSessionReplayWidgetFilterFields(configRef.current, { savedFilterId: value })
+ configRef.current = nextConfig
+ await persistConfigNow(nextConfig)
+ }
+
const applyWidgetFilters = (nextWidgetFilters: typeof widgetFilters): void => {
const nextConfig = patchSessionReplayWidgetFilterFields(configRef.current, { widgetFilters: nextWidgetFilters })
const current = parseSessionReplayWidgetConfig(configRef.current)
@@ -65,13 +103,19 @@ export function SessionReplayWidgetTileFilters({
if (!onUpdateConfig) {
return (
<WidgetTileFiltersBar dataAttr="session-replay-widget-tile-filters-readonly">
- <WidgetDateRangeReadOnlyValue dateFrom={dateFrom} />
- {filterDefinitions.length > 0 ? (
- <WidgetPropertyFiltersReadOnlyValues
- filterDefinitions={filterDefinitions}
- widgetFilters={widgetFilters}
- />
- ) : null}
+ {hasSavedFilter ? (
+ <span className="text-sm text-muted">Saved filter: {savedFilterLabel}</span>
+ ) : (
+ <>
+ <WidgetDateRangeReadOnlyValue dateFrom={dateFrom} />
+ {filterDefinitions.length > 0 ? (
+ <WidgetPropertyFiltersReadOnlyValues
+ filterDefinitions={filterDefinitions}
+ widgetFilters={widgetFilters}
+ />
+ ) : null}
+ </>
+ )}
</WidgetTileFiltersBar>
)
}
@@ -80,22 +124,36 @@ export function SessionReplayWidgetTileFilters({
<WidgetTileFiltersBar dataAttr="session-replay-widget-tile-filters">
<LemonSelect
size="small"
- value={dateFrom}
+ value={savedFilterId}
disabled={!canUpdate}
disabledReason={controlDisabledReason}
- options={WIDGET_DATE_RANGE_SELECT_OPTIONS}
- onChange={(value) => {
- if (value) {
- void applyDateFrom(value)
- }
- }}
+ loading={savedFiltersLoading}
+ options={savedFilterSelectOptions}
+ placeholder="Saved filter"
+ onChange={(value) => void applySavedFilter(value ?? null)}
/>
- {filterDefinitions.length > 0 ? (
- <WidgetPropertyFiltersSection
- filterDefinitions={filterDefinitions}
- widgetFilters={widgetFilters}
- onWidgetFiltersChange={applyWidgetFilters}
- />
+ {!hasSavedFilter ? (
+ <>
+ <LemonSelect
+ size="small"
+ value={dateFrom}
+ disabled={!canUpdate}
+ disabledReason={controlDisabledReason}
+ options={WIDGET_DATE_RANGE_SELECT_OPTIONS}
+ onChange={(value) => {
+ if (value) {
+ void applyDateFrom(value)
+ }
+ }}
+ />
+ {filterDefinitions.length > 0 ? (
+ <WidgetPropertyFiltersSection
+ filterDefinitions={filterDefinitions}
+ widgetFilters={widgetFilters}
+ onWidgetFiltersChange={applyWidgetFilters}
+ />
+ ) : null}
+ </>
) : null}
</WidgetTileFiltersBar>
)
diff --git a/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetConfigValidation.test.ts b/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetConfigValidation.test.ts
index 1cdd58ce39b5..f39a345eac08 100644
--- a/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetConfigValidation.test.ts
+++ b/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetConfigValidation.test.ts
@@ -99,6 +99,20 @@ describe('patchSessionReplayWidgetFilterFields', () => {
expect(next.dateRange).toEqual({ date_from: '-30d' })
expect(next.widgetFilters?.['qf-1']).toMatchObject({ value: 'Chrome' })
})
+
+ it('sets and clears the saved filter without dropping other tile filters', () => {
+ const config = sessionReplayWidgetConfigSchema.parse({ dateRange: { date_from: '-7d' } })
+
+ const withSavedFilter = patchSessionReplayWidgetFilterFields(config, { savedFilterId: 'abc123' })
+ expect(withSavedFilter.savedFilterId).toBe('abc123')
+
+ const dateChanged = patchSessionReplayWidgetFilterFields(withSavedFilter, { dateFrom: '-30d' })
+ expect(dateChanged.savedFilterId).toBe('abc123')
+
+ const cleared = patchSessionReplayWidgetFilterFields(dateChanged, { savedFilterId: null })
+ expect(cleared.savedFilterId).toBeNull()
+ expect(cleared.dateRange).toEqual({ date_from: '-30d' })
+ })
})
describe('parseSessionReplayWidgetConfigApiError', () => {
diff --git a/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetConfigValidation.ts b/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetConfigValidation.ts
index 36e96e46938d..1e2465180acc 100644
--- a/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetConfigValidation.ts
+++ b/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetConfigValidation.ts
@@ -34,14 +34,17 @@ export function patchSessionReplayWidgetFilterFields(
patch: {
dateFrom?: WidgetDateFromValue
widgetFilters?: Record<string, StoredWidgetFilter>
+ savedFilterId?: string | null
}
): SessionReplayWidgetConfig {
const base = parseSessionReplayWidgetConfig(config)
+ const savedFilterId = patch.savedFilterId !== undefined ? patch.savedFilterId : (base.savedFilterId ?? null)
return sessionReplayWidgetConfigSchema.parse({
...base,
dateRange: { date_from: patch.dateFrom ?? base.dateRange?.date_from ?? '-7d' },
widgetFilters: patch.widgetFilters ?? base.widgetFilters ?? {},
+ savedFilterId,
})
}
diff --git a/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetSavedFiltersLogic.ts b/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetSavedFiltersLogic.ts
new file mode 100644
index 000000000000..c3f6ab8b6fb0
--- /dev/null
+++ b/products/dashboards/frontend/widgets/session_replay/sessionReplayWidgetSavedFiltersLogic.ts
@@ -0,0 +1,45 @@
+import { afterMount, kea, path, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+import { toParams } from 'lib/utils'
+
+import type { SessionRecordingPlaylistType } from '~/types'
+
+import type { sessionReplayWidgetSavedFiltersLogicType } from './sessionReplayWidgetSavedFiltersLogicType'
+
+// Saved session replay filters are SessionRecordingPlaylist rows with type "filters".
+export const sessionReplayWidgetSavedFiltersLogic = kea<sessionReplayWidgetSavedFiltersLogicType>([
+ path(['products', 'dashboards', 'widgets', 'session_replay', 'sessionReplayWidgetSavedFiltersLogic']),
+ loaders({
+ savedFilters: {
+ __default: [] as SessionRecordingPlaylistType[],
+ loadSavedFilters: async () => {
+ const response = await api.recordings.listPlaylists(
+ toParams({ limit: 100, order: '-last_modified_at', type: 'filters' })
+ )
+ return response.results
+ },
+ },
+ }),
+ selectors({
+ savedFilterOptions: [
+ (s) => [s.savedFilters],
+ (savedFilters): { value: string; label: string }[] =>
+ savedFilters.map((filter) => ({
+ value: filter.short_id,
+ label: filter.name || filter.derived_name || 'Unnamed filter',
+ })),
+ ],
+ // Single source for resolving a saved-filter short_id to its display label, shared by the
+ // tile filter bar and the card header top heading.
+ savedFilterLabelById: [
+ (s) => [s.savedFilterOptions],
+ (savedFilterOptions): Record<string, string> =>
+ Object.fromEntries(savedFilterOptions.map((option) => [option.value, option.label])),
+ ],
+ }),
+ afterMount(({ actions }) => {
+ actions.loadSavedFilters()
+ }),
+])
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 059cfb674199..c776b076b922 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -4008,6 +4008,8 @@ export namespace Schemas {
orderBy?: SessionReplayListWidgetConfigOrderBy;
/** Sort direction for orderBy. */
orderDirection?: SessionReplayListWidgetConfigOrderDirection;
+ /** short_id of a saved session replay filter to use as the recordings source. When set, the saved filter owns the date range and property filters; only orderBy, orderDirection, and limit still apply. */
+ savedFilterId?: string | null;
}
export interface SessionReplayListWidgetAddRequestOpenApi {
diff --git a/services/mcp/src/generated/dashboards/api.ts b/services/mcp/src/generated/dashboards/api.ts
index 9994d7741b3c..6c350008b373 100644
--- a/services/mcp/src/generated/dashboards/api.ts
+++ b/services/mcp/src/generated/dashboards/api.ts
@@ -385,6 +385,12 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod
dashboardsPartialUpdateBodyTilesItemWidgetOneConfigOneTwoOrderDirectionDefault
)
.describe('Sort direction for orderBy.'),
+ savedFilterId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'short_id of a saved session replay filter to use as the recordings source. When set, the saved filter owns the date range and property filters; only orderBy, orderDirection, and limit still apply.'
+ ),
}),
])
.optional()
@@ -1053,6 +1059,12 @@ export const DashboardsWidgetsBatchCreateBody = /* @__PURE__ */ zod
dashboardsWidgetsBatchCreateBodyWidgetsItemTwoConfigOneOrderDirectionDefault
)
.describe('Sort direction for orderBy.'),
+ savedFilterId: zod
+ .union([zod.string(), zod.null()])
+ .optional()
+ .describe(
+ 'short_id of a saved session replay filter to use as the recordings source. When set, the saved filter owns the date range and property filters; only orderBy, orderDirection, and limit still apply.'
+ ),
})
.describe('Configuration for the recent recordings widget.'),
}),
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json
index 93d3edc31aa1..355c8146d404 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-update.json
@@ -351,6 +351,17 @@
"enum": ["ASC", "DESC"],
"type": "string"
},
+ "savedFilterId": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "short_id of a saved session replay filter to use as the recordings source. When set, the saved filter owns the date range and property filters; only orderBy, orderDirection, and limit still apply."
+ },
"widgetFilters": {
"anyOf": [
{
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.json
index aabb46032005..d0f296679532 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-widgets-batch-add.json
@@ -354,6 +354,17 @@
"enum": ["ASC", "DESC"],
"type": "string"
},
+ "savedFilterId": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "short_id of a saved session replay filter to use as the recordings source. When set, the saved filter owns the date range and property filters; only orderBy, orderDirection, and limit still apply."
+ },
"widgetFilters": {
"anyOf": [
{