: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(insights): add retention cohort line colors and a mean line (#101548)
Sam Pennington82646daf81d2
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 1c76837729db..07acd4e14a72 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3264,10 +3264,18 @@ snapshots:hash: v1.k794b7964.ec5fcf8d9e4c3a49e94ffe769cb6147257f0e8fa0639f615e8d0f8a35d471492.jTfjU2lenc3lmyfgHtnetORnAO8bK6N9RMhAUqpTR7Einsights-retentionlinechart--default--light:hash: v1.k794b7964.edbf96b6533735d758f0f8dd66c6b98ff08fdb85e62fc9da687604230eeb72df.ZBXowD5R6W-29bGliO8emlqCMONXlj-JHYTtKJ59_uE+ insights-retentionlinechart--mean-line--dark:+ hash: v1.k794b7964.fa01ad2ba765c81533d3cf2b46b2cdc9eccc2e9cda633dccecc1944345f98ab5.NwWGyEsGj5iAd_mEvX8M2w-6hn-V37pE00vcl5whwkI+ insights-retentionlinechart--mean-line--light:+ hash: v1.k794b7964.4eead0f414a9b5310777aab2b552e3eed8aa9867bab5102693716cb539d2acae.jWJ74kUWkNKI7GEsbY0cUkWdLGFOy1AykvoVVp0NLL8insights-retentionlinechart--realistic-curve--dark:hash: v1.k794b7964.5e7cb4e9649a3a925374122709e6e5f06079fbcee7b127e7bedfc9e559fd492a.wUhYjH1xkcQ02vo5Wimx2flSUHACY-Vxh3FIGoQi00Iinsights-retentionlinechart--realistic-curve--light:hash: v1.k794b7964.3e4141c2a16b3e2f47465433ef4a4c6465000255c97faec25f458a8c01fb8253.AVEwr4UWiTybgaqLQRr5pWoH814DvMPZPQ7UTz2XKAQ+ insights-retentionlinechart--single-shade--dark:+ hash: v1.k794b7964.c9b09cab9020fff3cc459d362f501eb3fb3cbdade8d95b79000f6ca29c729cd6.KiLyKmSPeyZcuFOPjeI6tUrWHWtTKbWiKuY6kQ-X1PY+ insights-retentionlinechart--single-shade--light:+ hash: v1.k794b7964.db509e943d13cdd2e8870f19668ea9696fd10d4ecae443970bca4f80b7587e85.UgARvcHkRuuLYsaVboElyOD_GeeiqqrzEYSoOzS87_sinsights-sqlbargraph--grouped-bar-with-negative-values--dark:hash: v1.k794b7964.3958ab3fd470dfbf3a3dde5536bdbccdfd5205289f25a3ba5f3d98e069fdc4e7.WqKR9SVpum4z1_KyM3TXG6nN9BLC7cUiDWp0w0vpYmsinsights-sqlbargraph--grouped-bar-with-negative-values--light:diff --git a/frontend/src/queries/nodes/InsightViz/DisplayOptions.tsx b/frontend/src/queries/nodes/InsightViz/DisplayOptions.tsxindex 545b95efdb66..702ec7cc68d2 100644--- a/frontend/src/queries/nodes/InsightViz/DisplayOptions.tsx+++ b/frontend/src/queries/nodes/InsightViz/DisplayOptions.tsx@@ -42,6 +42,8 @@ import { ChartDisplayType } from '~/types'import { RetentionCohortLabelStartIndexPicker } from 'products/product_analytics/frontend/insights/retention/filters/RetentionCohortLabelStartIndexPicker'import { RetentionDashboardDisplayPicker } from 'products/product_analytics/frontend/insights/retention/filters/RetentionDashboardDisplayPicker'+import { RetentionMeanLineToggle } from 'products/product_analytics/frontend/insights/retention/filters/RetentionMeanLineToggle'+import { RetentionSeriesColorModePicker } from 'products/product_analytics/frontend/insights/retention/filters/RetentionSeriesColorModePicker'import { ConfidenceLevelInput } from 'products/product_analytics/frontend/insights/trends/filters/ConfidenceLevelInput'import { MovingAverageIntervalsInput } from 'products/product_analytics/frontend/insights/trends/filters/MovingAverageIntervalsInput'import { trendsDataLogic } from 'products/product_analytics/frontend/insights/trends/trendsDataLogic'@@ -248,6 +250,8 @@ export const DisplayOptions = {DecimalPrecision,RetentionDashboardDisplay: RetentionDashboardDisplayPicker,RetentionCohortLabelStart: RetentionCohortLabelStartIndexPicker,+ RetentionSeriesColorMode: RetentionSeriesColorModePicker,+ RetentionMeanLine: RetentionMeanLineToggle,} satisfies Record<string, () => JSX.Element | null>export type DisplayOption = (typeof DisplayOptions)[keyof typeof DisplayOptions]diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsxindex 35bf485d7407..df26d06796d9 100644--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.test.tsx@@ -49,8 +49,8 @@ function makeTrendsQuery(}}-function makeRetentionQuery(): RetentionQuery {- return { kind: NodeKind.RetentionQuery, retentionFilter: {} }+function makeRetentionQuery(retentionFilter: NonNullable<RetentionQuery['retentionFilter']> = {}): RetentionQuery {+ return { kind: NodeKind.RetentionQuery, retentionFilter }}function makeStickinessQuery(display?: ChartDisplayType): StickinessQuery {@@ -274,8 +274,10 @@ describe('InsightDisplayConfig', () => {makeRetentionQuery(),{tabs: [],- sections: { General: ['On dashboards', 'Cohort labels start at', 'Style', 'Overlays'] },- overlayItems: ['Show trend lines'],+ sections: {+ General: ['On dashboards', 'Cohort labels start at', 'Style', 'Cohort line colors', 'Overlays'],+ },+ overlayItems: ['Show trend lines', 'Show mean line'],},],[@@ -386,6 +388,32 @@ describe('InsightDisplayConfig', () => {})})+ describe('retention cohort line colors', () => {+ it('keeps the line curve when switching to one shade', async () => {+ setupAndRender(makeRetentionQuery({ chartStyle: { curve: 'linear' } }))+ await openOptionsMenu()++ await userEvent.click(within(getPanel()).getByText('One shade'))++ expect(+ (insightVizDataLogic(insightProps).values.querySource as RetentionQuery).retentionFilter.chartStyle+ ).toEqual({ curve: 'linear', seriesColorMode: 'opacity' })+ })+ })++ describe('retention mean line', () => {+ it('writes showMeanLine when the toggle is clicked', async () => {+ setupAndRender(makeRetentionQuery())+ await openOptionsMenu()++ await userEvent.click(within(getPanel()).getByText('Show mean line'))++ expect(+ (insightVizDataLogic(insightProps).values.querySource as RetentionQuery).retentionFilter.showMeanLine+ ).toBe(true)+ })+ })+describe('line graph display options', () => {it('shows the "group by time period" interval picker (control for the slope graph)', async () => {setupAndRender(makeTrendsQuery(ChartDisplayType.ActionsLineGraph))diff --git a/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx b/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsxindex de5d5968be23..d4032cea5300 100644--- a/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx+++ b/frontend/src/queries/nodes/InsightViz/insightDisplayOptions.tsx@@ -7,7 +7,7 @@ import { PIE_DISPLAY_TYPES } from 'lib/constants'import { insightLogic } from 'scenes/insights/insightLogic'import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'-import type { TrendsFilter } from '~/queries/schema/schema-general'+import type { RetentionFilter, TrendsFilter } from '~/queries/schema/schema-general'import { hasBreakdownFilter } from '~/queries/utils'import { ChartDisplayType } from '~/types'@@ -280,10 +280,21 @@ export function useInsightDisplayOptions(): { tabs: DisplayOptionTab[]; count: nif (showAlertThresholdLinesConfig && !isBoxPlot) {overlayItems.push(DisplayOptions.AlertThresholdLines)}+ if (isRetention && isLineChartInsight) {+ overlayItems.push(DisplayOptions.RetentionMeanLine)+ }const linesSections: DisplayOptionSection[] = []if (styleItems.length > 0) {linesSections.push({ key: 'style', title: 'Style', items: styleItems })}+ if (isRetention && isLineChartInsight) {+ linesSections.push({+ key: 'retention-series-colors',+ title: 'Cohort line colors',+ tooltip: 'One shade draws every cohort in the same color, with the newest cohort the most solid.',+ items: [DisplayOptions.RetentionSeriesColorMode],+ })+ }if (overlayItems.length > 0) {linesSections.push({key: 'overlays',@@ -322,7 +333,11 @@ export function useInsightDisplayOptions(): { tabs: DisplayOptionTab[]; count: nshowTrendLinesConfig && !isBoxPlot && (insightFilter as TrendsFilter | undefined)?.showTrendLines,showStatisticalOverlays && showMovingAverage,showStatisticalOverlays && showConfidenceIntervals,- showAlertThresholdLinesConfig && !isBoxPlot && showAlertThresholdLines+ showAlertThresholdLinesConfig && !isBoxPlot && showAlertThresholdLines,+ isRetention &&+ isLineChartInsight &&+ (insightFilter as TrendsFilter | undefined)?.chartStyle?.seriesColorMode === 'opacity',+ isRetention && isLineChartInsight && (insightFilter as RetentionFilter | undefined)?.showMeanLine)const allTabs: DisplayOptionTab[] = [diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.jsonindex 768689ee62fe..dedf418a8abb 100644--- a/frontend/src/queries/schema.json+++ b/frontend/src/queries/schema.json@@ -16940,6 +16940,11 @@"description": "Line interpolation: straight segments or a smoothed curve through the points.","enum": ["linear", "smooth"],"type": "string"+ },+ "seriesColorMode": {+ "description": "How series are told apart: one color per series, or one color at stepped opacities.",+ "enum": ["palette", "opacity"],+ "type": "string"}},"type": "object"@@ -49082,6 +49087,10 @@],"description": "The selected interval to display across all cohorts (null = show all intervals for each cohort)"},+ "showMeanLine": {+ "description": "Draw the mean across cohorts as one line on the retention graph.",+ "type": "boolean"+ },"showTrendLines": {"type": "boolean"},diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.tsindex 545189927c7b..56427c43c983 100644--- a/frontend/src/queries/schema/schema-general.ts+++ b/frontend/src/queries/schema/schema-general.ts@@ -1714,6 +1714,8 @@ export type TrendsFormulaNode = {export interface ChartStyle {/** Line interpolation: straight segments or a smoothed curve through the points. */curve?: 'linear' | 'smooth'+ /** How series are told apart: one color per series, or one color at stepped opacities. */+ seriesColorMode?: 'palette' | 'opacity'}export type TrendsFilter = {@@ -2181,6 +2183,8 @@ export type RetentionFilter = {display?: ChartDisplayTypedashboardDisplay?: RetentionDashboardDisplayTypeshowTrendLines?: boolean+ /** Draw the mean across cohorts as one line on the retention graph. */+ showMeanLine?: boolean/** The selected interval to display across all cohorts (null = show all intervals for each cohort) */selectedInterval?: integer | nullgoalLines?: GoalLine[]diff --git a/frontend/src/scenes/insights/utils/queryUtils.ts b/frontend/src/scenes/insights/utils/queryUtils.tsindex aa93b7b70aa7..3c6db4836342 100644--- a/frontend/src/scenes/insights/utils/queryUtils.ts+++ b/frontend/src/scenes/insights/utils/queryUtils.ts@@ -321,6 +321,7 @@ export const cleanInsightQuery = (query: InsightQueryNode, opts?: CompareQueryOpshowConfidenceIntervals: undefined,confidenceLevel: undefined,showTrendLines: undefined,+ showMeanLine: undefined,showMovingAverage: undefined,movingAverageIntervals: undefined,stacked: undefined,diff --git a/posthog/schema.py b/posthog/schema.pyindex 1d92d0e36316..61740a1a63fe 100644--- a/posthog/schema.py+++ b/posthog/schema.py@@ -247,6 +247,7 @@ from posthog.schema_enums import (RetentionReference as RetentionReference,RetentionType as RetentionType,Scale as Scale,+ SeriesColorMode as SeriesColorMode,SessionAttributionGroupBy as SessionAttributionGroupBy,SessionsV2JoinMode as SessionsV2JoinMode,SessionTableVersion as SessionTableVersion,@@ -1031,6 +1032,10 @@ class ChartStyle(BaseModel):default=None,description=("Line interpolation: straight segments or a smoothed curve through the points."),)+ seriesColorMode: SeriesColorMode | None = Field(+ default=None,+ description=("How series are told apart: one color per series, or one color at stepped opacities."),+ )class ClientToolResultPayload(BaseModel):@@ -28252,6 +28257,10 @@ class RetentionFilter(BaseModel):default=None,description=("The selected interval to display across all cohorts (null = show all intervals for each cohort)"),)+ showMeanLine: bool | None = Field(+ default=None,+ description="Draw the mean across cohorts as one line on the retention graph.",+ )showTrendLines: bool | None = NonetargetEntity: RetentionEntity | None = NonetimeWindowMode: TimeWindowMode | None = Field(diff --git a/posthog/schema_enums.py b/posthog/schema_enums.pyindex d05a4ec24a12..ae39633b328c 100644--- a/posthog/schema_enums.py+++ b/posthog/schema_enums.py@@ -709,6 +709,11 @@ class Curve(StrEnum):SMOOTH = "smooth"+class SeriesColorMode(StrEnum):+ PALETTE = "palette"+ OPACITY = "opacity"++class ColorMode(StrEnum):LIGHT = "light"DARK = "dark"diff --git a/posthog/schema_helpers.py b/posthog/schema_helpers.pyindex 40cce79ab08f..25f518e751b4 100644--- a/posthog/schema_helpers.py+++ b/posthog/schema_helpers.py@@ -112,6 +112,7 @@ def to_dict(query: BaseModel) -> dict:"showConfidenceIntervals","confidenceLevel","showTrendLines",+ "showMeanLine","showMovingAverage","movingAverageIntervals","stacked",diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex 6b199a1dd4cc..8f8c8326d35c 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -2780,9 +2780,18 @@ export const CurveApi = {Smooth: 'smooth',} as const+export type SeriesColorModeApi = (typeof SeriesColorModeApi)[keyof typeof SeriesColorModeApi]++export const SeriesColorModeApi = {+ Palette: 'palette',+ Opacity: 'opacity',+} as const+export interface ChartStyleApi {/** Line interpolation: straight segments or a smoothed curve through the points. */curve?: CurveApi | null+ /** How series are told apart: one color per series, or one color at stepped opacities. */+ seriesColorMode?: SeriesColorModeApi | null}export type DetailedResultsAggregationTypeApi =@@ -3709,6 +3718,8 @@ export interface RetentionFilterApi {returningEntity?: RetentionEntityApi | null/** The selected interval to display across all cohorts (null = show all intervals for each cohort) */selectedInterval?: number | null+ /** Draw the mean across cohorts as one line on the retention graph. */+ showMeanLine?: boolean | nullshowTrendLines?: boolean | nulltargetEntity?: RetentionEntityApi | null/** The time window mode to use for retention calculations */diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.tsindex 71c765975cd6..8a77c49996b1 100644--- a/products/product_analytics/frontend/generated/api.schemas.ts+++ b/products/product_analytics/frontend/generated/api.schemas.ts@@ -1774,9 +1774,18 @@ export const CurveApi = {Smooth: 'smooth',} as const+export type SeriesColorModeApi = (typeof SeriesColorModeApi)[keyof typeof SeriesColorModeApi]++export const SeriesColorModeApi = {+ Palette: 'palette',+ Opacity: 'opacity',+} as const+export interface ChartStyleApi {/** Line interpolation: straight segments or a smoothed curve through the points. */curve?: CurveApi | null+ /** How series are told apart: one color per series, or one color at stepped opacities. */+ seriesColorMode?: SeriesColorModeApi | null}export type DetailedResultsAggregationTypeApi =@@ -2703,6 +2712,8 @@ export interface RetentionFilterApi {returningEntity?: RetentionEntityApi | null/** The selected interval to display across all cohorts (null = show all intervals for each cohort) */selectedInterval?: number | null+ /** Draw the mean across cohorts as one line on the retention graph. */+ showMeanLine?: boolean | nullshowTrendLines?: boolean | nulltargetEntity?: RetentionEntityApi | null/** The time window mode to use for retention calculations */diff --git a/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.stories.tsx b/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.stories.tsxindex 280845a1b421..a802eecdf5a4 100644--- a/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.stories.tsx+++ b/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.stories.tsx@@ -84,3 +84,39 @@ const realisticFixture = {export const RealisticCurve: Story = {render: () => renderRetentionLineChart(realisticFixture),}++const singleShadeFixture = {+ ...realisticFixture,+ query: {+ ...retentionFixture.query,+ source: {+ ...retentionFixture.query.source,+ retentionFilter: {+ ...retentionFixture.query.source.retentionFilter,+ chartStyle: { seriesColorMode: 'opacity' },+ },+ },+ },+}++export const SingleShade: Story = {+ render: () => renderRetentionLineChart(singleShadeFixture),+}++const meanLineFixture = {+ ...realisticFixture,+ query: {+ ...retentionFixture.query,+ source: {+ ...retentionFixture.query.source,+ retentionFilter: {+ ...retentionFixture.query.source.retentionFilter,+ showMeanLine: true,+ },+ },+ },+}++export const MeanLine: Story = {+ render: () => renderRetentionLineChart(meanLineFixture),+}diff --git a/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsx b/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsxindex 95504ca61531..4d03c58d8a2e 100644--- a/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsx+++ b/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsx@@ -6,6 +6,7 @@ import { TimeSeriesLineChart } from '@posthog/quill-charts'import type { PointClickData, TooltipContext } from '@posthog/quill-charts'import { useChartConfig, useChartTheme } from 'lib/charts/hooks'+import { getColorVar } from 'lib/colors'import { roundToDecimal } from 'lib/utils/numbers'import { insightLogic } from 'scenes/insights/insightLogic'import type { SeriesDatum } from 'scenes/insights/InsightTooltip/insightTooltipUtils'@@ -17,12 +18,15 @@ import type { GroupTypeIndex, LabelGroupType } from '~/types'import { chartStyleCurve } from '../../shared/chartStyleAdapter'import { InsightSeriesTooltip } from '../../shared/InsightSeriesTooltip'import { INSIGHT_TOOLTIP_CONFIG } from '../../shared/tooltipConfig'+import { dimHexColor } from '../../trends/shared/compareDimming'import { retentionGraphLogic } from '../retentionGraphLogic'import { retentionModalLogic } from '../retentionModalLogic'import {buildRetentionLineChartConfig,+ buildRetentionMeanSeries,buildRetentionSeries,type RetentionSeriesMeta,+ retentionSeriesOpacity,type RetentionTrendSeriesEntry,} from '../shared/retentionChartTransforms'@@ -61,6 +65,7 @@ export function RetentionLineChart({ inSharedMode = false }: RetentionLineChartPfilteredTrendSeries,incompletenessOffsetFromEnd,labelGroupType,+ meanLineData,shouldShowMeanPerBreakdown,showTrendLines,timezone,@@ -78,21 +83,41 @@ export function RetentionLineChart({ inSharedMode = false }: RetentionLineChartP// Shared (public) views don't have the persons modal mounted — disable click-to-open there.const canClick = !shouldShowMeanPerBreakdown && !inSharedMode && canOpenPersonModal- const series = useMemo(- () =>- buildRetentionSeries(filteredTrendSeries as RetentionTrendSeriesEntry[], {- incompletenessOffsetFromEnd,- isIntervalView,- getColor: (entry, index) => getRetentionColor(entry.rawBreakdownValue, index),- }),- [filteredTrendSeries, incompletenessOffsetFromEnd, isIntervalView, getRetentionColor]- )+ // Opacity only separates lines that are cohorts of one thing. The interval and+ // mean-per-breakdown views draw one line per breakdown value, which needs its own color.+ const fadeCohorts =+ retentionFilter?.chartStyle?.seriesColorMode === 'opacity' && !isIntervalView && !shouldShowMeanPerBreakdown++ // Re-resolved per theme: getColorVar reads the CSS variable, which changes with the theme.+ const meanColor = useMemo(() => getColorVar('color-accent'), [theme])++ const series = useMemo(() => {+ const cohortSeries = buildRetentionSeries(filteredTrendSeries as RetentionTrendSeriesEntry[], {+ incompletenessOffsetFromEnd,+ isIntervalView,+ getColor: (entry, index) => {+ const color = getRetentionColor(entry.rawBreakdownValue, fadeCohorts ? 0 : index)+ return fadeCohorts && color+ ? dimHexColor(color, retentionSeriesOpacity(index, filteredTrendSeries.length))+ : color+ },+ })+ return meanLineData ? [...cohortSeries, buildRetentionMeanSeries(meanLineData, meanColor)] : cohortSeries+ }, [+ filteredTrendSeries,+ incompletenessOffsetFromEnd,+ isIntervalView,+ getRetentionColor,+ fadeCohorts,+ meanLineData,+ meanColor,+ ])const groupTypeLabel = resolveGroupTypeLabel(labelGroupType, aggregationLabel)const onRowClick = useCallback((datum: SeriesDatum) => {- if (shouldShowMeanPerBreakdown) {+ if (shouldShowMeanPerBreakdown || series[datum.datasetIndex]?.meta?.isMean) {return}// In interval view each x-position is a different cohort, otherwise each series is.@@ -118,6 +143,9 @@ export function RetentionLineChart({ inSharedMode = false }: RetentionLineChartPaltTitle={altTitle}renderCount={(value) => (isPercentage ? `${roundToDecimal(value)}%` : `${roundToDecimal(value)}`)}renderSeriesOverride={(datum) => {+ if (series[datum.datasetIndex]?.meta?.isMean) {+ return datum.label ?? ''+ }const showCohortPrefix = selectedInterval !== null || !shouldShowMeanPerBreakdownreturn showCohortPrefix ? `Cohort ${datum.label ?? ''}` : (datum.label ?? '')}}@@ -135,12 +163,13 @@ export function RetentionLineChart({ inSharedMode = false }: RetentionLineChartPgroupTypeLabel,onRowClick,canClick,+ series,])const onPointClick = useCallback((clickData: PointClickData<RetentionSeriesMeta>) => {- if (shouldShowMeanPerBreakdown) {+ if (shouldShowMeanPerBreakdown || clickData.series.meta?.isMean) {return}const rowIndex = isIntervalViewdiff --git a/products/product_analytics/frontend/insights/retention/filters/RetentionMeanLineToggle.tsx b/products/product_analytics/frontend/insights/retention/filters/RetentionMeanLineToggle.tsxnew file mode 100644index 000000000000..61db01df9244--- /dev/null+++ b/products/product_analytics/frontend/insights/retention/filters/RetentionMeanLineToggle.tsx@@ -0,0 +1,38 @@+import { useActions, useValues } from 'kea'++import { LemonCheckbox } from '@posthog/lemon-ui'++import { insightLogic } from 'scenes/insights/insightLogic'+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'++import { retentionGraphLogic } from '../retentionGraphLogic'++export function RetentionMeanLineToggle(): JSX.Element | null {+ const { insightProps, canEditInsight } = useValues(insightLogic)+ const { retentionFilter } = useValues(insightVizDataLogic(insightProps))+ const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))+ const { hasValidBreakdown } = useValues(retentionGraphLogic(insightProps))++ if (!canEditInsight) {+ return null+ }++ const selectedInterval = retentionFilter?.selectedInterval ?? null+ const disabledReason =+ selectedInterval !== null+ ? 'Mean line is not available when viewing a single interval.'+ : hasValidBreakdown+ ? 'Mean line is not available with a breakdown applied.'+ : undefined++ return (+ <LemonCheckbox+ className="p-1 px-2"+ checked={!disabledReason && !!retentionFilter?.showMeanLine}+ onChange={(showMeanLine) => updateInsightFilter({ showMeanLine })}+ disabledReason={disabledReason}+ label={<span className="font-normal">Show mean line</span>}+ size="small"+ />+ )+}diff --git a/products/product_analytics/frontend/insights/retention/filters/RetentionSeriesColorModePicker.tsx b/products/product_analytics/frontend/insights/retention/filters/RetentionSeriesColorModePicker.tsxnew file mode 100644index 000000000000..89ffebc419df--- /dev/null+++ b/products/product_analytics/frontend/insights/retention/filters/RetentionSeriesColorModePicker.tsx@@ -0,0 +1,34 @@+import { useActions, useValues } from 'kea'++import { LemonSegmentedButton } from '@posthog/lemon-ui'++import { insightLogic } from 'scenes/insights/insightLogic'+import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'++export function RetentionSeriesColorModePicker(): JSX.Element | null {+ const { insightProps, canEditInsight } = useValues(insightLogic)+ const { retentionFilter } = useValues(insightVizDataLogic(insightProps))+ const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))++ if (!canEditInsight) {+ return null+ }++ const chartStyle = retentionFilter?.chartStyle++ return (+ <LemonSegmentedButton+ className="pb-2 px-2"+ value={chartStyle?.seriesColorMode || 'palette'}+ onChange={(value) => {+ updateInsightFilter({ chartStyle: { ...chartStyle, seriesColorMode: value } })+ }}+ options={[+ { value: 'palette', label: 'One per cohort' },+ { value: 'opacity', label: 'One shade' },+ ]}+ size="small"+ fullWidth+ />+ )+}diff --git a/products/product_analytics/frontend/insights/retention/retentionGraphLogic.test.ts b/products/product_analytics/frontend/insights/retention/retentionGraphLogic.test.tsindex d15ccb9452aa..647f1a7480df 100644--- a/products/product_analytics/frontend/insights/retention/retentionGraphLogic.test.ts+++ b/products/product_analytics/frontend/insights/retention/retentionGraphLogic.test.ts@@ -36,6 +36,28 @@ const breakdownRows = [cohortRow('2024-01-01T00:00:00Z', BREAKDOWN_OTHER_STRING_LABEL),]+// Far enough back that no interval is still in progress, so the mean covers every point.+const COMPLETE_RANGE = { date_to: '2024-01-05' }++const overallRows = [+ {+ date: '2024-01-01T00:00:00Z',+ label: 'Day 0',+ values: [+ { count: 100, aggregation_value: 100 },+ { count: 50, aggregation_value: 60 },+ ],+ },+ {+ date: '2024-01-02T00:00:00Z',+ label: 'Day 0',+ values: [+ { count: 80, aggregation_value: 80 },+ { count: 40, aggregation_value: 20 },+ ],+ },+]+let logic: ReturnType<typeof retentionGraphLogic.build>let builtRetentionLogic: ReturnType<typeof retentionLogic.build>@@ -131,4 +153,60 @@ describe('retentionGraphLogic', () => {expect(token('Chrome', 1)).toBe('preset-2')expect(builtRetentionLogic.values.getRetentionColor('Chrome', 1)).toBe('#222222')})++ describe('meanLineData', () => {+ it.each([+ ['off by default', { period: RetentionPeriod.Day }, null],+ [+ 'on with no breakdown or interval selected',+ { period: RetentionPeriod.Day, showMeanLine: true },+ [100, 50],+ ],+ [+ 'suppressed when an interval is selected',+ { period: RetentionPeriod.Day, showMeanLine: true, selectedInterval: 1 },+ null,+ ],+ ])('%s', async (_name, retentionFilter, expected) => {+ await loadResults(+ { kind: NodeKind.RetentionQuery, dateRange: COMPLETE_RANGE, retentionFilter },+ overallRows+ )+ expect(logic.values.meanLineData).toEqual(expected)+ })++ it('is suppressed when a breakdown is active', async () => {+ await loadResults(+ { ...breakdownQuery, retentionFilter: { period: RetentionPeriod.Day, showMeanLine: true } },+ breakdownRows+ )+ expect(logic.values.meanLineData).toBeNull()+ })++ it('stops before an in-progress interval rather than plotting its partial average', async () => {+ await loadResults(+ { kind: NodeKind.RetentionQuery, retentionFilter: { period: RetentionPeriod.Day, showMeanLine: true } },+ overallRows+ )++ expect(logic.values.meanLineData).toEqual([100])+ })++ it('uses meanValues instead of meanPercentages for property-value aggregation', async () => {+ await loadResults(+ {+ kind: NodeKind.RetentionQuery,+ dateRange: COMPLETE_RANGE,+ retentionFilter: {+ period: RetentionPeriod.Day,+ showMeanLine: true,+ aggregationType: 'sum',+ aggregationProperty: 'revenue',+ },+ },+ overallRows+ )+ expect(logic.values.meanLineData).toEqual([90, 40])+ })+ })})diff --git a/products/product_analytics/frontend/insights/retention/retentionGraphLogic.ts b/products/product_analytics/frontend/insights/retention/retentionGraphLogic.tsindex d97ea429c712..5d9fe4b84857 100644--- a/products/product_analytics/frontend/insights/retention/retentionGraphLogic.ts+++ b/products/product_analytics/frontend/insights/retention/retentionGraphLogic.ts@@ -21,7 +21,7 @@ import type { LabelGroupType } from '~/types'import { dateOptionPlurals } from './constants'import { dateOptionToTimeIntervalMap } from './constants'-import { MeanRetentionValue, retentionLogic } from './retentionLogic'+import { MeanRetentionValue, OVERALL_MEAN_KEY, retentionLogic } from './retentionLogic'import { ProcessedRetentionPayload, RetentionTrendPayload } from './types'import { formatRetentionCohortLabel } from './utils'@@ -58,6 +58,7 @@ export interface retentionGraphLogicValues {filteredTrendSeries: RetentionTrendPayload[]incompletenessOffsetFromEnd: numberintervalViewSeries: RetentionTrendPayload[]+ meanLineData: number[] | nullshouldShowMeanPerBreakdown: booleanshowTrendLines: booleantrendSeries: RetentionTrendPayload[]@@ -103,6 +104,13 @@ export interface retentionGraphLogicMeta {hasValidBreakdown: boolean,selectedBreakdownValue: boolean | number | string | null) => boolean+ meanLineData: (+ retentionFilter: RetentionFilter | null,+ retentionMeans: Record<string, MeanRetentionValue>,+ shouldShowMeanPerBreakdown: boolean,+ isPropertyValueAggregation: boolean,+ incompletenessOffsetFromEnd: number+ ) => number[] | nullfilteredTrendSeries: (hasValidBreakdown: boolean,trendSeries: RetentionTrendPayload[],@@ -315,6 +323,40 @@ export const retentionGraphLogic = kea<retentionGraphLogicType>([},],+ meanLineData: [+ (s) => [+ s.retentionFilter,+ s.retentionMeans,+ s.shouldShowMeanPerBreakdown,+ s.isPropertyValueAggregation,+ s.incompletenessOffsetFromEnd,+ ],+ (+ retentionFilter: RetentionFilter | null,+ retentionMeans: Record<string, MeanRetentionValue>,+ shouldShowMeanPerBreakdown: boolean,+ isPropertyValueAggregation: boolean,+ incompletenessOffsetFromEnd: number+ ): number[] | null => {+ // The overall mean is only keyed when there's no breakdown; the per-breakdown view+ // already draws a line per breakdown mean.+ if (!retentionFilter?.showMeanLine || shouldShowMeanPerBreakdown) {+ return null+ }+ if ((retentionFilter?.selectedInterval ?? null) !== null) {+ return null+ }+ const overall = retentionMeans[OVERALL_MEAN_KEY]+ if (!overall) {+ return null+ }+ const data = isPropertyValueAggregation ? overall.meanValues : overall.meanPercentages+ // The mean drops in-progress rows, so its tail averages fewer cohorts than the lines it overlays.+ const complete = incompletenessOffsetFromEnd < 0 ? data.slice(0, incompletenessOffsetFromEnd) : data+ return complete.length > 0 ? complete : null+ },+ ],+filteredTrendSeries: [(s) => [s.hasValidBreakdown,diff --git a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.ts b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.tsindex 00d4c34226f3..7f2105d2ba82 100644--- a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.ts@@ -9,12 +9,14 @@ import {buildRetentionBarChartConfig,buildRetentionChartModel,buildRetentionLineChartConfig,+ buildRetentionMeanSeries,buildRetentionSeries,type RetentionCohortLike,computeRetentionSeriesValue,formatRetentionCohortLabel,type RetentionResultLike,type RetentionSeriesMeta,+ retentionSeriesOpacity,type RetentionTrendSeriesEntry,sortRetentionCohorts,} from './retentionChartTransforms'@@ -180,6 +182,16 @@ describe('retentionChartTransforms', () => {expect(config.xAxis).toEqual({ interval: 'day', timezone: 'America/Chicago' })})+ describe('retentionSeriesOpacity', () => {+ it.each<[string, number, number, number]>([+ ['newest cohort stays solid', 4, 5, 1],+ ['oldest cohort fades', 0, 5, 0.25],+ ['a lone cohort stays solid', 0, 1, 1],+ ])('%s', (_name, index, total, expected) => {+ expect(retentionSeriesOpacity(index, total)).toBeCloseTo(expected)+ })+ })+describe('buildRetentionLineChartConfig', () => {const baseSeries: Series<RetentionSeriesMeta>[] = buildRetentionSeries([makeEntry({ index: 0 }), makeEntry({ index: 1 })],@@ -206,6 +218,18 @@ describe('retentionChartTransforms', () => {])})+ it('excludes the mean overlay from trend lines', () => {+ const config = buildRetentionLineChartConfig({+ isPercentage: true,+ series: [...baseSeries, buildRetentionMeanSeries([1, 2])],+ showTrendLines: true,+ })+ expect(config.trendLines).toEqual([+ { seriesKey: 'retention-0', kind: 'linear' },+ { seriesKey: 'retention-1', kind: 'linear' },+ ])+ })+it('omits trend lines when showTrendLines is false', () => {const config = buildRetentionLineChartConfig({ isPercentage: true, series: baseSeries })expect(config.trendLines).toBeUndefined()diff --git a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.tsindex 5aff94dd3648..72ac1192ab00 100644--- a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts+++ b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts@@ -39,6 +39,7 @@ export interface RetentionSeriesMeta {days?: string[]cohortLabel?: stringcohortCount: number+ isMean?: boolean}export interface BuildRetentionSeriesOpts {@@ -87,6 +88,27 @@ export function buildRetentionSeries(})}+/** Opacity for one cohort line when every line shares a color: the newest cohort is fully opaque+ * and earlier ones fade, so the lines stay separable without a palette. */+export function retentionSeriesOpacity(index: number, total: number): number {+ const MIN_OPACITY = 0.25+ if (total <= 1) {+ return 1+ }+ return MIN_OPACITY + (1 - MIN_OPACITY) * (index / (total - 1))+}++export function buildRetentionMeanSeries(data: number[], color?: string): Series<RetentionSeriesMeta> {+ return {+ key: 'retention-mean',+ label: 'Mean',+ data,+ color,+ meta: { rowIndex: -1, cohortCount: 0, isMean: true },+ stroke: { pattern: [6, 4] },+ }+}+export interface BuildRetentionChartConfigOpts {isPercentage: booleangoalLines?: GoalLineLike[] | null@@ -105,7 +127,7 @@ function buildTrendLines(if (!enabled || series.length === 0) {return undefined}- return series.map((s) => ({ seriesKey: s.key, kind: 'linear' }))+ return series.filter((s) => !s.meta?.isMean).map((s) => ({ seriesKey: s.key, kind: 'linear' }))}function buildGoalLines(goalLines: GoalLineLike[] | null | undefined): GoalLineConfig[] | undefined {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex c285b7cd1841..c8940914bd9a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -3923,9 +3923,19 @@ export namespace Schemas {Smooth: 'smooth',} as const;+ export type SeriesColorMode = typeof SeriesColorMode[keyof typeof SeriesColorMode];+++ export const SeriesColorMode = {+ Palette: 'palette',+ Opacity: 'opacity',+ } as const;+export interface ChartStyle {/** Line interpolation: straight segments or a smoothed curve through the points. */curve?: Curve | null;+ /** How series are told apart: one color per series, or one color at stepped opacities. */+ seriesColorMode?: SeriesColorMode | null;}export type DetailedResultsAggregationType = typeof DetailedResultsAggregationType[keyof typeof DetailedResultsAggregationType];@@ -4598,6 +4608,8 @@ export namespace Schemas {returningEntity?: RetentionEntity | null;/** The selected interval to display across all cohorts (null = show all intervals for each cohort) */selectedInterval?: number | null;+ /** Draw the mean across cohorts as one line on the retention graph. */+ showMeanLine?: boolean | null;showTrendLines?: boolean | null;targetEntity?: RetentionEntity | null;/** The time window mode to use for retention calculations */