: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(insights): keep dashboard overrides on the insight back link (#95404)
Phillc4321c451a8c
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.tsindex 552a66f1afb4..47a6aab98702 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts@@ -175,6 +175,10 @@ describe('dashboardLogic', () => {11: {...dashboardResult(11, [], { date_from: '-24h' }),},+ 12: {+ ...dashboardResult(12, []),+ persisted_filters: { date_from: '-24h' },+ },13: {...dashboardResult(13, []),},@@ -203,6 +207,7 @@ describe('dashboardLogic', () => {'/api/environments/:team_id/dashboards/9/': { ...dashboards[9] },'/api/environments/:team_id/dashboards/10/': { ...dashboards[10] },'/api/environments/:team_id/dashboards/11/': { ...dashboards[11] },+ '/api/environments/:team_id/dashboards/12/': { ...dashboards[12] },'/api/environments/:team_id/dashboards/': {count: 6,next: null,@@ -1195,27 +1200,31 @@ describe('dashboardLogic', () => {describe('url filter overrides', () => {const PROPERTY_OVERRIDE = [{ key: '$browser', value: 'Chrome', type: 'event' }]- const openWithUrlFilters = async (urlFilters: Record<string, any>): Promise<void> => {+ // Dashboard 12 saves `date_from: '-24h'`; dashboard 5 saves no filters.+ const openWithUrlFilters = async (urlFilters: Record<string, any>, dashboardId = 5): Promise<void> => {logic.unmount()- router.actions.push('/dashboard/5', {+ router.actions.push(`/dashboard/${dashboardId}`, {[dashboardUtils.SEARCH_PARAM_FILTERS_KEY]: JSON.stringify(urlFilters),})- logic = dashboardLogic({ id: 5 })+ logic = dashboardLogic({ id: dashboardId })logic.mount()await expectLogic(logic).toFinishAllListeners()}// The overrides banner renders off hasUrlFilters. An override that constrains nothing still// has keys, so testing for key presence announces overrides on a dashboard that is showing- // exactly its saved state.- const activeOverrideCases: [string, Record<string, any>, boolean][] = [- ['a date override is active', { date_from: '-7d', date_to: null }, true],- ['a property override is active', { properties: PROPERTY_OVERRIDE }, true],- ['properties cleared to empty is not active', { properties: [] }, false],+ // exactly its saved state. A back link from an insight writes the saved filters into the url,+ // which is that same state.+ const activeOverrideCases: [string, Record<string, any>, number, boolean][] = [+ ['a date override is active', { date_from: '-7d', date_to: null }, 5, true],+ ['a property override is active', { properties: PROPERTY_OVERRIDE }, 5, true],+ ['properties cleared to empty is not active', { properties: [] }, 5, false],+ ['a url that repeats the saved filters is not active', { date_from: '-24h' }, 12, false],+ ['a url that changes a saved filter is active', { date_from: '-7d' }, 12, true],]- it.each(activeOverrideCases)('%s', async (_name, urlFilters, expected) => {- await openWithUrlFilters(urlFilters)+ it.each(activeOverrideCases)('%s', async (_name, urlFilters, dashboardId, expected) => {+ await openWithUrlFilters(urlFilters, dashboardId)expect(logic.values.hasUrlFilters).toBe(expected)})diff --git a/frontend/src/scenes/dashboard/dashboardUtils.test.ts b/frontend/src/scenes/dashboard/dashboardUtils.test.tsindex 23e1002a21a9..313a10b7ca60 100644--- a/frontend/src/scenes/dashboard/dashboardUtils.test.ts+++ b/frontend/src/scenes/dashboard/dashboardUtils.test.ts@@ -2,7 +2,7 @@ import api from 'lib/api'import { ApiError } from 'lib/api-error'import { dayjs } from 'lib/dayjs'-import { BreakdownFilter } from '~/queries/schema/schema-general'+import { BreakdownFilter, DashboardFilter, HogQLVariable } from '~/queries/schema/schema-general'import {AnyPropertyFilter,DashboardPlacement,@@ -15,6 +15,7 @@ import {} from '~/types'import {+ dashboardSearchParamsFromOverrides,dashboardToSaveableTemplate,searchParamsWithUrlFilters,getDashboardTileDisplayName,@@ -234,6 +235,36 @@ describe('parseURLFilters', () => {})})+describe('dashboardSearchParamsFromOverrides', () => {+ const variableId = '00000000-0000-0000-0000-00000000beef'+ const cardNameVariable = (overrides: Partial<HogQLVariable>): Record<string, HogQLVariable> => ({+ [variableId]: { variableId, code_name: 'card_name', ...overrides },+ })++ it.each<+ [string, Record<string, HogQLVariable> | null, DashboardFilter | null, Record<string, any>, DashboardFilter]+ >([+ [+ 'a variable value',+ cardNameVariable({ value: 'Polukranos, Unchained' }),+ null,+ { card_name: 'Polukranos, Unchained' },+ {},+ ],+ ['a variable set to null', cardNameVariable({ value: 'ignored', isNull: true }), null, { card_name: null }, {}],+ ['a filter override', null, { date_from: '-7d' }, {}, { date_from: '-7d' }],+ ['nothing when there are no overrides', null, {}, {}, {}],+ ])(+ 'carries %s back into the dashboard URL',+ (_name, variablesOverride, filtersOverride, expectedVariables, expectedFilters) => {+ const searchParams = dashboardSearchParamsFromOverrides(variablesOverride, filtersOverride)++ expect(parseURLVariables(searchParams)).toEqual(expectedVariables)+ expect(parseURLFilters(searchParams)).toEqual(expectedFilters)+ }+ )+})+describe('getInsightWithRetry', () => {const insight = { id: 300, short_id: 'abc123', name: 'Test insight' } as QueryBasedInsightModelconst MAX_ATTEMPTS = 3diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.tsindex 78bd31321fe7..d84711f56faf 100644--- a/frontend/src/scenes/dashboard/dashboardUtils.ts+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts@@ -422,7 +422,7 @@ export const parseURLVariables = (searchParams: Record<string, any>): Record<strreturn variables}-export const encodeURLVariables = (variables: Record<string, string>): Record<string, string> => {+export const encodeURLVariables = (variables: Record<string, any>): Record<string, string> => {const encodedVariables: Record<string, string> = {}if (Object.keys(variables).length > 0) {@@ -460,6 +460,29 @@ export const encodeURLFilters = (filters: DashboardFilter): Record<string, strinreturn encodedFilters}+/**+ * An insight opened from a dashboard keys its variable overrides by variable id, while the dashboard URL keys them+ * by code name. Convert them back so a link to the dashboard reopens it with the same filters and variable values.+ */+export const dashboardSearchParamsFromOverrides = (+ variablesOverride: Record<string, HogQLVariable> | null | undefined,+ filtersOverride: DashboardFilter | null | undefined+): Record<string, string> => {+ const urlVariables: Record<string, any> = {}++ for (const variable of Object.values(variablesOverride ?? {})) {+ if (!variable?.code_name) {+ continue+ }+ const value = variable.isNull ? null : variable.value+ if (value !== undefined) {+ urlVariables[variable.code_name] = value+ }+ }++ return { ...encodeURLVariables(urlVariables), ...encodeURLFilters(filtersOverride ?? {}) }+}+/*** An empty override must stay in the URL when it clears a saved dashboard filter. Without that explicit* value, a reload restores the saved filter. Empty overrides on unfiltered dashboards can be removed.diff --git a/frontend/src/scenes/insights/insightSceneLogic.test.ts b/frontend/src/scenes/insights/insightSceneLogic.test.tsindex 395321bacc3b..754030a44885 100644--- a/frontend/src/scenes/insights/insightSceneLogic.test.ts+++ b/frontend/src/scenes/insights/insightSceneLogic.test.ts@@ -4,6 +4,7 @@ import { combineUrl, router } from 'kea-router'import { expectLogic, partial } from 'kea-test-utils'import { addProjectIdIfMissing } from 'lib/utils/kea-router'+import { parseURLFilters, parseURLVariables } from 'scenes/dashboard/dashboardUtils'import { insightSceneLogic } from 'scenes/insights/insightSceneLogic'import { sceneLogic } from 'scenes/sceneLogic'import { Scene } from 'scenes/sceneTypes'@@ -11,7 +12,7 @@ import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'import { examples } from '~/queries/examples'-import { InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-general'+import { DashboardFilter, HogQLVariable, InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-general'import { setLatestVersionsOnQuery } from '~/queries/utils'import { initKeaTests } from '~/test/init'import { ActivityScope, InsightShortId, InsightType, ItemMode } from '~/types'@@ -360,6 +361,46 @@ describe('insightSceneLogic', () => {expect(logic.values.insightLogicRef?.logic.values.insight.dashboards).toEqual([6])})+ const VARIABLE_ID = '00000000-0000-0000-0000-00000000beef'+ const CARD_NAME_OVERRIDE: Record<string, HogQLVariable> = {+ [VARIABLE_ID]: {+ variableId: VARIABLE_ID,+ code_name: 'card_name',+ value: 'Polukranos, Unchained',+ isNull: false,+ },+ }++ it.each<+ [+ string,+ Record<string, HogQLVariable> | undefined,+ DashboardFilter | undefined,+ Record<string, any>,+ DashboardFilter,+ ]+ >([+ ['a variable value', CARD_NAME_OVERRIDE, undefined, { card_name: 'Polukranos, Unchained' }, {}],+ ['a filter that clears a saved one', undefined, { properties: [] }, {}, { properties: [] }],+ ])(+ 'points the dashboard breadcrumb back at the dashboard with %s',+ async (_name, variablesOverride, filtersOverride, expectedVariables, expectedFilters) => {+ router.actions.push(urls.insightView(Insight42, 6, variablesOverride, filtersOverride))+ logic = insightSceneLogic()+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ const dashboardBreadcrumb = logic.values.breadcrumbs.find(+ (breadcrumb) => breadcrumb.key === Scene.Dashboard+ )+ const { pathname, searchParams } = combineUrl(dashboardBreadcrumb?.path ?? '')++ expect(pathname).toEqual(urls.dashboard(6))+ expect(parseURLVariables(searchParams)).toEqual(expectedVariables)+ expect(parseURLFilters(searchParams)).toEqual(expectedFilters)+ }+ )+it('remounts when URL insight id disagrees with dashboard tile id on the mounted editor (save-as regression)', async () => {useMocks({get: {diff --git a/frontend/src/scenes/insights/insightSceneLogic.tsx b/frontend/src/scenes/insights/insightSceneLogic.tsxindex 4a4141e3d155..2773dc732681 100644--- a/frontend/src/scenes/insights/insightSceneLogic.tsx+++ b/frontend/src/scenes/insights/insightSceneLogic.tsx@@ -11,7 +11,7 @@ import {sharedListeners,} from 'kea'import type { BreakPointFunction } from 'kea'-import { urlToAction } from 'kea-router'+import { combineUrl, router, urlToAction } from 'kea-router'import { objectsEqual } from 'kea-test-utils'import posthog from 'posthog-js'@@ -22,6 +22,11 @@ import { InsightEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'import { isEmptyObject, isObject } from 'lib/utils/guards'import { isDashboardFilterEmpty } from 'scenes/dashboard/dashboardFilterEmpty'import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'+import {+ SEARCH_PARAM_FILTERS_KEY,+ dashboardSearchParamsFromOverrides,+ parseURLFilters,+} from 'scenes/dashboard/dashboardUtils'import { createEmptyInsight, insightLogic } from 'scenes/insights/insightLogic'import type { insightLogicType } from 'scenes/insights/insightLogic'import { MaxContextInput, createMaxContextHelpers } from 'scenes/max/maxTypes'@@ -118,6 +123,7 @@ export interface insightSceneLogicValues {currentTeamId: number | null // teamLogicalertId: AlertType['id'] | nullbreadcrumbs: Breadcrumb[]+ dashboardBackPath: string | nulldashboardId: DashboardType['id'] | nulldashboardName: DashboardType['name'] | nullfiltersOverride: DashboardFilter | null@@ -264,6 +270,11 @@ export interface insightSceneLogicMeta {insight: (arg: Partial<QueryBasedInsightModel<Node<Record<string, any>>>> | null | undefined) => Partial<QueryBasedInsightModel<Node<Record<string, any>>>> | null | undefined+ dashboardBackPath: (+ dashboardId: number | null,+ variablesOverride: Record<string, HogQLVariable> | null,+ searchParams: Record<string, any>+ ) => string | nullbreadcrumbs: (insightLogicRef: {logic: BuiltLogic<insightLogicType>@@ -273,7 +284,8 @@ export interface insightSceneLogicMeta {insightQuery: Node<Record<string, any>> | null | undefined,dashboardId: number | null,dashboardName: string | null,- sceneSource: InsightSceneSource | null+ sceneSource: InsightSceneSource | null,+ dashboardBackPath: string | null) => Breadcrumb[]projectTreeRef: (insightId: InsightId) => ProjectTreeRefsidePanelContext: (@@ -511,8 +523,37 @@ export const insightSceneLogic = kea<insightSceneLogicType>([],(insight: Partial<QueryBasedInsightModel<Node<Record<string, any>>>> | null | undefined) => insight,],+ // The insight and the dashboard name the same overrides differently, so a link back to the dashboard+ // has to translate them. Take the filters from the url instead of from `filtersOverride`, because an+ // override that clears a saved dashboard filter reads as empty and normalizes to null on the way into+ // scene state. The dashboard needs that explicit empty value, or it restores the saved filter.+ dashboardBackPath: [+ (s) => [s.dashboardId, s.variablesOverride, router.selectors.searchParams],+ (+ dashboardId: DashboardType['id'] | null,+ variablesOverride: Record<string, HogQLVariable> | null,+ searchParams: Record<string, any>+ ): string | null =>+ dashboardId === null+ ? null+ : combineUrl(+ urls.dashboard(dashboardId),+ dashboardSearchParamsFromOverrides(+ variablesOverride,+ parseURLFilters({ [SEARCH_PARAM_FILTERS_KEY]: searchParams['filters_override'] })+ )+ ).url,+ ],breadcrumbs: [- (s) => [s.insightLogicRef, s.insight, s.insightQuery, s.dashboardId, s.dashboardName, s.sceneSource],+ (s) => [+ s.insightLogicRef,+ s.insight,+ s.insightQuery,+ s.dashboardId,+ s.dashboardName,+ s.sceneSource,+ s.dashboardBackPath,+ ],(insightLogicRef: {logic: BuiltLogic<insightLogicType>@@ -522,7 +563,8 @@ export const insightSceneLogic = kea<insightSceneLogicType>([insightQuery: Node<Record<string, any>> | null | undefined,dashboardId: DashboardType['id'] | null,dashboardName: DashboardType['name'] | null,- sceneSource: InsightSceneSource | null+ sceneSource: InsightSceneSource | null,+ dashboardBackPath: string | null): Breadcrumb[] => {const dashboardLabel = dashboardName ?? 'Dashboard'return [@@ -537,7 +579,8 @@ export const insightSceneLogic = kea<insightSceneLogicType>([{key: Scene.Dashboard,name: dashboardLabel,- path: urls.dashboard(dashboardId),+ // Going back must land on the dashboard as the user left it, not on its saved state+ path: dashboardBackPath ?? urls.dashboard(dashboardId),iconType: 'dashboard' as FileSystemIconType,},]