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.

feat(insights): explain a trends chart on the insight page (#126106)

Sam Pennington609e03c6e294
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5df82ad22a09..a9d08481fe30 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6259,11 +6259,11 @@ snapshots:
mcp-apps-experiments--running--light:
hash: v1.k794b7964.f7ae67feb87956b98204afeb00f52012a62fc090b18d186d0575110924e5cb69.lWvegECniqeejO8WWNUVam5X0NQTkwxq2iifV-mN5JI
mcp-apps-explain-chart--chapter-beside-the-chart--light:
- hash: v1.k794b7964.1b3a4ae5d4f98f938dda78e7339e93624825472835fce63a58f960d535986fe6.fM-kwGLy2mjTyMtlHv_or2Sxi83wlTcjjs4xOPz_Ldo
+ hash: v1.k794b7964.f22cfd254180901662be46141f1ea92d45772a8ce872d06e93da94c0f009c194.MEhp6vICxGBWYTtSUVeowxPvGR_FvdjE1UzNej1Y3zY
mcp-apps-explain-chart--evidence-chart--light:
- hash: v1.k794b7964.850e4f7171b0ba2dc7a44928d12787534ec33bff3f8d7108a8022690a166150c.Q0BhB8TGCyT0vAZK4wlYvG7qORDvCZaMQWMoHGZsmSw
+ hash: v1.k794b7964.f6017c01f6a2077c52fe185b21fd64f5759d67db65a582bd455b3d109435b177.aAgucmeGEuPyMncKt-ZETRpZZ4CCoEnG7F-j4yx7yBk
mcp-apps-explain-chart--single-chapter--light:
- hash: v1.k794b7964.8d0d4e81255c25acbe114b45d698a66d4b3ff5be122c97eea1f5cc2066711a72.jx6b5OO_YEIBQZHEUccM0lJ6vaRZBUUWxs3dJgxxwKw
+ hash: v1.k794b7964.9925b1072fdd0d84e4c6b2c1130182bb5be985f388323a55c12d86a75d5bd94e.tIYnyucaKDUR3kOT-DUcavWJ9OgqETjYm938-zSaVyQ
mcp-apps-explain-chart--summary--light:
hash: v1.k794b7964.8e544f3f6c9e2e43bf03efd6bf30e402e2f24a41ec060922b5e3068643ce4c86.BQcCbMIGeBusavfXWYInYZD6jMZfnN4zr-HV9oOAFHg
mcp-apps-explain-chart-evidence-chart--line--light:
@@ -14987,7 +14987,7 @@ snapshots:
scenes-app-replay-vision--observation-detail-inline-scan--light:
hash: v1.k794b7964.58c261c32ebe4877009c5f758aea489ac52f9afea88b3fb7e528f06beb12baee.yLN7cpDKxLxc4oOyubpLEzKTHWFBFtsZbMZxdUKgS1A
scenes-app-replay-vision--observation-detail-monitor--dark:
- hash: v1.k794b7964.deb691222dbfac3ac026fe5fd3e22fc1ca4282d3cea77339a453e6f89a737698.vLBiLKOhkrF7r5hcf4_w7vYAJqB7bE9avnCOat5nGRQ
+ hash: v1.k794b7964.e07b6a45529b531d5765d3f5ee7c35d8815553a2bf4c5d435e7c423e63756053.kqzoYEMHXLugfzC1wTLGfKLSGeOnIRqTqBHJhf_Y1MM
scenes-app-replay-vision--observation-detail-monitor--light:
hash: v1.k794b7964.7a3f583432dafb78a1712b3b526dc23a71e0f5aca25fe249caeb91542f743530.ZQJ6IbAigy-fkKYwESiijE75Pe3rGKU1tiK9nokMpZE
scenes-app-replay-vision--observation-detail-monitor-inconclusive--dark:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index b28dbf66dc06..5ea689da1277 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -336,6 +336,7 @@ export const FEATURE_FLAGS = {
EXPERIMENTS_RECALCULATION_RATE_LIMIT: 'experiment-metric-recalculation-rate-limit', // owner: @rodrigoi #team-experiments, five-minute window between manual metric reloads
EXPERIMENTS_SHOW_SQL: 'experiments-show-sql', // owner: @jurajmajerik #team-experiments
EXPERIMENTS_SYNC_QUERIES: 'experiments-sync-queries', // owner: @andehen #team-experiments
+ EXPLAIN_CHART: 'explain-chart', // owner: @sampennington #team-product-analytics, gates "Explain this chart" on trends insights, which walks a person through what stands out on the chart
FEATURE_FLAG_CLEANUP_ASSESSMENT: 'feature-flag-cleanup-assessment', // owner: #team-feature-flags, kill switch for the flag-page "Review cleanup with AI" action
FEATURE_FLAG_COHORT_CREATION: 'feature-flag-cohort-creation', // owner: #team-feature-flags
FEATURE_FLAG_CREATION_INTENTS: 'feature-flag-creation-intents', // owner: #team-feature-flags
diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
index 0b2ad6ac4cdb..07f5a4538c38 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
@@ -7,6 +7,7 @@ import { LemonButton, Spinner } from '@posthog/lemon-ui'
import { isBoxPlotMissingProperty } from 'lib/components/ChartFilter/isBoxPlotMissingProperty'
import { ExportButton } from 'lib/components/ExportButton/ExportButton'
import { InsightLegend } from 'lib/components/InsightLegend/InsightLegend'
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
import { keyForInsightLogicProps } from 'lib/insights/sharedUtils'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { lazyWithRetry } from 'lib/utils/retryImport'
@@ -74,6 +75,26 @@ import { ResultCustomizationsModal } from './ResultCustomizationsModal'
const WebAnalyticsInsight = lazyWithRetry(() =>
import('scenes/web-analytics/WebAnalyticsInsight').then((m) => ({ default: m.WebAnalyticsInsight }))
)
+const InsightExplainChart = lazyWithRetry(() =>
+ import('products/product_analytics/frontend/insights/explainChart/InsightExplainChart').then((m) => ({
+ default: m.InsightExplainChart,
+ }))
+)
+const ExplainChartButton = lazyWithRetry(() =>
+ import('products/product_analytics/frontend/insights/explainChart/ExplainChartButton').then((m) => ({
+ default: m.ExplainChartButton,
+ }))
+)
+const ExplainChartAgentBridge = lazyWithRetry(() =>
+ import('products/product_analytics/frontend/insights/explainChart/ExplainChartAgentBridge').then((m) => ({
+ default: m.ExplainChartAgentBridge,
+ }))
+)
+const ExplainChartAIAnalysisFallback = lazyWithRetry(() =>
+ import('products/product_analytics/frontend/insights/explainChart/ExplainChartAIAnalysisFallback').then((m) => ({
+ default: m.ExplainChartAIAnalysisFallback,
+ }))
+)
/** When the dashboard is still streaming/refreshing tiles, prefer loading UX over "Chart data didn't load". */
function DashboardInsightRefreshHintOrLoading({
@@ -225,6 +246,8 @@ export function InsightVizDisplay({
const { funnelVizType, hasFunnelResults, isFunnelWithEnoughSteps, isFunnelWithIncompleteDataWarehouseStep } =
useValues(funnelDataLogic(insightProps))
+ const explainChartEnabled = useFeatureFlag('EXPLAIN_CHART')
+
const isFlowViz = funnelVizType === FunnelVizType.Flow
const actionable = !embedded && editMode
@@ -382,14 +405,14 @@ export function InsightVizDisplay({
const chartDrawsOwnLegend = display === ChartDisplayType.SlopeGraph || usesInChartLegend
const showSideLegend = supportsDisplay && showLegend && !chartDrawsOwnLegend
- function renderActiveView(): JSX.Element | null {
+ function renderActiveView(viewContext = context): JSX.Element | null {
switch (activeView) {
case InsightType.TRENDS:
return (
<TrendInsight
view={InsightType.TRENDS}
editMode={editMode}
- context={context}
+ context={viewContext}
embedded={embedded}
inSharedMode={inSharedMode}
/>
@@ -547,12 +570,29 @@ export function InsightVizDisplay({
hasBlockingEmptyState: !!BlockingEmptyState,
hasResults: hasResultRows(insightData),
}) ? (
- <InsightAIAnalysis />
+ showsExplainChart ? (
+ <Suspense fallback={null}>
+ <ExplainChartAIAnalysisFallback insightProps={insightProps} />
+ </Suspense>
+ ) : (
+ <InsightAIAnalysis />
+ )
) : null
}
const showComputationMetadata = !disableLastComputation || !!samplingFactor
const showsDataChecks = !!context?.showDataChecks && !inSharedMode
+ const showsExplainChart = explainChartEnabled && !embedded && !inSharedMode && activeView === InsightType.TRENDS
+ const chart = showsExplainChart ? (
+ <Suspense fallback={renderActiveView()}>
+ <InsightExplainChart
+ insightProps={insightProps}
+ renderChart={(overlay) => renderActiveView(overlay ? { ...context, chartOverlay: overlay } : context)}
+ />
+ </Suspense>
+ ) : (
+ renderActiveView()
+ )
// Web Analytics insights don't use themes, so allow them to render without waiting for theme to load
if (!theme && activeView !== InsightType.WEB_ANALYTICS) {
@@ -599,6 +639,11 @@ export function InsightVizDisplay({
<div className="flex items-center gap-2">
{isPaths && <PathCanvasLabel />}
{isFunnels && <FunnelCanvasLabel />}
+ {showsExplainChart && (
+ <Suspense fallback={null}>
+ <ExplainChartButton insightProps={insightProps} />
+ </Suspense>
+ )}
{showsDataChecks && <InsightDataChecks insightProps={insightProps} />}
</div>
</div>
@@ -620,19 +665,24 @@ export function InsightVizDisplay({
BlockingEmptyState
) : showSideLegend ? (
<>
- <div className="InsightVizDisplay__content__left">{renderActiveView()}</div>
+ <div className="InsightVizDisplay__content__left">{chart}</div>
<div className="InsightVizDisplay__content__right empty:hidden">
{display === ChartDisplayType.BoxPlot ? <BoxPlotLegend /> : <InsightLegend />}
</div>
</>
) : (
- <>{renderActiveView()}</>
+ chart
)}
</div>
</>
)}
</div>
<ResultCustomizationsModal />
+ {showsExplainChart && (
+ <Suspense fallback={null}>
+ <ExplainChartAgentBridge insightProps={insightProps} />
+ </Suspense>
+ )}
{renderAIAnalysisSection()}
{renderTable()}
</>
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index cc165758effe..df776349efea 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -4770,6 +4770,9 @@ importers:
kea-subscriptions:
specifier: 'catalog:'
version: 3.0.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
+ lucide-react:
+ specifier: ^0.577.0
+ version: 0.577.0([email protected])
natural-orderby:
specifier: '*'
version: 3.0.2
diff --git a/products/product_analytics/frontend/insights/explainChart/ExplainChartAIAnalysisFallback.tsx b/products/product_analytics/frontend/insights/explainChart/ExplainChartAIAnalysisFallback.tsx
new file mode 100644
index 000000000000..529413c966c0
--- /dev/null
+++ b/products/product_analytics/frontend/insights/explainChart/ExplainChartAIAnalysisFallback.tsx
@@ -0,0 +1,16 @@
+import { useValues } from 'kea'
+
+import type { InsightLogicProps } from '~/types'
+
+import { InsightAIAnalysis } from 'products/product_analytics/frontend/insights/shared/InsightAIAnalysis'
+
+import { explainChartLogic } from './explainChartLogic'
+
+export function ExplainChartAIAnalysisFallback({
+ insightProps,
+}: {
+ insightProps: InsightLogicProps
+}): JSX.Element | null {
+ const { explainAvailable } = useValues(explainChartLogic(insightProps))
+ return explainAvailable ? null : <InsightAIAnalysis />
+}
diff --git a/products/product_analytics/frontend/insights/explainChart/ExplainChartAgentBridge.tsx b/products/product_analytics/frontend/insights/explainChart/ExplainChartAgentBridge.tsx
new file mode 100644
index 000000000000..d443308a953f
--- /dev/null
+++ b/products/product_analytics/frontend/insights/explainChart/ExplainChartAgentBridge.tsx
@@ -0,0 +1,30 @@
+import { useActions, useMountedLogic, useValues } from 'kea'
+
+import { keyForInsightLogicProps } from 'lib/insights/sharedUtils'
+
+import type { InsightLogicProps } from '~/types'
+
+import { getToolOutputRecord, useAttachedContext, useMcpToolApplyBack } from 'products/posthog_ai/frontend/api/logics'
+
+import { explainChartLogic } from './explainChartLogic'
+
+export function ExplainChartAgentBridge({ insightProps }: { insightProps: InsightLogicProps }): null {
+ useMountedLogic(explainChartLogic(insightProps))
+ const { explainAvailable, followUpContext } = useValues(explainChartLogic(insightProps))
+ const { explainChartToolCompleted } = useActions(explainChartLogic(insightProps))
+
+ useMcpToolApplyBack({
+ tools: ['explain-chart'],
+ targetKey: `explain-chart-${keyForInsightLogicProps('new')(insightProps)}`,
+ active: explainAvailable,
+ onApply: (event, { innerInput }) =>
+ explainChartToolCompleted(
+ event.toolCallId,
+ innerInput,
+ getToolOutputRecord({ rawOutput: event.invocation.output, status: event.invocation.status })
+ ),
+ })
+ useAttachedContext(followUpContext ? [followUpContext] : null)
+
+ return null
+}
diff --git a/products/product_analytics/frontend/insights/explainChart/ExplainChartButton.tsx b/products/product_analytics/frontend/insights/explainChart/ExplainChartButton.tsx
new file mode 100644
index 000000000000..27e7a6d85b38
--- /dev/null
+++ b/products/product_analytics/frontend/insights/explainChart/ExplainChartButton.tsx
@@ -0,0 +1,59 @@
+import { useActions, useValues } from 'kea'
+
+import { IconSparkles } from '@posthog/icons'
+import { Button } from '@posthog/quill'
+
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
+
+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 { explainClicked, approveConsent, dismissConsent } = useActions(explainChartLogic(insightProps))
+ const todayRailNav = useFeatureFlag('TODAY_RAIL_NAV')
+
+ if (!explainAvailable) {
+ return null
+ }
+ const label = investigating ? 'Investigating…' : 'Explain this chart'
+ return (
+ <AIConsentPopoverWrapper
+ hidden={!consentRequested}
+ ignoreDismissal
+ onApprove={approveConsent}
+ onDismiss={dismissConsent}
+ >
+ {todayRailNav ? (
+ <span data-quill>
+ <Button
+ variant="outline"
+ size="sm"
+ aria-expanded={storyShown}
+ loading={investigating}
+ onClick={explainClicked}
+ data-attr="explain-chart-toggle"
+ >
+ <IconSparkles />
+ {label}
+ </Button>
+ </span>
+ ) : (
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ icon={<IconSparkles />}
+ active={storyShown}
+ loading={investigating}
+ onClick={explainClicked}
+ data-attr="explain-chart-toggle"
+ >
+ {label}
+ </LemonButton>
+ )}
+ </AIConsentPopoverWrapper>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/explainChart/ExplainChartEvidenceChart.tsx b/products/product_analytics/frontend/insights/explainChart/ExplainChartEvidenceChart.tsx
new file mode 100644
index 000000000000..ca25a660f146
--- /dev/null
+++ b/products/product_analytics/frontend/insights/explainChart/ExplainChartEvidenceChart.tsx
@@ -0,0 +1,43 @@
+import { useChartTheme } from 'lib/charts/hooks'
+
+import { Query } from '~/queries/Query/Query'
+import { NodeKind } from '~/queries/schema/schema-general'
+import type { InsightVizNode } from '~/queries/schema/schema-general'
+import type { TrendResult } from '~/types'
+
+import type { StoryEvidence } from 'products/product_analytics/mcp/apps/explainChart/explainChartTypes'
+import { StoryEvidenceChart } from 'products/product_analytics/mcp/apps/explainChart/StoryEvidenceChart'
+import { isSeriesNamedIn } from 'products/product_analytics/mcp/apps/explainChart/storyNamedSeries'
+
+function seriesNames(result: TrendResult): string[] {
+ return [result.label ?? '', ...[result.breakdown_value ?? []].flat().map(String)]
+}
+
+export function ExplainChartEvidenceChart({ item }: { item: StoryEvidence }): JSX.Element | null {
+ const theme = useChartTheme()
+ if (item.chart) {
+ return <StoryEvidenceChart chart={item.chart} theme={theme} className="h-(--insight-viz-min-height)" />
+ }
+ if (!item.query) {
+ return null
+ }
+ const query: InsightVizNode = {
+ kind: NodeKind.InsightVizNode,
+ source: { kind: NodeKind.TrendsQuery, ...item.query } as unknown as InsightVizNode['source'],
+ full: false,
+ showHeader: false,
+ showTable: false,
+ }
+ return (
+ <div data-not-quill className="flex h-(--insight-viz-min-height) flex-col">
+ <Query
+ key={JSON.stringify(item.query)}
+ uniqueKey="explain-chart-evidence"
+ query={query}
+ context={{ isSeriesHighlighted: (result) => isSeriesNamedIn(seriesNames(result), item.text) }}
+ readOnly
+ embedded
+ />
+ </div>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/explainChart/ExplainChartFollowUp.tsx b/products/product_analytics/frontend/insights/explainChart/ExplainChartFollowUp.tsx
new file mode 100644
index 000000000000..ea9a1f17dec5
--- /dev/null
+++ b/products/product_analytics/frontend/insights/explainChart/ExplainChartFollowUp.tsx
@@ -0,0 +1,11 @@
+import { IconMessage } from '@posthog/icons'
+import { Button } from '@posthog/quill'
+
+export function ExplainChartFollowUp({ onClick }: { onClick: () => void }): JSX.Element {
+ return (
+ <Button variant="outline" size="sm" onClick={onClick} data-attr="explain-chart-ask-follow-up">
+ <IconMessage />
+ Ask PostHog AI a follow-up
+ </Button>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsx b/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsx
new file mode 100644
index 000000000000..7ad95a28c6ec
--- /dev/null
+++ b/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsx
@@ -0,0 +1,59 @@
+import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
+import type { ReactNode } from 'react'
+
+import type { InsightLogicProps } from '~/types'
+
+import {
+ ExplainChartView,
+ type StoryEvidenceCharts,
+} from 'products/product_analytics/mcp/apps/explainChart/ExplainChartView'
+
+import { ExplainChartEvidenceChart } from './ExplainChartEvidenceChart'
+import { ExplainChartFollowUp } from './ExplainChartFollowUp'
+import { explainChartLogic } from './explainChartLogic'
+
+const EVIDENCE_CHARTS: StoryEvidenceCharts = {
+ canShow: (item) => !!item.chart || !!item.query,
+ prefetch: () => {},
+ render: (item) => <ExplainChartEvidenceChart item={item} />,
+ onShow: () => posthog.capture('explain chart evidence chart shown'),
+}
+
+export interface InsightExplainChartProps {
+ insightProps: InsightLogicProps
+ renderChart: (overlay?: ReactNode) => ReactNode
+}
+
+export function InsightExplainChart({ insightProps, renderChart }: InsightExplainChartProps): JSX.Element {
+ const { explainAvailable, story, storyShown, storySeriesKey, formatValue } = useValues(
+ explainChartLogic(insightProps)
+ )
+ const { askFollowUp } = useActions(explainChartLogic(insightProps))
+
+ if (!explainAvailable || !story || !storyShown) {
+ return <>{renderChart()}</>
+ }
+ return (
+ <div data-quill>
+ <ExplainChartView
+ key={story.headline}
+ data={story}
+ renderChart={(overlay) => <div data-not-quill>{renderChart(overlay)}</div>}
+ openLink={(url) => window.open(url, '_blank', 'noopener')}
+ formatValue={formatValue}
+ evidenceCharts={EVIDENCE_CHARTS}
+ seriesKey={storySeriesKey ?? undefined}
+ chapterAction={(page, step) => <ExplainChartFollowUp onClick={() => askFollowUp(page, step)} />}
+ onPageChange={({ index, fromIndex, source }) =>
+ posthog.capture('explain chart page viewed', {
+ page_index: index,
+ from_page_index: fromIndex,
+ page_count: story.chapters.length + 1,
+ source,
+ })
+ }
+ />
+ </div>
+ )
+}
diff --git a/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts b/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts
new file mode 100644
index 000000000000..2c0f8ff96e13
--- /dev/null
+++ b/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts
@@ -0,0 +1,422 @@
+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import type { LogicWrapper } from 'kea'
+import posthog from 'posthog-js'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { formatAggregationAxisValue } from 'lib/insights/aggregationAxisFormat'
+import { keyForInsightLogicProps } from 'lib/insights/sharedUtils'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import type { FeatureFlagsSet } from 'lib/logic/featureFlagLogic'
+import { insightDataLogic } from 'scenes/insights/insightDataLogic'
+import { insightLogic } from 'scenes/insights/insightLogic'
+import type { insightLogicValues } from 'scenes/insights/insightLogic'
+import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
+import { autoRunMaxPrompt } from 'scenes/max/maxPrompt'
+import { teamLogic } from 'scenes/teamLogic'
+import type { teamLogicValues } from 'scenes/teamLogic'
+
+import { aiConsentLogic } from '~/layout/ai/aiConsentLogic'
+import { MAX_SIDE_PANEL_ID } from '~/layout/ai/aiPanelIds'
+import type { PhaiViewMode } from '~/layout/ai/aiPanelIds'
+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 type { TrendsFilter } from '~/queries/schema/schema-general'
+import { ChartDisplayType, SidePanelTab } from '~/types'
+import type { InsightLogicProps } from '~/types'
+
+import {
+ getToolOutputRecord,
+ resolveToolCall,
+ runStreamLogic,
+ toolStreamEventsLogic,
+} from 'products/posthog_ai/frontend/api/logics'
+import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'
+import type { IndexedTrendResult } from 'products/product_analytics/frontend/insights/trends/types'
+import type { ExplainChartData } from 'products/product_analytics/mcp/apps/explainChart/explainChartTypes'
+import type { StoryPage } from 'products/product_analytics/mcp/apps/explainChart/storyPages'
+
+import type { CurrencyCode, Node } from '../../../../../frontend/src/queries/schema/schema-general'
+import type { InsightModel } from '../../../../../frontend/src/types'
+import { explainChartStoryFor, followUpContextFor } from './explainChartStory'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface explainChartLogicValues {
+ dataProcessingAccepted: boolean // aiConsentLogic
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ queryChanged: boolean // insightDataLogic
+ insight: Partial<InsightModel<Node<Record<string, any>>>> // insightLogic
+ effectivePhaiView: PhaiViewMode // maxGlobalLogic
+ baseCurrency: CurrencyCode // teamLogic
+ display: ChartDisplayType | null | undefined // trendsDataLogic
+ indexedResults: IndexedTrendResult[] // trendsDataLogic
+ isTrends: boolean // trendsDataLogic
+ trendsFilter: TrendsFilter | null | undefined // trendsDataLogic
+ consentRequested: boolean
+ explainAvailable: boolean
+ followUpContext: AttachedContextItem | null
+ formatValue: (value: number) => string
+ investigating: boolean
+ investigationPrompt: string
+ investigationStreamKey: string | null
+ story: ExplainChartData | null
+ storySeriesKey: string | null
+ storyShown: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface explainChartLogicActions {
+ saveInsightSuccess: () => {
+ value: true
+ } // insightLogic
+ setActiveCreation: (creation: ActiveCreation) => {
+ creation: ActiveCreation
+ } // runnerPanelLogic
+ closeSidePanel: (tab?: SidePanelTab | undefined) => {
+ tab: SidePanelTab | undefined
+ } // sidePanelStateLogic
+ openSidePanel: (
+ tab: SidePanelTab,
+ options?: string | undefined
+ ) => {
+ options: string | undefined
+ tab: SidePanelTab
+ } // sidePanelStateLogic
+ approveConsent: () => {
+ value: true
+ }
+ askFollowUp: (
+ page: StoryPage,
+ step: number
+ ) => {
+ page: StoryPage
+ step: number
+ }
+ dismissConsent: () => {
+ value: true
+ }
+ explainChartToolCompleted: (
+ toolCallId: string,
+ input: Record<string, unknown> | null,
+ output: Record<string, unknown> | null
+ ) => {
+ input: Record<string, unknown> | null
+ output: Record<string, unknown> | null
+ toolCallId: string
+ }
+ explainClicked: () => {
+ value: true
+ }
+ forgetStory: () => {
+ value: true
+ }
+ hideStory: () => {
+ value: true
+ }
+ investigationEnded: () => {
+ value: true
+ }
+ receiveStory: (story: ExplainChartData) => {
+ story: ExplainChartData
+ }
+ requestConsent: () => {
+ value: true
+ }
+ setFollowUpContext: (item: AttachedContextItem) => {
+ item: AttachedContextItem
+ }
+ setInvestigationStream: (streamKey: string) => {
+ streamKey: string
+ }
+ showStory: () => {
+ value: true
+ }
+ startInvestigation: () => {
+ value: true
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface explainChartLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ explainAvailable: (
+ featureFlags: FeatureFlagsSet,
+ effectivePhaiView: PhaiViewMode,
+ isTrends: boolean,
+ display: ChartDisplayType | null | undefined,
+ insight: Partial<InsightModel<Node<Record<string, any>>>>,
+ queryChanged: boolean
+ ) => boolean
+ investigationPrompt: (insight: Partial<InsightModel<Node<Record<string, any>>>>) => string
+ storySeriesKey: (story: ExplainChartData | null, indexedResults: IndexedTrendResult[]) => string | null
+ formatValue: (
+ trendsFilter: TrendsFilter | null | undefined,
+ baseCurrency: CurrencyCode
+ ) => (value: number) => string
+ }
+}
+
+export type explainChartLogicType = MakeLogicType<
+ explainChartLogicValues,
+ explainChartLogicActions,
+ InsightLogicProps,
+ explainChartLogicMeta
+>
+
+export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explainChartLogicType>([
+ props({} as InsightLogicProps),
+ key(keyForInsightLogicProps('new')),
+ path((key) => ['products', 'product_analytics', 'insights', 'explainChart', 'explainChartLogic', key]),
+ connect((props: InsightLogicProps) => ({
+ values: [
+ featureFlagLogic,
+ ['featureFlags'],
+ maxGlobalLogic,
+ ['effectivePhaiView'],
+ aiConsentLogic,
+ ['dataProcessingAccepted'],
+ insightLogic(props),
+ ['insight'],
+ insightDataLogic(props),
+ ['queryChanged'],
+ teamLogic,
+ ['baseCurrency'],
+ trendsDataLogic(props),
+ ['display', 'indexedResults', 'isTrends', 'trendsFilter'],
+ ],
+ actions: [
+ sidePanelStateLogic,
+ ['openSidePanel', 'closeSidePanel'],
+ insightLogic(props),
+ ['saveInsightSuccess'],
+ runnerPanelLogic({ panelId: MAX_SIDE_PANEL_ID }),
+ ['setActiveCreation'],
+ ],
+ })),
+ actions({
+ explainClicked: true,
+ requestConsent: true,
+ approveConsent: true,
+ dismissConsent: true,
+ startInvestigation: true,
+ investigationEnded: true,
+ explainChartToolCompleted: (
+ toolCallId: string,
+ input: Record<string, unknown> | null,
+ output: Record<string, unknown> | null
+ ) => ({ toolCallId, input, output }),
+ setInvestigationStream: (streamKey: string) => ({ streamKey }),
+ receiveStory: (story: ExplainChartData) => ({ story }),
+ showStory: true,
+ hideStory: true,
+ forgetStory: true,
+ askFollowUp: (page: StoryPage, step: number) => ({ page, step }),
+ setFollowUpContext: (item: AttachedContextItem) => ({ item }),
+ }),
+ reducers({
+ consentRequested: [
+ false,
+ {
+ requestConsent: () => true,
+ approveConsent: () => false,
+ dismissConsent: () => false,
+ },
+ ],
+ investigating: [
+ false,
+ {
+ startInvestigation: () => true,
+ investigationEnded: () => false,
+ receiveStory: () => false,
+ forgetStory: () => false,
+ },
+ ],
+ investigationStreamKey: [
+ null as string | null,
+ {
+ startInvestigation: () => null,
+ setInvestigationStream: (_, { streamKey }) => streamKey,
+ },
+ ],
+ story: [
+ null as ExplainChartData | null,
+ {
+ receiveStory: (_, { story }) => story,
+ forgetStory: () => null,
+ },
+ ],
+ followUpContext: [
+ null as AttachedContextItem | null,
+ {
+ setFollowUpContext: (_, { item }) => item,
+ receiveStory: () => null,
+ hideStory: () => null,
+ forgetStory: () => null,
+ },
+ ],
+ storyShown: [
+ false,
+ {
+ receiveStory: () => true,
+ showStory: () => true,
+ hideStory: () => false,
+ forgetStory: () => false,
+ },
+ ],
+ }),
+ selectors(({ props }) => ({
+ explainAvailable: [
+ (s) => [s.featureFlags, s.effectivePhaiView, s.isTrends, s.display, s.insight, s.queryChanged],
+ (
+ featureFlags: FeatureFlagsSet,
+ effectivePhaiView: PhaiViewMode,
+ isTrends: boolean,
+ display: ChartDisplayType | null | undefined,
+ insight: insightLogicValues['insight'],
+ queryChanged: boolean
+ ): boolean =>
+ !!featureFlags[FEATURE_FLAGS.EXPLAIN_CHART] &&
+ effectivePhaiView === 'new' &&
+ isTrends &&
+ isOverTime(display) &&
+ !!insight.short_id &&
+ !queryChanged &&
+ !props.filtersOverride &&
+ !props.variablesOverride,
+ ],
+ 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.`
+ },
+ ],
+ storySeriesKey: [
+ (s) => [s.story, s.indexedResults],
+ (story: ExplainChartData | null, indexedResults: IndexedTrendResult[]): string | null => {
+ if (!story) {
+ return null
+ }
+ const rendered = indexedResults.find((result) => result.seriesIndex === story.seriesIndex)
+ return String(rendered?.id ?? story.seriesIndex)
+ },
+ ],
+ formatValue: [
+ (s) => [s.trendsFilter, s.baseCurrency],
+ (trendsFilter: TrendsFilter | null | undefined, baseCurrency: teamLogicValues['baseCurrency']) =>
+ (value: number): string =>
+ formatAggregationAxisValue(trendsFilter, value, baseCurrency),
+ ],
+ })),
+ listeners(({ actions, values, cache }) => ({
+ explainClicked: () => {
+ if (values.storyShown) {
+ actions.hideStory()
+ } else if (values.story) {
+ actions.showStory()
+ } else if (!values.dataProcessingAccepted) {
+ actions.requestConsent()
+ } else {
+ actions.startInvestigation()
+ }
+ },
+ approveConsent: () => {
+ actions.startInvestigation()
+ },
+ startInvestigation: () => {
+ posthog.capture('explain chart investigation started')
+ cache.disposables.add(
+ () => {
+ const listenerId = `explain-chart-investigation-${values.insight.short_id}`
+ const endIfOurs = ({ streamKey }: { streamKey: string }): void => {
+ if (values.investigationStreamKey === null || streamKey === values.investigationStreamKey) {
+ actions.investigationEnded()
+ }
+ }
+ toolStreamEventsLogic.actions.registerToolListener(listenerId, {
+ tools: '*',
+ onEvent: (event) => {
+ if (values.investigationStreamKey === null) {
+ actions.setInvestigationStream(event.streamKey)
+ }
+ if (
+ event.streamKey === values.investigationStreamKey &&
+ event.toolName === 'explain-chart' &&
+ event.phase === 'completed'
+ ) {
+ actions.explainChartToolCompleted(
+ event.toolCallId,
+ resolveToolCall(event.invocation).innerInput ?? null,
+ getToolOutputRecord({
+ rawOutput: event.invocation.output,
+ status: event.invocation.status,
+ })
+ )
+ }
+ },
+ onTurnComplete: endIfOurs,
+ onRunTerminal: endIfOurs,
+ })
+ return () => toolStreamEventsLogic.actions.deregisterToolListener(listenerId)
+ },
+ 'investigation',
+ { pauseOnPageHidden: false }
+ )
+ actions.openSidePanel(SidePanelTab.Max, autoRunMaxPrompt(values.investigationPrompt))
+ },
+ setActiveCreation: ({ creation }) => {
+ if (values.investigating && values.investigationStreamKey === null) {
+ actions.setInvestigationStream(creation.streamKey)
+ }
+ },
+ setInvestigationStream: ({ streamKey }) => {
+ cache.disposables.add(() => runStreamLogic({ streamKey }).mount(), 'investigationStream', {
+ pauseOnPageHidden: false,
+ })
+ },
+ investigationEnded: () => {
+ cache.disposables.dispose('investigation')
+ cache.disposables.dispose('investigationStream')
+ },
+ explainChartToolCompleted: ({ toolCallId, input, output }) => {
+ cache.appliedToolCallIds ??= new Set<string>()
+ if (cache.appliedToolCallIds.has(toolCallId)) {
+ return
+ }
+ const story = explainChartStoryFor(values.insight, input, output)
+ if (!story) {
+ return
+ }
+ cache.appliedToolCallIds.add(toolCallId)
+ const startedHere = values.investigating
+ actions.receiveStory(story)
+ if (startedHere) {
+ actions.closeSidePanel(SidePanelTab.Max)
+ }
+ },
+ askFollowUp: ({ page, step }) => {
+ posthog.capture('explain chart follow-up opened', { page_index: step })
+ actions.setFollowUpContext(followUpContextFor(values.insight, page, step))
+ actions.openSidePanel(SidePanelTab.Max)
+ },
+ receiveStory: ({ story }) => {
+ posthog.capture('explain chart story shown', { chapters: story.chapters.length })
+ },
+ saveInsightSuccess: () => {
+ actions.forgetStory()
+ },
+ })),
+])
+
+const EXPLAINABLE_DISPLAYS: ChartDisplayType[] = [
+ ChartDisplayType.ActionsLineGraph,
+ ChartDisplayType.ActionsBar,
+ ChartDisplayType.ActionsUnstackedBar,
+ ChartDisplayType.ActionsAreaGraph,
+ ChartDisplayType.ActionsStackedBar,
+]
+
+function isOverTime(display: ChartDisplayType | null | undefined): boolean {
+ return !display || EXPLAINABLE_DISPLAYS.includes(display)
+}
diff --git a/products/product_analytics/frontend/insights/explainChart/explainChartStory.test.ts b/products/product_analytics/frontend/insights/explainChart/explainChartStory.test.ts
new file mode 100644
index 000000000000..656df1e3d5f7
--- /dev/null
+++ b/products/product_analytics/frontend/insights/explainChart/explainChartStory.test.ts
@@ -0,0 +1,26 @@
+import type { insightLogicValues } from 'scenes/insights/insightLogic'
+
+import { explainChartStoryFor } from './explainChartStory'
+
+const INSIGHT = { id: 42, short_id: 'aBc12345' } as insightLogicValues['insight']
+const STORY = {
+ query: { kind: 'TrendsQuery' },
+ results: [{ label: 'Pageviews', data: [1, 2, 3], days: ['2026-10-01', '2026-10-02', '2026-10-03'] }],
+ seriesIndex: 0,
+ insightName: 'Pageviews',
+ lastPointInProgress: false,
+ headline: 'A peak on **October 2**.',
+ chapters: [],
+}
+
+describe('explainChartStoryFor', () => {
+ test.each([
+ ['the short id', { insightId: 'aBc12345' }, STORY, STORY],
+ ['the numeric id under an alias', { id: 42 }, STORY, STORY],
+ ['another insight', { insightId: 'zzz99999' }, STORY, null],
+ ['an unsaved query', { query: { kind: 'TrendsQuery' } }, STORY, null],
+ ['a result that is not a story', { insightId: 'aBc12345' }, { headline: 'A peak' }, null],
+ ])('takes a story for %s only when it explains this insight', (_, input, output, expected) => {
+ expect(explainChartStoryFor(INSIGHT, input, output)).toEqual(expected)
+ })
+})
diff --git a/products/product_analytics/frontend/insights/explainChart/explainChartStory.ts b/products/product_analytics/frontend/insights/explainChart/explainChartStory.ts
new file mode 100644
index 000000000000..4f54d9566b66
--- /dev/null
+++ b/products/product_analytics/frontend/insights/explainChart/explainChartStory.ts
@@ -0,0 +1,54 @@
+import type { insightLogicValues } from 'scenes/insights/insightLogic'
+
+import type { AttachedContextItem } from '~/layout/ai/attachedContext'
+
+import type { ExplainChartData } from 'products/product_analytics/mcp/apps/explainChart/explainChartTypes'
+import type { StoryPage } from 'products/product_analytics/mcp/apps/explainChart/storyPages'
+
+const INSIGHT_ID_KEYS = ['insightId', 'insight_id', 'id', 'short_id', 'shortId']
+
+export function explainChartStoryFor(
+ insight: insightLogicValues['insight'],
+ input: Record<string, unknown> | null,
+ output: Record<string, unknown> | null
+): ExplainChartData | null {
+ const insightIds = [insight.short_id, insight.id].filter((id) => id !== undefined && id !== null).map(String)
+ const requested = INSIGHT_ID_KEYS.map((key) => input?.[key]).find((id) => id !== undefined && id !== null)
+ if (requested === undefined || !insightIds.includes(String(requested))) {
+ return null
+ }
+ return isExplainChartData(output) ? output : null
+}
+
+export function followUpContextFor(
+ insight: insightLogicValues['insight'],
+ page: StoryPage,
+ step: number
+): AttachedContextItem {
+ const name = insight.name || insight.derived_name || 'this chart'
+ const parts = [
+ `Step ${step} of the chart explanation for the "${name}" insight (${insight.short_id}): ${page.title}.`,
+ page.facts,
+ page.chapter?.summary,
+ page.chapter?.cause && `Likely cause: ${page.chapter.cause}`,
+ ]
+ return {
+ type: 'text',
+ label: `Step ${step}: ${page.title}`,
+ value: parts.filter(Boolean).join(' '),
+ }
+}
+
+function isExplainChartData(
+ output: Record<string, unknown> | null
+): output is ExplainChartData & Record<string, unknown> {
+ return (
+ !!output &&
+ typeof output.headline === 'string' &&
+ Array.isArray(output.chapters) &&
+ Array.isArray(output.results) &&
+ typeof output.seriesIndex === 'number' &&
+ typeof output.query === 'object' &&
+ output.query !== null
+ )
+}
diff --git a/products/product_analytics/mcp/apps/explainChart/ExplainChartView.tsx b/products/product_analytics/mcp/apps/explainChart/ExplainChartView.tsx
index 235a1048a7f7..4ef6ed0de4b6 100644
--- a/products/product_analytics/mcp/apps/explainChart/ExplainChartView.tsx
+++ b/products/product_analytics/mcp/apps/explainChart/ExplainChartView.tsx
@@ -47,6 +47,8 @@ export interface ExplainChartViewProps {
formatValue?: (value: number) => string
onPageChange?: (change: StoryPageChange) => void
evidenceCharts?: StoryEvidenceCharts
+ seriesKey?: string
+ chapterAction?: (page: StoryPage, step: number) => ReactNode
}
function hasChapter(page: StoryPage): page is StoryPage & { chapter: StoryChapter } {
@@ -76,6 +78,8 @@ export function ExplainChartView({
formatValue = defaultFormat,
onPageChange,
evidenceCharts,
+ seriesKey,
+ chapterAction,
}: ExplainChartViewProps): ReactElement {
const pages = useMemo(() => buildStoryPages(data, formatValue), [data, formatValue])
// With one chapter, a summary page and steps add nothing, so the explanation is that chapter alone.
@@ -126,7 +130,7 @@ export function ExplainChartView({
const overlay = (
<StoryChartOverlay
- seriesKey={String(data.seriesIndex)}
+ seriesKey={seriesKey ?? String(data.seriesIndex)}
pages={pages}
highlightedIndex={previewIndex ?? activeIndex}
activeIndex={activeIndex}
@@ -220,6 +224,9 @@ export function ExplainChartView({
onPreview={setPreviewIndex}
/>
)}
+ {chapterAction && hasChapter(active) && (
+ <div className="mt-4">{chapterAction(active, activeIndex)}</div>
+ )}
</div>
{/* One chapter shows on its own and a chart with none shows its summary alone, so steps add nothing. */}
{pages.length > 2 && (
diff --git a/products/product_analytics/mcp/apps/explainChart/StoryLikelyCause.tsx b/products/product_analytics/mcp/apps/explainChart/StoryLikelyCause.tsx
index a10fd67665b6..52c69dce2fb6 100644
--- a/products/product_analytics/mcp/apps/explainChart/StoryLikelyCause.tsx
+++ b/products/product_analytics/mcp/apps/explainChart/StoryLikelyCause.tsx
@@ -43,7 +43,7 @@ export function StoryLikelyCause({ cause, confidence, confidenceReason }: StoryL
render={
<button
type="button"
- className="cursor-default rounded-md border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-ring"
+ className="flex cursor-default rounded-md border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-ring"
data-attr="explain-chart-confidence"
/>
}
diff --git a/products/product_analytics/package.json b/products/product_analytics/package.json
index 9043ebc06f90..0791f773bd90 100644
--- a/products/product_analytics/package.json
+++ b/products/product_analytics/package.json
@@ -11,6 +11,7 @@
"kea-loaders": "catalog:",
"kea-router": "catalog:",
"kea-subscriptions": "catalog:",
+ "lucide-react": "^0.577.0",
"posthog-js": "catalog:"
},
"devDependencies": {