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.

fix(experiments): report recording opens the playlist selects implicitly (#82257)

Marcel Poelker6bd62ea84352
diff --git a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
index 1e2038c1808f..2e23f59a4c34 100644
--- a/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
+++ b/frontend/src/scenes/experiments/ExperimentView/experimentReplayTabLogic.test.ts
@@ -808,6 +808,56 @@ describe('experimentReplayTabLogic', () => {
expect(logic.values.recordingsFilters.session_ids).toEqual([])
})
+ it('reports a bucket load once it is the one the list shows', async () => {
+ // The bucket events have never fired in production — every open so far used the default
+ // mode, which never asks the endpoint. This pins that the wiring works when one does.
+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)
+ const bucketLoads = (): any[] =>
+ captureSpy.mock.calls.filter(([event]) => event === 'experiment recordings bucket loaded')
+
+ await expectLogic(logic, () => {
+ logic.actions.setMetricSelected('metric-funnel', true)
+ logic.actions.setMetricFilterMode('fired_any')
+ }).toFinishAllListeners()
+
+ expect(bucketLoads()).toHaveLength(1)
+ expect(bucketLoads()[0][1]).toEqual({
+ experiment_id: 42,
+ bucket: 'fired_any',
+ metric_count: 1,
+ session_count: 2,
+ truncated: false,
+ considered_metric_count: 1,
+ excluded_metric_count: 0,
+ duration_ms: expect.any(Number),
+ })
+ })
+
+ it('reports a bucket failure with what the endpoint said', async () => {
+ const captureSpy = jest.spyOn(posthog, 'capture').mockReturnValue(undefined as any)
+ const bucketEvents = (): any[] =>
+ captureSpy.mock.calls.filter(([event]) => (event as string).startsWith('experiment recordings bucket'))
+ ;(experimentsSessionBucketsCreate as jest.Mock).mockRejectedValue(
+ Object.assign(new Error('boom'), { detail: 'Pick exactly one funnel metric' })
+ )
+
+ await expectLogic(logic, () => {
+ logic.actions.setMetricSelected('metric-funnel', true)
+ logic.actions.setMetricFilterMode('fired_any')
+ }).toFinishAllListeners()
+
+ expect(bucketEvents()).toHaveLength(1)
+ expect(bucketEvents()[0][0]).toBe('experiment recordings bucket failed')
+ // The endpoint's detail names what to fix; the generic message would hide it from us.
+ expect(bucketEvents()[0][1]).toEqual({
+ experiment_id: 42,
+ bucket: 'fired_any',
+ metric_count: 1,
+ duration_ms: expect.any(Number),
+ error: 'Pick exactly one funnel metric',
+ })
+ })
+
it('keeps a picked mode that has nothing to filter on yet', async () => {
// The tab pushes no session_ids until an eligible metric is picked, and the playlist echoes
// that back through onFiltersChange. Reading it as the user clearing the bucket bounced the
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
index a50be6aa3eae..439f42507a38 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
@@ -1011,6 +1011,121 @@ describe('sessionRecordingsPlaylistLogic', () => {
})
})
+ describe('onRecordingSelected', () => {
+ // Under autoPlay the player also picks recordings with no explicit selection — it shows
+ // whatever is at the top of the list, and follows it across reloads. Embedding surfaces
+ // count opens off this callback, so those implicit moves must be reported too, exactly
+ // once each (the experiment recordings tab under-reported opens without this).
+ let onRecordingSelected: jest.Mock
+
+ beforeEach(() => {
+ onRecordingSelected = jest.fn()
+ })
+
+ afterEach(() => {
+ jest.restoreAllMocks()
+ })
+
+ it('reports the autoplayed top recording on load, and again only when a reload changes it', async () => {
+ logic = sessionRecordingsPlaylistLogic({
+ logicKey: 'selection-reporting',
+ autoPlay: true,
+ onRecordingSelected,
+ })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])
+ expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id]])
+
+ // A reload that keeps the same recording on top doesn't move the player, so it must
+ // not be reported as another open.
+ const listSpy = jest
+ .spyOn(api.recordings, 'list')
+ .mockResolvedValueOnce({ results: listOfSessionRecordings, has_next: false } as Awaited<
+ ReturnType<typeof api.recordings.list>
+ >)
+ logic.actions.loadSessionRecordings()
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])
+ expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id]])
+
+ // A reload that changes the top (the way an embedding surface's filter change does,
+ // with nothing explicitly selected) moves the player to the new top recording.
+ const newestRecording = {
+ ...aRecording,
+ id: 'newest',
+ start_time: '2023-12-12T16:55:36.404000Z',
+ end_time: '2023-12-12T16:55:46.404000Z',
+ }
+ listSpy.mockResolvedValueOnce({ results: [newestRecording], has_next: false } as Awaited<
+ ReturnType<typeof api.recordings.list>
+ >)
+ logic.actions.loadSessionRecordings()
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])
+ expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id], ['newest']])
+ })
+
+ it('skips re-selecting the recording already shown, but reports every move — including back', async () => {
+ logic = sessionRecordingsPlaylistLogic({
+ logicKey: 'selection-reporting-dedupe',
+ autoPlay: true,
+ onRecordingSelected,
+ })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])
+ expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id]])
+
+ // Clicking the recording the autoplay fallback is already showing opens nothing new.
+ logic.actions.setSelectedRecordingId(aRecording.id)
+ expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id]])
+
+ logic.actions.setSelectedRecordingId(bRecording.id)
+ logic.actions.setSelectedRecordingId(aRecording.id)
+ expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id], [bRecording.id], [aRecording.id]])
+ })
+
+ it('re-reports a recording that returns after a reload matched nothing', async () => {
+ logic = sessionRecordingsPlaylistLogic({
+ logicKey: 'selection-reporting-empty-gap',
+ autoPlay: true,
+ onRecordingSelected,
+ })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])
+ expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id]])
+
+ // A facet can match nothing: the player unloads into the empty state. When the next
+ // reload brings the same recording back, it autoplays afresh — a new open, not a
+ // re-select of something still on screen.
+ const listSpy = jest
+ .spyOn(api.recordings, 'list')
+ .mockResolvedValueOnce({ results: [], has_next: false } as Awaited<
+ ReturnType<typeof api.recordings.list>
+ >)
+ logic.actions.loadSessionRecordings()
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])
+ expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id]])
+
+ listSpy.mockResolvedValueOnce({ results: listOfSessionRecordings, has_next: false } as Awaited<
+ ReturnType<typeof api.recordings.list>
+ >)
+ logic.actions.loadSessionRecordings()
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])
+ expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id], [aRecording.id]])
+ })
+
+ it('reports nothing on load without autoPlay — only explicit selection', async () => {
+ logic = sessionRecordingsPlaylistLogic({
+ logicKey: 'selection-reporting-no-autoplay',
+ onRecordingSelected,
+ })
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadSessionRecordingsSuccess'])
+ expect(onRecordingSelected).not.toHaveBeenCalled()
+
+ logic.actions.setSelectedRecordingId(aRecording.id)
+ expect(onRecordingSelected.mock.calls).toEqual([[aRecording.id]])
+ })
+ })
+
describe('person specific logic', () => {
beforeEach(() => {
logic = sessionRecordingsPlaylistLogic({
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
index fc0c9ba95ed3..eb4333c2cea8 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.ts
@@ -464,8 +464,10 @@ export interface SessionRecordingPlaylistLogicProps {
/** Called with each freshly loaded page of recordings (not the accumulated list). */
onRecordingsLoaded?: (recordings: SessionRecordingType[]) => void
/**
- * Called when a recording is selected (clicked, played next, or picked via the URL) —
- * not for the initial autoplayed recording, which is selected implicitly.
+ * Called once each time the recording the player shows changes — clicked, played next,
+ * picked via the URL, or the implicit autoplay fallback to the top of the list (on first
+ * load, and again when a reload changes which recording is at the top). Re-selecting the
+ * recording already shown does not re-fire.
*/
onRecordingSelected?: (recordingId: SessionRecordingType['id']) => void
pinnedFilters?: UniversalFiltersGroup
@@ -1257,7 +1259,28 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
},
],
})),
- listeners(({ props, actions, values }) => {
+ listeners(({ props, actions, values, cache }) => {
+ // The player can start showing a recording with no action dispatched: under autoPlay it
+ // falls back to the first in the list, and moves when a reload changes which recording
+ // is first. So selection is reported from the resulting active id after every action
+ // that can move it — deduped, since several of them can land on the same recording.
+ const notifyRecordingSelected = (): void => {
+ const activeId = values.activeSessionRecordingId
+ if (activeId) {
+ if (cache.lastReportedSelectedRecordingId !== activeId) {
+ cache.lastReportedSelectedRecordingId = activeId
+ props.onRecordingSelected?.(activeId)
+ }
+ } else if (!values.sessionRecordingsResponseLoading && !values.pinnedRecordingsLoading) {
+ // Settled on the empty state (a reload matched nothing): whatever shows next is
+ // shown afresh — even the recording reported last — so drop the dedupe. While a
+ // load is in flight the empty is transient (one loader's success can observe the
+ // other's reload window), and clearing on it would re-report an unchanged top
+ // recording once the reload lands.
+ cache.lastReportedSelectedRecordingId = undefined
+ }
+ }
+
// Selection is only ever set by user action, so it can go stale once the underlying
// list changes shape - keep it intersected with what's actually rendered.
const pruneSelectedRecordingsIds = (): void => {
@@ -1478,19 +1501,21 @@ export const sessionRecordingsPlaylistLogic = kea<sessionRecordingsPlaylistLogic
actions.maybeLoadPropertiesForSessions(values.sessionRecordings)
props.onRecordingsLoaded?.(sessionRecordingsResponse.results)
pruneSelectedRecordingsIds()
+ notifyRecordingSelected()
},
loadPinnedRecordingsSuccess: () => {
pruneSelectedRecordingsIds()
+ // Pinned recordings sort first, so this load can change which recording the
+ // autoplay fallback shows, just like a list load.
+ notifyRecordingSelected()
},
- setSelectedRecordingId: ({ id }) => {
+ setSelectedRecordingId: () => {
// Close filters when selecting a recording
actions.setIsFiltersExpanded(false)
- if (id) {
- props.onRecordingSelected?.(id)
- }
+ notifyRecordingSelected()
const recordingIndex = values.sessionRecordings.findIndex((s) => s.id === values.selectedRecordingId)