: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(dashboards): breakdown colors for retention and funnel trends (#73734)
Thomas Obermüller894c7ce25ce1
diff --git a/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx b/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsxindex 0dd8e51ea394..7d9813e14fe0 100644--- a/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx+++ b/frontend/src/scenes/dashboard/DashboardInsightColorsModal.tsx@@ -126,7 +126,7 @@ export function DashboardInsightColorsModal(): JSX.Element {<LemonLabel className="mt-4">Breakdown colors</LemonLabel><p className="text-muted-alt mb-4">Breakdown values get a consistent color across all insights on this dashboard. Pick a color to pin a- value to it. <i>Note: This feature currently only works for trend and step-based funnel insights.</i>+ value to it. <i>Note: This works for trend, funnel, and retention insights.</i></p><LemonTablecolumns={columns}diff --git a/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.ts b/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.tsindex 9016fd92d3ba..2f51f58ace21 100644--- a/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.ts+++ b/frontend/src/scenes/dashboard/dashboardBreakdownColors.test.ts@@ -144,17 +144,94 @@ describe('dashboardBreakdownColors', () => {])})- it('ignores non-matching insight types', () => {+ it('handles funnel insights with trends visualization, without a baseline row', () => {const tiles = [createTestTile({- result: [],+ result: [{ breakdown_value: ['Chrome'] }, { breakdown_value: ['Firefox'] }],query: {kind: NodeKind.InsightVizNode,- source: { kind: NodeKind.RetentionQuery },+ source: {+ kind: NodeKind.FunnelsQuery,+ funnelsFilter: {+ funnelVizType: FunnelVizType.Trends,+ },+ },} as InsightVizNode<InsightQueryNode>,}),]- expect(extractBreakdownValues(tiles, null)).toEqual([])++ expect(extractBreakdownValues(tiles, null)).toEqual([+ { breakdownValue: 'Chrome', breakdownType: 'event' },+ { breakdownValue: 'Firefox', breakdownType: 'event' },+ ])+ })++ it('handles retention insights with a breakdown', () => {+ const retentionTile = (result: any[]): DashboardTile<QueryBasedInsightModel> =>+ createTestTile({+ result,+ query: {+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.RetentionQuery,+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },+ },+ } as InsightVizNode<InsightQueryNode>,+ })++ const tiles = [+ retentionTile([+ { breakdown_value: 'Chrome' },+ { breakdown_value: 'Chrome' },+ { breakdown_value: '$$_posthog_breakdown_other_$$' },+ { breakdown_value: null },+ ]),+ retentionTile([{ breakdown_value: 'Firefox' }]),+ ]++ expect(extractBreakdownValues(tiles, null)).toEqual([+ { breakdownValue: '$$_posthog_breakdown_other_$$', breakdownType: 'event' },+ { breakdownValue: 'Chrome', breakdownType: 'event' },+ { breakdownValue: 'Firefox', breakdownType: 'event' },+ ])+ })++ it.each([+ [+ 'paths insight',+ createTestTile({+ result: [{ breakdown_value: 'Chrome' }],+ query: {+ kind: NodeKind.InsightVizNode,+ source: { kind: NodeKind.PathsQuery },+ } as InsightVizNode<InsightQueryNode>,+ }),+ ],+ [+ 'time-to-convert funnel',+ createTestTile({+ result: [{ breakdown_value: 'Chrome' }],+ query: {+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.FunnelsQuery,+ funnelsFilter: { funnelVizType: FunnelVizType.TimeToConvert },+ },+ } as InsightVizNode<InsightQueryNode>,+ }),+ ],+ [+ 'retention insight without a breakdown filter',+ createTestTile({+ result: [{ breakdown_value: 'Chrome' }],+ query: {+ kind: NodeKind.InsightVizNode,+ source: { kind: NodeKind.RetentionQuery },+ } as InsightVizNode<InsightQueryNode>,+ }),+ ],+ ])('ignores %s', (_name, tile) => {+ expect(extractBreakdownValues([tile], null)).toEqual([])})it('handles cohort breakdowns', () => {diff --git a/frontend/src/scenes/dashboard/dashboardBreakdownColors.ts b/frontend/src/scenes/dashboard/dashboardBreakdownColors.tsindex 039c776b480b..f49b3b895cbd 100644--- a/frontend/src/scenes/dashboard/dashboardBreakdownColors.ts+++ b/frontend/src/scenes/dashboard/dashboardBreakdownColors.ts@@ -8,7 +8,7 @@ import {} from 'scenes/insights/utils'import { BreakdownFilter } from '~/queries/schema/schema-general'-import { isFunnelsQuery, isInsightVizNode, isTrendsQuery } from '~/queries/utils'+import { hasBreakdownFilter, isFunnelsQuery, isInsightVizNode, isRetentionQuery, isTrendsQuery } from '~/queries/utils'import { CohortType, DashboardTile, FunnelVizType, QueryBasedInsightModel } from '~/types'export type BreakdownColorSource = 'auto' | 'manual'@@ -100,18 +100,23 @@ export function extractBreakdownValues(.flatMap((tile) => {if (isInsightVizNode(tile.insight?.query)) {const querySource = tile.insight?.query.source- if (- isFunnelsQuery(querySource) &&- (querySource.funnelsFilter?.funnelVizType === undefined ||- querySource.funnelsFilter?.funnelVizType === FunnelVizType.Steps)- ) {+ if (isFunnelsQuery(querySource)) {+ const funnelVizType = querySource.funnelsFilter?.funnelVizType+ const isStepsViz = funnelVizType === undefined || funnelVizType === FunnelVizType.Steps+ // Time-to-convert renders a single-color histogram, so it has nothing to contribute.+ if (!isStepsViz && funnelVizType !== FunnelVizType.Trends) {+ return []+ }const breakdownType = querySource.breakdownFilter?.breakdown_type || 'event'- const breakdownValues: (BreakdownValueAndType | null)[] = [- {- breakdownValue: FUNNEL_BASELINE_BREAKDOWN_LABEL,- breakdownType,- },- ]+ // Only the steps visualization renders a baseline series.+ const breakdownValues: (BreakdownValueAndType | null)[] = isStepsViz+ ? [+ {+ breakdownValue: FUNNEL_BASELINE_BREAKDOWN_LABEL,+ breakdownType,+ },+ ]+ : []tile.insight?.result?.forEach((result: any) => {const key = getFunnelDatasetKey(result)const breakdownValue = normalizeBreakdownValue(JSON.parse(key)['breakdown_value'])@@ -127,6 +132,17 @@ export function extractBreakdownValues(return breakdownValue == null ? null : { breakdownValue, breakdownType }}) || [])+ } else if (isRetentionQuery(querySource) && hasBreakdownFilter(querySource.breakdownFilter)) {+ const breakdownType = querySource.breakdownFilter.breakdown_type || 'event'+ // Retention results carry breakdown_value directly. There is no dataset-key helper+ // like trends/funnels have, because retention has no resultCustomizations whose+ // persisted keys the extraction would need to stay in sync with.+ return (+ tile.insight?.result?.map((result: any): BreakdownValueAndType | null => {+ const breakdownValue = normalizeBreakdownValue(result.breakdown_value)+ return breakdownValue == null ? null : { breakdownValue, breakdownType }+ }) || []+ )}return []}diff --git a/frontend/src/scenes/retention/retentionGraphLogic.test.ts b/frontend/src/scenes/retention/retentionGraphLogic.test.tsnew file mode 100644index 000000000000..9238fcf5e12b--- /dev/null+++ b/frontend/src/scenes/retention/retentionGraphLogic.test.ts@@ -0,0 +1,133 @@+import { expectLogic } from 'kea-test-utils'++import { dataThemeLogic } from 'lib/logic/dataThemeLogic'+import { BREAKDOWN_OTHER_DISPLAY, BREAKDOWN_OTHER_STRING_LABEL } from 'scenes/insights/utils'+import { teamLogic } from 'scenes/teamLogic'++import { useMocks } from '~/mocks/jest'+import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'+import { DataNode, NodeKind, RetentionQuery } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'+import { InsightLogicProps, InsightModel, RetentionPeriod } from '~/types'++import { retentionGraphLogic } from './retentionGraphLogic'+import { retentionLogic } from './retentionLogic'++const insightProps: InsightLogicProps = {+ dashboardItemId: undefined,+}++const cohortRow = (date: string, breakdownValue?: string | number | null): Record<string, any> => ({+ date,+ label: 'Day 0',+ values: [{ count: 100 }, { count: 50 }],+ ...(breakdownValue === undefined ? {} : { breakdown_value: breakdownValue }),+})++const breakdownQuery: RetentionQuery = {+ kind: NodeKind.RetentionQuery,+ retentionFilter: { period: RetentionPeriod.Day },+ breakdownFilter: { breakdown: '$browser', breakdown_type: 'event' },+}++const breakdownRows = [+ cohortRow('2024-01-01T00:00:00Z', 'Chrome'),+ cohortRow('2024-01-02T00:00:00Z', 'Chrome'),+ cohortRow('2024-01-01T00:00:00Z', BREAKDOWN_OTHER_STRING_LABEL),+]++let logic: ReturnType<typeof retentionGraphLogic.build>+let builtRetentionLogic: ReturnType<typeof retentionLogic.build>++describe('retentionGraphLogic', () => {+ beforeEach(async () => {+ useMocks({+ get: {+ '/api/projects/:team_id/cohorts/': { count: 0, results: [] },+ '/api/environments/:team_id/data_color_themes/': [],+ },+ })+ initKeaTests(false)+ teamLogic.mount()+ await expectLogic(teamLogic).toFinishAllListeners()++ dataThemeLogic.mount()+ dataThemeLogic.actions.setThemes([+ { id: 1, name: 'Test theme', colors: ['#111111', '#222222', '#333333'], is_global: true },+ ])++ dataNodeLogic({ key: 'InsightViz.new', query: {} as DataNode }).mount()++ builtRetentionLogic = retentionLogic(insightProps)+ builtRetentionLogic.mount()++ logic = retentionGraphLogic(insightProps)+ logic.mount()+ })++ async function loadResults(query: RetentionQuery, result: Record<string, any>[]): Promise<void> {+ await expectLogic(logic, () => {+ builtRetentionLogic.actions.updateQuerySource(query)+ // Rebuilding with the query as props mirrors how InsightViz passes the source query+ // down; retentionLogic.results gates on it. cachedResults set the response without+ // a network round-trip.+ dataNodeLogic({+ key: 'InsightViz.new',+ query: query as DataNode,+ cachedResults: { result } as Partial<InsightModel>,+ })+ }).toFinishAllListeners()+ }++ it('mean-per-breakdown series carry the raw breakdown value alongside the display label', async () => {+ await loadResults(breakdownQuery, breakdownRows)++ expect(logic.values.shouldShowMeanPerBreakdown).toBe(true)+ expect(logic.values.filteredTrendSeries.map((s) => [s.breakdown_value, s.rawBreakdownValue])).toEqual([+ ['Chrome', 'Chrome'],+ [BREAKDOWN_OTHER_DISPLAY, BREAKDOWN_OTHER_STRING_LABEL],+ ])+ })++ it('interval view series carry the raw breakdown value alongside the display label', async () => {+ await loadResults(+ {+ ...breakdownQuery,+ retentionFilter: { period: RetentionPeriod.Day, selectedInterval: 1 },+ },+ breakdownRows+ )++ expect(logic.values.filteredTrendSeries.map((s) => [s.breakdown_value, s.rawBreakdownValue])).toEqual([+ ['Chrome', 'Chrome'],+ [BREAKDOWN_OTHER_DISPLAY, BREAKDOWN_OTHER_STRING_LABEL],+ ])+ })++ it('per-cohort series keep rawBreakdownValue unset when filtered to one breakdown value', async () => {+ await loadResults(breakdownQuery, breakdownRows)++ builtRetentionLogic.actions.setSelectedBreakdownValue('Chrome')++ const series = logic.values.filteredTrendSeries+ expect(series).toHaveLength(2)+ // One series per cohort here: matching them all to the same breakdown color config+ // would color every cohort identically, so the raw value must not leak through.+ expect(series.map((s) => s.rawBreakdownValue)).toEqual([undefined, undefined])+ })++ it('getRetentionColorToken falls back to positional tokens and wraps at the theme size', () => {+ const token = (rawBreakdownValue: string | null, seriesIndex: number): string | null =>+ builtRetentionLogic.values.getRetentionColorToken(rawBreakdownValue, seriesIndex)[1]++ expect([token(null, 0), token(null, 1), token(null, 2), token(null, 3)]).toEqual([+ 'preset-1',+ 'preset-2',+ 'preset-3',+ 'preset-1',+ ])+ // Without a mounted dashboard there is no override, so a breakdown value is still positional+ expect(token('Chrome', 1)).toBe('preset-2')+ expect(builtRetentionLogic.values.getRetentionColor('Chrome', 1)).toBe('#222222')+ })+})diff --git a/frontend/src/scenes/retention/retentionGraphLogic.ts b/frontend/src/scenes/retention/retentionGraphLogic.tsindex a44a2c57d3bf..a94c9f06b881 100644--- a/frontend/src/scenes/retention/retentionGraphLogic.ts+++ b/frontend/src/scenes/retention/retentionGraphLogic.ts@@ -43,6 +43,10 @@ export interface retentionGraphLogicValues {retentionFilter: RetentionFilter | null // insightVizDataLogicbreakdownDisplayNames: Record<string, string> // retentionLogicfilteredResults: ProcessedRetentionPayload[] // retentionLogic+ getRetentionColor: (+ rawBreakdownValue: number | string | null | undefined,+ seriesIndex: number+ ) => string | undefined // retentionLogichasValidBreakdown: boolean // retentionLogicisPropertyValueAggregation: boolean // retentionLogicresults: ProcessedRetentionPayload[] // retentionLogic@@ -139,6 +143,7 @@ export const retentionGraphLogic = kea<retentionGraphLogicType>(['retentionMeans','breakdownDisplayNames','isPropertyValueAggregation',+ 'getRetentionColor',],teamLogic,['timezone'],@@ -167,6 +172,10 @@ export const retentionGraphLogic = kea<retentionGraphLogicType>([isPropertyValueAggregation ? (value.aggregation_value ?? 0) : value.percentage),index: datasetIndex,+ // Per-cohort series are colored positionally, even when filtered to a single+ // breakdown value: matching them all to one breakdown color config would make+ // the cohorts indistinguishable. Clear the value the spread copied over.+ rawBreakdownValue: undefined,}})},@@ -214,6 +223,7 @@ export const retentionGraphLogic = kea<retentionGraphLogicType>([labels: string[]days: string[]breakdownValue?: string | number | boolean | null+ rawBreakdownValue?: string | number | null}>()@@ -230,6 +240,7 @@ export const retentionGraphLogic = kea<retentionGraphLogicType>([labels: [],days: [],breakdownValue: cohort.breakdown_value,+ rawBreakdownValue: cohort.rawBreakdownValue,})}@@ -246,6 +257,7 @@ export const retentionGraphLogic = kea<retentionGraphLogicType>([days: group.days,labels: group.labels,breakdown_value: hasValidBreakdown ? getDisplayLabel(group.breakdownValue) : undefined,+ rawBreakdownValue: hasValidBreakdown ? (group.rawBreakdownValue ?? null) : undefined,index,}})@@ -355,6 +367,7 @@ export const retentionGraphLogic = kea<retentionGraphLogicType>([meanSeries.push({breakdown_value: displayLabel,+ rawBreakdownValue: meanData.rawBreakdownValue,data: isPropertyValueAggregation ? meanData.meanValues : meanData.meanPercentages,days: days,labels: days,diff --git a/frontend/src/scenes/retention/retentionLogic.ts b/frontend/src/scenes/retention/retentionLogic.tsindex cb6aa99754d5..1fb75a3ebdba 100644--- a/frontend/src/scenes/retention/retentionLogic.ts+++ b/frontend/src/scenes/retention/retentionLogic.ts@@ -1,11 +1,15 @@import { mean, sum } from 'd3'import { MakeLogicType, actions, connect, events, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { DataColorTheme, DataColorToken } from 'lib/colors'import { CUSTOM_OPTION_KEY } from 'lib/components/DateFilter/types'import { FEATURE_FLAGS } from 'lib/constants'import { dayjs } from 'lib/dayjs'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { formatDateRange } from 'lib/utils/datetime'+import { BreakdownColorConfig, findBreakdownColorConfig } from 'scenes/dashboard/dashboardBreakdownColors'+import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'+import { getColorFromToken } from 'scenes/dataThemeLogic'import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'import { keyForInsightLogicProps } from 'scenes/insights/sharedUtils'import { BREAKDOWN_OTHER_DISPLAY, BREAKDOWN_OTHER_STRING_LABEL, formatBreakdownLabel } from 'scenes/insights/utils'@@ -43,6 +47,9 @@ export const MAX_BRACKETS = 30// Define a type for the output of the retentionMeans selectorexport interface MeanRetentionValue {label: string | number | null+ /** Raw breakdown_value of the group's rows (pre display mapping), for matching+ * dashboard breakdown color configs. Null for the overall and empty groups. */+ rawBreakdownValue: string | number | nullmeanPercentages: number[]meanValues: number[]totalCohortSize: number@@ -55,6 +62,7 @@ export interface retentionLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogicbreakdownFilter: BreakdownFilter | null | undefined // insightVizDataLogicdateRange: DateRange | null | undefined // insightVizDataLogic+ getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null // insightVizDataLogicinsightData: Record<string, any> // insightVizDataLogicinsightQuery: DataNode<Record<string, any>> // insightVizDataLogicquerySource:@@ -73,6 +81,14 @@ export interface retentionLogicValues {breakdownValues: (number | string | null | undefined)[]dateMappings: DateMappingOption[]filteredResults: ProcessedRetentionPayload[]+ getRetentionColor: (+ rawBreakdownValue: number | string | null | undefined,+ seriesIndex: number+ ) => string | undefined+ getRetentionColorToken: (+ rawBreakdownValue: number | string | null | undefined,+ seriesIndex: number+ ) => [DataColorTheme | null, DataColorToken | null]hasValidBreakdown: booleanisPropertyValueAggregation: booleanisRetentionDWHEnabled: boolean@@ -150,6 +166,31 @@ export interface retentionLogicMeta {breakdownFilter: BreakdownFilter | null | undefined,cohortsById: Partial<Record<number | string, CohortType>>) => Record<string, string>+ getRetentionColorToken: (+ getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null, // insightVizDataLogic+ breakdownFilter: BreakdownFilter | null | undefined,+ querySource:+ | FunnelsQuery+ | LifecycleQuery+ | PathsQuery+ | RetentionQuery+ | StickinessQuery+ | TrendsQuery+ | WebOverviewQuery+ | WebStatsTableQuery+ | null,+ arg: BreakdownColorConfig[] | null,+ arg2: DataColorTheme | null+ ) => (+ rawBreakdownValue: number | string | null | undefined,+ seriesIndex: number+ ) => [DataColorTheme | null, DataColorToken | null]+ getRetentionColor: (+ getRetentionColorToken: (+ rawBreakdownValue: number | string | null | undefined,+ seriesIndex: number+ ) => [DataColorTheme | null, DataColorToken | null]+ ) => (rawBreakdownValue: number | string | null | undefined, seriesIndex: number) => string | undefined}}@@ -167,7 +208,15 @@ export const retentionLogic = kea<retentionLogicType>([connect((props: InsightLogicProps) => ({values: [insightVizDataLogic(props),- ['breakdownFilter', 'dateRange', 'insightQuery', 'insightData', 'querySource', 'retentionFilter'],+ [+ 'breakdownFilter',+ 'dateRange',+ 'insightQuery',+ 'insightData',+ 'querySource',+ 'retentionFilter',+ 'getTheme',+ ],teamLogic,['timezone'],featureFlagLogic,@@ -274,7 +323,7 @@ export const retentionLogic = kea<retentionLogicType>([},],}),- selectors({+ selectors(({ props }) => ({hasValidBreakdown: [(s) => [s.breakdownFilter],(breakdownFilter: null | import('~/queries/schema/schema-general').BreakdownFilter | undefined) =>@@ -340,6 +389,9 @@ export const retentionLogic = kea<retentionLogicType>([result.breakdown_value === BREAKDOWN_OTHER_STRING_LABEL? BREAKDOWN_OTHER_DISPLAY: result.breakdown_value,+ // Dashboard breakdown color configs store the raw value, so keep it+ // alongside the display-mapped one.+ rawBreakdownValue: result.breakdown_value ?? null,values: result.values.filter((value) => !value.isFuture),}))},@@ -453,6 +505,9 @@ export const retentionLogic = kea<retentionLogicType>([means[breakdownKey] = {label: label,+ rawBreakdownValue: isOverallGroupWithoutBreakdown+ ? null+ : (breakdownRows[0]?.rawBreakdownValue ?? null),meanPercentages: meanPercentagesForBreakdown,meanValues: meanValuesForBreakdown,totalCohortSize: totalCohortSizeForGroup,@@ -553,7 +608,93 @@ export const retentionLogic = kea<retentionLogicType>([)},],- }),++ getRetentionColorToken: [+ (s) => [+ s.getTheme,+ s.breakdownFilter,+ s.querySource,+ // The dashboard's colors live in a different logic, so they must be selector+ // inputs rather than reads inside the returned function: the charts memoize+ // series on this function's identity, which only changes when inputs do.+ () =>+ props.dashboardId != null+ ? (dashboardLogic.findMounted({ id: props.dashboardId })?.values.effectiveBreakdownColors ??+ null)+ : null,+ () =>+ props.dashboardId != null+ ? (dashboardLogic.findMounted({ id: props.dashboardId })?.values.dataColorTheme ?? null)+ : null,+ ],+ (+ getTheme: (themeId: number | string | null | undefined) => DataColorTheme | null,+ breakdownFilter: BreakdownFilter | null | undefined,+ querySource:+ | FunnelsQuery+ | LifecycleQuery+ | PathsQuery+ | RetentionQuery+ | StickinessQuery+ | TrendsQuery+ | WebOverviewQuery+ | WebStatsTableQuery+ | null,+ dashboardBreakdownColors: BreakdownColorConfig[] | null,+ dashboardDataColorTheme: DataColorTheme | null+ ) => {+ return (+ rawBreakdownValue: string | number | null | undefined,+ seriesIndex: number+ ): [DataColorTheme | null, DataColorToken | null] => {+ // dashboard color overrides+ const colorOverride = findBreakdownColorConfig(+ dashboardBreakdownColors,+ rawBreakdownValue,+ breakdownFilter?.breakdown_type+ )++ if (colorOverride?.colorToken) {+ // use the dashboard theme, or fallback to the default theme+ return [dashboardDataColorTheme || getTheme(undefined), colorOverride.colorToken]+ }++ // use the dashboard theme, or fallback to the insight theme, or the default theme+ const theme =+ dashboardDataColorTheme ||+ getTheme(+ querySource && 'dataColorTheme' in querySource ? querySource.dataColorTheme : undefined+ )+ if (!theme) {+ return [null, null]+ }++ // retention has no resultCustomizations, so the fallback is purely positional+ return [theme, `preset-${(seriesIndex % Object.keys(theme).length) + 1}` as DataColorToken]+ }+ },+ ],+ getRetentionColor: [+ (s) => [s.getRetentionColorToken],+ (+ getRetentionColorToken: (+ rawBreakdownValue: string | number | null | undefined,+ seriesIndex: number+ ) => [DataColorTheme | null, DataColorToken | null]+ ) => {+ return (+ rawBreakdownValue: string | number | null | undefined,+ seriesIndex: number+ ): string | undefined => {+ const [colorTheme, colorToken] = getRetentionColorToken(rawBreakdownValue, seriesIndex)+ // No theme means themes haven't loaded yet. That's a global condition (all+ // series or none), so leaving the color undefined lets the chart's own+ // palette cover the gap instead of flashing black.+ return colorTheme && colorToken ? getColorFromToken(colorTheme, colorToken) : undefined+ }+ },+ ],+ })),events(({ actions, values }) => ({afterMount: () => {const brackets = values.retentionFilter?.retentionCustomBracketsdiff --git a/frontend/src/scenes/retention/types.ts b/frontend/src/scenes/retention/types.tsindex 8ae62faa3236..dbf5cc4e406d 100644--- a/frontend/src/scenes/retention/types.ts+++ b/frontend/src/scenes/retention/types.ts@@ -20,6 +20,9 @@ export interface ProcessedRetentionPayload {people_url: stringvalues: ProcessedRetentionValue[]breakdown_value?: string | number | null+ /** The result's breakdown_value as returned by the query, before any display mapping+ * (e.g. the raw "other" sentinel). Used to match dashboard breakdown color configs. */+ rawBreakdownValue?: string | number | null}export interface RetentionTableRow {@@ -36,6 +39,10 @@ export interface RetentionTrendPayload {labels: string[]index: numberbreakdown_value?: string | number | null+ /** Set only when the series represents a single breakdown value (mean-per-breakdown and+ * breakdown interval views). Unlike breakdown_value, which holds the display label there,+ * this keeps the raw value so dashboard breakdown color configs can match it. */+ rawBreakdownValue?: string | number | null}export interface RetentionTablePeoplePayload {diff --git a/products/product_analytics/frontend/insights/retention/RetentionBarChart/RetentionBarChart.tsx b/products/product_analytics/frontend/insights/retention/RetentionBarChart/RetentionBarChart.tsxindex 9c0a45e7d73c..90cc1d17b0eb 100644--- a/products/product_analytics/frontend/insights/retention/RetentionBarChart/RetentionBarChart.tsx+++ b/products/product_analytics/frontend/insights/retention/RetentionBarChart/RetentionBarChart.tsx@@ -61,6 +61,7 @@ export function RetentionBarChart({ inSharedMode = false }: RetentionBarChartProlabelGroupType,shouldShowMeanPerBreakdown,xAxisLabels,+ getRetentionColor,} = useValues(retentionGraphLogic(insightProps))const { openModal } = useActions(retentionModalLogic(insightProps))const { aggregationLabel } = useValues(groupsModel)@@ -77,8 +78,9 @@ export function RetentionBarChart({ inSharedMode = false }: RetentionBarChartPro() =>buildRetentionSeries(filteredTrendSeries as RetentionTrendSeriesEntry[], {isIntervalView,+ getColor: (entry, index) => getRetentionColor(entry.rawBreakdownValue, index),}),- [filteredTrendSeries, isIntervalView]+ [filteredTrendSeries, isIntervalView, getRetentionColor])const groupTypeLabel = resolveGroupTypeLabel(labelGroupType, aggregationLabel)diff --git a/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsx b/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsxindex 16259105cf38..de1cd8207e7e 100644--- a/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsx+++ b/products/product_analytics/frontend/insights/retention/RetentionLineChart/RetentionLineChart.tsx@@ -64,6 +64,7 @@ export function RetentionLineChart({ inSharedMode = false }: RetentionLineChartPshouldShowMeanPerBreakdown,showTrendLines,xAxisLabels,+ getRetentionColor,} = useValues(retentionGraphLogic(insightProps))const { openModal } = useActions(retentionModalLogic(insightProps))const { aggregationLabel } = useValues(groupsModel)@@ -80,8 +81,9 @@ export function RetentionLineChart({ inSharedMode = false }: RetentionLineChartPbuildRetentionSeries(filteredTrendSeries as RetentionTrendSeriesEntry[], {incompletenessOffsetFromEnd,isIntervalView,+ getColor: (entry, index) => getRetentionColor(entry.rawBreakdownValue, index),}),- [filteredTrendSeries, incompletenessOffsetFromEnd, isIntervalView]+ [filteredTrendSeries, incompletenessOffsetFromEnd, isIntervalView, getRetentionColor])const groupTypeLabel = resolveGroupTypeLabel(labelGroupType, aggregationLabel)diff --git a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.ts b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.tsindex 9cfe13d36496..48141ab2f756 100644--- a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.test.ts@@ -80,6 +80,25 @@ describe('retentionChartTransforms', () => {expect(series[0].meta?.rowIndex).toBe(0)})+ it('colors series through getColor by array position, and leaves color unset without it', () => {+ // Payload indices deliberately differ from array positions: colors must follow the+ // array position, matching the chart's own colors[i % len] fallback, or explicit and+ // fallback-colored series could collide.+ const entries = [+ makeEntry({ index: 7, rawBreakdownValue: 'Chrome' }),+ makeEntry({ index: 3, rawBreakdownValue: null }),+ ]++ const series = buildRetentionSeries(entries, {+ isIntervalView: false,+ getColor: (entry, index) => (entry.rawBreakdownValue === 'Chrome' ? '#ff0000' : `position-${index}`),+ })+ expect(series.map((s) => s.color)).toEqual(['#ff0000', 'position-1'])++ const uncolored = buildRetentionSeries(entries, { isIntervalView: false })+ expect(uncolored.map((s) => s.color)).toEqual([undefined, undefined])+ })+it.each<[string, Partial<RetentionTrendSeriesEntry>, string]>([['breakdown value wins over the cohort label',diff --git a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.tsindex d4384c7ee3f6..73c54c2645e4 100644--- a/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts+++ b/products/product_analytics/frontend/insights/retention/shared/retentionChartTransforms.ts@@ -23,6 +23,7 @@ export interface RetentionResultLike {labels?: string[]index?: numberbreakdown_value?: string | number | null+ rawBreakdownValue?: string | number | null}// `retentionGraphLogic.trendSeries` spreads `cohortRetention` onto each entry, so the@@ -44,6 +45,11 @@ export interface BuildRetentionSeriesOpts {/** True when an interval is selected (x-axis is cohorts, not interval offsets).* In this layout the partial-stroke "in-progress" segment doesn't apply per-series. */isIntervalView: boolean+ /** Explicit per-series color; `index` is the array position, matching the chart's own+ * `colors[i % len]` fallback. Left undefined (callback absent or returning undefined),+ * the chart theme palette applies. A callback rather than resolved colors keeps this+ * module free of `~/`/`scenes/` deps for the MCP bundle. */+ getColor?: (entry: RetentionTrendSeriesEntry, index: number) => string | undefined}export function buildRetentionSeries(@@ -66,6 +72,7 @@ export function buildRetentionSeries(key: `retention-${rowIndex}`,label,data: s.data,+ color: opts.getColor?.(s, i),meta: {rowIndex,breakdown_value: s.breakdown_value,