: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(mcp): add the explain-chart walkthrough view (#119219)
Sam Pennington97fb27ffcf7b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 83dffa7ef3aa..d79d3e56987f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6426,6 +6426,12 @@ snapshots:hash: v1.k794b7964.fb16e88ea3b384dd8f67fe6012124373f57c30e37c09a786aa222664bb7fcb8b.mgcHhsY-mwox6xCW6CCwDrmhgLfHnLRPosHWNigYE_Ymcp-apps-experiments--running--light:hash: v1.k794b7964.f7ae67feb87956b98204afeb00f52012a62fc090b18d186d0575110924e5cb69.lWvegECniqeejO8WWNUVam5X0NQTkwxq2iifV-mN5JI+ mcp-apps-explain-chart--chapter-beside-the-chart--light:+ hash: v1.k794b7964.59974ba8a33be7e981f575614bb77b3fe73dc905c9f6cb5db54e61591c7484ae.Qzl-nCRtGQHeYMHKmGsneXCagaDtWsjsyZlavdRVmmU+ mcp-apps-explain-chart--evidence-chart--light:+ hash: v1.k794b7964.c25bffca27dae4d96ed3a8a534297c79fc55e9f5a332472bedfeb46f4cb79bd8.DQxHAg-l47utDGyaTLdaaAMkkaLBaeHnxF-YTKFnmh0+ mcp-apps-explain-chart--summary--light:+ hash: v1.k794b7964.8e544f3f6c9e2e43bf03efd6bf30e402e2f24a41ec060922b5e3068643ce4c86.BQcCbMIGeBusavfXWYInYZD6jMZfnN4zr-HV9oOAFHgmcp-apps-feature-flags--boolean-flag--light:hash: v1.k794b7964.f3ee0e724e30f350166b5a87d46cd36ba9f982735aa9d7e322aeaf28bc4c9b1c.KzlRVALZdoWS2mlKcnTJRTOo4SmFvIZzKhj6SodWt3Imcp-apps-feature-flags--flag-list--light:diff --git a/products/product_analytics/mcp/apps/explainChart/ExplainChartView.stories.tsx b/products/product_analytics/mcp/apps/explainChart/ExplainChartView.stories.tsxnew file mode 100644index 000000000000..f3600472be3c--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/ExplainChartView.stories.tsx@@ -0,0 +1,181 @@+import type { Meta, StoryFn, StoryObj } from '@storybook/react'+import { within } from '@testing-library/dom'+import type { ReactElement, ReactNode } from 'react'++import { McpThemeDecorator } from '@posthog/mcp-ui/storybook/decorator'+import { DEFAULT_CHART_COLORS, type Series, TimeSeriesLineChart, useChartTheme } from '@posthog/quill-charts'++import { userEvent } from 'storybook/test'++import type { ExplainChartData } from './explainChartTypes'+import { ExplainChartView, type StoryEvidenceCharts } from './ExplainChartView'+import { isSeriesNamedIn } from './storyNamedSeries'++const VALUES = [+ 58, 24, 22, 61, 64, 59, 63, 57, 26, 21, 60, 66, 62, 59, 498, 31, 23, 63, 58, 65, 61, 92, 41, 38, 95, 101, 97, 104,+ 99, 18,+]+const DAYS = VALUES.map((_, index) => new Date(Date.UTC(2026, 8, 18 + index)).toISOString().slice(0, 10))+const SPIKE_INDEX = 14+const referrer = (index: number, name: string, typical: (value: number) => number, spike: number): Series => ({+ key: String(index),+ label: `signed_up - ${name}`,+ data: VALUES.map((value, day) => (day === SPIKE_INDEX ? spike : typical(value))),+ color: DEFAULT_CHART_COLORS[index],+})+const REFERRERS = ['news.example.com', '$direct', 'google.com']+const BY_REFERRER: Series[] = [+ referrer(0, REFERRERS[0]!, () => 3, 412),+ referrer(1, REFERRERS[1]!, (value) => Math.round(value * 0.55), 52),+ referrer(2, REFERRERS[2]!, (value) => Math.round(value * 0.4), 34),+]++const story: ExplainChartData = {+ query: { kind: 'TrendsQuery', interval: 'day', series: [{ kind: 'EventsNode', event: 'signed_up' }] },+ results: [{ label: 'signed_up', data: VALUES, days: DAYS }],+ seriesIndex: 0,+ insightName: 'Sign-ups',+ lastPointInProgress: true,+ headline:+ 'One article on **news.example.com** caused the spike, and sign-ups from **Canada** lifted the level since.',+ chapters: [+ {+ title: 'A spike on October 2',+ range: [14, 14],+ summary: 'One day stands far above the rest of the month, and the next day is back to normal.',+ cause: 'Almost all of the extra sign-ups came from **news.example.com** to the **/pricing** page. This looks like one article sending visitors, not a change in the product.',+ confidence: 'high',+ confidenceReason:+ 'The referrer and the page both account for most of the day, and an annotation marks the article.',+ evidence: [+ {+ text: '**news.example.com** sent 412 of the 498 sign-ups that day, against 3 on a typical day.',+ url: 'https://us.posthog.com/project/1/insights/new',+ query: {+ kind: 'TrendsQuery',+ series: [{ kind: 'EventsNode', event: 'signed_up' }],+ breakdownFilter: { breakdown: '$referring_domain' },+ },+ },+ { text: 'An annotation on October 2 reads "Launch article published".', url: null },+ ],+ },+ {+ title: 'Higher since October 9',+ range: [21, 28],+ summary: 'The level steps up and stays there.',+ cause: 'Most of the rise comes from **Canada**, which started the same week as the **French-language** signup page.',+ confidence: 'medium',+ confidenceReason: null,+ evidence: [+ {+ text: 'Sign-ups from **Canada** went from 4 to 38 on a typical day.',+ url: 'https://us.posthog.com/project/1/insights/new',+ },+ ],+ },+ {+ title: 'Today so far',+ range: [29, 29],+ summary: null,+ cause: null,+ confidence: null,+ confidenceReason: null,+ evidence: [],+ },+ ],+}++const SIGN_UPS: Series[] = [{ key: '0', label: 'signed_up', data: VALUES, color: DEFAULT_CHART_COLORS[0] }]+const CHART_CONFIG = { xAxis: { interval: 'day', timezone: 'UTC' } } as const++function StoryChart({ series, overlay }: { series: Series[]; overlay?: ReactNode }): ReactElement {+ const theme = useChartTheme()+ return (+ <div className="flex h-[260px] flex-col @3xl/story:h-[400px]">+ <TimeSeriesLineChart series={series} labels={DAYS} theme={theme} config={CHART_CONFIG}>+ {overlay}+ </TimeSeriesLineChart>+ </div>+ )+}++const evidenceCharts: StoryEvidenceCharts = {+ canShow: () => true,+ prefetch: () => {},+ render: (_, text) => (+ <StoryChart+ series={BY_REFERRER.map((item, index) =>+ isSeriesNamedIn([item.label, REFERRERS[index]!], text) ? item : { ...item, color: `${item.color}40` }+ )}+ />+ ),+}++const renderStory = (): ReactElement => (+ <ExplainChartView+ data={story}+ renderChart={(overlay) => <StoryChart series={SIGN_UPS} overlay={overlay} />}+ openLink={() => {}}+ evidenceCharts={evidenceCharts}+ />+)++// The chart sizes its canvas off a ResizeObserver, so give it a definite width.+const width =+ (className: string) =>+ (Story: StoryFn): ReactElement => (+ <div className={className}>+ <Story />+ </div>+ )++// Opts the subtree into Quill's tokens, which the walkthrough reads directly as `var(--card)` and the like.+const quillTokens = (Story: StoryFn): ReactElement => (+ <div data-quill data-mcp-storybook>+ <Story />+ </div>+)++const meta: Meta = {+ title: 'MCP Apps/Explain Chart',+ decorators: [quillTokens, McpThemeDecorator],+ parameters: {+ mcpMaxWidth: 'none',+ testOptions: {+ // McpThemeDecorator has no dark mode, so skip it to avoid duplicated snapshots.+ skipDarkMode: true,+ },+ },+}+export default meta++type Story = StoryObj<{}>++export const Summary: Story = {+ decorators: [width('w-[680px]')],+ render: renderStory,+}++export const ChapterBesideTheChart: Story = {+ decorators: [width('w-[1100px]')],+ render: renderStory,+ play: async ({ canvasElement }) => {+ // The step and the marker on the chart share this name, and either one opens the chapter.+ const [button] = await within(canvasElement).findAllByRole('button', {+ name: 'Chapter 1: A spike on October 2',+ })+ await userEvent.click(button!)+ },+}++export const EvidenceChart: Story = {+ decorators: [width('w-[1100px]')],+ render: renderStory,+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement)+ const [chapter] = await canvas.findAllByRole('button', { name: 'Chapter 1: A spike on October 2' })+ await userEvent.click(chapter!)+ await userEvent.click(await canvas.findByRole('button', { name: 'Show chart' }))+ },+}diff --git a/products/product_analytics/mcp/apps/explainChart/ExplainChartView.tsx b/products/product_analytics/mcp/apps/explainChart/ExplainChartView.tsxnew file mode 100644index 000000000000..e0b604dae25b--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/ExplainChartView.tsx@@ -0,0 +1,215 @@+import { ArrowLeft } from 'lucide-react'+import { type ReactElement, type ReactNode, useEffect, useMemo, useState } from 'react'++import { Button, Text } from '@posthog/quill'++import type { ExplainChartData, StoryChapter, StoryEvidence } from './explainChartTypes'+import { StoryChapterView } from './StoryChapterView'+import { StoryChartOverlay } from './StoryChartOverlay'+import { buildStoryPages, type StoryPage } from './storyPages'+import { StorySteps } from './StorySteps'+import { StorySummaryView } from './StorySummaryView'++const wholeFormat = new Intl.NumberFormat('en-US', { maximumFractionDigits: 1 })+const smallFormat = new Intl.NumberFormat('en-US', { maximumSignificantDigits: 2 })+const defaultFormat = (value: number): string =>+ (value !== 0 && Math.abs(value) < 1 ? smallFormat : wholeFormat).format(value)++export type StoryNavigationSource = 'marker' | 'step' | 'summary_list' | 'next' | 'back'++export interface StoryPageChange {+ index: number+ fromIndex: number+ source: StoryNavigationSource+}++export interface StoryEvidenceCharts {+ canShow: (query: Record<string, unknown>) => boolean+ prefetch: (queries: Record<string, unknown>[]) => void+ /** Draws the chart, fading every series that the evidence's text does not name. */+ render: (query: Record<string, unknown>, text: string) => ReactNode+ onShow?: (query: Record<string, unknown>) => void+}++export interface ExplainChartViewProps {+ data: ExplainChartData+ /** Draws the chart with the overlay as a child, so the overlay can read the chart's scales. */+ renderChart: (overlay: ReactNode) => ReactNode+ openLink: (url: string) => void+ title?: string | null+ formatValue?: (value: number) => string+ onPageChange?: (change: StoryPageChange) => void+ evidenceCharts?: StoryEvidenceCharts+}++function hasChapter(page: StoryPage): page is StoryPage & { chapter: StoryChapter } {+ return page.chapter !== null+}++function warningMessages(warnings: unknown[] = []): string[] {+ return warnings.map((warning) =>+ typeof warning === 'string' ? warning : ((warning as { message?: string }).message ?? JSON.stringify(warning))+ )+}++function seriesNoteOf(data: ExplainChartData): string | null {+ if (data.results.length < 2) {+ return null+ }+ const series = data.results[data.seriesIndex]+ const label = series?.label || series?.action?.name || `series ${data.seriesIndex + 1}`+ return `This follows ${label}, one of the ${data.results.length} series on the chart.`+}++export function ExplainChartView({+ data,+ renderChart,+ openLink,+ title,+ formatValue = defaultFormat,+ onPageChange,+ evidenceCharts,+}: ExplainChartViewProps): ReactElement {+ const pages = useMemo(() => buildStoryPages(data, formatValue), [data, formatValue])+ const [activeIndex, setActiveIndex] = useState(0)+ const [previewIndex, setPreviewIndex] = useState<number | null>(null)+ const [shownEvidenceIndex, setShownEvidenceIndex] = useState<number | null>(null)+ const active = pages[activeIndex] ?? pages[0]!+ const hasNext = activeIndex + 1 < pages.length+ const shownEvidence: StoryEvidence | null =+ shownEvidenceIndex === null ? null : (active.chapter?.evidence[shownEvidenceIndex] ?? null)+ const evidenceView =+ evidenceCharts && shownEvidence?.query ? { text: shownEvidence.text, query: shownEvidence.query } : null++ const prefetch = evidenceCharts?.prefetch+ useEffect(() => {+ const queries = active.chapter?.evidence.flatMap((item) => (item.query ? [item.query] : [])) ?? []+ if (queries.length) {+ prefetch?.(queries)+ }+ }, [active, prefetch])++ const toggleEvidenceChart = (index: number): void => {+ const query = active.chapter?.evidence[index]?.query+ if (index === shownEvidenceIndex || !query) {+ setShownEvidenceIndex(null)+ return+ }+ setShownEvidenceIndex(index)+ evidenceCharts?.onShow?.(query)+ }++ const select = (index: number, source: StoryNavigationSource): void => {+ setPreviewIndex(null)+ setShownEvidenceIndex(null)+ if (index === activeIndex) {+ return+ }+ setActiveIndex(index)+ onPageChange?.({ index, fromIndex: activeIndex, source })+ }++ const overlay = (+ <StoryChartOverlay+ seriesKey={String(data.seriesIndex)}+ pages={pages}+ highlightedIndex={previewIndex ?? activeIndex}+ activeIndex={activeIndex}+ onSelect={(index) => select(index, 'marker')}+ />+ )++ return (+ <div className="@container/story" data-attr="explain-chart">+ <div className="flex flex-col @3xl/story:flex-row">+ <div className="min-w-0 flex-1">+ {/* The header is one line in both views, so showing an evidence chart moves nothing. The evidence's text stays highlighted in the panel. */}+ {evidenceCharts && evidenceView ? (+ <>+ <div className="box-content flex h-5 items-center pb-2">+ <Button+ variant="outline"+ size="xs"+ onClick={() => setShownEvidenceIndex(null)}+ data-attr="explain-chart-evidence-back"+ >+ <ArrowLeft className="size-3" />+ Back to the walkthrough+ </Button>+ </div>+ {evidenceCharts.render(evidenceView.query, evidenceView.text)}+ </>+ ) : (+ <>+ {title && (+ <Text size="sm" weight="medium" className="box-content block h-5 truncate pb-2">+ {title}+ </Text>+ )}+ {renderChart(overlay)}+ </>+ )}+ </div>+ <aside+ className="relative shrink-0 border-t border-border @3xl/story:w-80 @3xl/story:border-t-0 @3xl/story:border-l"+ aria-label="Walkthrough of this chart"+ >+ {/* Beside the chart, the panel takes the chart's height and the page scrolls inside it. */}+ <div className="flex flex-col @3xl/story:absolute @3xl/story:inset-0">+ {/* Keyed on the page, so each chapter opens at its top and an evidence chart keeps the scroll. */}+ <div key={activeIndex} className="min-h-0 flex-1 p-4 @3xl/story:overflow-y-auto">+ {hasChapter(active) ? (+ <StoryChapterView+ page={active}+ openLink={openLink}+ canShowChart={(item) => !!item.query && !!evidenceCharts?.canShow(item.query)}+ shownEvidenceIndex={shownEvidenceIndex}+ onToggleChart={toggleEvidenceChart}+ />+ ) : (+ <StorySummaryView+ headline={data.headline}+ pages={pages}+ seriesNote={seriesNoteOf(data)}+ warnings={warningMessages(data.warnings)}+ onSelect={(index) => select(index, 'summary_list')}+ onPreview={setPreviewIndex}+ />+ )}+ </div>+ <div className="flex items-center justify-between gap-3 border-t border-border py-2 ps-4 pe-3">+ <StorySteps+ pages={pages}+ activeIndex={activeIndex}+ onSelect={(index) => select(index, 'step')}+ onPreview={setPreviewIndex}+ />+ <div className="flex shrink-0 gap-1">+ {activeIndex > 0 && (+ <Button+ variant="outline"+ size="sm"+ onClick={() => select(activeIndex - 1, 'back')}+ data-attr="explain-chart-back"+ >+ Back+ </Button>+ )}+ {hasNext && (+ <Button+ variant="primary"+ size="sm"+ onClick={() => select(activeIndex + 1, 'next')}+ data-attr="explain-chart-next"+ >+ Next+ </Button>+ )}+ </div>+ </div>+ </div>+ </aside>+ </div>+ </div>+ )+}diff --git a/products/product_analytics/mcp/apps/explainChart/StoryChapterView.tsx b/products/product_analytics/mcp/apps/explainChart/StoryChapterView.tsxnew file mode 100644index 000000000000..daecb8dfc945--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/StoryChapterView.tsx@@ -0,0 +1,70 @@+import { type ReactElement } from 'react'++import { Text } from '@posthog/quill'++import type { StoryChapter, StoryEvidence } from './explainChartTypes'+import { StoryEvidenceList } from './StoryEvidenceList'+import { StoryLikelyCause } from './StoryLikelyCause'+import { StoryMarkedText } from './StoryMarkedText'+import type { StoryPage } from './storyPages'++export interface StoryChapterViewProps {+ page: StoryPage & { chapter: StoryChapter }+ openLink: (url: string) => void+ canShowChart: (item: StoryEvidence) => boolean+ shownEvidenceIndex: number | null+ onToggleChart: (index: number) => void+}++export function StoryChapterView({+ page,+ openLink,+ canShowChart,+ shownEvidenceIndex,+ onToggleChart,+}: StoryChapterViewProps): ReactElement {+ const { chapter } = page+ return (+ <div+ className="grid gap-4 transition-opacity duration-300 motion-reduce:transition-none starting:opacity-0 @xl/story:grid-cols-2 @3xl/story:grid-cols-1"+ data-attr="explain-chart-chapter"+ >+ <div className="flex flex-col gap-4">+ <div className="flex flex-col gap-1.5">+ <Text size="base" weight="medium" className="min-w-0 [overflow-wrap:anywhere]">+ {page.title}+ </Text>+ {page.facts && (+ <Text size="sm">+ <StoryMarkedText text={page.facts} />+ </Text>+ )}+ {!page.range && (+ <Text size="xs" variant="muted">+ The chart has no point for this chapter's dates, so nothing is highlighted.+ </Text>+ )}+ {chapter.summary && (+ <Text size="sm">+ <StoryMarkedText text={chapter.summary} />+ </Text>+ )}+ </div>+ {chapter.cause && (+ <StoryLikelyCause+ cause={chapter.cause}+ confidence={chapter.confidence}+ confidenceReason={chapter.confidenceReason}+ />+ )}+ </div>+ <StoryEvidenceList+ evidence={chapter.evidence}+ openLink={openLink}+ canShowChart={canShowChart}+ shownIndex={shownEvidenceIndex}+ onToggleChart={onToggleChart}+ />+ </div>+ )+}diff --git a/products/product_analytics/mcp/apps/explainChart/StoryChartHighlight.tsx b/products/product_analytics/mcp/apps/explainChart/StoryChartHighlight.tsxnew file mode 100644index 000000000000..0061fbfd284a--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/StoryChartHighlight.tsx@@ -0,0 +1,56 @@+/* eslint-disable react/forbid-dom-props -- pixel positions from the chart's scales */+import { type ReactElement } from 'react'++import type { ChartDimensions } from '@posthog/quill-charts'++import { type Band, dimsAround } from './storyOverlayGeometry'++// The brand orange in both themes, so the highlight never reads as one of the chart's series.+const HIGHLIGHT_COLOR = 'var(--primary-light)'+const FEATHER = 28++const tint = (share: number): string => `color-mix(in srgb, ${HIGHLIGHT_COLOR} ${share}%, transparent)`++export interface StoryChartHighlightProps {+ band: Band+ dimensions: ChartDimensions+ /** The chart's background, which the dimmed sides fade into. */+ surface: string+}++export function StoryChartHighlight({ band, dimensions, surface }: StoryChartHighlightProps): ReactElement {+ const { plotTop, plotHeight } = dimensions+ return (+ <>+ {dimsAround(band, dimensions).map((dim, index) => {+ const width = Math.max(dim.right - dim.left, 0)+ const feather = Math.min(FEATHER, width / 2)+ return (+ <div+ key={index}+ className="pointer-events-none absolute opacity-65 transition-[left,width] duration-500 ease-out motion-reduce:transition-none starting:opacity-0"+ style={{+ left: dim.left,+ top: plotTop,+ width,+ height: plotHeight,+ background: `linear-gradient(to right, ${dim.fadeLeft ? 'transparent' : surface}, ${surface} ${feather}px, ${surface} calc(100% - ${feather}px), ${dim.fadeRight ? 'transparent' : surface})`,+ }}+ />+ )+ })}+ <div+ className="pointer-events-none absolute rounded-t-md border-x border-t-2 transition-[left,width] duration-500 ease-out motion-reduce:transition-none starting:opacity-0"+ style={{+ left: band.left,+ top: plotTop,+ width: band.right - band.left,+ height: plotHeight,+ borderColor: tint(45),+ borderTopColor: HIGHLIGHT_COLOR,+ background: `linear-gradient(to bottom, ${tint(20)}, ${tint(5)})`,+ }}+ />+ </>+ )+}diff --git a/products/product_analytics/mcp/apps/explainChart/StoryChartMarker.tsx b/products/product_analytics/mcp/apps/explainChart/StoryChartMarker.tsxnew file mode 100644index 000000000000..74b27cb9688d--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/StoryChartMarker.tsx@@ -0,0 +1,40 @@+/* eslint-disable react/forbid-dom-props -- pixel positions from the chart's scales */+import { type ReactElement } from 'react'++import { MARKER_SIZE, type StoryMarker } from './storyOverlayGeometry'++export interface StoryChartMarkerProps {+ marker: StoryMarker+ active: boolean+ onSelect: (index: number) => void+}++export function StoryChartMarker({ marker, active, onSelect }: StoryChartMarkerProps): ReactElement {+ const { page, index, center } = marker+ return (+ <button+ type="button"+ data-hog-charts-interactive-overlay+ data-attr="explain-chart-marker"+ aria-label={`Chapter ${index}: ${page.title}`}+ aria-current={active ? 'step' : undefined}+ className={`pointer-events-auto absolute flex cursor-pointer items-center justify-center rounded-full border text-xs font-medium tabular-nums transition-colors focus-visible:outline-2 focus-visible:outline-ring ${+ active+ ? 'border-foreground bg-foreground text-background'+ : 'border-muted-foreground bg-card text-foreground hover:border-foreground'+ }`}+ style={{+ left: center.x - MARKER_SIZE / 2,+ top: center.y - MARKER_SIZE / 2,+ width: MARKER_SIZE,+ height: MARKER_SIZE,+ }}+ onClick={(event) => {+ event.stopPropagation()+ onSelect(index)+ }}+ >+ {index}+ </button>+ )+}diff --git a/products/product_analytics/mcp/apps/explainChart/StoryChartOverlay.tsx b/products/product_analytics/mcp/apps/explainChart/StoryChartOverlay.tsxnew file mode 100644index 000000000000..ec75083fcc6d--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/StoryChartOverlay.tsx@@ -0,0 +1,56 @@+import { type ReactElement } from 'react'++import { useChartLayout } from '@posthog/quill-charts'++import { StoryChartHighlight } from './StoryChartHighlight'+import { StoryChartMarker } from './StoryChartMarker'+import { StoryMarkerTails } from './StoryMarkerTails'+import { chapterBand, storyMarkers } from './storyOverlayGeometry'+import type { StoryPage } from './storyPages'++export interface StoryChartOverlayProps {+ seriesKey: string+ pages: StoryPage[]+ /** The page whose stretch is lit: the one on show, or the one the pointer is over. */+ highlightedIndex: number+ activeIndex: number+ onSelect: (index: number) => void+}++export function StoryChartOverlay({+ seriesKey,+ pages,+ highlightedIndex,+ activeIndex,+ onSelect,+}: StoryChartOverlayProps): ReactElement | null {+ const layout = useChartLayout()+ const series = layout.series.find((candidate) => candidate.key === seriesKey)+ const highlighted = pages[highlightedIndex]+ if (!series || !highlighted) {+ return null+ }++ const band = chapterBand(layout, series, highlighted.range)+ const markers = storyMarkers(layout, series, pages)+ return (+ <div data-attr="explain-chart-overlay">+ {band && (+ <StoryChartHighlight+ band={band}+ dimensions={layout.dimensions}+ surface={layout.theme.backgroundColor ?? 'var(--card)'}+ />+ )}+ <StoryMarkerTails markers={markers} dimensions={layout.dimensions} activeIndex={activeIndex} />+ {markers.map((marker) => (+ <StoryChartMarker+ key={marker.index}+ marker={marker}+ active={marker.index === activeIndex}+ onSelect={onSelect}+ />+ ))}+ </div>+ )+}diff --git a/products/product_analytics/mcp/apps/explainChart/StoryEvidenceList.tsx b/products/product_analytics/mcp/apps/explainChart/StoryEvidenceList.tsxnew file mode 100644index 000000000000..25224a70c7ba--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/StoryEvidenceList.tsx@@ -0,0 +1,84 @@+import { ArrowUpRight } from 'lucide-react'+import { type ReactElement } from 'react'++import { Button, Text } from '@posthog/quill'++import type { StoryEvidence } from './explainChartTypes'+import { StoryMarkedText } from './StoryMarkedText'++export interface StoryEvidenceListProps {+ evidence: StoryEvidence[]+ openLink: (url: string) => void+ canShowChart: (item: StoryEvidence) => boolean+ shownIndex: number | null+ onToggleChart: (index: number) => void+}++export function StoryEvidenceList({+ evidence,+ openLink,+ canShowChart,+ shownIndex,+ onToggleChart,+}: StoryEvidenceListProps): ReactElement | null {+ if (!evidence.length) {+ return null+ }+ return (+ <div className="flex flex-col gap-1.5" data-attr="explain-chart-evidence">+ <Text size="xs" weight="medium" variant="muted">+ Evidence+ </Text>+ <ul className="m-0 flex list-none flex-col gap-1 p-0">+ {evidence.map((item, index) => (+ <li+ key={index}+ className={`-mx-2 flex items-start gap-2 rounded-md px-2 py-1 ${+ index === shownIndex ? 'bg-muted' : ''+ }`}+ >+ <span+ className={`mt-2 size-1.5 shrink-0 rounded-full ${+ index === shownIndex ? 'bg-(--primary-light)' : 'bg-muted-foreground'+ }`}+ aria-hidden+ />+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <Text size="sm">+ <StoryMarkedText text={item.text} />+ </Text>+ {(canShowChart(item) || item.url) && (+ <div className="flex flex-wrap items-center gap-3">+ {canShowChart(item) && (+ <Button+ variant="link"+ size="xs"+ className="h-auto p-0"+ aria-pressed={index === shownIndex}+ onClick={() => onToggleChart(index)}+ data-attr="explain-chart-evidence-chart"+ >+ {index === shownIndex ? 'Hide chart' : 'Show chart'}+ </Button>+ )}+ {item.url && (+ <Button+ variant="link"+ size="xs"+ className="h-auto p-0"+ onClick={() => item.url && openLink(item.url)}+ data-attr="explain-chart-evidence-link"+ >+ Open in PostHog+ <ArrowUpRight className="size-3" />+ </Button>+ )}+ </div>+ )}+ </div>+ </li>+ ))}+ </ul>+ </div>+ )+}diff --git a/products/product_analytics/mcp/apps/explainChart/StoryLikelyCause.tsx b/products/product_analytics/mcp/apps/explainChart/StoryLikelyCause.tsxnew file mode 100644index 000000000000..a10fd67665b6--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/StoryLikelyCause.tsx@@ -0,0 +1,64 @@+import { type ReactElement } from 'react'++import { Badge, Text, Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'++import type { StoryConfidence } from './explainChartTypes'+import { StoryMarkedText } from './StoryMarkedText'++const CONFIDENCE: Record<StoryConfidence, { label: string; variant: 'success' | 'info' | 'default'; why: string }> = {+ high: {+ label: 'High confidence',+ variant: 'success',+ why: 'Several independent checks point at this cause.',+ },+ medium: {+ label: 'Medium confidence',+ variant: 'info',+ why: 'One check points at this cause, with nothing to confirm it.',+ },+ low: {+ label: 'A guess',+ variant: 'default',+ why: 'Nothing in the evidence confirms this cause.',+ },+}++export interface StoryLikelyCauseProps {+ cause: string+ confidence: StoryConfidence | null+ confidenceReason: string | null+}++export function StoryLikelyCause({ cause, confidence, confidenceReason }: StoryLikelyCauseProps): ReactElement {+ const badge = confidence ? CONFIDENCE[confidence] : null+ return (+ <div className="flex flex-col gap-1.5" data-attr="explain-chart-cause">+ <div className="flex items-center gap-2">+ <Text size="xs" weight="medium" variant="muted">+ Likely cause+ </Text>+ {badge && (+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ className="cursor-default rounded-md border-0 bg-transparent p-0 focus-visible:outline-2 focus-visible:outline-ring"+ data-attr="explain-chart-confidence"+ />+ }+ >+ <Badge variant={badge.variant}>{badge.label}</Badge>+ </TooltipTrigger>+ <TooltipContent side="left">{confidenceReason ?? badge.why}</TooltipContent>+ </Tooltip>+ )}+ </div>+ <div className="rounded-md bg-muted p-2.5">+ <Text size="sm">+ <StoryMarkedText text={cause} />+ </Text>+ </div>+ </div>+ )+}diff --git a/products/product_analytics/mcp/apps/explainChart/StoryMarkedText.tsx b/products/product_analytics/mcp/apps/explainChart/StoryMarkedText.tsxnew file mode 100644index 000000000000..597c300ba3d9--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/StoryMarkedText.tsx@@ -0,0 +1,34 @@+import { type ReactElement } from 'react'++import { Highlight } from '@posthog/quill'++import { storyTextParts } from './storyMarks'++const STROKE_GAP_MS = 180++export function StoryMarkedText({ text }: { text: string }): ReactElement {+ let marked = 0+ return (+ <>+ {storyTextParts(text).map((part, index) =>+ part.kind === 'name' ? (+ <Highlight+ key={index}+ color="green"+ animate+ delay={marked++ * STROKE_GAP_MS}+ className="font-medium [--mark:transparent]"+ >+ {part.text}+ </Highlight>+ ) : part.kind ? (+ <span key={index} className="font-medium">+ {part.text}+ </span>+ ) : (+ <span key={index}>{part.text}</span>+ )+ )}+ </>+ )+}diff --git a/products/product_analytics/mcp/apps/explainChart/StoryMarkerTails.tsx b/products/product_analytics/mcp/apps/explainChart/StoryMarkerTails.tsxnew file mode 100644index 000000000000..511cd145e7c0--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/StoryMarkerTails.tsx@@ -0,0 +1,31 @@+/* eslint-disable react/forbid-dom-props -- pixel positions from the chart's scales */+import { type ReactElement } from 'react'++import type { ChartDimensions } from '@posthog/quill-charts'++import { type StoryMarker, tailPoints } from './storyOverlayGeometry'++export interface StoryMarkerTailsProps {+ markers: StoryMarker[]+ dimensions: ChartDimensions+ activeIndex: number+}++export function StoryMarkerTails({ markers, dimensions, activeIndex }: StoryMarkerTailsProps): ReactElement {+ const { plotLeft, plotTop, plotWidth, plotHeight } = dimensions+ return (+ <svg+ className="pointer-events-none absolute overflow-visible"+ style={{ left: plotLeft, top: plotTop, width: plotWidth, height: plotHeight }}+ aria-hidden+ >+ {markers.map((marker) => (+ <polygon+ key={marker.index}+ points={tailPoints(marker, dimensions)}+ fill={marker.index === activeIndex ? 'var(--foreground)' : 'var(--muted-foreground)'}+ />+ ))}+ </svg>+ )+}diff --git a/products/product_analytics/mcp/apps/explainChart/StorySteps.tsx b/products/product_analytics/mcp/apps/explainChart/StorySteps.tsxnew file mode 100644index 000000000000..12250e11e714--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/StorySteps.tsx@@ -0,0 +1,49 @@+import { House } from 'lucide-react'+import { type ReactElement } from 'react'++import { Tooltip, TooltipContent, TooltipTrigger } from '@posthog/quill'++import type { StoryPage } from './storyPages'++export interface StoryStepsProps {+ pages: StoryPage[]+ activeIndex: number+ onSelect: (index: number) => void+ onPreview: (index: number | null) => void+}++export function StorySteps({ pages, activeIndex, onSelect, onPreview }: StoryStepsProps): ReactElement {+ return (+ <ol className="m-0 flex list-none flex-wrap items-center gap-1 p-0" aria-label="Chapters">+ {pages.map((page, index) => (+ <li key={index}>+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ aria-label={index === 0 ? page.title : `Chapter ${index}: ${page.title}`}+ aria-current={index === activeIndex ? 'step' : undefined}+ className={`flex size-6 cursor-pointer items-center justify-center rounded-full border text-xs font-medium tabular-nums transition-colors focus-visible:outline-2 focus-visible:outline-ring ${+ index === activeIndex+ ? 'border-foreground bg-foreground text-background'+ : 'border-border bg-transparent text-muted-foreground hover:border-foreground hover:text-foreground'+ }`}+ onClick={() => onSelect(index)}+ onMouseEnter={() => onPreview(index)}+ onMouseLeave={() => onPreview(null)}+ onFocus={() => onPreview(index)}+ onBlur={() => onPreview(null)}+ data-attr="explain-chart-step"+ />+ }+ >+ {index === 0 ? <House className="size-3" /> : index}+ </TooltipTrigger>+ <TooltipContent side="bottom">{page.title}</TooltipContent>+ </Tooltip>+ </li>+ ))}+ </ol>+ )+}diff --git a/products/product_analytics/mcp/apps/explainChart/StorySummaryView.tsx b/products/product_analytics/mcp/apps/explainChart/StorySummaryView.tsxnew file mode 100644index 000000000000..47a91b521315--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/StorySummaryView.tsx@@ -0,0 +1,90 @@+import { type ReactElement } from 'react'++import { Text } from '@posthog/quill'++import { StoryMarkedText } from './StoryMarkedText'+import type { StoryPage } from './storyPages'++export interface StorySummaryViewProps {+ headline: string+ pages: StoryPage[]+ /** Which series the story follows, when the chart has more than one. */+ seriesNote: string | null+ warnings?: string[]+ onSelect: (index: number) => void+ onPreview: (index: number | null) => void+}++export function StorySummaryView({+ headline,+ pages,+ seriesNote,+ warnings = [],+ onSelect,+ onPreview,+}: StorySummaryViewProps): ReactElement {+ const [summary, ...chapters] = pages+ return (+ <div+ className="grid gap-4 transition-opacity duration-300 motion-reduce:transition-none starting:opacity-0 @xl/story:grid-cols-2 @3xl/story:grid-cols-1"+ data-attr="explain-chart-summary"+ >+ <div className="flex flex-col gap-2">+ <Text size="xs" variant="muted">+ Summary+ </Text>+ <Text size="base" weight="medium">+ <StoryMarkedText text={headline} />+ </Text>+ {summary?.facts && (+ <Text size="sm">+ <StoryMarkedText text={summary.facts} />+ </Text>+ )}+ {seriesNote && (+ <Text size="xs" variant="muted">+ {seriesNote}+ </Text>+ )}+ {warnings.map((warning, index) => (+ <Text key={index} size="xs" variant="muted" data-attr="explain-chart-warning">+ {warning}+ </Text>+ ))}+ </div>+ {chapters.length > 0 && (+ <div className="flex flex-col gap-1.5">+ <Text size="xs" weight="medium" variant="muted">+ What stands out+ </Text>+ <ol className="-mx-2 my-0 flex list-none flex-col p-0">+ {chapters.map((page, offset) => {+ const index = offset + 1+ return (+ <li key={index}>+ <button+ type="button"+ className="flex w-full cursor-pointer items-center gap-2.5 rounded-md border-0 bg-transparent px-2 py-1.5 text-start hover:bg-muted focus-visible:outline-2 focus-visible:outline-ring"+ onClick={() => onSelect(index)}+ onMouseEnter={() => onPreview(index)}+ onMouseLeave={() => onPreview(null)}+ onFocus={() => onPreview(index)}+ onBlur={() => onPreview(null)}+ data-attr="explain-chart-contents-item"+ >+ <span className="flex size-5 shrink-0 items-center justify-center rounded-full border border-border text-xs font-medium tabular-nums text-muted-foreground">+ {index}+ </span>+ <Text size="sm" className="min-w-0 [overflow-wrap:anywhere]" render={<span />}>+ {page.title}+ </Text>+ </button>+ </li>+ )+ })}+ </ol>+ </div>+ )}+ </div>+ )+}diff --git a/products/product_analytics/mcp/apps/explainChart/storyOverlayGeometry.ts b/products/product_analytics/mcp/apps/explainChart/storyOverlayGeometry.tsnew file mode 100644index 000000000000..78951ec3a2ed--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/storyOverlayGeometry.ts@@ -0,0 +1,133 @@+import type { ChartDimensions, ChartLayoutContextValue, ResolvedSeries } from '@posthog/quill-charts'++import { type MarkerObstacles, placeMarkers, type Point } from './storyMarkerPlacement'+import type { StoryPage } from './storyPages'++export const MARKER_SIZE = 20+const MARKER_GAP = 12+const TAIL_SPREAD = 0.45+const TIP_CLEARANCE = 3+const MIN_REACH = 22+const BAR_PADDING = 4++export interface Band {+ left: number+ right: number+}++export interface Dim extends Band {+ fadeLeft: boolean+ fadeRight: boolean+}++export interface StoryMarker {+ page: StoryPage+ index: number+ x: number+ y: number+ center: Point+}++type Layout = ChartLayoutContextValue++function xAt({ labels, scales }: Layout, series: ResolvedSeries, index: number): number | null {+ const label = labels[index]+ const x = label == null ? undefined : scales.x(label, series.key)+ return x == null || !isFinite(x) ? null : x+}++function yScaleOf({ scales }: Layout, series: ResolvedSeries): (value: number) => number {+ return (series.yAxisId && scales.yAxes?.[series.yAxisId]?.scale) || scales.y+}++function barWidthOf({ labels, scales }: Layout): number | undefined {+ return labels[0] == null ? undefined : scales.extent?.(labels[0])+}++export function chapterBand(layout: Layout, series: ResolvedSeries, range: [number, number] | null): Band | null {+ const { plotLeft, plotWidth } = layout.dimensions+ const first = xAt(layout, series, 0)+ const second = xAt(layout, series, 1)+ const step = first !== null && second !== null ? Math.abs(second - first) : plotWidth+ // A bar fills its slot. A lone point on a line needs its neighbours in view to read as a rise or a fall.+ const barWidth = barWidthOf(layout)+ const isOnePoint = !!range && range[0] === range[1]+ const reach =+ barWidth !== undefined+ ? barWidth / 2 + (isOnePoint ? BAR_PADDING : 0)+ : isOnePoint+ ? Math.max(step, MIN_REACH)+ : step / 2++ const from = range ? xAt(layout, series, range[0]) : null+ const to = range ? xAt(layout, series, range[1]) : null+ return from !== null && to !== null+ ? { left: Math.max(from - reach, plotLeft), right: Math.min(to + reach, plotLeft + plotWidth) }+ : null+}++export function dimsAround(band: Band, { plotLeft, plotWidth }: ChartDimensions): Dim[] {+ return [+ { left: plotLeft, right: band.left, fadeLeft: false, fadeRight: true },+ { left: band.right, right: plotLeft + plotWidth, fadeLeft: true, fadeRight: false },+ ]+}++function obstaclesOf(layout: Layout, series: ResolvedSeries): MarkerObstacles {+ const { labels, scales, dimensions, resolvePositionValue } = layout+ const drawn = layout.series.filter((candidate) => !candidate.visibility?.excluded)+ const pointsOf = (target: ResolvedSeries): Point[] =>+ labels.flatMap((label, index) => {+ const x = scales.x(label, target.key)+ const y = yScaleOf(layout, target)(resolvePositionValue(target, index))+ return x != null && isFinite(x) && isFinite(y) ? [{ x, y }] : []+ })+ const barWidth = barWidthOf(layout)+ if (barWidth === undefined) {+ return { lines: drawn.map(pointsOf), bars: [] }+ }+ const zero = yScaleOf(layout, series)(0)+ const baseline = isFinite(zero) ? zero : dimensions.plotTop + dimensions.plotHeight+ return {+ lines: [],+ bars: drawn.flatMap((target) =>+ pointsOf(target).map(({ x, y }) => ({+ left: x - barWidth / 2,+ right: x + barWidth / 2,+ top: Math.min(y, baseline),+ bottom: Math.max(y, baseline),+ }))+ ),+ }+}++export function storyMarkers(layout: Layout, series: ResolvedSeries, pages: StoryPage[]): StoryMarker[] {+ const { plotLeft, plotTop, plotWidth, plotHeight } = layout.dimensions+ const yScale = yScaleOf(layout, series)+ const anchors = pages.flatMap((page, index) => {+ const x = page.anchor === null ? null : xAt(layout, series, page.anchor)+ if (page.anchor === null || x === null || x < plotLeft || x > plotLeft + plotWidth) {+ return []+ }+ const y = yScale(layout.resolvePositionValue(series, page.anchor))+ return isFinite(y) ? [{ page, index, x, y }] : []+ })+ const centers = placeMarkers(anchors, obstaclesOf(layout, series), {+ radius: MARKER_SIZE / 2,+ distance: MARKER_SIZE / 2 + MARKER_GAP,+ bounds: { left: plotLeft, top: 0, right: plotLeft + plotWidth, bottom: plotTop + plotHeight },+ })+ return anchors.map((anchor, index) => ({ ...anchor, center: centers[index]! }))+}++export function tailPoints({ x, y, center }: StoryMarker, { plotLeft, plotTop }: ChartDimensions): string {+ // The base starts under the badge, so the tail grows out of its border in the same colour.+ const angle = Math.atan2(y - center.y, x - center.x)+ const inset = MARKER_SIZE / 2 - 1.5+ const points: [number, number][] = [+ [center.x + Math.cos(angle - TAIL_SPREAD) * inset, center.y + Math.sin(angle - TAIL_SPREAD) * inset],+ [center.x + Math.cos(angle + TAIL_SPREAD) * inset, center.y + Math.sin(angle + TAIL_SPREAD) * inset],+ [x - Math.cos(angle) * TIP_CLEARANCE, y - Math.sin(angle) * TIP_CLEARANCE],+ ]+ return points.map(([px, py]) => `${px - plotLeft},${py - plotTop}`).join(' ')+}diff --git a/services/mcp/src/ui-apps/lib/storybook/decorator.tsx b/services/mcp/src/ui-apps/lib/storybook/decorator.tsxindex 813ca7478a3f..a9279e9dd5a4 100644--- a/services/mcp/src/ui-apps/lib/storybook/decorator.tsx+++ b/services/mcp/src/ui-apps/lib/storybook/decorator.tsx@@ -1,6 +1,6 @@import './theme.css'-import type { StoryFn } from '@storybook/react'+import type { StoryContext, StoryFn } from '@storybook/react'import type { ReactElement } from 'react'/**@@ -55,8 +55,8 @@ const mcpAppsCssVariables: Record<string, string> = {'--font-weight-bold': '700',}-/** Decorator that injects MCP Apps host CSS variables onto the story root. */-export function McpThemeDecorator(Story: StoryFn): ReactElement {+/** Decorator that injects MCP Apps host CSS variables onto the story root. Set `parameters.mcpMaxWidth` for a story wider than a chat column. */+export function McpThemeDecorator(Story: StoryFn, context: StoryContext): ReactElement {return (<divstyle={@@ -66,7 +66,7 @@ export function McpThemeDecorator(Story: StoryFn): ReactElement {color: 'var(--color-text-primary)',backgroundColor: 'var(--color-background-primary)',padding: '1.5rem',- maxWidth: 720,+ maxWidth: context.parameters.mcpMaxWidth ?? 720,minHeight: 200,} as React.CSSProperties}diff --git a/services/mcp/src/ui-apps/lib/storybook/theme.css b/services/mcp/src/ui-apps/lib/storybook/theme.cssindex a24728353e55..1829092b0201 100644--- a/services/mcp/src/ui-apps/lib/storybook/theme.css+++ b/services/mcp/src/ui-apps/lib/storybook/theme.css@@ -123,3 +123,24 @@.font-mono {font-family: var(--font-mono, ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace);}++/* PostHog's Tailwind marks `bg-muted` important over the `[data-quill]` bridge, and an important rule in an earlier layer beats one in `utilities`. */+@layer base {+ [data-mcp-storybook] .bg-muted {+ background-color: var(--color-background-tertiary, #f2f4f7) !important;+ }+}++/* Inverted surfaces, such as a selected marker. */+[data-mcp-storybook] .bg-foreground {+ background-color: var(--foreground);+}++[data-mcp-storybook] .text-background {+ color: var(--background);+}++[data-mcp-storybook] .border-foreground,+[data-mcp-storybook] .hover\:border-foreground:hover {+ border-color: var(--foreground);+}