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): save chart explanations from PostHog AI so a link reopens them (#130907)

Sam Penningtonef4d7e525bc7
diff --git a/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts b/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts
index 6ddfd8ced87e..5384de4f8d69 100644
--- a/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts
+++ b/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts
@@ -1,6 +1,6 @@
import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import type { LogicWrapper } from 'kea'
-import { urlToAction } from 'kea-router'
+import { router, urlToAction } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
@@ -41,10 +41,15 @@ import {
runStreamLogic,
toolStreamEventsLogic,
} from 'products/posthog_ai/frontend/api/logics'
-import { insightsExplanationsRetrieve } from 'products/product_analytics/frontend/generated/api'
+import {
+ insightsExplanationsCreate,
+ insightsExplanationsRetrieve,
+} from 'products/product_analytics/frontend/generated/api'
+import type { InsightExplanationCreateApi } from 'products/product_analytics/frontend/generated/api.schemas'
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 { storedExplanation } from 'products/product_analytics/mcp/apps/explainChart/storedExplanation'
import { insightPageShowsStory } from 'products/product_analytics/mcp/apps/explainChart/storyDisplays'
import type { StoryPage } from 'products/product_analytics/mcp/apps/explainChart/storyPages'
import { followedSeriesIndex } from 'products/product_analytics/mcp/apps/explainChart/storySeries'
@@ -175,6 +180,9 @@ export interface explainChartLogicActions {
startInvestigation: () => {
value: true
}
+ storySaved: (explanationId: string) => {
+ explanationId: string
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -278,6 +286,7 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
query,
origin,
}),
+ storySaved: (explanationId: string) => ({ explanationId }),
setLinkedExplanationId: (explanationId: string | null) => ({ explanationId }),
loadLinkedExplanation: true,
showStory: true,
@@ -329,6 +338,8 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
null as StoryOrigin | null,
{
receiveStory: (_, { origin }) => origin,
+ storySaved: (origin, { explanationId }) =>
+ origin?.source === 'agent' ? { ...origin, explanationId } : origin,
forgetStory: () => null,
},
],
@@ -434,7 +445,7 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
(s) => [s.storyOrigin],
(storyOrigin: StoryOrigin | null): StoryEventProperties => ({
story_source: storyOrigin?.source ?? null,
- explanation_id: storyOrigin?.source === 'link' ? storyOrigin.explanationId : null,
+ explanation_id: storyOrigin?.explanationId ?? null,
}),
],
formatValue: [
@@ -594,7 +605,7 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
actions.setFollowUpContext(followUpContextFor(values.insight, page, step))
actions.openSidePanel(SidePanelTab.Max)
},
- receiveStory: ({ story, origin }) => {
+ receiveStory: async ({ story, origin }) => {
posthog.capture('explain chart story shown', {
chapters: story.chapters.length,
// `source` predates `story_source` and stays for the insights that read it.
@@ -602,6 +613,32 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
...values.storyEventProperties,
...(origin.source === 'link' ? { opened_by_author: origin.openedByAuthor } : {}),
})
+ const insightId = values.insightId
+ const shortId = values.insight.short_id
+ if (origin.source !== 'agent' || !insightId || !shortId) {
+ return
+ }
+ try {
+ const saved = await insightsExplanationsCreate(String(getCurrentTeamId()), insightId, {
+ data: storedExplanation(story) as unknown as InsightExplanationCreateApi['data'],
+ })
+ if (cache.disposables.isDisposed || values.story !== story) {
+ return
+ }
+ // The address bar now opens this explanation, so loading it from there again is skipped.
+ cache.linkedExplanationIdLoaded = saved.id
+ actions.storySaved(saved.id)
+ const { location, searchParams, hashParams } = router.values
+ if (
+ [`/insights/${shortId}`, `/insights/${shortId}/edit`].some((path) =>
+ location.pathname.endsWith(path)
+ )
+ ) {
+ router.actions.replace(location.pathname, { ...searchParams, explanation: saved.id }, hashParams)
+ }
+ } catch {
+ // Someone who can view the insight but not edit it cannot save, so their explanation has no link.
+ }
},
saveInsightSuccess: () => {
if (values.storyOutdated) {
@@ -614,8 +651,8 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
storyAvailable: () => actions.loadLinkedExplanation(),
})),
urlToAction(({ actions, props }) => ({
- '/insights/:shortId': ({ shortId }, { explanation }) => {
- if (shortId === props.dashboardItemId) {
+ '/insights/:shortId(/:mode)': ({ shortId, mode }, { explanation }) => {
+ if (shortId === props.dashboardItemId && (mode === undefined || mode === 'edit')) {
actions.setLinkedExplanationId(
typeof explanation === 'string' && isUUIDLike(explanation) ? explanation : null
)
@@ -636,9 +673,11 @@ function dataDiffers(a: Node | null | undefined, b: Node | null | undefined): bo
return !!a && !!b && !compareQuery(a, b, { ignoreVisualizationOnlyChanges: true })
}
-export type StoryOrigin = { source: 'agent' } | { source: 'link'; explanationId: string; openedByAuthor: boolean }
+export type StoryOrigin =
+ | { source: 'agent'; explanationId: string | null }
+ | { source: 'link'; explanationId: string; openedByAuthor: boolean }
-const AGENT_ORIGIN: StoryOrigin = { source: 'agent' }
+const AGENT_ORIGIN: StoryOrigin = { source: 'agent', explanationId: null }
/** Sent with every explanation event, so each step can be split by how the explanation arrived. */
export interface StoryEventProperties {
diff --git a/products/product_analytics/mcp/apps/explainChart/storedExplanation.ts b/products/product_analytics/mcp/apps/explainChart/storedExplanation.ts
new file mode 100644
index 000000000000..ccc415f56296
--- /dev/null
+++ b/products/product_analytics/mcp/apps/explainChart/storedExplanation.ts
@@ -0,0 +1,20 @@
+import type { ExplainChartData } from './explainChartTypes'
+import { storySeriesLabel } from './storySeries'
+
+// The page builds PostHog links from the query or insight id, so only GitHub links are stored.
+export function storedExplanation(data: ExplainChartData): ExplainChartData {
+ return {
+ ...data,
+ results: data.results.map((result, index) =>
+ index === data.seriesIndex
+ ? { ...result, label: storySeriesLabel(result.label) }
+ : { label: storySeriesLabel(result.label) }
+ ),
+ chapters: data.chapters.map((chapter) => ({
+ ...chapter,
+ evidence: chapter.evidence.map((item) =>
+ item.query || item.insightShortId ? { ...item, url: null } : item
+ ),
+ })),
+ }
+}
diff --git a/services/mcp/src/tools/insights/explainChartSave.ts b/services/mcp/src/tools/insights/explainChartSave.ts
index f0203d223de7..6f974d6fa490 100644
--- a/services/mcp/src/tools/insights/explainChartSave.ts
+++ b/services/mcp/src/tools/insights/explainChartSave.ts
@@ -4,8 +4,7 @@ import { PostHogApiError } from '@/lib/errors'
import { ExplainChartSaveInputSchema } from '@/schema/tool-inputs'
import { type Context, POSTHOG_FORMATTED_RESULTS_OVERRIDE_KEY, type ToolBase } from '@/tools/types'
-import type { ExplainChartData } from 'products/product_analytics/mcp/apps/explainChart/explainChartTypes'
-import { storySeriesLabel } from 'products/product_analytics/mcp/apps/explainChart/storySeries'
+import { storedExplanation } from 'products/product_analytics/mcp/apps/explainChart/storedExplanation'
import { buildExplanation } from './explainChart'
@@ -22,24 +21,6 @@ type Result = {
const NOT_LINKABLE =
'This chart has no saved insight that shows the explanation beside it, so there is no link. Give the findings in text.'
-// The page builds PostHog links from the query or insight id, so only GitHub links are stored.
-function storedExplanation(data: ExplainChartData): ExplainChartData {
- return {
- ...data,
- results: data.results.map((result, index) =>
- index === data.seriesIndex
- ? { ...result, label: storySeriesLabel(result.label) }
- : { label: storySeriesLabel(result.label) }
- ),
- chapters: data.chapters.map((chapter) => ({
- ...chapter,
- evidence: chapter.evidence.map((item) =>
- item.query || item.insightShortId ? { ...item, url: null } : item
- ),
- })),
- }
-}
-
function isNotFound(error: unknown): boolean {
return error instanceof PostHogApiError && error.status === 404
}