Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(mcp): add display options to trends UI app (#63094)

Sam Penningtonaf862d03ed3e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 9fc655367191..652d1ce63754 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4057,17 +4057,17 @@ snapshots:
mcp-apps-surveys--stats--light:
hash: v1.k794b7964.da67b48f277665016d143ea09d4471ca6f01f3b8a6d22e7fe0f3dc51b075e92a.l81wzNlVna0bTrWF2HHg1RkJaB7vXRpAIdMbNylhzCw
mcp-apps-trends--area-chart--light:
- hash: v1.k794b7964.a999deccedf5244f57f6566d676aacadc4ef4c94722473c68df6c554bd87ad3e.ZHF5IaBqQ0FqN3hgvVZVeLUVvbFI4-7lpT-kWfJFcow
+ hash: v1.k794b7964.fea141e4555bf7c84c7df7d28f440f1967cf46eed78c9df63daa191b42156569.osoYKiT_8UiEIKvjzLfRzJxA6gY3cT4eD1g66S-kD5Q
mcp-apps-trends--bar-value-few-series--light:
hash: v1.k794b7964.17235de255bc7d04240957e537b7bc76027c19471525218a28582af1298cd0b3.aA5Dz0x9KR6knEKP4CvKEtRoVS7z6TeKEtTY4_qoML0
mcp-apps-trends--bar-value-many-breakdowns--light:
hash: v1.k794b7964.407f0a6b71b45525e4d45d20e1e6af8f0b7a4345748af552b53df223fbcf576a.GnlWLZvvw78tfb9YT0og22-n8GDKTQs3487BrZiQi_8
mcp-apps-trends--multi-series--light:
- hash: v1.k794b7964.b3592fc2ce95288f8ca5aeccf3333734383d51c13e4bd495cac91285b6d894d1.26ymJ354sVR0hF1sQR3_Py4lPCNLBQI-d5qUWoBinvc
+ hash: v1.k794b7964.de9682bc3d1cacf6198fa053c98657bc296202e4e1e800c98208b0922724cc5d.17c9wz8bYgE3_74LEk8BY5z_gkAp4NZ95x1pkMvip-s
mcp-apps-trends--single-series--light:
- hash: v1.k794b7964.0237d655cb884729a1b01cd8d4bcbc2300e3bb42a6c6bc3f89c70cd206cc91ba.1vqtb4aI3CDKE_XTPD4SOrHfS57ty28sbg1OwXiLcX8
+ hash: v1.k794b7964.6be4744f9c45242fa0945d4cb820c40248b1cb4ec74634d41c11f24f387e87f4.bFA-jAc2ZyaPqEbXMc3jKI6YB2BXTVkJwNpR2jHeMv4
mcp-apps-trends--time-series-bar--light:
- hash: v1.k794b7964.36adcc571f4e889579cad4209857a6f63b5cb350adf7d0ccfeba9510360a689c.Ftkx3aKLXu_zFVXyG3nXcz5Syk9oU3OkOXrDSy2QujE
+ hash: v1.k794b7964.a62cfb1eb173fb526193bf9793266dfcedfec505418b6d168991c01ee3c4fd92.3oRewiRVOH-3Rf4IMK0gYKfvHyLCWoPOt0p6I0CkJ2s
mcp-apps-workflows--active--light:
hash: v1.k794b7964.ad71858e2dc5a45e3d81bb38d46ad3bbe2dea9c152b625fbbf93117a27e624ca.Z4AVu3aic8bdKuv98SD1V1ZqQXsxPwGX2mZl3cL31bs
mcp-apps-workflows--archived--light:
diff --git a/services/mcp/src/ui-apps/components/ChartSettings.tsx b/services/mcp/src/ui-apps/components/ChartSettings.tsx
new file mode 100644
index 000000000000..2f29bab6e09c
--- /dev/null
+++ b/services/mcp/src/ui-apps/components/ChartSettings.tsx
@@ -0,0 +1,136 @@
+import { type ReactElement, useEffect, useId, useRef, useState } from 'react'
+
+import { Button, Label, Switch } from '@posthog/quill'
+
+import { type ChartConfig, Y_UNIT_OPTIONS, type YUnit } from './chartSettingsConfig'
+
+interface ChartSettingsProps {
+ family: 'line' | 'bar'
+ config: ChartConfig
+ onChange: (config: ChartConfig) => void
+ /** Disabled in area mode, where overlays would draw against the stacked totals. */
+ derivedSeriesDisabled?: boolean
+ /** Disabled for non-stacked types — only area / stacked bar have a 100% view. */
+ percentStackDisabled?: boolean
+}
+
+export function ChartSettings({
+ family,
+ config,
+ onChange,
+ derivedSeriesDisabled = false,
+ percentStackDisabled = false,
+}: ChartSettingsProps): ReactElement {
+ const [open, setOpen] = useState(false)
+ const containerRef = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ if (!open) {
+ return
+ }
+ const onDocumentClick = (e: MouseEvent): void => {
+ if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
+ setOpen(false)
+ }
+ }
+ document.addEventListener('mousedown', onDocumentClick)
+ return () => document.removeEventListener('mousedown', onDocumentClick)
+ }, [open])
+
+ const update = <K extends keyof ChartConfig>(key: K, value: ChartConfig[K]): void => {
+ onChange({ ...config, [key]: value })
+ }
+
+ return (
+ <div ref={containerRef} className="relative">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setOpen((o) => !o)}
+ aria-label="Chart options"
+ aria-expanded={open}
+ >
+ Options
+ </Button>
+ {open && (
+ <div
+ role="dialog"
+ className="absolute right-0 top-full z-10 mt-1 w-56 rounded-sm border border-input bg-background p-3 shadow-lg"
+ >
+ <div className="flex flex-col gap-2 text-xs">
+ <Toggle
+ label="Value labels"
+ checked={config.showValueLabels}
+ onChange={(v) => update('showValueLabels', v)}
+ />
+ {family === 'line' && (
+ <>
+ <Toggle
+ label="Trend line"
+ checked={config.showTrendLine}
+ disabled={derivedSeriesDisabled}
+ onChange={(v) => update('showTrendLine', v)}
+ />
+ <Toggle
+ label="Confidence intervals"
+ checked={config.showConfidenceIntervals}
+ disabled={derivedSeriesDisabled}
+ onChange={(v) => update('showConfidenceIntervals', v)}
+ />
+ </>
+ )}
+ <Toggle
+ label="Percent stack"
+ checked={config.percentStack}
+ disabled={percentStackDisabled}
+ onChange={(v) => update('percentStack', v)}
+ />
+ <div className="mt-1">
+ <div className="mb-1 text-muted-foreground">Y-axis unit</div>
+ {/* eslint-disable-next-line react/forbid-elements */}
+ <select
+ value={config.yUnit}
+ onChange={(e) => update('yUnit', e.target.value as YUnit)}
+ className="w-full cursor-pointer rounded-sm border border-input bg-background px-2 py-1 text-xs text-foreground"
+ >
+ {Y_UNIT_OPTIONS.map((opt) => (
+ <option key={opt.value} value={opt.value}>
+ {opt.label}
+ </option>
+ ))}
+ </select>
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
+
+function Toggle({
+ label,
+ checked,
+ onChange,
+ disabled = false,
+}: {
+ label: string
+ checked: boolean
+ onChange: (next: boolean) => void
+ disabled?: boolean
+}): ReactElement {
+ const id = useId()
+ return (
+ <div className={`flex items-center justify-between gap-2 ${disabled ? 'opacity-50' : ''}`}>
+ <Label htmlFor={id} className={disabled ? 'cursor-not-allowed' : 'cursor-pointer'}>
+ {label}
+ </Label>
+ <Switch
+ id={id}
+ size="sm"
+ checked={checked && !disabled}
+ disabled={disabled}
+ onCheckedChange={(next) => onChange(next)}
+ />
+ </div>
+ )
+}
diff --git a/services/mcp/src/ui-apps/components/Component.tsx b/services/mcp/src/ui-apps/components/Component.tsx
index 3873adf9b138..55d1b0333794 100644
--- a/services/mcp/src/ui-apps/components/Component.tsx
+++ b/services/mcp/src/ui-apps/components/Component.tsx
@@ -63,7 +63,12 @@ export function Component({ data }: ComponentProps): ReactElement {
switch (visualizationType) {
case 'trends':
return (
- <TrendsVisualizer query={payload.query as TrendsQuery} results={payload.results as TrendsResult} />
+ <TrendsVisualizer
+ // The host updates `data` in place, so key on the query to re-seed state per result.
+ key={JSON.stringify(payload.query)}
+ query={payload.query as TrendsQuery}
+ results={payload.results as TrendsResult}
+ />
)
case 'funnel':
diff --git a/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx b/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx
index c61eeb2b8cef..b6db4415be86 100644
--- a/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx
+++ b/services/mcp/src/ui-apps/components/TrendsVisualizer.tsx
@@ -2,7 +2,15 @@ import { type ReactElement, useState } from 'react'
import { emptyStateIllustration } from '@posthog/mcp-ui'
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia } from '@posthog/quill'
-import { BarChart as BarValueChart, SlopeChart, TimeSeriesBarChart, TimeSeriesLineChart } from '@posthog/quill-charts'
+import {
+ BarChart as BarValueChart,
+ ciRanges,
+ DefaultTooltip,
+ SlopeChart,
+ TimeSeriesBarChart,
+ TimeSeriesLineChart,
+ type TooltipContext,
+} from '@posthog/quill-charts'
import { buildTrendsBarChartModel } from 'products/product_analytics/frontend/insights/trends/TrendsBarChart/trendsBarChartTransforms'
import {
@@ -16,21 +24,33 @@ import {
import { BigNumber, Select } from './charts'
import { CHART_THEME, colorAt } from './charts/theme'
+import { ChartSettings } from './ChartSettings'
+import {
+ type ChartType,
+ chartConfigFromTrendsFilter,
+ defaultChartType,
+ isBarFamily,
+ resolveChartView,
+ supportsPercentStack,
+} from './chartSettingsConfig'
import type { TrendsResultItem, TrendsVisualizerProps } from './types'
-import { formatDate, getDisplayType, getSeriesLabel, isBarChart } from './utils'
-
-type ChartMode = 'line' | 'bar' | 'slope'
+import { formatDate, formatTooltipDate, getDisplayType, getSeriesLabel } from './utils'
-const CHART_MODE_OPTIONS = [
+const CHART_TYPE_OPTIONS = [
{ value: 'line' as const, label: 'Line' },
+ { value: 'area' as const, label: 'Area' },
{ value: 'bar' as const, label: 'Bar' },
+ { value: 'stacked-bar' as const, label: 'Stacked bar' },
]
-// "Slope" collapses each series to its first and last point — the start-vs-end view a user wants
-// when they ask "how much did X change between A and B?" rather than the path between them.
-const SLOPE_MODE_OPTION = { value: 'slope' as const, label: 'Slope' }
+const SLOPE_TYPE_OPTION = { value: 'slope' as const, label: 'Slope' }
-const TOOLTIP_CONFIG = { pinnable: true, placement: 'top' as const }
+const TOOLTIP_CONFIG = { pinnable: true, placement: 'cursor' as const }
+
+// DefaultTooltip shows the raw x label; format it like the axis.
+const renderDateTooltip = (ctx: TooltipContext): ReactElement => (
+ <DefaultTooltip {...ctx} label={formatTooltipDate(ctx.label)} />
+)
function calculateTotal(results: TrendsResultItem[]): number {
return results.reduce((sum, item) => {
@@ -49,11 +69,8 @@ function calculateTotal(results: TrendsResultItem[]): number {
export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): ReactElement {
const displayType = getDisplayType(query)
- // Honour the backend slope runner: a SlopeGraph query already comes back as two points per series,
- // so open straight into slope mode rather than line + a manual toggle.
- const [chartMode, setChartMode] = useState<ChartMode>(
- isBarChart(displayType) ? 'bar' : displayType === 'SlopeGraph' ? 'slope' : 'line'
- )
+ const [chartType, setChartType] = useState<ChartType>(defaultChartType(displayType))
+ const [chartConfig, setChartConfig] = useState(() => chartConfigFromTrendsFilter(query?.trendsFilter))
if (!results || results.length === 0) {
return (
@@ -72,8 +89,7 @@ export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): Rea
return <BigNumber value={total} label={label} />
}
- // ActionsBarValue returns aggregated_value per series (empty data[]/days[]) — render a
- // horizontal bar of totals, not a time series, so there's no line/bar mode toggle.
+ // ActionsBarValue is aggregated totals per series (no days[]) — a horizontal bar, not a time series.
if (displayType === 'ActionsBarValue') {
const items = results.map((item, i) => ({
label: getSeriesLabel(item, i),
@@ -101,20 +117,17 @@ export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): Rea
days: item.days,
incompleteEnd: !!item.incomplete_end,
}))
- const yAxisLabel = results.length === 1 && results[0] ? getSeriesLabel(results[0], 0) : undefined
+ const { slopeAvailable, effectiveType } = resolveChartView(chartType, labels.length)
+ const chartTypeOptions = slopeAvailable ? [...CHART_TYPE_OPTIONS, SLOPE_TYPE_OPTION] : CHART_TYPE_OPTIONS
- // A slope needs a start and an end, so only offer it when there are at least two time points.
- const slopeAvailable = labels.length >= 2
- const chartModeOptions = slopeAvailable ? [...CHART_MODE_OPTIONS, SLOPE_MODE_OPTION] : CHART_MODE_OPTIONS
- // Results can shrink below two points after slope was selected; fall back rather than render blank.
- const effectiveMode = chartMode === 'slope' && !slopeAvailable ? 'line' : chartMode
+ // Area auto-stacks, so derived overlays would draw against the stacked totals — disable them.
+ const derivedSeriesDisabled = effectiveType === 'area'
+ const isPercentStackView = chartConfig.percentStack && supportsPercentStack(effectiveType)
+ const effectiveTrendsFilter = { ...query?.trendsFilter, aggregationAxisFormat: chartConfig.yUnit }
+ const valueLabels = chartConfig.showValueLabels ? true : undefined
- // Build only the active mode's chart model — toggling shouldn't recompute the hidden one.
const renderChart = (): ReactElement => {
- if (effectiveMode === 'slope') {
- // Hand quill the full series and labels — it reduces to the first and last point itself,
- // so the slope shaping lives once in quill, not here. The backend's incomplete_end flag is
- // forwarded so the provisional end dashes exactly as it does in the insight.
+ if (effectiveType === 'slope') {
const slopeSeries = trendResults
.filter((item) => item.data.length >= 2)
.map((item) => ({
@@ -134,38 +147,69 @@ export function TrendsVisualizer({ query, results }: TrendsVisualizerProps): Rea
/>
)
}
- if (effectiveMode === 'bar') {
+ if (isBarFamily(effectiveType)) {
const { series, config } = buildTrendsBarChartModel(trendResults, {
getColor: (_, index) => colorAt(index),
labels,
- yAxisLabel,
- isPercentStackView: false,
- isGrouped: false,
+ trendsFilter: effectiveTrendsFilter,
+ isPercentStackView,
+ isGrouped: effectiveType === 'bar',
+ valueLabels,
xAxisTickFormatter: (value) => formatDate(value),
tooltip: TOOLTIP_CONFIG,
})
- return <TimeSeriesBarChart series={series} labels={labels} theme={CHART_THEME} config={config} />
+ return (
+ <TimeSeriesBarChart
+ series={series}
+ labels={labels}
+ theme={CHART_THEME}
+ config={config}
+ tooltip={renderDateTooltip}
+ />
+ )
}
const series = buildTrendsSeries(trendResults, {
- isArea: displayType === 'ActionsAreaGraph',
+ isArea: effectiveType === 'area',
getColor: (_, index) => colorAt(index),
})
const config = buildTrendsLineTimeSeriesConfig({
results: trendResults,
- trendsFilter: query?.trendsFilter,
- yAxisLabel,
- isPercentStackView: false,
+ trendsFilter: effectiveTrendsFilter,
+ isPercentStackView,
+ showTrendLines: chartConfig.showTrendLine && !derivedSeriesDisabled,
+ showConfidenceIntervals: chartConfig.showConfidenceIntervals && !derivedSeriesDisabled,
+ confidenceLevel: chartConfig.confidenceLevel,
+ ciRanges,
+ valueLabels,
showCrosshair: true,
xAxisTickFormatter: (value) => formatDate(value),
+ tooltip: TOOLTIP_CONFIG,
})
- return <TimeSeriesLineChart series={series} labels={labels} theme={CHART_THEME} config={config} />
+ return (
+ <TimeSeriesLineChart
+ series={series}
+ labels={labels}
+ theme={CHART_THEME}
+ config={config}
+ tooltip={renderDateTooltip}
+ />
+ )
}
return (
<div>
- <div className="mb-2 flex justify-end">
+ <div className="mb-2 flex items-center justify-end gap-2">
{/* eslint-disable-next-line react/forbid-elements */}
- <Select value={effectiveMode} onChange={setChartMode} options={chartModeOptions} />
+ <Select value={effectiveType} onChange={setChartType} options={chartTypeOptions} />
+ {effectiveType !== 'slope' && (
+ <ChartSettings
+ family={isBarFamily(effectiveType) ? 'bar' : 'line'}
+ config={chartConfig}
+ onChange={setChartConfig}
+ derivedSeriesDisabled={derivedSeriesDisabled}
+ percentStackDisabled={!supportsPercentStack(effectiveType)}
+ />
+ )}
</div>
<div className="flex flex-col w-full h-[400px]">{renderChart()}</div>
</div>
diff --git a/services/mcp/src/ui-apps/components/chartSettingsConfig.ts b/services/mcp/src/ui-apps/components/chartSettingsConfig.ts
new file mode 100644
index 000000000000..f69a4aecf5f4
--- /dev/null
+++ b/services/mcp/src/ui-apps/components/chartSettingsConfig.ts
@@ -0,0 +1,83 @@
+import type { YAxisFormat } from '@posthog/quill-charts'
+
+import type { ChartDisplayType, TrendsFilter } from './types'
+
+export type ChartType = 'line' | 'area' | 'bar' | 'stacked-bar' | 'slope'
+
+// Reuse quill's canonical y-unit union so the two can't drift.
+export type YUnit = YAxisFormat
+
+export interface ChartConfig {
+ showValueLabels: boolean
+ showTrendLine: boolean
+ showConfidenceIntervals: boolean
+ confidenceLevel: number
+ percentStack: boolean
+ yUnit: YUnit
+}
+
+export const DEFAULT_CHART_CONFIG: ChartConfig = {
+ showValueLabels: false,
+ showTrendLine: false,
+ showConfidenceIntervals: false,
+ confidenceLevel: 95,
+ percentStack: false,
+ yUnit: 'numeric',
+}
+
+export const Y_UNIT_OPTIONS: { value: YUnit; label: string }[] = [
+ { value: 'numeric', label: 'Numeric' },
+ { value: 'short', label: 'Compact (1.2K)' },
+ { value: 'percentage', label: 'Percentage (0–100)' },
+ { value: 'percentage_scaled', label: 'Percentage (0–1)' },
+ { value: 'duration', label: 'Duration (s)' },
+ { value: 'duration_ms', label: 'Duration (ms)' },
+ { value: 'currency', label: 'Currency' },
+]
+
+export function chartConfigFromTrendsFilter(trendsFilter: TrendsFilter | undefined): ChartConfig {
+ return {
+ showValueLabels: trendsFilter?.showValuesOnSeries ?? DEFAULT_CHART_CONFIG.showValueLabels,
+ showTrendLine: trendsFilter?.showTrendLines ?? DEFAULT_CHART_CONFIG.showTrendLine,
+ showConfidenceIntervals: trendsFilter?.showConfidenceIntervals ?? DEFAULT_CHART_CONFIG.showConfidenceIntervals,
+ confidenceLevel: trendsFilter?.confidenceLevel ?? DEFAULT_CHART_CONFIG.confidenceLevel,
+ percentStack: trendsFilter?.showPercentStackView ?? DEFAULT_CHART_CONFIG.percentStack,
+ yUnit: trendsFilter?.aggregationAxisFormat ?? DEFAULT_CHART_CONFIG.yUnit,
+ }
+}
+
+export function defaultChartType(displayType: ChartDisplayType): ChartType {
+ if (displayType === 'SlopeGraph') {
+ return 'slope'
+ }
+ if (displayType === 'ActionsAreaGraph') {
+ return 'area'
+ }
+ if (displayType === 'ActionsUnstackedBar') {
+ return 'bar'
+ }
+ // ActionsBar renders stacked on web, so map it to the stacked option.
+ if (displayType === 'ActionsBar' || displayType === 'ActionsStackedBar') {
+ return 'stacked-bar'
+ }
+ return 'line'
+}
+
+export function isBarFamily(chartType: ChartType): boolean {
+ return chartType === 'bar' || chartType === 'stacked-bar'
+}
+
+export function supportsPercentStack(chartType: ChartType): boolean {
+ return chartType === 'area' || chartType === 'stacked-bar'
+}
+
+export interface ResolvedChartView {
+ slopeAvailable: boolean
+ effectiveType: ChartType
+}
+
+// Slope needs at least two time points; below that it falls back to line.
+export function resolveChartView(chartType: ChartType, labelCount: number): ResolvedChartView {
+ const slopeAvailable = labelCount >= 2
+ return { slopeAvailable, effectiveType: chartType === 'slope' && !slopeAvailable ? 'line' : chartType }
+}
diff --git a/services/mcp/src/ui-apps/components/charts/theme.ts b/services/mcp/src/ui-apps/components/charts/theme.ts
index 1b5c6cbb3594..b3685d27400e 100644
--- a/services/mcp/src/ui-apps/components/charts/theme.ts
+++ b/services/mcp/src/ui-apps/components/charts/theme.ts
@@ -49,7 +49,7 @@ export const lifecycleColor = (status: string | undefined): string =>
export const CHART_THEME: ChartTheme = {
colors: CHART_COLORS,
backgroundColor: '#ffffff',
- axisColor: '#9ca3af',
+ axisColor: '#6b7280',
gridColor: 'rgba(128, 128, 128, 0.2)',
crosshairColor: 'rgba(128, 128, 128, 0.5)',
tooltipBackground: '#ffffff',
diff --git a/services/mcp/src/ui-apps/components/types.ts b/services/mcp/src/ui-apps/components/types.ts
index e15b7ca050ea..49ef273574d2 100644
--- a/services/mcp/src/ui-apps/components/types.ts
+++ b/services/mcp/src/ui-apps/components/types.ts
@@ -1,3 +1,5 @@
+import type { YAxisFormat } from '@posthog/quill-charts'
+
import type { AnalyticsMetadata } from '../types'
// Base payload that all tool results share
@@ -15,6 +17,8 @@ export type ChartDisplayType =
| 'ActionsLineGraph'
| 'ActionsLineGraphCumulative'
| 'ActionsBar'
+ | 'ActionsStackedBar'
+ | 'ActionsUnstackedBar'
| 'ActionsBarValue'
| 'ActionsAreaGraph'
| 'BoldNumber'
@@ -27,7 +31,17 @@ export interface TrendsFilter {
display?: ChartDisplayType
showLegend?: boolean
showValuesOnSeries?: boolean
- aggregationAxisFormat?: 'numeric' | 'duration' | 'duration_ms' | 'percentage'
+ showTrendLines?: boolean
+ showMovingAverage?: boolean
+ movingAverageIntervals?: number
+ showConfidenceIntervals?: boolean
+ confidenceLevel?: number
+ showPercentStackView?: boolean
+ aggregationAxisFormat?: YAxisFormat
+ aggregationAxisPrefix?: string
+ aggregationAxisPostfix?: string
+ decimalPlaces?: number
+ minDecimalPlaces?: number
}
export interface TrendsQuery {
diff --git a/services/mcp/src/ui-apps/components/utils.ts b/services/mcp/src/ui-apps/components/utils.ts
index 45ec38439093..ed4267b73578 100644
--- a/services/mcp/src/ui-apps/components/utils.ts
+++ b/services/mcp/src/ui-apps/components/utils.ts
@@ -4,10 +4,6 @@ export function getDisplayType(query: TrendsQuery | undefined): ChartDisplayType
return query?.trendsFilter?.display || 'ActionsLineGraph'
}
-export function isBarChart(displayType: ChartDisplayType): boolean {
- return displayType === 'ActionsBar' || displayType === 'ActionsBarValue'
-}
-
export function formatNumber(value: number): string {
if (value >= 1_000_000) {
return `${(value / 1_000_000).toFixed(1)}M`
@@ -53,6 +49,17 @@ export function formatDate(dateStr: string): string {
return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })
}
+export function formatTooltipDate(dateStr: string): string {
+ if (!ISO_DATE_PREFIX.test(dateStr)) {
+ return dateStr
+ }
+ const date = new Date(dateStr)
+ if (Number.isNaN(date.getTime())) {
+ return dateStr
+ }
+ return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })
+}
+
export function getSeriesLabel(item: { label?: string; action?: { name?: string } }, index: number): string {
return item.label || item.action?.name || `Series ${index + 1}`
}
diff --git a/services/mcp/tests/unit/insight-visualizations.test.ts b/services/mcp/tests/unit/insight-visualizations.test.ts
index 5a5575104f17..b7b8102ff79e 100644
--- a/services/mcp/tests/unit/insight-visualizations.test.ts
+++ b/services/mcp/tests/unit/insight-visualizations.test.ts
@@ -16,7 +16,6 @@ import {
formatPercent,
getDisplayType,
getSeriesLabel,
- isBarChart,
normalizeFunnelSteps,
} from '@/ui-apps/components/utils'
@@ -236,7 +235,7 @@ describe('insight visualizations', () => {
})
})
- describe('getDisplayType / isBarChart', () => {
+ describe('getDisplayType', () => {
it('defaults to ActionsLineGraph when the query or filter is missing', () => {
expect(getDisplayType(undefined)).toBe('ActionsLineGraph')
expect(getDisplayType({ kind: 'TrendsQuery' })).toBe('ActionsLineGraph')
@@ -247,15 +246,6 @@ describe('insight visualizations', () => {
'BoldNumber'
)
})
-
- it.each([
- ['ActionsBar', true],
- ['ActionsBarValue', true],
- ['ActionsLineGraph', false],
- ['BoldNumber', false],
- ] as const)('isBarChart(%s) is %s', (displayType, expected) => {
- expect(isBarChart(displayType)).toBe(expected)
- })
})
describe('normalizeFunnelSteps', () => {
diff --git a/services/mcp/tests/unit/trends-chart-settings.test.ts b/services/mcp/tests/unit/trends-chart-settings.test.ts
new file mode 100644
index 000000000000..a33e1320721e
--- /dev/null
+++ b/services/mcp/tests/unit/trends-chart-settings.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ chartConfigFromTrendsFilter,
+ DEFAULT_CHART_CONFIG,
+ defaultChartType,
+ isBarFamily,
+ resolveChartView,
+ supportsPercentStack,
+} from '../../src/ui-apps/components/chartSettingsConfig'
+import type { ChartDisplayType, TrendsFilter } from '../../src/ui-apps/components/types'
+
+describe('trends chart settings', () => {
+ describe('chartConfigFromTrendsFilter', () => {
+ it('returns defaults when there is no trendsFilter', () => {
+ expect(chartConfigFromTrendsFilter(undefined)).toEqual(DEFAULT_CHART_CONFIG)
+ })
+
+ it('seeds every field from a fully populated trendsFilter', () => {
+ const trendsFilter: TrendsFilter = {
+ showValuesOnSeries: true,
+ showTrendLines: true,
+ showConfidenceIntervals: true,
+ confidenceLevel: 90,
+ showPercentStackView: true,
+ aggregationAxisFormat: 'duration',
+ }
+ expect(chartConfigFromTrendsFilter(trendsFilter)).toEqual({
+ showValueLabels: true,
+ showTrendLine: true,
+ showConfidenceIntervals: true,
+ confidenceLevel: 90,
+ percentStack: true,
+ yUnit: 'duration',
+ })
+ })
+
+ it('ignores unrelated trendsFilter fields', () => {
+ expect(chartConfigFromTrendsFilter({ display: 'ActionsBar', showLegend: true })).toEqual(
+ DEFAULT_CHART_CONFIG
+ )
+ })
+ })
+
+ describe('defaultChartType', () => {
+ it.each([
+ ['ActionsLineGraph', 'line'],
+ ['ActionsLineGraphCumulative', 'line'],
+ ['ActionsAreaGraph', 'area'],
+ ['ActionsBar', 'stacked-bar'],
+ ['ActionsStackedBar', 'stacked-bar'],
+ ['ActionsUnstackedBar', 'bar'],
+ ['ActionsPie', 'line'],
+ ['SlopeGraph', 'slope'],
+ ] as Array<[ChartDisplayType, string]>)('maps %s to %s', (displayType, expected) => {
+ expect(defaultChartType(displayType)).toBe(expected)
+ })
+ })
+
+ describe('chart type predicates', () => {
+ it.each([
+ ['line', false, false],
+ ['area', false, true],
+ ['bar', true, false],
+ ['stacked-bar', true, true],
+ ['slope', false, false],
+ ] as const)('%s: isBarFamily=%s, supportsPercentStack=%s', (chartType, barFamily, percentStack) => {
+ expect(isBarFamily(chartType)).toBe(barFamily)
+ expect(supportsPercentStack(chartType)).toBe(percentStack)
+ })
+ })
+
+ describe('resolveChartView', () => {
+ it.each([
+ [0, false],
+ [1, false],
+ [2, true],
+ [7, true],
+ ] as const)('slope is available with %i labels: %s', (labelCount, slopeAvailable) => {
+ expect(resolveChartView('line', labelCount).slopeAvailable).toBe(slopeAvailable)
+ })
+
+ it('falls slope back to line when there are fewer than two points', () => {
+ expect(resolveChartView('slope', 1).effectiveType).toBe('line')
+ expect(resolveChartView('slope', 0).effectiveType).toBe('line')
+ })
+
+ it('keeps slope when there are at least two points', () => {
+ expect(resolveChartView('slope', 2).effectiveType).toBe('slope')
+ })
+
+ it.each(['line', 'area', 'bar', 'stacked-bar'] as const)('passes %s through unchanged', (chartType) => {
+ expect(resolveChartView(chartType, 7).effectiveType).toBe(chartType)
+ })
+ })
+})