:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(insights): use trends line chart in MCP app (#61809)
Sam Pennington018e5ca3c79a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex df46e7030c24..f1fd347c4d41 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -3838,6 +3838,12 @@ snapshots:hash: v1.k794b7964.d74c2774a1e3a73e7d34e0332ef1bcbb3b61a5442b89797447e23f5d56b033c2.qta1-W4_vRyunnAG5t1wzZKyzWUqS54HvnKvfvznYnAmcp-apps-surveys--stats--light:hash: v1.k794b7964.da67b48f277665016d143ea09d4471ca6f01f3b8a6d22e7fe0f3dc51b075e92a.l81wzNlVna0bTrWF2HHg1RkJaB7vXRpAIdMbNylhzCw+ mcp-apps-trends--area-chart--light:+ hash: v1.k794b7964.6ed37783ed84b48f2d648749ffc298bfd71075de834aae5d71f1a3b57dceb307.CP-Rjuy-9M_y2GO4qu462L0uVUqNr5EjDcW5v81BryE+ mcp-apps-trends--multi-series--light:+ hash: v1.k794b7964.466f26e9748bf36e37c3b01368ede6314529acc9de022545d2d7732fd27b9876.UBFF_lMm5lyhQHZ67NejD1gwBIUG40R24So4yyXge2I+ mcp-apps-trends--single-series--light:+ hash: v1.k794b7964.6a55c4fe9baa6788afe66f17d1a51caca5fa214e78d69e59f0992df68cd4895b.PHWgg1x5WWU8CDiukV2HjALQjNF5op7TM-mF7vIgEDMmcp-apps-workflows--active--light:hash: v1.k794b7964.ad71858e2dc5a45e3d81bb38d46ad3bbe2dea9c152b625fbbf93117a27e624ca.Z4AVu3aic8bdKuv98SD1V1ZqQXsxPwGX2mZl3cL31bsmcp-apps-workflows--archived--light:diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsxindex ecd196679041..6573791daf2a 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.tsx@@ -2,15 +2,10 @@ import { useValues } from 'kea'import { useCallback, useMemo } from 'react'import { DEFAULT_Y_AXIS_ID, TimeSeriesLineChart } from '@posthog/quill-charts'-import type {- PointClickData,- Series,- TimeSeriesLineChartConfig,- TooltipConfig,- TooltipContext,-} from '@posthog/quill-charts'+import type { PointClickData, TooltipConfig, TooltipContext } from '@posthog/quill-charts'import { buildTheme } from 'lib/charts/utils/theme'+import { ciRanges } from 'lib/statistics'import { percentage } from 'lib/utils'import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'import { InsightEmptyState } from 'scenes/insights/EmptyStates'@@ -25,6 +20,7 @@ import { themeLogic } from '~/layout/navigation-3000/themeLogic'import { groupsModel } from '~/models/groupsModel'import { InsightVizNode } from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'+import { ChartDisplayType } from '~/types'import { AnnotationsLayer } from '../shared/AnnotationsLayer'import { makeChartErrorHandler } from '../shared/chartErrorHandler'@@ -89,28 +85,6 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineChaindexedResults[0]?.data &&indexedResults.filter((result: IndexedTrendResult) => result.count !== 0).length > 0- const series: Series<TrendsSeriesMeta>[] = useMemo(- () =>- buildTrendsSeries<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {- display: display ?? undefined,- showMultipleYAxes: showMultipleYAxes ?? undefined,- incompletenessOffsetFromEnd,- isStickiness,- getColor: getTrendsColor,- getHidden: getTrendsHidden,- buildMeta: buildTrendsSeriesMeta,- }),- [- indexedResults,- display,- getTrendsColor,- getTrendsHidden,- isStickiness,- incompletenessOffsetFromEnd,- showMultipleYAxes,- ]- )-const valueLabelFormatter = useCallback((value: number) => {// In percent layout the chart computes each segment's share of its band and passes@@ -123,57 +97,6 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha[trendsFilter, isPercentStackView, baseCurrency])- const chartConfig: TimeSeriesLineChartConfig = useMemo(- () =>- buildTrendsLineTimeSeriesConfig({- results: indexedResults ?? [],- trendsFilter,- baseCurrency,- isPercentStackView,- isStickiness,- yAxisScaleType,- interval,- timezone,- allDays: currentPeriodResult?.days ?? [],- xAxisLabel: trendsFilter?.xAxisLabel,- yAxisLabel: trendsFilter?.yAxisLabel,- goalLines,- incompletenessOffsetFromEnd,- getHidden: getTrendsHidden,- showConfidenceIntervals,- confidenceLevel,- showMovingAverage,- movingAverageIntervals,- showTrendLines,- valueLabels: showValuesOnSeries ? { formatter: valueLabelFormatter } : false,- showCrosshair: true,- tooltip: TOOLTIP_CONFIG,- }),- [- indexedResults,- trendsFilter,- baseCurrency,- isPercentStackView,- isStickiness,- yAxisScaleType,- interval,- timezone,- currentPeriodResult?.days,- trendsFilter?.xAxisLabel,- trendsFilter?.yAxisLabel,- goalLines,- incompletenessOffsetFromEnd,- getTrendsHidden,- showConfidenceIntervals,- confidenceLevel,- showMovingAverage,- movingAverageIntervals,- showTrendLines,- showValuesOnSeries,- valueLabelFormatter,- ]- )-const indexByResult = useMemo(() => {const m = new Map<IndexedTrendResult, number>();(indexedResults ?? []).forEach((r, i) => m.set(r, i))@@ -264,6 +187,78 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineCha])+ const series = useMemo(+ () =>+ buildTrendsSeries<IndexedTrendResult, TrendsSeriesMeta>(indexedResults ?? [], {+ isArea: display === ChartDisplayType.ActionsAreaGraph,+ showMultipleYAxes: showMultipleYAxes ?? undefined,+ incompletenessOffsetFromEnd,+ isStickiness,+ getColor: getTrendsColor,+ getHidden: getTrendsHidden,+ buildMeta: buildTrendsSeriesMeta,+ }),+ [+ indexedResults,+ display,+ showMultipleYAxes,+ incompletenessOffsetFromEnd,+ isStickiness,+ getTrendsColor,+ getTrendsHidden,+ ]+ )++ const config = useMemo(+ () =>+ buildTrendsLineTimeSeriesConfig<IndexedTrendResult>({+ results: indexedResults ?? [],+ trendsFilter,+ baseCurrency,+ isPercentStackView,+ isStickiness,+ yAxisScaleType,+ interval,+ timezone,+ allDays: currentPeriodResult?.days ?? [],+ xAxisLabel: trendsFilter?.xAxisLabel,+ yAxisLabel: trendsFilter?.yAxisLabel,+ goalLines,+ incompletenessOffsetFromEnd,+ getHidden: getTrendsHidden,+ showConfidenceIntervals: showConfidenceIntervals ?? undefined,+ confidenceLevel: confidenceLevel ?? undefined,+ ciRanges,+ showMovingAverage: showMovingAverage ?? undefined,+ movingAverageIntervals: movingAverageIntervals ?? undefined,+ showTrendLines: showTrendLines ?? undefined,+ valueLabels: showValuesOnSeries && valueLabelFormatter ? { formatter: valueLabelFormatter } : false,+ showCrosshair: true,+ tooltip: TOOLTIP_CONFIG,+ }),+ [+ indexedResults,+ trendsFilter,+ baseCurrency,+ isPercentStackView,+ isStickiness,+ yAxisScaleType,+ interval,+ timezone,+ currentPeriodResult?.days,+ goalLines,+ incompletenessOffsetFromEnd,+ getTrendsHidden,+ showConfidenceIntervals,+ confidenceLevel,+ showMovingAverage,+ movingAverageIntervals,+ showTrendLines,+ showValuesOnSeries,+ valueLabelFormatter,+ ]+ )+if (!hasData) {return <InsightEmptyState heading={context?.emptyStateHeading} detail={context?.emptyStateDetail} />}@@ -276,7 +271,7 @@ export function TrendsLineChart({ context, inSharedMode = false }: TrendsLineChaseries={series}labels={labels}theme={theme}- config={chartConfig}+ config={config}tooltip={renderTooltip}onPointClick={canHandleClick ? onPointClick : undefined}className="LineGraph"diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.tsindex ae2ef7319d07..bc4bfaa82f6e 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.test.ts@@ -1,9 +1,11 @@import { DEFAULT_Y_AXIS_ID } from '@posthog/quill-charts'import type { TooltipConfig } from '@posthog/quill-charts'-import type { GoalLine as SchemaGoalLine } from '~/queries/schema/schema-general'-import { ChartDisplayType } from '~/types'+import { ciRanges } from 'lib/statistics'+import type { GoalLine as SchemaGoalLine, TrendsFilter as SchemaTrendsFilter } from '~/queries/schema/schema-general'++import type { GoalLineLike, YFormatterFields } from '../shared/trendsChartDisplayOptions'import {buildDerivedConfigs,buildMainTrendsSeries,@@ -13,6 +15,13 @@ import {type TrendsResultLike,} from './trendsChartTransforms'+// The neutral structural types in trendsChartDisplayOptions.ts exist so the shared chart code stays+// free of `~/` schema imports (the MCP Vite bundle can't resolve them). These helpers' return types+// enforce that the real schema types stay assignable to the neutral ones — if a schema field ever+// changes shape, the returns fail to compile and flag the drift here rather than at a distant call site.+const asNeutralGoalLine = (g: SchemaGoalLine): GoalLineLike => g+const asNeutralYFormatterFields = (f: NonNullable<SchemaTrendsFilter>): YFormatterFields => f+const RED = '#ff0000'const makeResult = (overrides: Partial<TrendsResultLike> = {}): TrendsResultLike => ({@@ -23,6 +32,15 @@ const makeResult = (overrides: Partial<TrendsResultLike> = {}): TrendsResultLike})describe('trendsChartTransforms', () => {+ describe('schema type firewall', () => {+ it('keeps the schema GoalLine / TrendsFilter assignable to the neutral structural types', () => {+ // Assignment is checked at compile time by the return types above; the runtime assertions+ // just keep the helpers referenced so they participate in the typecheck.+ expect(asNeutralGoalLine({ label: 'goal', value: 10 })).toMatchObject({ label: 'goal', value: 10 })+ expect(asNeutralYFormatterFields({ decimalPlaces: 2 })).toMatchObject({ decimalPlaces: 2 })+ })+ })+describe('buildMainTrendsSeries', () => {it('builds a single main series with no compare and no in-progress tail', () => {const series = buildMainTrendsSeries(makeResult(), 0, { getColor: () => RED })@@ -71,10 +89,10 @@ describe('trendsChartTransforms', () => {expect(series.stroke).toBeUndefined()})- it('attaches an empty fill object for ActionsAreaGraph display', () => {+ it('attaches an empty fill object when isArea is set', () => {const series = buildMainTrendsSeries(makeResult(), 0, {getColor: () => RED,- display: ChartDisplayType.ActionsAreaGraph,+ isArea: true,})expect(series.fill).toEqual({})})@@ -175,6 +193,7 @@ describe('trendsChartTransforms', () => {const out = buildDerivedConfigs([makeResult({ id: 'a' }), makeResult({ id: 'b' })], {showConfidenceIntervals: true,confidenceLevel: 95,+ ciRanges,})expect(out.confidenceIntervals).toHaveLength(2)expect(out.confidenceIntervals?.[0].seriesKey).toBe('a')@@ -186,11 +205,18 @@ describe('trendsChartTransforms', () => {const explicit = buildDerivedConfigs([makeResult()], {showConfidenceIntervals: true,confidenceLevel: 95,+ ciRanges,})- const defaulted = buildDerivedConfigs([makeResult()], { showConfidenceIntervals: true })+ const defaulted = buildDerivedConfigs([makeResult()], { showConfidenceIntervals: true, ciRanges })expect(defaulted.confidenceIntervals?.[0].lower).toEqual(explicit.confidenceIntervals?.[0].lower)})+ it('omits confidenceIntervals when ciRanges is not provided', () => {+ expect(+ buildDerivedConfigs([makeResult()], { showConfidenceIntervals: true }).confidenceIntervals+ ).toBeUndefined()+ })+it('omits confidenceIntervals when showConfidenceIntervals is false', () => {expect(buildDerivedConfigs([makeResult()], {}).confidenceIntervals).toBeUndefined()})@@ -330,6 +356,7 @@ describe('trendsChartTransforms', () => {goalLines: [{ label: 'goal', value: 10 }] satisfies SchemaGoalLine[],showConfidenceIntervals: true,confidenceLevel: 95,+ ciRanges,valueLabels: false,showCrosshair: true,tooltip: TOOLTIP,@@ -359,15 +386,28 @@ describe('trendsChartTransforms', () => {results,showConfidenceIntervals: true,confidenceLevel,+ ciRanges,})const direct = buildDerivedConfigs(results, {showConfidenceIntervals: true,confidenceLevel,+ ciRanges,})expect(config.confidenceIntervals).toEqual(direct.confidenceIntervals)})+ it('passes xAxisTickFormatter through to the x-axis', () => {+ const tickFormatter = (value: string): string => `tick:${value}`+ const config = buildTrendsLineTimeSeriesConfig({ ...baseOpts, xAxisTickFormatter: tickFormatter })+ expect(config.xAxis?.tickFormatter).toBe(tickFormatter)+ })++ it('leaves the x-axis tick formatter unset when xAxisTickFormatter is omitted', () => {+ const config = buildTrendsLineTimeSeriesConfig({ ...baseOpts })+ expect(config.xAxis?.tickFormatter).toBeUndefined()+ })+describe('valueLabels', () => {it('passes through valueLabels: false unchanged', () => {const config = buildTrendsLineTimeSeriesConfig({diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.tsindex 02749e76e31a..f7f6ba3dfca1 100644--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms.ts@@ -3,18 +3,15 @@ import type {ConfidenceIntervalConfig,MovingAverageConfig,Series,+ TimeInterval,TimeSeriesLineChartConfig,TooltipConfig,TrendLineConfig,} from '@posthog/quill-charts'-import { ciRanges } from 'lib/statistics'--import type { CurrencyCode, GoalLine as SchemaGoalLine, TrendsFilter } from '~/queries/schema/schema-general'-import { ChartDisplayType, type IntervalType } from '~/types'-import { schemaGoalLinesToConfigs } from '../shared/goalLinesAdapter'import { buildTrendsYAxisConfig } from '../shared/trendsAxisFormat'+import type { CiRangesFn, GoalLineLike, YFormatterFields } from '../shared/trendsChartDisplayOptions'// Shape both IndexedTrendResult (kea) and TrendsResultItem (MCP) satisfy.export interface TrendsResultLike {@@ -30,7 +27,8 @@ export interface TrendsResultLike {}export interface BuildTrendsSeriesOpts<R extends TrendsResultLike, M = unknown> {- display?: ChartDisplayType+ /** Area fill under each series (web maps `display === ActionsAreaGraph`). */+ isArea?: booleanshowMultipleYAxes?: boolean// Negative number — index from the end where the in-progress tail begins. Omit to skip.incompletenessOffsetFromEnd?: number@@ -71,7 +69,7 @@ export function buildMainTrendsSeries<R extends TrendsResultLike, M = unknown>(color: opts.getColor(r, index),yAxisId,meta,- fill: opts.display === ChartDisplayType.ActionsAreaGraph ? {} : undefined,+ fill: opts.isArea ? {} : undefined,stroke: dashedFromIndex !== undefined ? { partial: { fromIndex: dashedFromIndex } } : undefined,visibility: excluded ? { excluded: true } : undefined,}@@ -87,6 +85,8 @@ export function buildTrendsSeries<R extends TrendsResultLike, M = unknown>(export interface BuildDerivedConfigsOpts<R extends TrendsResultLike> {showConfidenceIntervals?: booleanconfidenceLevel?: number+ // Injected so the transforms stay free of `lib/statistics`. CI is skipped when omitted.+ ciRanges?: CiRangesFnshowMovingAverage?: booleanmovingAverageIntervals?: numbershowTrendLines?: boolean@@ -111,8 +111,9 @@ export function buildDerivedConfigs<R extends TrendsResultLike>(return out}- if (opts.showConfidenceIntervals) {+ if (opts.showConfidenceIntervals && opts.ciRanges) {const ci = (opts.confidenceLevel ?? 95) / 100+ const ciRanges = opts.ciRangesout.confidenceIntervals = results.map((r) => {const [lower, upper] = ciRanges(r.data, ci)return { seriesKey: String(r.id), lower, upper }@@ -169,22 +170,24 @@ export function buildDerivedConfigs<R extends TrendsResultLike>(export interface BuildTrendsLineTimeSeriesConfigOpts<R extends TrendsResultLike> {results: readonly R[]- trendsFilter?: TrendsFilter | null- baseCurrency?: CurrencyCode+ trendsFilter?: YFormatterFields | null+ baseCurrency?: stringisPercentStackView: booleanisStickiness?: booleanyAxisScaleType?: string | null- interval?: IntervalType | null+ interval?: TimeInterval | nulltimezone?: stringallDays?: string[]xAxisLabel?: string | nullyAxisLabel?: string | null- goalLines?: SchemaGoalLine[] | null+ xAxisTickFormatter?: (value: string, index: number) => string | null+ goalLines?: GoalLineLike[] | nullincompletenessOffsetFromEnd?: numbergetHidden?: (r: R) => booleanshowConfidenceIntervals?: booleanconfidenceLevel?: number+ ciRanges?: CiRangesFnshowMovingAverage?: booleanmovingAverageIntervals?: numbershowTrendLines?: boolean@@ -206,6 +209,7 @@ export function buildTrendsLineTimeSeriesConfig<R extends TrendsResultLike>(const derivedConfigs = buildDerivedConfigs(opts.results, {showConfidenceIntervals: opts.showConfidenceIntervals,confidenceLevel: opts.confidenceLevel,+ ciRanges: opts.ciRanges,showMovingAverage: opts.showMovingAverage,movingAverageIntervals: opts.movingAverageIntervals,showTrendLines: opts.showTrendLines,@@ -219,6 +223,7 @@ export function buildTrendsLineTimeSeriesConfig<R extends TrendsResultLike>(timezone: opts.timezone,interval: opts.interval ?? 'day',allDays: opts.allDays ?? [],+ tickFormatter: opts.xAxisTickFormatter,},yAxis: {...yAxis,diff --git a/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.ts b/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.tsindex e0480e892bcf..685534679a0e 100644--- a/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.ts+++ b/products/product_analytics/frontend/insights/trends/shared/goalLinesAdapter.ts@@ -1,7 +1,7 @@import { buildGoalLineReferenceLines } from '@posthog/quill-charts'import type { GoalLineConfig, ReferenceLineProps, Series } from '@posthog/quill-charts'-import type { GoalLine as SchemaGoalLine } from '~/queries/schema/schema-general'+import type { GoalLineLike as SchemaGoalLine } from './trendsChartDisplayOptions'export function schemaGoalLineToConfig(line: SchemaGoalLine): GoalLineConfig {return {diff --git a/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.ts b/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.tsindex 626d302aa834..f3e99153e313 100644--- a/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.ts+++ b/products/product_analytics/frontend/insights/trends/shared/trendsAxisFormat.ts@@ -1,11 +1,11 @@import type { YAxisConfig, YFormatterConfig } from '@posthog/quill-charts'-import { CurrencyCode, TrendsFilter } from '~/queries/schema/schema-general'+import type { YFormatterFields } from './trendsChartDisplayOptions'export function trendsFilterToYFormatterConfig(- trendsFilter: TrendsFilter | null | undefined,+ trendsFilter: YFormatterFields | null | undefined,isPercentStackView: boolean,- baseCurrency?: CurrencyCode+ baseCurrency?: string): YFormatterConfig {if (isPercentStackView) {// BarChart's percent layout puts the value scale on 0..1, so use the 0..1 formatter.@@ -22,9 +22,9 @@ export function trendsFilterToYFormatterConfig(}export function buildTrendsYAxisConfig(- trendsFilter: TrendsFilter | null | undefined,+ trendsFilter: YFormatterFields | null | undefined,isPercentStackView: boolean,- baseCurrency: CurrencyCode | undefined,+ baseCurrency: string | undefined,extras: { yAxisScaleType?: string | null; showGrid?: boolean } = {}): YAxisConfig {return {diff --git a/products/product_analytics/frontend/insights/trends/shared/trendsChartDisplayOptions.ts b/products/product_analytics/frontend/insights/trends/shared/trendsChartDisplayOptions.tsnew file mode 100644index 000000000000..27d0b63a52c7--- /dev/null+++ b/products/product_analytics/frontend/insights/trends/shared/trendsChartDisplayOptions.ts@@ -0,0 +1,35 @@+import type { YAxisFormat } from '@posthog/quill-charts'++// Dependency-neutral types shared by the web trends container and the MCP UI app when they call+// the trends chart transforms. Deliberately free of `~/` and `lib/` imports (and kea) so they+// compile in the MCP Vite bundle, which only resolves `products/*` and `@posthog/*`.++// Subset of the schema `TrendsFilter` the y-axis formatter reads. Declared structurally rather+// than imported as a deliberate firewall: this file is bundled into the MCP Vite app, which has+// no `~/` resolution, so importing `~/queries/schema/schema-general` would either break the build+// or force the entire generated-schema graph into the MCP typecheck. The real `TrendsFilter` is+// structurally assignable to this (asserted in trendsChartTransforms.test.ts), so web callers pass+// it unchanged.+export interface YFormatterFields {+ aggregationAxisFormat?: YAxisFormat+ aggregationAxisPrefix?: string+ aggregationAxisPostfix?: string+ decimalPlaces?: number+ minDecimalPlaces?: number+}++// Structural mirror of the schema `GoalLine`. Not imported for the same firewall reason as+// `YFormatterFields` above — keeping the MCP bundle free of `~/` schema deps. Assignability from+// the real `GoalLine` is asserted in trendsChartTransforms.test.ts so this can't silently drift.+export interface GoalLineLike {+ label: string+ value: number+ borderColor?: string+ displayLabel?: boolean+ displayIfCrossed?: boolean+ position?: 'start' | 'end'+}++// Confidence-interval helper signature. Injected (rather than imported from `lib/statistics`)+// so the transforms stay free of third-party stats deps the MCP bundle doesn't carry.+export type CiRangesFn = (data: number[], confidence: number) => [number[], number[]]diff --git a/products/product_analytics/mcp/apps/Trends.stories.tsx b/products/product_analytics/mcp/apps/Trends.stories.tsxnew file mode 100644index 000000000000..7c150accb538--- /dev/null+++ b/products/product_analytics/mcp/apps/Trends.stories.tsx@@ -0,0 +1,92 @@+import type { Meta, StoryObj } from '@storybook/react'+import type { ReactElement } from 'react'++import { McpThemeDecorator } from '@posthog/mcp-ui/storybook/decorator'+import { TimeSeriesLineChart } from '@posthog/quill-charts'+import type { ChartTheme } from '@posthog/quill-charts'++import {+ buildTrendsLineTimeSeriesConfig,+ buildTrendsSeries,+ 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 getColor = (_r: TrendsResultLike, i: number): string => CHART_COLORS[i % CHART_COLORS.length]!++const DAYS = ['2025-05-26', '2025-05-27', '2025-05-28', '2025-05-29', '2025-05-30', '2025-05-31', '2025-06-01']++const meta: Meta = {+ title: 'MCP Apps/Trends',+ decorators: [McpThemeDecorator],+ parameters: {+ testOptions: {+ skipDarkMode: true,+ },+ },+}+export default meta++type Story = StoryObj<{}>++// Renders the chart the same way the MCP app does: assemble series + config from results, then hand+// them to quill's TimeSeriesLineChart. Fixed pixel size, not width:100% — the chart sizes its canvas+// off a ResizeObserver, which measures 0 for a percentage width at mount in the headless snapshot+// runner and draws nothing.+function TrendsLineChartDemo({ results, isArea }: { results: TrendsResultLike[]; isArea?: boolean }): ReactElement {+ const series = buildTrendsSeries(results, { isArea, getColor })+ const config = buildTrendsLineTimeSeriesConfig({ results, isPercentStackView: false })+ return (+ // eslint-disable-next-line react/forbid-dom-props+ <div style={{ display: 'flex', flexDirection: 'column', width: 640, height: 300 }}>+ <TimeSeriesLineChart series={series} labels={DAYS} theme={CHART_THEME} config={config} />+ </div>+ )+}++export const SingleSeries: Story = {+ render: () => (+ <TrendsLineChartDemo+ results={[{ id: 1, label: 'Pageviews', data: [420, 380, 510, 490, 630, 580, 720], days: DAYS }]}+ />+ ),+ name: 'Single series',+}++export const MultiSeries: Story = {+ render: () => (+ <TrendsLineChartDemo+ 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 },+ { id: 3, label: 'Purchases', data: [8, 12, 9, 15, 11, 18, 14], days: DAYS },+ ]}+ />+ ),+ name: 'Multi-series',+}++export const AreaChart: Story = {+ render: () => (+ <TrendsLineChartDemo+ 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 },+ ]}+ isArea+ />+ ),+ name: 'Area chart',+}diff --git a/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx b/services/mcp/src/ui-apps/components/TrendsVisualizer.tsxindex cfff5cb3672d..93f43649bdf0 100644--- a/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx+++ b/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx@@ -2,10 +2,17 @@ import { type ReactElement, useState } from 'react'import { emptyStateIllustration } from '@posthog/mcp-ui'import { Empty, EmptyDescription, EmptyHeader, EmptyMedia } from '@posthog/quill'+import { TimeSeriesLineChart } from '@posthog/quill-charts'-import { BarChart, BigNumber, LineChart, Select, type Series } from './charts'+import {+ buildTrendsLineTimeSeriesConfig,+ buildTrendsSeries,+} from 'products/product_analytics/frontend/insights/trends/TrendsLineChart/trendsChartTransforms'++import { BarChart, BigNumber, Select, type Series } from './charts'+import { CHART_COLORS, CHART_THEME } from './charts/theme'import type { TrendsResultItem, TrendsVisualizerProps } from './types'-import { getDisplayType, getSeriesLabel, isBarChart } from './utils'+import { formatDate, getDisplayType, getSeriesLabel, isBarChart } from './utils'type ChartMode = 'line' | 'bar'@@ -82,6 +89,27 @@ export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): Reareturn <BigNumber value={total} label={label} />}+ const lineResults = 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) => CHART_COLORS[index % CHART_COLORS.length]!,+ })++ 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),+ })+return (<div><div className="mb-2 flex justify-end">@@ -96,12 +124,9 @@ export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): ReayAxisLabel={series.length === 1 ? series[0]?.label : undefined}/>) : (- <LineChart- 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>)