Skip to content

: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.

fix(insights): stop the AI change notice listing untouched sections (#93164)

Thomas Obermüllerbe6aca8b3c34
diff --git a/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.test.ts b/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.test.ts
index 22d54cd1da83..33621fb4d163 100644
--- a/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.test.ts
+++ b/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.test.ts
@@ -1,29 +1,96 @@
-import { NodeKind } from '~/queries/schema/schema-general'
-
-import { buildInsightNodeFromQueryTool } from './EditorFiltersShell'
-
-describe('buildInsightNodeFromQueryTool', () => {
- it.each([
- ['query-trends', NodeKind.TrendsQuery],
- ['query-funnel', NodeKind.FunnelsQuery],
- ['query-retention', NodeKind.RetentionQuery],
- ['query-paths', NodeKind.PathsQuery],
- ['query-stickiness', NodeKind.StickinessQuery],
- ['query-lifecycle', NodeKind.LifecycleQuery],
- ])('wraps %s input into an InsightVizNode with kind %s', (toolName, kind) => {
- const innerInput = { series: [{ event: '$pageview' }] }
-
- expect(buildInsightNodeFromQueryTool(toolName, innerInput)).toEqual({
- kind: NodeKind.InsightVizNode,
- source: { ...innerInput, kind },
+import { InsightVizNode, NodeKind, TrendsQuery } from '~/queries/schema/schema-general'
+import { checkLatestVersionsOnQuery } from '~/queries/utils'
+
+import { buildInsightNodeFromQueryTool, withCurrentQueryMetadata } from './EditorFiltersShell'
+
+describe('EditorFiltersShell', () => {
+ describe('buildInsightNodeFromQueryTool', () => {
+ it.each([
+ ['query-trends', NodeKind.TrendsQuery],
+ ['query-funnel', NodeKind.FunnelsQuery],
+ ['query-retention', NodeKind.RetentionQuery],
+ ['query-paths', NodeKind.PathsQuery],
+ ['query-stickiness', NodeKind.StickinessQuery],
+ ['query-lifecycle', NodeKind.LifecycleQuery],
+ ])('wraps %s input into an InsightVizNode with kind %s', (toolName, kind) => {
+ const innerInput = { series: [{ event: '$pageview' }] }
+
+ expect(buildInsightNodeFromQueryTool(toolName, innerInput)).toEqual({
+ kind: NodeKind.InsightVizNode,
+ source: { ...innerInput, kind },
+ })
+ })
+
+ it('returns null for a tool name outside the core query-* set (e.g. an actors drill-down)', () => {
+ expect(buildInsightNodeFromQueryTool('query-trends-actors', { series: [] })).toBeNull()
})
- })
- it('returns null for a tool name outside the core query-* set (e.g. an actors drill-down)', () => {
- expect(buildInsightNodeFromQueryTool('query-trends-actors', { series: [] })).toBeNull()
+ it('returns null when the inner input is null', () => {
+ expect(buildInsightNodeFromQueryTool('query-trends', null)).toBeNull()
+ })
})
- it('returns null when the inner input is null', () => {
- expect(buildInsightNodeFromQueryTool('query-trends', null)).toBeNull()
+ describe('withCurrentQueryMetadata', () => {
+ const suggested: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageleave' }],
+ },
+ }
+
+ it('carries the current query log tags over and stamps the latest schema versions', () => {
+ const currentSource: TrendsQuery = {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
+ tags: { productKey: 'product_analytics' },
+ }
+
+ const node = withCurrentQueryMetadata(suggested, currentSource)
+
+ expect(node.source.tags).toEqual({ productKey: 'product_analytics' })
+ expect(checkLatestVersionsOnQuery(node)).toBe(true)
+ })
+
+ it('adds no tags key when the current query has none', () => {
+ const node = withCurrentQueryMetadata(suggested, {
+ kind: NodeKind.TrendsQuery,
+ series: [],
+ })
+
+ expect('tags' in node.source).toBe(false)
+ })
+
+ it('carries the current query modifiers over when the suggestion sets none', () => {
+ const currentSource: TrendsQuery = {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
+ modifiers: { personsOnEventsMode: 'person_id_override_properties_joined' },
+ }
+
+ const node = withCurrentQueryMetadata(suggested, currentSource)
+
+ expect(node.source.modifiers).toEqual({ personsOnEventsMode: 'person_id_override_properties_joined' })
+ })
+
+ it('keeps the suggestion modifiers when it sets its own', () => {
+ const suggestedWithModifiers: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageleave' }],
+ modifiers: { personsOnEventsMode: 'disabled' },
+ },
+ }
+ const currentSource: TrendsQuery = {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
+ modifiers: { personsOnEventsMode: 'person_id_override_properties_joined' },
+ }
+
+ const node = withCurrentQueryMetadata(suggestedWithModifiers, currentSource)
+
+ expect(node.source.modifiers).toEqual({ personsOnEventsMode: 'disabled' })
+ })
})
})
diff --git a/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.tsx b/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.tsx
index b8135c2f95ff..ac68fc0a5001 100644
--- a/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.tsx
+++ b/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.tsx
@@ -22,10 +22,11 @@ import {
DataVisualizationNode,
InsightQueryNode,
InsightVizNode,
+ Node,
NodeKind,
QuerySchema,
} from '~/queries/schema/schema-general'
-import { isHogQLQuery, isInsightQueryNode } from '~/queries/utils'
+import { isHogQLQuery, isInsightQueryNode, setLatestVersionsOnQuery } from '~/queries/utils'
import { useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'
@@ -75,6 +76,30 @@ export function buildInsightNodeFromQueryTool(
return { kind: NodeKind.InsightVizNode, source } satisfies InsightVizNode
}
+/**
+ * Restore the query metadata a tool result can't carry: the query log tags of the query being
+ * edited, and the latest schema versions. Without the tags the applied query loses its product
+ * attribution, and without the versions the backend migrates a query that is already current.
+ *
+ * Also carries over the current query's modifiers (e.g. persons-on-events mode) when the
+ * suggestion doesn't set its own. A tool result arrives without modifiers, so applying it bare
+ * would silently reset a setting the user chose.
+ */
+export function withCurrentQueryMetadata<T extends Node>(node: T, currentSource?: InsightQueryNode | null): T {
+ const stamped = setLatestVersionsOnQuery(node) as T & { source?: Record<string, unknown> }
+ if (!currentSource || !stamped.source) {
+ return stamped
+ }
+ const carried: Record<string, unknown> = {}
+ if (currentSource.tags) {
+ carried.tags = currentSource.tags
+ }
+ if (currentSource.modifiers && !stamped.source.modifiers) {
+ carried.modifiers = currentSource.modifiers
+ }
+ return Object.keys(carried).length > 0 ? { ...stamped, source: { ...stamped.source, ...carried } } : stamped
+}
+
export function EditorFiltersShell({ query, showing, embedded, children }: EditorFiltersShellProps): JSX.Element {
const { insightProps } = useValues(insightLogic)
const { querySource, shouldShowSessionAnalysisWarning } = useValues(insightVizDataLogic(insightProps))
@@ -108,10 +133,11 @@ export function EditorFiltersShell({ query, showing, embedded, children }: Edito
if (!maxToolActive || !innerInput) {
return
}
- const node = buildInsightNodeFromQueryTool(event.toolName, innerInput)
- if (!node) {
+ const builtNode = buildInsightNodeFromQueryTool(event.toolName, innerInput)
+ if (!builtNode) {
return
}
+ const node = withCurrentQueryMetadata(builtNode, querySource)
handleInsightSuggested(node)
setQuery(node)
},
@@ -153,17 +179,18 @@ export function EditorFiltersShell({ query, showing, embedded, children }: Edito
if (!source) {
return
}
- let node: QuerySchema
+ let builtNode: QuerySchema
if (isHogQLQuery(source)) {
- node = {
+ builtNode = {
kind: NodeKind.DataVisualizationNode,
source,
} satisfies DataVisualizationNode
} else if (isInsightQueryNode(source)) {
- node = { kind: NodeKind.InsightVizNode, source } satisfies InsightVizNode
+ builtNode = { kind: NodeKind.InsightVizNode, source } satisfies InsightVizNode
} else {
- node = source
+ builtNode = source
}
+ const node = withCurrentQueryMetadata(builtNode, querySource)
handleInsightSuggested(node)
setQuery(node)
}}
diff --git a/frontend/src/scenes/insights/utils.test.ts b/frontend/src/scenes/insights/utils.test.ts
index 522c2e84a781..8bfe31da5e05 100644
--- a/frontend/src/scenes/insights/utils.test.ts
+++ b/frontend/src/scenes/insights/utils.test.ts
@@ -10,11 +10,19 @@ import {
getTrendDatasetKey,
NOT_IN_COHORT_ID,
} from 'scenes/insights/utils'
+import { teamLogic } from 'scenes/teamLogic'
import { IndexedTrendResult } from 'scenes/trends/types'
-import { ActionsNode, BreakdownFilter, EventsNode, InsightQueryNode, NodeKind } from '~/queries/schema/schema-general'
+import {
+ ActionsNode,
+ BreakdownFilter,
+ EventsNode,
+ InsightQueryNode,
+ InsightVizNode,
+ NodeKind,
+} from '~/queries/schema/schema-general'
import { isEventsNode } from '~/queries/utils'
-import { CompareLabelType, Entity, EntityFilter, FilterType, InsightType } from '~/types'
+import { BaseMathType, CompareLabelType, Entity, EntityFilter, FilterType, InsightType, TeamType } from '~/types'
const createFilter = (id?: Entity['id'], name?: string, custom_name?: string): EntityFilter => {
return {
@@ -804,6 +812,80 @@ describe('compareTopLevelSections()', () => {
expect(compareInsightTopLevelSections(obj1, obj2)).toEqual([])
})
+ it('ignores query plumbing and empty sections on a wrapped insight query', () => {
+ const previous: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ version: 3,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview', math: BaseMathType.TotalCount }],
+ trendsFilter: {},
+ tags: { productKey: 'product_analytics' },
+ },
+ }
+ const suggested: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageleave' }],
+ },
+ }
+
+ expect(compareInsightTopLevelSections(previous, suggested)).toEqual(['Series'])
+ })
+
+ it('reports a modifiers change when the current query overrides the team default', () => {
+ teamLogic.mount()
+
+ const previous: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
+ modifiers: { personsOnEventsMode: 'person_id_override_properties_joined' },
+ },
+ }
+ const suggested: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
+ },
+ }
+
+ expect(compareInsightTopLevelSections(previous, suggested)).toEqual(['Query modifiers'])
+
+ teamLogic.unmount()
+ })
+
+ it('ignores modifiers that match the team default', () => {
+ teamLogic.mount()
+ teamLogic.actions.loadCurrentTeamSuccess({
+ id: 1,
+ modifiers: { personsOnEventsMode: 'person_id_override_properties_joined' },
+ } as unknown as TeamType)
+
+ const previous: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
+ modifiers: { personsOnEventsMode: 'person_id_override_properties_joined' },
+ },
+ }
+ const suggested: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
+ },
+ }
+
+ expect(compareInsightTopLevelSections(previous, suggested)).toEqual([])
+
+ teamLogic.unmount()
+ })
+
it('handles null/undefined objects', () => {
expect(
compareInsightTopLevelSections(null as any, { kind: NodeKind.TrendsQuery, series: [] } as InsightQueryNode)
diff --git a/frontend/src/scenes/insights/utils.tsx b/frontend/src/scenes/insights/utils.tsx
index e8cd50c6c5e9..e81cb3a94d8f 100644
--- a/frontend/src/scenes/insights/utils.tsx
+++ b/frontend/src/scenes/insights/utils.tsx
@@ -13,6 +13,7 @@ import { humanFriendlyNumber } from 'lib/utils/numbers'
import { objectsEqual } from 'lib/utils/objects'
import { removeUndefinedAndNull } from 'lib/utils/objects'
import { ensureStringIsNotBlank } from 'lib/utils/strings'
+import { teamLogic } from 'scenes/teamLogic'
import { IndexedTrendResult } from 'scenes/trends/types'
import { urls } from 'scenes/urls'
@@ -27,6 +28,7 @@ import {
FileSystemIconType,
GroupNode,
HogQLQuery,
+ HogQLQueryModifiers,
HogQLVariable,
InsightVizNode,
Node,
@@ -742,6 +744,13 @@ export function crushDraftQueryForURL(query: Node<Record<string, any>>): string
return JSON.stringify(query)
}
+/**
+ * Query plumbing rather than editor sections: the schema version stamp, the query log tags, and
+ * the typing-only response. A suggested query arrives without them, so comparing them reports a
+ * change nobody made. `modifiers` are handled separately below.
+ */
+const IGNORED_SOURCE_FIELDS = ['version', 'tags', 'response']
+
const SOURCE_FIELD_LABELS: Record<string, string> = {
breakdownFilter: 'Breakdowns',
compareFilter: 'Compare filter',
@@ -753,6 +762,7 @@ const SOURCE_FIELD_LABELS: Record<string, string> = {
samplingFactor: 'Sampling',
series: 'Series',
trendsFilter: 'Display options',
+ modifiers: 'Query modifiers',
}
function arraysEqual(arr1: any[], arr2: any[]): boolean {
@@ -780,15 +790,51 @@ function deepEqual(val1: any, val2: any): boolean {
return equal(val1, val2)
}
+/**
+ * Resolve a query's modifiers the way the backend does: explicit query modifiers win, then the
+ * team overrides, then the PostHog defaults. Absent and default-equal modifiers both resolve to
+ * the team's effective set, so comparing resolved modifiers skips changes nobody made.
+ */
+function resolveModifiersForComparison(
+ modifiers: HogQLQueryModifiers | undefined,
+ teamModifiers: HogQLQueryModifiers | undefined
+): HogQLQueryModifiers {
+ return { ...teamModifiers, ...removeUndefinedAndNull(modifiers ?? {}) }
+}
+
+/**
+ * Clean the source of an insight query for comparison. Handles both InsightVizNode (with source)
+ * and InsightQueryNode (without source). `cleanInsightQuery` only strips empty values one level
+ * deep, so it must run on the source — given the wrapping node it leaves `source.trendsFilter: {}`
+ * behind, which then reads as a changed section.
+ */
+function cleanSourceForComparison(node: any, teamModifiers: HogQLQueryModifiers | undefined): Record<string, any> {
+ const withoutNullish = removeUndefinedAndNull(node)
+ const source = withoutNullish?.source ?? withoutNullish
+ if (!source || typeof source !== 'object') {
+ return {}
+ }
+ const cleaned = cleanInsightQuery(source) as Record<string, any>
+ for (const field of IGNORED_SOURCE_FIELDS) {
+ delete cleaned[field]
+ }
+ const resolvedModifiers = resolveModifiersForComparison(cleaned.modifiers, teamModifiers)
+ if (Object.keys(resolvedModifiers).length > 0) {
+ cleaned.modifiers = resolvedModifiers
+ } else {
+ delete cleaned.modifiers
+ }
+ return cleaned
+}
+
export function compareInsightTopLevelSections(obj1: any, obj2: any): string[] {
const changedLabels = new Set<string>()
- const cleanObj1 = cleanInsightQuery(removeUndefinedAndNull(obj1)) as Record<string, any>
- const cleanObj2 = cleanInsightQuery(removeUndefinedAndNull(obj2)) as Record<string, any>
+ const currentTeam = teamLogic.findMounted()?.values.currentTeam
+ const teamModifiers = { ...currentTeam?.default_modifiers, ...currentTeam?.modifiers }
- // Handle both InsightVizNode (with source) and InsightQueryNode (without source)
- const source1 = cleanObj1.source || cleanObj1
- const source2 = cleanObj2.source || cleanObj2
+ const source1 = cleanSourceForComparison(obj1, teamModifiers)
+ const source2 = cleanSourceForComparison(obj2, teamModifiers)
if (!objectsEqual(source1, source2)) {
const keys = new Set([...Object.keys(source1 || {}), ...Object.keys(source2 || {})])