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): track chart explanation links from save to read (#130896)

Sam Pennington56380894a3ee
diff --git a/products/product_analytics/backend/presentation/insight_explanation.py b/products/product_analytics/backend/presentation/insight_explanation.py
index c9e5c62f3a4a..28a3e8226052 100644
--- a/products/product_analytics/backend/presentation/insight_explanation.py
+++ b/products/product_analytics/backend/presentation/insight_explanation.py
@@ -18,6 +18,7 @@ from rest_framework_dataclasses.serializers import DataclassSerializer
from posthog.api.mixins import ValidatedRequest, validated_request
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.event_usage import report_user_action
from posthog.models import User
from posthog.permissions import AccessControlPermission, APIScopePermission, TeamMemberAccessPermission
@@ -319,6 +320,7 @@ class InsightExplanationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)
user_id=cast(User, request.user).id,
data=request.validated_data["data"],
)
+ self._report_saved(request, explanation, updated=False)
return Response(ChartExplanationSerializer(instance=explanation).data, status=status.HTTP_201_CREATED)
@validated_request(
@@ -335,8 +337,23 @@ class InsightExplanationViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet)
)
if explanation is None:
raise NotFound("You saved no explanation of this insight with this id.")
+ self._report_saved(request, explanation, updated=True)
return Response(ChartExplanationSerializer(instance=explanation).data)
+ def _report_saved(self, request: Request, explanation: ChartExplanation, *, updated: bool) -> None:
+ # Each save hands the agent a link, so this counts the links people are given, split by MCP client.
+ report_user_action(
+ cast(User, request.user),
+ "explain chart link saved",
+ {
+ "explanation_id": str(explanation.id),
+ "insight_id": self.insight.short_id,
+ "updated": updated,
+ },
+ team=self.team,
+ request=request,
+ )
+
@extend_schema(responses={200: ChartExplanationSerializer})
def retrieve(self, request: Request, pk: UUID, **kwargs: Any) -> Response:
explanation = api.get_insight_explanation(
diff --git a/products/product_analytics/backend/tests/api/test_insight_explanation.py b/products/product_analytics/backend/tests/api/test_insight_explanation.py
index d1eb1860d337..9f814a547a60 100644
--- a/products/product_analytics/backend/tests/api/test_insight_explanation.py
+++ b/products/product_analytics/backend/tests/api/test_insight_explanation.py
@@ -127,7 +127,8 @@ class TestInsightExplanationAPI(APIBaseTest):
assert response.status_code == status.HTTP_404_NOT_FOUND
- def test_fixing_an_explanation_keeps_its_link(self) -> None:
+ @patch("products.product_analytics.backend.presentation.insight_explanation.report_user_action")
+ def test_fixing_an_explanation_keeps_its_link(self, report_user_action: Any) -> None:
created = self.client.post(self._url(self.insight), {"data": EXPLANATION}, format="json")
url = f"{self._url(self.insight)}{created.json()['id']}/"
@@ -136,6 +137,13 @@ class TestInsightExplanationAPI(APIBaseTest):
assert fixed.status_code == status.HTTP_200_OK, fixed.json()
assert fixed.json()["id"] == created.json()["id"]
assert self.client.get(url).json()["data"]["headline"] == "A spike from **ads**."
+ assert [(call.args[1], call.args[2]) for call in report_user_action.call_args_list] == [
+ (
+ "explain chart link saved",
+ {"explanation_id": created.json()["id"], "insight_id": self.insight.short_id, "updated": updated},
+ )
+ for updated in (False, True)
+ ]
@parameterized.expand(
[
diff --git a/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsx b/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsx
index f5e92073b8aa..a2558ab3ebbd 100644
--- a/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsx
+++ b/products/product_analytics/frontend/insights/explainChart/InsightExplainChart.tsx
@@ -1,7 +1,7 @@
import { useActions, useValues } from 'kea'
import { ExternalLink } from 'lucide-react'
import posthog from 'posthog-js'
-import type { ReactNode } from 'react'
+import { type ReactNode, useMemo } from 'react'
import { LemonBanner } from '@posthog/lemon-ui'
@@ -22,7 +22,6 @@ const EVIDENCE_CHARTS: StoryEvidenceCharts = {
canShow: (item) => !!item.chart || !!item.queryTool,
prefetch: () => {},
render: (item) => <ExplainChartEvidenceChart item={item} />,
- onShow: () => posthog.capture('explain chart evidence chart shown'),
}
export interface InsightExplainChartProps {
@@ -40,9 +39,17 @@ export function InsightExplainChart({ insightProps, renderChart }: InsightExplai
storyVisible,
storyOutdated,
storySeriesKey,
+ storyEventProperties,
formatValue,
} = useValues(explainChartLogic(insightProps))
const { askFollowUp } = useActions(explainChartLogic(insightProps))
+ const evidenceCharts = useMemo<StoryEvidenceCharts>(
+ () => ({
+ ...EVIDENCE_CHARTS,
+ onShow: () => posthog.capture('explain chart evidence chart shown', storyEventProperties),
+ }),
+ [storyEventProperties]
+ )
if (storyAvailable && storyShown && storyOutdated) {
return (
@@ -76,7 +83,7 @@ export function InsightExplainChart({ insightProps, renderChart }: InsightExplai
</>
}
formatValue={formatValue}
- evidenceCharts={EVIDENCE_CHARTS}
+ evidenceCharts={evidenceCharts}
seriesKey={storySeriesKey ?? undefined}
chapterAction={
explainAvailable
@@ -89,6 +96,7 @@ export function InsightExplainChart({ insightProps, renderChart }: InsightExplai
from_page_index: fromIndex,
page_count: story.chapters.length + 1,
source,
+ ...storyEventProperties,
})
}
/>
diff --git a/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts b/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts
index 3d96ab2d5dee..6ddfd8ced87e 100644
--- a/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts
+++ b/products/product_analytics/frontend/insights/explainChart/explainChartLogic.ts
@@ -4,6 +4,7 @@ import { urlToAction } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import posthog from 'posthog-js'
+import { ApiError } from 'lib/api-error'
import { FEATURE_FLAGS } from 'lib/constants'
import { formatAggregationAxisValue } from 'lib/insights/aggregationAxisFormat'
import { keyForInsightLogicProps } from 'lib/insights/sharedUtils'
@@ -19,6 +20,7 @@ import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
import { autoRunMaxPrompt } from 'scenes/max/maxPrompt'
import { teamLogic } from 'scenes/teamLogic'
import type { teamLogicValues } from 'scenes/teamLogic'
+import { userLogic } from 'scenes/userLogic'
import { aiConsentLogic } from '~/layout/ai/aiConsentLogic'
import { MAX_SIDE_PANEL_ID } from '~/layout/ai/aiPanelIds'
@@ -31,7 +33,7 @@ import { compareQuery } from '~/queries/nodes/InsightViz/queryUtils'
import { isInsightVizNode } from '~/queries/schema/node-guards'
import type { InsightVizNode, TrendsFilter } from '~/queries/schema/schema-general'
import { ChartDisplayType, SidePanelTab } from '~/types'
-import type { InsightLogicProps, TrendResult } from '~/types'
+import type { InsightLogicProps, TrendResult, UserType } from '~/types'
import {
getToolOutputRecord,
@@ -66,6 +68,7 @@ export interface explainChartLogicValues {
isTrends: boolean // trendsDataLogic
results: TrendResult[] // trendsDataLogic
trendsFilter: TrendsFilter | null | undefined // trendsDataLogic
+ user: UserType | null // userLogic
chartStory: ExplainChartData | null
consentRequested: boolean
explainAvailable: boolean
@@ -80,6 +83,8 @@ export interface explainChartLogicValues {
linkedExplanationId: string | null
story: ExplainChartData | null
storyAvailable: boolean
+ storyEventProperties: StoryEventProperties
+ storyOrigin: StoryOrigin | null
storyOutdated: boolean
storyQuery: Node | null
storySeriesKey: string | null
@@ -146,10 +151,10 @@ export interface explainChartLogicActions {
receiveStory: (
story: ExplainChartData,
query: Node | null,
- source?: StorySource
+ origin?: StoryOrigin
) => {
+ origin: StoryOrigin
query: Node<Record<string, any>> | null
- source: StorySource
story: ExplainChartData
}
requestConsent: () => {
@@ -208,6 +213,7 @@ export interface explainChartLogicMeta {
incompletenessOffsetFromEnd: number
) => ExplainChartData | null
storySeriesKey: (followedChartIndex: number | null, indexedResults: IndexedTrendResult[]) => string | null
+ storyEventProperties: (storyOrigin: StoryOrigin | null) => StoryEventProperties
formatValue: (
trendsFilter: TrendsFilter | null | undefined,
baseCurrency: CurrencyCode
@@ -242,6 +248,8 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
['baseCurrency'],
trendsDataLogic(props),
['display', 'indexedResults', 'isTrends', 'trendsFilter', 'results', 'incompletenessOffsetFromEnd'],
+ userLogic,
+ ['user'],
],
actions: [
sidePanelStateLogic,
@@ -265,10 +273,10 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
output: Record<string, unknown> | null
) => ({ toolCallId, input, output }),
setInvestigationStream: (streamKey: string) => ({ streamKey }),
- receiveStory: (story: ExplainChartData, query: Node | null, source: StorySource = 'agent') => ({
+ receiveStory: (story: ExplainChartData, query: Node | null, origin: StoryOrigin = AGENT_ORIGIN) => ({
story,
query,
- source,
+ origin,
}),
setLinkedExplanationId: (explanationId: string | null) => ({ explanationId }),
loadLinkedExplanation: true,
@@ -317,6 +325,13 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
forgetStory: () => null,
},
],
+ storyOrigin: [
+ null as StoryOrigin | null,
+ {
+ receiveStory: (_, { origin }) => origin,
+ forgetStory: () => null,
+ },
+ ],
linkedExplanationId: [
null as string | null,
{
@@ -415,6 +430,13 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
return String(rendered?.id ?? followedChartIndex)
},
],
+ storyEventProperties: [
+ (s) => [s.storyOrigin],
+ (storyOrigin: StoryOrigin | null): StoryEventProperties => ({
+ story_source: storyOrigin?.source ?? null,
+ explanation_id: storyOrigin?.source === 'link' ? storyOrigin.explanationId : null,
+ }),
+ ],
formatValue: [
(s) => [s.trendsFilter, s.baseCurrency],
(trendsFilter: TrendsFilter | null | undefined, baseCurrency: teamLogicValues['baseCurrency']) =>
@@ -446,6 +468,11 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
return
}
if (explanation.data.shape !== 'time_series') {
+ // pinned: analytics event name
+ posthog.capture('explain chart link failed', {
+ explanation_id: explanationId,
+ reason: 'unsupported_shape',
+ })
lemonToast.error(
'This chart explanation needs a newer version of PostHog. Refresh the page to see it.'
)
@@ -454,12 +481,21 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
actions.receiveStory(
withEvidenceLinks(explanation.data as ExplainChartData),
explainedQuery(values.savedInsight.query, explanation.data.query),
- 'link'
+ {
+ source: 'link',
+ explanationId,
+ openedByAuthor: !!explanation.created_by && explanation.created_by.id === values.user?.id,
+ }
)
- } catch {
+ } catch (error) {
if (cache.disposables.isDisposed) {
return
}
+ posthog.capture('explain chart link failed', {
+ explanation_id: explanationId,
+ reason: error instanceof ApiError && error.status === 404 ? 'not_found' : 'error',
+ status: error instanceof ApiError ? (error.status ?? null) : null,
+ })
if (cache.linkedExplanationIdLoaded === explanationId) {
cache.linkedExplanationIdLoaded = null
}
@@ -554,12 +590,18 @@ export const explainChartLogic: LogicWrapper<explainChartLogicType> = kea<explai
actions.closeSidePanel(SidePanelTab.Max)
},
askFollowUp: ({ page, step }) => {
- posthog.capture('explain chart follow-up opened', { page_index: step })
+ posthog.capture('explain chart follow-up opened', { page_index: step, ...values.storyEventProperties })
actions.setFollowUpContext(followUpContextFor(values.insight, page, step))
actions.openSidePanel(SidePanelTab.Max)
},
- receiveStory: ({ story, source }) => {
- posthog.capture('explain chart story shown', { chapters: story.chapters.length, source })
+ receiveStory: ({ story, origin }) => {
+ posthog.capture('explain chart story shown', {
+ chapters: story.chapters.length,
+ // `source` predates `story_source` and stays for the insights that read it.
+ source: origin.source,
+ ...values.storyEventProperties,
+ ...(origin.source === 'link' ? { opened_by_author: origin.openedByAuthor } : {}),
+ })
},
saveInsightSuccess: () => {
if (values.storyOutdated) {
@@ -594,4 +636,12 @@ function dataDiffers(a: Node | null | undefined, b: Node | null | undefined): bo
return !!a && !!b && !compareQuery(a, b, { ignoreVisualizationOnlyChanges: true })
}
-type StorySource = 'agent' | 'link'
+export type StoryOrigin = { source: 'agent' } | { source: 'link'; explanationId: string; openedByAuthor: boolean }
+
+const AGENT_ORIGIN: StoryOrigin = { source: 'agent' }
+
+/** Sent with every explanation event, so each step can be split by how the explanation arrived. */
+export interface StoryEventProperties {
+ story_source: StoryOrigin['source'] | null
+ explanation_id: string | null
+}