: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(insights): add a keep option to the PostHog AI change notice (#102964)
Thomas Obermüller0221b0c0d442
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 1acd90ce8f69..af55c1182cb4 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9256,6 +9256,10 @@ snapshots:hash: v1.k794b7964.dfd3cfa4c22429f905144ad610de438cd4685b2f160970762ee53a0c57b51f7c.36ljh4-ECCoIoGsxSqYp-Bl_q4ndSo-sORGvmxkm75Ascenes-app-insights-mcp-missing-capability--mcp-missing-capability--light:hash: v1.k794b7964.1b1a18bc74d3513095cfeb8a172f426cbda4d1b9b5df5ba59479d8ceb2399535.1TyzFZmRmUYsqc9Q5dnyZQtCF7gppER5cdCkVWMsNdc+ scenes-app-insights-posthog-ai-suggestion--default--dark:+ hash: v1.k794b7964.9b9cc1445c7ce703d3b0dbb3d4a92be579932829994f414f1de80f8016ea1154.jb54m6G-4sIokLRkpEnOPhJu-hxlxtfJcQ7ri7sI3WY+ scenes-app-insights-posthog-ai-suggestion--default--light:+ hash: v1.k794b7964.63299b5e251d2a6beb724655ad8791f82f58ae681bb2c931ba6339dd8fe92a56.vHLJvasOolcLGCjkSmIZqRFJ0CQmc5nTTpBBT40kSc0scenes-app-insights-side-panel-actions--saved-data-visualization--dark:hash: v1.k794b7964.3911a695d4b7b073bd0bfbaa183acb078d81df968e2cfecd18f84bc1c181bb66.2Hh9UrgF9n3vN3ZVif3FKqyz4F9mFROKhyLIEflEvDYscenes-app-insights-side-panel-actions--saved-data-visualization--light:diff --git a/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.tsx b/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.tsxindex ac68fc0a5001..b7743b7a1f50 100644--- a/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.tsx+++ b/frontend/src/queries/nodes/InsightViz/EditorFiltersShell.tsx@@ -104,7 +104,9 @@ export function EditorFiltersShell({ query, showing, embedded, children }: Editoconst { insightProps } = useValues(insightLogic)const { querySource, shouldShowSessionAnalysisWarning } = useValues(insightVizDataLogic(insightProps))const { setQuery } = useActions(insightVizDataLogic(insightProps))- const { handleInsightSuggested, onRejectSuggestedInsight } = useActions(insightLogic(insightProps))+ const { handleInsightSuggested, onKeepSuggestedInsight, onRejectSuggestedInsight } = useActions(+ insightLogic(insightProps)+ )const { previousQuery, suggestedQuery } = useValues(insightLogic(insightProps))const panelRef = useRef<HTMLDivElement>(null)@@ -205,6 +207,7 @@ export function EditorFiltersShell({ query, showing, embedded, children }: Edito<SuggestionBannerpreviousQuery={previousQuery}suggestedQuery={suggestedQuery}+ onKeep={onKeepSuggestedInsight}onReject={onRejectSuggestedInsight}/>)}diff --git a/frontend/src/queries/nodes/InsightViz/SuggestionBanner.stories.tsx b/frontend/src/queries/nodes/InsightViz/SuggestionBanner.stories.tsxnew file mode 100644index 000000000000..a88868f1d379--- /dev/null+++ b/frontend/src/queries/nodes/InsightViz/SuggestionBanner.stories.tsx@@ -0,0 +1,48 @@+import type { Meta, StoryObj } from '@storybook/react'++import { InsightVizNode, NodeKind } from '~/queries/schema/schema-general'++import { SuggestionBanner } from './SuggestionBanner'++const meta: Meta<typeof SuggestionBanner> = {+ title: 'Scenes-App/Insights/PostHog AI suggestion',+ component: SuggestionBanner,+}+export default meta++type Story = StoryObj<typeof SuggestionBanner>++const PREVIOUS_QUERY: InsightVizNode = {+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],+ dateRange: { date_from: '-7d' },+ interval: 'day',+ },+}++const SUGGESTED_QUERY: InsightVizNode = {+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: 'sign up' }],+ dateRange: { date_from: '-30d' },+ interval: 'week',+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },+ },+}++// The editor panel is the narrowest surface this renders on, so the story pins that width.+export const Default: Story = {+ render: () => (+ <div className="w-[420px]">+ <SuggestionBanner+ previousQuery={PREVIOUS_QUERY}+ suggestedQuery={SUGGESTED_QUERY}+ onKeep={() => {}}+ onReject={() => {}}+ />+ </div>+ ),+}diff --git a/frontend/src/queries/nodes/InsightViz/SuggestionBanner.tsx b/frontend/src/queries/nodes/InsightViz/SuggestionBanner.tsxindex 9188b8f086d7..50fc40ff8ee1 100644--- a/frontend/src/queries/nodes/InsightViz/SuggestionBanner.tsx+++ b/frontend/src/queries/nodes/InsightViz/SuggestionBanner.tsx@@ -1,6 +1,6 @@import { useEffect, useRef } from 'react'-import { IconInfo, IconX } from '@posthog/icons'+import { IconCheck, IconInfo, IconX } from '@posthog/icons'import { LemonButton, Tooltip } from '@posthog/lemon-ui'import { pluralize } from 'lib/utils/strings'@@ -11,10 +11,16 @@ import { Node } from '~/queries/schema/schema-general'export interface SuggestionBannerProps {previousQuery: NodesuggestedQuery: Node | null+ onKeep: () => voidonReject: () => void}-export function SuggestionBanner({ previousQuery, suggestedQuery, onReject }: SuggestionBannerProps): JSX.Element {+export function SuggestionBanner({+ previousQuery,+ suggestedQuery,+ onKeep,+ onReject,+}: SuggestionBannerProps): JSX.Element {const ref = useRef<HTMLDivElement>(null)useEffect(() => {@@ -28,7 +34,7 @@ export function SuggestionBanner({ previousQuery, suggestedQuery, onReject }: Sureturn (<div className="w-full px-2" ref={ref}>- <div className="bg-surface-tertiary/80 w-full flex justify-between items-center p-1 pl-2 mx-auto rounded-bl rounded-br">+ <div className="bg-surface-tertiary/80 w-full flex flex-wrap gap-1 justify-between items-center p-1 pl-2 mx-auto rounded-bl rounded-br"><div className="text-sm text-muted flex items-center gap-2 no-wrap"><span className="size-2 bg-accent-active rounded-full" /><div className="flex items-center gap-1">@@ -41,9 +47,30 @@ export function SuggestionBanner({ previousQuery, suggestedQuery, onReject }: Su</div></div>- <LemonButton status="danger" onClick={onReject} tooltipPlacement="top" size="small" icon={<IconX />}>- Reject changes- </LemonButton>+ <div className="flex items-center gap-1">+ <LemonButton+ status="danger"+ onClick={onReject}+ tooltip="Go back to the query from before these changes"+ tooltipPlacement="top"+ size="small"+ icon={<IconX />}+ data-attr="insight-suggestion-reject"+ >+ Reject changes+ </LemonButton>+ <LemonButton+ type="tertiary"+ onClick={onKeep}+ tooltip="Keep these changes. They stay unsaved until you save the insight."+ tooltipPlacement="top"+ size="small"+ icon={<IconCheck className="text-success" />}+ data-attr="insight-suggestion-keep"+ >+ Keep changes+ </LemonButton>+ </div></div></div>)diff --git a/frontend/src/scenes/insights/insightLogic.test.ts b/frontend/src/scenes/insights/insightLogic.test.tsindex 008c9330b82d..d9a2d911f647 100644--- a/frontend/src/scenes/insights/insightLogic.test.ts+++ b/frontend/src/scenes/insights/insightLogic.test.ts@@ -39,6 +39,7 @@ import {import { insightDataLogic } from './insightDataLogic'import { createEmptyInsight, insightLogic } from './insightLogic'+import { insightVizDataLogic } from './insightVizDataLogic'const API_FILTERS: Partial<FilterType> = {insight: InsightType.TRENDS as InsightType,@@ -936,6 +937,76 @@ describe('insightLogic', () => {})})+ describe('PostHog AI suggestions', () => {+ const suggestedQuery: InsightVizNode = {+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [{ kind: NodeKind.EventsNode, event: '$pageview', math: BaseMathType.TotalCount }],+ },+ }+ let vizLogic: ReturnType<typeof insightVizDataLogic.build>++ const mountInsight = async (dashboardItemId: InsightShortId | 'new'): Promise<void> => {+ const insightProps: InsightLogicProps = { dashboardItemId }+ logic = insightLogic(insightProps)+ logic.mount()+ insightDataLogic(insightProps).mount()+ vizLogic = insightVizDataLogic(insightProps)+ vizLogic.mount()+ // A saved insight loads asynchronously and re-syncs the query when it arrives, which+ // would land on top of a suggestion applied before then.+ await expectLogic(logic).toFinishAllListeners()+ }++ const suggest = (): void => {+ logic.actions.handleInsightSuggested(suggestedQuery)+ vizLogic.actions.setQuery(suggestedQuery)+ }++ it.each([+ ['an unsaved', 'new' as const],+ ['a saved', Insight42],+ ])('keeping the changes on %s insight ends the review and holds on to the query', async (_, insightId) => {+ await mountInsight(insightId)+ suggest()++ await expectLogic(logic, () => {+ logic.actions.onKeepSuggestedInsight()+ }).toMatchValues({+ previousQuery: null,+ suggestedQuery: null,+ query: suggestedQuery,+ })+ })++ it('an edit made after the suggestion keeps it, so a reject cannot revert the edit', async () => {+ await mountInsight('new')+ suggest()++ await expectLogic(logic, () => {+ vizLogic.actions.updateQuerySource({ filterTestAccounts: true })+ }).toMatchValues({+ previousQuery: null,+ suggestedQuery: null,+ })+ })++ it('rejecting the suggestion restores the previous query and leaves it available to reapply', async () => {+ await mountInsight('new')+ const queryBeforeSuggestion = logic.values.query+ suggest()++ await expectLogic(logic, () => {+ logic.actions.onRejectSuggestedInsight()+ }).toMatchValues({+ previousQuery: null,+ suggestedQuery,+ query: queryBeforeSuggestion,+ })+ })+ })+describe('confirmDeleteInsight', () => {beforeEach(async () => {const insightProps: InsightLogicProps = { dashboardItemId: Insight42 }diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsxindex 19ef701ba8dc..26c76a996dbd 100644--- a/frontend/src/scenes/insights/insightLogic.tsx+++ b/frontend/src/scenes/insights/insightLogic.tsx@@ -284,6 +284,9 @@ export interface insightLogicActions {variablesOverride: Record<string, HogQLVariable> | null | undefined}}+ onKeepSuggestedInsight: () => {+ value: true+ }onReapplySuggestedInsight: () => {value: true}@@ -630,6 +633,7 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicTypehandleInsightSuggested: (suggestedInsight: Node | null) => ({ suggestedInsight }),onRejectSuggestedInsight: true,onReapplySuggestedInsight: true,+ onKeepSuggestedInsight: true,setPreviousQuery: (previousQuery: Node | null) => ({ previousQuery }),setSuggestedQuery: (suggestedQuery: Node | null) => ({ suggestedQuery }),reloadSavedInsights: true,@@ -930,10 +934,13 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicTypesetInsightMetadataFailure: () => false,},],+ // The editor notice and the thread's revert control read these two, so clearing both+ // is what takes the suggestion out of review.previousQuery: [null as Node | null,{setPreviousQuery: (_, { previousQuery }) => previousQuery,+ onKeepSuggestedInsight: () => null,saveInsight: () => null,},],@@ -941,6 +948,7 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicTypenull as Node | null,{setSuggestedQuery: (_, { suggestedQuery }) => suggestedQuery,+ onKeepSuggestedInsight: () => null,saveInsight: () => null,},],diff --git a/frontend/src/scenes/insights/insightVizDataLogic.ts b/frontend/src/scenes/insights/insightVizDataLogic.tsindex 9c35c13d0e09..4ab4c2418308 100644--- a/frontend/src/scenes/insights/insightVizDataLogic.ts+++ b/frontend/src/scenes/insights/insightVizDataLogic.ts@@ -20,9 +20,11 @@ import { dayjs } from 'lib/dayjs'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { dateMapping, is12HoursOrLess, isLessThan2Days } from 'lib/utils/dateFilters'import { eventUsageLogic } from 'lib/utils/eventUsageLogic'+import { objectsEqual } from 'lib/utils/objects'import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'import { dataThemeLogic } from 'scenes/dataThemeLogic'import { insightDataLogic } from 'scenes/insights/insightDataLogic'+import { insightLogic } from 'scenes/insights/insightLogic'import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'import { trendsResultsMatchQuery } from 'scenes/insights/utils/queryUtils'import { sceneLogic } from 'scenes/sceneLogic'@@ -2648,6 +2650,17 @@ export const insightVizDataLogic = kea<insightVizDataLogicType>([props.setQuery(query)}}+ // While a PostHog AI suggestion is under review the query is either the suggestion+ // itself or, after a reject, the query from before it. Any other query means the+ // reader edited the suggestion by hand, and a reject from then on would revert+ // their edit together with the suggestion.+ const mountedInsightLogic = insightLogic.findMounted(props)+ if (mountedInsightLogic) {+ const { previousQuery, suggestedQuery } = mountedInsightLogic.values+ if (previousQuery && !objectsEqual(query, suggestedQuery) && !objectsEqual(query, previousQuery)) {+ mountedInsightLogic.actions.onKeepSuggestedInsight()+ }+ }},// Discarding edits reverts the query to the saved version. A debounced filter