: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 the chart explanation through display edits (#128172)
Sam Penningtonc96fe2328a77
diff --git a/products/product_analytics/frontend/insights/explainChart/ExplainChartButton.tsx b/products/product_analytics/frontend/insights/explainChart/ExplainChartButton.tsxindex 27e7a6d85b38..9769bebea89c 100644--- a/products/product_analytics/frontend/insights/explainChart/ExplainChartButton.tsx+++ b/products/product_analytics/frontend/insights/explainChart/ExplainChartButton.tsx@@ -12,7 +12,9 @@ import type { InsightLogicProps } from '~/types'import { explainChartLogic } from './explainChartLogic'export function ExplainChartButton({ insightProps }: { insightProps: InsightLogicProps }): JSX.Element | null {- const { explainAvailable, storyShown, investigating, consentRequested } = useValues(explainChartLogic(insightProps))+ const { explainAvailable, storyVisible, investigating, consentRequested, explainDisabledReason } = useValues(+ explainChartLogic(insightProps)+ )const { explainClicked, approveConsent, dismissConsent } = useActions(explainChartLogic(insightProps))const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')@@ -32,7 +34,8 @@ export function ExplainChartButton({ insightProps }: { insightProps: InsightLogi<Buttonvariant="outline"size="sm"- aria-expanded={storyShown}+ aria-expanded={storyVisible}+ disabledReason={explainDisabledReason}loading={investigating}onClick={explainClicked}data-attr="explain-chart-toggle"@@ -46,7 +49,8 @@ export function ExplainChartButton({ insightProps }: { insightProps: InsightLogisize="xsmall"type="secondary"icon={<IconSparkles />}- active={storyShown}+ active={storyVisible}+ disabledReason={explainDisabledReason}loading={investigating}onClick={explainClicked}data-attr="explain-chart-toggle"diff --git a/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsx b/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsxindex 7ad95a28c6ec..92205d3226ad 100644--- a/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsx+++ b/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsx@@ -1,7 +1,10 @@import { useActions, useValues } from 'kea'+import { ExternalLink } from 'lucide-react'import posthog from 'posthog-js'import type { ReactNode } from 'react'+import { LemonBanner } from '@posthog/lemon-ui'+import type { InsightLogicProps } from '~/types'import {@@ -26,12 +29,23 @@ export interface InsightExplainChartProps {}export function InsightExplainChart({ insightProps, renderChart }: InsightExplainChartProps): JSX.Element {- const { explainAvailable, story, storyShown, storySeriesKey, formatValue } = useValues(+ const { explainAvailable, story, storyShown, storyVisible, storyOutdated, storySeriesKey, formatValue } = useValues(explainChartLogic(insightProps))const { askFollowUp } = useActions(explainChartLogic(insightProps))- if (!explainAvailable || !story || !storyShown) {+ if (explainAvailable && storyShown && storyOutdated) {+ return (+ <>+ <LemonBanner type="info" className="m-2">+ The explanation is hidden because your changes affect the chart's data. Undo them to see it again,+ or save and explain this version.+ </LemonBanner>+ {renderChart()}+ </>+ )+ }+ if (!explainAvailable || !story || !storyVisible) {return <>{renderChart()}</>}return (@@ -41,6 +55,12 @@ export function InsightExplainChart({ insightProps, renderChart }: InsightExplaidata={story}renderChart={(overlay) => <div data-not-quill>{renderChart(overlay)}</div>}openLink={(url) => window.open(url, '_blank', 'noopener')}+ openLinkLabel={+ <>+ Open+ <ExternalLink className="size-3" />+ </>+ }formatValue={formatValue}evidenceCharts={EVIDENCE_CHARTS}seriesKey={storySeriesKey ?? undefined}diff --git a/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts b/products/product_analytics/frontend/insights/explainChart/explainChartLogic.tsindex 2c0f8ff96e13..a24908de076c 100644--- a/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts+++ b/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts@@ -22,6 +22,7 @@ import type { AttachedContextItem } from '~/layout/ai/attachedContext'import { runnerPanelLogic } from '~/layout/ai/runnerPanelLogic'import type { ActiveCreation } from '~/layout/ai/runnerPanelLogic'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'+import { compareQuery } from '~/queries/nodes/InsightViz/queryUtils'import type { TrendsFilter } from '~/queries/schema/schema-general'import { ChartDisplayType, SidePanelTab } from '~/types'import type { InsightLogicProps } from '~/types'@@ -45,8 +46,9 @@ import { explainChartStoryFor, followUpContextFor } from './explainChartStory'export interface explainChartLogicValues {dataProcessingAccepted: boolean // aiConsentLogicfeatureFlags: FeatureFlagsSet // featureFlagLogic- queryChanged: boolean // insightDataLogic+ query: Node | null // insightDataLogicinsight: Partial<InsightModel<Node<Record<string, any>>>> // insightLogic+ savedInsight: Partial<InsightModel<Node<Record<string, any>>>> // insightLogiceffectivePhaiView: PhaiViewMode // maxGlobalLogicbaseCurrency: CurrencyCode // teamLogicdisplay: ChartDisplayType | null | undefined // trendsDataLogic@@ -55,14 +57,19 @@ export interface explainChartLogicValues {trendsFilter: TrendsFilter | null | undefined // trendsDataLogicconsentRequested: booleanexplainAvailable: boolean+ explainDisabledReason: string | nullfollowUpContext: AttachedContextItem | nullformatValue: (value: number) => stringinvestigating: booleaninvestigationPrompt: stringinvestigationStreamKey: string | nullstory: ExplainChartData | null+ storyOutdated: boolean+ storyQuery: Node | nullstorySeriesKey: string | nullstoryShown: boolean+ storyVisible: boolean+ unsavedDataChanges: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -117,7 +124,11 @@ export interface explainChartLogicActions {investigationEnded: () => {value: true}- receiveStory: (story: ExplainChartData) => {+ receiveStory: (+ story: ExplainChartData,+ query: Node | null+ ) => {+ query: Node<Record<string, any>> | nullstory: ExplainChartData}requestConsent: () => {@@ -146,9 +157,23 @@ export interface explainChartLogicMeta {effectivePhaiView: PhaiViewMode,isTrends: boolean,display: ChartDisplayType | null | undefined,- insight: Partial<InsightModel<Node<Record<string, any>>>>,- queryChanged: boolean+ insight: Partial<InsightModel<Node<Record<string, any>>>>+ ) => boolean+ unsavedDataChanges: (+ savedInsight: Partial<InsightModel<Node<Record<string, any>>>>,+ query: Node<Record<string, any>> | null+ ) => boolean+ storyOutdated: (+ story: ExplainChartData | null,+ storyQuery: Node<Record<string, any>> | null,+ query: Node<Record<string, any>> | null) => boolean+ storyVisible: (story: ExplainChartData | null, storyShown: boolean, storyOutdated: boolean) => boolean+ explainDisabledReason: (+ story: ExplainChartData | null,+ storyOutdated: boolean,+ unsavedDataChanges: boolean+ ) => string | nullinvestigationPrompt: (insight: Partial<InsightModel<Node<Record<string, any>>>>) => stringstorySeriesKey: (story: ExplainChartData | null, indexedResults: IndexedTrendResult[]) => string | nullformatValue: (@@ -178,9 +203,9 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explaiaiConsentLogic,['dataProcessingAccepted'],insightLogic(props),- ['insight'],+ ['insight', 'savedInsight'],insightDataLogic(props),- ['queryChanged'],+ ['query'],teamLogic,['baseCurrency'],trendsDataLogic(props),@@ -208,7 +233,7 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explaioutput: Record<string, unknown> | null) => ({ toolCallId, input, output }),setInvestigationStream: (streamKey: string) => ({ streamKey }),- receiveStory: (story: ExplainChartData) => ({ story }),+ receiveStory: (story: ExplainChartData, query: Node | null) => ({ story, query }),showStory: true,hideStory: true,forgetStory: true,@@ -247,6 +272,13 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explaiforgetStory: () => null,},],+ storyQuery: [+ null as Node | null,+ {+ receiveStory: (_, { query }) => query,+ forgetStory: () => null,+ },+ ],followUpContext: [null as AttachedContextItem | null,{@@ -268,28 +300,46 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai}),selectors(({ props }) => ({explainAvailable: [- (s) => [s.featureFlags, s.effectivePhaiView, s.isTrends, s.display, s.insight, s.queryChanged],+ (s) => [s.featureFlags, s.effectivePhaiView, s.isTrends, s.display, s.insight],(featureFlags: FeatureFlagsSet,effectivePhaiView: PhaiViewMode,isTrends: boolean,display: ChartDisplayType | null | undefined,- insight: insightLogicValues['insight'],- queryChanged: boolean+ insight: insightLogicValues['insight']): boolean =>!!featureFlags[FEATURE_FLAGS.EXPLAIN_CHART] &&effectivePhaiView === 'new' &&isTrends &&isOverTime(display) &&!!insight.short_id &&- !queryChanged &&!props.filtersOverride &&!props.variablesOverride,],+ unsavedDataChanges: [+ (s) => [s.savedInsight, s.query],+ (savedInsight: insightLogicValues['savedInsight'], query: Node | null): boolean =>+ dataDiffers(savedInsight.query, query),+ ],+ storyOutdated: [+ (s) => [s.story, s.storyQuery, s.query],+ (story: ExplainChartData | null, storyQuery: Node | null, query: Node | null): boolean =>+ !!story && dataDiffers(storyQuery, query),+ ],+ storyVisible: [+ (s) => [s.story, s.storyShown, s.storyOutdated],+ (story: ExplainChartData | null, storyShown: boolean, storyOutdated: boolean): boolean =>+ !!story && storyShown && !storyOutdated,+ ],+ explainDisabledReason: [+ (s) => [s.story, s.storyOutdated, s.unsavedDataChanges],+ (story: ExplainChartData | null, storyOutdated: boolean, unsavedDataChanges: boolean): string | null =>+ (!story || storyOutdated) && unsavedDataChanges ? 'Save your changes to explain this version' : null,+ ],investigationPrompt: [(s) => [s.insight],(insight: insightLogicValues['insight']): string => {- return `Explain why the insight ${insight.short_id} looks the way it does. I'm on the insight page, which opens your explain-chart result beside the chart as soon as the tool returns, so skip render-ui. In the chat, just tell me which moment to read first, by its number and title.`+ return `Explain why the insight ${insight.short_id} looks the way it does. I'm on the insight page, which opens your explain-chart result beside the chart as soon as the tool returns, so skip render-ui. In the chat, reply with one sentence naming the moment to read first, by its number and title. Leave the other findings to the explanation, and don't offer follow-up actions.`},],storySeriesKey: [@@ -311,7 +361,10 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai})),listeners(({ actions, values, cache }) => ({explainClicked: () => {- if (values.storyShown) {+ if (values.explainDisabledReason) {+ return+ }+ if (values.storyVisible) {actions.hideStory()} else if (values.story) {actions.showStory()@@ -389,11 +442,8 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explaireturn}cache.appliedToolCallIds.add(toolCallId)- const startedHere = values.investigating- actions.receiveStory(story)- if (startedHere) {- actions.closeSidePanel(SidePanelTab.Max)- }+ actions.receiveStory(story, values.savedInsight.query ?? null)+ actions.closeSidePanel(SidePanelTab.Max)},askFollowUp: ({ page, step }) => {posthog.capture('explain chart follow-up opened', { page_index: step })@@ -404,7 +454,9 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explaiposthog.capture('explain chart story shown', { chapters: story.chapters.length })},saveInsightSuccess: () => {- actions.forgetStory()+ if (values.storyOutdated) {+ actions.forgetStory()+ }},})),])@@ -417,6 +469,10 @@ const EXPLAINABLE_DISPLAYS: ChartDisplayType[] = [ChartDisplayType.ActionsStackedBar,]+function dataDiffers(a: Node | null | undefined, b: Node | null | undefined): boolean {+ return !!a && !!b && !compareQuery(a, b, { ignoreVisualizationOnlyChanges: true })+}+function isOverTime(display: ChartDisplayType | null | undefined): boolean {return !display || EXPLAINABLE_DISPLAYS.includes(display)}diff --git a/products/product_analytics/mcp/apps/explainChart/ExplainChartView.tsx b/products/product_analytics/mcp/apps/explainChart/ExplainChartView.tsxindex 4ef6ed0de4b6..ee6c554f3694 100644--- a/products/product_analytics/mcp/apps/explainChart/ExplainChartView.tsx+++ b/products/product_analytics/mcp/apps/explainChart/ExplainChartView.tsx@@ -43,6 +43,7 @@ export interface ExplainChartViewProps {/** Draws the chart with the overlay as a child, so the overlay can read the chart's scales. */renderChart: (overlay: ReactNode) => ReactNodeopenLink: (url: string) => void+ openLinkLabel?: ReactNodetitle?: string | nullformatValue?: (value: number) => stringonPageChange?: (change: StoryPageChange) => void@@ -74,6 +75,7 @@ export function ExplainChartView({data,renderChart,openLink,+ openLinkLabel,title,formatValue = defaultFormat,onPageChange,@@ -202,6 +204,7 @@ export function ExplainChartView({warnings={warningMessages(data.warnings)}page={active}openLink={openLink}+ openLinkLabel={openLinkLabel}canShowChart={canShowChart}shownEvidenceIndex={shownEvidenceIndex}onToggleChart={toggleEvidenceChart}@@ -210,6 +213,7 @@ export function ExplainChartView({<StoryChapterViewpage={active}openLink={openLink}+ openLinkLabel={openLinkLabel}canShowChart={canShowChart}shownEvidenceIndex={shownEvidenceIndex}onToggleChart={toggleEvidenceChart}diff --git a/products/product_analytics/mcp/apps/explainChart/StoryChapterView.tsx b/products/product_analytics/mcp/apps/explainChart/StoryChapterView.tsxindex daecb8dfc945..b7c2d641c516 100644--- a/products/product_analytics/mcp/apps/explainChart/StoryChapterView.tsx+++ b/products/product_analytics/mcp/apps/explainChart/StoryChapterView.tsx@@ -1,4 +1,4 @@-import { type ReactElement } from 'react'+import { type ReactElement, type ReactNode } from 'react'import { Text } from '@posthog/quill'@@ -11,6 +11,7 @@ import type { StoryPage } from './storyPages'export interface StoryChapterViewProps {page: StoryPage & { chapter: StoryChapter }openLink: (url: string) => void+ openLinkLabel?: ReactNodecanShowChart: (item: StoryEvidence) => booleanshownEvidenceIndex: number | nullonToggleChart: (index: number) => void@@ -19,6 +20,7 @@ export interface StoryChapterViewProps {export function StoryChapterView({page,openLink,+ openLinkLabel,canShowChart,shownEvidenceIndex,onToggleChart,@@ -61,6 +63,7 @@ export function StoryChapterView({<StoryEvidenceListevidence={chapter.evidence}openLink={openLink}+ openLinkLabel={openLinkLabel}canShowChart={canShowChart}shownIndex={shownEvidenceIndex}onToggleChart={onToggleChart}diff --git a/products/product_analytics/mcp/apps/explainChart/StoryEvidenceList.tsx b/products/product_analytics/mcp/apps/explainChart/StoryEvidenceList.tsxindex 25224a70c7ba..284cd3e84d03 100644--- a/products/product_analytics/mcp/apps/explainChart/StoryEvidenceList.tsx+++ b/products/product_analytics/mcp/apps/explainChart/StoryEvidenceList.tsx@@ -1,5 +1,5 @@import { ArrowUpRight } from 'lucide-react'-import { type ReactElement } from 'react'+import { type ReactElement, type ReactNode } from 'react'import { Button, Text } from '@posthog/quill'@@ -9,6 +9,7 @@ import { StoryMarkedText } from './StoryMarkedText'export interface StoryEvidenceListProps {evidence: StoryEvidence[]openLink: (url: string) => void+ openLinkLabel?: ReactNodecanShowChart: (item: StoryEvidence) => booleanshownIndex: number | nullonToggleChart: (index: number) => void@@ -17,6 +18,12 @@ export interface StoryEvidenceListProps {export function StoryEvidenceList({evidence,openLink,+ openLinkLabel = (+ <>+ Open in PostHog+ <ArrowUpRight className="size-3" />+ </>+ ),canShowChart,shownIndex,onToggleChart,@@ -69,8 +76,7 @@ export function StoryEvidenceList({onClick={() => item.url && openLink(item.url)}data-attr="explain-chart-evidence-link">- Open in PostHog- <ArrowUpRight className="size-3" />+ {openLinkLabel}</Button>)}</div>