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.

refactor(insights): render MCP retention app with quill charts (#62407)

Sam Penningtondd6cd2645983
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 7a6654dde325..2f640a73c7f0 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -3881,9 +3881,9 @@ snapshots:
mcp-apps-trends--area-chart--light:
hash: v1.k794b7964.6cf42e74cc7686abba8123717fd06198df9cec15b137857ebeff6a41d882f588.bIEusW4n6ate8V8Ujn33aEEEuqxdLQFibt6BcBUnK1g
mcp-apps-trends--bar-value-few-series--light:
- hash: v1.k794b7964.3a5ba60751ffd22f1e998cda41e63c30a1948b925de7c7f8861074e3ec572bea.llE1NKWEs58Fm4n5d10r7Tlm72vCzt-ZHubLiOkaIYU
+ hash: v1.k794b7964.0306912db87cc31480193197f8836a77bdb605eddff02f4f3a49513ea0607ffa.7eggN7eGBfu9J82WduiVyY_KMUPBFlus190tJfCKdnc
mcp-apps-trends--bar-value-many-breakdowns--light:
- hash: v1.k794b7964.1249026814f2d92f133f9a71e712fc17c7236211a3d1671092a3f8901f8adb22.QE5QFCKypNIrwCkKMrs_UyxYjU_vv-x4fVc5S2dVKg8
+ hash: v1.k794b7964.55d92ceb29c5fedf37ed82999dcb4d0a1122cead487ed73a8e8891cc4ce89ea2.zCQNhUwqzZqBkFs-rbqKBENtndciu2imsafQHGtsrsA
mcp-apps-trends--multi-series--light:
hash: v1.k794b7964.2622c6a6026ee9a0afdee272a93207428b6b162319c26f749f720301e95295b3.ud_GEZpQP8zR9kgPkMECKr09f544GEqMjVQzKPe-Zec
mcp-apps-trends--single-series--light:
diff --git a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.ts b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.ts
index fa7ca1da7e97..1614cad06fe7 100644
--- a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.ts
+++ b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.ts
@@ -301,6 +301,23 @@ describe('retentionChartTransforms', () => {
expect(model.series[0].data).toEqual([100, 50])
})
+ it('keeps every cohort when maxCohorts is omitted', () => {
+ const cohorts = [
+ cohort('2024-01-01', [100, 50]),
+ cohort('2024-01-02', [80, 40]),
+ cohort('2024-01-03', [60, 30]),
+ ]
+ const model = buildRetentionChartModel(cohorts, {
+ aggregationType: 'count',
+ reference: 'total',
+ period: 'Day',
+ getColor: colorAt,
+ })
+
+ expect(model.totalCohorts).toBe(3)
+ expect(model.series).toHaveLength(3)
+ })
+
it.each([
{ aggregationType: 'count', expectedLabel: 'Retention %', expectedFormat: 'percentage' },
{ aggregationType: 'sum', expectedLabel: 'Sum', expectedFormat: 'numeric' },
diff --git a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts
index 79972cfcab85..fef047f80bb4 100644
--- a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts
+++ b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts
@@ -242,8 +242,9 @@ export interface BuildRetentionChartModelOpts {
showTrendLines?: boolean
getColor: (index: number) => string
tooltip?: TooltipConfig
- /** Cohorts beyond this are dropped so each line keeps a distinct palette color. */
- maxCohorts: number
+ /** Cohorts beyond this are dropped so each line keeps a distinct palette color.
+ * Omit for no cap (web behavior) — colors wrap once they exceed the palette. */
+ maxCohorts?: number
}
export interface RetentionChartModel {
@@ -262,7 +263,7 @@ export function buildRetentionChartModel<C extends RetentionCohortLike>(
opts: BuildRetentionChartModelOpts
): RetentionChartModel {
const sorted = sortRetentionCohorts(cohorts)
- const limited = sorted.slice(0, opts.maxCohorts)
+ const limited = opts.maxCohorts != null ? sorted.slice(0, opts.maxCohorts) : sorted
const numIntervals = limited.reduce((max, c) => Math.max(max, c.values.length), 0)
const labels = Array.from({ length: numIntervals }, (_, i) => `${opts.period} ${i}`)
diff --git a/products/product_analytics/mcp/apps/Funnels.stories.tsx b/products/product_analytics/mcp/apps/Funnels.stories.tsx
index 175b3db49474..c163c2aea95f 100644
--- a/products/product_analytics/mcp/apps/Funnels.stories.tsx
+++ b/products/product_analytics/mcp/apps/Funnels.stories.tsx
@@ -1,8 +1,9 @@
import type { Meta, StoryObj } from '@storybook/react'
import type { ReactElement } from 'react'
+import { CHART_THEME, FUNNEL_COLOR } from '@posthog/mcp-ui'
import { McpThemeDecorator } from '@posthog/mcp-ui/storybook/decorator'
-import { BarChart, type ChartTheme, type TooltipContext, TooltipSurface } from '@posthog/quill-charts'
+import { BarChart, type TooltipContext, TooltipSurface } from '@posthog/quill-charts'
import {
buildFunnelStepsBarConfig,
@@ -10,18 +11,6 @@ import {
type FunnelStepsBarRow,
} from '../../frontend/insights/funnels/shared/funnelStepsBarShared'
-// PostHog brand palette — mirrors services/mcp/src/ui-apps/components/charts/theme.ts
-const CHART_THEME: ChartTheme = {
- colors: ['#1d4aff', '#621da6', '#00d683', '#f54e00', '#f7a501', '#dc2626'],
- backgroundColor: '#ffffff',
- axisColor: '#9ca3af',
- gridColor: 'rgba(128,128,128,0.2)',
- crosshairColor: 'rgba(128,128,128,0.5)',
- tooltipBackground: '#ffffff',
- tooltipColor: '#111827',
-}
-const FUNNEL_COLOR = '#1d4aff'
-
const NOOP = (): void => {}
const CHART_CONFIG = buildFunnelStepsBarConfig({ maxCategoryLabelWidth: 120, tooltipPlacement: 'cursor' })
diff --git a/products/product_analytics/mcp/apps/Trends.stories.tsx b/products/product_analytics/mcp/apps/Trends.stories.tsx
index 538d21909347..21463b4e5964 100644
--- a/products/product_analytics/mcp/apps/Trends.stories.tsx
+++ b/products/product_analytics/mcp/apps/Trends.stories.tsx
@@ -1,9 +1,9 @@
import type { Meta, StoryObj } from '@storybook/react'
import type { ReactElement } from 'react'
+import { CHART_THEME, colorAt } from '@posthog/mcp-ui'
import { McpThemeDecorator } from '@posthog/mcp-ui/storybook/decorator'
import { BarChart, TimeSeriesBarChart, TimeSeriesLineChart } from '@posthog/quill-charts'
-import type { ChartTheme } from '@posthog/quill-charts'
import { buildTrendsBarChartModel } from '../../frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms'
import {
@@ -17,20 +17,6 @@ import {
type TrendsResultLike,
} from '../../frontend/insights/trends/TrendsLineChart/trendsChartTransforms'
-// PostHog brand palette — mirrors services/mcp/src/ui-apps/components/charts/theme.ts
-const CHART_COLORS = ['#1d4aff', '#621da6', '#00d683', '#f54e00', '#f7a501', '#dc2626']
-
-const CHART_THEME: ChartTheme = {
- colors: CHART_COLORS,
- backgroundColor: '#ffffff',
- axisColor: '#9ca3af',
- gridColor: 'rgba(128,128,128,0.2)',
- crosshairColor: 'rgba(128,128,128,0.5)',
- tooltipBackground: '#ffffff',
- tooltipColor: '#111827',
-}
-
-const colorAt = (i: number): string => CHART_COLORS[i % CHART_COLORS.length]!
const getColor = (_r: TrendsResultLike, i: number): string => colorAt(i)
const DAYS = ['2025-05-26', '2025-05-27', '2025-05-28', '2025-05-29', '2025-05-30', '2025-05-31', '2025-06-01']
diff --git a/services/mcp/src/ui-apps/components/RetentionVisualizer.tsx b/services/mcp/src/ui-apps/components/RetentionVisualizer.tsx
index 83862354fe33..70c834251a50 100644
--- a/services/mcp/src/ui-apps/components/RetentionVisualizer.tsx
+++ b/services/mcp/src/ui-apps/components/RetentionVisualizer.tsx
@@ -2,16 +2,13 @@ import { type ReactElement, useMemo, useState } from 'react'
import { emptyStateIllustration } from '@posthog/mcp-ui'
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia } from '@posthog/quill'
+import { TimeSeriesBarChart, TimeSeriesLineChart, type TooltipConfig } from '@posthog/quill-charts'
-import { BarChart, LineChart, Select, type Series } from './charts'
-import type {
- RetentionAggregationType,
- RetentionPeriod,
- RetentionReference,
- RetentionResult,
- RetentionResultItem,
- RetentionVisualizerProps,
-} from './types'
+import { buildRetentionChartModel } from 'products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms'
+
+import { Select } from './charts'
+import { CHART_THEME, colorAt } from './charts/theme'
+import type { RetentionVisualizerProps } from './types'
type ChartMode = 'line' | 'bar'
@@ -20,142 +17,30 @@ const CHART_MODE_OPTIONS = [
{ value: 'bar' as const, label: 'Bar' },
]
-function formatStartDate(cohort: RetentionResultItem, period: RetentionPeriod): string | null {
- if (!cohort.date) {
- return null
- }
- const d = new Date(cohort.date)
- if (Number.isNaN(d.getTime())) {
- return null
- }
- if (period === 'Hour') {
- return d.toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric' })
- }
- if (period === 'Month') {
- return d.toLocaleDateString('en-US', { month: 'short', year: 'numeric' })
- }
- return d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
-}
-
-function formatCohortLegendLabel(cohort: RetentionResultItem, cohortNumber: number, period: RetentionPeriod): string {
- const startDate = formatStartDate(cohort, period)
- const breakdown =
- cohort.breakdown_value !== undefined && cohort.breakdown_value !== null && cohort.breakdown_value !== ''
- ? String(cohort.breakdown_value)
- : null
- const base = `Cohort ${cohortNumber}`
- if (breakdown) {
- return startDate ? `${base} (${breakdown}, ${startDate})` : `${base} (${breakdown})`
- }
- return startDate ? `${base} (${startDate})` : base
-}
-
-// Mirrors the math in `retentionLogic.ts`: each cohort's interval values become a percentage of the
-// reference cohort size (`total` = day-0, `previous` = preceding interval). For non-count aggregations
-// we surface `aggregation_value` directly without normalization.
-function computeSeriesValue(
- values: RetentionResultItem['values'],
- intervalIndex: number,
- aggregationType: RetentionAggregationType,
- reference: RetentionReference
-): number {
- const current = values[intervalIndex]
- if (!current) {
- return 0
- }
- if (aggregationType !== 'count') {
- return current.aggregation_value ?? 0
- }
- if (reference === 'previous') {
- if (intervalIndex === 0) {
- return 100
- }
- const prev = values[intervalIndex - 1]
- if (!prev || prev.count === 0) {
- return 0
- }
- return (current.count / prev.count) * 100
- }
- const baseline = values[0]?.count ?? 0
- if (baseline === 0) {
- return 0
- }
- return (current.count / baseline) * 100
-}
-
-function buildXAxisLabels(numIntervals: number, period: RetentionPeriod): string[] {
- return Array.from({ length: numIntervals }, (_, i) => `${period} ${i}`)
-}
-
-// Sort chronologically so "Cohort 1" is the earliest start date. Cohorts without a parseable date
-// preserve their original order at the end of the list.
-function sortCohorts(results: RetentionResult): RetentionResult {
- return [...results].sort((a, b) => {
- const ta = a.date ? new Date(a.date).getTime() : Number.POSITIVE_INFINITY
- const tb = b.date ? new Date(b.date).getTime() : Number.POSITIVE_INFINITY
- // `ta`/`tb` can each be a finite ms timestamp, NaN (invalid `date`), or POSITIVE_INFINITY
- // (missing `date`). `ta - tb` returns NaN whenever both are non-finite (Inf-Inf or NaN-*),
- // which violates the sort comparator contract — handle those pairings explicitly.
- const aMissing = Number.isNaN(ta) || !Number.isFinite(ta)
- const bMissing = Number.isNaN(tb) || !Number.isFinite(tb)
- if (aMissing && bMissing) {
- return 0
- }
- if (aMissing) {
- return 1
- }
- if (bMissing) {
- return -1
- }
- return ta - tb
- })
-}
-
-// Cap at the size of the shared chart palette so each cohort gets its own distinct color rather
-// than cycling — beyond this the lines blur into noise anyway.
-const MAX_COHORTS = 8
+const TOOLTIP_CONFIG: TooltipConfig = { pinnable: true, placement: 'top' }
export function RetentionVisualizer({ query, results }: RetentionVisualizerProps): ReactElement {
- const aggregationType: RetentionAggregationType = query?.retentionFilter?.aggregationType ?? 'count'
- const reference: RetentionReference = query?.retentionFilter?.retentionReference ?? 'total'
- const period: RetentionPeriod = query?.retentionFilter?.period ?? 'Day'
- const isPercentage = aggregationType === 'count'
-
const [chartMode, setChartMode] = useState<ChartMode>('line')
- const { series, labels, maxValue, totalCohorts } = useMemo(() => {
- if (!results || results.length === 0) {
- return { series: [] as Series[], labels: [] as string[], maxValue: 0, totalCohorts: 0 }
- }
- const sorted = sortCohorts(results)
- // Cap to MAX_COHORTS so each line gets a distinct palette color rather than wrapping back
- // to the first color. Older cohorts have the most observed intervals so we keep those.
- const limited = sorted.slice(0, MAX_COHORTS)
- const numIntervals = limited.reduce((m, c) => Math.max(m, c.values.length), 0)
- const xLabels = buildXAxisLabels(numIntervals, period)
- let computedMax = 0
-
- const built: Series[] = limited.map((cohort, idx) => {
- const points = Array.from({ length: numIntervals }, (_, i) => {
- const y = computeSeriesValue(cohort.values, i, aggregationType, reference)
- if (y > computedMax) {
- computedMax = y
- }
- return { x: i, y, label: xLabels[i] ?? `${i}` }
- })
- return {
- label: formatCohortLegendLabel(cohort, idx + 1, period),
- points,
- }
- })
-
- return {
- series: built,
- labels: xLabels,
- maxValue: computedMax || 1,
- totalCohorts: sorted.length,
- }
- }, [results, aggregationType, reference, period])
+ // No cohort cap — mirrors the web, which renders every cohort and lets colors wrap past the palette.
+ const { series, labels, lineConfig, barConfig } = useMemo(
+ () =>
+ buildRetentionChartModel(results ?? [], {
+ aggregationType: query?.retentionFilter?.aggregationType ?? 'count',
+ reference: query?.retentionFilter?.retentionReference ?? 'total',
+ period: query?.retentionFilter?.period ?? 'Day',
+ showTrendLines: query?.retentionFilter?.showTrendLines ?? false,
+ getColor: colorAt,
+ tooltip: TOOLTIP_CONFIG,
+ }),
+ [
+ results,
+ query?.retentionFilter?.aggregationType,
+ query?.retentionFilter?.retentionReference,
+ query?.retentionFilter?.period,
+ query?.retentionFilter?.showTrendLines,
+ ]
+ )
if (!results || results.length === 0 || series.length === 0 || labels.length === 0) {
return (
@@ -168,31 +53,19 @@ export function RetentionVisualizer({ query, results }: RetentionVisualizerProps
)
}
- const yAxisLabel = isPercentage ? 'Retention %' : aggregationType === 'sum' ? 'Sum' : 'Avg'
- const truncationNotice =
- totalCohorts > MAX_COHORTS ? `Showing first ${MAX_COHORTS} of ${totalCohorts} cohorts (oldest first)` : null
-
return (
<div>
- <div
- style={{
- display: 'flex',
- justifyContent: 'space-between',
- alignItems: 'center',
- marginBottom: '0.5rem',
- }}
- >
- <span style={{ fontSize: '0.75rem', color: 'var(--color-text-secondary, #6b7280)' }}>
- {truncationNotice}
- </span>
+ <div className="mb-2 flex items-center justify-end">
{/* eslint-disable-next-line react/forbid-elements */}
<Select value={chartMode} onChange={setChartMode} options={CHART_MODE_OPTIONS} />
</div>
- {chartMode === 'bar' ? (
- <BarChart series={series} labels={labels} maxValue={maxValue} yAxisLabel={yAxisLabel} />
- ) : (
- <LineChart series={series} labels={labels} maxValue={maxValue} yAxisLabel={yAxisLabel} />
- )}
+ <div className="flex flex-col w-full h-[400px]">
+ {chartMode === 'bar' ? (
+ <TimeSeriesBarChart series={series} labels={labels} theme={CHART_THEME} config={barConfig} />
+ ) : (
+ <TimeSeriesLineChart series={series} labels={labels} theme={CHART_THEME} config={lineConfig} />
+ )}
+ </div>
</div>
)
}
diff --git a/services/mcp/src/ui-apps/components/charts/theme.ts b/services/mcp/src/ui-apps/components/charts/theme.ts
index a02f89286f15..1b5c6cbb3594 100644
--- a/services/mcp/src/ui-apps/components/charts/theme.ts
+++ b/services/mcp/src/ui-apps/components/charts/theme.ts
@@ -4,14 +4,25 @@ 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.
+// same array to stay in sync. Mirrors the web's --data-color-1..15 (light mode) in
+// frontend/src/styles/base.scss so MCP charts match the product and series with many
+// categories (e.g. retention cohorts) get distinct colors before wrapping.
export const CHART_COLORS = [
- '#1d4aff', // PostHog blue
- '#621da6', // PostHog purple
- '#00d683', // PostHog green
- '#f54e00', // PostHog orange
- '#f7a501', // PostHog yellow
- '#dc2626', // red
+ '#1d4aff',
+ '#621da6',
+ '#42827e',
+ '#ce0e74',
+ '#f14f58',
+ '#7c440e',
+ '#529a0a',
+ '#0476fb',
+ '#fe729e',
+ '#35416b',
+ '#41cbc4',
+ '#b64b02',
+ '#e4a604',
+ '#a56eff',
+ '#30d5c8',
]
// Picks a palette color by index, wrapping when there are more series than colors.
diff --git a/services/mcp/src/ui-apps/lib/index.ts b/services/mcp/src/ui-apps/lib/index.ts
index 2234aa3f97be..e552a93d8ace 100644
--- a/services/mcp/src/ui-apps/lib/index.ts
+++ b/services/mcp/src/ui-apps/lib/index.ts
@@ -3,4 +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'
+export { CHART_COLORS, CHART_THEME, FUNNEL_COLOR, LIFECYCLE_COLORS, colorAt, lifecycleColor } from '../components/charts/theme'