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): highlight matching events in session replay widget (#65537)

Matt Pua70d465147510
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index ad040aa865bf..b6bd85fbe1fc 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -51,7 +51,6 @@ from posthog.schema import (
MatchingEventsResponse,
ProductIntentContext,
ProductKey,
- PropertyFilterType,
PropertyOperator,
QueryTiming,
RecordingPropertyFilter,
@@ -109,6 +108,7 @@ from posthog.session_recordings.utils import (
filter_from_params_to_query,
gate_surfacing_score_order,
query_as_params_to_dict,
+ recordings_query_has_event_filters,
)
from posthog.settings.session_replay import SESSION_REPLAY_AI_REGEX_MODEL
from posthog.temporal.common.client import async_connect
@@ -950,11 +950,7 @@ class SessionRecordingViewSet(
"Must specify exactly one session_id",
)
- has_event_properties = any(
- getattr(p, "type", None) == PropertyFilterType.EVENT for p in (query.properties or [])
- )
-
- if not query.events and not query.actions and not has_event_properties:
+ if not recordings_query_has_event_filters(query):
raise exceptions.ValidationError(
"Must specify at least one event or action filter, or event properties filter",
)
diff --git a/posthog/session_recordings/utils.py b/posthog/session_recordings/utils.py
index 79116ec966c8..06047717a78c 100644
--- a/posthog/session_recordings/utils.py
+++ b/posthog/session_recordings/utils.py
@@ -5,7 +5,7 @@ import posthoganalytics
from pydantic import ValidationError
from rest_framework import exceptions
-from posthog.schema import RecordingOrder, RecordingsQuery
+from posthog.schema import PropertyFilterType, RecordingOrder, RecordingsQuery
if TYPE_CHECKING:
from posthog.models import User
@@ -13,6 +13,16 @@ if TYPE_CHECKING:
SURFACING_SCORE_ORDER_FLAG = "replay-playlist-surfacing-score"
+def recordings_query_has_event_filters(query: RecordingsQuery) -> bool:
+ """Whether a query carries something the matching_events endpoint can highlight: an event filter,
+ an action filter, or an event-property filter. The endpoint rejects queries without one, so both
+ the endpoint's own precondition and any caller that decides whether to hit it share this check."""
+ has_event_properties = any(
+ getattr(prop, "type", None) == PropertyFilterType.EVENT for prop in (query.properties or [])
+ )
+ return bool(query.events) or bool(query.actions) or has_event_properties
+
+
def gate_surfacing_score_order(query: RecordingsQuery, user: "User | None") -> None:
"""`surfacing_score` ordering is gated behind a feature flag. It's exposed to clients via the
generated RecordingOrder enum (both the REST list endpoint and the MCP query), so the gate has to
diff --git a/products/dashboards/backend/api/test/test_run_widgets.py b/products/dashboards/backend/api/test/test_run_widgets.py
index 9d7d0444dbff..17a5bc723d7b 100644
--- a/products/dashboards/backend/api/test/test_run_widgets.py
+++ b/products/dashboards/backend/api/test/test_run_widgets.py
@@ -584,6 +584,64 @@ class TestDashboardRunWidgets(APIBaseTest):
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_attaches_matching_events_query_for_widget_filters(
+ self, mock_list_recordings: MagicMock
+ ) -> None:
+ mock_list_recordings.return_value = ([], False, None, None)
+
+ result = run_session_replay_list_widget(
+ self.team,
+ {"limit": 5, "dateRange": {"date_from": "-7d"}, "widgetFilters": self._widget_browser_filter("Chrome")},
+ user=self.user,
+ )
+
+ matching_events_query = result["matchingEventsQuery"]
+ assert matching_events_query["kind"] == "RecordingsQuery"
+ # session_ids are supplied per recording by the client, not baked into the shipped query.
+ assert "session_ids" not in matching_events_query
+ assert matching_events_query["properties"][0]["type"] == "event"
+ assert matching_events_query["properties"][0]["key"] == "$browser"
+ assert matching_events_query["properties"][0]["value"] == ["Chrome"]
+
+ @patch("posthog.session_recordings.session_recording_api.list_recordings_from_query")
+ def test_session_replay_widget_attaches_matching_events_query_for_saved_filter_with_events(
+ self, mock_list_recordings: MagicMock
+ ) -> None:
+ mock_list_recordings.return_value = ([], False, None, None)
+ saved_filter = SessionRecordingPlaylist.objects.create(
+ team=self.team,
+ name="Pageview filter",
+ type="filters",
+ filters={"events": [{"id": "$pageview", "type": "events", "order": 0, "name": "$pageview"}]},
+ )
+
+ result = run_session_replay_list_widget(
+ self.team,
+ {"limit": 5, "savedFilterId": saved_filter.short_id},
+ user=self.user,
+ )
+
+ matching_events_query = result["matchingEventsQuery"]
+ assert matching_events_query["events"][0]["id"] == "$pageview"
+ # Same invariant as the widget-filter path: session_ids are supplied per recording by the client.
+ assert "session_ids" not in matching_events_query
+
+ @patch("posthog.session_recordings.session_recording_api.list_recordings_from_query")
+ def test_session_replay_widget_omits_matching_events_query_without_event_filters(
+ self, mock_list_recordings: MagicMock
+ ) -> None:
+ mock_list_recordings.return_value = ([], False, None, None)
+
+ result = run_session_replay_list_widget(
+ self.team,
+ {"limit": 5, "dateRange": {"date_from": "-7d"}},
+ user=self.user,
+ )
+
+ # Nothing to highlight without an event/action/event-property filter, so the query is omitted.
+ assert "matchingEventsQuery" not in result
+
@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
diff --git a/products/dashboards/backend/widgets/session_replay_list.py b/products/dashboards/backend/widgets/session_replay_list.py
index de7259d4b5d1..875d9b078b88 100644
--- a/products/dashboards/backend/widgets/session_replay_list.py
+++ b/products/dashboards/backend/widgets/session_replay_list.py
@@ -11,7 +11,7 @@ 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
+from posthog.session_recordings.utils import filter_from_params_to_query, recordings_query_has_event_filters
from products.dashboards.backend.constants import MAX_WIDGET_RESULT_LIMIT
from products.dashboards.backend.widget_specs.configs import SESSION_REPLAY_LIST_WIDGET_TYPE
@@ -86,6 +86,20 @@ def _build_recordings_query(team: Team, config: ValidatedSessionReplayListWidget
return filter_from_params_to_query(params)
+def _build_matching_events_query(query: RecordingsQuery) -> dict[str, Any] | None:
+ # The player highlights the events that matched the same filters the list was built from. We ship
+ # the query the backend just resolved (saved-filter playlist included), so the client never has to
+ # reconstruct it; it only adds the session id per row. The matching_events endpoint requires at
+ # least one event/action/event-property filter, so omit the query when there's nothing to match.
+ if not recordings_query_has_event_filters(query):
+ return None
+
+ payload = query.model_dump(mode="json", exclude_none=True)
+ # The client sets session_ids per recording when opening the player.
+ payload.pop("session_ids", None)
+ return payload
+
+
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(
@@ -117,10 +131,16 @@ def run_session_replay_list_widget(
has_more=bool(data.get("has_next")),
)
- return run_list_widget(
+ result = run_list_widget(
limit=typed_config["limit"],
count_cap=MAX_WIDGET_RESULT_LIMIT,
include_total_count=include_total_count,
fetch_page=fetch_page,
log_key="session_replay_widget_total_count_failed",
)
+
+ matching_events_query = _build_matching_events_query(query)
+ if matching_events_query is not None:
+ result["matchingEventsQuery"] = matching_events_query
+
+ return result
diff --git a/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.test.tsx b/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.test.tsx
index 303b4c95856b..f9bb0578c652 100644
--- a/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.test.tsx
+++ b/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.test.tsx
@@ -2,8 +2,11 @@ import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
import '@testing-library/jest-dom'
-import { render, screen, cleanup } from '@testing-library/react'
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import posthog from 'posthog-js'
+import api from 'lib/api'
+import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'
import { teamLogic } from 'scenes/teamLogic'
import { initKeaTests } from '~/test/init'
@@ -66,4 +69,104 @@ describe('SessionReplayWidget', () => {
expect(screen.getByText('No recordings yet')).toBeInTheDocument()
expect(screen.getByText('No session recordings matched your filters.')).toBeInTheDocument()
})
+
+ const matchingEventsQuery = {
+ kind: 'RecordingsQuery',
+ properties: [{ type: 'event', key: '$current_url', operator: 'icontains', value: ['pricing'] }],
+ date_from: '-7d',
+ filter_test_accounts: true,
+ }
+
+ it('opens the player without highlights when the result carries no matching events query', async () => {
+ const getMatchingEvents = jest.spyOn(api.recordings, 'getMatchingEvents')
+ sessionPlayerModalLogic.mount()
+
+ render(
+ <SessionReplayWidget tileId={1} config={{ limit: 10 }} loading={false} result={{ results: [recording] }} />
+ )
+
+ fireEvent.click(screen.getByText('recording-1'))
+
+ await waitFor(() =>
+ expect(sessionPlayerModalLogic.values.activeSessionRecording).toEqual({ id: 'recording-1' })
+ )
+ expect(getMatchingEvents).not.toHaveBeenCalled()
+ })
+
+ it('fetches matching events for the clicked session and opens the player with highlights', async () => {
+ const events = [{ uuid: 'event-1', timestamp: '2026-05-26T08:00:30.000Z' }]
+ const getMatchingEvents = jest.spyOn(api.recordings, 'getMatchingEvents').mockResolvedValue({ results: events })
+ sessionPlayerModalLogic.mount()
+
+ render(
+ <SessionReplayWidget
+ tileId={1}
+ config={{ limit: 10 }}
+ loading={false}
+ result={{ results: [recording], matchingEventsQuery }}
+ />
+ )
+
+ fireEvent.click(screen.getByText('recording-1'))
+
+ await waitFor(() => expect(getMatchingEvents).toHaveBeenCalledTimes(1))
+ // The clicked session id is layered onto the query the backend supplied.
+ expect(getMatchingEvents.mock.calls[0][0]).toContain('session_ids')
+ expect(getMatchingEvents.mock.calls[0][0]).toContain('recording-1')
+ expect(sessionPlayerModalLogic.values.activeSessionRecording).toEqual({
+ id: 'recording-1',
+ matching_events: [{ session_id: 'recording-1', events }],
+ })
+ })
+
+ it('falls back to opening without highlights and captures the error when the fetch fails', async () => {
+ const error = new Error('boom')
+ jest.spyOn(api.recordings, 'getMatchingEvents').mockRejectedValue(error)
+ const captureException = jest.spyOn(posthog, 'captureException').mockImplementation(() => undefined as any)
+ sessionPlayerModalLogic.mount()
+
+ render(
+ <SessionReplayWidget
+ tileId={1}
+ config={{ limit: 10 }}
+ loading={false}
+ result={{ results: [recording], matchingEventsQuery }}
+ />
+ )
+
+ fireEvent.click(screen.getByText('recording-1'))
+
+ await waitFor(() =>
+ expect(sessionPlayerModalLogic.values.activeSessionRecording).toEqual({ id: 'recording-1' })
+ )
+ // A broken query must not degrade silently.
+ expect(captureException).toHaveBeenCalledWith(error, expect.objectContaining({ feature: expect.any(String) }))
+ })
+
+ it('shows a loading affordance on the row while matching events are being fetched', async () => {
+ let resolveFetch: (value: { results: { uuid: string; timestamp: string }[] }) => void = () => {}
+ jest.spyOn(api.recordings, 'getMatchingEvents').mockReturnValue(
+ new Promise((resolve) => {
+ resolveFetch = resolve
+ })
+ )
+ sessionPlayerModalLogic.mount()
+
+ const { container } = render(
+ <SessionReplayWidget
+ tileId={1}
+ config={{ limit: 10 }}
+ loading={false}
+ result={{ results: [recording], matchingEventsQuery }}
+ />
+ )
+
+ fireEvent.click(screen.getByText('recording-1'))
+
+ await waitFor(() => expect(container.querySelector('[aria-busy="true"]')).toBeInTheDocument())
+
+ resolveFetch({ results: [] })
+
+ await waitFor(() => expect(container.querySelector('[aria-busy="true"]')).not.toBeInTheDocument())
+ })
})
diff --git a/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.tsx b/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.tsx
index cfb68313238e..c9b69e2b5da7 100644
--- a/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.tsx
+++ b/products/dashboards/frontend/widgets/session_replay/SessionReplayWidget.tsx
@@ -1,7 +1,13 @@
+import clsx from 'clsx'
import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
+import { useRef, useState } from 'react'
+import api from 'lib/api'
import { CardTopHeadingRow } from 'lib/components/Cards/CardTopHeadingRow'
import { FilmCameraHog } from 'lib/components/hedgehogs'
+import { Spinner } from 'lib/lemon-ui/Spinner'
+import { toParams } from 'lib/utils/url'
import { sessionPlayerModalLogic } from 'scenes/session-recordings/player/modal/sessionPlayerModalLogic'
import 'scenes/session-recordings/playlist/SessionRecordingPreview.scss'
import {
@@ -31,27 +37,74 @@ type SessionReplayWidgetResult = {
limit?: number
totalCount?: number
totalCountCapped?: boolean
+ /**
+ * Filters the backend used to build this list (saved filter resolved server-side), so the player
+ * can highlight the matching events. Absent when nothing can match. The client adds session_ids.
+ */
+ matchingEventsQuery?: RecordingsQuery
}
function SessionReplayWidgetRecordingRow({
recording,
order,
+ matchingEventsQuery,
}: {
recording: SessionRecordingType
order: RecordingsQuery['order']
+ /** Base query (filters minus session id) used to fetch the events to highlight, or null when nothing can match. */
+ matchingEventsQuery: RecordingsQuery | null
}): JSX.Element {
const { openSessionPlayer } = useActions(sessionPlayerModalLogic)
const { reportRecordingOpenedFromRecentRecordingList } = useActions(sessionRecordingEventUsageLogic)
+ const [isOpening, setIsOpening] = useState(false)
+ // Ref guard, not the state value: state updates aren't visible to a second click that fires
+ // before the next render, so two rapid clicks would otherwise both pass the guard.
+ const isOpeningRef = useRef(false)
+
+ const openRecording = async (): Promise<void> => {
+ if (isOpeningRef.current) {
+ return
+ }
+ reportRecordingOpenedFromRecentRecordingList()
+
+ // No event/property filters means there's nothing to highlight — open straight away.
+ if (!matchingEventsQuery) {
+ openSessionPlayer({ id: recording.id })
+ return
+ }
+
+ isOpeningRef.current = true
+ setIsOpening(true)
+ try {
+ const query: RecordingsQuery = { ...matchingEventsQuery, session_ids: [recording.id] }
+ const response = await api.recordings.getMatchingEvents(toParams(query))
+ openSessionPlayer({
+ id: recording.id,
+ matching_events: [{ session_id: recording.id, events: response.results }],
+ })
+ } catch (error) {
+ // Highlighting matching events is best-effort; fall back to opening without it, but
+ // surface the failure so a systematically broken query doesn't degrade silently.
+ posthog.captureException(error, { feature: 'session-replay-widget-matching-events' })
+ openSessionPlayer({ id: recording.id })
+ } finally {
+ isOpeningRef.current = false
+ setIsOpening(false)
+ }
+ }
return (
<div
- className="border-b"
- onClick={() => {
- openSessionPlayer({ id: recording.id })
- reportRecordingOpenedFromRecentRecordingList()
- }}
+ className={clsx('relative border-b', isOpening && 'pointer-events-none opacity-60')}
+ onClick={() => void openRecording()}
+ aria-busy={isOpening}
>
<SessionRecordingPreview recording={recording} order={order} />
+ {isOpening && (
+ <div className="absolute inset-y-0 right-2 flex items-center">
+ <Spinner />
+ </div>
+ )}
</div>
)
}
@@ -61,6 +114,7 @@ export function SessionReplayWidget({ result, loading, config }: DashboardWidget
const recordings = payload?.results ?? []
const parsedConfig = parseSessionReplayWidgetConfig(config)
const order = parsedConfig.orderBy as RecordingsQuery['order']
+ const matchingEventsQuery = payload?.matchingEventsQuery ?? null
if (loading) {
return (
@@ -96,7 +150,12 @@ export function SessionReplayWidget({ result, loading, config }: DashboardWidget
<WidgetCardContent>
<div className="flex flex-col">
{recordings.map((recording) => (
- <SessionReplayWidgetRecordingRow key={recording.id} recording={recording} order={order} />
+ <SessionReplayWidgetRecordingRow
+ key={recording.id}
+ recording={recording}
+ order={order}
+ matchingEventsQuery={matchingEventsQuery}
+ />
))}
</div>
</WidgetCardContent>