: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
fix(web-analytics): break actionToUrl/urlToAction cascade on URL restore (#66642)
Paul D'Ambra5025ff26a40c
diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.tsindex c8ccf7f231e2..164d15abd470 100644--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.test.ts@@ -1,6 +1,8 @@import { MOCK_DEFAULT_USER, MOCK_TEAM_ID } from 'lib/api.mock'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import posthog from 'posthog-js'import api from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'@@ -10,7 +12,7 @@ import { userLogic } from 'scenes/userLogic'import { initKeaTests } from '~/test/init'import { UserType } from '~/types'-import { ProductTab, TileId } from './common'+import { GraphsTab, ProductTab, TileId } from './common'import { FOCUS_MODE_TILE_IDS } from './focus-mode/focusModeMapping'import { WebAnalyticsConcern, getFocusModeOnboardingSeenKey } from './focus-mode/types'import { webAnalyticsLogic } from './webAnalyticsLogic'@@ -316,3 +318,127 @@ describe('webAnalyticsLogic precompute payload', () => {})})})++describe('webAnalyticsLogic URL restoration', () => {+ let logic: ReturnType<typeof webAnalyticsLogic.build>++ beforeEach(() => {+ localStorage.clear()+ initKeaTests()+ jest.spyOn(api.propertyDefinitions, 'list').mockResolvedValue({ results: [] } as any)+ jest.spyOn(api.hogFunctions, 'list').mockResolvedValue({ results: [] } as any)+ jest.spyOn(api, 'update').mockResolvedValue({} as any)+ ;(posthog as any).setPersonProperties = jest.fn()+ featureFlagLogic.mount()+ logic = webAnalyticsLogic()+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ jest.restoreAllMocks()+ })++ // These lock the full URL <-> state contract so the restore path can be refactored (centralising+ // the per-action dispatches into a single un-mapped sync) without silently regressing it:+ // - every param restores into the right reducer (incl. state owned by the connected filter logic),+ // - restoration does not thrash the URL (the actionToUrl <-> urlToAction cascade),+ // - the bots tab keeps its flag-gating and last-day date default,+ // - actionToUrl still mirrors user changes back into the URL.+ it.each<[string, Record<string, string>, () => unknown, unknown]>([+ ['device_tab', { device_tab: 'BROWSER' }, () => logic.values._deviceTab, 'BROWSER'],+ ['source_tab', { source_tab: 'REFERRING_DOMAIN' }, () => logic.values._sourceTab, 'REFERRING_DOMAIN'],+ ['path_tab', { path_tab: 'INITIAL_PATH' }, () => logic.values._pathTab, 'INITIAL_PATH'],+ ['graphs_tab', { graphs_tab: 'UNIQUE_USERS' }, () => logic.values._graphsTab, 'UNIQUE_USERS'],+ ['geography_tab', { geography_tab: 'MAP' }, () => logic.values._geographyTab, 'MAP'],+ ['active_hours_tab', { active_hours_tab: 'UNIQUE' }, () => logic.values._activeHoursTab, 'UNIQUE'],+ ['path_cleaning', { path_cleaning: 'false' }, () => logic.values._isPathCleaningEnabled, false],+ ['filter_test_accounts', { filter_test_accounts: 'true' }, () => logic.values.shouldFilterTestAccounts, true],+ ['include_host_path', { include_host_path: 'true' }, () => logic.values.includeHostPath, true],+ ['percentile', { percentile: 'p99' }, () => logic.values.webVitalsPercentile, 'p99'],+ // domain and device_type are owned by the connected webAnalyticsFilterLogic, so these also lock+ // restoration of cross-logic state.+ ['domain', { domain: 'example.com' }, () => logic.values.domainFilter, 'example.com'],+ ['device_type', { device_type: 'Desktop' }, () => logic.values.deviceTypeFilter, 'Desktop'],+ ])('restores %s from the URL into logic state', async (_name, searchParams, read, expected) => {+ router.actions.push('/web', searchParams)+ await expectLogic(logic).toFinishAllListeners()+ expect(read()).toEqual(expected)+ })++ it('restores an action conversion goal and couples the graphs tab to conversions', async () => {+ router.actions.push('/web', { 'conversionGoal.actionId': '42' })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.conversionGoal).toEqual({ actionId: 42 })+ // Restoring a conversion goal must drag the graphs tab onto conversions — the same coupling the+ // setConversionGoal reducer applies for a user-set goal.+ expect(logic.values._graphsTab).toBe(GraphsTab.UNIQUE_CONVERSIONS)+ })++ it('reconciles the URL when a restored param is normalised away', async () => {+ // A conversion goal makes PAGE_VIEWS an incompatible graphs tab, so restoration coerces it to+ // UNIQUE_USERS. The URL must be updated to match, or the visible chart and the shareable/reload+ // URL diverge (the per-action actionToUrl writes are suppressed during restore).+ router.actions.push('/web', { 'conversionGoal.actionId': '42', graphs_tab: 'PAGE_VIEWS' })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.graphsTab).toBe(GraphsTab.UNIQUE_USERS)+ expect(router.values.searchParams.graphs_tab).toBe(GraphsTab.UNIQUE_USERS)+ })++ it('restores the date range and interval from the URL', async () => {+ router.actions.push('/web', { date_from: '-30d', date_to: '-1d', interval: 'week' })+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.dateFilter).toMatchObject({ dateFrom: '-30d', dateTo: '-1d', interval: 'week' })+ })++ it.each<[string, Record<string, string>]>([+ ['tab params', { device_tab: 'BROWSER', source_tab: 'REFERRING_DOMAIN', path_tab: 'INITIAL_PATH' }],+ ['cross-logic filter params', { domain: 'example.com', device_type: 'Desktop', percentile: 'p99' }],+ ['mixed params', { device_tab: 'BROWSER', domain: 'example.com', include_host_path: 'true' }],+ ])('restores %s in a single router push, without the actionToUrl cascade', async (_name, searchParams) => {+ const pushSpy = jest.spyOn(router.actions, 'push')++ router.actions.push('/web', searchParams)+ await expectLogic(logic).toFinishAllListeners()++ // The only push is our own navigation; restoring state must not re-push the URL per param.+ expect(pushSpy).toHaveBeenCalledTimes(1)+ })++ it('redirects off the bots tab when the bot-analysis flag is disabled', async () => {+ router.actions.push('/web/bots')+ await expectLogic(logic).toFinishAllListeners()++ // The pathname is project-prefixed in tests (e.g. /project/997/web); assert we left the bots route.+ expect(router.values.location.pathname.endsWith('/web')).toBe(true)+ })++ it('defaults the bots tab to the last day when the URL carries no date', async () => {+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.WEB_ANALYTICS_BOT_ANALYSIS], {+ [FEATURE_FLAGS.WEB_ANALYTICS_BOT_ANALYSIS]: true,+ })++ router.actions.push('/web/bots')+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.productTab).toBe(ProductTab.BOT_ANALYTICS)+ expect(logic.values.dateFilter.dateFrom).toBe('-1d')+ })++ // kea-router parses search values, so booleans round-trip as booleans (include_host_path -> true).+ it.each<[string, () => void, string, unknown]>([+ ['setDeviceTab', () => logic.actions.setDeviceTab('BROWSER'), 'device_tab', 'BROWSER'],+ ['setSourceTab', () => logic.actions.setSourceTab('REFERRING_DOMAIN'), 'source_tab', 'REFERRING_DOMAIN'],+ ['setPathTab', () => logic.actions.setPathTab('INITIAL_PATH'), 'path_tab', 'INITIAL_PATH'],+ ['setGeographyTab', () => logic.actions.setGeographyTab('MAP'), 'geography_tab', 'MAP'],+ ['setIncludeHostPath', () => logic.actions.setIncludeHostPath(true), 'include_host_path', true],+ ])('mirrors %s back into the URL via actionToUrl', async (_name, act, key, expected) => {+ act()+ await expectLogic(logic).toFinishAllListeners()++ expect(router.values.searchParams[key]).toBe(expected)+ })+})diff --git a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsxindex 147427f633c2..481c2f91b853 100644--- a/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx+++ b/frontend/src/scenes/web-analytics/webAnalyticsLogic.tsx@@ -2480,8 +2480,8 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([actions.loadShouldShowGeoIPQueries()}),- trackedActionToUrl(({ values }) => {- const stateToUrl = (): string => {+ trackedActionToUrl(({ values, cache }) => {+ const buildStateUrl = (): string => {const urlParams = new URLSearchParams(router.values.location.search)const {@@ -2604,6 +2604,22 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([return `${basePath}${urlParams.toString() ? '?' + urlParams.toString() : ''}`}+ // Exposed so `urlToAction` can reconcile the URL against the restored state in a single write once+ // restoration finishes (see `reconcileUrlAfterRestore`), without re-implementing this serialization.+ cache.buildStateUrl = buildStateUrl++ const stateToUrl = (): string | undefined => {+ // While `urlToAction` is applying state from the URL, the actions it dispatches would each+ // re-enter `actionToUrl` and recompute the (already-current) URL. Returning `undefined` here+ // tells kea-router to skip the write, breaking the actionToUrl <-> urlToAction cascade that+ // otherwise fires a burst of redundant evaluations and trips the rapid-URL-change detector.+ // A single corrective write is emitted afterwards by `reconcileUrlAfterRestore`.+ if (cache.applyUrlStateDepth > 0) {+ return undefined+ }+ return buildStateUrl()+ }+return {setWebAnalyticsFilters: stateToUrl,togglePropertyFilter: stateToUrl,@@ -2627,8 +2643,8 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([}}),- urlToAction(({ actions, values }) => {- const toAction = (+ urlToAction(({ actions, values, cache }) => {+ const applyUrlState = ({ productTab = ProductTab.ANALYTICS }: { productTab?: ProductTab },{filters,@@ -2770,6 +2786,52 @@ export const webAnalyticsLogic = kea<webAnalyticsLogicType>([}}+ // Reconcile the URL with the restored state in a single write. Restoring can normalise state that+ // the incoming URL contradicts — e.g. a conversion goal coerces an incompatible `graphs_tab` onto a+ // conversion-compatible tab. The per-action `actionToUrl` writes are suppressed during restore (see+ // `stateToUrl`), so without this the visible chart state and the shareable/reload URL would diverge.+ // Only fire when a param the URL actually carried no longer matches the restored state, so a plain+ // restore doesn't rewrite the URL with canonical-only defaults.+ const reconcileUrlAfterRestore = (): void => {+ const canonicalUrl = cache.buildStateUrl?.()+ if (!canonicalUrl) {+ return+ }+ const queryStart = canonicalUrl.indexOf('?')+ const canonicalParams = new URLSearchParams(queryStart === -1 ? '' : canonicalUrl.slice(queryStart + 1))+ const currentParams = new URLSearchParams(router.values.location.search)+ let diverged = false+ currentParams.forEach((value, key) => {+ // Only a param that restoration re-serialized to a *different* value is a genuine+ // correction (e.g. `graphs_tab`). A param the current tab simply doesn't serialize back+ // (e.g. `percentile` outside web vitals) is left untouched, so a plain restore is a no-op.+ const canonicalValue = canonicalParams.get(key)+ if (canonicalValue !== null && canonicalValue !== value) {+ diverged = true+ }+ })+ if (diverged) {+ router.actions.replace(canonicalUrl)+ }+ }++ // Guard the state-restoration so the actions it dispatches don't write back to the URL via+ // `actionToUrl` (see `stateToUrl`). Restoring a URL with several params would otherwise fan out+ // into a burst of redundant URL evaluations and trip the rapid-URL-change detector. The depth+ // counter keeps the guard correct if a restore re-enters (e.g. the bots-flag redirect).+ const toAction = (params: { productTab?: ProductTab }, searchParams: Record<string, any>): void => {+ cache.applyUrlStateDepth = (cache.applyUrlStateDepth ?? 0) + 1+ try {+ applyUrlState(params, searchParams)+ } finally {+ cache.applyUrlStateDepth -= 1+ }+ // Only reconcile once unwound to the outermost restore, so a nested restore doesn't fire its own.+ if (cache.applyUrlStateDepth === 0) {+ reconcileUrlAfterRestore()+ }+ }+return {'/web': toAction,'/web/bots': (_, searchParams) => {