: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
refactor(insights): render MCP lifecycle app with quill charts (#62409)
Sam Pennington4d02d2628bab
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 2d953a91f497..581937c83f7e 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3852,6 +3852,10 @@ snapshots:hash: v1.k794b7964.923aafaf8e1bce9f1caa2410cd58f7378ff97f8e9fb569e0ce18b45dfb885ff8.osZQjoZOyTIkZuiFFYz_vt8LWPp7oKhCd1an1UQjLwMmcp-apps-funnels--three-step--light:hash: v1.k794b7964.18bd10f06238debddaf314abc41971a2a811e0cc74174b10b3f224ed7df15066.8JtCrE123e2LAu3dIKIT_F0E_u29Q2wT-UKli7kracs+ mcp-apps-lifecycle--grouped--light:+ hash: v1.k794b7964.b8247c9b7542fdbcf8fe7f6c7a6adfca0e1548cbd5ae90c1a8373e810eb50065.2lEwgzg2R0L_DFCuop8tC15_oQUPrv3JVnXJMviUHbw+ mcp-apps-lifecycle--stacked--light:+ hash: v1.k794b7964.ce5ea9f9ffda7e65851691f582f798735e08bc196c038595243ad3a16cd116e6.LXzplsYjLiccg71arqdyvRVsdq9fzUG6lVLFWfG86g8mcp-apps-surveys--active-popover--light:hash: v1.k794b7964.c47633461e9a437f0761e09f795eb793b02ed0bac4489ce757a5837dbaa3f847.wclUgXFjBkoHXJLNP2R3ncawfRArgVyVEUWbIiQve0omcp-apps-surveys--completed--light:diff --git a/products/product_analytics/mcp/apps/Lifecycle.stories.tsx b/products/product_analytics/mcp/apps/Lifecycle.stories.tsxnew file mode 100644index 000000000000..bec2c53d86d6--- /dev/null+++ b/products/product_analytics/mcp/apps/Lifecycle.stories.tsx@@ -0,0 +1,68 @@+import type { Meta, StoryObj } from '@storybook/react'+import type { ReactElement } from 'react'++import { CHART_THEME, lifecycleColor } from '@posthog/mcp-ui'+import { McpThemeDecorator } from '@posthog/mcp-ui/storybook/decorator'+import { Legend, TimeSeriesBarChart, legendItemsFromSeries } from '@posthog/quill-charts'++import {+ buildTrendsLifecycleConfig,+ buildTrendsLifecycleSeries,+ type TrendsLifecycleResultLike,+} from '../../frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms'++const LABELS = ['Jun 1', 'Jun 2', 'Jun 3', 'Jun 4', 'Jun 5', 'Jun 6', 'Jun 7']++// `dormant` values come back negated from the backend so a diverging stack lays them below zero.+const RESULTS: TrendsLifecycleResultLike[] = [+ { id: 'new', status: 'new', label: 'Pageview - new', data: [40, 35, 50, 45, 60, 55, 70] },+ { id: 'returning', status: 'returning', label: 'Pageview - returning', data: [20, 30, 35, 40, 45, 50, 55] },+ { id: 'resurrecting', status: 'resurrecting', label: 'Pageview - resurrecting', data: [10, 8, 12, 9, 14, 11, 16] },+ { id: 'dormant', status: 'dormant', label: 'Pageview - dormant', data: [-15, -20, -18, -25, -22, -30, -28] },+]++const meta: Meta = {+ title: 'MCP Apps/Lifecycle',+ decorators: [McpThemeDecorator],+ parameters: {+ testOptions: {+ skipDarkMode: true,+ },+ },+}+export default meta++type Story = StoryObj<{}>++function LifecycleChartDemo({+ results,+ isStacked,+}: {+ results: TrendsLifecycleResultLike[]+ isStacked: boolean+}): ReactElement {+ const series = buildTrendsLifecycleSeries(results, { getColor: lifecycleColor })+ const config = buildTrendsLifecycleConfig({ isStacked })+ const legendItems = legendItemsFromSeries(series, CHART_THEME)+ return (+ <div className="flex flex-col gap-2">+ <Legend items={legendItems} orientation="horizontal" align="center" />+ {/* Fixed pixel size, not width:100% — the chart sizes its canvas off a ResizeObserver, which+ measures 0 for a percentage width at mount in the headless snapshot runner and draws nothing. */}+ {/* eslint-disable-next-line react/forbid-dom-props */}+ <div style={{ display: 'flex', flexDirection: 'column', width: 640, height: 320 }}>+ <TimeSeriesBarChart series={series} labels={LABELS} theme={CHART_THEME} config={config} />+ </div>+ </div>+ )+}++export const Stacked: Story = {+ render: () => <LifecycleChartDemo results={RESULTS} isStacked />,+ name: 'Stacked',+}++export const Grouped: Story = {+ render: () => <LifecycleChartDemo results={RESULTS} isStacked={false} />,+ name: 'Grouped',+}diff --git a/services/mcp/src/ui-apps/components/LifecycleVisualizer.tsx b/services/mcp/src/ui-apps/components/LifecycleVisualizer.tsxindex dd83a12af6cd..b8d25fc516ea 100644--- a/services/mcp/src/ui-apps/components/LifecycleVisualizer.tsx+++ b/services/mcp/src/ui-apps/components/LifecycleVisualizer.tsx@@ -1,281 +1,67 @@-import { type ReactElement } from 'react'+import { type ReactElement, useMemo } from 'react'import { emptyStateIllustration } from '@posthog/mcp-ui'import { Empty, EmptyDescription, EmptyHeader, EmptyMedia } from '@posthog/quill'+import { Legend, TimeSeriesBarChart, legendItemsFromSeries } from '@posthog/quill-charts'-import type { LifecycleResultItem, LifecycleStatus, LifecycleVisualizerProps } from './types'-import { formatDate, formatNumber } from './utils'+import { buildLifecycleChartModel } from 'products/product_analytics/frontend/insights/trends/TrendsLifecycleChart/trendsLifecycleChartTransforms'-const CHART_HEIGHT = 320-const CHART_WIDTH = 600-const PADDING = { top: 24, right: 24, bottom: 48, left: 56 }+import { CHART_THEME, lifecycleColor } from './charts/theme'+import type { LifecycleVisualizerProps } from './types'+import { formatDate } from './utils'-// Conventional lifecycle bucket colors — mirrors --color-lifecycle-* in frontend/src/styles/base.scss.-const LIFECYCLE_COLORS: Record<LifecycleStatus, string> = {- new: '#1d4aff',- returning: '#388600',- resurrecting: '#a56eff',- dormant: '#db3707',-}--// Stack order — positive buckets stack upward, dormant goes below zero.-const POSITIVE_STATUSES: LifecycleStatus[] = ['new', 'returning', 'resurrecting']-const NEGATIVE_STATUSES: LifecycleStatus[] = ['dormant']-const ALL_STATUSES: LifecycleStatus[] = [...POSITIVE_STATUSES, ...NEGATIVE_STATUSES]--interface SeriesByStatus {- status: LifecycleStatus- label: string- data: number[]-}--function groupByStatus(results: LifecycleResultItem[]): {- byStatus: Map<LifecycleStatus, SeriesByStatus>- labels: string[]-} {- const labels = results[0]?.days || results[0]?.labels || []- const byStatus = new Map<LifecycleStatus, SeriesByStatus>()-- for (const item of results) {- if (!item.status || !ALL_STATUSES.includes(item.status)) {- continue- }- // Multiple series can share the same status (e.g. when grouping by event).- // Sum element-wise.- const existing = byStatus.get(item.status)- const data = item.data ?? []- if (existing) {- for (let i = 0; i < data.length; i++) {- existing.data[i] = (existing.data[i] ?? 0) + (data[i] ?? 0)- }- } else {- byStatus.set(item.status, {- status: item.status,- label: item.status,- data: [...data],- })- }- }-- return { byStatus, labels }-}--function computeBounds(- byStatus: Map<LifecycleStatus, SeriesByStatus>,- dataLength: number,- isVisible: (status: LifecycleStatus) => boolean-): { max: number; min: number } {- let max = 0- let min = 0- for (let i = 0; i < dataLength; i++) {- let positiveStack = 0- let negativeStack = 0- for (const status of POSITIVE_STATUSES) {- if (!isVisible(status)) {- continue- }- const value = byStatus.get(status)?.data[i] ?? 0- if (value > 0) {- positiveStack += value- }- }- for (const status of NEGATIVE_STATUSES) {- if (!isVisible(status)) {- continue- }- const value = byStatus.get(status)?.data[i] ?? 0- if (value < 0) {- negativeStack += value- }- }- if (positiveStack > max) {- max = positiveStack- }- if (negativeStack < min) {- min = negativeStack- }- }- return { max, min }-}+const LIFECYCLE_TOOLTIP_CONFIG = { pinnable: true, placement: 'top' as const }export function LifecycleVisualizer({ query, results }: LifecycleVisualizerProps): ReactElement {- const renderEmpty = (): ReactElement => (- <Empty>- <EmptyHeader>- <EmptyMedia>{emptyStateIllustration('chart')}</EmptyMedia>- <EmptyDescription>No data available</EmptyDescription>- </EmptyHeader>- </Empty>- )-- if (!results || results.length === 0) {- return renderEmpty()- }-- const { byStatus, labels } = groupByStatus(results)- const dataLength = labels.length- if (dataLength === 0 || byStatus.size === 0) {- return renderEmpty()- }-- // `toggledLifecycles` is a client-side filter in the main app: the backend always returns- // all four buckets and the UI hides the toggled-off ones. Mirror that here.- const toggledLifecycles = query?.lifecycleFilter?.toggledLifecycles- const isVisible = (status: LifecycleStatus): boolean =>- byStatus.has(status) && (!toggledLifecycles || toggledLifecycles.includes(status))- const visibleBuckets = ALL_STATUSES.filter(isVisible)const showLegend = query?.lifecycleFilter?.showLegend ?? true- const { max, min } = computeBounds(byStatus, dataLength, isVisible)- const range = Math.max(max - min, 1)-- const innerWidth = CHART_WIDTH - PADDING.left - PADDING.right- const innerHeight = CHART_HEIGHT - PADDING.top - PADDING.bottom- const zeroY = PADDING.top + (max / range) * innerHeight- const valueToY = (value: number): number => zeroY - (value / range) * innerHeight- const barGroupWidth = innerWidth / dataLength- const barWidth = Math.min(barGroupWidth * 0.7, 36)+ const { series, labels, config } = useMemo(+ () =>+ buildLifecycleChartModel(+ (results ?? []).map((item, i) => ({+ id: i,+ label: item.label,+ data: item.data ?? [],+ status: item.status,+ days: item.days,+ })),+ {+ getColor: lifecycleColor,+ labels: (results?.[0]?.days ?? results?.[0]?.labels ?? []).map(formatDate),+ isStacked: query?.lifecycleFilter?.stacked ?? true,+ toggledLifecycles: query?.lifecycleFilter?.toggledLifecycles,+ tooltip: LIFECYCLE_TOOLTIP_CONFIG,+ }+ ),+ [results, query?.lifecycleFilter?.stacked, query?.lifecycleFilter?.toggledLifecycles]+ )- // Tick values: 0 plus a few evenly-spaced positions above and below.- const positiveTicks = [0.25, 0.5, 0.75, 1].map((ratio) => max * ratio).filter((v) => v > 0)- const negativeTicks = [0.25, 0.5, 0.75, 1].map((ratio) => min * ratio).filter((v) => v < 0)- const ticks = [...negativeTicks.reverse(), 0, ...positiveTicks]+ const legendItems = useMemo(() => legendItemsFromSeries(series, CHART_THEME), [series])++ if (!results || results.length === 0 || series.length === 0 || labels.length === 0) {+ return (+ <Empty>+ <EmptyHeader>+ <EmptyMedia>{emptyStateIllustration('chart')}</EmptyMedia>+ <EmptyDescription>No data available</EmptyDescription>+ </EmptyHeader>+ </Empty>+ )+ }+ // The chart box gets its width from a plain block (`w-full`) and an explicit height — not from+ // ChartLegend's `flex-1`/`self-stretch` slot, which can resolve to 0 at mount in the MCP iframe,+ // leaving the canvas measured at 0 and unpainted. Funnels/trends render the chart this way too.return (- <div>- <svg viewBox={`0 0 ${CHART_WIDTH} ${CHART_HEIGHT}`} style={{ width: '100%' }}>- {/* Y-axis grid + labels */}- {ticks.map((value) => {- const y = valueToY(value)- return (- <g key={value}>- <line- x1={PADDING.left}- y1={y}- x2={CHART_WIDTH - PADDING.right}- y2={y}- stroke="var(--color-border-primary, #e5e7eb)"- strokeDasharray={value === 0 ? '0' : '4,4'}- />- <text- x={PADDING.left - 8}- y={y + 4}- textAnchor="end"- fontSize="10"- fill="var(--color-text-secondary, #6b7280)"- >- {formatNumber(value)}- </text>- </g>- )- })}-- {/* X-axis labels — thin out when crowded. */}- {labels.map((label, i) => {- if (labels.length > 8 && i % Math.ceil(labels.length / 8) !== 0) {- return null- }- const x = PADDING.left + (i + 0.5) * barGroupWidth- return (- <text- key={i}- x={x}- y={CHART_HEIGHT - 16}- textAnchor="middle"- fontSize="10"- fill="var(--color-text-secondary, #6b7280)"- >- {formatDate(label)}- </text>- )- })}-- {/* Stacked bars — positive buckets stack upward, dormant extends downward. */}- {Array.from({ length: dataLength }).map((_, i) => {- const groupX = PADDING.left + i * barGroupWidth- const x = groupX + (barGroupWidth - barWidth) / 2-- let positiveCursor = 0- let negativeCursor = 0- return (- <g key={i}>- {POSITIVE_STATUSES.map((status) => {- if (!isVisible(status)) {- return null- }- const series = byStatus.get(status)- const value = series?.data[i] ?? 0- if (value <= 0) {- return null- }- const yTop = valueToY(positiveCursor + value)- const yBottom = valueToY(positiveCursor)- positiveCursor += value- return (- <rect- key={`${status}-${i}`}- x={x}- y={yTop}- width={barWidth}- height={Math.max(yBottom - yTop, 0)}- fill={LIFECYCLE_COLORS[status]}- />- )- })}- {NEGATIVE_STATUSES.map((status) => {- if (!isVisible(status)) {- return null- }- const series = byStatus.get(status)- const value = series?.data[i] ?? 0- if (value >= 0) {- return null- }- const yTop = valueToY(negativeCursor)- const yBottom = valueToY(negativeCursor + value)- negativeCursor += value- return (- <rect- key={`${status}-${i}`}- x={x}- y={yTop}- width={barWidth}- height={Math.max(yBottom - yTop, 0)}- fill={LIFECYCLE_COLORS[status]}- />- )- })}- </g>- )- })}- </svg>-- {showLegend && visibleBuckets.length > 0 && (- <div- style={{- display: 'flex',- flexWrap: 'wrap',- gap: '1rem',- justifyContent: 'center',- marginTop: '0.5rem',- fontSize: '0.75rem',- }}- >- {visibleBuckets.map((status) => (- <div key={status} style={{ display: 'flex', alignItems: 'center', gap: '0.25rem' }}>- <div- style={{- width: '12px',- height: '12px',- borderRadius: '2px',- backgroundColor: LIFECYCLE_COLORS[status],- }}- />- <span style={{ color: 'var(--color-text-secondary, #6b7280)' }}>{status}</span>- </div>- ))}+ <div className="w-full">+ {showLegend && legendItems.length > 0 && (+ <div className="mb-2">+ <Legend items={legendItems} orientation="horizontal" align="center" /></div>)}+ <div className="flex flex-col w-full h-[400px]">+ <TimeSeriesBarChart series={series} labels={labels} theme={CHART_THEME} config={config} />+ </div></div>)}diff --git a/services/mcp/src/ui-apps/components/charts/theme.ts b/services/mcp/src/ui-apps/components/charts/theme.tsindex cbb11fc8b635..a02f89286f15 100644--- a/services/mcp/src/ui-apps/components/charts/theme.ts+++ b/services/mcp/src/ui-apps/components/charts/theme.ts@@ -1,5 +1,7 @@import { type ChartTheme } from '@posthog/quill-charts'+import type { LifecycleStatus } from '../types'+// PostHog brand palette. Canvas can't read CSS custom properties, so we hand the// chart concrete hexes. The chart picks one per series by index; legends use the// same array to stay in sync.@@ -19,6 +21,17 @@ export const colorAt = (index: number): string => CHART_COLORS[index % CHART_COL// conversion, so distinct per-step colors would only add noise.export const FUNNEL_COLOR = '#1d4aff'+// Conventional lifecycle bucket colors — mirrors --color-lifecycle-* in frontend/src/styles/base.scss.+export const LIFECYCLE_COLORS: Record<LifecycleStatus, string> = {+ new: '#1d4aff',+ returning: '#388600',+ resurrecting: '#a56eff',+ dormant: '#db3707',+}++export const lifecycleColor = (status: string | undefined): string =>+ LIFECYCLE_COLORS[(status ?? 'new') as LifecycleStatus] ?? LIFECYCLE_COLORS.new+// Single mid-gray for axis labels — readable on both light and dark hosts. Claude// Desktop's iframe doesn't set `prefers-color-scheme`, so we can't detect the host// theme and adapt at runtime.diff --git a/services/mcp/src/ui-apps/lib/index.ts b/services/mcp/src/ui-apps/lib/index.tsindex 9fc2dd073873..2234aa3f97be 100644--- a/services/mcp/src/ui-apps/lib/index.ts+++ b/services/mcp/src/ui-apps/lib/index.ts@@ -3,3 +3,4 @@ export { DescriptionList, type DescriptionListProps, type DescriptionListItem }export { ListDetailView, type ListDetailViewProps } from './ListDetailView'export { emptyStateIllustration, type EmptyStateIllustrationType } from './illustrations/emptyStateIllustrations'export { cn, formatDate } from './utils'+export { CHART_THEME, LIFECYCLE_COLORS, lifecycleColor } from '../components/charts/theme'diff --git a/services/mcp/src/ui-apps/styles/tailwind.css b/services/mcp/src/ui-apps/styles/tailwind.cssindex 32adfadde9b5..29fcd9a469a5 100644--- a/services/mcp/src/ui-apps/styles/tailwind.css+++ b/services/mcp/src/ui-apps/styles/tailwind.css@@ -66,3 +66,4 @@@source "../../../../../products/*/mcp/**/*.tsx";@source "../../../../../packages/quill/packages/primitives/src/**/*.{ts,tsx}";@source "../../../../../packages/quill/packages/components/src/**/*.{ts,tsx}";+@source "../../../../../packages/quill/packages/charts/src/**/*.{ts,tsx}";