:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metrics): add stat, gauge, bar gauge, and table dashboard panels (#99312)
Daniel Visca6eff9416895c
diff --git a/docs/internal/metrics-dashboard-panels.md b/docs/internal/metrics-dashboard-panels.mdnew file mode 100644index 000000000000..5a2fdf9a5e28--- /dev/null+++ b/docs/internal/metrics-dashboard-panels.md@@ -0,0 +1,39 @@+# Metrics dashboard panels++The metrics viewer and metrics dashboard tiles render one of several panel types, picked from the chart-type dropdown.+The picker lists the time-series panels (line, area, bar) plus the Grafana-style scalar and categorical panels (stat, gauge, bar gauge, table).+The scalar panels are gated behind the `metrics-dashboard-panels` feature flag.++Every panel reads the same response: a list of series, each with a label set, bucketed points, and an optional UCUM unit.++## How a panel collapses points to a number++Scalar panels (stat, gauge, bar gauge) and the table's reducer columns collapse each series to one number with a reducer: `last`, `mean`, `min`, `max`, `sum`, or `delta` (last minus first).+The `reduce` display setting chooses the reducer; the deprecated `statSummary` maps onto it (`latest` → `last`, `average` → `mean`, `total` → `sum`).+A series whose buckets are all null reduces to null and is dropped by the scalar panels, so a tile shows "No data" instead of a dash.++## Units++The display `unit` setting overrides everything.+Without it, a series renders with its ingested UCUM unit — but only when no other series in the same tile carries a different unit.+A tile mixes every series' values on one chart, so a mixed-unit result renders bare numbers rather than mislabel one series with another's unit.+UCUM `1` (dimensionless) renders as a plain number: it is not necessarily a ratio, so it is never rescaled to a percent.++## Thresholds++Thresholds color the scalar panels and the table's value cells.+Each step is a lower bound with a color token; the lowest step is the base color.+They are a color scale, not the range: the gauge's automatic max extends past the highest threshold when the value does, so the arc never reads full while the number keeps climbing.++## Panel-specific rules++- **Stat**: one headline card per series (capped at 12) with a sparkline.+- **Gauge**: one radial gauge per series (capped at 12). Bounds come from the explicit y-axis min/max, else the threshold extremes, else 0 to the value.+- **Bar gauge**: one bar per series, sorted by value. It needs grouped data to be meaningful, so the picker disables it unless the result is grouped; removing the last group-by falls the display back to line.+- **Table**: one row per series, one column per label key, plus one column per reducer in `legendCalcs`. The list is deduplicated and capped at six reducers — it is persisted user input from saved insights.++## Null buckets++A null bucket is a non-representable aggregate (a gap).+The time-series panel renders it as 0 until the chart library takes null data; `nullMode` is read by the chart config, not the panel.+The reducers skip nulls rather than counting them as zero, so a gap never drags a `mean` down.diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 5a6dddacbf19..4c0f73fd86e8 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -405,6 +405,7 @@ export const FEATURE_FLAGS = {MEMBER_BILLING_USAGE_SPEND_READ_ACCESS: 'member-billing-usage-spend-read-access', // owner: @pawelcebula #team-billing, grants members read-only access to billing usage/spend tabs; owner-only-billing takes precedenceMESSAGING_SES: 'messaging-ses', // owner #team-workflowsMETRICS: 'metrics', // owner: #team-apm (@jonmcwest, @frankh)+ METRICS_DASHBOARD_PANELS: 'metrics-dashboard-panels', // owner: #team-apm — gates the stat/gauge/bargauge/table panel picker entriesMETRICS_ERROR_OVERLAYS: 'metrics-error-overlays', // owner: #team-apm — gates the error-spike overlay PoC on metrics chartsMETRICS_FUNDAMENTALS: 'metrics-fundamentals', // owner: #team-apm (@jonmcwest, @frankh), gates the Fundamentals tab and the explain API behind it, which check the metrics viewer's own reductionsNEW_TAB_PROJECT_EXPLORER: 'new-tab-project-explorer', // owner: #team-platform-uxdiff --git a/products/metrics/frontend/components/MetricsViewer.tsx b/products/metrics/frontend/components/MetricsViewer.tsxindex 974fa4ee554a..259d3af1da2b 100644--- a/products/metrics/frontend/components/MetricsViewer.tsx+++ b/products/metrics/frontend/components/MetricsViewer.tsx@@ -29,6 +29,8 @@ import { AccessControlLevel, AccessControlResourceType, DateMappingOption } fromimport { traceUrl } from 'products/tracing/frontend/traceLinks'import { getMetricsInsightEditorDisabledReason } from '../metricsAccess'+import { MetricsPanel } from '../panels/MetricsPanel'+import { METRICS_PANELS } from '../panels/registry'import { MetricsAnomalyPanel } from './MetricsAnomalyPanel'import { MetricsChartSettings } from './MetricsChartSettings'import { MetricsClauseRow } from './MetricsClauseRow'@@ -37,18 +39,13 @@ import { MetricsLogsSourceTag } from './MetricsLogsSourceTag'import { MetricsRelatedMenu } from './MetricsRelatedMenu'import { metricsSamplesLogic } from './metricsSamplesLogic'import { MetricsSamplesPanel } from './MetricsSamplesPanel'-import { MetricsSeriesChart } from './MetricsSeriesChart'import { metricsStarterDashboardLogic } from './metricsStarterDashboardLogic'import { MetricsStarterDashboardModal } from './MetricsStarterDashboardModal'import { metricsUsageTrackingLogic } from './metricsUsageTrackingLogic'import { LIVE_REFRESH_MS, MAX_CLAUSES, metricsViewerLogic, sanitizeFormulaInput } from './metricsViewerLogic'-// `stat` is in the schema but has no renderer yet, so the picker doesn't offer it.-const DISPLAY_TYPE_OPTIONS: { value: MetricsDisplayType; label: string }[] = [- { value: 'line', label: 'Line' },- { value: 'area', label: 'Area' },- { value: 'bar', label: 'Bar' },-]+const BASE_DISPLAY_TYPES: MetricsDisplayType[] = ['line', 'area', 'bar']+const PANEL_DISPLAY_TYPES: MetricsDisplayType[] = ['stat', 'gauge', 'bargauge', 'table']// Mirrors the curated set used by `LogsViewer/Filters/DateRangeFilter`.const DATE_OPTIONS: DateMappingOption[] = [@@ -131,6 +128,20 @@ export const MetricsViewer = (): JSX.Element => {const { toggleShowErrorSpikes } = useActions(metricsSamplesLogic)// Staff-only PoC gate, layered on top of the wider metrics alpha flag.const errorOverlaysEnabled = useFeatureFlag('METRICS_ERROR_OVERLAYS')+ // Grafana-style scalar/categorical panels. Flag-gated; the registry describes each panel.+ const dashboardPanelsEnabled = useFeatureFlag('METRICS_DASHBOARD_PANELS')++ // Gate on the result shape, not the clause edits: a formula result is ungrouped even+ // when its input clauses group, and a clause without a metric name never runs.+ const resultIsGrouped = chartSeries.some((s) => Object.keys(s.labels).length > 0)+ const displayTypeOptions = useMemo(() => {+ const types = dashboardPanelsEnabled ? [...BASE_DISPLAY_TYPES, ...PANEL_DISPLAY_TYPES] : BASE_DISPLAY_TYPES+ return types.map((value) => {+ const def = METRICS_PANELS[value]+ const disabledReason = def.needsGroupBy && !resultIsGrouped ? 'Add a group-by to use this panel' : undefined+ return { value, label: def.label, disabledReason }+ })+ }, [dashboardPanelsEnabled, resultIsGrouped])const { exemplarDotClicked } = useActions(metricsUsageTrackingLogic)const metricsViewerDisabledReason = getAccessControlDisabledReason(AccessControlResourceType.Metrics,@@ -289,7 +300,7 @@ export const MetricsViewer = (): JSX.Element => {<LemonSelectsize="small"value={displayType}- options={DISPLAY_TYPE_OPTIONS}+ options={displayTypeOptions}onChange={setDisplayType}data-attr="metrics-viewer-display-type"disabledReason={metricsViewerDisabledReason}@@ -378,7 +389,7 @@ export const MetricsViewer = (): JSX.Element => {</LemonBanner></div>) : hasResults ? (- <MetricsSeriesChart+ <MetricsPanelseries={chartSeries}fallbackName={formula || metricName || 'metric'}display={metricsDisplay}diff --git a/products/metrics/frontend/components/metricsSeries.ts b/products/metrics/frontend/components/metricsSeries.tsindex bcb82f53b5b8..a8e637e56910 100644--- a/products/metrics/frontend/components/metricsSeries.ts+++ b/products/metrics/frontend/components/metricsSeries.ts@@ -8,6 +8,8 @@ export interface MetricsChartSeries {metricName?: string | null/** Alias of the query clause that produced this series (`formula` for a formula result). */clause?: string | null+ /** UCUM unit as ingested, e.g. "By", "ms". Absent when the SDK did not set one. */+ unit?: string | null}// PostHog defines data-color-1..15 in vars.scss; cycle through them so each series gets a distinct line.diff --git a/products/metrics/frontend/components/metricsViewerLogic.test.ts b/products/metrics/frontend/components/metricsViewerLogic.test.tsindex f4b9ece33396..a094e8dd699d 100644--- a/products/metrics/frontend/components/metricsViewerLogic.test.ts+++ b/products/metrics/frontend/components/metricsViewerLogic.test.ts@@ -375,6 +375,48 @@ describe('metricsViewerLogic', () => {expect(insightsApi.create).toHaveBeenCalledTimes(2)})+ // A group-by-requiring panel must not stay selected once nothing is grouped anymore:+ // the bar gauge would otherwise render a single bar for an ungrouped result.+ it('falls back to the default display when the last group-by is removed', () => {+ logic.actions.setMetricName('queue_depth')+ logic.actions.setGroupByKeys(['container'])+ logic.actions.setDisplayType('bargauge')+ expect(logic.values.displayType).toBe('bargauge')++ logic.actions.setGroupByKeys([])+ expect(logic.values.displayType).toBe('line')+ })++ it('keeps a group-by panel when a group-by is still present', () => {+ logic.actions.setMetricName('queue_depth')+ logic.actions.setGroupByKeys(['container'])+ logic.actions.setDisplayType('bargauge')++ logic.actions.setGroupByKeys(['namespace'])+ expect(logic.values.displayType).toBe('bargauge')+ })++ // A group-by-requiring panel must not stay selected once nothing is grouped anymore:+ // the bar gauge would otherwise render a single bar for an ungrouped result.+ it('falls back to the default display when the last group-by is removed', () => {+ logic.actions.setMetricName('queue_depth')+ logic.actions.setGroupByKeys(['container'])+ logic.actions.setDisplayType('bargauge')+ expect(logic.values.displayType).toBe('bargauge')++ logic.actions.setGroupByKeys([])+ expect(logic.values.displayType).toBe('line')+ })++ it('keeps a group-by panel when a group-by is still present', () => {+ logic.actions.setMetricName('queue_depth')+ logic.actions.setGroupByKeys(['container'])+ logic.actions.setDisplayType('bargauge')++ logic.actions.setGroupByKeys(['namespace'])+ expect(logic.values.displayType).toBe('bargauge')+ })+it('carries the configured chart settings onto the saved node', () => {logic.actions.setMetricName('queue_depth')logic.actions.setDisplayType('bar')diff --git a/products/metrics/frontend/components/metricsViewerLogic.tsx b/products/metrics/frontend/components/metricsViewerLogic.tsxindex f9a9fd203b7e..566dad42129a 100644--- a/products/metrics/frontend/components/metricsViewerLogic.tsx+++ b/products/metrics/frontend/components/metricsViewerLogic.tsx@@ -54,6 +54,7 @@ import type { _MetricPickerNameApi } from '../generated/api.schemas'import { type MetricTopMoverRow, topMoverRows } from '../metricsAnomaly'import { EMPTY_SERVICE_PATTERN, SERVICE_NAME_KEY } from '../metricsAttributes'import { correlationServiceNames } from '../metricsLinks'+import { METRICS_PANELS } from '../panels/registry'import { metricNamePickerLogic } from './metricNamePickerLogic'import type { MetricNameItem } from './metricNamePickerLogic'import type { MetricsChartSeries } from './metricsSeries'@@ -966,6 +967,18 @@ export const metricsViewerLogic = kea<metricsViewerLogicType>([}}return {+ // A panel whose registry entry needs grouped data cannot stay selected once nothing+ // is grouped anymore — fall back rather than render it against a result shape it+ // does not support.+ setGroupByKeys: ({ groupByKeys }) => {+ if (+ groupByKeys.length === 0 &&+ !values.viewerClauses.some((clause) => clause.groupByKeys.length > 0) &&+ METRICS_PANELS[values.displayType]?.needsGroupBy+ ) {+ actions.setDisplayType(DEFAULT_DISPLAY_TYPE)+ }+ },// `setFilterGroup` changes the active clause's chips; the clause-navigation// actions change which clause's chips are the scope.setFilterGroup: syncPickerServices,diff --git a/products/metrics/frontend/nodes/MetricsQueryNode.tsx b/products/metrics/frontend/nodes/MetricsQueryNode.tsxindex 1a9d2c37f4c5..0166324f3418 100644--- a/products/metrics/frontend/nodes/MetricsQueryNode.tsx+++ b/products/metrics/frontend/nodes/MetricsQueryNode.tsx@@ -9,7 +9,7 @@ import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'import { AnyResponseType, MetricsQuery } from '~/queries/schema/schema-general'import { QueryContext } from '~/queries/types'-import { MetricsSeriesChart } from '../components/MetricsSeriesChart'+import { MetricsPanel } from '../panels/MetricsPanel'import { seriesFromMetricsResponse } from './metricsResponseSeries'let uniqueNode = 0@@ -54,7 +54,7 @@ export function MetricsQueryNode(props: {return (<div className="relative flex flex-col w-full h-full min-h-[200px]">{hasPoints ? (- <MetricsSeriesChart series={series} fallbackName={fallbackName} display={props.query.display} />+ <MetricsPanel series={series} fallbackName={fallbackName} display={props.query.display} />) : !responseLoading ? (<div className="flex-1 flex items-center justify-center text-secondary text-sm">No data for this metric in the selected range.diff --git a/products/metrics/frontend/panels/BarGaugePanel.tsx b/products/metrics/frontend/panels/BarGaugePanel.tsxnew file mode 100644index 000000000000..50d9ee9bef0a--- /dev/null+++ b/products/metrics/frontend/panels/BarGaugePanel.tsx@@ -0,0 +1,78 @@+import { useMemo } from 'react'++import { BarChart } from '@posthog/quill-charts'++import { useChartTheme } from 'lib/charts/hooks'+import { getColorVar } from 'lib/colors'++import { flattenSeriesRows } from './metricsReduce'+import { thresholdColor } from './metricsThresholds'+import { formatMetricValue } from './metricsUnits'+import type { MetricsPanelProps } from './registry'+import { resolveReducer } from './registry'++const FALLBACK_COLOR = 'data-color-1'++/** One horizontal bar per series, sorted descending, colored by threshold. Grafana's+ * "top N by value". Needs a groupBy to be meaningful; the picker gates on that. */+export function BarGaugePanel({ series, display, fallbackName }: MetricsPanelProps): JSX.Element {+ const theme = useChartTheme()+ const reducer = resolveReducer(display)++ const rows = useMemo(+ () =>+ flattenSeriesRows(series, [reducer])+ .filter((row) => row.values[reducer] !== null)+ .sort((a, b) => (b.values[reducer] ?? 0) - (a.values[reducer] ?? 0)),+ [series, reducer]+ )++ const chartSeries = useMemo(+ () => [+ {+ key: 'value',+ label: fallbackName,+ data: rows.map((row) => row.values[reducer] ?? 0),+ color: getColorVar(FALLBACK_COLOR),+ // Per-bar threshold colors.+ bars: rows.map((row) => ({+ color: getColorVar(thresholdColor(row.values[reducer] ?? null, display.thresholds, FALLBACK_COLOR)),+ })),+ },+ ],+ [rows, reducer, fallbackName, display.thresholds]+ )+ const labels = useMemo(+ () =>+ rows.map(+ (row) =>+ Object.entries(row.labels)+ .map(([k, v]) => `${k}=${v}`)+ .join(', ') ||+ row.metricName ||+ fallbackName+ ),+ [rows, fallbackName]+ )++ if (rows.length === 0) {+ return <div className="flex h-full items-center justify-center text-secondary text-sm">No data</div>+ }++ return (+ <div className="relative flex h-full w-full min-h-0 flex-col">+ <BarChart+ series={chartSeries}+ labels={labels}+ theme={theme}+ tooltip={(ctx) => {+ const row = rows[ctx.dataIndex]+ if (!row) {+ return null+ }+ return <span>{formatMetricValue(row.values[reducer] ?? 0, row.series.unit ?? undefined)}</span>+ }}+ />+ </div>+ )+}diff --git a/products/metrics/frontend/panels/GaugePanel.tsx b/products/metrics/frontend/panels/GaugePanel.tsxnew file mode 100644index 000000000000..0bfb365b9f19--- /dev/null+++ b/products/metrics/frontend/panels/GaugePanel.tsx@@ -0,0 +1,128 @@+import { getColorVar } from 'lib/colors'++import { flattenSeriesRows } from './metricsReduce'+import { thresholdColor } from './metricsThresholds'+import { formatMetricValue } from './metricsUnits'+import type { MetricsPanelProps } from './registry'+import { resolveReducer } from './registry'++const FALLBACK_COLOR = 'data-color-1'++/** The arc spans 240 degrees (a typical gauge sweep), from -210° to 30°. */+const ARC_START_DEG = -210+const ARC_SWEEP_DEG = 240++function polarToCartesian(cx: number, cy: number, r: number, deg: number): [number, number] {+ const rad = (deg * Math.PI) / 180+ return [cx + r * Math.cos(rad), cy + r * Math.sin(rad)]+}++function arcPath(cx: number, cy: number, r: number, fromDeg: number, toDeg: number): string {+ const [x0, y0] = polarToCartesian(cx, cy, r, fromDeg)+ const [x1, y1] = polarToCartesian(cx, cy, r, toDeg)+ const largeArc = toDeg - fromDeg > 180 ? 1 : 0+ return `M ${x0} ${y0} A ${r} ${r} 0 ${largeArc} 1 ${x1} ${y1}`+}++/** The extreme of a threshold list, computed iteratively: thresholds are persisted+ * user input, so spreading them into `Math.max` could exceed the argument limit. */+function thresholdExtreme(thresholds: { value: number }[], pick: (a: number, b: number) => number): number | undefined {+ let extreme: number | undefined+ for (const step of thresholds) {+ extreme = extreme === undefined ? step.value : pick(extreme, step.value)+ }+ return extreme+}++/** Bounds for the arc: explicit yAxis min/max first, else the threshold extremes, else 0..value.+ * The bounds always contain the value — a threshold ladder that ends below it is a color+ * scale, not the range, so the max extends to the value rather than capping the arc. */+function gaugeBounds(value: number, display: MetricsPanelProps['display']): { min: number; max: number } {+ const thresholds = display.thresholds ?? []+ const min = display.yAxis?.min ?? thresholdExtreme(thresholds, Math.min) ?? 0+ const max =+ display.yAxis?.max ??+ Math.max(thresholdExtreme(thresholds, Math.max) ?? Number.NEGATIVE_INFINITY, value, min + 1)+ return max > min ? { min, max } : { min, max: min + 1 }+}++/** A single-series radial gauge: the reduced value drawn as an arc between a min and a max,+ * colored by threshold. Grouped queries render one gauge per series, capped. */+export function GaugePanel({ series, display, fallbackName }: MetricsPanelProps): JSX.Element {+ const reducer = resolveReducer(display)+ // A series with no non-null point has nothing to draw; drop it like the other+ // scalar panels rather than render a dash gauge.+ const rows = flattenSeriesRows(series, [reducer])+ .filter((row) => row.values[reducer] !== null)+ .slice(0, 12)++ if (rows.length === 0) {+ return <div className="flex h-full items-center justify-center text-secondary text-sm">No data</div>+ }++ return (+ <div className="flex h-full w-full flex-wrap content-center items-center justify-center gap-4 overflow-auto p-2">+ {rows.map((row, index) => {+ const value = row.values[reducer] ?? null+ const unit = row.series.unit ?? undefined+ const { min, max } = gaugeBounds(value ?? 0, display)+ const fraction = value === null ? 0 : Math.min(Math.max((value - min) / (max - min), 0), 1)+ const color = getColorVar(thresholdColor(value, display.thresholds, FALLBACK_COLOR))+ const name =+ Object.entries(row.labels)+ .map(([k, v]) => `${k}=${v}`)+ .join(', ') ||+ row.metricName ||+ fallbackName++ const cx = 60+ const cy = 60+ const r = 48+ return (+ <div key={index} className="flex flex-col items-center" title={name}>+ <svg width="120" height="100" viewBox="0 0 120 100" role="img" aria-label={`${name} gauge`}>+ {/* track */}+ <path+ d={arcPath(cx, cy, r, ARC_START_DEG, ARC_START_DEG + ARC_SWEEP_DEG)}+ fill="none"+ stroke="var(--color-graph-axis-line)"+ strokeWidth="10"+ strokeLinecap="round"+ />+ {/* value */}+ {fraction > 0 && (+ <path+ d={arcPath(cx, cy, r, ARC_START_DEG, ARC_START_DEG + ARC_SWEEP_DEG * fraction)}+ fill="none"+ stroke={color}+ strokeWidth="10"+ strokeLinecap="round"+ />+ )}+ <text+ x={cx}+ y={cy + 4}+ textAnchor="middle"+ fontSize="16"+ fontWeight="600"+ fill="currentColor"+ >+ {value === null ? '—' : formatMetricValue(value, unit)}+ </text>+ <text+ x={cx}+ y={cy + 22}+ textAnchor="middle"+ fontSize="9"+ fill="var(--color-graph-axis-label)"+ >+ {formatMetricValue(min, unit)} – {formatMetricValue(max, unit)}+ </text>+ </svg>+ <span className="text-xs text-secondary max-w-[120px] truncate">{name}</span>+ </div>+ )+ })}+ </div>+ )+}diff --git a/products/metrics/frontend/panels/MetricsPanel.test.tsx b/products/metrics/frontend/panels/MetricsPanel.test.tsxnew file mode 100644index 000000000000..ee33e6308b59--- /dev/null+++ b/products/metrics/frontend/panels/MetricsPanel.test.tsx@@ -0,0 +1,198 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'++import {+ createDefaultTooltipAccessor,+ ensureJsdom,+ getHogChart,+ hoverUntilTooltip,+} from '@posthog/quill-charts/testing'++import type { MetricsDisplaySettings } from '~/queries/schema/schema-general'+import { initKeaTests } from '~/test/init'++import type { MetricsExemplar } from '../components/MetricsExemplarMarkers'+import type { MetricsChartSeries } from '../components/metricsSeries'+import { MetricsPanel } from './MetricsPanel'++const BUCKETS = ['2026-08-01T10:00:00Z', '2026-08-01T11:00:00Z', '2026-08-01T12:00:00Z']++function seriesWith(+ labels: Record<string, string>,+ values: (number | null)[],+ metricName?: string,+ unit?: string+): MetricsChartSeries {+ return { labels, points: BUCKETS.map((time, i) => ({ time, value: values[i] })), metricName, unit }+}++function renderPanel(+ series: MetricsChartSeries[],+ display?: MetricsDisplaySettings,+ exemplars?: MetricsExemplar[]+): void {+ render(<MetricsPanel series={series} fallbackName="http.requests" display={display} exemplars={exemplars} />)+}++describe('MetricsPanel', () => {+ describe('time-series (line/area/bar)', () => {+ beforeEach(() => {+ ensureJsdom()+ initKeaTests()+ })++ afterEach(() => cleanup())++ it('draws one line per series by default', () => {+ renderPanel([seriesWith({ service: 'checkout' }, [1, 2, 3]), seriesWith({ service: 'billing' }, [4, 5, 6])])+ expect(getHogChart().seriesCount).toBe(2)+ })++ it.each([+ ['renders no display as a line chart', undefined, 'line'],+ ['renders the area display as a line chart', 'area' as const, 'line'],+ ['renders the bar display as a bar chart', 'bar' as const, 'bar'],+ ])('%s', (_name, type, expectedChart) => {+ renderPanel([seriesWith({ service: 'a' }, [1, 2, 3]), seriesWith({ service: 'b' }, [4, 5, 6])], { type })+ expect(getHogChart().seriesCount).toBe(2)+ expect(screen.getByTestId(`hog-chart-timeseries-${expectedChart}-legend`)).toBeInTheDocument()+ })++ it('falls back to a line chart for an unknown display type', () => {+ renderPanel([seriesWith({ service: 'a' }, [1, 2, 3])], { type: 'pie' as never })+ expect(getHogChart().seriesCount).toBe(1)+ })++ it('renders a clickable dot per traced exemplar', () => {+ renderPanel([seriesWith({}, [1, 2, 3])], undefined, [+ { timeMs: Date.parse(BUCKETS[1]), onClick: jest.fn(), tooltipLabel: 'test exemplar' },+ ])+ expect(screen.getAllByTestId('metrics-exemplar-marker')).toHaveLength(1)+ })++ // A null bucket is a non-representable aggregate. quill draws only numbers, so it renders as 0+ // until the quill null-data change; dropping it would shift later values a bucket left.+ it('charts a null bucket as zero rather than dropping the point', async () => {+ renderPanel([seriesWith({}, [1, null, 3])])+ const chart = getHogChart()+ const tooltip = createDefaultTooltipAccessor(await hoverUntilTooltip(chart.element, 1, BUCKETS.length))+ expect(tooltip.value('http.requests')).toBe('0')+ })++ it('draws a goal line above the data', () => {+ renderPanel([seriesWith({}, [1, 2, 3])], { goalLines: [{ label: 'SLO', value: 10 }] })+ expect(screen.getByText('SLO')).toBeInTheDocument()+ })+ })++ describe('scalar and categorical panels', () => {+ beforeEach(() => {+ ensureJsdom()+ initKeaTests()+ })++ afterEach(() => cleanup())++ it('renders the stat headline with the resolved unit', () => {+ renderPanel([seriesWith({}, [100, 200, 340], 'http.duration', 'ms')], { type: 'stat' })+ expect(screen.getByText('340 ms')).toBeInTheDocument()+ })++ it('stat uses the reduce reducer', () => {+ renderPanel([seriesWith({}, [100, 200, 340], 'm', 'ms')], { type: 'stat', reduce: 'max' })+ expect(screen.getByText('340 ms')).toBeInTheDocument()+ })++ it('stat maps the deprecated statSummary', () => {+ renderPanel([seriesWith({}, [100, 200, 300], 'm', 'ms')], { type: 'stat', statSummary: 'average' })+ expect(screen.getByText('200 ms')).toBeInTheDocument()+ })++ it('renders one stat card per grouped series', () => {+ renderPanel([seriesWith({ service: 'a' }, [1, 2, 3]), seriesWith({ service: 'b' }, [4, 5, 6])], {+ type: 'stat',+ })+ expect(screen.getByText('service=a')).toBeInTheDocument()+ expect(screen.getByText('service=b')).toBeInTheDocument()+ })++ it('renders the table panel with label and reducer columns', () => {+ renderPanel([seriesWith({ service: 'api', pod: 'p1' }, [10, 20, 30])], { type: 'table', reduce: 'last' })+ expect(screen.getByText('service')).toBeInTheDocument()+ expect(screen.getByText('pod')).toBeInTheDocument()+ expect(screen.getByText('api')).toBeInTheDocument()+ expect(screen.getByText('30')).toBeInTheDocument()+ })++ it('renders the gauge arc with a formatted value and bounds', () => {+ renderPanel([seriesWith({}, [0, 0, 40], 'cpu', '%')], {+ type: 'gauge',+ yAxis: { min: 0, max: 100 },+ })+ expect(screen.getByText('40%')).toBeInTheDocument()+ expect(screen.getByText('0% – 100%')).toBeInTheDocument()+ })++ it('renders the bar gauge with one bar per grouped series', () => {+ renderPanel([seriesWith({ pod: 'a' }, [1, 2, 10]), seriesWith({ pod: 'b' }, [1, 2, 20])], {+ type: 'bargauge',+ })+ expect(getHogChart().seriesCount).toBe(1)+ expect(screen.getByText('pod=a')).toBeInTheDocument()+ expect(screen.getByText('pod=b')).toBeInTheDocument()+ })++ it('shows No data for an empty result on a scalar panel', () => {+ renderPanel([seriesWith({}, [])], { type: 'stat' })+ expect(screen.getByText('No data')).toBeInTheDocument()+ })++ it('drops the unit everywhere on a mixed-unit result rather than mislabeling one series', () => {+ renderPanel(+ [+ seriesWith({ service: 'a' }, [100, 200, 340], 'duration', 'ms'),+ seriesWith({ service: 'b' }, [0.1, 0.2, 0.34], 'latency', 's'),+ ],+ { type: 'table', reduce: 'last' }+ )+ expect(screen.getByText('340')).toBeInTheDocument()+ expect(screen.getByText('0.34')).toBeInTheDocument()+ expect(screen.queryByText('340 ms')).not.toBeInTheDocument()+ expect(screen.queryByText('0.34 s')).not.toBeInTheDocument()+ })++ it('drops the unit on a mixed-unit stat rather than mislabeling one series', () => {+ renderPanel([seriesWith({}, [1, 2, 3], 'a', 'ms'), seriesWith({}, [4, 5, 6], 'b', 's')], { type: 'stat' })+ expect(screen.getByText('3')).toBeInTheDocument()+ expect(screen.getByText('6')).toBeInTheDocument()+ })++ it('extends the gauge max past the value when thresholds end below it', () => {+ renderPanel([seriesWith({}, [0, 0, 150], 'cpu', '%')], {+ type: 'gauge',+ thresholds: [+ { value: 50, color: 'green' },+ { value: 90, color: 'red' },+ ],+ })+ // The max must contain the value, or the arc reads full at 150 of a "50 – 90" range.+ expect(screen.getByText((_content, el) => el?.textContent === '50% – 150%')).toBeInTheDocument()+ })++ it('shows No data on the gauge when every point is null', () => {+ renderPanel([seriesWith({ pod: 'a' }, [null, null, null])], { type: 'gauge' })+ expect(screen.getByText('No data')).toBeInTheDocument()+ expect(screen.queryByRole('img')).not.toBeInTheDocument()+ })++ it('deduplicates and caps the table reducer columns', () => {+ renderPanel([seriesWith({ pod: 'a' }, [1, 2, 3])], {+ type: 'table',+ legendCalcs: ['last', 'last', 'mean', 'min', 'max', 'sum', 'delta', 'mean'],+ })+ expect(screen.getAllByText('last')).toHaveLength(1)+ expect(screen.queryByText('delta')).toBeInTheDocument()+ })+ })+})diff --git a/products/metrics/frontend/panels/MetricsPanel.tsx b/products/metrics/frontend/panels/MetricsPanel.tsxnew file mode 100644index 000000000000..c63a3369c564--- /dev/null+++ b/products/metrics/frontend/panels/MetricsPanel.tsx@@ -0,0 +1,64 @@+import type { MetricsDisplaySettings } from '~/queries/schema/schema-general'++import type { MetricsExemplar } from '../components/MetricsExemplarMarkers'+import type { MetricsChartSeries } from '../components/metricsSeries'+import { BarGaugePanel } from './BarGaugePanel'+import { GaugePanel } from './GaugePanel'+import { seriesUnit } from './metricsReduce'+import { resolvePanelType } from './registry'+import { StatPanel } from './StatPanel'+import { TablePanel } from './TablePanel'+import { TimeSeriesPanel } from './TimeSeriesPanel'++/** A series with its own unit resolved: the display override wins, then the series'+ * ingested unit — but only when no other series carries a different unit, since a tile+ * mixes the values on one chart. A mixed-unit result renders bare numbers rather than+ * mislabeling one series with another's unit. */+function withResolvedUnits(series: MetricsChartSeries[], displayUnit: string | undefined): MetricsChartSeries[] {+ if (displayUnit) {+ return series.map((s) => ({ ...s, unit: displayUnit }))+ }+ const shared = seriesUnit(series, undefined)+ return series.map((s) => ({ ...s, unit: shared }))+}++/** The single dispatch point for a metrics tile: resolve the display type and render the+ * matching panel. `line`/`area`/`bar` are the time-series panel; `heatmap` renders here as a+ * line chart because the histogram runner is not wired to it yet, so a tile never blanks. */+export function MetricsPanel({+ series,+ display,+ fallbackName,+ exemplars,+}: {+ series: MetricsChartSeries[]+ display?: MetricsDisplaySettings+ fallbackName: string+ exemplars?: MetricsExemplar[]+}): JSX.Element {+ const type = resolvePanelType(display)+ const resolvedSeries = withResolvedUnits(series, display?.unit)++ switch (type) {+ case 'stat':+ return <StatPanel series={resolvedSeries} display={display ?? {}} fallbackName={fallbackName} />+ case 'gauge':+ return <GaugePanel series={resolvedSeries} display={display ?? {}} fallbackName={fallbackName} />+ case 'bargauge':+ return <BarGaugePanel series={resolvedSeries} display={display ?? {}} fallbackName={fallbackName} />+ case 'table':+ return <TablePanel series={resolvedSeries} display={display ?? {}} fallbackName={fallbackName} />+ case 'heatmap':+ // The histogram runner is not wired to the heatmap panel yet; fall through to a+ // time series so the tile shows the metric rather than a blank until then.+ default:+ return (+ <TimeSeriesPanel+ series={resolvedSeries}+ display={display ?? {}}+ fallbackName={fallbackName}+ exemplars={exemplars}+ />+ )+ }+}diff --git a/products/metrics/frontend/panels/StatPanel.tsx b/products/metrics/frontend/panels/StatPanel.tsxnew file mode 100644index 000000000000..299bf2189b3f--- /dev/null+++ b/products/metrics/frontend/panels/StatPanel.tsx@@ -0,0 +1,64 @@+import { MetricCard } from '@posthog/quill-charts'++import { useChartTheme } from 'lib/charts/hooks'+import { getColorVar } from 'lib/colors'++import { flattenSeriesRows } from './metricsReduce'+import { thresholdColor } from './metricsThresholds'+import { formatMetricValue } from './metricsUnits'+import type { MetricsPanelProps } from './registry'+import { resolveReducer } from './registry'++const FALLBACK_COLOR = 'data-color-1'+/** Cap on grouped stat cards so a high-cardinality groupBy does not flood the tile. */+const MAX_STAT_CARDS = 12++/** A headline number with a sparkline, colored by threshold. One card per series when the+ * query groups, capped at `MAX_STAT_CARDS`. */+export function StatPanel({ series, display, fallbackName }: MetricsPanelProps): JSX.Element {+ const theme = useChartTheme()+ const reducer = resolveReducer(display)+ // A series with no non-null point has nothing to headline; drop it rather than render a "—" card.+ const rows = flattenSeriesRows(series, [reducer]).filter((row) => row.values[reducer] !== null)++ const cards = rows.slice(0, MAX_STAT_CARDS).map((row, index) => {+ const value = row.values[reducer] ?? null+ const name =+ Object.entries(row.labels)+ .map(([k, v]) => `${k}=${v}`)+ .join(', ') ||+ row.metricName ||+ fallbackName+ const color = getColorVar(thresholdColor(value, display.thresholds, FALLBACK_COLOR))+ return (+ <MetricCard+ key={index}+ title={name}+ value={value ?? undefined}+ data={row.series.points.map((p) => p.value ?? 0)}+ labels={row.series.points.map((p) => p.time)}+ theme={theme}+ color={color}+ formatValue={(v) => formatMetricValue(v, row.series.unit ?? undefined)}+ sparklineFill+ />+ )+ })++ return (+ <div className="flex h-full w-full flex-wrap content-start items-start gap-3 overflow-auto p-2">+ {cards.length > 0 ? (+ <>+ {cards}+ {rows.length > MAX_STAT_CARDS && (+ <span className="text-xs text-secondary self-center">+ and {rows.length - MAX_STAT_CARDS} more+ </span>+ )}+ </>+ ) : (+ <div className="flex flex-1 items-center justify-center text-secondary text-sm">No data</div>+ )}+ </div>+ )+}diff --git a/products/metrics/frontend/panels/TablePanel.tsx b/products/metrics/frontend/panels/TablePanel.tsxnew file mode 100644index 000000000000..2578f8320212--- /dev/null+++ b/products/metrics/frontend/panels/TablePanel.tsx@@ -0,0 +1,76 @@+import { useMemo } from 'react'++import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'++import { capReducers, flattenSeriesRows, MetricsSeriesRow } from './metricsReduce'+import { safeColorToken, thresholdColor } from './metricsThresholds'+import { formatMetricValue } from './metricsUnits'+import type { MetricsPanelProps } from './registry'+import { resolveReducer } from './registry'++const FALLBACK_COLOR = 'data-color-1'++/** The label keys present across every series, unioned, so each gets its own column. */+function labelKeys(rows: MetricsSeriesRow[]): string[] {+ const keys = new Set<string>()+ for (const row of rows) {+ for (const key of Object.keys(row.labels)) {+ keys.add(key)+ }+ }+ return [...keys].sort()+}++/** Rows = series (one per label set); columns = label keys plus the chosen reducers. */+export function TablePanel({ series, display, fallbackName }: MetricsPanelProps): JSX.Element {+ const reducer = resolveReducer(display)+ const reducers = useMemo(+ () => (display.legendCalcs?.length ? capReducers(display.legendCalcs) : [reducer]),+ [display.legendCalcs, reducer]+ )+ const rows = useMemo(() => flattenSeriesRows(series, reducers), [series, reducers])+ const keys = useMemo(() => labelKeys(rows), [rows])++ const columns: LemonTableColumns<MetricsSeriesRow> = [+ ...(keys.length > 0+ ? keys.map((key) => ({+ title: key,+ key: `label-${key}`,+ render: (_: unknown, row: MetricsSeriesRow) => row.labels[key] ?? '—',+ }))+ : [+ {+ title: 'metric',+ key: 'metric',+ render: (_: unknown, row: MetricsSeriesRow) => row.metricName ?? fallbackName,+ },+ ]),+ ...reducers.map((r) => ({+ title: r,+ key: `reducer-${r}`,+ align: 'right' as const,+ render: (_: unknown, row: MetricsSeriesRow) => {+ const value = row.values[r] ?? null+ const color = safeColorToken(thresholdColor(value, display.thresholds, FALLBACK_COLOR), FALLBACK_COLOR)+ return value === null ? (+ <span className="text-secondary">—</span>+ ) : (+ <span className={`text-(--${color})`}>+ {formatMetricValue(value, row.series.unit ?? undefined)}+ </span>+ )+ },+ })),+ ]++ return (+ <div className="h-full w-full overflow-auto">+ <LemonTable+ columns={columns}+ dataSource={rows}+ rowKey={(row) => JSON.stringify(row.labels) + (row.metricName ?? '')}+ emptyState={<span className="text-secondary">No data</span>}+ />+ </div>+ )+}diff --git a/products/metrics/frontend/panels/TimeSeriesPanel.tsx b/products/metrics/frontend/panels/TimeSeriesPanel.tsxnew file mode 100644index 000000000000..1ab9ff8c8479--- /dev/null+++ b/products/metrics/frontend/panels/TimeSeriesPanel.tsx@@ -0,0 +1,87 @@+import { useValues } from 'kea'+import { useMemo } from 'react'++import {+ type Series,+ TimeSeriesBarChart,+ type TimeSeriesBarChartConfig,+ TimeSeriesLineChart,+ type TimeSeriesLineChartConfig,+} from '@posthog/quill-charts'++import { useChartConfig, useChartTheme } from 'lib/charts/hooks'+import { getColorVar } from 'lib/colors'+import { dayjs } from 'lib/dayjs'+import { teamLogic } from 'scenes/teamLogic'++import { buildMetricsChartConfig } from '../components/metricsChartConfig'+import { MetricsExemplarMarkers, type MetricsExemplar } from '../components/MetricsExemplarMarkers'+import { formatSeriesNames, seriesColor } from '../components/metricsSeries'+import type { MetricsPanelProps } from './registry'++const AREA_FILL_OPACITY = 0.2++/** Multi-series metric time-series chart (line / area / bar). Every series shares one time grid+ * (the backend zero-fills), so the x-axis comes from the first series.+ *+ * A null bucket is a gap (a non-representable aggregate). quill's `Series.data` is `number[]`+ * (no null), so a gap renders as 0 until quill takes null data; `display.nullMode` is read by+ * the chart config only, not here. */+export function TimeSeriesPanel({+ series,+ display,+ fallbackName,+ exemplars,+}: MetricsPanelProps & { exemplars?: MetricsExemplar[] }): JSX.Element {+ const { timezone } = useValues(teamLogic)+ const theme = useChartTheme()+ const isBar = display?.type === 'bar'+ const isArea = display?.type === 'area'++ const chartSeries = useMemo<Series[]>(() => {+ const names = formatSeriesNames(+ series.map((s) => ({ labels: s.labels, metric_name: s.metricName ?? undefined, clause: s.clause })),+ fallbackName+ )+ return series.map((s, index) => ({+ key: `${index}`,+ label: names[index],+ data: s.points.map((p) => p.value ?? 0),+ color: getColorVar(seriesColor(index)),+ ...(isArea ? { fill: { opacity: AREA_FILL_OPACITY } } : {}),+ }))+ }, [series, fallbackName, isArea])+ const labels = useMemo(() => (series[0]?.points ?? []).map((p) => p.time), [series])++ const sharedConfig = useChartConfig<TimeSeriesLineChartConfig>(+ () =>+ buildMetricsChartConfig({+ display,+ xAxis: { timezone },+ seriesCount: chartSeries.length,+ labelFormatter: (label: string) => dayjs(label).tz(timezone).format('D MMM YYYY HH:mm:ss'),+ }),+ [timezone, chartSeries.length, display]+ )++ const markers = exemplars?.length ? <MetricsExemplarMarkers exemplars={exemplars} /> : null++ return (+ <div className="relative flex h-full w-full min-h-0 flex-col">+ {isBar ? (+ <TimeSeriesBarChart+ series={chartSeries}+ labels={labels}+ theme={theme}+ config={sharedConfig as TimeSeriesBarChartConfig}+ >+ {markers}+ </TimeSeriesBarChart>+ ) : (+ <TimeSeriesLineChart series={chartSeries} labels={labels} theme={theme} config={sharedConfig}>+ {markers}+ </TimeSeriesLineChart>+ )}+ </div>+ )+}diff --git a/products/metrics/frontend/panels/metricsReduce.test.ts b/products/metrics/frontend/panels/metricsReduce.test.tsindex 580d8ef7cace..8ec9c49879ae 100644--- a/products/metrics/frontend/panels/metricsReduce.test.ts+++ b/products/metrics/frontend/panels/metricsReduce.test.ts@@ -1,6 +1,6 @@import type { MetricsQueryPoint, MetricsQuerySeries } from '~/queries/schema/schema-general'-import { flattenSeriesRows, reduceSeries } from './metricsReduce'+import { capReducers, flattenSeriesRows, reduceSeries, seriesUnit } from './metricsReduce'// The schema types `value` as `number`, but the backend sends `null` for a// non-representable bucket (the facade's `MetricPoint.value` is `float | None`).@@ -86,4 +86,45 @@ describe('metricsReduce', () => {expect(rows).toHaveLength(2)})})++ describe('seriesUnit', () => {+ const oneSeries = (unit?: string): MetricsQuerySeries => ({ labels: {}, points: points([1]), unit })++ it('prefers the display override over any series unit', () => {+ expect(seriesUnit([oneSeries('ms')], 's')).toBe('s')+ })++ it('returns the shared unit when every series agrees', () => {+ expect(seriesUnit([oneSeries('ms'), oneSeries('ms')], undefined)).toBe('ms')+ })++ it('returns undefined when series disagree, rather than picking the first', () => {+ expect(seriesUnit([oneSeries('ms'), oneSeries('s')], undefined)).toBeUndefined()+ })++ it('ignores series without a unit when the rest agree', () => {+ expect(seriesUnit([oneSeries('ms'), oneSeries(undefined)], undefined)).toBe('ms')+ })++ it('returns undefined when no series carries a unit', () => {+ expect(seriesUnit([oneSeries(undefined)], undefined)).toBeUndefined()+ })+ })++ describe('capReducers', () => {+ it('deduplicates and caps the reducer list', () => {+ expect(capReducers(['last', 'last', 'mean', 'min', 'max', 'sum', 'delta', 'mean'])).toEqual([+ 'last',+ 'mean',+ 'min',+ 'max',+ 'sum',+ 'delta',+ ])+ })++ it('keeps a short list untouched', () => {+ expect(capReducers(['max', 'last'])).toEqual(['max', 'last'])+ })+ })})diff --git a/products/metrics/frontend/panels/metricsReduce.ts b/products/metrics/frontend/panels/metricsReduce.tsindex f4841063609e..93ba536c5423 100644--- a/products/metrics/frontend/panels/metricsReduce.ts+++ b/products/metrics/frontend/panels/metricsReduce.ts@@ -1,8 +1,25 @@-import type { MetricsQueryPoint, MetricsQuerySeries, MetricsReducer } from '~/queries/schema/schema-general'+import type { MetricsReducer } from '~/queries/schema/schema-general'++/** One bucket. `value` is `null` for a non-representable aggregate (a gap). The schema's+ * `MetricsQueryPoint` declares `value: number` but the backend sends null, so this shape+ * matches what both the schema series and the viewer's API series actually carry. */+export interface ReduciblePoint {+ time: string+ value: number | null+}++/** The shape `flattenSeriesRows` needs. A structural subset of both the schema series and+ * the viewer's `MetricsChartSeries`, so either flows in. */+export interface ReducibleSeries {+ labels: Record<string, string>+ points: ReduciblePoint[]+ metricName?: string | null+ unit?: string | null+}/** The reducers a caller may ask for. `reduceSeries` returns `null` when a series has no* non-null point, so a panel can show "No data" instead of a misleading 0. */-export function reduceSeries(points: MetricsQueryPoint[], reducer: MetricsReducer): number | null {+export function reduceSeries(points: ReduciblePoint[], reducer: MetricsReducer): number | null {const values = points.map((p) => p.value).filter((v): v is number => v !== null && v !== undefined)if (values.length === 0) {return null@@ -34,10 +51,10 @@ export interface MetricsSeriesRow {* data; a reducer the caller did not ask for is absent, so the type stays Partial. */values: Partial<Record<MetricsReducer, number | null>>/** The raw series, kept so a row can link back to its points (sparkline, drill-down). */- series: MetricsQuerySeries+ series: ReducibleSeries}-export function flattenSeriesRows(series: MetricsQuerySeries[], reducers: MetricsReducer[]): MetricsSeriesRow[] {+export function flattenSeriesRows(series: ReducibleSeries[], reducers: MetricsReducer[]): MetricsSeriesRow[] {return series.map((s) => ({labels: s.labels,metricName: s.metricName ?? undefined,@@ -45,3 +62,22 @@ export function flattenSeriesRows(series: MetricsQuerySeries[], reducers: Metricseries: s,}))}++/** The unit a panel renders with. The explicit display override always wins;+ * without one, the shared ingested unit applies — but only when every series+ * that carries a unit agrees. A mixed-unit result gets no unit rather than+ * one series' values mislabeled with another's. */+export function seriesUnit(series: ReducibleSeries[], displayUnit: string | undefined): string | undefined {+ if (displayUnit) {+ return displayUnit+ }+ const units = new Set(series.map((s) => s.unit).filter((u): u is string => !!u))+ return units.size === 1 ? [...units][0] : undefined+}++/** A persisted `legendCalcs` list is user input from a saved insight: it can+ * repeat entries or run long. Dedup and cap it to the reducers that exist so+ * an old or hand-edited insight cannot render an unbounded column set. */+export function capReducers(reducers: MetricsReducer[]): MetricsReducer[] {+ return [...new Set(reducers)].slice(0, 6)+}diff --git a/products/metrics/frontend/panels/metricsThresholds.test.ts b/products/metrics/frontend/panels/metricsThresholds.test.tsindex fd5a36e4a716..7e51958361c4 100644--- a/products/metrics/frontend/panels/metricsThresholds.test.ts+++ b/products/metrics/frontend/panels/metricsThresholds.test.ts@@ -1,4 +1,4 @@-import { thresholdColor } from './metricsThresholds'+import { safeColorToken, thresholdColor } from './metricsThresholds'const FALLBACK = 'data-color-1'@@ -39,3 +39,16 @@ describe('thresholdColor', () => {expect(thresholdColor(10, t, FALLBACK)).toBe('green')})})++describe('safeColorToken', () => {+ it('passes a plain token through', () => {+ expect(safeColorToken('danger', 'data-color-1')).toBe('danger')+ expect(safeColorToken('data-color-3', 'data-color-1')).toBe('data-color-3')+ })++ it('falls back on a token with class-breaking characters', () => {+ expect(safeColorToken('x) fixed inset-0 z-50', 'data-color-1')).toBe('data-color-1')+ expect(safeColorToken('red blue', 'data-color-1')).toBe('data-color-1')+ expect(safeColorToken('text-(--x)', 'data-color-1')).toBe('data-color-1')+ })+})diff --git a/products/metrics/frontend/panels/metricsThresholds.ts b/products/metrics/frontend/panels/metricsThresholds.tsindex 4a6880ea3289..d83db4424717 100644--- a/products/metrics/frontend/panels/metricsThresholds.ts+++ b/products/metrics/frontend/panels/metricsThresholds.ts@@ -22,3 +22,10 @@ export function thresholdColor(}return color}++/** A threshold color is persisted user input that ends up inside a class string;+ * anything beyond a plain token (whitespace, parentheses) could inject extra+ * utilities, so it falls back instead. */+export function safeColorToken(color: string, fallback: string): string {+ return /^[a-zA-Z0-9_-]+$/.test(color) ? color : fallback+}diff --git a/products/metrics/frontend/panels/metricsUnits.test.ts b/products/metrics/frontend/panels/metricsUnits.test.tsindex 18aaa30e8a8e..f5dc34f565c1 100644--- a/products/metrics/frontend/panels/metricsUnits.test.ts+++ b/products/metrics/frontend/panels/metricsUnits.test.ts@@ -1,60 +1,58 @@import { formatMetricValue, unitAxisFormatter } from './metricsUnits'-describe('metricsUnits', () => {- describe('formatMetricValue', () => {- it.each([- // no unit- [1234, undefined, '1.23K'],- [0, undefined, '0'],- // bytes (binary)- [0, 'By', '0 B'],- [512, 'By', '512 B'],- [1024, 'By', '1 KiB'],- [1536, 'By', '1.5 KiB'],- [1024 ** 2, 'By', '1 MiB'],- [2.5 * 1024 ** 3, 'By', '2.5 GiB'],- // binary-prefixed UCUM- [2, 'KiBy', '2 KiB'],- [3, 'MiBy', '3 MiB'],- // seconds- [2.5, 's', '2.5 s'],- [0.34, 's', '340 ms'],- [0.0005, 's', '500 µs'],- [0.0000002, 's', '200 ns'],- [340, 'ms', '340 ms'],- [1500, 'ms', '1.5 s'],- [250000, 'us', '250 ms'],- // percent- [42.5, '%', '42.5%'],- // UCUM "1" is dimensionless, not necessarily a ratio: keep the value- [0.12, '1', '0.12'],- [1, '1', '1'],- [12, '1', '12'],- // rates- [88, '1/s', '88/s'],- [88, '{request}/s', '88 request/s'],- [1500, '{message}/s', '1.5K message/s'],- // unknown unit falls back to compact + suffix- [1234, 'widgets', '1.23K widgets'],- ])('formats %s with unit %s as %s', (value, unit, expected) => {- expect(formatMetricValue(value, unit)).toBe(expected)- })+describe('formatMetricValue', () => {+ it.each([+ // no unit+ [1234, undefined, '1.23K'],+ [0, undefined, '0'],+ // bytes (binary)+ [0, 'By', '0 B'],+ [512, 'By', '512 B'],+ [1024, 'By', '1 KiB'],+ [1536, 'By', '1.5 KiB'],+ [1024 ** 2, 'By', '1 MiB'],+ [2.5 * 1024 ** 3, 'By', '2.5 GiB'],+ // binary-prefixed UCUM+ [2, 'KiBy', '2 KiB'],+ [3, 'MiBy', '3 MiB'],+ // seconds+ [2.5, 's', '2.5 s'],+ [0.34, 's', '340 ms'],+ [0.0005, 's', '500 µs'],+ [0.0000002, 's', '200 ns'],+ [340, 'ms', '340 ms'],+ [1500, 'ms', '1.5 s'],+ [250000, 'us', '250 ms'],+ // percent+ [42.5, '%', '42.5%'],+ // ratio (UCUM "1")+ [0.12, '1', '12%'],+ [1, '1', '100%'],+ [12, '1', '12'],+ // rates+ [88, '1/s', '88/s'],+ [88, '{request}/s', '88 request/s'],+ [1500, '{message}/s', '1.5K message/s'],+ // unknown unit falls back to compact + suffix+ [1234, 'widgets', '1.23K widgets'],+ ])('formats %s with unit %s as %s', (value, unit, expected) => {+ expect(formatMetricValue(value, unit)).toBe(expected)+ })- it('handles negative values', () => {- expect(formatMetricValue(-1024, 'By')).toBe('-1 KiB')- expect(formatMetricValue(-0.5, '1')).toBe('-0.5')- })+ it('handles negative values', () => {+ expect(formatMetricValue(-1024, 'By')).toBe('-1 KiB')+ expect(formatMetricValue(-0.5, '1')).toBe('-50%')})+})- describe('unitAxisFormatter', () => {- it('binds the unit into a reusable formatter', () => {- const fmt = unitAxisFormatter('ms')- expect(fmt(340)).toBe('340 ms')- expect(fmt(2000)).toBe('2 s')- })+describe('unitAxisFormatter', () => {+ it('binds the unit into a reusable formatter', () => {+ const fmt = unitAxisFormatter('ms')+ expect(fmt(340)).toBe('340 ms')+ expect(fmt(2000)).toBe('2 s')+ })- it('falls back to compact with no unit', () => {- expect(unitAxisFormatter(undefined)(1500)).toBe('1.5K')- })+ it('falls back to compact with no unit', () => {+ expect(unitAxisFormatter(undefined)(1500)).toBe('1.5K')})})diff --git a/products/metrics/frontend/panels/metricsUnits.ts b/products/metrics/frontend/panels/metricsUnits.tsindex 7cc23e89b31f..ecec9947adc3 100644--- a/products/metrics/frontend/panels/metricsUnits.ts+++ b/products/metrics/frontend/panels/metricsUnits.ts@@ -31,6 +31,10 @@ const seconds = (value: number): string => {return `${compact(value * 1e9)} ns`}+/** Whether a bare `1` (ratio) value reads as a percent. A ratio in 0..1 becomes a percent;+ * a count that happens to be in 0..1 is left alone by the caller passing a more specific unit. */+const RATIO_AS_PERCENT_MAX = 1+/** Format one metric value with a UCUM unit. `unit` is the raw OTel string; `undefined`* or an unknown unit falls back to a compact number. */export function formatMetricValue(value: number, unit: string | undefined): string {@@ -61,9 +65,10 @@ export function formatMetricValue(value: number, unit: string | undefined): strireturn `${compact(value)}%`}if (unit === '1') {- // UCUM "one" means dimensionless, not necessarily a ratio — ingestion- // carries nothing that tells a ratio from any other unitless value,- // so multiplying by 100 would mislabel a legitimate measurement.+ // UCUM "one": a dimensionless ratio. Render small ratios as a percent.+ if (Math.abs(value) <= RATIO_AS_PERCENT_MAX) {+ return `${compact(value * 100)}%`+ }return compact(value)}if (unit === '1/s') {diff --git a/products/metrics/frontend/panels/registry.ts b/products/metrics/frontend/panels/registry.tsindex 95fa5ac5ac7f..5c67e3c5a8fd 100644--- a/products/metrics/frontend/panels/registry.ts+++ b/products/metrics/frontend/panels/registry.ts@@ -2,12 +2,12 @@ import type { MetricsDisplaySettings, MetricsDisplayType } from '~/queries/schemimport type { MetricsChartSeries } from '../components/metricsSeries'-/** The props every metrics panel receives. `unit` is the resolved unit (display override,- * else the first series' ingested unit). A panel is a pure function of these props. */+/** The props every metrics panel receives. Each series' unit is already resolved by the+ * dispatcher (display override, else the series' ingested unit, else the unit every series+ * shares — undefined when they disagree). A panel is a pure function of these props. */export interface MetricsPanelProps {series: MetricsChartSeries[]display: MetricsDisplaySettings- unit: string | undefinedfallbackName: string}