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(insights): configurable metric summary and hover change pill (#64761)

Sam Pennington0faecaa8bbe7
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 2c54f88cc5d1..c9bb8066ddc8 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -720,6 +720,10 @@ snapshots:
hash: v1.k794b7964.a09b8609071d1aaa038a5ed7981d94669e8640c2a877d11d9b70000482987c3e.JKqQfzNlh19Y1ZHWiGcl5jw6-g0pFjoFk7dClPCCa0w
components-hogcharts-metriccard--number-only--light:
hash: v1.k794b7964.a6d0fc80e033300bdfeeb68cd9b1c0268164dfe2434ced41f27312a3599984f0.kqH1RsyfSbLcK7vT-1FQW4dPfgo2FS1R7VKRb3fa35Y
+ components-hogcharts-metriccard--resting-summary--dark:
+ hash: v1.k794b7964.371e031f9b4aca1fbb681a1ca2bdb05474ef27d854a245bc55da66c9c09ccf42.iqisewbYmdeiLttYp-nCmU2E5rCPQ6tJNE2C0Ik-oeg
+ components-hogcharts-metriccard--resting-summary--light:
+ hash: v1.k794b7964.a30741d5811b5f94dc8ded69c36e7d017784f7c5e8698433de3a95d7088b5ee7.b2Prb8CqmoIL-caSlFDMMLrX0cZhUH6HgIdLW89i2S8
components-hogcharts-piechart--donut--dark:
hash: v1.k794b7964.95f52c48e6476dd49327e572e78275692bf3085a46c78b57d7ccb0f2af33229d.UKy0xtoAM3JGpdygHr-mG_fCI8HoINH0cq0e-w5MuYY
components-hogcharts-piechart--donut--light:
diff --git a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
index fac61720f15d..ea2beda72dbd 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightDisplayConfig.tsx
@@ -25,7 +25,11 @@ import { HideIncompleteConversionWindowPeriodsFilter } from 'scenes/insights/Edi
import { HideWeekendsFilter } from 'scenes/insights/EditorFilters/HideWeekendsFilter'
import { LifecyclePercentagesFilter } from 'scenes/insights/EditorFilters/LifecyclePercentagesFilter'
import { LifecycleStackingFilter } from 'scenes/insights/EditorFilters/LifecycleStackingFilter'
-import { MetricColorFilter, MetricShowChangeFilter } from 'scenes/insights/EditorFilters/MetricFilters'
+import {
+ MetricColorFilter,
+ MetricShowChangeFilter,
+ MetricSummaryFilter,
+} from 'scenes/insights/EditorFilters/MetricFilters'
import { PercentStackViewFilter } from 'scenes/insights/EditorFilters/PercentStackViewFilter'
import { ResultCustomizationByPicker } from 'scenes/insights/EditorFilters/ResultCustomizationByPicker'
import { ScalePicker } from 'scenes/insights/EditorFilters/ScalePicker'
@@ -234,6 +238,7 @@ export function InsightDisplayConfig(): JSX.Element {
: [
...(isMetric
? [
+ { label: () => <MetricSummaryFilter /> },
{ label: () => <MetricShowChangeFilter /> },
{ label: () => <MetricColorFilter /> },
]
@@ -435,7 +440,8 @@ export function InsightDisplayConfig(): JSX.Element {
(trendsFilter?.hideWeekends && hideWeekendsEnabled ? 1 : 0) +
(showAnnotationsConfig && showAnnotations === false ? 1 : 0) +
(isMetric && trendsFilter?.metricShowChange === false ? 1 : 0) +
- (isMetric && trendsFilter?.metricColorByDirection ? 1 : 0)
+ (isMetric && trendsFilter?.metricColorByDirection ? 1 : 0) +
+ (isMetric && !!trendsFilter?.metricSummary && trendsFilter.metricSummary !== 'total' ? 1 : 0)
return (
<div
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index aebe34fa5f41..438ba41e5195 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -4352,9 +4352,15 @@
},
"metricShowChange": {
"default": true,
- "description": "Only applies when `display` is `Metric`. Show the change pill next to the big number — the percentage change from the first to the last point of the series over the selected date range.",
+ "description": "Only applies when `display` is `Metric`. Show the change pill next to the big number. What it compares follows `metricSummary`: `total`/`average` compare against the previous period when \"compare to previous\" is on (otherwise first→last of the series), and `latest` is always first→last of the series.",
"type": "boolean"
},
+ "metricSummary": {
+ "default": "total",
+ "description": "Only applies when `display` is `Metric`. Which summary the resting big number shows: `total` (sum over the period), `average` (mean of the points), or `latest` (last point). Hovering the sparkline always shows the hovered point's value regardless of this setting. Also drives the change pill: `total`/`average` compare against the previous period when \"compare to previous\" is on; `latest` compares first→last of the series.",
+ "enum": ["total", "average", "latest"],
+ "type": "string"
+ },
"showAlertThresholdLines": {
"default": false,
"description": "Whether to show alert threshold lines on the chart.",
@@ -43620,6 +43626,12 @@
"description": "Show the period-over-period change pill on the Metric display.",
"type": "boolean"
},
+ "metricSummary": {
+ "default": "total",
+ "description": "Metric display: which summary the resting headline shows — the period total, the average, or the latest point. Hovering the sparkline always shows the hovered point's value. Also drives the change pill: total/average compare against the previous period when \"compare to previous\" is on; latest compares first→last of the series.",
+ "enum": ["total", "average", "latest"],
+ "type": "string"
+ },
"minDecimalPlaces": {
"type": "number"
},
diff --git a/frontend/src/queries/schema/schema-assistant-queries.ts b/frontend/src/queries/schema/schema-assistant-queries.ts
index 88be3ecca5c5..45e4d87f6850 100644
--- a/frontend/src/queries/schema/schema-assistant-queries.ts
+++ b/frontend/src/queries/schema/schema-assistant-queries.ts
@@ -562,8 +562,10 @@ export interface AssistantTrendsFilter {
showMultipleYAxes?: TrendsFilterLegacy['show_multiple_y_axes']
/**
- * Only applies when `display` is `Metric`. Show the change pill next to the big number — the
- * percentage change from the first to the last point of the series over the selected date range.
+ * Only applies when `display` is `Metric`. Show the change pill next to the big number. What it
+ * compares follows `metricSummary`: `total`/`average` compare against the previous period when
+ * "compare to previous" is on (otherwise first→last of the series), and `latest` is always
+ * first→last of the series.
* @default true
*/
metricShowChange?: boolean
@@ -602,6 +604,16 @@ export interface AssistantTrendsFilter {
* "lower is better" metric.
*/
metricLineDecreaseColor?: string
+
+ /**
+ * Only applies when `display` is `Metric`. Which summary the resting big number shows: `total`
+ * (sum over the period), `average` (mean of the points), or `latest` (last point). Hovering the
+ * sparkline always shows the hovered point's value regardless of this setting. Also drives the
+ * change pill: `total`/`average` compare against the previous period when "compare to previous"
+ * is on; `latest` compares first→last of the series.
+ * @default total
+ */
+ metricSummary?: 'total' | 'average' | 'latest'
}
export interface AssistantTrendsQuery extends AssistantInsightsQueryBase {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index a6804684a7f1..28a7eb884e82 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -1507,6 +1507,12 @@ export type TrendsFilter = {
metricLineIncreaseColor?: string
/** Metric display: line color when the metric decreased. Defaults to red. */
metricLineDecreaseColor?: string
+ /** Metric display: which summary the resting headline shows — the period total, the average,
+ * or the latest point. Hovering the sparkline always shows the hovered point's value. Also drives
+ * the change pill: total/average compare against the previous period when "compare to previous"
+ * is on; latest compares first→last of the series.
+ * @default total */
+ metricSummary?: 'total' | 'average' | 'latest'
}
export type CalendarHeatmapFilter = {
@@ -1545,6 +1551,7 @@ export const TRENDS_FILTER_PROPERTIES = new Set<keyof TrendsFilter>([
'metricColorByDirection',
'metricLineIncreaseColor',
'metricLineDecreaseColor',
+ 'metricSummary',
])
export interface BoxPlotDatum {
diff --git a/frontend/src/scenes/insights/EditorFilters/MetricFilters.tsx b/frontend/src/scenes/insights/EditorFilters/MetricFilters.tsx
index fe45b4ca728b..fc9ae3fd9e92 100644
--- a/frontend/src/scenes/insights/EditorFilters/MetricFilters.tsx
+++ b/frontend/src/scenes/insights/EditorFilters/MetricFilters.tsx
@@ -1,5 +1,7 @@
import { useActions, useValues } from 'kea'
+import { LemonSelect } from '@posthog/lemon-ui'
+
import { getSeriesColorPalette } from 'lib/colors'
import { LemonCheckbox } from 'lib/lemon-ui/LemonCheckbox'
import { LemonColorPicker } from 'lib/lemon-ui/LemonColor'
@@ -9,6 +11,8 @@ import {
METRIC_DEFAULT_DECREASE_COLOR,
METRIC_DEFAULT_INCREASE_COLOR,
METRIC_SHOW_CHANGE_DEFAULT,
+ METRIC_SUMMARY_DEFAULT,
+ type MetricSummary,
} from 'scenes/insights/views/Metric/Metric.utils'
import { insightLogic } from '../insightLogic'
@@ -52,6 +56,30 @@ function DirectionColorPickers({
)
}
+export function MetricSummaryFilter(): JSX.Element {
+ const { insightProps } = useValues(insightLogic)
+ const { trendsFilter } = useValues(insightVizDataLogic(insightProps))
+ const { updateInsightFilter } = useActions(insightVizDataLogic(insightProps))
+
+ const summary = trendsFilter?.metricSummary ?? METRIC_SUMMARY_DEFAULT
+
+ return (
+ <div className="flex items-center justify-between gap-2 p-1 px-2">
+ <span className="font-normal">Headline value</span>
+ <LemonSelect<MetricSummary>
+ size="small"
+ value={summary}
+ onChange={(value) => updateInsightFilter({ metricSummary: value })}
+ options={[
+ { value: 'total', label: 'Total' },
+ { value: 'average', label: 'Average' },
+ { value: 'latest', label: 'Latest' },
+ ]}
+ />
+ </div>
+ )
+}
+
export function MetricShowChangeFilter(): JSX.Element {
const { insightProps } = useValues(insightLogic)
const { trendsFilter } = useValues(insightVizDataLogic(insightProps))
diff --git a/frontend/src/scenes/insights/views/Metric/Metric.tsx b/frontend/src/scenes/insights/views/Metric/Metric.tsx
index 0c9d53a22aba..ebe70b54413c 100644
--- a/frontend/src/scenes/insights/views/Metric/Metric.tsx
+++ b/frontend/src/scenes/insights/views/Metric/Metric.tsx
@@ -5,7 +5,7 @@ import { MetricCard, useChartTheme } from '@posthog/quill-charts'
import { dayjs } from 'lib/dayjs'
import { hexToRGBA } from 'lib/utils/colors'
-import { formatDate } from 'lib/utils/datetime'
+import { DATE_FORMAT_WITHOUT_YEAR, formatDate } from 'lib/utils/datetime'
import { formatAggregationAxisValue } from 'scenes/insights/aggregationAxisFormat'
import { InsightEmptyState } from 'scenes/insights/EmptyStates'
import { insightVizDataLogic } from 'scenes/insights/insightVizDataLogic'
@@ -15,11 +15,15 @@ import { ChartParams, TrendResult } from '~/types'
import { insightLogic } from '../../insightLogic'
import {
- computeMetricChange,
+ computeMetricSummary,
+ computeMetricSummaryChange,
METRIC_COLOR_BY_DIRECTION_DEFAULT,
METRIC_DEFAULT_DECREASE_COLOR,
METRIC_DEFAULT_INCREASE_COLOR,
METRIC_SHOW_CHANGE_DEFAULT,
+ METRIC_SUMMARY_DEFAULT,
+ METRIC_SUMMARY_LABELS,
+ selectPreviousSeriesSummary,
} from './Metric.utils'
const makeChangeColor = (hex: string): { background: string; foreground: string } => ({
@@ -29,7 +33,7 @@ const makeChangeColor = (hex: string): { background: string; foreground: string
export function Metric({ inCardView }: ChartParams): JSX.Element {
const { insightProps } = useValues(insightLogic)
- const { insightData, trendsFilter } = useValues(insightVizDataLogic(insightProps))
+ const { insightData, trendsFilter, compareFilter } = useValues(insightVizDataLogic(insightProps))
const { baseCurrency } = useValues(teamLogic)
const theme = useChartTheme()
@@ -40,14 +44,21 @@ export function Metric({ inCardView }: ChartParams): JSX.Element {
return <InsightEmptyState />
}
- const headlineValue = resultSeries.count
+ const summary = trendsFilter?.metricSummary ?? METRIC_SUMMARY_DEFAULT
+ const headlineValue = computeMetricSummary(summary, resultSeries.count, resultSeries.data)
const showChange = trendsFilter?.metricShowChange ?? METRIC_SHOW_CHANGE_DEFAULT
- const { change, startValue } = computeMetricChange(resultSeries.data)
- const comparisonSubtitle =
- startValue != null
- ? `vs. ${formatAggregationAxisValue(trendsFilter, startValue, baseCurrency)} at start`
- : undefined
+ // When "compare to previous" is on, total/average compare against the previous period (matched by
+ // compare_label) instead of the within-window first→last movement.
+ const previousSeries = selectPreviousSeriesSummary(
+ !!compareFilter?.compare,
+ insightData?.result as TrendResult[] | undefined
+ )
+ const change = computeMetricSummaryChange(
+ summary,
+ { total: resultSeries.count, data: resultSeries.data },
+ previousSeries
+ )
const isIncrease = (change?.value ?? 0) >= 0
const pillColors = {
@@ -61,8 +72,9 @@ export function Metric({ inCardView }: ChartParams): JSX.Element {
lineColor = isIncrease ? lineIncreaseColor : lineDecreaseColor
}
- // Format the backend day labels the app's way ("June 16, 2026" rather than "16-Jun-2026").
- const labels = resultSeries.days?.map((day) => formatDate(dayjs(day))) ?? resultSeries.labels
+ // Format the backend day labels the app's way, without the year ("June 16" rather than "16-Jun-2026").
+ const labels =
+ resultSeries.days?.map((day) => formatDate(dayjs(day), DATE_FORMAT_WITHOUT_YEAR)) ?? resultSeries.labels
return (
<div className={clsx('Metric ph-no-capture flex flex-col w-full p-2', inCardView && 'flex-1')}>
@@ -75,8 +87,9 @@ export function Metric({ inCardView }: ChartParams): JSX.Element {
changeSize="md"
changeInline
change={change}
+ hoverChangeFromPreviousPoint
{...pillColors}
- subtitle={comparisonSubtitle}
+ restingSubtitle={METRIC_SUMMARY_LABELS[summary]}
data={resultSeries.data}
labels={labels}
theme={theme}
diff --git a/frontend/src/scenes/insights/views/Metric/Metric.utils.test.ts b/frontend/src/scenes/insights/views/Metric/Metric.utils.test.ts
index 61f6f321bd32..11a2e21ae596 100644
--- a/frontend/src/scenes/insights/views/Metric/Metric.utils.test.ts
+++ b/frontend/src/scenes/insights/views/Metric/Metric.utils.test.ts
@@ -1,57 +1,192 @@
-import { computeMetricChange, MetricChangeResult } from './Metric.utils'
+import { type MetricChange } from '@posthog/quill-charts'
+
+import {
+ computeMetricChange,
+ computeMetricSummary,
+ computeMetricSummaryChange,
+ type MetricSeriesSummary,
+ MetricSummary,
+ selectPreviousSeriesSummary,
+} from './Metric.utils'
describe('computeMetricChange', () => {
- const cases: { name: string; data: number[] | undefined; expected: MetricChangeResult }[] = [
- { name: 'undefined data → no change', data: undefined, expected: { change: undefined, startValue: undefined } },
- { name: 'empty series → no change', data: [], expected: { change: undefined, startValue: undefined } },
- { name: 'single point → no change', data: [5], expected: { change: undefined, startValue: undefined } },
+ const cases: { name: string; data: number[] | undefined; expected: MetricChange | null | undefined }[] = [
+ { name: 'undefined data → no change', data: undefined, expected: undefined },
+ { name: 'empty series → no change', data: [], expected: undefined },
+ { name: 'single point → no change', data: [5], expected: undefined },
+ { name: 'drops below two finite points → no change', data: [NaN, Infinity], expected: undefined },
+ { name: 'increase', data: [100, 150], expected: { value: 50 } },
+ { name: 'decrease', data: [200, 100], expected: { value: -50 } },
+ { name: 'zero start, positive end → +∞', data: [0, 50], expected: { value: 1, label: '∞' } },
+ { name: 'zero start, zero end → no movement', data: [0, 0], expected: null },
+ { name: 'zero start, negative end → -∞', data: [0, -5], expected: { value: -1, label: '∞' } },
+ { name: 'just below cap → real % with no ∞ label', data: [100, 10000], expected: { value: 9900 } },
+ { name: 'exactly at cap → ∞', data: [1, 101], expected: { value: 10000, label: '∞' } },
+ { name: 'over cap → ∞ (value preserved)', data: [1, 100000], expected: { value: 9999900, label: '∞' } },
{
- name: 'filtering drops below two finite points → no change',
- data: [NaN, Infinity],
- expected: { change: undefined, startValue: undefined },
+ name: 'negative over cap → ∞ (Math.abs on decreases)',
+ data: [100, -10000],
+ expected: { value: -10100, label: '∞' },
},
- { name: 'increase', data: [100, 150], expected: { change: { value: 50 }, startValue: 100 } },
- { name: 'decrease', data: [200, 100], expected: { change: { value: -50 }, startValue: 200 } },
+ { name: 'non-finite values filtered out', data: [NaN, 100, 200], expected: { value: 100 } },
+ { name: 'negative start increasing', data: [-100, -50], expected: { value: 50 } },
+ ]
+
+ it.each(cases)('$name', ({ data, expected }) => {
+ expect(computeMetricChange(data)).toEqual(expected)
+ })
+})
+
+describe('computeMetricSummary', () => {
+ const cases: {
+ name: string
+ summary: MetricSummary
+ total: number
+ data: number[] | undefined
+ expected: number
+ }[] = [
{
- name: 'zero start, positive end → +∞',
- data: [0, 50],
- expected: { change: { value: 1, label: '∞' }, startValue: 0 },
+ name: 'total returns the supplied aggregate',
+ summary: 'total',
+ total: 600,
+ data: [100, 200, 300],
+ expected: 600,
},
- { name: 'zero start, zero end → no movement', data: [0, 0], expected: { change: null, startValue: 0 } },
{
- name: 'zero start, negative end → -∞',
- data: [0, -5],
- expected: { change: { value: -1, label: '∞' }, startValue: 0 },
+ name: 'average is the mean of finite points',
+ summary: 'average',
+ total: 600,
+ data: [100, 200, 300],
+ expected: 200,
},
{
- name: 'just below cap → real % with no ∞ label',
- data: [100, 10000],
- expected: { change: { value: 9900 }, startValue: 100 },
+ name: 'latest is the last finite point',
+ summary: 'latest',
+ total: 600,
+ data: [100, 200, 300],
+ expected: 300,
},
{
- name: 'exactly at cap → ∞',
- data: [1, 101],
- expected: { change: { value: 10000, label: '∞' }, startValue: 1 },
+ name: 'average ignores non-finite points',
+ summary: 'average',
+ total: 0,
+ data: [NaN, 100, 200],
+ expected: 150,
},
{
- name: 'large positive over cap → ∞ (value preserved)',
- data: [1, 100000],
- expected: { change: { value: 9999900, label: '∞' }, startValue: 1 },
+ name: 'latest ignores a trailing non-finite point',
+ summary: 'latest',
+ total: 0,
+ data: [100, 200, NaN],
+ expected: 200,
},
{
- name: 'large negative over cap → ∞ (Math.abs triggers on decreases too)',
- data: [100, -10000],
- expected: { change: { value: -10100, label: '∞' }, startValue: 100 },
+ name: 'average falls back to total with no finite data',
+ summary: 'average',
+ total: 42,
+ data: [],
+ expected: 42,
},
{
- name: 'non-finite values filtered out',
- data: [NaN, 100, 200],
- expected: { change: { value: 100 }, startValue: 100 },
+ name: 'latest falls back to total with undefined data',
+ summary: 'latest',
+ total: 42,
+ data: undefined,
+ expected: 42,
},
- { name: 'negative start increasing', data: [-100, -50], expected: { change: { value: 50 }, startValue: -100 } },
]
- it.each(cases)('$name', ({ data, expected }) => {
- expect(computeMetricChange(data)).toEqual(expected)
+ it.each(cases)('$name', ({ summary, total, data, expected }) => {
+ expect(computeMetricSummary(summary, total, data)).toBe(expected)
+ })
+})
+
+describe('computeMetricSummaryChange', () => {
+ const current = { total: 600, data: [100, 200, 300] }
+
+ const cases: {
+ name: string
+ summary: MetricSummary
+ previous: { total: number; data: number[] | undefined } | undefined
+ expected: MetricChange | null | undefined
+ }[] = [
+ {
+ name: 'latest always uses first→last of the current series, ignoring the previous period',
+ summary: 'latest',
+ previous: { total: 300, data: [50, 100, 150] },
+ expected: { value: 200 },
+ },
+ {
+ name: 'total without a previous period falls back to first→last',
+ summary: 'total',
+ previous: undefined,
+ expected: { value: 200 },
+ },
+ {
+ name: 'average without a previous period falls back to first→last',
+ summary: 'average',
+ previous: undefined,
+ expected: { value: 200 },
+ },
+ {
+ name: 'total vs previous total when a comparison period is present',
+ summary: 'total',
+ previous: { total: 400, data: [100, 100, 200] },
+ expected: { value: 50 },
+ },
+ {
+ name: 'average vs previous average when a comparison period is present',
+ summary: 'average',
+ previous: { total: 300, data: [100, 100, 100] },
+ expected: { value: 100 },
+ },
+ {
+ name: 'previous total of zero reads as ∞',
+ summary: 'total',
+ previous: { total: 0, data: [] },
+ expected: { value: 1, label: '∞' },
+ },
+ {
+ name: 'average with no finite previous points yields no pill',
+ summary: 'average',
+ previous: { total: 0, data: [NaN] },
+ expected: undefined,
+ },
+ ]
+
+ it.each(cases)('$name', ({ summary, previous, expected }) => {
+ expect(computeMetricSummaryChange(summary, current, previous)).toEqual(expected)
+ })
+})
+
+describe('selectPreviousSeriesSummary', () => {
+ const current = { count: 600, data: [100, 200, 300], compare_label: 'current' }
+ const previous = { count: 300, data: [50, 100, 150], compare_label: 'previous' }
+
+ const cases: {
+ name: string
+ enabled: boolean
+ results: { count: number; data: number[]; compare_label?: string }[] | undefined
+ expected: MetricSeriesSummary | undefined
+ }[] = [
+ { name: 'compare disabled → no previous', enabled: false, results: [current, previous], expected: undefined },
+ { name: 'undefined results → no previous', enabled: true, results: undefined, expected: undefined },
+ { name: 'no previous-labelled series → no previous', enabled: true, results: [current], expected: undefined },
+ {
+ name: 'picks the previous-labelled series',
+ enabled: true,
+ results: [current, previous],
+ expected: { total: 300, data: [50, 100, 150] },
+ },
+ {
+ name: 'matches by compare_label, not array position',
+ enabled: true,
+ results: [previous, current],
+ expected: { total: 300, data: [50, 100, 150] },
+ },
+ ]
+
+ it.each(cases)('$name', ({ enabled, results, expected }) => {
+ expect(selectPreviousSeriesSummary(enabled, results)).toEqual(expected)
})
})
diff --git a/frontend/src/scenes/insights/views/Metric/Metric.utils.ts b/frontend/src/scenes/insights/views/Metric/Metric.utils.ts
index ffdcb38eaa30..bdb0fd3d1e33 100644
--- a/frontend/src/scenes/insights/views/Metric/Metric.utils.ts
+++ b/frontend/src/scenes/insights/views/Metric/Metric.utils.ts
@@ -3,30 +3,95 @@ import { type MetricChange } from '@posthog/quill-charts'
// Above this magnitude the exact percentage is noise (it comes from a near-zero start), so show ∞ instead.
export const MAX_CHANGE_PERCENT = 10_000 // ≈100×
+export type MetricSummary = 'total' | 'average' | 'latest'
+
+export const METRIC_SUMMARY_DEFAULT: MetricSummary = 'total'
+export const METRIC_SUMMARY_LABELS: Record<MetricSummary, string> = {
+ total: 'Total',
+ average: 'Avg',
+ latest: 'Latest',
+}
+
export const METRIC_SHOW_CHANGE_DEFAULT = true
export const METRIC_COLOR_BY_DIRECTION_DEFAULT = false
export const METRIC_DEFAULT_INCREASE_COLOR = '#388600'
export const METRIC_DEFAULT_DECREASE_COLOR = '#db3707'
-export interface MetricChangeResult {
- // `undefined` → no pill (fewer than two finite points); `null` → no movement worth showing.
- change: MetricChange | null | undefined
- startValue: number | undefined
+const finiteValues = (data: number[] | undefined): number[] => (data ?? []).filter((v) => Number.isFinite(v))
+
+const mean = (values: number[]): number => values.reduce((sum, v) => sum + v, 0) / values.length
+
+const meanOfFinite = (data: number[] | undefined): number | undefined => {
+ const finite = finiteValues(data)
+ return finite.length === 0 ? undefined : mean(finite)
+}
+
+// Percentage change from `start` to `end`. Renders ∞ when the start is zero (infinite) or the magnitude
+// is so large the exact percentage is just noise. A missing endpoint yields `undefined` (no pill).
+function changeBetween(start: number | undefined, end: number | undefined): MetricChange | null | undefined {
+ if (start == null || end == null) {
+ return undefined
+ }
+ if (start === 0) {
+ return end === 0 ? null : { value: end > 0 ? 1 : -1, label: '∞' }
+ }
+ const percent = ((end - start) / Math.abs(start)) * 100
+ return Math.abs(percent) >= MAX_CHANGE_PERCENT ? { value: percent, label: '∞' } : { value: percent }
+}
+
+export function computeMetricChange(data: number[] | undefined): MetricChange | null | undefined {
+ const finite = finiteValues(data)
+ return finite.length < 2 ? undefined : changeBetween(finite[0], finite[finite.length - 1])
}
-// Change from the first to the last finite point. Renders ∞ when the start is zero (infinite) or near-zero.
-export function computeMetricChange(data: number[] | undefined): MetricChangeResult {
- const finite = (data ?? []).filter((value) => Number.isFinite(value))
- if (finite.length < 2) {
- return { change: undefined, startValue: undefined }
+// Falls back to the total when the series has no finite points.
+export function computeMetricSummary(summary: MetricSummary, total: number, data: number[] | undefined): number {
+ if (summary === 'total') {
+ return total
}
- const startValue = finite[0]
- const endValue = finite[finite.length - 1]
- if (startValue === 0) {
- const change = endValue === 0 ? null : { value: endValue > 0 ? 1 : -1, label: '∞' }
- return { change, startValue }
+ const finite = finiteValues(data)
+ if (finite.length === 0) {
+ return total
+ }
+ return summary === 'latest' ? finite[finite.length - 1] : mean(finite)
+}
+
+export interface MetricSeriesSummary {
+ total: number
+ data: number[] | undefined
+}
+
+interface ComparableSeries {
+ count: number
+ data: number[]
+ compare_label?: string | null
+}
+
+// The previous comparison period, when "compare to previous" is on. Matched by `compare_label` rather
+// than position so it stays correct if the results array ever holds more than the current series.
+export function selectPreviousSeriesSummary(
+ compareEnabled: boolean,
+ results: readonly ComparableSeries[] | undefined
+): MetricSeriesSummary | undefined {
+ if (!compareEnabled || !results) {
+ return undefined
+ }
+ const previous = results.find((series) => series.compare_label === 'previous')
+ return previous ? { total: previous.count, data: previous.data } : undefined
+}
+
+// The change pill, matched to the chosen summary:
+// - `total`/`average` with a comparison period → this period's total/average vs the previous period's.
+// - `latest`, or `total`/`average` without a comparison period → first → last of the current series.
+export function computeMetricSummaryChange(
+ summary: MetricSummary,
+ current: MetricSeriesSummary,
+ previous: MetricSeriesSummary | undefined
+): MetricChange | null | undefined {
+ if (previous && summary !== 'latest') {
+ return summary === 'total'
+ ? changeBetween(previous.total, current.total)
+ : changeBetween(meanOfFinite(previous.data), meanOfFinite(current.data))
}
- const percent = ((endValue - startValue) / Math.abs(startValue)) * 100
- const change = Math.abs(percent) >= MAX_CHANGE_PERCENT ? { value: percent, label: '∞' } : { value: percent }
- return { change, startValue }
+ return computeMetricChange(current.data)
}
diff --git a/packages/quill/packages/charts/AGENTS.md b/packages/quill/packages/charts/AGENTS.md
index f6179b84341d..86dd44f07188 100644
--- a/packages/quill/packages/charts/AGENTS.md
+++ b/packages/quill/packages/charts/AGENTS.md
@@ -72,7 +72,7 @@ Charts fill their container and need a parent with real dimensions — a `0`-hei
- Every multi-series chart (`LineChart`, `BarChart`, `TimeSeriesLineChart`, `TimeSeriesBarChart`, `SlopeChart`) takes a `config.legend: ChartLegendConfig` (`{ show, position, align, gap, interactive, hiddenKeys, defaultHiddenKeys, onToggleSeries }`). With `show: true` the chart renders a built-in legend that, by default (`interactive`), is click-to-toggle: clicking a row hides that series (no draw, no scale contribution, no tooltip — the axes rescale into the freed space) while the row stays listed but dimmed so it can be restored. The chart owns the toggled-off state (uncontrolled); set `interactive: false` for a static legend, or pass `hiddenKeys` + `onToggleSeries` to control it yourself. Hidden by default. Toggling on time-series charts lists the user's series only (not derived trend lines / CI bands) — and hiding a series also hides everything derived from it (its CI band, moving average, and trend line), so no orphaned overlay floats over the gap.
- `Legend` (and `ChartLegend` for layout) is the lower-level presentational primitive: pass `items`, `onItemClick`, `hiddenKeys` — filtering series is the caller's state. Use it directly when the built-in `config.legend` can't express what you need (custom item order/labels). `useChartLegend(series, theme, config, items?)` is the shared hook the charts use — returns `visibleSeries` (hidden applied as `visibility.excluded`) plus `legendProps` to spread onto `<ChartLegend>`; `applyHiddenSeries` is the underlying helper. `LegendItem.secondaryLabel` shows muted trailing text (e.g. a slope chart's per-series change).
- `SlopeChart` config: `showSeriesLabels` (name beside each point; steepest line wins label collisions), `showStartLabels`/`showEndLabels` (defaults overridable per series via `meta.showStartLabel`/`showEndLabel`), `legend` (`{ show, position }`, rows carry the formatted change, ordered biggest-to-smallest by end value to match the lines' right-edge order), `valueFormatter`/`deltaFormatter`. The value axis is hidden by default — the start/end labels are the readout. The default tooltip orders its rows biggest-to-smallest by the hovered point's value (so many-breakdown tooltips match the lines' vertical order) and formats values with `valueFormatter` so they match the on-chart labels' units; pass your own `tooltip` to override. (`DefaultTooltip` itself takes an optional `valueFormatter` for the same reason — without it values fall back to `toLocaleString`.) Per-series `meta.incompleteEnd` dashes only the second half of that connector (the last point is the current incomplete period); the renderer splits the final segment at its midpoint via `stroke.partial.fromFraction`, so a two-point line needs no phantom interior point.
-- `MetricCard` is a left-aligned tile. Pass `title={null}` to drop the title row — the header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle (and no `labels`), so a value-only card renders just the number. `changeSize="md"` renders a larger change pill (default `sm`); `changeInline` puts the pill beside the headline instead of in the header; `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`.
+- `MetricCard` is a left-aligned tile. Pass `title={null}` to drop the title row — the header band collapses when there is no title and no change pill, and the subtitle row is omitted when there is no subtitle (and no `labels`), so a value-only card renders just the number. `changeSize="md"` renders a larger change pill (default `sm`); `changeInline` puts the pill beside the headline instead of in the header; `sparklineFill` makes the sparkline fill the card's remaining height instead of a fixed `sparklineHeight`. `subtitle` always wins (shown at rest and on hover); `restingSubtitle` (e.g. `'Avg'`) shows only at rest and yields to the hovered point's label on hover — pair it with a `value` that summarizes the series (average/total) so the headline reads as a summary until hovered. `hoverChangeFromPreviousPoint` keeps the supplied resting `change` pill at rest but, while hovering, swaps it for the hovered point's change vs the previous point (hidden at the first point).
- y-axis `format`: `numeric | short | percentage | percentage_scaled | currency | duration | duration-ms`, plus `prefix`/`suffix`.
- `onDateRangeZoom` (on `LineChart`/`TimeSeriesLineChart`/base `Chart`) enables x-axis drag-to-zoom: the user drags horizontally and the callback fires once with `{ startLabel, endLabel, startIndex, endIndex }` for the spanned range. The cursor switches to a crosshair when set. x-axis only — no effect on charts with a vertical interaction axis.
diff --git a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.stories.tsx b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.stories.tsx
index 30334149256a..d666518f1fbf 100644
--- a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.stories.tsx
+++ b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.stories.tsx
@@ -76,6 +76,30 @@ export const NoChange: Story = {
},
}
+export const RestingSummary: Story = {
+ render: () => {
+ const theme = useReactiveTheme()
+ const avg = Math.round(REVENUE.reduce((a, b) => a + b, 0) / REVENUE.length)
+ return (
+ <Stage width={360} height={320}>
+ <div className="rounded-xl border border-primary bg-surface-primary p-5 shadow-sm w-full h-full flex flex-col">
+ <MetricCard
+ title="Total Revenue"
+ value={avg}
+ restingSubtitle="Avg"
+ data={REVENUE}
+ labels={MONTHS}
+ theme={theme}
+ color="#22d3ee"
+ sparklineClassName="mt-4 -mx-5 -mb-5"
+ formatValue={(v) => `US$${Math.round(v).toLocaleString()}`}
+ />
+ </div>
+ </Stage>
+ )
+ },
+}
+
export const NumberOnly: Story = {
render: () => (
<Stage width={360} height={200}>
diff --git a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.test.tsx b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.test.tsx
index 62647bfdad9d..bd0d7a3e1d2b 100644
--- a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.test.tsx
+++ b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.test.tsx
@@ -224,6 +224,98 @@ describe('MetricCard', () => {
expect(container.textContent).toContain('Last 12 months')
expect(container.textContent).not.toContain('Apr')
})
+
+ it('shows restingSubtitle at rest and yields to the hovered point label on hover', () => {
+ const { container, chart } = renderHogChart(
+ <MetricCard
+ title="Revenue"
+ data={[100, 200, 300, 400]}
+ labels={LABELS}
+ theme={THEME}
+ animationMs={0}
+ hoverIntentMs={0}
+ restingSubtitle="Avg"
+ />
+ )
+ expect(container.textContent).toContain('Avg')
+ expect(container.textContent).not.toContain('Apr')
+ chart.hoverAtIndex(1)
+ expect(container.textContent).toContain('Feb')
+ expect(container.textContent).not.toContain('Avg')
+ })
+
+ it('lets a supplied subtitle win over restingSubtitle at rest and on hover', () => {
+ const { container, chart } = renderHogChart(
+ <MetricCard
+ title="Revenue"
+ data={[100, 200, 300, 400]}
+ labels={LABELS}
+ theme={THEME}
+ animationMs={0}
+ hoverIntentMs={0}
+ subtitle="Last 12 months"
+ restingSubtitle="Avg"
+ />
+ )
+ expect(container.textContent).toContain('Last 12 months')
+ expect(container.textContent).not.toContain('Avg')
+ chart.hoverAtIndex(1)
+ expect(container.textContent).toContain('Last 12 months')
+ })
+
+ it('with hoverChangeFromPreviousPoint, keeps the resting change but shows point-vs-previous on hover', () => {
+ const { container, chart } = renderHogChart(
+ <MetricCard
+ title="Revenue"
+ data={[100, 200, 300, 400]}
+ labels={LABELS}
+ theme={THEME}
+ animationMs={0}
+ hoverIntentMs={0}
+ change={{ value: 12.5, label: '+12.5% vs. prev period' }}
+ hoverChangeFromPreviousPoint
+ />
+ )
+ expect(container.textContent).toContain('+12.5% vs. prev period')
+ chart.hoverAtIndex(2) // 300 vs previous point 200 → +50%
+ expect(container.textContent).toContain('+50.0%')
+ expect(container.textContent).not.toContain('+12.5% vs. prev period')
+ })
+
+ it('with hoverChangeFromPreviousPoint, keeps the pill suppressed across hover when change is null', () => {
+ const { container, chart } = renderHogChart(
+ <MetricCard
+ title="Revenue"
+ data={[100, 200, 300, 400]}
+ labels={LABELS}
+ theme={THEME}
+ animationMs={0}
+ hoverIntentMs={0}
+ change={null}
+ hoverChangeFromPreviousPoint
+ />
+ )
+ expect(container.textContent).not.toContain('%')
+ chart.hoverAtIndex(2)
+ expect(container.textContent).not.toContain('%')
+ })
+
+ it('with hoverChangeFromPreviousPoint, hides the pill when hovering the first point', () => {
+ const { container, chart } = renderHogChart(
+ <MetricCard
+ title="Revenue"
+ data={[100, 200, 300, 400]}
+ labels={LABELS}
+ theme={THEME}
+ animationMs={0}
+ hoverIntentMs={0}
+ change={{ value: 12.5, label: '+12.5%' }}
+ hoverChangeFromPreviousPoint
+ />
+ )
+ chart.hoverAtIndex(0)
+ expect(container.textContent).not.toContain('%')
+ })
})
describe('number-only (no data)', () => {
@@ -307,11 +399,17 @@ describe('MetricCard', () => {
it('drops the fixed sparkline height when sparklineFill is set', () => {
const fixed = renderHogChart(
- <MetricCard title="Total" data={[100, 200]} labels={['Jan', 'Feb']} theme={THEME} sparklineHeight={120} />
- )
- expect((fixed.container.querySelector('[data-attr="metric-card-sparkline"]') as HTMLElement).style.height).toBe(
- '120px'
+ <MetricCard
+ title="Total"
+ data={[100, 200]}
+ labels={['Jan', 'Feb']}
+ theme={THEME}
+ sparklineHeight={120}
+ />
)
+ expect(
+ (fixed.container.querySelector('[data-attr="metric-card-sparkline"]') as HTMLElement).style.height
+ ).toBe('120px')
const filled = renderHogChart(
<MetricCard title="Total" data={[100, 200]} labels={['Jan', 'Feb']} theme={THEME} sparklineFill />
@@ -323,7 +421,13 @@ describe('MetricCard', () => {
it('renders the subtitle when provided and omits the row when empty', () => {
const withSubtitle = renderHogChart(
- <MetricCard title="Total" data={[100, 200]} labels={['Jan', 'Feb']} theme={THEME} subtitle="Last 7 days" />
+ <MetricCard
+ title="Total"
+ data={[100, 200]}
+ labels={['Jan', 'Feb']}
+ theme={THEME}
+ subtitle="Last 7 days"
+ />
)
expect(withSubtitle.container.querySelector('[data-attr="metric-card-subtitle"]')?.textContent).toBe(
'Last 7 days'
diff --git a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
index 5e4b383c52ae..878dcbc0a4f7 100644
--- a/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
+++ b/packages/quill/packages/charts/src/components/MetricCard/MetricCard.tsx
@@ -46,8 +46,16 @@ export interface MetricCardProps {
changeInline?: boolean
positiveColor?: ChangeColor
negativeColor?: ChangeColor
- /** Caption under the headline. Defaults to `labels[activeIndex]` when a sparkline is present. */
+ /** Caption under the headline. Defaults to `labels[activeIndex]` when a sparkline is present.
+ * Always wins — shown at rest and on hover. */
subtitle?: React.ReactNode
+ /** Caption shown only while at rest (e.g. `'Avg'`); on hover it yields to the hovered point's
+ * label. Ignored when `subtitle` is set. */
+ restingSubtitle?: React.ReactNode
+ /** While hovering a sparkline point, replace the resting `change` pill with the change from the
+ * previous point (`(data[i] - data[i-1]) / |data[i-1]|`). At the first point there is no previous,
+ * so the pill is hidden. The resting `change` (or fallback) still shows when not hovering. */
+ hoverChangeFromPreviousPoint?: boolean
animationMs?: number
/** Dwell (ms) a pointer must settle on the sparkline before the headline follows it.
* Keeps a quick pass-through from grabbing attention. `0` disables the gating. */
@@ -96,6 +104,8 @@ function MetricCardInner({
positiveColor = DEFAULT_POSITIVE_COLOR,
negativeColor = DEFAULT_NEGATIVE_COLOR,
subtitle,
+ restingSubtitle,
+ hoverChangeFromPreviousPoint = false,
animationMs = 350,
hoverIntentMs = 140,
className,
@@ -119,14 +129,26 @@ function MetricCardInner({
}
const liveValue = sparklineData ? (sparklineData[activeIndex] ?? 0) : restingValue
- const fallbackChangePercent =
- sparklineData == null || baselineValue == null
- ? null
- : ((liveValue - baselineValue) / Math.abs(baselineValue)) * 100
+ const usePrevPointHover = hoverChangeFromPreviousPoint && intentIndex >= 0 && sparklineData != null
+ const fallbackChangePercent = computeFallbackChangePercent(
+ sparklineData,
+ usePrevPointHover,
+ intentIndex,
+ liveValue,
+ baselineValue
+ )
- const delta = resolveDelta({ showChange, change, fallbackChangePercent, formatChange })
+ // A supplied `change` shows at rest; while hovering with `hoverChangeFromPreviousPoint` it yields to
+ // the point-vs-previous delta — except an explicit `null` (suppress) stays suppressed across hover.
+ const delta = resolveDelta({
+ showChange,
+ change: usePrevPointHover && change !== null ? undefined : change,
+ fallbackChangePercent,
+ formatChange,
+ })
const headlineDisplay = sparklineData ? formatValue(animatedValue) : formatValue(restingValue)
- const resolvedSubtitle = subtitle ?? labels?.[activeIndex]
+ const resolvedSubtitle =
+ subtitle ?? (intentIndex < 0 && restingSubtitle != null ? restingSubtitle : labels?.[activeIndex])
const positive = delta != null && delta.value >= 0
const isGood = goodDirection === 'up' ? positive : !positive
@@ -147,7 +169,12 @@ function MetricCardInner({
<div className={`flex items-start gap-2 ${headerJustify}`}>
{title != null && <div className="text-sm font-medium">{title}</div>}
{headerDelta != null && (
- <ChangePill positive={positive} label={headerDelta.label} colors={pillColors} size={changeSize} />
+ <ChangePill
+ positive={positive}
+ label={headerDelta.label}
+ colors={pillColors}
+ size={changeSize}
+ />
)}
</div>
)}
@@ -185,6 +212,38 @@ function MetricCardInner({
)
}
+// Percent change from the point before `index` to the point at `index`. Returns null when there is
+// no usable previous point (first index, missing/non-finite values, or a zero baseline).
+function changeFromPreviousPoint(data: number[], index: number): number | null {
+ const prev = data[index - 1]
+ const curr = data[index]
+ if (index < 1 || prev === 0 || !Number.isFinite(prev) || !Number.isFinite(curr)) {
+ return null
+ }
+ return ((curr - prev) / Math.abs(prev)) * 100
+}
+
+// The hover-driven change percent: the hovered point vs the previous point when
+// `hoverChangeFromPreviousPoint` is active, otherwise the live value vs the series baseline.
+function computeFallbackChangePercent(
+ sparklineData: number[] | null,
+ usePrevPointHover: boolean,
+ intentIndex: number,
+ liveValue: number,
+ baselineValue: number | undefined
+): number | null {
+ if (sparklineData == null) {
+ return null
+ }
+ if (usePrevPointHover) {
+ return changeFromPreviousPoint(sparklineData, intentIndex)
+ }
+ if (baselineValue == null) {
+ return null
+ }
+ return ((liveValue - baselineValue) / Math.abs(baselineValue)) * 100
+}
+
interface ChangePillProps {
positive: boolean
label: React.ReactNode
diff --git a/posthog/schema.py b/posthog/schema.py
index 02a7650b6539..cab16fb0d8a9 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -171,6 +171,7 @@ from posthog.schema_enums import (
MetaAdsTableKeywords as MetaAdsTableKeywords,
Method as Method,
Metric as Metric,
+ MetricSummary as MetricSummary,
MrrOrGross as MrrOrGross,
MultipleBreakdownType as MultipleBreakdownType,
MultipleVariantHandling as MultipleVariantHandling,
@@ -4291,8 +4292,21 @@ class AssistantTrendsFilter(BaseModel):
default=True,
description=(
"Only applies when `display` is `Metric`. Show the change pill next to the"
- " big number — the percentage change from the first to the last point of"
- " the series over the selected date range."
+ " big number. What it compares follows `metricSummary`: `total`/`average`"
+ ' compare against the previous period when "compare to previous" is on'
+ " (otherwise first→last of the series), and `latest` is always first→last"
+ " of the series."
+ ),
+ )
+ metricSummary: MetricSummary | None = Field(
+ default=MetricSummary.TOTAL,
+ description=(
+ "Only applies when `display` is `Metric`. Which summary the resting big"
+ " number shows: `total` (sum over the period), `average` (mean of the"
+ " points), or `latest` (last point). Hovering the sparkline always shows"
+ " the hovered point's value regardless of this setting. Also drives the"
+ " change pill: `total`/`average` compare against the previous period when"
+ ' "compare to previous" is on; `latest` compares first→last of the series.'
),
)
showAlertThresholdLines: bool | None = Field(
@@ -7779,6 +7793,16 @@ class TrendsFilter(BaseModel):
default=True,
description="Show the period-over-period change pill on the Metric display.",
)
+ metricSummary: MetricSummary | None = Field(
+ default=MetricSummary.TOTAL,
+ description=(
+ "Metric display: which summary the resting headline shows — the period"
+ " total, the average, or the latest point. Hovering the sparkline always"
+ " shows the hovered point's value. Also drives the change pill:"
+ ' total/average compare against the previous period when "compare to'
+ ' previous" is on; latest compares first→last of the series.'
+ ),
+ )
minDecimalPlaces: float | None = None
movingAverageIntervals: float | None = None
resultCustomizationBy: ResultCustomizationBy | None = Field(
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 451f88f7e166..a0a1e635ca96 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -441,6 +441,12 @@ class Display(StrEnum):
SLOPE_GRAPH = "SlopeGraph"
+class MetricSummary(StrEnum):
+ TOTAL = "total"
+ AVERAGE = "average"
+ LATEST = "latest"
+
+
class YAxisScaleType(StrEnum):
LOG10 = "log10"
LINEAR = "linear"
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index dca2d6e94203..f97a4abf3eb4 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -2056,6 +2056,14 @@ export interface GoalLineApi {
value: number
}
+export type MetricSummaryApi = (typeof MetricSummaryApi)[keyof typeof MetricSummaryApi]
+
+export const MetricSummaryApi = {
+ Total: 'total',
+ Average: 'average',
+ Latest: 'latest',
+} as const
+
export type ResultCustomizationByApi = (typeof ResultCustomizationByApi)[keyof typeof ResultCustomizationByApi]
export const ResultCustomizationByApi = {
@@ -2153,6 +2161,8 @@ export interface TrendsFilterApi {
metricLineIncreaseColor?: string | null
/** Show the period-over-period change pill on the Metric display. */
metricShowChange?: boolean | null
+ /** Metric display: which summary the resting headline shows — the period total, the average, or the latest point. Hovering the sparkline always shows the hovered point's value. Also drives the change pill: total/average compare against the previous period when "compare to previous" is on; latest compares first→last of the series. */
+ metricSummary?: MetricSummaryApi | null
minDecimalPlaces?: number | null
movingAverageIntervals?: number | null
/** Wether result datasets are associated by their values or by their order. */
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index e7096b3d2650..a5480b836761 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -1481,6 +1481,14 @@ export interface GoalLineApi {
value: number
}
+export type MetricSummaryApi = (typeof MetricSummaryApi)[keyof typeof MetricSummaryApi]
+
+export const MetricSummaryApi = {
+ Total: 'total',
+ Average: 'average',
+ Latest: 'latest',
+} as const
+
export type ResultCustomizationByApi = (typeof ResultCustomizationByApi)[keyof typeof ResultCustomizationByApi]
export const ResultCustomizationByApi = {
@@ -1578,6 +1586,8 @@ export interface TrendsFilterApi {
metricLineIncreaseColor?: string | null
/** Show the period-over-period change pill on the Metric display. */
metricShowChange?: boolean | null
+ /** Metric display: which summary the resting headline shows — the period total, the average, or the latest point. Hovering the sparkline always shows the hovered point's value. Also drives the change pill: total/average compare against the previous period when "compare to previous" is on; latest compares first→last of the series. */
+ metricSummary?: MetricSummaryApi | null
minDecimalPlaces?: number | null
movingAverageIntervals?: number | null
/** Wether result datasets are associated by their values or by their order. */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index a282109d3220..ef772c8a1805 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -2299,6 +2299,15 @@ export namespace Schemas {
value: number;
}
+ export type MetricSummary = typeof MetricSummary[keyof typeof MetricSummary];
+
+
+ export const MetricSummary = {
+ Total: 'total',
+ Average: 'average',
+ Latest: 'latest',
+ } as const;
+
export type ResultCustomizationBy = typeof ResultCustomizationBy[keyof typeof ResultCustomizationBy];
@@ -2396,6 +2405,8 @@ export namespace Schemas {
metricLineIncreaseColor?: string | null;
/** Show the period-over-period change pill on the Metric display. */
metricShowChange?: boolean | null;
+ /** Metric display: which summary the resting headline shows — the period total, the average, or the latest point. Hovering the sparkline always shows the hovered point's value. Also drives the change pill: total/average compare against the previous period when "compare to previous" is on; latest compares first→last of the series. */
+ metricSummary?: MetricSummary | null;
minDecimalPlaces?: number | null;
movingAverageIntervals?: number | null;
/** Wether result datasets are associated by their values or by their order. */
diff --git a/services/mcp/src/tools/generated/query-wrappers.ts b/services/mcp/src/tools/generated/query-wrappers.ts
index 03449d4c31fa..68ab52a0bb45 100644
--- a/services/mcp/src/tools/generated/query-wrappers.ts
+++ b/services/mcp/src/tools/generated/query-wrappers.ts
@@ -557,10 +557,17 @@ const AssistantTrendsFilter = z.object({
metricShowChange: z.coerce
.boolean()
.describe(
- 'Only applies when `display` is `Metric`. Show the change pill next to the big number — the percentage change from the first to the last point of the series over the selected date range.'
+ 'Only applies when `display` is `Metric`. Show the change pill next to the big number. What it compares follows `metricSummary`: `total`/`average` compare against the previous period when "compare to previous" is on (otherwise first→last of the series), and `latest` is always first→last of the series.'
)
.default(true)
.optional(),
+ metricSummary: z
+ .enum(['total', 'average', 'latest'])
+ .describe(
+ 'Only applies when `display` is `Metric`. Which summary the resting big number shows: `total` (sum over the period), `average` (mean of the points), or `latest` (last point). Hovering the sparkline always shows the hovered point\'s value regardless of this setting. Also drives the change pill: `total`/`average` compare against the previous period when "compare to previous" is on; `latest` compares first→last of the series.'
+ )
+ .default('total')
+ .optional(),
showAlertThresholdLines: z.coerce
.boolean()
.describe('Whether to show alert threshold lines on the chart.')
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
index f3327f8199df..950b15bba4c3 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends-actors.json
@@ -3856,9 +3856,15 @@
},
"metricShowChange": {
"default": true,
- "description": "Only applies when `display` is `Metric`. Show the change pill next to the big number — the percentage change from the first to the last point of the series over the selected date range.",
+ "description": "Only applies when `display` is `Metric`. Show the change pill next to the big number. What it compares follows `metricSummary`: `total`/`average` compare against the previous period when \"compare to previous\" is on (otherwise first→last of the series), and `latest` is always first→last of the series.",
"type": "boolean"
},
+ "metricSummary": {
+ "default": "total",
+ "description": "Only applies when `display` is `Metric`. Which summary the resting big number shows: `total` (sum over the period), `average` (mean of the points), or `latest` (last point). Hovering the sparkline always shows the hovered point's value regardless of this setting. Also drives the change pill: `total`/`average` compare against the previous period when \"compare to previous\" is on; `latest` compares first→last of the series.",
+ "enum": ["total", "average", "latest"],
+ "type": "string"
+ },
"showAlertThresholdLines": {
"default": false,
"description": "Whether to show alert threshold lines on the chart.",
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
index 8ddcc486228f..6d7945975f9f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-trends.json
@@ -3668,9 +3668,15 @@
},
"metricShowChange": {
"default": true,
- "description": "Only applies when `display` is `Metric`. Show the change pill next to the big number — the percentage change from the first to the last point of the series over the selected date range.",
+ "description": "Only applies when `display` is `Metric`. Show the change pill next to the big number. What it compares follows `metricSummary`: `total`/`average` compare against the previous period when \"compare to previous\" is on (otherwise first→last of the series), and `latest` is always first→last of the series.",
"type": "boolean"
},
+ "metricSummary": {
+ "default": "total",
+ "description": "Only applies when `display` is `Metric`. Which summary the resting big number shows: `total` (sum over the period), `average` (mean of the points), or `latest` (last point). Hovering the sparkline always shows the hovered point's value regardless of this setting. Also drives the change pill: `total`/`average` compare against the previous period when \"compare to previous\" is on; `latest` compares first→last of the series.",
+ "enum": ["total", "average", "latest"],
+ "type": "string"
+ },
"showAlertThresholdLines": {
"default": false,
"description": "Whether to show alert threshold lines on the chart.",