:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(web-analytics): report abandoned and background page loads (#112924)
Jordan Mryyan6addf3b91cc0
diff --git a/frontend/src/lib/internalMetrics.ts b/frontend/src/lib/internalMetrics.tsindex b798b9ee9828..0dc0b49ddc8f 100644--- a/frontend/src/lib/internalMetrics.ts+++ b/frontend/src/lib/internalMetrics.ts@@ -5,7 +5,7 @@ interface TimeToSeeDataFields {time_to_see_data_ms: numberprimary_interaction_id: stringquery_id?: string- status?: 'failure' | 'success' | 'cancelled'+ status?: 'failure' | 'success' | 'cancelled' | 'hidden' | 'no_load'api_response_bytes?: numberapi_url?: stringinsight?: string@@ -28,6 +28,14 @@ export interface PageLoadTimeToSeeData extends TimeToSeeDataFields {last_tile_kind?: string | nulllast_tile_status?: string | nulltiles_still_loading?: number+ tiles_succeeded?: number+ tiles_requeried_while_loading?: number+ tiles_mounted?: number+ first_tile_ms?: number | null+ kind_ready_ms?: Record<string, number>+ visible_ms?: number+ was_hidden?: boolean+ visit_id?: string | nullcancel_reason?: 'navigated_away' | 'left_app' | 'refreshed'}diff --git a/frontend/src/queries/nodes/DataNode/dataNodeCollectionLogic.test.ts b/frontend/src/queries/nodes/DataNode/dataNodeCollectionLogic.test.tsindex 45d2b9dfcac9..06ff3e113f88 100644--- a/frontend/src/queries/nodes/DataNode/dataNodeCollectionLogic.test.ts+++ b/frontend/src/queries/nodes/DataNode/dataNodeCollectionLogic.test.ts@@ -33,7 +33,9 @@ describe('dataNodeCollectionLogic', () => {}afterEach(() => {- logic?.unmount()+ if (logic?.isMounted()) {+ logic.unmount()+ }})it('reloadAll fires loadData on every mounted data node with force_async', () => {@@ -143,6 +145,11 @@ describe('dataNodeCollectionLogic', () => {last_tile_status: 'failure',time_to_see_data_ms: expect.any(Number),primary_interaction_id: expect.any(String),+ tiles_succeeded: 1,+ first_tile_ms: expect.any(Number),+ kind_ready_ms: { TrendsQuery: expect.any(Number) },+ was_hidden: false,+ visit_id: null,}),])})@@ -186,6 +193,7 @@ describe('dataNodeCollectionLogic', () => {logic.actions.collectionNodeLoadDataFailure('tile-a')logic.actions.collectionNodeLoadData('tile-a')+ logic.actions.collectionNodeLoadData('tile-b')logic.actions.collectionNodeLoadDataSuccess('tile-b')expect(capturedLoads()).toHaveLength(0)@@ -197,6 +205,7 @@ describe('dataNodeCollectionLogic', () => {insights_fetched: 2,insights_fetched_cached: 1,failed_tile_count: 0,+ tiles_requeried_while_loading: 1,}),])})@@ -275,5 +284,102 @@ describe('dataNodeCollectionLogic', () => {options)})++ it.each([+ [+ 'the visit ends before any query starts',+ (): void => logic.actions.endPageVisit(),+ { status: 'no_load', cancel_reason: 'navigated_away', tiles_mounted: 1 },+ undefined,+ ],+ [+ 'the page is hidden before any query starts',+ (): void => {+ window.dispatchEvent(new Event('pagehide'))+ logic.actions.endPageVisit()+ },+ { status: 'no_load', cancel_reason: 'left_app', tiles_mounted: 1 },+ { transport: 'sendBeacon' },+ ],+ [+ 'the visit ends mid-load',+ (): void => {+ logic.actions.collectionNodeLoadData('tile-a')+ logic.actions.endPageVisit()+ },+ { status: 'cancelled', cancel_reason: 'navigated_away', tiles_still_loading: 1 },+ undefined,+ ],+ [+ 'the collection unmounts mid-load without ending the visit',+ (): void => {+ logic.actions.collectionNodeLoadData('tile-a')+ logic.unmount()+ },+ { status: 'cancelled', cancel_reason: 'navigated_away' },+ undefined,+ ],+ ])('reports exactly one outcome for a page visit when %s', (_, act, expected, options) => {+ logic.actions.startPageVisit('visit-1')+ mountTile('tile-a')++ act()++ expect(posthog.capture).toHaveBeenCalledTimes(1)+ expect(posthog.capture).toHaveBeenCalledWith(+ 'time to see data',+ expect.objectContaining({ context: 'test-collection', visit_id: 'visit-1', ...expected }),+ options+ )+ })++ it('still reports a load that starts after the page returns from the back-forward cache', () => {+ logic.actions.startPageVisit('visit-1')+ mountTile('tile-a')+ logic.actions.collectionNodeLoadData('tile-a')+ window.dispatchEvent(new Event('pagehide'))++ logic.actions.collectionNodeLoadData('tile-a')+ window.dispatchEvent(new Event('pagehide'))+ logic.actions.endPageVisit()++ expect(capturedLoads().map((load) => [load.status, load.cancel_reason])).toEqual([+ ['cancelled', 'left_app'],+ ['cancelled', 'left_app'],+ ])+ })++ it('reports a provisional hidden event and counts only visible time toward the wait', () => {+ const setVisibility = (state: DocumentVisibilityState): void => {+ Object.defineProperty(document, 'visibilityState', { value: state, configurable: true })+ document.dispatchEvent(new Event('visibilitychange'))+ }+ jest.useFakeTimers()+ try {+ mountTile('tile-a')+ logic.actions.collectionNodeLoadData('tile-a')+ jest.advanceTimersByTime(1000)+ setVisibility('hidden')+ jest.advanceTimersByTime(3000)+ setVisibility('visible')+ jest.advanceTimersByTime(1000)+ logic.actions.collectionNodeLoadDataSuccess('tile-a')++ const [hidden, settled] = capturedLoads()+ expect(capturedLoads()).toHaveLength(2)+ expect(hidden).toMatchObject({ status: 'hidden', time_to_see_data_ms: 1000, was_hidden: true })+ expect(settled).toMatchObject({+ status: 'success',+ primary_interaction_id: hidden.primary_interaction_id,+ time_to_see_data_ms: 5000,+ visible_ms: 2000,+ was_hidden: true,+ })+ expect((posthog.capture as jest.Mock).mock.calls[0][2]).toEqual({ transport: 'sendBeacon' })+ } finally {+ Object.defineProperty(document, 'visibilityState', { value: 'visible', configurable: true })+ jest.useRealTimers()+ }+ })})})diff --git a/frontend/src/queries/nodes/DataNode/dataNodeCollectionLogic.ts b/frontend/src/queries/nodes/DataNode/dataNodeCollectionLogic.tsindex c79946b9401e..defc863d524d 100644--- a/frontend/src/queries/nodes/DataNode/dataNodeCollectionLogic.ts+++ b/frontend/src/queries/nodes/DataNode/dataNodeCollectionLogic.ts@@ -1,4 +1,16 @@-import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import {+ MakeLogicType,+ actions,+ afterMount,+ beforeUnmount,+ kea,+ key,+ listeners,+ path,+ props,+ reducers,+ selectors,+} from 'kea'import posthog, { CaptureOptions } from 'posthog-js'import { PageLoadTimeToSeeData } from 'lib/internalMetrics'@@ -44,6 +56,20 @@ interface DataCollectionLoadCycle {trigger: DataCollectionLoadTriggertiles: Map<string, DataCollectionLoadTile>lastTileId: string | null+ visitId: string | null+ hiddenMs: number+ reportedHidden: boolean+ firstTileMs: number | null+ kindReadyMs: Record<string, number>+ requeriedWhileLoading: number+}++interface DataCollectionPageVisit {+ id: string+ startedAt: number+ cycles: number+ tilesMounted: number+ reported: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -73,6 +99,9 @@ export interface dataNodeCollectionLogicActions {id: stringmeta: CollectionNodeLoadMeta | undefined}+ endPageVisit: () => {+ value: true+ }mountDataNode: (id: string,props: DataNodeRegisteredProps@@ -84,9 +113,15 @@ export interface dataNodeCollectionLogicActions {value: true}reloadAll: () => {}+ startPageVisit: (visitId: string) => {+ visitId: string+ }unmountDataNode: (id: string) => {id: string}+ visibilityChanged: (hidden: boolean) => {+ hidden: boolean+ }}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -119,6 +154,9 @@ export const dataNodeCollectionLogic = kea<dataNodeCollectionLogicType>([collectionNodeLoadDataSuccess: (id: string, meta?: CollectionNodeLoadMeta) => ({ id, meta }),collectionNodeLoadDataFailure: (id: string) => ({ id }),pageHidden: true,+ visibilityChanged: (hidden: boolean) => ({ hidden }),+ startPageVisit: (visitId: string) => ({ visitId }),+ endPageVisit: true,}),reducers({mountedDataNodes: [@@ -177,14 +215,23 @@ export const dataNodeCollectionLogic = kea<dataNodeCollectionLogicType>([if (!isPageCollection(props.key) || !posthog.capture) {return}+ const elapsedMs = Math.round(performance.now() - cycle.startedAt)+ const hiddenMs = Math.min(elapsedMs, Math.round(hiddenMsSoFar(cycle)))const payload: PageLoadTimeToSeeData = {type: 'page_load',context: props.key,action: cycle.trigger,primary_interaction_id: cycle.id,- time_to_see_data_ms: Math.round(performance.now() - cycle.startedAt),+ time_to_see_data_ms: elapsedMs,+ visible_ms: elapsedMs - hiddenMs,+ was_hidden: hiddenMs > 0 || cache.hiddenSince !== null,insights_fetched: cycle.tiles.size,insights_fetched_cached: countTiles(cycle, (tile) => tile.cached),+ tiles_succeeded: countTiles(cycle, (tile) => tile.status === 'success'),+ tiles_requeried_while_loading: cycle.requeriedWhileLoading,+ first_tile_ms: cycle.firstTileMs,+ kind_ready_ms: cycle.kindReadyMs,+ visit_id: cycle.visitId,scene: cycle.scene,time_since_mount_ms: Math.round(performance.now() - cache.mountedAt),...outcome,@@ -192,13 +239,53 @@ export const dataNodeCollectionLogic = kea<dataNodeCollectionLogicType>([posthog.capture('time to see data', payload, options)}+ const hiddenMsSoFar = (cycle: DataCollectionLoadCycle): number =>+ cycle.hiddenMs ++ (cache.hiddenSince !== null ? performance.now() - Math.max(cache.hiddenSince, cycle.startedAt) : 0)++ const finishVisit = (reason: 'navigated_away' | 'left_app', options?: CaptureOptions): void => {+ const visit: DataCollectionPageVisit | null = cache.visit+ if (!visit) {+ return+ }+ if (cache.cycle) {+ abandon(cache.cycle, reason, options)+ } else if (!visit.reported && visit.cycles === 0 && isPageCollection(props.key) && posthog.capture) {+ const payload: PageLoadTimeToSeeData = {+ type: 'page_load',+ context: props.key,+ action: 'initial_load',+ status: 'no_load',+ cancel_reason: reason,+ primary_interaction_id: uuid(),+ time_to_see_data_ms: Math.round(performance.now() - visit.startedAt),+ insights_fetched: 0,+ tiles_mounted: visit.tilesMounted,+ visit_id: visit.id,+ scene: sceneLogic.findMounted()?.values.activeSceneId ?? null,+ time_since_mount_ms: Math.round(performance.now() - cache.mountedAt),+ }+ posthog.capture('time to see data', payload, options)+ }+ visit.reported = true+ }+ cache.finishVisit = finishVisit+const finishTile = (id: string, status: 'success' | 'failure', cached = false): void => {const cycle = cache.cycleif (!cycle) {return}- cycle.tiles.set(id, { kind: cycle.tiles.get(id)?.kind ?? null, status, cached })+ const kind = cycle.tiles.get(id)?.kind ?? null+ cycle.tiles.set(id, { kind, status, cached })cycle.lastTileId = id+ if (status === 'success') {+ const readyMs = Math.round(performance.now() - cycle.startedAt)+ cycle.firstTileMs ??= readyMs+ if (kind && !(kind in cycle.kindReadyMs)) {+ cycle.kindReadyMs[kind] = readyMs+ }+ }if (!values.areAnyLoading) {settle(cycle)}@@ -268,7 +355,19 @@ export const dataNodeCollectionLogic = kea<dataNodeCollectionLogicType>([trigger: cache.pendingTrigger ?? (cache.completedCycles === 0 ? 'initial_load' : 'update'),tiles: new Map(),lastTileId: null,+ visitId: cache.visit?.id ?? null,+ hiddenMs: 0,+ reportedHidden: false,+ firstTileMs: null,+ kindReadyMs: {},+ requeriedWhileLoading: 0,} satisfies DataCollectionLoadCycle+ if (cache.visit) {+ cache.visit.cycles += 1+ }+ }+ if (cache.cycle.tiles.get(id)?.status === 'loading') {+ cache.cycle.requeriedWhileLoading += 1}cache.cycle.tiles.set(id, { kind: kind ?? null, status: 'loading', cached: false })},@@ -278,16 +377,54 @@ export const dataNodeCollectionLogic = kea<dataNodeCollectionLogicType>([collectionNodeLoadDataFailure: ({ id }) => {finishTile(id, 'failure')},+ mountDataNode: () => {+ if (cache.visit) {+ cache.visit.tilesMounted += 1+ }+ },unmountDataNode: ({ id }) => {if (cache.cycle?.tiles.get(id)?.status === 'loading') {abandon(cache.cycle, 'navigated_away')}},pageHidden: () => {- if (cache.cycle) {+ if (cache.visit) {+ finishVisit('left_app', { transport: 'sendBeacon' })+ } else if (cache.cycle) {abandon(cache.cycle, 'left_app', { transport: 'sendBeacon' })}},+ visibilityChanged: ({ hidden }) => {+ const cycle: DataCollectionLoadCycle | null = cache.cycle+ if (hidden) {+ cache.hiddenSince ??= performance.now()+ if (cycle && !cycle.reportedHidden) {+ cycle.reportedHidden = true+ report(cycle, { status: 'hidden' }, { transport: 'sendBeacon' })+ }+ return+ }+ if (cycle && cache.hiddenSince !== null) {+ cycle.hiddenMs += performance.now() - Math.max(cache.hiddenSince, cycle.startedAt)+ }+ cache.hiddenSince = null+ },+ startPageVisit: ({ visitId }) => {+ if (cache.cycle) {+ abandon(cache.cycle, 'navigated_away')+ }+ cache.visit = {+ id: visitId,+ startedAt: performance.now(),+ cycles: 0,+ tilesMounted: 0,+ reported: false,+ } satisfies DataCollectionPageVisit+ },+ endPageVisit: () => {+ finishVisit('navigated_away')+ cache.visit = null+ },}}),afterMount(({ actions, cache }) => {@@ -295,6 +432,8 @@ export const dataNodeCollectionLogic = kea<dataNodeCollectionLogicType>([cache.cycle = nullcache.completedCycles = 0cache.pendingTrigger = null+ cache.visit = null+ cache.hiddenSince = document.visibilityState === 'hidden' ? performance.now() : nullcache.disposables.add(() => {window.addEventListener('pagehide', actions.pageHidden)@@ -303,5 +442,17 @@ export const dataNodeCollectionLogic = kea<dataNodeCollectionLogicType>(['pagehide',{ pauseOnPageHidden: false })+ const onVisibilityChange = (): void => actions.visibilityChanged(document.visibilityState === 'hidden')+ cache.disposables.add(+ () => {+ document.addEventListener('visibilitychange', onVisibilityChange)+ return () => document.removeEventListener('visibilitychange', onVisibilityChange)+ },+ 'visibilitychange',+ { pauseOnPageHidden: false }+ )+ }),+ beforeUnmount(({ cache }) => {+ cache.finishVisit?.('navigated_away')}),])diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLoadTimeLogic.test.ts b/frontend/src/scenes/web-analytics/webAnalyticsLoadTimeLogic.test.tsindex 121eecc85285..0bb9ddab219a 100644--- a/frontend/src/scenes/web-analytics/webAnalyticsLoadTimeLogic.test.ts+++ b/frontend/src/scenes/web-analytics/webAnalyticsLoadTimeLogic.test.ts@@ -23,14 +23,30 @@ describe('webAnalyticsLoadTimeLogic', () => {})afterEach(() => {- logic.unmount()+ if (logic.isMounted()) {+ logic.unmount()+ }collection.unmount()})it('captures dashboard_mounted on mount', () => {expect(posthog.capture).toHaveBeenCalledWith('web_analytics_dashboard_mounted',- expect.objectContaining({ tile_skeletons_enabled: expect.any(Boolean) })+ expect.objectContaining({ tile_skeletons_enabled: expect.any(Boolean), visit_id: expect.any(String) })+ )+ })++ it('reports a dashboard left before any query as no_load under the mounted visit_id', () => {+ const [, mounted] = (posthog.capture as jest.Mock).mock.calls.find(+ ([event]) => event === 'web_analytics_dashboard_mounted'+ )++ logic.unmount()++ expect(posthog.capture).toHaveBeenCalledWith(+ 'time to see data',+ expect.objectContaining({ status: 'no_load', visit_id: mounted.visit_id }),+ undefined)})diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLoadTimeLogic.ts b/frontend/src/scenes/web-analytics/webAnalyticsLoadTimeLogic.tsindex 02cbb7e255cd..35719791e1be 100644--- a/frontend/src/scenes/web-analytics/webAnalyticsLoadTimeLogic.ts+++ b/frontend/src/scenes/web-analytics/webAnalyticsLoadTimeLogic.ts@@ -2,6 +2,7 @@ import {MakeLogicType,actions,afterMount,+ beforeUnmount,connect,kea,listeners,@@ -15,6 +16,7 @@ import posthog from 'posthog-js'import { FEATURE_FLAGS } from 'lib/constants'import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { uuid } from 'lib/utils/dom'import { teamLogic } from 'scenes/teamLogic'import { dataNodeCollectionLogic } from '~/queries/nodes/DataNode/dataNodeCollectionLogic'@@ -55,6 +57,12 @@ export interface webAnalyticsLoadTimeLogicActions {id: stringmeta: import('~/queries/nodes/DataNode/dataNodeCollectionLogic').CollectionNodeLoadMeta | undefined} // dataNodeCollectionLogic+ endPageVisit: () => {+ value: true+ } // dataNodeCollectionLogic+ startPageVisit: (visitId: string) => {+ visitId: string+ } // dataNodeCollectionLogicrecordVisit: () => {value: true}@@ -90,7 +98,13 @@ export const webAnalyticsLoadTimeLogic = kea<webAnalyticsLoadTimeLogicType>([connect(() => ({actions: [dataNodeCollectionLogic({ key: WEB_ANALYTICS_DATA_COLLECTION_NODE_ID }),- ['collectionNodeLoadData', 'collectionNodeLoadDataSuccess', 'collectionNodeLoadDataFailure'],+ [+ 'collectionNodeLoadData',+ 'collectionNodeLoadDataSuccess',+ 'collectionNodeLoadDataFailure',+ 'startPageVisit',+ 'endPageVisit',+ ],],values: [dataNodeCollectionLogic({ key: WEB_ANALYTICS_DATA_COLLECTION_NODE_ID }),@@ -129,6 +143,7 @@ export const webAnalyticsLoadTimeLogic = kea<webAnalyticsLoadTimeLogicType>([posthog.capture('web_analytics_dashboard_loaded', {duration_ms: Math.round(performance.now() - cache.mountStart),tile_skeletons_enabled: values.tileSkeletonsEnabled,+ visit_id: cache.visitId,})},})),@@ -158,9 +173,15 @@ export const webAnalyticsLoadTimeLogic = kea<webAnalyticsLoadTimeLogicType>([afterMount(({ cache, values, actions }) => {cache.mountStart = performance.now()cache.hasCapturedLoaded = false+ cache.visitId = uuid()+ actions.startPageVisit(cache.visitId)posthog.capture('web_analytics_dashboard_mounted', {tile_skeletons_enabled: values.tileSkeletonsEnabled,+ visit_id: cache.visitId,})actions.recordVisit()}),+ beforeUnmount(({ actions }) => {+ actions.endPageVisit()+ }),])