: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(toolbar): load the full clickmap automatically after first paint (#68063)
Paul D'Ambra32c34f7c7f04
diff --git a/frontend/src/toolbar/TELEMETRY.md b/frontend/src/toolbar/TELEMETRY.mdindex 8bfa36f431d1..4488ed0ae0f1 100644--- a/frontend/src/toolbar/TELEMETRY.md+++ b/frontend/src/toolbar/TELEMETRY.md@@ -162,10 +162,11 @@ A user paginating emits one event per page with cumulative `event_count` — gro| `matched_element_count` | `number` | Rows matched to a visible DOM element || `index_matched_count` | `number` | Rows matched via the DOM index fast path (before visibility trimming) || `fallback_matched_count` | `number` | Rows matched via the selector fallback (before visibility trimming); rising values signal index drift |+| `match_cache_hit_count` | `number` | Rows resolved from the per-row match cache (keyed on the server's chain hash) instead of re-matching || `page_element_count` | `number` | Elements collected from the page for matching || `has_shadow_roots` | `boolean` | Whether open shadow roots were detected; selects which fallback implementation runs, not whether a fallback runs || `duration_ms` | `number` | Wall-clock processing time, including main-thread yields; DOM index build time is included only on a cold cache |-| `trigger` | `string` | What started the run: `initial`, `pagination`, `refresh`, or `toggle` |+| `trigger` | `string` | What started the run: `initial`, `auto-load` (the background full fetch), `pagination`, `refresh`, or `toggle` || `cache_hit` | `boolean` | Whether the page-elements cache was warm (no collect + index rebuild) || `completed` | `boolean` | False when the run did not finish — superseded by a newer run, or failed mid-processing |diff --git a/frontend/src/toolbar/bar/toolbarLogic.ts b/frontend/src/toolbar/bar/toolbarLogic.tsindex 8355f058628a..d6f4e400b3f4 100644--- a/frontend/src/toolbar/bar/toolbarLogic.ts+++ b/frontend/src/toolbar/bar/toolbarLogic.ts@@ -741,17 +741,27 @@ export const toolbarLogic = kea<toolbarLogicType>([}switch (type) {- case PostHogAppToolbarEvent.PH_APP_INIT:+ case PostHogAppToolbarEvent.PH_APP_INIT: {+ const payload = e.data.payloadactions.setIsEmbeddedInApp(true)- actions.patchHeatmapFilters(e.data.payload.filters)- actions.setHeatmapColorPalette(e.data.payload.colorPalette)- actions.setHeatmapFixedPositionMode(e.data.payload.fixedPositionMode)- actions.setCommonFilters(e.data.payload.commonFilters)actions.toggleClickmapsEnabled(false)+ if (payload?.filters != null) {+ actions.patchHeatmapFilters(payload.filters)+ }+ if (payload?.colorPalette != null) {+ actions.setHeatmapColorPalette(payload.colorPalette)+ }+ if (payload?.fixedPositionMode != null) {+ actions.setHeatmapFixedPositionMode(payload.fixedPositionMode)+ }+ if (payload?.commonFilters != null) {+ actions.setCommonFilters(payload.commonFilters)+ }// it's ok to use we use a wildcard for the origin bc data isn't sensitive// nosemgrep: javascript.browser.security.wildcard-postmessage-configuration.wildcard-postmessage-configurationwindow.parent.postMessage({ type: PostHogAppToolbarEvent.PH_TOOLBAR_READY }, '*')return+ }case PostHogAppToolbarEvent.PH_ELEMENT_SELECTOR:if (e.data.payload.enabled) {actions.enableInspect()diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.tsindex a84798fc90aa..a30d15f41d5a 100644--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.test.ts@@ -1,6 +1,11 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'+import { toolbarApi } from '~/toolbar/toolbarApi'+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'import { ElementsEventType } from '~/toolbar/types'-import { dedupeByChainIdentity } from './heatmapToolbarMenuLogic'+import { dedupeByChainIdentity, heatmapToolbarMenuLogic } from './heatmapToolbarMenuLogic'function statsRow(overrides: Partial<ElementsEventType>): ElementsEventType {return {@@ -12,44 +17,135 @@ function statsRow(overrides: Partial<ElementsEventType>): ElementsEventType {} as ElementsEventType}-describe('dedupeByChainIdentity', () => {- const cases = [- {- name: 'keeps distinct chains when a legacy server returns hash null',- events: [- statsRow({ elements: [{ tag_name: 'button', attributes: {} }] as ElementsEventType['elements'] }),- statsRow({ elements: [{ tag_name: 'a', attributes: {} }] as ElementsEventType['elements'] }),- ],- expectedCount: 2,- },- {- name: 'drops a null-hash chain repeated across paginated pages, keeping the first occurrence',- events: [statsRow({ count: 10 }), statsRow({ count: 3 })],- expectedCount: 1,- },- {- name: 'keeps identical chains that differ by event type',- events: [statsRow({ type: '$autocapture' }), statsRow({ type: '$rageclick' })],- expectedCount: 2,- },- {- name: 'keeps distinct hashes even when attribute trimming made the chains serialize identically',- events: [statsRow({ hash: 'abc123' }), statsRow({ hash: 'def456' })],- expectedCount: 2,- },- {- name: 'drops a repeated hash across paginated pages, keeping the first occurrence',- events: [statsRow({ hash: 'abc123', count: 10 }), statsRow({ hash: 'abc123', count: 3 })],- expectedCount: 1,- },- ]-- it.each(cases)('$name', ({ events, expectedCount }) => {- expect(dedupeByChainIdentity(events)).toHaveLength(expectedCount)+describe('heatmapToolbarMenuLogic', () => {+ describe('dedupeByChainIdentity', () => {+ const cases = [+ {+ name: 'keeps distinct chains when a legacy server returns hash null',+ events: [+ statsRow({ elements: [{ tag_name: 'button', attributes: {} }] as ElementsEventType['elements'] }),+ statsRow({ elements: [{ tag_name: 'a', attributes: {} }] as ElementsEventType['elements'] }),+ ],+ expectedCount: 2,+ },+ {+ name: 'drops a null-hash chain repeated across paginated pages, keeping the first occurrence',+ events: [statsRow({ count: 10 }), statsRow({ count: 3 })],+ expectedCount: 1,+ },+ {+ name: 'keeps identical chains that differ by event type',+ events: [statsRow({ type: '$autocapture' }), statsRow({ type: '$rageclick' })],+ expectedCount: 2,+ },+ {+ name: 'keeps distinct hashes even when attribute trimming made the chains serialize identically',+ events: [statsRow({ hash: 'abc123' }), statsRow({ hash: 'def456' })],+ expectedCount: 2,+ },+ {+ name: 'drops a repeated hash across paginated pages, keeping the first occurrence',+ events: [statsRow({ hash: 'abc123', count: 10 }), statsRow({ hash: 'abc123', count: 3 })],+ expectedCount: 1,+ },+ ]++ it.each(cases)('$name', ({ events, expectedCount }) => {+ expect(dedupeByChainIdentity(events)).toHaveLength(expectedCount)+ })++ it('keeps the first occurrence of a duplicated chain', () => {+ const [kept] = dedupeByChainIdentity([statsRow({ count: 10 }), statsRow({ count: 3 })])+ expect(kept.count).toBe(10)+ })})- it('keeps the first occurrence of a duplicated chain', () => {- const [kept] = dedupeByChainIdentity([statsRow({ count: 10 }), statsRow({ count: 3 })])- expect(kept.count).toBe(10)+ describe('clickmap loading', () => {+ let logic: ReturnType<typeof heatmapToolbarMenuLogic.build>++ beforeEach(() => {+ global.IntersectionObserver = class {+ observe(): void {}+ unobserve(): void {}+ disconnect(): void {}+ } as any+ global.fetch = jest.fn(() =>+ Promise.resolve({+ ok: true,+ status: 200,+ json: () => Promise.resolve({ results: [] }),+ } as any as Response)+ )+ jest.spyOn(toolbarApi.elementStats, 'list').mockResolvedValue({+ ok: true,+ status: 200,+ data: { results: [], next: null, previous: null },+ } as any)++ initKeaTests()+ toolbarConfigLogic+ .build({+ apiURL: 'http://localhost',+ accessToken: 'test-token',+ refreshToken: 'test-refresh',+ clientId: 'test-client',+ })+ .mount()+ logic = heatmapToolbarMenuLogic()+ logic.mount()+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ it('loads element stats as soon as the heatmap menu opens, without toggling clickmaps', async () => {+ await expectLogic(logic, () => logic.actions.enableHeatmap()).toDispatchActions([+ 'getElementStats',+ 'getElementStatsSuccess',+ ])+ expect(toolbarApi.elementStats.list).toHaveBeenCalled()+ })++ it('does not fetch element stats on navigation while the heatmap menu is closed', async () => {+ await expectLogic(logic, () =>+ logic.actions.setHref('https://example.com/other')+ ).toNotHaveDispatchedActions(['getElementStats'])+ expect(toolbarApi.elementStats.list).not.toHaveBeenCalled()+ })++ it('fetches element stats on navigation while the heatmap menu is open', async () => {+ await expectLogic(logic, () => logic.actions.enableHeatmap()).toDispatchActions(['getElementStats'])+ await expectLogic(logic, () => logic.actions.setHref('https://example.com/other')).toDispatchActions([+ 'getElementStats',+ ])+ })++ it('does not fetch element stats when clickmaps are toggled off while the request is debouncing', async () => {+ await expectLogic(logic, () => {+ logic.actions.enableHeatmap()+ logic.actions.toggleClickmapsEnabled(false)+ }).toDispatchActions(['getElementStats', 'getElementStatsSuccess'])+ expect(toolbarApi.elementStats.list).not.toHaveBeenCalled()+ })++ it('keeps heatmapEnabled true after a stats fetch failure so the menu stays open', async () => {+ jest.spyOn(toolbarApi.elementStats, 'list').mockRejectedValue(new Error('network error'))+ await expectLogic(logic, () => logic.actions.enableHeatmap()).toDispatchActions([+ 'getElementStats',+ 'getElementStatsFailure',+ ])+ expect(logic.values.heatmapEnabled).toBe(true)+ })++ it('retries the initial load via load more after a stats fetch failure', async () => {+ jest.spyOn(toolbarApi.elementStats, 'list').mockRejectedValueOnce(new Error('network error'))+ await expectLogic(logic, () => logic.actions.enableHeatmap()).toDispatchActions(['getElementStatsFailure'])+ await expectLogic(logic, () => logic.actions.loadMoreElementStats()).toDispatchActions([+ 'getElementStats',+ 'getElementStatsSuccess',+ ])+ expect(toolbarApi.elementStats.list).toHaveBeenCalledTimes(2)+ })})})diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.tsindex 303bc38834ed..e1e0954b218e 100644--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts@@ -29,6 +29,10 @@ import type { heatmapToolbarMenuLogicType } from './heatmapToolbarMenuLogicType'export const doesVersionSupportScrollDepth = createVersionChecker('1.99')const ELEMENT_STATS_PAGE_LIMIT = 5000+// the follow-up fetch re-reads from offset 0 with a bigger limit rather than paginating:+// the server re-runs the full aggregation for any offset, so one big scan costs the same as+// a page and can't miss rows that shifted across page boundaries between scans+const ELEMENT_STATS_AUTO_LOAD_LIMIT = 50000function yieldToMain(): Promise<void> {return new Promise((resolve) => {@@ -42,12 +46,15 @@ function yieldToMain(): Promise<void> {})}-export type ClickmapProcessingTrigger = 'initial' | 'pagination' | 'refresh' | 'toggle'+export type ClickmapProcessingTrigger = 'initial' | 'auto-load' | 'pagination' | 'refresh' | 'toggle'interface ElementProcessingCache {pageElements?: HTMLElement[]domIndex?: DOMIndexselectorToElements: Map<string, HTMLElement[] | null>+ // matched DOM element (or a definitive miss) per type:chain_hash row identity, so the+ // auto-load refetch and pagination reprocess only rows they haven't matched before+ matchedElementByIdentity: Map<string, HTMLElement | null>lastHref?: stringintersectionObserver?: IntersectionObservervisibilityCache: WeakMap<HTMLElement, boolean>@@ -59,6 +66,7 @@ function invalidatePageElementsCache(cache: ElementProcessingCache): void {cache.cacheInvalidated = truecache.visibilityCache = new WeakMap()cache.domIndex = undefined+ cache.matchedElementByIdentity = new Map()}function getCachedPageElements(@@ -86,6 +94,7 @@ function getCachedPageElements(cache.domIndex = buildDOMIndex(cache.pageElements)cache.lastHref = hrefcache.selectorToElements = new Map()+ cache.matchedElementByIdentity = new Map()cache.cacheInvalidated = falsereturn {pageElements: cache.pageElements,@@ -141,8 +150,9 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([],})),actions({- getElementStats: (url?: string | null) => ({+ getElementStats: (url?: string | null, limit?: number) => ({url,+ limit,}),enableHeatmap: true,disableHeatmap: true,@@ -169,6 +179,15 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([})),reducers({matchLinksByHref: [false, { setMatchLinksByHref: (_, { matchLinksByHref }) => matchLinksByHref }],+ lastElementStatsRequest: [+ null as { url: string | null; limit: number } | null,+ {+ getElementStats: (_, { url, limit }) => ({+ url: url ?? null,+ limit: limit ?? ELEMENT_STATS_PAGE_LIMIT,+ }),+ },+ ],canLoadMoreElementStats: [true,{@@ -181,11 +200,10 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([{enableHeatmap: () => true,disableHeatmap: () => false,- getElementStatsFailure: () => false,},],clickmapsEnabled: [- false,+ true,{toggleClickmapsEnabled: (_, { enabled }) => enabled,},@@ -252,9 +270,15 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([null as PaginatedResponse<ElementsEventType> | null,{resetElementStats: () => emptyElementsStatsPages,- getElementStats: async ({ url }, breakpoint) => {+ getElementStats: async ({ url, limit }, breakpoint) => {await breakpoint(150)+ // the gates can flip while we sit in the breakpoint (the embedded app sends+ // toggleClickmapsEnabled(false) just after mount), so re-check before fetching+ if (!values.heatmapEnabled || !values.clickmapsEnabled) {+ return values.elementStats ?? emptyElementsStatsPages+ }+const { href, wildcardHref } = values// We re-raise below to drive getElementStatsFailure; let the global// loader handler report it once rather than capturing twice.@@ -290,7 +314,7 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([date_to: values.commonFilters.date_to,paginate_response: true,sampling_factor: values.samplingFactor,- limit: ELEMENT_STATS_PAGE_LIMIT,+ limit: limit ?? ELEMENT_STATS_PAGE_LIMIT,// the matchers only read the configured data attributes from each// element's attributes map, so let the server drop the restdata_attributes: values.wantedDataAttributes.join(','),@@ -416,29 +440,54 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([const eventsToProcess = elementStats.resultsconst totalEvents = eventsToProcess.length+ const matchedElementByIdentity = (cache as ElementProcessingCache).matchedElementByIdentityconst allTrimmedElements: CountedHTMLElement[] = []let indexMatchedCount = 0let fallbackMatchedCount = 0+ let matchCacheHitCount = 0let completed = falselet sliceStart = performance.now()try {for (let i = 0; i < totalEvents; i++) {const event = eventsToProcess[i]- let matched = matchEventToElementUsingIndex(event, dataAttributes, matchLinksByHref, domIndex)- if (matched) {- indexMatchedCount += 1+ const identity = event.hash ? `${event.type}:${event.hash}` : null+ const cachedElement = identity ? matchedElementByIdentity.get(identity) : undefined++ let matched: CountedHTMLElement | null = null+ if (cachedElement !== undefined) {+ matchCacheHitCount += 1+ matched = cachedElement+ ? {+ element: cachedElement,+ count: event.count,+ selector: '',+ hash: event.hash,+ type: event.type,+ clickCount: 0,+ rageclickCount: 0,+ deadclickCount: 0,+ }+ : null} else {- matched = matchEventToElementUsingSelectors(- event,- dataAttributes,- matchLinksByHref,- pageElements,- (cache as ElementProcessingCache).selectorToElements,- hasShadowRoots- )+ matched = matchEventToElementUsingIndex(event, dataAttributes, matchLinksByHref, domIndex)if (matched) {- fallbackMatchedCount += 1+ indexMatchedCount += 1+ } else {+ matched = matchEventToElementUsingSelectors(+ event,+ dataAttributes,+ matchLinksByHref,+ pageElements,+ (cache as ElementProcessingCache).selectorToElements,+ hasShadowRoots+ )+ if (matched) {+ fallbackMatchedCount += 1+ }+ }+ if (identity) {+ matchedElementByIdentity.set(identity, matched?.element ?? null)}}@@ -473,6 +522,7 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([matched_element_count: allTrimmedElements.length,index_matched_count: indexMatchedCount,fallback_matched_count: fallbackMatchedCount,+ match_cache_hit_count: matchCacheHitCount,page_element_count: pageElements.length,has_shadow_roots: hasShadowRoots,duration_ms: Math.round(performance.now() - startedAt),@@ -518,7 +568,9 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([},maybeLoadClickmap: async () => {- if (values.clickmapsEnabled) {+ // this logic stays mounted while the heatmap menu is closed, so navigation+ // must not fetch stats until the user is actually looking+ if (values.heatmapEnabled && values.clickmapsEnabled) {actions.getElementStats()}},@@ -553,12 +605,13 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([toggleClickmapsEnabled: () => {if (values.clickmapsEnabled) {- actions.getElementStats()+ actions.maybeLoadClickmap()} else {actions.stopElementObservation()actions.resetElementStats()cache.pageElements = undefinedcache.selectorToElements = new Map()+ cache.matchedElementByIdentity = new Map()cache.lastHref = undefinedcache.visibilityCache = new WeakMap()}@@ -567,14 +620,31 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([loadMoreElementStats: () => {if (values.elementStats?.next) {actions.getElementStats(values.elementStats.next)+ } else if (!values.elementStats) {+ // the initial load failed, so the button doubles as the retry affordance+ actions.maybeLoadClickmap()}},getElementStatsSuccess: ({ elementStats }) => {- actions.processElements(elementStats?.previous ? 'pagination' : 'initial')+ const request = values.lastElementStatsRequest+ const trigger: ClickmapProcessingTrigger = request?.url+ ? 'pagination'+ : request?.limit === ELEMENT_STATS_AUTO_LOAD_LIMIT+ ? 'auto-load'+ : 'initial'+ actions.processElements(trigger)++ // the first page painted; fetch the rest in one background request. Only the initial+ // trigger refetches, so an auto-load result can never re-trigger itself.+ if (trigger === 'initial' && elementStats?.next && values.heatmapEnabled && values.clickmapsEnabled) {+ actions.getElementStats(null, ELEMENT_STATS_AUTO_LOAD_LIMIT)+ }},setMatchLinksByHref: () => {+ // href matching changes what a row matches, so cached matches are stale+ ;(cache as ElementProcessingCache).matchedElementByIdentity = new Map()actions.processElements('toggle')},@@ -596,6 +666,7 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([})),afterMount(({ actions, cache, values }) => {cache.selectorToElements = new Map()+ cache.matchedElementByIdentity = new Map()cache.visibilityCache = new WeakMap()cache.disposables.add(() => {@@ -660,6 +731,7 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([beforeUnmount(({ cache }) => {cache.pageElements = undefinedcache.selectorToElements = new Map()+ cache.matchedElementByIdentity = new Map()cache.visibilityCache = new WeakMap()cache.lastHref = undefinedcache.cacheInvalidated = falsediff --git a/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx b/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsxindex c1a808291849..cabfe1696e63 100644--- a/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx+++ b/frontend/src/toolbar/stats/HeatmapToolbarMenu.tsx@@ -313,8 +313,9 @@ export const HeatmapToolbarMenu = (): JSX.Element => {</div>{canLoadMoreElementStats && loadedElementStatsCount > 0 && (<div className="mb-2 text-muted text-xs">- Showing the top {loadedElementStatsCount.toLocaleString()} element groups by click- count — load more for the full data range.+ {elementStatsLoading+ ? `Showing the top ${loadedElementStatsCount.toLocaleString()} element groups by click count — loading the rest automatically…`+ : `Showing the top ${loadedElementStatsCount.toLocaleString()} element groups by click count — load more for the full data range.`}</div>)}<div className="flex flex-col w-full h-full">