: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): only persist drafts for meaningfully edited queries (#73074)
Thomas Obermüllercd96d2821c32
diff --git a/frontend/src/scenes/insights/insightDataLogic.test.ts b/frontend/src/scenes/insights/insightDataLogic.test.tsindex 7384bd693619..14756715fc12 100644--- a/frontend/src/scenes/insights/insightDataLogic.test.ts+++ b/frontend/src/scenes/insights/insightDataLogic.test.ts@@ -4,6 +4,8 @@ jest.mock('~/queries/query', () => ({performQuery: jest.fn().mockResolvedValue({ result: [] }),}))+import { MOCK_TEAM_ID } from 'lib/api.mock'+import { expectLogic } from 'kea-test-utils'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'@@ -20,6 +22,7 @@ import { performQuery } from '~/queries/query'import {FunnelsQuery,InsightVizNode,+ Node,NodeKind,ResultCustomizationBy,TrendsQuery,@@ -552,4 +555,66 @@ describe('insightDataLogic', () => {}})})++ describe('draft query persistence', () => {+ const draftKey = `draft-query-${MOCK_TEAM_ID}`+ const newInsightQuery = (mutate?: (query: any) => void): Node => {+ const query = JSON.parse(JSON.stringify(getDefaultQuery(InsightType.TRENDS, false)))+ mutate?.(query)+ return query+ }++ let logic: ReturnType<typeof insightDataLogic.build>++ beforeEach(() => {+ localStorage.removeItem(draftKey)+ sceneLogic.mount()+ sceneLogic.actions.setScene(Scene.Insight, undefined, {} as any)+ logic = insightDataLogic({ dashboardItemId: 'new' })+ logic.mount()+ })++ afterEach(() => {+ logic.unmount()+ sceneLogic.unmount()+ localStorage.removeItem(draftKey)+ })++ const cosmeticOnlyEdit = (q: any): void => {+ q.source.dateRange = { date_from: '-90d' }+ }+ const tooLargeEdit = (q: any): void => {+ q.source.series[0].event = 'x'.repeat(1024 * 1024 + 1)+ }++ it.each([+ ['reverts to a cosmetic-only diff', cosmeticOnlyEdit],+ ['grows too large to store', tooLargeEdit],+ ])('clears the draft it persisted when the query %s', async (_, mutate) => {+ await expectLogic(logic, () => {+ logic.actions.setQuery(newInsightQuery((q) => (q.source.series[0].event = 'purchase')))+ }).toFinishAllListeners()+ expect(localStorage.getItem(draftKey)).not.toBeNull()++ await expectLogic(logic, () => {+ logic.actions.setQuery(newInsightQuery(mutate))+ }).toFinishAllListeners()+ expect(localStorage.getItem(draftKey)).toBeNull()+ })++ it.each([+ ['a cosmetic-only query', cosmeticOnlyEdit],+ ['a too-large query', tooLargeEdit],+ ])(+ "does not clear another session's draft when it has not persisted one itself and sets %s",+ async (_, mutate) => {+ localStorage.setItem(draftKey, JSON.stringify({ query: { kind: 'TrendsQuery' }, timestamp: 1 }))++ await expectLogic(logic, () => {+ logic.actions.setQuery(newInsightQuery(mutate))+ }).toFinishAllListeners()+ expect(localStorage.getItem(draftKey)).not.toBeNull()+ }+ )+ })})diff --git a/frontend/src/scenes/insights/insightDataLogic.tsx b/frontend/src/scenes/insights/insightDataLogic.tsxindex edd2c5f13be2..155ab1508906 100644--- a/frontend/src/scenes/insights/insightDataLogic.tsx+++ b/frontend/src/scenes/insights/insightDataLogic.tsx@@ -87,7 +87,7 @@ import { insightLogic } from './insightLogic'import { insightSceneLogic } from './insightSceneLogic'import { insightUsageLogic } from './insightUsageLogic'import { crushDraftQueryForLocalStorage, isQueryTooLarge } from './utils'-import { compareQuery } from './utils/queryUtils'+import { compareQuery, isDraftQueryWorthSaving } from './utils/queryUtils'export const isInsightSceneInstance = (props: InsightLogicProps): boolean =>sceneLogic.values.activeSceneId === Scene.Insight &&@@ -706,7 +706,7 @@ export const insightDataLogic = kea<insightDataLogicType>([],}),- listeners(({ actions, values, props }) => ({+ listeners(({ actions, cache, values, props }) => ({persistDisplayOptions: async ({ query }, breakpoint) => {// Never auto-persist while the user is editing this insight in the insight scene.// insightDataLogic is keyed `${shortId}/on-dashboard-${dashboardId}`, so an insight@@ -818,14 +818,32 @@ export const insightDataLogic = kea<insightDataLogicType>([}}+ // a draft that only differs from the type's default in cosmetic ways (or that the+ // editor marks as changed by construction) is noise when resurfaced as "unsaved insight"+ if (!isDraftQueryWorthSaving(query, values.filterTestAccountsDefault)) {+ // reverting a meaningful edit supersedes the draft this editor persisted — but an+ // editor that never persisted one must not delete a draft from an earlier session+ if (cache.persistedDraftQuery) {+ cache.persistedDraftQuery = false+ localStorage.removeItem(`draft-query-${values.currentTeamId}`)+ }+ return+ }+if (isQueryTooLarge(query)) {- localStorage.removeItem(`draft-query-${values.currentTeamId}`)+ // same gating as above: only supersede a draft this editor persisted itself+ if (cache.persistedDraftQuery) {+ cache.persistedDraftQuery = false+ localStorage.removeItem(`draft-query-${values.currentTeamId}`)+ }+ return}localStorage.setItem(`draft-query-${values.currentTeamId}`,crushDraftQueryForLocalStorage(query, Date.now()))+ cache.persistedDraftQuery = true},})),propsChanged(({ actions, props, values }, oldProps) => {diff --git a/frontend/src/scenes/insights/insightLogic.test.ts b/frontend/src/scenes/insights/insightLogic.test.tsindex 8b91c2cf498d..e44690b3fb74 100644--- a/frontend/src/scenes/insights/insightLogic.test.ts+++ b/frontend/src/scenes/insights/insightLogic.test.ts@@ -577,6 +577,32 @@ describe('insightLogic', () => {await expectLogic(logic).toDispatchActions([savedInsightsLogic().actionTypes.updateInsight])})+ test('saveInsight clears the browser draft only when saving a new insight', async () => {+ const draftKey = `draft-query-${MOCK_TEAM_ID}`+ localStorage.setItem(draftKey, JSON.stringify({ query: { kind: 'TrendsQuery' }, timestamp: 1 }))++ const updateProps: InsightLogicProps = {+ dashboardItemId: Insight42,+ cachedInsight: { id: 42, short_id: Insight42, query: examples.FunnelsQuery, result: {} },+ }+ logic = insightLogic(updateProps)+ logic.mount()+ insightDataLogic(updateProps).mount()+ await expectLogic(logic, () => {+ logic.actions.saveInsight()+ }).toFinishAllListeners()+ expect(localStorage.getItem(draftKey)).not.toBeNull()++ const newProps: InsightLogicProps = { dashboardItemId: 'new' }+ logic = insightLogic(newProps)+ logic.mount()+ insightDataLogic(newProps).mount()+ await expectLogic(logic, () => {+ logic.actions.saveInsight()+ }).toFinishAllListeners()+ expect(localStorage.getItem(draftKey)).toBeNull()+ })+test('saveInsight updates dashboards', async () => {const dashLogic = dashboardLogic({ id: MOCK_DASHBOARD_ID })dashLogic.mount()diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsxindex 93ee294b6c07..3abb13bc9f5c 100644--- a/frontend/src/scenes/insights/insightLogic.tsx+++ b/frontend/src/scenes/insights/insightLogic.tsx@@ -1055,8 +1055,11 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicTypealertsLogic.actions.loadAlerts()}}- // remove draft query from local storage- localStorage.removeItem(`draft-query-${values.currentTeamId}`)+ if (!insightNumericId) {+ // saving the new insight consumes its draft; updating an existing insight+ // must leave the (unrelated) draft alone+ localStorage.removeItem(`draft-query-${values.currentTeamId}`)+ }actions.saveInsightSuccess()} catch (e) {actions.saveInsightFailure()diff --git a/frontend/src/scenes/insights/utils/queryUtils.test.ts b/frontend/src/scenes/insights/utils/queryUtils.test.tsindex d5f8af09ba06..06d896e07ffd 100644--- a/frontend/src/scenes/insights/utils/queryUtils.test.ts+++ b/frontend/src/scenes/insights/utils/queryUtils.test.ts@@ -1,10 +1,13 @@-import { NodeKind, TrendsFilter, TrendsQuery } from '~/queries/schema/schema-general'+import { getDefaultQuery } from '~/queries/nodes/InsightViz/utils'+import { Node, NodeKind, TrendsFilter, TrendsQuery } from '~/queries/schema/schema-general'+import { InsightType } from '~/types'import {compareQuery,filterVariablesReferencedInQuery,hasInvalidRegexFilter,isBoxPlotMissingProperty,+ isDraftQueryWorthSaving,syncSelectedVariablesToQuery,validateQuery,} from './queryUtils'@@ -234,3 +237,54 @@ describe('compareQuery', () => {expect(compareQuery(plain, styled)).toBe(false)})})++describe('isDraftQueryWorthSaving', () => {+ const trends = (mutate?: (query: any) => void): Node => {+ const query = JSON.parse(JSON.stringify(getDefaultQuery(InsightType.TRENDS, false)))+ mutate?.(query)+ return query+ }++ it.each<[string, Node, boolean]>([+ ['an untouched default', trends(), false],+ ['only a changed date range', trends((q) => (q.source.dateRange = { date_from: '-90d' })), false],+ ['only a changed interval', trends((q) => (q.source.interval = 'week')), false],+ ['only the test account toggle', trends((q) => (q.source.filterTestAccounts = true)), false],+ ['only a changed display option', trends((q) => (q.source.trendsFilter = { display: 'ActionsPie' })), false],+ [+ 'an untouched default with editor-attached query log tags',+ trends((q) => (q.source.tags = { productKey: 'product_analytics' })),+ false,+ ],+ ['a changed series event', trends((q) => (q.source.series[0].event = 'purchase')), true],+ [+ 'an added series',+ trends((q) => q.source.series.push({ kind: NodeKind.EventsNode, event: '$pageview', math: 'dau' })),+ true,+ ],+ [+ 'an added breakdown',+ trends((q) => (q.source.breakdownFilter = { breakdown: '$browser', breakdown_type: 'event' })),+ true,+ ],+ [+ 'an added property filter',+ trends(+ (q) =>+ (q.source.properties = [{ type: 'event', key: '$browser', operator: 'exact', value: ['Chrome'] }])+ ),+ true,+ ],+ [+ 'a web analytics tile query',+ {+ kind: NodeKind.InsightVizNode,+ source: { kind: NodeKind.WebOverviewQuery, properties: [] },+ } as unknown as Node,+ false,+ ],+ ['an events table query', getDefaultQuery(InsightType.JSON, false), true],+ ])('treats %s correctly', (_name, query, expected) => {+ expect(isDraftQueryWorthSaving(query, false)).toBe(expected)+ })+})diff --git a/frontend/src/scenes/insights/utils/queryUtils.ts b/frontend/src/scenes/insights/utils/queryUtils.tsindex 6c553ba1ecc6..786b4fc013d5 100644--- a/frontend/src/scenes/insights/utils/queryUtils.ts+++ b/frontend/src/scenes/insights/utils/queryUtils.ts@@ -3,9 +3,20 @@ import { isValidRE2 } from 'lib/utils/regexp'import { isFunnelWithEnoughSteps, isFunnelWithIncompleteDataWarehouseStep } from 'scenes/funnels/funnelUtils'import { Variable } from '~/queries/nodes/DataVisualization/types'-import { DataNode, HogQLVariable, InsightQueryNode, Node, TrendsQuery } from '~/queries/schema/schema-general'+import { nodeKindToInsightType } from '~/queries/nodes/InsightQuery/utils/queryNodeToFilter'+import { getDefaultQuery } from '~/queries/nodes/InsightViz/utils'+import {+ DataNode,+ HogQLVariable,+ InsightQueryNode,+ InsightVizNode,+ Node,+ ProductAnalyticsInsightQueryNode,+ TrendsQuery,+} from '~/queries/schema/schema-general'import {filterForQuery,+ filterKeyForQuery,getMathTypeWarning,isEventsNode,isFunnelsQuery,@@ -133,6 +144,53 @@ export const compareDataNodeQuery = (a: Node, b: Node, opts?: CompareQueryOpts):return objectsEqual(objectCleanWithEmpty(a as any), objectCleanWithEmpty(b as any))}+/**+ * Whether an unsaved query is worth persisting as a browser draft (and later resurfacing as an+ * "unsaved insight" on the saved insights page).+ *+ * Skips queries that only differ from their type's default in cosmetic ways (date range, interval,+ * test account toggle, display options), and query kinds that `queryChanged` treats as changed by+ * construction (web analytics tiles, kinds without a product analytics default) — for those,+ * merely opening the editor would persist a draft the user never edited.+ */+export const isDraftQueryWorthSaving = (query: Node, filterTestAccountsDefault: boolean): boolean => {+ if (!isInsightVizNode(query)) {+ // Tables and SQL drafts have no cheap default to compare against+ return true+ }+ if (isWebAnalyticsInsightQuery(query.source) || !(query.source.kind in nodeKindToInsightType)) {+ return false+ }+ const source = query.source as ProductAnalyticsInsightQueryNode+ let defaultQuery: Node+ try {+ defaultQuery = getDefaultQuery(nodeKindToInsightType[source.kind], filterTestAccountsDefault)+ } catch {+ return true+ }+ if (!isInsightVizNode(defaultQuery)) {+ return true+ }+ // Overlay the draft's cosmetic fields onto the default: if that alone makes the two equal,+ // nothing worth resurfacing was edited. `tags` is query log metadata the editor attaches on+ // scene init (see `withDefaultProductAnalyticsTags`), never a user edit, so it's overlaid too.+ const draftSource = source as Record<string, any>+ const overlaidSource: Record<string, any> = { ...defaultQuery.source }+ for (const key of ['dateRange', 'interval', 'filterTestAccounts', 'tags']) {+ if (key in draftSource) {+ overlaidSource[key] = draftSource[key]+ } else {+ delete overlaidSource[key]+ }+ }+ const filterKey = filterKeyForQuery(source)+ if (draftSource[filterKey]?.display) {+ overlaidSource[filterKey] = { ...overlaidSource[filterKey], display: draftSource[filterKey].display }+ }+ const overlaidDefault: InsightVizNode = { ...defaultQuery, source: overlaidSource as InsightQueryNode }+ return !compareQuery(overlaidDefault, query, { ignoreVisualizationOnlyChanges: true })+}+export const hasInvalidRegexFilter = (obj: unknown): boolean => {if (Array.isArray(obj)) {return obj.some(hasInvalidRegexFilter)