:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): render trends time-series bar with quill (#62307)
Sam Penningtonef0720ff689d
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 483ac83db4e4..0937572f02d6 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -589,7 +589,7 @@ snapshots:components-hogcharts-linechart--error-boundary--light:hash: v1.k794b7964.71c1966fb319e455c7d712cd4a480e99ea73e66b04d72d4d1fe4222b058a5a3e.A2RMx3ED_wk_NM0l603i9XWa8hTv5r9JQgHOT5M7L9Ucomponents-hogcharts-linechart--hovering-interior--dark:- hash: v1.k794b7964.106a98b78fdf3d33e9945449c237d568674bb73e6cac2824b068d9dde18f8eb8.IiK8CXDqFcxbK38JcDZ2VvsvJC_hMF4CfeOCTALU61M+ hash: v1.k794b7964.7b5e5a16e1fac1241b49b2d880793b3553b34934435876aaceeacda4fa09b91e.Cxt0M7OEz9iyP74zK0MDhDEXLQ1D_32BpfRJ6IgtZ-wcomponents-hogcharts-linechart--hovering-interior--light:hash: v1.k794b7964.fbdce955d57f7fc414239a7dc502951925a647a510f59307b273a87a68acaa0a.tS4JZrw3ECahuMoFYTO3xoEJ89UQ84lFgvXFTKGwMNAcomponents-hogcharts-linechart--hovering-multi-series--dark:@@ -597,7 +597,7 @@ snapshots:components-hogcharts-linechart--hovering-multi-series--light:hash: v1.k794b7964.2fa5cdb17438c5d62f6b5c075c8160df3cc4c197754fe78c0bf722cd575b0dca.92ma-HCbFCtCf_jrLu2ntgzLy0g843soMAf-qaCna-Ecomponents-hogcharts-linechart--hovering-over-aux-series--dark:- hash: v1.k794b7964.1381975ad1f3cd6f0bd026ed40e2cdbb4d2f373af40565d3e04b681767987402.4ZDmXP-Pet9NoUXCH9u5N9IYRT4kiX_tBklnhDqz7TU+ hash: v1.k794b7964.34f8c3bb1756c1d58721760da0abd6e0f3aae32d8f206283b23a4dbaa3d42bee.chKDgJYsrkvrNeueP4OsA5rUMHDLiYfAmCOM5-3mP1Icomponents-hogcharts-linechart--hovering-over-aux-series--light:hash: v1.k794b7964.4c84ad5286c9fcbe5e781d8b33a8d0e7dc60b8f9743b64a5da4d4e01a54f0339.DXXeFCIu41B9QbBUxA8mdzHNLFZLLHQpZHReBIy9xwQcomponents-hogcharts-linechart--in-progress-tail--dark:@@ -3848,6 +3848,8 @@ snapshots:hash: v1.k794b7964.466f26e9748bf36e37c3b01368ede6314529acc9de022545d2d7732fd27b9876.UBFF_lMm5lyhQHZ67NejD1gwBIUG40R24So4yyXge2Imcp-apps-trends--single-series--light:hash: v1.k794b7964.6a55c4fe9baa6788afe66f17d1a51caca5fa214e78d69e59f0992df68cd4895b.PHWgg1x5WWU8CDiukV2HjALQjNF5op7TM-mF7vIgEDM+ mcp-apps-trends--time-series-bar--light:+ hash: v1.k794b7964.8ad80af6fb74db7437730153bfd2280a8a97ca815e8c82fbaf406f63999ca827.n7CeEcpzcj5mEDP9AFE6f4GslpN6pF7RUzFq5rzTjgQmcp-apps-workflows--active--light:hash: v1.k794b7964.ad71858e2dc5a45e3d81bb38d46ad3bbe2dea9c152b625fbbf93117a27e624ca.Z4AVu3aic8bdKuv98SD1V1ZqQXsxPwGX2mZl3cL31bsmcp-apps-workflows--archived--light:diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.tsindex ebbac2e0a8bb..00a0a03983c2 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.test.ts@@ -4,6 +4,7 @@ import type { CurrencyCode, GoalLine as SchemaGoalLine, TrendsFilter } from '~/qimport {buildTrendsBarAggregatedSeries,+ buildTrendsBarChartModel,buildTrendsBarTimeSeries,buildTrendsBarTimeSeriesConfig,type TrendsBarResultLike,@@ -40,6 +41,17 @@ describe('buildTrendsBarTimeSeries', () => {})+ // The inlined hex dimming must match lib/utils' hexToRGBA for valid hex (incl. 3-digit shorthand);+ // a non-hex color is passed through unchanged (the one intentional divergence from hexToRGBA).+ it.each([+ { base: '#ff0000', expected: hexToRGBA('#ff0000', 0.5) },+ { base: '#f00', expected: hexToRGBA('#f00', 0.5) },+ { base: 'not-a-hex', expected: 'not-a-hex' },+ ])('dims a compare-previous bar for $base', ({ base, expected }) => {+ const series = buildTrendsBarTimeSeries([makeResult({ compare_label: 'previous' })], { getColor: () => base })+ expect(series[0].color).toBe(expected)+ })+it('marks a series excluded when getHidden returns true', () => {const series = buildTrendsBarTimeSeries([makeResult()], {getColor: () => RED,@@ -343,3 +355,53 @@ describe('buildTrendsBarTimeSeriesConfig', () => {expect(cfg.tooltip).toEqual({ pinnable: true, placement: 'top' })})})++describe('buildTrendsBarChartModel', () => {+ const results: TrendsBarResultLike[] = [+ { id: 'a', label: 'Pageview', data: [1, 2, 3] },+ { id: 'b', label: 'Signup', data: [4, 5, 6] },+ ]++ it('assembles series + config and passes the host labels through', () => {+ const model = buildTrendsBarChartModel(results, {+ getColor: () => RED,+ labels: ['Mon', 'Tue', 'Wed'],+ isPercentStackView: false,+ isGrouped: false,+ })++ expect(model.labels).toEqual(['Mon', 'Tue', 'Wed'])+ expect(model.series.map((s) => s.key)).toEqual(['a', 'b'])+ expect(model.series[0].data).toEqual([1, 2, 3])+ expect(model.series[0].color).toBe(RED)+ expect(model.config.barLayout).toBe('stacked')+ })++ it.each([+ { isGrouped: false, isPercentStackView: false, expected: 'stacked' },+ { isGrouped: true, isPercentStackView: false, expected: 'grouped' },+ { isGrouped: false, isPercentStackView: true, expected: 'percent' },+ { isGrouped: true, isPercentStackView: true, expected: 'percent' },+ ])('maps layout flags to barLayout=$expected', ({ isGrouped, isPercentStackView, expected }) => {+ const model = buildTrendsBarChartModel(results, {+ getColor: () => RED,+ labels: [],+ isGrouped,+ isPercentStackView,+ })+ expect(model.config.barLayout).toBe(expected)+ })++ it('forwards an x-axis tick formatter into the config', () => {+ const model = buildTrendsBarChartModel(results, {+ getColor: () => RED,+ labels: [],+ isPercentStackView: false,+ isGrouped: false,+ xAxisTickFormatter: (value) => `~${value}`,+ })+ const { tickFormatter } = model.config.xAxis!+ expect(tickFormatter).toBeTruthy()+ expect(tickFormatter!('2024-01-01', 0)).toBe('~2024-01-01')+ })+})diff --git a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.tsindex 5f521e7987dc..7a461a78c827 100644--- a/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms.ts@@ -1,14 +1,32 @@import { normalizeAxisLabel } from '@posthog/quill-charts'-import type { Series, TimeSeriesBarChartConfig } from '@posthog/quill-charts'--import { hexToRGBA } from 'lib/utils'-import { COMPARE_PREVIOUS_DIM_OPACITY } from 'scenes/trends/viz/trendsAdapterConstants'--import type { CurrencyCode, GoalLine as SchemaGoalLine, TrendsFilter } from '~/queries/schema/schema-general'-import type { IntervalType } from '~/types'+import type { Series, TimeInterval, TimeSeriesBarChartConfig } from '@posthog/quill-charts'import { schemaGoalLinesToConfigs } from '../shared/goalLinesAdapter'import { buildTrendsYAxisConfig } from '../shared/trendsAxisFormat'+import type { GoalLineLike, YFormatterFields } from '../shared/trendsChartDisplayOptions'++// Compare-against-previous bars render at half opacity so they recede behind the current period.+const COMPARE_PREVIOUS_DIM_OPACITY = 0.5++// Inlined from `lib/utils` so this module stays free of `lib/`/`~/`/`scenes/` deps and compiles in+// the MCP Vite bundle, which only resolves `products/*` and `@posthog/*`. Returns the input unchanged+// if it isn't a 3/6/8-digit hex (callers always pass palette hexes).+function dimHexColor(hex: string, alpha: number): string {+ let h = hex.replace(/^#/, '')+ if (h.length === 3 || h.length === 4) {+ h = h+ .split('')+ .map((char) => char + char)+ .join('')+ }+ if (h.length !== 6 && h.length !== 8) {+ return hex+ }+ const r = parseInt(h.slice(0, 2), 16)+ const g = parseInt(h.slice(2, 4), 16)+ const b = parseInt(h.slice(4, 6), 16)+ return `rgba(${r},${g},${b},${alpha})`+}// Shape both IndexedTrendResult (kea) and TrendsResultItem (MCP) satisfy.export interface TrendsBarResultLike {@@ -48,7 +66,7 @@ function resolveBarColor<R extends TrendsBarResultLike, M = unknown>(opts: BuildTrendsBarSeriesOpts<R, M>): string {const baseColor = opts.getColor(r, index)- return r.compare_label === 'previous' ? hexToRGBA(baseColor, COMPARE_PREVIOUS_DIM_OPACITY) : baseColor+ return r.compare_label === 'previous' ? dimHexColor(baseColor, COMPARE_PREVIOUS_DIM_OPACITY) : baseColor}function buildMainTrendsBarSeries<R extends TrendsBarResultLike, M = unknown>(@@ -78,17 +96,20 @@ export function buildTrendsBarTimeSeries<R extends TrendsBarResultLike, M = unkn}export interface BuildTrendsBarTimeSeriesConfigOpts {- trendsFilter?: TrendsFilter | null- baseCurrency?: CurrencyCode+ trendsFilter?: YFormatterFields | null+ baseCurrency?: stringisPercentStackView: booleanisGrouped: booleanyAxisScaleType?: string | null- interval?: IntervalType | null+ interval?: TimeInterval | nulltimezone?: stringallDays?: string[]xAxisLabel?: string | nullyAxisLabel?: string | null- goalLines?: SchemaGoalLine[] | null+ // Explicit x-axis tick formatter — used by hosts (e.g. MCP) that have label strings but no+ // interval/timezone for the auto date formatter. Mirrors the line config.+ xAxisTickFormatter?: (value: string, index: number) => string | null+ goalLines?: GoalLineLike[] | nullvalueLabels?: TimeSeriesBarChartConfig['valueLabels']tooltip?: TimeSeriesBarChartConfig['tooltip']}@@ -105,6 +126,7 @@ export function buildTrendsBarTimeSeriesConfig(opts: BuildTrendsBarTimeSeriesContimezone: opts.timezone,interval: opts.interval ?? 'day',allDays: opts.allDays ?? [],+ tickFormatter: opts.xAxisTickFormatter,},yAxis: {...yAxis,@@ -123,6 +145,38 @@ export function buildTrendsBarTimeSeriesConfig(opts: BuildTrendsBarTimeSeriesCon/** Separator between the series id and compare label in synthetic stacked-mode band keys. */const BAND_KEY_SEP = '\u001f'+export interface BuildTrendsBarChartModelOpts<+ R extends TrendsBarResultLike,+ M = unknown,+> extends BuildTrendsBarTimeSeriesConfigOpts {+ /** Final x-axis labels (the host formats them — kea dates vs the MCP `formatDate`). */+ labels: string[]+ getColor: (r: R, index: number) => string+ getHidden?: (r: R, index: number) => boolean+ buildMeta?: (r: R, index: number) => M+}++export interface TrendsBarChartModel<M = unknown> {+ series: Series<M>[]+ labels: string[]+ config: TimeSeriesBarChartConfig+}++/** Assembles the time-series bar chart model (series + config) in one call so the MCP visualizer+ * builds the same series + config the web container assembles piecewise. */+export function buildTrendsBarChartModel<R extends TrendsBarResultLike, M = unknown>(+ results: R[],+ opts: BuildTrendsBarChartModelOpts<R, M>+): TrendsBarChartModel<M> {+ const series = buildTrendsBarTimeSeries<R, M>(results, {+ getColor: opts.getColor,+ getHidden: opts.getHidden,+ buildMeta: opts.buildMeta,+ })+ const config = buildTrendsBarTimeSeriesConfig(opts)+ return { series, labels: opts.labels, config }+}+export function buildTrendsBarAggregatedSeries<R extends TrendsBarResultLike, M = unknown>(results: R[],opts: BuildTrendsBarAggregatedSeriesOpts<R, M>diff --git a/products/product_analytics/mcp/apps/Trends.stories.tsx b/products/product_analytics/mcp/apps/Trends.stories.tsxindex c3259ae8f698..538d21909347 100644--- a/products/product_analytics/mcp/apps/Trends.stories.tsx+++ b/products/product_analytics/mcp/apps/Trends.stories.tsx@@ -2,9 +2,10 @@ import type { Meta, StoryObj } from '@storybook/react'import type { ReactElement } from 'react'import { McpThemeDecorator } from '@posthog/mcp-ui/storybook/decorator'-import { BarChart, TimeSeriesLineChart } from '@posthog/quill-charts'+import { BarChart, TimeSeriesBarChart, TimeSeriesLineChart } from '@posthog/quill-charts'import type { ChartTheme } from '@posthog/quill-charts'+import { buildTrendsBarChartModel } from '../../frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms'import {buildTrendsBarValueConfig,buildTrendsBarValueSeries,@@ -97,6 +98,35 @@ export const AreaChart: Story = {name: 'Area chart',}+// Renders the line/bar toggle's bar mode the same way the MCP app does: time-series results through+// buildTrendsBarChartModel, then quill's TimeSeriesBarChart.+function TrendsBarChartDemo({ results }: { results: TrendsResultLike[] }): ReactElement {+ const { series, config } = buildTrendsBarChartModel(results, {+ getColor: (_r, i) => colorAt(i),+ labels: DAYS,+ isPercentStackView: false,+ isGrouped: false,+ })+ return (+ // eslint-disable-next-line react/forbid-dom-props+ <div style={{ display: 'flex', flexDirection: 'column', width: 640, height: 300 }}>+ <TimeSeriesBarChart series={series} labels={DAYS} theme={CHART_THEME} config={config} />+ </div>+ )+}++export const TimeSeriesBar: Story = {+ render: () => (+ <TrendsBarChartDemo+ results={[+ { id: 1, label: 'Pageviews', data: [420, 380, 510, 490, 630, 580, 720], days: DAYS },+ { id: 2, label: 'Signups', data: [42, 38, 51, 49, 63, 58, 72], days: DAYS },+ ]}+ />+ ),+ name: 'Time-series bar',+}+// Renders ActionsBarValue the same way the MCP app does: aggregated totals through// buildTrendsBarValueSeries, then quill's BarChart. Fixed pixel size for the same// headless-snapshot reason as the line demo above.diff --git a/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx b/services/mcp/src/ui-apps/components/TrendsVisualizer.tsxindex 08fc31c1c3f6..51eba9d3ddbb 100644--- a/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx+++ b/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx@@ -2,8 +2,9 @@ import { type ReactElement, useState } from 'react'import { emptyStateIllustration } from '@posthog/mcp-ui'import { Empty, EmptyDescription, EmptyHeader, EmptyMedia } from '@posthog/quill'-import { BarChart as BarValueChart, TimeSeriesLineChart } from '@posthog/quill-charts'+import { BarChart as BarValueChart, TimeSeriesBarChart, TimeSeriesLineChart } from '@posthog/quill-charts'+import { buildTrendsBarChartModel } from 'products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms'import {buildTrendsBarValueConfig,buildTrendsBarValueSeries,@@ -13,7 +14,7 @@ import {buildTrendsSeries,} from 'products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms'-import { BarChart, BigNumber, Select, type Series } from './charts'+import { BigNumber, Select } from './charts'import { CHART_THEME, colorAt } from './charts/theme'import type { TrendsResultItem, TrendsVisualizerProps } from './types'import { formatDate, getDisplayType, getSeriesLabel, isBarChart } from './utils'@@ -25,36 +26,7 @@ const CHART_MODE_OPTIONS = [{ value: 'bar' as const, label: 'Bar' },]-function prepareChartData(results: TrendsResultItem[]): {- series: Series[]- labels: string[]- maxValue: number-} {- if (!results || results.length === 0) {- return { series: [], labels: [], maxValue: 0 }- }-- const labels = results[0]?.days || results[0]?.labels || []- let maxValue = 0-- const series = results.map((item, seriesIndex) => {- const data = item.data || []- const points = data.map((value, i) => {- maxValue = Math.max(maxValue, value)- return {- x: i,- y: value,- label: labels[i] || `${i}`,- }- })- return {- label: getSeriesLabel(item, seriesIndex),- points,- }- })-- return { series, labels, maxValue: maxValue || 1 }-}+const TOOLTIP_CONFIG = { pinnable: true, placement: 'top' as const }function calculateTotal(results: TrendsResultItem[]): number {return results.reduce((sum, item) => {@@ -74,9 +46,8 @@ function calculateTotal(results: TrendsResultItem[]): number {export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): ReactElement {const displayType = getDisplayType(query)const [chartMode, setChartMode] = useState<ChartMode>(isBarChart(displayType) ? 'bar' : 'line')- const { series, labels, maxValue } = prepareChartData(results)- if (!results || results.length === 0 || series.length === 0) {+ if (!results || results.length === 0) {return (<Empty><EmptyHeader>@@ -114,26 +85,43 @@ export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): Rea)}- const lineResults = results.map((item, i) => ({+ const labels = results[0]?.days ?? results[0]?.labels ?? []+ const trendResults = results.map((item, i) => ({id: i,label: getSeriesLabel(item, i),data: item.data ?? [],days: item.days,}))-- const lineSeries = buildTrendsSeries(lineResults, {- isArea: displayType === 'ActionsAreaGraph',- getColor: (_, index) => colorAt(index),- })-- const lineConfig = buildTrendsLineTimeSeriesConfig({- results: lineResults,- trendsFilter: query?.trendsFilter,- yAxisLabel: results.length === 1 && results[0] ? getSeriesLabel(results[0], 0) : undefined,- isPercentStackView: false,- showCrosshair: true,- xAxisTickFormatter: (value) => formatDate(value),- })+ const yAxisLabel = results.length === 1 && results[0] ? getSeriesLabel(results[0], 0) : undefined++ // Build only the active mode's chart model — toggling shouldn't recompute the hidden one.+ const renderChart = (): ReactElement => {+ if (chartMode === 'bar') {+ const { series, config } = buildTrendsBarChartModel(trendResults, {+ getColor: (_, index) => colorAt(index),+ labels,+ yAxisLabel,+ isPercentStackView: false,+ isGrouped: false,+ xAxisTickFormatter: (value) => formatDate(value),+ tooltip: TOOLTIP_CONFIG,+ })+ return <TimeSeriesBarChart series={series} labels={labels} theme={CHART_THEME} config={config} />+ }+ const series = buildTrendsSeries(trendResults, {+ isArea: displayType === 'ActionsAreaGraph',+ getColor: (_, index) => colorAt(index),+ })+ const config = buildTrendsLineTimeSeriesConfig({+ results: trendResults,+ trendsFilter: query?.trendsFilter,+ yAxisLabel,+ isPercentStackView: false,+ showCrosshair: true,+ xAxisTickFormatter: (value) => formatDate(value),+ })+ return <TimeSeriesLineChart series={series} labels={labels} theme={CHART_THEME} config={config} />+ }return (<div>@@ -141,18 +129,7 @@ export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): Rea{/* 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={series.length === 1 ? series[0]?.label : undefined}- />- ) : (- <div className="flex flex-col w-full h-[400px]">- <TimeSeriesLineChart series={lineSeries} labels={labels} theme={CHART_THEME} config={lineConfig} />- </div>- )}+ <div className="flex flex-col w-full h-[400px]">{renderChart()}</div></div>)}